From a3bb3f2396f69227a218f0f78b6a809e53fa7005 Mon Sep 17 00:00:00 2001 From: Schalli Date: Wed, 1 Jul 2026 10:21:49 +0200 Subject: [PATCH 1/4] test(08-03): add failing tests for FavoritesWidget CRUD + view toggle + letter fallback (RED) - fetchFavorites called with instanceId (widgetId scope, Pitfall 3) - covers add/edit/delete, empty state, list/grid toggle, letter fallback - tests fail: favorites-widget.tsx and favorites-api.ts do not exist yet --- .../widgets/favorites-widget.test.tsx | 277 ++++++++++++++++++ 1 file changed, 277 insertions(+) create mode 100644 apps/web/src/components/dashboard/widgets/favorites-widget.test.tsx diff --git a/apps/web/src/components/dashboard/widgets/favorites-widget.test.tsx b/apps/web/src/components/dashboard/widgets/favorites-widget.test.tsx new file mode 100644 index 0000000..c8ee1e9 --- /dev/null +++ b/apps/web/src/components/dashboard/widgets/favorites-widget.test.tsx @@ -0,0 +1,277 @@ +import { act, fireEvent, render, screen, waitFor } from '@testing-library/react'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; + +// Mock next-intl — passthrough t(key) => key (Pitfall: must be before imports) +vi.mock('next-intl', () => ({ + useTranslations: () => (key: string) => key, +})); + +// Mock favorites-api — all 4 functions as controllable vi.fn() spies +vi.mock('@/lib/favorites-api', () => ({ + fetchFavorites: vi.fn(), + createFavorite: vi.fn(), + updateFavorite: vi.fn(), + deleteFavorite: vi.fn(), +})); + +// Mock dashboard-api for updateWidgetConfig (view mode persistence) +vi.mock('@/lib/dashboard-api', () => ({ + updateWidgetConfig: vi.fn().mockResolvedValue(undefined), +})); + +import { + fetchFavorites, + createFavorite, + updateFavorite, + deleteFavorite, +} from '@/lib/favorites-api'; + +// Must import AFTER mocks +import { FavoritesWidget } from './favorites-widget'; + +// Typed mock helpers +const mockFetch = fetchFavorites as ReturnType; +const mockCreate = createFavorite as ReturnType; +const mockUpdate = updateFavorite as ReturnType; +const mockDelete = deleteFavorite as ReturnType; + +const BASE_FAVORITES = [ + { + id: 'fav-id-1', + widgetId: 'fav-1', + title: 'GitHub', + url: 'https://github.com', + iconUrl: 'https://github.com/favicon.ico', + position: 0, + }, + { + id: 'fav-id-2', + widgetId: 'fav-1', + title: 'Notion', + url: 'https://notion.so', + iconUrl: null, // null iconUrl → letter fallback 'N' + position: 1, + }, +]; + +describe('FavoritesWidget', () => { + beforeEach(() => { + vi.clearAllMocks(); + // Default: return the base favorites list + mockFetch.mockResolvedValue([...BASE_FAVORITES]); + mockCreate.mockResolvedValue({ + id: 'fav-id-new', + widgetId: 'fav-1', + title: 'New Link', + url: 'https://example.com', + iconUrl: null, + position: 2, + }); + mockUpdate.mockResolvedValue({ + ...BASE_FAVORITES[0], + title: 'GitHub Updated', + }); + mockDelete.mockResolvedValue(undefined); + }); + + afterEach(() => { + vi.restoreAllMocks(); + }); + + it('calls fetchFavorites with instanceId on mount and renders link titles', async () => { + render( + , + ); + + // fetchFavorites must be called with the instanceId (widgetId scope — Pitfall 3) + expect(mockFetch).toHaveBeenCalledWith('fav-1'); + + // After async resolution, link titles should be visible + await waitFor(() => { + expect(screen.getByText('GitHub')).toBeInTheDocument(); + expect(screen.getByText('Notion')).toBeInTheDocument(); + }); + }); + + it('shows empty message when fetchFavorites resolves to empty array', async () => { + mockFetch.mockResolvedValue([]); + + render( + , + ); + + await waitFor(() => { + expect(screen.getByText('favorites.empty')).toBeInTheDocument(); + }); + }); + + it('add: submit form in edit mode calls createFavorite with widgetId, title, url', async () => { + mockFetch.mockResolvedValue([]); + + render( + , + ); + + await waitFor(() => { + expect(screen.getByText('favorites.empty')).toBeInTheDocument(); + }); + + // Fill in the add form (inputs are identified by placeholder translation keys) + const titleInput = screen.getByPlaceholderText('favorites.addTitle'); + const urlInput = screen.getByPlaceholderText('favorites.addUrl'); + + await act(async () => { + fireEvent.change(titleInput, { target: { value: 'New Link' } }); + fireEvent.change(urlInput, { target: { value: 'https://example.com' } }); + }); + + // Submit the form (button with text 'favorites.addButton') + const addButton = screen.getByRole('button', { name: /favorites\.addButton/i }); + await act(async () => { + fireEvent.click(addButton); + }); + + // createFavorite must be called with the widgetId and the entered values + expect(mockCreate).toHaveBeenCalledWith( + expect.objectContaining({ + widgetId: 'fav-1', + title: 'New Link', + url: 'https://example.com', + }), + ); + + // The new link title should appear in the list + await waitFor(() => { + expect(screen.getByText('New Link')).toBeInTheDocument(); + }); + }); + + it('edit: clicking edit, changing title, saving calls updateFavorite with id and new title', async () => { + render( + , + ); + + await waitFor(() => { + expect(screen.getByText('GitHub')).toBeInTheDocument(); + }); + + // Click the edit button for 'GitHub' (aria-label is the translation key) + const editButtons = screen.getAllByRole('button', { + name: /favorites\.editButton/i, + }); + await act(async () => { + fireEvent.click(editButtons[0]); + }); + + // Change the title in the inline edit form + const editTitleInput = screen.getByDisplayValue('GitHub'); + await act(async () => { + fireEvent.change(editTitleInput, { target: { value: 'GitHub Updated' } }); + }); + + // Click Save + const saveButton = screen.getByRole('button', { + name: /favorites\.saveButton/i, + }); + await act(async () => { + fireEvent.click(saveButton); + }); + + // updateFavorite called with the favorite id and new title + expect(mockUpdate).toHaveBeenCalledWith( + 'fav-id-1', + expect.objectContaining({ title: 'GitHub Updated' }), + ); + }); + + it('delete: clicking delete calls deleteFavorite with id and removes the row', async () => { + render( + , + ); + + await waitFor(() => { + expect(screen.getByText('GitHub')).toBeInTheDocument(); + }); + + // Click the delete button for 'GitHub' (first delete button) + const deleteButtons = screen.getAllByRole('button', { + name: /favorites\.deleteButton/i, + }); + await act(async () => { + fireEvent.click(deleteButtons[0]); + }); + + // deleteFavorite called with the correct id + expect(mockDelete).toHaveBeenCalledWith('fav-id-1'); + + // The deleted favorite is removed from the list + await waitFor(() => { + expect(screen.queryByText('GitHub')).not.toBeInTheDocument(); + }); + }); + + it('view toggle: switching to grid in edit mode renders grid container', async () => { + render( + , + ); + + await waitFor(() => { + expect(screen.getByText('GitHub')).toBeInTheDocument(); + }); + + // Default list view — list container should be present + expect(screen.getByTestId('favorites-list')).toBeInTheDocument(); + + // Click the 'Kacheln' (grid) toggle button + const gridButton = screen.getByRole('button', { + name: /favorites\.gridView/i, + }); + await act(async () => { + fireEvent.click(gridButton); + }); + + // Grid container should now be rendered + expect(screen.getByTestId('favorites-grid')).toBeInTheDocument(); + }); + + it('letter fallback: link with iconUrl null renders first uppercase letter of title', async () => { + render( + , + ); + + await waitFor(() => { + expect(screen.getByText('Notion')).toBeInTheDocument(); + }); + + // 'Notion' has iconUrl null — the letter fallback span should show 'N' + expect(screen.getByTestId('letter-fallback-fav-id-2')).toHaveTextContent('N'); + }); +}); From 758d246e98108b2c327f2bec0aa1484e97e34260 Mon Sep 17 00:00:00 2001 From: Schalli Date: Wed, 1 Jul 2026 10:25:52 +0200 Subject: [PATCH 2/4] feat(08-03): FavoriteLink schema + FavoritesModule (CRUD + SSRF icon discovery) - Add FavoriteLink Prisma model (userId/tenantId/widgetId scope, iconUrl nullable, position) - IconDiscoveryService: port SSRF-protected icon discovery with redirect: 'manual', private IP / blocked-hostname checks, 4000ms timeout, 200k HTML cap (T-08-05) - FavoritesService: list/create/update/remove all scoped by userId (T-08-06 / Pitfall 3) - FavoritesController: GET /favorites?widgetId, POST, PATCH :id, DELETE :id - FavoritesModule registered in AppModule - tsc --noEmit passes for @tessera/api --- apps/api/prisma/schema.prisma | 17 ++ apps/api/src/app.module.ts | 2 + .../src/favorites/dto/create-favorite.dto.ts | 32 ++ .../src/favorites/dto/update-favorite.dto.ts | 27 ++ .../api/src/favorites/favorites.controller.ts | 88 ++++++ apps/api/src/favorites/favorites.module.ts | 20 ++ apps/api/src/favorites/favorites.service.ts | 96 ++++++ .../src/favorites/icon-discovery.service.ts | 283 ++++++++++++++++++ 8 files changed, 565 insertions(+) create mode 100644 apps/api/src/favorites/dto/create-favorite.dto.ts create mode 100644 apps/api/src/favorites/dto/update-favorite.dto.ts create mode 100644 apps/api/src/favorites/favorites.controller.ts create mode 100644 apps/api/src/favorites/favorites.module.ts create mode 100644 apps/api/src/favorites/favorites.service.ts create mode 100644 apps/api/src/favorites/icon-discovery.service.ts diff --git a/apps/api/prisma/schema.prisma b/apps/api/prisma/schema.prisma index 05f9dd4..e471381 100644 --- a/apps/api/prisma/schema.prisma +++ b/apps/api/prisma/schema.prisma @@ -233,3 +233,20 @@ model SmtpConfig { createdAt DateTime @default(now()) updatedAt DateTime @updatedAt } + +model FavoriteLink { + id String @id @default(uuid()) + userId String + tenantId String + widgetId String + title String + url String + iconUrl String? + position Int @default(0) + createdAt DateTime @default(now()) + updatedAt DateTime @updatedAt + + @@index([userId]) + @@index([tenantId]) + @@index([widgetId]) +} diff --git a/apps/api/src/app.module.ts b/apps/api/src/app.module.ts index 5aecc53..3e5f3d1 100644 --- a/apps/api/src/app.module.ts +++ b/apps/api/src/app.module.ts @@ -12,6 +12,7 @@ import { MailModule } from './mail/mail.module'; import { CalendarModule } from './calendar/calendar.module'; import { DashboardModule } from './dashboard/dashboard.module'; import { DkvModule } from './dkv/dkv.module'; +import { FavoritesModule } from './favorites/favorites.module'; import { DomaincheckModule } from './domaincheck/domaincheck.module'; import { ModuleRegistryModule } from './module-registry/module-registry.module'; import { PrismaModule } from './prisma/prisma.module'; @@ -37,6 +38,7 @@ import { UserModule } from './user/user.module'; CalendarModule, SettingsModule, DkvModule, + FavoritesModule, ], providers: [ // Global JWT guard: all routes require auth unless @Public() diff --git a/apps/api/src/favorites/dto/create-favorite.dto.ts b/apps/api/src/favorites/dto/create-favorite.dto.ts new file mode 100644 index 0000000..8d2db34 --- /dev/null +++ b/apps/api/src/favorites/dto/create-favorite.dto.ts @@ -0,0 +1,32 @@ +import { + IsInt, + IsNotEmpty, + IsOptional, + IsString, + IsUrl, + IsUUID, +} from 'class-validator'; + +/** + * DTO for creating a new FavoriteLink. + * widgetId scopes the link to a specific widget instance (T-08-06 / Pitfall 3). + */ +export class CreateFavoriteDto { + @IsUUID() + widgetId!: string; + + @IsString() + @IsNotEmpty() + title!: string; + + @IsUrl() + url!: string; + + @IsOptional() + @IsString() + iconUrl?: string; + + @IsOptional() + @IsInt() + position?: number; +} diff --git a/apps/api/src/favorites/dto/update-favorite.dto.ts b/apps/api/src/favorites/dto/update-favorite.dto.ts new file mode 100644 index 0000000..e17c57b --- /dev/null +++ b/apps/api/src/favorites/dto/update-favorite.dto.ts @@ -0,0 +1,27 @@ +import { IsInt, IsOptional, IsString, IsUrl } from 'class-validator'; + +/** + * DTO for updating an existing FavoriteLink. + * All fields are optional — only provided fields are updated. + * iconUrl accepts null explicitly to clear a stored icon. + */ +export class UpdateFavoriteDto { + @IsOptional() + @IsString() + title?: string; + + @IsOptional() + @IsUrl() + url?: string; + + /** + * iconUrl can be a string (updated URL), null (clear icon), or absent (no change). + * No strict type validation so null passes through to Prisma. + */ + @IsOptional() + iconUrl?: string | null; + + @IsOptional() + @IsInt() + position?: number; +} diff --git a/apps/api/src/favorites/favorites.controller.ts b/apps/api/src/favorites/favorites.controller.ts new file mode 100644 index 0000000..be8c988 --- /dev/null +++ b/apps/api/src/favorites/favorites.controller.ts @@ -0,0 +1,88 @@ +import { + Body, + Controller, + Delete, + ForbiddenException, + Get, + Param, + Patch, + Post, + Query, + Req, +} from '@nestjs/common'; +import { Request } from 'express'; +import { CreateFavoriteDto } from './dto/create-favorite.dto'; +import { UpdateFavoriteDto } from './dto/update-favorite.dto'; +import { FavoritesService } from './favorites.service'; + +/** + * REST controller for per-user, per-widget favorite links. + * + * All routes are protected by the global JwtAuthGuard + TenantGuard. + * + * Routes: + * - GET /favorites?widgetId= — list favorites for a widget instance + * - POST /favorites — create a favorite (triggers server-side icon discovery) + * - PATCH /favorites/:id — update a favorite (ownership verified in service) + * - DELETE /favorites/:id — delete a favorite (ownership verified in service) + */ +@Controller('favorites') +export class FavoritesController { + constructor(private readonly favoritesService: FavoritesService) {} + + private extractContext(req: Request) { + const userId = (req as any).user?.id; + const tenantId = + (req as any).tenantId ?? (req as any).user?.tenantId; + + if (!tenantId) { + throw new ForbiddenException('No tenant context'); + } + if (!userId) { + throw new ForbiddenException('No user context'); + } + + return { userId, tenantId }; + } + + @Get() + async list( + @Query('widgetId') widgetId: string, + @Req() req: Request, + ) { + const { userId } = this.extractContext(req); + + return this.favoritesService.list(userId, widgetId); + } + + @Post() + async create( + @Body() dto: CreateFavoriteDto, + @Req() req: Request, + ) { + const { userId, tenantId } = this.extractContext(req); + + return this.favoritesService.create(userId, tenantId, dto); + } + + @Patch(':id') + async update( + @Param('id') id: string, + @Body() dto: UpdateFavoriteDto, + @Req() req: Request, + ) { + const { userId } = this.extractContext(req); + + return this.favoritesService.update(id, userId, dto); + } + + @Delete(':id') + async remove( + @Param('id') id: string, + @Req() req: Request, + ) { + const { userId } = this.extractContext(req); + + return this.favoritesService.remove(id, userId); + } +} diff --git a/apps/api/src/favorites/favorites.module.ts b/apps/api/src/favorites/favorites.module.ts new file mode 100644 index 0000000..585f7ee --- /dev/null +++ b/apps/api/src/favorites/favorites.module.ts @@ -0,0 +1,20 @@ +import { Module } from '@nestjs/common'; +import { FavoritesController } from './favorites.controller'; +import { FavoritesService } from './favorites.service'; +import { IconDiscoveryService } from './icon-discovery.service'; + +/** + * NestJS module for per-user favorite link management. + * + * Provides: + * - FavoritesController: REST API under /favorites (CRUD scoped by user + widget) + * - FavoritesService: Business logic with userId-scoped queries (T-08-06) + * - IconDiscoveryService: Server-side icon/favicon discovery with SSRF protection (T-08-05) + * + * PrismaModule is global — no need to re-import here. + */ +@Module({ + controllers: [FavoritesController], + providers: [FavoritesService, IconDiscoveryService], +}) +export class FavoritesModule {} diff --git a/apps/api/src/favorites/favorites.service.ts b/apps/api/src/favorites/favorites.service.ts new file mode 100644 index 0000000..8e4c4a0 --- /dev/null +++ b/apps/api/src/favorites/favorites.service.ts @@ -0,0 +1,96 @@ +import { Injectable, NotFoundException } from '@nestjs/common'; +import { PrismaService } from '../prisma/prisma.service'; +import { CreateFavoriteDto } from './dto/create-favorite.dto'; +import { UpdateFavoriteDto } from './dto/update-favorite.dto'; +import { IconDiscoveryService } from './icon-discovery.service'; + +/** + * Service for managing per-user, per-widget favorite links. + * + * Access control (T-08-06 / Pitfall 3): + * - Every query is scoped by userId (prevents cross-user access). + * - list() additionally scopes by widgetId so each widget instance has its own set. + * - update() and remove() verify userId ownership before mutating. + */ +@Injectable() +export class FavoritesService { + constructor( + private readonly prisma: PrismaService, + private readonly iconDiscovery: IconDiscoveryService, + ) {} + + /** + * Returns all favorites for a user's widget instance, ordered by position asc. + * Scoped by userId AND widgetId (Pitfall 3 — separate widgets must not share links). + */ + async list(userId: string, widgetId: string) { + return this.prisma.favoriteLink.findMany({ + where: { userId, widgetId }, + orderBy: [{ position: 'asc' }, { title: 'asc' }], + }); + } + + /** + * Creates a new favorite link. + * If iconUrl is not provided, triggers server-side icon discovery with SSRF protection. + */ + async create(userId: string, tenantId: string, dto: CreateFavoriteDto) { + let iconUrl = dto.iconUrl ?? null; + + // Server-side icon discovery (D-05) — only when caller did not supply an icon + if (!iconUrl) { + iconUrl = await this.iconDiscovery.discoverFavoriteIconUrl(dto.url); + } + + return this.prisma.favoriteLink.create({ + data: { + userId, + tenantId, + widgetId: dto.widgetId, + title: dto.title, + url: dto.url, + iconUrl, + position: dto.position ?? 0, + }, + }); + } + + /** + * Updates an existing favorite. + * Verifies userId ownership before applying changes (T-08-06). + * Accepts null as an explicit value for iconUrl (clears stored icon). + */ + async update(id: string, userId: string, dto: UpdateFavoriteDto) { + const link = await this.prisma.favoriteLink.findUnique({ where: { id } }); + + if (!link || link.userId !== userId) { + throw new NotFoundException('FavoriteLink not found'); + } + + const data: Record = {}; + + if (dto.title !== undefined) data.title = dto.title; + if (dto.url !== undefined) data.url = dto.url; + if ('iconUrl' in dto) data.iconUrl = dto.iconUrl; // Allows explicit null + if (dto.position !== undefined) data.position = dto.position; + + return this.prisma.favoriteLink.update({ + where: { id }, + data, + }); + } + + /** + * Deletes a favorite link. + * Verifies userId ownership before deleting (T-08-06). + */ + async remove(id: string, userId: string) { + const link = await this.prisma.favoriteLink.findUnique({ where: { id } }); + + if (!link || link.userId !== userId) { + throw new NotFoundException('FavoriteLink not found'); + } + + await this.prisma.favoriteLink.delete({ where: { id } }); + } +} diff --git a/apps/api/src/favorites/icon-discovery.service.ts b/apps/api/src/favorites/icon-discovery.service.ts new file mode 100644 index 0000000..9cb9839 --- /dev/null +++ b/apps/api/src/favorites/icon-discovery.service.ts @@ -0,0 +1,283 @@ +import { Injectable } from '@nestjs/common'; +import { lookup } from 'dns/promises'; +import { isIP } from 'net'; + +/** + * Server-side favicon / icon discovery with SSRF protection (T-08-05). + * + * Ported from personal-dashboard/src/lib/favorite-icons.ts. + * Security guards: + * - DNS resolves every URL (including redirects) and checks for private IP ranges + * - redirect: 'manual' — follows redirects manually so each hop is re-validated + * - 4000 ms AbortController timeout per request + * - 200 000 character HTML cap to prevent memory exhaustion (T-08-09) + * - Blocked hostnames: localhost, .local, 0.0.0.0 + */ + +const FALLBACK_ICON_PATH = '/favicon.ico'; +const HTML_FETCH_TIMEOUT_MS = 4000; +const MAX_REDIRECTS = 2; +const MAX_HTML_CHARS = 200000; + +type FetchHtmlResult = { + html: string; + finalUrl: string; +}; + +function isPrivateIpv4(address: string): boolean { + const parts = address.split('.').map((part) => Number.parseInt(part, 10)); + + if ( + parts.length !== 4 || + parts.some( + (part) => !Number.isInteger(part) || part < 0 || part > 255, + ) + ) { + return true; + } + + const [a, b] = parts; + + return ( + a === 0 || + a === 10 || + a === 127 || + (a === 100 && b !== undefined && b >= 64 && b <= 127) || + (a === 169 && b === 254) || + (a === 172 && b !== undefined && b >= 16 && b <= 31) || + (a === 192 && b === 168) || + (a === 192 && b === 0) || + (a === 198 && (b === 18 || b === 19)) || + a >= 224 + ); +} + +function isPrivateIpv6(address: string): boolean { + const lower = address.toLowerCase(); + + return ( + lower === '::' || + lower === '::1' || + lower.startsWith('fc') || + lower.startsWith('fd') || + lower.startsWith('fe80:') || + lower.startsWith('::ffff:127.') || + lower.startsWith('::ffff:10.') || + lower.startsWith('::ffff:192.168.') + ); +} + +function isPrivateIpAddress(address: string): boolean { + const version = isIP(address); + + if (version === 4) return isPrivateIpv4(address); + if (version === 6) return isPrivateIpv6(address); + + return true; // Unknown format → block by default +} + +function isBlockedHostname(hostname: string): boolean { + const h = hostname.trim().toLowerCase(); + + return ( + h === 'localhost' || + h.endsWith('.localhost') || + h.endsWith('.local') || + h === '0.0.0.0' + ); +} + +async function isPublicHttpUrl(url: URL): Promise { + if (url.protocol !== 'http:' && url.protocol !== 'https:') { + return false; + } + + if (isBlockedHostname(url.hostname)) { + return false; + } + + const directVersion = isIP(url.hostname); + + if (directVersion !== 0) { + return !isPrivateIpAddress(url.hostname); + } + + try { + const addresses = await lookup(url.hostname, { all: true }); + + if (addresses.length === 0) return false; + + return addresses.every((a) => !isPrivateIpAddress(a.address)); + } catch { + return false; + } +} + +function getOriginFaviconUrl(pageUrl: string): string { + try { + const url = new URL(pageUrl); + + return new URL(FALLBACK_ICON_PATH, url.origin).toString(); + } catch { + return FALLBACK_ICON_PATH; + } +} + +function parseAttributes(tag: string): Record { + const attrs: Record = {}; + const re = /([a-zA-Z_:.-]+)\s*=\s*("([^"]*)"|'([^']*)'|([^\s"'>]+))/g; + let m: RegExpExecArray | null; + + while ((m = re.exec(tag)) !== null) { + const key = m[1].toLowerCase(); + const value = m[3] ?? m[4] ?? m[5] ?? ''; + + attrs[key] = value; + } + + return attrs; +} + +function toAbsoluteUrl(value: string | undefined, base: string): string | null { + if (!value) return null; + + try { + const url = new URL(value, base); + + if (url.protocol !== 'http:' && url.protocol !== 'https:') return null; + + return url.toString(); + } catch { + return null; + } +} + +function extractIconFromHtml(html: string, baseUrl: string): string | null { + const linkTags = html.match(/]*>/gi) ?? []; + const metaTags = html.match(/]*>/gi) ?? []; + + const linkCandidates = linkTags + .map((tag) => parseAttributes(tag)) + .map((a) => ({ + rel: (a.rel ?? '').toLowerCase(), + href: toAbsoluteUrl(a.href, baseUrl), + })) + .filter((c) => c.href); + + const appleTouchIcon = linkCandidates.find((c) => + c.rel.includes('apple-touch-icon'), + )?.href; + + if (appleTouchIcon) return appleTouchIcon; + + const icon = linkCandidates.find((c) => + c.rel.split(/\s+/).includes('icon'), + )?.href; + + if (icon) return icon; + + const shortcutIcon = linkCandidates.find((c) => + c.rel.includes('shortcut icon'), + )?.href; + + if (shortcutIcon) return shortcutIcon; + + const imageSrc = linkCandidates.find((c) => + c.rel.includes('image_src'), + )?.href; + + if (imageSrc) return imageSrc; + + const metaImage = metaTags + .map((tag) => parseAttributes(tag)) + .map((a) => ({ + property: (a.property ?? a.name ?? '').toLowerCase(), + content: toAbsoluteUrl(a.content, baseUrl), + })) + .find( + (c) => + c.content && + (c.property === 'og:image' || + c.property === 'og:logo' || + c.property === 'twitter:image'), + )?.content; + + return metaImage ?? null; +} + +async function fetchHtml(pageUrl: URL): Promise { + let currentUrl = pageUrl; + + for (let redirectCount = 0; redirectCount <= MAX_REDIRECTS; redirectCount++) { + const isPublic = await isPublicHttpUrl(currentUrl); + + if (!isPublic) return null; + + const controller = new AbortController(); + const timeout = setTimeout(() => controller.abort(), HTML_FETCH_TIMEOUT_MS); + + try { + const response = await fetch(currentUrl.toString(), { + redirect: 'manual', // SSRF: follow manually so each hop is re-validated + signal: controller.signal, + headers: { + Accept: 'text/html,application/xhtml+xml,*/*', + 'User-Agent': 'tessera/1.0', + }, + }); + + if (response.status >= 300 && response.status < 400) { + const location = response.headers.get('location'); + + if (!location) return null; + + currentUrl = new URL(location, currentUrl); + continue; + } + + if (!response.ok) return null; + + const contentType = response.headers.get('content-type') ?? ''; + + if (!contentType.toLowerCase().includes('text/html')) return null; + + const html = await response.text(); + + return { + html: html.slice(0, MAX_HTML_CHARS), // T-08-09: HTML cap + finalUrl: currentUrl.toString(), + }; + } catch { + return null; + } finally { + clearTimeout(timeout); + } + } + + return null; +} + +@Injectable() +export class IconDiscoveryService { + /** + * Discover the best icon URL for a given web page URL. + * Falls back to /favicon.ico when discovery fails or URL is private. + * + * SSRF protection: every URL and redirect target is validated against + * private IP ranges, blocked hostnames, and forced-proxy vectors (T-08-05). + */ + async discoverFavoriteIconUrl(pageUrl: string): Promise { + const fallback = getOriginFaviconUrl(pageUrl); + + try { + const url = new URL(pageUrl); + const htmlResult = await fetchHtml(url); + + if (!htmlResult) return fallback; + + return extractIconFromHtml(htmlResult.html, htmlResult.finalUrl) ?? fallback; + } catch { + return fallback; + } + } +} From cc6f5ae8935c8f186f519d5d11be365c348e155b Mon Sep 17 00:00:00 2001 From: Schalli Date: Wed, 1 Jul 2026 10:34:11 +0200 Subject: [PATCH 3/4] feat(08-03): FavoritesWidget frontend + API client + page.tsx wiring (GREEN) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - favorites-api.ts: FavoriteLink type + fetchFavorites/createFavorite/updateFavorite/deleteFavorite all use credentials: include and API_URL/favorites - favorites-widget.tsx: list/grid view, inline add/edit/delete in edit mode, icon + letter fallback, rel=noreferrer + target=_blank, no dangerouslySetInnerHTML (T-08-07) - useEffect deps fixed to [instanceId] only — excludes t() to prevent re-fetch on each render - page.tsx: wireFavoritesWidget(FavoritesWidget) wired - Full test suite: 81/81 pass (17 test files) - Web TypeScript: clean --- apps/web/src/app/(portal)/page.tsx | 4 +- .../widgets/favorites-widget.test.tsx | 53 +- .../dashboard/widgets/favorites-widget.tsx | 462 ++++++++++++++++++ apps/web/src/lib/favorites-api.ts | 81 +++ 4 files changed, 579 insertions(+), 21 deletions(-) create mode 100644 apps/web/src/components/dashboard/widgets/favorites-widget.tsx create mode 100644 apps/web/src/lib/favorites-api.ts diff --git a/apps/web/src/app/(portal)/page.tsx b/apps/web/src/app/(portal)/page.tsx index d371c93..14a51cd 100644 --- a/apps/web/src/app/(portal)/page.tsx +++ b/apps/web/src/app/(portal)/page.tsx @@ -5,13 +5,14 @@ import { useTranslations } from 'next-intl'; import { DashboardGrid } from '@/components/dashboard/dashboard-grid'; import { EditModeToggle } from '@/components/dashboard/edit-mode-toggle'; import { WidgetCatalogModal } from '@/components/dashboard/widget-catalog-modal'; -import { wireClockWidget, wireSearchWidget, wireCalendarWidget, wireNoteWidget, wireCalculatorWidget, wireStopwatchWidget } from '@/components/dashboard/widget-registry'; +import { wireClockWidget, wireSearchWidget, wireCalendarWidget, wireNoteWidget, wireCalculatorWidget, wireStopwatchWidget, wireFavoritesWidget } from '@/components/dashboard/widget-registry'; import { ClockWidget } from '@/components/dashboard/widgets/clock-widget'; import { SearchWidget } from '@/components/dashboard/widgets/search-widget'; import { CalendarWidget } from '@/components/dashboard/widgets/calendar-widget'; import { NoteWidget } from '@/components/dashboard/widgets/note-widget'; import { CalculatorWidget } from '@/components/dashboard/widgets/calculator-widget'; import { StopwatchWidget } from '@/components/dashboard/widgets/stopwatch-widget'; +import { FavoritesWidget } from '@/components/dashboard/widgets/favorites-widget'; import { useDashboardStore } from '@/lib/stores/dashboard-store'; import type { WidgetType } from '@/components/dashboard/widget-registry'; @@ -22,6 +23,7 @@ wireCalendarWidget(CalendarWidget); wireNoteWidget(NoteWidget); wireCalculatorWidget(CalculatorWidget); wireStopwatchWidget(StopwatchWidget); +wireFavoritesWidget(FavoritesWidget); export default function DashboardPage() { const t = useTranslations('widgets'); diff --git a/apps/web/src/components/dashboard/widgets/favorites-widget.test.tsx b/apps/web/src/components/dashboard/widgets/favorites-widget.test.tsx index c8ee1e9..628d19d 100644 --- a/apps/web/src/components/dashboard/widgets/favorites-widget.test.tsx +++ b/apps/web/src/components/dashboard/widgets/favorites-widget.test.tsx @@ -132,25 +132,28 @@ describe('FavoritesWidget', () => { const titleInput = screen.getByPlaceholderText('favorites.addTitle'); const urlInput = screen.getByPlaceholderText('favorites.addUrl'); - await act(async () => { + // Use sync fireEvent — RTL will flush state updates automatically + act(() => { fireEvent.change(titleInput, { target: { value: 'New Link' } }); fireEvent.change(urlInput, { target: { value: 'https://example.com' } }); }); - // Submit the form (button with text 'favorites.addButton') + // Submit the form const addButton = screen.getByRole('button', { name: /favorites\.addButton/i }); - await act(async () => { + act(() => { fireEvent.click(addButton); }); - // createFavorite must be called with the widgetId and the entered values - expect(mockCreate).toHaveBeenCalledWith( - expect.objectContaining({ - widgetId: 'fav-1', - title: 'New Link', - url: 'https://example.com', - }), - ); + // waitFor polls until the async chain (createFavorite → setFavorites) completes + await waitFor(() => { + expect(mockCreate).toHaveBeenCalledWith( + expect.objectContaining({ + widgetId: 'fav-1', + title: 'New Link', + url: 'https://example.com', + }), + ); + }); // The new link title should appear in the list await waitFor(() => { @@ -175,29 +178,37 @@ describe('FavoritesWidget', () => { const editButtons = screen.getAllByRole('button', { name: /favorites\.editButton/i, }); - await act(async () => { + act(() => { fireEvent.click(editButtons[0]); }); // Change the title in the inline edit form + await waitFor(() => { + expect(screen.getByDisplayValue('GitHub')).toBeInTheDocument(); + }); const editTitleInput = screen.getByDisplayValue('GitHub'); - await act(async () => { + act(() => { fireEvent.change(editTitleInput, { target: { value: 'GitHub Updated' } }); }); // Click Save + await waitFor(() => { + expect(screen.getByRole('button', { name: /favorites\.saveButton/i })).toBeInTheDocument(); + }); const saveButton = screen.getByRole('button', { name: /favorites\.saveButton/i, }); - await act(async () => { + act(() => { fireEvent.click(saveButton); }); // updateFavorite called with the favorite id and new title - expect(mockUpdate).toHaveBeenCalledWith( - 'fav-id-1', - expect.objectContaining({ title: 'GitHub Updated' }), - ); + await waitFor(() => { + expect(mockUpdate).toHaveBeenCalledWith( + 'fav-id-1', + expect.objectContaining({ title: 'GitHub Updated' }), + ); + }); }); it('delete: clicking delete calls deleteFavorite with id and removes the row', async () => { @@ -217,12 +228,14 @@ describe('FavoritesWidget', () => { const deleteButtons = screen.getAllByRole('button', { name: /favorites\.deleteButton/i, }); - await act(async () => { + act(() => { fireEvent.click(deleteButtons[0]); }); // deleteFavorite called with the correct id - expect(mockDelete).toHaveBeenCalledWith('fav-id-1'); + await waitFor(() => { + expect(mockDelete).toHaveBeenCalledWith('fav-id-1'); + }); // The deleted favorite is removed from the list await waitFor(() => { diff --git a/apps/web/src/components/dashboard/widgets/favorites-widget.tsx b/apps/web/src/components/dashboard/widgets/favorites-widget.tsx new file mode 100644 index 0000000..9332cad --- /dev/null +++ b/apps/web/src/components/dashboard/widgets/favorites-widget.tsx @@ -0,0 +1,462 @@ +'use client'; + +import { FormEvent, useEffect, useMemo, useState } from 'react'; +import { useTranslations } from 'next-intl'; +import { updateWidgetConfig } from '@/lib/dashboard-api'; +import { + createFavorite, + deleteFavorite, + fetchFavorites, + updateFavorite, + type FavoriteLink, +} from '@/lib/favorites-api'; +import type { WidgetProps } from '@/components/dashboard/widget-registry'; + +/** + * FavoritesWidget — persistent per-widget list of favorite links (DASH-09). + * + * Features: + * - Loads favorites scoped to this widget instance via instanceId (Pitfall 3) + * - Add / edit / delete in edit mode with inline forms + * - List view (default, D-03) and grid view switchable in edit mode + * - Server-side icon discovery (letter fallback when iconUrl is null) + * - Links open in new tab with rel="noreferrer" (T-08-08 open-redirect mitigation) + * - No dangerouslySetInnerHTML (T-08-07 XSS mitigation) + */ +export function FavoritesWidget({ + instanceId, + config, + isEditMode, +}: WidgetProps) { + const t = useTranslations('widgets'); + + const [favorites, setFavorites] = useState([]); + const [loading, setLoading] = useState(true); + const [error, setError] = useState(null); + + // View mode: read from config, default 'list' (D-03) + const [viewMode, setViewMode] = useState<'list' | 'grid'>( + (config.viewMode as 'list' | 'grid') ?? 'list', + ); + + // Add-form state + const [newTitle, setNewTitle] = useState(''); + const [newUrl, setNewUrl] = useState(''); + const [newIconUrl, setNewIconUrl] = useState(''); + + // Inline edit state + const [editingId, setEditingId] = useState(null); + const [editTitle, setEditTitle] = useState(''); + const [editUrl, setEditUrl] = useState(''); + const [editIconUrl, setEditIconUrl] = useState(''); + + // Sorted favorites: position asc, then title asc + const sortedFavorites = useMemo( + () => + [...favorites].sort((a, b) => { + if (a.position !== b.position) return a.position - b.position; + return a.title.localeCompare(b.title); + }), + [favorites], + ); + + useEffect(() => { + let cancelled = false; + + async function load() { + setLoading(true); + setError(null); + try { + const data = await fetchFavorites(instanceId); + if (!cancelled) setFavorites(data); + } catch { + // Use a stable error key — t is excluded from deps intentionally + if (!cancelled) setError('favorites.error'); + } finally { + if (!cancelled) setLoading(false); + } + } + + void load(); + + return () => { + cancelled = true; + }; + // instanceId is the only meaningful dependency — t is stable at runtime + // and excluded to prevent re-fetching on every render (mock creates new fn) + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [instanceId]); + + function getFallbackLetter(title: string): string { + const clean = title.trim(); + return clean ? clean.slice(0, 1).toUpperCase() : '?'; + } + + // --- View mode toggle (edit mode only, D-03) --- + function handleViewMode(next: 'list' | 'grid') { + setViewMode(next); + void updateWidgetConfig(instanceId, { viewMode: next }); + } + + // --- Add favorite --- + async function handleAdd(e: FormEvent) { + e.preventDefault(); + const cleanTitle = newTitle.trim(); + const cleanUrl = newUrl.trim(); + const cleanIconUrl = newIconUrl.trim(); + + if (!cleanTitle || !cleanUrl) return; + + try { + const created = await createFavorite({ + widgetId: instanceId, + title: cleanTitle, + url: cleanUrl, + iconUrl: cleanIconUrl || undefined, + }); + setFavorites((prev) => [...prev, created]); + setNewTitle(''); + setNewUrl(''); + setNewIconUrl(''); + } catch { + setError(t('favorites.error')); + } + } + + // --- Edit favorite --- + function startEdit(fav: FavoriteLink) { + setEditingId(fav.id); + setEditTitle(fav.title); + setEditUrl(fav.url); + setEditIconUrl(fav.iconUrl ?? ''); + setError(null); + } + + function cancelEdit() { + setEditingId(null); + setEditTitle(''); + setEditUrl(''); + setEditIconUrl(''); + } + + async function handleSaveEdit(id: string) { + const cleanTitle = editTitle.trim(); + const cleanUrl = editUrl.trim(); + const cleanIconUrl = editIconUrl.trim(); + + if (!cleanTitle || !cleanUrl) return; + + try { + const updated = await updateFavorite(id, { + title: cleanTitle, + url: cleanUrl, + iconUrl: cleanIconUrl || null, + }); + setFavorites((prev) => prev.map((f) => (f.id === id ? updated : f))); + cancelEdit(); + } catch { + setError(t('favorites.error')); + } + } + + // --- Delete favorite --- + async function handleDelete(id: string) { + try { + await deleteFavorite(id); + setFavorites((prev) => prev.filter((f) => f.id !== id)); + if (editingId === id) cancelEdit(); + } catch { + setError(t('favorites.error')); + } + } + + // --- Render --- + return ( +
+ {/* View mode toggle (edit mode only) */} + {isEditMode && ( +
+ + +
+ )} + + {/* Status messages */} + {loading && ( +

{t('favorites.loading')}

+ )} + {error && ( +

{error}

+ )} + + {/* Favorites list / grid */} + {!loading && sortedFavorites.length === 0 && ( +

{t('favorites.empty')}

+ )} + + {!loading && sortedFavorites.length > 0 && ( + viewMode === 'grid' ? ( +
+ {sortedFavorites.map((fav) => ( + + ))} +
+ ) : ( +
+ {sortedFavorites.map((fav) => ( + + ))} +
+ ) + )} + + {/* Add form (edit mode only, D-04) */} + {isEditMode && ( +
void handleAdd(e)} + className="flex flex-col gap-1 pt-1 border-t border-border widgetNoDrag" + > + setNewTitle(e.target.value)} + placeholder={t('favorites.addTitle')} + /> + setNewUrl(e.target.value)} + placeholder={t('favorites.addUrl')} + /> + +
+ )} +
+ ); +} + +// --- FavoriteTile sub-component --- + +type FavoriteTileProps = { + fav: FavoriteLink; + isEditMode: boolean; + editingId: string | null; + editTitle: string; + editUrl: string; + editIconUrl: string; + getFallbackLetter: (title: string) => string; + onStartEdit: (fav: FavoriteLink) => void; + onCancelEdit: () => void; + onSaveEdit: (id: string) => Promise; + onDelete: (id: string) => Promise; + onEditTitleChange: (v: string) => void; + onEditUrlChange: (v: string) => void; + onEditIconUrlChange: (v: string) => void; + t: (key: string) => string; +}; + +function FavoriteTile({ + fav, + isEditMode, + editingId, + editTitle, + editUrl, + editIconUrl, + getFallbackLetter, + onStartEdit, + onCancelEdit, + onSaveEdit, + onDelete, + onEditTitleChange, + onEditUrlChange, + onEditIconUrlChange, + t, +}: FavoriteTileProps) { + const isEditing = editingId === fav.id; + + return ( +
+ {/* Main link row */} +
+ {/* Anchor — opens in new tab, no server-side redirect (T-08-08) */} + isEditMode && e.preventDefault()} // block navigation in edit mode + > + {/* Icon container with letter fallback (T-08-07 — no dangerouslySetInnerHTML) */} +
+ + {getFallbackLetter(fav.title)} + + {fav.iconUrl && ( + { + (e.currentTarget as HTMLImageElement).style.display = 'none'; + }} + /> + )} +
+ + {fav.title} +
+ + {/* Action buttons (edit mode only, D-04) */} + {isEditMode && !isEditing && ( +
+ + +
+ )} +
+ + {/* Inline edit form */} + {isEditMode && isEditing && ( +
+ onEditTitleChange(e.target.value)} + placeholder={t('favorites.addTitle')} + /> + onEditUrlChange(e.target.value)} + placeholder={t('favorites.addUrl')} + /> + onEditIconUrlChange(e.target.value)} + placeholder="Logo-URL (optional)" + /> +
+ + +
+
+ )} +
+ ); +} diff --git a/apps/web/src/lib/favorites-api.ts b/apps/web/src/lib/favorites-api.ts new file mode 100644 index 0000000..bbef3c7 --- /dev/null +++ b/apps/web/src/lib/favorites-api.ts @@ -0,0 +1,81 @@ +/** + * Favorites API client functions. + * Mirrors the NestJS FavoritesController routes (08-03). + * All calls use credentials: 'include' for cookie-based auth. + */ + +const API_URL = process.env.NEXT_PUBLIC_API_URL || 'http://localhost:3001'; + +export interface FavoriteLink { + id: string; + widgetId: string; + title: string; + url: string; + iconUrl: string | null; + position: number; +} + +/** + * Fetch all favorite links for a specific widget instance. + * The widgetId parameter scopes the query to the correct widget (Pitfall 3). + */ +export async function fetchFavorites(widgetId: string): Promise { + const res = await fetch( + `${API_URL}/favorites?widgetId=${encodeURIComponent(widgetId)}`, + { credentials: 'include' }, + ); + if (!res.ok) throw new Error('Failed to fetch favorites'); + + return res.json(); +} + +/** + * Create a new favorite link. + * Server-side icon discovery runs automatically if iconUrl is not provided. + */ +export async function createFavorite(payload: { + widgetId: string; + title: string; + url: string; + iconUrl?: string; +}): Promise { + const res = await fetch(`${API_URL}/favorites`, { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + credentials: 'include', + body: JSON.stringify(payload), + }); + if (!res.ok) throw new Error('Failed to create favorite'); + + return res.json(); +} + +/** + * Update an existing favorite link. + * Pass iconUrl: null to clear a stored icon. + */ +export async function updateFavorite( + id: string, + payload: Partial<{ title: string; url: string; iconUrl: string | null; position: number }>, +): Promise { + const res = await fetch(`${API_URL}/favorites/${encodeURIComponent(id)}`, { + method: 'PATCH', + headers: { 'Content-Type': 'application/json' }, + credentials: 'include', + body: JSON.stringify(payload), + }); + if (!res.ok) throw new Error('Failed to update favorite'); + + return res.json(); +} + +/** + * Delete a favorite link by id. + */ +export async function deleteFavorite(id: string): Promise { + const res = await fetch(`${API_URL}/favorites/${encodeURIComponent(id)}`, { + method: 'DELETE', + credentials: 'include', + }); + if (!res.ok) throw new Error('Failed to delete favorite'); +} From f7d4818c0af8252895a8e8e2df366061c6de76fb Mon Sep 17 00:00:00 2001 From: Schalli Date: Wed, 1 Jul 2026 10:38:28 +0200 Subject: [PATCH 4/4] docs(08-03): complete Favorites widget plan summary --- .../08-03-SUMMARY.md | 172 ++++++++++++++++++ 1 file changed, 172 insertions(+) create mode 100644 .planning/phases/08-dashboard-widgets-vollimplementierung/08-03-SUMMARY.md diff --git a/.planning/phases/08-dashboard-widgets-vollimplementierung/08-03-SUMMARY.md b/.planning/phases/08-dashboard-widgets-vollimplementierung/08-03-SUMMARY.md new file mode 100644 index 0000000..96f1b81 --- /dev/null +++ b/.planning/phases/08-dashboard-widgets-vollimplementierung/08-03-SUMMARY.md @@ -0,0 +1,172 @@ +--- +phase: 08-dashboard-widgets-vollimplementierung +plan: "03" +subsystem: dashboard-widgets +tags: [favorites, widget, tdd, dashboard, persistence, ssrf, i18n, icons] +status: complete + +dependency_graph: + requires: + - 08-01 (wireFavoritesWidget, WIDGET_CONSTRAINTS.favorites, i18n keys) + - 08-02 (no direct dep, wave-3 parallel) + provides: + - FavoritesWidget component (add/edit/delete, list/grid, letter fallback) + - FavoriteLink Prisma model (userId/tenantId/widgetId scoped) + - FavoritesModule NestJS (CRUD + SSRF icon discovery) + - favorites-api.ts client (fetchFavorites/createFavorite/updateFavorite/deleteFavorite) + - wireFavoritesWidget() now connected in page.tsx + affects: + - apps/api/prisma/schema.prisma + - apps/api/src/app.module.ts + - apps/web/src/app/(portal)/page.tsx + +tech_stack: + added: [] + patterns: + - TDD Red/Green cycle (FavoritesWidget behavioral contract) + - SSRF protection ported from personal-dashboard/favorite-icons.ts + - redirect: 'manual' with per-hop DNS check (T-08-05) + - userId + widgetId scoping for all DB queries (T-08-06 / Pitfall 3) + - useEffect dep array excludes t() to prevent re-fetch on each render + - letter fallback span always in DOM (img layered on top via absolute positioning) + +key_files: + created: + - apps/api/src/favorites/favorites.module.ts + - apps/api/src/favorites/favorites.controller.ts + - apps/api/src/favorites/favorites.service.ts + - apps/api/src/favorites/icon-discovery.service.ts + - apps/api/src/favorites/dto/create-favorite.dto.ts + - apps/api/src/favorites/dto/update-favorite.dto.ts + - apps/web/src/lib/favorites-api.ts + - apps/web/src/components/dashboard/widgets/favorites-widget.tsx + - apps/web/src/components/dashboard/widgets/favorites-widget.test.tsx + modified: + - apps/api/prisma/schema.prisma (FavoriteLink model added) + - apps/api/src/app.module.ts (FavoritesModule registered) + - apps/web/src/app/(portal)/page.tsx (wireFavoritesWidget added) + +decisions: + - "useEffect deps: [instanceId] only — t() mock creates new fn ref on each render, causing re-fetch loops in tests; excluded intentionally" + - "dangerouslySetInnerHTML comment-only occurrences (2) are explanation comments, not actual usage — XSS threat T-08-07 mitigated" + - "Letter fallback span always rendered (absolute positioned), img layered on top and hidden via onError — avoids flash-of-no-icon" + - "Sync act() + waitFor() pattern in tests — async act() hangs when component uses void async handlers; waitFor polls until promise chain settles" + +metrics: + duration: "~25 minutes" + completed: "2026-07-01" + tasks_completed: 3 + tests_added: 7 + files_created: 9 + files_modified: 3 +--- + +# Phase 08 Plan 03: Favorites Widget Summary + +Favorites-Widget Vollimplementierung (DASH-09) via TDD Red/Green-Zyklus: persistente Favoritenliste mit server-seitiger Icon-Discovery (SSRF-Schutz), Inline-CRUD im Edit-Modus, Liste/Kacheln-Ansicht und Buchstaben-Fallback. + +## What Was Built + +- **FavoriteLink Prisma Model**: Felder userId, tenantId, widgetId, title, url, iconUrl (nullable), position. Indizes auf userId, tenantId, widgetId (Pitfall 3 — jede Widget-Instanz hat ihre eigene Favoritenliste). + +- **IconDiscoveryService** (`icon-discovery.service.ts`): Port aus `personal-dashboard/src/lib/favorite-icons.ts`. SSRF-Schutz: DNS-Aufloesung jeder URL und jedes Redirect-Ziels, private IPv4/IPv6-Ranges blockiert, blocked hostnames (localhost/.local/0.0.0.0), `redirect: 'manual'` mit manueller Redirect-Verfolgung bis MAX_REDIRECTS=2, 4000ms AbortController-Timeout, 200k-Zeichen HTML-Cap (T-08-05, T-08-09). User-Agent geaendert auf `tessera/1.0`. + +- **FavoritesModule** (NestJS): FavoritesController (GET/POST/PATCH/DELETE /favorites), FavoritesService (list/create/update/remove — alle Queries scoped by userId, T-08-06), IconDiscoveryService als Provider. In AppModule registriert. + +- **favorites-api.ts**: FavoriteLink-Typ + fetchFavorites(widgetId)/createFavorite(payload)/updateFavorite(id, payload)/deleteFavorite(id). Alle Requests mit `credentials: 'include'` und API_URL/favorites. + +- **FavoritesWidget** (`favorites-widget.tsx`): 'use client', useTranslations. Laedt Favoriten beim Mount via fetchFavorites(instanceId). Sortierung nach position asc + title asc. Listenansicht (default) und Kachelansicht (umschaltbar im Edit-Modus, persists via updateWidgetConfig). Inline-CRUD im Edit-Modus: '+'-Formular, Bearbeiten-Inline-Form, Loeschen-Button. Icons: `` mit onError-Hide + `` als Buchstaben-Fallback. Links: target="_blank" rel="noreferrer" (T-08-08). Kein dangerouslySetInnerHTML (T-08-07). + +- **page.tsx Wiring**: `wireFavoritesWidget(FavoritesWidget)` hinzugefuegt. + +## Tasks + +| Task | Description | Status | Commit | +|------|-------------|--------|--------| +| 1 | RED: Failing tests fuer FavoritesWidget CRUD + view toggle + letter fallback | Complete | a3bb3f2 | +| 2 | FavoriteLink schema + FavoritesModule (CRUD + SSRF icon discovery) | Complete | 758d246 | +| 3 | GREEN: FavoritesWidget frontend + API client + page.tsx wiring | Complete | cc6f5ae | + +## Test Results + +- **favorites-widget.test.tsx**: 7 Tests — fetchFavorites mit instanceId aufgerufen, empty state, add-Formular, inline edit, delete mit DOM-Entfernung, list/grid toggle, Buchstaben-Fallback +- **Full Web Suite**: 81/81 Tests bestehen (17 Test-Dateien) +- **Web TypeScript**: sauber (0 Fehler) +- **API TypeScript**: sauber (0 Fehler, prisma generate erfolgreich) + +## Deviations from Plan + +### Worktree Fast-Forward (auto-fix, Rule 3) + +**Found during:** Pre-task setup + +**Issue:** Das Worktree-Branch `worktree-agent-a80275c51086517d1` war bei `88db54f` (vor phase-08-Commits), nicht am erwarteten Basis-Commit `4645a5f` (Main nach Wave 2). Phase-08 wave-1 und wave-2 Artefakte (wireFavoritesWidget, WIDGET_CONSTRAINTS, i18n-Keys) fehlten. + +**Fix:** `git merge main --ff-only` — Fast-Forward auf `4645a5f`. Keine Konflikte. Node-Modules-Symlinks danach erstellt. + +**Impact:** Keiner. Alle Plan-01 und Plan-02-Artefakte standen danach vollstaendig zur Verfuegung. + +### useEffect Dependency Array: t() ausgeschlossen (auto-fix, Rule 1) + +**Found during:** Task 3 GREEN — test 'edit' scheiterte bei waitFor (saveButton nicht sichtbar) + +**Issue:** `t()` aus `useTranslations()` war in `useEffect([instanceId, t])`-Abhaengigkeiten. Der Mock erzeugt bei jedem Render eine neue Funktionsreferenz -> useEffect feuert bei jedem State-Update neu -> `setLoading(true)` loescht die geladenen Favoriten. + +**Fix:** Dependency-Array auf `[instanceId]` reduziert; error-Fallback nutzt stabilen String-Key statt `t()`. Kommentar erklaert Entscheidung. + +**Files modified:** `favorites-widget.tsx` (useEffect) + +**Commit:** cc6f5ae + +### Testmuster: Sync act() + waitFor() statt async act() (auto-fix, Rule 1) + +**Found during:** Task 3 GREEN — add/edit/delete Tests timeout nach 5000ms + +**Issue:** `await act(async () => { fireEvent.click(btn); })` bei Komponenten die `void asyncHandler(e)` nutzen: act() wartet nicht auf asynchrone Fortsetzungen in `void`-discarded Promises. + +**Fix:** Interaktions-Events mit sync `act(() => { fireEvent...; })` aufgerufen; assertions in `await waitFor(() => ...)` verschoben. waitFor pollt bis die async-Kette (API-Mock -> setState) abgeschlossen ist. + +**Files modified:** `favorites-widget.test.tsx` + +**Commit:** cc6f5ae + +### dangerouslySetInnerHTML grep-count = 2 (kein Problem) + +Beide Vorkommen sind in **Kommentaren** (Zeile 24 und 354) die erklaeren WARUM dangerouslySetInnerHTML nicht verwendet wird. Kein tatsaechlicher JSX-Attribut-Einsatz. T-08-07 korrekt mitigiert. + +## Known Stubs + +Keine Stubs. FavoritesWidget ist vollstaendig implementiert und mit Backend verbunden. + +## Threat Surface Scan + +Alle Threats aus dem Plan-Threat-Register wurden mitigiert: + +| Threat ID | Status | +|-----------|--------| +| T-08-05 (SSRF via IconDiscoveryService) | Mitigiert — vollstaendiger SSRF-Guard portiert: DNS-Check, private IPs, redirect:manual, 4000ms Timeout, 200k HTML-Cap | +| T-08-06 (Spoofing via FavoritesService) | Mitigiert — jede Query scoped by userId + widgetId; NotFoundException bei Ownership-Mismatch | +| T-08-07 (XSS via icon render) | Mitigiert — iconUrl nur via ``; kein dangerouslySetInnerHTML | +| T-08-08 (open redirect) | Mitigiert — Links mit target="_blank" rel="noreferrer"; kein server-seitiger Redirect | +| T-08-09 (DoS via HTML fetch) | Mitigiert — MAX_HTML_CHARS 200000 Truncation + 4000ms AbortController | + +Keine neuen Sicherheitsoberflaechen eingefuehrt, die nicht im Threat-Modell erwaehnt waren. + +## Self-Check: PASSED + +| Item | Status | +|------|--------| +| favorites-widget.tsx | FOUND | +| favorites-widget.test.tsx | FOUND | +| favorites-api.ts | FOUND | +| favorites.module.ts | FOUND | +| icon-discovery.service.ts | FOUND | +| FavoriteLink in schema.prisma | FOUND | +| FavoritesModule in app.module.ts | FOUND | +| page.tsx: wireFavoritesWidget(FavoritesWidget) | FOUND | +| Commit a3bb3f2 (RED) | FOUND | +| Commit 758d246 (backend) | FOUND | +| Commit cc6f5ae (GREEN) | FOUND | +| Full suite 81/81 | PASSED | +| Web TypeScript: 0 errors | PASSED | +| API TypeScript: 0 errors | PASSED |