feat: JWT过期自动重置 + 用户端登录页 + 系统设置前三个真实实现
CI / Backend (build / vet / test / cross-compile) (push) Has been cancelled
CI / Frontend (tsc + vite build) (push) Has been cancelled

agent-111 JWT过期重置+系统设置去占位:
- ws.ts 识别401/过期 markAuthExpired(清token+停重连+expired态),isTokenExpired;wsParse.ts拆出压行371;scheduleReconnect有token未过期才重连
- api.ts REST 401→auth_expired+清token+引导重登;login走skipAuthExpired密码错不误清
- types.ts WsStatus加expired;TopBar/Nav expired显示登录过期;System.tsx去alert占位改4张事实卡+合并Notice

agent-113 用户端登录页:
- components/Login.tsx Miuix登录卡(用户名/密码→login()→setAuthToken);App !getAuthToken()→<Login>;AdminApp LoginGate指向

agent-112 系统设置前三个(owner+审计):
- auth.APIKey.RevokeAll(吊销全部key);auth.JWTService.RotateSecret(≥32校验+并发安全+新密钥不回显)
- gateway admin_system.go: POST revoke-keys/rotate-jwt/backup(VACUUM INTO)/restore(防路径穿越+恢复前自动备份+原子替换+需重启)
- wire.go 传DatabasePath;全仓 build/vet/test绿+交叉编译;api-client v0.17系统设置契约

实机验证: 登录(role=owner)+revoke-keys 200+渠道列表含kook; 全仓绿+前端build绿; .env密码仅登录验证不打印
This commit is contained in:
Aska committed 2026-09-07 13:57:36 +08:00
1 parent 7e39153a69
commit 1ebc82fffd
19 files changed
+1164 -245

No files matched your search

+53 -6
View File
@@ -101,6 +101,38 @@ export function setStoredRole(role: Role | null): void {
else localStorage.removeItem(ROLE_KEY);
}
/** True when the JWT's `exp` (unix seconds) is already in the past. Used client-side
* to recognise a handshake rejection as "token expired" before the browser ever
* exposes the 401 (WS handshake failures surface only as a generic close). */
export function isTokenExpired(token: string): boolean {
const parts = token.split(".");
if (parts.length < 2) return false;
try {
const b64 = parts[1].replace(/-/g, "+").replace(/_/g, "/");
const padded = b64 + "=".repeat((4 - (b64.length % 4)) % 4);
const payload = JSON.parse(atob(padded)) as { exp?: number };
const exp = payload.exp;
return typeof exp === "number" && exp > 0 && Math.floor(Date.now() / 1000) >= exp;
} catch {
return false;
}
}
/** Subscribe to an "auth expired" event. The REST layer fires this exactly once
* when a non-login request comes back 401/unauthorized, after already clearing
* the stored token; the WS layer subscribes to stop reconnecting + flag the UI. */
type AuthExpiredHandler = () => void;
const authExpiredHandlers = new Set<AuthExpiredHandler>();
export function onAuthExpired(handler: AuthExpiredHandler): () => void {
authExpiredHandlers.add(handler);
return () => {
authExpiredHandlers.delete(handler);
};
}
function fireAuthExpired(): void {
authExpiredHandlers.forEach((h) => h());
}
/** Optional API key for admin endpoints (X-API-Key). */
export function getApiKey(): string | null {
return localStorage.getItem(API_KEY_KEY);
@@ -125,7 +157,8 @@ export interface ChannelConfigSaveResult {
async function request<T>(
path: string,
init: RequestInit = {}
init: RequestInit = {},
opts: { skipAuthExpired?: boolean } = {}
): Promise<T> {
const headers = new Headers(init.headers);
headers.set("Content-Type", "application/json");
@@ -151,9 +184,19 @@ async function request<T>(
}
if (!res.ok || body.error) {
const code = body.error?.code ?? (res.status === 401 ? "unauthorized" : "unknown");
// A 401/unauthorized on a logged-in (non-login) call means the stored token is
// gone/expired: clear it and notify the WS layer so it stops reconnecting, then
// throw a dedicated code so the UI can prompt re-login. The login call itself is
// exempt — a bad password is a per-request failure, not a stale session.
if (!opts.skipAuthExpired && (res.status === 401 || code === "unauthorized")) {
setAuthToken(null);
fireAuthExpired();
throw new ApiError(res.status, "auth_expired", "登录已过期,请重新登录");
}
throw new ApiError(
res.status,
body.error?.code ?? "unknown",
code,
body.error?.message ?? `请求失败(${res.status})`
);
}
@@ -162,10 +205,14 @@ async function request<T>(
/** POST /api/v1/auth/login — exchanges user/password for a JWT. */
export function login(username: string, password: string): Promise<LoginResult> {
return request<LoginResult>("/auth/login", {
method: "POST",
body: JSON.stringify({ username, password }),
});
return request<LoginResult>(
"/auth/login",
{
method: "POST",
body: JSON.stringify({ username, password }),
},
{ skipAuthExpired: true }
);
}
/** GET /api/v1/health — liveness probe. */