|
| 1 | +import path from 'node:path'; |
| 2 | +import { fileURLToPath, pathToFileURL } from 'node:url'; |
| 3 | + |
| 4 | +import { createClerkBridge } from '@clerk/electron'; |
| 5 | +import { storage } from '@clerk/electron/storage'; |
| 6 | +import { app, BrowserWindow, net, protocol } from 'electron'; |
| 7 | + |
| 8 | +const __dirname = path.dirname(fileURLToPath(import.meta.url)); |
| 9 | +const RENDERER_SCHEME = 'clerk'; |
| 10 | +const RENDERER_HOST = 'app'; |
| 11 | +const rendererRoot = path.resolve(__dirname, 'dist'); |
| 12 | + |
| 13 | +const clerk = createClerkBridge({ |
| 14 | + storage: storage({ unencryptedFallback: true }), |
| 15 | + renderer: { |
| 16 | + scheme: RENDERER_SCHEME, |
| 17 | + host: RENDERER_HOST, |
| 18 | + }, |
| 19 | +}); |
| 20 | + |
| 21 | +async function createWindow() { |
| 22 | + const win = new BrowserWindow({ |
| 23 | + width: 1000, |
| 24 | + height: 800, |
| 25 | + webPreferences: { |
| 26 | + contextIsolation: true, |
| 27 | + nodeIntegration: false, |
| 28 | + preload: path.resolve(__dirname, 'preload.mjs'), |
| 29 | + sandbox: false, |
| 30 | + }, |
| 31 | + }); |
| 32 | + |
| 33 | + await win.loadURL(`${RENDERER_SCHEME}://${RENDERER_HOST}/`); |
| 34 | +} |
| 35 | + |
| 36 | +function registerClerkAppProtocol() { |
| 37 | + protocol.handle(RENDERER_SCHEME, async request => { |
| 38 | + const url = new URL(request.url); |
| 39 | + |
| 40 | + if (url.host !== RENDERER_HOST) { |
| 41 | + return new Response('Not found', { status: 404 }); |
| 42 | + } |
| 43 | + |
| 44 | + let requestedPath; |
| 45 | + try { |
| 46 | + requestedPath = decodeURIComponent(url.pathname); |
| 47 | + } catch { |
| 48 | + return new Response('Bad request', { status: 400 }); |
| 49 | + } |
| 50 | + |
| 51 | + const resolvedPath = path.resolve(rendererRoot, `.${requestedPath}`); |
| 52 | + const relativePath = path.relative(rendererRoot, resolvedPath); |
| 53 | + const isSafe = relativePath === '' || (!relativePath.startsWith('..') && !path.isAbsolute(relativePath)); |
| 54 | + |
| 55 | + if (!isSafe) { |
| 56 | + return new Response('Forbidden', { status: 403 }); |
| 57 | + } |
| 58 | + |
| 59 | + const hasExtension = /\.[^/]+$/.test(url.pathname); |
| 60 | + const filePath = hasExtension ? resolvedPath : path.join(rendererRoot, 'index.html'); |
| 61 | + |
| 62 | + return net.fetch(pathToFileURL(filePath).toString()); |
| 63 | + }); |
| 64 | +} |
| 65 | + |
| 66 | +app.whenReady().then(async () => { |
| 67 | + registerClerkAppProtocol(); |
| 68 | + await createWindow(); |
| 69 | +}); |
| 70 | + |
| 71 | +app.on('window-all-closed', () => { |
| 72 | + app.quit(); |
| 73 | +}); |
| 74 | + |
| 75 | +app.on('before-quit', () => { |
| 76 | + clerk.cleanup(); |
| 77 | +}); |
0 commit comments