diff --git a/.claude/rules/external-api.md b/.claude/rules/external-api.md
index 8cef9f905..3dc1d20fb 100644
--- a/.claude/rules/external-api.md
+++ b/.claude/rules/external-api.md
@@ -4,6 +4,12 @@ paths:
- "server/routes/externalApi.js"
- "server/routes/externalRequests.js"
- "server/middleware/externalApiAuth.js"
+ - "client/src/components/ExternalRequests/**/*"
+ - "client/src/components/Configuration/sections/ApiKeysSection.tsx"
+ - "client/src/components/Configuration/sections/ApiKeysSection/**/*"
+ - "client/src/types/externalRequest.ts"
+ - "client/src/utils/externalRatingPolicy.ts"
+ - "client/src/utils/__tests__/externalRatingPolicy.test.ts"
---
# External API
@@ -20,5 +26,6 @@ The opt-in `/external-api/v1` surface for external tools: catalog reads and down
- The executor rechecks authority, claims `approved` -> `processing`, queues downloads through `downloadModule.doSpecificDownloads` with the request id as the job id, provisions, enables and grants channels, and deletes videos through `videoDeletionModule`.
- It holds requests with a message while downloads are paused or the video is busy, and recovers interrupted rows at startup.
- `externalRequestTargets.js` validates grant, channel, video and policy targets; `externalRequestReconciliation.js` closes processing video requests whose job ended; `externalRequestPrimitives.js` shares validation and DTOs.
-- Key-before-request locks serialize decisions; `externalWorkLimiter.js` bounds expensive work. `routes/externalRequests.js` exposes admin management endpoints that reject every API key; their UI is a separate follow-up.
+- Key-before-request locks serialize decisions; `externalWorkLimiter.js` bounds expensive work. `routes/externalRequests.js` exposes admin management endpoints that reject every API key; their UI lives in `client/src/components/ExternalRequests/`.
+- Grant replacement (`replaceChannelGrants`) touches only grants on enabled, non-terminated channels, the set the editor sees; a grant on a disabled channel stays dormant so re-enabling the channel restores it.
- External API jobs never use the cookies' membership: `doSpecificDownloads` keeps the members-only filter for the `(external request)` label or an `externalRequest: true` job flag, which `enqueueAutoRetryJob` copies onto its retries because their `Auto-retry:` label drops the source.
diff --git a/CLAUDE.md b/CLAUDE.md
index 292fa9383..6fa00d91f 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -54,7 +54,7 @@ For multi-part requests (e.g., "review this PR AND explain WebSocket handling"),
### Frontend (`client/src/`)
- `App.tsx`: routing plus the global `fetch()` override and axios response interceptor that turn a 503 `requiresDbFix` response into the database error overlay.
-- `components/`: one directory per feature (`Subscriptions/`, `ChannelPage/`, `PlaylistPage/`, `VideosPage/`, `FindVideos/`, `FindChannels/`, `DownloadManager/`, `SubscriptionImport/`, `Settings/` + `Configuration/`); `components/shared/` for cross-feature pieces (`VideoModal/`, `DeleteVideosDialog`, `AddChannelDialog`); `components/ui/` for theme-neutral primitives; `components/layout/` for the app shell and nav.
+- `components/`: one directory per feature (`Subscriptions/`, `ChannelPage/`, `PlaylistPage/`, `VideosPage/`, `FindVideos/`, `FindChannels/`, `DownloadManager/`, `SubscriptionImport/`, `Settings/` + `Configuration/`, `ExternalRequests/`); `components/shared/` for cross-feature pieces (`VideoModal/`, `DeleteVideosDialog`, `AddChannelDialog`); `components/ui/` for theme-neutral primitives; `components/layout/` for the app shell and nav.
- `hooks/`, `contexts/`, `providers/` (auth token, WebSocket, theme, video activity), `themes/` (the `ALL_THEMES` registry), `config/` (the `CONFIG_FIELDS` registry), `types/`, `utils/`.
### Database
diff --git a/client/src/App.test.tsx b/client/src/App.test.tsx
index 9804af197..9a32b4be4 100644
--- a/client/src/App.test.tsx
+++ b/client/src/App.test.tsx
@@ -83,6 +83,15 @@ jest.mock('./components/ChannelPage', () => {
};
});
+jest.mock('./components/Settings/Settings', () => ({
+ Settings: () =>
Settings Component
,
+}));
+
+jest.mock('./components/ExternalRequests/RequestsPage', () => ({
+ __esModule: true,
+ default: () => Requests Component
,
+}));
+
jest.mock('./components/ChangelogPage', () => {
return function ChangelogPage() {
return Changelog Page Component
;
@@ -171,6 +180,7 @@ Object.defineProperty(window, 'matchMedia', {
beforeEach(() => {
jest.clearAllMocks();
setMockLocation('http://localhost/');
+ window.history.replaceState({}, '', '/');
// Re-apply matchMedia mock - resetMocks:true in jest.config.cjs clears implementations
Object.defineProperty(window, 'matchMedia', {
writable: true,
@@ -533,6 +543,69 @@ describe('App Component', () => {
// ElfHosted platform sets token via platform-managed auth
});
+ test('redirects direct Requests navigation when external API is disabled', async () => {
+ localStorageMock.getItem.mockReturnValue('test-token');
+ window.history.replaceState({}, '', '/requests');
+ (global.fetch as jest.Mock).mockImplementation((url) => {
+ if (url === '/getconfig') {
+ return Promise.resolve({
+ ok: true,
+ json: async () => ({ isPlatformManaged: { externalApiEnabled: false } }),
+ });
+ }
+ if (url === '/api/db-status') {
+ return Promise.resolve({ ok: true, json: async () => ({ status: 'healthy' }) });
+ }
+ if (url === '/setup/status') {
+ return Promise.resolve({ ok: true, json: async () => ({ requiresSetup: false }) });
+ }
+ if (url === '/auth/validate') {
+ return Promise.resolve({ ok: true, json: async () => ({}) });
+ }
+ return Promise.resolve({ ok: true, json: async () => ({}) });
+ });
+
+ render( );
+
+ await waitFor(() => {
+ expect(screen.getByTestId('settings-page')).toBeInTheDocument();
+ });
+ expect(screen.queryByTestId('requests-page')).not.toBeInTheDocument();
+ });
+
+ test('waits for the config before deciding whether to open Requests', async () => {
+ localStorageMock.getItem.mockReturnValue('test-token');
+ window.history.replaceState({}, '', '/requests');
+ let resolveConfig: (value: unknown) => void = () => undefined;
+ (global.fetch as jest.Mock).mockImplementation((url) => {
+ if (url === '/getconfig') {
+ return new Promise((resolve) => { resolveConfig = resolve; });
+ }
+ if (url === '/api/db-status') {
+ return Promise.resolve({ ok: true, json: async () => ({ status: 'healthy' }) });
+ }
+ if (url === '/setup/status') {
+ return Promise.resolve({ ok: true, json: async () => ({ requiresSetup: false }) });
+ }
+ return Promise.resolve({ ok: true, json: async () => ({}) });
+ });
+
+ render( );
+
+ await waitFor(() => {
+ expect(global.fetch).toHaveBeenCalledWith('/getconfig', expect.anything());
+ });
+ expect(screen.queryByTestId('settings-page')).not.toBeInTheDocument();
+
+ resolveConfig({
+ ok: true,
+ json: async () => ({ isPlatformManaged: { externalApiEnabled: true } }),
+ });
+
+ expect(await screen.findByTestId('requests-page')).toBeInTheDocument();
+ expect(screen.queryByTestId('settings-page')).not.toBeInTheDocument();
+ });
+
test('renders authenticated pages when user has token', async () => {
localStorageMock.getItem.mockReturnValue('test-token');
diff --git a/client/src/App.tsx b/client/src/App.tsx
index 83667dc25..aa160876b 100644
--- a/client/src/App.tsx
+++ b/client/src/App.tsx
@@ -32,6 +32,7 @@ import InitialSetup from './components/InitialSetup';
import ChannelPage from './components/ChannelPage';
import PlaylistPage from './components/PlaylistPage';
import ImportSubscriptionsPage from './components/SubscriptionImport';
+import RequestsPage from './components/ExternalRequests/RequestsPage';
import ChangelogPage from './components/ChangelogPage';
import { AuthSplash } from './components/AuthSplash';
import { useConfig } from './hooks/useConfig';
@@ -83,10 +84,20 @@ function AppContent() {
const [dbErrors, setDbErrors] = useState([]);
const [dbRecovered, setDbRecovered] = useState(false);
const [countdown, setCountdown] = useState(15);
+ const [requestsNavLinkPreview, setRequestsNavLinkPreview] = useState(null);
const location = useLocation();
// Use config hook for global configuration access
- const { config: appConfig, deploymentEnvironment } = useConfig(token);
+ const {
+ config: appConfig,
+ initialConfig: loadedConfig,
+ error: configError,
+ isPlatformManaged: platformManagedConfig,
+ deploymentEnvironment,
+ } = useConfig(token);
+ // externalApiEnabled reads false until /getconfig answers, so routes gated on
+ // it wait for the config instead of redirecting a reload or bookmark.
+ const configResolved = loadedConfig !== null || configError !== null;
const { version } = packageJson;
const clientVersion = `v${version}`; // Create a version with 'v' prefix for comparison
const tmpDirectory = '/tmp';
@@ -541,6 +552,7 @@ function AppContent() {
serverVersion={serverVersion}
ytDlpUpdateAvailable={ytDlpUpdateAvailable}
ytDlpUpdateTooltip={ytDlpUpdateTooltip}
+ showRequestsNavLink={platformManagedConfig.externalApiEnabled && (requestsNavLinkPreview ?? appConfig.showRequestsNavLink)}
onLogout={handleLogout}
>
}
/>
- } />
+
+ }
+ />
} />
} />
} />
@@ -564,6 +584,7 @@ function AppContent() {
} />
} />
} />
+ : } />
} />
} />
} />
diff --git a/client/src/components/ChannelPage/__tests__/ChannelSettingsDialog.test.tsx b/client/src/components/ChannelPage/__tests__/ChannelSettingsDialog.test.tsx
index f5951670f..480757259 100644
--- a/client/src/components/ChannelPage/__tests__/ChannelSettingsDialog.test.tsx
+++ b/client/src/components/ChannelPage/__tests__/ChannelSettingsDialog.test.tsx
@@ -79,7 +79,8 @@ describe('ChannelSettingsDialog', () => {
plexUrl: false,
authEnabled: true,
useTmpForDownloads: false,
- ytdlpUpdates: false
+ ytdlpUpdates: false,
+ externalApiEnabled: false
},
deploymentEnvironment: {
platform: null,
@@ -362,7 +363,8 @@ describe('ChannelSettingsDialog', () => {
plexUrl: false,
authEnabled: true,
useTmpForDownloads: false,
- ytdlpUpdates: false
+ ytdlpUpdates: false,
+ externalApiEnabled: false
},
deploymentEnvironment: {
platform: null,
diff --git a/client/src/components/Configuration/sections/ApiKeysSection.tsx b/client/src/components/Configuration/sections/ApiKeysSection.tsx
index 7b6ffc1ea..8f4c1041a 100644
--- a/client/src/components/Configuration/sections/ApiKeysSection.tsx
+++ b/client/src/components/Configuration/sections/ApiKeysSection.tsx
@@ -1,254 +1,185 @@
-import React, { useState, useEffect, useCallback } from 'react';
+import React, { useState, useEffect, useCallback, useRef } from 'react';
import {
- Box,
Typography,
- Button,
- Table,
- TableBody,
- TableCell,
- TableContainer,
- TableHead,
- TableRow,
- Paper,
- IconButton,
- TextField,
- Dialog,
- DialogTitle,
- DialogContent,
- DialogActions,
Alert,
- Tooltip,
- Chip,
Skeleton,
Snackbar,
Divider,
- Checkbox,
- FormControlLabel,
} from '../../ui';
-import { Trash2 as DeleteIcon, Plus as AddIcon, Copy as ContentCopyIcon, AlertTriangle as WarningIcon } from 'lucide-react';
+import { Warning as WarningIcon } from '../../../lib/icons';
import { ConfigurationAccordion } from '../common/ConfigurationAccordion';
-import { InfoTooltip } from '../common/InfoTooltip';
import { locationUtils } from '../../../utils/location';
-
-interface ApiKey {
- id: number;
- name: string;
- key_prefix: string;
- created_at: string;
- last_used_at: string | null;
- is_active: boolean;
- revoked_at?: string | null;
- usage_count: number;
- role?: string;
-}
-
-interface ApiKeyCreatedResponse {
- success: boolean;
- message: string;
- id: number;
- name: string;
- key: string;
- prefix: string;
+import BookmarkletKeysSection from './ApiKeysSection/BookmarkletKeysSection';
+import ConfirmKeyActionDialog from './ApiKeysSection/ConfirmKeyActionDialog';
+import CreateKeyDialog from './ApiKeysSection/CreateKeyDialog';
+import CreatedKeyDialog from './ApiKeysSection/CreatedKeyDialog';
+import EditKeyDialog from './ApiKeysSection/EditKeyDialog';
+import ExternalKeysSection from './ApiKeysSection/ExternalKeysSection';
+import { apiKeyError } from './ApiKeysSection/apiKeyError';
+import {
+ ApiKey,
+ ApiKeyRole,
+ ApiKeyCreatedResponse,
+ isSimpleKeyRole,
+ useApiKeys,
+} from './ApiKeysSection/useApiKeys';
+
+const SECTION_TITLE = 'API Keys & Bookmarklet';
+
+interface CreatedKey {
+ key: ApiKeyCreatedResponse;
+ role: ApiKeyRole;
+ action: 'created' | 'regenerated';
}
-interface CreatedKey extends ApiKeyCreatedResponse {
- isStatusKey: boolean;
+// The key a revoke or regenerate confirmation is for; a revoke needs only its id and name.
+interface KeyConfirm {
+ key: (Pick & Partial>) | null;
+ busy: boolean;
}
-const STATUS_READ_ROLE = 'status_read';
-const DOWNLOAD_ROLE = 'legacy_download';
-
-const keyTypeLabel = (role?: string) => {
- if (role === STATUS_READ_ROLE) return 'Read-only status';
- if (!role || role === DOWNLOAD_ROLE) return 'Download';
- return 'External';
-};
+const CLOSED_CONFIRM: KeyConfirm = { key: null, busy: false };
interface ApiKeysSectionProps {
token: string | null;
apiKeyRateLimit: number;
onRateLimitChange: (value: number) => void;
+ externalApiEnabled?: boolean;
+ showRequestsNavLink: boolean;
+ onShowRequestsNavLinkChange: (value: boolean) => void;
}
-const ApiKeysSection: React.FC = ({ token, apiKeyRateLimit, onRateLimitChange }) => {
+const ApiKeysSection: React.FC = ({
+ token,
+ apiKeyRateLimit,
+ onRateLimitChange,
+ externalApiEnabled = false,
+ showRequestsNavLink,
+ onShowRequestsNavLinkChange,
+}) => {
const [apiKeys, setApiKeys] = useState([]);
const [loading, setLoading] = useState(true);
- const [createDialogOpen, setCreateDialogOpen] = useState(false);
- const [createdKeyDialogOpen, setCreatedKeyDialogOpen] = useState(false);
- const [newKeyName, setNewKeyName] = useState('');
- const [newKeyIsStatus, setNewKeyIsStatus] = useState(false);
- const [createdKey, setCreatedKey] = useState(null);
+ // The key type whose create dialog is open, or null when it is closed.
+ const [createKeyType, setCreateKeyType] = useState<'external' | 'legacy' | null>(null);
+ // The one-time secret on show, with how it came about.
+ const [created, setCreated] = useState(null);
const [error, setError] = useState(null);
+ const [editKey, setEditKey] = useState(null);
+ const apiKeyApi = useApiKeys(token);
const [snackbar, setSnackbar] = useState({ open: false, message: '' });
- const [deleteConfirmDialog, setDeleteConfirmDialog] = useState<{ open: boolean; keyId: number | null; keyName: string }>({
- open: false,
- keyId: null,
- keyName: '',
- });
- const [isHttpWarning] = useState(
- locationUtils.getProtocol() !== 'https:' && locationUtils.getHostname() !== 'localhost'
- );
-
+ const [revokeConfirm, setRevokeConfirm] = useState(CLOSED_CONFIRM);
+ const [regenerateConfirm, setRegenerateConfirm] = useState(CLOSED_CONFIRM);
+ const isHttpWarning =
+ locationUtils.getProtocol() !== 'https:' && locationUtils.getHostname() !== 'localhost';
+
+ const loadSequence = useRef(0);
+ const sessionSequence = useRef(0);
+ const mutationBusy = useRef(false);
const fetchApiKeys = useCallback(async () => {
- if (!token) return;
-
+ const sequence = ++loadSequence.current;
try {
- const response = await fetch('/api/keys', {
- headers: { 'x-access-token': token },
- });
-
- if (response.ok) {
- const data = await response.json();
- setApiKeys((data.keys || []).filter((key: ApiKey) => !key.revoked_at));
- } else {
- const errData = await response.json();
- setError(errData.error || 'Failed to fetch API keys');
- }
+ const keys = await apiKeyApi.fetchApiKeys();
+ if (sequence === loadSequence.current) { setApiKeys(keys); setError(null); }
} catch (err) {
- setError('Failed to fetch API keys');
+ if (sequence === loadSequence.current) setError(apiKeyError(err, 'Failed to fetch API keys'));
} finally {
- setLoading(false);
+ if (sequence === loadSequence.current) setLoading(false);
}
- }, [token]);
+ }, [apiKeyApi]);
useEffect(() => {
- fetchApiKeys();
+ ++sessionSequence.current;
+ setLoading(true);
+ setCreateKeyType(null); setEditKey(null); setCreated(null);
+ void fetchApiKeys();
+ return () => { ++loadSequence.current; ++sessionSequence.current; };
}, [fetchApiKeys]);
- // The dialog always opens on a download key, the default type.
- const closeCreateDialog = () => {
- setCreateDialogOpen(false);
- setNewKeyIsStatus(false);
- };
-
- const handleCreateKey = async () => {
- if (!token || !newKeyName.trim()) return;
-
- try {
- const response = await fetch('/api/keys', {
- method: 'POST',
- headers: {
- 'Content-Type': 'application/json',
- 'x-access-token': token,
- },
- body: JSON.stringify({
- name: newKeyName.trim(),
- ...(newKeyIsStatus ? { role: STATUS_READ_ROLE } : {}),
- }),
- });
-
- const data = await response.json();
-
- if (response.ok && data.success) {
- setCreatedKey({ ...data, isStatusKey: newKeyIsStatus });
- setCreateDialogOpen(false);
- setCreatedKeyDialogOpen(true);
- setNewKeyName('');
- setNewKeyIsStatus(false);
- fetchApiKeys();
- } else {
- setError(data.error || 'Failed to create API key');
- }
- } catch (err) {
- setError('Failed to create API key');
- }
+ const openEditDialog = (key: ApiKey) => {
+ if (token && !isSimpleKeyRole(key.role) && !key.revoked_at) setEditKey(key);
};
const handleDeleteKey = async () => {
- if (!token || !deleteConfirmDialog.keyId) return;
-
+ const { key } = revokeConfirm;
+ if (!token || !key || mutationBusy.current) return;
+ mutationBusy.current = true; setRevokeConfirm({ key, busy: true }); setError(null);
+ const session = sessionSequence.current;
try {
- const response = await fetch(`/api/keys/${deleteConfirmDialog.keyId}`, {
- method: 'DELETE',
- headers: { 'x-access-token': token },
- });
-
- if (response.ok) {
- setSnackbar({ open: true, message: 'API key deleted' });
- fetchApiKeys();
- } else {
- const data = await response.json();
- setError(data.error || 'Failed to delete API key');
- }
+ await apiKeyApi.revokeApiKey(key.id);
+ if (session !== sessionSequence.current) return;
+ setSnackbar({ open: true, message: 'API key revoked' });
+ void fetchApiKeys();
} catch (err) {
- setError('Failed to delete API key');
+ if (session === sessionSequence.current) setError(apiKeyError(err, 'Failed to revoke API key'));
} finally {
- setDeleteConfirmDialog({ open: false, keyId: null, keyName: '' });
+ mutationBusy.current = false;
+ setRevokeConfirm(CLOSED_CONFIRM);
}
};
const openDeleteConfirmDialog = (id: number, name: string) => {
- setDeleteConfirmDialog({ open: true, keyId: id, keyName: name });
+ setRevokeConfirm({ key: { id, name }, busy: false });
};
- const copyToClipboard = (text: string, label: string) => {
- navigator.clipboard.writeText(text);
- setSnackbar({ open: true, message: `${label} copied to clipboard` });
- };
-
- const formatDate = (dateStr: string | null) => {
- if (!dateStr) return 'Never';
- return new Date(dateStr).toLocaleDateString(undefined, {
- year: 'numeric',
- month: 'short',
- day: 'numeric',
- hour: '2-digit',
- minute: '2-digit',
- });
+ const handleRegenerateKey = async () => {
+ const { key } = regenerateConfirm;
+ if (!token || !key?.role || mutationBusy.current) return;
+ const { role } = key;
+ mutationBusy.current = true; setRegenerateConfirm({ key, busy: true }); setError(null);
+ const session = sessionSequence.current;
+ try {
+ const body = await apiKeyApi.regenerateApiKey(key.id);
+ if (session !== sessionSequence.current) return;
+ setCreated({ key: body, role, action: 'regenerated' });
+ await fetchApiKeys();
+ } catch (err) {
+ // The confirmation closes either way, so the error alert behind it is visible.
+ if (session === sessionSequence.current) setError(apiKeyError(err, 'Failed to regenerate API key'));
+ } finally {
+ mutationBusy.current = false;
+ setRegenerateConfirm(CLOSED_CONFIRM);
+ }
};
- const generateBookmarklet = (apiKey: string) => {
- const serverUrl = locationUtils.getOrigin();
- const code = `javascript:(function(){var k='${apiKey}';var s='${serverUrl}';var u=location.href;if(!/youtube\\.com|youtu\\.be/.test(u)){alert('Not YouTube');return;}fetch(s+'/api/videos/download',{method:'POST',headers:{'Content-Type':'application/json','x-api-key':k},body:JSON.stringify({url:u})}).then(function(r){return r.json()}).then(function(d){alert(d.success?'✓ Added: '+(d.video&&d.video.title?d.video.title:'Queued'):'✗ '+d.error)}).catch(function(){alert('✗ Connection failed')})})();`;
- return code;
+ const copyToClipboard = async (text: string, label: string) => {
+ try {
+ await navigator.clipboard.writeText(text);
+ setSnackbar({ open: true, message: `${label} copied to clipboard` });
+ } catch {
+ setSnackbar({ open: true, message: 'Unable to copy. Select and copy it manually.' });
+ }
};
if (loading) {
return (
-
+
);
}
- return (
-
-
-
- Get the "Send to Youtarr" button
-
-
-
- Click Create Key , give it a name like "Laptop browser", and click Create .
-
- In the window that opens, drag the Send to Youtarr button to your bookmarks bar.
- On any YouTube video, click the button to queue it.
-
-
- The button is only shown once. If you lose it, create another key.
-
-
-
-
- Keys also work with Apple Shortcuts, Tasker, and other tools.
- Note: API keys currently support single video downloads only. Playlists and channels require the web UI.
- {' '}A read-only status key is for dashboards and monitoring tools: it reads your library and download status
- and cannot start downloads.
-
-
-
- Manage API Keys
- }
- onClick={() => setCreateDialogOpen(true)}
- size="small"
- >
- Create Key
-
-
+ const externalKeys = apiKeys.filter((key) => !isSimpleKeyRole(key.role));
+ // GET /api/keys returns revoked keys for the external audit trail; the
+ // bookmarklet list shows only the keys that still work.
+ const bookmarkletKeys = apiKeys.filter((key) => isSimpleKeyRole(key.role) && !key.revoked_at);
+ // Active external keys still count toward the key limit while the External
+ // API is off, so they stay listed where they can be revoked.
+ const showExternalKeys = externalApiEnabled ||
+ externalKeys.some((key) => key.is_active && !key.revoked_at);
+ return (
+
{isHttpWarning && (
}>
Creating API keys over HTTP is insecure. Use HTTPS in production.
@@ -261,284 +192,100 @@ const ApiKeysSection: React.FC = ({ token, apiKeyRateLimit,
)}
- {apiKeys.length === 0 ? (
-
-
- No API keys yet. Create one to get your Send to Youtarr button.
-
-
- ) : (
-
-
-
-
- Name
- Type
- Key
- Created
- Last Used
- Uses
- Actions
-
-
-
- {apiKeys.map((key) => (
-
- {key.name}
- {keyTypeLabel(key.role)}
-
-
-
- {formatDate(key.created_at)}
- {formatDate(key.last_used_at)}
-
- 0 ? 'primary' : 'default'}
- variant="outlined"
- />
-
-
-
- openDeleteConfirmDialog(key.id, key.name)}
- color="error"
- aria-label="Delete"
- >
-
-
-
-
-
- ))}
-
-
-
- )}
+ setCreateKeyType('legacy')}
+ onRevoke={openDeleteConfirmDialog}
+ />
-
+ {showExternalKeys && (
+ <>
+
+ setCreateKeyType('external')}
+ onEdit={openEditDialog}
+ onRegenerate={(key) => setRegenerateConfirm({ key, busy: false })}
+ onRevoke={openDeleteConfirmDialog}
+ />
+ >
+ )}
- {/* Rate Limit Setting */}
-
- {
- const val = parseInt(e.target.value, 10);
- if (!isNaN(val) && val >= 1 && val <= 100) {
- onRateLimitChange(val);
- }
+ {createKeyType && (createKeyType === 'legacy' || externalApiEnabled) && (
+ setCreateKeyType(null)}
+ onCreated={(key, role) => {
+ setCreated({ key, role, action: 'created' });
+ setCreateKeyType(null);
+ void fetchApiKeys();
}}
- inputProps={{ min: 1, max: 100 }}
- size="small"
- className="w-[200px]"
/>
-
-
+ )}
+ {externalApiEnabled && editKey && (
+ setEditKey(null)}
+ onSaved={() => {
+ setEditKey(null);
+ setSnackbar({ open: true, message: 'External access updated' });
+ void fetchApiKeys();
+ }}
+ />
+ )}
- {/* Create Key Dialog */}
-
- Create API Key
-
- setNewKeyName(e.target.value)}
- inputProps={{ maxLength: 100 }}
- helperText="A descriptive name to identify this key"
- />
- setNewKeyIsStatus(e.target.checked)}
- />
- }
- label="Read-only status key"
- />
-
- {newKeyIsStatus
- ? "For dashboards and monitoring tools. It can only read the status summary and cannot start downloads. Next you'll get your key and the address to use. They're shown only once."
- : "Next you'll get your key, the Send to Youtarr button, and the details for phone shortcuts. They're shown only once."}
-
-
-
- Cancel
-
- Create
-
-
-
+ setCreated(null)}
+ onCopy={(text, label) => void copyToClipboard(text, label)}
+ />
- {/* Key Created Dialog with Bookmarklet */}
- setCreatedKeyDialogOpen(false)}
- maxWidth="md"
- fullWidth
+ setRegenerateConfirm(CLOSED_CONFIRM)}
+ onConfirm={handleRegenerateKey}
>
- ✓ API Key Created
-
-
- Save this key now - it will not be shown again!
-
-
-
- Your API Key
-
-
- {createdKey?.key}
- copyToClipboard(createdKey?.key || '', 'API key')}
- size="small"
- >
-
-
-
-
- {createdKey?.isStatusKey && (
- <>
-
- Use it in your dashboard
-
-
- This key can only read the status summary. Enter it as the API key in your dashboard, or send it
- yourself:
-
-
-
- URL: {locationUtils.getOrigin()}/api/status/summary
-
-
- Method: GET
-
-
- Header: x-api-key: {createdKey.key.substring(0, 8)}...
-
-
- >
- )}
-
- {!createdKey?.isStatusKey && (
- <>
-
- 📚 Add to Bookmarks
-
-
- Drag this button to your bookmarks bar:
-
-
- e.preventDefault()}
- draggable="true"
- style={{
- display: 'inline-block',
- padding: '8px 16px',
- backgroundColor: 'var(--primary)',
- color: 'var(--primary-foreground)',
- borderRadius: 'var(--radius-input)',
- textDecoration: 'none',
- fontWeight: 500,
- cursor: 'grab',
- }}
- >
- 📥 Send to Youtarr
-
-
-
-
- Or copy the bookmarklet code:
-
-
-
- {createdKey ? generateBookmarklet(createdKey.key) : ''}
-
-
- copyToClipboard(
- createdKey ? generateBookmarklet(createdKey.key) : '',
- 'Bookmarklet'
- )
- }
- size="small"
- >
-
-
-
-
-
- 📱 Mobile / Shortcuts
-
-
- Use this URL in Apple Shortcuts, Tasker, or other tools:
-
-
-
- URL: {locationUtils.getOrigin()}/api/videos/download
-
-
- Method: POST
-
-
- Header: x-api-key: {createdKey?.key?.substring(0, 8)}...
-
-
- Body: {`{ "url": "" }`}
-
-
- >
- )}
-
-
- setCreatedKeyDialogOpen(false)} variant="contained">
- Done
-
-
-
-
- {/* Delete Confirmation Dialog */}
- setDeleteConfirmDialog({ open: false, keyId: null, keyName: '' })}
+
+ The current key will stop working immediately.
+
+
+ Regenerate "{regenerateConfirm.key?.name}" ?
+
+
+ Its permissions and approved channels will stay the same. The replacement key is
+ shown only once, so copy it before closing the next dialog.
+
+
+
+ setRevokeConfirm(CLOSED_CONFIRM)}
+ onConfirm={handleDeleteKey}
>
- Delete API Key?
-
-
- Are you sure you want to delete the API key "{deleteConfirmDialog.keyName}" ?
-
-
- This action cannot be undone. Any integrations using this key will stop working.
-
-
-
- setDeleteConfirmDialog({ open: false, keyId: null, keyName: '' })}>
- Cancel
-
-
- Delete
-
-
-
+
+ Are you sure you want to revoke the API key "{revokeConfirm.key?.name}" ?
+
+
+ Any integration using this key will stop working immediately. Its audit history is retained.
+
+
= ({ token, apiKeyRateLimit,
};
export default ApiKeysSection;
-
diff --git a/client/src/components/Configuration/sections/ApiKeysSection/BookmarkletKeysSection.tsx b/client/src/components/Configuration/sections/ApiKeysSection/BookmarkletKeysSection.tsx
new file mode 100644
index 000000000..89ca5396a
--- /dev/null
+++ b/client/src/components/Configuration/sections/ApiKeysSection/BookmarkletKeysSection.tsx
@@ -0,0 +1,123 @@
+import React from 'react';
+import { Box, Button, Chip, IconButton, Paper, TextField, Tooltip, Typography } from '../../../ui';
+import { Plus as AddIcon, Trash2 as DeleteIcon } from '../../../../lib/icons';
+import { InfoTooltip } from '../../common/InfoTooltip';
+import { formatKeyDate } from './ExternalKeyCard';
+import { ApiKey, ApiKeyRole, STATUS_READ_ROLE } from './useApiKeys';
+
+const MIN_RATE_LIMIT = 1;
+const MAX_RATE_LIMIT = 100;
+
+const keyTypeLabel = (role: ApiKeyRole) => (role === STATUS_READ_ROLE ? 'Read-only status' : 'Download');
+
+interface BookmarkletKeysSectionProps {
+ /** Active download and read-only status keys; the caller leaves out revoked ones. */
+ keys: ApiKey[];
+ rateLimit: number;
+ onRateLimitChange: (value: number) => void;
+ onCreate: () => void;
+ onRevoke: (id: number, name: string) => void;
+}
+
+export default function BookmarkletKeysSection({
+ keys,
+ rateLimit,
+ onRateLimitChange,
+ onCreate,
+ onRevoke,
+}: BookmarkletKeysSectionProps) {
+ return (
+ <>
+
+
+ Get the "Send to Youtarr" button
+
+
+
+ Click Create Key , give it a name like "Laptop browser", and click Create .
+
+ In the window that opens, drag the Send to Youtarr button to your bookmarks bar.
+ On any YouTube video, click the button to queue it.
+
+
+ The button is only shown once. If you lose it, create another key.
+
+
+
+
+ Keys also work with Apple Shortcuts, Tasker, and other tools.
+ Note: API keys currently support single video downloads only. Playlists and channels require the web UI.
+ {' '}A read-only status key is for dashboards and monitoring tools: it reads your library and download status
+ and cannot start downloads.
+
+
+
+ Manage API Keys
+ } onClick={onCreate} size="small">
+ Create Key
+
+
+
+ {keys.length === 0 ? (
+
+ No API keys yet. Create one to get your Send to Youtarr button.
+
+ ) : (
+
+ {keys.map((key) => (
+
+
+
+
+ {key.name}
+
+
+
+
+
+
+ Created {formatKeyDate(key.created_at)} · Last used {formatKeyDate(key.last_used_at)}
+
+
+
+ onRevoke(key.id, key.name)}
+ color="error"
+ aria-label={`Revoke ${key.name}`}
+ >
+
+
+
+
+ ))}
+
+ )}
+
+
+ {
+ const val = parseInt(e.target.value, 10);
+ if (!isNaN(val) && val >= MIN_RATE_LIMIT && val <= MAX_RATE_LIMIT) {
+ onRateLimitChange(val);
+ }
+ }}
+ inputProps={{ min: MIN_RATE_LIMIT, max: MAX_RATE_LIMIT }}
+ size="small"
+ className="w-[200px]"
+ />
+
+
+ >
+ );
+}
diff --git a/client/src/components/Configuration/sections/ApiKeysSection/ChannelGrantPicker.tsx b/client/src/components/Configuration/sections/ApiKeysSection/ChannelGrantPicker.tsx
new file mode 100644
index 000000000..0d5b0a0ca
--- /dev/null
+++ b/client/src/components/Configuration/sections/ApiKeysSection/ChannelGrantPicker.tsx
@@ -0,0 +1,123 @@
+import React from 'react';
+import {
+ Box,
+ Checkbox,
+ FormControlLabel,
+ TextField,
+ Typography,
+} from '../../../ui';
+import { ChannelListEntry } from '../../../Subscriptions/hooks/useChannelList';
+
+interface ChannelGrantPickerProps {
+ channels: ChannelListEntry[];
+ selectedIds: number[];
+ search: string;
+ onSearchChange: (value: string) => void;
+ onSelectedIdsChange: (ids: number[]) => void;
+ label?: string;
+ maxHeight?: string;
+}
+
+const channelLabel = (channel: ChannelListEntry) =>
+ channel.title ||
+ channel.uploader ||
+ channel.channel_id ||
+ `Channel ${channel.database_id}`;
+
+const ChannelGrantPicker: React.FC = ({
+ channels,
+ selectedIds,
+ search,
+ onSearchChange,
+ onSelectedIdsChange,
+ label = 'Search channels',
+ maxHeight = '240px',
+}) => {
+ const visibleChannels = channels.filter((channel) => {
+ const query = search.trim().toLowerCase();
+ return (
+ !query ||
+ [channel.title, channel.uploader, channel.channel_id]
+ .filter(Boolean)
+ .some((value) => value?.toLowerCase().includes(query))
+ );
+ });
+ // Select all acts only on the channels the search shows, and leaves picks
+ // hidden by the search as they are.
+ const ids = visibleChannels
+ .map((channel) => channel.database_id)
+ .filter((id): id is number => typeof id === 'number');
+ const allVisibleSelected = ids.length > 0 && ids.every((id) => selectedIds.includes(id));
+ const setVisibleSelected = (checked: boolean) =>
+ onSelectedIdsChange(
+ checked
+ ? [...new Set([...selectedIds, ...ids])].sort((a, b) => a - b)
+ : selectedIds.filter((id) => !ids.includes(id))
+ );
+ const update = (id: number, checked: boolean) =>
+ onSelectedIdsChange(
+ checked
+ ? [...new Set([...selectedIds, id])].sort((a, b) => a - b)
+ : selectedIds.filter((value) => value !== id)
+ );
+ return (
+ <>
+ {ids.length > 0 && (
+ selectedIds.includes(id)) && !allVisibleSelected
+ }
+ onChange={(event) => setVisibleSelected(event.target.checked)}
+ />
+ }
+ label={search.trim() ? 'Select all shown channels' : 'Select all channels'}
+ />
+ )}
+ onSearchChange(event.target.value)}
+ fullWidth
+ size="small"
+ className="mb-3"
+ />
+ {channels.length === 0 ? (
+
+ No enabled, non-terminated channels are available.
+
+ ) : visibleChannels.length === 0 ? (
+
+ No channels match your search.
+
+ ) : (
+
+ {visibleChannels.map((channel) => {
+ if (typeof channel.database_id !== 'number') return null;
+ return (
+
+ update(channel.database_id, event.target.checked)
+ }
+ />
+ }
+ label={channelLabel(channel)}
+ />
+ );
+ })}
+
+ )}
+ >
+ );
+};
+
+export default ChannelGrantPicker;
diff --git a/client/src/components/Configuration/sections/ApiKeysSection/ConfirmKeyActionDialog.tsx b/client/src/components/Configuration/sections/ApiKeysSection/ConfirmKeyActionDialog.tsx
new file mode 100644
index 000000000..0ae422ab1
--- /dev/null
+++ b/client/src/components/Configuration/sections/ApiKeysSection/ConfirmKeyActionDialog.tsx
@@ -0,0 +1,39 @@
+import React from 'react';
+import { Button, Dialog, DialogActions, DialogContent, DialogTitle } from '../../../ui';
+
+interface ConfirmKeyActionDialogProps {
+ open: boolean;
+ title: string;
+ confirmLabel: string;
+ busyLabel?: string;
+ busy: boolean;
+ onCancel: () => void;
+ onConfirm: () => void;
+ children: React.ReactNode;
+}
+
+export default function ConfirmKeyActionDialog({
+ open,
+ title,
+ confirmLabel,
+ busyLabel,
+ busy,
+ onCancel,
+ onConfirm,
+ children,
+}: ConfirmKeyActionDialogProps) {
+ return (
+ !busy && onCancel()}>
+ {title}
+ {children}
+
+
+ Cancel
+
+
+ {busy && busyLabel ? busyLabel : confirmLabel}
+
+
+
+ );
+}
diff --git a/client/src/components/Configuration/sections/ApiKeysSection/CreateKeyDialog.tsx b/client/src/components/Configuration/sections/ApiKeysSection/CreateKeyDialog.tsx
new file mode 100644
index 000000000..2040ecf93
--- /dev/null
+++ b/client/src/components/Configuration/sections/ApiKeysSection/CreateKeyDialog.tsx
@@ -0,0 +1,245 @@
+import React, { useEffect, useRef, useState } from 'react';
+import {
+ Alert,
+ Button,
+ Checkbox,
+ Dialog,
+ DialogTitle,
+ DialogContent,
+ DialogActions,
+ Divider,
+ FormControlLabel,
+ TextField,
+ Typography,
+} from '../../../ui';
+import { Warning as WarningIcon } from '../../../../lib/icons';
+import {
+ ApiKeyCreatedResponse,
+ ApiKeyRole,
+ normalizePolicy,
+ STATUS_READ_ROLE,
+ useApiKeys,
+} from './useApiKeys';
+import { defaultPolicy } from './policy';
+import { apiKeyError } from './apiKeyError';
+import type { ChannelListEntry } from '../../../Subscriptions/hooks/useChannelList';
+import PolicyEditor from './PolicyEditor';
+import ChannelGrantPicker from './ChannelGrantPicker';
+
+interface Props {
+ api: ReturnType;
+ createKeyType: 'external' | 'legacy';
+ onClose: () => void;
+ onCreated: (key: ApiKeyCreatedResponse, role: ApiKeyRole) => void;
+}
+export default function CreateKeyDialog({
+ api,
+ createKeyType,
+ onClose,
+ onCreated,
+}: Props) {
+ const [newKeyName, setNewKeyName] = useState('');
+ const [newKeyIsStatus, setNewKeyIsStatus] = useState(false);
+ const [newKeyPolicy, setNewKeyPolicy] = useState(defaultPolicy);
+ const [newKeyChannelIds, setNewKeyChannelIds] = useState([]);
+ const [newKeyChannelSearch, setNewKeyChannelSearch] = useState('');
+ const [channelState, setChannelState] = useState<{
+ channels: ChannelListEntry[];
+ loading: boolean;
+ error: string | null;
+ }>({ channels: [], loading: createKeyType === 'external', error: null });
+ const [error, setError] = useState(null);
+ const [busy, setBusy] = useState(false);
+ const [reload, setReload] = useState(0);
+ const submitting = useRef(false);
+ const active = useRef(true);
+ const {
+ channels: channelOptions,
+ loading: channelsLoading,
+ error: channelsError,
+ } = channelState;
+ useEffect(() => {
+ active.current = true;
+ return () => {
+ active.current = false;
+ };
+ }, []);
+ useEffect(() => {
+ if (createKeyType === 'legacy') return;
+ const controller = new AbortController();
+ setChannelState({ channels: [], loading: true, error: null });
+ void api
+ .fetchAvailableChannels(controller.signal)
+ .then((channels) => {
+ if (!controller.signal.aborted)
+ setChannelState({
+ channels: channels.filter((channel) => !channel.terminated_at),
+ loading: false,
+ error: null,
+ });
+ })
+ .catch((error) => {
+ if (!controller.signal.aborted)
+ setChannelState({
+ channels: [],
+ loading: false,
+ error: apiKeyError(error, 'Failed to load channels'),
+ });
+ });
+ return () => controller.abort();
+ }, [api, createKeyType, reload]);
+ const close = () => {
+ if (!submitting.current) onClose();
+ };
+ const handleCreateKey = async () => {
+ if (
+ submitting.current ||
+ !newKeyName.trim() ||
+ (createKeyType === 'external' && (channelsLoading || channelsError))
+ )
+ return;
+ const normalized =
+ createKeyType === 'legacy' ? null : normalizePolicy(newKeyPolicy);
+ if (normalized && !normalized.policy) {
+ setError(normalized.error || 'Invalid policy values');
+ return;
+ }
+ submitting.current = true;
+ setBusy(true);
+ setError(null);
+ try {
+ const result = await api.createApiKey(
+ newKeyName.trim(),
+ normalized?.policy,
+ createKeyType === 'external' ? newKeyChannelIds : undefined,
+ createKeyType === 'legacy' && newKeyIsStatus ? STATUS_READ_ROLE : undefined
+ );
+ if (!active.current) return;
+ if (!result.success) {
+ setError(result.message || 'Failed to create API key');
+ return;
+ }
+ onCreated(
+ result,
+ createKeyType === 'external'
+ ? newKeyPolicy.role
+ : newKeyIsStatus
+ ? STATUS_READ_ROLE
+ : 'legacy_download'
+ );
+ } catch (error) {
+ if (active.current)
+ setError(apiKeyError(error, 'Failed to create API key'));
+ } finally {
+ submitting.current = false;
+ if (active.current) setBusy(false);
+ }
+ };
+ return (
+
+
+ {createKeyType === 'legacy'
+ ? 'Create API Key'
+ : 'Create External Access Key'}
+
+
+ {error && {error} }
+ {channelsLoading && (
+ Loading available channels...
+ )}
+ {channelsError && (
+
+ {channelsError}
+ setReload((value) => value + 1)}>
+ Retry
+
+
+ )}
+ setNewKeyName(e.target.value)}
+ inputProps={{ maxLength: 100 }}
+ helperText="A descriptive name to identify this key"
+ />
+ {createKeyType === 'legacy' && (
+ <>
+ setNewKeyIsStatus(e.target.checked)}
+ />
+ }
+ label="Read-only status key"
+ />
+
+ {newKeyIsStatus
+ ? "For dashboards and monitoring tools. It can only read the status summary and cannot start downloads. Next you'll get your key and the address to use. They're shown only once."
+ : "Next you'll get your key, the Send to Youtarr button, and the details for phone shortcuts. They're shown only once."}
+
+ >
+ )}
+ {createKeyType === 'external' && (
+ <>
+
+ Access policy
+
+
+
+
+ Approved channels ({newKeyChannelIds.length})
+
+
+ The key cannot browse or request from channels that are not
+ selected.
+
+ {newKeyChannelIds.length === 0 && (
+ }
+ >
+ Saving with zero approved channels is allowed, but the key will
+ fail closed and cannot view or request catalog content until
+ grants are added.
+
+ )}
+
+ >
+ )}
+
+
+
+ Cancel
+
+
+ {busy ? 'Creating…' : 'Create'}
+
+
+
+ );
+}
diff --git a/client/src/components/Configuration/sections/ApiKeysSection/CreatedKeyDialog.tsx b/client/src/components/Configuration/sections/ApiKeysSection/CreatedKeyDialog.tsx
new file mode 100644
index 000000000..9792c9dcc
--- /dev/null
+++ b/client/src/components/Configuration/sections/ApiKeysSection/CreatedKeyDialog.tsx
@@ -0,0 +1,163 @@
+import React from 'react';
+import {
+ Alert,
+ Box,
+ Button,
+ Dialog,
+ DialogActions,
+ DialogContent,
+ DialogTitle,
+ IconButton,
+ Paper,
+ Typography,
+} from '../../../ui';
+import { Copy as ContentCopyIcon } from '../../../../lib/icons';
+import { locationUtils } from '../../../../utils/location';
+import { ApiKeyCreatedResponse, ApiKeyRole } from './useApiKeys';
+
+export const generateBookmarklet = (apiKey: string) => {
+ const serverUrl = locationUtils.getOrigin();
+ return `javascript:(function(){var k='${apiKey}';var s='${serverUrl}';var u=location.href;if(!/youtube\\.com|youtu\\.be/.test(u)){alert('Not YouTube');return;}fetch(s+'/api/videos/download',{method:'POST',headers:{'Content-Type':'application/json','x-api-key':k},body:JSON.stringify({url:u})}).then(function(r){return r.json()}).then(function(d){alert(d.success?'✓ Added: '+(d.video&&d.video.title?d.video.title:'Queued'):'✗ '+d.error)}).catch(function(){alert('✗ Connection failed')})})();`;
+};
+
+interface CreatedKeyDialogProps {
+ createdKey: ApiKeyCreatedResponse | null;
+ role: ApiKeyRole;
+ action: 'created' | 'regenerated';
+ open: boolean;
+ onClose: () => void;
+ onCopy: (text: string, label: string) => void;
+}
+
+function BookmarkletDetails({ apiKey, onCopy }: { apiKey: string; onCopy: CreatedKeyDialogProps['onCopy'] }) {
+ const bookmarklet = generateBookmarklet(apiKey);
+ return (
+ <>
+
+ 📚 Add to Bookmarks
+
+
+ Drag this button to your bookmarks bar:
+
+
+ e.preventDefault()}
+ draggable="true"
+ style={{
+ display: 'inline-block',
+ padding: '8px 16px',
+ backgroundColor: 'var(--primary)',
+ color: 'var(--primary-foreground)',
+ borderRadius: 'var(--radius-input)',
+ textDecoration: 'none',
+ fontWeight: 500,
+ cursor: 'grab',
+ }}
+ >
+ 📥 Send to Youtarr
+
+
+
+
+ Or copy the bookmarklet code:
+
+
+ {bookmarklet}
+ onCopy(bookmarklet, 'Bookmarklet')} size="small">
+
+
+
+
+
+ 📱 Mobile / Shortcuts
+
+
+ Use this URL in Apple Shortcuts, Tasker, or other tools:
+
+
+
+ URL: {locationUtils.getOrigin()}/api/videos/download
+
+
+ Method: POST
+
+
+ Header: x-api-key: {apiKey.substring(0, 8)}...
+
+
+ Body: {`{ "url": "" }`}
+
+
+ >
+ );
+}
+
+function StatusKeyDetails({ apiKey }: { apiKey: string }) {
+ return (
+ <>
+
+ Use it in your dashboard
+
+
+ This key can only read the status summary. Enter it as the API key in your dashboard, or send it
+ yourself:
+
+
+
+ URL: {locationUtils.getOrigin()}/api/status/summary
+
+
+ Method: GET
+
+
+ Header: x-api-key: {apiKey.substring(0, 8)}...
+
+
+ >
+ );
+}
+
+export default function CreatedKeyDialog({ createdKey, role, action, open, onClose, onCopy }: CreatedKeyDialogProps) {
+ const key = createdKey?.key || '';
+ return (
+
+ ✓ API Key {action === 'regenerated' ? 'Regenerated' : 'Created'}
+
+
+ Save this key now - it will not be shown again!
+
+
+
+ Your API Key
+
+
+ {key}
+ onCopy(key, 'API key')} size="small">
+
+
+
+
+ {role === 'legacy_download' ? (
+ key &&
+ ) : role === 'status_read' ? (
+
+ ) : (
+
+
+ Use this key only with {locationUtils.getOrigin()}/external-api/v1 .
+
+
+ Only approved channels are available. You can update grants from this key's edit action.
+
+
+ )}
+
+
+
+ Done
+
+
+
+ );
+}
diff --git a/client/src/components/Configuration/sections/ApiKeysSection/EditKeyDialog.tsx b/client/src/components/Configuration/sections/ApiKeysSection/EditKeyDialog.tsx
new file mode 100644
index 000000000..3c69ba0a1
--- /dev/null
+++ b/client/src/components/Configuration/sections/ApiKeysSection/EditKeyDialog.tsx
@@ -0,0 +1,142 @@
+import React from 'react';
+import {
+ Alert,
+ Button,
+ Dialog,
+ DialogTitle,
+ DialogContent,
+ DialogActions,
+ Divider,
+ Typography,
+} from '../../../ui';
+import { Warning as WarningIcon } from '../../../../lib/icons';
+import { ApiKey, useApiKeys } from './useApiKeys';
+import { useExternalAccessEditor } from './useExternalAccessEditor';
+import PolicyEditor from './PolicyEditor';
+import ChannelGrantPicker from './ChannelGrantPicker';
+
+interface Props {
+ apiKey: ApiKey;
+ api: ReturnType;
+ onClose: () => void;
+ onSaved: () => void;
+}
+export default function EditKeyDialog(props: Props) {
+ const { apiKey } = props;
+ const {
+ editPolicy,
+ channelOptions,
+ channelSearch,
+ selectedChannelIds,
+ savingPolicy,
+ loading,
+ editLoadError,
+ editSubmitError,
+ pendingExternalUpdate,
+ setEditPolicy,
+ setChannelSearch,
+ setSelectedChannelIds,
+ closeEditDialog,
+ reload,
+ saveExternalAccess,
+ cancelPrivilegeConfirmation,
+ confirmPrivilegeIncrease,
+ } = useExternalAccessEditor(props);
+ return (
+ <>
+
+ Edit External Access — {apiKey.name}
+
+
+ Permissions, policy, and channel grants are enforced by Youtarr on
+ every request.
+
+ {editLoadError && (
+
+
+ {editLoadError}
+
+ Retry
+
+
+
+ )}
+ {editSubmitError && (
+
+ {editSubmitError}
+
+ )}
+ {!editLoadError && loading && (
+
+ Loading channel grants and available channels...
+
+ )}
+
+
+
+ Approved channels ({selectedChannelIds.length})
+
+ {!loading && !editLoadError && selectedChannelIds.length === 0 && (
+ }
+ >
+ Saving with zero approved channels is allowed, but this key will
+ fail closed and cannot view or request catalog content until
+ grants are added.
+
+ )}
+
+
+
+
+ Cancel
+
+
+ {savingPolicy ? 'Saving…' : 'Save External Access'}
+
+
+
+
+
+ Confirm expanded external access?
+
+
+ This change may increase what the external integration can view or
+ request.
+
+
+ Continue saving these expanded permissions and channel grants?
+
+
+
+
+ Cancel
+
+
+ {savingPolicy ? 'Saving...' : 'Continue'}
+
+
+
+ >
+ );
+}
diff --git a/client/src/components/Configuration/sections/ApiKeysSection/ExternalKeyCard.tsx b/client/src/components/Configuration/sections/ApiKeysSection/ExternalKeyCard.tsx
new file mode 100644
index 000000000..4806359bd
--- /dev/null
+++ b/client/src/components/Configuration/sections/ApiKeysSection/ExternalKeyCard.tsx
@@ -0,0 +1,233 @@
+import React from 'react';
+import {
+ Alert,
+ Chip,
+ IconButton,
+ Paper,
+ Tooltip,
+ Typography,
+} from '../../../ui';
+import {
+ Trash2 as DeleteIcon,
+ Warning as WarningIcon,
+ Pencil as EditIcon,
+ RefreshCw as RegenerateIcon,
+ Video as VideoIcon,
+ Radio as ChannelIcon,
+ Timer as ClockIcon,
+ Zap as AutoApproveIcon,
+ Eye as ViewIcon,
+} from '../../../../lib/icons';
+import { getExternalRatingBand } from '../../../../utils/externalRatingPolicy';
+import RatingBadge from '../../../shared/RatingBadge';
+import { ApiKey } from './useApiKeys';
+import { permissionsFromKey } from './policy';
+
+export const formatKeyDate = (dateStr: string | null) => {
+ if (!dateStr) return 'Never';
+ return new Date(dateStr).toLocaleDateString(undefined, {
+ year: 'numeric',
+ month: 'short',
+ day: 'numeric',
+ hour: '2-digit',
+ minute: '2-digit',
+ });
+};
+
+interface Props {
+ apiKey: ApiKey;
+ /** Left out while the External API is off: the key can only be revoked. */
+ onEdit?: (key: ApiKey) => void;
+ onRegenerate?: (key: ApiKey) => void;
+ onRevoke: (id: number, name: string) => void;
+}
+export default function ExternalKeyCard({
+ apiKey: key,
+ onEdit,
+ onRegenerate,
+ onRevoke,
+}: Props) {
+ const rawChannelGrantCount = key.channel_grant_count;
+ const channelGrantCount =
+ typeof rawChannelGrantCount === 'number' &&
+ Number.isInteger(rawChannelGrantCount) &&
+ rawChannelGrantCount >= 0
+ ? rawChannelGrantCount
+ : null;
+ const permissions = permissionsFromKey(key);
+ const ratingBand = getExternalRatingBand(key.max_rating_level);
+ const movieCeiling =
+ ratingBand.movieRatings[ratingBand.movieRatings.length - 1];
+ const tvCeiling = ratingBand.tvRatings[ratingBand.tvRatings.length - 1];
+ const permissionChips = [
+ permissions.allowVideoRequests && {
+ label: key.auto_approve_video_requests ? 'Videos · Auto' : 'Videos',
+ title: key.auto_approve_video_requests
+ ? 'Video requests are enabled and auto-approved after policy checks.'
+ : 'Video requests are enabled and require administrator approval.',
+ icon: ,
+ auto: key.auto_approve_video_requests,
+ },
+ permissions.allowChannelRequests && {
+ label: key.auto_approve_channel_requests ? 'Channels · Auto' : 'Channels',
+ title: key.auto_approve_channel_requests
+ ? 'Channel requests are enabled and auto-approved after policy checks.'
+ : 'Channel requests are enabled and require administrator approval.',
+ icon: ,
+ auto: key.auto_approve_channel_requests,
+ },
+ permissions.allowDeleteVideoRequests && {
+ label: key.auto_approve_delete_requests
+ ? 'Delete · Auto'
+ : 'Delete video',
+ title: key.auto_approve_delete_requests
+ ? 'Downloaded-video deletion requests are enabled and auto-approved after policy checks.'
+ : 'Downloaded-video deletion requests are enabled and require administrator approval.',
+ icon: ,
+ auto: key.auto_approve_delete_requests,
+ },
+ ].filter(Boolean) as Array<{
+ label: string;
+ title: string;
+ icon: React.ReactElement;
+ auto: boolean;
+ }>;
+
+ return (
+
+
+
+
+ {key.name}
+
+ {key.revoked_at && (
+
+ )}
+
+
+ {key.allow_unrated && (
+
+ )}
+
+
+
+ {permissionChips.length === 0 ? (
+
+ }
+ />
+
+ ) : (
+ permissionChips.map((permission) => (
+
+
+ ) : (
+ permission.icon
+ )
+ }
+ />
+
+ ))
+ )}
+
+ {channelGrantCount === 0 && (
+
}
+ >
+ No approved channels. This key cannot view or request catalog
+ content until you add grants.
+
+ )}
+
+
+
+
+
+
+ Last used
+
+
+ {formatKeyDate(key.last_used_at)}
+
+
+
+ {!key.revoked_at && onEdit && (
+
+ onEdit(key)}
+ aria-label={`Edit ${key.name} external access`}
+ >
+
+
+
+ )}
+ {!key.revoked_at && onRegenerate && (
+
+ onRegenerate(key)}
+ aria-label={`Regenerate ${key.name}`}
+ >
+
+
+
+ )}
+ {!key.revoked_at && (
+
+ onRevoke(key.id, key.name)}
+ color="error"
+ aria-label={`Revoke ${key.name}`}
+ >
+
+
+
+ )}
+
+
+
+ );
+}
diff --git a/client/src/components/Configuration/sections/ApiKeysSection/ExternalKeysSection.tsx b/client/src/components/Configuration/sections/ApiKeysSection/ExternalKeysSection.tsx
new file mode 100644
index 000000000..88b82f26c
--- /dev/null
+++ b/client/src/components/Configuration/sections/ApiKeysSection/ExternalKeysSection.tsx
@@ -0,0 +1,103 @@
+import React, { useState } from 'react';
+import { Alert, Box, Button, Paper, TextField, Typography } from '../../../ui';
+import { Filter as FilterIcon, Plus as AddIcon } from '../../../../lib/icons';
+import ExternalKeyCard from './ExternalKeyCard';
+import { ApiKey } from './useApiKeys';
+
+interface ExternalKeysSectionProps {
+ keys: ApiKey[];
+ /** While the External API is off the keys are listed only so they can be revoked. */
+ externalApiEnabled: boolean;
+ onCreate: () => void;
+ onEdit: (key: ApiKey) => void;
+ onRegenerate: (key: ApiKey) => void;
+ onRevoke: (id: number, name: string) => void;
+}
+
+export default function ExternalKeysSection({
+ keys,
+ externalApiEnabled,
+ onCreate,
+ onEdit,
+ onRegenerate,
+ onRevoke,
+}: ExternalKeysSectionProps) {
+ const [search, setSearch] = useState('');
+ const [activeOnly, setActiveOnly] = useState(true);
+ const query = search.trim().toLocaleLowerCase();
+ const visibleKeys = keys
+ .filter((key) => !activeOnly || (key.is_active && !key.revoked_at))
+ .filter((key) => !query || key.name.toLocaleLowerCase().includes(query))
+ .sort((a, b) => a.name.localeCompare(b.name, undefined, { sensitivity: 'base' }));
+
+ return (
+ <>
+
+
+ External access keys
+
+ For integrations that use /external-api/v1. Every external key can view its approved
+ channels. Add only the request permissions the integration needs.
+
+
+ {externalApiEnabled && (
+ } onClick={onCreate} size="small">
+ Create external key
+
+ )}
+
+
+ {!externalApiEnabled && (
+
+ The External API is turned off, so these keys cannot be used. They still count toward the key
+ limit, and you can revoke them here.
+
+ )}
+
+ {keys.length > 0 && (
+
+ setSearch(event.target.value)}
+ fullWidth
+ size="small"
+ />
+ }
+ onClick={() => setActiveOnly((current) => !current)}
+ aria-pressed={activeOnly}
+ size="small"
+ className="shrink-0 self-start sm:self-stretch"
+ style={{ height: 'auto' }}
+ >
+ Active only
+
+
+ )}
+
+ {visibleKeys.length === 0 ? (
+
+
+ {keys.length === 0
+ ? 'No external access keys yet.'
+ : 'No external access keys match the current search and filter.'}
+
+
+ ) : (
+
+ {visibleKeys.map((key) => (
+
+ ))}
+
+ )}
+ >
+ );
+}
diff --git a/client/src/components/Configuration/sections/ApiKeysSection/PolicyEditor.tsx b/client/src/components/Configuration/sections/ApiKeysSection/PolicyEditor.tsx
new file mode 100644
index 000000000..f5053b835
--- /dev/null
+++ b/client/src/components/Configuration/sections/ApiKeysSection/PolicyEditor.tsx
@@ -0,0 +1,224 @@
+import React from 'react';
+import {
+ Box,
+ Typography,
+ Paper,
+ Tooltip,
+ Chip,
+ TextField,
+ Switch,
+ FormControlLabel,
+ Select,
+ MenuItem,
+} from '../../../ui';
+import { Eye as ViewIcon } from '../../../../lib/icons';
+import {
+ EXTERNAL_RATING_BANDS,
+ formatExternalRatingBand,
+} from '../../../../utils/externalRatingPolicy';
+import { ApiKeyPolicy, MediaType, WORKLOAD_LIMITS } from './useApiKeys';
+import { roleForPolicy } from './policy';
+
+interface PolicyEditorProps {
+ policy: ApiKeyPolicy;
+ onChange: (policy: ApiKeyPolicy) => void;
+}
+
+const PolicyEditor: React.FC = ({ policy, onChange }) => {
+ const updatePolicy = (changes: Partial) => {
+ const next = { ...policy, ...changes };
+ onChange({ ...next, role: roleForPolicy(next) });
+ };
+ const togglePermission = (
+ permission:
+ | 'allowVideoRequests'
+ | 'allowChannelRequests'
+ | 'allowDeleteVideoRequests',
+ autoApprove:
+ | 'autoApproveVideoRequests'
+ | 'autoApproveChannelRequests'
+ | 'autoApproveDeleteRequests',
+ enabled: boolean
+ ) =>
+ updatePolicy({
+ [permission]: enabled,
+ ...(!enabled ? { [autoApprove]: false } : {}),
+ });
+ const toggleMedia = (mediaType: MediaType) => {
+ const selected = policy.allowedMediaTypes.includes(mediaType);
+ if (selected && policy.allowedMediaTypes.length === 1) return;
+ updatePolicy({
+ allowedMediaTypes: selected
+ ? policy.allowedMediaTypes.filter((value) => value !== mediaType)
+ : [...policy.allowedMediaTypes, mediaType],
+ });
+ };
+ return (
+
+
+
+ Maximum allowed rating
+
+
+ updatePolicy({ maxRatingLevel: Number(event.target.value) })
+ }
+ >
+ {EXTERNAL_RATING_BANDS.map((band) => (
+
+ {formatExternalRatingBand(band.level)}
+
+ ))}
+
+
+ Uses the video rating first, then the channel's manually assigned
+ default.
+
+
+
+ Content access
+
+ updatePolicy({ allowUnrated: event.target.checked })
+ }
+ />
+ }
+ label="Allow unrated or unrecognized ratings"
+ />
+
+ {(['video', 'short', 'livestream'] as MediaType[]).map(
+ (mediaType) => (
+ toggleMedia(mediaType)}
+ />
+ }
+ label={mediaType.charAt(0).toUpperCase() + mediaType.slice(1)}
+ />
+ )
+ )}
+
+
+
+
+ Request permissions
+
+ }
+ label="View included"
+ />
+
+
+ {(
+ [
+ [
+ 'allowVideoRequests',
+ 'autoApproveVideoRequests',
+ 'Request videos',
+ 'Submit requests to download eligible videos.',
+ ],
+ [
+ 'allowChannelRequests',
+ 'autoApproveChannelRequests',
+ 'Request channels',
+ 'Submit requests to add supported YouTube channels.',
+ ],
+ [
+ 'allowDeleteVideoRequests',
+ 'autoApproveDeleteRequests',
+ 'Delete downloaded videos',
+ 'Submit approval-backed requests to remove downloaded video assets.',
+ ],
+ ] as const
+ ).map(([permission, autoApprove, label, description]) => {
+ const enabled = policy[permission];
+ return (
+
+
+
+
+ {label}
+
+
+ {description}
+
+
+
+ togglePermission(
+ permission,
+ autoApprove,
+ event.target.checked
+ )
+ }
+ aria-label={label}
+ />
+
+ {enabled && (
+
+
+ Auto-approve
+
+ Skip manual review when all current policy checks pass.
+
+
+
+ updatePolicy({
+ [autoApprove]: event.target.checked,
+ } as Partial)
+ }
+ aria-label={`Auto-approve ${String(label).toLowerCase()}`}
+ />
+
+ )}
+
+ );
+ })}
+
+
+ Workload limits
+
+ Durable per-key ceilings. Limits can be reduced below the system
+ defaults.
+
+
+ {WORKLOAD_LIMITS.map(({ field, label, min, max }) => (
+
+ updatePolicy({
+ [field]: event.target.value,
+ } as Partial)
+ }
+ />
+ ))}
+
+
+
+ );
+};
+
+export default PolicyEditor;
diff --git a/client/src/components/Configuration/sections/ApiKeysSection/__tests__/ChannelGrantPicker.test.tsx b/client/src/components/Configuration/sections/ApiKeysSection/__tests__/ChannelGrantPicker.test.tsx
new file mode 100644
index 000000000..6789a648c
--- /dev/null
+++ b/client/src/components/Configuration/sections/ApiKeysSection/__tests__/ChannelGrantPicker.test.tsx
@@ -0,0 +1,75 @@
+import React, { useState } from 'react';
+import { render, screen } from '@testing-library/react';
+import userEvent from '@testing-library/user-event';
+import '@testing-library/jest-dom';
+import ChannelGrantPicker from '../ChannelGrantPicker';
+import type { ChannelListEntry } from '../../../../Subscriptions/hooks/useChannelList';
+
+const channel = (id: number, title: string): ChannelListEntry => ({
+ database_id: id,
+ url: `https://www.youtube.com/channel/UC${id}`,
+ channel_id: `UC${id}`,
+ uploader: title,
+ title,
+ terminated_at: null,
+});
+
+const channels = [channel(1, 'Kids Science'), channel(2, 'Kids Art'), channel(3, 'Cooking')];
+
+function Harness({ initialIds = [] }: { initialIds?: number[] }) {
+ const [selectedIds, setSelectedIds] = useState(initialIds);
+ const [search, setSearch] = useState('');
+ return (
+ <>
+
+ {selectedIds.join(',')}
+ >
+ );
+}
+
+describe('ChannelGrantPicker', () => {
+ test('select all picks every channel when nothing is searched', async () => {
+ const user = userEvent.setup();
+ render( );
+
+ await user.click(screen.getByLabelText('Select all channels'));
+
+ expect(screen.getByLabelText('Selected ids')).toHaveTextContent('1,2,3');
+ });
+
+ test('select all picks only the channels the search shows', async () => {
+ const user = userEvent.setup();
+ render( );
+
+ await user.type(screen.getByLabelText('Search channels'), 'kids');
+ await user.click(screen.getByLabelText('Select all shown channels'));
+
+ expect(screen.getByLabelText('Selected ids')).toHaveTextContent('1,2');
+ });
+
+ test('clearing select all keeps picks hidden by the search', async () => {
+ const user = userEvent.setup();
+ render( );
+
+ await user.type(screen.getByLabelText('Search channels'), 'kids');
+ await user.click(screen.getByLabelText('Select all shown channels'));
+
+ expect(screen.getByLabelText('Selected ids')).toHaveTextContent(/^3$/);
+ });
+
+ test('hides select all when the search matches nothing', async () => {
+ const user = userEvent.setup();
+ render( );
+
+ await user.type(screen.getByLabelText('Search channels'), 'nothing matches');
+
+ expect(screen.queryByLabelText('Select all shown channels')).not.toBeInTheDocument();
+ expect(screen.getByText('No channels match your search.')).toBeInTheDocument();
+ });
+});
diff --git a/client/src/components/Configuration/sections/ApiKeysSection/__tests__/ConfirmKeyActionDialog.test.tsx b/client/src/components/Configuration/sections/ApiKeysSection/__tests__/ConfirmKeyActionDialog.test.tsx
new file mode 100644
index 000000000..e7d81e623
--- /dev/null
+++ b/client/src/components/Configuration/sections/ApiKeysSection/__tests__/ConfirmKeyActionDialog.test.tsx
@@ -0,0 +1,43 @@
+import React from 'react';
+import { render, screen } from '@testing-library/react';
+import userEvent from '@testing-library/user-event';
+import ConfirmKeyActionDialog from '../ConfirmKeyActionDialog';
+
+const renderDialog = (overrides: Partial> = {}) => {
+ const props = {
+ open: true,
+ title: 'Revoke API Key?',
+ confirmLabel: 'Revoke',
+ busyLabel: 'Revoking…',
+ busy: false,
+ onCancel: jest.fn(),
+ onConfirm: jest.fn(),
+ ...overrides,
+ };
+ render(Body text );
+ return props;
+};
+
+describe('ConfirmKeyActionDialog', () => {
+ test('confirms the action', async () => {
+ const { onConfirm } = renderDialog();
+
+ await userEvent.click(screen.getByRole('button', { name: 'Revoke' }));
+
+ expect(onConfirm).toHaveBeenCalled();
+ });
+
+ test('cancels the action', async () => {
+ const { onCancel } = renderDialog();
+
+ await userEvent.click(screen.getByRole('button', { name: 'Cancel' }));
+
+ expect(onCancel).toHaveBeenCalled();
+ });
+
+ test('shows the busy label and locks the buttons while working', () => {
+ renderDialog({ busy: true });
+
+ expect(screen.getByRole('button', { name: 'Revoking…' })).toBeDisabled();
+ });
+});
diff --git a/client/src/components/Configuration/sections/ApiKeysSection/__tests__/CreatedKeyDialog.test.tsx b/client/src/components/Configuration/sections/ApiKeysSection/__tests__/CreatedKeyDialog.test.tsx
new file mode 100644
index 000000000..351490e79
--- /dev/null
+++ b/client/src/components/Configuration/sections/ApiKeysSection/__tests__/CreatedKeyDialog.test.tsx
@@ -0,0 +1,69 @@
+import React from 'react';
+import { render, screen } from '@testing-library/react';
+import userEvent from '@testing-library/user-event';
+import CreatedKeyDialog, { generateBookmarklet } from '../CreatedKeyDialog';
+
+const createdKey = {
+ success: true,
+ message: '',
+ id: 3,
+ name: 'Laptop browser',
+ key: 'abc12345def67890',
+ prefix: 'abc12345',
+};
+
+const renderDialog = (overrides: Partial> = {}) => {
+ const props = {
+ open: true,
+ createdKey,
+ role: 'legacy_download' as const,
+ action: 'created' as const,
+ onClose: jest.fn(),
+ onCopy: jest.fn(),
+ ...overrides,
+ };
+ render( );
+ return props;
+};
+
+describe('generateBookmarklet', () => {
+ test('embeds the key and posts to the download endpoint', () => {
+ const code = generateBookmarklet('my-key');
+
+ expect(code).toContain("var k='my-key'");
+ });
+});
+
+describe('CreatedKeyDialog', () => {
+ test('shows the draggable bookmarklet for a bookmarklet key', () => {
+ renderDialog();
+
+ expect(screen.getByText(/Send to Youtarr/)).toHaveAttribute('href', generateBookmarklet(createdKey.key));
+ });
+
+ test('shows phone shortcut details for a bookmarklet key', () => {
+ renderDialog();
+
+ expect(screen.getByText('Mobile / Shortcuts', { exact: false })).toBeInTheDocument();
+ });
+
+ test('points an external key at the versioned API instead of the bookmarklet', () => {
+ renderDialog({ role: 'view' });
+
+ expect(screen.queryByText(/Send to Youtarr/)).not.toBeInTheDocument();
+ });
+
+ test('copies the bookmarklet code', async () => {
+ const { onCopy } = renderDialog();
+
+ await userEvent.click(screen.getByRole('button', { name: 'Copy bookmarklet code' }));
+
+ expect(onCopy).toHaveBeenCalledWith(generateBookmarklet(createdKey.key), 'Bookmarklet');
+ });
+
+ test('titles a regenerated key', () => {
+ renderDialog({ action: 'regenerated', role: 'view' });
+
+ expect(screen.getByText(/API Key Regenerated/)).toBeInTheDocument();
+ });
+});
diff --git a/client/src/components/Configuration/sections/ApiKeysSection/__tests__/policy.test.ts b/client/src/components/Configuration/sections/ApiKeysSection/__tests__/policy.test.ts
new file mode 100644
index 000000000..3ac3cc519
--- /dev/null
+++ b/client/src/components/Configuration/sections/ApiKeysSection/__tests__/policy.test.ts
@@ -0,0 +1,96 @@
+import { increasesPrivilege, legacyRolePermissions, policyFromKey, roleForPolicy } from '../policy';
+import type { ApiKey, NormalizedApiKeyPolicy } from '../useApiKeys';
+
+const key: ApiKey = {
+ id: 7,
+ name: 'Client',
+ key_prefix: 'abc12345',
+ created_at: '2026-07-27T18:30:00.000Z',
+ last_used_at: null,
+ is_active: true,
+ usage_count: 0,
+ role: 'request',
+ allow_video_requests: true,
+ allow_channel_requests: false,
+ allow_delete_video_requests: false,
+ auto_approve_video_requests: false,
+ auto_approve_channel_requests: false,
+ auto_approve_delete_requests: false,
+ max_rating_level: 2,
+ allow_unrated: false,
+ allowed_media_types: ['video'],
+ max_active_jobs: 3,
+ hourly_write_limit: 10,
+ daily_write_limit: 50,
+ revoked_at: null,
+};
+
+const samePolicy = (): NormalizedApiKeyPolicy => {
+ const policy = policyFromKey(key);
+ return {
+ ...policy,
+ maxActiveJobs: Number(policy.maxActiveJobs),
+ hourlyWriteLimit: Number(policy.hourlyWriteLimit),
+ dailyWriteLimit: Number(policy.dailyWriteLimit),
+ };
+};
+
+describe('increasesPrivilege', () => {
+ test('is false for an unchanged policy and grant set', () => {
+ expect(increasesPrivilege(key, samePolicy(), [3], [3])).toBe(false);
+ });
+
+ test('is false when access only narrows', () => {
+ const narrower = { ...samePolicy(), allowVideoRequests: false, maxRatingLevel: 1, dailyWriteLimit: 20 };
+ expect(increasesPrivilege(key, narrower, [], [3])).toBe(false);
+ });
+
+ test.each([
+ ['a new permission', { allowChannelRequests: true }],
+ ['a new auto-approval', { autoApproveVideoRequests: true }],
+ ['unrated content', { allowUnrated: true }],
+ ['a higher rating ceiling', { maxRatingLevel: 3 }],
+ ['a new media type', { allowedMediaTypes: ['video', 'short'] }],
+ ['more active jobs', { maxActiveJobs: 4 }],
+ ['a higher hourly limit', { hourlyWriteLimit: 11 }],
+ ['a higher daily limit', { dailyWriteLimit: 51 }],
+ ] as const)('is true for %s', (_label, change) => {
+ expect(increasesPrivilege(key, { ...samePolicy(), ...change } as NormalizedApiKeyPolicy, [3], [3])).toBe(true);
+ });
+
+ test('is true when a channel is added', () => {
+ expect(increasesPrivilege(key, samePolicy(), [3, 9], [3])).toBe(true);
+ });
+});
+
+describe('policyFromKey', () => {
+ test('falls back to the role and the workload ceilings for older keys', () => {
+ const older = {
+ ...key,
+ role: 'delete' as const,
+ allow_video_requests: undefined,
+ allow_channel_requests: undefined,
+ allow_delete_video_requests: undefined,
+ max_active_jobs: undefined,
+ hourly_write_limit: undefined,
+ daily_write_limit: undefined,
+ } as unknown as ApiKey;
+
+ expect(policyFromKey(older)).toMatchObject({
+ ...legacyRolePermissions('delete'),
+ maxActiveJobs: 5,
+ hourlyWriteLimit: 30,
+ dailyWriteLimit: 200,
+ });
+ });
+});
+
+describe('roleForPolicy', () => {
+ test('derives the narrowest role that covers the permissions', () => {
+ const base = samePolicy();
+ expect(roleForPolicy({ ...base, allowVideoRequests: false })).toBe('view');
+ expect(roleForPolicy(base)).toBe('request');
+ expect(roleForPolicy({ ...base, allowDeleteVideoRequests: true })).toBe('delete');
+ expect(roleForPolicy({ ...base, role: 'admin' })).toBe('admin');
+ });
+});
diff --git a/client/src/components/Configuration/sections/ApiKeysSection/__tests__/useApiKeys.test.ts b/client/src/components/Configuration/sections/ApiKeysSection/__tests__/useApiKeys.test.ts
new file mode 100644
index 000000000..83d753d3c
--- /dev/null
+++ b/client/src/components/Configuration/sections/ApiKeysSection/__tests__/useApiKeys.test.ts
@@ -0,0 +1,181 @@
+import { act, renderHook } from '@testing-library/react';
+import axios from 'axios';
+import { normalizePolicy, ApiKeyPolicy, useApiKeys } from '../useApiKeys';
+import type { ChannelListResponse } from '../../../../Subscriptions/hooks/useChannelList';
+
+jest.mock('axios', () => ({
+ __esModule: true,
+ default: {
+ get: jest.fn(),
+ post: jest.fn(),
+ put: jest.fn(),
+ delete: jest.fn(),
+ },
+}));
+
+const mockedAxios = axios as jest.Mocked;
+
+const basePolicy: ApiKeyPolicy = {
+ role: 'view',
+ allowVideoRequests: false,
+ allowChannelRequests: false,
+ allowDeleteVideoRequests: false,
+ autoApproveVideoRequests: false,
+ autoApproveChannelRequests: false,
+ autoApproveDeleteRequests: false,
+ maxRatingLevel: 3,
+ allowUnrated: false,
+ allowedMediaTypes: ['video'],
+ maxActiveJobs: 5,
+ hourlyWriteLimit: 30,
+ dailyWriteLimit: 200,
+};
+
+describe('normalizePolicy', () => {
+ test.each([
+ ['maxActiveJobs', '0'],
+ ['hourlyWriteLimit', '31'],
+ ['dailyWriteLimit', '1.5'],
+ ['maxActiveJobs', ''],
+ ] as const)('rejects invalid %s value %s', (field, value) => {
+ const result = normalizePolicy({ ...basePolicy, [field]: value });
+ expect(result.policy).toBeUndefined();
+ expect(result.error).toBeTruthy();
+ });
+
+ it('keeps draft strings editable and normalizes valid integer values', () => {
+ const result = normalizePolicy({
+ ...basePolicy,
+ maxActiveJobs: '4',
+ hourlyWriteLimit: '12',
+ dailyWriteLimit: '180',
+ });
+ expect(result.error).toBeUndefined();
+ expect(result.policy).toMatchObject({ maxActiveJobs: 4, hourlyWriteLimit: 12, dailyWriteLimit: 180 });
+ });
+});
+
+describe('useApiKeys', () => {
+ beforeEach(() => {
+ jest.clearAllMocks();
+ });
+
+ it('loads every channel page and preserves the canonical database_id response shape', async () => {
+ const firstPage: ChannelListResponse = {
+ channels: [{
+ database_id: 41,
+ url: 'https://www.youtube.com/channel/UCALPHA',
+ uploader: 'Alpha',
+ terminated_at: null,
+ }],
+ total: 2,
+ totalPages: 2,
+ };
+ const secondPage: ChannelListResponse = {
+ channels: [{
+ database_id: 42,
+ url: 'https://www.youtube.com/channel/UCBETA',
+ uploader: 'Beta',
+ terminated_at: null,
+ }],
+ total: 2,
+ totalPages: 2,
+ };
+ mockedAxios.get
+ .mockResolvedValueOnce({ data: firstPage })
+ .mockResolvedValueOnce({ data: secondPage });
+
+ const { result } = renderHook(() => useApiKeys('token'));
+ let channels;
+ await act(async () => {
+ channels = await result.current.fetchAvailableChannels();
+ });
+
+ expect(channels).toEqual([
+ firstPage.channels[0],
+ secondPage.channels[0],
+ ]);
+ expect(mockedAxios.get).toHaveBeenNthCalledWith(1, '/getchannels', expect.objectContaining({
+ params: { page: 1, pageSize: 100, sortOrder: 'asc' },
+ }));
+ expect(mockedAxios.get).toHaveBeenNthCalledWith(2, '/getchannels', expect.objectContaining({
+ params: { page: 2, pageSize: 100, sortOrder: 'asc' },
+ }));
+ });
+
+ const headers = { headers: { 'x-access-token': 'token' } };
+ const normalizedPolicy = { ...basePolicy, maxActiveJobs: 5, hourlyWriteLimit: 30, dailyWriteLimit: 200 };
+
+ it('creates a download key with only its name', async () => {
+ mockedAxios.post.mockResolvedValueOnce({ data: { success: true } });
+ const { result } = renderHook(() => useApiKeys('token'));
+
+ await act(async () => { await result.current.createApiKey('Laptop'); });
+
+ expect(mockedAxios.post).toHaveBeenCalledWith('/api/keys', { name: 'Laptop' }, headers);
+ });
+
+ it('creates a read-only status key with its role and no policy', async () => {
+ mockedAxios.post.mockResolvedValueOnce({ data: { success: true } });
+ const { result } = renderHook(() => useApiKeys('token'));
+
+ await act(async () => { await result.current.createApiKey('Dashboard', undefined, undefined, 'status_read'); });
+
+ expect(mockedAxios.post).toHaveBeenCalledWith('/api/keys', { name: 'Dashboard', role: 'status_read' }, headers);
+ });
+
+ it('creates an external key with its policy and channel grants', async () => {
+ mockedAxios.post.mockResolvedValueOnce({ data: { success: true } });
+ const { result } = renderHook(() => useApiKeys('token'));
+
+ await act(async () => { await result.current.createApiKey('Client', normalizedPolicy, [3, 9]); });
+
+ expect(mockedAxios.post).toHaveBeenCalledWith(
+ '/api/keys',
+ { name: 'Client', policy: normalizedPolicy, channelIds: [3, 9] },
+ headers
+ );
+ });
+
+ it('saves policy and grants together, revokes, and regenerates by key id', async () => {
+ mockedAxios.put.mockResolvedValueOnce({ data: { success: true } });
+ mockedAxios.delete.mockResolvedValueOnce({ data: { success: true } });
+ mockedAxios.post.mockResolvedValueOnce({ data: { success: true, key: 'secret' } });
+ const { result } = renderHook(() => useApiKeys('token'));
+
+ await act(async () => {
+ await result.current.updateExternalAccess(7, { policy: normalizedPolicy, channelIds: [3] });
+ await result.current.revokeApiKey(7);
+ await result.current.regenerateApiKey(7);
+ });
+
+ expect(mockedAxios.put).toHaveBeenCalledWith(
+ '/api/keys/7/external-access',
+ { policy: normalizedPolicy, channelIds: [3] },
+ headers
+ );
+ expect(mockedAxios.delete).toHaveBeenCalledWith('/api/keys/7', headers);
+ expect(mockedAxios.post).toHaveBeenCalledWith('/api/keys/7/regenerate', undefined, headers);
+ });
+
+ it('loads a key\'s channel grants', async () => {
+ mockedAxios.get.mockResolvedValueOnce({ data: { keyId: 7, channelIds: [3, 9] } });
+ const { result } = renderHook(() => useApiKeys('token'));
+
+ let ids: number[] = [];
+ await act(async () => { ids = await result.current.fetchChannelGrants(7); });
+
+ expect(ids).toEqual([3, 9]);
+ expect(mockedAxios.get).toHaveBeenCalledWith('/api/keys/7/channels', expect.objectContaining(headers));
+ });
+
+ it('skips list requests without a session token', async () => {
+ const { result } = renderHook(() => useApiKeys(null));
+
+ let keys: unknown[] = ['unset'];
+ await act(async () => { keys = await result.current.fetchApiKeys(); });
+
+ expect(keys).toEqual([]);
+ expect(mockedAxios.get).not.toHaveBeenCalled();
+ });
+});
diff --git a/client/src/components/Configuration/sections/ApiKeysSection/__tests__/useExternalAccessEditor.test.ts b/client/src/components/Configuration/sections/ApiKeysSection/__tests__/useExternalAccessEditor.test.ts
new file mode 100644
index 000000000..7c7f7b097
--- /dev/null
+++ b/client/src/components/Configuration/sections/ApiKeysSection/__tests__/useExternalAccessEditor.test.ts
@@ -0,0 +1,123 @@
+import { act, renderHook, waitFor } from '@testing-library/react';
+import { useExternalAccessEditor } from '../useExternalAccessEditor';
+import type { ApiKey, useApiKeys } from '../useApiKeys';
+
+const key: ApiKey = {
+ id: 7,
+ name: 'Client',
+ key_prefix: 'abc12345',
+ created_at: '2026-07-27T18:30:00.000Z',
+ last_used_at: null,
+ is_active: true,
+ usage_count: 0,
+ role: 'view',
+ allow_video_requests: false,
+ allow_channel_requests: false,
+ allow_delete_video_requests: false,
+ auto_approve_video_requests: false,
+ auto_approve_channel_requests: false,
+ auto_approve_delete_requests: false,
+ max_rating_level: 2,
+ allow_unrated: false,
+ allowed_media_types: ['video'],
+ max_active_jobs: 5,
+ hourly_write_limit: 30,
+ daily_write_limit: 200,
+ revoked_at: null,
+};
+
+const channel = (id: number, terminated = false) => ({
+ database_id: id,
+ url: `https://www.youtube.com/channel/UC${id}`,
+ uploader: `Channel ${id}`,
+ terminated_at: terminated ? '2026-07-01T00:00:00.000Z' : null,
+});
+
+type Api = ReturnType;
+
+const makeApi = (overrides: Partial = {}): Api => ({
+ fetchApiKeys: jest.fn(),
+ fetchAvailableChannels: jest.fn().mockResolvedValue([channel(3), channel(4, true), channel(9)]),
+ fetchChannelGrants: jest.fn().mockResolvedValue([3]),
+ createApiKey: jest.fn(),
+ updateExternalAccess: jest.fn().mockResolvedValue({ success: true }),
+ revokeApiKey: jest.fn(),
+ regenerateApiKey: jest.fn(),
+ ...overrides,
+});
+
+const renderEditor = (api: Api) => {
+ const onSaved = jest.fn();
+ const onClose = jest.fn();
+ const view = renderHook(() => useExternalAccessEditor({ apiKey: key, api, onClose, onSaved }));
+ return { ...view, onSaved, onClose };
+};
+
+describe('useExternalAccessEditor', () => {
+ test('loads the current grants and hides terminated channels', async () => {
+ const { result } = renderEditor(makeApi());
+
+ expect(result.current.loading).toBe(true);
+ await waitFor(() => expect(result.current.loading).toBe(false));
+ expect(result.current.selectedChannelIds).toEqual([3]);
+ expect(result.current.channelOptions.map((option) => option.database_id)).toEqual([3, 9]);
+ });
+
+ test('saves a change that narrows access without asking first', async () => {
+ const api = makeApi();
+ const { result, onSaved } = renderEditor(api);
+ await waitFor(() => expect(result.current.loading).toBe(false));
+
+ act(() => result.current.setSelectedChannelIds([]));
+ await act(async () => { await result.current.saveExternalAccess(); });
+
+ expect(api.updateExternalAccess).toHaveBeenCalledWith(7, expect.objectContaining({ channelIds: [] }));
+ expect(onSaved).toHaveBeenCalled();
+ expect(result.current.pendingExternalUpdate).toBeNull();
+ });
+
+ test('asks before saving a change that widens access', async () => {
+ const api = makeApi();
+ const { result, onSaved } = renderEditor(api);
+ await waitFor(() => expect(result.current.loading).toBe(false));
+
+ act(() => result.current.setSelectedChannelIds([3, 9]));
+ await act(async () => { await result.current.saveExternalAccess(); });
+
+ expect(api.updateExternalAccess).not.toHaveBeenCalled();
+ expect(result.current.pendingExternalUpdate).toMatchObject({ keyId: 7, channelIds: [3, 9] });
+
+ await act(async () => { await result.current.confirmPrivilegeIncrease(); });
+ expect(api.updateExternalAccess).toHaveBeenCalledWith(7, expect.objectContaining({ channelIds: [3, 9] }));
+ expect(onSaved).toHaveBeenCalled();
+ });
+
+ test('keeps the dialog open with the error when saving fails', async () => {
+ const api = makeApi({ updateExternalAccess: jest.fn().mockRejectedValue(new Error('Save failed')) });
+ const { result, onSaved } = renderEditor(api);
+ await waitFor(() => expect(result.current.loading).toBe(false));
+
+ await act(async () => { await result.current.saveExternalAccess(); });
+
+ expect(onSaved).not.toHaveBeenCalled();
+ expect(result.current.editSubmitError).toBe('Save failed');
+ expect(result.current.savingPolicy).toBe(false);
+ });
+
+ test('blocks saving until a failed load is retried', async () => {
+ const fetchChannelGrants = jest.fn()
+ .mockRejectedValueOnce(new Error('Network down'))
+ .mockResolvedValueOnce([3]);
+ const api = makeApi({ fetchChannelGrants });
+ const { result } = renderEditor(api);
+ await waitFor(() => expect(result.current.editLoadError).toBe('Network down'));
+
+ await act(async () => { await result.current.saveExternalAccess(); });
+ expect(api.updateExternalAccess).not.toHaveBeenCalled();
+
+ act(() => result.current.reload());
+ await waitFor(() => expect(result.current.loading).toBe(false));
+ expect(result.current.editLoadError).toBeNull();
+ expect(result.current.selectedChannelIds).toEqual([3]);
+ });
+});
diff --git a/client/src/components/Configuration/sections/ApiKeysSection/apiKeyError.ts b/client/src/components/Configuration/sections/ApiKeysSection/apiKeyError.ts
new file mode 100644
index 000000000..1ca7c5f59
--- /dev/null
+++ b/client/src/components/Configuration/sections/ApiKeysSection/apiKeyError.ts
@@ -0,0 +1,8 @@
+import axios from 'axios';
+
+export function apiKeyError(error: unknown, fallback: string) {
+ if (axios.isAxiosError<{ error?: string }>(error)) {
+ return typeof error.response?.data?.error === 'string' ? error.response.data.error : fallback;
+ }
+ return error instanceof Error ? error.message : fallback;
+}
diff --git a/client/src/components/Configuration/sections/ApiKeysSection/policy.ts b/client/src/components/Configuration/sections/ApiKeysSection/policy.ts
new file mode 100644
index 000000000..9c8565653
--- /dev/null
+++ b/client/src/components/Configuration/sections/ApiKeysSection/policy.ts
@@ -0,0 +1,67 @@
+import { ApiKey, ApiKeyPolicy, ApiKeyRole, NormalizedApiKeyPolicy, workloadMax } from './useApiKeys';
+
+export const defaultPolicy: ApiKeyPolicy = {
+ role: 'view',
+ allowVideoRequests: false,
+ allowChannelRequests: false,
+ allowDeleteVideoRequests: false,
+ autoApproveVideoRequests: false,
+ autoApproveChannelRequests: false,
+ autoApproveDeleteRequests: false,
+ maxRatingLevel: 3,
+ allowUnrated: false,
+ allowedMediaTypes: ['video'],
+ maxActiveJobs: workloadMax('maxActiveJobs'),
+ hourlyWriteLimit: workloadMax('hourlyWriteLimit'),
+ dailyWriteLimit: workloadMax('dailyWriteLimit'),
+};
+
+export const legacyRolePermissions = (role: ApiKeyRole) => ({
+ allowVideoRequests: ['request', 'delete', 'admin'].includes(role),
+ allowChannelRequests: ['request', 'delete', 'admin'].includes(role),
+ allowDeleteVideoRequests: ['delete', 'admin'].includes(role),
+});
+
+export const permissionsFromKey = (key: ApiKey) => {
+ const fallback = legacyRolePermissions(key.role);
+ return {
+ allowVideoRequests: key.allow_video_requests ?? fallback.allowVideoRequests,
+ allowChannelRequests: key.allow_channel_requests ?? fallback.allowChannelRequests,
+ allowDeleteVideoRequests:
+ key.allow_delete_video_requests ?? fallback.allowDeleteVideoRequests,
+ };
+};
+
+export const roleForPolicy = (policy: ApiKeyPolicy): ApiKeyRole => {
+ if (policy.role === 'admin') return 'admin';
+ if (policy.allowDeleteVideoRequests) return 'delete';
+ if (policy.allowVideoRequests || policy.allowChannelRequests) return 'request';
+ return 'view';
+};
+
+export const policyFromKey = (key: ApiKey): ApiKeyPolicy => ({
+ role: key.role,
+ ...permissionsFromKey(key),
+ autoApproveVideoRequests: key.auto_approve_video_requests,
+ autoApproveChannelRequests: key.auto_approve_channel_requests,
+ autoApproveDeleteRequests: key.auto_approve_delete_requests,
+ maxRatingLevel: key.max_rating_level,
+ allowUnrated: key.allow_unrated,
+ allowedMediaTypes: key.allowed_media_types,
+ maxActiveJobs: key.max_active_jobs ?? workloadMax('maxActiveJobs'),
+ hourlyWriteLimit: key.hourly_write_limit ?? workloadMax('hourlyWriteLimit'),
+ dailyWriteLimit: key.daily_write_limit ?? workloadMax('dailyWriteLimit'),
+});
+
+export function increasesPrivilege(key: ApiKey, policy: NormalizedApiKeyPolicy, channelIds: number[], originalIds: number[]) {
+ const previous = policyFromKey(key);
+ const permissions = ['allowVideoRequests', 'allowChannelRequests', 'allowDeleteVideoRequests',
+ 'autoApproveVideoRequests', 'autoApproveChannelRequests', 'autoApproveDeleteRequests', 'allowUnrated'] as const;
+ return permissions.some(field => policy[field] && !previous[field]) ||
+ policy.maxRatingLevel > previous.maxRatingLevel ||
+ policy.allowedMediaTypes.some(type => !previous.allowedMediaTypes.includes(type)) ||
+ policy.maxActiveJobs > Number(previous.maxActiveJobs) ||
+ policy.hourlyWriteLimit > Number(previous.hourlyWriteLimit) ||
+ policy.dailyWriteLimit > Number(previous.dailyWriteLimit) ||
+ channelIds.some(id => !originalIds.includes(id));
+}
diff --git a/client/src/components/Configuration/sections/ApiKeysSection/useApiKeys.ts b/client/src/components/Configuration/sections/ApiKeysSection/useApiKeys.ts
new file mode 100644
index 000000000..6ff5bab14
--- /dev/null
+++ b/client/src/components/Configuration/sections/ApiKeysSection/useApiKeys.ts
@@ -0,0 +1,186 @@
+import { useCallback, useMemo } from 'react';
+import axios from 'axios';
+import {
+ ChannelListEntry,
+ ChannelListResponse,
+} from '../../../Subscriptions/hooks/useChannelList';
+
+export interface ApiKey {
+ id: number;
+ name: string;
+ key_prefix: string;
+ created_at: string;
+ last_used_at: string | null;
+ is_active: boolean;
+ usage_count: number;
+ channel_grant_count?: number;
+ role: ApiKeyRole;
+ auto_approve_video_requests: boolean;
+ auto_approve_channel_requests: boolean;
+ auto_approve_delete_requests: boolean;
+ allow_video_requests: boolean;
+ allow_channel_requests: boolean;
+ allow_delete_video_requests: boolean;
+ max_rating_level: number;
+ allow_unrated: boolean;
+ allowed_media_types: MediaType[];
+ max_active_jobs?: number;
+ hourly_write_limit?: number;
+ daily_write_limit?: number;
+ revoked_at: string | null;
+}
+
+export type ApiKeyRole = 'legacy_download' | 'status_read' | 'view' | 'request' | 'delete' | 'admin';
+export const DOWNLOAD_ROLE = 'legacy_download';
+export const STATUS_READ_ROLE = 'status_read';
+
+// Download and read-only status keys reach one fixed endpoint each and carry no
+// external policy; every other role is an external access key.
+export const isSimpleKeyRole = (role: ApiKeyRole) => role === DOWNLOAD_ROLE || role === STATUS_READ_ROLE;
+export type MediaType = 'video' | 'short' | 'livestream';
+
+export interface ApiKeyPolicy {
+ role: ApiKeyRole;
+ allowVideoRequests: boolean;
+ allowChannelRequests: boolean;
+ allowDeleteVideoRequests: boolean;
+ autoApproveVideoRequests: boolean;
+ autoApproveChannelRequests: boolean;
+ autoApproveDeleteRequests: boolean;
+ maxRatingLevel: number;
+ allowUnrated: boolean;
+ allowedMediaTypes: MediaType[];
+ maxActiveJobs: number | string;
+ hourlyWriteLimit: number | string;
+ dailyWriteLimit: number | string;
+}
+
+export type NormalizedApiKeyPolicy = Omit<
+ ApiKeyPolicy,
+ 'maxActiveJobs' | 'hourlyWriteLimit' | 'dailyWriteLimit'
+> & {
+ maxActiveJobs: number;
+ hourlyWriteLimit: number;
+ dailyWriteLimit: number;
+};
+
+export interface ApiKeyCreatedResponse {
+ success: boolean;
+ message: string;
+ id: number;
+ name: string;
+ key: string;
+ prefix: string;
+}
+
+interface ApiKeyListResponse { keys: ApiKey[] }
+interface ChannelGrantsResponse { keyId: number; channelIds: number[] }
+interface ApiKeyRequest { policy: NormalizedApiKeyPolicy; channelIds: number[] }
+
+export interface NormalizedPolicyResult {
+ policy?: NormalizedApiKeyPolicy;
+ error?: string;
+}
+
+// Mirrors the per-key ceilings enforced by server/middleware/externalApiAuth.js.
+export const WORKLOAD_LIMITS = [
+ { field: 'maxActiveJobs', label: 'Active jobs', min: 1, max: 5 },
+ { field: 'hourlyWriteLimit', label: 'Writes per hour', min: 1, max: 30 },
+ { field: 'dailyWriteLimit', label: 'Writes per day', min: 1, max: 200 },
+] as const;
+
+export type WorkloadField = (typeof WORKLOAD_LIMITS)[number]['field'];
+
+export const workloadMax = (field: WorkloadField) =>
+ WORKLOAD_LIMITS.find((limit) => limit.field === field)?.max ?? 1;
+
+export const normalizePolicy = (policy: ApiKeyPolicy): NormalizedPolicyResult => {
+ const normalized = { ...policy };
+ for (const { field, label, min, max } of WORKLOAD_LIMITS) {
+ const value = String(policy[field]).trim();
+ if (!/^\d+$/.test(value) || Number(value) < min || Number(value) > max) {
+ return { error: `${label} must be an integer from ${min} to ${max}.` };
+ }
+ normalized[field] = Number(value);
+ }
+ return { policy: normalized as NormalizedApiKeyPolicy };
+};
+
+export const useApiKeys = (token: string | null) => {
+ const headers = useMemo(() => (token ? { 'x-access-token': token } : undefined), [token]);
+ const fetchApiKeys = useCallback(async () => {
+ if (!token) return [];
+ const { data } = await axios.get('/api/keys', { headers });
+ return data.keys || [];
+ }, [headers, token]);
+
+ const fetchAvailableChannels = useCallback(async (signal?: AbortSignal) => {
+ if (!token) return [];
+ const channels: ChannelListEntry[] = [];
+ let page = 1;
+ let totalPages = 1;
+ do {
+ const { data } = await axios.get('/getchannels', {
+ headers, signal,
+ params: { page, pageSize: 100, sortOrder: 'asc' },
+ });
+ channels.push(...(data.channels || []));
+ totalPages = Number.isInteger(Number(data.totalPages)) && Number(data.totalPages) > 0
+ ? Number(data.totalPages) : 1;
+ page += 1;
+ } while (page <= totalPages);
+ return channels;
+ }, [headers, token]);
+
+ const fetchChannelGrants = useCallback(async (keyId: number, signal?: AbortSignal) => {
+ const { data } = await axios.get(`/api/keys/${keyId}/channels`, { headers, signal });
+ return data.channelIds || [];
+ }, [headers]);
+
+ const createApiKey = useCallback(async (
+ name: string,
+ policy?: NormalizedApiKeyPolicy,
+ channelIds?: number[],
+ role?: typeof STATUS_READ_ROLE
+ ) => {
+ const { data } = await axios.post('/api/keys', {
+ name,
+ ...(role ? { role } : {}),
+ ...(policy ? { policy, channelIds: channelIds || [] } : {}),
+ }, { headers });
+ return data;
+ }, [headers]);
+
+ const updateExternalAccess = useCallback(async (keyId: number, request: ApiKeyRequest) => {
+ const { data } = await axios.put(`/api/keys/${keyId}/external-access`, request, { headers });
+ return data;
+ }, [headers]);
+
+ const revokeApiKey = useCallback(async (keyId: number) => {
+ const { data } = await axios.delete(`/api/keys/${keyId}`, { headers });
+ return data;
+ }, [headers]);
+
+ const regenerateApiKey = useCallback(async (keyId: number) => {
+ const { data } = await axios.post(`/api/keys/${keyId}/regenerate`, undefined, { headers });
+ return data;
+ }, [headers]);
+
+ return useMemo(() => ({
+ fetchApiKeys,
+ fetchAvailableChannels,
+ fetchChannelGrants,
+ createApiKey,
+ updateExternalAccess,
+ revokeApiKey,
+ regenerateApiKey,
+ }), [
+ createApiKey,
+ fetchApiKeys,
+ fetchAvailableChannels,
+ fetchChannelGrants,
+ regenerateApiKey,
+ revokeApiKey,
+ updateExternalAccess,
+ ]);
+};
diff --git a/client/src/components/Configuration/sections/ApiKeysSection/useExternalAccessEditor.ts b/client/src/components/Configuration/sections/ApiKeysSection/useExternalAccessEditor.ts
new file mode 100644
index 000000000..2b65b46d8
--- /dev/null
+++ b/client/src/components/Configuration/sections/ApiKeysSection/useExternalAccessEditor.ts
@@ -0,0 +1,78 @@
+import { useEffect, useRef, useState } from 'react';
+import type { ChannelListEntry } from '../../../Subscriptions/hooks/useChannelList';
+import { ApiKey, ApiKeyPolicy, NormalizedApiKeyPolicy, normalizePolicy, useApiKeys } from './useApiKeys';
+import { increasesPrivilege, policyFromKey } from './policy';
+import { apiKeyError } from './apiKeyError';
+
+interface Update { keyId: number; policy: NormalizedApiKeyPolicy; channelIds: number[]; }
+interface Props { apiKey: ApiKey; api: ReturnType; onClose: () => void; onSaved: () => void; }
+interface LoadState { channels: ChannelListEntry[]; originalIds: number[]; loading: boolean; error: string | null; }
+export function useExternalAccessEditor({ apiKey, api, onClose, onSaved }: Props) {
+ const [editPolicy, setPolicy] = useState(() => policyFromKey(apiKey));
+ const [selectedChannelIds, setSelectedChannelIds] = useState([]);
+ const [channelSearch, setChannelSearch] = useState('');
+ const [load, setLoad] = useState({ channels: [], originalIds: [], loading: true, error: null });
+ const [editSubmitError, setEditSubmitError] = useState(null);
+ const [pendingExternalUpdate, setPendingExternalUpdate] = useState(null);
+ const [savingPolicy, setSavingPolicy] = useState(false);
+ const [reloadToken, setReloadToken] = useState(0);
+ const busy = useRef(false);
+ const active = useRef(true);
+ useEffect(() => {
+ active.current = true;
+ return () => { active.current = false; };
+ }, []);
+ useEffect(() => {
+ const controller = new AbortController();
+ setLoad(state => ({ ...state, loading: true, error: null }));
+ void Promise.all([
+ api.fetchAvailableChannels(controller.signal), api.fetchChannelGrants(apiKey.id, controller.signal),
+ ]).then(([channels, ids]) => {
+ if (controller.signal.aborted) return;
+ setSelectedChannelIds(ids);
+ setLoad({ channels: channels.filter(channel => !channel.terminated_at), originalIds: ids, loading: false, error: null });
+ }).catch(error => {
+ if (!controller.signal.aborted) setLoad(state => ({ ...state, loading: false, error: apiKeyError(error, 'Failed to load channel grants and available channels') }));
+ });
+ return () => controller.abort();
+ }, [api, apiKey.id, reloadToken]);
+
+ const submit = async (update: Update) => {
+ if (busy.current) return;
+ busy.current = true;
+ setSavingPolicy(true);
+ setEditSubmitError(null);
+ try {
+ await api.updateExternalAccess(update.keyId, { policy: update.policy, channelIds: update.channelIds });
+ if (active.current) onSaved();
+ } catch (error) {
+ if (active.current) {
+ setPendingExternalUpdate(null);
+ setEditSubmitError(apiKeyError(error, 'Failed to save external access'));
+ }
+ } finally {
+ busy.current = false;
+ if (active.current) setSavingPolicy(false);
+ }
+ };
+ const saveExternalAccess = async () => {
+ if (busy.current || load.loading || load.error) return;
+ setEditSubmitError(null);
+ const result = normalizePolicy(editPolicy);
+ if (!result.policy) { setEditSubmitError(result.error || 'Invalid policy values'); return; }
+ const update = { keyId: apiKey.id, policy: result.policy, channelIds: selectedChannelIds };
+ if (increasesPrivilege(apiKey, result.policy, selectedChannelIds, load.originalIds)) {
+ setPendingExternalUpdate(update);
+ } else await submit(update);
+ };
+ return {
+ editPolicy, channelOptions: load.channels, channelSearch, selectedChannelIds, savingPolicy,
+ loading: load.loading, editLoadError: load.error, editSubmitError, pendingExternalUpdate,
+ setEditPolicy: (policy: ApiKeyPolicy) => { setPolicy(policy); setEditSubmitError(null); },
+ setChannelSearch, setSelectedChannelIds,
+ closeEditDialog: () => { if (!busy.current) onClose(); },
+ reload: () => setReloadToken(value => value + 1), saveExternalAccess,
+ cancelPrivilegeConfirmation: () => { if (!busy.current) setPendingExternalUpdate(null); },
+ confirmPrivilegeIncrease: () => pendingExternalUpdate && submit(pendingExternalUpdate),
+ };
+}
diff --git a/client/src/components/Configuration/sections/__tests__/ApiKeysSection.privilege.test.tsx b/client/src/components/Configuration/sections/__tests__/ApiKeysSection.privilege.test.tsx
new file mode 100644
index 000000000..888437799
--- /dev/null
+++ b/client/src/components/Configuration/sections/__tests__/ApiKeysSection.privilege.test.tsx
@@ -0,0 +1,347 @@
+import React from 'react';
+import { act, screen, waitFor } from '@testing-library/react';
+import userEvent from '@testing-library/user-event';
+import '@testing-library/jest-dom';
+import ApiKeysSection from '../ApiKeysSection';
+import { renderWithProviders } from '../../../../test-utils';
+import { useApiKeys } from '../ApiKeysSection/useApiKeys';
+import type { ChannelListEntry } from '../../../Subscriptions/hooks/useChannelList';
+
+jest.mock('../ApiKeysSection/useApiKeys', () => {
+ const actual = jest.requireActual('../ApiKeysSection/useApiKeys');
+ return { ...actual, useApiKeys: jest.fn() };
+});
+
+const mockedUseApiKeys = useApiKeys as jest.MockedFunction;
+const externalKey = {
+ id: 7,
+ name: 'External Client',
+ key_prefix: 'client1234',
+ created_at: '2026-07-27T18:30:00.000Z',
+ last_used_at: null,
+ is_active: true,
+ usage_count: 0,
+ channel_grant_count: 0,
+ role: 'view' as const,
+ allow_video_requests: false,
+ allow_channel_requests: false,
+ allow_delete_video_requests: false,
+ auto_approve_video_requests: false,
+ auto_approve_channel_requests: false,
+ auto_approve_delete_requests: false,
+ max_rating_level: 3,
+ allow_unrated: false,
+ allowed_media_types: ['video' as const],
+ max_active_jobs: 5,
+ hourly_write_limit: 30,
+ daily_write_limit: 200,
+ revoked_at: null,
+};
+
+const props = (): React.ComponentProps => ({
+ token: 'test-token',
+ apiKeyRateLimit: 10,
+ externalApiEnabled: true,
+ onRateLimitChange: jest.fn(),
+ showRequestsNavLink: true,
+ onShowRequestsNavLinkChange: jest.fn(),
+});
+
+const safeChannel: ChannelListEntry = {
+ database_id: 12,
+ url: 'https://www.youtube.com/channel/UC123',
+ channel_id: 'UC123',
+ uploader: 'Safe Channel',
+ title: 'Safe Channel',
+ terminated_at: null,
+};
+
+const deferred = () => {
+ let resolve!: (value: T) => void;
+ const promise = new Promise((resolvePromise) => {
+ resolve = resolvePromise;
+ });
+ return { promise, resolve };
+};
+
+describe('ApiKeysSection privilege confirmation', () => {
+ beforeEach(() => {
+ jest.clearAllMocks();
+ mockedUseApiKeys.mockReturnValue({
+ fetchApiKeys: jest.fn().mockResolvedValue([externalKey]),
+ fetchAvailableChannels: jest.fn().mockResolvedValue([safeChannel]),
+ fetchChannelGrants: jest.fn().mockResolvedValue([]),
+ createApiKey: jest.fn(),
+ updateExternalAccess: jest.fn().mockResolvedValue({ success: true }),
+ revokeApiKey: jest.fn(),
+ regenerateApiKey: jest.fn(),
+ });
+ });
+
+ async function openEditor() {
+ const user = userEvent.setup();
+ renderWithProviders( );
+ await user.click(await screen.findByRole('button', {
+ name: 'Edit External Client external access',
+ }));
+ await screen.findByLabelText('Request videos');
+ return user;
+ }
+
+ it('uses the app Dialog and never calls native confirm for an increase', async () => {
+ const nativeConfirm = jest.spyOn(window, 'confirm');
+ const user = await openEditor();
+ await user.click(screen.getByLabelText('Request videos'));
+ await user.click(screen.getByRole('button', { name: 'Save External Access' }));
+
+ expect(nativeConfirm).not.toHaveBeenCalled();
+ expect(screen.getByText('Confirm expanded external access?')).toBeInTheDocument();
+ nativeConfirm.mockRestore();
+ });
+
+ it('cancels an increase without submitting', async () => {
+ const user = await openEditor();
+ await user.click(screen.getByLabelText('Request videos'));
+ await user.click(screen.getByRole('button', { name: 'Save External Access' }));
+ await user.click(screen.getByRole('button', { name: 'Cancel' }));
+
+ expect(mockedUseApiKeys.mock.results[0].value.updateExternalAccess).not.toHaveBeenCalled();
+ });
+
+ it('confirms an increase with exactly one normalized update', async () => {
+ const user = await openEditor();
+ await user.click(screen.getByLabelText('Request videos'));
+ await user.click(screen.getByRole('button', { name: 'Save External Access' }));
+ await user.click(screen.getByRole('button', { name: 'Continue' }));
+
+ const update = mockedUseApiKeys.mock.results[0].value.updateExternalAccess;
+ await waitFor(() => expect(update).toHaveBeenCalledTimes(1));
+ expect(update).toHaveBeenCalledWith(7, expect.objectContaining({
+ policy: expect.objectContaining({ allowVideoRequests: true, maxActiveJobs: 5 }),
+ channelIds: [],
+ }));
+ });
+
+ it('submits a direct non-increase without confirmation', async () => {
+ const user = await openEditor();
+ await user.click(screen.getByRole('button', { name: 'Save External Access' }));
+
+ const update = mockedUseApiKeys.mock.results[0].value.updateExternalAccess;
+ await waitFor(() => expect(update).toHaveBeenCalledTimes(1));
+ expect(screen.queryByText('Confirm expanded external access?')).not.toBeInTheDocument();
+ });
+
+ it('saves a corrected numeric policy without reloading channel grants', async () => {
+ const user = await openEditor();
+ const activeJobs = screen.getByRole('spinbutton', { name: 'Active jobs' });
+ const save = screen.getByRole('button', { name: 'Save External Access' });
+ await waitFor(() => expect(save).toBeEnabled());
+
+ await user.clear(activeJobs);
+ await user.click(save);
+ expect(screen.getByText('Active jobs must be an integer from 1 to 5.')).toBeInTheDocument();
+ expect(save).toBeEnabled();
+
+ await user.type(activeJobs, '3');
+ expect(screen.queryByText('Active jobs must be an integer from 1 to 5.')).not.toBeInTheDocument();
+ await user.click(save);
+
+ const api = mockedUseApiKeys.mock.results[0].value;
+ await waitFor(() => expect(api.updateExternalAccess).toHaveBeenCalledWith(
+ 7,
+ expect.objectContaining({
+ policy: expect.objectContaining({ maxActiveJobs: 3 }),
+ channelIds: [],
+ })
+ ));
+ expect(api.fetchChannelGrants).toHaveBeenCalledTimes(1);
+ expect(api.fetchAvailableChannels).toHaveBeenCalledTimes(1);
+ });
+
+ it('allows retrying a failed save without reloading channel grants', async () => {
+ const user = await openEditor();
+ const api = mockedUseApiKeys.mock.results[0].value;
+ const update = api.updateExternalAccess as jest.Mock;
+ update.mockRejectedValueOnce(new Error('Temporary save failure'));
+ const save = screen.getByRole('button', { name: 'Save External Access' });
+ await waitFor(() => expect(save).toBeEnabled());
+
+ await user.click(save);
+ expect(await screen.findByText('Temporary save failure')).toBeInTheDocument();
+ expect(save).toBeEnabled();
+ await user.click(save);
+
+ await waitFor(() => expect(update).toHaveBeenCalledTimes(2));
+ expect(api.fetchChannelGrants).toHaveBeenCalledTimes(1);
+ });
+
+ it('keeps Save disabled until channel grants and channel options finish loading', async () => {
+ const grants = deferred();
+ const channels = deferred();
+ const updateExternalAccess = jest.fn();
+ mockedUseApiKeys.mockReturnValue({
+ fetchApiKeys: jest.fn().mockResolvedValue([externalKey]),
+ fetchAvailableChannels: jest.fn().mockReturnValue(channels.promise),
+ fetchChannelGrants: jest.fn().mockReturnValue(grants.promise),
+ createApiKey: jest.fn(),
+ updateExternalAccess,
+ revokeApiKey: jest.fn(),
+ regenerateApiKey: jest.fn(),
+ });
+
+ const user = userEvent.setup();
+ renderWithProviders( );
+ await user.click(await screen.findByRole('button', {
+ name: 'Edit External Client external access',
+ }));
+
+ const save = screen.getByRole('button', { name: 'Save External Access' });
+ expect(save).toBeDisabled();
+ await user.click(save);
+ expect(updateExternalAccess).not.toHaveBeenCalled();
+
+ await act(async () => {
+ grants.resolve([12]);
+ channels.resolve([safeChannel]);
+ });
+ await waitFor(() => expect(save).toBeEnabled());
+ });
+
+ it('ignores a slow response from a previously opened key', async () => {
+ const slowGrants = deferred();
+ const slowChannels = deferred();
+ const secondChannel: ChannelListEntry = {
+ database_id: 22,
+ url: 'https://www.youtube.com/channel/UCSECOND',
+ channel_id: 'UCSECOND',
+ uploader: 'Second Channel',
+ title: 'Second Channel',
+ terminated_at: null,
+ };
+ const secondKey = { ...externalKey, id: 8, name: 'Second Client' };
+ const fetchAvailableChannels = jest.fn()
+ .mockReturnValueOnce(slowChannels.promise)
+ .mockResolvedValueOnce([secondChannel]);
+ const fetchChannelGrants = jest.fn((keyId: number) => (
+ keyId === externalKey.id ? slowGrants.promise : Promise.resolve([22])
+ ));
+ mockedUseApiKeys.mockReturnValue({
+ fetchApiKeys: jest.fn().mockResolvedValue([externalKey, secondKey]),
+ fetchAvailableChannels,
+ fetchChannelGrants,
+ createApiKey: jest.fn(),
+ updateExternalAccess: jest.fn(),
+ revokeApiKey: jest.fn(),
+ regenerateApiKey: jest.fn(),
+ });
+
+ const user = userEvent.setup();
+ renderWithProviders( );
+ await user.click(await screen.findByRole('button', {
+ name: 'Edit External Client external access',
+ }));
+ await user.click(screen.getByRole('button', { name: 'Cancel' }));
+ await user.click(await screen.findByRole('button', {
+ name: 'Edit Second Client external access',
+ }));
+
+ expect(await screen.findByText('Edit External Access — Second Client')).toBeInTheDocument();
+ const secondChannelCheckbox = await screen.findByLabelText('Second Channel');
+ await waitFor(() => expect(secondChannelCheckbox).toBeChecked());
+
+ await act(async () => {
+ slowGrants.resolve([12]);
+ slowChannels.resolve([safeChannel]);
+ });
+
+ expect(screen.getByText('Edit External Access — Second Client')).toBeInTheDocument();
+ expect(secondChannelCheckbox).toBeChecked();
+ expect(screen.queryByLabelText('Safe Channel')).not.toBeInTheDocument();
+ });
+});
+
+describe('API key dialog lifecycle', () => {
+ beforeEach(() => {
+ jest.clearAllMocks();
+ mockedUseApiKeys.mockReturnValue({
+ fetchApiKeys: jest.fn().mockResolvedValue([externalKey]),
+ fetchAvailableChannels: jest.fn().mockResolvedValue([safeChannel]),
+ fetchChannelGrants: jest.fn().mockResolvedValue([]),
+ createApiKey: jest.fn(), updateExternalAccess: jest.fn().mockResolvedValue({ success: true }),
+ revokeApiKey: jest.fn(), regenerateApiKey: jest.fn(),
+ });
+ });
+
+ it('ignores a cancelled create load while a different editor is loading', async () => {
+ const createChannels = deferred();
+ const editChannels = deferred();
+ const api = mockedUseApiKeys('test-token');
+ (api.fetchAvailableChannels as jest.Mock).mockReturnValueOnce(createChannels.promise)
+ .mockReturnValueOnce(editChannels.promise);
+ const user = userEvent.setup();
+ renderWithProviders( );
+ await user.click(await screen.findByRole('button', { name: 'Create external key' }));
+ await user.click(screen.getByRole('button', { name: 'Cancel' }));
+ await user.click(screen.getByRole('button', { name: 'Edit External Client external access' }));
+ await act(async () => createChannels.resolve([{ ...safeChannel, database_id: 99, title: 'Obsolete channel' }]));
+ expect(screen.getByRole('button', { name: 'Save External Access' })).toBeDisabled();
+ expect(screen.queryByLabelText('Obsolete channel')).not.toBeInTheDocument();
+ await act(async () => editChannels.resolve([safeChannel]));
+ expect(await screen.findByLabelText('Safe Channel')).toBeInTheDocument();
+ expect(screen.getByRole('button', { name: 'Save External Access' })).toBeEnabled();
+ });
+
+ it('blocks duplicate creation and cannot dismiss a submission before the secret arrives', async () => {
+ const created = deferred<{ success: boolean; id: number; name: string; key: string; prefix: string; message: string }>();
+ const api = mockedUseApiKeys('test-token');
+ (api.createApiKey as jest.Mock).mockReturnValue(created.promise);
+ const user = userEvent.setup();
+ renderWithProviders( );
+ await user.click(await screen.findByRole('button', { name: 'Create external key' }));
+ await user.type(screen.getByLabelText('Key Name'), 'Synthetic client');
+ await user.dblClick(screen.getByRole('button', { name: 'Create' }));
+ expect(api.createApiKey).toHaveBeenCalledTimes(1);
+ expect(screen.getByRole('button', { name: 'Cancel' })).toBeDisabled();
+ await user.keyboard('{Escape}');
+ expect(screen.getByText('Create External Access Key')).toBeInTheDocument();
+ await act(async () => created.resolve({ success: true, id: 1, name: 'Synthetic client', key: 'synthetic-only-secret', prefix: 'synthetic', message: '' }));
+ expect(await screen.findByText('synthetic-only-secret')).toBeInTheDocument();
+ await user.click(screen.getByRole('button', { name: 'Done' }));
+ expect(screen.queryByText('synthetic-only-secret')).not.toBeInTheDocument();
+ });
+
+ it('shows bookmarklet key creation errors inside the dialog when external access is disabled', async () => {
+ const api = mockedUseApiKeys('test-token');
+ (api.createApiKey as jest.Mock).mockRejectedValue(new Error('Creation failed'));
+ const user = userEvent.setup();
+ renderWithProviders( );
+ await user.click(await screen.findByRole('button', { name: 'Create Key' }));
+ await user.type(screen.getByLabelText('Key Name'), 'Bookmarklet');
+ await user.click(screen.getByRole('button', { name: 'Create' }));
+ expect(await screen.findByText('Creation failed')).toBeInTheDocument();
+ expect(screen.getByRole('button', { name: 'Create' })).toBeEnabled();
+ });
+
+ it('keeps an edit open during saving and only submits it once', async () => {
+ const saved = deferred<{ success: boolean }>();
+ const api = mockedUseApiKeys('test-token');
+ (api.updateExternalAccess as jest.Mock).mockReturnValue(saved.promise);
+ const user = userEvent.setup();
+ renderWithProviders( );
+ await user.click(await screen.findByRole('button', { name: 'Edit External Client external access' }));
+ await waitFor(() => expect(screen.getByRole('button', { name: 'Save External Access' })).toBeEnabled());
+ await user.dblClick(screen.getByRole('button', { name: 'Save External Access' }));
+ expect(api.updateExternalAccess).toHaveBeenCalledTimes(1);
+ expect(screen.getByRole('button', { name: 'Cancel' })).toBeDisabled();
+ await user.keyboard('{Escape}');
+ expect(screen.getByText('Edit External Access — External Client')).toBeInTheDocument();
+ await act(async () => saved.resolve({ success: true }));
+ await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument());
+ });
+
+ it('fails closed when effective feature availability has not been supplied', async () => {
+ renderWithProviders( );
+ await screen.findByRole('button', { name: 'Create Key' });
+ expect(screen.queryByRole('button', { name: 'Create external key' })).not.toBeInTheDocument();
+ });
+});
diff --git a/client/src/components/Configuration/sections/__tests__/ApiKeysSection.story.tsx b/client/src/components/Configuration/sections/__tests__/ApiKeysSection.story.tsx
index 5dc5ef227..0443516aa 100644
--- a/client/src/components/Configuration/sections/__tests__/ApiKeysSection.story.tsx
+++ b/client/src/components/Configuration/sections/__tests__/ApiKeysSection.story.tsx
@@ -9,12 +9,19 @@ const meta: Meta = {
args: {
token: 'storybook-token',
apiKeyRateLimit: 10,
+ externalApiEnabled: true,
onRateLimitChange: () => {},
+ showRequestsNavLink: true,
+ onShowRequestsNavLinkChange: () => {},
},
parameters: {
msw: {
handlers: [
http.get('/api/keys', () => HttpResponse.json({ keys: [] })),
+ http.get('/getchannels', () => HttpResponse.json({
+ channels: [],
+ totalPages: 1,
+ })),
],
},
},
@@ -26,8 +33,85 @@ type Story = StoryObj;
export const OpensCreateDialog: Story = {
play: async ({ canvasElement }) => {
const canvas = within(canvasElement);
- await userEvent.click(await canvas.findByRole('button', { name: /create key/i }));
+ await userEvent.click(await canvas.findByRole('button', { name: /create external key/i }));
const body = within(canvasElement.ownerDocument.body);
- await expect(await body.findByText('Create API Key')).toBeInTheDocument();
+ await expect(await body.findByText('Create External Access Key')).toBeInTheDocument();
+ await expect(await body.findByText('View included')).toBeInTheDocument();
+ },
+};
+
+export const ResponsiveKeyCards: Story = {
+ parameters: {
+ viewport: { defaultViewport: 'mobile1' },
+ msw: {
+ handlers: [
+ http.get('/api/keys', () => HttpResponse.json({
+ keys: [{
+ id: 4,
+ name: 'External Client',
+ key_prefix: 'client1234',
+ created_at: '2026-07-27T18:30:00.000Z',
+ last_used_at: '2026-07-27T19:00:00.000Z',
+ is_active: true,
+ usage_count: 12,
+ role: 'delete',
+ allow_video_requests: true,
+ allow_channel_requests: true,
+ allow_delete_video_requests: true,
+ auto_approve_video_requests: false,
+ auto_approve_channel_requests: true,
+ auto_approve_delete_requests: false,
+ max_rating_level: 3,
+ allow_unrated: false,
+ allowed_media_types: ['video', 'short'],
+ revoked_at: null,
+ }],
+ })),
+ ],
+ },
+ },
+ play: async ({ canvasElement }) => {
+ const canvas = within(canvasElement);
+ await expect(await canvas.findByText('External Client')).toBeInTheDocument();
+ await expect(await canvas.findByLabelText('Movie rating ceiling PG-13')).toBeInTheDocument();
+ await expect(await canvas.findByLabelText('TV rating ceiling TV-14')).toBeInTheDocument();
+ await expect(await canvas.findByText('Channels · Auto')).toBeInTheDocument();
+ },
+};
+
+export const BookmarkletKeysFirst: Story = {
+ parameters: {
+ msw: {
+ handlers: [
+ http.get('/api/keys', () => HttpResponse.json({
+ keys: [{
+ id: 2,
+ name: 'Old Bookmarklet',
+ key_prefix: 'legacy12',
+ created_at: '2026-07-01T18:30:00.000Z',
+ last_used_at: null,
+ is_active: true,
+ usage_count: 3,
+ role: 'legacy_download',
+ allow_video_requests: false,
+ allow_channel_requests: false,
+ allow_delete_video_requests: false,
+ auto_approve_video_requests: false,
+ auto_approve_channel_requests: false,
+ auto_approve_delete_requests: false,
+ max_rating_level: 3,
+ allow_unrated: false,
+ allowed_media_types: ['video'],
+ revoked_at: null,
+ }],
+ })),
+ ],
+ },
+ },
+ play: async ({ canvasElement }) => {
+ const canvas = within(canvasElement);
+ await expect(await canvas.findByText('No external access keys yet.')).toBeInTheDocument();
+ await expect(await canvas.findByText('Old Bookmarklet')).toBeInTheDocument();
+ await expect(await canvas.findByText('legacy12...')).toBeInTheDocument();
},
};
diff --git a/client/src/components/Configuration/sections/__tests__/ApiKeysSection.test.tsx b/client/src/components/Configuration/sections/__tests__/ApiKeysSection.test.tsx
index 145fbe9cf..ef8b3eace 100644
--- a/client/src/components/Configuration/sections/__tests__/ApiKeysSection.test.tsx
+++ b/client/src/components/Configuration/sections/__tests__/ApiKeysSection.test.tsx
@@ -4,810 +4,675 @@ import userEvent from '@testing-library/user-event';
import '@testing-library/jest-dom';
import ApiKeysSection from '../ApiKeysSection';
import { renderWithProviders } from '../../../../test-utils';
+import { useApiKeys } from '../ApiKeysSection/useApiKeys';
+import type { ChannelListResponse } from '../../../Subscriptions/hooks/useChannelList';
+
+jest.mock('../ApiKeysSection/useApiKeys', () => {
+ const actual = jest.requireActual('../ApiKeysSection/useApiKeys');
+ return { ...actual, useApiKeys: jest.fn() };
+});
+
+const mockedUseApiKeys = useApiKeys as jest.MockedFunction;
-// Mock fetch globally
const mockFetch = jest.fn();
global.fetch = mockFetch;
-const createSectionProps = (
- overrides: Partial> = {}
-): React.ComponentProps => ({
+const props = (): React.ComponentProps => ({
token: 'test-token-123',
apiKeyRateLimit: 10,
+ externalApiEnabled: true,
onRateLimitChange: jest.fn(),
- ...overrides,
+ showRequestsNavLink: true,
+ onShowRequestsNavLinkChange: jest.fn(),
});
-// Helper to expand accordion
-
-// Mock API key data
-const mockApiKeys = [
- {
- id: 1,
- name: 'My Bookmarklet',
- key_prefix: 'abc12345',
- created_at: '2024-01-15T10:30:00Z',
- last_used_at: '2024-01-20T15:45:00Z',
- is_active: true,
- usage_count: 42,
- },
- {
- id: 2,
- name: 'iPhone Shortcut',
- key_prefix: 'xyz98765',
- created_at: '2024-01-10T08:00:00Z',
- last_used_at: null,
- is_active: true,
- usage_count: 0,
- },
-];
-
-const mockCreatedKeyResponse = {
+const externalKey = {
+ id: 7,
+ name: 'External Client',
+ key_prefix: 'client1234',
+ created_at: '2026-07-27T18:30:00.000Z',
+ last_used_at: '2026-07-27T19:00:00.000Z',
+ is_active: true,
+ usage_count: 12,
+ channel_grant_count: 1,
+ role: 'delete',
+ allow_video_requests: true,
+ allow_channel_requests: true,
+ allow_delete_video_requests: true,
+ auto_approve_video_requests: false,
+ auto_approve_channel_requests: true,
+ auto_approve_delete_requests: false,
+ max_rating_level: 3,
+ allow_unrated: false,
+ allowed_media_types: ['video', 'short'],
+ revoked_at: null as string | null,
+};
+
+const legacyKey = {
+ ...externalKey,
+ id: 2,
+ name: 'My Bookmarklet',
+ key_prefix: 'abc12345',
+ role: 'legacy_download',
+ allow_video_requests: false,
+ allow_channel_requests: false,
+ allow_delete_video_requests: false,
+ auto_approve_channel_requests: false,
+ usage_count: 42,
+};
+
+const createdKey = {
success: true,
message: 'API key created. Save this key - it will not be shown again!',
- id: 3,
+ id: 8,
name: 'New Key',
key: 'abc12345def67890abc12345def67890abc12345def67890abc12345def67890',
prefix: 'abc12345',
};
-describe('ApiKeysSection Component', () => {
- beforeEach(() => {
- jest.clearAllMocks();
- mockFetch.mockClear();
-
- // Default mock for fetching API keys
- mockFetch.mockResolvedValue({
- ok: true,
- json: jest.fn().mockResolvedValue({ keys: [] }),
- });
- });
-
- describe('Component Rendering', () => {
- test('renders without crashing', async () => {
- const props = createSectionProps();
- renderWithProviders( );
- expect(screen.getByText(/API Keys/i)).toBeInTheDocument();
- });
-
- test('renders with ConfigurationAccordion wrapper', async () => {
- const props = createSectionProps();
- renderWithProviders( );
- expect(screen.getByText(/API Keys & Bookmarklet/i)).toBeInTheDocument();
- });
-
- test('accordion is collapsed by default', () => {
- const props = createSectionProps();
- renderWithProviders( );
-
- expect(screen.getByRole('heading', { name: /API Keys & Bookmarklet/i })).toBeInTheDocument();
- });
-
- test('first setup step includes the Create click that opens the button window', async () => {
- renderWithProviders( );
-
- expect(await screen.findByText(/give it a name like "Laptop browser", and click/i)).toBeInTheDocument();
- });
-
- test('explains that creating a key opens the Send to Youtarr button', async () => {
- renderWithProviders( );
-
- expect(await screen.findByText(/In the window that opens, drag the/i)).toBeInTheDocument();
- });
-
- test('warns that the Send to Youtarr button is only shown once', async () => {
- renderWithProviders( );
-
- expect(await screen.findByText(/The button is only shown once/i)).toBeInTheDocument();
- });
-
- test('shows loading skeleton initially', () => {
- const props = createSectionProps();
- renderWithProviders( );
- // Skeleton should be visible while loading
- expect(screen.getByText(/API Keys/i)).toBeInTheDocument();
- });
-
- test('shows single video limitation note', async () => {
- const user = userEvent.setup();
- mockFetch.mockResolvedValue({
- ok: true,
- json: jest.fn().mockResolvedValue({ keys: [] }),
- });
-
- const props = createSectionProps();
- renderWithProviders( );
+const channelListResponse: ChannelListResponse = {
+ channels: [{
+ database_id: 12,
+ url: 'https://www.youtube.com/channel/UC1234567890123456789012',
+ channel_id: 'UC1234567890123456789012',
+ uploader: 'Safe Channel',
+ title: 'Safe Channel',
+ terminated_at: null,
+ }],
+ total: 1,
+ totalPages: 1,
+};
+const jsonResponse = (body: unknown, ok = true) => ({
+ ok,
+ json: jest.fn().mockResolvedValue(body),
+});
- await waitFor(() => {
- expect(screen.getByText(/single video downloads only/i)).toBeInTheDocument();
- });
- });
+const installDefaultFetch = (
+ keys: Array> = [externalKey, legacyKey]
+) => {
+ mockFetch.mockImplementation(async (input: RequestInfo | URL, init?: RequestInit) => {
+ const url = String(input);
+ if (url === '/api/keys' && (!init?.method || init.method === 'GET')) {
+ return jsonResponse({ keys });
+ }
+ if (url === '/getchannels?page=1&pageSize=100&sortOrder=asc') {
+ return jsonResponse(channelListResponse);
+ }
+ if (url === '/api/keys/7/channels') {
+ return jsonResponse({ keyId: 7, channelIds: [] });
+ }
+ if (url === '/api/keys/7/external-access') {
+ return jsonResponse({ success: true, key: externalKey, channelIds: [12] });
+ }
+ if (url === '/api/keys/7/regenerate' && init?.method === 'POST') {
+ return jsonResponse({
+ ...createdKey,
+ message: 'API key regenerated. Save this key - it will not be shown again!',
+ id: 7,
+ name: 'External Client',
+ });
+ }
+ if (url === '/api/keys' && init?.method === 'POST') {
+ return jsonResponse(createdKey);
+ }
+ if (url.startsWith('/api/keys/') && init?.method === 'DELETE') {
+ return jsonResponse({ success: true });
+ }
+ return jsonResponse({});
});
+};
- describe('Rate Limit Setting', () => {
- test('renders rate limit input with current value', async () => {
- const user = userEvent.setup();
- mockFetch.mockResolvedValue({
- ok: true,
- json: jest.fn().mockResolvedValue({ keys: [] }),
- });
-
- const props = createSectionProps({ apiKeyRateLimit: 15 });
- renderWithProviders( );
-
-
- await waitFor(() => {
- const input = screen.getByLabelText(/Rate Limit/i);
- expect(input).toHaveValue(15);
- });
- });
-
- test('calls onRateLimitChange when value changes', async () => {
- const user = userEvent.setup();
- const onRateLimitChange = jest.fn();
- mockFetch.mockResolvedValue({
- ok: true,
- json: jest.fn().mockResolvedValue({ keys: [] }),
- });
-
- const props = createSectionProps({ apiKeyRateLimit: 10, onRateLimitChange });
- renderWithProviders( );
-
-
- await waitFor(() => {
- expect(screen.getByLabelText(/Rate Limit/i)).toBeInTheDocument();
- });
-
- const input = screen.getByLabelText(/Rate Limit/i) as HTMLInputElement;
- // Triple click to select all, then type new value
- await user.tripleClick(input);
- await user.keyboard('15');
-
- // onRateLimitChange is called with valid values during typing
- expect(onRateLimitChange).toHaveBeenCalled();
- });
+const installApiKeyHook = () => {
+ const request = async (url: string, init?: RequestInit) => {
+ const response = await mockFetch(url, init);
+ return response.json();
+ };
+ mockedUseApiKeys.mockReturnValue({
+ fetchApiKeys: async () => (await request('/api/keys')).keys || [],
+ fetchAvailableChannels: async () => (await request('/getchannels?page=1&pageSize=100&sortOrder=asc')).channels || [],
+ fetchChannelGrants: async (keyId) => (await request(`/api/keys/${keyId}/channels`)).channelIds || [],
+ createApiKey: async (name, policy, channelIds, role) => request('/api/keys', {
+ method: 'POST',
+ body: JSON.stringify({
+ name,
+ ...(role ? { role } : {}),
+ ...(policy ? { policy, channelIds: channelIds || [] } : {}),
+ }),
+ }),
+ updateExternalAccess: async (keyId, body) => request(`/api/keys/${keyId}/external-access`, {
+ method: 'PUT',
+ body: JSON.stringify(body),
+ }),
+ revokeApiKey: async (keyId) => request(`/api/keys/${keyId}`, { method: 'DELETE' }),
+ regenerateApiKey: async (keyId) => request(`/api/keys/${keyId}/regenerate`, { method: 'POST' }),
});
+};
- describe('Empty State', () => {
- test('shows empty state message when no keys exist', async () => {
- const user = userEvent.setup();
- mockFetch.mockResolvedValue({
- ok: true,
- json: jest.fn().mockResolvedValue({ keys: [] }),
- });
-
- const props = createSectionProps();
- renderWithProviders( );
-
-
- await waitFor(() => {
- expect(screen.getByText(/No API keys yet. Create one to get your Send to Youtarr button/i)).toBeInTheDocument();
- });
- });
-
- test('shows Create Key button in empty state', async () => {
- const user = userEvent.setup();
- mockFetch.mockResolvedValue({
- ok: true,
- json: jest.fn().mockResolvedValue({ keys: [] }),
- });
-
- const props = createSectionProps();
- renderWithProviders( );
-
-
- await waitFor(() => {
- expect(screen.getByRole('button', { name: /Create Key/i })).toBeInTheDocument();
- });
- });
+describe('ApiKeysSection', () => {
+ beforeEach(() => {
+ jest.clearAllMocks();
+ installDefaultFetch();
+ installApiKeyHook();
});
- describe('API Keys List', () => {
- test('displays list of API keys', async () => {
- const user = userEvent.setup();
- mockFetch.mockResolvedValue({
- ok: true,
- json: jest.fn().mockResolvedValue({ keys: mockApiKeys }),
- });
-
- const props = createSectionProps();
- renderWithProviders( );
-
-
- expect(await screen.findByText('My Bookmarklet')).toBeInTheDocument();
- expect(screen.getByText('iPhone Shortcut')).toBeInTheDocument();
- });
-
- test('displays key prefix with ellipsis', async () => {
- const user = userEvent.setup();
- mockFetch.mockResolvedValue({
- ok: true,
- json: jest.fn().mockResolvedValue({ keys: mockApiKeys }),
- });
-
- const props = createSectionProps();
- renderWithProviders( );
-
-
- expect(await screen.findByText('abc12345...')).toBeInTheDocument();
- expect(screen.getByText('xyz98765...')).toBeInTheDocument();
- });
+ test('toggles the Requests navigation link setting', async () => {
+ const user = userEvent.setup();
+ const onShowRequestsNavLinkChange = jest.fn();
+ renderWithProviders(
+
+ );
- test('displays "Never" for keys that have not been used', async () => {
- const user = userEvent.setup();
- mockFetch.mockResolvedValue({
- ok: true,
- json: jest.fn().mockResolvedValue({ keys: mockApiKeys }),
- });
-
- const props = createSectionProps();
- renderWithProviders( );
+ const toggle = await screen.findByTestId('requests-nav-link-switch');
+ expect(toggle).toBeChecked();
+ await user.click(toggle);
- await waitFor(() => {
- expect(screen.getByText('Never')).toBeInTheDocument();
- });
- });
-
- test('shows delete button for each key', async () => {
- const user = userEvent.setup();
- mockFetch.mockResolvedValue({
- ok: true,
- json: jest.fn().mockResolvedValue({ keys: mockApiKeys }),
- });
-
- const props = createSectionProps();
- renderWithProviders( );
-
-
- await waitFor(() => {
- const deleteButtons = screen.getAllByRole('button', { name: /Delete/i });
- expect(deleteButtons).toHaveLength(2);
- });
- });
-
- test('displays usage count for each key', async () => {
- const user = userEvent.setup();
- mockFetch.mockResolvedValue({
- ok: true,
- json: jest.fn().mockResolvedValue({ keys: mockApiKeys }),
- });
-
- const props = createSectionProps();
- renderWithProviders( );
-
-
- // Check that usage counts are displayed
- expect(await screen.findByText('42')).toBeInTheDocument();
- expect(screen.getByText('0')).toBeInTheDocument();
- });
+ expect(onShowRequestsNavLinkChange).toHaveBeenCalledWith(false);
});
- describe('Create API Key', () => {
- test('opens create dialog when Create Key button is clicked', async () => {
- const user = userEvent.setup();
- mockFetch.mockResolvedValue({
- ok: true,
- json: jest.fn().mockResolvedValue({ keys: [] }),
- });
-
- const props = createSectionProps();
- renderWithProviders( );
-
-
- await waitFor(() => {
- expect(screen.getByRole('button', { name: /Create Key/i })).toBeInTheDocument();
- });
-
- await user.click(screen.getByRole('button', { name: /Create Key/i }));
-
- expect(screen.getByText('Create API Key')).toBeInTheDocument();
- expect(screen.getByLabelText(/Key Name/i)).toBeInTheDocument();
- });
-
- test('create dialog says the Send to Youtarr button comes next', async () => {
- const user = userEvent.setup();
- renderWithProviders( );
+ test('puts the bookmarklet steps before the external access section', async () => {
+ renderWithProviders( );
- await user.click(await screen.findByRole('button', { name: /Create Key/i }));
+ const externalHeading = await screen.findByText('External access keys');
+ const bookmarkletHeading = screen.getByText('Get the "Send to Youtarr" button');
+ expect(bookmarkletHeading.compareDocumentPosition(externalHeading) &
+ Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy();
+ });
- expect(screen.getByText(/Next you'll get your key, the Send to Youtarr button/i)).toBeInTheDocument();
- });
+ test('names the section after the bookmarklet', async () => {
+ renderWithProviders( );
- test('Create button is disabled when name is empty', async () => {
- const user = userEvent.setup();
- mockFetch.mockResolvedValue({
- ok: true,
- json: jest.fn().mockResolvedValue({ keys: [] }),
- });
-
- const props = createSectionProps();
- renderWithProviders( );
+ expect(await screen.findByRole('heading', { name: /API Keys & Bookmarklet/i })).toBeInTheDocument();
+ });
+ test('first setup step includes the Create click that opens the button window', async () => {
+ renderWithProviders( );
- await waitFor(() => {
- expect(screen.getByRole('button', { name: /Create Key/i })).toBeInTheDocument();
- });
+ expect(await screen.findByText(/give it a name like "Laptop browser", and click/i)).toBeInTheDocument();
+ });
- await user.click(screen.getByRole('button', { name: /Create Key/i }));
+ test('warns that the Send to Youtarr button is only shown once', async () => {
+ renderWithProviders( );
- const createButton = screen.getByRole('button', { name: /^Create$/i });
- expect(createButton).toBeDisabled();
- });
+ expect(await screen.findByText(/The button is only shown once/i)).toBeInTheDocument();
+ });
- test('successfully creates API key and shows bookmarklet dialog', async () => {
- const user = userEvent.setup();
-
- // First call: fetch keys (empty)
- // Second call: create key
- // Third call: refresh keys
- mockFetch
- .mockResolvedValueOnce({
- ok: true,
- json: jest.fn().mockResolvedValue({ keys: [] }),
- })
- .mockResolvedValueOnce({
- ok: true,
- json: jest.fn().mockResolvedValue(mockCreatedKeyResponse),
- })
- .mockResolvedValueOnce({
- ok: true,
- json: jest.fn().mockResolvedValue({ keys: [{ ...mockApiKeys[0], name: 'New Key' }] }),
- });
-
- const props = createSectionProps();
- renderWithProviders( );
-
-
- await waitFor(() => {
- expect(screen.getByRole('button', { name: /Create Key/i })).toBeInTheDocument();
- });
+ test('hides the external access section when the external API is disabled and no external key is active', async () => {
+ installDefaultFetch([legacyKey, { ...externalKey, is_active: false, revoked_at: '2026-07-28T12:00:00.000Z' }]);
+ installApiKeyHook();
+ renderWithProviders( );
- await user.click(screen.getByRole('button', { name: /Create Key/i }));
+ await screen.findByLabelText('Bookmarklet API key rows');
+ expect(screen.queryByText('External access keys')).not.toBeInTheDocument();
+ });
- const nameInput = screen.getByLabelText(/Key Name/i);
- await user.type(nameInput, 'New Key');
+ test('keeps active external keys revocable while the external API is disabled', async () => {
+ const user = userEvent.setup();
+ renderWithProviders( );
+
+ const cards = await screen.findByLabelText('External API key cards');
+ expect(within(cards).getByText('External Client')).toBeInTheDocument();
+ expect(screen.getByText(/External API is turned off, so these keys cannot be used/i)).toBeInTheDocument();
+ expect(screen.queryByRole('button', { name: 'Create external key' })).not.toBeInTheDocument();
+ expect(screen.queryByRole('button', { name: 'Edit External Client external access' })).not.toBeInTheDocument();
+ expect(screen.queryByRole('button', { name: 'Regenerate External Client' })).not.toBeInTheDocument();
+
+ await user.click(screen.getByRole('button', { name: 'Revoke External Client' }));
+ await user.click(screen.getByRole('button', { name: /^Revoke$/ }));
+ await waitFor(() => expect(mockFetch).toHaveBeenCalledWith(
+ '/api/keys/7',
+ expect.objectContaining({ method: 'DELETE' })
+ ));
+ });
- const createButton = screen.getByRole('button', { name: /^Create$/i });
- await user.click(createButton);
+ test('hides the Requests navigation toggle when the external API is disabled', async () => {
+ renderWithProviders( );
- await waitFor(() => {
- expect(screen.getByText(/API Key Created/i)).toBeInTheDocument();
- });
+ await screen.findByLabelText('Bookmarklet API key rows');
+ expect(screen.queryByTestId('requests-nav-link-switch')).not.toBeInTheDocument();
+ });
- // Should show the key only once warning
- expect(screen.getByText(/Save this key now/i)).toBeInTheDocument();
- });
+ test('lists bookmarklet keys even when the external API is disabled', async () => {
+ renderWithProviders( );
- test('shows bookmarklet section in created key dialog', async () => {
- const user = userEvent.setup();
-
- mockFetch
- .mockResolvedValueOnce({
- ok: true,
- json: jest.fn().mockResolvedValue({ keys: [] }),
- })
- .mockResolvedValueOnce({
- ok: true,
- json: jest.fn().mockResolvedValue(mockCreatedKeyResponse),
- })
- .mockResolvedValueOnce({
- ok: true,
- json: jest.fn().mockResolvedValue({ keys: [] }),
- });
-
- const props = createSectionProps();
- renderWithProviders( );
-
-
- await waitFor(() => {
- expect(screen.getByRole('button', { name: /Create Key/i })).toBeInTheDocument();
- });
+ const rows = await screen.findByLabelText('Bookmarklet API key rows');
+ expect(within(rows).getByText('My Bookmarklet')).toBeInTheDocument();
+ });
- await user.click(screen.getByRole('button', { name: /Create Key/i }));
- await user.type(screen.getByLabelText(/Key Name/i), 'Test Key');
- await user.click(screen.getByRole('button', { name: /^Create$/i }));
+ test('uses compact cards with rating and permission chips but no key prefix', async () => {
+ renderWithProviders( );
+
+ const cards = await screen.findByLabelText('External API key cards');
+ expect(within(cards).getByText('External Client')).toBeInTheDocument();
+ expect(within(cards).getByLabelText('Movie rating ceiling PG-13')).toBeInTheDocument();
+ expect(within(cards).getByLabelText('TV rating ceiling TV-14')).toBeInTheDocument();
+ expect(within(cards).getByText('Videos')).toBeInTheDocument();
+ expect(within(cards).getByText('Channels · Auto')).toBeInTheDocument();
+ expect(within(cards).getByText('Delete video')).toBeInTheDocument();
+ expect(within(cards).getByText('1 approved channel')).toBeInTheDocument();
+ expect(within(cards).getByText(/Last used/i)).toBeInTheDocument();
+ expect(within(cards).queryByText('12 uses')).not.toBeInTheDocument();
+ expect(screen.queryByText('client1234...')).not.toBeInTheDocument();
+ });
- expect(await screen.findByText(/Add to Bookmarks/i)).toBeInTheDocument();
- const createdDialog = screen.getByRole('dialog', { name: /API Key Created/i });
- expect(within(createdDialog).getByText(/Send to Youtarr/i)).toBeInTheDocument();
- expect(screen.getByText(/Mobile \/ Shortcuts/i)).toBeInTheDocument();
- });
+ test('warns prominently when an external key has no effective channel grants', async () => {
+ installDefaultFetch([{ ...externalKey, channel_grant_count: 0 }]);
+ installApiKeyHook();
+ renderWithProviders( );
- test('shows error when API key creation fails', async () => {
- const user = userEvent.setup();
-
- mockFetch
- .mockResolvedValueOnce({
- ok: true,
- json: jest.fn().mockResolvedValue({ keys: [] }),
- })
- .mockResolvedValueOnce({
- ok: false,
- json: jest.fn().mockResolvedValue({ error: 'Maximum number of API keys reached' }),
- });
-
- const props = createSectionProps();
- renderWithProviders( );
-
-
- await waitFor(() => {
- expect(screen.getByRole('button', { name: /Create Key/i })).toBeInTheDocument();
- });
+ const cards = await screen.findByLabelText('External API key cards');
+ expect(within(cards).getByText('0 approved channels')).toBeInTheDocument();
+ expect(within(cards).getByText(/No approved channels\. This key cannot view or request catalog content/i))
+ .toBeInTheDocument();
+ });
- await user.click(screen.getByRole('button', { name: /Create Key/i }));
- await user.type(screen.getByLabelText(/Key Name/i), 'Test Key');
- await user.click(screen.getByRole('button', { name: /^Create$/i }));
+ test('uses a neutral state when an older management response omits the grant count', async () => {
+ const { channel_grant_count: _omitted, ...olderExternalKey } = externalKey;
+ installDefaultFetch([olderExternalKey]);
+ installApiKeyHook();
+ renderWithProviders( );
- await waitFor(() => {
- expect(screen.getByText(/Maximum number of API keys reached/i)).toBeInTheDocument();
- });
- });
+ const cards = await screen.findByLabelText('External API key cards');
+ expect(within(cards).getByText('Approved channel count unavailable')).toBeInTheDocument();
+ expect(within(cards).queryByText(/No approved channels\./i)).not.toBeInTheDocument();
});
- describe('Read-only status keys', () => {
- const mockKeyCreation = () => {
- mockFetch
- .mockResolvedValueOnce({
- ok: true,
- json: jest.fn().mockResolvedValue({ keys: [] }),
- })
- .mockResolvedValueOnce({
- ok: true,
- json: jest.fn().mockResolvedValue(mockCreatedKeyResponse),
- })
- .mockResolvedValueOnce({
- ok: true,
- json: jest.fn().mockResolvedValue({ keys: [] }),
- });
+ test('filters active external keys by default, sorts them alphabetically, and supports search and all-keys mode', async () => {
+ const alphaKey = {
+ ...externalKey,
+ id: 9,
+ name: 'Alpha Client',
};
-
- const createRequestBody = () => {
- const createCall = mockFetch.mock.calls.find(([, options]) => options?.method === 'POST');
- return JSON.parse(createCall[1].body);
+ const revokedKey = {
+ ...externalKey,
+ id: 10,
+ name: 'Revoked Client',
+ is_active: false,
+ revoked_at: '2026-07-28T12:00:00.000Z',
};
+ const inactiveKey = {
+ ...externalKey,
+ id: 11,
+ name: 'Inactive Client',
+ is_active: false,
+ };
+ installDefaultFetch([externalKey, alphaKey, revokedKey, inactiveKey]);
+ installApiKeyHook();
+ const user = userEvent.setup();
+ renderWithProviders( );
+
+ const cards = await screen.findByLabelText('External API key cards');
+ expect(within(cards).getByText('Alpha Client')).toBeInTheDocument();
+ expect(within(cards).getByText('External Client')).toBeInTheDocument();
+ expect(within(cards).queryByText('Revoked Client')).not.toBeInTheDocument();
+ expect(within(cards).queryByText('Inactive Client')).not.toBeInTheDocument();
+ const alphaName = within(cards).getByText('Alpha Client');
+ const externalName = within(cards).getByText('External Client');
+ expect(alphaName.compareDocumentPosition(externalName) & Node.DOCUMENT_POSITION_FOLLOWING)
+ .toBeTruthy();
+
+ await user.click(screen.getByRole('button', { name: 'Active only' }));
+ expect(within(cards).getByText('Revoked Client')).toBeInTheDocument();
+ expect(within(cards).getByText('Inactive Client')).toBeInTheDocument();
+
+ await user.type(screen.getByLabelText('Search external access keys'), 'revoked');
+ expect(within(cards).getByText('Revoked Client')).toBeInTheDocument();
+ expect(within(cards).queryByText('Alpha Client')).not.toBeInTheDocument();
+ });
- test('creates a status key when the read-only option is checked', async () => {
- const user = userEvent.setup();
- mockKeyCreation();
- renderWithProviders( );
-
- await user.click(await screen.findByRole('button', { name: /Create Key/i }));
- await user.type(screen.getByLabelText(/Key Name/i), 'Dashboard');
- await user.click(screen.getByRole('checkbox', { name: /Read-only status key/i }));
- await user.click(screen.getByRole('button', { name: /^Create$/i }));
-
- await screen.findByRole('dialog', { name: /API Key Created/i });
- expect(createRequestBody()).toEqual({ name: 'Dashboard', role: 'status_read' });
- });
-
- test('creates a download key when the read-only option is left unchecked', async () => {
- const user = userEvent.setup();
- mockKeyCreation();
- renderWithProviders( );
-
- await user.click(await screen.findByRole('button', { name: /Create Key/i }));
- await user.type(screen.getByLabelText(/Key Name/i), 'Bookmarklet');
- await user.click(screen.getByRole('button', { name: /^Create$/i }));
-
- await screen.findByRole('dialog', { name: /API Key Created/i });
- expect(createRequestBody()).toEqual({ name: 'Bookmarklet' });
- });
-
- test('shows the status summary address instead of the bookmarklet for a status key', async () => {
- const user = userEvent.setup();
- mockKeyCreation();
- renderWithProviders( );
-
- await user.click(await screen.findByRole('button', { name: /Create Key/i }));
- await user.type(screen.getByLabelText(/Key Name/i), 'Dashboard');
- await user.click(screen.getByRole('checkbox', { name: /Read-only status key/i }));
- await user.click(screen.getByRole('button', { name: /^Create$/i }));
-
- const createdDialog = await screen.findByRole('dialog', { name: /API Key Created/i });
- expect(within(createdDialog).getByText(/\/api\/status\/summary/)).toBeInTheDocument();
- expect(within(createdDialog).queryByText(/Add to Bookmarks/i)).not.toBeInTheDocument();
- expect(within(createdDialog).queryByText(/Send to Youtarr/i)).not.toBeInTheDocument();
- });
-
- test('explains what a status key can do before it is created', async () => {
- const user = userEvent.setup();
- renderWithProviders( );
-
- await user.click(await screen.findByRole('button', { name: /Create Key/i }));
- await user.click(screen.getByRole('checkbox', { name: /Read-only status key/i }));
-
- expect(screen.getByText(/cannot start downloads\. Next you'll get your key/i)).toBeInTheDocument();
- });
+ test('lists bookmarklet keys with their key prefix', async () => {
+ renderWithProviders( );
- test('goes back to a download key when the create dialog is cancelled', async () => {
- const user = userEvent.setup();
- renderWithProviders( );
+ const rows = await screen.findByLabelText('Bookmarklet API key rows');
+ expect(within(rows).getByText('abc12345...')).toBeInTheDocument();
+ });
- await user.click(await screen.findByRole('button', { name: /Create Key/i }));
- await user.click(screen.getByRole('checkbox', { name: /Read-only status key/i }));
- await user.click(screen.getByRole('button', { name: /Cancel/i }));
- await user.click(screen.getByRole('button', { name: /Create Key/i }));
+ test('hides revoked keys from the bookmarklet list', async () => {
+ installDefaultFetch([
+ legacyKey,
+ { ...legacyKey, id: 3, name: 'Old Bookmarklet', is_active: false, revoked_at: '2026-07-28T12:00:00.000Z' },
+ ]);
+ installApiKeyHook();
+ renderWithProviders( );
+
+ const rows = await screen.findByLabelText('Bookmarklet API key rows');
+ expect(within(rows).getByText('My Bookmarklet')).toBeInTheDocument();
+ expect(within(rows).queryByText('Old Bookmarklet')).not.toBeInTheDocument();
+ });
- expect(await screen.findByRole('checkbox', { name: /Read-only status key/i })).not.toBeChecked();
- });
+ test('lists read-only status keys with download keys and labels each type', async () => {
+ installDefaultFetch([
+ legacyKey,
+ { ...legacyKey, id: 4, name: 'Dashboard key', key_prefix: 'stat1234', role: 'status_read' },
+ ]);
+ installApiKeyHook();
+ renderWithProviders( );
+
+ const rows = await screen.findByLabelText('Bookmarklet API key rows');
+ expect(within(rows).getByText('Dashboard key')).toBeInTheDocument();
+ expect(within(rows).getByText('Read-only status')).toBeInTheDocument();
+ expect(within(rows).getByText('Download')).toBeInTheDocument();
+ expect(screen.queryByLabelText('External API key cards')).not.toBeInTheDocument();
+ });
- test('lists the type of each key', async () => {
- mockFetch.mockResolvedValue({
- ok: true,
- json: jest.fn().mockResolvedValue({
- keys: [
- { ...mockApiKeys[0], name: 'Bookmarklet key', role: 'legacy_download' },
- { ...mockApiKeys[1], name: 'Dashboard key', role: 'status_read' },
- ],
- }),
- });
- renderWithProviders( );
+ test('keeps external keys out of the bookmarklet list', async () => {
+ renderWithProviders( );
- const downloadRow = await screen.findByRole('row', { name: /Bookmarklet key/i });
- const statusRow = screen.getByRole('row', { name: /Dashboard key/i });
- expect(within(downloadRow).getByText('Download')).toBeInTheDocument();
- expect(within(statusRow).getByText('Read-only status')).toBeInTheDocument();
- });
+ const rows = await screen.findByLabelText('Bookmarklet API key rows');
+ expect(within(rows).queryByText('External Client')).not.toBeInTheDocument();
});
- describe('Delete API Key', () => {
- test('opens confirmation dialog when delete button is clicked', async () => {
- const user = userEvent.setup();
- mockFetch.mockResolvedValue({
- ok: true,
- json: jest.fn().mockResolvedValue({ keys: mockApiKeys }),
- });
-
- const props = createSectionProps();
- renderWithProviders( );
+ test('shows the rate limit below the bookmarklet keys', async () => {
+ renderWithProviders( );
+ expect(await screen.findByLabelText('Rate Limit (requests/min)')).toHaveValue(10);
+ });
- await waitFor(() => {
- expect(screen.getByText('My Bookmarklet')).toBeInTheDocument();
- });
+ test('shows separate empty states for external and bookmarklet keys', async () => {
+ installDefaultFetch([]);
+ installApiKeyHook();
+ renderWithProviders( );
- const deleteButtons = screen.getAllByRole('button', { name: /Delete/i });
- await user.click(deleteButtons[0]);
+ expect(await screen.findByText('No external access keys yet.')).toBeInTheDocument();
+ expect(screen.getByText('No API keys yet. Create one to get your Send to Youtarr button.')).toBeInTheDocument();
+ });
- expect(screen.getByText(/Delete API Key\?/i)).toBeInTheDocument();
- // The key name appears in both the table and dialog, so check for all instances
- expect(screen.getAllByText(/My Bookmarklet/i).length).toBeGreaterThanOrEqual(1);
- expect(screen.getByText(/cannot be undone/i)).toBeInTheDocument();
- });
+ test('shows auto-approve only after its permission is enabled', async () => {
+ const viewOnly = {
+ ...externalKey,
+ role: 'view',
+ allow_video_requests: false,
+ allow_channel_requests: false,
+ allow_delete_video_requests: false,
+ auto_approve_video_requests: false,
+ auto_approve_channel_requests: false,
+ auto_approve_delete_requests: false,
+ };
+ installDefaultFetch([viewOnly]);
+ installApiKeyHook();
+ const user = userEvent.setup();
+ renderWithProviders( );
+
+ await user.click(await screen.findByRole('button', {
+ name: 'Edit External Client external access',
+ }));
+ expect(screen.queryByLabelText('Auto-approve request videos')).not.toBeInTheDocument();
+
+ await user.click(screen.getByLabelText('Request videos'));
+ expect(screen.getByLabelText('Auto-approve request videos')).toBeInTheDocument();
+ expect(screen.getByLabelText('Request videos')).toHaveAttribute('data-state', 'checked');
+ });
- test('closes confirmation dialog when Cancel is clicked', async () => {
- const user = userEvent.setup();
- mockFetch.mockResolvedValue({
- ok: true,
- json: jest.fn().mockResolvedValue({ keys: mockApiKeys }),
- });
-
- const props = createSectionProps();
- renderWithProviders( );
+ test('saves independent permissions and channel grants atomically', async () => {
+ const viewOnly = {
+ ...externalKey,
+ role: 'view',
+ allow_video_requests: false,
+ allow_channel_requests: false,
+ allow_delete_video_requests: false,
+ auto_approve_video_requests: false,
+ auto_approve_channel_requests: false,
+ auto_approve_delete_requests: false,
+ };
+ installDefaultFetch([viewOnly]);
+ installApiKeyHook();
+ const confirm = jest.spyOn(window, 'confirm');
+ const user = userEvent.setup();
+ renderWithProviders( );
+
+ await user.click(await screen.findByRole('button', {
+ name: 'Edit External Client external access',
+ }));
+ await user.click(screen.getByLabelText('Request videos'));
+ await user.click(screen.getByLabelText('Safe Channel'));
+ await user.click(screen.getByRole('button', { name: 'Save External Access' }));
+ await user.click(screen.getByRole('button', { name: 'Continue' }));
+
+ await waitFor(() => expect(mockFetch.mock.calls.some(([url, init]) =>
+ url === '/api/keys/7/external-access' && init?.method === 'PUT'
+ )).toBe(true));
+ const call = mockFetch.mock.calls.find(([url, init]) =>
+ url === '/api/keys/7/external-access' && init?.method === 'PUT'
+ );
+ const requestBody = JSON.parse(call?.[1]?.body as string);
+ expect(requestBody).toEqual({
+ policy: expect.objectContaining({
+ role: 'request',
+ allowVideoRequests: true,
+ allowChannelRequests: false,
+ allowDeleteVideoRequests: false,
+ autoApproveVideoRequests: false,
+ }),
+ channelIds: [12],
+ });
+ expect(confirm).not.toHaveBeenCalled();
+ confirm.mockRestore();
+ });
+ test('selects and clears all approved channels when creating a key', async () => {
+ installDefaultFetch([]);
+ installApiKeyHook();
+ const user = userEvent.setup();
+ renderWithProviders( );
+
+ await user.click(await screen.findByRole('button', { name: 'Create external key' }));
+ expect(screen.getByText(/Saving with zero approved channels is allowed, but the key will fail closed/i))
+ .toBeInTheDocument();
+ const selectAll = await screen.findByLabelText('Select all channels');
+ await user.click(selectAll);
+ expect(screen.getByLabelText('Safe Channel')).toBeChecked();
+ expect(screen.getByText('Approved channels (1)')).toBeInTheDocument();
+ await user.click(selectAll);
+ expect(screen.getByLabelText('Safe Channel')).not.toBeChecked();
+ });
- await waitFor(() => {
- expect(screen.getByText('My Bookmarklet')).toBeInTheDocument();
- });
+ test('selects all approved channels when editing a key', async () => {
+ const user = userEvent.setup();
+ renderWithProviders( );
+
+ await user.click(await screen.findByRole('button', {
+ name: 'Edit External Client external access',
+ }));
+ expect(await screen.findByText(/Saving with zero approved channels is allowed, but this key will fail closed/i))
+ .toBeInTheDocument();
+ await user.click(await screen.findByLabelText('Select all channels'));
+ expect(screen.getByLabelText('Safe Channel')).toBeChecked();
+ });
- const deleteButtons = screen.getAllByRole('button', { name: /Delete/i });
- await user.click(deleteButtons[0]);
+ test('turning off a permission also turns off its auto-approval', async () => {
+ const user = userEvent.setup();
+ renderWithProviders( );
+
+ await user.click(await screen.findByRole('button', {
+ name: 'Edit External Client external access',
+ }));
+ expect(screen.getByLabelText('Auto-approve request channels'))
+ .toHaveAttribute('data-state', 'checked');
+ await user.click(screen.getByLabelText('Request channels'));
+ expect(screen.queryByLabelText('Auto-approve request channels')).not.toBeInTheDocument();
+ });
- await user.click(screen.getByRole('button', { name: /Cancel/i }));
+ test('creates an external key as view-only by default', async () => {
+ installDefaultFetch([]);
+ installApiKeyHook();
+ const user = userEvent.setup();
+ renderWithProviders( );
+
+ await user.click(await screen.findByRole('button', { name: 'Create external key' }));
+ expect(screen.getByText('Create External Access Key')).toBeInTheDocument();
+ expect(screen.getByText('View included')).toBeInTheDocument();
+ expect(screen.getByLabelText('Request videos')).toHaveAttribute('data-state', 'unchecked');
+
+ await user.type(screen.getByLabelText('Key Name'), 'New Key');
+ await user.click(screen.getByRole('button', { name: /^Create$/ }));
+
+ await waitFor(() => {
+ const call = mockFetch.mock.calls.find(([url, init]) =>
+ url === '/api/keys' && init?.method === 'POST'
+ );
+ const requestBody = JSON.parse(call?.[1]?.body as string);
+ expect(requestBody.policy).toEqual(expect.objectContaining({
+ role: 'view',
+ allowVideoRequests: false,
+ allowChannelRequests: false,
+ allowDeleteVideoRequests: false,
+ }));
+ });
+ expect(await screen.findByText(/API Key Created/)).toBeInTheDocument();
+ });
- await waitFor(() => {
- expect(screen.queryByText(/Delete API Key\?/i)).not.toBeInTheDocument();
- });
- });
+ const createBookmarkletKey = async () => {
+ installDefaultFetch([]);
+ installApiKeyHook();
+ const user = userEvent.setup();
+ renderWithProviders( );
- test('deletes key when confirmed', async () => {
- const user = userEvent.setup();
-
- mockFetch
- .mockResolvedValueOnce({
- ok: true,
- json: jest.fn().mockResolvedValue({ keys: mockApiKeys }),
- })
- .mockResolvedValueOnce({
- ok: true,
- json: jest.fn().mockResolvedValue({ success: true }),
- })
- .mockResolvedValueOnce({
- ok: true,
- json: jest.fn().mockResolvedValue({ keys: [{ ...mockApiKeys[0], is_active: false, revoked_at: '2026-10-29T12:00:00Z' }, mockApiKeys[1]] }),
- });
-
- const props = createSectionProps();
- renderWithProviders( );
-
-
- await waitFor(() => {
- expect(screen.getByText('My Bookmarklet')).toBeInTheDocument();
- });
+ await user.click(await screen.findByRole('button', { name: 'Create Key' }));
+ await user.type(screen.getByLabelText('Key Name'), 'Bookmarklet');
+ await user.click(screen.getByRole('button', { name: /^Create$/ }));
+ return screen.findByRole('dialog', { name: /API Key Created/i });
+ };
- const deleteButtons = screen.getAllByRole('button', { name: /Delete/i });
- await user.click(deleteButtons[0]);
+ test('create dialog says the Send to Youtarr button comes next', async () => {
+ const user = userEvent.setup();
+ renderWithProviders( );
- // Click the Delete button in the confirmation dialog
- const confirmDeleteButton = screen.getByRole('button', { name: /^Delete$/i });
- await user.click(confirmDeleteButton);
+ await user.click(await screen.findByRole('button', { name: 'Create Key' }));
- await waitFor(() => {
- expect(mockFetch).toHaveBeenCalledWith('/api/keys/1', expect.objectContaining({
- method: 'DELETE',
- }));
- });
- await waitFor(() => expect(screen.queryByText('My Bookmarklet')).not.toBeInTheDocument());
- expect(screen.getByText('iPhone Shortcut')).toBeInTheDocument();
- expect(screen.getAllByRole('button', { name: /Delete/i })).toHaveLength(1);
- });
+ expect(screen.getByText(/Next you'll get your key, the Send to Youtarr button/i)).toBeInTheDocument();
});
- describe('Copy to Clipboard', () => {
- test('copies API key to clipboard when copy button is clicked', async () => {
- const user = userEvent.setup();
-
- mockFetch
- .mockResolvedValueOnce({
- ok: true,
- json: jest.fn().mockResolvedValue({ keys: [] }),
- })
- .mockResolvedValueOnce({
- ok: true,
- json: jest.fn().mockResolvedValue(mockCreatedKeyResponse),
- })
- .mockResolvedValueOnce({
- ok: true,
- json: jest.fn().mockResolvedValue({ keys: [] }),
- });
-
- const props = createSectionProps();
- renderWithProviders( );
-
-
- await waitFor(() => {
- expect(screen.getByRole('button', { name: /Create Key/i })).toBeInTheDocument();
- });
-
- await user.click(screen.getByRole('button', { name: /Create Key/i }));
- await user.type(screen.getByLabelText(/Key Name/i), 'Test Key');
- await user.click(screen.getByRole('button', { name: /^Create$/i }));
+ test('create dialog for a bookmarklet key has no external policy', async () => {
+ const user = userEvent.setup();
+ renderWithProviders( );
- await waitFor(() => {
- expect(screen.getByText(/API Key Created/i)).toBeInTheDocument();
- });
+ await user.click(await screen.findByRole('button', { name: 'Create Key' }));
- // The API key should be displayed in the dialog
- expect(screen.getByText(mockCreatedKeyResponse.key)).toBeInTheDocument();
- });
+ expect(screen.queryByText('Request permissions')).not.toBeInTheDocument();
});
- describe('HTTP Warning', () => {
- // Note: HTTP warning tests are difficult to mock reliably due to window.location
- // The component correctly shows warnings when protocol is http and hostname is not localhost
- // These tests verify the default behavior (no warning on localhost)
-
- test('does not show warning on localhost (default test environment)', async () => {
- const user = userEvent.setup();
- mockFetch.mockResolvedValue({
- ok: true,
- json: jest.fn().mockResolvedValue({ keys: [] }),
- });
-
- const props = createSectionProps();
- renderWithProviders( );
-
+ test('creates bookmarklet keys without an external policy', async () => {
+ await createBookmarkletKey();
- await waitFor(() => {
- expect(screen.getByText(/No API keys yet. Create one to get your Send to Youtarr button/i)).toBeInTheDocument();
- });
+ const call = mockFetch.mock.calls.find(([url, init]) => url === '/api/keys' && init?.method === 'POST');
+ expect(JSON.parse(call?.[1]?.body as string)).toEqual({ name: 'Bookmarklet' });
+ });
- // Should not show HTTP warning on localhost (default in jsdom)
- expect(screen.queryByText(/insecure/i)).not.toBeInTheDocument();
- });
+ test('creates a read-only status key when its option is checked', async () => {
+ const user = userEvent.setup();
+ renderWithProviders( );
+
+ await user.click(await screen.findByRole('button', { name: 'Create Key' }));
+ await user.type(screen.getByLabelText('Key Name'), 'Dashboard');
+ await user.click(screen.getByRole('checkbox', { name: /Read-only status key/i }));
+ expect(screen.getByText(/cannot start downloads\. Next you'll get your key/i)).toBeInTheDocument();
+ await user.click(screen.getByRole('button', { name: /^Create$/ }));
+
+ const dialog = await screen.findByRole('dialog', { name: /API Key Created/i });
+ const call = mockFetch.mock.calls.find(([url, init]) => url === '/api/keys' && init?.method === 'POST');
+ expect(JSON.parse(call?.[1]?.body as string)).toEqual({ name: 'Dashboard', role: 'status_read' });
+ expect(within(dialog).getByText(/\/api\/status\/summary/)).toBeInTheDocument();
+ expect(within(dialog).queryByText(/Send to Youtarr/i)).not.toBeInTheDocument();
+ });
- test('shows warning on insecure external network', async () => {
- setMockLocation('http://192.168.1.10:3000/');
- const user = userEvent.setup();
- mockFetch.mockResolvedValue({
- ok: true,
- json: jest.fn().mockResolvedValue({ keys: [] }),
- });
-
- const props = createSectionProps();
- renderWithProviders( );
+ test('goes back to a download key when the create dialog is cancelled', async () => {
+ const user = userEvent.setup();
+ renderWithProviders( );
+ await user.click(await screen.findByRole('button', { name: 'Create Key' }));
+ await user.click(screen.getByRole('checkbox', { name: /Read-only status key/i }));
+ await user.click(screen.getByRole('button', { name: 'Cancel' }));
+ await user.click(screen.getByRole('button', { name: 'Create Key' }));
- await waitFor(() => {
- expect(screen.getByText(/insecure/i)).toBeInTheDocument();
- });
- });
+ expect(await screen.findByRole('checkbox', { name: /Read-only status key/i })).not.toBeChecked();
});
- describe('Error Handling', () => {
- test('shows error when fetching keys fails', async () => {
- const user = userEvent.setup();
- mockFetch.mockResolvedValue({
- ok: false,
- json: jest.fn().mockResolvedValue({ error: 'Failed to fetch API keys' }),
- });
-
- const props = createSectionProps();
- renderWithProviders( );
-
+ test('shows the draggable Send to Youtarr button after creating a bookmarklet key', async () => {
+ const dialog = await createBookmarkletKey();
- await waitFor(() => {
- expect(screen.getByText(/Failed to fetch API keys/i)).toBeInTheDocument();
- });
- });
+ expect(within(dialog).getByText(/Send to Youtarr/i)).toHaveAttribute('href', expect.stringMatching(/^javascript:/));
+ });
- test('error alert can be dismissed', async () => {
- const user = userEvent.setup();
- mockFetch.mockResolvedValue({
- ok: false,
- json: jest.fn().mockResolvedValue({ error: 'Failed to fetch API keys' }),
- });
-
- const props = createSectionProps();
- renderWithProviders( );
+ test('shows the phone shortcut details after creating a bookmarklet key', async () => {
+ const dialog = await createBookmarkletKey();
+ expect(within(dialog).getByText(/Mobile \/ Shortcuts/)).toBeInTheDocument();
+ });
- await waitFor(() => {
- expect(screen.getByText(/Failed to fetch API keys/i)).toBeInTheDocument();
- });
+ test('changes the bookmarklet rate limit', async () => {
+ const onRateLimitChange = jest.fn();
+ const user = userEvent.setup();
+ renderWithProviders( );
- // Close the error alert
- const closeButton = screen.getByRole('button', { name: /close/i });
- await user.click(closeButton);
+ const input = await screen.findByLabelText('Rate Limit (requests/min)');
+ await user.tripleClick(input);
+ await user.keyboard('15');
+ expect(onRateLimitChange).toHaveBeenCalled();
+ });
- await waitFor(() => {
- expect(screen.queryByText(/Failed to fetch API keys/i)).not.toBeInTheDocument();
- });
- });
+ test('revokes an active key after confirmation', async () => {
+ const user = userEvent.setup();
+ renderWithProviders( );
+
+ await user.click(await screen.findByRole('button', { name: 'Revoke External Client' }));
+ expect(screen.getByText('Revoke API Key?')).toBeInTheDocument();
+ await user.click(screen.getByRole('button', { name: /^Revoke$/ }));
+ await waitFor(() => expect(mockFetch).toHaveBeenCalledWith(
+ '/api/keys/7',
+ expect.objectContaining({ method: 'DELETE' })
+ ));
});
- describe('Accessibility', () => {
- test('accordion has proper aria attributes', () => {
- const props = createSectionProps();
- renderWithProviders( );
+ test('regenerates a key only after the safeguard dialog and shows it once', async () => {
+ const user = userEvent.setup();
+ renderWithProviders( );
+
+ await user.click(await screen.findByRole('button', { name: 'Regenerate External Client' }));
+ expect(screen.getByText('Regenerate API Key?')).toBeInTheDocument();
+ expect(screen.getByText(/current key will stop working immediately/i)).toBeInTheDocument();
+ await user.click(screen.getByRole('button', { name: 'Regenerate Key' }));
+
+ await waitFor(() => expect(mockFetch).toHaveBeenCalledWith(
+ '/api/keys/7/regenerate',
+ expect.objectContaining({ method: 'POST' })
+ ));
+ expect(await screen.findByText(/API Key Regenerated/)).toBeInTheDocument();
+ expect(screen.getByText(createdKey.key)).toBeInTheDocument();
+ });
- expect(screen.getByRole('heading', { name: /API Keys & Bookmarklet/i })).toBeInTheDocument();
+ test('closes the regenerate confirmation when regenerating fails so the error is visible', async () => {
+ const user = userEvent.setup();
+ const fetchDefault = mockFetch.getMockImplementation();
+ mockFetch.mockImplementation(async (input: RequestInfo | URL, init?: RequestInit) => {
+ if (String(input) === '/api/keys/7/regenerate') throw new Error('Failed to regenerate API key');
+ return fetchDefault?.(input, init);
});
+ renderWithProviders( );
- test('Create Key button is accessible', async () => {
- const user = userEvent.setup();
- mockFetch.mockResolvedValue({
- ok: true,
- json: jest.fn().mockResolvedValue({ keys: [] }),
- });
-
- const props = createSectionProps();
- renderWithProviders( );
-
+ await user.click(await screen.findByRole('button', { name: 'Regenerate External Client' }));
+ await user.click(screen.getByRole('button', { name: 'Regenerate Key' }));
- await waitFor(() => {
- expect(screen.getByRole('button', { name: /Create Key/i })).toBeInTheDocument();
- });
- });
+ expect(await screen.findByText('Failed to regenerate API key')).toBeInTheDocument();
+ await waitFor(() => expect(screen.queryByText('Regenerate API Key?')).not.toBeInTheDocument());
+ });
- test('delete buttons have accessible tooltips', async () => {
- const user = userEvent.setup();
- mockFetch.mockResolvedValue({
- ok: true,
- json: jest.fn().mockResolvedValue({ keys: mockApiKeys }),
- });
-
- const props = createSectionProps();
- renderWithProviders( );
+ test('shows API loading failures and allows dismissing the alert', async () => {
+ mockFetch.mockRejectedValue(new Error('Failed to fetch API keys'));
+ const user = userEvent.setup();
+ renderWithProviders( );
+ expect(await screen.findByText('Failed to fetch API keys')).toBeInTheDocument();
+ await user.click(screen.getByRole('button', { name: 'Close' }));
+ expect(screen.queryByText('Failed to fetch API keys')).not.toBeInTheDocument();
+ });
- await waitFor(() => {
- const deleteButtons = screen.getAllByRole('button', { name: /Delete/i });
- expect(deleteButtons).toHaveLength(2);
- });
- });
+ test('does not show the insecure-network warning on localhost', async () => {
+ renderWithProviders( );
+ await screen.findByText('External access keys');
+ expect(screen.queryByText(/Creating API keys over HTTP is insecure/i)).not.toBeInTheDocument();
});
});
-
diff --git a/client/src/components/Configuration/sections/__tests__/CoreSettingsSection.story.tsx b/client/src/components/Configuration/sections/__tests__/CoreSettingsSection.story.tsx
index 8e873750b..54bc5b28d 100644
--- a/client/src/components/Configuration/sections/__tests__/CoreSettingsSection.story.tsx
+++ b/client/src/components/Configuration/sections/__tests__/CoreSettingsSection.story.tsx
@@ -41,7 +41,7 @@ const meta: Meta = {
args: {
token: 'storybook-token',
deploymentEnvironment: { platform: null, isWsl: false },
- isPlatformManaged: { plexUrl: false, authEnabled: true, useTmpForDownloads: false, ytdlpUpdates: false },
+ isPlatformManaged: { plexUrl: false, authEnabled: true, useTmpForDownloads: false, ytdlpUpdates: false, externalApiEnabled: false },
onMobileTooltipClick: fn(),
},
};
diff --git a/client/src/components/Configuration/sections/__tests__/CoreSettingsSection.test.tsx b/client/src/components/Configuration/sections/__tests__/CoreSettingsSection.test.tsx
index ae9343c27..4fca06eb3 100644
--- a/client/src/components/Configuration/sections/__tests__/CoreSettingsSection.test.tsx
+++ b/client/src/components/Configuration/sections/__tests__/CoreSettingsSection.test.tsx
@@ -26,7 +26,7 @@ function renderCore({ config = {}, onConfigChange = jest.fn(), isPlatformManaged
diff --git a/client/src/components/Configuration/sections/__tests__/PlexIntegrationSection.test.tsx b/client/src/components/Configuration/sections/__tests__/PlexIntegrationSection.test.tsx
index 440c312bf..da8f4a449 100644
--- a/client/src/components/Configuration/sections/__tests__/PlexIntegrationSection.test.tsx
+++ b/client/src/components/Configuration/sections/__tests__/PlexIntegrationSection.test.tsx
@@ -19,6 +19,7 @@ const createPlatformManagedState = (
authEnabled: false,
useTmpForDownloads: false,
ytdlpUpdates: false,
+ externalApiEnabled: false,
...overrides,
});
diff --git a/client/src/components/Configuration/sections/__tests__/SchedulingSection.story.tsx b/client/src/components/Configuration/sections/__tests__/SchedulingSection.story.tsx
index 46a8c25c4..7da51d77c 100644
--- a/client/src/components/Configuration/sections/__tests__/SchedulingSection.story.tsx
+++ b/client/src/components/Configuration/sections/__tests__/SchedulingSection.story.tsx
@@ -62,7 +62,7 @@ const meta: Meta = {
config: DEFAULT_CONFIG,
savedConfig: DEFAULT_CONFIG,
deploymentEnvironment: { timezone: 'Europe/Paris', isWsl: false },
- isPlatformManaged: { plexUrl: false, authEnabled: true, useTmpForDownloads: false, ytdlpUpdates: false },
+ isPlatformManaged: { plexUrl: false, authEnabled: true, useTmpForDownloads: false, ytdlpUpdates: false, externalApiEnabled: false },
fieldErrors: {},
token: 'story-token',
},
diff --git a/client/src/components/Configuration/sections/__tests__/SchedulingSection.test.tsx b/client/src/components/Configuration/sections/__tests__/SchedulingSection.test.tsx
index 27594580d..45ab2f7c8 100644
--- a/client/src/components/Configuration/sections/__tests__/SchedulingSection.test.tsx
+++ b/client/src/components/Configuration/sections/__tests__/SchedulingSection.test.tsx
@@ -36,7 +36,7 @@ const axios = require('axios');
const props = {
config: DEFAULT_CONFIG,
deploymentEnvironment: { timezone: 'Europe/Paris', platform: null, isWsl: false },
- isPlatformManaged: { plexUrl: false, authEnabled: true, useTmpForDownloads: false, ytdlpUpdates: false },
+ isPlatformManaged: { plexUrl: false, authEnabled: true, useTmpForDownloads: false, ytdlpUpdates: false, externalApiEnabled: false },
onConfigChange: jest.fn(),
fieldErrors: {},
token: 'tok',
diff --git a/client/src/components/Configuration/sections/__tests__/YtdlpUpdateSection.test.tsx b/client/src/components/Configuration/sections/__tests__/YtdlpUpdateSection.test.tsx
index 401a6bc44..7dc5bb4cf 100644
--- a/client/src/components/Configuration/sections/__tests__/YtdlpUpdateSection.test.tsx
+++ b/client/src/components/Configuration/sections/__tests__/YtdlpUpdateSection.test.tsx
@@ -28,6 +28,7 @@ const createPlatformManagedState = (
authEnabled: false,
useTmpForDownloads: false,
ytdlpUpdates: false,
+ externalApiEnabled: false,
...overrides,
});
diff --git a/client/src/components/Configuration/types.ts b/client/src/components/Configuration/types.ts
index b26a04276..ad7d46832 100644
--- a/client/src/components/Configuration/types.ts
+++ b/client/src/components/Configuration/types.ts
@@ -85,6 +85,7 @@ export interface PlatformManagedState {
authEnabled: boolean;
useTmpForDownloads: boolean;
ytdlpUpdates: boolean;
+ externalApiEnabled: boolean;
}
export interface DeploymentEnvironment {
diff --git a/client/src/components/ExternalRequests/RequestsPage.stories.tsx b/client/src/components/ExternalRequests/RequestsPage.stories.tsx
new file mode 100644
index 000000000..d74fdca9c
--- /dev/null
+++ b/client/src/components/ExternalRequests/RequestsPage.stories.tsx
@@ -0,0 +1,283 @@
+import type { Meta, StoryObj } from '@storybook/react';
+import { expect, userEvent, within } from 'storybook/test';
+import { fireEvent } from '@testing-library/react';
+import { http, HttpResponse } from 'msw';
+import { MemoryRouter } from 'react-router-dom';
+import RequestsPage from './RequestsPage';
+import { ExternalRequestReview } from '../../types/externalRequest';
+
+const requestId = '9b89e5bc-8c90-4e72-b245-270fed2eacc2';
+const requests: ExternalRequestReview[] = [
+ {
+ id: requestId,
+ type: 'video',
+ status: 'pending',
+ requester: {
+ id: 4,
+ name: 'External Client',
+ keyPrefix: 'client1234',
+ role: 'request',
+ isActive: true,
+ revokedAt: null,
+ },
+ target: {
+ youtubeId: 'dQw4w9WgXcQ',
+ channelId: 8,
+ youtubeChannelId: 'UCuAXFkgsw1L7xaCfnd5JJOw',
+ channelTitle: 'Rick Astley',
+ title: 'Rick Astley - Never Gonna Give You Up (Official Video)',
+ mediaType: 'video',
+ rating: 'TV-PG',
+ },
+ job: null,
+ createdAt: '2026-07-27T18:30:00.000Z',
+ updatedAt: '2026-07-27T18:30:00.000Z',
+ },
+ {
+ id: '64fd65fd-870b-43b3-818d-8f2a5344e687',
+ type: 'delete_video',
+ status: 'approved',
+ requester: {
+ id: 4,
+ name: 'External Client',
+ keyPrefix: 'client1234',
+ role: 'delete',
+ isActive: true,
+ revokedAt: null,
+ },
+ target: {
+ youtubeId: 'yPYZpwSpKmA',
+ channelId: 8,
+ youtubeChannelId: 'UCuAXFkgsw1L7xaCfnd5JJOw',
+ channelTitle: 'Rick Astley',
+ title: 'Rick Astley - Together Forever (Official Video)',
+ mediaType: 'video',
+ rating: 'TV-PG',
+ },
+ job: null,
+ createdAt: '2026-07-27T17:30:00.000Z',
+ updatedAt: '2026-07-27T17:35:00.000Z',
+ },
+ {
+ id: '9f365adb-b718-4b53-99c9-cf42485b0367',
+ type: 'channel',
+ status: 'rejected',
+ requester: {
+ id: 4,
+ name: 'External Client',
+ keyPrefix: 'client1234',
+ role: 'request',
+ isActive: true,
+ revokedAt: null,
+ },
+ target: {
+ youtubeId: null,
+ channelId: null,
+ channelUrl: 'https://www.youtube.com/@RickAstleyYT',
+ youtubeChannelId: null,
+ channelTitle: null,
+ title: null,
+ mediaType: null,
+ rating: null,
+ },
+ job: null,
+ createdAt: '2026-07-27T16:30:00.000Z',
+ updatedAt: '2026-07-27T16:45:00.000Z',
+ message: 'Channel is outside this profile.',
+ },
+];
+
+const page = {
+ data: requests,
+ pagination: { page: 1, pageSize: 25, total: requests.length, totalPages: 1 },
+ filterOptions: { requesters: [requests[0].requester] },
+};
+
+const pageFor = (data: ExternalRequestReview[]) => ({
+ data,
+ pagination: { page: 1, pageSize: 25, total: data.length, totalPages: data.length ? 1 : 0 },
+ filterOptions: { requesters: [requests[0].requester] },
+});
+
+const lifecycleStatuses: ExternalRequestReview['status'][] = [
+ 'pending',
+ 'approved',
+ 'processing',
+ 'completed',
+ 'rejected',
+ 'failed',
+ 'cancelled',
+];
+const lifecycleRequests: ExternalRequestReview[] = lifecycleStatuses.map((status, index) => ({
+ ...requests[0],
+ id: `lifecycle-${index}`,
+ status,
+ target: {
+ ...requests[0].target,
+ title: `Lifecycle ${status} request`,
+ },
+}));
+const lifecyclePage = pageFor(lifecycleRequests);
+
+const staleRequestId = '1b89e5bc-8c90-4e72-b245-270fed2eacc2';
+const staleRequest: ExternalRequestReview = {
+ ...requests[0],
+ id: staleRequestId,
+ target: { ...requests[0].target, title: 'Request changed while open' },
+};
+const staleResponse: ExternalRequestReview = {
+ ...staleRequest,
+ status: 'completed',
+ job: {
+ id: 'stale-job',
+ status: 'completed',
+ type: 'External video request',
+ createdAt: staleRequest.createdAt,
+ startedAt: staleRequest.createdAt,
+ },
+};
+
+const meta: Meta = {
+ title: 'Pages/External Requests',
+ component: RequestsPage,
+ args: { token: 'storybook-session-token' },
+ decorators: [
+ (Story) => (
+
+
+
+ ),
+ ],
+ parameters: {
+ layout: 'fullscreen',
+ a11y: { disable: false },
+ msw: {
+ handlers: [
+ http.get('/api/external-requests', () => HttpResponse.json(page)),
+ http.get(`/api/external-requests/${requestId}`, () => HttpResponse.json(requests[0])),
+ ],
+ },
+ },
+};
+
+export default meta;
+type Story = StoryObj;
+
+export const DesktopQueue: Story = {
+ parameters: {
+ viewport: { defaultViewport: 'desktop' },
+ },
+};
+
+export const MobileCards: Story = {
+ parameters: {
+ viewport: { defaultViewport: 'mobile1' },
+ },
+};
+
+export const ReviewActions: Story = {
+ play: async ({ canvasElement }) => {
+ const canvas = within(canvasElement);
+ await expect(await canvas.findByText('Never Gonna Give You Up', { exact: false }))
+ .toBeInTheDocument();
+ const requestCard = within(await canvas.findByTestId(`request-card-${requestId}`));
+ await userEvent.click(await requestCard.findByRole('button', { name: 'Details' }));
+ const pageBody = within(canvasElement.ownerDocument.body);
+ await expect(await pageBody.findByText('Request details')).toBeInTheDocument();
+ await userEvent.click(await pageBody.findByRole('button', { name: 'Approve' }));
+ await expect(await pageBody.findByText('Confirm approval')).toBeInTheDocument();
+ },
+};
+
+export const LifecycleStates: Story = {
+ parameters: {
+ msw: {
+ handlers: [
+ http.get('/api/external-requests', () => HttpResponse.json(lifecyclePage)),
+ ],
+ },
+ },
+ play: async ({ canvasElement }) => {
+ const canvas = within(canvasElement);
+ for (const status of ['Pending', 'Approved', 'Processing', 'Completed', 'Rejected', 'Failed', 'Cancelled']) {
+ await expect(await canvas.findByText(status, { exact: true })).toBeInTheDocument();
+ }
+ },
+};
+
+export const QueueErrorRetry: Story = {
+ parameters: {
+ msw: {
+ handlers: [
+ http.get('/api/external-requests', () => HttpResponse.json(
+ { error: 'Request service unavailable' },
+ { status: 503 }
+ )),
+ ],
+ },
+ },
+ play: async ({ canvasElement }) => {
+ const canvas = within(canvasElement);
+ await expect(await canvas.findByText('Request service unavailable')).toBeInTheDocument();
+ await expect(await canvas.findByRole('button', { name: 'Retry' })).toBeInTheDocument();
+ },
+};
+
+export const StaleDetail: Story = {
+ parameters: {
+ msw: {
+ handlers: [
+ http.get('/api/external-requests', () => HttpResponse.json(pageFor([staleRequest]))),
+ http.get(`/api/external-requests/${staleRequestId}`, () => HttpResponse.json(staleResponse)),
+ ],
+ },
+ },
+ play: async ({ canvasElement }) => {
+ const canvas = within(canvasElement);
+ const requestCard = within(await canvas.findByTestId(`request-card-${staleRequestId}`));
+ await userEvent.click(await requestCard.findByRole('button', { name: 'Details' }));
+ const pageBody = within(canvasElement.ownerDocument.body);
+ await expect(await pageBody.findByText('Completed', { exact: true })).toBeInTheDocument();
+ await expect(pageBody.queryByRole('button', { name: 'Approve' })).not.toBeInTheDocument();
+ },
+};
+
+export const ThumbnailFailure: Story = {
+ parameters: {
+ msw: {
+ handlers: [
+ http.get('/api/external-requests', () => HttpResponse.json(pageFor([requests[0]]))),
+ ],
+ },
+ },
+ play: async ({ canvasElement }) => {
+ const canvas = within(canvasElement);
+ const image = await canvas.findByRole('img', { name: /Rick Astley.*thumbnail/ });
+ await fireEvent.error(image);
+ await expect(await canvas.findByTestId('request-thumbnail-fallback')).toBeInTheDocument();
+ },
+};
+
+export const ApprovalActionError: Story = {
+ parameters: {
+ msw: {
+ handlers: [
+ http.get('/api/external-requests', () => HttpResponse.json(pageFor([requests[0]]))),
+ http.get(`/api/external-requests/${requestId}`, () => HttpResponse.json(requests[0])),
+ http.post(`/api/external-requests/${requestId}/approve`, () => HttpResponse.json(
+ { error: 'Request is no longer pending.' },
+ { status: 409 }
+ )),
+ ],
+ },
+ },
+ play: async ({ canvasElement }) => {
+ const canvas = within(canvasElement);
+ const requestCard = within(await canvas.findByTestId(`request-card-${requestId}`));
+ await userEvent.click(await requestCard.findByRole('button', { name: 'Details' }));
+ const pageBody = within(canvasElement.ownerDocument.body);
+ await userEvent.click(await pageBody.findByRole('button', { name: 'Approve' }));
+ await userEvent.click(await pageBody.findByRole('button', { name: 'Confirm approval' }));
+ await expect(await pageBody.findByText('Request is no longer pending.')).toBeInTheDocument();
+ },
+};
diff --git a/client/src/components/ExternalRequests/RequestsPage.tsx b/client/src/components/ExternalRequests/RequestsPage.tsx
new file mode 100644
index 000000000..2cadc79b3
--- /dev/null
+++ b/client/src/components/ExternalRequests/RequestsPage.tsx
@@ -0,0 +1,280 @@
+import React from 'react';
+import { useMediaQuery } from '../../hooks/useMediaQuery';
+import { Key } from '../../lib/icons';
+import { Link } from 'react-router-dom';
+import {
+ Alert,
+ Button,
+ Card,
+ CardContent,
+ CircularProgress,
+ MenuItem,
+ Select,
+ Table,
+ TableBody,
+ TableCell,
+ TableContainer,
+ TableHead,
+ TableRow,
+ Typography,
+} from '../ui';
+import PageControls from '../shared/PageControls';
+import {
+ ExternalRequestReview,
+ ExternalRequestStatus,
+} from '../../types/externalRequest';
+import RequestActions from './components/RequestActions';
+import RequestActionDialog from './components/RequestActionDialog';
+import RequestDetailsDialog from './components/RequestDetailsDialog';
+import RequestTarget, { RequestStatus } from './components/RequestTarget';
+import { useExternalRequests } from './hooks/useExternalRequests';
+import { requestDateLabel as dateLabel, requestStatusLabel } from './requestPolicy';
+
+const STATUSES: ExternalRequestStatus[] = [
+ 'pending',
+ 'approved',
+ 'processing',
+ 'completed',
+ 'rejected',
+ 'failed',
+ 'cancelled',
+];
+
+interface RequestsPageProps {
+ token: string;
+}
+
+const RequestsPage: React.FC = ({ token }) => {
+ // Leave room for the application sidebar and the table's review controls.
+ const compact = useMediaQuery('(max-width: 1439px)');
+ const state = useExternalRequests(token);
+ const {
+ filters,
+ requests,
+ requesters,
+ loading,
+ error,
+ totalPages,
+ page,
+ selected,
+ action,
+ detailLoading,
+ reason,
+ actionError,
+ submitting,
+ grantToRequestingKey,
+ } = state;
+ const controls = (request: ExternalRequestReview) => (
+ void state.openDetail(request)}
+ onAction={(next) => state.beginInlineAction(request, next)}
+ />
+ );
+ return (
+
+
+
+ External Requests
+
+ Review video, channel, and deletion requests submitted by approved
+ external clients.
+
+
+
+
+ Manage API keys
+
+
+
+
+
+
+
+
+ Status
+
+ state.setFilter('status', value)}
+ fullWidth
+ size="small"
+ inputProps={{ 'aria-label': 'Filter by status' }}
+ >
+ All statuses
+ {STATUSES.map((value) => (
+
+ {requestStatusLabel(value)}
+
+ ))}
+
+
+
+
+ Requester
+
+ state.setFilter('apiKeyId', value)}
+ fullWidth
+ size="small"
+ inputProps={{ 'aria-label': 'Filter by requester' }}
+ >
+ All requesters
+ {requesters.map((r) => (
+
+ {r.name} ({r.keyPrefix})
+
+ ))}
+
+
+
+
+ Type
+
+ state.setFilter('requestType', value)}
+ fullWidth
+ size="small"
+ inputProps={{ 'aria-label': 'Filter by request type' }}
+ >
+ All types
+ Video download
+ Channel
+ Video deletion
+
+
+
+ Refresh
+
+
+ {loading && (
+
+
+ Loading requests...
+
+ )}
+ {!loading && error && (
+
+
+ {error}
+
+ Retry
+
+
+
+ )}
+ {!loading && !error && requests.length === 0 && (
+
+
+ No requests match these filters.
+
+
+ )}
+ {!loading && !error && requests.length > 0 && (compact ? (
+
+ {requests.map(request => (
+
+
+
+
{controls(request)}
+
+
+
+
+
+
{request.requester?.name || 'Unavailable key'}
+
{dateLabel(request.createdAt)}
+
+
+ ))}
+
+ ) : (
+
+
+
+
+ Status
+ Request
+ Requester
+ Submitted
+
+ Review
+
+
+
+
+ {requests.map((request) => (
+
+
+
+
+
+
+
+
+
+
+ {request.requester?.name || 'Unavailable key'}
+
+
+ {dateLabel(request.createdAt)}
+
+ {controls(request)}
+
+ ))}
+
+
+
+ ))}
+ {!loading && !error && totalPages > 1 && (
+
+ )}
+
+
+ {selected && action === null && (
+
+ )}
+ {selected && action !== null && (
+
void state.submitAction()}
+ />
+ )}
+
+ );
+};
+export default RequestsPage;
diff --git a/client/src/components/ExternalRequests/__tests__/RequestsPage.test.tsx b/client/src/components/ExternalRequests/__tests__/RequestsPage.test.tsx
new file mode 100644
index 000000000..85d69551b
--- /dev/null
+++ b/client/src/components/ExternalRequests/__tests__/RequestsPage.test.tsx
@@ -0,0 +1,364 @@
+import React from 'react';
+import { act, fireEvent, render, screen, waitFor, within } from '@testing-library/react';
+import userEvent from '@testing-library/user-event';
+import { MemoryRouter } from 'react-router-dom';
+import axios from 'axios';
+import RequestsPage from '../RequestsPage';
+import { useMediaQuery } from '../../../hooks/useMediaQuery';
+
+jest.mock('../../../hooks/useMediaQuery', () => ({ useMediaQuery: jest.fn(() => false) }));
+import { ExternalRequestReview } from '../../../types/externalRequest';
+
+jest.mock('axios', () => ({
+ get: jest.fn(),
+ post: jest.fn(),
+ isAxiosError: (error: unknown) => Boolean((error as { response?: unknown })?.response),
+ isCancel: () => false,
+}));
+
+const mockedAxios = axios as jest.Mocked;
+
+const requestId = '9b89e5bc-8c90-4e72-b245-270fed2eacc2';
+const pendingRequest = {
+ id: requestId,
+ type: 'video' as const,
+ status: 'pending' as const,
+ requester: {
+ id: 4,
+ name: 'External Client',
+ keyPrefix: 'abcd1234',
+ role: 'request',
+ isActive: true,
+ revokedAt: null,
+ },
+ target: {
+ youtubeId: 'abcdefghijk',
+ channelId: 8,
+ youtubeChannelId: 'UC1234567890123456789012',
+ channelTitle: 'Safe Channel',
+ title: 'Safe video',
+ mediaType: 'video',
+ rating: 'TV-PG',
+ contentRating: 'TV-Y',
+ },
+ job: null,
+ createdAt: '2026-07-26T12:00:00.000Z',
+ updatedAt: '2026-07-26T12:00:00.000Z',
+};
+
+const page = (data: ExternalRequestReview[] = [pendingRequest]) => ({
+ data,
+ pagination: { page: 1, pageSize: 25, total: data.length, totalPages: data.length ? 1 : 0 },
+ filterOptions: { requesters: [pendingRequest.requester] },
+});
+
+const axiosResponse = (data: T) => ({ data });
+const axiosError = (message: string) => Object.assign(new Error(message), {
+ response: { data: { error: message } },
+});
+
+const renderPage = () => render(
+
+
+
+);
+
+describe('RequestsPage', () => {
+ beforeEach(() => {
+ (useMediaQuery as jest.Mock).mockReturnValue(false);
+ mockedAxios.get.mockReset();
+ mockedAxios.post.mockReset();
+ });
+
+ test('loads the queue, opens details, confirms approval, and refreshes status', async () => {
+ const processing = {
+ ...pendingRequest,
+ status: 'processing' as const,
+ job: {
+ id: requestId,
+ status: 'In Progress',
+ type: 'External video request',
+ createdAt: pendingRequest.createdAt,
+ startedAt: pendingRequest.createdAt,
+ },
+ };
+ mockedAxios.get
+ .mockResolvedValueOnce(axiosResponse(page()))
+ .mockResolvedValueOnce(axiosResponse(pendingRequest))
+ .mockResolvedValueOnce(axiosResponse(page([processing])));
+ mockedAxios.post.mockResolvedValueOnce(axiosResponse(processing));
+
+ const user = userEvent.setup();
+ renderPage();
+
+ expect(await screen.findByText('Safe video')).toBeInTheDocument();
+ expect(screen.getByText('External Client')).toBeInTheDocument();
+ expect(screen.getByText('Pending')).toBeInTheDocument();
+ expect(screen.getByRole('link', { name: 'Manage API keys' }))
+ .toHaveAttribute('href', '/settings/api-keys');
+ expect(screen.getByRole('img', { name: 'Safe video thumbnail' }))
+ .toHaveAttribute('src', 'https://i.ytimg.com/vi/abcdefghijk/mqdefault.jpg');
+ await user.click(screen.getByRole('button', { name: 'Details' }));
+ expect(await screen.findByText('Request details')).toBeInTheDocument();
+ await user.click(screen.getByRole('button', { name: 'Approve' }));
+ await user.click(screen.getByRole('button', { name: 'Confirm approval' }));
+
+ await waitFor(() => {
+ expect(mockedAxios.post).toHaveBeenCalledWith(
+ `/api/external-requests/${requestId}/approve`,
+ {},
+ expect.objectContaining({
+ headers: {
+ 'x-access-token': 'session-token',
+ },
+ })
+ );
+ });
+ await waitFor(() => {
+ expect(mockedAxios.get).toHaveBeenCalledTimes(3);
+ });
+ // A decision taken from the details dialog returns there with the new status.
+ expect(await screen.findByText('Request details')).toBeInTheDocument();
+ expect(mockedAxios.get).toHaveBeenLastCalledWith(
+ "/api/external-requests",
+ expect.objectContaining({ headers: { "x-access-token": "session-token" }, params: expect.objectContaining({ page: 1, pageSize: 25 }) })
+ );
+ });
+
+ test('shows empty and retryable error states', async () => {
+ mockedAxios.get
+ .mockRejectedValueOnce(axiosError('Unable to read request queue'))
+ .mockResolvedValueOnce(axiosResponse(page([])));
+
+ const user = userEvent.setup();
+ renderPage();
+
+ expect(await screen.findByText('Unable to read request queue')).toBeInTheDocument();
+ await user.click(screen.getByRole('button', { name: 'Retry' }));
+ expect(await screen.findByText('No requests match these filters.')).toBeInTheDocument();
+ });
+
+ test('requires a rejection reason before submission', async () => {
+ mockedAxios.get
+ .mockResolvedValueOnce(axiosResponse(page()))
+ .mockResolvedValueOnce(axiosResponse(pendingRequest));
+
+ const user = userEvent.setup();
+ renderPage();
+ await user.click(await screen.findByRole('button', { name: 'Details' }));
+ await user.click(await screen.findByRole('button', { name: 'Reject' }));
+
+ const confirm = screen.getByRole('button', { name: 'Confirm rejection' });
+ expect(confirm).toBeDisabled();
+ fireEvent.change(screen.getByRole('textbox'), { target: { value: 'Not approved' } });
+ expect(confirm).toBeEnabled();
+ });
+
+ test('reviews channel requests and sends the grant decision', async () => {
+ const channelRequest: ExternalRequestReview = {
+ ...pendingRequest,
+ type: 'channel',
+ target: {
+ youtubeId: null,
+ channelId: null,
+ channelUrl: 'https://www.youtube.com/@safechannel',
+ youtubeChannelId: null,
+ channelTitle: null,
+ title: null,
+ mediaType: null,
+ rating: null,
+ },
+ };
+ const completed = {
+ ...channelRequest,
+ status: 'completed' as const,
+ target: {
+ ...channelRequest.target,
+ channelId: 12,
+ youtubeChannelId: 'UC1234567890123456789012',
+ channelTitle: 'Safe Channel',
+ rating: 'TV-PG',
+ },
+ };
+ mockedAxios.get
+ .mockResolvedValueOnce(axiosResponse(page([channelRequest])))
+ .mockResolvedValueOnce(axiosResponse(channelRequest))
+ .mockResolvedValueOnce(axiosResponse(page([completed])));
+ mockedAxios.post.mockResolvedValueOnce(axiosResponse(completed));
+
+ const user = userEvent.setup();
+ renderPage();
+
+ await user.click(await screen.findByRole('button', { name: 'Details' }));
+ expect(screen.getAllByText('@safechannel').length).toBeGreaterThan(0);
+ expect(screen.getByText('New channel request')).toBeInTheDocument();
+ expect(screen.queryByText('Channel null')).not.toBeInTheDocument();
+ expect(screen.queryByText('https://www.youtube.com/@safechannel')).not.toBeInTheDocument();
+ expect(screen.getByRole('link', { name: 'Open channel' }))
+ .toHaveAttribute('href', 'https://www.youtube.com/@safechannel');
+ await user.click(screen.getByRole('button', { name: 'Approve' }));
+ await user.click(screen.getByLabelText(
+ 'Grant the provisioned channel to the requesting key'
+ ));
+ await user.click(screen.getByRole('button', { name: 'Confirm approval' }));
+
+ await waitFor(() => expect(mockedAxios.post).toHaveBeenCalledWith(
+ `/api/external-requests/${requestId}/approve`,
+ { grantToRequestingKey: false },
+ expect.objectContaining({
+ headers: { 'x-access-token': 'session-token' },
+ })
+ ));
+ });
+
+ test('renders compact request metadata and starts approval from the review column', async () => {
+ mockedAxios.get
+ .mockResolvedValueOnce(axiosResponse(page()))
+ .mockResolvedValueOnce(axiosResponse(page([{ ...pendingRequest, status: 'processing' }])));
+ mockedAxios.post.mockResolvedValueOnce(axiosResponse({ ...pendingRequest, status: 'processing' }));
+
+ const user = userEvent.setup();
+ renderPage();
+
+ await screen.findByText('Safe video');
+ const requestCell = screen.getByTestId(`request-summary-${requestId}`);
+ const cell = within(requestCell);
+ expect(cell.getAllByText('TV-Y').length).toBeGreaterThan(0);
+ expect(cell.queryByText("Downloaded")).not.toBeInTheDocument();
+
+ expect(screen.getByRole('button', { name: 'Details' })).toBeEnabled();
+ expect(screen.getByRole('button', { name: 'Approve request' })).toBeEnabled();
+ expect(screen.getByRole('button', { name: 'Reject request' })).toBeEnabled();
+
+ await user.click(screen.getByRole('button', { name: 'Approve request' }));
+ expect(screen.getByRole('button', { name: 'Confirm approval' })).toBeInTheDocument();
+ await user.click(screen.getByRole('button', { name: 'Confirm approval' }));
+
+ await waitFor(() => {
+ expect(mockedAxios.post).toHaveBeenCalledWith(
+ `/api/external-requests/${requestId}/approve`,
+ {},
+ expect.objectContaining({ headers: { 'x-access-token': 'session-token' } })
+ );
+ });
+ // A decision taken from the list goes back to the list, not to the details.
+ await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument());
+ });
+
+ test('keeps review controls aligned but disables decisions for a completed request', async () => {
+ const completed = { ...pendingRequest, status: 'completed' as const };
+ mockedAxios.get.mockResolvedValueOnce(axiosResponse(page([completed])));
+
+ renderPage();
+
+ expect(await screen.findByRole('button', { name: 'Details' })).toBeEnabled();
+ expect(screen.getByRole('button', { name: 'Approve request' })).toBeDisabled();
+ expect(screen.getByRole('button', { name: 'Reject request' })).toBeDisabled();
+ });
+
+ test('ignores an obsolete details response after starting an inline action', async () => {
+ const other = {
+ ...pendingRequest,
+ id: '8b89e5bc-8c90-4e72-b245-270fed2eacc2',
+ target: { ...pendingRequest.target, title: 'Other video' },
+ };
+ let resolveDetails!: (response: { data: ExternalRequestReview }) => void;
+ const deferredDetails = new Promise<{ data: ExternalRequestReview }>((resolve) => {
+ resolveDetails = resolve;
+ });
+ mockedAxios.get
+ .mockResolvedValueOnce(axiosResponse(page([pendingRequest, other])))
+ .mockImplementationOnce(() => deferredDetails)
+ .mockResolvedValue(axiosResponse(page([other])));
+ mockedAxios.post.mockResolvedValueOnce(axiosResponse({ ...other, status: 'approved' }));
+
+ const user = userEvent.setup();
+ renderPage();
+ await screen.findByText('Other video');
+ await user.click(within(screen.getByTestId(`request-card-${requestId}`)).getByRole('button', { name: 'Details' }));
+ await user.click(within(screen.getByRole('dialog')).getByText('Close', { selector: 'button' }));
+ await user.click(within(screen.getByTestId(`request-card-${other.id}`)).getByRole('button', { name: 'Approve request' }));
+ resolveDetails(axiosResponse(pendingRequest));
+ await user.click(screen.getByRole('button', { name: 'Confirm approval' }));
+
+ await waitFor(() => expect(mockedAxios.post).toHaveBeenCalledWith(
+ `/api/external-requests/${other.id}/approve`, {}, expect.anything()
+ ));
+ });
+ test('does not offer another approval for a request already approved', async () => {
+ const approved: ExternalRequestReview = { ...pendingRequest, status: 'approved' };
+ mockedAxios.get.mockResolvedValue(axiosResponse(page([approved])));
+ renderPage();
+
+ expect(await screen.findByRole('button', { name: 'Approve request' })).toBeDisabled();
+ });
+
+ test('refreshes the queue on its own while a request is still being worked on', async () => {
+ jest.useFakeTimers();
+ try {
+ const approved: ExternalRequestReview = { ...pendingRequest, status: 'approved' };
+ mockedAxios.get
+ .mockResolvedValueOnce(axiosResponse(page([approved])))
+ .mockResolvedValue(axiosResponse(page([{ ...approved, status: 'completed', updatedAt: '2026-07-26T12:05:00.000Z' }])));
+ renderPage();
+ await screen.findByText('Approved');
+
+ await act(async () => { jest.advanceTimersByTime(5000); });
+
+ expect(await screen.findByText('Completed')).toBeInTheDocument();
+ } finally {
+ jest.runOnlyPendingTimers();
+ jest.useRealTimers();
+ }
+ });
+
+ test('stops refreshing once nothing is in flight', async () => {
+ jest.useFakeTimers();
+ try {
+ mockedAxios.get.mockResolvedValue(axiosResponse(page()));
+ renderPage();
+ await screen.findByText('Safe video');
+
+ await act(async () => { jest.advanceTimersByTime(15000); });
+
+ expect(mockedAxios.get).toHaveBeenCalledTimes(1);
+ } finally {
+ jest.runOnlyPendingTimers();
+ jest.useRealTimers();
+ }
+ });
+
+ test('shows who approved a request in its details', async () => {
+ const approved: ExternalRequestReview = { ...pendingRequest, status: 'completed', approvalSource: 'auto' };
+ mockedAxios.get.mockResolvedValueOnce(axiosResponse(page([approved]))).mockResolvedValueOnce(axiosResponse(approved));
+ const user = userEvent.setup();
+ renderPage();
+
+ await user.click(await screen.findByRole('button', { name: 'Details' }));
+
+ expect(await screen.findByText('Automatically, by the key policy')).toBeInTheDocument();
+ });
+
+ test('does not offer decisions using stale details after a permission failure', async () => {
+ mockedAxios.get.mockResolvedValueOnce(axiosResponse(page()))
+ .mockRejectedValueOnce({ response: { status: 403 } });
+ const user = userEvent.setup();
+ renderPage();
+ await user.click(await screen.findByRole('button', { name: 'Details' }));
+ expect(await screen.findByText('Your session cannot review this request.')).toBeInTheDocument();
+ expect(within(screen.getByRole('dialog')).queryByRole('button', { name: 'Approve' })).not.toBeInTheDocument();
+ });
+
+ test.each([390, 834, 1280])('keeps review actions visible in cards at %ipx', async (width) => {
+ (useMediaQuery as jest.Mock).mockImplementation((query: string) =>
+ window.matchMedia(query).matches || width <= Number(query.match(/max-width: (\d+)px/)?.[1] || 0)
+ );
+ mockedAxios.get.mockResolvedValueOnce(axiosResponse(page()));
+ renderPage();
+ const card = await screen.findByRole('article');
+ expect(within(card).getByRole('button', { name: 'Approve request' })).toBeEnabled();
+ expect(within(card).getByText('External Client')).toBeInTheDocument();
+ expect(screen.queryByRole('table')).not.toBeInTheDocument();
+ });
+
+});
diff --git a/client/src/components/ExternalRequests/components/RequestActionDialog.tsx b/client/src/components/ExternalRequests/components/RequestActionDialog.tsx
new file mode 100644
index 000000000..b4103669a
--- /dev/null
+++ b/client/src/components/ExternalRequests/components/RequestActionDialog.tsx
@@ -0,0 +1,108 @@
+import React from 'react';
+import {
+ Alert,
+ Button,
+ Checkbox,
+ Dialog,
+ DialogActions,
+ DialogContentBody,
+ DialogContentText,
+ DialogTitle,
+ FormControlLabel,
+ TextField,
+} from '../../ui';
+import { ExternalRequestReview } from '../../../types/externalRequest';
+import { ReviewAction } from '../requestPolicy';
+
+export default function RequestActionDialog({
+ request,
+ action,
+ reason,
+ setReason,
+ grant,
+ setGrant,
+ error,
+ submitting,
+ onCancel,
+ onSubmit,
+}: {
+ request: ExternalRequestReview;
+ action: ReviewAction;
+ reason: string;
+ setReason: (value: string) => void;
+ grant: boolean;
+ setGrant: (value: boolean) => void;
+ error: string | null;
+ submitting: boolean;
+ onCancel: () => void;
+ onSubmit: () => void;
+}) {
+ return (
+
+
+ Confirm {action === 'approve' ? 'approval' : 'rejection'}
+
+
+
+ {action === 'approve'
+ ? request.type === 'channel'
+ ? 'Youtarr rechecks the requester now, then adds the channel in the background and optionally grants it to that key.'
+ : request.type === 'delete_video'
+ ? 'Youtarr rechecks policy now, then deletes the local video files in the background.'
+ : 'Youtarr rechecks policy now, then downloads the video in the background.'
+ : 'Rejecting this request is final. The client may submit a new request later.'}
+
+ {action === 'reject' && (
+ setReason(event.target.value)}
+ inputProps={{ maxLength: 300 }}
+ helperText={`${reason.trim().length}/300 characters`}
+ multiline
+ rows={3}
+ fullWidth
+ required
+ />
+ )}
+ {action === 'approve' && request.type === 'channel' && (
+ setGrant(event.target.checked)}
+ />
+ }
+ label="Grant the provisioned channel to the requesting key"
+ />
+ )}
+ {action === 'approve' && (
+ The status on this page updates as the work runs.
+ )}
+ {error && {error} }
+
+
+
+ Cancel
+
+
+ Confirm {action === 'approve' ? 'approval' : 'rejection'}
+
+
+
+ );
+}
diff --git a/client/src/components/ExternalRequests/components/RequestActions.tsx b/client/src/components/ExternalRequests/components/RequestActions.tsx
new file mode 100644
index 000000000..f20595860
--- /dev/null
+++ b/client/src/components/ExternalRequests/components/RequestActions.tsx
@@ -0,0 +1,56 @@
+import React from 'react';
+import { Info, ThumbsDown, ThumbsUp } from '../../../lib/icons';
+import { IconButton } from '../../ui';
+import { ExternalRequestReview } from '../../../types/externalRequest';
+import {
+ canApproveRequest,
+ canRejectRequest,
+ ReviewAction,
+} from '../requestPolicy';
+interface Props {
+ request: ExternalRequestReview;
+ submitting: boolean;
+ onDetails: () => void;
+ onAction: (action: ReviewAction) => void;
+}
+export default function RequestActions({
+ request,
+ submitting,
+ onDetails,
+ onAction,
+}: Props) {
+ const approveLabel = 'Approve request';
+ return (
+
+
+
+
+ onAction('approve')}
+ >
+
+
+ onAction('reject')}
+ >
+
+
+
+ );
+}
diff --git a/client/src/components/ExternalRequests/components/RequestDetailsDialog.tsx b/client/src/components/ExternalRequests/components/RequestDetailsDialog.tsx
new file mode 100644
index 000000000..5d9c8f96a
--- /dev/null
+++ b/client/src/components/ExternalRequests/components/RequestDetailsDialog.tsx
@@ -0,0 +1,138 @@
+import React from 'react';
+import { ExternalLink } from '../../../lib/icons';
+import {
+ Alert,
+ Button,
+ CircularProgress,
+ Dialog,
+ DialogActions,
+ DialogContentBody,
+ DialogTitle,
+} from '../../ui';
+import { ExternalRequestReview } from '../../../types/externalRequest';
+import RequestTarget, {
+ requestChannelLabel,
+ RequestStatus,
+} from './RequestTarget';
+import {
+ canApproveRequest,
+ canRejectRequest,
+ requestDateLabel as dateLabel,
+ ReviewAction,
+} from '../requestPolicy';
+
+export default function RequestDetailsDialog({
+ request,
+ loading,
+ error,
+ onClose,
+ onAction,
+}: {
+ request: ExternalRequestReview;
+ loading: boolean;
+ error: string | null;
+ onClose: () => void;
+ onAction: (action: ReviewAction) => void;
+}) {
+ return (
+
+ Request details
+
+ {loading ? (
+
+
+
+ ) : (
+
+ {error &&
{error} }
+
+
+
+
+
+ {request.target.youtubeId && (
+ <>
+ YouTube ID
+ {request.target.youtubeId}
+ >
+ )}
+ {request.target.channelUrl && (
+ <>
+ YouTube channel
+
+
+ Open channel
+
+
+ >
+ )}
+ Channel
+ {requestChannelLabel(request)}
+ Requester
+
+ {request.requester
+ ? `${request.requester.name} (${request.requester.keyPrefix})`
+ : 'Unavailable key'}
+
+ {request.approvalSource && (
+ <>
+ Approved
+ {request.approvalSource === 'auto' ? 'Automatically, by the key policy' : 'By an administrator'}
+ >
+ )}
+ Submitted
+ {dateLabel(request.createdAt)}
+ Last updated
+ {dateLabel(request.updatedAt)}
+ {request.job && (
+ <>
+ Download job
+
+ {request.job.status} - {request.job.id}
+
+ >
+ )}
+ {request.message && (
+ <>
+ Message
+ {request.message}
+ >
+ )}
+
+
+ )}
+
+
+
+ Close
+
+ {!loading &&
+ !error &&
+ (canApproveRequest(request) || canRejectRequest(request)) && (
+ <>
+ onAction('reject')}
+ >
+ Reject
+
+ onAction('approve')}
+ >
+ Approve
+
+ >
+ )}
+
+
+ );
+}
diff --git a/client/src/components/ExternalRequests/components/RequestTarget.tsx b/client/src/components/ExternalRequests/components/RequestTarget.tsx
new file mode 100644
index 000000000..9a6bfd10e
--- /dev/null
+++ b/client/src/components/ExternalRequests/components/RequestTarget.tsx
@@ -0,0 +1,137 @@
+import React, { useState } from 'react';
+import {
+ ExternalLink,
+ Radio,
+ Trash2,
+ Video,
+} from '../../../lib/icons';
+import { Avatar, Chip } from '../../ui';
+import RatingBadge from '../../shared/RatingBadge';
+import { ExternalRequestReview, ExternalRequestStatus } from '../../../types/externalRequest';
+import { requestStatusLabel } from '../requestPolicy';
+
+type ChipColor = 'success' | 'error' | 'info' | 'warning';
+
+const TYPE_LABELS: Record = {
+ video: 'Video download',
+ channel: 'Channel',
+ delete_video: 'Video deletion',
+};
+
+const STATUS_COLORS: Record = {
+ pending: 'warning',
+ approved: 'info',
+ processing: 'info',
+ completed: 'success',
+ rejected: 'error',
+ failed: 'error',
+ cancelled: 'error',
+};
+
+export const requestChannelLabel = (request: ExternalRequestReview) => {
+ const { channelTitle, youtubeChannelId } = request.target;
+ if (channelTitle) return channelTitle;
+ if (youtubeChannelId) return youtubeChannelId;
+ return request.type === 'channel' ? 'New channel request' : 'Unknown channel';
+};
+
+const targetLabel = (request: ExternalRequestReview) => {
+ const { title, channelTitle, channelUrl, youtubeId } = request.target;
+ if (title) return title;
+ if (request.type === 'channel') {
+ if (channelTitle) return channelTitle;
+ return channelUrl?.split('/').filter(Boolean).pop() || 'Requested YouTube channel';
+ }
+ return youtubeId ? `YouTube video ${youtubeId}` : 'Request target';
+};
+
+const targetUrl = (request: ExternalRequestReview) => {
+ if (request.type === 'channel') return request.target.channelUrl || null;
+ return request.target.youtubeId ? `https://www.youtube.com/watch?v=${request.target.youtubeId}` : null;
+};
+
+const TypeIcon = ({ type }: { type: ExternalRequestReview['type'] }) => {
+ if (type === 'delete_video') return ;
+ if (type === 'channel') return ;
+ return ;
+};
+
+interface RequestTargetProps {
+ request: ExternalRequestReview;
+ compact?: boolean;
+}
+
+export default function RequestTarget({ request, compact = false }: RequestTargetProps) {
+ const [thumbnailFailed, setThumbnailFailed] = useState(false);
+ const label = targetLabel(request);
+ const url = targetUrl(request);
+ const isChannel = request.type === 'channel';
+ const rating = request.target.contentRating || request.target.rating;
+ const channelThumbnail =
+ !thumbnailFailed && request.target.youtubeChannelId
+ ? `/images/channelthumb-${request.target.youtubeChannelId}.jpg`
+ : undefined;
+
+ return (
+
+ {isChannel ? (
+
setThumbnailFailed(true) }}
+ >
+
+
+ ) : (
+
+ {request.target.youtubeId && !thumbnailFailed ? (
+
setThumbnailFailed(true)}
+ className="h-full w-full object-cover"
+ />
+ ) : (
+
+
+
+ )}
+
+ )}
+
+
+
+ {label}
+
+ {url && (
+
+
+
+ )}
+
+
+ }
+ size="small"
+ variant="outlined"
+ />
+ {!isChannel && (
+ {requestChannelLabel(request)}
+ )}
+ {rating && }
+
+
+
+ );
+}
+
+export function RequestStatus({ status }: { status: ExternalRequestStatus }) {
+ return ;
+}
diff --git a/client/src/components/ExternalRequests/components/__tests__/RequestActions.test.tsx b/client/src/components/ExternalRequests/components/__tests__/RequestActions.test.tsx
new file mode 100644
index 000000000..4d968730f
--- /dev/null
+++ b/client/src/components/ExternalRequests/components/__tests__/RequestActions.test.tsx
@@ -0,0 +1,74 @@
+import React from 'react';
+import { render, screen } from '@testing-library/react';
+import userEvent from '@testing-library/user-event';
+import RequestActions from '../RequestActions';
+import { ExternalRequestReview } from '../../../../types/externalRequest';
+
+const request: ExternalRequestReview = {
+ id: 'request-1',
+ type: 'video',
+ status: 'pending',
+ requester: null,
+ target: {
+ youtubeId: 'abcdefghijk',
+ channelId: null,
+ youtubeChannelId: null,
+ channelTitle: null,
+ title: 'Safe video',
+ mediaType: 'video',
+ rating: null,
+ },
+ job: null,
+ createdAt: '2026-07-26T12:00:00.000Z',
+ updatedAt: '2026-07-26T12:00:00.000Z',
+};
+
+const renderActions = (overrides: Partial> = {}) => {
+ const props = { request, submitting: false, onDetails: jest.fn(), onAction: jest.fn(), ...overrides };
+ render( );
+ return props;
+};
+
+describe('RequestActions', () => {
+ test('starts an approval', async () => {
+ const { onAction } = renderActions();
+
+ await userEvent.click(screen.getByRole('button', { name: 'Approve request' }));
+
+ expect(onAction).toHaveBeenCalledWith('approve');
+ });
+
+ test('starts a rejection', async () => {
+ const { onAction } = renderActions();
+
+ await userEvent.click(screen.getByRole('button', { name: 'Reject request' }));
+
+ expect(onAction).toHaveBeenCalledWith('reject');
+ });
+
+ test('opens details', async () => {
+ const { onDetails } = renderActions();
+
+ await userEvent.click(screen.getByRole('button', { name: 'Details' }));
+
+ expect(onDetails).toHaveBeenCalled();
+ });
+
+ test('disables approval once a request is approved', () => {
+ renderActions({ request: { ...request, status: 'approved' } });
+
+ expect(screen.getByRole('button', { name: 'Approve request' })).toBeDisabled();
+ });
+
+ test('disables decisions for a completed request', () => {
+ renderActions({ request: { ...request, status: 'completed' } });
+
+ expect(screen.getByRole('button', { name: 'Approve request' })).toBeDisabled();
+ });
+
+ test('disables every control while a decision is submitting', () => {
+ renderActions({ submitting: true });
+
+ expect(screen.getByRole('button', { name: 'Details' })).toBeDisabled();
+ });
+});
diff --git a/client/src/components/ExternalRequests/components/__tests__/RequestTarget.test.tsx b/client/src/components/ExternalRequests/components/__tests__/RequestTarget.test.tsx
new file mode 100644
index 000000000..ae0a3f801
--- /dev/null
+++ b/client/src/components/ExternalRequests/components/__tests__/RequestTarget.test.tsx
@@ -0,0 +1,80 @@
+import React from 'react';
+import { render, screen } from '@testing-library/react';
+import RequestTarget, { RequestStatus, requestChannelLabel } from '../RequestTarget';
+import { ExternalRequestReview } from '../../../../types/externalRequest';
+
+const baseRequest: ExternalRequestReview = {
+ id: 'request-1',
+ type: 'video',
+ status: 'pending',
+ requester: null,
+ target: {
+ youtubeId: 'abcdefghijk',
+ channelId: null,
+ youtubeChannelId: null,
+ channelTitle: null,
+ title: null,
+ mediaType: 'video',
+ rating: null,
+ },
+ job: null,
+ createdAt: '2026-07-26T12:00:00.000Z',
+ updatedAt: '2026-07-26T12:00:00.000Z',
+};
+
+const channelRequest: ExternalRequestReview = {
+ ...baseRequest,
+ type: 'channel',
+ target: { ...baseRequest.target, youtubeId: null, channelUrl: 'https://www.youtube.com/@safechannel' },
+};
+
+describe('requestChannelLabel', () => {
+ test('describes a pending channel request without a resolved channel', () => {
+ expect(requestChannelLabel(channelRequest)).toBe('New channel request');
+ });
+
+ test('uses the channel title when the request has one', () => {
+ expect(requestChannelLabel({ ...baseRequest, target: { ...baseRequest.target, channelTitle: 'Safe Channel' } }))
+ .toBe('Safe Channel');
+ });
+
+ test('never shows a database id or null for a video with no known channel', () => {
+ expect(requestChannelLabel({ ...baseRequest, target: { ...baseRequest.target, channelId: 42 } }))
+ .toBe('Unknown channel');
+ });
+});
+
+describe('RequestTarget', () => {
+ test('labels an untitled video by its YouTube id', () => {
+ render( );
+
+ expect(screen.getByText('YouTube video abcdefghijk')).toBeInTheDocument();
+ });
+
+ test('labels an unresolved channel request by its URL handle', () => {
+ render( );
+
+ expect(screen.getByText('@safechannel')).toBeInTheDocument();
+ });
+
+ test('links a video request to YouTube', () => {
+ render( );
+
+ expect(screen.getByRole('link', { name: 'Open YouTube video abcdefghijk on YouTube' }))
+ .toHaveAttribute('href', 'https://www.youtube.com/watch?v=abcdefghijk');
+ });
+
+ test('names the request type', () => {
+ render( );
+
+ expect(screen.getByText('Video deletion')).toBeInTheDocument();
+ });
+});
+
+describe('RequestStatus', () => {
+ test('capitalizes the status', () => {
+ render( );
+
+ expect(screen.getByText('Processing')).toBeInTheDocument();
+ });
+});
diff --git a/client/src/components/ExternalRequests/hooks/__tests__/useExternalRequests.test.ts b/client/src/components/ExternalRequests/hooks/__tests__/useExternalRequests.test.ts
new file mode 100644
index 000000000..c95d4d53f
--- /dev/null
+++ b/client/src/components/ExternalRequests/hooks/__tests__/useExternalRequests.test.ts
@@ -0,0 +1,65 @@
+import { renderHook, waitFor, act } from '@testing-library/react';
+import axios from 'axios';
+import { useExternalRequests } from '../useExternalRequests';
+
+jest.mock('axios', () => ({
+ get: jest.fn(),
+ post: jest.fn(),
+ isAxiosError: (error: unknown) => Boolean((error as { response?: unknown })?.response),
+ isCancel: () => false,
+}));
+
+const mockedAxios = axios as jest.Mocked;
+const request = { id: 'request-1', type: 'channel' as const, status: 'pending' as const, requester: null, target: { youtubeId: null, channelId: null, channelUrl: 'https://www.youtube.com/@safechannel', youtubeChannelId: null, channelTitle: null, title: null, mediaType: 'channel', rating: null, contentRating: null }, job: null, createdAt: '2026-01-01T00:00:00Z', updatedAt: '2026-01-01T00:00:00Z' };
+const page = (totalPages = 1) => ({ data: [request], pagination: { page: 1, pageSize: 25, total: 1, totalPages }, filterOptions: { requesters: [] } });
+
+describe('useExternalRequests', () => {
+ beforeEach(() => { mockedAxios.get.mockReset(); mockedAxios.post.mockReset(); });
+ it('loads typed queue data and clamps a page removed by a mutation', async () => {
+ mockedAxios.get.mockResolvedValueOnce({ data: page(1) });
+ const { result } = renderHook(() => useExternalRequests('token'));
+ await waitFor(() => expect(result.current.requests).toHaveLength(1));
+ mockedAxios.get.mockResolvedValue({ data: { ...page(0), data: [] } });
+ act(() => result.current.setPage(3));
+ await waitFor(() => expect(result.current.page).toBe(1));
+ expect(mockedAxios.get).toHaveBeenNthCalledWith(
+ 2,
+ '/api/external-requests',
+ expect.objectContaining({ params: expect.objectContaining({ page: 3, pageSize: 25 }) })
+ );
+ });
+ it('treats a filter change after a background poll as a normal load', async () => {
+ jest.useFakeTimers();
+ try {
+ const inFlight = { ...request, status: 'processing' as const };
+ mockedAxios.get.mockResolvedValue({ data: { ...page(), data: [inFlight] } });
+ const { result } = renderHook(() => useExternalRequests('token'));
+ await waitFor(() => expect(result.current.loading).toBe(false));
+ await act(async () => { jest.advanceTimersByTime(5000); });
+ await waitFor(() => expect(mockedAxios.get).toHaveBeenCalledTimes(2));
+
+ let rejectLoad: (reason: unknown) => void = () => undefined;
+ mockedAxios.get.mockImplementationOnce(() => new Promise((_, reject) => { rejectLoad = reject; }));
+ act(() => result.current.setFilter('status', 'pending'));
+ expect(result.current.loading).toBe(true);
+
+ await act(async () => { rejectLoad({ response: { status: 500, data: { error: 'boom' } } }); });
+ await waitFor(() => expect(result.current.error).not.toBeNull());
+ expect(result.current.loading).toBe(false);
+ } finally {
+ jest.runOnlyPendingTimers();
+ jest.useRealTimers();
+ }
+ });
+ it('resets the channel grant choice for every new inline action', async () => {
+ mockedAxios.get.mockResolvedValue({ data: page() });
+ const { result } = renderHook(() => useExternalRequests('token'));
+ await waitFor(() => expect(result.current.requests).toHaveLength(1));
+ act(() => result.current.setGrantToRequestingKey(false));
+ act(() => result.current.beginInlineAction(request, 'approve'));
+ expect(result.current.grantToRequestingKey).toBe(true);
+ act(() => result.current.cancelAction());
+ expect(result.current.selected).toBeNull();
+ expect(result.current.action).toBeNull();
+ });
+});
diff --git a/client/src/components/ExternalRequests/hooks/__tests__/useRequestReview.test.ts b/client/src/components/ExternalRequests/hooks/__tests__/useRequestReview.test.ts
new file mode 100644
index 000000000..75ab1311e
--- /dev/null
+++ b/client/src/components/ExternalRequests/hooks/__tests__/useRequestReview.test.ts
@@ -0,0 +1,132 @@
+import { act, renderHook, waitFor } from '@testing-library/react';
+import axios from 'axios';
+import { useExternalRequests } from '../useExternalRequests';
+import { ExternalRequestReview, ExternalRequestReviewPage } from '../../../../types/externalRequest';
+
+jest.mock('axios', () => ({ get: jest.fn(), post: jest.fn(), isCancel: () => false,
+ isAxiosError: (error: unknown) => Boolean((error as { response?: unknown })?.response) }));
+const api = axios as jest.Mocked;
+const request: ExternalRequestReview = {
+ id: 'request-1', type: 'channel', status: 'pending', requester: null,
+ target: { youtubeId: null, channelId: null, youtubeChannelId: null,
+ channelTitle: null, title: null, mediaType: null, rating: null },
+ job: null, createdAt: '', updatedAt: '',
+};
+const page = (data: ExternalRequestReview[]): ExternalRequestReviewPage => ({ data,
+ pagination: { page: 1, pageSize: 25, total: data.length, totalPages: 1 },
+ filterOptions: { requesters: [] } });
+function deferred() {
+ let resolve!: (data: { data: T }) => void;
+ const promise = new Promise<{ data: T }>(r => { resolve = r; });
+ return { promise, resolve };
+}
+beforeEach(() => jest.clearAllMocks());
+
+test('a late response from an old filter cannot replace the current queue', async () => {
+ const previous = deferred();
+ api.get.mockReturnValueOnce(previous.promise).mockResolvedValueOnce({ data: page([]) });
+ const { result } = renderHook(() => useExternalRequests('session'));
+ act(() => result.current.setFilter('status', 'rejected'));
+ await waitFor(() => expect(result.current.loading).toBe(false));
+ await act(async () => previous.resolve({ data: page([request]) }));
+ expect(result.current.requests).toEqual([]);
+ expect(result.current.filters.status).toBe('rejected');
+});
+
+test('a shrinking queue clamps to its final page and fetches that page', async () => {
+ api.get.mockResolvedValueOnce({ data: { ...page([request]), pagination: { page: 1, totalPages: 2 } } })
+ .mockResolvedValueOnce({ data: page([]) }).mockResolvedValueOnce({ data: page([request]) });
+ const { result } = renderHook(() => useExternalRequests('session'));
+ await waitFor(() => expect(result.current.loading).toBe(false));
+ act(() => result.current.setPage(2));
+ await waitFor(() => expect(api.get).toHaveBeenCalledTimes(3));
+ await waitFor(() => expect(result.current.loading).toBe(false));
+ expect(result.current.page).toBe(1);
+ expect(result.current.requests).toEqual([request]);
+});
+
+test('duplicate submission is prevented and a declined channel grant is sent', async () => {
+ api.get.mockResolvedValue({ data: page([request]) });
+ const pending = deferred();
+ api.post.mockReturnValueOnce(pending.promise);
+ const { result } = renderHook(() => useExternalRequests('session'));
+ await waitFor(() => expect(result.current.loading).toBe(false));
+ act(() => result.current.beginInlineAction(request, 'approve'));
+ act(() => result.current.setGrantToRequestingKey(false));
+ act(() => { void result.current.submitAction(); void result.current.submitAction(); result.current.cancelAction(); });
+ expect(api.post).toHaveBeenCalledTimes(1);
+ expect(api.post).toHaveBeenCalledWith('/api/external-requests/request-1/approve',
+ { grantToRequestingKey: false }, expect.anything());
+ expect(result.current.selected).not.toBeNull();
+ await act(async () => pending.resolve({ data: { ...request, status: 'completed' } }));
+ expect(result.current.action).toBeNull();
+ // An inline decision closes back to the list.
+ expect(result.current.selected).toBeNull();
+});
+
+test('capacity errors retain the confirmation and support retry without losing its choice', async () => {
+ api.get.mockResolvedValue({ data: page([request]) });
+ api.post.mockRejectedValueOnce({ response: { status: 503 } })
+ .mockResolvedValueOnce({ data: { ...request, status: 'completed' } });
+ const { result } = renderHook(() => useExternalRequests('session'));
+ await waitFor(() => expect(result.current.loading).toBe(false));
+ act(() => result.current.beginInlineAction(request, 'approve'));
+ act(() => result.current.setGrantToRequestingKey(false));
+ await act(async () => result.current.submitAction());
+ expect(result.current.actionError).toMatch(/capacity/);
+ expect(result.current.action).toBe('approve');
+ await act(async () => result.current.submitAction());
+ expect(api.post).toHaveBeenLastCalledWith('/api/external-requests/request-1/approve',
+ { grantToRequestingKey: false }, expect.anything());
+});
+
+test('changing session discards pending details and a cancelled approval resets its grant', async () => {
+ const details = deferred();
+ api.get.mockResolvedValueOnce({ data: page([request]) }).mockReturnValueOnce(details.promise)
+ .mockResolvedValue({ data: page([]) });
+ const { result, rerender } = renderHook(({ token }) => useExternalRequests(token), { initialProps: { token: 'first' } });
+ await waitFor(() => expect(result.current.loading).toBe(false));
+ act(() => { void result.current.openDetail(request); });
+ rerender({ token: 'second' });
+ await act(async () => details.resolve({ data: request }));
+ expect(result.current.selected).toBeNull();
+ act(() => result.current.beginInlineAction(request, 'approve'));
+ act(() => result.current.setGrantToRequestingKey(false));
+ act(() => result.current.cancelAction());
+ expect(result.current.selected).toBeNull();
+ act(() => result.current.beginInlineAction(request, 'approve'));
+ expect(result.current.grantToRequestingKey).toBe(true);
+});
+
+test('cancelling an action started from the details dialog returns to those details', async () => {
+ api.get.mockResolvedValueOnce({ data: page([request]) }).mockResolvedValueOnce({ data: request });
+ const { result } = renderHook(() => useExternalRequests('session'));
+ await waitFor(() => expect(result.current.loading).toBe(false));
+ await act(async () => result.current.openDetail(request));
+ act(() => result.current.beginDetailAction('approve'));
+ expect(result.current.action).toBe('approve');
+ act(() => result.current.cancelAction());
+ expect(result.current.action).toBeNull();
+ expect(result.current.selected?.id).toBe('request-1');
+});
+
+test('cancelling an inline action returns to the list', async () => {
+ api.get.mockResolvedValueOnce({ data: page([request]) });
+ const { result } = renderHook(() => useExternalRequests('session'));
+ await waitFor(() => expect(result.current.loading).toBe(false));
+ act(() => result.current.beginInlineAction(request, 'reject'));
+ act(() => result.current.cancelAction());
+ expect(result.current.selected).toBeNull();
+});
+
+test('an action started from details resets the grant choice', async () => {
+ api.get.mockResolvedValueOnce({ data: page([request]) }).mockResolvedValueOnce({ data: request });
+ const { result } = renderHook(() => useExternalRequests('session'));
+ await waitFor(() => expect(result.current.loading).toBe(false));
+ await act(async () => result.current.openDetail(request));
+ act(() => result.current.beginDetailAction('approve'));
+ act(() => result.current.setGrantToRequestingKey(false));
+ act(() => result.current.cancelAction());
+ act(() => result.current.beginDetailAction('approve'));
+ expect(result.current.grantToRequestingKey).toBe(true);
+});
diff --git a/client/src/components/ExternalRequests/hooks/useExternalRequests.ts b/client/src/components/ExternalRequests/hooks/useExternalRequests.ts
new file mode 100644
index 000000000..82dc52473
--- /dev/null
+++ b/client/src/components/ExternalRequests/hooks/useExternalRequests.ts
@@ -0,0 +1,130 @@
+import { useCallback, useEffect, useRef, useState } from 'react';
+import axios from 'axios';
+import { ExternalRequestReview, ExternalRequestReviewPage } from '../../../types/externalRequest';
+import { useRequestReview } from './useRequestReview';
+import { requestError } from '../requestPolicy';
+
+export type { ReviewAction } from '../requestPolicy';
+
+const PAGE_SIZE = 25;
+// Approved and processing requests advance in a background executor, so the
+// queue refreshes itself while any of them is on screen.
+const ACTIVE_POLL_INTERVAL_MS = 5000;
+const isInFlight = (request: ExternalRequestReview) =>
+ request.status === 'approved' || request.status === 'processing';
+
+export interface ExternalRequestFilters {
+ status: string;
+ apiKeyId: string;
+ requestType: string;
+}
+
+const EMPTY_FILTERS: ExternalRequestFilters = { status: '', apiKeyId: '', requestType: '' };
+
+const EMPTY_PAGE: ExternalRequestReviewPage = {
+ data: [],
+ pagination: { page: 1, pageSize: PAGE_SIZE, total: 0, totalPages: 0 },
+ filterOptions: { requesters: [] },
+};
+
+export function useExternalRequests(token: string) {
+ const [filters, setFilters] = useState(EMPTY_FILTERS);
+ const [page, setPage] = useState(1);
+ const [data, setData] = useState(EMPTY_PAGE);
+ const [loading, setLoading] = useState(true);
+ const [error, setError] = useState(null);
+ // silent reloads (background polls) keep the current rows on screen.
+ const [reload, setReload] = useState({ count: 0, silent: false });
+ const loadSequence = useRef(0);
+ const lastQuery = useRef(null);
+ const refresh = useCallback(() => setReload((current) => ({ count: current.count + 1, silent: false })), []);
+ const review = useRequestReview(token, refresh);
+ const { syncFromList } = review;
+
+ useEffect(() => {
+ const controller = new AbortController();
+ const sequence = ++loadSequence.current;
+ const current = () => sequence === loadSequence.current && !controller.signal.aborted;
+ // A poll is silent only while it reloads the query it was started for;
+ // a filter or page change after it gets a normal load.
+ const query = JSON.stringify([page, filters.status, filters.apiKeyId, filters.requestType]);
+ const silent = reload.silent && lastQuery.current === query;
+ lastQuery.current = query;
+ if (!silent) {
+ setLoading(true);
+ setError(null);
+ }
+ axios
+ .get('/api/external-requests', {
+ headers: { 'x-access-token': token },
+ params: {
+ page,
+ pageSize: PAGE_SIZE,
+ ...(filters.status ? { status: filters.status } : {}),
+ ...(filters.apiKeyId ? { apiKeyId: filters.apiKeyId } : {}),
+ ...(filters.requestType ? { requestType: filters.requestType } : {}),
+ },
+ signal: controller.signal,
+ })
+ .then((response) => {
+ if (!current()) return;
+ // A review action can empty the last page; step back to the new last page.
+ const totalPages = Math.max(1, response.data.pagination.totalPages);
+ if (page > totalPages) {
+ setPage(totalPages);
+ return;
+ }
+ setData(response.data);
+ syncFromList(response.data.data);
+ setLoading(false);
+ })
+ .catch((loadError) => {
+ if (!current() || axios.isCancel(loadError)) return;
+ // A failed background poll keeps the rows shown and tries again on the next tick.
+ if (silent) {
+ setData((previous) => ({ ...previous }));
+ return;
+ }
+ setError(requestError(loadError, 'Unable to load requests'));
+ setLoading(false);
+ });
+ return () => controller.abort();
+ }, [filters.apiKeyId, filters.requestType, filters.status, page, reload, syncFromList, token]);
+
+ const hasInFlight = data.data.some(isInFlight);
+ useEffect(() => {
+ if (!hasInFlight || loading || error) return undefined;
+ const poll = () => {
+ if (document.visibilityState === 'hidden') return;
+ setReload((current) => ({ count: current.count + 1, silent: true }));
+ };
+ const onVisibilityChange = () => {
+ if (document.visibilityState === 'visible') poll();
+ };
+ const timer = setTimeout(poll, ACTIVE_POLL_INTERVAL_MS);
+ document.addEventListener('visibilitychange', onVisibilityChange);
+ return () => {
+ clearTimeout(timer);
+ document.removeEventListener('visibilitychange', onVisibilityChange);
+ };
+ }, [data, error, hasInFlight, loading]);
+
+ const setFilter = useCallback((name: keyof ExternalRequestFilters, value: string) => {
+ setFilters((current) => ({ ...current, [name]: value }));
+ setPage(1);
+ }, []);
+
+ return {
+ requests: data.data,
+ requesters: data.filterOptions.requesters,
+ page,
+ totalPages: Math.max(1, data.pagination.totalPages),
+ loading,
+ error,
+ filters,
+ setPage,
+ setFilter,
+ refresh,
+ ...review,
+ };
+}
diff --git a/client/src/components/ExternalRequests/hooks/useRequestReview.ts b/client/src/components/ExternalRequests/hooks/useRequestReview.ts
new file mode 100644
index 000000000..e0074fb7c
--- /dev/null
+++ b/client/src/components/ExternalRequests/hooks/useRequestReview.ts
@@ -0,0 +1,175 @@
+import { useCallback, useEffect, useRef, useState } from 'react';
+import axios from 'axios';
+import { ExternalRequestReview } from '../../../types/externalRequest';
+import { canApproveRequest, canRejectRequest, requestError, ReviewAction } from '../requestPolicy';
+
+interface ReviewState {
+ selected: ExternalRequestReview | null;
+ detailLoading: boolean;
+ action: ReviewAction | null;
+ // True when the action was started from the details dialog, so cancelling
+ // returns there instead of closing back to the list.
+ actionFromDetails: boolean;
+ reason: string;
+ actionError: string | null;
+ submitting: boolean;
+ grantToRequestingKey: boolean;
+}
+
+const EMPTY_REVIEW: ReviewState = {
+ selected: null,
+ detailLoading: false,
+ action: null,
+ actionFromDetails: false,
+ reason: '',
+ actionError: null,
+ submitting: false,
+ grantToRequestingKey: true,
+};
+
+const canTakeAction = (request: ExternalRequestReview, action: ReviewAction) =>
+ action === 'approve' ? canApproveRequest(request) : canRejectRequest(request);
+
+export function useRequestReview(token: string, refresh: () => void) {
+ const [review, setReview] = useState(EMPTY_REVIEW);
+ const sequence = useRef(0);
+ const submitting = useRef(false);
+
+ useEffect(() => {
+ ++sequence.current;
+ setReview(EMPTY_REVIEW);
+ return () => {
+ ++sequence.current;
+ };
+ }, [token]);
+
+ const openDetail = useCallback(
+ async (request: ExternalRequestReview) => {
+ if (submitting.current) return;
+ const current = ++sequence.current;
+ setReview({ ...EMPTY_REVIEW, selected: request, detailLoading: true });
+ try {
+ const response = await axios.get(`/api/external-requests/${request.id}`, {
+ headers: { 'x-access-token': token },
+ });
+ if (current === sequence.current) {
+ setReview((state) => ({ ...state, selected: response.data, detailLoading: false }));
+ }
+ } catch (error) {
+ if (current === sequence.current) {
+ setReview((state) => ({
+ ...state,
+ detailLoading: false,
+ actionError: requestError(error, 'Unable to load request details'),
+ }));
+ }
+ }
+ },
+ [token]
+ );
+
+ const beginInlineAction = useCallback((request: ExternalRequestReview, action: ReviewAction) => {
+ if (submitting.current || !canTakeAction(request, action)) return;
+ ++sequence.current;
+ setReview({ ...EMPTY_REVIEW, selected: request, action, grantToRequestingKey: true });
+ }, []);
+
+ const beginDetailAction = useCallback((action: ReviewAction) => {
+ if (submitting.current) return;
+ setReview((state) => {
+ if (!state.selected || state.detailLoading || !canTakeAction(state.selected, action)) return state;
+ return {
+ ...state,
+ action,
+ actionFromDetails: true,
+ reason: '',
+ actionError: null,
+ grantToRequestingKey: true,
+ };
+ });
+ }, []);
+
+ const closeDetails = useCallback(() => {
+ if (submitting.current) return;
+ ++sequence.current;
+ setReview(EMPTY_REVIEW);
+ }, []);
+
+ const { actionFromDetails } = review;
+ const cancelAction = useCallback(() => {
+ if (submitting.current) return;
+ if (actionFromDetails) {
+ setReview((state) => ({ ...EMPTY_REVIEW, selected: state.selected }));
+ return;
+ }
+ ++sequence.current;
+ setReview(EMPTY_REVIEW);
+ }, [actionFromDetails]);
+
+ const submitAction = useCallback(async () => {
+ const { selected, action, reason, grantToRequestingKey, actionFromDetails: fromDetails } = review;
+ if (!selected || !action || submitting.current) return;
+ if (action === 'reject' && !reason.trim()) return;
+ const current = sequence.current;
+ submitting.current = true;
+ setReview((state) => ({ ...state, submitting: true, actionError: null }));
+ try {
+ const payload =
+ action === 'reject'
+ ? { reason: reason.trim() }
+ : selected.type === 'channel'
+ ? { grantToRequestingKey }
+ : {};
+ const response = await axios.post(
+ `/api/external-requests/${selected.id}/${action}`,
+ payload,
+ { headers: { 'x-access-token': token } }
+ );
+ if (current !== sequence.current) return;
+ // A decision made from the details dialog returns there with the new
+ // status; one made from the list goes back to the list.
+ if (fromDetails) {
+ setReview({ ...EMPTY_REVIEW, selected: response.data });
+ } else {
+ ++sequence.current;
+ setReview(EMPTY_REVIEW);
+ }
+ refresh();
+ } catch (error) {
+ if (current === sequence.current) {
+ setReview((state) => ({ ...state, actionError: requestError(error, `Unable to ${action} request`) }));
+ }
+ } finally {
+ submitting.current = false;
+ if (current === sequence.current) setReview((state) => ({ ...state, submitting: false }));
+ }
+ }, [refresh, review, token]);
+
+ // Keeps an open details dialog in step with the queue's background refreshes.
+ const syncFromList = useCallback((requests: ExternalRequestReview[]) => {
+ setReview((state) => {
+ if (!state.selected || state.action || state.submitting || state.detailLoading) return state;
+ const fresh = requests.find((request) => request.id === state.selected?.id);
+ return fresh && fresh.updatedAt !== state.selected.updatedAt ? { ...state, selected: fresh } : state;
+ });
+ }, []);
+
+ const setReason = useCallback((reason: string) => setReview((state) => ({ ...state, reason })), []);
+ const setGrantToRequestingKey = useCallback(
+ (grantToRequestingKey: boolean) => setReview((state) => ({ ...state, grantToRequestingKey })),
+ []
+ );
+
+ return {
+ ...review,
+ openDetail,
+ beginInlineAction,
+ beginDetailAction,
+ closeDetails,
+ cancelAction,
+ submitAction,
+ syncFromList,
+ setReason,
+ setGrantToRequestingKey,
+ };
+}
diff --git a/client/src/components/ExternalRequests/requestPolicy.ts b/client/src/components/ExternalRequests/requestPolicy.ts
new file mode 100644
index 000000000..ced9baefa
--- /dev/null
+++ b/client/src/components/ExternalRequests/requestPolicy.ts
@@ -0,0 +1,31 @@
+import axios from 'axios';
+import { ExternalRequestReview, ExternalRequestStatus } from '../../types/externalRequest';
+
+export type ReviewAction = 'approve' | 'reject';
+
+// Approval only queues the work; a background executor moves approved requests
+// on to processing and a final status, so only pending requests take a decision.
+export const canApproveRequest = (request: ExternalRequestReview) => request.status === 'pending';
+
+export const canRejectRequest = (request: ExternalRequestReview) => request.status === 'pending';
+
+export const requestError = (error: unknown, fallback: string) => {
+ if (axios.isAxiosError<{ error?: string }>(error)) {
+ if (error.response?.data?.error) return error.response.data.error;
+ if (error.response?.status === 403) return 'Your session cannot review this request.';
+ if (error.response?.status === 404) return 'This request is no longer available.';
+ if (error.response?.status === 409) return 'This request has changed. Refresh to see its current status.';
+ if (error.response?.status === 503) return 'Work capacity is temporarily unavailable. Retry this action.';
+ return fallback;
+ }
+ return error instanceof Error ? error.message : fallback;
+};
+
+export const requestDateLabel = (value?: string) => {
+ if (!value) return '-';
+ const date = new Date(value);
+ return Number.isNaN(date.getTime()) ? '-' : date.toLocaleString();
+};
+
+export const requestStatusLabel = (status: ExternalRequestStatus) =>
+ status.charAt(0).toUpperCase() + status.slice(1);
diff --git a/client/src/components/Settings/Settings.tsx b/client/src/components/Settings/Settings.tsx
index b599753be..a929ffb66 100644
--- a/client/src/components/Settings/Settings.tsx
+++ b/client/src/components/Settings/Settings.tsx
@@ -54,13 +54,14 @@ import { LoggingSection } from '../Configuration/sections/LoggingSection';
interface SettingsProps {
token: string | null;
+ onRequestsNavLinkPreview?: (visible: boolean | null) => void;
}
const PREVIEW_CUSTOM_TEMPLATE_MESSAGE = 'Preview this custom filename template before saving.';
const normalizeFilenamePrefix = (prefix?: string | null) => (prefix ?? '').replace(/\s+$/, '');
-export function Settings({ token }: SettingsProps) {
+export function Settings({ token, onRequestsNavLinkPreview }: SettingsProps) {
const location = useLocation();
const {
@@ -250,6 +251,12 @@ export function Settings({ token }: SettingsProps) {
}
};
+ useEffect(() => {
+ return () => {
+ onRequestsNavLinkPreview?.(null);
+ };
+ }, [onRequestsNavLinkPreview]);
+
useEffect(() => {
if (!initialConfig) {
setHasUnsavedChanges(false);
@@ -519,6 +526,12 @@ export function Settings({ token }: SettingsProps) {
token={token}
apiKeyRateLimit={config.apiKeyRateLimit}
onRateLimitChange={(value) => handleConfigChange({ apiKeyRateLimit: value })}
+ externalApiEnabled={isPlatformManaged.externalApiEnabled}
+ showRequestsNavLink={config.showRequestsNavLink}
+ onShowRequestsNavLinkChange={(value) => {
+ handleConfigChange({ showRequestsNavLink: value });
+ onRequestsNavLinkPreview?.(value);
+ }}
/>
}
/>
diff --git a/client/src/components/Settings/SettingsIndex.tsx b/client/src/components/Settings/SettingsIndex.tsx
index a3f6f3e6c..0a7d507bc 100644
--- a/client/src/components/Settings/SettingsIndex.tsx
+++ b/client/src/components/Settings/SettingsIndex.tsx
@@ -42,7 +42,7 @@ export const SETTINGS_PAGES: SettingsPage[] = [
{ key: 'autoremove', title: 'Auto Removal', group: 'automation', description: 'Automated cleanup and retention policies.' },
{ key: 'storage-limits', title: 'Storage Limits', group: 'automation', description: 'Pause downloads when storage is full or over a size limit.' },
{ key: 'maintenance', title: 'Maintenance & Rescan', group: 'automation', description: 'Rescan files on disk and other maintenance actions.' },
- { key: 'api-keys', title: 'API Keys & Bookmarklet', group: 'integrations', description: 'One-click "Send to Youtarr" bookmarklet and phone shortcuts.' },
+ { key: 'api-keys', title: 'API Keys & Bookmarklet', group: 'integrations', description: 'One-click "Send to Youtarr" bookmarklet, phone shortcuts, and keys for dashboards and external apps.' },
{ key: 'notifications', title: 'Notifications', group: 'integrations', description: 'Toast notifications and alert behavior.' },
{ key: 'rss-feeds', title: 'RSS Feeds', group: 'integrations', description: 'A private RSS feed of your downloaded videos.' },
{ key: 'sonarr-radarr', title: 'Sonarr / Radarr', group: 'integrations', description: 'Let Sonarr and Radarr search and grab YouTube videos through Youtarr.' },
diff --git a/client/src/components/Subscriptions/hooks/useChannelList.ts b/client/src/components/Subscriptions/hooks/useChannelList.ts
index dc776db9c..b7d86871e 100644
--- a/client/src/components/Subscriptions/hooks/useChannelList.ts
+++ b/client/src/components/Subscriptions/hooks/useChannelList.ts
@@ -13,13 +13,15 @@ interface UseChannelListParams {
append?: boolean;
}
-interface ChannelListResponse {
- channels: Channel[];
+export interface ChannelListResponse {
+ channels: ChannelListEntry[];
total: number;
totalPages: number;
subFolders?: Array;
}
+export type ChannelListEntry = Channel & { database_id: number };
+
export const useChannelList = ({
token,
page,
diff --git a/client/src/components/layout/AppShell.tsx b/client/src/components/layout/AppShell.tsx
index 76b6cb479..9c8806ae8 100644
--- a/client/src/components/layout/AppShell.tsx
+++ b/client/src/components/layout/AppShell.tsx
@@ -15,7 +15,7 @@ import { HEADER_HEIGHT_DESKTOP, HEADER_HEIGHT_MOBILE, NAV_SIDEBAR_COLLAPSED_WIDT
import './layoutFallback.css';
import { Tv as SubscriptionsIcon, Library as VideoLibraryIcon } from 'lucide-react';
-import { Download as DownloadIcon, Settings as SettingsIcon } from '../../lib/icons';
+import { ClipboardList as RequestsIcon, Download as DownloadIcon, Settings as SettingsIcon } from '../../lib/icons';
interface AppShellProps {
token: string | null;
@@ -28,6 +28,7 @@ interface AppShellProps {
serverVersion?: string;
ytDlpUpdateAvailable?: boolean;
ytDlpUpdateTooltip?: string;
+ showRequestsNavLink?: boolean;
children: React.ReactNode;
}
@@ -44,6 +45,7 @@ export function AppShell({
serverVersion,
ytDlpUpdateAvailable = false,
ytDlpUpdateTooltip,
+ showRequestsNavLink = true,
children,
}: AppShellProps) {
const isMobile = useMediaQuery('(max-width: 767px)');
@@ -149,6 +151,12 @@ export function AppShell({
to: '/downloads',
subItems: downloadsSubItems,
},
+ {
+ key: 'requests' as const,
+ label: 'Requests',
+ icon: ,
+ to: '/requests',
+ },
{
key: 'settings' as const,
label: 'Settings',
@@ -158,8 +166,8 @@ export function AppShell({
subItems: settingsSubItems,
hideSubItemsOnMobile: true,
},
- ],
- [channelsSubItems, videosSubItems, downloadsSubItems, settingsSubItems]
+ ].filter((item) => item.key !== 'requests' || showRequestsNavLink),
+ [channelsSubItems, videosSubItems, downloadsSubItems, settingsSubItems, showRequestsNavLink]
);
const toggleDrawer = () => {
diff --git a/client/src/components/layout/__tests__/AppShell.test.tsx b/client/src/components/layout/__tests__/AppShell.test.tsx
index d4b548042..b3b85a854 100644
--- a/client/src/components/layout/__tests__/AppShell.test.tsx
+++ b/client/src/components/layout/__tests__/AppShell.test.tsx
@@ -14,16 +14,21 @@ jest.mock('../BackgroundDecorations', () => ({
}));
jest.mock('../NavHeader', () => ({
- NavHeader: ({ toggleDrawer, isCollapsed, layoutPolicy }: { toggleDrawer: () => void; isCollapsed: boolean; layoutPolicy: { breakpoint: string; navPlacement: string; showHeaderToggleOnMobile: boolean } }) => {
+ NavHeader: ({ toggleDrawer, isCollapsed, layoutPolicy, navItems }: { toggleDrawer: () => void; isCollapsed: boolean; layoutPolicy: { breakpoint: string; navPlacement: string; showHeaderToggleOnMobile: boolean }; navItems: Array<{ label: string }> }) => {
const showToggle = layoutPolicy.breakpoint === 'mobile'
? layoutPolicy.showHeaderToggleOnMobile
: layoutPolicy.navPlacement === 'sidebar';
- return showToggle ? (
-
- toggle:{layoutPolicy.navPlacement}:{layoutPolicy.breakpoint}:{String(isCollapsed)}
-
- ) : null;
+ return (
+ <>
+ {navItems.map((item) => item.label).join('|')}
+ {showToggle ? (
+
+ toggle:{layoutPolicy.navPlacement}:{layoutPolicy.breakpoint}:{String(isCollapsed)}
+
+ ) : null}
+ >
+ );
},
}));
@@ -115,6 +120,40 @@ describe('AppShell', () => {
localStorage.clear();
});
+ it('hides the Requests navigation item when configured off', () => {
+ setViewportMatch(false);
+ localStorage.setItem('uiThemeMode', 'playful');
+
+ render(
+
+
+
+ Shell content
+
+
+
+ );
+
+ expect(screen.getByTestId('header-nav-items')).not.toHaveTextContent('Requests');
+ });
+
+ it('shows the Requests navigation item when the effective gate is enabled', () => {
+ setViewportMatch(false);
+ localStorage.setItem('uiThemeMode', 'playful');
+
+ render(
+
+
+
+ Shell content
+
+
+
+ );
+
+ expect(screen.getByTestId('header-nav-items')).toHaveTextContent('Requests');
+ });
+
it('updates nav width when desktop sidebar is collapsed', async () => {
const user = userEvent.setup();
renderShell('playful');
@@ -223,4 +262,4 @@ describe('AppShell', () => {
expect(getLayoutRoot().style.getPropertyValue('--layout-content-padding')).toBe('0px');
expect(getLayoutRoot().style.getPropertyValue('--layout-content-frame-radius')).toBe('0px');
});
-});
\ No newline at end of file
+});
diff --git a/client/src/components/ui/select.tsx b/client/src/components/ui/select.tsx
index e273e5307..48a7c8352 100644
--- a/client/src/components/ui/select.tsx
+++ b/client/src/components/ui/select.tsx
@@ -141,9 +141,13 @@ const Select = React.forwardRef(
aria-labelledby={labelId}
// Tests use fireEvent.mouseDown to open the Select.
// Radix only responds to pointerdown, so we open directly here.
- // We only open (not toggle) — Radix's own handler handles closing.
+ // Real input never needs this: Radix opens on pointerdown for a
+ // mouse and on click for touch. A tap's compatibility mousedown
+ // comes before that click, so opening here put the menu under the
+ // finger and the click then landed on an option and closed it.
+ // Only synthetic (untrusted) events open from here.
onMouseDown={(e) => {
- if (!e.defaultPrevented && !disabled && !isOpen) {
+ if (!e.nativeEvent.isTrusted && !e.defaultPrevented && !disabled && !isOpen) {
handleOpenChange(true);
}
}}
diff --git a/client/src/config/configSchema.ts b/client/src/config/configSchema.ts
index 360eb14fc..4beb14996 100644
--- a/client/src/config/configSchema.ts
+++ b/client/src/config/configSchema.ts
@@ -193,6 +193,7 @@ export const CONFIG_FIELDS = {
// API Keys
apiKeyRateLimit: { default: 10, trackChanges: true },
+ showRequestsNavLink: { default: true, trackChanges: true },
// yt-dlp auto-update
autoUpdateYtdlp: { default: false, trackChanges: true },
@@ -343,6 +344,7 @@ export const DEFAULT_CONFIG: ConfigState = {
darkModeEnabled: CONFIG_FIELDS.darkModeEnabled.default,
channelVideosHotLoad: CONFIG_FIELDS.channelVideosHotLoad.default,
apiKeyRateLimit: CONFIG_FIELDS.apiKeyRateLimit.default,
+ showRequestsNavLink: CONFIG_FIELDS.showRequestsNavLink.default,
autoUpdateYtdlp: CONFIG_FIELDS.autoUpdateYtdlp.default,
ytdlpUpdateChannel: CONFIG_FIELDS.ytdlpUpdateChannel.default,
ytdlpLastChecked: CONFIG_FIELDS.ytdlpLastChecked.default,
diff --git a/client/src/hooks/useConfig.ts b/client/src/hooks/useConfig.ts
index 6121ac9cf..59d92b7ff 100644
--- a/client/src/hooks/useConfig.ts
+++ b/client/src/hooks/useConfig.ts
@@ -26,7 +26,8 @@ export function useConfig(token: string | null): UseConfigResult {
plexUrl: false,
authEnabled: true,
useTmpForDownloads: false,
- ytdlpUpdates: false
+ ytdlpUpdates: false,
+ externalApiEnabled: false
});
const [deploymentEnvironment, setDeploymentEnvironment] = useState({
platform: null,
diff --git a/client/src/lib/icons.ts b/client/src/lib/icons.ts
index aba45917e..a39eb931c 100644
--- a/client/src/lib/icons.ts
+++ b/client/src/lib/icons.ts
@@ -152,4 +152,7 @@ export {
RefreshCw,
Plus,
FolderX,
+ Pencil,
+ Radio,
+ ClipboardList,
} from 'lucide-react';
diff --git a/client/src/tests/storybook_coverage.test.js b/client/src/tests/storybook_coverage.test.js
index e92463d50..8b7b048aa 100644
--- a/client/src/tests/storybook_coverage.test.js
+++ b/client/src/tests/storybook_coverage.test.js
@@ -7,7 +7,37 @@ import * as subtitleLanguageStories from '../components/Configuration/__tests__/
import * as appShellStories from '../components/layout/__tests__/AppShell.story';
import * as navHeaderStories from '../components/layout/__tests__/NavHeader.story';
+jest.mock('msw', () => ({
+ http: {
+ get: () => ({}),
+ post: () => ({}),
+ },
+ HttpResponse: {
+ json: (body, init = {}) => ({ body, ...init }),
+ },
+}));
+
+const externalRequestStories = require('../components/ExternalRequests/RequestsPage.stories');
+
describe('storybook parity coverage', () => {
+
+ describe('external request Storybook coverage', () => {
+ test('keeps lifecycle and failure stories interactive with a11y checks enabled', () => {
+ const requiredStories = [
+ 'LifecycleStates',
+ 'QueueErrorRetry',
+ 'StaleDetail',
+ 'ThumbnailFailure',
+ 'ApprovalActionError',
+ ];
+ requiredStories.forEach((storyName) => {
+ expect(externalRequestStories[storyName]).toBeDefined();
+ expect(typeof externalRequestStories[storyName].play).toBe('function');
+ });
+ expect(externalRequestStories.default.parameters?.a11y?.disable).not.toBe(true);
+ });
+ });
+
test('VideoListItem Selectable story preserves selection behavior parity', async () => {
const { args } = await runStoryWithPlay(videoListItemStories, 'Selectable');
diff --git a/client/src/types/Channel.ts b/client/src/types/Channel.ts
index 3f3481d5d..29578a043 100644
--- a/client/src/types/Channel.ts
+++ b/client/src/types/Channel.ts
@@ -15,6 +15,7 @@ export interface TabDownloadStats {
export type TabDownloadStatsByTab = Partial>;
export interface Channel {
+ database_id?: number;
url: string;
uploader: string;
channel_id?: string;
diff --git a/client/src/types/externalRequest.ts b/client/src/types/externalRequest.ts
new file mode 100644
index 000000000..7a1eb16b2
--- /dev/null
+++ b/client/src/types/externalRequest.ts
@@ -0,0 +1,62 @@
+export type ExternalRequestStatus =
+ | 'pending'
+ | 'approved'
+ | 'processing'
+ | 'completed'
+ | 'rejected'
+ | 'failed'
+ | 'cancelled';
+
+export interface ExternalRequestRequester {
+ id: number;
+ name: string;
+ keyPrefix: string;
+ role: string;
+ isActive: boolean;
+ revokedAt: string | null;
+}
+
+export interface ExternalRequestReview {
+ id: string;
+ type: 'video' | 'channel' | 'delete_video';
+ status: ExternalRequestStatus;
+ requester: ExternalRequestRequester | null;
+ target: {
+ youtubeId: string | null;
+ channelId: number | null;
+ channelUrl?: string | null;
+ youtubeChannelId: string | null;
+ channelTitle: string | null;
+ title: string | null;
+ mediaType: string | null;
+ rating: string | null;
+ contentRating?: string | null;
+ };
+ job: {
+ id: string;
+ status: string;
+ type: string;
+ createdAt: string;
+ startedAt: string;
+ } | null;
+ createdAt: string;
+ updatedAt: string;
+ decidedAt?: string;
+ completedAt?: string;
+ message?: string;
+ grantToRequestingKey?: boolean;
+ approvalSource?: 'auto' | 'admin' | null;
+}
+
+export interface ExternalRequestReviewPage {
+ data: ExternalRequestReview[];
+ pagination: {
+ page: number;
+ pageSize: number;
+ total: number;
+ totalPages: number;
+ };
+ filterOptions: {
+ requesters: ExternalRequestRequester[];
+ };
+}
diff --git a/client/src/utils/__tests__/externalRatingPolicy.test.ts b/client/src/utils/__tests__/externalRatingPolicy.test.ts
new file mode 100644
index 000000000..1c4ec602b
--- /dev/null
+++ b/client/src/utils/__tests__/externalRatingPolicy.test.ts
@@ -0,0 +1,21 @@
+import {
+ EXTERNAL_RATING_BANDS,
+ formatExternalRatingBand,
+ getExternalRatingBand,
+} from '../externalRatingPolicy';
+
+describe('external rating policy labels', () => {
+ test('maps every internal level to explicit movie and TV ratings', () => {
+ expect(EXTERNAL_RATING_BANDS).toEqual([
+ expect.objectContaining({ level: 1, movieRatings: ['G'], tvRatings: ['TV-Y', 'TV-G'] }),
+ expect.objectContaining({ level: 2, movieRatings: ['PG'], tvRatings: ['TV-Y7', 'TV-PG'] }),
+ expect.objectContaining({ level: 3, movieRatings: ['PG-13'], tvRatings: ['TV-14'] }),
+ expect.objectContaining({ level: 4, movieRatings: ['R', 'NC-17'], tvRatings: ['TV-MA'] }),
+ ]);
+ });
+
+ test('formats a rating ceiling without exposing the numeric implementation detail', () => {
+ expect(formatExternalRatingBand(3)).toBe('Teen · Movies PG-13 · TV TV-14');
+ expect(getExternalRatingBand(99).label).toBe('Mature');
+ });
+});
diff --git a/client/src/utils/externalRatingPolicy.ts b/client/src/utils/externalRatingPolicy.ts
new file mode 100644
index 000000000..20ab44fc7
--- /dev/null
+++ b/client/src/utils/externalRatingPolicy.ts
@@ -0,0 +1,47 @@
+export interface ExternalRatingBand {
+ level: 1 | 2 | 3 | 4;
+ label: string;
+ movieRatings: string[];
+ tvRatings: string[];
+}
+
+/**
+ * Human-readable presentation of the server's shared rating levels.
+ * The numeric value remains an internal API contract; administrators choose
+ * using the familiar movie and TV ratings that the policy actually allows.
+ */
+export const EXTERNAL_RATING_BANDS: ExternalRatingBand[] = [
+ {
+ level: 1,
+ label: 'General audiences',
+ movieRatings: ['G'],
+ tvRatings: ['TV-Y', 'TV-G'],
+ },
+ {
+ level: 2,
+ label: 'Parental guidance',
+ movieRatings: ['PG'],
+ tvRatings: ['TV-Y7', 'TV-PG'],
+ },
+ {
+ level: 3,
+ label: 'Teen',
+ movieRatings: ['PG-13'],
+ tvRatings: ['TV-14'],
+ },
+ {
+ level: 4,
+ label: 'Mature',
+ movieRatings: ['R', 'NC-17'],
+ tvRatings: ['TV-MA'],
+ },
+];
+
+export const getExternalRatingBand = (level: number) =>
+ EXTERNAL_RATING_BANDS.find((band) => band.level === level) ||
+ EXTERNAL_RATING_BANDS[EXTERNAL_RATING_BANDS.length - 1];
+
+export const formatExternalRatingBand = (level: number) => {
+ const band = getExternalRatingBand(level);
+ return `${band.label} · Movies ${band.movieRatings.join('/')} · TV ${band.tvRatings.join('/')}`;
+};
diff --git a/config/config.example.json b/config/config.example.json
index 562db40f5..da6da3acd 100644
--- a/config/config.example.json
+++ b/config/config.example.json
@@ -101,6 +101,7 @@
"uuid": "",
"supportPromptShownAt": null,
"apiKeyRateLimit": 10,
+ "showRequestsNavLink": true,
"autoUpdateYtdlp": false,
"ytdlpUpdateChannel": "stable",
"ytdlpLastChecked": null,
diff --git a/docs/AUTHENTICATION.md b/docs/AUTHENTICATION.md
index 1c059447b..8c516a11a 100644
--- a/docs/AUTHENTICATION.md
+++ b/docs/AUTHENTICATION.md
@@ -121,6 +121,18 @@ For deployments behind external authentication or not exposed to the internet:
API Keys provide persistent authentication for external integrations like bookmarklets, mobile shortcuts, and automation tools.
+### Key types
+
+Youtarr has three kinds of API key:
+
+- **Download keys** (`legacy_download`) queue single videos through `POST /api/videos/download`. Keys created before the External API existed are download keys.
+- **Read-only status keys** (`status_read`) read `GET /api/status/summary` and nothing else.
+- **External access keys** use the opt-in `/external-api/v1` surface, set with `EXTERNAL_API_ENABLED=true`. Each one carries its own request permissions, rating and media policy, workload limits and channel grants, and is created and edited under **Settings → API Keys & Bookmarklet**. See [EXTERNAL_API.md](EXTERNAL_API.md) for the policy model, endpoints and request review.
+
+No key type can use another type's endpoints. While the External API is turned off, external access keys cannot be used but stay listed in Settings, where they can be revoked, because they still count toward the 20-key limit.
+
+The schema and migration history are authoritative for field details. API-key values remain hashed and are never recoverable from the database; revocation is represented by `revoked_at` and inactive status.
+
### Key Features
- **Persistent**: No expiration (unlike session tokens)
- **Scoped**: A download key can only queue single videos; a read-only status key can only read the status summary
diff --git a/docs/CONFIG.md b/docs/CONFIG.md
index 9731d67eb..5ee716770 100644
--- a/docs/CONFIG.md
+++ b/docs/CONFIG.md
@@ -1136,9 +1136,16 @@ Settings for API key authentication used by the "Send to Youtarr" bookmarklet, m
- **Config Key**: `apiKeyRateLimit`
- **Type**: `number`
- **Default**: `10`
-- **Description**: Maximum download requests per minute per API key
+- **Description**: Maximum legacy download requests per minute per API key
- **Range**: 1-100
-- **Note**: Helps prevent abuse from external integrations. Each API key is rate-limited independently.
+- **Note**: Applies to legacy download keys. Versioned external access has separate read, write, and durable workload limits; see [External API rate limits](EXTERNAL_API.md#rate-limits).
+
+### Requests Navigation Link
+- **Config Key**: `showRequestsNavLink`
+- **Type**: `boolean`
+- **Default**: `true`
+- **Description**: Controls whether the administrator Requests page appears in the application navigation when the versioned external API is enabled.
+- **Note**: This setting cannot enable the Requests page unless `EXTERNAL_API_ENABLED` resolves to `true` after trimming whitespace and ignoring letter case; the environment capability is the controlling gate.
For detailed information on creating and using API keys, see [API Integration Guide](API_INTEGRATION.md).
diff --git a/docs/EXTERNAL_API.md b/docs/EXTERNAL_API.md
index f54e5a75f..3d80d855a 100644
--- a/docs/EXTERNAL_API.md
+++ b/docs/EXTERNAL_API.md
@@ -431,8 +431,21 @@ may contain secrets.
## Configuration and administration
-This runtime includes the management APIs. The external-access editor and
-request-review UI are a separate follow-up in [PR #809](https://github.com/DialmasterOrg/Youtarr/pull/809).
+In **Settings → API Keys & Bookmarklet**, choose **Create external key**,
+set the required request permissions, rating/media policy, workload limits,
+and approved channels, then save the one-time secret. Existing keys can be
+edited, regenerated, or revoked from their cards. Regeneration preserves
+policy and grants while immediately invalidating the previous credential.
+
+The **Requests** page supports status, requester, and request-type filters,
+pagination, details, approval, and rejection with a reason. Channel approval
+lets you choose whether to grant the provisioned channel to the requesting key.
+A decision error keeps the confirmation retryable. Approved requests advance
+automatically through the background executor; temporarily held work stays
+approved with a message until it can proceed. Mobile layouts keep review
+actions on each request card.
+
+The same operations are available through the management APIs:
1. Create an external key with session-authenticated `POST /api/keys` and save
the returned raw secret; it is shown only once. Omitting `policy` creates a
@@ -454,6 +467,11 @@ request-review UI are a separate follow-up in [PR #809](https://github.com/Dialm
`POST /api/external-requests/{id}/approve` or `/reject` (a rejection requires
a JSON `reason`). Policy and grants can be replaced atomically with
`PUT /api/keys/{id}/external-access` and a `{ "policy": ..., "channelIds": [...] }` body.
+ The replacement covers grants on enabled, non-terminated channels, the
+ ones `GET /api/keys/{id}/channels` lists. A grant on a disabled or
+ terminated channel is kept but grants nothing until the channel is enabled
+ again, at which point it is back in the editor and can be removed there.
+ A revoked key can use none of its grants.
`GET /getconfig` reports the effective feature flag in
`isPlatformManaged.externalApiEnabled`; clients should use this value when
@@ -464,6 +482,10 @@ accepted request and its idempotency key. Retry the same body to resume it
without charging another accepted write. Completed video, channel, and
deletion requests return their original result on an idempotent retry.
+While `EXTERNAL_API_ENABLED` is off, the settings page still lists active
+external keys so they can be revoked, since they count toward the 20-key
+limit; creating, editing and regenerating them wait until the API is on.
+
Saving an external key with zero approved channels is intentional and does not
backfill or grant access. That key fails closed: catalog reads and requests
return no granted content until an administrator adds enabled, non-terminated
diff --git a/docs/USAGE_GUIDE.md b/docs/USAGE_GUIDE.md
index 763542eab..7e4b6c489 100644
--- a/docs/USAGE_GUIDE.md
+++ b/docs/USAGE_GUIDE.md
@@ -753,6 +753,33 @@ Send videos to Youtarr from anywhere using API keys. This enables one-click down
- The full key is shown only once
- Copy it to a secure location before closing the dialog
+### Versioned external API keys and the Requests page
+
+When the server runs with `EXTERNAL_API_ENABLED=true` (see [External API](EXTERNAL_API.md)), the same settings page gains an **External access keys** section below the bookmarklet keys. These keys use `/external-api/v1` for approved catalog access and approval-backed video, channel, and deletion requests. Bookmarklet keys cannot use `/external-api/v1`, and external keys cannot use the bookmarklet endpoint. With the variable unset, the Requests page is hidden and the section appears only while an external key is still active, so you can revoke it (it still counts toward the 20-key limit); you cannot create, edit or regenerate external keys until the API is turned back on.
+
+1. Click **Create external key**, name it, choose its permissions and content policy, and select the channels it may see.
+2. To change grants later, use the edit action on the key's card. Youtarr asks for confirmation before saving a change that widens what the key can see or request.
+
+Open **Requests** in the main navigation to review what external clients submitted. The page filters by status, requester, and type, and every approval or rejection is confirmed first. The **Show Requests in navigation** switch on the API keys page hides the link without turning the API off; the page stays reachable at `/requests`.
+
+- **Approve** rechecks the requester's current role and policy, its current
+ channel grant, the enabled cached catalog entry, media type, rating, and
+ downloaded/duplicate state, then hands the work to a background runner. The
+ request shows **Approved** until the work starts, then **Processing**, then
+ **Completed** or **Failed**; the page refreshes itself while any request on
+ it is approved or processing. A request held while downloads are paused
+ stays Approved with a note saying what it is waiting for.
+- **Reject** requires a short reason. Rejection is final for that request, but
+ clears the active dedupe record so the client can submit a new request later.
+- Requests that are no longer safe fail without exposing internal errors.
+ Temporary work-capacity or storage limits hold the request as Approved for
+ automatic retry.
+- Channel approval provisions the canonical channel and grants it to the
+ requester by default. Video deletion approval removes only the downloaded
+ asset; it never removes the channel subscription.
+
+The Requests page uses your Youtarr login (or no login when `AUTH_ENABLED=false`). External API keys cannot reach the review queue or its actions.
+
### Install a Browser Bookmarklet
After creating an API key, you can set up a bookmarklet to send videos with one click:
diff --git a/server/__tests__/server.additional-routes.test.js b/server/__tests__/server.additional-routes.test.js
index c4ea7210a..07bbd6fd7 100644
--- a/server/__tests__/server.additional-routes.test.js
+++ b/server/__tests__/server.additional-routes.test.js
@@ -51,6 +51,7 @@ const createMockResponse = () => {
const createServerModule = ({
authEnabled = 'true',
+ externalApiEnabled,
passwordHash = 'hashed-password',
session,
skipInitialize = false,
@@ -73,6 +74,11 @@ const createServerModule = ({
} else {
process.env.AUTH_ENABLED = authEnabled;
}
+ if (externalApiEnabled === undefined) {
+ delete process.env.EXTERNAL_API_ENABLED;
+ } else {
+ process.env.EXTERNAL_API_ENABLED = externalApiEnabled;
+ }
const defaultSessionUpdate = jest.fn().mockResolvedValue();
let effectiveSession;
@@ -413,6 +419,7 @@ const createServerModule = ({
afterEach(() => {
delete process.env.AUTH_ENABLED;
+ delete process.env.EXTERNAL_API_ENABLED;
});
describe('server routes - plex integration', () => {
@@ -1450,3 +1457,26 @@ describe('server routes - getplexlibraries with test params', () => {
expect(res.body).toEqual([]);
});
});
+
+
+describe('external API capability consistency', () => {
+ test.each([
+ ['true', true],
+ [' true ', true],
+ ['TRUE', true],
+ ['false', false],
+ [undefined, false],
+ ])('keeps the route gate and /getconfig aligned for EXTERNAL_API_ENABLED=%s', async (externalApiEnabled, expected) => {
+ const { app } = await createServerModule({ externalApiEnabled });
+ const handlers = findRouteHandlers(app, 'get', '/getconfig');
+ const getConfigHandler = handlers[handlers.length - 1];
+ const req = createMockRequest({});
+ const res = createMockResponse();
+
+ await getConfigHandler(req, res);
+
+ expect(res.statusCode).toBe(200);
+ expect(res.body.isPlatformManaged.externalApiEnabled).toBe(expected);
+ expect(require('../modules/externalApi/externalApiConfig').isExternalApiEnabled()).toBe(expected);
+ });
+});
diff --git a/server/modules/channel/__tests__/channelCatalog.test.js b/server/modules/channel/__tests__/channelCatalog.test.js
index 86a9680b0..87a8e13dc 100644
--- a/server/modules/channel/__tests__/channelCatalog.test.js
+++ b/server/modules/channel/__tests__/channelCatalog.test.js
@@ -174,7 +174,7 @@ describe('channelCatalog', () => {
expect(Channel.findAndCountAll).toHaveBeenCalledWith(expect.objectContaining({
limit: 10,
offset: 10,
- order: [['uploader', 'DESC']]
+ order: [['uploader', 'DESC'], ['id', 'DESC']]
}));
expect(result).toEqual({
diff --git a/server/modules/channel/__tests__/channelMappers.test.js b/server/modules/channel/__tests__/channelMappers.test.js
index d24d58d71..a76a682b0 100644
--- a/server/modules/channel/__tests__/channelMappers.test.js
+++ b/server/modules/channel/__tests__/channelMappers.test.js
@@ -192,3 +192,9 @@ describe('channelMappers', () => {
});
});
});
+
+// database_id is required by API-key channel grants.
+test('mapChannelListEntry includes database_id', () => {
+ const result = require('../channelMappers').mapChannelListEntry({ id: 42, url: 'https://youtube.com/@test', uploader: 'Test', channel_id: 'UC123' });
+ expect(result.database_id).toBe(42);
+});
diff --git a/server/modules/channel/channelCatalog.js b/server/modules/channel/channelCatalog.js
index 284b948e8..a35bb6249 100644
--- a/server/modules/channel/channelCatalog.js
+++ b/server/modules/channel/channelCatalog.js
@@ -186,7 +186,8 @@ class ChannelCatalog {
where: whereClause,
limit: safePageSize,
offset,
- order: [[sortColumn, direction]],
+ // id breaks ties so equal or empty names keep a stable order across pages.
+ order: [[sortColumn, direction], ['id', direction]],
});
const distinctSubFolders = await Channel.findAll({
diff --git a/server/modules/externalApi/__tests__/apiKeyChannelGrantModule.test.js b/server/modules/externalApi/__tests__/apiKeyChannelGrantModule.test.js
index d50934628..885b44c74 100644
--- a/server/modules/externalApi/__tests__/apiKeyChannelGrantModule.test.js
+++ b/server/modules/externalApi/__tests__/apiKeyChannelGrantModule.test.js
@@ -23,14 +23,15 @@ describe('API key channel grants', () => {
test('normalizes and transactionally replaces the exact enabled set', async () => {
ApiKey.findByPk.mockResolvedValue({ id: 7, role: 'view', is_active: true, revoked_at: null });
Channel.count.mockResolvedValue(2);
+ ApiKeyChannelGrant.findAll.mockResolvedValue([{ channel_id: 3 }, { channel_id: 4 }]);
const result = await grants.replaceChannelGrants(7, [9, 3, 9]);
expect(result).toEqual({ keyId: 7, channelIds: [3, 9] });
expect(ApiKeyChannelGrant.destroy).toHaveBeenCalledWith({
- where: { api_key_id: 7 }, transaction: { id: 'transaction', LOCK: { UPDATE: 'UPDATE' } },
+ where: { api_key_id: 7, channel_id: [3, 4] }, transaction: { id: 'transaction', LOCK: { UPDATE: 'UPDATE' } },
});
expect(ApiKeyChannelGrant.bulkCreate).toHaveBeenCalledWith(
[{ api_key_id: 7, channel_id: 3 }, { api_key_id: 7, channel_id: 9 }],
- { transaction: { id: 'transaction', LOCK: { UPDATE: 'UPDATE' } } }
+ { transaction: { id: 'transaction', LOCK: { UPDATE: 'UPDATE' } }, ignoreDuplicates: true }
);
});
@@ -76,6 +77,33 @@ describe('API key channel grants', () => {
}));
});
+ test('keeps grants on disabled or terminated channels when replacing the visible set', async () => {
+ ApiKey.findByPk.mockResolvedValue({ id: 7, role: 'view', is_active: true, revoked_at: null });
+ Channel.count.mockResolvedValue(1);
+ // The eligible-channel join hides the grant on disabled channel 5.
+ ApiKeyChannelGrant.findAll.mockResolvedValue([{ channel_id: 3 }]);
+
+ await grants.replaceChannelGrants(7, [9]);
+
+ expect(ApiKeyChannelGrant.findAll).toHaveBeenCalledWith(expect.objectContaining({
+ where: { api_key_id: 7 },
+ include: [expect.objectContaining({
+ where: { enabled: true, terminated_at: { [Op.is]: null } },
+ })],
+ }));
+ expect(ApiKeyChannelGrant.destroy).toHaveBeenCalledWith(expect.objectContaining({
+ where: { api_key_id: 7, channel_id: [3] },
+ }));
+ });
+
+ test('skips the delete when no visible grants exist', async () => {
+ ApiKey.findByPk.mockResolvedValue({ id: 7, role: 'view', is_active: true, revoked_at: null });
+ ApiKeyChannelGrant.findAll.mockResolvedValue([]);
+
+ await expect(grants.replaceChannelGrants(7, [])).resolves.toEqual({ keyId: 7, channelIds: [] });
+ expect(ApiKeyChannelGrant.destroy).not.toHaveBeenCalled();
+ });
+
test('rejects legacy keys before changing grants', async () => {
ApiKey.findByPk.mockResolvedValue({ id: 7, role: 'legacy_download', is_active: true, revoked_at: null });
await expect(grants.replaceChannelGrants(7, [3])).rejects.toThrow('Only active external API keys');
diff --git a/server/modules/externalApi/apiKeyChannelGrantModule.js b/server/modules/externalApi/apiKeyChannelGrantModule.js
index 89395c672..789877c68 100644
--- a/server/modules/externalApi/apiKeyChannelGrantModule.js
+++ b/server/modules/externalApi/apiKeyChannelGrantModule.js
@@ -28,23 +28,30 @@ async function requireExternalKey(keyId, transaction) {
return key;
}
-async function getChannelGrants(keyId) {
- const key = await requireExternalKey(keyId);
- if (!key) return null;
+const eligibleChannelInclude = () => [{
+ model: Channel,
+ as: 'channel',
+ attributes: [],
+ required: true,
+ where: { enabled: true, terminated_at: { [Op.is]: null } },
+}];
+
+async function findEligibleGrantChannelIds(keyId, transaction) {
const grants = await ApiKeyChannelGrant.findAll({
where: { api_key_id: keyId },
attributes: ['channel_id'],
- include: [{
- model: Channel,
- as: 'channel',
- attributes: [],
- required: true,
- where: { enabled: true, terminated_at: { [Op.is]: null } },
- }],
+ include: eligibleChannelInclude(),
order: [['channel_id', 'ASC']],
raw: true,
+ ...(transaction ? { transaction } : {}),
});
- return { keyId, channelIds: grants.map((grant) => grant.channel_id) };
+ return grants.map((grant) => grant.channel_id);
+}
+
+async function getChannelGrants(keyId) {
+ const key = await requireExternalKey(keyId);
+ if (!key) return null;
+ return { keyId, channelIds: await findEligibleGrantChannelIds(keyId) };
}
async function getEffectiveChannelGrantCounts(keyIds) {
@@ -52,13 +59,7 @@ async function getEffectiveChannelGrantCounts(keyIds) {
const grants = await ApiKeyChannelGrant.findAll({
where: { api_key_id: keyIds },
attributes: ['api_key_id'],
- include: [{
- model: Channel,
- as: 'channel',
- attributes: [],
- required: true,
- where: { enabled: true, terminated_at: { [Op.is]: null } },
- }],
+ include: eligibleChannelInclude(),
raw: true,
});
return grants.reduce((counts, grant) => {
@@ -83,11 +84,22 @@ async function replaceChannelGrants(keyId, channelIds, { transaction: existingTr
}
}
- await ApiKeyChannelGrant.destroy({ where: { api_key_id: keyId }, transaction });
+ // Only grants the editor can see are replaced. A grant on a disabled or
+ // terminated channel grants nothing while it stays that way, and is kept
+ // so the channel is approved again when it is turned back on.
+ const replaceableIds = await findEligibleGrantChannelIds(keyId, transaction);
+ if (replaceableIds.length > 0) {
+ await ApiKeyChannelGrant.destroy({
+ where: { api_key_id: keyId, channel_id: replaceableIds },
+ transaction,
+ });
+ }
if (normalized.length > 0) {
+ // A channel disabled since the eligibility check keeps its dormant
+ // grant, which would otherwise collide with the new row.
await ApiKeyChannelGrant.bulkCreate(
normalized.map((channelId) => ({ api_key_id: keyId, channel_id: channelId })),
- { transaction }
+ { transaction, ignoreDuplicates: true }
);
}
return { keyId, channelIds: normalized };
diff --git a/server/routes/apikeys.js b/server/routes/apikeys.js
index 66efd4820..6e019b975 100644
--- a/server/routes/apikeys.js
+++ b/server/routes/apikeys.js
@@ -321,6 +321,10 @@ module.exports = function createApiKeyRoutes({ verifyToken }) {
* type: array
* uniqueItems: true
* items: { type: integer, minimum: 1 }
+ * description: >
+ * Replaces the grants on enabled, non-terminated channels.
+ * Grants on disabled or terminated channels are kept and
+ * take effect again when the channel is enabled.
* responses:
* 200: { description: Policy and exact grant set committed }
* 400: { description: Invalid policy or channel grant set }