mirror of
https://github.com/RaunoT/plex-rewind.git
synced 2026-11-30 04:12:01 +01:00
fix(security): harden privacy, offline fallback, image proxy and API routes (#577)
This commit is contained in:
1 parent
d46d8e5bb6
commit
ca31a65203
38 files changed
+1285
-160
No files matched your search
@@ -36,7 +36,7 @@ Run `pnpm lint:all` and `pnpm test` before every PR. CI also runs `pnpm build`.
|
||||
|
||||
## Architecture
|
||||
|
||||
- `src/app`: routes (`(home)`, `dashboard`, `rewind`, `activity`, `history`, `settings`, `api`, and `~offline` for the PWA). Components and server actions sit next to their route in `_components` and `_actions`; shared ones are in `src/components` and `src/hooks`.
|
||||
- `src/app`: routes (`(home)`, `dashboard`, `rewind`, `activity`, `history`, `settings`, `api`). Components and server actions sit next to their route in `_components` and `_actions`; shared ones are in `src/components` and `src/hooks`.
|
||||
- `src/proxy.ts`: the Next 16 proxy (formerly middleware), wrapped in next-auth's `withAuth`. It sets the Content Security Policy with a script nonce (`src/utils/csp.ts`) and redirects to the setup pages while required settings (`REQUIRED_SETTINGS` in `src/utils/helpers.ts`) are missing.
|
||||
- Settings live in `config/settings.json`, read and written by `src/utils/getSettings.ts`. The file is created from `DEFAULT_SETTINGS` in `src/utils/constants.ts` and merged with it when read. Types are in `src/types/settings.d.ts`. `config/` also holds the saved play history, the source snapshot, uploaded Rewind music and the music previews found for Rewind. In Docker it is a volume at `/app/config`.
|
||||
- Statistics source: `settings.connection.statisticsSource` is `tautulli` or `tracearr`. Both implement the `StatsSource` interface in `src/types/statsSource.d.ts`: Tautulli in `tautulliSource.ts` (HTTP client `fetchTautulli.ts`), Tracearr in `tracearrSource.ts` (HTTP client `fetchTracearr.ts`), which maps Tracearr data onto the shared types in `statsSource.d.ts` (`ItemRow`, `Library`, `Activity` and the rest, which keep Tautulli's field names). Types for one source's own API stay in `src/types/tautulli.d.ts` and `src/types/tracearr.d.ts`. `getStatsSource()` in `src/utils/statsSource.ts` picks one; the data utils and pages call it instead of branching on the source. A new statistic goes into the interface and both implementations. The media server is `settings.connection.mediaServerType` (`plex` or `jellyfin`); Tautulli only tracks Plex, and Tracearr's is the type of the server picked in the connection settings. Plex IDs are numbers in the shared types and Jellyfin IDs are hex strings, so compare IDs as strings.
|
||||
@@ -44,7 +44,7 @@ Run `pnpm lint:all` and `pnpm test` before every PR. CI also runs `pnpm build`.
|
||||
- Other data utils: `getDashboard.ts`, `getRewind.ts`, `getHistory.ts`, `getUsersTop.ts`, `fetchSeerr.ts`, `fetchTmdb.ts`.
|
||||
- Rewind music: a story plays the first of its sources that loads (`useStoryMusic.ts`), ending with the admin's own track. A show plays the library's theme song (`plexAudio.ts`), then Plex's own by TVDB ID; a movie the library's; a song its file from Plex. What those can't play falls back to a 30-second preview from Deezer or iTunes: `musicPreview.ts` finds a movie's or show's soundtrack by its TMDB ID, or a song by its artist and title (`musicPreviewSources.ts`, matched in `musicPreviewMatch.ts`), saves which track it is to `config/music-previews.json` and streams it through `/api/rewind/preview`.
|
||||
- Translations: `messages/*.json` (`en-GB`, `en-US`, `et`, `fr`, `de`, `it`, `es`), loaded by `src/i18n/request.ts`. The locale list is `LOCALES` in `src/utils/constants.ts`. `en-GB` is the reference and `en-US` only changes the spelling. `messages/messages.test.ts` checks that every locale has the same keys and placeholders, and `react/jsx-no-literals` flags hardcoded strings in JSX, so use next-intl.
|
||||
- PWA: the service worker source is `src/lib/sw.ts`; `public/manifest.json` is the web manifest. `next.config.ts` uses `output: 'standalone'`, which the `Dockerfile` relies on.
|
||||
- PWA: the service worker source is `src/lib/sw.ts`, with a static offline fallback in `public/offline.html`; `public/manifest.json` is the web manifest. `next.config.ts` uses `output: 'standalone'`, which the `Dockerfile` relies on.
|
||||
- `docker-compose.yml` is for local development: it builds the image, maps `3000:8383` and reads `.env.local`.
|
||||
|
||||
## Code style
|
||||
|
||||
@@ -157,10 +157,6 @@
|
||||
"Sidebar": {
|
||||
"label": "Hauptnavigation"
|
||||
},
|
||||
"Offline": {
|
||||
"title": "Du bist offline",
|
||||
"retry": "Erneut versuchen"
|
||||
},
|
||||
"Settings": {
|
||||
"title": "Einstellungen",
|
||||
"getStarted": "Lass uns loslegen!",
|
||||
|
||||
@@ -157,10 +157,6 @@
|
||||
"Sidebar": {
|
||||
"label": "Main navigation"
|
||||
},
|
||||
"Offline": {
|
||||
"title": "You are offline",
|
||||
"retry": "Try again"
|
||||
},
|
||||
"Settings": {
|
||||
"title": "Settings",
|
||||
"getStarted": "Let's get started",
|
||||
|
||||
@@ -157,10 +157,6 @@
|
||||
"Sidebar": {
|
||||
"label": "Main navigation"
|
||||
},
|
||||
"Offline": {
|
||||
"title": "You are offline",
|
||||
"retry": "Try again"
|
||||
},
|
||||
"Settings": {
|
||||
"title": "Settings",
|
||||
"getStarted": "Let's get started",
|
||||
|
||||
@@ -157,10 +157,6 @@
|
||||
"Sidebar": {
|
||||
"label": "Navegación principal"
|
||||
},
|
||||
"Offline": {
|
||||
"title": "Estás sin conexión",
|
||||
"retry": "Intentar de nuevo"
|
||||
},
|
||||
"Settings": {
|
||||
"title": "Ajustes",
|
||||
"getStarted": "Empecemos",
|
||||
|
||||
@@ -157,10 +157,6 @@
|
||||
"Sidebar": {
|
||||
"label": "Põhinavigatsioon"
|
||||
},
|
||||
"Offline": {
|
||||
"title": "Ühendus puudub",
|
||||
"retry": "Proovi uuesti"
|
||||
},
|
||||
"Settings": {
|
||||
"title": "Seaded",
|
||||
"getStarted": "Teeme algust!",
|
||||
|
||||
@@ -157,10 +157,6 @@
|
||||
"Sidebar": {
|
||||
"label": "Navigation principale"
|
||||
},
|
||||
"Offline": {
|
||||
"title": "Vous êtes hors ligne",
|
||||
"retry": "Réessayer"
|
||||
},
|
||||
"Settings": {
|
||||
"title": "Paramètres",
|
||||
"getStarted": "Commençons",
|
||||
|
||||
@@ -157,10 +157,6 @@
|
||||
"Sidebar": {
|
||||
"label": "Navigazione principale"
|
||||
},
|
||||
"Offline": {
|
||||
"title": "Sei offline",
|
||||
"retry": "Riprova"
|
||||
},
|
||||
"Settings": {
|
||||
"title": "Impostazioni",
|
||||
"getStarted": "Cominciamo",
|
||||
|
||||
+14
-6
@@ -19,10 +19,12 @@ const nextConfig: NextConfig = {
|
||||
{
|
||||
protocol: 'https',
|
||||
hostname: 'plex.tv',
|
||||
pathname: '/users/**',
|
||||
},
|
||||
{
|
||||
protocol: 'https',
|
||||
hostname: 'image.tmdb.org',
|
||||
pathname: '/t/p/**',
|
||||
},
|
||||
],
|
||||
},
|
||||
@@ -31,12 +33,8 @@ const nextConfig: NextConfig = {
|
||||
{
|
||||
source: '/(.*)',
|
||||
headers: [
|
||||
// includeSubDomains/preload would commit every self-hosted domain's
|
||||
// subdomains to HTTPS, which isn't this app's call to make.
|
||||
{
|
||||
key: 'Strict-Transport-Security',
|
||||
value: 'max-age=63072000',
|
||||
},
|
||||
// HSTS is left to the TLS-terminating reverse proxy so plain-HTTP
|
||||
// self-hosted installs are not locked into HTTPS across ports.
|
||||
// Pages get a stricter policy with a script nonce from the proxy.
|
||||
{
|
||||
key: 'Content-Security-Policy',
|
||||
@@ -70,6 +68,16 @@ const nextConfig: NextConfig = {
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
source: '/offline.html',
|
||||
headers: [
|
||||
{
|
||||
key: 'Content-Security-Policy',
|
||||
value:
|
||||
"default-src 'none'; style-src 'unsafe-inline'; script-src 'self'; base-uri 'self'; form-action 'self'; frame-ancestors 'self'",
|
||||
},
|
||||
],
|
||||
},
|
||||
]
|
||||
},
|
||||
}
|
||||
|
||||
@@ -0,0 +1,178 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||
<meta name="theme-color" content="#000000" />
|
||||
<title>You are offline | Rewindarr</title>
|
||||
<style>
|
||||
:root {
|
||||
color-scheme: dark;
|
||||
}
|
||||
|
||||
* {
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
html,
|
||||
body {
|
||||
margin: 0;
|
||||
min-height: 100%;
|
||||
background-color: #000;
|
||||
color: #fff;
|
||||
font-family:
|
||||
ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
|
||||
'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
|
||||
}
|
||||
|
||||
main {
|
||||
display: flex;
|
||||
min-height: 100dvh;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
padding: 1rem;
|
||||
}
|
||||
|
||||
.card {
|
||||
position: relative;
|
||||
display: flex;
|
||||
width: 100%;
|
||||
max-width: 24rem;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
border-radius: 1.5rem;
|
||||
padding: 1.25rem;
|
||||
text-align: center;
|
||||
background-color: rgb(255 255 255 / 3%);
|
||||
background-image: linear-gradient(
|
||||
to bottom,
|
||||
rgb(255 255 255 / 4%),
|
||||
transparent 40%
|
||||
);
|
||||
box-shadow:
|
||||
inset 0 1px 0 0 rgb(255 255 255 / 10%),
|
||||
0 24px 48px -24px rgb(0 0 0 / 70%);
|
||||
backdrop-filter: blur(40px) saturate(150%);
|
||||
}
|
||||
|
||||
.card::before {
|
||||
content: '';
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
border-radius: inherit;
|
||||
padding: 1px;
|
||||
pointer-events: none;
|
||||
background: linear-gradient(
|
||||
150deg,
|
||||
rgb(255 255 255 / 28%),
|
||||
rgb(255 255 255 / 6%) 30%,
|
||||
rgb(255 255 255 / 3%) 70%,
|
||||
rgb(255 255 255 / 12%)
|
||||
);
|
||||
mask:
|
||||
linear-gradient(#000 0 0) content-box exclude,
|
||||
linear-gradient(#000 0 0);
|
||||
}
|
||||
|
||||
.badge {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
width: 3rem;
|
||||
height: 3rem;
|
||||
margin-bottom: 1rem;
|
||||
border-radius: 9999px;
|
||||
background-color: rgb(255 255 255 / 5%);
|
||||
color: #d4d4d4;
|
||||
box-shadow: inset 0 0 0 1px rgb(255 255 255 / 10%);
|
||||
}
|
||||
|
||||
.badge svg {
|
||||
width: 1.5rem;
|
||||
height: 1.5rem;
|
||||
}
|
||||
|
||||
h1 {
|
||||
margin: 0;
|
||||
font-size: 1.5rem;
|
||||
line-height: 2rem;
|
||||
font-weight: 600;
|
||||
letter-spacing: -0.025em;
|
||||
}
|
||||
|
||||
.actions {
|
||||
display: flex;
|
||||
width: 100%;
|
||||
flex-direction: column;
|
||||
margin-top: 2rem;
|
||||
}
|
||||
|
||||
.button,
|
||||
.button:visited {
|
||||
display: flex;
|
||||
width: 100%;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
border-radius: 9999px;
|
||||
background-color: #fff;
|
||||
padding: 0.625rem 1.5rem;
|
||||
font-weight: 600;
|
||||
color: #000;
|
||||
text-decoration: none;
|
||||
transition:
|
||||
background-color 200ms,
|
||||
transform 200ms;
|
||||
}
|
||||
|
||||
.button:hover {
|
||||
background-color: #e5e5e5;
|
||||
}
|
||||
|
||||
.button:active {
|
||||
transform: scale(0.98);
|
||||
}
|
||||
|
||||
.button:focus-visible {
|
||||
outline: 2px solid #e5e5e5;
|
||||
outline-offset: 2px;
|
||||
}
|
||||
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.button {
|
||||
transition: none;
|
||||
}
|
||||
|
||||
.button:active {
|
||||
transform: none;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
<script src="/offline.js" defer></script>
|
||||
</head>
|
||||
<body>
|
||||
<main>
|
||||
<div class="card">
|
||||
<div class="badge" aria-hidden="true">
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
fill="none"
|
||||
viewBox="0 0 24 24"
|
||||
stroke-width="1.5"
|
||||
stroke="currentColor"
|
||||
>
|
||||
<path
|
||||
stroke-linecap="round"
|
||||
stroke-linejoin="round"
|
||||
d="m3 3 8.735 8.735m0 0a.374.374 0 1 1 .53.53m-.53-.53.53.53m0 0L21 21M14.652 9.348a3.75 3.75 0 0 1 0 5.304m2.121-7.425a6.75 6.75 0 0 1 0 9.546m2.121-11.667c3.808 3.807 3.808 9.98 0 13.788m-9.546-4.242a3.733 3.733 0 0 1-1.06-2.122m-1.061 4.243a6.75 6.75 0 0 1-1.625-6.929m-.496 9.05c-3.068-3.067-3.664-7.67-1.79-11.334M12 12h.008v.008H12V12Z"
|
||||
/>
|
||||
</svg>
|
||||
</div>
|
||||
<h1 id="offline-title">You are offline</h1>
|
||||
<div class="actions">
|
||||
<a id="offline-retry" href="" class="button">Try again</a>
|
||||
</div>
|
||||
</div>
|
||||
</main>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,60 @@
|
||||
;(() => {
|
||||
const MESSAGES = {
|
||||
en: { title: 'You are offline', retry: 'Try again' },
|
||||
de: { title: 'Du bist offline', retry: 'Erneut versuchen' },
|
||||
es: { title: 'Estás sin conexión', retry: 'Intentar de nuevo' },
|
||||
et: { title: 'Ühendus puudub', retry: 'Proovi uuesti' },
|
||||
fr: { title: 'Vous êtes hors ligne', retry: 'Réessayer' },
|
||||
it: { title: 'Sei offline', retry: 'Riprova' },
|
||||
}
|
||||
|
||||
function getCookieLocale() {
|
||||
for (const part of document.cookie.split('; ')) {
|
||||
const separator = part.indexOf('=')
|
||||
|
||||
if (separator > 0 && part.slice(0, separator) === 'locale') {
|
||||
try {
|
||||
return decodeURIComponent(part.slice(separator + 1))
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return null
|
||||
}
|
||||
|
||||
function findMatch(tags) {
|
||||
for (const tag of tags) {
|
||||
if (!tag) continue
|
||||
|
||||
const language = tag.toLowerCase().split('-')[0]
|
||||
|
||||
if (Object.hasOwn(MESSAGES, language)) {
|
||||
return { lang: tag, messages: MESSAGES[language] }
|
||||
}
|
||||
}
|
||||
|
||||
return null
|
||||
}
|
||||
|
||||
const cookieLocale = getCookieLocale()
|
||||
const browserLanguages = navigator.languages?.length
|
||||
? [...navigator.languages]
|
||||
: navigator.language
|
||||
? [navigator.language]
|
||||
: []
|
||||
const match = findMatch([cookieLocale, ...browserLanguages])
|
||||
|
||||
if (!match) return
|
||||
|
||||
const title = document.getElementById('offline-title')
|
||||
const retry = document.getElementById('offline-retry')
|
||||
|
||||
document.documentElement.lang = match.lang
|
||||
document.title = `${match.messages.title} | Rewindarr`
|
||||
|
||||
if (title) title.textContent = match.messages.title
|
||||
|
||||
if (retry) retry.textContent = match.messages.retry
|
||||
})()
|
||||
+30
-7
@@ -1,14 +1,37 @@
|
||||
// @ts-check
|
||||
import { serwist } from '@serwist/next/config'
|
||||
|
||||
const revision = crypto.randomUUID()
|
||||
|
||||
export default serwist({
|
||||
const config = await serwist({
|
||||
swSrc: 'src/lib/sw.ts',
|
||||
swDest: 'public/sw.js',
|
||||
// Only what the offline page needs: its stylesheet and the app icons.
|
||||
// Everything else is cached as it's used.
|
||||
globPatterns: ['.next/static/**/*.css', 'public/{manifest.json,icon-*.png}'],
|
||||
// Only the static offline fallback and its assets; hashed build chunks are
|
||||
// cached as they are used.
|
||||
globPatterns: ['public/{manifest.json,offline.html,offline.js,icon-*.png}'],
|
||||
precachePrerendered: false,
|
||||
additionalPrecacheEntries: [{ url: '/~offline', revision }],
|
||||
})
|
||||
// @serwist/next turns `public/offline.html` into `/public/offline`; restore its
|
||||
// real URL while keeping the content hash revision it computed.
|
||||
const serwistConfig = {
|
||||
...config,
|
||||
manifestTransforms: [
|
||||
...(config.manifestTransforms ?? []),
|
||||
/** @param {import('serwist').PrecacheEntry[]} manifest */
|
||||
(manifest) => {
|
||||
const mapped = manifest.map((entry) =>
|
||||
entry.url === '/public/offline'
|
||||
? { ...entry, url: '/offline.html' }
|
||||
: entry,
|
||||
)
|
||||
|
||||
if (!mapped.some((entry) => entry.url === '/offline.html')) {
|
||||
throw new Error(
|
||||
'Expected /offline.html in Serwist precache manifest after URL transform',
|
||||
)
|
||||
}
|
||||
|
||||
return { manifest: mapped, warnings: [] }
|
||||
},
|
||||
],
|
||||
}
|
||||
|
||||
export default serwistConfig
|
||||
@@ -109,9 +109,7 @@ export default function AppProvider({
|
||||
// container and keep sticky things inside from sticking.
|
||||
'group/main flex h-full min-h-dvh flex-col items-center overflow-x-clip p-4 pt-(--page-top)',
|
||||
{
|
||||
'justify-center':
|
||||
(pathname === '/' && !isBrowsing) ||
|
||||
pathname === '/~offline',
|
||||
'justify-center': pathname === '/' && !isBrowsing,
|
||||
'lg:pl-68': hasSidebar,
|
||||
},
|
||||
)}
|
||||
|
||||
@@ -51,7 +51,7 @@ export default async function HistoryTile({
|
||||
name: isAnonymous
|
||||
? t('History.anonymous')
|
||||
: play.userName || t('History.unknownUser'),
|
||||
avatar: play.avatar,
|
||||
avatar: isAnonymous ? '' : play.avatar,
|
||||
isAnonymous,
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,253 @@
|
||||
import { Settings } from '@/types/settings'
|
||||
import { DEFAULT_SETTINGS } from '@/utils/constants'
|
||||
import fs from 'fs'
|
||||
import { cloneDeep } from 'lodash'
|
||||
import os from 'os'
|
||||
import path from 'path'
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
|
||||
const canManageSettingsMock = vi.fn<() => Promise<boolean>>()
|
||||
const canPlayRewindMock = vi.fn<() => Promise<boolean>>()
|
||||
const getSettingsMock = vi.fn<() => Settings>()
|
||||
const writeSettingsMock = vi.fn<(settings: Settings) => void>()
|
||||
|
||||
vi.mock('@/lib/access', () => ({
|
||||
canManageSettings: canManageSettingsMock,
|
||||
canPlayRewind: canPlayRewindMock,
|
||||
}))
|
||||
vi.mock('@/utils/getSettings', () => ({
|
||||
default: getSettingsMock,
|
||||
writeSettings: writeSettingsMock,
|
||||
}))
|
||||
vi.mock('next/cache', () => ({ revalidatePath: vi.fn() }))
|
||||
|
||||
let directory: string
|
||||
let musicPath: string
|
||||
let route: typeof import('./route')
|
||||
|
||||
function settingsWithMusic(): Settings {
|
||||
const settings = cloneDeep(DEFAULT_SETTINGS)
|
||||
|
||||
settings.rewind.music = {
|
||||
name: 'theme.mp3',
|
||||
type: 'audio/mpeg',
|
||||
size: 5,
|
||||
updatedAt: 1000,
|
||||
}
|
||||
|
||||
return settings
|
||||
}
|
||||
|
||||
beforeEach(async () => {
|
||||
vi.resetModules()
|
||||
directory = fs.mkdtempSync(path.join(os.tmpdir(), 'rewindarr-music-'))
|
||||
fs.mkdirSync(path.join(directory, 'config'))
|
||||
musicPath = path.join(directory, 'config/rewind-music')
|
||||
|
||||
const cwd = vi.spyOn(process, 'cwd').mockReturnValue(directory)
|
||||
|
||||
try {
|
||||
route = await import('./route')
|
||||
} finally {
|
||||
cwd.mockRestore()
|
||||
}
|
||||
|
||||
vi.spyOn(console, 'error').mockImplementation(() => {})
|
||||
canManageSettingsMock.mockResolvedValue(true)
|
||||
canPlayRewindMock.mockResolvedValue(true)
|
||||
getSettingsMock.mockReturnValue(cloneDeep(DEFAULT_SETTINGS))
|
||||
writeSettingsMock.mockReset()
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks()
|
||||
fs.rmSync(directory, { recursive: true, force: true })
|
||||
})
|
||||
|
||||
describe('/api/rewind/music', () => {
|
||||
describe('GET', () => {
|
||||
it('serves full and ranged audio responses', async () => {
|
||||
fs.writeFileSync(musicPath, '0123456789')
|
||||
getSettingsMock.mockReturnValue(settingsWithMusic())
|
||||
|
||||
const full = await route.GET(
|
||||
new Request('http://localhost/api/rewind/music'),
|
||||
)
|
||||
|
||||
expect(full.status).toBe(200)
|
||||
expect(full.headers.get('Content-Length')).toBe('10')
|
||||
expect(await full.text()).toBe('0123456789')
|
||||
|
||||
const partial = await route.GET(
|
||||
new Request('http://localhost/api/rewind/music', {
|
||||
headers: { Range: 'bytes=2-5' },
|
||||
}),
|
||||
)
|
||||
|
||||
expect(partial.status).toBe(206)
|
||||
expect(partial.headers.get('Content-Range')).toBe('bytes 2-5/10')
|
||||
expect(await partial.text()).toBe('2345')
|
||||
})
|
||||
|
||||
it('returns 416 for unsatisfiable ranges and Content-Disposition on download', async () => {
|
||||
fs.writeFileSync(musicPath, '01234')
|
||||
getSettingsMock.mockReturnValue(settingsWithMusic())
|
||||
|
||||
const badRange = await route.GET(
|
||||
new Request('http://localhost/api/rewind/music?download', {
|
||||
headers: { Range: 'bytes=99-' },
|
||||
}),
|
||||
)
|
||||
|
||||
expect(badRange.status).toBe(416)
|
||||
expect(badRange.headers.get('Content-Range')).toBe('bytes */5')
|
||||
expect(badRange.headers.get('Content-Disposition')).toContain(
|
||||
'filename="theme.mp3"',
|
||||
)
|
||||
})
|
||||
|
||||
it('returns 404 when empty or unauthorized', async () => {
|
||||
fs.writeFileSync(musicPath, '')
|
||||
getSettingsMock.mockReturnValue(settingsWithMusic())
|
||||
|
||||
expect(
|
||||
(await route.GET(new Request('http://localhost/api/rewind/music')))
|
||||
.status,
|
||||
).toBe(404)
|
||||
|
||||
fs.writeFileSync(musicPath, '01234')
|
||||
canPlayRewindMock.mockResolvedValue(false)
|
||||
canManageSettingsMock.mockResolvedValue(false)
|
||||
|
||||
expect(
|
||||
(
|
||||
await route.GET(
|
||||
new Request('http://localhost/api/rewind/music?download'),
|
||||
)
|
||||
).status,
|
||||
).toBe(404)
|
||||
})
|
||||
})
|
||||
|
||||
describe('PUT', () => {
|
||||
it('rejects unauthorized requests', async () => {
|
||||
canManageSettingsMock.mockResolvedValue(false)
|
||||
|
||||
const res = await route.PUT(
|
||||
new Request('http://localhost/api/rewind/music', { method: 'PUT' }),
|
||||
)
|
||||
|
||||
expect(res.status).toBe(403)
|
||||
})
|
||||
|
||||
it('returns 400 on malformed x-file-name encoding', async () => {
|
||||
const res = await route.PUT(
|
||||
new Request('http://localhost/api/rewind/music', {
|
||||
method: 'PUT',
|
||||
headers: { 'x-file-name': '%E0%A4%A' },
|
||||
body: 'audio',
|
||||
}),
|
||||
)
|
||||
|
||||
expect(res.status).toBe(400)
|
||||
})
|
||||
|
||||
it('rejects unsupported file types with 415', async () => {
|
||||
const res = await route.PUT(
|
||||
new Request('http://localhost/api/rewind/music', {
|
||||
method: 'PUT',
|
||||
headers: { 'x-file-name': 'evil.html', 'content-length': '5' },
|
||||
body: '<svg/>',
|
||||
}),
|
||||
)
|
||||
|
||||
expect(res.status).toBe(415)
|
||||
})
|
||||
|
||||
it('rejects 0-byte uploads and oversized Content-Length', async () => {
|
||||
const zeroLength = await route.PUT(
|
||||
new Request('http://localhost/api/rewind/music', {
|
||||
method: 'PUT',
|
||||
headers: { 'x-file-name': 'song.mp3', 'content-length': '0' },
|
||||
body: new Uint8Array(0),
|
||||
}),
|
||||
)
|
||||
|
||||
expect(zeroLength.status).toBe(400)
|
||||
await expect(zeroLength.json()).resolves.toEqual({ error: 'empty' })
|
||||
|
||||
const emptyStream = new ReadableStream<Uint8Array>({
|
||||
start(controller) {
|
||||
controller.close()
|
||||
},
|
||||
})
|
||||
const emptyChunked = await route.PUT(
|
||||
new Request('http://localhost/api/rewind/music', {
|
||||
method: 'PUT',
|
||||
headers: { 'x-file-name': 'song.mp3' },
|
||||
body: emptyStream,
|
||||
// @ts-expect-error - required by undici for ReadableStream request bodies
|
||||
duplex: 'half',
|
||||
}),
|
||||
)
|
||||
|
||||
expect(emptyChunked.status).toBe(400)
|
||||
await expect(emptyChunked.json()).resolves.toEqual({ error: 'empty' })
|
||||
|
||||
const oversized = await route.PUT(
|
||||
new Request('http://localhost/api/rewind/music', {
|
||||
method: 'PUT',
|
||||
headers: {
|
||||
'x-file-name': 'song.mp3',
|
||||
'content-length': String(100 * 1024 * 1024),
|
||||
},
|
||||
body: 'x',
|
||||
}),
|
||||
)
|
||||
|
||||
expect(oversized.status).toBe(413)
|
||||
})
|
||||
|
||||
it('accepts chunked uploads without a Content-Length header', async () => {
|
||||
const stream = new ReadableStream<Uint8Array>({
|
||||
start(controller) {
|
||||
controller.enqueue(new TextEncoder().encode('mp3-data'))
|
||||
controller.close()
|
||||
},
|
||||
})
|
||||
const res = await route.PUT(
|
||||
new Request('http://localhost/api/rewind/music', {
|
||||
method: 'PUT',
|
||||
headers: { 'x-file-name': encodeURIComponent('my song.mp3') },
|
||||
body: stream,
|
||||
// @ts-expect-error - required by undici for ReadableStream request bodies
|
||||
duplex: 'half',
|
||||
}),
|
||||
)
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
await expect(res.json()).resolves.toMatchObject({
|
||||
music: { name: 'my song.mp3', type: 'audio/mpeg', size: 8 },
|
||||
})
|
||||
expect(fs.readFileSync(musicPath, 'utf-8')).toBe('mp3-data')
|
||||
expect(writeSettingsMock).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
})
|
||||
|
||||
describe('DELETE', () => {
|
||||
it('enforces settings access and removes the saved music file', async () => {
|
||||
fs.writeFileSync(musicPath, 'mp3-data')
|
||||
getSettingsMock.mockReturnValue(settingsWithMusic())
|
||||
|
||||
canManageSettingsMock.mockResolvedValueOnce(false)
|
||||
expect((await route.DELETE()).status).toBe(403)
|
||||
expect(fs.existsSync(musicPath)).toBe(true)
|
||||
|
||||
const res = await route.DELETE()
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
expect(fs.existsSync(musicPath)).toBe(false)
|
||||
expect(writeSettingsMock).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -40,7 +40,18 @@ export async function GET(request: Request) {
|
||||
return new Response(null, { status: 404 })
|
||||
}
|
||||
|
||||
const { size } = fs.statSync(REWIND_MUSIC_PATH)
|
||||
let size: number
|
||||
|
||||
try {
|
||||
size = fs.statSync(REWIND_MUSIC_PATH).size
|
||||
} catch {
|
||||
return new Response(null, { status: 404 })
|
||||
}
|
||||
|
||||
if (size === 0) {
|
||||
return new Response(null, { status: 404 })
|
||||
}
|
||||
|
||||
const range = parseRange(request.headers.get('range'), size)
|
||||
const headers = new Headers({
|
||||
'Content-Type': music.type,
|
||||
@@ -83,25 +94,50 @@ export async function PUT(request: Request) {
|
||||
return Response.json({ error: 'forbidden' }, { status: 403 })
|
||||
}
|
||||
|
||||
const name = decodeURIComponent(request.headers.get('x-file-name') ?? '')
|
||||
const type = getMusicType(name)
|
||||
const length = Number(request.headers.get('content-length'))
|
||||
let name: string
|
||||
|
||||
if (!type || !request.body || !length) {
|
||||
try {
|
||||
name = decodeURIComponent(request.headers.get('x-file-name') ?? '')
|
||||
} catch {
|
||||
return Response.json({ error: 'type' }, { status: 400 })
|
||||
}
|
||||
|
||||
const type = getMusicType(name)
|
||||
|
||||
if (!type || !request.body) {
|
||||
return Response.json({ error: 'type' }, { status: 415 })
|
||||
}
|
||||
|
||||
if (length > REWIND_MUSIC_MAX_BYTES) {
|
||||
return Response.json({ error: 'size' }, { status: 413 })
|
||||
const lengthHeader = request.headers.get('content-length')
|
||||
|
||||
if (lengthHeader !== null) {
|
||||
const trimmed = lengthHeader.trim()
|
||||
const length = Number(trimmed)
|
||||
|
||||
if (!/^\d+$/.test(trimmed)) {
|
||||
return Response.json({ error: 'type' }, { status: 400 })
|
||||
}
|
||||
|
||||
if (length === 0) {
|
||||
return Response.json({ error: 'empty' }, { status: 400 })
|
||||
}
|
||||
|
||||
if (length > REWIND_MUSIC_MAX_BYTES) {
|
||||
return Response.json({ error: 'size' }, { status: 413 })
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
const music = await saveMusic(request.body, name, type)
|
||||
|
||||
if (!music) {
|
||||
if (music === 'tooLarge') {
|
||||
return Response.json({ error: 'size' }, { status: 413 })
|
||||
}
|
||||
|
||||
if (music === 'empty') {
|
||||
return Response.json({ error: 'empty' }, { status: 400 })
|
||||
}
|
||||
|
||||
const settings = getSettings()
|
||||
|
||||
settings.rewind.music = music
|
||||
|
||||
@@ -0,0 +1,100 @@
|
||||
import { canPlayRewind } from '@/lib/access'
|
||||
import { Settings } from '@/types/settings'
|
||||
import { DEFAULT_SETTINGS } from '@/utils/constants'
|
||||
import getSettings from '@/utils/getSettings'
|
||||
import {
|
||||
getPlexThemeUrl,
|
||||
getPlexTrackUrl,
|
||||
streamPlexAudio,
|
||||
} from '@/utils/plexAudio'
|
||||
import { cloneDeep } from 'lodash'
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { GET } from './route'
|
||||
|
||||
vi.mock('@/lib/access', () => ({ canPlayRewind: vi.fn() }))
|
||||
vi.mock('@/utils/getSettings', () => ({ default: vi.fn() }))
|
||||
vi.mock('@/utils/plexAudio', async (importOriginal) => ({
|
||||
...(await importOriginal<typeof import('@/utils/plexAudio')>()),
|
||||
streamPlexAudio: vi.fn(),
|
||||
}))
|
||||
|
||||
function testSettings(themeActive = true): Settings {
|
||||
const settings = cloneDeep(DEFAULT_SETTINGS)
|
||||
|
||||
settings.connection.plexUrl = 'http://plex:32400'
|
||||
settings.connection.plexToken = 'plex-token'
|
||||
settings.rewind.isThemeMusicActive = themeActive
|
||||
|
||||
return settings
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.stubEnv('NEXTAUTH_SECRET', 'secret')
|
||||
vi.mocked(canPlayRewind).mockResolvedValue(true)
|
||||
vi.mocked(getSettings).mockReturnValue(testSettings())
|
||||
vi.mocked(streamPlexAudio).mockResolvedValue(new Response('audio'))
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks()
|
||||
vi.unstubAllEnvs()
|
||||
})
|
||||
|
||||
describe('GET /api/rewind/theme', () => {
|
||||
it('streams audio when authorized and validly signed', async () => {
|
||||
const signedPath = getPlexThemeUrl(testSettings(), 42)!
|
||||
const req = new Request(`http://localhost${signedPath}`)
|
||||
const res = await GET(req)
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
expect(streamPlexAudio).toHaveBeenCalledWith(
|
||||
expect.anything(),
|
||||
'theme',
|
||||
'42',
|
||||
req,
|
||||
)
|
||||
})
|
||||
|
||||
it('returns 404 when the viewer cannot play Rewind', async () => {
|
||||
vi.mocked(canPlayRewind).mockResolvedValue(false)
|
||||
|
||||
const signedPath = getPlexThemeUrl(testSettings(), 42)!
|
||||
const res = await GET(new Request(`http://localhost${signedPath}`))
|
||||
|
||||
expect(res.status).toBe(404)
|
||||
expect(streamPlexAudio).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('returns 404 when theme music is disabled', async () => {
|
||||
vi.mocked(getSettings).mockReturnValue(testSettings(false))
|
||||
|
||||
const signedPath = getPlexThemeUrl(testSettings(), 42)!
|
||||
const res = await GET(new Request(`http://localhost${signedPath}`))
|
||||
|
||||
expect(res.status).toBe(404)
|
||||
expect(streamPlexAudio).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('returns 404 without a valid key or signature, including track signatures', async () => {
|
||||
const trackSignedPath = new URL(
|
||||
getPlexTrackUrl(testSettings(), '42')!,
|
||||
'http://localhost',
|
||||
)
|
||||
|
||||
for (const query of [
|
||||
'',
|
||||
'?key=42',
|
||||
'?key=42&sig=bad',
|
||||
'?key=abc&sig=bad',
|
||||
trackSignedPath.search,
|
||||
]) {
|
||||
const res = await GET(
|
||||
new Request(`http://localhost/api/rewind/theme${query}`),
|
||||
)
|
||||
|
||||
expect(res.status).toBe(404)
|
||||
}
|
||||
|
||||
expect(streamPlexAudio).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
@@ -1,18 +1,20 @@
|
||||
import { canPlayRewind } from '@/lib/access'
|
||||
import getSettings from '@/utils/getSettings'
|
||||
import { streamPlexAudio } from '@/utils/plexAudio'
|
||||
import { isSignedTheme, streamPlexAudio } from '@/utils/plexAudio'
|
||||
|
||||
export const dynamic = 'force-dynamic'
|
||||
|
||||
// Streams a theme song from Plex, which needs the token the browser can't have
|
||||
export async function GET(request: Request) {
|
||||
const settings = getSettings()
|
||||
const ratingKey = new URL(request.url).searchParams.get('key') ?? ''
|
||||
const { searchParams } = new URL(request.url)
|
||||
const ratingKey = searchParams.get('key') ?? ''
|
||||
|
||||
if (
|
||||
!(await canPlayRewind(settings)) ||
|
||||
!settings.rewind.isThemeMusicActive ||
|
||||
!/^\d+$/.test(ratingKey)
|
||||
!/^\d+$/.test(ratingKey) ||
|
||||
!isSignedTheme(ratingKey, searchParams.get('sig') ?? '')
|
||||
) {
|
||||
return new Response(null, { status: 404 })
|
||||
}
|
||||
|
||||
@@ -0,0 +1,80 @@
|
||||
import { canPlayRewind } from '@/lib/access'
|
||||
import { Settings } from '@/types/settings'
|
||||
import { DEFAULT_SETTINGS } from '@/utils/constants'
|
||||
import getSettings from '@/utils/getSettings'
|
||||
import { getPlexTrackUrl, streamPlexAudio } from '@/utils/plexAudio'
|
||||
import { cloneDeep } from 'lodash'
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { GET } from './route'
|
||||
|
||||
vi.mock('@/lib/access', () => ({ canPlayRewind: vi.fn() }))
|
||||
vi.mock('@/utils/getSettings', () => ({ default: vi.fn() }))
|
||||
vi.mock('@/utils/plexAudio', async (importOriginal) => ({
|
||||
...(await importOriginal<typeof import('@/utils/plexAudio')>()),
|
||||
streamPlexAudio: vi.fn(),
|
||||
}))
|
||||
|
||||
function testSettings(themeActive = true): Settings {
|
||||
const settings = cloneDeep(DEFAULT_SETTINGS)
|
||||
|
||||
settings.connection.plexUrl = 'http://plex:32400'
|
||||
settings.connection.plexToken = 'plex-token'
|
||||
settings.rewind.isThemeMusicActive = themeActive
|
||||
|
||||
return settings
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.stubEnv('NEXTAUTH_SECRET', 'secret')
|
||||
vi.mocked(canPlayRewind).mockResolvedValue(true)
|
||||
vi.mocked(getSettings).mockReturnValue(testSettings())
|
||||
vi.mocked(streamPlexAudio).mockResolvedValue(new Response('audio'))
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks()
|
||||
vi.unstubAllEnvs()
|
||||
})
|
||||
|
||||
describe('GET /api/rewind/track', () => {
|
||||
it('streams audio when authorized and validly signed', async () => {
|
||||
const signedPath = getPlexTrackUrl(testSettings(), '77')!
|
||||
const req = new Request(`http://localhost${signedPath}`)
|
||||
const res = await GET(req)
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
expect(streamPlexAudio).toHaveBeenCalledWith(
|
||||
expect.anything(),
|
||||
'track',
|
||||
'77',
|
||||
req,
|
||||
)
|
||||
})
|
||||
|
||||
it('returns 404 when unauthorized, disabled, or missing a valid signature', async () => {
|
||||
const signedPath = getPlexTrackUrl(testSettings(), '77')!
|
||||
|
||||
vi.mocked(canPlayRewind).mockResolvedValueOnce(false)
|
||||
expect(
|
||||
(await GET(new Request(`http://localhost${signedPath}`))).status,
|
||||
).toBe(404)
|
||||
|
||||
vi.mocked(getSettings).mockReturnValueOnce(testSettings(false))
|
||||
expect(
|
||||
(await GET(new Request(`http://localhost${signedPath}`))).status,
|
||||
).toBe(404)
|
||||
|
||||
expect(
|
||||
(await GET(new Request('http://localhost/api/rewind/track?key=77')))
|
||||
.status,
|
||||
).toBe(404)
|
||||
expect(
|
||||
(
|
||||
await GET(
|
||||
new Request('http://localhost/api/rewind/track?key=77&sig=invalid'),
|
||||
)
|
||||
).status,
|
||||
).toBe(404)
|
||||
expect(streamPlexAudio).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,100 @@
|
||||
import { canManageSettings } from '@/lib/access'
|
||||
import { testTautulli } from '@/utils/connectionTests'
|
||||
import { DEFAULT_SETTINGS } from '@/utils/constants'
|
||||
import getSettings from '@/utils/getSettings'
|
||||
import { cloneDeep } from 'lodash'
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { POST } from './route'
|
||||
|
||||
vi.mock('@/lib/access', () => ({ canManageSettings: vi.fn() }))
|
||||
vi.mock('@/utils/getSettings', () => ({ default: vi.fn() }))
|
||||
vi.mock('@/utils/connectionTests', () => ({
|
||||
testMediaServerUrl: vi.fn(),
|
||||
testPlexToken: vi.fn(),
|
||||
testSeerr: vi.fn(),
|
||||
testTautulli: vi.fn(),
|
||||
testTracearr: vi.fn(),
|
||||
}))
|
||||
vi.mock('next-intl/server', () => ({
|
||||
getTranslations: vi.fn(async () => (key: string) => key),
|
||||
}))
|
||||
|
||||
beforeEach(() => {
|
||||
vi.mocked(canManageSettings).mockResolvedValue(true)
|
||||
vi.mocked(getSettings).mockReturnValue(cloneDeep(DEFAULT_SETTINGS))
|
||||
vi.mocked(testTautulli).mockResolvedValue(null)
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks()
|
||||
})
|
||||
|
||||
describe('POST /api/settings/connection-test', () => {
|
||||
it('returns 415 for non-JSON requests', async () => {
|
||||
const res = await POST(
|
||||
new Request('http://localhost/api/settings/connection-test', {
|
||||
method: 'POST',
|
||||
headers: { 'content-type': 'text/plain' },
|
||||
body: '{}',
|
||||
}),
|
||||
)
|
||||
|
||||
expect(res.status).toBe(415)
|
||||
expect(canManageSettings).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('returns 403 before parsing the body when unauthorized', async () => {
|
||||
vi.mocked(canManageSettings).mockResolvedValue(false)
|
||||
|
||||
const req = new Request('http://localhost/api/settings/connection-test', {
|
||||
method: 'POST',
|
||||
headers: { 'content-type': 'Application/JSON' },
|
||||
body: '{invalid json',
|
||||
})
|
||||
const jsonSpy = vi.spyOn(req, 'json')
|
||||
const res = await POST(req)
|
||||
|
||||
expect(res.status).toBe(403)
|
||||
expect(jsonSpy).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('returns 400 for malformed payloads when authorized', async () => {
|
||||
const res = await POST(
|
||||
new Request('http://localhost/api/settings/connection-test', {
|
||||
method: 'POST',
|
||||
headers: { 'content-type': 'application/json' },
|
||||
body: JSON.stringify({ service: 'unknown' }),
|
||||
}),
|
||||
)
|
||||
|
||||
expect(res.status).toBe(400)
|
||||
})
|
||||
|
||||
it('runs the requested connection test when authorized and valid', async () => {
|
||||
const res = await POST(
|
||||
new Request('http://localhost/api/settings/connection-test', {
|
||||
method: 'POST',
|
||||
headers: { 'content-type': 'application/json; charset=utf-8' },
|
||||
body: JSON.stringify({
|
||||
service: 'tautulli',
|
||||
mediaServerType: 'plex',
|
||||
fields: [
|
||||
['statisticsSource', 'tautulli'],
|
||||
['tautulliUrl', 'http://tautulli:8181'],
|
||||
['tautulliApiKey', 'secret-key'],
|
||||
],
|
||||
}),
|
||||
}),
|
||||
)
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
await expect(res.json()).resolves.toEqual({
|
||||
status: 'success',
|
||||
message: 'Connection.connected',
|
||||
})
|
||||
expect(testTautulli).toHaveBeenCalledWith(
|
||||
'http://tautulli:8181',
|
||||
'secret-key',
|
||||
)
|
||||
})
|
||||
})
|
||||
@@ -41,10 +41,19 @@ type Body = {
|
||||
export async function POST(request: Request) {
|
||||
// A form on another site can't send JSON without asking first, so it can't
|
||||
// test URLs as a signed-in admin
|
||||
if (!request.headers.get('content-type')?.startsWith('application/json')) {
|
||||
if (
|
||||
!request.headers
|
||||
.get('content-type')
|
||||
?.toLowerCase()
|
||||
.startsWith('application/json')
|
||||
) {
|
||||
return new Response(null, { status: 415 })
|
||||
}
|
||||
|
||||
if (!(await canManageSettings())) {
|
||||
return new Response(null, { status: 403 })
|
||||
}
|
||||
|
||||
const body: Partial<Body> | null = await request.json().catch(() => null)
|
||||
const { service, mediaServerType, fields } = body ?? {}
|
||||
|
||||
@@ -57,10 +66,6 @@ export async function POST(request: Request) {
|
||||
return new Response(null, { status: 400 })
|
||||
}
|
||||
|
||||
if (!(await canManageSettings())) {
|
||||
return new Response(null, { status: 403 })
|
||||
}
|
||||
|
||||
const formData = new FormData()
|
||||
|
||||
for (const field of fields) {
|
||||
|
||||
@@ -202,7 +202,7 @@ export default function HistoryItem({
|
||||
name: isAnonymous
|
||||
? t('History.anonymous')
|
||||
: play.userName || t('History.unknownUser'),
|
||||
avatar: play.avatar,
|
||||
avatar: isAnonymous ? '' : play.avatar,
|
||||
isAnonymous,
|
||||
}
|
||||
: null,
|
||||
|
||||
@@ -80,7 +80,7 @@ export default function HistoryRequestItem({
|
||||
name: isAnonymous
|
||||
? t('History.anonymous')
|
||||
: request.userName || t('History.unknownUser'),
|
||||
avatar: request.avatar,
|
||||
avatar: isAnonymous ? '' : request.avatar,
|
||||
isAnonymous,
|
||||
}
|
||||
: null
|
||||
|
||||
@@ -1,18 +0,0 @@
|
||||
'use client'
|
||||
|
||||
import { useTranslations } from 'next-intl'
|
||||
|
||||
export default function RetryButton() {
|
||||
const t = useTranslations('Offline')
|
||||
|
||||
return (
|
||||
// Reloads the page that failed to load, which the address bar still shows
|
||||
<button
|
||||
type='button'
|
||||
className='button w-full'
|
||||
onClick={() => window.location.reload()}
|
||||
>
|
||||
{t('retry')}
|
||||
</button>
|
||||
)
|
||||
}
|
||||
@@ -1,26 +0,0 @@
|
||||
import StatusMessage from '@/components/StatusMessage'
|
||||
import { SignalSlashIcon } from '@heroicons/react/24/outline'
|
||||
import type { Metadata } from 'next'
|
||||
import { getTranslations } from 'next-intl/server'
|
||||
import RetryButton from './_components/RetryButton'
|
||||
|
||||
export async function generateMetadata(): Promise<Metadata> {
|
||||
const t = await getTranslations('Offline')
|
||||
|
||||
return {
|
||||
title: t('title'),
|
||||
}
|
||||
}
|
||||
|
||||
export default async function Page() {
|
||||
const t = await getTranslations('Offline')
|
||||
|
||||
return (
|
||||
<StatusMessage
|
||||
icon={SignalSlashIcon}
|
||||
title={t('title')}
|
||||
as='h1'
|
||||
action={<RetryButton />}
|
||||
/>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
import { LOCALES } from '@/utils/constants'
|
||||
import fs from 'fs'
|
||||
import path from 'path'
|
||||
import { describe, expect, it } from 'vitest'
|
||||
|
||||
const PUBLIC_DIR = path.join(process.cwd(), 'public')
|
||||
|
||||
describe('static offline fallback', () => {
|
||||
it('renders a standalone reload link without inline scripts', () => {
|
||||
const html = fs.readFileSync(path.join(PUBLIC_DIR, 'offline.html'), 'utf-8')
|
||||
const inlineScripts = [...html.matchAll(/<script\b([^>]*)>/gi)].filter(
|
||||
([, attrs]) => !/\bsrc=/i.test(attrs),
|
||||
)
|
||||
|
||||
expect(inlineScripts).toEqual([])
|
||||
expect(html).toContain('<script src="/offline.js" defer></script>')
|
||||
expect(html).toMatch(/<a\b[^>]*\bhref=""[^>]*>/)
|
||||
})
|
||||
|
||||
it('covers every configured app language in offline.js', () => {
|
||||
const script = fs.readFileSync(path.join(PUBLIC_DIR, 'offline.js'), 'utf-8')
|
||||
const languages = new Set(LOCALES.map((locale) => locale.split('-')[0]))
|
||||
|
||||
for (const language of languages) {
|
||||
expect(script).toMatch(new RegExp(`\\b${language}:\\s*\\{`))
|
||||
}
|
||||
})
|
||||
})
|
||||
+1
-1
@@ -46,7 +46,7 @@ const serwist = new Serwist({
|
||||
fallbacks: {
|
||||
entries: [
|
||||
{
|
||||
url: '/~offline',
|
||||
url: '/offline.html',
|
||||
matcher({ request }) {
|
||||
return request.destination === 'document'
|
||||
},
|
||||
|
||||
@@ -23,12 +23,14 @@ function seerrFetch(
|
||||
override?: (skip: number) => Response | undefined,
|
||||
) {
|
||||
const requests: URL[] = []
|
||||
const stub = vi.fn<Fetch>(async (input) => {
|
||||
const inits: (RequestInit | undefined)[] = []
|
||||
const stub = vi.fn<Fetch>(async (input, init) => {
|
||||
const url = new URL(String(input))
|
||||
const take = Number(url.searchParams.get('take'))
|
||||
const skip = Number(url.searchParams.get('skip'))
|
||||
|
||||
requests.push(url)
|
||||
inits.push(init)
|
||||
|
||||
const overridden = override?.(skip)
|
||||
|
||||
@@ -68,7 +70,7 @@ function seerrFetch(
|
||||
|
||||
vi.stubGlobal('fetch', stub)
|
||||
|
||||
return { requests, stats }
|
||||
return { requests, inits, stats }
|
||||
}
|
||||
|
||||
// One request per hour, newest first, like Seerr returns them.
|
||||
@@ -96,7 +98,7 @@ afterEach(() => {
|
||||
|
||||
describe('fetchSeerrStats', () => {
|
||||
it('reads large pages, newest first', async () => {
|
||||
const { requests } = seerrFetch(hourlyRequests(30))
|
||||
const { requests, inits } = seerrFetch(hourlyRequests(30))
|
||||
const { fetchSeerrStats } = await load()
|
||||
const stats = await fetchSeerrStats(
|
||||
'request',
|
||||
@@ -107,6 +109,7 @@ describe('fetchSeerrStats', () => {
|
||||
expect(requests).toHaveLength(1)
|
||||
expect(requests[0].pathname).toBe('/api/v1/request')
|
||||
expect(requests[0].searchParams.get('take')).toBe('100')
|
||||
expect(inits[0]?.redirect).toBe('manual')
|
||||
})
|
||||
|
||||
it("reads a user's requests with only the parameters Seerr accepts", async () => {
|
||||
|
||||
@@ -89,6 +89,7 @@ export default async function fetchSeerr<T>(
|
||||
headers: {
|
||||
'X-API-KEY': apiKey,
|
||||
},
|
||||
redirect: 'manual',
|
||||
next: {
|
||||
revalidate: cache ? 3600 : 0,
|
||||
},
|
||||
@@ -96,6 +97,16 @@ export default async function fetchSeerr<T>(
|
||||
})
|
||||
|
||||
if (!res.ok) {
|
||||
await res.body?.cancel()
|
||||
|
||||
if (res.status >= 300 && res.status < 400) {
|
||||
console.error(
|
||||
`[SEERR] - API request was redirected (${res.status}) for '${endpoint}'. Check the configured Seerr URL.`,
|
||||
)
|
||||
|
||||
return null
|
||||
}
|
||||
|
||||
if (isGatewayError(res.status)) {
|
||||
markHostDown(seerrUrl)
|
||||
}
|
||||
|
||||
@@ -205,6 +205,21 @@ describe('fetchTautulli', () => {
|
||||
expect(cachedInit.next).toEqual({ revalidate: 3600 })
|
||||
})
|
||||
|
||||
it('URL-encodes API keys and commands with special characters', async () => {
|
||||
const settings = testSettings()
|
||||
|
||||
settings.connection.tautulliApiKey = 'k+e/y&cmd=evil'
|
||||
vi.mocked(getSettings).mockReturnValue(settings)
|
||||
fetchMock.mockResolvedValue(tautulliResponse({}))
|
||||
|
||||
await fetchTautulli('get_activity')
|
||||
|
||||
const url = new URL(String(fetchMock.mock.calls[0][0]))
|
||||
|
||||
expect(url.searchParams.get('apikey')).toBe('k+e/y&cmd=evil')
|
||||
expect(url.searchParams.get('cmd')).toBe('get_activity')
|
||||
})
|
||||
|
||||
it('returns null and says so when the request times out', async () => {
|
||||
const timeout = new DOMException('The operation timed out.', 'TimeoutError')
|
||||
|
||||
|
||||
@@ -45,7 +45,7 @@ export default async function fetchTautulli<T>(
|
||||
return null
|
||||
}
|
||||
|
||||
const apiUrl = `${tautulliUrl}/api/v2?apikey=${apiKey}`
|
||||
const apiUrl = `${tautulliUrl}/api/v2?apikey=${encodeURIComponent(apiKey)}`
|
||||
|
||||
if (isHostDown(tautulliUrl)) {
|
||||
return null
|
||||
@@ -54,15 +54,20 @@ export default async function fetchTautulli<T>(
|
||||
let res: Response | undefined
|
||||
|
||||
try {
|
||||
res = await fetch(`${apiUrl}&cmd=${query}&${qs.stringify(params)}`, {
|
||||
next: {
|
||||
revalidate: cache ? 3600 : 0,
|
||||
res = await fetch(
|
||||
`${apiUrl}&cmd=${encodeURIComponent(query)}&${qs.stringify(params)}`,
|
||||
{
|
||||
next: {
|
||||
revalidate: cache ? 3600 : 0,
|
||||
},
|
||||
signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
|
||||
},
|
||||
signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
|
||||
})
|
||||
)
|
||||
|
||||
// Tautulli answers with a 400 when something isn't there
|
||||
if (!res.ok && !(missingMessage && res.status === 400)) {
|
||||
await res.body?.cancel()
|
||||
|
||||
if (isGatewayError(res.status)) {
|
||||
markHostDown(tautulliUrl)
|
||||
}
|
||||
|
||||
@@ -705,6 +705,17 @@ describe('writeSettings', () => {
|
||||
expect(readSavedSettings().setupComplete).toBe(true)
|
||||
})
|
||||
|
||||
it.skipIf(process.platform === 'win32')(
|
||||
'creates a new settings file readable only by its owner',
|
||||
async () => {
|
||||
const { writeSettings } = await loadModule()
|
||||
|
||||
writeSettings(completeSettings())
|
||||
|
||||
expect(fs.statSync(settingsPath).mode & 0o777).toBe(0o600)
|
||||
},
|
||||
)
|
||||
|
||||
it.skipIf(process.platform === 'win32')(
|
||||
'keeps the permissions of the existing file',
|
||||
async () => {
|
||||
|
||||
@@ -91,7 +91,7 @@ export function writeSettings(settings: Settings): void {
|
||||
console.warn(
|
||||
`[SETTINGS] - Unable to replace ${SETTINGS_PATH} atomically (${code}), writing it in place instead.`,
|
||||
)
|
||||
fs.writeFileSync(SETTINGS_PATH, content)
|
||||
fs.writeFileSync(SETTINGS_PATH, content, { mode: 0o600 })
|
||||
}
|
||||
|
||||
invalid = undefined
|
||||
@@ -404,7 +404,11 @@ function writeAtomically(content: string): void {
|
||||
const original = statQuietly()
|
||||
|
||||
try {
|
||||
const fd = fs.openSync(tempPath, 'w', original && original.mode & 0o777)
|
||||
const fd = fs.openSync(
|
||||
tempPath,
|
||||
'w',
|
||||
original ? original.mode & 0o777 : 0o600,
|
||||
)
|
||||
|
||||
try {
|
||||
if (original) {
|
||||
|
||||
@@ -116,7 +116,16 @@ describe('isAllowedImageUrl', () => {
|
||||
'http://plex.tv/users/abc/avatar',
|
||||
'https://plex.tv.attacker.example/x.png',
|
||||
'https://images.plex.tv/photo?url=https://attacker.example/x.png',
|
||||
'https://images.plex.tv/users/abc/avatar',
|
||||
'https://plex.tv/photo/:/transcode?url=https://attacker.example/x.png',
|
||||
'https://plex.tv/Photo/:/transcode?url=https://attacker.example/x.png',
|
||||
'https://plex.tv//photo/:/transcode?url=https://attacker.example/x.png',
|
||||
'https://plex.tv/photo;x/:/transcode?url=https://attacker.example/x.png',
|
||||
'https://plex.tv/photo.json/:/transcode?url=https://attacker.example/x.png',
|
||||
'https://plex.tv/%70hoto/:/transcode?url=https://attacker.example/x.png',
|
||||
'https://plex.tv/users/..%2fphoto/x',
|
||||
'https://plex.tv/users/%ZZ/avatar',
|
||||
'https://image.tmdb.org/other/path.jpg',
|
||||
'https://attacker.example/x.svg',
|
||||
'http://127.0.0.1:32400/library/metadata/1/thumb',
|
||||
'http://tautulli:8181/api/v2?cmd=get_settings',
|
||||
|
||||
@@ -22,9 +22,10 @@ const PLEX_IMAGE_PATH =
|
||||
/^\/library\/metadata\/\d+\/(thumb|art|banner|clearLogo|poster)(\/\d+)?$/
|
||||
const MAX_DIMENSION = 2000
|
||||
const TMDB_IMAGE_HOST = 'image.tmdb.org'
|
||||
// plex.tv's own photo transcoder fetches any URL it is given
|
||||
const PLEX_TV_HOST = /(^|\.)plex\.tv$/
|
||||
const PLEX_TV_PHOTO_PATH = /^\/photo(\/|$)/
|
||||
// plex.tv's own photo transcoder (/photo) fetches any URL it is given, so
|
||||
// only explicit avatar paths on plex.tv are allowed directly.
|
||||
const PLEX_TV_HOST = 'plex.tv'
|
||||
const PLEX_TV_IMAGE_PATHS = ['/users/', '/avatars/']
|
||||
// Plex avatars redirect through Gravatar, which serves the plex.tv fallback
|
||||
// through WordPress's image proxy. Both fetch other URLs too, so they're only
|
||||
// followed as redirects, and the proxy only to plex.tv.
|
||||
@@ -115,11 +116,38 @@ function isTracearrImageUrl(url: URL, settings: Settings): boolean {
|
||||
)
|
||||
}
|
||||
|
||||
function decodeSafePath(pathname: string): string | null {
|
||||
if (ENCODED_SEPARATOR.test(pathname)) {
|
||||
return null
|
||||
}
|
||||
|
||||
try {
|
||||
const decoded = decodeURIComponent(pathname)
|
||||
|
||||
return ENCODED_SEPARATOR.test(decoded) ? null : decoded
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
function isPublicImageUrl({ protocol, hostname, pathname }: URL): boolean {
|
||||
if (protocol !== 'https:') {
|
||||
return false
|
||||
}
|
||||
|
||||
const decoded = decodeSafePath(pathname)
|
||||
|
||||
if (!decoded) {
|
||||
return false
|
||||
}
|
||||
|
||||
if (hostname === TMDB_IMAGE_HOST) {
|
||||
return decoded.startsWith('/t/p/')
|
||||
}
|
||||
|
||||
return (
|
||||
protocol === 'https:' &&
|
||||
(hostname === TMDB_IMAGE_HOST ||
|
||||
(PLEX_TV_HOST.test(hostname) && !PLEX_TV_PHOTO_PATH.test(pathname)))
|
||||
hostname === PLEX_TV_HOST &&
|
||||
PLEX_TV_IMAGE_PATHS.some((prefix) => decoded.startsWith(prefix))
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
+144
-4
@@ -6,9 +6,11 @@ import { isHostDown } from './hostBackoff'
|
||||
import {
|
||||
getPlexThemeUrl,
|
||||
getPlexTrackUrl,
|
||||
isSignedTheme,
|
||||
isSignedTrack,
|
||||
isThemePath,
|
||||
isTrackPath,
|
||||
MAX_AUDIO_PATHS,
|
||||
streamPlexAudio,
|
||||
} from './plexAudio'
|
||||
|
||||
@@ -63,25 +65,67 @@ beforeEach(() => {
|
||||
vi.spyOn(console, 'error').mockImplementation(() => {})
|
||||
vi.mocked(isHostDown).mockReturnValue(false)
|
||||
fetchMock.mockReset()
|
||||
|
||||
const { rewindarrPlexAudioPaths, rewindarrPendingPlexAudioPaths } =
|
||||
globalThis as {
|
||||
rewindarrPlexAudioPaths?: Map<string, unknown>
|
||||
rewindarrPendingPlexAudioPaths?: Map<string, unknown>
|
||||
}
|
||||
|
||||
rewindarrPlexAudioPaths?.clear()
|
||||
rewindarrPendingPlexAudioPaths?.clear()
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks()
|
||||
vi.unstubAllGlobals()
|
||||
vi.unstubAllEnvs()
|
||||
vi.useRealTimers()
|
||||
})
|
||||
|
||||
describe('getPlexThemeUrl', () => {
|
||||
it('links the app route with a token', () => {
|
||||
expect(getPlexThemeUrl(testSettings(), 123)).toBe(
|
||||
'/api/rewind/theme?key=123',
|
||||
it('signs the rating key separately from track URLs', () => {
|
||||
const themeUrl = new URL(
|
||||
getPlexThemeUrl(testSettings(), 123) ?? '',
|
||||
'http://x',
|
||||
)
|
||||
const trackUrl = new URL(
|
||||
getPlexTrackUrl(testSettings(), '123') ?? '',
|
||||
'http://x',
|
||||
)
|
||||
|
||||
expect(themeUrl.pathname).toBe('/api/rewind/theme')
|
||||
expect(themeUrl.searchParams.get('key')).toBe('123')
|
||||
expect(isSignedTheme('123', themeUrl.searchParams.get('sig') ?? '')).toBe(
|
||||
true,
|
||||
)
|
||||
expect(isSignedTheme('124', themeUrl.searchParams.get('sig') ?? '')).toBe(
|
||||
false,
|
||||
)
|
||||
expect(isSignedTheme('123', trackUrl.searchParams.get('sig') ?? '')).toBe(
|
||||
false,
|
||||
)
|
||||
expect(isSignedTrack('123', themeUrl.searchParams.get('sig') ?? '')).toBe(
|
||||
false,
|
||||
)
|
||||
expect(isSignedTheme('123', '')).toBe(false)
|
||||
})
|
||||
|
||||
it('has none without a token or rating key', () => {
|
||||
it('has none for Jellyfin, without a token, invalid key, or without a secret', () => {
|
||||
const jellyfin = testSettings()
|
||||
|
||||
jellyfin.connection.mediaServerType = 'jellyfin'
|
||||
|
||||
expect(getPlexThemeUrl(jellyfin, 123)).toBeNull()
|
||||
expect(getPlexThemeUrl(testSettings(''), 123)).toBeNull()
|
||||
expect(getPlexThemeUrl(testSettings(), 0)).toBeNull()
|
||||
expect(getPlexThemeUrl(testSettings(), 'abc')).toBeNull()
|
||||
expect(getPlexThemeUrl(testSettings(), undefined)).toBeNull()
|
||||
|
||||
vi.stubEnv('NEXTAUTH_SECRET', '')
|
||||
|
||||
expect(getPlexThemeUrl(testSettings(), 123)).toBeNull()
|
||||
expect(isSignedTheme('123', 'anything')).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
@@ -236,6 +280,102 @@ describe('streamPlexAudio', () => {
|
||||
expect(fetchMock).toHaveBeenCalledTimes(3)
|
||||
})
|
||||
|
||||
it('deduplicates concurrent metadata lookups for the same key', async () => {
|
||||
const key = nextKey()
|
||||
|
||||
let resolveMetadata!: (response: Response) => void
|
||||
|
||||
fetchMock.mockImplementation(async (input: string) => {
|
||||
if (input.endsWith(`/library/metadata/${key}`)) {
|
||||
return await new Promise<Response>((resolve) => {
|
||||
resolveMetadata = resolve
|
||||
})
|
||||
}
|
||||
|
||||
return new Response('audio')
|
||||
})
|
||||
|
||||
const first = streamPlexAudio(testSettings(), 'theme', key, request())
|
||||
const second = streamPlexAudio(
|
||||
testSettings(),
|
||||
'theme',
|
||||
key,
|
||||
request('bytes=10-'),
|
||||
)
|
||||
|
||||
expect(fetchMock).toHaveBeenCalledTimes(1)
|
||||
|
||||
resolveMetadata(themeMetadata(`/library/metadata/${key}/theme/1`))
|
||||
await Promise.all([first, second])
|
||||
|
||||
expect(fetchMock).toHaveBeenCalledTimes(3)
|
||||
})
|
||||
|
||||
it('clears failed lookups without caching so the next request retries', async () => {
|
||||
const key = nextKey()
|
||||
|
||||
fetchMock
|
||||
.mockResolvedValueOnce(new Response(null, { status: 500 }))
|
||||
.mockResolvedValueOnce(themeMetadata(`/library/metadata/${key}/theme/1`))
|
||||
.mockResolvedValueOnce(new Response('audio'))
|
||||
|
||||
expect(
|
||||
(await streamPlexAudio(testSettings(), 'theme', key, request())).status,
|
||||
).toBe(404)
|
||||
|
||||
const retry = await streamPlexAudio(testSettings(), 'theme', key, request())
|
||||
|
||||
expect(retry.status).toBe(200)
|
||||
expect(fetchMock).toHaveBeenCalledTimes(3)
|
||||
})
|
||||
|
||||
it('evicts the oldest cached audio paths once past the cap', async () => {
|
||||
fetchMock.mockImplementation(async (input: string) => {
|
||||
const match = input.match(/\/library\/metadata\/(\d+)$/)
|
||||
|
||||
if (match) {
|
||||
return themeMetadata(`/library/metadata/${match[1]}/theme/1`)
|
||||
}
|
||||
|
||||
return new Response('audio')
|
||||
})
|
||||
|
||||
const firstKey = nextKey()
|
||||
|
||||
await streamPlexAudio(testSettings(), 'theme', firstKey, request())
|
||||
|
||||
for (let i = 0; i < MAX_AUDIO_PATHS; i++) {
|
||||
await streamPlexAudio(testSettings(), 'theme', nextKey(), request())
|
||||
}
|
||||
|
||||
const callsBefore = fetchMock.mock.calls.length
|
||||
|
||||
await streamPlexAudio(testSettings(), 'theme', firstKey, request())
|
||||
|
||||
// Both metadata and audio were fetched again because `firstKey` was evicted
|
||||
expect(fetchMock).toHaveBeenCalledTimes(callsBefore + 2)
|
||||
})
|
||||
|
||||
it('drops expired cache entries when their TTL lapses', async () => {
|
||||
vi.useFakeTimers({ toFake: ['Date'] })
|
||||
|
||||
const key = nextKey()
|
||||
|
||||
fetchMock.mockImplementation(async (input: string) => {
|
||||
if (input.endsWith(`/library/metadata/${key}`)) {
|
||||
return themeMetadata(`/library/metadata/${key}/theme/1`)
|
||||
}
|
||||
|
||||
return new Response('audio')
|
||||
})
|
||||
|
||||
await streamPlexAudio(testSettings(), 'theme', key, request())
|
||||
vi.advanceTimersByTime(61 * 60 * 1000)
|
||||
await streamPlexAudio(testSettings(), 'theme', key, request())
|
||||
|
||||
expect(fetchMock).toHaveBeenCalledTimes(4)
|
||||
})
|
||||
|
||||
it('has none for an item without a theme', async () => {
|
||||
fetchMock.mockResolvedValueOnce(themeMetadata(undefined))
|
||||
|
||||
|
||||
+121
-26
@@ -19,6 +19,7 @@ type AudioPath = {
|
||||
|
||||
export const PLEX_THEME_URL = '/api/rewind/theme'
|
||||
export const PLEX_TRACK_URL = '/api/rewind/track'
|
||||
export const MAX_AUDIO_PATHS = 500
|
||||
|
||||
// Only how long Plex has to start answering; the song itself can take longer
|
||||
const PLEX_TIMEOUT_MS = 10 * 1000
|
||||
@@ -28,7 +29,13 @@ const AUDIO_PATH_TTL_MS = 60 * 60 * 1000
|
||||
const THEME_PATH = /^\/library\/metadata\/\d+\/theme\/\d+$/
|
||||
const TRACK_PATH = /^\/library\/parts\/\d+\/\d+\/file\.([a-z0-9]+)$/i
|
||||
// Browsers ask for parts of the song, each of which would look the item up
|
||||
const audioPaths = new Map<string, AudioPath>()
|
||||
const globalForPlexAudio = globalThis as unknown as {
|
||||
rewindarrPlexAudioPaths?: Map<string, AudioPath>
|
||||
rewindarrPendingPlexAudioPaths?: Map<string, Promise<string | null>>
|
||||
}
|
||||
const audioPaths = (globalForPlexAudio.rewindarrPlexAudioPaths ??= new Map())
|
||||
const pendingAudioPaths = (globalForPlexAudio.rewindarrPendingPlexAudioPaths ??=
|
||||
new Map())
|
||||
|
||||
// Plex only serves the library with a token. Jellyfin's items aren't Plex's.
|
||||
export function canStreamFromPlex({ connection }: Settings): boolean {
|
||||
@@ -39,19 +46,49 @@ export function canStreamFromPlex({ connection }: Settings): boolean {
|
||||
)
|
||||
}
|
||||
|
||||
function signAudio(kind: PlexAudioKind, ratingKey: string): Buffer {
|
||||
return createHmac('sha256', process.env.NEXTAUTH_SECRET ?? '')
|
||||
.update(`${kind}:${ratingKey}`)
|
||||
.digest()
|
||||
}
|
||||
|
||||
function isSignedAudio(
|
||||
kind: PlexAudioKind,
|
||||
ratingKey: string,
|
||||
signature: string,
|
||||
): boolean {
|
||||
if (!process.env.NEXTAUTH_SECRET) {
|
||||
return false
|
||||
}
|
||||
|
||||
// As UTF-8 text so decoding cannot accept alternate spellings of the last char
|
||||
const expected = Buffer.from(signAudio(kind, ratingKey).toString('base64url'))
|
||||
const given = Buffer.from(signature)
|
||||
|
||||
return given.length === expected.length && timingSafeEqual(given, expected)
|
||||
}
|
||||
|
||||
export function getPlexThemeUrl(
|
||||
settings: Settings,
|
||||
ratingKey: string | number | null | undefined,
|
||||
): string | null {
|
||||
return canStreamFromPlex(settings) && ratingKey
|
||||
? `${PLEX_THEME_URL}?key=${ratingKey}`
|
||||
: null
|
||||
const key = ratingKey ? String(ratingKey) : ''
|
||||
|
||||
if (
|
||||
!canStreamFromPlex(settings) ||
|
||||
!/^\d+$/.test(key) ||
|
||||
!process.env.NEXTAUTH_SECRET
|
||||
) {
|
||||
return null
|
||||
}
|
||||
|
||||
const signature = signAudio('theme', key).toString('base64url')
|
||||
|
||||
return `${PLEX_THEME_URL}?key=${key}&sig=${signature}`
|
||||
}
|
||||
|
||||
function signTrack(ratingKey: string): Buffer {
|
||||
return createHmac('sha256', process.env.NEXTAUTH_SECRET ?? '')
|
||||
.update(`track:${ratingKey}`)
|
||||
.digest()
|
||||
export function isSignedTheme(ratingKey: string, signature: string): boolean {
|
||||
return isSignedAudio('theme', ratingKey, signature)
|
||||
}
|
||||
|
||||
// Signed, so viewers can only play the songs their Rewind picked, not any in
|
||||
@@ -63,25 +100,19 @@ export function getPlexTrackUrl(
|
||||
if (
|
||||
!canStreamFromPlex(settings) ||
|
||||
!ratingKey ||
|
||||
!/^\d+$/.test(ratingKey) ||
|
||||
!process.env.NEXTAUTH_SECRET
|
||||
) {
|
||||
return null
|
||||
}
|
||||
|
||||
const signature = signTrack(ratingKey).toString('base64url')
|
||||
const signature = signAudio('track', ratingKey).toString('base64url')
|
||||
|
||||
return `${PLEX_TRACK_URL}?key=${ratingKey}&sig=${signature}`
|
||||
}
|
||||
|
||||
export function isSignedTrack(ratingKey: string, signature: string): boolean {
|
||||
if (!process.env.NEXTAUTH_SECRET) {
|
||||
return false
|
||||
}
|
||||
|
||||
const expected = signTrack(ratingKey)
|
||||
const given = Buffer.from(signature, 'base64url')
|
||||
|
||||
return given.length === expected.length && timingSafeEqual(given, expected)
|
||||
return isSignedAudio('track', ratingKey, signature)
|
||||
}
|
||||
|
||||
export function isThemePath(path: unknown): path is string {
|
||||
@@ -155,18 +186,58 @@ function findAudioPath(
|
||||
return isTrackPath(part) ? part : null
|
||||
}
|
||||
|
||||
async function getAudioPath(
|
||||
function getCachedAudioPath(
|
||||
cacheKey: string,
|
||||
now: number,
|
||||
): string | null | undefined {
|
||||
const cached = audioPaths.get(cacheKey)
|
||||
|
||||
if (!cached) {
|
||||
return undefined
|
||||
}
|
||||
|
||||
if (cached.expiresAt <= now) {
|
||||
audioPaths.delete(cacheKey)
|
||||
|
||||
return undefined
|
||||
}
|
||||
|
||||
audioPaths.delete(cacheKey)
|
||||
audioPaths.set(cacheKey, cached)
|
||||
|
||||
return cached.path
|
||||
}
|
||||
|
||||
function setCachedAudioPath(
|
||||
cacheKey: string,
|
||||
path: string | null,
|
||||
now: number,
|
||||
): void {
|
||||
for (const [key, entry] of audioPaths) {
|
||||
if (entry.expiresAt <= now) {
|
||||
audioPaths.delete(key)
|
||||
}
|
||||
}
|
||||
|
||||
if (audioPaths.has(cacheKey)) {
|
||||
audioPaths.delete(cacheKey)
|
||||
} else if (audioPaths.size >= MAX_AUDIO_PATHS) {
|
||||
const oldestKey = audioPaths.keys().next().value
|
||||
|
||||
if (oldestKey !== undefined) {
|
||||
audioPaths.delete(oldestKey)
|
||||
}
|
||||
}
|
||||
|
||||
audioPaths.set(cacheKey, { path, expiresAt: now + AUDIO_PATH_TTL_MS })
|
||||
}
|
||||
|
||||
async function loadAudioPath(
|
||||
settings: Settings,
|
||||
kind: PlexAudioKind,
|
||||
ratingKey: string,
|
||||
cacheKey: string,
|
||||
): Promise<string | null> {
|
||||
const cacheKey = `${settings.connection.plexUrl}|${kind}|${ratingKey}`
|
||||
const cached = audioPaths.get(cacheKey)
|
||||
|
||||
if (cached && cached.expiresAt > Date.now()) {
|
||||
return cached.path
|
||||
}
|
||||
|
||||
const response = await fetchPlex(settings, `/library/metadata/${ratingKey}`, {
|
||||
Accept: 'application/json',
|
||||
})
|
||||
@@ -180,11 +251,35 @@ async function getAudioPath(
|
||||
const data = await response.json().catch(() => null)
|
||||
const path = findAudioPath(kind, data?.MediaContainer?.Metadata?.[0])
|
||||
|
||||
audioPaths.set(cacheKey, { path, expiresAt: Date.now() + AUDIO_PATH_TTL_MS })
|
||||
setCachedAudioPath(cacheKey, path, Date.now())
|
||||
|
||||
return path
|
||||
}
|
||||
|
||||
async function getAudioPath(
|
||||
settings: Settings,
|
||||
kind: PlexAudioKind,
|
||||
ratingKey: string,
|
||||
): Promise<string | null> {
|
||||
const cacheKey = `${settings.connection.plexUrl}|${kind}|${ratingKey}`
|
||||
const cached = getCachedAudioPath(cacheKey, Date.now())
|
||||
|
||||
if (cached !== undefined) {
|
||||
return cached
|
||||
}
|
||||
|
||||
let pending = pendingAudioPaths.get(cacheKey)
|
||||
|
||||
if (!pending) {
|
||||
pending = loadAudioPath(settings, kind, ratingKey, cacheKey).finally(() => {
|
||||
pendingAudioPaths.delete(cacheKey)
|
||||
})
|
||||
pendingAudioPaths.set(cacheKey, pending)
|
||||
}
|
||||
|
||||
return pending
|
||||
}
|
||||
|
||||
// A song is served as its file's type. Plex calls a theme's MP3 audio/mpeg3,
|
||||
// which isn't a type every browser knows. Null for a file browsers can't play.
|
||||
function getAudioType(path: string, response: Response): string | null {
|
||||
|
||||
@@ -113,12 +113,11 @@ function limitSize(maxBytes: number) {
|
||||
}
|
||||
|
||||
// Written to a temporary file first, so a failed upload keeps the old track.
|
||||
// Returns null when the body is over the limit.
|
||||
export async function saveMusic(
|
||||
body: ReadableStream<Uint8Array>,
|
||||
name: string,
|
||||
type: string,
|
||||
): Promise<RewindMusic | null> {
|
||||
): Promise<RewindMusic | 'tooLarge' | 'empty'> {
|
||||
const tempPath = `${REWIND_MUSIC_PATH}.${randomBytes(6).toString('hex')}.tmp`
|
||||
|
||||
try {
|
||||
@@ -130,6 +129,12 @@ export async function saveMusic(
|
||||
|
||||
const { size } = fs.statSync(tempPath)
|
||||
|
||||
if (size === 0) {
|
||||
fs.rmSync(tempPath, { force: true })
|
||||
|
||||
return 'empty'
|
||||
}
|
||||
|
||||
fs.renameSync(tempPath, REWIND_MUSIC_PATH)
|
||||
|
||||
return { name, type, size, updatedAt: Date.now() }
|
||||
@@ -137,7 +142,7 @@ export async function saveMusic(
|
||||
fs.rmSync(tempPath, { force: true })
|
||||
|
||||
if (error instanceof TooLargeError) {
|
||||
return null
|
||||
return 'tooLarge'
|
||||
}
|
||||
|
||||
throw error
|
||||
|
||||
Reference in new issue
Block a user