From fdb21b5ba86f1ae5f190d95c0cb19fb71a10a871 Mon Sep 17 00:00:00 2001 From: pasta Date: Wed, 30 Sep 2026 15:51:16 -0500 Subject: [PATCH 1/2] fix(dg): keep the encryption key beside the limited key, describe runner keys, per-file passphrases QW2-004: dg auth login, dg auth new and dg auth keys add store the identity's ENCRYPTION keys beside the limited signing key (a bridge identity holding exactly those, no master key or words), so private repositories work without the master key on disk, as the web's Enable private repos does. --signing-only opts out. auth status shows a Private: line, doctor says it too, and E306/E301 now point at signing in again instead of --full-key. QW2-005: auth status and doctor describe a key bound to one document type (a CI runner key) as such, with its budget and expiry, instead of unlimited / a general write key; doctor fails a key that is not live on the identity. QW2-022: dg ci runner new reads the --runner file's passphrase from DASH_FORGE_RUNNER_PASSPHRASE (else DASH_FORGE_PASSPHRASE); a sealed file that does not open is E303 naming the file and where the passphrase came from, not an E204. QW-034: dg webhook list is a read that opens no key for a public repository. Co-Authored-By: Claude Opus 5.5 (1M context) --- crates/dg/src/auth/keys.rs | 14 +- crates/dg/src/auth/mod.rs | 260 +++++++++++++++++++++++++-- crates/dg/src/auth/new.rs | 32 +++- crates/dg/src/ci.rs | 7 +- crates/dg/src/doctor.rs | 57 +++++- crates/dg/src/webhook.rs | 11 +- crates/forge-core/src/keyring.rs | 68 ++++++- crates/forge-core/src/keystore.rs | 81 ++++++++- crates/forge-core/src/sealed.rs | 28 ++- crates/forge-core/src/user_error.rs | 14 +- crates/git-remote-dash/src/helper.rs | 2 +- docs/errors.md | 8 +- docs/guides/ci.md | 4 + docs/guides/collaborating.md | 2 +- docs/guides/identity-and-keys.md | 10 +- docs/guides/quick-start.md | 2 +- 16 files changed, 530 insertions(+), 70 deletions(-) diff --git a/crates/dg/src/auth/keys.rs b/crates/dg/src/auth/keys.rs index 6d1323eb7..d94a1809a 100644 --- a/crates/dg/src/auth/keys.rs +++ b/crates/dg/src/auth/keys.rs @@ -167,10 +167,9 @@ async fn list(ctx: &Ctx) -> Result<()> { /// id, so the words alone recover it. One identity update signed by the master key. /// /// Only a master identity that carries its words can do this: the private half must be -/// recoverable, and `dg` keeps nothing but limited keys (an ENCRYPTION key is not one). Readers -/// (`git clone`, `dg`) need the key's private half in the identity they sign with: sign in with -/// the full identity for private repositories (`dg auth login --full-key`), or keep the words' -/// file, which now derives it. +/// recoverable. Readers (`git clone`, `dg`) need the key's private half in the key source they +/// sign with: `dg auth login` again stores it beside a limited key (QW2-004), and the words' +/// file now derives it. async fn add_encryption( ctx: &Ctx, client: &forge_core::platform::PlatformClient, @@ -214,7 +213,10 @@ async fn add_encryption( "purpose": "ENCRYPTION", "derived": true, }), - || println!("✓ added ENCRYPTION key #{added}; the recovery words re-derive it"), + || { + println!("✓ added ENCRYPTION key #{added}; the recovery words re-derive it"); + println!(" to use it from this computer: `dg auth login ` (or --mnemonic) stores it beside a limited key"); + }, ); Ok(()) } @@ -276,7 +278,7 @@ async fn add(ctx: &Ctx, args: &AddArgs) -> Result<()> { &spec, replace, &checked, - args.storage.insecure_plaintext, + &args.storage, ) .await?; super::store::set_default(ctx, &master.identity_id, &stored.source())?; diff --git a/crates/dg/src/auth/mod.rs b/crates/dg/src/auth/mod.rs index 2f1bea42b..260fccfd7 100644 --- a/crates/dg/src/auth/mod.rs +++ b/crates/dg/src/auth/mod.rs @@ -8,7 +8,7 @@ //! - `new` — recovery words → deposit QR → asset lock → identity with its canonical keys and a //! limited key in one IdentityCreate ([`new`]). //! - `login` — import an identity file or the recovery words once, register a limited key, -//! store only that key. +//! store only that key (with the identity's encryption key beside it, QW2-004). //! - `status`, `balance`, `keys list|add|disable`, `name register`, `export`, `logout`. pub mod group; @@ -118,6 +118,10 @@ pub struct StorageArgs { /// passphrase. Every later use warns. #[arg(long)] pub insecure_plaintext: bool, + /// Store the limited signing key only, not your identity's encryption key beside it + /// (private repositories then need DASH_FORGE_KEY= for each command). + #[arg(long)] + pub signing_only: bool, } /// `dg auth login` arguments. @@ -429,6 +433,9 @@ pub async fn register_limited_key( /// outcome is unclear (the update errored, but it may have landed), the chain is asked: a key /// that landed is promoted; otherwise both copies stay and the error says where each is. /// Returns the new key's id and where it is stored. +/// +/// Unless `--signing-only`, the identity's `ENCRYPTION` keys that `master` holds are stored +/// beside the new key ([`encryption_keys_of`]), so private repositories work with it. pub async fn register_and_store( ctx: &Ctx, client: &PlatformClient, @@ -436,22 +443,42 @@ pub async fn register_and_store( spec: &LimitedKeySpec, replace: Option, checked: &group::GroupCheck, - insecure_plaintext: bool, + storage: &StorageArgs, ) -> Result<(u32, store::Stored)> { let network = ctx.network_label(); let id_ = master.identity_id.clone(); - let storer = std::cell::RefCell::new(store::Storer::new(insecure_plaintext)); + let encryption = if storage.signing_only { + vec![] + } else { + let identity = client + .fetch_signer(master) + .await + .context("fetching the signing identity")?; + encryption_keys_of(ctx, &identity, master) + }; + let storer = std::cell::RefCell::new(store::Storer::new(storage.insecure_plaintext)); let in_use = ctx.identity_path.as_ref().map_or_else( || "none".to_string(), |p| store::describe_source(&p.to_string_lossy()).0, ); + // The slots take the new key's `dfk1:` text and store it with the encryption keys. let slots = KeySlots { stage: |t: &Secret| { - storer - .borrow_mut() - .store(&network, &id_, t, store::Slot::Pending) + storer.borrow_mut().store( + &network, + &id_, + &with_encryption_keys(t, &encryption)?, + store::Slot::Pending, + ) + }, + promote: |t: &Secret| { + store::promote( + &mut storer.borrow_mut(), + &network, + &id_, + &with_encryption_keys(t, &encryption)?, + ) }, - promote: |t: &Secret| store::promote(&mut storer.borrow_mut(), &network, &id_, t), }; let mut staged = None; let result = register_limited_key(ctx, client, master, spec, replace, checked, &mut |t| { @@ -478,6 +505,89 @@ pub async fn register_and_store( settle(&slots, result, staged, landed, &in_use) } +/// The identity's `ENCRYPTION` keys `master` holds (or derives from its recovery words) that +/// match its keys on chain, as entries to store beside a limited key (QW2-004): a private +/// repository then opens with the limited key, as in the web app's "Enable private repos", +/// instead of needing the master key on disk. Empty on a network with no forge-v2 contracts, +/// or when the identity has none. +pub fn encryption_keys_of( + ctx: &Ctx, + identity: &LoadedIdentity, + master: &BridgeIdentity, +) -> Vec { + let Some(v2) = ctx.target.v2.as_ref() else { + return vec![]; + }; + forge_core::keyring::EncryptionKeys::held( + master, + &identity.public_keys(), + &v2.core, + ctx.network(), + ) + .to_identity_keys(ctx.network()) +} + +/// What is stored for the limited key `dfk1`: the `dfk1:` text alone, or with `encryption` +/// keys, a bridge-format identity holding exactly that key and those (no mnemonic, no master +/// key, nothing else). +pub fn with_encryption_keys(dfk1: &Secret, encryption: &[keystore::IdentityKey]) -> Result { + if encryption.is_empty() { + return Ok(dfk1.clone()); + } + let mut bridge = BridgeIdentity::from_dfk1(dfk1.expose())?; + bridge.identity_keys.extend(encryption.iter().cloned()); + Ok(bridge.to_json_with_secrets()) +} + +/// The login / new / keys add line for the encryption keys stored beside a limited key. +pub fn print_kept_encryption(kept: &[keystore::IdentityKey]) { + let ids: Vec = kept.iter().map(|k| k.id).collect(); + if ids.is_empty() { + println!(" signing key only: private repositories need DASH_FORGE_KEY="); + } else { + println!( + " with encryption key {}: private repositories you are a member of open with it", + key_id_list(&ids) + ); + } +} + +/// `#4`, or `#4, #7`. +pub fn key_id_list(ids: &[u32]) -> String { + ids.iter() + .map(|i| format!("#{i}")) + .collect::>() + .join(", ") +} + +/// `dg auth status`'s `Private:` line: whether private repositories open with the key source +/// (an `ENCRYPTION` key held beside the signing key). None when the key was not opened, or +/// for a CI runner key, which never needs one. +pub(crate) fn private_line(encryption: Option<&[u32]>, runner_key: bool) -> Option { + match encryption? { + [] if runner_key => None, + [] => Some( + "no encryption key stored; `dg auth login ` again stores it beside a \ + limited key" + .into(), + ), + ids => Some(format!( + "encryption key {} stored (opens private repositories you are a member of)", + key_id_list(ids) + )), + } +} + +/// The `ENCRYPTION` key ids a key source holds. +pub fn encryption_key_ids(bridge: &BridgeIdentity) -> Vec { + bridge + .identity_keys + .iter() + .filter(|k| k.purpose == "ENCRYPTION") + .map(|k| k.id) + .collect() +} + /// Where a new key is kept while it is being registered. struct KeySlots { /// Write the key to the staging slot. @@ -687,7 +797,7 @@ async fn login_source( } /// Import an identity once: register a limited key signed by its master key and store only -/// that key (or, with `--full-key`, the whole identity). +/// that key and the identity's encryption keys (or, with `--full-key`, the whole identity). #[allow(clippy::too_many_lines)] async fn login(ctx: &Ctx, args: &LoginArgs) -> Result<()> { let client = ctx.connect().await?; @@ -713,6 +823,13 @@ async fn login(ctx: &Ctx, args: &LoginArgs) -> Result<()> { "--full-key keeps the master key: it goes to a passphrase-sealed file, never unencrypted (drop --insecure-plaintext)", )); } + // The encryption keys stored with the signing key (all of the identity's, with + // --full-key); `register_and_store` finds the same ones for a new limited key. + let kept_encryption = if args.storage.signing_only && !full_key { + vec![] + } else { + encryption_keys_of(ctx, &on_chain, &master) + }; let (stored, key_id, spec) = if full_key || master.master_key().is_none() { // --full-key, no forge-v2 here, or a file holding one limited key (an export of this // or another computer's key): store it as it is. A master key never goes into the @@ -720,12 +837,14 @@ async fn login(ctx: &Ctx, args: &LoginArgs) -> Result<()> { let lone_key = master.master_key().is_none(); let text = if lone_key { let k = master.doc_op_key()?; - keystore::dfk1( + let dfk1 = keystore::dfk1( &master.network, &master.identity_id, k.id, k.private_key_wif.expose(), - ) + ); + // an export of a limited key and its encryption key keeps both + with_encryption_keys(&dfk1, &kept_encryption)? } else { master.to_json_with_secrets() }; @@ -754,7 +873,7 @@ async fn login(ctx: &Ctx, args: &LoginArgs) -> Result<()> { &spec, args.replace, &checked, - insecure, + &args.storage, ) .await?; (stored, Some(id), Some((spec, checked))) @@ -769,6 +888,7 @@ async fn login(ctx: &Ctx, args: &LoginArgs) -> Result<()> { "network": network, "keyId": key_id, "fullKey": full_key, + "encryptionKeyIds": kept_encryption.iter().map(|k| k.id).collect::>(), "budgetCredits": spec.as_ref().map(|(s, _)| s.budget_credits), "expiresAt": spec.as_ref().map(|(s, _)| s.expires_at_ms), "storage": stored.kind(), @@ -792,6 +912,9 @@ async fn login(ctx: &Ctx, args: &LoginArgs) -> Result<()> { ), _ => println!(" the key in the file is stored as it is (no new key registered)"), } + if !full_key { + print_kept_encryption(&kept_encryption); + } println!(" stored in {}", stored.describe()); println!(" balance {} DASH", dash_amount(credits_to_dash(balance))); if key_id.is_some() { @@ -841,15 +964,17 @@ pub fn explain_new_key( // --------------------------------------------------------------------------------------- /// Which key a source signs with, and what the chain says about it. -struct KeyReport { - key_id: Option, +pub(crate) struct KeyReport { + pub key_id: Option, limited: bool, + /// The one document type the key is bound to (a CI runner key: `checkRun`). + pub doc_type: Option, total: Option, remaining: Option, expires_at: Option, } -async fn key_report( +pub(crate) async fn key_report( client: &PlatformClient, identity: &LoadedIdentity, bridge: &BridgeIdentity, @@ -868,6 +993,9 @@ async fn key_report( KeyReport { key_id, limited: key_id.is_some_and(|id| identity.is_limited_key(id)), + doc_type: key_id + .and_then(|id| identity.key_doc_type(id)) + .map(|(_, doc_type)| doc_type), total: limits.and_then(|l| l.total_budget), remaining, expires_at: limits.and_then(|l| l.expires_at), @@ -925,6 +1053,8 @@ async fn status(ctx: &Ctx) -> Result<()> { None => (None, None, vec![]), }; let master = bridge.as_ref().map(|b| b.master_key().is_some()); + let encryption = bridge.as_ref().map(encryption_key_ids); + let runner_key = report.as_ref().is_some_and(|r| r.doc_type.is_some()); ctx.emit( json!({ "network": network, @@ -933,6 +1063,8 @@ async fn status(ctx: &Ctx) -> Result<()> { "names": names, "keyId": report.as_ref().and_then(|r| r.key_id), "limited": report.as_ref().map(|r| r.limited), + "boundDocumentType": report.as_ref().and_then(|r| r.doc_type.clone()), + "encryptionKeyIds": encryption, "budgetCredits": report.as_ref().and_then(|r| r.total), "budgetRemainingCredits": report.as_ref().and_then(|r| r.remaining), "expiresAt": report.as_ref().and_then(|r| r.expires_at), @@ -954,12 +1086,15 @@ async fn status(ctx: &Ctx) -> Result<()> { "Key: {}", key_line(report.as_ref(), unopened.as_deref(), reached) ); + if let Some(line) = private_line(encryption.as_deref(), runner_key) { + println!("Private: {line}"); + } if let Some(b) = balance { println!("Balance: {} DASH", dash_amount(credits_to_dash(b))); } println!("Stored: {where_}"); if master == Some(true) { - println!(" (holds the master key: `dg auth login ` would store only a limited key)"); + println!(" (holds the master key: `dg auth login ` would store only a limited key and the encryption key)"); if kind == "keychain" { println!(" warning: an older dg put this master key in the keychain, where any program running as you can read it; `dg auth login --full-key ` moves it to a sealed file"); } @@ -971,19 +1106,37 @@ async fn status(ctx: &Ctx) -> Result<()> { /// The status's `Key:` line: the key's limits, or why they were not checked (the key was not /// opened, or Platform was not `reached`). -fn key_line(report: Option<&KeyReport>, unopened: Option<&str>, reached: bool) -> String { +pub(crate) fn key_line( + report: Option<&KeyReport>, + unopened: Option<&str>, + reached: bool, +) -> String { match (report, unopened) { (Some(r), _) => { let id = r.key_id.map_or("?".to_string(), |i| format!("#{i}")); - if r.limited { + let limits = || { format!( - "{id} limited — {} of {} DASH left, expires {}", + "{} of {} DASH left, expires {}", r.remaining .map_or("?".into(), |c| dash_amount(credits_to_dash(c))), r.total .map_or("?".into(), |c| dash_amount(credits_to_dash(c))), r.expires_at.map_or("never".into(), expiry_text) ) + }; + if r.limited { + format!("{id} limited — {}", limits()) + } else if let Some(doc_type) = &r.doc_type { + // QW2-005: a CI runner key signs one document type, and nothing else. + format!( + "{id} bound to {doc_type} documents only{} — {}", + if doc_type == "checkRun" { + " (a CI runner key)" + } else { + "" + }, + limits() + ) } else { format!("{id} unlimited (not a Forge limited key)") } @@ -1463,6 +1616,77 @@ mod tests { assert_eq!(main.borrow().as_deref(), Some("dfk1:new")); } + /// QW2-004: a limited key is stored with the encryption keys as a bridge identity holding + /// exactly those (no master key, no words); without any, as the plain `dfk1:` key. + #[test] + fn a_limited_key_is_stored_with_its_encryption_keys() { + const ID: &str = "8hJmcHWTsdvkHyCrk4UgjbyugDAmE7QfuCTQXpXAc7nB"; + let dfk1 = keystore::dfk1("devnet-bonsia", ID, 5, "FAKE-wif"); + assert_eq!( + with_encryption_keys(&dfk1, &[]).unwrap().expose(), + dfk1.expose() + ); + let enc = keystore::IdentityKey { + id: 4, + name: "enc".into(), + key_type: "ECDSA_SECP256K1".into(), + purpose: "ENCRYPTION".into(), + security_level: "MEDIUM".into(), + private_key_wif: Secret::new("FAKE-enc-wif"), + private_key_hex: Secret::new("07".repeat(32)), + public_key_hex: "02ab".into(), + derivation_path: String::new(), + }; + let text = with_encryption_keys(&dfk1, std::slice::from_ref(&enc)).unwrap(); + let b = BridgeIdentity::from_source_text(text.expose()).unwrap(); + assert_eq!(b.identity_id, ID); + assert_eq!(b.network, "devnet-bonsia"); + assert!(b.master_key().is_none()); + assert!(b.mnemonic.expose().is_empty()); + assert_eq!(b.doc_op_key().unwrap().id, 5); + assert_eq!(encryption_key_ids(&b), [4]); + assert_eq!(b.identity_keys.len(), 2); + } + + /// QW2-005: a key bound to one document type (a CI runner key) says so, not "unlimited". + #[test] + fn a_runner_key_is_described_as_bound_to_its_document_type() { + let report = |limited, doc_type: Option<&str>| KeyReport { + key_id: Some(6), + limited, + doc_type: doc_type.map(str::to_string), + total: Some(50_000_000_000), + remaining: Some(49_000_000_000), + expires_at: None, + }; + let line = key_line(Some(&report(false, Some("checkRun"))), None, true); + assert!( + line.starts_with( + "#6 bound to checkRun documents only (a CI runner key) — 0.49 of 0.5 DASH left" + ), + "{line}" + ); + assert!(!line.contains("unlimited"), "{line}"); + assert!(key_line(Some(&report(true, None)), None, true).starts_with("#6 limited — ")); + assert_eq!( + key_line(Some(&report(false, None)), None, true), + "#6 unlimited (not a Forge limited key)" + ); + } + + #[test] + fn the_private_line_says_whether_private_repositories_open() { + assert_eq!(private_line(None, false), None); + assert_eq!(private_line(Some(&[]), true), None); + assert!(private_line(Some(&[]), false) + .unwrap() + .starts_with("no encryption key stored")); + assert_eq!( + private_line(Some(&[4, 7]), false).unwrap(), + "encryption key #4, #7 stored (opens private repositories you are a member of)" + ); + } + #[test] fn durations() { assert_eq!(parse_days("180d").unwrap(), 180); diff --git a/crates/dg/src/auth/new.rs b/crates/dg/src/auth/new.rs index 22bc00c98..e3ae482e3 100644 --- a/crates/dg/src/auth/new.rs +++ b/crates/dg/src/auth/new.rs @@ -721,6 +721,28 @@ async fn fund_and_lock( Ok((lock, proof)) } +/// The new identity's `ENCRYPTION` key entries (key 4, registered in the same IdentityCreate) +/// to store beside its limited key, unless `--signing-only`. +fn encryption_to_keep( + args: &NewArgs, + keys: &NewIdentityKeys, + identity_id: &str, +) -> Vec { + if args.storage.signing_only { + return vec![]; + } + keys.to_bridge(identity_id) + .identity_keys + .into_iter() + .filter(|k| k.purpose == "ENCRYPTION") + .map(|mut k| { + // what the stored key needs, not how to derive it again + k.derivation_path.clear(); + k + }) + .collect() +} + /// Store this computer's limited key, then register the identity with it (or, when an earlier /// run already created the identity, register a fresh limited key with the words' master key). #[allow(clippy::too_many_arguments)] @@ -762,7 +784,8 @@ async fn register( let replace = identity .is_limited_key(FIRST_LIMITED_KEY_ID) .then_some(FIRST_LIMITED_KEY_ID); - return register_and_store(ctx, client, &master, spec, replace, checked, insecure).await; + return register_and_store(ctx, client, &master, spec, replace, checked, &args.storage) + .await; } let limited = FreshKey::generate(ctx.network()); let dfk1 = forge_core::keystore::dfk1( @@ -771,8 +794,12 @@ async fn register( FIRST_LIMITED_KEY_ID, limited.wif().expose(), ); + // With the identity's encryption key (key 4, registered in the same IdentityCreate), so + // private repositories work with this computer's key (QW2-004), unless --signing-only. + let encryption = encryption_to_keep(args, keys, identity_id); + let text = super::with_encryption_keys(&dfk1, &encryption)?; // Stored before the identity exists: an interruption never leaves a key nobody holds. - let stored = store::store(&network, identity_id, &dfk1, insecure)?; + let stored = store::store(&network, identity_id, &text, insecure)?; say(ctx, " registering the identity…"); client .create_identity(keys, proof, &limited, spec) @@ -879,6 +906,7 @@ pub async fn run(ctx: &Ctx, args: &NewArgs) -> Result<()> { dash_amount(credits_to_dash(spec.budget_credits)), expiry_text(spec.expires_at_ms) ); + super::print_kept_encryption(&encryption_to_keep(args, &keys, &identity_id)); println!(" stored in {}", stored.describe()); println!(" balance {} DASH", dash_amount(credits_to_dash(balance))); println!(" next: cd my-project && dg init"); diff --git a/crates/dg/src/ci.rs b/crates/dg/src/ci.rs index ab0fb6fba..a942f7c9f 100644 --- a/crates/dg/src/ci.rs +++ b/crates/dg/src/ci.rs @@ -247,7 +247,12 @@ fn key_holder(ctx: &Ctx, args: &RunnerNewArgs, me: &str) -> Result Vec { if forge_core::keystore::is_file_source(&path) { out.push(file_mode_check(&path)); } - out.push(if bridge.doc_op_key().is_ok() { - Check::ok("keys", "HIGH/CRITICAL auth key for writes") - } else { - Check::fail( + if bridge.doc_op_key().is_err() { + out.push(Check::fail( "keys", "no HIGH or CRITICAL AUTHENTICATION key: nothing can be signed", "export the identity again from the bridge (it includes the auth keys)", - ) - }); - out.push(match ctx.connect().await { - Err(_) => Check::warn( + )); + } + let client = ctx.connect().await; + let identity = match &client { + Ok(c) => Some(c.fetch_identity(&bridge.identity_id).await), + Err(_) => None, + }; + if bridge.doc_op_key().is_ok() { + out.push(match (&client, &identity) { + (Ok(c), Some(Ok(identity))) => keys_check( + &crate::auth::key_report(c, identity, &bridge, ctx).await, + &bridge, + ), + // Not on chain, or not reachable: the balance row says which; what the key file + // holds is all that can be said. + _ => Check::ok( + "keys", + "HIGH/CRITICAL auth key for writes (its limits on chain not checked)", + ), + }); + } + out.push(match (client, identity) { + (Err(_), _) | (_, None) => Check::warn( "balance", "not checked: Platform unreachable (see network)", "run `dg doctor` again when the network row passes", ), - Ok(client) => match client.get_balance(&bridge.identity_id).await { + (Ok(_), Some(fetched)) => match fetched.map(|i| i.balance()) { Ok(credits) => balance_check(credits), Err(forge_core::Error::NotFound) => Check::fail( "balance", @@ -544,6 +561,28 @@ async fn check_identity(ctx: &Ctx) -> Vec { out } +/// The `keys` row: what the key in use can sign, as the chain says (QW2-005: a CI runner key +/// bound to `checkRun` passed as "HIGH/CRITICAL auth key for writes"), and whether private +/// repositories open with it (an `ENCRYPTION` key held beside it). +fn keys_check( + report: &crate::auth::KeyReport, + bridge: &forge_core::keystore::BridgeIdentity, +) -> Check { + if report.key_id.is_none() { + return Check::fail( + "keys", + "the key in use is not a live key of this identity (disabled, or never registered)", + "sign in again: `dg auth login ` or `dg auth login --mnemonic`", + ); + } + let line = crate::auth::key_line(Some(report), None, true); + let ids = crate::auth::encryption_key_ids(bridge); + let also = crate::auth::private_line(Some(&ids), report.doc_type.is_some()) + .map(|l| format!("; {l}")) + .unwrap_or_default(); + Check::ok("keys", format!("{line}{also}")) +} + fn balance_check(credits: u64) -> Check { let dash = credits_to_dash(credits); let detail = format!("{} DASH", dash_amount(dash)); diff --git a/crates/dg/src/webhook.rs b/crates/dg/src/webhook.rs index 7ed67b1c8..0ae0420b6 100644 --- a/crates/dg/src/webhook.rs +++ b/crates/dg/src/webhook.rs @@ -20,7 +20,7 @@ use forge_core::webhooks::{ WebhookService, }; -use crate::common::{resolve, RepoRef}; +use crate::common::{resolve, Reader, RepoRef}; use crate::context::Ctx; use crate::fmt::{cost_json, cost_line, dash_usd_price}; use crate::secret_out::{self, Stream, Surroundings}; @@ -275,12 +275,13 @@ fn refuse_unless_shown(here: Surroundings) -> Result<()> { .into()) } +/// A read: no key is opened for a public repository (QW-034: a sealed key with no terminal +/// stopped it with E303, while every other list reads on). async fn list(ctx: &Ctx, repo: &str) -> Result<()> { - let repo_ref = RepoRef::parse(repo)?; - let (client, _bridge, identity) = ctx.connect_with_identity().await?; - let handle = resolve(&client, &identity, &repo_ref).await?; + let r = Reader::open(ctx, repo).await?; + let handle = &r.repo; let hooks = newest_per_hook( - WebhookReader::new(&client) + WebhookReader::new(&r.client) .for_repo(handle.id()) .await .context("listing webhooks")?, diff --git a/crates/forge-core/src/keyring.rs b/crates/forge-core/src/keyring.rs index bf7c5ca14..67ca8d574 100644 --- a/crates/forge-core/src/keyring.rs +++ b/crates/forge-core/src/keyring.rs @@ -127,6 +127,24 @@ impl EncryptionKeys { .map(|(id, (k, _))| (*id, k)) } + /// The keys held, as identity-file entries (`ENCRYPTION` / `MEDIUM`, the private key as hex + /// and as a WIF for `network`, no derivation path): what `dg auth login` keeps beside a + /// limited signing key, so private repositories open with no master key on disk, as in the + /// web app (QW2-004). Disabled ones are kept too: they still open history. + pub fn to_identity_keys( + &self, + network: &platform::Network, + ) -> Vec { + use platform::identity_keys::{encryption_key_entry, EncryptionSecret}; + self.keys + .iter() + .filter_map(|(id, (k, _))| { + let secret = EncryptionSecret::new(*k.secret_bytes()).ok()?; + Some(encryption_key_entry(&secret, *id, network, "")) + }) + .collect() + } + /// The private key with `id`, enabled or not. fn get(&self, id: u32) -> Option<&PrivateKey> { self.keys.get(&id).map(|(k, _)| k) @@ -168,7 +186,7 @@ pub fn no_encryption_key_held_because(action: &str, why: &str) -> Error { codes::NO_ENCRYPTION_KEY, format!("{action}: the key stored on this computer holds no encryption key"), ) - .cause(format!("{why}; the key source in use holds none that matches an enabled one on your identity (a limited key from `dg auth login` or `dg auth new` is a signing key only)")) + .cause(format!("{why}; the key source in use holds none that matches an enabled one on your identity (a limited key stored by an older dg, or with --signing-only, is a signing key only)")) .fix(format!( "if your identity has an ENCRYPTION key (`dg auth keys list`), store a source that holds it: {}", crate::user_error::FIX_FULL_KEY_LOGIN @@ -2328,7 +2346,7 @@ mod tests { u.message ); assert!( - u.fix.iter().any(|f| f.contains("--mnemonic --full-key")), + u.fix.iter().any(|f| f.contains("dg auth login --mnemonic")), "{:?}", u.fix ); @@ -3075,6 +3093,52 @@ mod tests { assert_eq!(short_branch("refs/tags/v1"), "refs/tags/v1"); } + /// QW2-004: the encryption keys a source holds, as the entries a limited-key login stores + /// beside its signing key: only those matching the identity's keys on chain, and they are + /// held again when read back. + #[test] + fn held_encryption_keys_become_identity_file_entries() { + use crate::platform::identity_keys::{encryption_key_entry, EncryptionSecret}; + let net = platform::Network::from_key("testnet"); + let entry = |seed: u8, id| { + encryption_key_entry(&EncryptionSecret::new([seed; 32]).unwrap(), id, &net, "m/x") + }; + let mut bridge = BridgeIdentity::from_dfk1( + "dfk1:testnet:8hJmcHWTsdvkHyCrk4UgjbyugDAmE7QfuCTQXpXAc7nB:5:FAKE-wif", + ) + .unwrap(); + // key 4 is on chain; key 9 is not (a stale file): only 4 is kept + bridge.identity_keys.extend([entry(7, 4), entry(8, 9)]); + let on_chain = |e: &crate::keystore::IdentityKey| IdentityKeyInfo { + id: e.id, + purpose: "ENCRYPTION".into(), + security_level: "MEDIUM".into(), + key_type: "ECDSA_SECP256K1".into(), + public_key: hex::decode(&e.public_key_hex).unwrap(), + disabled: false, + bound_to: None, + }; + let chain = [on_chain(&entry(7, 4))]; + let kept = EncryptionKeys::held(&bridge, &chain, "CORE", &net).to_identity_keys(&net); + assert_eq!(kept.len(), 1); + assert_eq!(kept[0].id, 4); + assert_eq!(kept[0].purpose, "ENCRYPTION"); + assert_eq!(kept[0].public_key_hex, entry(7, 4).public_key_hex); + assert_eq!(kept[0].derivation_path, ""); + // stored beside the signing key, they open again + let mut stored = BridgeIdentity::from_dfk1( + "dfk1:testnet:8hJmcHWTsdvkHyCrk4UgjbyugDAmE7QfuCTQXpXAc7nB:5:FAKE-wif", + ) + .unwrap(); + stored.identity_keys.extend(kept); + let back = + BridgeIdentity::from_source_text(stored.to_json_with_secrets().expose()).unwrap(); + let again = EncryptionKeys::held(&back, &chain, "CORE", &net); + assert_eq!(again.sender().map(|(id, _)| id), Some(4)); + assert!(back.master_key().is_none()); + assert_eq!(back.doc_op_key().unwrap().id, 5); + } + #[test] fn recipient_is_the_highest_enabled_encryption_key() { let k = |id, disabled, purpose: &str| IdentityKeyInfo { diff --git a/crates/forge-core/src/keystore.rs b/crates/forge-core/src/keystore.rs index dfe0c2520..655677578 100644 --- a/crates/forge-core/src/keystore.rs +++ b/crates/forge-core/src/keystore.rs @@ -649,6 +649,32 @@ pub fn create_private_file(path: &Path, bytes: &[u8]) -> Result<()> { f.sync_all().map_err(io) } +/// E303 for the sealed key file `shown` that did not open with the passphrase given (from the +/// variable `via`, or typed), naming the file (QW2-022: it was an E204 that named neither of +/// two sealed files). A malformed file keeps `err`'s own message. +fn wrong_passphrase(shown: &str, via: Option<&str>, err: &Error) -> Error { + let Error::Config(msg) = err else { + return Error::Config(err.to_string()); + }; + if !msg.contains("wrong passphrase") { + return Error::Config(format!("{shown}: {msg}")); + } + let given = via.map_or_else(|| "the passphrase typed".to_string(), str::to_string); + crate::user_error::UserError::new( + crate::user_error::codes::IDENTITY_UNREADABLE, + format!("wrong passphrase for {shown}"), + ) + .cause(format!( + "{given} does not open this sealed file (or the file was modified)" + )) + .fix("each sealed file keeps its own passphrase: in a terminal each is asked for") + .fix( + "in scripts, DASH_FORGE_PASSPHRASE opens your key and DASH_FORGE_RUNNER_PASSPHRASE \ + the --runner file of `dg ci runner new`", + ) + .into() +} + /// Security levels acceptable for signing a document create/delete, in preference /// order. Document ops accept HIGH (spike S0.7); CRITICAL also works and is the /// fallback when a HIGH key is absent. @@ -680,6 +706,18 @@ impl BridgeIdentity { /// passphrase once). [`Self::from_source_text`] parses it; `dg` also hands it to /// `git-remote-dash` ([`crate::key_handoff`]) so the helper never asks again. pub fn unlock_source(path: impl AsRef) -> Result { + Self::unlock_source_with(path, &[crate::sealed::PASSPHRASE_ENV]) + } + + /// [`Self::load_from_file`], a sealed file's passphrase read from the first of + /// `passphrase_envs` that is set (else asked for): a second sealed file in one command + /// keeps its own passphrase (QW2-022, `dg ci runner new --runner`). + pub fn load_from_file_with(path: impl AsRef, passphrase_envs: &[&str]) -> Result { + Self::from_source_text(Self::unlock_source_with(path, passphrase_envs)?.expose()) + } + + /// [`Self::unlock_source`] with [`Self::load_from_file_with`]'s passphrase variables. + pub fn unlock_source_with(path: impl AsRef, passphrase_envs: &[&str]) -> Result { let path = path.as_ref(); if let Some(inline) = path.to_str().filter(|s| s.starts_with(DFK1_PREFIX)) { // Refused here, with the format's own message, rather than later. @@ -713,8 +751,12 @@ impl BridgeIdentity { .map_err(|e| Error::Io(format!("reading identity file {shown}: {e}")))?, ); if crate::sealed::is_sealed(&raw) { - let pass = crate::sealed::passphrase(&shown, false)?; - let plain = crate::sealed::open(&raw, pass.expose())?; + let pass = crate::sealed::passphrase_from(passphrase_envs, &shown, false)?; + let via = passphrase_envs + .iter() + .find(|e| std::env::var_os(e).is_some_and(|v| !v.is_empty())); + let plain = crate::sealed::open(&raw, pass.expose()) + .map_err(|e| wrong_passphrase(&shown, via.copied(), &e))?; let text = std::str::from_utf8(&plain) .map_err(|_| Error::Io("the sealed identity file does not hold text".into()))?; return Ok(Secret::new(text)); @@ -953,6 +995,41 @@ mod tests { } }"#; + /// QW2-022: a sealed file that does not open is E303 naming the file and where the + /// passphrase came from (it was an E204 naming neither), and the first variable given wins. + #[test] + fn a_wrong_passphrase_names_the_file_and_the_variable() { + const ENV: &str = "DASH_FORGE_TEST_QW2_022_PASSPHRASE"; + const OTHER: &str = "DASH_FORGE_TEST_QW2_022_UNSET"; + let t = tempfile::tempdir().unwrap(); + let p = t.path().join("runner.json"); + std::fs::write( + &p, + crate::sealed::seal(FIXTURE.as_bytes(), "correct horse battery").unwrap(), + ) + .unwrap(); + std::env::set_var(ENV, "not the passphrase"); + let err = BridgeIdentity::unlock_source_with(&p, &[OTHER, ENV]).unwrap_err(); + std::env::set_var(ENV, "correct horse battery"); + let opened = BridgeIdentity::load_from_file_with(&p, &[OTHER, ENV]); + std::env::remove_var(ENV); + let crate::Error::User(u) = err else { + panic!("expected a phrased error, got {err}") + }; + assert_eq!(u.code, "E303"); + assert!(u.message.contains("runner.json"), "{}", u.message); + assert!( + u.cause.as_deref().unwrap_or("").contains(ENV), + "{:?}", + u.cause + ); + assert!(u + .fix + .iter() + .any(|f| f.contains("DASH_FORGE_RUNNER_PASSPHRASE"))); + assert_eq!(opened.unwrap().network, "testnet"); + } + #[test] fn parses_bridge_fixture() { let id = BridgeIdentity::from_json(FIXTURE).expect("fixture should parse"); diff --git a/crates/forge-core/src/sealed.rs b/crates/forge-core/src/sealed.rs index 7cbaff279..68832d3d2 100644 --- a/crates/forge-core/src/sealed.rs +++ b/crates/forge-core/src/sealed.rs @@ -33,6 +33,10 @@ use crate::keystore::Secret; /// Environment variable a passphrase is read from before prompting. pub const PASSPHRASE_ENV: &str = "DASH_FORGE_PASSPHRASE"; +/// The passphrase of `dg ci runner new --runner ` when that file is sealed with another +/// passphrase than your own key (QW2-022); [`PASSPHRASE_ENV`] when unset. +pub const RUNNER_PASSPHRASE_ENV: &str = "DASH_FORGE_RUNNER_PASSPHRASE"; + /// Set by a program that must never read from the terminal (the importer, `dg --json`): a /// sealed file then needs [`PASSPHRASE_ENV`], and no prompt appears. `GIT_TERMINAL_PROMPT=0` /// has the same effect, so the helper does not ask when git was told not to. @@ -218,22 +222,32 @@ pub fn open(raw: &str, passphrase: &str) -> Result>> { /// The passphrase for `what`: [`PASSPHRASE_ENV`] when set, else a hidden prompt on the /// terminal. `confirm` asks twice (for a new file) and enforces [`MIN_PASSPHRASE_LEN`]. pub fn passphrase(what: &str, confirm: bool) -> Result { - if let Some(p) = std::env::var_os(PASSPHRASE_ENV).filter(|v| !v.is_empty()) { - let p = p - .into_string() - .map_err(|_| Error::Config(format!("{PASSPHRASE_ENV} is not UTF-8")))?; - return Ok(Secret::new(p)); + passphrase_from(&[PASSPHRASE_ENV], what, confirm) +} + +/// [`passphrase`], reading the first of `envs` that is set before prompting (a second sealed +/// file in one command, with its own passphrase: `DASH_FORGE_RUNNER_PASSPHRASE`, then +/// [`PASSPHRASE_ENV`]). Messages name the first. +pub fn passphrase_from(envs: &[&str], what: &str, confirm: bool) -> Result { + let first = envs.first().copied().unwrap_or(PASSPHRASE_ENV); + for env in envs { + if let Some(p) = std::env::var_os(env).filter(|v| !v.is_empty()) { + let p = p + .into_string() + .map_err(|_| Error::Config(format!("{env} is not UTF-8")))?; + return Ok(Secret::new(p)); + } } if !prompts_allowed() { return Err(Error::Config(format!( - "{what} needs a passphrase and this command does not prompt; set {PASSPHRASE_ENV}" + "{what} needs a passphrase and this command does not prompt; set {first}" ))); } let prompt = |label: &str| { rpassword::prompt_password(label).map_err(|e| { Error::Config(format!( "{what} needs a passphrase and there is no terminal to ask on ({e}); set \ - {PASSPHRASE_ENV}" + {first}" )) }) }; diff --git a/crates/forge-core/src/user_error.rs b/crates/forge-core/src/user_error.rs index 7342e9aaa..29cf6314f 100644 --- a/crates/forge-core/src/user_error.rs +++ b/crates/forge-core/src/user_error.rs @@ -765,10 +765,11 @@ fn not_permitted(ctx: &ErrorContext<'_>, action: &str, reason: &str, needs: &str } } -/// How a member stores a key source that can open private repositories: the limited key -/// `dg auth login` and `dg auth new` store is a signing key only, so the full identity is kept -/// instead, from its file or from the recovery words (QW-040). -pub const FIX_FULL_KEY_LOGIN: &str = "`dg auth login --full-key `, or `dg auth login --mnemonic --full-key` with your 12 recovery words"; +/// How a member stores a key source that can open private repositories: `dg auth login` +/// keeps the identity's encryption key beside the limited signing key (QW2-004), from its file +/// or from the recovery words (QW-040). A key stored by an older `dg`, or with +/// `--signing-only`, is a signing key only: signing in again fixes it. +pub const FIX_FULL_KEY_LOGIN: &str = "`dg auth login ` again, or `dg auth login --mnemonic` with your 12 recovery words: it stores a limited key with your encryption key beside it (never the master key)"; /// The E601 way in: the owner's add, and before it, for someone not a member yet, their own /// consent (`member_consent`: a `member` document naming the add is refused without it, E604; @@ -2783,8 +2784,9 @@ mod tests { u.fix ); let u = private_needs_identity("alice/secret"); - assert!(u.fix[0].contains("--full-key"), "{:?}", u.fix); - assert!(u.fix[0].contains("--mnemonic --full-key"), "{:?}", u.fix); + // QW2-004: a limited key with the encryption key, not the master key + assert!(u.fix[0].contains("dg auth login --mnemonic"), "{:?}", u.fix); + assert!(!u.fix[0].contains("--full-key"), "{:?}", u.fix); } #[test] diff --git a/crates/git-remote-dash/src/helper.rs b/crates/git-remote-dash/src/helper.rs index 4d3e7b4e9..d6decedc0 100644 --- a/crates/git-remote-dash/src/helper.rs +++ b/crates/git-remote-dash/src/helper.rs @@ -2904,7 +2904,7 @@ async fn load_signer( format!("{why}; DASH_FORGE_KEY is not set and no default identity is recorded") }; if repo.visibility == forge_core::rules::v2::Visibility::Private { - // A limited key (what `dg auth login ` stores) cannot open it: E306 next. + // Only a key source with the encryption key opens it (`dg auth login`). return Err(UserError::new(codes::NO_IDENTITY, "no identity configured") .cause(why) .fix(format!( diff --git a/docs/errors.md b/docs/errors.md index 8b7112063..b3eb98ff9 100644 --- a/docs/errors.md +++ b/docs/errors.md @@ -131,7 +131,7 @@ Fix: none within the private repository in this release. The label definitions ( Fix: `dg auth new` creates an identity and stores a limited key for this computer; `dg auth login ` (or `dg auth login --mnemonic`) signs in with an existing one. For a single command pass `--identity `, or set `DASH_FORGE_KEY` to a file, a `keychain:dash-forge//` entry, or a `dfk1:` key (this is also how `git-remote-dash` finds the key; without it the helper uses the default `dg auth` recorded, then `~/.config/dash-forge/identities/.identity.json`). -A private repository needs more than a signing key: its content is encrypted to each member's `ENCRYPTION` key, which the limited key `dg auth login ` and `dg auth new` store does not hold (that would be [E306](#e306) next). For one, sign in with `dg auth login --full-key `, or `dg auth login --mnemonic --full-key` with the 12 recovery words. +A private repository needs more than a signing key: its content is encrypted to each member's `ENCRYPTION` key. `dg auth login `, `dg auth login --mnemonic` and `dg auth new` store it beside the limited signing key (never the master key), unless `--signing-only`; a key stored by an older `dg` lacks it (that would be [E306](#e306) next): sign in again. ## E302 @@ -143,7 +143,7 @@ Fix: pass the identity file with `--master `, or type the recovery words w **Identity unreadable.** The identity file or stored key is missing, unreadable, not a bridge-format identity export or `dfk1:` key, or a sealed key file could not be opened (wrong passphrase). -Fix: `dg auth status` shows which key source is in use. Sign in again with `dg auth login ` or `dg auth login --mnemonic`. For a sealed file, set `DASH_FORGE_PASSPHRASE` or type the passphrase when asked. +Fix: `dg auth status` shows which key source is in use. Sign in again with `dg auth login ` or `dg auth login --mnemonic`. For a sealed file, set `DASH_FORGE_PASSPHRASE` or type the passphrase when asked. A wrong passphrase names the file and where the passphrase came from. Each sealed file keeps its own passphrase: `dg ci runner new --runner ` reads the runner file's from `DASH_FORGE_RUNNER_PASSPHRASE` (else `DASH_FORGE_PASSPHRASE`), so a script can open your key and the runner's when they differ. Reads do not open the key: `dg auth status`, `dg auth balance`, and `dg storage status` / `dg cost audit` of a public repository work with a sealed key and no terminal (the status says the key itself was not checked). @@ -174,10 +174,10 @@ Fix: register a fresh one with your master key (used once): `dg auth login ` has no encryption key" (`dg collab add` to a private repository): the member you named has no enabled `ENCRYPTION` key on their identity. -Fix: for the first, store a key source that holds it: `dg auth login --full-key ` (a passphrase-sealed file), or `dg auth login --mnemonic --full-key` with the 12 recovery words if you have no identity file (a `dg auth new` identity). For one command, point `DASH_FORGE_KEY` at the identity file. If the identity has no ENCRYPTION key at all, `dg auth keys add --encryption` adds one, derived from the recovery words (one identity update signed by the master key). A member you are adding does this themselves, or uses Settings → Keys → Enable private repos in the web app. See [identity and keys](guides/identity-and-keys.md#encryption-key-private-repositories). +Fix: for the first, sign in again: `dg auth login `, or `dg auth login --mnemonic` with the 12 recovery words if you have no identity file (a `dg auth new` identity). It registers a new limited key and stores your encryption key beside it; the master key is used once and not stored. For one command, point `DASH_FORGE_KEY` at the identity file. If the identity has no ENCRYPTION key at all, `dg auth keys add --encryption` adds one, derived from the recovery words (one identity update signed by the master key). A member you are adding does this themselves, or uses Settings → Keys → Enable private repos in the web app. See [identity and keys](guides/identity-and-keys.md#encryption-key-private-repositories). ## E307 diff --git a/docs/guides/ci.md b/docs/guides/ci.md index 81dafe09a..896c55432 100644 --- a/docs/guides/ci.md +++ b/docs/guides/ci.md @@ -36,6 +36,10 @@ The key is written to `runner.dfk1` (0600, unencrypted) *before* it is registere `dg auth export --format dfk1 --reveal-secrets -o -` prints this computer's limited key on stdout, for piping straight into a secret store (`| gh secret set DASH_FORGE_KEY`). That key can sign any Forge document within its budget; it is not a runner key, so use `dg ci runner new` for check runs. It is refused with `--json` and when a CI variable is set. Never run it where stdout is a log. +In a terminal, a passphrase-sealed key and a sealed `runner.json` are each asked for. In a script, `DASH_FORGE_PASSPHRASE` opens your key and `DASH_FORGE_RUNNER_PASSPHRASE` opens `runner.json` (it falls back to `DASH_FORGE_PASSPHRASE`); a wrong one is [`E303`](../errors.md#e303) naming the file. + +`dg auth status` and `dg doctor` with the runner key describe it as bound to `checkRun` documents only (a CI runner key), with its budget and expiry. + Other commands: | Command | Does | diff --git a/docs/guides/collaborating.md b/docs/guides/collaborating.md index f54deea57..54fda1526 100644 --- a/docs/guides/collaborating.md +++ b/docs/guides/collaborating.md @@ -119,7 +119,7 @@ Leave the description empty if the project's purpose is itself sensitive. **Repairs.** A maintainer's `dg` and `git push` check the key on every visit: if a non-member still holds the current key (two maintainers removed members at the same time), or a member has no wrap to their current encryption key (they replaced it, or an add was interrupted), `dg repo keys repair` fixes it. The key is re-read before every write, so nothing is ever written under a key that was rotated away. -**Cloning.** `git clone dash:///` works as for a public repository when your key source holds your encryption key: the identity file (`DASH_FORGE_KEY`) or `dg auth login --full-key`, not the limited key a plain `dg auth login` stores ([identity and keys](identity-and-keys.md#encryption-key-private-repositories)). A non-member gets [`E307`](../errors.md#e307); an identity without an encryption key gets [`E306`](../errors.md#e306). +**Cloning.** `git clone dash:///` works as for a public repository when your key source holds your encryption key: what `dg auth login` and `dg auth new` store (the limited key with your encryption key beside it), or the identity file (`DASH_FORGE_KEY`); not a key stored with `--signing-only` or by an older `dg` ([identity and keys](identity-and-keys.md#encryption-key-private-repositories)). A non-member gets [`E307`](../errors.md#e307); an identity without an encryption key gets [`E306`](../errors.md#e306). **No recovery.** If every member loses their encryption key (every copy of every identity file and mnemonic), the contents cannot be decrypted by anyone. diff --git a/docs/guides/identity-and-keys.md b/docs/guides/identity-and-keys.md index 3dce62551..a4fb40527 100644 --- a/docs/guides/identity-and-keys.md +++ b/docs/guides/identity-and-keys.md @@ -60,11 +60,11 @@ Do this once: 1. Write the 12 words on paper, in order. Keep two copies in separate places. 2. Keep the words offline. Do not put them in a password manager that syncs, in a note-taking app, or in a screenshot. -3. Treat the identity file (`dash-identity-.json`) like the words. It contains them, plus every private key. Keep it offline once you have signed in: `dg auth login` stores only a limited key. If you keep it on disk, keep it `chmod 600`; `dg doctor` warns when an identity file it uses is readable by other users, and `dg doctor --fix` tightens it. +3. Treat the identity file (`dash-identity-.json`) like the words. It contains them, plus every private key. Keep it offline once you have signed in: `dg auth login` stores only a limited key and the encryption key. If you keep it on disk, keep it `chmod 600`; `dg doctor` warns when an identity file it uses is readable by other users, and `dg doctor --fix` tightens it. If you lose a laptop but still have the words or a backup of the file, nothing is lost. Your repositories, issues and history are on Platform, not on your laptop: -1. On the new machine run `dg auth login --mnemonic` (type the 12 words) or `dg auth login ` with your backup. It registers a new limited key and stores only that. +1. On the new machine run `dg auth login --mnemonic` (type the 12 words) or `dg auth login ` with your backup. It registers a new limited key and stores only that, with the encryption key beside it. 2. Disable the lost machine's key: `dg auth keys list` shows it, `dg auth keys disable ` disables it (or pass `--replace ` to the login above to do both in one update). A limited key can only spend its remaining budget, and only on Forge, until then. 3. In a browser, **Sign in → Import an identity file or recovery phrase** registers a fresh limited key for that browser; the words alone are enough. @@ -90,7 +90,7 @@ A key *source* (`--identity`, `DASH_FORGE_KEY`, the recorded default) is any of: Things to know: -- On macOS `dg` reads and writes the keychain through Apple's `/usr/bin/security`, so `dg`, `git-remote-dash` and upgraded copies of either read the entry without an access dialog. Any program running as you can ask `security` for it without a prompt: the keychain protects entries at rest and from other users. What `dg` keeps there is limited identity keys (a budget, an expiry, Forge contracts only) and the storage credentials `dg storage add` is given, so scope those to the one bucket. A full identity (`dg auth login --full-key`: master key and recovery words) never goes there; it is always a passphrase-sealed file. The GitHub CLI stores its token the same way. +- On macOS `dg` reads and writes the keychain through Apple's `/usr/bin/security`, so `dg`, `git-remote-dash` and upgraded copies of either read the entry without an access dialog. Any program running as you can ask `security` for it without a prompt: the keychain protects entries at rest and from other users. What `dg` keeps there is limited identity keys (a budget, an expiry, Forge contracts only), with your identity's encryption key beside them (it reads your private repositories; `--signing-only` leaves it out), and the storage credentials `dg storage add` is given, so scope those to the one bucket. A full identity (`dg auth login --full-key`: master key and recovery words) never goes there; it is always a passphrase-sealed file. The GitHub CLI stores its token the same way. - Over SSH there is no keychain dialog to answer; use a sealed key file there (`DASH_FORGE_NO_KEYCHAIN=1 dg auth login …`). - `--insecure-plaintext` stores the key unencrypted (0600) where there is no keychain and no way to type a passphrase. Every later use warns. - In the web app, the key never leaves that browser, but any script running on the page can use it while it is unlocked ([details](#the-browser-vault-and-its-limits)). Lock or sign out on shared machines. @@ -138,7 +138,7 @@ If the **MASTER** key or the 12 words leak, rotating does not help: whoever has A private repository encrypts its content under a repository key, and each member gets that key wrapped (encrypted) to their identity's **ENCRYPTION** key. Without one, nobody can add you to a private repository and you cannot create one. Identities from `dg auth new`, the bridge and the web app carry key 4 for this. -**Using it from the CLI.** Reading or writing a private repository needs the ENCRYPTION key's private half, and the limited key `dg auth login` stores is a signing key only. For private repositories, point `DASH_FORGE_KEY` at your identity file, or sign in with `dg auth login --full-key ` (kept in a passphrase-sealed file, never the keychain). Without it, private-repo commands stop with [`E306`](../errors.md#e306). +**Using it from the CLI.** Reading or writing a private repository needs the ENCRYPTION key's private half. `dg auth login` (from the identity file or the recovery words) and `dg auth new` store it beside the limited signing key, where the limited key is kept (the keychain, or a passphrase-sealed file), as the web app's "Enable private repos" does: private repositories work with no master key on disk. `dg auth status` shows it (`Private:`). `--signing-only` stores the signing key alone; a key stored by an older `dg` is one too, and signing in again adds it. Without it, private-repo commands stop with [`E306`](../errors.md#e306); `DASH_FORGE_KEY=` works for one command. **An identity without one** can add it: @@ -185,7 +185,7 @@ From the terminal: ```sh dg auth new [--amount 0.05] [--name alice] # 12 words → deposit QR → identity + a limited key in the keychain -dg auth login | --mnemonic # import once; registers a limited key and stores only that +dg auth login | --mnemonic # import once; registers a limited key and stores it with the encryption key dg auth status # identity, name, key, budget left, expiry, balance, where it is stored dg auth export --new-key --format dfk1 --reveal-secrets -o runner.dfk1 # a key for CI dg auth name register