Files
pic/webui/src/services/api.js
T
roof 94957abd23 feat(webui): internet sharing UI — exit-offer toggle + peer route-via selector
CellNetwork page (CellPanel):
- Internet Sharing section below service toggles
- Toggle: 'Offer my internet to <cell>' (calls PUT /api/cells/<n>/exit-offer)
- Read-only indicator: whether remote cell offers internet back
- Contextual hints explaining what each party needs to do next

Peers page:
- Fetches connected cells on mount
- Edit modal: Internet Exit dropdown (route-via) showing all connected cells
  with ✓ marker for cells that have offered internet
- Warning if selected cell hasn't offered internet yet
- On save, calls PUT /api/peers/<n>/route-via only when value changed
- Table badge shows 'via <cell>' for peers with active routing

api.js:
- cellLinkAPI.setExitOffer(cellName, offered)
- peerRegistryAPI.setRouteVia(peerName, viaCell)

Tests (vitest + @testing-library/react):
- 19 new frontend tests in src/__tests__/
  - CellNetworkInternetSharing.test.jsx (10 tests)
  - PeersRouteVia.test.jsx (9 tests)
- make test-webui target runs them via docker node:18-alpine

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-01 23:07:50 -04:00

335 lines
14 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: () => api.post('/api/config/backup'),
listBackups: () => api.get('/api/config/backups'),
restoreBackup: (id, services = null) => api.post(`/api/config/restore/${id}`, services ? { services } : {}),
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 }),
getDHCPLeases: () => api.get('/api/dhcp/leases'),
addDHCPReservation: (reservation) => api.post('/api/dhcp/reservations', reservation),
removeDHCPReservation: (reservation) => api.delete('/api/dhcp/reservations', { data: reservation }),
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'),
};
// 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`),
};
// 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'),
};
// 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),
};
// 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 } }),
};
export default api;