tududi/frontend/utils/urlService.ts
Chris 6c9902b584
fix: add CSRF token support to frontend requests (#1025)
This commit implements CSRF token support for all session-based API
requests to fix the "CSRF token missing" and "CSRF token mismatch" errors
introduced after CSRF protection was added in commit 62c4cc84.

Changes:
- Created csrfService.ts utility for fetching and caching CSRF tokens
- Added getPostHeadersWithCsrf() helper to authUtils for async token injection
- Updated all service files (*Service.ts) to include CSRF tokens in POST/PUT/PATCH/DELETE requests
- Updated components with inline fetch calls to use getCsrfToken()
- Fixed CSRF middleware to use single lusca instance instead of creating new instances per request
- Improved generateToken() to use req.csrfToken() when available
- Added CalDAV path exemption to CSRF protection

Technical details:
- CSRF tokens are fetched from /api/csrf-token endpoint
- Tokens are cached and reused across requests to avoid unnecessary fetches
- Tokens are included in x-csrf-token header for state-changing requests
- Public endpoints (login, register) remain exempt from CSRF protection
- Bearer token authentication remains exempt from CSRF protection

Files modified:
- Backend: app.js, middleware/csrf.js
- Frontend: 13 service files, 8 component files
- New file: frontend/utils/csrfService.ts

This ensures all session-based requests properly include CSRF tokens while
maintaining support for API token authentication.
2026-04-14 15:06:56 +03:00

68 lines
1.9 KiB
TypeScript

import { handleAuthResponse, getPostHeadersWithCsrf } from './authUtils';
import { getApiPath } from '../config/paths';
export interface UrlTitleResult {
url: string;
title: string | null;
image?: string | null;
description?: string | null;
found?: boolean;
error?: string;
}
export const extractUrlTitle = async (url: string): Promise<UrlTitleResult> => {
try {
const response = await fetch(
getApiPath(`url/title?url=${encodeURIComponent(url)}`),
{
credentials: 'include',
headers: {
Accept: 'application/json',
},
}
);
await handleAuthResponse(response, 'Failed to extract URL title');
return await response.json();
} catch (error) {
console.error('Error extracting URL title:', error);
return { url, title: null, error: (error as Error).message };
}
};
export const extractTitleFromText = async (
text: string
): Promise<UrlTitleResult | null> => {
try {
const response = await fetch(getApiPath('url/extract-from-text'), {
method: 'POST',
credentials: 'include',
headers: await getPostHeadersWithCsrf(),
body: JSON.stringify({ text }),
});
await handleAuthResponse(response, 'Failed to extract title from text');
const result = await response.json();
if (result.found === false) {
return null;
}
return result;
} catch (error) {
console.error('Error extracting title from text:', error);
return null;
}
};
export const isUrl = (text: string): boolean => {
const trimmed = text.trim();
if (!trimmed || trimmed.length > 2000 || !trimmed.includes('.')) {
return false;
}
const urlRegex =
/^(https?:\/\/)?[a-z0-9][a-z0-9.-]*\.[a-z]{2,}(:[0-9]+)?(\/\S*)?$/i;
return urlRegex.test(trimmed);
};