A full-featured download manager.
fix(downloads): validate sources and stabilize url entry (#2154)
Dr_rOotd2ada0425370
diff --git a/docs/screenshots/url-editor-hover.png b/docs/screenshots/url-editor-hover.pngnew file mode 100644index 00000000..35f28874Binary files /dev/null and b/docs/screenshots/url-editor-hover.png differdiff --git a/e2e/add-task.spec.ts b/e2e/add-task.spec.tsindex cc36e1e4..15080c92 100644--- a/e2e/add-task.spec.ts+++ b/e2e/add-task.spec.ts@@ -1,6 +1,13 @@import { writeFile } from 'node:fs/promises'import path from 'node:path'import type { Page } from '@playwright/test'+import { ADD_TASK_COLLAPSED_HEIGHT } from '../src/shared/constants/add-task'+import { Queries } from '../src/shared/protocol/queries'+import {+ type DownloadTask,+ TaskStatus,+ TaskType,+} from '../src/shared/types/task'import {expect,findAddTaskWindow,@@ -49,6 +56,361 @@ async function removeAllTasks(page: Page): Promise<void> {}test.describe('add task', () => {+ test('blank input stays idle and URL editing preserves the collapsed window height', async ({+ electronApp,+ mainWindow,+ }, testInfo) => {+ await waitForEngineReady(mainWindow)+ await mainWindow.getByRole('button', { name: 'New task' }).click()+ const page = await findAddTaskWindow(electronApp)+ const textbox = page.getByRole('textbox', { name: 'URLs' })+ const download = page.getByRole('button', { name: 'Download', exact: true })+ await expect(textbox).toBeVisible()+ await expect(page.getByText('URLs', { exact: true })).toHaveCount(0)+ await expect+ .poll(() => page.evaluate(() => innerHeight))+ .toBe(ADD_TASK_COLLAPSED_HEIGHT)+ const heights = () =>+ page.evaluate(() => {+ const textarea = document.querySelector('textarea')!+ const content = document.querySelector<HTMLElement>(+ '[data-adaptive-content]'+ )!+ return {+ window: innerHeight,+ editor: textarea.clientHeight,+ natural: content.getBoundingClientRect().top + content.scrollHeight,+ }+ })+ const initial = await heights()+ expect(initial.editor).toBe(100)+ expect(initial.natural).toBeLessThanOrEqual(initial.window)+ await textbox.focus()+ await textbox.press('ControlOrMeta+Enter')+ await textbox.evaluate((element) => element.blur())+ await expect(textbox).toHaveAttribute('aria-invalid', 'false')+ await expect(page.getByRole('alert')).toHaveCount(0)+ await expect(download).toBeDisabled()+ await page.screenshot({ path: testInfo.outputPath('url-editor-empty.png') })++ for (const value of [+ 'htps://example.com',+ 'https://example.com/file.zip\nhtps://example.com',+ Array.from(+ { length: 40 },+ (_, index) => `https://example.com/${index}`+ ).join('\n'),+ ' \n ',+ '',+ ]) {+ await textbox.fill(value)+ await textbox.evaluate((element) => element.blur())+ // Let both ResizeObserver and the adaptive sizing frame settle.+ await page.evaluate(+ () =>+ new Promise<void>((resolve) => {+ requestAnimationFrame(() => requestAnimationFrame(() => resolve()))+ })+ )+ expect(await heights()).toEqual(initial)+ await expect(page.getByRole('alert')).toHaveCount(0)+ }+ await expect(textbox).toHaveAttribute('aria-invalid', 'false')+ await expect(download).toBeDisabled()+ await textbox.fill('https://example.com/dir\\file.zip')+ await page.getByRole('button', { name: /^Line 1:/ }).click()+ await page+ .getByRole('button', { name: 'Encode as literal characters' })+ .click()+ const undo = page.getByRole('button', { name: 'Undo URL correction' })+ await expect(undo).toBeVisible()+ expect(await heights()).toEqual(initial)+ await page.screenshot({+ path: testInfo.outputPath('url-editor-corrected.png'),+ })+ await undo.click()+ expect(await heights()).toEqual(initial)+ const advanced = page.getByRole('button', { name: 'Advanced', exact: true })+ await advanced.click()+ await expect+ .poll(() => page.evaluate(() => innerHeight))+ .toBeGreaterThan(initial.window)+ await advanced.click()+ await expect+ .poll(() => page.evaluate(() => innerHeight))+ .toBe(initial.window)+ })++ test('URL editor highlights tokens and keeps diagnostics aligned through wrapping, scrolling and resizing', async ({+ electronApp,+ mainWindow,+ }, testInfo) => {+ await waitForEngineReady(mainWindow)+ await mainWindow.getByRole('button', { name: 'New task' }).click()+ const page = await findAddTaskWindow(electronApp)+ await page.bringToFront()+ const textbox = page.getByRole('textbox', { name: 'URLs' })+ const marker = page.getByRole('button', {+ name: 'Line 1: This URL protocol is not supported for this download.',+ })+ const sample =+ 'htps://exmaple.com\nhttps://example.com/file.zip\nftp://files.example.com/archive.zip\nhttps://example.com/video.mp4'+ await textbox.fill(sample)+ await textbox.evaluate((element: HTMLTextAreaElement) => {+ element.scrollTop = 0+ element.dispatchEvent(new Event('scroll'))+ })+ await textbox.evaluate((element) => element.blur())+ await expect(page.locator('.url-editor-error')).toHaveText('htps')+ await expect(+ page.getByRole('button', { name: 'Download', exact: true })+ ).toBeEnabled()+ await page.mouse.move(8, 80)+ await marker.hover()+ await expect(page.getByRole('tooltip')).toHaveText(+ 'Line 1: This URL protocol is not supported for this download.'+ )+ await page.screenshot({ path: testInfo.outputPath('url-editor-hover.png') })+ await marker.click()+ await expect(textbox).toBeFocused()+ expect(+ await textbox.evaluate((element: HTMLTextAreaElement) =>+ element.value.slice(element.selectionStart, element.selectionEnd)+ )+ ).toBe('htps')+ await page.keyboard.insertText('https')+ await expect(marker).toHaveCount(0)+ await textbox.press('ControlOrMeta+z')+ await expect(textbox).toHaveValue(sample)++ const longUrl = `htps://example.com/${'segment-'.repeat(19)}file.zip`+ await textbox.fill(+ [+ longUrl,+ ...Array.from(+ { length: 16 },+ (_, index) => `https://example.com/${index}`+ ),+ ].join('\n')+ )+ // Native fill places the caret at the end and scrolls there.+ await textbox.evaluate((element: HTMLTextAreaElement) => {+ element.scrollTop = 0+ element.dispatchEvent(new Event('scroll'))+ })+ await expect(marker).toBeVisible()+ const measure = () =>+ page.evaluate(() => {+ const textarea = document.querySelector('textarea')!+ const mirror =+ document.querySelector<HTMLElement>('.url-editor-mirror')!+ const row = mirror.querySelector<HTMLElement>('[data-url-line="0"]')!+ const icon = document.querySelector<HTMLElement>(+ '[data-url-diagnostic="0"]'+ )!+ const lineHeight = Number.parseFloat(+ getComputedStyle(textarea).lineHeight+ )+ const rowRect = row.getBoundingClientRect()+ const iconRect = icon?.getBoundingClientRect()+ return {+ lineHeight,+ rows: rowRect.height / lineHeight,+ centerDifference: iconRect+ ? Math.abs(+ iconRect.y ++ iconRect.height / 2 -+ (rowRect.bottom - lineHeight / 2)+ )+ : Number.POSITIVE_INFINITY,+ nativeHeight: textarea.scrollHeight,+ mirrorHeight: mirror.offsetHeight,+ rightGap: iconRect+ ? textarea.getBoundingClientRect().right - iconRect.right+ : 0,+ lastLineY:+ rowRect.bottom -+ lineHeight / 2 -+ textarea.getBoundingClientRect().top,+ }+ })+ await expect+ .poll(async () => (await measure()).centerDifference)+ .toBeLessThan(1)+ const initial = await measure()+ expect(initial.rows).toBeGreaterThan(1)+ expect(initial.nativeHeight).toBe(initial.mirrorHeight)+ expect(initial.rightGap).toBeGreaterThanOrEqual(24)+ // Hit-test against the real native textarea, not only mirror geometry.+ await textbox.click({ position: { x: 16, y: initial.lastLineY } })+ const cursor = await textbox.evaluate(+ (element: HTMLTextAreaElement) => element.selectionStart+ )+ expect(cursor).toBeGreaterThan(0)+ expect(cursor).toBeLessThan(longUrl.length)+ await textbox.evaluate((element: HTMLTextAreaElement) => {+ element.scrollTop = 22+ element.dispatchEvent(new Event('scroll'))+ })+ await expect+ .poll(async () => (await measure()).centerDifference)+ .toBeLessThan(1)+ await textbox.evaluate((element: HTMLTextAreaElement) => {+ element.scrollTop = element.scrollHeight+ element.dispatchEvent(new Event('scroll'))+ })+ await expect(marker).toHaveCount(0)+ await textbox.evaluate((element: HTMLTextAreaElement) => {+ element.scrollTop = 0+ element.dispatchEvent(new Event('scroll'))+ })++ await electronApp.evaluate(({ BrowserWindow }) => {+ const window = BrowserWindow.getAllWindows().find((window) =>+ window.webContents.getURL().includes('w=add-task')+ )!+ window.setMinimumSize(420, 400)+ window.setSize(440, 640)+ })+ await expect+ .poll(async () => (await measure()).rows)+ .toBeGreaterThan(initial.rows)+ // The compact editor scrolls to reach the final row of a long URL.+ await textbox.evaluate((textarea: HTMLTextAreaElement) => {+ const row = document.querySelector<HTMLElement>('[data-url-line="0"]')!+ textarea.scrollTop = Math.max(+ 0,+ row.offsetTop + row.offsetHeight + 12 - textarea.clientHeight+ )+ textarea.dispatchEvent(new Event('scroll'))+ })+ await expect+ .poll(async () => (await measure()).centerDifference)+ .toBeLessThan(1)+ const narrow = await measure()+ expect(narrow.nativeHeight).toBe(narrow.mirrorHeight)+ expect(narrow.rightGap).toBeGreaterThanOrEqual(24)+ await marker.hover()+ await expect(page.getByRole('tooltip')).toBeVisible()+ const tooltipBounds = await page.getByRole('tooltip').boundingBox()+ const viewport = await page.evaluate(() => ({+ width: innerWidth,+ height: innerHeight,+ }))+ expect(tooltipBounds!.x).toBeGreaterThanOrEqual(0)+ expect(tooltipBounds!.x + tooltipBounds!.width).toBeLessThanOrEqual(+ viewport.width+ )+ await page.screenshot({+ path: testInfo.outputPath('url-editor-wrapped.png'),+ })+ await page.emulateMedia({ colorScheme: 'dark' })+ await page.screenshot({ path: testInfo.outputPath('url-editor-dark.png') })+ // A short hash expands on blur and wraps in this narrow window. Clicking+ // another line's correction must still hit its icon and edit that line.+ const hash = 'a03e3f9a05341aa336e9d9d3f06b33cddafe0bdc'+ await textbox.fill(`${hash}\nhttps://example.com/dir\\file`)+ await page.getByRole('button', { name: /^Line 2:/ }).click()+ await page+ .getByRole('button', { name: 'Encode as literal characters' })+ .click()+ await expect(textbox).toHaveValue(+ `magnet:?xt=urn:btih:${hash}\nhttps://example.com/dir%5Cfile`+ )+ })++ test('partial URL submission retains invalid input and correction is reversible', async ({+ electronApp,+ mainWindow,+ httpFixture,+ }) => {+ await waitForEngineReady(mainWindow)+ await mainWindow.getByRole('button', { name: 'New task' }).click()+ const page = await findAddTaskWindow(electronApp)+ const textbox = page.getByRole('textbox', { name: 'URLs' })+ const invalid = 'https://example.test/dir\\file?sig=%2f+%252F'+ await textbox.fill(`${httpFixture.fileUrl}\n${invalid}`)+ await page.getByRole('button', { name: 'Download', exact: true }).click()+ try {+ await expect(textbox).toHaveValue(invalid)+ await expect+ .poll(+ async () =>+ (+ (await mainWindow.evaluate(+ (channel) => window.motrix.invoke(channel),+ Queries.ListTasks+ )) as DownloadTask[]+ ).length+ )+ .toBe(1)+ await page.getByRole('button', { name: /^Line 1:/ }).click()+ await page+ .getByRole('button', { name: 'Encode as literal characters' })+ .click()+ await expect(textbox).toHaveValue(+ 'https://example.test/dir%5Cfile?sig=%2f+%252F'+ )+ await page.getByRole('button', { name: 'Undo URL correction' }).click()+ await expect(textbox).toHaveValue(invalid)+ await expect(+ page.getByRole('button', { name: 'Download', exact: true })+ ).toBeDisabled()+ } finally {+ await removeAllTasks(mainWindow).catch(() => undefined)+ }+ })++ for (const { input, hash } of [+ {+ input: 'A03E3F9A05341AA336E9D9D3F06B33CDDAFE0BDC',+ hash: 'a03e3f9a05341aa336e9d9d3f06b33cddafe0bdc',+ },+ {+ input: 'ua7d7gqfgqnkgnxj3hj7a2ztzxnp4c64',+ hash: 'a03e3f9a05341aa336e9d9d3f06b33cddafe0bdc',+ },+ ]) {+ test(`bare ${input.length}-character info hash creates a magnet task`, async ({+ electronApp,+ mainWindow,+ }) => {+ await waitForEngineReady(mainWindow)+ await mainWindow.getByRole('button', { name: 'New task' }).click()+ const addTaskPage = await findAddTaskWindow(electronApp)+ await addTaskPage.getByRole('textbox', { name: 'URLs' }).fill(input)+ await expect(+ addTaskPage.getByText('1 URL', { exact: true })+ ).toBeVisible()++ try {+ await addTaskPage.getByRole('button', { name: 'Download' }).click()+ await expect+ .poll(async () => {+ const tasks = (await mainWindow.evaluate(async (channel) => {+ return window.motrix.invoke(channel)+ }, Queries.ListTasks)) as DownloadTask[]+ const task = tasks.find((entry) => entry.infoHash === hash)+ return task+ ? {+ type: task.type,+ hasEngineTask: Boolean(task.engineTaskId),+ failed: task.status === TaskStatus.Error,+ }+ : null+ })+ .toEqual({+ type: TaskType.Magnet,+ hasEngineTask: true,+ failed: false,+ })+ } finally {+ // No peers serve this test hash; remove its pending metadata task.+ await removeAllTasks(mainWindow).catch(() => undefined)+ }+ })+ }+test('http url submitted via the add-task window appears in Downloads', async ({electronApp,mainWindow,diff --git a/src/core/bridge-receiver/bridge-receiver.test.ts b/src/core/bridge-receiver/bridge-receiver.test.tsindex 489cbe22..c7f0c7df 100644--- a/src/core/bridge-receiver/bridge-receiver.test.ts+++ b/src/core/bridge-receiver/bridge-receiver.test.ts@@ -226,7 +226,10 @@ describe('BridgeReceiver', () => {pageTitle: 'P',detectedAt: 1,},- selection: { kind: 'magnet', uri: 'magnet:?xt=urn:btih:abc' },+ selection: {+ kind: 'magnet',+ uri: 'magnet:?xt=urn:btih:a03e3f9a05341aa336e9d9d3f06b33cddafe0bdc',+ },meta: { suggestedFilename: 'm', qualityLabel: 'file' },},{@@ -236,7 +239,10 @@ describe('BridgeReceiver', () => {expect(out).toEqual({ taskId: 'mt1' })expect((createTask.mock.calls as unknown[][])[0]?.[0]).toMatchObject({type: 'bt',- payload: { kind: 'magnet', uri: 'magnet:?xt=urn:btih:abc' },+ payload: {+ kind: 'magnet',+ uri: 'magnet:?xt=urn:btih:a03e3f9a05341aa336e9d9d3f06b33cddafe0bdc',+ },})})diff --git a/src/core/bridge-receiver/pipelines/mux-pipeline.ts b/src/core/bridge-receiver/pipelines/mux-pipeline.tsindex 34d26d30..adfd8785 100644--- a/src/core/bridge-receiver/pipelines/mux-pipeline.ts+++ b/src/core/bridge-receiver/pipelines/mux-pipeline.ts@@ -35,6 +35,7 @@ export class MuxPipeline {// ffmpeg needs an output extension or it can't pick a muxer (exit 234).finalName: ensureMediaExtension(adapted.finalName, adapted.container),sourceMeta: adapted.sourceMeta,+ ...(adapted.receipt ? { receipt: adapted.receipt } : {}),...(adapted.durationSec !== undefined? { durationSec: adapted.durationSec }: {}),diff --git a/src/core/bridge-receiver/submit-download-adapter.test.ts b/src/core/bridge-receiver/submit-download-adapter.test.tsindex e68a2db5..3301745a 100644--- a/src/core/bridge-receiver/submit-download-adapter.test.ts+++ b/src/core/bridge-receiver/submit-download-adapter.test.ts@@ -80,7 +80,20 @@ describe('SubmitDownloadAdapter.adapt', () => {expect(result.sourceMeta.sessionKey).toBe('chromium:e')})- it('rejects non-http(s) URL with invalid-url-scheme', async () => {+ it('keeps the source fragment available to direct URL resolvers', async () => {+ const input = baseInput()+ if (input.selection.kind !== 'direct') throw new Error('expected direct')+ input.selection.primary.url += '#episode-2'+ const result = await adapter().adapt(input, {+ extensionId: 'e',+ browser: 'chromium',+ })+ expect(result).toMatchObject({+ primaryUrl: 'http://example.com/file.mp4#episode-2',+ })+ })++ it('rejects non-http(s) URL with a structured source error', async () => {const bad: DownloadSubmitParams = {...baseInput(),selection: {@@ -95,7 +108,13 @@ describe('SubmitDownloadAdapter.adapt', () => {}await expect(adapter().adapt(bad, { extensionId: 'e', browser: 'chromium' })- ).rejects.toMatchObject({ code: 'invalid-url-scheme' })+ ).rejects.toMatchObject({+ code: 'TASK_SOURCE_INVALID',+ details: {+ stage: 'input',+ diagnostic: { reason: 'unsupportedProtocol' },+ },+ })})it('preserves domain scope and millisecond expiry while omitting browser-only fields', async () => {@@ -363,7 +382,10 @@ describe('SubmitDownloadAdapter.adapt', () => {pageTitle: 'demo',detectedAt: 1,},- selection: { kind: 'magnet', uri: 'magnet:?xt=urn:btih:abc&dn=Movie' },+ selection: {+ kind: 'magnet',+ uri: 'magnet:?xt=urn:btih:a03e3f9a05341aa336e9d9d3f06b33cddafe0bdc&dn=Movie',+ },meta: { suggestedFilename: 'Movie', qualityLabel: 'file' },}const result = await adapter().adapt(input, {@@ -372,7 +394,9 @@ describe('SubmitDownloadAdapter.adapt', () => {})expect(result.kind).toBe('magnet')if (result.kind === 'magnet') {- expect(result.uri).toBe('magnet:?xt=urn:btih:abc&dn=Movie')+ expect(result.uri).toBe(+ 'magnet:?xt=urn:btih:a03e3f9a05341aa336e9d9d3f06b33cddafe0bdc&dn=Movie'+ )expect(result.saveDir).toBe('/tmp/save')expect(result.sourceMeta.kind).toBe('magnet')expect(result.sourceMeta.sessionKey).toBe('chromium:e')diff --git a/src/core/bridge-receiver/submit-download-adapter.ts b/src/core/bridge-receiver/submit-download-adapter.tsindex 128f2b96..2b655b00 100644--- a/src/core/bridge-receiver/submit-download-adapter.ts+++ b/src/core/bridge-receiver/submit-download-adapter.ts@@ -1,8 +1,12 @@import type { DownloadCookie } from '@core/engine/engine-adapter'+import type { CreateRequestReceipt } from '@core/task/create-request-id'+import {+ admitDownloadSources,+ admitHttpSource,+} from '@core/task/source-admission'import type { DownloadSubmitParams } from '@motrix/mdxp'import { type Browser, makeSessionKey } from '@shared/protocol/bridge'import type { BridgeSourceMeta, SourceMeta } from '@shared/types/task'-import { BridgeReceiverError } from './errors'import { stripHopByHopHeaders } from './header-replay'import { ensureMediaExtension } from './pipelines/media-final-name'@@ -52,6 +56,7 @@ export interface AdaptedDash extends Omit<AdaptedHls, 'kind' | 'container'> {}export interface AdaptedMux {+ receipt?: CreateRequestReceiptkind: 'mux'taskId: stringsaveDir: string@@ -83,32 +88,32 @@ export class SubmitDownloadAdapter {): Promise<AdaptedDirect | AdaptedMagnet | AdaptedHls | AdaptedDash | AdaptedMux> {- // Bootstrap already ran DownloadSubmitParamsSchema.safeParse() and threw- // InvalidParams on failure. We have typed data here, but MDXP's- // Resource.url is plain z.string() (not http-only), so we still need to- // reject non-http(s) schemes as a business rule.- if (- params.selection.kind === 'direct' ||- params.selection.kind === 'hls' ||- params.selection.kind === 'dash'- ) {- const url = params.selection.primary.url- if (!/^https?:\/\//i.test(url)) {- throw new BridgeReceiverError(- 'invalid-url-scheme',- 'URL must be http: or https:'- )- }- }+ params = structuredClone(params)if (params.selection.kind === 'mux') {- for (const r of [params.selection.video, params.selection.audio]) {- if (!/^https?:\/\//i.test(r.url)) {- throw new BridgeReceiverError(- 'invalid-url-scheme',- 'URL must be http: or https:'- )- }- }+ params.selection.video.url = admitHttpSource(+ params.selection.video.url,+ 'input'+ )+ params.selection.audio.url = admitHttpSource(+ params.selection.audio.url,+ 'input'+ )+ } else if (params.selection.kind === 'magnet') {+ params.selection.uri = admitDownloadSources(+ [params.selection.uri],+ 'input',+ ['magnet']+ )[0].sourceUrl+ } else {+ const source = admitDownloadSources(+ [params.selection.primary.url],+ 'input',+ ['http', 'https']+ )[0]+ params.selection.primary.url =+ params.selection.kind === 'direct'+ ? source.sourceUrl+ : source.requestUrl}const { selection, source, meta } = paramsdiff --git a/src/core/bridge/__tests__/unary-mdxp.test.ts b/src/core/bridge/__tests__/unary-mdxp.test.tsindex 3a5d9bd4..aa4d4c02 100644--- a/src/core/bridge/__tests__/unary-mdxp.test.ts+++ b/src/core/bridge/__tests__/unary-mdxp.test.ts@@ -1,6 +1,7 @@import { request as httpRequest } from 'node:http'import type { PairedClient } from '@core/bridge/pairing-service'import { WebSocketBridgeServer } from '@core/bridge/web-socket-bridge-server'+import { DownloadSourceError } from '@core/task/source-admission'import { ErrorCodes } from '@motrix/mdxp'import { AppError, ErrorCode } from '@shared/errors'import { EngineState } from '@shared/types/engine'@@ -274,8 +275,13 @@ describe('unary POST /mdxp', () => {describe('unary POST /mdxp — AppError normalization', () => {let server: WebSocketBridgeServerlet port: number+ let nativeError: ErrorbeforeEach(async () => {+ nativeError = new AppError(+ ErrorCode.IpcInvalidPayload,+ 'bad native request'+ )server = new WebSocketBridgeServer({pairing: makeFakePairing(),registry: makeFakeRegistry(),@@ -292,7 +298,7 @@ describe('unary POST /mdxp — AppError normalization', () => {// handleCreateTask throws AppError (string `code`) on native re-validation;// the unary catch must translate it instead of collapsing to a 500.createTask: async () => {- throw new AppError(ErrorCode.IpcInvalidPayload, 'bad native request')+ throw nativeError},parseTorrentFileCount: async () => 1,})@@ -318,6 +324,36 @@ describe('unary POST /mdxp — AppError normalization', () => {expect(res.body.error?.code).toBe(ErrorCodes.InvalidParams)expect(res.body.error?.message).toContain('bad native request')})++ it('returns the safe source reason and boundary without exposing the URL', async () => {+ const failure = {+ stage: 'plugin' as const,+ index: 0,+ diagnostic: { reason: 'ambiguousBackslash' as const, start: 22, end: 23 },+ }+ nativeError = new DownloadSourceError(failure)+ const res = await postMdxp(+ port,+ {+ jsonrpc: '2.0',+ id: 'source',+ method: 'download/add',+ params: {+ kind: 'url',+ saveDir: '/dl',+ uris: ['https://example.test/file?token=private'],+ },+ },+ { token: LOCAL_TOKEN }+ )+ expect(res.status).toBe(400)+ expect(res.body.error).toEqual({+ code: ErrorCodes.InvalidParams,+ message: 'task.add.sourceErrors.ambiguousBackslash',+ data: failure,+ })+ expect(JSON.stringify(res.body)).not.toContain('private')+ })})describe('unary POST /mdxp — paired-token auth (device-code)', () => {diff --git a/src/core/bridge/handlers/write-handlers.test.ts b/src/core/bridge/handlers/write-handlers.test.tsindex 9dfdca1a..e9a94e3e 100644--- a/src/core/bridge/handlers/write-handlers.test.ts+++ b/src/core/bridge/handlers/write-handlers.test.ts@@ -333,6 +333,23 @@ describe('download/add idempotency', () => {await d.dispatch('download/add', keyedParams, cliCtx)await d.dispatch('download/add', keyedParams, otherCtx)expect(deps.createTask).toHaveBeenCalledTimes(2)+ expect(vi.mocked(deps.createTask).mock.calls[0][0]).toHaveProperty(+ 'requestId',+ expect.any(String)+ )+ expect(vi.mocked(deps.createTask).mock.calls[0][0]).not.toEqual(+ vi.mocked(deps.createTask).mock.calls[1][0]+ )+ })++ it('keeps the Core request ID stable when the transport cache is recreated', async () => {+ const first = setup()+ const restarted = setup()+ await first.d.dispatch('download/add', keyedParams, cliCtx)+ await restarted.d.dispatch('download/add', keyedParams, cliCtx)+ expect(vi.mocked(first.deps.createTask).mock.calls[0][0]).toEqual(+ vi.mocked(restarted.deps.createTask).mock.calls[0][0]+ )})it('does not cache a failed attempt — the retry re-executes', async () => {diff --git a/src/core/bridge/handlers/write-handlers.ts b/src/core/bridge/handlers/write-handlers.tsindex 60b187fe..79796781 100644--- a/src/core/bridge/handlers/write-handlers.ts+++ b/src/core/bridge/handlers/write-handlers.ts@@ -1,3 +1,4 @@+import { scopedCreateRequestId } from '@core/task/create-request-id'import {DownloadAddParamsSchema,ErrorCodes,@@ -131,6 +132,12 @@ export function registerWriteHandlers(async (params, ctx): Promise<MdxpTask> => {const createAndSnapshot = async (): Promise<MdxpTask> => {const req = await buildCreateRequest(params, deps.parseTorrentFileCount)+ if (req.type === 'http' && params.idempotencyKey) {+ req.requestId = scopedCreateRequestId(+ clientKey(ctx.identity),+ params.idempotencyKey+ )+ }const { taskId } = await deps.createTask(req)// handleCreateTask registers the task synchronously, so getById should// resolve immediately; a miss means the create path is broken.diff --git a/src/core/bridge/web-socket-bridge-server.ts b/src/core/bridge/web-socket-bridge-server.tsindex f263acab..e016b792 100644--- a/src/core/bridge/web-socket-bridge-server.ts+++ b/src/core/bridge/web-socket-bridge-server.ts@@ -3,6 +3,7 @@ import type { IncomingMessage, ServerResponse } from 'node:http'import { createServer, type Server as HttpServer } from 'node:http'import type { Duplex } from 'node:stream'import { AsyncWorkTracker } from '@core/inspector-activity/async-work-tracker'+import { DownloadSourceError } from '@core/task/source-admission'import {type DownloadCancelParams,DownloadCancelParamsSchema,@@ -2484,6 +2485,7 @@ function isMdxpErrorShape(function appErrorToMdxpCode(code: ErrorCode): number {switch (code) {case ErrorCode.IpcInvalidPayload:+ case ErrorCode.TaskSourceInvalid:case ErrorCode.InvalidSelection:case ErrorCode.SettingsInvalid:return ErrorCodes.InvalidParams@@ -2498,6 +2500,12 @@ function appErrorToMdxpCode(code: ErrorCode): number {/** Normalize any thrown value into an MDXP-shaped error for the unary response. */function normalizeUnaryError(err: unknown): NormalizedError {+ if (err instanceof DownloadSourceError)+ return {+ code: ErrorCodes.InvalidParams,+ message: err.message,+ data: err.details,+ }if (err instanceof AppError) {return { code: appErrorToMdxpCode(err.code), message: err.message }}diff --git a/src/core/download/aria2-segment-client.ts b/src/core/download/aria2-segment-client.tsindex 29e70eed..3c15239c 100644--- a/src/core/download/aria2-segment-client.ts+++ b/src/core/download/aria2-segment-client.ts@@ -1,3 +1,4 @@+import { admitDownloadSources } from '@core/task/source-admission'import type { SegmentAria2 } from './segment-downloader'interface Aria2Event {@@ -71,6 +72,9 @@ export class Aria2SegmentClient implements SegmentAria2 {'retry-wait'?: number}): Promise<string> {+ uris = admitDownloadSources(uris, 'engine', ['http', 'https']).map(+ (source) => source.requestUrl+ )const options: Record<string, string | string[]> = {continue: 'false',dir: opts.dir,diff --git a/src/core/engine/aria2/aria2-adapter.test.ts b/src/core/engine/aria2/aria2-adapter.test.tsindex d214c22a..2e50ee75 100644--- a/src/core/engine/aria2/aria2-adapter.test.ts+++ b/src/core/engine/aria2/aria2-adapter.test.ts@@ -189,7 +189,7 @@ const RAW_MAGNET_ACTIVE: Aria2RawStatus = {selected: 'true',uris: [{- uri: 'magnet:?xt=urn:btih:aabb',+ uri: 'magnet:?xt=urn:btih:a03e3f9a05341aa336e9d9d3f06b33cddafe0bdc',status: 'used',},],@@ -785,8 +785,8 @@ describe('Aria2Adapter', () => {})it.each([- ['magnet:?xt=urn:btih:aabb', '0'],- ['MAGNET:?xt=urn:btih:aabb', '0'],+ ['magnet:?xt=urn:btih:a03e3f9a05341aa336e9d9d3f06b33cddafe0bdc', '0'],+ ['MAGNET:?xt=urn:btih:a03e3f9a05341aa336e9d9d3f06b33cddafe0bdc', '0'],['https://example.com/magnet:fixture.bin', '10'],])('isolates Web Seed 404s only for magnet URIs: %s',@@ -802,7 +802,7 @@ describe('Aria2Adapter', () => {})expect(rpc.addUri).toHaveBeenCalledWith(- [uri],+ [uri.replace(/^MAGNET:/, 'magnet:')],expect.objectContaining({ 'max-file-not-found': limit }))}@@ -814,13 +814,13 @@ describe('Aria2Adapter', () => {const adapter = new Aria2Adapter(rpc)await adapter.createDownload({- uris: ['u'],+ uris: ['https://example.com/file'],saveDir: '/d',connections: 8,})expect(rpc.addUri).toHaveBeenCalledWith(- ['u'],+ ['https://example.com/file'],expect.objectContaining({split: '8','max-connection-per-server': '8',@@ -841,13 +841,13 @@ describe('Aria2Adapter', () => {)await adapter.createDownload({- uris: ['u'],+ uris: ['https://example.com/file'],saveDir: '/d',connections: 64,})expect(rpc.addUri).toHaveBeenCalledWith(- ['u'],+ ['https://example.com/file'],expect.objectContaining({split: '16','max-connection-per-server': '16',@@ -862,13 +862,13 @@ describe('Aria2Adapter', () => {adapter.setFeatureReport(featureReport())await adapter.createDownload({- uris: ['u'],+ uris: ['https://example.com/file'],saveDir: '/d',connections: 64,})expect(rpc.addUri).toHaveBeenCalledWith(- ['u'],+ ['https://example.com/file'],expect.objectContaining({split: '64','max-connection-per-server': '64',@@ -890,20 +890,20 @@ describe('Aria2Adapter', () => {await expect(adapter.createDownload({- uris: ['first'],+ uris: ['https://example.com/first'],saveDir: '/d',connections: 64,})).resolves.toBe('gid-first')await adapter.createDownload({- uris: ['second'],+ uris: ['https://example.com/second'],saveDir: '/d',connections: 64,})expect(rpc.addUri).toHaveBeenNthCalledWith(1,- ['first'],+ ['https://example.com/first'],expect.objectContaining({split: '64','max-connection-per-server': '64',@@ -911,7 +911,7 @@ describe('Aria2Adapter', () => {)expect(rpc.addUri).toHaveBeenNthCalledWith(2,- ['first'],+ ['https://example.com/first'],expect.objectContaining({split: '16','max-connection-per-server': '16',@@ -919,7 +919,7 @@ describe('Aria2Adapter', () => {)expect(rpc.addUri).toHaveBeenNthCalledWith(3,- ['second'],+ ['https://example.com/second'],expect.objectContaining({split: '16','max-connection-per-server': '16',@@ -934,7 +934,7 @@ describe('Aria2Adapter', () => {await expect(adapter.createDownload({- uris: ['u'],+ uris: ['https://example.com/file'],saveDir: '/d',connections: 64,})@@ -948,7 +948,7 @@ describe('Aria2Adapter', () => {const adapter = new Aria2Adapter(rpc)await adapter.createDownload({- uris: ['u'],+ uris: ['https://example.com/file'],saveDir: '/d',performanceProfile: 'auto',protocol: 'http',@@ -956,7 +956,7 @@ describe('Aria2Adapter', () => {})expect(rpc.addUri).toHaveBeenCalledWith(- ['u'],+ ['https://example.com/file'],expect.objectContaining({split: '32','min-split-size': String(10 * 1024 * 1024),@@ -972,16 +972,17 @@ describe('Aria2Adapter', () => {const adapter = new Aria2Adapter(rpc)await adapter.createDownload({- uris: ['u'],+ uris: ['https://example.com/file'],saveDir: '/d',performanceProfile: 'high',protocol: 'http',totalSizeBytes: 10 * 1024 * 1024 * 1024,})- expect(rpc.addUri).toHaveBeenCalledWith(['u'], {+ expect(rpc.addUri).toHaveBeenCalledWith(['https://example.com/file'], {continue: 'false',dir: '/d',+ header: ['Accept: */*'],})})@@ -991,7 +992,7 @@ describe('Aria2Adapter', () => {const adapter = new Aria2Adapter(rpc)await adapter.createDownload({- uris: ['u'],+ uris: ['https://example.com/file'],saveDir: '/d',performanceProfile: 'auto',protocol: 'http',@@ -1000,7 +1001,7 @@ describe('Aria2Adapter', () => {})expect(rpc.addUri).toHaveBeenCalledWith(- ['u'],+ ['https://example.com/file'],expect.objectContaining({split: '8','max-connection-per-server': '8',@@ -1014,14 +1015,14 @@ describe('Aria2Adapter', () => {const adapter = new Aria2Adapter(rpc)await adapter.createDownload({- uris: ['u'],+ uris: ['https://example.com/file'],saveDir: '/d',proxy: 'http://a%40b:p%3As@p:1080',extraEngineOptions: { referer: 'https://r', 'load-cookies': '/c' },})expect(rpc.addUri).toHaveBeenCalledWith(- ['u'],+ ['https://example.com/file'],expect.objectContaining({'all-proxy': 'http://p:1080','all-proxy-user': 'a@b',@@ -1041,13 +1042,13 @@ describe('Aria2Adapter', () => {const adapter = new Aria2Adapter(rpc)await adapter.createDownload({- uris: ['u'],+ uris: ['https://example.com/file'],saveDir: '/d',userAgent: 'Motrix/Applied',})expect(rpc.addUri).toHaveBeenCalledWith(- ['u'],+ ['https://example.com/file'],expect.objectContaining({ 'user-agent': 'Motrix/Applied' }))})@@ -1079,7 +1080,7 @@ describe('Aria2Adapter', () => {})expect(rpc.addUri).toHaveBeenCalledWith(- ['HTTPS://downloads.example/release'],+ ['https://downloads.example/release'],expect.objectContaining({ header: ['Accept: */*'] }))})@@ -1109,13 +1110,13 @@ describe('Aria2Adapter', () => {const adapter = new Aria2Adapter(rpc)await adapter.createDownload({- uris: ['u'],+ uris: ['https://example.com/file'],saveDir: '/d',userAgent: '',})expect(rpc.addUri).toHaveBeenCalledWith(- ['u'],+ ['https://example.com/file'],expect.objectContaining({ 'user-agent': '' }))})@@ -1126,7 +1127,7 @@ describe('Aria2Adapter', () => {await expect(adapter.createDownload({- uris: ['u'],+ uris: ['https://example.com/file'],saveDir: '/d',userAgent: 'Motrix\nall-proxy=http://evil',})@@ -1140,13 +1141,13 @@ describe('Aria2Adapter', () => {const adapter = new Aria2Adapter(rpc)await adapter.createDownload({- uris: ['u'],+ uris: ['https://example.com/file'],saveDir: '/d',proxy: 'proxy.example:1080',})expect(rpc.addUri).toHaveBeenCalledWith(- ['u'],+ ['https://example.com/file'],expect.objectContaining({'all-proxy': 'proxy.example:1080','all-proxy-user': '',@@ -1161,13 +1162,13 @@ describe('Aria2Adapter', () => {const adapter = new Aria2Adapter(rpc)await adapter.createDownload({- uris: ['u'],+ uris: ['https://example.com/file'],saveDir: '/d',proxy: 'http://user:[email protected]:8080',})expect(rpc.addUri).toHaveBeenCalledWith(- ['u'],+ ['https://example.com/file'],expect.objectContaining({'all-proxy': 'http://127.1:8080','all-proxy-user': 'user',@@ -1182,7 +1183,7 @@ describe('Aria2Adapter', () => {await expect(adapter.createDownload({- uris: ['u'],+ uris: ['https://example.com/file'],saveDir: '/d',extraEngineOptions: { 'http-proxy': 'http://other:8080' },})@@ -1197,7 +1198,11 @@ describe('Aria2Adapter', () => {const adapter = new Aria2Adapter(rpc)await expect(- adapter.createDownload({ uris: ['u'], saveDir: '/d', proxy })+ adapter.createDownload({+ uris: ['https://example.com/file'],+ saveDir: '/d',+ proxy,+ })).rejects.toThrow('Task proxy must use aria2-compatible HTTP or HTTPS')expect(rpc.addUri).not.toHaveBeenCalled()}@@ -1209,7 +1214,7 @@ describe('Aria2Adapter', () => {await expect(adapter.createDownload({- uris: ['u'],+ uris: ['https://example.com/file'],saveDir: '/d',proxy:'http://user%0Ahttp-proxy%3Dhttp%3A%2F%2Fevil:[email protected]:8080',@@ -1594,7 +1599,7 @@ describe('Aria2Adapter', () => {)settings = { seedTime: 30, seedRatio: 2 }await adapter.createDownload({- uris: ['magnet:?xt=urn:btih:abc'],+ uris: ['magnet:?xt=urn:btih:a03e3f9a05341aa336e9d9d3f06b33cddafe0bdc'],saveDir: '/d',})expect(vi.mocked(rpc.addUri).mock.calls.at(-1)?.[1]).toMatchObject({diff --git a/src/core/engine/aria2/aria2-adapter.ts b/src/core/engine/aria2/aria2-adapter.tsindex b0b43494..7108dde8 100644--- a/src/core/engine/aria2/aria2-adapter.ts+++ b/src/core/engine/aria2/aria2-adapter.ts@@ -7,6 +7,7 @@ import {normalizeAria2TaskProxyUrl,stripAria2ProxyCredentials,} from '@core/proxy/aria2-proxy-routing'+import { admitDownloadSources } from '@core/task/source-admission'import { AppError, ErrorCode } from '@shared/errors'import type {EngineCapability,@@ -369,6 +370,12 @@ export class Aria2Adapter implements EngineAdapter {}async createDownload(params: CreateDownloadParams): Promise<string> {+ params = {+ ...params,+ uris: admitDownloadSources(params.uris, 'engine').map(+ (source) => source.requestUrl+ ),+ }const extraGid = params.extraEngineOptions?.gidif (extraGid !== undefined && typeof extraGid !== 'string') {throw new TypeError(diff --git a/src/core/media/fetch-source.ts b/src/core/media/fetch-source.tsnew file mode 100644index 00000000..99baca15--- /dev/null+++ b/src/core/media/fetch-source.ts@@ -0,0 +1,52 @@+import { admitHttpSource } from '@core/task/source-admission'+import { resolveUri } from './segment-plan'++export async function cancelResponseBody(response: Response): Promise<void> {+ try {+ await response.body?.cancel()+ } catch {+ // Preserve the original failure when body cancellation also fails.+ }+}++/** Validate each redirect before fetching another media resource. */+export async function fetchSource(+ url: string,+ opts: {+ headers?: Record<string, string>+ fetchImpl?: typeof fetch+ } = {}+): Promise<Response> {+ url = admitHttpSource(url)+ const doFetch = opts.fetchImpl ?? fetch+ const signal = AbortSignal.timeout(10_000)+ let headers = opts.headers ?? {}+ for (let redirects = 0; ; redirects++) {+ const response = await doFetch(url, {+ method: 'GET',+ headers,+ redirect: 'manual',+ signal,+ })+ if (![301, 302, 303, 307, 308].includes(response.status)) return response+ await cancelResponseBody(response)+ const location = response.headers.get('location')+ if (!location || redirects >= 5)+ throw new Error('media redirect limit or missing location')+ const next = resolveUri(url, location)+ if (new URL(next).origin !== new URL(url).origin) {+ headers = Object.fromEntries(+ Object.entries(headers).filter(+ ([key]) =>+ ![+ 'authorization',+ 'cookie',+ 'proxy-authorization',+ 'host',+ ].includes(key.toLowerCase())+ )+ )+ }+ url = next+ }+}diff --git a/src/core/media/manifest-fetcher.test.ts b/src/core/media/manifest-fetcher.test.tsindex 8ef6c726..7df26093 100644--- a/src/core/media/manifest-fetcher.test.ts+++ b/src/core/media/manifest-fetcher.test.ts@@ -2,6 +2,51 @@ import { describe, expect, it, vi } from 'vitest'import { fetchManifest } from './manifest-fetcher'describe('fetchManifest', () => {+ it('rejects a malformed redirect before following it', async () => {+ const fetchImpl = vi.fn(+ async () =>+ new Response(null, {+ status: 302,+ headers: { location: 'https://other.test/a\\b' },+ })+ )+ await expect(+ fetchManifest('https://example.test/list', { fetchImpl })+ ).rejects.toMatchObject({ code: 'TASK_SOURCE_INVALID' })+ expect(fetchImpl).toHaveBeenCalledOnce()+ })++ it('drops credentials on a cross-origin redirect and excludes fragments', async () => {+ const fetchImpl = vi+ .fn()+ .mockResolvedValueOnce(+ new Response(null, {+ status: 302,+ headers: { location: 'https://cdn.test/list#view' },+ })+ )+ .mockResolvedValueOnce(new Response('#EXTM3U'))+ await fetchManifest('https://example.test/list', {+ fetchImpl,+ headers: { Authorization: 'secret', Cookie: 'sid=secret', Accept: '*/*' },+ })+ expect(fetchImpl).toHaveBeenLastCalledWith(+ 'https://cdn.test/list',+ expect.objectContaining({+ redirect: 'manual',+ headers: { Accept: '*/*' },+ })+ )+ })++ it('limits the streamed UTF-8 byte count', async () => {+ await expect(+ fetchManifest('https://example.test/list', {+ fetchImpl: vi.fn(async () => new Response('中文')),+ maxBytes: 4,+ })+ ).rejects.toThrow('manifest too large')+ })it('GETs with replayed headers and returns text', async () => {const fetchImpl = vi.fn(async () => new Response('#EXTM3U', { status: 200 })diff --git a/src/core/media/manifest-fetcher.ts b/src/core/media/manifest-fetcher.tsindex 578917df..85d94402 100644--- a/src/core/media/manifest-fetcher.ts+++ b/src/core/media/manifest-fetcher.ts@@ -1,12 +1,6 @@-const DEFAULT_MAX = 5 * 1024 * 1024+import { cancelResponseBody, fetchSource } from './fetch-source'-async function cancelResponseBody(response: Response): Promise<void> {- try {- await response.body?.cancel()- } catch {- // Preserve the HTTP error when body cancellation also fails.- }-}+const DEFAULT_MAX = 5 * 1024 * 1024export async function fetchManifest(url: string,@@ -16,20 +10,28 @@ export async function fetchManifest(maxBytes?: number} = {}): Promise<string> {- const doFetch = opts.fetchImpl ?? fetch- const res = await doFetch(url, {- method: 'GET',- headers: opts.headers ?? {},- redirect: 'follow',- })+ const res = await fetchSource(url, opts)if (!res.ok) {await cancelResponseBody(res)throw new Error(`manifest fetch failed: HTTP ${res.status}`)}- const text = await res.text()const max = opts.maxBytes ?? DEFAULT_MAX- if (text.length > max) {- throw new Error(`manifest too large: ${text.length} > ${max}`)+ const reader = res.body?.getReader()+ if (!reader) return ''+ const decoder = new TextDecoder()+ let size = 0+ let text = ''+ try {+ for (;;) {+ const { done, value } = await reader.read()+ if (done) break+ size += value.byteLength+ if (size > max) throw new Error('manifest too large')+ text += decoder.decode(value, { stream: true })+ }+ return text + decoder.decode()+ } finally {+ await reader.cancel().catch(() => undefined)+ reader.releaseLock()}- return text}diff --git a/src/core/media/segment-decryptor.test.ts b/src/core/media/segment-decryptor.test.tsindex 5244ab64..93116245 100644--- a/src/core/media/segment-decryptor.test.ts+++ b/src/core/media/segment-decryptor.test.ts@@ -1,8 +1,59 @@import { createCipheriv } from 'node:crypto'-import { describe, expect, it, vi } from 'vitest'+import { afterEach, describe, expect, it, vi } from 'vitest'import { SegmentDecryptor } from './segment-decryptor'describe('SegmentDecryptor', () => {+ afterEach(() => vi.unstubAllGlobals())++ it('rejects an ambiguous key redirect before requesting its target', async () => {+ const fetch = vi.fn().mockResolvedValue(+ new Response(null, {+ status: 302,+ headers: { location: 'https://cdn.test/dir\\key' },+ })+ )+ vi.stubGlobal('fetch', fetch)+ await expect(+ new SegmentDecryptor().getKey('https://cdn.test/key')+ ).rejects.toMatchObject({+ code: 'TASK_SOURCE_INVALID',+ })+ expect(fetch).toHaveBeenCalledOnce()+ })++ it('validates relative key redirects and reads exactly 16 key bytes', async () => {+ const key = new Uint8Array(16).fill(7)+ const fetch = vi+ .fn()+ .mockResolvedValueOnce(+ new Response(null, { status: 302, headers: { location: '../key' } })+ )+ .mockResolvedValueOnce(new Response(key))+ vi.stubGlobal('fetch', fetch)+ await expect(+ new SegmentDecryptor().getKey('https://cdn.test/dir/key')+ ).resolves.toEqual(key)+ expect(fetch).toHaveBeenLastCalledWith(+ 'https://cdn.test/key',+ expect.objectContaining({ redirect: 'manual' })+ )+ })++ it('cancels an oversized key body before reading the remaining stream', async () => {+ const cancel = vi.fn()+ const stream = new ReadableStream({+ start(controller) {+ controller.enqueue(new Uint8Array(17))+ },+ cancel,+ })+ vi.stubGlobal('fetch', vi.fn().mockResolvedValue(new Response(stream)))+ await expect(+ new SegmentDecryptor().getKey('https://cdn.test/key')+ ).rejects.toThrow('Key must be 16 bytes')+ expect(cancel).toHaveBeenCalledOnce()+ })+describe('decrypt with known AES-128-CBC vector', () => {it('decrypts PKCS7-padded ciphertext to plaintext', () => {const plaintext = Buffer.from('Hello, World! 1234')diff --git a/src/core/media/segment-decryptor.ts b/src/core/media/segment-decryptor.tsindex 0f37d49b..c679f3e1 100644--- a/src/core/media/segment-decryptor.ts+++ b/src/core/media/segment-decryptor.ts@@ -1,4 +1,6 @@import { createDecipheriv } from 'node:crypto'+import { admitHttpSource } from '@core/task/source-admission'+import { cancelResponseBody, fetchSource } from './fetch-source'export class SegmentDecryptor {private keyCache: Map<string, Promise<Uint8Array>>@@ -12,13 +14,30 @@ export class SegmentDecryptor {this.defaultFetchKey = fetchKey} else {this.defaultFetchKey = async (uri: string) => {- const response = await fetch(uri)- const buffer = await response.arrayBuffer()- const key = new Uint8Array(buffer)- if (key.length !== 16) {- throw new Error(`Key must be 16 bytes, got ${key.length} from ${uri}`)+ const response = await fetchSource(uri)+ if (!response.ok) {+ await cancelResponseBody(response)+ throw new Error(`Key request failed: HTTP ${response.status}`)+ }+ const reader = response.body?.getReader()+ if (!reader) throw new Error('Key must be 16 bytes')+ const key = new Uint8Array(16)+ let size = 0+ try {+ for (;;) {+ const { done, value } = await reader.read()+ if (done) break+ if (size + value.byteLength > key.length)+ throw new Error('Key must be 16 bytes')+ key.set(value, size)+ size += value.byteLength+ }+ if (size !== key.length) throw new Error('Key must be 16 bytes')+ return key+ } finally {+ await reader.cancel().catch(() => undefined)+ reader.releaseLock()}- return key}}}@@ -66,6 +85,7 @@ export class SegmentDecryptor {}async getKey(uri: string): Promise<Uint8Array> {+ uri = admitHttpSource(uri)// Return cached promise if available (concurrent-safe)const cached = this.keyCache.get(uri)if (cached) {diff --git a/src/core/media/segment-plan.ts b/src/core/media/segment-plan.tsindex 39d6ef23..11f3726e 100644--- a/src/core/media/segment-plan.ts+++ b/src/core/media/segment-plan.ts@@ -1,3 +1,4 @@+import { admitHttpSource } from '@core/task/source-admission'export type Container = 'mpegts' | 'fmp4' | 'single'export interface ByteRange {@@ -53,5 +54,22 @@ export function seqNumberIv(seq: number): Uint8Array {}export function resolveUri(base: string, ref: string): string {- return new URL(ref, base).toString()+ base = admitHttpSource(base)+ if (/^[a-z][a-z0-9+.-]*:/i.test(ref)) return admitHttpSource(ref)+ // Validate reference characters before WHATWG can silently discard them.+ const suffixAt = ref.search(/[?#]/)+ const referencePath = suffixAt < 0 ? ref : ref.slice(0, suffixAt)+ const suffix = suffixAt < 0 ? '' : ref.slice(suffixAt)+ // Literal dot segments have an unambiguous meaning only with a known base.+ // Encoded dots and all other parser rewrites still require correction.+ const checkedPath = referencePath+ .split('/')+ .map((part) => (part === '.' || part === '..' ? 'segment' : part))+ .join('/')+ admitHttpSource(+ ref.startsWith('//')+ ? `https:${checkedPath}${suffix}`+ : `https://reference.invalid/${checkedPath.replace(/^\/+/, '')}${suffix}`+ )+ return admitHttpSource(new URL(ref, base).toString())}diff --git a/src/core/plugin/hooks/abort.test.ts b/src/core/plugin/hooks/abort.test.tsindex 8ceb3818..f9530f38 100644--- a/src/core/plugin/hooks/abort.test.ts+++ b/src/core/plugin/hooks/abort.test.ts@@ -1,22 +1,6 @@-import type { Worker } from 'node:worker_threads'import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'-import type { CapabilityBridge } from '../host/capability-bridge'import { newHookAbort } from './abort'-function makeBridge(): CapabilityBridge & {- notifyAbort: ReturnType<typeof vi.fn>-} {- return { notifyAbort: vi.fn() } as unknown as CapabilityBridge & {- notifyAbort: ReturnType<typeof vi.fn>- }-}--function makeWorker(): Worker & { terminate: ReturnType<typeof vi.fn> } {- return {- terminate: vi.fn().mockResolvedValue(0),- } as unknown as Worker & { terminate: ReturnType<typeof vi.fn> }-}-describe('newHookAbort', () => {beforeEach(() => {vi.useFakeTimers()@@ -26,70 +10,63 @@ describe('newHookAbort', () => {vi.useRealTimers()})- it('timer triggers abort with reason "timeout"', async () => {- const bridge = makeBridge()- const worker = makeWorker()- const budget = newHookAbort(bridge, worker, 50)+ it('aborts once at its deadline with the timeout reason', async () => {+ const budget = newHookAbort(50)+ const listener = vi.fn()+ budget.signal.addEventListener('abort', listener)+ await vi.advanceTimersByTimeAsync(49)expect(budget.signal.aborted).toBe(false)-- await vi.advanceTimersByTimeAsync(50)-- expect(budget.signal.aborted).toBe(true)+ await vi.advanceTimersByTimeAsync(1)expect(budget.signal.reason).toBe('timeout')+ expect(listener).toHaveBeenCalledOnce()+ budget.dispose()+ expect(vi.getTimerCount()).toBe(0)})- it('explicit abort cancels timer; bridge.notifyAbort called exactly once', async () => {- const bridge = makeBridge()- const worker = makeWorker()- const budget = newHookAbort(bridge, worker, 200)+ it('explicit abort cancels the deadline and preserves its first reason', async () => {+ const budget = newHookAbort(200)+ const listener = vi.fn()+ budget.signal.addEventListener('abort', listener)budget.abort('manual')-- // Advance past original timeout — the timer should have been cleared.+ budget.abort('another reason')+ expect(vi.getTimerCount()).toBe(0)await vi.advanceTimersByTimeAsync(500)expect(budget.signal.aborted).toBe(true)expect(budget.signal.reason).toBe('manual')- // Even with time advancing past the deadline, notifyAbort fires only once.- expect(bridge.notifyAbort).toHaveBeenCalledTimes(1)+ expect(listener).toHaveBeenCalledOnce()+ budget.dispose()})- it('bridge.notifyAbort is called once when timeout fires', async () => {- const bridge = makeBridge()- const worker = makeWorker()- newHookAbort(bridge, worker, 30)-- await vi.advanceTimersByTimeAsync(30)-- expect(bridge.notifyAbort).toHaveBeenCalledTimes(1)- })+ it('disposal cancels the timer without sending an abort, even when repeated', async () => {+ const budget = newHookAbort(200)+ const listener = vi.fn()+ budget.signal.addEventListener('abort', listener)- it('terminate: signal is aborted before worker.terminate is called', async () => {- const bridge = makeBridge()- const worker = makeWorker()- const budget = newHookAbort(bridge, worker, 10_000)-- const terminatePromise = budget.terminate()-- // Signal must be aborted immediately, before the 1 s grace elapses.- expect(budget.signal.aborted).toBe(true)- expect(worker.terminate).not.toHaveBeenCalled()-- // Advance through the 1 s grace period.- await vi.advanceTimersByTimeAsync(1_000)- await terminatePromise+ budget.dispose()+ budget.dispose()+ budget.abort('late cancellation')+ expect(vi.getTimerCount()).toBe(0)+ await vi.advanceTimersByTimeAsync(500)- expect(worker.terminate).toHaveBeenCalledTimes(1)+ expect(budget.signal.aborted).toBe(false)+ expect(listener).not.toHaveBeenCalled()})- it('abort.signal.reason matches the passed reason on explicit abort', () => {- const bridge = makeBridge()- const worker = makeWorker()- const budget = newHookAbort(bridge, worker, 5_000)-- budget.abort('plugin_timeout')-- expect(budget.signal.reason).toBe('plugin_timeout')+ it('disposing an earlier budget preserves the later invocation deadline', async () => {+ const first = newHookAbort(100)+ await vi.advanceTimersByTimeAsync(80)+ first.dispose()+ const second = newHookAbort(100)++ await vi.advanceTimersByTimeAsync(20)+ expect(first.signal.aborted).toBe(false)+ expect(second.signal.aborted).toBe(false)+ await vi.advanceTimersByTimeAsync(80)+ expect(second.signal.aborted).toBe(true)+ expect(second.signal.reason).toBe('timeout')+ second.dispose()})})diff --git a/src/core/plugin/hooks/abort.ts b/src/core/plugin/hooks/abort.tsindex d02a41a0..20c62fd8 100644--- a/src/core/plugin/hooks/abort.ts+++ b/src/core/plugin/hooks/abort.ts@@ -1,49 +1,30 @@-// src/core/plugin/hooks/abort.ts-// Host-owned AbortController for a single hook invocation (I37).-//-// Lifecycle:-// 1. newHookAbort() arms a deadline timer (timeoutMs).-// 2. On timeout OR explicit abort(), the AbortController fires.-// 3. The abort listener notifies the bridge (worker receives 'abort' event).-// 4. terminate() aborts first, then waits a 1-second grace period before-// calling worker.terminate() as a backstop for hung workers.--import type { Worker } from 'node:worker_threads'-import type { CapabilityBridge } from '../host/capability-bridge'+// A deadline belongs to one invocation, including its wait for admission.+// Only the bridge listener attached to that invocation may notify its worker.+// Dispose on completion without aborting the shared plugin's next invocation.export interface HookAbortBudget {signal: AbortSignalabort(reason: string): void- terminate(): Promise<void>+ dispose(): void}-export function newHookAbort(- bridge: CapabilityBridge,- worker: Worker,- timeoutMs: number-): HookAbortBudget {+export function newHookAbort(timeoutMs: number): HookAbortBudget {const ctrl = new AbortController()+ let disposed = false+ const timer = setTimeout(() => abort('timeout'), timeoutMs)- // Arm the deadline timer; cleared if abort fires before it expires.- const timer = setTimeout(() => ctrl.abort('timeout'), timeoutMs)-- ctrl.signal.addEventListener('abort', () => {+ function abort(reason: string): void {+ if (disposed) returnclearTimeout(timer)- bridge.notifyAbort()- })+ ctrl.abort(reason)+ }return {signal: ctrl.signal,-- abort(reason: string): void {- ctrl.abort(reason)- },-- async terminate(): Promise<void> {- ctrl.abort('terminate')- // Grace period: give in-flight ops up to 1 s to clean up after abort.- await new Promise<void>((r) => setTimeout(r, 1_000))- await worker.terminate()+ abort,+ dispose(): void {+ disposed = true+ clearTimeout(timer)},}}diff --git a/src/core/plugin/hooks/hook-orchestrator.integration.test.ts b/src/core/plugin/hooks/hook-orchestrator.integration.test.tsindex 1799dc15..320f6a7c 100644--- a/src/core/plugin/hooks/hook-orchestrator.integration.test.ts+++ b/src/core/plugin/hooks/hook-orchestrator.integration.test.ts@@ -47,7 +47,6 @@ interface FixturePlugin {interface MockBridge {setHookContext: Mock<(args: HookContextArgs) => void>clearHookContext: Mock<() => void>- notifyAbort: Mock<() => void>}function makeManifest(p: FixturePlugin): PluginManifest {@@ -71,7 +70,6 @@ function makeMockBridge(): MockBridge {return {setHookContext: vi.fn<(args: HookContextArgs) => void>(),clearHookContext: vi.fn<() => void>(),- notifyAbort: vi.fn<() => void>(),}}diff --git a/src/core/plugin/hooks/hook-orchestrator.test.ts b/src/core/plugin/hooks/hook-orchestrator.test.tsindex 374f1603..1af67598 100644--- a/src/core/plugin/hooks/hook-orchestrator.test.ts+++ b/src/core/plugin/hooks/hook-orchestrator.test.ts@@ -7,8 +7,8 @@//// Mocking strategy: we substitute a minimal PluginHost shape that the// orchestrator uses (allActive, invokeHook). The bridge/worker pair is mocked-// so newHookAbort can call notifyAbort without crashing. Real workers / VMs-// are not spawned here — that is T17's e2e responsibility.+// to track per-invocation context. Real workers / VMs are exercised by the+// PluginHost e2e tests.import { mkdir, mkdtemp, readFile, rm, stat, writeFile } from 'node:fs/promises'import os from 'node:os'@@ -57,7 +57,6 @@ interface FixturePlugin {interface MockBridge {setHookContext: ReturnType<typeof vi.fn>clearHookContext: ReturnType<typeof vi.fn>- notifyAbort: ReturnType<typeof vi.fn>}function makeManifest(p: FixturePlugin): PluginManifest {@@ -83,7 +82,6 @@ function makeMockBridge(): MockBridge {return {setHookContext: vi.fn(),clearHookContext: vi.fn(),- notifyAbort: vi.fn(),}}@@ -200,6 +198,62 @@ const ORCH_OPTS_BASE = {// ---------------------------------------------------------------------------describe('HookOrchestrator', () => {+ describe.each([+ 'beforeCreate',+ 'beforeFinalize',+ 'afterComplete',+ 'onError',+ ] as const)('%s budget cleanup', (hook) => {+ beforeEach(() => vi.useFakeTimers())+ afterEach(() => vi.useRealTimers())++ it.each(['success', 'failure'] as const)(+ 'releases its deadline after %s without cancelling a completed invocation',+ async (outcome) => {+ const signals: AbortSignal[] = []+ const { host } = makeMockHost([+ {+ id: 'budget-test',+ role: 'resolve',+ hooks: [hook],+ handler: ({ signal }) => {+ signals.push(signal)+ if (outcome === 'failure') throw new Error('hook failed')+ },+ },+ ])+ const orch = new HookOrchestrator({+ host,+ hookTimeoutMs: TIMEOUTS,+ ...ORCH_OPTS_BASE,+ })+ if (hook === 'beforeCreate') {+ const result = await orch.runBeforeCreateHttp(+ makeBeforeCreateDto(),+ 'task-1'+ )+ expect(result.aborted === true).toBe(outcome === 'failure')+ } else if (hook === 'beforeFinalize') {+ const result = await orch.runBeforeFinalize(+ makeBeforeFinalizeDto(),+ 'task-1'+ )+ expect(result.aborted === true).toBe(outcome === 'failure')+ } else {+ await orch.runParallel(+ hook,+ { task: { id: 'task-1' }, filePath: '/x' } as never,+ 'task-1'+ )+ }+ expect(signals).toHaveLength(1)+ expect(vi.getTimerCount()).toBe(0)+ await vi.advanceTimersByTimeAsync(1_000)+ expect(signals[0].aborted).toBe(false)+ }+ )+ })+it('discovers an inactive registry candidate and activates it on Hook demand', async () => {const plugin: FixturePlugin = {id: 'idle-plugin',diff --git a/src/core/plugin/hooks/hook-orchestrator.ts b/src/core/plugin/hooks/hook-orchestrator.tsindex f85db9d7..c0265e35 100644--- a/src/core/plugin/hooks/hook-orchestrator.ts+++ b/src/core/plugin/hooks/hook-orchestrator.ts@@ -1,3 +1,7 @@+import {+ admitDownloadSources,+ DownloadSourceError,+} from '@core/task/source-admission'// src/core/plugin/hooks/hook-orchestrator.ts// Plan C — drives every hook chain:// - beforeCreate / beforeFinalize: serial chain over eligible plugins,@@ -155,7 +159,7 @@ export class HookOrchestrator {log.info({taskId,- url: initial.uris[0],+ uriCount: initial.uris.length,chainLength: chain.length,chain: chain.map((e) => ({ id: e.id, role: e.role })),},@@ -188,7 +192,7 @@ export class HookOrchestrator {continue}- const abort = newHookAbort(entry.info.bridge, entry.info.worker, timeout)+ const abort = newHookAbort(timeout)try {const metadataSnapshot = await this.metadataSnapshot(taskId, entry.id)@@ -209,8 +213,13 @@ export class HookOrchestrator {},})working = mergeBeforeCreateWorking(initial, staged)+ working.uris = admitDownloadSources(working.uris, 'plugin', [+ 'http',+ 'https',+ ]).map((source) => source.sourceUrl)this.opts.breaker?.success(entry.id, 'beforeCreate')} catch (e) {+ if (e instanceof DownloadSourceError) throw ethis.opts.breaker?.failure(entry.id, 'beforeCreate')await this.maybeDisable(entry.id, 'beforeCreate')const message = (e as Error).message@@ -238,6 +247,8 @@ export class HookOrchestrator {// merge step does not pick them up.staged.removeFromPlugin(entry.id)working = mergeBeforeCreateWorking(initial, staged)+ } finally {+ abort.dispose()}}@@ -311,8 +322,6 @@ export class HookOrchestrator {continue}- const abort = newHookAbort(entry.info.bridge, entry.info.worker, timeout)-// beforeFinalize uses the saveDir derived from initial.filePath's parent// for path-escape validation (T3 validateFinalizePatch). The bridge gate// also needs a non-null fsTaskHost for the matrix branch.@@ -333,6 +342,7 @@ export class HookOrchestrator {staged.appendStaging(entry.id, staging)const previousFinalizePath = staged.pendingFinalizePath+ const abort = newHookAbort(timeout)try {const metadataSnapshot = await this.metadataSnapshot(taskId, entry.id)await this.opts.host.invokeHook(entry.id, 'beforeFinalize', {@@ -396,6 +406,8 @@ export class HookOrchestrator {filePath: previousFinalizePath ?? initial.filePath,targetFilePath: previousFinalizePath ?? initial.targetFilePath,}+ } finally {+ abort.dispose()}}@@ -459,7 +471,7 @@ export class HookOrchestrator {return}- const abort = newHookAbort(entry.info.bridge, entry.info.worker, timeout)+ const abort = newHookAbort(timeout)try {const metadataSnapshot = await this.metadataSnapshot(taskId, entry.id)@@ -490,6 +502,8 @@ export class HookOrchestrator {role: entry.role,error: (e as Error).message,})+ } finally {+ abort.dispose()}})diff --git a/src/core/plugin/host/capability-bridge.ts b/src/core/plugin/host/capability-bridge.tsindex f29bd9f7..4c41396a 100644--- a/src/core/plugin/host/capability-bridge.ts+++ b/src/core/plugin/host/capability-bridge.ts@@ -1520,15 +1520,15 @@ export class CapabilityBridge {})}- /**- * Called by abort.ts when the host-owned AbortController fires. Posts an- * 'abort' event to the worker so the plugin runtime can cancel in-flight ops.- *- * TODO(T16): also cancel any tracked ffmpeg/http handles held by this bridge.- */- notifyAbort(): void {- if (this.disposed || !this.currentInvocationScope) return- const scope = this.currentInvocationScope+ /** Cancel only the invocation captured by callHook's signal/deadline. */+ private notifyAbort(scope: HookInvocationScopeV1): void {+ if (+ this.disposed ||+ !this.currentInvocationScope ||+ !sameHookScope(this.currentInvocationScope, scope)+ ) {+ return+ }this.worker.postMessage({type: 'event',event: 'abort',@@ -1929,7 +1929,7 @@ export class CapabilityBridge {return new Promise<HookEffectsV1>((resolve, reject) => {const onAbort = () => {if (this.pendingHook && sameHookScope(this.pendingHook.scope, scope)) {- this.notifyAbort()+ this.notifyAbort(scope)this.pendingHook.detach()this.pendingHook = nullthis.clearHookContext()@@ -1940,7 +1940,7 @@ export class CapabilityBridge {}const timer = setTimeout(() => {if (this.pendingHook && sameHookScope(this.pendingHook.scope, scope)) {- this.notifyAbort()+ this.notifyAbort(scope)this.pendingHook.detach()this.pendingHook = nullthis.clearHookContext()@@ -1979,11 +1979,7 @@ export class CapabilityBridge {})}- /**- * Plan C — public accessor for the underlying Worker. Required by- * `newHookAbort(bridge, worker, timeoutMs)` so the abort budget can- * `worker.terminate()` as a backstop for hung workers.- */+ /** Worker access for host lifecycle management and diagnostics. */getWorker(): Worker {return this.worker}diff --git a/src/core/plugin/host/orchestrator.e2e.test.ts b/src/core/plugin/host/orchestrator.e2e.test.tsindex 346bb192..90748686 100644--- a/src/core/plugin/host/orchestrator.e2e.test.ts+++ b/src/core/plugin/host/orchestrator.e2e.test.ts@@ -20,6 +20,7 @@ import {CookieJar,ensureCookieJarSchema,} from '@core/plugin/capabilities/http-cookies'+import type { CapabilityHost } from '@core/plugin/capabilities/interface'import {ensureMetadataSchema,MetadataCapabilityHost,@@ -38,6 +39,7 @@ import {import { freezeHookPlan } from '@core/plugin/finalize/hook-plan'import { NativeFinalizeArtifactOperations } from '@core/plugin/finalize/native-artifact-operations'import { HookOrchestrator } from '@core/plugin/hooks/hook-orchestrator'+import { StagedEffectStore } from '@core/plugin/hooks/staged-effects'import { PluginRegistry } from '@core/plugin/plugin-registry'import { PluginStateStore } from '@core/plugin/state/plugin-state-store'import { migrate } from '@core/session/migrations'@@ -47,8 +49,8 @@ import type {PluginHookTask,} from '@shared/types/plugin-hooks'import Database from 'better-sqlite3'-import { Agent, type Dispatcher } from 'undici'-import { afterEach, describe, expect, it } from 'vitest'+import { Agent, type Dispatcher, MockAgent } from 'undici'+import { afterEach, describe, expect, it, vi } from 'vitest'import { ActivationDispatcher } from './activation-dispatcher'import { PluginHost } from './plugin-host'import { makeStubCapabilityHost } from './test-helpers'@@ -84,6 +86,7 @@ interface Harness {const cleanups: Array<() => Promise<void> | void> = []afterEach(async () => {+ vi.useRealTimers()for (const cleanup of cleanups.splice(0).reverse()) await cleanup()})@@ -315,6 +318,154 @@ function beforeFinalize(input: {}describe('locked builtin bundles through PluginHost + QuickJS Hooks', () => {+ it('expires a queued Hook without aborting the invocation holding the plugin lane', async () => {+ const dispatcher = new MockAgent()+ dispatcher.disableNetConnect()+ cleanups.push(() => dispatcher.close())+ const requestStarted = Promise.withResolvers<void>()+ const response = Promise.withResolvers<void>()+ let requests = 0+ dispatcher+ .get('https://example.test')+ .intercept({ method: 'HEAD', path: '/archive.zip' })+ .reply(async () => {+ requests += 1+ requestStarted.resolve()+ await response.promise+ return {+ statusCode: 200,+ data: '',+ responseOptions: {+ headers: { 'content-type': 'application/octet-stream' },+ },+ }+ })+ .persist()+ const harness = await makeHarness({ dispatcher })+ const pluginId = 'motrix.scraper-hook'+ enableOnly(harness, pluginId)+ await harness.host.activate(pluginId)+ const queuedEntry = Promise.withResolvers<void>()+ const invokeHook = harness.host.invokeHook.bind(harness.host)+ vi.spyOn(harness.host, 'invokeHook').mockImplementation(+ (id, hook, args) => {+ const result = invokeHook(id, hook, args)+ if (args.taskId === 'queued') queuedEntry.resolve()+ return result+ }+ )+ const url = 'https://example.test/archive.zip'+ vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] })+ try {+ const active = harness.host.invokeHook(pluginId, 'beforeCreate', {+ taskId: 'active',+ signal: new AbortController().signal,+ timeoutMs: 20_000,+ ctxPayload: beforeCreate('active', url, harness.root),+ context: {+ fsTaskHost: {} as ReturnType<CapabilityHost['fsTaskFor']>,+ taskId: 'active',+ phase: 'beforeCreate',+ staged: new StagedEffectStore(),+ role: 'pre-resolve',+ saveDir: harness.root,+ pluginStorageRoot: path.join(harness.root, 'storage'),+ },+ })+ const activeResult = active.then(+ () => 'completed',+ (error: Error) => error.message+ )+ await requestStarted.promise+ const queued = harness.orchestrator.runBeforeCreateHttp(+ beforeCreate('queued', url, harness.root),+ 'queued'+ )+ await queuedEntry.promise+ expect(harness.host.laneState(pluginId)).toMatchObject({+ running: 1,+ queued: 1,+ })+ await vi.advanceTimersByTimeAsync(10_001)+ expect(harness.host.bridgeFor(pluginId)?.operationState()).toMatchObject({+ hookCalls: 1,+ httpOperations: 1,+ })+ response.resolve()+ expect(await activeResult).toBe('completed')+ expect(await queued).toEqual({+ aborted: true,+ reason: `${pluginId}: plugin.runtime.entry_aborted`,+ })+ expect(requests).toBe(1)+ } finally {+ response.resolve()+ vi.useRealTimers()+ }+ }, 20_000)++ it('keeps a repeated scraper request alive across the previous Hook deadline', async () => {+ const dispatcher = new MockAgent()+ dispatcher.disableNetConnect()+ cleanups.push(() => dispatcher.close())+ const secondRequest = Promise.withResolvers<void>()+ const response = Promise.withResolvers<void>()+ let requests = 0+ dispatcher+ .get('https://example.test')+ .intercept({ method: 'HEAD', path: '/WeChatWin.exe' })+ .reply(async () => {+ requests += 1+ if (requests === 2) {+ secondRequest.resolve()+ await response.promise+ }+ return {+ statusCode: 200,+ data: '',+ responseOptions: {+ headers: { 'content-type': 'application/octet-stream' },+ },+ }+ })+ .persist()+ const harness = await makeHarness({ dispatcher })+ enableOnly(harness, 'motrix.scraper-hook')+ await harness.host.activate('motrix.scraper-hook')+ const invokeHook = vi.spyOn(harness.host, 'invokeHook')+ const url = 'https://example.test/WeChatWin.exe'+ const saveDir = String.raw`C:\Users\tester\Downloads`+ // The production 10-second budget runs on a controlled host clock;+ // worker execution and the HTTP response are synchronized by promises.+ vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] })+ try {+ const first = await harness.orchestrator.runBeforeCreateHttp(+ beforeCreate('first', url, saveDir),+ 'first'+ )+ expect(first.aborted).not.toBe(true)+ await vi.advanceTimersByTimeAsync(8_000)+ const second = harness.orchestrator.runBeforeCreateHttp(+ beforeCreate('second', url, saveDir),+ 'second'+ )+ await secondRequest.promise+ await vi.advanceTimersByTimeAsync(2_001)+ expect(invokeHook.mock.calls[1]?.[2].signal.aborted).toBe(false)+ response.resolve()+ const result = await second+ expect(result.aborted).not.toBe(true)+ if (result.aborted) throw new Error(result.reason)+ expect(result.final.uris).toEqual([url])+ expect(result.final.saveDir).toBe(saveDir)+ expect(requests).toBe(2)+ expect(harness.logs.filter((entry) => entry.level === 'warn')).toEqual([])+ } finally {+ response.resolve()+ vi.useRealTimers()+ }+ }, 20_000)+it('scraper-hook performs real HEAD+GET and resolves a nested relative archive', async () => {const requests: Array<{ method: string; host: string; path: string }> = []const loopback = await createOriginPreservingLoopback(diff --git a/src/core/plugin/host/plugin-host.ts b/src/core/plugin/host/plugin-host.tsindex 87504b57..9af0f6ed 100644--- a/src/core/plugin/host/plugin-host.ts+++ b/src/core/plugin/host/plugin-host.ts@@ -907,7 +907,7 @@ export class PluginHost {return this.activeForUse(pluginId)?.bridge}- /** Plan C — worker accessor used by `newHookAbort` for the terminate path. */+ /** Worker access for lifecycle diagnostics. */workerFor(pluginId: string): Worker | undefined {return this.active.get(pluginId)?.bridge.getWorker()}diff --git a/src/core/session/session-manager.test.ts b/src/core/session/session-manager.test.tsindex 7bf16b3c..d0f0977d 100644--- a/src/core/session/session-manager.test.ts+++ b/src/core/session/session-manager.test.ts@@ -3984,7 +3984,9 @@ describe('restore() with task_instances (Plan A Task 7)', () => {TaskInstancePhase.MagnetMetadataResolution),diskPath: '/tmp/motrix-magnet-metadata-xyz',- uris: ['magnet:?xt=urn:btih:abc'],+ uris: [+ 'magnet:?xt=urn:btih:a9993e364706816aba3e25717850c26c9cd0d89d',+ ],payload: { metadataDir: '/tmp/motrix-magnet-metadata-xyz' },},],@@ -3995,7 +3997,7 @@ describe('restore() with task_instances (Plan A Task 7)', () => {const addUri = (rpc as unknown as { addUri: ReturnType<typeof vi.fn> }).addUriexpect(addUri).toHaveBeenCalledWith(- ['magnet:?xt=urn:btih:abc'],+ ['magnet:?xt=urn:btih:a9993e364706816aba3e25717850c26c9cd0d89d'],expect.objectContaining({'bt-load-saved-metadata': 'false','bt-metadata-only': 'true',@@ -4041,7 +4043,9 @@ describe('restore() with task_instances (Plan A Task 7)', () => {TaskInstancePhase.MagnetMetadataResolution),diskPath: '/tmp/motrix-magnet-metadata-failed',- uris: ['magnet:?xt=urn:btih:failed'],+ uris: [+ 'magnet:?xt=urn:btih:5f5f8758f5f22d523e531f58123b6db9161683a4',+ ],payload: {metadataDir: '/tmp/motrix-magnet-metadata-failed',cleanupQuarantined: false,@@ -4099,7 +4103,9 @@ describe('restore() with task_instances (Plan A Task 7)', () => {),status: TaskStatus.Error,diskPath: '/tmp/motrix-magnet-metadata-q',- uris: ['magnet:?xt=urn:btih:q'],+ uris: [+ 'magnet:?xt=urn:btih:22ea1c649c82946aa6e479e1ffd321e4a318b1b0',+ ],payload: {metadataDir: '/tmp/motrix-magnet-metadata-q',cleanupQuarantined: true,diff --git a/src/core/session/session-manager.ts b/src/core/session/session-manager.tsindex cc9c48fa..7e54f946 100644--- a/src/core/session/session-manager.ts+++ b/src/core/session/session-manager.ts@@ -9,6 +9,10 @@ import {safeObserve,} from '@core/plugin/post/delivery-observability'import type { PostDeliveryAdmissionSummary } from '@core/plugin/post/delivery-retention'+import {+ admitDownloadSources,+ DownloadSourceError,+} from '@core/task/source-admission'import { parseDirectReplayRecipe } from '@shared/schemas/direct-replay-recipe'import type { DownloadTask } from '@shared/types/task'import {@@ -1534,6 +1538,17 @@ export class SessionManager {}if (primary && primary.uris.length > 0) {+ let admittedUris: string[]+ try {+ admittedUris = admitDownloadSources(primary.uris, 'recovery', [+ 'http',+ 'https',+ 'ftp',+ ]).map((source) => source.requestUrl)+ } catch (error) {+ if (!(error instanceof DownloadSourceError)) throw error+ return this.markRecoverErrorFromPair(pair, error.message)+ }const recipe = parseDirectReplayRecipe(primary.payload)if (recipe?.replayability === 'requires-credentials') {return this.markRecoverErrorFromPair(@@ -1605,7 +1620,7 @@ export class SessionManager {requestOptions &&canMirrorAria2MetadataHeaders(this.adapter.getFeatureReport?.())? await this.directResourceValidator.verify(- primary.uris[0] as string,+ admittedUris[0],recipe.resourceValidator,requestOptions)@@ -1625,7 +1640,7 @@ export class SessionManager {return this.dispatchRecoveryCandidate(pair, (gid) => {assertProxyCurrent?.()return this.adapter.createDownload({- uris: primary.uris,+ uris: admittedUris,gid,saveDir: plan.saveDir as string,filename: plan.filename as string,@@ -1839,7 +1854,10 @@ export class SessionManager {}try {- const newGid = await this.rpc.addUri([magnetUri], {+ const uris = admitDownloadSources([magnetUri], 'recovery', [+ 'magnet',+ ]).map((source) => source.requestUrl)+ const newGid = await this.rpc.addUri(uris, {'max-file-not-found': '0','bt-load-saved-metadata': 'false','bt-metadata-only': 'true',diff --git a/src/core/task/actions/re-add-task.ts b/src/core/task/actions/re-add-task.tsindex cf23fa55..3265a95c 100644--- a/src/core/task/actions/re-add-task.ts+++ b/src/core/task/actions/re-add-task.ts@@ -1,6 +1,7 @@import path from 'node:path'import { newEngineTaskId } from '@core/lib/ids'import type { AppliedDownloadProxyPolicyReader } from '@core/proxy/applied-download-proxy-policy'+import { admitDownloadSources } from '@core/task/source-admission'import { AppError, ErrorCode } from '@shared/errors'import { parseDirectReplayRecipe } from '@shared/schemas/direct-replay-recipe'import type { DownloadTask } from '@shared/types/task'@@ -219,6 +220,11 @@ async function buildDirectReAddParams(`Task ${task.id} cannot be retried: its direct replay recipe is unavailable`)}+ const sources = admitDownloadSources(primary.uris, 'recovery', [+ 'http',+ 'https',+ 'ftp',+ ])const requestOptions = getProxyOptions()const plan = await directRecoveryPlanner.plan({@@ -274,7 +280,7 @@ async function buildDirectReAddParams()}const validation = await resourceValidator.verify(- primary.uris[0] as string,+ sources[0].requestUrl,recipe.resourceValidator,requestOptions)@@ -289,7 +295,7 @@ async function buildDirectReAddParams(}return {- uris: primary.uris,+ uris: sources.map((source) => source.requestUrl),saveDir: plan.saveDir,filename: plan.filename,connections: recipe.connections,diff --git a/src/core/task/create-request-id.test.ts b/src/core/task/create-request-id.test.tsnew file mode 100644index 00000000..7d7286ac--- /dev/null+++ b/src/core/task/create-request-id.test.ts@@ -0,0 +1,73 @@+import { makeDownloadTask } from '@test-utils/task'+import { describe, expect, it, vi } from 'vitest'+import { z } from 'zod'+import { runCreateRequest, scopedCreateRequestId } from './create-request-id'++describe('create request receipts', () => {+ it('binds remote request IDs to both client identity and key', () => {+ const id = scopedCreateRequestId('client-one', 'retry-key')+ expect(z.uuid().safeParse(id).success).toBe(true)+ expect(scopedCreateRequestId('client-one', 'retry-key')).toBe(id)+ expect(scopedCreateRequestId('client-two', 'retry-key')).not.toBe(id)+ expect(scopedCreateRequestId('client-one', 'new-key')).not.toBe(id)+ })+ it('coalesces pending calls and rejects a different payload under the same key', async () => {+ const owners = { getAll: () => [] }+ let finish!: (value: {+ outcome: 'created'+ gid: string+ taskId: string+ }) => void+ const create = vi.fn(+ () =>+ new Promise<{ outcome: 'created'; gid: string; taskId: string }>(+ (resolve) => {+ finish = resolve+ }+ )+ )+ const first = runCreateRequest(owners, 'id', 'fingerprint', create)+ expect(runCreateRequest(owners, 'id', 'fingerprint', create)).toBe(first)+ await expect(+ runCreateRequest(owners, 'id', 'different', create)+ ).rejects.toMatchObject({ code: 'IPC_INVALID_PAYLOAD' })+ finish({ outcome: 'created', gid: 'gid', taskId: 'task' })+ await expect(first).resolves.toMatchObject({ taskId: 'task' })+ expect(create).toHaveBeenCalledOnce()+ })++ it('reuses durable task receipts after the in-memory owner is replaced', async () => {+ const task = makeDownloadTask({ id: 'task', engineTaskId: 'gid' })+ task.instances = [+ {+ payload: {+ createRequestId: 'id',+ createRequestFingerprint: 'fingerprint',+ },+ },+ ] as unknown as typeof task.instances+ const create = vi.fn()+ const owners = { getAll: () => [task] }+ await expect(+ runCreateRequest(owners, 'id', 'fingerprint', create)+ ).resolves.toEqual({ outcome: 'reused', gid: 'gid', taskId: 'task' })+ await expect(+ runCreateRequest({ getAll: () => [task] }, 'id', 'fingerprint', create)+ ).resolves.toMatchObject({ outcome: 'reused' })+ expect(create).not.toHaveBeenCalled()+ })++ it('permits a confirmed failure to retry and distinct keys to create duplicates', async () => {+ const owners = { getAll: () => [] }+ const create = vi+ .fn()+ .mockRejectedValueOnce(new Error('failed'))+ .mockResolvedValue({ outcome: 'created', taskId: 'task', gid: 'gid' })+ await expect(runCreateRequest(owners, 'id', 'f', create)).rejects.toThrow(+ 'failed'+ )+ await runCreateRequest(owners, 'id', 'f', create)+ await runCreateRequest(owners, 'another', 'f', create)+ expect(create).toHaveBeenCalledTimes(3)+ })+})diff --git a/src/core/task/create-request-id.ts b/src/core/task/create-request-id.tsnew file mode 100644index 00000000..ab4b7c8f--- /dev/null+++ b/src/core/task/create-request-id.ts@@ -0,0 +1,75 @@+import { createHash } from 'node:crypto'+import { AppError, ErrorCode } from '@shared/errors'+import type { TaskCreateSuccessResult } from '@shared/schemas/add-task'+import type { DownloadTask } from '@shared/types/task'++interface TaskOwners {+ getAll(): DownloadTask[]+}+export interface CreateRequestReceipt {+ createRequestId: string+ createRequestFingerprint: string+}+const pending = new WeakMap<+ TaskOwners,+ Map<string, { fingerprint: string; result: Promise<TaskCreateSuccessResult> }>+>()++export function createRequestFingerprint(request: unknown): string {+ return createHash('sha256').update(JSON.stringify(request)).digest('hex')+}++/** Deterministic UUIDv8 so a remote client's retry survives a host restart. */+export function scopedCreateRequestId(client: string, key: string): string {+ const bytes = createHash('sha256')+ .update(JSON.stringify(['mdxp.download/add', client, key]))+ .digest()+ .subarray(0, 16)+ bytes[6] = (bytes[6] & 0x0f) | 0x80+ bytes[8] = (bytes[8] & 0x3f) | 0x80+ const hex = bytes.toString('hex')+ return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`+}++/** Coalesce concurrent sends; the task graph retains receipts across a host restart. */+export function runCreateRequest(+ owners: TaskOwners,+ id: string | undefined,+ fingerprint: string,+ create: () => Promise<TaskCreateSuccessResult>+): Promise<TaskCreateSuccessResult> {+ if (!id) return create()+ let cache = pending.get(owners)+ if (!cache) {+ cache = new Map()+ pending.set(owners, cache)+ }+ const conflict = () =>+ new AppError(+ ErrorCode.IpcInvalidPayload,+ 'Create request ID was reused with different input'+ )+ const known = cache.get(id)+ if (known)+ return known.fingerprint === fingerprint+ ? known.result+ : Promise.reject(conflict())+ for (const task of owners.getAll()) {+ const receipt = task.instances.find(+ (instance) => instance.payload?.createRequestId === id+ )?.payload+ if (!receipt) continue+ if (receipt.createRequestFingerprint !== fingerprint)+ return Promise.reject(conflict())+ return Promise.resolve({+ outcome: 'reused',+ taskId: task.id,+ gid: task.engineTaskId || task.id,+ })+ }+ const result = Promise.resolve().then(create)+ cache.set(id, { fingerprint, result })+ // The durable task graph owns settled receipts. Pending calls are never evicted.+ void result.finally(() => cache.delete(id)).catch(() => undefined)+ return result+}diff --git a/src/core/task/create-task-handler.test.ts b/src/core/task/create-task-handler.test.tsindex 1c4ba5b2..2c1c1274 100644--- a/src/core/task/create-task-handler.test.ts+++ b/src/core/task/create-task-handler.test.ts@@ -130,6 +130,85 @@ function httpRequest() {}}+describe('source admission before side effects', () => {+ it.each([+ 'https:example.test/a',+ 'https://example.test/a\\b',+ 'https://example.test/a%ZZ',+ 'https://user:[email protected]/a',+ 'https://example.test/a\tb',+ 'sftp://example.test/a',+ 'ftps://example.test/a',+ ])(+ 'rejects %s without plugin, directory, probe or engine work',+ async (uri) => {+ const wait = vi.fn(async () => {})+ const prepare = vi.fn(async (dir: string) => dir)+ const deps = makeDeps({+ waitForEngineReady: wait,+ prepareSaveDir: prepare,+ })+ const { addUri, pick, add } = deps+ const plugin = vi.fn()+ const probe = vi.fn()+ deps.orchestrator = { runBeforeCreateHttp: plugin } as never+ deps.directResourceValidator = { capture: probe, probe }+ await expect(+ handleCreateTask({ ...httpRequest(), uris: [uri] }, deps)+ ).rejects.toMatchObject({+ code: ErrorCode.TaskSourceInvalid,+ details: { stage: 'input', index: 0 },+ })+ for (const fn of [+ wait,+ prepare,+ pick,+ plugin,+ probe,+ mkdirMock,+ addUri,+ add,+ ])+ expect(fn).not.toHaveBeenCalled()+ }+ )++ it('routes FTP to the FTP task type and skips HTTP plugins and probes', async () => {+ const deps = makeDeps()+ const { addUri, add } = deps+ const plugin = vi.fn()+ const probe = vi.fn()+ const resolve = vi.fn()+ deps.orchestrator = { runBeforeCreateHttp: plugin } as never+ deps.directResourceValidator = { capture: probe, probe }+ deps.resolveToMux = resolve+ await handleCreateTask(+ { ...httpRequest(), uris: ['ftp://example.test/archive.zip'] },+ deps+ )+ expect(addUri).toHaveBeenCalledWith(+ ['ftp://example.test/archive.zip'],+ expect.objectContaining({ dir: '/d' })+ )+ expect(addUri.mock.calls[0][1]).not.toHaveProperty('header')+ expect(add.mock.calls[0][0]).toMatchObject({ type: TaskType.Ftp })+ for (const fn of [plugin, probe, resolve]) expect(fn).not.toHaveBeenCalled()+ })++ it('reuses a persisted receipt even when the prepared directory differs from the request', async () => {+ const deps = makeDeps({ prepareSaveDir: async () => '/resolved-dir' })+ const { addUri, add } = deps+ const tasks: DownloadTask[] = []+ vi.mocked(deps.taskManager.getAll).mockImplementation(() => tasks)+ add.mockImplementation((task) => tasks.push(task))+ const request = { ...httpRequest(), requestId: crypto.randomUUID() }+ const first = await handleCreateTask(request, deps)+ const second = await handleCreateTask(request, deps)+ expect(second).toMatchObject({ outcome: 'reused', taskId: first.taskId })+ expect(addUri).toHaveBeenCalledOnce()+ })+})+function makeDeps(overrides: DepOverrides = {}): Deps & {addUri: ReturnType<typeof vi.fn>addUriWithCookies: ReturnType<typeof vi.fn>@@ -537,7 +616,7 @@ describe('handleCreateTask', () => {}})- it('redacts plugin-rewritten URIs without reducing the result to a count', async () => {+ it('logs plugin attribution and URI counts without exposing rewritten targets', async () => {const rewrittenSecret = 'REWRITTEN_URI_SECRET_753'const orchestrator = {runBeforeCreateHttp: vi.fn().mockResolvedValue({@@ -578,7 +657,7 @@ describe('handleCreateTask', () => {(call) => call[1] === 'beforeCreate hook chain result')expect(resultLog?.[0]).toMatchObject({- rewrittenUris: ['https://cdn.example/file.zip'],+ rewrittenUriCount: 1,contributors: { uris: 'plugin-rewriter' },})const task = lastAddedTask(deps)@@ -1026,7 +1105,10 @@ describe('handleCreateTask', () => {const result = await handleCreateTask({type: 'bt',- payload: { kind: 'magnet', uri: 'magnet:?xt=urn:btih:x' },+ payload: {+ kind: 'magnet',+ uri: 'magnet:?xt=urn:btih:a03e3f9a05341aa336e9d9d3f06b33cddafe0bdc',+ },dlLimit: 1_000_000,ulLimit: 512_000,selectedFiles: [0],@@ -1038,7 +1120,7 @@ describe('handleCreateTask', () => {expect(result.gid).toMatch(/^[0-9a-f]{16}$/)expect(typeof result.taskId).toBe('string')expect(deps.addUri).toHaveBeenCalledWith(- ['magnet:?xt=urn:btih:x'],+ ['magnet:?xt=urn:btih:a03e3f9a05341aa336e9d9d3f06b33cddafe0bdc'],expect.any(Object))const [, options] = deps.addUri.mock.calls[0]@@ -1147,7 +1229,7 @@ describe('handleCreateTask download paths', () => {type: 'bt',payload: {kind: 'magnet',- uri: 'magnet:?xt=urn:btih:deadbeef&dn=Ubuntu%2024.04',+ uri: 'magnet:?xt=urn:btih:a03e3f9a05341aa336e9d9d3f06b33cddafe0bdc&dn=Ubuntu%2024.04',},selectedFiles: [0],saveDir: '/d',@@ -1782,7 +1864,7 @@ describe('handleCreateTask mkdir target by task type', () => {type: 'bt',payload: {kind: 'magnet',- uri: 'magnet:?xt=urn:btih:deadbeef&dn=Ubuntu',+ uri: 'magnet:?xt=urn:btih:a03e3f9a05341aa336e9d9d3f06b33cddafe0bdc&dn=Ubuntu',},selectedFiles: [0],saveDir: '/d',@@ -2319,7 +2401,10 @@ describe('handleCreateTask plugin-hook chain (Plan C / T15)', () => {makeChainCommit({ uris: [uri], uriContributor: 'plugin-a' })),})- ).rejects.toMatchObject({ code: ErrorCode.TaskCreateFailed })+ ).rejects.toMatchObject({+ code: ErrorCode.TaskSourceInvalid,+ details: { stage: 'plugin' },+ })expect(deps.addUri).not.toHaveBeenCalled()expect(deps.reserveEngineTaskId).not.toHaveBeenCalled()})@@ -2846,7 +2931,10 @@ describe('handleCreateTask mux pre-resolve seam', () => {await handleCreateTask({type: 'bt',- payload: { kind: 'magnet', uri: 'magnet:?xt=urn:btih:abc&dn=Test' },+ payload: {+ kind: 'magnet',+ uri: 'magnet:?xt=urn:btih:a03e3f9a05341aa336e9d9d3f06b33cddafe0bdc&dn=Test',+ },selectedFiles: [],saveDir: '/d',},diff --git a/src/core/task/create-task-handler.ts b/src/core/task/create-task-handler.tsindex 3824cdf4..6b1d411a 100644--- a/src/core/task/create-task-handler.ts+++ b/src/core/task/create-task-handler.ts@@ -71,6 +71,11 @@ import {shouldPrioritizeBtPreviewPieces,UnsafeTorrentPathError,} from './bt-storage-layout'+import {+ type CreateRequestReceipt,+ createRequestFingerprint,+ runCreateRequest,+} from './create-request-id'import {buildDirectReplayRecipe,type DirectReplayRecipe,@@ -85,6 +90,12 @@ import {} from './direct-resource-validator'import type { FinalNamePicker } from './final-name-picker'import { toTempPath } from './paths'+import {+ admitDownloadSources,+ admitHttpSource,+ admitTaskCreateRequest,+ DownloadSourceError,+} from './source-admission'import type { TaskManager } from './task-manager'import type { TorrentMetaStore } from './torrent-meta-store'@@ -210,6 +221,10 @@ export interface CreateTaskOptions {extraEngineOptions?: Record<string, string | string[]>}+type AdmittedCreateOptions = CreateTaskOptions & {+ receipt?: CreateRequestReceipt+}+/*** Create a new download task. Side effects, in order:* 1. Resolve `finalName` via FinalNamePicker (collision-safe).@@ -233,6 +248,42 @@ export async function handleCreateTask(rawRequest: unknown,deps: CreateTaskDeps,opts: CreateTaskOptions = {}+): Promise<TaskCreateSuccessResult> {+ const request = admitTaskCreateRequest(rawRequest)+ if (request.type === 'http' && request.uris[0].startsWith('ftp:')) {+ const reason = !deps.adapter.getCapabilities().ftp+ ? 'unsupportedProtocol'+ : opts.cookies?.length ||+ Object.keys(opts.extraEngineOptions ?? {}).length+ ? 'unsupportedRequestOptions'+ : null+ if (reason)+ throw new DownloadSourceError({+ stage: 'input',+ index: 0,+ diagnostic: { reason, start: 0, end: 0 },+ })+ }+ const fingerprint = createRequestFingerprint({ request, opts })+ const receipt =+ request.type === 'http' && request.requestId+ ? {+ createRequestId: request.requestId,+ createRequestFingerprint: fingerprint,+ }+ : undefined+ return runCreateRequest(+ deps.taskManager,+ request.type === 'http' ? request.requestId : undefined,+ fingerprint,+ () => createAdmittedTask(request, deps, { ...opts, receipt })+ )+}++async function createAdmittedTask(+ rawRequest: unknown,+ deps: CreateTaskDeps,+ opts: AdmittedCreateOptions): Promise<TaskCreateSuccessResult> {const parsed = taskCreateRequestSchema.safeParse(rawRequest)if (parsed.success && parsed.data.type === 'http') {@@ -246,7 +297,6 @@ export async function handleCreateTask(// Keep a runtime guard for untyped composition code: missing policy// injection must disable metadata I/O instead of consulting newer,// potentially unapplied SettingsManager values.- assertHttpTaskSourceAdmission(parsed.data.uris)const requestedDir =parsed.data.saveDir || deps.settingsManager.getApp().defaultSaveDirconst preparedDir = deps.prepareSaveDir@@ -320,7 +370,7 @@ export async function handleCreateTask(async function handleCreateTaskUnderAdmission(rawRequest: unknown,deps: CreateTaskDeps,- opts: CreateTaskOptions = {},+ opts: AdmittedCreateOptions = {},appliedProxySnapshot?: AppliedDownloadProxySnapshot,assertAppliedProxyCurrent?: () => void,preparedSaveDir?: string@@ -337,7 +387,12 @@ async function handleCreateTaskUnderAdmission(const appSettings = deps.settingsManager.getApp()const engineSettings = deps.settingsManager.getEngine()- if (req.type === 'http') assertHttpTaskSourceAdmission(req.uris)+ if (req.type === 'http')+ req.uris = admitDownloadSources(req.uris, 'input', [+ 'http',+ 'https',+ 'ftp',+ ]).map((source) => source.sourceUrl)const requestedSaveDir = req.saveDir || appSettings.defaultSaveDirconst effectiveSaveDir =@@ -532,7 +587,23 @@ async function handleCreateTaskUnderAdmission(return deps.adapter.createDownload(params)}- if (req.type === 'http') {+ if (req.type === 'http' && req.uris[0].startsWith('ftp:')) {+ directReplay = buildDirectReplayRecipe({+ connections: req.connections,+ proxy: req.proxy,+ })+ canonicalUris = admitDownloadSources(req.uris, 'input', ['ftp']).map(+ (source) => source.requestUrl+ )+ dispatchEngine = dispatchCreateDownload({+ uris: canonicalUris,+ saveDir: effectiveSaveDir,+ filename: `${finalName}${INCOMPLETE_SUFFIX}`,+ performanceProfile: engineSettings.performanceProfile,+ connections: req.connections,+ proxy: req.proxy,+ })+ } else if (req.type === 'http') {const clampedConnections =req.connections !== undefined? Math.min(req.connections, engineSettings.maxConnectionPerServer)@@ -617,13 +688,14 @@ async function handleCreateTaskUnderAdmission(taskId,saveDir: effectiveSaveDir,finalName: muxFinalName,- videoUrl: muxResult.videoUrl,- audioUrl: muxResult.audioUrl,+ videoUrl: admitHttpSource(muxResult.videoUrl),+ audioUrl: admitHttpSource(muxResult.audioUrl),sanitizedHeaders,container: muxResult.container,// Desktop path: no extension session context; sourceMeta is null.// MediaTaskCoordinator accepts SourceMeta (= BridgeSourceMeta | null).sourceMeta: null,+ receipt: opts.receipt,}const muxDispatchResult = await deps.dispatchMux(adaptedMux)return {@@ -647,7 +719,7 @@ async function handleCreateTaskUnderAdmission(taskId,hasOrchestrator: Boolean(deps.orchestrator),reqType: req.type,- uris: req.uris,+ uriCount: req.uris.length,},'beforeCreate hook chain pre-check')@@ -672,7 +744,9 @@ async function handleCreateTaskUnderAdmission({taskId,aborted: result.aborted === true,- rewrittenUris: result.aborted ? undefined : result.final.uris,+ rewrittenUriCount: result.aborted+ ? undefined+ : result.final.uris.length,contributors: result.aborted ? undefined : result.contributors,},'beforeCreate hook chain result'@@ -699,7 +773,10 @@ async function handleCreateTaskUnderAdmission(// Hook outputs are task sources, not plugin HTTP requests. Re-run the// same source policy as user input; hostPermissions never authorize an// otherwise invalid or credential-bearing download target.- assertHttpTaskSourceAdmission(params.uris)+ params.uris = admitDownloadSources(params.uris, 'plugin', [+ 'http',+ 'https',+ ]).map((source) => source.requestUrl)if (result.final.headers.length > 0) {params.headers = Object.fromEntries(result.final.headers.map((h) => [h.name, h.value])@@ -737,6 +814,10 @@ async function handleCreateTaskUnderAdmission(const ambientMetadataProfile = metadataHeadersSupported? resolveDirectResourceMetadataProfile(deps.adapter): null+ params.uris = admitDownloadSources(params.uris, 'plugin', [+ 'http',+ 'https',+ ]).map((source) => source.requestUrl)const metadataRequestProfile = canApplyDirectResourceMetadataProfile(params,ambientMetadataProfile@@ -937,6 +1018,13 @@ async function handleCreateTaskUnderAdmission(updatedAt: now,}+ if (opts.receipt) {+ primaryInstance.payload = {+ ...primaryInstance.payload,+ ...opts.receipt,+ }+ }+const task: DownloadTask = makeDownloadTask({id: taskId,engineTaskId: gid,@@ -1109,7 +1197,8 @@ async function handleCreateTaskUnderAdmission(// ─── Helpers ──────────────────────────────────────────────────function deriveTaskType(req: TaskCreateRequest): TaskType {- if (req.type === 'http') return TaskType.Http+ if (req.type === 'http')+ return req.uris[0]?.startsWith('ftp:') ? TaskType.Ftp : TaskType.Httpreturn req.payload.kind === 'magnet' ? TaskType.Magnet : TaskType.Bt}@@ -1251,51 +1340,6 @@ function assertSupportedHttpTaskProxy(proxy: string | undefined): void {)}-function assertHttpTaskSourceAdmission(uris: readonly string[]): void {- if (uris.length === 0) {- throw new AppError(ErrorCode.TaskCreateFailed, 'Task source is required')- }- for (const rawUri of uris) {- let uri: URL- try {- uri = new URL(rawUri)- } catch {- throw new AppError(- ErrorCode.TaskCreateFailed,- 'Task source URL is invalid'- )- }- if (uri.protocol !== 'http:' && uri.protocol !== 'https:') {- throw new AppError(- ErrorCode.TaskCreateFailed,- 'Task source URL must use HTTP or HTTPS'- )- }- if (- uri.username.length > 0 ||- uri.password.length > 0 ||- rawAuthorityContainsUserInfo(rawUri)- ) {- throw new AppError(- ErrorCode.TaskCreateFailed,- 'Task source URL must not contain credentials'- )- }- }-}--function rawAuthorityContainsUserInfo(rawUri: string): boolean {- const schemeEnd = rawUri.indexOf('://')- if (schemeEnd < 0) return false- const authorityStart = schemeEnd + 3- let authorityEnd = rawUri.length- for (const separator of ['/', '?', '#', '\\']) {- const index = rawUri.indexOf(separator, authorityStart)- if (index >= 0 && index < authorityEnd) authorityEnd = index- }- return rawUri.slice(authorityStart, authorityEnd).includes('@')-}-function uriBasename(uri: string | undefined): string | null {if (!uri) return nulltry {diff --git a/src/core/task/direct-resource-validator.ts b/src/core/task/direct-resource-validator.tsindex d50d9dbd..7de57aec 100644--- a/src/core/task/direct-resource-validator.ts+++ b/src/core/task/direct-resource-validator.ts@@ -3,6 +3,7 @@ import {INCOMPLETE_SUFFIX,MAX_DEDUP_ATTEMPTS,} from '@shared/constants/incomplete'+import { analyzeDownloadSource } from '@shared/lib/download-source'import type { DirectResourceValidator } from '@shared/schemas/direct-replay-recipe'import type { EngineFeatureReport } from '@shared/types/engine'import type { Dispatcher } from 'undici'@@ -596,10 +597,11 @@ export function hasLikelyFileExtension(filename: string | null): boolean {function parseHttpUrl(uri: string): URL | null {try {- const url = new URL(uri)+ const source = analyzeDownloadSource(uri, ['http', 'https'])+ if (source.status !== 'accepted') return null+ const url = new URL(source.requestUrl)if (hasC0SpaceOrDel(uri) ||- uri.includes('\\') ||decideAria2ProxyRoute(uri) === 'unsupported' ||requestUrlPreservingAuthority(uri, url) === null) {@@ -624,7 +626,11 @@ function requestUrlPreservingAuthority(if (!authority || suffix === null) return nullconst requestSuffix =suffix === '' || suffix.startsWith('?') ? `/${suffix}` : suffix- if (requestSuffix !== `${normalized.pathname}${normalized.search}`) {+ const normalizedSuffix = `${normalized.pathname}${normalized.search}`+ if (+ requestSuffix !== normalizedSuffix &&+ !(normalized.search === '' && requestSuffix === `${normalizedSuffix}?`)+ ) {return null}return `${normalized.protocol}//${authority}${requestSuffix}`diff --git a/src/core/task/download-source.integration.test.ts b/src/core/task/download-source.integration.test.tsnew file mode 100644index 00000000..988c2fc9--- /dev/null+++ b/src/core/task/download-source.integration.test.ts@@ -0,0 +1,182 @@+import { mkdtemp, readFile, rm } from 'node:fs/promises'+import { createServer, type Server } from 'node:http'+import { createServer as createTcpServer, type Socket } from 'node:net'+import { tmpdir } from 'node:os'+import path from 'node:path'+import { analyzeDownloadSource } from '@shared/lib/download-source'+import {+ type Aria2Handle,+ bundledAria2Exists,+ canBindLoopbackTcp,+ connectAdapter,+ spawnAria2ForTest,+} from '@test-utils/aria2'+import { afterAll, beforeAll, describe, expect, it } from 'vitest'+import { DirectResourceValidatorService } from './direct-resource-validator'++describe.skipIf(!bundledAria2Exists() || !canBindLoopbackTcp())(+ 'download URL request-target parity',+ () => {+ let dir: string+ let server: Server+ let origin: string+ let engine: Aria2Handle+ let wired: Awaited<ReturnType<typeof connectAdapter>>+ const requests: string[] = []+ let count = 0++ beforeAll(async () => {+ dir = await mkdtemp(path.join(tmpdir(), 'motrix-url-parity-'))+ server = createServer((req, res) => {+ requests.push(req.url ?? '')+ res.writeHead(200, { 'content-length': '7', etag: '"fixture"' })+ res.end('fixture')+ })+ await new Promise<void>((resolve) =>+ server.listen(0, '127.0.0.1', resolve)+ )+ const address = server.address()+ if (!address || typeof address === 'string')+ throw new Error('Missing test listener')+ origin = `http://127.0.0.1:${address.port}`+ engine = await spawnAria2ForTest({ baseDir: dir })+ wired = await connectAdapter(engine)+ })++ afterAll(async () => {+ wired?.disconnect()+ await engine?.kill()+ await new Promise<void>((resolve) => server?.close(() => resolve()))+ if (dir) await rm(dir, { recursive: true, force: true })+ })++ it.each([+ [+ '/a//b?x=%2f&x=%2F&empty=&plus=+&space=%20&nested=%252F',+ '/a//b?x=%2f&x=%2F&empty=&plus=+&space=%20&nested=%252F',+ ],+ ['/file?path=one\\two&sig=%5C%25', '/file?path=one\\two&sig=%5C%25'],+ [+ '/文件?键=值&sig=%2f#preview',+ '/%E6%96%87%E4%BB%B6?%E9%94%AE=%E5%80%BC&sig=%2f',+ ],+ [+ '/encoded%2Fslash%5Ctext?x=%00%0D%0A',+ '/encoded%2Fslash%5Ctext?x=%00%0D%0A',+ ],+ ])('delivers identical bytes for %s', async (input, target) => {+ const source = analyzeDownloadSource(origin + input)+ expect(source.status).toBe('accepted')+ if (source.status !== 'accepted') return+ requests.length = 0+ const metadata = await new DirectResourceValidatorService().probe(+ source.requestUrl+ )+ expect(metadata).not.toBeNull()+ expect(requests).toEqual([target])+ requests.length = 0+ const filename = `sample-${count++}.bin`+ const gid = await wired.adapter.createDownload({+ uris: [source.requestUrl],+ saveDir: dir,+ filename,+ })+ await expect+ .poll(async () => (await wired.rpc.tellStatus(gid)).status, {+ timeout: 5000,+ })+ .toBe('complete')+ expect(requests).toEqual([target])+ expect(await readFile(path.join(dir, filename), 'utf8')).toBe('fixture')+ })++ it('downloads FTP through the bundled engine', async () => {+ const sockets = new Set<Socket>()+ let dataSocket: Socket | undefined+ const data = createTcpServer((socket) => {+ dataSocket = socket+ sockets.add(socket)+ })+ await new Promise<void>((resolve) => data.listen(0, '127.0.0.1', resolve))+ const dataAddress = data.address()+ if (!dataAddress || typeof dataAddress === 'string')+ throw new Error('Missing FTP data listener')+ const commands: string[] = []+ const control = createTcpServer((socket) => {+ sockets.add(socket)+ socket.write('220 Test FTP\r\n')+ let buffer = ''+ socket.on('data', (chunk) => {+ buffer += chunk.toString()+ for (;;) {+ const end = buffer.indexOf('\r\n')+ if (end < 0) break+ const line = buffer.slice(0, end)+ buffer = buffer.slice(end + 2)+ const command = line.split(' ')[0]+ commands.push(command)+ if (command === 'USER') socket.write('331 Password required\r\n')+ else if (command === 'PASS') socket.write('230 Logged in\r\n')+ else if (command === 'PWD') socket.write('257 "/"\r\n')+ else if (command === 'CWD')+ socket.write('250 Directory changed\r\n')+ else if (command === 'SIZE') socket.write('213 7\r\n')+ else if (command === 'MDTM') socket.write('213 20260916000000\r\n')+ else if (command === 'EPSV')+ socket.write(+ `229 Entering Extended Passive Mode (|||${dataAddress.port}|)\r\n`+ )+ else if (command === 'PASV')+ socket.write(+ `227 Entering Passive Mode (127,0,0,1,${dataAddress.port >> 8},${dataAddress.port & 255})\r\n`+ )+ else if (command === 'RETR') {+ socket.write('150 Opening data connection\r\n')+ dataSocket?.end('fixture', () =>+ socket.write('226 Transfer complete\r\n')+ )+ } else if (command === 'QUIT') socket.end('221 Goodbye\r\n')+ else socket.write('200 OK\r\n')+ }+ })+ })+ await new Promise<void>((resolve) =>+ control.listen(0, '127.0.0.1', resolve)+ )+ try {+ const address = control.address()+ if (!address || typeof address === 'string')+ throw new Error('Missing FTP listener')+ const gid = await wired.adapter.createDownload({+ uris: [`ftp://127.0.0.1:${address.port}/fixture.bin`],+ saveDir: dir,+ filename: 'ftp.bin',+ })+ try {+ await expect+ .poll(async () => (await wired.rpc.tellStatus(gid)).status, {+ timeout: 5000,+ })+ .toBe('complete')+ } catch {+ throw new Error(+ JSON.stringify({+ commands,+ status: await wired.rpc.tellStatus(gid),+ })+ )+ }+ expect(await readFile(path.join(dir, 'ftp.bin'), 'utf8')).toBe(+ 'fixture'+ )+ expect(commands).toContain('RETR')+ } finally {+ for (const socket of sockets) socket.destroy()+ await Promise.all([+ new Promise<void>((resolve) => control.close(() => resolve())),+ new Promise<void>((resolve) => data.close(() => resolve())),+ ])+ }+ }, 15000)+ }+)diff --git a/src/core/task/media-task-coordinator.test.ts b/src/core/task/media-task-coordinator.test.tsindex aa230164..2c3a8b6a 100644--- a/src/core/task/media-task-coordinator.test.ts+++ b/src/core/task/media-task-coordinator.test.ts@@ -230,6 +230,30 @@ describe('MediaTaskCoordinator.start', () => {vi.restoreAllMocks()})+ it.each(['segment', 'init', 'key'])(+ 'rejects an invalid %s before saving or creating directories',+ async (kind) => {+ const { deps, taskManager, downloaderFakes } = makeDeps()+ const job = baseJob()+ const invalid = 'https://cdn.test/a\\b'+ if (kind === 'segment') job.video.segments[0].url = invalid+ else if (kind === 'init') job.video.init = { url: invalid }+ else+ job.video.segments[0].key = {+ method: 'AES-128',+ uri: invalid,+ iv: new Uint8Array(16),+ }+ await expect(+ new MediaTaskCoordinator(deps).submit(job)+ ).rejects.toMatchObject({ code: 'TASK_SOURCE_INVALID' })+ expect(mkdirSpy).not.toHaveBeenCalled()+ expect(deps.persist).not.toHaveBeenCalled()+ expect(taskManager.getAll()).toHaveLength(0)+ expect(downloaderFakes).toHaveLength(0)+ }+ )+it('creates the output saveDir before muxing (so ffmpeg never ENOENTs)', async () => {const { deps } = makeDeps()const c = new MediaTaskCoordinator(deps)diff --git a/src/core/task/media-task-coordinator.ts b/src/core/task/media-task-coordinator.tsindex d854d97f..64acfdbe 100644--- a/src/core/task/media-task-coordinator.ts+++ b/src/core/task/media-task-coordinator.ts@@ -34,8 +34,10 @@ import {terminalSnapshotFromTask,} from './actions/shared'import { applyTerminalTransition } from './apply-terminal-transition'+import type { CreateRequestReceipt } from './create-request-id'import type { OccurrenceDispatcher } from './occurrences/occurrence-dispatcher'import { toTempPath } from './paths'+import { admitHttpSource } from './source-admission'import {applyTerminalStatusToTask,completeTaskAfterRename,@@ -50,6 +52,7 @@ const log = getLogger('media-coordinator')// ---------------------------------------------------------------------------export interface MediaJob {+ receipt?: CreateRequestReceipttaskId?: stringvideo: SegmentPlanaudio?: SegmentPlan@@ -226,6 +229,27 @@ export class MediaTaskCoordinator {taskId: string,onAccepted?: () => void): Promise<{ taskId: string }> {+ const admitPlan = (plan: SegmentPlan): SegmentPlan => {+ const admitPart = <T extends { url: string; key?: { uri: string } }>(+ part: T+ ): T => ({+ ...part,+ url: admitHttpSource(part.url),+ ...(part.key+ ? { key: { ...part.key, uri: admitHttpSource(part.key.uri) } }+ : {}),+ })+ return {+ ...plan,+ init: plan.init ? admitPart(plan.init) : undefined,+ segments: plan.segments.map(admitPart),+ }+ }+ job = {+ ...job,+ video: admitPlan(job.video),+ audio: job.audio ? admitPlan(job.audio) : undefined,+ }const now = Date.now()// Reserve the final name by creating the `.motrix` placeholder in saveDir —@@ -958,6 +982,8 @@ export class MediaTaskCoordinator {instances: TaskInstance[],now: number): DownloadTask {+ if (job.receipt && instances[0])+ instances[0].payload = { ...instances[0].payload, ...job.receipt }return makeDownloadTask({id: taskId,name: finalName,diff --git a/src/core/task/source-admission.ts b/src/core/task/source-admission.tsnew file mode 100644index 00000000..8d00a72c--- /dev/null+++ b/src/core/task/source-admission.ts@@ -0,0 +1,95 @@+import { AppError, ErrorCode } from '@shared/errors'+import { analyzeDownloadSource } from '@shared/lib/download-source'+import { taskCreateRequestSchema } from '@shared/schemas/add-task'+import {+ type AcceptedDownloadSource,+ MAX_MIRROR_URIS,+ type SourceFailure,+ type SourceProtocol,+} from '@shared/schemas/download-source'++export class DownloadSourceError extends AppError {+ constructor(public readonly details: SourceFailure) {+ super(+ ErrorCode.TaskSourceInvalid,+ `task.add.sourceErrors.${details.diagnostic.reason}`+ )+ }+}++export function admitDownloadSources(+ uris: readonly string[],+ stage: SourceFailure['stage'] = 'input',+ protocols: readonly SourceProtocol[] = ['http', 'https', 'ftp', 'magnet']+): AcceptedDownloadSource[] {+ if (uris.length === 0 || uris.length > MAX_MIRROR_URIS)+ throw new DownloadSourceError({+ stage,+ index: 0,+ diagnostic: { reason: 'tooManySources', start: 0, end: 0 },+ })+ const sources = uris.map((uri, index) => {+ const result = analyzeDownloadSource(uri, protocols)+ if (result.status !== 'accepted')+ throw new DownloadSourceError({+ stage,+ index,+ diagnostic: result.diagnostic,+ })+ return result+ })+ const family = (source: AcceptedDownloadSource) =>+ source.protocol === 'https' ? 'http' : source.protocol+ if (+ sources.some((source) => family(source) !== family(sources[0])) ||+ (sources[0].protocol === 'magnet' && sources.length !== 1)+ )+ throw new DownloadSourceError({+ stage,+ index: 0,+ diagnostic: { reason: 'mixedProtocols', start: 0, end: 0 },+ })+ return sources+}++export function admitHttpSource(+ uri: string,+ stage: SourceFailure['stage'] = 'resolution'+): string {+ return admitDownloadSources([uri], stage, ['http', 'https'])[0].requestUrl+}++export function taskCreateSourceFailure(error: unknown) {+ return error instanceof DownloadSourceError+ ? { outcome: 'invalid-source' as const, failure: error.details }+ : null+}++/** Run before plugin activation, engine readiness, and save-directory preparation. */+export function admitTaskCreateRequest(raw: unknown) {+ const parsed = taskCreateRequestSchema.safeParse(raw)+ if (!parsed.success)+ throw new AppError(+ ErrorCode.IpcInvalidPayload,+ 'Invalid task create request'+ )+ const req = parsed.data+ if (req.type === 'http') {+ req.uris = admitDownloadSources(req.uris, 'input', [+ 'http',+ 'https',+ 'ftp',+ ]).map((source) => source.sourceUrl)+ if (req.uris[0].startsWith('ftp:') && req.headers.length > 0)+ throw new DownloadSourceError({+ stage: 'input',+ index: 0,+ diagnostic: { reason: 'unsupportedRequestOptions', start: 0, end: 0 },+ })+ } else if (req.payload.kind === 'magnet') {+ req.payload.uri = admitDownloadSources([req.payload.uri], 'input', [+ 'magnet',+ ])[0].sourceUrl+ }+ return req+}diff --git a/src/core/torrent/magnet-selection-timeout.ts b/src/core/torrent/magnet-selection-timeout.tsindex 8581a946..9bcc2e08 100644--- a/src/core/torrent/magnet-selection-timeout.ts+++ b/src/core/torrent/magnet-selection-timeout.ts@@ -187,7 +187,10 @@ export class MagnetSelectionTimeout {displayName: selection.meta.name || undefined,existingTaskId: taskId,})- if (result.outcome !== 'conflict') {+ if (+ result.outcome !== 'conflict' &&+ result.outcome !== 'invalid-source'+ ) {outcome = 'started'downloadTaskId = result.taskId}diff --git a/src/core/torrent/magnet-tracker.test.ts b/src/core/torrent/magnet-tracker.test.tsindex 4703279e..3e9c1f72 100644--- a/src/core/torrent/magnet-tracker.test.ts+++ b/src/core/torrent/magnet-tracker.test.ts@@ -402,18 +402,24 @@ describe('MagnetTracker', () => {torrentParser)- await tracker.submit('magnet:?xt=urn:btih:abc123', dir)+ await tracker.submit(+ 'magnet:?xt=urn:btih:6367c48dd193d56ea7b0baad25b19455e529f5ee',+ dir+ )const metadataDir = lastMetadataDir()expect(metadataDir).not.toBe(dir)- expect(rpc.addUri).toHaveBeenCalledWith(['magnet:?xt=urn:btih:abc123'], {- 'max-file-not-found': '0',- 'bt-load-saved-metadata': 'false',- 'bt-metadata-only': 'true',- dir: metadataDir,- 'follow-torrent': 'false',- gid: expect.stringMatching(/^[a-f0-9]{16}$/),- })+ expect(rpc.addUri).toHaveBeenCalledWith(+ ['magnet:?xt=urn:btih:6367c48dd193d56ea7b0baad25b19455e529f5ee'],+ {+ 'max-file-not-found': '0',+ 'bt-load-saved-metadata': 'false',+ 'bt-metadata-only': 'true',+ dir: metadataDir,+ 'follow-torrent': 'false',+ gid: expect.stringMatching(/^[a-f0-9]{16}$/),+ }+ )})it('reuses a same-directory seed and rejects a second active directory', async () => {@@ -511,7 +517,7 @@ describe('MagnetTracker', () => {)const submitting = tracker.submit(- 'magnet:?xt=urn:btih:reserved-before-add',+ 'magnet:?xt=urn:btih:a00fc8f79a760f568d3ec349689f6e643ca1d013',dir)await addStarted@@ -547,7 +553,10 @@ describe('MagnetTracker', () => {activityRecorder)- const taskId = await tracker.submit('magnet:?xt=urn:btih:activity', dir)+ const taskId = await tracker.submit(+ 'magnet:?xt=urn:btih:0bf4170444cd473cd4066c79b80cf62ffce582d8',+ dir+ )const task = taskManager.getById(taskId)const save = db.saveTaskWithInstances as ReturnType<typeof vi.fn>@@ -601,7 +610,10 @@ describe('MagnetTracker', () => {lifecycle)- await tracker.submit('magnet:?xt=urn:btih:durable-parent', dir)+ await tracker.submit(+ 'magnet:?xt=urn:btih:6f6d3477d6434863b5951fb85c1e1e500a54fa70',+ dir+ )expect(lifecycle.parentTaskCreated).toHaveBeenCalledOnce()expect(order).toEqual([@@ -630,7 +642,10 @@ describe('MagnetTracker', () => {)await expect(- tracker.submit('magnet:?xt=urn:btih:parent-failure', dir)+ tracker.submit(+ 'magnet:?xt=urn:btih:a16da35a10b23c7916a73924ad287f46000cab0f',+ dir+ )).rejects.toThrow('parent persistence failed')const reservedGid = vi.mocked(taskManager.reserveEngineTaskId).mock@@ -660,7 +675,10 @@ describe('MagnetTracker', () => {)await expect(- tracker.submit('magnet:?xt=urn:btih:add-response-lost', dir)+ tracker.submit(+ 'magnet:?xt=urn:btih:549e00b51f7a4d4692c543d940e21810c06d155c',+ dir+ )).rejects.toThrow('rpc response lost')const requestedGid = rpc.addUri.mock.calls[0]?.[1]?.gid as string@@ -697,7 +715,10 @@ describe('MagnetTracker', () => {)await expect(- tracker.submit('magnet:?xt=urn:btih:hidden-tombstone-occurrence', dir)+ tracker.submit(+ 'magnet:?xt=urn:btih:e77f26bbac2dd08e0ea8325660915758a31d4cd9',+ dir+ )).rejects.toThrow('rpc response lost')expect(dispatch).not.toHaveBeenCalled()@@ -772,7 +793,7 @@ describe('MagnetTracker', () => {)const onError = rpc.onDownloadError.mock.calls[0][0]const taskId = await tracker.submit(- 'magnet:?xt=urn:btih:metadata-error',+ 'magnet:?xt=urn:btih:1c3829fa09c7e6d2cd049d8469d2540d2d9461db',saveDir)const gid = lastMetadataGid()@@ -828,7 +849,7 @@ describe('MagnetTracker', () => {{ runTaskMutation })const taskId = await tracker.submit(- 'magnet:?xt=urn:btih:callback-after-swap',+ 'magnet:?xt=urn:btih:de6514e24009c2cfb12b1b9e7ec711abfe24b374',saveDir)const gid = lastMetadataGid()@@ -908,7 +929,7 @@ describe('MagnetTracker', () => {torrentParser)const taskId = await tracker.submit(- 'magnet:?xt=urn:btih:stale-error-after-swap',+ 'magnet:?xt=urn:btih:de36c430bd1f6c8f7454dc9ce45e64316b10f985',saveDir)const gid = lastMetadataGid()@@ -959,7 +980,10 @@ describe('MagnetTracker', () => {taskManager,torrentParser)- await tracker.submit('magnet:?xt=urn:btih:duplicate-complete', saveDir)+ await tracker.submit(+ 'magnet:?xt=urn:btih:c01805e3b6a30a790b2e763d11cc302fa3a66d25',+ saveDir+ )const gid = lastMetadataGid()await writeTorrentFixture(lastMetadataDir())eventBus.emit.mockClear()@@ -999,7 +1023,7 @@ describe('MagnetTracker', () => {{ runExclusivePersistence })const taskId = await tracker.submit(- 'magnet:?xt=urn:btih:queued-autosave',+ 'magnet:?xt=urn:btih:12683da484f1d35228941df8350c968dd94b2548',saveDir)const gid = lastMetadataGid()@@ -1062,10 +1086,14 @@ describe('MagnetTracker', () => {submittedAt: 1,}- const taskId = await tracker.submit('magnet:?xt=urn:btih:abc123', dir, {- source: 'bridge',- sourceMeta,- })+ const taskId = await tracker.submit(+ 'magnet:?xt=urn:btih:6367c48dd193d56ea7b0baad25b19455e529f5ee',+ dir,+ {+ source: 'bridge',+ sourceMeta,+ }+ )const pair = db.getTask(taskId)expect(pair?.task.source).toBe('bridge')@@ -1083,7 +1111,10 @@ describe('MagnetTracker', () => {torrentParser)- const taskId = await tracker.submit('magnet:?xt=urn:btih:abc123', dir)+ const taskId = await tracker.submit(+ 'magnet:?xt=urn:btih:6367c48dd193d56ea7b0baad25b19455e529f5ee',+ dir+ )const pair = db.getTask(taskId)expect(pair?.task.source).toBe('user')@@ -1103,12 +1134,18 @@ describe('MagnetTracker', () => {torrentParser)- await tracker.submit('magnet:?xt=urn:btih:abc123', '/downloads')+ await tracker.submit(+ 'magnet:?xt=urn:btih:6367c48dd193d56ea7b0baad25b19455e529f5ee',+ '/downloads'+ )- expect(rpc.addUri).toHaveBeenCalledWith(['magnet:?xt=urn:btih:abc123'], {- dir: '/downloads',- 'max-file-not-found': '0',- })+ expect(rpc.addUri).toHaveBeenCalledWith(+ ['magnet:?xt=urn:btih:6367c48dd193d56ea7b0baad25b19455e529f5ee'],+ {+ dir: '/downloads',+ 'max-file-not-found': '0',+ }+ )})// ── 4. onComplete for known gid ──────────────────────────────@@ -1486,7 +1523,7 @@ describe('MagnetTracker', () => {)const onComplete = rpc.onDownloadComplete.mock.calls[0][0]const taskId = await tracker.submit(- 'magnet:?xt=urn:btih:result-purge-failed',+ 'magnet:?xt=urn:btih:5059f80d16ae552ccb397a269bb49d015a3c6388',saveDir)await writeTorrentFixture(lastMetadataDir())@@ -1556,7 +1593,7 @@ describe('MagnetTracker', () => {)const onComplete = rpc.onDownloadComplete.mock.calls[0][0]const taskId = await tracker.submit(- 'magnet:?xt=urn:btih:task-updated-throws',+ 'magnet:?xt=urn:btih:60cb4b775789a47367611766baad373e8dbf5c90',saveDir)await writeTorrentFixture(lastMetadataDir())@@ -1609,7 +1646,7 @@ describe('MagnetTracker', () => {)const onComplete = rpc.onBtDownloadComplete.mock.calls[0][0]const taskId = await tracker.submit(- 'magnet:?xt=urn:btih:file-selection-throws',+ 'magnet:?xt=urn:btih:19be438596485c6f3ff67002a7046ae2dbabd17b',saveDir)await writeTorrentFixture(lastMetadataDir())@@ -1659,7 +1696,7 @@ describe('MagnetTracker', () => {)const onComplete = rpc.onDownloadComplete.mock.calls[0][0]const taskId = await tracker.submit(- 'magnet:?xt=urn:btih:read-failed',+ 'magnet:?xt=urn:btih:5ab7152919bbbeea66421c7b727d0dc803b18393',saveDir)eventBus.emit.mockClear()@@ -1717,7 +1754,7 @@ describe('MagnetTracker', () => {)const onComplete = rpc.onBtDownloadComplete.mock.calls[0][0]const taskId = await tracker.submit(- 'magnet:?xt=urn:btih:parse-failed',+ 'magnet:?xt=urn:btih:42f497d831126938a5b45e9b2e29bcb2bf4f652e',saveDir)await writeTorrentFixture(lastMetadataDir())@@ -1794,7 +1831,10 @@ describe('MagnetTracker', () => {)const onError = rpc.onDownloadError.mock.calls[0][0]- const taskId = await tracker.submit('magnet:?xt=urn:btih:abc123', dir)+ const taskId = await tracker.submit(+ 'magnet:?xt=urn:btih:6367c48dd193d56ea7b0baad25b19455e529f5ee',+ dir+ )const gid = lastMetadataGid()eventBus.emit.mockClear()@@ -1842,7 +1882,10 @@ describe('MagnetTracker', () => {)const onError = rpc.onDownloadError.mock.calls[0][0]- const taskId = await tracker.submit('magnet:?xt=urn:btih:abc123', dir)+ const taskId = await tracker.submit(+ 'magnet:?xt=urn:btih:6367c48dd193d56ea7b0baad25b19455e529f5ee',+ dir+ )const gid = lastMetadataGid()await onError({ gid })@@ -1881,7 +1924,7 @@ describe('MagnetTracker', () => {const onError = rpc.onDownloadError.mock.calls[0][0]const taskId = await tracker.submit(- 'magnet:?xt=urn:btih:visible-after-restart',+ 'magnet:?xt=urn:btih:6166f8bf4cfb6b5051ab6724c37e0043c7535593',dir)const gid = lastMetadataGid()@@ -1925,7 +1968,10 @@ describe('MagnetTracker', () => {taskManager,torrentParser)- const taskId = await tracker.submit('magnet:?xt=urn:btih:slow-peers', dir)+ const taskId = await tracker.submit(+ 'magnet:?xt=urn:btih:5317e7774679644353d9f5deecd44bbeacffb344',+ dir+ )await vi.advanceTimersByTimeAsync(120_000)expect(db.getTask(taskId)?.task.aggStatus).toBe(TaskStatus.FetchingMetadata)@@ -1958,7 +2004,10 @@ describe('MagnetTracker', () => {torrentParser)- const taskId = await tracker.submit('magnet:?xt=urn:btih:abc123', dir)+ const taskId = await tracker.submit(+ 'magnet:?xt=urn:btih:6367c48dd193d56ea7b0baad25b19455e529f5ee',+ dir+ )const gid = lastMetadataGid()eventBus.emit.mockClear()@@ -1997,7 +2046,10 @@ describe('MagnetTracker', () => {torrentParser)- const taskId = await tracker.submit('magnet:?xt=urn:btih:abc', dir)+ const taskId = await tracker.submit(+ 'magnet:?xt=urn:btih:a9993e364706816aba3e25717850c26c9cd0d89d',+ dir+ )const gid = lastMetadataGid()expect(taskId).toMatch(/.+/)@@ -2034,7 +2086,10 @@ describe('MagnetTracker', () => {torrentParser)- await tracker.submit('magnet:?xt=urn:btih:emit', dir)+ await tracker.submit(+ 'magnet:?xt=urn:btih:2e96e89125f4c1aef797410a4bfdb32c0632ef0c',+ dir+ )const emit = (eventBus.emit as ReturnType<typeof vi.fn>).mock.calls.find((c) => c[0] === Events.TaskUpdated@@ -2062,7 +2117,10 @@ describe('MagnetTracker', () => {taskManager,torrentParser)- await tracker.submit('magnet:?xt=urn:btih:abc', dir)+ await tracker.submit(+ 'magnet:?xt=urn:btih:a9993e364706816aba3e25717850c26c9cd0d89d',+ dir+ )expect(tracker.observe({ gid: 'g-meta-1', status: 'active' } as never)@@ -2095,7 +2153,10 @@ describe('MagnetTracker', () => {taskManager,torrentParser)- const taskId = await tracker.submit('magnet:?xt=urn:btih:owner-heal', dir)+ const taskId = await tracker.submit(+ 'magnet:?xt=urn:btih:455bec88b6227cfd291f503a71e793a90a571e4c',+ dir+ )const metadataTask = taskManager.getById(taskId)if (!metadataTask) throw new Error('metadata task fixture missing')@@ -2103,7 +2164,7 @@ describe('MagnetTracker', () => {taskId,instanceId: `meta:${taskId}`,gid: 'g-bt-committed',- magnetUri: 'magnet:?xt=urn:btih:owner-heal',+ magnetUri: 'magnet:?xt=urn:btih:455bec88b6227cfd291f503a71e793a90a571e4c',saveDir: '/Downloads',metadataDir: '/Downloads/resolved.motrix',torrentMetaPath: '/torrent-meta/owner-heal.torrent',@@ -2149,7 +2210,10 @@ describe('MagnetTracker', () => {torrentParser)- const taskId = await tracker.submit('magnet:?xt=urn:btih:abc', dir)+ const taskId = await tracker.submit(+ 'magnet:?xt=urn:btih:a9993e364706816aba3e25717850c26c9cd0d89d',+ dir+ )await tracker.cancel(taskId)// Regression guard for Codex finding #2: cleanupCacheEntry must@@ -2180,7 +2244,10 @@ describe('MagnetTracker', () => {torrentParser)- const taskId = await tracker.submit('magnet:?xt=urn:btih:keep', dir)+ const taskId = await tracker.submit(+ 'magnet:?xt=urn:btih:1264bdfe5ff3215cf6abac2152fff607f7dc78dc',+ dir+ )expect(db.getTask(taskId)).not.toBeNull()await tracker.cancel(taskId, { deleteTaskRow: false })@@ -2212,7 +2279,10 @@ describe('MagnetTracker', () => {torrentParser)- await tracker.submit('magnet:?xt=urn:btih:def', dir)+ await tracker.submit(+ 'magnet:?xt=urn:btih:589c22335a381f122d129225f5c0ba3056ed5811',+ dir+ )await vi.advanceTimersByTimeAsync(1500)expect(rpc.forceRemove).toHaveBeenCalledWith('g-meta-timeout')@@ -2237,7 +2307,7 @@ describe('MagnetTracker', () => {)const taskId = await tracker.submit(- 'magnet:?xt=urn:btih:retry-timeout',+ 'magnet:?xt=urn:btih:43efb4f44e8b1198387ddd79269a2dbdece78bec',dir)const firstOptions = rpc.addUri.mock.calls[0][1]@@ -2296,7 +2366,7 @@ describe('MagnetTracker', () => {torrentParser)const taskId = await tracker.submit(- 'magnet:?xt=urn:btih:retry-restart',+ 'magnet:?xt=urn:btih:61b7491a0284c6e93550066f9f0854b94b92670d',dir)await vi.advanceTimersByTimeAsync(1_000)@@ -2340,7 +2410,7 @@ describe('MagnetTracker', () => {)const taskId = await tracker.submit(- 'magnet:?xt=urn:btih:retry-cleanup-pending',+ 'magnet:?xt=urn:btih:9f8696ac773d190b8e35a5da7ce7d52115719960',dir)await vi.advanceTimersByTimeAsync(1_000)@@ -2364,7 +2434,10 @@ describe('MagnetTracker', () => {)const onError = rpc.onDownloadError.mock.calls[0][0]- await tracker.submit('magnet:?xt=urn:btih:err', dir)+ await tracker.submit(+ 'magnet:?xt=urn:btih:eb35c321d6997c344882962b8aa1cd0939b123e1',+ dir+ )await onError({ gid: 'g-meta-err' })expect(rpc.forceRemove).toHaveBeenCalledWith('g-meta-err')@@ -2393,7 +2466,10 @@ describe('MagnetTracker', () => {torrentParser)- const taskId = await tracker.submit('magnet:?xt=urn:btih:flaky', dir)+ const taskId = await tracker.submit(+ 'magnet:?xt=urn:btih:0612bcf5b16a1ec368ef4ebb92d6be2f7040260b',+ dir+ )await tracker.cancel(taskId)expect(rpc.forceRemove).toHaveBeenCalledWith('g-meta-flaky')@@ -2418,7 +2494,7 @@ describe('MagnetTracker', () => {)const taskId = await tracker.submit(- 'magnet:?xt=urn:btih:stopped-result',+ 'magnet:?xt=urn:btih:437ce18345723780a1b100f9b6420946459e5f6d',dir)await expect(tracker.cancel(taskId)).resolves.toBe('removed')@@ -2449,7 +2525,10 @@ describe('MagnetTracker', () => {torrentParser)- const taskId = await tracker.submit('magnet:?xt=urn:btih:gone', dir)+ const taskId = await tracker.submit(+ 'magnet:?xt=urn:btih:a6dfdeaa3a44a4c52d44284847d7160892b4017e',+ dir+ )await tracker.cancel(taskId)expect(@@ -2476,7 +2555,10 @@ describe('MagnetTracker', () => {torrentParser)- const taskId = await tracker.submit('magnet:?xt=urn:btih:proxy', dir)+ const taskId = await tracker.submit(+ 'magnet:?xt=urn:btih:d799bae6088a90139b415fccb011d540531df83b',+ dir+ )await tracker.cancel(taskId)// Cache entry preserved because the failure was classified as@@ -2505,7 +2587,10 @@ describe('MagnetTracker', () => {torrentParser)- const taskId = await tracker.submit('magnet:?xt=urn:btih:real', dir)+ const taskId = await tracker.submit(+ 'magnet:?xt=urn:btih:c9c64e071d2853bc7906c017a231ad1cc46ab630',+ dir+ )await tracker.cancel(taskId)expect(@@ -2532,7 +2617,10 @@ describe('MagnetTracker', () => {torrentParser)- const taskId = await tracker.submit('magnet:?xt=urn:btih:recover', dir)+ const taskId = await tracker.submit(+ 'magnet:?xt=urn:btih:55bc5de4ad739fc0c332d826cb21bab6c0fd28b7',+ dir+ )await tracker.cancel(taskId)// First attempt: cache still present (transient failure).@@ -2576,7 +2664,10 @@ describe('MagnetTracker', () => {lifecycle)- const taskId = await tracker.submit('magnet:?xt=urn:btih:stuck', dir)+ const taskId = await tracker.submit(+ 'magnet:?xt=urn:btih:cfb18e81efbda9473cefbd150d9be1eb0ac7840b',+ dir+ )await tracker.cancel(taskId)await vi.advanceTimersByTimeAsync(400_000)@@ -2627,7 +2718,10 @@ describe('MagnetTracker', () => {torrentParser)- const taskId = await tracker.submit('magnet:?xt=urn:btih:revive', dir)+ const taskId = await tracker.submit(+ 'magnet:?xt=urn:btih:97dd8cdfab89963b2a8c0116f6a21bf32932860e',+ dir+ )await tracker.cancel(taskId)await vi.advanceTimersByTimeAsync(400_000)@@ -2675,7 +2769,10 @@ describe('MagnetTracker', () => {torrentParser)- const taskId = await tracker.submit('magnet:?xt=urn:btih:userdel', dir)+ const taskId = await tracker.submit(+ 'magnet:?xt=urn:btih:fe6fbe03b2e72b3e7477c88130e6d69031e62456',+ dir+ )const result = await tracker.cancel(taskId, { deleteTaskRow: false })expect(result).toBe('quarantined')@@ -2748,7 +2845,10 @@ describe('MagnetTracker', () => {{ deleteParentTask })- const taskId = await tracker.submit('magnet:?xt=urn:btih:delete-retry', dir)+ const taskId = await tracker.submit(+ 'magnet:?xt=urn:btih:44cf336cb7f1336842b3a0b08e50929a7de96db4',+ dir+ )await expect(tracker.cancel(taskId)).resolves.toBe('quarantined')expect(deleteParentTask).toHaveBeenCalledTimes(1)@@ -2822,7 +2922,9 @@ describe('MagnetTracker', () => {uploadedBytes: 0,diskPath: '/tmp/motrix-magnet-metadata-x',transitionPhase: TransitionPhase.Idle,- uris: ['magnet:?xt=urn:btih:quarantined'],+ uris: [+ 'magnet:?xt=urn:btih:6ecc2c259036f3099e06e4885d6e82a1ee8202d6',+ ],uriHash: null,payload: {metadataDir: '/tmp/motrix-magnet-metadata-x',@@ -2921,7 +3023,7 @@ describe('MagnetTracker', () => {uploadedBytes: 0,diskPath: '/tmp/original-metadata',transitionPhase: TransitionPhase.Idle,- uris: ['magnet:?xt=urn:btih:restart'],+ uris: ['magnet:?xt=urn:btih:16f766f2f5d7ff50934fb25604a14e9fd4126771'],uriHash: null,payload: { metadataDir: '/tmp/original-metadata' },createdAt: 1700000000,@@ -2979,7 +3081,8 @@ describe('MagnetTracker', () => {taskId: 'm-swap-restart',instanceId: 'meta:m-swap-restart',gid: 'g-bt-orphan',- magnetUri: 'magnet:?xt=urn:btih:restart',+ magnetUri:+ 'magnet:?xt=urn:btih:16f766f2f5d7ff50934fb25604a14e9fd4126771',saveDir: root,metadataDir: diskPath,torrentMetaPath,@@ -3126,7 +3229,7 @@ describe('MagnetTracker', () => {taskId: 'm-path-guard',instanceId: 'meta:m-path-guard',gid: 'g-path-guard',- magnetUri: 'magnet:?xt=urn:btih:path-guard',+ magnetUri: 'magnet:?xt=urn:btih:c53c83bd551481cfdd8eb8597f0694bbcf88650c',saveDir,metadataDir: unsafeMotrixPath,torrentMetaPath: unsafeTorrentPath,@@ -3165,7 +3268,7 @@ describe('MagnetTracker', () => {taskId,instanceId: `meta:${taskId}`,gid: 'g-indexed-cleanup',- magnetUri: 'magnet:?xt=urn:btih:indexed-cleanup',+ magnetUri: 'magnet:?xt=urn:btih:b725471d7373cd172c40ff8fb1a24dff0718a7f3',saveDir,metadataDir: workspacePath,torrentMetaPath: null,@@ -3230,7 +3333,9 @@ describe('MagnetTracker', () => {uploadedBytes: 0,diskPath: '/tmp/motrix-magnet-metadata-visible',transitionPhase: TransitionPhase.Idle,- uris: ['magnet:?xt=urn:btih:visible'],+ uris: [+ 'magnet:?xt=urn:btih:223883960405d6589d6cd37f175c73b073c4180f',+ ],uriHash: null,payload: {metadataDir: '/tmp/motrix-magnet-metadata-visible',@@ -3281,7 +3386,10 @@ describe('MagnetTracker', () => {torrentParser)- const taskId = await tracker.submit('magnet:?xt=urn:btih:shutdown', dir)+ const taskId = await tracker.submit(+ 'magnet:?xt=urn:btih:53669f193b2174641c72654b5c3e5b67950334ae',+ dir+ )await tracker.cancel(taskId)expect(tracker.observe({ gid: 'g-meta-shutdown', status: 'active' } as never)@@ -3326,7 +3434,10 @@ describe('MagnetTracker', () => {taskManager,torrentParser)- await tracker.submit('magnet:?xt=urn:btih:drain', dir)+ await tracker.submit(+ 'magnet:?xt=urn:btih:2780acf0b90856242725c016989fa59c5f78bd83',+ dir+ )const onError = rpc.onDownloadError.mock.calls[0][0]onError({ gid: 'g-meta-drain' })for (let i = 0; i < 20 && !resolveRemove; i += 1) {@@ -3392,7 +3503,10 @@ describe('MagnetTracker', () => {torrentParser)- const taskId = await tracker.submit('magnet:?xt=urn:btih:race', dir)+ const taskId = await tracker.submit(+ 'magnet:?xt=urn:btih:de4bedce64a13c433914abccee8d49016e57d089',+ dir+ )const cancelPromise = tracker.cancel(taskId)await vi.advanceTimersByTimeAsync(1100)diff --git a/src/core/torrent/magnet-tracker.ts b/src/core/torrent/magnet-tracker.tsindex ea02d231..68e21bab 100644--- a/src/core/torrent/magnet-tracker.ts+++ b/src/core/torrent/magnet-tracker.ts@@ -35,6 +35,7 @@ import {} from '@core/task/bt-duplicate-policy'import { btWorkspacePath } from '@core/task/bt-storage-layout'import type { OccurrenceDispatcher } from '@core/task/occurrences/occurrence-dispatcher'+import { admitDownloadSources } from '@core/task/source-admission'import type { TaskManager } from '@core/task/task-manager'import { taskRowToDownloadTask } from '@core/task/task-row-to-download-task'import { AppError, DownloadErrorCode, ErrorCode } from '@shared/errors'@@ -416,6 +417,7 @@ export class MagnetTracker {saveDir: string,provenance?: { source?: TaskSource; sourceMeta?: SourceMeta }): Promise<string> {+ uri = admitDownloadSources([uri], 'input', ['magnet'])[0].sourceUrlconst requestedInfoHash = extractInfoHash(uri)if (requestedInfoHash === UNKNOWN_INFO_HASH) {return this.submitUnderAdmission(uri, saveDir, provenance)@@ -446,7 +448,7 @@ export class MagnetTracker {'max-file-not-found': '0',})if (this.stopped) return ''- log.info({ gid, uri }, 'magnet added (file selection disabled)')+ log.info({ gid }, 'magnet added (file selection disabled)')return ''}@@ -757,6 +759,7 @@ export class MagnetTracker {// click can arrive while the old GID is still shielded. Serialize behind// that cleanup and require authoritative absence before creating a new// sibling GID.+ admitDownloadSources([magnetUri], 'recovery', ['magnet'])const previousEntry = this.findCacheEntryByTaskId(taskId)if (previousEntry) {previousEntry.cleanupAttempts = 0diff --git a/src/main/ipc/commands.test.ts b/src/main/ipc/commands.test.tsindex 17c83d49..a8b5b067 100644--- a/src/main/ipc/commands.test.ts+++ b/src/main/ipc/commands.test.ts@@ -550,7 +550,7 @@ describe('buildCommandHandlers', () => {// @ts-expect-error — partial ctxconst handlers = buildCommandHandlers(ctx)const result = (await handlers[Commands.AddMagnetTask]?.({- uri: 'magnet:?xt=x',+ uri: 'magnet:?xt=urn:btih:a03e3f9a05341aa336e9d9d3f06b33cddafe0bdc',selectedFiles: [0],saveDir: '',})) as { gid: string; taskId?: string } | undefined@@ -563,7 +563,7 @@ describe('buildCommandHandlers', () => {// Unresolved BT writes directly inside its final container under the// fallback save root.expect(ctx.rpcClient.addUri).toHaveBeenCalledWith(- ['magnet:?xt=x'],+ ['magnet:?xt=urn:btih:a03e3f9a05341aa336e9d9d3f06b33cddafe0bdc'],expect.objectContaining({dir: expect.stringMatching(/^\/tmp\/(?!.*\.motrix$).+$/@@ -604,14 +604,17 @@ describe('buildCommandHandlers', () => {const result = await handlers[Commands.CreateTask]?.({type: 'bt',- payload: { kind: 'magnet', uri: 'magnet:?xt=urn:btih:abc' },+ payload: {+ kind: 'magnet',+ uri: 'magnet:?xt=urn:btih:a03e3f9a05341aa336e9d9d3f06b33cddafe0bdc',+ },selectedFiles: [],saveDir: '/downloads',})expect(result).toEqual({ ok: true })expect(ctx.magnetTracker.submit).toHaveBeenCalledWith(- 'magnet:?xt=urn:btih:abc',+ 'magnet:?xt=urn:btih:a03e3f9a05341aa336e9d9d3f06b33cddafe0bdc','/downloads')expect(ctx.rpcClient.addUri).not.toHaveBeenCalled()diff --git a/src/main/ipc/commands.ts b/src/main/ipc/commands.tsindex d39ef7da..b383aaa2 100644--- a/src/main/ipc/commands.ts+++ b/src/main/ipc/commands.ts@@ -75,6 +75,10 @@ import { DirectResourceValidatorService } from '@core/task/direct-resource-validimport type { FileCleanupService } from '@core/task/file-cleanup-service'import type { FinalNamePicker } from '@core/task/final-name-picker'import type { OccurrenceDispatcher } from '@core/task/occurrences/occurrence-dispatcher'+import {+ admitTaskCreateRequest,+ taskCreateSourceFailure,+} from '@core/task/source-admission'import type { TaskManager } from '@core/task/task-manager'import type { TorrentMetaStore } from '@core/task/torrent-meta-store'import { MagnetSelectionTimeout } from '@core/torrent/magnet-selection-timeout'@@ -563,7 +567,8 @@ export function buildCommandHandlers(ctx: CommandContext): CommandHandlerMap {try {result = await handleCreateTask(request, createDeps)} catch (error) {- const conflict = taskCreateConflictResult(error)+ const conflict =+ taskCreateSourceFailure(error) ?? taskCreateConflictResult(error)if (conflict) return conflictthrow error}@@ -774,15 +779,22 @@ export function buildCommandHandlers(ctx: CommandContext): CommandHandlerMap {},[Commands.CreateTask]: async (request: unknown) => {- // Schema validation happens inside handleCreateTask; createAndPersist- // forwards the raw request unchanged. Activate plugins JIT first so- // beforeCreate hooks see the request (Plan C: onTaskType/onProtocol+ try {+ request = admitTaskCreateRequest(request)+ } catch (error) {+ const failure = taskCreateSourceFailure(error)+ if (failure) return failure+ throw error+ }+ // Activate plugins only after source admission, before task creation,+ // so beforeCreate hooks see the validated request (onTaskType/onProtocol// resolvers don't activate at startup).const parsed = taskCreateRequestSchema.safeParse(request)if (parsed.success) {const req = parsed.dataif (req.type === 'http') {- await activatePluginsForTask('http', req.uris[0] ?? '')+ if (!req.uris[0].startsWith('ftp:'))+ await activatePluginsForTask('http', req.uris[0] ?? '')} else if (req.payload.kind === 'magnet') {await activatePluginsForTask('magnet', req.payload.uri)if (@@ -796,7 +808,9 @@ export function buildCommandHandlers(ctx: CommandContext): CommandHandlerMap {req.saveDir || settingsManager.getApp().defaultSaveDir)} catch (error) {- const conflict = taskCreateConflictResult(error)+ const conflict =+ taskCreateSourceFailure(error) ??+ taskCreateConflictResult(error)if (conflict) return conflictthrow error}@@ -893,7 +907,9 @@ export function buildCommandHandlers(ctx: CommandContext): CommandHandlerMap {})} catch (error) {- const conflict = taskCreateConflictResult(error)+ const conflict =+ taskCreateSourceFailure(error) ??+ taskCreateConflictResult(error)if (conflict) return conflictthrow error}@@ -1122,7 +1138,10 @@ export function buildCommandHandlers(ctx: CommandContext): CommandHandlerMap {seedRatio: options.seedRatio,displayName: torrent.meta.name,})- if (result.outcome === 'conflict') {+ if (+ result.outcome === 'conflict' ||+ result.outcome === 'invalid-source'+ ) {failed += 1continue}diff --git a/src/renderer/components/add-task-dialog/add-task-dialog-host.test.tsx b/src/renderer/components/add-task-dialog/add-task-dialog-host.test.tsxindex 78508d58..9bb5688d 100644--- a/src/renderer/components/add-task-dialog/add-task-dialog-host.test.tsx+++ b/src/renderer/components/add-task-dialog/add-task-dialog-host.test.tsx@@ -3,6 +3,7 @@ import { beforeEach, describe, expect, it, vi } from 'vitest'import '@testing-library/jest-dom/vitest'import '@renderer/lib/i18n'import { transport } from '@renderer/lib/transport'+import { ADD_TASK_COLLAPSED_HEIGHT } from '@shared/constants/add-task'import { Events } from '@shared/protocol/events'import type { AddTaskFormValues } from '@shared/schemas/add-task'import { useState } from 'react'@@ -198,7 +199,7 @@ describe('AddTaskDialogHost', () => {'motion-reduce:transition-none','sm:max-w-[640px]')- expect(dialog.style.height).toBe('374px')+ expect(dialog.style.height).toBe(`${ADD_TASK_COLLAPSED_HEIGHT}px`)expect(dialog.style.maxHeight).toContain('760px')expect(dialog.style.maxHeight).toContain('100vh')expect(screen.getByTestId('add-task-form-stub')).toHaveAttribute(diff --git a/src/renderer/components/add-task/add-task-form.test.tsx b/src/renderer/components/add-task/add-task-form.test.tsxindex 8efeb1f9..03b33599 100644--- a/src/renderer/components/add-task/add-task-form.test.tsx+++ b/src/renderer/components/add-task/add-task-form.test.tsx@@ -64,11 +64,137 @@ function renderForm(props = {}, services: PlatformServices = mockServices) {}describe('AddTaskForm', () => {+ it('submits only valid lines and retains rejected input', async () => {+ const onSubmitSuccess = vi.fn()+ renderForm({+ onSubmitSuccess,+ defaultValues: {+ tab: 'links',+ urls: 'https://a/file\nsftp://a/file',+ saveDir: '/d',+ },+ })+ await userEvent.click(screen.getByRole('button', { name: 'Download' }))+ await waitFor(() =>+ expect(screen.getByRole('textbox')).toHaveValue('sftp://a/file')+ )+ expect(+ invokeMock.mock.calls.filter(+ ([channel]) => channel === 'command:createTask'+ )+ ).toHaveLength(1)+ expect(onSubmitSuccess).not.toHaveBeenCalled()+ })++ it('retries only unfinished rows with the same request ID after a lost response', async () => {+ let retry = false+ invokeMock.mockImplementation(async (channel, request) => {+ if (channel !== 'command:createTask') return {}+ if (request.uris[0] === 'https://a/second' && !retry)+ throw new TypeError('Failed to fetch')+ return {+ outcome: retry ? 'reused' : 'created',+ taskId: 'task',+ gid: 'gid',+ }+ })+ renderForm({+ defaultValues: {+ tab: 'links',+ urls: 'https://a/first\nhttps://a/second',+ saveDir: '/d',+ },+ })+ await userEvent.click(screen.getByRole('button', { name: /download/i }))+ await waitFor(() =>+ expect(screen.getByRole('textbox')).toHaveValue('https://a/second')+ )+ retry = true+ await userEvent.click(screen.getByRole('button', { name: /download/i }))+ const submitted = invokeMock.mock.calls+ .filter(([channel]) => channel === 'command:createTask')+ .map(([, request]) => request)+ expect(submitted).toHaveLength(3)+ expect(submitted[0].requestId).not.toBe(submitted[1].requestId)+ expect(submitted[1].requestId).toBe(submitted[2].requestId)+ expect(submitted[2].uris).toEqual(['https://a/second'])+ })+ it('autofills bare hashes from the clipboard as magnet links', async () => {+ const hash = 'a03e3f9a05341aa336e9d9d3f06b33cddafe0bdc'+ vi.mocked(mockServices.readClipboard).mockResolvedValueOnce(+ `${hash}\nhttps://a/b`+ )+ renderForm()+ await waitFor(() =>+ expect(screen.getByRole('textbox')).toHaveValue(+ `magnet:?xt=urn:btih:${hash}\nhttps://a/b`+ )+ )+ })++ it('submits a typed hash as a BT task even without a blur or paste event', async () => {+ const user = userEvent.setup()+ const hash = 'a03e3f9a05341aa336e9d9d3f06b33cddafe0bdc'+ const onSubmitSuccess = vi.fn()+ renderForm({ onSubmitSuccess })+ const textbox = screen.getByRole('textbox')+ await user.type(textbox, hash)+ fireEvent.click(screen.getByRole('button', { name: /download/i }))+ await waitFor(() =>+ expect(+ invokeMock.mock.calls.map(([, payload]) => payload)+ ).toContainEqual(+ expect.objectContaining({+ type: 'bt',+ payload: { kind: 'magnet', uri: `magnet:?xt=urn:btih:${hash}` },+ })+ )+ )+ expect(onSubmitSuccess).toHaveBeenCalledWith('test-gid')+ })+afterEach(() => {vi.clearAllMocks()+ localStorage.removeItem('motrix.pending-create-inputs.v1')invokeMock.mockResolvedValue({ gid: 'test-gid' })})+ it('recovers the request ID after closing and reopening an unconfirmed submission', async () => {+ let retry = false+ invokeMock.mockImplementation(async (channel) => {+ if (channel !== 'command:createTask') return {}+ if (!retry) throw new TypeError('Failed to fetch')+ return { outcome: 'reused', taskId: 'task', gid: 'gid' }+ })+ const props = {+ defaultValues: {+ tab: 'links',+ urls: 'https://a/uncertain',+ saveDir: '/d',+ },+ }+ const first = renderForm(props)+ await userEvent.click(screen.getByRole('button', { name: /download/i }))+ await waitFor(() =>+ expect(screen.getByRole('alert')).toHaveTextContent(+ 'The result is unconfirmed'+ )+ )+ const requestId = invokeMock.mock.calls.find(+ ([channel]) => channel === 'command:createTask'+ )?.[1].requestId+ first.unmount()+ retry = true+ renderForm(props)+ await userEvent.click(screen.getByRole('button', { name: /download/i }))+ const submissions = invokeMock.mock.calls.filter(+ ([channel]) => channel === 'command:createTask'+ )+ expect(submissions).toHaveLength(2)+ expect(submissions[1][1].requestId).toBe(requestId)+ expect(localStorage.getItem('motrix.pending-create-inputs.v1')).toBeNull()+ })+it('renders links tab by default', () => {renderForm()expect(screen.getByRole('textbox')).toBeInTheDocument()@@ -109,6 +235,42 @@ describe('AddTaskForm', () => {expect(submit).toBeDisabled()})+ it.each(['', ' \n '])(+ 'keeps blank input idle on blur, shortcut submission and clearing (%j)',+ async (blank) => {+ const user = userEvent.setup()+ renderForm()+ const textbox = screen.getByRole('textbox', { name: 'URLs' })+ expect(screen.queryByText('URLs')).not.toBeInTheDocument()+ await user.click(textbox)+ fireEvent.change(textbox, { target: { value: blank } })+ await user.tab()+ fireEvent.keyDown(window, { key: 'Enter', metaKey: true })+ fireEvent.keyDown(window, { key: 'Enter', ctrlKey: true })+ await waitFor(() => {+ expect(textbox).toHaveAttribute('aria-invalid', 'false')+ expect(screen.queryByRole('alert')).not.toBeInTheDocument()+ })++ await user.type(textbox, 'htps://example.com')+ await user.tab()+ expect(textbox).toHaveAttribute('aria-invalid', 'true')+ await user.clear(textbox)+ await user.tab()+ await waitFor(() => {+ expect(textbox).toHaveAttribute('aria-invalid', 'false')+ expect(screen.queryByRole('alert')).not.toBeInTheDocument()+ })+ expect(screen.getByRole('status')).toBeEmptyDOMElement()+ expect(screen.getByRole('button', { name: 'Download' })).toBeDisabled()+ expect(+ invokeMock.mock.calls.filter(+ ([channel]) => channel === 'command:createTask'+ )+ ).toHaveLength(0)+ }+ )+it('disables submit when saveDir is empty even if urls are filled', async () => {const user = userEvent.setup()renderForm({ defaultValues: { tab: 'links', urls: '', saveDir: '' } })@@ -659,7 +821,8 @@ describe('AddTaskForm', () => {{ ok: 1, failed: 1 }))- expect(onSubmitSuccess).toHaveBeenCalledWith('ok-gid')+ expect(onSubmitSuccess).not.toHaveBeenCalled()+ expect(screen.getByRole('textbox')).toHaveValue('https://bad/2')expect(recordRecentMock.mock.calls).toEqual([['/d']])})diff --git a/src/renderer/components/add-task/add-task-form.tsx b/src/renderer/components/add-task/add-task-form.tsxindex 292a4d09..50fc2237 100644--- a/src/renderer/components/add-task/add-task-form.tsx+++ b/src/renderer/components/add-task/add-task-form.tsx@@ -48,9 +48,16 @@ import {useWatch,} from 'react-hook-form'import { useTranslation } from 'react-i18next'+import { v4 as uuid } from 'uuid'import { AddTaskLayoutProvider } from './add-task-layout-context'import { FooterActions } from './footer-actions'import { LinksTabPanel } from './links-tab-panel'+import {+ createInputIdentity,+ forgetPendingCreate,+ readPendingCreates,+ rememberPendingCreate,+} from './pending-create-inputs'import { TorrentTabPanel } from './torrent-tab-panel'import { parseUrlLines } from './url-interpreters/multiline-url'import {@@ -104,6 +111,8 @@ export function AddTaskForm({const platform = usePlatformServices()const { t } = useTranslation()const [submitting, setSubmitting] = useState(false)+ const [initialSubmissionInputs] = useState(readPendingCreates)+ const submissionInputs = useRef(initialSubmissionInputs)const [advancingTorrent, setAdvancingTorrent] = useState(false)const [batchSubmitting, setBatchSubmitting] = useState(false)const [torrentQueue, setTorrentQueue] = useState<TorrentQueueState | null>(@@ -114,6 +123,8 @@ export function AddTaskForm({const [duplicateConflict, setDuplicateConflict] = useState<{request: TaskCreateRequestresult: Extract<TaskCreateCommandResult, { outcome: 'conflict' }>+ draft?: string+ line?: number} | null>(null)const form = useForm<AddTaskFormValues>({@@ -393,7 +404,10 @@ export function AddTaskForm({Commands.CreateTask,request)) as TaskCreateCommandResult- if (created.outcome === 'conflict') {+ if (+ created.outcome === 'conflict' ||+ created.outcome === 'invalid-source'+ ) {failed += 1continue}@@ -457,32 +471,110 @@ export function AddTaskForm({if (submitting || advancingTorrent || batchSubmitting) returnsetSubmitting(true)try {+ form.clearErrors('urls')const requests = formValuesToTaskCreateRequests(values)+ const lines = values.tab === 'links' ? parseUrlLines(values.urls) : []+ const validLines = lines.filter((line) => line.valid)+ const unused = [+ ...new Map(+ [...readPendingCreates(), ...submissionInputs.current].map(+ (input) => [input.id, input]+ )+ ).values(),+ ]+ const inputs = requests.map((request) => {+ const identity = createInputIdentity(request)+ const index = unused.findIndex((input) => input.identity === identity)+ return index < 0+ ? { id: uuid(), identity }+ : unused.splice(index, 1)[0]+ })+ submissionInputs.current = inputs+ const completedLines = new Set<number>()const successes: Array<Extract<TaskCreateCommandResult, { gid: string }>> = []- let failed = 0+ let failed = lines.length - validLines.lengthlet firstFailureReason: string | null = null+ let unconfirmed = falselet blockedByConflict = false- for (const request of requests) {+ for (const [index, originalRequest] of requests.entries()) {+ const request =+ originalRequest.type === 'http'+ ? { ...originalRequest, requestId: inputs[index].id }+ : originalRequesttry {+ if (request.type === 'http') rememberPendingCreate(inputs[index])const result = (await transport.invoke(Commands.CreateTask,request)) as TaskCreateCommandResult+ if (result.outcome === 'invalid-source') {+ if (request.type === 'http') forgetPendingCreate(inputs[index].id)+ failed += 1+ firstFailureReason ??= t(+ `task.add.sourceErrors.${result.failure.diagnostic.reason}`+ )+ continue+ }if (result.outcome === 'conflict') {- setDuplicateConflict({ request, result })+ setDuplicateConflict({+ request,+ result,+ draft: values.tab === 'links' ? values.urls : undefined,+ line: validLines[index]?.line,+ })blockedByConflict = truebreak}successes.push(result)+ if (request.type === 'http') forgetPendingCreate(inputs[index].id)+ if (validLines[index]) completedLines.add(validLines[index].line)void recordRecentDirectory(request.saveDir)} catch (err) {failed += 1+ if (request.type === 'http') unconfirmed = truefirstFailureReason ??= taskCreateFailureReason(err)console.error(err)}}+ if (values.tab === 'links' && form.getValues('urls') === values.urls) {+ form.setValue(+ 'urls',+ values.urls+ .split('\n')+ .filter((_, index) => !completedLines.has(index))+ .join('\n'),+ // A concurrent resolver pass would erase the submission error below.+ { shouldDirty: true, shouldValidate: false }+ )+ submissionInputs.current = inputs.filter(+ (_, index) => !completedLines.has(validLines[index]?.line)+ )+ if (blockedByConflict)+ setDuplicateConflict((current) =>+ current+ ? {+ ...current,+ draft: form.getValues('urls'),+ line:+ current.line === undefined+ ? undefined+ : current.line -+ [...completedLines].filter(+ (line) => line < (current.line ?? 0)+ ).length,+ }+ : null+ )+ }+ if (firstFailureReason)+ form.setError('urls', {+ type: 'submission',+ message: unconfirmed+ ? `${firstFailureReason}\n${t('task.add.submissionUnconfirmed')}`+ : firstFailureReason,+ })if (blockedByConflict) returnif (failed === 0 && successes.length > 0) {platform.notify('info', 'task.add.created')@@ -500,7 +592,7 @@ export function AddTaskForm({platform.notify('error', 'task.add.createFailed')}}- if (successes.length > 0) {+ if (successes.length > 0 && failed === 0) {await completeCurrentSubmission(successes[0].taskId ?? successes[0].gid)@@ -515,9 +607,32 @@ export function AddTaskForm({completeCurrentSubmission,platform,submitting,+ form,+ t,])+ const completeConflict = useCallback(+ async (taskId: string) => {+ const conflict = duplicateConflict+ setDuplicateConflict(null)+ if (conflict?.draft !== undefined && conflict.line !== undefined) {+ if (form.getValues('urls') !== conflict.draft) return+ const remaining = conflict.draft+ .split('\n')+ .filter((_, index) => index !== conflict.line)+ .join('\n')+ form.setValue('urls', remaining, {+ shouldDirty: true,+ shouldValidate: true,+ })+ if (remaining.trim()) return+ }+ await completeCurrentSubmission(taskId)+ },+ [duplicateConflict, form, completeCurrentSubmission]+ )+const createSeparateCopy = useCallback(async () => {if (!duplicateConflict) returnsetSubmitting(true)@@ -526,14 +641,21 @@ export function AddTaskForm({...duplicateConflict.request,duplicatePolicy: 'create-copy',})) as TaskCreateCommandResult+ if (result.outcome === 'invalid-source') {+ platform.notify(+ 'error',+ `task.add.sourceErrors.${result.failure.diagnostic.reason}`+ )+ return+ }if (result.outcome === 'conflict') {- setDuplicateConflict({ request: duplicateConflict.request, result })+ setDuplicateConflict({ ...duplicateConflict, result })return}setDuplicateConflict(null)void recordRecentDirectory(duplicateConflict.request.saveDir)platform.notify('info', 'task.add.createdCopy')- await completeCurrentSubmission(result.taskId)+ await completeConflict(result.taskId)} catch (error) {console.error(error)const reason = taskCreateFailureReason(error)@@ -545,13 +667,19 @@ export function AddTaskForm({} finally {setSubmitting(false)}- }, [completeCurrentSubmission, duplicateConflict, platform])+ }, [completeConflict, duplicateConflict, platform])// ⌘↵ / Ctrl+Enter submituseEffect(() => {const handler = (e: KeyboardEvent) => {if (e.key === 'Enter' && (e.metaKey || e.ctrlKey)) {e.preventDefault()+ const values = form.getValues()+ if (+ values.tab === 'links' &&+ !parseUrlLines(values.urls).some((line) => line.valid)+ )+ returnvoid form.handleSubmit(onSubmit)()}}@@ -628,7 +756,7 @@ export function AddTaskForm({const taskId =duplicateConflict.result.conflict.existingTaskIdsetDuplicateConflict(null)- if (taskId) void completeCurrentSubmission(taskId)+ if (taskId) void completeConflict(taskId)}}>{t('task.add.duplicate.showExisting')}@@ -709,10 +837,12 @@ function FooterActionsBridge({})const hasSaveDir = Boolean((saveDir ?? '').trim())+ const inputLines = tab === 'links' ? parseUrlLines(urls ?? '') : []+ const validLinks = inputLines.filter((line) => line.valid).lengthconst canSubmit =hasSaveDir &&(tab === 'links'- ? Boolean((urls ?? '').trim())+ ? validLinks > 0: Boolean(torrentMeta) && (selectedFiles ?? []).length > 0)return (diff --git a/src/renderer/components/add-task/pending-create-inputs.test.ts b/src/renderer/components/add-task/pending-create-inputs.test.tsnew file mode 100644index 00000000..3f5c1f83--- /dev/null+++ b/src/renderer/components/add-task/pending-create-inputs.test.ts@@ -0,0 +1,34 @@+import { afterEach, describe, expect, it } from 'vitest'+import {+ createInputIdentity,+ forgetPendingCreate,+ readPendingCreates,+ rememberPendingCreate,+} from './pending-create-inputs'++afterEach(() => localStorage.clear())++describe('unfinished create receipts', () => {+ it('stores opaque identities and can recover them after the form is recreated', () => {+ const request = {+ uris: ['https://example.test/file?token=private'],+ headers: [{ name: 'Cookie', value: 'sid=secret' }],+ }+ const input = {+ id: '018f3b2e-4c5d-7aaa-bbbb-cccccccccccc',+ identity: createInputIdentity(request),+ }+ rememberPendingCreate(input)+ expect(readPendingCreates()).toEqual([input])+ expect(createInputIdentity(request)).toBe(input.identity)+ expect(JSON.stringify(localStorage)).not.toMatch(/private|secret|https:/)+ forgetPendingCreate(input.id)+ expect(readPendingCreates()).toEqual([])+ })++ it('does not confuse changed options with a retry of the same request', () => {+ expect(+ createInputIdentity({ uris: ['https://a/f'], saveDir: '/one' })+ ).not.toBe(createInputIdentity({ uris: ['https://a/f'], saveDir: '/two' }))+ })+})diff --git a/src/renderer/components/add-task/pending-create-inputs.ts b/src/renderer/components/add-task/pending-create-inputs.tsnew file mode 100644index 00000000..bfd27ded--- /dev/null+++ b/src/renderer/components/add-task/pending-create-inputs.ts@@ -0,0 +1,48 @@+import { sha256 } from '@noble/hashes/sha2.js'+import { z } from 'zod'++const storageKey = 'motrix.pending-create-inputs.v1'+const pendingInputSchema = z.object({+ id: z.uuid(),+ identity: z.string().regex(/^[0-9a-f]{64}$/),+})+export type PendingCreateInput = z.infer<typeof pendingInputSchema>++/** Keep only opaque receipts, never URLs, headers, cookies or proxy credentials. */+export function createInputIdentity(request: unknown): string {+ return Array.from(+ sha256(new TextEncoder().encode(JSON.stringify(request))),+ (byte) => byte.toString(16).padStart(2, '0')+ ).join('')+}++export function readPendingCreates(): PendingCreateInput[] {+ try {+ const parsed = z+ .array(pendingInputSchema)+ .safeParse(JSON.parse(localStorage.getItem(storageKey) ?? '[]'))+ return parsed.success ? parsed.data : []+ } catch {+ return []+ }+}++export function rememberPendingCreate(input: PendingCreateInput): void {+ savePendingCreates([+ ...readPendingCreates().filter((entry) => entry.id !== input.id),+ input,+ ])+}++export function forgetPendingCreate(id: string): void {+ savePendingCreates(readPendingCreates().filter((entry) => entry.id !== id))+}++function savePendingCreates(inputs: PendingCreateInput[]): void {+ try {+ if (inputs.length) localStorage.setItem(storageKey, JSON.stringify(inputs))+ else localStorage.removeItem(storageKey)+ } catch {+ // The live draft still retains its IDs when browser storage is unavailable.+ }+}diff --git a/src/renderer/components/add-task/url-diagnostic.tsx b/src/renderer/components/add-task/url-diagnostic.tsxnew file mode 100644index 00000000..8838fbca--- /dev/null+++ b/src/renderer/components/add-task/url-diagnostic.tsx@@ -0,0 +1,114 @@+import { Button } from '@renderer/components/ui/button'+import {+ Popover,+ PopoverContent,+ PopoverTrigger,+} from '@renderer/components/ui/popover'+import {+ Tooltip,+ TooltipContent,+ TooltipTrigger,+} from '@renderer/components/ui/tooltip'+import type { DownloadInputLine } from '@shared/lib/download-source-input'+import type { SourceCorrection } from '@shared/schemas/download-source'+import { CircleAlert } from 'lucide-react'+import { useState } from 'react'+import { useTranslation } from 'react-i18next'++interface UrlDiagnosticProps {+ line: DownloadInputLine+ top: number+ right: number+ wrapped: boolean+ disabled?: boolean+ onCorrect: (line: DownloadInputLine, correction: SourceCorrection) => void+ onEdit: (line: DownloadInputLine) => void+}++export function UrlDiagnostic({+ line,+ top,+ right,+ wrapped,+ disabled,+ onCorrect,+ onEdit,+}: UrlDiagnosticProps) {+ const { t } = useTranslation()+ const [open, setOpen] = useState(false)+ if (line.analysis.status === 'accepted') return null+ const reason = t(`task.add.sourceErrors.${line.analysis.diagnostic.reason}`)+ const label = `${t('task.add.sourceLine', { line: line.line + 1 })}: ${reason}`+ const corrections =+ line.analysis.status === 'needsCorrection' ? line.analysis.corrections : []+ const button = (+ <button+ type="button"+ disabled={disabled}+ aria-label={label}+ data-url-diagnostic={line.line}+ className="url-editor-diagnostic pointer-events-auto absolute flex size-6 items-center justify-center rounded-sm text-destructive outline-none hover:bg-destructive/10 focus-visible:ring-2 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-50"+ style={{ top, right }}+ // Keep blur-time hash expansion from moving the pointer's target.+ onMouseDown={(event) => event.preventDefault()}+ />+ )+ return (+ <Popover open={open} onOpenChange={setOpen}>+ <Tooltip disabled={open}>+ <TooltipTrigger+ delay={300}+ render={+ corrections.length ? <PopoverTrigger render={button} /> : button+ }+ onClick={corrections.length ? undefined : () => onEdit(line)}+ >+ <CircleAlert className="size-3.5" aria-hidden="true" />+ </TooltipTrigger>+ <TooltipContent+ side={wrapped ? 'bottom' : 'top'}+ align="end"+ sideOffset={6}+ className="max-w-[min(20rem,calc(100vw-2rem))] text-left leading-relaxed"+ >+ {label}+ </TooltipContent>+ </Tooltip>+ {corrections.length > 0 && (+ <PopoverContent+ data-url-correction=""+ side="bottom"+ align="end"+ className="w-80 max-w-[calc(100vw-2rem)] space-y-3 p-3"+ aria-label={label}+ >+ <div className="space-y-1">+ <p className="text-xs text-muted-foreground">+ {t('task.add.sourceLine', { line: line.line + 1 })}+ </p>+ <p className="text-sm">{reason}</p>+ </div>+ {corrections.map((correction) => (+ <div key={correction.action} className="space-y-2">+ <code className="block max-h-24 overflow-auto rounded-sm bg-muted p-2 text-xs text-muted-foreground [overflow-wrap:anywhere]">+ {correction.url}+ </code>+ <Button+ type="button"+ variant="outline"+ size="sm"+ disabled={disabled}+ onClick={() => {+ setOpen(false)+ onCorrect(line, correction)+ }}+ >+ {t(`task.add.sourceCorrections.${correction.action}`)}+ </Button>+ </div>+ ))}+ </PopoverContent>+ )}+ </Popover>+ )+}diff --git a/src/renderer/components/add-task/url-editor-presentation.test.ts b/src/renderer/components/add-task/url-editor-presentation.test.tsnew file mode 100644index 00000000..96aaa4b3--- /dev/null+++ b/src/renderer/components/add-task/url-editor-presentation.test.ts@@ -0,0 +1,51 @@+import { analyzeDownloadInput } from '@shared/lib/download-source-input'+import { describe, expect, it } from 'vitest'+import { getUrlDisplayParts, getUrlErrorRange } from './url-editor-presentation'++describe('URL editor presentation', () => {+ it.each([+ [' htps://example.com ', 'htps'],+ ['\nhttps://example.com/a\n https://example.com/%zz', '%'],+ ['https://example.com/dir\\file?sig=%2f+%252F', '\\'],+ ['https://example.com/file name', ' '],+ ])(+ 'maps precise diagnostics back to the original input: %s',+ (text, expected) => {+ const line = analyzeDownloadInput(text).at(-1)!+ const range = getUrlErrorRange(line)!+ expect(line.raw.slice(range.start, range.end)).toBe(expected)+ const parts = getUrlDisplayParts(line.raw, line)+ expect(parts.map((part) => part.text).join('')).toBe(line.raw)+ expect(+ parts+ .filter((part) => part.kind === 'error')+ .map((part) => part.text)+ .join('')+ ).toBe(expected)+ }+ )++ it.each([+ 'missing scheme',+ 'https://',+ 'https://example.com:99999/a',+ 'https://example.com/../file',+ 'magnet:?xt=bad',+ ])('does not pretend a whole-URL diagnostic pinpoints a token: %s', (raw) => {+ expect(getUrlErrorRange(analyzeDownloadInput(raw)[0])).toBeUndefined()+ })++ it.each([+ ' https://例子.测试/中文?sig=%2f+%252F#section ',+ 'https://[::1]:8080/file',+ 'a03e3f9a05341aa336e9d9d3f06b33cddafe0bdc',+ '<img src=x onerror=alert(1)>',+ '',+ ])(+ 'paints original text without serialization, decoding or HTML: %s',+ (raw) => {+ const parts = getUrlDisplayParts(raw, analyzeDownloadInput(raw)[0])+ expect(parts.map((part) => part.text).join('')).toBe(raw)+ }+ )+})diff --git a/src/renderer/components/add-task/url-editor-presentation.ts b/src/renderer/components/add-task/url-editor-presentation.tsnew file mode 100644index 00000000..cc219718--- /dev/null+++ b/src/renderer/components/add-task/url-editor-presentation.ts@@ -0,0 +1,57 @@+import type { DownloadInputLine } from '@shared/lib/download-source-input'+import type { SourceReason } from '@shared/schemas/download-source'++// Other diagnostics describe the URL as a whole, rather than a precise token.+const preciseReasons = new Set<SourceReason>([+ 'unsupportedProtocol',+ 'invalidPercentEncoding',+ 'ambiguousBackslash',+ 'unescapedCharacter',+ 'controlCharacter',+ 'invalidUnicode',+])++export function getUrlErrorRange(line: DownloadInputLine) {+ if (line.analysis.status === 'accepted') return undefined+ const { diagnostic } = line.analysis+ if (!preciseReasons.has(diagnostic.reason)) return undefined+ const input = line.raw.replace(/\r$/, '').replace(/^ +| +$/g, '')+ // Diagnostic offsets refer to the analyzed URL. Never apply them to a+ // transformed value (for example an expanded hash) in the native textarea.+ if (input !== line.url) return undefined+ const leadingSpaces = line.raw.length - line.raw.replace(/^ +/, '').length+ const start = leadingSpaces + diagnostic.start+ const end = leadingSpaces + diagnostic.end+ if (start < 0 || end > line.raw.length || start >= end) return undefined+ return { start, end }+}++export function getUrlDisplayParts(raw: string, line?: DownloadInputLine) {+ const error = line && getUrlErrorRange(line)+ // Presentation only: never parse/serialize a URL to paint its host.+ const authority = /^ *[a-z][a-z0-9+.-]*:\/\/([^/?#\s]*)/i.exec(raw)+ const hostEnd = authority?.[0].length ?? 0+ const hostStart = hostEnd - (authority?.[1].length ?? 0)+ const boundaries = [+ ...new Set([+ 0,+ raw.length,+ hostStart,+ hostEnd,+ ...(error ? [error.start, error.end] : []),+ ]),+ ].sort((a, b) => a - b)+ return boundaries.slice(0, -1).map((start, index) => {+ const end = boundaries[index + 1]+ return {+ start,+ text: raw.slice(start, end),+ kind:+ error && start >= error.start && end <= error.end+ ? 'error'+ : start >= hostStart && end <= hostEnd+ ? 'host'+ : 'text',+ }+ })+}diff --git a/src/renderer/components/add-task/url-editor.css b/src/renderer/components/add-task/url-editor.cssnew file mode 100644index 00000000..c6440433--- /dev/null+++ b/src/renderer/components/add-task/url-editor.css@@ -0,0 +1,88 @@+.url-editor {+ position: relative;+ width: 100%;+ --url-line-height: 22px;+}++.url-editor-control,+.url-editor-mirror {+ box-sizing: border-box;+ margin: 0;+ border: 0;+ padding: 12px 56px 12px 12px;+ font-family: var(--font-mono);+ font-size: 13px;+ font-weight: 400;+ font-style: normal;+ font-variant-ligatures: none;+ line-height: var(--url-line-height);+ letter-spacing: 0;+ text-align: left;+ text-indent: 0;+ text-transform: none;+ tab-size: 4;+ white-space: pre-wrap;+ overflow-wrap: anywhere;+ word-break: normal;+}++.url-editor-control {+ display: block;+ width: 100%;+ field-sizing: fixed;+ height: 100px;+ overflow-y: auto;+ color: var(--foreground);+ caret-color: var(--foreground);+}++.url-editor-control::placeholder {+ color: var(--muted-foreground);+}++.url-editor[data-enhanced="true"] .url-editor-control {+ color: transparent;+}++.url-editor-control::selection {+ color: HighlightText;+ background: Highlight;+}++.url-editor-viewport {+ position: absolute;+ inset: 0;+ overflow: hidden;+ pointer-events: none;+}++.url-editor-mirror {+ position: relative;+ color: var(--muted-foreground);+}++.url-editor-line {+ min-height: var(--url-line-height);+}++.url-editor-host {+ color: var(--foreground);+}++.url-editor-error {+ color: var(--destructive);+ text-decoration: underline wavy;+ text-decoration-thickness: 1px;+ text-underline-offset: 3px;+ text-decoration-skip-ink: none;+}++@media (forced-colors: active) {+ .url-editor[data-enhanced="true"] .url-editor-control {+ color: CanvasText;+ }++ .url-editor-mirror {+ visibility: hidden;+ }+}diff --git a/src/renderer/components/add-task/url-editor.tsx b/src/renderer/components/add-task/url-editor.tsxnew file mode 100644index 00000000..7e811c75--- /dev/null+++ b/src/renderer/components/add-task/url-editor.tsx@@ -0,0 +1,193 @@+import { InputGroupTextarea } from '@renderer/components/ui/input-group'+import type { DownloadInputLine } from '@shared/lib/download-source-input'+import type { SourceCorrection } from '@shared/schemas/download-source'+import {+ type ComponentProps,+ type RefObject,+ useCallback,+ useEffect,+ useLayoutEffect,+ useMemo,+ useRef,+ useState,+} from 'react'+import { UrlDiagnostic } from './url-diagnostic'+import { getUrlDisplayParts, getUrlErrorRange } from './url-editor-presentation'+import './url-editor.css'++interface UrlEditorProps+ extends Omit<ComponentProps<'textarea'>, 'value' | 'ref'> {+ value: string+ controlRef: RefObject<HTMLTextAreaElement | null>+ lines: DownloadInputLine[]+ onCorrect: (line: DownloadInputLine, correction: SourceCorrection) => void+}++interface Marker {+ line: DownloadInputLine+ top: number+ right: number+ wrapped: boolean+}++export function UrlEditor({+ value,+ controlRef,+ lines,+ onCorrect,+ ...props+}: UrlEditorProps) {+ const mirrorRef = useRef<HTMLDivElement>(null)+ const frameRef = useRef<number | null>(null)+ const [markers, setMarkers] = useState<Marker[]>([])+ const [composing, setComposing] = useState(false)+ const oversized = lines.some(+ (line) =>+ line.analysis.status !== 'accepted' &&+ line.analysis.diagnostic.reason === 'tooManySources'+ )+ const enhanced = !oversized && !composing+ const display = useMemo(() => {+ if (oversized) return []+ const byLine = new Map(lines.map((line) => [line.line, line]))+ return value+ .split('\n')+ .map((raw, index) =>+ getUrlDisplayParts(raw.replace(/\r$/, ''), byLine.get(index))+ )+ }, [value, lines, oversized])++ const measure = useCallback(() => {+ const textarea = controlRef.current+ const mirror = mirrorRef.current+ if (!textarea || !mirror) return+ // Use the actual content width, including the platform's scrollbar gutter.+ mirror.style.width = `${textarea.clientWidth}px`+ mirror.style.transform = `translateY(${-textarea.scrollTop}px)`+ const lineHeight =+ Number.parseFloat(getComputedStyle(textarea).lineHeight) || 22+ // Overlay scrollbars on macOS occupy pixels without reducing clientWidth.+ const scrollbarWidth = Math.max(+ textarea.offsetWidth - textarea.clientWidth,+ textarea.scrollHeight > textarea.clientHeight ? 16 : 0+ )+ const next: Marker[] = []+ if (!composing) {+ for (const line of lines) {+ if (line.analysis.status === 'accepted') continue+ const row = mirror.children.item(line.line) as HTMLElement | null+ const center = oversized+ ? 12 + lineHeight / 2+ : row+ ? row.offsetTop + row.offsetHeight - lineHeight / 2+ : 0+ const top = center - textarea.scrollTop - 12+ if (top < 0 || top + 24 > textarea.clientHeight) continue+ next.push({+ line,+ top,+ right: scrollbarWidth + 8,+ wrapped: Boolean(row && row.offsetHeight > lineHeight),+ })+ }+ }+ setMarkers((previous) =>+ previous.length === next.length &&+ previous.every(+ (marker, i) =>+ marker.line === next[i].line &&+ marker.top === next[i].top &&+ marker.right === next[i].right &&+ marker.wrapped === next[i].wrapped+ )+ ? previous+ : next+ )+ }, [controlRef, lines, composing, oversized])++ useLayoutEffect(measure, [measure])+ useEffect(() => {+ const textarea = controlRef.current+ if (!textarea) return+ const observer =+ typeof ResizeObserver === 'undefined'+ ? undefined+ : new ResizeObserver(measure)+ observer?.observe(textarea)+ document.fonts?.addEventListener('loadingdone', measure)+ window.addEventListener('resize', measure)+ return () => {+ observer?.disconnect()+ document.fonts?.removeEventListener('loadingdone', measure)+ window.removeEventListener('resize', measure)+ if (frameRef.current !== null) cancelAnimationFrame(frameRef.current)+ }+ }, [controlRef, measure])++ return (+ <div className="url-editor" data-enhanced={enhanced}>+ <div+ className="url-editor-viewport"+ aria-hidden="true"+ style={{ visibility: enhanced ? undefined : 'hidden' }}+ >+ <div ref={mirrorRef} className="url-editor-mirror">+ {display.map((parts, index) => (+ // A line's position is its identity in this noninteractive mirror.+ // biome-ignore lint/suspicious/noArrayIndexKey: mirrors native textarea line positions+ <div key={index} className="url-editor-line" data-url-line={index}>+ {parts.length ? (+ parts.map((part) => (+ <span key={part.start} className={`url-editor-${part.kind}`}>+ {part.text}+ </span>+ ))+ ) : (+ <br />+ )}+ </div>+ ))}+ </div>+ </div>+ <InputGroupTextarea+ {...props}+ ref={controlRef}+ value={value}+ dir="ltr"+ spellCheck={false}+ autoCapitalize="off"+ autoCorrect="off"+ wrap="soft"+ className="url-editor-control"+ onScroll={() => {+ if (frameRef.current !== null) cancelAnimationFrame(frameRef.current)+ frameRef.current = requestAnimationFrame(() => {+ frameRef.current = null+ measure()+ })+ }}+ onCompositionStart={() => setComposing(true)}+ onCompositionEnd={() => setComposing(false)}+ />+ <div className="url-editor-viewport">+ {markers.map(({ line, ...position }) => (+ <UrlDiagnostic+ key={`${line.line}:${line.raw}`}+ line={line}+ {...position}+ disabled={props.disabled}+ onCorrect={onCorrect}+ onEdit={(line) => {+ const range = getUrlErrorRange(line)+ controlRef.current?.focus()+ controlRef.current?.setSelectionRange(+ line.start + (range?.start ?? 0),+ range ? line.start + range.end : line.end+ )+ }}+ />+ ))}+ </div>+ </div>+ )+}diff --git a/src/renderer/components/add-task/url-interpreters/containers.test.ts b/src/renderer/components/add-task/url-interpreters/containers.test.tsnew file mode 100644index 00000000..92364855--- /dev/null+++ b/src/renderer/components/add-task/url-interpreters/containers.test.ts@@ -0,0 +1,86 @@+import { describe, expect, it } from 'vitest'+import { curlInterpreter } from './curl'+import { jsonInterpreter } from './json'++describe('explicit input containers', () => {+ it('rejects oversized containers before importing URLs or request options', () => {+ const oversized = 'x'.repeat(MAX_DOWNLOAD_INPUT_BYTES)+ for (const [interpreter, input] of [+ [jsonInterpreter, JSON.stringify(`https://example.com/${oversized}`)],+ [+ jsonInterpreter,+ JSON.stringify(+ Array(MAX_DOWNLOAD_INPUT_LINES + 1).fill('https://example.com/file')+ ),+ ],+ [+ curlInterpreter,+ `curl https://example.com/file -H 'X-Large: ${oversized}'`,+ ],+ ] as const) {+ expect(interpreter.tryInterpret(input)).toMatchObject({ rejected: true })+ }+ })+ it('decodes a JSON string once and preserves URI escapes', () => {+ expect(+ jsonInterpreter.tryInterpret(+ String.raw`"https:\/\/example.test\/file?sig=%252F\u0026path=one\\two"`+ )+ ).toMatchObject({+ urls: [String.raw`https://example.test/file?sig=%252F&path=one\two`],+ })+ expect(jsonInterpreter.tryInterpret('https://example.test/file')).toBeNull()+ })+ it.each([+ '["https://a/f",42]',+ '"https://a/f',+ '"https://a/f\\nhttps://b/f"',+ ])('retains invalid JSON container %s', (input) => {+ expect(jsonInterpreter.tryInterpret(input)).toMatchObject({+ rejected: true,+ })+ })+ it('preserves Bash single-quote data and double-quote unknown escapes', () => {+ for (const input of [+ String.raw`curl 'https://example.test/f?q=a\b&sig=%2f'`,+ String.raw`curl "https://example.test/f?q=a\b&sig=%2f"`,+ ]) {+ expect(curlInterpreter.tryInterpret(input)).toMatchObject({+ urls: [String.raw`https://example.test/f?q=a\b&sig=%2f`],+ })+ }+ })+ it('imports GET headers, --url and a Bash line continuation', () => {+ expect(+ curlInterpreter.tryInterpret(+ "curl -L -g \\\n --url='https://example.test/a?x=%252F' -H 'X-Signature: token' -X GET"+ )+ ).toMatchObject({+ urls: ['https://example.test/a?x=%252F'],+ headers: { 'X-Signature': 'token' },+ })+ })+ it.each([+ "curl 'https://a/f' -X POST",+ "curl 'https://a/f' --data x",+ "curl -k 'https://a/f'",+ "curl --unknown 'https://a/f'",+ 'curl "https://a/$TOKEN"',+ 'curl https://a/$(whoami)',+ "curl 'https://a/f",+ 'curl.exe https://a/f',+ "curl 'https://a/{one,two}'",+ "curl 'https://a/f' -b cookies.txt",+ "curl 'https://a/f' -u username",+ "curl 'https://a/f' 'https://b/f' -o one.bin",+ ])('does not silently reinterpret %s as a GET', (input) => {+ expect(curlInterpreter.tryInterpret(input)).toMatchObject({+ rejected: true,+ })+ })+})++import {+ MAX_DOWNLOAD_INPUT_BYTES,+ MAX_DOWNLOAD_INPUT_LINES,+} from '@shared/schemas/download-source'diff --git a/src/renderer/components/add-task/url-interpreters/curl.ts b/src/renderer/components/add-task/url-interpreters/curl.tsindex fff0e915..4caf086d 100644--- a/src/renderer/components/add-task/url-interpreters/curl.ts+++ b/src/renderer/components/add-task/url-interpreters/curl.ts@@ -1,59 +1,95 @@+import { isDownloadInputTooLarge } from '@shared/lib/download-source-input'+import { MAX_DOWNLOAD_INPUT_LINES } from '@shared/schemas/download-source'import type { InterpretResult, UrlInputInterpreter } from './types'-const CURL_LEAD = /^\s*curl\s+/+const CURL_LEAD = /^\s*curl(?:\.exe)?\s+/i-// Tokenizer that handles single-quoted, double-quoted, and bare tokens,-// and silently swallows bash line-continuations (`\` at end of line).-function tokenize(input: string): string[] {+/** A deliberately bounded Bash word parser. It never evaluates shell expressions. */+function tokenize(input: string): string[] | null {const tokens: string[] = []- const text = input.replace(/\\\s*\n/g, ' ')- let i = 0- while (i < text.length) {- const ch = text[i]- if (ch === ' ' || ch === '\t' || ch === '\n') {- i+++ let word = ''+ let active = false+ let quote: "'" | '"' | null = null+ for (let i = 0; i < input.length; i++) {+ const ch = input[i]+ if (quote === "'") {+ if (ch === "'") quote = null+ else word += chcontinue}- if (ch === '"' || ch === "'") {- const quote = ch- i++- let buf = ''- while (i < text.length && text[i] !== quote) {- if (text[i] === '\\' && i + 1 < text.length) {- buf += text[i + 1]- i += 2- } else {- buf += text[i]- i++- }- }- i++ // skip closing quote- tokens.push(buf)- } else {- let buf = ''- while (- i < text.length &&- text[i] !== ' ' &&- text[i] !== '\t' &&- text[i] !== '\n'- ) {- buf += text[i]- i++- }- tokens.push(buf)+ if (ch === '\\') {+ const next = input[++i]+ if (next === undefined) return null+ if (next === '\n') continue+ if (quote === '"' && !['$', '`', '"', '\\'].includes(next)) word += '\\'+ word += next+ active = true+ continue+ }+ if (ch === '$' || ch === '`') return null+ if (quote === '"') {+ if (ch === '"') quote = null+ else word += ch+ continue}+ if (ch === "'" || ch === '"') {+ quote = ch+ active = true+ continue+ }+ if (/\s/.test(ch)) {+ if (active) tokens.push(word)+ word = ''+ active = false+ continue+ }+ if (/[;&|<>()^]/.test(ch)) return null+ word += ch+ active = true}+ if (quote) return null+ if (active) tokens.push(word)return tokens}-function b64EncodeUserPass(userPass: string): string {- if (typeof btoa === 'function') return btoa(userPass)- // Node fallback (tests may run in jsdom or node)- // biome-ignore lint/suspicious/noExplicitAny: allow Buffer- const g = globalThis as any- if (g.Buffer) return g.Buffer.from(userPass).toString('base64')- return userPass // graceful degradation-}+const rejected = (): InterpretResult => ({+ rejected: true,+ userNotice: { kind: 'warn', messageKey: 'task.add.unsupportedCurl' },+})+const flags = new Set([+ '-L',+ '--location',+ '-g',+ '--globoff',+ '-s',+ '--silent',+ '-S',+ '--show-error',+ '-sS',+ '-f',+ '--fail',+ '-O',+ '--remote-name',+])+const valueFlags = new Set([+ '-H',+ '--header',+ '-A',+ '--user-agent',+ '-e',+ '--referer',+ '-b',+ '--cookie',+ '-x',+ '--proxy',+ '-o',+ '--output',+ '-u',+ '--user',+ '-X',+ '--request',+ '--url',+])export const curlInterpreter: UrlInputInterpreter = {id: 'builtin:curl',@@ -61,76 +97,99 @@ export const curlInterpreter: UrlInputInterpreter = {priority: 10,tryInterpret(rawText): InterpretResult | null {if (!CURL_LEAD.test(rawText)) return null-+ if (isDownloadInputTooLarge(rawText)) return rejected()+ if (/^\s*curl\.exe/i.test(rawText)) return rejected()const tokens = tokenize(rawText.replace(CURL_LEAD, ''))- if (tokens.length === 0) return null-+ if (!tokens?.length) return rejected()const urls: string[] = []const headers: Record<string, string> = {}let proxy: string | undefinedlet filename: string | undefined-+ let globoff = false+ const addHeader = (name: string, value: string): boolean => {+ if (+ !name ||+ /[\r\n]/.test(name + value) ||+ Object.keys(headers).some(+ (key) => key.toLowerCase() === name.toLowerCase()+ )+ )+ return false+ headers[name] = value+ return true+ }for (let i = 0; i < tokens.length; i++) {- const t = tokens[i]- const next = tokens[i + 1]-- if (t === '-H' || t === '--header') {- if (next) {- const idx = next.indexOf(':')- if (idx > 0) {- const name = next.slice(0, idx).trim()- const value = next.slice(idx + 1).trim()- headers[name] = value+ let flag = tokens[i]+ if (flags.has(flag)) {+ if (flag === '-g' || flag === '--globoff') globoff = true+ continue+ }+ let inline: string | undefined+ if (flag.startsWith('--') && flag.includes('=')) {+ const at = flag.indexOf('=')+ inline = flag.slice(at + 1)+ flag = flag.slice(0, at)+ }+ if (valueFlags.has(flag)) {+ const value = inline ?? tokens[++i]+ if (!value) return rejected()+ if (flag === '--url') urls.push(value)+ else if (flag === '-X' || flag === '--request') {+ if (value !== 'GET') return rejected()+ } else if (flag === '-x' || flag === '--proxy') {+ if (proxy !== undefined) return rejected()+ proxy = value+ } else if (flag === '-o' || flag === '--output') {+ if (filename !== undefined) return rejected()+ filename = value+ } else if (flag === '-H' || flag === '--header') {+ const at = value.indexOf(':')+ if (+ at <= 0 ||+ !addHeader(value.slice(0, at).trim(), value.slice(at + 1).trim())+ )+ return rejected()+ } else {+ const name = (+ {+ '-A': 'User-Agent',+ '--user-agent': 'User-Agent',+ '-e': 'Referer',+ '--referer': 'Referer',+ '-b': 'Cookie',+ '--cookie': 'Cookie',+ '-u': 'Authorization',+ '--user': 'Authorization',+ } as Record<string, string>+ )[flag]+ if (name === 'Cookie' && !value.includes('=')) return rejected()+ let headerValue = value+ if (name === 'Authorization') {+ if (!value.includes(':')) return rejected()+ try {+ headerValue = `Basic ${btoa(value)}`+ } catch {+ return rejected()+ }}- i++- }- } else if (t === '-A' || t === '--user-agent') {- if (next) {- headers['User-Agent'] = next- i++- }- } else if (t === '-e' || t === '--referer') {- if (next) {- headers.Referer = next- i+++ if (!addHeader(name, headerValue)) return rejected()}- } else if (t === '-b' || t === '--cookie') {- if (next) {- headers.Cookie = next- i++- }- } else if (t === '-x' || t === '--proxy') {- if (next) {- proxy = next- i++- }- } else if (t === '-o' || t === '--output') {- if (next) {- filename = next- i++- }- } else if (t === '-u' || t === '--user') {- if (next) {- headers.Authorization = `Basic ${b64EncodeUserPass(next)}`- i++- }- } else if (t === '-X' || t === '--request') {- // Method flag; consume arg, ignore- if (next) i++- } else if (t.startsWith('-')) {- // Unknown single-letter or long flag; best-effort skip.- // If it plausibly carries a value (long --foo=bar), ignore.- // If it's a bare boolean switch (--silent), nothing to skip.- } else if (/^[a-zA-Z][a-zA-Z0-9+.-]*:\/\//.test(t)) {- urls.push(t)- }+ } else if (/^[a-z][a-z0-9+.-]*:\/\//i.test(flag)) urls.push(flag)+ else return rejected()}-- if (urls.length === 0) return null-+ if (+ !urls.length ||+ urls.length > MAX_DOWNLOAD_INPUT_LINES ||+ (urls.length > 1 && filename !== undefined) ||+ (!globoff &&+ urls.some((url) =>+ /[{}[\]]/.test(url.replace(/:\/\/\[[^\]]+\]/, '://host'))+ ))+ )+ return rejected()return {urls,- headers: Object.keys(headers).length > 0 ? headers : undefined,+ headers: Object.keys(headers).length ? headers : undefined,proxy,filename,userNotice: { kind: 'info', messageKey: 'task.add.interpretedCurl' },diff --git a/src/renderer/components/add-task/url-interpreters/index.ts b/src/renderer/components/add-task/url-interpreters/index.tsindex f64250a9..ecb753c1 100644--- a/src/renderer/components/add-task/url-interpreters/index.ts+++ b/src/renderer/components/add-task/url-interpreters/index.ts@@ -1,10 +1,12 @@import { curlInterpreter } from './curl'+import { jsonInterpreter } from './json'import { magnetLineInterpreter } from './magnet-line'import { multilineUrlInterpreter } from './multiline-url'import type { UrlInputInterpreter } from './types'export const builtinInterpreters: UrlInputInterpreter[] = [curlInterpreter,+ jsonInterpreter,magnetLineInterpreter,multilineUrlInterpreter,].sort((a, b) => a.priority - b.priority)diff --git a/src/renderer/components/add-task/url-interpreters/json.ts b/src/renderer/components/add-task/url-interpreters/json.tsnew file mode 100644index 00000000..57bf04dd--- /dev/null+++ b/src/renderer/components/add-task/url-interpreters/json.ts@@ -0,0 +1,36 @@+import { isDownloadInputTooLarge } from '@shared/lib/download-source-input'+import { MAX_DOWNLOAD_INPUT_LINES } from '@shared/schemas/download-source'+import type { InterpretResult, UrlInputInterpreter } from './types'++export const jsonInterpreter: UrlInputInterpreter = {+ id: 'builtin:json',+ name: 'JSON URL input',+ priority: 20,+ tryInterpret(rawText): InterpretResult | null {+ const text = rawText.trim()+ if (!text.startsWith('"') && !text.startsWith('[')) return null+ const rejected: InterpretResult = {+ rejected: true,+ userNotice: { kind: 'warn', messageKey: 'task.add.invalidJson' },+ }+ if (isDownloadInputTooLarge(rawText)) return rejected+ let parsed: unknown+ try {+ parsed = JSON.parse(text)+ } catch {+ return rejected+ }+ const urls = typeof parsed === 'string' ? [parsed] : parsed+ if (+ !Array.isArray(urls) ||+ !urls.length ||+ urls.length > MAX_DOWNLOAD_INPUT_LINES ||+ !urls.every((url) => typeof url === 'string' && !/[\r\n]/.test(url))+ )+ return rejected+ return {+ urls,+ userNotice: { kind: 'info', messageKey: 'task.add.interpretedJson' },+ }+ },+}diff --git a/src/renderer/components/add-task/url-interpreters/magnet-line.test.ts b/src/renderer/components/add-task/url-interpreters/magnet-line.test.tsindex 34fda2dc..49bc6d14 100644--- a/src/renderer/components/add-task/url-interpreters/magnet-line.test.ts+++ b/src/renderer/components/add-task/url-interpreters/magnet-line.test.ts@@ -2,6 +2,18 @@ import { describe, expect, it } from 'vitest'import { magnetLineInterpreter } from './magnet-line'describe('magnetLineInterpreter', () => {+ it.each([+ 'A03E3F9A05341AA336E9D9D3F06B33CDDAFE0BDC',+ 'u3vg6p2m2t4k4i7nl4zatcyxmvtzhdal',+ ])('expands a bare info hash: %s', (hash) => {+ expect(magnetLineInterpreter.tryInterpret(hash)).toEqual({+ urls: [+ `magnet:?xt=urn:btih:${hash.length === 40 ? hash.toLowerCase() : hash.toUpperCase()}`,+ ],+ userNotice: { kind: 'info', messageKey: 'task.add.interpretedInfoHash' },+ })+ })+it('detects a valid magnet line', () => {const r = magnetLineInterpreter.tryInterpret('magnet:?xt=urn:btih:abcdef1234567890'diff --git a/src/renderer/components/add-task/url-interpreters/magnet-line.ts b/src/renderer/components/add-task/url-interpreters/magnet-line.tsindex e876bc1a..6371c415 100644--- a/src/renderer/components/add-task/url-interpreters/magnet-line.ts+++ b/src/renderer/components/add-task/url-interpreters/magnet-line.ts@@ -1,3 +1,4 @@+import { infoHashToMagnetUri } from '@shared/schemas/magnet-input'import type { InterpretResult, UrlInputInterpreter } from './types'export const magnetLineInterpreter: UrlInputInterpreter = {@@ -7,6 +8,16 @@ export const magnetLineInterpreter: UrlInputInterpreter = {tryInterpret(rawText): InterpretResult | null {const trimmed = rawText.trim()if (trimmed.includes('\n')) return null+ const magnetUri = infoHashToMagnetUri(trimmed)+ if (magnetUri) {+ return {+ urls: [magnetUri],+ userNotice: {+ kind: 'info',+ messageKey: 'task.add.interpretedInfoHash',+ },+ }+ }if (!trimmed.startsWith('magnet:?')) return nullreturn {urls: [trimmed],diff --git a/src/renderer/components/add-task/url-interpreters/multiline-url.test.ts b/src/renderer/components/add-task/url-interpreters/multiline-url.test.tsindex 009eaa6e..476e5e88 100644--- a/src/renderer/components/add-task/url-interpreters/multiline-url.test.ts+++ b/src/renderer/components/add-task/url-interpreters/multiline-url.test.ts@@ -2,9 +2,20 @@ import { describe, expect, it } from 'vitest'import { multilineUrlInterpreter, parseUrlLines } from './multiline-url'describe('parseUrlLines', () => {+ it('recognizes bare hashes in a mixed batch without dropping invalid lines', () => {+ const hash = 'a03e3f9a05341aa336e9d9d3f06b33cddafe0bdc'+ expect(+ parseUrlLines(`https://a/b\n ${hash} \r\n\nnot-a-url`)+ ).toMatchObject([+ { line: 0, url: 'https://a/b', valid: true },+ { line: 1, url: `magnet:?xt=urn:btih:${hash}`, valid: true },+ { line: 3, url: 'not-a-url', valid: false },+ ])+ })+it('parses a single http URL', () => {const r = parseUrlLines('https://a.com/f')- expect(r).toEqual([{ line: 0, url: 'https://a.com/f', valid: true }])+ expect(r).toMatchObject([{ line: 0, url: 'https://a.com/f', valid: true }])})it('splits multiple URLs by newline', () => {@@ -24,7 +35,9 @@ describe('parseUrlLines', () => {})it('accepts magnet', () => {- const r = parseUrlLines('magnet:?xt=urn:btih:abc')+ const r = parseUrlLines(+ 'magnet:?xt=urn:btih:a03e3f9a05341aa336e9d9d3f06b33cddafe0bdc'+ )expect(r[0].valid).toBe(true)})@@ -47,7 +60,7 @@ describe('multilineUrlInterpreter.tryInterpret', () => {it('returns urls for valid multi-line input', () => {const r = multilineUrlInterpreter.tryInterpret('https://a\nhttps://b')- expect(r).toEqual({ urls: ['https://a', 'https://b'] })+ expect(r).toEqual({ urls: ['https://a/', 'https://b/'] })})it('returns null when no valid URL is present', () => {diff --git a/src/renderer/components/add-task/url-interpreters/multiline-url.ts b/src/renderer/components/add-task/url-interpreters/multiline-url.tsindex 52fed12b..746876e8 100644--- a/src/renderer/components/add-task/url-interpreters/multiline-url.ts+++ b/src/renderer/components/add-task/url-interpreters/multiline-url.ts@@ -1,34 +1,7 @@+import { analyzeDownloadInput } from '@shared/lib/download-source-input'import type { InterpretResult, UrlInputInterpreter } from './types'-export interface ParsedLine {- line: number- url: string- valid: boolean-}--const VALID_SCHEMES = ['http:', 'https:', 'ftp:']--export function parseUrlLines(text: string): ParsedLine[] {- const out: ParsedLine[] = []- const lines = text.split('\n')- for (let i = 0; i < lines.length; i++) {- const trimmed = lines[i].trim()- if (trimmed === '') continue- let valid = false- if (trimmed.startsWith('magnet:')) {- valid = trimmed.startsWith('magnet:?')- } else {- try {- const u = new URL(trimmed)- valid = VALID_SCHEMES.includes(u.protocol)- } catch {- valid = false- }- }- out.push({ line: i, url: trimmed, valid })- }- return out-}+export const parseUrlLines = analyzeDownloadInputexport const multilineUrlInterpreter: UrlInputInterpreter = {id: 'builtin:multiline-url',diff --git a/src/renderer/components/add-task/url-interpreters/types.ts b/src/renderer/components/add-task/url-interpreters/types.tsindex 4d00b4b2..64bf131c 100644--- a/src/renderer/components/add-task/url-interpreters/types.ts+++ b/src/renderer/components/add-task/url-interpreters/types.ts@@ -1,4 +1,5 @@export interface InterpretResult {+ rejected?: booleanurls?: string[]headers?: Record<string, string>proxy?: stringdiff --git a/src/renderer/components/add-task/url-textarea.test.tsx b/src/renderer/components/add-task/url-textarea.test.tsxindex 6558217a..e3ad77b3 100644--- a/src/renderer/components/add-task/url-textarea.test.tsx+++ b/src/renderer/components/add-task/url-textarea.test.tsx@@ -1,16 +1,29 @@-import { render, screen } from '@testing-library/react'+import { act, fireEvent, render, screen, waitFor } from '@testing-library/react'import userEvent from '@testing-library/user-event'import { FormProvider, useForm } from 'react-hook-form'-import { describe, expect, it, vi } from 'vitest'+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'import '@testing-library/jest-dom/vitest'import '@renderer/lib/i18n'import type { PlatformServices } from '@renderer/platform/services'import { PlatformServicesProvider } from '@renderer/platform/services'import { UrlTextarea } from './url-textarea'-function Wrapper({ children }: { children: React.ReactNode }) {+function Wrapper({+ children,+ onValidate,+}: {+ children: React.ReactNode+ onValidate?: () => void+}) {const form = useForm({defaultValues: { tab: 'links', urls: '', saveDir: '/d' },+ mode: 'onTouched',+ resolver: onValidate+ ? (values) => {+ onValidate()+ return { values, errors: {} }+ }+ : undefined,})const mockServices: PlatformServices = {kind: 'electron',@@ -28,6 +41,163 @@ function Wrapper({ children }: { children: React.ReactNode }) {}describe('UrlTextarea', () => {+ // jsdom has no layout; wrapped-line geometry is exercised in Electron E2E.+ beforeEach(() => {+ vi.spyOn(HTMLElement.prototype, 'clientHeight', 'get').mockReturnValue(100)+ vi.spyOn(HTMLElement.prototype, 'clientWidth', 'get').mockReturnValue(600)+ vi.spyOn(HTMLElement.prototype, 'offsetWidth', 'get').mockReturnValue(600)+ vi.spyOn(HTMLElement.prototype, 'offsetHeight', 'get').mockReturnValue(22)+ vi.spyOn(HTMLElement.prototype, 'offsetTop', 'get').mockImplementation(+ function (this: HTMLElement) {+ return 12 + Number(this.dataset.urlLine ?? 0) * 22+ }+ )+ })+ afterEach(() => vi.restoreAllMocks())++ it('does not run the form resolver for an empty or cleared URL draft', async () => {+ const user = userEvent.setup()+ const onValidate = vi.fn()+ render(+ <Wrapper onValidate={onValidate}>+ <UrlTextarea name="urls" />+ </Wrapper>+ )+ const textbox = screen.getByRole('textbox')+ await user.click(textbox)+ await user.tab()+ expect(onValidate).not.toHaveBeenCalled()+ await user.type(textbox, 'https://example.com')+ await user.tab()+ expect(onValidate).toHaveBeenCalled()+ onValidate.mockClear()+ await user.clear(textbox)+ await user.type(textbox, ' {Enter} ')+ await user.tab()+ expect(onValidate).not.toHaveBeenCalled()+ })++ it('corrects one path explicitly, preserves the query, and supports undo', async () => {+ const user = userEvent.setup()+ render(+ <Wrapper>+ <UrlTextarea name="urls" />+ </Wrapper>+ )+ const textbox = screen.getByRole('textbox')+ const original = 'https://a/dir\\file?sig=%2f+%252F'+ await user.type(textbox, original)+ await user.tab()+ await user.click(screen.getByRole('button', { name: /^Line 1:/ }))+ await user.click(+ screen.getByRole('button', { name: 'Encode as literal characters' })+ )+ expect(textbox).toHaveValue('https://a/dir%5Cfile?sig=%2f+%252F')+ await user.click(+ screen.getByRole('button', { name: 'Undo URL correction' })+ )+ expect(textbox).toHaveValue(original)+ })+ it('expands a pasted hash when replacing a selected line', async () => {+ const user = userEvent.setup()+ render(+ <Wrapper>+ <UrlTextarea name="urls" />+ </Wrapper>+ )+ const textbox = screen.getByRole('textbox') as HTMLTextAreaElement+ await user.type(textbox, 'https://a/b')+ textbox.setSelectionRange(0, textbox.value.length)+ const hash = 'a03e3f9a05341aa336e9d9d3f06b33cddafe0bdc'+ await user.paste(hash)+ expect(textbox).toHaveValue(`magnet:?xt=urn:btih:${hash}`)+ expect(screen.getByText(/1 URL/i)).toBeInTheDocument()+ })++ it('defers hash reflow while choosing a correction and undoes only that correction', async () => {+ const user = userEvent.setup()+ render(+ <Wrapper>+ <UrlTextarea name="urls" />+ </Wrapper>+ )+ const textbox = screen.getByRole('textbox')+ const hash = 'a03e3f9a05341aa336e9d9d3f06b33cddafe0bdc'+ const url = 'https://example.com/dir\\file'+ await user.click(textbox)+ fireEvent.change(textbox, { target: { value: `${hash}\n${url}` } })+ await user.click(screen.getByRole('button', { name: /^Line 2:/ }))+ const correction = screen.getByRole('button', {+ name: 'Encode as literal characters',+ })+ act(() => correction.focus())+ expect(correction).toHaveFocus()+ expect(textbox).toHaveValue(`${hash}\n${url}`)+ await user.click(correction)+ expect(textbox).toHaveValue(+ `magnet:?xt=urn:btih:${hash}\nhttps://example.com/dir%5Cfile`+ )+ await user.click(+ screen.getByRole('button', { name: 'Undo URL correction' })+ )+ expect(textbox).toHaveValue(`magnet:?xt=urn:btih:${hash}\n${url}`)+ })++ it('preserves a hash pasted as a URL query value', async () => {+ const user = userEvent.setup()+ render(+ <Wrapper>+ <UrlTextarea name="urls" />+ </Wrapper>+ )+ const textbox = screen.getByRole('textbox') as HTMLTextAreaElement+ await user.type(textbox, 'https://a/b?hash=')+ const hash = 'a03e3f9a05341aa336e9d9d3f06b33cddafe0bdc'+ await user.paste(hash)+ await user.tab()+ expect(textbox).toHaveValue(`https://a/b?hash=${hash}`)+ })++ it('counts typed hashes as valid and expands them on blur, preserving other lines', async () => {+ const user = userEvent.setup()+ render(+ <Wrapper>+ <UrlTextarea name="urls" />+ </Wrapper>+ )+ const textbox = screen.getByRole('textbox')+ const hash = 'a03e3f9a05341aa336e9d9d3f06b33cddafe0bdc'+ await user.type(textbox, `https://a/b{Enter}${hash}{Enter}bad text`)+ expect(textbox).toHaveValue(`https://a/b\n${hash}\nbad text`)+ expect(+ screen.getByRole('status', { name: '2 valid, 1 invalid' })+ ).toBeInTheDocument()+ await user.tab()+ // The first Tab focuses the inline diagnostic; the next leaves the editor.+ await user.tab()+ expect(textbox).toHaveValue(+ `https://a/b\nmagnet:?xt=urn:btih:${hash}\nbad text`+ )+ })++ it('preserves invalid lines in a mixed paste while expanding hashes on blur', async () => {+ const user = userEvent.setup()+ render(+ <Wrapper>+ <UrlTextarea name="urls" />+ </Wrapper>+ )+ const textbox = screen.getByRole('textbox')+ const hash = 'a03e3f9a05341aa336e9d9d3f06b33cddafe0bdc'+ await user.click(textbox)+ await user.paste(`${hash}\ninvalid\nhttps://a/b`)+ await user.tab()+ await user.tab()+ expect(textbox).toHaveValue(+ `magnet:?xt=urn:btih:${hash}\ninvalid\nhttps://a/b`+ )+ })+it('renders a textarea', () => {render(<Wrapper>@@ -56,7 +226,9 @@ describe('UrlTextarea', () => {</Wrapper>)await user.type(screen.getByRole('textbox'), 'https://a/b{Enter}not-a-url')- expect(screen.getByText(/1 invalid/i)).toBeInTheDocument()+ expect(+ screen.getByRole('status', { name: '1 valid, 1 invalid' })+ ).toBeInTheDocument()})// Plain URL pastes are handled natively — the onPaste handler only@@ -75,4 +247,80 @@ describe('UrlTextarea', () => {await user.paste('https://c/d')expect(textbox.value).toBe('https://c/d')})++ it('exposes an error tooltip and selects the exact original token on click', async () => {+ const user = userEvent.setup()+ const { container } = render(+ <Wrapper>+ <UrlTextarea name="urls" />+ </Wrapper>+ )+ const textbox = screen.getByRole('textbox') as HTMLTextAreaElement+ await user.click(textbox)+ await user.paste('https://example.com/file\n htps://example.com')+ const marker = screen.getByRole('button', {+ name: 'Line 2: This URL protocol is not supported for this download.',+ })+ expect(container.querySelector('.url-editor-error')).toHaveTextContent(+ 'htps'+ )+ expect(screen.queryByText(/Review .*invalid line/)).not.toBeInTheDocument()+ await user.hover(marker)+ expect(await screen.findByRole('tooltip')).toHaveTextContent(+ 'Line 2: This URL protocol is not supported for this download.'+ )+ await user.click(marker)+ expect(textbox).toHaveFocus()+ expect(+ textbox.value.slice(textbox.selectionStart, textbox.selectionEnd)+ ).toBe('htps')+ await user.keyboard('https')+ expect(+ screen.queryByRole('button', { name: /^Line 2:/ })+ ).not.toBeInTheDocument()+ })++ it('keeps native text visible during IME composition', async () => {+ const { container } = render(+ <Wrapper>+ <UrlTextarea name="urls" />+ </Wrapper>+ )+ const textbox = screen.getByRole('textbox')+ fireEvent.change(textbox, { target: { value: 'htps://example.com' } })+ fireEvent.compositionStart(textbox)+ expect(container.querySelector('.url-editor')).toHaveAttribute(+ 'data-enhanced',+ 'false'+ )+ expect(+ screen.queryByRole('button', { name: /^Line 1:/ })+ ).not.toBeInTheDocument()+ fireEvent.compositionEnd(textbox)+ await waitFor(() =>+ expect(container.querySelector('.url-editor')).toHaveAttribute(+ 'data-enhanced',+ 'true'+ )+ )+ expect(screen.getByRole('button', { name: /^Line 1:/ })).toBeInTheDocument()+ })++ it('uses bounded markup and one diagnostic for oversized pasted input', () => {+ const { container } = render(+ <Wrapper>+ <UrlTextarea name="urls" />+ </Wrapper>+ )+ const textbox = screen.getByRole('textbox')+ const raw = 'htps://example.com\n'.repeat(1001)+ fireEvent.change(textbox, { target: { value: raw } })+ expect(textbox).toHaveValue(raw)+ expect(container.querySelector('.url-editor')).toHaveAttribute(+ 'data-enhanced',+ 'false'+ )+ expect(container.querySelectorAll('[data-url-line]')).toHaveLength(0)+ expect(screen.getAllByRole('button', { name: /^Line 1:/ })).toHaveLength(1)+ })})diff --git a/src/renderer/components/add-task/url-textarea.tsx b/src/renderer/components/add-task/url-textarea.tsxindex 2a06db87..86207be9 100644--- a/src/renderer/components/add-task/url-textarea.tsx+++ b/src/renderer/components/add-task/url-textarea.tsx@@ -1,21 +1,29 @@+import { Button } from '@renderer/components/ui/button'import {InputGroup,InputGroupAddon,InputGroupText,- InputGroupTextarea,} from '@renderer/components/ui/input-group'-import { cn } from '@renderer/lib/utils'import { usePlatformServices } from '@renderer/platform/services'+import type { DownloadInputLine } from '@shared/lib/download-source-input'import type { AddTaskFormValues } from '@shared/schemas/add-task'+import type { SourceCorrection } from '@shared/schemas/download-source'+import {+ infoHashToMagnetUri,+ normalizeMagnetInputLines,+} from '@shared/schemas/magnet-input'import {type ClipboardEvent,useCallback,useEffect,+ useId,useMemo,useRef,+ useState,} from 'react'import { type FieldPath, useController, useFormContext } from 'react-hook-form'import { useTranslation } from 'react-i18next'+import { UrlEditor } from './url-editor'import { builtinInterpreters } from './url-interpreters'import { parseUrlLines } from './url-interpreters/multiline-url'import type { InterpretResult } from './url-interpreters/types'@@ -46,8 +54,14 @@ interface UrlTextareaProps {export function UrlTextarea({ name, autoFocus }: UrlTextareaProps) {const { t } = useTranslation()const platform = usePlatformServices()- const { setValue, getValues } = useFormContext<AddTaskFormValues>()- const { field } = useController<AddTaskFormValues>({ name })+ const { setValue, getValues, clearErrors, formState } =+ useFormContext<AddTaskFormValues>()+ const { field, fieldState } = useController<AddTaskFormValues>({ name })+ const statusId = useId()+ const errorId = useId()+ const [correctionHistory, setCorrectionHistory] = useState<+ Array<{ before: string; after: string }>+ >([])const ref = useRef<HTMLTextAreaElement>(null)@@ -61,6 +75,7 @@ export function UrlTextarea({ name, autoFocus }: UrlTextareaProps) {)const valid = parsed.filter((p) => p.valid).lengthconst invalid = parsed.length - valid+ const errorMessage = parsed.length > 0 ? fieldState.error?.message : undefinedconst counter = useMemo(() => {if (parsed.length === 0) return ''@@ -97,11 +112,26 @@ export function UrlTextarea({ name, autoFocus }: UrlTextareaProps) {Authorization: 'authorization' as never,}for (const [hName, hValue] of Object.entries(result.headers)) {- const target = map[hName]+ const canonicalName = Object.keys(map).find(+ (key) => key.toLowerCase() === hName.toLowerCase()+ )+ const target = canonicalName ? map[canonicalName] : undefinedif (target) {setValue(target as never, hValue as never, { shouldDirty: true })}}+ setValue(+ 'extraHeaders',+ Object.entries(result.headers)+ .filter(+ ([name]) =>+ !Object.keys(map).some(+ (key) => key.toLowerCase() === name.toLowerCase()+ )+ )+ .map(([name, value]) => ({ name, value })),+ { shouldDirty: true }+ )}if (result.proxy) {setValue('allProxy' as never, result.proxy as never, {@@ -126,9 +156,24 @@ export function UrlTextarea({ name, autoFocus }: UrlTextareaProps) {start: target.selectionStart,end: target.selectionEnd,}+ // A hash pasted into an existing URL may be a path or query value.+ // Expand only when it occupies an entire line after the selection is replaced.+ if (infoHashToMagnetUri(text)) {+ const before = target.value.slice(0, range.start).split('\n').at(-1)+ const after = target.value.slice(range.end).split('\n')[0]+ if (`${before}${after}`.trim()) return+ }for (const interp of builtinInterpreters) {const result = interp.tryInterpret(text)if (!result) continue+ if (result.rejected) {+ if (result.userNotice)+ platform.notify(+ result.userNotice.kind,+ result.userNotice.messageKey+ )+ return+ }// Only intercept when the interpreter produces side effects beyond// the urls field (magnet tab switch, curl headers/proxy/filename,// toast). A urls-only result means the pasted text IS the urls@@ -154,31 +199,115 @@ export function UrlTextarea({ name, autoFocus }: UrlTextareaProps) {[applyResult, platform])+ const correctLine = (+ line: DownloadInputLine,+ correction: SourceCorrection+ ) => {+ const current = String(getValues(name) ?? '')+ if (current !== String(field.value ?? '')) return+ // Apply deferred hash expansion only after the correction has been chosen.+ const before = normalizeMagnetInputLines(current)+ const after = normalizeMagnetInputLines(+ current.slice(0, line.start) + correction.url + current.slice(line.end)+ )+ setCorrectionHistory((history) => [+ ...history.slice(-19),+ { before, after },+ ])+ field.onChange(after)+ ref.current?.focus()+ }+return (- <div className="space-y-1">- <InputGroup>- <InputGroupTextarea- ref={ref}+ // biome-ignore lint/a11y/noStaticElementInteractions: observes focus leaving child controls without adding an interactive target+ <div+ className="space-y-1"+ onBlur={(e) => {+ // Treat the input, diagnostics and portaled corrections as one editor.+ if (+ e.relatedTarget instanceof HTMLElement &&+ (e.currentTarget.contains(e.relatedTarget) ||+ e.relatedTarget.closest('[data-url-correction]'))+ )+ return+ const value = String(getValues(name) ?? '')+ if (!value.trim()) return+ const normalized = normalizeMagnetInputLines(value)+ if (normalized !== value) field.onChange(normalized)+ field.onBlur()+ }}+ >+ <InputGroup className="h-auto flex-col !border-input !ring-ring/50 has-[[data-slot=input-group-control]:focus-visible]:!border-ring">+ <UrlEditor+ controlRef={ref}+ lines={parsed}+ onCorrect={correctLine}value={String(field.value ?? '')}- onChange={(e) => field.onChange(e.target.value)}- onBlur={field.onBlur}+ disabled={formState.isSubmitting}+ onChange={(e) => {+ const value = e.target.value+ if (value.trim()) {+ field.onChange(value)+ return+ }+ // An empty draft is idle, even after this field has been touched.+ setValue(name, value as never, { shouldDirty: true })+ clearErrors(name)+ }}onPaste={handlePaste}placeholder={t('task.add.urlPlaceholder')}- rows={4}- className="text-sm min-h-24"+ rows={3}aria-label={t('task.add.urlsLabel')}+ aria-invalid={invalid > 0 || Boolean(errorMessage)}+ aria-describedby={`${statusId}${errorMessage ? ` ${errorId}` : ''}`}/>- <InputGroupAddon align="block-end">+ <InputGroupAddon+ align="block-end"+ className="justify-between pt-0 pb-2"+ ><InputGroupText- className={cn(- 'tabular-nums',- invalid > 0 ? 'text-destructive' : 'text-muted-foreground'- )}+ id={statusId}+ role="status"+ aria-label={counter}+ className="min-h-4 gap-1.5 text-xs tabular-nums text-muted-foreground">- {counter}+ {invalid > 0 ? (+ <>+ <span>{t('task.add.validUrlCount', { count: valid })}</span>+ <span aria-hidden="true">·</span>+ <span className="text-destructive">+ {t('task.add.invalidUrlCount', { count: invalid })}+ </span>+ </>+ ) : (+ counter+ )}</InputGroupText>+ {correctionHistory.at(-1)?.after === String(field.value ?? '') && (+ <Button+ type="button"+ variant="link"+ size="sm"+ className="h-4 shrink-0 p-0 text-xs"+ disabled={formState.isSubmitting}+ onClick={() => {+ const last = correctionHistory.at(-1)+ if (!last || String(getValues(name) ?? '') !== last.after)+ return+ field.onChange(last.before)+ setCorrectionHistory((history) => history.slice(0, -1))+ }}+ >+ {t('task.add.undoCorrection')}+ </Button>+ )}</InputGroupAddon></InputGroup>+ {errorMessage && (+ <p id={errorId} role="alert" className="text-xs text-destructive">+ {t(errorMessage)}+ </p>+ )}</div>)}diff --git a/src/server/ipc/commands.test.ts b/src/server/ipc/commands.test.tsindex 8d2b6ca4..d2cc19fb 100644--- a/src/server/ipc/commands.test.ts+++ b/src/server/ipc/commands.test.ts@@ -1109,14 +1109,17 @@ describe('server Commands.CreateTask magnet metadata selection', () => {const result = await handlers[Commands.CreateTask]?.({type: 'bt',- payload: { kind: 'magnet', uri: 'magnet:?xt=urn:btih:abc' },+ payload: {+ kind: 'magnet',+ uri: 'magnet:?xt=urn:btih:a03e3f9a05341aa336e9d9d3f06b33cddafe0bdc',+ },selectedFiles: [],saveDir: '/downloads',})expect(result).toEqual({ ok: true })expect(ctx.magnetTracker.submit).toHaveBeenCalledWith(- 'magnet:?xt=urn:btih:abc',+ 'magnet:?xt=urn:btih:a03e3f9a05341aa336e9d9d3f06b33cddafe0bdc','/downloads')expect(ctx.downloadPathPolicy.prepareSaveDir).toHaveBeenCalledWith(diff --git a/src/server/ipc/commands.ts b/src/server/ipc/commands.tsindex 1cbdcfd8..2784fdec 100644--- a/src/server/ipc/commands.ts+++ b/src/server/ipc/commands.ts@@ -63,6 +63,10 @@ import type { FileCleanupService } from '@core/task/file-cleanup-service'import type { FinalNamePicker } from '@core/task/final-name-picker'import type { OccurrenceDispatcher } from '@core/task/occurrences/occurrence-dispatcher'import { createSetSelectedFilesHandler } from '@core/task/set-selected-files'+import {+ admitTaskCreateRequest,+ taskCreateSourceFailure,+} from '@core/task/source-admission'import type { TaskManager } from '@core/task/task-manager'import type { TorrentMetaStore } from '@core/task/torrent-meta-store'import type { MagnetTracker } from '@core/torrent/magnet-tracker'@@ -422,11 +426,19 @@ export function buildServerCommandHandlers(},[Commands.CreateTask]: async (request: unknown) => {+ try {+ request = admitTaskCreateRequest(request)+ } catch (error) {+ const failure = taskCreateSourceFailure(error)+ if (failure) return failure+ throw error+ }const parsed = taskCreateRequestSchema.safeParse(request)if (parsed.success) {const req = parsed.dataif (req.type === 'http') {- await activatePluginsForTask('http', req.uris[0] ?? '')+ if (!req.uris[0].startsWith('ftp:'))+ await activatePluginsForTask('http', req.uris[0] ?? '')} else if (req.payload.kind === 'magnet') {await activatePluginsForTask('magnet', req.payload.uri)if (@@ -440,7 +452,9 @@ export function buildServerCommandHandlers(try {taskId = await magnetTracker.submit(req.payload.uri, saveDir)} catch (error) {- const conflict = taskCreateConflictResult(error)+ const conflict =+ taskCreateSourceFailure(error) ??+ taskCreateConflictResult(error)if (conflict) return conflictthrow error}@@ -538,7 +552,9 @@ export function buildServerCommandHandlers(})} catch (error) {- const conflict = taskCreateConflictResult(error)+ const conflict =+ taskCreateSourceFailure(error) ??+ taskCreateConflictResult(error)if (conflict) return conflictthrow error}@@ -551,7 +567,8 @@ export function buildServerCommandHandlers(try {return await handleCreateTask(request, createDeps)} catch (error) {- const conflict = taskCreateConflictResult(error)+ const conflict =+ taskCreateSourceFailure(error) ?? taskCreateConflictResult(error)if (conflict) return conflictthrow error}diff --git a/src/shared/constants/add-task.ts b/src/shared/constants/add-task.tsindex 87fdcf92..fcb562d5 100644--- a/src/shared/constants/add-task.ts+++ b/src/shared/constants/add-task.ts@@ -1,2 +1,2 @@-export const ADD_TASK_COLLAPSED_HEIGHT = 374+export const ADD_TASK_COLLAPSED_HEIGHT = 386export const ADD_TASK_MAX_HEIGHT = 760diff --git a/src/shared/errors.ts b/src/shared/errors.tsindex 7dfdcca1..bb0acae7 100644--- a/src/shared/errors.ts+++ b/src/shared/errors.ts@@ -5,6 +5,7 @@ export enum ErrorCode {EngineProcessOwnershipUnverified = 'ENGINE_PROCESS_OWNERSHIP_UNVERIFIED',EngineProcessTerminationFailed = 'ENGINE_PROCESS_TERMINATION_FAILED',TaskCreateFailed = 'TASK_CREATE_FAILED',+ TaskSourceInvalid = 'TASK_SOURCE_INVALID',TaskNotFound = 'TASK_NOT_FOUND',TaskRevealFailed = 'TASK_REVEAL_FAILED',TaskOpenFailed = 'TASK_OPEN_FAILED',diff --git a/src/shared/lib/download-source-input.ts b/src/shared/lib/download-source-input.tsnew file mode 100644index 00000000..1117a92f--- /dev/null+++ b/src/shared/lib/download-source-input.ts@@ -0,0 +1,78 @@+import { analyzeDownloadSource } from '@shared/lib/download-source'+import {+ type DownloadSourceAnalysis,+ MAX_DOWNLOAD_INPUT_BYTES,+ MAX_DOWNLOAD_INPUT_LINES,+} from '@shared/schemas/download-source'+import { infoHashToMagnetUri } from '@shared/schemas/magnet-input'++export interface DownloadInputLine {+ line: number+ start: number+ end: number+ raw: string+ url: string+ valid: boolean+ analysis: DownloadSourceAnalysis+}++/** Check before parsing containers or splitting a potentially oversized draft. */+export function isDownloadInputTooLarge(text: string): boolean {+ return (+ text.length > MAX_DOWNLOAD_INPUT_BYTES ||+ new TextEncoder().encode(text).length > MAX_DOWNLOAD_INPUT_BYTES+ )+}++/** Textarea boundaries allow CRLF and outer ASCII spaces; API URLs do not trim. */+export function analyzeDownloadInput(text: string): DownloadInputLine[] {+ const tooLarge = isDownloadInputTooLarge(text)+ const lines = tooLarge ? [] : text.split('\n')+ if (tooLarge || lines.length > MAX_DOWNLOAD_INPUT_LINES)+ return [+ {+ line: 0,+ start: 0,+ end: text.length,+ raw: text,+ url: '',+ valid: false,+ analysis: {+ status: 'rejected',+ diagnostic: { reason: 'tooManySources', start: 0, end: text.length },+ },+ },+ ]+ const unsupportedContainer = /^\s*(?:curl(?:\.exe)?\s|["[])/i.test(text)+ let offset = 0+ return lines.flatMap((raw, line) => {+ const start = offset+ offset += raw.length + 1+ const input = raw.replace(/\r$/, '').replace(/^ +| +$/g, '')+ if (input === '') return []+ const url = input.includes('\t')+ ? input+ : (infoHashToMagnetUri(input) ?? input)+ const analysis: DownloadSourceAnalysis = unsupportedContainer+ ? {+ status: 'rejected',+ diagnostic: {+ reason: 'unsupportedInput',+ start: 0,+ end: raw.length,+ },+ }+ : analyzeDownloadSource(url)+ return [+ {+ line,+ start,+ end: start + raw.length,+ raw,+ url: analysis.status === 'accepted' ? analysis.sourceUrl : url,+ valid: analysis.status === 'accepted',+ analysis,+ },+ ]+ })+}diff --git a/src/shared/lib/download-source.test.ts b/src/shared/lib/download-source.test.tsnew file mode 100644index 00000000..3ae80db6--- /dev/null+++ b/src/shared/lib/download-source.test.ts@@ -0,0 +1,151 @@+import { downloadSourceAnalysisSchema } from '@shared/schemas/download-source'+import { describe, expect, it } from 'vitest'+import { analyzeDownloadSource } from './download-source'+import { analyzeDownloadInput } from './download-source-input'++const hash = 'a03e3f9a05341aa336e9d9d3f06b33cddafe0bdc'++describe('download source representation', () => {+ it.each(['path', 'query', 'fragment'])(+ 'rejects an oversized encoded Unicode %s before reporting an accepted URL',+ (part) => {+ const unicode = '界'.repeat(2000)+ const suffix =+ part === 'query'+ ? `?q=${unicode}`+ : part === 'fragment'+ ? `#${unicode}`+ : unicode+ expect(+ analyzeDownloadSource(`https://example.com/${suffix}`)+ ).toMatchObject({+ status: 'rejected',+ diagnostic: { reason: 'urlTooLong' },+ })+ }+ )++ it.each(['%20', '%09', '%0A', '%C2%A0'])(+ 'does not trim decoded %s inside a magnet exact topic',+ (space) => {+ for (const topic of [`${space}${hash}`, `${hash}${space}`]) {+ expect(+ analyzeDownloadSource(`magnet:?xt=urn:btih:${topic}`)+ ).toMatchObject({+ status: 'rejected',+ diagnostic: { reason: 'invalidMagnet' },+ })+ }+ }+ )++ it.each([+ [+ 'https://example.com/a//b?x=%2f&x=%2F&empty=&plus=+&space=%20&nested=%252F',+ 'https://example.com/a//b?x=%2f&x=%2F&empty=&plus=+&space=%20&nested=%252F',+ ],+ [+ 'HTTPS://EXAMPLE.COM:443/文件?键=值&sig=a%2Fb%5Cc',+ 'https://example.com/%E6%96%87%E4%BB%B6?%E9%94%AE=%E5%80%BC&sig=a%2Fb%5Cc',+ ],+ ['https://例子.测试/a', 'https://xn--fsqu00a.xn--0zwm56d/a'],+ ['https://example.com/a?x=one\\two', 'https://example.com/a?x=one\\two'],+ [+ 'https://example.com/a?x=%00%0D%0A#view',+ 'https://example.com/a?x=%00%0D%0A',+ ],+ ['http://[::1]:8080/file', 'http://[::1]:8080/file'],+ ['ftp://example.com/file.zip', 'ftp://example.com/file.zip'],+ [+ `magnet:?xt=urn:btih:${hash}&tr=x&tr=y`,+ `magnet:?xt=urn:btih:${hash}&tr=x&tr=y`,+ ],+ ])('preserves the executable representation of %s', (input, requestUrl) => {+ const result = analyzeDownloadSource(input)+ expect(result).toMatchObject({ status: 'accepted', requestUrl })+ expect(downloadSourceAnalysisSchema.safeParse(result).success).toBe(true)+ if (result.status === 'accepted')+ expect(analyzeDownloadSource(result.sourceUrl)).toEqual(result)+ })++ it.each([+ ['example.com/a', 'missingScheme'],+ ['https://a/\tfile', 'controlCharacter'],+ ['https://a/\0file', 'controlCharacter'],+ ['https://a/\u007ffile', 'controlCharacter'],+ ['https://a/\ud800', 'invalidUnicode'],+ ['https://a:70000/f', 'invalidPort'],+ ['https://[:::1]/a', 'invalidHost'],+ ['https://user:pass@a/f', 'credentialsInUrl'],+ ['https://@a/f', 'credentialsInUrl'],+ ['file:///tmp/a', 'unsupportedProtocol'],+ ['ftps://a/f', 'unsupportedProtocol'],+ ['sftp://a/f', 'unsupportedProtocol'],+ ['magnet:?xt=urn:btih:bad', 'invalidMagnet'],+ ])(+ 'rejects %s before a forgiving parser can hide the error',+ (input, reason) => {+ expect(analyzeDownloadSource(input)).toMatchObject({+ status: 'rejected',+ diagnostic: { reason },+ })+ }+ )++ it.each([+ ['https://example.com?', 'ambiguousStructure'],+ ['https:example.com/a', 'ambiguousStructure'],+ ['https:////example.com/a', 'ambiguousStructure'],+ ['https://a/dir\\file', 'ambiguousBackslash'],+ ['https://good.test\\@other.test/a', 'ambiguousBackslash'],+ ['https://a/a b', 'unescapedCharacter'],+ ['https://a/file%ZZ', 'invalidPercentEncoding'],+ ['https://a/a/../b', 'ambiguousStructure'],+ ['https://a/%2e%2e/b', 'ambiguousStructure'],+ ['http://127.1/a', 'ambiguousStructure'],+ ['http://0x7f000001/a', 'ambiguousStructure'],+ ["https://a/?sig='value'", 'ambiguousStructure'],+ ])('offers a correction without executing %s', (input, reason) => {+ const result = analyzeDownloadSource(input)+ expect(result).toMatchObject({+ status: 'needsCorrection',+ diagnostic: { reason },+ })+ expect(result).not.toHaveProperty('requestUrl')+ })++ it('offers both meanings of a path backslash without modifying signed query data', () => {+ const result = analyzeDownloadSource('https://a/dir\\file?sig=%2f+%252F')+ expect(result).toMatchObject({+ corrections: [+ {+ action: 'usePathSeparators',+ url: 'https://a/dir/file?sig=%2f+%252F',+ },+ {+ action: 'encodeLiteralCharacters',+ url: 'https://a/dir%5Cfile?sig=%2f+%252F',+ },+ ],+ })+ })++ it('retains line positions, rejects internal tabs, and only trims ASCII spaces', () => {+ const result = analyzeDownloadInput(+ ` https://a/f \r\n\n${hash}\n\thttps://a/g`+ )+ expect(result.map(({ line, valid }) => ({ line, valid }))).toEqual([+ { line: 0, valid: true },+ { line: 2, valid: true },+ { line: 3, valid: false },+ ])+ })++ it('does not pick valid-looking lines out of an unsupported command', () => {+ expect(+ analyzeDownloadInput('curl --data x\nhttps://a/f').every(+ (line) => !line.valid+ )+ ).toBe(true)+ })+})diff --git a/src/shared/lib/download-source.ts b/src/shared/lib/download-source.tsnew file mode 100644index 00000000..fe5502ed--- /dev/null+++ b/src/shared/lib/download-source.ts@@ -0,0 +1,184 @@+import {+ type DownloadSourceAnalysis,+ MAX_DOWNLOAD_URL_BYTES,+ type SourceCorrection,+ type SourceProtocol,+ type SourceReason,+} from '@shared/schemas/download-source'+import { infoHashToMagnetUri } from '@shared/schemas/magnet-input'++function failure(+ reason: SourceReason,+ start: number,+ end: number,+ corrections: SourceCorrection[] = []+): DownloadSourceAnalysis {+ const diagnostic = { reason, start, end }+ return corrections.length+ ? { status: 'needsCorrection', diagnostic, corrections }+ : { status: 'rejected', diagnostic }+}++/** Syntax and representation only: this performs no network or access-policy checks. */+export function analyzeDownloadSource(+ raw: string,+ protocols: readonly SourceProtocol[] = ['http', 'https', 'ftp', 'magnet']+): DownloadSourceAnalysis {+ if (+ raw.length > MAX_DOWNLOAD_URL_BYTES ||+ new TextEncoder().encode(raw).length > MAX_DOWNLOAD_URL_BYTES+ )+ return failure('urlTooLong', 0, raw.length)+ for (let i = 0; i < raw.length; i++) {+ const code = raw.charCodeAt(i)+ if (code <= 31 || code === 127) return failure('controlCharacter', i, i + 1)+ if (code >= 0xd800 && code <= 0xdbff) {+ const next = raw.charCodeAt(i + 1)+ if (!(next >= 0xdc00 && next <= 0xdfff))+ return failure('invalidUnicode', i, i + 1)+ i+++ } else if (code >= 0xdc00 && code <= 0xdfff)+ return failure('invalidUnicode', i, i + 1)+ }+ const scheme = /^([a-z][a-z0-9+.-]*):/i.exec(raw)+ if (!scheme) return failure('missingScheme', 0, raw.length)+ const protocol = scheme[1].toLowerCase() as SourceProtocol+ if (!protocols.includes(protocol))+ return failure('unsupportedProtocol', 0, scheme[1].length)+ const badPercent = /%(?![0-9a-f]{2})/i.exec(raw)+ if (badPercent)+ return failure(+ 'invalidPercentEncoding',+ badPercent.index,+ badPercent.index + 1,+ [+ {+ action: 'encodeLiteralCharacters',+ url: raw.replace(/%(?![0-9a-f]{2})/gi, '%25'),+ },+ ]+ )+ if (protocol === 'magnet') {+ if (!/^magnet:\?/i.test(raw)) return failure('invalidMagnet', 0, raw.length)+ const topics = new URLSearchParams(+ raw.slice(raw.indexOf('?') + 1).split('#')[0]+ ).getAll('xt')+ if (+ !topics.some(+ (topic) =>+ /^urn:btih:/i.test(topic) &&+ topic.slice(9) === topic.slice(9).trim() &&+ infoHashToMagnetUri(topic.slice(9))+ )+ )+ return failure('invalidMagnet', 0, raw.length)+ const uri = `magnet:${raw.slice(scheme[0].length)}`+ return {+ status: 'accepted',+ protocol,+ sourceUrl: uri,+ requestUrl: uri,+ host: '',+ }+ }+ // A reverse solidus is data in a query, but changes the target in an authority/path.+ const queryStart = raw.search(/[?#]/)+ const structuralEnd = queryStart < 0 ? raw.length : queryStart+ const backslash = raw.slice(0, structuralEnd).indexOf('\\')+ if (backslash >= 0) {+ const prefix = raw.slice(0, structuralEnd)+ const suffix = raw.slice(structuralEnd)+ const pathStart = raw.indexOf('/', scheme[0].length + 2)+ const corrections: SourceCorrection[] = [+ {+ action: 'usePathSeparators',+ url: prefix.replaceAll('\\', '/') + suffix,+ },+ ]+ if (+ raw.startsWith('//', scheme[0].length) &&+ pathStart >= 0 &&+ backslash >= pathStart+ )+ corrections.push({+ action: 'encodeLiteralCharacters',+ url: prefix.replaceAll('\\', '%5C') + suffix,+ })+ return failure('ambiguousBackslash', backslash, backslash + 1, corrections)+ }+ let parsed: URL+ try {+ parsed = new URL(raw)+ } catch {+ const authority = raw.slice(scheme[0].length + 2).split(/[/?#]/)[0]+ return failure(+ /:\d*[^\d\]]*$/.test(authority) || /:\d+$/.test(authority)+ ? 'invalidPort'+ : 'invalidHost',+ scheme[0].length,+ structuralEnd+ )+ }+ const parts =+ /^[a-z][a-z0-9+.-]*:\/\/([^/?#]+)([^?#]*)(\?[^#]*)?(#.*)?$/i.exec(raw)+ if (!parts || !parsed.hostname)+ return failure('ambiguousStructure', scheme[0].length, structuralEnd, [+ { action: 'useCanonicalUrl', url: parsed.href },+ ])+ const [, authority, path, query = '', fragment = ''] = parts+ // Fetch drops an empty query marker while aria2 preserves it. Do not let+ // discovery and download select different signed request targets.+ if (query === '?')+ return failure(+ 'ambiguousStructure',+ raw.indexOf('?'),+ raw.indexOf('?') + 1,+ [{ action: 'useCanonicalUrl', url: raw.replace(/\?(?=#|$)/, '') }]+ )+ if (authority.includes('@'))+ return failure(+ 'credentialsInUrl',+ scheme[0].length + 2,+ scheme[0].length + 2 + authority.length+ )+ const space = raw.search(/[ <>"`{}|^]/)+ if (space >= 0)+ return failure('unescapedCharacter', space, space + 1, [+ {+ action: 'encodeLiteralCharacters',+ url: raw.replace(/[ <>"`{}|^]/g, (char) => encodeURIComponent(char)),+ },+ ])+ const encodeUnicode = (part: string) =>+ part.replace(/[^\x20-\x7e]/gu, (char) => encodeURIComponent(char))+ const requestPath = encodeUnicode(path || '/')+ const requestQuery = encodeUnicode(query)+ // WHATWG removes literal/encoded dot segments and expands legacy IPv4 spellings.+ const rawHost = authority.startsWith('[')+ ? authority.slice(0, authority.indexOf(']') + 1)+ : authority.split(':')[0]+ const hostRewritten =+ !rawHost.startsWith('[') &&+ /^[\x20-\x7e]+$/.test(rawHost) &&+ rawHost.toLowerCase() !== parsed.hostname+ if (+ hostRewritten ||+ requestPath !== parsed.pathname ||+ (requestQuery && requestQuery !== '?' && requestQuery !== parsed.search)+ )+ return failure('ambiguousStructure', scheme[0].length + 2, structuralEnd, [+ { action: 'useCanonicalUrl', url: parsed.href },+ ])+ const requestUrl = `${protocol}://${parsed.host}${requestPath}${requestQuery}`+ const sourceUrl = requestUrl + encodeUnicode(fragment)+ // The canonical representation is ASCII and must pass the next admission gate.+ if (sourceUrl.length > MAX_DOWNLOAD_URL_BYTES)+ return failure('urlTooLong', 0, raw.length)+ return {+ status: 'accepted',+ protocol,+ requestUrl,+ sourceUrl,+ host: parsed.host,+ }+}diff --git a/src/shared/locales/en-US.json b/src/shared/locales/en-US.jsonindex 68216209..8a20f961 100644--- a/src/shared/locales/en-US.json+++ b/src/shared/locales/en-US.json@@ -854,7 +854,7 @@"title": "New Task","links": "Links","torrent": "Torrent",- "urlPlaceholder": "Enter URL, magnet link...",+ "urlPlaceholder": "Enter a URL, magnet link, or BT info hash…","dropTorrent": "Drop .torrent file here or click to select","clearSelection": "Clear selection","createFailed": "Failed to create download task.",@@ -863,6 +863,8 @@"urlsCount_one": "{{count}} URL","urlsCount_other": "{{count}} URLs","urlsWithInvalid": "{{valid}} valid, {{invalid}} invalid",+ "validUrlCount": "{{count}} valid",+ "invalidUrlCount": "{{count}} invalid","urlsLabel": "URLs","advanced": "Advanced","filename": "Filename",@@ -903,6 +905,35 @@},"adding": "Adding…","interpretedMagnet": "Magnet link detected",+ "interpretedInfoHash": "BT info hash converted to a magnet link",+ "unsupportedCurl": "This cURL command cannot be imported faithfully. Copy the URL or a Bash GET command with supported options.",+ "invalidJson": "Expected a JSON URL string or an array of URL strings.",+ "interpretedJson": "URLs imported from JSON",+ "sourceLine": "Line {{line}}",+ "sourceCorrections": {+ "useCanonicalUrl": "Use this expanded URL",+ "usePathSeparators": "Treat backslashes as path separators",+ "encodeLiteralCharacters": "Encode as literal characters"+ },+ "sourceErrors": {+ "missingScheme": "Include the URL scheme, such as https://.",+ "invalidHost": "The URL host is missing or invalid.",+ "invalidPort": "The URL port is invalid.",+ "controlCharacter": "Remove control characters from the URL.",+ "invalidUnicode": "The URL contains invalid Unicode.",+ "ambiguousBackslash": "A backslash makes the host or path ambiguous. Choose how to interpret it.",+ "invalidPercentEncoding": "A percent sign must be followed by two hexadecimal digits.",+ "credentialsInUrl": "Use the authentication fields instead of credentials in the URL.",+ "unsupportedProtocol": "This URL protocol is not supported for this download.",+ "urlTooLong": "The URL exceeds the 16 KiB limit.",+ "tooManySources": "Input exceeds the allowed number or size of links.",+ "ambiguousStructure": "The URL parser would change this address. Review the expanded URL.",+ "unescapedCharacter": "Encode spaces and reserved characters explicitly.",+ "invalidMagnet": "The magnet link needs a supported BT info hash in its xt parameter.",+ "mixedProtocols": "Mirrors of one download must use the same protocol family.",+ "unsupportedInput": "This input container was not imported. Paste a URL or a supported JSON or Bash cURL input.",+ "unsupportedRequestOptions": "HTTP headers cannot be applied to an FTP download."+ },"interpretedCurl": "cURL command parsed","filterBy": {"video": "Video",@@ -919,7 +950,9 @@"selectionTimeout": {"started": "File selection timed out: downloading all files in {{name}}","failed": "Could not start {{name}} automatically. Open task details to select files and retry."- }+ },+ "undoCorrection": "Undo URL correction",+ "submissionUnconfirmed": "The result is unconfirmed. Retry will check the original request before creating another task."},"detail": {"peers": "Peers: {{count}}",diff --git a/src/shared/locales/zh-CN.json b/src/shared/locales/zh-CN.jsonindex 6b1a27a8..2c79993a 100644--- a/src/shared/locales/zh-CN.json+++ b/src/shared/locales/zh-CN.json@@ -843,7 +843,7 @@"title": "新建任务","links": "链接","torrent": "种子",- "urlPlaceholder": "输入 URL、磁力链接…",+ "urlPlaceholder": "输入 URL、磁力链接或 BT 哈希值…","dropTorrent": "拖拽 .torrent 文件到此处,或点击选择","clearSelection": "清除选择","createFailed": "创建下载任务失败。",@@ -851,6 +851,8 @@"parseFailed": "解析种子文件失败。","urlsCount_other": "{{count}} 个 URL","urlsWithInvalid": "{{valid}} 个有效,{{invalid}} 个无效",+ "validUrlCount": "{{count}} 个有效",+ "invalidUrlCount": "{{count}} 个无效","urlsLabel": "链接","advanced": "高级","filename": "文件名",@@ -891,6 +893,35 @@},"adding": "添加中…","interpretedMagnet": "已识别磁力链接",+ "interpretedInfoHash": "已将 BT 哈希值转换为磁力链接",+ "unsupportedCurl": "无法准确导入此 cURL 命令。请复制 URL,或使用受支持选项的 Bash GET 命令。",+ "invalidJson": "请输入 JSON 格式的 URL 字符串或 URL 字符串数组。",+ "interpretedJson": "已从 JSON 导入链接",+ "sourceLine": "第 {{line}} 行",+ "sourceCorrections": {+ "useCanonicalUrl": "使用此展开后的地址",+ "usePathSeparators": "将反斜杠作为路径分隔符",+ "encodeLiteralCharacters": "按字面字符编码"+ },+ "sourceErrors": {+ "missingScheme": "请补全 URL 协议,例如 https://。",+ "invalidHost": "URL 缺少主机名,或主机名无效。",+ "invalidPort": "URL 端口无效。",+ "controlCharacter": "请移除 URL 中的控制字符。",+ "invalidUnicode": "URL 包含无效的 Unicode 字符。",+ "ambiguousBackslash": "反斜杠使主机或路径存在歧义,请选择其含义。",+ "invalidPercentEncoding": "百分号后必须紧跟两位十六进制数字。",+ "credentialsInUrl": "请使用认证字段,不要在 URL 中嵌入凭据。",+ "unsupportedProtocol": "此下载不支持该 URL 协议。",+ "urlTooLong": "URL 超过 16 KiB 长度限制。",+ "tooManySources": "输入的链接数量或文本大小超过限制。",+ "ambiguousStructure": "解析器会改变此地址,请核对展开后的 URL。",+ "unescapedCharacter": "请明确编码空格和保留字符。",+ "invalidMagnet": "磁力链接的 xt 参数需要包含受支持的 BT 哈希值。",+ "mixedProtocols": "同一下载的镜像地址必须属于相同协议族。",+ "unsupportedInput": "未能导入此输入格式,请粘贴 URL 或受支持的 JSON、Bash cURL 内容。",+ "unsupportedRequestOptions": "FTP 下载不能应用 HTTP 请求头。"+ },"interpretedCurl": "已解析 cURL 命令","filterBy": {"video": "视频",@@ -907,7 +938,9 @@"selectionTimeout": {"started": "选择文件已超时,开始下载 {{name}} 的全部文件","failed": "无法自动开始下载 {{name}},请打开任务详情,选择文件后重试。"- }+ },+ "undoCorrection": "撤销 URL 修正",+ "submissionUnconfirmed": "结果尚未确认。再次提交时会先核对原请求,避免重复创建任务。"},"detail": {"peers": "节点:{{count}}",diff --git a/src/shared/locales/zh-TW.json b/src/shared/locales/zh-TW.jsonindex b3043f45..35f196f2 100644--- a/src/shared/locales/zh-TW.json+++ b/src/shared/locales/zh-TW.json@@ -843,7 +843,7 @@"title": "新增任務","links": "連結","torrent": "Torrent",- "urlPlaceholder": "輸入 URL、Magnet 連結…",+ "urlPlaceholder": "輸入 URL、Magnet 連結或 BT 雜湊值…","dropTorrent": "將 .torrent 檔案拖放到這裡,或按一下以選擇檔案","clearSelection": "清除選取項目","createFailed": "無法建立下載任務。",@@ -851,6 +851,8 @@"parseFailed": "無法解析 Torrent 檔案。","urlsCount_other": "{{count}} 個 URL","urlsWithInvalid": "{{valid}} 個有效,{{invalid}} 個無效",+ "validUrlCount": "{{count}} 個有效",+ "invalidUrlCount": "{{count}} 個無效","urlsLabel": "URL","advanced": "進階","filename": "檔案名稱",@@ -891,6 +893,35 @@},"adding": "正在新增…","interpretedMagnet": "已偵測到 Magnet 連結",+ "interpretedInfoHash": "已將 BT 雜湊值轉換為 Magnet 連結",+ "unsupportedCurl": "無法準確匯入此 cURL 命令。請複製 URL,或使用支援選項的 Bash GET 命令。",+ "invalidJson": "請輸入 JSON 格式的 URL 字串或 URL 字串陣列。",+ "interpretedJson": "已從 JSON 匯入連結",+ "sourceLine": "第 {{line}} 行",+ "sourceCorrections": {+ "useCanonicalUrl": "使用此展開後的位址",+ "usePathSeparators": "將反斜線作為路徑分隔符號",+ "encodeLiteralCharacters": "按字面字元編碼"+ },+ "sourceErrors": {+ "missingScheme": "請補全 URL 協定,例如 https://。",+ "invalidHost": "URL 缺少主機名稱,或主機名稱無效。",+ "invalidPort": "URL 連接埠無效。",+ "controlCharacter": "請移除 URL 中的控制字元。",+ "invalidUnicode": "URL 包含無效的 Unicode 字元。",+ "ambiguousBackslash": "反斜線使主機或路徑存在歧義,請選擇其含義。",+ "invalidPercentEncoding": "百分號後必須緊接兩位十六進位數字。",+ "credentialsInUrl": "請使用認證欄位,不要在 URL 中嵌入憑證。",+ "unsupportedProtocol": "此下載不支援該 URL 協定。",+ "urlTooLong": "URL 超過 16 KiB 長度限制。",+ "tooManySources": "輸入的連結數量或文字大小超過限制。",+ "ambiguousStructure": "解析器會改變此位址,請核對展開後的 URL。",+ "unescapedCharacter": "請明確編碼空格和保留字元。",+ "invalidMagnet": "Magnet 連結的 xt 參數需要包含支援的 BT 雜湊值。",+ "mixedProtocols": "同一下載的鏡像位址必須屬於相同協定族。",+ "unsupportedInput": "未能匯入此輸入格式,請貼上 URL 或支援的 JSON、Bash cURL 內容。",+ "unsupportedRequestOptions": "FTP 下載不能套用 HTTP 請求標頭。"+ },"interpretedCurl": "已解析 cURL 命令","filterBy": {"video": "影片",@@ -907,7 +938,9 @@"selectionTimeout": {"started": "選擇檔案已逾時,開始下載 {{name}} 的全部檔案","failed": "無法自動開始下載 {{name}},請開啟任務詳細資料,選擇檔案後重試。"- }+ },+ "undoCorrection": "復原 URL 修正",+ "submissionUnconfirmed": "結果尚未確認。再次提交時會先核對原請求,避免重複建立任務。"},"detail": {"peers": "對等節點:{{count}}",diff --git a/src/shared/schemas/add-task.test.ts b/src/shared/schemas/add-task.test.tsindex a4342711..bf1de12b 100644--- a/src/shared/schemas/add-task.test.ts+++ b/src/shared/schemas/add-task.test.ts@@ -168,6 +168,36 @@ describe('taskCreateRequestSchema', () => {})describe('formValuesToTaskCreateRequests', () => {+ it('routes bare hashes and URLs in a batch to the correct task types', () => {+ const hash = 'a03e3f9a05341aa336e9d9d3f06b33cddafe0bdc'+ const base32 = 'U3VG6P2M2T4K4I7NL4ZATCYXMVTZHDAL'+ const url = `https://example.com/${hash}?sig=A%2Fb%5Cc`+ const reqs = formValuesToTaskCreateRequests({+ tab: 'links',+ urls: ` ${hash.toUpperCase()} \r\n${url}\n${base32.toLowerCase()}`,+ saveDir: '/d',+ })+ expect(reqs).toMatchObject([+ {+ type: 'bt',+ payload: { kind: 'magnet', uri: `magnet:?xt=urn:btih:${hash}` },+ },+ { type: 'http', uris: [url] },+ {+ type: 'bt',+ payload: { kind: 'magnet', uri: `magnet:?xt=urn:btih:${base32}` },+ },+ ])+ expect(+ reqs.every(+ (request) => taskCreateRequestSchema.safeParse(request).success+ )+ ).toBe(true)+ expect(+ formValuesToTaskCreateRequest({ tab: 'links', urls: hash, saveDir: '/d' })+ ).toEqual(reqs[0])+ })+it('creates one request per link line', () => {const reqs = formValuesToTaskCreateRequests({tab: 'links',diff --git a/src/shared/schemas/add-task.ts b/src/shared/schemas/add-task.tsindex 57733885..d391d611 100644--- a/src/shared/schemas/add-task.ts+++ b/src/shared/schemas/add-task.ts@@ -1,5 +1,8 @@+import { analyzeDownloadInput } from '@shared/lib/download-source-input'import { MAX_TORRENT_BASE64_SIZE } from '@shared/lib/torrent-meta'import { z } from 'zod'+import { MAX_MIRROR_URIS, type SourceFailure } from './download-source'+import { infoHashToMagnetUri } from './magnet-input'const torrentFileSchema = z.object({index: z.number().int().nonnegative(),@@ -17,11 +20,17 @@ const torrentMetaSchema = z.object({export { torrentMetaSchema }+const httpHeaderSchema = z.object({+ name: z.string().min(1),+ value: z.string(),+})+const linksTabSchema = z.object({tab: z.literal('links'),urls: z.string().min(1, { message: 'task.add.errors.urlsRequired' }),saveDir: z.string().min(1, { message: 'task.add.errors.saveDirRequired' }),filename: z.string().optional(),+ extraHeaders: z.array(httpHeaderSchema).optional(),split: z.number().int().min(1).max(128).optional(),userAgent: z.string().optional(),referer: z.string().optional(),@@ -67,14 +76,10 @@ export type AddTaskFormValues = z.infer<typeof addTaskFormSchema>// ── Engine-agnostic request ─────────────────────────────────-const httpHeaderSchema = z.object({- name: z.string().min(1),- value: z.string(),-})-const httpTaskRequestSchema = z.object({type: z.literal('http'),- uris: z.array(z.url()).min(1),+ requestId: z.uuid().optional(),+ uris: z.array(z.string()).min(1).max(MAX_MIRROR_URIS),saveDir: z.string().min(1),filename: z.string().optional(),connections: z.number().int().min(1).max(128).optional(),@@ -158,6 +163,7 @@ export type TaskCreateSuccessResult = {export type TaskCreateCommandResult =| TaskCreateSuccessResult+ | { outcome: 'invalid-source'; failure: SourceFailure }| {outcome: 'conflict'conflict: TorrentDuplicateConflict@@ -260,7 +266,7 @@ function compactHeader(name: string, value?: string) {function splitUrlLines(raw: string): string[] {return raw.split('\n')- .map((l) => l.trim())+ .map((l) => infoHashToMagnetUri(l) ?? l.trim()).filter((l) => l.length > 0)}@@ -276,7 +282,9 @@ export function formValuesToTaskCreateRequests(v: AddTaskFormValues): TaskCreateRequest[] {if (v.tab !== 'links') return [formValuesToTaskCreateRequest(v)]- const lines = splitUrlLines(v.urls)+ const lines = analyzeDownloadInput(v.urls)+ .filter((line) => line.valid)+ .map((line) => line.url)const filename = lines.length === 1 ? v.filename : undefinedreturn lines.map((line) =>formValuesToTaskCreateRequest({ ...v, urls: line, filename })@@ -300,6 +308,7 @@ export function formValuesToTaskCreateRequest(}}const headers = [+ ...(v.extraHeaders ?? []),...compactHeader('User-Agent', v.userAgent),...compactHeader('Referer', v.referer),...compactHeader('Cookie', v.cookie),diff --git a/src/shared/schemas/download-source.ts b/src/shared/schemas/download-source.tsnew file mode 100644index 00000000..5ac9223f--- /dev/null+++ b/src/shared/schemas/download-source.ts@@ -0,0 +1,75 @@+import { z } from 'zod'++export const MAX_DOWNLOAD_URL_BYTES = 16 * 1024+export const MAX_MIRROR_URIS = 128+export const MAX_DOWNLOAD_INPUT_LINES = 1000+export const MAX_DOWNLOAD_INPUT_BYTES = 1024 * 1024++export const sourceProtocolSchema = z.enum(['http', 'https', 'ftp', 'magnet'])+export const sourceReasonSchema = z.enum([+ 'missingScheme',+ 'invalidHost',+ 'invalidPort',+ 'controlCharacter',+ 'invalidUnicode',+ 'ambiguousBackslash',+ 'invalidPercentEncoding',+ 'credentialsInUrl',+ 'unsupportedProtocol',+ 'urlTooLong',+ 'tooManySources',+ 'ambiguousStructure',+ 'unescapedCharacter',+ 'invalidMagnet',+ 'mixedProtocols',+ 'unsupportedInput',+ 'unsupportedRequestOptions',+])+export const sourceDiagnosticSchema = z.object({+ reason: sourceReasonSchema,+ start: z.number().int().nonnegative(),+ end: z.number().int().nonnegative(),+})+export const sourceCorrectionSchema = z.object({+ action: z.enum([+ 'useCanonicalUrl',+ 'usePathSeparators',+ 'encodeLiteralCharacters',+ ]),+ url: z.string(),+})+export const downloadSourceAnalysisSchema = z.discriminatedUnion('status', [+ z.object({+ status: z.literal('accepted'),+ protocol: sourceProtocolSchema,+ sourceUrl: z.string(),+ requestUrl: z.string(),+ host: z.string(),+ }),+ z.object({+ status: z.literal('needsCorrection'),+ diagnostic: sourceDiagnosticSchema,+ corrections: z.array(sourceCorrectionSchema),+ }),+ z.object({+ status: z.literal('rejected'),+ diagnostic: sourceDiagnosticSchema,+ }),+])+export const sourceFailureSchema = z.object({+ stage: z.enum(['input', 'plugin', 'resolution', 'engine', 'recovery']),+ index: z.number().int().nonnegative(),+ diagnostic: sourceDiagnosticSchema,+})+export type SourceProtocol = z.infer<typeof sourceProtocolSchema>+export type SourceReason = z.infer<typeof sourceReasonSchema>+export type SourceDiagnostic = z.infer<typeof sourceDiagnosticSchema>+export type SourceCorrection = z.infer<typeof sourceCorrectionSchema>+export type DownloadSourceAnalysis = z.infer<+ typeof downloadSourceAnalysisSchema+>+export type AcceptedDownloadSource = Extract<+ DownloadSourceAnalysis,+ { status: 'accepted' }+>+export type SourceFailure = z.infer<typeof sourceFailureSchema>diff --git a/src/shared/schemas/magnet-input.test.ts b/src/shared/schemas/magnet-input.test.tsnew file mode 100644index 00000000..0b28c5df--- /dev/null+++ b/src/shared/schemas/magnet-input.test.ts@@ -0,0 +1,47 @@+import { describe, expect, it } from 'vitest'+import { infoHashToMagnetUri, normalizeMagnetInputLines } from './magnet-input'++const HEX_HASH = 'a03e3f9a05341aa336e9d9d3f06b33cddafe0bdc'+const BASE32_HASH = 'U3VG6P2M2T4K4I7NL4ZATCYXMVTZHDAL'++describe('infoHashToMagnetUri', () => {+ it.each([+ [HEX_HASH, HEX_HASH],+ [HEX_HASH.toUpperCase(), HEX_HASH],+ [` \t${HEX_HASH}\r\n`, HEX_HASH],+ [BASE32_HASH, BASE32_HASH],+ [BASE32_HASH.toLowerCase(), BASE32_HASH],+ ])('expands a complete BT info hash: %s', (input, hash) => {+ expect(infoHashToMagnetUri(input)).toBe(`magnet:?xt=urn:btih:${hash}`)+ })++ it.each([+ '',+ HEX_HASH.slice(1),+ `${HEX_HASH}0`,+ `g${HEX_HASH.slice(1)}`,+ '0123456789abcdef'.repeat(2),+ 'a'.repeat(64),+ `0${BASE32_HASH.slice(1)}`,+ `${BASE32_HASH}=`,+ `${HEX_HASH.slice(0, 20)} ${HEX_HASH.slice(20)}`,+ `${HEX_HASH.slice(0, 20)}\\${HEX_HASH.slice(20)}`,+ `hash: ${HEX_HASH}`,+ `https://example.com/${HEX_HASH}?sig=a%2Fb%5Cc`,+ `magnet:?xt=urn:btih:${HEX_HASH}&tr=https%3A%2F%2Ftracker.test`,+ `${HEX_HASH}\n${BASE32_HASH}`,+ ])('does not infer a bare info hash from %s', (input) => {+ expect(infoHashToMagnetUri(input)).toBeNull()+ })+})++describe('normalizeMagnetInputLines', () => {+ it('expands mixed hash lines while preserving other text and line positions', () => {+ const url = `https://example.com/${HEX_HASH}?sig=A%2Fb%5Cc`+ const magnet = `magnet:?xt=urn:btih:${HEX_HASH.toUpperCase()}&dn=a+b&tr=x&tr=y`+ const input = ` ${HEX_HASH} \r\n\n${url}\n${BASE32_HASH.toLowerCase()}\n bad text \n${magnet}`+ const expected = `magnet:?xt=urn:btih:${HEX_HASH}\n\n${url}\nmagnet:?xt=urn:btih:${BASE32_HASH}\n bad text \n${magnet}`+ expect(normalizeMagnetInputLines(input)).toBe(expected)+ expect(normalizeMagnetInputLines(expected)).toBe(expected)+ })+})diff --git a/src/shared/schemas/magnet-input.ts b/src/shared/schemas/magnet-input.tsnew file mode 100644index 00000000..8aa0ba68--- /dev/null+++ b/src/shared/schemas/magnet-input.ts@@ -0,0 +1,32 @@+import { z } from 'zod'++// BEP 9 permits a 160-bit btih encoded as 40 hex or 32 Base32 characters.+const bareInfoHashSchema = z+ .string()+ .trim()+ .pipe(+ z.union([+ z+ .string()+ .regex(/^[0-9a-f]{40}$/i)+ .toLowerCase(),+ z+ .string()+ .regex(/^[a-z2-7]{32}$/i)+ .toUpperCase(),+ ])+ )++/** Only complete bare hashes are expanded; URLs and surrounding prose are untouched. */+export function infoHashToMagnetUri(input: string): string | null {+ const result = bareInfoHashSchema.safeParse(input)+ return result.success ? `magnet:?xt=urn:btih:${result.data}` : null+}++/** Preserve line order, blank lines, and unrecognized input for inline editing. */+export function normalizeMagnetInputLines(input: string): string {+ return input+ .split('\n')+ .map((line) => infoHashToMagnetUri(line) ?? line)+ .join('\n')+}