Skip to content

Commit

Permalink
feat(bundler): add nsis, closes #4450, closes #2319
Browse files Browse the repository at this point in the history
  • Loading branch information
amrbashir committed Jul 15, 2022
1 parent 95abf48 commit 5dc506c
Show file tree
Hide file tree
Showing 13 changed files with 707 additions and 108 deletions.
33 changes: 32 additions & 1 deletion core/tauri-utils/src/config.rs
Expand Up @@ -76,6 +76,8 @@ pub enum BundleType {
AppImage,
/// The Microsoft Installer bundle (.msi).
Msi,
/// The NSIS bundle (.exe).
Nsis,
/// The macOS application bundle (.app).
App,
/// The Apple Disk Image bundle (.dmg).
Expand All @@ -93,6 +95,7 @@ impl Display for BundleType {
Self::Deb => "deb",
Self::AppImage => "appimage",
Self::Msi => "msi",
Self::Nsis => "nsis",
Self::App => "app",
Self::Dmg => "dmg",
Self::Updater => "updater",
Expand Down Expand Up @@ -120,6 +123,7 @@ impl<'de> Deserialize<'de> for BundleType {
"deb" => Ok(Self::Deb),
"appimage" => Ok(Self::AppImage),
"msi" => Ok(Self::Msi),
"nsis" => Ok(Self::Nsis),
"app" => Ok(Self::App),
"dmg" => Ok(Self::Dmg),
"updater" => Ok(Self::Updater),
Expand Down Expand Up @@ -407,6 +411,30 @@ pub struct WixConfig {
pub dialog_image_path: Option<PathBuf>,
}

/// Configuration for the Installer bundle using NSIS.
#[derive(Debug, Default, PartialEq, Eq, Clone, Deserialize, Serialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct NsisConfig {
/// The path to the license file to render on the installer.
///
/// Must be an RTF file, so if a different extension is provided, we convert it to the RTF format.
pub license: Option<PathBuf>,
/// The path to a bitmap file to display on the header of installers pages.
///
/// The recommended dimensions are 150pxx57px.
pub header_image: Option<PathBuf>,
/// The path to a bitmap file for the Welcome page and the Finish page.
///
/// The recommended dimensions are 164pxx314px.
pub sidebar_image: Option<PathBuf>,
/// The path to an icon file used as the installer icon.
pub installer_icon: Option<PathBuf>,
/// Whether the installation will be for all users or just the current user.
#[serde(default)]
pub per_machine: bool,
}

/// Install modes for the Webview2 runtime.
/// Note that for the updater bundle [`Self::DownloadBootstrapper`] is used.
///
Expand Down Expand Up @@ -499,6 +527,8 @@ pub struct WindowsConfig {
pub allow_downgrades: bool,
/// Configuration for the MSI generated with WiX.
pub wix: Option<WixConfig>,
/// Configuration for the installer generated with NSIS.
pub nsis: Option<NsisConfig>,
}

impl Default for WindowsConfig {
Expand All @@ -512,6 +542,7 @@ impl Default for WindowsConfig {
webview_fixed_runtime_path: None,
allow_downgrades: default_allow_downgrades(),
wix: None,
nsis: None,
}
}
}
Expand All @@ -529,7 +560,7 @@ pub struct BundleConfig {
/// Whether Tauri should bundle your application or just output the executable.
#[serde(default)]
pub active: bool,
/// The bundle targets, currently supports ["deb", "appimage", "msi", "app", "dmg", "updater"] or "all".
/// The bundle targets, currently supports ["deb", "appimage", "nsis", "msi", "app", "dmg", "updater"] or "all".
#[serde(default)]
pub targets: BundleTarget,
/// The application identifier in reverse domain name notation (e.g. `com.tauri.example`).
Expand Down
1 change: 1 addition & 0 deletions tooling/bundler/Cargo.toml
Expand Up @@ -44,6 +44,7 @@ uuid = { version = "1", features = [ "v4", "v5" ] }
bitness = "0.4"
winreg = "0.10"
sha2 = "0.10"
sha1 = "0.10"
hex = "0.4"
glob = "0.3"
zip = "0.6"
Expand Down
4 changes: 3 additions & 1 deletion tooling/bundler/src/bundle.rs
Expand Up @@ -23,7 +23,7 @@ pub use self::{
},
};
use log::{info, warn};
pub use settings::{WindowsSettings, WixLanguage, WixLanguageConfig, WixSettings};
pub use settings::{NsisSettings, WindowsSettings, WixLanguage, WixLanguageConfig, WixSettings};

use std::{fmt::Write, path::PathBuf};

Expand All @@ -50,6 +50,8 @@ pub fn bundle_project(settings: Settings) -> crate::Result<Vec<Bundle>> {
PackageType::IosBundle => macos::ios::bundle_project(&settings)?,
#[cfg(target_os = "windows")]
PackageType::WindowsMsi => windows::msi::bundle_project(&settings, false)?,
#[cfg(target_os = "windows")]
PackageType::Nsis => windows::nsis::bundle_project(&settings)?,
#[cfg(target_os = "linux")]
PackageType::Deb => linux::debian::bundle_project(&settings)?,
#[cfg(target_os = "linux")]
Expand Down
33 changes: 32 additions & 1 deletion tooling/bundler/src/bundle/settings.rs
Expand Up @@ -25,6 +25,8 @@ pub enum PackageType {
IosBundle,
/// The Windows bundle (.msi).
WindowsMsi,
/// The NSIS bundle (.exe).
Nsis,
/// The Linux Debian package bundle (.deb).
Deb,
/// The Linux RPM bundle (.rpm).
Expand All @@ -43,6 +45,7 @@ impl From<BundleType> for PackageType {
BundleType::Deb => Self::Deb,
BundleType::AppImage => Self::AppImage,
BundleType::Msi => Self::WindowsMsi,
BundleType::Nsis => Self::Nsis,
BundleType::App => Self::MacOsBundle,
BundleType::Dmg => Self::Dmg,
BundleType::Updater => Self::Updater,
Expand All @@ -59,6 +62,7 @@ impl PackageType {
"deb" => Some(PackageType::Deb),
"ios" => Some(PackageType::IosBundle),
"msi" => Some(PackageType::WindowsMsi),
"nsis" => Some(PackageType::Nsis),
"app" => Some(PackageType::MacOsBundle),
"rpm" => Some(PackageType::Rpm),
"appimage" => Some(PackageType::AppImage),
Expand All @@ -75,6 +79,7 @@ impl PackageType {
PackageType::Deb => "deb",
PackageType::IosBundle => "ios",
PackageType::WindowsMsi => "msi",
PackageType::Nsis => "nsis",
PackageType::MacOsBundle => "app",
PackageType::Rpm => "rpm",
PackageType::AppImage => "appimage",
Expand All @@ -96,6 +101,8 @@ const ALL_PACKAGE_TYPES: &[PackageType] = &[
PackageType::IosBundle,
#[cfg(target_os = "windows")]
PackageType::WindowsMsi,
#[cfg(target_os = "windows")]
PackageType::Nsis,
#[cfg(target_os = "macos")]
PackageType::MacOsBundle,
#[cfg(target_os = "linux")]
Expand Down Expand Up @@ -239,6 +246,27 @@ pub struct WixSettings {
pub dialog_image_path: Option<PathBuf>,
}

/// Settings specific to the NSIS implementation.
#[derive(Clone, Debug, Default)]
pub struct NsisSettings {
/// The path to the license file to render on the installer.
///
/// Must be an RTF file, so if a different extension is provided, we convert it to the RTF format.
pub license: Option<PathBuf>,
/// The path to a bitmap file to display on the header of installers pages.
///
/// The recommended dimensions are 150pxx57px.
pub header_image: Option<PathBuf>,
/// The path to a bitmap file for the Welcome page and the Finish page.
///
/// The recommended dimensions are 164pxx314px.
pub sidebar_image: Option<PathBuf>,
/// The path to an icon file used as the installer icon.
pub installer_icon: Option<PathBuf>,
/// Whether the installation will be for all users or just the current user.
pub per_machine: bool,
}

/// The Windows bundle settings.
#[derive(Clone, Debug)]
pub struct WindowsSettings {
Expand All @@ -253,6 +281,8 @@ pub struct WindowsSettings {
pub tsp: bool,
/// WiX configuration.
pub wix: Option<WixSettings>,
/// Nsis configuration.
pub nsis: Option<NsisSettings>,
/// The path to the application icon. Defaults to `./icons/icon.ico`.
pub icon_path: PathBuf,
/// The installation mode for the Webview2 runtime.
Expand All @@ -279,6 +309,7 @@ impl Default for WindowsSettings {
timestamp_url: None,
tsp: false,
wix: None,
nsis: None,
icon_path: PathBuf::from("icons/icon.ico"),
webview_install_mode: Default::default(),
webview_fixed_runtime_path: None,
Expand Down Expand Up @@ -565,7 +596,7 @@ impl Settings {
"macos" => vec![PackageType::MacOsBundle, PackageType::Dmg],
"ios" => vec![PackageType::IosBundle],
"linux" => vec![PackageType::Deb, PackageType::AppImage],
"windows" => vec![PackageType::WindowsMsi],
"windows" => vec![PackageType::WindowsMsi, PackageType::Nsis],
os => {
return Err(crate::Error::GenericError(format!(
"Native {} bundles not yet supported.",
Expand Down
2 changes: 2 additions & 0 deletions tooling/bundler/src/bundle/windows/mod.rs
Expand Up @@ -3,4 +3,6 @@
// SPDX-License-Identifier: MIT

pub mod msi;
pub mod nsis;
pub mod sign;
mod util;
112 changes: 9 additions & 103 deletions tooling/bundler/src/bundle/windows/msi/wix.rs
Expand Up @@ -2,38 +2,36 @@
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT

use super::super::sign::{sign, SignParams};
use crate::bundle::{
common::CommandExt,
path_utils::{copy_file, FileOpts},
settings::Settings,
windows::util::{
download, download_and_verify, extract_zip, try_sign, validate_version,
WEBVIEW2_BOOTSTRAPPER_URL, WEBVIEW2_X64_INSTALLER_GUID, WEBVIEW2_X86_INSTALLER_GUID,
},
};
use anyhow::{bail, Context};
use anyhow::Context;
use handlebars::{to_json, Handlebars};
use log::info;
use regex::Regex;
use serde::{Deserialize, Serialize};
use sha2::Digest;
use std::{
collections::{BTreeMap, HashMap},
fs::{create_dir_all, read_to_string, remove_dir_all, rename, write, File},
io::{Cursor, Read, Write},
io::Write,
path::{Path, PathBuf},
process::Command,
};
use tauri_utils::{config::WebviewInstallMode, resources::resource_relpath};
use uuid::Uuid;
use zip::ZipArchive;

// URLS for the WIX toolchain. Can be used for crossplatform compilation.
pub const WIX_URL: &str =
"https://github.com/wixtoolset/wix3/releases/download/wix3112rtm/wix311-binaries.zip";
pub const WIX_SHA256: &str = "2c1888d5d1dba377fc7fa14444cf556963747ff9a0a289a3599cf09da03b9e2e";
pub const MSI_FOLDER_NAME: &str = "msi";
pub const MSI_UPDATER_FOLDER_NAME: &str = "msi-updater";
const WEBVIEW2_BOOTSTRAPPER_URL: &str = "https://go.microsoft.com/fwlink/p/?LinkId=2124703";
const WEBVIEW2_X86_INSTALLER_GUID: &str = "a17bde80-b5ab-47b5-8bbb-1cbe93fc6ec9";
const WEBVIEW2_X64_INSTALLER_GUID: &str = "aa5fd9b3-dc11-4cbc-8343-a50f57b311e1";

// For Cross Platform Compilation.

Expand Down Expand Up @@ -173,30 +171,6 @@ fn copy_icon(settings: &Settings, filename: &str, path: &Path) -> crate::Result<
Ok(icon_target_path)
}

fn download(url: &str) -> crate::Result<Vec<u8>> {
info!(action = "Downloading"; "{}", url);
let response = attohttpc::get(url).send()?;
response.bytes().map_err(Into::into)
}

/// Function used to download Wix. Checks SHA256 to verify the download.
fn download_and_verify(url: &str, hash: &str) -> crate::Result<Vec<u8>> {
let data = download(url)?;
info!("validating hash");

let mut hasher = sha2::Sha256::new();
hasher.update(&data);

let url_hash = hasher.finalize().to_vec();
let expected_hash = hex::decode(hash)?;

if expected_hash == url_hash {
Ok(data)
} else {
Err(crate::Error::HashError)
}
}

/// The app installer output path.
fn app_installer_output_path(
settings: &Settings,
Expand Down Expand Up @@ -233,31 +207,6 @@ fn app_installer_output_path(
)))
}

/// Extracts the zips from Wix and VC_REDIST into a useable path.
fn extract_zip(data: &[u8], path: &Path) -> crate::Result<()> {
let cursor = Cursor::new(data);

let mut zipa = ZipArchive::new(cursor)?;

for i in 0..zipa.len() {
let mut file = zipa.by_index(i)?;
let dest_path = path.join(file.name());
let parent = dest_path.parent().expect("Failed to get parent");

if !parent.exists() {
create_dir_all(parent)?;
}

let mut buff: Vec<u8> = Vec::new();
file.read_to_end(&mut buff)?;
let mut fileout = File::create(dest_path).expect("Failed to open file");

fileout.write_all(&buff)?;
}

Ok(())
}

/// Generates the UUID for the Wix template.
fn generate_package_guid(settings: &Settings) -> Uuid {
generate_guid(settings.bundle_identifier().as_bytes())
Expand All @@ -273,7 +222,7 @@ fn generate_guid(key: &[u8]) -> Uuid {
pub fn get_and_extract_wix(path: &Path) -> crate::Result<()> {
info!("Verifying wix package");

let data = download_and_verify(WIX_URL, WIX_SHA256)?;
let data = download_and_verify(WIX_URL, WIX_SHA256, "sha256")?;

info!("extracting WIX");

Expand Down Expand Up @@ -361,24 +310,6 @@ fn run_light(
// Ok(())
// }

fn validate_version(version: &str) -> anyhow::Result<()> {
let version = semver::Version::parse(version).context("invalid app version")?;
if version.major > 255 {
bail!("app version major number cannot be greater than 255");
}
if version.minor > 255 {
bail!("app version minor number cannot be greater than 255");
}
if version.patch > 65535 {
bail!("app version patch number cannot be greater than 65535");
}
if !(version.pre.is_empty() && version.build.is_empty()) {
bail!("app version cannot have build metadata or pre-release identifier");
}

Ok(())
}

// Entry point for bundling and creating the MSI installer. For now the only supported platform is Windows x64.
pub fn build_wix_app_installer(
settings: &Settings,
Expand Down Expand Up @@ -407,33 +338,8 @@ pub fn build_wix_app_installer(
.find(|bin| bin.main())
.ok_or_else(|| anyhow::anyhow!("Failed to get main binary"))?;
let app_exe_source = settings.binary_path(main_binary);
let try_sign = |file_path: &PathBuf| -> crate::Result<()> {
if let Some(certificate_thumbprint) = &settings.windows().certificate_thumbprint {
info!(action = "Signing"; "{}", file_path.display());
sign(
&file_path,
&SignParams {
product_name: settings.product_name().into(),
digest_algorithm: settings
.windows()
.digest_algorithm
.as_ref()
.map(|algorithm| algorithm.to_string())
.unwrap_or_else(|| "sha256".to_string()),
certificate_thumbprint: certificate_thumbprint.to_string(),
timestamp_url: settings
.windows()
.timestamp_url
.as_ref()
.map(|url| url.to_string()),
tsp: settings.windows().tsp,
},
)?;
}
Ok(())
};

try_sign(&app_exe_source)?;
try_sign(&app_exe_source, &settings)?;

let output_path = settings.project_out_directory().join("wix").join(arch);

Expand Down Expand Up @@ -816,7 +722,7 @@ pub fn build_wix_app_installer(

run_light(wix_toolset_path, &output_path, arguments, &msi_output_path)?;
rename(&msi_output_path, &msi_path)?;
try_sign(&msi_path)?;
try_sign(&msi_path, &settings)?;
output_paths.push(msi_path);
}

Expand Down

0 comments on commit 5dc506c

Please sign in to comment.