Files
AeroFetch/src/main/probe.ts
T
debont80 b08d76a986 Apply all CODE-AUDIT.md findings (S1-S5, P1-P3, M1-M3)
Security:
- S1 (backup.ts): require explicit confirmation before enabling custom-command
  templates from a backup file; import templates in a disabled state if declined
- S2 (cookies.ts): deny non-http/https popups in cookie login window, matching
  the main window's setWindowOpenHandler defence
- S3 (download.ts): main-process concurrency cap — startDownload now rejects
  spawns when active.size >= maxConcurrent (defence-in-depth; renderer already
  enforces this but should not be the only gate)
- S4 (settings.ts, validation.ts): reject filenameTemplate values containing
  path traversal (.. segments or absolute paths); validate outputDir is absolute
- S5 (history.ts, errorlog.ts, templates.ts, validation.ts): per-field
  validation on JSON reads — invalid entries dropped rather than blindly trusted

Performance:
- P1 (settings.ts): getSettings() now only writes to disk when sanitization
  actually changed a value; removes synchronous file I/O on every hot-path read
- P2 (ipc.ts, download.ts, downloads.ts): renderer forwards its pre-probed
  metadata (title/channel/duration) via StartDownloadOptions.meta; main uses
  it directly instead of spawning a redundant second yt-dlp probe

Maintainability:
- M1 (log.ts, download.ts, probe.ts): extract duplicated cleanError() to
  src/main/log.ts; both callers import from the shared module
- M2 (buildArgs.ts): document parseExtraArgs escape-sequence limitations
- M3 (electron-builder.yml): clarify icon TODO as a pre-release action
- P3 (downloads.ts): document that lowering maxConcurrent mid-flight does
  not pause active downloads (intended behaviour, now written down)

Tests:
- Add test/validation.test.ts covering isSafeFilenameTemplate, isSafeOutputDir,
  isValidHistoryEntry, isValidErrorLogEntry, isTemplateLike (76 tests pass)

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-23 10:22:43 -04:00

193 lines
6.0 KiB
TypeScript

import { execFile } from 'child_process'
import { existsSync } from 'fs'
import { getYtdlpPath } from './binaries'
import { fmtBytes } from './download'
import { cleanError } from './log'
import { assertHttpUrl } from './url'
import {
BEST_FORMAT_ID,
type ProbeResult,
type MediaInfo,
type FormatOption,
type PlaylistInfo,
type PlaylistEntry
} from '@shared/ipc'
// The slice of `yt-dlp -J` output we actually read.
interface RawFormat {
format_id: string
ext?: string
vcodec?: string
acodec?: string
height?: number
fps?: number
tbr?: number
filesize?: number
filesize_approx?: number
}
interface RawEntry {
id?: string
title?: string
url?: string
webpage_url?: string
duration?: number
uploader?: string
channel?: string
}
interface RawInfo {
_type?: string
title?: string
uploader?: string
channel?: string
duration_string?: string
thumbnail?: string
formats?: RawFormat[]
entries?: RawEntry[]
}
/** Quality proxy for picking the best format at a given height. */
function score(f: RawFormat): number {
return (f.tbr ?? 0) + (f.ext === 'mp4' ? 0.5 : 0)
}
function toOption(f: RawFormat): FormatOption {
const size = f.filesize ?? f.filesize_approx
const fpsTag = f.fps && f.fps > 30 ? String(Math.round(f.fps)) : ''
const sizeLabel = size ? fmtBytes(size) : undefined
const parts = [`${f.height}p${fpsTag}`, f.ext, sizeLabel].filter(Boolean) as string[]
return {
id: f.format_id,
label: parts.join(' · '),
height: f.height,
ext: f.ext,
filesizeLabel: sizeLabel,
hasAudio: !!f.acodec && f.acodec !== 'none'
}
}
/** One option per distinct height (best at that height), best-first, plus auto. */
function buildVideoFormats(raw: RawFormat[]): FormatOption[] {
const bestByHeight = new Map<number, RawFormat>()
for (const f of raw) {
if (!f.vcodec || f.vcodec === 'none' || !f.height) continue
const cur = bestByHeight.get(f.height)
if (!cur || score(f) > score(cur)) bestByHeight.set(f.height, f)
}
const options = [...bestByHeight.values()]
.sort((a, b) => (b.height ?? 0) - (a.height ?? 0))
.map(toOption)
options.unshift({ id: BEST_FORMAT_ID, label: 'Best available', ext: 'mp4', hasAudio: true })
return options
}
function buildInfo(data: RawInfo): MediaInfo {
return {
title: data.title || 'Untitled',
channel: data.channel || data.uploader || undefined,
durationLabel: data.duration_string || undefined,
thumbnail: data.thumbnail || undefined,
formats: buildVideoFormats(data.formats ?? [])
}
}
/** Seconds → 'M:SS' or 'H:MM:SS'. Flat playlist entries give duration as a number. */
function fmtDuration(sec?: number): string | undefined {
if (sec == null || !Number.isFinite(sec)) return undefined
const s = Math.max(0, Math.round(sec))
const h = Math.floor(s / 3600)
const m = Math.floor((s % 3600) / 60)
const r = s % 60
const mm = h ? String(m).padStart(2, '0') : String(m)
return `${h ? `${h}:` : ''}${mm}:${String(r).padStart(2, '0')}`
}
/**
* Resolve the URL we'll enqueue for a playlist entry. Prefer an explicit http(s)
* URL; fall back to a YouTube watch URL built from the id (the common case where
* flat entries carry only an id). Returns null when nothing usable is present.
*/
function entryUrl(e: RawEntry): string | null {
const cand = e.url || e.webpage_url
if (cand && /^https?:\/\//i.test(cand)) return cand
if (e.id) return `https://www.youtube.com/watch?v=${e.id}`
return null
}
function buildPlaylist(data: RawInfo): PlaylistInfo {
const entries: PlaylistEntry[] = []
;(data.entries ?? []).forEach((e, i) => {
const url = entryUrl(e)
if (!url) return // skip entries we can't turn into a downloadable URL
entries.push({
index: i + 1,
id: e.id || String(i + 1),
title: e.title || `Item ${i + 1}`,
url,
durationLabel: fmtDuration(e.duration),
uploader: e.uploader || e.channel || undefined
})
})
return {
title: data.title || 'Playlist',
uploader: data.uploader || data.channel || undefined,
count: entries.length,
entries
}
}
/**
* Probe a URL with `yt-dlp -J --flat-playlist`. Resolves to a single video (with
* its format list) or, when the URL is a playlist, the flat list of its entries.
* `--flat-playlist` is a no-op for a lone video, so one call covers both cases.
*/
export function probeMedia(url: string): Promise<ProbeResult> {
const ytdlp = getYtdlpPath()
if (!existsSync(ytdlp)) {
return Promise.resolve({
ok: false,
error: `yt-dlp.exe not found at ${ytdlp}\nDrop it into resources/bin/ (see the README there).`
})
}
try {
assertHttpUrl(url)
} catch (e) {
return Promise.resolve({ ok: false, error: (e as Error).message })
}
return new Promise((resolve) => {
execFile(
ytdlp,
// `--` terminates option parsing so the URL can never be read as a flag.
['-J', '--flat-playlist', '--no-warnings', '--', url],
{ windowsHide: true, maxBuffer: 64 * 1024 * 1024, timeout: 60_000 },
(err, stdout, stderr) => {
if (err) {
// execFile sets `killed` when it terminated the process on timeout.
const msg = (err as { killed?: boolean }).killed
? 'Timed out fetching video info. Check the link or your connection.'
: cleanError(stderr) || err.message
resolve({ ok: false, error: msg })
return
}
try {
const data = JSON.parse(stdout) as RawInfo
if (data._type === 'playlist' || Array.isArray(data.entries)) {
const playlist = buildPlaylist(data)
if (playlist.count === 0) {
resolve({ ok: false, error: 'This playlist has no downloadable entries.' })
return
}
resolve({ ok: true, kind: 'playlist', playlist })
} else {
resolve({ ok: true, kind: 'video', info: buildInfo(data) })
}
} catch {
resolve({ ok: false, error: 'Could not parse video info from yt-dlp.' })
}
}
)
})
}