Compare commits
1 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| e2daf81712 |
Generated
+27
-10
@@ -327,9 +327,16 @@ dependencies = [
|
|||||||
"syn 2.0.119",
|
"syn 2.0.119",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "custos-browser"
|
||||||
|
version = "0.9.0"
|
||||||
|
dependencies = [
|
||||||
|
"zeroize",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "custos-gen"
|
name = "custos-gen"
|
||||||
version = "0.10.0"
|
version = "0.9.0"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"custos-vault",
|
"custos-vault",
|
||||||
"data-encoding",
|
"data-encoding",
|
||||||
@@ -341,7 +348,7 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "custos-kdbx"
|
name = "custos-kdbx"
|
||||||
version = "0.10.0"
|
version = "0.9.0"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"aes",
|
"aes",
|
||||||
"argon2",
|
"argon2",
|
||||||
@@ -362,7 +369,7 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "custos-keys"
|
name = "custos-keys"
|
||||||
version = "0.10.0"
|
version = "0.9.0"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"custos-vault",
|
"custos-vault",
|
||||||
"ed25519-dalek",
|
"ed25519-dalek",
|
||||||
@@ -373,13 +380,23 @@ dependencies = [
|
|||||||
"thiserror",
|
"thiserror",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "custos-native"
|
||||||
|
version = "0.9.0"
|
||||||
|
dependencies = [
|
||||||
|
"custos-browser",
|
||||||
|
"serde_json",
|
||||||
|
"windows-sys",
|
||||||
|
"zeroize",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "custos-qr"
|
name = "custos-qr"
|
||||||
version = "0.10.0"
|
version = "0.9.0"
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "custos-seal"
|
name = "custos-seal"
|
||||||
version = "0.10.0"
|
version = "0.9.0"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"chacha20poly1305",
|
"chacha20poly1305",
|
||||||
"hkdf",
|
"hkdf",
|
||||||
@@ -392,7 +409,7 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "custos-share"
|
name = "custos-share"
|
||||||
version = "0.10.0"
|
version = "0.9.0"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"argon2",
|
"argon2",
|
||||||
"chacha20poly1305",
|
"chacha20poly1305",
|
||||||
@@ -409,7 +426,7 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "custos-sign"
|
name = "custos-sign"
|
||||||
version = "0.10.0"
|
version = "0.9.0"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"blake2 0.10.6",
|
"blake2 0.10.6",
|
||||||
"data-encoding",
|
"data-encoding",
|
||||||
@@ -426,7 +443,7 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "custos-totp"
|
name = "custos-totp"
|
||||||
version = "0.10.0"
|
version = "0.9.0"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"custos-vault",
|
"custos-vault",
|
||||||
"data-encoding",
|
"data-encoding",
|
||||||
@@ -439,7 +456,7 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "custos-vault"
|
name = "custos-vault"
|
||||||
version = "0.10.0"
|
version = "0.9.0"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"argon2",
|
"argon2",
|
||||||
"bip39",
|
"bip39",
|
||||||
@@ -463,7 +480,7 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "custos-wasm"
|
name = "custos-wasm"
|
||||||
version = "0.10.0"
|
version = "0.9.0"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"custos-qr",
|
"custos-qr",
|
||||||
"custos-seal",
|
"custos-seal",
|
||||||
|
|||||||
+1
-1
@@ -3,7 +3,7 @@ resolver = "3"
|
|||||||
members = ["crates/*"]
|
members = ["crates/*"]
|
||||||
|
|
||||||
[workspace.package]
|
[workspace.package]
|
||||||
version = "0.10.0"
|
version = "0.9.0"
|
||||||
edition = "2024"
|
edition = "2024"
|
||||||
license = "MPL-2.0"
|
license = "MPL-2.0"
|
||||||
repository = "https://gitea.marek-novak.cz/mnovak/CustosPublic"
|
repository = "https://gitea.marek-novak.cz/mnovak/CustosPublic"
|
||||||
|
|||||||
@@ -0,0 +1,10 @@
|
|||||||
|
[package]
|
||||||
|
name = "custos-browser"
|
||||||
|
description = "Custos in the browser: which login may be filled into which page, and Chrome's native messaging frames"
|
||||||
|
version.workspace = true
|
||||||
|
edition.workspace = true
|
||||||
|
license.workspace = true
|
||||||
|
repository.workspace = true
|
||||||
|
|
||||||
|
[dependencies]
|
||||||
|
zeroize.workspace = true
|
||||||
@@ -0,0 +1,66 @@
|
|||||||
|
//! Chrome's native messaging frames: a 32-bit length in native byte order (little-endian on every machine
|
||||||
|
//! Custos runs on), then that many bytes of UTF-8 JSON. Messages to the host are capped here at 64 KiB (the
|
||||||
|
//! desktop's pipe limit); Chrome itself refuses messages to the browser over 1 MB.
|
||||||
|
//!
|
||||||
|
//! Frames can hold a login's password: they are `Zeroizing`, so the bytes are wiped when dropped.
|
||||||
|
|
||||||
|
use std::io::{self, Read, Write};
|
||||||
|
|
||||||
|
use zeroize::Zeroizing;
|
||||||
|
|
||||||
|
/// The largest message the extension may send to the host.
|
||||||
|
pub const MAX_TO_HOST: usize = 64 * 1024;
|
||||||
|
/// The largest message Chrome accepts from a host.
|
||||||
|
pub const MAX_TO_BROWSER: usize = 1024 * 1024;
|
||||||
|
|
||||||
|
/// Reads one frame. `Ok(None)` when the browser closed the stream (the extension disconnected).
|
||||||
|
pub fn read_frame(r: &mut impl Read) -> io::Result<Option<Zeroizing<Vec<u8>>>> {
|
||||||
|
let mut len = [0u8; 4];
|
||||||
|
match r.read_exact(&mut len) {
|
||||||
|
Ok(()) => {}
|
||||||
|
Err(e) if e.kind() == io::ErrorKind::UnexpectedEof => return Ok(None),
|
||||||
|
Err(e) => return Err(e),
|
||||||
|
}
|
||||||
|
let n = u32::from_le_bytes(len) as usize;
|
||||||
|
if n > MAX_TO_HOST {
|
||||||
|
return Err(io::Error::new(io::ErrorKind::InvalidData, "message too large"));
|
||||||
|
}
|
||||||
|
let mut buf = Zeroizing::new(vec![0u8; n]);
|
||||||
|
r.read_exact(&mut buf)?;
|
||||||
|
Ok(Some(buf))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Writes one frame and flushes it (Chrome reads frame by frame).
|
||||||
|
pub fn write_frame(w: &mut impl Write, msg: &[u8]) -> io::Result<()> {
|
||||||
|
if msg.len() > MAX_TO_BROWSER {
|
||||||
|
return Err(io::Error::new(io::ErrorKind::InvalidData, "message too large"));
|
||||||
|
}
|
||||||
|
w.write_all(&(msg.len() as u32).to_le_bytes())?;
|
||||||
|
w.write_all(msg)?;
|
||||||
|
w.flush()
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn frames_round_trip_and_oversized_ones_are_refused() {
|
||||||
|
let mut out = Vec::new();
|
||||||
|
write_frame(&mut out, br#"{"op":"browser_status"}"#).unwrap();
|
||||||
|
write_frame(&mut out, b"{}").unwrap();
|
||||||
|
assert_eq!(&out[..4], &23u32.to_le_bytes());
|
||||||
|
let mut r = &out[..];
|
||||||
|
assert_eq!(read_frame(&mut r).unwrap().unwrap().as_slice(), br#"{"op":"browser_status"}"#);
|
||||||
|
assert_eq!(read_frame(&mut r).unwrap().unwrap().as_slice(), b"{}");
|
||||||
|
assert!(read_frame(&mut r).unwrap().is_none(), "end of stream is the extension going away");
|
||||||
|
// A length over the limit is refused before anything is allocated.
|
||||||
|
let big = ((MAX_TO_HOST + 1) as u32).to_le_bytes();
|
||||||
|
assert_eq!(read_frame(&mut &big[..]).unwrap_err().kind(), io::ErrorKind::InvalidData);
|
||||||
|
// A frame cut short is an error, not a short message.
|
||||||
|
let mut cut = 10u32.to_le_bytes().to_vec();
|
||||||
|
cut.extend_from_slice(b"{}");
|
||||||
|
assert!(read_frame(&mut &cut[..]).is_err());
|
||||||
|
assert!(write_frame(&mut Vec::new(), &vec![b' '; MAX_TO_BROWSER + 1]).is_err());
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,281 @@
|
|||||||
|
//! What the browser extension may fill where (docs/BROWSER.md). The extension and its native host live in
|
||||||
|
//! this public repository; the rules that decide which login goes into which page live here too, so the
|
||||||
|
//! desktop app and anyone reviewing the extension apply the same ones.
|
||||||
|
//!
|
||||||
|
//! - [`Origin`]: a page's origin as the browser reports it (never as the page claims).
|
||||||
|
//! - [`login_matches`]: does a login's stored URL belong to that origin? Its host or a subdomain of it,
|
||||||
|
//! same scheme, same port when the login names one. Never a "similar" name, so look-alike domains
|
||||||
|
//! (`paypa1.com`, `paypal.com.evil.net`) never match.
|
||||||
|
//! - [`framing`]: Chrome's native messaging frames (a 4-byte little-endian length, then JSON).
|
||||||
|
//!
|
||||||
|
//! ```
|
||||||
|
//! use custos_browser::{login_matches, Origin};
|
||||||
|
//! let page = Origin::parse("https://accounts.github.com/login?return=/")?;
|
||||||
|
//! assert!(login_matches("https://github.com", &page).is_some());
|
||||||
|
//! assert!(login_matches("https://github.com.evil.net", &page).is_none());
|
||||||
|
//! # Ok::<(), custos_browser::OriginError>(())
|
||||||
|
//! ```
|
||||||
|
|
||||||
|
pub mod framing;
|
||||||
|
|
||||||
|
use std::fmt;
|
||||||
|
|
||||||
|
/// A page's origin: scheme, host (lowercase, no trailing dot) and port (the scheme's default when absent).
|
||||||
|
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||||
|
pub struct Origin {
|
||||||
|
pub scheme: Scheme,
|
||||||
|
pub host: String,
|
||||||
|
pub port: u16,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||||
|
pub enum Scheme {
|
||||||
|
Https,
|
||||||
|
Http,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Scheme {
|
||||||
|
fn default_port(self) -> u16 {
|
||||||
|
match self {
|
||||||
|
Scheme::Https => 443,
|
||||||
|
Scheme::Http => 80,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, PartialEq, Eq)]
|
||||||
|
pub enum OriginError {
|
||||||
|
/// Not an `http(s)://host…` URL.
|
||||||
|
NotWeb,
|
||||||
|
/// A host that is empty, too long or has characters a host cannot have.
|
||||||
|
BadHost,
|
||||||
|
BadPort,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl fmt::Display for OriginError {
|
||||||
|
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||||
|
f.write_str(match self {
|
||||||
|
OriginError::NotWeb => "not a web address",
|
||||||
|
OriginError::BadHost => "not a valid host",
|
||||||
|
OriginError::BadPort => "not a valid port",
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl std::error::Error for OriginError {}
|
||||||
|
|
||||||
|
/// Splits `scheme://host:port/…` (userinfo refused: `https://bank.com@evil.net` must not read as bank.com).
|
||||||
|
fn split(url: &str, default: Option<Scheme>) -> Result<(Scheme, String, Option<u16>), OriginError> {
|
||||||
|
let url = url.trim();
|
||||||
|
let (scheme, rest) = match url.split_once("://") {
|
||||||
|
Some((s, rest)) => match s.to_ascii_lowercase().as_str() {
|
||||||
|
"https" => (Scheme::Https, rest),
|
||||||
|
"http" => (Scheme::Http, rest),
|
||||||
|
_ => return Err(OriginError::NotWeb),
|
||||||
|
},
|
||||||
|
None => (default.ok_or(OriginError::NotWeb)?, url),
|
||||||
|
};
|
||||||
|
let authority = rest.split(['/', '?', '#']).next().unwrap_or("");
|
||||||
|
if authority.contains('@') {
|
||||||
|
return Err(OriginError::BadHost);
|
||||||
|
}
|
||||||
|
let (host, port) = if let Some(v6) = authority.strip_prefix('[') {
|
||||||
|
let (h, after) = v6.split_once(']').ok_or(OriginError::BadHost)?;
|
||||||
|
(format!("[{}]", h.to_ascii_lowercase()), after.strip_prefix(':'))
|
||||||
|
} else {
|
||||||
|
match authority.rsplit_once(':') {
|
||||||
|
Some((h, p)) => (h.to_ascii_lowercase(), Some(p)),
|
||||||
|
None => (authority.to_ascii_lowercase(), None),
|
||||||
|
}
|
||||||
|
};
|
||||||
|
let host = host.trim_end_matches('.').to_string();
|
||||||
|
let ok = |c: char| c.is_ascii_alphanumeric() || matches!(c, '-' | '.' | '_' | '[' | ']' | ':');
|
||||||
|
if host.is_empty() || host.len() > 253 || !host.chars().all(ok) || host.contains("..") {
|
||||||
|
return Err(OriginError::BadHost);
|
||||||
|
}
|
||||||
|
let port = match port {
|
||||||
|
None | Some("") => None,
|
||||||
|
Some(p) => Some(
|
||||||
|
p.parse::<u16>()
|
||||||
|
.map_err(|_| OriginError::BadPort)
|
||||||
|
.and_then(|n| if n == 0 { Err(OriginError::BadPort) } else { Ok(n) })?,
|
||||||
|
),
|
||||||
|
};
|
||||||
|
Ok((scheme, host, port))
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Origin {
|
||||||
|
/// A page URL as the browser reports it (`sender.url`, the tab's URL).
|
||||||
|
pub fn parse(url: &str) -> Result<Origin, OriginError> {
|
||||||
|
let (scheme, host, port) = split(url, None)?;
|
||||||
|
Ok(Origin { scheme, port: port.unwrap_or(scheme.default_port()), host })
|
||||||
|
}
|
||||||
|
|
||||||
|
fn is_loopback(&self) -> bool {
|
||||||
|
self.host == "localhost"
|
||||||
|
|| self.host.ends_with(".localhost")
|
||||||
|
|| self.host == "127.0.0.1"
|
||||||
|
|| self.host == "[::1]"
|
||||||
|
}
|
||||||
|
|
||||||
|
fn is_ip(&self) -> bool {
|
||||||
|
self.host.starts_with('[')
|
||||||
|
|| self.host.split('.').all(|l| !l.is_empty() && l.chars().all(|c| c.is_ascii_digit()))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// May a login be filled into this page at all? Only over https, or plain http on this machine.
|
||||||
|
pub fn fillable(&self) -> bool {
|
||||||
|
self.scheme == Scheme::Https || self.is_loopback()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl fmt::Display for Origin {
|
||||||
|
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||||
|
let scheme = match self.scheme {
|
||||||
|
Scheme::Https => "https",
|
||||||
|
Scheme::Http => "http",
|
||||||
|
};
|
||||||
|
if self.port == self.scheme.default_port() {
|
||||||
|
write!(f, "{scheme}://{}", self.host)
|
||||||
|
} else {
|
||||||
|
write!(f, "{scheme}://{}:{}", self.host, self.port)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// How well a login's URL fits a page, best first.
|
||||||
|
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
|
||||||
|
pub enum Match {
|
||||||
|
/// The page is on the login's host itself (`www.` counts as the host).
|
||||||
|
Exact,
|
||||||
|
/// The page is on a subdomain of the login's host (`accounts.github.com` for `github.com`).
|
||||||
|
Subdomain,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Does the login stored with `item_url` belong on `page`? `None` when it must not be offered there.
|
||||||
|
///
|
||||||
|
/// A stored URL without a scheme (`github.com/login`) means https. The page must be fillable, the schemes
|
||||||
|
/// equal, the port equal when the stored URL names one (else the page's must be the scheme's default), and
|
||||||
|
/// the page's host the login's host or a subdomain of it. A login for a bare top-level name (`com`) or for
|
||||||
|
/// an IP address matches only that exact host.
|
||||||
|
pub fn login_matches(item_url: &str, page: &Origin) -> Option<Match> {
|
||||||
|
if !page.fillable() {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
let (scheme, host, port) = split(item_url, Some(Scheme::Https)).ok()?;
|
||||||
|
if scheme != page.scheme || port.unwrap_or(scheme.default_port()) != page.port {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
let strip = |h: &str| h.strip_prefix("www.").map(str::to_string).unwrap_or_else(|| h.to_string());
|
||||||
|
let (item, at) = (strip(&host), strip(&page.host));
|
||||||
|
if item == at {
|
||||||
|
return Some(Match::Exact);
|
||||||
|
}
|
||||||
|
if page.is_ip() || !item.contains('.') || item.starts_with('[') {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
at.strip_suffix(&item).filter(|rest| rest.ends_with('.')).map(|_| Match::Subdomain)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The best match among a login's URLs.
|
||||||
|
pub fn best_match<'a>(urls: impl IntoIterator<Item = &'a str>, page: &Origin) -> Option<Match> {
|
||||||
|
urls.into_iter().filter_map(|u| login_matches(u, page)).min()
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
fn page(u: &str) -> Origin {
|
||||||
|
Origin::parse(u).unwrap()
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn origins_parse_as_the_browser_reports_them() {
|
||||||
|
assert_eq!(
|
||||||
|
page("https://GitHub.com./login?x=1#y"),
|
||||||
|
Origin { scheme: Scheme::Https, host: "github.com".into(), port: 443 }
|
||||||
|
);
|
||||||
|
assert_eq!(page("http://localhost:5173/").port, 5173);
|
||||||
|
assert_eq!(page("https://[::1]:8443/").host, "[::1]");
|
||||||
|
assert_eq!(page("https://bank.cz").to_string(), "https://bank.cz");
|
||||||
|
assert_eq!(page("http://127.0.0.1:8080/a").to_string(), "http://127.0.0.1:8080");
|
||||||
|
for bad in [
|
||||||
|
"ftp://x.cz",
|
||||||
|
"file:///C:/a.html",
|
||||||
|
"chrome-extension://abc/",
|
||||||
|
"javascript:alert(1)",
|
||||||
|
"about:blank",
|
||||||
|
"https://",
|
||||||
|
"https://a..b.cz/",
|
||||||
|
"https://bank.cz:99999/",
|
||||||
|
"https://bank.cz:0/",
|
||||||
|
"https://bad host.cz/",
|
||||||
|
] {
|
||||||
|
assert!(Origin::parse(bad).is_err(), "{bad}");
|
||||||
|
}
|
||||||
|
// Userinfo is refused outright: it is how look-alike links hide their real host.
|
||||||
|
assert_eq!(Origin::parse("https://bank.cz@evil.net/"), Err(OriginError::BadHost));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_login_matches_its_host_and_its_subdomains_only() {
|
||||||
|
let gh = page("https://github.com/login");
|
||||||
|
assert_eq!(login_matches("https://github.com", &gh), Some(Match::Exact));
|
||||||
|
assert_eq!(login_matches("github.com/login", &gh), Some(Match::Exact), "no scheme means https");
|
||||||
|
assert_eq!(login_matches("https://www.github.com/", &gh), Some(Match::Exact));
|
||||||
|
assert_eq!(login_matches("https://github.com", &page("https://www.github.com/")), Some(Match::Exact));
|
||||||
|
assert_eq!(login_matches("https://github.com", &page("https://gist.github.com/")), Some(Match::Subdomain));
|
||||||
|
// A login for a subdomain does not go to its parent or its siblings.
|
||||||
|
assert_eq!(login_matches("https://gist.github.com", &gh), None);
|
||||||
|
assert_eq!(login_matches("https://gist.github.com", &page("https://api.github.com/")), None);
|
||||||
|
// Look-alikes never match.
|
||||||
|
for evil in [
|
||||||
|
"https://github.com.evil.net/",
|
||||||
|
"https://evilgithub.com/",
|
||||||
|
"https://github.co/",
|
||||||
|
"https://githuh.com/",
|
||||||
|
"https://xn--gthub-cta.com/",
|
||||||
|
] {
|
||||||
|
assert_eq!(login_matches("https://github.com", &page(evil)), None, "{evil}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn scheme_port_and_plain_http_are_strict() {
|
||||||
|
// Never over plain http on the internet, even for a login saved with http.
|
||||||
|
assert_eq!(login_matches("http://intranet.example", &page("http://intranet.example/")), None);
|
||||||
|
// On this machine plain http is fine, with the port the login names.
|
||||||
|
assert_eq!(login_matches("http://localhost:5173", &page("http://localhost:5173/login")), Some(Match::Exact));
|
||||||
|
assert_eq!(login_matches("http://localhost:5173", &page("http://localhost:8080/")), None);
|
||||||
|
assert_eq!(login_matches("http://localhost", &page("http://localhost:8080/")), None);
|
||||||
|
// An https login does not go to the http page of the same host, nor the other way round.
|
||||||
|
assert_eq!(login_matches("https://localhost", &page("http://localhost/")), None);
|
||||||
|
assert_eq!(
|
||||||
|
login_matches("https://nas.home.arpa:5001", &page("https://nas.home.arpa:5001/")),
|
||||||
|
Some(Match::Exact)
|
||||||
|
);
|
||||||
|
assert_eq!(login_matches("https://nas.home.arpa:5001", &page("https://nas.home.arpa/")), None);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn bare_names_and_addresses_match_exactly_only() {
|
||||||
|
assert_eq!(login_matches("https://192.168.1.1", &page("https://192.168.1.1/")), Some(Match::Exact));
|
||||||
|
assert_eq!(login_matches("https://168.1.1", &page("https://192.168.1.1/")), None);
|
||||||
|
assert_eq!(login_matches("https://cz", &page("https://bank.cz/")), None);
|
||||||
|
assert_eq!(login_matches("https://[::1]", &page("https://[::1]/")), Some(Match::Exact));
|
||||||
|
assert_eq!(login_matches("not a url at all", &page("https://bank.cz/")), None);
|
||||||
|
assert_eq!(login_matches("", &page("https://bank.cz/")), None);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn the_best_of_several_urls_wins() {
|
||||||
|
let p = page("https://www.github.com/");
|
||||||
|
assert_eq!(best_match(["https://gitlab.com", "https://github.com"], &p), Some(Match::Exact));
|
||||||
|
assert_eq!(best_match(["https://gitlab.com"], &p), None);
|
||||||
|
assert_eq!(
|
||||||
|
best_match(["https://github.com", "https://www.github.com"], &page("https://gist.github.com/")),
|
||||||
|
Some(Match::Subdomain)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,15 @@
|
|||||||
|
[package]
|
||||||
|
name = "custos-native"
|
||||||
|
description = "Custos's native messaging host: the browser extension's way to the desktop Custos"
|
||||||
|
version.workspace = true
|
||||||
|
edition.workspace = true
|
||||||
|
license.workspace = true
|
||||||
|
repository.workspace = true
|
||||||
|
|
||||||
|
[dependencies]
|
||||||
|
custos-browser = { path = "../custos-browser" }
|
||||||
|
serde_json.workspace = true
|
||||||
|
zeroize.workspace = true
|
||||||
|
|
||||||
|
[target.'cfg(windows)'.dependencies]
|
||||||
|
windows-sys = { version = "0.61", features = ["Win32_Foundation", "Win32_Security", "Win32_Storage_FileSystem", "Win32_System_IO", "Win32_System_Pipes", "Win32_System_Threading"] }
|
||||||
@@ -0,0 +1,240 @@
|
|||||||
|
//! custos-native: the browser extension's native messaging host (docs/BROWSER.md). Edge or Chrome starts it
|
||||||
|
//! when the extension connects, and talks to it over stdin/stdout in native messaging frames. It forwards
|
||||||
|
//! three requests to the desktop Custos over its Domi pipe and returns the answers:
|
||||||
|
//!
|
||||||
|
//! - `browser_status`: is Custos running and unlocked;
|
||||||
|
//! - `browser_match { origin }`: the logins for a page (title, username; never a password);
|
||||||
|
//! - `browser_fill { id, origin }`: one login's username, password and 2FA code, when it matches the page.
|
||||||
|
//!
|
||||||
|
//! The host adds nothing and decides nothing: Custos checks the origin against the login and asks the
|
||||||
|
//! user once whether this host may use web logins. It forwards only those three requests, rebuilt from
|
||||||
|
//! their known fields, so the extension cannot reach Custos's other Domi requests through it. It refuses
|
||||||
|
//! a pipe that is not served by custos.exe.
|
||||||
|
|
||||||
|
use std::io::{self, Write};
|
||||||
|
|
||||||
|
use custos_browser::framing::{read_frame, write_frame};
|
||||||
|
use serde_json::{Value, json};
|
||||||
|
use zeroize::Zeroizing;
|
||||||
|
|
||||||
|
const PIPE: &str = r"\\.\pipe\custos-domi";
|
||||||
|
const OPS: &[&str] = &["browser_status", "browser_match", "browser_fill"];
|
||||||
|
|
||||||
|
/// The request Custos gets: only known fields, of the right types.
|
||||||
|
fn rebuild(msg: &[u8]) -> Result<Value, &'static str> {
|
||||||
|
let v: Value = serde_json::from_slice(msg).map_err(|_| "bad_request")?;
|
||||||
|
let op = v.get("op").and_then(Value::as_str).filter(|o| OPS.contains(o)).ok_or("bad_request")?;
|
||||||
|
let mut out = json!({ "op": op, "app": "Custos for your browser" });
|
||||||
|
if op != "browser_status" {
|
||||||
|
let origin = v.get("origin").and_then(Value::as_str).filter(|o| o.len() <= 2048).ok_or("bad_request")?;
|
||||||
|
out["origin"] = origin.into();
|
||||||
|
}
|
||||||
|
if op == "browser_fill" {
|
||||||
|
let id = v.get("id").and_then(Value::as_str).filter(|i| i.len() <= 128).ok_or("bad_request")?;
|
||||||
|
out["id"] = id.into();
|
||||||
|
}
|
||||||
|
// The extension's own request number comes back with the answer, so it can pair them.
|
||||||
|
if let Some(n) = v.get("seq").and_then(Value::as_u64) {
|
||||||
|
out["seq"] = n.into();
|
||||||
|
}
|
||||||
|
Ok(out)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn error(code: &str, seq: Option<u64>) -> Vec<u8> {
|
||||||
|
serde_json::to_vec(&json!({ "ok": false, "error": code, "seq": seq })).unwrap_or_default()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn answer(msg: &[u8], pipe: &str) -> Zeroizing<Vec<u8>> {
|
||||||
|
let seq = serde_json::from_slice::<Value>(msg).ok().and_then(|v| v.get("seq").and_then(Value::as_u64));
|
||||||
|
let req = match rebuild(msg) {
|
||||||
|
Ok(r) => r,
|
||||||
|
Err(code) => return Zeroizing::new(error(code, seq)),
|
||||||
|
};
|
||||||
|
let bytes = Zeroizing::new(serde_json::to_vec(&req).unwrap_or_default());
|
||||||
|
match pipe::call(pipe, &bytes) {
|
||||||
|
Ok(resp) => {
|
||||||
|
// Custos does not know the extension's request number: put it back.
|
||||||
|
let Ok(mut v) = serde_json::from_slice::<Value>(&resp) else {
|
||||||
|
return Zeroizing::new(error("bad_answer", seq));
|
||||||
|
};
|
||||||
|
if let (Some(obj), Some(n)) = (v.as_object_mut(), seq) {
|
||||||
|
obj.insert("seq".into(), n.into());
|
||||||
|
}
|
||||||
|
let out = Zeroizing::new(serde_json::to_vec(&v).unwrap_or_default());
|
||||||
|
zeroize_json(v);
|
||||||
|
out
|
||||||
|
}
|
||||||
|
Err(code) => Zeroizing::new(error(code, seq)),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Wipes the strings of a parsed answer (it can hold a password) before dropping it.
|
||||||
|
fn zeroize_json(v: Value) {
|
||||||
|
use zeroize::Zeroize;
|
||||||
|
match v {
|
||||||
|
Value::String(mut s) => s.zeroize(),
|
||||||
|
Value::Array(a) => a.into_iter().for_each(zeroize_json),
|
||||||
|
Value::Object(o) => o.into_iter().for_each(|(_, v)| zeroize_json(v)),
|
||||||
|
_ => {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn main() {
|
||||||
|
// Tests point the host at another Custos.
|
||||||
|
let pipe = std::env::var("CUSTOS_PIPE").unwrap_or_else(|_| PIPE.to_string());
|
||||||
|
let (mut stdin, stdout) = (io::stdin().lock(), io::stdout());
|
||||||
|
loop {
|
||||||
|
let msg = match read_frame(&mut stdin) {
|
||||||
|
Ok(Some(m)) => m,
|
||||||
|
// The extension disconnected, or sent something that is not a frame: done.
|
||||||
|
Ok(None) | Err(_) => return,
|
||||||
|
};
|
||||||
|
let out = answer(&msg, &pipe);
|
||||||
|
let mut w = stdout.lock();
|
||||||
|
if write_frame(&mut w, &out).is_err() || w.flush().is_err() {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(windows)]
|
||||||
|
mod pipe {
|
||||||
|
use std::time::Duration;
|
||||||
|
|
||||||
|
use windows_sys::Win32::Foundation::{
|
||||||
|
CloseHandle, ERROR_FILE_NOT_FOUND, ERROR_PIPE_BUSY, GENERIC_READ, GENERIC_WRITE, GetLastError, HANDLE,
|
||||||
|
INVALID_HANDLE_VALUE,
|
||||||
|
};
|
||||||
|
use windows_sys::Win32::Storage::FileSystem::{CreateFileW, OPEN_EXISTING, ReadFile, WriteFile};
|
||||||
|
use windows_sys::Win32::System::Pipes::{
|
||||||
|
GetNamedPipeServerProcessId, PIPE_READMODE_MESSAGE, SetNamedPipeHandleState, WaitNamedPipeW,
|
||||||
|
};
|
||||||
|
use windows_sys::Win32::System::Threading::{
|
||||||
|
OpenProcess, PROCESS_QUERY_LIMITED_INFORMATION, QueryFullProcessImageNameW,
|
||||||
|
};
|
||||||
|
use zeroize::Zeroizing;
|
||||||
|
|
||||||
|
struct Handle(HANDLE);
|
||||||
|
impl Drop for Handle {
|
||||||
|
fn drop(&mut self) {
|
||||||
|
unsafe { CloseHandle(self.0) };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn wide(s: &str) -> Vec<u16> {
|
||||||
|
s.encode_utf16().chain(Some(0)).collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn server_exe(h: HANDLE) -> Option<String> {
|
||||||
|
unsafe {
|
||||||
|
let mut pid = 0u32;
|
||||||
|
if GetNamedPipeServerProcessId(h, &mut pid) == 0 {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
let p = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, 0, pid);
|
||||||
|
if p.is_null() {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
let p = Handle(p);
|
||||||
|
let mut buf = vec![0u16; 1024];
|
||||||
|
let mut len = buf.len() as u32;
|
||||||
|
let ok = QueryFullProcessImageNameW(p.0, 0, buf.as_mut_ptr(), &mut len);
|
||||||
|
(ok != 0).then(|| String::from_utf16_lossy(&buf[..len as usize]))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// One request, one answer. The error is a code the extension shows as a sentence.
|
||||||
|
pub fn call(name: &str, request: &[u8]) -> Result<Zeroizing<Vec<u8>>, &'static str> {
|
||||||
|
let w = wide(name);
|
||||||
|
unsafe {
|
||||||
|
let mut h = INVALID_HANDLE_VALUE;
|
||||||
|
// Busy: every instance is in use. Not found: Custos is between instances for a moment, or not running.
|
||||||
|
for _ in 0..50 {
|
||||||
|
h = CreateFileW(
|
||||||
|
w.as_ptr(),
|
||||||
|
GENERIC_READ | GENERIC_WRITE,
|
||||||
|
0,
|
||||||
|
std::ptr::null(),
|
||||||
|
OPEN_EXISTING,
|
||||||
|
0,
|
||||||
|
std::ptr::null_mut(),
|
||||||
|
);
|
||||||
|
if h != INVALID_HANDLE_VALUE {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
match GetLastError() {
|
||||||
|
ERROR_PIPE_BUSY => {
|
||||||
|
WaitNamedPipeW(w.as_ptr(), 200);
|
||||||
|
}
|
||||||
|
ERROR_FILE_NOT_FOUND => std::thread::sleep(Duration::from_millis(20)),
|
||||||
|
_ => break,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if h == INVALID_HANDLE_VALUE {
|
||||||
|
return Err("not_running");
|
||||||
|
}
|
||||||
|
let h = Handle(h);
|
||||||
|
// Anything else serving this pipe could collect passwords: only custos.exe gets the request.
|
||||||
|
if !server_exe(h.0).unwrap_or_default().to_lowercase().ends_with("\\custos.exe") {
|
||||||
|
return Err("not_custos");
|
||||||
|
}
|
||||||
|
let mode = PIPE_READMODE_MESSAGE;
|
||||||
|
SetNamedPipeHandleState(h.0, &mode, std::ptr::null(), std::ptr::null());
|
||||||
|
let mut n = 0u32;
|
||||||
|
if WriteFile(h.0, request.as_ptr(), request.len() as u32, &mut n, std::ptr::null_mut()) == 0 {
|
||||||
|
return Err("not_running");
|
||||||
|
}
|
||||||
|
let mut buf = Zeroizing::new(vec![0u8; 64 * 1024]);
|
||||||
|
if ReadFile(h.0, buf.as_mut_ptr(), buf.len() as u32, &mut n, std::ptr::null_mut()) == 0 {
|
||||||
|
return Err("no_answer");
|
||||||
|
}
|
||||||
|
buf.truncate(n as usize);
|
||||||
|
Ok(buf)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(not(windows))]
|
||||||
|
mod pipe {
|
||||||
|
pub fn call(_: &str, _: &[u8]) -> Result<zeroize::Zeroizing<Vec<u8>>, &'static str> {
|
||||||
|
Err("not_running")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn only_the_three_browser_requests_pass_rebuilt_from_known_fields() {
|
||||||
|
let fill = rebuild(br#"{"op":"browser_fill","id":"abc","origin":"https://github.com","seq":7,"ref":"domi://arca/x","namespace":"arca"}"#).unwrap();
|
||||||
|
assert_eq!(
|
||||||
|
fill,
|
||||||
|
json!({ "op": "browser_fill", "id": "abc", "origin": "https://github.com", "seq": 7, "app": "Custos for your browser" })
|
||||||
|
);
|
||||||
|
assert_eq!(rebuild(br#"{"op":"browser_status"}"#).unwrap()["op"], "browser_status");
|
||||||
|
assert!(rebuild(br#"{"op":"browser_match","origin":"https://a.cz"}"#).is_ok());
|
||||||
|
// Custos's other Domi requests never pass through the browser's host.
|
||||||
|
for other in [
|
||||||
|
r#"{"op":"get","ref":"domi://arca/rclone-config-pass"}"#,
|
||||||
|
r#"{"op":"list","namespace":"arca"}"#,
|
||||||
|
r#"{"op":"set","ref":"domi://x/y","value":"v"}"#,
|
||||||
|
r#"{"op":"subkey"}"#,
|
||||||
|
] {
|
||||||
|
assert_eq!(rebuild(other.as_bytes()), Err("bad_request"), "{other}");
|
||||||
|
}
|
||||||
|
// Missing or wrong fields.
|
||||||
|
assert!(rebuild(br#"{"op":"browser_fill","origin":"https://a.cz"}"#).is_err());
|
||||||
|
assert!(rebuild(br#"{"op":"browser_match","origin":5}"#).is_err());
|
||||||
|
assert!(rebuild(b"not json").is_err());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn without_custos_the_answer_says_so_and_keeps_the_request_number() {
|
||||||
|
let out = answer(br#"{"op":"browser_status","seq":3}"#, r"\\.\pipe\custos-test-nobody-here");
|
||||||
|
let v: Value = serde_json::from_slice(&out).unwrap();
|
||||||
|
assert_eq!(v, json!({ "ok": false, "error": "not_running", "seq": 3 }));
|
||||||
|
let bad: Value = serde_json::from_slice(&answer(br#"{"op":"get","seq":4}"#, PIPE)).unwrap();
|
||||||
|
assert_eq!(bad, json!({ "ok": false, "error": "bad_request", "seq": 4 }));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,6 +1,5 @@
|
|||||||
//! The Domi identity's root key (docs/IDENTITY.md). It lives in the vault body and never leaves it: nothing
|
//! The Domi identity's root key (docs/IDENTITY.md). It lives in the vault body and never leaves it: nothing
|
||||||
//! here or on [`Vault`] returns it, and the vault signs nothing with it but subkey certificates and
|
//! here or on [`Vault`] returns it, and the vault signs nothing with it but subkey certificates.
|
||||||
//! revocations of keys the person revoked. It derives each app's backup secret from it.
|
|
||||||
//!
|
//!
|
||||||
//! Creating it is a typestate, so the mnemonic is always shown before the root exists:
|
//! Creating it is a typestate, so the mnemonic is always shown before the root exists:
|
||||||
//!
|
//!
|
||||||
@@ -47,13 +46,6 @@ use zeroize::Zeroizing;
|
|||||||
/// The root signs `CERT_DOMAIN ‖ tbs`, and only a `tbs` that starts with `CERT_MAGIC ‖ its public key`.
|
/// The root signs `CERT_DOMAIN ‖ tbs`, and only a `tbs` that starts with `CERT_MAGIC ‖ its public key`.
|
||||||
const CERT_DOMAIN: &[u8] = b"tessera cert v1\0";
|
const CERT_DOMAIN: &[u8] = b"tessera cert v1\0";
|
||||||
const CERT_MAGIC: &[u8] = b"TSC1";
|
const CERT_MAGIC: &[u8] = b"TSC1";
|
||||||
/// And `REVOKE_DOMAIN ‖ tbs`, only for a `tbs` that starts with `REVOKE_MAGIC ‖ its public key ‖ a key the
|
|
||||||
/// person revoked ‖ that key's revoked_at` (Fundamentum docs/TESSERA.md §12).
|
|
||||||
const REVOKE_DOMAIN: &[u8] = b"tessera revoke v1\0";
|
|
||||||
const REVOKE_MAGIC: &[u8] = b"TRV1";
|
|
||||||
/// magic 4, root 32, subkey 32, revoked_at 8, part 2, parts 2, count 4.
|
|
||||||
const REVOKE_HEADER: usize = 84;
|
|
||||||
const BACKUP_SALT: &[u8] = b"tessera backup v1";
|
|
||||||
const WORDS: usize = 24;
|
const WORDS: usize = 24;
|
||||||
|
|
||||||
/// Step 1: fresh entropy. Nothing is derived from it until the words have been shown.
|
/// Step 1: fresh entropy. Nothing is derived from it until the words have been shown.
|
||||||
@@ -119,26 +111,6 @@ impl Enrollment {
|
|||||||
display(&words);
|
display(&words);
|
||||||
Shown { entropy: self.entropy, challenge: random_challenge() }
|
Shown { entropy: self.entropy, challenge: random_challenge() }
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Restores an identity from its whole phrase, typed back (docs/IDENTITY.md, "Restoring it"): all 24
|
|
||||||
/// words prove more than three. Any case, any spacing. Anything that is not 24 English BIP39 words with a
|
|
||||||
/// valid checksum is [`Error::NotAMnemonic`], which names no word.
|
|
||||||
pub fn restore(phrase: &str) -> Result<Confirmed, Error> {
|
|
||||||
// Room for lowercasing without a reallocation that would leave a copy behind.
|
|
||||||
let mut joined = Zeroizing::new(String::with_capacity(phrase.len() * 3 + 1));
|
|
||||||
for (i, w) in phrase.split_whitespace().enumerate() {
|
|
||||||
if i > 0 {
|
|
||||||
joined.push(' ');
|
|
||||||
}
|
|
||||||
joined.extend(w.chars().flat_map(char::to_lowercase));
|
|
||||||
}
|
|
||||||
if joined.split(' ').count() != WORDS {
|
|
||||||
return Err(Error::NotAMnemonic);
|
|
||||||
}
|
|
||||||
let m =
|
|
||||||
bip39::Mnemonic::parse_in_normalized(bip39::Language::English, &joined).map_err(|_| Error::NotAMnemonic)?;
|
|
||||||
Ok(Confirmed { secret: crypto::domi_root_secret(&m) })
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Shown {
|
impl Shown {
|
||||||
@@ -193,7 +165,7 @@ impl fmt::Debug for Confirmed {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// A cert the vault signed, for display (docs/IDENTITY.md). A record, not a trust list.
|
/// A cert the vault signed, for display (docs/IDENTITY.md). A record, not a trust list.
|
||||||
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
|
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
pub struct Issued {
|
pub struct Issued {
|
||||||
/// `app` or `device`.
|
/// `app` or `device`.
|
||||||
pub kind: String,
|
pub kind: String,
|
||||||
@@ -208,12 +180,6 @@ pub struct Issued {
|
|||||||
pub not_after: u64,
|
pub not_after: u64,
|
||||||
/// Unix milliseconds.
|
/// Unix milliseconds.
|
||||||
pub issued: i64,
|
pub issued: i64,
|
||||||
/// Unix seconds: when the person revoked the key (core 0.10.0).
|
|
||||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
|
||||||
pub revoked_at: Option<u64>,
|
|
||||||
/// The signed `TRV1` statements, base64url, once an app sent the events to keep.
|
|
||||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
|
||||||
pub revocation: Vec<String>,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The identity in an unlocked vault.
|
/// The identity in an unlocked vault.
|
||||||
@@ -246,45 +212,6 @@ impl Root {
|
|||||||
Ok(crypto::ed25519_sign(&self.secret, &msg))
|
Ok(crypto::ed25519_sign(&self.secret, &msg))
|
||||||
}
|
}
|
||||||
|
|
||||||
pub(crate) fn sign_revocation(&self, tbs: &[u8]) -> Result<[u8; 64], Error> {
|
|
||||||
let names_me = tbs.len() >= REVOKE_HEADER && &tbs[..4] == REVOKE_MAGIC && tbs[4..36] == self.public;
|
|
||||||
if !names_me {
|
|
||||||
return Err(Error::NotARevocation);
|
|
||||||
}
|
|
||||||
let subkey = data_encoding::BASE64URL_NOPAD.encode(&tbs[36..68]);
|
|
||||||
let at = u64::from_be_bytes(tbs[68..76].try_into().expect("8 bytes"));
|
|
||||||
if !self.issued.iter().any(|i| i.subkey == subkey && i.revoked_at == Some(at)) {
|
|
||||||
return Err(Error::NotARevocation);
|
|
||||||
}
|
|
||||||
let msg = Zeroizing::new([REVOKE_DOMAIN, tbs].concat());
|
|
||||||
Ok(crypto::ed25519_sign(&self.secret, &msg))
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Marks every cert of `subkey` revoked; keeps the earliest time if one was marked before.
|
|
||||||
pub(crate) fn mark_revoked(&mut self, subkey: &str, at: u64) -> Result<u64, Error> {
|
|
||||||
let mut certs = self.issued.iter().filter(|i| i.subkey == subkey).peekable();
|
|
||||||
if certs.peek().is_none() {
|
|
||||||
return Err(Error::UnknownKey);
|
|
||||||
}
|
|
||||||
let at = certs.filter_map(|i| i.revoked_at).min().unwrap_or(at);
|
|
||||||
self.issued.iter_mut().filter(|i| i.subkey == subkey).for_each(|i| i.revoked_at = Some(at));
|
|
||||||
Ok(at)
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(crate) fn record_revocation(&mut self, subkey: &str, statements: Vec<String>) -> Result<(), Error> {
|
|
||||||
let mut certs = self.issued.iter_mut().filter(|i| i.subkey == subkey).peekable();
|
|
||||||
if certs.peek().is_none() {
|
|
||||||
return Err(Error::UnknownKey);
|
|
||||||
}
|
|
||||||
certs.for_each(|i| i.revocation = statements.clone());
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
/// `HKDF-SHA256(salt "tessera backup v1", ikm = root secret, info = app id)` (docs/IDENTITY.md).
|
|
||||||
pub(crate) fn backup_secret(&self, app_id: &str) -> Zeroizing<[u8; KEY_LEN]> {
|
|
||||||
crypto::hkdf(self.secret.as_ref(), BACKUP_SALT, app_id.as_bytes())
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(crate) fn json(&self) -> RootJson {
|
pub(crate) fn json(&self) -> RootJson {
|
||||||
RootJson {
|
RootJson {
|
||||||
root: SecretString::new(hex(self.secret.as_ref())),
|
root: SecretString::new(hex(self.secret.as_ref())),
|
||||||
|
|||||||
@@ -71,12 +71,6 @@ pub enum Error {
|
|||||||
NotACert,
|
NotACert,
|
||||||
#[error("those words are not the ones in the recovery phrase")]
|
#[error("those words are not the ones in the recovery phrase")]
|
||||||
WrongWords,
|
WrongWords,
|
||||||
#[error("these are not the 24 words of a recovery phrase: check each word and their order")]
|
|
||||||
NotAMnemonic,
|
|
||||||
#[error("the Domi identity signs a revocation only for a key revoked in Custos, at the time it was revoked")]
|
|
||||||
NotARevocation,
|
|
||||||
#[error("the Domi identity did not certify this key")]
|
|
||||||
UnknownKey,
|
|
||||||
#[error("this vault already has {0} signing keys")]
|
#[error("this vault already has {0} signing keys")]
|
||||||
SigningExists(&'static str),
|
SigningExists(&'static str),
|
||||||
#[error("signing keys: {0}")]
|
#[error("signing keys: {0}")]
|
||||||
@@ -834,27 +828,4 @@ impl Vault {
|
|||||||
self.identity.as_mut().ok_or(Error::NoIdentity)?.issued.push(issued);
|
self.identity.as_mut().ok_or(Error::NoIdentity)?.issued.push(issued);
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The person revoked the key `subkey` (base64url): marks every cert of it. Returns the revocation time in
|
|
||||||
/// effect, the earlier one if it was marked before. The caller saves the vault.
|
|
||||||
pub fn domi_mark_revoked(&mut self, subkey: &str, revoked_at: u64) -> Result<u64, Error> {
|
|
||||||
self.identity.as_mut().ok_or(Error::NoIdentity)?.mark_revoked(subkey, revoked_at)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Ed25519 with the root over `"tessera revoke v1\0" ‖ tbs`, for a `tbs` that starts with `TRV1`, this
|
|
||||||
/// root's public key, a key marked revoked and its `revoked_at` ([`Error::NotARevocation`] otherwise).
|
|
||||||
pub fn domi_sign_revocation(&self, tbs: &[u8]) -> Result<[u8; 64], Error> {
|
|
||||||
self.identity.as_ref().ok_or(Error::NoIdentity)?.sign_revocation(tbs)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Keeps the signed statements (base64url `TRV1`) with every cert of `subkey`. The caller saves the vault.
|
|
||||||
pub fn domi_record_revocation(&mut self, subkey: &str, statements: Vec<String>) -> Result<(), Error> {
|
|
||||||
self.identity.as_mut().ok_or(Error::NoIdentity)?.record_revocation(subkey, statements)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The backup secret of the app `app_id` (docs/IDENTITY.md): derived from the root, handed to that app
|
|
||||||
/// only. The caller checks `app_id` (a-z, 0-9, `-`) and the app's right to it.
|
|
||||||
pub fn domi_backup_secret(&self, app_id: &str) -> Result<Zeroizing<[u8; 32]>, Error> {
|
|
||||||
Ok(self.identity.as_ref().ok_or(Error::NoIdentity)?.backup_secret(app_id))
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -128,8 +128,6 @@ fn the_identity_survives_saving_in_both_versions() {
|
|||||||
not_before: 1,
|
not_before: 1,
|
||||||
not_after: 2,
|
not_after: 2,
|
||||||
issued: 3,
|
issued: 3,
|
||||||
revoked_at: Some(4),
|
|
||||||
revocation: vec!["VFJWMQ".into()],
|
|
||||||
};
|
};
|
||||||
// Version 1.
|
// Version 1.
|
||||||
let mut v = vault();
|
let mut v = vault();
|
||||||
@@ -167,176 +165,8 @@ fn a_record_needs_an_identity() {
|
|||||||
not_before: 0,
|
not_before: 0,
|
||||||
not_after: 1,
|
not_after: 1,
|
||||||
issued: 0,
|
issued: 0,
|
||||||
..Issued::default()
|
|
||||||
};
|
};
|
||||||
assert!(matches!(v.domi_record(i), Err(Error::NoIdentity)));
|
assert!(matches!(v.domi_record(i), Err(Error::NoIdentity)));
|
||||||
assert!(matches!(v.domi_mark_revoked("x", 1), Err(Error::NoIdentity)));
|
|
||||||
assert!(matches!(v.domi_backup_secret("fiscus"), Err(Error::NoIdentity)));
|
|
||||||
}
|
|
||||||
|
|
||||||
// ---- v1.1: restoring, revoking, the backup secret (docs/IDENTITY.md) ----
|
|
||||||
|
|
||||||
const ZERO_PHRASE: &str = "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon \
|
|
||||||
abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon \
|
|
||||||
abandon art";
|
|
||||||
const REVOKE_DOMAIN: &[u8] = b"tessera revoke v1\0";
|
|
||||||
const SUBKEY_9: &str = "CQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQk"; // [9; 32]
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn the_24_words_restore_the_same_root() {
|
|
||||||
let mut v = vault();
|
|
||||||
Enrollment::restore(ZERO_PHRASE).unwrap().import(&mut v).unwrap();
|
|
||||||
assert_eq!(v.domi_root_public().unwrap().to_vec(), b64url(ROOT_PUB_ZERO));
|
|
||||||
// Any case, any spacing, as long as the words are right.
|
|
||||||
let mut w = vault();
|
|
||||||
let messy = format!(" {}\n", ZERO_PHRASE.to_uppercase().replace(' ', " \t"));
|
|
||||||
Enrollment::restore(&messy).unwrap().import(&mut w).unwrap();
|
|
||||||
assert_eq!(w.domi_root_public(), v.domi_root_public());
|
|
||||||
// And from words that were shown: the same root as enrolling.
|
|
||||||
let mut e = vault();
|
|
||||||
let words = enrol(&mut e, [42; 32]);
|
|
||||||
let mut r = vault();
|
|
||||||
Enrollment::restore(&words.join(" ")).unwrap().import(&mut r).unwrap();
|
|
||||||
assert_eq!(r.domi_root_public(), e.domi_root_public());
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn a_wrong_phrase_restores_nothing_and_names_no_word() {
|
|
||||||
let bad_checksum = ZERO_PHRASE.replace("art", "abandon");
|
|
||||||
let short = "abandon ".repeat(11) + "about";
|
|
||||||
let typo = ZERO_PHRASE.replacen("abandon", "abandn", 1);
|
|
||||||
for phrase in [bad_checksum.as_str(), short.as_str(), typo.as_str(), "", "art"] {
|
|
||||||
let e = Enrollment::restore(phrase).map(|_| ()).unwrap_err();
|
|
||||||
assert!(matches!(e, Error::NotAMnemonic), "{phrase}");
|
|
||||||
let shown = format!("{e} {e:?}");
|
|
||||||
assert!(!shown.contains("abandon") && !shown.contains("art "), "{shown}");
|
|
||||||
}
|
|
||||||
// Into a vault that has one already: refused, the old one stays.
|
|
||||||
let mut v = vault();
|
|
||||||
enrol(&mut v, [5; 32]);
|
|
||||||
let before = v.domi_root_public();
|
|
||||||
assert!(matches!(Enrollment::restore(ZERO_PHRASE).unwrap().import(&mut v), Err(Error::IdentityExists)));
|
|
||||||
assert_eq!(v.domi_root_public(), before);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A revocation's to-be-signed bytes as tessera makes them: TRV1 ‖ root ‖ subkey ‖ revoked_at ‖ part ‖
|
|
||||||
/// parts ‖ count ‖ hashes.
|
|
||||||
fn trv1(root: &[u8; 32], subkey: &[u8; 32], revoked_at: u64) -> Vec<u8> {
|
|
||||||
let mut t = b"TRV1".to_vec();
|
|
||||||
t.extend_from_slice(root);
|
|
||||||
t.extend_from_slice(subkey);
|
|
||||||
t.extend_from_slice(&revoked_at.to_be_bytes());
|
|
||||||
t.extend_from_slice(&0u16.to_be_bytes());
|
|
||||||
t.extend_from_slice(&1u16.to_be_bytes());
|
|
||||||
t.extend_from_slice(&1u32.to_be_bytes());
|
|
||||||
t.extend_from_slice(&[7; 32]);
|
|
||||||
t
|
|
||||||
}
|
|
||||||
|
|
||||||
fn issued_to(subkey: &str, app_id: &str) -> Issued {
|
|
||||||
Issued {
|
|
||||||
kind: "app".into(),
|
|
||||||
app_id: app_id.into(),
|
|
||||||
purpose: "sync".into(),
|
|
||||||
subkey: subkey.into(),
|
|
||||||
label: "fiscus.exe".into(),
|
|
||||||
not_before: 1,
|
|
||||||
not_after: 2,
|
|
||||||
issued: 3,
|
|
||||||
..Issued::default()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn the_root_signs_a_revocation_only_for_a_key_the_person_revoked() {
|
|
||||||
let mut v = vault();
|
|
||||||
enrol(&mut v, [0; 32]);
|
|
||||||
let root = v.domi_root_public().unwrap();
|
|
||||||
v.domi_record(issued_to(SUBKEY_9, "fiscus")).unwrap();
|
|
||||||
// Issued, but not revoked yet: refused.
|
|
||||||
let t = trv1(&root, &[9; 32], 1000);
|
|
||||||
assert!(matches!(v.domi_sign_revocation(&t), Err(Error::NotARevocation)));
|
|
||||||
// An unknown key cannot be marked.
|
|
||||||
assert!(matches!(v.domi_mark_revoked("CgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgo", 1000), Err(Error::UnknownKey)));
|
|
||||||
|
|
||||||
// A renewal issued a second cert for the same key: marking covers both, and the first time stays.
|
|
||||||
v.domi_record(issued_to(SUBKEY_9, "fiscus")).unwrap();
|
|
||||||
assert_eq!(v.domi_mark_revoked(SUBKEY_9, 1000).unwrap(), 1000);
|
|
||||||
assert_eq!(v.domi_mark_revoked(SUBKEY_9, 2000).unwrap(), 1000, "the first revocation time stays");
|
|
||||||
assert!(v.domi_issued().iter().all(|i| i.revoked_at == Some(1000)));
|
|
||||||
|
|
||||||
let sig = v.domi_sign_revocation(&t).unwrap();
|
|
||||||
let vk = VerifyingKey::from_bytes(&root).unwrap();
|
|
||||||
vk.verify_strict(&[REVOKE_DOMAIN, &t].concat(), &Signature::from_bytes(&sig)).unwrap();
|
|
||||||
assert!(
|
|
||||||
vk.verify_strict(&[CERT_DOMAIN, &t].concat(), &Signature::from_bytes(&sig)).is_err(),
|
|
||||||
"not a cert signature"
|
|
||||||
);
|
|
||||||
|
|
||||||
// Another time, another key, another root, a cert, garbage, the bare prefix: refused.
|
|
||||||
for bad in [
|
|
||||||
trv1(&root, &[9; 32], 999),
|
|
||||||
trv1(&root, &[10; 32], 1000),
|
|
||||||
trv1(&[1; 32], &[9; 32], 1000),
|
|
||||||
tbs(&root),
|
|
||||||
b"pay 100 CZK to mallory".to_vec(),
|
|
||||||
t[..76].to_vec(),
|
|
||||||
] {
|
|
||||||
assert!(matches!(v.domi_sign_revocation(&bad), Err(Error::NotARevocation)), "{bad:?}");
|
|
||||||
}
|
|
||||||
// And the cert signer never signs a revocation.
|
|
||||||
assert!(matches!(v.domi_sign_cert(&t), Err(Error::NotACert)));
|
|
||||||
|
|
||||||
// The statements are kept with every cert of the key, and survive a save.
|
|
||||||
v.domi_record_revocation(SUBKEY_9, vec!["first".into(), "second".into()]).unwrap();
|
|
||||||
assert!(matches!(
|
|
||||||
v.domi_record_revocation("CgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgo", vec![]),
|
|
||||||
Err(Error::UnknownKey)
|
|
||||||
));
|
|
||||||
let back = Vault::open(&v.to_bytes().unwrap(), &SecretString::from("pw")).unwrap();
|
|
||||||
assert!(back.domi_issued().iter().all(|i| i.revoked_at == Some(1000) && i.revocation == ["first", "second"]));
|
|
||||||
assert_eq!(back.domi_sign_revocation(&t).unwrap(), sig);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn a_cert_without_a_revocation_is_saved_as_before() {
|
|
||||||
let mut v = vault();
|
|
||||||
enrol(&mut v, [0; 32]);
|
|
||||||
v.domi_record(issued_to(SUBKEY_9, "fiscus")).unwrap();
|
|
||||||
let json = serde_json::to_string(&v.domi_issued()[0]).unwrap();
|
|
||||||
assert!(!json.contains("revoked_at") && !json.contains("revocation"), "{json}");
|
|
||||||
// And a record from core 0.7.0, without the two members, reads.
|
|
||||||
let old: Issued = serde_json::from_str(
|
|
||||||
r#"{"kind":"app","app_id":"fiscus","purpose":"sync","subkey":"x","label":"l","not_before":1,"not_after":2,"issued":3}"#,
|
|
||||||
)
|
|
||||||
.unwrap();
|
|
||||||
assert_eq!((old.revoked_at, old.revocation.len()), (None, 0));
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn the_backup_secret_matches_fundamentum() {
|
|
||||||
use chacha20poly1305::aead::{Aead, KeyInit, Payload};
|
|
||||||
let mut v = vault();
|
|
||||||
enrol(&mut v, [0; 32]);
|
|
||||||
let secret = v.domi_backup_secret("fiscus").unwrap();
|
|
||||||
let expand = |info: &[u8]| {
|
|
||||||
let mut out = [0u8; 32];
|
|
||||||
hkdf::Hkdf::<sha2::Sha256>::from_prk(secret.as_ref()).unwrap().expand(info, &mut out).unwrap();
|
|
||||||
out
|
|
||||||
};
|
|
||||||
// Fundamentum docs/TESSERA.md §12.
|
|
||||||
assert_eq!(expand(b"mailbox").to_vec(), b64url("IygCOrh-ibO6-KY5AXQ9Prl2SyPWQIyZZ-anffcbMCU"));
|
|
||||||
let key = expand(b"seal");
|
|
||||||
let tag = chacha20poly1305::XChaCha20Poly1305::new_from_slice(&key)
|
|
||||||
.unwrap()
|
|
||||||
.encrypt(&chacha20poly1305::XNonce::try_from(&[0u8; 24][..]).unwrap(), Payload { msg: b"", aad: b"" })
|
|
||||||
.unwrap();
|
|
||||||
assert_eq!(tag, b64url("ci_JRbtsx5prR83KT9Y7LA"));
|
|
||||||
// One per app, the same from the restored words.
|
|
||||||
assert_ne!(*v.domi_backup_secret("calenda").unwrap(), *secret);
|
|
||||||
let mut r = vault();
|
|
||||||
Enrollment::restore(ZERO_PHRASE).unwrap().import(&mut r).unwrap();
|
|
||||||
assert_eq!(*r.domi_backup_secret("fiscus").unwrap(), *secret);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
@@ -376,19 +206,13 @@ fn the_identity_surface_is_locked() {
|
|||||||
"identity.rs: pub fn challenge(&self) -> [usize; 3]",
|
"identity.rs: pub fn challenge(&self) -> [usize; 3]",
|
||||||
"identity.rs: pub fn confirm(self, words: &[&str; 3]) -> Result<Confirmed, (Shown, Error)>",
|
"identity.rs: pub fn confirm(self, words: &[&str; 3]) -> Result<Confirmed, (Shown, Error)>",
|
||||||
"identity.rs: pub fn import(self, vault: &mut Vault) -> Result<[u8; 32], Error>",
|
"identity.rs: pub fn import(self, vault: &mut Vault) -> Result<[u8; 32], Error>",
|
||||||
"identity.rs: pub fn restore(phrase: &str) -> Result<Confirmed, Error>",
|
|
||||||
"identity.rs: pub fn show(self, display: impl FnOnce(&[&str])) -> Shown",
|
"identity.rs: pub fn show(self, display: impl FnOnce(&[&str])) -> Shown",
|
||||||
"identity.rs: pub fn with_entropy(entropy: [u8; 32]) -> Enrollment",
|
"identity.rs: pub fn with_entropy(entropy: [u8; 32]) -> Enrollment",
|
||||||
// The app's own backup secret, derived: by design (docs/IDENTITY.md), never the root.
|
|
||||||
"lib.rs: pub fn domi_backup_secret(&self, app_id: &str) -> Result<Zeroizing<[u8; 32]>, Error>",
|
|
||||||
"lib.rs: pub fn domi_created(&self) -> Option<i64>",
|
"lib.rs: pub fn domi_created(&self) -> Option<i64>",
|
||||||
"lib.rs: pub fn domi_issued(&self) -> &[identity::Issued]",
|
"lib.rs: pub fn domi_issued(&self) -> &[identity::Issued]",
|
||||||
"lib.rs: pub fn domi_mark_revoked(&mut self, subkey: &str, revoked_at: u64) -> Result<u64, Error>",
|
|
||||||
"lib.rs: pub fn domi_record(&mut self, issued: identity::Issued) -> Result<(), Error>",
|
"lib.rs: pub fn domi_record(&mut self, issued: identity::Issued) -> Result<(), Error>",
|
||||||
"lib.rs: pub fn domi_record_revocation(&mut self, subkey: &str, statements: Vec<String>) -> Result<(), Error>",
|
|
||||||
"lib.rs: pub fn domi_root_public(&self) -> Option<[u8; 32]>",
|
"lib.rs: pub fn domi_root_public(&self) -> Option<[u8; 32]>",
|
||||||
"lib.rs: pub fn domi_sign_cert(&self, tbs: &[u8]) -> Result<[u8; 64], Error>",
|
"lib.rs: pub fn domi_sign_cert(&self, tbs: &[u8]) -> Result<[u8; 64], Error>",
|
||||||
"lib.rs: pub fn domi_sign_revocation(&self, tbs: &[u8]) -> Result<[u8; 64], Error>",
|
|
||||||
];
|
];
|
||||||
want.sort();
|
want.sort();
|
||||||
assert_eq!(got, want, "review the identity surface: it must never return the root secret");
|
assert_eq!(got, want, "review the identity surface: it must never return the root secret");
|
||||||
|
|||||||
+1
-2
@@ -119,8 +119,7 @@ UTF-8 JSON, held in zeroizing buffers while being encrypted or parsed:
|
|||||||
- `fields` is an ordered list; a name may repeat (several `url`s). Unknown names are kept as custom fields.
|
- `fields` is an ordered list; a name may repeat (several `url`s). Unknown names are kept as custom fields.
|
||||||
- `history` keeps the previous value of a secret field each time it changes (newest last, at most 20 per item).
|
- `history` keeps the previous value of a secret field each time it changes (newest last, at most 20 per item).
|
||||||
- Readers ignore JSON members they do not know, so later versions can add them.
|
- Readers ignore JSON members they do not know, so later versions can add them.
|
||||||
- `identity` (optional, core 0.7.0): the Domi identity's root key and the certs it issued (docs/IDENTITY.md);
|
- `identity` (optional, core 0.7.0): the Domi identity's root key and the certs it issued (docs/IDENTITY.md).
|
||||||
since core 0.10.0 a cert may carry `revoked_at` and `revocation`.
|
|
||||||
An older Custos drops it when it saves, so every Custos that saves the vault must be 0.7.0 or later.
|
An older Custos drops it when it saves, so every Custos that saves the vault must be 0.7.0 or later.
|
||||||
- `folder` (optional item member, core 0.8.0): a list of folder names, outermost first (a KeePass group path,
|
- `folder` (optional item member, core 0.8.0): a list of folder names, outermost first (a KeePass group path,
|
||||||
docs/KDBX.md). Absent or empty = no folder.
|
docs/KDBX.md). Absent or empty = no folder.
|
||||||
|
|||||||
+5
-34
@@ -2,7 +2,7 @@
|
|||||||
|
|
||||||
Every Domi app gets its own subkey, certified by **one root Ed25519 key per person**. The root key lives in
|
Every Domi app gets its own subkey, certified by **one root Ed25519 key per person**. The root key lives in
|
||||||
the vault and never leaves it: no function of this crate returns it, and the vault signs nothing with it but
|
the vault and never leaves it: no function of this crate returns it, and the vault signs nothing with it but
|
||||||
subkey certificates and revocations of keys the person revoked. The certificate format, the match code and verification are in Fundamentum
|
subkey certificates. The certificate format, the match code and verification are in Fundamentum
|
||||||
(`crates/tessera`, `docs/TESSERA.md`); this page is the vault side.
|
(`crates/tessera`, `docs/TESSERA.md`); this page is the vault side.
|
||||||
|
|
||||||
## Creating it: the order is mandatory
|
## Creating it: the order is mandatory
|
||||||
@@ -31,12 +31,6 @@ is `Clone` or `Serialize`; each prints `[redacted]`.
|
|||||||
Test vector: entropy `00` × 32 → `abandon` × 23 + `art` → root public key
|
Test vector: entropy `00` × 32 → `abandon` × 23 + `art` → root public key
|
||||||
`vCrwX9p44un1ftQLgJtuaVQ0qPWbFfzNjgrlDkL4TKs` (base64url). Fundamentum pins the same value.
|
`vCrwX9p44un1ftQLgJtuaVQ0qPWbFfzNjgrlDkL4TKs` (base64url). Fundamentum pins the same value.
|
||||||
|
|
||||||
### Restoring it from the 24 words (core 0.10.0)
|
|
||||||
`Enrollment::restore(phrase)` takes the whole phrase, typed back, and gives a `Confirmed`: the person typed
|
|
||||||
all 24 words, which proves more than three. The words are checked against the BIP39 English list and its
|
|
||||||
checksum (any case, any spacing between them); anything else is `Error::NotAMnemonic`, which names no word.
|
|
||||||
The same words give the same root, so every app and every group trusts it again.
|
|
||||||
|
|
||||||
## In the vault file
|
## In the vault file
|
||||||
|
|
||||||
A body member next to `items` (docs/FORMAT.md, "Body"); old vaults without it open as before:
|
A body member next to `items` (docs/FORMAT.md, "Body"); old vaults without it open as before:
|
||||||
@@ -48,19 +42,13 @@ A body member next to `items` (docs/FORMAT.md, "Body"); old vaults without it op
|
|||||||
"created": 1793000000000,
|
"created": 1793000000000,
|
||||||
"issued": [
|
"issued": [
|
||||||
{ "kind": "app", "app_id": "fiscus", "purpose": "sync", "subkey": "<base64url>", "label": "fiscus.exe",
|
{ "kind": "app", "app_id": "fiscus", "purpose": "sync", "subkey": "<base64url>", "label": "fiscus.exe",
|
||||||
"not_before": 1793000000, "not_after": 1824536000, "issued": 1793000000000,
|
"not_before": 1793000000, "not_after": 1824536000, "issued": 1793000000000 }
|
||||||
"revoked_at": 1795000000, "revocation": ["<base64url TRV1>"] }
|
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
- `issued` records each cert the vault signed, for *Domi identity → apps and devices*. It is a record, not
|
- `issued` records each cert the vault signed, for *Domi identity → apps and devices*. It is a record, not
|
||||||
a trust list.
|
a trust list: revocation is v1.1.
|
||||||
- `revoked_at` (Unix seconds, core 0.10.0) is set when the person revokes the key; `revocation` holds the
|
|
||||||
signed statements once they exist. Both are left out until then. A renewed key has several certs: all of
|
|
||||||
them are marked.
|
|
||||||
- **A Custos older than core 0.10.0 drops `revoked_at` and `revocation` when it saves the vault**, so a
|
|
||||||
revocation in progress would have to be started again.
|
|
||||||
- **An older Custos drops the member when it saves the vault** (it ignores members it does not know). Every
|
- **An older Custos drops the member when it saves the vault** (it ignores members it does not know). Every
|
||||||
Custos that saves this vault must run core 0.7.0 or later. The mnemonic recovers the root either way.
|
Custos that saves this vault must run core 0.7.0 or later. The mnemonic recovers the root either way.
|
||||||
|
|
||||||
@@ -71,26 +59,9 @@ A body member next to `items` (docs/FORMAT.md, "Body"); old vaults without it op
|
|||||||
| `Vault::domi_root_public()` | the root public key, if there is an identity |
|
| `Vault::domi_root_public()` | the root public key, if there is an identity |
|
||||||
| `Vault::domi_sign_cert(tbs)` | Ed25519 over `"tessera cert v1\0" ‖ tbs`. Refuses a `tbs` that does not start with `TSC1` followed by this root's public key |
|
| `Vault::domi_sign_cert(tbs)` | Ed25519 over `"tessera cert v1\0" ‖ tbs`. Refuses a `tbs` that does not start with `TSC1` followed by this root's public key |
|
||||||
| `Vault::domi_issued()`, `domi_record(issued)` | the record of issued certs |
|
| `Vault::domi_issued()`, `domi_record(issued)` | the record of issued certs |
|
||||||
| `Vault::domi_mark_revoked(subkey, at)` | the person revoked this key: marks every cert of it, returns the time in effect (the first one, if it was marked before) |
|
|
||||||
| `Vault::domi_sign_revocation(tbs)` | Ed25519 over `"tessera revoke v1\0" ‖ tbs`. Refuses a `tbs` that does not start with `TRV1`, this root's public key, a key marked revoked and that key's `revoked_at` |
|
|
||||||
| `Vault::domi_record_revocation(subkey, statements)` | keeps the signed statements with the key's certs |
|
|
||||||
| `Vault::domi_backup_secret(app_id)` | the app's backup secret (below) |
|
|
||||||
|
|
||||||
The prefix checks mean the vault is not a general signing oracle: whatever the app hands it, the result
|
The prefix check means the vault is not a general signing oracle: whatever the app hands it, the result
|
||||||
can only ever verify as a certificate naming this root, or as a revocation of a key the person revoked, at
|
can only ever verify as a certificate naming this root.
|
||||||
the time they did. The two domains differ, so neither can pass for the other. Statement format: Fundamentum
|
|
||||||
docs/TESSERA.md §12.
|
|
||||||
|
|
||||||
### The backup secret (core 0.10.0)
|
|
||||||
```
|
|
||||||
backup secret = HKDF-SHA256(salt = "tessera backup v1", ikm = the root secret, info = app id)
|
|
||||||
```
|
|
||||||
Custos hands an app its own (Domi pipe `backup_key`, behind the app's namespace grant); the app seals its
|
|
||||||
backup with it and names its backup mailbox from it (Fundamentum docs/TESSERA.md §12). It comes back from
|
|
||||||
the 24 words alone. The caller passes a valid app id (a-z, 0-9, `-`). Test vector, shared with Fundamentum:
|
|
||||||
the zero-entropy root, app `fiscus` → `HKDF-Expand(secret, "mailbox")` =
|
|
||||||
`IygCOrh-ibO6-KY5AXQ9Prl2SyPWQIyZZ-anffcbMCU`, and XChaCha20-Poly1305 with
|
|
||||||
`HKDF-Expand(secret, "seal")`, a zero nonce and empty input = `ci_JRbtsx5prR83KT9Y7LA` (the tag).
|
|
||||||
|
|
||||||
## What it does not protect
|
## What it does not protect
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,91 @@
|
|||||||
|
// Custos's service worker (docs/BROWSER.md). It owns the connection to the native host and answers the
|
||||||
|
// content scripts and the popup. The page origin it sends to Custos is always the browser's (`sender.url`,
|
||||||
|
// the tab's URL), never what a page says about itself; Custos decides which logins belong to it.
|
||||||
|
|
||||||
|
const HOST = 'cz.marek_novak.custos';
|
||||||
|
|
||||||
|
/** The native host, connected on first use; Edge and Chrome keep the worker alive while it is open. */
|
||||||
|
let port = null;
|
||||||
|
let seq = 0;
|
||||||
|
const waiting = new Map();
|
||||||
|
|
||||||
|
function connect() {
|
||||||
|
if (port) return port;
|
||||||
|
port = chrome.runtime.connectNative(HOST);
|
||||||
|
port.onMessage.addListener((msg) => {
|
||||||
|
const w = waiting.get(msg.seq);
|
||||||
|
if (!w) return;
|
||||||
|
waiting.delete(msg.seq);
|
||||||
|
w(msg);
|
||||||
|
});
|
||||||
|
port.onDisconnect.addListener(() => {
|
||||||
|
// Not registered, or the host exited: every open request fails the same way.
|
||||||
|
const why = chrome.runtime.lastError?.message ?? '';
|
||||||
|
const error = /not found|forbidden/i.test(why) ? 'not_connected' : 'not_running';
|
||||||
|
for (const w of waiting.values()) w({ ok: false, error });
|
||||||
|
waiting.clear();
|
||||||
|
port = null;
|
||||||
|
});
|
||||||
|
return port;
|
||||||
|
}
|
||||||
|
|
||||||
|
function ask(request) {
|
||||||
|
return new Promise((resolve) => {
|
||||||
|
const n = ++seq;
|
||||||
|
waiting.set(n, resolve);
|
||||||
|
try {
|
||||||
|
connect().postMessage({ ...request, seq: n });
|
||||||
|
} catch {
|
||||||
|
waiting.delete(n);
|
||||||
|
resolve({ ok: false, error: 'not_connected' });
|
||||||
|
}
|
||||||
|
// Custos may wait up to a minute for an unlock or an approval.
|
||||||
|
setTimeout(() => {
|
||||||
|
if (waiting.delete(n)) resolve({ ok: false, error: 'no_answer' });
|
||||||
|
}, 75_000);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/** `https://host[:port]` of a page or frame URL; null for anything Custos never fills. */
|
||||||
|
function originOf(url) {
|
||||||
|
try {
|
||||||
|
const u = new URL(url);
|
||||||
|
if (u.protocol !== 'https:' && u.protocol !== 'http:') return null;
|
||||||
|
return u.origin;
|
||||||
|
} catch {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
chrome.runtime.onMessage.addListener((msg, sender, reply) => {
|
||||||
|
// Only this extension's own pages and content scripts reach here; pages cannot send to it.
|
||||||
|
if (sender.id !== chrome.runtime.id) return false;
|
||||||
|
(async () => {
|
||||||
|
switch (msg?.kind) {
|
||||||
|
case 'status':
|
||||||
|
return reply(await ask({ op: 'browser_status' }));
|
||||||
|
case 'match': {
|
||||||
|
// From a content script: the logins for the frame it runs in.
|
||||||
|
const origin = originOf(sender.url);
|
||||||
|
if (!origin) return reply({ ok: false, error: 'no_match' });
|
||||||
|
return reply({ ...(await ask({ op: 'browser_match', origin })), origin });
|
||||||
|
}
|
||||||
|
case 'fill': {
|
||||||
|
// The secrets go back to the frame that asked, and only if Custos agrees the login belongs there.
|
||||||
|
const origin = originOf(sender.url);
|
||||||
|
if (!origin || typeof msg.id !== 'string') return reply({ ok: false, error: 'no_match' });
|
||||||
|
return reply(await ask({ op: 'browser_fill', id: msg.id, origin }));
|
||||||
|
}
|
||||||
|
case 'match-tab': {
|
||||||
|
// From the popup: the logins for the active tab's page.
|
||||||
|
const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
|
||||||
|
const origin = tab && originOf(tab.url);
|
||||||
|
if (!origin) return reply({ ok: false, error: 'no_match', tab: tab?.id ?? null });
|
||||||
|
return reply({ ...(await ask({ op: 'browser_match', origin })), origin, tab: tab.id });
|
||||||
|
}
|
||||||
|
default:
|
||||||
|
return reply({ ok: false, error: 'bad_request' });
|
||||||
|
}
|
||||||
|
})();
|
||||||
|
return true;
|
||||||
|
});
|
||||||
@@ -0,0 +1,173 @@
|
|||||||
|
// Custos's content script (docs/BROWSER.md): finds login fields, offers the logins Custos has for this
|
||||||
|
// frame's site, and fills the one the person picks. Nothing is filled without a click. The button and the
|
||||||
|
// list live in a closed shadow root, out of the page's reach; logins are asked for only when the list opens.
|
||||||
|
(() => {
|
||||||
|
const SENTENCES = {
|
||||||
|
not_connected: 'Connect this browser in Custos first: Settings → Browser.',
|
||||||
|
not_running: 'Custos is not running. Start it, then try again.',
|
||||||
|
not_custos: 'Something other than Custos answered. Nothing was sent.',
|
||||||
|
locked: 'Custos is locked. Unlock it, then try again.',
|
||||||
|
denied: 'Custos did not allow this browser to use your logins.',
|
||||||
|
not_found: 'That login is no longer in Custos.',
|
||||||
|
no_match: 'That login does not belong to this site.',
|
||||||
|
no_answer: 'Custos did not answer.',
|
||||||
|
};
|
||||||
|
const say = (code) => SENTENCES[code] ?? 'Custos could not do that.';
|
||||||
|
|
||||||
|
const visible = (el) => {
|
||||||
|
const r = el.getBoundingClientRect();
|
||||||
|
const s = getComputedStyle(el);
|
||||||
|
return r.width > 0 && r.height > 0 && s.visibility !== 'hidden' && s.display !== 'none' && !el.disabled && !el.readOnly;
|
||||||
|
};
|
||||||
|
const isText = (el) => el instanceof HTMLInputElement && ['text', 'email', 'tel'].includes(el.type);
|
||||||
|
const isOtp = (el) =>
|
||||||
|
el instanceof HTMLInputElement &&
|
||||||
|
(el.autocomplete === 'one-time-code' || /(^|[^a-z])(otp|totp|2fa|mfa|one.?time|verification.?code)/i.test(`${el.name} ${el.id}`));
|
||||||
|
const isUserName = (el) => isText(el) && /username|email/i.test(`${el.autocomplete} ${el.name} ${el.id} ${el.type}`);
|
||||||
|
|
||||||
|
/** The username field of a password field: the one the page marks, else the last text field before it. */
|
||||||
|
function usernameFor(pw) {
|
||||||
|
const inputs = [...(pw.form ?? document).querySelectorAll('input')].filter(visible);
|
||||||
|
const marked = inputs.find((el) => isText(el) && /username|email/i.test(el.autocomplete));
|
||||||
|
if (marked) return marked;
|
||||||
|
for (let i = inputs.indexOf(pw) - 1; i >= 0; i--) if (isText(inputs[i]) && !isOtp(inputs[i])) return inputs[i];
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The fields a login fills, around `near` (the focused field) or on the whole page. */
|
||||||
|
function fieldsAround(near) {
|
||||||
|
const all = [...document.querySelectorAll('input')].filter(visible);
|
||||||
|
const otp = (near && isOtp(near) ? near : null) ?? all.find(isOtp) ?? null;
|
||||||
|
const scope = near?.form ? [...near.form.querySelectorAll('input')].filter(visible) : all;
|
||||||
|
const pass = (near?.type === 'password' ? near : null) ?? scope.find((el) => el.type === 'password') ?? null;
|
||||||
|
const user = pass ? usernameFor(pass) : ((near && isUserName(near) ? near : null) ?? scope.find(isUserName) ?? null);
|
||||||
|
return { user, pass, otp };
|
||||||
|
}
|
||||||
|
|
||||||
|
const setValue = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value').set;
|
||||||
|
function put(el, value) {
|
||||||
|
if (!el || typeof value !== 'string' || !value) return;
|
||||||
|
el.focus();
|
||||||
|
setValue.call(el, value);
|
||||||
|
el.dispatchEvent(new Event('input', { bubbles: true }));
|
||||||
|
el.dispatchEvent(new Event('change', { bubbles: true }));
|
||||||
|
}
|
||||||
|
|
||||||
|
async function fill(id, near) {
|
||||||
|
const r = await chrome.runtime.sendMessage({ kind: 'fill', id });
|
||||||
|
if (!r?.ok) return say(r?.error);
|
||||||
|
const f = fieldsAround(near);
|
||||||
|
put(f.user, r.username);
|
||||||
|
put(f.pass, r.password);
|
||||||
|
if (f.otp) put(f.otp, r.totp);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- the button and the list ----
|
||||||
|
|
||||||
|
const host = document.createElement('custos-fill');
|
||||||
|
const root = host.attachShadow({ mode: 'closed' });
|
||||||
|
root.innerHTML = `
|
||||||
|
<style>
|
||||||
|
:host { all: initial; }
|
||||||
|
.chip, .menu { position: fixed; z-index: 2147483647; font: 13px/1.4 "Segoe UI", system-ui, sans-serif; }
|
||||||
|
.chip { width: 24px; height: 24px; padding: 0; border: 1px solid #5d6573; border-radius: 6px; background: #15181d;
|
||||||
|
cursor: pointer; display: grid; place-items: center; box-shadow: 0 2px 6px rgba(0,0,0,.35); }
|
||||||
|
.chip:hover, .chip:focus-visible { border-color: #c9d1dc; outline: none; }
|
||||||
|
.menu { min-width: 240px; max-width: 360px; padding: 6px; border: 1px solid #3a404b; border-radius: 10px;
|
||||||
|
background: #15181d; color: #e8ebf0; box-shadow: 0 14px 32px rgba(0,0,0,.45); }
|
||||||
|
.head { padding: 4px 8px 6px; color: #9aa3b1; font-size: 11px; letter-spacing: .14em; text-transform: uppercase; }
|
||||||
|
button.login { display: grid; width: 100%; padding: 7px 8px; border: 0; border-radius: 7px; background: none;
|
||||||
|
color: inherit; text-align: left; cursor: pointer; font: inherit; }
|
||||||
|
button.login:hover, button.login:focus-visible { background: #262b33; outline: none; }
|
||||||
|
.title { font-weight: 600; }
|
||||||
|
.user { color: #9aa3b1; font-size: 12px; }
|
||||||
|
.note { padding: 6px 8px; color: #c9d1dc; }
|
||||||
|
[hidden] { display: none !important; }
|
||||||
|
</style>
|
||||||
|
<button class="chip" type="button" title="Fill from Custos" aria-label="Fill from Custos" hidden>
|
||||||
|
<svg width="14" height="14" viewBox="0 0 16 16" aria-hidden="true"><path d="M8 1.5l5 2v4c0 3.2-2.1 5.8-5 7-2.9-1.2-5-3.8-5-7v-4z"
|
||||||
|
fill="none" stroke="#c9d1dc" stroke-width="1.5" stroke-linejoin="round"/><path d="M5.8 8l1.6 1.6L10.4 6.4" fill="none"
|
||||||
|
stroke="#c9d1dc" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg>
|
||||||
|
</button>
|
||||||
|
<div class="menu" role="menu" aria-label="Custos logins" hidden></div>`;
|
||||||
|
const chip = root.querySelector('.chip');
|
||||||
|
const menu = root.querySelector('.menu');
|
||||||
|
let field = null;
|
||||||
|
|
||||||
|
function place() {
|
||||||
|
if (!field || !field.isConnected) return hide();
|
||||||
|
const r = field.getBoundingClientRect();
|
||||||
|
chip.style.left = `${Math.max(0, r.right - 28)}px`;
|
||||||
|
chip.style.top = `${r.top + Math.max(0, (r.height - 24) / 2)}px`;
|
||||||
|
menu.style.left = `${Math.max(4, r.left)}px`;
|
||||||
|
menu.style.top = `${r.bottom + 4}px`;
|
||||||
|
}
|
||||||
|
|
||||||
|
function hide() {
|
||||||
|
chip.hidden = true;
|
||||||
|
menu.hidden = true;
|
||||||
|
field = null;
|
||||||
|
}
|
||||||
|
|
||||||
|
function note(text) {
|
||||||
|
menu.replaceChildren(Object.assign(document.createElement('div'), { className: 'note', textContent: text }));
|
||||||
|
menu.hidden = false;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function open() {
|
||||||
|
const target = field;
|
||||||
|
note('Asking Custos…');
|
||||||
|
const r = await chrome.runtime.sendMessage({ kind: 'match' });
|
||||||
|
if (field !== target) return;
|
||||||
|
if (!r?.ok) return note(say(r?.error));
|
||||||
|
if (!r.logins.length) return note('Custos has no login for this site.');
|
||||||
|
const head = Object.assign(document.createElement('div'), { className: 'head', textContent: 'Custos' });
|
||||||
|
const items = r.logins.map((l) => {
|
||||||
|
const b = Object.assign(document.createElement('button'), { className: 'login', type: 'button' });
|
||||||
|
b.setAttribute('role', 'menuitem');
|
||||||
|
b.append(
|
||||||
|
Object.assign(document.createElement('span'), { className: 'title', textContent: l.title }),
|
||||||
|
Object.assign(document.createElement('span'), { className: 'user', textContent: l.username || '—' }),
|
||||||
|
);
|
||||||
|
b.addEventListener('click', async () => {
|
||||||
|
const why = await fill(l.id, target);
|
||||||
|
if (why) note(why);
|
||||||
|
else hide();
|
||||||
|
});
|
||||||
|
return b;
|
||||||
|
});
|
||||||
|
menu.replaceChildren(head, ...items);
|
||||||
|
items[0]?.focus();
|
||||||
|
}
|
||||||
|
|
||||||
|
chip.addEventListener('click', () => (menu.hidden ? void open() : (menu.hidden = true)));
|
||||||
|
// A press inside the shadow root is a press on `host` for the page: keep the field's focus logic out of it.
|
||||||
|
host.addEventListener('mousedown', (e) => e.preventDefault());
|
||||||
|
|
||||||
|
document.addEventListener(
|
||||||
|
'focusin',
|
||||||
|
(e) => {
|
||||||
|
const el = e.target;
|
||||||
|
if (!(el instanceof HTMLInputElement) || !visible(el)) return;
|
||||||
|
if (el.type !== 'password' && !isOtp(el) && !(isText(el) && fieldsAround(el).pass) && !isUserName(el)) return;
|
||||||
|
if (!host.isConnected) document.documentElement.append(host);
|
||||||
|
field = el;
|
||||||
|
menu.hidden = true;
|
||||||
|
chip.hidden = false;
|
||||||
|
place();
|
||||||
|
},
|
||||||
|
true,
|
||||||
|
);
|
||||||
|
document.addEventListener('keydown', (e) => e.key === 'Escape' && !menu.hidden && hide(), true);
|
||||||
|
document.addEventListener('pointerdown', (e) => e.target !== host && e.target !== field && hide(), true);
|
||||||
|
window.addEventListener('scroll', place, true);
|
||||||
|
window.addEventListener('resize', place);
|
||||||
|
|
||||||
|
// The popup's choice, in the top frame: fill the page's login form.
|
||||||
|
chrome.runtime.onMessage.addListener((msg, sender, reply) => {
|
||||||
|
if (sender.id !== chrome.runtime.id || msg?.kind !== 'fill-now' || typeof msg.id !== 'string') return false;
|
||||||
|
fill(msg.id, null).then((why) => reply({ ok: !why, error: why }));
|
||||||
|
return true;
|
||||||
|
});
|
||||||
|
})();
|
||||||
@@ -0,0 +1,38 @@
|
|||||||
|
{
|
||||||
|
"manifest_version": 3,
|
||||||
|
"name": "Custos",
|
||||||
|
"short_name": "Custos",
|
||||||
|
"description": "Fills your logins from the Custos on this computer, only into the site they belong to.",
|
||||||
|
"version": "0.10.0",
|
||||||
|
"key": "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAs+NtlDNsfBr8q2WbrurbDDfX4rL2dTHsNZToKBKradRb5WZU3wjHAcBMsPlYCiqHF4c/KUyGQ33mpPb0aXA5l3w7n6JgMLHPQBbCw5v076ViF6NIE3a0LOoffDg9ZQmfIJcgjb9baX2qS8VaEFTsEzb/BgQ2Ewx/BPHwZaFeJkucBsIeRZnaPajdqViaNDQdq91VnxIoSGr21Sc+9ZxfZL288S6wATdlDYBUyUZZjVwggHfiwdDmQQMdnFtks2r38V25h+t3ruGCi2mArj8DO1so1oX/NulLNT+6VBP6r/ap228af3rNNcv7sPeriI90ORqzh4Lwni8Hq1lzKuXLrwIDAQAB",
|
||||||
|
"minimum_chrome_version": "116",
|
||||||
|
"permissions": [
|
||||||
|
"nativeMessaging",
|
||||||
|
"activeTab"
|
||||||
|
],
|
||||||
|
"background": {
|
||||||
|
"service_worker": "background.js"
|
||||||
|
},
|
||||||
|
"action": {
|
||||||
|
"default_title": "Custos",
|
||||||
|
"default_popup": "popup.html"
|
||||||
|
},
|
||||||
|
"content_scripts": [
|
||||||
|
{
|
||||||
|
"matches": [
|
||||||
|
"https://*/*",
|
||||||
|
"http://localhost/*",
|
||||||
|
"http://127.0.0.1/*",
|
||||||
|
"http://*.localhost/*"
|
||||||
|
],
|
||||||
|
"js": [
|
||||||
|
"content.js"
|
||||||
|
],
|
||||||
|
"all_frames": true,
|
||||||
|
"run_at": "document_idle"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"content_security_policy": {
|
||||||
|
"extension_pages": "default-src 'self'; script-src 'self'; style-src 'self'; img-src 'self'"
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,77 @@
|
|||||||
|
:root {
|
||||||
|
color-scheme: dark;
|
||||||
|
--bg: #101216;
|
||||||
|
--panel: #15181d;
|
||||||
|
--hover: #262b33;
|
||||||
|
--line: #2b3038;
|
||||||
|
--fg: #e8ebf0;
|
||||||
|
--muted: #9aa3b1;
|
||||||
|
--accent: #c9d1dc;
|
||||||
|
}
|
||||||
|
body {
|
||||||
|
width: 320px;
|
||||||
|
margin: 0;
|
||||||
|
background: var(--bg);
|
||||||
|
color: var(--fg);
|
||||||
|
font: 13px/1.45 "Segoe UI", system-ui, sans-serif;
|
||||||
|
}
|
||||||
|
header {
|
||||||
|
display: flex;
|
||||||
|
align-items: baseline;
|
||||||
|
gap: 10px;
|
||||||
|
padding: 12px 14px 10px;
|
||||||
|
border-bottom: 1px solid var(--line);
|
||||||
|
background: var(--panel);
|
||||||
|
}
|
||||||
|
.wordmark {
|
||||||
|
color: var(--accent);
|
||||||
|
font-size: 12px;
|
||||||
|
letter-spacing: 0.3em;
|
||||||
|
}
|
||||||
|
.site {
|
||||||
|
overflow: hidden;
|
||||||
|
color: var(--muted);
|
||||||
|
white-space: nowrap;
|
||||||
|
text-overflow: ellipsis;
|
||||||
|
}
|
||||||
|
main {
|
||||||
|
padding: 8px;
|
||||||
|
}
|
||||||
|
.note {
|
||||||
|
margin: 6px 6px 10px;
|
||||||
|
}
|
||||||
|
.logins {
|
||||||
|
margin: 0;
|
||||||
|
padding: 0;
|
||||||
|
list-style: none;
|
||||||
|
}
|
||||||
|
.logins button {
|
||||||
|
display: grid;
|
||||||
|
width: 100%;
|
||||||
|
padding: 8px 10px;
|
||||||
|
border: 0;
|
||||||
|
border-radius: 8px;
|
||||||
|
background: none;
|
||||||
|
color: inherit;
|
||||||
|
font: inherit;
|
||||||
|
text-align: left;
|
||||||
|
cursor: pointer;
|
||||||
|
}
|
||||||
|
.logins button:hover,
|
||||||
|
.logins button:focus-visible {
|
||||||
|
background: var(--hover);
|
||||||
|
outline: none;
|
||||||
|
}
|
||||||
|
.title {
|
||||||
|
font-weight: 600;
|
||||||
|
}
|
||||||
|
.user {
|
||||||
|
color: var(--muted);
|
||||||
|
font-size: 12px;
|
||||||
|
}
|
||||||
|
footer {
|
||||||
|
padding: 8px 14px 12px;
|
||||||
|
border-top: 1px solid var(--line);
|
||||||
|
color: var(--muted);
|
||||||
|
font-size: 12px;
|
||||||
|
}
|
||||||
@@ -0,0 +1,20 @@
|
|||||||
|
<!doctype html>
|
||||||
|
<html lang="en">
|
||||||
|
<head>
|
||||||
|
<meta charset="utf-8">
|
||||||
|
<title>Custos</title>
|
||||||
|
<link rel="stylesheet" href="popup.css">
|
||||||
|
<script src="popup.js" defer></script>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<header>
|
||||||
|
<span class="wordmark">CUSTOS</span>
|
||||||
|
<span id="site" class="site"></span>
|
||||||
|
</header>
|
||||||
|
<main>
|
||||||
|
<p id="note" class="note">Asking Custos…</p>
|
||||||
|
<ul id="logins" class="logins" aria-label="Logins for this site"></ul>
|
||||||
|
</main>
|
||||||
|
<footer>Only logins saved for this site are offered here.</footer>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
@@ -0,0 +1,50 @@
|
|||||||
|
// The toolbar popup: the logins Custos has for the active tab's site; a click fills the page's login form
|
||||||
|
// (the top frame's content script asks for the secrets itself, so they go only where they belong).
|
||||||
|
const SENTENCES = {
|
||||||
|
not_connected: 'Connect this browser in Custos first: Settings → Browser.',
|
||||||
|
not_running: 'Custos is not running. Start it, then try again.',
|
||||||
|
not_custos: 'Something other than Custos answered. Nothing was sent.',
|
||||||
|
locked: 'Custos is locked. Unlock it, then try again.',
|
||||||
|
denied: 'Custos did not allow this browser to use your logins.',
|
||||||
|
not_found: 'That login is no longer in Custos.',
|
||||||
|
no_match: 'Custos fills only web pages (https, or this computer).',
|
||||||
|
no_answer: 'Custos did not answer.',
|
||||||
|
};
|
||||||
|
const say = (code) => SENTENCES[code] ?? 'Custos could not do that.';
|
||||||
|
const note = document.getElementById('note');
|
||||||
|
const list = document.getElementById('logins');
|
||||||
|
|
||||||
|
async function show() {
|
||||||
|
const r = await chrome.runtime.sendMessage({ kind: 'match-tab' });
|
||||||
|
if (r?.origin) document.getElementById('site').textContent = new URL(r.origin).host;
|
||||||
|
if (!r?.ok) {
|
||||||
|
note.textContent = say(r?.error);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (!r.logins.length) {
|
||||||
|
note.textContent = 'Custos has no login for this site.';
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
note.hidden = true;
|
||||||
|
for (const l of r.logins) {
|
||||||
|
const li = document.createElement('li');
|
||||||
|
const b = Object.assign(document.createElement('button'), { type: 'button' });
|
||||||
|
b.append(
|
||||||
|
Object.assign(document.createElement('span'), { className: 'title', textContent: l.title }),
|
||||||
|
Object.assign(document.createElement('span'), { className: 'user', textContent: l.username || '—' }),
|
||||||
|
);
|
||||||
|
b.addEventListener('click', async () => {
|
||||||
|
const done = await chrome.tabs.sendMessage(r.tab, { kind: 'fill-now', id: l.id }, { frameId: 0 }).catch(() => null);
|
||||||
|
if (done?.ok) window.close();
|
||||||
|
else {
|
||||||
|
note.hidden = false;
|
||||||
|
note.textContent = done?.error ?? 'This page has no login form Custos can fill.';
|
||||||
|
}
|
||||||
|
});
|
||||||
|
li.append(b);
|
||||||
|
list.append(li);
|
||||||
|
}
|
||||||
|
list.querySelector('button')?.focus();
|
||||||
|
}
|
||||||
|
|
||||||
|
void show();
|
||||||
Reference in New Issue
Block a user