Files
otunes/apps/desktop/main.cjs
T
joshuafhigginsandClaude Opus 5.5 Verified 4578d466a3 fix(desktop): proxy avatars and cross-compile per OS
Avatar requests now go to the selected server, since the bundled UI
strips sharp. Windows and Linux runners build both architectures, so
three machines cover all five targets.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 00:14:36 -05:00

304 lines
8.9 KiB
JavaScript

const {
app,
BrowserWindow,
Menu,
nativeTheme,
session,
utilityProcess,
} = require("electron")
const { createServer, request: httpRequest } = require("node:http")
const { request: httpsRequest } = require("node:https")
const { readFile, mkdir, writeFile, rename } = require("node:fs/promises")
const path = require("node:path")
const { parseServer } = require("./server-config.cjs")
const origin = "http://127.0.0.1:47836"
let window,
gateway,
nextProcess,
config,
changingServer = false
let nextPort
const configPath = () => path.join(app.getPath("userData"), "server.json")
const webRoot = path.join(
app.isPackaged ? process.resourcesPath : __dirname,
"web",
"apps",
"web"
)
async function startWeb() {
if (nextProcess) {
const previous = nextProcess
nextProcess = undefined
await new Promise((resolve) => {
previous.once("exit", resolve)
previous.kill()
})
}
// Let the OS allocate a private port for the bundled Next.js server.
const reservation = createServer()
await new Promise((resolve, reject) => {
reservation.once("error", reject)
reservation.listen(0, "127.0.0.1", resolve)
})
nextPort = reservation.address().port
await new Promise((resolve) => reservation.close(resolve))
nextProcess = utilityProcess.fork(path.join(webRoot, "server.js"), [], {
cwd: webRoot,
env: {
...process.env,
NODE_ENV: "production",
HOSTNAME: "127.0.0.1",
PORT: String(nextPort),
OTUNES_DESKTOP: "1",
OTUNES_DESKTOP_HOSTNAME: config?.hostname ?? "",
PUBLIC_CONVEX_URL: config?.convexUrl ?? "",
CONVEX_INTERNAL_URL: config?.convexUrl ?? "http://127.0.0.1:3210",
NEXT_PUBLIC_CONVEX_URL: config?.convexUrl ?? "",
},
stdio: "pipe",
})
nextProcess.stdout.on("data", (data) => console.log(data.toString()))
nextProcess.stderr.on("data", (data) => console.error(data.toString()))
let exited = false
const child = nextProcess
child.once("exit", () => {
exited = true
if (nextProcess === child) nextProcess = undefined
})
for (let attempt = 0; attempt < 150; attempt++) {
if (exited) throw new Error("The packaged web server exited during startup")
try {
const response = await fetch(`http://127.0.0.1:${nextPort}/desktop`, {
signal: AbortSignal.timeout(1000),
})
if (!response.ok) throw new Error("Server entry page did not load")
await response.body?.cancel()
return
} catch {
await new Promise((resolve) => setTimeout(resolve, 200))
}
}
throw new Error("The packaged web server did not start")
}
async function saveServer(request, response) {
if (
request.headers.origin !== origin ||
request.headers["content-type"] !== "application/json"
) {
response.writeHead(403).end()
return
}
if (changingServer) {
response.writeHead(409).end()
return
}
changingServer = true
try {
let body = ""
for await (const chunk of request) {
body += chunk
if (body.length > 2048) throw new Error("Server address is too long.")
}
const selected = parseServer(JSON.parse(body).hostname)
// Validate against Convex before replacing the current server and session.
const check = await fetch(`${selected.convexUrl}/version`, {
signal: AbortSignal.timeout(10000),
})
if (!check.ok)
throw new Error(
"Could not reach the Convex server. Check the address and try again."
)
const previous = config
config = selected
try {
await startWeb()
} catch (error) {
config = previous
await startWeb()
throw error
}
await mkdir(app.getPath("userData"), { recursive: true })
await writeFile(`${configPath()}.tmp`, JSON.stringify(selected), {
mode: 0o600,
})
await rename(`${configPath()}.tmp`, configPath())
if (previous?.hostname !== selected.hostname) {
await session.defaultSession.clearStorageData()
await session.defaultSession.clearCache()
}
response
.writeHead(200, {
"Content-Type": "application/json",
"Cache-Control": "no-store",
})
.end("{}")
} catch (error) {
response.writeHead(400, { "Content-Type": "application/json" }).end(
JSON.stringify({
error:
error instanceof TypeError
? "Could not reach the server. Check the address and try again."
: error.message,
})
)
} finally {
changingServer = false
}
}
function handleRequest(request, response) {
if (request.headers.host !== new URL(origin).host) {
response.writeHead(403).end()
return
}
const url = new URL(request.url, origin)
if (url.pathname === "/__desktop/server" && request.method === "POST") {
void saveServer(request, response)
return
}
if (changingServer) {
response.writeHead(503).end("Switching server")
return
}
// Only data routes go to the remote server. All UI and auth routes stay local.
const remote =
config && /^\/api\/(song|album|artist|playlist|user)\//.test(url.pathname)
const target = new URL(
`${url.pathname}${url.search}`,
remote ? config.serverUrl : `http://127.0.0.1:${nextPort}`
)
const headers = {
...request.headers,
host: remote ? target.host : request.headers.host,
}
if (remote) {
delete headers.origin
// Convex Auth uses __Host- cookie names on public HTTPS servers.
// Forward only the access token, never the local refresh token.
const token = request.headers.cookie
?.split(";")
.map((part) => part.trim())
.find((part) => part.startsWith("__convexAuthJWT="))
?.slice("__convexAuthJWT=".length)
delete headers.cookie
if (token) {
const prefix = /(localhost|127\.0\.0\.1):\d+/.test(target.host)
? ""
: "__Host-"
headers.cookie = `${prefix}__convexAuthJWT=${token}`
}
}
delete headers.connection
const upstream = (target.protocol === "https:" ? httpsRequest : httpRequest)(
target,
{
method: request.method,
headers,
},
(incoming) => {
// Never redirect the window to remote HTML or accept remote session cookies.
const resultHeaders = { ...incoming.headers }
if (remote) delete resultHeaders["set-cookie"]
response.writeHead(incoming.statusCode ?? 502, resultHeaders)
incoming.on("error", () => response.destroy())
incoming.pipe(response)
}
)
upstream.on("error", () => {
if (!response.headersSent) response.writeHead(502)
response.end("Server unavailable")
})
request.on("aborted", () => upstream.destroy())
response.on("close", () => upstream.destroy())
request.pipe(upstream)
}
function openWindow() {
window = new BrowserWindow({
title: "oTunes",
width: 1280,
height: 850,
backgroundColor: nativeTheme.shouldUseDarkColors ? "#000000" : "#ffffff",
webPreferences: {
nodeIntegration: false,
contextIsolation: true,
sandbox: true,
webSecurity: true,
},
})
window.webContents.setWindowOpenHandler(() => ({ action: "deny" }))
const restrictNavigation = (event, target) => {
if (new URL(target).origin !== origin) event.preventDefault()
}
window.webContents.on("will-navigate", restrictNavigation)
window.webContents.on("will-redirect", restrictNavigation)
session.defaultSession.setPermissionRequestHandler(
(_contents, _permission, callback) => callback(false)
)
session.defaultSession.setPermissionCheckHandler(() => false)
window.loadURL(`${origin}${config ? "/" : "/desktop"}`).catch(console.error)
window.on("closed", () => {
window = undefined
})
}
if (!app.requestSingleInstanceLock()) app.quit()
else {
app.on("second-instance", () => {
window?.show()
window?.focus()
})
app
.whenReady()
.then(async () => {
try {
config = parseServer(
JSON.parse(await readFile(configPath(), "utf8")).hostname
)
} catch {
config = undefined
}
await startWeb()
gateway = createServer(handleRequest)
await new Promise((resolve, reject) => {
gateway.once("error", reject)
gateway.listen(47836, "127.0.0.1", resolve)
})
Menu.setApplicationMenu(
Menu.buildFromTemplate([
...(process.platform === "darwin" ? [{ role: "appMenu" }] : []),
{
label: "Server",
submenu: [
{
label: "Change server…",
click: () => window?.loadURL(`${origin}/desktop`),
},
],
},
{ role: "editMenu" },
{ role: "viewMenu" },
{ role: "windowMenu" },
])
)
openWindow()
app.on("activate", () => {
if (BrowserWindow.getAllWindows().length === 0) openWindow()
})
})
.catch((error) => {
console.error(error)
app.quit()
})
}
app.on("before-quit", () => {
nextProcess?.kill()
gateway?.close()
})
app.on("window-all-closed", () => {
if (process.platform !== "darwin") app.quit()
})