From dbee0cc891acaf525fefc54840c8f23b9cbe2950 Mon Sep 17 00:00:00 2001 From: Anders Alm Date: Sat, 7 Nov 2026 21:01:43 -0500 Subject: [PATCH 01/19] Build the Linux ARM64 launcher on the Ubuntu 22.04 runner. The Jetson uses glibc 2.35, and the bundled fpm binary is x86. Co-authored-by: Cursor --- .github/workflows/build.yml | 6 ++- .github/workflows/linux-arm64.yml | 59 +++++++++++++++++++++++++ .github/workflows/runtime-smoke.yml | 13 ++++-- package.json | 14 ++++++ scripts/electron-e2e.js | 5 ++- scripts/linux-lifecycle-e2e.js | 56 ++++++++++++++++++++++++ src/main/index.ts | 1 + test/installer-ux.test.js | 1 + test/linux-arm64.test.js | 67 +++++++++++++++++++++++++++++ 9 files changed, 217 insertions(+), 5 deletions(-) create mode 100644 .github/workflows/linux-arm64.yml create mode 100644 scripts/linux-lifecycle-e2e.js create mode 100644 test/linux-arm64.test.js diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 42e9242..1f6c7b0 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -86,8 +86,12 @@ jobs: dist-electron/*.deb if-no-files-found: error + linux-arm64: + if: startsWith(github.ref, 'refs/tags/') || github.event_name == 'workflow_dispatch' + uses: ./.github/workflows/linux-arm64.yml + release: - needs: build + needs: [build, linux-arm64] runs-on: ubuntu-latest if: startsWith(github.ref, 'refs/tags/') diff --git a/.github/workflows/linux-arm64.yml b/.github/workflows/linux-arm64.yml new file mode 100644 index 0000000..51eaff5 --- /dev/null +++ b/.github/workflows/linux-arm64.yml @@ -0,0 +1,59 @@ +name: Linux ARM64 package + +# Ubuntu 22.04 matches the Jetson glibc (2.35). app-builder ships an x86 fpm +# for every non-amd64 CPU, so the deb is built with the system fpm. +on: + pull_request: + workflow_dispatch: + workflow_call: + +permissions: + contents: read + +jobs: + package: + runs-on: ubuntu-22.04-arm + timeout-minutes: 90 + steps: + - name: Checkout code + uses: actions/checkout@v4 + + - name: Setup Node.js + uses: actions/setup-node@v4 + with: + node-version: '20' + cache: npm + + - name: Install dependencies + run: npm ci + + - name: Install system fpm + run: | + set -euo pipefail + sudo apt-get update + sudo apt-get install -y ruby ruby-dev ruby-rubygems build-essential + sudo gem install fpm --no-document + command -v fpm + fpm --version + + - name: Build the arm64 AppImage and deb + env: + USE_SYSTEM_FPM: "true" + APPIMAGE_EXTRACT_AND_RUN: "1" + run: npm run build:linux -- --arm64 --publish never + + - name: Record checksums + run: | + set -euo pipefail + sha256sum dist-electron/*.AppImage dist-electron/*.deb + test -n "$(find dist-electron -maxdepth 1 -name '*arm64*.AppImage' -print)" + test -n "$(find dist-electron -maxdepth 1 -name '*arm64*.deb' -print)" + + - name: Upload the arm64 packages + uses: actions/upload-artifact@v4 + with: + name: ElastOS-linux-arm64 + path: | + dist-electron/*.AppImage + dist-electron/*.deb + if-no-files-found: error diff --git a/.github/workflows/runtime-smoke.yml b/.github/workflows/runtime-smoke.yml index f83efd8..03adc6d 100644 --- a/.github/workflows/runtime-smoke.yml +++ b/.github/workflows/runtime-smoke.yml @@ -1,6 +1,6 @@ name: Runtime smoke -# Linux x64, macOS arm64, and the ElastOS WSL2 distro are required. +# Linux x64, Linux arm64, macOS arm64, and the ElastOS WSL2 distro are required. # A red run fails the pull request. Each job verifies the selected channel # against the maintainer DID and rollback floor. Failed verification means # install stops. The job then checks gateway /healthz and @@ -21,6 +21,8 @@ jobs: platform: linux-x64 - os: macos-14 platform: darwin-arm64 + - os: ubuntu-22.04-arm + platform: linux-arm64 runs-on: ${{ matrix.os }} steps: - name: Checkout code @@ -54,15 +56,20 @@ jobs: electron-e2e: name: e2e (${{ matrix.platform }}) - timeout-minutes: 40 + timeout-minutes: 50 strategy: fail-fast: false matrix: include: - os: ubuntu-24.04 platform: linux-x64 + packages: xvfb libnss3 libatk1.0-0 libatk-bridge2.0-0 libcups2 libdrm2 libxkbcommon0 libxcomposite1 libxdamage1 libxfixes3 libxrandr2 libgbm1 libasound2t64 libgtk-3-0t64 libxss1 + - os: ubuntu-22.04-arm + platform: linux-arm64 + packages: xvfb libnss3 libatk1.0-0 libatk-bridge2.0-0 libcups2 libdrm2 libxkbcommon0 libxcomposite1 libxdamage1 libxfixes3 libxrandr2 libgbm1 libasound2 libgtk-3-0 libxss1 libayatana-appindicator3-1 - os: macos-14 platform: darwin-arm64 + packages: "" runs-on: ${{ matrix.os }} steps: - name: Checkout code @@ -78,7 +85,7 @@ jobs: if: runner.os == 'Linux' run: | sudo apt-get update - sudo apt-get install -y xvfb libnss3 libatk1.0-0 libatk-bridge2.0-0 libcups2 libdrm2 libxkbcommon0 libxcomposite1 libxdamage1 libxfixes3 libxrandr2 libgbm1 libasound2t64 libgtk-3-0t64 libxss1 + sudo apt-get install -y ${{ matrix.packages }} - name: Install dependencies env: diff --git a/package.json b/package.json index 13227c2..f460eba 100644 --- a/package.json +++ b/package.json @@ -70,6 +70,20 @@ ], "category": "Utility" }, + "deb": { + "depends": [ + "libgtk-3-0", + "libnotify4", + "libnss3", + "libxss1", + "libxtst6", + "xdg-utils", + "libatspi2.0-0", + "libuuid1", + "libsecret-1-0", + "libayatana-appindicator3-1" + ] + }, "afterAllArtifactBuild": "scripts/notarize.js", "extraResources": [ { diff --git a/scripts/electron-e2e.js b/scripts/electron-e2e.js index 8a19141..eb849ec 100644 --- a/scripts/electron-e2e.js +++ b/scripts/electron-e2e.js @@ -213,6 +213,9 @@ async function main() { executablePath: electronPath, cwd: root, args, env, timeout: 120000, }); } + if (process.platform === 'linux') { + await require('./linux-lifecycle-e2e')(electronApp, page, home); + } return; } if (errorVisible && errorText && /Set up ElastOS on Windows|Windows needs Linux support|Windows needs one step/.test(errorText)) { @@ -287,7 +290,7 @@ async function main() { } } -const capMs = process.platform === 'win32' ? 50 * 60 * 1000 : 35 * 60 * 1000; +const capMs = process.platform === 'win32' ? 50 * 60 * 1000 : process.platform === 'linux' ? 45 * 60 * 1000 : 35 * 60 * 1000; setTimeout(() => { console.error(`e2e did not finish within ${capMs / 60000} minutes`); process.exit(1); diff --git a/scripts/linux-lifecycle-e2e.js b/scripts/linux-lifecycle-e2e.js new file mode 100644 index 0000000..95181af --- /dev/null +++ b/scripts/linux-lifecycle-e2e.js @@ -0,0 +1,56 @@ +const assert = require('node:assert/strict'); +const fs = require('node:fs'); +const path = require('node:path'); +const { isHealthOk, probeGatewayHealth } = require('../dist/main/targets/runtimeGateway'); + +async function health(wanted) { + const deadline = Date.now() + 180000; + while (Date.now() < deadline) { + if (isHealthOk(await probeGatewayHealth()) === wanted) return; + await new Promise((resolve) => setTimeout(resolve, 500)); + } + throw new Error(`Home health did not become ${wanted}`); +} + +async function status(page, wanted) { + await page.waitForFunction(async (next) => await window.elastos.getStatus() === next, wanted, { timeout: 180000 }); + await page.waitForFunction((next) => document.querySelector('#status-text').textContent.toLowerCase() === next, wanted, { timeout: 10000 }); +} + +module.exports = async function (app, page, home) { + assert.equal(await app.evaluate(() => global.__elastosTray), true); + console.log('PASS the tray icon is ready'); + + await app.evaluate(({ shell }) => { + global.__openedHome = []; + shell.openExternal = async (url) => { global.__openedHome.push(url); }; + }); + await page.click('#open-btn'); + assert.deepEqual(await app.evaluate(() => global.__openedHome), ['http://localhost:8090/home/']); + const response = await fetch('http://localhost:8090/home/'); + assert.equal(response.status, 200); + console.log('PASS Open Home invokes the browser with localhost:8090/home/ and Home returns HTTP 200'); + + await app.evaluate(({ BrowserWindow }) => BrowserWindow.getAllWindows()[0].close()); + await new Promise((resolve) => setTimeout(resolve, 2500)); + assert.equal(await app.evaluate(({ BrowserWindow }) => BrowserWindow.getAllWindows()[0].isVisible()), false); + await health(true); + console.log('PASS closing the window keeps Home running'); + await app.evaluate(({ BrowserWindow }) => BrowserWindow.getAllWindows()[0].show()); + + await page.click('#power-btn'); + await status(page, 'stopped'); + await health(false); + console.log('PASS Stop Home closes the listener'); + await page.click('#open-btn'); + await status(page, 'running'); + await health(true); + console.log('PASS Start Home becomes healthy'); + + const checked = await page.evaluate(() => window.elastos.checkForUpdate()); + assert.equal(checked.updateAvailable, false); + const data = path.join(home, '.local', 'share', 'elastos'); + const update = JSON.parse(fs.readFileSync(path.join(data, 'update-check.json'), 'utf8')); + assert.equal(update.outcome, 'up_to_date'); + console.log('PASS elastos update --check writes up_to_date'); +}; diff --git a/src/main/index.ts b/src/main/index.ts index 8ef3f10..be5d57d 100644 --- a/src/main/index.ts +++ b/src/main/index.ts @@ -96,6 +96,7 @@ function createTray(): void { } tray = new Tray(icon.resize({ width: 16, height: 16 })); + (global as typeof globalThis & { __elastosTray?: true }).__elastosTray = true; tray.setToolTip('ElastOS'); updateTrayMenu(); diff --git a/test/installer-ux.test.js b/test/installer-ux.test.js index e300494..f3dc96c 100644 --- a/test/installer-ux.test.js +++ b/test/installer-ux.test.js @@ -102,6 +102,7 @@ test('sign-in launch writes a desktop file and can remove it', () => { }; const written = syncLinuxAutostart(true, '/home/tester', '/usr/bin/elastos', fs); assert.match(files.get(written), /Name=ElastOS/); + assert.match(files.get(written), /X-GNOME-Autostart-enabled=true/); assert.match(linuxAutostartFile('/usr/bin/elastos'), /Exec=\/usr\/bin\/elastos/); assert.equal(syncLinuxAutostart(false, '/home/tester', '/usr/bin/elastos', fs), null); assert.equal(files.size, 0); diff --git a/test/linux-arm64.test.js b/test/linux-arm64.test.js new file mode 100644 index 0000000..be90ceb --- /dev/null +++ b/test/linux-arm64.test.js @@ -0,0 +1,67 @@ +const assert = require('node:assert/strict'); +const fs = require('node:fs'); +const path = require('node:path'); +const test = require('node:test'); + +const root = path.join(__dirname, '..'); + +const DEB_DEPENDS = [ + 'libgtk-3-0', + 'libnotify4', + 'libnss3', + 'libxss1', + 'libxtst6', + 'xdg-utils', + 'libatspi2.0-0', + 'libuuid1', + 'libsecret-1-0', + 'libayatana-appindicator3-1', +]; + +test('the arm64 package job uses the Jetson glibc and a system fpm', () => { + const workflow = fs.readFileSync(path.join(root, '.github/workflows/linux-arm64.yml'), 'utf8'); + const build = fs.readFileSync(path.join(root, '.github/workflows/build.yml'), 'utf8'); + assert.match(workflow, /pull_request:/); + assert.match(workflow, /runs-on: ubuntu-22\.04-arm/); + assert.match(workflow, /USE_SYSTEM_FPM/); + assert.match(workflow, /--arm64/); + assert.match(workflow, /APPIMAGE_EXTRACT_AND_RUN/); + assert.match(build, /uses: \.\/\.github\/workflows\/linux-arm64\.yml/); + assert.match(build, /needs: \[build, linux-arm64\]/); +}); + +test('runtime smoke and electron e2e have a linux-arm64 row on Ubuntu 22.04', () => { + const workflow = fs.readFileSync(path.join(root, '.github/workflows/runtime-smoke.yml'), 'utf8'); + assert.match(workflow, /ubuntu-24\.04/); + assert.match(workflow, /libasound2t64 libgtk-3-0t64/); + const armRows = workflow.match(/os: ubuntu-22\.04-arm\n\s+platform: linux-arm64/g) || []; + assert.equal(armRows.length, 2); + const armPackages = workflow.match(/os: ubuntu-22\.04-arm\n\s+platform: linux-arm64\n\s+packages: (.*)/); + assert.ok(armPackages, 'linux-arm64 e2e package list'); + assert.equal(armPackages[1].includes('t64'), false); + assert.match(armPackages[1], /libasound2 libgtk-3-0 libxss1 libayatana-appindicator3-1/); +}); + +test('the deb depends keep the electron-builder defaults and add the tray library', () => { + const pkg = JSON.parse(fs.readFileSync(path.join(root, 'package.json'), 'utf8')); + assert.deepEqual(pkg.build.deb.depends, DEB_DEPENDS); +}); + +test('linux e2e runs the linux lifecycle and leaves the mac lifecycle on darwin', () => { + const e2e = fs.readFileSync(path.join(root, 'scripts/electron-e2e.js'), 'utf8'); + const life = fs.readFileSync(path.join(root, 'scripts/linux-lifecycle-e2e.js'), 'utf8'); + assert.match(e2e, /process\.platform === 'darwin'/); + assert.match(e2e, /mac-lifecycle-e2e/); + assert.match(e2e, /process\.platform === 'linux'/); + assert.match(e2e, /linux-lifecycle-e2e/); + assert.match(life, /PASS Open Home/); + assert.match(life, /PASS closing the window keeps Home running/); + assert.match(life, /PASS Stop Home closes the listener/); + assert.match(life, /PASS Start Home becomes healthy/); + assert.match(life, /PASS elastos update --check writes up_to_date/); + assert.match(life, /PASS the tray icon is ready/); + assert.match(life, /__elastosTray/); + assert.equal(life.includes('Application Support'), false); + assert.equal(life.includes('home --browser'), false); + assert.match(life, /\.local', 'share', 'elastos'/); +}); From e449e36177b9f7e111d6353d9e2566a8ec0e0b44 Mon Sep 17 00:00:00 2001 From: Anders Alm Date: Sat, 7 Nov 2026 21:07:33 -0500 Subject: [PATCH 02/19] Use electron-builder's arm64 fpm for the Jetson package. Version 26.16.1 already downloads fpm-1.17.0-ruby-3.4.3-linux-arm64v8, so the system fpm install is obsolete. Co-authored-by: Cursor --- .github/workflows/linux-arm64.yml | 15 +-------------- .github/workflows/runtime-smoke.yml | 1 - scripts/linux-lifecycle-e2e.js | 3 --- src/main/index.ts | 3 --- test/linux-arm64.test.js | 11 ++++++----- 5 files changed, 7 insertions(+), 26 deletions(-) diff --git a/.github/workflows/linux-arm64.yml b/.github/workflows/linux-arm64.yml index 51eaff5..d1a87d8 100644 --- a/.github/workflows/linux-arm64.yml +++ b/.github/workflows/linux-arm64.yml @@ -1,7 +1,6 @@ name: Linux ARM64 package -# Ubuntu 22.04 matches the Jetson glibc (2.35). app-builder ships an x86 fpm -# for every non-amd64 CPU, so the deb is built with the system fpm. +# Ubuntu 22.04 matches the Jetson glibc (2.35). on: pull_request: workflow_dispatch: @@ -27,19 +26,7 @@ jobs: - name: Install dependencies run: npm ci - - name: Install system fpm - run: | - set -euo pipefail - sudo apt-get update - sudo apt-get install -y ruby ruby-dev ruby-rubygems build-essential - sudo gem install fpm --no-document - command -v fpm - fpm --version - - name: Build the arm64 AppImage and deb - env: - USE_SYSTEM_FPM: "true" - APPIMAGE_EXTRACT_AND_RUN: "1" run: npm run build:linux -- --arm64 --publish never - name: Record checksums diff --git a/.github/workflows/runtime-smoke.yml b/.github/workflows/runtime-smoke.yml index 2cd9ea1..d867971 100644 --- a/.github/workflows/runtime-smoke.yml +++ b/.github/workflows/runtime-smoke.yml @@ -1,6 +1,5 @@ name: Runtime smoke -# Linux x64, Linux arm64, macOS arm64, and the ElastOS WSL2 distro are required. # A red run fails the pull request. Each job verifies the selected channel # against the maintainer DID and rollback floor. Failed verification means # install stops. The job then checks gateway /healthz and diff --git a/scripts/linux-lifecycle-e2e.js b/scripts/linux-lifecycle-e2e.js index 21aac52..76aa190 100644 --- a/scripts/linux-lifecycle-e2e.js +++ b/scripts/linux-lifecycle-e2e.js @@ -29,9 +29,6 @@ async function status(page, wanted) { } module.exports = async function (app, page, home) { - assert.equal(await app.evaluate(() => global.__elastosTray), true); - console.log('PASS the tray icon is ready'); - await app.evaluate(({ shell }) => { global.__openedHome = []; shell.openExternal = async (url) => { global.__openedHome.push(url); }; diff --git a/src/main/index.ts b/src/main/index.ts index be5d57d..d2be04f 100644 --- a/src/main/index.ts +++ b/src/main/index.ts @@ -77,14 +77,12 @@ function createWindow(): void { } function createTray(): void { - // Simple tray icon const iconPath = path.join(__dirname, '../../resources/icon.png'); let icon: Electron.NativeImage; try { icon = nativeImage.createFromPath(iconPath); if (icon.isEmpty()) { - // Fallback to a simple icon icon = nativeImage.createFromDataURL( 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAABHNCSVQICAgIfAhkiAAAAAlwSFlzAAAA7AAAAOwBeShxvQAAABl0RVh0U29mdHdhcmUAd3d3Lmlua3NjYXBlLm9yZ5vuPBoAAAH5SURBVFiF7Ze/axRBFMc/M7t3yUWjhYVYiI2NjQERbfwPrGxEOwsLsRAsLPwPbGwsxMbKQrCwEWzEQrDQRhALC8FCCYiIRuNdkuzujsXu3e7l7nKXM+D3wzDM8N7MZ+a9NzOQUXAIGAN2s+0CtXBkCfgD/AJ+ArPAT2ANWBdRFXgEZuUmcAEodshrA5yECcBTcBB4BZwGfOAZ8ETESv+X+i5wEbiY9H0Z2AmMA/uTvieqGuvpxfMYOJbSrqvOIEACMpAJSAJeAF5S9gM2U2OaAYmqhcAz8BpoBc+BzuuLdEiKZrLMSj0B7JIGFQK1wBM/xhp05QfsBKoNYC8wDzzvFyQJiCeJN8DFaJHXxXJV1tQ68IaYcLrpDyLoJ5APvCOLCRwNVCcJYy2wyQs7KiZlJuoB79oj/wBwtXNOtfYmGIrLWpLK+w5c60UYTANFJOsYcKRPCHPAAWASeMojwChWBxTpFrKu2vQC4BlwyUeFE0KxP0AqYT3JQE+B4SSwH6hnQAFYBO6JqPQKkQZYS5bXgccitP8N/oEKMCGi3C/IEPARuNcvRIb+yO4nngvMAe+Tzr5BkoBBYDfwot9qSOsUyxUNjQ8i6sMggmRoD7nHI/+wHTAGPBNR7hciCRj6LpjCxBpw00d5nyAZGgT2AEv/M/4vmHGRlTWP0ioAAAAASUVORK5CYII=' ); @@ -96,7 +94,6 @@ function createTray(): void { } tray = new Tray(icon.resize({ width: 16, height: 16 })); - (global as typeof globalThis & { __elastosTray?: true }).__elastosTray = true; tray.setToolTip('ElastOS'); updateTrayMenu(); diff --git a/test/linux-arm64.test.js b/test/linux-arm64.test.js index be90ceb..e06ddc5 100644 --- a/test/linux-arm64.test.js +++ b/test/linux-arm64.test.js @@ -18,14 +18,15 @@ const DEB_DEPENDS = [ 'libayatana-appindicator3-1', ]; -test('the arm64 package job uses the Jetson glibc and a system fpm', () => { +test('the arm64 package job uses the Jetson glibc and the bundled fpm', () => { const workflow = fs.readFileSync(path.join(root, '.github/workflows/linux-arm64.yml'), 'utf8'); const build = fs.readFileSync(path.join(root, '.github/workflows/build.yml'), 'utf8'); assert.match(workflow, /pull_request:/); assert.match(workflow, /runs-on: ubuntu-22\.04-arm/); - assert.match(workflow, /USE_SYSTEM_FPM/); assert.match(workflow, /--arm64/); - assert.match(workflow, /APPIMAGE_EXTRACT_AND_RUN/); + assert.equal(workflow.includes('USE_SYSTEM_FPM'), false); + assert.equal(workflow.includes('APPIMAGE_EXTRACT_AND_RUN'), false); + assert.equal(workflow.includes('gem install fpm'), false); assert.match(build, /uses: \.\/\.github\/workflows\/linux-arm64\.yml/); assert.match(build, /needs: \[build, linux-arm64\]/); }); @@ -59,8 +60,8 @@ test('linux e2e runs the linux lifecycle and leaves the mac lifecycle on darwin' assert.match(life, /PASS Stop Home closes the listener/); assert.match(life, /PASS Start Home becomes healthy/); assert.match(life, /PASS elastos update --check writes up_to_date/); - assert.match(life, /PASS the tray icon is ready/); - assert.match(life, /__elastosTray/); + assert.equal(life.includes('waitForFunction'), false); + assert.equal(life.includes('__elastosTray'), false); assert.equal(life.includes('Application Support'), false); assert.equal(life.includes('home --browser'), false); assert.match(life, /\.local', 'share', 'elastos'/); From bb7d4b6e48fbec31cb417300f94209de34d5f292 Mon Sep 17 00:00:00 2001 From: Anders Alm Date: Sat, 7 Nov 2026 21:15:30 -0500 Subject: [PATCH 03/19] Read a 2.0.0 update check from the command text when the status file is absent. Co-authored-by: Cursor --- scripts/linux-lifecycle-e2e.js | 9 ++------- src/main/targets/runtimeUpdate.ts | 23 ++++++++++++++++++++++- test/linux-arm64.test.js | 4 ++-- test/runtime-update.test.js | 29 +++++++++++++++++++++++++++++ 4 files changed, 55 insertions(+), 10 deletions(-) diff --git a/scripts/linux-lifecycle-e2e.js b/scripts/linux-lifecycle-e2e.js index 76aa190..d5182a8 100644 --- a/scripts/linux-lifecycle-e2e.js +++ b/scripts/linux-lifecycle-e2e.js @@ -1,6 +1,4 @@ const assert = require('node:assert/strict'); -const fs = require('node:fs'); -const path = require('node:path'); const { isHealthOk, probeGatewayHealth } = require('../dist/main/targets/runtimeGateway'); async function health(wanted) { @@ -28,7 +26,7 @@ async function status(page, wanted) { 10000, `Window status did not become ${wanted}`); } -module.exports = async function (app, page, home) { +module.exports = async function (app, page) { await app.evaluate(({ shell }) => { global.__openedHome = []; shell.openExternal = async (url) => { global.__openedHome.push(url); }; @@ -57,8 +55,5 @@ module.exports = async function (app, page, home) { const checked = await page.evaluate(() => window.elastos.checkForUpdate()); assert.equal(checked.updateAvailable, false); - const data = path.join(home, '.local', 'share', 'elastos'); - const update = JSON.parse(fs.readFileSync(path.join(data, 'update-check.json'), 'utf8')); - assert.equal(update.outcome, 'up_to_date'); - console.log('PASS elastos update --check writes up_to_date'); + console.log('PASS elastos update --check reports up to date'); }; diff --git a/src/main/targets/runtimeUpdate.ts b/src/main/targets/runtimeUpdate.ts index 95a518d..9dc9411 100644 --- a/src/main/targets/runtimeUpdate.ts +++ b/src/main/targets/runtimeUpdate.ts @@ -58,6 +58,27 @@ export function parseUpdateCheckStatus(raw: string): ParsedUpdateCheck { }; } +/** Runtime 2.0.0 prints the result and does not write update-check.json. */ +export function parseUpdateCheckText(stdout: string): ParsedUpdateCheck { + const latestMatch = stdout.match(/^\s*Latest available:\s*(\S+)\s*$/m); + const installedMatch = stdout.match(/^\s*Installed release:\s*(\S+)\s*$/m); + const latest = latestMatch ? latestMatch[1] : null; + const installed = installedMatch && installedMatch[1] !== 'unknown' ? installedMatch[1] : null; + if (/^\s*Installed release is up to date\.\s*$/m.test(stdout)) { + const version = installed || latest || ''; + return { + updateAvailable: false, + detail: version, + latest: latest || installed, + }; + } + if (/Run `elastos update` to install\./.test(stdout)) { + if (!latest) throw new Error(UPDATE_STATUS_UNREADABLE); + return { updateAvailable: true, detail: latest, latest }; + } + throw new Error(UPDATE_STATUS_UNREADABLE); +} + export function parseHeadCid(stdout: string): string | null { for (const line of stdout.split(/\r?\n/)) { const match = line.match(/^\s*Head CID:\s*(\S+)/); @@ -102,7 +123,7 @@ export async function checkRuntimeUpdate( try { raw = readStatus(); } catch { - throw new Error(UPDATE_STATUS_UNREADABLE); + return parseUpdateCheckText(result.stdout); } return parseUpdateCheckStatus(raw); } diff --git a/test/linux-arm64.test.js b/test/linux-arm64.test.js index e06ddc5..419285e 100644 --- a/test/linux-arm64.test.js +++ b/test/linux-arm64.test.js @@ -59,10 +59,10 @@ test('linux e2e runs the linux lifecycle and leaves the mac lifecycle on darwin' assert.match(life, /PASS closing the window keeps Home running/); assert.match(life, /PASS Stop Home closes the listener/); assert.match(life, /PASS Start Home becomes healthy/); - assert.match(life, /PASS elastos update --check writes up_to_date/); + assert.match(life, /PASS elastos update --check reports up to date/); + assert.equal(life.includes('update-check.json'), false); assert.equal(life.includes('waitForFunction'), false); assert.equal(life.includes('__elastosTray'), false); assert.equal(life.includes('Application Support'), false); assert.equal(life.includes('home --browser'), false); - assert.match(life, /\.local', 'share', 'elastos'/); }); diff --git a/test/runtime-update.test.js b/test/runtime-update.test.js index 4919d91..5e6a137 100644 --- a/test/runtime-update.test.js +++ b/test/runtime-update.test.js @@ -95,6 +95,35 @@ test('update --check is read from the status file, not from stdout or the exit c assert.equal(readOnFailure, false); }); +test('update --check reads the runtime text when the status file is absent', async () => { + const current = await checkRuntimeUpdate(async () => ({ + code: 0, + stdout: ' Latest available: 2.0.0\n Installed release: 2.0.0\n\n Installed release is up to date.\n', + stderr: '', + }), () => { + throw new Error('ENOENT'); + }); + assert.equal(current.updateAvailable, false); + assert.equal(current.latest, '2.0.0'); + + const newer = await checkRuntimeUpdate(async () => ({ + code: 0, + stdout: ' Latest available: 2.1.0\n Installed release: 2.0.0\n\n Run `elastos update` to install.\n', + stderr: '', + }), () => { + throw new Error('ENOENT'); + }); + assert.equal(newer.updateAvailable, true); + assert.equal(newer.latest, '2.1.0'); + + await assert.rejects( + () => checkRuntimeUpdate(async () => ({ code: 0, stdout: 'no report\n', stderr: '' }), () => { + throw new Error('ENOENT'); + }), + /not readable/, + ); +}); + test('update stores only a head CID the launcher verified', async () => { const calls = []; const fetched = []; From 03d251cec0ee21fba6c664c0b2b105f32ad0aa38 Mon Sep 17 00:00:00 2001 From: Anders Alm Date: Sat, 7 Nov 2026 21:31:28 -0500 Subject: [PATCH 04/19] Treat a Linux computer as glibc when its glibc loader is present. Co-authored-by: Cursor --- src/main/targets/hostTools.ts | 3 ++- test/host-tools.test.js | 6 ++++++ 2 files changed, 8 insertions(+), 1 deletion(-) diff --git a/src/main/targets/hostTools.ts b/src/main/targets/hostTools.ts index 8efe06f..f296d19 100644 --- a/src/main/targets/hostTools.ts +++ b/src/main/targets/hostTools.ts @@ -80,8 +80,9 @@ export function detectLinuxLibc( // That directory is not on this computer. } } - if (names.some((name) => name.startsWith('ld-musl-'))) return 'musl'; + // The glibc loader is the system libc when a leftover musl loader is also present. if (names.some((name) => name.startsWith('ld-linux') || name === 'libc.so.6')) return 'glibc'; + if (names.some((name) => name.startsWith('ld-musl-'))) return 'musl'; return 'unknown'; } diff --git a/test/host-tools.test.js b/test/host-tools.test.js index ead6353..4bb4878 100644 --- a/test/host-tools.test.js +++ b/test/host-tools.test.js @@ -13,6 +13,7 @@ const { BASH_MESSAGE, MUSL_MESSAGE, PYTHON_VERIFY_MESSAGE, + detectLinuxLibc, prepareInstallerEnvironment, } = require('../dist/main/targets/hostTools'); const { evaluatePreflight } = require('../dist/main/targets/preflight'); @@ -258,6 +259,11 @@ test('a tampered python archive is refused and nothing is unpacked', async () => assert.equal(fs.existsSync(path.join(home, '.elastos-launcher', 'python', 'python', 'bin', 'python3')), false); }); +test('a glibc computer that also has a musl loader is not musl', () => { + assert.equal(detectLinuxLibc('linux', () => ['ld-musl-aarch64.so.1', 'ld-linux-aarch64.so.1']), 'glibc'); + assert.equal(detectLinuxLibc('linux', () => ['ld-musl-x86_64.so.1']), 'musl'); +}); + test('musl and a missing shell block install, and a bad python hash is refused', async () => { const dir = tempDir(); await assert.rejects( From e947b47e1bd78b27a746a1b18253a98549165364 Mon Sep 17 00:00:00 2001 From: Anders Alm Date: Sat, 7 Nov 2026 21:49:00 -0500 Subject: [PATCH 05/19] Revert "Read a 2.0.0 update check from the command text when the status file is absent." This reverts commit bb7d4b6e48fbec31cb417300f94209de34d5f292. --- scripts/linux-lifecycle-e2e.js | 9 +++++++-- src/main/targets/runtimeUpdate.ts | 23 +---------------------- test/linux-arm64.test.js | 4 ++-- test/runtime-update.test.js | 29 ----------------------------- 4 files changed, 10 insertions(+), 55 deletions(-) diff --git a/scripts/linux-lifecycle-e2e.js b/scripts/linux-lifecycle-e2e.js index d5182a8..76aa190 100644 --- a/scripts/linux-lifecycle-e2e.js +++ b/scripts/linux-lifecycle-e2e.js @@ -1,4 +1,6 @@ const assert = require('node:assert/strict'); +const fs = require('node:fs'); +const path = require('node:path'); const { isHealthOk, probeGatewayHealth } = require('../dist/main/targets/runtimeGateway'); async function health(wanted) { @@ -26,7 +28,7 @@ async function status(page, wanted) { 10000, `Window status did not become ${wanted}`); } -module.exports = async function (app, page) { +module.exports = async function (app, page, home) { await app.evaluate(({ shell }) => { global.__openedHome = []; shell.openExternal = async (url) => { global.__openedHome.push(url); }; @@ -55,5 +57,8 @@ module.exports = async function (app, page) { const checked = await page.evaluate(() => window.elastos.checkForUpdate()); assert.equal(checked.updateAvailable, false); - console.log('PASS elastos update --check reports up to date'); + const data = path.join(home, '.local', 'share', 'elastos'); + const update = JSON.parse(fs.readFileSync(path.join(data, 'update-check.json'), 'utf8')); + assert.equal(update.outcome, 'up_to_date'); + console.log('PASS elastos update --check writes up_to_date'); }; diff --git a/src/main/targets/runtimeUpdate.ts b/src/main/targets/runtimeUpdate.ts index 9dc9411..95a518d 100644 --- a/src/main/targets/runtimeUpdate.ts +++ b/src/main/targets/runtimeUpdate.ts @@ -58,27 +58,6 @@ export function parseUpdateCheckStatus(raw: string): ParsedUpdateCheck { }; } -/** Runtime 2.0.0 prints the result and does not write update-check.json. */ -export function parseUpdateCheckText(stdout: string): ParsedUpdateCheck { - const latestMatch = stdout.match(/^\s*Latest available:\s*(\S+)\s*$/m); - const installedMatch = stdout.match(/^\s*Installed release:\s*(\S+)\s*$/m); - const latest = latestMatch ? latestMatch[1] : null; - const installed = installedMatch && installedMatch[1] !== 'unknown' ? installedMatch[1] : null; - if (/^\s*Installed release is up to date\.\s*$/m.test(stdout)) { - const version = installed || latest || ''; - return { - updateAvailable: false, - detail: version, - latest: latest || installed, - }; - } - if (/Run `elastos update` to install\./.test(stdout)) { - if (!latest) throw new Error(UPDATE_STATUS_UNREADABLE); - return { updateAvailable: true, detail: latest, latest }; - } - throw new Error(UPDATE_STATUS_UNREADABLE); -} - export function parseHeadCid(stdout: string): string | null { for (const line of stdout.split(/\r?\n/)) { const match = line.match(/^\s*Head CID:\s*(\S+)/); @@ -123,7 +102,7 @@ export async function checkRuntimeUpdate( try { raw = readStatus(); } catch { - return parseUpdateCheckText(result.stdout); + throw new Error(UPDATE_STATUS_UNREADABLE); } return parseUpdateCheckStatus(raw); } diff --git a/test/linux-arm64.test.js b/test/linux-arm64.test.js index 419285e..e06ddc5 100644 --- a/test/linux-arm64.test.js +++ b/test/linux-arm64.test.js @@ -59,10 +59,10 @@ test('linux e2e runs the linux lifecycle and leaves the mac lifecycle on darwin' assert.match(life, /PASS closing the window keeps Home running/); assert.match(life, /PASS Stop Home closes the listener/); assert.match(life, /PASS Start Home becomes healthy/); - assert.match(life, /PASS elastos update --check reports up to date/); - assert.equal(life.includes('update-check.json'), false); + assert.match(life, /PASS elastos update --check writes up_to_date/); assert.equal(life.includes('waitForFunction'), false); assert.equal(life.includes('__elastosTray'), false); assert.equal(life.includes('Application Support'), false); assert.equal(life.includes('home --browser'), false); + assert.match(life, /\.local', 'share', 'elastos'/); }); diff --git a/test/runtime-update.test.js b/test/runtime-update.test.js index 5e6a137..4919d91 100644 --- a/test/runtime-update.test.js +++ b/test/runtime-update.test.js @@ -95,35 +95,6 @@ test('update --check is read from the status file, not from stdout or the exit c assert.equal(readOnFailure, false); }); -test('update --check reads the runtime text when the status file is absent', async () => { - const current = await checkRuntimeUpdate(async () => ({ - code: 0, - stdout: ' Latest available: 2.0.0\n Installed release: 2.0.0\n\n Installed release is up to date.\n', - stderr: '', - }), () => { - throw new Error('ENOENT'); - }); - assert.equal(current.updateAvailable, false); - assert.equal(current.latest, '2.0.0'); - - const newer = await checkRuntimeUpdate(async () => ({ - code: 0, - stdout: ' Latest available: 2.1.0\n Installed release: 2.0.0\n\n Run `elastos update` to install.\n', - stderr: '', - }), () => { - throw new Error('ENOENT'); - }); - assert.equal(newer.updateAvailable, true); - assert.equal(newer.latest, '2.1.0'); - - await assert.rejects( - () => checkRuntimeUpdate(async () => ({ code: 0, stdout: 'no report\n', stderr: '' }), () => { - throw new Error('ENOENT'); - }), - /not readable/, - ); -}); - test('update stores only a head CID the launcher verified', async () => { const calls = []; const fetched = []; From 7429483bc7431ac9ab53724b529eec5e4ca49f71 Mon Sep 17 00:00:00 2001 From: Anders Alm Date: Sat, 7 Nov 2026 21:51:06 -0500 Subject: [PATCH 06/19] Expect Linux Update to stop Home and start it again. Windows Update stays one command. The Linux test fails until that restart lands. Co-authored-by: Cursor --- test/runtime-update.test.js | 37 +++++++++++++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) diff --git a/test/runtime-update.test.js b/test/runtime-update.test.js index 48e89b3..393dfc5 100644 --- a/test/runtime-update.test.js +++ b/test/runtime-update.test.js @@ -198,6 +198,43 @@ test('Mac Update stops Home, runs the update and starts the current binary even assert.deepEqual(calls, ['stop', 'update', 'start-current-binary']); }); +test('Linux Update stops Home, runs the update, and starts the current binary even after failure', async (t) => { + const gateway = require('../dist/main/targets/runtimeGateway'); + const updates = require('../dist/main/targets/runtimeUpdate'); + const probe = require('../dist/main/targets/runtimeProbe'); + const { createRuntimeTarget } = require('../dist/main/targets/runtimeTarget'); + const calls = []; + t.mock.method(probe, 'findRuntimeBinary', () => '/installed/elastos'); + t.mock.method(gateway, 'createDefaultGatewaySupervisor', () => ({ + stop: async () => { calls.push('stop'); }, start: async () => { calls.push('start-current-binary'); }, + })); + let fail = false; + t.mock.method(updates, 'applyRuntimeUpdate', async () => { + calls.push('update'); + if (fail) throw new Error('update failed'); + }); + const target = createRuntimeTarget('linux'); + await target.update(); + assert.deepEqual(calls, ['stop', 'update', 'start-current-binary']); + calls.length = 0; + fail = true; + await assert.rejects(() => target.update(), /update failed/); + assert.deepEqual(calls, ['stop', 'update', 'start-current-binary']); +}); + +test('Windows Update does not stop or start Home around the command', async (t) => { + const gateway = require('../dist/main/targets/runtimeGateway'); + const updates = require('../dist/main/targets/runtimeUpdate'); + const { createRuntimeTarget } = require('../dist/main/targets/runtimeTarget'); + const calls = []; + t.mock.method(gateway, 'createDefaultGatewaySupervisor', () => ({ + stop: async () => { calls.push('stop'); }, start: async () => { calls.push('start'); }, + })); + t.mock.method(updates, 'applyRuntimeUpdate', async () => { calls.push('update'); }); + await createRuntimeTarget('win32').update(); + assert.deepEqual(calls, ['update']); +}); + test('Runtime 2.0.0 gets the #61 status record only after a successful check and signed head verification', async () => { const fixture = require('./helpers/signed-release'); const { writeSignedUpdateCheck } = require('../dist/main/targets/runtimeUpdate'); From f1eff78d65c3a23e3c347b791068d1edf6607bef Mon Sep 17 00:00:00 2001 From: Anders Alm Date: Sat, 7 Nov 2026 21:55:58 -0500 Subject: [PATCH 07/19] Start Linux Home with the update controller. A closed window leaves Home and the tray. Update and Undo stop Home, run the command, and start Home again. Co-authored-by: Cursor --- scripts/linux-lifecycle-e2e.js | 31 ++++++++++++++++- src/main/index.ts | 15 +++++++-- src/main/launchController.ts | 9 +++-- src/main/targets/descriptors.ts | 4 +-- src/main/targets/runtimeGateway.ts | 41 +++++++++++++++++++++-- src/main/targets/runtimeTarget.ts | 46 ++++++++++++++++---------- src/main/targets/types.ts | 1 + src/preload/index.ts | 2 ++ src/renderer/app.js | 5 ++- test/linux-arm64.test.js | 5 +++ test/runtime-gateway.test.js | 53 ++++++++++++++++++++++++++++++ test/runtime-update.test.js | 25 ++++++++++++++ 12 files changed, 207 insertions(+), 30 deletions(-) diff --git a/scripts/linux-lifecycle-e2e.js b/scripts/linux-lifecycle-e2e.js index 76aa190..6bfa208 100644 --- a/scripts/linux-lifecycle-e2e.js +++ b/scripts/linux-lifecycle-e2e.js @@ -28,6 +28,29 @@ async function status(page, wanted) { 10000, `Window status did not become ${wanted}`); } +async function liveController(data) { + const statusPath = path.join(data, 'update-controller', 'status.json'); + const deadline = Date.now() + 180000; + let last = 'absent'; + while (Date.now() < deadline) { + try { + const record = JSON.parse(fs.readFileSync(statusPath, 'utf8')); + const pid = record.controller_pid; + if (record.phase === 'ready' && Number.isInteger(pid) && pid > 0) { + const cmdline = fs.readFileSync(`/proc/${pid}/cmdline`, 'utf8').replace(/\0/g, ' '); + if (cmdline.includes('__update-controller')) return record; + last = `pid ${pid} command ${cmdline}`; + } else { + last = `phase ${record.phase}`; + } + } catch (err) { + last = err && err.code ? err.code : 'unread'; + } + await new Promise((resolve) => setTimeout(resolve, 500)); + } + throw new Error(`Home system update check did not reach a live controller (${last})`); +} + module.exports = async function (app, page, home) { await app.evaluate(({ shell }) => { global.__openedHome = []; @@ -55,9 +78,15 @@ module.exports = async function (app, page, home) { await health(true); console.log('PASS Start Home becomes healthy'); + const data = path.join(home, '.local', 'share', 'elastos'); + const controller = await liveController(data); + assert.equal(controller.phase, 'ready'); + console.log('PASS Home system update check reaches the live controller'); + console.log('NOT EXERCISED a full System update because no newer signed release exists'); + console.log('NOT EXERCISED the owner System summary because that route needs a wallet token'); + const checked = await page.evaluate(() => window.elastos.checkForUpdate()); assert.equal(checked.updateAvailable, false); - const data = path.join(home, '.local', 'share', 'elastos'); const update = JSON.parse(fs.readFileSync(path.join(data, 'update-check.json'), 'utf8')); assert.equal(update.outcome, 'up_to_date'); console.log('PASS elastos update --check writes up_to_date'); diff --git a/src/main/index.ts b/src/main/index.ts index d2be04f..cb80e84 100644 --- a/src/main/index.ts +++ b/src/main/index.ts @@ -1,7 +1,7 @@ import { app, BrowserWindow, dialog, ipcMain, Tray, Menu, nativeImage, shell } from 'electron'; import * as path from 'path'; import log from 'electron-log'; -import { createDefaultLaunchController, finishQuitAfterGatewayStop, TargetStatus } from './launchController'; +import { createDefaultLaunchController, finishQuitAfterGatewayStop, homeLaunchForPlatform, TargetStatus } from './launchController'; import { describeLegacyPc2OnThisComputer, removeLegacyPc2OnThisComputer, withSupportBundle } from './legacyPc2Removal'; const launch = createDefaultLaunchController(process.env); @@ -27,6 +27,7 @@ if (process.platform === 'darwin') { let mainWindow: BrowserWindow | null = null; let tray: Tray | null = null; let isQuitting = false; +let stopHomeOnQuit = true; const quitGate = { started: false, ready: false }; let currentStatus: TargetStatus = 'stopped'; @@ -137,9 +138,18 @@ function updateTrayMenu(): void { }, { type: 'separator' }, { label: 'Show Window', click: () => mainWindow?.show() }, + ...(homeLaunchForPlatform(process.platform).offerKeepHomeOnQuit ? [{ + label: 'Quit and keep Home', + click: () => { + stopHomeOnQuit = false; + isQuitting = true; + app.quit(); + }, + }] : []), { label: 'Quit and stop Home', click: () => { + stopHomeOnQuit = true; isQuitting = true; app.quit(); } @@ -273,7 +283,7 @@ app.whenReady().then(() => { }); app.on('window-all-closed', () => { - if (process.platform !== 'darwin') { + if (homeLaunchForPlatform(process.platform).quitWhenLastWindowCloses) { isQuitting = true; app.quit(); } @@ -289,6 +299,7 @@ app.on('activate', () => { app.on('before-quit', (event) => { isQuitting = true; + if (!stopHomeOnQuit) return; void finishQuitAfterGatewayStop(quitGate, event, () => launch.shutdown(), () => { app.quit(); }, { diff --git a/src/main/launchController.ts b/src/main/launchController.ts index 5a5cae5..019e5da 100644 --- a/src/main/launchController.ts +++ b/src/main/launchController.ts @@ -1,7 +1,9 @@ import * as os from 'os'; import { applyOpenAtLogin, readOpenAtLogin } from './targets/openAtLogin'; import { buildDiagnostics, collectPreflight, PreflightReport, saveCollectedSupportBundle } from './targets/preflight'; -import { confirmInstalledGateway, isForeignGatewayError, isHealthOk, probeGatewayHealth, STOP_GRACE_MS } from './targets/runtimeGateway'; +import { confirmInstalledGateway, homeLaunchForPlatform, isForeignGatewayError, isHealthOk, probeGatewayHealth, STOP_GRACE_MS } from './targets/runtimeGateway'; + +export { homeLaunchForPlatform }; import { collectFailureFacts, failureScreen, FailureScreen, fixCollectedFailure, windowsFixResult } from './targets/runtimeRecovery'; import { resolveLaunchTargetId } from './targets/preferences'; import { LAUNCH_TARGET_ENV, retiredPc2Notice } from './targets/registry'; @@ -10,7 +12,6 @@ import { setRuntimeLogSink } from './targets/runtimeGateway'; import { loadActiveRuntimePin } from './targets/runtimePin'; import { browserNote } from './targets/runtimeSupport'; import { runtimeHeadStore } from './targets/runtimeUpdate'; -import { rollbackRuntimeUpdate } from './targets/runtimeTarget'; import { BackupDescription, describeRuntimeBackupOnThisComputer } from './targets/runtimeBackup'; import { resetRuntimeOnThisComputer, ResetResult } from './targets/runtimeUninstall'; import { describeDistroBackupOnThisComputer, resetRuntimeInDistroOnThisComputer } from './targets/windowsReset'; @@ -130,6 +131,7 @@ export interface LaunchInfo { preflight: PreflightReport; openAtLogin: boolean; canRollback: boolean; + openBrowserAfterInstall: boolean; } function messageOf(err: unknown): string { @@ -259,7 +261,7 @@ export function createLaunchController(options: LaunchControllerOptions = {}): L describeResetBackup: () => (process.platform === 'win32' ? describeDistroBackupOnThisComputer() : describeRuntimeBackupOnThisComputer()), - rollback: (onProgress) => runRuntime(() => rollbackRuntimeUpdate(onProgress)), + rollback: (onProgress) => runRuntime(() => active.rollback(onProgress ?? (() => {}))), getVersion: () => runRuntimeSync(() => active.getVersion()), checkForUpdate: () => runRuntime(() => active.checkForUpdate()), openInBrowser: () => { @@ -291,6 +293,7 @@ export function createLaunchController(options: LaunchControllerOptions = {}): L preflight, openAtLogin: readOpenAtLogin(), canRollback: Boolean(runtimeHeadStore().get()), + openBrowserAfterInstall: homeLaunchForPlatform(process.platform).openBrowserAfterInstall, }; }, getPreflight: () => collectPreflight(), diff --git a/src/main/targets/descriptors.ts b/src/main/targets/descriptors.ts index 80f4a57..cc05b18 100644 --- a/src/main/targets/descriptors.ts +++ b/src/main/targets/descriptors.ts @@ -3,8 +3,8 @@ import { LaunchTargetDescriptor } from './types'; /** * Facts taken from elastos-runtime. - * `elastos gateway` is the supervised entry: `elastos home --browser` - * also opens the system browser itself. + * Darwin and Linux start `home --browser` from homeLaunchForPlatform. + * `startArgs` stays the gateway command for the other platforms. * Health is GET /healthz → "OK" on the gateway. * darwin/x64 is included because a runtime build for Intel Mac is planned. * Native win32 is absent: Windows uses a WSL2 distro. diff --git a/src/main/targets/runtimeGateway.ts b/src/main/targets/runtimeGateway.ts index c168918..861b672 100644 --- a/src/main/targets/runtimeGateway.ts +++ b/src/main/targets/runtimeGateway.ts @@ -20,6 +20,31 @@ export { HEALTH_URL, HOME_URL, LEGACY_GATEWAY_ADDR, LOOPBACK_ADDRESSES }; /** Supervised command from the launcher contract. */ export const GATEWAY_ARGS: readonly string[] = ['gateway', '--addr', GATEWAY_ADDR]; +const TERMINAL_KEEP_LINE = 'Keep this terminal open. Press Ctrl+C to stop Home.'; + +export interface HomeLaunch { + args: readonly string[]; + quitWhenLastWindowCloses: boolean; + updateRestartsHome: boolean; + rollbackRestartsHome: boolean; + hideTerminalKeepLine: boolean; + openBrowserAfterInstall: boolean; + offerKeepHomeOnQuit: boolean; +} + +/** Darwin and Linux start the signed Home controller. Windows keeps the gateway command. */ +export function homeLaunchForPlatform(platform: string): HomeLaunch { + const browserHome = platform === 'darwin' || platform === 'linux'; + return { + args: browserHome ? ['home', '--browser'] : GATEWAY_ARGS, + quitWhenLastWindowCloses: platform !== 'darwin' && platform !== 'linux', + updateRestartsHome: browserHome, + rollbackRestartsHome: platform === 'linux', + hideTerminalKeepLine: platform === 'linux', + openBrowserAfterInstall: platform !== 'linux', + offerKeepHomeOnQuit: platform === 'linux', + }; +} export const ALREADY_OWNS_TEXT = 'another ElastOS host already owns'; export const EXIT_BINARY_REPLACED = 75; export const STOP_GRACE_MS = 15_000; @@ -149,6 +174,8 @@ export interface GatewaySupervisorDeps { now: () => number; openUrl: (url: string) => void; log: (line: string) => void; + /** Linux drops the runtime's terminal sentence. Exit 75 still reads the raw stream. */ + hideTerminalKeepLine?: boolean; confirmForeign?: () => Promise; /** * True when the running gateway is one an earlier launcher started on @@ -319,6 +346,12 @@ export function scrubRuntimeLog(chunk: string): string { return chunk; } +export function launcherLogText(text: string, hideTerminalKeepLine: boolean): string { + const clean = scrubRuntimeLog(text); + if (!hideTerminalKeepLine) return clean; + return clean.split('\n').filter((line) => !line.includes(TERMINAL_KEEP_LINE)).join('\n'); +} + export function createGatewaySupervisor(deps: GatewaySupervisorDeps): GatewaySupervisor { const graceMs = deps.graceMs ?? STOP_GRACE_MS; const healthTimeoutMs = deps.healthTimeoutMs ?? 60_000; @@ -332,7 +365,7 @@ export function createGatewaySupervisor(deps: GatewaySupervisorDeps): GatewaySup let current: 'running' | 'stopped' | 'starting' | 'stopping' | 'error' = 'stopped'; const note = (line: string) => { - const clean = scrubRuntimeLog(line).replace(/\s+$/g, ''); + const clean = launcherLogText(line, deps.hideTerminalKeepLine === true).replace(/\s+$/g, ''); if (!clean) return; logs.push(clean); deps.log(clean); @@ -415,7 +448,7 @@ export function createGatewaySupervisor(deps: GatewaySupervisorDeps): GatewaySup if (output.includes(ALREADY_OWNS_TEXT)) { return 'already'; } - const tail = scrubRuntimeLog(output).trim().split('\n').slice(-3).join(' '); + const tail = launcherLogText(output, deps.hideTerminalKeepLine === true).trim().split('\n').slice(-3).join(' '); throw new Error( tail ? `ElastOS stopped before it was ready. ${tail}` @@ -754,9 +787,11 @@ export async function pidOwnsGatewayPort( } export function createDefaultGatewaySupervisor(binary: string, platform: string = process.platform): GatewaySupervisor { + const launch = homeLaunchForPlatform(platform); return createGatewaySupervisor({ binary, - args: platform === 'darwin' ? ['home', '--browser'] : GATEWAY_ARGS, + args: launch.args, + hideTerminalKeepLine: launch.hideTerminalKeepLine, adoptForControls: platform === 'darwin', healthTimeoutMs: platform === 'darwin' ? 150000 : 60000, spawn: spawnGatewayProcess, diff --git a/src/main/targets/runtimeTarget.ts b/src/main/targets/runtimeTarget.ts index aa67f6d..67514d5 100644 --- a/src/main/targets/runtimeTarget.ts +++ b/src/main/targets/runtimeTarget.ts @@ -8,6 +8,7 @@ import { confirmInstalledGateway, ForeignGatewayError, GatewaySupervisor, + homeLaunchForPlatform, isHealthOk, openRuntimeHome, probeGatewayHealth, @@ -55,6 +56,25 @@ export function createRuntimeTarget(platform: NodeJS.Platform = process.platform await supervisor.stop({ adopt }); } + async function runWithHomeRestart(action: () => Promise): Promise { + if (updating) throw new Error('An ElastOS update is already running.'); + updating = true; + try { + await stopGateway(true); + await action(); + } finally { + supervisor = null; + try { + const file = binary(); + if (!file) throw new Error('ElastOS is not installed yet. Click Install.'); + supervisor = createDefaultGatewaySupervisor(file, platform); + await supervisor.start(); + } finally { + updating = false; + } + } + } + return { id: 'runtime', descriptor: RUNTIME_TARGET, @@ -124,24 +144,14 @@ export function createRuntimeTarget(platform: NodeJS.Platform = process.platform await supervisor.start(); }, install: (onProgress) => runtimeInstall.installRuntimeOnThisComputer(onProgress), - update: async (onProgress) => { - if (platform !== 'darwin') return applyRuntimeUpdate(runtimeCommand(), runtimeHeadStore(), headVerify(), onProgress); - if (updating) throw new Error('An ElastOS update is already running.'); - updating = true; - try { - await stopGateway(true); - await applyRuntimeUpdate(runtimeCommand(), runtimeHeadStore(), headVerify(), onProgress); - } finally { - supervisor = null; - try { - const file = binary(); - if (!file) throw new Error('ElastOS is not installed yet. Click Install.'); - supervisor = createDefaultGatewaySupervisor(file, platform); - await supervisor.start(); - } finally { - updating = false; - } - } + update: (onProgress) => { + const action = () => applyRuntimeUpdate(runtimeCommand(), runtimeHeadStore(), headVerify(), onProgress); + if (!homeLaunchForPlatform(platform).updateRestartsHome) return action(); + return runWithHomeRestart(action); + }, + rollback: (onProgress) => { + if (!homeLaunchForPlatform(platform).rollbackRestartsHome) return rollbackRuntimeUpdate(onProgress); + return runWithHomeRestart(() => rollbackRuntimeUpdate(onProgress)); }, // On Windows the launch controller runs uninstallRuntimeInDistro (windowsUninstall.ts) with the two answers. uninstall: () => (platform === 'win32' ? Promise.reject(new Error('Uninstall on Windows needs your answer in the Uninstall window. Nothing was removed.')) : runtimeUninstall(() => stopGateway(true))), diff --git a/src/main/targets/types.ts b/src/main/targets/types.ts index dcf0dce..557d16f 100644 --- a/src/main/targets/types.ts +++ b/src/main/targets/types.ts @@ -66,6 +66,7 @@ export interface LaunchTarget { restart(): Promise; install(onProgress: (message: string) => void): Promise; update(onProgress: (message: string) => void): Promise; + rollback(onProgress: (message: string) => void): Promise; uninstall(): Promise; getVersion(): string; checkForUpdate(): Promise; diff --git a/src/preload/index.ts b/src/preload/index.ts index 15cc82a..04b8caa 100644 --- a/src/preload/index.ts +++ b/src/preload/index.ts @@ -99,6 +99,8 @@ declare global { preflight: { ok: boolean; checks: Array<{ id: string; level: string; message: string }> }; openAtLogin: boolean; canRollback: boolean; + error: string | null; + openBrowserAfterInstall: boolean; }>; getPreflight: () => Promise<{ ok: boolean; checks: Array<{ id: string; level: string; message: string }> }>; getDiagnostics: () => Promise; diff --git a/src/renderer/app.js b/src/renderer/app.js index 9adf613..0ce2c92 100644 --- a/src/renderer/app.js +++ b/src/renderer/app.js @@ -216,7 +216,10 @@ async function runInstall() { renderSteps('Starting'); await window.elastos.start(); renderSteps('Your computer is ready'); - await window.elastos.openBrowser(); + const started = await window.elastos.getLaunchInfo(); + if (started.openBrowserAfterInstall !== false) { + await window.elastos.openBrowser(); + } } catch (err) { showError(err && err.message ? err.message : 'Something went wrong. Try again.'); updateStatus('error'); diff --git a/test/linux-arm64.test.js b/test/linux-arm64.test.js index e06ddc5..0620582 100644 --- a/test/linux-arm64.test.js +++ b/test/linux-arm64.test.js @@ -59,6 +59,11 @@ test('linux e2e runs the linux lifecycle and leaves the mac lifecycle on darwin' assert.match(life, /PASS closing the window keeps Home running/); assert.match(life, /PASS Stop Home closes the listener/); assert.match(life, /PASS Start Home becomes healthy/); + assert.match(life, /PASS Home system update check reaches the live controller/); + assert.match(life, /NOT EXERCISED a full System update because no newer signed release exists/); + assert.match(life, /NOT EXERCISED the owner System summary because that route needs a wallet token/); + assert.match(life, /update-controller', 'status.json'/); + assert.match(life, /__update-controller/); assert.match(life, /PASS elastos update --check writes up_to_date/); assert.equal(life.includes('waitForFunction'), false); assert.equal(life.includes('__elastosTray'), false); diff --git a/test/runtime-gateway.test.js b/test/runtime-gateway.test.js index 26a9755..3f2eb22 100644 --- a/test/runtime-gateway.test.js +++ b/test/runtime-gateway.test.js @@ -8,6 +8,8 @@ const { createGatewaySupervisor, isHealthOk, scrubRuntimeLog, + launcherLogText, + homeLaunchForPlatform, signalProcessGroup, ForeignGatewayError, foreignListenerIsElastos, @@ -820,6 +822,57 @@ test('logs omit attach secrets', async () => { assert.equal(text.includes('sekrit'), false); assert.match(text, /omitted a line/); assert.equal(scrubRuntimeLog('attach_secret=nope').includes('nope'), false); + const keep = 'Keep this terminal open. Press Ctrl+C to stop Home.\nwas replaced on disk\n'; + assert.equal(launcherLogText(keep, true).includes('Keep this terminal open'), false); + assert.match(launcherLogText(keep, true), /was replaced on disk/); + assert.match(launcherLogText(keep, false), /Keep this terminal open/); + assert.deepEqual(homeLaunchForPlatform('linux').args, ['home', '--browser']); + assert.equal(homeLaunchForPlatform('linux').quitWhenLastWindowCloses, false); + assert.equal(homeLaunchForPlatform('linux').updateRestartsHome, true); + assert.equal(homeLaunchForPlatform('linux').rollbackRestartsHome, true); + assert.equal(homeLaunchForPlatform('linux').hideTerminalKeepLine, true); + assert.equal(homeLaunchForPlatform('linux').openBrowserAfterInstall, false); + assert.equal(homeLaunchForPlatform('linux').offerKeepHomeOnQuit, true); + assert.deepEqual(homeLaunchForPlatform('darwin').args, ['home', '--browser']); + assert.equal(homeLaunchForPlatform('darwin').quitWhenLastWindowCloses, false); + assert.equal(homeLaunchForPlatform('darwin').updateRestartsHome, true); + assert.equal(homeLaunchForPlatform('darwin').rollbackRestartsHome, false); + assert.equal(homeLaunchForPlatform('darwin').hideTerminalKeepLine, false); + assert.equal(homeLaunchForPlatform('darwin').openBrowserAfterInstall, true); + assert.equal(homeLaunchForPlatform('darwin').offerKeepHomeOnQuit, false); + assert.deepEqual(homeLaunchForPlatform('win32').args, ['gateway', '--addr', 'localhost:8090']); + assert.equal(homeLaunchForPlatform('win32').quitWhenLastWindowCloses, true); + assert.equal(homeLaunchForPlatform('win32').updateRestartsHome, false); + assert.equal(homeLaunchForPlatform('win32').openBrowserAfterInstall, true); + assert.equal(homeLaunchForPlatform('win32').offerKeepHomeOnQuit, false); +}); + +test('a Linux supervisor log drops the terminal sentence and keeps the other lines', async () => { + const launch = homeLaunchForPlatform('linux'); + let proc; + const logs = []; + const sup = createGatewaySupervisor({ + binary: '/bin/elastos', + args: launch.args, + hideTerminalKeepLine: launch.hideTerminalKeepLine, + spawn() { + proc = fakeProcess(11); + return proc; + }, + fetchHealth: async () => { + proc.emit('Keep this terminal open. Press Ctrl+C to stop Home.\nHome: http://localhost:8090/home/\n'); + return { status: 200, body: 'OK' }; + }, + sleep: async () => {}, + now: () => 0, + openUrl() {}, + log: (line) => logs.push(line), + listenerOwned: () => true, + }); + await sup.start(); + const text = logs.join('\n'); + assert.equal(text.includes('Keep this terminal open'), false); + assert.match(text, /Home: http:\/\/localhost:8090\/home\//); }); test('uninstall removes only the runtime binary and data dir', async () => { diff --git a/test/runtime-update.test.js b/test/runtime-update.test.js index 393dfc5..8ae4550 100644 --- a/test/runtime-update.test.js +++ b/test/runtime-update.test.js @@ -222,6 +222,31 @@ test('Linux Update stops Home, runs the update, and starts the current binary ev assert.deepEqual(calls, ['stop', 'update', 'start-current-binary']); }); +test('Linux Undo stops Home, restores the release, and starts Home again', async (t) => { + const gateway = require('../dist/main/targets/runtimeGateway'); + const updates = require('../dist/main/targets/runtimeUpdate'); + const probe = require('../dist/main/targets/runtimeProbe'); + const { createRuntimeTarget } = require('../dist/main/targets/runtimeTarget'); + const calls = []; + t.mock.method(probe, 'findRuntimeBinary', () => '/installed/elastos'); + t.mock.method(gateway, 'createDefaultGatewaySupervisor', () => ({ + stop: async () => { calls.push('stop'); }, + start: async () => { calls.push('start-current-binary'); }, + })); + t.mock.method(updates, 'rollbackRuntime', async () => { calls.push('rollback'); }); + await createRuntimeTarget('linux').rollback(() => {}); + assert.deepEqual(calls, ['stop', 'rollback', 'start-current-binary']); +}); + +test('Mac Undo does not stop or start Home around the command', async (t) => { + const updates = require('../dist/main/targets/runtimeUpdate'); + const { createRuntimeTarget } = require('../dist/main/targets/runtimeTarget'); + const calls = []; + t.mock.method(updates, 'rollbackRuntime', async () => { calls.push('rollback'); }); + await createRuntimeTarget('darwin').rollback(() => {}); + assert.deepEqual(calls, ['rollback']); +}); + test('Windows Update does not stop or start Home around the command', async (t) => { const gateway = require('../dist/main/targets/runtimeGateway'); const updates = require('../dist/main/targets/runtimeUpdate'); From 352e8401cd6e468319e334eb1d0bfaa31e3367c4 Mon Sep 17 00:00:00 2001 From: Anders Alm Date: Sat, 7 Nov 2026 22:06:09 -0500 Subject: [PATCH 08/19] Count a Home child as the owner of port 8090. The update controller does not hold the listen socket. Its child does. Co-authored-by: Cursor --- src/main/targets/runtimeGateway.ts | 153 ++++++++++++++++++++++++----- test/runtime-gateway.test.js | 26 +++++ 2 files changed, 154 insertions(+), 25 deletions(-) diff --git a/src/main/targets/runtimeGateway.ts b/src/main/targets/runtimeGateway.ts index 861b672..d1e8a17 100644 --- a/src/main/targets/runtimeGateway.ts +++ b/src/main/targets/runtimeGateway.ts @@ -278,6 +278,65 @@ export function procListenersFor(tcp: string, tcp6: string, fdLinks: readonly st return procNetListeners(tcp, tcp6, port).map((entry) => ({ address: entry.address, owned: owned.has(entry.inode) })); } +export interface ProcProcess { + pid: number; + ppid: number; + fdLinks: readonly string[]; +} + +/** `comm` may contain spaces. The kernel ends the name at the last `)`. */ +export function procStatParent(stat: string): { pid: number; ppid: number } | null { + const end = stat.lastIndexOf(')'); + const space = stat.indexOf(' '); + if (end < 0 || space <= 0 || space > end) return null; + const pid = Number(stat.slice(0, space)); + const ppid = Number(stat.slice(end + 2).split(' ')[1]); + if (!Number.isInteger(pid) || pid <= 0 || !Number.isInteger(ppid) || ppid < 0) return null; + return { pid, ppid }; +} + +/** `root` and every process that descends from it. A cycle is visited once. */ +export function descendantPids(root: number, rows: readonly { pid: number; ppid: number }[]): number[] { + const children = new Map(); + for (const row of rows) { + const list = children.get(row.ppid); + if (list) list.push(row.pid); + else children.set(row.ppid, [row.pid]); + } + const out: number[] = []; + const seen = new Set(); + const stack = [root]; + while (stack.length > 0) { + const pid = stack.pop() as number; + if (seen.has(pid)) continue; + seen.add(pid); + out.push(pid); + const kids = children.get(pid); + if (kids) for (const kid of kids) stack.push(kid); + } + return out; +} + +/** + * The Home controller does not hold the listen socket. Its child does. + * A socket of a process outside that tree stays foreign. + */ +export function listenersFromProcSnapshot( + tcp: string, + tcp6: string, + root: number, + rows: readonly ProcProcess[], + port = GATEWAY_PORT, +): PortListener[] { + const tree = new Set(descendantPids(root, rows)); + const links: string[] = []; + for (const row of rows) { + if (!tree.has(row.pid)) continue; + for (const link of row.fdLinks) links.push(link); + } + return procListenersFor(tcp, tcp6, links, port); +} + /** * `lsof -nP -iTCP: -sTCP:LISTEN -Fpn` output. `n` names look like * `127.0.0.1:8090`, `[::1]:8090`, or `*:8090`. A socket of another account is @@ -723,38 +782,82 @@ export async function probeGatewayHealth(options: { return combineHealth(results); } -/** LISTEN sockets on the gateway port, marked by whether `pid` holds each. Null when they cannot be read. */ -export async function localListeners(pid: number, platform: string = process.platform): Promise { - if (!Number.isInteger(pid) || pid <= 0) return null; - if (platform === 'linux') { - let tcp: string; - try { - tcp = fs.readFileSync('/proc/net/tcp', 'utf8'); - } catch { - return null; - } - let tcp6 = ''; +const PROC_STAT_MAX = 4096; +const PROC_TREE_MAX = 64; + +function fdLinks(pid: number): string[] | null { + const links: string[] = []; + let names: string[]; + try { + names = fs.readdirSync(`/proc/${pid}/fd`); + } catch { + return null; + } + for (const name of names) { try { - tcp6 = fs.readFileSync('/proc/net/tcp6', 'utf8'); + links.push(fs.readlinkSync(`/proc/${pid}/fd/${name}`)); } catch { - // No IPv6 on this kernel. Nothing can listen on ::1. - tcp6 = ''; + // A descriptor can disappear between readdir and readlink. } - const links: string[] = []; + } + return links; +} + +/** Listeners held by `pid` or its descendants. Null when the tree cannot be read. */ +function linuxProcessListeners(pid: number): PortListener[] | null { + let tcp: string; + try { + tcp = fs.readFileSync('/proc/net/tcp', 'utf8'); + } catch { + return null; + } + let tcp6 = ''; + try { + tcp6 = fs.readFileSync('/proc/net/tcp6', 'utf8'); + } catch { + // No IPv6 on this kernel. Nothing can listen on ::1. + tcp6 = ''; + } + let names: string[]; + try { + names = fs.readdirSync('/proc'); + } catch { + return null; + } + const parents: { pid: number; ppid: number }[] = []; + for (const name of names) { + if (!/^[1-9][0-9]*$/.test(name)) continue; try { - const dir = `/proc/${pid}/fd`; - for (const name of fs.readdirSync(dir)) { - try { - links.push(fs.readlinkSync(`${dir}/${name}`)); - } catch { - // A descriptor can disappear between readdir and readlink. - } - } + const buf = fs.readFileSync(`/proc/${name}/stat`); + if (buf.length > PROC_STAT_MAX) continue; + const parsed = procStatParent(buf.toString('utf8')); + if (parsed && parsed.pid === Number(name)) parents.push(parsed); } catch { - return null; + // The process can exit between readdir and the stat read. } - return procListenersFor(tcp, tcp6, links); } + if (!parents.some((row) => row.pid === pid)) return null; + let tree = descendantPids(pid, parents); + if (tree.length > PROC_TREE_MAX) { + tree = [pid, ...parents.filter((row) => row.ppid === pid).map((row) => row.pid)]; + } + if (tree.length > PROC_TREE_MAX) return null; + const rootLinks = fdLinks(pid); + if (!rootLinks) return null; + const rows: ProcProcess[] = [{ pid, ppid: parents.find((row) => row.pid === pid)?.ppid ?? 0, fdLinks: rootLinks }]; + for (const id of tree) { + if (id === pid) continue; + const links = fdLinks(id); + if (!links) return null; + rows.push({ pid: id, ppid: parents.find((row) => row.pid === id)?.ppid ?? 0, fdLinks: links }); + } + return listenersFromProcSnapshot(tcp, tcp6, pid, rows); +} + +/** LISTEN sockets on the gateway port, marked by whether `pid` or a descendant holds each. Null when they cannot be read. */ +export async function localListeners(pid: number, platform: string = process.platform): Promise { + if (!Number.isInteger(pid) || pid <= 0) return null; + if (platform === 'linux') return linuxProcessListeners(pid); if (platform === 'darwin') { return new Promise((resolve) => { execFile('lsof', ['-nP', `-iTCP:${GATEWAY_PORT}`, '-sTCP:LISTEN', '-Fpn'], { diff --git a/test/runtime-gateway.test.js b/test/runtime-gateway.test.js index 3f2eb22..3f55762 100644 --- a/test/runtime-gateway.test.js +++ b/test/runtime-gateway.test.js @@ -25,6 +25,9 @@ const { procListenersFor, procNetAddress, procNetListeners, + procStatParent, + descendantPids, + listenersFromProcSnapshot, } = require('../dist/main/targets/runtimeGateway'); const { uninstallRuntime } = require('../dist/main/targets/runtimeUninstall'); @@ -225,6 +228,29 @@ test('the gateway must own every localhost listener, on 127.0.0.1 and on ::1', ( assert.equal(listenerOwnership(procListenersFor(tcp, tcp6, ['socket:[4242]', 'socket:[4343]']), wants, ['::1']), 'owned'); }); +test('a Home controller owns port 8090 when its child listens', () => { + const tcp = [TCP_HEADER, tcpRow('0100007F', 4242)].join('\n'); + const tcp6 = [TCP_HEADER, tcpRow(V6_LOOPBACK, 4343)].join('\n'); + const wants = ['127.0.0.1', '::1']; + assert.deepEqual(procStatParent('20 (elastos home) S 10 9'), { pid: 20, ppid: 10 }); + assert.equal(procStatParent('no-paren'), null); + assert.deepEqual( + descendantPids(10, [{ pid: 20, ppid: 10 }, { pid: 21, ppid: 20 }, { pid: 30, ppid: 1 }]).sort((a, b) => a - b), + [10, 20, 21], + ); + const child = [ + { pid: 10, ppid: 1, fdLinks: ['pipe:[1]'] }, + { pid: 20, ppid: 10, fdLinks: ['socket:[4242]', 'socket:[4343]'] }, + ]; + assert.equal(listenerOwnership(listenersFromProcSnapshot(tcp, tcp6, 10, child), wants), 'owned'); + const stranger = [ + { pid: 10, ppid: 1, fdLinks: [] }, + { pid: 20, ppid: 10, fdLinks: ['socket:[4242]'] }, + { pid: 30, ppid: 1, fdLinks: ['socket:[4343]'] }, + ]; + assert.equal(listenerOwnership(listenersFromProcSnapshot(tcp, tcp6, 10, stranger), wants), 'foreign'); +}); + test('lsof listeners name the owner pid for IPv4, [::1], and *', () => { const out = ['p41', 'f7', 'n127.0.0.1:8090', 'f8', 'n[::1]:8090', 'p99', 'f3', 'n*:8090', 'p100', 'n127.0.0.1:9000'].join('\n'); assert.deepEqual(parseLsofListeners(out, 41), [ From a3e935565e9f94f891959dd594e4ed284f48d661 Mon Sep 17 00:00:00 2001 From: Anders Alm Date: Sat, 7 Nov 2026 22:54:44 -0500 Subject: [PATCH 09/19] Adopt a Linux Home only when its controller record still matches. A descendant socket or a reused pid was treated as this Home, so Quit and stop left a retained Home running. Co-authored-by: Cursor --- CONTRIBUTING.md | 2 +- docs/RUNTIME_MIGRATION.md | 4 +- scripts/electron-e2e.js | 4 +- scripts/linux-lifecycle-e2e.js | 72 +++++- src/main/index.ts | 4 + src/main/targets/openAtLogin.ts | 24 +- src/main/targets/runtimeGateway.ts | 369 +++++++++++++++++++++++------ test/installer-ux.test.js | 9 +- test/linux-arm64.test.js | 8 +- test/runtime-gateway.test.js | 110 ++++++++- 10 files changed, 511 insertions(+), 95 deletions(-) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index a7fd0d0..3befda8 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -14,7 +14,7 @@ A wrong signature or channel, version below the floor, changed metadata snapshot - Home is `http://localhost:8090/home/`. - Update offers require signed metadata. Runtime 2.0.0 needs a compatibility `update-check.json` record after a successful CLI check. Human-readable stdout never determines the offer. A 2.0.0 source with an unknown head uses the stored signed install record and matching binary version for rollback identity. - A foreign listener on 8090 keeps running and its specific error reaches the window. A status probe that overlaps Start, Stop, or Update must honor the newer control phase. -- On Mac, the signed Home controller owns System update restarts. Re-read the verified host generation before Stop. Other platforms signal the gateway process group with `SIGTERM`, 15 seconds, then `SIGKILL`, and only after the pid has exited and `/healthz` has failed twice. +- On Mac, the signed Home controller owns System update restarts. Re-read the verified host generation before Stop. On Linux, Stop and Quit signal the controller only when `status.json` and the host lock prove it, and the start time in `/proc` still matches. Windows signals the gateway process group with `SIGTERM`, 15 seconds, then `SIGKILL`, and only after the pid has exited and `/healthz` has failed twice. - Reset and uninstall remove only the ElastOS program, its data directory, and the launcher stage file. Other home directories stay on disk. - IPC channel names are `elastos:*`. The preload object is `window.elastos`. - `src/main/index.ts` does not import `./targets`. diff --git a/docs/RUNTIME_MIGRATION.md b/docs/RUNTIME_MIGRATION.md index 462afc5..1abf42c 100644 --- a/docs/RUNTIME_MIGRATION.md +++ b/docs/RUNTIME_MIGRATION.md @@ -68,7 +68,7 @@ Uninstall on Windows removes the whole ElastOS WSL2 Linux environment with `wsl. Remove PC2 is a separate action in `src/main/legacyPc2Removal.ts`. The button stays hidden until a legacy install is on disk: `~/.pc2`, `~/.elastos/node` when it is the old bundled Node 22.13.1 tree, a PC2 launch agent or autostart file, a sudoers file whose text matches the rules the old installer wrote (`/etc/sudoers.d/wireguard` with `wg-quick`, or `/etc/sudoers.d/amneziawg` with `NOPASSWD:SETENV`, `amneziawg-go`, and `/var/run/amneziawg/`) together with one of those installs, a `~/.pc2` folder inside another Windows Linux distro, or a Windows distro named `pc2` or `pc2-wsl` that itself contains that folder or Node tree. The old installer never wrote `/etc/sudoers.d/elastos` or `/etc/sudoers.d/pc2-wireguard`. This repo has no hash for the VPN programs it compiled, so those programs are not deleted by name. The ElastOS distro is never unregistered. The confirm dialog lists each path and its size. Removal deletes only the paths from that list. “Back up my PC2 data first” must write a backup before anything is deleted, including a Windows Linux folder or distro; if that backup cannot be saved, nothing is removed. One privileged prompt covers a matching sudoers rule. That prompt is pkexec. Cancelling it (exit 126), a missing authorization or a missing prompt (exit 127), and a missing pkexec program each have their own sentence. pkexec is not replaced with sudo. An exit after the prompt has started is the removal command's own result. The list of files still there is what that privileged script can see, including a sudoers file the app itself cannot stat. A failure says what is still there and saves a support bundle. -On Mac, Stop and Quit re-read the installed Home generation and signal its verified controller when present. The controller drains its children. Linux and Windows retain gateway process-group supervision with `SIGTERM`, 15 seconds, then `SIGKILL`, and two failed health probes after the pid exits. Quit waits through shutdown and its health probes. Reset and Uninstall, after the confirm dialog, adopt that gateway from the host lock and signal the pid they read. They do not ask again. On Windows they adopt only when the distro facts say the listener is ElastOS. A different listener, and a facts read that fails, is left running. On macOS and Linux the adopt itself checks the host lock, the command line, and the health socket. On Windows, an error asking whether that pid has exited is treated as still running. Exit 75 restarts only when the binary was replaced on disk. +On Mac and Linux, Stop and Quit re-read the installed Home and signal its verified controller when the host lock and the update-controller status agree. Linux re-reads that controller's start time from /proc immediately before the signal. A descendant, a reused pid, or a stale status file is left running. The controller drains its children. Windows retains gateway process-group supervision with `SIGTERM`, 15 seconds, then `SIGKILL`, and two failed health probes after the pid exits. Quit waits through shutdown and its health probes. Reset and Uninstall, after the confirm dialog, adopt that gateway from the host lock and signal the pid they read. They do not ask again. On Windows they adopt only when the distro facts say the listener is ElastOS. A different listener, and a facts read that fails, is left running. On macOS and Linux the adopt itself checks the host lock, the command line, and the health socket. On Windows, an error asking whether that pid has exited is treated as still running. Exit 75 restarts only when the binary was replaced on disk. The support bundle redacts labeled secrets (`password`, `token`, `api_key`, `attach_secret`, `cookie`, `authorization`, `seed`, `mnemonic`, `private_key`, `secret`, bearer tokens, and JWTs), the rest of a `seed`, `mnemonic`, `private_key`, or `secret` line, a run of 12 or more BIP39 words in any case, split by spaces, line breaks, commas, hyphens, quotes, or numbering such as `1.` or `2:`, known secret prefixes (AWS access key ids, `ghp_` tokens, and `sk-` keys), hex of 32 or more characters with or without `0x`, including a 64-character hex string unless that line is labelled sha256 or hash, hex wrapped over two or more lines that holds 32 or more characters together (a list of whole 40- or 64-character hashes stays), an unlabeled uppercase token of 16 or more characters that contains a digit and no underscore, a lowercase token of 32 or more characters with high entropy, and an unlabeled mixed-case token of 20 or more characters with high entropy. It keeps paths, a 40-character hex hash on its own line or beside a hash, cid, commit, or installer label, a 64-character hex string on a sha256 or hash line, CIDv0 and CIDv1, `did:key` values, versions, UUIDs, and `UPPER_SNAKE` names. An unlabeled secret shorter than that, or with low entropy, is not redacted. `secret-line` is a short phrase that stays. @@ -95,6 +95,6 @@ Check these before the runtime on `main` is marketed as a live product and this - [ ] No phone-home telemetry. - [x] Uninstall and Reset remove only the exact runtime paths: `~/.local/bin/elastos`, `~/.local/share/elastos`, `~/Library/Application Support/elastos`, `~/.elastos-launcher/install-stage.json`, and `~/.elastos-launcher/resume-install.json`. Reset also removes `~/.elastos-launcher/resume-install.json.lock`. An XDG data directory under this home is included when it is empty or holds only the partial-install files, or when every entry is a runtime name and the signed install record verifies. A user file is refused by name even beside that record. Other folders stay on disk. - [x] Remove PC2 is separate from Reset and Uninstall. It is shown only when a legacy install is detected, lists those known paths and their sizes, and refuses runtime paths, symlink escapes, and any other path. -- A foreign listener is left running. On Mac, Start, Stop, Restart and Quit can adopt the verified installed Home. Controller shutdown drains its child processes. Other platforms retain their existing gateway supervision path. +- A foreign listener is left running. On Mac and Linux, Start, Stop, Restart and Quit can adopt the verified installed Home. Controller shutdown drains its child processes. Windows retains its gateway supervision path. - [ ] Diagnostics and the log panel do not contain `attach_secret` or the coordinate JSON files. Labeled secrets, AWS key ids, `ghp_` tokens, `sk-` keys, a run of 12 or more BIP39 words in any layout, wrapped hex, and hex that is not a 40-character hash or a 64-character hex string on a sha256 or hash line are redacted. An unlabeled short or low-entropy phrase is not. - Live rollback of historical alpha releases is no longer a CI job. Stable 2.0.0's linked predecessor is Canary 2.0.0-rc.2; Runtime correctly refuses that channel change, and there is no prior Stable release within the 2.0.0 floor to exercise. Current signed install and health checks remain in smoke. Unit tests exercise the launcher's verified rollback CID and refusal paths. A future live rollback fixture must use releases on the subscribed channel and within the install floor. diff --git a/scripts/electron-e2e.js b/scripts/electron-e2e.js index a4ab433..7692dc9 100644 --- a/scripts/electron-e2e.js +++ b/scripts/electron-e2e.js @@ -226,7 +226,9 @@ async function main() { }); } if (process.platform === 'linux') { - await require('./linux-lifecycle-e2e')(electronApp, page, home); + await require('./linux-lifecycle-e2e')(electronApp, page, home, { + executablePath: electronPath, cwd: root, args, env, timeout: 120000, + }); } return; } diff --git a/scripts/linux-lifecycle-e2e.js b/scripts/linux-lifecycle-e2e.js index 6bfa208..e9b2d13 100644 --- a/scripts/linux-lifecycle-e2e.js +++ b/scripts/linux-lifecycle-e2e.js @@ -37,9 +37,16 @@ async function liveController(data) { const record = JSON.parse(fs.readFileSync(statusPath, 'utf8')); const pid = record.controller_pid; if (record.phase === 'ready' && Number.isInteger(pid) && pid > 0) { - const cmdline = fs.readFileSync(`/proc/${pid}/cmdline`, 'utf8').replace(/\0/g, ' '); - if (cmdline.includes('__update-controller')) return record; - last = `pid ${pid} command ${cmdline}`; + const command = Buffer.alloc(4096); + const fd = fs.openSync(`/proc/${pid}/cmdline`, 'r'); + let bytes = 0; + try { + bytes = fs.readSync(fd, command, 0, command.length, 0); + } finally { + fs.closeSync(fd); + } + if (command.subarray(0, bytes).includes('__update-controller')) return record; + last = `pid ${pid} is not the update controller`; } else { last = `phase ${record.phase}`; } @@ -51,7 +58,41 @@ async function liveController(data) { throw new Error(`Home system update check did not reach a live controller (${last})`); } -module.exports = async function (app, page, home) { +async function clickTray(app, id) { + const exit = new Promise((resolve) => app.process().once('exit', resolve)); + const clicked = app.evaluate((_electron, itemId) => { + const menu = global.__elastosTrayMenu; + const item = menu && menu.getMenuItemById(itemId); + if (!item || !item.enabled) return false; + item.click(); + return true; + }, id).catch(() => false); + const ok = await Promise.race([ + clicked, + exit.then(() => true), + ]); + assert.equal(ok, true, id); + await exit; +} + +function portClosed(port, host) { + const net = require('node:net'); + return new Promise((resolve) => { + const socket = net.connect({ port, host }); + const finish = (closed) => { + socket.removeAllListeners(); + socket.destroy(); + resolve(closed); + }; + socket.once('connect', () => finish(false)); + socket.once('error', () => finish(true)); + }); +} + +module.exports = async function (app, page, home, launch) { + assert.equal(await app.evaluate(() => global.__elastosTray), true); + console.log('PASS the tray icon is ready'); + await app.evaluate(({ shell }) => { global.__openedHome = []; shell.openExternal = async (url) => { global.__openedHome.push(url); }; @@ -90,4 +131,27 @@ module.exports = async function (app, page, home) { const update = JSON.parse(fs.readFileSync(path.join(data, 'update-check.json'), 'utf8')); assert.equal(update.outcome, 'up_to_date'); console.log('PASS elastos update --check writes up_to_date'); + + const keptPid = controller.controller_pid; + await clickTray(app, 'quit-keep-home'); + await health(true); + assert.equal(fs.existsSync(`/proc/${keptPid}`), true); + console.log('PASS Quit and keep Home leaves the controller running'); + + const { _electron: electron } = require('playwright'); + const reopened = await electron.launch(launch); + try { + const again = await reopened.firstWindow(); + await status(again, 'running'); + assert.equal(await again.locator('#open-label').innerText(), 'Open my computer'); + console.log('PASS a reopened launcher sees the retained Home'); + await clickTray(reopened, 'quit-stop-home'); + } finally { + await reopened.close().catch(() => {}); + } + await health(false); + assert.equal(await portClosed(8090, '127.0.0.1'), true); + assert.equal(await portClosed(8090, '::1'), true); + assert.equal(fs.existsSync(`/proc/${keptPid}`), false); + console.log('PASS Quit and stop Home after reopen stops the retained Home'); }; diff --git a/src/main/index.ts b/src/main/index.ts index cb80e84..5bd8c52 100644 --- a/src/main/index.ts +++ b/src/main/index.ts @@ -95,6 +95,7 @@ function createTray(): void { } tray = new Tray(icon.resize({ width: 16, height: 16 })); + (global as typeof globalThis & { __elastosTray?: true }).__elastosTray = true; tray.setToolTip('ElastOS'); updateTrayMenu(); @@ -139,6 +140,7 @@ function updateTrayMenu(): void { { type: 'separator' }, { label: 'Show Window', click: () => mainWindow?.show() }, ...(homeLaunchForPlatform(process.platform).offerKeepHomeOnQuit ? [{ + id: 'quit-keep-home', label: 'Quit and keep Home', click: () => { stopHomeOnQuit = false; @@ -147,6 +149,7 @@ function updateTrayMenu(): void { }, }] : []), { + id: 'quit-stop-home', label: 'Quit and stop Home', click: () => { stopHomeOnQuit = true; @@ -157,6 +160,7 @@ function updateTrayMenu(): void { ]); tray?.setContextMenu(contextMenu); + (global as typeof globalThis & { __elastosTrayMenu?: Menu }).__elastosTrayMenu = contextMenu; } // Set up status change listener diff --git a/src/main/targets/openAtLogin.ts b/src/main/targets/openAtLogin.ts index 527b2fa..3d1cfce 100644 --- a/src/main/targets/openAtLogin.ts +++ b/src/main/targets/openAtLogin.ts @@ -10,13 +10,33 @@ export function linuxAutostartPath(homeDir: string): string { return path.join(homeDir, '.config', 'autostart', 'elastos.desktop'); } +/** A mounted AppImage reports a temporary exec path. `$APPIMAGE` is the file the user keeps. */ +export function linuxAutostartExecPath(env: NodeJS.ProcessEnv, execPath: string): string { + const image = typeof env.APPIMAGE === 'string' ? env.APPIMAGE.trim() : ''; + return image || execPath; +} + +/** Quote a desktop Exec value when it contains a reserved character. */ +export function desktopExecValue(execPath: string): string { + if (/[\r\n\0]/.test(execPath)) { + throw new Error('The sign-in program path is not valid.'); + } + if (!/[\s"'\\><~|&;$*?#()`]/.test(execPath)) return execPath; + const escaped = execPath + .replace(/\\/g, '\\\\') + .replace(/"/g, '\\"') + .replace(/`/g, '\\`') + .replace(/\$/g, '\\$'); + return `"${escaped}"`; +} + export function linuxAutostartFile(execPath: string): string { return [ '[Desktop Entry]', 'Type=Application', 'Name=ElastOS', 'Comment=Open your computer', - `Exec=${execPath}`, + `Exec=${desktopExecValue(execPath)}`, 'X-GNOME-Autostart-enabled=true', '', ].join('\n'); @@ -63,7 +83,7 @@ export function syncLinuxAutostart( export function applyOpenAtLogin(enabled: boolean, homeDir: string = os.homedir()): void { writeOpenAtLogin(enabled, homeDir); if (process.platform === 'linux') { - syncLinuxAutostart(enabled, homeDir, process.execPath, { + syncLinuxAutostart(enabled, homeDir, linuxAutostartExecPath(process.env, process.execPath), { mkdirp: (dir) => fs.mkdirSync(dir, { recursive: true }), writeFile: (file, contents) => fs.writeFileSync(file, contents), remove: (file) => fs.rmSync(file, { force: true }), diff --git a/src/main/targets/runtimeGateway.ts b/src/main/targets/runtimeGateway.ts index d1e8a17..4e7c149 100644 --- a/src/main/targets/runtimeGateway.ts +++ b/src/main/targets/runtimeGateway.ts @@ -166,7 +166,7 @@ export function foreignListenerIsElastos(input: Parameters GatewayProcess; fetchHealth: () => Promise; @@ -295,31 +295,9 @@ export function procStatParent(stat: string): { pid: number; ppid: number } | nu return { pid, ppid }; } -/** `root` and every process that descends from it. A cycle is visited once. */ -export function descendantPids(root: number, rows: readonly { pid: number; ppid: number }[]): number[] { - const children = new Map(); - for (const row of rows) { - const list = children.get(row.ppid); - if (list) list.push(row.pid); - else children.set(row.ppid, [row.pid]); - } - const out: number[] = []; - const seen = new Set(); - const stack = [root]; - while (stack.length > 0) { - const pid = stack.pop() as number; - if (seen.has(pid)) continue; - seen.add(pid); - out.push(pid); - const kids = children.get(pid); - if (kids) for (const kid of kids) stack.push(kid); - } - return out; -} - /** - * The Home controller does not hold the listen socket. Its child does. - * A socket of a process outside that tree stays foreign. + * Sockets on `port` held by `root` itself. + * Home names the gateway pid in the controller status. A descendant is not that pid. */ export function listenersFromProcSnapshot( tcp: string, @@ -328,13 +306,147 @@ export function listenersFromProcSnapshot( rows: readonly ProcProcess[], port = GATEWAY_PORT, ): PortListener[] { - const tree = new Set(descendantPids(root, rows)); - const links: string[] = []; - for (const row of rows) { - if (!tree.has(row.pid)) continue; - for (const link of row.fdLinks) links.push(link); + const own = rows.find((row) => row.pid === root); + return procListenersFor(tcp, tcp6, own ? own.fdLinks : [], port); +} + +/** Field 22 of `/proc//stat`, the starttime tick. `comm` may contain spaces. */ +export function linuxStatStartTicks(stat: string): string | null { + const end = stat.lastIndexOf(')'); + if (end < 0) return null; + const ticks = stat.slice(end + 1).trim().split(/\s+/)[19]; + if (!ticks || !/^[0-9]+$/.test(ticks)) return null; + return ticks; +} + +/** + * The same birth string Runtime 2.0.0 stores in `controller_start` + * (`update_controller/child.rs` `process_identity`). + */ +export function linuxProcessIdentity(stat: string | null, bootId: string | null): string | null { + if (!stat) return null; + const ticks = linuxStatStartTicks(stat); + if (!ticks) return null; + const boot = (bootId ?? '').trim(); + if (!boot) return `linux:${ticks}`; + if (/[\r\n]/.test(boot)) return null; + return `linux:${boot}:${ticks}`; +} + +export interface LinuxHomeStatus { + controllerPid: number; + controllerStart: string; + hostPid: number; + generation: string; +} + +export interface HostLockRecord { + pid: number; + role: string; + addr: string; + generation: string; +} + +function positivePid(value: unknown): number | null { + return typeof value === 'number' && Number.isInteger(value) && value > 0 ? value : null; +} + +/** `update-controller/status.json` from Runtime 2.0.0. A missing field is not a Home. */ +export function parseLinuxHomeStatus(text: string | null): LinuxHomeStatus | null { + if (!text || text.length > 16 * 1024) return null; + let parsed: { + controller_pid?: unknown; + controller_start?: unknown; + host_pid?: unknown; + generation?: unknown; + }; + try { + parsed = JSON.parse(text) as typeof parsed; + } catch { + return null; + } + const controllerPid = positivePid(parsed.controller_pid); + const hostPid = positivePid(parsed.host_pid); + const controllerStart = typeof parsed.controller_start === 'string' ? parsed.controller_start : ''; + const generation = typeof parsed.generation === 'string' ? parsed.generation : ''; + if (!controllerPid || !hostPid || !controllerStart || !generation) return null; + if (controllerStart.length > 200 || generation.length > 128) return null; + if (/[\r\n]/.test(controllerStart) || /[\r\n]/.test(generation)) return null; + return { controllerPid, controllerStart, hostPid, generation }; +} + +/** `host-process.lock`. `generation` may be empty for a gateway this controller did not start. */ +export function parseHostLockRecord(text: string | null): HostLockRecord | null { + if (!text || text.length > 16 * 1024) return null; + let parsed: { pid?: unknown; role?: unknown; addr?: unknown; generation?: unknown }; + try { + parsed = JSON.parse(text) as typeof parsed; + } catch { + return null; + } + const pid = positivePid(parsed.pid); + if (!pid || typeof parsed.role !== 'string' || typeof parsed.addr !== 'string') return null; + const generation = typeof parsed.generation === 'string' ? parsed.generation : ''; + if (generation.length > 128 || /[\r\n]/.test(generation)) return null; + return { pid, role: parsed.role, addr: parsed.addr, generation }; +} + +/** The controller Runtime 2.0.0 recorded, proved against the host lock and `/proc`. */ +export interface ProvedLinuxHome { + controllerPid: number; + controllerStart: string; + hostPid: number; + hostStart: string; + generation: string; +} + +/** + * Fail closed. The host lock must name this gateway on `localhost:8090`. + * The status file must name that same pid, generation, and controller birth. + * The host birth must be the same value on both sides of the descriptor read. + */ +export function proveLinuxHome(input: { + statusText: string | null; + lockText: string | null; + bootId: string | null; + controllerStat: string | null; + hostStatBefore: string | null; + hostFdLinks: readonly string[] | null; + hostStatAfter: string | null; + tcp: string; + tcp6: string; + answered?: readonly string[]; +}): ProvedLinuxHome | null { + const status = parseLinuxHomeStatus(input.statusText); + const lock = parseHostLockRecord(input.lockText); + if (!status || !lock) return null; + if (lock.role !== 'gateway' || lock.addr !== GATEWAY_ADDR) return null; + if (lock.pid !== status.hostPid || lock.generation !== status.generation) return null; + const controllerNow = linuxProcessIdentity(input.controllerStat, input.bootId); + const controllerParsed = input.controllerStat ? procStatParent(input.controllerStat) : null; + if (controllerNow !== status.controllerStart || !controllerParsed || controllerParsed.pid !== status.controllerPid) { + return null; } - return procListenersFor(tcp, tcp6, links, port); + const before = linuxProcessIdentity(input.hostStatBefore, input.bootId); + const after = linuxProcessIdentity(input.hostStatAfter, input.bootId); + const hostParsed = input.hostStatBefore ? procStatParent(input.hostStatBefore) : null; + if (!before || before !== after || !hostParsed || hostParsed.pid !== status.hostPid) return null; + if (!input.hostFdLinks) return null; + const listeners = procListenersFor(input.tcp, input.tcp6, input.hostFdLinks); + if (listenerOwnership(listeners, LOOPBACK_ADDRESSES, input.answered ?? []) !== 'owned') return null; + return { + controllerPid: status.controllerPid, + controllerStart: status.controllerStart, + hostPid: status.hostPid, + hostStart: before, + generation: status.generation, + }; +} + +/** The pid to signal, or null when its birth no longer matches the proof. */ +export function linuxControllerSignalPid(proved: ProvedLinuxHome, identityNow: string | null): number | null { + if (!identityNow || identityNow !== proved.controllerStart) return null; + return proved.controllerPid; } /** @@ -783,7 +895,8 @@ export async function probeGatewayHealth(options: { } const PROC_STAT_MAX = 4096; -const PROC_TREE_MAX = 64; +const PROC_TEXT_MAX = 8 * 1024 * 1024; +const HOME_RECORD_MAX = 16 * 1024; function fdLinks(pid: number): string[] | null { const links: string[] = []; @@ -803,58 +916,106 @@ function fdLinks(pid: number): string[] | null { return links; } -/** Listeners held by `pid` or its descendants. Null when the tree cannot be read. */ -function linuxProcessListeners(pid: number): PortListener[] | null { - let tcp: string; +/** `undefined` when the path is absent. `null` when the bytes are not a bounded file. */ +function readProcOptional(file: string, max: number): string | null | undefined { + let fd: number | null = null; try { - tcp = fs.readFileSync('/proc/net/tcp', 'utf8'); - } catch { + fd = fs.openSync(file, fs.constants.O_RDONLY | fs.constants.O_NOFOLLOW); + const chunks: Buffer[] = []; + let total = 0; + const buf = Buffer.alloc(64 * 1024); + for (;;) { + const n = fs.readSync(fd, buf, 0, buf.length, null); + if (n <= 0) break; + total += n; + if (total > max) return null; + chunks.push(Buffer.from(buf.subarray(0, n))); + } + return Buffer.concat(chunks).toString('utf8'); + } catch (err) { + const code = err && typeof err === 'object' && 'code' in err ? String((err as { code?: string }).code) : ''; + if (code === 'ENOENT') return undefined; return null; + } finally { + if (fd !== null) { + try { fs.closeSync(fd); } catch { /* already closed */ } + } } - let tcp6 = ''; - try { - tcp6 = fs.readFileSync('/proc/net/tcp6', 'utf8'); - } catch { - // No IPv6 on this kernel. Nothing can listen on ::1. - tcp6 = ''; - } - let names: string[]; +} + +function readRegularText(file: string, max: number): string | null { + let fd: number | null = null; try { - names = fs.readdirSync('/proc'); + fd = fs.openSync(file, fs.constants.O_RDONLY | fs.constants.O_NOFOLLOW); + const info = fs.fstatSync(fd); + if (!info.isFile() || info.size > max) return null; + const buf = Buffer.alloc(info.size); + let offset = 0; + while (offset < info.size) { + const n = fs.readSync(fd, buf, offset, info.size - offset, offset); + if (n <= 0) return null; + offset += n; + } + return buf.toString('utf8'); } catch { return null; - } - const parents: { pid: number; ppid: number }[] = []; - for (const name of names) { - if (!/^[1-9][0-9]*$/.test(name)) continue; - try { - const buf = fs.readFileSync(`/proc/${name}/stat`); - if (buf.length > PROC_STAT_MAX) continue; - const parsed = procStatParent(buf.toString('utf8')); - if (parsed && parsed.pid === Number(name)) parents.push(parsed); - } catch { - // The process can exit between readdir and the stat read. + } finally { + if (fd !== null) { + try { fs.closeSync(fd); } catch { /* already closed */ } } } - if (!parents.some((row) => row.pid === pid)) return null; - let tree = descendantPids(pid, parents); - if (tree.length > PROC_TREE_MAX) { - tree = [pid, ...parents.filter((row) => row.ppid === pid).map((row) => row.pid)]; - } - if (tree.length > PROC_TREE_MAX) return null; - const rootLinks = fdLinks(pid); - if (!rootLinks) return null; - const rows: ProcProcess[] = [{ pid, ppid: parents.find((row) => row.pid === pid)?.ppid ?? 0, fdLinks: rootLinks }]; - for (const id of tree) { - if (id === pid) continue; - const links = fdLinks(id); - if (!links) return null; - rows.push({ pid: id, ppid: parents.find((row) => row.pid === id)?.ppid ?? 0, fdLinks: links }); - } - return listenersFromProcSnapshot(tcp, tcp6, pid, rows); } -/** LISTEN sockets on the gateway port, marked by whether `pid` or a descendant holds each. Null when they cannot be read. */ +/** Listeners held by `pid` itself. Null when `/proc` cannot prove that. */ +function linuxProcessListeners(pid: number): PortListener[] | null { + const tcp = readProcOptional('/proc/net/tcp', PROC_TEXT_MAX); + if (!tcp) return null; + const tcp6 = readProcOptional('/proc/net/tcp6', PROC_TEXT_MAX); + if (tcp6 === null) return null; + const links = fdLinks(pid); + if (!links) return null; + return procListenersFor(tcp, tcp6 ?? '', links); +} + +function readProvedLinuxHome(answered: readonly string[] = []): ProvedLinuxHome | null { + const data = runtimeDataDir('linux', os.homedir(), process.env); + const statusText = readRegularText(`${data}/update-controller/status.json`, HOME_RECORD_MAX); + const lockText = readRegularText(runtimeHostLockPath(data), HOME_RECORD_MAX); + const bootId = readProcOptional('/proc/sys/kernel/random/boot_id', 128); + if (bootId === null) return null; + const status = parseLinuxHomeStatus(statusText); + if (!status) return null; + const hostStatBefore = readProcOptional(`/proc/${status.hostPid}/stat`, PROC_STAT_MAX); + const hostFdLinks = fdLinks(status.hostPid); + const hostStatAfter = readProcOptional(`/proc/${status.hostPid}/stat`, PROC_STAT_MAX); + const controllerStat = readProcOptional(`/proc/${status.controllerPid}/stat`, PROC_STAT_MAX); + const tcp = readProcOptional('/proc/net/tcp', PROC_TEXT_MAX); + const tcp6 = readProcOptional('/proc/net/tcp6', PROC_TEXT_MAX); + if (!controllerStat || !hostStatBefore || !hostStatAfter || !tcp || tcp6 === null) return null; + return proveLinuxHome({ + statusText, + lockText, + bootId: bootId ?? null, + controllerStat, + hostStatBefore, + hostFdLinks, + hostStatAfter, + tcp, + tcp6: tcp6 ?? '', + answered, + }); +} + +function linuxControllerOwnsListeners(controllerPid: number, health: HealthResult): boolean { + const proved = readProvedLinuxHome(health.addresses ?? []); + if (!proved || proved.controllerPid !== controllerPid) return false; + const bootId = readProcOptional('/proc/sys/kernel/random/boot_id', 128); + const stat = readProcOptional(`/proc/${proved.controllerPid}/stat`, PROC_STAT_MAX); + if (bootId === null || !stat) return false; + return linuxControllerSignalPid(proved, linuxProcessIdentity(stat, bootId ?? null)) === proved.controllerPid; +} + +/** LISTEN sockets on the gateway port, marked by whether `pid` itself holds each. Null when they cannot be read. */ export async function localListeners(pid: number, platform: string = process.platform): Promise { if (!Number.isInteger(pid) || pid <= 0) return null; if (platform === 'linux') return linuxProcessListeners(pid); @@ -889,13 +1050,18 @@ export async function pidOwnsGatewayPort( return listenerOwnership(listeners, wants, answered) === 'owned'; } +/** Linux and Mac Stop and Quit take the installed Home. Windows does not. */ +export function platformAdoptsInstalledHome(platform: string): boolean { + return platform === 'darwin' || platform === 'linux'; +} + export function createDefaultGatewaySupervisor(binary: string, platform: string = process.platform): GatewaySupervisor { const launch = homeLaunchForPlatform(platform); return createGatewaySupervisor({ binary, args: launch.args, hideTerminalKeepLine: launch.hideTerminalKeepLine, - adoptForControls: platform === 'darwin', + adoptForControls: platformAdoptsInstalledHome(platform), healthTimeoutMs: platform === 'darwin' ? 150000 : 60000, spawn: spawnGatewayProcess, fetchHealth: () => probeGatewayHealth(), @@ -907,7 +1073,9 @@ export function createDefaultGatewaySupervisor(binary: string, platform: string foreignIsLegacy: async () => (await installedGatewayOnThisComputer()) === 'legacy', listenerOwned: (pid, health) => platform === 'darwin' ? confirmInstalledGateway() - : pidOwnsGatewayPort(pid, LOOPBACK_ADDRESSES, health.addresses ?? []), + : platform === 'linux' + ? linuxControllerOwnsListeners(pid, health) + : pidOwnsGatewayPort(pid, LOOPBACK_ADDRESSES, health.addresses ?? []), adoptInstalled: adoptInstalledGatewayProcess, }); } @@ -987,8 +1155,57 @@ export function localPidHasExited( * window did not spawn. A `127.0.0.1:8090` gateway from an earlier launcher is * adopted too, so Start, Reset, and Uninstall can stop it. */ +function signalErrorCode(err: unknown): string { + return err && typeof err === 'object' && 'code' in err ? String((err as { code?: string }).code) : ''; +} + +/** Linux Home. Signal the proved controller, or the legacy gateway's own pid. */ +async function adoptLinuxGatewayProcess(): Promise { + const data = runtimeDataDir('linux', os.homedir(), process.env); + const lockText = readRegularText(runtimeHostLockPath(data), HOME_RECORD_MAX); + const lock = parseHostLockRecord(lockText); + if (!lock) return null; + if (lock.addr === LEGACY_GATEWAY_ADDR) { + if (!(await hostLockGatewayKind(lockText, lock.pid))) return null; + const pid = lock.pid; + return { + pid, + onOutput() {}, + onExit() {}, + hasExited() { return localPidHasExited(pid); }, + signal(signal) { signalProcessGroup(pid, signal); }, + }; + } + if (lock.addr !== GATEWAY_ADDR || lock.role !== 'gateway') return null; + const proved = readProvedLinuxHome(); + if (!proved) return null; + return { + pid: proved.hostPid, + onOutput() {}, + onExit() {}, + hasExited() { + return localPidHasExited(proved.hostPid) && localPidHasExited(proved.controllerPid); + }, + signal(signal) { + const bootId = readProcOptional('/proc/sys/kernel/random/boot_id', 128); + const stat = readProcOptional(`/proc/${proved.controllerPid}/stat`, PROC_STAT_MAX); + if (bootId === null || !stat) return; + const target = linuxControllerSignalPid(proved, linuxProcessIdentity(stat, bootId ?? null)); + if (!target) return; + try { + process.kill(target, signal); + } catch (err) { + if (signalErrorCode(err) === 'ESRCH') return; + const message = err instanceof Error ? err.message : String(err); + throw new Error(`Could not signal ElastOS (${signal}): ${message}`); + } + }, + }; +} + export async function adoptInstalledGatewayProcess(): Promise { if (process.platform === 'win32') return null; + if (process.platform === 'linux') return adoptLinuxGatewayProcess(); const { text, pid } = readHostLock(); if (pid <= 0 || !(await hostLockGatewayKind(text, pid))) return null; let stopPid = pid; diff --git a/test/installer-ux.test.js b/test/installer-ux.test.js index b5d23a4..694d7fb 100644 --- a/test/installer-ux.test.js +++ b/test/installer-ux.test.js @@ -13,7 +13,7 @@ const { publisherHost, publisherOffline, } = require('../dist/main/targets/preflight'); -const { linuxAutostartFile, syncLinuxAutostart } = require('../dist/main/targets/openAtLogin'); +const { linuxAutostartFile, linuxAutostartExecPath, syncLinuxAutostart } = require('../dist/main/targets/openAtLogin'); const flow = require('../src/renderer/flow.js'); test('launcher logs omit terminal-only advice and retain replacement diagnostics', () => { @@ -110,6 +110,13 @@ test('sign-in launch writes a desktop file and can remove it', () => { assert.match(files.get(written), /Name=ElastOS/); assert.match(files.get(written), /X-GNOME-Autostart-enabled=true/); assert.match(linuxAutostartFile('/usr/bin/elastos'), /Exec=\/usr\/bin\/elastos/); + assert.equal( + linuxAutostartExecPath({ APPIMAGE: '/home/me/ElastOS.AppImage' }, '/tmp/.mount_abc/elastos'), + '/home/me/ElastOS.AppImage', + ); + assert.equal(linuxAutostartExecPath({ APPIMAGE: ' ' }, '/usr/bin/elastos'), '/usr/bin/elastos'); + assert.match(linuxAutostartFile('/home/me/ElastOS App.AppImage'), /Exec="\/home\/me\/ElastOS App\.AppImage"/); + assert.match(linuxAutostartFile('/home/me/ElastOS-$APP.AppImage'), /Exec="\/home\/me\/ElastOS-\\\$APP\.AppImage"/); assert.equal(syncLinuxAutostart(false, '/home/tester', '/usr/bin/elastos', fs), null); assert.equal(files.size, 0); }); diff --git a/test/linux-arm64.test.js b/test/linux-arm64.test.js index 0620582..0eaab24 100644 --- a/test/linux-arm64.test.js +++ b/test/linux-arm64.test.js @@ -65,8 +65,14 @@ test('linux e2e runs the linux lifecycle and leaves the mac lifecycle on darwin' assert.match(life, /update-controller', 'status.json'/); assert.match(life, /__update-controller/); assert.match(life, /PASS elastos update --check writes up_to_date/); + assert.match(life, /PASS the tray icon is ready/); + assert.match(life, /__elastosTray/); + assert.match(life, /quit-keep-home/); + assert.match(life, /quit-stop-home/); + assert.match(life, /PASS Quit and keep Home leaves the controller running/); + assert.match(life, /PASS Quit and stop Home after reopen stops the retained Home/); assert.equal(life.includes('waitForFunction'), false); - assert.equal(life.includes('__elastosTray'), false); + assert.equal(life.includes('command ${'), false); assert.equal(life.includes('Application Support'), false); assert.equal(life.includes('home --browser'), false); assert.match(life, /\.local', 'share', 'elastos'/); diff --git a/test/runtime-gateway.test.js b/test/runtime-gateway.test.js index 3f55762..1454768 100644 --- a/test/runtime-gateway.test.js +++ b/test/runtime-gateway.test.js @@ -26,8 +26,12 @@ const { procNetAddress, procNetListeners, procStatParent, - descendantPids, listenersFromProcSnapshot, + linuxProcessIdentity, + linuxStatStartTicks, + proveLinuxHome, + linuxControllerSignalPid, + platformAdoptsInstalledHome, } = require('../dist/main/targets/runtimeGateway'); const { uninstallRuntime } = require('../dist/main/targets/runtimeUninstall'); @@ -228,21 +232,27 @@ test('the gateway must own every localhost listener, on 127.0.0.1 and on ::1', ( assert.equal(listenerOwnership(procListenersFor(tcp, tcp6, ['socket:[4242]', 'socket:[4343]']), wants, ['::1']), 'owned'); }); -test('a Home controller owns port 8090 when its child listens', () => { +function procStat(pid, ppid, start) { + const fields = ['S', String(ppid), ...Array(17).fill('0'), String(start)]; + return `${pid} (elastos) ${fields.join(' ')}`; +} + +test('a Home controller does not own a descendant socket', () => { const tcp = [TCP_HEADER, tcpRow('0100007F', 4242)].join('\n'); const tcp6 = [TCP_HEADER, tcpRow(V6_LOOPBACK, 4343)].join('\n'); const wants = ['127.0.0.1', '::1']; assert.deepEqual(procStatParent('20 (elastos home) S 10 9'), { pid: 20, ppid: 10 }); assert.equal(procStatParent('no-paren'), null); - assert.deepEqual( - descendantPids(10, [{ pid: 20, ppid: 10 }, { pid: 21, ppid: 20 }, { pid: 30, ppid: 1 }]).sort((a, b) => a - b), - [10, 20, 21], - ); + assert.equal(linuxStatStartTicks(procStat(20, 10, 200)), '200'); + assert.equal(linuxStatStartTicks('20 (elastos home) S 10'), null); + assert.equal(linuxProcessIdentity(procStat(10, 1, 100), 'boot-1'), 'linux:boot-1:100'); const child = [ { pid: 10, ppid: 1, fdLinks: ['pipe:[1]'] }, { pid: 20, ppid: 10, fdLinks: ['socket:[4242]', 'socket:[4343]'] }, ]; - assert.equal(listenerOwnership(listenersFromProcSnapshot(tcp, tcp6, 10, child), wants), 'owned'); + assert.equal(listenerOwnership(listenersFromProcSnapshot(tcp, tcp6, 10, child), wants), 'foreign'); + const host = [{ pid: 20, ppid: 10, fdLinks: ['socket:[4242]', 'socket:[4343]'] }]; + assert.equal(listenerOwnership(listenersFromProcSnapshot(tcp, tcp6, 20, host), wants), 'owned'); const stranger = [ { pid: 10, ppid: 1, fdLinks: [] }, { pid: 20, ppid: 10, fdLinks: ['socket:[4242]'] }, @@ -251,6 +261,89 @@ test('a Home controller owns port 8090 when its child listens', () => { assert.equal(listenerOwnership(listenersFromProcSnapshot(tcp, tcp6, 10, stranger), wants), 'foreign'); }); +test('Linux Home ownership follows the controller record, not a descendant or a reused pid', () => { + const tcp = [TCP_HEADER, tcpRow('0100007F', 4242)].join('\n'); + const tcp6 = [TCP_HEADER, tcpRow(V6_LOOPBACK, 4343)].join('\n'); + const bootId = 'boot-1'; + const statusText = JSON.stringify({ + phase: 'ready', + controller_pid: 10, + controller_start: 'linux:boot-1:100', + host_pid: 20, + generation: 'abc', + }); + const lockText = JSON.stringify({ + pid: 20, role: 'gateway', addr: 'localhost:8090', generation: 'abc', + }); + const proved = proveLinuxHome({ + statusText, + lockText, + bootId, + controllerStat: procStat(10, 1, 100), + hostStatBefore: procStat(20, 10, 200), + hostFdLinks: ['socket:[4242]', 'socket:[4343]'], + hostStatAfter: procStat(20, 10, 200), + tcp, + tcp6, + }); + assert.equal(proved && proved.controllerPid, 10); + assert.equal(linuxControllerSignalPid(proved, 'linux:boot-1:100'), 10); + assert.equal(linuxControllerSignalPid(proved, 'linux:boot-1:999'), null); + assert.equal(linuxControllerSignalPid(proved, null), null); + + const descendant = proveLinuxHome({ + statusText, + lockText, + bootId, + controllerStat: procStat(10, 1, 100), + hostStatBefore: procStat(20, 10, 200), + hostFdLinks: ['pipe:[1]'], + hostStatAfter: procStat(20, 10, 200), + tcp, + tcp6, + }); + assert.equal(descendant, null); + + const reused = proveLinuxHome({ + statusText, + lockText, + bootId, + controllerStat: procStat(10, 1, 100), + hostStatBefore: procStat(20, 10, 200), + hostFdLinks: ['socket:[4242]', 'socket:[4343]'], + hostStatAfter: procStat(20, 10, 300), + tcp, + tcp6, + }); + assert.equal(reused, null); + + const stale = proveLinuxHome({ + statusText, + lockText, + bootId, + controllerStat: procStat(10, 1, 50), + hostStatBefore: procStat(20, 10, 200), + hostFdLinks: ['socket:[4242]', 'socket:[4343]'], + hostStatAfter: procStat(20, 10, 200), + tcp, + tcp6, + }); + assert.equal(stale, null); + + const wrongRole = proveLinuxHome({ + statusText, + lockText: JSON.stringify({ pid: 20, role: 'serve', addr: 'localhost:8090', generation: 'abc' }), + bootId, + controllerStat: procStat(10, 1, 100), + hostStatBefore: procStat(20, 10, 200), + hostFdLinks: ['socket:[4242]', 'socket:[4343]'], + hostStatAfter: procStat(20, 10, 200), + tcp, + tcp6, + }); + assert.equal(wrongRole, null); +}); + test('lsof listeners name the owner pid for IPv4, [::1], and *', () => { const out = ['p41', 'f7', 'n127.0.0.1:8090', 'f8', 'n[::1]:8090', 'p99', 'f3', 'n*:8090', 'p100', 'n127.0.0.1:9000'].join('\n'); assert.deepEqual(parseLsofListeners(out, 41), [ @@ -859,6 +952,9 @@ test('logs omit attach secrets', async () => { assert.equal(homeLaunchForPlatform('linux').hideTerminalKeepLine, true); assert.equal(homeLaunchForPlatform('linux').openBrowserAfterInstall, false); assert.equal(homeLaunchForPlatform('linux').offerKeepHomeOnQuit, true); + assert.equal(platformAdoptsInstalledHome('linux'), true); + assert.equal(platformAdoptsInstalledHome('darwin'), true); + assert.equal(platformAdoptsInstalledHome('win32'), false); assert.deepEqual(homeLaunchForPlatform('darwin').args, ['home', '--browser']); assert.equal(homeLaunchForPlatform('darwin').quitWhenLastWindowCloses, false); assert.equal(homeLaunchForPlatform('darwin').updateRestartsHome, true); From 8607ddf76e20979bc0ba763bc99c060b77c093a7 Mon Sep 17 00:00:00 2001 From: Anders Alm Date: Sat, 7 Nov 2026 23:13:06 -0500 Subject: [PATCH 10/19] Read the launcher update check when Runtime 2.0.0 does not write one. The Mac branch stores that record under .elastos-launcher. The Linux Electron test still opened the runtime data file, so both Linux e2e jobs failed. Co-authored-by: Cursor --- scripts/linux-lifecycle-e2e.js | 4 +++- test/linux-arm64.test.js | 1 + 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/scripts/linux-lifecycle-e2e.js b/scripts/linux-lifecycle-e2e.js index e9b2d13..942578f 100644 --- a/scripts/linux-lifecycle-e2e.js +++ b/scripts/linux-lifecycle-e2e.js @@ -128,7 +128,9 @@ module.exports = async function (app, page, home, launch) { const checked = await page.evaluate(() => window.elastos.checkForUpdate()); assert.equal(checked.updateAvailable, false); - const update = JSON.parse(fs.readFileSync(path.join(data, 'update-check.json'), 'utf8')); + const nativeUpdate = path.join(data, 'update-check.json'); + const update = JSON.parse(fs.readFileSync(fs.existsSync(nativeUpdate) ? nativeUpdate + : path.join(home, '.elastos-launcher', 'update-check.json'), 'utf8')); assert.equal(update.outcome, 'up_to_date'); console.log('PASS elastos update --check writes up_to_date'); diff --git a/test/linux-arm64.test.js b/test/linux-arm64.test.js index 0eaab24..5595632 100644 --- a/test/linux-arm64.test.js +++ b/test/linux-arm64.test.js @@ -65,6 +65,7 @@ test('linux e2e runs the linux lifecycle and leaves the mac lifecycle on darwin' assert.match(life, /update-controller', 'status.json'/); assert.match(life, /__update-controller/); assert.match(life, /PASS elastos update --check writes up_to_date/); + assert.match(life, /\.elastos-launcher', 'update-check.json'/); assert.match(life, /PASS the tray icon is ready/); assert.match(life, /__elastosTray/); assert.match(life, /quit-keep-home/); From 97cdeca1c53db8c6cde255c1b61b85731c1e4f24 Mon Sep 17 00:00:00 2001 From: Anders Alm Date: Sat, 7 Nov 2026 23:56:44 -0500 Subject: [PATCH 11/19] Signal a Linux Home only after the update controller still matches. A host pid and a process group are no longer signal targets, and a gateway on 127.0.0.1:8090 is left running. Co-authored-by: Cursor --- CONTRIBUTING.md | 2 +- docs/RUNTIME_MIGRATION.md | 2 +- src/main/index.ts | 4 +- src/main/targets/runtimeGateway.ts | 227 ++++++++++++++++++-------- src/main/targets/runtimeTarget.ts | 4 + src/main/targets/types.ts | 3 +- src/preload/index.ts | 2 +- src/renderer/app.js | 6 +- src/renderer/flow.js | 3 + test/installer-ux.test.js | 3 + test/runtime-gateway.test.js | 247 +++++++++++++++++++---------- 11 files changed, 345 insertions(+), 158 deletions(-) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 3befda8..f8f126f 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -14,7 +14,7 @@ A wrong signature or channel, version below the floor, changed metadata snapshot - Home is `http://localhost:8090/home/`. - Update offers require signed metadata. Runtime 2.0.0 needs a compatibility `update-check.json` record after a successful CLI check. Human-readable stdout never determines the offer. A 2.0.0 source with an unknown head uses the stored signed install record and matching binary version for rollback identity. - A foreign listener on 8090 keeps running and its specific error reaches the window. A status probe that overlaps Start, Stop, or Update must honor the newer control phase. -- On Mac, the signed Home controller owns System update restarts. Re-read the verified host generation before Stop. On Linux, Stop and Quit signal the controller only when `status.json` and the host lock prove it, and the start time in `/proc` still matches. Windows signals the gateway process group with `SIGTERM`, 15 seconds, then `SIGKILL`, and only after the pid has exited and `/healthz` has failed twice. +- On Mac, the signed Home controller owns System update restarts. Re-read the verified host generation before Stop. On Linux, Stop and Quit signal the update controller only, and only after a fresh read of its `/proc` start time, its exe, and the host lock generation. A mismatch sends no signal. A gateway on `127.0.0.1:8090` stays running and has no Stop control. A process the launcher spawned is signaled through its own process handle. Windows signals the gateway process group with `SIGTERM`, 15 seconds, then `SIGKILL`, and only after the pid has exited and `/healthz` has failed twice. - Reset and uninstall remove only the ElastOS program, its data directory, and the launcher stage file. Other home directories stay on disk. - IPC channel names are `elastos:*`. The preload object is `window.elastos`. - `src/main/index.ts` does not import `./targets`. diff --git a/docs/RUNTIME_MIGRATION.md b/docs/RUNTIME_MIGRATION.md index 1abf42c..613c603 100644 --- a/docs/RUNTIME_MIGRATION.md +++ b/docs/RUNTIME_MIGRATION.md @@ -68,7 +68,7 @@ Uninstall on Windows removes the whole ElastOS WSL2 Linux environment with `wsl. Remove PC2 is a separate action in `src/main/legacyPc2Removal.ts`. The button stays hidden until a legacy install is on disk: `~/.pc2`, `~/.elastos/node` when it is the old bundled Node 22.13.1 tree, a PC2 launch agent or autostart file, a sudoers file whose text matches the rules the old installer wrote (`/etc/sudoers.d/wireguard` with `wg-quick`, or `/etc/sudoers.d/amneziawg` with `NOPASSWD:SETENV`, `amneziawg-go`, and `/var/run/amneziawg/`) together with one of those installs, a `~/.pc2` folder inside another Windows Linux distro, or a Windows distro named `pc2` or `pc2-wsl` that itself contains that folder or Node tree. The old installer never wrote `/etc/sudoers.d/elastos` or `/etc/sudoers.d/pc2-wireguard`. This repo has no hash for the VPN programs it compiled, so those programs are not deleted by name. The ElastOS distro is never unregistered. The confirm dialog lists each path and its size. Removal deletes only the paths from that list. “Back up my PC2 data first” must write a backup before anything is deleted, including a Windows Linux folder or distro; if that backup cannot be saved, nothing is removed. One privileged prompt covers a matching sudoers rule. That prompt is pkexec. Cancelling it (exit 126), a missing authorization or a missing prompt (exit 127), and a missing pkexec program each have their own sentence. pkexec is not replaced with sudo. An exit after the prompt has started is the removal command's own result. The list of files still there is what that privileged script can see, including a sudoers file the app itself cannot stat. A failure says what is still there and saves a support bundle. -On Mac and Linux, Stop and Quit re-read the installed Home and signal its verified controller when the host lock and the update-controller status agree. Linux re-reads that controller's start time from /proc immediately before the signal. A descendant, a reused pid, or a stale status file is left running. The controller drains its children. Windows retains gateway process-group supervision with `SIGTERM`, 15 seconds, then `SIGKILL`, and two failed health probes after the pid exits. Quit waits through shutdown and its health probes. Reset and Uninstall, after the confirm dialog, adopt that gateway from the host lock and signal the pid they read. They do not ask again. On Windows they adopt only when the distro facts say the listener is ElastOS. A different listener, and a facts read that fails, is left running. On macOS and Linux the adopt itself checks the host lock, the command line, and the health socket. On Windows, an error asking whether that pid has exited is treated as still running. Exit 75 restarts only when the binary was replaced on disk. +On Mac and Linux, Stop and Quit re-read the installed Home and signal its verified controller when the host lock and the update-controller status agree. Linux reads the controller start time from /proc, the controller exe, and the host lock generation immediately before every signal. A reused pid, a stale status file, a wrong exe, or a generation mismatch is left running, and the window says to stop that Home with Ctrl+C. Linux does not signal a host pid, a process group, or a descendant, and it does not adopt a gateway on 127.0.0.1:8090. That gateway is shown as another ElastOS Home with no Stop control. A process the launcher spawned is signaled through its own process handle. The controller drains its children. Windows retains gateway process-group supervision with `SIGTERM`, 15 seconds, then `SIGKILL`, and two failed health probes after the pid exits. Quit waits through shutdown and its health probes. Reset and Uninstall, after the confirm dialog, adopt that gateway from the host lock and signal the pid they read. They do not ask again. On Windows they adopt only when the distro facts say the listener is ElastOS. A different listener, and a facts read that fails, is left running. On macOS and Linux the adopt itself checks the host lock, the command line, and the health socket. On Windows, an error asking whether that pid has exited is treated as still running. Exit 75 restarts only when the binary was replaced on disk. The support bundle redacts labeled secrets (`password`, `token`, `api_key`, `attach_secret`, `cookie`, `authorization`, `seed`, `mnemonic`, `private_key`, `secret`, bearer tokens, and JWTs), the rest of a `seed`, `mnemonic`, `private_key`, or `secret` line, a run of 12 or more BIP39 words in any case, split by spaces, line breaks, commas, hyphens, quotes, or numbering such as `1.` or `2:`, known secret prefixes (AWS access key ids, `ghp_` tokens, and `sk-` keys), hex of 32 or more characters with or without `0x`, including a 64-character hex string unless that line is labelled sha256 or hash, hex wrapped over two or more lines that holds 32 or more characters together (a list of whole 40- or 64-character hashes stays), an unlabeled uppercase token of 16 or more characters that contains a digit and no underscore, a lowercase token of 32 or more characters with high entropy, and an unlabeled mixed-case token of 20 or more characters with high entropy. It keeps paths, a 40-character hex hash on its own line or beside a hash, cid, commit, or installer label, a 64-character hex string on a sha256 or hash line, CIDv0 and CIDv1, `did:key` values, versions, UUIDs, and `UPPER_SNAKE` names. An unlabeled secret shorter than that, or with low entropy, is not redacted. `secret-line` is a short phrase that stays. diff --git a/src/main/index.ts b/src/main/index.ts index 5bd8c52..09a2d91 100644 --- a/src/main/index.ts +++ b/src/main/index.ts @@ -115,7 +115,8 @@ function updateTrayMenu(): void { 'starting': '🟡 Starting...', 'stopping': '🟡 Stopping...', 'error': '🔴 Error', - 'not-installed': '⚪ Not Installed' + 'not-installed': '⚪ Not Installed', + 'other-home': 'another ElastOS Home is running', }; const contextMenu = Menu.buildFromTemplate([ @@ -128,6 +129,7 @@ function updateTrayMenu(): void { }, { label: 'Stop', + visible: currentStatus !== 'other-home', enabled: currentStatus === 'running', click: () => { void launch.stop(); } }, diff --git a/src/main/targets/runtimeGateway.ts b/src/main/targets/runtimeGateway.ts index 4e7c149..c521b50 100644 --- a/src/main/targets/runtimeGateway.ts +++ b/src/main/targets/runtimeGateway.ts @@ -14,7 +14,7 @@ import { LOOPBACK_ADDRESSES, } from './gatewayAddress'; import { runtimeChildEnv } from './releaseHead'; -import { runtimeDataDir, runtimeHostLockPath } from './runtimePaths'; +import { runtimeBinaryPath, runtimeDataDir, runtimeHostLockPath } from './runtimePaths'; export { HEALTH_URL, HOME_URL, LEGACY_GATEWAY_ADDR, LOOPBACK_ADDRESSES }; @@ -52,6 +52,9 @@ export const FOREIGN_LISTENER_MESSAGE = `Another program is answering at ${GATEWAY_ADDR}, so Home was not opened. Quit that program and click Try again.`; export const LEGACY_STILL_RUNNING_MESSAGE = 'An older ElastOS is still running and could not be stopped. Quit it, then click Start.'; +export const HOME_UNCONFIRMED_MESSAGE = + 'Home could not be confirmed; stop it with Ctrl+C in its terminal'; +export const OTHER_HOME_MESSAGE = 'another ElastOS Home is running'; /** A gateway this window did not start. Callers match the type, not the sentence. */ export class ForeignGatewayError extends Error { @@ -77,6 +80,8 @@ export interface HealthResult { export interface GatewayProcess { readonly pid: number; + /** True only for the ChildProcess this launcher created. Stop keeps that handle. */ + readonly spawnedHere?: boolean; onOutput(listener: (chunk: string) => void): void; onExit(listener: (code: number | null) => void): void; signal(signal: NodeJS.Signals): void; @@ -95,29 +100,11 @@ export function binaryReplacement(output: string, code: number | null): boolean return /was replaced on disk|changed on disk/i.test(output); } -/** The gateway is its own process group. Signal the group, not only the leader. */ -export function signalProcessGroup( - pid: number, - signal: NodeJS.Signals, - kill: (pid: number, signal: NodeJS.Signals) => void = process.kill, -): void { - if (!Number.isInteger(pid) || pid <= 0) return; - try { - kill(-pid, signal); - } catch (err) { - const code = err && typeof err === 'object' && 'code' in err - ? String((err as { code?: string }).code) - : ''; - if (code === 'ESRCH') return; - const message = err instanceof Error ? err.message : String(err); - throw new Error(`Could not signal ElastOS (${signal}): ${message}`); - } -} - /** * `current` is a gateway on `localhost:8090`, the address this launcher * starts. `legacy` is one an earlier launcher started on `127.0.0.1:8090`. - * A legacy gateway is only stopped and started again. Home never opens on it. + * Linux does not signal a legacy gateway. Windows may stop its distro + * gateway and start `localhost:8090`. Home never opens on the legacy one. */ export type InstalledGatewayKind = 'current' | 'legacy'; @@ -183,6 +170,11 @@ export interface GatewaySupervisorDeps { * starts it again on `localhost:8090`. */ foreignIsLegacy?: () => Promise; + /** + * Linux sets this. A bare gateway on 127.0.0.1:8090 is another Home. + * Start reports that and does not signal it. Windows leaves this unset. + */ + reportLegacyHome?: () => Promise; /** * An OK body counts only when this returns true: the started gateway owns * every `localhost` address that answered. Without it, OK is enough. @@ -207,7 +199,7 @@ export interface GatewaySupervisor { * Uninstall, after the person confirmed. Quit, Stop, and Restart omit it. */ stop(options?: { adopt?: boolean }): Promise; - /** SIGKILL the process group this supervisor is stopping. Used when quit runs out of time. */ + /** SIGKILL the process this supervisor is stopping. Used when quit runs out of time. */ forceKill(): void; openHome(): void; getLogs(lines?: number): string; @@ -449,6 +441,70 @@ export function linuxControllerSignalPid(proved: ProvedLinuxHome, identityNow: s return proved.controllerPid; } +/** One fresh read of the controller record, the lock, and `/proc`. */ +export interface ControllerObservation { + statusText: string | null; + lockText: string | null; + bootId: string | null; + controllerStat: string | null; + exePath: string | null; + allowedExes: readonly string[]; +} + +/** + * The update controller pid, or null. The start time, the exe, and the host + * lock generation must all match this read. A host pid is not a target. + */ +export function confirmedControllerPid(observed: ControllerObservation): number | null { + const status = parseLinuxHomeStatus(observed.statusText); + const lock = parseHostLockRecord(observed.lockText); + if (!status || !lock) return null; + if (lock.role !== 'gateway' || lock.addr !== GATEWAY_ADDR) return null; + if (!status.generation || lock.generation !== status.generation) return null; + const identity = linuxProcessIdentity(observed.controllerStat, observed.bootId); + const parsed = observed.controllerStat ? procStatParent(observed.controllerStat) : null; + if (identity !== status.controllerStart || !parsed || parsed.pid !== status.controllerPid) return null; + const exe = observed.exePath; + if (!exe || exe.endsWith(' (deleted)')) return null; + if (!observed.allowedExes.includes(exe)) return null; + return status.controllerPid; +} + +/** Read the controller, then signal that pid. A mismatch signals nothing. */ +export function signalRecordedController( + signal: NodeJS.Signals, + read: () => ControllerObservation, + kill: (pid: number, signal: NodeJS.Signals) => void = process.kill, +): void { + const target = confirmedControllerPid(read()); + if (!target) throw new Error(HOME_UNCONFIRMED_MESSAGE); + try { + kill(target, signal); + } catch (err) { + if (signalErrorCode(err) === 'ESRCH') return; + const message = err instanceof Error ? err.message : String(err); + throw new Error(`Could not signal ElastOS (${signal}): ${message}`); + } +} + +/** Every signal re-reads the controller. The pid field is not a signal target. */ +export function controllerGateway( + read: () => ControllerObservation, + kill?: (pid: number, signal: NodeJS.Signals) => void, +): GatewayProcess { + return { + pid: -1, + onOutput() {}, + onExit() {}, + hasExited() { + return confirmedControllerPid(read()) === null; + }, + signal(signal) { + signalRecordedController(signal, read, kill); + }, + }; +} + /** * `lsof -nP -iTCP: -sTCP:LISTEN -Fpn` output. `n` names look like * `127.0.0.1:8090`, `[::1]:8090`, or `*:8090`. A socket of another account is @@ -674,6 +730,10 @@ export function createGatewaySupervisor(deps: GatewaySupervisorDeps): GatewaySup const result = await launchOnce(); if (result === 'replaced') continue; if (result === 'already') { + if (deps.reportLegacyHome && await deps.reportLegacyHome()) { + current = 'error'; + throw new Error(OTHER_HOME_MESSAGE); + } if (!legacyStopped && deps.foreignIsLegacy && await deps.foreignIsLegacy()) { // An earlier launcher started it on 127.0.0.1. Passkeys need // localhost, so stop it once and start it again here. @@ -715,7 +775,10 @@ export function createGatewaySupervisor(deps: GatewaySupervisorDeps): GatewaySup } }, async stop(options?: { adopt?: boolean }) { - if (deps.adoptForControls && isHealthOk(await deps.fetchHealth())) { + const currentProc = owned; + const keepSpawned = currentProc !== null && currentProc.spawnedHere === true + && !(await currentProc.hasExited()); + if (!keepSpawned && deps.adoptForControls && isHealthOk(await deps.fetchHealth())) { const installed = await (deps.adoptInstalled?.() ?? null); if (!installed) throw new ForeignGatewayError(); owned = installed; @@ -789,8 +852,15 @@ export function spawnGatewayProcess(binary: string, args: readonly string[]): Ga hasExited() { return exited; }, + spawnedHere: true, signal(signal) { - signalProcessGroup(child.pid ?? -1, signal); + try { + child.kill(signal); + } catch (err) { + if (signalErrorCode(err) === 'ESRCH') return; + const message = err instanceof Error ? err.message : String(err); + throw new Error(`Could not signal ElastOS (${signal}): ${message}`); + } }, }; } @@ -1070,7 +1140,7 @@ export function createDefaultGatewaySupervisor(binary: string, platform: string openUrl: openRuntimeHome, log: (line) => logSink(line), confirmForeign: confirmInstalledGateway, - foreignIsLegacy: async () => (await installedGatewayOnThisComputer()) === 'legacy', + reportLegacyHome: async () => (await installedGatewayOnThisComputer()) === 'legacy', listenerOwned: (pid, health) => platform === 'darwin' ? confirmInstalledGateway() : platform === 'linux' @@ -1151,58 +1221,82 @@ export function localPidHasExited( } /** - * The installed gateway from the host lock, so Stop can signal a process this - * window did not spawn. A `127.0.0.1:8090` gateway from an earlier launcher is - * adopted too, so Start, Reset, and Uninstall can stop it. + * Stop can signal one process this window did not spawn: the update controller + * named by status.json. A `127.0.0.1:8090` gateway is not that process. */ function signalErrorCode(err: unknown): string { return err && typeof err === 'object' && 'code' in err ? String((err as { code?: string }).code) : ''; } -/** Linux Home. Signal the proved controller, or the legacy gateway's own pid. */ -async function adoptLinuxGatewayProcess(): Promise { +function resolvedFile(file: string): string | null { + try { + const real = fs.realpathSync(file); + return real ? real : null; + } catch { + return null; + } +} + +function controllerExeFromProc(pid: number): string | null { + let link: string; + try { + link = fs.readlinkSync(`/proc/${pid}/exe`); + } catch { + return null; + } + if (!link || link.endsWith(' (deleted)')) return null; + return resolvedFile(link); +} + +/** The installed binary, and the controller copy Runtime stores under the data dir. */ +function allowedControllerExes(dataDir: string): string[] { + const files = [ + runtimeBinaryPath(os.homedir()), + `${dataDir}/update-controller/runtime`, + ]; + const allowed: string[] = []; + for (const file of files) { + const real = resolvedFile(file); + if (real && !allowed.includes(real)) allowed.push(real); + } + return allowed; +} + +function observeRecordedController(): ControllerObservation { const data = runtimeDataDir('linux', os.homedir(), process.env); + const statusText = readRegularText(`${data}/update-controller/status.json`, HOME_RECORD_MAX); const lockText = readRegularText(runtimeHostLockPath(data), HOME_RECORD_MAX); - const lock = parseHostLockRecord(lockText); - if (!lock) return null; - if (lock.addr === LEGACY_GATEWAY_ADDR) { - if (!(await hostLockGatewayKind(lockText, lock.pid))) return null; - const pid = lock.pid; - return { - pid, - onOutput() {}, - onExit() {}, - hasExited() { return localPidHasExited(pid); }, - signal(signal) { signalProcessGroup(pid, signal); }, - }; - } - if (lock.addr !== GATEWAY_ADDR || lock.role !== 'gateway') return null; - const proved = readProvedLinuxHome(); - if (!proved) return null; + const boot = readProcOptional('/proc/sys/kernel/random/boot_id', 128); + const status = parseLinuxHomeStatus(statusText); + const pid = status ? status.controllerPid : 0; + const stat = pid > 0 ? readProcOptional(`/proc/${pid}/stat`, PROC_STAT_MAX) : null; return { - pid: proved.hostPid, - onOutput() {}, - onExit() {}, - hasExited() { - return localPidHasExited(proved.hostPid) && localPidHasExited(proved.controllerPid); - }, - signal(signal) { - const bootId = readProcOptional('/proc/sys/kernel/random/boot_id', 128); - const stat = readProcOptional(`/proc/${proved.controllerPid}/stat`, PROC_STAT_MAX); - if (bootId === null || !stat) return; - const target = linuxControllerSignalPid(proved, linuxProcessIdentity(stat, bootId ?? null)); - if (!target) return; - try { - process.kill(target, signal); - } catch (err) { - if (signalErrorCode(err) === 'ESRCH') return; - const message = err instanceof Error ? err.message : String(err); - throw new Error(`Could not signal ElastOS (${signal}): ${message}`); - } - }, + statusText, + lockText, + bootId: boot ?? null, + controllerStat: stat ?? null, + exePath: pid > 0 ? controllerExeFromProc(pid) : null, + allowedExes: allowedControllerExes(data), }; } +/** `controller` may be signaled. `other-home` is a legacy gateway and is never signaled. */ +export function linuxControllerAdopt(lockText: string | null): 'controller' | 'other-home' | 'none' { + const lock = parseHostLockRecord(lockText); + if (!lock || lock.role !== 'gateway') return 'none'; + if (lock.addr === LEGACY_GATEWAY_ADDR) return 'other-home'; + if (lock.addr !== GATEWAY_ADDR) return 'none'; + return 'controller'; +} + +/** Linux Home. Signal only the recorded update controller. A legacy gateway is not adopted. */ +async function adoptLinuxGatewayProcess(): Promise { + const data = runtimeDataDir('linux', os.homedir(), process.env); + const lockText = readRegularText(runtimeHostLockPath(data), HOME_RECORD_MAX); + if (linuxControllerAdopt(lockText) !== 'controller') return null; + return controllerGateway(observeRecordedController); +} + export async function adoptInstalledGatewayProcess(): Promise { if (process.platform === 'win32') return null; if (process.platform === 'linux') return adoptLinuxGatewayProcess(); @@ -1238,7 +1332,6 @@ export async function adoptInstalledGatewayProcess(): Promise runtimeIsInstalled(), getStatus: async () => { if (updating) return 'starting'; + if (platform === 'linux' && (await installedGatewayOnThisComputer()) === 'legacy') { + return 'other-home'; + } const observedSupervisor = supervisor; const observedPhase = supervisor?.phase(); if (supervisor) { diff --git a/src/main/targets/types.ts b/src/main/targets/types.ts index 557d16f..bab706c 100644 --- a/src/main/targets/types.ts +++ b/src/main/targets/types.ts @@ -12,7 +12,8 @@ export type TargetStatus = | 'starting' | 'stopping' | 'error' - | 'not-installed'; + | 'not-installed' + | 'other-home'; export interface TargetPlatform { platform: 'darwin' | 'linux' | 'win32'; diff --git a/src/preload/index.ts b/src/preload/index.ts index 63510d9..76b3ca2 100644 --- a/src/preload/index.ts +++ b/src/preload/index.ts @@ -1,6 +1,6 @@ import { contextBridge, ipcRenderer } from 'electron'; -export type RuntimeStatus = 'running' | 'stopped' | 'starting' | 'stopping' | 'error' | 'not-installed'; +export type RuntimeStatus = 'running' | 'stopped' | 'starting' | 'stopping' | 'error' | 'not-installed' | 'other-home'; contextBridge.exposeInMainWorld('elastos', { platform: process.platform, diff --git a/src/renderer/app.js b/src/renderer/app.js index fd9defc..2c313c6 100644 --- a/src/renderer/app.js +++ b/src/renderer/app.js @@ -69,7 +69,8 @@ const statusLabels = { starting: 'Starting...', stopping: 'Stopping...', error: 'Needs attention', - 'not-installed': 'Not installed' + 'not-installed': 'Not installed', + 'other-home': 'another ElastOS Home is running' }; async function showError(message) { @@ -176,7 +177,8 @@ function updateStatus(status) { openBtn.dataset.action = action.id; powerBtn.className = 'power-button' + (status === 'running' ? ' running' : ''); - powerBtn.disabled = busy || status === 'starting' || status === 'stopping' || status === 'not-installed'; + powerBtn.classList.toggle('hidden', status === 'other-home'); + powerBtn.disabled = busy || status === 'starting' || status === 'stopping' || status === 'not-installed' || status === 'other-home'; const isInstalled = status !== 'not-installed'; uninstallBtn.disabled = !isInstalled || status === 'running' || busy; diff --git a/src/renderer/flow.js b/src/renderer/flow.js index 6d66de9..62cec54 100644 --- a/src/renderer/flow.js +++ b/src/renderer/flow.js @@ -28,6 +28,9 @@ function stepStates(message) { function primaryAction(state) { const status = state.status; if (state.busy) return { id: 'busy', label: 'Working…', enabled: false }; + if (status === 'other-home') { + return { id: 'busy', label: 'another ElastOS Home is running', enabled: false }; + } if (status === 'running') { return { id: 'open', diff --git a/test/installer-ux.test.js b/test/installer-ux.test.js index 694d7fb..c02fb4f 100644 --- a/test/installer-ux.test.js +++ b/test/installer-ux.test.js @@ -124,6 +124,9 @@ test('sign-in launch writes a desktop file and can remove it', () => { test('the install button is the primary action until the computer is healthy', () => { assert.equal(flow.primaryAction({ targetId: 'runtime', status: 'not-installed', busy: false }).label, 'Install'); assert.equal(flow.primaryAction({ targetId: 'runtime', status: 'running', busy: false }).label, 'Open my computer'); + const otherHome = flow.primaryAction({ targetId: 'runtime', status: 'other-home', busy: false }); + assert.equal(otherHome.enabled, false); + assert.equal(otherHome.label, 'another ElastOS Home is running'); assert.equal(flow.primaryAction({ targetId: 'runtime', status: 'error', busy: false }).id, 'retry'); assert.match(flow.firstRunCopy('runtime', 'not-installed'), /One button/); assert.equal(flow.firstRunCopy('runtime', 'running'), ''); diff --git a/test/runtime-gateway.test.js b/test/runtime-gateway.test.js index 1454768..382460a 100644 --- a/test/runtime-gateway.test.js +++ b/test/runtime-gateway.test.js @@ -1,21 +1,26 @@ const assert = require('node:assert/strict'); const test = require('node:test'); -const { spawn } = require('node:child_process'); const { HOME_URL, binaryReplacement, createGatewaySupervisor, + controllerGateway, + confirmedControllerPid, + signalRecordedController, isHealthOk, scrubRuntimeLog, launcherLogText, homeLaunchForPlatform, - signalProcessGroup, + spawnGatewayProcess, ForeignGatewayError, foreignListenerIsElastos, installedGatewayKind, FOREIGN_LISTENER_MESSAGE, LEGACY_STILL_RUNNING_MESSAGE, + HOME_UNCONFIRMED_MESSAGE, + OTHER_HOME_MESSAGE, + linuxControllerAdopt, combineHealth, listenerOwnership, localhostIsLoopback, @@ -475,7 +480,7 @@ test('an OK that the started gateway does not own never opens Home', async () => assert.equal(await ready.start(), 'started'); }); -test('upgrade: a gateway an earlier launcher started on 127.0.0.1 is stopped and started on localhost', async () => { +test('a gateway on 127.0.0.1:8090 is another Home and receives no signal', async () => { const legacyLock = JSON.stringify({ pid: 7, role: 'gateway', addr: '127.0.0.1:8090' }); const legacyFacts = { lockText: legacyLock, @@ -484,56 +489,46 @@ test('upgrade: a gateway an earlier launcher started on 127.0.0.1 is stopped and ownsSocket: (_pid, wants) => wants.length === 1 && wants[0] === '127.0.0.1', }; assert.equal(installedGatewayKind(legacyFacts), 'legacy'); - // Home never opens on the legacy gateway. assert.equal(foreignListenerIsElastos(legacyFacts), false); assert.equal(installedGatewayKind({ ...legacyFacts, lockText: JSON.stringify({ pid: 7, addr: '0.0.0.0:8090' }) }), null); assert.equal(installedGatewayKind({ ...legacyFacts, ownsSocket: () => false }), null); const spawned = []; const opened = []; - const logs = []; - let legacyRunning = true; - const legacySignals = []; - const legacy = { - pid: 7, - onOutput() {}, - onExit() {}, - hasExited: () => !legacyRunning, - signal(sig) { legacySignals.push(sig); legacyRunning = false; }, - }; - let mine = null; + const signals = []; const sup = createGatewaySupervisor({ binary: '/bin/elastos', - spawn(binary, args) { + spawn(_binary, args) { spawned.push([...args]); - const proc = fakeProcess(50 + spawned.length); - if (legacyRunning) { - queueMicrotask(() => { - proc.emit('another ElastOS host already owns this data directory\n'); - proc.exit(1); - }); - } else { - mine = proc; - } + const proc = fakeProcess(50); + queueMicrotask(() => { + proc.emit('another ElastOS host already owns this data directory\n'); + proc.exit(1); + }); return proc; }, - fetchHealth: async () => (legacyRunning || mine ? { status: 200, body: 'OK', addresses: ['127.0.0.1'] } : null), + fetchHealth: async () => ({ status: 200, body: 'OK', addresses: ['127.0.0.1'] }), sleep: async () => {}, now: () => 0, openUrl: (url) => opened.push(url), - log: (line) => logs.push(line), + log: () => {}, confirmForeign: async () => foreignListenerIsElastos(legacyFacts), - foreignIsLegacy: async () => installedGatewayKind(legacyFacts) === 'legacy', - adoptInstalled: () => legacy, - listenerOwned: (pid) => Boolean(mine && pid === mine.pid), + reportLegacyHome: async () => installedGatewayKind(legacyFacts) === 'legacy', + adoptInstalled: () => { + signals.push('adopt'); + return { + pid: 7, + onOutput() {}, + onExit() {}, + hasExited: () => false, + signal(sig) { signals.push(sig); }, + }; + }, }); - assert.equal(await sup.start(), 'started'); - assert.deepEqual(legacySignals, ['SIGTERM']); - assert.deepEqual(spawned, [['gateway', '--addr', 'localhost:8090'], ['gateway', '--addr', 'localhost:8090']]); + await assert.rejects(() => sup.start(), (err) => err.message === OTHER_HOME_MESSAGE); + assert.deepEqual(signals, []); assert.deepEqual(opened, []); - assert.ok(logs.some((line) => /older ElastOS is running on 127\.0\.0\.1:8090/.test(line))); - sup.openHome(); - assert.deepEqual(opened, ['http://localhost:8090/home/']); + assert.deepEqual(spawned, [['gateway', '--addr', 'localhost:8090']]); }); test('upgrade: a legacy gateway that cannot be adopted is not opened and says so', async () => { @@ -717,37 +712,19 @@ test('one failed health poll while the process is alive is not a stop', async () assert.deepEqual(world.signals, ['SIGTERM', 'SIGKILL']); }); -test('signalProcessGroup uses the negative pid and surfaces a failed kill', () => { - const seen = []; - signalProcessGroup(42, 'SIGTERM', (pid, signal) => { seen.push([pid, signal]); }); - assert.deepEqual(seen, [[-42, 'SIGTERM']]); - signalProcessGroup(0, 'SIGTERM', () => { throw new Error('pid 0 must not be signaled'); }); - signalProcessGroup(-5, 'SIGTERM', () => { throw new Error('a negative pid must not be signaled'); }); - signalProcessGroup(42, 'SIGTERM', () => { - const err = new Error('gone'); - err.code = 'ESRCH'; - throw err; - }); - assert.throws( - () => signalProcessGroup(42, 'SIGKILL', () => { - const err = new Error('operation not permitted'); - err.code = 'EPERM'; - throw err; - }), - /Could not signal ElastOS \(SIGKILL\): operation not permitted/, - ); -}); - -test('signalProcessGroup kills the leader and a child in that group', async () => { - const child = spawn('bash', ['-c', 'sleep 30 & echo $!; wait'], { - detached: true, - stdio: ['ignore', 'pipe', 'pipe'], - }); +test('a process this launcher spawned is signaled through its own handle', async () => { + const proc = spawnGatewayProcess(process.execPath, ['-e', ` + const { spawn } = require('child_process'); + const child = spawn(process.execPath, ['-e', 'setInterval(() => {}, 1000)'], { stdio: 'ignore' }); + process.stdout.write(String(child.pid)); + setInterval(() => {}, 1000); + `]); + let grandchild = 0; try { - const grandchild = await new Promise((resolve, reject) => { + grandchild = await new Promise((resolve, reject) => { const timer = setTimeout(() => reject(new Error('grandchild pid was not printed')), 3000); let buf = ''; - child.stdout.on('data', (chunk) => { + proc.onOutput((chunk) => { buf += chunk.toString(); const line = buf.trim(); if (/^\d+$/.test(line)) { @@ -756,33 +733,135 @@ test('signalProcessGroup kills the leader and a child in that group', async () = } }); }); - signalProcessGroup(child.pid, 'SIGTERM'); - await new Promise((resolve, reject) => { - const timer = setTimeout(() => reject(new Error('leader did not exit')), 3000); - child.once('exit', () => { + proc.signal('SIGTERM'); + const leaderGone = await new Promise((resolve) => { + const timer = setTimeout(() => resolve(false), 3000); + proc.onExit(() => { clearTimeout(timer); - resolve(); + resolve(true); }); }); - // The orphaned child is reaped by init, which can take longer than a - // fixed wait on a busy machine. Poll instead of sleeping once. - const gone = () => { - try { - process.kill(grandchild, 0); - return false; - } catch { - return true; - } - }; - for (let waited = 0; waited < 5000 && !gone(); waited += 50) { - await new Promise((resolve) => setTimeout(resolve, 50)); - } - assert.throws(() => process.kill(grandchild, 0)); + assert.equal(leaderGone, true); + process.kill(grandchild, 0); } finally { - try { process.kill(-(child.pid), 'SIGKILL'); } catch { /* already gone */ } + try { if (grandchild) process.kill(grandchild, 'SIGKILL'); } catch { /* already gone */ } + try { proc.signal('SIGKILL'); } catch { /* already gone */ } } }); +function controllerView(overrides = {}) { + return { + statusText: JSON.stringify({ + phase: 'ready', + controller_pid: 10, + controller_start: 'linux:boot-1:100', + host_pid: 20, + generation: 'abc', + }), + lockText: JSON.stringify({ + pid: 20, role: 'gateway', addr: 'localhost:8090', generation: 'abc', + }), + bootId: 'boot-1', + controllerStat: procStat(10, 1, 100), + exePath: '/home/user/.local/share/elastos/update-controller/runtime', + allowedExes: [ + '/home/user/.local/bin/elastos', + '/home/user/.local/share/elastos/update-controller/runtime', + ], + ...overrides, + }; +} + +function refusedSignal(observed) { + const kills = []; + assert.equal(confirmedControllerPid(observed), null); + assert.throws( + () => signalRecordedController('SIGTERM', () => observed, (pid, signal) => kills.push([pid, signal])), + { message: HOME_UNCONFIRMED_MESSAGE }, + ); + assert.deepEqual(kills, []); +} + +test('a controller pid reused before the first read is not signaled', () => { + refusedSignal(controllerView({ controllerStat: procStat(10, 1, 999) })); + refusedSignal(controllerView({ statusText: null })); + refusedSignal(controllerView({ statusText: 'x'.repeat((16 * 1024) + 1) })); + refusedSignal(controllerView({ + lockText: JSON.stringify({ pid: 20, role: 'gateway', addr: 'localhost:8090', generation: 'stale' }), + })); + refusedSignal(controllerView({ exePath: '/usr/bin/other' })); + refusedSignal(controllerView({ exePath: '/home/user/.local/bin/elastos (deleted)' })); + const installed = controllerView({ exePath: '/home/user/.local/bin/elastos' }); + assert.equal(confirmedControllerPid(installed), 10); +}); + +test('a controller pid reused between the check and the signal is not signaled', () => { + let observed = controllerView(); + assert.equal(confirmedControllerPid(observed), 10); + observed = controllerView({ controllerStat: procStat(10, 1, 999) }); + const kills = []; + assert.throws( + () => signalRecordedController('SIGKILL', () => observed, (pid, signal) => kills.push([pid, signal])), + { message: HOME_UNCONFIRMED_MESSAGE }, + ); + assert.deepEqual(kills, []); + const host = []; + signalRecordedController('SIGTERM', () => controllerView(), (pid, signal) => host.push([pid, signal])); + assert.deepEqual(host, [[10, 'SIGTERM']]); + assert.equal(host.some((row) => row[0] === 20 || row[0] < 0), false); +}); + +test('Quit and stop after a retained Home signals only the confirmed controller', async () => { + let observed = controllerView(); + const kills = []; + const adopted = controllerGateway(() => observed, (pid, signal) => { + kills.push([pid, signal]); + if (signal === 'SIGTERM') observed = controllerView({ controllerStat: null }); + }); + let health = { status: 200, body: 'OK' }; + let clock = 0; + const sup = createGatewaySupervisor({ + binary: '/home/tester/.local/bin/elastos', + args: ['home', '--browser'], + adoptForControls: true, + spawn() { throw new Error('a retained Home is not spawned again'); }, + fetchHealth: async () => { + if (kills.length > 0) health = null; + return health; + }, + adoptInstalled: async () => adopted, + now: () => clock, + sleep: async () => { clock += 1000; }, + openUrl() {}, + log() {}, + graceMs: 3000, + pollMs: 1000, + }); + await sup.stop(); + assert.deepEqual(kills, [[10, 'SIGTERM']]); + assert.equal(sup.phase(), 'stopped'); + sup.forceKill(); + assert.deepEqual(kills, [[10, 'SIGTERM']]); + + observed = controllerView(); + const later = []; + const again = controllerGateway(() => observed, (pid, signal) => later.push([pid, signal])); + again.signal('SIGTERM'); + observed = controllerView({ controllerStat: procStat(10, 1, 999) }); + assert.throws(() => again.signal('SIGKILL'), { message: HOME_UNCONFIRMED_MESSAGE }); + assert.deepEqual(later, [[10, 'SIGTERM']]); +}); + +test('a legacy 127.0.0.1 gateway is not a controller the launcher can signal', () => { + const legacy = JSON.stringify({ pid: 7, role: 'gateway', addr: '127.0.0.1:8090', generation: 'abc' }); + assert.equal(linuxControllerAdopt(legacy), 'other-home'); + assert.equal(linuxControllerAdopt(JSON.stringify({ + pid: 7, role: 'gateway', addr: 'localhost:8090', generation: 'abc', + })), 'controller'); + assert.equal(linuxControllerAdopt(null), 'none'); + refusedSignal(controllerView({ lockText: legacy })); +}); + test('stop does not kill a gateway this launcher did not start', async () => { const world = supervisor(); world.setHealth({ status: 200, body: 'OK' }); From 9360122ff5c606df4266a5a93c5f931bb0dfddf3 Mon Sep 17 00:00:00 2001 From: Anders Alm Date: Sun, 8 Nov 2026 00:04:28 -0500 Subject: [PATCH 12/19] Pass the Home directory into the Linux controller read. The Windows restart of a 127.0.0.1 gateway stays tested. Linux still does not signal that gateway. Co-authored-by: Cursor --- src/main/targets/runtimeGateway.ts | 20 +++++----- src/main/targets/runtimeTarget.ts | 2 +- test/runtime-gateway.test.js | 60 ++++++++++++++++++++++++++++++ 3 files changed, 71 insertions(+), 11 deletions(-) diff --git a/src/main/targets/runtimeGateway.ts b/src/main/targets/runtimeGateway.ts index cca00ce..cdc9eee 100644 --- a/src/main/targets/runtimeGateway.ts +++ b/src/main/targets/runtimeGateway.ts @@ -1183,7 +1183,7 @@ export function createDefaultGatewaySupervisor(binary: string, platform: string openUrl: openRuntimeHome, log: (line) => logSink(line), confirmForeign: confirmInstalledGateway, - reportLegacyHome: async () => (await installedGatewayOnThisComputer()) === 'legacy', + reportLegacyHome: async () => (await installedGatewayOnThisComputer(platform)) === 'legacy', listenerOwned: (pid, health) => platform === 'darwin' ? confirmInstalledGateway() : platform === 'linux' @@ -1359,9 +1359,9 @@ function controllerExeFromProc(pid: number): string | null { } /** The installed binary, and the controller copy Runtime stores under the data dir. */ -function allowedControllerExes(dataDir: string): string[] { +function allowedControllerExes(homeDir: string, dataDir: string): string[] { const files = [ - runtimeBinaryPath(os.homedir()), + runtimeBinaryPath(homeDir), `${dataDir}/update-controller/runtime`, ]; const allowed: string[] = []; @@ -1372,8 +1372,8 @@ function allowedControllerExes(dataDir: string): string[] { return allowed; } -function observeRecordedController(): ControllerObservation { - const data = runtimeDataDir('linux', os.homedir(), process.env); +function observeRecordedController(homeDir: string): ControllerObservation { + const data = runtimeDataDir('linux', homeDir, process.env); const statusText = readRegularText(`${data}/update-controller/status.json`, HOME_RECORD_MAX); const lockText = readRegularText(runtimeHostLockPath(data), HOME_RECORD_MAX); const boot = readProcOptional('/proc/sys/kernel/random/boot_id', 128); @@ -1386,7 +1386,7 @@ function observeRecordedController(): ControllerObservation { bootId: boot ?? null, controllerStat: stat ?? null, exePath: pid > 0 ? controllerExeFromProc(pid) : null, - allowedExes: allowedControllerExes(data), + allowedExes: allowedControllerExes(homeDir, data), }; } @@ -1400,18 +1400,18 @@ export function linuxControllerAdopt(lockText: string | null): 'controller' | 'o } /** Linux Home. Signal only the recorded update controller. A legacy gateway is not adopted. */ -async function adoptLinuxGatewayProcess(): Promise { - const data = runtimeDataDir('linux', os.homedir(), process.env); +async function adoptLinuxGatewayProcess(homeDir: string): Promise { + const data = runtimeDataDir('linux', homeDir, process.env); const lockText = readRegularText(runtimeHostLockPath(data), HOME_RECORD_MAX); if (linuxControllerAdopt(lockText) !== 'controller') return null; - return controllerGateway(observeRecordedController); + return controllerGateway(() => observeRecordedController(homeDir)); } export async function adoptInstalledGatewayProcess( platform: string = process.platform, homeDir: string = os.homedir(), ): Promise { if (platform === 'win32') return null; - if (platform === 'linux') return adoptLinuxGatewayProcess(); + if (platform === 'linux') return adoptLinuxGatewayProcess(homeDir); const { text, pid } = readHostLock(platform, homeDir); const hostIdentity = platform === 'darwin' ? macProcessIdentity(pid) : null; if (pid <= 0 || !(await hostLockGatewayKind(text, pid, platform, homeDir))) return null; diff --git a/src/main/targets/runtimeTarget.ts b/src/main/targets/runtimeTarget.ts index 80a5a7e..0674014 100644 --- a/src/main/targets/runtimeTarget.ts +++ b/src/main/targets/runtimeTarget.ts @@ -129,7 +129,7 @@ export function createRuntimeTarget(platform: NodeJS.Platform = process.platform isInstalled: () => runtimeIsInstalled(), getStatus: async () => { if (updating) return 'starting'; - if (platform === 'linux' && (await installedGatewayOnThisComputer()) === 'legacy') { + if (platform === 'linux' && (await installedGatewayOnThisComputer(platform)) === 'legacy') { return 'other-home'; } const observedSupervisor = supervisor; diff --git a/test/runtime-gateway.test.js b/test/runtime-gateway.test.js index 3a6a918..11865cb 100644 --- a/test/runtime-gateway.test.js +++ b/test/runtime-gateway.test.js @@ -531,6 +531,66 @@ test('a gateway on 127.0.0.1:8090 is another Home and receives no signal', async assert.deepEqual(spawned, [['gateway', '--addr', 'localhost:8090']]); }); +test('upgrade: a gateway an earlier launcher started on 127.0.0.1 is stopped and started on localhost', async () => { + const legacyLock = JSON.stringify({ pid: 7, role: 'gateway', addr: '127.0.0.1:8090' }); + const legacyFacts = { + lockText: legacyLock, + command: '/home/user/.local/bin/elastos gateway --addr 127.0.0.1:8090', + pidAlive: () => true, + ownsSocket: (_pid, wants) => wants.length === 1 && wants[0] === '127.0.0.1', + }; + assert.equal(installedGatewayKind(legacyFacts), 'legacy'); + assert.equal(foreignListenerIsElastos(legacyFacts), false); + assert.equal(installedGatewayKind({ ...legacyFacts, lockText: JSON.stringify({ pid: 7, addr: '0.0.0.0:8090' }) }), null); + assert.equal(installedGatewayKind({ ...legacyFacts, ownsSocket: () => false }), null); + + const spawned = []; + const opened = []; + const logs = []; + let legacyRunning = true; + const legacySignals = []; + const legacy = { + pid: 7, + onOutput() {}, + onExit() {}, + hasExited: () => !legacyRunning, + signal(sig) { legacySignals.push(sig); legacyRunning = false; }, + }; + let mine = null; + const sup = createGatewaySupervisor({ + binary: '/bin/elastos', + spawn(_binary, args) { + spawned.push([...args]); + const proc = fakeProcess(50 + spawned.length); + if (legacyRunning) { + queueMicrotask(() => { + proc.emit('another ElastOS host already owns this data directory\n'); + proc.exit(1); + }); + } else { + mine = proc; + } + return proc; + }, + fetchHealth: async () => (legacyRunning || mine ? { status: 200, body: 'OK', addresses: ['127.0.0.1'] } : null), + sleep: async () => {}, + now: () => 0, + openUrl: (url) => opened.push(url), + log: (line) => logs.push(line), + confirmForeign: async () => foreignListenerIsElastos(legacyFacts), + foreignIsLegacy: async () => installedGatewayKind(legacyFacts) === 'legacy', + adoptInstalled: () => legacy, + listenerOwned: (pid) => Boolean(mine && pid === mine.pid), + }); + assert.equal(await sup.start(), 'started'); + assert.deepEqual(legacySignals, ['SIGTERM']); + assert.deepEqual(spawned, [['gateway', '--addr', 'localhost:8090'], ['gateway', '--addr', 'localhost:8090']]); + assert.deepEqual(opened, []); + assert.ok(logs.some((line) => /older ElastOS is running on 127\.0\.0\.1:8090/.test(line))); + sup.openHome(); + assert.deepEqual(opened, ['http://localhost:8090/home/']); +}); + test('upgrade: a legacy gateway that cannot be adopted is not opened and says so', async () => { const opened = []; const sup = createGatewaySupervisor({ From 76d8f45d11a5eebfaebe3549ca07a1580b443574 Mon Sep 17 00:00:00 2001 From: Anders Alm Date: Sun, 8 Nov 2026 01:33:46 -0500 Subject: [PATCH 13/19] Record the darwin listener failure as a kernel-path command check. Runtime smoke run 42449751731 reports a foreign program at localhost:8090 after Home is ready. installedGatewayKind returns null when the command does not start with the proved kernel path. This test fails on that result. Co-authored-by: Cursor --- test/darwin-kernel-path.test.js | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) create mode 100644 test/darwin-kernel-path.test.js diff --git a/test/darwin-kernel-path.test.js b/test/darwin-kernel-path.test.js new file mode 100644 index 0000000..94677c0 --- /dev/null +++ b/test/darwin-kernel-path.test.js @@ -0,0 +1,22 @@ +const assert = require('node:assert/strict'); +const test = require('node:test'); + +const { installedGatewayKind } = require('../dist/main/targets/runtimeGateway'); + +test('a proved kernel path accepts a gateway whose command does not start with that path', () => { + const kernel = '/Users/example/.local/share/elastos/elastos'; + const facts = { + lockText: JSON.stringify({ pid: 10, addr: 'localhost:8090' }), + verifiedExecutable: kernel, + pidAlive: () => true, + ownsSocket: () => true, + }; + assert.equal(installedGatewayKind({ + ...facts, + command: 'elastos gateway --addr localhost:8090', + }), 'current'); + assert.equal(installedGatewayKind({ + ...facts, + command: 'elastos serve', + }), null); +}); From 8d486e87ca5979fadca0d71487d34b8356e15160 Mon Sep 17 00:00:00 2001 From: Anders Alm Date: Sun, 8 Nov 2026 02:37:09 -0500 Subject: [PATCH 14/19] Signal a Linux Home controller through a pidfd opened before the proc check. A pid reused after the start-time and exe reads received kill by pid number. The pidfd is opened first, and TERM and KILL both use that fd. If pidfd is unavailable, Stop does not signal. Co-authored-by: Cursor --- package.json | 4 +- scripts/build-linux-pidfd.js | 13 ++ src/main/targets/runtimeGateway.ts | 263 ++++++++++++++++++++++++++--- src/native/linux-pidfd.c | 125 ++++++++++++++ test/runtime-gateway.test.js | 194 ++++++++++++++++++++- 5 files changed, 570 insertions(+), 29 deletions(-) create mode 100644 scripts/build-linux-pidfd.js create mode 100644 src/native/linux-pidfd.c diff --git a/package.json b/package.json index e1e0e8d..272516f 100644 --- a/package.json +++ b/package.json @@ -10,7 +10,7 @@ "license": "AGPL-3.0", "scripts": { "dev": "electron .", - "build:ts": "node scripts/build-mac-process-info.js && tsc", + "build:ts": "node scripts/build-mac-process-info.js && node scripts/build-linux-pidfd.js && tsc", "build": "npm run build:ts && electron-builder", "build:mac": "npm run build:ts && electron-builder --mac", "build:win": "npm run build:ts && electron-builder --win", @@ -84,7 +84,7 @@ "libayatana-appindicator3-1" ] }, - "asarUnpack": ["dist/native/mac-process-info"], + "asarUnpack": ["dist/native/mac-process-info", "dist/native/linux-pidfd"], "afterAllArtifactBuild": "scripts/notarize.js", "extraResources": [ { diff --git a/scripts/build-linux-pidfd.js b/scripts/build-linux-pidfd.js new file mode 100644 index 0000000..95a0057 --- /dev/null +++ b/scripts/build-linux-pidfd.js @@ -0,0 +1,13 @@ +const { spawnSync } = require('node:child_process'); +const fs = require('node:fs'); +const path = require('node:path'); + +if (process.platform !== 'linux') process.exit(0); +const output = path.join(__dirname, '../dist/native/linux-pidfd'); +fs.mkdirSync(path.dirname(output), { recursive: true }); +const result = spawnSync('cc', [ + '-Wall', '-Wextra', '-Werror', '-O2', + path.join(__dirname, '../src/native/linux-pidfd.c'), '-o', output, +], { stdio: 'inherit', timeout: 30000 }); +if (result.error) throw result.error; +process.exit(result.status ?? 1); diff --git a/src/main/targets/runtimeGateway.ts b/src/main/targets/runtimeGateway.ts index 9c7dc5b..0d8da6e 100644 --- a/src/main/targets/runtimeGateway.ts +++ b/src/main/targets/runtimeGateway.ts @@ -1,4 +1,4 @@ -import { execFile, execFileSync, spawn } from 'child_process'; +import { ChildProcess, execFile, execFileSync, spawn, spawnSync } from 'child_process'; import * as dns from 'dns'; import * as fs from 'fs'; import * as http from 'http'; @@ -482,6 +482,16 @@ export interface ControllerObservation { allowedExes: readonly string[]; } +export type ControllerRecord = Pick; + +export type ControllerProcView = Pick; + +/** A pidfd for one process. `send` cannot target a later occupant of the same pid number. */ +export interface Pidfd { + send(signal: NodeJS.Signals): void; + close(): void; +} + /** * The update controller pid, or null. The start time, the exe, and the host * lock generation must all match this read. A host pid is not a target. @@ -501,16 +511,52 @@ export function confirmedControllerPid(observed: ControllerObservation): number return status.controllerPid; } -/** Read the controller, then signal that pid. A mismatch signals nothing. */ export function signalRecordedController( signal: NodeJS.Signals, - read: () => ControllerObservation, - kill: (pid: number, signal: NodeJS.Signals) => void = process.kill, + io: { + readRecord: () => ControllerRecord; + readProc: (pid: number) => ControllerProcView; + openPidfd: (pid: number) => Pidfd; + }, + held: { pidfd: Pidfd | null }, ): void { - const target = confirmedControllerPid(read()); - if (!target) throw new Error(HOME_UNCONFIRMED_MESSAGE); + if (!held.pidfd) { + const record = io.readRecord(); + const status = parseLinuxHomeStatus(record.statusText); + const lock = parseHostLockRecord(record.lockText); + if (!status || !lock || lock.role !== 'gateway' || lock.addr !== GATEWAY_ADDR + || !status.generation || lock.generation !== status.generation) { + throw new Error(HOME_UNCONFIRMED_MESSAGE); + } + let pidfd: Pidfd; + try { + pidfd = io.openPidfd(status.controllerPid); + } catch { + throw new Error(HOME_UNCONFIRMED_MESSAGE); + } + let proc: ControllerProcView; + try { + proc = io.readProc(status.controllerPid); + } catch { + pidfd.close(); + throw new Error(HOME_UNCONFIRMED_MESSAGE); + } + const confirmed = confirmedControllerPid({ + statusText: record.statusText, + lockText: record.lockText, + bootId: record.bootId, + allowedExes: record.allowedExes, + controllerStat: proc.controllerStat, + exePath: proc.exePath, + }); + if (confirmed !== status.controllerPid) { + pidfd.close(); + throw new Error(HOME_UNCONFIRMED_MESSAGE); + } + held.pidfd = pidfd; + } try { - kill(target, signal); + held.pidfd.send(signal); } catch (err) { if (signalErrorCode(err) === 'ESRCH') return; const message = err instanceof Error ? err.message : String(err); @@ -518,24 +564,195 @@ export function signalRecordedController( } } -/** Every signal re-reads the controller. The pid field is not a signal target. */ export function controllerGateway( - read: () => ControllerObservation, - kill?: (pid: number, signal: NodeJS.Signals) => void, + readRecord: () => ControllerRecord, + readProc: (pid: number) => ControllerProcView, + openPidfd: (pid: number) => Pidfd, ): GatewayProcess { + const held: { pidfd: Pidfd | null } = { pidfd: null }; + function observation(): ControllerObservation | null { + const record = readRecord(); + const status = parseLinuxHomeStatus(record.statusText); + if (!status) return null; + const proc = readProc(status.controllerPid); + return { + statusText: record.statusText, + lockText: record.lockText, + bootId: record.bootId, + allowedExes: record.allowedExes, + controllerStat: proc.controllerStat, + exePath: proc.exePath, + }; + } return { pid: -1, onOutput() {}, onExit() {}, hasExited() { - return confirmedControllerPid(read()) === null; + let gone = false; + try { + const observed = observation(); + gone = observed === null || confirmedControllerPid(observed) === null; + } catch { + return false; + } + if (gone && held.pidfd) { + held.pidfd.close(); + held.pidfd = null; + } + return gone; }, signal(signal) { - signalRecordedController(signal, read, kill); + signalRecordedController(signal, { readRecord, readProc, openPidfd }, held); }, }; } +function throwSignalCode(code: string, message: string): never { + throw Object.assign(new Error(message), { code }); +} + +function linuxPidfdHelperPath(): string { + return path.join(__dirname, '../../native/linux-pidfd') + .replace(`${path.sep}app.asar${path.sep}`, `${path.sep}app.asar.unpacked${path.sep}`); +} + +function makeFifo(file: string): void { + const result = spawnSync('mkfifo', ['-m', '600', file], { timeout: 1000 }); + if (result.error || result.status !== 0) throwSignalCode('ENOSYS', 'pidfd is unavailable'); +} + +function waitBriefly(): void { + Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 20); +} + +function readPidfdLine(fd: number, deadline: number): string { + const buf = Buffer.alloc(64); + let text = ''; + while (!text.includes('\n')) { + if (text.length > 64) throwSignalCode('EIO', 'pidfd reply is too long'); + if (Date.now() >= deadline) throwSignalCode('ETIMEDOUT', 'pidfd helper timed out'); + try { + const n = fs.readSync(fd, buf, 0, buf.length, null); + if (n === 0) { + waitBriefly(); + continue; + } + text += buf.toString('utf8', 0, n); + } catch (err) { + const code = signalErrorCode(err); + if (code === 'EAGAIN' || code === 'EWOULDBLOCK') { + waitBriefly(); + continue; + } + throw err; + } + } + return text.slice(0, text.indexOf('\n')); +} + +function openFifoWrite(file: string, deadline: number): number { + const flags = fs.constants.O_WRONLY | fs.constants.O_NONBLOCK | fs.constants.O_NOFOLLOW; + for (;;) { + if (Date.now() >= deadline) throwSignalCode('ETIMEDOUT', 'pidfd helper timed out'); + try { + return fs.openSync(file, flags); + } catch (err) { + if (signalErrorCode(err) === 'ENXIO') { + waitBriefly(); + continue; + } + throw err; + } + } +} + +export function openLinuxPidfd(pid: number, options?: { helper?: string }): Pidfd { + if (!Number.isInteger(pid) || pid <= 0) throwSignalCode('EINVAL', 'bad pid'); + const helper = options?.helper ?? linuxPidfdHelperPath(); + if (!options?.helper && process.platform !== 'linux') throwSignalCode('ENOSYS', 'pidfd is unavailable'); + if (!fs.existsSync(helper)) throwSignalCode('ENOENT', 'pidfd helper is missing'); + const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'elastos-pidfd-')); + fs.chmodSync(dir, 0o700); + const replyPath = path.join(dir, 'reply'); + const cmdPath = path.join(dir, 'cmd'); + let child: ChildProcess | null = null; + let replyFd: number | null = null; + let cmdFd: number | null = null; + let settled = false; + const cleanup = (): void => { + if (settled) return; + settled = true; + if (cmdFd === null) { + try { + cmdFd = fs.openSync(cmdPath, fs.constants.O_WRONLY | fs.constants.O_NONBLOCK | fs.constants.O_NOFOLLOW); + } catch (err) { + const code = signalErrorCode(err); + if (code !== 'ENXIO' && code !== 'ENOENT') throw err; + } + } + const command = cmdFd; + const reply = replyFd; + cmdFd = null; + replyFd = null; + let closeError: unknown = null; + if (command !== null) { + try { fs.closeSync(command); } catch (err) { closeError = err; } + } + if (reply !== null) { + try { fs.closeSync(reply); } catch (err) { if (!closeError) closeError = err; } + } + child?.unref(); + fs.rmSync(dir, { recursive: true, force: true }); + if (closeError) throw closeError; + }; + try { + makeFifo(replyPath); + makeFifo(cmdPath); + child = spawn(helper, [String(pid), replyPath, cmdPath], { stdio: 'ignore' }); + // Node crashes when the spawn error event has no listener. + child.on('error', () => {}); + if (!child.pid) throwSignalCode('ENOENT', 'pidfd helper is missing'); + const replyFlags = fs.constants.O_RDONLY | fs.constants.O_NONBLOCK | fs.constants.O_NOFOLLOW; + replyFd = fs.openSync(replyPath, replyFlags); + const ready = readPidfdLine(replyFd, Date.now() + 2000); + if (ready.startsWith('errno ')) throwSignalCode(ready.slice('errno '.length), ready); + if (ready !== 'ready') throwSignalCode('EIO', 'pidfd helper did not become ready'); + cmdFd = openFifoWrite(cmdPath, Date.now() + 2000); + const reply = replyFd; + const cmd = cmdFd; + let closed = false; + return { + send(signal: NodeJS.Signals): void { + if (closed) throwSignalCode('EBADF', 'pidfd is closed'); + if (signal !== 'SIGTERM' && signal !== 'SIGKILL') throwSignalCode('EINVAL', 'unsupported signal'); + fs.writeSync(cmd, `${signal}\n`); + const line = readPidfdLine(reply, Date.now() + 2000); + if (line === 'sent') return; + if (line.startsWith('errno ')) throwSignalCode(line.slice('errno '.length), line); + throwSignalCode('EIO', 'pidfd helper reply was not a signal result'); + }, + close(): void { + if (closed) return; + closed = true; + try { + fs.writeSync(cmd, 'close\n'); + } catch (err) { + const code = signalErrorCode(err); + if (code !== 'EPIPE' && code !== 'EBADF') { + cleanup(); + throw err; + } + } + cleanup(); + }, + }; + } catch (err) { + cleanup(); + throw err; + } +} + /** * `lsof -nP -iTCP: -sTCP:LISTEN -Fpn` output. `n` names look like * `127.0.0.1:8090`, `[::1]:8090`, or `*:8090`. A socket of another account is @@ -1426,24 +1643,28 @@ function allowedControllerExes(homeDir: string, dataDir: string): string[] { return allowed; } -function observeRecordedController(homeDir: string): ControllerObservation { +function observeControllerRecord(homeDir: string): ControllerRecord { const data = runtimeDataDir('linux', homeDir, process.env); const statusText = readRegularText(`${data}/update-controller/status.json`, HOME_RECORD_MAX); const lockText = readRegularText(runtimeHostLockPath(data), HOME_RECORD_MAX); const boot = readProcOptional('/proc/sys/kernel/random/boot_id', 128); - const status = parseLinuxHomeStatus(statusText); - const pid = status ? status.controllerPid : 0; - const stat = pid > 0 ? readProcOptional(`/proc/${pid}/stat`, PROC_STAT_MAX) : null; return { statusText, lockText, bootId: boot ?? null, - controllerStat: stat ?? null, - exePath: pid > 0 ? controllerExeFromProc(pid) : null, allowedExes: allowedControllerExes(homeDir, data), }; } +function observeControllerProc(pid: number): ControllerProcView { + if (!Number.isInteger(pid) || pid <= 0) return { controllerStat: null, exePath: null }; + const stat = readProcOptional(`/proc/${pid}/stat`, PROC_STAT_MAX); + return { + controllerStat: stat ?? null, + exePath: controllerExeFromProc(pid), + }; +} + /** `controller` may be signaled. `other-home` is a legacy gateway and is never signaled. */ export function linuxControllerAdopt(lockText: string | null): 'controller' | 'other-home' | 'none' { const lock = parseHostLockRecord(lockText); @@ -1458,7 +1679,11 @@ async function adoptLinuxGatewayProcess(homeDir: string): Promise observeRecordedController(homeDir)); + return controllerGateway( + () => observeControllerRecord(homeDir), + (pid) => observeControllerProc(pid), + openLinuxPidfd, + ); } export async function adoptInstalledGatewayProcess( diff --git a/src/native/linux-pidfd.c b/src/native/linux-pidfd.c new file mode 100644 index 0000000..f77180e --- /dev/null +++ b/src/native/linux-pidfd.c @@ -0,0 +1,125 @@ +#define _GNU_SOURCE +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#ifndef __NR_pidfd_open +#define __NR_pidfd_open 434 +#endif +#ifndef __NR_pidfd_send_signal +#define __NR_pidfd_send_signal 424 +#endif + +static int write_text(int fd, const char *text) { + size_t len = strlen(text); + size_t off = 0; + while (off < len) { + ssize_t n = write(fd, text + off, len - off); + if (n < 0) { + if (errno == EINTR) continue; + return -1; + } + off += (size_t)n; + } + return 0; +} + +static const char *errno_name(int err) { + switch (err) { + case ESRCH: return "ESRCH"; + case ENOSYS: return "ENOSYS"; + case EPERM: return "EPERM"; + case EINVAL: return "EINVAL"; + case EBADF: return "EBADF"; + default: return "EIO"; + } +} + +static void report(int reply, int err) { + char line[32]; + int n = snprintf(line, sizeof line, "errno %s\n", errno_name(err)); + if (n > 0 && (size_t)n < sizeof line) write_text(reply, line); +} + +static int read_line(int fd, char *buf, size_t cap) { + size_t n = 0; + while (n + 1 < cap) { + char c = 0; + ssize_t r = read(fd, &c, 1); + if (r < 0) { + if (errno == EINTR) continue; + return -1; + } + if (r == 0) return -1; + buf[n++] = c; + if (c == '\n') { + buf[n] = '\0'; + return 0; + } + } + return -1; +} + +int main(int argc, char **argv) { + char *end = NULL; + long pid; + int reply; + int fd; + int cmd; + char line[32]; + if (argc != 4) return 2; + prctl(PR_SET_PDEATHSIG, SIGKILL); + if (getppid() == 1) return 2; + alarm(2); + errno = 0; + pid = strtol(argv[1], &end, 10); + if (errno || !argv[1][0] || (end && *end) || pid <= 0 || pid > 0x7fffffff) return 2; + reply = open(argv[2], O_WRONLY | O_CLOEXEC | O_NOFOLLOW); + if (reply < 0) return 2; + fd = (int)syscall(__NR_pidfd_open, (int)pid, 0); + if (fd < 0) { + report(reply, errno); + close(reply); + return 1; + } + if (write_text(reply, "ready\n") != 0) { + close(fd); + close(reply); + return 1; + } + cmd = open(argv[3], O_RDONLY | O_CLOEXEC | O_NOFOLLOW); + alarm(0); + if (cmd < 0) { + report(reply, errno); + close(fd); + close(reply); + return 1; + } + while (read_line(cmd, line, sizeof line) == 0) { + int sig = 0; + if (strcmp(line, "close\n") == 0) { + close(fd); + close(cmd); + close(reply); + return 0; + } + if (strcmp(line, "SIGTERM\n") == 0) sig = SIGTERM; + else if (strcmp(line, "SIGKILL\n") == 0) sig = SIGKILL; + else { + report(reply, EINVAL); + continue; + } + if (syscall(__NR_pidfd_send_signal, fd, sig, NULL, 0) != 0) report(reply, errno); + else write_text(reply, "sent\n"); + } + close(fd); + close(cmd); + close(reply); + return 0; +} diff --git a/test/runtime-gateway.test.js b/test/runtime-gateway.test.js index 35ea915..d5a93e0 100644 --- a/test/runtime-gateway.test.js +++ b/test/runtime-gateway.test.js @@ -9,6 +9,7 @@ const { controllerGateway, confirmedControllerPid, signalRecordedController, + openLinuxPidfd, signalProcessGroup, isHealthOk, scrubRuntimeLog, @@ -834,14 +835,88 @@ function controllerView(overrides = {}) { }; } +const RUNTIME_EXE = '/home/user/.local/share/elastos/update-controller/runtime'; + +function signalIo(observed, delivered) { + return { + readRecord: () => observed, + readProc: () => ({ controllerStat: observed.controllerStat, exePath: observed.exePath }), + openPidfd(pid) { + return { + send(signal) { delivered.push([pid, signal]); }, + close() {}, + }; + }, + }; +} + function refusedSignal(observed) { - const kills = []; + const delivered = []; assert.equal(confirmedControllerPid(observed), null); assert.throws( - () => signalRecordedController('SIGTERM', () => observed, (pid, signal) => kills.push([pid, signal])), + () => signalRecordedController('SIGTERM', signalIo(observed, delivered), { pidfd: null }), { message: HOME_UNCONFIRMED_MESSAGE }, ); - assert.deepEqual(kills, []); + assert.deepEqual(delivered, []); +} + +function errno(code) { + return Object.assign(new Error(code), { code }); +} + +function controllerKernel(replaceOn) { + let live = { birth: 100, exe: RUNTIME_EXE }; + const delivered = []; + let opens = 0; + const replace = () => { live = { birth: 999, exe: '/usr/bin/foreign' }; }; + return { + delivered, + opens: () => opens, + replace, + readRecord() { + if (replaceOn === 'after-record') replace(); + return controllerView(); + }, + readProc(pid) { + const statBirth = live.birth; + if (replaceOn === 'during-proc') replace(); + const exe = live.exe; + const snap = { controllerStat: procStat(pid, 1, statBirth), exePath: exe }; + if (replaceOn === 'after-proc') replace(); + return snap; + }, + openPidfd(pid) { + opens += 1; + const bound = { pid, birth: live.birth, exe: live.exe }; + return { + send(signal) { + if (bound.birth !== live.birth || bound.exe !== live.exe) throw errno('ESRCH'); + delivered.push({ pid: bound.pid, signal, birth: live.birth, exe: live.exe }); + }, + close() {}, + }; + }, + }; +} + +function boundController(getView, onDelivered) { + return controllerGateway( + () => getView(), + () => { + const view = getView(); + return { controllerStat: view.controllerStat, exePath: view.exePath }; + }, + (pid) => { + const bound = getView().controllerStat; + return { + send(signal) { + if (getView().controllerStat !== bound) throw errno('ESRCH'); + onDelivered(pid, signal); + }, + close() {}, + }; + }, + ); } test('a controller pid reused before the first read is not signaled', () => { @@ -863,20 +938,123 @@ test('a controller pid reused between the check and the signal is not signaled', observed = controllerView({ controllerStat: procStat(10, 1, 999) }); const kills = []; assert.throws( - () => signalRecordedController('SIGKILL', () => observed, (pid, signal) => kills.push([pid, signal])), + () => signalRecordedController('SIGKILL', signalIo(observed, kills), { pidfd: null }), { message: HOME_UNCONFIRMED_MESSAGE }, ); assert.deepEqual(kills, []); const host = []; - signalRecordedController('SIGTERM', () => controllerView(), (pid, signal) => host.push([pid, signal])); + signalRecordedController('SIGTERM', signalIo(controllerView(), host), { pidfd: null }); assert.deepEqual(host, [[10, 'SIGTERM']]); assert.equal(host.some((row) => row[0] === 20 || row[0] < 0), false); }); +test('a controller replaced during the proc read is not signaled', () => { + const kernel = controllerKernel('during-proc'); + assert.throws( + () => signalRecordedController('SIGTERM', kernel, { pidfd: null }), + { message: HOME_UNCONFIRMED_MESSAGE }, + ); + assert.deepEqual(kernel.delivered, []); +}); + +test('a controller replaced after the proc reads and before the signal is not signaled', () => { + const kernel = controllerKernel('after-proc'); + signalRecordedController('SIGTERM', kernel, { pidfd: null }); + assert.deepEqual(kernel.delivered, []); + assert.equal(kernel.opens(), 1); +}); + +test('a pid reused before pidfd_open fails the identity check', () => { + const kernel = controllerKernel('after-record'); + assert.throws( + () => signalRecordedController('SIGTERM', kernel, { pidfd: null }), + { message: HOME_UNCONFIRMED_MESSAGE }, + ); + assert.deepEqual(kernel.delivered, []); +}); + +test('escalation sends SIGKILL through the pidfd opened for SIGTERM', () => { + const kernel = controllerKernel(); + const gateway = controllerGateway(kernel.readRecord, kernel.readProc, kernel.openPidfd); + gateway.signal('SIGTERM'); + gateway.signal('SIGKILL'); + assert.equal(kernel.opens(), 1); + assert.deepEqual(kernel.delivered.map((row) => row.signal), ['SIGTERM', 'SIGKILL']); + assert.deepEqual(kernel.delivered.map((row) => row.birth), [100, 100]); + assert.deepEqual(kernel.delivered.map((row) => row.exe), [RUNTIME_EXE, RUNTIME_EXE]); +}); + +test('escalation does not signal a pid reused after SIGTERM', () => { + const kernel = controllerKernel(); + const gateway = controllerGateway(kernel.readRecord, kernel.readProc, kernel.openPidfd); + gateway.signal('SIGTERM'); + kernel.replace(); + gateway.signal('SIGKILL'); + assert.equal(kernel.opens(), 1); + assert.deepEqual(kernel.delivered, [{ pid: 10, signal: 'SIGTERM', birth: 100, exe: RUNTIME_EXE }]); +}); + +test('a missing pidfd does not signal the recorded pid', () => { + const delivered = []; + assert.throws( + () => signalRecordedController('SIGTERM', { + readRecord: () => controllerView(), + readProc: () => ({ controllerStat: procStat(10, 1, 100), exePath: RUNTIME_EXE }), + openPidfd() { throw errno('ENOSYS'); }, + }, { pidfd: null }), + { message: HOME_UNCONFIRMED_MESSAGE }, + ); + assert.deepEqual(delivered, []); + if (process.platform !== 'linux') { + assert.throws(() => openLinuxPidfd(10), (err) => err.code === 'ENOSYS'); + } +}); + +test('the linux package unpacks the pidfd helper', () => { + const pkg = require('../package.json'); + assert.equal(pkg.build.asarUnpack.includes('dist/native/linux-pidfd'), true); + assert.equal(pkg.scripts['build:ts'].includes('scripts/build-linux-pidfd.js'), true); +}); + +test('the pidfd helper command is the pid and two fifo paths', { timeout: 5000 }, () => { + const fs = require('node:fs'); + const os = require('node:os'); + const path = require('node:path'); + const dir = fs.mkdtempSync(path.join(fs.realpathSync(os.tmpdir()), 'pidfd-client-')); + const log = path.join(dir, 'log'); + const helper = path.join(dir, 'helper'); + fs.writeFileSync(helper, `#!/bin/sh +printf '%s\\n' "$#" >> '${log}' +printf '%s\\n' "$1" >> '${log}' +exec 3>"$2" +printf '%s\\n' ready >&3 +exec 4<"$3" +while IFS= read -r line <&4; do + printf '%s\\n' "$line" >> '${log}' + case $line in + SIGTERM|SIGKILL) printf '%s\\n' sent >&3 ;; + close) exit 0 ;; + *) printf '%s\\n' 'errno EINVAL' >&3 ;; + esac +done +`, { mode: 0o755 }); + const pidfd = openLinuxPidfd(10, { helper }); + try { + pidfd.send('SIGTERM'); + pidfd.send('SIGKILL'); + } finally { + pidfd.close(); + } + const lines = fs.readFileSync(log, 'utf8').split('\n').filter(Boolean); + assert.deepEqual(lines.filter((line) => line !== 'close'), ['3', '10', 'SIGTERM', 'SIGKILL']); + assert.equal(lines.every((line) => ['3', '10', 'SIGTERM', 'SIGKILL', 'close'].includes(line)), true); + fs.rmSync(dir, { recursive: true, force: true }); +}); + test('Quit and stop after a retained Home signals only the confirmed controller', async () => { let observed = controllerView(); const kills = []; - const adopted = controllerGateway(() => observed, (pid, signal) => { + const adopted = boundController(() => observed, (pid, signal) => { kills.push([pid, signal]); if (signal === 'SIGTERM') observed = controllerView({ controllerStat: null }); }); @@ -907,10 +1085,10 @@ test('Quit and stop after a retained Home signals only the confirmed controller' observed = controllerView(); const later = []; - const again = controllerGateway(() => observed, (pid, signal) => later.push([pid, signal])); + const again = boundController(() => observed, (pid, signal) => later.push([pid, signal])); again.signal('SIGTERM'); observed = controllerView({ controllerStat: procStat(10, 1, 999) }); - assert.throws(() => again.signal('SIGKILL'), { message: HOME_UNCONFIRMED_MESSAGE }); + again.signal('SIGKILL'); assert.deepEqual(later, [[10, 'SIGTERM']]); }); From b7483d11629390cf28e1b28034d022838705483b Mon Sep 17 00:00:00 2001 From: Anders Alm Date: Sun, 8 Nov 2026 03:17:54 -0500 Subject: [PATCH 15/19] Add a regression for a Stop that leaks the pidfd helper. Repeated Stop after a send error or a timeout must return the helper, the FIFO directory, and the descriptors to the counts from before the Stop. Co-authored-by: Cursor --- test/runtime-gateway.test.js | 146 +++++++++++++++++++++++++++++++++++ 1 file changed, 146 insertions(+) diff --git a/test/runtime-gateway.test.js b/test/runtime-gateway.test.js index d5a93e0..bdbecab 100644 --- a/test/runtime-gateway.test.js +++ b/test/runtime-gateway.test.js @@ -1051,6 +1051,152 @@ done fs.rmSync(dir, { recursive: true, force: true }); }); +function pidfdResources(pidFile) { + const fs = require('node:fs'); + const path = require('node:path'); + const text = fs.existsSync(pidFile) ? fs.readFileSync(pidFile, 'utf8') : ''; + const inodes = new Set(); + let helpers = 0; + let dirs = 0; + for (const line of text.split('\n')) { + const [pidText, cmd] = line.split(' '); + const pid = Number(pidText); + if (!pid || !cmd) continue; + try { + process.kill(pid, 0); + helpers += 1; + } catch { + // The helper has exited. + } + const fifoDir = path.dirname(cmd); + if (fs.existsSync(fifoDir)) dirs += 1; + for (const leaf of ['cmd', 'reply']) { + try { + const st = fs.statSync(path.join(fifoDir, leaf)); + inodes.add(`${st.dev}:${st.ino}`); + } catch { + // close() removes the FIFO directory. + } + } + } + let fds = 0; + for (const name of fs.readdirSync('/dev/fd')) { + const fd = Number(name); + if (!Number.isInteger(fd)) continue; + try { + const st = fs.fstatSync(fd); + if (inodes.has(`${st.dev}:${st.ino}`)) fds += 1; + } catch { + // The fd closed while this scan was reading /dev/fd. + } + } + return { helpers, dirs, fds }; +} + +function releasePidfdLeak(pidFile, scriptDir) { + const fs = require('node:fs'); + const path = require('node:path'); + const text = fs.existsSync(pidFile) ? fs.readFileSync(pidFile, 'utf8') : ''; + for (const line of text.split('\n')) { + const [pidText, cmd] = line.split(' '); + const pid = Number(pidText); + if (pid) { + try { process.kill(pid, 'SIGKILL'); } catch { /* already gone */ } + } + if (!cmd) continue; + fs.rmSync(path.dirname(cmd), { recursive: true, force: true }); + } + fs.rmSync(scriptDir, { recursive: true, force: true }); +} + +function writePidfdHelper(mode) { + const fs = require('node:fs'); + const os = require('node:os'); + const path = require('node:path'); + const dir = fs.mkdtempSync(path.join(fs.realpathSync(os.tmpdir()), 'pidfd-leak-')); + const helper = path.join(dir, 'helper'); + const pidFile = path.join(dir, 'pids'); + const signalArm = mode === 'timeout' + ? 'SIGTERM|SIGKILL) ;;' + : "SIGTERM|SIGKILL) printf '%s\\n' 'errno EPERM' >&3 ;;"; + fs.writeFileSync(helper, `#!/bin/sh +printf '%s %s\\n' "$$" "$3" >> '${pidFile}' +exec 3>"$2" +printf '%s\\n' ready >&3 +exec 4<"$3" +while IFS= read -r line <&4; do + case $line in + close) exit 0 ;; + ${signalArm} + *) printf '%s\\n' 'errno EINVAL' >&3 ;; + esac +done +exit 0 +`, { mode: 0o755 }); + return { helper, pidFile, dir }; +} + +async function failStopTwice(helper, pattern) { + const sup = createGatewaySupervisor({ + binary: '/home/tester/.local/bin/elastos', + args: ['home', '--browser'], + adoptForControls: true, + spawn() { throw new Error('a retained Home is not spawned'); }, + fetchHealth: async () => ({ status: 200, body: 'OK' }), + adoptInstalled: () => controllerGateway( + () => controllerView(), + () => ({ controllerStat: procStat(10, 1, 100), exePath: RUNTIME_EXE }), + (pid) => openLinuxPidfd(pid, { helper }), + ), + now: () => Date.now(), + sleep: async () => {}, + openUrl() {}, + log() {}, + graceMs: 30, + pollMs: 10, + }); + await assert.rejects(() => sup.stop(), pattern); + await assert.rejects(() => sup.stop(), pattern); + assert.equal(sup.phase(), 'error'); +} + +async function waitForPidfdBaseline(pidFile, before) { + const deadline = Date.now() + 1000; + let after = pidfdResources(pidFile); + while (Date.now() < deadline) { + if (after.helpers === before.helpers && after.dirs === before.dirs && after.fds === before.fds) { + return after; + } + await new Promise((resolve) => { setTimeout(resolve, 20); }); + after = pidfdResources(pidFile); + } + return after; +} + +test('repeated Stop after a pidfd send error returns helper resources to baseline', { timeout: 10000 }, async () => { + const { helper, pidFile, dir } = writePidfdHelper('eperm'); + const before = pidfdResources(pidFile); + try { + await failStopTwice(helper, /Could not signal ElastOS \(SIGTERM\): errno EPERM/); + const after = await waitForPidfdBaseline(pidFile, before); + assert.deepEqual(after, before); + } finally { + releasePidfdLeak(pidFile, dir); + } +}); + +test('repeated Stop after a pidfd timeout returns helper resources to baseline', { timeout: 20000 }, async () => { + const { helper, pidFile, dir } = writePidfdHelper('timeout'); + const before = pidfdResources(pidFile); + try { + await failStopTwice(helper, /Could not signal ElastOS \(SIGTERM\): pidfd helper timed out/); + const after = await waitForPidfdBaseline(pidFile, before); + assert.deepEqual(after, before); + } finally { + releasePidfdLeak(pidFile, dir); + } +}); + test('Quit and stop after a retained Home signals only the confirmed controller', async () => { let observed = controllerView(); const kills = []; From c31efcd4883be6daa71ac413eb6a4a00a607666d Mon Sep 17 00:00:00 2001 From: Anders Alm Date: Sun, 8 Nov 2026 03:17:54 -0500 Subject: [PATCH 16/19] Release the pidfd helper when Stop fails or replaces its controller. dispose closes the helper on a terminal Stop failure and before a new owner replaces it. SIGTERM and SIGKILL still share one pidfd. The helper also exits after 60 seconds without a command, which is longer than the 15 second stop grace. Co-authored-by: Cursor --- src/main/targets/runtimeGateway.ts | 54 +++++++++++++++++++++--------- src/native/linux-pidfd.c | 5 +++ 2 files changed, 44 insertions(+), 15 deletions(-) diff --git a/src/main/targets/runtimeGateway.ts b/src/main/targets/runtimeGateway.ts index 0d8da6e..6097f03 100644 --- a/src/main/targets/runtimeGateway.ts +++ b/src/main/targets/runtimeGateway.ts @@ -87,6 +87,8 @@ export interface GatewayProcess { onExit(listener: (code: number | null) => void): void; signal(signal: NodeJS.Signals): void; hasExited(): boolean | Promise; + /** Drop a pidfd helper. A spawned process and a Mac process have none. */ + dispose?(): void; } /** @@ -605,6 +607,16 @@ export function controllerGateway( signal(signal) { signalRecordedController(signal, { readRecord, readProc, openPidfd }, held); }, + dispose() { + const pidfd = held.pidfd; + held.pidfd = null; + if (!pidfd) return; + try { + pidfd.close(); + } catch { + // Stop still reports its own error. close() has already dropped the helper. + } + }, }; } @@ -858,8 +870,13 @@ export function createGatewaySupervisor(deps: GatewaySupervisorDeps): GatewaySup : `ElastOS stopped (exit ${code}). Click Start to try again.`); } - function ownAdopted(proc: GatewayProcess | null): void { + function replaceOwned(proc: GatewayProcess | null): void { + if (owned && owned !== proc) owned.dispose?.(); owned = proc; + } + + function ownAdopted(proc: GatewayProcess | null): void { + replaceOwned(proc); proc?.onExit((code) => recordExit(proc, code)); } @@ -880,7 +897,7 @@ export function createGatewaySupervisor(deps: GatewaySupervisorDeps): GatewaySup intentionalStop = false; foreign = false; const proc = deps.spawn(deps.binary, deps.args ?? GATEWAY_ARGS); - owned = proc; + replaceOwned(proc); let output = ''; let exited = false; let exitCode: number | null = null; @@ -992,20 +1009,25 @@ export function createGatewaySupervisor(deps: GatewaySupervisorDeps): GatewaySup async function stopProcess(proc: GatewayProcess): Promise { intentionalStop = true; current = 'stopping'; - proc.signal('SIGTERM'); - if (await confirmedStopped(proc, graceMs)) { - owned = null; - current = 'stopped'; - return; - } - proc.signal('SIGKILL'); - if (await confirmedStopped(proc, graceMs)) { - owned = null; - current = 'stopped'; - return; + try { + proc.signal('SIGTERM'); + if (await confirmedStopped(proc, graceMs)) { + owned = null; + current = 'stopped'; + return; + } + proc.signal('SIGKILL'); + if (await confirmedStopped(proc, graceMs)) { + owned = null; + current = 'stopped'; + return; + } + current = 'error'; + throw new Error('ElastOS is still running.'); + } catch (err) { + proc.dispose?.(); + throw err; } - current = 'error'; - throw new Error('ElastOS is still running.'); } const supervisor: GatewaySupervisor = { @@ -1100,11 +1122,13 @@ export function createGatewaySupervisor(deps: GatewaySupervisorDeps): GatewaySup }, forceKill() { if (!owned) return; + const failed = current === 'error'; try { owned.signal('SIGKILL'); } catch { // Quit still closes. The error from stop() is logged by the caller. } + if (failed) owned.dispose?.(); }, openHome() { deps.openUrl(HOME_URL); diff --git a/src/native/linux-pidfd.c b/src/native/linux-pidfd.c index f77180e..8755249 100644 --- a/src/native/linux-pidfd.c +++ b/src/native/linux-pidfd.c @@ -16,6 +16,9 @@ #define __NR_pidfd_send_signal 424 #endif +/* The launcher waits up to 15s between SIGTERM and SIGKILL. */ +#define PIDFD_IDLE_SEC 60 + static int write_text(int fd, const char *text) { size_t len = strlen(text); size_t off = 0; @@ -101,8 +104,10 @@ int main(int argc, char **argv) { close(reply); return 1; } + alarm(PIDFD_IDLE_SEC); while (read_line(cmd, line, sizeof line) == 0) { int sig = 0; + alarm(PIDFD_IDLE_SEC); if (strcmp(line, "close\n") == 0) { close(fd); close(cmd); From 9d3b0ca070186b3ec39c2f46953cee7ccbbf2962 Mon Sep 17 00:00:00 2001 From: Anders Alm Date: Sun, 8 Nov 2026 03:46:02 -0500 Subject: [PATCH 17/19] Remove test comments that only restate the helper count. Co-authored-by: Cursor --- test/runtime-gateway.test.js | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/test/runtime-gateway.test.js b/test/runtime-gateway.test.js index bdbecab..49f5b9e 100644 --- a/test/runtime-gateway.test.js +++ b/test/runtime-gateway.test.js @@ -1066,7 +1066,6 @@ function pidfdResources(pidFile) { process.kill(pid, 0); helpers += 1; } catch { - // The helper has exited. } const fifoDir = path.dirname(cmd); if (fs.existsSync(fifoDir)) dirs += 1; @@ -1075,7 +1074,6 @@ function pidfdResources(pidFile) { const st = fs.statSync(path.join(fifoDir, leaf)); inodes.add(`${st.dev}:${st.ino}`); } catch { - // close() removes the FIFO directory. } } } @@ -1101,7 +1099,7 @@ function releasePidfdLeak(pidFile, scriptDir) { const [pidText, cmd] = line.split(' '); const pid = Number(pidText); if (pid) { - try { process.kill(pid, 'SIGKILL'); } catch { /* already gone */ } + try { process.kill(pid, 'SIGKILL'); } catch {} } if (!cmd) continue; fs.rmSync(path.dirname(cmd), { recursive: true, force: true }); From 76a361b0ae8bbac54063f6b0686f53a8e9cc9020 Mon Sep 17 00:00:00 2001 From: Anders Alm Date: Sun, 8 Nov 2026 04:34:17 -0500 Subject: [PATCH 18/19] Add a regression for a Stop that outlasts the pidfd idle alarm. A health lookup that does not return must not hang the probe. After SIGTERM, SIGKILL must still go through the same pidfd, and the helper must still request SIGKILL when its parent dies. Co-authored-by: Cursor --- test/native/include/sys/prctl.h | 8 ++ test/native/pidfd_obs.c | 84 +++++++++++++++++++++ test/runtime-gateway.test.js | 130 ++++++++++++++++++++++++++++++++ 3 files changed, 222 insertions(+) create mode 100644 test/native/include/sys/prctl.h create mode 100644 test/native/pidfd_obs.c diff --git a/test/native/include/sys/prctl.h b/test/native/include/sys/prctl.h new file mode 100644 index 0000000..67612e9 --- /dev/null +++ b/test/native/include/sys/prctl.h @@ -0,0 +1,8 @@ +#ifndef PIDFD_TEST_PRCTL_H +#define PIDFD_TEST_PRCTL_H + +#define PR_SET_PDEATHSIG 1 + +int prctl(int option, unsigned long arg); + +#endif diff --git a/test/native/pidfd_obs.c b/test/native/pidfd_obs.c new file mode 100644 index 0000000..56acb4f --- /dev/null +++ b/test/native/pidfd_obs.c @@ -0,0 +1,84 @@ +#include +#include +#include +#include +#include +#include +#include + +#ifndef PIDFD_ALARM_LOG +#error PIDFD_ALARM_LOG is required +#endif +#ifndef PIDFD_SIGNAL_LOG +#error PIDFD_SIGNAL_LOG is required +#endif +#ifndef PIDFD_PRCTL_LOG +#error PIDFD_PRCTL_LOG is required +#endif +#ifndef PIDFD_PID_LOG +#error PIDFD_PID_LOG is required +#endif + +static void pidfd_record(const char *path, const char *line) { + FILE *file = fopen(path, "a"); + if (!file) return; + fputs(line, file); + fclose(file); +} + +static void pidfd_note_self(void) { + char line[32]; + int n = snprintf(line, sizeof line, "%ld\n", (long)getpid()); + if (n > 0) pidfd_record(PIDFD_PID_LOG, line); +} + +unsigned int pidfd_test_alarm(unsigned int seconds) { + char line[32]; + int n = snprintf(line, sizeof line, "%u\n", seconds); + if (n > 0) pidfd_record(PIDFD_ALARM_LOG, line); +#ifdef PIDFD_PASSTHROUGH_ALARM + return alarm(seconds); +#else + { + struct itimerval value; + if (seconds >= 60) seconds = 1; + memset(&value, 0, sizeof value); + value.it_value.tv_sec = seconds; + setitimer(ITIMER_REAL, &value, NULL); + } + return 0; +#endif +} + +int pidfd_test_prctl(int option, unsigned long arg) { + char line[64]; + int n = snprintf(line, sizeof line, "%d %lu\n", option, arg); + pidfd_note_self(); + if (n > 0) pidfd_record(PIDFD_PRCTL_LOG, line); + return 0; +} + +int pidfd_test_syscall(int number, ...) { + va_list args; + char line[32]; + int sig; + int n; + va_start(args, number); + if (number == 434) { + (void)va_arg(args, int); + (void)va_arg(args, int); + va_end(args); + return open("/dev/null", O_RDONLY | O_CLOEXEC); + } + if (number == 424) { + (void)va_arg(args, int); + sig = va_arg(args, int); + va_end(args); + n = snprintf(line, sizeof line, "%d\n", sig); + if (n > 0) pidfd_record(PIDFD_SIGNAL_LOG, line); + return 0; + } + va_end(args); + errno = ENOSYS; + return -1; +} diff --git a/test/runtime-gateway.test.js b/test/runtime-gateway.test.js index 49f5b9e..8b18a7c 100644 --- a/test/runtime-gateway.test.js +++ b/test/runtime-gateway.test.js @@ -419,6 +419,14 @@ test('pidOwnsGatewayPort refuses when the listeners cannot be read', async () => assert.equal(await pidOwnsGatewayPort(7, ['127.0.0.1', '::1'], [], async () => [{ address: '::1', owned: true }]), true); }); +test('the health probe returns when localhost lookup does not answer', { timeout: 2000 }, async () => { + const health = await probeGatewayHealth({ + timeoutMs: 200, + lookup: () => new Promise(() => {}), + }); + assert.equal(health, null); +}); + test('the health probe asks every address localhost resolves to', async () => { const asked = []; const ok = { status: 200, body: 'OK' }; @@ -1584,6 +1592,128 @@ test('signalProcessGroup uses the negative pid and surfaces a failed kill', () = ); }); +function compileObservedPidfd(dir, passthroughAlarm) { + const fs = require('node:fs'); + const path = require('node:path'); + const { spawnSync } = require('node:child_process'); + const helper = path.join(dir, 'linux-pidfd'); + const alarmLog = path.join(dir, 'alarm'); + const signalLog = path.join(dir, 'signals'); + const prctlLog = path.join(dir, 'prctl'); + const pidLog = path.join(dir, 'pid'); + const include = path.join(__dirname, 'native/include'); + const source = path.join(__dirname, '../src/native/linux-pidfd.c'); + const obs = path.join(__dirname, 'native/pidfd_obs.c'); + const quote = (file) => file.replace(/\\/g, '\\\\').replace(/"/g, '\\"'); + const compile = (args) => { + const result = spawnSync('cc', args, { encoding: 'utf8' }); + if (result.status !== 0) { + throw new Error(result.stderr || result.stdout || 'cc failed'); + } + }; + compile([ + '-Wall', '-Wextra', '-Werror', '-Wno-deprecated-declarations', '-O2', + '-I', include, + '-Dalarm=pidfd_test_alarm', + '-Dprctl=pidfd_test_prctl', + '-Dsyscall=pidfd_test_syscall', + '-c', source, '-o', path.join(dir, 'helper.o'), + ]); + compile([ + '-Wall', '-Wextra', '-Werror', '-O2', + ...(passthroughAlarm ? ['-DPIDFD_PASSTHROUGH_ALARM'] : []), + `-DPIDFD_ALARM_LOG="${quote(alarmLog)}"`, + `-DPIDFD_SIGNAL_LOG="${quote(signalLog)}"`, + `-DPIDFD_PRCTL_LOG="${quote(prctlLog)}"`, + `-DPIDFD_PID_LOG="${quote(pidLog)}"`, + '-c', obs, '-o', path.join(dir, 'obs.o'), + ]); + compile([path.join(dir, 'helper.o'), path.join(dir, 'obs.o'), '-o', helper]); + return { helper, alarmLog, signalLog, prctlLog, pidLog }; +} + +function releaseObservedPidfd(dir, pidLog) { + const fs = require('node:fs'); + const text = pidLog && fs.existsSync(pidLog) ? fs.readFileSync(pidLog, 'utf8') : ''; + for (const line of text.split('\n')) { + const pid = Number(line); + if (pid) { + try { process.kill(pid, 'SIGKILL'); } catch {} + } + } + fs.rmSync(dir, { recursive: true, force: true }); +} + +test('Stop still sends SIGKILL on the same pidfd when health outlasts the idle alarm', { timeout: 10000 }, async () => { + const fs = require('node:fs'); + const os = require('node:os'); + const path = require('node:path'); + const dir = fs.mkdtempSync(path.join(fs.realpathSync(os.tmpdir()), 'pidfd-idle-')); + let built = null; + let phase = 'adopt'; + let waited = false; + let err = null; + try { + built = compileObservedPidfd(dir, false); + const sup = createGatewaySupervisor({ + binary: '/home/tester/.local/bin/elastos', + args: ['home', '--browser'], + adoptForControls: true, + spawn() { throw new Error('a retained Home is not spawned'); }, + fetchHealth: async () => { + if (phase === 'wait' && !waited) { + waited = true; + await new Promise((resolve) => setTimeout(resolve, 2000)); + } + return { status: 200, body: 'OK' }; + }, + adoptInstalled: () => controllerGateway( + () => controllerView(), + () => ({ controllerStat: procStat(10, 1, 100), exePath: RUNTIME_EXE }), + (pid) => { + const pidfd = openLinuxPidfd(pid, { helper: built.helper }); + return { + send(signal) { + pidfd.send(signal); + if (signal === 'SIGTERM') phase = 'wait'; + }, + close() { pidfd.close(); }, + }; + }, + ), + now: () => Date.now(), + sleep: async () => {}, + openUrl() {}, + log() {}, + graceMs: 30, + pollMs: 1, + }); + try { + await sup.stop(); + } catch (caught) { + err = caught; + } + assert.equal(fs.readFileSync(built.signalLog, 'utf8'), '15\n9\n'); + assert.equal(fs.readFileSync(built.alarmLog, 'utf8'), '2\n0\n'); + assert.equal(fs.readFileSync(built.prctlLog, 'utf8'), '1 9\n'); + assert.match(String(err && err.message), /still running/); + const helperPid = Number(fs.readFileSync(built.pidLog, 'utf8')); + let helperGone = false; + for (let i = 0; i < 50; i += 1) { + try { + process.kill(helperPid, 0); + } catch { + helperGone = true; + break; + } + await new Promise((resolve) => setTimeout(resolve, 20)); + } + assert.equal(helperGone, true); + } finally { + releaseObservedPidfd(dir, built && built.pidLog); + } +}); + test('signalProcessGroup kills the leader and a child in that group', async () => { const child = spawn('bash', ['-c', 'sleep 30 & echo $!; wait'], { detached: true, From 43e5cbe5785bfc2ced17158c6c630180d7f85447 Mon Sep 17 00:00:00 2001 From: Anders Alm Date: Sun, 8 Nov 2026 04:34:17 -0500 Subject: [PATCH 19/19] Stop the pidfd helper from dying while Stop waits on health. The 60 second alarm started again after SIGTERM, so a slow lookup killed the helper and the later SIGKILL failed. The helper now stays up until close, FIFO end, or parent death. The localhost lookup uses the probe deadline. Co-authored-by: Cursor --- src/main/targets/runtimeGateway.ts | 23 ++++++++++++++++++++--- src/native/linux-pidfd.c | 5 ----- 2 files changed, 20 insertions(+), 8 deletions(-) diff --git a/src/main/targets/runtimeGateway.ts b/src/main/targets/runtimeGateway.ts index 6097f03..fef8fd8 100644 --- a/src/main/targets/runtimeGateway.ts +++ b/src/main/targets/runtimeGateway.ts @@ -1206,9 +1206,24 @@ export function emitRuntimeLog(line: string): void { logSink(line); } +function withDeadline(work: Promise, timeoutMs: number): Promise { + let timer: ReturnType | undefined; + const timeout = new Promise((_resolve, reject) => { + timer = setTimeout(() => { + reject(Object.assign(new Error('localhost lookup timed out'), { code: 'ETIMEDOUT' })); + }, timeoutMs); + }); + return Promise.race([work, timeout]).finally(() => { + if (timer !== undefined) clearTimeout(timer); + }); +} + /** The addresses `localhost` resolves to on this computer, in resolver order. */ -export async function resolveLocalhost(): Promise { - const found = await dns.promises.lookup(GATEWAY_HOST, { all: true, verbatim: true }); +export async function resolveLocalhost(timeoutMs = 2000): Promise { + const found = await withDeadline( + dns.promises.lookup(GATEWAY_HOST, { all: true, verbatim: true }), + timeoutMs, + ); return [...new Set(found.map((entry) => entry.address))]; } @@ -1285,7 +1300,9 @@ export async function probeGatewayHealth(options: { const timeoutMs = options.timeoutMs ?? 2000; let addresses: string[]; try { - addresses = await (options.lookup ?? resolveLocalhost)(); + addresses = options.lookup + ? await withDeadline(options.lookup(), timeoutMs) + : await resolveLocalhost(timeoutMs); } catch { return null; } diff --git a/src/native/linux-pidfd.c b/src/native/linux-pidfd.c index 8755249..f77180e 100644 --- a/src/native/linux-pidfd.c +++ b/src/native/linux-pidfd.c @@ -16,9 +16,6 @@ #define __NR_pidfd_send_signal 424 #endif -/* The launcher waits up to 15s between SIGTERM and SIGKILL. */ -#define PIDFD_IDLE_SEC 60 - static int write_text(int fd, const char *text) { size_t len = strlen(text); size_t off = 0; @@ -104,10 +101,8 @@ int main(int argc, char **argv) { close(reply); return 1; } - alarm(PIDFD_IDLE_SEC); while (read_line(cmd, line, sizeof line) == 0) { int sig = 0; - alarm(PIDFD_IDLE_SEC); if (strcmp(line, "close\n") == 0) { close(fd); close(cmd);