tududi/frontend/utils/sharesService.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

94 lines
2.7 KiB
TypeScript

import { getApiPath } from '../config/paths';
import { getCsrfToken } from './csrfService';
export type AccessLevel = 'ro' | 'rw';
export interface ShareGrantRequest {
resource_type: 'project' | 'task' | 'note' | 'area' | 'tag';
resource_uid: string;
target_user_email: string;
access_level: AccessLevel;
}
export async function grantShare(req: ShareGrantRequest): Promise<void> {
const res = await fetch(getApiPath('shares'), {
method: 'POST',
credentials: 'include',
headers: {
'Content-Type': 'application/json',
Accept: 'application/json',
'x-csrf-token': await getCsrfToken(),
},
body: JSON.stringify(req),
});
if (!res.ok) {
let message = 'Failed to share resource';
try {
const body = await res.json();
if (body?.error) message = body.error;
} catch {
// ignore non-JSON error bodies
}
throw new Error(message);
}
}
export interface ListSharesResponseRow {
user_id: number;
access_level: AccessLevel | 'owner';
created_at: string | null;
email?: string | null;
avatar_image?: string | null;
is_owner?: boolean;
}
export async function listShares(
resource_type: ShareGrantRequest['resource_type'],
resource_uid: string
): Promise<ListSharesResponseRow[]> {
const params = new URLSearchParams({ resource_type, resource_uid });
const res = await fetch(getApiPath(`shares?${params.toString()}`), {
method: 'GET',
credentials: 'include',
headers: { Accept: 'application/json' },
});
if (!res.ok) {
let message = 'Failed to load shares';
try {
const body = await res.json();
if (body?.error) message = body.error;
} catch {
// ignore non-JSON error bodies
}
throw new Error(message);
}
const data = await res.json();
return data.shares || [];
}
export async function revokeShare(
resource_type: ShareGrantRequest['resource_type'],
resource_uid: string,
target_user_id: number
): Promise<void> {
const res = await fetch(getApiPath('shares'), {
method: 'DELETE',
credentials: 'include',
headers: {
'Content-Type': 'application/json',
Accept: 'application/json',
'x-csrf-token': await getCsrfToken(),
},
body: JSON.stringify({ resource_type, resource_uid, target_user_id }),
});
if (!res.ok) {
let message = 'Failed to revoke share';
try {
const body = await res.json();
if (body?.error) message = body.error;
} catch {
// ignore non-JSON error bodies
}
throw new Error(message);
}
}