context.rs 17 KB

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