use std::fs;
use std::io::{self, Write};
use std::path::{Path, PathBuf};
use serde::{Deserialize, Serialize};
use crate::adapters::browser::platform;
use super::is_native_origin;
const HOST_NAME: &str = "dev.kyrboforge.aoc_toolkit";
#[derive(Debug, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
struct NativeHostManifest {
name: String,
description: String,
path: PathBuf,
#[serde(rename = "type")]
transport: String,
allowed_origins: Vec<String>,
}
#[derive(Debug, PartialEq, Eq)]
pub(crate) enum RegistrationStatus {
Missing,
Registered,
Stale,
}
pub(crate) fn install(extension_id: &str) -> io::Result<PathBuf> {
let executable = std::env::current_exe()?.canonicalize()?;
let directory = platform::native_hosts_dir()?;
install_at(&directory, &executable, extension_id)
}
pub(crate) fn status() -> io::Result<RegistrationStatus> {
let executable = std::env::current_exe()?.canonicalize()?;
let directory = platform::native_hosts_dir()?;
status_at(&directory, &executable)
}
fn status_at(directory: &Path, executable: &Path) -> io::Result<RegistrationStatus> {
let Some(manifest) = read_manifest(&manifest_path(directory))? else {
return Ok(RegistrationStatus::Missing);
};
if manifest.path != executable || !manifest.path.is_file() {
return Ok(RegistrationStatus::Stale);
}
Ok(RegistrationStatus::Registered)
}
pub(crate) fn uninstall() -> io::Result<bool> {
let directory = platform::native_hosts_dir()?;
let executable = std::env::current_exe()?.canonicalize()?;
uninstall_at(&directory, &executable)
}
fn uninstall_at(directory: &Path, executable: &Path) -> io::Result<bool> {
let path = manifest_path(directory);
let Some(manifest) = read_manifest(&path)? else {
return Ok(false);
};
if manifest.path != executable {
return Err(io::Error::new(
io::ErrorKind::InvalidData,
"Registration belongs to a different executable",
));
}
fs::remove_file(path)?;
Ok(true)
}
fn install_at(directory: &Path, executable: &Path, extension_id: &str) -> io::Result<PathBuf> {
let origin = format!("chrome-extension://{extension_id}/");
if !is_native_origin(&origin) {
return Err(io::Error::new(
io::ErrorKind::InvalidInput,
"Invalid browser extension ID",
));
}
if !executable.is_absolute() || !executable.is_file() {
return Err(io::Error::new(
io::ErrorKind::InvalidInput,
"Invalid native host executable",
));
}
let manifest = NativeHostManifest {
name: HOST_NAME.to_owned(),
description: "AOC Toolkit Native Messaging Host".to_owned(),
path: executable.to_path_buf(),
transport: "stdio".to_owned(),
allowed_origins: vec![origin],
};
let content = serde_json::to_vec_pretty(&manifest).map_err(io::Error::other)?;
fs::create_dir_all(directory)?;
let destination = manifest_path(directory);
if let Some(existing) = read_manifest(&destination)? {
if existing.path == manifest.path && existing.allowed_origins == manifest.allowed_origins {
return Ok(destination);
}
return Err(io::Error::new(
io::ErrorKind::AlreadyExists,
"Conflicting native host registration",
));
}
let mut temporary = tempfile::NamedTempFile::new_in(directory)?;
temporary.write_all(&content)?;
temporary.flush()?;
temporary
.persist_noclobber(&destination)
.map_err(|error| error.error)?;
Ok(destination)
}
fn manifest_path(directory: &Path) -> PathBuf {
directory.join(format!("{HOST_NAME}.json"))
}
fn read_manifest(path: &Path) -> io::Result<Option<NativeHostManifest>> {
match fs::symlink_metadata(path) {
Ok(metadata) if metadata.is_file() => {}
Ok(_) => {
return Err(io::Error::new(
io::ErrorKind::InvalidData,
"Invalid native host manifest file",
));
}
Err(error) if error.kind() == io::ErrorKind::NotFound => {
return Ok(None);
}
Err(error) => return Err(error),
}
let manifest: NativeHostManifest =
serde_json::from_slice(&fs::read(path)?).map_err(io::Error::other)?;
if manifest.name != HOST_NAME
|| manifest.transport != "stdio"
|| !manifest.path.is_absolute()
|| manifest.allowed_origins.len() != 1
|| !manifest
.allowed_origins
.iter()
.all(|origin| is_native_origin(origin))
{
return Err(io::Error::new(
io::ErrorKind::InvalidData,
"Invalid native host manifest",
));
}
Ok(Some(manifest))
}
#[cfg(test)]
mod tests;