Skip to content

A full-featured download manager.

12.0 KB
Raw Blame
import { createHash } from 'node:crypto'
import path from 'node:path'
import { containsOnlyVideoFiles } from '@shared/constants/file-types'
import { parseEngineTorrent as parseTorrent } from '@shared/lib/engine-torrent'
import type { DownloadTask } from '@shared/types/task'
import { outputNameIdentity } from './output-path-identity'

const STORAGE_ROOT = '.motrix'
const PAYLOAD_ENTRY = 'p'
const LAYOUT_KEY = 'btStorageLayout'

export interface BtStorageLayoutV1 {
  version: 1
  strategy: 'indexed-staging'
  workspacePath: string
  payloadEntry: typeof PAYLOAD_ENTRY
  torrentRootName: string
  multiFile: boolean
}

export interface BtDirectStorageLayout {
  version: 2
  strategy: 'direct'
  /** Null means the engine owns the paths inside the final container. */
  torrentRootName: string | null
  multiFile: boolean | null
  finalized: boolean
}

export function createBtDirectStoragePlan(
  finalPath: string,
  parsed: ParsedBtFileLayout | null,
  torrentMetaPath?: string | null
) {
  const layout: BtDirectStorageLayout = {
    version: 2,
    strategy: 'direct',
    torrentRootName: parsed?.torrentRootName ?? null,
    multiFile: parsed?.multiFile ?? null,
    finalized: false,
  }
  return {
    layout,
    ...buildBtDirectOutputPaths(finalPath, parsed, torrentMetaPath),
  }
}

/** Keep engine metadata separate while payloads go directly to final paths. */
export function buildBtDirectOutputPaths(
  finalPath: string,
  parsed: ParsedBtFileLayout | null,
  torrentMetaPath?: string | null
): {
  saveDir: string
  outputRoot?: string
  outputFilePaths?: BtOutputFilePath[]
} {
  if (!parsed) return { saveDir: finalPath }
  if (!torrentMetaPath)
    throw new Error('BT requires a durable torrent metadata path')
  const saveDir = `${torrentMetaPath}.state`
  if (!parsed.multiFile)
    return {
      saveDir,
      outputRoot: path.dirname(finalPath),
      outputFilePaths: buildFinalOutputFilePaths(parsed, finalPath),
    }
  return {
    saveDir,
    outputRoot: finalPath,
    outputFilePaths: parsed.files.map((file) => {
      if (!file.pathInsideRoot)
        throw new UnsafeTorrentPathError('Multi-file torrent has an empty path')
      return { fileIndex: file.fileIndex, relativePath: file.pathInsideRoot }
    }),
  }
}

export function getBtDirectStorageLayout(
  task: Pick<DownloadTask, 'instances'>
): BtDirectStorageLayout | null {
  for (const instance of task.instances ?? []) {
    const value = instance.payload?.[LAYOUT_KEY] as
      | Partial<BtDirectStorageLayout>
      | undefined
    if (
      value?.version === 2 &&
      value.strategy === 'direct' &&
      typeof value.finalized === 'boolean' &&
      ((value.torrentRootName === null && value.multiFile === null) ||
        (typeof value.torrentRootName === 'string' &&
          isSafePathComponent(value.torrentRootName) &&
          typeof value.multiFile === 'boolean'))
    )
      return value as BtDirectStorageLayout
  }
  return null
}

export function markBtDirectOutputFinalized(task: DownloadTask): void {
  if (!getBtDirectStorageLayout(task)) return
  for (const instance of task.instances) {
    const layout = instance.payload[LAYOUT_KEY]
    if (
      layout &&
      typeof layout === 'object' &&
      'version' in layout &&
      layout.version === 2
    ) {
      instance.payload = {
        ...instance.payload,
        [LAYOUT_KEY]: { ...layout, finalized: true },
      }
    }
  }
}

export interface BtOutputFilePath {
  /** Domain-native, zero-based torrent file index. */
  fileIndex: number
  /** Path relative to outputRoot, or the engine saveDir when absent. */
  relativePath: string
}

export interface ParsedBtFileLayout {
  totalBytes?: number
  /** Canonical lowercase hexadecimal BitTorrent content identity. */
  infoHash: string
  torrentRootName: string
  multiFile: boolean
  isPrivate: boolean
  files: Array<{ fileIndex: number; pathInsideRoot: string | null }>
}

export class UnsafeTorrentPathError extends Error {
  constructor(message: string) {
    super(message)
    this.name = 'UnsafeTorrentPathError'
  }
}

/**
 * Parse and validate the paths declared by untrusted torrent metadata.
 * The engine projection preserves raw component boundaries; relative paths are
 * mapped into the selected output directory.
 */
export async function parseBtFileLayout(
  metadata: Uint8Array,
  selectedFiles?: readonly number[]
): Promise<ParsedBtFileLayout> {
  const parsed = await parseTorrent(metadata)
  if (
    typeof parsed.infoHash !== 'string' ||
    !/^[a-f0-9]{40}$/i.test(parsed.infoHash)
  ) {
    throw new UnsafeTorrentPathError('Torrent contains no valid info hash')
  }
  const torrentRootName = validatePathComponent(parsed.name, 'torrent name')
  const parsedFiles = parsed.files ?? []
  if (parsedFiles.length === 0) {
    throw new UnsafeTorrentPathError('Torrent contains no files')
  }

  const selected = selectedFiles?.length ? new Set(selectedFiles) : null
  if (
    selected &&
    [...selected].some(
      (index) =>
        !Number.isInteger(index) || index < 0 || index >= parsedFiles.length
    )
  )
    throw new Error('Torrent file selection is outside the file list')
  const multiFile = parsed.multiFile === true
  const files = parsedFiles.map((file, fileIndex) => {
    const components = file.pathComponents.map((component) =>
      validatePathComponent(component, 'torrent file path')
    )
    if (components[0] !== torrentRootName) {
      throw new UnsafeTorrentPathError(
        `Torrent file ${fileIndex} is outside its declared root directory`
      )
    }
    if (!multiFile) {
      if (components.length !== 1) {
        throw new UnsafeTorrentPathError(
          `Single-file torrent ${fileIndex} has a nested path`
        )
      }
      return { fileIndex, pathInsideRoot: null }
    }
    if (components.length < 2) {
      throw new UnsafeTorrentPathError(
        `Multi-file torrent ${fileIndex} has an empty path`
      )
    }
    return {
      fileIndex,
      pathInsideRoot: path.join(...components.slice(1)),
    }
  })

  const mapped = new Map<string, (typeof parsedFiles)[number]>()
  for (const [index, entry] of files.entries()) {
    const key = outputNameIdentity(entry.pathInsideRoot ?? torrentRootName)
    const previous = mapped.get(key)
    const source = parsedFiles[index]
    if (
      previous &&
      !(previous.padding && source.padding && previous.length === source.length)
    )
      throw new UnsafeTorrentPathError('Overlapping torrent paths')
    mapped.set(key, source)
  }
  for (const key of mapped.keys()) {
    const parts = key.split(path.sep)
    for (let i = 1; i < parts.length; i++)
      if (mapped.has(parts.slice(0, i).join(path.sep)))
        throw new UnsafeTorrentPathError('Overlapping torrent paths')
  }

  return {
    totalBytes: parsedFiles.reduce(
      (sum, file, index) =>
        sum + (!selected || selected.has(index) ? file.length : 0),
      0
    ),
    infoHash: parsed.infoHash.toLowerCase(),
    torrentRootName,
    multiFile,
    isPrivate: parsed.private === true,
    files,
  }
}

/**
 * Enable preview-oriented piece ordering only when validated torrent metadata
 * proves that every declared file is a video. A mixed torrent stays on the
 * engine's normal piece policy even when the user selects only its videos.
 */
export function shouldPrioritizeBtPreviewPieces(
  parsed: ParsedBtFileLayout
): boolean {
  return containsOnlyVideoFiles(
    parsed.files.map((file) => file.pathInsideRoot ?? parsed.torrentRootName)
  )
}

/** Parse failures are an explicit "not proven video-only" result. */
export async function shouldPrioritizeBtPreviewPiecesFromMetadata(
  metadata: Uint8Array
): Promise<boolean> {
  try {
    return shouldPrioritizeBtPreviewPieces(await parseBtFileLayout(metadata))
  } catch {
    return false
  }
}

export function btWorkspacePath(taskId: string, saveDir: string): string {
  const workspaceId = createHash('sha256')
    .update(taskId)
    .digest('hex')
    .slice(0, 20)
  return path.join(saveDir, STORAGE_ROOT, workspaceId)
}

export function buildStagingOutputFilePaths(
  parsed: ParsedBtFileLayout,
  layout: BtStorageLayoutV1
): BtOutputFilePath[] {
  assertLayoutMatchesMetadata(layout, parsed)
  return parsed.files.map((file) => ({
    fileIndex: file.fileIndex,
    relativePath:
      file.pathInsideRoot === null
        ? layout.payloadEntry
        : path.join(layout.payloadEntry, file.pathInsideRoot),
  }))
}

export function buildFinalOutputFilePaths(
  parsed: ParsedBtFileLayout,
  finalPath: string,
  expectedLayout?: BtStorageLayoutV1
): BtOutputFilePath[] {
  if (expectedLayout) assertLayoutMatchesMetadata(expectedLayout, parsed)
  const finalEntry = validatePathComponent(
    path.basename(finalPath),
    'final name'
  )
  return parsed.files.map((file) => ({
    fileIndex: file.fileIndex,
    relativePath:
      file.pathInsideRoot === null
        ? finalEntry
        : path.join(finalEntry, file.pathInsideRoot),
  }))
}

export function btStoragePayload(
  layout: BtStorageLayoutV1 | BtDirectStorageLayout
): Record<string, unknown> {
  return { [LAYOUT_KEY]: layout }
}

export function getBtStorageLayout(
  task: Pick<DownloadTask, 'instances' | 'saveDir' | 'diskPath' | 'finalPath'>
): BtStorageLayoutV1 | null {
  for (const instance of task.instances) {
    const candidate = instance.payload[LAYOUT_KEY]
    if (isBtStorageLayout(candidate) && isLayoutOwnedByTask(candidate, task)) {
      return candidate
    }
  }
  return null
}

export function getBtPayloadPath(
  task: Pick<DownloadTask, 'instances' | 'saveDir' | 'diskPath' | 'finalPath'>
): string | null {
  const layout = getBtStorageLayout(task)
  return layout ? path.join(layout.workspacePath, layout.payloadEntry) : null
}

function assertLayoutMatchesMetadata(
  layout: BtStorageLayoutV1,
  parsed: ParsedBtFileLayout
): void {
  if (
    layout.torrentRootName !== parsed.torrentRootName ||
    layout.multiFile !== parsed.multiFile
  ) {
    throw new Error(
      'Persisted BT storage layout does not match torrent metadata'
    )
  }
}

function validatePathComponent(value: unknown, description: string): string {
  if (
    typeof value !== 'string' ||
    value.length === 0 ||
    value === '.' ||
    value === '..' ||
    value.includes('/') ||
    value.includes('\\') ||
    [...value].some(
      (char) => char.charCodeAt(0) < 32 || char.charCodeAt(0) === 127
    ) ||
    (process.platform === 'win32' &&
      (/[<>:"|?*]/.test(value) ||
        /[. ]$/.test(value) ||
        /^(con|prn|aux|nul|com[1-9¹²³]|lpt[1-9¹²³])(?:\.|$)/i.test(value)))
  ) {
    throw new UnsafeTorrentPathError(`Invalid ${description}`)
  }
  return value
}

function isBtStorageLayout(value: unknown): value is BtStorageLayoutV1 {
  if (!value || typeof value !== 'object') return false
  const candidate = value as Partial<BtStorageLayoutV1>
  return (
    candidate.version === 1 &&
    candidate.strategy === 'indexed-staging' &&
    typeof candidate.workspacePath === 'string' &&
    path.isAbsolute(candidate.workspacePath) &&
    candidate.payloadEntry === PAYLOAD_ENTRY &&
    typeof candidate.torrentRootName === 'string' &&
    isSafePathComponent(candidate.torrentRootName) &&
    typeof candidate.multiFile === 'boolean'
  )
}

function isLayoutOwnedByTask(
  layout: BtStorageLayoutV1,
  task: Pick<DownloadTask, 'saveDir' | 'diskPath' | 'finalPath'>
): boolean {
  if (!task.saveDir) return false
  const workspacePath = path.resolve(layout.workspacePath)
  const storageRoot = path.resolve(task.saveDir, STORAGE_ROOT)
  if (
    path.dirname(workspacePath) !== storageRoot ||
    !/^[a-f0-9]{20}$/.test(path.basename(workspacePath))
  ) {
    return false
  }

  // While the task is in-flight, the canonical diskPath must identify the
  // same workspace. After rename diskPath equals finalPath, so the retained
  // layout remains available for reseed/retry mapping without authorizing
  // arbitrary filesystem operations from persisted JSON.
  return (
    task.diskPath === task.finalPath ||
    path.resolve(task.diskPath) === workspacePath
  )
}

function isSafePathComponent(value: string): boolean {
  return (
    value.length > 0 &&
    value !== '.' &&
    value !== '..' &&
    !value.includes('/') &&
    !value.includes('\\') &&
    !value.includes('\0')
  )
}