| 'use strict'
|
|
|
| const { app, BrowserWindow, ipcMain, shell, dialog, safeStorage, session, Menu, Tray, screen } = require('electron')
|
| const path = require('path')
|
| const fs = require('fs')
|
| const os = require('os')
|
| const { spawn, spawnSync } = require('child_process')
|
| const platform = require('./runtime/platform')
|
| let ptyModule = null
|
|
|
| function getPtyModule() {
|
| if (ptyModule) return ptyModule
|
| ptyModule = require('node-pty')
|
| return ptyModule
|
| }
|
|
|
| function isWritableDirectory(dirPath) {
|
| try {
|
| fs.mkdirSync(dirPath, { recursive: true })
|
| fs.accessSync(dirPath, fs.constants.W_OK)
|
| const probe = path.join(dirPath, `.write-test-${process.pid}-${Date.now()}.tmp`)
|
| fs.writeFileSync(probe, 'ok')
|
| fs.unlinkSync(probe)
|
| return true
|
| } catch {
|
| return false
|
| }
|
| }
|
|
|
| function configureRuntimeWritablePaths() {
|
| const candidates = platform.getWritableCandidates('Dev-Launcher')
|
|
|
| for (const basePath of candidates) {
|
| if (!isWritableDirectory(basePath)) continue
|
| const sessionPath = path.join(basePath, 'session-data')
|
| const cachePath = path.join(sessionPath, 'Cache')
|
| const gpuCachePath = path.join(sessionPath, 'GPUCache')
|
|
|
| if (!isWritableDirectory(sessionPath)) continue
|
| isWritableDirectory(cachePath)
|
| isWritableDirectory(gpuCachePath)
|
|
|
| try {
|
| app.setPath('userData', basePath)
|
| app.setPath('sessionData', sessionPath)
|
| app.commandLine.appendSwitch('disk-cache-dir', cachePath)
|
| return true
|
| } catch {
|
|
|
| }
|
| }
|
|
|
| return false
|
| }
|
|
|
| configureRuntimeWritablePaths()
|
|
|
| let win = null
|
| let splashWin = null
|
| let tray = null
|
| let currentProc = null
|
| let currentProcKind = null
|
| let currentMainCommandKey = null
|
| const popupRuns = new Map()
|
| let popupRunSeq = 0
|
| let metricsTimer = null
|
| let cpuSnapshot = null
|
| let popupClampGuard = false
|
| let popupDockSeq = 0
|
|
|
| function popupChannel(runId, topic) {
|
| return `popup:${String(runId || '')}:${String(topic || '')}`
|
| }
|
|
|
| function popupLegacyChannel(topic) {
|
| const t = String(topic || '').trim().toLowerCase()
|
| if (t === 'meta') return 'popup-meta'
|
| if (t === 'out') return 'popup-out'
|
| if (t === 'done') return 'popup-done'
|
| if (t === 'metrics') return 'popup-metrics'
|
| return ''
|
| }
|
|
|
| function sendToPopup(ctx, topic, payload) {
|
| if (!ctx || !ctx.win || ctx.win.isDestroyed()) return
|
| const scopedChannel = popupChannel(ctx.runId, topic)
|
| ctx.win.webContents.send(scopedChannel, payload)
|
|
|
|
|
| const legacyChannel = popupLegacyChannel(topic)
|
| if (legacyChannel) {
|
| ctx.win.webContents.send(legacyChannel, payload)
|
| }
|
| }
|
| const secureConfigPath = path.join(app.getPath('userData'), 'secure-r2-config.json')
|
| const auditLogPath = path.join(app.getPath('userData'), 'audit.log')
|
| const isDev = !app.isPackaged
|
| let requestGuardInstalled = false
|
| const EXTERNAL_HOST_ALLOWLIST = new Set([
|
| 'dash.cloudflare.com',
|
| 'www.buymeacoffee.com',
|
| 'buymeacoffee.com',
|
| 'huggingface.co',
|
| 'www.chahuadev.com',
|
| 'chahuadev.com'
|
| ])
|
|
|
| function isPathUnder(candidate, baseDir) {
|
| const base = path.resolve(String(baseDir || ''))
|
| const target = path.resolve(String(candidate || ''))
|
| if (!base || !target) return false
|
| if (process.platform === 'win32') {
|
| const b = base.toLowerCase()
|
| const t = target.toLowerCase()
|
| return t === b || t.startsWith(`${b}\\`)
|
| }
|
| return target === base || target.startsWith(`${base}/`)
|
| }
|
|
|
| function getRestrictedPathReason(targetPath) {
|
| const resolved = path.resolve(String(targetPath || ''))
|
| for (const base of platform.getProtectedPathBases()) {
|
| if (isPathUnder(resolved, base)) {
|
| return `Selection is blocked because the folder is inside a protected OS location: ${base}`
|
| }
|
| }
|
| return null
|
| }
|
|
|
| function notifyProtectedPathBlocked(selectedPath, reason) {
|
| const message = [
|
| 'SECURITY POLICY NOTICE',
|
| '',
|
| 'The selected folder is part of operating system directories.',
|
| 'Access is blocked to protect system integrity and user data.',
|
| '',
|
| 'Please select a project folder outside protected OS locations.'
|
| ].join('\n')
|
|
|
| writeAudit('blocked_project_root', { selectedPath, reason })
|
| sendToRenderer('project-selection-blocked', {
|
| selectedPath,
|
| reason,
|
| message
|
| })
|
| }
|
|
|
|
|
|
|
| let projectRoot = app.isPackaged
|
| ? (process.env.PORTABLE_EXECUTABLE_DIR || path.dirname(process.execPath))
|
| : __dirname
|
| let selectedExternalProjectRoot = null
|
| let selectedExternalProjectMode = null
|
|
|
| function getEffectiveProjectRoot() {
|
| return selectedExternalProjectRoot || projectRoot
|
| }
|
|
|
| function isExternalDevOnlyModeForRoot(root) {
|
| if (!selectedExternalProjectRoot) return false
|
| if (selectedExternalProjectMode !== 'npm-run-dev-only') return false
|
| return path.resolve(String(root || '')) === path.resolve(selectedExternalProjectRoot)
|
| }
|
|
|
| function buildDevOnlyGroups(root) {
|
| return [
|
| {
|
| label: 'Dev Mode', icon: 'npm', color: '#e84040',
|
| cmds: [
|
| { label: prettyCmdLabel('npm', ['run', 'dev']), cmd: 'npm', args: ['run', 'dev'], cwd: root }
|
| ]
|
| }
|
| ]
|
| }
|
|
|
| function buildCommandGroupsForProject(pkg, root, hasAndroid) {
|
| if (isExternalDevOnlyModeForRoot(root)) {
|
| return buildDevOnlyGroups(root)
|
| }
|
| return buildGroups(pkg, root, hasAndroid)
|
| }
|
|
|
| function createSplashWindow() {
|
| splashWin = new BrowserWindow({
|
| width: 520,
|
| height: 320,
|
| frame: false,
|
| resizable: false,
|
| alwaysOnTop: true,
|
| skipTaskbar: true,
|
| center: true,
|
| backgroundColor: '#09080f',
|
| webPreferences: { nodeIntegration: false, contextIsolation: true }
|
| })
|
| splashWin.loadFile(path.join(__dirname, 'splash.html'))
|
| splashWin.webContents.on('will-navigate', (e) => e.preventDefault())
|
| }
|
|
|
| function createWindow() {
|
| win = new BrowserWindow({
|
| width: 960,
|
| height: 660,
|
| minWidth: 740,
|
| minHeight: 520,
|
| backgroundColor: '#0d0d1a',
|
| icon: path.join(__dirname, 'icons', 'icon.png'),
|
| webPreferences: {
|
| preload: path.join(__dirname, 'preload.js'),
|
| contextIsolation: true,
|
| nodeIntegration: false,
|
| sandbox: false,
|
|
|
| devTools: !!isDev
|
| },
|
| title: 'Dev Launcher',
|
| show: false
|
| })
|
|
|
| win.loadFile(path.join(__dirname, 'index.html'))
|
| installAppMenu()
|
|
|
|
|
| win.webContents.setWindowOpenHandler(() => ({ action: 'deny' }))
|
| win.webContents.on('will-navigate', (e, url) => {
|
| const allowed = String(url || '').startsWith('file:')
|
| if (!allowed) {
|
| e.preventDefault()
|
| writeAudit('blocked_navigation', { url: String(url || '') })
|
| if (!isDev) {
|
| dialog.showErrorBox('Security Blocked', 'Unauthorized external navigation attempt detected. The app will close.')
|
| app.quit()
|
| }
|
| }
|
| })
|
|
|
| if (!isDev) {
|
|
|
| const _blockDevToolsKeys = (event, input) => {
|
| const key = String(input.key || '').toLowerCase()
|
| const openDevTools =
|
| key === 'f12' ||
|
| ((input.control || input.meta) && input.shift && (key === 'i' || key === 'j' || key === 'c'))
|
| if (openDevTools) event.preventDefault()
|
| }
|
| win.webContents.on('before-input-event', _blockDevToolsKeys)
|
| win.once('closed', () => win.webContents.removeListener('before-input-event', _blockDevToolsKeys))
|
| }
|
|
|
| win.once('ready-to-show', () => {
|
|
|
| setTimeout(() => {
|
| if (splashWin && !splashWin.isDestroyed()) {
|
| splashWin.close()
|
| splashWin = null
|
| }
|
| win.show()
|
| }, isDev ? 150 : 500)
|
| })
|
|
|
|
|
| win.on('close', (e) => {
|
| if (tray && !win.isDestroyed()) {
|
| e.preventDefault()
|
| win.hide()
|
| }
|
| })
|
|
|
| const _onWinMove = () => layoutDockedPopups()
|
| win.on('move', _onWinMove)
|
| win.once('closed', () => win.removeListener('move', _onWinMove))
|
|
|
| win.on('resize', () => {
|
| layoutDockedPopups()
|
| })
|
| }
|
|
|
| function createTray() {
|
| tray = new Tray(path.join(__dirname, 'icons', 'icon.png'))
|
| tray.setToolTip('Dev Launcher')
|
|
|
| const ctxMenu = Menu.buildFromTemplate([
|
| {
|
| label: 'Show Dev Launcher',
|
| click: () => {
|
| if (win && !win.isDestroyed()) {
|
| win.show()
|
| win.focus()
|
| }
|
| }
|
| },
|
| { type: 'separator' },
|
| {
|
| label: 'Quit',
|
| click: () => {
|
| tray.removeListener('double-click', _onTrayDblClick)
|
| tray.destroy()
|
| tray = null
|
| killAllRunningJobs()
|
| app.quit()
|
| }
|
| }
|
| ])
|
| tray.setContextMenu(ctxMenu)
|
|
|
| const _onTrayDblClick = () => {
|
| if (win && !win.isDestroyed()) { win.show(); win.focus() }
|
| }
|
| tray.on('double-click', _onTrayDblClick)
|
| }
|
|
|
| async function chooseExternalProjectFolder(mode = 'full-project') {
|
| const targetWin = win && !win.isDestroyed() ? win : null
|
| const res = await dialog.showOpenDialog(targetWin, {
|
| title: mode === 'npm-run-dev-only'
|
| ? 'Select Project Folder (npm run dev only)'
|
| : 'Select Project Folder',
|
| properties: ['openDirectory']
|
| })
|
|
|
| if (res.canceled || !res.filePaths || !res.filePaths[0]) return { ok: false, cancelled: true }
|
|
|
| const picked = path.resolve(res.filePaths[0])
|
| const blockedReason = getRestrictedPathReason(picked)
|
| if (blockedReason) {
|
| notifyProtectedPathBlocked(picked, blockedReason)
|
| return { ok: false, blocked: true, error: blockedReason }
|
| }
|
|
|
| const pkgPath = path.join(picked, 'package.json')
|
| if (!fs.existsSync(pkgPath)) {
|
| dialog.showErrorBox('Invalid Project', `No package.json found in:\n${picked}`)
|
| return { ok: false, error: `No package.json found in ${picked}` }
|
| }
|
|
|
| selectedExternalProjectRoot = picked
|
| selectedExternalProjectMode = mode === 'npm-run-dev-only' ? 'npm-run-dev-only' : 'full-project'
|
| writeAudit('set_external_project_root', { root: picked, mode: selectedExternalProjectMode })
|
| sendToRenderer('project-root-changed', {
|
| root: getEffectiveProjectRoot(),
|
| external: true,
|
| mode: selectedExternalProjectMode
|
| })
|
| return { ok: true, root: picked, mode: selectedExternalProjectMode }
|
| }
|
|
|
| function useLauncherProjectRoot() {
|
| selectedExternalProjectRoot = null
|
| selectedExternalProjectMode = null
|
| writeAudit('reset_project_root', { root: projectRoot })
|
| sendToRenderer('project-root-changed', {
|
| root: getEffectiveProjectRoot(),
|
| external: false,
|
| mode: 'default'
|
| })
|
| return { ok: true, root: getEffectiveProjectRoot(), mode: 'default' }
|
| }
|
|
|
| function installAppMenu() {
|
| if (!isDev) {
|
|
|
| Menu.setApplicationMenu(null)
|
| if (win && !win.isDestroyed()) win.setMenu(null)
|
| return
|
| }
|
|
|
| const template = [
|
| {
|
| label: 'Dev',
|
| submenu: [
|
| {
|
| label: 'Select External Project Folder...',
|
| accelerator: 'Ctrl+Shift+O',
|
| click: () => { chooseExternalProjectFolder('full-project').catch(() => {}) }
|
| },
|
| {
|
| label: 'Select External Project Folder (npm run dev only)...',
|
| accelerator: 'Ctrl+Shift+D',
|
| click: () => { chooseExternalProjectFolder('npm-run-dev-only').catch(() => {}) }
|
| },
|
| {
|
| label: 'Use Launcher Project',
|
| accelerator: 'Ctrl+Shift+R',
|
| click: () => useLauncherProjectRoot()
|
| },
|
| { type: 'separator' },
|
| {
|
| label: 'Reload',
|
| accelerator: 'Ctrl+R',
|
| click: () => { if (win && !win.isDestroyed()) win.reload() }
|
| }
|
| ]
|
| }
|
| ]
|
| const menu = Menu.buildFromTemplate(template)
|
| Menu.setApplicationMenu(menu)
|
| if (win && !win.isDestroyed()) win.setMenu(menu)
|
| }
|
|
|
| function installRequestGuard() {
|
| if (requestGuardInstalled) return
|
| requestGuardInstalled = true
|
|
|
| const ses = session.defaultSession
|
| if (!ses) return
|
|
|
|
|
| ses.setPermissionRequestHandler((_, __, callback) => callback(false))
|
|
|
| if (isDev) return
|
|
|
| ses.webRequest.onBeforeRequest((details, callback) => {
|
| const url = String(details.url || '')
|
| const allowed =
|
| url.startsWith('file:') ||
|
| url.startsWith('data:') ||
|
| url.startsWith('about:blank')
|
|
|
| if (allowed) {
|
| callback({ cancel: false })
|
| return
|
| }
|
|
|
| callback({ cancel: true })
|
| writeAudit('blocked_request', { url })
|
|
|
|
|
| dialog.showErrorBox('Security Blocked', `Unauthorized external request detected:\n${url}\n\nThe app will close.`)
|
| app.quit()
|
| })
|
| }
|
|
|
| app.whenReady().then(() => {
|
| createSplashWindow()
|
| installRequestGuard()
|
| createWindow()
|
| setTimeout(() => {
|
| if (!tray) createTray()
|
| }, 300)
|
| }).catch(err => {
|
| console.error('[app] startup error:', err)
|
| app.quit()
|
| })
|
|
|
| app.on('window-all-closed', () => {
|
|
|
| if (!tray) {
|
| killAllRunningJobs()
|
| app.quit()
|
| }
|
| })
|
|
|
| app.on('before-quit', () => {
|
| killAllRunningJobs()
|
| })
|
|
|
| function killCurrentProc() {
|
| if (!currentProc) return
|
| try {
|
| if (currentProcKind === 'pty' && typeof currentProc.kill === 'function') {
|
| currentProc.kill()
|
| }
|
|
|
| if (currentProc && currentProc.pid) {
|
| spawn('taskkill', ['/pid', String(currentProc.pid), '/f', '/t'], { shell: false, windowsHide: true })
|
| }
|
| } catch (_e) { }
|
| currentProc = null
|
| currentProcKind = null
|
| currentMainCommandKey = null
|
| }
|
|
|
| function killProcessObject(proc, kind) {
|
| if (!proc) return
|
| try {
|
| if (kind === 'pty' && typeof proc.kill === 'function') {
|
| proc.kill()
|
| }
|
| if (proc && proc.pid) {
|
| spawn('taskkill', ['/pid', String(proc.pid), '/f', '/t'], { shell: false, windowsHide: true })
|
| }
|
| } catch (_e) { }
|
| }
|
|
|
| function getCommandDisplayLine(cmd, args) {
|
| const normalizedArgs = (args || []).map(x => String(x || ''))
|
| return [String(cmd || ''), ...normalizedArgs].join(' ').trim()
|
| }
|
|
|
| function sanitizePopupTitle(raw) {
|
| return String(raw || 'Terminal').replace(/[<>:"/\\|?*]+/g, ' ').replace(/\s+/g, ' ').trim() || 'Terminal'
|
| }
|
|
|
| function buildPopupRunId() {
|
| popupRunSeq += 1
|
| return `popup-${Date.now()}-${popupRunSeq}`
|
| }
|
|
|
| function getCpuSnapshot() {
|
| const cpus = os.cpus() || []
|
| return cpus.map((cpu) => {
|
| const times = cpu && cpu.times ? cpu.times : {}
|
| return {
|
| user: Number(times.user || 0),
|
| nice: Number(times.nice || 0),
|
| sys: Number(times.sys || 0),
|
| idle: Number(times.idle || 0),
|
| irq: Number(times.irq || 0)
|
| }
|
| })
|
| }
|
|
|
| function computeCpuUsagePercent(prev, next) {
|
| if (!Array.isArray(prev) || !Array.isArray(next) || prev.length === 0 || next.length === 0) return null
|
| const count = Math.min(prev.length, next.length)
|
| let idleDelta = 0
|
| let totalDelta = 0
|
| for (let i = 0; i < count; i++) {
|
| const p = prev[i]
|
| const n = next[i]
|
| const pIdle = Number(p.idle || 0)
|
| const nIdle = Number(n.idle || 0)
|
| const pTotal = Number(p.user || 0) + Number(p.nice || 0) + Number(p.sys || 0) + pIdle + Number(p.irq || 0)
|
| const nTotal = Number(n.user || 0) + Number(n.nice || 0) + Number(n.sys || 0) + nIdle + Number(n.irq || 0)
|
| idleDelta += Math.max(0, nIdle - pIdle)
|
| totalDelta += Math.max(0, nTotal - pTotal)
|
| }
|
| if (totalDelta <= 0) return null
|
| const usage = Math.max(0, Math.min(100, ((totalDelta - idleDelta) / totalDelta) * 100))
|
| return Math.round(usage * 10) / 10
|
| }
|
|
|
| function collectSystemUsage() {
|
| const nextSnapshot = getCpuSnapshot()
|
| const cpuPercent = cpuSnapshot ? computeCpuUsagePercent(cpuSnapshot, nextSnapshot) : null
|
| cpuSnapshot = nextSnapshot
|
|
|
| const totalMem = Number(os.totalmem() || 0)
|
| const freeMem = Number(os.freemem() || 0)
|
| const usedMem = Math.max(0, totalMem - freeMem)
|
| const memPercent = totalMem > 0 ? Math.round(((usedMem / totalMem) * 100) * 10) / 10 : 0
|
|
|
| return {
|
| cpuPercent,
|
| memPercent,
|
| usedMem,
|
| totalMem
|
| }
|
| }
|
|
|
| function maybeStopMetricsTicker() {
|
| if (popupRuns.size > 0) return
|
| if (metricsTimer) {
|
| clearInterval(metricsTimer)
|
| metricsTimer = null
|
| }
|
| cpuSnapshot = null
|
| }
|
|
|
| function ensureMetricsTicker() {
|
| if (metricsTimer) return
|
| cpuSnapshot = getCpuSnapshot()
|
| metricsTimer = setInterval(() => {
|
| const usage = collectSystemUsage()
|
| for (const ctx of popupRuns.values()) {
|
| if (!ctx || !ctx.win || ctx.win.isDestroyed()) continue
|
| sendToPopup(ctx, 'metrics', usage)
|
| }
|
| }, 1200)
|
| }
|
|
|
| function getClampedBounds(targetWin, proposedBounds) {
|
| const display = screen.getDisplayMatching(proposedBounds)
|
| const area = display && display.workArea ? display.workArea : { x: 0, y: 0, width: 1280, height: 720 }
|
| const [minWidth, minHeight] = targetWin.getMinimumSize()
|
| const safeWidth = Math.max(minWidth || 620, Math.min(proposedBounds.width, area.width))
|
| const safeHeight = Math.max(minHeight || 380, Math.min(proposedBounds.height, area.height))
|
| let x = proposedBounds.x
|
| let y = proposedBounds.y
|
| const maxX = area.x + area.width - safeWidth
|
| const maxY = area.y + area.height - safeHeight
|
|
|
| if (x < area.x) x = area.x
|
| if (y < area.y) y = area.y
|
| if (x > maxX) x = maxX
|
| if (y > maxY) y = maxY
|
|
|
| return { x, y, width: safeWidth, height: safeHeight }
|
| }
|
|
|
| function clampWindowInsideDisplay(targetWin) {
|
| if (!targetWin || targetWin.isDestroyed()) return
|
| if (targetWin.isMinimized() || targetWin.isMaximized() || targetWin.isFullScreen()) return
|
| if (popupClampGuard) return
|
|
|
| popupClampGuard = true
|
| try {
|
| const current = targetWin.getBounds()
|
| const clamped = getClampedBounds(targetWin, current)
|
| const changed =
|
| clamped.x !== current.x ||
|
| clamped.y !== current.y ||
|
| clamped.width !== current.width ||
|
| clamped.height !== current.height
|
| if (changed) {
|
| targetWin.setBounds(clamped, false)
|
| }
|
| } finally {
|
| popupClampGuard = false
|
| }
|
| }
|
|
|
| function notifyPopupState(payload) {
|
| sendToRenderer('popup-run-state', payload)
|
| }
|
|
|
| function closePopupRunByKey(cmdKey) {
|
| const existing = popupRuns.get(cmdKey)
|
| if (!existing) return false
|
| killProcessObject(existing.proc, existing.procKind)
|
| try {
|
| if (existing.win && !existing.win.isDestroyed()) {
|
| existing.win.destroy()
|
| }
|
| } catch (_e) { }
|
| popupRuns.delete(cmdKey)
|
| layoutDockedPopups()
|
| maybeStopMetricsTicker()
|
| return true
|
| }
|
|
|
| function closeAllPopupRuns() {
|
| const keys = Array.from(popupRuns.keys())
|
| for (const key of keys) {
|
| closePopupRunByKey(key)
|
| }
|
| }
|
|
|
| function killAllRunningJobs() {
|
| closeAllPopupRuns()
|
| killCurrentProc()
|
| }
|
|
|
| function listDockedPopupContexts() {
|
| const docked = []
|
| for (const ctx of popupRuns.values()) {
|
| if (!ctx || !ctx.isDocked) continue
|
| if (!ctx.win || ctx.win.isDestroyed()) continue
|
| docked.push(ctx)
|
| }
|
| docked.sort((a, b) => Number(a.dockOrder || 0) - Number(b.dockOrder || 0))
|
| return docked
|
| }
|
|
|
| function layoutDockedPopups() {
|
| if (!win || win.isDestroyed()) return
|
| const docked = listDockedPopupContexts()
|
| if (!docked.length) return
|
|
|
| const host = win.getBounds()
|
| const slotWidth = 230
|
| const slotHeight = 56
|
| const gap = 8
|
| const startX = host.x + 286
|
| const startY = host.y + 78
|
| const endX = host.x + host.width - 10
|
| const usableWidth = Math.max(slotWidth, endX - startX)
|
| const perRow = Math.max(1, Math.floor((usableWidth + gap) / (slotWidth + gap)))
|
|
|
| for (let i = 0; i < docked.length; i++) {
|
| const ctx = docked[i]
|
| const row = Math.floor(i / perRow)
|
| const col = i % perRow
|
| const x = startX + (col * (slotWidth + gap))
|
| const y = startY + (row * (slotHeight + gap))
|
| const nextTitle = `#${i + 1} Sandbox Terminal - ${ctx.displayLabel}`
|
| if (ctx.win.getTitle() !== nextTitle) {
|
| ctx.win.setTitle(nextTitle)
|
| }
|
| ctx.win.setBounds({ x, y, width: slotWidth, height: slotHeight }, false)
|
| ctx.win.moveTop()
|
| }
|
| }
|
|
|
| function dockPopupWindow(ctx) {
|
| if (!ctx || !ctx.win || ctx.win.isDestroyed()) return
|
| if (ctx.isDocked) {
|
| layoutDockedPopups()
|
| return
|
| }
|
|
|
| ctx.normalBounds = ctx.win.getBounds()
|
| ctx.isDocked = true
|
| popupDockSeq += 1
|
| ctx.dockOrder = popupDockSeq
|
|
|
| try {
|
| ctx.win.setAlwaysOnTop(true, 'floating')
|
| ctx.win.setResizable(false)
|
| ctx.win.setSkipTaskbar(true)
|
| } catch (_e) { }
|
|
|
| layoutDockedPopups()
|
| notifyPopupState({ cmdKey: ctx.cmdKey, status: 'docked', runId: ctx.runId })
|
| }
|
|
|
| function undockPopupWindow(ctx) {
|
| if (!ctx || !ctx.win || ctx.win.isDestroyed()) return
|
| if (!ctx.isDocked) return
|
|
|
| ctx.isDocked = false
|
| try {
|
| ctx.win.setAlwaysOnTop(false)
|
| ctx.win.setResizable(true)
|
| ctx.win.setSkipTaskbar(false)
|
| ctx.win.setTitle(`Sandbox Terminal - ${ctx.displayLabel}`)
|
| if (ctx.normalBounds) {
|
| ctx.win.setBounds(getClampedBounds(ctx.win, ctx.normalBounds), false)
|
| }
|
| } catch (_e) { }
|
|
|
| layoutDockedPopups()
|
| notifyPopupState({ cmdKey: ctx.cmdKey, status: 'undocked', runId: ctx.runId })
|
| }
|
|
|
| function createPopupWindow(ctx) {
|
| const parentBounds = win && !win.isDestroyed() ? win.getBounds() : { x: 80, y: 80, width: 1080, height: 720 }
|
| const popupPreloadPath = fs.existsSync(path.join(__dirname, 'popup-preload.js'))
|
| ? path.join(__dirname, 'popup-preload.js')
|
| : path.join(__dirname, 'preload.js')
|
| const popup = new BrowserWindow({
|
| width: 880,
|
| height: 520,
|
| minWidth: 620,
|
| minHeight: 380,
|
| x: parentBounds.x + 32,
|
| y: parentBounds.y + 32,
|
| resizable: true,
|
| movable: true,
|
| minimizable: true,
|
| maximizable: true,
|
| frame: true,
|
| backgroundColor: '#00101a',
|
| title: `Sandbox Terminal - ${ctx.displayLabel}`,
|
| parent: win && !win.isDestroyed() ? win : null,
|
| webPreferences: {
|
| preload: popupPreloadPath,
|
| contextIsolation: true,
|
| nodeIntegration: false,
|
| sandbox: true,
|
| devTools: !!isDev
|
| },
|
| show: false
|
| })
|
|
|
| popup.webContents.setWindowOpenHandler(() => ({ action: 'deny' }))
|
| popup.webContents.on('will-navigate', (e, url) => {
|
| if (!String(url || '').startsWith('file:')) {
|
| e.preventDefault()
|
| writeAudit('blocked_popup_navigation', { url: String(url || ''), runId: ctx.runId })
|
| }
|
| })
|
|
|
| popup.on('move', () => {
|
| if (ctx.isDocked) {
|
| layoutDockedPopups()
|
| return
|
| }
|
| clampWindowInsideDisplay(popup)
|
| })
|
| popup.on('resize', () => {
|
| if (ctx.isDocked) {
|
| layoutDockedPopups()
|
| return
|
| }
|
| clampWindowInsideDisplay(popup)
|
| })
|
| popup.on('minimize', (e) => {
|
| e.preventDefault()
|
| dockPopupWindow(ctx)
|
| })
|
| popup.on('focus', () => {
|
| const latest = popupRuns.get(ctx.cmdKey)
|
| if (!latest || latest.runId !== ctx.runId) return
|
| if (latest.isDocked) {
|
| undockPopupWindow(latest)
|
| }
|
| })
|
| popup.once('ready-to-show', () => {
|
| clampWindowInsideDisplay(popup)
|
| popup.show()
|
| })
|
|
|
| popup.on('closed', () => {
|
| popup.removeAllListeners('move')
|
| const latest = popupRuns.get(ctx.cmdKey)
|
| if (!latest || latest.runId !== ctx.runId) return
|
| killProcessObject(latest.proc, latest.procKind)
|
| popupRuns.delete(ctx.cmdKey)
|
| maybeStopMetricsTicker()
|
| layoutDockedPopups()
|
| notifyPopupState({ cmdKey: ctx.cmdKey, status: 'closed' })
|
| })
|
|
|
| const htmlPath = path.join(__dirname, 'web', 'popup-terminal.html')
|
| popup.loadFile(htmlPath, { hash: encodeURIComponent(ctx.runId) })
|
| return popup
|
| }
|
|
|
| function validateAndNormalizeCommand(cmd, args, cwd) {
|
| const effectiveRoot = getEffectiveProjectRoot()
|
| const requestedCmd = normalizeExecName(cmd)
|
| const requestedArgs = (args || []).map(x => String(x || ''))
|
| const requestedCwd = path.resolve(String(cwd || effectiveRoot))
|
| const restrictedPathReason = getRestrictedPathReason(requestedCwd)
|
| if (restrictedPathReason) {
|
| return {
|
| ok: false,
|
| error: restrictedPathReason
|
| }
|
| }
|
|
|
| if (!isDev && isNpmRunDevCommand(requestedCmd, requestedArgs)) {
|
| return {
|
| ok: false,
|
| error: 'npm run dev is disabled in packaged builds'
|
| }
|
| }
|
|
|
| const allowed = buildAllowedCommandSet(effectiveRoot)
|
| const directKey = commandKey(cmd, requestedArgs, requestedCwd)
|
| const normalizedKey = commandKey(requestedCmd, requestedArgs, requestedCwd)
|
| if (!allowed.has(directKey) && !allowed.has(normalizedKey)) {
|
| return {
|
| ok: false,
|
| error: `Command is not allowlisted: ${String(cmd || '')} ${requestedArgs.join(' ')}`
|
| }
|
| }
|
|
|
| const runtime = resolveRuntimeCommand(requestedCmd, requestedArgs, requestedCwd)
|
|
|
| return {
|
| ok: true,
|
| normalizedCmd: runtime.normalizedCmd,
|
| normalizedArgs: runtime.normalizedArgs,
|
| normalizedCwd: runtime.normalizedCwd,
|
| commandHash: normalizedKey,
|
| originalCmd: requestedCmd,
|
| originalArgs: requestedArgs,
|
| originalCwd: requestedCwd,
|
| rewriteInfo: runtime.rewriteInfo,
|
| envOverrides: runtime.envOverrides || {}
|
| }
|
| }
|
|
|
| function isNpmRunDevCommand(cmd, args) {
|
| const normalizedCmd = String(cmd || '').trim().toLowerCase()
|
| const normalizedArgs = (args || []).map(x => String(x || '').trim().toLowerCase()).filter(Boolean)
|
| if (!(normalizedCmd === 'npm' || normalizedCmd === 'npm.cmd')) return false
|
| if (normalizedArgs.length !== 2) return false
|
| return normalizedArgs[0] === 'run' && normalizedArgs[1] === 'dev'
|
| }
|
|
|
| function readPopupCspStatus() {
|
| try {
|
| const html = fs.readFileSync(path.join(__dirname, 'web', 'popup-terminal.html'), 'utf8')
|
| return {
|
| hasUnsafeInlineStyle: /style-src[^\n>]*'unsafe-inline'/.test(html)
|
| }
|
| } catch {
|
| return {
|
| hasUnsafeInlineStyle: false
|
| }
|
| }
|
| }
|
|
|
| function getPreferredPopupContext() {
|
| let focused = null
|
| let latest = null
|
| for (const ctx of popupRuns.values()) {
|
| if (!ctx || !ctx.win || ctx.win.isDestroyed()) continue
|
| if (ctx.win.isFocused()) focused = ctx
|
| if (!latest || Number(ctx.startedAt || 0) > Number(latest.startedAt || 0)) {
|
| latest = ctx
|
| }
|
| }
|
| return focused || latest
|
| }
|
|
|
| function spawnPtyWithStreaming(options) {
|
| const {
|
| normalizedCmd,
|
| normalizedArgs,
|
| normalizedCwd,
|
| streamMode,
|
| cols,
|
| rows,
|
| onOutput,
|
| onDone,
|
| onError,
|
| onStarted,
|
| auditMeta,
|
| envOverrides,
|
| } = options
|
|
|
| const useShell = shouldUseShellForCommand(normalizedCmd)
|
| let ptyFile = normalizedCmd
|
| let ptyArgs = normalizedArgs
|
| if (useShell) {
|
| const shellSpawn = platform.buildShellSpawn(normalizedCmd, normalizedArgs)
|
| ptyFile = shellSpawn.file
|
| ptyArgs = shellSpawn.args
|
| }
|
|
|
| const ptyCols = Number.isFinite(Number(cols)) ? Math.max(20, Math.floor(Number(cols))) : 120
|
| const ptyRows = Number.isFinite(Number(rows)) ? Math.max(5, Math.floor(Number(rows))) : 30
|
| const procEnv = {
|
| ...process.env,
|
| FORCE_COLOR: '1',
|
| CLICOLOR: '1',
|
| CLICOLOR_FORCE: '1',
|
| COLORTERM: 'truecolor',
|
| TERM: 'xterm-256color',
|
| npm_config_color: 'always',
|
| ...(envOverrides || {}),
|
| }
|
|
|
|
|
| const ptyExtra = platform.getPtySpawnOptions()
|
|
|
| let proc
|
| try {
|
| const pty = getPtyModule()
|
| proc = pty.spawn(ptyFile, ptyArgs, {
|
| cwd: normalizedCwd,
|
| env: procEnv,
|
| cols: ptyCols,
|
| rows: ptyRows,
|
| name: 'xterm-256color',
|
| ...ptyExtra
|
| })
|
| } catch (err) {
|
| const message = err && err.message ? err.message : String(err || 'Unknown PTY error')
|
| onError(message)
|
| return null
|
| }
|
|
|
| onStarted(proc)
|
|
|
| const normalizedStreamMode = String(streamMode || 'realtime').toLowerCase() === 'stable'
|
| ? 'stable'
|
| : 'realtime'
|
| const stableFlushMs = 30
|
| let outputBuffer = ''
|
| let flushTimer = null
|
|
|
| function flushBufferedOutput() {
|
| if (outputBuffer.length > 0) {
|
| onOutput(outputBuffer)
|
| outputBuffer = ''
|
| }
|
| flushTimer = null
|
| }
|
|
|
| function queueStableOutput(chunk) {
|
| const text = Buffer.isBuffer(chunk) ? chunk.toString('utf8') : String(chunk || '')
|
| if (!text) return
|
| outputBuffer += text
|
| if (!flushTimer) {
|
| flushTimer = setTimeout(flushBufferedOutput, stableFlushMs)
|
| }
|
| }
|
|
|
| function streamOutput(chunk) {
|
| const text = Buffer.isBuffer(chunk) ? chunk.toString('utf8') : String(chunk || '')
|
| if (!text) return
|
| onOutput(text)
|
| }
|
|
|
| proc.onData(normalizedStreamMode === 'stable' ? queueStableOutput : streamOutput)
|
| proc.onExit(({ exitCode }) => {
|
| if (flushTimer) {
|
| clearTimeout(flushTimer)
|
| flushTimer = null
|
| }
|
| if (normalizedStreamMode === 'stable') flushBufferedOutput()
|
| writeAudit('run_command_done', {
|
| ...(auditMeta || {}),
|
| cmd: normalizedCmd,
|
| cwd: normalizedCwd,
|
| code: exitCode,
|
| streamMode: normalizedStreamMode
|
| })
|
|
|
|
|
|
|
| setTimeout(() => setTimeout(() => onDone(exitCode ?? 0), 0), 0)
|
| })
|
|
|
| return {
|
| proc,
|
| kind: 'pty'
|
| }
|
| }
|
|
|
| function startPopupCommand(payload) {
|
| const validated = validateAndNormalizeCommand(payload.cmd, payload.args, payload.cwd)
|
| if (!validated.ok) {
|
| writeAudit('blocked_command', { cmd: String(payload.cmd || ''), args: payload.args || [], cwd: payload.cwd || '', mode: 'popup' })
|
| return { ok: false, error: validated.error }
|
| }
|
|
|
| const { normalizedCmd, normalizedArgs, normalizedCwd, commandHash } = validated
|
| const restarted = closePopupRunByKey(commandHash)
|
| const runId = buildPopupRunId()
|
| const displayLabel = sanitizePopupTitle(payload.label || getCommandDisplayLine(normalizedCmd, normalizedArgs))
|
| const commandLine = validated.rewriteInfo && validated.rewriteInfo.applied
|
| ? getCommandDisplayLine(validated.originalCmd, validated.originalArgs)
|
| : getCommandDisplayLine(normalizedCmd, normalizedArgs)
|
| const rawLogCapture = openRawLogCapture('popup', commandLine, runId)
|
|
|
| const ctx = {
|
| runId,
|
| cmdKey: commandHash,
|
| displayLabel,
|
| normalizedCmd,
|
| normalizedArgs,
|
| normalizedCwd,
|
| startedAt: Date.now(),
|
| proc: null,
|
| procKind: null,
|
| win: null
|
| }
|
|
|
| const popup = createPopupWindow(ctx)
|
| ctx.win = popup
|
| popupRuns.set(commandHash, ctx)
|
| ensureMetricsTicker()
|
|
|
| popup.webContents.on('did-finish-load', () => {
|
| sendToPopup(ctx, 'meta', {
|
| runId,
|
| title: displayLabel,
|
| cwd: normalizedCwd,
|
| commandLine,
|
| streamMode: String(payload.streamMode || 'realtime')
|
| })
|
| sendToPopup(ctx, 'out', `▶ ${commandLine}\n${'─'.repeat(70)}\n`)
|
| if (rawLogCapture.filePath) {
|
| sendToPopup(ctx, 'out', `[INFO] Raw log file: ${rawLogCapture.filePath}\n`)
|
| }
|
| })
|
|
|
| writeAudit('run_command', {
|
| cmd: normalizedCmd,
|
| args: normalizedArgs,
|
| cwd: normalizedCwd,
|
| mode: 'popup',
|
| originalCmd: validated.originalCmd,
|
| originalArgs: validated.originalArgs,
|
| originalCwd: validated.originalCwd,
|
| rewrite: validated.rewriteInfo,
|
| runId,
|
| restarted
|
| })
|
|
|
| const started = spawnPtyWithStreaming({
|
| normalizedCmd,
|
| normalizedArgs,
|
| normalizedCwd,
|
| streamMode: payload.streamMode,
|
| cols: payload.cols,
|
| rows: payload.rows,
|
| onOutput: (text) => {
|
| const latest = popupRuns.get(commandHash)
|
| if (!latest || latest.runId !== runId || !latest.win || latest.win.isDestroyed()) return
|
| rawLogCapture.append(text)
|
| sendToPopup(latest, 'out', text)
|
| },
|
| onDone: (exitCode) => {
|
| const latest = popupRuns.get(commandHash)
|
| if (!latest || latest.runId !== runId) return
|
| rawLogCapture.close()
|
| latest.proc = null
|
| latest.procKind = null
|
| if (latest.win && !latest.win.isDestroyed()) {
|
| sendToPopup(latest, 'done', exitCode)
|
| }
|
| notifyPopupState({ cmdKey: commandHash, status: 'done', exitCode })
|
| },
|
| onError: (message) => {
|
| const latest = popupRuns.get(commandHash)
|
| if (!latest || latest.runId !== runId) return
|
| rawLogCapture.close()
|
| if (latest.win && !latest.win.isDestroyed()) {
|
| sendToPopup(latest, 'out', `\n[ERROR] Failed to start PTY: ${message}\n`)
|
| sendToPopup(latest, 'done', 1)
|
| }
|
| notifyPopupState({ cmdKey: commandHash, status: 'done', exitCode: 1 })
|
| writeAudit('run_command_error', { cmd: normalizedCmd, cwd: normalizedCwd, mode: 'popup', runId, error: message })
|
| },
|
| onStarted: (proc) => {
|
| const latest = popupRuns.get(commandHash)
|
| if (!latest || latest.runId !== runId) {
|
| killProcessObject(proc, 'pty')
|
| return
|
| }
|
| latest.proc = proc
|
| latest.procKind = 'pty'
|
| },
|
| auditMeta: { mode: 'popup', runId },
|
| envOverrides: validated.envOverrides
|
| })
|
|
|
| if (!started || !started.proc) {
|
| closePopupRunByKey(commandHash)
|
| return { ok: false, error: 'Failed to start popup command process' }
|
| }
|
|
|
| notifyPopupState({
|
| cmdKey: commandHash,
|
| status: restarted ? 'restarted' : 'started',
|
| runId,
|
| label: displayLabel,
|
| commandLine
|
| })
|
|
|
| return {
|
| ok: true,
|
| mode: 'popup',
|
| cmdKey: commandHash,
|
| runId,
|
| restarted
|
| }
|
| }
|
|
|
| function sendToRenderer(channel, data) {
|
| if (win && !win.isDestroyed()) {
|
| win.webContents.send(channel, data)
|
| }
|
| }
|
|
|
| function sanitizeLogLabel(input) {
|
| return String(input || 'run')
|
| .toLowerCase()
|
| .replace(/[^a-z0-9._-]+/g, '-')
|
| .replace(/-+/g, '-')
|
| .replace(/^-|-$/g, '') || 'run'
|
| }
|
|
|
| function openRawLogCapture(mode, cmd, runId) {
|
| try {
|
| const dir = path.join(app.getPath('userData'), 'raw-logs')
|
| fs.mkdirSync(dir, { recursive: true })
|
| const stamp = new Date().toISOString().replace(/[:.]/g, '-')
|
| const fileName = `${stamp}-${sanitizeLogLabel(mode)}-${sanitizeLogLabel(cmd)}-${sanitizeLogLabel(runId || process.pid)}.log`
|
| const filePath = path.join(dir, fileName)
|
| const stream = fs.createWriteStream(filePath, { flags: 'a' })
|
|
|
| return {
|
| filePath,
|
| append(text) {
|
| if (!stream || stream.destroyed) return
|
| if (typeof text !== 'string' || text.length === 0) return
|
| stream.write(text)
|
| },
|
| close() {
|
| if (!stream || stream.destroyed) return
|
| stream.end()
|
| }
|
| }
|
| } catch {
|
| return {
|
| filePath: null,
|
| append() {},
|
| close() {}
|
| }
|
| }
|
| }
|
|
|
| function writeAudit(event, meta = {}) {
|
| try {
|
| const safeMeta = { ...meta }
|
| delete safeMeta.accessKeyId
|
| delete safeMeta.secretAccessKey
|
| delete safeMeta.accountId
|
| const line = `${new Date().toISOString()} ${event} ${JSON.stringify(safeMeta)}\n`
|
| fs.appendFileSync(auditLogPath, line, 'utf8')
|
| } catch (_e) { }
|
| }
|
|
|
| function sanitizeExternalUrl(input) {
|
| try {
|
| const u = new URL(String(input || ''))
|
| const host = String(u.hostname || '').toLowerCase()
|
| const protocolOk = u.protocol === 'https:'
|
| if (!protocolOk) return { ok: false, error: 'Only https URLs are allowed' }
|
| if (!EXTERNAL_HOST_ALLOWLIST.has(host)) return { ok: false, error: `Host is not allowlisted: ${host}` }
|
| return { ok: true, url: u.toString(), host }
|
| } catch {
|
| return { ok: false, error: 'Invalid URL' }
|
| }
|
| }
|
|
|
| function normalizeExecName(cmd) {
|
| return platform.normalizeExecName(cmd)
|
| }
|
|
|
| function resolveNodeRuntimeCommand() {
|
| return platform.resolveNodeRuntime()
|
| }
|
|
|
| function isNpmRunLauncherLinuxBuildCommand(cmd, args) {
|
| const normalizedCmd = String(cmd || '').trim().toLowerCase()
|
| const normalizedArgs = (args || []).map(x => String(x || '').trim().toLowerCase()).filter(Boolean)
|
| if (!(normalizedCmd === 'npm' || normalizedCmd === 'npm.cmd')) return false
|
| if (normalizedArgs.length !== 2) return false
|
| if (normalizedArgs[0] !== 'run') return false
|
| return normalizedArgs[1] === 'build:linux:wsl' || normalizedArgs[1] === 'build:linux'
|
| }
|
|
|
| function isNpmRunBuildV8Command(cmd, args) {
|
| const normalizedCmd = String(cmd || '').trim().toLowerCase()
|
| const normalizedArgs = (args || []).map(x => String(x || '').trim().toLowerCase()).filter(Boolean)
|
| if (!(normalizedCmd === 'npm' || normalizedCmd === 'npm.cmd')) return false
|
| if (normalizedArgs.length !== 2) return false
|
| return normalizedArgs[0] === 'run' && normalizedArgs[1] === 'build-v8'
|
| }
|
|
|
| function materializeLauncherScript(relativePath) {
|
| const sourcePath = path.join(__dirname, relativePath)
|
| if (!fs.existsSync(sourcePath)) return null
|
|
|
|
|
| if (!/\.asar[\\/]/i.test(sourcePath)) {
|
| return sourcePath
|
| }
|
|
|
| const runtimeDir = path.join(app.getPath('userData'), 'runtime-scripts')
|
| fs.mkdirSync(runtimeDir, { recursive: true })
|
| const targetPath = path.join(runtimeDir, path.basename(relativePath))
|
| const buf = fs.readFileSync(sourcePath)
|
| fs.writeFileSync(targetPath, buf)
|
|
|
| if (process.platform !== 'win32') {
|
| try {
|
| fs.chmodSync(targetPath, 0o755)
|
| } catch (_e) { }
|
| }
|
|
|
| return targetPath
|
| }
|
|
|
| function resolveRuntimeCommand(cmd, args, cwd) {
|
| const normalizedCmd = normalizeExecName(cmd)
|
| const normalizedArgs = (args || []).map(x => String(x || ''))
|
| const normalizedCwd = path.resolve(String(cwd || getEffectiveProjectRoot()))
|
|
|
| if (isNpmRunLauncherLinuxBuildCommand(normalizedCmd, normalizedArgs)) {
|
| const rewrite = platform.rewriteLinuxBuildCommand(normalizedCwd)
|
| return {
|
| normalizedCmd: rewrite.cmd,
|
| normalizedArgs: rewrite.args,
|
| normalizedCwd,
|
| rewriteInfo: rewrite.rewriteInfo,
|
| envOverrides: {}
|
| }
|
| }
|
|
|
| if (isNpmRunBuildV8Command(normalizedCmd, normalizedArgs)) {
|
| const launcherV8Script = materializeLauncherScript(path.join('scripts', 'build-v8-external.js'))
|
| if (launcherV8Script) {
|
| const nodeRuntimeCmd = resolveNodeRuntimeCommand()
|
| const runtimeScriptDir = path.dirname(launcherV8Script)
|
| return {
|
| normalizedCmd: nodeRuntimeCmd,
|
| normalizedArgs: [launcherV8Script, normalizedCwd],
|
| normalizedCwd: runtimeScriptDir,
|
| rewriteInfo: {
|
| applied: true,
|
| kind: 'launcher-build-v8',
|
| launcherScriptPath: launcherV8Script,
|
| nodeRuntimeCmd,
|
| targetProjectPath: normalizedCwd,
|
| },
|
| envOverrides: {}
|
| }
|
| }
|
| }
|
|
|
| return {
|
| normalizedCmd,
|
| normalizedArgs,
|
| normalizedCwd,
|
| rewriteInfo: {
|
| applied: false
|
| },
|
| envOverrides: {}
|
| }
|
| }
|
|
|
| function shouldUseShellForCommand(cmd) {
|
| return platform.shouldUseShell(cmd)
|
| }
|
|
|
| function commandKey(cmd, args, cwd) {
|
| const a = (args || []).map(x => String(x || '').trim())
|
| const dir = path.resolve(String(cwd || projectRoot))
|
| return `${String(cmd || '').trim().toLowerCase()}\u241f${a.join('\u241f').toLowerCase()}\u241f${dir.toLowerCase()}`
|
| }
|
|
|
| function buildAllowedCommandSet(root) {
|
| try {
|
| const pkgPath = path.join(root, 'package.json')
|
| const pkg = JSON.parse(fs.readFileSync(pkgPath, 'utf-8'))
|
| const hasAndroid = fs.existsSync(path.join(root, 'android', 'gradlew.bat'))
|
| const groups = buildCommandGroupsForProject(pkg, root, hasAndroid)
|
| const out = new Set()
|
| for (const g of groups) {
|
| for (const c of (g.cmds || [])) {
|
| out.add(commandKey(c.cmd, c.args || [], c.cwd || root))
|
| }
|
| }
|
| return out
|
| } catch {
|
| return new Set()
|
| }
|
| }
|
|
|
| function deriveAppBase(pkgName) {
|
| let slug = String(pkgName || 'app').toLowerCase()
|
| slug = slug.replace(/^@/, '').replace('/', '-')
|
| slug = slug.replace(/\s+/g, '-')
|
| slug = slug.replace(/^chahuadev-/, '')
|
| slug = slug.replace(/-(app|apk)$/i, '')
|
| return slug || 'app'
|
| }
|
|
|
| function normalizeCredential(value) {
|
| return String(value || '').replace(/[\r\n\t ]+/g, '').trim()
|
| }
|
|
|
| function friendlyAwsError(raw) {
|
| const msg = String(raw || '').trim()
|
| if (!msg) return 'Unknown AWS CLI error'
|
| if (msg.includes('SignatureDoesNotMatch')) {
|
| return 'SignatureDoesNotMatch: R2 credentials do not match this Account ID/Bucket. Check Account ID, Access Key, Secret Key.'
|
| }
|
| if (msg.includes('InvalidAccessKeyId')) {
|
| return 'InvalidAccessKeyId: R2 access key is invalid.'
|
| }
|
| if (msg.includes('AccessDenied')) {
|
| return 'AccessDenied: credentials are valid but do not have permission for this bucket/path.'
|
| }
|
| return msg
|
| }
|
|
|
| function isEncryptionReady() {
|
| try {
|
| return !!safeStorage && safeStorage.isEncryptionAvailable()
|
| } catch {
|
| return false
|
| }
|
| }
|
|
|
| function encryptValue(value) {
|
| if (!isEncryptionReady()) {
|
| throw new Error('OS encryption service is not available on this machine')
|
| }
|
| return safeStorage.encryptString(String(value)).toString('base64')
|
| }
|
|
|
| function decryptValue(value) {
|
| if (!isEncryptionReady()) {
|
| throw new Error('OS encryption service is not available on this machine')
|
| }
|
| return safeStorage.decryptString(Buffer.from(String(value), 'base64'))
|
| }
|
|
|
| function loadSecureConfigRaw() {
|
| if (!fs.existsSync(secureConfigPath)) return null
|
| try {
|
| return JSON.parse(fs.readFileSync(secureConfigPath, 'utf-8'))
|
| } catch {
|
| return null
|
| }
|
| }
|
|
|
| function loadSecureR2Config() {
|
| const raw = loadSecureConfigRaw()
|
| if (!raw || !raw.r2) return null
|
| return {
|
| accountId: decryptValue(raw.r2.accountId),
|
| bucket: decryptValue(raw.r2.bucket),
|
| accessKeyId: decryptValue(raw.r2.accessKeyId),
|
| secretAccessKey: decryptValue(raw.r2.secretAccessKey),
|
| }
|
| }
|
|
|
| function saveSecureR2Config(cfg) {
|
| const raw = loadSecureConfigRaw() || { version: 1 }
|
| const payload = {
|
| ...raw,
|
| version: 1,
|
| updatedAt: new Date().toISOString(),
|
| r2: {
|
| accountId: encryptValue(cfg.accountId),
|
| bucket: encryptValue(cfg.bucket),
|
| accessKeyId: encryptValue(cfg.accessKeyId),
|
| secretAccessKey: encryptValue(cfg.secretAccessKey),
|
| }
|
| }
|
| fs.writeFileSync(secureConfigPath, JSON.stringify(payload, null, 2), 'utf-8')
|
| }
|
|
|
| function maskMiddle(value, left = 4, right = 4) {
|
| const s = String(value || '')
|
| if (!s) return ''
|
| if (s.length <= left + right) return '*'.repeat(Math.max(6, s.length))
|
| return `${s.slice(0, left)}${'*'.repeat(Math.max(6, s.length - (left + right)))}${s.slice(-right)}`
|
| }
|
|
|
| function listR2Folders(cfg) {
|
| const endpoint = `https://${cfg.accountId}.r2.cloudflarestorage.com`
|
| const env = {
|
| ...process.env,
|
| AWS_ACCESS_KEY_ID: cfg.accessKeyId,
|
| AWS_SECRET_ACCESS_KEY: cfg.secretAccessKey,
|
| AWS_DEFAULT_REGION: 'auto'
|
| }
|
| const result = spawnSync(normalizeExecName('aws'), ['s3', 'ls', `s3://${cfg.bucket}/`, '--endpoint-url', endpoint], {
|
| env,
|
| shell: false,
|
| windowsHide: true,
|
| encoding: 'utf8'
|
| })
|
|
|
| if (result.error) {
|
| throw new Error(`Unable to run AWS CLI: ${result.error.message}`)
|
| }
|
| if (result.status !== 0) {
|
| const msg = friendlyAwsError(result.stderr || result.stdout || 'Unknown AWS CLI error')
|
| throw new Error(`AWS CLI failed while listing bucket: ${msg}`)
|
| }
|
|
|
| const lines = (result.stdout || '').split(/\r?\n/)
|
| const out = []
|
| for (const line of lines) {
|
| const m = line.match(/\bPRE\s+([^\s/]+)\/?/)
|
| if (m && m[1]) out.push(m[1])
|
| }
|
| return out
|
| }
|
|
|
| function testR2Config(cfg) {
|
| const endpoint = `https://${cfg.accountId}.r2.cloudflarestorage.com`
|
| const env = {
|
| ...process.env,
|
| AWS_ACCESS_KEY_ID: cfg.accessKeyId,
|
| AWS_SECRET_ACCESS_KEY: cfg.secretAccessKey,
|
| AWS_DEFAULT_REGION: 'auto'
|
| }
|
|
|
| const result = spawnSync(normalizeExecName('aws'), ['s3', 'ls', `s3://${cfg.bucket}/`, '--endpoint-url', endpoint], {
|
| env,
|
| shell: false,
|
| windowsHide: true,
|
| encoding: 'utf8'
|
| })
|
|
|
| if (result.error) {
|
| return { ok: false, error: `Unable to run AWS CLI: ${result.error.message}` }
|
| }
|
| if (result.status !== 0) {
|
| return { ok: false, error: friendlyAwsError(result.stderr || result.stdout || 'Unknown AWS CLI error') }
|
| }
|
| return { ok: true }
|
| }
|
|
|
| function chooseR2Target(folders, appBase) {
|
| if (!folders.length) return appBase
|
| const exact = folders.find(f => f.toLowerCase() === appBase.toLowerCase())
|
| if (exact) return exact
|
| const contains = folders.find(f => f.toLowerCase().includes(appBase.toLowerCase()))
|
| if (contains) return contains
|
| return appBase
|
| }
|
|
|
| function clearSecureR2Config() {
|
| try {
|
| if (fs.existsSync(secureConfigPath)) fs.unlinkSync(secureConfigPath)
|
| return { ok: true }
|
| } catch (e) {
|
| return { ok: false, error: e.message }
|
| }
|
| }
|
|
|
| function listR2UploadCandidates(distPath) {
|
| const exts = new Set(['.exe', '.msi', '.appimage'])
|
| const out = []
|
| const stack = [distPath]
|
|
|
| while (stack.length > 0) {
|
| const dir = stack.pop()
|
| const entries = fs.readdirSync(dir, { withFileTypes: true })
|
| for (const entry of entries) {
|
| const abs = path.join(dir, entry.name)
|
| if (entry.isDirectory()) {
|
| stack.push(abs)
|
| continue
|
| }
|
| if (!entry.isFile()) continue
|
|
|
| const ext = path.extname(entry.name).toLowerCase()
|
| if (!exts.has(ext)) continue
|
|
|
| const rel = path.relative(distPath, abs).replace(/\\/g, '/')
|
| out.push({ abs, rel })
|
| }
|
| }
|
|
|
| out.sort((a, b) => a.rel.localeCompare(b.rel))
|
| return out
|
| }
|
|
|
| function prettyCmdLabel(cmd, args) {
|
| const c = String(cmd || '').trim()
|
| const a = (args || []).map(x => String(x || '').trim()).filter(Boolean)
|
| if (!c) return ''
|
| return [c, ...a].join(' ')
|
| }
|
|
|
|
|
| function detectType(pkg) {
|
| const d = { ...pkg.dependencies, ...pkg.devDependencies, ...pkg.peerDependencies }
|
| const has = (name) => !!d[name]
|
|
|
| const kinds = []
|
| if (has('electron')) kinds.push('Electron')
|
| if (has('expo')) kinds.push('Expo')
|
| if (has('react-native')) kinds.push('React Native')
|
| if (has('next')) kinds.push('Next.js')
|
| if (has('vite')) kinds.push('Vite')
|
| if (has('@angular/core')) kinds.push('Angular')
|
| if (has('nuxt') || has('nuxt3')) kinds.push('Nuxt')
|
| if (has('svelte') || has('@sveltejs/kit')) kinds.push('Svelte')
|
| if (has('astro')) kinds.push('Astro')
|
| if (has('remix') || has('@remix-run/node')) kinds.push('Remix')
|
| if (has('gatsby')) kinds.push('Gatsby')
|
| if (has('vue')) kinds.push('Vue')
|
| if (has('react')) kinds.push('React')
|
| if (has('nestjs') || has('@nestjs/core')) kinds.push('NestJS')
|
| if (has('express')) kinds.push('Express')
|
| if (has('fastify')) kinds.push('Fastify')
|
| if (has('koa')) kinds.push('Koa')
|
|
|
| const primaryType =
|
| has('electron') ? 'electron' :
|
| has('expo') ? 'expo' :
|
| has('react-native') ? 'rn' :
|
| has('next') ? 'nextjs' :
|
| has('vite') ? 'vite' :
|
| 'npm'
|
|
|
| const badgeClass =
|
| primaryType === 'expo' ? 'badge-expo' :
|
| primaryType === 'rn' ? 'badge-rn' :
|
| primaryType === 'electron' ? 'badge-electron' :
|
| primaryType === 'nextjs' ? 'badge-nextjs' :
|
| primaryType === 'vite' ? 'badge-vite' :
|
| 'badge-npm'
|
|
|
| const withNode = kinds.includes('Node.js') ? kinds : [...kinds, 'Node.js']
|
| const label = withNode.length ? withNode.join(' + ') : 'Node.js'
|
| return { type: primaryType, label, badgeClass }
|
| }
|
|
|
| function getRuntimeOsStatus() {
|
| const p = String(process.platform || '').toLowerCase()
|
| if (p === 'win32') return { platform: p, label: 'Windows' }
|
| if (p === 'darwin') return { platform: p, label: 'macOS' }
|
| if (p === 'linux') return { platform: p, label: 'Linux' }
|
| return { platform: p || 'unknown', label: p || 'Unknown' }
|
| }
|
|
|
| function buildGroups(pkg, root, hasAndroid) {
|
| const d = { ...pkg.dependencies, ...pkg.devDependencies, ...pkg.peerDependencies }
|
| const has = (name) => !!d[name]
|
| const isExpoLike = has('expo') || has('react-native')
|
| const isElectron = has('electron')
|
| const isNext = has('next')
|
| const isVite = has('vite')
|
| const androidPath = path.join(root, 'android')
|
| const groups = []
|
|
|
|
|
| if (isExpoLike) {
|
| groups.push({
|
| label: 'Expo / Metro', icon: 'expo', color: '#7c6cf6',
|
| cmds: [
|
| { label: 'expo start', cmd: 'npx', args: ['expo', 'start'], cwd: root },
|
| { label: 'expo run:android', cmd: 'npx', args: ['expo', 'run:android'], cwd: root },
|
| { label: 'expo prebuild', cmd: 'npx', args: ['expo', 'prebuild', '--platform', 'android'], cwd: root },
|
| ]
|
| })
|
| if (hasAndroid) {
|
| groups.push({
|
| label: 'Android / Gradle', icon: 'android', color: '#3ddc84',
|
| cmds: [
|
| { label: 'installDebug ▶', cmd: 'gradlew.bat', args: ['app:installDebug', '--daemon', '--console=rich'], cwd: androidPath },
|
| { label: 'installRelease', cmd: 'gradlew.bat', args: ['app:installRelease', '--daemon', '--console=rich'], cwd: androidPath },
|
| { label: 'assembleDebug', cmd: 'gradlew.bat', args: ['app:assembleDebug', '--daemon', '--console=rich'], cwd: androidPath },
|
| { label: 'assembleRelease', cmd: 'gradlew.bat', args: ['app:assembleRelease','--daemon', '--console=rich'], cwd: androidPath },
|
| { label: 'clean', cmd: 'gradlew.bat', args: ['clean', '--console=rich'], cwd: androidPath },
|
| { label: 'clean + install', cmd: 'gradlew.bat', args: ['clean','app:installDebug','--daemon', '--console=rich'], cwd: androidPath },
|
| ]
|
| })
|
| groups.push({
|
| label: 'ADB', icon: 'adb', color: '#f39c12',
|
| cmds: [
|
| { label: 'adb devices', cmd: 'adb', args: ['devices'], cwd: root },
|
| { label: 'adb logcat', cmd: 'adb', args: ['logcat'], cwd: root },
|
| { label: 'adb reverse', cmd: 'adb', args: ['reverse','tcp:8081','tcp:8081'], cwd: root },
|
| ]
|
| })
|
| }
|
| }
|
|
|
|
|
| const usedScripts = new Set()
|
| if (isElectron) {
|
| const launcherManagedBuildKeys = ['build-v8', 'build:linux', 'build:linux:wsl']
|
| const buildKeys = ['build','build-win','build-exe','build-v8','build-nsis','build-msi','build:linux','build:linux:wsl','pack','dist']
|
| const scriptedBuildKeys = buildKeys.filter(s => (pkg.scripts || {})[s])
|
| const foundKeys = Array.from(new Set([...launcherManagedBuildKeys, ...scriptedBuildKeys]))
|
| foundKeys.forEach(s => usedScripts.add(s))
|
| if (foundKeys.length) {
|
| groups.push({
|
| label: 'Electron Build', icon: 'electron', color: '#47c4e2',
|
| cmds: foundKeys.map(s => ({ label: prettyCmdLabel('npm', ['run', s]), cmd: 'npm', args: ['run', s], cwd: root }))
|
| })
|
| }
|
| }
|
|
|
|
|
| if (isNext) {
|
| groups.push({
|
| label: 'Next.js', icon: 'nextjs', color: '#ffffff',
|
| cmds: [
|
| { label: prettyCmdLabel('npm', ['run','dev']), cmd: 'npm', args: ['run','dev'], cwd: root },
|
| { label: prettyCmdLabel('npm', ['run','build']), cmd: 'npm', args: ['run','build'], cwd: root },
|
| { label: prettyCmdLabel('npm', ['run','start']), cmd: 'npm', args: ['run','start'], cwd: root },
|
| { label: prettyCmdLabel('npm', ['run','lint']), cmd: 'npm', args: ['run','lint'], cwd: root },
|
| ]
|
| })
|
| }
|
|
|
|
|
| if (isVite) {
|
| groups.push({
|
| label: 'Vite', icon: 'vite', color: '#bd34fe',
|
| cmds: [
|
| { label: prettyCmdLabel('npm', ['run','dev']), cmd: 'npm', args: ['run','dev'], cwd: root },
|
| { label: prettyCmdLabel('npm', ['run','build']), cmd: 'npm', args: ['run','build'], cwd: root },
|
| { label: prettyCmdLabel('npm', ['run','preview']), cmd: 'npm', args: ['run','preview'], cwd: root },
|
| ]
|
| })
|
| }
|
|
|
|
|
| const scripts = pkg.scripts || {}
|
| const skipPrefixes = ['pre', 'post']
|
| const scriptEntries = Object.keys(scripts).filter(s =>
|
| !skipPrefixes.some(p => s.startsWith(p)) && !usedScripts.has(s)
|
| )
|
| if (scriptEntries.length) {
|
| groups.push({
|
| label: 'NPM Scripts', icon: 'scripts', color: '#f7c948',
|
| cmds: scriptEntries.map(s => ({ label: prettyCmdLabel('npm', ['run', s]), cmd: 'npm', args: ['run', s], cwd: root }))
|
| })
|
| }
|
|
|
|
|
| groups.push({
|
| label: 'NPM', icon: 'npm', color: '#e84040',
|
| cmds: [
|
| { label: 'npm install', cmd: 'npm', args: ['install'], cwd: root },
|
| { label: 'npm install --legacy-peer-deps', cmd: 'npm', args: ['install','--legacy-peer-deps'], cwd: root },
|
| { label: 'npm ci', cmd: 'npm', args: ['ci'], cwd: root },
|
| ]
|
| })
|
|
|
| return groups
|
| }
|
|
|
|
|
| ipcMain.handle('get-project', () => {
|
| const runtimeOs = getRuntimeOsStatus()
|
| const root = getEffectiveProjectRoot()
|
| const blockedReason = getRestrictedPathReason(root)
|
| if (blockedReason) {
|
| return {
|
| ok: false,
|
| blocked: true,
|
| error: blockedReason,
|
| projectRoot: root,
|
| isDev,
|
| runtimeOs
|
| }
|
| }
|
| const pkgPath = path.join(root, 'package.json')
|
| try {
|
| const pkg = JSON.parse(fs.readFileSync(pkgPath, 'utf-8'))
|
| const hasAndroid = fs.existsSync(path.join(root, 'android', 'gradlew.bat'))
|
| const typeInfo = isExternalDevOnlyModeForRoot(root)
|
| ? { type: 'npm-dev-only', label: 'NPM Dev Mode', badgeClass: 'badge-npm' }
|
| : detectType(pkg)
|
| const groups = buildCommandGroupsForProject(pkg, root, hasAndroid)
|
| return {
|
| ok: true,
|
| projectRoot: root,
|
| projectName: pkg.name || null,
|
| typeInfo,
|
| groups,
|
| isDev,
|
| runtimeOs,
|
| }
|
| } catch (e) {
|
| return { ok: false, error: e.message, projectRoot: root, isDev, runtimeOs }
|
| }
|
| })
|
|
|
| ipcMain.handle('select-project-folder', async (_, mode = 'full-project') => {
|
| return chooseExternalProjectFolder(mode === 'npm-run-dev-only' ? 'npm-run-dev-only' : 'full-project')
|
| })
|
|
|
| ipcMain.handle('use-launcher-project', () => {
|
| return useLauncherProjectRoot()
|
| })
|
|
|
|
|
| ipcMain.handle('run-cmd', (event, { cmd, args, cwd, streamMode, cols, rows }) => {
|
| killCurrentProc()
|
|
|
| const validated = validateAndNormalizeCommand(cmd, args, cwd)
|
| if (!validated.ok) {
|
| writeAudit('blocked_command', { cmd: String(cmd || ''), args: args || [], cwd: cwd || '', mode: 'main' })
|
| const msg = validated.error
|
| sendToRenderer('proc-out', `\n[ERROR] ${msg}\n`)
|
| sendToRenderer('proc-done', 1)
|
| return { ok: false, error: msg }
|
| }
|
|
|
| const normalizedCmd = validated.normalizedCmd
|
| const normalizedArgs = validated.normalizedArgs
|
| const normalizedCwd = validated.normalizedCwd
|
| currentMainCommandKey = validated.commandHash
|
| const commandLine = validated.rewriteInfo && validated.rewriteInfo.applied
|
| ? getCommandDisplayLine(validated.originalCmd, validated.originalArgs)
|
| : getCommandDisplayLine(normalizedCmd, normalizedArgs)
|
| const rawLogCapture = openRawLogCapture('main', commandLine, currentMainCommandKey)
|
|
|
| if (validated.rewriteInfo && validated.rewriteInfo.applied) {
|
| sendToRenderer('proc-out', `[INFO] Rewriting ${validated.originalCmd} ${validated.originalArgs.join(' ')} via launcher (${validated.rewriteInfo.kind})\n`)
|
| if (validated.rewriteInfo.launcherScriptPath) {
|
| sendToRenderer('proc-out', `[INFO] Launcher script: ${validated.rewriteInfo.launcherScriptPath}\n`)
|
| }
|
| sendToRenderer('proc-out', `[INFO] Target project: ${validated.rewriteInfo.targetProjectPath}\n`)
|
| }
|
| if (rawLogCapture.filePath) {
|
| sendToRenderer('proc-out', `[INFO] Raw log file: ${rawLogCapture.filePath}\n`)
|
| }
|
|
|
| writeAudit('run_command', {
|
| cmd: normalizedCmd,
|
| args: normalizedArgs,
|
| cwd: normalizedCwd,
|
| mode: 'main',
|
| originalCmd: validated.originalCmd,
|
| originalArgs: validated.originalArgs,
|
| originalCwd: validated.originalCwd,
|
| rewrite: validated.rewriteInfo
|
| })
|
|
|
| const started = spawnPtyWithStreaming({
|
| normalizedCmd,
|
| normalizedArgs,
|
| normalizedCwd,
|
| streamMode,
|
| cols,
|
| rows,
|
| onOutput: (text) => {
|
| rawLogCapture.append(text)
|
| sendToRenderer('proc-out', text)
|
| },
|
| onDone: (exitCode) => {
|
| rawLogCapture.close()
|
| currentProc = null
|
| currentProcKind = null
|
| currentMainCommandKey = null
|
| setImmediate(() => sendToRenderer('proc-done', exitCode ?? 0))
|
| },
|
| onError: (message) => {
|
| rawLogCapture.close()
|
| sendToRenderer('proc-out', `\n[ERROR] Failed to start PTY: ${message}\n`)
|
| sendToRenderer('proc-done', 1)
|
| currentMainCommandKey = null
|
| writeAudit('run_command_error', { cmd: normalizedCmd, cwd: normalizedCwd, mode: 'main', error: message })
|
| },
|
| onStarted: (proc) => {
|
| currentProc = proc
|
| currentProcKind = 'pty'
|
| },
|
| auditMeta: { mode: 'main' },
|
| envOverrides: validated.envOverrides
|
| })
|
|
|
| if (!started || !started.proc) {
|
| return { ok: false, error: 'Failed to start process' }
|
| }
|
|
|
| return { ok: true, pid: started.proc.pid, mode: 'main', cmdKey: currentMainCommandKey }
|
| })
|
|
|
| ipcMain.handle('run-cmd-popup', (_, payload) => {
|
| return startPopupCommand(payload || {})
|
| })
|
|
|
| ipcMain.handle('open-devtools-for-command', (_, payload) => {
|
| if (!isDev) {
|
| return { ok: false, error: 'DevTools are disabled in packaged builds' }
|
| }
|
| const cmd = payload && payload.cmd
|
| const args = payload && payload.args
|
| if (!isNpmRunDevCommand(cmd, args)) {
|
| return { ok: false, error: 'DevTools can only be opened for npm run dev' }
|
| }
|
| if (!win || win.isDestroyed()) {
|
| return { ok: false, error: 'Main window is not available' }
|
| }
|
| try {
|
| win.webContents.openDevTools({ mode: 'detach', activate: true })
|
| void writeAudit('open_devtools_for_command', { cmd: String(cmd || ''), args: args || [] })
|
| return { ok: true }
|
| } catch (e) {
|
| return { ok: false, error: e && e.message ? e.message : 'Failed to open DevTools' }
|
| }
|
| })
|
|
|
| ipcMain.handle('open-main-devtools', () => {
|
| if (!isDev) {
|
| return { ok: false, error: 'DevTools are disabled in packaged builds' }
|
| }
|
| if (!win || win.isDestroyed()) {
|
| return { ok: false, error: 'Main window is not available' }
|
| }
|
| try {
|
| win.webContents.openDevTools({ mode: 'detach', activate: true })
|
| return { ok: true }
|
| } catch (e) {
|
| return { ok: false, error: e && e.message ? e.message : 'Failed to open main DevTools' }
|
| }
|
| })
|
|
|
| ipcMain.handle('open-popup-devtools', () => {
|
| if (!isDev) {
|
| return { ok: false, error: 'DevTools are disabled in packaged builds' }
|
| }
|
| const ctx = getPreferredPopupContext()
|
| if (!ctx || !ctx.win || ctx.win.isDestroyed()) {
|
| return { ok: false, error: 'No active popup terminal' }
|
| }
|
| try {
|
| ctx.win.webContents.openDevTools({ mode: 'detach', activate: true })
|
| return { ok: true, runId: ctx.runId }
|
| } catch (e) {
|
| return { ok: false, error: e && e.message ? e.message : 'Failed to open popup DevTools' }
|
| }
|
| })
|
|
|
| ipcMain.handle('get-dev-security-status', () => {
|
| if (!isDev) {
|
| return {
|
| ok: true,
|
| appMode: 'packaged',
|
| requestGuardInstalled,
|
| externalRequestBlockActive: true,
|
| shortcutDevtoolsBlockedInProduction: true,
|
| mainWindowDevtoolsCapable: false,
|
| popupWindowDevtoolsCapable: false,
|
| popupCspInlineStyleAllowed: false,
|
| popupRunCount: 0,
|
| securityNote: 'Dev mode features are disabled in packaged builds.'
|
| }
|
| }
|
| const popupCsp = readPopupCspStatus()
|
| const activePopupCount = Array.from(popupRuns.values()).filter(ctx => ctx && ctx.win && !ctx.win.isDestroyed()).length
|
| return {
|
| ok: true,
|
| appMode: isDev ? 'dev' : 'packaged',
|
| requestGuardInstalled,
|
| externalRequestBlockActive: !isDev,
|
| shortcutDevtoolsBlockedInProduction: !isDev,
|
| mainWindowDevtoolsCapable: true,
|
| popupWindowDevtoolsCapable: true,
|
| popupCspInlineStyleAllowed: popupCsp.hasUnsafeInlineStyle,
|
| popupRunCount: activePopupCount,
|
| securityNote: 'DevTools open via button is allowed. Keyboard shortcuts remain blocked in production.'
|
| }
|
| })
|
|
|
|
|
| ipcMain.handle('kill-proc', () => {
|
| if (!currentProc) return false
|
| killCurrentProc()
|
| sendToRenderer('proc-done', -1)
|
| return true
|
| })
|
|
|
| ipcMain.handle('resize-proc-pty', (_, size) => {
|
| if (!currentProc || currentProcKind !== 'pty' || typeof currentProc.resize !== 'function') {
|
| return false
|
| }
|
| const cols = Number(size && size.cols)
|
| const rows = Number(size && size.rows)
|
| if (!Number.isFinite(cols) || !Number.isFinite(rows)) return false
|
|
|
| const safeCols = Math.max(20, Math.floor(cols))
|
| const safeRows = Math.max(5, Math.floor(rows))
|
| try {
|
| currentProc.resize(safeCols, safeRows)
|
| return true
|
| } catch {
|
| return false
|
| }
|
| })
|
|
|
| ipcMain.handle('popup-kill', (_, { runId }) => {
|
| const rid = String(runId || '')
|
| for (const ctx of popupRuns.values()) {
|
| if (!ctx || ctx.runId !== rid) continue
|
| killProcessObject(ctx.proc, ctx.procKind)
|
| return true
|
| }
|
| return false
|
| })
|
|
|
| ipcMain.handle('popup-resize', (_, { runId, cols, rows }) => {
|
| const rid = String(runId || '')
|
| const safeCols = Math.max(20, Math.floor(Number(cols || 0)))
|
| const safeRows = Math.max(5, Math.floor(Number(rows || 0)))
|
| if (!Number.isFinite(safeCols) || !Number.isFinite(safeRows)) return false
|
|
|
| for (const ctx of popupRuns.values()) {
|
| if (!ctx || ctx.runId !== rid) continue
|
| if (!ctx.proc || ctx.procKind !== 'pty' || typeof ctx.proc.resize !== 'function') return false
|
| try {
|
| ctx.proc.resize(safeCols, safeRows)
|
| return true
|
| } catch {
|
| return false
|
| }
|
| }
|
| return false
|
| })
|
|
|
| ipcMain.handle('open-external', (_, url) => {
|
| const checked = sanitizeExternalUrl(url)
|
| if (!checked.ok) {
|
| writeAudit('blocked_open_external', { reason: checked.error, requested: String(url || '') })
|
| return false
|
| }
|
| writeAudit('open_external', { host: checked.host })
|
| shell.openExternal(checked.url)
|
| return true
|
| })
|
|
|
| ipcMain.handle('r2-get-config-status', () => {
|
| return { ok: false, error: 'R2 moved to dedicated app: chahuadev-R2' }
|
| })
|
|
|
| ipcMain.handle('r2-save-config', (_, cfg) => {
|
| return { ok: false, error: 'R2 moved to dedicated app: chahuadev-R2' }
|
| })
|
|
|
| ipcMain.handle('r2-test-config', (_, cfg) => {
|
| return { ok: false, error: 'R2 moved to dedicated app: chahuadev-R2' }
|
| })
|
|
|
| ipcMain.handle('r2-clear-config', () => {
|
| return { ok: true }
|
| })
|
|
|
| ipcMain.handle('r2-suggest-target', () => {
|
| return { ok: false, error: 'R2 moved to dedicated app: chahuadev-R2' }
|
| })
|
|
|
| ipcMain.handle('r2-upload-dist', (_, { target }) => {
|
| sendToRenderer('proc-out', '\n[ERROR] R2 moved to dedicated app: chahuadev-R2\n')
|
| sendToRenderer('proc-done', 1)
|
| return { ok: false, error: 'R2 moved to dedicated app: chahuadev-R2' }
|
| })
|
|
|
|
|