d39c091cec
Unit Tests / test (push) Successful in 13m15s
Health probes (probe_health/refresh_health) are type-aware: WireGuard checks the last WG handshake timestamp, OpenVPN checks the tun/tap interface, Tor checks the control-port GETINFO, and sshuttle/proxy types do a TCP reachability probe to the remote endpoint. Results are persisted via set_connection_status and wired into the health_monitor_loop so the UI always has a current health snapshot without polling. Per-peer fail-open semantics: VPN, SSH, and proxy connections default to fail-closed (kill-switch stays active even when the tunnel is down). Tor defaults to fail-open. The default can be overridden per-peer via set_peer_failopen/effective_failopen. apply_routes skips the fwmark and kill-switch rules for any fail-open peer whose connection health is not "working", letting traffic fall back to direct routing transparently. New generic admin-only connection CRUD endpoints (GET/POST/PUT/DELETE /api/connectivity/connections, GET /<id>/health, PUT /api/connectivity/peers/<peer>/failopen) are guarded by the existing admin role check. connection.create, connection.update, connection.delete, and peer.failopen are all registered in ROUTE_ACTION_MAP for the audit hook so every change is recorded in the owner-visible change log. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
424 lines
18 KiB
JavaScript
424 lines
18 KiB
JavaScript
import axios from 'axios';
|
|
|
|
// Module-level CSRF token — populated after login or token refresh
|
|
let _csrfToken = null;
|
|
|
|
/**
|
|
* Update the module-level CSRF token.
|
|
* Call this after a successful login with the token returned in the response body.
|
|
*/
|
|
export function setCsrfToken(token) {
|
|
_csrfToken = token;
|
|
}
|
|
|
|
export function getCsrfToken() {
|
|
return _csrfToken;
|
|
}
|
|
|
|
// Create axios instance with base configuration
|
|
const api = axios.create({
|
|
baseURL: import.meta.env.VITE_API_URL || '',
|
|
timeout: 10000,
|
|
withCredentials: true,
|
|
headers: {
|
|
'Content-Type': 'application/json',
|
|
},
|
|
});
|
|
|
|
// Request interceptor — logging + CSRF header injection
|
|
api.interceptors.request.use(
|
|
(config) => {
|
|
console.log(`API Request: ${config.method?.toUpperCase()} ${config.url}`);
|
|
// Attach CSRF token for all state-changing methods
|
|
const method = (config.method || 'get').toLowerCase();
|
|
if (['post', 'put', 'delete', 'patch'].includes(method) && _csrfToken) {
|
|
config.headers = config.headers || {};
|
|
config.headers['X-CSRF-Token'] = _csrfToken;
|
|
}
|
|
return config;
|
|
},
|
|
(error) => {
|
|
console.error('API Request Error:', error);
|
|
return Promise.reject(error);
|
|
}
|
|
);
|
|
|
|
// Response interceptor — error handling + CSRF token refresh on 403
|
|
api.interceptors.response.use(
|
|
(response) => {
|
|
return response;
|
|
},
|
|
async (error) => {
|
|
console.error('API Response Error:', error.response?.data || error.message);
|
|
|
|
// Handle CSRF token expiry: refresh the token and retry the original request once
|
|
if (
|
|
error.response?.status === 403 &&
|
|
error.response?.data?.error === 'CSRF token missing or invalid' &&
|
|
!error.config._csrfRetry
|
|
) {
|
|
try {
|
|
const refreshResp = await api.get('/api/auth/csrf-token');
|
|
const newToken = refreshResp.data?.csrf_token;
|
|
if (newToken) {
|
|
setCsrfToken(newToken);
|
|
// Retry the original request with the new token
|
|
const retryConfig = { ...error.config, _csrfRetry: true };
|
|
retryConfig.headers = retryConfig.headers || {};
|
|
retryConfig.headers['X-CSRF-Token'] = newToken;
|
|
return api(retryConfig);
|
|
}
|
|
} catch (refreshErr) {
|
|
console.error('CSRF token refresh failed:', refreshErr);
|
|
}
|
|
}
|
|
|
|
if (
|
|
error.response?.status === 401 &&
|
|
!error.config.url.includes('/auth/login') &&
|
|
!error.config.url.includes('/auth/me') &&
|
|
window.location.pathname !== '/login'
|
|
) {
|
|
window.location.href = '/login';
|
|
}
|
|
return Promise.reject(error);
|
|
}
|
|
);
|
|
|
|
// Cell Status API
|
|
export const cellAPI = {
|
|
getStatus: () => api.get('/api/status'),
|
|
getConfig: () => api.get('/api/config'),
|
|
updateConfig: (config) => api.put('/api/config', config),
|
|
createBackup: (passphrase = null) => api.post('/api/config/backup', passphrase ? { passphrase } : {}),
|
|
listBackups: () => api.get('/api/config/backups'),
|
|
restoreBackup: (id, services = null, passphrase = null) => {
|
|
const body = {};
|
|
if (services) body.services = services;
|
|
if (passphrase) body.passphrase = passphrase;
|
|
return api.post(`/api/config/restore/${id}`, body);
|
|
},
|
|
deleteBackup: (id) => api.delete(`/api/config/backups/${id}`),
|
|
downloadBackup: (id) => api.get(`/api/config/backups/${id}/download`, { responseType: 'blob' }),
|
|
uploadBackup: (file) => {
|
|
const form = new FormData();
|
|
form.append('file', file);
|
|
return api.post('/api/config/backup/upload', form, { headers: { 'Content-Type': 'multipart/form-data' } });
|
|
},
|
|
exportConfig: (format = 'json', services = null) => {
|
|
const params = { format };
|
|
if (services) params.services = services.join(',');
|
|
return api.get('/api/config/export', { params });
|
|
},
|
|
importConfig: (config, format = 'json', services = null) =>
|
|
api.post('/api/config/import', { config, format, ...(services ? { services } : {}) }),
|
|
getPending: () => api.get('/api/config/pending'),
|
|
cancelPending: () => api.delete('/api/config/pending'),
|
|
applyPending: () => api.post('/api/config/apply'),
|
|
};
|
|
|
|
// Network Services API
|
|
export const networkAPI = {
|
|
getDNSRecords: () => api.get('/api/dns/records'),
|
|
addDNSRecord: (record) => api.post('/api/dns/records', record),
|
|
removeDNSRecord: (record) => api.delete('/api/dns/records', { data: record }),
|
|
getDNSOverview: () => api.get('/api/dns/overview'),
|
|
getNTPStatus: () => api.get('/api/ntp/status'),
|
|
testNetwork: (data) => api.post('/api/network/test', data),
|
|
};
|
|
|
|
// WireGuard API
|
|
export const wireguardAPI = {
|
|
getKeys: () => api.get('/api/wireguard/keys'),
|
|
generatePeerKeys: (data) => api.post('/api/wireguard/keys/peer', data),
|
|
getConfig: () => api.get('/api/wireguard/config'),
|
|
getPeers: () => api.get('/api/wireguard/peers'),
|
|
addPeer: (peer) => api.post('/api/wireguard/peers', peer),
|
|
removePeer: (peer) => api.delete('/api/wireguard/peers', { data: peer }),
|
|
getStatus: () => api.get('/api/wireguard/status'),
|
|
testConnectivity: (data) => api.post('/api/wireguard/connectivity', data),
|
|
updatePeerIP: (data) => api.put('/api/wireguard/peers/ip', data),
|
|
getPeerConfig: (data) => api.post('/api/wireguard/peers/config', data),
|
|
getPeerStatuses: () => api.get('/api/wireguard/peers/statuses'),
|
|
getEndpoint: () => api.get('/api/wireguard/endpoint'),
|
|
setEndpointOverride: (endpoint_override) => api.put('/api/wireguard/endpoint', { endpoint_override }),
|
|
};
|
|
|
|
// Peer Registry API
|
|
export const peerRegistryAPI = {
|
|
getPeers: () => api.get('/api/peers'),
|
|
addPeer: (peer) => api.post('/api/peers', peer),
|
|
removePeer: (peerName) => api.delete(`/api/peers/${peerName}`),
|
|
registerPeer: (data) => api.post('/api/peers/register', data),
|
|
unregisterPeer: (peerName) => api.delete(`/api/peers/${peerName}/unregister`),
|
|
updatePeerIP: (peerName, data) => api.put(`/api/peers/${peerName}/update-ip`, data),
|
|
setRouteVia: (peerName, viaCell) =>
|
|
api.put(`/api/peers/${peerName}/route-via`, { via_cell: viaCell }),
|
|
};
|
|
|
|
// Auth API
|
|
export const authAPI = {
|
|
login: async (username, password) => {
|
|
const response = await api.post('/api/auth/login', { username, password });
|
|
if (response.data?.csrf_token) {
|
|
setCsrfToken(response.data.csrf_token);
|
|
}
|
|
return response;
|
|
},
|
|
logout: () => api.post('/api/auth/logout'),
|
|
me: () => api.get('/api/auth/me'),
|
|
changePassword: (old_password, new_password) => api.post('/api/auth/change-password', { old_password, new_password }),
|
|
adminResetPassword: (username, new_password) => api.post('/api/auth/admin/reset-password', { username, new_password }),
|
|
listUsers: () => api.get('/api/auth/users'),
|
|
getCsrfToken: () => api.get('/api/auth/csrf-token'),
|
|
};
|
|
|
|
// Peer-facing dashboard API
|
|
export const peerAPI = {
|
|
dashboard: () => api.get('/api/peer/dashboard'),
|
|
services: () => api.get('/api/peer/services'),
|
|
};
|
|
|
|
// Email Services API
|
|
export const emailAPI = {
|
|
getUsers: () => api.get('/api/email/users'),
|
|
createUser: (user) => api.post('/api/email/users', user),
|
|
deleteUser: (username) => api.delete(`/api/email/users/${username}`),
|
|
getStatus: () => api.get('/api/email/status'),
|
|
testConnectivity: () => api.get('/api/email/connectivity'),
|
|
sendEmail: (data) => api.post('/api/email/send', data),
|
|
getMailboxInfo: (username) => api.get(`/api/email/mailbox/${username}`),
|
|
};
|
|
|
|
// Calendar Services API
|
|
export const calendarAPI = {
|
|
getUsers: () => api.get('/api/calendar/users'),
|
|
createUser: (user) => api.post('/api/calendar/users', user),
|
|
deleteUser: (username) => api.delete(`/api/calendar/users/${username}`),
|
|
createCalendar: (data) => api.post('/api/calendar/calendars', data),
|
|
addEvent: (data) => api.post('/api/calendar/events', data),
|
|
getEvents: (username, calendarName, params) =>
|
|
api.get(`/api/calendar/events/${username}/${calendarName}`, { params }),
|
|
getStatus: () => api.get('/api/calendar/status'),
|
|
testConnectivity: () => api.get('/api/calendar/connectivity'),
|
|
};
|
|
|
|
// File Services API
|
|
export const fileAPI = {
|
|
getUsers: () => api.get('/api/files/users'),
|
|
createUser: (user) => api.post('/api/files/users', user),
|
|
deleteUser: (username) => api.delete(`/api/files/users/${username}`),
|
|
createFolder: (data) => api.post('/api/files/folders', data),
|
|
deleteFolder: (username, folderPath) => api.delete(`/api/files/folders/${username}/${folderPath}`),
|
|
uploadFile: (username, file, path) => {
|
|
const formData = new FormData();
|
|
formData.append('file', file);
|
|
formData.append('path', path);
|
|
return api.post(`/api/files/upload/${username}`, formData, {
|
|
headers: { 'Content-Type': 'multipart/form-data' },
|
|
});
|
|
},
|
|
downloadFile: (username, filePath) => api.get(`/api/files/download/${username}/${filePath}`),
|
|
deleteFile: (username, filePath) => api.delete(`/api/files/delete/${username}/${filePath}`),
|
|
listFiles: (username, folder = '') => api.get(`/api/files/list/${username}`, { params: { folder } }),
|
|
getStatus: () => api.get('/api/files/status'),
|
|
testConnectivity: () => api.get('/api/files/connectivity'),
|
|
};
|
|
|
|
// Routing API
|
|
export const routingAPI = {
|
|
getStatus: () => api.get('/api/routing/status'),
|
|
// NAT
|
|
getNatRules: () => api.get('/api/routing/nat'),
|
|
addNatRule: (rule) => api.post('/api/routing/nat', rule),
|
|
deleteNatRule: (ruleId) => api.delete(`/api/routing/nat/${ruleId}`),
|
|
// Peer Routes
|
|
getPeerRoutes: () => api.get('/api/routing/peers'),
|
|
addPeerRoute: (route) => api.post('/api/routing/peers', route),
|
|
deletePeerRoute: (peerName) => api.delete(`/api/routing/peers/${peerName}`),
|
|
// Firewall
|
|
getFirewallRules: () => api.get('/api/routing/firewall'),
|
|
addFirewallRule: (rule) => api.post('/api/routing/firewall', rule),
|
|
deleteFirewallRule: (ruleId) => api.delete(`/api/routing/firewall/${ruleId}`),
|
|
getLiveIptables: () => api.get('/api/routing/live-iptables'),
|
|
// Other
|
|
addExitNode: (node) => api.post('/api/routing/exit-nodes', node),
|
|
addBridgeRoute: (route) => api.post('/api/routing/bridge', route),
|
|
addSplitRoute: (route) => api.post('/api/routing/split', route),
|
|
testConnectivity: (data) => api.post('/api/routing/connectivity', data),
|
|
getLogs: (lines = 50) => api.get('/api/routing/logs', { params: { lines } }),
|
|
};
|
|
|
|
// Vault & Trust API
|
|
export const vaultAPI = {
|
|
getStatus: () => api.get('/api/vault/status'),
|
|
getCertificates: () => api.get('/api/vault/certificates'),
|
|
generateCertificate: (data) => api.post('/api/vault/certificates', data),
|
|
revokeCertificate: (commonName) => api.delete(`/api/vault/certificates/${commonName}`),
|
|
getCACertificate: () => api.get('/api/vault/ca/certificate'),
|
|
getAgePublicKey: () => api.get('/api/vault/age/public-key'),
|
|
getTrustedKeys: () => api.get('/api/vault/trust/keys'),
|
|
addTrustedKey: (data) => api.post('/api/vault/trust/keys', data),
|
|
removeTrustedKey: (name) => api.delete(`/api/vault/trust/keys/${name}`),
|
|
verifyTrustChain: (data) => api.post('/api/vault/trust/verify', data),
|
|
getTrustChains: () => api.get('/api/vault/trust/chains'),
|
|
// Secrets management
|
|
listSecrets: () => api.get('/api/vault/secrets'),
|
|
storeSecret: (name, value) => api.post('/api/vault/secrets', { name, value }),
|
|
getSecret: (name) => api.get(`/api/vault/secrets/${name}`),
|
|
deleteSecret: (name) => api.delete(`/api/vault/secrets/${name}`),
|
|
};
|
|
|
|
// Services API
|
|
export const servicesAPI = {
|
|
getAllStatus: () => api.get('/api/services/status'),
|
|
testAllConnectivity: () => api.get('/api/services/connectivity'),
|
|
startService: (serviceName) => api.post(`/api/services/bus/services/${serviceName}/start`),
|
|
stopService: (serviceName) => api.post(`/api/services/bus/services/${serviceName}/stop`),
|
|
restartService: (serviceName) => api.post(`/api/services/bus/services/${serviceName}/restart`),
|
|
listActive: () => api.get('/api/services/active'),
|
|
};
|
|
|
|
// Accounts API (peer service account provisioning via AccountManager)
|
|
export const accountsAPI = {
|
|
list: (serviceId) => api.get(`/api/services/catalog/${serviceId}/accounts`),
|
|
provision: (serviceId, username, password) =>
|
|
api.post(`/api/services/catalog/${serviceId}/accounts`, {
|
|
username,
|
|
...(password ? { password } : {}),
|
|
}),
|
|
deprovision: (serviceId, username) =>
|
|
api.delete(`/api/services/catalog/${serviceId}/accounts/${username}`),
|
|
getCredentials: (serviceId, username) =>
|
|
api.get(`/api/services/catalog/${serviceId}/accounts/${username}/credentials`),
|
|
};
|
|
|
|
// Cell-to-cell connections API
|
|
export const cellLinkAPI = {
|
|
getInvite: () => api.get('/api/cells/invite'),
|
|
listConnections: () => api.get('/api/cells'),
|
|
addConnection: (invite) => api.post('/api/cells', invite),
|
|
removeConnection: (name) => api.delete(`/api/cells/${name}`),
|
|
getStatus: (name) => api.get(`/api/cells/${name}/status`),
|
|
getPermissions: (cellName) => api.get(`/api/cells/${cellName}/permissions`),
|
|
updatePermissions: (cellName, inbound, outbound) =>
|
|
api.put(`/api/cells/${cellName}/permissions`, { inbound, outbound }),
|
|
setExitOffer: (cellName, offered) =>
|
|
api.put(`/api/cells/${cellName}/exit-offer`, { exit_offered: offered }),
|
|
getServices: () => api.get('/api/cells/services'),
|
|
};
|
|
|
|
// Service Store API
|
|
export const storeAPI = {
|
|
listServices: () => api.get('/api/store/services'),
|
|
getManifest: (id) => api.get(`/api/store/services/${id}/manifest`),
|
|
installService: (id) => api.post(`/api/store/services/${id}/install`),
|
|
removeService: (id, purge = false) => api.delete(`/api/store/services/${id}`, { params: { purge } }),
|
|
listInstalled: () => api.get('/api/store/installed'),
|
|
refreshIndex: () => api.post('/api/store/refresh'),
|
|
};
|
|
|
|
// Health check
|
|
export const healthAPI = {
|
|
check: () => api.get('/health'),
|
|
};
|
|
|
|
// Monitoring API
|
|
export const monitoringAPI = {
|
|
getBackendLogs: (lines = 100) => api.get('/api/logs', { params: { lines } }),
|
|
getHealthHistory: () => api.get('/api/health/history'),
|
|
clearHealthHistory: () => api.post('/api/health/history/clear'),
|
|
};
|
|
|
|
// Logs API
|
|
export const logsAPI = {
|
|
getServiceLogs: (service, level = 'ALL', lines = 100) =>
|
|
api.get(`/api/logs/services/${service}`, { params: { level, lines } }),
|
|
searchLogs: (data) => api.post('/api/logs/search', data),
|
|
getLogFiles: () => api.get('/api/logs/files'),
|
|
rotateLogs: (service) => api.post('/api/logs/rotate', service ? { service } : {}),
|
|
getVerbosity: () => api.get('/api/logs/verbosity'),
|
|
setVerbosity: (levels) => api.put('/api/logs/verbosity', levels),
|
|
};
|
|
|
|
export const auditAPI = {
|
|
list: (params) => api.get('/api/audit', { params }),
|
|
exportCsv: (params) => api.get('/api/audit/export', { params, responseType: 'blob' }),
|
|
verify: () => api.get('/api/audit/verify'),
|
|
};
|
|
|
|
// DDNS API
|
|
export const ddnsAPI = {
|
|
checkName: (name) => api.get(`/api/ddns/check/${name}`),
|
|
updateConfig: (data) => api.put('/api/ddns', data),
|
|
register: () => api.post('/api/ddns/register'),
|
|
getStatus: () => api.get('/api/ddns/status'),
|
|
syncRecords: () => api.post('/api/ddns/sync'),
|
|
};
|
|
|
|
// Setup Wizard API
|
|
export const setupAPI = {
|
|
getStatus: () => api.get('/api/setup/status'),
|
|
validate: (step, data) => api.post('/api/setup/validate', { step, data }),
|
|
complete: (payload) => api.post('/api/setup/complete', payload),
|
|
};
|
|
|
|
// Per-service Egress API
|
|
export const egressAPI = {
|
|
getStatus: () => api.get('/api/egress/status'),
|
|
setServiceExit: (serviceId, connectionId) =>
|
|
api.put(`/api/egress/services/${serviceId}/exit`, { connection_id: connectionId }),
|
|
};
|
|
|
|
// Connectivity / Exit Routing API
|
|
export const connectivityAPI = {
|
|
getStatus: () => api.get('/api/connectivity/status'),
|
|
listExits: () => api.get('/api/connectivity/exits'),
|
|
uploadWireguard: (conf_text) => api.post('/api/connectivity/exits/wireguard', { conf_text }),
|
|
uploadOpenvpn: (ovpn_text, name = 'default') => api.post('/api/connectivity/exits/openvpn', { ovpn_text, name }),
|
|
configureSshuttle: (cfg) => api.post('/api/connectivity/exits/sshuttle', cfg),
|
|
configureProxy: (cfg) => api.post('/api/connectivity/exits/proxy', cfg),
|
|
applyRoutes: () => api.post('/api/connectivity/exits/apply'),
|
|
getPeerExits: () => api.get('/api/connectivity/peers'),
|
|
setPeerExit: (peer_name, connection_id) => api.put(`/api/connectivity/peers/${peer_name}/exit`, { connection_id }),
|
|
// Connectivity v2 — generic connection CRUD + health + per-peer fallback
|
|
listConnections: () => api.get('/api/connectivity/connections'),
|
|
createConnection: (type, name, config = {}, secrets = {}) =>
|
|
api.post('/api/connectivity/connections', { type, name, config, secrets }),
|
|
updateConnection: (id, fields) => api.put(`/api/connectivity/connections/${id}`, fields),
|
|
deleteConnection: (id) => api.delete(`/api/connectivity/connections/${id}`),
|
|
probeConnectionHealth: (id) => api.get(`/api/connectivity/connections/${id}/health`),
|
|
setPeerFailopen: (peer_name, failopen) =>
|
|
api.put(`/api/connectivity/peers/${peer_name}/failopen`, { failopen }),
|
|
};
|
|
|
|
// Container Management API
|
|
export const containerAPI = {
|
|
// Containers
|
|
listContainers: () => api.get('/api/containers'),
|
|
startContainer: (name) => api.post(`/api/containers/${name}/start`),
|
|
stopContainer: (name) => api.post(`/api/containers/${name}/stop`),
|
|
restartContainer: (name) => api.post(`/api/containers/${name}/restart`),
|
|
getContainerLogs: (name, tail = 100) => api.get(`/api/containers/${name}/logs`, { params: { tail } }),
|
|
getContainerStats: (name) => api.get(`/api/containers/${name}/stats`),
|
|
createContainer: (data) => api.post('/api/containers', data), // data may include 'secrets' array
|
|
removeContainer: (name, force = false) => api.delete(`/api/containers/${name}`, { params: { force } }),
|
|
// Images
|
|
listImages: () => api.get('/api/images'),
|
|
pullImage: (image) => api.post('/api/images/pull', { image }),
|
|
removeImage: (image, force = false) => api.delete(`/api/images/${image}`, { params: { force } }),
|
|
// Volumes
|
|
listVolumes: () => api.get('/api/volumes'),
|
|
createVolume: (name) => api.post('/api/volumes', { name }),
|
|
removeVolume: (name, force = false) => api.delete(`/api/volumes/${name}`, { params: { force } }),
|
|
};
|
|
|
|
// Caddy / TLS API
|
|
export const caddyAPI = {
|
|
getCertStatus: () => api.get('/api/caddy/cert-status'),
|
|
renewCert: () => api.post('/api/caddy/cert-renew'),
|
|
uploadCustomCert: (certPem, keyPem) =>
|
|
api.post('/api/caddy/custom-cert', { cert_pem: certPem, key_pem: keyPem }),
|
|
};
|
|
|
|
export default api;
|