/** * Navidrome MCP Server - Web remote sessions and admin credential * Copyright (C) 2025 * SPDX-License-Identifier: AGPL-3.0-or-later */ import type { IncomingMessage, ServerResponse } from 'node:http'; import type { Config, ConfigSource } from '../../config.js'; import { type WebuiAdminAccess, type WebuiAuthMode } from '../../constants/defaults.js'; import { type QueuedNames } from '../jukebox/jukebox-names.js'; import { type AdminSession, type Ban, type GuestSession, type JukeboxCode, type SessionRecord } from './auth-store.js'; import { LoginThrottle } from './login-throttle.js'; export declare const MAX_GUESTS_PER_CODE = 100; /** * `closed` is the host closing the jukebox, `new-code` a new code made in place of the guests' code, * `idle` a guest's idle expiry under a live code, `expired` the code's expiry, `removed` a sign-out or * ban of one guest. */ type GuestEndReason = 'closed' | 'expired' | 'idle' | 'new-code' | 'removed'; export interface MintedSession { token: string; session: S; } interface JukeboxStatus { active: boolean; createdAt: number | null; expiresAt: number | null; guestCount: number; } interface JukeboxShare extends JukeboxStatus { key: string | null; } /** The `jukebox` field of the guest stream. `joinedAt` names the session, since a rotation can change `expiresAt`. */ export interface GuestJukebox { label: string; nickname: string | null; expiresAt: number | null; joinedAt: number; } /** An admin session queues from the guest page as the host, under the host nickname or `Host`. */ export declare function jukeboxNameOf(session: SessionRecord): string; export declare function jukeboxNicknameOf(session: SessionRecord): string | null; export interface GuestStatus { session: GuestSession; online: boolean; } type BanResult = { kind: 'banned'; session: GuestSession; bans: Ban[]; } | { kind: 'not-found'; } | { kind: 'loopback'; } | { kind: 'own-network'; }; type JoinResult = ({ kind: 'joined'; } & MintedSession) | { kind: 'kept'; session: GuestSession; } | { kind: 'invalid'; } | { kind: 'full'; } | { kind: 'banned'; } | { kind: 'name-taken'; message: string; }; /** `presented` is false when the request carried no usable device cookie, so `id` is new. */ export interface BrowserDevice { id: string; presented: boolean; } /** The saved `webui.auth` values a store-run player applies while it runs. A mode change needs a restart. */ export type SavedAuth = Pick; interface AuthServiceOptions { source?: ConfigSource; envAdminHash?: string | null; now?: () => number; /** Store mode only. Undefined means the store is absent, unreadable or invalid, so the current values stay. */ readSavedAuth?: () => SavedAuth | undefined; } /** The guest page reads this last event to say why its jukebox ended. */ export declare function endGuestStream(res: ServerResponse, reason: GuestEndReason): void; /** * Owns the admin credential, the jukebox code, the session table, the bans and the streams each session * holds open. Mode `none` keeps it empty and touches the auth store only to drop the jukebox state. */ export declare class AuthService { readonly mode: WebuiAuthMode; readonly throttle: LoginThrottle; readonly source: ConfigSource; /** Made at each start, so a key from an earlier start opens nothing. */ readonly launchKey: string; private readonly port; private readonly cookieName; private readonly deviceCookieName; private readonly secureCookie; private readonly now; private readonly readSavedAuth; private currentAdminAccess; private currentAskPassword; private readonly sessions; private readonly streams; private readonly publicJoins; private readonly localJoins; private readonly nicknameChanges; private readonly passwordlessLogins; private jukeboxCode; private bans; private readonly envAdminHash; private configuredHash; private adminHash; private credentialEpoch; private dirty; private lastWriteAt; constructor(config: Config, options?: AuthServiceOptions); /** * Hashes WEBUI_ADMIN_PASSWORD, so construction itself stays synchronous. Sessions wait for * `claimStore`, since a process that loses the port race must not overwrite the owner's store. */ static load(config: Config, source: ConfigSource, envAdminPassword: string | null): Promise; /** * Called once the port is owned. The previous owner may have changed the sessions since `load`, * so they come from a fresh read, and the write drops the dead ones. The jukebox code loads first, * since a guest session and a guest ban live only while their code does. A start in another mode drops the code, its * guests and their guest bans, so a later jukebox start never revives an old QR code. An admin session * whose last request the admin access level does not admit ends, the rule a live narrowing applies. */ claimStore(): void; /** A store-run player changes it while it runs, so a caller reads it at each use and never keeps a copy. */ get adminAccess(): WebuiAdminAccess; /** A store-run player changes it while it runs, so a caller reads it at each use and never keeps a copy. */ get askPasswordOnThisComputer(): boolean; hasAdminPassword(): boolean; isLaunchKey(presented: string | undefined): boolean; verifyAdminPassword(password: string): Promise; /** * The heartbeat or another request can swap the credential while the hash runs, so a password that matched the old * credential starts no session under the new one. */ login(password: string, address: string, local: boolean): Promise; /** Every cookie of the session name is tried, since a stale one may come first. */ findSession(req: IncomingMessage): SessionRecord | null; /** * Slides the idle expiry, which never passes the admin absolute cap or the guest's jukebox code expiry. * `local` is whether the request passed `isLocalRequest`. Only an admin session keeps it. */ touch(session: SessionRecord, address: string, local: boolean): void; /** Returns the token, which only the cookie carries. The store keeps the secret's digest. */ createSession(address: string, local: boolean): MintedSession; /** A session minted while the ask is off carries its own epoch, so turning the ask back on ends it. */ createPasswordlessSession(address: string, local: boolean): MintedSession; private mintAdminSession; deleteSession(sessionId: string): void; sessionCookie(token: string): string; /** * A rotation can move a kept guest to a later code expiry, and no path re-sends its cookie, so the * cookie takes the longest code lifetime. The session's own expiry on the server bounds the access. */ guestSessionCookie(token: string): string; /** The first well-formed device cookie names the browser. A request with none gets a new id. */ deviceOf(req: IncomingMessage): BrowserDevice; deviceCookie(deviceId: string): string; hasJukeboxCode(): boolean; jukeboxStatus(): JukeboxStatus; /** * The status and raw key come from one clock reading, so an expiry between them never shows an open * jukebox with no links. Only `GET /api/jukebox/code` and `POST /api/jukebox/key` send the key. */ jukeboxShare(): JukeboxShare; /** * A rotation that keeps the guests moves them to the new code, with their idle expiry capped by the * new code's expiry, and their numbering continues. Every rotation moves the guest bans to the new * code, so a new code never lets a banned browser back in. */ createJukeboxCode(lifetimeHours: number, signOutGuests: boolean): { key: string; jukeboxCode: JukeboxCode; rotated: boolean; }; /** Returns false when no live code existed. A code past its expiry that the sweep has not reached is still removed. */ revokeJukeboxCode(): boolean; /** Spends one join from the source's budget. Returns 0 then, or the wait in milliseconds. */ takeJoinToken(budgetKey: string, publicSource: boolean): number; /** Spends one name change from the guest or host session's budget. Returns 0 then, or the wait in milliseconds. */ takeNicknameToken(sessionId: string): number; /** Spends one passwordless login from the network's budget. Returns 0 then, or the wait in milliseconds. */ takePasswordlessLoginToken(networkKey: string): number; /** * Only the host's songs may show a host name, so a guest may not take one that reads as `Host` or a host nickname. * The host may not take a guest's name or label. Returns the refusal message, or null when the name is free. */ jukeboxNameConflict(nickname: string, role: SessionRecord['role'], queuedNames: QueuedNames): string | null; /** The store write is batched, as for a last-seen update. An admin session stores the host nickname. */ setJukeboxNickname(session: SessionRecord, nickname: string): void; /** * A banned browser is refused before its key is checked, so a new code tells it the same reason. A * requester that already holds a guest session for the current code keeps it, and a nickname it * sends is ignored. The nickname route changes a stored name, since a kept join spends no budget. * The name check runs last, so only a holder of the live code learns a host nickname. */ join(key: string, nickname: string | null, address: string, current: GuestSession | null, deviceId: string, queuedNames: () => QueuedNames): JoinResult; /** An admin join mints nothing, so this check alone makes a dead link fail for the host too. */ isLiveJukeboxCode(key: string): boolean; /** * Null once the session is gone. An admin session uses the guest page as the host while a code exists. * An expired code stays until the sweep, so the sweep ends the host's stream with its reason. */ guestJukeboxFor(sessionId: string): GuestJukebox | null; /** Online means an open stream, or a request within `GUEST_ONLINE_WINDOW_MS`. */ listGuests(): GuestStatus[]; /** A guest session queues while it is live, and an admin session queues as the host only while a code is live too. */ isLiveJukeboxSession(sessionId: string): boolean; /** Ends the guest session and its streams. The jukebox code still admits the guest. */ signOutGuest(sessionId: string): GuestSession | null; /** * Ends the guest session and records a `guest` ban on its browser, plus a `network` ban when * `networkBanHours` is above 0. A network ban is refused on a loopback source, which no network ban * blocks, and on the requester's own network, since it would lock the admin out of the page that lifts it. */ banGuest(sessionId: string, networkBanHours: number, requesterAddress: string | undefined): BanResult; /** A network ban on one of these keys also blocks an admin device, so the ban panel warns about it. */ adminNetworkKeys(): Set; /** Leaves out an expired ban that the sweep has not pruned yet. */ listBans(): Ban[]; liftBan(banId: string): Ban | null; /** Mode `none` has no bans, and a loopback source is the host, which no network ban blocks. */ isNetworkBanned(remoteAddress: string | undefined): boolean; expiredSessionCookie(): string; isCsrfTokenValid(session: SessionRecord, presented: string | string[] | undefined): boolean; /** Logout, expiry and a password change close the session's streams at once through this. */ trackStream(sessionId: string, res: ServerResponse, address: string | undefined, guestPage?: boolean): void; /** * Runs on the SSE heartbeat, so an expired session, an expired jukebox code, a changed password, an ask * turned back on or a narrowed admin access level ends the affected streams within one beat. */ sweep(): void; /** * The settings page writes these values to the store, and only a store-run player reads them back. * The heartbeat and each request run this, so a page load after a Save sees the new values. The * admin sessions that the new values end are removed at once, with their streams, so changing a * value back before the next heartbeat never revives them. */ refreshSavedAuth(): void; /** The admin password crosses the network in clear text when a login from anywhere runs over plain HTTP. */ warnOnPlainHttpLogin(): void; /** Called at shutdown, to keep the last `lastSeenAt` values. */ flush(): void; private matchToken; private isLive; /** A guest session answers to the jukebox code, never to the admin access level. */ private levelAdmitsLastRequest; private askOffEpoch; private liveJukeboxCode; private statusOf; /** The key is compared by its digest in constant time. */ private matchLiveJukeboxCode; private liveGuest; private isDeviceBanned; private newBan; private guestSessions; private countGuests; /** * Revocation and expiry both sign out every guest and close their streams. The host keeps its admin * session, so only its guest page streams close, with the same reason. */ private endJukebox; private closeHostGuestPageStreams; /** * A host action names itself to every guest of the live code, an idle one the sweep has not reached * included, since its code stops working too. A guest whose code is no longer live ended by the code's expiry. */ private endReasonOf; /** Only a guest whose code is still live can have ended by its own idle expiry. */ private expiryReasonOf; private onLiveCode; /** A guest ban lasts while the jukebox stays open, so it ends when the jukebox closes or expires. */ private dropGuestBans; /** Returns true when the credential epoch changed, which ends every admin session minted under the old one. */ private applySavedHash; /** Returns true when the ask turned on, which ends every session minted while it was off. */ private applySavedAsk; /** Returns true when the level narrowed, which ends each admin session whose last request it no longer admits. */ private applySavedAdminAccess; /** * The ban refuses each new request from the key, but a stream opened earlier from it would keep * pushing jukebox state, so it closes. A stream matches by the address it opened from, since its * session may have moved since. The sessions stay, so lifting the ban lets them back in. Until then * the ban shuts a guest out as a removal does, so its page shows the same reason. */ private closeStreamsOn; /** * An admin session's pages, its guest page included, read a missing reason as the admin session ending, * and a guest cookie this browser replaced has no page left to tell, so these streams close with no reason. */ private removeSession; /** Batches the writes a request can repeat without limit. */ private markDirty; /** * Mode `none` keeps no sessions in memory, so the file keeps its admin sessions, network bans and * env hash for a later start with a login. A file with no jukebox state is left unwritten. An * unreadable code record counts as jukebox state, so the rewrite clears it. */ private dropStoredJukebox; private persist; private writeStore; } export {}; //# sourceMappingURL=auth-service.d.ts.map