1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
use proc_macro2::TokenStream;
use quote::{quote, ToTokens, TokenStreamExt};
use sha2::{Digest, Sha256};
use std::{
collections::HashMap,
fmt::Write,
fs::File,
path::{Path, PathBuf},
};
use tauri_utils::config::PatternKind;
use tauri_utils::{assets::AssetKey, config::DisabledCspModificationKind};
use thiserror::Error;
use walkdir::{DirEntry, WalkDir};
#[cfg(feature = "compression")]
use brotli::enc::backward_references::BrotliEncoderParams;
const TARGET_PATH: &str = "tauri-codegen-assets";
type Asset = (AssetKey, (PathBuf, PathBuf));
#[derive(Debug, Error)]
#[non_exhaustive]
pub enum EmbeddedAssetsError {
#[error("failed to read asset at {path} because {error}")]
AssetRead {
path: PathBuf,
error: std::io::Error,
},
#[error("failed to write asset from {path} to Vec<u8> because {error}")]
AssetWrite {
path: PathBuf,
error: std::io::Error,
},
#[error("failed to create hex from bytes because {0}")]
Hex(std::fmt::Error),
#[error("invalid prefix {prefix} used while including path {path}")]
PrefixInvalid { prefix: PathBuf, path: PathBuf },
#[error("failed to walk directory {path} because {error}")]
Walkdir {
path: PathBuf,
error: walkdir::Error,
},
#[error("OUT_DIR env var is not set, do you have a build script?")]
OutDir,
}
#[derive(Default)]
pub struct EmbeddedAssets {
assets: HashMap<AssetKey, (PathBuf, PathBuf)>,
csp_hashes: CspHashes,
}
pub struct EmbeddedAssetsInput(Vec<PathBuf>);
impl From<PathBuf> for EmbeddedAssetsInput {
fn from(path: PathBuf) -> Self {
Self(vec![path])
}
}
impl From<Vec<PathBuf>> for EmbeddedAssetsInput {
fn from(paths: Vec<PathBuf>) -> Self {
Self(paths)
}
}
struct RawEmbeddedAssets {
paths: Vec<(PathBuf, DirEntry)>,
csp_hashes: CspHashes,
}
impl RawEmbeddedAssets {
fn new(input: EmbeddedAssetsInput, options: &AssetOptions) -> Result<Self, EmbeddedAssetsError> {
let mut csp_hashes = CspHashes::default();
input
.0
.into_iter()
.flat_map(|path| {
let prefix = if path.is_dir() {
path.clone()
} else {
path
.parent()
.expect("embedded file asset has no parent")
.to_path_buf()
};
WalkDir::new(&path)
.follow_links(true)
.contents_first(true)
.into_iter()
.map(move |entry| (prefix.clone(), entry))
})
.filter_map(|(prefix, entry)| {
match entry {
Ok(entry) if entry.file_type().is_dir() => None,
Ok(entry) => {
if let Err(error) = csp_hashes
.add_if_applicable(&entry, &options.dangerous_disable_asset_csp_modification)
{
Some(Err(error))
} else {
Some(Ok((prefix, entry)))
}
}
Err(error) => Some(Err(EmbeddedAssetsError::Walkdir {
path: prefix,
error,
})),
}
})
.collect::<Result<Vec<(PathBuf, DirEntry)>, _>>()
.map(|paths| Self { paths, csp_hashes })
}
}
#[derive(Debug, Default)]
pub struct CspHashes {
pub(crate) scripts: Vec<String>,
pub(crate) inline_scripts: HashMap<String, Vec<String>>,
pub(crate) styles: Vec<String>,
}
impl CspHashes {
pub fn add_if_applicable(
&mut self,
entry: &DirEntry,
dangerous_disable_asset_csp_modification: &DisabledCspModificationKind,
) -> Result<(), EmbeddedAssetsError> {
let path = entry.path();
if let Some("js") | Some("mjs") = path.extension().and_then(|os| os.to_str()) {
if dangerous_disable_asset_csp_modification.can_modify("script-src") {
let mut hasher = Sha256::new();
hasher.update(
&std::fs::read(path).map_err(|error| EmbeddedAssetsError::AssetRead {
path: path.to_path_buf(),
error,
})?,
);
let hash = hasher.finalize();
self
.scripts
.push(format!("'sha256-{}'", base64::encode(hash)));
}
}
Ok(())
}
}
#[derive(Default)]
pub struct AssetOptions {
pub(crate) csp: bool,
pub(crate) pattern: PatternKind,
pub(crate) freeze_prototype: bool,
pub(crate) dangerous_disable_asset_csp_modification: DisabledCspModificationKind,
#[cfg(feature = "isolation")]
pub(crate) isolation_schema: String,
}
impl AssetOptions {
pub fn new(pattern: PatternKind) -> Self {
Self {
csp: false,
pattern,
freeze_prototype: false,
dangerous_disable_asset_csp_modification: DisabledCspModificationKind::Flag(false),
#[cfg(feature = "isolation")]
isolation_schema: format!("isolation-{}", uuid::Uuid::new_v4()),
}
}
#[must_use]
pub fn with_csp(mut self) -> Self {
self.csp = true;
self
}
#[must_use]
pub fn freeze_prototype(mut self, freeze: bool) -> Self {
self.freeze_prototype = freeze;
self
}
pub fn dangerous_disable_asset_csp_modification(
mut self,
dangerous_disable_asset_csp_modification: DisabledCspModificationKind,
) -> Self {
self.dangerous_disable_asset_csp_modification = dangerous_disable_asset_csp_modification;
self
}
}
impl EmbeddedAssets {
pub fn new(
input: impl Into<EmbeddedAssetsInput>,
options: &AssetOptions,
map: impl Fn(&AssetKey, &Path, &mut Vec<u8>, &mut CspHashes) -> Result<(), EmbeddedAssetsError>,
) -> Result<Self, EmbeddedAssetsError> {
let RawEmbeddedAssets { paths, csp_hashes } = RawEmbeddedAssets::new(input.into(), options)?;
struct CompressState {
csp_hashes: CspHashes,
assets: HashMap<AssetKey, (PathBuf, PathBuf)>,
}
let CompressState { assets, csp_hashes } = paths.into_iter().try_fold(
CompressState {
csp_hashes,
assets: HashMap::new(),
},
move |mut state, (prefix, entry)| {
let (key, asset) = Self::compress_file(&prefix, entry.path(), &map, &mut state.csp_hashes)?;
state.assets.insert(key, asset);
Ok(state)
},
)?;
Ok(Self { assets, csp_hashes })
}
#[cfg(feature = "compression")]
fn compression_settings() -> BrotliEncoderParams {
let mut settings = BrotliEncoderParams::default();
if cfg!(debug_assertions) {
settings.quality = 2
} else {
settings.quality = 9
}
settings
}
fn compress_file(
prefix: &Path,
path: &Path,
map: &impl Fn(&AssetKey, &Path, &mut Vec<u8>, &mut CspHashes) -> Result<(), EmbeddedAssetsError>,
csp_hashes: &mut CspHashes,
) -> Result<Asset, EmbeddedAssetsError> {
let mut input = std::fs::read(path).map_err(|error| EmbeddedAssetsError::AssetRead {
path: path.to_owned(),
error,
})?;
let key = path
.strip_prefix(prefix)
.map(AssetKey::from)
.map_err(|_| EmbeddedAssetsError::PrefixInvalid {
prefix: prefix.to_owned(),
path: path.to_owned(),
})?;
map(&key, path, &mut input, csp_hashes)?;
let out_dir = std::env::var("OUT_DIR")
.map_err(|_| EmbeddedAssetsError::OutDir)
.map(PathBuf::from)
.and_then(|p| p.canonicalize().map_err(|_| EmbeddedAssetsError::OutDir))
.map(|p| p.join(TARGET_PATH))?;
std::fs::create_dir_all(&out_dir).map_err(|_| EmbeddedAssetsError::OutDir)?;
let hash = {
let mut hasher = crate::vendor::blake3_reference::Hasher::default();
hasher.update(&input);
let mut bytes = [0u8; 32];
hasher.finalize(&mut bytes);
let mut hex = String::with_capacity(2 * bytes.len());
for b in bytes {
write!(hex, "{:02x}", b).map_err(EmbeddedAssetsError::Hex)?;
}
hex
};
let out_path = if let Some(ext) = path.extension().and_then(|e| e.to_str()) {
out_dir.join(format!("{}.{}", hash, ext))
} else {
out_dir.join(hash)
};
if !out_path.exists() {
#[allow(unused_mut)]
let mut out_file =
File::create(&out_path).map_err(|error| EmbeddedAssetsError::AssetWrite {
path: out_path.clone(),
error,
})?;
#[cfg(not(feature = "compression"))]
{
use std::io::Write;
out_file
.write_all(&input)
.map_err(|error| EmbeddedAssetsError::AssetWrite {
path: path.to_owned(),
error,
})?;
}
#[cfg(feature = "compression")]
{
let mut input = std::io::Cursor::new(input);
brotli::BrotliCompress(&mut input, &mut out_file, &Self::compression_settings()).map_err(
|error| EmbeddedAssetsError::AssetWrite {
path: path.to_owned(),
error,
},
)?;
}
}
Ok((key, (path.into(), out_path)))
}
}
impl ToTokens for EmbeddedAssets {
fn to_tokens(&self, tokens: &mut TokenStream) {
let mut assets = TokenStream::new();
for (key, (input, output)) in &self.assets {
let key: &str = key.as_ref();
let input = input.display().to_string();
let output = output.display().to_string();
assets.append_all(quote!(#key => {
const _: &[u8] = include_bytes!(#input);
include_bytes!(#output)
},));
}
let mut global_hashes = TokenStream::new();
for script_hash in &self.csp_hashes.scripts {
let hash = script_hash.as_str();
global_hashes.append_all(quote!(CspHash::Script(#hash),));
}
for style_hash in &self.csp_hashes.styles {
let hash = style_hash.as_str();
global_hashes.append_all(quote!(CspHash::Style(#hash),));
}
let mut html_hashes = TokenStream::new();
for (path, hashes) in &self.csp_hashes.inline_scripts {
let key = path.as_str();
let mut value = TokenStream::new();
for script_hash in hashes {
let hash = script_hash.as_str();
value.append_all(quote!(CspHash::Script(#hash),));
}
html_hashes.append_all(quote!(#key => &[#value],));
}
tokens.append_all(quote! {{
use ::tauri::utils::assets::{CspHash, EmbeddedAssets, phf, phf::phf_map};
EmbeddedAssets::new(phf_map! { #assets }, &[#global_hashes], phf_map! { #html_hashes })
}});
}
}