move transmission and slskd credentials into the database

both sidecars read their upstream from a new service_connections table instead of
process.env: one row per (user, service), the secret encrypted at rest, upserted
through a /_config route the app drives. transmission gains a Connection section,
soulseek gains one too, and both take over the whole app while nothing is stored.

TRANSMISSION_URL/USER/PASS/RPC_PATH and SLSKD_URL/API_KEY can come out of .env.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
2026-08-03 18:04:22 +00:00
co-authored by Claude Opus 5
parent f20d4a300e
commit d7b775113b
26 changed files with 1235 additions and 175 deletions
@@ -0,0 +1,91 @@
import { deleteServiceConnection, getServiceConnection, saveServiceConnection } from 'officerdb';
import { probe } from './rpc';
import {
basicAuth,
getTransmissionConfig,
invalidateTransmissionConfig,
normalizeBase,
normalizeRpcPath,
} from './upstream';
// `/_config` — where the Transmission daemon is, driven from the app rather than from a shell on the server.
//
// ONE connection, not a registry: nobody runs two Transmission daemons. So there is no label, no id in the
// path and no activate route — a save is an upsert over the single row, and the UI is one form.
//
// The URL is the only thing usually needed. Most Transmission daemons run with no RPC auth at all, so
// username/password are optional and an EMPTY username means "no auth" rather than "empty credentials" —
// see basicAuth in upstream.ts, where sending a Basic header anyway makes the daemon reject the request.
// `rpcPath` is there for the reverse-proxy case and defaults to /transmission/rpc.
//
// The password is WRITE-ONLY across this boundary: the GET reports whether one is stored, never its value.
// A save is validated with a live session-get first, so a wrong URL or rejected credentials is a 400 with
// the reason rather than a stored row that makes every later screen fail mysteriously.
/** What the browser is allowed to know about the connection. Never includes the password. */
async function connectionState(userId: number): Promise<Response> {
const connection = await getServiceConnection(userId, 'transmission');
return Response.json({ configured: !!connection, connection });
}
const bad = (error: string, status = 400) => Response.json({ error }, { status });
type ConnectionBody = { url?: unknown; username?: unknown; password?: unknown; rpcPath?: unknown };
const isHttpUrl = (url: string): boolean => /^https?:\/\//i.test(url);
const readString = (value: unknown): string => (typeof value === 'string' ? value.trim() : '');
/** Save the connection: validated against the live daemon, then stored. */
async function save(req: Request, userId: number): Promise<Response> {
const body = ((await req.json().catch(() => null)) as ConnectionBody | null) ?? {};
const url = typeof body.url === 'string' ? normalizeBase(body.url) : '';
const username = readString(body.username);
const rpcPath = normalizeRpcPath(readString(body.rpcPath));
// A blank password with a username still set means "keep the stored one", so changing the URL does not
// need the password re-typed. Clearing the username clears the auth entirely.
const password = typeof body.password === 'string' && body.password ? body.password : null;
if (!url) return bad('url is required');
if (!isHttpUrl(url)) return bad('url must start with http:// or https://');
const current = await getServiceConnection(userId, 'transmission');
const keepPassword = !password && !!username && username === current?.username && current.hasSecret;
// Probing needs the real password, so a save that keeps the stored one borrows it through the normal read
// path rather than reaching for the ciphertext here.
const stored = keepPassword ? await getTransmissionConfig(userId) : null;
const auth = keepPassword ? (stored?.auth ?? null) : basicAuth(username || null, password);
const result = await probe({ base: url, rpcPath, auth });
if (!result.ok) return bad(result.error ?? 'could not reach the daemon');
const connection = await saveServiceConnection({
userId,
service: 'transmission',
url,
username: username || null,
// undefined keeps the stored password; null clears it, which is what dropping the username means.
secret: keepPassword ? undefined : (password ?? null),
path: rpcPath,
version: result.version ?? null,
});
invalidateTransmissionConfig(userId);
return Response.json({ connection, rpcVersion: result.rpcVersion ?? null });
}
/** `/_config` — GET the connection, PUT/POST to save it, DELETE to forget it. */
export async function handleConfigRoute(req: Request, userId: number, subpath: string): Promise<Response> {
if (subpath && subpath !== '/') return bad('not found', 404);
if (req.method === 'GET') return connectionState(userId);
if (req.method === 'POST' || req.method === 'PUT') return save(req, userId);
if (req.method === 'DELETE') {
await deleteServiceConnection(userId, 'transmission');
invalidateTransmissionConfig(userId);
return connectionState(userId);
}
return bad('method not allowed', 405);
}
+38 -8
View File
@@ -1,8 +1,9 @@
import type { SidecarCommand, SidecarEvent } from '../protocol';
import { createSidecarConnector } from '../connect';
import { handleConfigRoute } from './config';
import { handleOfficerRoute } from './routes';
import { probe } from './rpc';
import { getTransmissionBase } from './upstream';
import { getTransmissionConfig } from './upstream';
// The officer-transmission sidecar. Owns the whole Transmission contract for Officer: the daemon URL and
// credentials, the X-Transmission-Session-Id CSRF handshake, and the translation from Transmission's
@@ -13,6 +14,10 @@ import { getTransmissionBase } from './upstream';
// HTTP CONTRACT — the platform strips its /api/transmission mount prefix before forwarding.
//
// GET /_health ours. Probes the daemon with a cheap session-get.
// GET /_config { configured, connection } — where the daemon is, never the password
// PUT /_config { url, username?, password?, rpcPath? } — validated with a live
// session-get, then stored. A blank password keeps the stored one
// DEL /_config forget the connection
// GET /_officer/session full session settings + version + rpc-version
// POST /_officer/session write a partial settings object (whitelisted), returns it read back
// GET /_officer/stats session-stats: cumulative + current-session counters
@@ -34,6 +39,10 @@ import { getTransmissionBase } from './upstream';
// through one POST body, reports failures as `{"result": "<error>"}` inside a 200, and demands a CSRF token
// that rotates on every daemon restart. Proxying that raw would push all three into the browser. Every
// quirk is absorbed here — see rpc.ts.
//
// Every route needs `X-Officer-User`, which the platform proxy sets after authenticating the owner. We bind
// loopback only, so its presence is the trust signal — a request without it did not come through the
// platform, and which daemon to talk to is per-owner data.
// ─────────────────────────────────────────────────────────────────────────────────────────────────
const API_URL = process.env.API_URL ?? `ws://127.0.0.1:${process.env.PORT ?? '5000'}`;
@@ -57,18 +66,37 @@ const server = Bun.serve({
async fetch(req) {
const url = new URL(req.url);
if (url.pathname === '/_health') {
if (!getTransmissionBase()) {
return Response.json({ ok: false, error: 'TRANSMISSION_URL not configured' }, { status: 503 });
const officerUser = req.headers.get('X-Officer-User');
const userId = Number(officerUser);
if (!officerUser || !Number.isInteger(userId) || userId <= 0) {
return Response.json({ error: 'missing or invalid X-Officer-User' }, { status: 401 });
}
if (url.pathname === '/_config' || url.pathname.startsWith('/_config/')) {
try {
return await handleConfigRoute(req, userId, url.pathname.slice('/_config'.length));
} catch (err) {
console.error(`[transmission] ${req.method} ${url.pathname} failed`, err);
return Response.json({ error: 'internal error' }, { status: 500 });
}
}
// 503 with `configured: false` is the signal the UI turns into the setup form. Distinguishing it from a
// configured-but-unreachable daemon is the whole reason the flag is on the response.
if (url.pathname === '/_health') {
const cfg = await getTransmissionConfig(userId);
if (!cfg) return Response.json({ ok: false, configured: false, error: 'not connected' }, { status: 503 });
const started = Date.now();
const result = await probe();
return Response.json({ ...result, ms: Date.now() - started }, { status: result.ok ? 200 : 502 });
const result = await probe(cfg);
return Response.json(
{ ...result, configured: true, ms: Date.now() - started },
{ status: result.ok ? 200 : 502 },
);
}
if (url.pathname.startsWith('/_officer/')) {
try {
const res = await handleOfficerRoute(req, url);
const res = await handleOfficerRoute(userId, req, url);
if (res) return res;
return Response.json({ error: 'not found' }, { status: 404 });
} catch (err) {
@@ -81,7 +109,9 @@ const server = Bun.serve({
},
});
console.log(`[transmission] listening on 127.0.0.1:${port} -> ${getTransmissionBase() ?? '(TRANSMISSION_URL unset)'}`);
// No upstream in the banner: where the daemon lives is now per-owner state read from the database per
// request, not a constant this process knows at boot.
console.log(`[transmission] listening on 127.0.0.1:${port}`);
type ReplyFn = (msg: SidecarEvent) => void;
+36 -42
View File
@@ -128,16 +128,10 @@ function pick(body: Record<string, unknown>, allowed: Set<string>): Record<strin
/**
* Dispatch an /_officer/* request. Returns null when nothing matches, which the caller turns into a 404.
*
* The platform injects X-Officer-User after authenticating the owner. We bind loopback only, so its presence
* is the trust signal — a request without it did not come through the platform.
* `userId` was authenticated by the platform proxy and validated at the server boundary — every call below
* needs it, because which daemon to talk to is per-owner state read from the database.
*/
export async function handleOfficerRoute(req: Request, url: URL): Promise<Response | null> {
const officerUser = req.headers.get('X-Officer-User');
if (!officerUser) return Response.json({ error: 'missing X-Officer-User' }, { status: 401 });
const userId = Number(officerUser);
if (!Number.isInteger(userId) || userId <= 0) return badRequest('invalid X-Officer-User');
export async function handleOfficerRoute(userId: number, req: Request, url: URL): Promise<Response | null> {
const segments = url.pathname.slice('/_officer/'.length).split('/').filter(Boolean);
if (segments.length === 0) return null;
@@ -171,7 +165,7 @@ async function handleSession(ctx: OfficerContext, rest: string[]): Promise<Respo
if (ctx.req.method === 'GET') {
// No `fields` argument: session-get returns everything, and the settings UI reads nearly all of it.
const session = await rpc<SessionSettings>('session-get');
const session = await rpc<SessionSettings>(ctx.userId, 'session-get');
return Response.json({ session });
}
@@ -180,10 +174,10 @@ async function handleSession(ctx: OfficerContext, rest: string[]): Promise<Respo
if (!body) return badRequest('expected a JSON object body');
const args = pick(body, SESSION_SET_FIELDS);
if (Object.keys(args).length === 0) return badRequest('no writable session fields in body');
await rpc('session-set', args);
await rpc(ctx.userId, 'session-set', args);
// Read back rather than echoing the request: Transmission clamps and normalises several of these
// (alt-speed times, queue sizes), so the request body is not what the daemon ends up holding.
const session = await rpc<SessionSettings>('session-get');
const session = await rpc<SessionSettings>(ctx.userId, 'session-get');
return Response.json({ session });
}
@@ -192,7 +186,7 @@ async function handleSession(ctx: OfficerContext, rest: string[]): Promise<Respo
async function handleStats(ctx: OfficerContext): Promise<Response> {
if (ctx.req.method !== 'GET') return methodNotAllowed();
const stats = await rpc<SessionStats>('session-stats');
const stats = await rpc<SessionStats>(ctx.userId, 'session-stats');
return Response.json({ stats });
}
@@ -200,19 +194,19 @@ async function handleFreeSpace(ctx: OfficerContext): Promise<Response> {
if (ctx.req.method !== 'GET') return methodNotAllowed();
const path = ctx.url.searchParams.get('path');
if (!path) return badRequest('path query parameter is required');
const result = await rpc<{ path: string; 'size-bytes': number }>('free-space', { path });
const result = await rpc<{ path: string; 'size-bytes': number }>(ctx.userId, 'free-space', { path });
return Response.json({ path: result.path, bytes: result['size-bytes'] });
}
async function handlePortTest(ctx: OfficerContext): Promise<Response> {
if (ctx.req.method !== 'POST') return methodNotAllowed();
const result = await rpc<{ 'port-is-open': boolean }>('port-test');
const result = await rpc<{ 'port-is-open': boolean }>(ctx.userId, 'port-test');
return Response.json({ open: result['port-is-open'] });
}
async function handleBlocklistUpdate(ctx: OfficerContext): Promise<Response> {
if (ctx.req.method !== 'POST') return methodNotAllowed();
const result = await rpc<{ 'blocklist-size': number }>('blocklist-update');
const result = await rpc<{ 'blocklist-size': number }>(ctx.userId, 'blocklist-update');
return Response.json({ size: result['blocklist-size'] });
}
@@ -221,7 +215,7 @@ async function handleTorrents(ctx: OfficerContext, rest: string[]): Promise<Resp
// GET /_officer/torrents — the list poll.
if (rest.length === 0 && req.method === 'GET') {
const result = await rpc<{ torrents: Torrent[] }>('torrent-get', { fields: [...LIST_FIELDS] });
const result = await rpc<{ torrents: Torrent[] }>(ctx.userId, 'torrent-get', { fields: [...LIST_FIELDS] });
return Response.json({ torrents: result.torrents.map(decorate) });
}
@@ -231,17 +225,17 @@ async function handleTorrents(ctx: OfficerContext, rest: string[]): Promise<Resp
if (req.method === 'POST') {
switch (segment) {
case 'add':
return await addTorrent(req);
return await addTorrent(ctx);
case 'action':
return await runAction(req);
return await runAction(ctx);
case 'set':
return await setTorrent(req);
return await setTorrent(ctx);
case 'location':
return await setLocation(req);
return await setLocation(ctx);
case 'rename':
return await renamePath(req);
return await renamePath(ctx);
case 'remove':
return await removeTorrents(req);
return await removeTorrents(ctx);
}
}
@@ -250,7 +244,7 @@ async function handleTorrents(ctx: OfficerContext, rest: string[]): Promise<Resp
if (!Number.isInteger(id) || id <= 0) return notFound();
if (req.method !== 'GET') return methodNotAllowed();
const result = await rpc<{ torrents: Torrent[] }>('torrent-get', {
const result = await rpc<{ torrents: Torrent[] }>(ctx.userId, 'torrent-get', {
ids: [id],
fields: [...LIST_FIELDS, ...DETAIL_FIELDS],
});
@@ -262,8 +256,8 @@ async function handleTorrents(ctx: OfficerContext, rest: string[]): Promise<Resp
return null;
}
async function addTorrent(req: Request): Promise<Response> {
const body = await readJson(req);
async function addTorrent(ctx: OfficerContext): Promise<Response> {
const body = await readJson(ctx.req);
if (!body) return badRequest('expected a JSON object body');
const args: Record<string, unknown> = {};
@@ -281,7 +275,7 @@ async function addTorrent(req: Request): Promise<Response> {
const result = await rpc<{
'torrent-added'?: { id: number; name: string; hashString: string };
'torrent-duplicate'?: { id: number; name: string; hashString: string };
}>('torrent-add', args);
}>(ctx.userId, 'torrent-add', args);
const added = result['torrent-added'];
const duplicate = result['torrent-duplicate'];
@@ -292,8 +286,8 @@ async function addTorrent(req: Request): Promise<Response> {
return Response.json({ status: 'added', torrent: null });
}
async function runAction(req: Request): Promise<Response> {
const body = await readJson(req);
async function runAction(ctx: OfficerContext): Promise<Response> {
const body = await readJson(ctx.req);
if (!body) return badRequest('expected a JSON object body');
const action = typeof body['action'] === 'string' ? body['action'] : '';
@@ -304,12 +298,12 @@ async function runAction(req: Request): Promise<Response> {
if (!ids) return badRequest('ids must be an array of positive integers');
if (ids.length === 0) return Response.json({ ok: true, affected: 0 });
await rpc(method, { ids });
await rpc(ctx.userId, method, { ids });
return Response.json({ ok: true, affected: ids.length });
}
async function setTorrent(req: Request): Promise<Response> {
const body = await readJson(req);
async function setTorrent(ctx: OfficerContext): Promise<Response> {
const body = await readJson(ctx.req);
if (!body) return badRequest('expected a JSON object body');
const ids = readIds(body);
@@ -319,12 +313,12 @@ async function setTorrent(req: Request): Promise<Response> {
if (Object.keys(fields).length === 0) return badRequest('no writable torrent fields in body');
if (ids.length === 0) return Response.json({ ok: true, affected: 0 });
await rpc('torrent-set', { ids, ...fields });
await rpc(ctx.userId, 'torrent-set', { ids, ...fields });
return Response.json({ ok: true, affected: ids.length });
}
async function setLocation(req: Request): Promise<Response> {
const body = await readJson(req);
async function setLocation(ctx: OfficerContext): Promise<Response> {
const body = await readJson(ctx.req);
if (!body) return badRequest('expected a JSON object body');
const ids = readIds(body);
@@ -336,12 +330,12 @@ async function setLocation(req: Request): Promise<Response> {
// `move: false` re-points the torrent at data already sitting there; `true` physically moves it. Getting
// this backwards either loses the data or copies gigabytes unasked, so it is required, not defaulted.
const move = body['move'] === true;
await rpc('torrent-set-location', { ids, location, move });
await rpc(ctx.userId, 'torrent-set-location', { ids, location, move });
return Response.json({ ok: true, affected: ids.length });
}
async function renamePath(req: Request): Promise<Response> {
const body = await readJson(req);
async function renamePath(ctx: OfficerContext): Promise<Response> {
const body = await readJson(ctx.req);
if (!body) return badRequest('expected a JSON object body');
const id = Number(body['id']);
@@ -352,12 +346,12 @@ async function renamePath(req: Request): Promise<Response> {
if (!name) return badRequest('name is required');
// torrent-rename-path takes ONE id — an array is accepted but the result is undefined. Enforce it.
await rpc('torrent-rename-path', { ids: [id], path, name });
await rpc(ctx.userId, 'torrent-rename-path', { ids: [id], path, name });
return Response.json({ ok: true });
}
async function removeTorrents(req: Request): Promise<Response> {
const body = await readJson(req);
async function removeTorrents(ctx: OfficerContext): Promise<Response> {
const body = await readJson(ctx.req);
if (!body) return badRequest('expected a JSON object body');
const ids = readIds(body);
@@ -365,6 +359,6 @@ async function removeTorrents(req: Request): Promise<Response> {
if (ids.length === 0) return Response.json({ ok: true, affected: 0 });
const deleteLocalData = body['deleteLocalData'] === true;
await rpc('torrent-remove', { ids, 'delete-local-data': deleteLocalData });
await rpc(ctx.userId, 'torrent-remove', { ids, 'delete-local-data': deleteLocalData });
return Response.json({ ok: true, affected: ids.length, deletedData: deleteLocalData });
}
+38 -22
View File
@@ -1,5 +1,6 @@
import type { Torrent, TrackerStat } from './types';
import { getAuthHeader, getRpcPath, getTransmissionBase } from './upstream';
import type { TransmissionConfig } from './upstream';
import { getTransmissionConfig } from './upstream';
// The Transmission RPC call layer. Every upstream request in this sidecar goes through here, so the
// wire-level quirks are handled exactly once:
@@ -12,7 +13,7 @@ import { getAuthHeader, getRpcPath, getTransmissionBase } from './upstream';
// in a way that looks like an auth bug.
// • Errors are NOT signalled by HTTP status. A perfectly successful-looking 200 carries
// `{"result": "some error string"}`; only `result === 'success'` means it worked.
// • Auth is HTTP Basic, and an EMPTY username must send no header at all — see getAuthHeader.
// • Auth is HTTP Basic, and an EMPTY username must send no header at all — see basicAuth in upstream.ts.
// • `torrent-get` with an unknown field name fails the whole call rather than ignoring the field, so
// LIST_FIELDS/DETAIL_FIELDS are curated against the running daemon's rpc-version, not guessed.
@@ -29,32 +30,45 @@ export class TransmissionError extends Error {
}
}
// The CSRF token for the current daemon session. Module-level because it is a property of the connection,
// not of any one request, and every caller benefits from a refresh any one of them performs.
let sessionId: string | null = null;
// The CSRF token for a daemon session, keyed by endpoint rather than by owner: the token belongs to the
// daemon, so two owners pointed at the same one share a refresh, and re-pointing at a different daemon
// cannot carry a token that daemon never issued.
const sessionIds = new Map<string, string>();
type RpcResponse<T> = { result: string; arguments?: T };
/**
* Issue one RPC call. Retries exactly once on 409 after adopting the new session id; a second 409 means
* something other than a stale token (a proxy stripping the header, most likely) and is surfaced.
*/
export async function rpc<T = unknown>(method: string, args: Record<string, unknown> = {}): Promise<T> {
return call<T>(method, args, true);
/** Issue one RPC call against the owner's configured daemon. */
export async function rpc<T = unknown>(userId: number, method: string, args: Record<string, unknown> = {}): Promise<T> {
const cfg = await getTransmissionConfig(userId);
if (!cfg) throw new TransmissionError(503, 'transmission is not connected');
return call<T>(cfg, method, args, true);
}
async function call<T>(method: string, args: Record<string, unknown>, mayRetry: boolean): Promise<T> {
const base = getTransmissionBase();
if (!base) throw new TransmissionError(503, 'TRANSMISSION_URL is not configured');
/** The same call against a connection that may not be stored yet — used to validate one before saving it. */
export async function rpcWith<T = unknown>(
cfg: TransmissionConfig,
method: string,
args: Record<string, unknown> = {},
): Promise<T> {
return call<T>(cfg, method, args, true);
}
async function call<T>(
cfg: TransmissionConfig,
method: string,
args: Record<string, unknown>,
mayRetry: boolean,
): Promise<T> {
const endpoint = `${cfg.base}${cfg.rpcPath}`;
const headers: Record<string, string> = { 'Content-Type': 'application/json' };
const sessionId = sessionIds.get(endpoint);
if (sessionId) headers['X-Transmission-Session-Id'] = sessionId;
const auth = getAuthHeader();
if (auth) headers['Authorization'] = auth;
if (cfg.auth) headers['Authorization'] = cfg.auth;
let res: Response;
try {
res = await fetch(`${base}${getRpcPath()}`, {
res = await fetch(endpoint, {
method: 'POST',
headers,
body: JSON.stringify({ method, arguments: args }),
@@ -68,8 +82,8 @@ async function call<T>(method: string, args: Record<string, unknown>, mayRetry:
if (res.status === 409) {
const fresh = res.headers.get('X-Transmission-Session-Id');
if (fresh && mayRetry) {
sessionId = fresh;
return call<T>(method, args, false);
sessionIds.set(endpoint, fresh);
return call<T>(cfg, method, args, false);
}
throw new TransmissionError(502, 'transmission rejected the session id handshake');
}
@@ -85,10 +99,12 @@ async function call<T>(method: string, args: Record<string, unknown>, mayRetry:
return (body.arguments ?? {}) as T;
}
/** Reachability + credential probe, used by /_health. */
export async function probe(): Promise<{ ok: boolean; version?: string; rpcVersion?: number; error?: string }> {
/** Reachability + credential probe, used by /_health and before a connection is saved. */
export async function probe(
cfg: TransmissionConfig,
): Promise<{ ok: boolean; version?: string; rpcVersion?: number; error?: string }> {
try {
const args = await rpc<{ version: string; 'rpc-version': number }>('session-get', {
const args = await rpcWith<{ version: string; 'rpc-version': number }>(cfg, 'session-get', {
fields: ['version', 'rpc-version'],
});
return { ok: true, version: args.version, rpcVersion: args['rpc-version'] };
+55 -29
View File
@@ -1,46 +1,72 @@
import { getServiceCredentials } from 'officerdb';
// Transmission upstream config for the officer-transmission sidecar.
//
// All knowledge of the Transmission daemon (its URL, its RPC path and its credentials) lives here,
// mirroring the officer-slskd/officer-vault philosophy: the platform API is a thin auth+forward proxy and
// holds NO Transmission credentials.
// All knowledge of the daemon its URL, its RPC path and its credentials lives here. The platform API is
// a thin auth+forward proxy and holds NO Transmission credentials.
//
// The daemon is CONFIGURED BY THE OWNER FROM THE UI and stored in `service_connections` (see
// databases/officer_db/src/queries/service-connections.ts), no longer read from the environment: Bun
// auto-loads `.env` into every process started in the platform directory, so TRANSMISSION_* was also
// sitting in `officer`'s own process.env, and pointing Officer at a daemon meant editing a file on the
// server. Nothing in this file reads process.env.
const { TRANSMISSION_URL, TRANSMISSION_USER, TRANSMISSION_PASS, TRANSMISSION_RPC_PATH } = process.env;
/** Everything needed to make one RPC call. A candidate being validated has this and nothing else yet. */
export type TransmissionConfig = { base: string; rpcPath: string; auth: string | null };
let warnedUnset = false;
/** The Transmission base URL (no trailing slash), or null when unconfigured (the sidecar then 503s). */
export function getTransmissionBase(): string | null {
const raw = TRANSMISSION_URL?.trim();
if (!raw) {
if (!warnedUnset) {
console.warn('[transmission] TRANSMISSION_URL is unset — the sidecar will respond 503 until it is set');
warnedUnset = true;
}
return null;
}
return raw.replace(/\/+$/, '');
}
/** Trailing slashes off, so `${base}${rpcPath}` never doubles the separator. */
export const normalizeBase = (url: string): string => url.trim().replace(/\/+$/, '');
/**
* The RPC endpoint path. Transmission serves it at /transmission/rpc by default, but a reverse proxy can
* mount it anywhere, so it is configurable rather than hardcoded.
* mount it anywhere, so it is stored per connection rather than hardcoded.
*/
export function getRpcPath(): string {
const raw = TRANSMISSION_RPC_PATH?.trim();
if (!raw) return '/transmission/rpc';
return raw.startsWith('/') ? raw : `/${raw}`;
}
export const normalizeRpcPath = (raw: string | null | undefined): string => {
const path = raw?.trim();
if (!path) return '/transmission/rpc';
return path.startsWith('/') ? path : `/${path}`;
};
/**
* The `Authorization: Basic …` header value, or null when the daemon has no auth configured.
*
* Transmission treats an empty username as "no authentication required" — sending an empty Basic header in
* that case is not merely useless, it makes the daemon reject the request. So this returns null unless a
* username is actually set.
* username is actually set, which is why the stored username is nullable rather than defaulting to ''.
*/
export function getAuthHeader(): string | null {
const user = TRANSMISSION_USER?.trim();
export function basicAuth(username: string | null, password: string | null): string | null {
const user = username?.trim();
if (!user) return null;
const pass = TRANSMISSION_PASS ?? '';
return `Basic ${Buffer.from(`${user}:${pass}`).toString('base64')}`;
return `Basic ${Buffer.from(`${user}:${password ?? ''}`).toString('base64')}`;
}
// The torrent list polls every couple of seconds, so the row is cached rather than re-read per request.
// Writes invalidate immediately; the TTL only covers someone editing the row in psql, which then takes
// effect within a minute instead of needing a restart.
const TTL_MS = 60_000;
const cache = new Map<number, { cfg: TransmissionConfig | null; at: number }>();
/**
* The owner's Transmission connection, or null when nothing is configured — the sidecar then answers 503,
* and the UI turns that into the setup form rather than an empty torrent list.
*/
export async function getTransmissionConfig(userId: number): Promise<TransmissionConfig | null> {
const hit = cache.get(userId);
if (hit && Date.now() - hit.at < TTL_MS) return hit.cfg;
const creds = await getServiceCredentials(userId, 'transmission');
const cfg = creds
? {
base: normalizeBase(creds.url),
rpcPath: normalizeRpcPath(creds.path),
auth: basicAuth(creds.username, creds.secret),
}
: null;
cache.set(userId, { cfg, at: Date.now() });
return cfg;
}
/** Drop the cached row — called by the config routes after any save or removal. */
export function invalidateTransmissionConfig(userId: number): void {
cache.delete(userId);
}