A full-featured download manager.
fix(bridge): sanitize browser cookies before engine dispatch (#2469)
Dr_rOot868cf23f0abc
diff --git a/src/core/bridge-receiver/pipelines/direct-pipeline.test.ts b/src/core/bridge-receiver/pipelines/direct-pipeline.test.tsindex e7d915f8..4bac8acf 100644--- a/src/core/bridge-receiver/pipelines/direct-pipeline.test.ts+++ b/src/core/bridge-receiver/pipelines/direct-pipeline.test.ts@@ -1,3 +1,6 @@+import { TaskCookieError } from '@core/engine/task-cookie-error'+import { TaskCookieAdmissionError } from '@core/task/task-cookie-admission'+import { ErrorCodes } from '@motrix/mdxp'import { taskCreateRequestSchema } from '@shared/schemas/add-task'import { describe, expect, it, vi } from 'vitest'import type { AdaptedDirect } from '../submit-download-adapter'@@ -36,6 +39,40 @@ function buildAdapted(): AdaptedDirect {}describe('DirectPipeline.dispatch', () => {+ it.each(['noUsableCookies', 'count'] as const)(+ 'reports pre-dispatch %s as a definite rejection',+ async (reason) => {+ const diagnostic = { index: 1, field: 'name', reason }+ const createTask = vi+ .fn()+ .mockRejectedValue(new TaskCookieAdmissionError(diagnostic))+ const pipeline = new DirectPipeline({ createTask, removeTask: vi.fn() })+ await expect(pipeline.dispatch(buildAdapted())).rejects.toMatchObject({+ code: ErrorCodes.InvalidParams,+ data: {+ appCode: 'download-cookies-rejected',+ retryable: false,+ context: { diagnostic },+ },+ })+ expect(createTask).toHaveBeenCalledOnce()+ }+ )++ it.each([+ new Error('RPC timed out'),+ new TaskCookieError({+ index: 0,+ field: 'name',+ reason: 'syntax',+ }),+ ])('keeps post-admission failures uncertain', async (error) => {+ const pipeline = new DirectPipeline({+ createTask: vi.fn().mockRejectedValue(error),+ removeTask: vi.fn(),+ })+ await expect(pipeline.dispatch(buildAdapted())).rejects.toBe(error)+ })it('calls createTask with HTTP type, headers, cookies, referer, source meta', async () => {const createTask = vi.fn(async () => ({gid: 'gid-1',diff --git a/src/core/bridge-receiver/pipelines/direct-pipeline.ts b/src/core/bridge-receiver/pipelines/direct-pipeline.tsindex ad59e6c8..0e897117 100644--- a/src/core/bridge-receiver/pipelines/direct-pipeline.ts+++ b/src/core/bridge-receiver/pipelines/direct-pipeline.ts@@ -1,4 +1,6 @@import type { CreateTaskOptions } from '@core/task/create-task-handler'+import { TaskCookieAdmissionError } from '@core/task/task-cookie-admission'+import { ErrorCodes, makeMdxpError } from '@motrix/mdxp'import type { AdaptedDirect } from '../submit-download-adapter'export interface DirectPipelineDeps {@@ -53,12 +55,24 @@ export class DirectPipeline {headers,proxy: undefined,}- const { taskId } = await this.deps.createTask(req, undefined, {- source: 'bridge',- sourceMeta: adapted.sourceMeta,- // Even [] requests an isolated task cookie jar in the engine.- cookies: adapted.cookies,- })+ const { taskId } = await this.deps+ .createTask(req, undefined, {+ source: 'bridge',+ sourceMeta: adapted.sourceMeta,+ // Even [] requests an isolated task cookie jar in the engine.+ cookies: adapted.cookies,+ })+ .catch((error: unknown) => {+ // Only admission before side effects proves that browser fallback is safe.+ if (error instanceof TaskCookieAdmissionError) {+ throw makeMdxpError(ErrorCodes.InvalidParams, error.message, {+ appCode: 'download-cookies-rejected',+ retryable: false,+ context: { diagnostic: error.diagnostic },+ })+ }+ throw error+ })return { taskId }}diff --git a/src/core/bridge-receiver/submit-download-adapter.ts b/src/core/bridge-receiver/submit-download-adapter.tsindex 07d4ac1a..b4286db3 100644--- a/src/core/bridge-receiver/submit-download-adapter.ts+++ b/src/core/bridge-receiver/submit-download-adapter.ts@@ -242,7 +242,7 @@ export class SubmitDownloadAdapter {httpOnly: cookie.httpOnly,...(cookie.expiresAt === undefined? {}- : { expiresAt: Math.max(0, Math.floor(cookie.expiresAt)) }),+ : { expiresAt: Math.floor(cookie.expiresAt) }),})),sourceMeta: this.makeSourceMeta('direct', input, source, meta),pageUrl: source.pageUrl,diff --git a/src/core/bridge-receiver/task-cookies.integration.test.ts b/src/core/bridge-receiver/task-cookies.integration.test.tsindex 6c9baf0a..4a2b06ad 100644--- a/src/core/bridge-receiver/task-cookies.integration.test.ts+++ b/src/core/bridge-receiver/task-cookies.integration.test.ts@@ -4,7 +4,7 @@ import { tmpdir } from 'node:os'import path from 'node:path'import { handleCreateTask } from '@core/task/create-task-handler'import { TaskManager } from '@core/task/task-manager'-import type { DownloadSubmitParams } from '@motrix/mdxp'+import { type DownloadSubmitParams, ErrorCodes } from '@motrix/mdxp'import { ErrorCode } from '@shared/errors'import { DEFAULT_ENGINE_SETTINGS } from '@shared/schemas/engine-settings'import { DEFAULT_PROXY_SETTINGS } from '@shared/schemas/proxy-settings'@@ -169,6 +169,128 @@ describe.skipIf(!bundledAria2Exists() || !canBindLoopbackTcp())(}}, 20_000)+ it('cleans incompatible cookies for the released engine and rejects unsafe jars before dispatch', async () => {+ const invalidCookies = [+ { name: '', value: 'bare', domain: '127.0.0.1' },+ { name: '中文', value: 'account-A', domain: '127.0.0.1' },+ { name: 'a b', value: 'account-B', domain: '127.0.0.1' },+ ]+ const validCookies = [+ { name: 'sid', value: 'account-A', domain: '127.0.0.1' },+ ...Array.from({ length: 49 }, (_, i) => ({+ name: `tracking${i}`,+ value: `value${i}`,+ domain: '127.0.0.1',+ })),+ ]+ const cookies = [...validCookies, ...invalidCookies]+ const tasks = new TaskManager()+ type Deps = Parameters<typeof handleCreateTask>[1]+ const deps = {+ adapter: wired.adapter,+ settingsManager: {+ getApp: () => ({ defaultSaveDir: root }),+ getEngine: () => DEFAULT_ENGINE_SETTINGS,+ getProxy: () => DEFAULT_PROXY_SETTINGS,+ },+ finalNamePicker: { pick: async (_dir: string, name: string) => name },+ torrentMetaStore: {},+ taskManager: tasks,+ activityRecorder: { recordSubmitted: vi.fn() },+ eventBus: { emit: vi.fn() },+ publishTaskUpdate: vi.fn(),+ } as unknown as Deps+ const pipeline = new DirectPipeline({+ createTask: (request, _unused, options) =>+ handleCreateTask(request, deps, options),+ removeTask: async () => {},+ })+ const submitAdapter = new SubmitDownloadAdapter({+ getDefaultSaveDir: () => root,+ pickName: async (_dir, name) => name,+ mintTaskId: () => 'browser-names',+ })+ const adapted = await submitAdapter.adapt(+ {+ source: {+ pageUrl: base,+ pageTitle: 'Fixture',+ detectedAt: Date.now(),+ },+ selection: {+ kind: 'direct',+ primary: {+ url: `${base}/browser-names`,+ headers: {},+ refererPolicy: 'strict-origin-when-cross-origin',+ cookies: cookies.map((cookie) => ({+ ...cookie,+ path: '/',+ sameSite: 'lax',+ secure: false,+ httpOnly: false,+ })),+ },+ },+ meta: {+ suggestedFilename: 'browser-names.bin',+ qualityLabel: 'original',+ },+ },+ { extensionId: 'fixture', browser: 'chromium' }+ )+ if (adapted.kind !== 'direct') throw new Error('expected direct')+ const { taskId } = await pipeline.dispatch(adapted)+ const gid = tasks.getById(taskId)!.engineTaskId!+ await vi.waitFor(+ async () =>+ expect((await wired.rpc.tellStatus(gid)).status).toBe('complete'),+ { timeout: 10_000 }+ )+ const header = Buffer.from(+ received.get('/browser-names') ?? '',+ 'latin1'+ ).toString('utf8')+ const sentCookies = header+ .split(';')+ .map((s) => s.trim())+ .filter(Boolean)+ expect(sentCookies).toHaveLength(50)+ expect(sentCookies).toEqual(+ expect.arrayContaining(+ validCookies.map((cookie) => `${cookie.name}=${cookie.value}`)+ )+ )+ expect(await readFile(tasks.getById(taskId)!.diskPath, 'utf8')).toBe(+ 'REAL_FILE'+ )+ for (const [label, invalid] of [+ ['unusable', invalidCookies],+ [+ 'capacity',+ Array.from({ length: 51 }, (_, i) => ({+ name: `c${i}`,+ value: 'secret',+ domain: '127.0.0.1',+ })),+ ],+ ] as const) {+ await expect(+ pipeline.dispatch({+ ...adapted,+ primaryUrl: `${base}/${label}`,+ finalName: `${label}.bin`,+ cookies: [...invalid],+ })+ ).rejects.toMatchObject({+ code: ErrorCodes.InvalidParams,+ data: { appCode: 'download-cookies-rejected', retryable: false },+ })+ expect(received.has(`/${label}`)).toBe(false)+ expect(tasks.getAll()).toHaveLength(1)+ }+ })+it('restores a task cookie from the engine database after restart', async () => {const restartDir = path.join(root, 'restart-cookie')const databasePath = path.join(restartDir, 'aria2.db')diff --git a/src/core/engine/aria2/aria2-adapter.ts b/src/core/engine/aria2/aria2-adapter.tsindex b041721e..0f6b9b67 100644--- a/src/core/engine/aria2/aria2-adapter.ts+++ b/src/core/engine/aria2/aria2-adapter.ts@@ -2,6 +2,7 @@ import { createHash } from 'node:crypto'import { access, mkdir } from 'node:fs/promises'import path from 'node:path'import { setTimeout as delay } from 'node:timers/promises'+import { TaskCookieError } from '@core/engine/task-cookie-error'import { getLogger } from '@core/logger'import {extractAria2ProxyCredentials,@@ -51,6 +52,7 @@ import { legacyWirePath } from './aria2-legacy-path'import type { Aria2RpcClient } from './aria2-rpc-client'import { recommend } from './aria2-tuning'import { isConnectionLimitRangeError, isNotFoundError } from './error-utils'+import { prepareAria2TaskCookies } from './task-cookies'/*** Per-multicall cap for removeDownloadResults. One unbounded batch must@@ -338,6 +340,10 @@ export class Aria2Adapter implements EngineAdapter {return this.featureReport}+ prepareDownloadCookies(cookies: readonly DownloadCookie[]) {+ return prepareAria2TaskCookies(cookies)+ }+/*** Inject the feature report the EngineSupervisor already probed. Production* never calls `connect()`, so without this the adapter would keep its@@ -419,6 +425,19 @@ export class Aria2Adapter implements EngineAdapter {}async createDownload(params: CreateDownloadParams): Promise<string> {+ if (params.cookies !== undefined) {+ const prepared = prepareAria2TaskCookies(params.cookies)+ // Only admission may choose a reduced credential set. Later corruption or+ // mutation must not silently change a task after its durable intent exists.+ const incompatible = prepared.discarded.find(+ (d) => d.reason !== 'expired' && d.reason !== 'duplicate'+ )+ if (incompatible) throw new TaskCookieError(incompatible)+ params = {+ ...params,+ cookies: prepared.cookies,+ }+ }if (params.legacyCheckpointActivation &&!(await this.supportsLegacyHttpActivation())diff --git a/src/core/engine/aria2/task-cookies.test.ts b/src/core/engine/aria2/task-cookies.test.tsnew file mode 100644index 00000000..89be9179--- /dev/null+++ b/src/core/engine/aria2/task-cookies.test.ts@@ -0,0 +1,174 @@+import { describe, expect, it } from 'vitest'+import { TaskCookieError } from '../task-cookie-error'+import { prepareAria2TaskCookies } from './task-cookies'++const cookie = {+ name: 'sid',+ value: 'synthetic-secret',+ domain: '.example.com',+ path: '/',+}+const now = 1_800_000_000_000++describe('published aria2 cookie adaptation', () => {+ it('keeps usable credentials byte-for-byte while projecting fields and filtering incompatible records', () => {+ const input = [+ { ...cookie, sameSite: 'lax', secure: true, httpOnly: true },+ ...['', '中文', 'a b', 'a:b'].map((name) => ({ ...cookie, name })),+ { ...cookie, name: 'unicodeValue', value: '中文=原值' },+ ]+ const before = structuredClone(input)+ const result = prepareAria2TaskCookies(input, now)+ expect(result.cookies).toEqual([+ { ...cookie, secure: true, httpOnly: true },+ { ...cookie, name: 'unicodeValue', value: '中文=原值' },+ ])+ expect(result.discarded.map((d) => d.index)).toEqual([1, 2, 3, 4])+ expect(input).toEqual(before)+ input[0]!.value = 'changed later'+ expect(result.cookies[0]?.value).toBe('synthetic-secret')+ })++ it.each([+ { name: '', value: '' },+ { name: '', value: 'sid=secret' },+ { name: 'bad=name' },+ { name: 'a\nb' },+ { value: 'a\0b' },+ { value: 'a\rb' },+ { value: 'a\tb' },+ { value: 'a\x7fb' },+ { value: 'a;b' },+ { path: '' },+ { path: 'relative' },+ { path: '/a;b' },+ { domain: '' },+ { domain: '..example.com' },+ { domain: 'a..com' },+ { domain: 'example.com.' },+ { domain: 'bad/domain' },+ { domain: 'K.com' },+ { name: '\ud800' },+ { value: '\udfff' },+ { expiresAt: -1 },+ { expiresAt: Infinity },+ { expiresAt: Number.MAX_SAFE_INTEGER + 1 },+ { value: '界'.repeat(1365) },+ { secure: 'true' },+ ])(+ 'filters only the incompatible entry and never retains its contents in diagnostics: %j',+ (overrides) => {+ const result = prepareAria2TaskCookies(+ [cookie, { ...cookie, ...overrides }] as never,+ now+ )+ expect(result.cookies).toEqual([cookie])+ expect(result.discarded).toEqual([expect.objectContaining({ index: 1 })])+ expect(JSON.stringify(result.discarded)).not.toContain(cookie.value)+ expect(JSON.stringify(result.discarded)).not.toContain(cookie.domain)+ }+ )++ it('refuses a fully incompatible jar rather than silently creating an anonymous task', () => {+ expect(() =>+ prepareAria2TaskCookies([{ ...cookie, name: '' }], now)+ ).toThrow(TaskCookieError)+ try {+ prepareAria2TaskCookies([{ ...cookie, name: '' }], now)+ } catch (error) {+ expect(error).toMatchObject({ diagnostic: { reason: 'noUsableCookies' } })+ expect(JSON.stringify(error)).not.toContain(cookie.value)+ }+ expect(prepareAria2TaskCookies([], now)).toEqual({+ cookies: [],+ discarded: [],+ })+ expect(+ prepareAria2TaskCookies([{ ...cookie, expiresAt: now }], now)+ ).toMatchObject({ cookies: [], discarded: [{ reason: 'expired' }] })+ })++ it('applies byte limits without truncating multibyte values', () => {+ expect(+ prepareAria2TaskCookies([{ ...cookie, value: 'a'.repeat(4093) }], now)+ .cookies+ ).toHaveLength(1)+ const result = prepareAria2TaskCookies(+ [cookie, { ...cookie, name: 'long', value: 'a'.repeat(4093) }],+ now+ )+ expect(result.cookies).toEqual([cookie])+ expect(result.discarded).toEqual([+ { index: 1, field: 'nameValue', reason: 'size', byteLength: 4097 },+ ])+ })++ it('deduplicates by the engine identity, preserves the last scope and ignores expired entries', () => {+ const result = prepareAria2TaskCookies(+ [+ { ...cookie, domain: '.EXAMPLE.com', path: undefined, hostOnly: false },+ {+ ...cookie,+ domain: 'example.com',+ value: 'last',+ secure: true,+ hostOnly: true,+ },+ { ...cookie, value: 'expired', expiresAt: now - 1 },+ { ...cookie, name: '', expiresAt: 0 },+ ],+ now+ )+ expect(result.cookies).toEqual([+ {+ ...cookie,+ domain: 'example.com',+ value: 'last',+ secure: true,+ hostOnly: true,+ },+ ])+ expect(result.discarded.map((d) => d.reason)).toEqual([+ 'duplicate',+ 'expired',+ 'expired',+ ])+ })++ it('checks final jar capacity without arbitrarily selecting credentials', () => {+ const fifty = Array.from({ length: 50 }, (_, i) => ({+ ...cookie,+ name: `c${i}`,+ }))+ expect(+ prepareAria2TaskCookies([...fifty, { ...cookie, name: '' }], now).cookies+ ).toEqual(fifty)+ expect(() => prepareAria2TaskCookies([...fifty, cookie], now)).toThrow(+ TaskCookieError+ )+ expect(+ prepareAria2TaskCookies(Array(301).fill(cookie), now).cookies+ ).toEqual([cookie])+ const many = Array.from({ length: 300 }, (_, i) => ({+ ...cookie,+ name: `c${i}`,+ domain: `host${Math.floor(i / 50)}.example.com`,+ }))+ expect(prepareAria2TaskCookies(many, now).cookies).toEqual(many)+ expect(() => prepareAria2TaskCookies([...many, cookie], now)).toThrow(+ TaskCookieError+ )+ })++ it('filters array holes instead of serializing them as null cookie records', () => {+ const input = Array(2)+ input[1] = cookie+ expect(prepareAria2TaskCookies(input, now)).toMatchObject({+ cookies: [cookie],+ discarded: [{ index: 0, reason: 'type' }],+ })+ expect(() => prepareAria2TaskCookies(null as never, now)).toThrow(+ TaskCookieError+ )+ })+})diff --git a/src/core/engine/aria2/task-cookies.ts b/src/core/engine/aria2/task-cookies.tsnew file mode 100644index 00000000..8befc713--- /dev/null+++ b/src/core/engine/aria2/task-cookies.ts@@ -0,0 +1,138 @@+import { isIP } from 'node:net'+import { z } from 'zod'+import type { DownloadCookie, PreparedDownloadCookies } from '../engine-adapter'+import {+ type TaskCookieDiagnostic,+ TaskCookieError,+} from '../task-cookie-error'++const cookieSchema = z.object({+ name: z.string(),+ value: z.string(),+ domain: z.string(),+ path: z.string().optional(),+ hostOnly: z.boolean().optional(),+ secure: z.boolean().optional(),+ httpOnly: z.boolean().optional(),+ expiresAt: z.number().int().min(0).max(Number.MAX_SAFE_INTEGER).optional(),+})+const tokenName = /^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/+// biome-ignore lint/suspicious/noControlCharactersInRegex: HTTP credential delimiters.+const unsafeValue = /[\x00-\x1f\x7f;]/++/** Adapt to the published task-cookie RPC; never rewrite or truncate credentials. */+export function prepareAria2TaskCookies(+ cookies: readonly DownloadCookie[],+ now = Date.now()+): PreparedDownloadCookies {+ const reject = (diagnostic: TaskCookieDiagnostic): never => {+ throw new TaskCookieError(diagnostic)+ }+ if (!Array.isArray(cookies))+ reject({ index: -1, field: 'cookies', reason: 'type' })+ const discarded: TaskCookieDiagnostic[] = []+ const retained = new Map<+ string,+ { cookie: DownloadCookie; host: string; index: number }+ >()+ for (const [index, input] of cookies.entries()) {+ const parsed = cookieSchema.safeParse(input)+ if (!parsed.success) {+ const field = String(parsed.error.issues[0]?.path[0] ?? 'cookie')+ discarded.push({+ index,+ field,+ reason: field === 'expiresAt' ? 'expiry' : 'type',+ })+ continue+ }+ const cookie = parsed.data+ if (cookie.expiresAt !== undefined && cookie.expiresAt <= now) {+ discarded.push({ index, field: 'expiresAt', reason: 'expired' })+ continue+ }+ const { name, value, domain } = cookie+ const path = cookie.path ?? '/'+ let diagnostic: TaskCookieDiagnostic | undefined+ const invalid = (+ field: string,+ reason: TaskCookieDiagnostic['reason'],+ byteLength?: number+ ) => {+ diagnostic ??= {+ index,+ field,+ reason,+ ...(byteLength === undefined ? {} : { byteLength }),+ }+ }+ for (const [field, text] of [+ ['name', name],+ ['value', value],+ ['domain', domain],+ ['path', path],+ ] as const) {+ if (!text.isWellFormed()) invalid(field, 'syntax')+ }+ const bytes = Buffer.byteLength(name) + Buffer.byteLength(value)+ if (bytes > 4096) invalid('nameValue', 'size', bytes)+ if (!tokenName.test(name)) invalid('name', 'syntax')+ if (unsafeValue.test(value)) invalid('value', 'syntax')+ if (unsafeValue.test(path) || !path.startsWith('/'))+ invalid('path', 'syntax')+ for (const [field, text, limit] of [+ ['domain', domain, 254],+ ['path', path, 4096],+ ] as const) {+ const byteLength = Buffer.byteLength(text)+ if (byteLength > limit) invalid(field, 'size', byteLength)+ }+ // Match the engine's ASCII case folding; Unicode lowercasing can turn an+ // invalid host such as U+212A into an otherwise valid ASCII hostname.+ const host = domain+ .replace(/^\./, '')+ .replace(/[A-Z]/g, (char) => char.toLowerCase())+ if (+ !host ||+ host.startsWith('.') ||+ host.endsWith('.') ||+ host.includes('..') ||+ (!isIP(host) && /[^a-z0-9.-]/.test(host))+ ) {+ invalid('domain', 'domain')+ }+ if (diagnostic) {+ discarded.push(diagnostic)+ continue+ }+ const identity = JSON.stringify([host, path, name])+ const previous = retained.get(identity)+ if (previous)+ discarded.push({+ index: previous.index,+ field: 'cookie',+ reason: 'duplicate',+ })+ // The engine replaces by canonical domain/path/name, preserving first insertion order.+ retained.set(identity, { cookie, host, index })+ }+ if (+ retained.size === 0 &&+ discarded.some((d) => d.reason !== 'expired' && d.reason !== 'duplicate')+ ) {+ reject({ index: -1, field: 'cookies', reason: 'noUsableCookies' })+ }+ if (retained.size > 300)+ reject({ index: -1, field: 'cookies', reason: 'count' })+ const domains = new Map<string, number>()+ for (const { host, index } of retained.values()) {+ const count = (domains.get(host) ?? 0) + 1+ domains.set(host, count)+ // Refuse before creation instead of silently evicting a credential or choosing an arbitrary subset.+ if (count > 50) reject({ index, field: 'domain', reason: 'count' })+ }+ return {+ cookies: [...retained.values()].map((entry) => entry.cookie),+ discarded,+ }+}diff --git a/src/core/engine/engine-adapter.ts b/src/core/engine/engine-adapter.tsindex 583a3171..6ff2a277 100644--- a/src/core/engine/engine-adapter.ts+++ b/src/core/engine/engine-adapter.ts@@ -21,6 +21,7 @@ import type { TaskPiecesResult } from '@shared/types/pieces'import type { GlobalStats } from '@shared/types/stats'import type { DownloadTask, TaskFile } from '@shared/types/task'import type { FileAllocation } from '@shared/types/tuning'+import type { TaskCookieDiagnostic } from './task-cookie-error'export interface OutputFilePath {/** Engine-neutral, zero-based file index. */@@ -107,6 +108,11 @@ export interface DownloadCookie {expiresAt?: number}+export interface PreparedDownloadCookies {+ cookies: DownloadCookie[]+ discarded: TaskCookieDiagnostic[]+}+export interface CreateDownloadParams {/** Explicit in-place legacy HTTP activation after content verification. */legacyCheckpointActivation?: { token: string; targetPath: string }@@ -217,6 +223,10 @@ export interface EngineAdapter {getDirectResourceMetadataProfile?(): DirectResourceMetadataProfile | nullcreateDownload(params: CreateDownloadParams): Promise<string>+ /** Side-effect-free credential adaptation. Diagnostics must never contain credentials. */+ prepareDownloadCookies?(+ cookies: readonly DownloadCookie[]+ ): PreparedDownloadCookiespauseTask(engineTaskId: string): Promise<void>resumeTask(engineTaskId: string): Promise<void>removeTask(engineTaskId: string): Promise<void>diff --git a/src/core/engine/task-cookie-error.ts b/src/core/engine/task-cookie-error.tsnew file mode 100644index 00000000..19f25167--- /dev/null+++ b/src/core/engine/task-cookie-error.ts@@ -0,0 +1,24 @@+import { AppError, ErrorCode } from '@shared/errors'++export interface TaskCookieDiagnostic {+ index: number+ field: string+ reason:+ | 'type'+ | 'syntax'+ | 'size'+ | 'domain'+ | 'expiry'+ | 'count'+ | 'expired'+ | 'duplicate'+ | 'noUsableCookies'+ byteLength?: number+}++/** Contains metadata only: never retain a cookie, name, value or validation input. */+export class TaskCookieError extends AppError {+ constructor(readonly diagnostic: TaskCookieDiagnostic) {+ super(ErrorCode.TaskCreateFailed, 'task.add.createFailed')+ }+}diff --git a/src/core/task/create-task-handler.test.ts b/src/core/task/create-task-handler.test.tsindex e3587e2f..8b69db9e 100644--- a/src/core/task/create-task-handler.test.ts+++ b/src/core/task/create-task-handler.test.ts@@ -549,6 +549,88 @@ describe('browser direct download filenames', () => {})describe('handleCreateTask', () => {+ it('cleans and snapshots credentials before waiting and reports only safe filtering metadata', async () => {+ const deps = makeDeps()+ let ready!: () => void+ deps.waitForEngineReady = () =>+ new Promise<void>((resolve) => {+ ready = resolve+ })+ const cookies = [+ { name: 'sid', value: 'auth-secret', domain: 'example.com' },+ { name: '', value: 'discarded-secret', domain: 'example.com' },+ ]+ const pending = handleCreateTask(+ {+ type: 'http',+ uris: ['https://example.com/file'],+ saveDir: '/d',+ headers: [],+ },+ deps,+ { source: 'bridge', cookies }+ )+ cookies[0]!.value = 'mutated\nsecret'+ ready()+ await pending+ expect(deps.addUriWithCookies).toHaveBeenCalledWith(+ expect.any(Array),+ [{ name: 'sid', value: 'auth-secret', domain: 'example.com' }],+ expect.any(Object)+ )+ expect(logWarn.mock.calls[0]?.[0]).toMatchObject({+ inputCount: 2,+ keptCount: 1,+ discardedCount: 1,+ diagnostics: [{ index: 1, field: 'name', reason: 'syntax' }],+ })+ expect(JSON.stringify(logWarn.mock.calls)).not.toContain('secret')+ expect(JSON.stringify(lastAddedTask(deps))).not.toContain('secret')+ })+ it.each([+ { name: 'sid', value: 'secret\nvalue', domain: 'example.com' },+ { name: '', value: 'secret', domain: 'example.com' },+ ])(+ 'rejects cookies before creating directories, persistent intent or engine tasks',+ async (cookie) => {+ const deps = makeDeps()+ const prepareSaveDir = vi.fn(async (directory: string) => directory)+ deps.prepareSaveDir = prepareSaveDir+ const persistTask = vi.fn()+ deps.persistTask = persistTask+ const request = {+ type: 'http',+ uris: ['https://example.com/file'],+ saveDir: '/d',+ headers: [],+ }+ await expect(+ handleCreateTask(request, deps, { source: 'bridge', cookies: [cookie] })+ ).rejects.toMatchObject({+ diagnostic: { index: -1, reason: 'noUsableCookies' },+ })+ for (const effect of [+ prepareSaveDir,+ persistTask,+ deps.pick,+ deps.reserveEngineTaskId,+ deps.addUri,+ deps.addUriWithCookies,+ deps.forceRemove,+ ]) {+ expect(effect).not.toHaveBeenCalled()+ }+ expect(JSON.stringify(logInfo.mock.calls)).not.toContain('secret')+ expect(logWarn.mock.calls[0]?.[0]).toMatchObject({+ diagnostic: {+ index: -1,+ field: expect.any(String),+ reason: expect.any(String),+ },+ })+ expect(JSON.stringify(logWarn.mock.calls)).not.toContain('secret')+ }+ )it('reserves different final outputs for concurrent torrents with the same chosen name', async () => {const deps = makeDeps()const owners: DownloadTask[] = []diff --git a/src/core/task/create-task-handler.ts b/src/core/task/create-task-handler.tsindex ee512d48..8f789845 100644--- a/src/core/task/create-task-handler.ts+++ b/src/core/task/create-task-handler.ts@@ -107,6 +107,7 @@ import {admitTaskCreateRequest,DownloadSourceError,} from './source-admission'+import { admitTaskCookies } from './task-cookie-admission'import type { TaskManager } from './task-manager'import type { TorrentMetaStore } from './torrent-meta-store'@@ -305,6 +306,10 @@ async function createAdmittedTask(): Promise<TaskCreateSuccessResult> {const parsed = taskCreateRequestSchema.safeParse(rawRequest)if (parsed.success && parsed.data.type === 'http') {+ // Snapshot and clean credentials before any await or task side effect.+ // Existing idempotent receipts are resolved before reaching this admission.+ if (opts.cookies !== undefined)+ opts = { ...opts, cookies: admitTaskCookies(deps.adapter, opts.cookies) }const policy = deps.directResourceProxyPolicy// Cold-start waiting happens before taking the proxy read lease. Once the// lease is held, a later disconnect must fail fast instead of waiting ondiff --git a/src/core/task/task-cookie-admission.ts b/src/core/task/task-cookie-admission.tsnew file mode 100644index 00000000..02c83f4e--- /dev/null+++ b/src/core/task/task-cookie-admission.ts@@ -0,0 +1,37 @@+import type { DownloadCookie, EngineAdapter } from '@core/engine/engine-adapter'+import { TaskCookieError } from '@core/engine/task-cookie-error'+import { getLogger } from '@core/logger'++/** Proof that cookie validation failed before task creation acquired side effects. */+export class TaskCookieAdmissionError extends TaskCookieError {}++export function admitTaskCookies(+ adapter: EngineAdapter,+ cookies: readonly DownloadCookie[]+): readonly DownloadCookie[] {+ try {+ const prepared = adapter.prepareDownloadCookies?.(cookies)+ if (!prepared) return structuredClone(cookies)+ if (prepared.discarded.length > 0) {+ getLogger('task-cookie-admission').warn(+ {+ inputCount: cookies.length,+ keptCount: prepared.cookies.length,+ discardedCount: prepared.discarded.length,+ diagnostics: prepared.discarded.slice(0, 20),+ },+ 'task cookies adapted for the engine'+ )+ }+ return prepared.cookies+ } catch (error) {+ if (error instanceof TaskCookieError) {+ getLogger('task-cookie-admission').warn(+ { diagnostic: error.diagnostic },+ 'task cookie admission rejected'+ )+ throw new TaskCookieAdmissionError(error.diagnostic)+ }+ throw error+ }+}