context.rs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539
  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. let mut info_plist = if info_plist_path.exists() {
  237. plist::Value::from_file(&info_plist_path)
  238. .unwrap_or_else(|e| panic!("failed to read plist {}: {}", info_plist_path.display(), e))
  239. } else {
  240. plist::Value::Dictionary(Default::default())
  241. };
  242. if let Some(dict) = info_plist.as_dictionary_mut() {
  243. if let Some(product_name) = &config.package.product_name {
  244. dict.insert("CFBundleName".into(), product_name.clone().into());
  245. }
  246. }
  247. let out_path = out_dir.join("Info.plist");
  248. info_plist
  249. .to_file_xml(&out_path)
  250. .expect("failed to write Info.plist");
  251. let info_plist_path = out_path.display().to_string();
  252. quote!({
  253. tauri::embed_plist::embed_info_plist!(#info_plist_path);
  254. })
  255. } else {
  256. quote!(())
  257. }
  258. };
  259. #[cfg(not(target_os = "macos"))]
  260. let info_plist = quote!(());
  261. let pattern = match &options.pattern {
  262. PatternKind::Brownfield => quote!(#root::Pattern::Brownfield(std::marker::PhantomData)),
  263. #[cfg(feature = "isolation")]
  264. PatternKind::Isolation { dir } => {
  265. let dir = config_parent.join(dir);
  266. if !dir.exists() {
  267. panic!(
  268. "The isolation dir configuration is set to `{:?}` but this path doesn't exist",
  269. dir
  270. )
  271. }
  272. let key = uuid::Uuid::new_v4().to_string();
  273. let assets = EmbeddedAssets::new(dir.clone(), &options, map_isolation(&options, dir))?;
  274. let schema = options.isolation_schema;
  275. quote!(#root::Pattern::Isolation {
  276. assets: ::std::sync::Arc::new(#assets),
  277. schema: #schema.into(),
  278. key: #key.into(),
  279. crypto_keys: std::boxed::Box::new(::tauri::utils::pattern::isolation::Keys::new().expect("unable to generate cryptographically secure keys for Tauri \"Isolation\" Pattern")),
  280. })
  281. }
  282. };
  283. #[cfg(feature = "shell-scope")]
  284. let shell_scope_config = {
  285. use regex::Regex;
  286. use tauri_utils::config::ShellAllowlistOpen;
  287. let shell_scopes = get_allowed_clis(&root, &config.tauri.allowlist.shell.scope);
  288. let shell_scope_open = match &config.tauri.allowlist.shell.open {
  289. ShellAllowlistOpen::Flag(false) => quote!(::std::option::Option::None),
  290. ShellAllowlistOpen::Flag(true) => {
  291. quote!(::std::option::Option::Some(#root::regex::Regex::new("^https?://").unwrap()))
  292. }
  293. ShellAllowlistOpen::Validate(regex) => match Regex::new(regex) {
  294. Ok(_) => quote!(::std::option::Option::Some(#root::regex::Regex::new(#regex).unwrap())),
  295. Err(error) => {
  296. let error = error.to_string();
  297. quote!({
  298. compile_error!(#error);
  299. ::std::option::Option::Some(#root::regex::Regex::new(#regex).unwrap())
  300. })
  301. }
  302. },
  303. _ => panic!("unknown shell open format, unable to prepare"),
  304. };
  305. quote!(#root::ShellScopeConfig {
  306. open: #shell_scope_open,
  307. scopes: #shell_scopes
  308. })
  309. };
  310. #[cfg(not(feature = "shell-scope"))]
  311. let shell_scope_config = quote!();
  312. Ok(quote!(#root::Context::new(
  313. #config,
  314. ::std::sync::Arc::new(#assets),
  315. #default_window_icon,
  316. #system_tray_icon,
  317. #package_info,
  318. #info_plist,
  319. #pattern,
  320. #shell_scope_config
  321. )))
  322. }
  323. fn ico_icon<P: AsRef<Path>>(
  324. root: &TokenStream,
  325. out_dir: &Path,
  326. path: P,
  327. ) -> Result<TokenStream, EmbeddedAssetsError> {
  328. use std::fs::File;
  329. use std::io::Write;
  330. let path = path.as_ref();
  331. let bytes = std::fs::read(&path)
  332. .unwrap_or_else(|_| panic!("failed to read icon {}", path.display()))
  333. .to_vec();
  334. let icon_dir = ico::IconDir::read(std::io::Cursor::new(bytes))
  335. .unwrap_or_else(|_| panic!("failed to parse icon {}", path.display()));
  336. let entry = &icon_dir.entries()[0];
  337. let rgba = entry
  338. .decode()
  339. .unwrap_or_else(|_| panic!("failed to decode icon {}", path.display()))
  340. .rgba_data()
  341. .to_vec();
  342. let width = entry.width();
  343. let height = entry.height();
  344. let out_path = out_dir.join(path.file_name().unwrap());
  345. let mut out_file = File::create(&out_path).map_err(|error| EmbeddedAssetsError::AssetWrite {
  346. path: out_path.clone(),
  347. error,
  348. })?;
  349. out_file
  350. .write_all(&rgba)
  351. .map_err(|error| EmbeddedAssetsError::AssetWrite {
  352. path: path.to_owned(),
  353. error,
  354. })?;
  355. let out_path = out_path.display().to_string();
  356. let icon = quote!(Some(#root::Icon::Rgba { rgba: include_bytes!(#out_path).to_vec(), width: #width, height: #height }));
  357. Ok(icon)
  358. }
  359. fn png_icon<P: AsRef<Path>>(
  360. root: &TokenStream,
  361. out_dir: &Path,
  362. path: P,
  363. ) -> Result<TokenStream, EmbeddedAssetsError> {
  364. use std::fs::File;
  365. use std::io::Write;
  366. let path = path.as_ref();
  367. let bytes = std::fs::read(&path)
  368. .unwrap_or_else(|_| panic!("failed to read icon {}", path.display()))
  369. .to_vec();
  370. let decoder = png::Decoder::new(std::io::Cursor::new(bytes));
  371. let mut reader = decoder
  372. .read_info()
  373. .unwrap_or_else(|_| panic!("failed to read icon {}", path.display()));
  374. let mut buffer: Vec<u8> = Vec::new();
  375. while let Ok(Some(row)) = reader.next_row() {
  376. buffer.extend(row.data());
  377. }
  378. let width = reader.info().width;
  379. let height = reader.info().height;
  380. let out_path = out_dir.join(path.file_name().unwrap());
  381. let mut out_file = File::create(&out_path).map_err(|error| EmbeddedAssetsError::AssetWrite {
  382. path: out_path.clone(),
  383. error,
  384. })?;
  385. out_file
  386. .write_all(&buffer)
  387. .map_err(|error| EmbeddedAssetsError::AssetWrite {
  388. path: path.to_owned(),
  389. error,
  390. })?;
  391. let out_path = out_path.display().to_string();
  392. let icon = quote!(Some(#root::Icon::Rgba { rgba: include_bytes!(#out_path).to_vec(), width: #width, height: #height }));
  393. Ok(icon)
  394. }
  395. #[cfg(any(windows, target_os = "linux"))]
  396. fn find_icon<F: Fn(&&String) -> bool>(
  397. config: &Config,
  398. config_parent: &Path,
  399. predicate: F,
  400. default: &str,
  401. ) -> PathBuf {
  402. let icon_path = config
  403. .tauri
  404. .bundle
  405. .icon
  406. .iter()
  407. .find(|i| predicate(i))
  408. .cloned()
  409. .unwrap_or_else(|| default.to_string());
  410. config_parent.join(icon_path)
  411. }
  412. #[cfg(feature = "shell-scope")]
  413. fn get_allowed_clis(root: &TokenStream, scope: &ShellAllowlistScope) -> TokenStream {
  414. let commands = scope
  415. .0
  416. .iter()
  417. .map(|scope| {
  418. let sidecar = &scope.sidecar;
  419. let name = &scope.name;
  420. let name = quote!(#name.into());
  421. let command = scope.command.to_string_lossy();
  422. let command = quote!(::std::path::PathBuf::from(#command));
  423. let args = match &scope.args {
  424. ShellAllowedArgs::Flag(true) => quote!(::std::option::Option::None),
  425. ShellAllowedArgs::Flag(false) => quote!(::std::option::Option::Some(::std::vec![])),
  426. ShellAllowedArgs::List(list) => {
  427. let list = list.iter().map(|arg| match arg {
  428. ShellAllowedArg::Fixed(fixed) => {
  429. quote!(#root::scope::ShellScopeAllowedArg::Fixed(#fixed.into()))
  430. }
  431. ShellAllowedArg::Var { validator } => {
  432. let validator = match regex::Regex::new(validator) {
  433. Ok(regex) => {
  434. let regex = regex.as_str();
  435. quote!(#root::regex::Regex::new(#regex).unwrap())
  436. }
  437. Err(error) => {
  438. let error = error.to_string();
  439. quote!({
  440. compile_error!(#error);
  441. #root::regex::Regex::new(#validator).unwrap()
  442. })
  443. }
  444. };
  445. quote!(#root::scope::ShellScopeAllowedArg::Var { validator: #validator })
  446. }
  447. _ => panic!("unknown shell scope arg, unable to prepare"),
  448. });
  449. quote!(::std::option::Option::Some(::std::vec![#(#list),*]))
  450. }
  451. _ => panic!("unknown shell scope command, unable to prepare"),
  452. };
  453. (
  454. quote!(#name),
  455. quote!(
  456. #root::scope::ShellScopeAllowedCommand {
  457. command: #command,
  458. args: #args,
  459. sidecar: #sidecar,
  460. }
  461. ),
  462. )
  463. })
  464. .collect::<Vec<_>>();
  465. if commands.is_empty() {
  466. quote!(::std::collections::HashMap::new())
  467. } else {
  468. let insertions = commands
  469. .iter()
  470. .map(|(name, value)| quote!(hashmap.insert(#name, #value);));
  471. quote!({
  472. let mut hashmap = ::std::collections::HashMap::new();
  473. #(#insertions)*
  474. hashmap
  475. })
  476. }
  477. }