返回 DeepSeek-Reasonix
protocol.ts
根目录 / desktop / electron / src / main / protocol.ts
1 import { createReadStream, statSync } from "node:fs";
2 import { extname, join, resolve, sep } from "node:path";
3 import { Readable } from "node:stream";
4 import { errorText, type Logger } from "./log.js";
5
6 export const APP_SCHEME = "reasonix";
7 export const APP_ORIGIN = "reasonix://app";
8 export const APP_INDEX_URL = "reasonix://app/index.html";
9
10 // Must match desktop/workspace_media.go, desktop/theme_assets.go and
11 // desktop/remote_markdown_image.go; only these reach the resource origin.
12 export const FORWARDED_PATHS = [
13 "/__reasonix_workspace_media/",
14 "/__reasonix_theme_asset/",
15 "/__reasonix_remote_markdown_image",
16 ] as const;
17
18 const ATTACHMENT_UPLOAD_PATH = "/__reasonix_attachment_upload";
19
20 export type AppRoute =
21 | { kind: "file"; path: string; mime: string }
22 | { kind: "forward"; target: string }
23 | { kind: "notFound"; reason: string };
24
25 const MIME: Record<string, string> = {
26 ".html": "text/html; charset=utf-8",
27 ".js": "text/javascript; charset=utf-8",
28 ".mjs": "text/javascript; charset=utf-8",
29 ".css": "text/css; charset=utf-8",
30 ".json": "application/json; charset=utf-8",
31 ".map": "application/json; charset=utf-8",
32 ".webmanifest": "application/manifest+json",
33 ".svg": "image/svg+xml",
34 ".png": "image/png",
35 ".jpg": "image/jpeg",
36 ".jpeg": "image/jpeg",
37 ".gif": "image/gif",
38 ".webp": "image/webp",
39 ".ico": "image/x-icon",
40 ".woff": "font/woff",
41 ".woff2": "font/woff2",
42 ".ttf": "font/ttf",
43 ".txt": "text/plain; charset=utf-8",
44 ".wasm": "application/wasm",
45 ".mp3": "audio/mpeg",
46 ".ogg": "audio/ogg",
47 ".wav": "audio/wav",
48 ".mp4": "video/mp4",
49 ".webm": "video/webm",
50 };
51
52 export function mimeFor(path: string): string {
53 return MIME[extname(path).toLowerCase()] ?? "application/octet-stream";
54 }
55
56 export function isForwardedPath(pathname: string): boolean {
57 return pathname === ATTACHMENT_UPLOAD_PATH || FORWARDED_PATHS.some((prefix) =>
58 prefix.endsWith("/") ? pathname.startsWith(prefix) : pathname === prefix || pathname.startsWith(prefix + "/"));
59 }
60
61 const notFound = (reason: string): AppRoute => ({ kind: "notFound", reason });
62
63 export function routeAppRequest(rawURL: string, distRoot: string, isFile: (path: string) => boolean): AppRoute {
64 let url: URL;
65 try {
66 url = new URL(rawURL);
67 } catch {
68 return notFound("malformed URL");
69 }
70 if (url.protocol !== `${APP_SCHEME}:`) return notFound("unsupported scheme");
71 if (url.host !== "app") return notFound("unknown host");
72 if (isForwardedPath(url.pathname)) return { kind: "forward", target: url.pathname + url.search };
73 let decoded: string;
74 try {
75 decoded = decodeURIComponent(url.pathname);
76 } catch {
77 return notFound("malformed path");
78 }
79 if (decoded.includes("\0") || decoded.includes("\\")) return notFound("illegal characters");
80 const pathname = decoded === "/" || decoded === "" ? "/index.html" : decoded;
81 const segments = pathname.split("/").slice(1);
82 if (segments.some((segment) => segment === "" || segment === "." || segment === "..")) return notFound("path traversal");
83 const root = resolve(distRoot);
84 const file = join(root, ...segments);
85 if (!file.startsWith(root + sep)) return notFound("outside dist root");
86 if (!isFile(file)) return notFound("no such file");
87 return { kind: "file", path: file, mime: mimeFor(file) };
88 }
89
90 export function resolveDistRoot(input: { env: NodeJS.ProcessEnv; appPath: string; resourcesPath: string; packaged: boolean }): string {
91 const override = (input.env.REASONIX_FRONTEND_DIST ?? "").trim();
92 if (override !== "") return resolve(override);
93 return input.packaged ? join(input.resourcesPath, "app") : resolve(input.appPath, "..", "frontend", "dist");
94 }
95
96 export interface ResourceOrigin {
97 origin: string;
98 token: string;
99 }
100
101 export interface AppProtocolDeps {
102 protocol: { handle(scheme: string, handler: (request: Request) => Promise<Response> | Response): void };
103 fetch(input: string, init: RequestInit & { bypassCustomProtocolHandlers?: boolean }): Promise<Response>;
104 distRoot: string;
105 resources(): ResourceOrigin | null;
106 log: Logger;
107 }
108
109 const FORWARDED_REQUEST_HEADERS = ["accept", "range", "if-none-match", "if-modified-since"];
110
111 function fileExists(path: string): boolean {
112 try {
113 return statSync(path).isFile();
114 } catch {
115 return false;
116 }
117 }
118
119 function text(status: number, body: string): Response {
120 return new Response(body, { status, headers: { "content-type": "text/plain; charset=utf-8" } });
121 }
122
123 export function registerAppProtocol(deps: AppProtocolDeps): void {
124 deps.protocol.handle(APP_SCHEME, async (request) => {
125 const route = routeAppRequest(request.url, deps.distRoot, fileExists);
126 if (route.kind === "notFound") {
127 deps.log.warn(`404 ${request.url}: ${route.reason}`);
128 return text(404, "Not found");
129 }
130 const upload = new URL(request.url).pathname === ATTACHMENT_UPLOAD_PATH;
131 if (upload ? request.method !== "POST" : request.method !== "GET" && request.method !== "HEAD") {
132 return text(405, "Method not allowed");
133 }
134 if (upload && request.headers.get("content-type") !== "application/octet-stream") return text(415, "Unsupported upload type");
135 if (route.kind === "forward") {
136 const resources = deps.resources();
137 if (!resources) return text(503, "Desktop service unavailable");
138 const headers = new Headers({ authorization: `Bearer ${resources.token}` });
139 for (const name of FORWARDED_REQUEST_HEADERS) {
140 const value = request.headers.get(name);
141 if (value) headers.set(name, value);
142 }
143 if (upload) headers.set("content-type", "application/octet-stream");
144 try {
145 const init: RequestInit & { bypassCustomProtocolHandlers?: boolean; duplex?: "half" } = {
146 method: request.method, headers, signal: request.signal, bypassCustomProtocolHandlers: true,
147 ...(upload ? { body: request.body, duplex: "half" as const } : {}),
148 };
149 return await deps.fetch(resources.origin + route.target, init);
150 } catch (error) {
151 deps.log.warn(`resource forward failed for ${new URL(request.url).pathname}: ${errorText(error)}`);
152 return text(502, "Resource origin unreachable");
153 }
154 }
155 const body = Readable.toWeb(createReadStream(route.path)) as unknown as ReadableStream;
156 return new Response(body, { status: 200, headers: { "content-type": route.mime, "cache-control": "no-cache" } });
157 });
158 }
159
159 lines TYPESCRIPT