返回 DeepSeek-Reasonix
protocol.test.ts
根目录 / desktop / electron / src / main / protocol.test.ts
1 import assert from "node:assert/strict";
2 import { mkdirSync, mkdtempSync, rmSync, statSync, writeFileSync } from "node:fs";
3 import { tmpdir } from "node:os";
4 import { join } from "node:path";
5 import { after, before, test } from "node:test";
6 import { isForwardedPath, registerAppProtocol, resolveDistRoot, routeAppRequest } from "./protocol.js";
7
8 let dist = "";
9 const isFile = (path: string) => {
10 try {
11 return statSync(path).isFile();
12 } catch {
13 return false;
14 }
15 };
16 const route = (url: string) => routeAppRequest(url, dist, isFile);
17
18 test("normal app documents do not pre-enable a profiling engine", async () => {
19 let handler!: (request: Request) => Promise<Response> | Response;
20 registerAppProtocol({
21 protocol: { handle: (_scheme, callback) => { handler = callback; } },
22 fetch: async () => new Response("forwarded"), distRoot: dist, resources: () => null,
23 log: { info() {}, warn() {}, error() {} },
24 });
25 const response = await handler(new Request("reasonix://app/"));
26 assert.equal(response.headers.get("Document-Policy"), null);
27 await response.text();
28 });
29
30 before(() => {
31 dist = mkdtempSync(join(tmpdir(), "reasonix-dist-"));
32 mkdirSync(join(dist, "assets"), { recursive: true });
33 writeFileSync(join(dist, "index.html"), "<!doctype html>");
34 writeFileSync(join(dist, "assets", "app.js"), "export {};");
35 writeFileSync(join(dist, "assets", "styles.css"), "body{}");
36 writeFileSync(join(dist, "assets", "font.woff2"), "");
37 });
38
39 after(() => rmSync(dist, { recursive: true, force: true }));
40
41 test("the root and existing files under dist are served with their MIME types", () => {
42 assert.deepEqual(route("reasonix://app/"), { kind: "file", path: join(dist, "index.html"), mime: "text/html; charset=utf-8" });
43 assert.deepEqual(route("reasonix://app"), { kind: "file", path: join(dist, "index.html"), mime: "text/html; charset=utf-8" });
44 assert.deepEqual(route("reasonix://app/index.html?boot=1"), { kind: "file", path: join(dist, "index.html"), mime: "text/html; charset=utf-8" });
45 assert.deepEqual(route("reasonix://app/assets/app.js"), { kind: "file", path: join(dist, "assets", "app.js"), mime: "text/javascript; charset=utf-8" });
46 assert.equal(route("reasonix://app/assets/styles.css").kind, "file");
47 assert.equal((route("reasonix://app/assets/font.woff2") as { mime: string }).mime, "font/woff2");
48 });
49
50 test("index.html is not a fallback for other paths", () => {
51 assert.equal(route("reasonix://app/settings").kind, "notFound");
52 assert.equal(route("reasonix://app/assets/").kind, "notFound");
53 assert.equal(route("reasonix://app/assets/missing.js").kind, "notFound");
54 });
55
56 test("traversal, absolute escapes and odd hosts are rejected", () => {
57 // The WHATWG parser collapses literal and %2e-encoded dot segments before
58 // routing, exactly as Chromium does for a standard scheme, so these can only
59 // land inside dist; the encoded-slash and backslash forms must still fail.
60 assert.equal(route("reasonix://app/../index.html").kind, "file");
61 assert.equal(route("reasonix://app/%2e%2e/index.html").kind, "file");
62 assert.equal(route("reasonix://app/assets/../../etc/passwd").kind, "notFound");
63 assert.equal(route("reasonix://app/assets/%2e%2e/%2e%2e/etc/passwd").kind, "notFound");
64 for (const url of [
65 "reasonix://app//etc/passwd",
66 "reasonix://app/assets/..%2Fapp.js",
67 "reasonix://app/assets%5Capp.js",
68 "reasonix://app/%00",
69 "reasonix://evil/index.html",
70 "http://app/index.html",
71 "not a url",
72 ]) {
73 assert.equal(route(url).kind, "notFound", url);
74 }
75 });
76
77 test("only the resource prefixes forward to the loopback origin, query included", () => {
78 assert.deepEqual(route("reasonix://app/__reasonix_workspace_media/tok/a.png"), { kind: "forward", target: "/__reasonix_workspace_media/tok/a.png" });
79 assert.deepEqual(route("reasonix://app/__reasonix_theme_asset/x.jpg?v=2"), { kind: "forward", target: "/__reasonix_theme_asset/x.jpg?v=2" });
80 assert.deepEqual(route("reasonix://app/__reasonix_remote_markdown_image?url=https%3A%2F%2Fx"), {
81 kind: "forward",
82 target: "/__reasonix_remote_markdown_image?url=https%3A%2F%2Fx",
83 });
84 assert.equal(isForwardedPath("/__reasonix_remote_markdown_imagex"), false);
85 assert.equal(isForwardedPath("/__reasonix_workspace_media"), false);
86 assert.equal(route("reasonix://app/__shell/quit").kind, "notFound");
87 });
88
89 test("attachment uploads forward only the exact upload route, preserving the filename and target", () => {
90 const query = "?target=chat%2Fsession&name=large%20app.apk";
91 assert.deepEqual(route(`reasonix://app/__reasonix_attachment_upload${query}`), {
92 kind: "forward",
93 target: `/__reasonix_attachment_upload${query}`,
94 });
95 for (const path of ["/__reasonix_attachment_upload/", "/__reasonix_attachment_upload/extra", "/__reasonix_attachment_uploadx"]) {
96 assert.equal(isForwardedPath(path), false, path);
97 assert.equal(route(`reasonix://app${path}`).kind, "notFound", path);
98 }
99 });
100
101 test("upload forwarding delivers chunks before the source finishes and preserves cancellation", async () => {
102 let handler!: (request: Request) => Promise<Response> | Response;
103 let source!: ReadableStreamDefaultController<Uint8Array>;
104 const chunks = [new Uint8Array([0x50, 0x4b, 0x03, 0x04]), new Uint8Array([0, 255, 128, 1])];
105 const stream = new ReadableStream<Uint8Array>({
106 start(controller) {
107 source = controller;
108 controller.enqueue(chunks[0]);
109 },
110 });
111 const controller = new AbortController();
112 const query = "?target=chat%2Fsession&name=large%20app.apk";
113 const request = new Request(`reasonix://app/__reasonix_attachment_upload${query}`, {
114 method: "POST",
115 headers: {
116 "content-type": "application/octet-stream",
117 authorization: "Bearer renderer-controlled",
118 cookie: "private=value",
119 origin: "https://untrusted.example",
120 "x-untrusted": "not-forwarded",
121 },
122 body: stream,
123 signal: controller.signal,
124 duplex: "half",
125 } as RequestInit);
126 // Reading through any whole-body convenience method would recreate the
127 // large-file allocation that this transport is intended to avoid.
128 request.arrayBuffer = async () => { throw new Error("upload was buffered with arrayBuffer()"); };
129 request.text = async () => { throw new Error("upload was buffered with text()"); };
130 request.blob = async () => { throw new Error("upload was buffered with blob()"); };
131 let forwarded = false;
132 registerAppProtocol({
133 protocol: { handle: (_scheme, callback) => { handler = callback; } },
134 fetch: async (input, init) => {
135 forwarded = true;
136 assert.equal(input, `http://127.0.0.1:12345/__reasonix_attachment_upload${query}`);
137 assert.equal(init.method, "POST");
138 assert.equal(init.body, request.body);
139 assert.equal((init as RequestInit & { duplex?: string }).duplex, "half");
140 assert.equal(init.signal, request.signal);
141 assert.equal(init.bypassCustomProtocolHandlers, true);
142 const headers = new Headers(init.headers);
143 assert.equal(headers.get("authorization"), "Bearer server-secret");
144 assert.equal(headers.get("content-type"), "application/octet-stream");
145 for (const name of ["cookie", "origin", "x-untrusted"]) assert.equal(headers.get(name), null, name);
146
147 const reader = (init.body as ReadableStream<Uint8Array>).getReader();
148 assert.deepEqual(await reader.read(), { done: false, value: chunks[0] });
149 // The final chunk does not exist until the origin has received the first.
150 // Aggregating the body before forwarding cannot complete this exchange.
151 source.enqueue(chunks[1]);
152 source.close();
153 assert.deepEqual(await reader.read(), { done: false, value: chunks[1] });
154 assert.equal((await reader.read()).done, true);
155 controller.abort();
156 assert.equal(init.signal?.aborted, true);
157 return new Response('{"name":"large app.apk"}', { status: 201, headers: { "content-type": "application/json" } });
158 },
159 distRoot: dist,
160 resources: () => ({ origin: "http://127.0.0.1:12345", token: "server-secret" }),
161 log: { info() {}, warn() {}, error() {} },
162 });
163 const response = await handler(request);
164 assert.equal(forwarded, true, "the upload must reach the resource origin");
165 assert.equal(response.status, 201);
166 assert.deepEqual(await response.json(), { name: "large app.apk" });
167 });
168
169 test("upload routes reject methods other than POST and unsupported body formats", async () => {
170 let handler!: (request: Request) => Promise<Response> | Response;
171 let forwarded = 0;
172 registerAppProtocol({
173 protocol: { handle: (_scheme, callback) => { handler = callback; } },
174 fetch: async () => { forwarded++; return new Response("unexpected forward"); },
175 distRoot: dist,
176 resources: () => ({ origin: "http://127.0.0.1:12345", token: "server-secret" }),
177 log: { info() {}, warn() {}, error() {} },
178 });
179 for (const method of ["GET", "HEAD", "PUT", "PATCH", "DELETE"]) {
180 const response = await handler(new Request("reasonix://app/__reasonix_attachment_upload?name=large.apk", { method }));
181 assert.equal(response.status, 405, method);
182 }
183 for (const contentType of ["application/json", "multipart/form-data; boundary=test", "text/plain"]) {
184 const response = await handler(new Request("reasonix://app/__reasonix_attachment_upload?name=large.apk", {
185 method: "POST", headers: { "content-type": contentType }, body: "not raw bytes",
186 }));
187 assert.equal(response.status, 415, contentType);
188 }
189 assert.equal(forwarded, 0);
190 });
191
192 test("asset routes cannot be used to forward writes or request bodies", async () => {
193 let handler!: (request: Request) => Promise<Response> | Response;
194 let forwarded = 0;
195 registerAppProtocol({
196 protocol: { handle: (_scheme, callback) => { handler = callback; } },
197 fetch: async () => { forwarded++; return new Response("unexpected forward"); },
198 distRoot: dist,
199 resources: () => ({ origin: "http://127.0.0.1:12345", token: "server-secret" }),
200 log: { info() {}, warn() {}, error() {} },
201 });
202 for (const path of ["/__reasonix_workspace_media/token/a.png", "/__reasonix_theme_asset/a.png", "/__reasonix_remote_markdown_image?url=https%3A%2F%2Fexample.com%2Fa.png", "/assets/app.js"]) {
203 for (const method of ["POST", "PUT", "PATCH", "DELETE"]) {
204 const response = await handler(new Request(`reasonix://app${path}`, { method, body: "must not reach the origin" }));
205 assert.equal(response.status, 405, `${method} ${path}`);
206 }
207 }
208 assert.equal(forwarded, 0);
209 });
210
211 test("the dist root honours the override, then packaging layout", () => {
212 assert.equal(resolveDistRoot({ env: { REASONIX_FRONTEND_DIST: "/tmp/dist" }, appPath: "/app/electron", resourcesPath: "/res", packaged: true }), "/tmp/dist");
213 assert.equal(resolveDistRoot({ env: {}, appPath: "/app/electron", resourcesPath: "/res", packaged: false }), "/app/frontend/dist");
214 assert.equal(resolveDistRoot({ env: {}, appPath: "/app/electron", resourcesPath: "/res", packaged: true }), "/res/app");
215 });
216
216 lines TYPESCRIPT