Files
jellyfin/sidecar/config.ts
T
pastilhasandClaude Fable 5 05e11f81c9 store the token provisioning mints, so members can open video
Provisioning already created each member's Jellyfin account and signed in as
them to get a token — its own header says the token exists so "the person's
Officer session can already read their library". It was then dropped, because
linkJellyfinAccount had nowhere to put it.

So every non-owner resolved to no config and got a 503 setup form, asking them
to connect a Jellyfin server with a password nobody knows. It reads as a
permissions fault and is not one: the grant, the role and the account list were
all correct.

jellyfin_accounts now carries access_token and device_id, getConfig falls back
to the link row when the caller has no registry of their own, and there is no
path from there to the owner's token — a member resolving to the owner's
credential would read the owner's watch state and every library.

POST /_config/:id/provision repairs accounts linked before the column existed.
It resets the password to mint, which is free on an account Officer created
(random, discarded, known to nobody) and destructive on an adopted one, so
adopted accounts are skipped unless includeAdopted says otherwise.

Applied on alpha: conceiba and guipinto minted and verified against the live
server; fedra and diogo skipped as adopted.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-08-21 15:26:11 +00:00

345 lines
14 KiB
TypeScript

import type { JellyfinServer } from '../db';
import {
createJellyfinServer,
deleteJellyfinServer,
getJellyfinCredentials,
listJellyfinServers,
recordJellyfinProbe,
setActiveJellyfinServer,
updateJellyfinServer,
} from '../db';
import { UpstreamError, authenticate, invalidateConfig, normalizeBase, probe, publicInfo } from './upstream';
import { backfillAccountTokens, runProvisioning } from './provision-run';
import { buildAccountView } from './account-view';
// `/_config` — the Jellyfin server registry, driven from the app.
//
// The access token is WRITE-ONLY across this boundary, and it is never even written directly: the owner
// supplies a URL, a username and a password, and the sidecar trades them for a token through
// `POST /Users/AuthenticateByName`. The password lives for the duration of that one call. The list route
// reports label, URL, account name, server name and version — it has no field that could carry a token,
// masked or otherwise.
//
// A save is validated against the live instance before it is stored, in two steps that answer two different
// questions: `/System/Info/Public` says "this URL is a Jellyfin, and it is called X", and the sign-in says
// "these credentials work on it". Reporting them separately is what makes a typo'd port distinguishable from
// a wrong password in the setup form.
const bad = (error: string, status = 400) => Response.json({ error }, { status });
/** What the browser is allowed to know about the registry. Never includes a token. */
async function serverList(userId: number): Promise<Response> {
const servers = await listJellyfinServers(userId);
const active = servers.find((server) => server.isActive) ?? null;
return Response.json({ configured: !!active, activeId: active?.id ?? null, servers });
}
/** Record that the instance answered, so the UI can tell "never connected" from "was working, now isn't". */
export async function noteProbe(userId: number, id: number, version: string | null): Promise<void> {
await recordJellyfinProbe(userId, id, version).catch(() => {
/* a stale lastSeenAt is not worth failing a request over */
});
}
type ServerBody = { label?: unknown; url?: unknown; username?: unknown; password?: unknown };
const readBody = async (req: Request): Promise<ServerBody> =>
((await req.json().catch(() => null)) as ServerBody | null) ?? {};
const readLabel = (body: ServerBody): string => (typeof body.label === 'string' ? body.label.trim() : '');
const readUrl = (body: ServerBody): string => (typeof body.url === 'string' ? normalizeBase(body.url) : '');
const readUsername = (body: ServerBody): string => (typeof body.username === 'string' ? body.username.trim() : '');
const readPassword = (body: ServerBody): string => (typeof body.password === 'string' ? body.password : '');
const isHttpUrl = (url: string): boolean => /^https?:\/\//i.test(url);
/** Sign-in and reachability failures, in the words of what the owner actually did. */
function upstreamError(err: unknown): string {
if (err instanceof UpstreamError) return err.message;
return `could not reach that URL (${err instanceof Error ? err.message : String(err)})`;
}
const duplicateLabel = (err: unknown): boolean => String(err).includes('uq_jellyfin_servers_user_label');
/**
* Add a server: the URL is identified, the credentials are traded for a token, then the token is stored
* encrypted and the password is dropped.
*
* A fresh `DeviceId` is minted here and only here. It is what Jellyfin keys sessions and remembered devices
* by, so it belongs to the ROW, not to a request — see schema/jellyfin.ts.
*/
async function addServer(req: Request, userId: number): Promise<Response> {
const body = await readBody(req);
const url = readUrl(body);
const username = readUsername(body);
const password = readPassword(body);
let label = readLabel(body);
if (!url) return bad('url is required');
if (!isHttpUrl(url)) return bad('url must start with http:// or https://');
if (!username) return bad('username is required');
if (!password) return bad('password is required');
let info;
try {
info = await publicInfo(url);
} catch (err) {
return bad(upstreamError(err));
}
const deviceId = crypto.randomUUID();
let auth;
try {
auth = await authenticate(url, deviceId, username, password);
} catch (err) {
return bad(upstreamError(err));
}
// An unlabelled server takes the instance's own name, which is nearly always what the owner would type.
// Falling back to the host keeps the switcher readable when the server is unnamed.
if (!label) label = info.serverName ?? new URL(url).host;
// The first server wins the selection: a registry with rows but nothing selected reads as "not connected".
const existing = await listJellyfinServers(userId);
const activate = existing.length === 0;
try {
const server = await createJellyfinServer({
userId,
label,
url,
accessToken: auth.token,
jellyfinUserId: auth.userId,
jellyfinUsername: auth.username ?? username,
deviceId,
serverName: info.serverName,
version: info.version,
activate,
});
invalidateConfig(userId);
// ── Provision, if this connection can ──
//
// The trigger is registering an ADMIN server, not installing the plugin: at install time there is no
// credential, so there is nothing to provision with. This is also the right moment for a re-run — a
// token revoked and re-issued, or the server moving, both come back through here.
//
// Awaited, so the response says what happened rather than the owner discovering it in a log. It can
// take a few seconds against a server with many accounts; that is the honest cost of telling the truth
// in the reply.
const provisioning = await runProvisioning({
userId,
serverId: server.id,
base: url,
token: auth.token,
jellyfinUserId: auth.userId,
deviceId,
});
// And the tokens for anyone this server already knew about. Reconnecting an instance that has been
// registered before is the ordinary case for a moved server or a revoked credential, and its accounts
// are all "already linked" by then — so provisioning alone would report success and change nothing.
const tokens = await backfillAccountTokens({
cfg: { base: url, token: auth.token, jellyfinUserId: auth.userId, deviceId },
serverId: server.id,
});
return Response.json({ server, provisioning, tokens });
} catch (err) {
if (duplicateLabel(err)) return bad(`you already have a server called "${label}"`);
throw err;
}
}
/**
* Edit one server. No password means "keep the stored token", so a rename never needs one re-typed.
*
* Re-authenticating deliberately keeps the row's existing `deviceId`: the point of signing in again is
* usually that the token was revoked, and reusing the device id keeps the new session attached to the same
* entry in Jellyfin's device list instead of adding a second ghost.
*/
async function editServer(req: Request, userId: number, id: number): Promise<Response> {
const body = await readBody(req);
const label = readLabel(body);
const url = readUrl(body);
const username = readUsername(body);
const password = readPassword(body);
const current = await getJellyfinCredentials(userId, id);
if (!current) return bad('no such server', 404);
if (url && !isHttpUrl(url)) return bad('url must start with http:// or https://');
const base = url || normalizeBase(current.url);
let accessToken: string | undefined;
let jellyfinUserId: string | undefined;
let jellyfinUsername: string | null | undefined;
let serverName: string | null | undefined;
let version: string | null | undefined;
if (password) {
if (!username) return bad('username is required to sign in again');
try {
const info = await publicInfo(base);
const auth = await authenticate(base, current.deviceId, username, password);
accessToken = auth.token;
jellyfinUserId = auth.userId;
jellyfinUsername = auth.username ?? username;
serverName = info.serverName;
version = info.version;
} catch (err) {
return bad(upstreamError(err));
}
} else if (url && base !== normalizeBase(current.url)) {
// Moving a server to a new URL without re-authenticating is allowed — a reverse proxy in front of the
// same instance keeps the token valid — but it has to be checked, because pointing at a DIFFERENT
// Jellyfin would leave a row whose token belongs to another server.
const result = await probe({ ...current, base, token: current.accessToken });
if (!result.ok) return bad(result.error ?? 'that URL did not accept the stored token');
serverName = result.serverName;
version = result.version;
}
try {
const server = await updateJellyfinServer(userId, id, {
label: label || undefined,
url: url || undefined,
accessToken,
jellyfinUserId,
jellyfinUsername,
serverName,
version,
});
if (!server) return bad('no such server', 404);
invalidateConfig(userId);
return Response.json({ server });
} catch (err) {
if (duplicateLabel(err)) return bad(`you already have a server called "${label}"`);
throw err;
}
}
/**
* Re-run provisioning against a server already registered, and mint whatever tokens are missing.
*
* The repair action, and the answer to "members cannot open Video". `addServer` does this once, at
* connect; this is the same work without needing the owner to re-type a password they traded away.
*
* Owner-only WITHOUT a permission rule, and worth saying why out loud: every `/_config` route resolves its
* server through `getJellyfinCredentials(userId, id)`, which is scoped to the caller's own rows. A member
* holding `jellyfin` at write reaches this handler and gets a 404, because they have no server registry of
* their own — the credential they read the library with lives on their link row, not here. So the scoping
* that was already there for the registry does this job too.
*/
async function reprovision(req: Request, userId: number, id: number): Promise<Response> {
const creds = await getJellyfinCredentials(userId, id);
if (!creds) return bad('no such server', 404);
const body = ((await req.json().catch(() => null)) as { includeAdopted?: unknown } | null) ?? {};
// `=== true` rather than truthy: this decides whether somebody else's Jellyfin password gets reset, and
// a stray "false" string must not be the thing that turns it on.
const includeAdopted = body.includeAdopted === true;
const base = normalizeBase(creds.url);
const cfg = { base, token: creds.accessToken, jellyfinUserId: creds.jellyfinUserId, deviceId: creds.deviceId };
const provisioning = await runProvisioning({
userId,
serverId: id,
base,
token: creds.accessToken,
jellyfinUserId: creds.jellyfinUserId,
deviceId: creds.deviceId,
});
const tokens = await backfillAccountTokens({ cfg, serverId: id, includeAdopted });
return Response.json({ provisioning, tokens });
}
/** Check one stored server without switching to it — what the "test" button on each row calls. */
async function testServer(userId: number, id: number): Promise<Response> {
const creds = await getJellyfinCredentials(userId, id);
if (!creds) return bad('no such server', 404);
const started = Date.now();
const result = await probe({ ...creds, base: normalizeBase(creds.url), token: creds.accessToken });
const ms = Date.now() - started;
if (!result.ok) return Response.json({ ok: false, error: result.error, ms }, { status: 502 });
await noteProbe(userId, id, result.version);
return Response.json({ ok: true, version: result.version, serverName: result.serverName, ms });
}
export type { JellyfinServer };
/** `subpath` is '' for /_config, or '/<id>', '/<id>/activate', '/<id>/test'. */
export async function handleConfigRoute(req: Request, userId: number, subpath: string): Promise<Response> {
const [, rawId, action] = subpath.split('/');
if (!rawId) {
if (req.method === 'GET') return serverList(userId);
if (req.method === 'POST' || req.method === 'PUT') return addServer(req, userId);
return bad('method not allowed', 405);
}
const id = Number(rawId);
if (!Number.isInteger(id) || id <= 0) return bad('invalid server id', 404);
if (action === 'activate') {
if (req.method !== 'POST') return bad('method not allowed', 405);
const server = await setActiveJellyfinServer(userId, id);
if (!server) return bad('no such server', 404);
invalidateConfig(userId);
return serverList(userId);
}
if (action === 'provision') {
if (req.method !== 'POST') return bad('method not allowed', 405);
return reprovision(req, userId, id);
}
// Who exists on each side, and which pairs are the same person. Read-only and computed on demand —
// nothing is cached, because the interesting case is somebody adding or removing an account in
// Jellyfin's own UI and wondering why Officer disagrees.
if (action === 'users') {
if (req.method !== 'GET') return bad('method not allowed', 405);
const creds = await getJellyfinCredentials(userId, id);
if (!creds) return bad('no such server', 404);
try {
const view = await buildAccountView(
{
base: normalizeBase(creds.url),
token: creds.accessToken,
jellyfinUserId: creds.jellyfinUserId,
deviceId: creds.deviceId,
},
id,
userId,
);
return Response.json(view);
} catch (err) {
// The server being unreachable is the common one, and it is not this route's fault. Reported as a
// reason rather than a 500 so the screen can say so beside the connection details.
return Response.json({ known: false, reason: err instanceof Error ? err.message : String(err) });
}
}
// GET only. It probes one server and reports whether it answered — nothing is written, and nothing is
// switched (that is `activate`, below). It accepted POST as well until 2026-08-06, which made the
// method meaningless for deciding whether this is a read; the permission model needs that answer.
if (action === 'test') {
if (req.method !== 'GET') return bad('method not allowed', 405);
return testServer(userId, id);
}
if (action) return bad('not found', 404);
if (req.method === 'PATCH' || req.method === 'PUT') return editServer(req, userId, id);
if (req.method === 'DELETE') {
const removed = await deleteJellyfinServer(userId, id);
if (!removed) return bad('no such server', 404);
invalidateConfig(userId);
return serverList(userId);
}
return bad('method not allowed', 405);
}