Compare commits
2 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| bcae59626f | |||
| f851305d78 |
@@ -0,0 +1,25 @@
|
||||
import crypto from "node:crypto";
|
||||
import type { Request, Response, NextFunction } from "express";
|
||||
|
||||
const SAFE_METHODS = new Set(["GET", "HEAD", "OPTIONS", "TRACE"]);
|
||||
|
||||
export function getCsrfToken(req: Request): string {
|
||||
if (!req.session.csrfToken) {
|
||||
req.session.csrfToken = crypto.randomBytes(24).toString("hex");
|
||||
}
|
||||
return req.session.csrfToken;
|
||||
}
|
||||
|
||||
export function csrfProtection(req: Request, res: Response, next: NextFunction): void {
|
||||
if (SAFE_METHODS.has(req.method.toUpperCase())) {
|
||||
next();
|
||||
return;
|
||||
}
|
||||
const provided = req.headers["x-csrf-token"];
|
||||
const token = getCsrfToken(req);
|
||||
if (typeof provided === "string" && provided && provided === token) {
|
||||
next();
|
||||
return;
|
||||
}
|
||||
res.status(403).json({ error: "CSRF token missing or invalid" });
|
||||
}
|
||||
@@ -8,6 +8,7 @@ import { logger } from "../lib/logger";
|
||||
import { writeAuditLog } from "../lib/audit";
|
||||
import { loginRateLimit, passwordRateLimit } from "../lib/rate-limit";
|
||||
import { getEntitlements, requireFeature } from "../middleware/feature";
|
||||
import { getCsrfToken } from "../middleware/csrf";
|
||||
|
||||
const router: IRouter = Router();
|
||||
|
||||
@@ -109,6 +110,10 @@ router.get("/auth/mode", (_req, res): void => {
|
||||
res.json({ mode: isOidcConfigured() ? "oidc" : "local" });
|
||||
});
|
||||
|
||||
router.get("/auth/csrf", (req, res): void => {
|
||||
res.json({ token: getCsrfToken(req) });
|
||||
});
|
||||
|
||||
router.post("/auth/login", loginRateLimit, async (req, res): Promise<void> => {
|
||||
if (isOidcConfigured()) {
|
||||
res.status(400).json({ error: "Use OIDC login when Keycloak is configured." });
|
||||
|
||||
@@ -8,9 +8,12 @@ import usersRouter from "./users";
|
||||
import auditRouter from "./audit";
|
||||
import costsRouter from "./costs";
|
||||
import adminRouter from "./admin";
|
||||
import { csrfProtection } from "../middleware/csrf";
|
||||
|
||||
const router: IRouter = Router();
|
||||
|
||||
router.use(csrfProtection);
|
||||
|
||||
router.use(authRouter);
|
||||
router.use(healthRouter);
|
||||
router.use(toolsRouter);
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { Router, type IRouter } from "express";
|
||||
import { eq, desc, asc, sql, and, not, isNull, inArray } from "drizzle-orm";
|
||||
import { eq, desc, asc, sql, and, not, isNull, inArray, type SQL } from "drizzle-orm";
|
||||
import { z } from "zod";
|
||||
import { db, toolsTable, ratingsTable, toolRelationsTable } from "@workspace/db";
|
||||
import {
|
||||
@@ -57,21 +57,23 @@ router.get("/tools", async (req, res): Promise<void> => {
|
||||
const tagList = (tags ?? "").split(",").map((t) => t.trim()).filter(Boolean);
|
||||
const featureList = (features ?? "").split(",").map((f) => f.trim()).filter(Boolean);
|
||||
|
||||
let query = db.select().from(toolsTable).where(isNull(toolsTable.deletedAt)).$dynamic();
|
||||
const conditions: SQL[] = [isNull(toolsTable.deletedAt)];
|
||||
if (category) {
|
||||
query = query.where(eq(toolsTable.category, category));
|
||||
conditions.push(eq(toolsTable.category, category));
|
||||
}
|
||||
if (search) {
|
||||
const escaped = search.replace(/[%_\\]/g, (m) => `\\${m}`);
|
||||
query = query.where(sql`${toolsTable.name} ilike ${`%${escaped}%`} escape '\\'`);
|
||||
conditions.push(sql`${toolsTable.name} ilike ${`%${escaped}%`} escape '\\'`);
|
||||
}
|
||||
if (tagList.length > 0) {
|
||||
query = query.where(sql`${toolsTable.tags} @> ARRAY[${sql.join(tagList.map((t) => sql`${t}`), sql`, `)}]::text[]`);
|
||||
conditions.push(sql`${toolsTable.tags} @> ARRAY[${sql.join(tagList.map((t) => sql`${t}`), sql`, `)}]::text[]`);
|
||||
}
|
||||
if (featureList.length > 0) {
|
||||
query = query.where(sql`${toolsTable.features} @> ARRAY[${sql.join(featureList.map((f) => sql`${f}`), sql`, `)}]::text[]`);
|
||||
conditions.push(sql`${toolsTable.features} @> ARRAY[${sql.join(featureList.map((f) => sql`${f}`), sql`, `)}]::text[]`);
|
||||
}
|
||||
|
||||
const query = db.select().from(toolsTable).where(and(...conditions));
|
||||
|
||||
const tools = await query.orderBy(desc(toolsTable.createdAt));
|
||||
|
||||
const toolIds = tools.map((t) => t.id);
|
||||
|
||||
+1
@@ -14,5 +14,6 @@ declare module "express-session" {
|
||||
codeVerifier?: string;
|
||||
returnTo?: string;
|
||||
oidcState?: string;
|
||||
csrfToken?: string;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
import { Switch, Route, Router as WouterRouter } from "wouter";
|
||||
import { useEffect } from "react";
|
||||
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
|
||||
import { I18nextProvider } from "react-i18next";
|
||||
import i18n from "@/i18n";
|
||||
import { loadCsrfToken } from "@/lib/csrf";
|
||||
import { Toaster } from "@/components/ui/toaster";
|
||||
import { TooltipProvider } from "@/components/ui/tooltip";
|
||||
|
||||
@@ -50,6 +52,9 @@ function Router() {
|
||||
}
|
||||
|
||||
function App() {
|
||||
useEffect(() => {
|
||||
void loadCsrfToken();
|
||||
}, []);
|
||||
return (
|
||||
<I18nextProvider i18n={i18n}>
|
||||
<QueryClientProvider client={queryClient}>
|
||||
|
||||
@@ -127,7 +127,12 @@
|
||||
"relatedTools": "Ähnliche Tools",
|
||||
"costs": "Kosten",
|
||||
"addCost": "Kosten hinzufügen",
|
||||
"recentRatings": "Letzte Bewertungen"
|
||||
"recentRatings": "Letzte Bewertungen",
|
||||
"deleteConfirmTitle": "Dieses Tool löschen?",
|
||||
"deleteToTrash": "Dies verschiebt {{name}} in den Papierkorb. Es kann später wiederhergestellt werden.",
|
||||
"deletePermanent": "Dies entfernt {{name}} dauerhaft inklusive aller Bewertungen. Das kann nicht rückgängig gemacht werden.",
|
||||
"deleting": "Löschen…",
|
||||
"deleteAction": "Löschen"
|
||||
},
|
||||
"compare": {
|
||||
"title": "Tools vergleichen",
|
||||
|
||||
@@ -127,7 +127,12 @@
|
||||
"relatedTools": "Related Tools",
|
||||
"costs": "Costs",
|
||||
"addCost": "Add Cost",
|
||||
"recentRatings": "Recent Ratings"
|
||||
"recentRatings": "Recent Ratings",
|
||||
"deleteConfirmTitle": "Delete this tool?",
|
||||
"deleteToTrash": "This will move {{name}} to the trash. It can be restored later.",
|
||||
"deletePermanent": "This will permanently remove {{name}} and all its ratings. This cannot be undone.",
|
||||
"deleting": "Deleting…",
|
||||
"deleteAction": "Delete"
|
||||
},
|
||||
"compare": {
|
||||
"title": "Compare Tools",
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
import { setCsrfTokenGetter } from "@workspace/api-client-react";
|
||||
|
||||
let token: string | null = null;
|
||||
|
||||
setCsrfTokenGetter(() => token);
|
||||
|
||||
export function getCsrfToken(): string | null {
|
||||
return token;
|
||||
}
|
||||
|
||||
export async function loadCsrfToken(): Promise<string | null> {
|
||||
try {
|
||||
const res = await fetch(`/api/auth/csrf`, {
|
||||
credentials: "include",
|
||||
});
|
||||
if (!res.ok) {
|
||||
token = null;
|
||||
return null;
|
||||
}
|
||||
const data = (await res.json()) as { token?: string };
|
||||
token = data.token ?? null;
|
||||
return token;
|
||||
} catch {
|
||||
token = null;
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -6,6 +6,7 @@ import { Button } from "@/components/ui/button";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Label } from "@/components/ui/label";
|
||||
import { PasswordInput } from "@/components/password-input";
|
||||
import { loadCsrfToken } from "@/lib/csrf";
|
||||
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from "@/components/ui/card";
|
||||
import { ThemeToggle } from "@/components/theme-toggle";
|
||||
import { Wrench, AlertCircle } from "lucide-react";
|
||||
@@ -33,6 +34,7 @@ export default function Login() {
|
||||
{
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries();
|
||||
void loadCsrfToken();
|
||||
setLocation(returnTo);
|
||||
},
|
||||
onError: (err) => {
|
||||
|
||||
@@ -914,23 +914,23 @@ export default function ToolDetail() {
|
||||
<AlertDialog open={deleteOpen} onOpenChange={setDeleteOpen}>
|
||||
<AlertDialogContent>
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle>Delete this tool?</AlertDialogTitle>
|
||||
<AlertDialogTitle>{t("detail.deleteConfirmTitle")}</AlertDialogTitle>
|
||||
<AlertDialogDescription>
|
||||
{hasTrash ? (
|
||||
<>This will move <span className="font-medium">{tool?.name}</span> to the trash. It can be restored later.</>
|
||||
<>{t("detail.deleteToTrash", { name: tool?.name })}</>
|
||||
) : (
|
||||
<>This will permanently remove <span className="font-medium">{tool?.name}</span> and all its ratings. This cannot be undone.</>
|
||||
<>{t("detail.deletePermanent", { name: tool?.name })}</>
|
||||
)}
|
||||
</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogCancel>Cancel</AlertDialogCancel>
|
||||
<AlertDialogCancel>{t("common.cancel")}</AlertDialogCancel>
|
||||
<AlertDialogAction
|
||||
className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
|
||||
onClick={handleDelete}
|
||||
disabled={deleteTool.isPending}
|
||||
>
|
||||
{deleteTool.isPending ? "Deleting…" : "Delete"}
|
||||
{deleteTool.isPending ? t("detail.deleting") : t("detail.deleteAction")}
|
||||
</AlertDialogAction>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
|
||||
@@ -17,6 +17,7 @@ const DEFAULT_JSON_ACCEPT = "application/json, application/problem+json";
|
||||
|
||||
let _baseUrl: string | null = null;
|
||||
let _authTokenGetter: AuthTokenGetter | null = null;
|
||||
let _csrfTokenGetter: (() => string | null) | null = null;
|
||||
|
||||
/**
|
||||
* Set a base URL that is prepended to every relative request URL
|
||||
@@ -44,6 +45,15 @@ export function setAuthTokenGetter(getter: AuthTokenGetter | null): void {
|
||||
_authTokenGetter = getter;
|
||||
}
|
||||
|
||||
/**
|
||||
* Register a getter that supplies a CSRF token. Before every state-changing
|
||||
* fetch an `X-CSRF-Token` header is attached when the getter returns a value.
|
||||
* Pass `null` to clear the getter.
|
||||
*/
|
||||
export function setCsrfTokenGetter(getter: (() => string | null) | null): void {
|
||||
_csrfTokenGetter = getter;
|
||||
}
|
||||
|
||||
function isRequest(input: RequestInfo | URL): input is Request {
|
||||
return typeof Request !== "undefined" && input instanceof Request;
|
||||
}
|
||||
@@ -349,6 +359,14 @@ export async function customFetch<T = unknown>(
|
||||
headers.set("accept", DEFAULT_JSON_ACCEPT);
|
||||
}
|
||||
|
||||
// Attach CSRF token for state-changing requests, unless one is already set.
|
||||
if (_csrfTokenGetter && !headers.has("x-csrf-token")) {
|
||||
const csrf = _csrfTokenGetter();
|
||||
if (csrf) {
|
||||
headers.set("x-csrf-token", csrf);
|
||||
}
|
||||
}
|
||||
|
||||
// Attach bearer token when an auth getter is configured and no
|
||||
// Authorization header has been explicitly provided.
|
||||
if (_authTokenGetter && !headers.has("authorization")) {
|
||||
|
||||
@@ -30,6 +30,10 @@ export interface AuthMode {
|
||||
mode: AuthModeMode;
|
||||
}
|
||||
|
||||
export interface CsrfToken {
|
||||
token: string;
|
||||
}
|
||||
|
||||
export interface LocalLoginInput {
|
||||
username: string;
|
||||
password: string;
|
||||
|
||||
@@ -26,6 +26,7 @@ import type {
|
||||
AuthUser,
|
||||
CategoryStats,
|
||||
ChangePasswordInput,
|
||||
CsrfToken,
|
||||
EmptyTrash200,
|
||||
ErrorResponse,
|
||||
GetRatingDistributionParams,
|
||||
@@ -1906,6 +1907,83 @@ export function useGetAuthMode<TData = Awaited<ReturnType<typeof getAuthMode>>,
|
||||
|
||||
|
||||
|
||||
export const getGetCsrfTokenUrl = () => {
|
||||
|
||||
|
||||
|
||||
|
||||
return `/api/auth/csrf`
|
||||
}
|
||||
|
||||
/**
|
||||
* @summary Get a CSRF token for state-changing requests
|
||||
*/
|
||||
export const getCsrfToken = async ( options?: RequestInit): Promise<CsrfToken> => {
|
||||
|
||||
return customFetch<CsrfToken>(getGetCsrfTokenUrl(),
|
||||
{
|
||||
...options,
|
||||
method: 'GET'
|
||||
|
||||
|
||||
}
|
||||
);}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
export const getGetCsrfTokenQueryKey = () => {
|
||||
return [
|
||||
`/api/auth/csrf`
|
||||
] as const;
|
||||
}
|
||||
|
||||
|
||||
export const getGetCsrfTokenQueryOptions = <TData = Awaited<ReturnType<typeof getCsrfToken>>, TError = ErrorType<unknown>>( options?: { query?:UseQueryOptions<Awaited<ReturnType<typeof getCsrfToken>>, TError, TData>, request?: SecondParameter<typeof customFetch>}
|
||||
) => {
|
||||
|
||||
const {query: queryOptions, request: requestOptions} = options ?? {};
|
||||
|
||||
const queryKey = queryOptions?.queryKey ?? getGetCsrfTokenQueryKey();
|
||||
|
||||
|
||||
|
||||
const queryFn: QueryFunction<Awaited<ReturnType<typeof getCsrfToken>>> = ({ signal }) => getCsrfToken({ signal, ...requestOptions });
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
return { queryKey, queryFn, ...queryOptions} as UseQueryOptions<Awaited<ReturnType<typeof getCsrfToken>>, TError, TData> & { queryKey: QueryKey }
|
||||
}
|
||||
|
||||
export type GetCsrfTokenQueryResult = NonNullable<Awaited<ReturnType<typeof getCsrfToken>>>
|
||||
export type GetCsrfTokenQueryError = ErrorType<unknown>
|
||||
|
||||
|
||||
/**
|
||||
* @summary Get a CSRF token for state-changing requests
|
||||
*/
|
||||
|
||||
export function useGetCsrfToken<TData = Awaited<ReturnType<typeof getCsrfToken>>, TError = ErrorType<unknown>>(
|
||||
options?: { query?:UseQueryOptions<Awaited<ReturnType<typeof getCsrfToken>>, TError, TData>, request?: SecondParameter<typeof customFetch>}
|
||||
|
||||
): UseQueryResult<TData, TError> & { queryKey: QueryKey } {
|
||||
|
||||
const queryOptions = getGetCsrfTokenQueryOptions(options)
|
||||
|
||||
const query = useQuery(queryOptions) as UseQueryResult<TData, TError> & { queryKey: QueryKey };
|
||||
|
||||
return { ...query, queryKey: queryOptions.queryKey };
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
export const getLocalLoginUrl = () => {
|
||||
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
export * from "./generated/api";
|
||||
export * from "./generated/api.schemas";
|
||||
export { setBaseUrl, setAuthTokenGetter, customFetch } from "./custom-fetch";
|
||||
export { setBaseUrl, setAuthTokenGetter, setCsrfTokenGetter, customFetch } from "./custom-fetch";
|
||||
export type { AuthTokenGetter } from "./custom-fetch";
|
||||
|
||||
@@ -570,6 +570,19 @@ paths:
|
||||
schema:
|
||||
$ref: "#/components/schemas/AuthMode"
|
||||
|
||||
/auth/csrf:
|
||||
get:
|
||||
operationId: getCsrfToken
|
||||
tags: [auth]
|
||||
summary: Get a CSRF token for state-changing requests
|
||||
responses:
|
||||
"200":
|
||||
description: CSRF token
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: "#/components/schemas/CsrfToken"
|
||||
|
||||
/auth/login:
|
||||
post:
|
||||
operationId: localLogin
|
||||
@@ -942,6 +955,13 @@ components:
|
||||
type: string
|
||||
enum: [oidc, local]
|
||||
|
||||
CsrfToken:
|
||||
type: object
|
||||
required: [token]
|
||||
properties:
|
||||
token:
|
||||
type: string
|
||||
|
||||
LocalLoginInput:
|
||||
type: object
|
||||
required: [username, password]
|
||||
|
||||
@@ -445,6 +445,14 @@ export const GetAuthModeResponse = zod.object({
|
||||
})
|
||||
|
||||
|
||||
/**
|
||||
* @summary Get a CSRF token for state-changing requests
|
||||
*/
|
||||
export const GetCsrfTokenResponse = zod.object({
|
||||
"token": zod.string()
|
||||
})
|
||||
|
||||
|
||||
/**
|
||||
* @summary Local username/password login
|
||||
*/
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
/**
|
||||
* Generated by orval v8.9.1 🍺
|
||||
* Do not edit manually.
|
||||
* Api
|
||||
* ToolRate API — Tool listing and rating platform
|
||||
* OpenAPI spec version: 0.1.0
|
||||
*/
|
||||
|
||||
export interface CsrfToken {
|
||||
token: string;
|
||||
}
|
||||
@@ -15,6 +15,7 @@ export * from './authUserRole';
|
||||
export * from './authUserTier';
|
||||
export * from './categoryStats';
|
||||
export * from './changePasswordInput';
|
||||
export * from './csrfToken';
|
||||
export * from './emptyTrash200';
|
||||
export * from './errorResponse';
|
||||
export * from './getRatingDistributionParams';
|
||||
|
||||
Reference in New Issue
Block a user