feat(api-docs): enhance API documentation with missing endpoints, search, collapse, and route sync test

- Add 29 undocumented routes across 4 new sections (Settings, Xray Settings,
  Subscription Server, WebSocket) plus 4 missing Server API endpoints
- Fix inaccuracies: history metric keys, node metric keys, VLESS enc description
- Add response schemas to 15+ key endpoints
- Add search bar and expand/collapse all controls to the docs page
- Add collapsible endpoint sections with endpoint count
- Add Go test (TestAPIRoutesDocumented) to verify all Go routes are documented
This commit is contained in:
abdulrahman 2026-05-12 18:08:47 +03:00
parent 07bc74a521
commit a141b4f457
4 changed files with 669 additions and 21 deletions

View file

@ -1,5 +1,5 @@
<script setup>
import { ref, onMounted } from 'vue';
import { ref, computed, onMounted } from 'vue';
import { useI18n } from 'vue-i18n';
import { Modal, message } from 'ant-design-vue';
import {
@ -8,12 +8,15 @@ import {
CopyOutlined,
EyeOutlined,
EyeInvisibleOutlined,
SearchOutlined,
ExpandOutlined,
CompressOutlined,
} from '@ant-design/icons-vue';
import { theme as themeState, antdThemeConfig } from '@/composables/useTheme.js';
import AppSidebar from '@/components/AppSidebar.vue';
import { HttpUtil, ClipboardManager } from '@/utils/index.js';
import { sections } from './endpoints.js';
import { sections as allSections } from './endpoints.js';
import EndpointSection from './EndpointSection.vue';
const { t } = useI18n();
@ -26,11 +29,55 @@ const tokenLoading = ref(false);
const tokenRotating = ref(false);
const tokenVisible = ref(false);
const curlExample = `curl -X GET \\
-H "Authorization: Bearer YOUR_API_TOKEN" \\
-H "Accept: application/json" \\
const searchQuery = ref('');
const collapsedSections = ref(new Set());
const curlExample = `curl -X GET \
-H "Authorization: Bearer YOUR_API_TOKEN" \
-H "Accept: application/json" \
https://your-panel.example.com/panel/api/inbounds/list`;
const sections = computed(() => {
const q = searchQuery.value.toLowerCase().trim();
if (!q) return allSections;
return allSections
.map(s => {
const matching = s.endpoints.filter(e =>
e.path.toLowerCase().includes(q) ||
e.summary?.toLowerCase().includes(q) ||
e.method.toLowerCase().includes(q)
);
return { ...s, endpoints: matching };
})
.filter(s => s.endpoints.length > 0);
});
const endpointCount = computed(() =>
allSections.reduce((sum, s) => sum + s.endpoints.length, 0)
);
const visibleSections = computed(() =>
sections.value.reduce((sum, s) => sum + s.endpoints.length, 0)
);
function isCollapsed(id) {
return collapsedSections.value.has(id);
}
function toggleSection(id) {
const s = new Set(collapsedSections.value);
if (s.has(id)) s.delete(id); else s.add(id);
collapsedSections.value = s;
}
function expandAll() {
collapsedSections.value = new Set();
}
function collapseAll() {
collapsedSections.value = new Set(allSections.map(s => s.id));
}
async function loadApiToken() {
tokenLoading.value = true;
try {
@ -64,7 +111,7 @@ function regenerateApiToken() {
async function copyApiToken() {
if (!apiToken.value) return;
const ok = await ClipboardManager.copyText(apiToken.value);
const ok = await ClipboardManager.copy(apiToken.value);
if (ok) message.success(t('success'));
}
@ -138,15 +185,45 @@ onMounted(() => {
<pre class="code-block">{{ curlExample }}</pre>
</a-card>
<div class="toolbar">
<a-input-search
v-model:value="searchQuery"
placeholder="Search endpoints by path, method, or description…"
allow-clear
class="search-bar"
>
<template #prefix><SearchOutlined /></template>
</a-input-search>
<span class="match-count" v-if="searchQuery">
{{ visibleSections }} / {{ endpointCount }} endpoints
</span>
<a-space size="small">
<a-button size="small" @click="expandAll">
<template #icon><ExpandOutlined /></template>
Expand all
</a-button>
<a-button size="small" @click="collapseAll">
<template #icon><CompressOutlined /></template>
Collapse all
</a-button>
</a-space>
</div>
<nav class="toc-nav">
<span class="toc-label">On this page:</span>
<a v-for="s in sections" :key="s.id" class="toc-link" :href="`#${s.id}`"
@click.prevent="scrollToSection(s.id)">
{{ s.title }}
{{ s.title }} ({{ s.endpoints.length }})
</a>
</nav>
<EndpointSection v-for="s in sections" :key="s.id" :section="s" />
<EndpointSection
v-for="s in sections"
:key="s.id"
:section="s"
:collapsed="isCollapsed(s.id)"
@toggle="toggleSection(s.id)"
/>
</div>
</a-layout-content>
</a-layout>
@ -275,6 +352,26 @@ onMounted(() => {
overflow-x: auto;
}
.toolbar {
display: flex;
align-items: center;
gap: 12px;
flex-wrap: wrap;
margin-bottom: 16px;
}
.search-bar {
flex: 1;
min-width: 200px;
max-width: 480px;
}
.match-count {
font-size: 12px;
color: rgba(0, 0, 0, 0.5);
white-space: nowrap;
}
.toc-nav {
display: flex;
flex-wrap: wrap;

View file

@ -1,16 +1,37 @@
<script setup>
import { computed } from 'vue';
import {
DownOutlined,
RightOutlined,
} from '@ant-design/icons-vue';
import EndpointRow from './EndpointRow.vue';
defineProps({
const props = defineProps({
section: { type: Object, required: true },
collapsed: { type: Boolean, default: false },
});
const emit = defineEmits(['toggle']);
const endpointLabel = computed(() =>
props.section.endpoints.length === 1
? '1 endpoint'
: `${props.section.endpoints.length} endpoints`
);
</script>
<template>
<section :id="section.id" class="api-section">
<h2 class="section-title">{{ section.title }}</h2>
<p v-if="section.description" class="section-description">{{ section.description }}</p>
<div class="endpoints">
<div class="section-header" @click="emit('toggle')">
<div class="section-header-left">
<DownOutlined v-if="!collapsed" class="collapse-icon" />
<RightOutlined v-else class="collapse-icon" />
<h2 class="section-title">{{ section.title }}</h2>
</div>
<span class="endpoint-count">{{ endpointLabel }}</span>
</div>
<p v-if="section.description && !collapsed" class="section-description">{{ section.description }}</p>
<div v-show="!collapsed" class="endpoints">
<EndpointRow v-for="(endpoint, idx) in section.endpoints" :key="idx" :endpoint="endpoint" />
</div>
</section>
@ -21,11 +42,35 @@ defineProps({
background: #fff;
border: 1px solid rgba(128, 128, 128, 0.15);
border-radius: 8px;
padding: 20px 24px;
margin-bottom: 20px;
padding: 16px 24px;
margin-bottom: 16px;
scroll-margin-top: 16px;
}
.section-header {
display: flex;
align-items: center;
justify-content: space-between;
cursor: pointer;
user-select: none;
}
.section-header:hover .collapse-icon {
color: #1677ff;
}
.section-header-left {
display: flex;
align-items: center;
gap: 8px;
}
.collapse-icon {
font-size: 12px;
color: rgba(0, 0, 0, 0.45);
transition: color 0.2s;
}
.section-title {
font-size: 20px;
font-weight: 600;
@ -33,12 +78,23 @@ defineProps({
color: rgba(0, 0, 0, 0.88);
}
.endpoint-count {
font-size: 12px;
color: rgba(0, 0, 0, 0.45);
white-space: nowrap;
}
.section-description {
margin: 6px 0 14px;
margin: 10px 0 14px;
color: rgba(0, 0, 0, 0.65);
line-height: 1.55;
}
.endpoints {
padding-top: 8px;
border-top: 1px solid rgba(128, 128, 128, 0.1);
}
.endpoints > :first-child {
padding-top: 0;
}

View file

@ -67,6 +67,7 @@ export const sections = [
params: [
{ name: 'email', in: 'path', type: 'string', desc: 'Client email (unique across the panel).' },
],
response: '{\n "success": true,\n "obj": {\n "email": "user1",\n "up": 1048576,\n "down": 2097152,\n "total": 10737418240,\n "expiryTime": 1735689600000\n }\n}',
},
{
method: 'GET',
@ -75,6 +76,7 @@ export const sections = [
params: [
{ name: 'id', in: 'path', type: 'string', desc: 'Client subId / UUID.' },
],
response: '{\n "success": true,\n "obj": {\n "email": "user1",\n "up": 1048576,\n "down": 2097152,\n "total": 10737418240,\n "expiryTime": 1735689600000\n }\n}',
},
{
method: 'POST',
@ -209,6 +211,7 @@ export const sections = [
method: 'POST',
path: '/panel/api/inbounds/lastOnline',
summary: 'Map of client email → last-seen unix timestamp.',
response: '{\n "success": true,\n "obj": [\n { "email": "user1", "lastOnline": 1700000000 },\n { "email": "user2", "lastOnline": 1699999000 }\n ]\n}',
},
{
method: 'GET',
@ -264,6 +267,7 @@ export const sections = [
method: 'GET',
path: '/panel/api/server/status',
summary: 'Real-time machine snapshot: CPU, memory, swap, disk, network IO, load averages, open connections, Xray state. Cached and refreshed every 2 seconds in the background.',
response: '{\n "success": true,\n "obj": {\n "cpu": 12.5,\n "mem": { "current": 2147483648, "total": 8589934592 },\n "swap": { "current": 0, "total": 4294967296 },\n "disk": { "current": 53687091200, "total": 268435456000 },\n "netIO": { "up": 1073741824, "down": 2147483648 },\n "xray": { "state": "running", "version": "v25.10.31" },\n "tcpCount": 42,\n "load": { "load1": 0.5, "load5": 0.3, "load15": 0.2 }\n }\n}',
},
{
method: 'GET',
@ -278,7 +282,36 @@ export const sections = [
path: '/panel/api/server/history/:metric/:bucket',
summary: 'Aggregated time-series for one metric. Returns an array of {t, v} samples covering the last ~6 hours.',
params: [
{ name: 'metric', in: 'path', type: 'string', desc: 'cpu | mem | swap | netIn | netOut | tcpCount | udpCount | load1 | online.' },
{ name: 'metric', in: 'path', type: 'string', desc: 'cpu | mem | netUp | netDown | online | load1 | load5 | load15.' },
{ name: 'bucket', in: 'path', type: 'number', desc: 'Bucket size in seconds. Allowed: 2, 30, 60, 120, 180, 300.' },
],
response: '{\n "success": true,\n "obj": [\n { "t": 1700000000, "v": 12.5 },\n { "t": 1700000002, "v": 13.1 }\n ]\n}',
},
{
method: 'GET',
path: '/panel/api/server/xrayMetricsState',
summary: 'Xray runtime metrics state — whether the xray config has a `metrics` block, which expvar keys are flowing, and the current snapshot values for each. Returns an empty state when metrics are not configured.',
},
{
method: 'GET',
path: '/panel/api/server/xrayMetricsHistory/:metric/:bucket',
summary: 'Time-series history for one Xray runtime metric over the last ~6 hours. Same {t, v} shape as /history/:metric/:bucket.',
params: [
{ name: 'metric', in: 'path', type: 'string', desc: 'xrAlloc | xrSys | xrHeapObjects | xrNumGC | xrPauseNs.' },
{ name: 'bucket', in: 'path', type: 'number', desc: 'Bucket size in seconds. Allowed: 2, 30, 60, 120, 180, 300.' },
],
},
{
method: 'GET',
path: '/panel/api/server/xrayObservatory',
summary: 'Latest snapshot from the Xray observatory — per-outbound latency, health status, and last-probe time. Only populated when the Xray config has an observatory configured.',
},
{
method: 'GET',
path: '/panel/api/server/xrayObservatoryHistory/:tag/:bucket',
summary: 'Time-series of observatory probe results for one outbound tag. Same {t, v} shape as the other history endpoints.',
params: [
{ name: 'tag', in: 'path', type: 'string', desc: 'Outbound tag from the observatory config.' },
{ name: 'bucket', in: 'path', type: 'number', desc: 'Bucket size in seconds. Allowed: 2, 30, 60, 120, 180, 300.' },
],
},
@ -286,6 +319,7 @@ export const sections = [
method: 'GET',
path: '/panel/api/server/getXrayVersion',
summary: 'List Xray binary versions available for install on this host.',
response: '{\n "success": true,\n "obj": ["v25.10.31", "v25.9.15", "v25.8.1"]\n}',
},
{
method: 'GET',
@ -295,7 +329,8 @@ export const sections = [
{
method: 'GET',
path: '/panel/api/server/getConfigJson',
summary: 'Return the assembled Xray config thats currently running on this host.',
summary: 'Return the assembled Xray config that\u2019s currently running on this host.',
response: '{\n "success": true,\n "obj": {\n "log": { "loglevel": "warning" },\n "inbounds": [...],\n "outbounds": [...],\n "routing": { "rules": [...] }\n }\n}',
},
{
method: 'GET',
@ -306,26 +341,31 @@ export const sections = [
method: 'GET',
path: '/panel/api/server/getNewUUID',
summary: 'Generate a fresh UUID v4. Convenience helper for client IDs.',
response: '{\n "success": true,\n "obj": "550e8400-e29b-41d4-a716-446655440000"\n}',
},
{
method: 'GET',
path: '/panel/api/server/getNewX25519Cert',
summary: 'Generate a new X25519 keypair for Reality.',
response: '{\n "success": true,\n "obj": {\n "privateKey": "uN9qLfV3zH8w...",\n "publicKey": "5v8xPqR2sM7k..."\n }\n}',
},
{
method: 'GET',
path: '/panel/api/server/getNewmldsa65',
summary: 'Generate a new ML-DSA-65 keypair (post-quantum signature). Returns {privateKey, publicKey, seed}.',
response: '{\n "success": true,\n "obj": {\n "privateKey": "mdsa65priv...",\n "publicKey": "mdsa65pub...",\n "seed": "random-seed..."\n }\n}',
},
{
method: 'GET',
path: '/panel/api/server/getNewmlkem768',
summary: 'Generate a new ML-KEM-768 keypair (post-quantum KEM). Returns {clientKey, serverKey}.',
response: '{\n "success": true,\n "obj": {\n "clientKey": "mlkem768-client...",\n "serverKey": "mlkem768-server..."\n }\n}',
},
{
method: 'GET',
path: '/panel/api/server/getNewVlessEnc',
summary: 'Generate VLESS encryption auth options. Returns auths with id, label, decryption, and encryption.',
summary: 'Generate VLESS encryption auth options. Returns an auths array each with id, label, encryption, and decryption fields.',
response: '{\n "success": true,\n "obj": {\n "auths": [\n { "id": 0, "label": "Auth #0", "encryption": "aes-256-gcm", "decryption": "" }\n ]\n }\n}',
},
{
method: 'POST',
@ -366,11 +406,12 @@ export const sections = [
{
method: 'POST',
path: '/panel/api/server/logs/:count',
summary: 'Return the last N lines of the panels own log.',
summary: 'Return the last N lines of the panel\u2019s own log.',
params: [
{ name: 'count', in: 'path', type: 'number', desc: 'Number of trailing log lines.' },
],
body: '{\n "level": "info",\n "syslog": false\n}',
response: '{\n "success": true,\n "obj": "2025/01/01 12:00:00 [INFO] Server started\\n2025/01/01 12:00:01 [INFO] Xray is running"\n}',
},
{
method: 'POST',
@ -403,6 +444,7 @@ export const sections = [
method: 'GET',
path: '/panel/api/nodes/list',
summary: 'List every configured node with its connection details, health, and last heartbeat patch.',
response: '{\n "success": true,\n "obj": [\n {\n "id": 1,\n "name": "de-fra-1",\n "scheme": "https",\n "host": "node1.example.com",\n "port": 2053,\n "status": "online",\n "cpu": 23.5,\n "mem": 45.1\n }\n ]\n}',
},
{
method: 'GET',
@ -463,8 +505,8 @@ export const sections = [
summary: 'Aggregated metric history for a node — same shape as /server/history, scoped to one node.',
params: [
{ name: 'id', in: 'path', type: 'number', desc: 'Node ID.' },
{ name: 'metric', in: 'path', type: 'string', desc: 'Metric key (cpu, mem, netIn, …).' },
{ name: 'bucket', in: 'path', type: 'number', desc: 'Bucket size in seconds.' },
{ name: 'metric', in: 'path', type: 'string', desc: 'cpu | mem.' },
{ name: 'bucket', in: 'path', type: 'number', desc: 'Bucket size in seconds. Allowed: 2, 30, 60, 120, 180, 300.' },
],
},
],
@ -537,6 +579,194 @@ export const sections = [
},
],
},
{
id: 'settings',
title: 'Settings API',
description:
'Panel configuration, user credentials, and API token management. All endpoints live under /panel/setting and require a logged-in session or Bearer token.',
endpoints: [
{
method: 'POST',
path: '/panel/setting/all',
summary: 'Return every panel setting: web server, Telegram bot, subscription, security, LDAP. The full JSON blob that the Settings page edits.',
response: '{\n "success": true,\n "obj": {\n "webPort": 2053,\n "webCertFile": "",\n "webKeyFile": "",\n "webBasePath": "/",\n "subPort": 10882,\n "subPath": "/sub/",\n "tgBotEnable": false,\n "tgBotToken": "",\n ...\n }\n}',
},
{
method: 'POST',
path: '/panel/setting/defaultSettings',
summary: 'Return the computed default settings based on the request host. Useful to preview what a fresh install would use.',
},
{
method: 'POST',
path: '/panel/setting/update',
summary: 'Persist every setting at once. The body mirrors the shape returned by /all. Invalid values (bad ports, missing cert pairs, etc.) are rejected before write.',
body: '{\n "webPort": 2053,\n "webBasePath": "/",\n "subPort": 10882,\n "subPath": "/sub/",\n "tgBotEnable": false,\n ...\n}',
},
{
method: 'POST',
path: '/panel/setting/updateUser',
summary: 'Change the panel admin username and password. Requires the current credentials for verification. The session is refreshed with the new values on success.',
params: [
{ name: 'oldUsername', in: 'body', type: 'string', desc: 'Current admin username.' },
{ name: 'oldPassword', in: 'body', type: 'string', desc: 'Current admin password.' },
{ name: 'newUsername', in: 'body', type: 'string', desc: 'Desired new username.' },
{ name: 'newPassword', in: 'body', type: 'string', desc: 'Desired new password.' },
],
body: '{\n "oldUsername": "admin",\n "oldPassword": "admin",\n "newUsername": "newadmin",\n "newPassword": "newpass"\n}',
},
{
method: 'POST',
path: '/panel/setting/restartPanel',
summary: 'Restart the entire 3x-ui process after a 3-second grace period. The connection drops immediately; the panel comes back online ~5-10 seconds later.',
},
{
method: 'GET',
path: '/panel/setting/getDefaultJsonConfig',
summary: 'Return the built-in default Xray JSON config template that ships with this panel version.',
},
{
method: 'GET',
path: '/panel/setting/getApiToken',
summary: 'Return the current API Bearer token. The token is auto-generated on first read so existing installs upgrade transparently.',
response: '{\n "success": true,\n "obj": "abcdef-12345-..."\n}',
},
{
method: 'POST',
path: '/panel/setting/regenerateApiToken',
summary: 'Rotate the API Bearer token. Any remote central panel that cached the old value will start failing heartbeats until updated with the new token.',
response: '{\n "success": true,\n "obj": "new-token-string"\n}',
},
],
},
{
id: 'xraySettings',
title: 'Xray Settings API',
description:
'Xray configuration template, outbound management, Warp/Nord integration, and config testing. All endpoints under /panel/xray.',
endpoints: [
{
method: 'POST',
path: '/panel/xray/',
summary: 'Return the Xray config template (JSON string), available inbound tags, client reverse tags, and the configured outbound test URL in one response.',
response: '{\n "success": true,\n "obj": {\n "xraySetting": "{...raw xray config...}",\n "inboundTags": "[\"inbound-443\"]",\n "clientReverseTags": "[]",\n "outboundTestUrl": "https://www.google.com/generate_204"\n }\n}',
},
{
method: 'GET',
path: '/panel/xray/getDefaultJsonConfig',
summary: 'Return the built-in default Xray config shipped with the panel (identical to /panel/setting/getDefaultJsonConfig).',
},
{
method: 'GET',
path: '/panel/xray/getOutboundsTraffic',
summary: 'Return traffic statistics for every outbound. Each outbound shows up/down/total counters.',
},
{
method: 'GET',
path: '/panel/xray/getXrayResult',
summary: 'Return the most recent Xray process stdout/stderr output. Useful to check for startup errors or runtime warnings.',
},
{
method: 'POST',
path: '/panel/xray/update',
summary: 'Save the Xray JSON config template and optionally the outbound test URL. Both are sent as form fields.',
params: [
{ name: 'xraySetting', in: 'body (form)', type: 'string', desc: 'Full Xray JSON config template.' },
{ name: 'outboundTestUrl', in: 'body (form)', type: 'string', desc: 'URL used for outbound reachability tests. Defaults to https://www.google.com/generate_204.' },
],
},
{
method: 'POST',
path: '/panel/xray/warp/:action',
summary: 'Manage Cloudflare Warp integration. The action parameter selects the operation.',
params: [
{ name: 'action', in: 'path', type: 'string', desc: 'data — return Warp stats (quota, remaining). del — delete Warp data. config — return current Warp config. reg — register a new Warp endpoint (sends privateKey, publicKey). license — set a Warp+ license key (sends license).' },
{ name: 'privateKey', in: 'body (form)', type: 'string', desc: 'Required when action=reg.' },
{ name: 'publicKey', in: 'body (form)', type: 'string', desc: 'Required when action=reg.' },
{ name: 'license', in: 'body (form)', type: 'string', desc: 'Required when action=license.' },
],
},
{
method: 'POST',
path: '/panel/xray/nord/:action',
summary: 'Manage NordVPN integration. The action parameter selects the operation.',
params: [
{ name: 'action', in: 'path', type: 'string', desc: 'countries — list available countries. servers — list servers in a country (sends countryId). reg — get NordVPN credentials (sends token). setKey — store NordVPN API key (sends key). data — return current NordVPN connection data. del — delete NordVPN data.' },
{ name: 'countryId', in: 'body (form)', type: 'string', desc: 'Required when action=servers.' },
{ name: 'token', in: 'body (form)', type: 'string', desc: 'Required when action=reg.' },
{ name: 'key', in: 'body (form)', type: 'string', desc: 'Required when action=setKey.' },
],
},
{
method: 'POST',
path: '/panel/xray/resetOutboundsTraffic',
summary: 'Reset traffic counters for a specific outbound by tag.',
params: [
{ name: 'tag', in: 'body (form)', type: 'string', desc: 'Outbound tag to reset (e.g. "proxy", "direct").' },
],
body: 'tag=proxy',
},
{
method: 'POST',
path: '/panel/xray/testOutbound',
summary: 'Test an outbound configuration. Sends the outbound JSON (required), optionally all outbounds (to resolve sockopt.dialerProxy dependencies), and a mode flag.',
params: [
{ name: 'outbound', in: 'body (form)', type: 'string', desc: 'JSON-encoded single outbound to test (required).' },
{ name: 'allOutbounds', in: 'body (form)', type: 'string', desc: 'JSON array of all outbounds — used to resolve dialerProxy chains.' },
{ name: 'mode', in: 'body (form)', type: 'string', desc: '"tcp" for a fast dial-only probe (parallel-safe). Default/empty uses a full HTTP probe through a temp xray instance.' },
],
body: 'outbound={"protocol":"freedom","settings":{}}&mode=tcp',
},
],
},
{
id: 'subscription',
title: 'Subscription Server',
description:
'A separate HTTP/HTTPS server that serves proxy subscription links (standard, JSON, and Clash) to clients. The server listens on its own port (default 10882) and is configured in Settings → Subscription. Paths are configurable; defaults are shown below.',
endpoints: [
{
method: 'GET',
path: '/{subPath}:subid',
summary: 'Return base64-encoded subscription links for all enabled clients matching the subscription ID. When the request has an Accept: text/html header or ?html=1, renders a styled info page instead. Response headers include Subscription-Userinfo (traffic/expiry), Profile-Title, Profile-Web-Page-Url, Support-Url, and Profile-Update-Interval. Default path: /sub/:subid.',
params: [
{ name: 'subid', in: 'path', type: 'string', desc: 'Client subscription ID.' },
],
},
{
method: 'GET',
path: '/{jsonPath}:subid',
summary: 'Return subscription as a JSON array of proxy configs (one per enabled client). Only when JSON subscription is enabled in settings. Default path: /json/:subid.',
params: [
{ name: 'subid', in: 'path', type: 'string', desc: 'Client subscription ID.' },
],
},
{
method: 'GET',
path: '/{clashPath}:subid',
summary: 'Return subscription as a Clash/Mihomo-compatible YAML config. Only when Clash subscription is enabled in settings. Default path: /clash/:subid.',
params: [
{ name: 'subid', in: 'path', type: 'string', desc: 'Client subscription ID.' },
],
},
],
},
{
id: 'websocket',
title: 'WebSocket',
description:
'Real-time status updates via WebSocket. Connect once to receive a stream of server state without polling.',
endpoints: [
{
method: 'GET',
path: '/ws',
summary: 'Upgrade an HTTP connection to WebSocket for real-time server status, Xray state, and notification events. Requires an authenticated session cookie (Bearer token auth is not supported for WebSocket). The server pushes JSON messages on every 2-second status tick.',
},
],
},
];
export const methodColors = {

View file

@ -0,0 +1,265 @@
package controller
import (
"os"
"path/filepath"
"regexp"
"strings"
"testing"
)
type routeDef struct {
Method string
Path string
}
// expectedRoutes lists every route documented in frontend/src/pages/api-docs/endpoints.js.
// Keep this in sync when adding new endpoints to the docs.
var expectedRoutes = []routeDef{
// Authentication — no prefix
{Method: "POST", Path: "/login"},
{Method: "GET", Path: "/logout"},
{Method: "GET", Path: "/csrf-token"},
{Method: "POST", Path: "/getTwoFactorEnable"},
// Inbounds API — prefix /panel/api/inbounds
{Method: "GET", Path: "/panel/api/inbounds/list"},
{Method: "GET", Path: "/panel/api/inbounds/get/:id"},
{Method: "GET", Path: "/panel/api/inbounds/getClientTraffics/:email"},
{Method: "GET", Path: "/panel/api/inbounds/getClientTrafficsById/:id"},
{Method: "GET", Path: "/panel/api/inbounds/getSubLinks/:subId"},
{Method: "GET", Path: "/panel/api/inbounds/getClientLinks/:id/:email"},
{Method: "POST", Path: "/panel/api/inbounds/add"},
{Method: "POST", Path: "/panel/api/inbounds/del/:id"},
{Method: "POST", Path: "/panel/api/inbounds/update/:id"},
{Method: "POST", Path: "/panel/api/inbounds/setEnable/:id"},
{Method: "POST", Path: "/panel/api/inbounds/clientIps/:email"},
{Method: "POST", Path: "/panel/api/inbounds/clearClientIps/:email"},
{Method: "POST", Path: "/panel/api/inbounds/addClient"},
{Method: "POST", Path: "/panel/api/inbounds/:id/copyClients"},
{Method: "POST", Path: "/panel/api/inbounds/:id/delClient/:clientId"},
{Method: "POST", Path: "/panel/api/inbounds/updateClient/:clientId"},
{Method: "POST", Path: "/panel/api/inbounds/:id/resetClientTraffic/:email"},
{Method: "POST", Path: "/panel/api/inbounds/resetAllTraffics"},
{Method: "POST", Path: "/panel/api/inbounds/resetAllClientTraffics/:id"},
{Method: "POST", Path: "/panel/api/inbounds/delDepletedClients/:id"},
{Method: "POST", Path: "/panel/api/inbounds/import"},
{Method: "POST", Path: "/panel/api/inbounds/onlines"},
{Method: "POST", Path: "/panel/api/inbounds/lastOnline"},
{Method: "POST", Path: "/panel/api/inbounds/updateClientTraffic/:email"},
{Method: "POST", Path: "/panel/api/inbounds/:id/delClientByEmail/:email"},
// Server API — prefix /panel/api/server
{Method: "GET", Path: "/panel/api/server/status"},
{Method: "GET", Path: "/panel/api/server/cpuHistory/:bucket"},
{Method: "GET", Path: "/panel/api/server/history/:metric/:bucket"},
{Method: "GET", Path: "/panel/api/server/xrayMetricsState"},
{Method: "GET", Path: "/panel/api/server/xrayMetricsHistory/:metric/:bucket"},
{Method: "GET", Path: "/panel/api/server/xrayObservatory"},
{Method: "GET", Path: "/panel/api/server/xrayObservatoryHistory/:tag/:bucket"},
{Method: "GET", Path: "/panel/api/server/getXrayVersion"},
{Method: "GET", Path: "/panel/api/server/getPanelUpdateInfo"},
{Method: "GET", Path: "/panel/api/server/getConfigJson"},
{Method: "GET", Path: "/panel/api/server/getDb"},
{Method: "GET", Path: "/panel/api/server/getNewUUID"},
{Method: "GET", Path: "/panel/api/server/getNewX25519Cert"},
{Method: "GET", Path: "/panel/api/server/getNewmldsa65"},
{Method: "GET", Path: "/panel/api/server/getNewmlkem768"},
{Method: "GET", Path: "/panel/api/server/getNewVlessEnc"},
{Method: "POST", Path: "/panel/api/server/stopXrayService"},
{Method: "POST", Path: "/panel/api/server/restartXrayService"},
{Method: "POST", Path: "/panel/api/server/installXray/:version"},
{Method: "POST", Path: "/panel/api/server/updatePanel"},
{Method: "POST", Path: "/panel/api/server/updateGeofile"},
{Method: "POST", Path: "/panel/api/server/updateGeofile/:fileName"},
{Method: "POST", Path: "/panel/api/server/logs/:count"},
{Method: "POST", Path: "/panel/api/server/xraylogs/:count"},
{Method: "POST", Path: "/panel/api/server/importDB"},
{Method: "POST", Path: "/panel/api/server/getNewEchCert"},
// Nodes API — prefix /panel/api/nodes
{Method: "GET", Path: "/panel/api/nodes/list"},
{Method: "GET", Path: "/panel/api/nodes/get/:id"},
{Method: "POST", Path: "/panel/api/nodes/add"},
{Method: "POST", Path: "/panel/api/nodes/update/:id"},
{Method: "POST", Path: "/panel/api/nodes/del/:id"},
{Method: "POST", Path: "/panel/api/nodes/setEnable/:id"},
{Method: "POST", Path: "/panel/api/nodes/test"},
{Method: "POST", Path: "/panel/api/nodes/probe/:id"},
{Method: "GET", Path: "/panel/api/nodes/history/:id/:metric/:bucket"},
// Custom Geo API — prefix /panel/api/custom-geo
{Method: "GET", Path: "/panel/api/custom-geo/list"},
{Method: "GET", Path: "/panel/api/custom-geo/aliases"},
{Method: "POST", Path: "/panel/api/custom-geo/add"},
{Method: "POST", Path: "/panel/api/custom-geo/update/:id"},
{Method: "POST", Path: "/panel/api/custom-geo/delete/:id"},
{Method: "POST", Path: "/panel/api/custom-geo/download/:id"},
{Method: "POST", Path: "/panel/api/custom-geo/update-all"},
// Backup — prefix /panel/api
{Method: "GET", Path: "/panel/api/backuptotgbot"},
// Settings API — prefix /panel/setting
{Method: "POST", Path: "/panel/setting/all"},
{Method: "POST", Path: "/panel/setting/defaultSettings"},
{Method: "POST", Path: "/panel/setting/update"},
{Method: "POST", Path: "/panel/setting/updateUser"},
{Method: "POST", Path: "/panel/setting/restartPanel"},
{Method: "GET", Path: "/panel/setting/getDefaultJsonConfig"},
{Method: "GET", Path: "/panel/setting/getApiToken"},
{Method: "POST", Path: "/panel/setting/regenerateApiToken"},
// Xray Settings API — prefix /panel/xray
{Method: "POST", Path: "/panel/xray/"},
{Method: "GET", Path: "/panel/xray/getDefaultJsonConfig"},
{Method: "GET", Path: "/panel/xray/getOutboundsTraffic"},
{Method: "GET", Path: "/panel/xray/getXrayResult"},
{Method: "POST", Path: "/panel/xray/update"},
{Method: "POST", Path: "/panel/xray/warp/:action"},
{Method: "POST", Path: "/panel/xray/nord/:action"},
{Method: "POST", Path: "/panel/xray/resetOutboundsTraffic"},
{Method: "POST", Path: "/panel/xray/testOutbound"},
// WebSocket
{Method: "GET", Path: "/ws"},
// Subscription server — separate server (not on main Gin engine)
// Documented in Subscription Server section but not tested here
// because the sub server is a separate Gin engine.
// {Method: "GET", Path: "/sub/:subid"},
// {Method: "GET", Path: "/json/:subid"},
// {Method: "GET", Path: "/clash/:subid"},
}
// routePattern matches route registrations like g.GET("/path", handler) or api.GET("/path", handler)
var routePattern = regexp.MustCompile(`\b(g|api)\.(GET|POST|PUT|DELETE|PATCH|HEAD|OPTIONS)\("([^"]+)"`)
func TestAPIRoutesDocumented(t *testing.T) {
// Build a set of documented routes for fast lookup
docSet := make(map[string]bool)
for _, r := range expectedRoutes {
key := r.Method + " " + r.Path
if docSet[key] {
t.Errorf("Duplicate documented route: %s", key)
}
docSet[key] = true
}
// Walk the web directory to find all Go files with route definitions
controllerDir, err := filepath.Abs(".")
if err != nil {
t.Fatalf("failed to get current dir: %v", err)
}
// Collect all routes from the controller files
var allRoutes []routeDef
entries, err := os.ReadDir(controllerDir)
if err != nil {
t.Fatalf("failed to read controller dir: %v", err)
}
for _, entry := range entries {
if entry.IsDir() || !strings.HasSuffix(entry.Name(), ".go") || strings.HasSuffix(entry.Name(), "_test.go") {
continue
}
data, err := os.ReadFile(filepath.Join(controllerDir, entry.Name()))
if err != nil {
t.Fatalf("failed to read %s: %v", entry.Name(), err)
}
src := string(data)
// Determine the base path for this file based on its initRouter patterns
basePath := ""
switch entry.Name() {
case "index.go":
basePath = ""
case "xui.go":
basePath = "/panel"
case "api.go":
basePath = "/panel/api"
case "inbound.go":
basePath = "/panel/api/inbounds"
case "server.go":
basePath = "/panel/api/server"
case "node.go":
basePath = "/panel/api/nodes"
case "setting.go":
basePath = "/panel/setting"
case "xray_setting.go":
basePath = "/panel/xray"
case "custom_geo.go":
basePath = "/panel/api/custom-geo"
case "websocket.go":
basePath = ""
}
// Find all route registrations
matches := routePattern.FindAllStringSubmatch(src, -1)
for _, m := range matches {
method := m[2]
path := strings.TrimSpace(m[3])
if basePath == "" {
allRoutes = append(allRoutes, routeDef{Method: method, Path: path})
} else {
fullPath := basePath + path
allRoutes = append(allRoutes, routeDef{Method: method, Path: fullPath})
}
}
}
// The WebSocket route /ws is registered in web/web.go (not a controller file)
allRoutes = append(allRoutes, routeDef{Method: "GET", Path: "/ws"})
// Check each source route against the documented set
missingFromDocs := 0
foundInDoc := 0
sourceSet := make(map[string]bool)
for _, r := range allRoutes {
key := r.Method + " " + r.Path
// Skip SPA page routes (these are UI pages, not API endpoints)
spaPages := map[string]bool{
"/": true, "/panel/": true, "/panel/inbounds": true,
"/panel/nodes": true, "/panel/settings": true,
"/panel/xray": true, "/panel/api-docs": true,
}
if spaPages[r.Path] {
continue
}
// Skip /panel/csrf-token (documented under auth)
if r.Path == "/panel/csrf-token" {
continue
}
// Skip Chrome DevTools route
if strings.Contains(r.Path, ".well-known") {
continue
}
sourceSet[key] = true
if docSet[key] {
foundInDoc++
} else {
missingFromDocs++
t.Errorf("Route not documented in endpoints.js: %s %s", r.Method, r.Path)
}
}
// Report undocumented documented routes
extraInDocs := 0
for _, r := range expectedRoutes {
key := r.Method + " " + r.Path
if !sourceSet[key] {
extraInDocs++
t.Logf("Documented route not found in source (perhaps deleted or moved): %s %s", r.Method, r.Path)
}
}
t.Logf("Routes found in source: %d, documented: %d, matching: %d, missing: %d, extra in docs: %d",
len(sourceSet), len(docSet), foundInDoc, missingFromDocs, extraInDocs)
if missingFromDocs > 0 {
t.Errorf("Found %d undocumented route(s). Update endpoints.js to match.", missingFromDocs)
}
}