Files
SnowLuma/packages/webui/src/lib/api/client.ts
T
DrSmoothl caf724b25c fix(webui): preserve config edits on save and UIN choice across tabs
Two regressions slipped into the ApiClient/ConfigPage refactor:

1. api.config.save() ran the POST response through normalizeOneBotConfig
   and used it to overwrite local state. But POST /api/config/:uin
   returns { success, reloaded, message } — no config body — so the
   normaliser produced an empty config and wiped the user's edits as
   soon as the save succeeded. Honour the "save returns canonical view"
   contract by following the POST with a GET inside the client; the
   round-trip stays hidden behind the seam.

2. selectedUin lived inside useOneBotInstanceConfig, so navigating away
   from ConfigPage unmounted the hook and lost the user's selection.
   Lift selectedUin to AppInner and make the hook externally controlled
   via { selectedUin, onSelectedUinChange }. Clear it on logout.
2026-05-16 02:22:48 +08:00

251 lines
8.0 KiB
TypeScript

import type { HookProcessInfo, LogEntry, QQInfo, SystemInfo } from '@/types';
import type { PasswordRule } from '@/components/pages/change-password-page';
import { normalizeOneBotConfig } from '@/lib/onebot-config';
import {
ApiError,
type ApiClient,
type ChangePasswordResult,
type CreateApiClientOptions,
type LoginResult,
type LogsStreamOptions,
type ProcessActionResult,
type TokenStore,
} from './types';
import { localStorageTokenStore } from './token-store';
const DEFAULT_TOKEN_KEY = 'snowluma_token';
interface ErrorPayload {
message?: string;
error?: string;
code?: string;
}
async function readJson<T>(res: Response): Promise<T> {
try {
return (await res.json()) as T;
} catch {
return {} as T;
}
}
function extractErrorMessage(payload: ErrorPayload, fallback: string): string {
return payload.message || payload.error || fallback;
}
class HttpApiClient implements ApiClient {
private tokenStore: TokenStore;
private currentToken: string | null;
private onUnauthorized?: () => void;
// namespaced surfaces are bound up-front so callers can destructure
readonly processes: ApiClient['processes'];
readonly config: ApiClient['config'];
readonly logs: ApiClient['logs'];
constructor(opts: CreateApiClientOptions = {}) {
this.tokenStore = opts.tokenStore ?? localStorageTokenStore(DEFAULT_TOKEN_KEY);
this.currentToken = this.tokenStore.load();
this.onUnauthorized = opts.onUnauthorized;
this.processes = {
list: () => this.getJson<{ list: HookProcessInfo[] }>('/api/processes').then((d) => d.list ?? []),
load: (pid) => this.postJson<ProcessActionResult>(`/api/processes/${pid}/load`),
unload: (pid) => this.postJson<ProcessActionResult>(`/api/processes/${pid}/unload`),
refresh: (pid) => this.postJson<ProcessActionResult>(`/api/processes/${pid}/refresh`),
};
this.config = {
get: async (uin) => {
const url = `/api/config/${encodeURIComponent(uin)}`;
const data = await this.getJson<{ config?: unknown } | unknown>(url);
const raw =
typeof data === 'object' && data != null && 'config' in (data as Record<string, unknown>)
? (data as { config: unknown }).config
: data;
return normalizeOneBotConfig(raw);
},
save: async (uin, config) => {
const url = `/api/config/${encodeURIComponent(uin)}`;
// POST returns { success, reloaded, message } — no config body. To
// honour the "save returns canonical server view" contract, refetch
// after a successful POST.
await this.fetchJson<unknown>(url, {
method: 'POST',
body: JSON.stringify(config),
});
return this.config.get(uin);
},
};
this.logs = {
list: async (limit = 500) => {
const data = await this.getJson<{ list: LogEntry[] }>(`/api/logs?limit=${limit}`);
return data.list ?? [];
},
stream: (options) => this.openLogStream(options),
};
}
// ---------- HTTP helpers ----------
async request(url: string, init: RequestInit = {}): Promise<Response> {
const headers: Record<string, string> = {
...((init.headers as Record<string, string> | undefined) ?? {}),
};
if (this.currentToken) headers['Authorization'] = `Bearer ${this.currentToken}`;
if (init.body && !headers['Content-Type']) headers['Content-Type'] = 'application/json';
const res = await fetch(url, { ...init, headers });
if (res.status === 401) {
this.setToken(null);
this.onUnauthorized?.();
}
return res;
}
/** Like request(), but throws ApiError on non-2xx and parses JSON. */
private async fetchJson<T>(url: string, init: RequestInit = {}): Promise<T> {
const res = await this.request(url, init);
if (!res.ok) {
const payload = await readJson<ErrorPayload>(res);
throw new ApiError(res.status, extractErrorMessage(payload, res.statusText || '请求失败'), payload.code);
}
return readJson<T>(res);
}
private getJson<T>(url: string): Promise<T> {
return this.fetchJson<T>(url);
}
private postJson<T>(url: string, body?: unknown): Promise<T> {
return this.fetchJson<T>(url, {
method: 'POST',
body: body == null ? undefined : JSON.stringify(body),
});
}
// ---------- token management ----------
private setToken(token: string | null): void {
this.currentToken = token;
this.tokenStore.save(token);
}
// ---------- auth ----------
async login(password: string): Promise<LoginResult> {
// Login deliberately bypasses fetchJson/onUnauthorized so a bad password
// doesn't trigger a global sign-out side effect.
try {
const res = await fetch('/api/login', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ password }),
});
if (!res.ok) {
const payload = await readJson<ErrorPayload>(res);
return { ok: false, message: extractErrorMessage(payload, '令牌错误') };
}
const payload = await readJson<{ token: string; mustChangePassword?: boolean }>(res);
this.setToken(payload.token);
return { ok: true, mustChangePassword: !!payload.mustChangePassword };
} catch (e) {
return { ok: false, message: e instanceof Error ? e.message : '网络错误' };
}
}
async logout(): Promise<void> {
try {
await this.request('/api/logout', { method: 'POST' });
} catch {
/* ignore */
}
this.setToken(null);
}
async status(): Promise<boolean> {
if (!this.currentToken) return false;
try {
const res = await this.request('/api/status');
return res.ok;
} catch {
return false;
}
}
async mustChangePassword(): Promise<boolean> {
try {
const data = await this.getJson<{ mustChangePassword?: boolean }>('/api/auth/state');
return !!data.mustChangePassword;
} catch {
return false;
}
}
async checkPasswordStrength(password: string): Promise<{ rules: PasswordRule[]; valid: boolean }> {
try {
const data = await this.postJson<{ rules?: PasswordRule[]; valid?: boolean }>(
'/api/auth/check-strength',
{ password },
);
return { rules: data.rules ?? [], valid: !!data.valid };
} catch {
return { rules: [], valid: false };
}
}
async changePassword(oldPassword: string, newPassword: string): Promise<ChangePasswordResult> {
try {
const data = await this.postJson<{ success?: boolean; message?: string }>(
'/api/auth/change-password',
{ oldPassword, newPassword },
);
return { success: !!data.success, message: data.message };
} catch (e) {
if (e instanceof ApiError) return { success: false, message: e.message };
return { success: false, message: e instanceof Error ? e.message : '网络错误' };
}
}
// ---------- top-level resources ----------
async qqList(): Promise<QQInfo[]> {
const data = await this.getJson<{ list: QQInfo[] }>('/api/qq-list');
return data.list ?? [];
}
system(): Promise<SystemInfo> {
return this.getJson<SystemInfo>('/api/system');
}
// ---------- SSE ----------
private openLogStream(options: LogsStreamOptions): () => void {
if (!this.currentToken) {
options.onStatus?.('closed');
return () => {};
}
const url = `/api/logs/stream?token=${encodeURIComponent(this.currentToken)}`;
const source = new EventSource(url);
source.onopen = () => options.onStatus?.('open');
source.onerror = () => options.onStatus?.('reconnecting');
source.onmessage = (event) => {
try {
const parsed = JSON.parse(event.data) as LogEntry | { type: string };
if ('type' in parsed) return; // control frame, not a log line
options.onLine(parsed);
} catch {
/* malformed frame, skip */
}
};
return () => {
source.close();
options.onStatus?.('closed');
};
}
}
export function createApiClient(options: CreateApiClientOptions = {}): ApiClient {
return new HttpApiClient(options);
}