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: reject a bad --inject file before the build instead of dropping settings (#1439)
visveshkhannae4e663bbad18
diff --git a/bin/cli.ts b/bin/cli.tsindex 8a92d0dd..09687d31 100644--- a/bin/cli.ts+++ b/bin/cli.ts@@ -13,7 +13,11 @@ import {throwIfBuildCancelled,} from './utils/build-workspace';import { isPakeError, PakeError } from './utils/error';-import { validateUrlInput, validateDownloadDirInput } from './utils/validate';+import {+ validateUrlInput,+ validateDownloadDirInput,+ validateInjectInput,+} from './utils/validate';import {ERROR_EXIT_CODES,PakeErrorCode,@@ -128,6 +132,7 @@ program.action(async (urlArg: string, options: PakeCliOptions) => {}validateDownloadDirInput(options.downloadDir);+ options.inject = validateInjectInput(options.inject);if (!url) {if (jsonMode) {diff --git a/bin/helpers/merge.ts b/bin/helpers/merge.tsindex d469c63b..f11d8069 100644--- a/bin/helpers/merge.ts+++ b/bin/helpers/merge.ts@@ -23,6 +23,7 @@ import {} from '@/utils/dir';import { PakeError } from '@/utils/error';import { LINUX_TARGET_TYPES, resolveLinuxBundleTargets } from '@/utils/targets';+import { validateInjectInput } from '@/utils/validate';import {applyDarwinIconComposerPackage,iconPathExtension,@@ -509,15 +510,9 @@ async function injectCustomCode();if (inject?.length > 0) {- const injectArray = Array.isArray(inject) ? inject : [inject];- if (- !injectArray.every(- (item) => item.endsWith('.css') || item.endsWith('.js'),- )- ) {- logger.error('The injected file must be in either CSS or JS format.');- return;- }+ const injectArray = validateInjectInput(+ Array.isArray(inject) ? inject : [inject],+ );const files = injectArray.map((filepath) =>path.isAbsolute(filepath) ? filepath : path.join(process.cwd(), filepath),);diff --git a/bin/utils/combine.ts b/bin/utils/combine.tsindex 5b2a6f0b..7f67a1c3 100644--- a/bin/utils/combine.ts+++ b/bin/utils/combine.ts@@ -3,7 +3,7 @@ import fs from 'fs/promises';export default async function combineFiles(files: string[], output: string) {const contents = await Promise.all(files.map(async (file) => {- if (file.endsWith('.css')) {+ if (file.toLowerCase().endsWith('.css')) {const fileContent = await fs.readFile(file, 'utf-8');return `window.addEventListener('DOMContentLoaded', (_event) => {const css = ${JSON.stringify(fileContent)};diff --git a/bin/utils/validate.ts b/bin/utils/validate.tsindex 8dfae527..43dd4857 100644--- a/bin/utils/validate.ts+++ b/bin/utils/validate.ts@@ -69,3 +69,38 @@ export function validateDownloadDirInput(value: string): string {}return value;}++const INJECT_EXTENSIONS = new Set(['.css', '.js']);++// Shared by --inject and the config "inject" field, so a config entry is split+// on commas like the flag and a bad file fails before anything is built.+export function validateInjectInput(+ inject: string[] | undefined,+ cwd: string = process.cwd(),+): string[] {+ if (!Array.isArray(inject)) return [];+ const files = inject+ .flatMap((entry) => entry.split(','))+ .map((item) => item.trim())+ .filter((item) => item.length > 0);++ for (const file of files) {+ if (!INJECT_EXTENSIONS.has(path.extname(file).toLowerCase())) {+ throw new PakeError(+ `Injected file "${file}" is not a .css or .js file.`,+ {+ code: 'INVALID_INPUT',+ hint: 'Pass local CSS or JS files to --inject, separated by commas.',+ },+ );+ }+ const resolved = path.isAbsolute(file) ? file : path.join(cwd, file);+ if (!fs.statSync(resolved, { throwIfNoEntry: false })?.isFile()) {+ throw new PakeError(`Injected file not found: ${file}`, {+ code: 'INVALID_INPUT',+ hint: 'Relative --inject paths resolve against the current directory.',+ });+ }+ }+ return files;+}diff --git a/dist/cli.js b/dist/cli.jsindex 1ae5762f..034f43ec 100644--- a/dist/cli.js+++ b/dist/cli.js@@ -13,10 +13,10 @@ import fs from 'fs';import { fileURLToPath } from 'url';import { setTimeout as setTimeout$1 } from 'timers/promises';import fs$1 from 'fs/promises';+import { InvalidArgumentError, program as program$1, Option } from 'commander';+import * as psl from 'psl';import { dir } from 'tmp-promise';import { fileTypeFromBuffer } from 'file-type';-import * as psl from 'psl';-import { InvalidArgumentError, program as program$1, Option } from 'commander';var name = "pake-cli";var version = "3.19.6";@@ -848,7 +848,7 @@ function hasWindowsGnuToolchain() {async function combineFiles(files, output) {const contents = await Promise.all(files.map(async (file) => {- if (file.endsWith('.css')) {+ if (file.toLowerCase().endsWith('.css')) {const fileContent = await fs$1.readFile(file, 'utf-8');return `window.addEventListener('DOMContentLoaded', (_event) => {const css = ${JSON.stringify(fileContent)};@@ -934,6 +934,145 @@ function resolveLinuxBundleTargets(targets) {return { bundleTargets, hasValidTarget: requested.length > 0 };}+// Extracts the domain from a given URL.+function getDomain(inputUrl) {+ try {+ const url = new URL(inputUrl);+ // Use PSL to parse domain names.+ const parsed = psl.parse(url.hostname);+ // If domain is available, split it and return the SLD.+ if ('domain' in parsed && parsed.domain) {+ return parsed.domain.split('.')[0];+ }+ else {+ return null;+ }+ }+ catch (error) {+ return null;+ }+}+// Appends 'https://' protocol to the URL if not present.+function appendProtocol(inputUrl) {+ try {+ new URL(inputUrl);+ return inputUrl;+ }+ catch {+ return `https://${inputUrl}`;+ }+}+// Normalizes the URL by ensuring it has a protocol and is valid.+function normalizeUrl(urlToNormalize) {+ const urlWithProtocol = appendProtocol(urlToNormalize);+ try {+ new URL(urlWithProtocol);+ return urlWithProtocol;+ }+ catch (err) {+ throw new Error(`Your url "${urlWithProtocol}" is invalid: ${err.message}`);+ }+}+// Compiles a comma-separated domain list into a regex source for+// internal_url_regex. Each domain is escaped and matched against the URL host+// and its subdomains so path or query text cannot accidentally opt a link in.+// Returns '' for empty input.+function safeDomainsToRegex(domains) {+ const escaped = domains+ .split(',')+ .map((domain) => domain.trim().toLowerCase())+ .filter(Boolean)+ .map((domain) => domain.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'));+ return escaped.length+ ? `^https?:\\/\\/(?:[^/?#@]+\\.)*(?:${escaped.join('|')})(?::\\d+)?(?:[/?#]|$)`+ : '';+}++function validateNumberInput(value) {+ if (value.trim() === '') {+ throw new InvalidArgumentError('Not a number.');+ }+ const parsedValue = Number(value);+ if (!Number.isFinite(parsedValue)) {+ throw new InvalidArgumentError('Not a number.');+ }+ if (parsedValue < 0) {+ throw new InvalidArgumentError('Must not be negative.');+ }+ return parsedValue;+}+// Path-shaped input (./x, ../x, /x, ~/x, C:\x). A missing path must fail+// loudly: appending https:// to "./typo" would otherwise produce a valid URL+// like https://./typo and a silently broken app (worst case for agents).+const PATH_LIKE_PATTERN = /^(\.{1,2}[\\/]|[\\/]|~[\\/]|[a-zA-Z]:[\\/])/;+function validateUrlInput(url) {+ const isFile = fs.existsSync(url);+ if (!isFile) {+ if (PATH_LIKE_PATTERN.test(url)) {+ throw new InvalidArgumentError(`Local path "${url}" does not exist. Check the path, or pass a web URL instead.`);+ }+ try {+ return normalizeUrl(url);+ }+ catch (error) {+ if (error instanceof Error) {+ throw new InvalidArgumentError(error.message);+ }+ throw error;+ }+ }+ return url;+}+function validateDownloadDirInput(value) {+ if (value === '')+ return value;+ const homeRelative = value.startsWith('~/') ? value.slice(2) : null;+ const invalidHomePath = homeRelative !== null &&+ (path.isAbsolute(homeRelative) ||+ (process.platform === 'win32' &&+ /^(?:[a-zA-Z]:|[\\/])/.test(homeRelative)));+ if (invalidHomePath ||+ value.includes('\0') ||+ !(path.isAbsolute(value) || value === '~' || value.startsWith('~/')) ||+ (process.platform === 'win32' &&+ value !== '~' &&+ !value.startsWith('~/') &&+ !/^(?:[a-zA-Z]:[\\/]|[\\/]{2}[^\\/]+[\\/][^\\/]+)/.test(value))) {+ throw new PakeError('Invalid download directory.', {+ code: 'INVALID_INPUT',+ hint: 'Use an absolute path or a quoted ~/path; relative paths are not supported.',+ });+ }+ return value;+}+const INJECT_EXTENSIONS = new Set(['.css', '.js']);+// Shared by --inject and the config "inject" field, so a config entry is split+// on commas like the flag and a bad file fails before anything is built.+function validateInjectInput(inject, cwd = process.cwd()) {+ if (!Array.isArray(inject))+ return [];+ const files = inject+ .flatMap((entry) => entry.split(','))+ .map((item) => item.trim())+ .filter((item) => item.length > 0);+ for (const file of files) {+ if (!INJECT_EXTENSIONS.has(path.extname(file).toLowerCase())) {+ throw new PakeError(`Injected file "${file}" is not a .css or .js file.`, {+ code: 'INVALID_INPUT',+ hint: 'Pass local CSS or JS files to --inject, separated by commas.',+ });+ }+ const resolved = path.isAbsolute(file) ? file : path.join(cwd, file);+ if (!fs.statSync(resolved, { throwIfNoEntry: false })?.isFile()) {+ throw new PakeError(`Injected file not found: ${file}`, {+ code: 'INVALID_INPUT',+ hint: 'Relative --inject paths resolve against the current directory.',+ });+ }+ }+ return files;+}+const ACTOOL_VERSION_ARGS = ['--version','--output-format=human-readable-text',@@ -1506,11 +1645,7 @@ async function injectCustomCode(options, tauriConf) {const { inject, proxyUrl, basicAuth, multiInstance, multiWindow, wasm } = options;const injectFilePath = path.join(npmDirectory, 'src-tauri/src/inject/custom.js');if (inject?.length > 0) {- const injectArray = Array.isArray(inject) ? inject : [inject];- if (!injectArray.every((item) => item.endsWith('.css') || item.endsWith('.js'))) {- logger.error('The injected file must be in either CSS or JS format.');- return;- }+ const injectArray = validateInjectInput(Array.isArray(inject) ? inject : [inject]);const files = injectArray.map((filepath) => path.isAbsolute(filepath) ? filepath : path.join(process.cwd(), filepath));tauriConf.pake.inject = files;await combineFiles(files, injectFilePath);@@ -3682,60 +3817,6 @@ async function saveIconFile(iconData, extension) {return originalIconPath;}-// Extracts the domain from a given URL.-function getDomain(inputUrl) {- try {- const url = new URL(inputUrl);- // Use PSL to parse domain names.- const parsed = psl.parse(url.hostname);- // If domain is available, split it and return the SLD.- if ('domain' in parsed && parsed.domain) {- return parsed.domain.split('.')[0];- }- else {- return null;- }- }- catch (error) {- return null;- }-}-// Appends 'https://' protocol to the URL if not present.-function appendProtocol(inputUrl) {- try {- new URL(inputUrl);- return inputUrl;- }- catch {- return `https://${inputUrl}`;- }-}-// Normalizes the URL by ensuring it has a protocol and is valid.-function normalizeUrl(urlToNormalize) {- const urlWithProtocol = appendProtocol(urlToNormalize);- try {- new URL(urlWithProtocol);- return urlWithProtocol;- }- catch (err) {- throw new Error(`Your url "${urlWithProtocol}" is invalid: ${err.message}`);- }-}-// Compiles a comma-separated domain list into a regex source for-// internal_url_regex. Each domain is escaped and matched against the URL host-// and its subdomains so path or query text cannot accidentally opt a link in.-// Returns '' for empty input.-function safeDomainsToRegex(domains) {- const escaped = domains- .split(',')- .map((domain) => domain.trim().toLowerCase())- .filter(Boolean)- .map((domain) => domain.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'));- return escaped.length- ? `^https?:\\/\\/(?:[^/?#@]+\\.)*(?:${escaped.join('|')})(?::\\d+)?(?:[/?#]|$)`- : '';-}-function resolveAppName(name, platform) {const domain = getDomain(name) || 'pake';return platform !== 'linux' ? capitalizeFirstLetter(domain) : domain;@@ -3876,64 +3957,6 @@ const DEFAULT_PAKE_OPTIONS = {microphone: false,};-function validateNumberInput(value) {- if (value.trim() === '') {- throw new InvalidArgumentError('Not a number.');- }- const parsedValue = Number(value);- if (!Number.isFinite(parsedValue)) {- throw new InvalidArgumentError('Not a number.');- }- if (parsedValue < 0) {- throw new InvalidArgumentError('Must not be negative.');- }- return parsedValue;-}-// Path-shaped input (./x, ../x, /x, ~/x, C:\x). A missing path must fail-// loudly: appending https:// to "./typo" would otherwise produce a valid URL-// like https://./typo and a silently broken app (worst case for agents).-const PATH_LIKE_PATTERN = /^(\.{1,2}[\\/]|[\\/]|~[\\/]|[a-zA-Z]:[\\/])/;-function validateUrlInput(url) {- const isFile = fs.existsSync(url);- if (!isFile) {- if (PATH_LIKE_PATTERN.test(url)) {- throw new InvalidArgumentError(`Local path "${url}" does not exist. Check the path, or pass a web URL instead.`);- }- try {- return normalizeUrl(url);- }- catch (error) {- if (error instanceof Error) {- throw new InvalidArgumentError(error.message);- }- throw error;- }- }- return url;-}-function validateDownloadDirInput(value) {- if (value === '')- return value;- const homeRelative = value.startsWith('~/') ? value.slice(2) : null;- const invalidHomePath = homeRelative !== null &&- (path.isAbsolute(homeRelative) ||- (process.platform === 'win32' &&- /^(?:[a-zA-Z]:|[\\/])/.test(homeRelative)));- if (invalidHomePath ||- value.includes('\0') ||- !(path.isAbsolute(value) || value === '~' || value.startsWith('~/')) ||- (process.platform === 'win32' &&- value !== '~' &&- !value.startsWith('~/') &&- !/^(?:[a-zA-Z]:[\\/]|[\\/]{2}[^\\/]+[\\/][^\\/]+)/.test(value))) {- throw new PakeError('Invalid download directory.', {- code: 'INVALID_INPUT',- hint: 'Use an absolute path or a quoted ~/path; relative paths are not supported.',- });- }- return value;-}-function getCliProgram() {const { green, yellow } = chalk;const logo = `${chalk.green(' ____ _')}@@ -4330,6 +4353,7 @@ program.action(async (urlArg, options) => {}}validateDownloadDirInput(options.downloadDir);+ options.inject = validateInjectInput(options.inject);if (!url) {if (jsonMode) {throw new PakeError('No URL or local path to package.', {diff --git a/tests/unit/combine.test.ts b/tests/unit/combine.test.tsindex 6df37de0..e4857fd4 100644--- a/tests/unit/combine.test.ts+++ b/tests/unit/combine.test.ts@@ -62,6 +62,18 @@ describe('combineFiles', () => {expect(injectedCss).toEqual(['body { color: red; }']);});+ it('wraps an upper-case .CSS file as a style injection, not as script', async () => {+ const cssFile = path.join(dir, 'THEME.CSS');+ const out = path.join(dir, 'out-upper-css.js');+ await fs.writeFile(cssFile, 'body { color: red; }');++ await combineFiles([cssFile], out);+ const result = await fs.readFile(out, 'utf-8');++ expect(() => new Function(result)).not.toThrow();+ expect(result).toContain(JSON.stringify('body { color: red; }'));+ });+it('returns the input file list', async () => {const jsFile = path.join(dir, 'ret.js');const out = path.join(dir, 'out-ret.js');diff --git a/tests/unit/validate-inject-input.test.ts b/tests/unit/validate-inject-input.test.tsnew file mode 100644index 00000000..4bc11f45--- /dev/null+++ b/tests/unit/validate-inject-input.test.ts@@ -0,0 +1,90 @@+import { afterAll, beforeAll, describe, expect, it } from 'vitest';+import fs from 'node:fs';+import os from 'node:os';+import path from 'node:path';+import { validateInjectInput } from '@/utils/validate';++describe('validateInjectInput', () => {+ let dir: string;++ beforeAll(() => {+ dir = fs.mkdtempSync(path.join(os.tmpdir(), 'pake-inject-'));+ for (const name of ['style.css', 'hotkey.js', 'THEME.CSS', 'notes.txt']) {+ fs.writeFileSync(path.join(dir, name), '');+ }+ fs.mkdirSync(path.join(dir, 'folder.js'));+ });++ afterAll(() => {+ fs.rmSync(dir, { recursive: true, force: true });+ });++ it('returns no files when nothing is injected', () => {+ expect(validateInjectInput(undefined, dir)).toEqual([]);+ expect(validateInjectInput([], dir)).toEqual([]);+ });++ it('accepts relative and absolute .css and .js files', () => {+ const absolute = path.join(dir, 'hotkey.js');+ expect(validateInjectInput(['style.css', absolute], dir)).toEqual([+ 'style.css',+ absolute,+ ]);+ });++ it('accepts upper-case extensions', () => {+ expect(validateInjectInput(['THEME.CSS'], dir)).toEqual(['THEME.CSS']);+ });++ it('splits a comma-separated config entry the way the flag does', () => {+ expect(validateInjectInput(['style.css, hotkey.js', ' '], dir)).toEqual([+ 'style.css',+ 'hotkey.js',+ ]);+ });++ it('rejects a file that is neither CSS nor JS', () => {+ expect(() => validateInjectInput(['style.css', 'notes.txt'], dir)).toThrow(+ expect.objectContaining({+ code: 'INVALID_INPUT',+ message: expect.stringMatching(+ /"notes\.txt" is not a \.css or \.js file/,+ ),+ }),+ );+ });++ it('rejects a missing file instead of failing later in the build', () => {+ expect(() => validateInjectInput(['missing.js'], dir)).toThrow(+ expect.objectContaining({+ code: 'INVALID_INPUT',+ message: expect.stringMatching(/Injected file not found: missing\.js/),+ }),+ );+ });++ it('rejects a directory whose name ends in .js', () => {+ expect(() => validateInjectInput(['folder.js'], dir)).toThrow(+ expect.objectContaining({+ code: 'INVALID_INPUT',+ message: expect.stringMatching(/Injected file not found: folder\.js/),+ }),+ );+ });++ it('runs in the CLI before the build workspace is entered', () => {+ const source = fs+ .readFileSync(path.join(__dirname, '../../bin/cli.ts'), 'utf8')+ .replace(/\r\n/g, '\n');+ const validateAt = source.indexOf(+ 'options.inject = validateInjectInput(options.inject);',+ );+ expect(validateAt).toBeGreaterThan(-1);+ expect(validateAt).toBeGreaterThan(+ source.indexOf('loadConfigFile(options.config'),+ );+ expect(validateAt).toBeLessThan(+ source.indexOf('await enterBuildWorkspace()'),+ );+ });+});