Skip to content

armgit / Pake

Public Imported from GitHub
0

Turn any website into a lightweight desktop app with one command, on macOS, Windows and Linux.

fix: harden post-3.10.1 code review findings

Tw931a34b5f912c2
diff --git a/bin/builders/BaseBuilder.ts b/bin/builders/BaseBuilder.ts
index ff3cfcd9..62c03feb 100644
--- a/bin/builders/BaseBuilder.ts
+++ b/bin/builders/BaseBuilder.ts
@@ -316,20 +316,16 @@ export default abstract class BaseBuilder {
const appBundleName = path.basename(appBundlePath);
const appDest = path.join('/Applications', appBundleName);
- if (await fsExtra.pathExists(appDest)) {
- await fsExtra.remove(appDest);
- }
-
- await fsExtra.copy(appBundlePath, appDest);
- await fsExtra.remove(appBundlePath);
+ // fsExtra.move uses fs.rename (atomic on same filesystem) and falls back
+ // to copy+remove only when moving across volumes.
+ await fsExtra.move(appBundlePath, appDest, { overwrite: true });
logger.success(
`✔ ${appBundleName.replace(/\.app$/, '')} installed to /Applications`,
);
- logger.success('✔ Local app bundle removed');
} catch (error) {
logger.error(`✕ Failed to install ${appName}: ${error}`);
- logger.info(` The app bundle is still available at: ${appBundlePath}`);
+ logger.info(` App bundle still available at: ${appBundlePath}`);
}
}
diff --git a/bin/defaults.ts b/bin/defaults.ts
index e919f5da..6fb41c02 100644
--- a/bin/defaults.ts
+++ b/bin/defaults.ts
@@ -51,6 +51,8 @@ export const DEFAULT_PAKE_OPTIONS: PakeCliOptions = {
ignoreCertificateErrors: false,
newWindow: false,
install: false,
+ camera: false,
+ microphone: false,
};
// Just for cli development
diff --git a/bin/helpers/cli-program.ts b/bin/helpers/cli-program.ts
index 76dad137..a43773bc 100644
--- a/bin/helpers/cli-program.ts
+++ b/bin/helpers/cli-program.ts
@@ -256,6 +256,16 @@ ${green('|_| \\__,_|_|\\_\\___| can turn any webpage into a desktop app with
'Auto-install app to /Applications (macOS) after build and remove local bundle',
DEFAULT.install,
)
+ .addOption(
+ new Option('--camera', 'Request camera permission on macOS')
+ .default(DEFAULT.camera)
+ .hideHelp(),
+ )
+ .addOption(
+ new Option('--microphone', 'Request microphone permission on macOS')
+ .default(DEFAULT.microphone)
+ .hideHelp(),
+ )
.version(packageJson.version, '-v, --version')
.configureHelp({
sortSubcommands: true,
diff --git a/bin/helpers/merge.ts b/bin/helpers/merge.ts
index 54712ed2..8f23eeaf 100644
--- a/bin/helpers/merge.ts
+++ b/bin/helpers/merge.ts
@@ -79,6 +79,8 @@ export async function mergeConfig(
minHeight,
ignoreCertificateErrors,
newWindow,
+ camera,
+ microphone,
} = options;
const { platform } = process;
@@ -385,6 +387,35 @@ Terminal=false
};
}
+ // Write entitlements dynamically on macOS so camera/microphone are opt-in
+ if (platform === 'darwin') {
+ const entitlementEntries: string[] = [];
+ if (camera) {
+ entitlementEntries.push(
+ ' <key>com.apple.security.device.camera</key>\n <true/>',
+ );
+ }
+ if (microphone) {
+ entitlementEntries.push(
+ ' <key>com.apple.security.device.audio-input</key>\n <true/>',
+ );
+ }
+ const entitlementsContent = `<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
+<plist version="1.0">
+ <dict>
+${entitlementEntries.join('\n')}
+ </dict>
+</plist>
+`;
+ const entitlementsPath = path.join(
+ npmDirectory,
+ 'src-tauri',
+ 'entitlements.plist',
+ );
+ await fsExtra.writeFile(entitlementsPath, entitlementsContent);
+ }
+
// Save config file.
const platformConfigPaths: PlatformMap = {
win32: 'tauri.windows.conf.json',
diff --git a/bin/options/index.ts b/bin/options/index.ts
index 6bd7240e..634b735b 100644
--- a/bin/options/index.ts
+++ b/bin/options/index.ts
@@ -64,8 +64,6 @@ export default async function handleOptions(
name = generateLinuxPackageName(name);
}
- const resolvedName = name || 'pake-app';
-
if (name && !isValidName(name, platform)) {
const LINUX_NAME_ERROR = `✕ Name should only include lowercase letters, numbers, and dashes (not leading dashes). Examples: com-123-xxx, 123pan, pan123, weread, we-read, 123.`;
const DEFAULT_NAME_ERROR = `✕ Name should only include letters, numbers, dashes, and spaces (not leading dashes and spaces). Examples: 123pan, 123Pan, Pan123, weread, WeRead, WERead, we-read, We Read, 123.`;
@@ -80,10 +78,12 @@ export default async function handleOptions(
}
}
+ const resolvedName = name || 'pake-app';
+
const appOptions: PakeAppOptions = {
...options,
name: resolvedName,
- identifier: resolveIdentifier(url, resolvedName, options.identifier),
+ identifier: resolveIdentifier(url, options.name, options.identifier),
};
const iconPath = await handleIcon(appOptions, url);
diff --git a/bin/types.ts b/bin/types.ts
index caab4e40..28cd1248 100644
--- a/bin/types.ts
+++ b/bin/types.ts
@@ -129,6 +129,12 @@ export interface PakeCliOptions {
// Auto-install app to /Applications (macOS) after build, default false
install: boolean;
+
+ // Request camera entitlement on macOS, default false
+ camera: boolean;
+
+ // Request microphone entitlement on macOS, default false
+ microphone: boolean;
}
export interface PakeAppOptions extends PakeCliOptions {
diff --git a/bin/utils/info.ts b/bin/utils/info.ts
index 872b0f4a..13298f9d 100644
--- a/bin/utils/info.ts
+++ b/bin/utils/info.ts
@@ -3,11 +3,15 @@ import prompts from 'prompts';
import ora from 'ora';
import chalk from 'chalk';
-// Generates a stable identifier based on the app URL and name.
-export function getIdentifier(url: string, name: string) {
+// Generates a stable identifier based on the app URL (and optionally name).
+// When name is provided it is included in the hash so two apps wrapping
+// the same URL can coexist. Omitting name preserves backward compatibility
+// with identifiers generated before V3.10.1.
+export function getIdentifier(url: string, name?: string) {
+ const hashInput = name ? `${url}::${name}` : url;
const postFixHash = crypto
.createHash('md5')
- .update(`${url}::${name}`)
+ .update(hashInput)
.digest('hex')
.substring(0, 6);
return `com.pake.${postFixHash}`;
@@ -15,7 +19,7 @@ export function getIdentifier(url: string, name: string) {
export function resolveIdentifier(
url: string,
- name: string,
+ explicitName: string | undefined,
customIdentifier?: string,
) {
const trimmedIdentifier = customIdentifier?.trim();
@@ -23,7 +27,7 @@ export function resolveIdentifier(
return trimmedIdentifier;
}
- return getIdentifier(url, name);
+ return getIdentifier(url, explicitName);
}
export async function promptText(
diff --git a/dist/cli.js b/dist/cli.js
index 0c4034f6..9c32c1aa 100644
--- a/dist/cli.js
+++ b/dist/cli.js
@@ -171,21 +171,25 @@ let tauriConfig = {
pake: pakeConf,
};
-// Generates a stable identifier based on the app URL and name.
+// Generates a stable identifier based on the app URL (and optionally name).
+// When name is provided it is included in the hash so two apps wrapping
+// the same URL can coexist. Omitting name preserves backward compatibility
+// with identifiers generated before V3.10.1.
function getIdentifier(url, name) {
+ const hashInput = name ? `${url}::${name}` : url;
const postFixHash = crypto
.createHash('md5')
- .update(`${url}::${name}`)
+ .update(hashInput)
.digest('hex')
.substring(0, 6);
return `com.pake.${postFixHash}`;
}
-function resolveIdentifier(url, name, customIdentifier) {
+function resolveIdentifier(url, explicitName, customIdentifier) {
const trimmedIdentifier = customIdentifier?.trim();
if (trimmedIdentifier) {
return trimmedIdentifier;
}
- return getIdentifier(url, name);
+ return getIdentifier(url, explicitName);
}
async function promptText(message, initial) {
const response = await prompts({
@@ -491,7 +495,7 @@ async function mergeConfig(url, options, tauriConf) {
await fsExtra.copy(sourcePath, destPath);
}
}));
- const { width, height, fullscreen, maximize, hideTitleBar, alwaysOnTop, appVersion, darkMode, disabledWebShortcuts, activationShortcut, userAgent, showSystemTray, systemTrayIcon, useLocalFile, identifier, name = 'pake-app', resizable = true, inject, proxyUrl, installerLanguage, hideOnClose, incognito, title, wasm, enableDragDrop, multiInstance, multiWindow, startToTray, forceInternalNavigation, internalUrlRegex, zoom, minWidth, minHeight, ignoreCertificateErrors, newWindow, } = options;
+ const { width, height, fullscreen, maximize, hideTitleBar, alwaysOnTop, appVersion, darkMode, disabledWebShortcuts, activationShortcut, userAgent, showSystemTray, systemTrayIcon, useLocalFile, identifier, name = 'pake-app', resizable = true, inject, proxyUrl, installerLanguage, hideOnClose, incognito, title, wasm, enableDragDrop, multiInstance, multiWindow, startToTray, forceInternalNavigation, internalUrlRegex, zoom, minWidth, minHeight, ignoreCertificateErrors, newWindow, camera, microphone, } = options;
const { platform } = process;
const platformHideOnClose = hideOnClose ?? platform === 'darwin';
const tauriConfWindowOptions = {
@@ -746,6 +750,26 @@ Terminal=false
},
};
}
+ // Write entitlements dynamically on macOS so camera/microphone are opt-in
+ if (platform === 'darwin') {
+ const entitlementEntries = [];
+ if (camera) {
+ entitlementEntries.push(' <key>com.apple.security.device.camera</key>\n <true/>');
+ }
+ if (microphone) {
+ entitlementEntries.push(' <key>com.apple.security.device.audio-input</key>\n <true/>');
+ }
+ const entitlementsContent = `<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
+<plist version="1.0">
+ <dict>
+${entitlementEntries.join('\n')}
+ </dict>
+</plist>
+`;
+ const entitlementsPath = path.join(npmDirectory, 'src-tauri', 'entitlements.plist');
+ await fsExtra.writeFile(entitlementsPath, entitlementsContent);
+ }
// Save config file.
const platformConfigPaths = {
win32: 'tauri.windows.conf.json',
@@ -978,17 +1002,14 @@ class BaseBuilder {
logger.info(`- Installing ${appName} to /Applications...`);
const appBundleName = path.basename(appBundlePath);
const appDest = path.join('/Applications', appBundleName);
- if (await fsExtra.pathExists(appDest)) {
- await fsExtra.remove(appDest);
- }
- await fsExtra.copy(appBundlePath, appDest);
- await fsExtra.remove(appBundlePath);
+ // fsExtra.move uses fs.rename (atomic on same filesystem) and falls back
+ // to copy+remove only when moving across volumes.
+ await fsExtra.move(appBundlePath, appDest, { overwrite: true });
logger.success(`✔ ${appBundleName.replace(/\.app$/, '')} installed to /Applications`);
- logger.success('✔ Local app bundle removed');
}
catch (error) {
logger.error(`✕ Failed to install ${appName}: ${error}`);
- logger.info(` The app bundle is still available at: ${appBundlePath}`);
+ logger.info(` App bundle still available at: ${appBundlePath}`);
}
}
getFileType(target) {
@@ -2009,7 +2030,6 @@ async function handleOptions(options, url) {
if (name && platform === 'linux') {
name = generateLinuxPackageName(name);
}
- const resolvedName = name || 'pake-app';
if (name && !isValidName(name, platform)) {
const LINUX_NAME_ERROR = `✕ Name should only include lowercase letters, numbers, and dashes (not leading dashes). Examples: com-123-xxx, 123pan, pan123, weread, we-read, 123.`;
const DEFAULT_NAME_ERROR = `✕ Name should only include letters, numbers, dashes, and spaces (not leading dashes and spaces). Examples: 123pan, 123Pan, Pan123, weread, WeRead, WERead, we-read, We Read, 123.`;
@@ -2023,10 +2043,11 @@ async function handleOptions(options, url) {
process.exit(1);
}
}
+ const resolvedName = name || 'pake-app';
const appOptions = {
...options,
name: resolvedName,
- identifier: resolveIdentifier(url, resolvedName, options.identifier),
+ identifier: resolveIdentifier(url, options.name, options.identifier),
};
const iconPath = await handleIcon(appOptions, url);
appOptions.icon = iconPath || '';
@@ -2083,6 +2104,8 @@ const DEFAULT_PAKE_OPTIONS = {
ignoreCertificateErrors: false,
newWindow: false,
install: false,
+ camera: false,
+ microphone: false,
};
function validateNumberInput(value) {
@@ -2122,8 +2145,7 @@ ${green('|_| \\__,_|_|\\_\\___| can turn any webpage into a desktop app with
.showHelpAfterError()
.argument('[url]', 'The web URL you want to package', validateUrlInput)
.option('--name <string>', 'Application name')
- .addOption(new Option('--identifier <string>', 'Application identifier / bundle ID')
- .hideHelp())
+ .addOption(new Option('--identifier <string>', 'Application identifier / bundle ID').hideHelp())
.option('--icon <string>', 'Application icon', DEFAULT_PAKE_OPTIONS.icon)
.option('--width <number>', 'Window width', validateNumberInput, DEFAULT_PAKE_OPTIONS.width)
.option('--height <number>', 'Window height', validateNumberInput, DEFAULT_PAKE_OPTIONS.height)
@@ -2245,6 +2267,12 @@ ${green('|_| \\__,_|_|\\_\\___| can turn any webpage into a desktop app with
.default(DEFAULT_PAKE_OPTIONS.newWindow)
.hideHelp())
.option('--install', 'Auto-install app to /Applications (macOS) after build and remove local bundle', DEFAULT_PAKE_OPTIONS.install)
+ .addOption(new Option('--camera', 'Request camera permission on macOS')
+ .default(DEFAULT_PAKE_OPTIONS.camera)
+ .hideHelp())
+ .addOption(new Option('--microphone', 'Request microphone permission on macOS')
+ .default(DEFAULT_PAKE_OPTIONS.microphone)
+ .hideHelp())
.version(packageJson.version, '-v, --version')
.configureHelp({
sortSubcommands: true,
diff --git a/docs/advanced-usage.md b/docs/advanced-usage.md
index 7d66d3ba..9db2034b 100644
--- a/docs/advanced-usage.md
+++ b/docs/advanced-usage.md
@@ -124,6 +124,20 @@ pake ./my-app/index.html --name my-static-app --use-local-file
Requirements: Pake CLI >= 3.0.0
+## macOS Media Permissions
+
+By default, apps built with Pake do not request camera or microphone access. For sites that require these (for example, video conferencing or voice input), pass the relevant flags at build time:
+
+```bash
+pake https://chatgpt.com --name ChatGPT --microphone
+pake https://meet.google.com --name GoogleMeet --camera --microphone
+```
+
+- `--microphone` — grants microphone access (`com.apple.security.device.audio-input`)
+- `--camera` — grants camera access (`com.apple.security.device.camera`)
+
+macOS will prompt the user for permission on first use. Only add these flags for sites that actually need them.
+
## Multiple Apps For The Same Site
If you need separate apps for the same site, for example two Gmail accounts with different login state, build them with different app names:
diff --git a/docs/advanced-usage_CN.md b/docs/advanced-usage_CN.md
index a0808b09..8c8deaf3 100644
--- a/docs/advanced-usage_CN.md
+++ b/docs/advanced-usage_CN.md
@@ -124,6 +124,20 @@ pake ./my-app/index.html --name my-static-app --use-local-file
要求:Pake CLI >= 3.0.0
+## macOS 摄像头与麦克风权限
+
+Pake 构建的应用默认不申请摄像头或麦克风权限。对于需要这些权限的站点(例如视频会议或语音输入),在构建时传入对应的标志:
+
+```bash
+pake https://chatgpt.com --name ChatGPT --microphone
+pake https://meet.google.com --name GoogleMeet --camera --microphone
+```
+
+- `--microphone` — 申请麦克风权限(`com.apple.security.device.audio-input`)
+- `--camera` — 申请摄像头权限(`com.apple.security.device.camera`)
+
+macOS 会在首次使用时向用户弹出权限确认对话框。请仅在确实需要的站点上添加这些标志。
+
## 同一站点生成多个独立应用
如果你需要为同一个站点生成多个彼此独立的应用,例如两个不同登录态的 Gmail,可以直接使用不同的应用名称进行构建:
diff --git a/src-tauri/entitlements.plist b/src-tauri/entitlements.plist
index c2fcd7b3..bddf1d48 100644
--- a/src-tauri/entitlements.plist
+++ b/src-tauri/entitlements.plist
@@ -2,9 +2,6 @@
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
- <key>com.apple.security.device.audio-input</key>
- <true/>
- <key>com.apple.security.device.camera</key>
- <true/>
+
</dict>
</plist>
diff --git a/src-tauri/src/app/window.rs b/src-tauri/src/app/window.rs
index 0694687e..a0c7bcac 100644
--- a/src-tauri/src/app/window.rs
+++ b/src-tauri/src/app/window.rs
@@ -57,6 +57,13 @@ pub fn open_additional_window(app: &AppHandle) -> tauri::Result<WebviewWindow> {
build_window_with_label(app, &state.pake_config, &state.tauri_config, &label)
}
+struct WindowBuildOptions<'a> {
+ label: &'a str,
+ url: WebviewUrl,
+ visible: bool,
+ new_window_features: Option<NewWindowFeatures>,
+}
+
fn open_requested_window(
app: &AppHandle,
config: &PakeConfig,
@@ -70,13 +77,16 @@ fn open_requested_window(
app,
config,
tauri_config,
- &label,
- WebviewUrl::External("about:blank".parse().unwrap()),
- true,
- Some(features),
+ WindowBuildOptions {
+ label: &label,
+ url: WebviewUrl::External("about:blank".parse().unwrap()),
+ visible: true,
+ new_window_features: Some(features),
+ },
)?;
- let _ = window.set_title(target_url.as_str());
+ let title = target_url.host_str().unwrap_or(target_url.as_str());
+ let _ = window.set_title(title);
let _ = window.set_focus();
Ok(window)
@@ -119,18 +129,31 @@ fn build_window_with_label(
_ => panic!("url type can only be web or local"),
};
- build_window(app, config, tauri_config, label, url, false, None)
+ build_window(
+ app,
+ config,
+ tauri_config,
+ WindowBuildOptions {
+ label,
+ url,
+ visible: false,
+ new_window_features: None,
+ },
+ )
}
fn build_window(
app: &AppHandle,
config: &PakeConfig,
tauri_config: &Config,
- label: &str,
- url: WebviewUrl,
- visible: bool,
- new_window_features: Option<NewWindowFeatures>,
+ opts: WindowBuildOptions,
) -> tauri::Result<WebviewWindow> {
+ let WindowBuildOptions {
+ label,
+ url,
+ visible,
+ new_window_features,
+ } = opts;
let package_name = tauri_config.clone().product_name.unwrap();
let _data_dir = get_data_dir(app, package_name);