context.rs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525
  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. let out_dir = {
  159. let out_dir = std::env::var("OUT_DIR")
  160. .map_err(|_| EmbeddedAssetsError::OutDir)
  161. .map(PathBuf::from)
  162. .and_then(|p| p.canonicalize().map_err(|_| EmbeddedAssetsError::OutDir))?;
  163. // make sure that our output directory is created
  164. std::fs::create_dir_all(&out_dir).map_err(|_| EmbeddedAssetsError::OutDir)?;
  165. out_dir
  166. };
  167. // handle default window icons for Windows targets
  168. #[cfg(windows)]
  169. let default_window_icon = {
  170. let mut icon_path = find_icon(
  171. &config,
  172. &config_parent,
  173. |i| i.ends_with(".ico"),
  174. "icons/icon.ico",
  175. );
  176. if !icon_path.exists() {
  177. icon_path = find_icon(
  178. &config,
  179. &config_parent,
  180. |i| i.ends_with(".png"),
  181. "icons/icon.png",
  182. );
  183. }
  184. ico_icon(&root, &out_dir, icon_path)?
  185. };
  186. #[cfg(target_os = "linux")]
  187. let default_window_icon = {
  188. let icon_path = find_icon(
  189. &config,
  190. &config_parent,
  191. |i| i.ends_with(".png"),
  192. "icons/icon.png",
  193. );
  194. png_icon(&root, &out_dir, icon_path)?
  195. };
  196. #[cfg(not(any(windows, target_os = "linux")))]
  197. let default_window_icon = quote!(None);
  198. let package_name = if let Some(product_name) = &config.package.product_name {
  199. quote!(#product_name.to_string())
  200. } else {
  201. quote!(env!("CARGO_PKG_NAME").to_string())
  202. };
  203. let package_version = if let Some(version) = &config.package.version {
  204. semver::Version::from_str(version)?;
  205. quote!(#version.to_string())
  206. } else {
  207. quote!(env!("CARGO_PKG_VERSION").to_string())
  208. };
  209. let package_info = quote!(
  210. #root::PackageInfo {
  211. name: #package_name,
  212. version: #package_version.parse().unwrap(),
  213. authors: env!("CARGO_PKG_AUTHORS"),
  214. description: env!("CARGO_PKG_DESCRIPTION"),
  215. }
  216. );
  217. let system_tray_icon = if let Some(tray) = &config.tauri.system_tray {
  218. let system_tray_icon_path = config_parent.join(&tray.icon_path);
  219. let ext = system_tray_icon_path.extension();
  220. if ext.map_or(false, |e| e == "ico") {
  221. ico_icon(&root, &out_dir, system_tray_icon_path)?
  222. } else if ext.map_or(false, |e| e == "png") {
  223. png_icon(&root, &out_dir, system_tray_icon_path)?
  224. } else {
  225. quote!(compile_error!(
  226. "The tray icon extension must be either `.ico` or `.png`."
  227. ))
  228. }
  229. } else {
  230. quote!(None)
  231. };
  232. #[cfg(target_os = "macos")]
  233. let info_plist = {
  234. if dev {
  235. let info_plist_path = config_parent.join("Info.plist");
  236. if info_plist_path.exists() {
  237. let info_plist_path = info_plist_path.display().to_string();
  238. quote!({
  239. tauri::embed_plist::embed_info_plist!(#info_plist_path);
  240. })
  241. } else {
  242. quote!(())
  243. }
  244. } else {
  245. quote!(())
  246. }
  247. };
  248. #[cfg(not(target_os = "macos"))]
  249. let info_plist = quote!(());
  250. let pattern = match &options.pattern {
  251. PatternKind::Brownfield => quote!(#root::Pattern::Brownfield(std::marker::PhantomData)),
  252. #[cfg(feature = "isolation")]
  253. PatternKind::Isolation { dir } => {
  254. let dir = config_parent.join(dir);
  255. if !dir.exists() {
  256. panic!(
  257. "The isolation dir configuration is set to `{:?}` but this path doesn't exist",
  258. dir
  259. )
  260. }
  261. let key = uuid::Uuid::new_v4().to_string();
  262. let assets = EmbeddedAssets::new(dir.clone(), &options, map_isolation(&options, dir))?;
  263. let schema = options.isolation_schema;
  264. quote!(#root::Pattern::Isolation {
  265. assets: ::std::sync::Arc::new(#assets),
  266. schema: #schema.into(),
  267. key: #key.into(),
  268. crypto_keys: std::boxed::Box::new(::tauri::utils::pattern::isolation::Keys::new().expect("unable to generate cryptographically secure keys for Tauri \"Isolation\" Pattern")),
  269. })
  270. }
  271. };
  272. #[cfg(feature = "shell-scope")]
  273. let shell_scope_config = {
  274. use regex::Regex;
  275. use tauri_utils::config::ShellAllowlistOpen;
  276. let shell_scopes = get_allowed_clis(&root, &config.tauri.allowlist.shell.scope);
  277. let shell_scope_open = match &config.tauri.allowlist.shell.open {
  278. ShellAllowlistOpen::Flag(false) => quote!(::std::option::Option::None),
  279. ShellAllowlistOpen::Flag(true) => {
  280. quote!(::std::option::Option::Some(#root::regex::Regex::new("^https?://").unwrap()))
  281. }
  282. ShellAllowlistOpen::Validate(regex) => match Regex::new(regex) {
  283. Ok(_) => quote!(::std::option::Option::Some(#root::regex::Regex::new(#regex).unwrap())),
  284. Err(error) => {
  285. let error = error.to_string();
  286. quote!({
  287. compile_error!(#error);
  288. ::std::option::Option::Some(#root::regex::Regex::new(#regex).unwrap())
  289. })
  290. }
  291. },
  292. _ => panic!("unknown shell open format, unable to prepare"),
  293. };
  294. quote!(#root::ShellScopeConfig {
  295. open: #shell_scope_open,
  296. scopes: #shell_scopes
  297. })
  298. };
  299. #[cfg(not(feature = "shell-scope"))]
  300. let shell_scope_config = quote!();
  301. Ok(quote!(#root::Context::new(
  302. #config,
  303. ::std::sync::Arc::new(#assets),
  304. #default_window_icon,
  305. #system_tray_icon,
  306. #package_info,
  307. #info_plist,
  308. #pattern,
  309. #shell_scope_config
  310. )))
  311. }
  312. fn ico_icon<P: AsRef<Path>>(
  313. root: &TokenStream,
  314. out_dir: &Path,
  315. path: P,
  316. ) -> Result<TokenStream, EmbeddedAssetsError> {
  317. use std::fs::File;
  318. use std::io::Write;
  319. let path = path.as_ref();
  320. let bytes = std::fs::read(&path)
  321. .unwrap_or_else(|_| panic!("failed to read icon {}", path.display()))
  322. .to_vec();
  323. let icon_dir = ico::IconDir::read(std::io::Cursor::new(bytes))
  324. .unwrap_or_else(|_| panic!("failed to parse icon {}", path.display()));
  325. let entry = &icon_dir.entries()[0];
  326. let rgba = entry
  327. .decode()
  328. .unwrap_or_else(|_| panic!("failed to decode icon {}", path.display()))
  329. .rgba_data()
  330. .to_vec();
  331. let width = entry.width();
  332. let height = entry.height();
  333. let out_path = out_dir.join(path.file_name().unwrap());
  334. let mut out_file = File::create(&out_path).map_err(|error| EmbeddedAssetsError::AssetWrite {
  335. path: out_path.clone(),
  336. error,
  337. })?;
  338. out_file
  339. .write_all(&rgba)
  340. .map_err(|error| EmbeddedAssetsError::AssetWrite {
  341. path: path.to_owned(),
  342. error,
  343. })?;
  344. let out_path = out_path.display().to_string();
  345. let icon = quote!(Some(#root::Icon::Rgba { rgba: include_bytes!(#out_path).to_vec(), width: #width, height: #height }));
  346. Ok(icon)
  347. }
  348. fn png_icon<P: AsRef<Path>>(
  349. root: &TokenStream,
  350. out_dir: &Path,
  351. path: P,
  352. ) -> Result<TokenStream, EmbeddedAssetsError> {
  353. use std::fs::File;
  354. use std::io::Write;
  355. let path = path.as_ref();
  356. let bytes = std::fs::read(&path)
  357. .unwrap_or_else(|_| panic!("failed to read icon {}", path.display()))
  358. .to_vec();
  359. let decoder = png::Decoder::new(std::io::Cursor::new(bytes));
  360. let mut reader = decoder
  361. .read_info()
  362. .unwrap_or_else(|_| panic!("failed to read icon {}", path.display()));
  363. let mut buffer: Vec<u8> = Vec::new();
  364. while let Ok(Some(row)) = reader.next_row() {
  365. buffer.extend(row.data());
  366. }
  367. let width = reader.info().width;
  368. let height = reader.info().height;
  369. let out_path = out_dir.join(path.file_name().unwrap());
  370. let mut out_file = File::create(&out_path).map_err(|error| EmbeddedAssetsError::AssetWrite {
  371. path: out_path.clone(),
  372. error,
  373. })?;
  374. out_file
  375. .write_all(&buffer)
  376. .map_err(|error| EmbeddedAssetsError::AssetWrite {
  377. path: path.to_owned(),
  378. error,
  379. })?;
  380. let out_path = out_path.display().to_string();
  381. let icon = quote!(Some(#root::Icon::Rgba { rgba: include_bytes!(#out_path).to_vec(), width: #width, height: #height }));
  382. Ok(icon)
  383. }
  384. #[cfg(any(windows, target_os = "linux"))]
  385. fn find_icon<F: Fn(&&String) -> bool>(
  386. config: &Config,
  387. config_parent: &Path,
  388. predicate: F,
  389. default: &str,
  390. ) -> PathBuf {
  391. let icon_path = config
  392. .tauri
  393. .bundle
  394. .icon
  395. .iter()
  396. .find(|i| predicate(i))
  397. .cloned()
  398. .unwrap_or_else(|| default.to_string());
  399. config_parent.join(icon_path)
  400. }
  401. #[cfg(feature = "shell-scope")]
  402. fn get_allowed_clis(root: &TokenStream, scope: &ShellAllowlistScope) -> TokenStream {
  403. let commands = scope
  404. .0
  405. .iter()
  406. .map(|scope| {
  407. let sidecar = &scope.sidecar;
  408. let name = &scope.name;
  409. let name = quote!(#name.into());
  410. let command = scope.command.to_string_lossy();
  411. let command = quote!(::std::path::PathBuf::from(#command));
  412. let args = match &scope.args {
  413. ShellAllowedArgs::Flag(true) => quote!(::std::option::Option::None),
  414. ShellAllowedArgs::Flag(false) => quote!(::std::option::Option::Some(::std::vec![])),
  415. ShellAllowedArgs::List(list) => {
  416. let list = list.iter().map(|arg| match arg {
  417. ShellAllowedArg::Fixed(fixed) => {
  418. quote!(#root::scope::ShellScopeAllowedArg::Fixed(#fixed.into()))
  419. }
  420. ShellAllowedArg::Var { validator } => {
  421. let validator = match regex::Regex::new(validator) {
  422. Ok(regex) => {
  423. let regex = regex.as_str();
  424. quote!(#root::regex::Regex::new(#regex).unwrap())
  425. }
  426. Err(error) => {
  427. let error = error.to_string();
  428. quote!({
  429. compile_error!(#error);
  430. #root::regex::Regex::new(#validator).unwrap()
  431. })
  432. }
  433. };
  434. quote!(#root::scope::ShellScopeAllowedArg::Var { validator: #validator })
  435. }
  436. _ => panic!("unknown shell scope arg, unable to prepare"),
  437. });
  438. quote!(::std::option::Option::Some(::std::vec![#(#list),*]))
  439. }
  440. _ => panic!("unknown shell scope command, unable to prepare"),
  441. };
  442. (
  443. quote!(#name),
  444. quote!(
  445. #root::scope::ShellScopeAllowedCommand {
  446. command: #command,
  447. args: #args,
  448. sidecar: #sidecar,
  449. }
  450. ),
  451. )
  452. })
  453. .collect::<Vec<_>>();
  454. if commands.is_empty() {
  455. quote!(::std::collections::HashMap::new())
  456. } else {
  457. let insertions = commands
  458. .iter()
  459. .map(|(name, value)| quote!(hashmap.insert(#name, #value);));
  460. quote!({
  461. let mut hashmap = ::std::collections::HashMap::new();
  462. #(#insertions)*
  463. hashmap
  464. })
  465. }
  466. }