// Headless HTTP add API: torlnk exposes a tiny local server so another program // (a seedbox web app, a script, curl) can hand it a torrent over HTTP instead of // a keypress. It complements the watch folder — same headless runtime, a // different doorway. // // Default port 9161 sits next to Tor's control port (9051 / browser 9151); it's // deliberately non-standard and overridable with --port. Binds 127.0.0.1 by // default; exposing it on a public interface requires a token. import http from "node:http"; import { startRuntime, addInput, type Runtime } from "./runtime"; import { magnetFromTorrentBytes } from "../sources/torrentFile"; import { startSeedReaper } from "./seed-reaper"; import { LOOPBACK_HOSTS, isAuthorized, hostHeaderOk, localRequestOk } from "./auth"; import { parseDuration } from "../util/duration"; import { logNetwork, validPort } from "../download/network"; import type { NetworkPatch } from "../download/engine"; import { VERSION } from "../version"; export { isAuthorized } from "./auth"; export const DEFAULT_API_PORT = 9161; // A magnet is tiny, but /add also takes an uploaded .torrent, and that is one // 20-byte hash per piece: a large multi-file release runs to a few hundred KB // before base64 adds a third on top. The old 64KB cap fit every magnet and // every torrent small enough to test with, then answered 413 on real content. const MAX_BODY_BYTES = 1024 * 1024; export interface ApiResponse { status: number; body: Record; } export interface ServeOptions { playlist?: boolean; port?: number; host?: string; token?: string; downloadDir?: string; /** Stop seeding each torrent this long after it finishes (ms). */ seedTimeMs?: number; /** With seedTimeMs, also delete the files when the timer expires. */ deleteFiles?: boolean; } // Pull a magnet / info hash out of a request body. Accepts JSON ({ magnet } or // { infohash }) or a raw body that is itself a magnet or info hash — forgiving, // so callers don't have to guess the exact envelope. // A base64 .torrent from the request body, or null. // // The bytes travel in the JSON rather than the path to them: torlink already // refuses to let a network caller name a local file (runtime.ts's // allowTorrentPath), and that refusal is worth keeping -- "add this torrent" // and "read this file off your disk and tell me about it" must not be the same // request. Uploading the content sidesteps it entirely. export function extractTorrentBytes(bodyText: string): Uint8Array | null { const raw = bodyText.trim(); if (!raw.startsWith("{")) return null; let obj: Record; try { obj = JSON.parse(raw) as Record; } catch { return null; } const value = obj.torrent ?? obj.torrentFile ?? obj.file; if (typeof value !== "string" || !value.trim()) return null; // A data: URI is what a browser's FileReader hands you, and stripping the // prefix here is cheaper than making every caller remember to. const b64 = value.replace(/^data:[^,]*,/, "").trim(); try { const bytes = Buffer.from(b64, "base64"); // Buffer.from ignores anything it cannot decode rather than throwing, so a // non-base64 string yields a short buffer instead of an error. Every // torrent starts with a bencoded dictionary, which is the cheap check that // this is one. if (bytes.length === 0 || bytes[0] !== 0x64) return null; return new Uint8Array(bytes); } catch { return null; } } export function extractMagnet(bodyText: string): string | null { const raw = bodyText.trim(); if (!raw) return null; if (raw.startsWith("{")) { try { const obj = JSON.parse(raw) as Record; const val = obj.magnet ?? obj.infohash ?? obj.infoHash ?? obj.hash; return typeof val === "string" && val.trim() ? val.trim() : null; } catch { return null; } } return raw; } // The optional per-torrent seed limit on /add and /control: a `seedTime` field // holding a duration in the --seed-time grammar ("30d", "2h", "90m"; a bare // number is seconds), or 0 to never stop seeding that torrent. Three answers: // undefined the field is absent (inherit the daemon-wide --seed-time) // null it is there but unusable (the caller gets a 400) // number milliseconds // A raw (non-JSON) body carries no seedTime. export function extractSeedTime(bodyText: string): number | null | undefined { const raw = bodyText.trim(); if (!raw.startsWith("{")) return undefined; let obj: Record; try { obj = JSON.parse(raw) as Record; } catch { return undefined; } return seedTimeField(obj.seedTime); } function seedTimeField(value: unknown): number | null | undefined { if (value === undefined || value === null) return undefined; if (typeof value === "number") { return Number.isFinite(value) && value >= 0 ? Math.floor(value) * 1000 : null; } if (typeof value === "string") { if (!value.trim()) return undefined; return parseDuration(value); } return null; } // Control actions the headless API accepts (POST /control). A seedbox web app // drives per-torrent buttons through these instead of the interactive keymap. export const CONTROL_ACTIONS = [ "pause", // pause an active/queued download "resume", // resume a paused download "start-seed", // (re)start seeding a finished torrent "stop-seed", // stop seeding but keep the files "remove", // forget the torrent, keep files on disk "delete", // forget the torrent AND delete its files "seed-time", // set this torrent's own seed limit ({ seedTime }); "" clears it ] as const; export type ControlAction = (typeof CONTROL_ACTIONS)[number]; export interface ControlRequest { id: string; action: string; deleteFiles: boolean; // Parsed `seedTime` for the seed-time action: ms, undefined when absent or // blank (clear the override), null when present but unusable. seedTimeMs?: number | null; } // Parse a control request body: JSON { id, action, deleteFiles?, seedTime? }. // Returns null for anything missing the two required string fields; the action // string itself is validated later so an unknown action gets a precise error. export function parseControl(bodyText: string): ControlRequest | null { const raw = bodyText.trim(); if (!raw.startsWith("{")) return null; let obj: Record; try { obj = JSON.parse(raw) as Record; } catch { return null; } const id = typeof obj.id === "string" ? obj.id.trim() : ""; const action = typeof obj.action === "string" ? obj.action.trim() : ""; if (!id || !action) return null; return { id, action, deleteFiles: obj.deleteFiles === true, seedTimeMs: seedTimeField(obj.seedTime) }; } export type ControlOutcome = "ok" | "not-found" | "unknown-action" | "invalid-seed-time"; // Apply a parsed control request to the queue. Pure over the runtime so it's // unit-testable with a fake queue. export async function applyControl( runtime: Runtime, req: ControlRequest, ): Promise { const q = runtime.queue; const { id, action, deleteFiles, seedTimeMs } = req; switch (action as ControlAction) { case "pause": if (!q.has(id)) return "not-found"; q.pause(id); return "ok"; case "resume": if (!q.has(id)) return "not-found"; q.resume(id); return "ok"; case "stop-seed": if (!q.getSeed(id)) return "not-found"; q.stopSeeding(id); return "ok"; case "start-seed": { const h = q.getHistory().find((x) => x.id === id); if (!h) return "not-found"; q.startSeeding(h); return "ok"; } case "remove": case "delete": { const found = await q.remove(id, { deleteFiles: action === "delete" || deleteFiles }); return found ? "ok" : "not-found"; } case "seed-time": { if (seedTimeMs === null) return "invalid-seed-time"; return q.setSeedTime(id, seedTimeMs) ? "ok" : "not-found"; } default: return "unknown-action"; } } function statusPayload(runtime: Runtime): Record { const downloads = runtime.queue.getItems().map((it) => ({ id: it.id, name: it.name, status: it.status, progress: it.progress, peers: it.peers, speed: it.speed, ...(it.seedTimeMs !== undefined ? { seedTimeMs: it.seedTimeMs } : {}), })); const history = new Map(runtime.queue.getHistory().map((h) => [h.id, h])); const seeds = runtime.queue.getSeeds().map((s) => { const h = history.get(s.id); return { id: s.id, name: s.name, status: s.status, peers: s.peers, uploaded: s.uploaded, // Only a torrent's own limit is reported; a daemon-wide --seed-time is // the caller's to know. seedUntil is when that own limit falls due. ...(h?.seedTimeMs !== undefined ? { seedTimeMs: h.seedTimeMs, seedUntil: h.seedTimeMs > 0 ? h.completedAt + h.seedTimeMs : null, } : {}), }; }); return { downloads, seeds, network: runtime.queue.networkStatus() }; } // Body of POST /network: { interface?: string | null, peerPort?: number | null, // dhtPort?: number | null }. null clears a field; a key left out is kept. export function parseNetworkPatch(bodyText: string): NetworkPatch | null { let body: unknown; try { body = JSON.parse(bodyText); } catch { return null; } if (typeof body !== "object" || body === null || Array.isArray(body)) return null; const raw = body as Record; const patch: NetworkPatch = {}; if ("interface" in raw) { const v = raw.interface; if (v === null) patch.interface = null; else if (typeof v === "string" && v.trim() && !/:/.test(v)) patch.interface = v.trim(); else return null; } for (const key of ["peerPort", "dhtPort"] as const) { if (!(key in raw)) continue; const v = raw[key]; if (v === null) patch[key] = null; else if (validPort(v)) patch[key] = v; else return null; } if (Object.keys(patch).length === 0) return null; return patch; } // Pure request router — no node:http types, so it's trivially testable. export async function handleApi( runtime: Runtime, token: string | null, method: string, urlPath: string, authHeader: string | undefined, bodyText: string, ): Promise { if (method === "GET" && urlPath === "/health") { return { status: 200, body: { ok: true, version: VERSION } }; } if (!isAuthorized(token, authHeader)) { return { status: 401, body: { error: "unauthorized" } }; } if (method === "GET" && (urlPath === "/downloads" || urlPath === "/status")) { return { status: 200, body: statusPayload(runtime) }; } if (method === "GET" && urlPath === "/network") { return { status: 200, body: { ...runtime.queue.networkStatus() } }; } if (method === "POST" && urlPath === "/network") { const patch = parseNetworkPatch(bodyText); if (!patch) { return { status: 400, body: { error: "expected { interface?: string|null, peerPort?: 1-65535|null, dhtPort?: 1-65535|null }" }, }; } const result = runtime.queue.reconfigureNetwork(patch); if (!result.ok) return { status: 400, body: { error: result.error } }; return { status: 200, body: { ok: true, ...result.status } }; } if (method === "POST" && urlPath === "/add") { // A .torrent is tried first because it is strictly more information: it // carries the piece hashes, so data already on disk verifies locally // instead of waiting on a swarm to serve metadata back. const seedTimeMs = extractSeedTime(bodyText); if (seedTimeMs === null) return { status: 400, body: { error: "invalid seedTime" } }; const addOptions = seedTimeMs !== undefined ? { seedTimeMs } : {}; const bytes = extractTorrentBytes(bodyText); if (bytes) { const parsed = await magnetFromTorrentBytes(bytes); if (!parsed) return { status: 400, body: { error: "invalid .torrent" } }; const outcome = await addInput(runtime, parsed.magnet, addOptions); if (outcome === "invalid") return { status: 400, body: { error: "invalid .torrent" } }; return { status: 200, body: { ok: true, outcome, infoHash: parsed.infoHash } }; } const magnet = extractMagnet(bodyText); if (!magnet) return { status: 400, body: { error: "missing magnet, info hash or .torrent" } }; const outcome = await addInput(runtime, magnet, addOptions); if (outcome === "invalid") return { status: 400, body: { error: "invalid magnet or info hash" } }; return { status: 200, body: { ok: true, outcome } }; } if (method === "POST" && urlPath === "/control") { const req = parseControl(bodyText); if (!req) return { status: 400, body: { error: "missing or invalid { id, action }" } }; const outcome = await applyControl(runtime, req); if (outcome === "unknown-action") { return { status: 400, body: { error: `unknown action: ${req.action}` } }; } if (outcome === "invalid-seed-time") return { status: 400, body: { error: "invalid seedTime" } }; if (outcome === "not-found") return { status: 404, body: { error: "no such torrent" } }; return { status: 200, body: { ok: true, id: req.id, action: req.action } }; } return { status: 404, body: { error: "not found" } }; } // Read the body up to the size cap. On overflow resolve tooLarge immediately // (further chunks are ignored) so the caller can answer 413 on a live socket // and close the connection afterwards, instead of writing to a destroyed one. function readBody(req: http.IncomingMessage): Promise<{ text: string; tooLarge: boolean }> { return new Promise((resolve) => { let size = 0; let settled = false; const chunks: Buffer[] = []; req.on("data", (c: Buffer) => { if (settled) return; size += c.length; if (size > MAX_BODY_BYTES) { settled = true; resolve({ text: "", tooLarge: true }); return; } chunks.push(c); }); req.on("end", () => { if (settled) return; settled = true; resolve({ text: Buffer.concat(chunks).toString("utf8"), tooLarge: false }); }); req.on("error", () => { if (settled) return; settled = true; resolve({ text: "", tooLarge: false }); }); }); } function log(message: string): void { console.log(`[torlnk serve] ${new Date().toISOString()} ${message}`); } export async function runServe(options: ServeOptions = {}): Promise { const port = options.port ?? DEFAULT_API_PORT; const host = options.host ?? "127.0.0.1"; const token = options.token && options.token.trim() ? options.token.trim() : null; // Fail soft, not open: never expose a public interface without a token. if (!LOOPBACK_HOSTS.has(host) && !token) { console.error( `error: refusing to bind ${host} without a token. Pass --token ` + `(or set TORLINK_API_TOKEN), or bind 127.0.0.1.`, ); process.exit(1); return; } const runtime = await startRuntime(options.downloadDir, { playlist: options.playlist }); logNetwork(runtime.queue, log); // Always on: with no --seed-time it only acts on torrents that carry their // own limit (set over the API), and does nothing at all otherwise. startSeedReaper(runtime.queue, options.seedTimeMs ?? 0, { deleteFiles: options.deleteFiles, log }); const server = http.createServer((req, res) => { void (async () => { const method = req.method ?? "GET"; const urlPath = (req.url ?? "/").split("?")[0]!; // Tokenless means loopback-bound; require a loopback Host and no Origin // so a hostile webpage can't drive us, by DNS rebinding or a no-cors POST. if (!token && !localRequestOk(req.headers.host, req.headers.origin)) { const why = hostHeaderOk(req.headers.host) ? "origin" : "host"; res.writeHead(403, { "Content-Type": "application/json" }); res.end(JSON.stringify({ error: `forbidden ${why}` })); log(`${method} ${urlPath} -> 403 (${why})`); return; } const body = method === "POST" ? await readBody(req) : { text: "", tooLarge: false }; if (body.tooLarge) { res.writeHead(413, { "Content-Type": "application/json", Connection: "close" }); res.end(JSON.stringify({ error: "body too large" })); res.once("finish", () => req.destroy()); log(`${method} ${urlPath} -> 413`); return; } const bodyText = body.text; let out: ApiResponse; try { out = await handleApi(runtime, token, method, urlPath, req.headers.authorization, bodyText); } catch { out = { status: 500, body: { error: "internal error" } }; } const payload = JSON.stringify(out.body); res.writeHead(out.status, { "Content-Type": "application/json" }); res.end(payload); if (method !== "GET" || urlPath !== "/health") { log(`${method} ${urlPath} -> ${out.status}`); } })(); }); await new Promise((resolve) => { server.listen(port, host, () => { log(`listening on http://${host}:${port} (downloads -> ${runtime.downloadDir})`); log(token ? "auth: token required" : "auth: none (loopback only)"); resolve(); }); }); await new Promise((resolve) => { const shutdown = (): void => { server.close(); runtime.queue.suspend(); resolve(); }; process.on("SIGINT", shutdown); process.on("SIGTERM", shutdown); }); }