feat(gui): the spine — typed API, session, store, composables, theme

The backend's calls in one typed module with a session-scoped client
(a reset aborts every request, a 401 ends the session, a busy backend is
asked again for a read); the Pinia store; composables for dialogs,
notices, banners, loading, the message socket, the traffic ring buffer,
the log stream and outbound groups; the share-link codec moved from the
old editor; the Material 3 theme derived from a seed colour (tonal
spot, monochrome for colourless seeds), the type scale and the
component overrides.
This commit is contained in:
Zakk committed 2026-09-19 23:17:05 +10:00
1 parent 0daa826396
commit 89fb7d87b1
40 files changed
+3967

No files matched your search

+188
View File
@@ -0,0 +1,188 @@
// @vitest-environment happy-dom
import { beforeEach, describe, expect, test, vi } from "vitest";
import type { AxiosRequestConfig } from "axios";
import {
ApiError,
abortSession,
apiRoot,
call,
client,
setClientHooks,
} from "./client";
// A fake transport: records what the client sends and answers what the
// test scripted, so the assertions are on the wire shape, not on axios.
type Sent = {
url: string;
method: string;
headers: Record<string, unknown>;
query: string;
body: unknown;
};
const sent: Sent[] = [];
let reply: (
config: AxiosRequestConfig,
) => Promise<{ status: number; data: unknown }> = async () => ({
status: 200,
data: { code: "SUCCESS", data: {} },
});
client.defaults.adapter = async (config) => {
const serializer = config.paramsSerializer as
| ((p: unknown) => string)
| { serialize?: (p: unknown) => string }
| undefined;
const fn =
typeof serializer === "function" ? serializer : serializer?.serialize;
const query = fn && config.params ? fn(config.params) : "";
sent.push({
url: config.url ?? "",
method: config.method ?? "get",
headers: { ...(config.headers as Record<string, unknown>) },
query,
body: config.data,
});
const r = await reply(config);
if (r.status >= 400) {
const err = Object.assign(
new Error(`Request failed with status code ${r.status}`),
{
config,
response: { status: r.status, data: r.data, headers: {}, config },
isAxiosError: true,
},
);
throw err;
}
return {
status: r.status,
statusText: "OK",
headers: {},
config,
data: r.data,
};
};
beforeEach(() => {
sent.length = 0;
localStorage.setItem("backendAddress", "http://backend.test:2017");
localStorage.setItem("token", "tok-1");
reply = async () => ({
status: 200,
data: { code: "SUCCESS", data: { ok: 1 } },
});
});
describe("the client sends what the old components sent", () => {
test("token and request id only on the backend's own requests", async () => {
await call({ url: "touch", method: "get" });
expect(sent[0].url).toBe(`${apiRoot()}/touch`);
expect(sent[0].headers.Authorization).toBe("tok-1");
expect(String(sent[0].headers["X-V2raya-Request-Id"])).toMatch(
/^[A-Za-z0-9_-]{21}$/,
);
await client
.get("http://elsewhere.test/api/version")
.catch(() => undefined);
expect(sent[1].headers.Authorization).toBeUndefined();
expect(sent[1].headers["X-V2raya-Request-Id"]).toBeUndefined();
});
test("object query parameters go as JSON text", async () => {
await call({
url: "sharingAddress",
method: "get",
params: { touch: { id: 1, _type: "server" }, n: 2, skip: undefined },
});
expect(sent[0].query).toBe(
`touch=${encodeURIComponent('{"id":1,"_type":"server"}')}&n=2`,
);
});
test("a FAIL envelope is an error with the backend's message", async () => {
reply = async () => ({
status: 200,
data: {
code: "FAIL",
message: "no such node",
errorCode: "NODE_NOT_FOUND",
data: null,
},
});
const err = (await call({ url: "touch", method: "get" }).catch(
(e) => e,
)) as ApiError;
expect(err).toBeInstanceOf(ApiError);
expect(err.kind).toBe("http");
expect(err.body?.errorCode).toBe("NODE_NOT_FOUND");
});
test("a busy backend is asked again for a read, not for a write", async () => {
vi.useFakeTimers();
let calls = 0;
reply = async () => {
calls++;
return calls < 3
? {
status: 200,
data: {
code: "FAIL",
message: "busy",
errorCode: "REQUEST_IN_PROGRESS",
data: null,
},
}
: { status: 200, data: { code: "SUCCESS", data: { ok: true } } };
};
const read = call<{ ok: boolean }>({ url: "touch", method: "get" });
await vi.advanceTimersByTimeAsync(400);
await vi.advanceTimersByTimeAsync(800);
expect(await read).toEqual({ ok: true });
expect(calls).toBe(3);
calls = 0;
const err = (await call({ url: "v2ray", method: "post" }).catch(
(e) => e,
)) as ApiError;
expect(err.body?.errorCode).toBe("REQUEST_IN_PROGRESS");
expect(calls).toBe(1);
vi.useRealTimers();
});
test("401 outside login and account calls the hook", async () => {
const onUnauthorized = vi.fn();
setClientHooks({ onUnauthorized });
reply = async () => ({
status: 401,
data: { code: "FAIL", message: "unauthorized", data: null },
});
await call({ url: "touch", method: "get" }).catch(() => undefined);
expect(onUnauthorized).toHaveBeenCalledTimes(1);
await call({
url: "login",
method: "post",
data: { username: "u", password: "p" },
}).catch(() => undefined);
expect(onUnauthorized).toHaveBeenCalledTimes(1);
setClientHooks({ onUnauthorized: undefined });
});
test("a response from a previous session is refused", async () => {
let release!: () => void;
reply = () =>
new Promise(
(r) =>
(release = () =>
r({
status: 200,
data: { code: "SUCCESS", data: { late: true } },
})),
);
const p = call({ url: "touch", method: "get" }).catch((e) => e as ApiError);
await new Promise((r) => setTimeout(r, 0)); // the transport is now waiting
abortSession();
release();
const err = (await p) as ApiError;
expect(err).toBeInstanceOf(ApiError);
expect(["stale", "cancelled"]).toContain(err.kind);
});
});
+250
View File
@@ -0,0 +1,250 @@
// One HTTP client for the redo. It carries what plugins/axios.js gave the
// old components — the JSON query serializer the backend reads, the token
// and request id on the backend's own requests only, the 401 handling —
// and nothing of the old file's UI: an error comes back as an ApiError the
// caller (or the app's error handler) turns into a notice.
import axios, {
AxiosError,
type AxiosRequestConfig,
type AxiosResponse,
} from "axios";
import { nanoid } from "nanoid";
import { reactive, readonly } from "vue";
export type ApiErrorKind =
"http" | "network" | "timeout" | "mixed-content" | "cancelled" | "stale";
export class ApiError extends Error {
kind: ApiErrorKind;
status?: number;
/** The backend's envelope when it answered: code, message, errorCode, params. */
body?: ApiEnvelope<unknown>;
url: string;
constructor(
kind: ApiErrorKind,
message: string,
url: string,
extra: { status?: number; body?: ApiEnvelope<unknown> } = {},
) {
super(message);
this.name = "ApiError";
this.kind = kind;
this.url = url;
this.status = extra.status;
this.body = extra.body;
}
}
/** The backend's response envelope. */
export interface ApiEnvelope<T> {
code: "SUCCESS" | "FAIL" | string;
message?: string;
errorCode?: string;
params?: Record<string, unknown>;
data: T;
}
/** The backend address as stored; empty means same origin. */
export function backendAddress(): string {
return localStorage.getItem("backendAddress") ?? "";
}
export function apiRoot(): string {
return `${backendAddress()}/api`;
}
// Per-operation timeouts the old components set on their calls; the
// default is the client's.
export const timeouts = {
default: 60_000,
import: 120_000,
/** latency tests, saving a node, updating GFWList: no limit */
none: 0,
} as const;
// A session is one token on one backend. Requests carry the session's
// number; when the session is reset (logout, another backend) the ones in
// flight are aborted and a response that still arrives is refused, so it
// cannot write into the new session's state.
let sessionNumber = 0;
const inFlight = new Set<AbortController>();
export function currentSession(): number {
return sessionNumber;
}
/** abortSession aborts every request in flight and starts a new session number. */
export function abortSession(): void {
sessionNumber++;
for (const c of inFlight) c.abort();
inFlight.clear();
}
type Hooks = {
/** A 401 on a request that is not the login or registration call. */
onUnauthorized?: () => void;
/** Any failure other than a cancellation; the app decides how to show it. */
onError?: (err: ApiError) => void;
/** The backend answered: whatever said it was unreachable can go. */
onReached?: () => void;
};
const hooks: Hooks = {};
export function setClientHooks(h: Hooks): void {
Object.assign(hooks, h);
}
export const client = axios.create({
timeout: timeouts.default,
// The backend reads object query parameters (touch, whiches) as JSON
// text, which is how axios 0.21 serialized them; later versions expand
// them into touch[id]=… instead.
paramsSerializer: (params) =>
Object.entries(params as Record<string, unknown>)
.filter(([, v]) => v !== undefined && v !== null)
.map(
([k, v]) =>
`${encodeURIComponent(k)}=${encodeURIComponent(typeof v === "object" ? JSON.stringify(v) : String(v))}`,
)
.join("&"),
});
client.interceptors.request.use((config) => {
const url = config.url ?? "";
// Only the backend that issued the token gets it: the address dialog
// probes a user-typed URL with /api/version and that must go bare.
const token = localStorage.getItem("token");
if (token !== null && url.startsWith(apiRoot())) {
config.headers = {
...config.headers,
Authorization: token,
"X-V2raya-Request-Id": nanoid(),
};
}
// Every request gets the session's controller, so a reset aborts it; a
// caller's own signal (the connect watcher) is joined to it.
const controller = new AbortController();
inFlight.add(controller);
const own = config.signal as AbortSignal | undefined;
config.signal = own
? AbortSignal.any([own, controller.signal])
: controller.signal;
(config as SessionConfig).sessionController = controller;
(config as SessionConfig).session = sessionNumber;
return config;
});
interface SessionConfig extends AxiosRequestConfig {
session?: number;
sessionController?: AbortController;
}
function settle(config: SessionConfig | undefined) {
if (config?.sessionController) inFlight.delete(config.sessionController);
}
client.interceptors.response.use(
(res: AxiosResponse) => {
settle(res.config as SessionConfig);
if ((res.config as SessionConfig).session !== sessionNumber) {
throw new ApiError(
"stale",
"response from a previous session",
res.config.url ?? "",
);
}
hooks.onReached?.();
return res;
},
(raw: unknown) => {
// axios's isCancel is a type guard to Cancel, which would narrow the
// error to never in the branches below; keep the error untyped here.
const err = raw as AxiosError<ApiEnvelope<unknown>>;
const config = err.config as SessionConfig | undefined;
settle(config);
const url = config?.url ?? "";
const cancelled = axios.isCancel(raw) || err.code === "ERR_CANCELED";
let apiErr: ApiError;
if (cancelled) {
apiErr = new ApiError("cancelled", "cancelled", url);
} else if (config && config.session !== sessionNumber) {
apiErr = new ApiError("stale", "response from a previous session", url);
} else if (err.code === "ECONNABORTED") {
apiErr = new ApiError("timeout", err.message, url);
} else if (err.response) {
apiErr = new ApiError("http", err.message, url, {
status: err.response.status,
body: err.response.data,
});
const isAuthAction =
url.includes("/api/login") || url.includes("/api/account");
if (err.response.status === 401 && !isAuthAction) {
hooks.onUnauthorized?.();
}
} else if (location.protocol === "https:" && /^http:\/\//i.test(url)) {
// an https page cannot reach an http backend; the browser blocks it
apiErr = new ApiError("mixed-content", err.message, url);
} else {
apiErr = new ApiError("network", err.message, url);
}
if (apiErr.kind !== "cancelled" && apiErr.kind !== "stale")
hooks.onError?.(apiErr);
return Promise.reject(apiErr);
},
);
// how many calls are in flight; the shell's progress bar reads it
const activity = reactive({ inFlight: 0 });
export const requestActivity = readonly(activity);
/** call performs one backend operation and unwraps the envelope; a FAIL envelope is an ApiError of kind http with status 200. */
// The backend serves one state-changing request at a time and answers
// REQUEST_IN_PROGRESS to a read that arrives meanwhile (a touch during a
// latency test, say). A read waits and asks again a few times before the
// page hears of it.
const busyRetries = [400, 800, 1600];
export async function call<T>(
config: AxiosRequestConfig & { url: string },
): Promise<T> {
const url =
config.url.startsWith("http") || config.url.startsWith("/")
? config.url
: `${apiRoot()}/${config.url}`;
const isRead = (config.method ?? "get").toLowerCase() === "get";
for (let attempt = 0; ; attempt++) {
activity.inFlight++;
let res;
try {
res = await client.request<ApiEnvelope<T>>({ ...config, url });
} finally {
activity.inFlight--;
}
const body = res.data;
if (body?.code === "SUCCESS") return body.data;
if (
isRead &&
body?.errorCode === "REQUEST_IN_PROGRESS" &&
attempt < busyRetries.length
) {
await new Promise((r) => setTimeout(r, busyRetries[attempt]));
continue;
}
throw new ApiError("http", body?.message ?? "request failed", config.url, {
status: res.status,
body,
});
}
}
/** probe asks another backend for its version without credentials; the address dialog uses it. */
export async function probe(
address: string,
timeout = 5_000,
): Promise<ApiEnvelope<{ version: string }>> {
const res = await axios.get<ApiEnvelope<{ version: string }>>(
`${address}/api/version`,
{ timeout },
);
return res.data;
}
+71
View File
@@ -0,0 +1,71 @@
// The old networkInspect.waitingConnected: while a request that changes
// the proxy runs (start, connect, a new outbound), the transparent proxy
// it sets up can cut the very connection carrying the answer. So GET
// /touch is polled meanwhile; once the core reports running with a
// connected server the work is done, the request is abandoned and the
// poll stops. The poll also stops when the request settles, on a 401,
// and after `timeout` at the latest.
import { getTouch } from "./index";
import { ApiError } from "./client";
export interface WatchOptions {
/** poll period and the poll's own timeout, ms */
interval?: number;
/** hard stop for the poll, ms */
timeout?: number;
/** a FAIL from /touch other than "request in progress" */
onCheckFailed?: (err: ApiError) => void;
}
/** watchConnected runs `request` and resolves with its result, or with `undefined` when the poll saw the core connected first. */
export function watchConnected<T>(
request: Promise<T>,
abort: () => void,
{ interval = 3000, timeout = 30_000, onCheckFailed }: WatchOptions = {},
): Promise<T | undefined> {
let settled = false;
let timer: ReturnType<typeof setInterval> | null = null;
const stop = () => {
if (timer !== null) clearInterval(timer);
timer = null;
};
return new Promise<T | undefined>((resolve, reject) => {
const finish = (fn: () => void) => {
if (settled) return;
settled = true;
stop();
fn();
};
timer = setInterval(async () => {
try {
const touch = await getTouch({ timeout: interval });
if (touch.running && touch.touch.connectedServer) {
abort();
finish(() => resolve(undefined));
}
} catch (err) {
if (!(err instanceof ApiError)) return;
if (err.status === 401) {
abort();
finish(() => reject(err));
} else if (
err.kind === "http" &&
err.body?.errorCode !== "REQUEST_IN_PROGRESS" &&
err.body?.message !== "the last request is being processed"
) {
onCheckFailed?.(err);
}
}
}, interval);
setTimeout(stop, timeout);
request.then(
(v) => finish(() => resolve(v)),
(e) => {
// the abort above rejects the request with a cancellation, which
// the poll already answered
if (settled) return;
finish(() => reject(e));
},
);
});
}
+25
View File
@@ -0,0 +1,25 @@
// The text a failed operation shows. The backend answers with an
// errorCode and params that the locale's backend.* messages know, or with
// a message of its own; a transport failure has the client's message.
// Plain text: the notice renders it as text, so nothing is escaped here.
import i18n from "@/plugins/i18n";
import { ApiError } from "./client";
export function errorText(err: unknown): string {
const t = i18n.global.t;
if (!(err instanceof ApiError)) {
return err instanceof Error && err.message ? err.message : t("common.fail");
}
const body = err.body;
if (body) {
const code = body.errorCode;
if (code && i18n.global.te("backend." + code)) {
return t("backend." + code, {
...(body.params ?? {}),
message: body.message,
});
}
if (body.message) return body.message;
}
return err.message || t("common.fail");
}
+188
View File
@@ -0,0 +1,188 @@
// One function per backend operation (method + path), 41 in all, named
// <method><Path>. Bodies and queries are what the old components sent, so
// the recorded requests match byte for byte; types narrow them where the
// backend's Go types are known (types.ts) and stay open elsewhere.
import { apiRoot, call, client, timeouts } from "./client";
/** What a caller may attach to a request: the connect watcher aborts through `signal`, its poll shortens `timeout`. */
export interface RequestOptions {
signal?: AbortSignal;
timeout?: number;
}
import type {
CustomInbound,
DnsRule,
DnsRulesResponse,
Ports,
Setting,
SettingResponse,
TouchResponse,
VersionResponse,
Which,
} from "./types";
// ---- account and session ----------------------------------------------
export const getAccount = () =>
call<{ hasAnyAccounts: boolean }>({ url: "account", method: "get" });
export const postAccount = (body: { username: string; password: string }) =>
call<{ token: string }>({ url: "account", method: "post", data: body });
export const postLogin = (body: { username: string; password: string }) =>
call<{ token: string }>({ url: "login", method: "post", data: body });
export const getVersion = () =>
call<VersionResponse>({ url: "version", method: "get" });
// ---- nodes and subscriptions ---------------------------------------------
export const getTouch = (o: RequestOptions = {}) =>
call<TouchResponse>({ url: "touch", method: "get", ...o });
export const deleteTouch = (touches: Which[]) =>
call<TouchResponse>({ url: "touch", method: "delete", data: { touches } });
// The editor sends `which: null` for a new node, as the old page did; the
// key stays in the body. Saving one node has no time limit, a batch has.
export const postImport = (
body: { url: string; kind?: string; which?: Which | null },
timeout: number = timeouts.import,
) =>
call<TouchResponse>({ url: "import", method: "post", data: body, timeout });
export const getSharingAddress = (touch: Which) =>
call<{ sharingAddress: string }>({
url: "sharingAddress",
method: "get",
params: { touch },
});
export const putSubscription = (which: Which) =>
call<TouchResponse>({ url: "subscription", method: "put", data: which });
export const patchSubscription = (body: Record<string, unknown>) =>
call<TouchResponse>({ url: "subscription", method: "patch", data: body });
export const getPingLatency = (whiches: Which[]) =>
call<{ whiches: Which[] }>({
url: "pingLatency",
method: "get",
params: { whiches },
timeout: timeouts.none,
});
export const getHttpLatency = (whiches: Which[]) =>
call<{ whiches: Which[] }>({
url: "httpLatency",
method: "get",
params: { whiches },
timeout: timeouts.none,
});
// ---- connections and the core ---------------------------------------------
export const postConnection = (which: Which, o: RequestOptions = {}) =>
call<TouchResponse>({ url: "connection", method: "post", data: which, ...o });
export const deleteConnection = (which: Which) =>
call<TouchResponse>({ url: "connection", method: "delete", data: which });
export const putOutboundConnections = (body: {
outbound: string;
touches: Which[];
}) =>
call<TouchResponse>({
url: "outboundConnections",
method: "put",
data: body,
});
/** the member a group routes through alone; null returns it to balancing */
export const putOutboundSelection = (body: {
outbound: string;
which: Which | null;
}) =>
call<TouchResponse>({
url: "outboundSelection",
method: "put",
data: body,
});
export const postV2ray = (o: RequestOptions = {}) =>
call<TouchResponse>({ url: "v2ray", method: "post", ...o });
export const deleteV2ray = () =>
call<TouchResponse>({ url: "v2ray", method: "delete" });
// ---- outbound groups ---------------------------------------------------------
export const getOutbounds = () =>
call<{ outbounds: string[] }>({ url: "outbounds", method: "get" });
export interface OutboundSetting {
probeURL: string;
probeInterval: string;
type: string;
/** the share link of the member routed through alone; empty balances */
selected?: string;
}
export const getOutbound = (outbound: string) =>
call<{ setting: OutboundSetting }>({
url: "outbound",
method: "get",
params: { outbound },
});
export const postOutbound = (
body: Record<string, unknown>,
o: RequestOptions = {},
) => call<unknown>({ url: "outbound", method: "post", data: body, ...o });
export const putOutbound = (body: {
outbound: string;
setting: OutboundSetting;
}) => call<unknown>({ url: "outbound", method: "put", data: body });
export const deleteOutbound = (
body: Record<string, unknown>,
o: RequestOptions = {},
) => call<unknown>({ url: "outbound", method: "delete", data: body, ...o });
// ---- settings ------------------------------------------------------------------
export const getSetting = () =>
call<SettingResponse>({ url: "setting", method: "get" });
export const putSetting = (setting: Setting, o: RequestOptions = {}) =>
call<unknown>({ url: "setting", method: "put", data: setting, ...o });
export const getPorts = () => call<Ports>({ url: "ports", method: "get" });
export const putPorts = (ports: Ports) =>
call<unknown>({ url: "ports", method: "put", data: ports });
export const getCustomInbound = () =>
call<{ inbounds: CustomInbound[] }>({ url: "customInbound", method: "get" });
export const postCustomInbound = (body: CustomInbound) =>
call<unknown>({ url: "customInbound", method: "post", data: body });
export const deleteCustomInbound = (body: { tag: string }) =>
call<unknown>({ url: "customInbound", method: "delete", data: body });
export const getRoutingA = () =>
call<{ routingA: string }>({ url: "routingA", method: "get" });
export const putRoutingA = (body: { routingA: string }) =>
call<unknown>({ url: "routingA", method: "put", data: body });
export const getDnsRules = () =>
call<DnsRulesResponse>({ url: "dnsRules", method: "get" });
export const putDnsRules = (body: DnsRule[]) =>
call<unknown>({ url: "dnsRules", method: "put", data: body });
export const getDomainsExcluded = () =>
call<{ domains: string }>({ url: "domainsExcluded", method: "get" });
export const putDomainsExcluded = (body: { domains: string }) =>
call<unknown>({ url: "domainsExcluded", method: "put", data: body });
export const getTproxyWhiteIpGroups = () =>
call<{ countryCodes: string[]; customIps: string[] }>({
url: "tproxyWhiteIpGroups",
method: "get",
});
export const putTproxyWhiteIpGroups = (body: {
countryCodes: string[];
customIps: string[];
}) => call<unknown>({ url: "tproxyWhiteIpGroups", method: "put", data: body });
export const getRemoteGFWListVersion = () =>
call<{ remoteGFWListVersion: string }>({
url: "remoteGFWListVersion",
method: "get",
});
export const putGfwList = (body: { downloadLink: string }) =>
call<{ localGFWListVersion: string; alreadyUpToDate?: boolean }>({
url: "gfwList",
method: "put",
data: body,
timeout: timeouts.none,
});
export const deleteGfwList = () =>
call<unknown>({ url: "gfwList", method: "delete" });
// ---- logs ------------------------------------------------------------------------
/** GET /logger answers plain text from the byte offset `skip`, not the envelope. */
export const getLogger = async (params: { skip: number }): Promise<string> => {
const res = await client.get<string>(`${apiRoot()}/logger`, {
params,
responseType: "text",
transformResponse: (data) => data,
});
return typeof res.data === "string" ? res.data : "";
};
+156
View File
@@ -0,0 +1,156 @@
// Shapes the backend sends and accepts, named after the Go types they come
// from (service/kernel/touch, service/db/configure). Fields the redo does
// not read are left out on purpose; a widening is a one-line change here.
export type TouchType = "server" | "subscription" | "subscriptionServer";
/** configure.Which — how the backend addresses one node or subscription. */
export interface Which {
_type: TouchType;
id: number;
/** subscription index, only for subscriptionServer */
sub?: number;
pingLatency?: string;
Link?: string;
outbound?: string;
/** in a touch's connectedServer: the member its group routes through alone */
selected?: boolean;
}
/** touch.Server; `sub` and `connected` are the page's own marks on a row */
export interface TouchServer {
id: number;
_type: TouchType;
name: string;
address: string;
net: string;
pingLatency: string;
sub?: number;
connected?: boolean;
}
/** touch.Subscription */
export interface TouchSubscription {
id: number;
_type: TouchType;
remarks?: string;
host: string;
address: string;
status: string;
info: string;
servers: TouchServer[];
autoSelect: boolean;
}
/** touch.Touch */
export interface Touch {
servers: TouchServer[];
subscriptions: TouchSubscription[];
connectedServer: Which[] | null;
}
/** GET /touch */
export interface TouchResponse {
running: boolean;
networkPaused: boolean;
touch: Touch;
}
/** GET /version */
export interface VersionResponse {
version: string;
foundNew: boolean;
remoteVersion: string;
serviceValid: boolean;
v5: boolean;
/** 0 or 1: the backend sends its lite flag as a number */
lite: number;
loadBalanceValid: boolean;
variant: string;
/** the core binary's version; empty when it could not be asked */
coreVersion?: string;
os: string;
isRoot: boolean;
tunSupported: boolean;
coreVersionValid: boolean;
coreVersionErr: string;
hasAccounts: boolean;
lastKernelExit: unknown;
docker?: boolean;
}
/** configure.Setting — kept as the backend's own keys; the settings dialog owns the full list. */
export type Setting = Record<string, unknown> & {
transparent: string;
transparentType: string;
pacMode: string;
logLevel: string;
};
/** GET /setting */
export interface SettingResponse {
setting: Setting;
localGFWListVersion: string;
}
/** configure.Ports */
export interface Ports {
socks5: number;
http: number;
socks5WithPac: number;
httpWithPac: number;
vmess: number;
vmessLink?: string;
api: { port: number; services: string[] };
}
/** configure.CustomInbound */
export interface CustomInbound {
tag: string;
protocol: "socks" | "http";
port: number;
outbound: string;
outboundType: "direct" | "routingA" | string;
routingARules: string;
username: string;
password: string;
}
export interface DnsRule {
server: string;
domains: string;
outbound: string;
}
export interface DnsRulesResponse {
rules?: Partial<DnsRule>[] | null;
}
/** The WebSocket frames on /api/message: the ones the interface reads, and any other the backend may add. */
export interface RunningStateMessage {
type: "running_state";
body: { running: boolean; networkPaused?: boolean };
}
/** kernel/v2ray OutboundStatus: what the core's observatory saw of one connected node */
export interface OutboundStatus {
alive: boolean;
delay: number;
outbound_tag: string;
which: Which;
last_seen_time: number;
last_try_time: number;
}
export interface ObservatoryMessage {
type: "observatory";
body: { outboundName: string; outboundStatus: OutboundStatus[] };
}
export interface TrafficMessage {
type: "traffic";
body: {
up: number;
down: number;
upTotal: number;
downTotal: number;
};
}
export type WsMessage = { type: string; body?: unknown };
+76
View File
@@ -0,0 +1,76 @@
// What the app does with a failed request beyond the caller's own notice:
// a 401 ends the session, and a backend that cannot be reached is
// announced once per address with the way out (the address dialog, the
// manual). This is the old axios interceptor's UI, as a banner.
import { setClientHooks, type ApiError } from "@/api/client";
import { showBanner, withdrawBanner } from "@/composables/useBanner";
import i18n from "@/plugins/i18n";
import { resetSession } from "@/session";
import { useAppStore } from "@/stores/app";
let informed = "";
export function installClientHooks(ui: { openAddressDialog(): void }): void {
const t = i18n.global.t;
const informNotRunning = (url: string) => {
if (informed === url) return;
informed = url;
showBanner({
key: "backend",
kind: "warning",
text: t("axios.messages.noBackendFound", { url }),
action: {
label: t("axios.messages.optimizeBackend"),
onClick: ui.openAddressDialog,
},
});
};
setClientHooks({
onReached() {
// the backend is back: the banner about it goes, and a later outage
// is announced afresh
if (informed) withdrawBanner("backend");
informed = "";
},
onUnauthorized() {
const store = useAppStore();
if (store.loggedIn) void resetSession({ token: "" });
},
onError(err: ApiError) {
const origin = originOf(err.url);
if (err.kind === "mixed-content") {
const host = new URL(err.url).hostname;
const local = ["localhost", "local", "127.0.0.1"].includes(host);
const ua = navigator.userAgent;
if (local && ua.includes("AppleWebKit")) {
// Chrome allows an https page to reach http://localhost; the
// failure means the service is not running there
informNotRunning(origin);
return;
}
const gecko = ua.includes("Gecko") && !ua.includes("KHTML");
showBanner({
key: "backend",
kind: "warning",
text: t(`axios.messages.cannotCommunicate.${local && gecko ? 1 : 0}`),
action: {
label: t("operations.switchSite"),
onClick: () => window.open("http://v.v2raya.org", "_self"),
},
});
} else if (err.kind === "network") {
informNotRunning(origin);
}
},
});
}
/** originOf gives the backend's origin for a request URL: the absolute address, or this page's for a relative one. */
function originOf(url: string): string {
try {
return new URL(url, location.href).origin;
} catch {
return url;
}
}
+74
View File
@@ -0,0 +1,74 @@
// @vitest-environment happy-dom
import { describe, expect, test, vi } from "vitest";
import {
closeAllNotices,
dismissNotice,
noticeState,
useNotify,
} from "./useNotify";
import { closeAllDialogs, dialogState, openDialog } from "./useDialog";
import { closeAllLoadings, loadingState, openLoading } from "./useLoading";
describe("useNotify shows one notice at a time", () => {
test("queues in order and advances on dismiss", () => {
closeAllNotices();
const notify = useNotify();
const a = notify.info("a");
const b = notify.error("b");
expect(noticeState.current?.id).toBe(a);
expect(noticeState.queue.map((n) => n.id)).toEqual([b]);
dismissNotice(a);
expect(noticeState.current?.id).toBe(b);
expect(noticeState.current?.timeout).toBe(8000);
dismissNotice(b);
expect(noticeState.current).toBeNull();
});
test("a queued notice can be removed before it shows", () => {
closeAllNotices();
const notify = useNotify();
notify.info("a");
const b = notify.info("b");
dismissNotice(b);
expect(noticeState.queue).toHaveLength(0);
});
});
describe("useDialog resolves through the handle", () => {
test("close resolves the result and removes the entry", async () => {
closeAllDialogs();
const h = openDialog<string>({ render: () => null }, { x: 1 });
expect(dialogState.stack).toHaveLength(1);
h.close("done");
expect(dialogState.stack).toHaveLength(0);
await expect(h.result).resolves.toBe("done");
});
test("closeAll closes the child first", async () => {
const order: number[] = [];
const a = openDialog({ render: () => null });
const b = openDialog({ render: () => null });
a.result.then(() => order.push(a.id));
b.result.then(() => order.push(b.id));
closeAllDialogs();
await Promise.all([a.result, b.result]);
expect(order).toEqual([b.id, a.id]);
});
});
describe("useLoading keeps the overlay until the last handle closes", () => {
test("two handles, two closes", () => {
closeAllLoadings();
const a = openLoading();
const b = openLoading();
expect(loadingState.open.size).toBe(2);
a.close();
expect(loadingState.open.size).toBe(1);
b.close();
expect(loadingState.open.size).toBe(0);
});
test("closeAll drops every handle", () => {
openLoading();
closeAllLoadings();
expect(loadingState.open.size).toBe(0);
vi.restoreAllMocks();
});
});
+18
View File
@@ -0,0 +1,18 @@
export { useNotify, dismissNotice, closeAllNotices } from "./useNotify";
export {
useBanner,
showBanner,
withdrawBanner,
closeAllBanners,
} from "./useBanner";
export {
useDialog,
openDialog,
closeDialog,
closeAllDialogs,
} from "./useDialog";
export { useLoading, openLoading, closeAllLoadings } from "./useLoading";
export { useConfirm, usePrompt } from "./useConfirm";
export { useMessageSocket, createMessageSocket } from "./useWebSocket";
export { useTraffic } from "./useTraffic";
export { useOutboundGroups } from "./useOutboundGroups";
+42
View File
@@ -0,0 +1,42 @@
import { reactive, readonly } from "vue";
// Banners are the persistent notices — a new version, a core that does
// not match, a backend that cannot be reached — shown at the top of the
// page until dismissed or withdrawn, with an action when there is one.
// A notice with the same key replaces the earlier one.
export interface Banner {
key: string;
kind: "info" | "warning" | "error";
text: string;
action?: { label: string; onClick: () => void };
/** the user may close it; false keeps it until withdrawn */
dismissible: boolean;
}
const state = reactive({ list: [] as Banner[] });
/** showBanner adds or replaces the banner with that key. */
export function showBanner(
banner: Omit<Banner, "dismissible"> & { dismissible?: boolean },
): void {
const entry: Banner = { dismissible: true, ...banner };
const i = state.list.findIndex((b) => b.key === banner.key);
if (i >= 0) state.list.splice(i, 1, entry);
else state.list.push(entry);
}
export function withdrawBanner(key: string): void {
const i = state.list.findIndex((b) => b.key === key);
if (i >= 0) state.list.splice(i, 1);
}
/** closeAllBanners drops every banner; the session reset calls it. */
export function closeAllBanners(): void {
state.list.length = 0;
}
export const bannerState = readonly(state);
export function useBanner() {
return { show: showBanner, withdraw: withdrawBanner };
}
+40
View File
@@ -0,0 +1,40 @@
import ConfirmDialog from "@/components/hosts/ConfirmDialog.vue";
import { openDialog } from "./useDialog";
export interface ConfirmOptions {
title?: string;
message: string;
confirmText?: string;
cancelText?: string;
destructive?: boolean;
}
/** useConfirm resolves true on confirm, false on cancel, ESC or the scrim. */
export function useConfirm() {
return (options: ConfirmOptions): Promise<boolean> =>
openDialog<boolean>(
ConfirmDialog,
{ ...options },
{ width: 440 },
).result.then((r) => r === true);
}
export interface PromptOptions extends Omit<ConfirmOptions, "destructive"> {
input: {
label?: string;
placeholder?: string;
value?: string;
maxlength?: number;
validate?: (v: string) => string | true;
};
}
/** usePrompt resolves the entered text, or null on cancel. */
export function usePrompt() {
return (options: PromptOptions): Promise<string | null> =>
openDialog<string | null>(
ConfirmDialog,
{ ...options },
{ width: 440 },
).result.then((r) => (typeof r === "string" ? r : null));
}
+71
View File
@@ -0,0 +1,71 @@
import { markRaw, reactive, readonly, type Component } from "vue";
// Dialogs open programmatically with
// a component: the host renders them from this stack, the caller gets a
// handle and a promise for the result. Nested dialogs close child first.
export interface DialogEntry {
id: number;
component: Component;
props: Record<string, unknown>;
/** ESC and the scrim do nothing; only the dialog's own controls close it */
persistent: boolean;
/** Vuetify's max-width */
width: number | string;
resolve: (value: unknown) => void;
open: boolean;
}
export interface DialogHandle<T = unknown> {
id: number;
close(result?: T): void;
result: Promise<T | undefined>;
}
const state = reactive({ stack: [] as DialogEntry[] });
let nextId = 1;
export function openDialog<T = unknown>(
component: Component,
props: Record<string, unknown> = {},
options: { persistent?: boolean; width?: number | string } = {},
): DialogHandle<T> {
let resolve!: (v: unknown) => void;
const result = new Promise<T | undefined>(
(r) => (resolve = r as (v: unknown) => void),
);
const entry: DialogEntry = {
id: nextId++,
component: markRaw(component),
props,
persistent: options.persistent ?? false,
width: options.width ?? 640,
resolve,
open: true,
};
state.stack.push(entry);
return {
id: entry.id,
close: (value?: T) => closeDialog(entry.id, value),
result,
};
}
/** closeDialog resolves and removes one dialog; the host calls it after the closing transition too. */
export function closeDialog(id: number, result?: unknown): void {
const i = state.stack.findIndex((d) => d.id === id);
if (i < 0) return;
const [entry] = state.stack.splice(i, 1);
entry.resolve(result);
}
/** closeAllDialogs closes from the top of the stack down; the session reset calls it. */
export function closeAllDialogs(): void {
while (state.stack.length)
closeDialog(state.stack[state.stack.length - 1].id);
}
export const dialogState = readonly(state);
export function useDialog() {
return { open: openDialog, close: closeDialog };
}
+23
View File
@@ -0,0 +1,23 @@
import { reactive, readonly } from "vue";
// A full-page overlay while something runs. Several callers may hold one
// at once; the overlay stays until the last handle closes.
const state = reactive({ open: new Set<number>() });
let nextId = 1;
export function openLoading(): { close(): void } {
const id = nextId++;
state.open.add(id);
return { close: () => state.open.delete(id) };
}
/** closeAllLoadings drops every handle; the session reset calls it. */
export function closeAllLoadings(): void {
state.open.clear();
}
export const loadingState = readonly(state);
export function useLoading() {
return { open: openLoading };
}
+37
View File
@@ -0,0 +1,37 @@
// @vitest-environment happy-dom
import { describe, expect, test, vi } from "vitest";
vi.mock("@/api", () => ({ getLogger: vi.fn() }));
import { detectLevel, detectSource, useLogStream } from "./useLogStream";
describe("the log stream", () => {
test("a chunk ending mid-line is completed by the next chunk", () => {
const s = useLogStream();
s.append("2026/09/19 [I] [main.go:24] Start");
expect(s.lines.value.map((l) => l.text)).toEqual([
"2026/09/19 [I] [main.go:24] Start",
]);
s.append("ing...\n2026/09/19 [W] [tun.go:9] warn\n");
expect(s.lines.value.map((l) => l.text)).toEqual([
"2026/09/19 [I] [main.go:24] Starting...",
"2026/09/19 [W] [tun.go:9] warn",
]);
expect(s.lines.value[1].level).toBe("warn");
expect(s.sources.value).toEqual(["main.go", "tun.go"]);
});
test("multi-byte text advances the offset by bytes", async () => {
const api = await import("@/api");
const s = useLogStream();
s.append("中文\n");
await s.fetch();
expect(api.getLogger).toHaveBeenCalledWith({ skip: 7 });
});
test("level and source detection", () => {
expect(detectLevel("x [E] boom")).toBe("error");
expect(detectLevel("plain")).toBe("other");
expect(detectSource("[A] [index.go:224] listening")).toBe("index.go");
expect(detectSource("[LoggerService] up")).toBe("LoggerService");
});
});
+109
View File
@@ -0,0 +1,109 @@
// The core's log as a growing list of lines: GET /logger from a byte
// offset every few seconds, a half line kept until its rest arrives,
// the level and source of each line read off its text. Scope-bound:
// the timer stops with the component.
import { computed, onScopeDispose, ref, watch } from "vue";
import { getLogger } from "@/api";
export interface LogLine {
id: number;
text: string;
level: string;
source: string;
}
export function detectLevel(text: string): string {
const lower = text.toLowerCase();
if (lower.includes("[e]") || lower.includes(" error ")) return "error";
if (lower.includes("[w]") || lower.includes(" warn")) return "warn";
if (lower.includes("[d]") || lower.includes(" debug")) return "debug";
if (lower.includes("[t]") || lower.includes(" trace")) return "trace";
if (lower.includes("[i]") || lower.includes(" info")) return "info";
return "other";
}
/** detectSource reads the [file.go:123] or [SomeService] tag. */
export function detectSource(text: string): string {
const m =
/\[([^\]]+\.go|[A-Za-z]+Service|[A-Za-z]+\.[A-Za-z]+)(?::\d+)?\]/.exec(
text,
);
return m ? m[1] : "other";
}
export function useLogStream(intervalSeconds = 5) {
const lines = ref<LogLine[]>([]);
const sources = ref<string[]>([]);
const interval = ref(intervalSeconds);
let skip = 0;
let endOfLine = true;
let fetching = false;
let timer: ReturnType<typeof setInterval> | null = null;
function noteSource(source: string) {
if (source && !sources.value.includes(source)) sources.value.push(source);
}
/** append folds a chunk into the lines; the chunk may end mid-line. */
function append(chunk: string) {
if (!chunk) return;
const parts = chunk.split("\n");
const complete = chunk.endsWith("\n");
if (complete) parts.pop();
if (!endOfLine && lines.value.length) {
const last = lines.value[lines.value.length - 1];
last.text += parts.shift() ?? "";
last.level = detectLevel(last.text);
last.source = detectSource(last.text);
noteSource(last.source);
}
const base = lines.value.length;
for (const [i, text] of parts.entries()) {
const source = detectSource(text);
noteSource(source);
lines.value.push({
id: base + i,
text,
level: detectLevel(text),
source,
});
}
endOfLine = complete;
// the offset is in bytes, the text in characters
skip += new Blob([chunk]).size;
}
async function fetch(): Promise<void> {
if (fetching) return;
fetching = true;
try {
append(await getLogger({ skip }));
} catch {
// the next tick tries again
} finally {
fetching = false;
}
}
function start() {
stop();
timer = setInterval(fetch, interval.value * 1000);
}
function stop() {
if (timer) clearInterval(timer);
timer = null;
}
watch(interval, start);
onScopeDispose(stop);
return {
lines,
sources,
interval,
fetch,
start,
stop,
append,
count: computed(() => lines.value.length),
};
}
+89
View File
@@ -0,0 +1,89 @@
import { reactive, readonly } from "vue";
import i18n from "@/plugins/i18n";
import { refresh } from "@/session/refresh";
// Notices show one at a time, in order — the old GUI's defaultNoticeQueue:
// a failing action clicked five times shows one toast, not a stack. Text
// only; a backend message is never rendered as HTML.
export type NoticeKind = "info" | "success" | "warning" | "error";
export interface Notice {
id: number;
kind: NoticeKind;
text: string;
/** milliseconds; 0 keeps it until dismissed */
timeout: number;
action?: { label: string; onClick: () => void };
}
const state = reactive({
queue: [] as Notice[],
current: null as Notice | null,
});
let nextId = 1;
function advance() {
state.current = state.queue.shift() ?? null;
}
/** a notice saying the backend is still busy offers a refresh, so nobody has to guess */
function refreshActionFor(text: string): Notice["action"] | undefined {
const busy = i18n.global.t("backend.REQUEST_IN_PROGRESS");
if (!busy || !text.includes(busy)) return undefined;
return { label: i18n.global.t("operations.refresh"), onClick: refresh };
}
function push(
kind: NoticeKind,
text: string,
options: { timeout?: number; action?: Notice["action"] } = {},
): number {
const notice: Notice = {
id: nextId++,
kind,
text,
timeout: options.timeout ?? (kind === "error" ? 8000 : 4000),
action: options.action ?? refreshActionFor(text),
};
state.queue.push(notice);
if (!state.current) advance();
return notice.id;
}
/** dismiss ends the notice being shown (or removes a queued one) and shows the next. */
export function dismissNotice(id?: number): void {
if (id !== undefined && state.current?.id !== id) {
const i = state.queue.findIndex((n) => n.id === id);
if (i >= 0) state.queue.splice(i, 1);
return;
}
advance();
}
/** closeAllNotices drops the queue and the notice on screen; the session reset calls it. */
export function closeAllNotices(): void {
state.queue.length = 0;
state.current = null;
}
export const noticeState = readonly(state);
export function useNotify() {
return {
info: (text: string, o?: { timeout?: number; action?: Notice["action"] }) =>
push("info", text, o),
success: (
text: string,
o?: { timeout?: number; action?: Notice["action"] },
) => push("success", text, o),
warning: (
text: string,
o?: { timeout?: number; action?: Notice["action"] },
) => push("warning", text, o),
error: (
text: string,
o?: { timeout?: number; action?: Notice["action"] },
) => push("error", text, o),
dismiss: dismissNotice,
};
}
+73
View File
@@ -0,0 +1,73 @@
// Creating and deleting outbound groups, shared by the group menu and
// the proxies page: a prompt for the name, a confirmation before the
// delete, the store's list refreshed from the backend's answer.
import { useI18n } from "vue-i18n";
import { deleteOutbound, getOutbounds, postOutbound } from "@/api";
import { watchConnected } from "@/api/connect";
import { errorText } from "@/api/errors";
import { useAppStore } from "@/stores/app";
import { useConfirm } from "./useConfirm";
import { usePrompt } from "./useConfirm";
import { useNotify } from "./useNotify";
export function useOutboundGroups() {
const { t } = useI18n();
const store = useAppStore();
const notify = useNotify();
const prompt = usePrompt();
const confirm = useConfirm();
/** add asks for a name and creates the group; resolves true when one was created. */
async function add(): Promise<boolean> {
const outbound = await prompt({
message: t("outbound.addMessage"),
input: { maxlength: 10 },
});
if (outbound === null) return false;
const control = new AbortController();
try {
const res = await watchConnected(
postOutbound({ outbound }, { signal: control.signal }),
() => control.abort(),
);
if (res) {
notify.success(t("outbound.added"));
store.setOutbounds((res as { outbounds: unknown }).outbounds);
} else {
store.setOutbounds((await getOutbounds()).outbounds);
}
return true;
} catch (err) {
notify.warning(t("outbound.addFailed", { message: errorText(err) }));
return false;
}
}
/** remove confirms and deletes the group; resolves true when it was deleted. */
async function remove(outbound: string): Promise<boolean> {
const ok = await confirm({
message: t("outbound.deleteMessage", { outboundName: outbound }),
confirmText: t("operations.delete"),
destructive: true,
});
if (!ok) return false;
try {
const res = (await deleteOutbound({ outbound })) as {
outbounds: unknown;
};
notify.success(t("outbound.deleted"));
store.setOutbounds(res.outbounds);
return true;
} catch (err) {
notify.warning(
t("outbound.deleteFailed", {
group: outbound,
message: errorText(err),
}),
);
return false;
}
}
return { add, remove };
}
+69
View File
@@ -0,0 +1,69 @@
import { describe, expect, test } from "vitest";
import type { TrafficMessage } from "@/api/types";
import { formatBytes, formatRate } from "@/lib/format";
import { createTraffic } from "./useTraffic";
function message(n: number): TrafficMessage {
return {
type: "traffic",
body: { up: n, down: n * 2, upTotal: n * 100, downTotal: n * 200 },
};
}
describe("traffic history", () => {
test("keeps the newest 30 rates in order across repeated wraps, padded to the window", () => {
const traffic = createTraffic();
expect(traffic.upSeries.value).toEqual(new Array(30).fill(0));
for (let n = 1; n <= 125; n++) {
traffic.feed(message(n));
const expected = [
...new Array(Math.max(0, 30 - n)).fill(0),
...Array.from(
{ length: Math.min(n, 30) },
(_, i) => Math.max(1, n - 29) + i,
),
];
expect(traffic.upSeries.value).toEqual(expected);
expect(traffic.downSeries.value).toEqual(expected.map((v) => v * 2));
}
expect(traffic.up.value).toBe(125);
expect(traffic.down.value).toBe(250);
expect(traffic.upTotal.value).toBe(12500);
expect(traffic.downTotal.value).toBe(25000);
});
test("resets a wrapped history and starts a new session without stale samples", () => {
const traffic = createTraffic();
for (let n = 1; n <= 65; n++) traffic.feed(message(n));
traffic.reset();
expect(traffic.upSeries.value).toEqual(new Array(30).fill(0));
expect(traffic.downSeries.value).toEqual(new Array(30).fill(0));
expect([
traffic.up.value,
traffic.down.value,
traffic.upTotal.value,
traffic.downTotal.value,
]).toEqual([0, 0, 0, 0]);
traffic.feed(message(2));
expect(traffic.upSeries.value.slice(-2)).toEqual([0, 2]);
expect(traffic.downSeries.value.slice(-2)).toEqual([0, 4]);
expect(traffic.upTotal.value).toBe(200);
expect(traffic.downTotal.value).toBe(400);
});
});
describe("traffic formatting", () => {
test.each([
[0, "0.0 B"],
[1023, "1023.0 B"],
[1024, "1.0 KiB"],
[1536, "1.5 KiB"],
[1024 ** 2, "1.0 MiB"],
[1.25 * 1024 ** 2, "1.3 MiB"],
[1024 ** 3, "1.0 GiB"],
[1024 ** 4, "1024.0 GiB"],
])("formats %s bytes with binary units and one decimal", (n, expected) => {
expect(formatBytes(n)).toBe(expected);
expect(formatRate(n)).toBe(`${expected}/s`);
});
});
+53
View File
@@ -0,0 +1,53 @@
import { computed, ref, shallowRef, triggerRef } from "vue";
import type { TrafficMessage } from "@/api/types";
const capacity = 30;
/** createTraffic retains the last thirty one-second traffic frames, oldest sample first. */
export function createTraffic() {
const up = ref(0);
const down = ref(0);
const upTotal = ref(0);
const downTotal = ref(0);
const upSamples = shallowRef<number[]>([]);
const downSamples = shallowRef<number[]>([]);
let next = 0;
// oldest first, padded with zeros to the window so the chart is a flat
// line before the first frame and keeps one time scale as frames come in
const ordered = (samples: number[]) => [
...new Array<number>(capacity - samples.length).fill(0),
...samples.map((_, i) => samples[(next + i) % samples.length]),
];
const upSeries = computed(() => ordered(upSamples.value));
const downSeries = computed(() => ordered(downSamples.value));
function feed({ body }: TrafficMessage) {
up.value = body.up;
down.value = body.down;
upTotal.value = body.upTotal;
downTotal.value = body.downTotal;
upSamples.value[next] = body.up;
downSamples.value[next] = body.down;
next = (next + 1) % capacity;
triggerRef(upSamples);
triggerRef(downSamples);
}
function reset() {
next = 0;
up.value = down.value = upTotal.value = downTotal.value = 0;
upSamples.value = [];
downSamples.value = [];
}
return { feed, reset, up, down, upTotal, downTotal, upSeries, downSeries };
}
// One stream for the page: the shell feeds it from the message socket
// and resets it with the session; the dashboard reads it.
const shared = createTraffic();
export function useTraffic() {
return shared;
}
+88
View File
@@ -0,0 +1,88 @@
import { onScopeDispose } from "vue";
import { apiRoot } from "@/api/client";
import type { WsMessage } from "@/api/types";
// The backend's message socket, with the reconnect the old App.vue had:
// 1 s after the first drop, doubling to 30 s, back to 1 s once a connection
// succeeds. Messages are not replayed, so every open — the first one too —
// asks the caller to re-sync what it may have missed.
export interface MessageSocket {
start(): void;
stop(): void;
}
export function createMessageSocket(handlers: {
onMessage(msg: WsMessage): void;
onOpen(): void;
}): MessageSocket {
let ws: WebSocket | null = null;
let retries = 0;
let timer: ReturnType<typeof setTimeout> | null = null;
let stopped = false;
function url(): string {
let root = apiRoot();
if (!root.trim() || root.startsWith("/"))
root = location.protocol + "//" + location.host + root;
const u = new URL(root);
const proto = u.protocol === "https:" ? "wss" : "ws";
let base = u.pathname;
if (base.endsWith("/api")) base = base.slice(0, -4);
return `${proto}://${u.host}${base}/api/message?Authorization=${encodeURIComponent(localStorage.getItem("token") ?? "")}`;
}
function connect() {
if (stopped) return;
const socket = new WebSocket(url());
ws = socket;
socket.onopen = () => {
retries = 0;
handlers.onOpen();
};
socket.onmessage = (ev) => {
if (ev.data) handlers.onMessage(JSON.parse(ev.data));
};
socket.onclose = () => {
socket.onmessage = null;
if (ws === socket) ws = null;
if (stopped) return;
const delay = Math.min(1000 * 2 ** retries, 30_000);
retries++;
timer = setTimeout(() => {
timer = null;
if (ws === null) connect();
}, delay);
};
}
return {
start() {
stopped = false;
if (ws) ws.close();
connect();
},
stop() {
stopped = true;
if (timer) {
clearTimeout(timer);
timer = null;
}
if (ws) {
// detach first: onclose would otherwise schedule a reconnect
ws.onclose = null;
ws.close();
ws = null;
}
},
};
}
/** useMessageSocket binds a socket to the current effect scope: it stops when the scope does. */
export function useMessageSocket(handlers: {
onMessage(msg: WsMessage): void;
onOpen(): void;
}): MessageSocket {
const socket = createMessageSocket(handlers);
onScopeDispose(() => socket.stop());
return socket;
}
+61
View File
@@ -0,0 +1,61 @@
// Hand-written share links, one per protocol the editor supports, plus a
// VLESS xhttp link with the mux fields. The expected forms and links in
// serverCodec.json were recorded from modalServer.vue's original
// resolveURL/generateURL before the move to lib/serverCodec.ts.
const b64 = (s: string) => Buffer.from(s, "utf8").toString("base64");
export const links = {
vmess:
"vmess://" +
b64(
JSON.stringify({
v: "2",
ps: "vmess node",
add: "1.2.3.4",
port: "443",
id: "b831381d-6324-4d53-ad4f-8cda48b30811",
aid: "0",
scy: "auto",
net: "ws",
type: "none",
host: "h.example.com",
path: "/ws",
tls: "tls",
sni: "h.example.com",
alpn: "h2,http/1.1",
fp: "chrome",
}),
),
vless:
"vless://b831381d-6324-4d53-ad4f-8cda48b30811@1.2.3.4:443?encryption=none&flow=xtls-rprx-vision&security=reality&sni=example.com&fp=chrome&pbk=PUBLICKEY&sid=abcd1234&spx=%2F&type=tcp#vless%20node",
vlessXhttp:
"vless://b831381d-6324-4d53-ad4f-8cda48b30811@1.2.3.4:443?encryption=none&security=tls&sni=example.com&type=xhttp&path=%2Fx&xhttpMode=packet-up&xmuxMaxConcurFrom=8&xmuxMaxConcurTo=16&xhttpHeaders=%7B%22X-A%22%3A%22b%22%7D#vless%20xhttp",
ss:
"ss://" +
b64("chacha20-ietf-poly1305:passw0rd") +
"@1.2.3.4:8388?plugin=obfs-local%3Bobfs%3Dhttp%3Bobfs-host%3Dexample.com#ss%20node",
ssr:
"ssr://" +
b64(
"1.2.3.4:8388:auth_aes128_md5:aes-256-cfb:tls1.2_ticket_auth:" +
b64("passw0rd") +
"/?obfsparam=" +
b64("obfs.example.com") +
"&protoparam=" +
b64("1:abc") +
"&remarks=" +
b64("ssr node"),
),
trojan:
"trojan://passw0rd@1.2.3.4:443?security=tls&sni=example.com&type=ws&host=example.com&path=%2Ftr#trojan%20node",
juicity:
"juicity://b831381d-6324-4d53-ad4f-8cda48b30811:passw0rd@1.2.3.4:443?congestion_control=bbr&sni=example.com&allow_insecure=false#juicity%20node",
tuic: "tuic://b831381d-6324-4d53-ad4f-8cda48b30811:passw0rd@1.2.3.4:443?congestion_control=bbr&alpn=h3&sni=example.com&udp_relay_mode=native&allow_insecure=0#tuic%20node",
hysteria2:
"hysteria2://passw0rd@1.2.3.4:443?sni=example.com&insecure=0&obfs=salamander&obfs-password=obf#hy2%20node",
http: "http://user:passw0rd@1.2.3.4:8080#http%20node",
socks5: "socks5://user:passw0rd@1.2.3.4:1080#socks%20node",
anytls:
"anytls://passw0rd@1.2.3.4:443?sni=example.com&insecure=0#anytls%20node",
wireguard:
"wireguard://PRIVATEKEY%3D@1.2.3.4:51820?publicKey=PUBKEY%3D&address=10.0.0.2%2F32&preSharedKey=&allowedIPs=0.0.0.0%2F0&keepAlive=25&mtu=1420#wg%20node",
};
+314
View File
@@ -0,0 +1,314 @@
{
"vmess": {
"link": "vmess://eyJ2IjoiMiIsInBzIjoidm1lc3Mgbm9kZSIsImFkZCI6IjEuMi4zLjQiLCJwb3J0IjoiNDQzIiwiaWQiOiJiODMxMzgxZC02MzI0LTRkNTMtYWQ0Zi04Y2RhNDhiMzA4MTEiLCJhaWQiOiIwIiwic2N5IjoiYXV0byIsIm5ldCI6IndzIiwidHlwZSI6Im5vbmUiLCJob3N0IjoiaC5leGFtcGxlLmNvbSIsInBhdGgiOiIvd3MiLCJ0bHMiOiJ0bHMiLCJzbmkiOiJoLmV4YW1wbGUuY29tIiwiYWxwbiI6ImgyLGh0dHAvMS4xIiwiZnAiOiJjaHJvbWUifQ==",
"form": {
"v": "2",
"ps": "vmess node",
"add": "1.2.3.4",
"port": "443",
"id": "b831381d-6324-4d53-ad4f-8cda48b30811",
"aid": "0",
"scy": "auto",
"net": "ws",
"type": "none",
"host": "h.example.com",
"path": "/ws",
"tls": "tls",
"sni": "h.example.com",
"alpn": "h2,http/1.1",
"fp": "chrome",
"protocol": "vmess",
"xhttpHeaders": []
},
"back": "vmess://eyJ2IjoiMiIsInBzIjoidm1lc3Mgbm9kZSIsImFkZCI6IjEuMi4zLjQiLCJwb3J0IjoiNDQzIiwiaWQiOiJiODMxMzgxZC02MzI0LTRkNTMtYWQ0Zi04Y2RhNDhiMzA4MTEiLCJhaWQiOiIwIiwic2N5IjoiYXV0byIsIm5ldCI6IndzIiwidHlwZSI6IiIsImhvc3QiOiJoLmV4YW1wbGUuY29tIiwicGF0aCI6Ii93cyIsInRscyI6InRscyIsInNuaSI6ImguZXhhbXBsZS5jb20iLCJhbHBuIjoiaDIsaHR0cC8xLjEiLCJwcm90b2NvbCI6InZtZXNzIiwieGh0dHBIZWFkZXJzIjoiIiwiZmluZ2VycHJpbnQiOiJjaHJvbWUifQ=="
},
"vless": {
"link": "vless://b831381d-6324-4d53-ad4f-8cda48b30811@1.2.3.4:443?encryption=none&flow=xtls-rprx-vision&security=reality&sni=example.com&fp=chrome&pbk=PUBLICKEY&sid=abcd1234&spx=%2F&type=tcp#vless%20node",
"form": {
"ps": "vless node",
"add": "1.2.3.4",
"port": 443,
"id": "b831381d-6324-4d53-ad4f-8cda48b30811",
"flow": "xtls-rprx-vision",
"net": "tcp",
"type": "none",
"host": "",
"path": "",
"alpn": "",
"sni": "example.com",
"tls": "reality",
"quicSecurity": "none",
"fp": "chrome",
"pbk": "PUBLICKEY",
"sid": "abcd1234",
"spx": "/",
"pinnedPeerCertSha256": "",
"verifyPeerCertByName": "",
"xhttpMode": "auto",
"noGRPCHeader": false,
"noSSEHeader": false,
"uplinkHTTPMethod": "",
"scMaxEachPostBytesFrom": "",
"scMaxEachPostBytesTo": "",
"scMinPostsIntervalFrom": "",
"scMinPostsIntervalTo": "",
"scMaxBufferedPosts": "",
"scStreamUpServerFrom": "",
"scStreamUpServerTo": "",
"xPaddingBytesFrom": "",
"xPaddingBytesTo": "",
"xmuxMaxConcurFrom": "",
"xmuxMaxConcurTo": "",
"xmuxMaxConnFrom": "",
"xmuxMaxConnTo": "",
"xmuxCMaxReuseFrom": "",
"xmuxCMaxReuseTo": "",
"xmuxHMaxReqFrom": "",
"xmuxHMaxReqTo": "",
"xmuxHMaxReusableFrom": "",
"xmuxHMaxReusableTo": "",
"xmuxHKeepAlive": "",
"xhttpHeaders": [],
"maxEarlyData": "",
"earlyDataHeaderName": "",
"multiMode": false,
"idleTimeout": "",
"healthCheckTimeout": "",
"permitWithoutStream": false,
"initialWindowsSize": "",
"protocol": "vless"
},
"back": "vless://b831381d-6324-4d53-ad4f-8cda48b30811@1.2.3.4:443/?type=tcp&flow=xtls-rprx-vision&security=reality&fp=chrome&path=&host=&headerType=none&sni=example.com&pinnedPeerCertSha256=&verifyPeerCertByName=&pbk=PUBLICKEY&sid=abcd1234&spx=%2F#vless node"
},
"vlessXhttp": {
"link": "vless://b831381d-6324-4d53-ad4f-8cda48b30811@1.2.3.4:443?encryption=none&security=tls&sni=example.com&type=xhttp&path=%2Fx&xhttpMode=packet-up&xmuxMaxConcurFrom=8&xmuxMaxConcurTo=16&xhttpHeaders=%7B%22X-A%22%3A%22b%22%7D#vless%20xhttp",
"form": {
"ps": "vless xhttp",
"add": "1.2.3.4",
"port": 443,
"id": "b831381d-6324-4d53-ad4f-8cda48b30811",
"flow": "",
"net": "xhttp",
"type": "none",
"host": "",
"path": "/x",
"alpn": "",
"sni": "example.com",
"tls": "tls",
"quicSecurity": "none",
"fp": "",
"pbk": "",
"sid": "",
"spx": "",
"pinnedPeerCertSha256": "",
"verifyPeerCertByName": "",
"xhttpMode": "packet-up",
"noGRPCHeader": false,
"noSSEHeader": false,
"uplinkHTTPMethod": "",
"scMaxEachPostBytesFrom": "",
"scMaxEachPostBytesTo": "",
"scMinPostsIntervalFrom": "",
"scMinPostsIntervalTo": "",
"scMaxBufferedPosts": "",
"scStreamUpServerFrom": "",
"scStreamUpServerTo": "",
"xPaddingBytesFrom": "",
"xPaddingBytesTo": "",
"xmuxMaxConcurFrom": "8",
"xmuxMaxConcurTo": "16",
"xmuxMaxConnFrom": "",
"xmuxMaxConnTo": "",
"xmuxCMaxReuseFrom": "",
"xmuxCMaxReuseTo": "",
"xmuxHMaxReqFrom": "",
"xmuxHMaxReqTo": "",
"xmuxHMaxReusableFrom": "",
"xmuxHMaxReusableTo": "",
"xmuxHKeepAlive": "",
"xhttpHeaders": [
{
"key": "X-A",
"value": "b"
}
],
"maxEarlyData": "",
"earlyDataHeaderName": "",
"multiMode": false,
"idleTimeout": "",
"healthCheckTimeout": "",
"permitWithoutStream": false,
"initialWindowsSize": "",
"protocol": "vless"
},
"back": "vless://b831381d-6324-4d53-ad4f-8cda48b30811@1.2.3.4:443/?type=xhttp&flow=&security=tls&fp=&path=%2Fx&host=&headerType=none&sni=example.com&pinnedPeerCertSha256=&verifyPeerCertByName=&xhttpMode=packet-up&xmuxMaxConcurFrom=8&xmuxMaxConcurTo=16&xhttpHeaders=%7B%22X-A%22%3A%22b%22%7D#vless xhttp"
},
"ss": {
"link": "ss://Y2hhY2hhMjAtaWV0Zi1wb2x5MTMwNTpwYXNzdzByZA==@1.2.3.4:8388?plugin=obfs-local%3Bobfs%3Dhttp%3Bobfs-host%3Dexample.com#ss%20node",
"form": {
"method": "chacha20-ietf-poly1305",
"password": "passw0rd",
"server": "1.2.3.4",
"port": 8388,
"name": "ss node",
"plugin": "simple-obfs",
"obfs": "http",
"tls": "",
"mode": "websocket",
"host": "example.com",
"path": "",
"impl": "",
"protocol": "ss",
"backend": ""
},
"back": "ss://Y2hhY2hhMjAtaWV0Zi1wb2x5MTMwNTpwYXNzdzByZA@1.2.3.4:8388/?plugin=simple-obfs%3Bobfs%3Dhttp%3Bobfs-host%3Dexample.com%3Bobfs-uri%3D#ss%20node"
},
"ssr": {
"link": "ssr://MS4yLjMuNDo4Mzg4OmF1dGhfYWVzMTI4X21kNTphZXMtMjU2LWNmYjp0bHMxLjJfdGlja2V0X2F1dGg6Y0dGemMzY3djbVE9Lz9vYmZzcGFyYW09YjJKbWN5NWxlR0Z0Y0d4bExtTnZiUT09JnByb3RvcGFyYW09TVRwaFltTT0mcmVtYXJrcz1jM055SUc1dlpHVT0=",
"form": {
"method": "aes-256-cfb",
"password": "passw0rd",
"server": "1.2.3.4",
"port": "8388",
"name": "ssr node",
"proto": "auth_aes128_md5",
"protoParam": "1:abc",
"obfs": "tls1.2_ticket_auth",
"obfsParam": "obfs.example.com",
"protocol": "ssr"
},
"back": "ssr://MS4yLjMuNDo4Mzg4OmF1dGhfYWVzMTI4X21kNTphZXMtMjU2LWNmYjp0bHMxLjJfdGlja2V0X2F1dGg6Y0dGemMzY3djbVEvP3JlbWFya3M9YzNOeUlHNXZaR1UmcHJvdG9wYXJhbT1NVHBoWW1NJm9iZnNwYXJhbT1iMkptY3k1bGVHRnRjR3hsTG1OdmJR"
},
"trojan": {
"link": "trojan://passw0rd@1.2.3.4:443?security=tls&sni=example.com&type=ws&host=example.com&path=%2Ftr#trojan%20node",
"form": {
"password": "passw0rd",
"server": "1.2.3.4",
"port": 443,
"name": "trojan node",
"peer": "example.com",
"pinnedPeerCertSha256": "",
"verifyPeerCertByName": "",
"method": "origin",
"net": "ws",
"host": "example.com",
"obfs": "none",
"ssCipher": "2022-blake3-aes-128-gcm",
"path": "/tr",
"protocol": "trojan",
"backend": ""
},
"back": "trojan://passw0rd@1.2.3.4:443/?type=ws&pinnedPeerCertSha256=&verifyPeerCertByName=&sni=example.com&host=example.com&path=%2Ftr#trojan node"
},
"juicity": {
"link": "juicity://b831381d-6324-4d53-ad4f-8cda48b30811:passw0rd@1.2.3.4:443?congestion_control=bbr&sni=example.com&allow_insecure=false#juicity%20node",
"form": {
"name": "juicity node",
"uuid": "b831381d-6324-4d53-ad4f-8cda48b30811",
"password": "passw0rd",
"server": "1.2.3.4",
"port": 443,
"sni": "example.com",
"pinnedCertchainSha256": "",
"cc": "bbr",
"allowInsecure": false,
"protocol": "juicity"
},
"back": "juicity://b831381d-6324-4d53-ad4f-8cda48b30811:passw0rd@1.2.3.4:443/?congestion_control=bbr&sni=example.com#juicity node"
},
"tuic": {
"link": "tuic://b831381d-6324-4d53-ad4f-8cda48b30811:passw0rd@1.2.3.4:443?congestion_control=bbr&alpn=h3&sni=example.com&udp_relay_mode=native&allow_insecure=0#tuic%20node",
"form": {
"name": "tuic node",
"uuid": "b831381d-6324-4d53-ad4f-8cda48b30811",
"password": "passw0rd",
"server": "1.2.3.4",
"port": 443,
"sni": "example.com",
"pinnedPeerCertSha256": "",
"verifyPeerCertByName": "",
"disableSni": false,
"alpn": "h3",
"cc": "bbr",
"udpRelayMode": "native",
"allowInsecure": false,
"protocol": "tuic"
},
"back": "tuic://b831381d-6324-4d53-ad4f-8cda48b30811:passw0rd@1.2.3.4:443/?pinnedPeerCertSha256=&verifyPeerCertByName=&congestion_control=bbr&disable_sni=false&alpn=h3&udp_relay_mode=native&sni=example.com#tuic node"
},
"hysteria2": {
"link": "hysteria2://passw0rd@1.2.3.4:443?sni=example.com&insecure=0&obfs=salamander&obfs-password=obf#hy2%20node",
"form": {
"name": "hy2 node",
"password": "passw0rd",
"server": "1.2.3.4",
"port": 443,
"sni": "example.com",
"pinnedPeerCertSha256": "",
"verifyPeerCertByName": "",
"obfs": "salamander",
"obfsPassword": "obf",
"protocol": "hysteria2"
},
"back": "hysteria2://passw0rd@1.2.3.4:443/?pinned_peer_cert_sha256=&verify_peer_cert_by_name=&sni=example.com&obfs=salamander&obfs-password=obf#hy2 node"
},
"http": {
"link": "http://user:passw0rd@1.2.3.4:8080#http%20node",
"form": {
"username": "user",
"password": "passw0rd",
"host": "1.2.3.4",
"port": 8080,
"protocol": "http",
"name": "http node"
},
"back": "http-proxy://user:passw0rd@1.2.3.4:8080/#http node"
},
"socks5": {
"link": "socks5://user:passw0rd@1.2.3.4:1080#socks%20node",
"form": {
"username": "user",
"password": "passw0rd",
"host": "1.2.3.4",
"port": 1080,
"protocol": "socks5",
"name": "socks node"
},
"back": "socks5://user:passw0rd@1.2.3.4:1080/#socks node"
},
"anytls": {
"link": "anytls://passw0rd@1.2.3.4:443?sni=example.com&insecure=0#anytls%20node",
"form": {
"name": "anytls node",
"host": "1.2.3.4",
"port": 443,
"auth": "passw0rd",
"sni": "example.com",
"pinnedPeerCertSha256": "",
"verifyPeerCertByName": "",
"allowInsecure": false,
"minIdleSession": "",
"protocol": "anytls"
},
"back": "anytls://passw0rd@1.2.3.4:443/?sni=example.com#anytls node"
},
"wireguard": {
"link": "wireguard://PRIVATEKEY%3D@1.2.3.4:51820?publicKey=PUBKEY%3D&address=10.0.0.2%2F32&preSharedKey=&allowedIPs=0.0.0.0%2F0&keepAlive=25&mtu=1420#wg%20node",
"form": {
"protocol": "wireguard",
"name": "wg node",
"address": "1.2.3.4",
"port": 51820,
"privateKey": "PRIVATEKEY=",
"publicKey": "PUBKEY=",
"localAddress": "10.0.0.2/32",
"dns": "",
"mtu": "1420",
"allowedIPs": "0.0.0.0/0",
"persistentKeepalive": "25",
"preSharedKey": "",
"endpoint": ""
},
"back": "wireguard://PRIVATEKEY%3D@1.2.3.4:51820/?publicKey=PUBKEY%3D&address=10.0.0.2%2F32&mtu=1420&allowedIPs=0.0.0.0%2F0&keepAlive=25#wg node"
}
}
+21
View File
@@ -0,0 +1,21 @@
// Copying text: the Clipboard API where the page is a secure context, the
// selection-and-execCommand path elsewhere (v2rayA is usually served over
// plain http on a LAN address, where navigator.clipboard is undefined).
export async function copyText(text: string): Promise<void> {
if (navigator.clipboard && window.isSecureContext) {
await navigator.clipboard.writeText(text);
return;
}
const area = document.createElement("textarea");
area.value = text;
area.setAttribute("readonly", "");
area.style.position = "fixed";
area.style.opacity = "0";
document.body.appendChild(area);
area.select();
try {
if (!document.execCommand("copy")) throw new Error("copy command failed");
} finally {
area.remove();
}
}
+16
View File
@@ -0,0 +1,16 @@
const units = ["B", "KiB", "MiB", "GiB"] as const;
/** Formats a nonnegative byte count with one decimal, capped at GiB. */
export function formatBytes(n: number): string {
let unit = 0;
while (n >= 1024 && unit < units.length - 1) {
n /= 1024;
unit++;
}
return `${n.toFixed(1)} ${units[unit]}`;
}
/** Formats bytes per second without locale-specific separators. */
export function formatRate(n: number): string {
return `${formatBytes(n)}/s`;
}
+38
View File
@@ -0,0 +1,38 @@
import { describe, expect, test } from "vitest";
import { parseQuota } from "./quota";
describe("parseQuota", () => {
test("reads the three shapes the backend writes", () => {
expect(
parseQuota("Used 54.30 GiB / 100.00 GiB · Expires 2026-10-04"),
).toEqual({
used: "54.30 GiB",
total: "100.00 GiB",
expires: "2026-10-04",
percent: 54.3,
});
expect(parseQuota("Used 1.50 GiB")).toEqual({
used: "1.50 GiB",
total: "",
expires: "",
});
expect(parseQuota("Total 20.00 GiB · Expires 2027-01-01")).toEqual({
used: "",
total: "20.00 GiB",
expires: "2027-01-01",
});
expect(parseQuota("Expires 2027-01-01")).toEqual({
used: "",
total: "",
expires: "2027-01-01",
});
expect(parseQuota("")).toBeNull();
expect(parseQuota("anything else")).toBeNull();
});
test("normalises units and caps the bar", () => {
expect(parseQuota("Used 512.00 MiB / 1.00 GiB")?.percent).toBe(50);
expect(parseQuota("Used 3.00 GiB / 1.00 GiB")?.percent).toBe(100);
expect(parseQuota("Used 1.00 GiB / 0.00 GiB")?.percent).toBeUndefined();
});
});
+51
View File
@@ -0,0 +1,51 @@
// The subscription's quota, read back from the text the backend writes
// (server/service/subscription.go, SubscriptionUserInfo.String): one of
// "Used X GiB / Y GiB", "Used X GiB", "Total Y GiB", each optionally
// followed by " · Expires YYYY-MM-DD". The GUI shows a bar only when both
// sides are known.
export interface Quota {
/** the used amount as the backend wrote it, "" when unknown */
used: string;
/** the total as the backend wrote it, "" when unknown */
total: string;
expires: string;
/** 0–100 when both sides are known, else undefined */
percent?: number;
}
const units: Record<string, number> = {
B: 1,
KiB: 1024,
MiB: 1024 ** 2,
GiB: 1024 ** 3,
TiB: 1024 ** 4,
};
const bytes = (amount: string) => {
const m = /^([\d.]+) (\w+)$/.exec(amount);
return m ? Number(m[1]) * (units[m[2]] ?? 1) : NaN;
};
/** parseQuota reads the backend's text; null when it says nothing about the quota. */
export function parseQuota(info: string | undefined): Quota | null {
if (!info) return null;
const expires = /Expires (\S+)/.exec(info)?.[1] ?? "";
const both = /Used ([\d.]+ \w+) \/ ([\d.]+ \w+)/.exec(info);
const usedOnly = /Used ([\d.]+ \w+)/.exec(info);
const totalOnly = /Total ([\d.]+ \w+)/.exec(info);
if (both) {
const total = bytes(both[2]);
return {
used: both[1],
total: both[2],
expires,
percent:
total > 0
? Math.min(100, Number(((bytes(both[1]) / total) * 100).toFixed(1)))
: undefined,
};
}
if (usedOnly) return { used: usedOnly[1], total: "", expires };
if (totalOnly) return { used: "", total: totalOnly[1], expires };
return expires ? { used: "", total: "", expires } : null;
}
+30
View File
@@ -0,0 +1,30 @@
// @vitest-environment happy-dom
import { describe, expect, test } from "vitest";
import { generateShareLink, parseShareLink } from "./serverCodec";
import { links } from "./__fixtures__/links";
import expected from "./__fixtures__/serverCodec.json";
// The expected values are what the editor produced before the codec
// moved out of modalServer.vue: this suite pins the move, not a spec of
// the share-link formats (the http branch, for one, generates
// http-proxy:// and parses http://, and that stays as it is).
describe("serverCodec keeps the editor's behaviour", () => {
for (const [name, link] of Object.entries(links)) {
test(`${name}: link → form`, () => {
expect(parseShareLink(link)).toEqual(
expected[name as keyof typeof expected].form,
);
});
test(`${name}: form → link`, () => {
const form = parseShareLink(link);
expect(form && generateShareLink(form)).toEqual(
expected[name as keyof typeof expected].back,
);
});
}
test("an unknown scheme is null both ways", () => {
expect(parseShareLink("gopher://x")).toBeNull();
expect(generateShareLink({ protocol: "gopher" })).toBeNull();
});
});
+819
View File
@@ -0,0 +1,819 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
// Share-link codec: a share link in, the editor's form object out, and
// back. Moved from modalServer.vue without changes in logic; the form
// objects keep the shapes the protocol forms bind to. The editor is the
// only consumer: the import dialog posts links as typed, and the share
// dialog shows the backend's link.
import { Base64 } from "js-base64";
import { decodeSafe, generateURL as buildURL, parseURL } from "@/lib/url";
export type ShareForm = Record<string, any>;
/** parseShareLink turns a share link into the editor's form object, or null for an unknown scheme. */
export function parseShareLink(url: string): ShareForm | null {
if (url.toLowerCase().startsWith("vmess://")) {
const obj = JSON.parse(
Base64.decode(url.substring(url.indexOf("://") + 3)),
);
// the backend stores ps as typed; only decode when it is valid
// percent-encoding, a literal "%" in a name must survive
obj.ps = decodeSafe(obj.ps);
// the backend keys the uTLS fingerprint "fingerprint" in vmess JSON
obj.fp = obj.fp || obj.fingerprint || "";
obj.tls = obj.tls || "none";
obj.type = obj.type || "none";
obj.scy = obj.scy || "auto";
obj.protocol = obj.protocol || "vmess";
// xhttpHeaders arrives as a JSON-encoded string; convert it to the
// array model used by the GUI so the editor round-trips correctly.
if (typeof obj.xhttpHeaders === "string") {
try {
const hdrsObj = JSON.parse(obj.xhttpHeaders);
obj.xhttpHeaders = Object.entries(hdrsObj || {}).map(
([key, value]) => ({ key, value }),
);
} catch {
obj.xhttpHeaders = [];
}
}
if (!Array.isArray(obj.xhttpHeaders)) obj.xhttpHeaders = [];
// multiMode/permitWithoutStream arrive as strings; restore the booleans
// used by the GUI model.
if (typeof obj.multiMode === "string")
obj.multiMode = obj.multiMode === "true" || obj.multiMode === "1";
if (typeof obj.permitWithoutStream === "string")
obj.permitWithoutStream =
obj.permitWithoutStream === "true" || obj.permitWithoutStream === "1";
return obj;
} else if (url.toLowerCase().startsWith("vless://")) {
const u = parseURL(url);
const o: ShareForm = {
ps: decodeSafe(u.hash),
add: u.host,
port: u.port,
id: decodeSafe(u.username),
flow: u.params.flow || "",
net: u.params.type || "tcp",
type: u.params.headerType || "none",
host: u.params.host || "",
path: u.params.path || u.params.serviceName || "",
alpn: u.params.alpn || "",
sni: u.params.sni || "",
tls: u.params.security === "xtls" ? "tls" : u.params.security || "none",
quicSecurity: u.params.quicSecurity || "none",
fp: u.params.fp || "",
pbk: u.params.pbk || "",
sid: u.params.sid || "",
spx: u.params.spx || "",
pinnedPeerCertSha256: u.params.pinnedPeerCertSha256 || "",
verifyPeerCertByName: u.params.verifyPeerCertByName || "",
key: u.params.key,
xhttpMode: u.params.xhttpMode || "auto",
noGRPCHeader: u.params.noGRPCHeader === "true",
noSSEHeader: u.params.noSSEHeader === "true",
uplinkHTTPMethod: u.params.uplinkHTTPMethod || "",
scMaxEachPostBytesFrom: u.params.scMaxEachPostBytesFrom || "",
scMaxEachPostBytesTo: u.params.scMaxEachPostBytesTo || "",
scMinPostsIntervalFrom: u.params.scMinPostsIntervalFrom || "",
scMinPostsIntervalTo: u.params.scMinPostsIntervalTo || "",
scMaxBufferedPosts: u.params.scMaxBufferedPosts || "",
scStreamUpServerFrom: u.params.scStreamUpServerFrom || "",
scStreamUpServerTo: u.params.scStreamUpServerTo || "",
xPaddingBytesFrom: u.params.xPaddingBytesFrom || "",
xPaddingBytesTo: u.params.xPaddingBytesTo || "",
xmuxMaxConcurFrom: u.params.xmuxMaxConcurFrom || "",
xmuxMaxConcurTo: u.params.xmuxMaxConcurTo || "",
xmuxMaxConnFrom: u.params.xmuxMaxConnFrom || "",
xmuxMaxConnTo: u.params.xmuxMaxConnTo || "",
xmuxCMaxReuseFrom: u.params.xmuxCMaxReuseFrom || "",
xmuxCMaxReuseTo: u.params.xmuxCMaxReuseTo || "",
xmuxHMaxReqFrom: u.params.xmuxHMaxReqFrom || "",
xmuxHMaxReqTo: u.params.xmuxHMaxReqTo || "",
xmuxHMaxReusableFrom: u.params.xmuxHMaxReusableFrom || "",
xmuxHMaxReusableTo: u.params.xmuxHMaxReusableTo || "",
xmuxHKeepAlive: u.params.xmuxHKeepAlive || "",
xhttpHeaders: (() => {
try {
const raw = u.params.xhttpHeaders;
if (!raw) return [];
const obj = JSON.parse(raw);
return Object.entries(obj).map(([key, value]) => ({ key, value }));
} catch {
return [];
}
})(),
maxEarlyData: u.params.maxEarlyData || "",
earlyDataHeaderName: u.params.earlyDataHeaderName || "",
multiMode: u.params.multiMode === "true" || u.params.multiMode === "1",
idleTimeout: u.params.idleTimeout || "",
healthCheckTimeout: u.params.healthCheckTimeout || "",
permitWithoutStream:
u.params.permitWithoutStream === "true" ||
u.params.permitWithoutStream === "1",
initialWindowsSize: u.params.initialWindowsSize || "",
protocol: "vless",
};
if (o.alpn !== "") {
o.alpn = decodeSafe(o.alpn);
}
if (o.net === "mkcp" || o.net === "kcp") {
o.path = u.params.seed;
}
return o;
} else if (url.toLowerCase().startsWith("ss://")) {
const u = parseURL(url);
let userinfo = u.username;
// The backend percent-escapes the base64 userinfo ("=" becomes %3D),
// and js-base64 decodes those escapes as data, which corrupted the
// password of every shadowsocks node opened for editing.
try {
userinfo = decodeSafe(userinfo);
} catch {
// a literal "%" in the userinfo: use it as it came
}
// Handle SIP002 format: ss://BASE64URL@host:port vs legacy ss://BASE64
let method = "",
password = "";
try {
const decoded = Base64.decode(userinfo);
const idx = decoded.indexOf(":");
if (idx > -1) {
method = decoded.substring(0, idx);
password = decoded.substring(idx + 1);
}
} catch {
method = userinfo;
}
// parseURL already decoded the query values; decoding again turns
// %2F into a path separator and throws on a literal percent sign
const ssPlugin = u.params.plugin || "";
const opts = ssPlugin.split(";");
const o: ShareForm = {
method: method,
password: password,
server: u.host,
port: u.port,
name: decodeSafe(u.hash || ""),
plugin: opts[0] || "",
obfs: "http",
tls: "",
mode: "websocket",
host: "",
path: "",
impl: "",
protocol: "ss",
backend: u.params["v2raya-backend"] || "",
};
switch (o.plugin) {
case "obfs-local":
case "simpleobfs":
o.plugin = "simple-obfs";
break;
}
// "obfs-local;obfs=tls;obfs-host=example.com" or
// "v2ray-plugin;tls;mode=websocket;host=example.com;path=/ws"
for (const opt of opts.slice(1)) {
const [k, v = ""] = opt.split("=");
switch (k) {
case "obfs":
o.obfs = v;
break;
case "host":
case "obfs-host":
o.host = v;
break;
case "path":
case "obfs-path":
case "obfs-uri":
o.path = v;
break;
case "mode":
o.mode = v;
break;
case "tls":
o.tls = "tls";
break;
case "impl":
o.impl = v;
break;
}
}
return o;
} else if (url.toLowerCase().startsWith("ssr://")) {
url = Base64.decode(url.substr(6));
const arr = url.split("/?");
const query = (arr[1] ?? "").split("&");
const m: ShareForm = {};
for (const param of query) {
const [key, val] = param.split("=", 2);
m[key] = Base64.decode(val);
}
let pre = arr[0].split(":");
if (pre.length > 6) {
//如果长度多于6,说明host中包含字符:,重新合并前几个分组到host去
pre[pre.length - 6] = pre.slice(0, pre.length - 5).join(":");
pre = pre.slice(pre.length - 6);
}
pre[5] = Base64.decode(pre[5]);
return {
method: pre[3],
password: pre[5],
server: pre[0],
port: pre[1],
name: m["remarks"],
proto: pre[2],
protoParam: m["protoparam"],
obfs: pre[4],
obfsParam: m["obfsparam"],
protocol: "ssr",
};
} else if (
url.toLowerCase().startsWith("trojan://") ||
url.toLowerCase().startsWith("trojan-go://")
) {
const u = parseURL(url);
const o: ShareForm = {
password: decodeSafe(u.username),
server: u.host,
port: u.port,
name: decodeSafe(u.hash),
peer: u.params.peer || u.params.sni || "",
pinnedPeerCertSha256: u.params.pinnedPeerCertSha256 || "",
verifyPeerCertByName: u.params.verifyPeerCertByName || "",
method: "origin",
net: u.params.type || "tcp",
host: u.params.host || "",
obfs: "none",
ssCipher: "2022-blake3-aes-128-gcm",
path: u.params.path || u.params.serviceName || "",
protocol: "trojan",
backend: u.params["v2raya-backend"] || "",
};
if (url.toLowerCase().startsWith("trojan-go://")) {
if (u.params.encryption?.startsWith("ss;")) {
o.method = "shadowsocks";
const fields = u.params.encryption.split(";");
o.ssCipher = fields[1];
o.ssPassword = fields[2];
}
if (u.params.type === "ws") {
o.obfs = "websocket";
o.host = u.params.host || "";
o.path = u.params.path || "/";
}
}
return o;
} else if (url.toLowerCase().startsWith("juicity://")) {
const u = parseURL(url);
return {
name: decodeSafe(u.hash),
uuid: decodeSafe(u.username),
password: decodeSafe(u.password),
server: u.host,
port: u.port,
sni: u.params.sni || "",
pinnedCertchainSha256: u.params.pinned_certchain_sha256 || "",
cc: u.params.congestion_control || "bbr",
allowInsecure:
u.params.allow_insecure === "true" || u.params.allowInsecure === "true",
protocol: "juicity",
};
} else if (url.toLowerCase().startsWith("tuic://")) {
const u = parseURL(url);
return {
name: decodeSafe(u.hash),
uuid: decodeSafe(u.username),
password: decodeSafe(u.password),
server: u.host,
port: u.port,
sni: u.params.sni || "",
pinnedPeerCertSha256:
u.params.pinnedPeerCertSha256 || u.params.pinned_peer_cert_sha256 || "",
verifyPeerCertByName:
u.params.verifyPeerCertByName ||
u.params.verify_peer_cert_by_name ||
"",
disableSni:
u.params.disable_sni === "true" || u.params.disable_sni === "1",
alpn: u.params.alpn,
cc: u.params.congestion_control || "bbr",
udpRelayMode: u.params.udp_relay_mode || "native",
allowInsecure:
u.params.allow_insecure === "true" || u.params.allow_insecure === "1",
protocol: "tuic",
};
} else if (
url.toLowerCase().startsWith("hysteria2://") ||
url.toLowerCase().startsWith("hy2://")
) {
const u = parseURL(url);
let password = decodeSafe(u.username);
const userInfoEnd = u.source.indexOf("@");
if (
userInfoEnd !== -1 &&
u.source.slice(u.source.indexOf("://") + 3, userInfoEnd).includes(":")
) {
password += `:${decodeSafe(u.password)}`;
}
return {
name: decodeSafe(u.hash),
password: password,
server: u.host,
port: u.port,
sni: u.params.sni || "",
pinnedPeerCertSha256:
u.params.pinSHA256 ||
u.params.pinSha256 ||
u.params.pin_sha256 ||
u.params.pinned_peer_cert_sha256 ||
u.params.pinnedPeerCertSha256 ||
"",
verifyPeerCertByName:
u.params.verifyPeerCertByName ||
u.params.verify_peer_cert_by_name ||
"",
obfs: u.params.obfs || "none",
obfsPassword: u.params["obfs-password"] || "",
protocol: "hysteria2",
};
} else if (
url.toLowerCase().startsWith("http://") ||
url.toLowerCase().startsWith("https://")
) {
const u = parseURL(url);
return {
username: decodeSafe(u.username),
password: decodeSafe(u.password),
host: u.host,
port: u.port,
protocol: u.protocol,
name: decodeSafe(u.hash),
};
} else if (url.toLowerCase().startsWith("socks5://")) {
const u = parseURL(url);
return {
username: decodeSafe(u.username),
password: decodeSafe(u.password),
host: u.host,
port: u.port,
protocol: u.protocol,
name: decodeSafe(u.hash),
};
} else if (url.toLowerCase().startsWith("anytls://")) {
const u = parseURL(url);
const auth = u.username ? decodeSafe(u.username) : "";
const sni = u.params.peer || u.params.sni || "";
return {
name: decodeSafe(u.hash),
host: u.host,
port: u.port,
auth: auth,
sni: sni,
pinnedPeerCertSha256:
u.params.pinnedPeerCertSha256 || u.params.pinned_peer_cert_sha256 || "",
verifyPeerCertByName:
u.params.verifyPeerCertByName ||
u.params.verify_peer_cert_by_name ||
"",
allowInsecure:
u.params.allow_insecure === "true" || u.params.allow_insecure === "1",
minIdleSession: u.params.minIdleSession || "",
protocol: "anytls",
};
} else if (url.toLowerCase().startsWith("wireguard://")) {
// layout of kernel/serverObj/wireguard.go:
// wireguard://PRIVATEKEY@server:port?publicKey=&address=&preSharedKey=&allowedIPs=&keepAlive=&mtu=#name
const u = parseURL(url);
return {
protocol: "wireguard",
name: decodeSafe(u.hash),
address: u.host,
port: u.port,
privateKey: decodeSafe(u.username || ""),
publicKey: u.params.publicKey || "",
localAddress: u.params.address || "",
dns: u.params.dns || "",
mtu: u.params.mtu || "",
allowedIPs: u.params.allowedIPs || "",
persistentKeepalive: u.params.keepAlive || "",
preSharedKey: u.params.preSharedKey || "",
endpoint: u.params.endpoint || "",
};
}
return null;
}
/** generateShareLink turns the editor's form object back into a share link, or null when the protocol is unknown. */
export function generateShareLink(srcObj: ShareForm): string | null {
let query: ShareForm = {};
let obj: ShareForm = {};
let tmp;
switch (srcObj.protocol) {
case "vless":
// todo: support reality and xhttp
// https://github.com/XTLS/Xray-core/discussions/716
query = {
type: srcObj.net,
flow: srcObj.flow || "",
security: srcObj.tls,
fp: srcObj.fp || "",
path: srcObj.path,
host: srcObj.host,
headerType: srcObj.type,
sni: srcObj.sni,
pinnedPeerCertSha256: srcObj.pinnedPeerCertSha256,
verifyPeerCertByName: srcObj.verifyPeerCertByName,
};
if (srcObj.alpn !== "") {
query.alpn = srcObj.alpn;
}
if (srcObj.net === "ws") {
if (srcObj.maxEarlyData) {
query.maxEarlyData = srcObj.maxEarlyData;
}
if (srcObj.earlyDataHeaderName) {
query.earlyDataHeaderName = srcObj.earlyDataHeaderName;
}
}
if (srcObj.net === "grpc") {
query.serviceName = srcObj.path;
if (srcObj.multiMode) {
query.multiMode = srcObj.multiMode;
}
if (srcObj.idleTimeout) {
query.idleTimeout = srcObj.idleTimeout;
}
if (srcObj.healthCheckTimeout) {
query.healthCheckTimeout = srcObj.healthCheckTimeout;
}
if (srcObj.permitWithoutStream) {
query.permitWithoutStream = srcObj.permitWithoutStream;
}
if (srcObj.initialWindowsSize) {
query.initialWindowsSize = srcObj.initialWindowsSize;
}
}
if (srcObj.net === "mkcp" || srcObj.net === "kcp") {
query.seed = srcObj.path;
}
if (srcObj.net === "quic") {
query.key = srcObj.key;
query.quicSecurity = srcObj.quicSecurity;
}
if (srcObj.net === "xhttp") {
query.xhttpMode = srcObj.xhttpMode;
if (srcObj.noGRPCHeader) query.noGRPCHeader = "true";
if (srcObj.noSSEHeader) query.noSSEHeader = "true";
if (srcObj.uplinkHTTPMethod)
query.uplinkHTTPMethod = srcObj.uplinkHTTPMethod;
if (srcObj.scMaxEachPostBytesFrom)
query.scMaxEachPostBytesFrom = srcObj.scMaxEachPostBytesFrom;
if (srcObj.scMaxEachPostBytesTo)
query.scMaxEachPostBytesTo = srcObj.scMaxEachPostBytesTo;
if (srcObj.scMinPostsIntervalFrom)
query.scMinPostsIntervalFrom = srcObj.scMinPostsIntervalFrom;
if (srcObj.scMinPostsIntervalTo)
query.scMinPostsIntervalTo = srcObj.scMinPostsIntervalTo;
if (srcObj.scMaxBufferedPosts)
query.scMaxBufferedPosts = srcObj.scMaxBufferedPosts;
if (srcObj.scStreamUpServerFrom)
query.scStreamUpServerFrom = srcObj.scStreamUpServerFrom;
if (srcObj.scStreamUpServerTo)
query.scStreamUpServerTo = srcObj.scStreamUpServerTo;
if (srcObj.xPaddingBytesFrom)
query.xPaddingBytesFrom = srcObj.xPaddingBytesFrom;
if (srcObj.xPaddingBytesTo)
query.xPaddingBytesTo = srcObj.xPaddingBytesTo;
if (srcObj.xmuxMaxConcurFrom)
query.xmuxMaxConcurFrom = srcObj.xmuxMaxConcurFrom;
if (srcObj.xmuxMaxConcurTo)
query.xmuxMaxConcurTo = srcObj.xmuxMaxConcurTo;
if (srcObj.xmuxMaxConnFrom)
query.xmuxMaxConnFrom = srcObj.xmuxMaxConnFrom;
if (srcObj.xmuxMaxConnTo) query.xmuxMaxConnTo = srcObj.xmuxMaxConnTo;
if (srcObj.xmuxCMaxReuseFrom)
query.xmuxCMaxReuseFrom = srcObj.xmuxCMaxReuseFrom;
if (srcObj.xmuxCMaxReuseTo)
query.xmuxCMaxReuseTo = srcObj.xmuxCMaxReuseTo;
if (srcObj.xmuxHMaxReqFrom)
query.xmuxHMaxReqFrom = srcObj.xmuxHMaxReqFrom;
if (srcObj.xmuxHMaxReqTo) query.xmuxHMaxReqTo = srcObj.xmuxHMaxReqTo;
if (srcObj.xmuxHMaxReusableFrom)
query.xmuxHMaxReusableFrom = srcObj.xmuxHMaxReusableFrom;
if (srcObj.xmuxHMaxReusableTo)
query.xmuxHMaxReusableTo = srcObj.xmuxHMaxReusableTo;
if (srcObj.xmuxHKeepAlive) query.xmuxHKeepAlive = srcObj.xmuxHKeepAlive;
if (srcObj.xhttpHeaders && srcObj.xhttpHeaders.length > 0) {
const hdrsObj: ShareForm = {};
srcObj.xhttpHeaders.forEach((h: ShareForm) => {
if (h.key) hdrsObj[h.key] = h.value;
});
if (Object.keys(hdrsObj).length > 0)
query.xhttpHeaders = JSON.stringify(hdrsObj);
}
}
if (query.security == "reality") {
query.pbk = srcObj.pbk;
query.sid = srcObj.sid;
query.spx = srcObj.spx;
}
return buildURL({
protocol: "vless",
username: srcObj.id,
host: srcObj.add,
port: srcObj.port,
hash: srcObj.ps,
params: query,
});
case "vmess":
//https://github.com/2dust/v2rayN/wiki/%E5%88%86%E4%BA%AB%E9%93%BE%E6%8E%A5%E6%A0%BC%E5%BC%8F%E8%AF%B4%E6%98%8E(ver-2)
obj = Object.assign({}, srcObj);
// xhttpHeaders is stored on the backend as a JSON-encoded string; the
// GUI model uses an array of {key,value}. Serialize as a string so the
// vmess payload can round-trip through the backend parser.
if (Array.isArray(obj.xhttpHeaders)) {
const hdrsObj: ShareForm = {};
obj.xhttpHeaders.forEach((h: ShareForm) => {
if (h && h.key) hdrsObj[h.key] = h.value;
});
obj.xhttpHeaders =
Object.keys(hdrsObj).length > 0 ? JSON.stringify(hdrsObj) : "";
}
// multiMode/permitWithoutStream are stored as strings on the backend
// but modeled as booleans in the GUI; serialize them as strings.
if (typeof obj.multiMode === "boolean")
obj.multiMode = obj.multiMode ? "true" : "false";
if (typeof obj.permitWithoutStream === "boolean")
obj.permitWithoutStream = obj.permitWithoutStream ? "true" : "false";
// kernel/serverObj/v2ray.go tags the uTLS fingerprint "fingerprint"
if (obj.fp) obj.fingerprint = obj.fp;
delete obj.fp;
switch (obj.net) {
case "kcp":
case "tcp":
case "quic":
break;
default:
obj.type = "";
}
switch (obj.net) {
case "ws":
case "h2":
case "http":
case "quic":
case "grpc":
case "kcp":
case "mkcp":
break;
default:
if (obj.net === "tcp" && obj.type === "http") {
break;
}
obj.path = "";
}
return "vmess://" + Base64.encode(JSON.stringify(obj));
case "ss":
/* ss://BASE64URL(method:password)@server:port#name; SIP002 userinfo is
base64url without padding and the backend decodes only that. */
tmp = `ss://${Base64.encodeURI(`${srcObj.method}:${srcObj.password}`)}@${
srcObj.server
}:${srcObj.port}/`;
if (srcObj.plugin) {
const plugin = [srcObj.plugin];
if (srcObj.plugin === "v2ray-plugin") {
if (srcObj.tls) {
plugin.push("tls");
}
if (srcObj.mode !== "websocket") {
plugin.push("mode=" + srcObj.mode);
}
if (srcObj.host) {
plugin.push("host=" + srcObj.host);
}
if (srcObj.path) {
if (!srcObj.path.startsWith("/")) {
srcObj.path = "/" + srcObj.path;
}
plugin.push("path=" + srcObj.path);
}
if (srcObj.impl) {
plugin.push("impl=" + srcObj.impl);
}
} else {
plugin.push("obfs=" + srcObj.obfs);
plugin.push("obfs-host=" + srcObj.host);
if (srcObj.obfs === "http") {
plugin.push("obfs-uri=" + srcObj.path);
}
if (srcObj.impl) {
plugin.push("impl=" + srcObj.impl);
}
}
tmp += `?plugin=${encodeURIComponent(plugin.join(";"))}`;
}
if (srcObj.backend) {
tmp += `${srcObj.plugin ? "&" : "?"}v2raya-backend=${encodeURIComponent(srcObj.backend)}`;
}
tmp += srcObj.name.length ? `#${encodeURIComponent(srcObj.name)}` : "";
return tmp;
case "ssr":
/* ssr://server:port:proto:method:obfs:URLBASE64(password)/?remarks=URLBASE64(remarks)&protoparam=URLBASE64(protoparam)&obfsparam=URLBASE64(obfsparam)) */
return `ssr://${Base64.encode(
`${srcObj.server}:${srcObj.port}:${srcObj.proto}:${srcObj.method}:${
srcObj.obfs
}:${Base64.encodeURI(srcObj.password)}/?remarks=${Base64.encodeURI(
srcObj.name,
)}&protoparam=${Base64.encodeURI(
srcObj.protoParam,
)}&obfsparam=${Base64.encodeURI(srcObj.obfsParam)}`,
)}`;
case "trojan":
/* trojan://password@server:port?allowInsecure=1&sni=sni#URIESCAPE(name) */
query = {
type: srcObj.net,
pinnedPeerCertSha256: srcObj.pinnedPeerCertSha256,
verifyPeerCertByName: srcObj.verifyPeerCertByName,
};
if (srcObj.peer !== "") {
query.sni = srcObj.peer;
}
tmp = "trojan";
if (srcObj.method !== "origin" || srcObj.obfs !== "none") {
tmp = "trojan-go";
query.type = srcObj.obfs === "none" ? "original" : "ws";
if (srcObj.method === "shadowsocks") {
query.encryption = `ss;${srcObj.ssCipher};${srcObj.ssPassword}`;
}
if (query.type === "ws") {
query.host = srcObj.host || "";
query.path = srcObj.path || "/";
}
}
if (tmp === "trojan" && (srcObj.net === "ws" || srcObj.net === "h2")) {
query.host = srcObj.host;
query.path = srcObj.path;
}
if (srcObj.alpn !== "") {
query.alpn = srcObj.alpn;
}
if (srcObj.net === "grpc") {
query.serviceName = srcObj.path;
}
if (srcObj.net === "mkcp" || srcObj.net === "kcp") {
query.seed = srcObj.path;
}
if (srcObj.backend) {
query["v2raya-backend"] = srcObj.backend;
}
return buildURL({
protocol: tmp,
username: srcObj.password,
host: srcObj.server,
port: srcObj.port,
hash: srcObj.name,
params: query,
});
case "juicity":
query = {
congestion_control: srcObj.cc,
};
if (srcObj.sni !== "") {
query.sni = srcObj.sni;
}
if (srcObj.pinnedCertchainSha256 !== "") {
query.pinned_certchain_sha256 = srcObj.pinnedCertchainSha256;
}
if (srcObj.allowInsecure) {
query.allow_insecure = "true";
}
return buildURL({
protocol: "juicity",
username: srcObj.uuid,
password: srcObj.password,
host: srcObj.server,
port: srcObj.port,
hash: srcObj.name,
params: query,
});
case "tuic":
query = {
pinnedPeerCertSha256: srcObj.pinnedPeerCertSha256,
verifyPeerCertByName: srcObj.verifyPeerCertByName,
congestion_control: srcObj.cc,
disable_sni: srcObj.disableSni,
alpn: srcObj.alpn,
udp_relay_mode: srcObj.udpRelayMode,
};
if (srcObj.sni !== "") {
query.sni = srcObj.sni;
}
if (srcObj.allowInsecure) {
query.allow_insecure = "true";
}
return buildURL({
protocol: "tuic",
username: srcObj.uuid,
password: srcObj.password,
host: srcObj.server,
port: srcObj.port,
hash: srcObj.ps || srcObj.name,
params: query,
});
case "hysteria2":
query = {
pinned_peer_cert_sha256: srcObj.pinnedPeerCertSha256,
verify_peer_cert_by_name: srcObj.verifyPeerCertByName,
};
if (srcObj.sni !== "") {
query.sni = srcObj.sni;
}
if (srcObj.obfs !== "none") {
query.obfs = srcObj.obfs;
query["obfs-password"] = srcObj.obfsPassword;
}
return buildURL({
protocol: "hysteria2",
username: srcObj.password,
host: srcObj.server,
port: srcObj.port,
hash: srcObj.ps || srcObj.name,
params: query,
});
case "http":
case "https":
tmp = {
protocol: srcObj.protocol + "-proxy",
host: srcObj.host,
port: srcObj.port,
hash: srcObj.name,
};
if (srcObj.username && srcObj.password) {
Object.assign(tmp, {
username: srcObj.username,
password: srcObj.password,
});
}
return buildURL(tmp);
case "socks5":
tmp = {
protocol: "socks5",
host: srcObj.host,
port: srcObj.port,
hash: srcObj.name,
};
if (srcObj.username && srcObj.password) {
Object.assign(tmp, {
username: srcObj.username,
password: srcObj.password,
});
}
return buildURL(tmp);
case "anytls":
if (srcObj.sni) {
// the backend (kernel/serverObj/anytls.go) reads sni, not peer
query.sni = srcObj.sni;
}
if (srcObj.pinnedPeerCertSha256) {
query.pinnedPeerCertSha256 = srcObj.pinnedPeerCertSha256;
}
if (srcObj.verifyPeerCertByName) {
query.verifyPeerCertByName = srcObj.verifyPeerCertByName;
}
if (srcObj.allowInsecure) {
query.allow_insecure = "true";
}
if (srcObj.minIdleSession) {
query.minIdleSession = srcObj.minIdleSession;
}
return buildURL({
protocol: "anytls",
username: srcObj.auth,
host: srcObj.host,
port: srcObj.port,
hash: srcObj.name,
params: query,
});
case "wireguard":
// parameter names of kernel/serverObj/wireguard.go; the private key
// travels as the userinfo
query = {};
if (srcObj.publicKey) query.publicKey = srcObj.publicKey;
if (srcObj.localAddress) query.address = srcObj.localAddress;
if (srcObj.mtu) query.mtu = srcObj.mtu;
if (srcObj.allowedIPs) query.allowedIPs = srcObj.allowedIPs;
if (srcObj.persistentKeepalive)
query.keepAlive = srcObj.persistentKeepalive;
if (srcObj.preSharedKey) query.preSharedKey = srcObj.preSharedKey;
return buildURL({
protocol: "wireguard",
username: srcObj.privateKey,
host: srcObj.address,
port: srcObj.port,
hash: srcObj.name,
params: query,
});
}
return null;
}
+69
View File
@@ -0,0 +1,69 @@
// @vitest-environment happy-dom
import { describe, expect, test } from "vitest";
import { generateURL, parseURL } from "./url";
import { links } from "./__fixtures__/links";
describe("share-link URL parts", () => {
test("preserves the custom scheme and encoded identity and fragment", () => {
expect(parseURL(links.wireguard)).toMatchObject({
protocol: "wireguard",
username: "PRIVATEKEY%3D",
host: "1.2.3.4",
port: 51820,
hash: "wg%20node",
params: {
publicKey: "PUBKEY=",
address: "10.0.0.2/32",
preSharedKey: "",
allowedIPs: "0.0.0.0/0",
},
});
});
test("decodes structured query values once", () => {
expect(parseURL(links.ss).params.plugin).toBe(
"obfs-local;obfs=http;obfs-host=example.com",
);
expect(parseURL(links.vlessXhttp).params.xhttpHeaders).toBe('{"X-A":"b"}');
expect(parseURL(links.trojan).params.path).toBe("/tr");
});
test("keeps credentials separate from host and port", () => {
expect(parseURL(links.juicity)).toMatchObject({
username: "b831381d-6324-4d53-ad4f-8cda48b30811",
password: "passw0rd",
protocol: "juicity",
host: "1.2.3.4",
port: 443,
});
expect(parseURL(links.http)).toMatchObject({
username: "user",
password: "passw0rd",
port: 8080,
});
});
test("uses the last repeated query value and retains literal plus signs", () => {
expect(
parseURL("tuic://user@host:443?alpn=h3&alpn=h2&key=a+b").params,
).toEqual({
alpn: "h2",
key: "a+b",
});
});
test("generates custom URLs with query escaping and an unescaped name", () => {
expect(
generateURL({
protocol: "wireguard",
username: "PRIVATEKEY=",
host: "1.2.3.4",
port: 51820,
params: { publicKey: "PUBKEY=", address: "10.0.0.2/32" },
hash: "wg node",
}),
).toBe(
"wireguard://PRIVATEKEY%3D@1.2.3.4:51820/?publicKey=PUBKEY%3D&address=10.0.0.2%2F32#wg node",
);
});
});
+88
View File
@@ -0,0 +1,88 @@
import URI from "urijs";
export interface URLParts {
username?: string;
password?: string;
protocol?: string;
host?: string;
port?: number | string;
params?: Record<string, unknown>;
hash?: string;
path?: string;
}
export function parseURL(source: string) {
let url = source;
let protocol = "";
let fakeProtocol = false;
const separator = url.indexOf("://");
if (separator === -1) {
url = "http://" + url;
} else {
protocol = url.slice(0, separator);
if (!["http", "https", "ws", "wss"].includes(protocol)) {
// Parse custom schemes as HTTP so credentials, host and port follow browser rules.
url = "http" + url.slice(separator);
fakeProtocol = true;
}
}
const anchor = document.createElement("a");
anchor.href = url;
const params: Record<string, string> = {};
for (const segment of anchor.search.replace(/^\?/, "").split("&")) {
if (!segment) continue;
const [key, raw] = segment.split("=");
params[key] = decodeSafe(raw);
}
return {
source,
username: anchor.username,
password: anchor.password,
protocol: fakeProtocol ? protocol : anchor.protocol.replace(":", ""),
host: anchor.hostname,
port: anchor.port
? parseInt(anchor.port)
: protocol === "https" || protocol === "wss"
? 443
: 80,
query: anchor.search,
params,
file: (anchor.pathname.match(/\/([^/?#]+)$/i) || [null, ""])[1]!,
hash: anchor.hash.replace("#", ""),
path: anchor.pathname.replace(/^([^/])/, "/$1"),
relative: (anchor.href.match(/tps?:\/\/[^/]+(.+)/) || [null, ""])[1]!,
segments: anchor.pathname.replace(/^\//, "").split("/"),
};
}
export function generateURL({
username,
password,
protocol,
host,
port,
params,
hash,
path,
}: URLParts): string {
// URI.js treats undefined arguments as getters, which would break the chain.
return URI()
.protocol(protocol || "http")
.username(username || "")
.password(password || "")
.host(host || "")
.port(port || 80)
.path(path || "")
.query(params || {})
.hash(hash || "")
.toString();
}
/** decodeSafe decodes a URI component, or returns the text as it is when it is not encoded (a name with a literal %). */
export function decodeSafe(text: string): string {
try {
return decodeURIComponent(text);
} catch {
return text;
}
}
+37
View File
@@ -0,0 +1,37 @@
// @vitest-environment happy-dom
import { describe, expect, test } from "vitest";
import { createPinia, setActivePinia } from "pinia";
import { onSessionTeardown, resetSession, setSessionStarter } from "./session";
import { openDialog, dialogState } from "./composables/useDialog";
import { useNotify, noticeState } from "./composables/useNotify";
import { openLoading, loadingState } from "./composables/useLoading";
import { useAppStore } from "./stores/app";
describe("resetSession runs the teardown in order", () => {
test("teardown, then what is on screen, then the stores, then the starter", async () => {
const pinia = createPinia();
setActivePinia(pinia);
const order: string[] = [];
onSessionTeardown(() => order.push("teardown"));
openDialog({ render: () => null }).result.then(() =>
order.push("dialog closed"),
);
useNotify().info("x");
openLoading();
const app = useAppStore(pinia);
app.setRunning("running");
setSessionStarter(async () => {
order.push(`start:${app.token}@${app.backendAddress}:${app.running}`);
});
await resetSession({ token: "tok-2", backendAddress: "http://b" }, pinia);
expect(order).toEqual([
"teardown",
"dialog closed",
"start:tok-2@http://b:checking",
]);
expect(dialogState.stack).toHaveLength(0);
expect(noticeState.current).toBeNull();
expect(loadingState.open.size).toBe(0);
expect(localStorage.getItem("token")).toBe("tok-2");
});
});
+59
View File
@@ -0,0 +1,59 @@
// A session is one token on one backend. Logging in or out and changing
// the backend address reset it; the old GUI rebuilt its whole root for
// that. Here the reset is an explicit order: stop what the session started,
// refuse late responses, close what is on screen, reset the stores, start
// again.
import { getActivePinia, type Pinia } from "pinia";
import { abortSession } from "@/api/client";
import { closeAllDialogs } from "@/composables/useDialog";
import { closeAllNotices } from "@/composables/useNotify";
import { closeAllBanners } from "@/composables/useBanner";
import { closeAllLoadings } from "@/composables/useLoading";
import { useAppStore } from "@/stores/app";
type Teardown = () => void;
const teardowns = new Set<Teardown>();
let starter: (() => void | Promise<void>) | null = null;
/** onSessionTeardown registers what a session started (a socket, a listener, a timer); returns the unregister. */
export function onSessionTeardown(fn: Teardown): () => void {
teardowns.add(fn);
return () => teardowns.delete(fn);
}
/** setSessionStarter names the routine that brings a session up: account check, version, socket. */
export function setSessionStarter(fn: () => void | Promise<void>): void {
starter = fn;
}
export interface SessionChange {
token?: string;
backendAddress?: string;
}
/** resetSession tears the current session down in order and starts the next one. */
export async function resetSession(
change: SessionChange = {},
pinia: Pinia | undefined = getActivePinia(),
): Promise<void> {
// 1. what the session started
for (const fn of [...teardowns]) fn();
teardowns.clear();
// 2. requests in flight are aborted and their late answers refused
abortSession();
// 3. nothing of the old session stays on screen
closeAllDialogs();
closeAllNotices();
closeAllBanners();
closeAllLoadings();
// the dialogs' result handlers run before the next session starts
await new Promise((r) => setTimeout(r, 0));
// 4. the stores, then the facts that identify the next session
const app = useAppStore(pinia);
app.$reset();
if (change.backendAddress !== undefined)
app.setBackendAddress(change.backendAddress);
if (change.token !== undefined) app.setToken(change.token);
// 5. up again
await starter?.();
}
+28
View File
@@ -0,0 +1,28 @@
import { createApp } from "vue";
import { createPinia } from "pinia";
import AppShell from "@/AppShell.vue";
import i18n from "@/plugins/i18n";
import "@/plugins/dayjs";
import { vuetify } from "@/theme";
function initializeBackendAddress(): void {
// Reverse-proxy deployments serve the GUI and API under the same path prefix.
const address = localStorage.getItem("backendAddress");
const prefix = window.location.pathname.match(
/^(.*)\/(?:login|setting|log|server|rule|running)?\/?$/,
)?.[1];
if (
prefix &&
prefix !== "/" &&
(!address || (address.startsWith("/") && !address.startsWith("//")))
) {
localStorage.setItem("backendAddress", prefix);
} else if (address === null) {
localStorage.setItem("backendAddress", "");
}
}
export function buildApp() {
initializeBackendAddress();
return createApp(AppShell).use(createPinia()).use(vuetify).use(i18n);
}
+13
View File
@@ -0,0 +1,13 @@
// "Refresh" for a notice that asks for one (the backend is still busy
// with the previous request): the shell registers the current page's
// sync; without one the page reloads.
let refresher: (() => Promise<void> | void) | null = null;
export function setRefresher(fn: (() => Promise<void> | void) | null): void {
refresher = fn;
}
export function refresh(): void {
if (refresher) void refresher();
else location.reload();
}
+135
View File
@@ -0,0 +1,135 @@
import { defineStore } from "pinia";
import { Base64 } from "js-base64";
import type { OutboundStatus, Which, VersionResponse } from "@/api/types";
import { brandSeed, isSeed } from "@/theme/scheme";
/** normalizeOutbounds keeps the backend's list as names: trimmed, unique, "proxy" first. */
export function normalizeOutbounds(outbounds: unknown): string[] {
const seen = new Set<string>();
const names: string[] = [];
if (Array.isArray(outbounds)) {
for (const outbound of outbounds) {
if (typeof outbound !== "string") continue;
const name = outbound.trim();
if (!name || seen.has(name)) continue;
seen.add(name);
names.push(name);
}
}
if (!seen.has("proxy")) names.unshift("proxy");
return names;
}
/** The core's state as the backend reports it; text for it comes from the locale. */
export type Running = "checking" | "running" | "stopped" | "paused";
export type ThemePreference = "auto" | "light" | "dark";
/** The page's destinations, in the order the rail and the bar show them. */
export type View = "dashboard" | "proxies" | "settings" | "logs" | "about";
// One store for the session-wide state the old App.vue kept in data and
// localStorage: what was a translated text ("正在运行") is an enum here, so
// switching the language does not have to rebuild the page.
export const useAppStore = defineStore("app", {
state: () => ({
token: localStorage.getItem("token") ?? "",
backendAddress: localStorage.getItem("backendAddress") ?? "",
running: "checking" as Running,
networkPaused: false,
connectedServer: [] as Which[],
outboundName: "proxy",
outbounds: ["proxy"] as string[],
/** the last observatory frame of each outbound group: what the core sees of its members */
observatory: {} as Record<string, OutboundStatus[]>,
version: null as VersionResponse | null,
/** the last /version banner facts, seeded from localStorage before the request answers */
// "1"/"0" as the backend sends it; the old settings dialog parses it
lite: parseInt(localStorage.getItem("lite") ?? "0") > 0,
docker: localStorage.getItem("docker") === "true",
variant: localStorage.getItem("variant") ?? "",
loadBalanceValid: localStorage.getItem("loadBalanceValid") !== "false",
coreVersionValid: localStorage.getItem("coreVersionValid") !== "false",
coreVersionErr: localStorage.getItem("coreVersionErr") ?? "",
themePreference: (["light", "dark"].includes(
localStorage.getItem("theme") ?? "",
)
? localStorage.getItem("theme")
: "auto") as ThemePreference,
systemDark: window.matchMedia("(prefers-color-scheme: dark)").matches,
/** the seed colour the theme's palettes derive from */
themeSeed: (() => {
const seed = localStorage.getItem("themeSeed") ?? "";
return isSeed(seed) ? seed.toLowerCase() : brandSeed;
})(),
language: localStorage.getItem("_lang") ?? "",
view: "dashboard" as View,
}),
getters: {
loggedIn: (s) => s.token !== "",
/** the name inside the token; empty when there is no token or it does not parse */
username: (s) => {
if (!s.token) return "";
try {
const payload = JSON.parse(Base64.decode(s.token.split(".")[1]));
return typeof payload.uname === "string" ? payload.uname : "";
} catch {
return "";
}
},
isDark: (s) =>
s.themePreference === "auto"
? s.systemDark
: s.themePreference === "dark",
},
actions: {
setToken(token: string) {
this.token = token;
if (token) localStorage.setItem("token", token);
else localStorage.removeItem("token");
},
setBackendAddress(address: string) {
this.backendAddress = address;
localStorage.setItem("backendAddress", address);
},
setRunning(running: Running, networkPaused = false) {
this.running = running;
this.networkPaused = networkPaused;
},
setOutbounds(outbounds: unknown) {
this.outbounds = normalizeOutbounds(outbounds);
if (!this.outbounds.includes(this.outboundName))
this.outboundName = "proxy";
// a deleted group's last frame would otherwise outlive it
for (const name of Object.keys(this.observatory))
if (!this.outbounds.includes(name)) delete this.observatory[name];
},
setTheme(preference: ThemePreference) {
this.themePreference = preference;
localStorage.setItem("theme", preference);
},
setThemeSeed(seed: string) {
if (!isSeed(seed)) return;
this.themeSeed = seed.toLowerCase();
localStorage.setItem("themeSeed", this.themeSeed);
},
setLanguage(code: string) {
this.language = code;
localStorage.setItem("_lang", code);
},
applyVersion(v: VersionResponse) {
this.version = v;
this.lite = v.lite > 0;
this.docker = !!v.docker;
this.variant = v.variant;
this.loadBalanceValid = v.loadBalanceValid;
this.coreVersionValid = v.coreVersionValid;
this.coreVersionErr = v.coreVersionErr ?? "";
localStorage.setItem("lite", String(v.lite));
localStorage.setItem("docker", String(!!v.docker));
localStorage.setItem("variant", v.variant ?? "");
localStorage.setItem("loadBalanceValid", String(v.loadBalanceValid));
localStorage.setItem("coreVersionValid", String(v.coreVersionValid));
localStorage.setItem("coreVersionErr", v.coreVersionErr ?? "");
localStorage.setItem("version", v.version ?? "");
},
},
});
+64
View File
@@ -0,0 +1,64 @@
// Where Vuetify's Material 3 blueprint stops short of the spec: the
// filter chip's outline and corners, the primary tab's indicator.
// Material's state layers: 8 % hover, 10 % focus and pressed (Vuetify's
// defaults are 4 / 12 / 12)
.v-application {
--v-hover-opacity: 0.08;
--v-focus-opacity: 0.1;
--v-pressed-opacity: 0.1;
}
// chips: 8 dp corners, a 1 dp outline-variant border when outlined
.v-chip.v-chip--variant-outlined {
border-color: rgb(var(--v-theme-outline-variant));
}
// primary tabs: a 3 dp indicator with rounded top corners
.v-tabs:not(.v-tabs--inset) .v-tab__slider {
height: 3px;
border-radius: 3px 3px 0 0;
}
// dialog actions: 40 dp buttons with Material's padding (24 dp filled,
// 12 dp text) and an 8 dp gap; the card-actions preset slims them
.v-card-actions {
gap: 8px;
}
.v-card-actions .v-btn {
height: 40px;
min-width: 64px;
}
.v-card-actions .v-btn.v-btn--slim {
padding: 0 12px;
}
.v-card-actions .v-btn.v-btn--slim.v-btn--variant-flat,
.v-card-actions .v-btn.v-btn--slim.v-btn--variant-tonal,
.v-card-actions .v-btn.v-btn--slim.v-btn--variant-outlined {
padding: 0 24px;
}
// dialog bodies: a text field's floating label rises 8 dp above the
// field, so the body keeps that much above its first child even when a
// title precedes it (Vuetify zeroes it there)
.v-card-item + .v-card-text,
.v-card-title + .v-card-text {
padding-top: 8px;
}
// scrollbars: thin, in the outline colour, on every scrolling region
* {
scrollbar-width: thin;
scrollbar-color: rgb(var(--v-theme-outline-variant)) transparent;
}
// plain tooltips: Material's inverse surface, 4 dp corners, body-small
.v-tooltip > .v-overlay__content {
background: rgb(var(--v-theme-inverse-surface));
color: rgb(var(--v-theme-inverse-on-surface));
border-radius: 4px;
padding: 4px 8px;
font-size: 12px;
line-height: 16px;
letter-spacing: 0.4px;
}
+46
View File
@@ -0,0 +1,46 @@
// Red Hat Text, self-hosted (Google Fonts v19, latin and latin-ext, variable weight 300–700);
// the CJK and other scripts fall through to the system stack.
@font-face {
font-family: "Red Hat Text";
font-style: italic;
font-weight: 300 700;
font-display: swap;
src: url("/static/fonts/red-hat-text-italic-latin-ext.woff2") format("woff2");
unicode-range:
U+0100-02BA, U+02BD-02C5, U+02C7-02CC, U+02CE-02D7, U+02DD-02FF, U+0304,
U+0308, U+0329, U+1D00-1DBF, U+1E00-1E9F, U+1EF2-1EFF, U+2020, U+20A0-20AB,
U+20AD-20C0, U+2113, U+2C60-2C7F, U+A720-A7FF;
}
@font-face {
font-family: "Red Hat Text";
font-style: italic;
font-weight: 300 700;
font-display: swap;
src: url("/static/fonts/red-hat-text-italic-latin.woff2") format("woff2");
unicode-range:
U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC,
U+0304, U+0308, U+0329, U+2000-206F, U+20AC, U+2122, U+2191, U+2193, U+2212,
U+2215, U+FEFF, U+FFFD;
}
@font-face {
font-family: "Red Hat Text";
font-style: normal;
font-weight: 300 700;
font-display: swap;
src: url("/static/fonts/red-hat-text-normal-latin-ext.woff2") format("woff2");
unicode-range:
U+0100-02BA, U+02BD-02C5, U+02C7-02CC, U+02CE-02D7, U+02DD-02FF, U+0304,
U+0308, U+0329, U+1D00-1DBF, U+1E00-1E9F, U+1EF2-1EFF, U+2020, U+20A0-20AB,
U+20AD-20C0, U+2113, U+2C60-2C7F, U+A720-A7FF;
}
@font-face {
font-family: "Red Hat Text";
font-style: normal;
font-weight: 300 700;
font-display: swap;
src: url("/static/fonts/red-hat-text-normal-latin.woff2") format("woff2");
unicode-range:
U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC,
U+0304, U+0308, U+0329, U+2000-206F, U+20AC, U+2122, U+2191, U+2193, U+2212,
U+2215, U+FEFF, U+FFFD;
}
+76
View File
@@ -0,0 +1,76 @@
import "vuetify/styles";
import { createVuetify, type ThemeDefinition } from "vuetify";
import { md3 } from "vuetify/blueprints";
import { aliases, mdi } from "vuetify/iconsets/mdi-svg";
import { en, fa, ko, pt, ru, zhHans } from "vuetify/locale";
import "./typography.scss";
import "./components.scss";
import { brandSeed, schemeColors } from "./scheme";
// The interface's locale codes (localStorage _lang, the locales/ files)
// and Vuetify's own message sets for its built-in texts (the table's
// pagination, the date picker).
export const vuetifyLocales: Record<string, string> = {
en: "en",
zh: "zhHans",
fa: "fa",
ru: "ru",
pt: "pt",
ko: "ko",
};
// The two themes start from the brand seed; the shell recomputes them when
// the user picks another seed (theme/scheme.ts).
export const light: ThemeDefinition = {
dark: false,
colors: schemeColors(brandSeed, false),
};
export const dark: ThemeDefinition = {
dark: true,
colors: schemeColors(brandSeed, true),
};
// The theme name Vuetify starts with; App switches it from the stored
// preference (auto/light/dark) and the OS query.
export const vuetify = createVuetify({
blueprint: md3,
icons: { defaultSet: "mdi", aliases, sets: { mdi } },
locale: {
locale: "en",
fallback: "en",
messages: { en, zhHans, fa, ko, pt, ru },
},
theme: {
defaultTheme: "light",
themes: { light, dark },
// the state layer opacities MD3 specifies; the blueprint does not set them
variations: {
colors: ["primary", "secondary", "tertiary"],
lighten: 1,
darken: 1,
},
},
defaults: {
global: { ripple: false },
VBtn: { variant: "flat", height: 40 },
VCard: { elevation: 0, rounded: "lg" },
VDialog: { scrim: "on-surface" },
// Material's menu: surface-container at elevation 2, 8 dp from its anchor
VMenu: {
offset: 8,
VList: { bgColor: "surface-container", elevation: 2, rounded: "lg" },
VCard: { color: "surface-container", elevation: 2, rounded: "lg" },
},
VTooltip: { location: "top" },
VTextField: { variant: "outlined", density: "comfortable" },
VSelect: { variant: "outlined", density: "comfortable" },
VCombobox: { variant: "outlined", density: "comfortable" },
VTextarea: { variant: "outlined", density: "comfortable" },
VSwitch: { inset: true, color: "primary" },
// Material's chips: 8 dp corners; a selected filter chip is secondary-container
VChip: { rounded: "lg" },
VChipGroup: {
selectedClass: "bg-secondary-container text-on-secondary-container",
},
},
});
+133
View File
@@ -0,0 +1,133 @@
// Material 3 colour roles from one seed colour, the way the Material theme
// builder derives them: the seed's hue and chroma in HCT space give the
// primary, secondary, tertiary and neutral tonal palettes, and each role
// is a fixed tone of one palette, in a light and a dark version. The
// scheme is "tonal spot", Material's default. Only the seed is the user's
// choice; success, warning and info are the primary, error and tertiary roles.
import {
argbFromHex,
Hct,
hexFromArgb,
MaterialDynamicColors,
SchemeMonochrome,
SchemeTonalSpot,
} from "@material/material-color-utilities";
/** The default seed: Google yellow. */
export const brandSeed = "#fbbc04";
export const presetSeeds: { name: string; seed: string }[] = [
{ name: "brand", seed: brandSeed },
{ name: "teal", seed: "#13aab7" },
{ name: "blue", seed: "#4a6fd5" },
{ name: "green", seed: "#3d8f5a" },
{ name: "purple", seed: "#7b57c7" },
{ name: "red", seed: "#c8493f" },
];
// role → Vuetify colour key
const roles = {
primary: "primary",
onPrimary: "on-primary",
primaryContainer: "primary-container",
onPrimaryContainer: "on-primary-container",
inversePrimary: "inverse-primary",
secondary: "secondary",
onSecondary: "on-secondary",
secondaryContainer: "secondary-container",
onSecondaryContainer: "on-secondary-container",
tertiary: "tertiary",
onTertiary: "on-tertiary",
tertiaryContainer: "tertiary-container",
onTertiaryContainer: "on-tertiary-container",
error: "error",
onError: "on-error",
errorContainer: "error-container",
onErrorContainer: "on-error-container",
background: "background",
onBackground: "on-background",
surface: "surface",
onSurface: "on-surface",
surfaceDim: "surface-dim",
surfaceBright: "surface-bright",
surfaceContainerLowest: "surface-container-lowest",
surfaceContainerLow: "surface-container-low",
surfaceContainer: "surface-container",
surfaceContainerHigh: "surface-container-high",
surfaceContainerHighest: "surface-container-highest",
surfaceVariant: "surface-variant",
onSurfaceVariant: "on-surface-variant",
inverseSurface: "inverse-surface",
inverseOnSurface: "inverse-on-surface",
outline: "outline",
outlineVariant: "outline-variant",
surfaceTint: "surface-tint",
} as const;
// Vuetify's success / warning / info keys, which v-alert's `type` uses,
// follow the scheme: success is the primary, info the tertiary, warning
// the error role, each with its "on" colour
function statusColors(colors: Record<string, string>) {
return {
success: colors.primary,
"on-success": colors["on-primary"],
warning: colors.error,
"on-warning": colors["on-error"],
info: colors.tertiary,
"on-info": colors["on-tertiary"],
};
}
/** isSeed accepts a #rrggbb colour. */
/** seedFromHue gives a vivid seed at a hue (0–360): HCT chroma 48, tone 60, as the theme builder's wheel does. */
export function seedFromHue(hue: number): string {
return hexFromArgb(Hct.from(((hue % 360) + 360) % 360, 48, 60).toInt());
}
/** hueOf reads a seed's HCT hue, for the slider's position. */
export function hueOf(seed: string): number {
return isSeed(seed) ? Hct.fromInt(argbFromHex(seed)).hue : 0;
}
export function isSeed(value: string): boolean {
return /^#[0-9a-f]{6}$/i.test(value);
}
/** The colour set of one theme, complete: Vuetify's required keys and every Material role. */
export type SchemeColors = Record<string, string> &
Record<
| "background"
| "surface"
| "primary"
| "secondary"
| "success"
| "warning"
| "error"
| "info"
| "on-background"
| "on-surface"
| "on-primary"
| "on-secondary"
| "on-success"
| "on-warning"
| "on-error"
| "on-info",
string
>;
/** schemeColors gives the Vuetify colour set for one seed in one brightness. */
export function schemeColors(seed: string, dark: boolean): SchemeColors {
const hct = Hct.fromInt(argbFromHex(isSeed(seed) ? seed : brandSeed));
// a grey, black or white seed has no hue to speak of: tonal spot would
// paint it pink from hue 0, so those get the monochrome scheme instead
const scheme =
hct.chroma < 5
? new SchemeMonochrome(hct, dark, 0)
: new SchemeTonalSpot(hct, dark, 0);
const colors: Record<string, string> = {};
for (const [role, key] of Object.entries(roles)) {
const color = MaterialDynamicColors[role as keyof typeof roles];
colors[key] = hexFromArgb(color.getArgb(scheme));
}
return { ...colors, ...statusColors(colors) } as SchemeColors;
}
+129
View File
@@ -0,0 +1,129 @@
// Material 3 type scale, expressed as utility classes on top of Vuetify's
// own text classes so a template says which role it renders. The family is
// Red Hat Text (self-hosted, fonts.scss) over the system stack, which
// carries the CJK and other scripts.
@use "./fonts";
$md3-font:
"Red Hat Text",
BlinkMacSystemFont,
-apple-system,
"Segoe UI",
Roboto,
Oxygen,
Ubuntu,
Cantarell,
"Fira Sans",
"Droid Sans",
"Helvetica Neue",
Helvetica,
Arial,
sans-serif;
.v-application {
--v-font-body: #{$md3-font};
--v-font-heading: #{$md3-font};
font-family: $md3-font;
}
$md3-scale: (
"display-large": (
57px,
64px,
400,
-0.25px,
),
"display-medium": (
45px,
52px,
400,
0,
),
"display-small": (
36px,
44px,
400,
0,
),
"headline-large": (
32px,
40px,
400,
0,
),
"headline-medium": (
28px,
36px,
400,
0,
),
"headline-small": (
24px,
32px,
400,
0,
),
"title-large": (
22px,
28px,
400,
0,
),
"title-medium": (
16px,
24px,
500,
0.15px,
),
"title-small": (
14px,
20px,
500,
0.1px,
),
"body-large": (
16px,
24px,
400,
0.5px,
),
"body-medium": (
14px,
20px,
400,
0.25px,
),
"body-small": (
12px,
16px,
400,
0.4px,
),
"label-large": (
14px,
20px,
500,
0.1px,
),
"label-medium": (
12px,
16px,
500,
0.5px,
),
"label-small": (
11px,
16px,
500,
0.5px,
),
);
@each $name, $spec in $md3-scale {
.md3-#{$name} {
font-size: nth($spec, 1);
line-height: nth($spec, 2);
font-weight: nth($spec, 3);
letter-spacing: nth($spec, 4);
}
}