use std::collections::{HashMap, VecDeque};
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::time::Duration;
use futures::SinkExt;
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
use serde_json::{Value, json};
use sha2::{Digest, Sha256};
use tokio::io::{AsyncBufReadExt, BufReader};
use tokio::net::UnixStream;
use tokio::net::unix::OwnedWriteHalf;
use tokio::sync::{Mutex, oneshot};
use tokio_util::codec::{FramedWrite, LinesCodec};
use crate::model::now_ms;
use crate::store::state_dir;
pub const EXTENSION_PROTOCOL_VERSION: u64 = 1;
pub const EXTENSION_SOCKET_NAME: &str = "apoc-extension.sock";
pub const DEFAULT_EXTENSION_HOST_NAME: &str = "com.douglance.apoc";
pub const PACKAGED_EXTENSION_ID: &str = "agnjkkdhkkcmdeeeamngnokpbpciebbn";
const MAX_EXTENSION_EVENTS: usize = 1_000;
const PACKAGED_EXTENSION_ASSETS: &[(&str, &[u8])] = &[
(
"manifest.json",
include_bytes!(concat!(
env!("CARGO_MANIFEST_DIR"),
"/extensions/chrome-extension/manifest.json"
)),
),
(
"service-worker.js",
include_bytes!(concat!(
env!("CARGO_MANIFEST_DIR"),
"/extensions/chrome-extension/service-worker.js"
)),
),
(
"content-script.js",
include_bytes!(concat!(
env!("CARGO_MANIFEST_DIR"),
"/extensions/chrome-extension/content-script.js"
)),
),
(
"page-probe.js",
include_bytes!(concat!(
env!("CARGO_MANIFEST_DIR"),
"/extensions/chrome-extension/page-probe.js"
)),
),
];
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
pub struct ExtensionBridgeConnection {
pub connected: bool,
pub socket: String,
pub host_name: Option<String>,
pub extension_origin: Option<String>,
pub extension_id: Option<String>,
pub version: Option<String>,
pub connected_at: Option<u64>,
pub last_seen_at: Option<u64>,
pub retained_events: usize,
}
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, PartialEq)]
pub struct ExtensionEvent {
pub ts: u64,
#[serde(default)]
#[serde(alias = "tabId")]
pub tab_id: Option<u64>,
pub kind: String,
#[serde(default)]
pub url: Option<String>,
#[serde(default)]
pub method: Option<String>,
#[serde(default)]
pub level: Option<String>,
#[serde(default)]
pub message: Option<String>,
#[serde(default)]
pub data: Option<Value>,
}
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
pub struct ExtensionTab {
pub id: u64,
#[serde(default)]
#[serde(alias = "windowId")]
pub window_id: Option<u64>,
#[serde(default)]
pub active: Option<bool>,
#[serde(default)]
pub title: Option<String>,
#[serde(default)]
pub url: Option<String>,
#[serde(default)]
pub status: Option<String>,
#[serde(default)]
pub attached: Option<bool>,
}
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
pub struct ExtensionRuntimeStatus {
pub connected: bool,
#[serde(default)]
#[serde(alias = "extensionId")]
pub extension_id: Option<String>,
#[serde(default)]
pub version: Option<String>,
#[serde(default)]
#[serde(alias = "tabId")]
pub tab_id: Option<u64>,
#[serde(default)]
#[serde(alias = "attachedTabs")]
pub attached_tabs: Vec<u64>,
#[serde(default)]
#[serde(alias = "observedTabs")]
pub observed_tabs: Vec<ExtensionObservation>,
#[serde(default)]
#[serde(alias = "lastSeenTs")]
pub last_seen_ts: Option<u64>,
}
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
pub struct ExtensionObservation {
#[serde(alias = "tabId")]
pub tab_id: u64,
pub kinds: Vec<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
pub struct ExtensionStatusView {
pub bridge: ExtensionBridgeConnection,
pub extension: Option<ExtensionRuntimeStatus>,
}
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, PartialEq)]
pub struct ExtensionAttachResult {
#[serde(default)]
pub tab: Option<ExtensionTab>,
#[serde(default)]
pub attached: Option<bool>,
#[serde(default)]
pub detached: Option<bool>,
}
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, PartialEq)]
pub struct ExtensionEvaluation {
pub value: Value,
}
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, PartialEq)]
pub struct ExtensionCdpResult {
pub cdp: Value,
}
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, PartialEq)]
pub struct ExtensionSnapshotResult {
pub snapshot: Value,
#[serde(default)]
#[serde(alias = "artifactPath")]
pub artifact_path: Option<String>,
#[serde(default)]
#[serde(alias = "traceAnchor")]
pub trace_anchor: Option<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
pub struct ExtensionObserveResult {
#[serde(default)]
pub observing: Vec<ExtensionObservation>,
}
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, PartialEq)]
pub struct ExtensionHostInstallation {
pub installed: bool,
pub browser: String,
pub manifest_path: String,
pub manifest_backup: Option<String>,
pub user_data_dir: Option<String>,
pub host_path: String,
pub extension_id: String,
pub extension_path: String,
pub extension_backup: Option<String>,
pub extension_assets: Vec<ExtensionAsset>,
pub manifest: Value,
}
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
pub struct ExtensionAsset {
pub name: String,
pub path: String,
pub bytes: u64,
pub sha256: String,
}
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, PartialEq)]
pub struct ExtensionDoctor {
pub browser: String,
pub manifest_path: String,
pub user_data_dir: Option<String>,
pub manifest_exists: bool,
pub manifest_valid: bool,
pub host_path: String,
pub host_exists: bool,
pub extension_id: String,
pub extension_path: String,
pub extension_exists: bool,
pub extension_valid: bool,
pub extension_assets: Vec<ExtensionAsset>,
pub issues: Vec<String>,
}
pub fn install_extension_host(
browser: &str,
extension_id: &str,
host_name: &str,
host_path: Option<&str>,
home: Option<&str>,
user_data_dir: Option<&str>,
dry_run: bool,
) -> Result<ExtensionHostInstallation, String> {
validate_host_name(host_name)?;
validate_extension_id(extension_id)?;
let explicit_home = home.is_some();
let home = resolve_home(home)?;
let host_path = resolve_host_path(host_path)?;
if !dry_run && !host_path.is_file() {
return Err(format!(
"Chrome native host executable does not exist: {}",
host_path.display()
));
}
let user_data_dir = resolve_optional_path(user_data_dir, "user_data_dir")?;
let manifest_path =
extension_manifest_path(browser, host_name, &home, user_data_dir.as_deref())?;
let extension_path = extension_install_path(&home, explicit_home)?;
let (extension_assets, extension_backup) =
install_packaged_extension(&extension_path, dry_run)?;
let mut allowed_origins = vec![format!("chrome-extension://{PACKAGED_EXTENSION_ID}/")];
let requested_origin = format!("chrome-extension://{extension_id}/");
if requested_origin != allowed_origins[0] {
allowed_origins.push(requested_origin);
}
let manifest = json!({
"name":host_name,
"description":"apoc Chrome native messaging host",
"path":host_path.display().to_string(),
"type":"stdio",
"allowed_origins":allowed_origins
});
let mut manifest_backup = None;
if !dry_run {
let parent = manifest_path
.parent()
.ok_or_else(|| "extension manifest path has no parent".to_string())?;
std::fs::create_dir_all(parent).map_err(|error| error.to_string())?;
let temporary = manifest_path.with_extension(format!("json.{}.tmp", uuid::Uuid::now_v7()));
std::fs::write(
&temporary,
serde_json::to_vec_pretty(&manifest).map_err(|error| error.to_string())?,
)
.map_err(|error| error.to_string())?;
if manifest_path.exists() {
let backup =
manifest_path.with_extension(format!("json.backup-{}", uuid::Uuid::now_v7()));
std::fs::rename(&manifest_path, &backup).map_err(|error| error.to_string())?;
manifest_backup = Some(backup);
}
if let Err(error) = std::fs::rename(&temporary, &manifest_path) {
let _ = std::fs::remove_file(&temporary);
if let Some(backup) = manifest_backup.as_ref() {
let _ = std::fs::rename(backup, &manifest_path);
}
return Err(error.to_string());
}
}
Ok(ExtensionHostInstallation {
installed: !dry_run,
browser: browser.to_string(),
manifest_path: manifest_path.display().to_string(),
manifest_backup: manifest_backup.map(|path| path.display().to_string()),
user_data_dir: user_data_dir.map(|path| path.display().to_string()),
host_path: host_path.display().to_string(),
extension_id: PACKAGED_EXTENSION_ID.to_string(),
extension_path: extension_path.display().to_string(),
extension_backup,
extension_assets,
manifest,
})
}
pub fn extension_doctor(
browser: &str,
host_name: &str,
host_path: Option<&str>,
home: Option<&str>,
user_data_dir: Option<&str>,
) -> Result<ExtensionDoctor, String> {
validate_host_name(host_name)?;
let explicit_home = home.is_some();
let home = resolve_home(home)?;
let user_data_dir = resolve_optional_path(user_data_dir, "user_data_dir")?;
let manifest_path =
extension_manifest_path(browser, host_name, &home, user_data_dir.as_deref())?;
let extension_path = extension_install_path(&home, explicit_home)?;
let extension_assets = packaged_extension_assets(&extension_path);
let extension_exists = extension_path.is_dir();
let extension_valid = extension_exists
&& extension_assets.iter().all(|asset| {
std::fs::read(&asset.path)
.ok()
.is_some_and(|bytes| sha256(&bytes) == asset.sha256)
});
let requested_host = resolve_host_path(host_path)?;
let manifest = std::fs::read(&manifest_path)
.ok()
.and_then(|bytes| serde_json::from_slice::<Value>(&bytes).ok());
let manifest_host = manifest
.as_ref()
.and_then(|value| value.get("path"))
.and_then(Value::as_str)
.map(PathBuf::from);
let effective_host = manifest_host.unwrap_or(requested_host);
let manifest_valid = manifest.as_ref().is_some_and(|value| {
value.get("name").and_then(Value::as_str) == Some(host_name)
&& value.get("type").and_then(Value::as_str) == Some("stdio")
&& value
.get("allowed_origins")
.and_then(Value::as_array)
.is_some_and(|origins| {
let packaged_origin = format!("chrome-extension://{PACKAGED_EXTENSION_ID}/");
origins
.iter()
.any(|origin| origin.as_str() == Some(packaged_origin.as_str()))
})
});
let mut issues = Vec::new();
if !manifest_path.is_file() {
issues.push("native host manifest is not installed".to_string());
} else if !manifest_valid {
issues.push("native host manifest is invalid".to_string());
}
if !effective_host.is_file() {
issues.push("native host executable is missing".to_string());
}
if !extension_exists {
issues.push("packaged Chrome extension is not installed".to_string());
} else if !extension_valid {
issues.push("packaged Chrome extension assets do not match this apoc build".to_string());
}
Ok(ExtensionDoctor {
browser: browser.to_string(),
manifest_path: manifest_path.display().to_string(),
user_data_dir: user_data_dir.map(|path| path.display().to_string()),
manifest_exists: manifest_path.is_file(),
manifest_valid,
host_path: effective_host.display().to_string(),
host_exists: effective_host.is_file(),
extension_id: PACKAGED_EXTENSION_ID.to_string(),
extension_path: extension_path.display().to_string(),
extension_exists,
extension_valid,
extension_assets,
issues,
})
}
fn extension_install_path(home: &Path, explicit_home: bool) -> Result<PathBuf, String> {
if explicit_home {
Ok(home.join(".apoc/chrome-extension"))
} else {
Ok(state_dir()?.join("chrome-extension"))
}
}
fn install_packaged_extension(
extension_path: &Path,
dry_run: bool,
) -> Result<(Vec<ExtensionAsset>, Option<String>), String> {
let assets = packaged_extension_assets(extension_path);
if dry_run {
return Ok((assets, None));
}
let parent = extension_path
.parent()
.ok_or_else(|| "packaged extension path has no parent".to_string())?;
std::fs::create_dir_all(parent).map_err(|error| error.to_string())?;
let staging = parent.join(format!(".chrome-extension.{}.tmp", uuid::Uuid::now_v7()));
std::fs::create_dir(&staging).map_err(|error| error.to_string())?;
for (name, bytes) in PACKAGED_EXTENSION_ASSETS {
if let Err(error) = std::fs::write(staging.join(name), bytes) {
let _ = std::fs::remove_dir_all(&staging);
return Err(error.to_string());
}
}
let backup = if extension_path.exists() {
let backup = parent.join(format!("chrome-extension.backup-{}", now_ms()));
std::fs::rename(extension_path, &backup).map_err(|error| error.to_string())?;
Some(backup)
} else {
None
};
if let Err(error) = std::fs::rename(&staging, extension_path) {
if let Some(backup) = &backup {
let _ = std::fs::rename(backup, extension_path);
}
let _ = std::fs::remove_dir_all(&staging);
return Err(error.to_string());
}
Ok((assets, backup.map(|path| path.display().to_string())))
}
fn packaged_extension_assets(extension_path: &Path) -> Vec<ExtensionAsset> {
PACKAGED_EXTENSION_ASSETS
.iter()
.map(|(name, bytes)| ExtensionAsset {
name: (*name).to_string(),
path: extension_path.join(name).display().to_string(),
bytes: bytes.len() as u64,
sha256: sha256(bytes),
})
.collect()
}
fn sha256(bytes: &[u8]) -> String {
format!("sha256:{:x}", Sha256::digest(bytes))
}
pub fn extension_manifest_path(
browser: &str,
host_name: &str,
home: &Path,
user_data_dir: Option<&Path>,
) -> Result<PathBuf, String> {
match browser {
"chrome" | "chrome-for-testing" | "chromium" => {}
_ => return Err("browser must be chrome, chrome-for-testing, or chromium".to_string()),
}
if let Some(user_data_dir) = user_data_dir {
return Ok(user_data_dir
.join("NativeMessagingHosts")
.join(format!("{host_name}.json")));
}
let directory = if cfg!(target_os = "macos") {
match browser {
"chrome" => "Library/Application Support/Google/Chrome/NativeMessagingHosts",
"chrome-for-testing" => {
"Library/Application Support/Google/ChromeForTesting/NativeMessagingHosts"
}
"chromium" => "Library/Application Support/Chromium/NativeMessagingHosts",
_ => return Err("browser must be chrome, chrome-for-testing, or chromium".to_string()),
}
} else if cfg!(target_os = "linux") {
match browser {
"chrome" => ".config/google-chrome/NativeMessagingHosts",
"chrome-for-testing" => ".config/google-chrome-for-testing/NativeMessagingHosts",
"chromium" => ".config/chromium/NativeMessagingHosts",
_ => return Err("browser must be chrome, chrome-for-testing, or chromium".to_string()),
}
} else {
return Err("Chrome native-host installation supports macOS and Linux".to_string());
};
Ok(home.join(directory).join(format!("{host_name}.json")))
}
fn resolve_optional_path(path: Option<&str>, name: &str) -> Result<Option<PathBuf>, String> {
match path {
Some(path) if !path.trim().is_empty() => Ok(Some(PathBuf::from(path))),
Some(_) => Err(format!("{name} must not be empty")),
None => Ok(None),
}
}
fn resolve_home(home: Option<&str>) -> Result<PathBuf, String> {
match home {
Some(home) if !home.trim().is_empty() => Ok(PathBuf::from(home)),
Some(_) => Err("home must not be empty".to_string()),
None => dirs::home_dir().ok_or_else(|| "could not resolve the user home".to_string()),
}
}
fn resolve_host_path(host_path: Option<&str>) -> Result<PathBuf, String> {
let path = match host_path {
Some(path) if !path.trim().is_empty() => PathBuf::from(path),
Some(_) => return Err("host_path must not be empty".to_string()),
None => std::env::current_exe()
.map_err(|error| error.to_string())?
.with_file_name("apoc-chrome-native-host"),
};
if !path.is_absolute() {
return Err("host_path must be absolute".to_string());
}
Ok(path)
}
fn validate_host_name(host_name: &str) -> Result<(), String> {
if host_name.is_empty()
|| host_name.starts_with('.')
|| host_name.ends_with('.')
|| host_name.contains("..")
|| !host_name
.bytes()
.all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'.' | b'_' | b'-'))
{
return Err("invalid Chrome native host name".to_string());
}
Ok(())
}
fn validate_extension_id(extension_id: &str) -> Result<(), String> {
if extension_id.is_empty()
|| !extension_id
.bytes()
.all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'_' | b'-'))
{
return Err("invalid Chrome extension id".to_string());
}
Ok(())
}
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
struct BridgeConnect {
cmd: String,
host_name: String,
#[serde(default)]
extension_origin: Option<String>,
}
#[derive(Default)]
struct ExtensionBridgeState {
generation: u64,
writer: Option<FramedWrite<OwnedWriteHalf, LinesCodec>>,
host_name: Option<String>,
extension_origin: Option<String>,
extension_id: Option<String>,
version: Option<String>,
connected_at: Option<u64>,
last_seen_at: Option<u64>,
events: VecDeque<ExtensionEvent>,
pending: HashMap<String, oneshot::Sender<Result<Value, String>>>,
}
#[derive(Clone, Default)]
pub struct ExtensionBridge {
state: Arc<Mutex<ExtensionBridgeState>>,
}
impl ExtensionBridge {
pub async fn serve_connection(&self, stream: UnixStream) -> Result<(), String> {
let (reader, writer) = stream.into_split();
let mut lines = BufReader::new(reader).lines();
let handshake = lines
.next_line()
.await
.map_err(|error| error.to_string())?
.ok_or_else(|| "extension bridge closed before handshake".to_string())?;
let handshake = serde_json::from_str::<BridgeConnect>(&handshake)
.map_err(|error| format!("invalid extension bridge handshake: {error}"))?;
if handshake.cmd != "ext.bridge.connect" || handshake.host_name.trim().is_empty() {
return Err("invalid extension bridge handshake".to_string());
}
let generation = {
let mut state = self.state.lock().await;
state.generation = state.generation.wrapping_add(1);
let generation = state.generation;
let replaced = state
.pending
.drain()
.map(|(_, pending)| pending)
.collect::<Vec<_>>();
for pending in replaced {
let _ = pending.send(Err("extension bridge connection was replaced".to_string()));
}
state.writer = Some(FramedWrite::new(writer, LinesCodec::new()));
state.host_name = Some(handshake.host_name);
state.extension_origin = handshake.extension_origin;
state.extension_id = None;
state.version = None;
state.connected_at = Some(now_ms());
state.last_seen_at = Some(now_ms());
generation
};
self.send_envelope(json!({"v":1,"type":"ack","id":"bridge"}))
.await?;
while let Some(line) = lines.next_line().await.map_err(|error| error.to_string())? {
let envelope = serde_json::from_str::<Value>(&line)
.map_err(|error| format!("invalid extension bridge envelope: {error}"))?;
if envelope.get("v").and_then(Value::as_u64) != Some(EXTENSION_PROTOCOL_VERSION) {
continue;
}
let mut state = self.state.lock().await;
if state.generation != generation {
break;
}
state.last_seen_at = Some(now_ms());
match envelope.get("type").and_then(Value::as_str) {
Some("hello") => {
state.extension_id = envelope
.get("extensionId")
.and_then(Value::as_str)
.map(str::to_string);
state.version = envelope
.get("version")
.and_then(Value::as_str)
.map(str::to_string);
}
Some("response") => {
let Some(id) = envelope.get("id").and_then(Value::as_str) else {
continue;
};
let Some(pending) = state.pending.remove(id) else {
continue;
};
let response = if envelope.get("ok").and_then(Value::as_bool) == Some(true) {
Ok(envelope.get("result").cloned().unwrap_or_else(|| json!({})))
} else {
Err(envelope
.get("error")
.and_then(Value::as_str)
.unwrap_or("extension request failed")
.to_string())
};
let _ = pending.send(response);
}
Some("event") => {
if let Some(event) = envelope.get("event")
&& let Ok(event) = serde_json::from_value::<ExtensionEvent>(event.clone())
{
state.events.push_back(event);
while state.events.len() > MAX_EXTENSION_EVENTS {
state.events.pop_front();
}
}
}
_ => {}
}
}
let mut state = self.state.lock().await;
if state.generation == generation {
state.writer = None;
let pending = state
.pending
.drain()
.map(|(_, pending)| pending)
.collect::<Vec<_>>();
for pending in pending {
let _ = pending.send(Err("extension bridge disconnected".to_string()));
}
}
Ok(())
}
pub async fn request(&self, request: Value, timeout: Duration) -> Result<Value, String> {
let id = uuid::Uuid::now_v7().to_string();
let (sender, receiver) = oneshot::channel();
{
let mut state = self.state.lock().await;
if state.writer.is_none() {
return Err("Chrome extension bridge is not connected".to_string());
}
state.pending.insert(id.clone(), sender);
}
if let Err(error) = self
.send_envelope(json!({
"v": EXTENSION_PROTOCOL_VERSION,
"id": id,
"type": "request",
"request": request
}))
.await
{
self.state.lock().await.pending.remove(&id);
return Err(error);
}
match tokio::time::timeout(timeout, receiver).await {
Ok(Ok(result)) => result,
Ok(Err(_)) => Err("extension bridge disconnected".to_string()),
Err(_) => {
self.state.lock().await.pending.remove(&id);
Err("extension request timed out".to_string())
}
}
}
pub async fn status(&self, socket: String) -> ExtensionBridgeConnection {
let state = self.state.lock().await;
ExtensionBridgeConnection {
connected: state.writer.is_some(),
socket,
host_name: state.host_name.clone(),
extension_origin: state.extension_origin.clone(),
extension_id: state.extension_id.clone(),
version: state.version.clone(),
connected_at: state.connected_at,
last_seen_at: state.last_seen_at,
retained_events: state.events.len(),
}
}
pub async fn events(&self, after: u64, limit: usize) -> Vec<ExtensionEvent> {
self.state
.lock()
.await
.events
.iter()
.filter(|event| event.ts > after)
.take(limit.min(MAX_EXTENSION_EVENTS))
.cloned()
.collect()
}
async fn send_envelope(&self, envelope: Value) -> Result<(), String> {
let line = serde_json::to_string(&envelope).map_err(|error| error.to_string())?;
let mut state = self.state.lock().await;
let writer = state
.writer
.as_mut()
.ok_or_else(|| "Chrome extension bridge is not connected".to_string())?;
writer.send(line).await.map_err(|error| error.to_string())
}
}
#[cfg(test)]
mod tests {
use super::*;
use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader};
#[tokio::test]
async fn bridge_correlates_requests_and_retains_connection_state_and_events() {
let bridge = ExtensionBridge::default();
let (daemon, extension) = UnixStream::pair().unwrap();
let serving = {
let bridge = bridge.clone();
tokio::spawn(async move { bridge.serve_connection(daemon).await })
};
let (reader, mut writer) = extension.into_split();
let mut reader = BufReader::new(reader).lines();
writer
.write_all(b"{\"cmd\":\"ext.bridge.connect\",\"hostName\":\"com.douglance.apoc\",\"extensionOrigin\":\"chrome-extension://one/\"}\n")
.await
.unwrap();
assert_eq!(
serde_json::from_str::<Value>(&reader.next_line().await.unwrap().unwrap()).unwrap(),
json!({"v":1,"type":"ack","id":"bridge"})
);
writer
.write_all(
b"{\"v\":1,\"type\":\"hello\",\"extensionId\":\"one\",\"version\":\"0.5.0\"}\n",
)
.await
.unwrap();
writer
.write_all(b"{\"v\":1,\"type\":\"event\",\"event\":{\"ts\":7,\"kind\":\"route\",\"message\":\"ready\"}}\n")
.await
.unwrap();
let request = {
let bridge = bridge.clone();
tokio::spawn(async move {
bridge
.request(json!({"op":"tabs"}), Duration::from_secs(1))
.await
})
};
let envelope =
serde_json::from_str::<Value>(&reader.next_line().await.unwrap().unwrap()).unwrap();
assert_eq!(envelope["request"], json!({"op":"tabs"}));
writer
.write_all(
format!(
"{{\"v\":1,\"id\":{},\"type\":\"response\",\"ok\":true,\"result\":{{\"tabs\":[{{\"id\":3}}]}}}}\n",
serde_json::to_string(envelope["id"].as_str().unwrap()).unwrap()
)
.as_bytes(),
)
.await
.unwrap();
assert_eq!(request.await.unwrap().unwrap(), json!({"tabs":[{"id":3}]}));
tokio::task::yield_now().await;
let status = bridge.status("/tmp/apoc-extension.sock".to_string()).await;
assert!(status.connected);
assert_eq!(status.extension_id.as_deref(), Some("one"));
assert_eq!(bridge.events(0, 10).await.len(), 1);
drop(writer);
serving.await.unwrap().unwrap();
assert!(!bridge.status("socket".to_string()).await.connected);
}
#[test]
fn native_host_installation_writes_a_valid_distribution_manifest() {
let home = tempfile::tempdir().unwrap();
let host = home.path().join("apoc-chrome-native-host");
std::fs::write(&host, b"fixture").unwrap();
let installed = install_extension_host(
"chrome-for-testing",
"fixture_extension",
DEFAULT_EXTENSION_HOST_NAME,
Some(host.to_str().unwrap()),
Some(home.path().to_str().unwrap()),
None,
false,
)
.unwrap();
assert!(installed.installed);
assert_eq!(installed.manifest["path"], host.display().to_string());
assert_eq!(
installed.manifest["allowed_origins"][0],
format!("chrome-extension://{PACKAGED_EXTENSION_ID}/")
);
assert_eq!(
installed.manifest["allowed_origins"][1],
"chrome-extension://fixture_extension/"
);
assert_eq!(installed.extension_id, PACKAGED_EXTENSION_ID);
assert_eq!(installed.extension_assets.len(), 4);
assert!(
installed
.extension_assets
.iter()
.all(|asset| Path::new(&asset.path).is_file())
);
let doctor = extension_doctor(
"chrome-for-testing",
DEFAULT_EXTENSION_HOST_NAME,
Some(host.to_str().unwrap()),
Some(home.path().to_str().unwrap()),
None,
)
.unwrap();
assert!(doctor.manifest_exists);
assert!(doctor.manifest_valid);
assert!(doctor.host_exists);
assert!(doctor.extension_exists);
assert!(doctor.extension_valid);
assert_eq!(doctor.extension_id, PACKAGED_EXTENSION_ID);
assert!(doctor.issues.is_empty());
let replaced = install_extension_host(
"chrome-for-testing",
"fixture_extension",
DEFAULT_EXTENSION_HOST_NAME,
Some(host.to_str().unwrap()),
Some(home.path().to_str().unwrap()),
None,
false,
)
.unwrap();
assert!(
replaced
.manifest_backup
.as_deref()
.is_some_and(|path| Path::new(path).is_file())
);
let user_data_dir = home.path().join("isolated-profile");
let installed = install_extension_host(
"chrome-for-testing",
PACKAGED_EXTENSION_ID,
DEFAULT_EXTENSION_HOST_NAME,
Some(host.to_str().unwrap()),
Some(home.path().to_str().unwrap()),
Some(user_data_dir.to_str().unwrap()),
false,
)
.unwrap();
assert_eq!(
Path::new(&installed.manifest_path),
user_data_dir
.join("NativeMessagingHosts")
.join(format!("{DEFAULT_EXTENSION_HOST_NAME}.json"))
);
assert_eq!(installed.user_data_dir.as_deref(), user_data_dir.to_str());
}
}