Files
OmniArr/server/index.ts
T

978 lines
33 KiB
TypeScript

import { createServer, type IncomingMessage, type ServerResponse } from 'node:http';
import { readFile } from 'node:fs/promises';
import { BlockList, isIP } from 'node:net';
import { resolve } from 'node:path';
import {
defaultConfig,
HIDEABLE_SECTIONS,
type AppConfig,
type AuthPayload,
type BackupFile,
type MediaCard,
type WishlistEntry,
type WishlistTogglePayload,
type EpisodeRequestPayload,
type SeriesEpisodeRequestPayload,
type EpisodeWatchStateRequest,
type DiskSpaceStatus,
type HideableSection,
type HubPageResponse,
type JellyfinLoginPayload,
type MovieDeletePayload,
type SeasonDeletePayload,
type SeasonRequestPayload,
type TitleDetailsRequest
} from '../shared/contracts.js';
import { decryptJson, deriveEncryptionKey, encryptJson, randomToken, verifyPassword, createPasswordRecord } from './lib/security.js';
import {
loadState,
migrateConfig,
readAdmin,
readAllWishlists,
readEncryptedConfig,
readWishlist,
restoreBackup,
saveAdminAndConfig,
updateEncryptedConfig,
updateWishlist
} from './lib/store.js';
import {
getCalendar,
getConnectionStatuses,
getDashboard,
getHubPage,
getMediaDiskSpace,
searchTitles,
getTitleDetails,
getTmdbLogos,
deleteMovieFiles,
deleteSeasonFiles,
getServiceOptions,
loadJellyfinUsers,
authenticateJellyfinUser,
proxyJellyfinImage,
removeDownload,
requestEpisode,
requestSeriesEpisode,
requestMovie,
requestSeason,
requestSeries,
setEpisodeWatchState,
sanitizeConfig,
getDownloadsResponse,
getProfileLibraryAccess,
dismissCompletedDownload,
dismissAllCompletedDownloads
} from './lib/services.js';
interface SessionRecord {
role: 'admin' | 'user';
userId?: string;
encryptionKey?: Buffer;
expiresAt: number;
}
const PORT = Number(process.env.PORT || 8787);
const SESSION_COOKIE = 'omniarr_session';
const SESSION_TTL_MS = 1000 * 60 * 60 * 12;
const sessions = new Map<string, SessionRecord>();
const sessionUsers = new WeakMap<Buffer, string>();
const failedAttempts = new Map<string, { count: number; lastAttempt: number }>();
const server = createServer(async (request, response) => {
try {
await routeRequest(request, response);
} catch (error) {
console.error('Unhandled request error:', error);
sendJson(response, 500, {
error: error instanceof Error ? error.message : 'Internal server error'
});
}
});
server.listen(PORT, '0.0.0.0', () => {
console.log(`OmniArr server listening on http://127.0.0.1:${PORT}`);
});
setInterval(cleanupSessions, 1000 * 60 * 15).unref();
async function routeRequest(request: IncomingMessage, response: ServerResponse): Promise<void> {
const method = request.method || 'GET';
const url = new URL(request.url || '/', `http://${request.headers.host || '127.0.0.1'}`);
console.log(`${method} ${url.pathname}`);
if (url.pathname === '/api/health' && method === 'GET') {
sendJson(response, 200, {
ok: true
});
return;
}
if (url.pathname === '/api/auth/session' && method === 'GET') {
const state = await loadState();
const session = getSession(request);
sendJson(response, 200, {
needsSetup: !state.admin,
authenticated: Boolean(session),
role: session?.role,
userId: session?.userId
});
return;
}
if (url.pathname === '/api/auth/register' && method === 'POST') {
const state = await loadState();
if (state.admin) {
console.warn('Register blocked: app already initialized');
sendJson(response, 409, { error: 'The app has already been initialized.' });
return;
}
const body = await readJson<AuthPayload>(request);
const password = String(body.password || '');
if (password.length < 8) {
console.warn('Register blocked: password too short');
sendJson(response, 400, { error: 'Password must be at least 8 characters long.' });
return;
}
const record = createPasswordRecord(password);
const configKey = createConfigKey();
await saveAdminAndConfig(
{
...record,
createdAt: new Date().toISOString()
},
encryptJson(defaultConfig, Buffer.from(configKey)),
configKey
);
const token = createSession({ role: 'admin', encryptionKey: Buffer.from(randomToken()) });
setSessionCookie(request, response, token);
resetFailedAttempts(getClientAddress(request));
console.log('Register completed successfully');
sendJson(response, 200, {
ok: true,
needsSetup: false
});
return;
}
if (url.pathname === '/api/auth/login' && method === 'POST') {
const admin = await readAdmin();
if (!admin) {
console.warn('Login blocked: no master password configured');
sendJson(response, 409, { error: 'The app does not have a master password yet.' });
return;
}
if (isRateLimited(getClientAddress(request))) {
console.warn('Login blocked: rate limited');
sendJson(response, 429, { error: 'Too many attempts. Wait one minute.' });
return;
}
const body = await readJson<AuthPayload>(request);
const password = String(body.password || '');
if (!verifyPassword(password, admin)) {
trackFailedAttempt(getClientAddress(request));
console.warn('Login blocked: incorrect password');
sendJson(response, 401, { error: 'Incorrect password.' });
return;
}
const legacyEncryptionKey = deriveEncryptionKey(password, admin.encryptionSalt);
const state = await loadState();
if (!state.configKey && state.config) {
const config = await readConfig(legacyEncryptionKey);
const configKey = createConfigKey();
await migrateConfig(encryptJson(config, Buffer.from(configKey)), configKey);
}
const token = createSession({ role: 'admin', encryptionKey: Buffer.from(randomToken()) });
setSessionCookie(request, response, token);
resetFailedAttempts(getClientAddress(request));
console.log('Login completed successfully');
sendJson(response, 200, {
ok: true,
needsSetup: false
});
return;
}
if (url.pathname === '/api/auth/profiles' && method === 'GET') {
let config: AppConfig;
try {
config = await readConfig();
} catch {
sendJson(response, 409, { error: 'An administrator must sign in once to migrate the existing configuration.' });
return;
}
// A Jellyfin outage is reported through the connection status, so the
// client can show it instead of an empty profile list.
const [jellyfinUsers, connections] = await Promise.all([
loadJellyfinUsers(config.jellyfin.baseUrl, config.jellyfin.apiKey).catch(() => []),
getConnectionStatuses(config)
]);
sendJson(response, 200, { jellyfinUsers, connections });
return;
}
if (url.pathname.startsWith('/api/auth/profile-image/') && method === 'GET') {
const config = await readConfig();
const userId = decodeURIComponent(url.pathname.replace('/api/auth/profile-image/', ''));
const image = await proxyJellyfinImage(config, userId, 'Primary', 160, url.searchParams.get('tag') || '', true);
if (!image) {
sendJson(response, 404, { error: 'Profile image not found.' });
return;
}
response.writeHead(200, { 'Content-Type': image.contentType || 'image/jpeg', 'Cache-Control': 'private, max-age=3600' });
response.end(Buffer.from(image.data));
return;
}
if (url.pathname === '/api/auth/profile-login' && method === 'POST') {
if (isRateLimited(getClientAddress(request))) {
sendJson(response, 429, { error: 'Too many attempts. Wait one minute.' });
return;
}
const body = await readJson<JellyfinLoginPayload>(request);
const config = await readConfig();
const userId = String(body.userId || '');
if (!await authenticateJellyfinUser(config, userId, String(body.password || ''))) {
trackFailedAttempt(getClientAddress(request));
sendJson(response, 401, { error: 'Incorrect Jellyfin password.' });
return;
}
const token = createSession({ role: 'user', userId, encryptionKey: Buffer.from(randomToken()) });
setSessionCookie(request, response, token);
resetFailedAttempts(getClientAddress(request));
sendJson(response, 200, { ok: true, needsSetup: false });
return;
}
if (url.pathname === '/api/auth/logout' && method === 'POST') {
const token = getSessionToken(request);
if (token) {
sessions.delete(token);
}
clearSessionCookie(request, response);
sendJson(response, 200, { ok: true, needsSetup: false });
return;
}
const session = getSession(request);
if (!session && url.pathname.startsWith('/api/')) {
sendJson(response, 401, { error: 'Unauthorized.' });
return;
}
if (url.pathname === '/api/settings' && method === 'PUT' && session?.role !== 'admin') {
sendJson(response, 403, { error: 'Administrator access is required.' });
return;
}
if (url.pathname.startsWith('/api/admin/') && session?.role !== 'admin') {
sendJson(response, 403, { error: 'Administrator access is required.' });
return;
}
if (url.pathname === '/api/admin/profile-access' && method === 'GET') {
const config = await readConfig(session!.encryptionKey);
sendJson(response, 200, { profiles: await getProfileLibraryAccess(config) });
return;
}
// Sections the administrator switched off for this profile are closed on the
// server too, not only hidden from the menu.
const section = session?.role === 'user' && session.userId ? getSectionOfRoute(url.pathname) : null;
if (section) {
const config = await readConfig(session!.encryptionKey);
if ((config.preferences.hiddenSections[session!.userId!] ?? []).includes(section)) {
sendJson(response, 403, { error: 'This section is not available for your profile.' });
return;
}
}
if (url.pathname === '/api/admin/backup' && method === 'GET') {
const backup: BackupFile = {
app: 'omniarr',
format: 1,
exportedAt: new Date().toISOString(),
config: await readConfig(),
wishlists: await readAllWishlists()
};
const fileName = `omniarr-backup-${backup.exportedAt.slice(0, 10)}.json`;
response.writeHead(200, {
'Content-Type': 'application/json; charset=utf-8',
'Content-Disposition': `attachment; filename="${fileName}"`,
'Cache-Control': 'no-store'
});
response.end(JSON.stringify(backup, null, 2));
return;
}
if (url.pathname === '/api/admin/backup' && method === 'POST') {
let body: Partial<BackupFile>;
let config: AppConfig;
try {
body = await readJson<Partial<BackupFile>>(request);
if (body.app !== 'omniarr' || body.format !== 1 || !body.config || typeof body.config !== 'object') {
throw new Error('invalid');
}
config = mergeStoredConfig(body.config);
} catch {
sendJson(response, 400, { error: 'This file is not an OmniArr backup.' });
return;
}
config = { ...config, jellyfin: { ...config.jellyfin, userId: '' } };
await restoreBackup(
encryptJson(config, await getConfigEncryptionKey()),
sanitizeWishlists(body.wishlists)
);
sendJson(response, 200, { config, connections: await getConnectionStatuses(config) });
return;
}
if (url.pathname === '/api/wishlist' && method === 'GET') {
sendJson(response, 200, { items: await readWishlist(getWishlistOwner(session!)) });
return;
}
if (url.pathname === '/api/wishlist' && method === 'POST') {
const body = await readJson<WishlistTogglePayload>(request);
const card = sanitizeWishlistCard(body.card);
if (!card) {
sendJson(response, 400, { error: 'A title is required.' });
return;
}
const key = getWishlistKey(card);
const items = await updateWishlist(getWishlistOwner(session!), (entries) => {
const remaining = entries.filter((entry) => getWishlistKey(entry.card) !== key);
return body.wishlisted ? [{ card, addedAt: new Date().toISOString() }, ...remaining] : remaining;
});
sendJson(response, 200, { items });
return;
}
if (url.pathname === '/api/settings' && method === 'GET') {
const config = await readConfig(session!.encryptionKey);
sendJson(response, 200, session!.role === 'admin' ? config : redactConfig(config));
return;
}
if (url.pathname === '/api/settings' && method === 'PUT') {
const body = await readJson<AppConfig>(request);
const sanitized = sanitizeConfig(body);
const config = { ...sanitized, jellyfin: { ...sanitized.jellyfin, userId: '' } };
await updateEncryptedConfig(encryptJson(config, await getConfigEncryptionKey()));
const connections = await getConnectionStatuses(config);
sendJson(response, 200, {
config,
connections
});
return;
}
if (url.pathname === '/api/settings/options' && method === 'GET') {
const config = await readConfig(session!.encryptionKey);
sendJson(response, 200, await getServiceOptions(config));
return;
}
if (url.pathname === '/api/settings/jellyfin-users' && method === 'POST') {
const body = await readJson<{ baseUrl: string; apiKey: string }>(request);
sendJson(response, 200, {
jellyfinUsers: await loadJellyfinUsers(String(body.baseUrl || ''), String(body.apiKey || ''))
});
return;
}
if (url.pathname === '/api/dashboard' && method === 'GET') {
const config = await readConfig(session!.encryptionKey);
sendJson(response, 200, await getDashboard(config));
return;
}
if (url.pathname === '/api/storage' && method === 'GET') {
const config = await readConfig(session!.encryptionKey);
sendJson(response, 200, await getDiskSpaceStatus(config));
return;
}
if (url.pathname.startsWith('/api/hubs/') && method === 'GET') {
const config = await readConfig(session!.encryptionKey);
const page = decodeURIComponent(url.pathname.replace('/api/hubs/', ''));
console.log(`[API] GET /api/hubs/${page}`);
try {
const result = await getHubPage(config, page as HubPageResponse['page']);
sendJson(response, 200, result);
} catch (err) {
console.error(`[API] Error in GET /api/hubs/${page}:`, err);
sendJson(response, 500, { error: err instanceof Error ? err.message : 'Internal server error' });
}
return;
}
if (url.pathname === '/api/downloads' && method === 'GET') {
const config = await readConfig(session!.encryptionKey);
sendJson(response, 200, await getDownloadsResponse(config));
return;
}
if (url.pathname === '/api/calendar' && method === 'GET') {
const config = await readConfig(session!.encryptionKey);
const startParam = url.searchParams.get('start');
const endParam = url.searchParams.get('end');
let start = new Date();
start.setDate(1);
start.setHours(0, 0, 0, 0);
let end = new Date(start);
end.setMonth(end.getMonth() + 1);
end.setDate(0);
end.setHours(23, 59, 59, 999);
if (startParam) {
try {
start = new Date(startParam);
} catch {
// ignore invalid date
}
}
if (endParam) {
try {
end = new Date(endParam);
} catch {
// ignore invalid date
}
}
sendJson(response, 200, await getCalendar(config, start, end));
return;
}
if (url.pathname === '/api/search' && method === 'GET') {
const config = await readConfig(session!.encryptionKey);
const query = String(url.searchParams.get('query') || '');
sendJson(response, 200, await searchTitles(config, query));
return;
}
if (url.pathname === '/api/title-details' && method === 'POST') {
const config = await readConfig(session!.encryptionKey);
const body = await readJson<TitleDetailsRequest>(request);
sendJson(response, 200, await getTitleDetails(config, body));
return;
}
if (url.pathname === '/api/episodes/watch-state' && method === 'POST') {
const config = await readConfig(session!.encryptionKey);
const body = await readJson<EpisodeWatchStateRequest>(request);
await setEpisodeWatchState(config, body);
sendJson(response, 200, { ok: true });
return;
}
if (url.pathname === '/api/downloads/delete' && method === 'POST') {
const config = await readConfig(session!.encryptionKey);
const body = await readJson<{ id: string }>(request);
await removeDownload(config, String(body.id || ''));
sendJson(response, 200, { ok: true });
return;
}
if (url.pathname === '/api/downloads/dismiss' && method === 'POST') {
const body = await readJson<{ id: string }>(request);
dismissCompletedDownload(String(body.id || ''));
sendJson(response, 200, { ok: true });
return;
}
if (url.pathname === '/api/downloads/dismiss-all' && method === 'POST') {
dismissAllCompletedDownloads();
sendJson(response, 200, { ok: true });
return;
}
if (url.pathname === '/api/requests/movie' && method === 'POST') {
const config = await readConfig(session!.encryptionKey);
const body = await readJson<{ tmdbId: number; user: string | null; qualityProfileId?: number }>(request);
await requestMovie(config, Number(body.tmdbId), body.user, Number(body.qualityProfileId) || undefined);
sendJson(response, 200, { ok: true });
return;
}
if (url.pathname === '/api/requests/series' && method === 'POST') {
const config = await readConfig(session!.encryptionKey);
const body = await readJson<{ tmdbId: number; user: string | null; qualityProfileId?: number; seasonNumber?: number }>(request);
await requestSeries(config, Number(body.tmdbId), body.user, Number(body.qualityProfileId) || undefined, Number(body.seasonNumber) || undefined);
sendJson(response, 200, { ok: true });
return;
}
if (url.pathname === '/api/requests/season' && method === 'POST') {
const config = await readConfig(session!.encryptionKey);
const body = await readJson<SeasonRequestPayload & { user: string | null }>(request);
await requestSeason(config, body, body.user);
sendJson(response, 200, { ok: true });
return;
}
if (url.pathname === '/api/requests/episode' && method === 'POST') {
const config = await readConfig(session!.encryptionKey);
const body = await readJson<EpisodeRequestPayload & { user:string | null }>(request);
await requestEpisode(config, body, body.user);
sendJson(response, 200, { ok: true });
return;
}
if (url.pathname === '/api/requests/series-episode' && method === 'POST') {
const config = await readConfig(session!.encryptionKey);
const body = await readJson<SeriesEpisodeRequestPayload & { user: string | null }>(request);
await requestSeriesEpisode(config, body, body.user);
sendJson(response, 200, { ok: true });
return;
}
if (url.pathname === '/api/seasons/delete' && method === 'POST') {
const config = await readConfig(session!.encryptionKey);
const body = await readJson<SeasonDeletePayload>(request);
await deleteSeasonFiles(config, body);
sendJson(response, 200, { ok: true });
return;
}
if (url.pathname === '/api/movies/delete' && method === 'POST') {
const config = await readConfig(session!.encryptionKey);
const body = await readJson<MovieDeletePayload>(request);
await deleteMovieFiles(config, body);
sendJson(response, 200, { ok: true });
return;
}
if (url.pathname.startsWith('/api/assets/jellyfin/') && method === 'GET') {
const config = await readConfig(session!.encryptionKey);
const itemId = decodeURIComponent(url.pathname.replace('/api/assets/jellyfin/', ''));
const kind = url.searchParams.get('kind') || 'Primary';
const maxWidth = Number(url.searchParams.get('maxWidth') || 640);
const tag = url.searchParams.get('tag') || '';
const image = await proxyJellyfinImage(config, itemId, kind, maxWidth, tag);
if (!image) {
response.writeHead(302, {
Location: '/placeholder.jpg',
'Cache-Control': 'private, max-age=300'
});
response.end();
return;
}
response.writeHead(200, {
'Content-Type': image.contentType || 'image/jpeg',
'Cache-Control': 'private, max-age=300'
});
response.end(Buffer.from(image.data));
return;
}
if (url.pathname === '/api/tmdb/logo' && method === 'GET') {
const config = await readConfig(session!.encryptionKey);
const tmdbId = Number(url.searchParams.get('tmdbId') || 0);
const mediaTypeParam = url.searchParams.get('mediaType');
const mediaType = mediaTypeParam === 'tv' ? 'tv' : mediaTypeParam === 'movie' ? 'movie' : null;
if (!tmdbId || !mediaType) {
sendJson(response, 400, { error: 'tmdbId and mediaType are required.' });
return;
}
const logos = await getTmdbLogos(config, tmdbId, mediaType);
sendJson(response, 200, { logos });
return;
}
await serveApp(url.pathname, response);
}
function createSession(session: Omit<SessionRecord, 'expiresAt'>): string {
const token = randomToken();
if (session.userId && session.encryptionKey) {
sessionUsers.set(session.encryptionKey, session.userId);
}
sessions.set(token, {
...session,
expiresAt: Date.now() + SESSION_TTL_MS
});
return token;
}
function createConfigKey(): string {
return randomToken().slice(0, 32);
}
async function getDiskSpaceStatus(config: AppConfig): Promise<DiskSpaceStatus | null> {
return getMediaDiskSpace(config);
}
function getSession(request: IncomingMessage): SessionRecord | null {
const token = getSessionToken(request);
if (!token) {
return null;
}
const session = sessions.get(token);
if (!session) {
return null;
}
if (session.expiresAt < Date.now()) {
sessions.delete(token);
return null;
}
session.expiresAt = Date.now() + SESSION_TTL_MS;
return session;
}
function getSessionToken(request: IncomingMessage): string | null {
const cookieHeader = request.headers.cookie;
if (!cookieHeader) {
return null;
}
for (const part of cookieHeader.split(';')) {
const [key, value] = part.trim().split('=');
if (key === SESSION_COOKIE && value) {
return value;
}
}
return null;
}
// Mark the cookie Secure only when the browser reached us over HTTPS, so plain
// HTTP access on a LAN still works.
function isSecureRequest(request: IncomingMessage): boolean {
if ('encrypted' in request.socket && request.socket.encrypted) {
return true;
}
const forwardedProto = request.headers['x-forwarded-proto'];
const proto = (Array.isArray(forwardedProto) ? forwardedProto[0] : forwardedProto)?.split(',')[0].trim().toLowerCase();
return proto === 'https';
}
function setSessionCookie(request: IncomingMessage, response: ServerResponse, token: string): void {
const isSecure = isSecureRequest(request);
response.setHeader(
'Set-Cookie',
`${SESSION_COOKIE}=${token}; HttpOnly; Path=/; SameSite=Strict; Max-Age=${Math.floor(SESSION_TTL_MS / 1000)}${isSecure ? '; Secure' : ''}`
);
}
function clearSessionCookie(request: IncomingMessage, response: ServerResponse): void {
const isSecure = isSecureRequest(request);
response.setHeader(
'Set-Cookie',
`${SESSION_COOKIE}=; HttpOnly; Path=/; SameSite=Strict; Max-Age=0${isSecure ? '; Secure' : ''}`
);
}
async function readConfig(legacyEncryptionKey?: Buffer): Promise<AppConfig> {
const encrypted = await readEncryptedConfig();
if (!encrypted) {
return defaultConfig;
}
const state = await loadState();
const encryptionKey = state.configKey ? Buffer.from(state.configKey) : legacyEncryptionKey;
if (!encryptionKey) {
throw new Error('The configuration must be unlocked by an administrator.');
}
const config = mergeStoredConfig(decryptJson<Partial<AppConfig>>(encrypted, encryptionKey));
// The Jellyfin user always comes from the profile the session signed in
// with; admin sessions have none, so a userId saved by older versions is ignored.
const userId = legacyEncryptionKey ? sessionUsers.get(legacyEncryptionKey) : undefined;
return { ...config, jellyfin: { ...config.jellyfin, userId: userId || '' } };
}
// Fills in whatever a stored config (or an imported backup) leaves out with
// the defaults, so configs saved by older versions keep loading.
function mergeStoredConfig(stored: Partial<AppConfig>): AppConfig {
return sanitizeConfig({
preferences: {
...defaultConfig.preferences,
...(stored.preferences || {})
},
jellyfin: {
...defaultConfig.jellyfin,
...(stored.jellyfin || {})
},
sonarr: {
...defaultConfig.sonarr,
...(stored.sonarr || {})
},
radarr: {
...defaultConfig.radarr,
...(stored.radarr || {})
},
tmdb: {
...defaultConfig.tmdb,
...(stored.tmdb || {})
},
tvdb: {
...defaultConfig.tvdb,
...(stored.tvdb || {})
}
});
}
// Profiles keep their own wishlist; the administrator has no Jellyfin profile
// and shares a single one.
// The section of the app an API route serves, if the administrator can switch it off.
function getSectionOfRoute(pathname: string): HideableSection | null {
const section = pathname.startsWith('/api/downloads') ? 'downloads'
: pathname.startsWith('/api/calendar') ? 'calendar'
: pathname.startsWith('/api/search') ? 'search'
: pathname.startsWith('/api/hubs/') ? decodeURIComponent(pathname.replace('/api/hubs/', ''))
: '';
return HIDEABLE_SECTIONS.find((candidate) => candidate.id === section)?.id ?? null;
}
function getWishlistOwner(session: SessionRecord): string {
return session.role === 'user' && session.userId ? session.userId : 'admin';
}
// The same title can reach the client as a Jellyfin card or a TMDb card, so
// titles are matched by their TMDb id when they have one.
function getWishlistKey(card: MediaCard): string {
return card.tmdbId ? `${card.mediaType === 'movie' ? 'movie' : 'tv'}:${card.tmdbId}` : card.id;
}
const WISHLIST_MEDIA_TYPES = new Set<MediaCard['mediaType']>(['movie', 'tv', 'series']);
// Only what the wishlist page needs to draw a tile and open the title is kept;
// progress and labels belong to the moment the card was saved.
function sanitizeWishlistCard(input: unknown): MediaCard | null {
if (!input || typeof input !== 'object') {
return null;
}
const card = input as Partial<MediaCard>;
const text = (value: unknown) => (typeof value === 'string' ? value : '');
const id = text(card.id);
if (!id || !card.mediaType || !WISHLIST_MEDIA_TYPES.has(card.mediaType)) {
return null;
}
return {
id,
tmdbId: Number(card.tmdbId) || undefined,
providerId: text(card.providerId) || undefined,
title: text(card.title),
subtitle: text(card.subtitle),
overview: text(card.overview),
mediaType: card.mediaType,
posterUrl: text(card.posterUrl),
backdropUrl: text(card.backdropUrl),
logoUrl: text(card.logoUrl) || undefined,
backdropLanguageFallback: card.backdropLanguageFallback ? true : undefined,
releaseDate: text(card.releaseDate) || undefined,
firstAirDate: text(card.firstAirDate) || undefined
};
}
function sanitizeWishlists(input: unknown): Record<string, WishlistEntry[]> {
const wishlists: Record<string, WishlistEntry[]> = {};
if (!input || typeof input !== 'object') {
return wishlists;
}
for (const [owner, entries] of Object.entries(input)) {
if (!Array.isArray(entries)) {
continue;
}
wishlists[owner] = entries.flatMap((entry: Partial<WishlistEntry>) => {
const card = sanitizeWishlistCard(entry?.card);
return card ? [{ card, addedAt: typeof entry.addedAt === 'string' ? entry.addedAt : new Date().toISOString() }] : [];
});
}
return wishlists;
}
async function getConfigEncryptionKey(): Promise<Buffer> {
const state = await loadState();
if (!state.configKey) {
throw new Error('The configuration must be unlocked by an administrator.');
}
return Buffer.from(state.configKey);
}
function redactConfig(config: AppConfig): AppConfig {
return {
...config,
jellyfin: { ...config.jellyfin, apiKey: 'configured' },
sonarr: { ...config.sonarr, apiKey: '' },
radarr: { ...config.radarr, apiKey: '' },
tmdb: { ...config.tmdb, bearerToken: '' },
tvdb: { ...config.tvdb, apiKey: '' }
};
}
async function readJson<T>(request: IncomingMessage): Promise<T> {
const chunks: Buffer[] = [];
for await (const chunk of request) {
chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
}
const raw = Buffer.concat(chunks).toString('utf8');
if (!raw) {
return {} as T;
}
return JSON.parse(raw) as T;
}
function sendJson(response: ServerResponse, statusCode: number, payload: unknown): void {
response.writeHead(statusCode, {
'Content-Type': 'application/json; charset=utf-8',
'Cache-Control': 'no-store'
});
response.end(JSON.stringify(payload));
}
async function serveApp(pathname: string, response: ServerResponse): Promise<void> {
const relativePath = pathname === '/' ? '/index.html' : pathname;
const filePath = resolve(process.cwd(), 'dist', `.${relativePath}`);
try {
const content = await readFile(filePath);
response.writeHead(200, {
'Content-Type': contentType(filePath),
// Hashed bundles never change; the entry page must always be revalidated so a new release reaches every browser.
'Cache-Control': relativePath.startsWith('/assets/') ? 'public, max-age=31536000, immutable' : 'no-cache'
});
response.end(content);
} catch {
try {
const indexHtml = await readFile(resolve(process.cwd(), 'dist', 'index.html'));
response.writeHead(200, {
'Content-Type': 'text/html; charset=utf-8',
'Cache-Control': 'no-cache'
});
response.end(indexHtml);
} catch {
response.writeHead(404, {
'Content-Type': 'text/plain; charset=utf-8'
});
response.end('Build the frontend first with `npm run build`.');
}
}
}
function contentType(filePath: string): string {
if (filePath.endsWith('.js')) {
return 'text/javascript; charset=utf-8';
}
if (filePath.endsWith('.css')) {
return 'text/css; charset=utf-8';
}
if (filePath.endsWith('.svg')) {
return 'image/svg+xml';
}
if (filePath.endsWith('.png')) {
return 'image/png';
}
if (filePath.endsWith('.jpg') || filePath.endsWith('.jpeg')) {
return 'image/jpeg';
}
if (filePath.endsWith('.html')) {
return 'text/html; charset=utf-8';
}
return 'application/octet-stream';
}
const PRIVATE_NETWORKS = new BlockList();
PRIVATE_NETWORKS.addSubnet('127.0.0.0', 8, 'ipv4');
PRIVATE_NETWORKS.addSubnet('10.0.0.0', 8, 'ipv4');
PRIVATE_NETWORKS.addSubnet('172.16.0.0', 12, 'ipv4');
PRIVATE_NETWORKS.addSubnet('192.168.0.0', 16, 'ipv4');
PRIVATE_NETWORKS.addSubnet('169.254.0.0', 16, 'ipv4');
PRIVATE_NETWORKS.addAddress('::1', 'ipv6');
PRIVATE_NETWORKS.addSubnet('fc00::', 7, 'ipv6');
PRIVATE_NETWORKS.addSubnet('fe80::', 10, 'ipv6');
function normalizeAddress(address: string): string {
const trimmed = address.trim();
return trimmed.toLowerCase().startsWith('::ffff:') && isIP(trimmed.slice(7)) === 4 ? trimmed.slice(7) : trimmed;
}
function isPrivateAddress(address: string): boolean {
const version = isIP(address);
return version !== 0 && PRIVATE_NETWORKS.check(address, version === 4 ? 'ipv4' : 'ipv6');
}
// Behind a reverse proxy every request comes from the proxy's address, so the
// forwarded client IP is used instead. It is only trusted when the connection
// itself comes from a private network, where the proxy lives; requests from
// the internet cannot spoof it.
function getClientAddress(request: IncomingMessage): string {
const socketAddress = normalizeAddress(request.socket.remoteAddress || '');
if (!isPrivateAddress(socketAddress)) {
return socketAddress || 'unknown';
}
const forwardedFor = request.headers['x-forwarded-for'];
const realIp = request.headers['x-real-ip'];
const chain = (Array.isArray(forwardedFor) ? forwardedFor.join(',') : forwardedFor || (Array.isArray(realIp) ? realIp[0] : realIp) || '')
.split(',')
.map(normalizeAddress)
.filter((address) => isIP(address) !== 0);
if (chain.length === 0) {
return socketAddress;
}
// Each proxy appends the address it saw, so walk from the right and take the
// first public address; anything left of it could be forged by the client.
for (let index = chain.length - 1; index >= 0; index -= 1) {
if (!isPrivateAddress(chain[index])) {
return chain[index];
}
}
return chain[0];
}
function trackFailedAttempt(address: string): void {
const current = failedAttempts.get(address);
failedAttempts.set(address, {
count: (current?.count || 0) + 1,
lastAttempt: Date.now()
});
}
function resetFailedAttempts(address: string): void {
failedAttempts.delete(address);
}
function isRateLimited(address: string): boolean {
const current = failedAttempts.get(address);
if (!current) {
return false;
}
if (Date.now() - current.lastAttempt > 60_000) {
failedAttempts.delete(address);
return false;
}
return current.count >= 5;
}
function cleanupSessions(): void {
const now = Date.now();
for (const [token, session] of sessions.entries()) {
if (session.expiresAt < now) {
sessions.delete(token);
}
}
}