Skip to content

An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作

:bug: Handle remote kernel authentication redirects https://github.com/siyuan-note/siyuan/issues/19201

Daniele6a63fc0ea6f
diff --git a/app/electron/main.js b/app/electron/main.js
index 31d18da204..7078f5cf23 100644
--- a/app/electron/main.js
+++ b/app/electron/main.js
@@ -42,6 +42,7 @@ const {pathToFileURL} = require("url");
const gNet = require("net");
const childProcess = require("child_process");
const remote = require("@electron/remote/main");
+const {probeRemoteKernelAuthentication} = require("./remoteKernelAuth");
const {
rawFormatType, readClipboardBuffer, readClipboardText, getClipboardFormats, parseClipboardFilePaths
} = require("./clipboard");
@@ -1415,25 +1416,8 @@ const installRemoteFrontendProtocol = (target) => {
}
if (localDocumentRequest &&
["/stage/build/app/", "/stage/build/app/window.html"].includes(requestURL.pathname)) {
- const authenticationResponse = await session.defaultSession.fetch(request, {
- bypassCustomProtocolHandlers: true,
- credentials: "include",
- redirect: "manual",
- });
- await authenticationResponse.body?.cancel();
- if (!authenticationResponse.ok) {
- const responseLocation = authenticationResponse.headers.get("location");
- let authenticationRequired = authenticationResponse.status === 401;
- if (responseLocation && authenticationResponse.status >= 300 && authenticationResponse.status < 400) {
- try {
- const redirectURL = new URL(responseLocation, target.origin);
- authenticationRequired = redirectURL.origin === target.origin &&
- redirectURL.pathname === "/check-auth";
- } catch (error) {
- authenticationRequired = false;
- }
- }
- if (authenticationRequired) {
+ try {
+ if (!await probeRemoteKernelAuthentication(net, session.defaultSession, requestURL.href)) {
const authURL = new URL("/check-auth", target.origin);
authURL.searchParams.set("to", requestURL.pathname + requestURL.search);
authURL.searchParams.set("lang", resolveAppLanguage(app.getPreferredSystemLanguages()));
@@ -1446,8 +1430,10 @@ const installRemoteFrontendProtocol = (target) => {
},
});
}
+ } catch (error) {
+ writeLog("probe remote kernel authentication before loading local UI failed: " + error.message);
return new Response("Remote kernel UI probe failed.", {
- status: authenticationResponse.status >= 400 ? authenticationResponse.status : 502,
+ status: error.statusCode >= 400 && error.statusCode <= 599 ? error.statusCode : 502,
headers: {
"Cache-Control": "no-store",
"Content-Type": "text/plain; charset=utf-8",
@@ -2587,22 +2573,8 @@ const requestRemoteKernelVersion = async (target) => {
return response.json();
};
-const isRemoteKernelAuthenticated = async (target) => {
- const response = await fetchWithTimeout(target.origin + "/stage/build/app/", {
- method: "GET",
- redirect: "manual",
- });
- if (response.status === 401 || response.status >= 300 && response.status < 400) {
- await response.body?.cancel();
- return false;
- }
- if (!response.ok) {
- await response.body?.cancel();
- throw new Error("authentication probe returned HTTP " + response.status);
- }
- await response.body?.cancel();
- return true;
-};
+const isRemoteKernelAuthenticated = (target) =>
+ probeRemoteKernelAuthentication(net, session.defaultSession, target.origin + "/stage/build/app/");
const initRemoteKernel = async (target) => {
createBootWindow();
diff --git a/app/electron/remoteKernelAuth.js b/app/electron/remoteKernelAuth.js
new file mode 100644
index 0000000000..a73b9cb20c
--- /dev/null
+++ b/app/electron/remoteKernelAuth.js
@@ -0,0 +1,64 @@
+// 使用会话 Cookie 探测鉴权状态,在重定向事件中判断登录页并终止请求。
+const probeRemoteKernelAuthentication = (net, session, url, timeout = 5000) => new Promise((resolve, reject) => {
+ const origin = new URL(url).origin;
+ const request = net.request({
+ url,
+ method: "GET",
+ session,
+ credentials: "include",
+ bypassCustomProtocolHandlers: true,
+ cache: "no-store",
+ redirect: "manual",
+ });
+ let settled = false;
+ const finish = (error, authenticated) => {
+ if (settled) {
+ return;
+ }
+ settled = true;
+ clearTimeout(timer);
+ if (error) {
+ reject(error);
+ } else {
+ resolve(authenticated);
+ }
+ request.abort();
+ };
+ const timer = setTimeout(() => finish(new Error("authentication probe timed out")), timeout);
+ request.on("error", (error) => finish(error));
+ request.on("redirect", (status, method, location) => {
+ try {
+ const redirectURL = new URL(location, url);
+ if (redirectURL.origin === origin && !redirectURL.username && !redirectURL.password &&
+ redirectURL.pathname === "/check-auth") {
+ finish(null, false);
+ return;
+ }
+ } catch (error) {
+ finish(error);
+ return;
+ }
+ finish(new Error("authentication probe returned an unexpected redirect [HTTP " + status +
+ ", method=" + method + "]"));
+ });
+ request.on("response", (response) => {
+ response.on("error", (error) => finish(error));
+ const status = response.statusCode;
+ if (status === 401) {
+ finish(null, false);
+ } else if (status >= 200 && status < 300) {
+ finish(null, true);
+ } else {
+ const error = new Error("authentication probe returned HTTP " + status);
+ error.statusCode = status;
+ finish(error);
+ }
+ });
+ try {
+ request.end();
+ } catch (error) {
+ finish(error);
+ }
+});
+
+module.exports = {probeRemoteKernelAuthentication};
diff --git a/app/electron/remoteKernelAuth.test.js b/app/electron/remoteKernelAuth.test.js
new file mode 100644
index 0000000000..b15d6c92ce
--- /dev/null
+++ b/app/electron/remoteKernelAuth.test.js
@@ -0,0 +1,103 @@
+const assert = require("node:assert/strict");
+const {probeRemoteKernelAuthentication} = require("./remoteKernelAuth");
+
+if (!process.versions.electron) {
+ const {test} = require("node:test");
+ const {execFile} = require("node:child_process");
+ const {promisify} = require("node:util");
+ const fs = require("node:fs");
+ const os = require("node:os");
+ const path = require("node:path");
+
+ test("remote authentication probes use Electron redirects and session cookies", async () => {
+ const profile = fs.mkdtempSync(path.join(os.tmpdir(), "siyuan-auth-test-"));
+ const env = {...process.env};
+ delete env.ELECTRON_RUN_AS_NODE;
+ try {
+ const {stdout} = await promisify(execFile)(require("electron"), [__filename, profile], {
+ env,
+ timeout: 60000,
+ windowsHide: true,
+ });
+ assert.match(stdout, /Authentication probes passed/);
+ } finally {
+ fs.rmSync(profile, {recursive: true, force: true, maxRetries: 5, retryDelay: 200});
+ }
+ });
+} else {
+ const {app, net, session} = require("electron");
+ const http = require("node:http");
+ app.setPath("userData", process.argv[2]);
+ app.disableHardwareAcceleration();
+ app.whenReady().then(async () => {
+ let loginRequests = 0;
+ const server = http.createServer((request, response) => {
+ const url = new URL(request.url, "http://localhost");
+ if (url.pathname === "/timeout") {
+ return;
+ }
+ if (url.pathname === "/disconnect") {
+ request.socket.destroy();
+ return;
+ }
+ if (url.pathname === "/redirect") {
+ response.writeHead(Number(url.searchParams.get("status") || 302), {
+ Location: url.searchParams.get("to") || "/check-auth",
+ });
+ } else if (url.pathname === "/check-auth") {
+ loginRequests++;
+ } else if (url.pathname === "/session") {
+ if (request.headers.cookie !== "auth=valid") {
+ response.writeHead(302, {Location: "/check-auth?to=/session"});
+ }
+ } else {
+ response.writeHead(Number(url.searchParams.get("status") || 200));
+ }
+ response.end("probe");
+ });
+ await new Promise(resolve => server.listen(0, "127.0.0.1", resolve));
+ const origin = "http://127.0.0.1:" + server.address().port;
+ const probe = (pathname, timeout) =>
+ probeRemoteKernelAuthentication(net, session.defaultSession, origin + pathname, timeout);
+ try {
+ assert.equal(await probe("/"), true);
+ assert.equal(await probe("/?status=204"), true);
+ assert.equal(await probe("/?status=401"), false);
+ for (const status of [301, 302, 303, 307, 308]) {
+ assert.equal(await probe("/redirect?status=" + status), false);
+ }
+ for (const target of ["/other", "https://example.com/check-auth", "/redirect",
+ origin.replace("http://", "http://user:password@") + "/check-auth"]) {
+ await assert.rejects(probe("/redirect?to=" + encodeURIComponent(target)), /unexpected redirect/);
+ }
+ for (const status of [403, 404, 500, 503]) {
+ await assert.rejects(probe("/?status=" + status), {statusCode: status});
+ }
+ assert.equal(await probe("/session"), false);
+ await session.defaultSession.cookies.set({url: origin, name: "auth", value: "valid"});
+ assert.equal(await probe("/session"), true);
+ await session.defaultSession.cookies.remove(origin, "auth");
+ assert.equal(await probe("/session"), false);
+ assert.equal(loginRequests, 0);
+ session.defaultSession.protocol.handle("http", () => {
+ throw new Error("authentication probe must bypass the frontend protocol");
+ });
+ assert.equal(await probe("/"), true);
+ assert.equal(await probe("/redirect"), false);
+ await assert.rejects(probe("/timeout", 100), /timed out/);
+ await assert.rejects(probe("/disconnect"));
+ session.defaultSession.protocol.unhandle("http");
+ server.closeAllConnections();
+ await new Promise(resolve => server.close(resolve));
+ await assert.rejects(probe("/"));
+ console.log("Authentication probes passed");
+ app.exit(0);
+ } catch (error) {
+ console.error(error);
+ app.exit(1);
+ }
+ }).catch((error) => {
+ console.error(error);
+ app.exit(1);
+ });
+}