mirror of
https://github.com/kikootwo/ReadMeABook.git
synced 2026-06-03 04:40:09 +00:00
Add API tokens management, docs & UI
Introduce full API token support: add a Prisma migration to create api_tokens table and indexes; add types, constants and a generateApiToken utility (hashed token + prefix). Update admin and user token routes to use the generator, enforce per-user active token caps, and integrate rate-limit checks. Add an interactive API docs page with TokenInput, EndpointCard and ResponseViewer components, plus a protected page route. Improve confirmation UX with an accessible ConfirmDialog (focus trap, Escape to close, animations) and wire confirm flows into admin/profile token sections; also update ConfirmModal to accept node messages. Add dialog CSS animations and enhance clipboard error handling. Update related middleware, utils and tests to reflect changes.
This commit is contained in:
@@ -20,7 +20,9 @@ vi.mock('@/lib/utils/jwt', () => ({
|
||||
verifyAccessToken: verifyAccessTokenMock,
|
||||
}));
|
||||
|
||||
const makeRequest = (authHeader?: string) => ({
|
||||
const makeRequest = (authHeader?: string, pathname = '/api/requests', method = 'GET') => ({
|
||||
method,
|
||||
nextUrl: { pathname },
|
||||
headers: {
|
||||
get: (key: string) => {
|
||||
if (key.toLowerCase() === 'authorization') {
|
||||
@@ -231,7 +233,7 @@ describe('auth middleware', () => {
|
||||
expect(payload.message).toMatch(/invalid.*expired/i);
|
||||
});
|
||||
|
||||
it('accepts valid API tokens for active users', async () => {
|
||||
it('accepts valid API tokens for active users on allowed endpoints', async () => {
|
||||
prismaMock.apiToken.findUnique.mockResolvedValue({
|
||||
id: 'token-1',
|
||||
tokenHash: testTokenHash,
|
||||
@@ -250,12 +252,103 @@ describe('auth middleware', () => {
|
||||
const handler = vi.fn(async (req: any) =>
|
||||
NextResponse.json({ ok: true, userId: req.user?.id })
|
||||
);
|
||||
const response = await requireAuth(makeRequest(`Bearer ${testToken}`) as any, handler);
|
||||
const response = await requireAuth(
|
||||
makeRequest(`Bearer ${testToken}`, '/api/requests', 'GET') as any,
|
||||
handler
|
||||
);
|
||||
const payload = await response.json();
|
||||
|
||||
expect(handler).toHaveBeenCalled();
|
||||
expect(payload.userId).toBe('user-1');
|
||||
});
|
||||
|
||||
it('blocks API tokens on endpoints not in the allowlist', async () => {
|
||||
prismaMock.apiToken.findUnique.mockResolvedValue({
|
||||
id: 'token-1',
|
||||
tokenHash: testTokenHash,
|
||||
role: 'admin',
|
||||
expiresAt: null,
|
||||
tokenUser: {
|
||||
id: 'user-1',
|
||||
plexUsername: 'activeuser',
|
||||
role: 'admin',
|
||||
deletedAt: null,
|
||||
},
|
||||
});
|
||||
prismaMock.apiToken.update.mockResolvedValue({});
|
||||
const { requireAuth } = await import('@/lib/middleware/auth');
|
||||
|
||||
const handler = vi.fn();
|
||||
const response = await requireAuth(
|
||||
makeRequest(`Bearer ${testToken}`, '/api/admin/settings', 'GET') as any,
|
||||
handler
|
||||
);
|
||||
const payload = await response.json();
|
||||
|
||||
expect(handler).not.toHaveBeenCalled();
|
||||
expect(response.status).toBe(403);
|
||||
expect(payload.message).toMatch(/not available via API token/i);
|
||||
});
|
||||
|
||||
it('allows API tokens on all 5 permitted endpoints', async () => {
|
||||
const allowedPaths = [
|
||||
'/api/auth/me',
|
||||
'/api/requests',
|
||||
'/api/admin/metrics',
|
||||
'/api/admin/downloads/active',
|
||||
'/api/admin/requests/recent',
|
||||
];
|
||||
|
||||
for (const path of allowedPaths) {
|
||||
vi.clearAllMocks();
|
||||
prismaMock.apiToken.findUnique.mockResolvedValue({
|
||||
id: 'token-1',
|
||||
tokenHash: testTokenHash,
|
||||
role: 'admin',
|
||||
expiresAt: null,
|
||||
tokenUser: {
|
||||
id: 'user-1',
|
||||
plexUsername: 'activeuser',
|
||||
role: 'admin',
|
||||
deletedAt: null,
|
||||
},
|
||||
});
|
||||
prismaMock.apiToken.update.mockResolvedValue({});
|
||||
const { requireAuth } = await import('@/lib/middleware/auth');
|
||||
|
||||
const handler = vi.fn(async () => NextResponse.json({ ok: true }));
|
||||
const response = await requireAuth(
|
||||
makeRequest(`Bearer ${testToken}`, path, 'GET') as any,
|
||||
handler
|
||||
);
|
||||
|
||||
expect(handler).toHaveBeenCalled();
|
||||
expect(response.status).toBe(200);
|
||||
}
|
||||
});
|
||||
|
||||
it('does not restrict JWT-authenticated users to the allowlist', async () => {
|
||||
verifyAccessTokenMock.mockReturnValue({
|
||||
sub: 'user-1',
|
||||
plexId: 'plex-1',
|
||||
username: 'user',
|
||||
role: 'admin',
|
||||
iat: 1,
|
||||
exp: 2,
|
||||
});
|
||||
prismaMock.user.findUnique.mockResolvedValue({ id: 'user-1' });
|
||||
const { requireAuth } = await import('@/lib/middleware/auth');
|
||||
|
||||
const handler = vi.fn(async () => NextResponse.json({ ok: true }));
|
||||
// Use a non-allowlisted endpoint — JWT should still work
|
||||
const response = await requireAuth(
|
||||
makeRequest('Bearer jwttoken', '/api/admin/settings', 'POST') as any,
|
||||
handler
|
||||
);
|
||||
|
||||
expect(handler).toHaveBeenCalled();
|
||||
expect(response.status).toBe(200);
|
||||
});
|
||||
});
|
||||
|
||||
it('returns current user from token', async () => {
|
||||
|
||||
@@ -1,21 +1,26 @@
|
||||
/**
|
||||
* Component: API Token Rate Limit Tests
|
||||
* Documentation: documentation/backend/services/auth.md
|
||||
* Documentation: documentation/backend/services/api-tokens.md
|
||||
*/
|
||||
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import {
|
||||
checkApiTokenCreateRateLimit,
|
||||
checkApiTokenRevokeRateLimit,
|
||||
_resetBuckets,
|
||||
_getBucketCount,
|
||||
} from '@/lib/utils/apiTokenRateLimit';
|
||||
import { MAX_TOKENS_PER_USER } from '@/lib/constants/api-tokens';
|
||||
|
||||
describe('API Token Rate Limiting', () => {
|
||||
beforeEach(() => {
|
||||
vi.useFakeTimers();
|
||||
_resetBuckets();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.useRealTimers();
|
||||
_resetBuckets();
|
||||
});
|
||||
|
||||
describe('checkApiTokenCreateRateLimit', () => {
|
||||
@@ -119,4 +124,80 @@ describe('API Token Rate Limiting', () => {
|
||||
expect(result.retryAfterSeconds).toBeGreaterThan(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe('lazy eviction', () => {
|
||||
it('deletes expired buckets when they are next accessed', () => {
|
||||
const actorId = 'user-evict-1';
|
||||
|
||||
// Create a bucket
|
||||
checkApiTokenCreateRateLimit(actorId);
|
||||
expect(_getBucketCount()).toBe(1);
|
||||
|
||||
// Expire the window
|
||||
vi.advanceTimersByTime(61 * 1000);
|
||||
|
||||
// Accessing the same key should evict the old bucket and create a fresh one
|
||||
checkApiTokenCreateRateLimit(actorId);
|
||||
// Should still be 1 (old one deleted, new one created)
|
||||
expect(_getBucketCount()).toBe(1);
|
||||
});
|
||||
|
||||
it('does not delete buckets that are still active', () => {
|
||||
// Create buckets for two actors
|
||||
checkApiTokenCreateRateLimit('actor-a');
|
||||
checkApiTokenCreateRateLimit('actor-b');
|
||||
expect(_getBucketCount()).toBe(2);
|
||||
|
||||
// Advance partially (not past the 60s window)
|
||||
vi.advanceTimersByTime(30 * 1000);
|
||||
|
||||
// Both should still be there
|
||||
checkApiTokenCreateRateLimit('actor-a');
|
||||
expect(_getBucketCount()).toBe(2);
|
||||
});
|
||||
});
|
||||
|
||||
describe('periodic sweep', () => {
|
||||
it('sweeps all expired buckets every 100 checks', () => {
|
||||
// Create 10 unique actor buckets
|
||||
for (let i = 0; i < 10; i++) {
|
||||
checkApiTokenCreateRateLimit(`sweep-actor-${i}`);
|
||||
}
|
||||
expect(_getBucketCount()).toBe(10);
|
||||
|
||||
// Expire all windows
|
||||
vi.advanceTimersByTime(61 * 1000);
|
||||
|
||||
// Add some fresh buckets that should NOT be swept
|
||||
checkApiTokenCreateRateLimit('sweep-fresh-1');
|
||||
checkApiTokenCreateRateLimit('sweep-fresh-2');
|
||||
|
||||
// We've done 10 + 2 = 12 calls so far. Need 100 total to trigger sweep.
|
||||
// Do 88 more calls with unique actors to reach 100
|
||||
for (let i = 0; i < 88; i++) {
|
||||
checkApiTokenCreateRateLimit(`sweep-filler-${i}`);
|
||||
}
|
||||
|
||||
// After the 100th call, the sweep should have removed the 10 expired buckets.
|
||||
// Remaining: 2 fresh + 88 filler = 90
|
||||
expect(_getBucketCount()).toBe(90);
|
||||
});
|
||||
});
|
||||
|
||||
describe('_resetBuckets', () => {
|
||||
it('clears all buckets', () => {
|
||||
checkApiTokenCreateRateLimit('reset-1');
|
||||
checkApiTokenCreateRateLimit('reset-2');
|
||||
expect(_getBucketCount()).toBeGreaterThan(0);
|
||||
|
||||
_resetBuckets();
|
||||
expect(_getBucketCount()).toBe(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe('MAX_TOKENS_PER_USER constant', () => {
|
||||
it('is set to 25', () => {
|
||||
expect(MAX_TOKENS_PER_USER).toBe(25);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user