feat: connect Jellyfin auth through Jellyseerr

This commit is contained in:
Zebratic committed 2026-08-16 03:33:30 +00:00
1 parent 103f9844ed
commit 24211ed48a
37 files changed
+2168 -183

No files matched your search

+6 -2
View File
@@ -11,6 +11,12 @@ NEXT_SERVER_ACTIONS_ENCRYPTION_KEY=replace-with-openssl-rand-base64-32-output
ARRMATE_ENABLE_DEV_AUTH=false
# Server-side integration settings. None of these are NEXT_PUBLIC_* values.
# Jellyseerr is the current identity, discovery, quota, and request boundary.
# Users sign in through it with Jellyfin credentials; no Jellyseerr API key is
# required for that user-scoped flow.
SEERR_URL=http://localhost:5055
# Planned or partially implemented integration settings.
JELLYFIN_URL=http://localhost:8096
JELLYFIN_API_KEY=replace-me
SONARR_URL=http://localhost:8989
@@ -21,8 +27,6 @@ PROWLARR_URL=http://localhost:9696
PROWLARR_API_KEY=replace-me
BAZARR_URL=http://localhost:6767
BAZARR_API_KEY=replace-me
SEERR_URL=http://localhost:5055
SEERR_API_KEY=replace-me
QBITTORRENT_URL=http://localhost:8080
QBITTORRENT_USERNAME=replace-me
QBITTORRENT_PASSWORD=replace-me
+57 -9
View File
@@ -4,7 +4,13 @@
Arrmate is an open-source, mobile-first management experience for Jellyfin ecosystems. It brings discovery, requests, downloads, library health, subtitle workflows, and service operations into one fast interface instead of making people jump between a pile of separate dashboards.
> **Status:** first working vertical slice. The responsive requester and operator surfaces, role model, PostgreSQL schema, atomic quota core, and read-only qBittorrent adapter are implemented. Other integrations remain honest disconnected states.
> **Status:** early working vertical slice. Jellyfin credential sign-in,
> Jellyseerr-powered discovery/requests/quotas, responsive requester and
> operator surfaces, the PostgreSQL domain foundation, and a read-only
> qBittorrent adapter are implemented. Unconfigured integrations stay in
> honest disconnected states.
![Arrmate — your media stack, finally in one place](./public/assets/arrmate-social.png)
## The idea
@@ -23,20 +29,40 @@ Arrmate is inspired by the unified feel of nzb360, but the goal is a self-hosted
- A visual system that feels calm, quick, modern, and proud to be open source.
- No fake success states: when a service is disconnected or an action is unavailable, the UI should say so clearly.
## Initial integration targets
## Integration map
The first adapter boundary should be designed around these services, without making the core domain model depend on one vendor:
Arrmate keeps its domain model separate from any one vendor. The current target
map is based on the real public service inventory used to shape this project:
- Jellyfin
- Jellyseerr
- Sonarr
- Radarr
- Prowlarr
- Bazarr
- Seerr or Jellyseerr compatibility where useful
- Lidarr
- qBittorrent
- Huntarr and other optional *arr ecosystem tools
- Cleanuparr
- Unmanic
- FlareSolverr
- JFA
Future adapters may include download clients, indexers, media servers, notification providers, transcoding/health tools, and alternative implementations of the same capability.
Huntarr was part of the original idea but was not present in that inventory, so
it remains an optional future adapter rather than a claimed active dependency.
Other download clients, request managers, indexers, media servers, notification
providers, and health tools can implement the same capability contracts.
## Sign in once with Jellyfin
People do not create a second Arrmate account. The sign-in form sends their
Jellyfin username and password to an Arrmate server action, which immediately
exchanges them through Jellyseerr. The password is never stored or returned to
browser code.
Arrmate encrypts the resulting user-scoped Jellyseerr session in an HTTP-only
cookie. Search, quotas, and requests then run as that person, preserving
Jellyseerr attribution, movie/series permissions, approval rules, and limits.
No Jellyseerr API key is needed for this flow.
## Permission model direction
@@ -54,8 +80,10 @@ Every mutation should be authorized server-side. Hiding a button is not authoriz
The current implementation uses:
- Next.js 16 with strict TypeScript for the web application and server boundary.
- A custom responsive CSS design system with no external font or image request.
- A custom responsive CSS and original SVG brand system with no external font request.
- PostgreSQL for Arrmate-owned users, sessions, permissions, quotas, integrations, request records, audit events, and cached normalized state.
- AES-256-GCM authenticated encryption for the user-scoped Jellyseerr session cookie.
- A server-only, response-validated Jellyseerr adapter for sign-in, health, live search, quotas, requests, and logout.
- Typed adapter interfaces and capability checks so unsupported service features degrade gracefully.
- A server-only, response-validated qBittorrent adapter for live queue and transfer data.
- Docker-first local development and tests at the domain, adapter, authorization, and browser workflow boundaries.
@@ -77,7 +105,14 @@ tests/
NEXT_PROMPT.md
```
The current slice deliberately keeps qBittorrent read-only and leaves discovery disconnected until a real provider is configured. Queue mutations, media deletion/replacement, and production authentication are future audited workflows—not placeholder buttons.
The current slice deliberately keeps qBittorrent read-only. Discovery stays
disconnected until `SEERR_URL` points to an authorized Jellyseerr instance.
Queue mutations, media deletion/replacement, subtitle operations, user-limit
editing, and request history are future audited workflows—not placeholder
success states. Series requests currently request all seasons.
Original editable identity assets live in [`public/assets/`](./public/assets/):
the app mark, lockup, orbit illustration, installable icons, and social card.
## Safety and privacy
@@ -101,7 +136,20 @@ npm run db:migrate
npm run dev
```
Node.js 22 or newer and npm 10 are supported. No integration is required to open the app; unconfigured services show a disconnected state. To use the live qBittorrent read path, replace only the qBittorrent placeholders in `.env.local` with an authorized server URL and credentials.
Node.js 22 or newer and npm 10 are supported. No integration is required to
open the app; unconfigured services show a disconnected state.
Generate real development secrets before testing sign-in:
```bash
openssl rand -base64 48 # use for AUTH_SECRET
openssl rand -base64 32 # use for NEXT_SERVER_ACTIONS_ENCRYPTION_KEY
```
Set `SEERR_URL` to an authorized Jellyseerr base URL to enable Jellyfin sign-in,
discovery, quotas, and requests. Set the qBittorrent variables to enable the
read-only live operations path. All integration variables are server-only;
never prefix them with `NEXT_PUBLIC_`.
Before contributing, run:
+13
View File
@@ -26,6 +26,19 @@ Do not include active API keys, passwords, private URLs, media libraries, or use
- Redact authorization headers, cookies, passwords, and API keys from logs.
- Keep dependencies patched and review adapter changes carefully.
## Authentication boundary
Arrmate currently signs people in through Jellyseerr's Jellyfin authentication
endpoint. The password is exchanged once by a server action and is not stored.
The resulting Jellyseerr session is sealed with AES-256-GCM inside an HTTP-only
Arrmate cookie. Treat `AUTH_SECRET` as a production encryption key: make it
high-entropy, keep it consistent across replicas, and never commit it.
This design preserves each person's Jellyseerr permissions, attribution, and
quota. It does not make an internet-facing development deployment production
safe. Authentication rate limiting, deployment origin policy, and broader
session lifecycle controls remain release blockers.
## Scope
The project is early. The absence of a published release does not mean a deployment is safe by default. Operators are responsible for network exposure, TLS, identity provider configuration, backups, and upstream service permissions.
+37 -6
View File
@@ -2,10 +2,17 @@
## Boundaries
Arrmate owns users, roles, request limits, requests, integration configuration,
normalized cached state, and audit events. Jellyfin, the *arr services,
qBittorrent, and subtitle providers remain systems of record for their own
media and job state.
Jellyfin owns media identities. In the current slice Jellyseerr owns the
user-scoped session, permissions, request limits, and request records. Arrmate
normalizes those capabilities into its own role and discovery models without
copying a password or silently becoming an administrator on the person's
behalf. The *arr services, qBittorrent, and subtitle providers remain systems
of record for their media and job state.
The PostgreSQL schema provides a foundation for Arrmate-owned policy overlays,
integration configuration, normalized cached state, and audit events. Those
records are not yet presented as live product state unless a repository is
actually connected.
Browser code never talks to those services directly. A server-side adapter
authenticates upstream, validates responses, applies timeouts, and returns a
@@ -35,6 +42,25 @@ The adapter currently reads deployment environment configuration. The future
integration editor must encrypt credentials before persistence and emit audit
events when an owner changes or tests a connection.
## Jellyfin identity through Jellyseerr
The sign-in form is a server action. It exchanges a Jellyfin username and
password once with Jellyseerr's `/api/v1/auth/jellyfin` endpoint. Browser-side
code never calls Jellyfin or Jellyseerr directly, and Arrmate never persists
the password.
On success, Jellyseerr returns a user profile and `connect.sid` session. Arrmate
puts that upstream session inside an AES-256-GCM authenticated envelope stored
as a same-site, HTTP-only `arrmate-session` cookie for up to 12 hours. The
envelope key is derived from `AUTH_SECRET`; production refuses the documented
placeholder or a secret shorter than 32 characters. Every instance in a
deployment must share the same secret.
Search, quota lookup, and request submission use that person's Jellyseerr
session. This preserves upstream attribution, separate movie/series
permissions, auto-approval behavior, and configured request limits. No
Jellyseerr administrator API key is required for this path.
## Authorization
Roles map to explicit permissions in `src/domain/auth.ts`. Server actions and
@@ -42,8 +68,13 @@ application services must call `authorize` or `can`; route visibility is only a
convenience. Owner, maintainer, requester, and guest are intentionally separate
even when two roles temporarily share a permission.
Local development uses a signed, HTTP-only role cookie. It is not a production
identity system and is disabled in production unless explicitly enabled.
Jellyseerr's `ADMIN` permission maps to owner. Settings, user, or request
management permissions map to maintainer. Other authenticated people are
requesters, with movie and series request abilities checked independently.
Local development also offers a signed, HTTP-only role cookie. It is not a
production identity system and is disabled in production unless explicitly
enabled.
## Quotas and data
+12 -1
View File
@@ -16,6 +16,16 @@ security boundary. Sessions must use HTTP-only, secure, same-site cookies in
production. Authentication and public request endpoints require rate limiting
and CSRF-aware design.
The Jellyfin password enters only the Arrmate server action and is immediately
exchanged through Jellyseerr. It must never be logged, cached, persisted, added
to an error message, or returned to client JavaScript. The resulting upstream
session cookie is encrypted and authenticated inside the Arrmate cookie, but it
still carries the user's authority and must be handled like a credential.
`AUTH_SECRET` protects provider sessions. It must be high-entropy, at least 32
characters, stable across instances, and rotated with the understanding that a
rotation signs everyone out. TLS is required for any non-local deployment.
### Arrmate to upstream services
Credentials stay server-side and must be encrypted at rest before database
@@ -45,7 +55,8 @@ protect anonymous searching, requests, and sign-in attempts.
## Deferred work before production
- Replace development sign-in with an OIDC or similarly mature identity flow.
- Add authentication rate limits, lockout-aware responses, and session
revocation/refresh behavior around the Jellyfin-through-Jellyseerr flow.
- Keep `NEXT_SERVER_ACTIONS_ENCRYPTION_KEY` stable and secret across instances.
- Encrypt stored integration credentials and define key rotation.
- Add CSRF and deployment-aware origin validation to mutations.
@@ -0,0 +1,34 @@
# Jellyfin sign-in and Jellyseerr request slice
Date: 2026-08-16
## Outcome
Let a person sign into Arrmate with the Jellyfin credentials they already use,
then search, request, and see quota information through their own Jellyseerr
identity. Add an original Arrmate SVG brand and artwork system suitable for the
web app, installable icons, repository presentation, and future marketing.
## Security decisions
- Credentials are accepted only by a server action and immediately exchanged
with Jellyseerr's Jellyfin authentication endpoint. They are never persisted,
logged, or returned to client code.
- Arrmate stores the resulting upstream session cookie inside an authenticated,
AES-256-GCM-encrypted, HTTP-only Arrmate cookie with a bounded lifetime.
- Discovery and request calls use the person's Jellyseerr session, not an admin
API key, so upstream permissions, attribution, and quotas remain authoritative.
- Jellyseerr admin permission maps to Arrmate owner; request-management
permissions map to maintainer; everyone else maps to requester.
- Integration requests reject redirects, validate response shapes, and use
deadlines. Upstream failure is distinct from an empty result.
## Deliberate limits
- Arrmate does not create Jellyfin or Jellyseerr accounts.
- User and quota editing remain a later admin workflow. This slice reads and
presents the limits already configured in Jellyseerr.
- TV requests initially request all seasons. Season-by-season selection belongs
in the next media-detail flow.
- Raster campaign artwork is deferred because the built-in generator is not
available in this session. All delivered artwork is original editable SVG.
Binary file not shown.

After

Width:  |  Height:  |  Size: 4.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 13 KiB

+13
View File
@@ -0,0 +1,13 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 360 88" role="img" aria-labelledby="title desc">
<title id="title">Arrmate</title>
<desc id="desc">The Arrmate media signal emblem and wordmark</desc>
<g transform="translate(8 8)">
<rect width="72" height="72" rx="22" fill="#F07D57"/>
<path d="M15 38C15 27 24 18 35 18h19" fill="none" stroke="#20130F" stroke-width="5" stroke-linecap="round" opacity=".25"/>
<rect x="18" y="37" width="8" height="19" rx="4" fill="#20130F"/>
<rect x="32" y="26" width="8" height="30" rx="4" fill="#20130F"/>
<rect x="46" y="15" width="8" height="41" rx="4" fill="#20130F"/>
<circle cx="19" cy="24" r="4" fill="#FFF7F2"/>
</g>
<text x="101" y="58" fill="#F5F4EF" font-family="Inter, ui-sans-serif, system-ui, sans-serif" font-size="49" font-weight="760" letter-spacing="-2">Arr<tspan fill="#F4A181">mate</tspan></text>
</svg>

After

Width:  |  Height:  |  Size: 895 B

+9
View File
@@ -0,0 +1,9 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64" role="img" aria-labelledby="title">
<title id="title">Arrmate</title>
<rect x="5" y="5" width="54" height="54" rx="17" fill="#F07D57"/>
<path d="M16 36.5C16 28.49 22.49 22 30.5 22h14" fill="none" stroke="#20130F" stroke-width="4" stroke-linecap="round" opacity=".25"/>
<rect x="18" y="32" width="6" height="14" rx="3" fill="#20130F"/>
<rect x="29" y="24" width="6" height="22" rx="3" fill="#20130F"/>
<rect x="40" y="16" width="6" height="30" rx="3" fill="#20130F"/>
<circle cx="18" cy="23" r="3" fill="#FFF7F2"/>
</svg>

After

Width:  |  Height:  |  Size: 595 B

+82
View File
@@ -0,0 +1,82 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 960 900" role="img" aria-labelledby="title desc">
<title id="title">The Arrmate media orbit</title>
<desc id="desc">Abstract movie, series, subtitle, and download cards orbiting a connected Arrmate hub</desc>
<defs>
<radialGradient id="bg" cx="52%" cy="47%" r="70%">
<stop offset="0" stop-color="#23362E"/>
<stop offset=".52" stop-color="#16211D"/>
<stop offset="1" stop-color="#0F1513"/>
</radialGradient>
<linearGradient id="coral" x1="0" y1="0" x2="1" y2="1">
<stop stop-color="#B8684D"/>
<stop offset="1" stop-color="#49352D"/>
</linearGradient>
<linearGradient id="teal" x1="0" y1="0" x2="1" y2="1">
<stop stop-color="#477B6C"/>
<stop offset="1" stop-color="#1D302A"/>
</linearGradient>
<linearGradient id="violet" x1="0" y1="0" x2="1" y2="1">
<stop stop-color="#655A85"/>
<stop offset="1" stop-color="#292637"/>
</linearGradient>
<linearGradient id="blue" x1="0" y1="0" x2="1" y2="1">
<stop stop-color="#47758A"/>
<stop offset="1" stop-color="#1D2C33"/>
</linearGradient>
<filter id="shadow" x="-40%" y="-40%" width="180%" height="180%">
<feDropShadow dx="0" dy="24" stdDeviation="18" flood-color="#000" flood-opacity=".32"/>
</filter>
<filter id="grain" x="0" y="0" width="100%" height="100%">
<feTurbulence baseFrequency=".8" numOctaves="3" seed="17" type="fractalNoise" result="noise"/>
<feColorMatrix in="noise" type="saturate" values="0" result="mono"/>
<feComponentTransfer in="mono"><feFuncA type="table" tableValues="0 .045"/></feComponentTransfer>
</filter>
</defs>
<rect width="960" height="900" rx="44" fill="url(#bg)"/>
<circle cx="480" cy="450" r="316" fill="none" stroke="#B8C8BE" stroke-opacity=".08" stroke-width="2"/>
<circle cx="480" cy="450" r="234" fill="none" stroke="#B8C8BE" stroke-opacity=".12" stroke-width="2" stroke-dasharray="7 13"/>
<ellipse cx="480" cy="450" rx="390" ry="195" fill="none" stroke="#F4A181" stroke-opacity=".15" stroke-width="2" transform="rotate(-18 480 450)"/>
<path d="M277 270 414 391M667 261 547 389M682 628 550 512M274 641 411 516" stroke="#ADC6B8" stroke-opacity=".16" stroke-width="3" stroke-linecap="round"/>
<g filter="url(#shadow)" transform="translate(379 349)">
<circle cx="101" cy="101" r="101" fill="#E87951" fill-opacity=".12"/>
<circle cx="101" cy="101" r="75" fill="#F07D57"/>
<rect x="69" y="103" width="13" height="31" rx="6.5" fill="#20130F"/>
<rect x="95" y="84" width="13" height="50" rx="6.5" fill="#20130F"/>
<rect x="121" y="64" width="13" height="70" rx="6.5" fill="#20130F"/>
<circle cx="70" cy="81" r="7" fill="#FFF7F2"/>
</g>
<g filter="url(#shadow)" transform="rotate(-8 229 228)">
<rect x="111" y="116" width="236" height="224" rx="30" fill="url(#coral)" stroke="#EAB6A2" stroke-opacity=".24"/>
<rect x="139" y="147" width="180" height="118" rx="18" fill="#1B201D" fill-opacity=".55"/>
<path d="M177 178h104M177 205h73M177 232h91" stroke="#F3D5C8" stroke-opacity=".55" stroke-width="11" stroke-linecap="round"/>
<g fill="#F4A181" opacity=".76"><rect x="145" y="286" width="24" height="20" rx="5"/><rect x="179" y="286" width="24" height="20" rx="5"/><rect x="213" y="286" width="24" height="20" rx="5"/><rect x="247" y="286" width="24" height="20" rx="5"/><rect x="281" y="286" width="24" height="20" rx="5"/></g>
</g>
<g filter="url(#shadow)" transform="rotate(7 731 214)">
<rect x="623" y="104" width="216" height="220" rx="30" fill="url(#violet)" stroke="#C0B7E6" stroke-opacity=".24"/>
<rect x="656" y="138" width="150" height="105" rx="18" fill="#17171E" fill-opacity=".57"/>
<path d="m716 175 38 22-38 22Z" fill="#D5CFF0" fill-opacity=".72"/>
<rect x="658" y="270" width="99" height="11" rx="5.5" fill="#D5CFF0" fill-opacity=".48"/>
<circle cx="783" cy="275" r="11" fill="#A99BE6"/>
</g>
<g filter="url(#shadow)" transform="rotate(-5 213 669)">
<rect x="103" y="563" width="235" height="215" rx="30" fill="url(#blue)" stroke="#B3D8E8" stroke-opacity=".22"/>
<path d="M153 613h136a18 18 0 0 1 18 18v67a18 18 0 0 1-18 18h-61l-31 28 6-28h-50a18 18 0 0 1-18-18v-67a18 18 0 0 1 18-18Z" fill="#122027" fill-opacity=".6"/>
<path d="M166 649h111M166 678h78" stroke="#B8D8E5" stroke-opacity=".68" stroke-width="11" stroke-linecap="round"/>
</g>
<g filter="url(#shadow)" transform="rotate(8 731 668)">
<rect x="619" y="556" width="228" height="222" rx="30" fill="url(#teal)" stroke="#B9DED1" stroke-opacity=".22"/>
<path d="M683 614v67M712 635v46M741 598v83M770 649v32" stroke="#C3E3D7" stroke-opacity=".7" stroke-width="14" stroke-linecap="round"/>
<rect x="666" y="714" width="134" height="11" rx="5.5" fill="#14241F" fill-opacity=".75"/>
<rect x="666" y="714" width="91" height="11" rx="5.5" fill="#78D49F"/>
</g>
<g fill="#F4A181"><circle cx="379" cy="357" r="7"/><circle cx="584" cy="355" r="7"/><circle cx="587" cy="551" r="7"/><circle cx="376" cy="548" r="7"/></g>
<g fill="#E8F0EA" fill-opacity=".62"><circle cx="172" cy="449" r="6"/><circle cx="789" cy="428" r="6"/><circle cx="480" cy="138" r="6"/><circle cx="480" cy="766" r="6"/></g>
<rect width="960" height="900" rx="44" filter="url(#grain)" opacity=".8"/>
</svg>

After

Width:  |  Height:  |  Size: 5.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 282 KiB

+19
View File
@@ -0,0 +1,19 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1200 630" role="img" aria-labelledby="title desc">
<title id="title">Arrmate</title>
<desc id="desc">The friendly control plane for your self-hosted media stack</desc>
<defs>
<radialGradient id="g" cx="70%" cy="20%" r="90%"><stop stop-color="#274236"/><stop offset=".55" stop-color="#121B17"/><stop offset="1" stop-color="#0D1110"/></radialGradient>
</defs>
<rect width="1200" height="630" fill="url(#g)"/>
<circle cx="947" cy="315" r="218" fill="none" stroke="#8AB39A" stroke-opacity=".14" stroke-width="2"/>
<circle cx="947" cy="315" r="147" fill="none" stroke="#F4A181" stroke-opacity=".24" stroke-width="2" stroke-dasharray="8 12"/>
<g transform="translate(861 229)">
<rect width="172" height="172" rx="51" fill="#F07D57"/>
<path d="M38 94c0-28 23-51 51-51h47" fill="none" stroke="#20130F" stroke-width="13" stroke-linecap="round" opacity=".25"/>
<rect x="43" y="88" width="19" height="45" rx="9.5" fill="#20130F"/><rect x="76" y="62" width="19" height="71" rx="9.5" fill="#20130F"/><rect x="109" y="36" width="19" height="97" rx="9.5" fill="#20130F"/><circle cx="44" cy="58" r="10" fill="#FFF7F2"/>
</g>
<g fill="#F4A181"><circle cx="947" cy="96" r="8"/><circle cx="729" cy="315" r="8"/><circle cx="947" cy="533" r="8"/><circle cx="1165" cy="315" r="8"/></g>
<text x="88" y="258" fill="#F5F4EF" font-family="Inter, ui-sans-serif, system-ui, sans-serif" font-size="96" font-weight="760" letter-spacing="-5">Arr<tspan fill="#F4A181">mate</tspan></text>
<text x="93" y="337" fill="#B1BAB4" font-family="Inter, ui-sans-serif, system-ui, sans-serif" font-size="34" font-weight="500">Your media stack, finally in one place.</text>
<text x="93" y="408" fill="#78D49F" font-family="Inter, ui-sans-serif, system-ui, sans-serif" font-size="22" font-weight="700" letter-spacing="3">SELF-HOSTED · OPEN SOURCE · MOBILE FIRST</text>
</svg>

After

Width:  |  Height:  |  Size: 1.9 KiB

+190
View File
@@ -0,0 +1,190 @@
import { describe, expect, it, vi } from "vitest";
import { JellyseerrAdapter } from "./jellyseerr";
function adapter(fetchImpl: typeof fetch, timeoutMs = 100) {
return new JellyseerrAdapter(
{ baseUrl: "http://jellyseerr.test:5055", timeoutMs },
fetchImpl,
);
}
function pathname(input: RequestInfo | URL): string {
if (input instanceof URL) return `${input.pathname}${input.search}`;
if (input instanceof Request) {
const url = new URL(input.url);
return `${url.pathname}${url.search}`;
}
const url = new URL(input);
return `${url.pathname}${url.search}`;
}
describe("Jellyseerr adapter", () => {
it("exchanges Jellyfin credentials for a user-scoped session", async () => {
const fetchMock = vi.fn(async () =>
Response.json(
{
id: 7,
jellyfinUsername: "friend",
permissions: 32,
avatar: "/avatarproxy/user",
},
{
headers: {
"set-cookie": "connect.sid=s%3Atest.signature; Path=/; HttpOnly",
},
},
),
) as unknown as typeof fetch;
const result = await adapter(fetchMock).login("friend", "local-test-value");
expect(result).toEqual({
ok: true,
data: {
user: {
id: 7,
displayName: "friend",
permissions: 32,
avatarPath: "/avatarproxy/user",
},
sessionCookie: "connect.sid=s%3Atest.signature",
},
});
const [, init] = vi.mocked(fetchMock).mock.calls[0];
expect(init?.redirect).toBe("error");
expect(JSON.parse(String(init?.body))).toEqual({
username: "friend",
password: "local-test-value",
});
});
it("returns a safe message when Jellyfin rejects the credentials", async () => {
const fetchMock = vi.fn(async () =>
Response.json({}, { status: 401 }),
) as unknown as typeof fetch;
const result = await adapter(fetchMock).login("friend", "local-test-value");
expect(result).toEqual({
ok: false,
error: {
code: "authentication",
message: "Jellyfin did not accept those credentials",
retryable: false,
},
});
});
it("rejects a login response without an upstream session", async () => {
const fetchMock = vi.fn(async () =>
Response.json({ id: 7, permissions: 32 }),
) as unknown as typeof fetch;
const result = await adapter(fetchMock).login("friend", "local-test-value");
expect(result).toMatchObject({
ok: false,
error: { code: "malformed-response" },
});
});
it("normalizes movie and series search results and ignores people", async () => {
const fetchMock = vi.fn(async () =>
Response.json({
page: 1,
totalPages: 1,
totalResults: 3,
results: [
{
id: 10,
mediaType: "movie",
title: "A Film",
releaseDate: "2026-03-02",
overview: "Movie overview",
posterPath: "/film.jpg",
voteAverage: 8.2,
mediaInfo: { status: 5 },
},
{
id: 11,
mediaType: "tv",
name: "A Series",
firstAirDate: "2025-01-01",
overview: "Series overview",
},
{ id: 12, mediaType: "person", name: "An Actor" },
],
}),
) as unknown as typeof fetch;
const result = await adapter(fetchMock).search("test", "connect.sid=test");
expect(result).toMatchObject({
ok: true,
data: {
items: [
{
id: 10,
mediaType: "movie",
title: "A Film",
year: "2026",
availability: 5,
},
{ id: 11, mediaType: "series", title: "A Series", year: "2025" },
],
},
});
const [, init] = vi.mocked(fetchMock).mock.calls[0];
expect(new Headers(init?.headers).get("cookie")).toBe("connect.sid=test");
});
it("reads the user's Jellyseerr quota", async () => {
const fetchMock = vi.fn(async () =>
Response.json({
movie: { days: 7, limit: 3, used: 1, remaining: 2, restricted: false },
tv: { days: 30, limit: 2, used: 2, remaining: 0, restricted: true },
}),
) as unknown as typeof fetch;
const result = await adapter(fetchMock).quota(7, "connect.sid=test");
expect(result).toMatchObject({
ok: true,
data: {
movie: { remaining: 2 },
series: { remaining: 0, restricted: true },
},
});
});
it("requests every season for the initial series request flow", async () => {
const fetchMock = vi.fn(async () =>
Response.json({ id: 99, status: 1 }, { status: 201 }),
) as unknown as typeof fetch;
const result = await adapter(fetchMock).createRequest(
42,
"series",
"connect.sid=test",
);
expect(result).toEqual({ ok: true, data: { id: 99, status: "pending" } });
const [input, init] = vi.mocked(fetchMock).mock.calls[0];
expect(pathname(input)).toBe("/api/v1/request");
expect(JSON.parse(String(init?.body))).toEqual({
mediaId: 42,
mediaType: "tv",
seasons: "all",
});
});
it("distinguishes an upstream timeout", async () => {
const fetchMock = vi.fn(
(_input: RequestInfo | URL, init?: RequestInit) =>
new Promise<Response>((_resolve, reject) => {
init?.signal?.addEventListener("abort", () =>
reject(new DOMException("aborted", "AbortError")),
);
}),
) as unknown as typeof fetch;
const result = await adapter(fetchMock, 2).search(
"test",
"connect.sid=test",
);
expect(result).toMatchObject({
ok: false,
error: { code: "timeout", retryable: true },
});
});
});
+381
View File
@@ -0,0 +1,381 @@
import { z } from "zod";
import type {
DiscoveryItem,
DiscoveryPage,
DiscoveryMediaType,
SeerrQuota,
SeerrRequestReceipt,
SeerrUser,
} from "@/domain/discovery";
import type {
AdapterError,
AdapterResult,
CapabilitySet,
} from "@/domain/integrations";
import type { IntegrationAdapter } from "./contracts";
import { normalizeIntegrationUrl } from "./url";
const userSchema = z
.object({
id: z.number().int().positive(),
displayName: z.string().optional().nullable(),
username: z.string().optional().nullable(),
jellyfinUsername: z.string().optional().nullable(),
email: z.string().optional().nullable(),
permissions: z.number().int().nonnegative().default(0),
avatar: z.string().optional().nullable(),
})
.passthrough();
const mediaInfoSchema = z
.object({
status: z.number().int().optional().nullable(),
})
.passthrough()
.optional()
.nullable();
const searchItemSchema = z
.object({
id: z.number().int().positive(),
mediaType: z.string(),
title: z.string().optional(),
name: z.string().optional(),
overview: z.string().optional().default(""),
releaseDate: z.string().optional().nullable(),
firstAirDate: z.string().optional().nullable(),
posterPath: z.string().optional().nullable(),
backdropPath: z.string().optional().nullable(),
voteAverage: z.number().optional().nullable(),
mediaInfo: mediaInfoSchema,
})
.passthrough();
const searchResponseSchema = z.object({
page: z.number().int().nonnegative(),
totalPages: z.number().int().nonnegative(),
totalResults: z.number().int().nonnegative(),
results: z.array(searchItemSchema),
});
const quotaWindowSchema = z.object({
days: z.number().nonnegative().nullable().default(null),
limit: z.number().nonnegative().nullable().default(null),
used: z.number().nonnegative().default(0),
remaining: z.number().nonnegative().nullable().default(null),
restricted: z.boolean().default(false),
});
const quotaSchema = z.object({
movie: quotaWindowSchema,
tv: quotaWindowSchema,
});
const requestReceiptSchema = z.object({
id: z.number().int().positive(),
status: z.number().int(),
});
export interface JellyseerrConfig {
baseUrl: string;
timeoutMs?: number;
}
export interface JellyseerrLogin {
user: SeerrUser;
sessionCookie: string;
}
type Fetch = typeof fetch;
function errorResult(
code: AdapterError["code"],
message: string,
retryable: boolean,
): AdapterResult<never> {
return { ok: false, error: { code, message, retryable } };
}
function normalizeUser(user: z.infer<typeof userSchema>): SeerrUser {
return {
id: user.id,
displayName:
user.displayName ||
user.username ||
user.jellyfinUsername ||
user.email?.split("@")[0] ||
"Jellyfin user",
permissions: user.permissions,
avatarPath: user.avatar || null,
};
}
function normalizeSearchItem(
item: z.infer<typeof searchItemSchema>,
): DiscoveryItem | null {
if (item.mediaType !== "movie" && item.mediaType !== "tv") return null;
const title = item.mediaType === "movie" ? item.title : item.name;
if (!title) return null;
const date =
item.mediaType === "movie" ? item.releaseDate : item.firstAirDate;
return {
id: item.id,
mediaType: item.mediaType === "movie" ? "movie" : "series",
title,
overview: item.overview,
year: date?.slice(0, 4) || null,
posterPath: item.posterPath || null,
backdropPath: item.backdropPath || null,
rating: typeof item.voteAverage === "number" ? item.voteAverage : null,
availability: item.mediaInfo?.status ?? null,
};
}
function requestStatus(status: number): SeerrRequestReceipt["status"] {
if (status === 1) return "pending";
if (status === 2) return "approved";
if (status === 3) return "declined";
return "unknown";
}
export class JellyseerrAdapter implements IntegrationAdapter {
readonly name = "Jellyseerr";
readonly capabilities: CapabilitySet = {
readQueue: false,
manageQueue: false,
search: true,
request: true,
deleteMedia: false,
replaceMedia: false,
searchSubtitles: false,
};
private readonly baseUrl: URL;
private readonly timeoutMs: number;
constructor(
config: JellyseerrConfig,
private readonly fetchImpl: Fetch = fetch,
) {
this.baseUrl = normalizeIntegrationUrl(config.baseUrl);
this.timeoutMs = config.timeoutMs ?? 8_000;
}
async health(): Promise<AdapterResult<{ latencyMs: number }>> {
const startedAt = performance.now();
const response = await this.request("/api/v1/status");
if (!response.ok) return response;
if (!response.data.ok) return this.httpError(response.data.status);
return {
ok: true,
data: { latencyMs: Math.round(performance.now() - startedAt) },
};
}
async login(
username: string,
password: string,
): Promise<AdapterResult<JellyseerrLogin>> {
const response = await this.request("/api/v1/auth/jellyfin", undefined, {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({ username, password }),
});
if (!response.ok) return response;
if (!response.data.ok) return this.httpError(response.data.status, true);
const sessionCookie = response.data.headers
.get("set-cookie")
?.match(/connect\.sid=[^;]+/)?.[0];
if (!sessionCookie) {
return errorResult(
"malformed-response",
"Jellyseerr did not create a user session",
true,
);
}
try {
const user = userSchema.parse(await response.data.json());
return { ok: true, data: { user: normalizeUser(user), sessionCookie } };
} catch {
return errorResult(
"malformed-response",
"Jellyseerr returned an invalid user profile",
true,
);
}
}
async search(
query: string,
sessionCookie: string,
page = 1,
): Promise<AdapterResult<DiscoveryPage>> {
const params = new URLSearchParams({ query, page: String(page) });
const response = await this.request(
`/api/v1/search?${params}`,
sessionCookie,
);
if (!response.ok) return response;
if (!response.data.ok) return this.httpError(response.data.status);
try {
const result = searchResponseSchema.parse(await response.data.json());
return {
ok: true,
data: {
page: result.page,
totalPages: result.totalPages,
totalResults: result.totalResults,
items: result.results
.map(normalizeSearchItem)
.filter((item): item is DiscoveryItem => item !== null),
},
};
} catch {
return errorResult(
"malformed-response",
"Jellyseerr returned search data Arrmate could not validate",
true,
);
}
}
async quota(
userId: number,
sessionCookie: string,
): Promise<AdapterResult<SeerrQuota>> {
const response = await this.request(
`/api/v1/user/${userId}/quota`,
sessionCookie,
);
if (!response.ok) return response;
if (!response.data.ok) return this.httpError(response.data.status);
try {
const quota = quotaSchema.parse(await response.data.json());
return {
ok: true,
data: { movie: quota.movie, series: quota.tv },
};
} catch {
return errorResult(
"malformed-response",
"Jellyseerr returned invalid quota data",
true,
);
}
}
async createRequest(
mediaId: number,
mediaType: DiscoveryMediaType,
sessionCookie: string,
): Promise<AdapterResult<SeerrRequestReceipt>> {
const response = await this.request("/api/v1/request", sessionCookie, {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({
mediaId,
mediaType: mediaType === "series" ? "tv" : "movie",
...(mediaType === "series" ? { seasons: "all" } : {}),
}),
});
if (!response.ok) return response;
if (!response.data.ok) return this.httpError(response.data.status);
try {
const receipt = requestReceiptSchema.parse(await response.data.json());
return {
ok: true,
data: { id: receipt.id, status: requestStatus(receipt.status) },
};
} catch {
return errorResult(
"malformed-response",
"Jellyseerr accepted the request but returned an invalid receipt",
false,
);
}
}
async logout(sessionCookie: string): Promise<void> {
await this.request("/api/v1/auth/logout", sessionCookie, {
method: "POST",
});
}
artworkUrl(path: string, size: "w342" | "w500" = "w342"): URL {
if (!/^\/[A-Za-z0-9/_-]+\.(jpg|jpeg|png|webp)$/i.test(path)) {
throw new Error("Invalid artwork path");
}
return new URL(
`/imageproxy/t/p/${size}${path}`,
`${this.baseUrl.toString()}/`,
);
}
private httpError(status: number, login = false): AdapterResult<never> {
if (status === 401 || status === 403) {
return errorResult(
"authentication",
login
? "Jellyfin did not accept those credentials"
: "Your Jellyseerr session is no longer valid",
false,
);
}
return errorResult(
"upstream",
status === 429
? "Jellyseerr is receiving too many requests"
: "Jellyseerr request failed",
status >= 500 || status === 429,
);
}
private async request(
path: string,
sessionCookie?: string,
init: RequestInit = {},
): Promise<AdapterResult<Response>> {
const controller = new AbortController();
const timeout = setTimeout(() => controller.abort(), this.timeoutMs);
try {
const headers = new Headers(init.headers);
headers.set("accept", "application/json");
headers.set("referer", this.baseUrl.toString());
if (sessionCookie) headers.set("cookie", sessionCookie);
const response = await this.fetchImpl(
new URL(path, `${this.baseUrl.toString()}/`),
{
...init,
headers,
signal: controller.signal,
cache: "no-store",
redirect: "error",
},
);
return { ok: true, data: response };
} catch (error) {
if (
controller.signal.aborted ||
(error instanceof Error && error.name === "AbortError")
) {
return errorResult(
"timeout",
"Jellyseerr did not respond before the timeout",
true,
);
}
return errorResult(
"unreachable",
"Jellyseerr could not be reached",
true,
);
} finally {
clearTimeout(timeout);
}
}
}
+79 -3
View File
@@ -1,14 +1,55 @@
"use server";
import { redirect } from "next/navigation";
import { z } from "zod";
import type { Role } from "@/domain/auth";
import { roles } from "@/domain/auth";
import { authorize, roles } from "@/domain/auth";
import type { DiscoveryMediaType } from "@/domain/discovery";
import { canRequestThroughSeerr } from "@/domain/seerr-permissions";
import {
clearDevelopmentViewer,
clearSessions,
developmentAuthEnabled,
getProviderSession,
getViewer,
setProviderSession,
setDevelopmentViewer,
} from "@/server/auth/session";
import { jellyseerrFromEnvironment } from "@/server/integrations/jellyseerr";
export interface SignInState {
error?: string;
}
const signInSchema = z.object({
username: z.string().trim().min(1).max(128),
password: z.string().min(1).max(512),
});
const requestSchema = z.object({
mediaId: z.coerce.number().int().positive(),
mediaType: z.enum(["movie", "series"]),
});
export async function jellyfinSignIn(
_state: SignInState,
formData: FormData,
): Promise<SignInState> {
const input = signInSchema.safeParse({
username: formData.get("username"),
password: formData.get("password"),
});
if (!input.success)
return { error: "Enter your Jellyfin username and password." };
const adapter = jellyseerrFromEnvironment();
if (!adapter)
return { error: "Jellyseerr sign-in has not been configured yet." };
const result = await adapter.login(input.data.username, input.data.password);
if (!result.ok) return { error: result.error.message };
await setProviderSession(result.data);
redirect("/");
}
export async function developmentSignIn(formData: FormData) {
if (!developmentAuthEnabled()) redirect("/sign-in?error=disabled");
@@ -19,6 +60,41 @@ export async function developmentSignIn(formData: FormData) {
}
export async function signOut() {
await clearDevelopmentViewer();
const session = await getProviderSession();
const adapter = jellyseerrFromEnvironment();
if (session && adapter) await adapter.logout(session.upstreamCookie);
await clearSessions();
redirect("/");
}
export async function createMediaRequest(formData: FormData) {
const input = requestSchema.safeParse({
mediaId: formData.get("mediaId"),
mediaType: formData.get("mediaType"),
});
if (!input.success) redirect("/discover?request=invalid");
const viewer = await getViewer();
authorize(viewer, "request:create");
const session = await getProviderSession();
if (!session) redirect("/sign-in");
if (
!canRequestThroughSeerr(
session.user.permissions,
input.data.mediaType as DiscoveryMediaType,
)
) {
redirect("/discover?request=forbidden");
}
const adapter = jellyseerrFromEnvironment();
if (!adapter) redirect("/discover?request=unavailable");
const result = await adapter.createRequest(
input.data.mediaId,
input.data.mediaType,
session.upstreamCookie,
);
redirect(
`/discover?request=${result.ok ? result.data.status : result.error.code}`,
);
}
+34
View File
@@ -0,0 +1,34 @@
import { type NextRequest, NextResponse } from "next/server";
const artworkPath = /^\/[A-Za-z0-9/_-]+\.(jpg|jpeg|png|webp)$/i;
export async function GET(request: NextRequest) {
const path = request.nextUrl.searchParams.get("path");
if (!path || !artworkPath.test(path)) {
return NextResponse.json(
{ error: "Invalid artwork path" },
{ status: 400 },
);
}
try {
const upstream = await fetch(`https://image.tmdb.org/t/p/w500${path}`, {
redirect: "error",
next: { revalidate: 60 * 60 * 24 * 7 },
signal: AbortSignal.timeout(8_000),
});
const contentType = upstream.headers.get("content-type");
if (!upstream.ok || !contentType?.startsWith("image/")) {
return new NextResponse(null, { status: 404 });
}
return new NextResponse(upstream.body, {
headers: {
"content-type": contentType,
"cache-control": "public, max-age=86400, stale-while-revalidate=604800",
"content-security-policy": "default-src 'none'",
},
});
} catch {
return new NextResponse(null, { status: 502 });
}
}
+179 -24
View File
@@ -1,15 +1,40 @@
import { CircleSlash2, Search, SlidersHorizontal } from "lucide-react";
import {
Check,
CircleSlash2,
Film,
Search,
SlidersHorizontal,
Star,
Tv,
} from "lucide-react";
import Image from "next/image";
import Link from "next/link";
import { createMediaRequest } from "@/app/actions";
import { EmptyState } from "@/components/empty-state";
import type { DiscoveryItem } from "@/domain/discovery";
import { canRequestThroughSeerr } from "@/domain/seerr-permissions";
import { getProviderSession } from "@/server/auth/session";
import { jellyseerrFromEnvironment } from "@/server/integrations/jellyseerr";
export const metadata = { title: "Discover" };
export const dynamic = "force-dynamic";
export default async function DiscoverPage({
searchParams,
}: {
searchParams: Promise<{ q?: string }>;
searchParams: Promise<{ q?: string; request?: string }>;
}) {
const query = (await searchParams).q?.trim() ?? "";
const params = await searchParams;
const query = params.q?.trim().slice(0, 120) ?? "";
const session = await getProviderSession();
const adapter = jellyseerrFromEnvironment();
const result =
query.length >= 2 && session && adapter
? await adapter.search(query, session.upstreamCookie)
: null;
const items = result?.ok ? result.data.items : [];
return (
<div className="page-stack compact-stack">
<section className="welcome-row">
@@ -17,7 +42,7 @@ export default async function DiscoverPage({
<p className="eyebrow">Discover</p>
<h1>Find anything.</h1>
<p className="page-lead">
Movies and series will share one clean search.
Movies and series. One search. One request.
</p>
</div>
</section>
@@ -30,6 +55,7 @@ export default async function DiscoverPage({
aria-label="Search movies and series"
placeholder="Search movies and series…"
autoComplete="off"
maxLength={120}
/>
<button
className="filter-button"
@@ -41,27 +67,156 @@ export default async function DiscoverPage({
</button>
</form>
<div className="connection-banner" role="status">
<span className="banner-dot" />
<div>
<strong>Discovery isn’t connected yet</strong>
<p>
Connect Jellyseerr or a metadata provider to return real results.
</p>
</div>
</div>
{params.request && <RequestNotice value={params.request} />}
<section className="surface-card min-card">
<EmptyState
icon={CircleSlash2}
title={
query
? `No live results for “${query}”`
: "Ready when your provider is"
}
description="Arrmate won't fill this screen with demo titles. Once connected, search results and request availability will show here."
/>
</section>
{!adapter ? (
<div className="connection-banner" role="status">
<span className="banner-dot" />
<div>
<strong>Discovery isn’t connected yet</strong>
<p>Configure Jellyseerr to return real results.</p>
</div>
</div>
) : !session ? (
<div className="connection-banner connected-banner" role="status">
<span className="banner-dot" />
<div>
<strong>Jellyseerr is ready</strong>
<p>
<Link href="/sign-in">Sign in with Jellyfin</Link> to search and
request.
</p>
</div>
</div>
) : null}
{items.length > 0 && session ? (
<section className="media-grid" aria-label="Search results">
{items.map((item) => (
<MediaCard
key={`${item.mediaType}-${item.id}`}
item={item}
canRequest={canRequestThroughSeerr(
session.user.permissions,
item.mediaType,
)}
/>
))}
</section>
) : (
<section className="surface-card min-card">
<EmptyState
icon={CircleSlash2}
title={
result && !result.ok
? "Jellyseerr needs attention"
: query.length >= 2 && session
? `No results for “${query}”`
: "Search your next favorite"
}
description={
result && !result.ok
? result.error.message
: session
? "Try a movie or series title. Results come live from Jellyseerr."
: "Sign in with Jellyfin to search the connected Jellyseerr library."
}
/>
</section>
)}
</div>
);
}
function RequestNotice({ value }: { value: string }) {
const success = value === "pending" || value === "approved";
return (
<div
className={success ? "request-notice success" : "request-notice error"}
role="status"
>
{success && <Check size={17} />}
<div>
<strong>
{value === "approved"
? "Request approved"
: value === "pending"
? "Request sent"
: "Request could not be sent"}
</strong>
<p>
{success
? "Jellyseerr is taking it from here."
: value === "forbidden"
? "Your Jellyseerr permissions do not allow this request."
: "Check your quota or try again in a moment."}
</p>
</div>
</div>
);
}
function MediaCard({
item,
canRequest,
}: {
item: DiscoveryItem;
canRequest: boolean;
}) {
const available = item.availability === 5;
const alreadyRequested =
item.availability !== null && item.availability >= 2 && !available;
const Icon = item.mediaType === "movie" ? Film : Tv;
return (
<article className="media-card">
<div className="media-poster">
{item.posterPath ? (
<Image
src={`/api/artwork?path=${encodeURIComponent(item.posterPath)}`}
alt=""
fill
sizes="(max-width: 560px) 44vw, 220px"
/>
) : (
<span>
<Icon size={32} />
</span>
)}
<span className="media-kind">
<Icon size={12} /> {item.mediaType}
</span>
</div>
<div className="media-card-copy">
<div className="media-title">
<strong>{item.title}</strong>
<span>{item.year ?? "—"}</span>
</div>
{item.rating !== null && (
<span className="media-rating">
<Star size={12} fill="currentColor" /> {item.rating.toFixed(1)}
</span>
)}
<p>{item.overview || "No overview available."}</p>
{available ? (
<span className="availability available">
<Check size={14} /> Available
</span>
) : alreadyRequested ? (
<span className="availability processing">Already requested</span>
) : (
<form action={createMediaRequest}>
<input type="hidden" name="mediaId" value={item.id} />
<input type="hidden" name="mediaType" value={item.mediaType} />
<button
className="request-button"
type="submit"
disabled={!canRequest}
>
Request {item.mediaType}
</button>
</form>
)}
</div>
</article>
);
}
+392 -30
View File
@@ -98,39 +98,13 @@ button:disabled {
}
.brand-mark {
align-items: flex-end;
background: linear-gradient(145deg, #f18a61, #d55f3d);
border-radius: 11px;
box-shadow: 0 7px 22px rgba(215, 94, 57, 0.22);
display: flex;
gap: 2.5px;
height: 34px;
justify-content: center;
overflow: hidden;
padding: 8px 7px 7px;
transform: rotate(-3deg);
width: 34px;
}
.brand-mark span {
background: #18100c;
border-radius: 2px 2px 1px 1px;
display: block;
width: 4px;
}
.brand-mark span:first-child {
height: 45%;
}
.brand-mark span:nth-child(2) {
height: 72%;
}
.brand-mark span:last-child {
height: 100%;
}
.brand-wordmark {
font-size: 20px;
font-weight: 760;
@@ -693,6 +667,21 @@ h3 {
border: 1px solid rgba(229, 183, 104, 0.2);
}
.connected-banner {
background: rgba(120, 212, 159, 0.07);
border-color: rgba(120, 212, 159, 0.18);
}
.connected-banner .banner-dot {
background: var(--green);
box-shadow: 0 0 0 4px rgba(120, 212, 159, 0.1);
}
.connected-banner a {
color: var(--green);
font-weight: 700;
}
.banner-dot {
background: var(--warning);
border-radius: 50%;
@@ -834,6 +823,30 @@ h3 {
background: rgba(73, 121, 214, 0.13);
color: #759ee8;
}
.service-jellyseerr {
background: rgba(137, 105, 224, 0.13);
color: #b29af0;
}
.service-lidarr {
background: rgba(78, 184, 154, 0.13);
color: #74cdb4;
}
.service-cleanuparr {
background: rgba(218, 98, 146, 0.13);
color: #e78fb1;
}
.service-unmanic {
background: rgba(239, 137, 74, 0.13);
color: #f0a276;
}
.service-flaresolverr {
background: rgba(230, 146, 49, 0.13);
color: #ecad63;
}
.service-jfa {
background: rgba(154, 117, 210, 0.13);
color: #bea0e7;
}
.service-copy {
min-width: 0;
@@ -1026,12 +1039,18 @@ h3 {
text-align: center;
}
.signin-wrap {
.signin-layout {
display: grid;
gap: 18px;
margin: 0 auto;
max-width: 1080px;
}
.signin-panel {
display: flex;
flex-direction: column;
gap: 24px;
margin: 5vh auto 0;
max-width: 720px;
gap: 22px;
padding: 9px 0;
}
.signin-heading {
@@ -1043,6 +1062,322 @@ h3 {
margin-bottom: 0;
}
.jellyfin-form {
display: flex;
flex-direction: column;
max-width: 470px;
}
.field-label {
color: #cbd0cb;
font-size: 11px;
font-weight: 700;
margin: 0 0 7px 2px;
}
.field-label:not(:first-child) {
margin-top: 15px;
}
.input-shell {
align-items: center;
background: var(--surface);
border: 1px solid var(--line-strong);
border-radius: 13px;
display: flex;
min-height: 51px;
padding: 0 13px;
transition:
border-color 160ms ease,
box-shadow 160ms ease;
}
.input-shell:focus-within {
border-color: rgba(244, 161, 129, 0.65);
box-shadow: 0 0 0 3px rgba(232, 121, 81, 0.09);
}
.input-shell > svg {
color: var(--faint);
flex: 0 0 auto;
}
.input-shell input {
background: transparent;
border: 0;
color: var(--ink);
flex: 1;
min-width: 0;
outline: 0;
padding: 0 12px;
}
.password-toggle {
align-items: center;
background: transparent;
border: 0;
color: var(--faint);
cursor: pointer;
display: flex;
height: 42px;
justify-content: center;
width: 38px;
}
.form-error {
color: var(--danger);
font-size: 11px;
margin: 10px 2px 0;
}
.signin-button {
margin-top: 18px;
width: 100%;
}
.credential-note {
color: var(--faint);
font-size: 10px;
margin: 9px 3px 0;
text-align: center;
}
.spin {
animation: spin 900ms linear infinite;
}
@keyframes spin {
to {
transform: rotate(360deg);
}
}
.signin-art {
border: 1px solid rgba(193, 224, 204, 0.12);
border-radius: var(--radius-lg);
min-height: 340px;
overflow: hidden;
position: relative;
}
.signin-art > img {
object-fit: cover;
}
.signin-art::after {
background: linear-gradient(0deg, rgba(8, 12, 10, 0.82), transparent 47%);
content: "";
inset: 0;
position: absolute;
}
.signin-art-copy {
bottom: 23px;
display: flex;
flex-direction: column;
left: 23px;
max-width: 310px;
position: absolute;
right: 23px;
z-index: 2;
}
.signin-art-copy span {
color: #a9cdb6;
font-size: 10px;
font-weight: 800;
letter-spacing: 0.13em;
margin-bottom: 7px;
text-transform: uppercase;
}
.signin-art-copy strong {
font-size: 20px;
letter-spacing: -0.025em;
line-height: 1.2;
}
.dev-access {
border-top: 1px solid var(--line);
padding-top: 18px;
}
.dev-access summary {
color: var(--faint);
cursor: pointer;
font-size: 11px;
margin-bottom: 13px;
}
.request-notice {
align-items: flex-start;
border: 1px solid;
border-radius: 15px;
display: flex;
gap: 10px;
padding: 13px 15px;
}
.request-notice.success {
background: rgba(120, 212, 159, 0.07);
border-color: rgba(120, 212, 159, 0.2);
color: var(--green);
}
.request-notice.error {
background: rgba(238, 132, 123, 0.07);
border-color: rgba(238, 132, 123, 0.2);
color: var(--danger);
}
.request-notice strong {
display: block;
font-size: 12px;
}
.request-notice p {
color: var(--muted);
font-size: 11px;
margin-bottom: 0;
}
.media-grid {
display: grid;
gap: 13px;
grid-template-columns: repeat(2, minmax(0, 1fr));
}
.media-card {
background: var(--surface);
border: 1px solid var(--line);
border-radius: 16px;
min-width: 0;
overflow: hidden;
transition:
border-color 160ms ease,
transform 160ms ease;
}
.media-card:hover {
border-color: var(--line-strong);
transform: translateY(-2px);
}
.media-poster {
aspect-ratio: 2 / 3;
background: linear-gradient(145deg, #28352f, #18201c);
overflow: hidden;
position: relative;
}
.media-poster > img {
object-fit: cover;
}
.media-poster > span:not(.media-kind) {
align-items: center;
color: var(--faint);
display: flex;
height: 100%;
justify-content: center;
}
.media-kind {
align-items: center;
backdrop-filter: blur(10px);
background: rgba(9, 13, 11, 0.7);
border: 1px solid rgba(255, 255, 255, 0.1);
border-radius: 99px;
bottom: 8px;
display: flex;
font-size: 8px;
font-weight: 760;
gap: 4px;
left: 8px;
padding: 4px 7px;
position: absolute;
text-transform: capitalize;
}
.media-card-copy {
padding: 11px;
}
.media-title {
align-items: baseline;
display: flex;
gap: 6px;
justify-content: space-between;
}
.media-title strong {
display: -webkit-box;
font-size: 12px;
line-height: 1.25;
overflow: hidden;
-webkit-box-orient: vertical;
-webkit-line-clamp: 2;
}
.media-title span {
color: var(--faint);
flex: 0 0 auto;
font-size: 9px;
}
.media-rating {
align-items: center;
color: var(--warning);
display: flex;
font-size: 9px;
gap: 3px;
margin-top: 5px;
}
.media-card-copy > p {
color: var(--faint);
display: -webkit-box;
font-size: 9px;
line-height: 1.45;
margin: 7px 0 10px;
overflow: hidden;
-webkit-box-orient: vertical;
-webkit-line-clamp: 3;
}
.request-button,
.availability {
align-items: center;
border-radius: 9px;
display: flex;
font-size: 9px;
font-weight: 740;
justify-content: center;
min-height: 34px;
width: 100%;
}
.request-button {
background: rgba(232, 121, 81, 0.12);
border: 1px solid rgba(232, 121, 81, 0.28);
color: var(--accent-light);
cursor: pointer;
}
.availability {
gap: 5px;
}
.availability.available {
background: rgba(120, 212, 159, 0.08);
color: var(--green);
}
.availability.processing {
background: rgba(114, 184, 215, 0.08);
color: var(--blue);
}
.role-grid {
display: grid;
gap: 10px;
@@ -1141,6 +1476,10 @@ h3 {
grid-template-columns: 1fr 1fr;
}
.media-grid {
grid-template-columns: repeat(3, minmax(0, 1fr));
}
.settings-tag {
display: inline;
}
@@ -1277,6 +1616,25 @@ h3 {
.empty-state {
min-height: 300px;
}
.signin-layout {
align-items: stretch;
grid-template-columns: minmax(320px, 0.85fr) minmax(390px, 1.15fr);
min-height: 650px;
}
.signin-panel {
justify-content: center;
padding: 28px 22px 28px 0;
}
.signin-art {
min-height: 650px;
}
.dev-access {
grid-column: 1 / -1;
}
}
@media (min-width: 1120px) {
@@ -1293,6 +1651,10 @@ h3 {
grid-template-columns: repeat(3, 1fr);
}
.media-grid {
grid-template-columns: repeat(4, minmax(0, 1fr));
}
.discover-hero {
min-height: 365px;
}
+8
View File
@@ -0,0 +1,8 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64">
<rect x="5" y="5" width="54" height="54" rx="17" fill="#F07D57"/>
<path d="M16 36.5C16 28.49 22.49 22 30.5 22h14" fill="none" stroke="#20130F" stroke-width="4" stroke-linecap="round" opacity=".25"/>
<rect x="18" y="32" width="6" height="14" rx="3" fill="#20130F"/>
<rect x="29" y="24" width="6" height="22" rx="3" fill="#20130F"/>
<rect x="40" y="16" width="6" height="30" rx="3" fill="#20130F"/>
<circle cx="18" cy="23" r="3" fill="#FFF7F2"/>
</svg>

After

Width:  |  Height:  |  Size: 524 B

+8
View File
@@ -7,12 +7,20 @@ import { getViewer } from "@/server/auth/session";
import "./globals.css";
export const metadata: Metadata = {
metadataBase: new URL(
process.env.NEXT_PUBLIC_APP_URL ?? "http://localhost:3000",
),
title: {
default: "Arrmate",
template: "%s · Arrmate",
},
description: "The friendly control plane for your self-hosted media stack.",
applicationName: "Arrmate",
openGraph: {
title: "Arrmate",
description: "Your media stack, finally in one place.",
images: [{ url: "/assets/arrmate-social.png", width: 1200, height: 630 }],
},
};
export const viewport: Viewport = {
+30
View File
@@ -0,0 +1,30 @@
import type { MetadataRoute } from "next";
export default function manifest(): MetadataRoute.Manifest {
return {
name: "Arrmate",
short_name: "Arrmate",
description: "The friendly control plane for your self-hosted media stack.",
start_url: "/",
display: "standalone",
background_color: "#0d1110",
theme_color: "#0d1110",
icons: [
{
src: "/assets/arrmate-icon-192.png",
sizes: "192x192",
type: "image/png",
},
{
src: "/assets/arrmate-icon-512.png",
sizes: "512x512",
type: "image/png",
},
{
src: "/assets/arrmate-mark.svg",
sizes: "any",
type: "image/svg+xml",
},
],
};
}
+27 -5
View File
@@ -11,13 +11,22 @@ import Link from "next/link";
import { EmptyState } from "@/components/empty-state";
import { can } from "@/domain/auth";
import { getViewer } from "@/server/auth/session";
import type { SeerrQuotaWindow } from "@/domain/discovery";
import { getProviderSession, getViewer } from "@/server/auth/session";
import { jellyseerrFromEnvironment } from "@/server/integrations/jellyseerr";
export const dynamic = "force-dynamic";
export default async function HomePage() {
const viewer = await getViewer();
const isOperator = can(viewer, "operations:view");
const session = await getProviderSession();
const adapter = jellyseerrFromEnvironment();
const quotaResult =
session && adapter
? await adapter.quota(session.user.id, session.upstreamCookie)
: null;
const quota = quotaResult?.ok ? quotaResult.data : null;
return (
<div className="page-stack">
@@ -75,8 +84,10 @@ export default async function HomePage() {
</span>
<div>
<span>Movie requests</span>
<strong>—</strong>
<small>Limit loads after setup</small>
<strong>{quota ? quotaValue(quota.movie) : "—"}</strong>
<small>
{quota ? quotaCaption(quota.movie) : "Sign in to see your limit"}
</small>
</div>
</article>
<article className="quota-card">
@@ -85,8 +96,10 @@ export default async function HomePage() {
</span>
<div>
<span>Series requests</span>
<strong>—</strong>
<small>Limit loads after setup</small>
<strong>{quota ? quotaValue(quota.series) : "—"}</strong>
<small>
{quota ? quotaCaption(quota.series) : "Sign in to see your limit"}
</small>
</div>
</article>
</section>
@@ -117,3 +130,12 @@ export default async function HomePage() {
</div>
);
}
function quotaValue(quota: SeerrQuotaWindow): string {
return quota.limit ? String(quota.remaining ?? 0) : "∞";
}
function quotaCaption(quota: SeerrQuotaWindow): string {
if (!quota.limit) return "No request limit";
return `${quota.used} of ${quota.limit} used${quota.days ? ` · ${quota.days}d window` : ""}`;
}
+2 -2
View File
@@ -35,8 +35,8 @@ const settings = [
{
icon: KeyRound,
title: "Authentication",
copy: "Replace local sign-in with your identity provider",
tag: "Local development",
copy: "Jellyfin credentials via Jellyseerr",
tag: "Server-side session",
},
];
+55 -42
View File
@@ -1,10 +1,13 @@
import { HardHat, LockKeyhole, UserRound, UsersRound } from "lucide-react";
import Image from "next/image";
import Link from "next/link";
import { developmentSignIn } from "@/app/actions";
import { JellyfinSignInForm } from "@/components/jellyfin-sign-in-form";
import { developmentAuthEnabled } from "@/server/auth/session";
import { jellyseerrFromEnvironment } from "@/server/integrations/jellyseerr";
export const metadata = { title: "Local sign in" };
export const metadata = { title: "Sign in" };
const options = [
{
@@ -35,50 +38,60 @@ const options = [
export default function SignInPage() {
const enabled = developmentAuthEnabled();
const configured = jellyseerrFromEnvironment() !== null;
return (
<div className="signin-wrap">
<div className="signin-heading">
<p className="eyebrow">Local development</p>
<h1>Choose a view</h1>
<p>
Switch roles to verify Arrmate’s permission boundaries. This is not a
production identity provider.
</p>
</div>
{enabled ? (
<form className="role-grid" action={developmentSignIn}>
{options.map(({ role, label, copy, icon: Icon }) => (
<button
type="submit"
name="role"
value={role}
className="role-option"
key={role}
>
<span className="role-icon">
<Icon size={20} />
</span>
<span>
<strong>{label}</strong>
<small>{copy}</small>
</span>
</button>
))}
</form>
) : (
<div className="security-banner">
<LockKeyhole size={20} />
<div>
<strong>Local sign-in is disabled</strong>
<p>
Configure a production identity provider before granting access.
</p>
</div>
<div className="signin-layout">
<section className="signin-panel">
<div className="signin-heading">
<p className="eyebrow">One account. Your whole library.</p>
<h1>Welcome to Arrmate.</h1>
<p>Use the same credentials you already use to watch on Jellyfin.</p>
</div>
<JellyfinSignInForm configured={configured} />
<Link className="text-link" href="/">
Continue as guest
</Link>
</section>
<aside
className="signin-art"
aria-label="Arrmate media library illustration"
>
<Image
src="/assets/arrmate-orbit.svg"
alt=""
fill
priority
sizes="(min-width: 900px) 50vw, 100vw"
/>
<div className="signin-art-copy">
<span>Private by design</span>
<strong>Your media. Your rules. One beautifully calm place.</strong>
</div>
</aside>
{enabled && (
<details className="dev-access" open>
<summary>Development role switcher</summary>
<form className="role-grid" action={developmentSignIn}>
{options.map(({ role, label, copy, icon: Icon }) => (
<button
type="submit"
name="role"
value={role}
className="role-option"
key={role}
>
<span className="role-icon">
<Icon size={20} />
</span>
<span>
<strong>{label}</strong>
<small>{copy}</small>
</span>
</button>
))}
</form>
</details>
)}
<Link className="text-link" href="/">
Continue as guest
</Link>
</div>
);
}
+9 -5
View File
@@ -1,13 +1,17 @@
import Image from "next/image";
import Link from "next/link";
export function Brand({ compact = false }: { compact?: boolean }) {
return (
<Link className="brand" href="/" aria-label="Arrmate home">
<span className="brand-mark" aria-hidden="true">
<span />
<span />
<span />
</span>
<Image
className="brand-mark"
src="/assets/arrmate-mark.svg"
alt=""
width={34}
height={34}
priority
/>
{!compact && (
<span className="brand-wordmark">
Arr<span>mate</span>
+83
View File
@@ -0,0 +1,83 @@
"use client";
import {
Eye,
EyeOff,
LoaderCircle,
LockKeyhole,
UserRound,
} from "lucide-react";
import { useActionState, useState } from "react";
import { jellyfinSignIn } from "@/app/actions";
export function JellyfinSignInForm({ configured }: { configured: boolean }) {
const [state, action, pending] = useActionState(jellyfinSignIn, {});
const [showPassword, setShowPassword] = useState(false);
return (
<form className="jellyfin-form" action={action}>
<label className="field-label" htmlFor="username">
Jellyfin username
</label>
<div className="input-shell">
<UserRound size={18} aria-hidden="true" />
<input
id="username"
name="username"
autoComplete="username"
required
disabled={!configured || pending}
/>
</div>
<label className="field-label" htmlFor="password">
Password
</label>
<div className="input-shell">
<LockKeyhole size={18} aria-hidden="true" />
<input
id="password"
name="password"
type={showPassword ? "text" : "password"}
autoComplete="current-password"
required
disabled={!configured || pending}
/>
<button
className="password-toggle"
type="button"
onClick={() => setShowPassword((value) => !value)}
aria-label={showPassword ? "Hide password" : "Show password"}
disabled={!configured || pending}
>
{showPassword ? <EyeOff size={17} /> : <Eye size={17} />}
</button>
</div>
{state.error && (
<p className="form-error" role="alert">
{state.error}
</p>
)}
{!configured && (
<p className="form-error" role="status">
The server owner still needs to configure Jellyseerr.
</p>
)}
<button
className="primary-button signin-button"
type="submit"
disabled={!configured || pending}
>
{pending ? (
<LoaderCircle className="spin" size={18} />
) : (
<LockKeyhole size={17} />
)}
{pending ? "Signing in…" : "Sign in with Jellyfin"}
</button>
<p className="credential-note">
Arrmate exchanges these credentials once. Your password is never stored.
</p>
</form>
);
}
+45
View File
@@ -0,0 +1,45 @@
export type DiscoveryMediaType = "movie" | "series";
export interface DiscoveryItem {
id: number;
mediaType: DiscoveryMediaType;
title: string;
overview: string;
year: string | null;
posterPath: string | null;
backdropPath: string | null;
rating: number | null;
availability: number | null;
}
export interface DiscoveryPage {
page: number;
totalPages: number;
totalResults: number;
items: DiscoveryItem[];
}
export interface SeerrUser {
id: number;
displayName: string;
permissions: number;
avatarPath: string | null;
}
export interface SeerrQuotaWindow {
days: number | null;
limit: number | null;
used: number;
remaining: number | null;
restricted: boolean;
}
export interface SeerrQuota {
movie: SeerrQuotaWindow;
series: SeerrQuotaWindow;
}
export interface SeerrRequestReceipt {
id: number;
status: "pending" | "approved" | "declined" | "unknown";
}
+4
View File
@@ -5,6 +5,10 @@ export const integrationKinds = [
"subtitle-provider",
"request-manager",
"download-client",
"maintenance",
"transcoder",
"access",
"indexer-helper",
] as const;
export type IntegrationKind = (typeof integrationKinds)[number];
+29
View File
@@ -0,0 +1,29 @@
import { describe, expect, it } from "vitest";
import {
canRequestThroughSeerr,
roleFromSeerrPermissions,
SeerrPermission,
} from "./seerr-permissions";
describe("Jellyseerr permission mapping", () => {
it("maps upstream admin and management permissions to Arrmate roles", () => {
expect(roleFromSeerrPermissions(SeerrPermission.ADMIN)).toBe("owner");
expect(roleFromSeerrPermissions(SeerrPermission.MANAGE_REQUESTS)).toBe(
"maintainer",
);
expect(roleFromSeerrPermissions(SeerrPermission.REQUEST)).toBe("requester");
});
it("keeps movie and series request permissions distinct", () => {
expect(canRequestThroughSeerr(SeerrPermission.REQUEST_MOVIE, "movie")).toBe(
true,
);
expect(
canRequestThroughSeerr(SeerrPermission.REQUEST_MOVIE, "series"),
).toBe(false);
expect(canRequestThroughSeerr(SeerrPermission.REQUEST, "series")).toBe(
true,
);
});
});
+43
View File
@@ -0,0 +1,43 @@
import type { Role } from "./auth";
import type { DiscoveryMediaType } from "./discovery";
export const SeerrPermission = {
ADMIN: 2,
MANAGE_SETTINGS: 4,
MANAGE_USERS: 8,
MANAGE_REQUESTS: 16,
REQUEST: 32,
REQUEST_MOVIE: 262_144,
REQUEST_TV: 524_288,
} as const;
export function hasSeerrPermission(value: number, permission: number): boolean {
return Boolean(value & SeerrPermission.ADMIN) || Boolean(value & permission);
}
export function roleFromSeerrPermissions(permissions: number): Role {
if (hasSeerrPermission(permissions, SeerrPermission.ADMIN)) return "owner";
if (
hasSeerrPermission(permissions, SeerrPermission.MANAGE_SETTINGS) ||
hasSeerrPermission(permissions, SeerrPermission.MANAGE_USERS) ||
hasSeerrPermission(permissions, SeerrPermission.MANAGE_REQUESTS)
) {
return "maintainer";
}
return "requester";
}
export function canRequestThroughSeerr(
permissions: number,
mediaType: DiscoveryMediaType,
): boolean {
return (
hasSeerrPermission(permissions, SeerrPermission.REQUEST) ||
hasSeerrPermission(
permissions,
mediaType === "movie"
? SeerrPermission.REQUEST_MOVIE
: SeerrPermission.REQUEST_TV,
)
);
}
+23
View File
@@ -0,0 +1,23 @@
import { describe, expect, it } from "vitest";
import { sealSession, unsealSession } from "./session-crypto";
describe("encrypted session envelope", () => {
const secret = "a-test-only-secret-that-is-long-enough";
it("round trips a provider session without exposing plaintext", () => {
const value = { userId: 7, upstreamCookie: "connect.sid=test-value" };
const sealed = sealSession(value, secret);
expect(sealed).not.toContain("connect.sid");
expect(unsealSession(sealed, secret)).toEqual(value);
});
it("rejects tampering and the wrong key", () => {
const sealed = sealSession({ userId: 7 }, secret);
const segments = sealed.split(".");
segments[2] = `${segments[2].startsWith("a") ? "b" : "a"}${segments[2].slice(1)}`;
const tampered = segments.join(".");
expect(unsealSession(tampered, secret)).toBeNull();
expect(unsealSession(sealed, "another-test-only-secret-value")).toBeNull();
});
});
+48
View File
@@ -0,0 +1,48 @@
import {
createCipheriv,
createDecipheriv,
createHash,
randomBytes,
} from "node:crypto";
function encryptionKey(secret: string): Buffer {
return createHash("sha256")
.update("arrmate:session:v1")
.update(secret)
.digest();
}
export function sealSession(value: unknown, secret: string): string {
const iv = randomBytes(12);
const cipher = createCipheriv("aes-256-gcm", encryptionKey(secret), iv);
const encrypted = Buffer.concat([
cipher.update(JSON.stringify(value), "utf8"),
cipher.final(),
]);
return [
"v1",
iv.toString("base64url"),
encrypted.toString("base64url"),
cipher.getAuthTag().toString("base64url"),
].join(".");
}
export function unsealSession(value: string, secret: string): unknown | null {
const [version, ivValue, encryptedValue, tagValue] = value.split(".");
if (version !== "v1" || !ivValue || !encryptedValue || !tagValue) return null;
try {
const decipher = createDecipheriv(
"aes-256-gcm",
encryptionKey(secret),
Buffer.from(ivValue, "base64url"),
);
decipher.setAuthTag(Buffer.from(tagValue, "base64url"));
const decrypted = Buffer.concat([
decipher.update(Buffer.from(encryptedValue, "base64url")),
decipher.final(),
]);
return JSON.parse(decrypted.toString("utf8")) as unknown;
} catch {
return null;
}
}
+79 -7
View File
@@ -3,11 +3,33 @@ import "server-only";
import { createHmac, timingSafeEqual } from "node:crypto";
import { cookies } from "next/headers";
import { z } from "zod";
import type { Role, Viewer } from "@/domain/auth";
import { roles } from "@/domain/auth";
import type { JellyseerrLogin } from "@/adapters/jellyseerr";
import { roleFromSeerrPermissions } from "@/domain/seerr-permissions";
const COOKIE_NAME = "arrmate-dev-session";
import { sealSession, unsealSession } from "./session-crypto";
const DEV_COOKIE_NAME = "arrmate-dev-session";
const SESSION_COOKIE_NAME = "arrmate-session";
const SESSION_SECONDS = 60 * 60 * 12;
const providerSessionSchema = z.object({
version: z.literal(1),
provider: z.literal("jellyseerr"),
user: z.object({
id: z.number().int().positive(),
displayName: z.string().min(1),
permissions: z.number().int().nonnegative(),
avatarPath: z.string().nullable(),
}),
upstreamCookie: z.string().startsWith("connect.sid="),
expiresAt: z.number().int().positive(),
});
export type ProviderSession = z.infer<typeof providerSessionSchema>;
const developmentViewers: Record<Role, Viewer> = {
owner: {
@@ -34,10 +56,16 @@ const developmentViewers: Record<Role, Viewer> = {
function key(): string {
const configured = process.env.AUTH_SECRET;
if (configured) return configured;
if (
configured &&
configured.length >= 32 &&
!configured.startsWith("replace-with")
) {
return configured;
}
if (process.env.NODE_ENV !== "production")
return "arrmate-development-only-session-key";
throw new Error("AUTH_SECRET is required in production");
throw new Error("A strong AUTH_SECRET is required in production");
}
function signature(payload: string): string {
@@ -81,23 +109,67 @@ export function developmentAuthEnabled(): boolean {
}
export async function getViewer(): Promise<Viewer> {
const token = (await cookies()).get(COOKIE_NAME)?.value;
const providerSession = await getProviderSession();
if (providerSession) {
return {
id: `jellyseerr:${providerSession.user.id}`,
name: providerSession.user.displayName,
role: roleFromSeerrPermissions(providerSession.user.permissions),
};
}
const token = (await cookies()).get(DEV_COOKIE_NAME)?.value;
const role = token ? decode(token) : null;
return developmentViewers[role ?? "guest"];
}
export async function getProviderSession(): Promise<ProviderSession | null> {
const token = (await cookies()).get(SESSION_COOKIE_NAME)?.value;
if (!token) return null;
const parsed = providerSessionSchema.safeParse(unsealSession(token, key()));
if (!parsed.success || parsed.data.expiresAt <= Date.now()) return null;
return parsed.data;
}
export async function setProviderSession(
login: JellyseerrLogin,
): Promise<void> {
const expiresAt = Date.now() + SESSION_SECONDS * 1_000;
const value: ProviderSession = {
version: 1,
provider: "jellyseerr",
user: login.user,
upstreamCookie: login.sessionCookie,
expiresAt,
};
const cookieStore = await cookies();
cookieStore.set(SESSION_COOKIE_NAME, sealSession(value, key()), {
httpOnly: true,
sameSite: "lax",
secure: process.env.NODE_ENV === "production",
path: "/",
maxAge: SESSION_SECONDS,
priority: "high",
});
cookieStore.delete(DEV_COOKIE_NAME);
}
export async function setDevelopmentViewer(role: Role): Promise<void> {
if (!developmentAuthEnabled())
throw new Error("Development sign-in is disabled");
(await cookies()).set(COOKIE_NAME, encode(role), {
const cookieStore = await cookies();
cookieStore.set(DEV_COOKIE_NAME, encode(role), {
httpOnly: true,
sameSite: "lax",
secure: process.env.NODE_ENV === "production",
path: "/",
maxAge: 60 * 60 * 12,
});
cookieStore.delete(SESSION_COOKIE_NAME);
}
export async function clearDevelopmentViewer(): Promise<void> {
(await cookies()).delete(COOKIE_NAME);
export async function clearSessions(): Promise<void> {
const cookieStore = await cookies();
cookieStore.delete(DEV_COOKIE_NAME);
cookieStore.delete(SESSION_COOKIE_NAME);
}
+16
View File
@@ -0,0 +1,16 @@
import "server-only";
import { JellyseerrAdapter } from "@/adapters/jellyseerr";
export function jellyseerrFromEnvironment(): JellyseerrAdapter | null {
const baseUrl = process.env.SEERR_URL;
if (!baseUrl) return null;
const parsedTimeout = Number(process.env.INTEGRATION_REQUEST_TIMEOUT_MS);
return new JellyseerrAdapter({
baseUrl,
timeoutMs:
Number.isFinite(parsedTimeout) && parsedTimeout > 0
? parsedTimeout
: 8_000,
});
}
+100 -47
View File
@@ -3,6 +3,7 @@ import "server-only";
import type { DownloadOverview } from "@/domain/downloads";
import type { AdapterError, IntegrationSummary } from "@/domain/integrations";
import { jellyseerrFromEnvironment } from "./integrations/jellyseerr";
import { qBittorrentFromEnvironment } from "./integrations/qbittorrent";
export interface OperationsSnapshot {
@@ -47,37 +48,64 @@ const plannedIntegrations: IntegrationSummary[] = [
health: "not-configured",
detail: "Subtitle provider is not configured",
},
{
id: "lidarr",
name: "Lidarr",
kind: "media-manager",
health: "not-configured",
detail: "Music manager adapter is not configured",
},
{
id: "cleanuparr",
name: "Cleanuparr",
kind: "maintenance",
health: "not-configured",
detail: "Queue maintenance adapter is not configured",
},
{
id: "unmanic",
name: "Unmanic",
kind: "transcoder",
health: "not-configured",
detail: "Transcoding adapter is not configured",
},
{
id: "flaresolverr",
name: "FlareSolverr",
kind: "indexer-helper",
health: "not-configured",
detail: "Indexer helper adapter is not configured",
},
{
id: "jfa",
name: "JFA",
kind: "access",
health: "not-configured",
detail: "Account helper adapter is not configured",
},
];
export async function getOperationsSnapshot(): Promise<OperationsSnapshot> {
const adapter = qBittorrentFromEnvironment();
if (!adapter) {
return {
integrations: [
...plannedIntegrations,
{
id: "qbittorrent",
name: "qBittorrent",
kind: "download-client",
health: "not-configured",
detail: "Download client connection is not configured",
},
],
downloads: null,
downloadError: null,
};
}
const startedAt = performance.now();
const overview = await adapter.overview();
const qBittorrent = qBittorrentFromEnvironment();
const jellyseerr = jellyseerrFromEnvironment();
const qStartedAt = performance.now();
const seerrStartedAt = performance.now();
const [overview, seerrHealth] = await Promise.all([
qBittorrent ? qBittorrent.overview() : null,
jellyseerr ? jellyseerr.health() : null,
]);
const checkedAt = new Date();
const latencyMs = Math.round(performance.now() - startedAt);
if (!overview.ok) {
return {
integrations: [
...plannedIntegrations,
{
const qBittorrentSummary: IntegrationSummary = !qBittorrent
? {
id: "qbittorrent",
name: "qBittorrent",
kind: "download-client",
health: "not-configured",
detail: "Download client connection is not configured",
}
: overview && !overview.ok
? {
id: "qbittorrent",
name: "qBittorrent",
kind: "download-client",
@@ -85,31 +113,56 @@ export async function getOperationsSnapshot(): Promise<OperationsSnapshot> {
overview.error.code === "authentication" ? "offline" : "degraded",
detail: overview.error.message,
checkedAt,
latencyMs,
},
],
downloads: null,
downloadError: overview.error,
};
}
latencyMs: Math.round(performance.now() - qStartedAt),
}
: {
id: "qbittorrent",
name: "qBittorrent",
kind: "download-client",
health: "online",
detail:
overview && overview.ok && overview.data.items.length > 0
? `Connected · ${overview.data.items.length} active item${overview.data.items.length === 1 ? "" : "s"}`
: "Connected · queue is empty",
checkedAt,
latencyMs: Math.round(performance.now() - qStartedAt),
};
const jellyseerrSummary: IntegrationSummary = !jellyseerr
? {
id: "jellyseerr",
name: "Jellyseerr",
kind: "request-manager",
health: "not-configured",
detail: "Discovery and requests are not configured",
}
: seerrHealth && !seerrHealth.ok
? {
id: "jellyseerr",
name: "Jellyseerr",
kind: "request-manager",
health: "degraded",
detail: seerrHealth.error.message,
checkedAt,
latencyMs: Math.round(performance.now() - seerrStartedAt),
}
: {
id: "jellyseerr",
name: "Jellyseerr",
kind: "request-manager",
health: "online",
detail: "Discovery, sign-in, and requests are ready",
checkedAt,
latencyMs: seerrHealth?.ok ? seerrHealth.data.latencyMs : undefined,
};
return {
integrations: [
...plannedIntegrations,
{
id: "qbittorrent",
name: "qBittorrent",
kind: "download-client",
health: "online",
detail:
overview.data.items.length === 0
? "Connected · queue is empty"
: `Connected · ${overview.data.items.length} active item${overview.data.items.length === 1 ? "" : "s"}`,
checkedAt,
latencyMs,
},
jellyseerrSummary,
qBittorrentSummary,
],
downloads: overview.data,
downloadError: null,
downloads: overview?.ok ? overview.data : null,
downloadError: overview && !overview.ok ? overview.error : null,
};
}
+22
View File
@@ -25,6 +25,26 @@ test("mobile layout does not overflow horizontally", async ({ page }) => {
).toBeVisible();
});
test("sign-in uses Jellyfin identity and is honest when unconfigured", async ({
page,
}) => {
await page.goto("/sign-in");
await expect(
page.getByRole("heading", { name: "Welcome to Arrmate." }),
).toBeVisible();
await expect(
page.getByRole("link", { name: "Arrmate home" }).first(),
).toBeVisible();
await expect(page.getByLabel("Jellyfin username")).toBeDisabled();
await expect(page.getByLabel("Password", { exact: true })).toBeDisabled();
await expect(
page.getByRole("button", { name: "Sign in with Jellyfin" }),
).toBeDisabled();
await expect(
page.getByText("The server owner still needs to configure Jellyseerr."),
).toBeVisible();
});
test("local owner session can open honest operations state", async ({
page,
}) => {
@@ -34,4 +54,6 @@ test("local owner session can open honest operations state", async ({
await expect(page.getByRole("heading", { name: "Operations" })).toBeVisible();
await expect(page.getByText("qBittorrent is not connected")).toBeVisible();
await expect(page.getByText("Not connected").first()).toBeVisible();
await expect(page.getByText("Jellyseerr", { exact: true })).toBeVisible();
await expect(page.getByText("Lidarr", { exact: true })).toBeVisible();
});