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
This commit is contained in:
@@ -233,3 +233,20 @@ model SmtpConfig {
|
|||||||
createdAt DateTime @default(now())
|
createdAt DateTime @default(now())
|
||||||
updatedAt DateTime @updatedAt
|
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])
|
||||||
|
}
|
||||||
|
|||||||
@@ -12,6 +12,7 @@ import { MailModule } from './mail/mail.module';
|
|||||||
import { CalendarModule } from './calendar/calendar.module';
|
import { CalendarModule } from './calendar/calendar.module';
|
||||||
import { DashboardModule } from './dashboard/dashboard.module';
|
import { DashboardModule } from './dashboard/dashboard.module';
|
||||||
import { DkvModule } from './dkv/dkv.module';
|
import { DkvModule } from './dkv/dkv.module';
|
||||||
|
import { FavoritesModule } from './favorites/favorites.module';
|
||||||
import { DomaincheckModule } from './domaincheck/domaincheck.module';
|
import { DomaincheckModule } from './domaincheck/domaincheck.module';
|
||||||
import { ModuleRegistryModule } from './module-registry/module-registry.module';
|
import { ModuleRegistryModule } from './module-registry/module-registry.module';
|
||||||
import { PrismaModule } from './prisma/prisma.module';
|
import { PrismaModule } from './prisma/prisma.module';
|
||||||
@@ -37,6 +38,7 @@ import { UserModule } from './user/user.module';
|
|||||||
CalendarModule,
|
CalendarModule,
|
||||||
SettingsModule,
|
SettingsModule,
|
||||||
DkvModule,
|
DkvModule,
|
||||||
|
FavoritesModule,
|
||||||
],
|
],
|
||||||
providers: [
|
providers: [
|
||||||
// Global JWT guard: all routes require auth unless @Public()
|
// Global JWT guard: all routes require auth unless @Public()
|
||||||
|
|||||||
@@ -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;
|
||||||
|
}
|
||||||
@@ -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;
|
||||||
|
}
|
||||||
@@ -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);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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 {}
|
||||||
@@ -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<string, unknown> = {};
|
||||||
|
|
||||||
|
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 } });
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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<boolean> {
|
||||||
|
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<string, string> {
|
||||||
|
const attrs: Record<string, string> = {};
|
||||||
|
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(/<link\b[^>]*>/gi) ?? [];
|
||||||
|
const metaTags = html.match(/<meta\b[^>]*>/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<FetchHtmlResult | null> {
|
||||||
|
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 <origin>/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<string> {
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user