Add extensible notification providers + UI/API

Introduce a provider-based notification system and wire it through the API and admin UI. Added INotificationProvider + notification service implementation and providers (apprise, discord, ntfy, pushover), plus a GET /api/admin/notifications/providers endpoint to expose provider metadata. Refactored code to use provider type strings (removed enum coupling), updated masking/encryption calls, and simplified the test notification endpoint to accept backendId or type+config and call sendToBackend directly.

UI: NotificationsTab now fetches provider metadata and renders provider cards and dynamic config forms (fields driven by provider metadata). Added config field rendering, improved backend cards, and edit/delete actions.

APIs: New providers route, updated admin notification CRUD routes to validate provider types dynamically, updated test route schema. Added download-client categories POST API to fetch categories from clients and wired postImportCategory handling in download-client routes.

Other notable changes: BookDate now fetches Claude models dynamically from Anthropic's Models API; added paginated model fetch helper. Added ALLOW_WEAK_PASSWORD flag exposure to auth providers and password change logic. Doc updates and various tests added/updated. File-organization doc clarifies EPERM fix using stream-based copy.
This commit is contained in:
kikootwo
2026-02-10 15:06:20 -05:00
parent 4a38dd3da8
commit af0eaceb98
73 changed files with 3421 additions and 866 deletions
@@ -30,8 +30,9 @@ vi.mock('@/lib/middleware/auth', () => ({
requireAdmin: requireAdminMock,
}));
vi.mock('@/lib/services/notification.service', () => ({
vi.mock('@/lib/services/notification', () => ({
getNotificationService: () => notificationServiceMock,
getRegisteredProviderTypes: () => ['discord', 'ntfy', 'pushover'],
}));
describe('Admin notifications test route', () => {
+2 -1
View File
@@ -35,8 +35,9 @@ vi.mock('@/lib/middleware/auth', () => ({
requireAdmin: requireAdminMock,
}));
vi.mock('@/lib/services/notification.service', () => ({
vi.mock('@/lib/services/notification', () => ({
getNotificationService: () => notificationServiceMock,
getRegisteredProviderTypes: () => ['discord', 'ntfy', 'pushover'],
}));
describe('Admin notifications routes', () => {
+2 -1
View File
@@ -13,6 +13,7 @@ const configServiceMock = vi.hoisted(() => ({
}));
const prowlarrMock = vi.hoisted(() => ({
search: vi.fn(),
searchWithVariations: vi.fn(),
}));
const rankTorrentsMock = vi.hoisted(() => vi.fn());
const groupIndexersMock = vi.hoisted(() => vi.fn());
@@ -68,7 +69,7 @@ describe('Audiobooks search torrents route', () => {
.mockResolvedValueOnce(null);
groupIndexersMock.mockReturnValue({ groups: [{ categories: [1], indexerIds: [1] }], skippedIndexers: [] });
prowlarrMock.search.mockResolvedValue([{ title: 'Result', size: 100, indexer: 'Indexer', indexerId: 1 }]);
prowlarrMock.searchWithVariations.mockResolvedValue([{ title: 'Result', size: 100, indexer: 'Indexer', indexerId: 1 }]);
rankTorrentsMock.mockReturnValue([
{
title: 'Result',
@@ -68,6 +68,32 @@ describe('Change password route', () => {
expect(payload.error).toMatch(/at least 8 characters/i);
});
it('allows short passwords when ALLOW_WEAK_PASSWORD is enabled', async () => {
process.env.ALLOW_WEAK_PASSWORD = 'true';
prismaMock.user.findUnique.mockResolvedValue({
id: 'user-1',
authProvider: 'local',
authToken: 'enc-hash',
plexId: 'local-user',
plexUsername: 'user',
});
encryptionMock.decrypt.mockReturnValue('hash');
bcryptMock.compare.mockResolvedValue(true);
bcryptMock.hash.mockResolvedValue('new-hash');
encryptionMock.encrypt.mockReturnValue('enc-new-hash');
prismaMock.user.update.mockResolvedValue({});
const { POST } = await import('@/app/api/auth/change-password/route');
const response = await POST(
makeRequest({ currentPassword: 'oldpass', newPassword: 'ab', confirmPassword: 'ab' }) as any
);
const payload = await response.json();
expect(response.status).toBe(200);
expect(payload.success).toBe(true);
delete process.env.ALLOW_WEAK_PASSWORD;
});
it('blocks non-local users', async () => {
prismaMock.user.findUnique.mockResolvedValue({
id: 'user-1',
@@ -149,6 +149,15 @@ describe('BookDate test connection route', () => {
it('returns Claude models for unauthenticated requests', async () => {
const fetchMock = vi.fn().mockResolvedValue({
ok: true,
json: vi.fn().mockResolvedValue({
data: [
{ id: 'claude-sonnet-4-5-20250929', display_name: 'Claude Sonnet 4.5', type: 'model', created_at: '2025-09-29T00:00:00Z' },
{ id: 'claude-haiku-4-5-20251001', display_name: 'Claude Haiku 4.5', type: 'model', created_at: '2025-10-01T00:00:00Z' },
],
has_more: false,
first_id: 'claude-sonnet-4-5-20250929',
last_id: 'claude-haiku-4-5-20251001',
}),
text: vi.fn().mockResolvedValue('ok'),
});
vi.stubGlobal('fetch', fetchMock);
@@ -161,7 +170,142 @@ describe('BookDate test connection route', () => {
const payload = await response.json();
expect(payload.success).toBe(true);
expect(payload.models.length).toBe(4);
expect(payload.models).toEqual([
{ id: 'claude-sonnet-4-5-20250929', name: 'Claude Sonnet 4.5' },
{ id: 'claude-haiku-4-5-20251001', name: 'Claude Haiku 4.5' },
]);
expect(fetchMock).toHaveBeenCalledWith(
expect.stringContaining('https://api.anthropic.com/v1/models'),
expect.objectContaining({
headers: expect.objectContaining({ 'x-api-key': 'key' }),
})
);
});
it('returns Claude models for authenticated requests', async () => {
requireAuthMock.mockImplementation((_req: any, handler: any) => handler(_req));
const fetchMock = vi.fn().mockResolvedValue({
ok: true,
json: vi.fn().mockResolvedValue({
data: [
{ id: 'claude-opus-4-20250514', display_name: 'Claude Opus 4', type: 'model', created_at: '2025-05-14T00:00:00Z' },
],
has_more: false,
first_id: 'claude-opus-4-20250514',
last_id: 'claude-opus-4-20250514',
}),
text: vi.fn().mockResolvedValue('ok'),
});
vi.stubGlobal('fetch', fetchMock);
const { POST } = await import('@/app/api/bookdate/test-connection/route');
const response = await POST({
headers: { get: () => 'Bearer token' },
json: vi.fn().mockResolvedValue({ provider: 'claude', apiKey: 'key' }),
} as any);
const payload = await response.json();
expect(payload.success).toBe(true);
expect(payload.models).toEqual([
{ id: 'claude-opus-4-20250514', name: 'Claude Opus 4' },
]);
});
it('returns error for invalid Claude API key', async () => {
const fetchMock = vi.fn().mockResolvedValue({
ok: false,
text: vi.fn().mockResolvedValue('{"type":"error","error":{"type":"authentication_error","message":"invalid x-api-key"}}'),
});
vi.stubGlobal('fetch', fetchMock);
const { POST } = await import('@/app/api/bookdate/test-connection/route');
const response = await POST({
headers: { get: () => null },
json: vi.fn().mockResolvedValue({ provider: 'claude', apiKey: 'bad-key' }),
} as any);
const payload = await response.json();
expect(response.status).toBe(400);
expect(payload.error).toMatch(/Invalid Claude API key/i);
});
it('paginates through Claude models when has_more is true', async () => {
let callCount = 0;
const fetchMock = vi.fn().mockImplementation(() => {
callCount++;
if (callCount === 1) {
return Promise.resolve({
ok: true,
json: vi.fn().mockResolvedValue({
data: [
{ id: 'claude-sonnet-4-5-20250929', display_name: 'Claude Sonnet 4.5', type: 'model', created_at: '2025-09-29T00:00:00Z' },
],
has_more: true,
first_id: 'claude-sonnet-4-5-20250929',
last_id: 'claude-sonnet-4-5-20250929',
}),
text: vi.fn().mockResolvedValue('ok'),
});
}
return Promise.resolve({
ok: true,
json: vi.fn().mockResolvedValue({
data: [
{ id: 'claude-haiku-4-5-20251001', display_name: 'Claude Haiku 4.5', type: 'model', created_at: '2025-10-01T00:00:00Z' },
],
has_more: false,
first_id: 'claude-haiku-4-5-20251001',
last_id: 'claude-haiku-4-5-20251001',
}),
text: vi.fn().mockResolvedValue('ok'),
});
});
vi.stubGlobal('fetch', fetchMock);
const { POST } = await import('@/app/api/bookdate/test-connection/route');
const response = await POST({
headers: { get: () => null },
json: vi.fn().mockResolvedValue({ provider: 'claude', apiKey: 'key' }),
} as any);
const payload = await response.json();
expect(payload.success).toBe(true);
expect(payload.models).toEqual([
{ id: 'claude-sonnet-4-5-20250929', name: 'Claude Sonnet 4.5' },
{ id: 'claude-haiku-4-5-20251001', name: 'Claude Haiku 4.5' },
]);
expect(fetchMock).toHaveBeenCalledTimes(2);
// Second call should include after_id for pagination
expect(fetchMock.mock.calls[1][0]).toContain('after_id=claude-sonnet-4-5-20250929');
});
it('falls back to model id when display_name is missing', async () => {
const fetchMock = vi.fn().mockResolvedValue({
ok: true,
json: vi.fn().mockResolvedValue({
data: [
{ id: 'claude-test-model', type: 'model', created_at: '2025-01-01T00:00:00Z' },
],
has_more: false,
first_id: 'claude-test-model',
last_id: 'claude-test-model',
}),
text: vi.fn().mockResolvedValue('ok'),
});
vi.stubGlobal('fetch', fetchMock);
const { POST } = await import('@/app/api/bookdate/test-connection/route');
const response = await POST({
headers: { get: () => null },
json: vi.fn().mockResolvedValue({ provider: 'claude', apiKey: 'key' }),
} as any);
const payload = await response.json();
expect(payload.success).toBe(true);
expect(payload.models).toEqual([
{ id: 'claude-test-model', name: 'claude-test-model' },
]);
});
it('returns OpenAI error for unauthenticated requests with invalid key', async () => {
+93 -6
View File
@@ -10,9 +10,11 @@ let authRequest: any;
const prismaMock = createPrismaMock();
const requireAuthMock = vi.hoisted(() => vi.fn());
const prowlarrMock = vi.hoisted(() => ({ search: vi.fn() }));
const prowlarrMock = vi.hoisted(() => ({ search: vi.fn(), searchWithVariations: vi.fn() }));
const rankTorrentsMock = vi.hoisted(() => vi.fn());
const configServiceMock = vi.hoisted(() => ({ get: vi.fn() }));
const groupIndexersMock = vi.hoisted(() => vi.fn());
const groupDescriptionMock = vi.hoisted(() => vi.fn(() => 'Group'));
const configState = vi.hoisted(() => ({
values: new Map<string, string>(),
}));
@@ -23,6 +25,9 @@ const jobQueueMock = vi.hoisted(() => ({
addSearchEbookJob: vi.fn(() => Promise.resolve()),
}));
const downloadEbookMock = vi.hoisted(() => vi.fn());
const audibleServiceMock = vi.hoisted(() => ({
getRuntime: vi.fn(),
}));
const fsMock = vi.hoisted(() => ({
access: vi.fn(),
}));
@@ -44,6 +49,11 @@ vi.mock('@/lib/utils/ranking-algorithm', () => ({
rankTorrents: rankTorrentsMock,
}));
vi.mock('@/lib/utils/indexer-grouping', () => ({
groupIndexersByCategories: groupIndexersMock,
getGroupDescription: groupDescriptionMock,
}));
vi.mock('@/lib/services/config.service', () => ({
getConfigService: () => configServiceMock,
}));
@@ -56,6 +66,10 @@ vi.mock('@/lib/services/ebook-scraper', () => ({
downloadEbook: downloadEbookMock,
}));
vi.mock('@/lib/integrations/audible.service', () => ({
getAudibleService: () => audibleServiceMock,
}));
vi.mock('fs/promises', () => ({ default: fsMock, ...fsMock, constants: { R_OK: 4 } }));
describe('Request action routes', () => {
@@ -72,22 +86,24 @@ describe('Request action routes', () => {
);
});
it('performs interactive search and ranks results', async () => {
it('performs interactive search and ranks results with runtime from ASIN', async () => {
authRequest.json.mockResolvedValue({});
prismaMock.request.findUnique.mockResolvedValueOnce({
id: 'req-1',
userId: 'user-1',
audiobook: { title: 'Title', author: 'Author' },
audiobook: { title: 'Title', author: 'Author', audibleAsin: 'B00ASIN123' },
});
prismaMock.user.findUnique.mockResolvedValueOnce({
role: 'user',
interactiveSearchAccess: null,
});
configServiceMock.get.mockResolvedValueOnce(JSON.stringify([{ id: 1, priority: 10 }]));
configServiceMock.get.mockResolvedValueOnce(JSON.stringify([{ id: 1, priority: 10, categories: [3030] }]));
configServiceMock.get.mockResolvedValueOnce(null);
prowlarrMock.search.mockResolvedValueOnce([{ title: 'Result', size: 100 }]);
groupIndexersMock.mockReturnValue({ groups: [{ categories: [3030], indexerIds: [1] }], skippedIndexers: [] });
prowlarrMock.searchWithVariations.mockResolvedValueOnce([{ title: 'Result', size: 500 * 1024 * 1024 }]);
audibleServiceMock.getRuntime.mockResolvedValueOnce(600);
rankTorrentsMock.mockReturnValueOnce([
{ title: 'Result', score: 50, breakdown: { matchScore: 50, formatScore: 0, seederScore: 0, notes: [] }, bonusPoints: 0, bonusModifiers: [], finalScore: 50 },
{ title: 'Result', size: 500 * 1024 * 1024, score: 50, breakdown: { matchScore: 50, formatScore: 0, sizeScore: 12, seederScore: 0, notes: [] }, bonusPoints: 0, bonusModifiers: [], finalScore: 62 },
]);
const { POST } = await import('@/app/api/requests/[id]/interactive-search/route');
@@ -96,6 +112,77 @@ describe('Request action routes', () => {
expect(payload.success).toBe(true);
expect(payload.results[0].rank).toBe(1);
expect(audibleServiceMock.getRuntime).toHaveBeenCalledWith('B00ASIN123');
expect(rankTorrentsMock).toHaveBeenCalledWith(
expect.any(Array),
expect.objectContaining({ title: 'Title', author: 'Author', durationMinutes: 600 }),
expect.any(Object)
);
});
it('performs interactive search without runtime when no ASIN', async () => {
authRequest.json.mockResolvedValue({});
prismaMock.request.findUnique.mockResolvedValueOnce({
id: 'req-1b',
userId: 'user-1',
audiobook: { title: 'Title', author: 'Author', audibleAsin: null },
});
prismaMock.user.findUnique.mockResolvedValueOnce({
role: 'user',
interactiveSearchAccess: null,
});
configServiceMock.get.mockResolvedValueOnce(JSON.stringify([{ id: 1, priority: 10, categories: [3030] }]));
configServiceMock.get.mockResolvedValueOnce(null);
groupIndexersMock.mockReturnValue({ groups: [{ categories: [3030], indexerIds: [1] }], skippedIndexers: [] });
prowlarrMock.searchWithVariations.mockResolvedValueOnce([{ title: 'Result', size: 100 }]);
rankTorrentsMock.mockReturnValueOnce([
{ title: 'Result', size: 100, score: 50, breakdown: { matchScore: 50, formatScore: 0, sizeScore: 0, seederScore: 0, notes: [] }, bonusPoints: 0, bonusModifiers: [], finalScore: 50 },
]);
const { POST } = await import('@/app/api/requests/[id]/interactive-search/route');
const response = await POST({} as any, { params: Promise.resolve({ id: 'req-1b' }) });
const payload = await response.json();
expect(payload.success).toBe(true);
expect(audibleServiceMock.getRuntime).not.toHaveBeenCalled();
expect(rankTorrentsMock).toHaveBeenCalledWith(
expect.any(Array),
expect.objectContaining({ title: 'Title', author: 'Author', durationMinutes: undefined }),
expect.any(Object)
);
});
it('performs interactive search gracefully when runtime fetch fails', async () => {
authRequest.json.mockResolvedValue({});
prismaMock.request.findUnique.mockResolvedValueOnce({
id: 'req-1c',
userId: 'user-1',
audiobook: { title: 'Title', author: 'Author', audibleAsin: 'B00FAIL' },
});
prismaMock.user.findUnique.mockResolvedValueOnce({
role: 'user',
interactiveSearchAccess: null,
});
configServiceMock.get.mockResolvedValueOnce(JSON.stringify([{ id: 1, priority: 10, categories: [3030] }]));
configServiceMock.get.mockResolvedValueOnce(null);
groupIndexersMock.mockReturnValue({ groups: [{ categories: [3030], indexerIds: [1] }], skippedIndexers: [] });
prowlarrMock.searchWithVariations.mockResolvedValueOnce([{ title: 'Result', size: 100 }]);
audibleServiceMock.getRuntime.mockRejectedValueOnce(new Error('Network error'));
rankTorrentsMock.mockReturnValueOnce([
{ title: 'Result', size: 100, score: 50, breakdown: { matchScore: 50, formatScore: 0, sizeScore: 0, seederScore: 0, notes: [] }, bonusPoints: 0, bonusModifiers: [], finalScore: 50 },
]);
const { POST } = await import('@/app/api/requests/[id]/interactive-search/route');
const response = await POST({} as any, { params: Promise.resolve({ id: 'req-1c' }) });
const payload = await response.json();
expect(payload.success).toBe(true);
expect(payload.results).toHaveLength(1);
expect(rankTorrentsMock).toHaveBeenCalledWith(
expect.any(Array),
expect.objectContaining({ durationMinutes: undefined }),
expect.any(Object)
);
});
it('triggers manual search job', async () => {
@@ -24,6 +24,7 @@ const AudiobookshelfHarness = ({
absApiToken: 'token',
absLibraryId: '',
absTriggerScanAfterImport: false,
absLibraries: [] as { id: string; name: string; itemCount: number }[],
...initialState,
});
+1
View File
@@ -24,6 +24,7 @@ const PlexHarness = ({
plexToken: 'token',
plexLibraryId: '',
plexTriggerScanAfterImport: false,
plexLibraries: [] as { id: string; title: string; type: string }[],
...initialState,
});
+120 -5
View File
@@ -100,8 +100,8 @@ describe('substituteTemplate', () => {
expect(result).toBe('Author/Title/Narrator');
});
it('should handle mixed forward and backward slashes', () => {
const template = '{author}\\{title}/{narrator}';
it('should resolve escaped braces to literal brace characters', () => {
const template = '{author}/\\{{narrator}\\}/{title}';
const variables: TemplateVariables = {
author: 'Author',
title: 'Title',
@@ -109,7 +109,7 @@ describe('substituteTemplate', () => {
};
const result = substituteTemplate(template, variables);
expect(result).toBe('Author/Title/Narrator');
expect(result).toBe('Author/{Narrator}/Title');
});
it('should trim dots from path components', () => {
@@ -145,6 +145,74 @@ describe('substituteTemplate', () => {
const result = substituteTemplate(template, variables);
expect(result).toBe('Audiobooks/Author/Books/Title');
});
it('should resolve escaped left brace only', () => {
const template = '{author}/\\{prefix {title}';
const variables: TemplateVariables = {
author: 'Author',
title: 'Title'
};
const result = substituteTemplate(template, variables);
expect(result).toBe('Author/{prefix Title');
});
it('should resolve escaped right brace only', () => {
const template = '{author}/{title} suffix\\}';
const variables: TemplateVariables = {
author: 'Author',
title: 'Title'
};
const result = substituteTemplate(template, variables);
expect(result).toBe('Author/Title suffix}');
});
it('should resolve multiple escaped brace pairs', () => {
const template = '\\{{author}\\}/\\{{title}\\}';
const variables: TemplateVariables = {
author: 'Author',
title: 'Title'
};
const result = substituteTemplate(template, variables);
expect(result).toBe('{Author}/{Title}');
});
it('should handle escaped braces with missing optional variable', () => {
const template = '{author}/\\{{narrator}\\}/{title}';
const variables: TemplateVariables = {
author: 'Author',
title: 'Title'
// narrator is missing
};
const result = substituteTemplate(template, variables);
expect(result).toBe('Author/{}/Title');
});
it('should handle escaped braces adjacent to path separators', () => {
const template = '{author}/\\{{narrator}\\}/{title}';
const variables: TemplateVariables = {
author: 'Author',
title: 'Title',
narrator: 'Michael Kramer'
};
const result = substituteTemplate(template, variables);
expect(result).toBe('Author/{Michael Kramer}/Title');
});
it('should handle escaped braces around static text', () => {
const template = '{author}/\\{narrated\\}/{title}';
const variables: TemplateVariables = {
author: 'Author',
title: 'Title'
};
const result = substituteTemplate(template, variables);
expect(result).toBe('Author/{narrated}/Title');
});
});
describe('validateTemplate', () => {
@@ -205,8 +273,8 @@ describe('validateTemplate', () => {
});
});
it('should reject backslashes in template', () => {
const result = validateTemplate('{author}\\{title}');
it('should reject backslashes that are not brace escapes', () => {
const result = validateTemplate('{author}\\n{title}');
expect(result.valid).toBe(false);
expect(result.error).toContain('forward slashes');
});
@@ -230,6 +298,42 @@ describe('validateTemplate', () => {
expect(result.error).toContain('{narrator}');
expect(result.error).toContain('{asin}');
});
it('should accept escaped braces around a variable', () => {
const result = validateTemplate('{author}/\\{{narrator}\\}/{title}');
expect(result.valid).toBe(true);
});
it('should accept escaped braces around static text', () => {
const result = validateTemplate('{author}/\\{custom\\}/{title}');
expect(result.valid).toBe(true);
});
it('should accept escaped left brace only', () => {
const result = validateTemplate('{author}/\\{prefix {title}');
expect(result.valid).toBe(true);
});
it('should accept escaped right brace only', () => {
const result = validateTemplate('{author}/{title} suffix\\}');
expect(result.valid).toBe(true);
});
it('should accept multiple escaped brace pairs', () => {
const result = validateTemplate('\\{{author}\\}/\\{{title}\\}');
expect(result.valid).toBe(true);
});
it('should accept backslash before brace but reject backslash before other characters', () => {
const result = validateTemplate('{author}\\n/\\{{title}\\}');
expect(result.valid).toBe(false);
expect(result.error).toContain('forward slashes');
});
it('should accept a template that is only escaped braces', () => {
const result = validateTemplate('\\{\\}');
expect(result.valid).toBe(true);
});
});
describe('generateMockPreviews', () => {
@@ -305,6 +409,17 @@ describe('generateMockPreviews', () => {
expect(preview).toContain(' - B');
});
});
it('should resolve escaped braces in previews', () => {
const template = '{author}/\\{{narrator}\\}/{title}';
const previews = generateMockPreviews(template);
// First two mock entries have narrators
expect(previews[0]).toContain('{Michael Kramer}');
expect(previews[1]).toContain('{Stephen Fry}');
// Third mock entry has no narrator - escaped braces remain empty
expect(previews[2]).toContain('{}');
});
});
describe('getValidVariables', () => {
@@ -10,7 +10,7 @@ import { createJobQueueMock } from '../helpers/job-queue';
const prismaMock = createPrismaMock();
const configMock = vi.hoisted(() => ({ get: vi.fn() }));
const jobQueueMock = createJobQueueMock();
const prowlarrMock = vi.hoisted(() => ({ search: vi.fn() }));
const prowlarrMock = vi.hoisted(() => ({ search: vi.fn(), searchWithVariations: vi.fn() }));
vi.mock('@/lib/db', () => ({
prisma: prismaMock,
@@ -44,7 +44,7 @@ describe('processSearchIndexers', () => {
}
return null;
});
prowlarrMock.search.mockResolvedValue([]);
prowlarrMock.searchWithVariations.mockResolvedValue([]);
prismaMock.request.update.mockResolvedValue({});
const { processSearchIndexers } = await import('@/lib/processors/search-indexers.processor');
@@ -73,7 +73,7 @@ describe('processSearchIndexers', () => {
return null;
});
prowlarrMock.search.mockResolvedValue([
prowlarrMock.searchWithVariations.mockResolvedValue([
{
indexer: 'Indexer',
indexerId: 1,
@@ -9,7 +9,7 @@ const notificationServiceMock = vi.hoisted(() => ({
sendNotification: vi.fn(),
}));
vi.mock('@/lib/services/notification.service', () => ({
vi.mock('@/lib/services/notification', () => ({
getNotificationService: () => notificationServiceMock,
}));
+473
View File
@@ -0,0 +1,473 @@
/**
* Component: Apprise Notification Provider Tests
* Documentation: documentation/backend/services/notifications.md
*/
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { createPrismaMock } from '../helpers/prisma';
const prismaMock = createPrismaMock();
prismaMock.notificationBackend = {
findMany: vi.fn(),
findUnique: vi.fn(),
create: vi.fn(),
update: vi.fn(),
delete: vi.fn(),
} as any;
const encryptionMock = vi.hoisted(() => ({
encrypt: vi.fn((value: string) => `enc:${value}`),
decrypt: vi.fn((value: string) => value.replace('enc:', '')),
}));
const fetchMock = vi.hoisted(() => vi.fn());
vi.mock('@/lib/db', () => ({
prisma: prismaMock,
}));
vi.mock('@/lib/services/encryption.service', () => ({
getEncryptionService: () => encryptionMock,
}));
describe('AppriseProvider', () => {
beforeEach(() => {
vi.clearAllMocks();
vi.stubGlobal('fetch', fetchMock);
});
describe('send — stateless mode (urls)', () => {
it('sends notification to correct Apprise endpoint with JSON body', async () => {
fetchMock.mockResolvedValue({
ok: true,
text: async () => 'ok',
});
const { AppriseProvider } = await import('@/lib/services/notification');
const provider = new AppriseProvider();
await provider.send(
{
serverUrl: 'http://apprise:8000',
urls: 'slack://tokenA/tokenB/tokenC',
authToken: 'mytoken123',
},
{
event: 'request_approved',
requestId: 'req-1',
title: 'Test Book',
author: 'Test Author',
userName: 'Test User',
timestamp: new Date('2024-01-01T00:00:00Z'),
}
);
expect(fetchMock).toHaveBeenCalledTimes(1);
const fetchCall = fetchMock.mock.calls[0];
expect(fetchCall[0]).toBe('http://apprise:8000/notify/');
expect(fetchCall[1].method).toBe('POST');
expect(fetchCall[1].headers['Content-Type']).toBe('application/json');
expect(fetchCall[1].headers['Authorization']).toBe('Bearer mytoken123');
const body = JSON.parse(fetchCall[1].body);
expect(body.urls).toBe('slack://tokenA/tokenB/tokenC');
expect(body.title).toBe('Request Approved');
expect(body.body).toContain('Test Book');
expect(body.body).toContain('Test Author');
expect(body.body).toContain('Test User');
expect(body.type).toBe('success');
});
it('strips trailing slashes from server URL', async () => {
fetchMock.mockResolvedValue({
ok: true,
text: async () => 'ok',
});
const { AppriseProvider } = await import('@/lib/services/notification');
const provider = new AppriseProvider();
await provider.send(
{ serverUrl: 'http://apprise:8000/', urls: 'slack://token' },
{
event: 'request_approved',
requestId: 'req-1',
title: 'Test Book',
author: 'Test Author',
userName: 'Test User',
timestamp: new Date(),
}
);
const fetchCall = fetchMock.mock.calls[0];
expect(fetchCall[0]).toBe('http://apprise:8000/notify/');
});
it('does not include Authorization header when authToken is not provided', async () => {
fetchMock.mockResolvedValue({
ok: true,
text: async () => 'ok',
});
const { AppriseProvider } = await import('@/lib/services/notification');
const provider = new AppriseProvider();
await provider.send(
{ serverUrl: 'http://apprise:8000', urls: 'slack://token' },
{
event: 'request_approved',
requestId: 'req-1',
title: 'Test Book',
author: 'Test Author',
userName: 'Test User',
timestamp: new Date(),
}
);
const fetchCall = fetchMock.mock.calls[0];
expect(fetchCall[1].headers['Authorization']).toBeUndefined();
});
it('throws error when neither urls nor configKey is provided', async () => {
const { AppriseProvider } = await import('@/lib/services/notification');
const provider = new AppriseProvider();
await expect(
provider.send(
{ serverUrl: 'http://apprise:8000' },
{
event: 'request_approved',
requestId: 'req-1',
title: 'Test Book',
author: 'Test Author',
userName: 'Test User',
timestamp: new Date(),
}
)
).rejects.toThrow('Apprise requires either notification URLs or a config key');
});
});
describe('send — stateful mode (configKey)', () => {
it('sends notification to configKey endpoint', async () => {
fetchMock.mockResolvedValue({
ok: true,
text: async () => 'ok',
});
const { AppriseProvider } = await import('@/lib/services/notification');
const provider = new AppriseProvider();
await provider.send(
{
serverUrl: 'http://apprise:8000',
configKey: 'my-config',
tag: 'audiobooks',
},
{
event: 'request_available',
requestId: 'req-1',
title: 'Test Book',
author: 'Test Author',
userName: 'Test User',
timestamp: new Date(),
}
);
expect(fetchMock).toHaveBeenCalledTimes(1);
const fetchCall = fetchMock.mock.calls[0];
expect(fetchCall[0]).toBe('http://apprise:8000/notify/my-config');
const body = JSON.parse(fetchCall[1].body);
expect(body.tag).toBe('audiobooks');
expect(body.title).toBe('Audiobook Available');
expect(body.body).toContain('Test Book');
expect(body.type).toBe('success');
});
it('omits tag from body when not provided', async () => {
fetchMock.mockResolvedValue({
ok: true,
text: async () => 'ok',
});
const { AppriseProvider } = await import('@/lib/services/notification');
const provider = new AppriseProvider();
await provider.send(
{ serverUrl: 'http://apprise:8000', configKey: 'my-config' },
{
event: 'request_approved',
requestId: 'req-1',
title: 'Test Book',
author: 'Test Author',
userName: 'Test User',
timestamp: new Date(),
}
);
const body = JSON.parse(fetchMock.mock.calls[0][1].body);
expect(body.tag).toBeUndefined();
});
it('prefers configKey over urls when both are provided', async () => {
fetchMock.mockResolvedValue({
ok: true,
text: async () => 'ok',
});
const { AppriseProvider } = await import('@/lib/services/notification');
const provider = new AppriseProvider();
await provider.send(
{
serverUrl: 'http://apprise:8000',
configKey: 'my-config',
urls: 'slack://token',
},
{
event: 'request_approved',
requestId: 'req-1',
title: 'Test Book',
author: 'Test Author',
userName: 'Test User',
timestamp: new Date(),
}
);
const fetchCall = fetchMock.mock.calls[0];
expect(fetchCall[0]).toBe('http://apprise:8000/notify/my-config');
const body = JSON.parse(fetchCall[1].body);
expect(body.urls).toBeUndefined();
});
});
describe('notification types by event', () => {
it('maps event types to correct Apprise notification types', async () => {
fetchMock.mockResolvedValue({
ok: true,
text: async () => 'ok',
});
const { AppriseProvider } = await import('@/lib/services/notification');
const provider = new AppriseProvider();
const events = [
{ event: 'request_pending_approval', expectedType: 'info' },
{ event: 'request_approved', expectedType: 'success' },
{ event: 'request_available', expectedType: 'success' },
{ event: 'request_error', expectedType: 'failure' },
] as const;
for (const { event, expectedType } of events) {
fetchMock.mockClear();
await provider.send(
{ serverUrl: 'http://apprise:8000', urls: 'slack://token' },
{
event,
requestId: 'req-1',
title: 'Test Book',
author: 'Test Author',
userName: 'Test User',
timestamp: new Date(),
}
);
const body = JSON.parse(fetchMock.mock.calls[0][1].body);
expect(body.type).toBe(expectedType);
}
});
});
describe('error handling', () => {
it('throws descriptive error when API returns non-OK response', async () => {
fetchMock.mockResolvedValue({
ok: false,
status: 500,
text: async () => 'Internal Server Error',
});
const { AppriseProvider } = await import('@/lib/services/notification');
const provider = new AppriseProvider();
await expect(
provider.send(
{ serverUrl: 'http://apprise:8000', urls: 'slack://token' },
{
event: 'request_approved',
requestId: 'req-1',
title: 'Test Book',
author: 'Test Author',
userName: 'Test User',
timestamp: new Date(),
}
)
).rejects.toThrow('Apprise API failed: 500 Internal Server Error');
});
it('throws descriptive error on stateful mode failure', async () => {
fetchMock.mockResolvedValue({
ok: false,
status: 424,
text: async () => 'No recipients',
});
const { AppriseProvider } = await import('@/lib/services/notification');
const provider = new AppriseProvider();
await expect(
provider.send(
{ serverUrl: 'http://apprise:8000', configKey: 'bad-key' },
{
event: 'request_approved',
requestId: 'req-1',
title: 'Test Book',
author: 'Test Author',
userName: 'Test User',
timestamp: new Date(),
}
)
).rejects.toThrow('Apprise API failed: 424 No recipients');
});
it('includes error message in notification body for error events', async () => {
fetchMock.mockResolvedValue({
ok: true,
text: async () => 'ok',
});
const { AppriseProvider } = await import('@/lib/services/notification');
const provider = new AppriseProvider();
await provider.send(
{ serverUrl: 'http://apprise:8000', urls: 'slack://token' },
{
event: 'request_error',
requestId: 'req-1',
title: 'Test Book',
author: 'Test Author',
userName: 'Test User',
message: 'Download timed out',
timestamp: new Date(),
}
);
const body = JSON.parse(fetchMock.mock.calls[0][1].body);
expect(body.body).toContain('⚠️ Error: Download timed out');
expect(body.type).toBe('failure');
});
});
describe('integration with NotificationService.sendToBackend', () => {
it('decrypts sensitive fields and sends to Apprise', async () => {
fetchMock.mockResolvedValue({
ok: true,
text: async () => 'ok',
});
const { NotificationService } = await import('@/lib/services/notification');
const service = new NotificationService();
// Use iv:authTag:data format to pass isEncrypted() check
// Note: the value must have exactly 3 colon-separated segments
await service.sendToBackend(
'apprise',
{
serverUrl: 'http://apprise:8000',
urls: 'iv:tag:encryptedUrlsData',
authToken: 'iv:tag:mytoken123',
},
{
event: 'request_approved',
requestId: 'req-1',
title: 'Test Book',
author: 'Test Author',
userName: 'Test User',
timestamp: new Date(),
}
);
// Verify decrypt was called for the sensitive fields
expect(encryptionMock.decrypt).toHaveBeenCalledWith('iv:tag:encryptedUrlsData');
expect(encryptionMock.decrypt).toHaveBeenCalledWith('iv:tag:mytoken123');
// Verify the decrypted values reach the fetch call
expect(fetchMock).toHaveBeenCalledTimes(1);
const fetchCall = fetchMock.mock.calls[0];
expect(fetchCall[1].headers['Authorization']).toBe('Bearer iv:tag:mytoken123');
const body = JSON.parse(fetchCall[1].body);
expect(body.urls).toBe('iv:tag:encryptedUrlsData');
});
it('does not decrypt non-sensitive fields', async () => {
fetchMock.mockResolvedValue({
ok: true,
text: async () => 'ok',
});
const { NotificationService } = await import('@/lib/services/notification');
const service = new NotificationService();
await service.sendToBackend(
'apprise',
{
serverUrl: 'http://apprise:8000',
configKey: 'my-config',
},
{
event: 'request_approved',
requestId: 'req-1',
title: 'Test Book',
author: 'Test Author',
userName: 'Test User',
timestamp: new Date(),
}
);
// decrypt should not be called since there are no sensitive fields with encrypted values
expect(encryptionMock.decrypt).not.toHaveBeenCalled();
expect(fetchMock).toHaveBeenCalledTimes(1);
});
});
describe('encryptConfig and maskConfig', () => {
it('encrypts urls and authToken', async () => {
const { NotificationService } = await import('@/lib/services/notification');
const service = new NotificationService();
const encrypted = service.encryptConfig('apprise', {
serverUrl: 'http://apprise:8000',
urls: 'slack://tokenA/tokenB',
configKey: 'my-config',
authToken: 'mytoken123',
});
expect(encryptionMock.encrypt).toHaveBeenCalledWith('slack://tokenA/tokenB');
expect(encryptionMock.encrypt).toHaveBeenCalledWith('mytoken123');
expect(encrypted.urls).toBe('enc:slack://tokenA/tokenB');
expect(encrypted.authToken).toBe('enc:mytoken123');
expect(encrypted.serverUrl).toBe('http://apprise:8000'); // Not encrypted
expect(encrypted.configKey).toBe('my-config'); // Not encrypted
});
it('masks urls and authToken', async () => {
const { NotificationService } = await import('@/lib/services/notification');
const service = new NotificationService();
const masked = service.maskConfig('apprise', {
serverUrl: 'http://apprise:8000',
urls: 'slack://tokenA/tokenB',
configKey: 'my-config',
authToken: 'mytoken123',
});
expect(masked.urls).toBe('••••••••');
expect(masked.authToken).toBe('••••••••');
expect(masked.serverUrl).toBe('http://apprise:8000'); // Not masked
expect(masked.configKey).toBe('my-config'); // Not masked
});
});
});
@@ -191,6 +191,40 @@ describe('LocalAuthProvider', () => {
expect(result.error).toContain('Password');
});
it('allows short passwords when ALLOW_WEAK_PASSWORD is enabled', async () => {
process.env.ALLOW_WEAK_PASSWORD = 'true';
configMock.get.mockResolvedValueOnce('true'); // registration enabled
configMock.get.mockResolvedValueOnce('false'); // no admin approval
prismaMock.user.findFirst.mockResolvedValue(null);
prismaMock.user.count.mockResolvedValue(0);
prismaMock.user.create.mockResolvedValue({
id: 'user-1',
plexId: 'local-user',
plexUsername: 'user',
role: 'admin',
});
bcryptHash.mockResolvedValue('hash');
const { LocalAuthProvider } = await import('@/lib/services/auth/LocalAuthProvider');
const provider = new LocalAuthProvider();
const result = await provider.register({ username: 'user', password: 'ab' });
expect(result.success).toBe(true);
delete process.env.ALLOW_WEAK_PASSWORD;
});
it('still rejects empty passwords when ALLOW_WEAK_PASSWORD is enabled', async () => {
process.env.ALLOW_WEAK_PASSWORD = 'true';
const { LocalAuthProvider } = await import('@/lib/services/auth/LocalAuthProvider');
const provider = new LocalAuthProvider();
const result = await provider.register({ username: 'user', password: '' });
expect(result.success).toBe(false);
expect(result.error).toContain('required');
delete process.env.ALLOW_WEAK_PASSWORD;
});
it('rejects registration when username is taken', async () => {
configMock.get.mockResolvedValueOnce('true');
prismaMock.user.findFirst.mockResolvedValue({ id: 'user-10' });
+178 -40
View File
@@ -66,7 +66,7 @@ describe('NotificationService', () => {
json: async () => ({ success: true }),
});
const { NotificationService } = await import('@/lib/services/notification.service');
const { NotificationService } = await import('@/lib/services/notification');
const service = new NotificationService();
await service.sendNotification({
@@ -92,7 +92,7 @@ describe('NotificationService', () => {
it('does not send if no backends are subscribed to the event', async () => {
prismaMock.notificationBackend.findMany.mockResolvedValue([]);
const { NotificationService } = await import('@/lib/services/notification.service');
const { NotificationService } = await import('@/lib/services/notification');
const service = new NotificationService();
await service.sendNotification({
@@ -139,7 +139,7 @@ describe('NotificationService', () => {
json: async () => ({ success: true }),
});
const { NotificationService } = await import('@/lib/services/notification.service');
const { NotificationService } = await import('@/lib/services/notification');
const service = new NotificationService();
await service.sendNotification({
@@ -156,19 +156,99 @@ describe('NotificationService', () => {
});
});
describe('sendDiscord', () => {
describe('sendToBackend', () => {
it('routes to Discord provider and decrypts config', async () => {
fetchMock.mockResolvedValue({
ok: true,
json: async () => ({ success: true }),
});
const { NotificationService } = await import('@/lib/services/notification');
const service = new NotificationService();
await service.sendToBackend(
'discord',
{ webhookUrl: 'enc:https://discord.com/webhook', username: 'ReadMeABook' },
{
event: 'request_approved',
requestId: 'req-1',
title: 'Test Book',
author: 'Test Author',
userName: 'Test User',
timestamp: new Date('2024-01-01T00:00:00Z'),
}
);
expect(encryptionMock.decrypt).toHaveBeenCalledWith('enc:https://discord.com/webhook');
expect(fetchMock).toHaveBeenCalled();
const fetchCall = fetchMock.mock.calls[0];
// Decrypted URL should be used
expect(fetchCall[0]).toBe('https://discord.com/webhook');
});
it('routes to Pushover provider and decrypts config', async () => {
fetchMock.mockResolvedValue({
ok: true,
json: async () => ({ status: 1 }),
});
const { NotificationService } = await import('@/lib/services/notification');
const service = new NotificationService();
// Use iv:authTag:data format to pass isEncrypted() check
await service.sendToBackend(
'pushover',
{ userKey: 'iv:tag:user123', appToken: 'iv:tag:app456', priority: 1 },
{
event: 'request_approved',
requestId: 'req-1',
title: 'Test Book',
author: 'Test Author',
userName: 'Test User',
timestamp: new Date(),
}
);
expect(encryptionMock.decrypt).toHaveBeenCalledWith('iv:tag:user123');
expect(encryptionMock.decrypt).toHaveBeenCalledWith('iv:tag:app456');
expect(fetchMock).toHaveBeenCalled();
});
it('throws error for unsupported backend type', async () => {
const { NotificationService } = await import('@/lib/services/notification');
const service = new NotificationService();
await expect(
service.sendToBackend(
'email',
{},
{
event: 'request_approved',
requestId: 'req-1',
title: 'Test Book',
author: 'Test Author',
userName: 'Test User',
timestamp: new Date(),
}
)
).rejects.toThrow('Unsupported backend type: email');
});
});
describe('DiscordProvider', () => {
it('sends Discord webhook with rich embed', async () => {
fetchMock.mockResolvedValue({
ok: true,
json: async () => ({ success: true }),
});
const { NotificationService } = await import('@/lib/services/notification.service');
const service = new NotificationService();
const { DiscordProvider } = await import('@/lib/services/notification');
const provider = new DiscordProvider();
await service.sendDiscord(
await provider.send(
{
webhookUrl: 'enc:https://discord.com/webhook',
webhookUrl: 'https://discord.com/webhook',
username: 'ReadMeABook',
},
{
@@ -181,12 +261,12 @@ describe('NotificationService', () => {
}
);
// Should call the webhook (URL decryption happens internally)
expect(fetchMock).toHaveBeenCalled();
const fetchCall = fetchMock.mock.calls[0];
const body = JSON.parse(fetchCall[1].body);
expect(fetchCall[0]).toBe('https://discord.com/webhook');
expect(fetchCall[1].method).toBe('POST');
expect(fetchCall[1].headers['Content-Type']).toBe('application/json');
expect(body.username).toBe('ReadMeABook');
@@ -201,12 +281,12 @@ describe('NotificationService', () => {
json: async () => ({ success: true }),
});
const { NotificationService } = await import('@/lib/services/notification.service');
const service = new NotificationService();
const { DiscordProvider } = await import('@/lib/services/notification');
const provider = new DiscordProvider();
await service.sendDiscord(
await provider.send(
{
webhookUrl: 'enc:https://discord.com/webhook',
webhookUrl: 'https://discord.com/webhook',
},
{
event: 'request_approved',
@@ -230,12 +310,12 @@ describe('NotificationService', () => {
text: async () => 'Bad Request',
});
const { NotificationService } = await import('@/lib/services/notification.service');
const service = new NotificationService();
const { DiscordProvider } = await import('@/lib/services/notification');
const provider = new DiscordProvider();
await expect(
service.sendDiscord(
{ webhookUrl: 'enc:https://discord.com/webhook' },
provider.send(
{ webhookUrl: 'https://discord.com/webhook' },
{
event: 'request_approved',
requestId: 'req-1',
@@ -249,20 +329,20 @@ describe('NotificationService', () => {
});
});
describe('sendPushover', () => {
describe('PushoverProvider', () => {
it('sends Pushover notification with correct payload', async () => {
fetchMock.mockResolvedValue({
ok: true,
json: async () => ({ status: 1 }),
});
const { NotificationService } = await import('@/lib/services/notification.service');
const service = new NotificationService();
const { PushoverProvider } = await import('@/lib/services/notification');
const provider = new PushoverProvider();
await service.sendPushover(
await provider.send(
{
userKey: 'enc:user123',
appToken: 'enc:app456',
userKey: 'user123',
appToken: 'app456',
priority: 1,
},
{
@@ -275,7 +355,6 @@ describe('NotificationService', () => {
}
);
// Should call the Pushover API (credential decryption happens internally)
expect(fetchMock).toHaveBeenCalled();
const fetchCall = fetchMock.mock.calls[0];
@@ -296,13 +375,13 @@ describe('NotificationService', () => {
json: async () => ({ status: 1 }),
});
const { NotificationService } = await import('@/lib/services/notification.service');
const service = new NotificationService();
const { PushoverProvider } = await import('@/lib/services/notification');
const provider = new PushoverProvider();
await service.sendPushover(
await provider.send(
{
userKey: 'enc:user123',
appToken: 'enc:app456',
userKey: 'user123',
appToken: 'app456',
},
{
event: 'request_approved',
@@ -325,12 +404,12 @@ describe('NotificationService', () => {
text: async () => 'invalid user key',
});
const { NotificationService } = await import('@/lib/services/notification.service');
const service = new NotificationService();
const { PushoverProvider } = await import('@/lib/services/notification');
const provider = new PushoverProvider();
await expect(
service.sendPushover(
{ userKey: 'enc:user123', appToken: 'enc:app456' },
provider.send(
{ userKey: 'user123', appToken: 'app456' },
{
event: 'request_approved',
requestId: 'req-1',
@@ -344,11 +423,9 @@ describe('NotificationService', () => {
});
});
// Note: formatDiscordEmbed is a private method, tested indirectly through sendDiscord
describe('encryptConfig', () => {
it('encrypts sensitive Discord config values', async () => {
const { NotificationService } = await import('@/lib/services/notification.service');
const { NotificationService } = await import('@/lib/services/notification');
const service = new NotificationService();
const encrypted = service.encryptConfig('discord', {
@@ -362,7 +439,7 @@ describe('NotificationService', () => {
});
it('encrypts sensitive Pushover config values', async () => {
const { NotificationService } = await import('@/lib/services/notification.service');
const { NotificationService } = await import('@/lib/services/notification');
const service = new NotificationService();
const encrypted = service.encryptConfig('pushover', {
@@ -379,11 +456,72 @@ describe('NotificationService', () => {
});
});
// Note: decryptConfig is a private method, tested indirectly through sendDiscord/sendPushover
describe('getRegisteredProviderTypes', () => {
it('returns all registered provider type keys', async () => {
const { getRegisteredProviderTypes } = await import('@/lib/services/notification');
const types = getRegisteredProviderTypes();
expect(types).toContain('apprise');
expect(types).toContain('discord');
expect(types).toContain('ntfy');
expect(types).toContain('pushover');
expect(types).toHaveLength(4);
});
});
describe('getAllProviderMetadata', () => {
it('returns metadata for all registered providers', async () => {
const { getAllProviderMetadata } = await import('@/lib/services/notification');
const metadata = getAllProviderMetadata();
expect(metadata).toHaveLength(4);
const apprise = metadata.find((m) => m.type === 'apprise');
expect(apprise).toBeDefined();
expect(apprise!.displayName).toBe('Apprise');
expect(apprise!.iconLabel).toBe('A');
expect(apprise!.iconColor).toBe('bg-purple-500');
const discord = metadata.find((m) => m.type === 'discord');
expect(discord).toBeDefined();
expect(discord!.displayName).toBe('Discord');
expect(discord!.iconLabel).toBe('D');
expect(discord!.iconColor).toBe('bg-indigo-500');
expect(discord!.configFields.length).toBeGreaterThan(0);
const ntfy = metadata.find((m) => m.type === 'ntfy');
expect(ntfy).toBeDefined();
expect(ntfy!.displayName).toBe('ntfy');
expect(ntfy!.iconLabel).toBe('N');
const pushover = metadata.find((m) => m.type === 'pushover');
expect(pushover).toBeDefined();
expect(pushover!.displayName).toBe('Pushover');
expect(pushover!.iconLabel).toBe('P');
});
it('includes config field definitions with correct properties', async () => {
const { getAllProviderMetadata } = await import('@/lib/services/notification');
const metadata = getAllProviderMetadata();
const discord = metadata.find((m) => m.type === 'discord')!;
const webhookField = discord.configFields.find((f) => f.name === 'webhookUrl');
expect(webhookField).toBeDefined();
expect(webhookField!.required).toBe(true);
expect(webhookField!.type).toBe('text');
const pushover = metadata.find((m) => m.type === 'pushover')!;
const priorityField = pushover.configFields.find((f) => f.name === 'priority');
expect(priorityField).toBeDefined();
expect(priorityField!.type).toBe('select');
expect(priorityField!.options).toBeDefined();
expect(priorityField!.options!.length).toBe(5);
});
});
describe('maskConfig', () => {
it('masks sensitive Discord config values', async () => {
const { NotificationService } = await import('@/lib/services/notification.service');
const { NotificationService } = await import('@/lib/services/notification');
const service = new NotificationService();
const masked = service.maskConfig('discord', {
@@ -396,7 +534,7 @@ describe('NotificationService', () => {
});
it('masks sensitive Pushover config values', async () => {
const { NotificationService } = await import('@/lib/services/notification.service');
const { NotificationService } = await import('@/lib/services/notification');
const service = new NotificationService();
const masked = service.maskConfig('pushover', {
+368
View File
@@ -0,0 +1,368 @@
/**
* Component: ntfy Notification Provider Tests
* Documentation: documentation/backend/services/notifications.md
*/
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { createPrismaMock } from '../helpers/prisma';
const prismaMock = createPrismaMock();
prismaMock.notificationBackend = {
findMany: vi.fn(),
findUnique: vi.fn(),
create: vi.fn(),
update: vi.fn(),
delete: vi.fn(),
} as any;
const encryptionMock = vi.hoisted(() => ({
encrypt: vi.fn((value: string) => `enc:${value}`),
decrypt: vi.fn((value: string) => value.replace('enc:', '')),
}));
const fetchMock = vi.hoisted(() => vi.fn());
vi.mock('@/lib/db', () => ({
prisma: prismaMock,
}));
vi.mock('@/lib/services/encryption.service', () => ({
getEncryptionService: () => encryptionMock,
}));
describe('NtfyProvider', () => {
beforeEach(() => {
vi.clearAllMocks();
vi.stubGlobal('fetch', fetchMock);
});
describe('send', () => {
it('sends notification to correct ntfy endpoint with JSON body', async () => {
fetchMock.mockResolvedValue({
ok: true,
json: async () => ({ id: 'msg123' }),
});
const { NtfyProvider } = await import('@/lib/services/notification');
const provider = new NtfyProvider();
await provider.send(
{
serverUrl: 'https://ntfy.example.com',
topic: 'audiobooks',
accessToken: 'tk_mytoken123',
},
{
event: 'request_approved',
requestId: 'req-1',
title: 'Test Book',
author: 'Test Author',
userName: 'Test User',
timestamp: new Date('2024-01-01T00:00:00Z'),
}
);
expect(fetchMock).toHaveBeenCalledTimes(1);
const fetchCall = fetchMock.mock.calls[0];
expect(fetchCall[0]).toBe('https://ntfy.example.com/audiobooks');
expect(fetchCall[1].method).toBe('POST');
expect(fetchCall[1].headers['Content-Type']).toBe('application/json');
expect(fetchCall[1].headers['Authorization']).toBe('Bearer tk_mytoken123');
const body = JSON.parse(fetchCall[1].body);
expect(body.topic).toBe('audiobooks');
expect(body.title).toBe('Request Approved');
expect(body.message).toContain('Test Book');
expect(body.message).toContain('Test Author');
expect(body.message).toContain('Test User');
expect(body.priority).toBe(3);
expect(body.tags).toEqual(['white_check_mark']);
});
it('uses default server URL (https://ntfy.sh) when not provided', async () => {
fetchMock.mockResolvedValue({
ok: true,
json: async () => ({ id: 'msg123' }),
});
const { NtfyProvider } = await import('@/lib/services/notification');
const provider = new NtfyProvider();
await provider.send(
{
topic: 'audiobooks',
},
{
event: 'request_available',
requestId: 'req-1',
title: 'Test Book',
author: 'Test Author',
userName: 'Test User',
timestamp: new Date(),
}
);
const fetchCall = fetchMock.mock.calls[0];
expect(fetchCall[0]).toBe('https://ntfy.sh/audiobooks');
});
it('does not include Authorization header when accessToken is not provided', async () => {
fetchMock.mockResolvedValue({
ok: true,
json: async () => ({ id: 'msg123' }),
});
const { NtfyProvider } = await import('@/lib/services/notification');
const provider = new NtfyProvider();
await provider.send(
{
topic: 'audiobooks',
},
{
event: 'request_approved',
requestId: 'req-1',
title: 'Test Book',
author: 'Test Author',
userName: 'Test User',
timestamp: new Date(),
}
);
const fetchCall = fetchMock.mock.calls[0];
expect(fetchCall[1].headers['Authorization']).toBeUndefined();
});
it('uses default priority based on event type when not configured', async () => {
fetchMock.mockResolvedValue({
ok: true,
json: async () => ({ id: 'msg123' }),
});
const { NtfyProvider } = await import('@/lib/services/notification');
const provider = new NtfyProvider();
// request_error should default to priority 4 (high)
await provider.send(
{ topic: 'audiobooks' },
{
event: 'request_error',
requestId: 'req-1',
title: 'Test Book',
author: 'Test Author',
userName: 'Test User',
message: 'Download failed',
timestamp: new Date(),
}
);
const body = JSON.parse(fetchMock.mock.calls[0][1].body);
expect(body.priority).toBe(4);
expect(body.tags).toEqual(['x']);
expect(body.message).toContain('Download failed');
});
it('uses configured priority over default', async () => {
fetchMock.mockResolvedValue({
ok: true,
json: async () => ({ id: 'msg123' }),
});
const { NtfyProvider } = await import('@/lib/services/notification');
const provider = new NtfyProvider();
await provider.send(
{ topic: 'audiobooks', priority: 5 },
{
event: 'request_approved',
requestId: 'req-1',
title: 'Test Book',
author: 'Test Author',
userName: 'Test User',
timestamp: new Date(),
}
);
const body = JSON.parse(fetchMock.mock.calls[0][1].body);
expect(body.priority).toBe(5);
});
it('strips trailing slashes from server URL', async () => {
fetchMock.mockResolvedValue({
ok: true,
json: async () => ({ id: 'msg123' }),
});
const { NtfyProvider } = await import('@/lib/services/notification');
const provider = new NtfyProvider();
await provider.send(
{ serverUrl: 'https://ntfy.example.com/', topic: 'audiobooks' },
{
event: 'request_approved',
requestId: 'req-1',
title: 'Test Book',
author: 'Test Author',
userName: 'Test User',
timestamp: new Date(),
}
);
const fetchCall = fetchMock.mock.calls[0];
expect(fetchCall[0]).toBe('https://ntfy.example.com/audiobooks');
});
it('throws descriptive error when API returns non-OK response', async () => {
fetchMock.mockResolvedValue({
ok: false,
status: 401,
text: async () => 'unauthorized',
});
const { NtfyProvider } = await import('@/lib/services/notification');
const provider = new NtfyProvider();
await expect(
provider.send(
{ topic: 'audiobooks', accessToken: 'bad_token' },
{
event: 'request_approved',
requestId: 'req-1',
title: 'Test Book',
author: 'Test Author',
userName: 'Test User',
timestamp: new Date(),
}
)
).rejects.toThrow('ntfy API failed: 401 unauthorized');
});
it('includes error message in notification body for error events', async () => {
fetchMock.mockResolvedValue({
ok: true,
json: async () => ({ id: 'msg123' }),
});
const { NtfyProvider } = await import('@/lib/services/notification');
const provider = new NtfyProvider();
await provider.send(
{ topic: 'audiobooks' },
{
event: 'request_error',
requestId: 'req-1',
title: 'Test Book',
author: 'Test Author',
userName: 'Test User',
message: 'Download timed out',
timestamp: new Date(),
}
);
const body = JSON.parse(fetchMock.mock.calls[0][1].body);
expect(body.message).toContain('⚠️ Error: Download timed out');
});
});
describe('integration with NotificationService.sendToBackend', () => {
it('decrypts accessToken and sends to ntfy', async () => {
fetchMock.mockResolvedValue({
ok: true,
json: async () => ({ id: 'msg123' }),
});
const { NotificationService } = await import('@/lib/services/notification');
const service = new NotificationService();
// Use iv:authTag:data format to pass isEncrypted() check
await service.sendToBackend(
'ntfy',
{
serverUrl: 'https://ntfy.example.com',
topic: 'audiobooks',
accessToken: 'iv:tag:tk_mytoken123',
},
{
event: 'request_approved',
requestId: 'req-1',
title: 'Test Book',
author: 'Test Author',
userName: 'Test User',
timestamp: new Date(),
}
);
// Verify decrypt was called for the sensitive field
expect(encryptionMock.decrypt).toHaveBeenCalledWith('iv:tag:tk_mytoken123');
// Verify the decrypted value reaches the fetch call
expect(fetchMock).toHaveBeenCalledTimes(1);
const fetchCall = fetchMock.mock.calls[0];
expect(fetchCall[1].headers['Authorization']).toBe('Bearer iv:tag:tk_mytoken123');
});
it('does not decrypt non-sensitive fields', async () => {
fetchMock.mockResolvedValue({
ok: true,
json: async () => ({ id: 'msg123' }),
});
const { NotificationService } = await import('@/lib/services/notification');
const service = new NotificationService();
await service.sendToBackend(
'ntfy',
{
serverUrl: 'https://ntfy.example.com',
topic: 'audiobooks',
},
{
event: 'request_approved',
requestId: 'req-1',
title: 'Test Book',
author: 'Test Author',
userName: 'Test User',
timestamp: new Date(),
}
);
// decrypt should not be called since there's no accessToken
expect(encryptionMock.decrypt).not.toHaveBeenCalled();
expect(fetchMock).toHaveBeenCalledTimes(1);
});
});
describe('encryptConfig and maskConfig', () => {
it('encrypts accessToken', async () => {
const { NotificationService } = await import('@/lib/services/notification');
const service = new NotificationService();
const encrypted = service.encryptConfig('ntfy', {
serverUrl: 'https://ntfy.example.com',
topic: 'audiobooks',
accessToken: 'tk_mytoken123',
});
expect(encryptionMock.encrypt).toHaveBeenCalledWith('tk_mytoken123');
expect(encrypted.accessToken).toBe('enc:tk_mytoken123');
expect(encrypted.serverUrl).toBe('https://ntfy.example.com'); // Not encrypted
expect(encrypted.topic).toBe('audiobooks'); // Not encrypted
});
it('masks accessToken', async () => {
const { NotificationService } = await import('@/lib/services/notification');
const service = new NotificationService();
const masked = service.maskConfig('ntfy', {
serverUrl: 'https://ntfy.example.com',
topic: 'audiobooks',
accessToken: 'tk_mytoken123',
});
expect(masked.accessToken).toBe('••••••••');
expect(masked.serverUrl).toBe('https://ntfy.example.com'); // Not masked
expect(masked.topic).toBe('audiobooks'); // Not masked
});
});
});
+85
View File
@@ -0,0 +1,85 @@
/**
* Component: Stream-based File Copy Utility Tests
* Documentation: documentation/phase3/file-organization.md
*/
import { describe, expect, it, vi, beforeEach } from 'vitest';
import { Readable, Writable } from 'stream';
const pipelineMock = vi.hoisted(() => vi.fn());
const createReadStreamMock = vi.hoisted(() => vi.fn());
const createWriteStreamMock = vi.hoisted(() => vi.fn());
vi.mock('stream/promises', () => ({
pipeline: pipelineMock,
}));
vi.mock('fs', () => ({
createReadStream: createReadStreamMock,
createWriteStream: createWriteStreamMock,
}));
import { copyFile } from '@/lib/utils/copy-file';
describe('copyFile', () => {
beforeEach(() => {
vi.clearAllMocks();
});
it('pipes source to destination via pipeline', async () => {
const mockReadStream = new Readable({ read() {} });
const mockWriteStream = new Writable({ write(_, __, cb) { cb(); } });
createReadStreamMock.mockReturnValue(mockReadStream);
createWriteStreamMock.mockReturnValue(mockWriteStream);
pipelineMock.mockResolvedValue(undefined);
await copyFile('/source/file.m4b', '/dest/file.m4b');
expect(createReadStreamMock).toHaveBeenCalledWith('/source/file.m4b');
expect(createWriteStreamMock).toHaveBeenCalledWith('/dest/file.m4b');
expect(pipelineMock).toHaveBeenCalledWith(mockReadStream, mockWriteStream);
});
it('propagates read errors', async () => {
const mockReadStream = new Readable({ read() {} });
const mockWriteStream = new Writable({ write(_, __, cb) { cb(); } });
createReadStreamMock.mockReturnValue(mockReadStream);
createWriteStreamMock.mockReturnValue(mockWriteStream);
pipelineMock.mockRejectedValue(
Object.assign(new Error('ENOENT: no such file or directory'), { code: 'ENOENT' })
);
await expect(copyFile('/missing/file.m4b', '/dest/file.m4b'))
.rejects.toThrow('ENOENT');
});
it('propagates write errors', async () => {
const mockReadStream = new Readable({ read() {} });
const mockWriteStream = new Writable({ write(_, __, cb) { cb(); } });
createReadStreamMock.mockReturnValue(mockReadStream);
createWriteStreamMock.mockReturnValue(mockWriteStream);
pipelineMock.mockRejectedValue(
Object.assign(new Error('EACCES: permission denied'), { code: 'EACCES' })
);
await expect(copyFile('/source/file.m4b', '/readonly/file.m4b'))
.rejects.toThrow('EACCES');
});
it('propagates EPERM errors (the original bug scenario)', async () => {
const mockReadStream = new Readable({ read() {} });
const mockWriteStream = new Writable({ write(_, __, cb) { cb(); } });
createReadStreamMock.mockReturnValue(mockReadStream);
createWriteStreamMock.mockReturnValue(mockWriteStream);
pipelineMock.mockRejectedValue(
Object.assign(new Error('EPERM: operation not permitted'), { code: 'EPERM' })
);
await expect(copyFile('/nfs/source.m4b', '/nfs/dest.m4b'))
.rejects.toThrow('EPERM');
});
});
+29 -24
View File
@@ -11,7 +11,6 @@ const fsMock = vi.hoisted(() => ({
access: vi.fn(),
stat: vi.fn(),
mkdir: vi.fn(),
copyFile: vi.fn(),
chmod: vi.fn(),
unlink: vi.fn(),
writeFile: vi.fn(),
@@ -71,11 +70,17 @@ const ebookMock = vi.hoisted(() => ({
downloadEbook: vi.fn(),
}));
const copyFileMock = vi.hoisted(() => ({
copyFile: vi.fn(),
}));
vi.mock('fs/promises', () => ({
default: fsMock,
...fsMock,
}));
vi.mock('@/lib/utils/copy-file', () => copyFileMock);
vi.mock('axios', () => ({
default: axiosMock,
...axiosMock,
@@ -109,7 +114,7 @@ describe('file organizer', () => {
throw new Error('missing');
});
fsMock.mkdir.mockResolvedValue(undefined);
fsMock.copyFile.mockResolvedValue(undefined);
copyFileMock.copyFile.mockResolvedValue(undefined);
fsMock.chmod.mockResolvedValue(undefined);
const organizer = new FileOrganizer('/media', '/tmp');
@@ -174,7 +179,7 @@ describe('file organizer', () => {
throw new Error('missing');
});
fsMock.mkdir.mockResolvedValue(undefined);
fsMock.copyFile.mockResolvedValue(undefined);
copyFileMock.copyFile.mockResolvedValue(undefined);
fsMock.chmod.mockResolvedValue(undefined);
const organizer = new FileOrganizer('/media', '/tmp');
@@ -216,7 +221,7 @@ describe('file organizer', () => {
throw new Error('missing');
});
fsMock.mkdir.mockResolvedValue(undefined);
fsMock.copyFile.mockResolvedValue(undefined);
copyFileMock.copyFile.mockResolvedValue(undefined);
fsMock.chmod.mockResolvedValue(undefined);
fsMock.unlink.mockResolvedValue(undefined);
@@ -235,7 +240,7 @@ describe('file organizer', () => {
const expectedDir = path.join('/media', 'Author', 'Book');
expect(result.success).toBe(true);
expect(result.targetPath).toBe(expectedDir);
expect(fsMock.copyFile).toHaveBeenCalledWith('/tmp/tagged.m4b', path.join(expectedDir, 'book.m4b'));
expect(copyFileMock.copyFile).toHaveBeenCalledWith('/tmp/tagged.m4b', path.join(expectedDir, 'book.m4b'));
expect(fsMock.unlink).toHaveBeenCalledWith('/tmp/tagged.m4b');
});
@@ -261,7 +266,7 @@ describe('file organizer', () => {
throw new Error('missing');
});
fsMock.mkdir.mockResolvedValue(undefined);
fsMock.copyFile.mockResolvedValue(undefined);
copyFileMock.copyFile.mockResolvedValue(undefined);
fsMock.chmod.mockResolvedValue(undefined);
const result = await organizer.organize('/downloads/book', {
@@ -272,7 +277,7 @@ describe('file organizer', () => {
expect(result.success).toBe(true);
expect(result.errors).toContain('Metadata tagging skipped: ffmpeg not available');
expect(metadataMock.tagMultipleFiles).not.toHaveBeenCalled();
expect(fsMock.copyFile).toHaveBeenCalledWith(sourcePath, targetFile);
expect(copyFileMock.copyFile).toHaveBeenCalledWith(sourcePath, targetFile);
});
it('downloads remote cover art when no local cover exists', async () => {
@@ -294,7 +299,7 @@ describe('file organizer', () => {
throw new Error('missing');
});
fsMock.mkdir.mockResolvedValue(undefined);
fsMock.copyFile.mockResolvedValue(undefined);
copyFileMock.copyFile.mockResolvedValue(undefined);
fsMock.chmod.mockResolvedValue(undefined);
fsMock.writeFile.mockResolvedValue(undefined);
@@ -316,7 +321,7 @@ describe('file organizer', () => {
// NOTE: Ebook downloads are now handled as first-class requests through the job queue
// The file organizer no longer downloads ebooks inline
expect(ebookMock.downloadEbook).not.toHaveBeenCalled();
expect(fsMock.copyFile).toHaveBeenCalledWith(sourcePath, targetFile);
expect(copyFileMock.copyFile).toHaveBeenCalledWith(sourcePath, targetFile);
expect(result.filesMovedCount).toBe(1);
});
@@ -340,7 +345,7 @@ describe('file organizer', () => {
throw new Error('missing');
});
fsMock.mkdir.mockResolvedValue(undefined);
fsMock.copyFile.mockResolvedValue(undefined);
copyFileMock.copyFile.mockResolvedValue(undefined);
fsMock.chmod.mockResolvedValue(undefined);
axiosMock.get.mockRejectedValue(new Error('cover failed'));
@@ -352,7 +357,7 @@ describe('file organizer', () => {
expect(result.success).toBe(true);
expect(result.errors.join(' ')).toContain('Failed to download cover art');
expect(fsMock.copyFile).toHaveBeenCalledWith(sourcePath, targetFile);
expect(copyFileMock.copyFile).toHaveBeenCalledWith(sourcePath, targetFile);
});
it('continues when chapter analysis returns no valid chapters', async () => {
@@ -378,7 +383,7 @@ describe('file organizer', () => {
throw new Error('missing');
});
fsMock.mkdir.mockResolvedValue(undefined);
fsMock.copyFile.mockResolvedValue(undefined);
copyFileMock.copyFile.mockResolvedValue(undefined);
fsMock.chmod.mockResolvedValue(undefined);
const result = await organizer.organize('/downloads/book', {
@@ -415,7 +420,7 @@ describe('file organizer', () => {
throw new Error('missing');
});
fsMock.mkdir.mockResolvedValue(undefined);
fsMock.copyFile.mockResolvedValue(undefined);
copyFileMock.copyFile.mockResolvedValue(undefined);
fsMock.chmod.mockResolvedValue(undefined);
fsMock.unlink.mockResolvedValue(undefined);
@@ -502,7 +507,7 @@ describe('file organizer', () => {
expect(result.audioFiles).toEqual([]);
expect(result.errors.join(' ')).toContain('Source file not found');
expect(result.errors.join(' ')).toContain('No audio files were successfully copied');
expect(fsMock.copyFile).not.toHaveBeenCalled();
expect(copyFileMock.copyFile).not.toHaveBeenCalled();
});
it('skips copying when target files already exist', async () => {
@@ -535,7 +540,7 @@ describe('file organizer', () => {
expect(result.success).toBe(true);
expect(result.audioFiles).toEqual([targetPath]);
expect(result.filesMovedCount).toBe(0);
expect(fsMock.copyFile).not.toHaveBeenCalled();
expect(copyFileMock.copyFile).not.toHaveBeenCalled();
});
it('continues when metadata tagging throws', async () => {
@@ -557,7 +562,7 @@ describe('file organizer', () => {
throw new Error('missing');
});
fsMock.mkdir.mockResolvedValue(undefined);
fsMock.copyFile.mockResolvedValue(undefined);
copyFileMock.copyFile.mockResolvedValue(undefined);
fsMock.chmod.mockResolvedValue(undefined);
const result = await organizer.organize('/downloads/book', {
@@ -567,7 +572,7 @@ describe('file organizer', () => {
expect(result.success).toBe(true);
expect(result.errors.join(' ')).toContain('Metadata tagging failed');
expect(fsMock.copyFile).toHaveBeenCalled();
expect(copyFileMock.copyFile).toHaveBeenCalled();
});
it('validates paths and reports multiple issues', async () => {
@@ -668,7 +673,7 @@ describe('file organizer', () => {
throw new Error('missing');
});
fsMock.mkdir.mockResolvedValue(undefined);
fsMock.copyFile.mockRejectedValue(
copyFileMock.copyFile.mockRejectedValue(
Object.assign(new Error('EPERM: operation not permitted, copyfile'), { code: 'EPERM' })
);
@@ -705,7 +710,7 @@ describe('file organizer', () => {
throw new Error('missing');
});
fsMock.mkdir.mockResolvedValue(undefined);
fsMock.copyFile.mockImplementation(async (src: string, dest: string) => {
copyFileMock.copyFile.mockImplementation(async (src: string, dest: string) => {
// Tagged file copy fails with EPERM
if (path.normalize(src) === path.normalize(taggedPath)) {
throw Object.assign(new Error('EPERM: operation not permitted'), { code: 'EPERM' });
@@ -736,7 +741,7 @@ describe('file organizer', () => {
// Tagged temp file should be cleaned up
expect(fsMock.unlink).toHaveBeenCalledWith(taggedPath);
// Fallback copy should use the original source
expect(fsMock.copyFile).toHaveBeenCalledWith(sourcePath, targetFile);
expect(copyFileMock.copyFile).toHaveBeenCalledWith(sourcePath, targetFile);
// Should record that tagged copy failed
expect(result.errors.join(' ')).toContain('Tagged copy failed');
expect(result.errors.join(' ')).toContain('without metadata tags');
@@ -760,7 +765,7 @@ describe('file organizer', () => {
});
fsMock.mkdir.mockResolvedValue(undefined);
// Both tagged and original copies fail
fsMock.copyFile.mockRejectedValue(
copyFileMock.copyFile.mockRejectedValue(
Object.assign(new Error('EPERM: operation not permitted'), { code: 'EPERM' })
);
fsMock.unlink.mockResolvedValue(undefined);
@@ -808,7 +813,7 @@ describe('file organizer', () => {
throw new Error('missing');
});
fsMock.mkdir.mockResolvedValue(undefined);
fsMock.copyFile.mockImplementation(async (src: string) => {
copyFileMock.copyFile.mockImplementation(async (src: string) => {
// First file succeeds, second fails
if (path.normalize(src) === path.normalize(source2)) {
throw Object.assign(new Error('EPERM: operation not permitted'), { code: 'EPERM' });
@@ -847,7 +852,7 @@ describe('file organizer', () => {
throw new Error('missing');
});
fsMock.mkdir.mockResolvedValue(undefined);
fsMock.copyFile.mockResolvedValue(undefined);
copyFileMock.copyFile.mockResolvedValue(undefined);
fsMock.chmod.mockResolvedValue(undefined);
fsMock.writeFile.mockResolvedValue(undefined);
axiosMock.get.mockResolvedValue({ data: Buffer.from('cover') });
@@ -881,7 +886,7 @@ describe('file organizer', () => {
throw new Error('missing');
});
fsMock.mkdir.mockResolvedValue(undefined);
fsMock.copyFile.mockRejectedValue(
copyFileMock.copyFile.mockRejectedValue(
Object.assign(new Error('EPERM: operation not permitted'), { code: 'EPERM' })
);
fsMock.writeFile.mockResolvedValue(undefined);