Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,11 @@
# Changelog

## Unreleased

- 修复插件安装失败时错误正文泄漏到界面:普通请求、上传及安装 SSE 统一保留结构化错误与翻译,非 JSON 响应仅展示 HTTP 状态与请求编号,错误读取限制为 16 KiB / 2 秒。
- 插件下载、解压和依赖安装移至后台,注册和运行时刷新保留在事件循环;加入下载超时、大小及总时间预算,同插件并发冲突和取消保护,更新失败恢复旧文件与注册,禁用插件更新后保持禁用。


本文件记录项目的所有重要变更。

格式遵循 [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),版本号遵循 [语义化版本规范](https://semver.org/spec/v2.0.0.html)。
Expand Down
19 changes: 10 additions & 9 deletions dashboard/src/api/modules/browser.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
import i18n from "../../i18n";
import { requestStream } from "../request";
import { apiErrorMessage } from "../../utils/apiError";
import { bridgeAgentHeaders, request, getAuthToken } from "../request";
import { getApiUrl, getWsUrl } from "../config";
import { getWsUrl } from "../config";
import type {
BrowserReplayRequest,
BrowserReplayResponse,
Expand Down Expand Up @@ -33,21 +36,16 @@ function streamBrowserSse(
onDone: (success: boolean) => void,
): AbortController {
const controller = new AbortController();
const url = getApiUrl(path);
const token = getAuthToken();

fetch(url, {
requestStream(path, {
method: "POST",
headers: {
...(token ? { Authorization: `Bearer ${token}` } : {}),
},
signal: controller.signal,
})
.then(async (res) => {
if (!res.ok || !res.body) {
onDone(false);
return;
}
const reader = res.body.getReader();
const decoder = new TextDecoder();
let buffer = "";
Expand Down Expand Up @@ -87,8 +85,11 @@ function streamBrowserSse(
}
onDone(false);
})
.catch(() => {
if (!controller.signal.aborted) onDone(false);
.catch((error: unknown) => {
if (!controller.signal.aborted) {
onLog(apiErrorMessage(error, "Request failed", i18n.t));
onDone(false);
}
});

return controller;
Expand Down
16 changes: 8 additions & 8 deletions dashboard/src/api/modules/decision.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { requestStream } from "../request";
import { apiErrorMessage } from "../../utils/apiError";
import i18n from "../../i18n";
import { getApiUrl } from "../config";
import { getAuthToken, request } from "../request";

export type DecisionProvider = "laya" | "jev" | "microsoft" | "custom";
Expand Down Expand Up @@ -72,7 +73,7 @@ function streamLayaInstall(
): AbortController {
const controller = new AbortController();
const token = getAuthToken();
fetch(getApiUrl("/settings/decision/laya/install"), {
requestStream("/settings/decision/laya/install", {
method: "POST",
headers: {
...(token ? { Authorization: `Bearer ${token}` } : {}),
Expand All @@ -81,10 +82,6 @@ function streamLayaInstall(
signal: controller.signal,
})
.then(async (res) => {
if (!res.ok || !res.body) {
onDone(false);
return;
}
const reader = res.body.getReader();
const decoder = new TextDecoder();
let buffer = "";
Expand Down Expand Up @@ -117,8 +114,11 @@ function streamLayaInstall(
}
onDone(false);
})
.catch(() => {
if (!controller.signal.aborted) onDone(false);
.catch((error: unknown) => {
if (!controller.signal.aborted) {
onLog(apiErrorMessage(error, "Request failed", i18n.t));
onDone(false);
}
});
return controller;
}
Expand Down
18 changes: 9 additions & 9 deletions dashboard/src/api/modules/desktop.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
import { getApiUrl } from "../config";
import i18n from "../../i18n";
import { requestStream } from "../request";
import { apiErrorMessage } from "../../utils/apiError";
import { request, getAuthToken } from "../request";

export interface DesktopStatusResponse {
Expand All @@ -24,21 +26,16 @@ function streamDesktopSse(
onDone: (success: boolean) => void,
): AbortController {
const controller = new AbortController();
const url = getApiUrl(path);
const token = getAuthToken();

fetch(url, {
requestStream(path, {
method: "POST",
headers: {
...(token ? { Authorization: `Bearer ${token}` } : {}),
},
signal: controller.signal,
})
.then(async (res) => {
if (!res.ok || !res.body) {
onDone(false);
return;
}
const reader = res.body.getReader();
const decoder = new TextDecoder();
let buffer = "";
Expand Down Expand Up @@ -78,8 +75,11 @@ function streamDesktopSse(
}
onDone(false);
})
.catch(() => {
if (!controller.signal.aborted) onDone(false);
.catch((error: unknown) => {
if (!controller.signal.aborted) {
onLog(apiErrorMessage(error, "Request failed", i18n.t));
onDone(false);
}
});

return controller;
Expand Down
5 changes: 5 additions & 0 deletions dashboard/src/api/modules/mobile.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,11 @@ import { afterEach, describe, expect, it, vi } from "vitest";

vi.mock("../request", () => ({
request: vi.fn(),
requestStream: async (path: string, options: RequestInit) => {
const response = await fetch(`/api${path}`, options);
if (!response.ok) throw new Error(`HTTP ${response.status}`);
return { body: response.body, contentType: "text/event-stream" };
},
getAuthToken: () => "test-token",
}));

Expand Down
13 changes: 5 additions & 8 deletions dashboard/src/api/modules/mobile.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import i18n from "../../i18n";
import { requestStream } from "../request";
import { apiErrorMessage } from "../../utils/apiError";
import { request, getAuthToken } from "../request";
import { getApiUrl } from "../config";

export type MobileSetupState =
| "needs_device"
Expand Down Expand Up @@ -33,7 +35,6 @@ function streamMobileSse(
onDone: (ok: boolean, error?: string) => void,
): AbortController {
const controller = new AbortController();
const url = getApiUrl(path);
const token = getAuthToken();

// ``onDone`` is the only thing that moves the caller out of its "installing"
Expand All @@ -50,18 +51,14 @@ function streamMobileSse(
onDone(ok, error);
};

fetch(url, {
requestStream(path, {
method: "POST",
headers: {
...(token ? { Authorization: `Bearer ${token}` } : {}),
},
signal: controller.signal,
})
.then(async (res) => {
if (!res.ok || !res.body) {
settle(false, `HTTP ${res.status}`);
return;
}
const reader = res.body.getReader();
const decoder = new TextDecoder();
let buffer = "";
Expand Down Expand Up @@ -98,7 +95,7 @@ function streamMobileSse(
})
.catch((err: unknown) => {
if ((err as Error).name !== "AbortError") {
settle(false, String(err));
settle(false, apiErrorMessage(err, "Request failed", i18n.t));
}
});
return controller;
Expand Down
13 changes: 13 additions & 0 deletions dashboard/src/api/request.setup.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -93,4 +93,17 @@ describe("setup lockdown handling", () => {
);
expect(replace).not.toHaveBeenCalled();
});
it("bounds a non-setup 503 without cloning or displaying its HTML", async () => {
const response = new Response("<html>private diagnostics</html>", {
status: 503,
headers: { "x-request-id": "trace-503" },
});
const clone = vi.spyOn(response, "clone");
fetchMock.mockResolvedValueOnce(response);
await expect(mod.request("/agents")).rejects.toThrow(
"HTTP 503 (Request ID: trace-503)",
);
expect(clone).not.toHaveBeenCalled();
expect(mod.isSetupRequiredKnown()).toBe(false);
});
});
64 changes: 30 additions & 34 deletions dashboard/src/api/request.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,8 @@
import {
ApiResponseError,
readErrorBody,
responseError,
} from "./responseError";
import { getApiUrl } from "./config";
import {
isLocalDesktopUser,
Expand Down Expand Up @@ -173,7 +178,7 @@ async function check503ForSetupRequired(
if (response.status !== 503) return false;
let body: unknown = null;
try {
body = await response.clone().json();
body = await readErrorBody(response);
} catch {
/* not JSON — fall through to the standard error path. */
return false;
Expand Down Expand Up @@ -374,7 +379,7 @@ async function throwIfUnauthorized(
let message = "Unauthorized";
if (path.startsWith("/setup/")) {
try {
const body = (await response.clone().json()) as {
const body = (await readErrorBody(response)) as {
error?: { message?: string };
};
if (body?.error?.message) {
Expand Down Expand Up @@ -458,12 +463,7 @@ export async function request<T = unknown>(
new CustomEvent(FORBIDDEN_EVENT, { detail: { path } }),
);
}
const text = await response.text().catch(() => "");
throw new Error(
`Request failed: ${response.status} ${response.statusText}${
text ? ` - ${text}` : ""
}`,
);
throw await responseError(response);
}

if (response.status === 204) {
Expand Down Expand Up @@ -507,12 +507,7 @@ export async function requestBlob(
applyRenewedAccessToken(response);

if (!response.ok) {
const text = await response.text().catch(() => "");
throw new Error(
`Request failed: ${response.status} ${response.statusText}${
text ? ` - ${text}` : ""
}`,
);
throw await responseError(response);
}

const total = Number(response.headers.get("content-length")) || 0;
Expand Down Expand Up @@ -560,12 +555,7 @@ export async function probeAuthResource(
applyRenewedAccessToken(response);

if (!response.ok) {
const text = await response.text().catch(() => "");
throw new Error(
`Request failed: ${response.status} ${response.statusText}${
text ? ` - ${text}` : ""
}`,
);
throw await responseError(response);
}

try {
Expand Down Expand Up @@ -600,12 +590,7 @@ export async function requestStream(
applyRenewedAccessToken(response);

if (!response.ok) {
const text = await response.text().catch(() => "");
throw new Error(
`Request failed: ${response.status} ${response.statusText}${
text ? ` - ${text}` : ""
}`,
);
throw await responseError(response);
}

if (!response.body) {
Expand Down Expand Up @@ -677,11 +662,29 @@ export async function requestUpload<T = unknown>(
);
}

xhr.onprogress = (event) => {
if (xhr.status >= 400 && event.loaded > 16 * 1024) {
const requestId =
xhr.getResponseHeader("x-request-id") ??
xhr.getResponseHeader("x-octop-request-id");
reject(new ApiResponseError(xhr.status, null, requestId));
xhr.abort();
}
};

xhr.onload = () => {
void (async () => {
const status = xhr.status;
const responseText = xhr.responseText;
const responseHeaders = new Headers();
for (const key of [
"content-type",
"x-request-id",
"x-octop-request-id",
]) {
const value = xhr.getResponseHeader(key);
if (value) responseHeaders.set(key, value);
}
const renewed = xhr.getResponseHeader(ACCESS_TOKEN_RESPONSE_HEADER);
if (renewed) {
responseHeaders.set(ACCESS_TOKEN_RESPONSE_HEADER, renewed);
Expand All @@ -706,14 +709,7 @@ export async function requestUpload<T = unknown>(
applyRenewedAccessToken(response);

if (!response.ok) {
// Same shape as request() so parseApiError() can read the error envelope.
reject(
new Error(
`Upload failed: ${status}${
responseText ? ` - ${responseText}` : ""
}`,
),
);
reject(await responseError(response));
return;
}

Expand Down
5 changes: 4 additions & 1 deletion dashboard/src/api/request.unauthorized.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -118,7 +118,10 @@ describe("401 handling", () => {

await expect(
mod.request("/bridge/probe", { method: "POST" }),
).rejects.toThrow(/BRIDGE_AUTH_FAILED/);
).rejects.toMatchObject({
message: "peer rejected credentials",
apiError: { code: "BRIDGE_AUTH_FAILED" },
});

expect(replace).not.toHaveBeenCalled();
expect(mod.getAuthToken()).toBe("expired-token");
Expand Down
Loading
Loading