From a3ab5600a069f791b74ba749e8472d25a07b2c1f Mon Sep 17 00:00:00 2001 From: pasta Date: Sun, 4 Oct 2026 12:34:55 -0400 Subject: [PATCH 1/8] feat(auth): hand a browser its key from dg, one warning on every phrase prompt, keys up to a year dg auth keys add --for-browser registers a limited key with the master key on the terminal and prints it sealed (ECDH + HKDF + AES-256-GCM) to the one-time key the browser tab shows, so the recovery phrase never enters a web page. The web app gains Sign in -> Use dg and Renew -> With dg (the default for a key that came from dg), checks the key on chain before storing it, and can take the encryption key too. Every recovery-phrase prompt in the web app and dg shows the same fixed warning, and new browser keys can live 30 days to a year. Rust and TypeScript share the key_handoff_* and copy__* conformance vectors; forge-v2.md 6.4 documents the convention (TS-06). Co-Authored-By: Claude Opus 5.5 (1M context) --- crates/dg/src/auth/keys.rs | 198 ++++++++- crates/dg/src/auth/mod.rs | 6 +- crates/forge-core/src/browser_key.rs | 403 ++++++++++++++++++ crates/forge-core/src/lib.rs | 1 + crates/forge-core/src/rules.rs | 135 +++++- docs/contracts/forge-v2.md | 14 + docs/guides/identity-and-keys.md | 26 +- .../copy__recovery_phrase_warning.json | 12 + .../vectors/key_handoff__limited_key.json | 17 + .../key_handoff__with_encryption_key.json | 17 + ...andoff_open__a_request_is_not_a_reply.json | 14 + .../vectors/key_handoff_open__altered.json | 14 + .../key_handoff_open__network_swapped.json | 14 + .../vectors/key_handoff_open__opens.json | 14 + .../key_handoff_open__other_network.json | 14 + .../vectors/key_handoff_open__truncated.json | 14 + .../key_handoff_open__wrong_browser_key.json | 14 + .../components/auth/create-identity-flow.tsx | 2 + forge-web/components/auth/dg-handoff-flow.tsx | 149 +++++++ forge-web/components/auth/key-lifetime.tsx | 23 + .../components/auth/master-key-input.tsx | 26 +- forge-web/components/auth/phrase-warning.tsx | 22 + forge-web/components/encryption-key-panel.tsx | 3 + forge-web/components/identity-top-up-flow.tsx | 2 + forge-web/components/login-modal.tsx | 134 +++++- forge-web/contexts/auth-context.tsx | 4 + forge-web/hooks/use-ui-store.ts | 2 +- forge-web/lib/auth/controller.ts | 54 ++- forge-web/lib/auth/index.ts | 3 + forge-web/lib/auth/key-handoff.test.ts | 74 ++++ forge-web/lib/auth/key-handoff.ts | 238 +++++++++++ forge-web/lib/auth/limited-key.ts | 13 + forge-web/lib/auth/vault.ts | 10 +- forge-web/lib/rules/conformance.test.ts | 45 ++ 34 files changed, 1669 insertions(+), 62 deletions(-) create mode 100644 crates/forge-core/src/browser_key.rs create mode 100644 forge-contracts/vectors/copy__recovery_phrase_warning.json create mode 100644 forge-contracts/vectors/key_handoff__limited_key.json create mode 100644 forge-contracts/vectors/key_handoff__with_encryption_key.json create mode 100644 forge-contracts/vectors/key_handoff_open__a_request_is_not_a_reply.json create mode 100644 forge-contracts/vectors/key_handoff_open__altered.json create mode 100644 forge-contracts/vectors/key_handoff_open__network_swapped.json create mode 100644 forge-contracts/vectors/key_handoff_open__opens.json create mode 100644 forge-contracts/vectors/key_handoff_open__other_network.json create mode 100644 forge-contracts/vectors/key_handoff_open__truncated.json create mode 100644 forge-contracts/vectors/key_handoff_open__wrong_browser_key.json create mode 100644 forge-web/components/auth/dg-handoff-flow.tsx create mode 100644 forge-web/components/auth/key-lifetime.tsx create mode 100644 forge-web/components/auth/phrase-warning.tsx create mode 100644 forge-web/lib/auth/key-handoff.test.ts create mode 100644 forge-web/lib/auth/key-handoff.ts diff --git a/crates/dg/src/auth/keys.rs b/crates/dg/src/auth/keys.rs index 16f686adf..a9ff69554 100644 --- a/crates/dg/src/auth/keys.rs +++ b/crates/dg/src/auth/keys.rs @@ -22,7 +22,9 @@ pub enum KeysCommand { /// Register a key: a limited key 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 chain. Needs the master key once. Disable { @@ -52,13 +54,23 @@ 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, /// 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 live on chain (it is no longer stored here). @@ -238,7 +250,176 @@ 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 `master` opens. +/// 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, + master: &forge_core::keystore::BridgeIdentity, +) -> Result { + let storage = super::StorageArgs { + insecure_plaintext: false, + signing_only: false, + }; + let key = super::encryption_to_store(ctx, &storage, identity, &[master]) + .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(), + }) +} + +/// `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<()> { + use forge_core::browser_key::{self, EncryptionKey, Payload}; + let request = browser_request(ctx, request)?; + let network = ctx.network_label(); + let client = ctx.connect().await?; + let current_id = ctx.load_bridge().map(|b| b.identity_id).unwrap_or_default(); + let master = if current_id.is_empty() && args.master.is_none() { + eprintln!("{}", super::MASTER_PROMPT); + let words = super::read_mnemonic()?; + super::identity_from_words(ctx, &client, &words).await? + } else { + master_identity(ctx, args.master.as_deref(), ¤t_id)? + }; + let identity = client.fetch_signer(&master).await?; + let encryption = if args.with_encryption_key { + Some(handover_encryption_key(ctx, &identity, &master)?) + } else { + None + }; + let spec = key_spec(ctx, &args.limits, BROWSER_KEY_BUDGET_DASH, BROWSER_KEY_DAYS)?; + 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); + if !ctx.json { + if let Some(old) = args.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 + ); + } + } + 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 bridge = forge_core::keystore::BridgeIdentity::from_dfk1(dfk1.expose())?; + let key = bridge.doc_op_key()?; + let payload = Payload { + v: 1, + network: network.clone(), + identity_id: master.identity_id.clone(), + key_id: key.id, + wif: key.private_key_wif.expose().to_string(), + replaced_key_id: args.replace, + encryption_key: encryption.as_ref().map(|e| EncryptionKey { + key_id: e.key_id, + private_key_hex: e.private_key_hex.clone(), + }), + }; + Ok((key.id, browser_key::seal(&request, &payload)?)) + }; + let mut sealed: Option<(u32, String)> = None; + let registered = super::register_limited_key( + ctx, + &client, + &master, + &spec, + args.replace, + &checked, + &mut |t| { + sealed = Some(seal(t)?); + Ok(()) + }, + ) + .await; + let (id, reply) = match (registered, sealed) { + (Ok(id), Some((sealed_id, reply))) if id == sealed_id => (id, reply), + (Ok(id), _) => { + anyhow::bail!("internal error: key #{id} registered, but its reply was not sealed") + } + (Err(e), _) => 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, + }), + || { + 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(()) +} + 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)?; @@ -378,3 +559,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 63bb1d59c..754ef499e 100644 --- a/crates/dg/src/auth/mod.rs +++ b/crates/dg/src/auth/mod.rs @@ -291,6 +291,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". @@ -309,7 +311,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 recovery words below, or press Ctrl-C and run the command again with \ --master (the file from the bridge, or a `dg auth new --backup-file`)."; @@ -354,7 +356,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 2a0c44b72..5807419da 100644 --- a/crates/forge-core/src/rules.rs +++ b/crates/forge-core/src/rules.rs @@ -2484,23 +2484,7 @@ mod tests { }); assert_eq!(got, v.expected, "vector `{ctx}`"); } - "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), @@ -2509,10 +2493,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 1dc681364..739e2b69a 100644 --- a/docs/contracts/forge-v2.md +++ b/docs/contracts/forge-v2.md @@ -477,6 +477,20 @@ The trailer is an HTML comment, which GitHub-flavoured renderers (forge-web's am **Why not a chain of comments.** The other design considered stores the rest of a text in further `comment` documents (anyone may write one, and no storage is needed). It was not taken: releases have no comments, so the release notes this item is about could not use it; the parts would count in every proved comment count (§6.1) and interleave with other people's comments in a paged thread; each part is a deletable document of its own, refused on a locked thread to non-members; and an edit would rewrite all of them. The artifact keeps one mechanism for every field, uses the storage and reader rule artifacts already have, and costs the reads above only where the text is shown. Its limit is the gate: a non-member's text stays within the field. A later attribute naming another repository the writer may store in (a PR's fork, say) would lift that; readers of this version treat an unknown attribute as unsupported, never as another meaning. An optional pointer property on the document types was also possible by a contract update, and is not needed. +### 6.4 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. 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 f640bfc80..e4d2571dc 100644 --- a/docs/guides/identity-and-keys.md +++ b/docs/guides/identity-and-keys.md @@ -103,7 +103,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. @@ -118,6 +119,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) ``` @@ -168,7 +170,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 | @@ -194,11 +196,27 @@ dg auth name register