context.rs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641
  1. // Copyright 2019-2022 Tauri Programme within The Commons Conservancy
  2. // SPDX-License-Identifier: Apache-2.0
  3. // SPDX-License-Identifier: MIT
  4. use std::path::{Path, PathBuf};
  5. use std::{ffi::OsStr, str::FromStr};
  6. use proc_macro2::TokenStream;
  7. use quote::quote;
  8. use sha2::{Digest, Sha256};
  9. use tauri_utils::assets::AssetKey;
  10. use tauri_utils::config::{AppUrl, Config, PatternKind, WindowUrl};
  11. use tauri_utils::html::{
  12. inject_nonce_token, parse as parse_html, serialize_node as serialize_html_node,
  13. };
  14. #[cfg(feature = "shell-scope")]
  15. use tauri_utils::config::{ShellAllowedArg, ShellAllowedArgs, ShellAllowlistScope};
  16. use crate::embedded_assets::{AssetOptions, CspHashes, EmbeddedAssets, EmbeddedAssetsError};
  17. /// Necessary data needed by [`context_codegen`] to generate code for a Tauri application context.
  18. pub struct ContextData {
  19. pub dev: bool,
  20. pub config: Config,
  21. pub config_parent: PathBuf,
  22. pub root: TokenStream,
  23. }
  24. fn map_core_assets(
  25. options: &AssetOptions,
  26. target: Target,
  27. ) -> impl Fn(&AssetKey, &Path, &mut Vec<u8>, &mut CspHashes) -> Result<(), EmbeddedAssetsError> {
  28. #[cfg(feature = "isolation")]
  29. let pattern = tauri_utils::html::PatternObject::from(&options.pattern);
  30. let csp = options.csp;
  31. let dangerous_disable_asset_csp_modification =
  32. options.dangerous_disable_asset_csp_modification.clone();
  33. move |key, path, input, csp_hashes| {
  34. if path.extension() == Some(OsStr::new("html")) {
  35. #[allow(clippy::collapsible_if)]
  36. if csp {
  37. let mut document = parse_html(String::from_utf8_lossy(input).into_owned());
  38. if target == Target::Linux {
  39. ::tauri_utils::html::inject_csp_token(&mut document);
  40. }
  41. inject_nonce_token(&mut document, &dangerous_disable_asset_csp_modification);
  42. if dangerous_disable_asset_csp_modification.can_modify("script-src") {
  43. if let Ok(inline_script_elements) = document.select("script:not(empty)") {
  44. let mut scripts = Vec::new();
  45. for inline_script_el in inline_script_elements {
  46. let script = inline_script_el.as_node().text_contents();
  47. let mut hasher = Sha256::new();
  48. hasher.update(&script);
  49. let hash = hasher.finalize();
  50. scripts.push(format!("'sha256-{}'", base64::encode(hash)));
  51. }
  52. csp_hashes
  53. .inline_scripts
  54. .entry(key.clone().into())
  55. .or_default()
  56. .append(&mut scripts);
  57. }
  58. }
  59. #[cfg(feature = "isolation")]
  60. if dangerous_disable_asset_csp_modification.can_modify("style-src") {
  61. if let tauri_utils::html::PatternObject::Isolation { .. } = &pattern {
  62. // create the csp for the isolation iframe styling now, to make the runtime less complex
  63. let mut hasher = Sha256::new();
  64. hasher.update(tauri_utils::pattern::isolation::IFRAME_STYLE);
  65. let hash = hasher.finalize();
  66. csp_hashes
  67. .styles
  68. .push(format!("'sha256-{}'", base64::encode(hash)));
  69. }
  70. }
  71. *input = serialize_html_node(&document);
  72. }
  73. }
  74. Ok(())
  75. }
  76. }
  77. #[cfg(feature = "isolation")]
  78. fn map_isolation(
  79. _options: &AssetOptions,
  80. dir: PathBuf,
  81. ) -> impl Fn(&AssetKey, &Path, &mut Vec<u8>, &mut CspHashes) -> Result<(), EmbeddedAssetsError> {
  82. move |_key, path, input, _csp_hashes| {
  83. if path.extension() == Some(OsStr::new("html")) {
  84. let mut isolation_html =
  85. tauri_utils::html::parse(String::from_utf8_lossy(input).into_owned());
  86. // this is appended, so no need to reverse order it
  87. tauri_utils::html::inject_codegen_isolation_script(&mut isolation_html);
  88. // temporary workaround for windows not loading assets
  89. tauri_utils::html::inline_isolation(&mut isolation_html, &dir);
  90. *input = isolation_html.to_string().as_bytes().to_vec()
  91. }
  92. Ok(())
  93. }
  94. }
  95. #[derive(PartialEq, Eq, Clone, Copy)]
  96. enum Target {
  97. Linux,
  98. Windows,
  99. Darwin,
  100. Android,
  101. // iOS.
  102. Ios,
  103. }
  104. /// Build a `tauri::Context` for including in application code.
  105. pub fn context_codegen(data: ContextData) -> Result<TokenStream, EmbeddedAssetsError> {
  106. let ContextData {
  107. dev,
  108. config,
  109. config_parent,
  110. root,
  111. } = data;
  112. let target =
  113. if let Ok(target) = std::env::var("TARGET").or_else(|_| std::env::var("TAURI_TARGET_TRIPLE")) {
  114. if target.contains("unknown-linux") {
  115. Target::Linux
  116. } else if target.contains("pc-windows") {
  117. Target::Windows
  118. } else if target.contains("apple-darwin") {
  119. Target::Darwin
  120. } else if target.contains("android") {
  121. Target::Android
  122. } else if target.contains("apple-ios") {
  123. Target::Ios
  124. } else {
  125. panic!("unknown codegen target {}", target);
  126. }
  127. } else if cfg!(target_os = "linux") {
  128. Target::Linux
  129. } else if cfg!(windows) {
  130. Target::Windows
  131. } else if cfg!(target_os = "macos") {
  132. Target::Darwin
  133. } else if cfg!(target_os = "android") {
  134. Target::Android
  135. } else if cfg!(target_os = "ios") {
  136. Target::Ios
  137. } else {
  138. panic!("unknown codegen target")
  139. };
  140. let mut options = AssetOptions::new(config.tauri.pattern.clone())
  141. .freeze_prototype(config.tauri.security.freeze_prototype)
  142. .dangerous_disable_asset_csp_modification(
  143. config
  144. .tauri
  145. .security
  146. .dangerous_disable_asset_csp_modification
  147. .clone(),
  148. );
  149. let csp = if dev {
  150. config
  151. .tauri
  152. .security
  153. .dev_csp
  154. .clone()
  155. .or_else(|| config.tauri.security.csp.clone())
  156. } else {
  157. config.tauri.security.csp.clone()
  158. };
  159. if csp.is_some() {
  160. options = options.with_csp();
  161. }
  162. let app_url = if dev {
  163. &config.build.dev_path
  164. } else {
  165. &config.build.dist_dir
  166. };
  167. let assets = match app_url {
  168. AppUrl::Url(url) => match url {
  169. WindowUrl::External(_) => Default::default(),
  170. WindowUrl::App(path) => {
  171. if path.components().count() == 0 {
  172. panic!(
  173. "The `{}` configuration cannot be empty",
  174. if dev { "devPath" } else { "distDir" }
  175. )
  176. }
  177. let assets_path = config_parent.join(path);
  178. if !assets_path.exists() {
  179. panic!(
  180. "The `{}` configuration is set to `{:?}` but this path doesn't exist",
  181. if dev { "devPath" } else { "distDir" },
  182. path
  183. )
  184. }
  185. EmbeddedAssets::new(assets_path, &options, map_core_assets(&options, target))?
  186. }
  187. _ => unimplemented!(),
  188. },
  189. AppUrl::Files(files) => EmbeddedAssets::new(
  190. files
  191. .iter()
  192. .map(|p| config_parent.join(p))
  193. .collect::<Vec<_>>(),
  194. &options,
  195. map_core_assets(&options, target),
  196. )?,
  197. _ => unimplemented!(),
  198. };
  199. let out_dir = {
  200. let out_dir = std::env::var("OUT_DIR")
  201. .map_err(|_| EmbeddedAssetsError::OutDir)
  202. .map(PathBuf::from)
  203. .and_then(|p| p.canonicalize().map_err(|_| EmbeddedAssetsError::OutDir))?;
  204. // make sure that our output directory is created
  205. std::fs::create_dir_all(&out_dir).map_err(|_| EmbeddedAssetsError::OutDir)?;
  206. out_dir
  207. };
  208. let default_window_icon = {
  209. if target == Target::Windows {
  210. // handle default window icons for Windows targets
  211. let icon_path = find_icon(
  212. &config,
  213. &config_parent,
  214. |i| i.ends_with(".ico"),
  215. "icons/icon.ico",
  216. );
  217. if icon_path.exists() {
  218. ico_icon(&root, &out_dir, icon_path)?
  219. } else {
  220. let icon_path = find_icon(
  221. &config,
  222. &config_parent,
  223. |i| i.ends_with(".png"),
  224. "icons/icon.png",
  225. );
  226. png_icon(&root, &out_dir, icon_path)?
  227. }
  228. } else if target == Target::Linux {
  229. // handle default window icons for Linux targets
  230. let icon_path = find_icon(
  231. &config,
  232. &config_parent,
  233. |i| i.ends_with(".png"),
  234. "icons/icon.png",
  235. );
  236. png_icon(&root, &out_dir, icon_path)?
  237. } else {
  238. quote!(None)
  239. }
  240. };
  241. let app_icon = if target == Target::Darwin && dev {
  242. let mut icon_path = find_icon(
  243. &config,
  244. &config_parent,
  245. |i| i.ends_with(".icns"),
  246. "icons/icon.png",
  247. );
  248. if !icon_path.exists() {
  249. icon_path = find_icon(
  250. &config,
  251. &config_parent,
  252. |i| i.ends_with(".png"),
  253. "icons/icon.png",
  254. );
  255. }
  256. raw_icon(&out_dir, icon_path)?
  257. } else {
  258. quote!(None)
  259. };
  260. let package_name = if let Some(product_name) = &config.package.product_name {
  261. quote!(#product_name.to_string())
  262. } else {
  263. quote!(env!("CARGO_PKG_NAME").to_string())
  264. };
  265. let package_version = if let Some(version) = &config.package.version {
  266. semver::Version::from_str(version)?;
  267. quote!(#version.to_string())
  268. } else {
  269. quote!(env!("CARGO_PKG_VERSION").to_string())
  270. };
  271. let package_info = quote!(
  272. #root::PackageInfo {
  273. name: #package_name,
  274. version: #package_version.parse().unwrap(),
  275. authors: env!("CARGO_PKG_AUTHORS"),
  276. description: env!("CARGO_PKG_DESCRIPTION"),
  277. }
  278. );
  279. let system_tray_icon = if let Some(tray) = &config.tauri.system_tray {
  280. let system_tray_icon_path = config_parent.join(&tray.icon_path);
  281. let ext = system_tray_icon_path.extension();
  282. if ext.map_or(false, |e| e == "ico") {
  283. ico_icon(&root, &out_dir, system_tray_icon_path)?
  284. } else if ext.map_or(false, |e| e == "png") {
  285. png_icon(&root, &out_dir, system_tray_icon_path)?
  286. } else {
  287. quote!(compile_error!(
  288. "The tray icon extension must be either `.ico` or `.png`."
  289. ))
  290. }
  291. } else {
  292. quote!(None)
  293. };
  294. #[cfg(target_os = "macos")]
  295. let info_plist = if target == Target::Darwin && dev {
  296. let info_plist_path = config_parent.join("Info.plist");
  297. let mut info_plist = if info_plist_path.exists() {
  298. plist::Value::from_file(&info_plist_path)
  299. .unwrap_or_else(|e| panic!("failed to read plist {}: {}", info_plist_path.display(), e))
  300. } else {
  301. plist::Value::Dictionary(Default::default())
  302. };
  303. if let Some(plist) = info_plist.as_dictionary_mut() {
  304. if let Some(product_name) = &config.package.product_name {
  305. plist.insert("CFBundleName".into(), product_name.clone().into());
  306. }
  307. if let Some(version) = &config.package.version {
  308. plist.insert("CFBundleShortVersionString".into(), version.clone().into());
  309. }
  310. let format =
  311. time::format_description::parse("[year][month][day].[hour][minute][second]").unwrap();
  312. if let Ok(build_number) = time::OffsetDateTime::now_utc().format(&format) {
  313. plist.insert("CFBundleVersion".into(), build_number.into());
  314. }
  315. }
  316. let out_path = out_dir.join("Info.plist");
  317. info_plist
  318. .to_file_xml(&out_path)
  319. .expect("failed to write Info.plist");
  320. let info_plist_path = out_path.display().to_string();
  321. quote!({
  322. tauri::embed_plist::embed_info_plist!(#info_plist_path);
  323. })
  324. } else {
  325. quote!(())
  326. };
  327. #[cfg(not(target_os = "macos"))]
  328. let info_plist = quote!(());
  329. let pattern = match &options.pattern {
  330. PatternKind::Brownfield => quote!(#root::Pattern::Brownfield(std::marker::PhantomData)),
  331. #[cfg(not(feature = "isolation"))]
  332. PatternKind::Isolation { dir: _ } => {
  333. quote!(#root::Pattern::Brownfield(std::marker::PhantomData))
  334. }
  335. #[cfg(feature = "isolation")]
  336. PatternKind::Isolation { dir } => {
  337. let dir = config_parent.join(dir);
  338. if !dir.exists() {
  339. panic!(
  340. "The isolation application path is set to `{:?}` but it does not exist",
  341. dir
  342. )
  343. }
  344. let mut sets_isolation_hook = false;
  345. let key = uuid::Uuid::new_v4().to_string();
  346. let map_isolation = map_isolation(&options, dir.clone());
  347. let assets = EmbeddedAssets::new(dir, &options, |key, path, input, csp_hashes| {
  348. // we check if `__TAURI_ISOLATION_HOOK__` exists in the isolation code
  349. // before modifying the files since we inject our own `__TAURI_ISOLATION_HOOK__` reference in HTML files
  350. if String::from_utf8_lossy(input).contains("__TAURI_ISOLATION_HOOK__") {
  351. sets_isolation_hook = true;
  352. }
  353. map_isolation(key, path, input, csp_hashes)
  354. })?;
  355. if !sets_isolation_hook {
  356. panic!("The isolation application does not contain a file setting the `window.__TAURI_ISOLATION_HOOK__` value.");
  357. }
  358. let schema = options.isolation_schema;
  359. quote!(#root::Pattern::Isolation {
  360. assets: ::std::sync::Arc::new(#assets),
  361. schema: #schema.into(),
  362. key: #key.into(),
  363. crypto_keys: std::boxed::Box::new(::tauri::utils::pattern::isolation::Keys::new().expect("unable to generate cryptographically secure keys for Tauri \"Isolation\" Pattern")),
  364. })
  365. }
  366. };
  367. #[cfg(feature = "shell-scope")]
  368. let shell_scope_config = {
  369. use regex::Regex;
  370. use tauri_utils::config::ShellAllowlistOpen;
  371. let shell_scopes = get_allowed_clis(&root, &config.tauri.allowlist.shell.scope);
  372. let shell_scope_open = match &config.tauri.allowlist.shell.open {
  373. ShellAllowlistOpen::Flag(false) => quote!(::std::option::Option::None),
  374. ShellAllowlistOpen::Flag(true) => {
  375. quote!(::std::option::Option::Some(#root::regex::Regex::new("^https?://").unwrap()))
  376. }
  377. ShellAllowlistOpen::Validate(regex) => match Regex::new(regex) {
  378. Ok(_) => quote!(::std::option::Option::Some(#root::regex::Regex::new(#regex).unwrap())),
  379. Err(error) => {
  380. let error = error.to_string();
  381. quote!({
  382. compile_error!(#error);
  383. ::std::option::Option::Some(#root::regex::Regex::new(#regex).unwrap())
  384. })
  385. }
  386. },
  387. _ => panic!("unknown shell open format, unable to prepare"),
  388. };
  389. quote!(#root::ShellScopeConfig {
  390. open: #shell_scope_open,
  391. scopes: #shell_scopes
  392. })
  393. };
  394. #[cfg(not(feature = "shell-scope"))]
  395. let shell_scope_config = quote!();
  396. Ok(quote!(#root::Context::new(
  397. #config,
  398. ::std::sync::Arc::new(#assets),
  399. #default_window_icon,
  400. #app_icon,
  401. #system_tray_icon,
  402. #package_info,
  403. #info_plist,
  404. #pattern,
  405. #shell_scope_config
  406. )))
  407. }
  408. fn ico_icon<P: AsRef<Path>>(
  409. root: &TokenStream,
  410. out_dir: &Path,
  411. path: P,
  412. ) -> Result<TokenStream, EmbeddedAssetsError> {
  413. let path = path.as_ref();
  414. let bytes = std::fs::read(path)
  415. .unwrap_or_else(|e| panic!("failed to read icon {}: {}", path.display(), e))
  416. .to_vec();
  417. let icon_dir = ico::IconDir::read(std::io::Cursor::new(bytes))
  418. .unwrap_or_else(|e| panic!("failed to parse icon {}: {}", path.display(), e));
  419. let entry = &icon_dir.entries()[0];
  420. let rgba = entry
  421. .decode()
  422. .unwrap_or_else(|e| panic!("failed to decode icon {}: {}", path.display(), e))
  423. .rgba_data()
  424. .to_vec();
  425. let width = entry.width();
  426. let height = entry.height();
  427. let out_path = out_dir.join(path.file_name().unwrap());
  428. write_if_changed(&out_path, &rgba).map_err(|error| EmbeddedAssetsError::AssetWrite {
  429. path: path.to_owned(),
  430. error,
  431. })?;
  432. let out_path = out_path.display().to_string();
  433. let icon = quote!(Some(#root::Icon::Rgba { rgba: include_bytes!(#out_path).to_vec(), width: #width, height: #height }));
  434. Ok(icon)
  435. }
  436. fn raw_icon<P: AsRef<Path>>(out_dir: &Path, path: P) -> Result<TokenStream, EmbeddedAssetsError> {
  437. let path = path.as_ref();
  438. let bytes = std::fs::read(path)
  439. .unwrap_or_else(|e| panic!("failed to read icon {}: {}", path.display(), e))
  440. .to_vec();
  441. let out_path = out_dir.join(path.file_name().unwrap());
  442. write_if_changed(&out_path, &bytes).map_err(|error| EmbeddedAssetsError::AssetWrite {
  443. path: path.to_owned(),
  444. error,
  445. })?;
  446. let out_path = out_path.display().to_string();
  447. let icon = quote!(Some(include_bytes!(#out_path).to_vec()));
  448. Ok(icon)
  449. }
  450. fn png_icon<P: AsRef<Path>>(
  451. root: &TokenStream,
  452. out_dir: &Path,
  453. path: P,
  454. ) -> Result<TokenStream, EmbeddedAssetsError> {
  455. let path = path.as_ref();
  456. let bytes = std::fs::read(path)
  457. .unwrap_or_else(|e| panic!("failed to read icon {}: {}", path.display(), e))
  458. .to_vec();
  459. let decoder = png::Decoder::new(std::io::Cursor::new(bytes));
  460. let mut reader = decoder
  461. .read_info()
  462. .unwrap_or_else(|e| panic!("failed to read icon {}: {}", path.display(), e));
  463. let mut buffer: Vec<u8> = Vec::new();
  464. while let Ok(Some(row)) = reader.next_row() {
  465. buffer.extend(row.data());
  466. }
  467. let width = reader.info().width;
  468. let height = reader.info().height;
  469. let out_path = out_dir.join(path.file_name().unwrap());
  470. write_if_changed(&out_path, &buffer).map_err(|error| EmbeddedAssetsError::AssetWrite {
  471. path: path.to_owned(),
  472. error,
  473. })?;
  474. let out_path = out_path.display().to_string();
  475. let icon = quote!(Some(#root::Icon::Rgba { rgba: include_bytes!(#out_path).to_vec(), width: #width, height: #height }));
  476. Ok(icon)
  477. }
  478. fn write_if_changed(out_path: &Path, data: &[u8]) -> std::io::Result<()> {
  479. use std::fs::File;
  480. use std::io::Write;
  481. if let Ok(curr) = std::fs::read(out_path) {
  482. if curr == data {
  483. return Ok(());
  484. }
  485. }
  486. let mut out_file = File::create(out_path)?;
  487. out_file.write_all(data)
  488. }
  489. fn find_icon<F: Fn(&&String) -> bool>(
  490. config: &Config,
  491. config_parent: &Path,
  492. predicate: F,
  493. default: &str,
  494. ) -> PathBuf {
  495. let icon_path = config
  496. .tauri
  497. .bundle
  498. .icon
  499. .iter()
  500. .find(|i| predicate(i))
  501. .cloned()
  502. .unwrap_or_else(|| default.to_string());
  503. config_parent.join(icon_path)
  504. }
  505. #[cfg(feature = "shell-scope")]
  506. fn get_allowed_clis(root: &TokenStream, scope: &ShellAllowlistScope) -> TokenStream {
  507. let commands = scope
  508. .0
  509. .iter()
  510. .map(|scope| {
  511. let sidecar = &scope.sidecar;
  512. let name = &scope.name;
  513. let name = quote!(#name.into());
  514. let command = scope.command.to_string_lossy();
  515. let command = quote!(::std::path::PathBuf::from(#command));
  516. let args = match &scope.args {
  517. ShellAllowedArgs::Flag(true) => quote!(::std::option::Option::None),
  518. ShellAllowedArgs::Flag(false) => quote!(::std::option::Option::Some(::std::vec![])),
  519. ShellAllowedArgs::List(list) => {
  520. let list = list.iter().map(|arg| match arg {
  521. ShellAllowedArg::Fixed(fixed) => {
  522. quote!(#root::scope::ShellScopeAllowedArg::Fixed(#fixed.into()))
  523. }
  524. ShellAllowedArg::Var { validator } => {
  525. let validator = match regex::Regex::new(validator) {
  526. Ok(regex) => {
  527. let regex = regex.as_str();
  528. quote!(#root::regex::Regex::new(#regex).unwrap())
  529. }
  530. Err(error) => {
  531. let error = error.to_string();
  532. quote!({
  533. compile_error!(#error);
  534. #root::regex::Regex::new(#validator).unwrap()
  535. })
  536. }
  537. };
  538. quote!(#root::scope::ShellScopeAllowedArg::Var { validator: #validator })
  539. }
  540. _ => panic!("unknown shell scope arg, unable to prepare"),
  541. });
  542. quote!(::std::option::Option::Some(::std::vec![#(#list),*]))
  543. }
  544. _ => panic!("unknown shell scope command, unable to prepare"),
  545. };
  546. (
  547. quote!(#name),
  548. quote!(
  549. #root::scope::ShellScopeAllowedCommand {
  550. command: #command,
  551. args: #args,
  552. sidecar: #sidecar,
  553. }
  554. ),
  555. )
  556. })
  557. .collect::<Vec<_>>();
  558. if commands.is_empty() {
  559. quote!(::std::collections::HashMap::new())
  560. } else {
  561. let insertions = commands
  562. .iter()
  563. .map(|(name, value)| quote!(hashmap.insert(#name, #value);));
  564. quote!({
  565. let mut hashmap = ::std::collections::HashMap::new();
  566. #(#insertions)*
  567. hashmap
  568. })
  569. }
  570. }