Turn any website into a lightweight desktop app with one command, on macOS, Windows and Linux.
Rust chatgptclaudeclidesktopdesktop-appelectron-alternativegeminilinuxmacosnativefierno-electronrusttauriweb-to-desktopwebsite-to-appwebviewwindowsyoutube
fix: make local-input staging safe to fail and restore dist after runs
Tw931b97a50fe1b5
diff --git a/bin/cli.ts b/bin/cli.tsindex a6d57072..408671b6 100644--- a/bin/cli.ts+++ b/bin/cli.ts@@ -6,6 +6,7 @@ import BuilderProvider from './builders/BuilderProvider';import handleInputOptions from './options/index';import { getCliProgram } from './helpers/cli-program';import { loadConfigFile } from './helpers/config-file';+import { restoreLocalTree } from './helpers/merge';import { isPakeError, PakeError } from './utils/error';import { validateUrlInput } from './utils/validate';import {@@ -87,6 +88,10 @@ program.action(async (urlArg: string, options: PakeCliOptions) => {let url = urlArg;try {+ // Heal a dist_bak stranded by an earlier crashed local-input run before+ // building, or this build would embed that run's staged files.+ restoreLocalTree();+if (!jsonMode) {await checkUpdateTips();}@@ -158,7 +163,7 @@ program.action(async (urlArg: string, options: PakeCliOptions) => {// program.help() and --help/--version throw under exitOverride with// exitCode 0; a clean commander exit is not a failure.if (isCommanderExit(error) && error.exitCode === 0) {- process.exit(0);+ return;}const classified = classifyError(error, phase);@@ -187,7 +192,14 @@ program.action(async (urlArg: string, options: PakeCliOptions) => {console.error(chalk.red(`✕ Unexpected error: ${String(error)}`));}- process.exit(ERROR_EXIT_CODES[classified.code]);+ // exitCode + natural exit instead of process.exit: lets the finally+ // restore run and guarantees the JSON result is flushed on piped stdout.+ process.exitCode = ERROR_EXIT_CODES[classified.code];+ } finally {+ // A local-input run replaces the package's own dist/ during staging; put+ // it back so the CLI stays intact and later builds cannot embed this+ // user's files.+ restoreLocalTree();}});@@ -195,7 +207,7 @@ program.parseAsync().catch((error: unknown) => {if (isCommanderExit(error)) {// --help / --version and friends exit clean; commander already printed.if (error.exitCode === 0) {- process.exit(0);+ return;}// Parse errors (unknown option, invalid argument, missing value) are// invalid input. Commander already printed the message to stderr; in@@ -215,12 +227,13 @@ program.parseAsync().catch((error: unknown) => {},});}- process.exit(ERROR_EXIT_CODES.INVALID_INPUT);+ process.exitCode = ERROR_EXIT_CODES.INVALID_INPUT;+ return;}if (error instanceof Error) {console.error(chalk.red(`✕ ${error.message}`));} else {console.error(chalk.red(`✕ Unexpected error: ${String(error)}`));}- process.exit(1);+ process.exitCode = 1;});diff --git a/bin/helpers/merge.ts b/bin/helpers/merge.tsindex 7d3ac9b8..e8f5cfb9 100644--- a/bin/helpers/merge.ts+++ b/bin/helpers/merge.ts@@ -116,19 +116,74 @@ async function stageLocalTree(sourceDir: string): Promise<void> {const distDir = path.join(npmDirectory, 'dist');const distBakDir = path.join(npmDirectory, 'dist_bak');- if (await fsExtra.pathExists(distBakDir)) {- fsExtra.removeSync(distDir);- } else {- fsExtra.moveSync(distDir, distBakDir);+ // Resolve symlinked input up front: staging must produce a real copy, or+ // the cli.js copy-back below would write through the link into the user's+ // own directory.+ const resolvedSource = await fsExtra.realpath(sourceDir);+ const resolvedPackage = await fsExtra+ .realpath(npmDirectory)+ .catch(() => path.resolve(npmDirectory));+ const packageDist = path.join(resolvedPackage, 'dist');+ if (+ resolvedSource === resolvedPackage ||+ resolvedPackage.startsWith(resolvedSource + path.sep) ||+ resolvedSource === packageDist ||+ resolvedSource.startsWith(packageDist + path.sep)+ ) {+ throw new PakeError(+ `Local input "${sourceDir}" contains the Pake CLI installation itself.`,+ {+ code: 'INVALID_INPUT',+ hint: 'Point Pake at your built output directory, not at a directory containing pake-cli.',+ },+ );}- fsExtra.copySync(sourceDir, distDir, { overwrite: true });- const filesToCopyBack = ['cli.js'];- await Promise.all(- filesToCopyBack.map((file) =>- fsExtra.copy(path.join(distBakDir, file), path.join(distDir, file)),- ),- );+ try {+ if (await fsExtra.pathExists(distBakDir)) {+ fsExtra.removeSync(distDir);+ } else {+ fsExtra.moveSync(distDir, distBakDir);+ }+ fsExtra.copySync(resolvedSource, distDir, {+ overwrite: true,+ dereference: true,+ });++ const filesToCopyBack = ['cli.js'];+ await Promise.all(+ filesToCopyBack.map((file) =>+ fsExtra.copy(path.join(distBakDir, file), path.join(distDir, file)),+ ),+ );+ } catch (error) {+ // Never leave the package without its own dist/: cli.js lives there and+ // every later `pake` invocation would fail until a manual reinstall.+ restoreLocalTree();+ throw error;+ }+}++// Put the package's original dist/ back once a local-input run is over (or+// failed). Tauri bakes `frontendDist: ../dist` into every binary, so a stale+// staged tree would leak this user's files into the next app built from the+// same install. Safe to call on any run: a present dist_bak always holds the+// original package dist, including one stranded by an older crashed run.+export function restoreLocalTree(): void {+ const distDir = path.join(npmDirectory, 'dist');+ const distBakDir = path.join(npmDirectory, 'dist_bak');+ if (!fsExtra.pathExistsSync(distBakDir)) {+ return;+ }+ try {+ fsExtra.removeSync(distDir);+ fsExtra.moveSync(distBakDir, distDir);+ } catch (error) {+ const detail = error instanceof Error ? error.message : String(error);+ logger.warn(+ `Failed to restore the CLI's original dist/ from dist_bak: ${detail}`,+ );+ }}// Exported for unit tests (web fallback and directory entry guard).diff --git a/tests/unit/local-staging.test.ts b/tests/unit/local-staging.test.tsnew file mode 100644index 00000000..4da2de95--- /dev/null+++ b/tests/unit/local-staging.test.ts@@ -0,0 +1,168 @@+import path from 'path';+import os from 'os';+import fs from 'fs';+import fsExtra from 'fs-extra';+import { describe, it, expect, beforeEach, afterAll, vi } from 'vitest';++// stageLocalTree mutates the package's own dist/, so these tests point+// npmDirectory at a throwaway fake package instead of the repo.+const baseDir = path.join(os.tmpdir(), `pake-staging-${process.pid}`);+const fakePkg = path.join(baseDir, 'pkg');++vi.mock('@/utils/dir', async () => {+ const { default: nodePath } = await import('path');+ const { default: nodeOs } = await import('os');+ const base = nodePath.join(nodeOs.tmpdir(), `pake-staging-${process.pid}`);+ return {+ npmDirectory: nodePath.join(base, 'pkg'),+ tauriConfigDirectory: nodePath.join(base, 'pkg', 'src-tauri', '.pake'),+ };+});++import { handleLocalFile, restoreLocalTree } from '@/helpers/merge';+import { PakeTauriConfig } from '@/types';++function makeTauriConf(): PakeTauriConfig {+ return {+ pake: {+ windows: [{ url: '', url_type: 'web' } as never],+ user_agent: { macos: '', linux: '', windows: '' },+ system_tray: { macos: false, linux: false, windows: false },+ system_tray_path: '',+ proxy_url: '',+ multi_instance: false,+ multi_window: false,+ },+ bundle: {},+ app: {},+ };+}++async function makeUserDir(name: string): Promise<string> {+ const dir = path.join(baseDir, name);+ await fsExtra.ensureDir(dir);+ await fsExtra.writeFile(path.join(dir, 'index.html'), '<html></html>');+ await fsExtra.writeFile(path.join(dir, 'asset.txt'), 'asset');+ return dir;+}++describe('stageLocalTree via handleLocalFile', () => {+ beforeEach(async () => {+ await fsExtra.remove(baseDir);+ await fsExtra.ensureDir(path.join(fakePkg, 'dist'));+ await fsExtra.writeFile(path.join(fakePkg, 'dist', 'cli.js'), 'cli');+ await fsExtra.writeFile(path.join(fakePkg, 'dist', 'dev.js'), 'dev');+ });++ afterAll(async () => {+ await fsExtra.remove(baseDir);+ });++ it('stages a directory into dist and keeps cli.js, backing up the original', async () => {+ const userDir = await makeUserDir('site');+ const conf = makeTauriConf();+ await handleLocalFile(userDir, false, conf);++ const dist = path.join(fakePkg, 'dist');+ expect(await fsExtra.pathExists(path.join(dist, 'index.html'))).toBe(true);+ expect(await fsExtra.pathExists(path.join(dist, 'asset.txt'))).toBe(true);+ expect(await fsExtra.readFile(path.join(dist, 'cli.js'), 'utf8')).toBe(+ 'cli',+ );+ // Original package dist preserved in dist_bak.+ const bak = path.join(fakePkg, 'dist_bak');+ expect(await fsExtra.readFile(path.join(bak, 'dev.js'), 'utf8')).toBe(+ 'dev',+ );+ expect(conf.pake.windows[0].url).toBe('index.html');+ expect(conf.pake.windows[0].url_type).toBe('local');+ });++ it('restoreLocalTree puts the original dist back and removes dist_bak', async () => {+ const userDir = await makeUserDir('site');+ await handleLocalFile(userDir, false, makeTauriConf());++ restoreLocalTree();++ const dist = path.join(fakePkg, 'dist');+ expect(await fsExtra.readFile(path.join(dist, 'dev.js'), 'utf8')).toBe(+ 'dev',+ );+ expect(await fsExtra.pathExists(path.join(dist, 'index.html'))).toBe(false);+ expect(await fsExtra.pathExists(path.join(fakePkg, 'dist_bak'))).toBe(+ false,+ );+ });++ it('restores the original dist when staging fails midway', async () => {+ const userDir = await makeUserDir('broken');+ // Dangling symlink: copySync with dereference follows it and throws.+ fs.symlinkSync(+ path.join(userDir, 'missing-target'),+ path.join(userDir, 'dangling'),+ );++ await expect(+ handleLocalFile(userDir, false, makeTauriConf()),+ ).rejects.toBeTruthy();++ // The failed staging must leave the package usable: original dist back,+ // no dist_bak left behind.+ const dist = path.join(fakePkg, 'dist');+ expect(await fsExtra.readFile(path.join(dist, 'cli.js'), 'utf8')).toBe(+ 'cli',+ );+ expect(await fsExtra.readFile(path.join(dist, 'dev.js'), 'utf8')).toBe(+ 'dev',+ );+ expect(await fsExtra.pathExists(path.join(dist, 'index.html'))).toBe(false);+ expect(await fsExtra.pathExists(path.join(fakePkg, 'dist_bak'))).toBe(+ false,+ );+ });++ it('copies through a symlinked input without writing into the real source', async () => {+ const realDir = await makeUserDir('real-site');+ const linkPath = path.join(baseDir, 'link-to-site');+ fs.symlinkSync(realDir, linkPath);++ await handleLocalFile(linkPath, false, makeTauriConf());++ const dist = path.join(fakePkg, 'dist');+ expect(fs.lstatSync(dist).isSymbolicLink()).toBe(false);+ expect(await fsExtra.pathExists(path.join(dist, 'index.html'))).toBe(true);+ // cli.js copy-back must land in the staged copy, never in the user's dir.+ expect(await fsExtra.pathExists(path.join(realDir, 'cli.js'))).toBe(false);+ });++ it('rejects an input directory that contains the CLI package itself', async () => {+ await fsExtra.writeFile(path.join(baseDir, 'index.html'), '<html></html>');++ await expect(+ handleLocalFile(baseDir, false, makeTauriConf()),+ ).rejects.toMatchObject({ code: 'INVALID_INPUT' });++ // Guard fires before any move: dist untouched, no dist_bak.+ expect(await fsExtra.pathExists(path.join(fakePkg, 'dist', 'cli.js'))).toBe(+ true,+ );+ expect(await fsExtra.pathExists(path.join(fakePkg, 'dist_bak'))).toBe(+ false,+ );+ });++ it("rejects the package's own dist as input", async () => {+ await fsExtra.writeFile(+ path.join(fakePkg, 'dist', 'index.html'),+ '<html></html>',+ );++ await expect(+ handleLocalFile(path.join(fakePkg, 'dist'), false, makeTauriConf()),+ ).rejects.toMatchObject({ code: 'INVALID_INPUT' });++ expect(await fsExtra.pathExists(path.join(fakePkg, 'dist', 'cli.js'))).toBe(+ true,+ );+ });+});