A full-featured download manager.
fix(download): preserve filenames for proxied redirect downloads (#2013)
Dr_rOot2a385883a474
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex c97b3d60..c1e77021 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -99,6 +99,44 @@ jobs:src/core/plugin/update/builtin-updater.test.tssrc/core/plugin/update/signature.test.ts+ # The runtime test repeats the real loopback proxy probe under Electron's+ # embedded Node via ELECTRON_RUN_AS_NODE; keep the hydrated runtime above.+ - name: Undici proxy compatibility (Node + Electron)+ run: >-+ pnpm exec vitest run+ src/core/engine/aria2/aria2-adapter.test.ts+ src/core/engine/aria2/aria2-config-builder.test.ts+ src/core/engine/aria2/aria2-process-manager.test.ts+ src/core/engine/aria2/aria2-trust-store.test.ts+ src/core/engine/engine-supervisor.test.ts+ src/core/proxy/applied-download-proxy-policy.test.ts+ src/core/proxy/applier.test.ts+ src/core/proxy/aria2-proxy-routing.test.ts+ src/core/proxy/serializers.test.ts+ src/core/session/session-manager.test.ts+ src/core/task/actions/re-add-task.test.ts+ src/core/task/create-task-handler.test.ts+ src/core/task/direct-resource-validator.test.ts+ src/core/task/direct-resource-validator.proxy-contract.test.ts+ src/core/task/direct-resource-validator.proxy.test.ts+ src/core/tracker/tracker-prober.test.ts+ src/core/tracker/tracker-syncer.test.ts+ src/main/ipc/commands.test.ts+ src/server/ipc/commands.test.ts+ env:+ MOTRIX_REQUIRE_ELECTRON_PROXY_TEST: '1'++ - name: Undici response and dispatcher lifecycle+ run: >-+ pnpm exec vitest run+ src/core/geoip/geo-ip-downloader.test.ts+ src/core/media/manifest-fetcher.test.ts+ src/core/plugin/capabilities/http.proxy-lifecycle.test.ts+ src/core/plugin/install/github-fetcher.test.ts+ src/core/plugin/install/url-fetcher.test.ts+ src/core/plugin/registry/registry-client.test.ts+ src/server/plugin/install-service.test.ts+- name: Schema parity checkrun: pnpm run check:schema-paritydiff --git a/src/core/engine/aria2/aria2-adapter.test.ts b/src/core/engine/aria2/aria2-adapter.test.tsindex 44fa10a8..00debbca 100644--- a/src/core/engine/aria2/aria2-adapter.test.ts+++ b/src/core/engine/aria2/aria2-adapter.test.ts@@ -3,7 +3,11 @@ import type { EngineFeatureReport } from '@shared/types/engine'import type { Mock } from 'vitest'import { describe, expect, it, vi } from 'vitest'import type { CreateDownloadParams } from '../engine-adapter'-import { Aria2Adapter } from './aria2-adapter'+import { DIRECT_RESOURCE_METADATA_PROFILE } from '../engine-adapter'+import {+ Aria2Adapter,+ directResourceMetadataProfileFromGlobalOptions,+} from './aria2-adapter'import type { Aria2RpcClient } from './aria2-rpc-client'import type { Aria2RawFile, Aria2RawGlobalStat, Aria2RawStatus } from './types'@@ -32,6 +36,7 @@ function createMockRpc(): Aria2RpcClient {tellStopped: vi.fn(),getFiles: vi.fn(),getGlobalStat: vi.fn(),+ getGlobalOption: vi.fn(),getVersion: vi.fn(),onBtDownloadComplete: vi.fn(),onDownloadComplete: vi.fn(),@@ -242,6 +247,77 @@ const RAW_FILES: Aria2RawFile[] = [// ─── Tests ──────────────────────────────────────────────────describe('Aria2Adapter', () => {+ describe('direct resource metadata profile', () => {+ const safeOptions = {+ 'content-disposition-default-utf8': 'false',+ 'http-accept-gzip': 'true',+ 'no-want-digest-header': 'false',+ 'no-netrc': 'true',+ }++ it('accepts the controlled HTTP baseline without retaining raw options', async () => {+ await expect(+ directResourceMetadataProfileFromGlobalOptions(safeOptions)+ ).resolves.toBe(DIRECT_RESOURCE_METADATA_PROFILE)++ const rpc = createMockRpc()+ vi.mocked(rpc.getGlobalOption).mockResolvedValue({+ ...safeOptions,+ 'all-proxy-passwd': 'must-not-be-cached',+ })+ const adapter = new Aria2Adapter(rpc)+ const profile = await adapter.inspectDirectResourceMetadataProfile()+ adapter.setDirectResourceMetadataProfile(profile)++ expect(adapter.getDirectResourceMetadataProfile()).toBe(+ DIRECT_RESOURCE_METADATA_PROFILE+ )+ expect(adapter).not.toHaveProperty('globalOptions')+ })++ it.each([+ ['header', 'X-Ambient: yes\n'],+ ['referer', 'https://ref.example/'],+ ['load-cookies', '/tmp/cookies.txt'],+ ['http-user', 'alice'],+ ['http-passwd', 'secret'],+ ['conditional-get', 'true'],+ ['dry-run', 'true'],+ ['http-auth-challenge', 'true'],+ ['http-no-cache', 'true'],+ ['use-head', 'true'],+ ])('rejects ambient %s request semantics', async (name, value) => {+ await expect(+ directResourceMetadataProfileFromGlobalOptions({+ ...safeOptions,+ [name]: value,+ })+ ).resolves.toBeNull()+ })++ it('rejects an active netrc but permits the default missing file', async () => {+ const options = {+ ...safeOptions,+ 'no-netrc': 'false',+ 'netrc-path': '/private/profile/.netrc',+ }+ await expect(+ directResourceMetadataProfileFromGlobalOptions(+ options,+ vi.fn().mockResolvedValue(undefined)+ )+ ).resolves.toBeNull()++ const missing = Object.assign(new Error('missing'), { code: 'ENOENT' })+ await expect(+ directResourceMetadataProfileFromGlobalOptions(+ options,+ vi.fn().mockRejectedValue(missing)+ )+ ).resolves.toBe(DIRECT_RESOURCE_METADATA_PROFILE)+ })+ })+describe('getCapabilities / getFeatureReport', () => {it('returns conservative defaults before connect()', () => {const rpc = createMockRpc()@@ -341,6 +417,74 @@ describe('Aria2Adapter', () => {})describe('createDownload', () => {+ it('pins the metadata-owned baseline and preserves explicit credentials', async () => {+ const rpc = createMockRpc()+ vi.mocked(rpc.addUri).mockResolvedValue('profile-gid')+ const adapter = new Aria2Adapter(rpc)+ adapter.setDirectResourceMetadataProfile(DIRECT_RESOURCE_METADATA_PROFILE)++ await adapter.createDownload({+ uris: ['https://example.com/file'],+ saveDir: '/d',+ headers: { Cookie: 'session=user', authorization: 'Bearer user' },+ directResourceMetadataProfile: DIRECT_RESOURCE_METADATA_PROFILE,+ extraEngineOptions: {+ referer: 'https://user.example/',+ 'use-head': 'true',+ },+ })++ expect(rpc.addUri).toHaveBeenCalledWith(+ ['https://example.com/file'],+ expect.objectContaining({+ header: [+ 'Cookie: session=user',+ 'authorization: Bearer user',+ 'Accept: */*',+ ],+ referer: 'https://user.example/',+ 'use-head': 'true',+ 'http-no-cache': 'false',+ 'conditional-get': 'false',+ 'no-netrc': 'true',+ })+ )+ })++ it('adds empty Cookie and Authorization only for the safe profile', async () => {+ const rpc = createMockRpc()+ vi.mocked(rpc.addUri).mockResolvedValue('profile-gid')+ const adapter = new Aria2Adapter(rpc)+ adapter.setDirectResourceMetadataProfile(DIRECT_RESOURCE_METADATA_PROFILE)++ await adapter.createDownload({+ uris: ['https://example.com/file'],+ saveDir: '/d',+ directResourceMetadataProfile: DIRECT_RESOURCE_METADATA_PROFILE,+ })++ expect(rpc.addUri).toHaveBeenCalledWith(+ ['https://example.com/file'],+ expect.objectContaining({+ header: ['Cookie: ', 'Authorization: ', 'Accept: */*'],+ })+ )+ })++ it('fails before addUri when the published profile is unavailable', async () => {+ const rpc = createMockRpc()+ const adapter = new Aria2Adapter(rpc)++ await expect(+ adapter.createDownload({+ uris: ['https://example.com/file'],+ saveDir: '/d',+ directResourceMetadataProfile: DIRECT_RESOURCE_METADATA_PROFILE,+ })+ ).rejects.toThrow('request profile changed')+ expect(rpc.addUri).not.toHaveBeenCalled()+ })+it('translates params and calls addUri', async () => {const rpc = createMockRpc()vi.mocked(rpc.addUri).mockResolvedValue('gid123')@@ -360,6 +504,7 @@ describe('Aria2Adapter', () => {expect(rpc.addUri).toHaveBeenCalledWith(['http://example.com/file.zip'], {continue: 'false',dir: '/tmp',+ header: ['Accept: */*'],out: 'custom.zip','max-download-limit': '1024','max-upload-limit': '512',@@ -379,6 +524,7 @@ describe('Aria2Adapter', () => {expect(rpc.addUri).toHaveBeenCalledWith(['http://example.com/f.zip'], {continue: 'false',dir: '/tmp',+ header: ['Accept: */*'],})})@@ -753,7 +899,7 @@ describe('Aria2Adapter', () => {await adapter.createDownload({uris: ['u'],saveDir: '/d',- proxy: 'http://p:1080',+ proxy: 'http://a%40b:p%3As@p:1080',extraEngineOptions: { referer: 'https://r', 'load-cookies': '/c' },})@@ -761,10 +907,198 @@ describe('Aria2Adapter', () => {['u'],expect.objectContaining({'all-proxy': 'http://p:1080',+ 'all-proxy-user': 'a@b',+ 'all-proxy-passwd': 'p:s',referer: 'https://r','load-cookies': '/c',}))+ const proxy = vi.mocked(rpc.addUri).mock.calls[0]?.[1]?.['all-proxy']+ expect(proxy).not.toContain('a%40b')+ expect(proxy).not.toContain('p%3As')+ })++ it('pins the captured engine User-Agent as a per-task option', async () => {+ const rpc = createMockRpc()+ vi.mocked(rpc.addUri).mockResolvedValue('gidXYZ')+ const adapter = new Aria2Adapter(rpc)++ await adapter.createDownload({+ uris: ['u'],+ saveDir: '/d',+ userAgent: 'Motrix/Applied',+ })++ expect(rpc.addUri).toHaveBeenCalledWith(+ ['u'],+ expect.objectContaining({ 'user-agent': 'Motrix/Applied' })+ )+ })++ it('pins the default HTTP Accept header against Metalink negotiation', async () => {+ const rpc = createMockRpc()+ vi.mocked(rpc.addUri).mockResolvedValue('gidXYZ')+ const adapter = new Aria2Adapter(rpc)++ await adapter.createDownload({+ uris: ['https://downloads.example/release'],+ saveDir: '/d',+ })++ expect(rpc.addUri).toHaveBeenCalledWith(+ ['https://downloads.example/release'],+ expect.objectContaining({ header: ['Accept: */*'] })+ )+ })++ it('pins the default Accept header for uppercase HTTP schemes', async () => {+ const rpc = createMockRpc()+ vi.mocked(rpc.addUri).mockResolvedValue('gidXYZ')+ const adapter = new Aria2Adapter(rpc)++ await adapter.createDownload({+ uris: ['HTTPS://downloads.example/release'],+ saveDir: '/d',+ })++ expect(rpc.addUri).toHaveBeenCalledWith(+ ['HTTPS://downloads.example/release'],+ expect.objectContaining({ header: ['Accept: */*'] })+ )+ })++ it('preserves a task-provided Accept header', async () => {+ const rpc = createMockRpc()+ vi.mocked(rpc.addUri).mockResolvedValue('gidXYZ')+ const adapter = new Aria2Adapter(rpc)++ await adapter.createDownload({+ uris: ['https://downloads.example/release'],+ saveDir: '/d',+ headers: { aCcEpT: 'application/octet-stream' },+ })++ expect(rpc.addUri).toHaveBeenCalledWith(+ ['https://downloads.example/release'],+ expect.objectContaining({+ header: ['aCcEpT: application/octet-stream'],+ })+ )+ })++ it('pins an explicitly empty engine User-Agent', async () => {+ const rpc = createMockRpc()+ vi.mocked(rpc.addUri).mockResolvedValue('gidXYZ')+ const adapter = new Aria2Adapter(rpc)++ await adapter.createDownload({+ uris: ['u'],+ saveDir: '/d',+ userAgent: '',+ })++ expect(rpc.addUri).toHaveBeenCalledWith(+ ['u'],+ expect.objectContaining({ 'user-agent': '' })+ )+ })++ it('rejects a task User-Agent containing persistent option controls', async () => {+ const rpc = createMockRpc()+ const adapter = new Aria2Adapter(rpc)++ await expect(+ adapter.createDownload({+ uris: ['u'],+ saveDir: '/d',+ userAgent: 'Motrix\nall-proxy=http://evil',+ })+ ).rejects.toThrow('Task User-Agent must not contain control characters')+ expect(rpc.addUri).not.toHaveBeenCalled()+ })++ it('clears inherited global credentials for an unauthenticated task proxy', async () => {+ const rpc = createMockRpc()+ vi.mocked(rpc.addUri).mockResolvedValue('gidXYZ')+ const adapter = new Aria2Adapter(rpc)++ await adapter.createDownload({+ uris: ['u'],+ saveDir: '/d',+ proxy: 'proxy.example:1080',+ })++ expect(rpc.addUri).toHaveBeenCalledWith(+ ['u'],+ expect.objectContaining({+ 'all-proxy': 'proxy.example:1080',+ 'all-proxy-user': '',+ 'all-proxy-passwd': '',+ })+ )+ })++ it('preserves an aria2-compatible legacy IPv4 task proxy', async () => {+ const rpc = createMockRpc()+ vi.mocked(rpc.addUri).mockResolvedValue('gidXYZ')+ const adapter = new Aria2Adapter(rpc)++ await adapter.createDownload({+ uris: ['u'],+ saveDir: '/d',+ proxy: 'http://user:[email protected]:8080',+ })++ expect(rpc.addUri).toHaveBeenCalledWith(+ ['u'],+ expect.objectContaining({+ 'all-proxy': 'http://127.1:8080',+ 'all-proxy-user': 'user',+ 'all-proxy-passwd': 'pass',+ })+ )+ })++ it('rejects passthrough options that could override the applied proxy route', async () => {+ const rpc = createMockRpc()+ const adapter = new Aria2Adapter(rpc)++ await expect(+ adapter.createDownload({+ uris: ['u'],+ saveDir: '/d',+ extraEngineOptions: { 'http-proxy': 'http://other:8080' },+ })+ ).rejects.toThrow('Reserved aria2 proxy option')+ expect(rpc.addUri).not.toHaveBeenCalled()+ })++ it.each(['socks5://proxy.example:1080', 'http://proxy.example:8080/path'])(+ 'rejects an unsupported task proxy before RPC: %s',+ async (proxy) => {+ const rpc = createMockRpc()+ const adapter = new Aria2Adapter(rpc)++ await expect(+ adapter.createDownload({ uris: ['u'], saveDir: '/d', proxy })+ ).rejects.toThrow('Task proxy must use aria2-compatible HTTP or HTTPS')+ expect(rpc.addUri).not.toHaveBeenCalled()+ }+ )++ it('rejects decoded control characters before aria2 persists task options', async () => {+ const rpc = createMockRpc()+ const adapter = new Aria2Adapter(rpc)++ await expect(+ adapter.createDownload({+ uris: ['u'],+ saveDir: '/d',+ proxy:+ 'http://user%0Ahttp-proxy%3Dhttp%3A%2F%2Fevil:[email protected]:8080',+ })+ ).rejects.toThrow('Unsupported aria2 proxy credentials')+ expect(rpc.addUri).not.toHaveBeenCalled()})})@@ -1278,6 +1612,20 @@ describe('Aria2Adapter', () => {)})+ it('rejects torrent passthrough options that could override the proxy route', async () => {+ const rpc = createMockRpc()+ const adapter = new Aria2Adapter(rpc)++ await expect(+ adapter.addTorrent({+ metadata: new Uint8Array(),+ saveDir: '/d',+ extraEngineOptions: { 'no-proxy': 'attacker.example' },+ })+ ).rejects.toThrow('Reserved aria2 proxy option')+ expect(rpc.addTorrent).not.toHaveBeenCalled()+ })+it('passes selectedFiles through as-is (index-neutral raw join)', async () => {const rpc = createMockRpc()vi.mocked(rpc.addTorrent).mockResolvedValue('gid')diff --git a/src/core/engine/aria2/aria2-adapter.ts b/src/core/engine/aria2/aria2-adapter.tsindex b8f1407f..650917b5 100644--- a/src/core/engine/aria2/aria2-adapter.ts+++ b/src/core/engine/aria2/aria2-adapter.ts@@ -1,5 +1,11 @@+import { access } from 'node:fs/promises'import path from 'node:path'import { getLogger } from '@core/logger'+import {+ extractAria2ProxyCredentials,+ normalizeAria2TaskProxyUrl,+ stripAria2ProxyCredentials,+} from '@core/proxy/aria2-proxy-routing'import { AppError, ErrorCode } from '@shared/errors'import type {EngineCapability,@@ -20,8 +26,10 @@ import { probeQuick } from '../../probe/disk-probe'import type {AddTorrentParams,CreateDownloadParams,+ DirectResourceMetadataProfile,EngineAdapter,} from '../engine-adapter'+import { DIRECT_RESOURCE_METADATA_PROFILE } from '../engine-adapter'import type { Aria2RpcClient } from './aria2-rpc-client'import { recommend } from './aria2-tuning'import { isConnectionLimitRangeError, isNotFoundError } from './error-utils'@@ -36,6 +44,73 @@ import { isConnectionLimitRangeError, isNotFoundError } from './error-utils'* defaults to unlimited) and merges them into tellStopped.*/const REMOVE_RESULT_CHUNK_SIZE = 100+const RESERVED_TASK_PROXY_OPTIONS = new Set([+ 'all-proxy',+ 'all-proxy-user',+ 'all-proxy-passwd',+ 'http-proxy',+ 'http-proxy-user',+ 'http-proxy-passwd',+ 'https-proxy',+ 'https-proxy-user',+ 'https-proxy-passwd',+ 'ftp-proxy',+ 'ftp-proxy-user',+ 'ftp-proxy-passwd',+ 'no-proxy',+ 'proxy-method',+])++type FileAccess = (filePath: string) => Promise<void>++const AMBIENT_HTTP_TEXT_OPTIONS = [+ 'referer',+ 'load-cookies',+ 'http-user',+ 'http-passwd',+] as const++const AMBIENT_HTTP_TRUE_OPTIONS = [+ 'conditional-get',+ 'dry-run',+ 'http-auth-challenge',+ 'http-no-cache',+ 'use-head',+] as const++/**+ * Convert aria2's effective global options into a non-secret compatibility+ * decision. User values are never returned or logged. A configured netrc is+ * safe only when it is disabled or its effective file does not exist; a+ * present file may change Authorization and must preserve the user's behavior.+ */+export async function directResourceMetadataProfileFromGlobalOptions(+ options: Readonly<Record<string, string>>,+ accessFile: FileAccess = access+): Promise<DirectResourceMetadataProfile | null> {+ if (+ hasEffectiveCumulativeValue(options.header) ||+ AMBIENT_HTTP_TEXT_OPTIONS.some((name) => options[name]?.length > 0) ||+ AMBIENT_HTTP_TRUE_OPTIONS.some((name) => isAria2True(options[name])) ||+ options['http-accept-gzip'] !== 'true' ||+ options['no-want-digest-header'] !== 'false'+ ) {+ return null+ }++ if (!isAria2True(options['no-netrc'])) {+ const netrcPath = options['netrc-path']?.trim()+ if (!netrcPath) return null+ try {+ await accessFile(netrcPath)+ return null+ } catch (error) {+ if (!isMissingPathError(error)) return null+ }+ }++ return DIRECT_RESOURCE_METADATA_PROFILE+}import {buildFeatureReport,@@ -68,6 +143,8 @@ export class Aria2Adapter implements EngineAdapter {hasMoveStorage: false,}private connectionOptionLimit: number | null = null+ private directResourceMetadataProfile: DirectResourceMetadataProfile | null =+ nullprivate btCompleteHandlers: Array<(engineTaskId: string) => void> = []private downloadCompleteHandlers: Array<(engineTaskId: string) => void> = []@@ -75,7 +152,10 @@ export class Aria2Adapter implements EngineAdapter {private readonly rpcUnsubscribers: Array<() => void> = []private disposed = false- constructor(private rpc: Aria2RpcClient) {+ constructor(+ private rpc: Aria2RpcClient,+ private readonly accessFile: FileAccess = access+ ) {const unsubscribers = [this.rpc.onBtDownloadComplete((event) => {this.fanOut(this.btCompleteHandlers, event.gid)@@ -94,6 +174,34 @@ export class Aria2Adapter implements EngineAdapter {}}+ async inspectDirectResourceMetadataProfile(): Promise<DirectResourceMetadataProfile | null> {+ try {+ return await directResourceMetadataProfileFromGlobalOptions(+ await this.rpc.getGlobalOption(),+ this.accessFile+ )+ } catch (error) {+ // The profile is a safety proof, not a startup dependency. RPC or file+ // inspection failures disable optional probing/replay without exposing+ // the possibly secret global option values in logs.+ this.log.debug(+ { err: error },+ 'aria2 HTTP metadata request profile is unavailable'+ )+ return null+ }+ }++ setDirectResourceMetadataProfile(+ profile: DirectResourceMetadataProfile | null+ ): void {+ this.directResourceMetadataProfile = profile+ }++ getDirectResourceMetadataProfile(): DirectResourceMetadataProfile | null {+ return this.directResourceMetadataProfile+ }+dispose(): void {if (this.disposed) returnthis.disposed = true@@ -233,6 +341,15 @@ export class Aria2Adapter implements EngineAdapter {'aria2 addUri gid must contain exactly 16 hexadecimal characters')}+ const metadataProfile = params.directResourceMetadataProfile+ if (+ metadataProfile !== undefined &&+ this.getDirectResourceMetadataProfile() !== metadataProfile+ ) {+ throw new Error(+ 'aria2 HTTP request profile changed before download dispatch'+ )+ }const options: Record<string, string | string[]> = {dir: params.saveDir,}@@ -249,19 +366,85 @@ export class Aria2Adapter implements EngineAdapter {// engine state matches the persisted Motrix status.options.pause = 'true'}- if (params.headers) {- options.header = Object.entries(params.headers).map(- ([key, value]) => `${key}: ${value}`- )+ const requestHeaders = Object.entries(params.headers ?? {})+ if (metadataProfile === DIRECT_RESOURCE_METADATA_PROFILE) {+ // An empty custom field suppresses aria2's built-in Cookie/AuthConfig+ // values while preserving the exact field presence mirrored by Undici.+ // Explicit task values always win.+ if (!hasRequestHeader(requestHeaders, 'cookie')) {+ requestHeaders.push(['Cookie', ''])+ }+ if (!hasRequestHeader(requestHeaders, 'authorization')) {+ requestHeaders.push(['Authorization', ''])+ }+ }+ if (+ params.uris.every((uri) => /^https?:\/\//i.test(uri)) &&+ !hasRequestHeader(requestHeaders, 'accept')+ ) {+ // A Metalink-enabled aria2 expands its built-in Accept value on the+ // first HTTP request. Pin Motrix direct downloads to the exact value+ // used by metadata validation so content negotiation cannot diverge.+ requestHeaders.push(['Accept', '*/*'])+ }+ if (requestHeaders.length > 0) {+ options.header = requestHeaders.map(([key, value]) => `${key}: ${value}`)+ }+ if (params.userAgent !== undefined) {+ if (hasC0OrDel(params.userAgent)) {+ throw new TypeError(+ 'Task User-Agent must not contain control characters'+ )+ }+ options['user-agent'] = params.userAgent}if (params.connections != null) {options.split = String(params.connections)options['max-connection-per-server'] = String(params.connections)}- if (params.proxy?.trim()) options['all-proxy'] = params.proxy.trim()+ if (metadataProfile === DIRECT_RESOURCE_METADATA_PROFILE) {+ // Pin every scalar request semantic represented by the profile before+ // passthrough options. A caller that intentionally supplies an engine+ // option keeps the historical last-write-wins behavior below; such+ // calls are excluded from metadata probing by CreateTaskHandler.+ options.referer = ''+ options['http-no-cache'] = 'false'+ options['conditional-get'] = 'false'+ options['use-head'] = 'false'+ options['no-netrc'] = 'true'+ options['http-user'] = ''+ options['http-passwd'] = ''+ options['http-auth-challenge'] = 'false'+ options['http-accept-gzip'] = 'true'+ options['no-want-digest-header'] = 'false'+ }if (params.extraEngineOptions) {- for (const [k, v] of Object.entries(params.extraEngineOptions))+ for (const [k, v] of Object.entries(params.extraEngineOptions)) {+ if (RESERVED_TASK_PROXY_OPTIONS.has(k.toLowerCase())) {+ throw new TypeError(`Reserved aria2 proxy option: ${k}`)+ }options[k] = v+ }+ }+ const taskProxy = params.proxy?.trim()+ if (taskProxy) {+ const normalizedProxy = normalizeAria2TaskProxyUrl(taskProxy)+ if (!normalizedProxy) {+ throw new TypeError(+ 'Task proxy must use aria2-compatible HTTP or HTTPS syntax'+ )+ }+ const credentials = extractAria2ProxyCredentials(taskProxy)+ const proxyWithoutCredentials = stripAria2ProxyCredentials(taskProxy)+ if (!credentials || !proxyWithoutCredentials) {+ throw new TypeError('Unsupported aria2 proxy credentials')+ }+ // Reapply the complete task proxy after passthrough options. Carry+ // credentials only in aria2's dedicated fields: duplicating them in the+ // URI also makes them more likely to appear in engine state or logs.+ options['all-proxy'] = proxyWithoutCredentials+ options['all-proxy-user'] = credentials.username+ options['all-proxy-passwd'] = credentials.password}const automaticTuning =@@ -541,6 +724,9 @@ export class Aria2Adapter implements EngineAdapter {}if (params.extraEngineOptions) {for (const [k, v] of Object.entries(params.extraEngineOptions)) {+ if (RESERVED_TASK_PROXY_OPTIONS.has(k.toLowerCase())) {+ throw new TypeError(`Reserved aria2 proxy option: ${k}`)+ }opts[k] = v}}@@ -750,3 +936,35 @@ export class Aria2Adapter implements EngineAdapter {}}}++function hasC0OrDel(value: string): boolean {+ for (const character of value) {+ const codePoint = character.codePointAt(0) ?? 0+ if (codePoint <= 0x1f || codePoint === 0x7f) return true+ }+ return false+}++function hasRequestHeader(+ headers: ReadonlyArray<readonly [string, string]>,+ expectedName: string+): boolean {+ return headers.some(([name]) => name.toLowerCase() === expectedName)+}++function hasEffectiveCumulativeValue(value: string | undefined): boolean {+ return Boolean(value?.split('\n').some((line) => line.trim().length > 0))+}++function isAria2True(value: string | undefined): boolean {+ return value?.toLowerCase() === 'true'+}++function isMissingPathError(error: unknown): boolean {+ return (+ typeof error === 'object' &&+ error !== null &&+ 'code' in error &&+ (error.code === 'ENOENT' || error.code === 'ENOTDIR')+ )+}diff --git a/src/core/engine/aria2/aria2-config-builder.test.ts b/src/core/engine/aria2/aria2-config-builder.test.tsindex 44896494..ea06bb05 100644--- a/src/core/engine/aria2/aria2-config-builder.test.ts+++ b/src/core/engine/aria2/aria2-config-builder.test.ts@@ -732,20 +732,176 @@ describe('Aria2ConfigBuilder', () => {expect(args).toContain('--no-proxy=localhost,127.0.0.1')})- it('omits --no-proxy when bypass empty', () => {+ it('clears --no-proxy when bypass is empty', () => {const args = buildArgs(makeEngineSettings(), true, baseProxy, {download: 0,upload: 0,})- expect(args.some((a) => a.startsWith('--no-proxy='))).toBe(false)+ expect(args).toContain('--no-proxy=')})- it('omits proxy args when proxy is null', () => {+ it('explicitly clears all proxy sources when proxy is null', () => {const args = buildArgs(makeEngineSettings(), true, null, {download: 0,upload: 0,})- expect(args.some((a) => a.startsWith('--all-proxy='))).toBe(false)+ expect(args).toEqual(+ expect.arrayContaining([+ '--all-proxy=',+ '--http-proxy=',+ '--http-proxy-user=',+ '--http-proxy-passwd=',+ '--https-proxy=',+ '--https-proxy-user=',+ '--https-proxy-passwd=',+ '--ftp-proxy=',+ '--ftp-proxy-user=',+ '--ftp-proxy-passwd=',+ '--all-proxy-user=',+ '--all-proxy-passwd=',+ '--no-proxy=',+ '--proxy-method=get',+ ])+ )+ })++ it('clears protocol-specific proxies even when all-proxy is enabled', () => {+ const args = buildArgs(makeEngineSettings(), true, baseProxy, {+ download: 0,+ upload: 0,+ })+ expect(args).toEqual(+ expect.arrayContaining([+ '--http-proxy=',+ '--http-proxy-user=',+ '--http-proxy-passwd=',+ '--https-proxy=',+ '--https-proxy-user=',+ '--https-proxy-passwd=',+ '--ftp-proxy=',+ '--ftp-proxy-user=',+ '--ftp-proxy-passwd=',+ ])+ )+ })++ it('pins decoded proxy credentials against stale aria2.conf values', () => {+ const args = buildArgs(+ makeEngineSettings(),+ true,+ {+ allProxy: 'http://a%40b:p%[email protected]:8080',+ noProxy: '',+ },+ { download: 0, upload: 0 }+ )++ expect(args).toEqual(+ expect.arrayContaining([+ '--all-proxy=http://p.example.com:8080',+ '--all-proxy-user=a@b',+ '--all-proxy-passwd=p:s',+ '--proxy-method=get',+ ])+ )+ })++ it('accepts equivalent expanded IPv6 proxy authorities', () => {+ const args = buildArgs(+ makeEngineSettings(),+ true,+ {+ allProxy: 'http://user:pass@[0:0:0:0:0:0:0:1]:8080',+ noProxy: '',+ },+ { download: 0, upload: 0 }+ )++ expect(args).toEqual(+ expect.arrayContaining([+ '--all-proxy=http://[0:0:0:0:0:0:0:1]:8080',+ '--all-proxy-user=user',+ '--all-proxy-passwd=pass',+ ])+ )+ })++ it('preserves an aria2-compatible legacy IPv4 proxy authority', () => {+ const args = buildArgs(+ makeEngineSettings(),+ true,+ {+ allProxy: 'http://user:[email protected]:8080',+ noProxy: '',+ },+ { download: 0, upload: 0 }+ )++ expect(args).toEqual(+ expect.arrayContaining([+ '--all-proxy=http://127.1:8080',+ '--all-proxy-user=user',+ '--all-proxy-passwd=pass',+ ])+ )+ })++ it('rejects a raw line break in no-proxy before aria2 reparses argv', () => {+ expect(() =>+ buildArgs(+ makeEngineSettings(),+ true,+ {+ allProxy: 'http://p.example.com:8080',+ noProxy: 'localhost\nhttp-proxy=http://evil:8080',+ },+ { download: 0, upload: 0 }+ )+ ).toThrow('aria2 option values must not contain CR or LF')+ })++ it('rejects percent-encoded control characters in proxy credentials', () => {+ expect(() =>+ buildArgs(+ makeEngineSettings(),+ true,+ {+ allProxy:+ 'http://user%0Ahttp-proxy%3Dhttp%3A%2F%2Fevil:[email protected]:8080',+ noProxy: '',+ },+ { download: 0, upload: 0 }+ )+ ).toThrow('Unsupported aria2 proxy credentials')+ })+ })++ describe('argv line integrity', () => {+ it.each([+ ['RPC secret', { rpcSecret: 'secret\nrpc-listen-all=true' }],+ ['User-Agent', { userAgent: 'Motrix\nhttp-proxy=http://evil' }],+ ])('rejects a line break in %s', (_label, overrides) => {+ expect(() =>+ builder.buildArgs(+ makeEngineSettings(overrides),+ true,+ null,+ { download: 0, upload: 0 },+ DEFAULT_SAVE_DIR+ )+ ).toThrow('aria2 option values must not contain CR or LF')+ })++ it('rejects a line break in a path option', () => {+ expect(() =>+ builder.buildArgs(+ makeEngineSettings(),+ true,+ null,+ { download: 0, upload: 0 },+ '/downloads\nhttp-proxy=http://evil'+ )+ ).toThrow('aria2 option values must not contain CR or LF')})})@@ -784,6 +940,16 @@ describe('Aria2ConfigBuilder', () => {expect(args).toContain('--bt-seed-unverified=false')})+ it('pins the HTTP headers mirrored by direct-resource metadata requests', () => {+ const args = buildArgs(DEFAULT_ENGINE_SETTINGS, true, null, {+ download: 0,+ upload: 0,+ })++ expect(args).toContain('--http-accept-gzip=true')+ expect(args).toContain('--no-want-digest-header=false')+ })+it('sets bt-remove-unselected-file=true so partial placeholders are cleaned by aria2', () => {const args = buildArgs(DEFAULT_ENGINE_SETTINGS, true, null, {download: 0,diff --git a/src/core/engine/aria2/aria2-config-builder.ts b/src/core/engine/aria2/aria2-config-builder.tsindex 0343c0b4..a7ae1185 100644--- a/src/core/engine/aria2/aria2-config-builder.ts+++ b/src/core/engine/aria2/aria2-config-builder.ts@@ -1,6 +1,10 @@import { randomUUID } from 'node:crypto'import { access, copyFile, mkdir, rename } from 'node:fs/promises'import path from 'node:path'+import {+ extractAria2ProxyCredentials,+ stripAria2ProxyCredentials,+} from '@core/proxy/aria2-proxy-routing'import type { Aria2ProxyOptions } from '@core/proxy/serializers'import type { EngineSettings } from '@shared/types/settings'import { dnsModeToAsyncDns } from './dns-fallback'@@ -136,6 +140,16 @@ export class Aria2ConfigBuilder {// invariants cannot be silently undone by anything earlier in the// chain or by user edits in `aria2.conf`.+ const proxyCredentials = proxy+ ? extractAria2ProxyCredentials(proxy.allProxy)+ : { username: '', password: '' }+ const proxyEndpoint = proxy+ ? stripAria2ProxyCredentials(proxy.allProxy)+ : ''+ if (!proxyCredentials || proxyEndpoint === null) {+ throw new TypeError('Unsupported aria2 proxy credentials')+ }+const args: string[] = []// ── L4 base conf ──@@ -205,13 +219,27 @@ export class Aria2ConfigBuilder {`--save-session-interval=${settings.sessionSaveInterval}`)- // ── L2.5 proxy (only when enabled & download scope on) ──- if (proxy) {- args.push(`--all-proxy=${proxy.allProxy}`)- if (proxy.noProxy) {- args.push(`--no-proxy=${proxy.noProxy}`)- }- }+ // ── L2.5 proxy ──+ // Always override every ambient/config-file proxy source. aria2 can read+ // protocol-specific proxy values from aria2.conf and conventional proxy+ // environment variables; leaving one unset would make the route differ+ // from the applied snapshot used by metadata validation.+ args.push(+ `--all-proxy=${proxyEndpoint}`,+ '--http-proxy=',+ '--http-proxy-user=',+ '--http-proxy-passwd=',+ '--https-proxy=',+ '--https-proxy-user=',+ '--https-proxy-passwd=',+ '--ftp-proxy=',+ '--ftp-proxy-user=',+ '--ftp-proxy-passwd=',+ `--all-proxy-user=${proxyCredentials.username}`,+ `--all-proxy-passwd=${proxyCredentials.password}`,+ `--no-proxy=${proxy?.noProxy ?? ''}`,+ '--proxy-method=get'+ )// ── L1 product-contract invariants — DO NOT REMOVE without spec change ──args.push(@@ -225,6 +253,8 @@ export class Aria2ConfigBuilder {'--pause=false','--pause-metadata=false','--bt-seed-unverified=false',+ '--http-accept-gzip=true',+ '--no-want-digest-header=false',// Remove unselected files when BT download completes. Without// this, piece-boundary writes leak partial / sparse placeholders// for every unselected file into saveDir, surfacing as confusing@@ -234,6 +264,13 @@ export class Aria2ConfigBuilder {'--bt-remove-unselected-file=true')+ // aria2 does not consume argv directly: it rewrites each option into a+ // line-oriented configuration stream. Reject line breaks at this single+ // boundary so every current and future option value is protected from+ // injecting a second configuration directive.+ if (args.some((arg) => /[\r\n]/.test(arg))) {+ throw new TypeError('aria2 option values must not contain CR or LF')+ }return args}}diff --git a/src/core/engine/aria2/aria2-process-manager.test.ts b/src/core/engine/aria2/aria2-process-manager.test.tsindex 7da1fa5f..567ab0c3 100644--- a/src/core/engine/aria2/aria2-process-manager.test.ts+++ b/src/core/engine/aria2/aria2-process-manager.test.ts@@ -264,6 +264,8 @@ describe('Aria2ProcessManager', () => {'--rpc-listen-port=16800','--rpc-secret=test','--all-proxy=http://local-user:[email protected]:43123',+ '--all-proxy-user=local-user',+ '--all-proxy-passwd=local-password',]const spawnPromise = manager.spawn('/usr/bin/aria2c', args)@@ -284,6 +286,8 @@ describe('Aria2ProcessManager', () => {'--rpc-listen-port=16800','--rpc-secret=<redacted>','--all-proxy=<redacted>',+ '--all-proxy-user=<redacted>',+ '--all-proxy-passwd=<redacted>',],},'aria2 process spawned'@@ -345,6 +349,8 @@ describe('Aria2ProcessManager', () => {const args = ['--rpc-secret=rpc-secret-value','--all-proxy=http://local-user:[email protected]:43123',+ '--all-proxy-user=local-user',+ '--all-proxy-passwd=local-password',]await manager.spawn('/missing/aria2c', args)@@ -362,8 +368,13 @@ describe('Aria2ProcessManager', () => {err: expect.objectContaining({code: 'ENOENT',message:- 'spawn failed: --rpc-secret=<redacted> --all-proxy=<redacted>',- spawnargs: ['--rpc-secret=<redacted>', '--all-proxy=<redacted>'],+ 'spawn failed: --rpc-secret=<redacted> --all-proxy=<redacted> --all-proxy-user=<redacted> --all-proxy-passwd=<redacted>',+ spawnargs: [+ '--rpc-secret=<redacted>',+ '--all-proxy=<redacted>',+ '--all-proxy-user=<redacted>',+ '--all-proxy-passwd=<redacted>',+ ],}),},'aria2 process error'@@ -383,6 +394,8 @@ describe('Aria2ProcessManager', () => {const sensitiveArgs = ['--rpc-secret=rpc-secret-value','--all-proxy=http://local-user:[email protected]:43123',+ '--all-proxy-user=local-user',+ '--all-proxy-passwd=local-password',]await manager.spawn('/usr/bin/aria2c', sensitiveArgs)const firstStderrHandler = firstChild.stderr.on.mock.calls[0]?.[1]@@ -396,6 +409,10 @@ describe('Aria2ProcessManager', () => {)expect(manager.getRecentStderr()).toContain('--rpc-secret=<redacted>')expect(manager.getRecentStderr()).toContain('--all-proxy=<redacted>')+ expect(manager.getRecentStderr()).toContain('--all-proxy-user=<redacted>')+ expect(manager.getRecentStderr()).toContain(+ '--all-proxy-passwd=<redacted>'+ )expect(manager.getRecentStderr()).not.toContain('rpc-secret-value')expect(manager.getRecentStderr()).not.toContain('local-password')diff --git a/src/core/engine/aria2/aria2-process-manager.ts b/src/core/engine/aria2/aria2-process-manager.tsindex 10d6ad7e..87e698d5 100644--- a/src/core/engine/aria2/aria2-process-manager.ts+++ b/src/core/engine/aria2/aria2-process-manager.ts@@ -26,7 +26,18 @@ const OWNER_MARKER_PREFIXES = ['--save-session=','--sqlite3-db-path=',] as const-const REDACTED_ARG_PREFIXES = ['--rpc-secret=', '--all-proxy='] as const+const REDACTED_ARG_PREFIXES = [+ '--rpc-secret=',+ '--all-proxy=',+ '--http-proxy-user=',+ '--http-proxy-passwd=',+ '--https-proxy-user=',+ '--https-proxy-passwd=',+ '--ftp-proxy-user=',+ '--ftp-proxy-passwd=',+ '--all-proxy-user=',+ '--all-proxy-passwd=',+] as constconst ownerRecordSchema = z.object({version: z.literal(OWNER_RECORD_VERSION),diff --git a/src/core/engine/aria2/aria2-trust-store.test.ts b/src/core/engine/aria2/aria2-trust-store.test.tsindex cc2351cd..e1a8da5a 100644--- a/src/core/engine/aria2/aria2-trust-store.test.ts+++ b/src/core/engine/aria2/aria2-trust-store.test.ts@@ -22,7 +22,7 @@ describe('Aria2TrustStore', () => {await rm(userConfigDir, { recursive: true, force: true })})- it('does nothing outside Linux', async () => {+ it('preserves non-proxy environment values outside Linux', async () => {const getCertificates = vi.fn()const trustStore = new Aria2TrustStore(userConfigDir, {platform: 'darwin',@@ -30,10 +30,30 @@ describe('Aria2TrustStore', () => {getCertificates,})- await expect(trustStore.prepareEnvironment()).resolves.toBeUndefined()+ await expect(trustStore.prepareEnvironment()).resolves.toEqual({+ PATH: '/usr/bin',+ })expect(getCertificates).not.toHaveBeenCalled()})+ it('removes every proxy environment spelling before spawning aria2', async () => {+ const trustStore = new Aria2TrustStore(userConfigDir, {+ platform: 'win32',+ env: {+ PATH: 'C:\\Windows',+ http_proxy: 'http://user:[email protected]:8080',+ HTTPS_PROXY: 'http://proxy.example:8443',+ Ftp_Proxy: 'http://proxy.example:2121',+ ALL_PROXY: 'http://proxy.example:3128',+ No_PrOxY: 'localhost,.internal',+ },+ })++ await expect(trustStore.prepareEnvironment()).resolves.toEqual({+ PATH: 'C:\\Windows',+ })+ })+it.each(['SSL_CERT_FILE', 'SSL_CERT_DIR'] as const)('preserves a caller-provided %s',async (variable) => {@@ -45,7 +65,7 @@ describe('Aria2TrustStore', () => {getCertificates,})- await expect(trustStore.prepareEnvironment()).resolves.toBe(env)+ await expect(trustStore.prepareEnvironment()).resolves.toEqual(env)expect(getCertificates).not.toHaveBeenCalled()})diff --git a/src/core/engine/aria2/aria2-trust-store.ts b/src/core/engine/aria2/aria2-trust-store.tsindex e31979d0..7ebe249e 100644--- a/src/core/engine/aria2/aria2-trust-store.ts+++ b/src/core/engine/aria2/aria2-trust-store.ts@@ -7,6 +7,13 @@ import writeFileAtomic from 'write-file-atomic'const log = getLogger('aria2')const CA_BUNDLE_FILENAME = 'aria2-ca-bundle.pem'+const PROXY_ENVIRONMENT_KEYS = new Set([+ 'http_proxy',+ 'https_proxy',+ 'ftp_proxy',+ 'all_proxy',+ 'no_proxy',+])type Aria2CertificateSource = 'system' | 'bundled'@@ -24,6 +31,14 @@ function normalizeCertificates(certificates: string[]): string[] {]}+function withoutProxyEnvironment(env: NodeJS.ProcessEnv): NodeJS.ProcessEnv {+ return Object.fromEntries(+ Object.entries(env).filter(+ ([key]) => !PROXY_ENVIRONMENT_KEYS.has(key.toLowerCase())+ )+ )+}+export class Aria2TrustStore {private readonly platform: NodeJS.Platformprivate readonly env: NodeJS.ProcessEnv@@ -40,12 +55,16 @@ export class Aria2TrustStore {this.bundlePath = path.join(userConfigDir, CA_BUNDLE_FILENAME)}- async prepareEnvironment(): Promise<NodeJS.ProcessEnv | undefined> {- if (this.platform !== 'linux') return undefined+ async prepareEnvironment(): Promise<NodeJS.ProcessEnv> {+ // Motrix's applied proxy policy must be the only source of aria2 routing.+ // aria2 otherwise imports protocol-specific proxy environment variables,+ // which can override both all-proxy and the metadata client's route.+ const childEnvironment = withoutProxyEnvironment(this.env)+ if (this.platform !== 'linux') return childEnvironmentif (this.env.SSL_CERT_FILE?.trim() || this.env.SSL_CERT_DIR?.trim()) {log.info('using caller-provided OpenSSL trust store for aria2')- return this.env+ return childEnvironment}let certificates: string[] = []@@ -78,7 +97,7 @@ export class Aria2TrustStore {)return {- ...this.env,+ ...childEnvironment,SSL_CERT_FILE: this.bundlePath,}}diff --git a/src/core/engine/engine-adapter.ts b/src/core/engine/engine-adapter.tsindex ed948d72..c9dd1157 100644--- a/src/core/engine/engine-adapter.ts+++ b/src/core/engine/engine-adapter.ts@@ -32,6 +32,16 @@ export interface OutputFilePath {*/export type DownloadResumePolicy = 'none' | 'checkpoint' | 'sequential-prefix'+/**+ * Versioned aria2 HTTP request shape mirrored by DirectResourceValidator.+ * Callers may persist only the identifier; it contains no header values or+ * credentials.+ */+export const DIRECT_RESOURCE_METADATA_PROFILE =+ 'aria2-http-baseline-v1' as const+export type DirectResourceMetadataProfile =+ typeof DIRECT_RESOURCE_METADATA_PROFILE+export interface AddTorrentParams {metadata: Uint8ArraysaveDir: string@@ -76,6 +86,14 @@ export interface CreateDownloadParams {gid?: stringfilename?: stringheaders?: Record<string, string>+ /** Effective engine User-Agent pinned for this request lifecycle. */+ userAgent?: string+ /**+ * Internal proof that ambient aria2 HTTP options were compatible when the+ * matching metadata request ran. Aria2 adapters re-check the profile before+ * dispatch and pin the corresponding per-task request options.+ */+ directResourceMetadataProfile?: DirectResourceMetadataProfile// ── create-path additions (was Aria2TaskRequestAdapter) ──/** Requested per-server connections. Adapter maps to split +* max-connection-per-server. Caller is responsible for clamping. */@@ -116,6 +134,13 @@ export interface EngineAdapter {*/getFeatureReport(): EngineFeatureReport+ /**+ * Return the currently reproducible HTTP request profile, or null when+ * ambient engine options (headers/cookies/auth/etc.) make metadata probing+ * unsafe. Optional for non-aria2 adapters and lightweight test doubles.+ */+ getDirectResourceMetadataProfile?(): DirectResourceMetadataProfile | null+createDownload(params: CreateDownloadParams): Promise<string>pauseTask(engineTaskId: string): Promise<void>resumeTask(engineTaskId: string): Promise<void>diff --git a/src/core/engine/engine-supervisor.test.ts b/src/core/engine/engine-supervisor.test.tsindex bcccefcf..cbdd3d7b 100644--- a/src/core/engine/engine-supervisor.test.ts+++ b/src/core/engine/engine-supervisor.test.ts@@ -1,5 +1,6 @@import { registerEngineFailureSubscriber } from '@core/notifications/engine-failure-subscriber'import { NotificationCenter } from '@core/notifications/notification-center'+import { AppliedDownloadProxyPolicy } from '@core/proxy/applied-download-proxy-policy'import { MotrixDatabase } from '@core/session/motrix-database'import { ErrorCode } from '@shared/errors'import { Events } from '@shared/protocol/events'@@ -22,6 +23,7 @@ import type { Aria2ConfigBuilder } from './aria2/aria2-config-builder'import type { Aria2ProcessManager } from './aria2/aria2-process-manager'import type { Aria2RpcClient } from './aria2/aria2-rpc-client'import type { Aria2TrustStore } from './aria2/aria2-trust-store'+import { DIRECT_RESOURCE_METADATA_PROFILE } from './engine-adapter'import { EngineSupervisor } from './engine-supervisor'import { checkPort } from './port-check'@@ -144,6 +146,11 @@ function createMockTrustStore(): Aria2TrustStore {function createMockAdapter(): Aria2Adapter {return {setFeatureReport: vi.fn(),+ inspectDirectResourceMetadataProfile: vi+ .fn()+ .mockResolvedValue(DIRECT_RESOURCE_METADATA_PROFILE),+ setDirectResourceMetadataProfile: vi.fn(),+ getDirectResourceMetadataProfile: vi.fn(() => null),} as unknown as Aria2Adapter}@@ -234,6 +241,146 @@ describe('EngineSupervisor', () => {)})+ it('commits the exact resolved route before publishing Ready', async () => {+ const resolved = {+ allProxy: 'http://bridge-user:[email protected]:43123',+ noProxy: 'localhost',+ }+ proxyBridge.resolveForDownload.mockResolvedValue(resolved)+ const order: string[] = []+ const policy = {+ commit: vi.fn(() => {+ order.push('commit')+ }),+ markUnavailable: vi.fn(),+ }+ eventBus.on(Events.EngineRecovered, () => order.push('ready'))+ supervisor = new EngineSupervisor(+ eventBus,+ settings,+ processManager,+ configBuilder,+ trustStore,+ rpcClient,+ adapter,+ proxyBridge,+ policy+ )++ await supervisor.start('/usr/bin/aria2c')+ expect(policy.commit).toHaveBeenCalledWith(resolved)+ expect(order).toEqual(['commit', 'ready'])+ expect(supervisor.getState()).toBe(EngineState.Ready)+ })++ it('repairs a proxy update persisted while the engine is Starting', async () => {+ const before = {+ enabled: true,+ protocol: 'http' as const,+ host: 'before.example',+ port: 8080,+ user: '',+ password: '',+ bypass: [],+ scopes: {+ download: true,+ updateApp: false,+ updateTrackers: false,+ },+ }+ const after = { ...before, host: 'after.example' }+ let current = before+ vi.mocked(settings.getProxy).mockImplementation(() => current)+ proxyBridge.resolveForDownload.mockImplementation(async (value) => ({+ allProxy: `http://${value.host}:${value.port}`,+ noProxy: value.bypass.join(','),+ }))+ let releaseConnect: (() => void) | undefined+ vi.mocked(rpcClient.connect).mockImplementation(+ () =>+ new Promise<void>((resolve) => {+ releaseConnect = resolve+ })+ )+ const policy = new AppliedDownloadProxyPolicy()+ supervisor = new EngineSupervisor(+ eventBus,+ settings,+ processManager,+ configBuilder,+ trustStore,+ rpcClient,+ adapter,+ proxyBridge,+ policy+ )++ const startup = supervisor.start('/usr/bin/aria2c')+ await vi.waitFor(() => expect(rpcClient.connect).toHaveBeenCalled())+ current = after+ const earlyTransition = policy.applyTransition(() =>+ supervisor+ .applyProxyChange({+ allProxy: 'http://after.example:8080',+ noProxy: '',+ })+ .then((applied) =>+ applied+ ? {+ downloadProxy: 'applied' as const,+ appliedProxy: {+ allProxy: 'http://after.example:8080',+ noProxy: '',+ },+ }+ : { downloadProxy: 'unavailable' as const }+ )+ )+ await earlyTransition+ expect(policy.snapshot()).toBeNull()++ releaseConnect?.()+ await startup++ expect(supervisor.getState()).toBe(EngineState.Ready)+ expect(policy.snapshot()).toEqual({+ proxy: 'http://after.example:8080',+ noProxy: '',+ })+ expect(rpcClient.changeGlobalOption).toHaveBeenCalledWith(+ expect.objectContaining({+ 'all-proxy': 'http://after.example:8080',+ 'no-proxy': '',+ 'proxy-method': 'get',+ })+ )+ })++ it('does not commit an applied route when startup fails', async () => {+ const policy = {+ commit: vi.fn(),+ markUnavailable: vi.fn(),+ }+ vi.mocked(rpcClient.connect).mockRejectedValue(new Error('RPC down'))+ supervisor = new EngineSupervisor(+ eventBus,+ settings,+ processManager,+ configBuilder,+ trustStore,+ rpcClient,+ adapter,+ proxyBridge,+ policy+ )++ await supervisor.start('/usr/bin/aria2c')++ expect(policy.commit).not.toHaveBeenCalled()+ expect(policy.markUnavailable).toHaveBeenCalled()+ expect(supervisor.getState()).toBe(EngineState.Failed)+ })+it('transitions Stopped → Starting → Ready', async () => {const states: EngineState[] = []eventBus.on(Events.EngineStateChanged, (state) => {@@ -246,6 +393,45 @@ describe('EngineSupervisor', () => {expect(supervisor.getState()).toBe(EngineState.Ready)})+ it('publishes the sanitized metadata profile before Ready and clears it on stop', async () => {+ const readyObserved = vi.fn()+ eventBus.on(Events.EngineStateChanged, (state) => {+ if (state === EngineState.Ready) readyObserved()+ })++ await supervisor.start('/usr/bin/aria2c')++ expect(+ adapter.inspectDirectResourceMetadataProfile+ ).toHaveBeenCalledOnce()+ expect(adapter.setDirectResourceMetadataProfile).toHaveBeenCalledWith(+ DIRECT_RESOURCE_METADATA_PROFILE+ )+ expect(+ vi+ .mocked(adapter.setDirectResourceMetadataProfile)+ .mock.invocationCallOrder.at(-1)+ ).toBeLessThan(readyObserved.mock.invocationCallOrder[0] as number)++ await supervisor.stop()+ expect(adapter.setDirectResourceMetadataProfile).toHaveBeenLastCalledWith(+ null+ )+ })++ it('keeps the engine Ready with a fail-closed profile when inspection fails', async () => {+ vi.mocked(adapter.inspectDirectResourceMetadataProfile).mockRejectedValue(+ new Error('profile unavailable')+ )++ await supervisor.start('/usr/bin/aria2c')++ expect(supervisor.getState()).toBe(EngineState.Ready)+ expect(adapter.setDirectResourceMetadataProfile).toHaveBeenCalledWith(+ null+ )+ })+it('synchronizes the latest RPC secret on every start before authenticated calls', async () => {const initial = settings.getEngine()let current = initial@@ -1381,7 +1567,19 @@ describe('EngineSupervisor', () => {})expect(rpcClient.changeGlobalOption).toHaveBeenCalledWith({'all-proxy': 'http://p:80',+ 'http-proxy': '',+ 'http-proxy-user': '',+ 'http-proxy-passwd': '',+ 'https-proxy': '',+ 'https-proxy-user': '',+ 'https-proxy-passwd': '',+ 'ftp-proxy': '',+ 'ftp-proxy-user': '',+ 'ftp-proxy-passwd': '',+ 'all-proxy-user': '',+ 'all-proxy-passwd': '','no-proxy': 'localhost',+ 'proxy-method': 'get',})})@@ -1390,8 +1588,69 @@ describe('EngineSupervisor', () => {await supervisor.applyProxyChange(null)expect(rpcClient.changeGlobalOption).toHaveBeenCalledWith({'all-proxy': '',+ 'http-proxy': '',+ 'http-proxy-user': '',+ 'http-proxy-passwd': '',+ 'https-proxy': '',+ 'https-proxy-user': '',+ 'https-proxy-passwd': '',+ 'ftp-proxy': '',+ 'ftp-proxy-user': '',+ 'ftp-proxy-passwd': '',+ 'all-proxy-user': '',+ 'all-proxy-passwd': '','no-proxy': '',+ 'proxy-method': 'get',+ })+ })++ it('pins decoded all-proxy credentials during a hot update', async () => {+ await supervisor.start('/usr/bin/aria2c')+ await supervisor.applyProxyChange({+ allProxy: 'http://a%40b:p%3As@p:80',+ noProxy: '',+ })++ expect(rpcClient.changeGlobalOption).toHaveBeenLastCalledWith(+ expect.objectContaining({+ 'all-proxy': 'http://p:80',+ 'all-proxy-user': 'a@b',+ 'all-proxy-passwd': 'p:s',+ 'proxy-method': 'get',+ })+ )+ })++ it('accepts equivalent expanded IPv6 proxy authorities during a hot update', async () => {+ await supervisor.start('/usr/bin/aria2c')+ await supervisor.applyProxyChange({+ allProxy: 'http://user:pass@[0:0:0:0:0:0:0:1]:8080',+ noProxy: '',+ })++ expect(rpcClient.changeGlobalOption).toHaveBeenLastCalledWith(+ expect.objectContaining({+ 'all-proxy': 'http://[0:0:0:0:0:0:0:1]:8080',+ 'all-proxy-user': 'user',+ 'all-proxy-passwd': 'pass',+ })+ )+ })++ it('preserves an aria2-compatible legacy IPv4 proxy during a hot update', async () => {+ await supervisor.start('/usr/bin/aria2c')+ await supervisor.applyProxyChange({+ allProxy: 'http://user:[email protected]:8080',+ noProxy: '',})++ expect(rpcClient.changeGlobalOption).toHaveBeenLastCalledWith(+ expect.objectContaining({+ 'all-proxy': 'http://127.1:8080',+ 'all-proxy-user': 'user',+ 'all-proxy-passwd': 'pass',+ })+ )})})diff --git a/src/core/engine/engine-supervisor.ts b/src/core/engine/engine-supervisor.tsindex f005b4ab..dd043b7c 100644--- a/src/core/engine/engine-supervisor.ts+++ b/src/core/engine/engine-supervisor.ts@@ -1,6 +1,12 @@import path from 'node:path'import { getLogger } from '@core/logger'+import type { AppliedDownloadProxyPolicy } from '@core/proxy/applied-download-proxy-policy'+import {+ extractAria2ProxyCredentials,+ stripAria2ProxyCredentials,+} from '@core/proxy/aria2-proxy-routing'import type { ProxyBridgeResolver } from '@core/proxy/proxy-bridge-manager'+import type { Aria2ProxyOptions } from '@core/proxy/serializers'import { ENGINE_RPC_PORT } from '@shared/constants'import { AppError, ErrorCode } from '@shared/errors'import { Events } from '@shared/protocol/events'@@ -34,6 +40,7 @@ import {isMotrixFork,STANDARD_ARIA2_CONNECTION_LIMIT,} from './aria2/feature-report'+import type { DirectResourceMetadataProfile } from './engine-adapter'import { checkPort, findAvailablePort } from './port-check'const log = getLogger('engine')@@ -49,6 +56,14 @@ const MAX_RESTARTS = 5const HEALTH_CHECK_INTERVAL = 30_000const MAX_CONSECUTIVE_FAILURES = 3+function sameProxyOptions(+ left: Aria2ProxyOptions | null,+ right: Aria2ProxyOptions | null+): boolean {+ if (left === null || right === null) return left === right+ return left.allProxy === right.allProxy && left.noProxy === right.noProxy+}+const HOT_ENGINE_OPTIONS = {maxConcurrentDownloads: 'max-concurrent-downloads',maxConnectionPerServer: 'max-connection-per-server',@@ -103,7 +118,12 @@ export class EngineSupervisor {private trustStore: Aria2TrustStore,private rpcClient: Aria2RpcClient,private adapter: Aria2Adapter,- private proxyBridge: Pick<ProxyBridgeResolver, 'resolveForDownload'>+ private proxyBridge: Pick<ProxyBridgeResolver, 'resolveForDownload'>,+ private appliedDownloadProxyPolicy?: Pick<+ AppliedDownloadProxyPolicy,+ 'commit' | 'markUnavailable'+ > &+ Partial<Pick<AppliedDownloadProxyPolicy, 'publishStartupRoute'>>) {// Wire up process exit handlerthis.processManager.onExit = (code, _signal) => {@@ -317,11 +337,38 @@ export class EngineSupervisor {*/async applyProxyChange(opts: { allProxy: string; noProxy: string } | null+ ): Promise<boolean> {+ if (this.state !== EngineState.Ready) return false+ await this.writeGlobalProxyOptions(opts)+ return true+ }++ private async writeGlobalProxyOptions(+ opts: Aria2ProxyOptions | null): Promise<void> {- if (this.state !== EngineState.Ready) return- const params = opts- ? { 'all-proxy': opts.allProxy, 'no-proxy': opts.noProxy }- : { 'all-proxy': '', 'no-proxy': '' }+ const proxyCredentials = opts+ ? extractAria2ProxyCredentials(opts.allProxy)+ : { username: '', password: '' }+ const proxyEndpoint = opts ? stripAria2ProxyCredentials(opts.allProxy) : ''+ if (!proxyCredentials || proxyEndpoint === null) {+ throw new TypeError('Unsupported aria2 proxy credentials')+ }+ const params = {+ 'all-proxy': proxyEndpoint,+ 'http-proxy': '',+ 'http-proxy-user': '',+ 'http-proxy-passwd': '',+ 'https-proxy': '',+ 'https-proxy-user': '',+ 'https-proxy-passwd': '',+ 'ftp-proxy': '',+ 'ftp-proxy-user': '',+ 'ftp-proxy-passwd': '',+ 'all-proxy-user': proxyCredentials.username,+ 'all-proxy-passwd': proxyCredentials.password,+ 'no-proxy': opts?.noProxy ?? '',+ 'proxy-method': 'get',+ }await this.rpcClient.changeGlobalOption(params)}@@ -412,8 +459,9 @@ export class EngineSupervisor {// every start so an explicit settings rotation authenticates the first// RPC sent to the newly spawned aria2 process.this.rpcClient.setSecret(engineSettings.rpcSecret)- const proxy = this.settingsManager.getProxy()- const resolvedProxy = await this.proxyBridge.resolveForDownload(proxy)+ const configuredProxy = structuredClone(this.settingsManager.getProxy())+ const resolvedProxy =+ await this.proxyBridge.resolveForDownload(configuredProxy)if (this.stopping) returnconst defaultSaveDir = this.settingsManager.getApp().defaultSaveDir// Provider is wired by the shell (Task 8) before start() in production;@@ -487,6 +535,22 @@ export class EngineSupervisor {// resume behavior. Motrix-owned recovery still overrides `continue`// explicitly per task where safety requires it.await this.rpcClient.changeGlobalOption({ continue: 'true' })+ // Inspect only a sanitized compatibility decision. Raw global options+ // can contain passwords, custom headers and cookie paths and must never+ // be cached on the adapter or published to task composition.+ let pendingMetadataProfile: DirectResourceMetadataProfile | null = null+ try {+ pendingMetadataProfile =+ typeof this.adapter.inspectDirectResourceMetadataProfile ===+ 'function'+ ? await this.adapter.inspectDirectResourceMetadataProfile()+ : null+ } catch (error) {+ log.debug(+ { err: error },+ 'aria2 HTTP metadata request profile inspection failed closed'+ )+ }// Step 6: Readyif (this.stopping) {@@ -494,7 +558,35 @@ export class EngineSupervisor {await this.processManager.gracefulStop()return}- this.setState(EngineState.Ready)+ const publishReady = () => {+ this.adapter.setDirectResourceMetadataProfile?.(pendingMetadataProfile)+ this.setState(EngineState.Ready)+ }+ if (this.appliedDownloadProxyPolicy?.publishStartupRoute) {+ const published =+ await this.appliedDownloadProxyPolicy.publishStartupRoute(+ async () => {+ // A proxy update can be persisted after buildArgs() captured its+ // startup route but before aria2 connects. Re-resolve under the+ // policy writer and repair aria2 before publishing Ready.+ const latestConfiguredProxy = structuredClone(+ this.settingsManager.getProxy()+ )+ const latestResolvedProxy =+ await this.proxyBridge.resolveForDownload(latestConfiguredProxy)+ if (!sameProxyOptions(resolvedProxy, latestResolvedProxy)) {+ await this.writeGlobalProxyOptions(latestResolvedProxy)+ }+ return latestResolvedProxy+ },+ publishReady,+ () => !this.stopping+ )+ if (!published) return+ } else {+ this.appliedDownloadProxyPolicy?.commit(resolvedProxy)+ publishReady()+ }this.lastError = nullthis.failure = nullthis.restartAttempts = 0@@ -675,6 +767,11 @@ export class EngineSupervisor {if (prev === newState) returnthis.state = newState+ if (newState !== EngineState.Ready) {+ this.adapter.setDirectResourceMetadataProfile?.(null)+ this.appliedDownloadProxyPolicy?.markUnavailable()+ }+this.eventBus.emit(Events.EngineStateChanged, newState)if (prev === EngineState.Ready && newState !== EngineState.Ready) {@@ -943,4 +1040,13 @@ export class EngineSupervisor {this.eventBus.on(Events.EngineStateChanged, onState)})}++ assertReady(): void {+ if (this.state !== EngineState.Ready) {+ throw new AppError(+ ErrorCode.EngineConnectionLost,+ `engine is not ready (${this.state})`+ )+ }+ }}diff --git a/src/core/geoip/geo-ip-downloader.test.ts b/src/core/geoip/geo-ip-downloader.test.tsindex 9bc35345..da20b07a 100644--- a/src/core/geoip/geo-ip-downloader.test.ts+++ b/src/core/geoip/geo-ip-downloader.test.ts@@ -116,13 +116,51 @@ describe('GeoIPDownloader.download', () => {})it('surfaces non-2xx responses as download errors', async () => {+ const cancel = vi.fn()vi.spyOn(globalThis, 'fetch').mockResolvedValue(- new Response('not found', { status: 404, statusText: 'Not Found' })+ new Response(+ new ReadableStream<Uint8Array>({+ start(controller) {+ controller.enqueue(new TextEncoder().encode('not found'))+ },+ cancel,+ }),+ { status: 404, statusText: 'Not Found' }+ ))const dl = new GeoIPDownloader()await expect(dl.download('https://example.com/db.mmdb', dbPath)).rejects.toThrow(/http 404/)+ expect(cancel).toHaveBeenCalledOnce()+ })++ it('releases and cancels the response body when streaming work throws', async () => {+ const cancel = vi.fn()+ vi.spyOn(globalThis, 'fetch').mockResolvedValue(+ new Response(+ new ReadableStream<Uint8Array>({+ start(controller) {+ controller.enqueue(new Uint8Array(1024))+ },+ cancel,+ }),+ { status: 200 }+ )+ )+ const dl = new GeoIPDownloader({+ timeoutMs: 60_000,+ progressByteThreshold: 1,+ progressTimeThresholdMs: 250,+ })++ await expect(+ dl.download('https://example.com/db.mmdb', dbPath, () => {+ throw new Error('progress failed')+ })+ ).rejects.toThrow('progress failed')++ expect(cancel).toHaveBeenCalledOnce()})it('surfaces network failures', async () => {diff --git a/src/core/geoip/geo-ip-downloader.ts b/src/core/geoip/geo-ip-downloader.tsindex ca32075e..303603a5 100644--- a/src/core/geoip/geo-ip-downloader.ts+++ b/src/core/geoip/geo-ip-downloader.ts@@ -15,6 +15,17 @@ const MMDB_METADATA_TAIL = 'MaxMind.com'export type ProgressListener = (progress: DownloadProgress) => void+async function cancelResponseBody(+ response: Response,+ reason?: unknown+): Promise<void> {+ try {+ await response.body?.cancel(reason)+ } catch {+ // Preserve the download error when cancellation races a closed body.+ }+}+/*** Stream a `.mmdb` file from `url` into `dbPath` atomically.*@@ -63,44 +74,44 @@ export class GeoIPDownloader {)}- if (!response.ok) {- clearTimeout(timeoutId)- throw new AppError(- ErrorCode.GeoIPDownloadFailed,- `http ${response.status} ${response.statusText} for ${url}`- )- }+ let bodyConsumed = false+ try {+ if (!response.ok) {+ throw new AppError(+ ErrorCode.GeoIPDownloadFailed,+ `http ${response.status} ${response.statusText} for ${url}`+ )+ }- const totalHeader = response.headers.get('content-length')- const bytesTotal = totalHeader ? Number.parseInt(totalHeader, 10) : -1- const version = deriveVersion(response.headers)-- let bytesReceived = 0- let lastEmitBytes = 0- let lastEmitTime = Date.now()- const chunks: Uint8Array[] = []-- const emit = (force = false) => {- const now = Date.now()- const elapsed = now - lastEmitTime- const delta = bytesReceived - lastEmitBytes- if (- !force &&- delta < this.options.progressByteThreshold &&- elapsed < this.options.progressTimeThresholdMs- ) {- return+ const totalHeader = response.headers.get('content-length')+ const bytesTotal = totalHeader ? Number.parseInt(totalHeader, 10) : -1+ const version = deriveVersion(response.headers)++ let bytesReceived = 0+ let lastEmitBytes = 0+ let lastEmitTime = Date.now()+ const chunks: Uint8Array[] = []++ const emit = (force = false) => {+ const now = Date.now()+ const elapsed = now - lastEmitTime+ const delta = bytesReceived - lastEmitBytes+ if (+ !force &&+ delta < this.options.progressByteThreshold &&+ elapsed < this.options.progressTimeThresholdMs+ ) {+ return+ }+ lastEmitBytes = bytesReceived+ lastEmitTime = now+ onProgress?.({+ bytesReceived,+ bytesTotal,+ percent: bytesTotal > 0 ? bytesReceived / bytesTotal : -1,+ })}- lastEmitBytes = bytesReceived- lastEmitTime = now- onProgress?.({- bytesReceived,- bytesTotal,- percent: bytesTotal > 0 ? bytesReceived / bytesTotal : -1,- })- }- try {const body = response.bodyif (!body) {throw new AppError(@@ -110,62 +121,70 @@ export class GeoIPDownloader {}const reader = body.getReader()- while (true) {- const { value, done } = await reader.read()- if (done) break- if (value) {- chunks.push(value)- bytesReceived += value.byteLength- emit(false)+ try {+ while (true) {+ const { value, done } = await reader.read()+ if (done) break+ if (value) {+ chunks.push(value)+ bytesReceived += value.byteLength+ emit(false)+ }}+ } finally {+ reader.releaseLock()}- } finally {- clearTimeout(timeoutId)- }+ bodyConsumed = true- const buffer = Buffer.concat(chunks)- if (buffer.length < MIN_VALID_SIZE_BYTES) {- throw new AppError(- ErrorCode.GeoIPDatabaseInvalid,- `database too small (${buffer.length} bytes)`- )- }- if (!hasMmdbSentinel(buffer)) {- throw new AppError(- ErrorCode.GeoIPDatabaseInvalid,- 'MaxMind.com metadata marker not found — file is not a valid .mmdb'- )- }+ const buffer = Buffer.concat(chunks)+ if (buffer.length < MIN_VALID_SIZE_BYTES) {+ throw new AppError(+ ErrorCode.GeoIPDatabaseInvalid,+ `database too small (${buffer.length} bytes)`+ )+ }+ if (!hasMmdbSentinel(buffer)) {+ throw new AppError(+ ErrorCode.GeoIPDatabaseInvalid,+ 'MaxMind.com metadata marker not found — file is not a valid .mmdb'+ )+ }- try {- // writeFileAtomic handles fsync + rename + tmp cleanup on- // failure, so we no longer need an explicit unlink in the- // catch path.- await writeFileAtomic(dbPath, buffer)- } catch (err) {- throw new AppError(- ErrorCode.GeoIPDownloadFailed,- `failed to install database: ${(err as Error).message}`,- err- )- }+ try {+ // writeFileAtomic handles fsync + rename + tmp cleanup on+ // failure, so we no longer need an explicit unlink in the+ // catch path.+ await writeFileAtomic(dbPath, buffer)+ } catch (err) {+ throw new AppError(+ ErrorCode.GeoIPDownloadFailed,+ `failed to install database: ${(err as Error).message}`,+ err+ )+ }- onProgress?.({- bytesReceived,- bytesTotal: bytesTotal > 0 ? bytesTotal : bytesReceived,- percent: 1,- })+ onProgress?.({+ bytesReceived,+ bytesTotal: bytesTotal > 0 ? bytesTotal : bytesReceived,+ percent: 1,+ })- let installedSize = bytesReceived- try {- const s = await stat(dbPath)- installedSize = s.size- } catch {- // stat failure is non-fatal: bytesReceived from the stream is a- // safe approximation for status reporting.- }+ let installedSize = bytesReceived+ try {+ const s = await stat(dbPath)+ installedSize = s.size+ } catch {+ // stat failure is non-fatal: bytesReceived from the stream is a+ // safe approximation for status reporting.+ }- return { sizeBytes: installedSize, version }+ return { sizeBytes: installedSize, version }+ } catch (error) {+ if (!bodyConsumed) await cancelResponseBody(response, error)+ throw error+ } finally {+ clearTimeout(timeoutId)+ }}}diff --git a/src/core/media/manifest-fetcher.test.ts b/src/core/media/manifest-fetcher.test.tsindex 8168c78f..8ef6c726 100644--- a/src/core/media/manifest-fetcher.test.ts+++ b/src/core/media/manifest-fetcher.test.ts@@ -19,11 +19,24 @@ describe('fetchManifest', () => {})it('throws with the status on non-2xx', async () => {- const fetchImpl = vi.fn(async () => new Response('no', { status: 403 }))+ const cancel = vi.fn()+ const fetchImpl = vi.fn(+ async () =>+ new Response(+ new ReadableStream<Uint8Array>({+ start(controller) {+ controller.enqueue(new TextEncoder().encode('no'))+ },+ cancel,+ }),+ { status: 403 }+ )+ )await expect(fetchManifest('https://h.example/m.m3u8', {fetchImpl: fetchImpl as unknown as typeof fetch,})).rejects.toThrow(/403/)+ expect(cancel).toHaveBeenCalledOnce()})})diff --git a/src/core/media/manifest-fetcher.ts b/src/core/media/manifest-fetcher.tsindex a76269d4..578917df 100644--- a/src/core/media/manifest-fetcher.ts+++ b/src/core/media/manifest-fetcher.ts@@ -1,5 +1,13 @@const DEFAULT_MAX = 5 * 1024 * 1024+async function cancelResponseBody(response: Response): Promise<void> {+ try {+ await response.body?.cancel()+ } catch {+ // Preserve the HTTP error when body cancellation also fails.+ }+}+export async function fetchManifest(url: string,opts: {@@ -15,6 +23,7 @@ export async function fetchManifest(redirect: 'follow',})if (!res.ok) {+ await cancelResponseBody(res)throw new Error(`manifest fetch failed: HTTP ${res.status}`)}const text = await res.text()diff --git a/src/core/plugin/capabilities/http.proxy-lifecycle.test.ts b/src/core/plugin/capabilities/http.proxy-lifecycle.test.tsnew file mode 100644index 00000000..fda4cf54--- /dev/null+++ b/src/core/plugin/capabilities/http.proxy-lifecycle.test.ts@@ -0,0 +1,155 @@+import { Readable } from 'node:stream'+import { beforeEach, describe, expect, it, vi } from 'vitest'++const mocks = vi.hoisted(() => ({+ request: vi.fn(),+ sharedDestroy: vi.fn(async () => undefined),+ proxyAgents: [] as Array<{+ options: unknown+ destroy: ReturnType<typeof vi.fn>+ }>,+}))++vi.mock('undici', () => ({+ Agent: class MockAgent {+ destroy = mocks.sharedDestroy+ },+ ProxyAgent: class MockProxyAgent {+ readonly destroy = vi.fn(async () => undefined)++ constructor(readonly options: unknown) {+ mocks.proxyAgents.push(this)+ }+ },+ request: (...args: unknown[]) => mocks.request(...args),+}))++const { HttpCapabilityHost } = await import('./http')++function response(body: Readable = Readable.from(Buffer.from('ok'))) {+ return { statusCode: 200, headers: {}, body }+}++beforeEach(() => {+ mocks.request.mockReset()+ mocks.sharedDestroy.mockClear()+ mocks.proxyAgents.splice(0)+})++describe('HttpCapabilityHost proxy lifecycle', () => {+ it('destroys an owned HTTP ProxyAgent after a successful response', async () => {+ mocks.request.mockResolvedValueOnce(response())++ const result = await new HttpCapabilityHost().get(+ 'https://downloads.example/file',+ { proxy: 'http://127.0.0.1:8080' }+ )++ expect(result.body).toBe('ok')+ expect(mocks.proxyAgents).toHaveLength(1)+ expect(mocks.request.mock.calls[0]?.[1]).toMatchObject({+ dispatcher: mocks.proxyAgents[0],+ })+ expect(mocks.proxyAgents[0]?.destroy).toHaveBeenCalledOnce()+ expect(mocks.sharedDestroy).not.toHaveBeenCalled()+ })++ it('destroys an owned HTTP ProxyAgent when the request rejects', async () => {+ mocks.request.mockRejectedValueOnce(new Error('connect failed'))++ await expect(+ new HttpCapabilityHost().get('https://downloads.example/file', {+ proxy: 'https://127.0.0.1:8443',+ })+ ).rejects.toMatchObject({ code: 'plugin.http.network' })++ expect(mocks.proxyAgents).toHaveLength(1)+ expect(mocks.proxyAgents[0]?.destroy).toHaveBeenCalledOnce()+ })++ it('does not allocate a ProxyAgent for an already-aborted request', async () => {+ const controller = new AbortController()+ controller.abort()++ await expect(+ new HttpCapabilityHost().get('https://downloads.example/file', {+ proxy: 'http://127.0.0.1:8080',+ signal: controller.signal,+ })+ ).rejects.toMatchObject({ code: 'plugin.http.aborted' })++ expect(mocks.proxyAgents).toHaveLength(0)+ expect(mocks.request).not.toHaveBeenCalled()+ })++ it('fails closed for SOCKS proxies before opening a connection', async () => {+ await expect(+ new HttpCapabilityHost().get('https://downloads.example/file', {+ proxy: 'socks5://127.0.0.1:1080',+ })+ ).rejects.toMatchObject({+ code: 'plugin.http.proxy_scheme_not_supported',+ })++ expect(mocks.proxyAgents).toHaveLength(0)+ expect(mocks.request).not.toHaveBeenCalled()+ })++ it('cancels a stalled response body and reports a body-phase timeout', async () => {+ let body: Readable | undefined+ mocks.request.mockImplementationOnce(+ async (_url: unknown, options: { signal: AbortSignal }) => {+ body = Readable.from(+ (async function* () {+ yield Buffer.from('partial')+ await new Promise<void>((_resolve, reject) => {+ options.signal.addEventListener(+ 'abort',+ () => reject(new Error('body aborted')),+ { once: true }+ )+ })+ })()+ )+ return response(body)+ }+ )++ await expect(+ new HttpCapabilityHost({ defaultTimeoutMs: 10 }).get(+ 'https://downloads.example/file',+ { proxy: 'http://127.0.0.1:8080' }+ )+ ).rejects.toMatchObject({ code: 'plugin.http.timeout' })++ expect(body?.destroyed).toBe(true)+ expect(mocks.proxyAgents[0]?.destroy).toHaveBeenCalledOnce()+ })++ it('installs an error listener before destroying an unread response', async () => {+ const order: string[] = []+ const body = {+ once: vi.fn((event: string) => {+ order.push(`once:${event}`)+ }),+ destroy: vi.fn(() => {+ order.push('destroy')+ }),+ }+ mocks.request.mockResolvedValueOnce({+ statusCode: 302,+ headers: { location: 'https://downloads.example/redirected' },+ body,+ })++ await expect(+ new HttpCapabilityHost().get('https://downloads.example/file', {+ proxy: 'http://127.0.0.1:8080',+ redirect: 'error',+ })+ ).rejects.toMatchObject({ code: 'plugin.http.redirect_not_allowed' })++ expect(order.slice(0, 2)).toEqual(['once:error', 'destroy'])+ expect(mocks.proxyAgents[0]?.destroy).toHaveBeenCalledOnce()+ })+})diff --git a/src/core/plugin/capabilities/http.ts b/src/core/plugin/capabilities/http.tsindex 70510594..eae592a2 100644--- a/src/core/plugin/capabilities/http.ts+++ b/src/core/plugin/capabilities/http.ts@@ -9,7 +9,7 @@// - Timeout: default 30 s; hard cap 300 s.// - Redirect: 'follow' (up to 10), 'manual', or 'error' (reject any 3xx).// - Range: `{start, end}` generates a `Range: bytes=start-end` header.-// - Proxy: `http://host:port` / `socks5://...` etc.; per-request override.+// - Proxy: `http://host:port` / `https://host:port`; per-request override.// - Cookies: opt-in via cookies: 'jar' (reads jar before, captures after).// - AbortSignal chaining: plugin's signal + internal timeout both abort.// - JSON body shorthand: body.type === 'json' auto-serializes + Content-Type.@@ -79,7 +79,7 @@ export interface HttpRequestOptions<R extends HttpResponseType = 'text'> {cookies?: 'jar' | 'none'/** Partial download via `Range: bytes=start-end`. */range?: { start: number; end: number }- /** `http://`, `https://`, or `socks5://` URL; per-request override. */+ /** `http://` or `https://` URL; per-request override. */proxy?: stringsignal?: AbortSignal}@@ -219,9 +219,107 @@ function buildBodyPayload(body: HttpRequestBody): {return { bodyStr: body.data as Uint8Array, contentType: null }}-function pickDispatcher(proxy: string | undefined): Dispatcher {- if (!proxy) return sharedAgent- return new ProxyAgent({ uri: proxy })+interface DispatcherLease {+ dispatcher: Dispatcher+ owned: boolean+}++function pickDispatcher(proxy: string | undefined): DispatcherLease {+ if (!proxy) return { dispatcher: sharedAgent, owned: false }++ let parsed: URL+ try {+ parsed = new URL(proxy)+ } catch {+ throw new HttpError('plugin.http.invalid_proxy', 'Invalid proxy URL')+ }++ if (parsed.protocol === 'socks:' || parsed.protocol === 'socks5:') {+ // Undici 8.10's experimental SOCKS dispatcher does not own a TCP socket+ // until after the SOCKS greeting. Abort/destroy therefore cannot close a+ // proxy that accepts TCP and then stalls. Plugin-provided proxies cannot+ // use the app's managed SOCKS-to-HTTP bridge, so fail closed instead of+ // allowing an untrusted plugin to accumulate sockets and timers.+ throw new HttpError(+ 'plugin.http.proxy_scheme_not_supported',+ 'SOCKS proxies are not supported for plugin HTTP requests'+ )+ }+ if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') {+ throw new HttpError(+ 'plugin.http.proxy_scheme_not_supported',+ `Proxy scheme '${parsed.protocol}' is not supported`+ )+ }++ return {+ dispatcher: new ProxyAgent({ uri: parsed.toString() }),+ owned: true,+ }+}++async function destroyOwnedDispatcher(+ lease: DispatcherLease | undefined+): Promise<void> {+ if (!lease?.owned) return+ try {+ await lease.dispatcher.destroy()+ } catch {+ // Teardown must not replace the request's result with a cleanup failure.+ }+}++async function cancelResponseBody(body: unknown): Promise<void> {+ const responseBody = body as {+ destroy?: (error?: Error) => unknown+ cancel?: (reason?: unknown) => Promise<void>+ once?: (event: 'error', listener: () => void) => unknown+ }+ try {+ if (typeof responseBody.destroy === 'function') {+ // Undici BodyReadable emits RequestAbortedError asynchronously for an+ // intentional destroy. A surrounding try/catch cannot catch an Event+ // Emitter error, so attach the cleanup listener before destroying it.+ responseBody.once?.('error', () => undefined)+ responseBody.destroy()+ return+ }+ if (typeof responseBody.cancel === 'function') {+ await responseBody.cancel()+ }+ } catch {+ // Cancellation is best-effort and must not replace the original error.+ }+}++async function drainResponseBody(body: unknown): Promise<void> {+ const responseBody = body as { dump?: () => Promise<void> }+ try {+ if (typeof responseBody.dump === 'function') {+ await responseBody.dump()+ return+ }+ } catch {+ // Fall through to cancellation when draining fails.+ }+ await cancelResponseBody(body)+}++function abortError(+ signal: AbortSignal,+ timeoutMs: number+): HttpError | undefined {+ if (!signal.aborted) return undefined+ if (signal.reason === 'timeout') {+ return new HttpError(+ 'plugin.http.timeout',+ `Request timed out after ${timeoutMs}ms`+ )+ }+ if (signal.reason === 'plugin_abort') {+ return new HttpError('plugin.http.aborted', 'Request aborted by plugin')+ }+ return new HttpError('plugin.http.aborted', 'Request aborted')}// ---------------------------------------------------------------------------@@ -277,8 +375,6 @@ export class HttpCapabilityHost {const method = (opts.method ?? 'GET').toUpperCase() as Dispatcher.HttpMethodconst redirect = opts.redirect ?? 'follow'const useCookies = opts.cookies === 'jar'- const dispatcher = pickDispatcher(opts.proxy)-// ---- Outbound headers (Record, lowercased) ----const reqHeaders: Record<string, string> = {}if (opts.headers) {@@ -302,20 +398,6 @@ export class HttpCapabilityHost {const internalCtrl = new AbortController()const cleanup: (() => void)[] = []- if (opts.signal) {- if (opts.signal.aborted) {- throw new HttpError('plugin.http.aborted', 'Request aborted by plugin')- }- const onPluginAbort = () => internalCtrl.abort('plugin_abort')- opts.signal.addEventListener('abort', onPluginAbort, { once: true })- cleanup.push(() =>- opts.signal?.removeEventListener('abort', onPluginAbort)- )- }-- const timer = setTimeout(() => internalCtrl.abort('timeout'), timeoutMs)- cleanup.push(() => clearTimeout(timer))-const doCleanup = () => {for (const fn of cleanup) fn()}@@ -324,8 +406,28 @@ export class HttpCapabilityHost {let currentUrl = opts.urllet redirected = falselet hops = 0+ let lease: DispatcherLease | undefinedtry {+ if (opts.signal) {+ if (opts.signal.aborted) {+ throw new HttpError(+ 'plugin.http.aborted',+ 'Request aborted by plugin'+ )+ }+ const onPluginAbort = () => internalCtrl.abort('plugin_abort')+ opts.signal.addEventListener('abort', onPluginAbort, { once: true })+ cleanup.push(() =>+ opts.signal?.removeEventListener('abort', onPluginAbort)+ )+ }++ const timer = setTimeout(() => internalCtrl.abort('timeout'), timeoutMs)+ cleanup.push(() => clearTimeout(timer))++ lease = pickDispatcher(opts.proxy)+while (true) {// Cookie jar inject (uses currentUrl so cookies follow the host).if (useCookies && this.cookieJar) {@@ -346,25 +448,11 @@ export class HttpCapabilityHost {headers: reqHeaders,body: bodyPayload,signal: internalCtrl.signal,- dispatcher,+ dispatcher: lease.dispatcher,})} catch (err: unknown) {- if (internalCtrl.signal.aborted) {- const reason = internalCtrl.signal.reason- if (reason === 'timeout') {- throw new HttpError(- 'plugin.http.timeout',- `Request timed out after ${timeoutMs}ms`- )- }- if (reason === 'plugin_abort') {- throw new HttpError(- 'plugin.http.aborted',- 'Request aborted by plugin'- )- }- throw new HttpError('plugin.http.aborted', 'Request aborted')- }+ const aborted = abortError(internalCtrl.signal, timeoutMs)+ if (aborted) throw abortedif (err instanceof Error &&(err.name === 'AbortError' ||@@ -382,78 +470,83 @@ export class HttpCapabilityHost {)}- // Capture cookies from response on this hop.- if (useCookies && this.cookieJar) {- const rawSetCookie = response.headers['set-cookie']- const arr = Array.isArray(rawSetCookie)- ? rawSetCookie- : typeof rawSetCookie === 'string'- ? [rawSetCookie]- : []- if (arr.length > 0) {- this.cookieJar.captureFromResponseHeaders(currentUrl, arr)+ try {+ // Capture cookies from response on this hop.+ if (useCookies && this.cookieJar) {+ const rawSetCookie = response.headers['set-cookie']+ const arr = Array.isArray(rawSetCookie)+ ? rawSetCookie+ : typeof rawSetCookie === 'string'+ ? [rawSetCookie]+ : []+ if (arr.length > 0) {+ this.cookieJar.captureFromResponseHeaders(currentUrl, arr)+ }}- }- const status = response.statusCode- const location = response.headers.location- const isRedirect = status >= 300 && status < 400 && location-- if (isRedirect) {- if (redirect === 'manual') {- // Surface the 3xx as-is.- return await buildResponse<R>(- response,- opts.responseType,- maxBodyBytes,- internalCtrl,- currentUrl,- redirected,- doCleanup- )- }- if (redirect === 'error') {- await response.body.dump?.()- throw new HttpError(- 'plugin.http.redirect_not_allowed',- `redirect: 'error' set; refusing to follow ${status} to ${location}`- )- }- // redirect === 'follow'- if (hops >= MAX_REDIRECTS) {- await response.body.dump?.()- throw new HttpError(- 'plugin.http.too_many_redirects',- `Too many redirects (>${MAX_REDIRECTS})`- )+ const status = response.statusCode+ const location = response.headers.location+ const isRedirect = status >= 300 && status < 400 && location++ if (isRedirect) {+ if (redirect === 'manual') {+ // Surface the 3xx as-is.+ return await buildResponse<R>(+ response,+ opts.responseType,+ maxBodyBytes,+ timeoutMs,+ internalCtrl,+ currentUrl,+ redirected+ )+ }+ if (redirect === 'error') {+ await drainResponseBody(response.body)+ throw new HttpError(+ 'plugin.http.redirect_not_allowed',+ `redirect: 'error' set; refusing to follow ${status} to ${location}`+ )+ }+ // redirect === 'follow'+ if (hops >= MAX_REDIRECTS) {+ await drainResponseBody(response.body)+ throw new HttpError(+ 'plugin.http.too_many_redirects',+ `Too many redirects (>${MAX_REDIRECTS})`+ )+ }+ await drainResponseBody(response.body)+ const loc = Array.isArray(location) ? (location[0] ?? '') : location+ const nextUrl = new URL(loc, currentUrl)+ // Re-validate the scheme and host confinement on every hop. Both+ // only ran on the initial URL, so a 3xx Location to file:// (or to+ // a host outside hostPermissions) would otherwise escape.+ checkScheme(nextUrl)+ this.checkHostPermitted(nextUrl.toString())+ currentUrl = nextUrl.toString()+ redirected = true+ hops += 1+ continue}- await response.body.dump?.()- const loc = Array.isArray(location) ? (location[0] ?? '') : location- const nextUrl = new URL(loc, currentUrl)- // Re-validate the scheme and host confinement on every hop. Both- // only ran on the initial URL, so a 3xx Location to file:// (or to- // a host outside hostPermissions) would otherwise escape.- checkScheme(nextUrl)- this.checkHostPermitted(nextUrl.toString())- currentUrl = nextUrl.toString()- redirected = true- hops += 1- continue- }- return await buildResponse<R>(- response,- opts.responseType,- maxBodyBytes,- internalCtrl,- currentUrl,- redirected,- doCleanup- )+ return await buildResponse<R>(+ response,+ opts.responseType,+ maxBodyBytes,+ timeoutMs,+ internalCtrl,+ currentUrl,+ redirected+ )+ } catch (error) {+ await cancelResponseBody(response.body)+ throw error+ }}- } catch (err) {+ } finally {doCleanup()- throw err+ await destroyOwnedDispatcher(lease)}}@@ -507,10 +600,10 @@ async function buildResponse<R extends HttpResponseType>(response: Awaited<ReturnType<typeof undiciRequest>>,responseType: R,maxBodyBytes: number,+ timeoutMs: number,internalCtrl: AbortController,finalUrl: string,- redirected: boolean,- doCleanup: () => void+ redirected: boolean): Promise<HttpResponse<R>> {const chunks: Buffer[] = []let totalBytes = 0@@ -522,16 +615,22 @@ async function buildResponse<R extends HttpResponseType>(if (totalBytes > maxBodyBytes) {capped = trueinternalCtrl.abort('body_too_large')- response.body.destroy?.()+ await cancelResponseBody(response.body)break}chunks.push(buf)}- } catch {- // Ignore stream errors that arise from aborting the body read.+ } catch (error) {+ await cancelResponseBody(response.body)+ if (!capped) {+ const aborted = abortError(internalCtrl.signal, timeoutMs)+ if (aborted) throw aborted+ throw new HttpError(+ 'plugin.http.network',+ `Network error while reading response body: ${error instanceof Error ? error.message : String(error)}`+ )+ }}- doCleanup()-if (capped) {throw new HttpError('plugin.http.response_too_large',@@ -539,6 +638,9 @@ async function buildResponse<R extends HttpResponseType>()}+ const aborted = abortError(internalCtrl.signal, timeoutMs)+ if (aborted) throw aborted+const rawBody = Buffer.concat(chunks)let parsedBody: unknownif (responseType === 'bytes') {diff --git a/src/core/plugin/hooks/ctx-update.test.ts b/src/core/plugin/hooks/ctx-update.test.tsindex de65deac..d82e5a49 100644--- a/src/core/plugin/hooks/ctx-update.test.ts+++ b/src/core/plugin/hooks/ctx-update.test.ts@@ -38,12 +38,19 @@ describe('validateHttpPatch', () => {expect(result.proxy).toBe('')})- it('accepts a valid socks5 proxy with credentials', () => {+ it('accepts a valid HTTP task proxy with credentials', () => {const result = validateHttpPatch(- { proxy: 'socks5://user:pass@host:1080' },+ { proxy: 'http://user:pass@host:1080' },makeOpts())- expect(result.proxy).toBe('socks5://user:pass@host:1080')+ expect(result.proxy).toBe('http://user:pass@host:1080')+ })++ it.each([+ 'socks5://user:pass@host:1080',+ 'http://user%0Aevil:pass@host:1080',+ ])('rejects a task proxy aria2 cannot safely consume: %s', (proxy) => {+ expect(() => validateHttpPatch({ proxy }, makeOpts())).toThrow(AppError)})it('accepts a headers array with name/value objects', () => {diff --git a/src/core/plugin/hooks/ctx-update.ts b/src/core/plugin/hooks/ctx-update.tsindex 930f4c51..503da172 100644--- a/src/core/plugin/hooks/ctx-update.ts+++ b/src/core/plugin/hooks/ctx-update.ts@@ -1,9 +1,21 @@import path from 'node:path'+import {+ extractAria2ProxyCredentials,+ normalizeAria2TaskProxyUrl,+} from '@core/proxy/aria2-proxy-routing'import { AppError, ErrorCode } from '@shared/errors'import { z } from 'zod'import type { RoleBand } from './role-band'-const PROXY_RE = /^(http|https|socks5):\/\/([^@]+@)?[^:/]+:\d+$/+const taskProxySchema = z+ .string()+ .refine(+ (value) =>+ value === '' ||+ (normalizeAria2TaskProxyUrl(value) !== null &&+ extractAria2ProxyCredentials(value) !== null),+ { message: 'must be an aria2-compatible HTTP or HTTPS task proxy' }+ )export const HttpPatchSchema = z.object({@@ -23,7 +35,7 @@ export const HttpPatchSchema = zheaders: z.array(z.object({ name: z.string(), value: z.string() })).optional(),- proxy: z.union([z.literal(''), z.string().regex(PROXY_RE)]).optional(),+ proxy: taskProxySchema.optional(),}).strict()diff --git a/src/core/plugin/install/github-fetcher.test.ts b/src/core/plugin/install/github-fetcher.test.tsindex 3e29b45c..5af73c8e 100644--- a/src/core/plugin/install/github-fetcher.test.ts+++ b/src/core/plugin/install/github-fetcher.test.ts@@ -147,9 +147,11 @@ describe('downloadGithubMoext', () => {})it('rejects when GitHub returns non-200', async () => {- mockRequest.mockResolvedValueOnce(- jsonResponse({ message: 'not found' }, 404)- )+ const destroy = vi.fn()+ mockRequest.mockResolvedValueOnce({+ statusCode: 404,+ body: { json: async () => ({ message: 'not found' }), destroy },+ })await expect(downloadGithubMoext({ owner: 'acme', repo: 'widget' },@@ -158,6 +160,29 @@ describe('downloadGithubMoext', () => {).rejects.toMatchObject({message: 'plugin.install.gh_release_unavailable: 404',})+ expect(destroy).toHaveBeenCalledOnce()+ })++ it('cancels the metadata body when JSON decoding fails', async () => {+ const destroy = vi.fn()+ mockRequest.mockResolvedValueOnce({+ statusCode: 200,+ body: {+ json: async () => {+ throw new SyntaxError('invalid JSON')+ },+ destroy,+ },+ })++ await expect(+ downloadGithubMoext(+ { owner: 'acme', repo: 'widget' },+ path.join(tmp, 'x.moext')+ )+ ).rejects.toThrow('invalid JSON')++ expect(destroy).toHaveBeenCalledOnce()})it('rejects when no asset ends with .moext', async () => {@@ -181,6 +206,9 @@ describe('downloadGithubMoext', () => {})it('rejects when asset download itself fails', async () => {+ const failedBody = Readable.from(Buffer.alloc(0))+ const once = vi.spyOn(failedBody, 'once')+ const destroy = vi.spyOn(failedBody, 'destroy')mockRequest.mockResolvedValueOnce(jsonResponse({@@ -193,7 +221,7 @@ describe('downloadGithubMoext', () => {],}))- .mockResolvedValueOnce(streamResponse(Buffer.alloc(0), 500))+ .mockResolvedValueOnce({ statusCode: 500, body: failedBody, headers: {} })await expect(downloadGithubMoext({ owner: 'acme', repo: 'widget' },@@ -202,6 +230,51 @@ describe('downloadGithubMoext', () => {).rejects.toMatchObject({message: 'plugin.install.gh_asset_download_failed: 500',})+ expect(once).toHaveBeenCalledWith('error', expect.any(Function))+ expect(destroy).toHaveBeenCalledOnce()+ expect(once.mock.invocationCallOrder[0]).toBeLessThan(+ destroy.mock.invocationCallOrder[0] as number+ )+ })++ it('cancels a failing asset stream and removes any destination file', async () => {+ let emitted = false+ const failedBody = new Readable({+ read() {+ if (emitted) return+ emitted = true+ this.push(Buffer.from('partial'))+ this.destroy(new Error('asset stream failed'))+ },+ })+ const destroy = vi.spyOn(failedBody, 'destroy')+ mockRequest+ .mockResolvedValueOnce(+ jsonResponse({+ tag_name: 'v0.1.0',+ assets: [+ {+ name: 'x.moext',+ browser_download_url: 'https://gh/assets/x.moext',+ },+ ],+ })+ )+ .mockResolvedValueOnce({+ statusCode: 200,+ body: failedBody,+ headers: {},+ })+ const destination = path.join(tmp, 'x.moext')++ await expect(+ downloadGithubMoext({ owner: 'acme', repo: 'widget' }, destination)+ ).rejects.toThrow('asset stream failed')++ expect(destroy).toHaveBeenCalled()+ await expect(readFile(destination)).rejects.toMatchObject({+ code: 'ENOENT',+ })})it('rejects an insecure GitHub asset URL before downloading it', async () => {diff --git a/src/core/plugin/install/github-fetcher.ts b/src/core/plugin/install/github-fetcher.tsindex 3e0d5608..5f523aea 100644--- a/src/core/plugin/install/github-fetcher.ts+++ b/src/core/plugin/install/github-fetcher.ts@@ -67,11 +67,20 @@ async function cancelBody(body: unknown): Promise<void> {const stream = body as {destroy?: (error?: Error) => unknowncancel?: (reason?: unknown) => Promise<void>+ once?: (event: 'error', listener: () => void) => unknown}- if (typeof stream.destroy === 'function') {- stream.destroy()- } else if (typeof stream.cancel === 'function') {- await stream.cancel().catch(() => undefined)+ try {+ if (typeof stream.destroy === 'function') {+ // Undici BodyReadable emits RequestAbortedError asynchronously for an+ // intentional destroy. Swallow that cleanup signal without waiting for+ // a close event that can itself depend on dispatcher teardown.+ stream.once?.('error', () => undefined)+ stream.destroy()+ } else if (typeof stream.cancel === 'function') {+ await stream.cancel()+ }+ } catch {+ // Response cleanup is best-effort and must not mask the install error.}}@@ -109,12 +118,19 @@ export async function downloadGithubMoext(},})if (meta.statusCode !== 200) {+ await cancelBody(meta.body)throw new AppError(ErrorCode.PluginManifestInvalid,`plugin.install.gh_release_unavailable: ${meta.statusCode}`)}- const body = (await meta.body.json()) as GhReleaseResponse+ let body: GhReleaseResponse+ try {+ body = (await meta.body.json()) as GhReleaseResponse+ } catch (cause) {+ await cancelBody(meta.body)+ throw cause+ }const asset = body.assets.find((a) => a.name.endsWith('.moext'))if (!asset) {throw new AppError(@@ -158,6 +174,7 @@ export async function downloadGithubMoext(assetUrl = resolveHttpsRedirect(location, assetUrl)}if (dl.statusCode !== 200) {+ await cancelBody(dl.body)throw new AppError(ErrorCode.PluginManifestInvalid,`plugin.install.gh_asset_download_failed: ${dl.statusCode}`@@ -179,6 +196,7 @@ export async function downloadGithubMoext(}await writeFile(destFile, Buffer.concat(chunks, total), { mode: 0o600 })} catch (cause) {+ await cancelBody(dl.body)await rm(destFile, { force: true }).catch(() => undefined)throw cause}diff --git a/src/core/plugin/install/url-fetcher.test.ts b/src/core/plugin/install/url-fetcher.test.tsnew file mode 100644index 00000000..958a70d1--- /dev/null+++ b/src/core/plugin/install/url-fetcher.test.ts@@ -0,0 +1,131 @@+import { mkdtemp, readFile, rm } from 'node:fs/promises'+import { tmpdir } from 'node:os'+import path from 'node:path'+import { Readable } from 'node:stream'+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'++const mocks = vi.hoisted(() => ({+ request: vi.fn(),+ compose: vi.fn(),+ destroy: vi.fn(async () => undefined),+ redirect: vi.fn(),+ dispatcher: { kind: 'composed-dispatcher' },+ interceptor: { kind: 'redirect-interceptor' },+}))++vi.mock('undici', () => ({+ Agent: class MockAgent {+ compose(interceptor: unknown) {+ mocks.compose(interceptor)+ return mocks.dispatcher+ }++ destroy() {+ return mocks.destroy()+ }+ },+ interceptors: {+ redirect(options: unknown) {+ mocks.redirect(options)+ return mocks.interceptor+ },+ },+ request: (...args: unknown[]) => mocks.request(...args),+}))++const { downloadUrlMoext } = await import('./url-fetcher')++let tempDir: string++beforeEach(async () => {+ tempDir = await mkdtemp(path.join(tmpdir(), 'motrix-url-fetcher-'))+ mocks.request.mockReset()+ mocks.compose.mockClear()+ mocks.destroy.mockClear()+ mocks.redirect.mockClear()+})++afterEach(async () => {+ await rm(tempDir, { recursive: true, force: true })+})++describe('downloadUrlMoext', () => {+ it('streams a successful response and destroys its owned Agent', async () => {+ mocks.request.mockResolvedValueOnce({+ statusCode: 200,+ body: Readable.from(Buffer.from('plugin-bytes')),+ })+ const destination = path.join(tempDir, 'nested', 'plugin.moext')++ await downloadUrlMoext('https://plugins.example/plugin.moext', destination)++ expect((await readFile(destination)).toString()).toBe('plugin-bytes')+ expect(mocks.redirect).toHaveBeenCalledWith({ maxRedirections: 5 })+ expect(mocks.compose).toHaveBeenCalledWith(mocks.interceptor)+ expect(mocks.request).toHaveBeenCalledWith(+ 'https://plugins.example/plugin.moext',+ { dispatcher: mocks.dispatcher }+ )+ expect(mocks.destroy).toHaveBeenCalledOnce()+ })++ it('cancels a non-200 response body before destroying the Agent', async () => {+ const body = Readable.from(Buffer.from('server error'))+ const once = vi.spyOn(body, 'once')+ const destroy = vi.spyOn(body, 'destroy')+ mocks.request.mockResolvedValueOnce({ statusCode: 503, body })+ const destination = path.join(tempDir, 'plugin.moext')++ await expect(+ downloadUrlMoext('https://plugins.example/plugin.moext', destination)+ ).rejects.toMatchObject({+ message: 'plugin.install.url_download_failed: 503',+ })++ expect(once).toHaveBeenCalledWith('error', expect.any(Function))+ expect(destroy).toHaveBeenCalled()+ expect(once.mock.invocationCallOrder[0]).toBeLessThan(+ destroy.mock.invocationCallOrder[0] as number+ )+ expect(mocks.destroy).toHaveBeenCalledOnce()+ await expect(readFile(destination)).rejects.toMatchObject({+ code: 'ENOENT',+ })+ })++ it('removes a partial file and destroys the Agent on a body stream error', async () => {+ let emitted = false+ const body = new Readable({+ read() {+ if (emitted) return+ emitted = true+ this.push(Buffer.from('partial'))+ this.destroy(new Error('stream failed'))+ },+ })+ mocks.request.mockResolvedValueOnce({ statusCode: 200, body })+ const destination = path.join(tempDir, 'plugin.moext')++ await expect(+ downloadUrlMoext('https://plugins.example/plugin.moext', destination)+ ).rejects.toThrow('stream failed')++ expect(mocks.destroy).toHaveBeenCalledOnce()+ await expect(readFile(destination)).rejects.toMatchObject({+ code: 'ENOENT',+ })+ })++ it('destroys the Agent when request fails before returning a response', async () => {+ mocks.request.mockRejectedValueOnce(new Error('connect failed'))++ await expect(+ downloadUrlMoext(+ 'https://plugins.example/plugin.moext',+ path.join(tempDir, 'plugin.moext')+ )+ ).rejects.toThrow('connect failed')++ expect(mocks.destroy).toHaveBeenCalledOnce()+ })+})diff --git a/src/core/plugin/install/url-fetcher.ts b/src/core/plugin/install/url-fetcher.tsnew file mode 100644index 00000000..c94b3752--- /dev/null+++ b/src/core/plugin/install/url-fetcher.ts@@ -0,0 +1,67 @@+import { createWriteStream } from 'node:fs'+import { mkdir, rm } from 'node:fs/promises'+import path from 'node:path'+import { pipeline } from 'node:stream/promises'+import { AppError, ErrorCode } from '@shared/errors'+import { Agent, interceptors, request } from 'undici'++const MAX_REDIRECTS = 5++async function cancelBody(body: unknown): Promise<void> {+ const responseBody = body as {+ destroy?: (error?: Error) => unknown+ cancel?: (reason?: unknown) => Promise<void>+ once?: (event: 'error', listener: () => void) => unknown+ }+ try {+ if (typeof responseBody.destroy === 'function') {+ // Undici BodyReadable reports an intentional destroy as an asynchronous+ // RequestAbortedError. Install the listener before destroy so cleanup of+ // a non-200/partial response cannot become an uncaught process error.+ responseBody.once?.('error', () => undefined)+ responseBody.destroy()+ return+ }+ if (typeof responseBody.cancel === 'function') {+ await responseBody.cancel()+ }+ } catch {+ // Preserve the download error when response cancellation also fails.+ }+}++/** Download a URL-sourced plugin package and release every owned socket. */+export async function downloadUrlMoext(+ url: string,+ destFile: string+): Promise<void> {+ const agent = new Agent()+ let body: unknown++ try {+ const dispatcher = agent.compose(+ interceptors.redirect({ maxRedirections: MAX_REDIRECTS })+ )+ const response = await request(url, { dispatcher })+ body = response.body+ if (response.statusCode !== 200) {+ await cancelBody(body)+ throw new AppError(+ ErrorCode.PluginManifestInvalid,+ `plugin.install.url_download_failed: ${response.statusCode}`+ )+ }++ await mkdir(path.dirname(destFile), { recursive: true })+ await pipeline(response.body, createWriteStream(destFile, { mode: 0o600 }))+ body = undefined+ } catch (cause) {+ await cancelBody(body)+ await rm(destFile, { force: true }).catch(() => undefined)+ throw cause+ } finally {+ // The interceptor wrapper delegates to this Agent. Destroy the owner, not+ // an implementation-detail wrapper whose lifecycle differs by Undici ABI.+ await agent.destroy().catch(() => undefined)+ }+}diff --git a/src/core/plugin/registry/registry-client.test.ts b/src/core/plugin/registry/registry-client.test.tsindex 38b88014..c2b0ac6c 100644--- a/src/core/plugin/registry/registry-client.test.ts+++ b/src/core/plugin/registry/registry-client.test.ts@@ -254,6 +254,26 @@ describe('RegistryClient', () => {expect(await makeClient(impl).load()).toBeNull()})+ it('cancels a non-ok registry response body', async () => {+ const cancel = vi.fn()+ const impl = vi.fn(async () =>+ Promise.resolve(+ new Response(+ new ReadableStream<Uint8Array>({+ start(controller) {+ controller.enqueue(new TextEncoder().encode('server error'))+ },+ cancel,+ }),+ { status: 500 }+ )+ )+ ) as unknown as typeof fetch++ expect(await makeClient(impl).load()).toBeNull()+ expect(cancel).toHaveBeenCalledOnce()+ })+it('rejects an oversized Content-Length before reading the body', async () => {let signal: AbortSignal | undefinedlet cancelled = false@@ -359,6 +379,40 @@ describe('RegistryClient', () => {expect(signal?.aborted).toBe(true)})+ it('cancels a late response from a fetch implementation that ignores abort', async () => {+ vi.useFakeTimers()+ let resolveResponse!: (response: Response) => void+ const deferred = new Promise<Response>((resolve) => {+ resolveResponse = resolve+ })+ const impl = vi.fn(() => deferred) as unknown as typeof fetch+ const client = makeClient(impl, {+ statImpl: async () => {+ throw new Error('no cache')+ },+ })++ const pending = client.load()+ await vi.advanceTimersByTimeAsync(0)+ await vi.advanceTimersByTimeAsync(15_000)+ expect(await pending).toBeNull()++ const cancel = vi.fn()+ resolveResponse(+ new Response(+ new ReadableStream<Uint8Array>({+ start(controller) {+ controller.enqueue(new TextEncoder().encode('{}'))+ },+ cancel,+ })+ )+ )+ await vi.advanceTimersByTimeAsync(0)++ expect(cancel).toHaveBeenCalledOnce()+ })+it('annotates entries with the host compatibility gate', async () => {const { impl } = makeFetch([{ status: 200 }])const client = makeClient(impl)diff --git a/src/core/plugin/registry/registry-client.ts b/src/core/plugin/registry/registry-client.tsindex caeb2695..2ca2d915 100644--- a/src/core/plugin/registry/registry-client.ts+++ b/src/core/plugin/registry/registry-client.ts@@ -15,6 +15,17 @@ const FETCH_TIMEOUT_MS = 15_000export const MAX_REGISTRY_BYTES = 4 * 1024 * 1024const MAX_CACHE_BYTES = MAX_REGISTRY_BYTES + 64 * 1024+async function cancelResponseBody(+ response: Response,+ reason?: unknown+): Promise<void> {+ try {+ await response.body?.cancel(reason)+ } catch {+ // Preserve the refresh result when cancellation races a closed body.+ }+}+const CacheEnvelopeSchema = z.object({cacheFormat: z.literal(2),etag: z.string().nullable(),@@ -148,17 +159,29 @@ export class RegistryClient {const headers: Record<string, string> = {}if (this.cache?.etag) headers['if-none-match'] = this.cache.etag- const res = await Promise.race([- this.fetchImpl(this.url, { headers, signal: controller.signal }),- deadline,- ])+ const fetchResponse = this.fetchImpl(this.url, {+ headers,+ signal: controller.signal,+ }).then(async (response) => {+ // A custom fetch implementation may ignore AbortSignal and resolve+ // after the deadline already won the race. Dispose that late response+ // instead of leaving its body and connection unowned.+ if (controller.signal.aborted) {+ await cancelResponseBody(response, controller.signal.reason)+ throw controller.signal.reason+ }+ return response+ })+ const res = await Promise.race([fetchResponse, deadline])if (res.status === 304 && this.cache) {+ await cancelResponseBody(res)this.cache = { ...this.cache, fetchedAt: this.now() }await this.persist()return this.cache.file}if (!res.ok) {+ await cancelResponseBody(res)throw new Error(`registry responded ${res.status}`)}diff --git a/src/core/proxy/applied-download-proxy-policy.test.ts b/src/core/proxy/applied-download-proxy-policy.test.tsnew file mode 100644index 00000000..81b8a440--- /dev/null+++ b/src/core/proxy/applied-download-proxy-policy.test.ts@@ -0,0 +1,211 @@+import { describe, expect, it, vi } from 'vitest'+import { AppliedDownloadProxyPolicy } from './applied-download-proxy-policy'++const PROXIED = {+ allProxy: 'http://proxy-user:[email protected]:8080',+ noProxy: 'localhost,127.0.0.0/8',+}++describe('AppliedDownloadProxyPolicy', () => {+ it('reports whether a transition is recovering an unavailable route', async () => {+ const policy = new AppliedDownloadProxyPolicy()+ const states: boolean[] = []++ await policy.applyTransition(async ({ wasUnavailable }) => {+ states.push(wasUnavailable)+ return { downloadProxy: 'unchanged' }+ })+ policy.commit(null)+ await policy.applyTransition(async ({ wasUnavailable }) => {+ states.push(wasUnavailable)+ return { downloadProxy: 'unchanged' }+ })++ expect(states).toEqual([true, false])+ })++ it('distinguishes an unavailable policy from a confirmed direct route', async () => {+ const policy = new AppliedDownloadProxyPolicy()+ expect(policy.snapshot()).toBeNull()++ await policy.commit(null)+ expect(policy.snapshot()).toEqual({ noProxy: '' })+ })++ it('keeps the exact applied proxy only in its in-memory snapshot', async () => {+ const policy = new AppliedDownloadProxyPolicy()+ await policy.commit(PROXIED)++ expect(policy.snapshot()).toEqual({+ proxy: 'http://proxy-user:[email protected]:8080',+ noProxy: 'localhost,127.0.0.0/8',+ })+ })++ it('commits only after aria2 confirms a proxy transition', async () => {+ const policy = new AppliedDownloadProxyPolicy()+ await policy.commit(null)+ let observedDuringApply: unknown = 'not-called'++ await policy.applyTransition(async () => {+ observedDuringApply = policy.snapshot()+ return { downloadProxy: 'applied' as const, appliedProxy: PROXIED }+ })++ expect(observedDuringApply).toBeNull()+ expect(policy.snapshot()).toMatchObject({+ proxy: expect.stringContaining('proxy-user:proxy-pass@'),+ })+ })++ it('stays unavailable when the engine was not ready', async () => {+ const policy = new AppliedDownloadProxyPolicy()+ await policy.commit(null)++ await policy.applyTransition(async () => ({+ downloadProxy: 'unavailable' as const,+ }))++ expect(policy.snapshot()).toBeNull()+ })++ it('stays unavailable after a partial apply failure', async () => {+ const policy = new AppliedDownloadProxyPolicy()+ await policy.commit(null)++ await expect(+ policy.applyTransition(async () => {+ throw new Error('RPC failed')+ })+ ).rejects.toThrow('RPC failed')+ expect(policy.snapshot()).toBeNull()+ })++ it('restores the prior snapshot when download routing was unchanged', async () => {+ const policy = new AppliedDownloadProxyPolicy()+ await policy.commit(PROXIED)++ await policy.applyTransition(async () => ({+ downloadProxy: 'unchanged' as const,+ }))++ expect(policy.snapshot()).toMatchObject({+ proxy: expect.stringContaining('proxy.example'),+ })+ })++ it('holds a settings writer behind active task readers', async () => {+ const policy = new AppliedDownloadProxyPolicy()+ await policy.commit(null)+ let releaseReader: (() => void) | undefined+ const readerGate = new Promise<void>((resolve) => {+ releaseReader = resolve+ })+ const events: string[] = []++ const reader = policy.runWithSnapshot(async () => {+ events.push('reader-start')+ await readerGate+ events.push('reader-end')+ })+ await vi.waitFor(() => expect(events).toEqual(['reader-start']))++ const writer = policy.applyTransition(async () => {+ events.push('writer')+ return { downloadProxy: 'applied' as const, appliedProxy: PROXIED }+ })+ await Promise.resolve()+ expect(events).toEqual(['reader-start'])++ releaseReader?.()+ await Promise.all([reader, writer])+ expect(events).toEqual(['reader-start', 'reader-end', 'writer'])+ })++ it('queues readers while an apply is in progress', async () => {+ const policy = new AppliedDownloadProxyPolicy()+ await policy.commit(null)+ let finishApply: (() => void) | undefined+ const applyGate = new Promise<void>((resolve) => {+ finishApply = resolve+ })+ const reader = vi.fn()++ const writer = policy.applyTransition(async () => {+ await applyGate+ return { downloadProxy: 'applied' as const, appliedProxy: PROXIED }+ })+ await vi.waitFor(() => expect(policy.snapshot()).toBeNull())+ const queuedReader = policy.runWithSnapshot(async (snapshot) => {+ reader(snapshot)+ })+ await Promise.resolve()+ expect(reader).not.toHaveBeenCalled()++ finishApply?.()+ await Promise.all([writer, queuedReader])+ expect(reader).toHaveBeenCalledWith(+ expect.objectContaining({+ proxy: expect.stringContaining('proxy.example'),+ })+ )+ })++ it('commits startup without waiting for a null reader and invalidates its lease', async () => {+ const policy = new AppliedDownloadProxyPolicy()+ let releaseReader: (() => void) | undefined+ const readerGate = new Promise<void>((resolve) => {+ releaseReader = resolve+ })+ let assertCurrent: (() => void) | undefined+ const reader = policy.runWithSnapshot(async (snapshot, lease) => {+ expect(snapshot).toBeNull()+ assertCurrent = lease.assertCurrent+ await readerGate+ })+ await vi.waitFor(() => expect(assertCurrent).toBeTypeOf('function'))++ policy.commit(PROXIED)++ expect(policy.snapshot()).toEqual({+ proxy: PROXIED.allProxy,+ noProxy: PROXIED.noProxy,+ })+ expect(() => assertCurrent?.()).toThrow(+ 'applied download proxy policy changed'+ )+ releaseReader?.()+ await reader+ })++ it('publishes the startup route before Ready and holds queued transitions', async () => {+ const policy = new AppliedDownloadProxyPolicy()+ let releaseResolve: (() => void) | undefined+ const resolveGate = new Promise<void>((resolve) => {+ releaseResolve = resolve+ })+ const events: string[] = []++ const startup = policy.publishStartupRoute(+ async () => {+ events.push('startup-resolve')+ await resolveGate+ return PROXIED+ },+ () => events.push('ready')+ )+ await vi.waitFor(() => expect(events).toEqual(['startup-resolve']))++ const transition = policy.applyTransition(async () => {+ events.push('transition')+ return { downloadProxy: 'applied' as const, appliedProxy: null }+ })+ await Promise.resolve()+ expect(events).toEqual(['startup-resolve'])++ releaseResolve?.()+ await Promise.all([startup, transition])+ expect(events).toEqual(['startup-resolve', 'ready', 'transition'])+ expect(policy.snapshot()).toEqual({ noProxy: '' })+ })+})diff --git a/src/core/proxy/applied-download-proxy-policy.ts b/src/core/proxy/applied-download-proxy-policy.tsnew file mode 100644index 00000000..51107399--- /dev/null+++ b/src/core/proxy/applied-download-proxy-policy.ts@@ -0,0 +1,266 @@+import type { Aria2ProxyOptions } from './serializers'++/**+ * The download route known to be active in aria2.+ *+ * `null` is deliberately distinct from a direct route: it means the engine's+ * effective policy is unknown, so optional metadata requests and resumability+ * validation must fail closed. A direct route is represented by+ * `{ noProxy: '' }`, matching the empty global options sent to aria2.+ */+export type AppliedDownloadProxySnapshot = Readonly<{+ proxy?: string+ noProxy: string+}> | null++export type DownloadProxyApplyOutcome = 'applied' | 'unchanged' | 'unavailable'++export type DownloadProxyApplyResult =+ | Readonly<{+ downloadProxy: 'applied'+ /** Exact endpoint/no-proxy pair passed to aria2; null means direct. */+ appliedProxy: Aria2ProxyOptions | null+ }>+ | Readonly<{+ downloadProxy: Exclude<DownloadProxyApplyOutcome, 'applied'>+ }>++export interface AppliedDownloadProxyPolicyReader {+ snapshot(): AppliedDownloadProxySnapshot+ runWithSnapshot<T>(+ operation: (+ snapshot: AppliedDownloadProxySnapshot,+ lease: AppliedDownloadProxyLease+ ) => Promise<T>+ ): Promise<T>+}++export interface AppliedDownloadProxyLease {+ /** Abort before engine dispatch if restart invalidated this snapshot. */+ assertCurrent(): void+}++export interface AppliedDownloadProxyTransitionContext {+ /** The route was already unknown before this transition acquired its lock. */+ wasUnavailable: boolean+}++export class AppliedDownloadProxyPolicyChangedError extends Error {+ constructor() {+ super('applied download proxy policy changed during task admission')+ this.name = 'AppliedDownloadProxyPolicyChangedError'+ }+}++/** Fail-closed sentinel for optional outer composition seams and tests. */+export const UNAVAILABLE_APPLIED_DOWNLOAD_PROXY_POLICY: AppliedDownloadProxyPolicyReader =+ Object.freeze({+ snapshot: () => null,+ runWithSnapshot: <T>(+ operation: (+ snapshot: AppliedDownloadProxySnapshot,+ lease: AppliedDownloadProxyLease+ ) => Promise<T>+ ) => operation(null, { assertCurrent: () => undefined }),+ })++type LockWaiter = {+ mode: 'read' | 'write'+ resolve: (release: () => void) => void+}++/**+ * In-memory coordination between aria2 proxy changes and short-lived resource+ * requests. Nothing in this object is serialized or attached to task records.+ */+export class AppliedDownloadProxyPolicy+ implements AppliedDownloadProxyPolicyReader+{+ private current: AppliedDownloadProxySnapshot+ private generation = 0+ private activeReaders = 0+ private writerActive = false+ private readonly waiters: LockWaiter[] = []++ constructor(initial: AppliedDownloadProxySnapshot = null) {+ this.current = cloneSnapshot(initial)+ }++ snapshot(): AppliedDownloadProxySnapshot {+ return cloneSnapshot(this.current)+ }++ /** Called when the engine starts/restarts with its exact resolved route. */+ commit(resolvedProxy: Aria2ProxyOptions | null): void {+ // Startup must be able to publish the route before Ready even when a+ // fail-closed reader is waiting for Ready. Existing readers are fenced by+ // their generation lease and must assert it immediately before dispatch.+ this.current = snapshotFromResolvedProxy(resolvedProxy)+ this.generation+++ }++ /** Unknown engine state is never equivalent to a confirmed direct route. */+ markUnavailable(): void {+ this.current = null+ this.generation+++ }++ async runWithSnapshot<T>(+ operation: (+ snapshot: AppliedDownloadProxySnapshot,+ lease: AppliedDownloadProxyLease+ ) => Promise<T>+ ): Promise<T> {+ const release = await this.acquire('read')+ const generation = this.generation+ try {+ return await operation(this.snapshot(), {+ assertCurrent: () => {+ if (this.generation !== generation) {+ throw new AppliedDownloadProxyPolicyChangedError()+ }+ },+ })+ } finally {+ release()+ }+ }++ /**+ * Serialize a settings transition against metadata validation and engine+ * dispatch. Readers are held while the engine route is changing. On a thrown+ * or explicitly unavailable application, queued readers observe `null` and+ * fail closed. An unrelated proxy-scope change restores the prior snapshot.+ */+ async applyTransition<T extends DownloadProxyApplyResult>(+ operation: (context: AppliedDownloadProxyTransitionContext) => Promise<T>+ ): Promise<T> {+ const release = await this.acquire('write')+ const previous = this.current+ this.current = null+ this.generation+++ const transitionGeneration = this.generation+ try {+ const result = await operation({ wasUnavailable: previous === null })+ if (this.generation !== transitionGeneration) {+ // A startup/restart committed while the hot apply was in flight. The+ // relative order of its route and the RPC result is not provable.+ this.current = null+ } else if (result.downloadProxy === 'applied') {+ this.current = snapshotFromResolvedProxy(result.appliedProxy)+ } else if (result.downloadProxy === 'unchanged') {+ this.current = previous+ } else {+ this.current = null+ }+ this.generation+++ return result+ } catch (error) {+ // The bridge and aria2 may now disagree after a partial failure. Keeping+ // either old or new credentials would claim knowledge we do not have.+ this.current = null+ this.generation+++ throw error+ } finally {+ release()+ }+ }++ /**+ * Publish the route selected at the end of engine startup and Ready as one+ * writer transaction. Settings updates can be persisted while aria2 is+ * Starting, but their proxy transition then queues behind this writer (or+ * runs before it). In either order, `resolveRoute` re-reads the latest+ * settings and no observer can see Ready with a stale route snapshot.+ */+ async publishStartupRoute(+ resolveRoute: () => Promise<Aria2ProxyOptions | null>,+ publishReady: () => void,+ shouldPublish: () => boolean = () => true+ ): Promise<boolean> {+ const release = await this.acquire('write')+ this.current = null+ this.generation+++ try {+ const resolvedProxy = await resolveRoute()+ if (!shouldPublish()) return false+ this.current = snapshotFromResolvedProxy(resolvedProxy)+ this.generation+++ publishReady()+ return true+ } catch (error) {+ this.current = null+ this.generation+++ throw error+ } finally {+ release()+ }+ }++ private acquire(mode: LockWaiter['mode']): Promise<() => void> {+ if (this.canAcquireImmediately(mode)) {+ return Promise.resolve(this.activate(mode))+ }+ return new Promise((resolve) => {+ this.waiters.push({ mode, resolve })+ })+ }++ private canAcquireImmediately(mode: LockWaiter['mode']): boolean {+ if (this.writerActive) return false+ if (mode === 'write') return this.activeReaders === 0+ // Once a writer queues, later readers wait behind it so settings changes+ // cannot starve under a stream of concurrent task submissions.+ return !this.waiters.some((waiter) => waiter.mode === 'write')+ }++ private activate(mode: LockWaiter['mode']): () => void {+ let released = false+ if (mode === 'write') this.writerActive = true+ else this.activeReaders+++ return () => {+ if (released) return+ released = true+ if (mode === 'write') this.writerActive = false+ else this.activeReaders--+ this.drain()+ }+ }++ private drain(): void {+ if (+ this.writerActive ||+ this.activeReaders > 0 ||+ this.waiters.length === 0+ ) {+ return+ }++ if (this.waiters[0]?.mode === 'write') {+ const waiter = this.waiters.shift()+ waiter?.resolve(this.activate('write'))+ return+ }++ while (this.waiters[0]?.mode === 'read') {+ const waiter = this.waiters.shift()+ waiter?.resolve(this.activate('read'))+ }+ }+}++function snapshotFromResolvedProxy(+ resolvedProxy: Aria2ProxyOptions | null+): Exclude<AppliedDownloadProxySnapshot, null> {+ return Object.freeze(+ resolvedProxy+ ? { proxy: resolvedProxy.allProxy, noProxy: resolvedProxy.noProxy }+ : { noProxy: '' }+ )+}++function cloneSnapshot(+ snapshot: AppliedDownloadProxySnapshot+): AppliedDownloadProxySnapshot {+ return snapshot ? { ...snapshot } : null+}diff --git a/src/core/proxy/applier.test.ts b/src/core/proxy/applier.test.tsindex 02a056ea..a4256a92 100644--- a/src/core/proxy/applier.test.ts+++ b/src/core/proxy/applier.test.ts@@ -12,7 +12,7 @@ const baseProxy = {function makeDeps() {return {- engineSupervisor: { applyProxyChange: vi.fn() },+ engineSupervisor: { applyProxyChange: vi.fn().mockResolvedValue(true) },trackerManager: { invalidateProxyCache: vi.fn() },proxyBridge: {reconcile: vi.fn().mockResolvedValue(undefined),@@ -28,7 +28,7 @@ describe('proxyApplier.apply', () => {it('routes to engine when download scope flips on', async () => {const deps = makeDeps()const applier = createProxyApplier(deps)- await applier.apply(+ const result = await applier.apply({...baseProxy,scopes: { download: false, updateApp: false, updateTrackers: false },@@ -42,6 +42,10 @@ describe('proxyApplier.apply', () => {allProxy: 'http://p:80',noProxy: '',})+ expect(result).toEqual({+ downloadProxy: 'applied',+ appliedProxy: { allProxy: 'http://p:80', noProxy: '' },+ })})it('routes to engine with null when download scope flips off', async () => {@@ -68,7 +72,7 @@ describe('proxyApplier.apply', () => {})const applier = createProxyApplier(deps)- await applier.apply(+ const result = await applier.apply({...baseProxy,scopes: { download: false, updateApp: false, updateTrackers: false },@@ -84,6 +88,13 @@ describe('proxyApplier.apply', () => {allProxy: 'http://127.0.0.1:43123',noProxy: '',})+ expect(result).toEqual({+ downloadProxy: 'applied',+ appliedProxy: {+ allProxy: 'http://127.0.0.1:43123',+ noProxy: '',+ },+ })})it('skips engine when download scope unchanged and fields unchanged', async () => {@@ -93,8 +104,9 @@ describe('proxyApplier.apply', () => {...baseProxy,scopes: { download: true, updateApp: false, updateTrackers: false },}- await applier.apply(both, both)+ const result = await applier.apply(both, both)expect(deps.engineSupervisor.applyProxyChange).not.toHaveBeenCalled()+ expect(result).toEqual({ downloadProxy: 'unchanged' })})it('routes to applyUpdateAppProxy when updateApp scope on and handler injected', async () => {@@ -115,7 +127,9 @@ describe('proxyApplier.apply', () => {it('skips updateApp when handler is undefined', async () => {const applier = createProxyApplier({- engineSupervisor: { applyProxyChange: vi.fn() },+ engineSupervisor: {+ applyProxyChange: vi.fn().mockResolvedValue(true),+ },trackerManager: { invalidateProxyCache: vi.fn() },proxyBridge: {reconcile: vi.fn().mockResolvedValue(undefined),@@ -175,7 +189,7 @@ describe('proxyApplier.apply', () => {expect(deps.proxyBridge.resolveForDownload).not.toHaveBeenCalled()})- it('applyAll(current) treats old as fully-disabled', async () => {+ it('applyAll(current) reasserts every proxy scope', async () => {const deps = makeDeps()const applier = createProxyApplier(deps)await applier.applyAll({@@ -186,4 +200,47 @@ describe('proxyApplier.apply', () => {expect(deps.applyUpdateAppProxy).toHaveBeenCalled()expect(deps.trackerManager.invalidateProxyCache).toHaveBeenCalled()})++ it('applyAll(current) explicitly clears a direct download route', async () => {+ const deps = makeDeps()+ const applier = createProxyApplier(deps)++ const result = await applier.applyAll({+ ...DEFAULT_PROXY_SETTINGS,+ scopes: {+ download: false,+ updateApp: false,+ updateTrackers: false,+ },+ })++ expect(deps.proxyBridge.reconcile).toHaveBeenCalledOnce()+ expect(deps.proxyBridge.resolveForDownload).toHaveBeenCalledOnce()+ expect(deps.engineSupervisor.applyProxyChange).toHaveBeenCalledWith(null)+ expect(deps.applyUpdateAppProxy).toHaveBeenCalledWith(null)+ expect(deps.trackerManager.invalidateProxyCache).toHaveBeenCalledOnce()+ expect(result).toEqual({+ downloadProxy: 'applied',+ appliedProxy: null,+ })+ })++ it('reports unavailable when aria2 is not Ready', async () => {+ const deps = makeDeps()+ deps.engineSupervisor.applyProxyChange.mockResolvedValue(false)+ const applier = createProxyApplier(deps)++ const result = await applier.apply(+ {+ ...baseProxy,+ scopes: { download: false, updateApp: false, updateTrackers: false },+ },+ {+ ...baseProxy,+ scopes: { download: true, updateApp: false, updateTrackers: false },+ }+ )++ expect(result).toEqual({ downloadProxy: 'unavailable' })+ })})diff --git a/src/core/proxy/applier.ts b/src/core/proxy/applier.tsindex 8000472c..6ebc331c 100644--- a/src/core/proxy/applier.ts+++ b/src/core/proxy/applier.ts@@ -1,13 +1,13 @@import { getLogger } from '@core/logger'-import { DEFAULT_PROXY_SETTINGS } from '@shared/schemas/proxy-settings'import type { ProxySettings } from '@shared/types/settings'+import type { DownloadProxyApplyResult } from './applied-download-proxy-policy'import type { ProxyBridgeResolver } from './proxy-bridge-manager'import { proxyToElectronConfig } from './serializers'interface EngineSupervisorLike {applyProxyChange: (opts: { allProxy: string; noProxy: string } | null- ) => Promise<void> | void+ ) => Promise<boolean> | boolean}interface TrackerManagerLike {@@ -29,14 +29,17 @@ export function createProxyApplier(deps: ProxyApplierDeps) {async function apply(oldProxy: ProxySettings,newProxy: ProxySettings- ): Promise<void> {+ ): Promise<DownloadProxyApplyResult> {+ let result: DownloadProxyApplyResult = { downloadProxy: 'unchanged' }// Reconcile even when only the tracker scope changed, so a SOCKS5// listener never outlives the settings that require it.await deps.proxyBridge.reconcile(newProxy)if (scopeDirty(oldProxy, newProxy, 'download')) {const opts = await deps.proxyBridge.resolveForDownload(newProxy)- await deps.engineSupervisor.applyProxyChange(opts)+ result = (await deps.engineSupervisor.applyProxyChange(opts))+ ? { downloadProxy: 'applied', appliedProxy: opts }+ : { downloadProxy: 'unavailable' }log.info({ enabled: opts !== null }, 'download proxy applied')}@@ -56,14 +59,29 @@ export function createProxyApplier(deps: ProxyApplierDeps) {deps.trackerManager.invalidateProxyCache()log.info('updateTrackers proxy invalidated')}++ return result}- async function applyAll(current: ProxySettings): Promise<void> {- const allDisabled: ProxySettings = {- ...DEFAULT_PROXY_SETTINGS,- scopes: { download: false, updateApp: false, updateTrackers: false },+ async function applyAll(+ current: ProxySettings+ ): Promise<DownloadProxyApplyResult> {+ // This is also the recovery path after a partial/failed hot apply, so it+ // must not infer work from a synthetic old value. Reassert every scope,+ // including an explicitly direct download route, against the current+ // persisted settings.+ await deps.proxyBridge.reconcile(current)+ const opts = await deps.proxyBridge.resolveForDownload(current)+ const result: DownloadProxyApplyResult =+ (await deps.engineSupervisor.applyProxyChange(opts))+ ? { downloadProxy: 'applied', appliedProxy: opts }+ : { downloadProxy: 'unavailable' }++ if (deps.applyUpdateAppProxy) {+ await deps.applyUpdateAppProxy(proxyToElectronConfig(current))}- await apply(allDisabled, current)+ deps.trackerManager.invalidateProxyCache()+ return result}return { apply, applyAll }diff --git a/src/core/proxy/aria2-proxy-routing.test.ts b/src/core/proxy/aria2-proxy-routing.test.tsnew file mode 100644index 00000000..e3c2f1fc--- /dev/null+++ b/src/core/proxy/aria2-proxy-routing.test.ts@@ -0,0 +1,241 @@+// @vitest-environment node++import { describe, expect, it } from 'vitest'+import {+ decideAria2ProxyRoute,+ extractAria2ProxyCredentials,+ normalizeAria2TaskProxyUrl,+ normalizeProxyUrl,+} from './aria2-proxy-routing'++describe('normalizeProxyUrl', () => {+ it.each([+ ['proxy.example:8080', 'http://proxy.example:8080/'],+ ['user:p%[email protected]:8080', 'http://user:p%[email protected]:8080/'],+ ['socks5://proxy.example:1080', 'socks5://proxy.example:1080'],+ ['[2001:db8::1]:8080', 'http://[2001:db8::1]:8080/'],+ ['[0:0:0:0:0:0:0:1]:8080', 'http://[::1]:8080/'],+ ])('normalizes %s as %s', (input, expected) => {+ expect(normalizeProxyUrl(input)?.toString()).toBe(expected)+ })++ it.each([+ '',+ ' ',+ ' proxy.example ',+ 'HTTPS://proxy.example:8443',+ 'ftp://proxy.example:21',+ 'socks5h://proxy.example:1080',+ 'http://',+ 'http:proxy.example',+ 'http://proxy.example:0',+ 'http://proxy.example:70000',+ 'http://proxy.example/path',+ 'http://proxy.example?',+ 'http://proxy.example?mode=tunnel',+ 'http://proxy.example#',+ 'http://proxy.example#fragment',+ 'http://%6cocalhost:8080',+ 'http://127.1:8080',+ 'http://proxy.example:8\t0',+ 'http:\\proxy.example:8080',+ ])('rejects an unsupported proxy value: %s', (input) => {+ expect(normalizeProxyUrl(input)).toBeNull()+ })+})++describe('normalizeAria2TaskProxyUrl', () => {+ it('accepts aria2 HTTP syntax but rejects SOCKS5 without a per-task bridge', () => {+ expect(+ normalizeAria2TaskProxyUrl('https://proxy.example:8443')?.protocol+ ).toBe('https:')+ expect(normalizeAria2TaskProxyUrl('http://127.1:8080')?.hostname).toBe(+ '127.0.0.1'+ )+ expect(normalizeAria2TaskProxyUrl('socks5://proxy.example:1080')).toBeNull()+ })+})++describe('extractAria2ProxyCredentials', () => {+ it('decodes URI userinfo for aria2 dedicated credential options', () => {+ expect(+ extractAria2ProxyCredentials('http://a%40b:p%[email protected]:8080')+ ).toEqual({ username: 'a@b', password: 'p:s' })+ expect(extractAria2ProxyCredentials('proxy.example:8080')).toEqual({+ username: '',+ password: '',+ })+ expect(+ extractAria2ProxyCredentials('http://user:pass@[0:0:0:0:0:0:0:1]:8080')+ ).toEqual({ username: 'user', password: 'pass' })+ expect(extractAria2ProxyCredentials('http://user:[email protected]:8080')).toEqual(+ { username: 'user', password: 'pass' }+ )+ })++ it('fails closed when credentials cannot be represented exactly', () => {+ expect(+ extractAria2ProxyCredentials('http://user%zz:[email protected]:8080')+ ).toBeNull()+ expect(+ extractAria2ProxyCredentials('http://user:%[email protected]:8080')+ ).toBeNull()+ expect(+ extractAria2ProxyCredentials(+ 'http://user%0Ahttp-proxy%3Dhttp%3A%2F%2Fevil:[email protected]:8080'+ )+ ).toBeNull()+ expect(+ extractAria2ProxyCredentials('http://user:%[email protected]:8080')+ ).toBeNull()+ })+})++describe('decideAria2ProxyRoute', () => {+ it('uses exact host and IP matching', () => {+ expect(decideAria2ProxyRoute('http://localhost/file', 'localhost')).toBe(+ 'direct'+ )+ expect(+ decideAria2ProxyRoute('http://sub.localhost/file', 'localhost')+ ).toBe('proxy')+ expect(decideAria2ProxyRoute('http://127.0.0.1/file', '127.0.0.1')).toBe(+ 'direct'+ )+ expect(decideAria2ProxyRoute('http://[::1]/file', '::1')).toBe('direct')+ })++ it('strips spaces like aria2 and skips empty entries', () => {+ expect(+ decideAria2ProxyRoute(+ 'http://localhost/file',+ ' , example.test, localhost, '+ )+ ).toBe('direct')+ })++ it('rejects control characters in targets and no-proxy policy', () => {+ expect(+ decideAria2ProxyRoute(+ 'http://localhost/file',+ 'localhost\nhttp-proxy=http://evil'+ )+ ).toBe('unsupported')+ expect(decideAria2ProxyRoute('http://local\thost/file', '')).toBe(+ 'unsupported'+ )+ })++ it('keeps aria2 exact and suffix comparisons case-sensitive', () => {+ expect(decideAria2ProxyRoute('http://localhost/file', 'LOCALHOST')).toBe(+ 'proxy'+ )+ expect(decideAria2ProxyRoute('http://api.internal/file', '.INTERNAL')).toBe(+ 'proxy'+ )+ expect(decideAria2ProxyRoute('http://LOCALHOST/file', 'LOCALHOST')).toBe(+ 'direct'+ )+ expect(decideAria2ProxyRoute('http://LOCALHOST/file', 'localhost')).toBe(+ 'proxy'+ )+ expect(decideAria2ProxyRoute('http://API.Internal/file', '.internal')).toBe(+ 'proxy'+ )+ })++ it('matches a leading-dot domain only for subdomains', () => {+ expect(+ decideAria2ProxyRoute('https://api.internal/file', '.internal')+ ).toBe('direct')+ expect(+ decideAria2ProxyRoute('https://deep.api.internal/file', '.internal')+ ).toBe('direct')+ expect(decideAria2ProxyRoute('https://internal/file', '.internal')).toBe(+ 'proxy'+ )+ })++ it('does not treat a leading dot as a suffix for numeric hosts', () => {+ expect(decideAria2ProxyRoute('http://127.0.0.1/file', '.0.0.1')).toBe(+ 'proxy'+ )+ })++ it('treats wildcard, port, and URL-like entries exactly as aria2 does', () => {+ expect(+ decideAria2ProxyRoute('https://api.internal/file', '*.internal')+ ).toBe('proxy')+ expect(+ decideAria2ProxyRoute('http://127.0.0.1:8080/file', '127.0.0.1:8080')+ ).toBe('proxy')+ expect(+ decideAria2ProxyRoute('https://api.internal/file', 'https://api.internal')+ ).toBe('proxy')+ })++ it('matches IPv4 and IPv6 CIDR without resolving hostnames', () => {+ expect(+ decideAria2ProxyRoute('http://127.22.33.44/file', '127.0.0.0/8')+ ).toBe('direct')+ expect(decideAria2ProxyRoute('http://128.0.0.1/file', '127.0.0.0/8')).toBe(+ 'proxy'+ )+ expect(+ decideAria2ProxyRoute('http://[2001:db8::42]/file', '2001:db8::/32')+ ).toBe('direct')+ expect(+ decideAria2ProxyRoute('http://service.internal/file', '127.0.0.0/8')+ ).toBe('proxy')+ expect(decideAria2ProxyRoute('http://127.1/file', '127.0.0.0/8')).toBe(+ 'unsupported'+ )+ expect(decideAria2ProxyRoute('http://%6cocalhost/file', 'localhost')).toBe(+ 'unsupported'+ )+ })++ it('clamps an oversized CIDR prefix to the address width like aria2', () => {+ expect(+ decideAria2ProxyRoute('http://127.0.0.1/file', '127.0.0.1/999')+ ).toBe('direct')+ expect(+ decideAria2ProxyRoute('http://127.0.0.2/file', '127.0.0.1/999')+ ).toBe('proxy')+ })++ it('ignores malformed CIDR entries instead of changing later matches', () => {+ expect(+ decideAria2ProxyRoute(+ 'http://localhost/file',+ '127.0.0.0/not-a-prefix,localhost'+ )+ ).toBe('direct')+ expect(decideAria2ProxyRoute('http://127.0.0.1/file', 'not-an-ip/8')).toBe(+ 'proxy'+ )+ })++ it('can be called for every redirect hop', () => {+ const noProxy = '.internal,10.0.0.0/8'+ expect(+ decideAria2ProxyRoute('https://downloads.example/start', noProxy)+ ).toBe('proxy')+ expect(+ decideAria2ProxyRoute('https://mirror.internal/release', noProxy)+ ).toBe('direct')+ expect(decideAria2ProxyRoute('http://10.20.30.40/release', noProxy)).toBe(+ 'direct'+ )+ })++ it('returns unsupported only when the target itself cannot be routed', () => {+ expect(decideAria2ProxyRoute('not a URL', 'localhost')).toBe('unsupported')+ expect(decideAria2ProxyRoute('ftp://localhost/file', 'localhost')).toBe(+ 'unsupported'+ )+ expect(decideAria2ProxyRoute('HTTP://LOCALHOST/file', 'LOCALHOST')).toBe(+ 'unsupported'+ )+ })+})diff --git a/src/core/proxy/aria2-proxy-routing.ts b/src/core/proxy/aria2-proxy-routing.tsnew file mode 100644index 00000000..23a1935d--- /dev/null+++ b/src/core/proxy/aria2-proxy-routing.ts@@ -0,0 +1,324 @@+import { BlockList, isIP } from 'node:net'++const EXPLICIT_PROXY_SCHEME = /^[A-Za-z][A-Za-z\d+.-]*:\/\//+const ARIA2_STRIP = /^[\r\n\t ]+|[\r\n\t ]+$/g+const ARIA2_UNSIGNED_INTEGER = /^[\t\n\v\f\r ]*[+-]?\d+[\t\n\v\f\r ]*$/+const MAX_ARIA2_UNSIGNED_INTEGER = 2_147_483_647++export type ProxyRouteDecision = 'direct' | 'proxy' | 'unsupported'++export interface Aria2ProxyCredentials {+ username: string+ password: string+}++/**+ * Normalize a proxy authority for the HTTP clients used by core services.+ * aria2 accepts a scheme-less proxy value as HTTP, so preserve that behavior+ * instead of requiring callers to special-case persisted or task-level input.+ */+export function normalizeProxyUrl(input: string): URL | null {+ if (hasC0SpaceOrDel(input) || input.includes('\\')) return null+ const value = input+ if (!value || value.includes('?') || value.includes('#')) return null+ const candidate = EXPLICIT_PROXY_SCHEME.test(value)+ ? value+ : `http://${value}`++ let url: URL+ try {+ url = new URL(candidate)+ } catch {+ return null+ }++ if (+ url.protocol !== 'http:' &&+ url.protocol !== 'https:' &&+ url.protocol !== 'socks5:'+ ) {+ return null+ }+ const scheme = rawUrlScheme(candidate)+ const hostname = rawUrlHostname(candidate)+ if (+ scheme !== url.protocol.slice(0, -1) ||+ !hostname ||+ !equivalentUrlHostname(hostname, unbracketHostname(url.hostname))+ ) {+ return null+ }+ if (+ !url.hostname ||+ (url.pathname !== '' && url.pathname !== '/') ||+ url.search ||+ url.hash+ ) {+ return null+ }+ if (url.port === '0') return null++ return url+}++/**+ * Normalize the per-download `all-proxy` syntax accepted by aria2. Unlike the+ * application-wide SOCKS setting, task proxies do not pass through the local+ * bridge and aria2 itself cannot consume a socks5:// URI.+ */+export function normalizeAria2TaskProxyUrl(input: string): URL | null {+ const url = parseAria2ProxyUrl(input)+ return url && url.protocol !== 'socks5:' ? url : null+}++/** Remove URI userinfo without canonicalizing aria2's accepted authority. */+export function stripAria2ProxyCredentials(input: string): string | null {+ if (!parseAria2ProxyUrl(input)) return null+ const scheme = EXPLICIT_PROXY_SCHEME.exec(input)+ const authorityStart = scheme?.[0].length ?? 0+ const delimiter = input.lastIndexOf('@')+ return delimiter < authorityStart+ ? input+ : `${input.slice(0, authorityStart)}${input.slice(delimiter + 1)}`+}++/**+ * Resolve the credential values aria2's dedicated proxy options expect.+ * aria2 percent-decodes URI userinfo before authentication, while standalone+ * `*-proxy-user` / `*-proxy-passwd` values are consumed as plain text.+ */+export function extractAria2ProxyCredentials(+ input: string+): Aria2ProxyCredentials | null {+ const url = parseAria2ProxyUrl(input)+ if (!url) return null++ try {+ const credentials = {+ username: decodeURIComponent(url.username),+ password: decodeURIComponent(url.password),+ }+ // aria2 reparses argv values through a line-oriented config stream. A+ // decoded CR/LF would become a new option; other controls are likewise+ // not portable between its URI parser and dedicated credential options.+ if (hasC0OrDel(credentials.username) || hasC0OrDel(credentials.password)) {+ return null+ }+ return credentials+ } catch {+ return null+ }+}++/**+ * Parse syntax consumed by aria2 itself. This intentionally does not require+ * raw hostname text to equal WHATWG's canonical form: aria2 accepts legacy+ * numeric IPv4 authorities such as 127.1. Metadata clients still use the+ * stricter normalizeProxyUrl() and therefore fail closed when they cannot+ * reproduce that authority exactly.+ */+function parseAria2ProxyUrl(input: string): URL | null {+ if (hasC0SpaceOrDel(input) || input.includes('\\')) return null+ if (!input || input.includes('?') || input.includes('#')) return null+ const candidate = EXPLICIT_PROXY_SCHEME.test(input)+ ? input+ : `http://${input}`++ let url: URL+ try {+ url = new URL(candidate)+ } catch {+ return null+ }+ if (+ url.protocol !== 'http:' &&+ url.protocol !== 'https:' &&+ url.protocol !== 'socks5:'+ ) {+ return null+ }+ if (rawUrlScheme(candidate) !== url.protocol.slice(0, -1)) return null+ if (+ !rawUrlHostname(candidate) ||+ !url.hostname ||+ (url.pathname !== '' && url.pathname !== '/') ||+ url.search ||+ url.hash ||+ url.port === '0'+ ) {+ return null+ }+ return url+}++/**+ * Decide the route for one HTTP(S) hop using aria2's no-proxy semantics.+ * Call this again for every redirect target; a bypass decision for one origin+ * must not be inherited by another origin.+ */+export function decideAria2ProxyRoute(+ target: string | URL,+ noProxy = ''+): ProxyRouteDecision {+ if (+ (typeof target === 'string' && hasC0OrDel(target)) ||+ hasC0OrDel(noProxy)+ ) {+ return 'unsupported'+ }+ const parsed = parseHttpTarget(target)+ if (!parsed) return 'unsupported'++ const hostname = unbracketHostname(parsed.hostname)+ if (!hostname) return 'unsupported'++ const entries = noProxy+ .split(',')+ .map((entry) => entry.replace(ARIA2_STRIP, ''))+ .filter(Boolean)++ for (const entry of entries) {+ const slash = entry.indexOf('/')+ if (slash === -1) {+ if (aria2DomainMatch(hostname, entry)) return 'direct'+ continue+ }++ const bits = parseAria2UnsignedInteger(entry.slice(slash + 1))+ if (bits === null) continue++ const cidrMatch = inAria2CidrBlock(entry.slice(0, slash), hostname, bits)+ if (cidrMatch === 'unsupported') return 'unsupported'+ if (cidrMatch) return 'direct'+ }++ return 'proxy'+}++function parseHttpTarget(target: string | URL): { hostname: string } | null {+ let url: URL+ try {+ url = typeof target === 'string' ? new URL(target) : target+ } catch {+ return null+ }+ if (url.protocol !== 'http:' && url.protocol !== 'https:') return null++ // WHATWG URL lowercases and canonicalizes hostnames. aria2 deliberately+ // compares no-proxy domain entries against the original authority text, so+ // retain it whenever the caller still has the raw URL string. This matters+ // for case-sensitive entries and non-canonical numeric forms such as 127.1.+ if (typeof target !== 'string') return { hostname: url.hostname }++ const hostname = rawUrlHostname(target)+ if (!hostname) return null+ // Avoid letting WHATWG-only host canonicalization turn a probe into a+ // request aria2 would route or resolve differently (percent-encoded hosts,+ // legacy IPv4 numbers, IDN punycode, or alternate IPv6 spellings).+ const scheme = rawUrlScheme(target)+ if (scheme !== 'http' && scheme !== 'https') return null+ if (!equivalentUrlHostname(hostname, unbracketHostname(url.hostname))) {+ return null+ }+ return { hostname }+}++function rawUrlScheme(input: string): string | null {+ const match = /^[\r\n\t ]*([A-Za-z][A-Za-z\d+.-]*):\/\//.exec(input)+ return match?.[1] ?? null+}++function rawUrlHostname(input: string): string | null {+ const match = /^[\r\n\t ]*[A-Za-z][A-Za-z\d+.-]*:\/\/([^/?#]*)/.exec(input)+ if (!match?.[1]) return null++ const authority = match[1]+ const hostAndPort = authority.slice(authority.lastIndexOf('@') + 1)+ if (hostAndPort.startsWith('[')) {+ const closingBracket = hostAndPort.indexOf(']')+ return closingBracket > 1 ? hostAndPort.slice(1, closingBracket) : null+ }++ const portSeparator = hostAndPort.lastIndexOf(':')+ return portSeparator === -1+ ? hostAndPort+ : hostAndPort.slice(0, portSeparator)+}++function unbracketHostname(hostname: string): string {+ return hostname.startsWith('[') && hostname.endsWith(']')+ ? hostname.slice(1, -1)+ : hostname+}++function equivalentUrlHostname(raw: string, normalized: string): boolean {+ if (raw.toLowerCase() === normalized.toLowerCase()) return true+ if (isIP(raw) !== 6 || isIP(normalized) !== 6) return false+ try {+ return (+ unbracketHostname(new URL(`http://[${raw}]/`).hostname).toLowerCase() ===+ normalized.toLowerCase()+ )+ } catch {+ return false+ }+}++function hasC0OrDel(value: string): boolean {+ for (const character of value) {+ const codePoint = character.codePointAt(0) ?? 0+ if (codePoint <= 0x1f || codePoint === 0x7f) return true+ }+ return false+}++function hasC0SpaceOrDel(value: string): boolean {+ for (const character of value) {+ const codePoint = character.codePointAt(0) ?? 0+ if (codePoint <= 0x20 || codePoint === 0x7f) return true+ }+ return false+}++function aria2DomainMatch(hostname: string, entry: string): boolean {+ if (entry.startsWith('.') && isIP(hostname) === 0) {+ return hostname.endsWith(entry)+ }+ return hostname === entry+}++function parseAria2UnsignedInteger(value: string): number | null {+ if (!ARIA2_UNSIGNED_INTEGER.test(value)) return null+ const parsed = Number(value)+ if (+ !Number.isInteger(parsed) ||+ parsed < 0 ||+ parsed > MAX_ARIA2_UNSIGNED_INTEGER+ ) {+ return null+ }+ return parsed+}++function inAria2CidrBlock(+ network: string,+ hostname: string,+ bits: number+): boolean | 'unsupported' {+ const networkFamily = isIP(network)+ const hostnameFamily = isIP(hostname)+ if (networkFamily === 0 || networkFamily !== hostnameFamily) return false++ const addressType = networkFamily === 4 ? 'ipv4' : 'ipv6'+ const prefix = Math.min(bits, networkFamily === 4 ? 32 : 128)+ try {+ const block = new BlockList()+ block.addSubnet(network, prefix, addressType)+ return block.check(hostname, addressType)+ } catch {+ // Both addresses passed Node's numeric-host parser. If its subnet parser+ // still cannot represent them, do not guess a route that could diverge+ // from aria2.+ return 'unsupported'+ }+}diff --git a/src/core/proxy/serializers.test.ts b/src/core/proxy/serializers.test.tsindex b1369248..54426591 100644--- a/src/core/proxy/serializers.test.ts+++ b/src/core/proxy/serializers.test.ts@@ -2,6 +2,7 @@ import { DEFAULT_PROXY_SETTINGS } from '@shared/schemas/proxy-settings'import { describe, expect, it } from 'vitest'import {proxyToAria2Options,+ proxyToDownloadRequestOptions,proxyToElectronConfig,proxyToFetchUrl,} from './serializers'@@ -68,6 +69,23 @@ describe('proxyToAria2Options', () => {})expect(r?.allProxy).toBe('http://[2001:db8::1]:8080')})++ it('rejects control characters at the serialization boundary', () => {+ expect(+ proxyToAria2Options({+ ...enabledHttp,+ bypass: ['localhost\nhttp-proxy=http://evil'],+ scopes: { download: true, updateApp: false, updateTrackers: false },+ })+ ).toBeNull()+ expect(+ proxyToAria2Options({+ ...enabledHttp,+ user: 'user\nhttp-proxy=http://evil',+ scopes: { download: true, updateApp: false, updateTrackers: false },+ })+ ).toBeNull()+ })})describe('proxyToElectronConfig', () => {@@ -93,6 +111,29 @@ describe('proxyToElectronConfig', () => {})})+describe('proxyToDownloadRequestOptions', () => {+ it('returns null outside the enabled download scope', () => {+ expect(proxyToDownloadRequestOptions(DEFAULT_PROXY_SETTINGS)).toBeNull()+ expect(proxyToDownloadRequestOptions(enabledHttp)).toBeNull()+ })++ it('keeps the current proxy credentials and bypass only in request memory', () => {+ expect(+ proxyToDownloadRequestOptions({+ ...enabledHttp,+ protocol: 'socks5',+ user: 'a@b',+ password: 'p:s',+ bypass: ['localhost', '127.0.0.0/8'],+ scopes: { download: true, updateApp: false, updateTrackers: false },+ })+ ).toEqual({+ proxy: 'socks5://a%40b:p%[email protected]:8080',+ noProxy: 'localhost,127.0.0.0/8',+ })+ })+})+describe('proxyToFetchUrl', () => {it('returns null when scope off', () => {expect(proxyToFetchUrl(enabledHttp)).toBeNull()diff --git a/src/core/proxy/serializers.ts b/src/core/proxy/serializers.tsindex e0965086..3882a09b 100644--- a/src/core/proxy/serializers.ts+++ b/src/core/proxy/serializers.ts@@ -5,10 +5,16 @@ export interface Aria2ProxyOptions {noProxy: string}+export interface DownloadProxyRequestOptions {+ proxy: string+ noProxy: string+}+export function proxyToAria2Options(p: ProxySettings): Aria2ProxyOptions | null {if (!p.enabled || !p.scopes.download) return null+ if (hasUnsafeProxyControls(p)) return nullif (p.protocol === 'socks5') return nullif (!p.host || p.port <= 0) return nullreturn {@@ -21,6 +27,7 @@ export function proxyToElectronConfig(p: ProxySettings): { proxyRules: string; proxyBypassRules: string } | null {if (!p.enabled || !p.scopes.updateApp) return null+ if (hasUnsafeProxyControls(p)) return nullif (!p.host || p.port <= 0) return nullconst url = proxyToUrl(p)const rules = p.protocol === 'socks5' ? `socks5=${url}` : url@@ -29,11 +36,32 @@ export function proxyToElectronConfig(export function proxyToFetchUrl(p: ProxySettings): string | null {if (!p.enabled || !p.scopes.updateTrackers) return null+ if (hasUnsafeProxyControls(p)) return nullif (!p.host || p.port <= 0) return nullreturn proxyToUrl(p)}+/**+ * Snapshot the current global download-proxy policy for a short-lived HTTP+ * request. Unlike proxyToAria2Options(), SOCKS5 remains usable here because+ * the metadata client can speak SOCKS5 directly.+ */+export function proxyToDownloadRequestOptions(+ p: ProxySettings+): DownloadProxyRequestOptions | null {+ if (!p.enabled || !p.scopes.download) return null+ if (hasUnsafeProxyControls(p)) return null+ if (!p.host || p.port <= 0) return null+ return {+ proxy: proxyToUrl(p),+ noProxy: p.bypass.join(','),+ }+}+export function proxyToUrl(p: ProxySettings): string {+ if (hasUnsafeProxyControls(p)) {+ throw new TypeError('Proxy fields must not contain control characters')+ }const auth = p.user? `${encodeURIComponent(p.user)}:${encodeURIComponent(p.password)}@`: ''@@ -41,3 +69,15 @@ export function proxyToUrl(p: ProxySettings): string {p.host.includes(':') && !p.host.startsWith('[') ? `[${p.host}]` : p.hostreturn `${p.protocol}://${auth}${host}:${p.port}`}++function hasUnsafeProxyControls(p: ProxySettings): boolean {+ return [p.host, p.user, p.password, ...p.bypass].some(hasC0OrDel)+}++function hasC0OrDel(value: string): boolean {+ for (const character of value) {+ const codePoint = character.codePointAt(0) ?? 0+ if (codePoint <= 0x1f || codePoint === 0x7f) return true+ }+ return false+}diff --git a/src/core/session/session-manager.test.ts b/src/core/session/session-manager.test.tsindex 806c0e57..d7fd4b0c 100644--- a/src/core/session/session-manager.test.ts+++ b/src/core/session/session-manager.test.ts@@ -1,6 +1,7 @@import fs from 'node:fs'import os from 'node:os'import path from 'node:path'+import { AppliedDownloadProxyPolicy } from '@core/proxy/applied-download-proxy-policy'import { DownloadErrorCode } from '@shared/errors'import type { DownloadTask } from '@shared/types/task'import {@@ -15,6 +16,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'import type { Aria2RpcClient } from '../engine/aria2/aria2-rpc-client'import type { Aria2RawStatus } from '../engine/aria2/types'import type { EngineAdapter } from '../engine/engine-adapter'+import { DIRECT_RESOURCE_METADATA_PROFILE } from '../engine/engine-adapter'import { clearStoppedTasks } from '../task/actions/clear-stopped-tasks'import { stopSeedingTask } from '../task/actions/stop-seeding-task'import { TaskManager } from '../task/task-manager'@@ -338,6 +340,9 @@ function createMockAdapter(): EngineAdapter {disconnect: vi.fn(),getCapabilities: vi.fn(),getFeatureReport: vi.fn(),+ getDirectResourceMetadataProfile: vi.fn(+ () => DIRECT_RESOURCE_METADATA_PROFILE+ ),createDownload: vi.fn(async ({ gid }) => gid ?? 'gid-mock'),pauseTask: vi.fn(),resumeTask: vi.fn(),@@ -1927,7 +1932,7 @@ describe('SessionManager', () => {expect(restored?.engineTaskId).not.toBe('lost-http')})- it('re-adds HTTP at the exact .motrix path when an aria2 checkpoint exists', async () => {+ it('blocks an HTTP checkpoint that has no captured resource validator', async () => {const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'motrix-http-checkpoint-'))@@ -1959,17 +1964,13 @@ describe('SessionManager', () => {await sessionManager.restore()- expect(adapter.createDownload).toHaveBeenCalledWith(- expect.objectContaining({- saveDir: tempDir,- filename: 'archive.zip.motrix',- connections: 4,- resumePolicy: 'checkpoint',- })- )- expect(taskManager.getById('m-http-checkpoint')?.status).toBe(- TaskStatus.Downloading- )+ expect(adapter.createDownload).not.toHaveBeenCalled()+ expect(taskManager.getById('m-http-checkpoint')).toMatchObject({+ status: TaskStatus.Error,+ errorDetailKey: 'task.recovery.startup.resumeValidationFailed',+ })+ expect(fs.existsSync(diskPath)).toBe(true)+ expect(fs.existsSync(`${diskPath}.aria2`)).toBe(true)} finally {fs.rmSync(tempDir, { recursive: true, force: true })}@@ -1986,9 +1987,13 @@ describe('SessionManager', () => {contentLength: 4096,capturedAt: 7,}- const verify = vi.fn().mockResolvedValue({- outcome: 'unchanged' as const,- ifRange: resourceValidator.value,+ let currentUserAgent = 'Motrix/Verified'+ const verify = vi.fn(async () => {+ currentUserAgent = 'Motrix/Newer'+ return {+ outcome: 'unchanged' as const,+ ifRange: resourceValidator.value,+ }})try {fs.writeFileSync(diskPath, Buffer.alloc(32, 0x61))@@ -2018,18 +2023,29 @@ describe('SessionManager', () => {adapter,undefined,undefined,- { verify }+ { verify },+ () => ({+ proxy: 'http://proxy.example:8080',+ noProxy: '.internal',+ userAgent: currentUserAgent,+ }))await sessionManager.restore()expect(verify).toHaveBeenCalledWith('https://example.com/archive.zip',- resourceValidator+ resourceValidator,+ {+ proxy: 'http://proxy.example:8080',+ noProxy: '.internal',+ userAgent: 'Motrix/Verified',+ })expect(adapter.createDownload).toHaveBeenCalledWith(expect.objectContaining({headers: { 'If-Range': '"release-v1"' },+ userAgent: 'Motrix/Verified',resumePolicy: 'checkpoint',}))@@ -2038,6 +2054,81 @@ describe('SessionManager', () => {}})+ it.each(['unchanged', 'source-changed', 'unverifiable'] as const)(+ 'does not persist a stale %s validation after proxy restart',+ async (outcome) => {+ const tempDir = fs.mkdtempSync(+ path.join(os.tmpdir(), 'motrix-http-validator-proxy-lease-')+ )+ const diskPath = path.join(tempDir, 'archive.zip.motrix')+ const resourceValidator = {+ kind: 'strong-etag' as const,+ value: '"release-v1"',+ capturedAt: 7,+ }+ const policy = new AppliedDownloadProxyPolicy({+ proxy: 'http://proxy.example:8080',+ noProxy: '.internal',+ })+ const verify = vi.fn(async () => {+ policy.markUnavailable()+ return {+ outcome,+ ifRange: outcome === 'unchanged' ? resourceValidator.value : null,+ }+ })+ try {+ fs.writeFileSync(diskPath, Buffer.alloc(32, 0x61))+ fs.writeFileSync(`${diskPath}.aria2`, Buffer.alloc(16, 0x62))+ seedAsPair(db, {+ motrixId: 'm-http-validator-proxy-lease',+ gid: 'lost-http-validator-proxy-lease',+ name: 'archive.zip',+ diskPath,+ finalPath: path.join(tempDir, 'archive.zip'),+ finalName: 'archive.zip',+ uris: ['https://example.com/archive.zip'],+ status: TaskStatus.Downloading,+ payload: {+ directReplay: {+ version: 1,+ requestModifiers: [],+ replayability: 'uri-only',+ resourceValidator,+ },+ },+ })+ sessionManager = new SessionManager(+ taskManager,+ rpc,+ db,+ adapter,+ undefined,+ undefined,+ { verify },+ () => policy.snapshot()+ )++ await expect(+ policy.runWithSnapshot((_snapshot, lease) =>+ sessionManager.restore(lease.assertCurrent)+ )+ ).rejects.toThrow('applied download proxy policy changed')++ expect(verify).toHaveBeenCalledOnce()+ expect(adapter.createDownload).not.toHaveBeenCalled()+ expect(+ taskManager.getById('m-http-validator-proxy-lease')+ ).toBeUndefined()+ expect(+ db.getTask('m-http-validator-proxy-lease')?.task.aggStatus+ ).toBe(TaskStatus.Downloading)+ } finally {+ fs.rmSync(tempDir, { recursive: true, force: true })+ }+ }+ )+it.each([['source-changed', 'task.recovery.startup.resumeSourceChanged'] as const,[@@ -2089,7 +2180,8 @@ describe('SessionManager', () => {adapter,undefined,undefined,- { verify }+ { verify },+ () => ({}))await sessionManager.restore()@@ -2106,6 +2198,72 @@ describe('SessionManager', () => {})+ it('does not verify a checkpoint when aria2 lacks mirrored header features', async () => {+ const tempDir = fs.mkdtempSync(+ path.join(os.tmpdir(), 'motrix-http-validator-feature-profile-')+ )+ const diskPath = path.join(tempDir, 'archive.zip.motrix')+ const resourceValidator = {+ kind: 'strong-etag' as const,+ value: '"release-v1"',+ capturedAt: 7,+ }+ const verify = vi.fn()+ try {+ fs.writeFileSync(diskPath, Buffer.from('partial'))+ fs.writeFileSync(`${diskPath}.aria2`, Buffer.from('checkpoint'))+ seedAsPair(db, {+ motrixId: 'm-http-validator-feature-profile',+ gid: 'lost-http-validator-feature-profile',+ name: 'archive.zip',+ diskPath,+ finalPath: path.join(tempDir, 'archive.zip'),+ finalName: 'archive.zip',+ uris: ['https://example.com/archive.zip'],+ status: TaskStatus.Downloading,+ payload: {+ directReplay: {+ version: 1,+ requestModifiers: [],+ replayability: 'uri-only',+ resourceValidator,+ },+ },+ })+ vi.mocked(adapter.getFeatureReport).mockReturnValue({+ version: '1.37.0',+ features: ['GZip'],+ hasSqlitePersistence: false,+ hasBtSeedUnverified: false,+ hasBtSaveMetadata: false,+ hasMoveStorage: false,+ })+ sessionManager = new SessionManager(+ taskManager,+ rpc,+ db,+ adapter,+ undefined,+ undefined,+ { verify },+ () => ({})+ )++ await sessionManager.restore()++ expect(verify).not.toHaveBeenCalled()+ expect(adapter.createDownload).not.toHaveBeenCalled()+ expect(+ taskManager.getById('m-http-validator-feature-profile')+ ).toMatchObject({+ status: TaskStatus.Error,+ errorDetailKey: 'task.recovery.startup.resumeValidationFailed',+ })+ } finally {+ fs.rmSync(tempDir, { recursive: true, force: true })+ }+ })+it('preserves a non-empty HTTP partial when its checkpoint is missing', async () => {const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'motrix-http-no-checkpoint-')diff --git a/src/core/session/session-manager.ts b/src/core/session/session-manager.tsindex 61fbb6fa..4f575844 100644--- a/src/core/session/session-manager.ts+++ b/src/core/session/session-manager.ts@@ -27,7 +27,10 @@ import {translateStatus,} from '../engine/aria2/translate'import type { Aria2RawStatus } from '../engine/aria2/types'-import type { EngineAdapter } from '../engine/engine-adapter'+import type {+ DirectResourceMetadataProfile,+ EngineAdapter,+} from '../engine/engine-adapter'import {buildTerminalOccurrence,terminalSnapshotFromTask,@@ -37,7 +40,11 @@ import {terminalFieldsFromRow,} from '../task/apply-terminal-transition'import { shouldPrioritizeBtPreviewPiecesFromMetadata } from '../task/bt-storage-layout'-import { DirectResourceValidatorService } from '../task/direct-resource-validator'+import {+ canMirrorAria2MetadataHeaders,+ type DirectResourceProxyOptionsProvider,+ DirectResourceValidatorService,+} from '../task/direct-resource-validator'import { isTempPath } from '../task/paths'import { setTaskTransitionPhase } from '../task/task-instance'import type { TaskManager } from '../task/task-manager'@@ -238,7 +245,9 @@ export class SessionManager {private directResourceValidator: Pick<DirectResourceValidatorService,'verify'- > = new DirectResourceValidatorService()+ > = new DirectResourceValidatorService(),+ private getDirectResourceProxyOptions: DirectResourceProxyOptionsProvider = () =>+ null) {}runExclusivePersistence<T>(operation: () => T | Promise<T>): Promise<T> {@@ -395,7 +404,7 @@ export class SessionManager {return { task: taskRow, instances }}- async restore(): Promise<void> {+ async restore(assertProxyCurrent?: () => void): Promise<void> {// aria2 is the source of truth for engine lifecycle. motrix.db is a// metadata sidecar tracking task identity and the relationship between// a task and its instances. The loop is driven by aria2: every live@@ -715,7 +724,7 @@ export class SessionManager {continue}- const task = await this.reAddOrMarkErrorFromPair(pair)+ const task = await this.reAddOrMarkErrorFromPair(pair, assertProxyCurrent)this.taskManager.set(task.id, task)}@@ -749,7 +758,7 @@ export class SessionManager {private static readonly LEGACY_LOST_MESSAGE ='Task lost: aria2 engine no longer has this download'- async recoverLegacyTaskLost(): Promise<void> {+ async recoverLegacyTaskLost(assertProxyCurrent?: () => void): Promise<void> {const tasks = this.taskManager.getAll()for (const task of tasks) {if (@@ -760,7 +769,10 @@ export class SessionManager {}const pair = this.db.getTask(task.id)if (!pair) continue- const fresh = await this.reAddOrMarkErrorFromPair(pair)+ const fresh = await this.reAddOrMarkErrorFromPair(+ pair,+ assertProxyCurrent+ )// reAddOrMarkErrorFromPair's Error outcome already persisted itself via// markRecoverErrorFromPair's persistTaskWithOccurrence; only its// successful-re-add outcome (adoptByPair alone, which never returns@@ -1127,7 +1139,8 @@ export class SessionManager {}private async reAddOrMarkErrorFromPair(- pair: TaskWithInstances+ pair: TaskWithInstances,+ assertProxyCurrent?: () => void): Promise<DownloadTask> {const taskPart = pair.taskconst primary = pair.instances[0]@@ -1178,6 +1191,7 @@ export class SessionManager {'task.recovery.startup.resumeCredentialsRequired')}+ const requestOptions = this.getDirectResourceProxyOptions()const plan = await this.directRecoveryPlanner.plan({primary,@@ -1213,6 +1227,23 @@ export class SessionManager {? 'sequential-prefix': 'none'let ifRange: string | null = null+ const metadataProfile = canMirrorAria2MetadataHeaders(+ this.adapter.getFeatureReport?.()+ )+ ? resolveDirectResourceMetadataProfile(this.adapter)+ : null+ if (plan.kind === 'checkpoint' && metadataProfile === null) {+ return this.markRecoverErrorFromPair(+ pair,+ 'task.recovery.startup.resumeValidationFailed'+ )+ }+ if (plan.kind === 'checkpoint' && !recipe?.resourceValidator) {+ return this.markRecoverErrorFromPair(+ pair,+ 'task.recovery.startup.resumeValidationFailed'+ )+ }if (plan.kind === 'checkpoint' && recipe?.resourceValidator) {if (primary.uris.length !== 1) {return this.markRecoverErrorFromPair(@@ -1220,10 +1251,16 @@ export class SessionManager {'task.recovery.startup.resumeValidationFailed')}- const validation = await this.directResourceValidator.verify(- primary.uris[0] as string,- recipe.resourceValidator- )+ const validation =+ requestOptions &&+ canMirrorAria2MetadataHeaders(this.adapter.getFeatureReport?.())+ ? await this.directResourceValidator.verify(+ primary.uris[0] as string,+ recipe.resourceValidator,+ requestOptions+ )+ : { outcome: 'unverifiable' as const, ifRange: null }+ assertProxyCurrent?.()if (validation.outcome !== 'unchanged') {const errorDetailKey =validation.outcome === 'source-changed'@@ -1235,18 +1272,25 @@ export class SessionManager {}ifRange = validation.ifRange}- return this.dispatchRecoveryCandidate(pair, (gid) =>- this.adapter.createDownload({+ return this.dispatchRecoveryCandidate(pair, (gid) => {+ assertProxyCurrent?.()+ return this.adapter.createDownload({uris: primary.uris,gid,saveDir: plan.saveDir as string,filename: plan.filename as string,connections: recipe?.connections,+ ...(plan.kind !== 'checkpoint' || metadataProfile === null+ ? {}+ : { directResourceMetadataProfile: metadataProfile }),+ ...(requestOptions?.userAgent === undefined+ ? {}+ : { userAgent: requestOptions.userAgent }),...(ifRange ? { headers: { 'If-Range': ifRange } } : {}),pause: taskPart.aggStatus === TaskStatus.Paused,resumePolicy,})- )+ })}return this.markRecoverErrorFromPair(@@ -1522,6 +1566,17 @@ export class SessionManager {}}+function resolveDirectResourceMetadataProfile(+ adapter: EngineAdapter+): DirectResourceMetadataProfile | null {+ if (!adapter.getDirectResourceMetadataProfile) return null+ try {+ return adapter.getDirectResourceMetadataProfile()+ } catch {+ return null+ }+}+function synthesizePrimaryInstance(task: DownloadTask,now: numberdiff --git a/src/core/settings/validators.test.ts b/src/core/settings/validators.test.tsindex 416b9954..930ff89d 100644--- a/src/core/settings/validators.test.ts+++ b/src/core/settings/validators.test.ts@@ -107,6 +107,17 @@ describe('validateEngineSettings', () => {expect(result.userAgent).toBe(DEFAULT_ENGINE_SETTINGS.userAgent)})+ it('rejects control characters in RPC credentials and User-Agent', () => {+ const result = validateEngineSettings({+ ...DEFAULT_ENGINE_SETTINGS,+ rpcSecret: 'secret\nrpc-listen-all=true',+ userAgent: 'Motrix\nhttp-proxy=http://evil',+ })++ expect(result.rpcSecret).toBe('')+ expect(result.userAgent).toBe(DEFAULT_ENGINE_SETTINGS.userAgent)+ })+it('uses the Motrix 2.0 default user agent', () => {expect(DEFAULT_ENGINE_SETTINGS.userAgent).toBe('Motrix/2.0')})diff --git a/src/core/task/actions/re-add-task.test.ts b/src/core/task/actions/re-add-task.test.tsindex 20433a38..b4c0afd4 100644--- a/src/core/task/actions/re-add-task.test.ts+++ b/src/core/task/actions/re-add-task.test.ts@@ -1,6 +1,7 @@import fs from 'node:fs'import os from 'node:os'import path from 'node:path'+import { AppliedDownloadProxyPolicy } from '@core/proxy/applied-download-proxy-policy'import { ErrorCode } from '@shared/errors'import { Events } from '@shared/protocol/events'import type { DownloadTask } from '@shared/types/task'@@ -15,6 +16,7 @@ import { makeDownloadTask } from '@test-utils/task'import { directTaskUpdatePublication } from '@test-utils/task-update'import { describe, expect, it, vi } from 'vitest'import type { EngineAdapter } from '../../engine/engine-adapter'+import { DIRECT_RESOURCE_METADATA_PROFILE } from '../../engine/engine-adapter'import type { EventBus } from '../../events/event-bus'import type { Logger } from '../../logger'import { TaskManager } from '../task-manager'@@ -78,6 +80,10 @@ function makeDeps(task: DownloadTask | undefined) {retireEngineTaskIdReservation: vi.fn(() => true),} as unknown as TaskManager,adapter: {+ getFeatureReport: vi.fn(),+ getDirectResourceMetadataProfile: vi.fn(+ () => DIRECT_RESOURCE_METADATA_PROFILE+ ),getEngineTaskOptions: vi.fn().mockResolvedValue(null),forceRemoveTask: vi.fn().mockResolvedValue(undefined),removeDownloadResult: vi.fn().mockResolvedValue(undefined),@@ -432,33 +438,150 @@ describe('reAddTask (HTTP path)', () => {},}const deps = makeDeps(task)- const verify = vi.fn().mockResolvedValue({- outcome: 'unchanged' as const,- ifRange: '"release-v1"',+ let currentUserAgent = 'Motrix/Verified'+ const verify = vi.fn(async () => {+ currentUserAgent = 'Motrix/Newer'+ return {+ outcome: 'unchanged' as const,+ ifRange: '"release-v1"',+ }})+ const proxyOptions = {+ proxy: 'http://proxy.example:8080',+ noProxy: '.internal',+ userAgent: 'Motrix/Verified',+ }await reAddTask('t2', {...deps,directResourceValidator: { verify },+ getDirectResourceProxyOptions: () => ({+ ...proxyOptions,+ userAgent: currentUserAgent,+ }),})expect(verify).toHaveBeenCalledWith('https://example.com/file.zip',- expect.objectContaining({ value: '"release-v1"' })+ expect.objectContaining({ value: '"release-v1"' }),+ proxyOptions)expect(deps.adapter.createDownload).toHaveBeenCalledWith(expect.objectContaining({saveDir: tempDir,filename: 'file.zip.motrix',headers: { 'If-Range': '"release-v1"' },+ userAgent: 'Motrix/Verified',resumePolicy: 'checkpoint',}))+ expect(deps.adapter.createDownload).not.toHaveBeenCalledWith(+ expect.objectContaining({ proxy: expect.anything() })+ )} finally {fs.rmSync(tempDir, { recursive: true, force: true })}})+ it('rejects a checkpoint with no resource validator before mutation', async () => {+ const tempDir = fs.mkdtempSync(+ path.join(os.tmpdir(), 'motrix-direct-no-validator-')+ )+ const diskPath = path.join(tempDir, 'file.zip.motrix')+ try {+ fs.writeFileSync(diskPath, Buffer.from('partial'))+ fs.writeFileSync(`${diskPath}.aria2`, Buffer.from('checkpoint'))+ const task = makeHttpTask({+ diskPath,+ finalPath: path.join(tempDir, 'file.zip'),+ })+ task.instances[0].diskPath = diskPath+ task.instances[0].payload = {+ directReplay: {+ version: 1,+ requestModifiers: [],+ replayability: 'uri-only',+ },+ }+ const deps = makeDeps(task)+ const verify = vi.fn()++ await expect(+ reAddTask('t2', {+ ...deps,+ directResourceValidator: { verify },+ getDirectResourceProxyOptions: () => ({}),+ })+ ).rejects.toMatchObject({ code: ErrorCode.TaskNotRetryable })++ expect(verify).not.toHaveBeenCalled()+ expect(deps.adapter.createDownload).not.toHaveBeenCalled()+ expect(deps.persistTask).not.toHaveBeenCalled()+ expect(deps.adapter.forceRemoveTask).not.toHaveBeenCalled()+ expect(fs.existsSync(diskPath)).toBe(true)+ expect(fs.existsSync(`${diskPath}.aria2`)).toBe(true)+ } finally {+ fs.rmSync(tempDir, { recursive: true, force: true })+ }+ })++ it.each(['unchanged', 'source-changed', 'unverifiable'] as const)(+ 'rejects a stale %s validation result before durable intent',+ async (outcome) => {+ const tempDir = fs.mkdtempSync(+ path.join(os.tmpdir(), 'motrix-direct-readd-proxy-lease-')+ )+ const diskPath = path.join(tempDir, 'file.zip.motrix')+ try {+ fs.writeFileSync(diskPath, Buffer.alloc(32, 0x61))+ fs.writeFileSync(`${diskPath}.aria2`, Buffer.alloc(16, 0x62))+ const task = makeHttpTask({+ diskPath,+ finalPath: path.join(tempDir, 'file.zip'),+ })+ task.instances[0].diskPath = diskPath+ task.instances[0].payload = {+ directReplay: {+ version: 1,+ requestModifiers: [],+ replayability: 'uri-only',+ resourceValidator: {+ kind: 'strong-etag',+ value: '"release-v1"',+ capturedAt: 7,+ },+ },+ }+ const deps = makeDeps(task)+ const policy = new AppliedDownloadProxyPolicy({+ proxy: 'http://proxy.example:8080',+ noProxy: '.internal',+ })+ const verify = vi.fn(async () => {+ policy.markUnavailable()+ return {+ outcome,+ ifRange: outcome === 'unchanged' ? '"release-v1"' : null,+ }+ })++ await expect(+ reAddTask('t2', {+ ...deps,+ directResourceValidator: { verify },+ directResourceProxyPolicy: policy,+ })+ ).rejects.toThrow('applied download proxy policy changed')++ expect(verify).toHaveBeenCalledOnce()+ expect(deps.adapter.createDownload).not.toHaveBeenCalled()+ expect(deps.persistTask).not.toHaveBeenCalled()+ } finally {+ fs.rmSync(tempDir, { recursive: true, force: true })+ }+ }+ )+it('rejects a changed checkpoint source before touching the engine', async () => {const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'motrix-direct-changed-')@@ -508,6 +631,104 @@ describe('reAddTask (HTTP path)', () => {}})+ it('does not verify or resume when aria2 lacks mirrored header features', async () => {+ const tempDir = fs.mkdtempSync(+ path.join(os.tmpdir(), 'motrix-direct-feature-profile-')+ )+ const diskPath = path.join(tempDir, 'file.zip.motrix')+ try {+ fs.writeFileSync(diskPath, Buffer.from('partial'))+ fs.writeFileSync(`${diskPath}.aria2`, Buffer.from('checkpoint'))+ const task = makeHttpTask({+ diskPath,+ finalPath: path.join(tempDir, 'file.zip'),+ })+ task.instances[0].diskPath = diskPath+ task.instances[0].payload = {+ directReplay: {+ version: 1,+ requestModifiers: [],+ replayability: 'uri-only',+ resourceValidator: {+ kind: 'strong-etag',+ value: '"release-v1"',+ capturedAt: 7,+ },+ },+ }+ const deps = makeDeps(task)+ vi.mocked(deps.adapter.getFeatureReport).mockReturnValue({+ version: '1.37.0',+ features: ['Message Digest'],+ hasSqlitePersistence: false,+ hasBtSeedUnverified: false,+ hasBtSaveMetadata: false,+ hasMoveStorage: false,+ })+ const verify = vi.fn()++ await expect(+ reAddTask('t2', {+ ...deps,+ directResourceValidator: { verify },+ getDirectResourceProxyOptions: () => ({}),+ })+ ).rejects.toMatchObject({ code: ErrorCode.TaskNotRetryable })++ expect(verify).not.toHaveBeenCalled()+ expect(deps.adapter.createDownload).not.toHaveBeenCalled()+ expect(deps.persistTask).not.toHaveBeenCalled()+ } finally {+ fs.rmSync(tempDir, { recursive: true, force: true })+ }+ })++ it('rejects checkpoint recovery before mutation when the ambient profile is unsafe', async () => {+ const tempDir = fs.mkdtempSync(+ path.join(os.tmpdir(), 'motrix-direct-ambient-profile-')+ )+ const diskPath = path.join(tempDir, 'file.zip.motrix')+ try {+ fs.writeFileSync(diskPath, Buffer.from('partial'))+ fs.writeFileSync(`${diskPath}.aria2`, Buffer.from('checkpoint'))+ const task = makeHttpTask({+ diskPath,+ finalPath: path.join(tempDir, 'file.zip'),+ })+ task.instances[0].diskPath = diskPath+ task.instances[0].payload = {+ directReplay: {+ version: 1,+ requestModifiers: [],+ replayability: 'uri-only',+ resourceValidator: {+ kind: 'strong-etag',+ value: '"release-v1"',+ capturedAt: 7,+ },+ },+ }+ const deps = makeDeps(task)+ deps.adapter.getDirectResourceMetadataProfile = vi.fn(() => null)+ const verify = vi.fn()++ await expect(+ reAddTask('t2', {+ ...deps,+ directResourceValidator: { verify },+ getDirectResourceProxyOptions: () => ({}),+ })+ ).rejects.toMatchObject({ code: ErrorCode.TaskNotRetryable })++ expect(verify).not.toHaveBeenCalled()+ expect(deps.persistTask).not.toHaveBeenCalled()+ expect(deps.adapter.forceRemoveTask).not.toHaveBeenCalled()+ expect(deps.adapter.createDownload).not.toHaveBeenCalled()+ } finally {+ fs.rmSync(tempDir, { recursive: true, force: true })+ }+ })+it('rejects HTTP retry before engine mutation when a partial has no checkpoint', async () => {const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'motrix-direct-blocked-')diff --git a/src/core/task/actions/re-add-task.ts b/src/core/task/actions/re-add-task.tsindex 56c17031..39a825d0 100644--- a/src/core/task/actions/re-add-task.ts+++ b/src/core/task/actions/re-add-task.ts@@ -1,5 +1,6 @@import path from 'node:path'import { newEngineTaskId } from '@core/lib/ids'+import type { AppliedDownloadProxyPolicyReader } from '@core/proxy/applied-download-proxy-policy'import { AppError, ErrorCode } from '@shared/errors'import { parseDirectReplayRecipe } from '@shared/schemas/direct-replay-recipe'import type { EngineTaskOptions } from '@shared/types/engine-task-options'@@ -13,6 +14,7 @@ import {} from '@shared/types/task-actions'import type {CreateDownloadParams,+ DirectResourceMetadataProfile,EngineAdapter,} from '../../engine/engine-adapter'import type { Logger } from '../../logger'@@ -26,7 +28,11 @@ import {shouldPrioritizeBtPreviewPieces,shouldPrioritizeBtPreviewPiecesFromMetadata,} from '../bt-storage-layout'-import { DirectResourceValidatorService } from '../direct-resource-validator'+import {+ canMirrorAria2MetadataHeaders,+ type DirectResourceProxyOptionsProvider,+ DirectResourceValidatorService,+} from '../direct-resource-validator'import type { TorrentMetaStore } from '../torrent-meta-store'import { commitTaskUpdate, getTaskOrWarn, type TaskActionDeps } from './shared'@@ -36,6 +42,8 @@ export interface ReAddTaskDeps extends TaskActionDeps {torrentMetaStore: TorrentMetaStorecreateEngineTaskId?: () => stringdirectResourceValidator?: Pick<DirectResourceValidatorService, 'verify'>+ getDirectResourceProxyOptions?: DirectResourceProxyOptionsProvider+ directResourceProxyPolicy?: AppliedDownloadProxyPolicyReader}async function bestEffortRemove(@@ -170,7 +178,11 @@ const directResourceValidator = new DirectResourceValidatorService()async function buildDirectReAddParams(task: DownloadTask,- resourceValidator: Pick<DirectResourceValidatorService, 'verify'>+ adapter: EngineAdapter,+ resourceValidator: Pick<DirectResourceValidatorService, 'verify'>,+ getProxyOptions: DirectResourceProxyOptionsProvider,+ assertProxyCurrent: (() => void) | undefined,+ metadataHeadersSupported: boolean): Promise<Omit<CreateDownloadParams, 'gid'>> {const primary = task.instances.find((instance) => instance.phase === TaskInstancePhase.HttpDownload@@ -182,6 +194,7 @@ async function buildDirectReAddParams(`Task ${task.id} cannot be retried: its direct replay recipe is unavailable`)}+ const requestOptions = getProxyOptions()const plan = await directRecoveryPlanner.plan({primary,@@ -201,6 +214,21 @@ async function buildDirectReAddParams(}let ifRange: string | null = null+ const metadataProfile = metadataHeadersSupported+ ? resolveDirectResourceMetadataProfile(adapter)+ : null+ if (plan.kind === 'checkpoint' && metadataProfile === null) {+ throw new AppError(+ ErrorCode.TaskNotRetryable,+ `Task ${task.id} cannot be retried safely: metadata-request-profile-unsupported`+ )+ }+ if (plan.kind === 'checkpoint' && !recipe.resourceValidator) {+ throw new AppError(+ ErrorCode.TaskNotRetryable,+ `Task ${task.id} cannot be retried safely: resource-validator-unavailable`+ )+ }if (plan.kind === 'checkpoint' && recipe.resourceValidator) {if (primary.uris.length !== 1) {throw new AppError(@@ -208,10 +236,24 @@ async function buildDirectReAddParams(`Task ${task.id} cannot be retried safely: ambiguous-validator-source`)}+ if (requestOptions === null) {+ throw new AppError(+ ErrorCode.TaskNotRetryable,+ `Task ${task.id} cannot be retried safely: proxy-policy-unavailable`+ )+ }+ if (!metadataHeadersSupported) {+ throw new AppError(+ ErrorCode.TaskNotRetryable,+ `Task ${task.id} cannot be retried safely: metadata-header-profile-unsupported`+ )+ }const validation = await resourceValidator.verify(primary.uris[0] as string,- recipe.resourceValidator+ recipe.resourceValidator,+ requestOptions)+ assertProxyCurrent?.()if (validation.outcome !== 'unchanged') {throw new AppError(ErrorCode.TaskNotRetryable,@@ -226,6 +268,12 @@ async function buildDirectReAddParams(saveDir: plan.saveDir,filename: plan.filename,connections: recipe.connections,+ ...(plan.kind !== 'checkpoint' || metadataProfile === null+ ? {}+ : { directResourceMetadataProfile: metadataProfile }),+ ...(requestOptions?.userAgent === undefined+ ? {}+ : { userAgent: requestOptions.userAgent }),...(ifRange ? { headers: { 'If-Range': ifRange } } : {}),pause: false,resumePolicy:@@ -237,6 +285,17 @@ async function buildDirectReAddParams(}}+function resolveDirectResourceMetadataProfile(+ adapter: EngineAdapter+): DirectResourceMetadataProfile | null {+ if (!adapter.getDirectResourceMetadataProfile) return null+ try {+ return adapter.getDirectResourceMetadataProfile()+ } catch {+ return null+ }+}+/*** Rebuild the task with a new reserved engine gid stamped on the aggregate* and its primary instance (the one whose gid matches the outgoing@@ -385,8 +444,30 @@ export async function reAddTask(taskId: string,deps: ReAddTaskDeps): Promise<void> {- const reAdd = (): Promise<void> => reAddTaskUnderMutation(taskId, deps)- await deps.runTaskMutation([taskId], reAdd)+ const run = (+ getProxyOptions: DirectResourceProxyOptionsProvider,+ assertProxyCurrent?: () => void+ ) => {+ const reAdd = (): Promise<void> =>+ reAddTaskUnderMutation(taskId, deps, getProxyOptions, assertProxyCurrent)+ return deps.runTaskMutation([taskId], reAdd)+ }+ if (deps.directResourceProxyPolicy) {+ await deps.directResourceProxyPolicy.runWithSnapshot((snapshot, lease) => {+ const providerOptions = deps.getDirectResourceProxyOptions?.()+ const requestOptions = snapshot+ ? {+ ...snapshot,+ ...(providerOptions?.userAgent === undefined+ ? {}+ : { userAgent: providerOptions.userAgent }),+ }+ : null+ return run(() => requestOptions, lease.assertCurrent)+ })+ return+ }+ await run(deps.getDirectResourceProxyOptions ?? (() => null))}/**@@ -397,7 +478,9 @@ export async function reAddTask(*/async function reAddTaskUnderMutation(taskId: string,- deps: ReAddTaskDeps+ deps: ReAddTaskDeps,+ getProxyOptions: DirectResourceProxyOptionsProvider,+ assertProxyCurrent?: () => void): Promise<void> {const task = getTaskOrWarn(deps, taskId, 'reAddTask')if (!task) return@@ -433,7 +516,11 @@ async function reAddTaskUnderMutation(? null: await buildDirectReAddParams(task,- deps.directResourceValidator ?? directResourceValidator+ deps.adapter,+ deps.directResourceValidator ?? directResourceValidator,+ getProxyOptions,+ assertProxyCurrent,+ canMirrorAria2MetadataHeaders(deps.adapter.getFeatureReport?.()))let opts: EngineTaskOptions | null = nulltry {@@ -477,6 +564,7 @@ async function reAddTaskUnderMutation(if (torrentLike && torrentMetadata) {await reAddBt(task, opts, deps, reservedGid, torrentMetadata)} else if (directParams) {+ assertProxyCurrent?.()await deps.adapter.createDownload({ ...directParams, gid: reservedGid })}} catch (error) {diff --git a/src/core/task/create-task-handler.plugin-hook-e2e.test.ts b/src/core/task/create-task-handler.plugin-hook-e2e.test.tsindex 27347e3b..e7ebe530 100644--- a/src/core/task/create-task-handler.plugin-hook-e2e.test.ts+++ b/src/core/task/create-task-handler.plugin-hook-e2e.test.ts@@ -24,6 +24,7 @@ import { HookOrchestrator } from '@core/plugin/hooks/hook-orchestrator'import { PluginHost } from '@core/plugin/host/plugin-host'import { PluginRegistry } from '@core/plugin/plugin-registry'import { PluginStateStore } from '@core/plugin/state/plugin-state-store'+import { AppliedDownloadProxyPolicy } from '@core/proxy/applied-download-proxy-policy'import { migrate } from '@core/session/migrations'import Database from 'better-sqlite3'import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'@@ -220,6 +221,7 @@ function makeBaseDeps(saveDir: string): Deps & {return {adapter,settingsManager,+ directResourceProxyPolicy: new AppliedDownloadProxyPolicy({ noProxy: '' }),finalNamePicker,torrentMetaStore,taskManager,diff --git a/src/core/task/create-task-handler.test.ts b/src/core/task/create-task-handler.test.tsindex 85cf1410..cfc52e82 100644--- a/src/core/task/create-task-handler.test.ts+++ b/src/core/task/create-task-handler.test.ts@@ -1,7 +1,13 @@import { initLogger } from '@core/logger'+import {+ AppliedDownloadProxyPolicy,+ type AppliedDownloadProxySnapshot,+} from '@core/proxy/applied-download-proxy-policy'+import { proxyToDownloadRequestOptions } from '@core/proxy/serializers'import { AppError, ErrorCode } from '@shared/errors'import { DEFAULT_ENGINE_SETTINGS } from '@shared/schemas/engine-settings'import { DEFAULT_PROXY_SETTINGS } from '@shared/schemas/proxy-settings'+import type { EngineFeatureReport } from '@shared/types/engine'import type { ProxySettings } from '@shared/types/settings'import type { DownloadTask } from '@shared/types/task'import {@@ -15,6 +21,7 @@ import {} from '@shared/types/task'import { beforeEach, describe, expect, it, vi } from 'vitest'import { Aria2Adapter } from '../engine/aria2/aria2-adapter'+import { DIRECT_RESOURCE_METADATA_PROFILE } from '../engine/engine-adapter'import { parseBtFileLayout } from './bt-storage-layout'import { handleCreateTask } from './create-task-handler'import { sanitizeRemoteFilename } from './direct-resource-validator'@@ -107,6 +114,9 @@ interface DepOverrides {persist?: (id: string, bytes: Uint8Array) => Promise<string>defaultSaveDir?: stringproxySettings?: ProxySettings+ appliedProxySnapshot?: AppliedDownloadProxySnapshot+ engineUserAgent?: string+ engineFeatureReport?: EngineFeatureReportwaitForEngineReady?: () => Promise<void>prepareSaveDir?: (requested: string) => Promise<string>}@@ -179,6 +189,10 @@ function makeDeps(overrides: DepOverrides = {}): Deps & {// The mock rpc only needs the subset Aria2Adapter touches on the create// path (addUri/addTorrent + the three on* subscriptions).const adapter = new Aria2Adapter(rpcClient as never)+ adapter.setDirectResourceMetadataProfile(DIRECT_RESOURCE_METADATA_PROFILE)+ if (overrides.engineFeatureReport) {+ adapter.setFeatureReport(overrides.engineFeatureReport)+ }const settingsManager = {getApp: () => ({defaultSaveDir: overrides.defaultSaveDir ?? '/fallback',@@ -186,9 +200,16 @@ function makeDeps(overrides: DepOverrides = {}): Deps & {getEngine: () => ({performanceProfile: DEFAULT_ENGINE_SETTINGS.performanceProfile,maxConnectionPerServer: DEFAULT_ENGINE_SETTINGS.maxConnectionPerServer,+ userAgent: overrides.engineUserAgent,}),getProxy: () => overrides.proxySettings ?? DEFAULT_PROXY_SETTINGS,} as unknown as Deps['settingsManager']+ const configuredRequestProxy = proxyToDownloadRequestOptions(+ overrides.proxySettings ?? DEFAULT_PROXY_SETTINGS+ )+ const appliedProxySnapshot = Object.hasOwn(overrides, 'appliedProxySnapshot')+ ? (overrides.appliedProxySnapshot ?? null)+ : (configuredRequestProxy ?? { noProxy: '' })const finalNamePicker = { pick } as unknown as Deps['finalNamePicker']const torrentMetaStore = {persist,@@ -217,6 +238,9 @@ function makeDeps(overrides: DepOverrides = {}): Deps & {const deps: ReturnType<typeof makeDeps> = {adapter,settingsManager,+ directResourceProxyPolicy: new AppliedDownloadProxyPolicy(+ appliedProxySnapshot+ ),finalNamePicker,torrentMetaStore,taskManager,@@ -408,24 +432,19 @@ describe('handleCreateTask', () => {expect(dispatch?.[0]).toMatchObject({method: 'createDownload',uriCount: 1,- params: {- uris: ['https://example.com/file.zip'],- saveDir: '/d',- filename: 'file.zip.motrix',- connections: 8,- headers: ['Authorization', 'Cookie'],- proxy: 'http://proxy.example:8080',- extraEngineOptions: {- referer: 'https://origin.example/watch',- 'load-cookies': '[redacted-path]',- 'unknown-option': '[redacted]',- },- },+ saveDir: '/d',+ filename: 'file.zip.motrix',+ connections: 8,})const dispatchFields = dispatch?.[0] as- | { params: { gid: string } }+ | { gid: string; params?: unknown; uris?: unknown; headers?: unknown }| undefined- expect(dispatchFields?.params.gid).toMatch(/^[0-9a-f]{16}$/)+ expect(dispatchFields?.gid).toMatch(/^[0-9a-f]{16}$/)+ expect(dispatchFields).not.toHaveProperty('params')+ expect(dispatchFields).not.toHaveProperty('uris')+ expect(dispatchFields).not.toHaveProperty('headers')+ expect(dispatchFields).not.toHaveProperty('proxy')+ expect(dispatchFields).not.toHaveProperty('extraEngineOptions')const taskPayload = lastAddedTask(deps).instances[0]?.payloadexpect(taskPayload).toEqual({@@ -552,6 +571,132 @@ describe('handleCreateTask', () => {})})+ it('passes the effective engine User-Agent to metadata discovery', async () => {+ const deps = makeDeps({ engineUserAgent: 'Motrix/Test' })+ const probe = vi.fn(async () => {+ vi.spyOn(deps.settingsManager, 'getEngine').mockReturnValue({+ ...DEFAULT_ENGINE_SETTINGS,+ userAgent: 'Motrix/Newer',+ })+ return { filename: null, validator: null }+ })+ deps.directResourceValidator = { capture: vi.fn(), probe }++ await handleCreateTask(+ {+ type: 'http',+ uris: ['https://example.com/stable'],+ saveDir: '/d',+ headers: [],+ },+ deps+ )++ expect(probe).toHaveBeenCalledWith('https://example.com/stable', {+ userAgent: 'Motrix/Test',+ })+ expect(deps.addUri).toHaveBeenCalledWith(+ ['https://example.com/stable'],+ expect.objectContaining({ 'user-agent': 'Motrix/Test' })+ )+ })++ it('skips metadata when a concrete aria2 lacks mirrored header features', async () => {+ const deps = makeDeps({+ engineFeatureReport: {+ version: '1.37.0',+ features: ['GZip'],+ hasSqlitePersistence: false,+ hasBtSeedUnverified: false,+ hasBtSaveMetadata: false,+ hasMoveStorage: false,+ },+ })+ const probe = vi.fn()+ const capture = vi.fn()+ deps.directResourceValidator = { probe, capture }++ await handleCreateTask(+ {+ type: 'http',+ uris: ['https://example.com/stable'],+ saveDir: '/d',+ headers: [],+ },+ deps+ )++ expect(probe).not.toHaveBeenCalled()+ expect(capture).not.toHaveBeenCalled()+ expect(deps.addUri).toHaveBeenCalledOnce()+ })++ it('preserves unsafe ambient aria2 behavior and records it as non-replayable', async () => {+ const deps = makeDeps()+ ;(deps.adapter as Aria2Adapter).setDirectResourceMetadataProfile(null)+ const probe = vi.fn()+ const capture = vi.fn()+ deps.directResourceValidator = { probe, capture }++ await handleCreateTask(httpRequest(), deps)++ expect(probe).not.toHaveBeenCalled()+ expect(capture).not.toHaveBeenCalled()+ expect(lastAddedTask(deps).instances[0]?.payload).toEqual({+ directReplay: {+ version: 1,+ requestModifiers: ['engineGlobalOptions'],+ replayability: 'requires-credentials',+ },+ })+ const options = deps.addUri.mock.calls[0]?.[1]+ expect(options?.header).toEqual(['Accept: */*'])+ expect(options).not.toHaveProperty('no-netrc')+ })++ it('skips metadata when passthrough engine options change HTTP semantics', async () => {+ const deps = makeDeps()+ const probe = vi.fn()+ const capture = vi.fn()+ deps.directResourceValidator = { capture, probe }++ await handleCreateTask(+ {+ type: 'http',+ uris: ['https://example.com/stable'],+ saveDir: '/d',+ headers: [],+ },+ deps,+ { extraEngineOptions: { referer: 'https://origin.example/' } }+ )++ expect(probe).not.toHaveBeenCalled()+ expect(capture).not.toHaveBeenCalled()+ expect(deps.addUri).toHaveBeenCalledOnce()+ })++ it('skips metadata when a task header cannot be represented by Fetch', async () => {+ const deps = makeDeps()+ const probe = vi.fn()+ const capture = vi.fn()+ deps.directResourceValidator = { capture, probe }++ await handleCreateTask(+ {+ type: 'http',+ uris: ['https://example.com/stable'],+ saveDir: '/d',+ headers: [{ name: 'Host', value: 'other.example' }],+ },+ deps+ )++ expect(probe).not.toHaveBeenCalled()+ expect(capture).not.toHaveBeenCalled()+ expect(deps.addUri).toHaveBeenCalledOnce()+ })+it('does not probe a direct request that depends on credentials', async () => {const deps = makeDeps()const capture = vi.fn()@@ -981,6 +1126,7 @@ describe('handleCreateTask with incomplete-suffix', () => {{headers: { 'User-Agent': 'Motrix test' },proxy: 'http://proxy.example:8080',+ noProxy: 'localhost',})expect(deps.pick).toHaveBeenCalledWith(@@ -1000,6 +1146,184 @@ describe('handleCreateTask with incomplete-suffix', () => {expect(capture).not.toHaveBeenCalled()})+ it('HTTP task: rejects an explicit SOCKS proxy before metadata or durable intent', async () => {+ const deps = makeDeps()+ const probe = vi.fn()+ const capture = vi.fn()+ deps.directResourceValidator = { capture, probe }++ await expect(+ handleCreateTask(+ {+ type: 'http',+ uris: ['https://downloads.example/stable'],+ saveDir: '/d',+ headers: [{ name: 'Authorization', value: 'Bearer secret' }],+ proxy: 'socks5://proxy.example:1080',+ },+ deps+ )+ ).rejects.toThrow('Task proxy must use aria2-compatible HTTP or HTTPS')++ expect(probe).not.toHaveBeenCalled()+ expect(capture).not.toHaveBeenCalled()+ expect(deps.addUri).not.toHaveBeenCalled()+ expect(deps.reserveEngineTaskId).not.toHaveBeenCalled()+ })++ it('HTTP task: downloads through legacy IPv4 proxy syntax without metadata I/O', async () => {+ const deps = makeDeps()+ const probe = vi.fn()+ const capture = vi.fn()+ deps.directResourceValidator = { capture, probe }++ await handleCreateTask(+ {+ type: 'http',+ uris: ['https://downloads.example/stable'],+ saveDir: '/d',+ headers: [],+ proxy: 'http://user:[email protected]:8080',+ },+ deps+ )++ expect(probe).not.toHaveBeenCalled()+ expect(capture).not.toHaveBeenCalled()+ expect(deps.addUri).toHaveBeenCalledWith(+ ['https://downloads.example/stable'],+ expect.objectContaining({+ 'all-proxy': 'http://127.1:8080',+ 'all-proxy-user': 'user',+ 'all-proxy-passwd': 'pass',+ })+ )+ })++ it('HTTP task: never probes through malformed task proxy syntax', async () => {+ const deps = makeDeps()+ const probe = vi.fn()+ const capture = vi.fn()+ deps.directResourceValidator = { capture, probe }++ await expect(+ handleCreateTask(+ {+ type: 'http',+ uris: ['https://downloads.example/stable'],+ saveDir: '/d',+ headers: [{ name: 'Authorization', value: 'Bearer secret' }],+ proxy: 'http://proxy.example:8080/not-an-authority',+ },+ deps+ )+ ).rejects.toThrow('Task proxy must use aria2-compatible HTTP or HTTPS')++ expect(probe).not.toHaveBeenCalled()+ expect(capture).not.toHaveBeenCalled()+ expect(deps.addUri).not.toHaveBeenCalled()+ expect(deps.reserveEngineTaskId).not.toHaveBeenCalled()+ })++ it('HTTP task: rejects control characters decoded from proxy credentials before metadata or durable intent', async () => {+ const deps = makeDeps()+ const probe = vi.fn()+ const capture = vi.fn()+ deps.directResourceValidator = { capture, probe }++ await expect(+ handleCreateTask(+ {+ type: 'http',+ uris: ['https://downloads.example/stable'],+ saveDir: '/d',+ headers: [],+ proxy:+ 'http://user%0Ahttp-proxy%3Dhttp%3A%2F%2Fevil:[email protected]:8080',+ },+ deps+ )+ ).rejects.toThrow('Task proxy must use aria2-compatible HTTP or HTTPS')++ expect(probe).not.toHaveBeenCalled()+ expect(capture).not.toHaveBeenCalled()+ expect(deps.addUri).not.toHaveBeenCalled()+ expect(deps.reserveEngineTaskId).not.toHaveBeenCalled()+ })++ it('HTTP task: skips metadata when the applied route is unavailable even with an explicit proxy', async () => {+ const deps = makeDeps({ appliedProxySnapshot: null })+ const probe = vi.fn()+ const capture = vi.fn()+ deps.directResourceValidator = { capture, probe }++ await handleCreateTask(+ {+ type: 'http',+ uris: ['https://downloads.example/stable'],+ saveDir: '/d',+ headers: [{ name: 'Authorization', value: 'Bearer secret' }],+ proxy: 'http://task-proxy.example:8080',+ },+ deps+ )++ expect(probe).not.toHaveBeenCalled()+ expect(capture).not.toHaveBeenCalled()+ expect(deps.addUri).toHaveBeenCalledOnce()+ })++ it('HTTP task: uses the applied snapshot instead of newer settings for metadata', async () => {+ const deps = makeDeps({+ proxySettings: {+ ...DEFAULT_PROXY_SETTINGS,+ enabled: true,+ host: 'new-unapplied.example',+ port: 9000,+ scopes: { ...DEFAULT_PROXY_SETTINGS.scopes, download: true },+ },+ appliedProxySnapshot: {+ proxy: 'http://old-applied.example:8080',+ noProxy: '.internal',+ },+ })+ const capture = vi.fn().mockResolvedValue(null)+ deps.directResourceValidator = { capture }++ await handleCreateTask(httpRequest(), deps)++ expect(capture).toHaveBeenCalledWith('https://a/b', {+ proxy: 'http://old-applied.example:8080',+ noProxy: '.internal',+ })+ })++ it('HTTP task: aborts before addUri when restart invalidates its metadata lease', async () => {+ const deps = makeDeps()+ let finishCapture: (() => void) | undefined+ const captureGate = new Promise<void>((resolve) => {+ finishCapture = resolve+ })+ const capture = vi.fn(async () => {+ await captureGate+ return null+ })+ deps.directResourceValidator = { capture }+ deps.assertEngineReady = vi.fn()++ const creating = handleCreateTask(httpRequest(), deps)+ await vi.waitFor(() => expect(capture).toHaveBeenCalledOnce())+ ;(+ deps.directResourceProxyPolicy as AppliedDownloadProxyPolicy+ ).markUnavailable()+ finishCapture?.()++ await expect(creating).rejects.toThrow(+ 'applied download proxy policy changed'+ )+ expect(deps.addUri).not.toHaveBeenCalled()+ })+it('HTTP task: an explicit filename skips discovery but still captures a URI-only validator once', async () => {const deps = makeDeps({proxySettings: {@@ -1049,6 +1373,11 @@ describe('handleCreateTask with incomplete-suffix', () => {version: 1,requestModifiers: [],replayability: 'uri-only',+ resourceValidator: {+ kind: 'strong-etag',+ value: '"proxied-release"',+ capturedAt: 9,+ },},})})@@ -1167,7 +1496,7 @@ describe('handleCreateTask with incomplete-suffix', () => {})})- it('HTTP task: follows the global download proxy and does not persist its validator for direct recovery', async () => {+ it('HTTP task: persists a validator observed through the global download proxy without proxy credentials', async () => {const deps = makeDeps({proxySettings: {...DEFAULT_PROXY_SETTINGS,@@ -1206,13 +1535,22 @@ describe('handleCreateTask with incomplete-suffix', () => {noProxy: 'localhost,*.internal',})expect(capture).not.toHaveBeenCalled()- expect(lastAddedTask(deps).instances[0]?.payload).toEqual({+ const payload = lastAddedTask(deps).instances[0]?.payload+ expect(payload).toEqual({directReplay: {version: 1,requestModifiers: [],replayability: 'uri-only',+ resourceValidator: {+ kind: 'strong-etag',+ value: '"proxied-release"',+ capturedAt: 8,+ },},})+ expect(JSON.stringify(payload)).not.toContain('proxy-user')+ expect(JSON.stringify(payload)).not.toContain('proxy-pass')+ expect(JSON.stringify(payload)).not.toContain('proxy.example')})it('HTTP task: metadata failure logs no signed URL or credential value', async () => {@@ -1755,7 +2093,13 @@ describe('handleCreateTask plugin-hook chain (Plan C / T15)', () => {expect(orchestrator?.runBeforeCreateHttp).toHaveBeenCalledOnce()const [, options] = deps.addUri.mock.calls[0]expect(deps.addUri.mock.calls[0][0]).toEqual(['https://cdn.example/b'])- expect(options.header).toEqual(['X-Plugin: on', 'User-Agent: rewritten'])+ expect(options.header).toEqual([+ 'X-Plugin: on',+ 'User-Agent: rewritten',+ 'Cookie: ',+ 'Authorization: ',+ 'Accept: */*',+ ])expect(options['all-proxy']).toBe('http://proxy.example:1080')expect(options.out).toBe('rewritten-release.exe.motrix')expect(probe).toHaveBeenCalledWith('https://cdn.example/b', {@@ -1774,6 +2118,31 @@ describe('handleCreateTask plugin-hook chain (Plan C / T15)', () => {)})+ it('rejects a plugin-rewritten SOCKS proxy before metadata or durable intent', async () => {+ const orchestrator = makeOrchestrator(+ makeChainCommit({+ proxy: 'socks5://proxy.example:1080',+ proxyContributor: 'plugin-a',+ })+ )+ const deps = makeDeps()+ const probe = vi.fn()+ const capture = vi.fn()++ await expect(+ handleCreateTask(httpRequest(), {+ ...deps,+ orchestrator,+ directResourceValidator: { capture, probe },+ })+ ).rejects.toThrow('Task proxy must use aria2-compatible HTTP or HTTPS')++ expect(probe).not.toHaveBeenCalled()+ expect(capture).not.toHaveBeenCalled()+ expect(deps.addUri).not.toHaveBeenCalled()+ expect(deps.reserveEngineTaskId).not.toHaveBeenCalled()+ })+it('commits staged metadata inside the same transaction as task add', async () => {const staged = makeStaged()const orchestrator = makeOrchestrator(@@ -1922,6 +2291,31 @@ describe('handleCreateTask engine-ready gate', () => {expect(order).toEqual(['gate', 'adapter'])})+ it('waits for HTTP readiness before acquiring the applied-proxy lease', async () => {+ const order: string[] = []+ const deps = makeDeps({+ waitForEngineReady: async () => {+ order.push('gate')+ },+ })+ const policy = deps.directResourceProxyPolicy+ deps.directResourceProxyPolicy = {+ snapshot: () => policy.snapshot(),+ runWithSnapshot: (operation) => {+ order.push('reader')+ return policy.runWithSnapshot(operation)+ },+ }+ deps.addUri.mockImplementation(async (_uris, options) => {+ order.push('adapter')+ return String(options.gid)+ })++ await handleCreateTask(httpRequest(), deps)++ expect(order).toEqual(['gate', 'reader', 'adapter'])+ })+it('throws and does NOT call the adapter when the gate rejects', async () => {const waitForEngineReady = vi.fn(async () => {throw new AppError(diff --git a/src/core/task/create-task-handler.ts b/src/core/task/create-task-handler.tsindex 16f78d3a..0ebaaabf 100644--- a/src/core/task/create-task-handler.ts+++ b/src/core/task/create-task-handler.ts@@ -9,12 +9,23 @@ import {import type {AddTorrentParams,CreateDownloadParams,+ DirectResourceMetadataProfile,EngineAdapter,} from '@core/engine/engine-adapter'+import { DIRECT_RESOURCE_METADATA_PROFILE } from '@core/engine/engine-adapter'import { newEngineTaskId, newTaskId } from '@core/lib/ids'import { getLogger } from '@core/logger'import type { HookAuditLog } from '@core/plugin/hooks/audit-log'import type { HookOrchestrator } from '@core/plugin/hooks/hook-orchestrator'+import type {+ AppliedDownloadProxyPolicyReader,+ AppliedDownloadProxySnapshot,+} from '@core/proxy/applied-download-proxy-policy'+import {+ extractAria2ProxyCredentials,+ normalizeAria2TaskProxyUrl,+ normalizeProxyUrl,+} from '@core/proxy/aria2-proxy-routing'import type { SettingsManager } from '@core/settings/settings-manager'import { INCOMPLETE_SUFFIX } from '@shared/constants/incomplete'import { AppError, ErrorCode } from '@shared/errors'@@ -24,7 +35,6 @@ import type {} from '@shared/schemas/add-task'import { taskCreateRequestSchema } from '@shared/schemas/add-task'import type { BeforeCreateHttpContextDTO } from '@shared/types/plugin-hooks'-import type { ProxySettings } from '@shared/types/settings'import type {DownloadTask,SourceMeta,@@ -65,6 +75,8 @@ import {type DirectReplayRecipe,} from './direct-replay-recipe'import {+ canMirrorAria2MetadataHeaders,+ canRepresentDirectResourceHeaders,type DirectResourceMetadata,type DirectResourceRequestOptions,type DirectResourceValidatorService,@@ -83,11 +95,6 @@ type CreateDirectResourceValidator = Pick<> &Partial<Pick<DirectResourceValidatorService, 'probe'>>-interface DirectResourceRequestContext {- options: DirectResourceRequestOptions- usesGlobalProxy: boolean-}-export interface CreateTaskDeps {adapter: EngineAdaptersettingsManager: SettingsManager@@ -98,6 +105,11 @@ export interface CreateTaskDeps {eventBus: { emit(event: string, payload: unknown): void }/** Optional best-effort capture of a non-secret HTTP resource validator. */directResourceValidator?: CreateDirectResourceValidator+ /**+ * Holds the engine's applied proxy generation stable from metadata discovery+ * through the matching aria2 addUri dispatch.+ */+ directResourceProxyPolicy: AppliedDownloadProxyPolicyReader/*** Coalesced TaskUpdated publication (TaskUpdatePublisher.publish). Both* create-side broadcasts are non-terminal (announce a new owned task /@@ -113,6 +125,12 @@ export interface CreateTaskDeps {* adapter call so a cold-start request waits for aria2 instead of hitting* a not-yet-connected RPC socket. Absent ⇒ no gate (back-compat / tests). */waitForEngineReady?: () => Promise<void>+ /**+ * Synchronous readiness check used while an applied-proxy read lease is+ * held. It must not wait for a restart: a restarted engine belongs to a new+ * applied-proxy generation and the current admission must fail closed.+ */+ assertEngineReady?: () => void/*** Host-owned save-directory preflight. Server injects containment and* writability enforcement; Electron may omit it because its native picker@@ -205,6 +223,29 @@ export async function handleCreateTask(opts: CreateTaskOptions = {}): Promise<TaskCreateSuccessResult> {const parsed = taskCreateRequestSchema.safeParse(rawRequest)+ if (parsed.success && parsed.data.type === 'http') {+ 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 on+ // a restart that belongs to a newer applied-route generation.+ if (deps.waitForEngineReady) {+ await deps.waitForEngineReady()+ }+ // Keep a runtime guard for untyped composition code: missing policy+ // injection must disable metadata I/O instead of consulting newer,+ // potentially unapplied SettingsManager values.+ return policy+ ? policy.runWithSnapshot((snapshot, lease) =>+ handleCreateTaskUnderAdmission(+ rawRequest,+ deps,+ opts,+ snapshot,+ lease.assertCurrent+ )+ )+ : handleCreateTaskUnderAdmission(rawRequest, deps, opts, null)+ }if (!parsed.success || parsed.data.type !== 'bt') {return handleCreateTaskUnderAdmission(rawRequest, deps, opts)}@@ -235,7 +276,9 @@ export async function handleCreateTask(async function handleCreateTaskUnderAdmission(rawRequest: unknown,deps: CreateTaskDeps,- opts: CreateTaskOptions = {}+ opts: CreateTaskOptions = {},+ appliedProxySnapshot?: AppliedDownloadProxySnapshot,+ assertAppliedProxyCurrent?: () => void): Promise<TaskCreateSuccessResult> {const parsed = taskCreateRequestSchema.safeParse(rawRequest)if (!parsed.success) {@@ -426,7 +469,9 @@ async function handleCreateTaskUnderAdmission(let canonicalUris = deriveUris(req)let resourceMetadata: DirectResourceMetadata | null = nulllet resourceProbeAttempted = false- let resourceProbeUsedGlobalProxy = false+ const metadataHeadersSupported = canMirrorAria2MetadataHeaders(+ deps.adapter.getFeatureReport?.()+ )// Shared by the HTTP and magnet branches — both dispatch through// createDownload with an identical log line; only their params differ.const dispatchCreateDownload =@@ -434,7 +479,14 @@ async function handleCreateTaskUnderAdmission(async (reservedGid: string): Promise<string> => {params.gid = reservedGidlog.info(- { method: 'createDownload', uriCount: params.uris.length, params },+ {+ method: 'createDownload',+ uriCount: params.uris.length,+ gid: reservedGid,+ saveDir: params.saveDir,+ filename: params.filename,+ connections: params.connections,+ },'dispatching to engine')return deps.adapter.createDownload(params)@@ -456,6 +508,7 @@ async function handleCreateTaskUnderAdmission(saveDir: effectiveSaveDir,filename: `${finalName}${INCOMPLETE_SUFFIX}`,performanceProfile: engineSettings.performanceProfile,+ userAgent: engineSettings.userAgent,connections: clampedConnections,headers: headersRecord,proxy: req.proxy,@@ -631,6 +684,19 @@ async function handleCreateTaskUnderAdmission(}}+ assertSupportedHttpTaskProxy(params.proxy)++ const ambientMetadataProfile = metadataHeadersSupported+ ? resolveDirectResourceMetadataProfile(deps.adapter)+ : null+ const metadataRequestProfile = canApplyDirectResourceMetadataProfile(+ params,+ ambientMetadataProfile+ )+ if (metadataRequestProfile) {+ params.directResourceMetadataProfile = metadataRequestProfile+ }+// The hook may replace the source URI. Rebase the non-explicit fallback// name onto that final URI before probing, so a failed/empty metadata// response cannot resurrect the original request's basename.@@ -645,6 +711,7 @@ async function handleCreateTaskUnderAdmission(if (!req.filename?.trim() &¶ms.uris.length === 1 &&+ metadataRequestProfile !== null &&deps.directResourceValidator?.probe) {const uri = params.uris[0]@@ -653,13 +720,11 @@ async function handleCreateTaskUnderAdmission(try {const requestContext = directResourceRequestContext(params,- deps.settingsManager- )- resourceProbeUsedGlobalProxy = requestContext.usesGlobalProxy- resourceMetadata = await deps.directResourceValidator.probe(- uri,- requestContext.options+ appliedProxySnapshot ?? null)+ resourceMetadata = requestContext+ ? await deps.directResourceValidator.probe(uri, requestContext)+ : nullconst remoteName = resourceMetadata?.filename? sanitizeRemoteFilename(resourceMetadata.filename): null@@ -679,9 +744,13 @@ async function handleCreateTaskUnderAdmission(// future retry can be reconstructed from TaskInstance. Paths and URIs are// already canonical fields on the instance; modifier VALUES remain// engine-call-only so credentials never enter motrix.db.- directReplay = buildDirectReplayRecipe(params)+ directReplay = buildDirectReplayRecipe(+ params,+ ambientMetadataProfile === null+ )if (directReplay.replayability === 'uri-only' &&+ metadataRequestProfile !== null &&deps.directResourceValidator &¶ms.uris.length === 1) {@@ -689,21 +758,14 @@ async function handleCreateTaskUnderAdmission(const uri = params.uris[0] as stringconst requestContext = directResourceRequestContext(params,- deps.settingsManager+ appliedProxySnapshot ?? null)const resourceValidator = resourceProbeAttempted? resourceMetadata?.validator- : await deps.directResourceValidator.capture(- uri,- requestContext.options- )- // SessionManager.verify currently has no proxy context. Persisting a- // validator observed through the global proxy would make recovery- // verify the same URI by a different (direct) route.- const validatorUsedGlobalProxy = resourceProbeAttempted- ? resourceProbeUsedGlobalProxy- : requestContext.usesGlobalProxy- if (resourceValidator && !validatorUsedGlobalProxy) {+ : requestContext+ ? await deps.directResourceValidator.capture(uri, requestContext)+ : null+ if (resourceValidator) {directReplay = { ...directReplay, resourceValidator }}} catch (error) {@@ -790,7 +852,10 @@ async function handleCreateTaskUnderAdmission(// Resolve readiness before publishing a durable create intent. A rejected// cold-start gate must not leave a queued task that was never dispatched.- if (deps.waitForEngineReady) {+ if (req.type === 'http') {+ assertAppliedProxyCurrent?.()+ deps.assertEngineReady?.()+ } else if (deps.waitForEngineReady) {await deps.waitForEngineReady()}@@ -919,6 +984,10 @@ async function handleCreateTaskUnderAdmission(deps.taskManager.setReservedEngineTaskOwner(task.id, task, gid)try {+ if (req.type === 'http') {+ deps.assertEngineReady?.()+ assertAppliedProxyCurrent?.()+ }const actualGid = await dispatchEngine(gid)if (actualGid.toLowerCase() !== gid.toLowerCase()) {throw new Error(@@ -1025,36 +1094,108 @@ function deriveDesiredName(}function directResourceRequestContext(- params: Pick<CreateDownloadParams, 'headers' | 'proxy'>,- settingsManager: SettingsManager-): DirectResourceRequestContext {+ params: Pick<+ CreateDownloadParams,+ | 'headers'+ | 'proxy'+ | 'extraEngineOptions'+ | 'userAgent'+ | 'directResourceMetadataProfile'+ >,+ appliedProxySnapshot: AppliedDownloadProxySnapshot+): DirectResourceRequestOptions | null {+ // Passthrough engine options can add cookies, a referer, headers, or other+ // request semantics the metadata client cannot reconstruct safely.+ if (+ (params.extraEngineOptions &&+ Object.keys(params.extraEngineOptions).length > 0) ||+ params.directResourceMetadataProfile !== DIRECT_RESOURCE_METADATA_PROFILE ||+ !canRepresentDirectResourceHeaders(params.headers)+ ) {+ return null+ }const options: DirectResourceRequestOptions = {}if (params.headers) options.headers = params.headers+ if (params.userAgent !== undefined) options.userAgent = params.userAgent+ if (appliedProxySnapshot === null) return null+ const globalProxy = appliedProxySnapshotconst explicitProxy = params.proxy?.trim()if (explicitProxy) {+ // aria2's task-level all-proxy accepts HTTP proxy syntax only. In+ // particular, probing through Undici's SOCKS agent before aria2 rejects+ // the task would expose request headers to a route the download never+ // uses. Invalid or SOCKS task proxies therefore disable metadata I/O.+ const metadataProxy = normalizeProxyUrl(explicitProxy)+ if (!metadataProxy || metadataProxy.protocol === 'socks5:') return nulloptions.proxy = explicitProxy- return { options, usesGlobalProxy: false }+ // aria2's task-level all-proxy overrides only the proxy endpoint. Its+ // global no-proxy list still applies, so metadata discovery must inherit+ // the same bypass decision or it could send task headers to a proxy while+ // the actual download connects directly.+ if (globalProxy.noProxy) {+ options.noProxy = globalProxy.noProxy+ }+ return options}- const globalProxy = settingsManager.getProxy()- if (globalProxy.enabled && globalProxy.scopes.download) {- options.proxy = proxySettingsToUrl(globalProxy)- options.noProxy = globalProxy.bypass.join(',')- return { options, usesGlobalProxy: true }+ if (globalProxy.proxy) options.proxy = globalProxy.proxy+ if (globalProxy.noProxy) options.noProxy = globalProxy.noProxy+ return options+}++function resolveDirectResourceMetadataProfile(+ adapter: EngineAdapter+): DirectResourceMetadataProfile | null {+ if (!adapter.getDirectResourceMetadataProfile) return null+ try {+ return adapter.getDirectResourceMetadataProfile()+ } catch {+ return null}- return { options, usesGlobalProxy: false }}-function proxySettingsToUrl(proxy: ProxySettings): string {- const auth = proxy.user- ? `${encodeURIComponent(proxy.user)}:${encodeURIComponent(proxy.password)}@`- : ''- const host =- proxy.host.includes(':') && !proxy.host.startsWith('[')- ? `[${proxy.host}]`- : proxy.host- return `${proxy.protocol}://${auth}${host}:${proxy.port}`+function canApplyDirectResourceMetadataProfile(+ params: Pick<CreateDownloadParams, 'uris' | 'extraEngineOptions'>,+ profile: DirectResourceMetadataProfile | null+): DirectResourceMetadataProfile | null {+ if (+ profile === null ||+ (params.extraEngineOptions &&+ Object.keys(params.extraEngineOptions).length > 0) ||+ !params.uris.every(isCredentialFreeHttpUri)+ ) {+ return null+ }+ return profile+}++function isCredentialFreeHttpUri(uri: string): boolean {+ try {+ const parsed = new URL(uri)+ return (+ (parsed.protocol === 'http:' || parsed.protocol === 'https:') &&+ parsed.username === '' &&+ parsed.password === ''+ )+ } catch {+ return false+ }+}++function assertSupportedHttpTaskProxy(proxy: string | undefined): void {+ const value = proxy?.trim()+ if (+ !value ||+ (normalizeAria2TaskProxyUrl(value) &&+ extractAria2ProxyCredentials(value) !== null)+ ) {+ return+ }+ throw new AppError(+ ErrorCode.TaskCreateFailed,+ 'Task proxy must use aria2-compatible HTTP or HTTPS syntax; configure SOCKS5 as the global download proxy instead'+ )}function uriBasename(uri: string | undefined): string | null {diff --git a/src/core/task/direct-replay-recipe.test.ts b/src/core/task/direct-replay-recipe.test.tsindex 843954ba..75839fbd 100644--- a/src/core/task/direct-replay-recipe.test.ts+++ b/src/core/task/direct-replay-recipe.test.ts@@ -15,6 +15,14 @@ describe('direct replay recipe', () => {expect(parseDirectReplayRecipe({ directReplay: recipe })).toEqual(recipe)})+ it('treats a whitespace-only proxy as no request modifier', () => {+ expect(buildDirectReplayRecipe({ proxy: ' \t ' })).toEqual({+ version: 1,+ requestModifiers: [],+ replayability: 'uri-only',+ })+ })+it('records only modifier categories and never their sensitive values', () => {const secrets = ['Bearer AUTH_SECRET',@@ -40,6 +48,14 @@ describe('direct replay recipe', () => {for (const secret of secrets) expect(serialized).not.toContain(secret)})+ it('records an unsafe ambient engine profile without persisting its values', () => {+ expect(buildDirectReplayRecipe({}, true)).toEqual({+ version: 1,+ requestModifiers: ['engineGlobalOptions'],+ replayability: 'requires-credentials',+ })+ })+it('accepts a bounded non-secret resource validator on a uri-only recipe', () => {const recipe = {...buildDirectReplayRecipe({ connections: 4 }),diff --git a/src/core/task/direct-replay-recipe.ts b/src/core/task/direct-replay-recipe.tsindex 525db773..9dd5b92b 100644--- a/src/core/task/direct-replay-recipe.ts+++ b/src/core/task/direct-replay-recipe.ts@@ -15,7 +15,8 @@ export function buildDirectReplayRecipe(params: Pick<CreateDownloadParams,'connections' | 'headers' | 'proxy' | 'extraEngineOptions'- >+ >,+ ambientEngineRequestOptions = false): DirectReplayRecipe {const requestModifiers: DirectReplayRequestModifier[] = []@@ -24,6 +25,9 @@ export function buildDirectReplayRecipe(if (hasEntries(params.extraEngineOptions)) {requestModifiers.push('extraEngineOptions')}+ if (ambientEngineRequestOptions) {+ requestModifiers.push('engineGlobalOptions')+ }return {version: 1,@@ -41,5 +45,5 @@ function hasEntries(value: object | undefined): boolean {}function hasText(value: string | undefined): boolean {- return value !== undefined && value.length > 0+ return value !== undefined && value.trim().length > 0}diff --git a/src/core/task/direct-resource-validator.proxy-contract.test.ts b/src/core/task/direct-resource-validator.proxy-contract.test.tsnew file mode 100644index 00000000..3f5b942b--- /dev/null+++ b/src/core/task/direct-resource-validator.proxy-contract.test.ts@@ -0,0 +1,594 @@+// @vitest-environment node++import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'++const undiciMock = vi.hoisted(() => {+ const agents: Array<{+ kind: 'direct' | 'http' | 'socks5'+ options: unknown+ destroy: ReturnType<typeof vi.fn>+ }> = []++ class Agent {+ readonly kind = 'direct' as const+ readonly options = undefined+ readonly destroy = vi.fn(async () => undefined)++ constructor() {+ agents.push(this)+ }+ }++ class ProxyAgent {+ readonly kind = 'http' as const+ readonly destroy = vi.fn(async () => undefined)++ constructor(readonly options: unknown) {+ agents.push(this)+ }+ }++ class Socks5ProxyAgent {+ readonly kind = 'socks5' as const+ readonly destroy = vi.fn(async () => undefined)++ constructor(+ readonly options: URL,+ readonly config?: unknown+ ) {+ agents.push(this)+ }+ }++ const connector = vi.fn()++ return {+ agents,+ fetch: vi.fn(),+ Agent,+ ProxyAgent,+ Socks5ProxyAgent,+ connector,+ buildConnector: vi.fn(() => connector),+ }+})++vi.mock('undici', () => ({+ fetch: undiciMock.fetch,+ request: undiciMock.fetch,+ Agent: undiciMock.Agent,+ ProxyAgent: undiciMock.ProxyAgent,+ Socks5ProxyAgent: undiciMock.Socks5ProxyAgent,+ buildConnector: undiciMock.buildConnector,+}))++import { DirectResourceValidatorService } from './direct-resource-validator'++describe('DirectResourceValidatorService proxy client contract', () => {+ beforeEach(() => {+ vi.restoreAllMocks()+ undiciMock.agents.length = 0+ undiciMock.connector.mockReset()+ undiciMock.buildConnector.mockClear()+ undiciMock.fetch.mockReset()+ undiciMock.fetch.mockResolvedValue(+ new Response(null, {+ status: 200,+ headers: {+ 'Content-Disposition': 'attachment; filename="release.zip"',+ },+ })+ )+ })++ afterEach(() => {+ vi.restoreAllMocks()+ })++ it('binds an HTTP proxy agent to fetch from the same Undici module', async () => {+ const globalFetch = vi+ .spyOn(globalThis, 'fetch')+ .mockRejectedValue(+ new Error('global fetch must not receive a dispatcher')+ )+ const service = new DirectResourceValidatorService()++ await expect(+ service.probe('https://downloads.example/latest', {+ proxy: 'http://proxy.example:8080',+ noProxy: 'localhost,*.internal',+ })+ ).resolves.toEqual({ filename: 'release.zip', validator: null })++ expect(globalFetch).not.toHaveBeenCalled()+ expect(undiciMock.agents).toHaveLength(2)+ const proxyAgent = undiciMock.agents.find((agent) => agent.kind === 'http')+ expect(proxyAgent).toMatchObject({+ kind: 'http',+ options: 'http://proxy.example:8080/',+ })+ expect(undiciMock.fetch).toHaveBeenCalledOnce()+ expect(undiciMock.fetch.mock.calls[0]?.[1]).toEqual(+ expect.objectContaining({ dispatcher: proxyAgent })+ )+ for (const agent of undiciMock.agents) {+ expect(agent.destroy).toHaveBeenCalledOnce()+ }+ })++ it('routes every redirect hop with aria2-compatible bypass semantics', async () => {+ undiciMock.fetch+ .mockResolvedValueOnce(+ new Response(null, {+ status: 302,+ headers: { Location: 'http://mirror.internal/release' },+ })+ )+ .mockResolvedValueOnce(+ new Response(null, {+ status: 200,+ headers: {+ 'Content-Disposition': 'attachment; filename="release.zip"',+ },+ })+ )+ const service = new DirectResourceValidatorService()++ await expect(+ service.probe('https://downloads.example/latest', {+ proxy: 'proxy.example:8080',+ noProxy: '.internal',+ })+ ).resolves.toEqual({ filename: 'release.zip', validator: null })++ const proxyAgent = undiciMock.agents.find((agent) => agent.kind === 'http')+ const directAgent = undiciMock.agents.find(+ (agent) => agent.kind === 'direct'+ )+ expect(proxyAgent?.options).toBe('http://proxy.example:8080/')+ expect(undiciMock.fetch.mock.calls[0]?.[1]).toEqual(+ expect.objectContaining({ dispatcher: proxyAgent })+ )+ expect(undiciMock.fetch.mock.calls[1]?.[1]).toEqual(+ expect.objectContaining({ dispatcher: directAgent })+ )+ })++ it('preserves authority case when applying aria2 no-proxy rules', async () => {+ const service = new DirectResourceValidatorService()++ await expect(+ service.probe('http://API.Internal/release', {+ proxy: 'proxy.example:8080',+ noProxy: '.internal',+ })+ ).resolves.toEqual({ filename: 'release.zip', validator: null })++ const proxyAgent = undiciMock.agents.find((agent) => agent.kind === 'http')+ expect(undiciMock.fetch).toHaveBeenCalledWith(+ 'http://API.Internal/release',+ expect.objectContaining({ dispatcher: proxyAgent })+ )+ })++ it.each([+ 'http://127.1/release',+ 'http://%6cocalhost/release',+ 'http://localhost:8\t0/release',+ ' http://localhost/release',+ ])(+ 'fails closed for a target WHATWG canonicalizes differently: %s',+ async (target) => {+ const service = new DirectResourceValidatorService()++ await expect(+ service.probe(target, { proxy: 'proxy.example:8080' })+ ).resolves.toBeNull()++ expect(undiciMock.agents).toHaveLength(0)+ expect(undiciMock.fetch).not.toHaveBeenCalled()+ }+ )++ it('fails closed for an uppercase initial scheme that aria2 rejects', async () => {+ const service = new DirectResourceValidatorService()++ await expect(+ service.probe('HTTP://LOCALHOST/release', {+ proxy: 'proxy.example:8080',+ noProxy: 'LOCALHOST',+ })+ ).resolves.toBeNull()++ expect(undiciMock.agents).toHaveLength(0)+ expect(undiciMock.fetch).not.toHaveBeenCalled()+ })++ it('fails closed when WHATWG rewrites an encoded-dot initial path', async () => {+ const service = new DirectResourceValidatorService()++ await expect(+ service.probe('http://downloads.example/safe/%2e%2e/private', {+ proxy: 'proxy.example:8080',+ })+ ).resolves.toBeNull()++ expect(undiciMock.agents).toHaveLength(0)+ expect(undiciMock.fetch).not.toHaveBeenCalled()+ })++ it('does not follow an uppercase redirect scheme that aria2 rejects', async () => {+ undiciMock.fetch.mockResolvedValue(+ new Response(null, {+ status: 302,+ headers: { Location: 'HTTP://LOCALHOST/private' },+ })+ )+ const service = new DirectResourceValidatorService()++ await expect(+ service.probe('https://downloads.example/latest', {+ proxy: 'proxy.example:8080',+ noProxy: 'LOCALHOST',+ })+ ).resolves.toBeNull()++ expect(undiciMock.fetch).toHaveBeenCalledOnce()+ for (const [target] of undiciMock.fetch.mock.calls) {+ expect(target).toBe('https://downloads.example/latest')+ }+ })++ it('rejects a backslash redirect instead of probing WHATWG\u2019s rewritten host', async () => {+ undiciMock.fetch.mockResolvedValue(+ new Response(null, {+ status: 302,+ headers: { Location: 'http:\\\\127.0.0.1/release' },+ })+ )+ const service = new DirectResourceValidatorService()++ await expect(+ service.probe('https://downloads.example/latest', {+ proxy: 'proxy.example:8080',+ })+ ).resolves.toBeNull()++ expect(undiciMock.fetch).toHaveBeenCalledOnce()+ for (const [target] of undiciMock.fetch.mock.calls) {+ expect(target).toBe('https://downloads.example/latest')+ }+ for (const agent of undiciMock.agents) {+ expect(agent.destroy).toHaveBeenCalledOnce()+ }+ })++ it.each([+ '/safe/%2e%2e/private',+ '?download=private',+ '/safe//private',+ '/safe path/private',+ 'http://localhost:8\t0/private',+ '/next^release',+ '/next`release',+ 'next{release',+ 'next}release',+ "next?q=x'y",+ '/next?',+ '/café',+ ])(+ 'does not follow an aria2-divergent redirect reference: %s',+ async (location) => {+ undiciMock.fetch.mockResolvedValue(+ new Response(null, { status: 302, headers: { Location: location } })+ )+ const service = new DirectResourceValidatorService()++ await expect(+ service.probe('https://downloads.example/latest', {+ proxy: 'proxy.example:8080',+ })+ ).resolves.toBeNull()++ expect(undiciMock.fetch).toHaveBeenCalledOnce()+ for (const [target] of undiciMock.fetch.mock.calls) {+ expect(target).toBe('https://downloads.example/latest')+ }+ }+ )++ it.each([304, 305, 306, 309])(+ 'does not follow status %i because aria2 does not treat it as a redirect',+ async (status) => {+ undiciMock.fetch.mockResolvedValue(+ new Response(null, {+ status,+ headers: { Location: 'http://localhost/private' },+ })+ )+ const service = new DirectResourceValidatorService()++ await expect(+ service.probe('https://downloads.example/latest', {+ proxy: 'proxy.example:8080',+ noProxy: 'localhost',+ })+ ).resolves.toBeNull()++ expect(undiciMock.fetch).toHaveBeenCalledOnce()+ expect(undiciMock.fetch.mock.calls[0]?.[0]).toBe(+ 'https://downloads.example/latest'+ )+ }+ )++ it('uses the direct package dispatcher for a SOCKS5 bypass target', async () => {+ const service = new DirectResourceValidatorService()++ await expect(+ service.probe('http://127.22.33.44/release', {+ proxy: 'socks5://proxy.example:1080',+ noProxy: '127.0.0.0/8',+ })+ ).resolves.toEqual({ filename: 'release.zip', validator: null })++ const directAgent = undiciMock.agents.find(+ (agent) => agent.kind === 'direct'+ )+ expect(undiciMock.fetch.mock.calls[0]?.[1]).toEqual(+ expect.objectContaining({ dispatcher: directAgent })+ )+ })++ it('matches aria2 by treating an HTTPS proxy declaration as HTTP', async () => {+ const service = new DirectResourceValidatorService()++ await service.probe('https://downloads.example/latest', {+ proxy: 'https://proxy.example:8443',+ })++ expect(+ undiciMock.agents.find((agent) => agent.kind === 'http')?.options+ ).toBe('http://proxy.example:8443/')+ })++ it('preserves the HTTPS default port when adapting aria2 proxy syntax', async () => {+ const service = new DirectResourceValidatorService()++ await service.probe('https://downloads.example/latest', {+ proxy: 'https://proxy.example',+ })++ expect(+ undiciMock.agents.find((agent) => agent.kind === 'http')?.options+ ).toBe('http://proxy.example:443/')+ })++ it('keeps the metadata GET on the SOCKS5-bound client', async () => {+ const globalFetch = vi+ .spyOn(globalThis, 'fetch')+ .mockRejectedValue(+ new Error('global fetch must not receive a dispatcher')+ )+ undiciMock.fetch.mockResolvedValueOnce(+ new Response(null, {+ status: 200,+ headers: {+ 'Content-Disposition': 'attachment; filename="release.zip"',+ },+ })+ )+ const service = new DirectResourceValidatorService()++ await expect(+ service.probe('https://downloads.example/latest', {+ proxy: 'socks5://proxy.example:1080',+ })+ ).resolves.toEqual({ filename: 'release.zip', validator: null })++ expect(globalFetch).not.toHaveBeenCalled()+ expect(undiciMock.agents).toHaveLength(2)+ const proxyAgent = undiciMock.agents.find(+ (agent) => agent.kind === 'socks5'+ )+ expect(proxyAgent).toMatchObject({+ kind: 'socks5',+ })+ expect(String(proxyAgent?.options)).toBe('socks5://proxy.example:1080')+ expect(undiciMock.fetch).toHaveBeenCalledOnce()+ expect(undiciMock.fetch.mock.calls[0]?.[1]).toEqual(+ expect.objectContaining({+ method: 'GET',+ dispatcher: proxyAgent,+ })+ )+ for (const agent of undiciMock.agents) {+ expect(agent.destroy).toHaveBeenCalledOnce()+ }+ })++ it('unbrackets an IPv6 SOCKS5 proxy endpoint through the public connector seam', async () => {+ const service = new DirectResourceValidatorService()++ await service.probe('https://downloads.example/latest', {+ proxy: 'socks5://[::1]:1080',+ })++ const socksAgent = undiciMock.agents.find(+ (agent) => agent.kind === 'socks5'+ ) as+ | ((typeof undiciMock.agents)[number] & {+ config?: { connect?: (...args: unknown[]) => unknown }+ })+ | undefined+ const connect = socksAgent?.config?.connect+ expect(connect).toBeTypeOf('function')+ const callback = vi.fn()+ connect?.(+ {+ hostname: '[::1]',+ host: '[::1]',+ protocol: 'http:',+ port: '1080',+ },+ callback+ )+ expect(undiciMock.connector).toHaveBeenCalledWith(+ expect.objectContaining({ hostname: '::1', host: '::1' }),+ expect.any(Function)+ )+ const socket = { destroy: vi.fn(), once: vi.fn() }+ const connectorCallback = undiciMock.connector.mock.calls[0]?.[1] as+ | ((error: Error | null, value: typeof socket | null) => void)+ | undefined+ connectorCallback?.(null, socket)+ expect(socket.destroy).toHaveBeenCalledOnce()+ expect(callback).toHaveBeenCalledWith(expect.any(Error), null)+ })++ it('fails closed for an IPv6 target that Undici cannot encode over SOCKS5', async () => {+ const service = new DirectResourceValidatorService()++ await expect(+ service.probe('http://[::1]/release', {+ proxy: 'socks5://proxy.example:1080',+ })+ ).resolves.toBeNull()++ expect(undiciMock.fetch).not.toHaveBeenCalled()+ for (const agent of undiciMock.agents) {+ expect(agent.destroy).toHaveBeenCalledOnce()+ }+ })++ it('captures validators through the proxy-bound client', async () => {+ const globalFetch = vi+ .spyOn(globalThis, 'fetch')+ .mockRejectedValue(+ new Error('global fetch must not receive a dispatcher')+ )+ undiciMock.fetch.mockResolvedValueOnce(+ new Response(null, {+ status: 200,+ headers: {+ ETag: '"proxy-release-v1"',+ 'Content-Length': '4096',+ },+ })+ )+ const service = new DirectResourceValidatorService(undefined, 100, () => 7)++ await expect(+ service.capture('https://downloads.example/release.zip', {+ proxy: 'http://proxy.example:8080',+ })+ ).resolves.toEqual({+ kind: 'strong-etag',+ value: '"proxy-release-v1"',+ contentLength: 4096,+ capturedAt: 7,+ })++ expect(globalFetch).not.toHaveBeenCalled()+ expect(undiciMock.agents).toHaveLength(2)+ const proxyAgent = undiciMock.agents.find((agent) => agent.kind === 'http')+ expect(undiciMock.fetch).toHaveBeenCalledOnce()+ expect(undiciMock.fetch.mock.calls[0]?.[1]).toEqual(+ expect.objectContaining({+ method: 'GET',+ dispatcher: proxyAgent,+ })+ )+ for (const agent of undiciMock.agents) {+ expect(agent.destroy).toHaveBeenCalledOnce()+ }+ })++ it('verifies a Range response through the package proxy client', async () => {+ undiciMock.fetch.mockResolvedValueOnce(+ new Response(null, {+ status: 206,+ headers: {+ ETag: '"proxy-release-v1"',+ 'Content-Range': 'bytes 0-0/4096',+ },+ })+ )+ const service = new DirectResourceValidatorService()++ await expect(+ service.verify(+ 'https://downloads.example/release.zip',+ {+ kind: 'strong-etag',+ value: '"proxy-release-v1"',+ contentLength: 4096,+ capturedAt: 7,+ },+ { proxy: 'http://proxy.example:8080' }+ )+ ).resolves.toEqual({+ outcome: 'unchanged',+ ifRange: '"proxy-release-v1"',+ })++ const proxyAgent = undiciMock.agents.find((agent) => agent.kind === 'http')+ expect(undiciMock.fetch.mock.calls[0]?.[1]).toEqual(+ expect.objectContaining({+ dispatcher: proxyAgent,+ method: 'GET',+ headers: expect.objectContaining({ range: 'bytes=0-0' }),+ })+ )+ for (const agent of undiciMock.agents) {+ expect(agent.destroy).toHaveBeenCalledOnce()+ }+ })++ it('destroys the proxy agent when package fetch fails', async () => {+ const globalFetch = vi+ .spyOn(globalThis, 'fetch')+ .mockRejectedValue(+ new Error('global fetch must not receive a dispatcher')+ )+ undiciMock.fetch.mockRejectedValue(new Error('proxy unavailable'))+ const service = new DirectResourceValidatorService()++ await expect(+ service.probe('https://downloads.example/latest', {+ proxy: 'http://proxy.example:8080',+ })+ ).resolves.toBeNull()++ expect(globalFetch).not.toHaveBeenCalled()+ expect(undiciMock.agents).toHaveLength(2)+ const proxyAgent = undiciMock.agents.find((agent) => agent.kind === 'http')+ expect(undiciMock.fetch).toHaveBeenCalledOnce()+ expect(undiciMock.fetch.mock.calls[0]?.[1]).toEqual(+ expect.objectContaining({ dispatcher: proxyAgent })+ )+ for (const agent of undiciMock.agents) {+ expect(agent.destroy).toHaveBeenCalledOnce()+ }+ })++ it('uses a package-owned direct dispatcher instead of global fetch', async () => {+ const globalFetch = vi+ .spyOn(globalThis, 'fetch')+ .mockRejectedValue(new Error('global fetch must not run'))+ const service = new DirectResourceValidatorService()++ await expect(+ service.probe('https://downloads.example/latest')+ ).resolves.toEqual({ filename: 'release.zip', validator: null })++ expect(globalFetch).not.toHaveBeenCalled()+ expect(undiciMock.agents).toHaveLength(1)+ const directAgent = undiciMock.agents[0]+ expect(directAgent?.kind).toBe('direct')+ expect(undiciMock.fetch.mock.calls[0]?.[1]).toEqual(+ expect.objectContaining({ dispatcher: directAgent, method: 'GET' })+ )+ expect(directAgent?.destroy).toHaveBeenCalledOnce()+ })+})diff --git a/src/core/task/direct-resource-validator.proxy.test.ts b/src/core/task/direct-resource-validator.proxy.test.tsnew file mode 100644index 00000000..40087b3e--- /dev/null+++ b/src/core/task/direct-resource-validator.proxy.test.ts@@ -0,0 +1,760 @@+// @vitest-environment node++import { execFile, spawn } from 'node:child_process'+import {+ existsSync,+ mkdtempSync,+ readFileSync,+ rmSync,+ writeFileSync,+} from 'node:fs'+import {+ createServer,+ type Server as HttpServer,+ type IncomingHttpHeaders,+} from 'node:http'+import { createServer as createHttpsServer } from 'node:https'+import { createRequire } from 'node:module'+import {+ type AddressInfo,+ createServer as createTcpServer,+ type Socket,+ type Server as TcpServer,+} from 'node:net'+import os from 'node:os'+import path from 'node:path'+import { pathToFileURL } from 'node:url'+import { Server as ProxyServer } from 'proxy-chain'+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import { DirectResourceValidatorService } from './direct-resource-validator'++const LOOPBACK_HOST = '127.0.0.1'+const REMOTE_FILENAME = 'VSCodeSetup-x64-proxy-test.exe'+const ELECTRON_RUN_TIMEOUT_MS = 15_000+const SOCKS_STALL_TIMEOUT_MS = 150+const REQUIRE_ELECTRON_RUNTIME =+ process.env.MOTRIX_REQUIRE_ELECTRON_PROXY_TEST === '1'+const bundledAria2Path = path.resolve(+ process.cwd(),+ 'extra',+ process.platform,+ process.arch,+ 'aria2c'+)+const bundledAria2Test = existsSync(bundledAria2Path) ? it : it.skip++// Test-only self-signed certificate for 127.0.0.1. HTTPS verification is+// disabled only in the two child/request scopes that exercise proxy CONNECT.+const TEST_TLS_KEY = `-----BEGIN PRIVATE KEY-----+MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQCzMvQoVep4eh5K++yQsBf6kaWJOj8Pzpr7aBxnoHR5NJeQBpg3h4J5pBSyoNdLKbFV6vSnt8IMLhlU++jTPgx9oPPUjNgijiF+Q+3cx+k+NnJKxxO1vWB7IYkvIHuqVuWwA856Ya/ipZb1o4+xK9oQgEXhsAglTCT7SRJJgJ4a7sM+4acKSvb7zoml0mLwvbFoldt6hOw+TYbAtzo+kSP+SqVUyuO8tndn4ZdFHLQ2SEEUT2lJj29XQHU9qbu1TguFMZEcMIjAGiY6f7be+gTpaC1In9iQq7Gdu6ILNMOe8a1NdjrKy/UqxkB4p3YpvvRwf3uCwRWS3BxBW6HuH+j7A+Y/OxAgMBAAECggEAATOkxoZ4+ZDcFiWkAvWRVRnt0lgNeNtT6VNl3ZQgaWUJ+J+esrSib91lVCNW/kaLzWczd9J4JyvB+Ltq0j9vXPwXqsJIgYw/E9JT5M5obSsxI+qcO7pG5Nx/NoUxvx0xEiKcZl60VsFEh2Yu4SvRDAQB+jtzQ47K0I8sKh/pu+V+Jv+D4F7bWCunhaOM0WVvoFPQ6KQPccoJaRL0EvCykpSUZTzwHmJ1BJL/dFxp+BsABCL+g26gomB72qJhbSCY5owx5F5iLKQUy7EU2QYAIHg+v6tuLpdugZq+JtvMQQnTMI74+dkL8rWWpBsmKRL99qfj27SCHYQCflb04T7CtQ1XO5wKBgQDbrq0FAR7q7tVfmavP+oGU/7TsjXbE8EWs9REAmBU5usiz1ZjGzGNUcCWTs3JhLpssh7hGJgYfLqvFh88tS+CRfCxO5x05uRaOEsI1hovj74KlLLNv84ytC+9i+PP940Lp6fjxK0T0aCxqUruZT0+SDkHKbfo/jQXO011wobSBlzyywKBgQDQ0vUOLlX9ze/DBSVqFAYuivomlp3vq44J+5A306hEehMCveQHSzon4G7gVzGQESfWGkd8iHnZqmLMSsFBS4kU8ZH6kc8WuSfkY+NnFAAYP/LGxjt0hIilGSj65G0PcAFqvppiFgR+EYpr/DmqEST9rqEqpQBIuRgac5+qao+B6PX8wKBgEDlOPdhfWCpbR7wpnCPUVmxGuc3pkO4YZWXs9uHdcP9nopfxg7C+JzJBFC9kexjeDOPZEBUuzo670NK+0jFJvlsrEcVOXYZ3FQ2U42kNykxFNHATrxF3+2HKRBzuqAlon63P3L+9T++BmDiT8jaQcMbyL9mg9r+Ws/xTqgilI9+xBAoGANcD3+/8yBqjGmtEbQ2LuK09RGjERdJ2K7z2P7C75s5bQ6fXDivUcZUNqhykqwvEHlh9xo+2bmJterUvczRAGTqeZ9M0jxS+IhmLItnH5jER51B0XFOlA227ck6jVQhIM61NhHj+qYsXMGdMGafmKnaP3Y0sdiiVXMFJMJiyEAGbdW0CgYBCkkVR3Qa3LhqhgHOPW98n+RAMHTNmhgGOEDq1vzT61ApiW3WlQxwwjTfELY6ynqxRSeXKYVude2iRIT78MJtT4+CLjJyy6J2Gj19g1Wj0DWmoxvTsCu9RKi+O02AVXm/HXV3HhIyfO7ggBbF+MLr+tl+oBhOGFOBD2dWzgKDbyy6hw==+-----END PRIVATE KEY-----`++const TEST_TLS_CERT = `-----BEGIN CERTIFICATE-----+MIIDJTCCAg2gAwIBAgIUF4ztfsfVGCjAspx3wLeWkRvmQ6AwDQYJKoZIhvcNAQEL+BQAwFDESMBAGA1UEAwwJMTI3LjAuMC4xMB4XDTI2MDgyOTAxNDEzNFoXDTM2MDgy+NjAxNDEzNFowFDESMBAGA1UEAwwJMTI3LjAuMC4xMIIBIjANBgkqhkiG9w0BAQEF+AAOCAQ8AMIIBCgKCAQEAszL0KFXqeHoeSvskLAX+pGliTo/D86a+2gcZ6B0eTSXk+AaYN4eCeaQUsqDXSymxVer0p7fCDC4ZVPo0z4MfaDz1IzYIo4hfkPt3MfpPjZySs+cTtb1geyGJLyB7qlblsAPOemGv4qWW9aOMSvaEIBF4bAIJUwk+0kSSYCeGu7DPuG+nCkr2+86JpdJi8L2xaJXbeoTsPk2GwLc6JEj/kqlVMrjvLZ3Z+GXRRy0NkhBFE9p+SY9vV0B1Pam7tU4LhTGRHDCIwBomOn+23oE6WgtSJ/YkKuxnbuiCzTDnvGtTXY6y+sv1KsZAeKd2Kb70cH97gsEVktwcQVuh7h4+wPmPzsQIDAQABo28wbTAdBgNVHQ4E+FgQUvtf3LJ4KQlKUHYglQPJnzriNmXkwHwYDVR0jBBgwFoAUvtf3LJ4KQlKUHYgl+QPJnzriNmXkwDwYDVR0TAQH/BAUwAwEB/zAaBgNVHREEEzARhwR/AAABgglsb2Nh+bGhvc3QwDQYJKoZIhvcNAQELBQADggEBAD91BW2leyuWHz4XVE/kY+KXhyWr189q+76JVkJvXSpe1xxfj05mj5h4tug1ScqoTM9LRN4zfxyO4Sg2VdFx26UnJewFUvMdo+8y2xgNt3E1BZvmFeSVqs4xZBYJN755/K4DGKKyxUNGpMwj2mRTx1+d5+RuEuwQ3h+lXLsEqlkYSRsOePFt1FG7S3lqvvp0FZIhm6OfJSwonFzyLUy4a2N/2UIk75ppjS2+lTv1/xRVw+/pxmhhc+8i/YrbEdtgNk8Q+qBo1HMYXQxiTMm1nNBIWx/A0BNhlSh5+1RW5cFDUfeI1TKinPDbPqqqYkOZQ55kzjk4OrCN+WW4e2+3xayAfOWY=+-----END CERTIFICATE-----`++interface ElectronProbeOutput {+ globalFetchCalls: number+ result: {+ filename: string | null+ validator: {+ kind: string+ value: string+ contentLength?: number+ capturedAt: number+ } | null+ } | null+ runtime: {+ electron: string | null+ embeddedUndici: string | null+ node: string+ }+}++function resolveInstalledElectronPath(): string | null {+ const require = createRequire(import.meta.url)+ const packageDirectory = path.dirname(+ require.resolve('electron/package.json')+ )+ let executableRelativePath: string+ try {+ executableRelativePath = readFileSync(+ path.join(packageDirectory, 'path.txt'),+ 'utf8'+ ).trim()+ } catch {+ return null+ }+ if (!executableRelativePath) return null++ const distDirectory =+ process.env.ELECTRON_OVERRIDE_DIST_PATH ??+ path.join(packageDirectory, 'dist')+ const executablePath = path.join(distDirectory, executableRelativePath)+ return existsSync(executablePath) ? executablePath : null+}++const electronPath = resolveInstalledElectronPath()+if (REQUIRE_ELECTRON_RUNTIME && !electronPath) {+ throw new Error(+ 'Electron proxy compatibility test requires a hydrated Electron runtime'+ )+}+const electronRuntimeTest = electronPath ? it : it.skip++async function listen(server: TcpServer): Promise<number> {+ await new Promise<void>((resolve, reject) => {+ server.once('error', reject)+ server.listen(0, LOOPBACK_HOST, () => {+ server.off('error', reject)+ resolve()+ })+ })+ return (server.address() as AddressInfo).port+}++async function closeTcpServer(+ server: TcpServer | undefined,+ sockets: ReadonlySet<Socket>+): Promise<void> {+ if (!server?.listening) return+ for (const socket of sockets) socket.destroy()+ await new Promise<void>((resolve, reject) => {+ server.close((error) => (error ? reject(error) : resolve()))+ })+}++async function closeServer(server: HttpServer | undefined): Promise<void> {+ if (!server?.listening) return+ await new Promise<void>((resolve, reject) => {+ server.close((error) => (error ? reject(error) : resolve()))+ server.closeAllConnections()+ })+}++function runElectronProbe(+ targetUrl: string,+ proxyUrl: string | null,+ allowSelfSignedTls = false+): Promise<ElectronProbeOutput> {+ if (!electronPath) {+ throw new Error('Electron runtime is unavailable')+ }+ const moduleUrl = pathToFileURL(+ path.resolve(process.cwd(), 'src/core/task/direct-resource-validator.ts')+ ).href+ const script = `+let globalFetchCalls = 0+globalThis.fetch = async () => {+ globalFetchCalls += 1+ throw new Error('embedded global fetch must not receive a package dispatcher')+}+const { DirectResourceValidatorService } = await import(${JSON.stringify(moduleUrl)})+const result = await new DirectResourceValidatorService().probe(+ ${JSON.stringify(targetUrl)},+ ${+ proxyUrl === null+ ? `{ userAgent: 'Motrix/2.0' }`+ : `{ proxy: ${JSON.stringify(proxyUrl)}, noProxy: '', userAgent: 'Motrix/2.0' }`+ },+)+process.stdout.write(JSON.stringify({+ globalFetchCalls,+ result,+ runtime: {+ electron: process.versions.electron ?? null,+ embeddedUndici: process.versions.undici ?? null,+ node: process.versions.node,+ },+}))+`++ return new Promise((resolve, reject) => {+ execFile(+ electronPath,+ ['--import', 'tsx', '--input-type=module', '--eval', script],+ {+ cwd: process.cwd(),+ encoding: 'utf8',+ env: {+ ...process.env,+ ELECTRON_RUN_AS_NODE: '1',+ ...(allowSelfSignedTls ? { NODE_TLS_REJECT_UNAUTHORIZED: '0' } : {}),+ },+ maxBuffer: 1024 * 1024,+ timeout: ELECTRON_RUN_TIMEOUT_MS,+ },+ (error, stdout, stderr) => {+ if (error) {+ reject(+ new Error(+ `Electron proxy probe failed: ${stderr.trim() || error.message}`+ )+ )+ return+ }+ try {+ const line = stdout.trim().split(/\r?\n/u).at(-1)+ if (!line) throw new Error('Electron proxy probe produced no output')+ resolve(JSON.parse(line) as ElectronProbeOutput)+ } catch (parseError) {+ reject(parseError)+ }+ }+ )+ })+}++describe('DirectResourceValidatorService proxy runtime', () => {+ let origin: HttpServer | undefined+ let originUrl = ''+ let proxy: ProxyServer | undefined+ const originRequests: string[] = []+ const originHeaders: IncomingHttpHeaders[] = []+ const proxyRoutes: Array<{+ hostname: string+ isHttp: boolean+ port: number+ }> = []++ beforeEach(async () => {+ originRequests.length = 0+ originHeaders.length = 0+ proxyRoutes.length = 0+ origin = createServer((request, response) => {+ originRequests.push(`${request.method} ${request.url}`)+ originHeaders.push({ ...request.headers })+ if (request.url === '/stable') {+ response.writeHead(302, { Location: '/artifacts/latest' })+ response.end()+ return+ }+ if (request.url === '/artifacts/latest') {+ response.writeHead(200, {+ 'Content-Disposition': `attachment; filename="${REMOTE_FILENAME}"`,+ 'Content-Length': '4096',+ ETag: '"proxy-release-v1"',+ })+ response.end(Buffer.alloc(4096))+ return+ }+ if (request.url === '/verify') {+ if (+ request.headers.range === 'bytes=0-0' &&+ request.headers['if-range'] === '"proxy-release-v1"'+ ) {+ response.writeHead(206, {+ 'Content-Range': 'bytes 0-0/4096',+ 'Content-Length': '1',+ ETag: '"proxy-release-v1"',+ })+ response.end('x')+ return+ }+ response.writeHead(412)+ response.end()+ return+ }+ if (request.url === '/aria2-accept') {+ response.writeHead(200, { 'Content-Length': '1' })+ response.end('x')+ return+ }+ if (request.url === '/cookie-start') {+ response.writeHead(302, {+ Location: '/cookie-final',+ 'Set-Cookie': 'variant=cookie; Path=/',+ })+ response.end()+ return+ }+ if (request.url === '/cookie-final') {+ const hasRedirectCookie =+ request.headers.cookie?.includes('variant=cookie') ?? false+ const body = hasRedirectCookie ? 'cookie-variant' : 'baseline-variant'+ response.writeHead(200, {+ 'Content-Disposition': `attachment; filename="${body}.bin"`,+ 'Content-Length': String(Buffer.byteLength(body)),+ ETag: hasRedirectCookie ? '"cookie-v1"' : '"baseline-v1"',+ })+ response.end(body)+ return+ }+ response.writeHead(404)+ response.end()+ })+ originUrl = `http://${LOOPBACK_HOST}:${await listen(origin)}`++ proxy = new ProxyServer({+ host: LOOPBACK_HOST,+ port: 0,+ prepareRequestFunction: ({ hostname, isHttp, port }) => {+ proxyRoutes.push({ hostname, isHttp, port })+ },+ })+ await proxy.listen()+ })++ afterEach(async () => {+ vi.restoreAllMocks()+ await proxy?.close(true)+ proxy = undefined+ await closeServer(origin)+ origin = undefined+ })++ it('uses the package fetch with its proxy dispatcher across redirects', async () => {+ const globalFetch = vi+ .spyOn(globalThis, 'fetch')+ .mockRejectedValue(+ new Error('embedded global fetch must not receive a package dispatcher')+ )+ const service = new DirectResourceValidatorService()++ await expect(+ service.probe(`${originUrl}/stable`, {+ proxy: `http://${LOOPBACK_HOST}:${proxy?.port}`,+ noProxy: '',+ userAgent: 'Motrix/2.0',+ })+ ).resolves.toEqual({+ filename: REMOTE_FILENAME,+ validator: {+ kind: 'strong-etag',+ value: '"proxy-release-v1"',+ contentLength: 4096,+ capturedAt: expect.any(Number),+ },+ })++ expect(globalFetch).not.toHaveBeenCalled()+ expect(proxy?.stats.httpRequestCount).toBeGreaterThanOrEqual(2)+ expect(originRequests).toEqual(['GET /stable', 'GET /artifacts/latest'])+ expect(originHeaders[0]).toMatchObject({+ accept: '*/*',+ 'accept-encoding': 'deflate, gzip',+ 'user-agent': 'Motrix/2.0',+ 'want-digest': 'SHA-512;q=1, SHA-256;q=1, SHA;q=0.1',+ })+ expect(originHeaders[0]).not.toHaveProperty('accept-language')+ expect(originHeaders[0]).not.toHaveProperty('sec-fetch-mode')+ })++ it('honors aria2 CIDR bypass without touching the configured proxy', async () => {+ const globalFetch = vi+ .spyOn(globalThis, 'fetch')+ .mockRejectedValue(+ new Error('embedded global fetch must not receive a package dispatcher')+ )+ const service = new DirectResourceValidatorService()++ await expect(+ service.probe(`${originUrl}/stable`, {+ proxy: `http://${LOOPBACK_HOST}:${proxy?.port}`,+ noProxy: '127.0.0.0/8',+ })+ ).resolves.toEqual({+ filename: REMOTE_FILENAME,+ validator: expect.objectContaining({ value: '"proxy-release-v1"' }),+ })++ expect(globalFetch).not.toHaveBeenCalled()+ expect(proxy?.stats.httpRequestCount).toBe(0)+ expect(originRequests).toEqual(['GET /stable', 'GET /artifacts/latest'])+ })++ it('sends an explicitly empty User-Agent without an Undici default', async () => {+ const service = new DirectResourceValidatorService()++ await expect(+ service.probe(`${originUrl}/stable`, { userAgent: '' })+ ).resolves.toEqual({+ filename: REMOTE_FILENAME,+ validator: expect.objectContaining({ value: '"proxy-release-v1"' }),+ })++ expect(originHeaders[0]).toHaveProperty('user-agent', '')+ })++ bundledAria2Test(+ 'pins the bundled aria2 HTTP Accept header to the metadata value',+ async () => {+ const outputDir = mkdtempSync(+ path.join(os.tmpdir(), 'motrix-aria2-accept-')+ )+ try {+ await new Promise<void>((resolve, reject) => {+ const child = spawn(bundledAria2Path, [+ `--dir=${outputDir}`,+ '--out=payload',+ '--allow-overwrite=true',+ '--auto-file-renaming=false',+ '--console-log-level=error',+ '--summary-interval=0',+ '--all-proxy=',+ '--http-proxy=',+ '--https-proxy=',+ '--ftp-proxy=',+ '--header=Accept: */*',+ `${originUrl}/aria2-accept`,+ ])+ const timer = setTimeout(() => {+ child.kill('SIGKILL')+ reject(new Error('bundled aria2 header probe timed out'))+ }, 10_000)+ child.once('error', (error) => {+ clearTimeout(timer)+ reject(error)+ })+ child.once('exit', (code) => {+ clearTimeout(timer)+ if (code === 0) resolve()+ else reject(new Error(`bundled aria2 exited with code ${code}`))+ })+ })++ expect(originHeaders.at(-1)?.accept).toBe('*/*')+ } finally {+ rmSync(outputDir, { recursive: true, force: true })+ }+ }+ )++ bundledAria2Test(+ 'suppresses redirect CookieStorage with the same empty Cookie field as metadata requests',+ async () => {+ const outputDir = mkdtempSync(+ path.join(os.tmpdir(), 'motrix-aria2-cookie-')+ )+ const runAria2Sequence = async (+ outputPrefix: string,+ headers: readonly string[] = []+ ) => {+ const inputPath = path.join(outputDir, `${outputPrefix}.txt`)+ writeFileSync(+ inputPath,+ [+ `${originUrl}/cookie-start`,+ ` out=${outputPrefix}-first`,+ `${originUrl}/cookie-final`,+ ` out=${outputPrefix}-second`,+ '',+ ].join('\n')+ )+ await new Promise<void>((resolve, reject) => {+ const child = spawn(bundledAria2Path, [+ `--dir=${outputDir}`,+ `--input-file=${inputPath}`,+ '--max-concurrent-downloads=1',+ '--allow-overwrite=true',+ '--auto-file-renaming=false',+ '--console-log-level=error',+ '--summary-interval=0',+ '--all-proxy=',+ '--http-proxy=',+ '--https-proxy=',+ '--ftp-proxy=',+ ...headers.map((header) => `--header=${header}`),+ ])+ const timer = setTimeout(() => {+ child.kill('SIGKILL')+ reject(new Error('bundled aria2 CookieStorage probe timed out'))+ }, 10_000)+ child.once('error', (error) => {+ clearTimeout(timer)+ reject(error)+ })+ child.once('exit', (code) => {+ clearTimeout(timer)+ if (code === 0) resolve()+ else reject(new Error(`bundled aria2 exited with code ${code}`))+ })+ })+ return [+ readFileSync(path.join(outputDir, `${outputPrefix}-first`), 'utf8'),+ readFileSync(path.join(outputDir, `${outputPrefix}-second`), 'utf8'),+ ]+ }++ try {+ const service = new DirectResourceValidatorService()+ await expect(+ service.probe(`${originUrl}/cookie-start`)+ ).resolves.toEqual({+ filename: 'baseline-variant.bin',+ validator: {+ kind: 'strong-etag',+ value: '"baseline-v1"',+ contentLength: Buffer.byteLength('baseline-variant'),+ capturedAt: expect.any(Number),+ },+ })+ expect(originHeaders.at(-1)).toHaveProperty('cookie', '')++ originRequests.length = 0+ originHeaders.length = 0+ await expect(runAria2Sequence('ambient-cookie')).resolves.toEqual([+ 'cookie-variant',+ 'cookie-variant',+ ])+ expect(originRequests).toEqual([+ 'GET /cookie-start',+ 'GET /cookie-final',+ 'GET /cookie-final',+ ])+ expect(originHeaders.at(-1)?.cookie).toContain('variant=cookie')++ originRequests.length = 0+ originHeaders.length = 0+ await expect(+ runAria2Sequence('pinned-empty-cookie', [+ 'Cookie: ',+ 'Authorization: ',+ 'Accept: */*',+ ])+ ).resolves.toEqual(['baseline-variant', 'baseline-variant'])+ expect(originRequests).toEqual([+ 'GET /cookie-start',+ 'GET /cookie-final',+ 'GET /cookie-final',+ ])+ expect(originHeaders.at(-1)).toMatchObject({+ authorization: '',+ cookie: '',+ })+ } finally {+ rmSync(outputDir, { recursive: true, force: true })+ }+ }+ )++ it('verifies a resumable source through the real proxy dispatcher', async () => {+ const globalFetch = vi+ .spyOn(globalThis, 'fetch')+ .mockRejectedValue(+ new Error('embedded global fetch must not receive a package dispatcher')+ )+ const service = new DirectResourceValidatorService()++ await expect(+ service.verify(+ `${originUrl}/verify`,+ {+ kind: 'strong-etag',+ value: '"proxy-release-v1"',+ contentLength: 4096,+ capturedAt: 7,+ },+ { proxy: `http://${LOOPBACK_HOST}:${proxy?.port}`, noProxy: '' }+ )+ ).resolves.toEqual({+ outcome: 'unchanged',+ ifRange: '"proxy-release-v1"',+ })++ expect(globalFetch).not.toHaveBeenCalled()+ expect(proxy?.stats.httpRequestCount).toBeGreaterThanOrEqual(1)+ expect(originRequests).toEqual(['GET /verify'])+ })++ it('tears down a SOCKS5 socket stalled before its greeting response', async () => {+ const sockets = new Set<Socket>()+ let acceptedConnections = 0+ const socksServer = createTcpServer((socket) => {+ acceptedConnections += 1+ sockets.add(socket)+ socket.on('close', () => sockets.delete(socket))+ socket.on('error', () => undefined)+ // Consume the client's greeting but intentionally never send a reply.+ socket.resume()+ })+ const socksPort = await listen(socksServer)++ try {+ const service = new DirectResourceValidatorService(+ undefined,+ SOCKS_STALL_TIMEOUT_MS+ )++ await expect(+ service.probe(`${originUrl}/stable`, {+ proxy: `socks5://${LOOPBACK_HOST}:${socksPort}`,+ })+ ).resolves.toBeNull()++ expect(acceptedConnections).toBeGreaterThan(0)+ await vi.waitFor(+ () => {+ expect(sockets.size).toBe(0)+ },+ { interval: 10, timeout: 2_000 }+ )+ } finally {+ await closeTcpServer(socksServer, sockets)+ }+ })++ electronRuntimeTest(+ 'uses CONNECT for each HTTPS redirect origin in Electron',+ async () => {+ const secureRequests: string[] = []+ const tlsOptions = { cert: TEST_TLS_CERT, key: TEST_TLS_KEY }+ let artifactOrigin: HttpServer | undefined+ let redirectOrigin: HttpServer | undefined++ try {+ artifactOrigin = createHttpsServer(tlsOptions, (request, response) => {+ secureRequests.push(`artifact ${request.method} ${request.url}`)+ if (request.url !== '/artifacts/latest') {+ response.writeHead(404)+ response.end()+ return+ }+ response.writeHead(200, {+ 'Content-Disposition': `attachment; filename="${REMOTE_FILENAME}"`,+ 'Content-Length': '4096',+ ETag: '"proxy-release-v1"',+ })+ response.end(Buffer.alloc(4096))+ })+ const artifactPort = await listen(artifactOrigin)++ redirectOrigin = createHttpsServer(tlsOptions, (request, response) => {+ secureRequests.push(`redirect ${request.method} ${request.url}`)+ if (request.url !== '/stable') {+ response.writeHead(404)+ response.end()+ return+ }+ response.writeHead(302, {+ Location: `https://${LOOPBACK_HOST}:${artifactPort}/artifacts/latest`,+ })+ response.end()+ })+ const redirectPort = await listen(redirectOrigin)++ const output = await runElectronProbe(+ `https://${LOOPBACK_HOST}:${redirectPort}/stable`,+ `http://${LOOPBACK_HOST}:${proxy?.port}`,+ true+ )++ expect(output.result).toEqual({+ filename: REMOTE_FILENAME,+ validator: {+ kind: 'strong-etag',+ value: '"proxy-release-v1"',+ contentLength: 4096,+ capturedAt: expect.any(Number),+ },+ })+ expect(output.globalFetchCalls).toBe(0)+ expect(output.runtime.electron).toBeTruthy()+ expect(proxy?.stats.httpRequestCount).toBe(0)+ expect(proxy?.stats.connectRequestCount).toBe(2)+ expect(proxyRoutes).toEqual([+ { hostname: LOOPBACK_HOST, isHttp: false, port: redirectPort },+ { hostname: LOOPBACK_HOST, isHttp: false, port: artifactPort },+ ])+ expect(secureRequests).toEqual([+ 'redirect GET /stable',+ 'artifact GET /artifacts/latest',+ ])+ } finally {+ await closeServer(redirectOrigin)+ await closeServer(artifactOrigin)+ }+ }+ )++ electronRuntimeTest(+ 'uses package-owned fetch and dispatcher without a configured proxy in Electron',+ async () => {+ const output = await runElectronProbe(`${originUrl}/stable`, null)++ expect(output.result).toEqual({+ filename: REMOTE_FILENAME,+ validator: {+ kind: 'strong-etag',+ value: '"proxy-release-v1"',+ contentLength: 4096,+ capturedAt: expect.any(Number),+ },+ })+ expect(output.globalFetchCalls).toBe(0)+ expect(output.runtime.electron).toBeTruthy()+ expect(proxy?.stats.httpRequestCount).toBe(0)+ expect(proxy?.stats.connectRequestCount).toBe(0)+ expect(originRequests).toEqual(['GET /stable', 'GET /artifacts/latest'])+ expect(originHeaders[0]).not.toHaveProperty('accept-language')+ expect(originHeaders[0]).not.toHaveProperty('sec-fetch-mode')+ }+ )++ electronRuntimeTest(+ 'uses the package fetch with its proxy dispatcher in Electron',+ async () => {+ const output = await runElectronProbe(+ `${originUrl}/stable`,+ `http://${LOOPBACK_HOST}:${proxy?.port}`+ )++ expect(output.result).toEqual({+ filename: REMOTE_FILENAME,+ validator: {+ kind: 'strong-etag',+ value: '"proxy-release-v1"',+ contentLength: 4096,+ capturedAt: expect.any(Number),+ },+ })+ expect(output.globalFetchCalls).toBe(0)+ expect(output.runtime.electron).toBeTruthy()+ expect(output.runtime.embeddedUndici).toBeTruthy()+ expect(output.runtime.node).toBeTruthy()+ expect(proxy?.stats.httpRequestCount).toBeGreaterThanOrEqual(2)+ expect(originRequests).toEqual(['GET /stable', 'GET /artifacts/latest'])+ }+ )+})diff --git a/src/core/task/direct-resource-validator.test.ts b/src/core/task/direct-resource-validator.test.tsindex 38e80833..b2a2f37a 100644--- a/src/core/task/direct-resource-validator.test.ts+++ b/src/core/task/direct-resource-validator.test.ts@@ -2,9 +2,9 @@ import {INCOMPLETE_SUFFIX,MAX_DEDUP_ATTEMPTS,} from '@shared/constants/incomplete'-import { EnvHttpProxyAgent, Socks5ProxyAgent } from 'undici'import { describe, expect, it, vi } from 'vitest'import {+ canMirrorAria2MetadataHeaders,DirectResourceValidatorService,sanitizeRemoteFilename,} from './direct-resource-validator'@@ -17,6 +17,37 @@ function fetchSequence(...responses: Response[]) {}describe('DirectResourceValidatorService', () => {+ it('fails closed only for concrete aria2 reports missing request features', () => {+ const report = (+ features: string[],+ version = '1.37.0-motrix.10',+ hasSqlitePersistence = true+ ) => ({+ version,+ features,+ hasSqlitePersistence,+ hasBtSeedUnverified: false,+ hasBtSaveMetadata: false,+ hasMoveStorage: false,+ })++ expect(+ canMirrorAria2MetadataHeaders(report(['GZip', 'Message Digest']))+ ).toBe(true)+ expect(canMirrorAria2MetadataHeaders(report(['GZip']))).toBe(false)+ expect(canMirrorAria2MetadataHeaders(report(['Message Digest']))).toBe(+ false+ )+ expect(+ canMirrorAria2MetadataHeaders(+ report(['GZip', 'Message Digest'], '1.37.0', false)+ )+ ).toBe(false)+ expect(canMirrorAria2MetadataHeaders(report([], 'unknown', false))).toBe(+ true+ )+ })+it('distinguishes redirected source URLs whose path tokens both end in stable', async () => {const serviceFor = (filename: string) =>new DirectResourceValidatorService(@@ -50,7 +81,38 @@ describe('DirectResourceValidatorService', () => {])})- it('resolves a redirected Content-Disposition filename without leaking headers cross-origin', async () => {+ it('ignores a non-ASCII legacy filename but accepts RFC 5987 UTF-8', async () => {+ const legacy = new DirectResourceValidatorService(+ fetchSequence(+ new Response(null, {+ headers: {+ 'Content-Disposition': 'attachment; filename="résumé.zip"',+ },+ })+ ),+ 100+ )+ const extended = new DirectResourceValidatorService(+ fetchSequence(+ new Response(null, {+ headers: {+ 'Content-Disposition':+ "attachment; filename*=UTF-8''r%C3%A9sum%C3%A9.zip",+ },+ })+ ),+ 100+ )++ await expect(+ legacy.probe('https://downloads.example/fallback.exe')+ ).resolves.toEqual({ filename: 'fallback.exe', validator: null })+ await expect(+ extended.probe('https://downloads.example/fallback.exe')+ ).resolves.toEqual({ filename: 'résumé.zip', validator: null })+ })++ it('fails closed before a cross-origin redirect would strip request headers', async () => {const fetchImpl = fetchSequence(new Response(null, {status: 302,@@ -68,13 +130,13 @@ describe('DirectResourceValidatorService', () => {},}))- const dispatcher = { close: vi.fn(async () => undefined) }- const makeDispatcher = vi.fn(async () => dispatcher)+ const close = vi.fn(async () => undefined)+ const makeProxyClient = vi.fn(async () => ({ fetch: fetchImpl, close }))const service = new DirectResourceValidatorService(fetchImpl,100,Date.now,- makeDispatcher+ makeProxyClient)await expect(@@ -87,72 +149,134 @@ describe('DirectResourceValidatorService', () => {proxy: 'http://proxy.example:8080',noProxy: 'localhost,*.internal',})- ).resolves.toEqual({- filename: 'VSCodeUserSetup-x64-1.103.2.exe',- validator: null,- })+ ).resolves.toBeNull()- expect(makeDispatcher).toHaveBeenCalledWith({+ expect(makeProxyClient).toHaveBeenCalledWith({proxy: 'http://proxy.example:8080',noProxy: 'localhost,*.internal',})- expect(fetchImpl).toHaveBeenCalledTimes(2)+ expect(fetchImpl).toHaveBeenCalledOnce()expect(String(fetchImpl.mock.calls[0]?.[0])).toBe('https://update.example/latest/win32-x64-user/stable')expect(fetchImpl.mock.calls[0]?.[1]).toEqual(expect.objectContaining({- method: 'HEAD',+ method: 'GET',headers: {- 'accept-encoding': 'identity',+ accept: '*/*',+ 'accept-encoding': 'deflate, gzip',authorization: 'Bearer secret',+ cookie: '','user-agent': 'Motrix test',+ 'want-digest': 'SHA-512;q=1, SHA-256;q=1, SHA;q=0.1','x-api-key': 'also-secret',},redirect: 'manual',- dispatcher,}))+ expect(fetchImpl.mock.calls[0]?.[1]).not.toHaveProperty('dispatcher')+ expect(close).toHaveBeenCalledOnce()+ })++ it('follows a cross-origin redirect when every request header is replayable', async () => {+ const fetchImpl = fetchSequence(+ new Response(null, {+ status: 302,+ headers: { Location: 'https://cdn.example/release' },+ }),+ new Response(null, {+ status: 200,+ headers: {+ 'Content-Disposition': 'attachment; filename="release.zip"',+ },+ })+ )+ const service = new DirectResourceValidatorService(fetchImpl, 100)++ await expect(+ service.probe('https://downloads.example/latest', {+ headers: { Accept: 'application/octet-stream' },+ userAgent: 'Motrix/2.0',+ })+ ).resolves.toEqual({ filename: 'release.zip', validator: null })++ expect(fetchImpl).toHaveBeenCalledTimes(2)expect(fetchImpl.mock.calls[1]?.[1]).toEqual(expect.objectContaining({headers: {- 'accept-encoding': 'identity',- 'user-agent': 'Motrix test',+ accept: 'application/octet-stream',+ 'accept-encoding': 'deflate, gzip',+ authorization: '',+ cookie: '',+ 'user-agent': 'Motrix/2.0',+ 'want-digest': 'SHA-512;q=1, SHA-256;q=1, SHA;q=0.1',},}))- expect(dispatcher.close).toHaveBeenCalledOnce()})- it('falls back to a body-cancelled Range GET and applies Content-Type extension', async () => {- const ranged = new Response(Uint8Array.of(1), {- status: 206,+ it('replays sensitive headers across a same-origin redirect', async () => {+ const fetchImpl = fetchSequence(+ new Response(null, {+ status: 302,+ headers: { Location: '/release' },+ }),+ new Response(null, {+ status: 200,+ headers: {+ 'Content-Disposition': 'attachment; filename="release.zip"',+ },+ })+ )+ const service = new DirectResourceValidatorService(fetchImpl, 100)++ await expect(+ service.probe('https://downloads.example/latest', {+ headers: { Authorization: 'Bearer secret' },+ })+ ).resolves.toEqual({ filename: 'release.zip', validator: null })++ expect(fetchImpl.mock.calls[1]?.[1]).toEqual(+ expect.objectContaining({+ headers: expect.objectContaining({+ authorization: 'Bearer secret',+ }),+ })+ )+ })++ it('cancels a metadata GET body and applies a Content-Type extension', async () => {+ const response = new Response(Uint8Array.of(1), {+ status: 200,headers: {- 'Content-Range': 'bytes 0-0/1024','Content-Type': 'application/vnd.microsoft.portable-executable',},})- const cancel = vi.spyOn(ranged.body as ReadableStream, 'cancel')- const fetchImpl = fetchSequence(new Response(null, { status: 405 }), ranged)+ const cancel = vi.spyOn(response.body as ReadableStream, 'cancel')+ const fetchImpl = fetchSequence(response)const service = new DirectResourceValidatorService(fetchImpl, 100)await expect(service.probe('https://update.example/latest/win32-x64-user/stable')).resolves.toEqual({ filename: 'stable.exe', validator: null })- expect(fetchImpl.mock.calls[1]?.[1]).toEqual(+ expect(fetchImpl).toHaveBeenCalledOnce()+ expect(fetchImpl.mock.calls[0]?.[1]).toEqual(expect.objectContaining({method: 'GET',headers: {- 'accept-encoding': 'identity',- range: 'bytes=0-0',+ accept: '*/*',+ 'accept-encoding': 'deflate, gzip',+ authorization: '',+ cookie: '',+ 'want-digest': 'SHA-512;q=1, SHA-256;q=1, SHA;q=0.1',},}))expect(cancel).toHaveBeenCalledOnce()})- it('returns filename and validator from the same successful HEAD', async () => {+ it('returns filename and validator from the same successful GET', async () => {const fetchImpl = fetchSequence(new Response(null, {status: 200,@@ -179,16 +303,32 @@ describe('DirectResourceValidatorService', () => {expect(fetchImpl).toHaveBeenCalledOnce()})+ it('rejects duplicate ETags merged into one response header', async () => {+ const headers = new Headers({+ 'Content-Disposition': 'attachment; filename="release.zip"',+ })+ headers.append('ETag', '"release-v1"')+ headers.append('ETag', '"release-v2"')+ const fetchImpl = fetchSequence(+ new Response(null, { status: 200, headers })+ )+ const service = new DirectResourceValidatorService(fetchImpl, 100, () => 7)++ await expect(+ service.probe('https://example.com/download.php')+ ).resolves.toEqual({ filename: 'release.zip', validator: null })+ })+it('does not bypass a proxy that cannot be represented', async () => {const fetchImpl = vi.fn()- const makeDispatcher = vi.fn(async () => {+ const makeProxyClient = vi.fn(async () => {throw new Error('unsupported proxy')})const service = new DirectResourceValidatorService(fetchImpl,100,Date.now,- makeDispatcher+ makeProxyClient)await expect(@@ -199,53 +339,44 @@ describe('DirectResourceValidatorService', () => {expect(fetchImpl).not.toHaveBeenCalled()})- it('uses EnvHttpProxyAgent for HTTP proxy+bypass and Socks5ProxyAgent for SOCKS5', async () => {- const response = () =>+ it('uses a proxy-bound client instead of the direct fetch implementation', async () => {+ const directFetch = vi.fn(async () => {+ throw new Error('direct fetch must not run for a proxied probe')+ })+ const proxyFetch = fetchSequence(new Response(null, {status: 200,headers: {'Content-Disposition': 'attachment; filename="release.zip"',},})- const httpFetch = fetchSequence(response())- const socksFetch = fetchSequence(response())-- await new DirectResourceValidatorService(httpFetch, 100).probe(- 'https://example.com/download.php',- {- proxy: 'http://proxy.example:8080',- noProxy: 'localhost,*.internal',- })- await new DirectResourceValidatorService(socksFetch, 100).probe(- 'https://example.com/download.php',- { proxy: 'socks5://proxy.example:1080' }+ const close = vi.fn(async () => undefined)+ const makeProxyClient = vi.fn(async () => ({ fetch: proxyFetch, close }))+ const service = new DirectResourceValidatorService(+ directFetch,+ 100,+ Date.now,+ makeProxyClient)- const httpInit = httpFetch.mock.calls[0]?.[1] as- | { dispatcher?: unknown }- | undefined- const socksInit = socksFetch.mock.calls[0]?.[1] as- | { dispatcher?: unknown }- | undefined- expect(httpInit?.dispatcher).toBeInstanceOf(EnvHttpProxyAgent)- expect(socksInit?.dispatcher).toBeInstanceOf(Socks5ProxyAgent)- })-- it('declines SOCKS5 metadata probing when a bypass list cannot be represented', async () => {- const fetchImpl = vi.fn()- const service = new DirectResourceValidatorService(fetchImpl, 100)-await expect(service.probe('https://example.com/download.php', {- proxy: 'socks5://proxy.example:1080',- noProxy: 'localhost',+ proxy: 'http://proxy.example:8080',+ noProxy: 'localhost,*.internal',})- ).resolves.toBeNull()- expect(fetchImpl).not.toHaveBeenCalled()+ ).resolves.toEqual({ filename: 'release.zip', validator: null })++ expect(makeProxyClient).toHaveBeenCalledWith({+ proxy: 'http://proxy.example:8080',+ noProxy: 'localhost,*.internal',+ })+ expect(directFetch).not.toHaveBeenCalled()+ expect(proxyFetch).toHaveBeenCalledOnce()+ expect(close).toHaveBeenCalledOnce()})- it('captures a strong ETag and content length with HEAD', async () => {+ it('captures a strong ETag and content length with GET', async () => {const fetchImpl = fetchSequence(new Response(null, {status: 200,@@ -261,17 +392,81 @@ describe('DirectResourceValidatorService', () => {capturedAt: 7,})expect(fetchImpl).toHaveBeenCalledWith(+ 'https://example.com/file',expect.objectContaining({- href: 'https://example.com/file',- }),- expect.objectContaining({- method: 'HEAD',- headers: { 'accept-encoding': 'identity' },+ method: 'GET',+ headers: {+ accept: '*/*',+ 'accept-encoding': 'deflate, gzip',+ authorization: '',+ cookie: '',+ 'want-digest': 'SHA-512;q=1, SHA-256;q=1, SHA;q=0.1',+ },redirect: 'manual',}))})+ it('uses the effective engine User-Agent unless the task overrides it', async () => {+ const inheritedFetch = fetchSequence(new Response(null, { status: 200 }))+ const overriddenFetch = fetchSequence(new Response(null, { status: 200 }))++ await new DirectResourceValidatorService(inheritedFetch, 100).capture(+ 'https://example.com/file',+ { userAgent: 'Motrix/2.0' }+ )+ await new DirectResourceValidatorService(overriddenFetch, 100).capture(+ 'https://example.com/file',+ {+ headers: { 'User-Agent': 'Task Agent' },+ userAgent: 'Motrix/2.0',+ }+ )++ expect(inheritedFetch.mock.calls[0]?.[1]).toEqual(+ expect.objectContaining({+ headers: expect.objectContaining({ 'user-agent': 'Motrix/2.0' }),+ })+ )+ expect(overriddenFetch.mock.calls[0]?.[1]).toEqual(+ expect.objectContaining({+ headers: expect.objectContaining({ 'user-agent': 'Task Agent' }),+ })+ )+ })++ it('sends an explicitly empty effective User-Agent', async () => {+ const fetchImpl = fetchSequence(new Response(null, { status: 200 }))++ await new DirectResourceValidatorService(fetchImpl, 100).capture(+ 'https://example.com/file',+ { userAgent: '' }+ )++ expect(fetchImpl.mock.calls[0]?.[1]).toEqual(+ expect.objectContaining({+ headers: expect.objectContaining({ 'user-agent': '' }),+ })+ )+ })++ it.each([+ [{ Host: 'other.example' }],+ [{ Authorization: 'one', authorization: 'two' }],+ [{ 'X-Test': 'safe\r\nInjected: yes' }],+ ])(+ 'does not request metadata for an unrepresentable header map',+ async (headers) => {+ const fetchImpl = vi.fn()+ const service = new DirectResourceValidatorService(fetchImpl, 100)++ await expect(+ service.probe('https://example.com/file', { headers })+ ).resolves.toBeNull()+ expect(fetchImpl).not.toHaveBeenCalled()+ }+ )+it('falls back to Last-Modified only when content length is known', async () => {const fetchImpl = fetchSequence(new Response(null, {@@ -306,24 +501,101 @@ describe('DirectResourceValidatorService', () => {const service = new DirectResourceValidatorService(fetchImpl)await expect(- service.verify('https://example.com/file', {- kind: 'strong-etag',- value: '"release-v1"',- contentLength: 4096,- capturedAt: 1,- })+ service.verify(+ 'https://example.com/file',+ {+ kind: 'strong-etag',+ value: '"release-v1"',+ contentLength: 4096,+ capturedAt: 1,+ },+ { userAgent: 'Motrix/2.0' }+ )).resolves.toEqual({ outcome: 'unchanged', ifRange: '"release-v1"' })expect(fetchImpl).toHaveBeenCalledWith('https://example.com/file',expect.objectContaining({method: 'GET',headers: {- 'Accept-Encoding': 'identity',- Range: 'bytes=0-0',- 'If-Range': '"release-v1"',+ accept: '*/*',+ 'accept-encoding': 'deflate, gzip',+ authorization: '',+ cookie: '',+ 'user-agent': 'Motrix/2.0',+ 'want-digest': 'SHA-512;q=1, SHA-256;q=1, SHA;q=0.1',+ range: 'bytes=0-0',+ 'if-range': '"release-v1"',+ },+ redirect: 'manual',+ signal: expect.any(AbortSignal),+ })+ )+ })++ it('verifies through a proxy client and closes it without direct fallback', async () => {+ const directFetch = vi.fn()+ const proxyFetch = fetchSequence(+ new Response(null, {+ status: 206,+ headers: {+ ETag: '"release-v1"',+ 'Content-Range': 'bytes 0-0/4096',},}))+ const close = vi.fn(async () => undefined)+ const makeProxyClient = vi.fn(async () => ({ fetch: proxyFetch, close }))+ const service = new DirectResourceValidatorService(+ directFetch,+ 100,+ () => 7,+ makeProxyClient+ )++ await expect(+ service.verify(+ 'https://example.com/file',+ {+ kind: 'strong-etag',+ value: '"release-v1"',+ contentLength: 4096,+ capturedAt: 1,+ },+ { proxy: 'proxy.example:8080', noProxy: 'localhost' }+ )+ ).resolves.toEqual({ outcome: 'unchanged', ifRange: '"release-v1"' })++ expect(makeProxyClient).toHaveBeenCalledWith({+ proxy: 'proxy.example:8080',+ noProxy: 'localhost',+ })+ expect(directFetch).not.toHaveBeenCalled()+ expect(proxyFetch).toHaveBeenCalledOnce()+ expect(close).toHaveBeenCalledOnce()+ })++ it('fails closed when a verification proxy cannot be represented', async () => {+ const directFetch = vi.fn()+ const makeProxyClient = vi.fn(async () => null)+ const service = new DirectResourceValidatorService(+ directFetch,+ 100,+ Date.now,+ makeProxyClient+ )++ await expect(+ service.verify(+ 'https://example.com/file',+ {+ kind: 'strong-etag',+ value: '"release-v1"',+ capturedAt: 1,+ },+ { proxy: 'unsupported://proxy.example' }+ )+ ).resolves.toEqual({ outcome: 'unverifiable', ifRange: null })+ expect(directFetch).not.toHaveBeenCalled()})it('classifies changed ETag or total length as source-changed', async () => {diff --git a/src/core/task/direct-resource-validator.ts b/src/core/task/direct-resource-validator.tsindex b5a570ae..d50d9dbd 100644--- a/src/core/task/direct-resource-validator.ts+++ b/src/core/task/direct-resource-validator.ts@@ -1,11 +1,21 @@+import type { Socket } from 'node:net'import {INCOMPLETE_SUFFIX,MAX_DEDUP_ATTEMPTS,} from '@shared/constants/incomplete'import type { DirectResourceValidator } from '@shared/schemas/direct-replay-recipe'+import type { EngineFeatureReport } from '@shared/types/engine'+import type { Dispatcher } from 'undici'+import { isMotrixFork } from '../engine/aria2/feature-report'+import {+ decideAria2ProxyRoute,+ normalizeProxyUrl,+} from '../proxy/aria2-proxy-routing'const DEFAULT_TIMEOUT_MS = 3_000const MAX_FILENAME_REDIRECTS = 5+const ARIA2_REDIRECT_STATUSES = new Set([300, 301, 302, 303, 307, 308])+const ARIA2_WANT_DIGEST = 'SHA-512;q=1, SHA-256;q=1, SHA;q=0.1'const MAX_FILESYSTEM_NAME_BYTES = 255const MAX_DEDUP_SUFFIX_BYTES = Buffer.byteLength(` (${MAX_DEDUP_ATTEMPTS})`,@@ -16,34 +26,66 @@ const MAX_FINAL_NAME_BYTES =Buffer.byteLength(INCOMPLETE_SUFFIX, 'utf8') -MAX_DEDUP_SUFFIX_BYTES-interface ProxyDispatcher {- close?(): Promise<void> | void- destroy?(): Promise<void> | void-}+type FetchLike = (input: string | URL, init?: RequestInit) => Promise<Response>+type UndiciRequestLike = typeof import('undici').request-interface ResourceRequestInit extends RequestInit {- /** Node/undici extension used by the main and server runtimes. */- dispatcher?: ProxyDispatcher+interface ResourceHttpResponse {+ status: number+ headers: Headers+ cancel(): Promise<void> | void}-type FetchLike = (- input: string | URL | Request,- init?: ResourceRequestInit-) => Promise<Response>+type ResourceRequestLike = (+ input: string | URL,+ init?: RequestInit+) => Promise<ResourceHttpResponse>++interface ResourceHttpClient {+ /** Production clients use request; injected tests may retain the fetch seam. */+ request?: ResourceRequestLike+ fetch?: FetchLike+ close(): Promise<void> | void+}interface ProxyDispatcherOptions {proxy: stringnoProxy?: string}-type ProxyDispatcherFactory = (+type ProxyHttpClientFactory = (options: ProxyDispatcherOptions-) => Promise<ProxyDispatcher | null>+) => Promise<ResourceHttpClient | null>-export interface DirectResourceRequestOptions {- headers?: Readonly<Record<string, string>>+export interface DirectResourceProxyOptions {proxy?: stringnoProxy?: string+ /** aria2's effective global User-Agent for recovery validation requests. */+ userAgent?: string+}++export interface DirectResourceRequestOptions+ extends DirectResourceProxyOptions {+ headers?: Readonly<Record<string, string>>+}++export type DirectResourceProxyOptionsProvider =+ () => DirectResourceProxyOptions | null++/**+ * Exact probe headers are guaranteed only for the bundled Motrix fork with+ * both corresponding compile-time features. An unprobed adapter reports+ * `unknown`; retain that test/startup compatibility, but fail closed for any+ * other concrete binary profile.+ */+export function canMirrorAria2MetadataHeaders(+ report: EngineFeatureReport | null | undefined+): boolean {+ if (!report || report.version === 'unknown') return true+ return (+ isMotrixFork(report) &&+ report.features.includes('GZip') &&+ report.features.includes('Message Digest')+ )}export interface DirectResourceMetadata {@@ -65,8 +107,9 @@ const REDIRECT_SAFE_HEADERS = new Set(['pragma','range','user-agent',+ 'want-digest',])-+const EMPTY_CREDENTIAL_HEADERS = new Set(['authorization', 'cookie'])const REQUEST_HEADER_DENYLIST = new Set(['connection','content-length',@@ -112,33 +155,160 @@ const CONTENT_TYPE_EXTENSIONS: Readonly<Record<string, string>> = {'video/webm': '.webm',}-const createProxyDispatcher: ProxyDispatcherFactory = async ({+const createProxyHttpClient: ProxyHttpClientFactory = async ({proxy,noProxy,}) => {- let parsed: URL+ const parsed = normalizeProxyUrl(proxy)+ if (!parsed) return null++ const { request, Agent, ProxyAgent, Socks5ProxyAgent, buildConnector } =+ await import('undici')+ let proxyDispatcher: Dispatcher | undefined+ let directDispatcher: Dispatcher | undefined+ const socksSockets = new Set<Socket>()+ let closed = falsetry {- parsed = new URL(proxy)+ if (parsed.protocol === 'socks5:') {+ const baseConnect = buildConnector({})+ const connect: typeof baseConnect = (options, callback) => {+ const hostname = unbracketHostname(options.hostname)+ return baseConnect(+ { ...options, hostname, host: hostname },+ (error, socket) => {+ if (error) {+ callback(error, null)+ return+ }+ if (!socket) {+ callback(new Error('SOCKS connector returned no socket'), null)+ return+ }+ if (closed) {+ socket.destroy()+ callback(new Error('SOCKS connector completed after close'), null)+ return+ }+ // Socks5ProxyAgent does not own the TCP socket until its greeting+ // finishes. Track it from connect so abort/teardown can also close+ // a proxy that accepts TCP and then stalls during negotiation.+ socksSockets.add(socket)+ socket.once('close', () => socksSockets.delete(socket))+ callback(null, socket)+ }+ )+ }+ proxyDispatcher = new Socks5ProxyAgent(parsed, { connect })+ } else {+ // aria2 treats an https:// proxy URI as an HTTP proxy declaration. Match+ // the download engine instead of attempting TLS to a different endpoint.+ const aria2Proxy = new URL(parsed)+ if (aria2Proxy.protocol === 'https:') {+ // Preserve the port selected while the URI still has HTTPS defaults.+ // Changing protocol first would silently turn an omitted 443 into 80.+ const effectivePort = aria2Proxy.port || '443'+ aria2Proxy.protocol = 'http:'+ aria2Proxy.port = effectivePort+ }+ proxyDispatcher = new ProxyAgent(aria2Proxy.toString())+ }+ directDispatcher = new Agent()} catch {+ await destroyDispatcher(proxyDispatcher)+ await destroyDispatcher(directDispatcher)return null}- const { EnvHttpProxyAgent, Socks5ProxyAgent } = await import('undici')- if (parsed.protocol === 'http:' || parsed.protocol === 'https:') {- return new EnvHttpProxyAgent({- httpProxy: parsed.toString(),- httpsProxy: parsed.toString(),- noProxy: noProxy ?? '',+ // A dispatcher is an Undici-internal protocol object. Bind it to request()+ // from the same module instance so Node/Electron's embedded Undici can never+ // receive a different major's handler contract.+ const requestWithDispatcher: ResourceRequestLike = (input, init) => {+ const route = decideAria2ProxyRoute(input, noProxy)+ if (route === 'unsupported') {+ return Promise.reject(new TypeError('Unsupported proxy route target'))+ }+ if (+ route === 'proxy' &&+ parsed.protocol === 'socks5:' &&+ isBracketedIpv6Target(input)+ ) {+ // Undici 8.10 serializes an IPv6 SOCKS target as the literal domain+ // "[::1]". Decline the optional request until upstream can encode ATYP 4.+ return Promise.reject(new TypeError('Unsupported IPv6 SOCKS target'))+ }+ if (route !== 'proxy' || parsed.protocol !== 'socks5:' || !init?.signal) {+ return requestResource(+ request,+ input,+ init,+ route === 'direct' ? directDispatcher : proxyDispatcher+ )+ }++ // Socks5ProxyAgent does not own the TCP socket until its greeting+ // completes. Its request promise therefore cannot abort a proxy that+ // accepts TCP and stalls before the greeting response. Close the sockets+ // tracked by our connector as soon as this request is aborted.+ const signal = init.signal+ const abortSockets = () => {+ for (const socket of socksSockets) socket.destroy()+ }+ return new Promise<ResourceHttpResponse>((resolve, reject) => {+ let settled = false+ const succeed = (response: ResourceHttpResponse) => {+ if (settled) return+ settled = true+ signal.removeEventListener('abort', onAbort)+ resolve(response)+ }+ const fail = (error: unknown) => {+ if (settled) return+ settled = true+ signal.removeEventListener('abort', onAbort)+ reject(error)+ }+ const onAbort = () => {+ abortSockets()+ fail(new DOMException('The operation was aborted', 'AbortError'))+ }++ // Register before request() starts connecting so a very short timeout+ // cannot race past our ownership of the pre-handshake TCP socket.+ signal.addEventListener('abort', onAbort, { once: true })+ if (signal.aborted) {+ onAbort()+ return+ }+ void requestResource(request, input, init, proxyDispatcher).then(+ succeed,+ fail+ )})}- if (parsed.protocol === 'socks5:') {- // Socks5ProxyAgent has no NO_PROXY equivalent. Silently ignoring a global- // bypass list would change the user's routing policy, so decline the- // optional probe instead of sending it through the wrong route.- if (noProxy?.trim()) return null- return new Socks5ProxyAgent(parsed)++ return {+ request: requestWithDispatcher,+ close: async () => {+ if (closed) return+ closed = true+ for (const socket of socksSockets) {+ socket.destroy()+ }+ socksSockets.clear()+ if (parsed.protocol === 'socks5:') {+ // Undici 8 waits for its fixed authentication timer even after a+ // pre-handshake socket closes. Invoke package-owned teardown without+ // extending our bounded metadata timeout while that timer settles.+ void destroyDispatcher(proxyDispatcher)+ await destroyDispatcher(directDispatcher)+ } else {+ await Promise.allSettled([+ destroyDispatcher(directDispatcher),+ destroyDispatcher(proxyDispatcher),+ ])+ }+ },}- return null}export type DirectResourceValidationOutcome =@@ -154,16 +324,15 @@ export interface DirectResourceValidationResult {/*** Captures and verifies non-secret HTTP validators for URI-only direct tasks.- * A verifier never downloads a response body: capture uses HEAD, while resume- * verification cancels a one-byte Range response immediately after headers.+ * Every request uses GET like aria2 and cancels the response body immediately+ * after headers; resume verification additionally requests a one-byte range.*/export class DirectResourceValidatorService {constructor(- private readonly fetchImpl: FetchLike = (input, init) =>- globalThis.fetch(input, init as RequestInit),+ private readonly fetchImpl: FetchLike | undefined = undefined,private readonly timeoutMs = DEFAULT_TIMEOUT_MS,private readonly now: () => number = Date.now,- private readonly proxyDispatcherFactory: ProxyDispatcherFactory = createProxyDispatcher+ private readonly proxyHttpClientFactory: ProxyHttpClientFactory = createProxyHttpClient) {}/** Resolve the filename and resumability validator in one bounded probe. */@@ -173,50 +342,32 @@ export class DirectResourceValidatorService {): Promise<DirectResourceMetadata | null> {const initialUrl = parseHttpUrl(uri)if (!initialUrl) return null+ const headers = probeHeaders(options.headers, options.userAgent)+ if (!headers) return null- const dispatcher = await this.resolveDispatcher(options)- if (dispatcher === null) return null+ const client = await this.resolveHttpClient(options)+ if (client === null) return nullconst controller = new AbortController()const timeout = setTimeout(() => controller.abort(), this.timeoutMs)- const headers = probeHeaders(options.headers)try {- const head = await this.requestMetadata(+ const metadata = await this.requestMetadata(initialUrl,- 'HEAD',+ uri,headers,- dispatcher,+ client,controller.signal)- let validator: DirectResourceValidator | null = null- if (head && head.status >= 200 && head.status < 300) {- validator = readMetadataValidator(head, this.now())- const filename = filenameFromMetadata(initialUrl, head)- if (filename) return { filename, validator }- } else if (head && head.status !== 405 && head.status !== 501) {+ if (!metadata || metadata.status < 200 || metadata.status >= 300) {return null}-- if (controller.signal.aborted) {- return validator ? { filename: null, validator } : null- }- const ranged = await this.requestMetadata(- initialUrl,- 'GET',- { ...headers, range: 'bytes=0-0' },- dispatcher,- controller.signal- )- if (!ranged || ranged.status < 200 || ranged.status >= 300) {- return validator ? { filename: null, validator } : null- }return {- filename: filenameFromMetadata(initialUrl, ranged),- validator: validator ?? readMetadataValidator(ranged, this.now()),+ filename: filenameFromMetadata(initialUrl, metadata),+ validator: readMetadataValidator(metadata, this.now()),}} finally {clearTimeout(timeout)- await closeDispatcher(dispatcher)+ await closeHttpClient(client)}}@@ -226,18 +377,20 @@ export class DirectResourceValidatorService {): Promise<DirectResourceValidator | null> {const initialUrl = parseHttpUrl(uri)if (!initialUrl) return null+ const headers = probeHeaders(options.headers, options.userAgent)+ if (!headers) return null- const dispatcher = await this.resolveDispatcher(options)- if (dispatcher === null) return null+ const client = await this.resolveHttpClient(options)+ if (client === null) return nullconst controller = new AbortController()const timeout = setTimeout(() => controller.abort(), this.timeoutMs)try {const metadata = await this.requestMetadata(initialUrl,- 'HEAD',- probeHeaders(),- dispatcher,+ uri,+ headers,+ client,controller.signal)if (!metadata || metadata.status < 200 || metadata.status >= 300) {@@ -246,102 +399,99 @@ export class DirectResourceValidatorService {return readMetadataValidator(metadata, this.now())} finally {clearTimeout(timeout)- await closeDispatcher(dispatcher)+ await closeHttpClient(client)}}async verify(uri: string,- expected: DirectResourceValidator+ expected: DirectResourceValidator,+ options: DirectResourceProxyOptions = {}): Promise<DirectResourceValidationResult> {- const response = await this.request(uri, {- method: 'GET',- headers: {- 'Accept-Encoding': 'identity',- Range: 'bytes=0-0',- 'If-Range': expected.value,- },- })- if (!response) return { outcome: 'unverifiable', ifRange: null }- if (response.status !== 200 && response.status !== 206) {- await cancelBody(response)- return { outcome: 'unverifiable', ifRange: null }- }-- const current = readValidator(response.headers, this.now())- const currentValue = validatorValueForKind(current, expected.kind)- if (!currentValue) {- await cancelBody(response)+ const initialUrl = parseHttpUrl(uri)+ if (!initialUrl) return { outcome: 'unverifiable', ifRange: null }+ const client = await this.resolveHttpClient(options)+ if (client === null) return { outcome: 'unverifiable', ifRange: null }+ const headers = probeHeaders(undefined, options.userAgent)+ if (!headers) {+ await closeHttpClient(client)return { outcome: 'unverifiable', ifRange: null }}- if (currentValue !== expected.value) {- await cancelBody(response)- return { outcome: 'source-changed', ifRange: null }- }+ headers.range = 'bytes=0-0'+ headers['if-range'] = expected.value- const currentLength = totalResponseLength(response)- if (- expected.contentLength !== undefined &&- currentLength !== null &&- currentLength !== expected.contentLength- ) {- await cancelBody(response)- return { outcome: 'source-changed', ifRange: null }- }-- const rangeSatisfied = response.status === 206- await cancelBody(response)- return rangeSatisfied- ? { outcome: 'unchanged', ifRange: expected.value }- : { outcome: 'range-unsupported', ifRange: null }- }-- private async request(- uri: string,- init: RequestInit- ): Promise<Response | null> {const controller = new AbortController()const timeout = setTimeout(() => controller.abort(), this.timeoutMs)try {- return await this.fetchImpl(uri, {- ...init,- redirect: 'follow',- signal: controller.signal,- })- } catch {- return null+ const metadata = await this.requestMetadata(+ initialUrl,+ uri,+ headers,+ client,+ controller.signal+ )+ if (!metadata || (metadata.status !== 200 && metadata.status !== 206)) {+ return { outcome: 'unverifiable', ifRange: null }+ }++ const current = readMetadataValidator(metadata, this.now())+ const currentValue = validatorValueForKind(current, expected.kind)+ if (!currentValue) {+ return { outcome: 'unverifiable', ifRange: null }+ }+ if (currentValue !== expected.value) {+ return { outcome: 'source-changed', ifRange: null }+ }++ const currentLength = totalMetadataLength(metadata)+ if (+ expected.contentLength !== undefined &&+ currentLength !== null &&+ currentLength !== expected.contentLength+ ) {+ return { outcome: 'source-changed', ifRange: null }+ }++ return metadata.status === 206+ ? { outcome: 'unchanged', ifRange: expected.value }+ : { outcome: 'range-unsupported', ifRange: null }} finally {clearTimeout(timeout)+ await closeHttpClient(client)}}private async requestMetadata(initialUrl: URL,- method: 'HEAD' | 'GET',+ initialRequestUrl: string,initialHeaders: Record<string, string>,- dispatcher: ProxyDispatcher | undefined,+ client: ResourceHttpClient,signal: AbortSignal): Promise<ResourceMetadata | null> {let currentUrl = initialUrl+ let currentRequestUrl = requestUrlPreservingAuthority(+ initialRequestUrl,+ initialUrl+ )+ if (!currentRequestUrl) return nulllet headers = initialHeadersfor (let redirects = 0; redirects <= MAX_FILENAME_REDIRECTS; redirects++) {- let response: Response+ let response: ResourceHttpResponsetry {- response = await this.fetchImpl(currentUrl, {- method,+ response = await issueResourceRequest(client, currentRequestUrl, {+ method: 'GET',headers,redirect: 'manual',signal,- ...(dispatcher ? { dispatcher } : {}),})} catch {return null}const location = response.headers.get('location')- if (response.status >= 300 && response.status < 400 && location) {- await cancelBody(response)+ if (ARIA2_REDIRECT_STATUSES.has(response.status) && location) {+ await cancelResourceResponse(response)if (redirects === MAX_FILENAME_REDIRECTS) return nulllet nextUrl: URLtry {@@ -350,8 +500,17 @@ export class DirectResourceValidatorService {return null}if (!isHttpUrl(nextUrl)) return null- headers = redirectHeaders(headers, currentUrl, nextUrl)+ const nextRequestUrl = redirectRequestUrl(+ location,+ currentRequestUrl,+ nextUrl+ )+ if (!nextRequestUrl) return null+ const nextHeaders = redirectHeaders(headers, currentUrl, nextUrl)+ if (!nextHeaders) return null+ headers = nextHeaderscurrentUrl = nextUrl+ currentRequestUrl = nextRequestUrlcontinue}@@ -360,20 +519,38 @@ export class DirectResourceValidatorService {headers: response.headers,status: response.status,}- await cancelBody(response)+ await cancelResourceResponse(response)return metadata}return null}- private async resolveDispatcher(- options: DirectResourceRequestOptions- ): Promise<ProxyDispatcher | undefined | null> {+ private async resolveHttpClient(+ options: DirectResourceProxyOptions+ ): Promise<ResourceHttpClient | null> {const proxy = options.proxy?.trim()- if (!proxy) return undefined+ if (!proxy) {+ if (!this.fetchImpl) {+ try {+ const { request, Agent } = await import('undici')+ const dispatcher = new Agent()+ return {+ request: (input, init) =>+ requestResource(request, input, init, dispatcher),+ close: () => destroyDispatcher(dispatcher),+ }+ } catch {+ return null+ }+ }+ return {+ fetch: this.fetchImpl,+ close: async () => undefined,+ }+ }try {- return await this.proxyDispatcherFactory({+ return await this.proxyHttpClientFactory({proxy,...(options.noProxy === undefined ? {} : { noProxy: options.noProxy }),})@@ -420,6 +597,14 @@ export function hasLikelyFileExtension(filename: string | null): boolean {function parseHttpUrl(uri: string): URL | null {try {const url = new URL(uri)+ if (+ hasC0SpaceOrDel(uri) ||+ uri.includes('\\') ||+ decideAria2ProxyRoute(uri) === 'unsupported' ||+ requestUrlPreservingAuthority(uri, url) === null+ ) {+ return null+ }return isHttpUrl(url) ? url : null} catch {return null@@ -430,17 +615,155 @@ function isHttpUrl(url: URL): boolean {return url.protocol === 'http:' || url.protocol === 'https:'}-function probeHeaders(+function requestUrlPreservingAuthority(+ input: string,+ normalized: URL+): string | null {+ const authority = rawUrlAuthority(input)+ const suffix = rawUrlPathAndSearch(input)+ if (!authority || suffix === null) return null+ const requestSuffix =+ suffix === '' || suffix.startsWith('?') ? `/${suffix}` : suffix+ if (requestSuffix !== `${normalized.pathname}${normalized.search}`) {+ return null+ }+ return `${normalized.protocol}//${authority}${requestSuffix}`+}++function redirectRequestUrl(+ location: string,+ currentRequestUrl: string,+ normalized: URL+): string | null {+ if (hasC0SpaceOrDel(location)) return null+ const value = location.trim()+ // aria2 treats backslashes as path text, while WHATWG can reinterpret them+ // as authority separators for special URLs. Decline instead of probing a+ // host the download engine would never select.+ if (!value || value.includes('\\')) return null+ if (unsafeRedirectReference(value)) return null++ const absoluteScheme = /^([A-Za-z][A-Za-z\d+.-]*):\/\//.exec(value)?.[1]+ if (+ absoluteScheme !== undefined &&+ absoluteScheme !== 'http' &&+ absoluteScheme !== 'https'+ ) {+ return null+ }++ const authoritySource = /^[A-Za-z][A-Za-z\d+.-]*:\/\//.test(value)+ ? value+ : value.startsWith('//')+ ? `${normalized.protocol}${value}`+ : currentRequestUrl+ const authority = rawUrlAuthority(authoritySource)+ if (!authority) return null+ if (authoritySource !== currentRequestUrl) {+ const suffix = rawUrlPathAndSearch(authoritySource)+ if (suffix === null) return null+ const requestSuffix =+ suffix === '' || suffix.startsWith('?') ? `/${suffix}` : suffix+ if (requestSuffix !== `${normalized.pathname}${normalized.search}`) {+ return null+ }+ }+ const requestUrl = `${normalized.protocol}//${authority}${normalized.pathname}${normalized.search}`+ return decideAria2ProxyRoute(requestUrl) === 'unsupported' ? null : requestUrl+}++function rawUrlAuthority(input: string): string | null {+ const match = /^[\r\n\t ]*[A-Za-z][A-Za-z\d+.-]*:\/\/([^/?#]*)/.exec(input)+ return match?.[1] || null+}++function rawUrlPathAndSearch(input: string): string | null {+ const match = /^[\r\n\t ]*[A-Za-z][A-Za-z\d+.-]*:\/\/[^/?#]*([^#]*)/.exec(+ input+ )+ return match?.[1] ?? null+}++function unsafeRedirectReference(value: string): boolean {+ if (value.startsWith('?') || value.startsWith('#')) return true+ if (hasC0SpaceOrDel(value)) return true+ if (/^[A-Za-z][A-Za-z\d+.-]*:(?!\/\/)/.test(value)) return true++ const withoutFragment = value.split('#', 1)[0] ?? ''+ const path = withoutFragment.split('?', 1)[0] ?? ''+ const querySeparator = withoutFragment.indexOf('?')+ const query =+ querySeparator === -1 ? null : withoutFragment.slice(querySeparator + 1)+ if (/%2e/i.test(path)) return true+ if (/[\^`{}]/.test(path)) return true+ // aria2 preserves apostrophes in Location query text, while WHATWG's+ // special-query serializer changes them to %27. It also preserves an empty+ // query delimiter and percent-encodes the response's original non-ASCII+ // bytes rather than re-encoding JavaScript code points as UTF-8.+ if (query === '' || query?.includes("'") || hasNonAscii(value)) {+ return true+ }++ const pathWithoutAuthority = /^[A-Za-z][A-Za-z\d+.-]*:\/\//.test(path)+ ? path.slice(path.indexOf('/', path.indexOf('//') + 2))+ : path.startsWith('//')+ ? path.slice(path.indexOf('/', 2))+ : path+ return pathWithoutAuthority.includes('//')+}++export function canRepresentDirectResourceHeaders(+ input?: Readonly<Record<string, string>>+): boolean {+ return normalizedTaskHeaders(input) !== null+}++function normalizedTaskHeaders(input?: Readonly<Record<string, string>>-): Record<string, string> {+): Record<string, string> | null {const result: Record<string, string> = {}for (const [rawName, value] of Object.entries(input ?? {})) {- const name = rawName.trim().toLowerCase()- if (!name || REQUEST_HEADER_DENYLIST.has(name)) continue- if (INVALID_HEADER_NAME.test(name) || /[\r\n]/.test(value)) continue+ const name = rawName.toLowerCase()+ if (+ !name ||+ rawName !== rawName.trim() ||+ REQUEST_HEADER_DENYLIST.has(name) ||+ INVALID_HEADER_NAME.test(name) ||+ !/^[!#$%&'*+\-.^_`|~\dA-Za-z]+$/.test(rawName) ||+ /[\r\n]/.test(value) ||+ Object.hasOwn(result, name)+ ) {+ return null+ }result[name] = value}- result['accept-encoding'] = 'identity'+ return result+}++function probeHeaders(+ input?: Readonly<Record<string, string>>,+ userAgent?: string+): Record<string, string> | null {+ const result = normalizedTaskHeaders(input)+ if (!result) return null+ if (!Object.hasOwn(result, 'user-agent') && userAgent !== undefined) {+ if (hasC0OrDel(userAgent)) return null+ result['user-agent'] = userAgent+ }+ if (!Object.hasOwn(result, 'accept')) result.accept = '*/*'+ // The bundled aria2.conf enables http-accept-gzip. Preserve an explicit task+ // override; otherwise mirror aria2's compiled-with-zlib request value.+ if (!Object.hasOwn(result, 'accept-encoding')) {+ result['accept-encoding'] = 'deflate, gzip'+ }+ if (!Object.hasOwn(result, 'want-digest')) {+ result['want-digest'] = ARIA2_WANT_DIGEST+ }+ // Metadata-eligible aria2 tasks carry the same empty custom fields. Their+ // presence suppresses aria2's process-wide CookieStorage and AuthConfig+ // factories without replacing an explicit task credential.+ if (!Object.hasOwn(result, 'cookie')) result.cookie = ''+ if (!Object.hasOwn(result, 'authorization')) result.authorization = ''return result}@@ -448,13 +771,17 @@ function redirectHeaders(headers: Record<string, string>,from: URL,to: URL-): Record<string, string> {+): Record<string, string> | null {if (from.origin === to.origin) return headers- return Object.fromEntries(- Object.entries(headers).filter(([name]) =>- REDIRECT_SAFE_HEADERS.has(name.toLowerCase())+ return Object.entries(headers).every(([name, value]) => {+ const normalizedName = name.toLowerCase()+ return (+ REDIRECT_SAFE_HEADERS.has(normalizedName) ||+ (value === '' && EMPTY_CREDENTIAL_HEADERS.has(normalizedName)))- )+ })+ ? headers+ : null}function filenameFromMetadata(@@ -524,7 +851,12 @@ function contentDispositionFilename(value: string | null): string | null {const extended = decodeExtendedFilename(rawValue)if (extended) return extended} else if (name === 'filename' && !basic) {- basic = rawValue+ // aria2's default content-disposition-default-utf8=false interprets a+ // legacy filename using locale-dependent bytes. Undici exposes a JS+ // string instead, so only consume the portable ASCII subset here. For a+ // non-ASCII legacy value, filenameFromMetadata falls back to the URL and+ // pins that result as aria2's `out`; RFC 5987 filename* stays supported.+ if (/^[\x20-\x7e]*$/.test(rawValue)) basic = rawValue}}return basic@@ -585,18 +917,99 @@ function decodeExtendedFilename(value: string): string | null {return null}-async function closeDispatcher(- dispatcher: ProxyDispatcher | undefined-): Promise<void> {- if (!dispatcher) return+async function closeHttpClient(client: ResourceHttpClient): Promise<void> {try {- if (dispatcher.destroy) await dispatcher.destroy()- else if (dispatcher.close) await dispatcher.close()+ await client.close()} catch {// Best-effort teardown must not turn a filename fallback into a failure.}}+async function issueResourceRequest(+ client: ResourceHttpClient,+ input: string | URL,+ init: RequestInit+): Promise<ResourceHttpResponse> {+ if (client.request) return client.request(input, init)+ if (!client.fetch) throw new TypeError('HTTP client has no request method')+ const response = await client.fetch(input, init)+ return {+ status: response.status,+ headers: response.headers,+ cancel: () => cancelBody(response),+ }+}++async function requestResource(+ requestImpl: UndiciRequestLike,+ input: string | URL,+ init: RequestInit | undefined,+ dispatcher: Dispatcher | undefined+): Promise<ResourceHttpResponse> {+ const response = await requestImpl(input, {+ dispatcher,+ method: init?.method ?? 'GET',+ // Some Undici versions append synthesized fields (notably Host) to the+ // supplied header object. Never let that mutate our per-hop replay set:+ // doing so can either leak a stale authority or falsely block a safe+ // cross-origin redirect.+ headers:+ init?.headers === undefined+ ? undefined+ : { ...(init.headers as Record<string, string>) },+ signal: init?.signal ?? undefined,+ maxRedirections: 0,+ } as Parameters<UndiciRequestLike>[1])++ // Contract tests retain their Response-based seam; production takes the+ // lower-level Undici response branch and never applies Fetch defaults.+ if (response instanceof Response) {+ return {+ status: response.status,+ headers: response.headers,+ cancel: () => cancelBody(response),+ }+ }++ const headers = new Headers()+ for (const [name, value] of Object.entries(response.headers)) {+ if (Array.isArray(value)) {+ for (const item of value) headers.append(name, item)+ } else if (value !== undefined) {+ headers.set(name, value)+ }+ }+ return {+ status: response.statusCode,+ headers,+ cancel: () => destroyResponseBody(response.body),+ }+}++async function destroyResponseBody(+ body: import('node:stream').Readable+): Promise<void> {+ if (body.closed) return+ // Undici emits RequestAbortedError when a BodyReadable is destroyed. Install+ // the listener first so cancellation cannot become an unhandled process-level+ // error in Node or Electron. The owning client destroys its dispatcher next.+ body.once('error', () => undefined)+ body.destroy()+ // Let Undici process the abort before a redirect reuses this dispatcher.+ // Do not wait indefinitely for `close`: a malformed/truncated body may only+ // settle when the owning dispatcher is destroyed in the caller's finally.+ await new Promise<void>((resolve) => {+ body.once('close', resolve)+ setImmediate(resolve)+ })+}++async function cancelResourceResponse(+ response: ResourceHttpResponse+): Promise<void> {+ await Promise.resolve(response.cancel()).catch(() => {})+}+function readValidator(headers: Headers,capturedAt: number,@@ -608,10 +1021,10 @@ function readValidator(const etag = headers.get('etag')?.trim()if (etag &&- !etag.startsWith('W/') &&- etag.startsWith('"') &&- etag.endsWith('"') &&- !/[\r\n]/.test(etag) &&+ // RFC entity-tag opaque bytes exclude DQUOTE, SP, controls and DEL.+ // Reject non-Latin-1 code points too: a combined duplicate header such as+ // `"a", "b"` must never be mistaken for one strong validator.+ /^"[\x21\x23-\x7e\x80-\xff]*"$/.test(etag) &&etag.length <= 512) {return {@@ -677,15 +1090,60 @@ function parseContentLength(value: string | null): number | null {return Number.isSafeInteger(parsed) ? parsed : null}-function totalResponseLength(response: Response): number | null {- const contentRange = response.headers.get('content-range')+function totalMetadataLength(metadata: ResourceMetadata): number | null {+ const contentRange = metadata.headers.get('content-range')const match = contentRange?.match(/\/([0-9]+)$/)if (match?.[1]) return parseContentLength(match[1])- return response.status === 200- ? parseContentLength(response.headers.get('content-length'))+ return metadata.status === 200+ ? parseContentLength(metadata.headers.get('content-length')): null}+function unbracketHostname(hostname: string): string {+ return hostname.startsWith('[') && hostname.endsWith(']')+ ? hostname.slice(1, -1)+ : hostname+}++function isBracketedIpv6Target(input: string | URL): boolean {+ try {+ const url = typeof input === 'string' ? new URL(input) : input+ return url.hostname.startsWith('[') && url.hostname.endsWith(']')+ } catch {+ return true+ }+}++function hasC0SpaceOrDel(value: string): boolean {+ for (const character of value) {+ const codePoint = character.codePointAt(0) ?? 0+ if (codePoint <= 0x20 || codePoint === 0x7f) return true+ }+ return false+}++function hasC0OrDel(value: string): boolean {+ for (const character of value) {+ const codePoint = character.codePointAt(0) ?? 0+ if (codePoint <= 0x1f || codePoint === 0x7f) return true+ }+ return false+}++function hasNonAscii(value: string): boolean {+ for (const character of value) {+ if ((character.codePointAt(0) ?? 0) > 0x7f) return true+ }+ return false+}++async function destroyDispatcher(+ dispatcher: Dispatcher | undefined+): Promise<void> {+ if (!dispatcher) return+ await dispatcher.destroy().catch(() => {})+}+async function cancelBody(response: Response): Promise<void> {await response.body?.cancel().catch(() => {})}diff --git a/src/main/index.ts b/src/main/index.tsindex 3c164fb0..f5c81c30 100644--- a/src/main/index.ts+++ b/src/main/index.ts@@ -50,6 +50,7 @@ import { PluginRegistry } from '@core/plugin/plugin-registry'import { RegistryClient } from '@core/plugin/registry/registry-client'import { PluginStateStore } from '@core/plugin/state/plugin-state-store'import { BuiltinUpdater } from '@core/plugin/update/builtin-updater'+import { AppliedDownloadProxyPolicy } from '@core/proxy/applied-download-proxy-policy'import { ProxyBridgeManager } from '@core/proxy/proxy-bridge-manager'import { MotrixDatabase } from '@core/session/motrix-database'import { SessionManager } from '@core/session/session-manager'@@ -330,6 +331,7 @@ const settingsManager = new SettingsManager(settingsPath, {}},})+const appliedDownloadProxyPolicy = new AppliedDownloadProxyPolicy()// ─── aria2 Infrastructure ───────────────────────────────@@ -1120,8 +1122,12 @@ async function startEngineAndRestore(}try {- await sessionManager.restore()- await sessionManager.recoverLegacyTaskLost()+ await appliedDownloadProxyPolicy.runWithSnapshot(+ async (_snapshot, lease) => {+ await sessionManager.restore(lease.assertCurrent)+ await sessionManager.recoverLegacyTaskLost(lease.assertCurrent)+ }+ )// Plan B: re-prime MagnetTracker's in-memory cache from the// restored db state so polling skips magnet metadata GIDs and@@ -1554,7 +1560,8 @@ async function initializeMainProcess(): Promise<void> {trustStore,rpcClient,adapter,- proxyBridge+ proxyBridge,+ appliedDownloadProxyPolicy)// Construct SpeedLimitController immediately after supervisor so@@ -1768,7 +1775,15 @@ async function initializeMainProcess(): Promise<void> {rpcClient,motrixDb,adapter,- mediaTmpDir+ mediaTmpDir,+ undefined,+ undefined,+ () => {+ const snapshot = appliedDownloadProxyPolicy.snapshot()+ return snapshot+ ? { ...snapshot, userAgent: settingsManager.getEngine().userAgent }+ : null+ })pollingScheduler = new PollingScheduler(rpcClient,@@ -1948,8 +1963,13 @@ async function initializeMainProcess(): Promise<void> {trackerManager,proxyBridge)+ const initialProxySettings = settingsManager.getProxy()const proxyReady = mainProcessWork- .run(() => proxyApplier.applyAll(settingsManager.getProxy()))+ .run(() =>+ appliedDownloadProxyPolicy.applyTransition(() =>+ proxyApplier.applyAll(initialProxySettings)+ )+ ).catch((err) => log.warn({ err }, 'initial proxy apply failed'))if (@@ -2046,10 +2066,18 @@ async function initializeMainProcess(): Promise<void> {publishTaskUpdate,publishTaskUpdateNow,torrentMetaStore,+ getDirectResourceProxyOptions: () => {+ const snapshot = appliedDownloadProxyPolicy.snapshot()+ return snapshot+ ? { ...snapshot, userAgent: settingsManager.getEngine().userAgent }+ : null+ },+ directResourceProxyPolicy: appliedDownloadProxyPolicy,}const createTaskDeps = {adapter,directResourceValidator: new DirectResourceValidatorService(),+ directResourceProxyPolicy: appliedDownloadProxyPolicy,settingsManager,finalNamePicker,torrentMetaStore,@@ -2084,6 +2112,7 @@ async function initializeMainProcess(): Promise<void> {await supervisor.waitUntilReady(ENGINE_READY_TIMEOUT_MS)await mainProcessWork.waitForStartup()},+ assertEngineReady: () => supervisor.assertReady(),reuseExistingBt: (taskId: string) =>reAddTaskAction(taskId, bridgeReAddDeps),}@@ -2317,6 +2346,7 @@ async function initializeMainProcess(): Promise<void> {motrixDatabase: motrixDb,geoipManager,proxyApplier,+ appliedDownloadProxyPolicy,pluginRegistry,pluginStateStore,// biome-ignore lint/style/noNonNullAssertion: assigned before registerCommandHandlers@@ -2427,9 +2457,13 @@ async function initializeMainProcess(): Promise<void> {}void mainProcessWork- .startStartup(() =>- startEngineAndRestore(engineSettings.sessionSaveInterval, adapter)- )+ .startStartup(async () => {+ // Finish the non-engine proxy scopes before startup commits the exact+ // aria2 route. This prevents a late non-Ready apply result from+ // overwriting the Ready snapshot.+ await proxyReady+ return startEngineAndRestore(engineSettings.sessionSaveInterval, adapter)+ }).catch((err) => {log.error({ err }, 'engine start/restore failed')})diff --git a/src/main/ipc/commands.test.ts b/src/main/ipc/commands.test.tsindex bd08c10f..918c6a52 100644--- a/src/main/ipc/commands.test.ts+++ b/src/main/ipc/commands.test.ts@@ -3,6 +3,7 @@ import { tmpdir } from 'node:os'import path from 'node:path'import { NOOP_TASK_ACTIVITY_RECORDER } from '@core/activity'import { Aria2Adapter } from '@core/engine/aria2/aria2-adapter'+import { AppliedDownloadProxyPolicy } from '@core/proxy/applied-download-proxy-policy'import { EXTERNAL_URLS } from '@shared/external-urls'import { Commands } from '@shared/protocol/commands'import { Events } from '@shared/protocol/events'@@ -118,6 +119,7 @@ function fakeCtx() {// (engine-ready gate); the handler tests must stub it or task// creation throws "supervisor.waitUntilReady is not a function".waitUntilReady: vi.fn().mockResolvedValue(undefined),+ assertReady: vi.fn(),},sessionManager: {save: vi.fn().mockResolvedValue(undefined),@@ -210,9 +212,10 @@ function fakeCtx() {notify: vi.fn(() => ({ fresh: true })),},proxyApplier: {- apply: vi.fn().mockResolvedValue(undefined),- applyAll: vi.fn().mockResolvedValue(undefined),+ apply: vi.fn().mockResolvedValue({ downloadProxy: 'unchanged' }),+ applyAll: vi.fn().mockResolvedValue({ downloadProxy: 'unchanged' }),},+ appliedDownloadProxyPolicy: new AppliedDownloadProxyPolicy({ noProxy: '' }),motrixDatabase: {database: undefined,deleteTask: vi.fn(),@@ -1327,13 +1330,13 @@ describe('Commands.UpdateSettings', () => {expect(ctx.supervisor.restart).not.toHaveBeenCalled()})- it('invokes proxyApplier.apply when proxy fields changed', async () => {+ it('reasserts every proxy scope when proxy fields changed', async () => {const ctx = fakeCtx()const before = makeSettingsLike(PROXY_OFF)const after = makeSettingsLike(PROXY_ON)const settingsManager = {...ctx.settingsManager,- get: vi.fn().mockReturnValueOnce(before).mockReturnValueOnce(after),+ get: vi.fn().mockReturnValueOnce(before).mockReturnValue(after),update: vi.fn().mockResolvedValue({ok: true,requiresRestart: false,@@ -1346,10 +1349,212 @@ describe('Commands.UpdateSettings', () => {protocolManager: { register: vi.fn() },} as unknown as CommandContext)await handlers[Commands.UpdateSettings]?.({ proxy: PROXY_ON })- expect(ctx.proxyApplier.apply).toHaveBeenCalledWith(PROXY_OFF, PROXY_ON)+ expect(ctx.proxyApplier.applyAll).toHaveBeenCalledWith(PROXY_ON)+ expect(ctx.proxyApplier.apply).not.toHaveBeenCalled()expect(ctx.supervisor.restart).not.toHaveBeenCalled()})+ it('commits the exact route returned by a proxy hot-apply', async () => {+ const ctx = fakeCtx()+ const policy = new AppliedDownloadProxyPolicy({ noProxy: '' })+ const before = makeSettingsLike(PROXY_OFF)+ const after = makeSettingsLike(PROXY_ON)+ const settingsManager = {+ ...ctx.settingsManager,+ get: vi.fn().mockReturnValueOnce(before).mockReturnValue(after),+ update: vi.fn().mockResolvedValue({+ ok: true,+ requiresRestart: false,+ changedRestartKeys: [],+ }),+ }+ ;(ctx.proxyApplier.applyAll as ReturnType<typeof vi.fn>).mockResolvedValue({+ downloadProxy: 'applied',+ appliedProxy: {+ allProxy: 'http://127.0.0.1:43123',+ noProxy: '.internal',+ },+ })+ const handlers = buildCommandHandlers({+ ...ctx,+ settingsManager,+ appliedDownloadProxyPolicy: policy,+ protocolManager: { register: vi.fn() },+ } as unknown as CommandContext)++ await handlers[Commands.UpdateSettings]?.({ proxy: PROXY_ON })++ expect(policy.snapshot()).toEqual({+ proxy: 'http://127.0.0.1:43123',+ noProxy: '.internal',+ })+ })++ it('force-reapplies the same proxy after a failed hot apply', async () => {+ const ctx = fakeCtx()+ const policy = new AppliedDownloadProxyPolicy({ noProxy: '' })+ const before = makeSettingsLike(PROXY_OFF)+ const after = makeSettingsLike(PROXY_ON)+ let current = before+ const settingsManager = {+ ...ctx.settingsManager,+ get: vi.fn(() => current),+ update: vi.fn(async () => {+ current = after+ return {+ ok: true,+ requiresRestart: false,+ changedRestartKeys: [],+ }+ }),+ }+ ;(ctx.proxyApplier.applyAll as ReturnType<typeof vi.fn>)+ .mockRejectedValueOnce(new Error('RPC failed'))+ .mockResolvedValueOnce({+ downloadProxy: 'applied',+ appliedProxy: {+ allProxy: 'http://p.example:80',+ noProxy: '',+ },+ })+ const handlers = buildCommandHandlers({+ ...ctx,+ settingsManager,+ appliedDownloadProxyPolicy: policy,+ protocolManager: { register: vi.fn() },+ } as unknown as CommandContext)++ await expect(+ handlers[Commands.UpdateSettings]?.({ proxy: PROXY_ON })+ ).rejects.toThrow('RPC failed')+ expect(policy.snapshot()).toBeNull()++ await expect(+ handlers[Commands.UpdateSettings]?.({ proxy: PROXY_ON })+ ).resolves.toBeDefined()+ expect(ctx.proxyApplier.apply).not.toHaveBeenCalled()+ expect(ctx.proxyApplier.applyAll).toHaveBeenCalledTimes(2)+ expect(ctx.proxyApplier.applyAll).toHaveBeenLastCalledWith(PROXY_ON)+ expect(policy.snapshot()).toEqual({+ proxy: 'http://p.example:80',+ noProxy: '',+ })+ })++ it('does not lose a download proxy when concurrent updates change different scopes', async () => {+ const ctx = fakeCtx()+ const policy = new AppliedDownloadProxyPolicy({ noProxy: '' })+ const proxyA = {+ ...PROXY_ON,+ scopes: { download: true, updateApp: false, updateTrackers: false },+ }+ const proxyB = {+ ...proxyA,+ scopes: { download: true, updateApp: true, updateTrackers: false },+ }+ const before = makeSettingsLike(PROXY_OFF)+ const afterA = makeSettingsLike(proxyA)+ const afterB = makeSettingsLike(proxyB)+ let current = before+ let releaseReader!: () => void+ const readerGate = new Promise<void>((resolve) => {+ releaseReader = resolve+ })+ const reader = policy.runWithSnapshot(async () => readerGate)+ const settingsManager = {+ ...ctx.settingsManager,+ get: vi.fn(() => current),+ update: vi.fn(async (partial: { proxy?: { scopes?: object } }) => {+ current = partial.proxy?.scopes === proxyA.scopes ? afterA : afterB+ return {+ ok: true,+ requiresRestart: false,+ changedRestartKeys: [],+ }+ }),+ }+ ;(ctx.proxyApplier.applyAll as ReturnType<typeof vi.fn>).mockImplementation(+ async (next) => ({+ downloadProxy: 'applied',+ appliedProxy: {+ allProxy: `http://${next.host}:${next.port}`,+ noProxy: '',+ },+ })+ )+ const handlers = buildCommandHandlers({+ ...ctx,+ settingsManager,+ appliedDownloadProxyPolicy: policy,+ protocolManager: { register: vi.fn() },+ } as unknown as CommandContext)++ const first = handlers[Commands.UpdateSettings]?.({ proxy: proxyA })+ await vi.waitFor(() => expect(current).toBe(afterA))+ const second = handlers[Commands.UpdateSettings]?.({ proxy: proxyB })+ await vi.waitFor(() => expect(current).toBe(afterB))+ releaseReader()+ await Promise.all([reader, first, second])++ expect(ctx.proxyApplier.apply).not.toHaveBeenCalled()+ expect(ctx.proxyApplier.applyAll).toHaveBeenCalledExactlyOnceWith(proxyB)+ expect(policy.snapshot()).toEqual({+ proxy: 'http://p.example:80',+ noProxy: '',+ })+ })++ it('applies proxy state before a later bridge side effect can fail', async () => {+ const ctx = fakeCtx()+ const policy = new AppliedDownloadProxyPolicy({ noProxy: '' })+ const proxy = {+ ...PROXY_ON,+ scopes: { download: true, updateApp: false, updateTrackers: false },+ }+ const before = makeSettingsLike(PROXY_OFF, {+ browserBridgeEnabled: false,+ })+ const after = makeSettingsLike(proxy, { browserBridgeEnabled: true })+ const settingsManager = {+ ...ctx.settingsManager,+ get: vi.fn().mockReturnValueOnce(before).mockReturnValue(after),+ update: vi.fn().mockResolvedValue({+ ok: true,+ requiresRestart: false,+ changedRestartKeys: [],+ }),+ }+ ;(ctx.proxyApplier.applyAll as ReturnType<typeof vi.fn>).mockResolvedValue({+ downloadProxy: 'applied',+ appliedProxy: {+ allProxy: 'http://p.example:80',+ noProxy: '',+ },+ })+ ctx.bridgeManager.setEnabled.mockRejectedValueOnce(+ new Error('bridge failed')+ )+ const handlers = buildCommandHandlers({+ ...ctx,+ settingsManager,+ appliedDownloadProxyPolicy: policy,+ protocolManager: { register: vi.fn() },+ } as unknown as CommandContext)++ await expect(+ handlers[Commands.UpdateSettings]?.({+ proxy,+ app: { browserBridgeEnabled: true },+ })+ ).rejects.toThrow('bridge failed')++ expect(ctx.proxyApplier.applyAll).toHaveBeenCalledWith(proxy)+ expect(policy.snapshot()).toEqual({+ proxy: 'http://p.example:80',+ noProxy: '',+ })+ })+it('hot-applies a changed default save directory', async () => {const ctx = fakeCtx()const before = makeSettingsLike(PROXY_OFF, {diff --git a/src/main/ipc/commands.ts b/src/main/ipc/commands.tsindex 727a05de..8532b1e4 100644--- a/src/main/ipc/commands.ts+++ b/src/main/ipc/commands.ts@@ -28,12 +28,17 @@ import {type RegistryExpectation,} from '@core/plugin/install/registry-expectation'import type { SourceInput } from '@core/plugin/install/source-resolver'+import { downloadUrlMoext } from '@core/plugin/install/url-fetcher'import type { PluginRegistry } from '@core/plugin/plugin-registry'import type { RegistryClient } from '@core/plugin/registry/registry-client'import { downloadRegistryMoext } from '@core/plugin/registry/registry-fetcher'import { scanForUpdates } from '@core/plugin/registry/update-scan'import type { PluginStateStore } from '@core/plugin/state/plugin-state-store'import type { BuiltinUpdater } from '@core/plugin/update/builtin-updater'+import {+ type AppliedDownloadProxyPolicy,+ UNAVAILABLE_APPLIED_DOWNLOAD_PROXY_POLICY,+} from '@core/proxy/applied-download-proxy-policy'import type { MotrixDatabase } from '@core/session/motrix-database'import type { SessionManager } from '@core/session/session-manager'import type { SettingsManager } from '@core/settings/settings-manager'@@ -169,6 +174,7 @@ export interface CommandContext {motrixDatabase: MotrixDatabasegeoipManager: GeoIPManagerproxyApplier: ReturnType<typeof createMainProxyApplier>+ appliedDownloadProxyPolicy: AppliedDownloadProxyPolicypluginRegistry: PluginRegistrypluginStateStore: PluginStateStorepluginHost: PluginHost@@ -252,6 +258,7 @@ export function buildCommandHandlers(ctx: CommandContext): CommandHandlerMap {fileCleanupService,eventBus,notificationCenter,+ appliedDownloadProxyPolicy,motrixDatabase,geoipManager,proxyApplier,@@ -300,6 +307,8 @@ export function buildCommandHandlers(ctx: CommandContext): CommandHandlerMap {const createDeps: CreateTaskDeps = {adapter,directResourceValidator: new DirectResourceValidatorService(),+ directResourceProxyPolicy:+ appliedDownloadProxyPolicy ?? UNAVAILABLE_APPLIED_DOWNLOAD_PROXY_POLICY,settingsManager,finalNamePicker,torrentMetaStore,@@ -326,6 +335,7 @@ export function buildCommandHandlers(ctx: CommandContext): CommandHandlerMap {await supervisor.waitUntilReady(ENGINE_READY_TIMEOUT_MS)await waitForTasksReady?.()},+ assertEngineReady: () => supervisor.assertReady(),// Lazy closures over bridgeManager.current so command-registration order// vs bridge bootstrap order never matters. When the bridge is disabled or// not yet started, resolveToMux returns null → HTTP fallback; dispatchMux@@ -402,6 +412,16 @@ export function buildCommandHandlers(ctx: CommandContext): CommandHandlerMap {runTaskMutation,publishTaskUpdate,publishTaskUpdateNow,+ getDirectResourceProxyOptions: () => {+ const snapshot = (+ appliedDownloadProxyPolicy ?? UNAVAILABLE_APPLIED_DOWNLOAD_PROXY_POLICY+ ).snapshot()+ return snapshot+ ? { ...snapshot, userAgent: settingsManager.getEngine().userAgent }+ : null+ },+ directResourceProxyPolicy:+ appliedDownloadProxyPolicy ?? UNAVAILABLE_APPLIED_DOWNLOAD_PROXY_POLICY,}createDeps.reuseExistingBt = (taskId) => reAddTask(taskId, reAddDeps)// The DNS fallback consumer retries through the same deps bundle as@@ -526,30 +546,7 @@ export function buildCommandHandlers(ctx: CommandContext): CommandHandlerMap {}case 'url': {const target = path.join(downloadDir, `download-${Date.now()}.moext`)- // Streaming via undici keeps the install boundary uniform with github.- // undici v8 moved redirect handling out of request() options into a- // composed dispatcher; follow redirects so a 30x URL yields the bytes.- const { Agent, interceptors, request } = await import('undici')- const dispatcher = new Agent().compose(- interceptors.redirect({ maxRedirections: 5 })- )- const res = await request(p.url, { dispatcher })- if (res.statusCode !== 200) {- throw new AppError(- ErrorCode.PluginManifestInvalid,- `plugin.install.url_download_failed: ${res.statusCode}`- )- }- const { createWriteStream } = await import('node:fs')- const { mkdir } = await import('node:fs/promises')- await mkdir(downloadDir, { recursive: true })- await new Promise<void>((resolve, reject) => {- const ws = createWriteStream(target)- res.body.on('error', reject)- ws.on('error', reject)- ws.on('finish', () => resolve())- res.body.pipe(ws)- })+ await downloadUrlMoext(p.url, target)return target}case 'local':@@ -951,6 +948,10 @@ export function buildCommandHandlers(ctx: CommandContext): CommandHandlerMap {// Build a patched partial that reflects the user's dialog choice.const partialObj = partial as Record<string, unknown> | null | undefined+ const proxySubmitted =+ typeof partialObj === 'object' &&+ partialObj !== null &&+ Object.hasOwn(partialObj, 'proxy')const appPartial = partialObj?.app as| { protocols?: { magnet?: unknown } }| undefined@@ -967,6 +968,28 @@ export function buildCommandHandlers(ctx: CommandContext): CommandHandlerMap {const result = await settingsManager.update(patched)const newFull = settingsManager.get()++ const proxySettingsChanged = proxyChanged(oldFull.proxy, newFull.proxy)+ if (+ proxySettingsChanged ||+ proxySubmitted ||+ appliedDownloadProxyPolicy.snapshot() === null+ ) {+ await appliedDownloadProxyPolicy.applyTransition(() => {+ const latestProxy = settingsManager.get().proxy+ // A command-local old value cannot describe concurrent updates+ // across independent scopes. Stale commands do no work; the one+ // matching the latest persisted value idempotently reasserts all+ // proxy consumers, including aria2's explicit direct route.+ return proxyChanged(newFull.proxy, latestProxy)+ ? Promise.resolve({ downloadProxy: 'unchanged' } as const)+ : proxyApplier.applyAll(latestProxy)+ })+ }++ // Proxy state is security-sensitive and settings are already durable at+ // this point. Apply/fail-closed before unrelated shell side effects can+ // reject and otherwise leave aria2 on the previous non-null route.let protocolAssociationApplied: boolean | undefinedif (oldFull.app.updateChannel !== newFull.app.updateChannel) {@@ -1001,10 +1024,6 @@ export function buildCommandHandlers(ctx: CommandContext): CommandHandlerMap {}}- if (proxyChanged(oldFull.proxy, newFull.proxy)) {- await proxyApplier.apply(oldFull.proxy, newFull.proxy)- }-if (oldFull.app.defaultSaveDir !== newFull.app.defaultSaveDir) {await supervisor.applyDefaultSaveDir(newFull.app.defaultSaveDir)}diff --git a/src/main/main-process-work-coordinator.test.ts b/src/main/main-process-work-coordinator.test.tsindex 85c06563..f2d64509 100644--- a/src/main/main-process-work-coordinator.test.ts+++ b/src/main/main-process-work-coordinator.test.ts@@ -214,7 +214,7 @@ describe('MainProcessWorkCoordinator', () => {path.resolve(process.cwd(), 'src/main/index.ts'),'utf8')- const restore = source.indexOf('await sessionManager.restore()')+ const restore = source.indexOf('await sessionManager.restore(')const recovery = source.indexOf('recoveryService.recoverOnStartup()')// The post-recovery snapshot bypasses the coalescing window: the// renderer's first paint must not wait 16 ms behind a startup barrier.diff --git a/src/server/index.ts b/src/server/index.tsindex 67921bae..f96ef0fc 100644--- a/src/server/index.ts+++ b/src/server/index.ts@@ -52,6 +52,7 @@ import { PluginInstaller } from '@core/plugin/install/plugin-installer'import { PluginRegistry } from '@core/plugin/plugin-registry'import { RegistryClient } from '@core/plugin/registry/registry-client'import { PluginStateStore } from '@core/plugin/state/plugin-state-store'+import { AppliedDownloadProxyPolicy } from '@core/proxy/applied-download-proxy-policy'import { ProxyBridgeManager } from '@core/proxy/proxy-bridge-manager'import { MotrixDatabase } from '@core/session/motrix-database'import { SessionManager } from '@core/session/session-manager'@@ -624,6 +625,7 @@ async function main() {}}const proxyBridge = new ProxyBridgeManager()+ const appliedDownloadProxyPolicy = new AppliedDownloadProxyPolicy()const supervisor = new EngineSupervisor(eventBus,settingsManager,@@ -632,7 +634,8 @@ async function main() {trustStore,rpcClient,adapter,- proxyBridge+ proxyBridge,+ appliedDownloadProxyPolicy)shutdownActions.stopEngine = async () => {try {@@ -641,7 +644,21 @@ async function main() {await proxyBridge.close()}}- const sessionManager = new SessionManager(taskManager, rpcClient, db, adapter)+ const sessionManager = new SessionManager(+ taskManager,+ rpcClient,+ db,+ adapter,+ undefined,+ undefined,+ undefined,+ () => {+ const snapshot = appliedDownloadProxyPolicy.snapshot()+ return snapshot+ ? { ...snapshot, userAgent: settingsManager.getEngine().userAgent }+ : null+ }+ )shutdownActions.drainSession = () => sessionManager.stopAndDrain()const persistTask = createServerPersistTask(taskManager, sessionManager)const persistTaskWithOccurrence =@@ -929,6 +946,7 @@ async function main() {fileCleanupService,eventBus,proxyApplier,+ appliedDownloadProxyPolicy,motrixDatabase: db,notificationCenter,taskPersistence: sessionManager,@@ -1131,13 +1149,15 @@ async function main() {})}- runShellAsyncWork('initial proxy apply', async () => {- try {- await proxyApplier.applyAll(settingsManager.getProxy())- } catch (err) {- log.warn({ err }, 'initial proxy apply failed')- }- })+ try {+ const initialProxySettings = settingsManager.getProxy()+ await appliedDownloadProxyPolicy.applyTransition(() =>+ proxyApplier.applyAll(initialProxySettings)+ )+ } catch (err) {+ log.warn({ err }, 'initial proxy apply failed')+ }+ if (!shellAsyncWork.isAccepting()) returnrunShellAsyncWork('tracker manager init', async () => {try {await trackerManager.init()@@ -1270,9 +1290,12 @@ async function main() {dnsFallbackConsumer.consume)- await sessionManager.restore()- if (!shellAsyncWork.isAccepting()) return- await sessionManager.recoverLegacyTaskLost()+ await appliedDownloadProxyPolicy.runWithSnapshot(+ async (_snapshot, lease) => {+ await sessionManager.restore(lease.assertCurrent)+ await sessionManager.recoverLegacyTaskLost(lease.assertCurrent)+ }+ )if (!shellAsyncWork.isAccepting()) return// Plan B: re-prime MagnetTracker's in-memory cache from the@@ -1453,6 +1476,7 @@ async function main() {const createTaskDeps = {adapter,directResourceValidator: new DirectResourceValidatorService(),+ directResourceProxyPolicy: appliedDownloadProxyPolicy,settingsManager,finalNamePicker,torrentMetaStore,@@ -1478,6 +1502,7 @@ async function main() {) => taskInspectorActivityRuntime.runTaskMutation(taskIds, operation),waitForEngineReady: () =>supervisor.waitUntilReady(ENGINE_READY_TIMEOUT_MS),+ assertEngineReady: () => supervisor.assertReady(),prepareSaveDir: (requested: string) =>downloadPathPolicy.prepareSaveDir(requested),reuseExistingBt: (taskId: string) =>@@ -1502,6 +1527,16 @@ async function main() {) => taskInspectorActivityRuntime.runTaskMutation(taskIds, operation),publishTaskUpdate,publishTaskUpdateNow,+ getDirectResourceProxyOptions: () => {+ const snapshot = appliedDownloadProxyPolicy.snapshot()+ return snapshot+ ? {+ ...snapshot,+ userAgent: settingsManager.getEngine().userAgent,+ }+ : null+ },+ directResourceProxyPolicy: appliedDownloadProxyPolicy,}const mdxpPort = parseServerPort(process.env.MOTRIX_MDXP_PORT,diff --git a/src/server/ipc/commands.test.ts b/src/server/ipc/commands.test.tsindex 27f52dd4..b7077e30 100644--- a/src/server/ipc/commands.test.ts+++ b/src/server/ipc/commands.test.ts@@ -11,6 +11,7 @@ import type { PluginHost } from '@core/plugin/host/plugin-host'import type { PluginInstaller } from '@core/plugin/install/plugin-installer'import type { PluginRegistry } from '@core/plugin/plugin-registry'import type { PluginStateStore } from '@core/plugin/state/plugin-state-store'+import { AppliedDownloadProxyPolicy } from '@core/proxy/applied-download-proxy-policy'import { MotrixDatabase } from '@core/session/motrix-database'import type { SettingsManager } from '@core/settings/settings-manager'import type { FileCleanupService } from '@core/task/file-cleanup-service'@@ -52,6 +53,8 @@ function makeFakeCtx() {applyEngineSettings: vi.fn().mockResolvedValue(undefined),applyAsyncDns: vi.fn().mockResolvedValue(undefined),applyDefaultSaveDir: vi.fn().mockResolvedValue(undefined),+ waitUntilReady: vi.fn().mockResolvedValue(undefined),+ assertReady: vi.fn(),} as unknown as EngineSupervisor,dnsFallback: { reset: vi.fn() },settingsManager: {@@ -62,6 +65,7 @@ function makeFakeCtx() {defaultSaveDir: '/tmp',magnetFileSelection: true,})),+ getEngine: vi.fn(() => ({ userAgent: 'Motrix/Test' })),} as unknown as SettingsManager,geoipManager: {triggerUpdate: vi.fn(),@@ -81,9 +85,10 @@ function makeFakeCtx() {fileCleanupService: {} as FileCleanupService,eventBus: { emit: vi.fn() } as unknown as EventBus,proxyApplier: {- apply: vi.fn().mockResolvedValue(undefined),- applyAll: vi.fn().mockResolvedValue(undefined),+ apply: vi.fn().mockResolvedValue({ downloadProxy: 'unchanged' }),+ applyAll: vi.fn().mockResolvedValue({ downloadProxy: 'unchanged' }),},+ appliedDownloadProxyPolicy: new AppliedDownloadProxyPolicy({ noProxy: '' }),motrixDatabase: {deleteMetadata: vi.fn(),} as unknown as MotrixDatabase,@@ -196,11 +201,11 @@ describe('server Commands.UpdateSettings', () => {expect(ctx.supervisor.stop).not.toHaveBeenCalled()})- it('invokes proxyApplier.apply when proxy fields changed', async () => {+ it('reasserts every proxy scope when proxy fields changed', async () => {const ctx = makeFakeCtx();(ctx.settingsManager.get as ReturnType<typeof vi.fn>).mockReturnValueOnce(makeSettings(PROXY_OFF))- .mockReturnValueOnce(makeSettings(PROXY_ON))+ .mockReturnValue(makeSettings(PROXY_ON));(ctx.settingsManager.update as ReturnType<typeof vi.fn>).mockResolvedValue({ ok: true, requiresRestart: false, changedRestartKeys: [] })@@ -208,7 +213,169 @@ describe('server Commands.UpdateSettings', () => {ctx as Parameters<typeof buildServerCommandHandlers>[0])await handlers[Commands.UpdateSettings]?.({ proxy: PROXY_ON })- expect(ctx.proxyApplier.apply).toHaveBeenCalledWith(PROXY_OFF, PROXY_ON)+ expect(ctx.proxyApplier.applyAll).toHaveBeenCalledWith(PROXY_ON)+ expect(ctx.proxyApplier.apply).not.toHaveBeenCalled()+ })++ it('commits the exact route returned by a successful proxy hot-apply', async () => {+ const ctx = makeFakeCtx()+ const policy = new AppliedDownloadProxyPolicy({ noProxy: '' })+ ;(ctx.settingsManager.get as ReturnType<typeof vi.fn>)+ .mockReturnValueOnce(makeSettings(PROXY_OFF))+ .mockReturnValue(makeSettings(PROXY_ON))+ ;(ctx.settingsManager.update as ReturnType<typeof vi.fn>).mockResolvedValue(+ { ok: true, requiresRestart: false, changedRestartKeys: [] }+ )+ ;(ctx.proxyApplier.applyAll as ReturnType<typeof vi.fn>).mockResolvedValue({+ downloadProxy: 'applied',+ appliedProxy: {+ allProxy: 'http://bridge-user:[email protected]:43123',+ noProxy: 'localhost',+ },+ })+ const handlers = buildServerCommandHandlers({+ ...ctx,+ appliedDownloadProxyPolicy: policy,+ } as Parameters<typeof buildServerCommandHandlers>[0])++ await handlers[Commands.UpdateSettings]?.({ proxy: PROXY_ON })++ expect(policy.snapshot()).toEqual({+ proxy: 'http://bridge-user:[email protected]:43123',+ noProxy: 'localhost',+ })+ })++ it('leaves the route unavailable when proxy hot-apply throws', async () => {+ const ctx = makeFakeCtx()+ const policy = new AppliedDownloadProxyPolicy({ noProxy: '' })+ ;(ctx.settingsManager.get as ReturnType<typeof vi.fn>)+ .mockReturnValueOnce(makeSettings(PROXY_OFF))+ .mockReturnValue(makeSettings(PROXY_ON))+ ;(ctx.settingsManager.update as ReturnType<typeof vi.fn>).mockResolvedValue(+ { ok: true, requiresRestart: false, changedRestartKeys: [] }+ )+ ;(ctx.proxyApplier.applyAll as ReturnType<typeof vi.fn>).mockRejectedValue(+ new Error('RPC failed')+ )+ const handlers = buildServerCommandHandlers({+ ...ctx,+ appliedDownloadProxyPolicy: policy,+ } as Parameters<typeof buildServerCommandHandlers>[0])++ await expect(+ handlers[Commands.UpdateSettings]?.({ proxy: PROXY_ON })+ ).rejects.toThrow('RPC failed')+ expect(policy.snapshot()).toBeNull()+ })++ it('force-reapplies the same proxy after a failed hot apply', async () => {+ const ctx = makeFakeCtx()+ const policy = new AppliedDownloadProxyPolicy({ noProxy: '' })+ const before = makeSettings(PROXY_OFF)+ const after = makeSettings(PROXY_ON)+ let current = before+ ;(ctx.settingsManager.get as ReturnType<typeof vi.fn>).mockImplementation(+ () => current+ )+ ;(+ ctx.settingsManager.update as ReturnType<typeof vi.fn>+ ).mockImplementation(async () => {+ current = after+ return { ok: true, requiresRestart: false, changedRestartKeys: [] }+ })+ ;(ctx.proxyApplier.applyAll as ReturnType<typeof vi.fn>)+ .mockRejectedValueOnce(new Error('RPC failed'))+ .mockResolvedValueOnce({+ downloadProxy: 'applied',+ appliedProxy: {+ allProxy: 'http://p.example:80',+ noProxy: '',+ },+ })+ const handlers = buildServerCommandHandlers({+ ...ctx,+ appliedDownloadProxyPolicy: policy,+ } as Parameters<typeof buildServerCommandHandlers>[0])++ await expect(+ handlers[Commands.UpdateSettings]?.({ proxy: PROXY_ON })+ ).rejects.toThrow('RPC failed')+ expect(policy.snapshot()).toBeNull()++ await expect(+ handlers[Commands.UpdateSettings]?.({ proxy: PROXY_ON })+ ).resolves.toBeDefined()+ expect(ctx.proxyApplier.apply).not.toHaveBeenCalled()+ expect(ctx.proxyApplier.applyAll).toHaveBeenCalledTimes(2)+ expect(ctx.proxyApplier.applyAll).toHaveBeenLastCalledWith(PROXY_ON)+ expect(policy.snapshot()).toEqual({+ proxy: 'http://p.example:80',+ noProxy: '',+ })+ })++ it('does not lose a download proxy when concurrent updates change different scopes', async () => {+ const ctx = makeFakeCtx()+ const policy = new AppliedDownloadProxyPolicy({ noProxy: '' })+ const proxyA = {+ ...PROXY_ON,+ scopes: { download: true, updateApp: false, updateTrackers: false },+ }+ const proxyB = {+ ...proxyA,+ scopes: { download: true, updateApp: true, updateTrackers: false },+ }+ const before = makeSettings(PROXY_OFF)+ const afterA = makeSettings(proxyA)+ const afterB = makeSettings(proxyB)+ let current = before+ let releaseReader!: () => void+ let readerStarted = false+ const readerGate = new Promise<void>((resolve) => {+ releaseReader = resolve+ })+ const reader = policy.runWithSnapshot(async () => {+ readerStarted = true+ await readerGate+ })+ await vi.waitFor(() => expect(readerStarted).toBe(true))+ ;(ctx.settingsManager.get as ReturnType<typeof vi.fn>).mockImplementation(+ () => current+ )+ ;(+ ctx.settingsManager.update as ReturnType<typeof vi.fn>+ ).mockImplementation(async (partial: { proxy?: { scopes?: object } }) => {+ current = partial.proxy?.scopes === proxyA.scopes ? afterA : afterB+ return { ok: true, requiresRestart: false, changedRestartKeys: [] }+ })+ ;(ctx.proxyApplier.applyAll as ReturnType<typeof vi.fn>).mockImplementation(+ async (next) => ({+ downloadProxy: 'applied',+ appliedProxy: {+ allProxy: `http://${next.host}:${next.port}`,+ noProxy: '',+ },+ })+ )+ const handlers = buildServerCommandHandlers({+ ...ctx,+ appliedDownloadProxyPolicy: policy,+ } as Parameters<typeof buildServerCommandHandlers>[0])++ const first = handlers[Commands.UpdateSettings]?.({ proxy: proxyA })+ await vi.waitFor(() => expect(current).toBe(afterA))+ const second = handlers[Commands.UpdateSettings]?.({ proxy: proxyB })+ await vi.waitFor(() => expect(current).toBe(afterB))+ releaseReader()+ await Promise.all([reader, first, second])++ expect(ctx.proxyApplier.apply).not.toHaveBeenCalled()+ expect(ctx.proxyApplier.applyAll).toHaveBeenCalledExactlyOnceWith(proxyB)+ expect(policy.snapshot()).toEqual({+ proxy: 'http://p.example:80',+ noProxy: '',+ })})it('hot-applies a changed default save directory', async () => {diff --git a/src/server/ipc/commands.ts b/src/server/ipc/commands.tsindex bb4ec6c6..d395ebc1 100644--- a/src/server/ipc/commands.ts+++ b/src/server/ipc/commands.ts@@ -21,6 +21,10 @@ import type { PluginHost } from '@core/plugin/host/plugin-host'import type { PluginInstaller } from '@core/plugin/install/plugin-installer'import type { PluginRegistry } from '@core/plugin/plugin-registry'import type { PluginStateStore } from '@core/plugin/state/plugin-state-store'+import {+ type AppliedDownloadProxyPolicy,+ UNAVAILABLE_APPLIED_DOWNLOAD_PROXY_POLICY,+} from '@core/proxy/applied-download-proxy-policy'import type { MotrixDatabase } from '@core/session/motrix-database'import type { SessionManager } from '@core/session/session-manager'import type { SettingsManager } from '@core/settings/settings-manager'@@ -100,6 +104,7 @@ export interface ServerCommandContext {fileCleanupService: FileCleanupServiceeventBus: EventBusproxyApplier: ReturnType<typeof createServerProxyApplier>+ appliedDownloadProxyPolicy: AppliedDownloadProxyPolicymotrixDatabase: MotrixDatabasenotificationCenter: NotificationCentertaskPersistence: Pick<SessionManager, 'runExclusivePersistence'>@@ -158,6 +163,7 @@ export function buildServerCommandHandlers(fileCleanupService,eventBus,proxyApplier,+ appliedDownloadProxyPolicy,motrixDatabase,notificationCenter,taskPersistence,@@ -220,6 +226,8 @@ export function buildServerCommandHandlers(const createDeps: CreateTaskDeps = {adapter,directResourceValidator: new DirectResourceValidatorService(),+ directResourceProxyPolicy:+ appliedDownloadProxyPolicy ?? UNAVAILABLE_APPLIED_DOWNLOAD_PROXY_POLICY,settingsManager,finalNamePicker,torrentMetaStore,@@ -241,6 +249,7 @@ export function buildServerCommandHandlers(runTaskMutation,waitForEngineReady: () =>supervisor.waitUntilReady(ENGINE_READY_TIMEOUT_MS),+ assertEngineReady: () => supervisor.assertReady(),prepareSaveDir: (requested: string) =>downloadPathPolicy.prepareSaveDir(requested),}@@ -286,6 +295,16 @@ export function buildServerCommandHandlers(runTaskMutation,publishTaskUpdate,publishTaskUpdateNow,+ getDirectResourceProxyOptions: () => {+ const snapshot = (+ appliedDownloadProxyPolicy ?? UNAVAILABLE_APPLIED_DOWNLOAD_PROXY_POLICY+ ).snapshot()+ return snapshot+ ? { ...snapshot, userAgent: settingsManager.getEngine().userAgent }+ : null+ },+ directResourceProxyPolicy:+ appliedDownloadProxyPolicy ?? UNAVAILABLE_APPLIED_DOWNLOAD_PROXY_POLICY,}createDeps.reuseExistingBt = (taskId) => reAddTask(taskId, reAddDeps)// The DNS fallback consumer retries through the same deps bundle as@@ -626,14 +645,31 @@ export function buildServerCommandHandlers(app: { ...saveDirPatch.data.app, defaultSaveDir },}}+ const proxySubmitted =+ typeof validatedPartial === 'object' &&+ validatedPartial !== null &&+ Object.hasOwn(validatedPartial, 'proxy')const oldFull = settingsManager.get()const result = await settingsManager.update(validatedPartial as Parameters<typeof settingsManager.update>[0])const newFull = settingsManager.get()- if (proxyChanged(oldFull.proxy, newFull.proxy)) {- await proxyApplier.apply(oldFull.proxy, newFull.proxy)+ const proxySettingsChanged = proxyChanged(oldFull.proxy, newFull.proxy)+ if (+ proxySettingsChanged ||+ proxySubmitted ||+ appliedDownloadProxyPolicy.snapshot() === null+ ) {+ await appliedDownloadProxyPolicy.applyTransition(() => {+ const latestProxy = settingsManager.get().proxy+ // Re-check after acquiring the writer, then reassert the entire+ // latest proxy state. Incremental command-local diffs lose updates+ // when concurrent commands modify different proxy scopes.+ return proxyChanged(newFull.proxy, latestProxy)+ ? Promise.resolve({ downloadProxy: 'unchanged' } as const)+ : proxyApplier.applyAll(latestProxy)+ })}if (oldFull.app.defaultSaveDir !== newFull.app.defaultSaveDir) {diff --git a/src/server/plugin/install-service.test.ts b/src/server/plugin/install-service.test.tsindex 14e9466b..cd4fe024 100644--- a/src/server/plugin/install-service.test.ts+++ b/src/server/plugin/install-service.test.ts@@ -130,6 +130,86 @@ describe('ServerPluginInstallService', () => {)})+ it('cancels a non-ok URL response body', async () => {+ const cancel = vi.fn()+ const response = new Response(+ new ReadableStream<Uint8Array>({+ start(controller) {+ controller.enqueue(new TextEncoder().encode('server error'))+ },+ cancel,+ }),+ { status: 503 }+ )+ const fetchImpl = vi.fn(async () => response) as unknown as typeof fetch+ const { service, stage } = makeService({ fetchImpl })++ await expect(+ service.stage({+ sourceType: 'url',+ url: 'https://plugins.example/test.moext',+ })+ ).rejects.toMatchObject({+ message: 'plugin.install.url_download_failed: 503',+ })++ expect(cancel).toHaveBeenCalledOnce()+ expect(stage).not.toHaveBeenCalled()+ })++ it('cancels a body rejected by its declared content length', async () => {+ const cancel = vi.fn()+ const response = new Response(+ new ReadableStream<Uint8Array>({+ start(controller) {+ controller.enqueue(new Uint8Array([1]))+ },+ cancel,+ }),+ {+ status: 200,+ headers: { 'content-length': String(5 * 1024 * 1024 + 1) },+ }+ )+ const fetchImpl = vi.fn(async () => response) as unknown as typeof fetch+ const { service, stage } = makeService({ fetchImpl })++ await expect(+ service.stage({+ sourceType: 'url',+ url: 'https://plugins.example/test.moext',+ })+ ).rejects.toMatchObject({ message: 'plugin.install.package_too_large' })++ expect(cancel).toHaveBeenCalledOnce()+ expect(stage).not.toHaveBeenCalled()+ })++ it('cancels a streamed body when actual bytes exceed the limit', async () => {+ const cancel = vi.fn()+ const response = new Response(+ new ReadableStream<Uint8Array>({+ start(controller) {+ controller.enqueue(new Uint8Array(5 * 1024 * 1024 + 1))+ },+ cancel,+ }),+ { status: 200 }+ )+ const fetchImpl = vi.fn(async () => response) as unknown as typeof fetch+ const { service, stage } = makeService({ fetchImpl })++ await expect(+ service.stage({+ sourceType: 'url',+ url: 'https://plugins.example/test.moext',+ })+ ).rejects.toMatchObject({ message: 'plugin.install.package_too_large' })++ expect(cancel).toHaveBeenCalledOnce()+ expect(stage).not.toHaveBeenCalled()+ })+it('rejects non-http URL sources before fetching', async () => {const fetchImpl = vi.fn() as unknown as typeof fetchconst { service } = makeService({ fetchImpl })diff --git a/src/server/plugin/install-service.ts b/src/server/plugin/install-service.tsindex 71533443..9b55ece6 100644--- a/src/server/plugin/install-service.ts+++ b/src/server/plugin/install-service.ts@@ -70,12 +70,31 @@ function pathIsInside(root: string, candidate: string): boolean {)}+async function cancelResponseBody(response: Response): Promise<void> {+ try {+ await response.body?.cancel()+ } catch {+ // Preserve the install error if cancellation races a closed/erroring body.+ }+}++async function cancelReader(+ reader: ReadableStreamDefaultReader<Uint8Array>+): Promise<void> {+ try {+ await reader.cancel()+ } catch {+ // Cancellation is best-effort and must not mask the bounded-read error.+ }+}+async function readResponseBounded(response: Response): Promise<Buffer> {const declaredLength = Number(response.headers.get('content-length'))if (Number.isFinite(declaredLength) &&declaredLength > MAX_PLUGIN_PACKAGE_BYTES) {+ await cancelResponseBody(response)throw new AppError(ErrorCode.PluginManifestInvalid,'plugin.install.package_too_large'@@ -91,18 +110,24 @@ async function readResponseBounded(response: Response): Promise<Buffer> {const chunks: Uint8Array[] = []let total = 0const reader = response.body.getReader()- for (;;) {- const { done, value } = await reader.read()- if (done) break- total += value.byteLength- if (total > MAX_PLUGIN_PACKAGE_BYTES) {- await reader.cancel()- throw new AppError(- ErrorCode.PluginManifestInvalid,- 'plugin.install.package_too_large'- )+ try {+ for (;;) {+ const { done, value } = await reader.read()+ if (done) break+ total += value.byteLength+ if (total > MAX_PLUGIN_PACKAGE_BYTES) {+ throw new AppError(+ ErrorCode.PluginManifestInvalid,+ 'plugin.install.package_too_large'+ )+ }+ chunks.push(value)}- chunks.push(value)+ } catch (cause) {+ await cancelReader(reader)+ throw cause+ } finally {+ reader.releaseLock()}return Buffer.concat(chunks, total)}@@ -162,6 +187,7 @@ export class ServerPluginInstallService {const url = this.parseHttpUrl(payload.url)const response = await this.fetchImpl(url, { redirect: 'follow' })if (!response.ok) {+ await cancelResponseBody(response)throw new AppError(ErrorCode.PluginManifestInvalid,`plugin.install.url_download_failed: ${response.status}`diff --git a/src/server/polling-publication.test.ts b/src/server/polling-publication.test.tsindex 67bf277f..9bc1d58f 100644--- a/src/server/polling-publication.test.ts+++ b/src/server/polling-publication.test.ts@@ -38,7 +38,7 @@ describe('server poll tick publication', () => {path.resolve(process.cwd(), 'src/server/index.ts'),'utf8')- const restore = source.indexOf('await sessionManager.restore()')+ const restore = source.indexOf('await sessionManager.restore(')const recovery = source.indexOf('recoveryService.recoverOnStartup()')const publish = source.indexOf('publishTaskUpdateNow()', recovery)diff --git a/src/shared/locales/en-US.json b/src/shared/locales/en-US.jsonindex 194ba7e0..16be472e 100644--- a/src/shared/locales/en-US.json+++ b/src/shared/locales/en-US.json@@ -1343,7 +1343,7 @@"showPassword": "Show password","hidePassword": "Hide password","bypass": "Bypass list",- "bypassDesc": "One host per line. Wildcards like `*.local` are allowed.",+ "bypassDesc": "One exact host or CIDR per line. Use a leading dot like `.local` for subdomains (not the root domain); `*` wildcards are not supported for downloads.","bypassScopeNote": "Downloads + App update only","scopes": "Apply to","scopesDesc": "Choose which kinds of traffic go through the proxy.",diff --git a/src/shared/locales/zh-CN.json b/src/shared/locales/zh-CN.jsonindex 12c25386..fd258f76 100644--- a/src/shared/locales/zh-CN.json+++ b/src/shared/locales/zh-CN.json@@ -1330,7 +1330,7 @@"showPassword": "显示密码","hidePassword": "隐藏密码","bypass": "绕过列表",- "bypassDesc": "每行一台主机,支持 `*.local` 通配符。",+ "bypassDesc": "每行填写一个精确主机或 CIDR。用 `.local` 这样的前导点匹配子域(不含根域);下载代理不支持 `*` 通配符。","bypassScopeNote": "仅作用于下载与应用更新","scopes": "应用于","scopesDesc": "选择哪些流量通过代理。",diff --git a/src/shared/locales/zh-TW.json b/src/shared/locales/zh-TW.jsonindex ee450dfe..62630cae 100644--- a/src/shared/locales/zh-TW.json+++ b/src/shared/locales/zh-TW.json@@ -1330,7 +1330,7 @@"showPassword": "顯示密碼","hidePassword": "隱藏密碼","bypass": "略過清單",- "bypassDesc": "每行一個主機。可使用 `*.local` 等萬用字元。",+ "bypassDesc": "每行填寫一個精確主機或 CIDR。使用 `.local` 這類前導點比對子網域(不含根網域);下載 Proxy 不支援 `*` 萬用字元。","bypassScopeNote": "僅下載與應用程式更新","scopes": "套用至","scopesDesc": "選擇哪些流量要通過 Proxy。",diff --git a/src/shared/schemas/direct-replay-recipe.ts b/src/shared/schemas/direct-replay-recipe.tsindex 7734b179..16bb235f 100644--- a/src/shared/schemas/direct-replay-recipe.ts+++ b/src/shared/schemas/direct-replay-recipe.ts@@ -9,6 +9,7 @@ export const directReplayRequestModifierSchema = z.enum(['headers','proxy','extraEngineOptions',+ 'engineGlobalOptions',])const validatorValueSchema = z@@ -49,7 +50,7 @@ const directReplayV1Schema = z.object({version: z.literal(1),connections: z.number().int().min(1).max(128).optional(),- requestModifiers: z.array(directReplayRequestModifierSchema).max(3),+ requestModifiers: z.array(directReplayRequestModifierSchema).max(4),replayability: z.enum(['uri-only', 'requires-credentials']),resourceValidator: directResourceValidatorSchema.optional(),})diff --git a/src/shared/schemas/engine-settings.ts b/src/shared/schemas/engine-settings.tsindex a9947d68..64bda97f 100644--- a/src/shared/schemas/engine-settings.ts+++ b/src/shared/schemas/engine-settings.ts@@ -11,6 +11,15 @@ export { MAX_CONNECTIONS_PER_SERVER } from '../constants/engine-performance-profconst AUTO_PERFORMANCE = ENGINE_PERFORMANCE_PROFILES.auto+const controlFreeString = () =>+ z.string().refine((value) => {+ for (const character of value) {+ const codePoint = character.codePointAt(0) ?? 0+ if (codePoint <= 0x1f || codePoint === 0x7f) return false+ }+ return true+ })+export const engineSettingsSchema = z.object({// RPC & engine startup (RESTART)@@ -18,7 +27,7 @@ export const engineSettingsSchema = z// Missing/invalid persisted values are a first-run sentinel seeded by// SettingsManager while loading; live updates reject non-strings. An// explicitly persisted empty string disables tokens.- rpcSecret: z.string().catch(''),+ rpcSecret: controlFreeString().catch(''),listenPort: z.number().int().min(1024).max(65535).catch(6881),dhtListenPort: z.number().int().min(1024).max(65535).catch(6881),dhtEnabled: z.boolean().catch(true),@@ -36,7 +45,7 @@ export const engineSettingsSchema = zminSplitSize: z.number().min(1048576).catch(AUTO_PERFORMANCE.minSplitSize),// Network reliability (HOT)- userAgent: z.string().catch('Motrix/2.0'),+ userAgent: controlFreeString().catch('Motrix/2.0'),connectTimeout: z.number().int().min(1).max(600).catch(30),socketTimeout: z.number().int().min(1).max(600).catch(30),maxTries: z.number().int().min(0).max(100).catch(5),diff --git a/src/shared/schemas/proxy-settings.test.ts b/src/shared/schemas/proxy-settings.test.tsindex 3784ef13..515bebdd 100644--- a/src/shared/schemas/proxy-settings.test.ts+++ b/src/shared/schemas/proxy-settings.test.ts@@ -57,6 +57,20 @@ describe('proxySettingsSchema', () => {expect(proxySettingsSchema.parse({ bypass: long }).bypass).toEqual([])})+ it('drops proxy fields and bypass lists containing control characters', () => {+ const parsed = proxySettingsSchema.parse({+ host: 'proxy.example\nhttp-proxy=evil',+ user: 'user\rname',+ password: 'pass\u007fword',+ bypass: ['localhost', 'safe\nhttp-proxy=evil'],+ })++ expect(parsed.host).toBe('')+ expect(parsed.user).toBe('')+ expect(parsed.password).toBe('')+ expect(parsed.bypass).toEqual([])+ })+it('parses partial scopes', () => {const r = proxySettingsSchema.parse({scopes: { download: true },diff --git a/src/shared/schemas/proxy-settings.ts b/src/shared/schemas/proxy-settings.tsindex dc977fa9..8e30a85e 100644--- a/src/shared/schemas/proxy-settings.ts+++ b/src/shared/schemas/proxy-settings.ts@@ -1,14 +1,28 @@import type { ProxySettings } from '@shared/types/settings'import { z } from 'zod'+const withoutControlCharacters = (max: number) =>+ z+ .string()+ .max(max)+ .refine((value) => !hasC0OrDel(value))++function hasC0OrDel(value: string): boolean {+ for (const character of value) {+ const codePoint = character.codePointAt(0) ?? 0+ if (codePoint <= 0x1f || codePoint === 0x7f) return true+ }+ return false+}+export const proxySettingsSchema = z.object({enabled: z.boolean().catch(false),protocol: z.enum(['http', 'https', 'socks5']).catch('http'),- host: z.string().max(253).catch(''),+ host: withoutControlCharacters(253).catch(''),port: z.number().int().min(1).max(65535).catch(8080),- user: z.string().max(256).catch(''),- password: z.string().max(256).catch(''),- bypass: z.array(z.string().max(253)).max(64).catch([]),+ user: withoutControlCharacters(256).catch(''),+ password: withoutControlCharacters(256).catch(''),+ bypass: z.array(withoutControlCharacters(253)).max(64).catch([]),scopes: z.object({download: z.boolean().catch(false),