-
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmain.ts
More file actions
468 lines (422 loc) · 14.3 KB
/
Copy pathmain.ts
File metadata and controls
468 lines (422 loc) · 14.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
import { app, BrowserWindow, ipcMain } from "electron";
import { ChildProcess, spawn } from "child_process";
import * as path from "path";
import * as http from "http";
import * as net from "net";
import * as crypto from "crypto";
let mainWindow: BrowserWindow | null = null;
let pythonProcess: ChildProcess | null = null;
let apiPort: number | null = null;
let staticServer: http.Server | null = null;
let staticRendererPort: number | null = null;
// Per-launch bearer token. Both the Python backend and Electron see it via
// PROTONSHIFT_API_TOKEN, and every renderer-originated fetch attaches it.
const apiToken = crypto.randomBytes(32).toString("base64url");
const isDev = !app.isPackaged;
import * as fs from "fs";
function pickFreePort(): Promise<number> {
return new Promise((resolve, reject) => {
const srv = net.createServer();
srv.unref();
srv.on("error", reject);
srv.listen(0, "127.0.0.1", () => {
const addr = srv.address();
if (addr && typeof addr === "object") {
const port = addr.port;
srv.close(() => resolve(port));
} else {
srv.close();
reject(new Error("Failed to bind ephemeral port"));
}
});
});
}
function findPythonCmd(projectRoot: string): string {
// Prefer the project venv if it exists (dev workflow)
const candidates = [
path.join(projectRoot, ".venv", "bin", "python3"),
path.join(projectRoot, ".venv", "bin", "python"),
"python3",
"python",
];
for (const c of candidates) {
if (c.startsWith("/") && fs.existsSync(c)) return c;
if (!c.startsWith("/")) return c; // fall back to PATH
}
return "python3";
}
const EXTRA_PATH_DIRS = [
"/usr/bin",
"/usr/local/bin",
"/var/usrlocal/bin",
"/usr/lib/extensions/vulkan/MangoHud/bin",
"/usr/lib64/extensions/vulkan/MangoHud/bin",
"/run/current-system/sw/bin", // NixOS
].join(":");
function getPythonCommand(port: number): { cmd: string; args: string[]; env: NodeJS.ProcessEnv } {
const env = { ...process.env };
// Packaged trees (especially AppImages) live on read-only mounts; bytecode
// writes beside shipped *.py would raise PermissionError and exit before /health.
if (!isDev) {
env.PYTHONDONTWRITEBYTECODE = "1";
}
// Immutable distros (Bazzite, SteamOS, Fedora Atomic) and AppImage
// wrappers can strip PATH entries. Ensure common locations are present.
if (env.PATH && !env.PATH.includes("/var/usrlocal/bin")) {
env.PATH = `${env.PATH}:${EXTRA_PATH_DIRS}`;
}
// Hand the backend the auth token. compare_digest on the Python side will
// reject any other Authorization header.
env.PROTONSHIFT_API_TOKEN = apiToken;
const portArg = String(port);
if (isDev) {
const projectRoot = path.resolve(__dirname, "..", "..");
const srcDir = path.join(projectRoot, "src");
env.PYTHONPATH = srcDir + (env.PYTHONPATH ? `:${env.PYTHONPATH}` : "");
return {
cmd: findPythonCmd(projectRoot),
args: ["-m", "game_setup_hub.api", "--port", portArg],
env,
};
}
const resourcesPath = process.resourcesPath;
const srcDir = path.join(resourcesPath, "python", "src");
const vendorDir = path.join(resourcesPath, "python", "vendor");
const bundledPython = path.join(resourcesPath, "python", "runtime", "bin", "python3");
const pyPathParts: string[] = [];
if (fs.existsSync(vendorDir)) {
pyPathParts.push(vendorDir);
}
pyPathParts.push(srcDir);
if (env.PYTHONPATH) {
pyPathParts.push(env.PYTHONPATH);
}
env.PYTHONPATH = pyPathParts.join(":");
// Prefer the bundled interpreter (python-build-standalone). It is ABI-locked
// to our vendored wheels, so pydantic_core etc. always loads cleanly.
if (fs.existsSync(bundledPython)) {
// Ignore any user-site noise from the host Python install — we own this
// interpreter and the wheels live entirely under /resources/python.
env.PYTHONNOUSERSITE = "1";
// Make the bundled libpython resolvable for any subprocess we exec.
const bundledLib = path.join(resourcesPath, "python", "runtime", "lib");
env.LD_LIBRARY_PATH = env.LD_LIBRARY_PATH
? `${bundledLib}:${env.LD_LIBRARY_PATH}`
: bundledLib;
return {
cmd: bundledPython,
args: ["-m", "game_setup_hub.api", "--port", portArg],
env,
};
}
// Defensive fallback: if the runtime dir is missing (e.g. user manually
// unpacked just the python/src subset), fall back to system python3 and let
// _vendor_compat sort out ABI drift.
delete env.PYTHONNOUSERSITE;
return {
cmd: "python3",
args: ["-m", "game_setup_hub.api", "--port", portArg],
env,
};
}
async function startPython(): Promise<number> {
// Pick the port on the Node side so we know it before spawning. Avoids the
// old stdout-regex dance, and we can pass it straight to `--port`.
const port = await pickFreePort();
const { cmd, args, env } = getPythonCommand(port);
return new Promise((resolve, reject) => {
pythonProcess = spawn(cmd, args, { env, stdio: ["pipe", "pipe", "pipe"] });
let stderrTail = "";
const timeout = setTimeout(() => {
reject(new Error("Python backend did not start within 15 seconds"));
}, 15000);
pythonProcess.stdout?.on("data", (data: Buffer) => {
// Stdout is informational only now; readiness comes from /health.
console.log("[python]", data.toString().trim());
});
pythonProcess.stderr?.on("data", (data: Buffer) => {
const chunk = data.toString();
stderrTail = (stderrTail + chunk).slice(-6000);
console.error("[python]", chunk.trimEnd());
});
pythonProcess.on("error", (err) => {
clearTimeout(timeout);
reject(err);
});
pythonProcess.on("exit", (code) => {
if (code !== null && code !== 0) {
clearTimeout(timeout);
const hint = stderrTail.trim() ? `\n${stderrTail.trim()}` : "";
reject(new Error(`Python exited with code ${code}${hint}`));
}
pythonProcess = null;
});
// Resolve as soon as /health responds. waitForHealth handles retries.
waitForHealth(port).then(
() => {
clearTimeout(timeout);
resolve(port);
},
(err) => {
clearTimeout(timeout);
reject(err);
},
);
});
}
function waitForHealth(port: number, retries = 30): Promise<void> {
return new Promise((resolve, reject) => {
let attempt = 0;
const check = () => {
const req = http.get(`http://127.0.0.1:${port}/health`, (res) => {
if (res.statusCode === 200) {
resolve();
} else if (++attempt < retries) {
setTimeout(check, 500);
} else {
reject(new Error("Health check failed"));
}
});
req.on("error", () => {
if (++attempt < retries) {
setTimeout(check, 500);
} else {
reject(new Error("Python backend not reachable"));
}
});
req.end();
};
check();
});
}
function getIconPath(): string {
if (isDev) {
return path.resolve(__dirname, "..", "..", "assets", "256x256.png");
}
return path.join(process.resourcesPath, "assets", "256x256.png");
}
function mimeFor(filePath: string): string {
const ext = path.extname(filePath).toLowerCase();
const map: Record<string, string> = {
".html": "text/html; charset=utf-8",
".js": "application/javascript; charset=utf-8",
".css": "text/css; charset=utf-8",
".json": "application/json; charset=utf-8",
".png": "image/png",
".jpg": "image/jpeg",
".jpeg": "image/jpeg",
".webp": "image/webp",
".svg": "image/svg+xml",
".ico": "image/x-icon",
".woff": "font/woff",
".woff2": "font/woff2",
".txt": "text/plain; charset=utf-8",
".map": "application/json; charset=utf-8",
};
return map[ext] ?? "application/octet-stream";
}
/** Serves Next static export over http://127.0.0.1 — root-relative /_next/... URLs do not work with file://.
* Detects RSC requests (Next App Router client-side navigation) and serves the
* matching .txt payload Next writes alongside each .html during `output: "export"`.
* Without this, clicking nav links produced an HTML response that the router
* could not parse, so the URL changed but the page did not switch. */
function isRscRequest(req: http.IncomingMessage): boolean {
const h = req.headers;
if (h["rsc"] === "1" || h["rsc"] === "true") return true;
if (typeof h["next-router-prefetch"] !== "undefined") return true;
if (typeof h["next-router-segment-prefetch"] !== "undefined") return true;
if (typeof h["next-router-state-tree"] !== "undefined") return true;
return false;
}
function startStaticRendererServer(rootDir: string): Promise<number> {
const root = path.resolve(rootDir);
return new Promise((resolve, reject) => {
const server = http.createServer((req, res) => {
try {
const rawPath = req.url?.split("?")[0] ?? "/";
let pathname: string;
try {
pathname = decodeURIComponent(rawPath);
} catch {
res.writeHead(400).end();
return;
}
// Reject true directory-traversal segments (".."/".") but allow dots
// inside filenames — Turbopack's content-hashed chunk names can contain
// consecutive dots, e.g. `16-.0wq_hn57..css`. A naive `includes("..")`
// check 403s the CSS bundle and renders the app completely unstyled.
const segments = pathname.split("/").filter((s) => s.length > 0);
if (segments.some((s) => s === ".." || s === ".")) {
res.writeHead(403).end();
return;
}
const rel = pathname.replace(/^\/+/, "");
const rootResolved = path.resolve(root);
const rsc = isRscRequest(req);
const hasExt = path.extname(rel) !== "";
const candidates: string[] = [];
if (rel === "" || rel === "/") {
if (rsc) candidates.push(path.join(rootResolved, "index.txt"));
candidates.push(path.join(rootResolved, "index.html"));
} else if (rsc && !hasExt) {
candidates.push(
path.join(rootResolved, `${rel}.txt`),
path.join(rootResolved, rel, "index.txt"),
path.join(rootResolved, `${rel}.html`),
path.join(rootResolved, rel, "index.html"),
);
} else {
candidates.push(
path.join(rootResolved, rel),
path.join(rootResolved, `${rel}.html`),
path.join(rootResolved, rel, "index.html"),
);
}
let found: string | null = null;
for (const candidate of candidates) {
const normalized = path.resolve(candidate);
if (!normalized.startsWith(rootResolved + path.sep) && normalized !== rootResolved) {
continue;
}
if (fs.existsSync(normalized) && fs.statSync(normalized).isFile()) {
found = normalized;
break;
}
}
if (!found) {
res.writeHead(404).end("Not found");
return;
}
const body = fs.readFileSync(found);
const ext = path.extname(found).toLowerCase();
const contentType = rsc && ext === ".txt" ? "text/x-component" : mimeFor(found);
res.writeHead(200, {
"Content-Type": contentType,
"Content-Length": String(body.length),
"Cache-Control": "no-store",
Vary: "RSC, Next-Router-State-Tree, Next-Router-Prefetch, Next-Router-Segment-Prefetch",
});
res.end(body);
} catch {
res.writeHead(500).end();
}
});
server.on("error", reject);
server.listen(0, "127.0.0.1", () => {
const addr = server.address();
staticServer = server;
if (addr && typeof addr === "object") {
staticRendererPort = addr.port;
resolve(addr.port);
} else {
reject(new Error("Static server failed to bind"));
}
});
});
}
function createWindow(): void {
mainWindow = new BrowserWindow({
width: 1400,
height: 800,
minWidth: 960,
minHeight: 600,
title: "ProtonShift",
icon: getIconPath(),
frame: false,
backgroundColor: "#0f0f14",
webPreferences: {
preload: path.join(__dirname, "preload.js"),
contextIsolation: true,
nodeIntegration: false,
sandbox: false,
},
});
if (isDev) {
mainWindow.loadURL("http://localhost:3000");
if (process.env.PROTONSHIFT_DEVTOOLS === "1") {
mainWindow.webContents.openDevTools({ mode: "detach" });
}
} else if (staticRendererPort) {
mainWindow.loadURL(`http://127.0.0.1:${staticRendererPort}/`);
} else {
mainWindow.loadFile(path.join(__dirname, "..", "renderer", "out", "index.html"));
}
mainWindow.on("closed", () => {
mainWindow = null;
});
}
ipcMain.handle("get-api-port", () => apiPort);
ipcMain.handle("get-app-version", () => app.getVersion());
ipcMain.handle("window-close", () => {
mainWindow?.close();
});
ipcMain.handle("window-minimize", () => {
mainWindow?.minimize();
});
ipcMain.handle("window-toggle-maximize", () => {
if (!mainWindow) return;
if (mainWindow.isMaximized()) {
mainWindow.unmaximize();
} else {
mainWindow.maximize();
}
});
ipcMain.handle("api-fetch", async (_event, urlPath: string, init?: RequestInit) => {
if (!apiPort) throw new Error("API not ready");
const url = `http://127.0.0.1:${apiPort}${urlPath}`;
try {
const response = await fetch(url, {
...init,
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${apiToken}`,
...init?.headers,
},
});
const body = await response.text();
return {
ok: response.ok,
status: response.status,
body,
};
} catch (err) {
return {
ok: false,
status: 0,
body: JSON.stringify({ detail: String(err) }),
};
}
});
app.on("ready", async () => {
try {
apiPort = await startPython();
if (!isDev) {
const outDir = path.join(__dirname, "..", "renderer", "out");
await startStaticRendererServer(outDir);
}
} catch (err) {
console.error("Failed to start Python backend:", err);
app.quit();
return;
}
createWindow();
});
app.on("window-all-closed", () => {
app.quit();
});
app.on("before-quit", () => {
if (pythonProcess) {
pythonProcess.kill("SIGTERM");
pythonProcess = null;
}
if (staticServer) {
staticServer.close();
staticServer = null;
staticRendererPort = null;
}
});
app.on("activate", () => {
if (mainWindow === null) {
createWindow();
}
});