tauri-utils 3.0.0-alpha.0

Utilities for Tauri
Documentation
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
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
// Copyright 2019-2024 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT

//! ACL items that are only useful inside of build script/codegen context.

use std::{
  collections::{BTreeMap, HashMap},
  env, fs,
  path::{Path, PathBuf},
};

use crate::{
  acl::{AllowedCommands, Error, has_app_manifest},
  config::Config,
  write_if_changed,
};

use super::{
  ALLOWED_COMMANDS_FILE_NAME, PERMISSION_SCHEMA_FILE_NAME, PERMISSION_SCHEMAS_FOLDER_NAME,
  REMOVE_UNUSED_COMMANDS_ENV_VAR,
  capability::{Capability, CapabilityFile},
  manifest::PermissionFile,
};

/// Known name of the folder containing autogenerated permissions.
pub const AUTOGENERATED_FOLDER_NAME: &str = "autogenerated";

/// Known name of the file listing the commands that get permissions autogenerated on demand.
pub const AUTOGENERATED_COMMANDS_FILE_NAME: &str = "commands.toml";

/// Cargo cfg key for permissions file paths
pub const PERMISSION_FILES_PATH_KEY: &str = "PERMISSION_FILES_PATH";

/// Cargo cfg key for global scope schemas
pub const GLOBAL_SCOPE_SCHEMA_PATH_KEY: &str = "GLOBAL_SCOPE_SCHEMA_PATH";

/// Allowed permission file extensions
pub const PERMISSION_FILE_EXTENSIONS: &[&str] = &["json", "toml"];

/// Known filename of the permission documentation file
pub const PERMISSION_DOCS_FILE_NAME: &str = "reference.md";

/// Allowed capability file extensions
const CAPABILITY_FILE_EXTENSIONS: &[&str] = &[
  "json",
  #[cfg(feature = "config-json5")]
  "json5",
  "toml",
];

/// Known folder name of the capability schemas
const CAPABILITIES_SCHEMA_FOLDER_NAME: &str = "schemas";

const CORE_PLUGIN_PERMISSIONS_TOKEN: &str = "__CORE_PLUGIN__";

fn parse_permissions(paths: Vec<PathBuf>) -> Result<Vec<PermissionFile>, Error> {
  let mut permissions = Vec::new();
  for path in paths {
    let ext = path.extension().unwrap().to_string_lossy().to_string();
    let permission_file = fs::read_to_string(&path).map_err(|e| Error::ReadFile(e, path))?;
    let permission: PermissionFile = match ext.as_str() {
      "toml" => toml::from_str(&permission_file)?,
      "json" => serde_json::from_str(&permission_file)?,
      _ => return Err(Error::UnknownPermissionFormat(ext)),
    };
    permissions.push(permission);
  }
  Ok(permissions)
}

/// Collects the permission file paths matching the given glob `pattern`, skipping files with
/// unknown extensions and permission schema files.
///
/// Use this together with [`define_permissions_from_files`] when the permissions of a single crate
/// are spread across multiple directories (e.g. hand-authored files in the crate and autogenerated
/// files in `OUT_DIR`) and must be merged into a single permission file list.
pub fn collect_permission_files<F: Fn(&Path) -> bool>(
  pattern: &str,
  filter_fn: F,
) -> Result<Vec<PathBuf>, Error> {
  Ok(
    glob::glob(pattern)?
      .flatten()
      .flat_map(|p| p.canonicalize())
      // filter extension
      .filter(|p| {
        p.extension()
          .and_then(|e| e.to_str())
          .map(|e| PERMISSION_FILE_EXTENSIONS.contains(&e))
          .unwrap_or_default()
      })
      .filter(|p| filter_fn(p))
      // filter schemas
      .filter(|p| p.parent().unwrap().file_name().unwrap() != PERMISSION_SCHEMAS_FOLDER_NAME)
      .collect::<Vec<PathBuf>>(),
  )
}

/// Write the permission file list to a temporary directory and pass it to the immediate consuming
/// crate, then parse and return the permissions.
pub fn define_permissions_from_files(
  permission_files: Vec<PathBuf>,
  pkg_name: &str,
  out_dir: &Path,
) -> Result<Vec<PermissionFile>, Error> {
  let pkg_name_valid_path = pkg_name.replace(':', "-");
  let permission_files_path = out_dir.join(format!("{pkg_name_valid_path}-permission-files"));
  let permission_files_json = serde_json::to_string(&permission_files)?;

  write_if_changed(&permission_files_path, permission_files_json)
    .map_err(|e| Error::WriteFile(e, permission_files_path.clone()))?;

  if let Some(plugin_name) = pkg_name.strip_prefix("tauri:") {
    println!(
      "cargo:{plugin_name}{CORE_PLUGIN_PERMISSIONS_TOKEN}_{PERMISSION_FILES_PATH_KEY}={}",
      permission_files_path.display()
    );
  } else {
    println!(
      "cargo:{PERMISSION_FILES_PATH_KEY}={}",
      permission_files_path.display()
    );
  }

  parse_permissions(permission_files)
}

/// Write the permissions to a temporary directory and pass it to the immediate consuming crate.
pub fn define_permissions<F: Fn(&Path) -> bool>(
  pattern: &str,
  pkg_name: &str,
  out_dir: &Path,
  filter_fn: F,
) -> Result<Vec<PermissionFile>, Error> {
  let permission_files = collect_permission_files(pattern, filter_fn)?;
  define_permissions_from_files(permission_files, pkg_name, out_dir)
}

/// Read all permissions listed from the defined cargo cfg key value.
pub fn read_permissions() -> Result<HashMap<String, Vec<PermissionFile>>, Error> {
  let mut permissions_map = HashMap::new();

  for (key, value) in env::vars_os() {
    let key = key.to_string_lossy();

    if let Some(plugin_crate_name_var) = key
      .strip_prefix("DEP_")
      .and_then(|v| v.strip_suffix(&format!("_{PERMISSION_FILES_PATH_KEY}")))
      .map(|v| {
        v.strip_suffix(CORE_PLUGIN_PERMISSIONS_TOKEN)
          .and_then(|v| v.strip_prefix("TAURI_"))
          .unwrap_or(v)
      })
    {
      let permissions_path = PathBuf::from(value);
      let permissions_str =
        fs::read_to_string(&permissions_path).map_err(|e| Error::ReadFile(e, permissions_path))?;
      let permissions: Vec<PathBuf> = serde_json::from_str(&permissions_str)?;
      let permissions = parse_permissions(permissions)?;

      let plugin_crate_name = plugin_crate_name_var.to_lowercase().replace('_', "-");
      let plugin_crate_name = plugin_crate_name
        .strip_prefix("tauri-plugin-")
        .map(ToString::to_string)
        .unwrap_or(plugin_crate_name);

      permissions_map.insert(plugin_crate_name, permissions);
    }
  }

  Ok(permissions_map)
}

/// Define the global scope schema JSON file path if it exists and pass it to the immediate consuming crate.
pub fn define_global_scope_schema(
  schema: schemars::Schema,
  pkg_name: &str,
  out_dir: &Path,
) -> Result<(), Error> {
  let path = out_dir.join("global-scope.json");
  write_if_changed(&path, serde_json::to_vec(&schema)?)
    .map_err(|e| Error::WriteFile(e, path.clone()))?;

  if let Some(plugin_name) = pkg_name.strip_prefix("tauri:") {
    println!(
      "cargo:{plugin_name}{CORE_PLUGIN_PERMISSIONS_TOKEN}_{GLOBAL_SCOPE_SCHEMA_PATH_KEY}={}",
      path.display()
    );
  } else {
    println!("cargo:{GLOBAL_SCOPE_SCHEMA_PATH_KEY}={}", path.display());
  }

  Ok(())
}

/// Read all global scope schemas listed from the defined cargo cfg key value.
pub fn read_global_scope_schemas() -> Result<HashMap<String, serde_json::Value>, Error> {
  let mut schemas_map = HashMap::new();

  for (key, value) in env::vars_os() {
    let key = key.to_string_lossy();

    if let Some(plugin_crate_name_var) = key
      .strip_prefix("DEP_")
      .and_then(|v| v.strip_suffix(&format!("_{GLOBAL_SCOPE_SCHEMA_PATH_KEY}")))
      .map(|v| {
        v.strip_suffix(CORE_PLUGIN_PERMISSIONS_TOKEN)
          .and_then(|v| v.strip_prefix("TAURI_"))
          .unwrap_or(v)
      })
    {
      let path = PathBuf::from(value);
      let json = fs::read_to_string(&path).map_err(|e| Error::ReadFile(e, path))?;
      let schema: serde_json::Value = serde_json::from_str(&json)?;

      let plugin_crate_name = plugin_crate_name_var.to_lowercase().replace('_', "-");
      let plugin_crate_name = plugin_crate_name
        .strip_prefix("tauri-plugin-")
        .map(ToString::to_string)
        .unwrap_or(plugin_crate_name);

      schemas_map.insert(plugin_crate_name, schema);
    }
  }

  Ok(schemas_map)
}

/// Parses all capability files with the given glob pattern.
pub fn parse_capabilities(pattern: &str) -> Result<BTreeMap<String, Capability>, Error> {
  let mut capabilities_map = BTreeMap::new();

  for path in glob::glob(pattern)?
    .flatten() // filter extension
    .filter(|p| {
      p.extension()
        .and_then(|e| e.to_str())
        .map(|e| CAPABILITY_FILE_EXTENSIONS.contains(&e))
        .unwrap_or_default()
    })
    // filter schema files
    // TODO: remove this before stable
    .filter(|p| p.parent().unwrap().file_name().unwrap() != CAPABILITIES_SCHEMA_FOLDER_NAME)
  {
    match CapabilityFile::load(&path)? {
      CapabilityFile::Capability(capability) => {
        if capabilities_map.contains_key(&capability.identifier) {
          return Err(Error::CapabilityAlreadyExists {
            identifier: capability.identifier,
          });
        }

        capabilities_map.insert(capability.identifier.clone(), capability);
      }
      CapabilityFile::List(capabilities) | CapabilityFile::NamedList { capabilities } => {
        for capability in capabilities {
          if capabilities_map.contains_key(&capability.identifier) {
            return Err(Error::CapabilityAlreadyExists {
              identifier: capability.identifier,
            });
          }

          capabilities_map.insert(capability.identifier.clone(), capability);
        }
      }
    }
  }

  Ok(capabilities_map)
}

/// Permissions that are generated from commands using [`autogenerate_command_permissions`].
pub struct AutogeneratedPermissions {
  /// The allow permissions generated from commands.
  pub allowed: Vec<String>,
  /// The deny permissions generated from commands.
  pub denied: Vec<String>,
}

/// Autogenerate a permission file listing the given commands.
///
/// Instead of writing two explicit permissions (`allow-$command` and `deny-$command`) per command,
/// a single [`AUTOGENERATED_COMMANDS_FILE_NAME`] file is written listing the command names. The
/// `allow-`/`deny-` permissions are then [materialized on demand](super::manifest::Manifest::command_permission)
/// by the ACL resolver, which drastically reduces the size of the manifest for plugins with many commands.
///
/// Returns the `allow-`/`deny-` permission identifiers for the commands (e.g. for a default permission set).
pub fn autogenerate_command_permissions(
  path: &Path,
  commands: &[&str],
  license_header: &str,
  schema_ref: bool,
) -> AutogeneratedPermissions {
  if !path.exists() {
    fs::create_dir_all(path).expect("unable to create autogenerated commands dir");
  }

  // remove stale per-command permission files written by older Tauri versions
  // (one file with two permissions per command); the commands are now listed in a single file
  // and resolved on demand.
  for entry in fs::read_dir(path).into_iter().flatten().flatten() {
    let entry_path = entry.path();
    let is_command_file =
      entry_path.file_name() == Some(std::ffi::OsStr::new(AUTOGENERATED_COMMANDS_FILE_NAME));
    let is_toml = entry_path.extension().and_then(|e| e.to_str()) == Some("toml");
    if is_toml && !is_command_file {
      let _ = fs::remove_file(entry_path);
    }
  }

  let schema_entry = if schema_ref {
    let cwd = env::current_dir().unwrap();
    let components_len = path.strip_prefix(&cwd).unwrap_or(path).components().count();
    let schema_path = (1..components_len)
      .map(|_| "..")
      .collect::<PathBuf>()
      .join(PERMISSION_SCHEMAS_FOLDER_NAME)
      .join(PERMISSION_SCHEMA_FILE_NAME);
    format!(
      "\n\"$schema\" = \"{}\"\n",
      dunce::simplified(&schema_path)
        .display()
        .to_string()
        .replace('\\', "/")
    )
  } else {
    "".to_string()
  };

  let autogenerated = AutogeneratedPermissions {
    allowed: commands
      .iter()
      .map(|command| format!("allow-{}", command.replace('_', "-")))
      .collect(),
    denied: commands
      .iter()
      .map(|command| format!("deny-{}", command.replace('_', "-")))
      .collect(),
  };

  let commands_list = serde_json::to_string(commands).expect("failed to serialize command list");
  let toml = format!(
    r###"{license_header}# Automatically generated - DO NOT EDIT!
{schema_entry}
commands = {commands_list}
"###,
  );

  let out_path = path.join(AUTOGENERATED_COMMANDS_FILE_NAME);
  write_if_changed(&out_path, toml)
    .unwrap_or_else(|_| panic!("unable to autogenerate {out_path:?}"));

  autogenerated
}

const PERMISSION_TABLE_HEADER: &str =
  "## Permission Table\n\n<table>\n<tr>\n<th>Identifier</th>\n<th>Description</th>\n</tr>\n";

/// Generate a markdown documentation page containing the list of permissions of the plugin.
pub fn generate_docs(
  permissions: &[PermissionFile],
  out_dir: &Path,
  plugin_identifier: &str,
) -> Result<(), Error> {
  let mut default_permission = "".to_owned();
  let mut permission_table = "".to_string();

  fn docs_from(id: &str, description: Option<&str>, plugin_identifier: &str) -> String {
    let mut docs = format!("\n<tr>\n<td>\n\n`{plugin_identifier}:{id}`\n\n</td>\n");
    if let Some(d) = description {
      docs.push_str(&format!("<td>\n\n{d}\n\n</td>"));
    }
    docs.push_str("\n</tr>");
    docs
  }

  for permission in permissions {
    for set in &permission.set {
      permission_table.push_str(&docs_from(
        &set.identifier,
        Some(&set.description),
        plugin_identifier,
      ));
      permission_table.push('\n');
    }

    if let Some(default) = &permission.default {
      default_permission.push_str("## Default Permission\n\n");
      default_permission.push_str(default.description.as_deref().unwrap_or_default().trim());
      default_permission.push('\n');
      default_permission.push('\n');
      if !default.permissions.is_empty() {
        default_permission.push_str("#### This default permission set includes the following:\n\n");
        for permission in &default.permissions {
          default_permission.push_str(&format!("- `{permission}`\n"));
        }
        default_permission.push('\n');
      }
    }

    for permission in &permission.permission {
      permission_table.push_str(&docs_from(
        &permission.identifier,
        permission.description.as_deref(),
        plugin_identifier,
      ));
      permission_table.push('\n');
    }

    // docs for the `allow-$command`/`deny-$command` permissions generated on demand
    // (sorted so the generated reference stays stable regardless of the command declaration order)
    let mut commands = permission.commands.clone();
    commands.sort();
    for command in &commands {
      let slug = command.replace('_', "-");
      permission_table.push_str(&docs_from(
        &format!("allow-{slug}"),
        Some(&format!(
          "Enables the {command} command without any pre-configured scope."
        )),
        plugin_identifier,
      ));
      permission_table.push('\n');
      permission_table.push_str(&docs_from(
        &format!("deny-{slug}"),
        Some(&format!(
          "Denies the {command} command without any pre-configured scope."
        )),
        plugin_identifier,
      ));
      permission_table.push('\n');
    }
  }

  let docs = format!("{default_permission}{PERMISSION_TABLE_HEADER}\n{permission_table}</table>\n");

  let reference_path = out_dir.join(PERMISSION_DOCS_FILE_NAME);
  write_if_changed(&reference_path, docs).map_err(|e| Error::WriteFile(e, reference_path))?;

  Ok(())
}

// TODO: We have way too many duplicated code around getting the config files, e.g.
//  - crates/tauri-codegen/src/lib.rs          (`get_config`)
//  - crates/tauri-build/src/lib.rs            (`try_build`)
//  - crates/tauri-cli/src/helpers/config.rs   (`get_internal`)
/// Generate allowed commands file for the `generate_handler` macro to remove never allowed commands
pub fn generate_allowed_commands(
  out_dir: &Path,
  capabilities_from_files: Option<BTreeMap<String, Capability>>,
  permissions_map: BTreeMap<String, Vec<PermissionFile>>,
) -> Result<(), anyhow::Error> {
  println!("cargo:rerun-if-env-changed={REMOVE_UNUSED_COMMANDS_ENV_VAR}");

  let allowed_commands_file_path = out_dir.join(ALLOWED_COMMANDS_FILE_NAME);

  let remove_unused_commands_env_var = std::env::var(REMOVE_UNUSED_COMMANDS_ENV_VAR);

  let should_generate_allowed_commands =
    remove_unused_commands_env_var.is_ok() && !permissions_map.is_empty();

  if !should_generate_allowed_commands {
    let _ = std::fs::remove_file(allowed_commands_file_path);
    return Ok(());
  }

  // It's safe to `unwrap` here since we have checked if the result is ok above
  let config_directory = PathBuf::from(remove_unused_commands_env_var.unwrap());
  let capabilities_path = config_directory.join("capabilities");
  // Cargo re-builds if the variable points to an empty path,
  // so we check for exists here
  // see https://github.com/rust-lang/cargo/issues/4213
  if capabilities_path.exists() {
    println!("cargo:rerun-if-changed={}", capabilities_path.display());
  }

  let target_triple = env::var("TARGET")?;
  let target = crate::platform::Target::from_triple(&target_triple);
  let (mut config, config_paths) = crate::config::parse::read_from(target, &config_directory)?;

  for config_file_path in config_paths {
    println!("cargo:rerun-if-changed={}", config_file_path.display());
  }

  if let Ok(env) = std::env::var("TAURI_CONFIG") {
    let merge_config: serde_json::Value = serde_json::from_str(&env)?;
    json_patch::merge(&mut config, &merge_config);
  }

  println!("cargo:rerun-if-env-changed=TAURI_CONFIG");

  // Set working directory to where `tauri.config.json` is, so that relative paths in it are parsed correctly.
  let old_cwd = std::env::current_dir()?;
  std::env::set_current_dir(config_directory)?;

  let config: Config = serde_json::from_value(config)?;

  // Reset working directory.
  std::env::set_current_dir(old_cwd)?;

  let acl: BTreeMap<String, crate::acl::manifest::Manifest> = permissions_map
    .into_iter()
    .map(|(key, permissions)| {
      let key = key
        .strip_prefix("tauri-plugin-")
        .unwrap_or(&key)
        .to_string();
      let manifest = crate::acl::manifest::Manifest::new(permissions, None);
      (key, manifest)
    })
    .collect();

  let capabilities_from_files = if let Some(capabilities) = capabilities_from_files {
    capabilities
  } else {
    crate::acl::build::parse_capabilities(&format!(
      "{}/**/*",
      glob::Pattern::escape(&capabilities_path.to_string_lossy())
    ))?
  };
  let capabilities = crate::acl::get_capabilities(&config, capabilities_from_files, None)?;

  let permission_entries = capabilities
    .into_values()
    .flat_map(|capabilities| capabilities.permissions);
  let mut allowed_commands = AllowedCommands {
    has_app_acl: has_app_manifest(&acl),
    ..Default::default()
  };
  for permission_entry in permission_entries {
    let Ok(permissions) =
      crate::acl::resolved::get_permissions(permission_entry.identifier(), &acl)
    else {
      continue;
    };
    for permission in permissions {
      let plugin_name = permission.key;
      let allowed_command_names = &permission.permission.commands.allow;
      for allowed_command in allowed_command_names {
        let command_name = if plugin_name == crate::acl::APP_ACL_KEY {
          allowed_command.to_string()
        } else if let Some(core_plugin_name) = plugin_name.strip_prefix("core:") {
          format!("plugin:{core_plugin_name}|{allowed_command}")
        } else {
          format!("plugin:{plugin_name}|{allowed_command}")
        };
        allowed_commands.commands.insert(command_name);
      }
    }
  }

  write_if_changed(
    allowed_commands_file_path,
    serde_json::to_string(&allowed_commands)?,
  )?;

  Ok(())
}