Files
pastilhasandClaude Opus 5 864dd16355 transmission, extracted from the platform into its own repository
The sixth plugin out, immediately after photos. A sidecar, a proxy router and
29 web files; no db/ directory, because there are no tables.

── The one thing that is not self-contained ──

The connection lives in `service_connections`, a CORE table, reached through
getServiceConnection/saveServiceConnection/getServiceCredentials. This plugin
declares no schema.

Deliberate: that table is the app store's shared credential store, keyed on
(user_id, service), already encrypted at rest and already read by
app-store/effects.ts. A private copy of the same three columns would be a
second place the same fact could live, and the runbook is explicit that a move
plus a data-format change gives any failure two causes.

The cost, stated rather than hidden: this plugin depends on a core facility it
does not own, and would break if that table changed shape. Photos, by contrast,
owns photos_config outright.

── 38 palette classes paid down, mapped by meaning ──

  blue     downloading / download speed  -> info
  cyan     checking (verifying)          -> busy
  emerald  seeding / complete            -> success
  amber    queued / stalled / warnings   -> warning

Collapsing blue and cyan into one tone would have lost a real distinction in
the status dot, so `checking` went to `busy` — in-progress work, which is what
that tone is for.

── A near-miss worth recording ──

The first copy globbed *.tsx and *.ts and silently missed detail/ and dialogs/
— ten components. tsgo caught it as ten "cannot find module" errors. Worth
stating because it is quiet in the other direction: had those been imported
lazily, the typecheck would have passed and the panels would have broken at
runtime. Check the directory tree, not the file glob.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-18 19:19:30 +00:00

92 lines
4.4 KiB
TypeScript

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);
}