feat: ship Arrmate first vertical slice

This commit is contained in:
Zebratic committed 2026-08-16 03:01:44 +00:00
1 parent 38ef1ada0b
commit 103f9844ed
56 files changed
+13320 -26

No files matched your search

+4
View File
@@ -5,6 +5,10 @@ NODE_ENV=development
NEXT_PUBLIC_APP_URL=http://localhost:3000
DATABASE_URL=postgresql://arrmate:arrmate_dev_password@localhost:5432/arrmate
AUTH_SECRET=replace-with-a-long-random-development-secret
# Stable 32-byte base64 key shared by every Arrmate instance in a deployment.
NEXT_SERVER_ACTIONS_ENCRYPTION_KEY=replace-with-openssl-rand-base64-32-output
# Keep false in production. Local `next dev` enables the role switcher.
ARRMATE_ENABLE_DEV_AUTH=false
# Server-side integration settings. None of these are NEXT_PUBLIC_* values.
JELLYFIN_URL=http://localhost:8096
+6
View File
@@ -0,0 +1,6 @@
.next
coverage
node_modules
package-lock.json
playwright-report
test-results
+9
View File
@@ -0,0 +1,9 @@
<!-- BEGIN:nextjs-agent-rules -->
# This is NOT the Next.js you know
This version has breaking changes — APIs, conventions, and file structure may all differ from your training data. Read the relevant guide in `node_modules/next/dist/docs/` (resolved from this file's directory; in monorepos the `next` package may not be visible from the repo root) before writing any code. Heed deprecation notices.
This block is written and re-added by `next dev` — verify at `node_modules/next/dist/server/lib/generate-agent-files.js`. Removing it from a diff only re-creates the uncommitted change; committing it with your work keeps the tree clean.
<!-- END:nextjs-agent-rules -->
+1
View File
@@ -0,0 +1 @@
@AGENTS.md
+6 -1
View File
@@ -1,4 +1,9 @@
# Next coding-AI prompt: Arrmate foundation and first vertical slice
# Completed handoff: Arrmate foundation and first vertical slice
> This milestone was implemented and verified on 2026-08-16. It remains in
> the repository as the acceptance record for the first vertical slice; it is
> not the current next-step prompt. See `docs/plans/` and the README for the
> implemented state.
You are the implementation agent for **Arrmate**, an open-source, self-hosted, mobile-first media management control plane inspired by the unified feel of nzb360.
+32 -25
View File
@@ -2,13 +2,13 @@
**The friendly control plane for your self-hosted media stack.**
Arrmate is a planned 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.
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:** early project foundation. This repository currently contains product direction and the implementation handoff prompt. It is not yet connected to a live media stack and does not pretend otherwise.
> **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.
## The idea
The name comes from the *arr* family of services and a friendly companion that helps keep a homelab media setup moving. The product should feel like a polished native app on a phone, while remaining useful on tablets, desktop browsers, and eventually any device with a modern web browser.
The name comes from the _arr_ family of services and a friendly companion that helps keep a homelab media setup moving. The product should feel like a polished native app on a phone, while remaining useful on tablets, desktop browsers, and eventually any device with a modern web browser.
Arrmate is inspired by the unified feel of nzb360, but the goal is a self-hosted, open-source product with a first-class request experience rather than a basic launcher for separate services.
@@ -49,40 +49,35 @@ Arrmate should support at least these conceptual roles:
Every mutation should be authorized server-side. Hiding a button is not authorization.
## Suggested technical direction
## Technical foundation
The implementation handoff should validate the details, but the working direction is:
The current implementation uses:
- Next.js with TypeScript for the web application and API boundary.
- Tailwind CSS plus shadcn/ui primitives, with a custom Arrmate visual system rather than an untouched component template.
- 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.
- PostgreSQL for Arrmate-owned users, sessions, permissions, quotas, integrations, request records, audit events, and cached normalized state.
- A background job/refresh layer for polling and reconciling external services without blocking the UI.
- Typed adapter interfaces and capability checks so unsupported service features degrade gracefully.
- Docker-first local development with an explicit `.env.example` and no credentials in Git.
- Tests at the domain, adapter, authorization, and browser workflow boundaries.
- 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.
## Repository layout target
## Repository layout
```text
src/
app/ # routes and screens
components/ # reusable UI
features/ # vertical product slices
server/ # application services and adapter orchestration
adapters/ # external service integrations
db/ # schema, migrations, repositories
lib/ # shared utilities and typed contracts
styles/ # design tokens and global styles
docs/
product/ # product and UX decisions
architecture/ # system and adapter decisions
plans/ # implementation plans
public/
tests/
NEXT_PROMPT.md
```
This is a direction, not permission to build every future feature in the first milestone. The first implementation should establish a trustworthy vertical slice: authentication/roles, service connection health, a mobile dashboard, media search, a request, and a visible live download status.
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.
## Safety and privacy
@@ -96,19 +91,31 @@ Arrmate is intended for self-hosted deployments. Integrations will handle powerf
- avoid assuming that an internet-facing deployment is safe merely because the UI has a login page;
- provide a threat model and deployment security documentation before calling a release production-ready.
## Development
The implementation has not started yet. Read [`NEXT_PROMPT.md`](./NEXT_PROMPT.md) for the next coding-AI handoff. The handoff is deliberately designed to begin with repository inspection, product decisions, and a small verified vertical slice rather than generating a large untested scaffold.
When development begins, the expected local flow will be documented here and should include:
## Local development
```bash
cp .env.example .env
# install dependencies using the committed package manager
# start the local database and app
# run lint, typecheck, unit tests, and browser tests
npm install
cp .env.example .env.local
docker compose up -d postgres
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.
Before contributing, run:
```bash
npm run format:check
npm run lint
npm run typecheck
npm test
npm run test:browser
npm run build
```
Architecture, threat-model, product, and milestone decisions live under [`docs/`](./docs/).
## Contributing
Arrmate should be welcoming to homelab users who are not enterprise developers. Contributions need clear setup instructions, reproducible tests, security-minded review, and an explanation of how a change behaves when an external service is unavailable.
+20
View File
@@ -0,0 +1,20 @@
services:
postgres:
image: postgres:17-alpine
restart: unless-stopped
environment:
POSTGRES_DB: arrmate
POSTGRES_USER: arrmate
POSTGRES_PASSWORD: arrmate_dev_password
ports:
- "127.0.0.1:5432:5432"
volumes:
- arrmate-postgres:/var/lib/postgresql/data
healthcheck:
test: ["CMD-SHELL", "pg_isready -U arrmate -d arrmate"]
interval: 5s
timeout: 3s
retries: 10
volumes:
arrmate-postgres:
+54
View File
@@ -0,0 +1,54 @@
# Architecture foundation
## 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.
Browser code never talks to those services directly. A server-side adapter
authenticates upstream, validates responses, applies timeouts, and returns a
small normalized domain model. This prevents upstream API keys from entering a
browser bundle and stops UI components from depending on vendor response
shapes.
```text
browser -> Arrmate authorization -> application service -> typed adapter -> upstream
\-> PostgreSQL + audit events
```
An adapter returns a discriminated result. `not-configured`, authentication,
timeout, unreachable, malformed-response, and upstream failures remain
distinct from a successful empty response. The UI can therefore state that a
queue is empty only after a valid upstream response.
## First adapter
`QbittorrentAdapter` implements the read-only `DownloadClientAdapter`. It logs
in through qBittorrent Web API v2, keeps the session cookie server-side, reads
transfer and torrent information, validates both payloads with Zod, and maps
vendor states into Arrmate download states. Mutating capabilities are false in
this milestone.
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.
## Authorization
Roles map to explicit permissions in `src/domain/auth.ts`. Server actions and
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.
## Quotas and data
The PostgreSQL quota repository increments hourly and daily usage buckets with
conditional upserts inside one transaction. If any active bucket is full, the
transaction rolls back. This prevents straightforward concurrent requests from
oversubscribing a limit. The in-memory implementation exists only for isolated
domain tests and development.
+55
View File
@@ -0,0 +1,55 @@
# Initial threat model
## Assets
- Upstream API keys, usernames, passwords, and session cookies.
- Media library metadata and request history.
- Owner actions capable of deleting media or changing downloads.
- User roles, request limits, sessions, and audit evidence.
## Trust boundaries and mitigations
### Browser to Arrmate
Every mutation needs server-side permission enforcement. UI hiding is not a
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.
### Arrmate to upstream services
Credentials stay server-side and must be encrypted at rest before database
editing is enabled. Logs must redact headers, cookies, request bodies, and
configured URLs. Requests use deadlines and validated response shapes.
Operator-supplied integration URLs create SSRF risk. Only owners may configure
them. URLs are limited to HTTP(S), cannot embed credentials, and should be
resolved and checked against an operator-defined network allow-list before the
future editor is enabled. Redirects need the same validation. Private network
addresses cannot be prohibited by default because reaching homelab services is
the product's purpose.
### Destructive actions
Delete, replace, torrent removal, and library mutation are not implemented in
the first slice. They require an exact target summary, typed or otherwise
deliberate confirmation, a fresh authorization check, upstream outcome
handling, and an immutable audit event that records actor, target, and result.
### Public requests and quotas
Public discovery can leak library availability and viewing interests. Operators
need explicit exposure controls. Per-user quotas are enforced with conditional
database updates in a transaction. Network-level rate limits must additionally
protect anonymous searching, requests, and sign-in attempts.
## Deferred work before production
- Replace development sign-in with an OIDC or similarly mature identity 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.
- Add application and edge rate limits.
- Define URL/network allow-lists and redirect checks.
- Implement append-only audit persistence and retention.
- Add secure deployment, proxy, TLS, backup, and recovery guidance.
@@ -0,0 +1,44 @@
# First vertical slice
Date: 2026-08-16
## Outcome
Ship a runnable, mobile-first Arrmate foundation that is useful before every
integration exists. The application must tell the truth about disconnected
services, provide a safe local-development sign-in boundary, and prove one
real adapter path through qBittorrent.
## Milestones
1. Establish the Next.js, TypeScript, CSS, test, and PostgreSQL foundations.
2. Define roles, permissions, request quotas, audit events, integrations, and
normalized download state independently of any upstream service.
3. Implement a server-only qBittorrent adapter with response validation,
timeouts, redacted errors, and focused tests.
4. Build the phone-first requester and operations surfaces with honest live,
disconnected, loading, empty, and error states.
5. Verify formatting, lint, types, unit tests, browser workflows, and a
production build; document architecture, UX, and security decisions.
## Deliberate limits
- qBittorrent is read-only in this milestone. Pause, delete, recheck, and
manual-release mutations require audited confirmation flows in a later
slice.
- Discovery does not synthesize media. Until a discovery provider is
connected, the UI explains what is missing.
- Development sign-in is unavailable in production unless explicitly enabled.
- The database schema and atomic quota repository are included, but local
pages remain useful when PostgreSQL is not running.
- No production homelab endpoint or credential is used for tests or demos.
## Acceptance checks
- A 360px viewport has complete navigation and no horizontal overflow.
- Requester/guest sessions cannot call owner-only server actions.
- Quota reservation cannot exceed an active bucket under concurrent calls.
- qBittorrent reports authentication, timeout, malformed-response, empty, and
disconnected states distinctly.
- The default checkout starts without pretending any integration is online.
- The repository contains no secret, personal media metadata, or private URL.
+37
View File
@@ -0,0 +1,37 @@
# Mobile surfaces and permissions
## Navigation
Phones use four or fewer persistent bottom destinations. Requesters see Home,
Discover, and Activity. Operators gain Operations. Desktop moves the same
destinations into a sidebar and adds Settings for owners.
Home is request-first rather than a miniature infrastructure dashboard. It
shows the person's allowance and requests. Operations contains service health,
transfer speed, and queue state. This keeps friends away from implementation
details while giving an owner fast access from the same application.
## Honest states
Disconnected discovery accepts a query but explains why no result provider can
answer it. It does not display popular titles from fixtures. Operations treats
an empty qBittorrent response as a clear queue and treats no configuration,
authentication failures, timeouts, and malformed responses as different
conditions.
## Quota behavior
Movie and series limits are independent. An owner can eventually apply hourly
and/or daily limits to each person. The strictest remaining bucket is shown.
Submitting a request reserves every active bucket atomically; a double tap
cannot create extra allowance. A denied request should state when the limiting
bucket resets.
The current UI shows an em dash until persisted limits are connected. Showing a
made-up number would teach people to distrust the product.
## Motion and access
Touch targets aim for at least 42px, focus indicators remain visible, and
content works at 360px without horizontal scrolling. Motion is restrained and
reduced when the operating system requests reduced motion.
+14
View File
@@ -0,0 +1,14 @@
import { defineConfig, globalIgnores } from "eslint/config";
import nextVitals from "eslint-config-next/core-web-vitals";
import nextTypescript from "eslint-config-next/typescript";
export default defineConfig([
...nextVitals,
...nextTypescript,
globalIgnores([
".next/**",
"coverage/**",
"playwright-report/**",
"test-results/**",
]),
]);
+79
View File
@@ -0,0 +1,79 @@
CREATE TYPE "public"."audit_outcome" AS ENUM('success', 'denied', 'failed');--> statement-breakpoint
CREATE TYPE "public"."integration_health" AS ENUM('online', 'degraded', 'offline', 'not-configured');--> statement-breakpoint
CREATE TYPE "public"."media_type" AS ENUM('movie', 'series');--> statement-breakpoint
CREATE TYPE "public"."quota_window" AS ENUM('hour', 'day');--> statement-breakpoint
CREATE TYPE "public"."request_status" AS ENUM('pending', 'approved', 'available', 'declined', 'failed');--> statement-breakpoint
CREATE TYPE "public"."role" AS ENUM('owner', 'maintainer', 'requester', 'guest');--> statement-breakpoint
CREATE TABLE "audit_events" (
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
"actor_id" uuid,
"action" text NOT NULL,
"target_type" text NOT NULL,
"target_id" text NOT NULL,
"outcome" "audit_outcome" NOT NULL,
"metadata" jsonb DEFAULT '{}'::jsonb NOT NULL,
"created_at" timestamp with time zone DEFAULT now() NOT NULL
);
--> statement-breakpoint
CREATE TABLE "integrations" (
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
"name" text NOT NULL,
"kind" text NOT NULL,
"base_url" text NOT NULL,
"encrypted_credential" text NOT NULL,
"health" "integration_health" DEFAULT 'not-configured' NOT NULL,
"capabilities" jsonb DEFAULT '{}'::jsonb NOT NULL,
"last_checked_at" timestamp with time zone,
"created_at" timestamp with time zone DEFAULT now() NOT NULL,
"updated_at" timestamp with time zone DEFAULT now() NOT NULL
);
--> statement-breakpoint
CREATE TABLE "media_requests" (
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
"requested_by" uuid NOT NULL,
"media_type" "media_type" NOT NULL,
"external_id" text NOT NULL,
"title" text NOT NULL,
"status" "request_status" DEFAULT 'pending' NOT NULL,
"created_at" timestamp with time zone DEFAULT now() NOT NULL,
"updated_at" timestamp with time zone DEFAULT now() NOT NULL
);
--> statement-breakpoint
CREATE TABLE "quota_usage" (
"user_id" uuid NOT NULL,
"media_type" "media_type" NOT NULL,
"window" "quota_window" NOT NULL,
"window_started_at" timestamp with time zone NOT NULL,
"used" integer DEFAULT 0 NOT NULL,
CONSTRAINT "quota_usage_scope_pk" PRIMARY KEY("user_id","media_type","window","window_started_at")
);
--> statement-breakpoint
CREATE TABLE "request_limits" (
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
"user_id" uuid NOT NULL,
"media_type" "media_type" NOT NULL,
"window" "quota_window" NOT NULL,
"maximum" integer NOT NULL,
"updated_at" timestamp with time zone DEFAULT now() NOT NULL
);
--> statement-breakpoint
CREATE TABLE "users" (
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
"email" text NOT NULL,
"display_name" text NOT NULL,
"role" "role" DEFAULT 'requester' NOT NULL,
"active" boolean DEFAULT true NOT NULL,
"created_at" timestamp with time zone DEFAULT now() NOT NULL,
"updated_at" timestamp with time zone DEFAULT now() NOT NULL
);
--> statement-breakpoint
ALTER TABLE "audit_events" ADD CONSTRAINT "audit_events_actor_id_users_id_fk" FOREIGN KEY ("actor_id") REFERENCES "public"."users"("id") ON DELETE set null ON UPDATE no action;--> statement-breakpoint
ALTER TABLE "media_requests" ADD CONSTRAINT "media_requests_requested_by_users_id_fk" FOREIGN KEY ("requested_by") REFERENCES "public"."users"("id") ON DELETE restrict ON UPDATE no action;--> statement-breakpoint
ALTER TABLE "quota_usage" ADD CONSTRAINT "quota_usage_user_id_users_id_fk" FOREIGN KEY ("user_id") REFERENCES "public"."users"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
ALTER TABLE "request_limits" ADD CONSTRAINT "request_limits_user_id_users_id_fk" FOREIGN KEY ("user_id") REFERENCES "public"."users"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
CREATE INDEX "audit_events_actor_created_idx" ON "audit_events" USING btree ("actor_id","created_at");--> statement-breakpoint
CREATE UNIQUE INDEX "integrations_name_unique" ON "integrations" USING btree ("name");--> statement-breakpoint
CREATE INDEX "media_requests_user_created_idx" ON "media_requests" USING btree ("requested_by","created_at");--> statement-breakpoint
CREATE UNIQUE INDEX "media_requests_user_media_unique" ON "media_requests" USING btree ("requested_by","media_type","external_id");--> statement-breakpoint
CREATE UNIQUE INDEX "request_limits_scope_unique" ON "request_limits" USING btree ("user_id","media_type","window");--> statement-breakpoint
CREATE UNIQUE INDEX "users_email_unique" ON "users" USING btree ("email");
+597
View File
@@ -0,0 +1,597 @@
{
"id": "c5341eff-8446-4a56-a93c-32256e92b4e0",
"prevId": "00000000-0000-0000-0000-000000000000",
"version": "7",
"dialect": "postgresql",
"tables": {
"public.audit_events": {
"name": "audit_events",
"schema": "",
"columns": {
"id": {
"name": "id",
"type": "uuid",
"primaryKey": true,
"notNull": true,
"default": "gen_random_uuid()"
},
"actor_id": {
"name": "actor_id",
"type": "uuid",
"primaryKey": false,
"notNull": false
},
"action": {
"name": "action",
"type": "text",
"primaryKey": false,
"notNull": true
},
"target_type": {
"name": "target_type",
"type": "text",
"primaryKey": false,
"notNull": true
},
"target_id": {
"name": "target_id",
"type": "text",
"primaryKey": false,
"notNull": true
},
"outcome": {
"name": "outcome",
"type": "audit_outcome",
"typeSchema": "public",
"primaryKey": false,
"notNull": true
},
"metadata": {
"name": "metadata",
"type": "jsonb",
"primaryKey": false,
"notNull": true,
"default": "'{}'::jsonb"
},
"created_at": {
"name": "created_at",
"type": "timestamp with time zone",
"primaryKey": false,
"notNull": true,
"default": "now()"
}
},
"indexes": {
"audit_events_actor_created_idx": {
"name": "audit_events_actor_created_idx",
"columns": [
{
"expression": "actor_id",
"isExpression": false,
"asc": true,
"nulls": "last"
},
{
"expression": "created_at",
"isExpression": false,
"asc": true,
"nulls": "last"
}
],
"isUnique": false,
"concurrently": false,
"method": "btree",
"with": {}
}
},
"foreignKeys": {
"audit_events_actor_id_users_id_fk": {
"name": "audit_events_actor_id_users_id_fk",
"tableFrom": "audit_events",
"tableTo": "users",
"columnsFrom": ["actor_id"],
"columnsTo": ["id"],
"onDelete": "set null",
"onUpdate": "no action"
}
},
"compositePrimaryKeys": {},
"uniqueConstraints": {},
"policies": {},
"checkConstraints": {},
"isRLSEnabled": false
},
"public.integrations": {
"name": "integrations",
"schema": "",
"columns": {
"id": {
"name": "id",
"type": "uuid",
"primaryKey": true,
"notNull": true,
"default": "gen_random_uuid()"
},
"name": {
"name": "name",
"type": "text",
"primaryKey": false,
"notNull": true
},
"kind": {
"name": "kind",
"type": "text",
"primaryKey": false,
"notNull": true
},
"base_url": {
"name": "base_url",
"type": "text",
"primaryKey": false,
"notNull": true
},
"encrypted_credential": {
"name": "encrypted_credential",
"type": "text",
"primaryKey": false,
"notNull": true
},
"health": {
"name": "health",
"type": "integration_health",
"typeSchema": "public",
"primaryKey": false,
"notNull": true,
"default": "'not-configured'"
},
"capabilities": {
"name": "capabilities",
"type": "jsonb",
"primaryKey": false,
"notNull": true,
"default": "'{}'::jsonb"
},
"last_checked_at": {
"name": "last_checked_at",
"type": "timestamp with time zone",
"primaryKey": false,
"notNull": false
},
"created_at": {
"name": "created_at",
"type": "timestamp with time zone",
"primaryKey": false,
"notNull": true,
"default": "now()"
},
"updated_at": {
"name": "updated_at",
"type": "timestamp with time zone",
"primaryKey": false,
"notNull": true,
"default": "now()"
}
},
"indexes": {
"integrations_name_unique": {
"name": "integrations_name_unique",
"columns": [
{
"expression": "name",
"isExpression": false,
"asc": true,
"nulls": "last"
}
],
"isUnique": true,
"concurrently": false,
"method": "btree",
"with": {}
}
},
"foreignKeys": {},
"compositePrimaryKeys": {},
"uniqueConstraints": {},
"policies": {},
"checkConstraints": {},
"isRLSEnabled": false
},
"public.media_requests": {
"name": "media_requests",
"schema": "",
"columns": {
"id": {
"name": "id",
"type": "uuid",
"primaryKey": true,
"notNull": true,
"default": "gen_random_uuid()"
},
"requested_by": {
"name": "requested_by",
"type": "uuid",
"primaryKey": false,
"notNull": true
},
"media_type": {
"name": "media_type",
"type": "media_type",
"typeSchema": "public",
"primaryKey": false,
"notNull": true
},
"external_id": {
"name": "external_id",
"type": "text",
"primaryKey": false,
"notNull": true
},
"title": {
"name": "title",
"type": "text",
"primaryKey": false,
"notNull": true
},
"status": {
"name": "status",
"type": "request_status",
"typeSchema": "public",
"primaryKey": false,
"notNull": true,
"default": "'pending'"
},
"created_at": {
"name": "created_at",
"type": "timestamp with time zone",
"primaryKey": false,
"notNull": true,
"default": "now()"
},
"updated_at": {
"name": "updated_at",
"type": "timestamp with time zone",
"primaryKey": false,
"notNull": true,
"default": "now()"
}
},
"indexes": {
"media_requests_user_created_idx": {
"name": "media_requests_user_created_idx",
"columns": [
{
"expression": "requested_by",
"isExpression": false,
"asc": true,
"nulls": "last"
},
{
"expression": "created_at",
"isExpression": false,
"asc": true,
"nulls": "last"
}
],
"isUnique": false,
"concurrently": false,
"method": "btree",
"with": {}
},
"media_requests_user_media_unique": {
"name": "media_requests_user_media_unique",
"columns": [
{
"expression": "requested_by",
"isExpression": false,
"asc": true,
"nulls": "last"
},
{
"expression": "media_type",
"isExpression": false,
"asc": true,
"nulls": "last"
},
{
"expression": "external_id",
"isExpression": false,
"asc": true,
"nulls": "last"
}
],
"isUnique": true,
"concurrently": false,
"method": "btree",
"with": {}
}
},
"foreignKeys": {
"media_requests_requested_by_users_id_fk": {
"name": "media_requests_requested_by_users_id_fk",
"tableFrom": "media_requests",
"tableTo": "users",
"columnsFrom": ["requested_by"],
"columnsTo": ["id"],
"onDelete": "restrict",
"onUpdate": "no action"
}
},
"compositePrimaryKeys": {},
"uniqueConstraints": {},
"policies": {},
"checkConstraints": {},
"isRLSEnabled": false
},
"public.quota_usage": {
"name": "quota_usage",
"schema": "",
"columns": {
"user_id": {
"name": "user_id",
"type": "uuid",
"primaryKey": false,
"notNull": true
},
"media_type": {
"name": "media_type",
"type": "media_type",
"typeSchema": "public",
"primaryKey": false,
"notNull": true
},
"window": {
"name": "window",
"type": "quota_window",
"typeSchema": "public",
"primaryKey": false,
"notNull": true
},
"window_started_at": {
"name": "window_started_at",
"type": "timestamp with time zone",
"primaryKey": false,
"notNull": true
},
"used": {
"name": "used",
"type": "integer",
"primaryKey": false,
"notNull": true,
"default": 0
}
},
"indexes": {},
"foreignKeys": {
"quota_usage_user_id_users_id_fk": {
"name": "quota_usage_user_id_users_id_fk",
"tableFrom": "quota_usage",
"tableTo": "users",
"columnsFrom": ["user_id"],
"columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
}
},
"compositePrimaryKeys": {
"quota_usage_scope_pk": {
"name": "quota_usage_scope_pk",
"columns": ["user_id", "media_type", "window", "window_started_at"]
}
},
"uniqueConstraints": {},
"policies": {},
"checkConstraints": {},
"isRLSEnabled": false
},
"public.request_limits": {
"name": "request_limits",
"schema": "",
"columns": {
"id": {
"name": "id",
"type": "uuid",
"primaryKey": true,
"notNull": true,
"default": "gen_random_uuid()"
},
"user_id": {
"name": "user_id",
"type": "uuid",
"primaryKey": false,
"notNull": true
},
"media_type": {
"name": "media_type",
"type": "media_type",
"typeSchema": "public",
"primaryKey": false,
"notNull": true
},
"window": {
"name": "window",
"type": "quota_window",
"typeSchema": "public",
"primaryKey": false,
"notNull": true
},
"maximum": {
"name": "maximum",
"type": "integer",
"primaryKey": false,
"notNull": true
},
"updated_at": {
"name": "updated_at",
"type": "timestamp with time zone",
"primaryKey": false,
"notNull": true,
"default": "now()"
}
},
"indexes": {
"request_limits_scope_unique": {
"name": "request_limits_scope_unique",
"columns": [
{
"expression": "user_id",
"isExpression": false,
"asc": true,
"nulls": "last"
},
{
"expression": "media_type",
"isExpression": false,
"asc": true,
"nulls": "last"
},
{
"expression": "window",
"isExpression": false,
"asc": true,
"nulls": "last"
}
],
"isUnique": true,
"concurrently": false,
"method": "btree",
"with": {}
}
},
"foreignKeys": {
"request_limits_user_id_users_id_fk": {
"name": "request_limits_user_id_users_id_fk",
"tableFrom": "request_limits",
"tableTo": "users",
"columnsFrom": ["user_id"],
"columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
}
},
"compositePrimaryKeys": {},
"uniqueConstraints": {},
"policies": {},
"checkConstraints": {},
"isRLSEnabled": false
},
"public.users": {
"name": "users",
"schema": "",
"columns": {
"id": {
"name": "id",
"type": "uuid",
"primaryKey": true,
"notNull": true,
"default": "gen_random_uuid()"
},
"email": {
"name": "email",
"type": "text",
"primaryKey": false,
"notNull": true
},
"display_name": {
"name": "display_name",
"type": "text",
"primaryKey": false,
"notNull": true
},
"role": {
"name": "role",
"type": "role",
"typeSchema": "public",
"primaryKey": false,
"notNull": true,
"default": "'requester'"
},
"active": {
"name": "active",
"type": "boolean",
"primaryKey": false,
"notNull": true,
"default": true
},
"created_at": {
"name": "created_at",
"type": "timestamp with time zone",
"primaryKey": false,
"notNull": true,
"default": "now()"
},
"updated_at": {
"name": "updated_at",
"type": "timestamp with time zone",
"primaryKey": false,
"notNull": true,
"default": "now()"
}
},
"indexes": {
"users_email_unique": {
"name": "users_email_unique",
"columns": [
{
"expression": "email",
"isExpression": false,
"asc": true,
"nulls": "last"
}
],
"isUnique": true,
"concurrently": false,
"method": "btree",
"with": {}
}
},
"foreignKeys": {},
"compositePrimaryKeys": {},
"uniqueConstraints": {},
"policies": {},
"checkConstraints": {},
"isRLSEnabled": false
}
},
"enums": {
"public.audit_outcome": {
"name": "audit_outcome",
"schema": "public",
"values": ["success", "denied", "failed"]
},
"public.integration_health": {
"name": "integration_health",
"schema": "public",
"values": ["online", "degraded", "offline", "not-configured"]
},
"public.media_type": {
"name": "media_type",
"schema": "public",
"values": ["movie", "series"]
},
"public.quota_window": {
"name": "quota_window",
"schema": "public",
"values": ["hour", "day"]
},
"public.request_status": {
"name": "request_status",
"schema": "public",
"values": ["pending", "approved", "available", "declined", "failed"]
},
"public.role": {
"name": "role",
"schema": "public",
"values": ["owner", "maintainer", "requester", "guest"]
}
},
"schemas": {},
"sequences": {},
"roles": {},
"policies": {},
"views": {},
"_meta": {
"columns": {},
"schemas": {},
"tables": {}
}
}
+13
View File
@@ -0,0 +1,13 @@
{
"version": "7",
"dialect": "postgresql",
"entries": [
{
"idx": 0,
"version": "7",
"when": 1786848815547,
"tag": "0000_familiar_queen_noir",
"breakpoints": true
}
]
}
+8
View File
@@ -0,0 +1,8 @@
import type { NextConfig } from "next";
const nextConfig: NextConfig = {
reactStrictMode: true,
poweredByHeader: false,
};
export default nextConfig;
+8518
View File
File diff suppressed because it is too large. Load diff
+44
View File
@@ -0,0 +1,44 @@
{
"name": "arrmate",
"version": "0.1.0",
"private": true,
"type": "module",
"description": "The friendly control plane for your self-hosted media stack.",
"engines": {
"node": ">=22.0.0"
},
"packageManager": "[email protected]",
"scripts": {
"dev": "next dev",
"build": "next build",
"start": "next start",
"format": "prettier --write .",
"format:check": "prettier --check .",
"lint": "eslint .",
"typecheck": "next typegen && tsc --noEmit",
"test": "vitest run",
"test:watch": "vitest",
"test:browser": "playwright test",
"db:migrate": "node scripts/migrate.mjs"
},
"dependencies": {
"drizzle-orm": "^0.45.2",
"lucide-react": "^1.31.0",
"next": "^16.3.1",
"postgres": "^3.4.7",
"react": "^19.2.8",
"react-dom": "^19.2.8",
"zod": "^4.4.3"
},
"devDependencies": {
"@playwright/test": "^1.58.2",
"@types/node": "^22.19.15",
"@types/react": "^19.2.14",
"@types/react-dom": "^19.2.3",
"eslint": "^9.39.2",
"eslint-config-next": "^16.3.1",
"prettier": "^3.8.2",
"typescript": "^5.9.3",
"vitest": "^4.1.10"
}
}
+29
View File
@@ -0,0 +1,29 @@
import { defineConfig, devices } from "@playwright/test";
export default defineConfig({
testDir: "./tests/browser",
fullyParallel: true,
forbidOnly: Boolean(process.env.CI),
retries: process.env.CI ? 2 : 0,
reporter: "list",
use: {
baseURL: "http://127.0.0.1:3100",
trace: "on-first-retry",
},
projects: [
{
name: "mobile-chromium",
use: { ...devices["Pixel 7"] },
},
{
name: "desktop-chromium",
use: { ...devices["Desktop Chrome"] },
},
],
webServer: {
command: "npm run dev -- --hostname 127.0.0.1 --port 3100",
url: "http://127.0.0.1:3100",
reuseExistingServer: !process.env.CI,
timeout: 120_000,
},
});
+18
View File
@@ -0,0 +1,18 @@
import { drizzle } from "drizzle-orm/postgres-js";
import { migrate } from "drizzle-orm/postgres-js/migrator";
import postgres from "postgres";
const databaseUrl = process.env.DATABASE_URL;
if (!databaseUrl) {
throw new Error("DATABASE_URL is required to run migrations");
}
const client = postgres(databaseUrl, { max: 1 });
const database = drizzle(client);
try {
await migrate(database, { migrationsFolder: "migrations" });
console.log("Arrmate database migrations are up to date.");
} finally {
await client.end();
}
+17
View File
@@ -0,0 +1,17 @@
import type { DownloadOverview } from "@/domain/downloads";
import type { AdapterResult, CapabilitySet } from "@/domain/integrations";
export interface IntegrationAdapter {
readonly name: string;
readonly capabilities: CapabilitySet;
health(): Promise<AdapterResult<{ latencyMs: number }>>;
}
export interface DownloadClientAdapter extends IntegrationAdapter {
overview(): Promise<AdapterResult<DownloadOverview>>;
}
export type MediaServerAdapter = IntegrationAdapter;
export type MediaManagerAdapter = IntegrationAdapter;
export type IndexerAdapter = IntegrationAdapter;
export type SubtitleProviderAdapter = IntegrationAdapter;
+142
View File
@@ -0,0 +1,142 @@
import { describe, expect, it, vi } from "vitest";
import { QbittorrentAdapter } from "./qbittorrent";
function adapter(fetchImpl: typeof fetch, timeoutMs = 100) {
return new QbittorrentAdapter(
{
baseUrl: "http://qbittorrent.test:8080",
username: "test-user",
password: "test-value",
timeoutMs,
},
fetchImpl,
);
}
function pathname(input: RequestInfo | URL): string {
if (input instanceof URL) return input.pathname;
if (input instanceof Request) return new URL(input.url).pathname;
return new URL(input).pathname;
}
const loginResponse = () =>
new Response("Ok.", {
status: 200,
headers: { "set-cookie": "SID=test-session; HttpOnly" },
});
describe("qBittorrent adapter", () => {
it("normalizes a live transfer and download response", async () => {
const fetchMock = vi.fn(async (input: RequestInfo | URL) => {
if (pathname(input) === "/api/v2/auth/login") return loginResponse();
if (pathname(input) === "/api/v2/torrents/info") {
return Response.json([
{
hash: "abc123",
name: "Example movie",
size: 10_000,
progress: 0.42,
dlspeed: 800,
upspeed: 20,
eta: 90,
state: "downloading",
ratio: 0.2,
category: "movies",
},
]);
}
return Response.json({
dl_info_speed: 800,
up_info_speed: 20,
dl_info_data: 4_200,
up_info_data: 200,
});
}) as unknown as typeof fetch;
const result = await adapter(fetchMock).overview();
expect(result.ok).toBe(true);
if (!result.ok) return;
expect(result.data.items).toEqual([
expect.objectContaining({
id: "abc123",
name: "Example movie",
progress: 0.42,
state: "downloading",
}),
]);
expect(result.data.transfer.downloadSpeedBytes).toBe(800);
const torrentCall = vi
.mocked(fetchMock)
.mock.calls.find(
([input]) => pathname(input) === "/api/v2/torrents/info",
);
expect(new Headers(torrentCall?.[1]?.headers).get("cookie")).toBe(
"SID=test-session",
);
});
it("distinguishes a valid empty queue from an error", async () => {
const fetchMock = vi.fn(async (input: RequestInfo | URL) => {
if (pathname(input) === "/api/v2/auth/login") return loginResponse();
if (pathname(input) === "/api/v2/torrents/info") return Response.json([]);
return Response.json({
dl_info_speed: 0,
up_info_speed: 0,
dl_info_data: 0,
up_info_data: 0,
});
}) as unknown as typeof fetch;
const result = await adapter(fetchMock).overview();
expect(result).toMatchObject({ ok: true, data: { items: [] } });
});
it("returns a safe authentication error", async () => {
const fetchMock = vi.fn(
async () => new Response("Fails.", { status: 403 }),
) as unknown as typeof fetch;
const result = await adapter(fetchMock).overview();
expect(result).toEqual({
ok: false,
error: {
code: "authentication",
message: "qBittorrent rejected the credentials",
retryable: false,
},
});
});
it("reports a timeout without exposing request details", 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).overview();
expect(result).toMatchObject({
ok: false,
error: { code: "timeout", retryable: true },
});
});
it("rejects malformed upstream data", async () => {
const fetchMock = vi.fn(async (input: RequestInfo | URL) => {
if (pathname(input) === "/api/v2/auth/login") return loginResponse();
if (pathname(input) === "/api/v2/torrents/info") {
return Response.json([{ hash: "missing-required-fields" }]);
}
return Response.json({ unexpected: true });
}) as unknown as typeof fetch;
const result = await adapter(fetchMock).overview();
expect(result).toMatchObject({
ok: false,
error: { code: "malformed-response", retryable: true },
});
});
});
+276
View File
@@ -0,0 +1,276 @@
import { z } from "zod";
import type {
DownloadItem,
DownloadOverview,
DownloadState,
} from "@/domain/downloads";
import type {
AdapterError,
AdapterResult,
CapabilitySet,
} from "@/domain/integrations";
import type { DownloadClientAdapter } from "./contracts";
import { normalizeIntegrationUrl } from "./url";
const torrentSchema = z
.object({
hash: z.string().min(1),
name: z.string(),
size: z.number().nonnegative(),
progress: z.number(),
dlspeed: z.number().nonnegative(),
upspeed: z.number().nonnegative(),
eta: z.number(),
state: z.string(),
ratio: z.number(),
category: z.string().optional().default(""),
})
.passthrough();
const torrentsSchema = z.array(torrentSchema);
const transferSchema = z
.object({
dl_info_speed: z.number().nonnegative(),
up_info_speed: z.number().nonnegative(),
dl_info_data: z.number().nonnegative(),
up_info_data: z.number().nonnegative(),
})
.passthrough();
export interface QbittorrentConfig {
baseUrl: string;
username: string;
password: string;
timeoutMs?: number;
}
type Fetch = typeof fetch;
function adapterError(
code: AdapterError["code"],
message: string,
retryable: boolean,
): AdapterResult<never> {
return { ok: false, error: { code, message, retryable } };
}
function normalizeState(state: string, progress: number): DownloadState {
const normalized = state.toLowerCase();
if (progress >= 1 && ["pausedUP", "stoppedUP"].includes(state))
return "complete";
if (state.includes("error") || state === "missingFiles") return "error";
if (normalized.includes("checking")) return "checking";
if (normalized.includes("stalled")) return "stalled";
if (state.startsWith("paused") || state.startsWith("stopped"))
return "paused";
if (
normalized.includes("downloading") ||
state.includes("DL") ||
state === "metaDL" ||
state === "forcedDL"
) {
return "downloading";
}
if (normalized.includes("queued")) return "queued";
if (state.includes("UP") || state === "uploading" || state === "forcedUP") {
return "seeding";
}
return progress >= 1 ? "complete" : "unknown";
}
function normalizeTorrent(
torrent: z.infer<typeof torrentSchema>,
): DownloadItem {
return {
id: torrent.hash,
name: torrent.name,
sizeBytes: torrent.size,
progress: Math.max(0, Math.min(1, torrent.progress)),
downloadSpeedBytes: torrent.dlspeed,
uploadSpeedBytes: torrent.upspeed,
etaSeconds: torrent.eta >= 8_640_000 ? null : Math.max(0, torrent.eta),
state: normalizeState(torrent.state, torrent.progress),
ratio: torrent.ratio,
category: torrent.category || null,
};
}
export class QbittorrentAdapter implements DownloadClientAdapter {
readonly name = "qBittorrent";
readonly capabilities: CapabilitySet = {
readQueue: true,
manageQueue: false,
search: false,
request: false,
deleteMedia: false,
replaceMedia: false,
searchSubtitles: false,
};
private readonly baseUrl: URL;
private readonly timeoutMs: number;
constructor(
private readonly config: QbittorrentConfig,
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 session = await this.login();
if (!session.ok) return session;
const response = await this.request("/api/v2/app/version", session.data);
if (!response.ok) return response;
if (!response.data.ok) {
return adapterError("upstream", "qBittorrent health check failed", true);
}
return {
ok: true,
data: { latencyMs: Math.round(performance.now() - startedAt) },
};
}
async overview(): Promise<AdapterResult<DownloadOverview>> {
const session = await this.login();
if (!session.ok) return session;
const [torrentsResponse, transferResponse] = await Promise.all([
this.request("/api/v2/torrents/info", session.data),
this.request("/api/v2/transfer/info", session.data),
]);
if (!torrentsResponse.ok) return torrentsResponse;
if (!transferResponse.ok) return transferResponse;
if (
torrentsResponse.data.status === 403 ||
transferResponse.data.status === 403
) {
return adapterError(
"authentication",
"qBittorrent rejected the session",
false,
);
}
if (!torrentsResponse.data.ok || !transferResponse.data.ok) {
return adapterError(
"upstream",
"qBittorrent returned an unsuccessful response",
true,
);
}
try {
const torrents = torrentsSchema.parse(await torrentsResponse.data.json());
const transfer = transferSchema.parse(await transferResponse.data.json());
return {
ok: true,
data: {
items: torrents.map(normalizeTorrent),
transfer: {
downloadSpeedBytes: transfer.dl_info_speed,
uploadSpeedBytes: transfer.up_info_speed,
downloadedBytes: transfer.dl_info_data,
uploadedBytes: transfer.up_info_data,
},
fetchedAt: new Date(),
},
};
} catch {
return adapterError(
"malformed-response",
"qBittorrent returned data Arrmate could not validate",
true,
);
}
}
private async login(): Promise<AdapterResult<string>> {
const body = new URLSearchParams({
username: this.config.username,
password: this.config.password,
});
const response = await this.request("/api/v2/auth/login", undefined, {
method: "POST",
body,
headers: { "content-type": "application/x-www-form-urlencoded" },
});
if (!response.ok) return response;
if (response.data.status === 403) {
return adapterError(
"authentication",
"qBittorrent rejected the credentials",
false,
);
}
const text = await response.data.text();
if (!response.data.ok || text.trim() !== "Ok.") {
return adapterError(
"authentication",
"qBittorrent rejected the credentials",
false,
);
}
const cookie = response.data.headers
.get("set-cookie")
?.match(/SID=[^;]+/)?.[0];
if (!cookie) {
return adapterError(
"malformed-response",
"qBittorrent did not create a session",
true,
);
}
return { ok: true, data: cookie };
}
private async request(
path: string,
session?: 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("referer", this.baseUrl.toString());
if (session) headers.set("cookie", session);
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 adapterError(
"timeout",
"qBittorrent did not respond before the timeout",
true,
);
}
return adapterError(
"unreachable",
"qBittorrent could not be reached",
true,
);
} finally {
clearTimeout(timeout);
}
}
}
+20
View File
@@ -0,0 +1,20 @@
import { describe, expect, it } from "vitest";
import { normalizeIntegrationUrl } from "./url";
describe("integration URL validation", () => {
it("keeps an operator-configured private HTTP endpoint", () => {
expect(
normalizeIntegrationUrl("http://192.168.1.20:8080/").toString(),
).toBe("http://192.168.1.20:8080/");
});
it("rejects embedded credentials and non-HTTP protocols", () => {
expect(() =>
normalizeIntegrationUrl("http://admin:pass@host:8080"),
).toThrow("cannot contain credentials");
expect(() => normalizeIntegrationUrl("file:///etc/passwd")).toThrow(
"HTTP or HTTPS",
);
});
});
+15
View File
@@ -0,0 +1,15 @@
export function normalizeIntegrationUrl(value: string): URL {
const url = new URL(value);
if (!["http:", "https:"].includes(url.protocol)) {
throw new Error("Integration URL must use HTTP or HTTPS");
}
if (url.username || url.password) {
throw new Error("Integration URL cannot contain credentials");
}
if (url.hash) {
throw new Error("Integration URL cannot contain a fragment");
}
url.pathname = url.pathname.replace(/\/$/, "");
url.search = "";
return url;
}
+24
View File
@@ -0,0 +1,24 @@
"use server";
import { redirect } from "next/navigation";
import type { Role } from "@/domain/auth";
import { roles } from "@/domain/auth";
import {
clearDevelopmentViewer,
developmentAuthEnabled,
setDevelopmentViewer,
} from "@/server/auth/session";
export async function developmentSignIn(formData: FormData) {
if (!developmentAuthEnabled()) redirect("/sign-in?error=disabled");
const role = formData.get("role");
if (!roles.includes(role as Role)) redirect("/sign-in?error=role");
await setDevelopmentViewer(role as Role);
redirect(role === "owner" || role === "maintainer" ? "/operations" : "/");
}
export async function signOut() {
await clearDevelopmentViewer();
redirect("/");
}
+46
View File
@@ -0,0 +1,46 @@
import { Inbox, ListFilter } from "lucide-react";
import { EmptyState } from "@/components/empty-state";
export const metadata = { title: "Activity" };
export default function ActivityPage() {
return (
<div className="page-stack compact-stack">
<section className="welcome-row">
<div>
<p className="eyebrow">Requests</p>
<h1>Activity</h1>
<p className="page-lead">
Follow each title from request to ready-to-watch.
</p>
</div>
<button
className="secondary-button desktop-only"
type="button"
disabled
>
<ListFilter size={16} /> Filter
</button>
</section>
<div className="segmented-control" aria-label="Activity filter">
<button className="selected" type="button">
All
</button>
<button type="button" disabled>
Pending
</button>
<button type="button" disabled>
Available
</button>
</div>
<section className="surface-card min-card">
<EmptyState
icon={Inbox}
title="No request activity"
description="New requests, approvals, downloads, and availability updates will collect here."
/>
</section>
</div>
);
}
+67
View File
@@ -0,0 +1,67 @@
import { CircleSlash2, Search, SlidersHorizontal } from "lucide-react";
import { EmptyState } from "@/components/empty-state";
export const metadata = { title: "Discover" };
export default async function DiscoverPage({
searchParams,
}: {
searchParams: Promise<{ q?: string }>;
}) {
const query = (await searchParams).q?.trim() ?? "";
return (
<div className="page-stack compact-stack">
<section className="welcome-row">
<div>
<p className="eyebrow">Discover</p>
<h1>Find anything.</h1>
<p className="page-lead">
Movies and series will share one clean search.
</p>
</div>
</section>
<form className="search-shell" action="/discover">
<Search size={20} aria-hidden="true" />
<input
name="q"
defaultValue={query}
aria-label="Search movies and series"
placeholder="Search movies and series…"
autoComplete="off"
/>
<button
className="filter-button"
type="button"
disabled
aria-label="Search filters are not available yet"
>
<SlidersHorizontal size={18} />
</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>
<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>
</div>
);
}
+1331
View File
File diff suppressed because it is too large. Load diff
+36
View File
@@ -0,0 +1,36 @@
import type { Metadata, Viewport } from "next";
import type { ReactNode } from "react";
import { AppShell } from "@/components/app-shell";
import { getViewer } from "@/server/auth/session";
import "./globals.css";
export const metadata: Metadata = {
title: {
default: "Arrmate",
template: "%s · Arrmate",
},
description: "The friendly control plane for your self-hosted media stack.",
applicationName: "Arrmate",
};
export const viewport: Viewport = {
width: "device-width",
initialScale: 1,
themeColor: "#0d1110",
colorScheme: "dark",
};
export default async function RootLayout({
children,
}: Readonly<{ children: ReactNode }>) {
const viewer = await getViewer();
return (
<html lang="en">
<body>
<AppShell viewer={viewer}>{children}</AppShell>
</body>
</html>
);
}
+162
View File
@@ -0,0 +1,162 @@
import {
Activity,
ArrowDown,
Gauge,
HardDrive,
RefreshCw,
Settings2,
Unplug,
} from "lucide-react";
import Link from "next/link";
import { redirect } from "next/navigation";
import { DownloadRow, formatBytes } from "@/components/download-row";
import { EmptyState } from "@/components/empty-state";
import { StatusPill } from "@/components/status-pill";
import { can } from "@/domain/auth";
import { getViewer } from "@/server/auth/session";
import { getOperationsSnapshot } from "@/server/operations";
export const metadata = { title: "Operations" };
export const dynamic = "force-dynamic";
export default async function OperationsPage() {
const viewer = await getViewer();
if (!can(viewer, "operations:view")) redirect("/sign-in");
const snapshot = await getOperationsSnapshot();
const online = snapshot.integrations.filter(
(item) => item.health === "online",
).length;
const active =
snapshot.downloads?.items.filter((item) => item.state === "downloading")
.length ?? 0;
return (
<div className="page-stack compact-stack">
<section className="welcome-row">
<div>
<p className="eyebrow">Admin workspace</p>
<h1>Operations</h1>
<p className="page-lead">The pulse of your media pipeline.</p>
</div>
<Link className="secondary-button desktop-only" href="/settings">
<Settings2 size={16} /> Manage services
</Link>
</section>
<section className="stat-grid">
<article className="stat-card">
<span className="stat-icon green">
<Activity size={19} />
</span>
<div>
<small>Services online</small>
<strong>
{online}
<span> / {snapshot.integrations.length}</span>
</strong>
</div>
</article>
<article className="stat-card">
<span className="stat-icon coral">
<ArrowDown size={19} />
</span>
<div>
<small>Active downloads</small>
<strong>{active}</strong>
</div>
</article>
<article className="stat-card">
<span className="stat-icon blue">
<Gauge size={19} />
</span>
<div>
<small>Down speed</small>
<strong>
{snapshot.downloads
? formatBytes(snapshot.downloads.transfer.downloadSpeedBytes)
: "—"}
<span>{snapshot.downloads ? "/s" : ""}</span>
</strong>
</div>
</article>
<article className="stat-card">
<span className="stat-icon violet">
<HardDrive size={19} />
</span>
<div>
<small>Queue size</small>
<strong>{snapshot.downloads?.items.length ?? "—"}</strong>
</div>
</article>
</section>
<section className="section-block">
<div className="section-heading">
<div>
<p className="eyebrow">Connected apps</p>
<h2>Service health</h2>
</div>
<span className="fresh-label">
<RefreshCw size={13} /> Checked now
</span>
</div>
<div className="service-grid">
{snapshot.integrations.map((integration) => (
<article className="service-card" key={integration.id}>
<div className={`service-monogram service-${integration.id}`}>
{integration.name.slice(0, 2).toUpperCase()}
</div>
<div className="service-copy">
<strong>{integration.name}</strong>
<p>{integration.detail}</p>
</div>
<StatusPill status={integration.health} />
</article>
))}
</div>
</section>
<section className="section-block">
<div className="section-heading">
<div>
<p className="eyebrow">qBittorrent</p>
<h2>Download queue</h2>
</div>
{snapshot.downloads && (
<span className="fresh-label">Live adapter data</span>
)}
</div>
<div className="surface-card queue-card">
{snapshot.downloads?.items.length ? (
snapshot.downloads.items.map((item) => (
<DownloadRow item={item} key={item.id} />
))
) : (
<EmptyState
icon={Unplug}
title={
snapshot.downloadError
? "Download client needs attention"
: snapshot.downloads
? "Queue is clear"
: "qBittorrent is not connected"
}
description={
snapshot.downloadError?.message ??
(snapshot.downloads
? "There are no active or completed queue items."
: "Add server-side qBittorrent settings to see live downloads here.")
}
action={
<Link className="secondary-button" href="/settings">
Open integration setup
</Link>
}
/>
)}
</div>
</section>
</div>
);
}
+119
View File
@@ -0,0 +1,119 @@
import {
ArrowRight,
Clapperboard,
Clock3,
Film,
Search,
Sparkles,
Tv,
} from "lucide-react";
import Link from "next/link";
import { EmptyState } from "@/components/empty-state";
import { can } from "@/domain/auth";
import { getViewer } from "@/server/auth/session";
export const dynamic = "force-dynamic";
export default async function HomePage() {
const viewer = await getViewer();
const isOperator = can(viewer, "operations:view");
return (
<div className="page-stack">
<section className="welcome-row">
<div>
<p className="eyebrow">Sunday, 16 August</p>
<h1>
{viewer.role === "guest"
? "Find your next watch."
: `Welcome back, ${viewer.name.split(" ")[0]}.`}
</h1>
<p className="page-lead">
{isOperator
? "Your whole media stack, without the dashboard shuffle."
: "Explore the library and request what should be added next."}
</p>
</div>
{isOperator && (
<Link className="text-link desktop-only" href="/operations">
Open operations <ArrowRight size={16} />
</Link>
)}
</section>
<section className="discover-hero">
<div className="hero-glow hero-glow-one" />
<div className="hero-glow hero-glow-two" />
<div className="hero-art" aria-hidden="true">
<span className="poster poster-one">
<Film />
</span>
<span className="poster poster-two">
<Tv />
</span>
<span className="poster poster-three">
<Clapperboard />
</span>
</div>
<div className="hero-copy">
<span className="hero-kicker">
<Sparkles size={14} /> One search. Every screen.
</span>
<h2>What should we watch next?</h2>
<p>Search movies and series, then send a request in a few taps.</p>
<Link className="primary-button" href="/discover">
<Search size={17} /> Start exploring
</Link>
</div>
</section>
<section className="quota-grid" aria-label="Request allowance">
<article className="quota-card">
<span className="quota-icon coral">
<Film size={19} />
</span>
<div>
<span>Movie requests</span>
<strong>—</strong>
<small>Limit loads after setup</small>
</div>
</article>
<article className="quota-card">
<span className="quota-icon blue">
<Tv size={19} />
</span>
<div>
<span>Series requests</span>
<strong>—</strong>
<small>Limit loads after setup</small>
</div>
</article>
</section>
<section className="section-block">
<div className="section-heading">
<div>
<p className="eyebrow">Your queue</p>
<h2>Recent requests</h2>
</div>
<Link className="text-link" href="/activity">
View all <ArrowRight size={15} />
</Link>
</div>
<div className="surface-card">
<EmptyState
icon={Clock3}
title="Nothing waiting yet"
description="Your requests and their progress will appear here once a request provider is connected."
action={
<Link className="secondary-button" href="/discover">
Browse titles
</Link>
}
/>
</div>
</section>
</div>
);
}
+86
View File
@@ -0,0 +1,86 @@
import {
ChevronRight,
KeyRound,
LockKeyhole,
PlugZap,
ShieldCheck,
Users,
} from "lucide-react";
import { redirect } from "next/navigation";
import { can } from "@/domain/auth";
import { getViewer } from "@/server/auth/session";
export const metadata = { title: "Settings" };
const settings = [
{
icon: PlugZap,
title: "Integrations",
copy: "URLs, credentials, capabilities",
tag: "Environment setup",
},
{
icon: Users,
title: "People & access",
copy: "Roles and request permissions",
tag: "Schema ready",
},
{
icon: ShieldCheck,
title: "Request limits",
copy: "Hourly and daily movie or series quotas",
tag: "Atomic core ready",
},
{
icon: KeyRound,
title: "Authentication",
copy: "Replace local sign-in with your identity provider",
tag: "Local development",
},
];
export default async function SettingsPage() {
const viewer = await getViewer();
if (!can(viewer, "integration:manage")) redirect("/sign-in");
return (
<div className="page-stack compact-stack narrow-page">
<section className="welcome-row">
<div>
<p className="eyebrow">Owner controls</p>
<h1>Settings</h1>
<p className="page-lead">Securely shape who can do what.</p>
</div>
</section>
<div className="security-banner">
<LockKeyhole size={20} />
<div>
<strong>Secrets stay on the server</strong>
<p>
Upstream API keys are never sent to the browser. This milestone
reads integration settings from the deployment environment.
</p>
</div>
</div>
<section className="settings-list">
{settings.map(({ icon: Icon, title, copy, tag }) => (
<article className="settings-row" key={title}>
<span className="settings-icon">
<Icon size={19} />
</span>
<div>
<strong>{title}</strong>
<p>{copy}</p>
</div>
<span className="settings-tag">{tag}</span>
<ChevronRight className="settings-chevron" size={18} />
</article>
))}
</section>
<p className="settings-footnote">
Editing is intentionally disabled until encrypted credential storage and
audit events are wired to the UI.
</p>
</div>
);
}
+84
View File
@@ -0,0 +1,84 @@
import { HardHat, LockKeyhole, UserRound, UsersRound } from "lucide-react";
import Link from "next/link";
import { developmentSignIn } from "@/app/actions";
import { developmentAuthEnabled } from "@/server/auth/session";
export const metadata = { title: "Local sign in" };
const options = [
{
role: "owner",
label: "Owner",
copy: "Full setup, people, and operations access",
icon: LockKeyhole,
},
{
role: "maintainer",
label: "Maintainer",
copy: "Operate media without security settings",
icon: HardHat,
},
{
role: "requester",
label: "Requester",
copy: "Discover, request, and follow progress",
icon: UserRound,
},
{
role: "guest",
label: "Guest",
copy: "Preview the least-privileged public view",
icon: UsersRound,
},
];
export default function SignInPage() {
const enabled = developmentAuthEnabled();
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>
)}
<Link className="text-link" href="/">
Continue as guest
</Link>
</div>
);
}
+85
View File
@@ -0,0 +1,85 @@
import { LogOut, ShieldCheck } from "lucide-react";
import Link from "next/link";
import type { ReactNode } from "react";
import { signOut } from "@/app/actions";
import type { Viewer } from "@/domain/auth";
import { can } from "@/domain/auth";
import { Brand } from "./brand";
import { NavLinks } from "./nav-links";
function initials(name: string) {
return name
.split(" ")
.map((part) => part[0])
.join("")
.slice(0, 2)
.toUpperCase();
}
export function AppShell({
children,
viewer,
}: {
children: ReactNode;
viewer: Viewer;
}) {
const showOperations = can(viewer, "operations:view");
const isGuest = viewer.role === "guest";
return (
<div className="app-shell">
<aside className="sidebar">
<Brand />
<p className="sidebar-label">Your media stack</p>
<NavLinks showOperations={showOperations} desktop />
<div className="sidebar-foot">
<div className="privacy-note">
<ShieldCheck size={17} aria-hidden="true" />
<span>Private by design</span>
</div>
<div className="profile-block">
<span className="avatar">{initials(viewer.name)}</span>
<span className="profile-copy">
<strong>{viewer.name}</strong>
<small>{viewer.role}</small>
</span>
{!isGuest && (
<form action={signOut}>
<button
className="icon-button"
type="submit"
aria-label="Sign out"
>
<LogOut size={17} />
</button>
</form>
)}
</div>
</div>
</aside>
<div className="app-column">
<header className="mobile-header">
<Brand />
{isGuest ? (
<Link className="small-button" href="/sign-in">
Sign in
</Link>
) : (
<Link
className="avatar avatar-link"
href="/sign-in"
aria-label="Switch local role"
>
{initials(viewer.name)}
</Link>
)}
</header>
<main className="page-content">{children}</main>
<NavLinks showOperations={showOperations} />
</div>
</div>
);
}
+18
View File
@@ -0,0 +1,18 @@
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>
{!compact && (
<span className="brand-wordmark">
Arr<span>mate</span>
</span>
)}
</Link>
);
}
+58
View File
@@ -0,0 +1,58 @@
import { ArrowDown, Clock3 } from "lucide-react";
import type { DownloadItem } from "@/domain/downloads";
export function formatBytes(bytes: number): string {
if (bytes <= 0) return "0 B";
const units = ["B", "KB", "MB", "GB", "TB"];
const index = Math.min(
Math.floor(Math.log(bytes) / Math.log(1024)),
units.length - 1,
);
const value = bytes / 1024 ** index;
return `${value.toFixed(value >= 10 || index === 0 ? 0 : 1)} ${units[index]}`;
}
function formatEta(seconds: number | null): string {
if (seconds === null) return "No ETA";
if (seconds < 60) return `${seconds}s`;
if (seconds < 3600) return `${Math.ceil(seconds / 60)}m`;
return `${Math.floor(seconds / 3600)}h ${Math.ceil((seconds % 3600) / 60)}m`;
}
export function DownloadRow({ item }: { item: DownloadItem }) {
const percentage = Math.round(item.progress * 100);
return (
<article className="download-row">
<div className="download-main">
<div className="download-title-line">
<strong title={item.name}>{item.name}</strong>
<span>{percentage}%</span>
</div>
<div
className="progress-track"
aria-label={`${percentage}% downloaded`}
role="progressbar"
aria-valuemin={0}
aria-valuemax={100}
aria-valuenow={percentage}
>
<span style={{ width: `${percentage}%` }} />
</div>
<div className="download-meta">
<span className={`state-label state-${item.state}`}>
{item.state}
</span>
<span>
<ArrowDown size={13} aria-hidden="true" />
{formatBytes(item.downloadSpeedBytes)}/s
</span>
<span>
<Clock3 size={13} aria-hidden="true" />
{formatEta(item.etaSeconds)}
</span>
</div>
</div>
</article>
);
}
+25
View File
@@ -0,0 +1,25 @@
import type { LucideIcon } from "lucide-react";
import type { ReactNode } from "react";
export function EmptyState({
icon: Icon,
title,
description,
action,
}: {
icon: LucideIcon;
title: string;
description: string;
action?: ReactNode;
}) {
return (
<div className="empty-state">
<span className="empty-icon">
<Icon size={23} aria-hidden="true" />
</span>
<h3>{title}</h3>
<p>{description}</p>
{action}
</div>
);
}
+59
View File
@@ -0,0 +1,59 @@
"use client";
import { Activity, Compass, House, RadioTower, Settings2 } from "lucide-react";
import Link from "next/link";
import { usePathname } from "next/navigation";
const baseItems = [
{ href: "/", label: "Home", icon: House },
{ href: "/discover", label: "Discover", icon: Compass },
{ href: "/activity", label: "Activity", icon: Activity },
];
export function NavLinks({
showOperations,
desktop = false,
}: {
showOperations: boolean;
desktop?: boolean;
}) {
const pathname = usePathname();
const items = [
...baseItems,
...(showOperations
? [
{ href: "/operations", label: "Operations", icon: RadioTower },
...(desktop
? [{ href: "/settings", label: "Settings", icon: Settings2 }]
: []),
]
: []),
];
return (
<nav
className={desktop ? "desktop-nav" : "mobile-nav"}
aria-label="Primary navigation"
>
{items.map(({ href, label, icon: Icon }) => {
const active =
href === "/" ? pathname === href : pathname.startsWith(href);
return (
<Link
key={href}
href={href}
className={active ? "nav-link active" : "nav-link"}
aria-current={active ? "page" : undefined}
>
<Icon
aria-hidden="true"
size={desktop ? 19 : 21}
strokeWidth={active ? 2.4 : 1.8}
/>
<span>{label}</span>
</Link>
);
})}
</nav>
);
}
+32
View File
@@ -0,0 +1,32 @@
import {
CircleAlert,
CircleCheck,
CircleDashed,
TriangleAlert,
} from "lucide-react";
import type { IntegrationHealth } from "@/domain/integrations";
const statusCopy: Record<IntegrationHealth, string> = {
online: "Online",
degraded: "Needs attention",
offline: "Offline",
"not-configured": "Not connected",
};
export function StatusPill({ status }: { status: IntegrationHealth }) {
const Icon =
status === "online"
? CircleCheck
: status === "degraded"
? TriangleAlert
: status === "offline"
? CircleAlert
: CircleDashed;
return (
<span className={`status-pill status-${status}`}>
<Icon size={13} aria-hidden="true" />
{statusCopy[status]}
</span>
);
}
+24
View File
@@ -0,0 +1,24 @@
import "server-only";
import { drizzle } from "drizzle-orm/postgres-js";
import postgres from "postgres";
import * as schema from "./schema";
let client: ReturnType<typeof postgres> | undefined;
export function database() {
const url = process.env.DATABASE_URL;
if (!url) throw new Error("DATABASE_URL is required for database operations");
client ??= postgres(url, {
max: 10,
idle_timeout: 20,
connect_timeout: 10,
});
return drizzle(client, { schema });
}
export function sqlClient() {
database();
return client!;
}
+104
View File
@@ -0,0 +1,104 @@
import "server-only";
import type { QuotaReservation, QuotaStore } from "@/domain/quota";
import type { MediaType } from "@/domain/requests";
import { sqlClient } from "./client";
class QuotaBlocked extends Error {
constructor(
readonly resetAt: Date,
readonly window: "hour" | "day",
) {
super("Request quota reached");
}
}
function bucket(now: Date, window: "hour" | "day") {
const startedAt = new Date(now);
startedAt.setUTCMinutes(0, 0, 0);
if (window === "day") startedAt.setUTCHours(0);
const resetAt = new Date(startedAt);
if (window === "hour") resetAt.setUTCHours(resetAt.getUTCHours() + 1);
else resetAt.setUTCDate(resetAt.getUTCDate() + 1);
return { startedAt, resetAt };
}
/** Atomically increments every active quota window in one SQL transaction. */
export class PostgresQuotaStore implements QuotaStore {
async reserve(
userId: string,
mediaType: MediaType,
now = new Date(),
): Promise<QuotaReservation> {
const sql = sqlClient();
try {
return await sql.begin(async (transaction) => {
const limits = await transaction<
{ window: "hour" | "day"; maximum: number }[]
>`
select window, maximum
from request_limits
where user_id = ${userId} and media_type = ${mediaType}
order by window asc
`;
if (limits.length === 0) {
const { resetAt } = bucket(now, "day");
return {
allowed: true,
remaining: Number.POSITIVE_INFINITY,
resetsAt: resetAt,
limitingWindow: "day" as const,
};
}
const reservations: {
window: "hour" | "day";
maximum: number;
used: number;
resetAt: Date;
}[] = [];
for (const limit of limits) {
const { startedAt, resetAt } = bucket(now, limit.window);
if (limit.maximum <= 0) throw new QuotaBlocked(resetAt, limit.window);
const rows = await transaction<{ used: number }[]>`
insert into quota_usage (user_id, media_type, window, window_started_at, used)
values (${userId}, ${mediaType}, ${limit.window}, ${startedAt}, 1)
on conflict (user_id, media_type, window, window_started_at)
do update set used = quota_usage.used + 1
where quota_usage.used < ${limit.maximum}
returning used
`;
if (rows.length === 0) throw new QuotaBlocked(resetAt, limit.window);
reservations.push({ ...limit, used: rows[0].used, resetAt });
}
const limiting = reservations.reduce((current, candidate) =>
candidate.maximum - candidate.used < current.maximum - current.used
? candidate
: current,
);
return {
allowed: true,
remaining: limiting.maximum - limiting.used,
resetsAt: limiting.resetAt,
limitingWindow: limiting.window,
};
});
} catch (error) {
if (error instanceof QuotaBlocked) {
return {
allowed: false,
remaining: 0,
resetsAt: error.resetAt,
limitingWindow: error.window,
};
}
throw error;
}
}
}
+180
View File
@@ -0,0 +1,180 @@
import {
boolean,
index,
integer,
jsonb,
pgEnum,
pgTable,
primaryKey,
text,
timestamp,
uniqueIndex,
uuid,
} from "drizzle-orm/pg-core";
export const roleEnum = pgEnum("role", [
"owner",
"maintainer",
"requester",
"guest",
]);
export const mediaTypeEnum = pgEnum("media_type", ["movie", "series"]);
export const quotaWindowEnum = pgEnum("quota_window", ["hour", "day"]);
export const requestStatusEnum = pgEnum("request_status", [
"pending",
"approved",
"available",
"declined",
"failed",
]);
export const integrationHealthEnum = pgEnum("integration_health", [
"online",
"degraded",
"offline",
"not-configured",
]);
export const auditOutcomeEnum = pgEnum("audit_outcome", [
"success",
"denied",
"failed",
]);
export const users = pgTable(
"users",
{
id: uuid("id").defaultRandom().primaryKey(),
email: text("email").notNull(),
displayName: text("display_name").notNull(),
role: roleEnum("role").notNull().default("requester"),
active: boolean("active").notNull().default(true),
createdAt: timestamp("created_at", { withTimezone: true })
.notNull()
.defaultNow(),
updatedAt: timestamp("updated_at", { withTimezone: true })
.notNull()
.defaultNow(),
},
(table) => [uniqueIndex("users_email_unique").on(table.email)],
);
export const requestLimits = pgTable(
"request_limits",
{
id: uuid("id").defaultRandom().primaryKey(),
userId: uuid("user_id")
.notNull()
.references(() => users.id, { onDelete: "cascade" }),
mediaType: mediaTypeEnum("media_type").notNull(),
window: quotaWindowEnum("window").notNull(),
maximum: integer("maximum").notNull(),
updatedAt: timestamp("updated_at", { withTimezone: true })
.notNull()
.defaultNow(),
},
(table) => [
uniqueIndex("request_limits_scope_unique").on(
table.userId,
table.mediaType,
table.window,
),
],
);
export const quotaUsage = pgTable(
"quota_usage",
{
userId: uuid("user_id")
.notNull()
.references(() => users.id, { onDelete: "cascade" }),
mediaType: mediaTypeEnum("media_type").notNull(),
window: quotaWindowEnum("window").notNull(),
windowStartedAt: timestamp("window_started_at", {
withTimezone: true,
}).notNull(),
used: integer("used").notNull().default(0),
},
(table) => [
primaryKey({
name: "quota_usage_scope_pk",
columns: [
table.userId,
table.mediaType,
table.window,
table.windowStartedAt,
],
}),
],
);
export const mediaRequests = pgTable(
"media_requests",
{
id: uuid("id").defaultRandom().primaryKey(),
requestedBy: uuid("requested_by")
.notNull()
.references(() => users.id, { onDelete: "restrict" }),
mediaType: mediaTypeEnum("media_type").notNull(),
externalId: text("external_id").notNull(),
title: text("title").notNull(),
status: requestStatusEnum("status").notNull().default("pending"),
createdAt: timestamp("created_at", { withTimezone: true })
.notNull()
.defaultNow(),
updatedAt: timestamp("updated_at", { withTimezone: true })
.notNull()
.defaultNow(),
},
(table) => [
index("media_requests_user_created_idx").on(
table.requestedBy,
table.createdAt,
),
uniqueIndex("media_requests_user_media_unique").on(
table.requestedBy,
table.mediaType,
table.externalId,
),
],
);
export const integrations = pgTable(
"integrations",
{
id: uuid("id").defaultRandom().primaryKey(),
name: text("name").notNull(),
kind: text("kind").notNull(),
baseUrl: text("base_url").notNull(),
encryptedCredential: text("encrypted_credential").notNull(),
health: integrationHealthEnum("health").notNull().default("not-configured"),
capabilities: jsonb("capabilities").notNull().default({}),
lastCheckedAt: timestamp("last_checked_at", { withTimezone: true }),
createdAt: timestamp("created_at", { withTimezone: true })
.notNull()
.defaultNow(),
updatedAt: timestamp("updated_at", { withTimezone: true })
.notNull()
.defaultNow(),
},
(table) => [uniqueIndex("integrations_name_unique").on(table.name)],
);
export const auditEvents = pgTable(
"audit_events",
{
id: uuid("id").defaultRandom().primaryKey(),
actorId: uuid("actor_id").references(() => users.id, {
onDelete: "set null",
}),
action: text("action").notNull(),
targetType: text("target_type").notNull(),
targetId: text("target_id").notNull(),
outcome: auditOutcomeEnum("outcome").notNull(),
metadata: jsonb("metadata").notNull().default({}),
createdAt: timestamp("created_at", { withTimezone: true })
.notNull()
.defaultNow(),
},
(table) => [
index("audit_events_actor_created_idx").on(table.actorId, table.createdAt),
],
);
+36
View File
@@ -0,0 +1,36 @@
import { describe, expect, it } from "vitest";
import type { Role, Viewer } from "./auth";
import { AuthorizationError, authorize, can } from "./auth";
const viewer = (role: Role): Viewer => ({ id: role, name: role, role });
describe("role authorization", () => {
it("gives the owner administrative and destructive permissions", () => {
expect(can(viewer("owner"), "integration:manage")).toBe(true);
expect(can(viewer("owner"), "user:manage")).toBe(true);
expect(can(viewer("owner"), "media:delete")).toBe(true);
});
it("lets maintainers operate media without changing security", () => {
expect(can(viewer("maintainer"), "download:manage")).toBe(true);
expect(can(viewer("maintainer"), "media:replace")).toBe(true);
expect(can(viewer("maintainer"), "integration:manage")).toBe(false);
expect(can(viewer("maintainer"), "security:manage")).toBe(false);
});
it("limits requester and guest sessions to their request surface", () => {
for (const role of ["requester", "guest"] as const) {
expect(can(viewer(role), "discovery:search")).toBe(true);
expect(can(viewer(role), "request:create")).toBe(true);
expect(can(viewer(role), "operations:view")).toBe(false);
expect(can(viewer(role), "media:delete")).toBe(false);
}
});
it("throws a typed error when a server mutation is denied", () => {
expect(() => authorize(viewer("guest"), "integration:manage")).toThrow(
AuthorizationError,
);
});
});
+78
View File
@@ -0,0 +1,78 @@
export const roles = ["owner", "maintainer", "requester", "guest"] as const;
export type Role = (typeof roles)[number];
export const permissions = [
"dashboard:view",
"operations:view",
"discovery:search",
"request:create",
"request:view-own",
"download:manage",
"media:delete",
"media:replace",
"subtitle:search",
"integration:manage",
"user:manage",
"quota:manage",
"audit:view",
"security:manage",
] as const;
export type Permission = (typeof permissions)[number];
export interface Viewer {
id: string;
name: string;
role: Role;
}
const everyPermission = new Set<Permission>(permissions);
const rolePermissions: Record<Role, ReadonlySet<Permission>> = {
owner: everyPermission,
maintainer: new Set([
"dashboard:view",
"operations:view",
"discovery:search",
"request:create",
"request:view-own",
"download:manage",
"media:delete",
"media:replace",
"subtitle:search",
"audit:view",
]),
requester: new Set([
"dashboard:view",
"discovery:search",
"request:create",
"request:view-own",
"subtitle:search",
]),
guest: new Set([
"dashboard:view",
"discovery:search",
"request:create",
"request:view-own",
]),
};
export class AuthorizationError extends Error {
readonly code = "FORBIDDEN";
constructor(permission: Permission) {
super(`Permission required: ${permission}`);
this.name = "AuthorizationError";
}
}
export function can(viewer: Viewer, permission: Permission): boolean {
return rolePermissions[viewer.role].has(permission);
}
export function authorize(viewer: Viewer, permission: Permission): void {
if (!can(viewer, permission)) {
throw new AuthorizationError(permission);
}
}
+36
View File
@@ -0,0 +1,36 @@
export type DownloadState =
| "downloading"
| "queued"
| "paused"
| "seeding"
| "checking"
| "stalled"
| "error"
| "complete"
| "unknown";
export interface DownloadItem {
id: string;
name: string;
progress: number;
state: DownloadState;
downloadSpeedBytes: number;
uploadSpeedBytes: number;
sizeBytes: number;
etaSeconds: number | null;
ratio: number;
category: string | null;
}
export interface TransferStats {
downloadSpeedBytes: number;
uploadSpeedBytes: number;
downloadedBytes: number;
uploadedBytes: number;
}
export interface DownloadOverview {
items: DownloadItem[];
transfer: TransferStats;
fetchedAt: Date;
}
+49
View File
@@ -0,0 +1,49 @@
export const integrationKinds = [
"media-server",
"media-manager",
"indexer",
"subtitle-provider",
"request-manager",
"download-client",
] as const;
export type IntegrationKind = (typeof integrationKinds)[number];
export type IntegrationHealth =
"online" | "degraded" | "offline" | "not-configured";
export type AdapterErrorCode =
| "not-configured"
| "authentication"
| "timeout"
| "unreachable"
| "malformed-response"
| "upstream";
export interface AdapterError {
code: AdapterErrorCode;
message: string;
retryable: boolean;
}
export type AdapterResult<T> =
{ ok: true; data: T } | { ok: false; error: AdapterError };
export interface IntegrationSummary {
id: string;
name: string;
kind: IntegrationKind;
health: IntegrationHealth;
detail: string;
latencyMs?: number;
checkedAt?: Date;
}
export interface CapabilitySet {
readQueue: boolean;
manageQueue: boolean;
search: boolean;
request: boolean;
deleteMedia: boolean;
replaceMedia: boolean;
searchSubtitles: boolean;
}
+49
View File
@@ -0,0 +1,49 @@
import { describe, expect, it } from "vitest";
import { InMemoryQuotaStore } from "./quota";
describe("quota reservations", () => {
it("blocks after the configured limit and returns the reset", async () => {
const store = new InMemoryQuotaStore([
{ userId: "friend", mediaType: "movie", window: "day", maximum: 2 },
]);
const now = new Date("2026-08-16T12:30:00.000Z");
expect(await store.reserve("friend", "movie", now)).toMatchObject({
allowed: true,
remaining: 1,
});
expect(await store.reserve("friend", "movie", now)).toMatchObject({
allowed: true,
remaining: 0,
});
expect(await store.reserve("friend", "movie", now)).toMatchObject({
allowed: false,
remaining: 0,
resetsAt: new Date("2026-08-17T00:00:00.000Z"),
});
});
it("enforces movie and series limits independently", async () => {
const store = new InMemoryQuotaStore([
{ userId: "friend", mediaType: "movie", window: "hour", maximum: 1 },
{ userId: "friend", mediaType: "series", window: "hour", maximum: 1 },
]);
expect((await store.reserve("friend", "movie")).allowed).toBe(true);
expect((await store.reserve("friend", "movie")).allowed).toBe(false);
expect((await store.reserve("friend", "series")).allowed).toBe(true);
});
it("does not oversubscribe a bucket during concurrent double submits", async () => {
const store = new InMemoryQuotaStore([
{ userId: "friend", mediaType: "movie", window: "hour", maximum: 3 },
]);
const attempts = await Promise.all(
Array.from({ length: 12 }, () => store.reserve("friend", "movie")),
);
expect(attempts.filter((attempt) => attempt.allowed)).toHaveLength(3);
expect(attempts.filter((attempt) => !attempt.allowed)).toHaveLength(9);
});
});
+104
View File
@@ -0,0 +1,104 @@
import type { MediaType, RequestLimit } from "./requests";
export interface QuotaReservation {
allowed: boolean;
remaining: number;
resetsAt: Date;
limitingWindow: "hour" | "day";
}
export interface QuotaStore {
reserve(
userId: string,
mediaType: MediaType,
now?: Date,
): Promise<QuotaReservation>;
}
interface Bucket {
used: number;
resetAt: Date;
}
function windowStart(now: Date, window: "hour" | "day"): Date {
const start = new Date(now);
start.setUTCMinutes(0, 0, 0);
if (window === "day") start.setUTCHours(0);
return start;
}
function nextWindow(start: Date, window: "hour" | "day"): Date {
const reset = new Date(start);
if (window === "hour") reset.setUTCHours(reset.getUTCHours() + 1);
else reset.setUTCDate(reset.getUTCDate() + 1);
return reset;
}
/**
* A deterministic development/test repository. Production uses the SQL
* repository so quota increments and request creation share one transaction.
*/
export class InMemoryQuotaStore implements QuotaStore {
private readonly buckets = new Map<string, Bucket>();
constructor(private readonly limits: RequestLimit[]) {}
async reserve(
userId: string,
mediaType: MediaType,
now = new Date(),
): Promise<QuotaReservation> {
const active = this.limits.filter(
(limit) => limit.userId === userId && limit.mediaType === mediaType,
);
if (active.length === 0) {
return {
allowed: true,
remaining: Number.POSITIVE_INFINITY,
resetsAt: nextWindow(windowStart(now, "day"), "day"),
limitingWindow: "day",
};
}
const states = active.map((limit) => {
const start = windowStart(now, limit.window);
const key = `${userId}:${mediaType}:${limit.window}:${start.toISOString()}`;
const bucket = this.buckets.get(key) ?? {
used: 0,
resetAt: nextWindow(start, limit.window),
};
return { limit, key, bucket };
});
const blocked = states.find(
({ limit, bucket }) => bucket.used >= limit.maximum,
);
if (blocked) {
return {
allowed: false,
remaining: 0,
resetsAt: blocked.bucket.resetAt,
limitingWindow: blocked.limit.window,
};
}
for (const { key, bucket } of states) {
this.buckets.set(key, { ...bucket, used: bucket.used + 1 });
}
const limiting = states.reduce((current, candidate) => {
const currentRemaining = current.limit.maximum - current.bucket.used - 1;
const candidateRemaining =
candidate.limit.maximum - candidate.bucket.used - 1;
return candidateRemaining < currentRemaining ? candidate : current;
});
return {
allowed: true,
remaining: limiting.limit.maximum - limiting.bucket.used - 1,
resetsAt: limiting.bucket.resetAt,
limitingWindow: limiting.limit.window,
};
}
}
+39
View File
@@ -0,0 +1,39 @@
export const mediaTypes = ["movie", "series"] as const;
export type MediaType = (typeof mediaTypes)[number];
export const requestStatuses = [
"pending",
"approved",
"available",
"declined",
"failed",
] as const;
export type RequestStatus = (typeof requestStatuses)[number];
export interface MediaRequest {
id: string;
requestedBy: string;
mediaType: MediaType;
externalId: string;
title: string;
status: RequestStatus;
createdAt: Date;
}
export interface RequestLimit {
userId: string;
mediaType: MediaType;
window: "hour" | "day";
maximum: number;
}
export interface AuditEvent {
id: string;
actorId: string;
action: string;
targetType: string;
targetId: string;
outcome: "success" | "denied" | "failed";
metadata: Record<string, string | number | boolean | null>;
createdAt: Date;
}
+103
View File
@@ -0,0 +1,103 @@
import "server-only";
import { createHmac, timingSafeEqual } from "node:crypto";
import { cookies } from "next/headers";
import type { Role, Viewer } from "@/domain/auth";
import { roles } from "@/domain/auth";
const COOKIE_NAME = "arrmate-dev-session";
const developmentViewers: Record<Role, Viewer> = {
owner: {
id: "00000000-0000-4000-8000-000000000001",
name: "Zeb",
role: "owner",
},
maintainer: {
id: "00000000-0000-4000-8000-000000000002",
name: "Media maintainer",
role: "maintainer",
},
requester: {
id: "00000000-0000-4000-8000-000000000003",
name: "Friend account",
role: "requester",
},
guest: {
id: "00000000-0000-4000-8000-000000000004",
name: "Guest",
role: "guest",
},
};
function key(): string {
const configured = process.env.AUTH_SECRET;
if (configured) return configured;
if (process.env.NODE_ENV !== "production")
return "arrmate-development-only-session-key";
throw new Error("AUTH_SECRET is required in production");
}
function signature(payload: string): string {
return createHmac("sha256", key()).update(payload).digest("base64url");
}
function encode(role: Role): string {
const payload = Buffer.from(JSON.stringify({ role, version: 1 })).toString(
"base64url",
);
return `${payload}.${signature(payload)}`;
}
function decode(token: string): Role | null {
const [payload, provided] = token.split(".");
if (!payload || !provided) return null;
const expected = signature(payload);
const expectedBytes = Buffer.from(expected);
const providedBytes = Buffer.from(provided);
if (
expectedBytes.length !== providedBytes.length ||
!timingSafeEqual(expectedBytes, providedBytes)
) {
return null;
}
try {
const value = JSON.parse(Buffer.from(payload, "base64url").toString()) as {
role?: unknown;
};
return roles.includes(value.role as Role) ? (value.role as Role) : null;
} catch {
return null;
}
}
export function developmentAuthEnabled(): boolean {
return (
process.env.NODE_ENV !== "production" ||
process.env.ARRMATE_ENABLE_DEV_AUTH === "true"
);
}
export async function getViewer(): Promise<Viewer> {
const token = (await cookies()).get(COOKIE_NAME)?.value;
const role = token ? decode(token) : null;
return developmentViewers[role ?? "guest"];
}
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), {
httpOnly: true,
sameSite: "lax",
secure: process.env.NODE_ENV === "production",
path: "/",
maxAge: 60 * 60 * 12,
});
}
export async function clearDevelopmentViewer(): Promise<void> {
(await cookies()).delete(COOKIE_NAME);
}
+27
View File
@@ -0,0 +1,27 @@
import "server-only";
import { QbittorrentAdapter } from "@/adapters/qbittorrent";
export function qBittorrentFromEnvironment(): QbittorrentAdapter | null {
const { QBITTORRENT_URL, QBITTORRENT_USERNAME, QBITTORRENT_PASSWORD } =
process.env;
if (!QBITTORRENT_URL || !QBITTORRENT_USERNAME || !QBITTORRENT_PASSWORD)
return null;
if (
[QBITTORRENT_USERNAME, QBITTORRENT_PASSWORD].some(
(value) => value === "replace-me",
)
) {
return null;
}
const parsedTimeout = Number(process.env.INTEGRATION_REQUEST_TIMEOUT_MS);
return new QbittorrentAdapter({
baseUrl: QBITTORRENT_URL,
username: QBITTORRENT_USERNAME,
password: QBITTORRENT_PASSWORD,
timeoutMs:
Number.isFinite(parsedTimeout) && parsedTimeout > 0
? parsedTimeout
: 8_000,
});
}
+115
View File
@@ -0,0 +1,115 @@
import "server-only";
import type { DownloadOverview } from "@/domain/downloads";
import type { AdapterError, IntegrationSummary } from "@/domain/integrations";
import { qBittorrentFromEnvironment } from "./integrations/qbittorrent";
export interface OperationsSnapshot {
integrations: IntegrationSummary[];
downloads: DownloadOverview | null;
downloadError: AdapterError | null;
}
const plannedIntegrations: IntegrationSummary[] = [
{
id: "jellyfin",
name: "Jellyfin",
kind: "media-server",
health: "not-configured",
detail: "Media server connection is not configured",
},
{
id: "radarr",
name: "Radarr",
kind: "media-manager",
health: "not-configured",
detail: "Movie manager connection is not configured",
},
{
id: "sonarr",
name: "Sonarr",
kind: "media-manager",
health: "not-configured",
detail: "Series manager connection is not configured",
},
{
id: "prowlarr",
name: "Prowlarr",
kind: "indexer",
health: "not-configured",
detail: "Indexer connection is not configured",
},
{
id: "bazarr",
name: "Bazarr",
kind: "subtitle-provider",
health: "not-configured",
detail: "Subtitle provider 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 checkedAt = new Date();
const latencyMs = Math.round(performance.now() - startedAt);
if (!overview.ok) {
return {
integrations: [
...plannedIntegrations,
{
id: "qbittorrent",
name: "qBittorrent",
kind: "download-client",
health:
overview.error.code === "authentication" ? "offline" : "degraded",
detail: overview.error.message,
checkedAt,
latencyMs,
},
],
downloads: null,
downloadError: overview.error,
};
}
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,
},
],
downloads: overview.data,
downloadError: null,
};
}
+37
View File
@@ -0,0 +1,37 @@
import { expect, test } from "@playwright/test";
test("guest sees the request-first home without fake activity", async ({
page,
}) => {
await page.goto("/");
await expect(
page.getByRole("heading", { name: "Find your next watch." }),
).toBeVisible();
await expect(
page.getByRole("link", { name: "Start exploring" }),
).toBeVisible();
await expect(page.getByText("Nothing waiting yet")).toBeVisible();
});
test("mobile layout does not overflow horizontally", async ({ page }) => {
await page.goto("/");
const sizes = await page.evaluate(() => ({
viewport: document.documentElement.clientWidth,
content: document.documentElement.scrollWidth,
}));
expect(sizes.content).toBeLessThanOrEqual(sizes.viewport);
await expect(
page.getByRole("navigation", { name: "Primary navigation" }),
).toBeVisible();
});
test("local owner session can open honest operations state", async ({
page,
}) => {
await page.goto("/sign-in");
await page.getByRole("button", { name: /Owner/ }).click();
await expect(page).toHaveURL(/\/operations$/);
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();
});
+33
View File
@@ -0,0 +1,33 @@
{
"compilerOptions": {
"target": "ES2022",
"lib": ["dom", "dom.iterable", "esnext"],
"allowJs": false,
"skipLibCheck": true,
"strict": true,
"noEmit": true,
"esModuleInterop": true,
"module": "esnext",
"moduleResolution": "bundler",
"resolveJsonModule": true,
"isolatedModules": true,
"jsx": "react-jsx",
"incremental": true,
"plugins": [
{
"name": "next"
}
],
"paths": {
"@/*": ["./src/*"]
}
},
"include": [
"next-env.d.ts",
"**/*.ts",
"**/*.tsx",
".next/types/**/*.ts",
".next/dev/types/**/*.ts"
],
"exclude": ["node_modules"]
}
+16
View File
@@ -0,0 +1,16 @@
import { defineConfig } from "vitest/config";
export default defineConfig({
test: {
environment: "node",
exclude: ["tests/browser/**", "node_modules/**"],
coverage: {
reporter: ["text", "html"],
},
},
resolve: {
alias: {
"@": new URL("./src", import.meta.url).pathname,
},
},
});