UI review, stage 1: 401 on /auth/*, expiring certs, VPN netmask, formatBytes

401 from change-password/change-username no longer logs the user out;
Analytics reads the plain /profiles array; VPN settings send vpn_netmask
with vpn_network (the API reset it to 255.255.255.0); formatBytes guards
null/NaN/negative; Certificates sorts 0 days correctly. Vitest added for
formatters, CIDR parsing and the 401 interceptor.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
ayurishchevandClaude Sonnet 5.5 committed 2026-10-07 13:05:55 +03:00
1 parent 3fac8d70d8
commit b78de98f26
11 files changed
+672 -57

No files matched your search

+20 -16
View File
@@ -9,6 +9,23 @@ const profilesApiClient = axios.create();
const getBaseUrl = (config) => config?.api_base_url || 'http://localhost:5001/api/v1';
const getProfilesBaseUrl = (config) => config?.profiles_api_base_url || 'http://localhost:8000';
// Auth endpoints answer 401 for a wrong current password or 2FA code (change-password, change-username):
// that is a form error, not an expired session, so it must not log the user out.
export const isAuthRequest = (url) => /(^|\/)auth\//.test(url || '');
// 401 on a regular API request: the session is gone, clear it and go to the login page
export const handleUnauthorized = (error) => {
if (error.response && error.response.status === 401 && !isAuthRequest(error.config?.url)) {
localStorage.removeItem('ovpmon_token');
localStorage.removeItem('ovpmon_user');
// Redirecting using window.location for absolute refresh
if (window.location.pathname !== '/login') {
window.location.href = '/login';
}
}
return Promise.reject(error);
};
// Add interceptors to handle Auth and Dynamic Base URLs
const setupInterceptors = (instance, getBase) => {
instance.interceptors.request.use((reqConfig) => {
@@ -22,20 +39,7 @@ const setupInterceptors = (instance, getBase) => {
return reqConfig;
});
instance.interceptors.response.use(
response => response,
error => {
if (error.response && error.response.status === 401) {
localStorage.removeItem('ovpmon_token');
localStorage.removeItem('ovpmon_user');
// Redirecting using window.location for absolute refresh
if (window.location.pathname !== '/login') {
window.location.href = '/login';
}
}
return Promise.reject(error);
}
);
instance.interceptors.response.use(response => response, handleUnauthorized);
};
setupInterceptors(apiClient, getBaseUrl);
@@ -59,10 +63,10 @@ export function useApi() {
const fetchCertificates = async () => {
const res = await profilesApiClient.get('/profiles');
return res.data;
// GET /profiles returns a plain array (not the {success, data} envelope of the monitoring API)
return Array.isArray(res.data) ? res.data : [];
};
return {
apiClient,
profilesApiClient,
+48
View File
@@ -0,0 +1,48 @@
import { describe, it, expect, beforeEach, vi } from 'vitest';
import { AxiosError } from 'axios';
const store = {};
let location;
beforeEach(() => {
for (const k of Object.keys(store)) delete store[k];
store.ovpmon_token = 'tok';
store.ovpmon_user = 'admin';
location = { pathname: '/account', href: '/account' };
vi.stubGlobal('localStorage', {
getItem: (k) => (k in store ? store[k] : null),
setItem: (k, v) => { store[k] = String(v); },
removeItem: (k) => { delete store[k]; }
});
vi.stubGlobal('window', { location });
});
// Make the client answer with the given status without any network
const failWith = async (client, status, url) => {
client.defaults.adapter = (config) => Promise.reject(
new AxiosError('failed', 'ERR_BAD_REQUEST', config, null, { status, data: {}, config })
);
await client.post(url).catch(() => {});
};
describe('401 handling', () => {
it('keeps the session on 401 from /auth/* (wrong password or 2FA code)', async () => {
const { useApi } = await import('./useApi');
await failWith(useApi().apiClient, 401, '../auth/change-password');
expect(store.ovpmon_token).toBe('tok');
expect(location.href).toBe('/account');
});
it('ends the session on 401 from other requests', async () => {
const { useApi } = await import('./useApi');
await failWith(useApi().apiClient, 401, '/stats');
expect(store.ovpmon_token).toBeUndefined();
expect(location.href).toBe('/login');
});
it('ignores other error codes', async () => {
const { useApi } = await import('./useApi');
await failWith(useApi().profilesApiClient, 500, '/profiles');
expect(store.ovpmon_token).toBe('tok');
});
});
+6 -4
View File
@@ -1,15 +1,17 @@
export function useFormatters() {
function formatBytes(bytes, decimals = 2) {
if (bytes === 0) return '0 B';
const value = Number(bytes);
// null, undefined, NaN and negative values are shown as zero
if (!Number.isFinite(value) || value <= 0) return '0 B';
const k = 1024;
const dm = decimals < 0 ? 0 : decimals;
const sizes = ['B', 'KB', 'MB', 'GB', 'TB'];
const i = Math.floor(Math.log(bytes) / Math.log(k));
return parseFloat((bytes / Math.pow(k, i)).toFixed(dm)) + ' ' + sizes[i];
const i = Math.min(Math.max(Math.floor(Math.log(value) / Math.log(k)), 0), sizes.length - 1);
return parseFloat((value / Math.pow(k, i)).toFixed(dm)) + ' ' + sizes[i];
}
function formatRate(rate) {
return parseFloat(rate).toFixed(3) + ' Mbps';
return (parseFloat(rate) || 0).toFixed(3) + ' Mbps';
}
function parseServerDate(dateStr) {
@@ -0,0 +1,29 @@
import { describe, it, expect } from 'vitest';
import { useFormatters } from './useFormatters';
const { formatBytes, formatRate } = useFormatters();
describe('formatBytes', () => {
it('formats regular values', () => {
expect(formatBytes(1536)).toBe('1.5 KB');
expect(formatBytes(5 * 1024 * 1024)).toBe('5 MB');
});
it('shows zero for empty, non-numeric and negative values', () => {
for (const v of [0, null, undefined, NaN, 'abc', -5, Infinity]) {
expect(formatBytes(v)).toBe('0 B');
}
});
it('stays inside the unit table', () => {
expect(formatBytes(0.5)).toBe('0.5 B');
expect(formatBytes(Math.pow(1024, 6))).toMatch(/ TB$/);
});
});
describe('formatRate', () => {
it('does not produce NaN', () => {
expect(formatRate(1.23456)).toBe('1.235 Mbps');
expect(formatRate(null)).toBe('0.000 Mbps');
});
});
+34
View File
@@ -0,0 +1,34 @@
// IPv4 helpers for the VPN subnet field: "a.b.c.d/nn" <-> network address + dotted netmask.
const IPV4 = /^(25[0-5]|2[0-4]\d|1?\d?\d)(\.(25[0-5]|2[0-4]\d|1?\d?\d)){3}$/;
// 24 -> '255.255.255.0'; null for a value outside 0..32
export function cidrToMask(bits) {
const n = Number(bits);
if (bits === '' || bits === null || !Number.isInteger(n) || n < 0 || n > 32) return null;
const mask = n === 0 ? 0 : (0xFFFFFFFF << (32 - n)) >>> 0;
return [24, 16, 8, 0].map(shift => (mask >>> shift) & 255).join('.');
}
// '255.255.255.0' -> 24; null for a malformed or non-contiguous mask
export function maskToCidr(mask) {
if (typeof mask !== 'string' || !IPV4.test(mask)) return null;
const value = mask.split('.').reduce((acc, p) => ((acc << 8) | Number(p)) >>> 0, 0);
let bits = 0;
while (bits < 32 && (value & (0x80000000 >>> bits))) bits++;
// The rest must be zeros, otherwise the mask is not contiguous
const expected = bits === 0 ? 0 : (0xFFFFFFFF << (32 - bits)) >>> 0;
return value === expected ? bits : null;
}
// '172.20.1.0/24' -> { network: '172.20.1.0', netmask: '255.255.255.0' }
// '172.20.1.0' -> { network: '172.20.1.0', netmask: null } (no suffix: the caller keeps the current mask)
// anything else -> null
export function parseCidr(value) {
const text = String(value ?? '').trim();
const [network, suffix, ...rest] = text.split('/');
if (rest.length || !IPV4.test(network)) return null;
if (suffix === undefined) return { network, netmask: null };
const netmask = cidrToMask(suffix);
return netmask ? { network, netmask } : null;
}
+36
View File
@@ -0,0 +1,36 @@
import { describe, it, expect } from 'vitest';
import { cidrToMask, maskToCidr, parseCidr } from './cidr';
describe('cidrToMask / maskToCidr', () => {
it('converts a suffix to a netmask and back', () => {
for (const [bits, mask] of [[8, '255.0.0.0'], [22, '255.255.252.0'], [24, '255.255.255.0'], [30, '255.255.255.252']]) {
expect(cidrToMask(bits)).toBe(mask);
expect(maskToCidr(mask)).toBe(bits);
}
expect(cidrToMask(0)).toBe('0.0.0.0');
expect(cidrToMask(32)).toBe('255.255.255.255');
});
it('rejects out-of-range suffixes and non-contiguous masks', () => {
for (const v of [-1, 33, 'x', '', null]) expect(cidrToMask(v)).toBeNull();
expect(maskToCidr('255.0.255.0')).toBeNull();
expect(maskToCidr('255.255.255')).toBeNull();
});
});
describe('parseCidr', () => {
it('splits the address and the mask', () => {
expect(parseCidr('172.20.1.0/24')).toEqual({ network: '172.20.1.0', netmask: '255.255.255.0' });
expect(parseCidr(' 10.8.0.0/22 ')).toEqual({ network: '10.8.0.0', netmask: '255.255.252.0' });
});
it('keeps the mask empty when there is no suffix', () => {
expect(parseCidr('10.8.0.0')).toEqual({ network: '10.8.0.0', netmask: null });
});
it('rejects malformed input', () => {
for (const v of ['', 'abc', '10.8.0.0/', '10.8.0.0/33', '10.8.0/24', '300.1.1.1/24', '10.8.0.0/24/1']) {
expect(parseCidr(v)).toBeNull();
}
});
});
+10 -11
View File
@@ -201,17 +201,16 @@ const loadAnalytics = async () => {
const loadCerts = async () => {
loading.certs = true;
try {
const res = await fetchCertificates();
if(res.success && Array.isArray(res.data)) {
const list = res.data.filter(cert => {
// Only active, non-revoked, and expiring soon (within 45 days)
return !cert.is_revoked && !cert.is_expired &&
cert.days_remaining !== null && cert.days_remaining <= 45;
});
kpi.expiringCerts = list.length;
expiringCertsList.value = list.sort((a,b) => (a.days_remaining || 0) - (b.days_remaining || 0));
}
// fetchCertificates returns the plain array of profiles
const profiles = await fetchCertificates();
const list = profiles.filter(cert => {
// Only active, non-revoked, and expiring soon (within 45 days)
return !cert.is_revoked && !cert.is_expired &&
cert.days_remaining != null && cert.days_remaining <= 45;
});
kpi.expiringCerts = list.length;
expiringCertsList.value = list.sort((a, b) => a.days_remaining - b.days_remaining);
} catch (e) {
console.error(e);
} finally {
+2 -2
View File
@@ -234,8 +234,8 @@ const categorized = computed(() => {
});
// Sort logic
active.sort((a,b) => (a.days_remaining || 9999) - (b.days_remaining || 9999));
expired.sort((a,b) => (b.days_remaining || -9999) - (a.days_remaining || -9999));
active.sort((a,b) => (a.days_remaining ?? 9999) - (b.days_remaining ?? 9999));
expired.sort((a,b) => (b.days_remaining ?? -9999) - (a.days_remaining ?? -9999));
return { active, expired };
});
+17 -17
View File
@@ -264,6 +264,7 @@ import { ref, onMounted, reactive, watch } from 'vue';
import { useApi } from '../composables/useApi';
import { useToast } from '../composables/useToast';
import { usePkiStatus } from '../composables/usePkiStatus';
import { maskToCidr, parseCidr } from '../utils/cidr';
const { profilesApiClient } = useApi();
const toast = useToast();
@@ -302,15 +303,8 @@ watch(isSplitTunnel, (val) => {
form.tunnel_type = val ? 'SPLIT' : 'FULL';
});
// Helpers
function maskToCidr(mask) {
if (!mask) return '';
const parts = mask.split('.');
let bits = 0;
const map = {255:8, 254:7, 252:6, 248:5, 240:4, 224:3, 192:2, 128:1, 0:0};
for(let p of parts) bits += map[parseInt(p)] || 0;
return bits;
}
// Netmask received from the server: used when the subnet is typed without a /nn suffix
let currentNetmask = '';
// Methods
const showMessage = (text, type = 'success') => toast.show(text, type);
@@ -337,9 +331,10 @@ const loadConfig = async () => {
}
});
currentNetmask = data.vpn_netmask || '';
if (data.vpn_network && data.vpn_netmask) {
const cidrSuffix = maskToCidr(data.vpn_netmask);
if (cidrSuffix) {
if (cidrSuffix !== null) {
form.vpn_network = `${data.vpn_network}/${cidrSuffix}`;
}
}
@@ -351,20 +346,25 @@ const loadConfig = async () => {
};
const handleSave = async () => {
// The API takes the address and the netmask separately: without vpn_netmask it resets the mask to 255.255.255.0
const subnet = parseCidr(form.vpn_network);
if (!subnet) {
showMessage('VPN subnet must be an IPv4 network in CIDR format, e.g. 172.20.1.0/24', 'error');
return;
}
isLoading.value = true;
action.value = 'save';
const payload = { ...form };
payload.split_routes = payload.split_routes.filter(r => r && r.trim() !== '');
payload.dns_servers = payload.dns_servers.filter(d => d && d.trim() !== '');
if (payload.vpn_network.includes('/')) {
const [ip, suffix] = payload.vpn_network.split('/');
payload.vpn_network = ip;
}
payload.vpn_network = subnet.network;
payload.vpn_netmask = subnet.netmask || currentNetmask || '255.255.255.0';
try {
await profilesApiClient.put('/config/server', payload);
currentNetmask = payload.vpn_netmask;
showMessage('Server configuration saved!', 'success');
} catch (err) {
showMessage(`Error saving: ${err.response?.data?.detail || err.message}`, 'error');