Fully autonomous AI Agents system capable of performing complex penetration testing tasks
Go ai-agentsai-security-toolanthropicautonomous-agentsgolanggptgraphqlmulti-agent-systemoffensive-securityopen-sourceopenaipenetration-testingpenetration-testing-toolsreactsecurity-automationsecurity-testingsecurity-toolsself-hosted
refactor: introduce typed axios api wrapper and migrate consumers
Sergey Kozyrenko52825cadebab
diff --git a/frontend/src/features/authentication/password-change-form.tsx b/frontend/src/features/authentication/password-change-form.tsxindex 20bf883a..fe12f3cb 100644--- a/frontend/src/features/authentication/password-change-form.tsx+++ b/frontend/src/features/authentication/password-change-form.tsx@@ -8,21 +8,7 @@ import * as z from 'zod';import { Button } from '@/components/ui/button';import { Form, FormControl, FormDescription, FormField, FormItem, FormLabel, FormMessage } from '@/components/ui/form';import { Input } from '@/components/ui/input';-import { axios } from '@/lib/axios';--interface AxiosErrorResponse {- message?: string;- response?: {- data?: ErrorResponse;- };-}--interface ErrorResponse {- code?: string;- error?: string;- msg?: string;- status?: string;-}+import { api, type ApiErrorResponse, type ApiHttpError } from '@/lib/axios';const passwordChangeSchema = z.object({@@ -98,7 +84,7 @@ export function PasswordChangeForm({setError(null);try {- await axios.put('/user/password', {+ await api.put('/user/password', {confirm_password: values.confirmPassword,current_password: values.currentPassword,password: values.newPassword,@@ -115,16 +101,14 @@ export function PasswordChangeForm({onSuccess();}} catch (err: unknown) {- const error = err as AxiosErrorResponse;- const responseData = error.response?.data;+ const error = err as ApiHttpError;+ const responseData = error.response?.data as ApiErrorResponse | undefined;let errorMessage = 'Failed to change password';- // Always prefer the msg from the response if availableif (responseData?.msg) {errorMessage = responseData.msg;} else if (responseData?.code) {- // Fallback to code-based messagesswitch (responseData.code) {case 'AuthRequired':errorMessage = 'Authentication required';diff --git a/frontend/src/lib/axios.ts b/frontend/src/lib/axios.tsindex 9bd55475..7f784d7c 100644--- a/frontend/src/lib/axios.ts+++ b/frontend/src/lib/axios.ts@@ -1,4 +1,4 @@-import type { AxiosError } from 'axios';+import type { AxiosError, AxiosRequestConfig } from 'axios';import Axios from 'axios';@@ -7,26 +7,72 @@ import { AUTH_STORAGE_KEY } from '@/providers/user-provider';import { Log } from './log';import { getReturnUrlParam } from './utils/auth';+// ── shared API protocol types ────────────────────────────────────────────────+//+// The backend wraps every successful response as { status: 'success', data?: T }+// and every business-level failure as { status: 'error', code?, msg?, error? }.+// HTTP-level failures (4xx/5xx) are rejected by the response interceptor below+// and surface as `ApiHttpError` to the caller.++export interface ApiErrorResponse {+ code?: string;+ error?: string;+ msg?: string;+ status: 'error';+}++/** Shape returned by the response-error interceptor (rejected promise payload). */+export interface ApiHttpError {+ message: string;+ name: string;+ response?: AxiosError['response'];+ stack?: string;+ statusCode?: number;+ statusText?: string;+ warnings?: unknown;+}++export type ApiResponse<T> = ApiErrorResponse | ApiSuccessResponse<T>;++export type ApiResponseStatus = 'error' | 'success';++export interface ApiSuccessResponse<T> {+ data?: T;+ status: 'success';+}++// ── shared instance ──────────────────────────────────────────────────────────++/**+ * Central axios instance for all REST calls in the app.+ *+ * Best practices from https://axios.rest/:+ * - Sets a sensible default `timeout` to avoid hanging requests+ * (override per-call via `{ timeout: 0 }` for long uploads).+ * - Uses `withCredentials` so the session cookie is sent on every request.+ * - The response interceptor unwraps `res.data` on success — every method+ * returns the API payload (typed as `ApiResponse<T>` via the helpers below)+ * instead of the raw `AxiosResponse<T>`.+ */const axios = Axios.create({baseURL: '/api/v1',headers: {'Content-Type': 'application/json',},+ timeout: 30_000,withCredentials: true,});+axios.interceptors.response.use(- (res) => {- return res.data;- },- (err: AxiosError) => {- const error = {+ (res) => res.data,+ (err: AxiosError): Promise<never> => {+ const error: ApiHttpError = {message: err.message,name: err.name,response: err.response,stack: err.stack,statusCode: err.response?.status,statusText: err.response?.statusText,- warnings: undefined,};if (error.statusCode) {@@ -60,7 +106,6 @@ axios.interceptors.response.use(Log.warn('Authentication required.');localStorage.removeItem(AUTH_STORAGE_KEY);- // Redirect to login with current URL preservedconst currentPath = window.location.pathname;if (currentPath !== '/login') {@@ -74,7 +119,6 @@ axios.interceptors.response.use(case 403: {const responseData = err.response?.data as undefined | { code?: string };- // Only redirect to login for auth-related 403 errorsif (responseData?.code === 'AuthRequired' ||responseData?.code === 'NotPermitted' ||@@ -92,7 +136,6 @@ axios.interceptors.response.use(window.location.href = `/login${returnParam}`;}} else {- // For other 403 errors (like invalid password), just logLog.warn(err.response?.data);}@@ -110,4 +153,76 @@ axios.interceptors.response.use(return Promise.reject(error);},);++// ── typed wrapper ────────────────────────────────────────────────────────────+//+// The wrapper hides the awkward `<unknown, ApiResponse<T>>` cast that's needed+// because the response interceptor returns `res.data` directly. Callers write:+//+// const response = await api.post<MyData>('/things', body);+// // response is typed as ApiResponse<MyData>++export const api = {+ delete: <T>(url: string, config?: AxiosRequestConfig) => axios.delete<T, ApiResponse<T>>(url, config),+ get: <T>(url: string, config?: AxiosRequestConfig) => axios.get<T, ApiResponse<T>>(url, config),+ patch: <T, B = unknown>(url: string, body?: B, config?: AxiosRequestConfig) =>+ axios.patch<T, ApiResponse<T>, B>(url, body, config),+ post: <T, B = unknown>(url: string, body?: B, config?: AxiosRequestConfig) =>+ axios.post<T, ApiResponse<T>, B>(url, body, config),+ put: <T, B = unknown>(url: string, body?: B, config?: AxiosRequestConfig) =>+ axios.put<T, ApiResponse<T>, B>(url, body, config),+};++// ── helpers ──────────────────────────────────────────────────────────────────++export const isApiSuccess = <T>(response: ApiResponse<T>): response is ApiSuccessResponse<T> =>+ response.status === 'success';++/** Returns `response.data`, or throws if the API marked the response as an error. */+export const unwrapApiResponse = <T>(response: ApiResponse<T>): T => {+ if (!isApiSuccess(response) || response.data == null) {+ const message = !isApiSuccess(response) ? (response.msg ?? response.error) : undefined;++ throw new Error(message ?? 'Unexpected response from server');+ }++ return response.data;+};++/**+ * Extracts a human-readable message from an unknown error thrown by axios calls.+ *+ * Lookup order:+ * 1. `response.data.msg` — backend-provided message,+ * 2. `statusFallbacks[status]` — caller-provided defaults per HTTP status,+ * 3. `error.message` — generic axios/network message,+ * 4. `fallback` — last-resort string.+ */+export const getApiErrorMessage = (+ error: unknown,+ fallback: string,+ statusFallbacks?: Record<number, string>,+): string => {+ if (!error || typeof error !== 'object') {+ return fallback;+ }++ const err = error as ApiHttpError;+ const status = err.statusCode ?? err.response?.status;+ const responseData = err.response?.data;+ const responseMsg =+ responseData && typeof responseData === 'object' ? (responseData as ApiErrorResponse).msg : undefined;++ if (responseMsg) {+ return responseMsg;+ }++ if (status != null && statusFallbacks?.[status]) {+ return statusFallbacks[status];+ }++ return err.message || fallback;+};++export default axios;export { axios };diff --git a/frontend/src/providers/user-provider.tsx b/frontend/src/providers/user-provider.tsxindex 5e8408c2..492f8e74 100644--- a/frontend/src/providers/user-provider.tsx+++ b/frontend/src/providers/user-provider.tsx@@ -4,9 +4,9 @@ import { createContext, use, useCallback, useEffect, useState } from 'react';import { useLocation, useNavigate } from 'react-router-dom';import { toast } from 'sonner';-import type { AuthInfo, AuthInfoResponse } from '@/models/info';+import type { AuthInfo } from '@/models/info';-import { axios } from '@/lib/axios';+import { api } from '@/lib/axios';import { getReturnUrlParam } from '@/lib/utils/auth';import { baseUrl } from '@/models/api';@@ -80,7 +80,7 @@ export const UserProvider = ({ children }: { children: ReactNode }) => {// Load from API for guests or when localStorage is emptyif (shouldFetchFromApi) {try {- const info: AuthInfoResponse = await axios.get('/info');+ const info = await api.get<AuthInfo>('/info');if (info?.status === 'success' && info.data) {// Set authInfo even for guest (contains providers list)@@ -126,7 +126,7 @@ export const UserProvider = ({ children }: { children: ReactNode }) => {const refreshAuthInfo = useCallback(async () => {try {- const info: AuthInfoResponse = await axios.get('/info');+ const info = await api.get<AuthInfo>('/info');if (info?.status === 'success' && info.data) {setAuth(info.data);@@ -151,7 +151,7 @@ export const UserProvider = ({ children }: { children: ReactNode }) => {const finalReturnUrl = returnUrl || getReturnUrlParam(currentPath);try {- await axios.get('/auth/logout');+ await api.get('/auth/logout');toast.success('Successfully logged out');} catch {toast.error('Logout failed, but clearing local session');@@ -166,10 +166,7 @@ export const UserProvider = ({ children }: { children: ReactNode }) => {const login = useCallback(async (credentials: LoginCredentials): Promise<LoginResult> => {try {- const loginResponse = await axios.post<unknown, { data?: unknown; error?: string; status: string }>(- '/auth/login',- credentials,- );+ const loginResponse = await api.post<unknown>('/auth/login', credentials);if (loginResponse?.status !== 'success') {const errorMessage = 'Invalid login or password';@@ -179,7 +176,7 @@ export const UserProvider = ({ children }: { children: ReactNode }) => {}// After login, backend set cookie, so we need to get fresh auth info- const infoResponse: AuthInfoResponse = await axios.get('/info');+ const infoResponse = await api.get<AuthInfo>('/info');if (infoResponse?.status !== 'success' || !infoResponse.data) {const errorMessage = 'Failed to load user information';@@ -295,7 +292,7 @@ export const UserProvider = ({ children }: { children: ReactNode }) => {if (event.data.status === 'success') {try {- const info: AuthInfoResponse = await axios.get('/info');+ const info = await api.get<AuthInfo>('/info');if (info?.status === 'success' && info.data?.type === 'user') {setAuth(info.data);@@ -342,7 +339,7 @@ export const UserProvider = ({ children }: { children: ReactNode }) => {}try {- const info: AuthInfoResponse = await axios.get('/info', {+ const info = await api.get<AuthInfo>('/info', {params: {refresh_cookie: true,},