Compare commits

...

6 Commits

Author SHA1 Message Date
mnovak 04a6031c5d [browser] Firefox: one extension source for Firefox, Edge and Chrome; frames, public suffixes, the caller check, 2FA codes and saving logins; v0.20.0
- custos-browser: fill_allowed (a frame gets a login only when its page would too), public suffixes match
  exactly only (psl), ports digits only, caller (which extension started the host); spoof tests.
- custos-native: answers not_allowed to anything but the Custos extension, browser_totp and browser_save,
  the frame's and the page's origins, a random session per connection (its match code on Custos's cards).
- extension/: manifest.firefox.json (gecko id custos@marek-novak.cz) and manifest.chromium.json, one set of
  scripts; the popup shows 2FA codes, the save offer and the connection's code; tools/extension.mjs builds
  each browser and reproducible zips; tools/extension-test.mjs runs the background against a fake browser.
2026-11-22 21:57:35 +01:00
mnovak a3b3a32745 [repo] Merge: fix/android-grant-compat (a key the Android grant makes is standing-granted; v0.19.1, PR #26) 2026-11-21 09:07:02 +01:00
mnovak 0eee7632ae [vault] Signing: a key the Android grant makes is standing-granted, a value older cores read; v0.19.1
0.19.0 wrote a new security action, android-key-made, which every older core refuses. The phone app and the
web vault open the same vault with their own pinned core, so a vault in which the grant made a key would stop
opening there. The key's creation is now standing-granted with 'Android grant made <id> for <repo> pipeline
release'; the grant itself is a member older cores ignore.
2026-11-21 09:06:35 +01:00
mnovak 6588461438 [repo] Merge: feature/android-grant (the Android grant: every Domi app's release APK and its key on first use; v0.19.0, PR #25) 2026-11-21 08:58:25 +01:00
mnovak e533a38883 [vault] Signing: the Android grant, one answer for every Domi app's release APK and its key on first use; v0.19.0
signing.android: patterns owner/name or owner/*, the certificate's O and C, uses, last used and the keys it
made. A request fits when it is an apk from this PC's pipe with a run, pipeline release, a covered repository,
and that repository's own app key (<name>-android, scoped to exactly it and release, role release), while
card-signing is not ticked; a key's first signature fits. android_grant_make_key makes that key for a covered
repository (android-key-made in the security audit). Granting and revoking write standing-granted and
standing-revoked. A vault whose grant made a key needs core 0.19.0; older cores drop the grant itself.
2026-11-21 08:57:48 +01:00
mnovak 47146a6ea2 [repo] Merge: fix/team-review (deployment ticket on target.request, unknown author under others, refuse after sign; v0.18.1, PR #24) 2026-11-17 12:45:27 +01:00
24 changed files with 1745 additions and 193 deletions
+7 -3
View File
@@ -16,9 +16,11 @@ crates/custos-team team vaults' pure parts: member keys, policy evaluation, s
crates/custos-share private share links: XChaCha20-Poly1305 blob, key in the URL fragment, optional password
crates/custos-wasm the browser build (web vault + share page): JSON `call` ABI, no wasm-bindgen; js/custos.mjs
crates/custos-kdbx KeePass import (KDBX 3.1, 4) and export (KDBX 4); tools/kdbx/interop.sh checks it with keepassxc-cli
crates/custos-browser which login belongs on which page (origins, no fuzzy matching), native messaging frames
crates/custos-native the browser extension's native messaging host: three ops, rebuilt, to custos.exe's pipe only
extension/ the MV3 extension for Edge and Chrome (fixed id jchkapmceepdnlhagfppeckggaecdcmn)
crates/custos-browser which login belongs on which page and frame (origins, public suffixes, no fuzzy matching),
which extension started the host, native messaging frames
crates/custos-native the browser extension's native messaging host: five browser_* ops, rebuilt, to custos.exe's pipe only
extension/ the MV3 extension, one source for Firefox (custos@marek-novak.cz) and Edge/Chrome (fixed id
jchkapmceepdnlhagfppeckggaecdcmn); tools/extension.mjs builds each, tools/extension-test.mjs
docs/FORMAT.md the vault file format, version 1 (versioned; change it before the code)
docs/FACTORS.md version 2: any two factors open the vault; the machine store
docs/KEYS.md secret keys, API keys and key pairs
@@ -36,6 +38,8 @@ docs/TEAM.md team vaults (member slots, kind 6), policies, sign.request
```
cargo test --workspace # all mandatory tests
cargo test --workspace --release # same, faster Argon2
node tools/extension-test.mjs # the extension's background against a fake browser
node tools/extension.mjs --zip # target/extension/{firefox,chromium}/ and their zips
# the browser build, with the server's toolchain (WSL + Nix here; nixpkgs rev as in the Custos flake):
nix shell nixpkgs#cargo nixpkgs#rustc nixpkgs#stdenv.cc nixpkgs#lld -c \n cargo build --release --target wasm32-unknown-unknown -p custos-wasm
node crates/custos-wasm/js/test.mjs <custos_wasm.wasm> [<vault> <password>] # the JS loader against it
Generated
+30 -13
View File
@@ -329,14 +329,15 @@ dependencies = [
[[package]]
name = "custos-browser"
version = "0.18.1"
version = "0.20.0"
dependencies = [
"psl",
"zeroize",
]
[[package]]
name = "custos-gen"
version = "0.18.1"
version = "0.20.0"
dependencies = [
"custos-vault",
"data-encoding",
@@ -348,7 +349,7 @@ dependencies = [
[[package]]
name = "custos-kdbx"
version = "0.18.1"
version = "0.20.0"
dependencies = [
"aes",
"argon2",
@@ -369,7 +370,7 @@ dependencies = [
[[package]]
name = "custos-keys"
version = "0.18.1"
version = "0.20.0"
dependencies = [
"custos-vault",
"ed25519-dalek",
@@ -382,9 +383,10 @@ dependencies = [
[[package]]
name = "custos-native"
version = "0.18.1"
version = "0.20.0"
dependencies = [
"custos-browser",
"rand 0.10.3",
"serde_json",
"windows-sys",
"zeroize",
@@ -392,11 +394,11 @@ dependencies = [
[[package]]
name = "custos-qr"
version = "0.18.1"
version = "0.20.0"
[[package]]
name = "custos-seal"
version = "0.18.1"
version = "0.20.0"
dependencies = [
"chacha20poly1305",
"hkdf",
@@ -409,7 +411,7 @@ dependencies = [
[[package]]
name = "custos-share"
version = "0.18.1"
version = "0.20.0"
dependencies = [
"argon2",
"chacha20poly1305",
@@ -426,7 +428,7 @@ dependencies = [
[[package]]
name = "custos-sign"
version = "0.18.1"
version = "0.20.0"
dependencies = [
"blake2 0.10.6",
"data-encoding",
@@ -446,7 +448,7 @@ dependencies = [
[[package]]
name = "custos-team"
version = "0.18.1"
version = "0.20.0"
dependencies = [
"custos-seal",
"custos-sign",
@@ -464,7 +466,7 @@ dependencies = [
[[package]]
name = "custos-totp"
version = "0.18.1"
version = "0.20.0"
dependencies = [
"custos-vault",
"data-encoding",
@@ -477,7 +479,7 @@ dependencies = [
[[package]]
name = "custos-vault"
version = "0.18.1"
version = "0.20.0"
dependencies = [
"argon2",
"bip39",
@@ -503,7 +505,7 @@ dependencies = [
[[package]]
name = "custos-wasm"
version = "0.18.1"
version = "0.20.0"
dependencies = [
"custos-qr",
"custos-seal",
@@ -1025,6 +1027,21 @@ dependencies = [
"unicode-ident",
]
[[package]]
name = "psl"
version = "2.1.261"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3058f918351d1ee290ff4e70243e419b33269dcb83bc8cd46c5afa8a97a90012"
dependencies = [
"psl-types",
]
[[package]]
name = "psl-types"
version = "2.0.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "33cb294fe86a74cbcf50d4445b37da762029549ebeea341421c7c70370f86cac"
[[package]]
name = "qrcode"
version = "0.14.1"
+1 -1
View File
@@ -3,7 +3,7 @@ resolver = "3"
members = ["crates/*"]
[workspace.package]
version = "0.18.1"
version = "0.20.0"
edition = "2024"
license = "MPL-2.0"
repository = "https://gitea.marek-novak.cz/mnovak/CustosPublic"
+1 -1
View File
@@ -12,7 +12,7 @@ password and secret manager: everything that touches plaintext or keys.
| `custos-share` | Private share links: encrypted in the sender's app, key in the link's `#fragment`, optional password ([`docs/SHARE.md`](docs/SHARE.md)) |
| `custos-wasm` | The same code compiled to WebAssembly for the web vault and the share page (no wasm-bindgen; `js/custos.mjs` is the whole JS side) |
| `custos-kdbx` | KeePass import (KDBX 3.1 and 4) and export (KDBX 4), checked against KeePassXC ([`docs/KDBX.md`](docs/KDBX.md)) |
| `custos-browser`, `custos-native`, `extension/` | The Edge/Chrome extension, its native messaging host and the rule for which login belongs on which page ([`docs/BROWSER.md`](docs/BROWSER.md)) |
| `custos-browser`, `custos-native`, `extension/` | The Firefox, Edge and Chrome extension, its native messaging host and the rule for which login belongs on which page ([`docs/BROWSER.md`](docs/BROWSER.md)) |
Read [`docs/FORMAT.md`](docs/FORMAT.md) for the file format and [`docs/THREAT_MODEL.md`](docs/THREAT_MODEL.md)
for what it does and does not protect. Report vulnerabilities as described in [`SECURITY.md`](SECURITY.md).
+2
View File
@@ -7,4 +7,6 @@ license.workspace = true
repository.workspace = true
[dependencies]
# Mozilla's Public Suffix List, compiled in: a login for `github.io` or `co.uk` never goes to their subdomains.
psl = "2"
zeroize.workspace = true
+66
View File
@@ -0,0 +1,66 @@
//! Which extension started the native host. Browsers start `custos-native.exe` only for the extensions its
//! host manifest names (`allowed_origins` for Chromium, `allowed_extensions` for Firefox), and they say which
//! one it was in the host's arguments:
//!
//! - **Chromium** (Edge, Chrome): the first argument is the caller's origin, `chrome-extension://<id>/`
//! (then `--parent-window=<n>` on Windows);
//! - **Firefox**: the first argument is the host manifest's path, the second the add-on's id.
//!
//! The host checks them again ([`caller`]) and answers every request from anything else with `not_allowed`,
//! without reaching Custos: a second line behind the browser's own check, for a manifest someone else wrote.
/// The Chromium extension's id, fixed by the public key in its manifest (`extension/manifest.chromium.json`).
pub const CHROMIUM_ID: &str = "jchkapmceepdnlhagfppeckggaecdcmn";
/// The Firefox add-on's id (`browser_specific_settings.gecko.id` in `extension/manifest.firefox.json`).
pub const FIREFOX_ID: &str = "custos@marek-novak.cz";
/// The kind of browser the Custos extension runs in, as its host's arguments say.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Browser {
Chromium,
Firefox,
}
/// The caller of the host, from its arguments without the program name; `None` unless it is the Custos
/// extension.
pub fn caller<S: AsRef<str>>(args: &[S]) -> Option<Browser> {
let first = args.first()?.as_ref();
if first == format!("chrome-extension://{CHROMIUM_ID}/") {
return Some(Browser::Chromium);
}
// Firefox: <manifest path> <add-on id>. The path is the browser's business; the id must be exactly ours.
if first.to_ascii_lowercase().ends_with(".json") && args.get(1).map(AsRef::as_ref) == Some(FIREFOX_ID) {
return Some(Browser::Firefox);
}
None
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn only_the_custos_extension_may_use_the_host() {
let edge = ["chrome-extension://jchkapmceepdnlhagfppeckggaecdcmn/", "--parent-window=0"];
assert_eq!(caller(&edge), Some(Browser::Chromium));
let firefox = [r"F:\Apps\Custos\cz.marek_novak.custos.firefox.json", "custos@marek-novak.cz"];
assert_eq!(caller(&firefox), Some(Browser::Firefox));
// Any other extension, a look-alike id, or no arguments at all (started by hand): refused.
let refused: [&[&str]; 11] = [
&["chrome-extension://aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/"],
&["chrome-extension://jchkapmceepdnlhagfppeckggaecdcmnx/"],
&["chrome-extension://jchkapmceepdnlhagfppeckggaecdcmn"],
&["CHROME-EXTENSION://JCHKAPMCEEPDNLHAGFPPECKGGAECDCMN/"],
&["moz-extension://jchkapmceepdnlhagfppeckggaecdcmn/"],
&[r"C:\x\manifest.json", "evil@example.com"],
&[r"C:\x\manifest.json", "custos@marek-novak.cz.evil"],
&[r"C:\x\manifest.json", "Custos@marek-novak.cz"],
&["custos@marek-novak.cz"],
&[r"C:\x\manifest.txt", "custos@marek-novak.cz"],
&[],
];
for other in refused {
assert_eq!(caller(other), None, "{other:?}");
}
}
}
+114 -3
View File
@@ -6,7 +6,10 @@
//! - [`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).
//! - [`fill_allowed`]: the same for a login field in a frame: the frame's origin, and the top page's too when
//! the frame is not the top page, so a login never goes into a site embedded by another one.
//! - [`caller`]: which extension started the native host (the browser's arguments), refused unless it is Custos's.
//! - [`framing`]: native messaging frames (a 4-byte little-endian length, then JSON), the same in every browser.
//!
//! ```
//! use custos_browser::{login_matches, Origin};
@@ -16,6 +19,7 @@
//! # Ok::<(), custos_browser::OriginError>(())
//! ```
pub mod caller;
pub mod framing;
use std::fmt;
@@ -95,6 +99,7 @@ fn split(url: &str, default: Option<Scheme>) -> Result<(Scheme, String, Option<u
}
let port = match port {
None | Some("") => None,
Some(p) if !p.bytes().all(|b| b.is_ascii_digit()) => return Err(OriginError::BadPort),
Some(p) => Some(
p.parse::<u16>()
.map_err(|_| OriginError::BadPort)
@@ -157,7 +162,8 @@ pub enum Match {
/// 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.
/// an IP address matches only that exact host, and so does a login for a public suffix (`co.uk`, `github.io`,
/// Mozilla's Public Suffix List): its subdomains belong to different people.
pub fn login_matches(item_url: &str, page: &Origin) -> Option<Match> {
if !page.fillable() {
return None;
@@ -171,7 +177,7 @@ pub fn login_matches(item_url: &str, page: &Origin) -> Option<Match> {
if item == at {
return Some(Match::Exact);
}
if page.is_ip() || !item.contains('.') || item.starts_with('[') {
if page.is_ip() || !item.contains('.') || item.starts_with('[') || psl::domain_str(&item).is_none() {
return None;
}
at.strip_suffix(&item).filter(|rest| rest.ends_with('.')).map(|_| Match::Subdomain)
@@ -182,6 +188,23 @@ pub fn best_match<'a>(urls: impl IntoIterator<Item = &'a str>, page: &Origin) ->
urls.into_iter().filter_map(|u| login_matches(u, page)).min()
}
/// May the login with `urls` be filled into a field of the frame at `frame`, on the tab whose top page is `top`?
///
/// The frame must match (it is where the password goes). A frame that is not the top page (another origin) must
/// match **and** the top page must match too: `evil.net` embedding `github.com/login` in an iframe gets nothing,
/// and neither does a `github.com` page that embeds an advertiser's frame. The answer is the frame's match.
pub fn fill_allowed<'a>(
urls: impl IntoIterator<Item = &'a str> + Clone,
frame: &Origin,
top: &Origin,
) -> Option<Match> {
let m = best_match(urls.clone(), frame)?;
if frame != top && best_match(urls, top).is_none() {
return None;
}
Some(m)
}
#[cfg(test)]
mod tests {
use super::*;
@@ -278,4 +301,92 @@ mod tests {
Some(Match::Subdomain)
);
}
/// Hostile pages, one trick each: none of them gets the `github.com` login.
#[test]
fn spoofed_addresses_never_get_a_login() {
let gh = "https://github.com";
// Look-alike hosts: punycode twins (Cyrillic and Greek letters), extra labels, hyphens, typos.
for evil in [
"https://xn--gthub-n4a.com/",
"https://xn--80ak6aa92e.com/",
"https://xn--github-xyz.com/",
"https://github.com.evil.net/",
"https://www.github.com.evil.net/",
"https://github.com-login.evil.net/",
"https://wwwgithub.com/",
"https://github.co.evil.net/",
"https://evil.net/github.com",
"https://evil.net/?next=https://github.com",
"https://evil.net/#@github.com",
] {
assert_eq!(login_matches(gh, &page(evil)), None, "{evil}");
}
// Addresses that hide their host: userinfo, encoded dots, backslashes, unicode, odd ports. Refused outright.
for bad in [
"https://github.com@evil.net/",
"https://github.com:443@evil.net/",
r"https://evil.net\@github.com/",
"https://github%2ecom/",
"https://github.com%2eevil.net/",
r"https://github.com\.evil.net/",
"https://g\u{0456}thub.com/",
"https://github.com:+443/",
"https://github.com:-1/",
"https://github.com: 443/",
] {
assert!(Origin::parse(bad).is_err(), "{bad}");
}
// A stored URL that hides its host never matches either.
assert_eq!(login_matches("https://evil.net@github.com", &page("https://github.com/")), None);
assert_eq!(
login_matches("https://bücher.de", &page("https://xn--bcher-kva.de/")),
None,
"only what the browser reports"
);
// Plain http, even of the right host, and https logins on http pages: never.
assert_eq!(login_matches(gh, &page("http://github.com/")), None);
assert_eq!(login_matches("http://github.com", &page("http://github.com/")), None);
assert_eq!(login_matches("http://github.com", &page("https://github.com/")), None);
// The case and a trailing dot are the same host; that is not a trick.
assert_eq!(login_matches(gh, &page("https://GITHUB.com./")), Some(Match::Exact));
}
#[test]
fn a_public_suffix_has_no_subdomains_to_fill() {
// Anyone can own a subdomain of these: a login saved for the suffix itself fits only the suffix.
for (login, other) in [
("https://github.io", "https://attacker.github.io/"),
("https://co.uk", "https://bank.co.uk/"),
("https://blogspot.com", "https://evil.blogspot.com/"),
("https://herokuapp.com", "https://evil.herokuapp.com/"),
] {
assert_eq!(login_matches(login, &page(other)), None, "{login} on {other}");
assert_eq!(login_matches(login, &page(&format!("{login}/"))), Some(Match::Exact), "{login}");
}
// A site on such a suffix keeps its own subdomains.
assert_eq!(
login_matches("https://mark.github.io", &page("https://docs.mark.github.io/")),
Some(Match::Subdomain)
);
assert_eq!(login_matches("https://mark.github.io", &page("https://eve.github.io/")), None);
assert_eq!(login_matches("https://bank.co.uk", &page("https://login.bank.co.uk/")), Some(Match::Subdomain));
}
#[test]
fn a_frame_gets_a_login_only_when_its_page_would_too() {
let gh = ["https://github.com"];
let (login, top_gh, evil) =
(page("https://github.com/login"), page("https://github.com/"), page("https://evil.net/"));
// The top page itself.
assert_eq!(fill_allowed(gh, &login, &login), Some(Match::Exact));
// A frame of the same site, on a page of the same site.
assert_eq!(fill_allowed(gh, &page("https://gist.github.com/"), &top_gh), Some(Match::Subdomain));
// github.com framed by evil.net: the frame's own origin matches, the page does not. Nothing.
assert_eq!(fill_allowed(gh, &login, &evil), None);
// An evil frame on github.com: its own origin does not match. Nothing.
assert_eq!(fill_allowed(gh, &evil, &top_gh), None);
// A plain-http top page around an https frame of the site: nothing either.
assert_eq!(fill_allowed(gh, &login, &page("http://github.com/")), None);
}
}
+1
View File
@@ -8,6 +8,7 @@ repository.workspace = true
[dependencies]
custos-browser = { path = "../custos-browser" }
rand.workspace = true
serde_json.workspace = true
zeroize.workspace = true
+167 -35
View File
@@ -1,37 +1,95 @@
//! 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:
//! custos-native: the browser extension's native messaging host (docs/BROWSER.md). Firefox, Edge or Chrome
//! starts it when the extension connects, and talks to it over stdin/stdout in native messaging frames. It
//! forwards five 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.
//! - `browser_status`: is Custos running, and this connection's match code;
//! - `browser_match { origin, top }`: the logins for a frame (title, username, has 2FA; never a password);
//! - `browser_fill { id, origin, top }`: one login's username, password and 2FA code, when it matches;
//! - `browser_totp { id, origin, top }`: only the 2FA code, for the popup;
//! - `browser_save { origin, top, username, password, title }`: offer a new login (or a changed password);
//! Custos shows a card and stores it only on *Save*.
//!
//! 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.
//! The host adds nothing and decides nothing: Custos checks the origins against the login and asks the user
//! once whether this host may use web logins. It forwards only those requests, rebuilt from their known fields,
//! so the extension cannot reach Custos's other Domi requests through it. It answers nothing to an extension
//! that is not Custos's (`custos_browser::caller`), and it refuses a pipe that is not served by custos.exe.
//!
//! Every request carries this connection's `session`: 32 random bytes made when the host starts. Custos shows
//! their match code on its card and in the audit; the extension shows the same code in its popup.
use std::io::{self, Write};
use custos_browser::caller::{Browser, caller};
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"];
const OPS: &[&str] = &["browser_status", "browser_match", "browser_fill", "browser_totp", "browser_save"];
/// The connection: who started the host, and its session.
struct Conn {
browser: Browser,
session: String,
}
impl Conn {
fn new(browser: Browser) -> Conn {
use rand::Rng;
let mut raw = Zeroizing::new([0u8; 32]);
rand::rand_core::UnwrapErr(rand::rngs::SysRng).fill_bytes(raw.as_mut());
Conn { browser, session: raw.iter().map(|b| format!("{b:02x}")).collect() }
}
/// The browser's name as Custos shows it: Firefox is what the arguments say; for Chromium the extension
/// names it (Edge or Chrome), a label only.
fn browser_name(&self, hint: Option<&str>) -> &'static str {
match (self.browser, hint) {
(Browser::Firefox, _) => "firefox",
(Browser::Chromium, Some("edge")) => "edge",
(Browser::Chromium, Some("chrome")) => "chrome",
(Browser::Chromium, _) => "chromium",
}
}
}
/// A string field of at most `max` bytes, or `bad_request`.
fn field<'a>(v: &'a Value, name: &str, max: usize) -> Result<&'a str, &'static str> {
v.get(name).and_then(Value::as_str).filter(|s| s.len() <= max).ok_or("bad_request")
}
/// The request Custos gets: only known fields, of the right types.
fn rebuild(msg: &[u8]) -> Result<Value, &'static str> {
fn rebuild(msg: &[u8], conn: &Conn) -> Result<Value, &'static str> {
let v: Value = serde_json::from_slice(msg).map_err(|_| "bad_request")?;
let out = build(&v, conn);
// The parsed message can hold a password: wiped before it is dropped.
zeroize_json(v);
out
}
fn build(v: &Value, conn: &Conn) -> Result<Value, &'static str> {
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" });
let hint = v.get("browser").and_then(Value::as_str);
let mut out = json!({
"op": op,
"app": "Custos for your browser",
"browser": conn.browser_name(hint),
"session": conn.session,
});
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();
out["origin"] = field(v, "origin", 2048)?.into();
out["top"] = field(v, "top", 2048)?.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();
if matches!(op, "browser_fill" | "browser_totp") {
out["id"] = field(v, "id", 128)?.into();
}
if op == "browser_save" {
out["username"] = field(v, "username", 1024)?.into();
out["password"] =
field(v, "password", 4096).and_then(|p| if p.is_empty() { Err("bad_request") } else { Ok(p) })?.into();
if let Some(t) = v.get("title") {
out["title"] = t.as_str().filter(|t| t.len() <= 200).ok_or("bad_request")?.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) {
@@ -44,13 +102,19 @@ 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>> {
/// One answer. `conn` is `None` when the host was started by anything but the Custos extension: then every
/// request gets `not_allowed` and nothing reaches Custos.
fn answer(msg: &[u8], conn: Option<&Conn>, 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) {
let Some(conn) = conn else {
return Zeroizing::new(error("not_allowed", seq));
};
let req = match rebuild(msg, conn) {
Ok(r) => r,
Err(code) => return Zeroizing::new(error(code, seq)),
};
let bytes = Zeroizing::new(serde_json::to_vec(&req).unwrap_or_default());
zeroize_json(req);
match pipe::call(pipe, &bytes) {
Ok(resp) => {
// Custos does not know the extension's request number: put it back.
@@ -68,13 +132,16 @@ fn answer(msg: &[u8], pipe: &str) -> Zeroizing<Vec<u8>> {
}
}
/// Wipes the strings of a parsed answer (it can hold a password) before dropping it.
/// Wipes the strings of a parsed message (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)),
Value::Object(o) => o.into_iter().for_each(|(mut k, v)| {
k.zeroize();
zeroize_json(v)
}),
_ => {}
}
}
@@ -82,6 +149,8 @@ fn zeroize_json(v: Value) {
fn main() {
// Tests point the host at another Custos.
let pipe = std::env::var("CUSTOS_PIPE").unwrap_or_else(|_| PIPE.to_string());
let args: Vec<String> = std::env::args().skip(1).collect();
let conn = caller(&args).map(Conn::new);
let (mut stdin, stdout) = (io::stdin().lock(), io::stdout());
loop {
let msg = match read_frame(&mut stdin) {
@@ -89,7 +158,7 @@ fn main() {
// The extension disconnected, or sent something that is not a frame: done.
Ok(None) | Err(_) => return,
};
let out = answer(&msg, &pipe);
let out = answer(&msg, conn.as_ref(), &pipe);
let mut w = stdout.lock();
if write_frame(&mut w, &out).is_err() || w.flush().is_err() {
return;
@@ -205,36 +274,99 @@ mod pipe {
mod tests {
use super::*;
fn conn(b: Browser) -> Conn {
Conn::new(b)
}
#[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();
fn only_the_browser_requests_pass_rebuilt_from_known_fields() {
let c = conn(Browser::Chromium);
let fill = rebuild(
br#"{"op":"browser_fill","id":"abc","origin":"https://github.com","top":"https://github.com","seq":7,"ref":"domi://arca/x","namespace":"arca","browser":"edge","session":"mine"}"#,
&c,
)
.unwrap();
assert_eq!(
fill,
json!({ "op": "browser_fill", "id": "abc", "origin": "https://github.com", "seq": 7, "app": "Custos for your browser" })
json!({ "op": "browser_fill", "id": "abc", "origin": "https://github.com", "top": "https://github.com", "seq": 7,
"app": "Custos for your browser", "browser": "edge", "session": c.session })
);
assert_eq!(rebuild(br#"{"op":"browser_status"}"#).unwrap()["op"], "browser_status");
assert!(rebuild(br#"{"op":"browser_match","origin":"https://a.cz"}"#).is_ok());
assert_eq!(c.session.len(), 64, "the host's own session, never the extension's");
assert_ne!(c.session, conn(Browser::Chromium).session, "a new one for every connection");
assert_eq!(rebuild(br#"{"op":"browser_status"}"#, &c).unwrap()["op"], "browser_status");
assert!(rebuild(br#"{"op":"browser_match","origin":"https://a.cz","top":"https://a.cz"}"#, &c).is_ok());
let totp =
rebuild(br#"{"op":"browser_totp","id":"x","origin":"https://a.cz","top":"https://a.cz"}"#, &c).unwrap();
assert_eq!(totp["id"], "x");
let save = rebuild(
br#"{"op":"browser_save","origin":"https://a.cz","top":"https://a.cz","username":"mark","password":"pw","title":"A","extra":1}"#,
&c,
)
.unwrap();
assert_eq!(
(save["username"].as_str(), save["password"].as_str(), save["title"].as_str()),
(Some("mark"), Some("pw"), Some("A"))
);
assert!(save.get("extra").is_none());
// The browser's name: Firefox from the arguments, whatever the extension says; Chromium names itself.
let f = conn(Browser::Firefox);
assert_eq!(rebuild(br#"{"op":"browser_status","browser":"chrome"}"#, &f).unwrap()["browser"], "firefox");
assert_eq!(rebuild(br#"{"op":"browser_status","browser":"lynx"}"#, &c).unwrap()["browser"], "chromium");
// 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"}"#,
r#"{"op":"sign"}"#,
r#"{"op":"browser_anything","origin":"https://a.cz","top":"https://a.cz"}"#,
] {
assert_eq!(rebuild(other.as_bytes()), Err("bad_request"), "{other}");
assert_eq!(rebuild(other.as_bytes(), &c), Err("bad_request"), "{other}");
}
// Missing or wrong fields, or too long.
for bad in [
r#"{"op":"browser_fill","origin":"https://a.cz","top":"https://a.cz"}"#,
r#"{"op":"browser_fill","id":"x","origin":"https://a.cz"}"#,
r#"{"op":"browser_match","origin":5,"top":"https://a.cz"}"#,
r#"{"op":"browser_save","origin":"https://a.cz","top":"https://a.cz","username":"m"}"#,
r#"{"op":"browser_save","origin":"https://a.cz","top":"https://a.cz","username":"m","password":""}"#,
r#"{"op":"browser_save","origin":"https://a.cz","top":"https://a.cz","username":"m","password":"p","title":7}"#,
"not json",
] {
assert!(rebuild(bad.as_bytes(), &c).is_err(), "{bad}");
}
let long = format!(
r#"{{"op":"browser_fill","id":"{}","origin":"https://a.cz","top":"https://a.cz"}}"#,
"x".repeat(129)
);
assert!(rebuild(long.as_bytes(), &c).is_err());
}
#[test]
fn an_extension_that_is_not_custos_gets_nothing() {
// Started by another extension (or by hand): `not_allowed` for every request, and the pipe is never
// opened (this pipe does not exist; reaching for it would answer `not_running`).
let args = ["chrome-extension://aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/"];
let conn = caller(&args).map(Conn::new);
assert!(conn.is_none());
for msg in [
&br#"{"op":"browser_status","seq":1}"#[..],
br#"{"op":"browser_match","origin":"https://github.com","top":"https://github.com","seq":2}"#,
br#"{"op":"browser_fill","id":"x","origin":"https://github.com","top":"https://github.com","seq":3}"#,
] {
let v: Value =
serde_json::from_slice(&answer(msg, conn.as_ref(), r"\\.\pipe\custos-test-nobody-here")).unwrap();
assert_eq!(v["error"], "not_allowed");
}
// 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 c = conn(Browser::Firefox);
let out = answer(br#"{"op":"browser_status","seq":3}"#, Some(&c), 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();
let bad: Value = serde_json::from_slice(&answer(br#"{"op":"get","seq":4}"#, Some(&c), PIPE)).unwrap();
assert_eq!(bad, json!({ "ok": false, "error": "bad_request", "seq": 4 }));
}
}
+23
View File
@@ -829,6 +829,29 @@ mod tests {
assert_eq!(full.standing_rules()[0].uses, u64::MAX);
}
#[test]
fn a_broken_android_grant_makes_the_vault_refuse_to_open() {
let mut v = vault();
v.android_grant_set(&["mnovak/*".to_string()], "Marek Novak", "CZ", NOW).unwrap();
let json = body_json(&v);
assert!(Vault::open(&with_body(&v, &json), &SecretString::from("pw")).is_ok());
let from = r#""repos":["mnovak/*"],"o":"Marek Novak","c":"CZ""#;
assert!(json.contains(from), "{json}");
for to in [
r#""repos":["*/*"],"o":"Marek Novak","c":"CZ""#,
r#""repos":["*"],"o":"Marek Novak","c":"CZ""#,
r#""repos":[],"o":"Marek Novak","c":"CZ""#,
r#""repos":["mnovak/*","mnovak/*"],"o":"Marek Novak","c":"CZ""#,
r#""repos":["mnovak/*"],"o":"","c":"CZ""#,
r#""repos":["mnovak/*"],"o":"Marek Novak","c":"Czech""#,
r#""repos":["mnovak/*"],"o":"Marek Novak","c":"CZ","made":["Not An Id"]"#,
] {
let bad = json.replacen(from, to, 1);
let r = Vault::open(&with_body(&v, &bad), &SecretString::from("pw"));
assert!(matches!(r, Err(Error::Corrupted)), "{to}: {r:?}");
}
}
#[test]
fn a_broken_standing_approval_makes_the_vault_refuse_to_open() {
let v = vault_with_a_standing_approval();
+234 -4
View File
@@ -203,6 +203,35 @@ pub struct StandingRule {
/// At most this many standing approvals in a vault.
pub const STANDING_MAX: usize = 256;
/// The Android grant (core 0.19.0, docs/SIGNING.md "The Android grant"): Mark's one answer for every Domi app's
/// release APK. It signs an app key's APKs from this PC's pipe, its first signature included, and makes the key when
/// the app's first release asks. Nothing in it is secret.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct AndroidGrant {
/// `owner/name` or `owner/*`, 1 to [`ANDROID_PATTERNS_MAX`].
pub repos: Vec<String>,
/// The organisation and country in the certificates of the keys it makes.
pub o: String,
pub c: String,
/// Unix milliseconds: when Mark granted it, or last changed it.
pub granted: i64,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub last_used: Option<i64>,
#[serde(default)]
pub uses: u64,
/// The ids of the keys it made, oldest first.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub made: Vec<String>,
}
/// The one pipeline the Android grant covers.
pub const ANDROID_PIPELINE: &str = "release";
/// At most this many repository patterns in the Android grant.
pub const ANDROID_PATTERNS_MAX: usize = 64;
/// At most this many keys the Android grant remembers making.
const ANDROID_MADE_MAX: usize = 256;
/// A signature handed back to the build.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Signed {
@@ -269,6 +298,7 @@ pub(crate) struct Store {
pub(crate) keys: Vec<Key>,
pub(crate) audit: Vec<AuditEntry>,
standing: Vec<StandingRule>,
android: Option<AndroidGrant>,
}
#[derive(Serialize, Deserialize)]
@@ -303,6 +333,9 @@ pub(crate) struct StoreJson {
/// Standing approvals (core 0.16.0); absent while there are none.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
standing: Vec<StandingRule>,
/// The Android grant (core 0.19.0); absent while there is none. Older cores ignore and drop it.
#[serde(default, skip_serializing_if = "Option::is_none")]
android: Option<AndroidGrant>,
}
fn b64(bytes: &[u8]) -> String {
@@ -330,7 +363,7 @@ fn unhex8(s: &str) -> Option<[u8; 8]> {
impl Store {
pub(crate) fn is_empty(&self) -> bool {
self.keys.is_empty() && self.audit.is_empty() && self.standing.is_empty()
self.keys.is_empty() && self.audit.is_empty() && self.standing.is_empty() && self.android.is_none()
}
pub(crate) fn from_json(j: StoreJson) -> Option<Store> {
@@ -389,7 +422,10 @@ impl Store {
if j.standing.len() > STANDING_MAX || !j.standing.iter().all(rule_ok) {
return None;
}
Some(Store { keys, audit: j.audit, standing: j.standing })
if j.android.as_ref().is_some_and(|g| !grant_ok(g)) {
return None;
}
Some(Store { keys, audit: j.audit, standing: j.standing, android: j.android })
}
pub(crate) fn json(&self) -> Option<StoreJson> {
@@ -418,7 +454,12 @@ impl Store {
repos: k.repos.clone(),
})
.collect();
Some(StoreJson { keys, audit: self.audit.clone(), standing: self.standing.clone() })
Some(StoreJson {
keys,
audit: self.audit.clone(),
standing: self.standing.clone(),
android: self.android.clone(),
})
}
pub(crate) fn get(&self, id: &str) -> Option<&Key> {
@@ -514,6 +555,64 @@ fn rule_words(r: &StandingRule) -> String {
format!("{} {} {} pipeline {} {}{targets}", r.repo, r.key, kind_word(r.kind), r.pipeline, via_word(r.via))
}
/// `owner/name`, each 1 to 64 of `A-Z a-z 0-9 . _ -`: the owner and the name, or `None`.
fn repo_parts(repo: &str) -> Option<(&str, &str)> {
let part =
|x: &str| (1..=64).contains(&x.len()) && x.bytes().all(|b| b.is_ascii_alphanumeric() || b"._-".contains(&b));
let (owner, name) = repo.split_once('/')?;
(part(owner) && part(name)).then_some((owner, name))
}
/// The app key of a repository (core 0.19.0): `mnovak/Culina` is `culina-android` (the name in lower case, `.` and
/// `_` as `-`); `None` for anything that is not `owner/name` or an id longer than 64.
pub fn android_key_id(repo: &str) -> Option<String> {
let (_, name) = repo_parts(repo)?;
let id: String = name.chars().map(|c| if c == '.' || c == '_' { '-' } else { c.to_ascii_lowercase() }).collect();
let id = format!("{id}-android");
(id.len() <= 64).then_some(id)
}
/// A pattern of the Android grant: `owner/name`, or `owner/*` for every repository of that owner.
fn grant_pattern_ok(p: &str) -> bool {
match p.strip_suffix("/*") {
Some(owner) => repo_parts(&format!("{owner}/x")).is_some(),
None => repo_parts(p).is_some(),
}
}
fn grant_covers(g: &AndroidGrant, repo: &str) -> bool {
let Some((owner, _)) = repo_parts(repo) else { return false };
g.repos.iter().any(|p| p == repo || p.strip_suffix("/*") == Some(owner))
}
/// The certificate's O (1 to 64, no control characters) and C (two ASCII capitals) for the keys the grant makes.
fn grant_subject_ok(o: &str, c: &str) -> bool {
(1..=64).contains(&o.chars().count())
&& !o.chars().any(char::is_control)
&& o.trim() == o
&& c.len() == 2
&& c.bytes().all(|b| b.is_ascii_uppercase())
}
/// A stored grant is what [`Vault::android_grant_set`] could have written; anything else makes the vault refuse to
/// open.
fn grant_ok(g: &AndroidGrant) -> bool {
let id_ok = |id: &String| {
(1..=64).contains(&id.len()) && id.bytes().all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-')
};
(1..=ANDROID_PATTERNS_MAX).contains(&g.repos.len())
&& g.repos.iter().all(|p| grant_pattern_ok(p))
&& g.repos.iter().enumerate().all(|(i, p)| !g.repos[..i].contains(p))
&& grant_subject_ok(&g.o, &g.c)
&& g.made.len() <= ANDROID_MADE_MAX
&& g.made.iter().all(id_ok)
}
/// What the grant says, for the security audit: names only.
fn grant_words(g: &AndroidGrant) -> String {
format!("Android releases: {} pipeline {ANDROID_PIPELINE}, keys made on first use", g.repos.join(", "))
}
fn in_scope(list: &[String], what: &str) -> bool {
list.iter().any(|x| x == "*" || x == what)
}
@@ -846,7 +945,9 @@ impl Vault {
return Err(r);
}
let rule = self.standing_rule_for(req, now).map(|r| r.id);
if approval == Approval::Standing && rule.is_none() {
// A standing approval first; the Android grant only where none fits (core 0.19.0).
let by_grant = approval == Approval::Standing && rule.is_none() && self.android_grant_fits(req, now);
if approval == Approval::Standing && rule.is_none() && !by_grant {
let r = Refusal::NeedsApproval(req.key.clone());
self.signing_record(req, Outcome::Refused, Some(r.to_string()), None, now);
return Err(r);
@@ -902,6 +1003,10 @@ impl Vault {
r.uses = r.uses.saturating_add(1);
r.last_used = Some(now);
}
if by_grant && let Some(g) = self.signing.android.as_mut() {
g.uses = g.uses.saturating_add(1);
g.last_used = Some(now);
}
Ok(Signed { bytes, sha256 })
}
@@ -1091,6 +1196,131 @@ impl Vault {
true
}
/// The Android grant, if Mark gave it (core 0.19.0, docs/SIGNING.md "The Android grant").
pub fn android_grant(&self) -> Option<AndroidGrant> {
self.signing.android.clone()
}
/// Stores the Android grant, or replaces its patterns and subject (its counts and the keys it made stay), and
/// writes `standing-granted`. Refused while *Sign only with a card* is ticked. Call it only from Mark's own
/// click. The caller saves.
pub fn android_grant_set(&mut self, repos: &[String], o: &str, c: &str, now: i64) -> Result<AndroidGrant, Error> {
if self.security.is_ticked(crate::security::Item::CardSigning) {
return Err(Error::Signing("Sign only with a card is ticked".into()));
}
let mut patterns: Vec<String> = Vec::new();
for p in repos.iter().map(|p| p.trim()).filter(|p| !p.is_empty()) {
if !grant_pattern_ok(p) {
return Err(Error::Signing(format!(
"`{p}` is not a repository (owner/name) or every repository of an owner (owner/*)"
)));
}
if !patterns.iter().any(|x| x == p) {
patterns.push(p.to_string());
}
}
if patterns.is_empty() || patterns.len() > ANDROID_PATTERNS_MAX {
return Err(Error::Signing(format!("the grant names 1 to {ANDROID_PATTERNS_MAX} repositories")));
}
if !grant_subject_ok(o, c) {
return Err(Error::Signing(
"the certificates need an organisation (1-64 characters) and a two-letter country code".into(),
));
}
let old = self.signing.android.clone();
let grant = AndroidGrant {
repos: patterns,
o: o.into(),
c: c.into(),
granted: now,
last_used: old.as_ref().and_then(|g| g.last_used),
uses: old.as_ref().map_or(0, |g| g.uses),
made: old.map(|g| g.made).unwrap_or_default(),
};
self.security.standing_note(crate::security::Action::StandingGranted, &grant_words(&grant), now);
self.signing.android = Some(grant.clone());
Ok(grant)
}
/// Removes the Android grant (`standing-revoked`); the keys it made stay. False when there is none. The caller
/// saves.
pub fn android_grant_revoke(&mut self, now: i64) -> bool {
let Some(g) = self.signing.android.take() else { return false };
self.security.standing_note(crate::security::Action::StandingRevoked, &grant_words(&g), now);
true
}
/// Whether `req` is signed by the Android grant: an `apk` from this PC's pipe with a run, in the key's scope, for
/// a repository the grant covers and pipeline `release`, by that repository's own app key (scoped to exactly it
/// and `release`, role release), while *Sign only with a card* is not ticked. A key's first signature fits.
pub fn android_grant_fits(&self, req: &Request, now: i64) -> bool {
let Some(g) = &self.signing.android else { return false };
let Ok((view, _)) = self.check(req, now) else { return false };
req.kind == SignKind::Apk
&& req.via == Via::Local
&& req.run.is_some()
&& !self.security.is_ticked(crate::security::Item::CardSigning)
&& view.kind == KeyKind::Android
&& view.role == Role::Release
&& req.context.pipeline == ANDROID_PIPELINE
&& grant_covers(g, &req.context.repo)
&& android_key_id(&req.context.repo).as_deref() == Some(req.key.as_str())
&& view.repos == [req.context.repo.clone()]
&& view.pipelines == [ANDROID_PIPELINE.to_string()]
}
/// Makes `repo`'s app key under the Android grant, when its first release asks (`custos-sign apk`): the grant
/// covers `repo`, `pipeline` is `release`, `via` is local, *Sign only with a card* is not ticked, and there is
/// no key under that id. RSA-4096, `CN=<Name>`, the grant's O and C, scoped to exactly `repo` and `release`.
/// Writes `standing-granted` with `Android grant made <id> for <repo> pipeline release`: a value every core since
/// 0.16.0 reads, so the phone and the web vault still open the vault (core 0.19.1). The caller saves. Slow: one
/// RSA-4096 key.
pub fn android_grant_make_key(&mut self, repo: &str, pipeline: &str, via: Via, now: i64) -> Result<String, Error> {
let no = |why: String| Err(Error::Signing(why));
let Some(g) = self.signing.android.clone() else { return no("there is no Android grant".into()) };
let (Some((_, name)), Some(id)) = (repo_parts(repo), android_key_id(repo)) else {
return no(format!("`{repo}` is not a repository (owner/name)"));
};
if via != Via::Local {
return no("the server runner never makes a key".into());
}
if pipeline != ANDROID_PIPELINE {
return no(format!("the Android grant makes keys for the pipeline `{ANDROID_PIPELINE}` only"));
}
if self.security.is_ticked(crate::security::Item::CardSigning) {
return no("Sign only with a card is ticked".into());
}
if !grant_covers(&g, repo) {
return no(format!("the Android grant does not cover `{repo}`"));
}
if self.signing.get(&id).is_some() {
return no(format!("there is a key `{id}` already"));
}
let mut cn = name.to_string();
if let Some(first) = cn.get_mut(0..1) {
first.make_ascii_uppercase();
}
let spec = AndroidKey {
id: id.clone(),
name: format!("{cn} Android"),
cn,
o: g.o.clone(),
c: g.c.clone(),
role: Role::Release,
pipelines: vec![ANDROID_PIPELINE.into()],
repos: vec![repo.into()],
};
self.signing_create_android(&spec, now)?;
if let Some(g) = self.signing.android.as_mut()
&& g.made.len() < ANDROID_MADE_MAX
{
g.made.push(id.clone());
}
let words = format!("Android grant made {id} for {repo} pipeline {ANDROID_PIPELINE}");
self.security.standing_note(crate::security::Action::StandingGranted, &words, now);
Ok(id)
}
/// Every request any key was named in, oldest first.
pub fn signing_audit(&self) -> &[AuditEntry] {
&self.signing.audit
+266
View File
@@ -0,0 +1,266 @@
//! The Android grant (core 0.19.0, docs/SIGNING.md "The Android grant"): one answer for every Domi app's release
//! APK. It signs a request for a repository's own app key (`<name>-android`, scoped to exactly that repository and
//! `release`) from this PC's pipe, its first signature included, and makes that key when the app's first release
//! asks. Everything else still needs a card.
use custos_vault::security::{Action, Auth, Item};
use custos_vault::signing::{
AndroidKey, Approval, Context, KeyKind, Outcome, Refusal, Request, Role, SignKind, Via, android_key_id,
};
use custos_vault::{KdfParams, SecretString, Vault};
const FAST: KdfParams = KdfParams { m_cost_kib: 64, t_cost: 1, p_cost: 1 };
const NOW: i64 = 1_793_750_000_000;
const COMMIT: &str = "6925d0cb08b9e0c5c3a4a7a2c37b7f2a9f7ed3b1";
fn s(v: &[&str]) -> Vec<String> {
v.iter().map(|x| x.to_string()).collect()
}
fn vault() -> Vault {
let mut v = Vault::create(&SecretString::from("pw"), FAST).unwrap();
v.signing_create(Role::Release, &s(&["release"]), &s(&["mnovak/Culina"]), NOW).unwrap();
v
}
fn granted(repos: &[&str]) -> Vault {
let mut v = vault();
v.android_grant_set(&s(repos), "Marek Novak", "CZ", NOW).unwrap();
v
}
fn apk(key: &str, repo: &str, pipeline: &str, run: Option<&str>) -> Request {
Request {
key: key.into(),
kind: SignKind::Apk,
digest: vec![5; 64],
manifest: None,
approval: None,
run: run.map(Into::into),
context: Context {
repo: repo.into(),
commit: COMMIT.into(),
pipeline: pipeline.into(),
step: "sign-apk".into(),
trigger: "tag".into(),
file: "Culina-1.2.0.apk".into(),
size: 9_400_000,
sha256: "c4995c6e2e0c20fec7e8dcb05d70144da58f42d379c6705df66edb42abafb8a3".into(),
version: "1.2.0".into(),
},
via: Via::Local,
}
}
fn culina(run: &str) -> Request {
apk("culina-android", "mnovak/Culina", "release", Some(run))
}
fn notes(v: &Vault, action: Action) -> Vec<String> {
v.security_view(NOW + 1_000)
.audit
.into_iter()
.filter(|e| e.action == action)
.map(|e| e.detail.unwrap_or_default())
.collect()
}
#[test]
fn an_app_key_is_named_by_its_repository() {
assert_eq!(android_key_id("mnovak/Culina").as_deref(), Some("culina-android"));
assert_eq!(android_key_id("mnovak/domi-office").as_deref(), Some("domi-office-android"));
assert_eq!(android_key_id("mnovak/Domi.Office_2").as_deref(), Some("domi-office-2-android"));
for bad in ["Culina", "mnovak/", "/Culina", "mnovak/*", "a/b/c", "mnovak/Cu lina", "mnovak/Čulina", ""] {
assert_eq!(android_key_id(bad), None, "{bad}");
}
assert_eq!(android_key_id(&format!("mnovak/{}", "x".repeat(57))), None, "the id would be longer than 64");
}
#[test]
fn the_grant_makes_an_apps_key_and_signs_its_first_apk_without_a_card() {
let mut v = granted(&["mnovak/*"]);
assert!(!v.android_grant_fits(&culina("r-1"), NOW + 1), "no key yet");
let id = v.android_grant_make_key("mnovak/Culina", "release", Via::Local, NOW + 1).unwrap();
assert_eq!(id, "culina-android");
let k = v.signing_keys().into_iter().find(|k| k.id == id).unwrap();
assert_eq!((k.kind, k.role, k.name.as_str()), (KeyKind::Android, Role::Release, "Culina Android"));
assert_eq!((k.pipelines.clone(), k.repos.clone()), (s(&["release"]), s(&["mnovak/Culina"])));
let cert = String::from_utf8_lossy(k.cert.as_ref().unwrap()).into_owned();
assert!(cert.contains("Culina") && cert.contains("Marek Novak"), "the certificate names the app and Mark");
// Its first signature: no card, recorded as `standing`, counted on the grant.
assert!(v.android_grant_fits(&culina("r-1"), NOW + 2));
assert!(v.standing_rule_for(&culina("r-1"), NOW + 2).is_none(), "the grant is not a per-key rule");
let signed = v.signing_sign(&culina("r-1"), Approval::Standing, NOW + 2);
assert!(signed.is_ok(), "{signed:?}");
assert_eq!(v.signing_audit().last().unwrap().outcome, Outcome::Standing);
assert_eq!(v.signing_audit().last().unwrap().context.file, "Culina-1.2.0.apk");
v.signing_sign(&culina("r-2"), Approval::Standing, NOW + 3).unwrap();
let g = v.android_grant().unwrap();
assert_eq!((g.uses, g.last_used, g.made.clone()), (2, Some(NOW + 3), s(&["culina-android"])));
// Granting, then the key it made: both `standing-granted`, a value cores since 0.16.0 read (core 0.19.1).
let granted_note = notes(&v, Action::StandingGranted);
assert_eq!(granted_note.len(), 2, "{granted_note:?}");
assert!(granted_note[0].contains("Android releases") && granted_note[0].contains("mnovak/*"), "{granted_note:?}");
assert_eq!(granted_note[1], "Android grant made culina-android for mnovak/Culina pipeline release");
// The public note call cannot write it.
assert!(v.security_note(Action::StandingGranted, "x", NOW).is_err());
}
#[test]
fn the_grant_never_makes_a_key_it_does_not_cover() {
let mut v = granted(&["mnovak/Culina", "mnovak/Liber"]);
for (repo, pipeline, via, why) in [
("mnovak/Postea", "release", Via::Local, "a repository no pattern matches"),
("someone/Culina", "release", Via::Local, "another owner"),
("mnovak/Culina", "ci", Via::Local, "another pipeline"),
("mnovak/Culina", "release", Via::Remote, "the server runner"),
("Culina", "release", Via::Local, "not owner/name"),
] {
assert!(v.android_grant_make_key(repo, pipeline, via, NOW + 1).is_err(), "{why}");
}
assert!(v.signing_keys().iter().all(|k| k.kind != KeyKind::Android), "nothing was made");
v.android_grant_make_key("mnovak/Liber", "release", Via::Local, NOW + 2).unwrap();
assert!(v.android_grant_make_key("mnovak/Liber", "release", Via::Local, NOW + 3).is_err(), "made once");
v.security_tick(Item::CardSigning, NOW + 4);
assert!(v.android_grant_make_key("mnovak/Culina", "release", Via::Local, NOW + 5).is_err(), "paused");
v.security_untick(Item::CardSigning, Auth::Hello, NOW + 6);
assert!(v.android_grant_revoke(NOW + 7));
assert!(v.android_grant_make_key("mnovak/Culina", "release", Via::Local, NOW + 8).is_err(), "no grant");
assert_eq!(v.android_grant().map(|g| g.made), None);
}
#[test]
fn only_the_repositorys_own_app_key_in_its_own_scope_from_this_pc_with_a_run_fits() {
let mut v = granted(&["mnovak/*"]);
v.android_grant_make_key("mnovak/Culina", "release", Via::Local, NOW).unwrap();
// A key of the right name with a wider scope, and one for the wrong repository, made by hand.
let wide = AndroidKey {
id: "liber-android".into(),
name: "Liber Android".into(),
cn: "Liber".into(),
o: "Marek Novak".into(),
c: "CZ".into(),
role: Role::Release,
pipelines: s(&["release"]),
repos: s(&["*"]),
};
v.signing_create_android(&wide, NOW).unwrap();
v.signing_create_android(
&AndroidKey { id: "other-android".into(), repos: s(&["mnovak/Rosea"]), ..wide.clone() },
NOW,
)
.unwrap();
v.signing_create_android(&AndroidKey { id: "domi-test-android".into(), role: Role::Test, ..wide.clone() }, NOW)
.unwrap();
let mut remote = culina("r-1");
remote.via = Via::Remote;
let mut minisign = culina("r-1");
minisign.kind = SignKind::Minisign;
minisign.key = "domi-release".into();
minisign.digest = vec![7; 64];
for (req, why) in [
(remote, "the server runner"),
(apk("culina-android", "mnovak/Culina", "release", None), "no run"),
(apk("liber-android", "mnovak/Liber", "release", Some("r-1")), "a key with a wider scope"),
(apk("other-android", "mnovak/Rosea", "release", Some("r-1")), "not the repository's app key"),
(apk("domi-test-android", "mnovak/Liber", "release", Some("r-1")), "a test key"),
(minisign, "another kind"),
] {
assert!(!v.android_grant_fits(&req, NOW + 1), "{why}");
assert!(v.signing_sign(&req, Approval::Standing, NOW + 1).is_err(), "{why}: never signed without a card");
assert_ne!(v.signing_audit().last().unwrap().outcome, Outcome::Standing, "{why}");
}
assert_eq!(v.android_grant().unwrap().uses, 0);
}
#[test]
fn an_explicit_list_covers_only_its_repositories_and_bad_patterns_are_refused() {
let mut v = granted(&["mnovak/Culina"]);
v.signing_create_android(
&AndroidKey {
id: "liber-android".into(),
name: "Liber Android".into(),
cn: "Liber".into(),
o: "Marek Novak".into(),
c: "CZ".into(),
role: Role::Release,
pipelines: s(&["release"]),
repos: s(&["mnovak/Liber"]),
},
NOW,
)
.unwrap();
let liber = apk("liber-android", "mnovak/Liber", "release", Some("r-1"));
assert!(!v.android_grant_fits(&liber, NOW + 1), "not in the list");
// Editing the list keeps the counts and covers the new repository; a key made by hand in that shape is covered.
v.android_grant_set(&s(&["mnovak/Culina", "mnovak/Liber", "mnovak/Liber"]), "Marek Novak", "CZ", NOW + 2).unwrap();
assert_eq!(v.android_grant().unwrap().repos, s(&["mnovak/Culina", "mnovak/Liber"]));
assert!(v.android_grant_fits(&liber, NOW + 3));
for bad in [&[][..], &["mnovak"], &["*/*"], &["*"], &["mnovak/*/x"], &["mn ovak/*"], &["mnovak/Cu*"]] {
assert!(v.android_grant_set(&s(bad), "Marek Novak", "CZ", NOW + 4).is_err(), "{bad:?}");
}
let many: Vec<String> = (0..65).map(|i| format!("mnovak/app{i}")).collect();
assert!(v.android_grant_set(&many, "Marek Novak", "CZ", NOW + 4).is_err(), "at most 64");
assert!(v.android_grant_set(&s(&["mnovak/*"]), "Marek Novak", "Czech", NOW + 4).is_err(), "a two-letter country");
assert!(v.android_grant_set(&s(&["mnovak/*"]), "", "CZ", NOW + 4).is_err(), "an organisation");
assert_eq!(
v.android_grant().unwrap().repos,
s(&["mnovak/Culina", "mnovak/Liber"]),
"a refused edit changes nothing"
);
}
#[test]
fn sign_only_with_a_card_pauses_the_grant_and_revoking_ends_it() {
let mut v = granted(&["mnovak/*"]);
v.android_grant_make_key("mnovak/Culina", "release", Via::Local, NOW).unwrap();
v.security_tick(Item::CardSigning, NOW + 1);
assert!(!v.android_grant_fits(&culina("r-1"), NOW + 2));
assert!(matches!(v.signing_sign(&culina("r-1"), Approval::Standing, NOW + 2), Err(Refusal::NeedsApproval(_))));
assert!(v.android_grant_set(&s(&["mnovak/*"]), "Marek Novak", "CZ", NOW + 2).is_err(), "no grant while ticked");
assert!(v.android_grant().is_some(), "kept, paused");
v.security_untick(Item::CardSigning, Auth::Hello, NOW + 3);
assert!(v.android_grant_fits(&culina("r-1"), NOW + 4));
assert!(v.android_grant_revoke(NOW + 5));
assert!(!v.android_grant_revoke(NOW + 6), "once");
assert!(!v.android_grant_fits(&culina("r-2"), NOW + 7));
assert!(matches!(v.signing_sign(&culina("r-2"), Approval::Standing, NOW + 7), Err(Refusal::NeedsApproval(_))));
// Mark still signs it on a card, and the key stays.
assert!(v.signing_sign(&culina("r-2"), Approval::Mark, NOW + 8).is_ok());
let revoked = notes(&v, Action::StandingRevoked);
assert_eq!(revoked.len(), 1);
assert!(revoked[0].contains("Android releases"), "{revoked:?}");
}
#[test]
fn a_standing_rule_for_the_same_request_is_used_first() {
let mut v = granted(&["mnovak/*"]);
v.android_grant_make_key("mnovak/Culina", "release", Via::Local, NOW).unwrap();
v.signing_sign(&culina("r-1"), Approval::Mark, NOW + 1).unwrap();
v.standing_grant(&culina("r-2"), NOW + 2).unwrap();
v.signing_sign(&culina("r-2"), Approval::Standing, NOW + 2).unwrap();
assert_eq!(v.standing_rules()[0].uses, 1);
assert_eq!(v.android_grant().unwrap().uses, 0);
}
#[test]
fn the_grant_and_its_counts_survive_a_reopen() {
let mut v = granted(&["mnovak/*", "domi/*"]);
v.android_grant_make_key("mnovak/Culina", "release", Via::Local, NOW).unwrap();
v.signing_sign(&culina("r-1"), Approval::Standing, NOW + 1).unwrap();
let mut back = Vault::open(&v.to_bytes().unwrap(), &SecretString::from("pw")).unwrap();
assert_eq!(back.android_grant(), v.android_grant());
assert!(back.signing_sign(&culina("r-2"), Approval::Standing, NOW + 2).is_ok());
assert_eq!(back.android_grant().unwrap().uses, 2);
assert!(back.android_grant_revoke(NOW + 3));
let again = Vault::open(&back.to_bytes().unwrap(), &SecretString::from("pw")).unwrap();
assert_eq!(again.android_grant(), None);
}
+67 -36
View File
@@ -1,12 +1,13 @@
# Custos in the browser
Version 1 of the browser extension: Chromium (Edge and Chrome) on Windows, logins only. Passkeys come later.
Version 2 of the browser extension (core 0.20.0): Firefox, Edge and Chrome on Windows, from one source; logins
and their 2FA codes, and saving a new login. Passkeys come later.
The extension, its native host and the rule that decides which login belongs on which page are all in this
public repository, so anyone can read what the browser side does. The desktop app (the private `Custos`
repo) holds the vault and answers the host; its side is `docs/13_browser.md` there.
```
page ─(content script)─► service worker ─(native messaging)─► custos-native.exe ─(\\.\pipe\custos-domi)─► custos.exe
page ─(content script)─► background ─(native messaging)─► custos-native.exe ─(\\.\pipe\custos-domi)─► custos.exe
extension/content.js extension/background.js crates/custos-native the desktop app
```
@@ -14,11 +15,12 @@ page ─(content script)─► service worker ─(native messaging)─► custos
| Piece | What it does | What it never does |
|:--|:--|:--|
| `extension/content.js` | Finds login fields (password, username next to one, one-time code); on focus shows a small Custos button in a **closed** shadow root; on click asks for the logins of *its own frame*, and fills the one the person picks. | Fill without a click; read anything from Custos before the list is opened; trust what the page says about its own address. |
| `extension/popup.*` | The toolbar popup: the logins for the active tab; a click asks the top frame's content script to fill. | Receive a password: the content script asks for the secrets itself. |
| `extension/background.js` | Owns the one connection to the native host; turns each request into `browser_status`, `browser_match` or `browser_fill`, with the origin taken from **`sender.url`** (the frame's real URL, as the browser reports it). | Accept messages from pages or other extensions (`sender.id` must be its own). |
| `crates/custos-native` | The native messaging host. Reads frames from stdin, **rebuilds** each request from its known fields (op, origin ≤ 2 KiB, id ≤ 128 bytes, seq), forwards it to the Custos pipe and returns the answer. | Forward any other Domi op (`get`, `list`, `sign`, …); talk to a pipe served by anything but `custos.exe`; keep a secret after the answer is written (frames and parsed answers are zeroized). |
| `crates/custos-browser` | `Origin::parse`, `login_matches`, `best_match` (which login fits which page) and the native messaging framing. The desktop uses the same crate, so both sides apply one rule. | Fuzzy matching of any kind. |
| `extension/content.js` | Finds login fields (password, username next to one, one-time code); on focus shows a small Custos button in a **closed** shadow root; on a (trusted) click asks for the logins of *its own frame*, and fills the one the person picks: username and password, or only the 2FA code on a page that asks only for that. When a form is sent with a password the person typed (not one Custos filled), offers to save it. | Fill without a click; read anything from Custos before the list is opened; put a secret anywhere but its field; trust what the page says about its own address. |
| `extension/popup.*` | The toolbar popup: the logins for the active tab, a 2FA code on request, a login offered for saving, and this connection's match code. A click asks the top frame's content script to fill. | Receive a password: the content script asks for the secrets itself. |
| `extension/background.js` | Owns the one connection to the native host; turns each request into a `browser_*` op, with the frame's origin from **`sender.url`** and its page's from **`sender.tab.url`** (as the browser reports them). Holds a login offered for saving in memory, for its tab, at most 3 minutes. | Accept messages from pages or other extensions (`sender.id` must be its own); ask for a frame whose real origin is not its URL's (`sender.origin`, e.g. a sandboxed frame); write anything to `storage`. |
| `crates/custos-native` | The native messaging host. Checks who started it (`custos_browser::caller`); reads frames from stdin, **rebuilds** each request from its known fields, adds its connection's `session`, forwards it to the Custos pipe and returns the answer. | Answer an extension that is not Custos's (`not_allowed`, nothing reaches Custos); forward any other Domi op (`get`, `list`, `sign`, …); talk to a pipe served by anything but `custos.exe`; keep a secret after the answer is written (frames and parsed messages are zeroized). |
| `crates/custos-browser` | `Origin::parse`, `login_matches`, `best_match`, `fill_allowed` (which login fits which frame of which page), `caller`, and the native messaging framing. The desktop uses the same crate, so both sides apply one rule. | Fuzzy matching of any kind. |
| `tools/extension.mjs` | Builds `target/extension/firefox/` and `…/chromium/` from the one source with each browser's manifest (`extension/manifest.<browser>.json`) and the workspace version; `--zip` writes reproducible packages for AMO and the stores. | Differ per browser: the scripts are the same files. |
## Which login goes where (`custos-browser`)
@@ -31,69 +33,98 @@ fields (an item may have several) match a page when:
3. the ports are equal (the stored URL's port, or the scheme's default when it names none);
4. the page's host is the login's host (**exact**; `www.` counts as the host) or a subdomain of it
(**subdomain**: `accounts.github.com` for `github.com`). A login for a subdomain never goes to its parent
or to a sibling. A login for an IP address or a bare name (`cz`) matches only that exact host.
or to a sibling. A login for an IP address, a bare name (`cz`) or a **public suffix** (`co.uk`, `github.io`,
`herokuapp.com`: Mozilla's Public Suffix List, the `psl` crate) matches only that exact host, because the
subdomains of a public suffix belong to different people;
5. **in a frame** (`fill_allowed`): the frame matches, and when the frame is not the top page, the top page
matches too. `evil.net` framing `github.com/login` gets nothing, and neither does an ad frame on
`github.com`.
URLs with userinfo (`https://bank.cz@evil.net`) are refused outright. Look-alikes (`github.com.evil.net`,
URLs with userinfo (`https://bank.cz@evil.net`), a port that is not only digits (`:+443`) or a host that is not
ASCII (the browser reports punycode, and that is what is compared) are refused outright. Look-alikes (`github.com.evil.net`,
`githuh.com`, punycode twins) never match, because nothing is compared but labels. Exact matches are offered
before subdomain matches, then by title; at most 50 logins per page.
## The messages
Native messaging frames: a 4-byte little-endian length, then UTF-8 JSON. The host accepts at most 64 KiB per
message (the desktop pipe's limit). Every request may carry `seq` (a number); the answer carries it back.
Native messaging frames: a 4-byte little-endian length, then UTF-8 JSON (the same in Firefox and Chromium). The
host accepts at most 64 KiB per message (the desktop pipe's limit). Every request may carry `seq` (a number); the
answer carries it back. The host adds `app`, `browser` (`firefox` from its arguments; `edge`, `chrome` or
`chromium` as the extension says, a label) and `session` (64 hex digits, random per connection) to each.
| Extension → host | Host → Custos | Answer |
|:--|:--|:--|
| `{"op":"browser_status"}` | `{"op":"browser_status","app":"Custos for your browser"}` | `{"ok":true}` |
| `{"op":"browser_match","origin":"https://github.com"}` | + `origin` | `{"ok":true,"logins":[{"id","title","username"}]}`: never a password |
| `{"op":"browser_fill","id":"…","origin":"…"}` | + `origin`, `id` | `{"ok":true,"username","password","totp"}` only if that login matches `origin`, else `"error":"no_match"` |
| Extension → host | Answer |
|:--|:--|
| `{"op":"browser_status"}` | `{"ok":true,"code":"123456"}`: the session's match code |
| `{"op":"browser_match","origin","top"}` | `{"ok":true,"logins":[{"id","title","username","totp"}]}` (`totp`: it has a 2FA code); never a secret |
| `{"op":"browser_fill","id","origin","top"}` | `{"ok":true,"username","password","totp"}` only if that login may go into that frame of that page, else `no_match` |
| `{"op":"browser_totp","id","origin","top"}` | `{"ok":true,"totp","remaining"}` (seconds left) under the same rule; `no_totp` without one |
| `{"op":"browser_save","origin","top","username","password"[,"title"]}` | after Custos's card: `{"ok":true,"saved":"new"/"updated"/"unchanged"}`, or `refused` |
Errors the extension turns into a sentence: `not_connected` (no host registered), `not_running`,
`not_custos` (the pipe's server is not `custos.exe`: nothing was sent), `locked`, `denied`, `not_found`,
`no_match`, `no_answer`, `bad_request`.
Limits: `origin`, `top` ≤ 2 KiB, `id` ≤ 128 bytes, `username` ≤ 1 KiB, `password` 1 byte to 4 KiB, `title`
≤ 200 bytes. Errors the extension turns into a sentence: `not_connected` (no host registered), `not_allowed`
(not the Custos extension), `not_running`, `not_custos` (the pipe's server is not `custos.exe`: nothing was sent),
`locked`, `denied`, `refused`, `not_found`, `no_match`, `no_totp`, `no_answer`, `bad_request`.
## What Custos checks (the desktop's side, summarised)
- The host is a Domi client like any other: Custos identifies it by its executable and asks the person once
whether it may use **`web-logins/`**. That grant is the browser's only; no `domi://` ref may use the
`web-logins` namespace and the browser ops reach nothing else.
- Custos parses the origin again with `custos-browser` and checks the login against it on **every**
`browser_fill`, whatever the extension asked for before.
- Custos parses both origins again with `custos-browser` and checks the login with `fill_allowed` on **every**
`browser_fill` and `browser_totp`, whatever the extension asked for before.
- The grant card shows the session's match code, the one the popup shows. Every fill, code and save goes in the
vault's audit with that code.
- `browser_save` always shows a card (*Save* / *Don't save*): a new *Web login* for the origin, or, when a login
of that site has the same username, its new password. An identical login is `unchanged`, without a card.
- Only items of type *Web login* are offered. A locked Custos waits for the unlock (up to a minute), then
answers `locked`.
## Registration and the extension id
## Registration and the extension ids
The extension's `manifest.json` carries a public `key`, which fixes its id to
**`jchkapmceepdnlhagfppeckggaecdcmn`** however it is loaded (unpacked or packed). The desktop's *Connect*
writes the host manifest with `"allowed_origins": ["chrome-extension://jchkapmceepdnlhagfppeckggaecdcmn/"]`
and registers it under `HKCU\Software\Microsoft\Edge\NativeMessagingHosts\cz.marek_novak.custos` and
`HKCU\Software\Google\Chrome\NativeMessagingHosts\cz.marek_novak.custos`, so only this extension can start
the host. The private key that matches the public key is not in this repository; it is only needed to pack a
`.crx` with the same id.
| Browser | Extension id | Host manifest | Registry (HKCU, per user) |
|:--|:--|:--|:--|
| Firefox | `custos@marek-novak.cz` (`browser_specific_settings.gecko.id`) | `"allowed_extensions": ["custos@marek-novak.cz"]` | `Software\Mozilla\NativeMessagingHosts\cz.marek_novak.custos` |
| Edge | `jchkapmceepdnlhagfppeckggaecdcmn` (the `key` in `manifest.chromium.json`) | `"allowed_origins": ["chrome-extension://jchkapmceepdnlhagfppeckggaecdcmn/"]` | `Software\Microsoft\Edge\NativeMessagingHosts\cz.marek_novak.custos` |
| Chrome | the same | the same | `Software\Google\Chrome\NativeMessagingHosts\cz.marek_novak.custos` |
The desktop writes both host manifests and registers them. The Chromium `key` fixes the id however the extension
is loaded; the private key that matches it is not in this repository (it is held in Custos) and is needed only to
pack a `.crx`, or for the first upload to the Chrome Web Store, to keep the id. Release Firefox installs only
add-ons signed by Mozilla: the Firefox zip is signed through AMO as an *unlisted* (self-distributed) add-on.
## Threat model, briefly
- A malicious **page** cannot ask for a login: content scripts run in an isolated world, the button and list
are in a closed shadow root, the origin comes from the browser, and filling needs a click in Custos's own UI.
A page *can* read what was filled into its own fields: that is what filling is.
- A malicious **frame** on a good site is a different origin: it gets only its own origin's logins.
- Another **extension** cannot message this one (`sender.id`), and cannot start the host (`allowed_origins`).
- A malicious **frame** on a good site is a different origin: it gets only its own origin's logins, and those
only if the page around it matches them too. A good site framed by a malicious page gets nothing.
- Another **extension** cannot message this one (`sender.id`), cannot start the host (`allowed_origins`,
`allowed_extensions`), and if a stray manifest let it, the host answers it only `not_allowed` (`caller`).
- A page can make the extension *offer* to save a login for **its own** origin, with values of its choosing; it
is saved only on Custos's card, which names the site.
- A program that **impersonates Custos** by creating the pipe first gets nothing: the host checks the pipe
server's image path ends in `\custos.exe` before writing the request. (A process of the same user that can
replace `custos.exe` is out of scope, as everywhere in Custos: docs/THREAT_MODEL.md.)
- The extension holds no secret at rest and no state beyond the open native port.
- The extension holds no secret at rest. Its only state is the open native port and, for a login offered for
saving, that login in the background's memory for at most 3 minutes (JavaScript strings cannot be wiped;
they are dropped).
## Not yet
Passkeys (WebAuthn through the extension), Firefox, saving new logins from the browser, filling cards.
Passkeys (WebAuthn through the extension), filling cards, other operating systems.
## Tests
```
cargo test -p custos-browser -p custos-native
node tools/extension-test.mjs
```
`custos-browser` covers origin parsing, look-alikes, ports and schemes, bare names and IPs, best-of-several and
the frames; `custos-native` that only the three ops pass, rebuilt from known fields. The desktop repo has the
pipe tests and an end-to-end run in Edge.
`custos-browser` covers origin parsing, look-alikes (punycode twins, extra labels, userinfo, encoded dots,
backslashes, odd ports), public suffixes, frames and their pages, ports and schemes, bare names and IPs,
best-of-several, the callers and the frames. `custos-native` covers that only the five ops pass, rebuilt from
known fields, and that another extension gets `not_allowed` without reaching Custos. `tools/extension-test.mjs`
runs the background script against a fake browser: origins from the browser and never from the message, frames,
sandboxed and blank frames, other extensions, a locked Custos, and a login offered for saving that never comes back
out. The desktop repo has the pipe tests and the end-to-end runs in each browser.
+5 -2
View File
@@ -149,7 +149,10 @@ of kind `android` and an audit entry of kind `apk` (docs/SIGNING.md); a vault th
core before 0.14.0. Core 0.16.0 adds the `signing` audit outcome `standing` and the `security` actions
`standing-granted` and `standing-revoked` (docs/SIGNING.md, "Standing approvals"): a vault in which a standing
approval was ever granted does not open in a core before 0.16.0. The rules themselves (`signing.standing`) are a
member older cores ignore and drop.
member older cores ignore and drop. Core 0.19.0 adds the member `signing.android` (the Android grant, docs/SIGNING.md "The Android
grant"), which older cores ignore and drop (the grant is lost, never widened). It adds no closed-list value:
a key the grant makes is `standing-granted` in the security audit (core 0.19.1), so a vault with the grant still
opens in every core since 0.16.0, as the phone app and the web vault may be.
### The provision audit (core 0.11.0)
@@ -213,7 +216,7 @@ an outcome; a code the server then refuses (its exit 10) is not seen by Custos,
| `finished` | optional: when that window ended, by *Finish setup*, or `until` once its expiry was noticed |
| `ticked` | the checklist items that are ticked: `totp-on-phone`, `hello-approvals`, `narrow-scope`, `rotate-setup`, `no-ssh`, `phone-approves`, and (core 0.13.0) `no-auto-connect`, `no-unattended`, `card-signing` |
| `keptScope` | optional: the server scope prefixes *Narrow the server scope* replaced (`ask`, `offer`: at most 64 each, 1–200 characters, no control characters), kept for its undo |
| `audit` | `{at, action, item?, auth?, detail?}`; `action` is `setup-started`, `setup-finished`, `setup-expired`, `ticked`, `unticked`, `ssh-connected`, `totp-moved`, or (core 0.13.0) `auto-connected`, `unattended-stored`, `setup-item-removed`, `unattended-signed`, `taken-over`, or (core 0.16.0) `standing-granted`, `standing-revoked`, or (core 0.17.0) `recovery-created`, `recovery-removed`, `recovered` (docs/FACTORS.md, "The recovery key"; their `detail` is the key's id); `item` a checklist item (with `ticked`, `unticked`); `auth` is `hello` or `password` (with `unticked`); `detail` (core 0.13.0, the four notes; core 0.16.0, the two standing actions) names what happened, never a value: 1–500 characters, no control characters |
| `audit` | `{at, action, item?, auth?, detail?}`; `action` is `setup-started`, `setup-finished`, `setup-expired`, `ticked`, `unticked`, `ssh-connected`, `totp-moved`, or (core 0.13.0) `auto-connected`, `unattended-stored`, `setup-item-removed`, `unattended-signed`, `taken-over`, or (core 0.16.0) `standing-granted`, `standing-revoked` (also for the Android grant and the keys it makes), or (core 0.17.0) `recovery-created`, `recovery-removed`, `recovered` (docs/FACTORS.md, "The recovery key"; their `detail` is the key's id); `item` a checklist item (with `ticked`, `unticked`); `auth` is `hello` or `password` (with `unticked`); `detail` (core 0.13.0, the four notes; core 0.16.0, the two standing actions) names what happened, never a value: 1–500 characters, no control characters |
The **level** is computed, never stored:
+60 -1
View File
@@ -1,4 +1,4 @@
# Signing keys (core 0.9.0; deploy approvals 0.12.0; Android APKs 0.14.0; standing approvals 0.16.0; teams 0.18.0)
# Signing keys (core 0.9.0; deploy approvals 0.12.0; Android APKs 0.14.0; standing approvals 0.16.0; teams 0.18.0; the Android grant 0.19.0)
Custos signs releases for Fabrica Domi · Artifex without a private key ever leaving the vault. A build asks for a
signature over a **digest**; Custos checks who may ask, Mark approves with a match code, and the vault signs and
@@ -249,6 +249,59 @@ Never covered by a rule, by construction: another repository, key, kind, pipelin
key's scope; a request without a run; a key's first signature; a deploy to a target the rule was not granted for;
a release signature the server runner asks for; creating a key.
## The Android grant (core 0.19.0)
A standing approval is one repository's one key, and never a key's first signature. Mark has a dozen Domi apps, each
with its own Android key (`<app>-android`), each new: that is a card to make the key's first signature and another to
store the rule, per app. **The Android grant** is one answer for all of them: "sign my apps' release APKs, and make
each app's key when its first release asks". One grant per vault, in `signing.android`:
```json
"android": { "repos": ["mnovak/*"], "o": "Marek Novak", "c": "CZ", "granted": 1794000000000,
"lastUsed": 1794100000000, "uses": 3, "made": ["culina-android"] }
```
- `repos`: 1 to 64 patterns, each `owner/name` or `owner/*` (every repository of that owner, never another
owner's); owner and name are 1 to 64 of `A-Z a-z 0-9 . _ -`.
- `o`, `c`: the certificate subject's organisation and country for the keys it makes.
- `uses`, `lastUsed`: as on a standing approval. `made`: the ids of the keys it made, oldest first (at most 256).
**An app's key** is named by its repository: `android_key_id("mnovak/Culina")` is `culina-android` (the name in
lower case, `.` and `_` as `-`). The grant only ever deals in that key, and only when its scope is exactly that
repository and the pipeline `release`, with the role `release`: a key with a wider scope (or `*`) is never the
grant's, and a key the grant did not make but that has this shape (`postea-android`) is covered too.
**A request fits the grant** (`android_grant_fits`) when all of these hold:
- `signing_check` passes (scope as always: the grant never widens a key's scope);
- the kind is `apk` and `via` is `local`: an APK the server runner asks for never fits;
- the request names a run;
- the pipeline is `release` and the repository matches one of the patterns;
- the key is that repository's app key, as above;
- `card-signing` (*Sign only with a card*) is not ticked.
A key's first signature fits too: that is the point of the grant. `signing_sign(req, Approval::Standing, now)` signs
a request that fits a standing approval or the grant (a standing approval first), records the outcome `standing`,
and counts the use on whichever fitted.
**Making a key** (`android_grant_make_key(repo, pipeline, via, now)`): the grant covers the repository, the
pipeline is `release`, `via` is `local`, `card-signing` is not ticked, and the vault has no key under that id. It
makes the RSA-4096 key with the certificate `CN=<Name>` (the repository's name, first letter upper case), `O` and `C`
from the grant, named `<Name> Android`, scoped to exactly that repository and `release`, adds the id to `made`, and
writes `standing-granted` to the security audit (`Android grant made <id> for <repo> pipeline release`). Core 0.19.0
wrote a new action, `android-key-made`, which older cores refuse; 0.19.1 keeps to the values every core since 0.16.0
reads, because the phone app and the web vault open the same vault. It is a key like any other: not exportable,
removed only as any key is.
**Granting** (`android_grant_set(repos, o, c, now)`) stores or replaces the grant (the counts and `made` stay) and
writes `standing-granted` with `Android releases: <patterns> pipeline release, keys made on first use`. It is
refused while `card-signing` is ticked. `android_grant_revoke` removes it (`standing-revoked`). Neither asks
anyone: the app calls them only from Mark's own click.
Never covered by the grant: another kind, the server runner, a pipeline other than `release`, a repository no pattern
matches, a key that is not the repository's app key, a request without a run, anything while *Sign only with a card*
is ticked.
## The audit log
`audit` is append-only: there is no function that edits or removes an entry. Every request a key is named in gets
@@ -302,6 +355,12 @@ Vault::standing_grant(&request, now) -> StandingRule //
Vault::standing_rule_for(&request, now) -> Option<StandingRule>
Vault::standing_rules() -> [StandingRule]
Vault::standing_revoke(id, now) -> bool
android_key_id(repo) -> Option<String> (core 0.19.0)
Vault::android_grant() -> Option<AndroidGrant>
Vault::android_grant_set(repos, o, c, now) -> Result<AndroidGrant, Error>
Vault::android_grant_revoke(now) -> bool
Vault::android_grant_fits(req, now) -> bool
Vault::android_grant_make_key(repo, pipeline, via, now) -> Result<String, Error>
```
No function returns a `secret`. The views and the audit entries print and serialise without one; there is a test.
+161 -41
View File
@@ -1,27 +1,41 @@
// 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.
// Custos's background script (docs/BROWSER.md): an event page in Firefox, a service worker in Edge and Chrome.
// It owns the connection to the native host and answers the content scripts and the popup. The origins it sends
// to Custos are always the browser's (`sender.url` of the frame, `sender.tab.url` of its page), never what a page
// says about itself; Custos decides which logins belong there.
//
// It keeps no secret at rest: nothing goes to `storage`, and a login offered for saving waits in memory only, for
// its tab, until it is saved, dismissed or three minutes old.
const api = globalThis.browser ?? globalThis.chrome;
const HOST = 'cz.marek_novak.custos';
const SAVE_KEPT_MS = 3 * 60_000;
/** The native host, connected on first use; Edge and Chrome keep the worker alive while it is open. */
/** Which browser this is, for Custos's card (a label only: the host knows Firefox from its arguments). */
function browserHint() {
const brands = (globalThis.navigator?.userAgentData?.brands ?? []).map((b) => b.brand);
if (brands.includes('Microsoft Edge')) return 'edge';
if (brands.includes('Google Chrome')) return 'chrome';
return null;
}
/** The native host, connected on first use; the browser keeps the background 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 = api.runtime.connectNative(HOST);
port.onMessage.addListener((msg) => {
const w = waiting.get(msg.seq);
const w = waiting.get(msg?.seq);
if (!w) return;
waiting.delete(msg.seq);
w(msg);
});
port.onDisconnect.addListener(() => {
port.onDisconnect.addListener((p) => {
// 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';
const why = `${p?.error?.message ?? api.runtime.lastError?.message ?? ''}`;
const error = /not found|forbidden|no such native application|not allowed/i.test(why) ? 'not_connected' : 'not_running';
for (const w of waiting.values()) w({ ok: false, error });
waiting.clear();
port = null;
@@ -34,19 +48,19 @@ function ask(request) {
const n = ++seq;
waiting.set(n, resolve);
try {
connect().postMessage({ ...request, seq: n });
connect().postMessage({ ...request, browser: browserHint(), 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.
// Custos may wait up to a minute for an unlock or an answer on its card.
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. */
/** `scheme://host[:port]` of a page or frame URL; null for anything Custos never fills. */
function originOf(url) {
try {
const u = new URL(url);
@@ -57,35 +71,141 @@ function originOf(url) {
}
}
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' });
/**
* The frame's origin and its page's, from what the browser says about the sender. Null when either is unknown,
* or when the frame's real origin is not its URL's (a sandboxed frame has an opaque origin: it gets nothing).
*/
function placeOf(sender) {
const origin = originOf(sender.url);
if (!origin) return null;
if (typeof sender.origin === 'string' && sender.origin !== origin) return null;
const top = sender.frameId === 0 ? origin : originOf(sender.tab?.url);
if (!top) return null;
return { origin, top };
}
// ---- logins offered for saving: in memory, per tab ----
const offers = new Map();
function offerFor(tabId) {
const o = offers.get(tabId);
if (o && Date.now() - o.at > SAVE_KEPT_MS) offers.delete(tabId);
return offers.get(tabId) ?? null;
}
function showBadge(tabId) {
const on = !!offerFor(tabId);
Promise.resolve(api.action.setBadgeText({ tabId, text: on ? '1' : '' })).catch(() => {});
if (on) Promise.resolve(api.action.setBadgeBackgroundColor({ tabId, color: '#c9a96e' })).catch(() => {});
}
api.tabs.onRemoved.addListener((tabId) => offers.delete(tabId));
/** What the popup and the page may see of an offer: never its password. */
const offerView = (o) => (o ? { host: new URL(o.origin).host, username: o.username } : null);
async function save(tabId) {
const o = offerFor(tabId);
if (!o) return { ok: false, error: 'gone' };
offers.delete(tabId);
showBadge(tabId);
const r = await ask({ op: 'browser_save', origin: o.origin, top: o.top, username: o.username, password: o.password, title: o.title });
o.password = '';
return r;
}
async function activeTab() {
const [tab] = await api.tabs.query({ active: true, currentWindow: true });
return tab ?? null;
}
// ---- messages from the content scripts and the popup ----
async function handle(msg, sender) {
switch (msg?.kind) {
case 'status':
return ask({ op: 'browser_status' });
case 'match': {
// From a content script: the logins for the frame it runs in, on its page.
const at = placeOf(sender);
if (!at) return { ok: false, error: 'no_match' };
return { ...(await ask({ op: 'browser_match', ...at })), origin: at.origin };
}
})();
case 'fill':
case 'totp': {
// The secrets go back to the frame that asked, and only if Custos agrees the login belongs there.
const at = placeOf(sender);
if (!at || typeof msg.id !== 'string') return { ok: false, error: 'no_match' };
return ask({ op: msg.kind === 'fill' ? 'browser_fill' : 'browser_totp', id: msg.id, ...at });
}
case 'offer-save': {
// A login form was sent with a password Custos did not fill: keep it for this tab until the person decides.
const at = placeOf(sender);
const tabId = sender.tab?.id;
if (!at || tabId == null || typeof msg.password !== 'string' || !msg.password || msg.password.length > 4096) {
return { ok: false, error: 'bad_request' };
}
const username = typeof msg.username === 'string' ? msg.username.slice(0, 1024) : '';
const title = new URL(at.origin).host;
offers.set(tabId, { ...at, username, password: msg.password, title, at: Date.now() });
showBadge(tabId);
// The open connection keeps a service worker (Edge, Chrome) alive, and the offer with it.
void ask({ op: 'browser_status' });
return { ok: true, offer: offerView(offers.get(tabId)) };
}
case 'pending-save': {
// The top page of the tab that sent the form, on the same site, asks whether to show the offer.
const at = placeOf(sender);
const o = sender.tab?.id != null ? offerFor(sender.tab.id) : null;
if (!at || !o || sender.frameId !== 0 || at.top !== o.top) return { ok: true, offer: null };
return { ok: true, offer: offerView(o) };
}
case 'save':
// From the page's own offer: its tab's offer only.
if (sender.tab?.id == null || sender.frameId !== 0) return { ok: false, error: 'bad_request' };
return save(sender.tab.id);
case 'dismiss-save':
if (sender.tab?.id != null) {
offers.delete(sender.tab.id);
showBadge(sender.tab.id);
}
return { ok: true };
case 'match-tab': {
// From the popup: the logins for the active tab's page, and any login offered for saving there.
const tab = await activeTab();
const origin = tab && originOf(tab.url);
const offer = tab ? offerView(offerFor(tab.id)) : null;
if (!origin) return { ok: false, error: 'no_match', tab: tab?.id ?? null, offer };
return { ...(await ask({ op: 'browser_match', origin, top: origin })), origin, tab: tab.id, offer };
}
case 'totp-tab': {
// From the popup: one login's 2FA code for the active tab's page.
const tab = await activeTab();
const origin = tab && originOf(tab.url);
if (!origin || typeof msg.id !== 'string') return { ok: false, error: 'no_match' };
return ask({ op: 'browser_totp', id: msg.id, origin, top: origin });
}
case 'save-tab': {
const tab = await activeTab();
return tab ? save(tab.id) : { ok: false, error: 'gone' };
}
case 'dismiss-tab': {
const tab = await activeTab();
if (tab) {
offers.delete(tab.id);
showBadge(tab.id);
}
return { ok: true };
}
default:
return { ok: false, error: 'bad_request' };
}
}
api.runtime.onMessage.addListener((msg, sender, reply) => {
// Only this extension's own pages and content scripts reach here; pages and other extensions cannot.
if (sender.id !== api.runtime.id) return false;
handle(msg, sender).then(reply, () => reply({ ok: false, error: 'bad_request' }));
return true;
});
+115 -26
View File
@@ -1,18 +1,25 @@
// 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.
// frame's site, and fills the one the person picks. Nothing is filled without a click. The button, the list and
// the save offer live in a closed shadow root, out of the page's reach; logins are asked for only when the list
// opens, and a secret goes only into the field it is for.
(() => {
const api = globalThis.browser ?? globalThis.chrome;
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.',
not_allowed: 'This copy of the extension is not the one Custos knows.',
locked: 'Custos is locked. Unlock it, then try again.',
denied: 'Custos did not allow this browser to use your logins.',
refused: 'Not saved.',
not_found: 'That login is no longer in Custos.',
no_match: 'That login does not belong to this site.',
no_totp: 'That login has no 2FA code in Custos.',
no_answer: 'Custos did not answer.',
gone: 'That offer has expired.',
};
const say = (code) => SENTENCES[code] ?? 'Custos could not do that.';
const send = (msg) => Promise.resolve(api.runtime.sendMessage(msg)).catch(() => ({ ok: false, error: 'not_running' }));
const visible = (el) => {
const r = el.getBoundingClientRect();
@@ -44,38 +51,51 @@
return { user, pass, otp };
}
// Fields Custos filled and the person has not typed in since: a form sent with them is not offered for saving.
const filledByCustos = new WeakSet();
document.addEventListener('input', (e) => e.isTrusted && filledByCustos.delete(e.target), true);
const setValue = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value').set;
function put(el, value) {
if (!el || typeof value !== 'string' || !value) return;
if (!el || !el.isConnected || 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 }));
filledByCustos.add(el);
}
/** Fills login `id` around `near`. Only what the page has fields for is asked for: a 2FA page gets the code only. */
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);
if (!f.pass && !f.user && f.otp) {
const r = await send({ kind: 'totp', id });
if (!r?.ok) return say(r?.error);
put(f.otp, r.totp);
return null;
}
const r = await send({ kind: 'fill', id });
if (!r?.ok) return say(r?.error);
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 ----
// ---- the button, the list and the save offer ----
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, .menu, .offer { 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;
.menu, .offer { 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); }
.offer { top: 12px; right: 12px; padding: 10px 12px; }
.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; }
@@ -83,6 +103,10 @@
.title { font-weight: 600; }
.user { color: #9aa3b1; font-size: 12px; }
.note { padding: 6px 8px; color: #c9d1dc; }
.row { display: flex; gap: 8px; justify-content: flex-end; margin-top: 8px; }
.row button { padding: 5px 12px; border: 1px solid #3a404b; border-radius: 7px; background: #1d2128; color: inherit;
font: inherit; cursor: pointer; }
.row button.primary { border-color: #c9a96e; }
[hidden] { display: none !important; }
</style>
<button class="chip" type="button" title="Fill from Custos" aria-label="Fill from Custos" hidden>
@@ -90,11 +114,16 @@
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>`;
<div class="menu" role="menu" aria-label="Custos logins" hidden></div>
<div class="offer" role="dialog" aria-label="Save in Custos" hidden></div>`;
const chip = root.querySelector('.chip');
const menu = root.querySelector('.menu');
const offerBox = root.querySelector('.offer');
let field = null;
const attach = () => host.isConnected || document.documentElement.append(host);
const el = (tag, props) => Object.assign(document.createElement(tag), props);
function place() {
if (!field || !field.isConnected) return hide();
const r = field.getBoundingClientRect();
@@ -111,48 +140,48 @@
}
function note(text) {
menu.replaceChildren(Object.assign(document.createElement('div'), { className: 'note', textContent: text }));
menu.replaceChildren(el('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' });
const r = await send({ 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' });
const b = el('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 || '—' }),
el('span', { className: 'title', textContent: l.title }),
el('span', { className: 'user', textContent: (l.username || '—') + (l.totp ? ' · 2FA' : '') }),
);
b.addEventListener('click', async () => {
b.addEventListener('click', async (e) => {
if (!e.isTrusted) return;
const why = await fill(l.id, target);
if (why) note(why);
else hide();
});
return b;
});
menu.replaceChildren(head, ...items);
menu.replaceChildren(el('div', { className: 'head', textContent: 'Custos' }), ...items);
items[0]?.focus();
}
chip.addEventListener('click', () => (menu.hidden ? void open() : (menu.hidden = true)));
chip.addEventListener('click', (e) => e.isTrusted && (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;
const t = e.target;
if (!(t instanceof HTMLInputElement) || !visible(t)) return;
if (t.type !== 'password' && !isOtp(t) && !(isText(t) && fieldsAround(t).pass) && !isUserName(t)) return;
attach();
field = t;
menu.hidden = true;
chip.hidden = false;
place();
@@ -164,9 +193,69 @@
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;
// ---- saving a login the person typed ----
function showOffer(offer) {
if (!offer || window.top !== window) return;
attach();
const yes = el('button', { type: 'button', className: 'primary', textContent: 'Save in Custos' });
const no = el('button', { type: 'button', textContent: 'Not now' });
yes.addEventListener('click', async (e) => {
if (!e.isTrusted) return;
offerBox.replaceChildren(el('div', { className: 'note', textContent: 'Answer in Custos…' }));
const r = await send({ kind: 'save' });
const done = r?.ok ? (r.saved === 'unchanged' ? 'Custos already has this login.' : 'Saved in Custos.') : say(r?.error);
offerBox.replaceChildren(el('div', { className: 'note', textContent: done }));
setTimeout(() => (offerBox.hidden = true), 2500);
});
no.addEventListener('click', (e) => {
if (!e.isTrusted) return;
void send({ kind: 'dismiss-save' });
offerBox.hidden = true;
});
offerBox.replaceChildren(
el('div', { className: 'head', textContent: 'Custos' }),
el('div', { className: 'note', textContent: `Save the login${offer.username ? ` of ${offer.username}` : ''} for ${offer.host}?` }),
Object.assign(el('div', { className: 'row' }), {}),
);
offerBox.lastChild.append(no, yes);
offerBox.hidden = false;
}
/** A form is being sent: if it has a password the person typed (not one Custos filled), offer to save it. */
function sent(form) {
const scope = form ? [...form.querySelectorAll('input')] : [...document.querySelectorAll('input')];
const pass = scope.find((i) => i.type === 'password' && visible(i) && i.value);
if (!pass || filledByCustos.has(pass)) return;
const user = usernameFor(pass);
// Read once, handed to the background in memory, and not kept here.
void send({ kind: 'offer-save', username: user?.value ?? '', password: pass.value }).then((r) => r?.ok && showOffer(r.offer));
}
document.addEventListener('submit', (e) => e.isTrusted && sent(e.target instanceof HTMLFormElement ? e.target : null), true);
// Pages that sign in by script never send a form: a click on their button, or Enter in the password, counts.
document.addEventListener(
'click',
(e) => {
if (!e.isTrusted) return;
const b = e.target instanceof Element ? e.target.closest('button, input[type=submit]') : null;
if (!b || b.form?.querySelector('input[type=password]') == null || (b.type && b.type !== 'submit')) return;
sent(b.form);
},
true,
);
document.addEventListener(
'keydown',
(e) => e.isTrusted && e.key === 'Enter' && e.target instanceof HTMLInputElement && e.target.type === 'password' && !e.target.form && sent(null),
true,
);
// After the sign-in page went away: the next page of the same site shows the offer.
if (window.top === window) void send({ kind: 'pending-save' }).then((r) => r?.ok && showOffer(r.offer));
// ---- the popup's choice, in the top frame: fill the page's login form, or only its 2FA field ----
api.runtime.onMessage.addListener((msg, sender, reply) => {
if (sender.id !== api.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;
});
@@ -2,14 +2,19 @@
"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.15.0",
"description": "Fills your logins from the Custos on this computer, only into the site they belong to, and offers to save new ones.",
"key": "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAs+NtlDNsfBr8q2WbrurbDDfX4rL2dTHsNZToKBKradRb5WZU3wjHAcBMsPlYCiqHF4c/KUyGQ33mpPb0aXA5l3w7n6JgMLHPQBbCw5v076ViF6NIE3a0LOoffDg9ZQmfIJcgjb9baX2qS8VaEFTsEzb/BgQ2Ewx/BPHwZaFeJkucBsIeRZnaPajdqViaNDQdq91VnxIoSGr21Sc+9ZxfZL288S6wATdlDYBUyUZZjVwggHfiwdDmQQMdnFtks2r38V25h+t3ruGCi2mArj8DO1so1oX/NulLNT+6VBP6r/ap228af3rNNcv7sPeriI90ORqzh4Lwni8Hq1lzKuXLrwIDAQAB",
"minimum_chrome_version": "116",
"permissions": [
"nativeMessaging",
"activeTab"
],
"host_permissions": [
"https://*/*",
"http://localhost/*",
"http://127.0.0.1/*",
"http://*.localhost/*"
],
"background": {
"service_worker": "background.js"
},
+54
View File
@@ -0,0 +1,54 @@
{
"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, and offers to save new ones.",
"browser_specific_settings": {
"gecko": {
"id": "custos@marek-novak.cz",
"strict_min_version": "140.0",
"data_collection_permissions": {
"required": [
"none"
]
}
}
},
"permissions": [
"nativeMessaging",
"activeTab"
],
"host_permissions": [
"https://*/*",
"http://localhost/*",
"http://127.0.0.1/*",
"http://*.localhost/*"
],
"background": {
"scripts": [
"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'"
}
}
+53
View File
@@ -69,9 +69,62 @@ main {
color: var(--muted);
font-size: 12px;
}
.logins li {
display: flex;
align-items: center;
gap: 6px;
}
.logins button.login {
flex: 1;
min-width: 0;
}
.logins button.code {
display: block;
width: auto;
flex: none;
padding: 4px 8px;
border: 1px solid var(--line);
color: var(--accent);
font-variant-numeric: tabular-nums;
letter-spacing: 0.08em;
}
.offer {
margin: 4px 4px 10px;
padding: 10px;
border: 1px solid #c9a96e;
border-radius: 8px;
}
.offer p {
margin: 0 0 8px;
}
.buttons {
display: flex;
justify-content: flex-end;
gap: 8px;
}
.buttons button {
padding: 5px 12px;
border: 1px solid var(--line);
border-radius: 7px;
background: var(--panel);
color: inherit;
font: inherit;
cursor: pointer;
}
.buttons button.primary {
border-color: #c9a96e;
}
footer {
display: grid;
gap: 2px;
padding: 8px 14px 12px;
border-top: 1px solid var(--line);
color: var(--muted);
font-size: 12px;
}
.code-line {
font-variant-numeric: tabular-nums;
}
[hidden] {
display: none !important;
}
+11 -1
View File
@@ -12,9 +12,19 @@
<span id="site" class="site"></span>
</header>
<main>
<section id="offer" class="offer" hidden>
<p id="offer-text"></p>
<div id="offer-buttons" class="buttons">
<button id="offer-dismiss" type="button">Not now</button>
<button id="offer-save" type="button" class="primary">Save in Custos</button>
</div>
</section>
<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>
<footer>
<span>Only logins saved for this site are offered here.</span>
<span id="code" class="code-line"></span>
</footer>
</body>
</html>
+72 -24
View File
@@ -1,50 +1,98 @@
// 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).
// (the top frame's content script asks for the secrets itself, so they go only where they belong). A login with
// 2FA can show its current code here. A login the page just sent can be saved in Custos. The footer shows this
// connection's match code, the one Custos shows on its card.
const api = globalThis.browser ?? globalThis.chrome;
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.',
not_allowed: 'This copy of the extension is not the one Custos knows.',
locked: 'Custos is locked. Unlock it, then try again.',
denied: 'Custos did not allow this browser to use your logins.',
refused: 'Not saved.',
not_found: 'That login is no longer in Custos.',
no_match: 'Custos fills only web pages (https, or this computer).',
no_totp: 'That login has no 2FA code in Custos.',
no_answer: 'Custos did not answer.',
gone: 'That offer has expired.',
};
const say = (code) => SENTENCES[code] ?? 'Custos could not do that.';
const note = document.getElementById('note');
const list = document.getElementById('logins');
const send = (msg) => Promise.resolve(api.runtime.sendMessage(msg)).catch(() => ({ ok: false, error: 'not_running' }));
const $ = (id) => document.getElementById(id);
const el = (tag, props) => Object.assign(document.createElement(tag), props);
const note = $('note');
const list = $('logins');
function tell(text) {
note.hidden = false;
note.textContent = text;
}
/** The 2FA code, shown until it changes; then the next one is asked for. */
async function showCode(id, out) {
const r = await send({ kind: 'totp-tab', id });
if (!r?.ok) {
out.textContent = say(r?.error);
return;
}
out.textContent = `${r.totp.slice(0, 3)} ${r.totp.slice(3)}`;
out.title = `Changes in ${r.remaining} s`;
setTimeout(() => out.isConnected && showCode(id, out), Math.max(1, r.remaining) * 1000);
}
function offer(o) {
if (!o) return;
const box = $('offer');
box.hidden = false;
$('offer-text').textContent = `Save the login${o.username ? ` of ${o.username}` : ''} for ${o.host}?`;
$('offer-save').addEventListener('click', async () => {
$('offer-text').textContent = 'Answer in Custos…';
const r = await send({ kind: 'save-tab' });
$('offer-text').textContent = r?.ok ? (r.saved === 'unchanged' ? 'Custos already has this login.' : 'Saved in Custos.') : say(r?.error);
$('offer-buttons').hidden = true;
});
$('offer-dismiss').addEventListener('click', async () => {
await send({ kind: 'dismiss-tab' });
box.hidden = true;
});
}
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;
}
const r = await send({ kind: 'match-tab' });
if (r?.origin) $('site').textContent = new URL(r.origin).host;
offer(r?.offer);
if (!r?.ok) return tell(say(r?.error));
if (!r.logins.length) return tell('Custos has no login for this site.');
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 || '—' }),
);
const li = el('li', {});
const b = el('button', { type: 'button', className: 'login' });
b.append(el('span', { className: 'title', textContent: l.title }), el('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);
const done = await Promise.resolve(api.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.';
}
else tell(done?.error ?? 'This page has no login form Custos can fill.');
});
li.append(b);
if (l.totp) {
const code = el('button', { type: 'button', className: 'code', textContent: '2FA code' });
code.addEventListener('click', () => {
code.disabled = true;
code.textContent = '…';
void showCode(l.id, code);
});
li.append(code);
}
list.append(li);
}
list.querySelector('button')?.focus();
}
async function connection() {
const r = await send({ kind: 'status' });
if (r?.ok && typeof r.code === 'string') $('code').textContent = `Connection ${r.code.slice(0, 3)} ${r.code.slice(3)}`;
}
void show();
void connection();
+141
View File
@@ -0,0 +1,141 @@
// Tests of the extension's background script against a fake browser (docs/BROWSER.md, "Tests"):
//
// node tools/extension-test.mjs
//
// The background is the extension's one gate to Custos: what it sends to the host must come from the browser's
// own view of the sender, never from the message; other extensions and odd frames get nothing; a login offered for
// saving never comes back out of it.
import assert from 'node:assert/strict';
import fs from 'node:fs';
import path from 'node:path';
import vm from 'node:vm';
const root = path.resolve(path.dirname(new URL(import.meta.url).pathname.replace(/^\/([A-Za-z]:)/, '$1')), '..');
const code = fs.readFileSync(path.join(root, 'extension', 'background.js'), 'utf8');
const ID = 'custos-test-id';
/** A fresh background with a fake API. `host(req)` answers the native host's requests. */
function background(host) {
const sent = [];
let listener = null;
const port = {
onMessage: { addListener: (f) => (port.deliver = f) },
onDisconnect: { addListener: () => {} },
postMessage: (m) => {
sent.push(m);
queueMicrotask(() => port.deliver({ ...host(m), seq: m.seq }));
},
};
const tabs = [{ id: 1, url: 'https://github.com/login', active: true }];
const api = {
runtime: { id: ID, connectNative: () => port, onMessage: { addListener: (f) => (listener = f) } },
tabs: { query: async () => tabs, onRemoved: { addListener: () => {} } },
action: { setBadgeText: async () => {}, setBadgeBackgroundColor: async () => {} },
};
vm.runInNewContext(code, { chrome: api, URL, setTimeout, Promise, queueMicrotask, console });
const call = (msg, sender) =>
new Promise((resolve) => {
// Answers are made in the background's realm: compared as plain JSON.
const kept = listener(msg, { id: ID, ...sender }, (v) => resolve(JSON.parse(JSON.stringify(v))));
if (kept !== true) resolve('ignored');
});
return { call, sent, tabs };
}
const tab = (url) => ({ id: 1, url });
const top = (url) => ({ url, frameId: 0, tab: tab(url) });
const frame = (url, pageUrl) => ({ url, frameId: 7, tab: tab(pageUrl) });
const tests = [];
const test = (name, f) => tests.push([name, f]);
test('another extension, or a page, is not answered at all', async () => {
const b = background(() => ({ ok: true, logins: [{ id: 'a' }] }));
for (const id of ['someone-else', undefined, '']) {
assert.equal(await b.call({ kind: 'match' }, { ...top('https://github.com/'), id }), 'ignored');
assert.equal(await b.call({ kind: 'fill', id: 'a' }, { ...top('https://github.com/'), id }), 'ignored');
}
assert.equal(b.sent.length, 0);
});
test('the origins come from the browser, never from the message', async () => {
const b = background(() => ({ ok: true, logins: [] }));
await b.call({ kind: 'match', origin: 'https://bank.cz', top: 'https://bank.cz' }, top('https://github.com/login?x=1'));
assert.deepEqual(b.sent.map((m) => [m.op, m.origin, m.top]), [['browser_match', 'https://github.com', 'https://github.com']]);
});
test('a frame asks with its own origin and its page’s', async () => {
const b = background(() => ({ ok: true, logins: [] }));
await b.call({ kind: 'match' }, frame('https://evil.net/ad', 'https://github.com/'));
await b.call({ kind: 'fill', id: 'x' }, frame('https://github.com/login', 'https://evil.net/'));
assert.deepEqual(
b.sent.map((m) => [m.op, m.origin, m.top]),
[
['browser_match', 'https://evil.net', 'https://github.com'],
['browser_fill', 'https://github.com', 'https://evil.net'],
],
);
});
test('sandboxed, blank, script and file frames get nothing, and nothing is asked', async () => {
const b = background(() => ({ ok: true, logins: [{ id: 'a' }] }));
const odd = [
{ ...frame('https://github.com/login', 'https://evil.net/'), origin: 'null' },
{ ...top('https://github.com/'), origin: 'https://evil.net' },
frame('about:blank', 'https://github.com/'),
top('javascript:alert(1)'),
top('file:///C:/x.html'),
top('data:text/html,<input type=password>'),
{ url: 'https://github.com/', frameId: 3 },
];
for (const s of odd) {
assert.deepEqual(await b.call({ kind: 'match' }, s), { ok: false, error: 'no_match' }, JSON.stringify(s));
assert.deepEqual(await b.call({ kind: 'fill', id: 'a' }, s), { ok: false, error: 'no_match' });
}
assert.equal(b.sent.length, 0);
});
test('a locked Custos answers nothing but locked', async () => {
const b = background(() => ({ ok: false, error: 'locked' }));
const r = await b.call({ kind: 'fill', id: 'a' }, top('https://github.com/'));
assert.deepEqual(r, { ok: false, error: 'locked', seq: 1 });
});
test('a login offered for saving never comes back out, and goes only to Custos', async () => {
const b = background((m) => (m.op === 'browser_save' ? { ok: true, saved: 'new' } : { ok: true, code: '123456' }));
const at = top('https://github.com/login');
const offered = await b.call({ kind: 'offer-save', username: 'mark', password: 'hunter2-secret' }, at);
assert.deepEqual(offered, { ok: true, offer: { host: 'github.com', username: 'mark' } });
// Another page of the site in the same tab sees the offer, without the password; a frame or another site does not.
assert.deepEqual(await b.call({ kind: 'pending-save' }, top('https://github.com/home')), { ok: true, offer: { host: 'github.com', username: 'mark' } });
assert.deepEqual(await b.call({ kind: 'pending-save' }, frame('https://github.com/x', 'https://github.com/')), { ok: true, offer: null });
assert.deepEqual(await b.call({ kind: 'pending-save' }, top('https://evil.net/')), { ok: true, offer: null });
const popup = await b.call({ kind: 'match-tab' }, { url: `chrome-extension://${ID}/popup.html` });
assert.ok(!JSON.stringify(popup).includes('hunter2'), 'the popup never sees the password');
// A frame cannot save; the top page can, once.
assert.deepEqual(await b.call({ kind: 'save' }, frame('https://github.com/x', 'https://github.com/')), { ok: false, error: 'bad_request' });
const saved = await b.call({ kind: 'save' }, top('https://github.com/home'));
assert.equal(saved.saved, 'new');
const req = b.sent.find((m) => m.op === 'browser_save');
assert.deepEqual([req.origin, req.top, req.username, req.password], ['https://github.com', 'https://github.com', 'mark', 'hunter2-secret']);
assert.deepEqual(await b.call({ kind: 'save' }, top('https://github.com/home')), { ok: false, error: 'gone' });
});
test('an offer needs a password, from a web page', async () => {
const b = background(() => ({ ok: true }));
assert.equal((await b.call({ kind: 'offer-save', username: 'm', password: '' }, top('https://github.com/'))).ok, false);
assert.equal((await b.call({ kind: 'offer-save', username: 'm', password: 'p' }, top('about:blank'))).ok, false);
assert.equal((await b.call({ kind: 'offer-save', username: 'm', password: 'x'.repeat(4097) }, top('https://a.cz/'))).ok, false);
});
let failed = 0;
for (const [name, f] of tests) {
try {
await f();
console.log(`ok ${name}`);
} catch (e) {
failed++;
console.log(`FAIL ${name}\n${e.stack}`);
}
}
console.log(`${tests.length - failed} passed, ${failed} failed`);
process.exit(failed ? 1 : 0);
+87
View File
@@ -0,0 +1,87 @@
// Builds the browser extension for each browser from the one source in extension/ (docs/BROWSER.md):
//
// node tools/extension.mjs [--out <dir>] [--zip]
//
// writes <out>/firefox/ and <out>/chromium/ (default out: target/extension), each with its manifest.json (the
// browser's manifest.<browser>.json, with the workspace version) and the shared scripts and popup. With --zip
// also custos-<browser>-<version>.zip next to them, reproducible (fixed order and times): the Firefox one is what
// AMO signs, the Chromium one what the Edge and Chrome stores take.
import fs from 'node:fs';
import path from 'node:path';
import zlib from 'node:zlib';
const root = path.resolve(path.dirname(new URL(import.meta.url).pathname.replace(/^\/([A-Za-z]:)/, '$1')), '..');
const arg = (name) => {
const i = process.argv.indexOf(name);
return i > 0 ? process.argv[i + 1] : null;
};
const out = path.resolve(arg('--out') ?? path.join(root, 'target', 'extension'));
const zip = process.argv.includes('--zip');
const cargo = fs.readFileSync(path.join(root, 'Cargo.toml'), 'utf8');
const version = /\[workspace\.package\][^[]*?version = "([^"]+)"/s.exec(cargo)?.[1];
if (!version) throw new Error('no workspace version in Cargo.toml');
const SHARED = ['background.js', 'content.js', 'popup.html', 'popup.js', 'popup.css'];
const BROWSERS = ['firefox', 'chromium'];
/** A zip of `files` ([name, bytes]), deflated, with a fixed time: the same input gives the same bytes. */
function zipOf(files) {
const parts = [];
const central = [];
let offset = 0;
const time = 0, date = (2026 - 1980) << 9 | 1 << 5 | 1; // 2026-01-01 00:00
for (const [name, data] of files) {
const n = Buffer.from(name, 'utf8');
const packed = zlib.deflateRawSync(data, { level: 9 });
const crc = zlib.crc32(data);
const local = Buffer.alloc(30);
local.writeUInt32LE(0x04034b50, 0);
local.writeUInt16LE(20, 4);
local.writeUInt16LE(0x0800, 6); // UTF-8 names
local.writeUInt16LE(8, 8);
local.writeUInt16LE(time, 10);
local.writeUInt16LE(date, 12);
local.writeUInt32LE(crc, 14);
local.writeUInt32LE(packed.length, 18);
local.writeUInt32LE(data.length, 22);
local.writeUInt16LE(n.length, 26);
parts.push(local, n, packed);
const c = Buffer.alloc(46);
c.writeUInt32LE(0x02014b50, 0);
c.writeUInt16LE(20, 4);
c.writeUInt16LE(20, 6);
c.writeUInt16LE(0x0800, 8);
c.writeUInt16LE(8, 10);
c.writeUInt16LE(time, 12);
c.writeUInt16LE(date, 14);
c.writeUInt32LE(crc, 16);
c.writeUInt32LE(packed.length, 20);
c.writeUInt32LE(data.length, 24);
c.writeUInt16LE(n.length, 28);
c.writeUInt32LE(offset, 42);
central.push(c, n);
offset += 30 + n.length + packed.length;
}
const dir = Buffer.concat(central);
const end = Buffer.alloc(22);
end.writeUInt32LE(0x06054b50, 0);
end.writeUInt16LE(files.length, 8);
end.writeUInt16LE(files.length, 10);
end.writeUInt32LE(dir.length, 12);
end.writeUInt32LE(offset, 16);
return Buffer.concat([...parts, dir, end]);
}
for (const browser of BROWSERS) {
const manifest = JSON.parse(fs.readFileSync(path.join(root, 'extension', `manifest.${browser}.json`), 'utf8'));
const withVersion = { manifest_version: manifest.manifest_version, name: manifest.name, version, ...manifest };
const files = [['manifest.json', Buffer.from(JSON.stringify(withVersion, null, 2) + '\n')]];
for (const f of SHARED) files.push([f, fs.readFileSync(path.join(root, 'extension', f))]);
const dir = path.join(out, browser);
fs.rmSync(dir, { recursive: true, force: true });
fs.mkdirSync(dir, { recursive: true });
for (const [name, data] of files) fs.writeFileSync(path.join(dir, name), data);
if (zip) fs.writeFileSync(path.join(out, `custos-${browser}-${version}.zip`), zipOf(files));
console.log(`${browser}: ${dir}${zip ? ` (+ custos-${browser}-${version}.zip)` : ''}`);
}