diff --git a/crates/dg/src/auth/keys.rs b/crates/dg/src/auth/keys.rs index e1d00dd21..0f3871983 100644 --- a/crates/dg/src/auth/keys.rs +++ b/crates/dg/src/auth/keys.rs @@ -24,7 +24,9 @@ pub enum KeysCommand { /// A limited key is what this computer then signs with (default: 0.25 DASH / 180 /// days, bound to dash-forge; `--replace ` disables the old one in the same update), or /// with --encryption the ENCRYPTION key private repositories need. Needs the master key once. - /// For a key to hand to CI use `dg auth export --new-key`. + /// For a key to hand to CI use `dg auth export --new-key`. With `--for-browser ` + /// the key is for a browser tab instead: dg prints it sealed to that tab, so the recovery + /// phrase never goes into a web page. Add(AddArgs), /// Disable a key on Platform. Needs the master key once. Disable { @@ -54,13 +56,27 @@ impl KeysCommand { #[derive(Debug, clap::Args)] pub struct AddArgs { /// Add an ENCRYPTION key (for private repositories) instead of a limited key. - #[arg(long, conflicts_with_all = ["budget", "expires", "replace"])] + #[arg(long, conflicts_with_all = ["budget", "expires", "replace", "for_browser"])] pub encryption: bool, + /// Register a limited key for a browser tab and print it sealed to that tab: paste the + /// `dfkr1:` request the browser shows (Sign in → Use dg, or Renew). This computer keeps + /// signing with its own key. Default limits are the browser's: 0.05 DASH for 90 days. + #[arg(long, value_name = "REQUEST", conflicts_with = "keep_current")] + pub for_browser: Option, + /// With --for-browser: also hand over the identity's encryption key, so the browser opens + /// private repositories. + #[arg(long, requires = "for_browser")] + pub with_encryption_key: bool, + /// With --for-browser: the identity the browser asked a key for. dg refuses, before anything + /// is signed, to make the key for another identity. + #[arg(long, value_name = "IDENTITY_ID", requires = "for_browser")] + pub for_identity: Option, /// Bound to the `dash-forge` contract group (the only binding dg makes; kept for the /// spec's command line). #[arg(long, value_name = "GROUP", default_value = "dash-forge", value_parser = ["dash-forge"])] pub bound: String, - /// Disable this limited key in the same update (default: the one this computer signs with). + /// Disable this limited key in the same update (default: the one this computer signs with; + /// none with --for-browser). #[arg(long, value_name = "KEY_ID")] pub replace: Option, /// Keep the key this computer signs with now valid on Platform (it is no longer stored here). @@ -240,7 +256,283 @@ async fn add_encryption( Ok(()) } +/// The browser key defaults (`forge-web/lib/auth/limited-key.ts` `BROWSER_KEY_DEFAULTS`). +const BROWSER_KEY_BUDGET_DASH: f64 = 0.05; +const BROWSER_KEY_DAYS: u64 = 90; + +/// The flag that selects `network`, a network key (`testnet`, `mainnet`, `devnet-`). +fn network_flag(network: &str) -> String { + match network.strip_prefix("devnet-") { + Some(name) => format!("--devnet-name {name}"), + None => format!("--network {network}"), + } +} + +/// The browser's `dfkr1:` request, refused when it is not one or is for another network. +fn browser_request(ctx: &Ctx, text: &str) -> Result { + let request = forge_core::browser_key::parse_request(text).map_err(|e| { + UserError::new(codes::USAGE, "that is not a browser key request") + .cause(e.to_string()) + .fix("copy the whole command the browser shows, including the dfkr1:… request") + })?; + let network = ctx.network_label(); + if request.network != network { + return Err( + UserError::new(codes::USAGE, "the browser is on another network") + .cause(format!( + "the request is from a site on {}, and dg is on {network}", + request.network + )) + .fix(format!( + "run it again with {}", + network_flag(&request.network) + )) + .note("nothing was sent") + .into(), + ); + } + Ok(request) +} + +/// The encryption key `--with-encryption-key` hands over: the highest-id one `sources` (the +/// master source and the key dg signs with) open. +/// Checked before anything is paid for, so a key dg cannot hand over never leaves the browser +/// with a signing key and a promise. +fn handover_encryption_key( + ctx: &Ctx, + identity: &forge_core::platform::LoadedIdentity, + sources: &[&forge_core::keystore::BridgeIdentity], +) -> Result { + let storage = super::StorageArgs { + insecure_plaintext: false, + signing_only: false, + }; + let key = super::encryption_to_store(ctx, &storage, identity, sources) + .into_iter() + .max_by_key(|k| k.id) + .ok_or_else(|| { + UserError::new(codes::KEY_CANNOT_SIGN, "no encryption key to hand over") + .cause("this identity has no encryption key that the recovery words or the --master file open") + .fix("run it without --with-encryption-key, or add one first: `dg auth keys add --encryption`") + .note("nothing was sent") + })?; + Ok(forge_core::browser_key::EncryptionKey { + key_id: key.id, + private_key_hex: key.private_key_hex.expose().to_string(), + }) +} + +/// The longest a browser key may live (the web app's longest choice, TS-06). +const BROWSER_KEY_MAX_DAYS: u64 = 365; + +/// The master identity for `--for-browser`: `--master`, else the identity dg is signed in as, +/// else the recovery words (only when dg is not signed in at all: a key file that fails to +/// open is an error, not a reason to ask for the words). Refused when it is not `for_identity`. +async fn browser_master( + ctx: &Ctx, + client: &forge_core::platform::PlatformClient, + args: &AddArgs, +) -> Result<( + forge_core::keystore::BridgeIdentity, + Option, +)> { + let current = match ctx.identity_path { + Some(_) => Some(ctx.load_bridge()?), + None => None, + }; + let current_id = current.as_ref().map(|b| b.identity_id.clone()); + let master = match (¤t_id, &args.master) { + (None, None) => { + eprintln!("{}", super::MASTER_PROMPT); + let words = super::read_mnemonic()?; + super::identity_from_words(ctx, client, &words).await? + } + _ => master_identity( + ctx, + args.master.as_deref(), + current_id.as_deref().unwrap_or(""), + )?, + }; + if let Some(want) = &args.for_identity { + if *want != master.identity_id { + return Err( + UserError::new(codes::KEY_CANNOT_SIGN, "that is a different identity") + .cause(format!( + "the browser asked for a key of {want}, and dg would sign for {}", + master.identity_id + )) + .fix(format!("pass --master with the identity file of {want}")) + .note("nothing was sent") + .into(), + ); + } + } + Ok((master, current)) +} + +/// The key a reply carries, from the `dfk1:` text `register_limited_key` hands its `persist`. +fn handoff_payload( + network: &str, + dfk1: &forge_core::keystore::Secret, + replaced: Option, + encryption: Option<&forge_core::browser_key::EncryptionKey>, +) -> Result { + let bridge = forge_core::keystore::BridgeIdentity::from_dfk1(dfk1.expose())?; + let key = bridge.doc_op_key()?; + Ok(forge_core::browser_key::Payload { + v: 1, + network: network.to_string(), + identity_id: bridge.identity_id.clone(), + key_id: key.id, + wif: key.private_key_wif.expose().to_string(), + replaced_key_id: replaced, + encryption_key: encryption.map(|e| forge_core::browser_key::EncryptionKey { + key_id: e.key_id, + private_key_hex: e.private_key_hex.clone(), + }), + }) +} + +/// `dg auth keys add --for-browser ` (TS-06): register a limited key for a browser tab +/// and print it sealed to the tab's one-time key (`forge_core::browser_key`). Nothing is stored +/// here; this computer's own key is untouched unless `--replace` names it. +async fn add_for_browser(ctx: &Ctx, args: &AddArgs, request: &str) -> Result<()> { + let request = browser_request(ctx, request)?; + let network = ctx.network_label(); + let client = ctx.connect().await?; + let (master, current) = browser_master(ctx, &client, args).await?; + let identity = client.fetch_signer(&master).await?; + let encryption = if args.with_encryption_key { + let sources: Vec<_> = std::iter::once(&master).chain(current.as_ref()).collect(); + Some(handover_encryption_key(ctx, &identity, &sources)?) + } else { + None + }; + let spec = key_spec(ctx, &args.limits, BROWSER_KEY_BUDGET_DASH, BROWSER_KEY_DAYS)?; + if spec.expires_at_ms > super::expiry_ms(BROWSER_KEY_MAX_DAYS) { + return Err(crate::errors::usage(format!( + "a browser key lives at most {BROWSER_KEY_MAX_DAYS} days; pass --expires 365d or less" + ))); + } + let checked = super::check_group(ctx, &client, &spec.group, args.limits.strict_group()).await?; + super::explain_new_key(ctx, &master.identity_id, &spec, "for a browser", &checked); + explain_handover(ctx, args.replace, encryption.as_ref()); + ctx.confirm_or_cancel("Add the key?")?; + // The reply is sealed before anything is sent (as `register_limited_key` stores a key before + // it registers it), and again if the key lands under another id. + let seal = |dfk1: &forge_core::keystore::Secret| -> Result<(u32, String)> { + let payload = handoff_payload(&network, dfk1, args.replace, encryption.as_ref())?; + Ok(( + payload.key_id, + forge_core::browser_key::seal(&request, &payload)?, + )) + }; + let mut sealed: Option<(u32, String, forge_core::keystore::Secret)> = None; + let registered = super::register_limited_key( + ctx, + &client, + &master, + &spec, + args.replace, + &checked, + &mut |t| { + let (id, reply) = seal(t)?; + sealed = Some((id, reply, t.clone())); + Ok(()) + }, + ) + .await; + let (id, reply, unconfirmed) = match (registered, sealed) { + (Ok(id), Some((sealed_id, reply, _))) if id == sealed_id => (id, reply, None), + (Ok(id), _) => { + anyhow::bail!("internal error: key #{id} registered, but its reply was not sealed") + } + // The update errored but may have landed (a broadcast that timed out, a node behind): + // a key that is on chain is handed over, or nobody would hold it. + (Err(e), Some((_, _, dfk1))) => { + let Some(landed) = landed_key(ctx, &client, &network, &dfk1).await else { + return Err(e); + }; + let (id, reply) = seal(&landed)?; + (id, reply, Some(format!("{e:#}"))) + } + (Err(e), None) => return Err(e), + }; + ctx.emit( + json!({ + "status": "added", + "keyId": id, + "budgetCredits": spec.budget_credits, + "expiresAt": spec.expires_at_ms, + "replacedKeyId": args.replace, + "encryptionKeyId": encryption.as_ref().map(|e| e.key_id), + "reply": reply, + "warning": unconfirmed, + }), + || { + if let Some(why) = &unconfirmed { + eprintln!("note: the update reported an error ({why}), but key #{id} is on chain"); + } + eprintln!("✓ limited key #{id} added for the browser"); + if let Some(old) = args.replace { + eprintln!(" key #{old} disabled"); + } + eprintln!( + "Paste this line into the browser. It opens only in the tab that asked for it:" + ); + println!("{reply}"); + }, + ); + Ok(()) +} + +/// The key in `dfk1` under the id it is live with on chain (a `dfk1:` text again), if it landed. +async fn landed_key( + ctx: &Ctx, + client: &forge_core::platform::PlatformClient, + network: &str, + dfk1: &forge_core::keystore::Secret, +) -> Option { + let bridge = forge_core::keystore::BridgeIdentity::from_dfk1(dfk1.expose()).ok()?; + let wif = bridge.doc_op_key().ok()?.private_key_wif.clone(); + let identity = client.fetch_identity(&bridge.identity_id).await.ok()?; + let id = identity.key_id_for(wif.expose(), ctx.network())?; + Some(forge_core::keystore::dfk1( + network, + &bridge.identity_id, + id, + wif.expose(), + )) +} + +/// What else the update does (human mode): the key it disables, the encryption key it hands over. +fn explain_handover( + ctx: &Ctx, + replace: Option, + encryption: Option<&forge_core::browser_key::EncryptionKey>, +) { + if ctx.json { + return; + } + // Anyone can show a request: a look-alike page could ask for this command too. + eprintln!( + " run this only for a Forge page you opened yourself: the key can write to Forge as you" + ); + if let Some(old) = replace { + eprintln!(" key #{old} is disabled in the same update"); + } + if let Some(e) = encryption { + eprintln!( + " the browser also gets encryption key #{}: it opens your private repositories", + e.key_id + ); + } +} + async fn add(ctx: &Ctx, args: &AddArgs) -> Result<()> { + if let Some(request) = &args.for_browser { + return add_for_browser(ctx, args, request).await; + } let current = ctx.load_bridge()?; let client = ctx.connect().await?; let master = master_identity(ctx, args.master.as_deref(), ¤t.identity_id)?; @@ -380,3 +672,14 @@ async fn disable(ctx: &Ctx, id: u32, master: Option<&std::path::Path>, force: bo ); Ok(()) } + +#[cfg(test)] +mod tests { + use super::network_flag; + + #[test] + fn the_network_flag_matches_the_browser_command() { + assert_eq!(network_flag("devnet-sakura"), "--devnet-name sakura"); + assert_eq!(network_flag("testnet"), "--network testnet"); + } +} diff --git a/crates/dg/src/auth/mod.rs b/crates/dg/src/auth/mod.rs index 031b78c89..33cd1ba4b 100644 --- a/crates/dg/src/auth/mod.rs +++ b/crates/dg/src/auth/mod.rs @@ -297,6 +297,8 @@ pub fn read_mnemonic() -> Result { .into(), ); } + // The same words before every phrase prompt, here and in the web app (TS-06). + eprintln!("{}", forge_core::browser_key::RECOVERY_PHRASE_WARNING); let words = rpassword::prompt_password("Recovery words (12, hidden as you type): ").map_err(|e| { // Ctrl-D or Ctrl-C: the user left, nothing was written (E803), not "no terminal". @@ -315,7 +317,7 @@ pub fn read_mnemonic() -> Result { /// What [`master_identity`] says before it asks for the recovery words: a user who signed in /// with an identity file has no words at hand, and `--master ` takes that file instead /// (L-34). -const MASTER_PROMPT: &str = +pub(crate) const MASTER_PROMPT: &str = "This needs your master key once. It is used for this one signature and not stored.\n\ Type your 12-word recovery phrase below, or press Ctrl-C and run the command again with \ --master (the file from the bridge, or a `dg auth new --backup-file`)."; @@ -360,7 +362,7 @@ pub fn master_identity( /// The identity's master identity loaded when only words are available and the id is unknown /// yet: derive, then find the identity by its master key on chain. -async fn identity_from_words( +pub(crate) async fn identity_from_words( ctx: &Ctx, client: &PlatformClient, words: &Secret, diff --git a/crates/forge-core/src/browser_key.rs b/crates/forge-core/src/browser_key.rs new file mode 100644 index 000000000..161b9acbb --- /dev/null +++ b/crates/forge-core/src/browser_key.rs @@ -0,0 +1,403 @@ +//! Handing a limited key from `dg` to a browser tab, so the recovery phrase never reaches a web +//! page (trust and safety TS-06; `docs/contracts/forge-v2.md` "Key handoff"). +//! +//! 1. The browser draws a one-time secp256k1 key pair and shows its public half as a +//! **request**: `dfkr1::`. +//! 2. `dg auth keys add --for-browser ` registers a limited key (signed by the master +//! key on the terminal) and prints a **reply** sealed to that public key: +//! `dfkh1::`. +//! 3. The browser opens the reply with its one-time private key, checks the key on chain and +//! keeps it in its vault. +//! +//! The AES key is `HKDF-SHA256(ikm = x(ECDH), salt = ephemeral public ‖ request public, +//! info = "dash-forge/key-handoff/1")`; the associated data is `"dfkh1:" ‖ network`, so a reply +//! for one network does not open on another. The plaintext is a JSON object +//! ([`Payload`]). The reply is useless to anyone without the browser's one-time private key, so +//! it may be printed and pasted; the key it carries is still a limited key, which is the point. +//! +//! The browser side is `forge-web/lib/auth/key-handoff.ts`; both run the +//! `key_handoff_*` conformance vectors. + +use aes_gcm::aead::{Aead as _, Payload as AeadPayload}; +use aes_gcm::{Aes256Gcm, KeyInit as _, Nonce}; +use base64::engine::general_purpose::URL_SAFE_NO_PAD; +use base64::Engine as _; +use hkdf::Hkdf; +use secp256k1::{PublicKey, SecretKey}; +use serde::{Deserialize, Serialize}; +use sha2::Sha256; +use zeroize::Zeroizing; + +use crate::error::{Error, Result}; + +/// The prefix of a browser's request. +pub const REQUEST_PREFIX: &str = "dfkr1:"; +/// The prefix of `dg`'s reply. +pub const REPLY_PREFIX: &str = "dfkh1:"; +/// The HKDF `info` of the reply key. +const INFO: &[u8] = b"dash-forge/key-handoff/1"; +/// The largest plaintext a reply carries (a key, an encryption key and their ids fit in 400 B). +const MAX_PAYLOAD: usize = 2048; + +/// The fixed warning shown before every recovery-phrase prompt, in `dg` and in the web app +/// (TS-06; vector `copy__recovery_phrase_warning`). +pub const RECOVERY_PHRASE_WARNING: &str = + "Your recovery phrase controls your identity. Forge asks \ +for it only after you start a key action yourself, never because a message, an email or a pop-up \ +says so. If you didn't start this, stop here."; + +/// A browser's request: the network it is on and its one-time public key. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Request { + /// The network key (`sakura`, `testnet`, …). + pub network: String, + /// The browser's one-time public key. + pub public_key: PublicKey, +} + +fn bad_request(why: &str) -> Error { + Error::Config(format!( + "that is not a browser key request ({why}); copy the whole dfkr1:… line the browser shows" + )) +} + +fn valid_network(n: &str) -> bool { + !n.is_empty() && n.len() <= 32 && n.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'-') +} + +/// Parse a `dfkr1:` request. +pub fn parse_request(text: &str) -> Result { + let rest = text + .trim() + .strip_prefix(REQUEST_PREFIX) + .ok_or_else(|| bad_request("it does not start with dfkr1:"))?; + let (network, key) = rest + .split_once(':') + .ok_or_else(|| bad_request("it has no network"))?; + if !valid_network(network) { + return Err(bad_request("the network is not a network name")); + } + let bytes = URL_SAFE_NO_PAD + .decode(key) + .map_err(|_| bad_request("the key is not base64url"))?; + if bytes.len() != 33 { + return Err(bad_request("the key is not a compressed public key")); + } + let public_key = + PublicKey::from_slice(&bytes).map_err(|_| bad_request("the key is not on the curve"))?; + Ok(Request { + network: network.to_string(), + public_key, + }) +} + +/// The `dfkr1:` text of a request (the browser makes these; here for tests). +pub fn request_text(network: &str, public_key: &PublicKey) -> String { + format!( + "{REQUEST_PREFIX}{network}:{}", + URL_SAFE_NO_PAD.encode(public_key.serialize()) + ) +} + +/// The key the reply carries. +#[derive(Serialize, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct Payload { + /// Always 1. + pub v: u32, + /// The network key; equal to the request's. + pub network: String, + /// The identity the key belongs to. + pub identity_id: String, + /// The new limited key's id on the identity. + pub key_id: u32, + /// Its private key, WIF. + pub wif: String, + /// The limited key it replaced (disabled in the same update), if any. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub replaced_key_id: Option, + /// The identity's encryption key, when the user chose to hand it over too. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub encryption_key: Option, +} + +/// An `ENCRYPTION` key in a [`Payload`]. +#[derive(Serialize, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct EncryptionKey { + /// Its id on the identity. + pub key_id: u32, + /// The private key, 64 hex characters. + pub private_key_hex: String, +} + +impl Drop for Payload { + fn drop(&mut self) { + use zeroize::Zeroize as _; + self.wif.zeroize(); + } +} + +impl Drop for EncryptionKey { + fn drop(&mut self) { + use zeroize::Zeroize as _; + self.private_key_hex.zeroize(); + } +} + +impl std::fmt::Debug for EncryptionKey { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("EncryptionKey") + .field("key_id", &self.key_id) + .finish_non_exhaustive() + } +} + +impl std::fmt::Debug for Payload { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("Payload") + .field("network", &self.network) + .field("identity_id", &self.identity_id) + .field("key_id", &self.key_id) + .finish_non_exhaustive() + } +} + +/// The AES key for a reply between `ephemeral` (dg's) and `request` (the browser's) keys. +fn reply_key(shared_x: &[u8], ephemeral: &PublicKey, request: &PublicKey) -> Zeroizing<[u8; 32]> { + let mut salt = [0u8; 66]; + salt[..33].copy_from_slice(&ephemeral.serialize()); + salt[33..].copy_from_slice(&request.serialize()); + let hk = Hkdf::::new(Some(&salt), shared_x); + let mut key = Zeroizing::new([0u8; 32]); + hk.expand(INFO, key.as_mut()) + .expect("32 bytes is a valid HKDF-SHA256 length"); + key +} + +fn shared_x(point: &PublicKey, scalar: &SecretKey) -> Zeroizing<[u8; 32]> { + let full = Zeroizing::new(secp256k1::ecdh::shared_secret_point(point, scalar)); + let mut x = Zeroizing::new([0u8; 32]); + x.copy_from_slice(&full[..32]); + x +} + +fn aad(network: &str) -> Vec { + format!("{REPLY_PREFIX}{network}").into_bytes() +} + +/// Seal `payload` for `request` with a fresh ephemeral key and nonce. +pub fn seal(request: &Request, payload: &Payload) -> Result { + let mut eph = Zeroizing::new([0u8; 32]); + let mut nonce = [0u8; 12]; + loop { + getrandom::getrandom(eph.as_mut()) + .map_err(|e| Error::Config(format!("no randomness: {e}")))?; + if SecretKey::from_slice(eph.as_ref()).is_ok() { + break; + } + } + getrandom::getrandom(&mut nonce).map_err(|e| Error::Config(format!("no randomness: {e}")))?; + seal_with(request, payload, &eph, nonce) +} + +/// [`seal`] with a given ephemeral secret and nonce (conformance vectors). +pub fn seal_with( + request: &Request, + payload: &Payload, + ephemeral_secret: &[u8; 32], + nonce: [u8; 12], +) -> Result { + if payload.network != request.network { + return Err(Error::Config(format!( + "the key is for {}, but the browser is on {}", + payload.network, request.network + ))); + } + let plain = Zeroizing::new( + serde_json::to_vec(payload).map_err(|e| Error::Config(format!("payload: {e}")))?, + ); + seal_bytes(request, &plain, ephemeral_secret, nonce) +} + +/// Seal raw plaintext bytes (the vectors fix them byte for byte). +pub fn seal_bytes( + request: &Request, + plain: &[u8], + ephemeral_secret: &[u8; 32], + nonce: [u8; 12], +) -> Result { + if plain.len() > MAX_PAYLOAD { + return Err(Error::Config("the key handoff is too large".into())); + } + let secp = secp256k1::Secp256k1::new(); + let eph = SecretKey::from_slice(ephemeral_secret) + .map_err(|_| Error::Config("bad ephemeral key".into()))?; + let eph_pub = PublicKey::from_secret_key(&secp, &eph); + let x = shared_x(&request.public_key, &eph); + let key = reply_key(x.as_ref(), &eph_pub, &request.public_key); + let cipher = Aes256Gcm::new_from_slice(key.as_ref()).expect("32-byte key"); + let aad = aad(&request.network); + let ct = cipher + .encrypt( + Nonce::from_slice(&nonce), + AeadPayload { + msg: plain, + aad: &aad, + }, + ) + .map_err(|_| Error::Config("sealing the key handoff failed".into()))?; + let mut out = Vec::with_capacity(33 + 12 + ct.len()); + out.extend_from_slice(&eph_pub.serialize()); + out.extend_from_slice(&nonce); + out.extend_from_slice(&ct); + Ok(format!( + "{REPLY_PREFIX}{}:{}", + request.network, + URL_SAFE_NO_PAD.encode(out) + )) +} + +/// Why a reply does not open. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum OpenError { + /// Not a `dfkh1:` reply, or cut short. + Malformed, + /// Made for another network. + Network, + /// Not sealed to this request's key, or altered. + Unreadable, +} + +/// Open a reply with the browser's one-time `secret` (the browser does this; here for tests and +/// for the vectors). Returns the plaintext bytes. +pub fn open( + reply: &str, + network: &str, + secret: &[u8; 32], +) -> std::result::Result>, OpenError> { + let rest = reply + .trim() + .strip_prefix(REPLY_PREFIX) + .ok_or(OpenError::Malformed)?; + let (net, body) = rest.split_once(':').ok_or(OpenError::Malformed)?; + if !valid_network(net) { + return Err(OpenError::Malformed); + } + if net != network { + return Err(OpenError::Network); + } + let bytes = URL_SAFE_NO_PAD + .decode(body) + .map_err(|_| OpenError::Malformed)?; + if bytes.len() < 33 + 12 + 16 { + return Err(OpenError::Malformed); + } + let eph_pub = PublicKey::from_slice(&bytes[..33]).map_err(|_| OpenError::Malformed)?; + let mine = SecretKey::from_slice(secret).map_err(|_| OpenError::Unreadable)?; + let secp = secp256k1::Secp256k1::new(); + let my_pub = PublicKey::from_secret_key(&secp, &mine); + let x = shared_x(&eph_pub, &mine); + let key = reply_key(x.as_ref(), &eph_pub, &my_pub); + let cipher = Aes256Gcm::new_from_slice(key.as_ref()).expect("32-byte key"); + let aad = aad(net); + cipher + .decrypt( + Nonce::from_slice(&bytes[33..45]), + AeadPayload { + msg: &bytes[45..], + aad: &aad, + }, + ) + .map(Zeroizing::new) + .map_err(|_| OpenError::Unreadable) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn browser() -> ([u8; 32], Request) { + let secret = [7u8; 32]; + let secp = secp256k1::Secp256k1::new(); + let pk = PublicKey::from_secret_key(&secp, &SecretKey::from_slice(&secret).unwrap()); + ( + secret, + Request { + network: "sakura".into(), + public_key: pk, + }, + ) + } + + fn payload(network: &str) -> Payload { + Payload { + v: 1, + network: network.into(), + identity_id: "8hJmcHWTsdvkHyCrk4UgjbyugDAmE7QfuCTQXpXAc7nB".into(), + key_id: 7, + wif: "cTestWif".into(), + replaced_key_id: Some(5), + encryption_key: None, + } + } + + #[test] + fn a_request_round_trips_and_garbage_is_refused() { + let (_, req) = browser(); + let text = request_text("sakura", &req.public_key); + assert_eq!(parse_request(&text).unwrap(), req); + assert_eq!(parse_request(&format!(" {text}\n")).unwrap(), req); + for bad in [ + "", + "dfkr1:", + "dfkr1:sakura", + "dfkr1:sa kura:AAAA", + "dfkh1:sakura:AAAA", + "dfkr1:sakura:AAAA", + ] { + assert!(parse_request(bad).is_err(), "{bad}"); + } + } + + #[test] + fn a_reply_opens_only_with_the_request_key_and_network() { + let (secret, req) = browser(); + let reply = seal(&req, &payload("sakura")).unwrap(); + let plain = open(&reply, "sakura", &secret).unwrap(); + let back: Payload = serde_json::from_slice(&plain).unwrap(); + assert_eq!(back.key_id, 7); + assert_eq!(back.replaced_key_id, Some(5)); + assert_eq!( + open(&reply, "testnet", &secret).unwrap_err(), + OpenError::Network + ); + assert_eq!( + open(&reply, "sakura", &[9u8; 32]).unwrap_err(), + OpenError::Unreadable + ); + // one flipped character of the ciphertext + let mut tampered = reply.clone(); + let last = tampered.pop().unwrap(); + tampered.push(if last == 'A' { 'B' } else { 'A' }); + assert!(open(&tampered, "sakura", &secret).is_err()); + // the network in the clear cannot be swapped: it is the associated data + let moved = reply.replacen("dfkh1:sakura:", "dfkh1:testnet:", 1); + assert_eq!( + open(&moved, "testnet", &secret).unwrap_err(), + OpenError::Unreadable + ); + } + + #[test] + fn a_key_for_another_network_is_never_sealed() { + let (_, req) = browser(); + assert!(seal(&req, &payload("testnet")).is_err()); + } + + #[test] + fn the_payload_never_debug_prints_its_keys() { + let p = payload("sakura"); + assert!(!format!("{p:?}").contains("cTestWif")); + } +} diff --git a/crates/forge-core/src/lib.rs b/crates/forge-core/src/lib.rs index 75f534d4b..485a29f68 100644 --- a/crates/forge-core/src/lib.rs +++ b/crates/forge-core/src/lib.rs @@ -38,6 +38,7 @@ //! (`test_support` validates with rs-dpp directly, and never ships). pub mod backends; +pub mod browser_key; pub mod budget; pub mod cache; pub mod ci; diff --git a/crates/forge-core/src/rules.rs b/crates/forge-core/src/rules.rs index e1ba75e49..7abfd2cf0 100644 --- a/crates/forge-core/src/rules.rs +++ b/crates/forge-core/src/rules.rs @@ -2550,23 +2550,7 @@ mod tests { "pubkey_entry" | "commit_signature" => run_signature_case(v), "repo_name" => run_repo_name_case(v), "webhook_url" => run_webhook_url_case(v), - "role_oracle" => { - let inp: RoleOracleInput = input(v); - let oracle = v2::RoleOracle::new(inp.memberships); - let got: Vec = inp - .queries - .iter() - .map(|q| { - serde_json::json!({ - "roleAt": oracle.role_at(&q.identity, q.at), - "memberAt": oracle.member_at(&q.identity, q.at), - "currentRole": oracle.current_role(&q.identity), - "approverAt": oracle.approver_at(&q.identity, q.at), - }) - }) - .collect(); - assert_eq!(serde_json::Value::from(got), v.expected, "vector `{ctx}`"); - } + "role_oracle" => run_role_oracle(v), "code_owners" | "code_owner_requests" => run_code_owners_case(v), "fold_review" | "policy" | "anchor" | "review_group" | "suggestion" | "linked_issues" => run_review_case(v), @@ -2575,10 +2559,127 @@ mod tests { } "long_body" => run_long_body(v), "ci_rerun" | "ci_rerun_write" => run_ci_rerun_case(v), + "key_handoff" | "key_handoff_open" | "copy" => run_key_handoff_case(v), other => panic!("vector `{ctx}`: unknown v2 case `{other}`"), } } + fn run_role_oracle(v: &Vector) { + let inp: RoleOracleInput = input(v); + let oracle = v2::RoleOracle::new(inp.memberships); + let got: Vec = inp + .queries + .iter() + .map(|q| { + serde_json::json!({ + "roleAt": oracle.role_at(&q.identity, q.at), + "memberAt": oracle.member_at(&q.identity, q.at), + "currentRole": oracle.current_role(&q.identity), + "approverAt": oracle.approver_at(&q.identity, q.at), + }) + }) + .collect(); + assert_eq!( + serde_json::Value::from(got), + v.expected, + "vector `{}`", + v.name + ); + } + + #[derive(Deserialize, Serialize)] + #[serde(deny_unknown_fields, rename_all = "camelCase")] + struct KeyHandoffInput { + network: String, + browser_secret: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + ephemeral_secret: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + nonce: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + plaintext: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + reply: Option, + } + + #[derive(Deserialize, Serialize)] + #[serde(deny_unknown_fields)] + struct CopyInput { + id: String, + } + + /// `key_handoff__*` (seal a reply for a request), `key_handoff_open__*` (open one) and + /// `copy__*` (fixed user-facing text): `crate::browser_key`. + fn run_key_handoff_case(v: &Vector) { + use crate::browser_key::{open, request_text, seal_bytes, OpenError, Request}; + let ctx = &v.name; + if v.case == "copy" { + let inp: CopyInput = input(v); + let text = match inp.id.as_str() { + "recoveryPhraseWarning" => crate::browser_key::RECOVERY_PHRASE_WARNING, + other => panic!("vector `{ctx}`: unknown copy `{other}`"), + }; + assert_eq!( + serde_json::json!({ "text": text }), + v.expected, + "vector `{ctx}`" + ); + return; + } + let inp: KeyHandoffInput = input(v); + let h32 = |s: &str| -> [u8; 32] { + hex::decode(s) + .unwrap_or_else(|e| panic!("vector `{ctx}`: {e}")) + .try_into() + .unwrap_or_else(|_| panic!("vector `{ctx}`: not 32 bytes")) + }; + let secret = h32(&inp.browser_secret); + let opened = |reply: &str| match open(reply, &inp.network, &secret) { + Ok(p) => serde_json::json!({ "plaintext": String::from_utf8(p.to_vec()).unwrap() }), + Err(e) => serde_json::json!({ "error": match e { + OpenError::Malformed => "malformed", + OpenError::Network => "network", + OpenError::Unreadable => "unreadable", + } }), + }; + if v.case == "key_handoff_open" { + let reply = inp.reply.as_deref().expect("reply"); + assert_eq!(opened(reply), v.expected, "vector `{ctx}`"); + return; + } + let secp = secp256k1::Secp256k1::new(); + let public_key = secp256k1::PublicKey::from_secret_key( + &secp, + &secp256k1::SecretKey::from_slice(&secret).unwrap(), + ); + let request = Request { + network: inp.network.clone(), + public_key, + }; + let plaintext = inp.plaintext.as_deref().expect("plaintext"); + let nonce: [u8; 12] = hex::decode(inp.nonce.as_deref().expect("nonce")) + .unwrap() + .try_into() + .unwrap(); + let reply = seal_bytes( + &request, + plaintext.as_bytes(), + &h32(inp.ephemeral_secret.as_deref().expect("ephemeralSecret")), + nonce, + ) + .unwrap(); + let got = serde_json::json!({ + "request": request_text(&inp.network, &public_key), + "reply": reply, + }); + assert_eq!(got, v.expected, "vector `{ctx}`"); + assert_eq!( + opened(&reply), + serde_json::json!({ "plaintext": plaintext }), + "vector `{ctx}`: round trip" + ); + } + #[derive(Deserialize, Serialize)] #[serde(deny_unknown_fields, rename_all = "camelCase")] struct LongBodyInput { diff --git a/docs/contracts/forge-v2.md b/docs/contracts/forge-v2.md index d64c06b2f..07c7fdc49 100644 --- a/docs/contracts/forge-v2.md +++ b/docs/contracts/forge-v2.md @@ -499,6 +499,20 @@ The trailer is an HTML comment, which GitHub-flavoured renderers (forge-web's am **What it does not prove.** The file proves that someone who can push to the source named this repo. It says nothing about whether the mirror's content is current: the branch comparison does that, and only for the branch it compares. A source's maintainers can list several mirrors, and take one off the list. Only GitHub sources are checked; GitLab claims stay "says it mirrors". The check tells github.com the viewer's address, which is why it is a button. +### 6.5 Key handoff: a limited key from `dg` to a browser (client convention, TS-06) + +A browser can get its limited key from `dg` instead of from the recovery phrase, so the phrase never enters a web page. Nothing on chain changes: `dg` registers an ordinary limited key (§2, the `dash-forge` group, a budget and an expiry) with one master-key `IdentityUpdate` on the terminal, and hands its private key to the browser sealed. The rules, shared by forge-core (`browser_key`) and forge-web (`lib/auth/key-handoff.ts`) and pinned by the `key_handoff__*` and `key_handoff_open__*` vectors: + +| | Rule | +|---|---| +| **Request** (the browser shows it) | `dfkr1::`, from a one-time key pair drawn for this request and kept only in the tab's memory. `` is the network key (`testnet`, `mainnet`, `devnet-sakura`): 1 to 32 characters of `[A-Za-z0-9-]`. base64url is RFC 4648 §5 without padding, decoded strictly (no `=`, no stray bits). | +| **Reply** (`dg auth keys add --for-browser ` prints it) | `dfkh1::`: `E` dg's ephemeral compressed public key (33 bytes), `N` a random 12-byte nonce, `C` AES-256-GCM of the payload (tag included). Key: `HKDF-SHA256(ikm = x-coordinate of ECDH(ephemeral, request key), salt = E ‖ request public key, info = "dash-forge/key-handoff/1")`. Associated data: `"dfkh1:" ‖ network`, so a reply relabelled for another network does not open. | +| **Payload** | JSON `{"v":1,"network","identityId","keyId","wif"}` plus optional `"replacedKeyId"` (the key disabled in the same update) and `"encryptionKey":{"keyId","privateKeyHex"}` (with `--with-encryption-key`). Unknown fields, another version or another network: refused. At most 2,048 bytes. | +| **Opening** | Not a `dfkh1:` reply, or too short for a tag: *malformed*. Another network: *network*, before decrypting. A tag that fails (another tab's request, an altered reply): *unreadable*. | +| **Adopting** | The browser reads the key back from the chain before storing anything: live, AUTHENTICATION/HIGH, bound to the group, with a budget and an expiry, and controlled by the private key the payload carries. A renewal takes only a key for the signed-in identity, and a key this browser already holds for the identity must be the one the reply says was replaced (else it would stay live with nothing holding it); wallet keys, which `dg` cannot disable by id, renew with the identity file or phrase instead. The command names the identity when the tab knows it (`--for-identity`), and `dg` refuses another one before signing. `dg` refuses a browser key that lives longer than 365 days. The vault records that the key came from `dg`, and **Renew** then offers `dg` first. | + +The reply is useless without the tab's one-time private key, so it may be printed and pasted like any text; what it carries is still only a limited key. A request works once: the tab forgets its private key when the key is stored or the view closes. + ## 7. Measured size and cost From `tools/contract-validate` (rs-dpp v5.0.0-beta.1, `PlatformVersion` 14) on the RC2 build with every flag on. The signed-shape transitions carry a 65-byte recoverable signature and the contract group fields. diff --git a/docs/guides/identity-and-keys.md b/docs/guides/identity-and-keys.md index 912d43e1c..666ae73d1 100644 --- a/docs/guides/identity-and-keys.md +++ b/docs/guides/identity-and-keys.md @@ -105,7 +105,8 @@ Things to know: A web page is whoever served it. If the page, or a script it loads, is compromised, anything you paste into it is gone. - **Never paste your MASTER key, your 12 words, or your main identity file into a website.** That includes forge.dashhq.org. Nothing on Forge needs them. -- The web app's **Import** reads your identity file (or recovery phrase) once: its master key signs one update that registers a [limited key](#limited-keys) for this browser, and is not retained. If you would rather not load the master key into a web page at all, use **Use my Dash wallet** instead (the wallet registers the key), or register a key for the browser from the terminal: `dg auth export --new-key --reveal-secrets --format dfk1 -o key.dfk1`, then under **Advanced** enter the identity id and the key's WIF (the last `:`-separated field of the `dfk1` value). It signs for that tab only. +- The web app's **Import** reads your identity file (or recovery phrase) once: its master key signs one update that registers a [limited key](#limited-keys) for this browser, and is not retained. If you would rather not load the master key into a web page at all, use **Sign in → Use dg on your computer**: the page shows a `dg auth keys add --for-browser …` command, `dg` registers the key with your master key on the terminal and prints a line that only that tab can open ([below](#a-browser-key-from-dg)). **Use my Dash wallet** also keeps the master key out of the page (the wallet registers the key). +- Forge asks for your recovery phrase only after you start a key action yourself. Every phrase prompt, in the web app and in `dg`, shows the same warning: *"Your recovery phrase controls your identity. Forge asks for it only after you start a key action yourself, never because a message, an email or a pop-up says so. If you didn't start this, stop here."* A page that asks for your words without it, or because a message told you to, is not Forge. - For CI, give a pipeline its own limited key: `dg auth export --new-key --budget 0.5 --expires 365d --format dfk1 --reveal-secrets -o runner.dfk1` makes one, and the file's one line is the `DASH_FORGE_KEY` secret. - Prefer a copy of the web app that you [serve yourself](verify-forge.md#run-your-own-copy-of-the-web-app) if you do not want to trust the one on forge.dashhq.org. @@ -120,6 +121,7 @@ Platform lets the MASTER key add new keys to an identity and disable old ones. A ```sh dg auth keys list # every key: purpose, level, budget left, expiry, this computer's dg auth keys add [--budget 0.25 --expires 180d] [--replace | --keep-current] # a new key for this computer; disables the one it replaces +dg auth keys add --for-browser [--replace ] [--with-encryption-key] # a key for a browser tab, printed sealed to it dg auth keys disable # disable one (limited keys; --force for others) dg auth logout [--disable] # forget the key here (and disable it on chain) ``` @@ -170,7 +172,7 @@ A limited key is an identity key with four restrictions: | Where | Budget | Expires | |---|---|---| -| Browser | 0.05 DASH | 90 days | +| Browser | 0.05 DASH | 90 days (30 days to 1 year) | | CLI (`dg auth new` / `login` / `keys add`) | 0.25 DASH | 180 days | | CI runner (`dg auth export --new-key`, Mirror Action) | 0.5 DASH | 365 days | @@ -196,11 +198,27 @@ dg auth name register