diff --git a/crates/dg/src/auth/keys.rs b/crates/dg/src/auth/keys.rs
index e1d00dd21..08abd7123 100644
--- a/crates/dg/src/auth/keys.rs
+++ b/crates/dg/src/auth/keys.rs
@@ -1,4 +1,4 @@
-//! `dg auth keys list | add | disable` (ux-dx-spec §2.4, §2.5, §9).
+//! `dg auth keys list | add | disable | rotate` (ux-dx-spec §2.4, §2.5, §9).
use std::path::PathBuf;
@@ -24,7 +24,9 @@ pub enum KeysCommand {
/// A limited key is what this computer then signs with (default: 0.25 DASH / 180
/// days, bound to dash-forge; `--replace ` disables the old one in the same update), or
/// with --encryption the ENCRYPTION key private repositories need. Needs the master key once.
- /// For a key to hand to CI use `dg auth export --new-key`.
+ /// For a key to hand to CI use `dg auth export --new-key`. With `--for-browser `
+ /// the key is for a browser tab instead: dg prints it sealed to that tab, so the recovery
+ /// phrase never goes into a web page.
Add(AddArgs),
/// Disable a key on Platform. Needs the master key once.
Disable {
@@ -37,6 +39,25 @@ pub enum KeysCommand {
#[arg(long)]
force: bool,
},
+ /// Replace the encryption key after a lost device or a leak: add a new one from the recovery
+ /// phrase, move every private repository you maintain to it, then disable the old one.
+ ///
+ /// Repositories you don't maintain are listed, for a maintainer to move. Run it again to
+ /// continue after a failure. To replace a limited key, use `dg auth keys add --replace `.
+ Rotate {
+ /// Replace the ENCRYPTION key (the only key this command rotates).
+ #[arg(long, required = true)]
+ encryption: bool,
+ /// Keep the old key enabled (it still opens what was sealed for it).
+ #[arg(long)]
+ keep_old: bool,
+ /// The identity file with the master key and the recovery phrase (else you are asked for
+ /// the phrase).
+ #[arg(long, value_name = "FILE")]
+ master: Option,
+ #[command(flatten)]
+ storage: StorageArgs,
+ },
}
impl KeysCommand {
@@ -46,6 +67,7 @@ impl KeysCommand {
KeysCommand::List => "could not list keys",
KeysCommand::Add(_) => "key not added",
KeysCommand::Disable { .. } => "key not disabled",
+ KeysCommand::Rotate { .. } => "encryption key not replaced",
}
}
}
@@ -54,13 +76,27 @@ impl KeysCommand {
#[derive(Debug, clap::Args)]
pub struct AddArgs {
/// Add an ENCRYPTION key (for private repositories) instead of a limited key.
- #[arg(long, conflicts_with_all = ["budget", "expires", "replace"])]
+ #[arg(long, conflicts_with_all = ["budget", "expires", "replace", "for_browser"])]
pub encryption: bool,
+ /// Register a limited key for a browser tab and print it sealed to that tab: paste the
+ /// `dfkr1:` request the browser shows (Sign in → Use dg, or Renew). This computer keeps
+ /// signing with its own key. Default limits are the browser's: 0.05 DASH for 90 days.
+ #[arg(long, value_name = "REQUEST", conflicts_with = "keep_current")]
+ pub for_browser: Option,
+ /// With --for-browser: also hand over the identity's encryption key, so the browser opens
+ /// private repositories.
+ #[arg(long, requires = "for_browser")]
+ pub with_encryption_key: bool,
+ /// With --for-browser: the identity the browser asked a key for. dg refuses, before anything
+ /// is signed, to make the key for another identity.
+ #[arg(long, value_name = "IDENTITY_ID", requires = "for_browser")]
+ pub for_identity: Option,
/// Bound to the `dash-forge` contract group (the only binding dg makes; kept for the
/// spec's command line).
#[arg(long, value_name = "GROUP", default_value = "dash-forge", value_parser = ["dash-forge"])]
pub bound: String,
- /// Disable this limited key in the same update (default: the one this computer signs with).
+ /// Disable this limited key in the same update (default: the one this computer signs with;
+ /// none with --for-browser).
#[arg(long, value_name = "KEY_ID")]
pub replace: Option,
/// Keep the key this computer signs with now valid on Platform (it is no longer stored here).
@@ -83,6 +119,12 @@ pub async fn run(ctx: &Ctx, cmd: &KeysCommand) -> Result<()> {
KeysCommand::Disable { id, master, force } => {
disable(ctx, *id, master.as_deref(), *force).await
}
+ KeysCommand::Rotate {
+ encryption: _,
+ keep_old,
+ master,
+ storage,
+ } => super::rekey::rotate_encryption(ctx, master.as_deref(), storage, *keep_old).await,
}
}
@@ -240,7 +282,283 @@ async fn add_encryption(
Ok(())
}
+/// The browser key defaults (`forge-web/lib/auth/limited-key.ts` `BROWSER_KEY_DEFAULTS`).
+const BROWSER_KEY_BUDGET_DASH: f64 = 0.05;
+const BROWSER_KEY_DAYS: u64 = 90;
+
+/// The flag that selects `network`, a network key (`testnet`, `mainnet`, `devnet-`).
+fn network_flag(network: &str) -> String {
+ match network.strip_prefix("devnet-") {
+ Some(name) => format!("--devnet-name {name}"),
+ None => format!("--network {network}"),
+ }
+}
+
+/// The browser's `dfkr1:` request, refused when it is not one or is for another network.
+fn browser_request(ctx: &Ctx, text: &str) -> Result {
+ let request = forge_core::browser_key::parse_request(text).map_err(|e| {
+ UserError::new(codes::USAGE, "that is not a browser key request")
+ .cause(e.to_string())
+ .fix("copy the whole command the browser shows, including the dfkr1:… request")
+ })?;
+ let network = ctx.network_label();
+ if request.network != network {
+ return Err(
+ UserError::new(codes::USAGE, "the browser is on another network")
+ .cause(format!(
+ "the request is from a site on {}, and dg is on {network}",
+ request.network
+ ))
+ .fix(format!(
+ "run it again with {}",
+ network_flag(&request.network)
+ ))
+ .note("nothing was sent")
+ .into(),
+ );
+ }
+ Ok(request)
+}
+
+/// The encryption key `--with-encryption-key` hands over: the highest-id one `sources` (the
+/// master source and the key dg signs with) open.
+/// Checked before anything is paid for, so a key dg cannot hand over never leaves the browser
+/// with a signing key and a promise.
+fn handover_encryption_key(
+ ctx: &Ctx,
+ identity: &forge_core::platform::LoadedIdentity,
+ sources: &[&forge_core::keystore::BridgeIdentity],
+) -> Result {
+ let storage = super::StorageArgs {
+ insecure_plaintext: false,
+ signing_only: false,
+ };
+ let key = super::encryption_to_store(ctx, &storage, identity, sources)
+ .into_iter()
+ .max_by_key(|k| k.id)
+ .ok_or_else(|| {
+ UserError::new(codes::KEY_CANNOT_SIGN, "no encryption key to hand over")
+ .cause("this identity has no encryption key that the recovery words or the --master file open")
+ .fix("run it without --with-encryption-key, or add one first: `dg auth keys add --encryption`")
+ .note("nothing was sent")
+ })?;
+ Ok(forge_core::browser_key::EncryptionKey {
+ key_id: key.id,
+ private_key_hex: key.private_key_hex.expose().to_string(),
+ })
+}
+
+/// The longest a browser key may live (the web app's longest choice, TS-06).
+const BROWSER_KEY_MAX_DAYS: u64 = 365;
+
+/// The master identity for `--for-browser`: `--master`, else the identity dg is signed in as,
+/// else the recovery words (only when dg is not signed in at all: a key file that fails to
+/// open is an error, not a reason to ask for the words). Refused when it is not `for_identity`.
+async fn browser_master(
+ ctx: &Ctx,
+ client: &forge_core::platform::PlatformClient,
+ args: &AddArgs,
+) -> Result<(
+ forge_core::keystore::BridgeIdentity,
+ Option,
+)> {
+ let current = match ctx.identity_path {
+ Some(_) => Some(ctx.load_bridge()?),
+ None => None,
+ };
+ let current_id = current.as_ref().map(|b| b.identity_id.clone());
+ let master = match (¤t_id, &args.master) {
+ (None, None) => {
+ eprintln!("{}", super::MASTER_PROMPT);
+ let words = super::read_mnemonic()?;
+ super::identity_from_words(ctx, client, &words).await?
+ }
+ _ => master_identity(
+ ctx,
+ args.master.as_deref(),
+ current_id.as_deref().unwrap_or(""),
+ )?,
+ };
+ if let Some(want) = &args.for_identity {
+ if *want != master.identity_id {
+ return Err(
+ UserError::new(codes::KEY_CANNOT_SIGN, "that is a different identity")
+ .cause(format!(
+ "the browser asked for a key of {want}, and dg would sign for {}",
+ master.identity_id
+ ))
+ .fix(format!("pass --master with the identity file of {want}"))
+ .note("nothing was sent")
+ .into(),
+ );
+ }
+ }
+ Ok((master, current))
+}
+
+/// The key a reply carries, from the `dfk1:` text `register_limited_key` hands its `persist`.
+fn handoff_payload(
+ network: &str,
+ dfk1: &forge_core::keystore::Secret,
+ replaced: Option,
+ encryption: Option<&forge_core::browser_key::EncryptionKey>,
+) -> Result {
+ let bridge = forge_core::keystore::BridgeIdentity::from_dfk1(dfk1.expose())?;
+ let key = bridge.doc_op_key()?;
+ Ok(forge_core::browser_key::Payload {
+ v: 1,
+ network: network.to_string(),
+ identity_id: bridge.identity_id.clone(),
+ key_id: key.id,
+ wif: key.private_key_wif.expose().to_string(),
+ replaced_key_id: replaced,
+ encryption_key: encryption.map(|e| forge_core::browser_key::EncryptionKey {
+ key_id: e.key_id,
+ private_key_hex: e.private_key_hex.clone(),
+ }),
+ })
+}
+
+/// `dg auth keys add --for-browser ` (TS-06): register a limited key for a browser tab
+/// and print it sealed to the tab's one-time key (`forge_core::browser_key`). Nothing is stored
+/// here; this computer's own key is untouched unless `--replace` names it.
+async fn add_for_browser(ctx: &Ctx, args: &AddArgs, request: &str) -> Result<()> {
+ let request = browser_request(ctx, request)?;
+ let network = ctx.network_label();
+ let client = ctx.connect().await?;
+ let (master, current) = browser_master(ctx, &client, args).await?;
+ let identity = client.fetch_signer(&master).await?;
+ let encryption = if args.with_encryption_key {
+ let sources: Vec<_> = std::iter::once(&master).chain(current.as_ref()).collect();
+ Some(handover_encryption_key(ctx, &identity, &sources)?)
+ } else {
+ None
+ };
+ let spec = key_spec(ctx, &args.limits, BROWSER_KEY_BUDGET_DASH, BROWSER_KEY_DAYS)?;
+ if spec.expires_at_ms > super::expiry_ms(BROWSER_KEY_MAX_DAYS) {
+ return Err(crate::errors::usage(format!(
+ "a browser key lives at most {BROWSER_KEY_MAX_DAYS} days; pass --expires 365d or less"
+ )));
+ }
+ let checked = super::check_group(ctx, &client, &spec.group, args.limits.strict_group()).await?;
+ super::explain_new_key(ctx, &master.identity_id, &spec, "for a browser", &checked);
+ explain_handover(ctx, args.replace, encryption.as_ref());
+ ctx.confirm_or_cancel("Add the key?")?;
+ // The reply is sealed before anything is sent (as `register_limited_key` stores a key before
+ // it registers it), and again if the key lands under another id.
+ let seal = |dfk1: &forge_core::keystore::Secret| -> Result<(u32, String)> {
+ let payload = handoff_payload(&network, dfk1, args.replace, encryption.as_ref())?;
+ Ok((
+ payload.key_id,
+ forge_core::browser_key::seal(&request, &payload)?,
+ ))
+ };
+ let mut sealed: Option<(u32, String, forge_core::keystore::Secret)> = None;
+ let registered = super::register_limited_key(
+ ctx,
+ &client,
+ &master,
+ &spec,
+ args.replace,
+ &checked,
+ &mut |t| {
+ let (id, reply) = seal(t)?;
+ sealed = Some((id, reply, t.clone()));
+ Ok(())
+ },
+ )
+ .await;
+ let (id, reply, unconfirmed) = match (registered, sealed) {
+ (Ok(id), Some((sealed_id, reply, _))) if id == sealed_id => (id, reply, None),
+ (Ok(id), _) => {
+ anyhow::bail!("internal error: key #{id} registered, but its reply was not sealed")
+ }
+ // The update errored but may have landed (a broadcast that timed out, a node behind):
+ // a key that is on chain is handed over, or nobody would hold it.
+ (Err(e), Some((_, _, dfk1))) => {
+ let Some(landed) = landed_key(ctx, &client, &network, &dfk1).await else {
+ return Err(e);
+ };
+ let (id, reply) = seal(&landed)?;
+ (id, reply, Some(format!("{e:#}")))
+ }
+ (Err(e), None) => return Err(e),
+ };
+ ctx.emit(
+ json!({
+ "status": "added",
+ "keyId": id,
+ "budgetCredits": spec.budget_credits,
+ "expiresAt": spec.expires_at_ms,
+ "replacedKeyId": args.replace,
+ "encryptionKeyId": encryption.as_ref().map(|e| e.key_id),
+ "reply": reply,
+ "warning": unconfirmed,
+ }),
+ || {
+ if let Some(why) = &unconfirmed {
+ eprintln!("note: the update reported an error ({why}), but key #{id} is on chain");
+ }
+ eprintln!("✓ limited key #{id} added for the browser");
+ if let Some(old) = args.replace {
+ eprintln!(" key #{old} disabled");
+ }
+ eprintln!(
+ "Paste this line into the browser. It opens only in the tab that asked for it:"
+ );
+ println!("{reply}");
+ },
+ );
+ Ok(())
+}
+
+/// The key in `dfk1` under the id it is live with on chain (a `dfk1:` text again), if it landed.
+async fn landed_key(
+ ctx: &Ctx,
+ client: &forge_core::platform::PlatformClient,
+ network: &str,
+ dfk1: &forge_core::keystore::Secret,
+) -> Option {
+ let bridge = forge_core::keystore::BridgeIdentity::from_dfk1(dfk1.expose()).ok()?;
+ let wif = bridge.doc_op_key().ok()?.private_key_wif.clone();
+ let identity = client.fetch_identity(&bridge.identity_id).await.ok()?;
+ let id = identity.key_id_for(wif.expose(), ctx.network())?;
+ Some(forge_core::keystore::dfk1(
+ network,
+ &bridge.identity_id,
+ id,
+ wif.expose(),
+ ))
+}
+
+/// What else the update does (human mode): the key it disables, the encryption key it hands over.
+fn explain_handover(
+ ctx: &Ctx,
+ replace: Option,
+ encryption: Option<&forge_core::browser_key::EncryptionKey>,
+) {
+ if ctx.json {
+ return;
+ }
+ // Anyone can show a request: a look-alike page could ask for this command too.
+ eprintln!(
+ " run this only for a Forge page you opened yourself: the key can write to Forge as you"
+ );
+ if let Some(old) = replace {
+ eprintln!(" key #{old} is disabled in the same update");
+ }
+ if let Some(e) = encryption {
+ eprintln!(
+ " the browser also gets encryption key #{}: it opens your private repositories",
+ e.key_id
+ );
+ }
+}
+
async fn add(ctx: &Ctx, args: &AddArgs) -> Result<()> {
+ if let Some(request) = &args.for_browser {
+ return add_for_browser(ctx, args, request).await;
+ }
let current = ctx.load_bridge()?;
let client = ctx.connect().await?;
let master = master_identity(ctx, args.master.as_deref(), ¤t.identity_id)?;
@@ -380,3 +698,14 @@ async fn disable(ctx: &Ctx, id: u32, master: Option<&std::path::Path>, force: bo
);
Ok(())
}
+
+#[cfg(test)]
+mod tests {
+ use super::network_flag;
+
+ #[test]
+ fn the_network_flag_matches_the_browser_command() {
+ assert_eq!(network_flag("devnet-sakura"), "--devnet-name sakura");
+ assert_eq!(network_flag("testnet"), "--network testnet");
+ }
+}
diff --git a/crates/dg/src/auth/mod.rs b/crates/dg/src/auth/mod.rs
index 031b78c89..4e6fc990a 100644
--- a/crates/dg/src/auth/mod.rs
+++ b/crates/dg/src/auth/mod.rs
@@ -14,6 +14,7 @@
pub mod group;
mod keys;
mod new;
+mod rekey;
pub mod store;
use std::path::PathBuf;
@@ -297,6 +298,8 @@ pub fn read_mnemonic() -> Result {
.into(),
);
}
+ // The same words before every phrase prompt, here and in the web app (TS-06).
+ eprintln!("{}", forge_core::browser_key::RECOVERY_PHRASE_WARNING);
let words =
rpassword::prompt_password("Recovery words (12, hidden as you type): ").map_err(|e| {
// Ctrl-D or Ctrl-C: the user left, nothing was written (E803), not "no terminal".
@@ -315,7 +318,7 @@ pub fn read_mnemonic() -> Result {
/// What [`master_identity`] says before it asks for the recovery words: a user who signed in
/// with an identity file has no words at hand, and `--master ` takes that file instead
/// (L-34).
-const MASTER_PROMPT: &str =
+pub(crate) const MASTER_PROMPT: &str =
"This needs your master key once. It is used for this one signature and not stored.\n\
Type your 12-word recovery phrase below, or press Ctrl-C and run the command again with \
--master (the file from the bridge, or a `dg auth new --backup-file`).";
@@ -360,7 +363,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/dg/src/auth/rekey.rs b/crates/dg/src/auth/rekey.rs
new file mode 100644
index 000000000..5f4215751
--- /dev/null
+++ b/crates/dg/src/auth/rekey.rs
@@ -0,0 +1,443 @@
+//! `dg auth keys rotate --encryption`: replace the identity's ENCRYPTION key
+//! (`docs/security/private-repos.md` §5.2 "Rekey flow"), for a lost device or a leaked key.
+//!
+//! In order: add a new key at the next key id (derived from the recovery words, master-signed);
+//! rotate every private repository this identity maintains so its new epoch is wrapped to the new
+//! key (§5.5), and check that it was; name the repositories where it is only a member (a
+//! maintainer's repair check moves them, §5.6); then disable every other enabled encryption key.
+//!
+//! Every run adds a fresh key and treats every enabled key as old: a lost device may have held
+//! any of them, an earlier run's new key included. So a run that stopped half way is finished by
+//! running it again, at the price of one more key add.
+
+use std::path::Path;
+
+use anyhow::{Context as _, Result};
+use serde_json::{json, Value};
+
+use forge_core::keyring::{self, EncryptionKeys, PrivateSigner};
+use forge_core::keystore::BridgeIdentity;
+use forge_core::platform::{identity_keys, LoadedIdentity};
+use forge_core::scope::RepoRef;
+use forge_core::user_error::{codes, UserError};
+
+use super::{master_identity, store, StorageArgs};
+use crate::context::Ctx;
+use crate::fmt::{cost_json, cost_line};
+
+/// What happened to one maintained repository.
+enum Outcome {
+ /// Rotated, and its current epoch is wrapped to the new key.
+ Rotated(keyring::Rotation),
+ /// No longer a maintainer there: a maintainer must move it (like a member-only repository).
+ NotMaintainer,
+ /// Not moved to the new key (an error, or the current epoch still opens only with an old
+ /// key): the old keys stay enabled.
+ Failed(String),
+}
+
+/// The rekey as it will run, worked out before anything is signed.
+struct Plan {
+ id: String,
+ old_ids: Vec,
+ new_id: u32,
+ secret: identity_keys::EncryptionSecret,
+ members: keyring::PrivateMemberships,
+ keep_old: bool,
+}
+
+/// What the run did, for the report.
+struct Done<'a> {
+ plan: &'a Plan,
+ outcomes: Vec<(&'a RepoRef, Outcome)>,
+ disabled: Option>,
+ stored: Result, String>,
+}
+
+impl Done<'_> {
+ fn failed(&self) -> bool {
+ self.outcomes
+ .iter()
+ .any(|(_, o)| matches!(o, Outcome::Failed(_)))
+ }
+
+ /// The repositories a maintainer must move: member-only ones, and maintained ones where the
+ /// identity turned out not to be a maintainer any more.
+ fn ask_maintainer(&self) -> Vec<&RepoRef> {
+ self.plan
+ .members
+ .member_only
+ .iter()
+ .chain(
+ self.outcomes
+ .iter()
+ .filter(|(_, o)| matches!(o, Outcome::NotMaintainer))
+ .map(|(r, _)| *r),
+ )
+ .collect()
+ }
+}
+
+pub(super) async fn rotate_encryption(
+ ctx: &Ctx,
+ master_file: Option<&Path>,
+ storage: &StorageArgs,
+ keep_old: bool,
+) -> Result<()> {
+ let forge = ctx
+ .target
+ .v2
+ .clone()
+ .context("Dash Forge is not deployed on this network")?;
+ let current = ctx.load_bridge()?;
+ let client = ctx.connect().await?;
+ let master = master_identity(ctx, master_file, ¤t.identity_id)?;
+ identity_keys::require_master_key(&master)?;
+ let identity = client.fetch_signer(&master).await?;
+ let plan = plan(ctx, &client, &forge, &master, &identity, keep_old).await?;
+ let price = ctx.usd_price();
+ if !ctx.json {
+ print_plan(&plan, price);
+ }
+ ctx.confirm_or_cancel("Replace the key?")?;
+ let before = client.get_balance(&plan.id).await.unwrap_or(0);
+
+ // 1. The new key.
+ let added = identity_keys::add_encryption_key(&client, &identity, &master, &plan.secret)
+ .await
+ .context("adding the new encryption key")?;
+ anyhow::ensure!(
+ added == plan.new_id,
+ "the new encryption key landed as #{added}, not #{}; run this again",
+ plan.new_id
+ );
+ if !ctx.json {
+ println!("✓ added ENCRYPTION key #{added}");
+ }
+
+ // 2. Rotate every repository this identity maintains, signing with the key in use and
+ // holding every encryption key: an old one opens the current epoch, the new one is the
+ // highest enabled key, so the new epoch is wrapped to it (self first).
+ let signing = client.fetch_signer(¤t).await?;
+ let work = holding_every_encryption_key(¤t, &master, &signing, &forge.core, ctx);
+ let signer = PrivateSigner {
+ client: &client,
+ identity: &signing,
+ bridge: &work,
+ };
+ let mut done = Done {
+ plan: &plan,
+ outcomes: Vec::new(),
+ disabled: None,
+ stored: Ok(None),
+ };
+ for repo in &plan.members.maintained {
+ let outcome = rotate_one(&signer, repo, plan.new_id).await;
+ if !ctx.json {
+ print_outcome(repo, &outcome);
+ }
+ done.outcomes.push((repo, outcome));
+ }
+
+ // 3. The old keys: disabled once every maintained repository is on the new key.
+ if !done.failed() && !keep_old && !plan.old_ids.is_empty() {
+ let wif = &master
+ .master_key()
+ .context("no master key")?
+ .private_key_wif;
+ client
+ .update_identity_keys(&plan.id, wif, &[], &plan.old_ids)
+ .await
+ .context("disabling the old encryption key")?;
+ done.disabled = Some(plan.old_ids.clone());
+ }
+
+ // 4. The key this computer stores: its encryption keys now include the new one. Everything
+ // above is on chain already, so a failure here is reported, not raised.
+ done.stored = restore_login(ctx, storage, ¤t, &work).map_err(|e| format!("{e:#}"));
+ let spent = crate::common::spent_since(&client, &plan.id, before).await;
+ ctx.emit(report_json(&done, &cost_json(spent, price)), || {
+ print_done(&done, &cost_line(spent, price));
+ });
+ if done.failed() {
+ return Err(
+ UserError::new(codes::PARTIAL, "not every repository moved to the new key")
+ .cause("the old encryption keys stay enabled, so nothing is lost")
+ .fix("run `dg auth keys rotate --encryption` again: it adds a fresh key and moves every repository to it")
+ .into(),
+ );
+ }
+ Ok(())
+}
+
+/// Which keys go and which comes, and the repositories it touches.
+async fn plan(
+ ctx: &Ctx,
+ client: &forge_core::platform::PlatformClient,
+ forge: &forge_core::network::ForgeIds,
+ master: &BridgeIdentity,
+ identity: &LoadedIdentity,
+ keep_old: bool,
+) -> Result {
+ let id = identity.id();
+ let mut old_ids: Vec = identity
+ .public_keys()
+ .into_iter()
+ .filter(|k| k.is_usable_encryption_key(&forge.core))
+ .map(|k| k.id)
+ .collect();
+ old_ids.sort_unstable();
+ if old_ids.is_empty() {
+ return Err(UserError::new(
+ codes::NO_ENCRYPTION_KEY,
+ "there is no encryption key to replace",
+ )
+ .cause(format!("identity {id} has no enabled ENCRYPTION key"))
+ .fix("add one: `dg auth keys add --encryption`")
+ .into());
+ }
+ if !identity_keys::recorded_keys_match(master, &identity.public_keys()) {
+ return Err(words_needed());
+ }
+ let new_id = identity_keys::next_key_id(identity);
+ let secret = identity_keys::derive_encryption_secret(master, new_id, ctx.network())
+ .ok_or_else(words_needed)?;
+ let members = keyring::private_memberships(client, forge, &id).await?;
+ Ok(Plan {
+ id,
+ old_ids,
+ new_id,
+ secret,
+ members,
+ keep_old,
+ })
+}
+
+fn words_needed() -> anyhow::Error {
+ UserError::new(
+ codes::KEY_CANNOT_SIGN,
+ "the new encryption key cannot be derived from what was given",
+ )
+ .cause("a new key must come from the identity's recovery words, so that they alone recover it; the master key source given does not hold words that reproduce the identity's keys")
+ .fix("pass --master with the recovery words in it")
+ .fix("or sign in with a limited key (`dg auth login`), then run it again and type the words when asked")
+ .note("nothing was sent")
+ .into()
+}
+
+/// `current` (the key this computer signs with) holding, in memory, every encryption key the
+/// master source's words derive for the identity, old and new. What is stored afterwards is
+/// decided by [`restore_login`].
+fn holding_every_encryption_key(
+ current: &BridgeIdentity,
+ master: &BridgeIdentity,
+ identity: &LoadedIdentity,
+ core: &str,
+ ctx: &Ctx,
+) -> BridgeIdentity {
+ let on_chain = identity.public_keys();
+ let mut keys = std::collections::BTreeMap::new();
+ for source in [master, current] {
+ for k in EncryptionKeys::held(source, &on_chain, core, ctx.network())
+ .to_identity_keys(ctx.network())
+ {
+ keys.entry(k.id).or_insert(k);
+ }
+ }
+ let mut work = current.clone();
+ work.identity_keys.retain(|k| k.purpose != "ENCRYPTION");
+ work.identity_keys.extend(keys.into_values());
+ work
+}
+
+/// Rotate `repo`, then check, from a fresh read, that this identity's wrap for the current epoch
+/// went to `new_id`: a resumed epoch can keep an earlier self-wrap to an old key, and another
+/// maintainer's concurrent anchor may have been wrapped before the new key existed.
+async fn rotate_one(signer: &PrivateSigner<'_>, repo: &RepoRef, new_id: u32) -> Outcome {
+ match keyring::rotate(signer, repo, &[]).await {
+ Ok(r) => match signer.keyring(repo).await {
+ Ok(kr) if kr.own_current_wrap_keys().contains(&new_id) => Outcome::Rotated(r),
+ Ok(kr) => Outcome::Failed(format!(
+ "its current key epoch {} is still wrapped to your old key, not #{new_id}",
+ kr.resolution().current_epoch.unwrap_or_default()
+ )),
+ Err(e) => Outcome::Failed(format!("rotated, but reading it back failed: {e}")),
+ },
+ Err(forge_core::Error::NotPermitted { .. }) => Outcome::NotMaintainer,
+ Err(e) => Outcome::Failed(e.to_string()),
+ }
+}
+
+/// Store the key in use again with the new encryption key beside it, in the same place, when it
+/// is dg's own stored limited key (`dg auth login`) and kept encryption keys there. A full
+/// identity is never re-stored (its words derive the new key by themselves), nor a key file of
+/// the user's own, nor a plaintext one (encryption keys are never written in the clear).
+fn restore_login(
+ ctx: &Ctx,
+ storage: &StorageArgs,
+ current: &BridgeIdentity,
+ work: &BridgeIdentity,
+) -> Result> {
+ let Some(path) = ctx.identity_path.as_ref() else {
+ return Ok(None);
+ };
+ let source = path.to_string_lossy();
+ let kept_encryption = current
+ .identity_keys
+ .iter()
+ .any(|k| k.purpose == "ENCRYPTION");
+ if storage.signing_only
+ || storage.insecure_plaintext
+ || !kept_encryption
+ || current.master_key().is_some()
+ {
+ return Ok(None);
+ }
+ let network = ctx.network_label();
+ let Some(mut writer) = store::main_slot_storer(&network, ¤t.identity_id, &source)? else {
+ return Ok(None);
+ };
+ let stored = writer
+ .store(
+ &network,
+ ¤t.identity_id,
+ &work.to_json_with_secrets(),
+ store::Slot::Main,
+ )
+ .context("storing the new encryption key beside the key in use")?;
+ Ok(Some(stored))
+}
+
+fn names(repos: &[&RepoRef]) -> String {
+ repos
+ .iter()
+ .map(|r| r.display())
+ .collect::>()
+ .join(", ")
+}
+
+fn ids(ids: &[u32]) -> String {
+ ids.iter()
+ .map(|i| format!("#{i}"))
+ .collect::>()
+ .join(", ")
+}
+
+fn print_plan(plan: &Plan, price: Option) {
+ let (id, new_id, members) = (&plan.id, plan.new_id, &plan.members);
+ let maintained: Vec<&RepoRef> = members.maintained.iter().collect();
+ let member_only: Vec<&RepoRef> = members.member_only.iter().collect();
+ let estimate = identity_keys::ADD_KEY_ESTIMATE_CREDITS
+ + maintained.len() as u64 * crate::keys::rotation_estimate(2).0;
+ println!(
+ "Replace the encryption key {} of {id} with a new key #{new_id}, derived from the recovery phrase:",
+ ids(&plan.old_ids)
+ );
+ println!(" 1. add key #{new_id} (one identity update, signed by the master key)");
+ if maintained.is_empty() {
+ println!(" 2. no private repository you maintain needs rotating");
+ } else {
+ println!(
+ " 2. rotate the key of the {} private repo(s) you maintain, so new content is sealed for key #{new_id}: {}",
+ maintained.len(),
+ names(&maintained)
+ );
+ }
+ if !member_only.is_empty() {
+ println!(
+ " {} repo(s) where you are not a maintainer keep using the old key until a maintainer moves them (their next visit does it): {}",
+ member_only.len(),
+ names(&member_only)
+ );
+ }
+ if plan.keep_old {
+ println!(" 3. keep {} enabled (--keep-old)", ids(&plan.old_ids));
+ } else {
+ println!(
+ " 3. disable {}: whoever holds it can no longer read what is sealed from now on (past content stays readable to them)",
+ ids(&plan.old_ids)
+ );
+ }
+ println!(
+ " about {} (two members a repo assumed)",
+ cost_line(estimate, price)
+ );
+}
+
+fn print_outcome(repo: &RepoRef, o: &Outcome) {
+ match o {
+ Outcome::Rotated(r) => crate::keys::print_rotation(repo, r),
+ Outcome::NotMaintainer => println!(
+ "{}: you are no longer a maintainer; a maintainer must move it",
+ repo.display()
+ ),
+ Outcome::Failed(e) => eprintln!("{}: not moved to the new key: {e}", repo.display()),
+ }
+}
+
+fn print_done(done: &Done<'_>, cost: &str) {
+ let plan = done.plan;
+ let new_id = plan.new_id;
+ if let Some(d) = &done.disabled {
+ println!(
+ "✓ disabled {}; private repos now use key #{new_id} · {cost}",
+ ids(d)
+ );
+ } else if done.failed() {
+ println!(
+ " {} stay enabled until every repository moved · {cost}",
+ ids(&plan.old_ids)
+ );
+ } else {
+ println!(
+ " {} stay enabled (--keep-old) · {cost}",
+ ids(&plan.old_ids)
+ );
+ }
+ match &done.stored {
+ Ok(Some(s)) => println!(
+ " this computer now keeps key #{new_id} too, in {}",
+ s.describe()
+ ),
+ Ok(None) => {}
+ Err(e) => eprintln!(
+ "warning: key #{new_id} could not be stored on this computer ({e}); sign in again with `dg auth login` to keep it"
+ ),
+ }
+ let ask = done.ask_maintainer();
+ if !ask.is_empty() {
+ println!(
+ " ask a maintainer of {} to move it to your new key (`dg repo keys repair `); until then new content there is sealed for the old key",
+ names(&ask)
+ );
+ }
+ println!(" other browsers and computers: add the new key from the recovery phrase (web: Settings → Private repos)");
+}
+
+fn report_json(done: &Done<'_>, cost: &Value) -> Value {
+ let plan = done.plan;
+ let repos: Vec = done
+ .outcomes
+ .iter()
+ .map(|(repo, o)| {
+ let (status, detail) = match o {
+ Outcome::Rotated(r) => ("rotated", crate::keys::rotation_json(r)),
+ Outcome::NotMaintainer => ("not_maintainer", Value::Null),
+ Outcome::Failed(e) => ("failed", json!(e)),
+ };
+ json!({ "repo": repo.display(), "repoId": repo.id(), "status": status, "detail": detail })
+ })
+ .collect();
+ json!({
+ "status": if done.disabled.is_some() { "replaced" } else { "added" },
+ "identityId": plan.id,
+ "oldKeyIds": plan.old_ids,
+ "newKeyId": plan.new_id,
+ "repos": repos,
+ "askMaintainer": done.ask_maintainer().iter().map(|r| json!({ "repo": r.display(), "repoId": r.id() })).collect::>(),
+ "disabledKeyIds": done.disabled,
+ "storedAt": done.stored.as_ref().ok().and_then(Option::as_ref).map(store::Stored::describe),
+ "storeError": done.stored.as_ref().err(),
+ "cost": cost,
+ })
+}
diff --git a/crates/dg/src/auth/store.rs b/crates/dg/src/auth/store.rs
index d990d5b0f..75c00934d 100644
--- a/crates/dg/src/auth/store.rs
+++ b/crates/dg/src/auth/store.rs
@@ -245,6 +245,26 @@ fn passphrase_reason(why: &str) -> String {
)
}
+/// A storer that writes back to `source` when it is this identity's main slot (dg's own
+/// keychain entry, or its passphrase-sealed key file), else `None` (a key file or inline key of
+/// the user's own, or a plaintext one: those are left alone). The keychain entry is written to
+/// the keychain again, the sealed file to a sealed file.
+pub fn main_slot_storer(network: &str, identity_id: &str, source: &str) -> Result> {
+ let keychain_source = format!(
+ "{}{}/{}",
+ keystore::KEYCHAIN_PREFIX,
+ keychain::SERVICE,
+ account(network, identity_id, Slot::Main)
+ );
+ if source == keychain_source {
+ return Ok(Some(Storer::new(false)));
+ }
+ let main = slot_file(network, identity_id, Slot::Main)?;
+ let sealed_here = std::path::Path::new(source) == main
+ && std::fs::read_to_string(&main).is_ok_and(|raw| sealed::is_sealed(&raw));
+ Ok(sealed_here.then(|| Storer::sealed_only(false)))
+}
+
/// Store a limited key in the main slot (one-off).
pub fn store(
network: &str,
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/keyring.rs b/crates/forge-core/src/keyring.rs
index 6a9229a79..aa2c53a69 100644
--- a/crates/forge-core/src/keyring.rs
+++ b/crates/forge-core/src/keyring.rs
@@ -511,6 +511,19 @@ impl Keyring {
crate::members::best_role(&self.members, &platform::encode_identifier(self.reader))
}
+ /// The `ENCRYPTION` key ids the reader's own opened wraps for the current epoch went to
+ /// (§5.2 rekey: a wrap to the new key means this repository already moved to it).
+ pub fn own_current_wrap_keys(&self) -> Vec {
+ let Some(n) = self.resolution.current_epoch else {
+ return vec![];
+ };
+ self.wraps
+ .iter()
+ .filter(|w| w.member == self.reader && w.epoch == n && w.key.is_some())
+ .map(|w| w.recipient_key_id)
+ .collect()
+ }
+
/// Epochs with a wrap to the reader that it could not open.
pub fn unreadable_wraps(&self) -> &[u32] {
&self.unreadable_wraps
@@ -1560,6 +1573,65 @@ pub struct Rotation {
pub burned: Option,
}
+/// The private repositories an identity is a current member of (§5.2 rekey), from the
+/// `byMember` index of `maintainer` and `writer`.
+#[derive(Debug, Default)]
+pub struct PrivateMemberships {
+ /// Where it is a maintainer: it can rotate the key itself.
+ pub maintained: Vec,
+ /// Where it is only a writer, triage or reader: a maintainer must rotate (§5.6 repair).
+ pub member_only: Vec,
+}
+
+/// [`PrivateMemberships`] of `identity` (base58) on `forge`'s contracts. A membership whose
+/// repository is gone is skipped; public repositories have no keys and are left out.
+pub async fn private_memberships(
+ client: &PlatformClient,
+ forge: &crate::network::ForgeIds,
+ identity: &str,
+) -> Result {
+ let me = platform::decode_identifier(identity)?;
+ let core = client.fetch_contract(&forge.core).await?;
+ let mut by_type = Vec::new();
+ for doc_type in ["maintainer", "writer"] {
+ let docs = client
+ .query_all_documents(
+ &core,
+ doc_type,
+ &[QueryFilter::eq("memberId", FieldValue::identifier(me))],
+ &[QueryOrder::asc("memberId")],
+ )
+ .await?;
+ // Each membership document records its repository's visibility (`vis`): public ones
+ // have no keys and are not even resolved.
+ by_type.push(
+ docs.iter()
+ .filter(|d| d.field_str("vis").as_deref() == Some("private"))
+ .filter_map(|d| d.field_bytes32("repoId"))
+ .collect::>(),
+ );
+ }
+ let (maintains, writes) = (&by_type[0], &by_type[1]);
+ let mut out = PrivateMemberships::default();
+ for id in maintains.union(writes) {
+ let repo = match crate::resolve::resolve_id(client, &platform::encode_identifier(*id)).await
+ {
+ Ok(r) => r,
+ Err(Error::NotFound) => continue,
+ Err(e) => return Err(e),
+ };
+ if repo.visibility != crate::rules::v2::Visibility::Private {
+ continue;
+ }
+ if maintains.contains(id) {
+ out.maintained.push(repo);
+ } else {
+ out.member_only.push(repo);
+ }
+ }
+ Ok(out)
+}
+
/// The epoch a rotation chains from: the current epoch and its key. A burned current epoch
/// still chains (§5.3); one the rotator cannot read cannot.
fn chain_from(kr: &Keyring, repo: &RepoRef) -> Result<(u32, EpochKey)> {
diff --git a/crates/forge-core/src/lib.rs b/crates/forge-core/src/lib.rs
index 75f534d4b..485a29f68 100644
--- a/crates/forge-core/src/lib.rs
+++ b/crates/forge-core/src/lib.rs
@@ -38,6 +38,7 @@
//! (`test_support` validates with rs-dpp directly, and never ships).
pub mod backends;
+pub mod browser_key;
pub mod budget;
pub mod cache;
pub mod ci;
diff --git a/crates/forge-core/src/rules.rs b/crates/forge-core/src/rules.rs
index e1ba75e49..7abfd2cf0 100644
--- a/crates/forge-core/src/rules.rs
+++ b/crates/forge-core/src/rules.rs
@@ -2550,23 +2550,7 @@ mod tests {
"pubkey_entry" | "commit_signature" => run_signature_case(v),
"repo_name" => run_repo_name_case(v),
"webhook_url" => run_webhook_url_case(v),
- "role_oracle" => {
- let inp: RoleOracleInput = input(v);
- let oracle = v2::RoleOracle::new(inp.memberships);
- let got: Vec = inp
- .queries
- .iter()
- .map(|q| {
- serde_json::json!({
- "roleAt": oracle.role_at(&q.identity, q.at),
- "memberAt": oracle.member_at(&q.identity, q.at),
- "currentRole": oracle.current_role(&q.identity),
- "approverAt": oracle.approver_at(&q.identity, q.at),
- })
- })
- .collect();
- assert_eq!(serde_json::Value::from(got), v.expected, "vector `{ctx}`");
- }
+ "role_oracle" => run_role_oracle(v),
"code_owners" | "code_owner_requests" => run_code_owners_case(v),
"fold_review" | "policy" | "anchor" | "review_group" | "suggestion"
| "linked_issues" => run_review_case(v),
@@ -2575,10 +2559,127 @@ mod tests {
}
"long_body" => run_long_body(v),
"ci_rerun" | "ci_rerun_write" => run_ci_rerun_case(v),
+ "key_handoff" | "key_handoff_open" | "copy" => run_key_handoff_case(v),
other => panic!("vector `{ctx}`: unknown v2 case `{other}`"),
}
}
+ fn run_role_oracle(v: &Vector) {
+ let inp: RoleOracleInput = input(v);
+ let oracle = v2::RoleOracle::new(inp.memberships);
+ let got: Vec = inp
+ .queries
+ .iter()
+ .map(|q| {
+ serde_json::json!({
+ "roleAt": oracle.role_at(&q.identity, q.at),
+ "memberAt": oracle.member_at(&q.identity, q.at),
+ "currentRole": oracle.current_role(&q.identity),
+ "approverAt": oracle.approver_at(&q.identity, q.at),
+ })
+ })
+ .collect();
+ assert_eq!(
+ serde_json::Value::from(got),
+ v.expected,
+ "vector `{}`",
+ v.name
+ );
+ }
+
+ #[derive(Deserialize, Serialize)]
+ #[serde(deny_unknown_fields, rename_all = "camelCase")]
+ struct KeyHandoffInput {
+ network: String,
+ browser_secret: String,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ ephemeral_secret: Option,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ nonce: Option,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ plaintext: Option,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ reply: Option,
+ }
+
+ #[derive(Deserialize, Serialize)]
+ #[serde(deny_unknown_fields)]
+ struct CopyInput {
+ id: String,
+ }
+
+ /// `key_handoff__*` (seal a reply for a request), `key_handoff_open__*` (open one) and
+ /// `copy__*` (fixed user-facing text): `crate::browser_key`.
+ fn run_key_handoff_case(v: &Vector) {
+ use crate::browser_key::{open, request_text, seal_bytes, OpenError, Request};
+ let ctx = &v.name;
+ if v.case == "copy" {
+ let inp: CopyInput = input(v);
+ let text = match inp.id.as_str() {
+ "recoveryPhraseWarning" => crate::browser_key::RECOVERY_PHRASE_WARNING,
+ other => panic!("vector `{ctx}`: unknown copy `{other}`"),
+ };
+ assert_eq!(
+ serde_json::json!({ "text": text }),
+ v.expected,
+ "vector `{ctx}`"
+ );
+ return;
+ }
+ let inp: KeyHandoffInput = input(v);
+ let h32 = |s: &str| -> [u8; 32] {
+ hex::decode(s)
+ .unwrap_or_else(|e| panic!("vector `{ctx}`: {e}"))
+ .try_into()
+ .unwrap_or_else(|_| panic!("vector `{ctx}`: not 32 bytes"))
+ };
+ let secret = h32(&inp.browser_secret);
+ let opened = |reply: &str| match open(reply, &inp.network, &secret) {
+ Ok(p) => serde_json::json!({ "plaintext": String::from_utf8(p.to_vec()).unwrap() }),
+ Err(e) => serde_json::json!({ "error": match e {
+ OpenError::Malformed => "malformed",
+ OpenError::Network => "network",
+ OpenError::Unreadable => "unreadable",
+ } }),
+ };
+ if v.case == "key_handoff_open" {
+ let reply = inp.reply.as_deref().expect("reply");
+ assert_eq!(opened(reply), v.expected, "vector `{ctx}`");
+ return;
+ }
+ let secp = secp256k1::Secp256k1::new();
+ let public_key = secp256k1::PublicKey::from_secret_key(
+ &secp,
+ &secp256k1::SecretKey::from_slice(&secret).unwrap(),
+ );
+ let request = Request {
+ network: inp.network.clone(),
+ public_key,
+ };
+ let plaintext = inp.plaintext.as_deref().expect("plaintext");
+ let nonce: [u8; 12] = hex::decode(inp.nonce.as_deref().expect("nonce"))
+ .unwrap()
+ .try_into()
+ .unwrap();
+ let reply = seal_bytes(
+ &request,
+ plaintext.as_bytes(),
+ &h32(inp.ephemeral_secret.as_deref().expect("ephemeralSecret")),
+ nonce,
+ )
+ .unwrap();
+ let got = serde_json::json!({
+ "request": request_text(&inp.network, &public_key),
+ "reply": reply,
+ });
+ assert_eq!(got, v.expected, "vector `{ctx}`");
+ assert_eq!(
+ opened(&reply),
+ serde_json::json!({ "plaintext": plaintext }),
+ "vector `{ctx}`: round trip"
+ );
+ }
+
#[derive(Deserialize, Serialize)]
#[serde(deny_unknown_fields, rename_all = "camelCase")]
struct LongBodyInput {
diff --git a/docs/contracts/forge-v2.md b/docs/contracts/forge-v2.md
index d64c06b2f..07c7fdc49 100644
--- a/docs/contracts/forge-v2.md
+++ b/docs/contracts/forge-v2.md
@@ -499,6 +499,20 @@ The trailer is an HTML comment, which GitHub-flavoured renderers (forge-web's am
**What it does not prove.** The file proves that someone who can push to the source named this repo. It says nothing about whether the mirror's content is current: the branch comparison does that, and only for the branch it compares. A source's maintainers can list several mirrors, and take one off the list. Only GitHub sources are checked; GitLab claims stay "says it mirrors". The check tells github.com the viewer's address, which is why it is a button.
+### 6.5 Key handoff: a limited key from `dg` to a browser (client convention, TS-06)
+
+A browser can get its limited key from `dg` instead of from the recovery phrase, so the phrase never enters a web page. Nothing on chain changes: `dg` registers an ordinary limited key (§2, the `dash-forge` group, a budget and an expiry) with one master-key `IdentityUpdate` on the terminal, and hands its private key to the browser sealed. The rules, shared by forge-core (`browser_key`) and forge-web (`lib/auth/key-handoff.ts`) and pinned by the `key_handoff__*` and `key_handoff_open__*` vectors:
+
+| | Rule |
+|---|---|
+| **Request** (the browser shows it) | `dfkr1::`, from a one-time key pair drawn for this request and kept only in the tab's memory. `` is the network key (`testnet`, `mainnet`, `devnet-sakura`): 1 to 32 characters of `[A-Za-z0-9-]`. base64url is RFC 4648 §5 without padding, decoded strictly (no `=`, no stray bits). |
+| **Reply** (`dg auth keys add --for-browser ` prints it) | `dfkh1::`: `E` dg's ephemeral compressed public key (33 bytes), `N` a random 12-byte nonce, `C` AES-256-GCM of the payload (tag included). Key: `HKDF-SHA256(ikm = x-coordinate of ECDH(ephemeral, request key), salt = E ‖ request public key, info = "dash-forge/key-handoff/1")`. Associated data: `"dfkh1:" ‖ network`, so a reply relabelled for another network does not open. |
+| **Payload** | JSON `{"v":1,"network","identityId","keyId","wif"}` plus optional `"replacedKeyId"` (the key disabled in the same update) and `"encryptionKey":{"keyId","privateKeyHex"}` (with `--with-encryption-key`). Unknown fields, another version or another network: refused. At most 2,048 bytes. |
+| **Opening** | Not a `dfkh1:` reply, or too short for a tag: *malformed*. Another network: *network*, before decrypting. A tag that fails (another tab's request, an altered reply): *unreadable*. |
+| **Adopting** | The browser reads the key back from the chain before storing anything: live, AUTHENTICATION/HIGH, bound to the group, with a budget and an expiry, and controlled by the private key the payload carries. A renewal takes only a key for the signed-in identity, and a key this browser already holds for the identity must be the one the reply says was replaced (else it would stay live with nothing holding it); wallet keys, which `dg` cannot disable by id, renew with the identity file or phrase instead. The command names the identity when the tab knows it (`--for-identity`), and `dg` refuses another one before signing. `dg` refuses a browser key that lives longer than 365 days. The vault records that the key came from `dg`, and **Renew** then offers `dg` first. |
+
+The reply is useless without the tab's one-time private key, so it may be printed and pasted like any text; what it carries is still only a limited key. A request works once: the tab forgets its private key when the key is stored or the view closes.
+
## 7. Measured size and cost
From `tools/contract-validate` (rs-dpp v5.0.0-beta.1, `PlatformVersion` 14) on the RC2 build with every flag on. The signed-shape transitions carry a 65-byte recoverable signature and the contract group fields.
diff --git a/docs/guides/identity-and-keys.md b/docs/guides/identity-and-keys.md
index 912d43e1c..8e446bb82 100644
--- a/docs/guides/identity-and-keys.md
+++ b/docs/guides/identity-and-keys.md
@@ -68,8 +68,9 @@ Do this once:
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, 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.
+2. Disable the lost machine's key: in the web app, **Settings → Devices & keys** lists every key and has **Disable** (your identity file or recovery phrase signs once); in the terminal, `dg auth keys list` shows it and `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.
+4. If you use private repositories, the lost machine also held your **encryption key**, which a disabled signing key does not protect. Replace it: `dg auth keys rotate --encryption` ([below](#replacing-it-after-a-lost-device)).
Your **repository data** needs no backup of its own. Refs, issues and PRs are on Platform. Pack bytes are on Platform or in the storage you chose. Any clone also holds a full copy of the history, and [`dg reseed --from-local`](bring-your-own-storage.md#restoring-a-lost-copy) can restore a lost pack copy from it.
@@ -105,7 +106,8 @@ Things to know:
A web page is whoever served it. If the page, or a script it loads, is compromised, anything you paste into it is gone.
- **Never paste your MASTER key, your 12 words, or your main identity file into a website.** That includes forge.dashhq.org. Nothing on Forge needs them.
-- The web app's **Import** reads your identity file (or recovery phrase) once: its master key signs one update that registers a [limited key](#limited-keys) for this browser, and is not retained. If you would rather not load the master key into a web page at all, use **Use my Dash wallet** instead (the wallet registers the key), or register a key for the browser from the terminal: `dg auth export --new-key --reveal-secrets --format dfk1 -o key.dfk1`, then under **Advanced** enter the identity id and the key's WIF (the last `:`-separated field of the `dfk1` value). It signs for that tab only.
+- The web app's **Import** reads your identity file (or recovery phrase) once: its master key signs one update that registers a [limited key](#limited-keys) for this browser, and is not retained. If you would rather not load the master key into a web page at all, use **Sign in → Use dg on your computer**: the page shows a `dg auth keys add --for-browser …` command, `dg` registers the key with your master key on the terminal and prints a line that only that tab can open ([below](#a-browser-key-from-dg)). **Use my Dash wallet** also keeps the master key out of the page (the wallet registers the key).
+- Forge asks for your recovery phrase only after you start a key action yourself. Every phrase prompt, in the web app and in `dg`, shows the same warning: *"Your recovery phrase controls your identity. Forge asks for it only after you start a key action yourself, never because a message, an email or a pop-up says so. If you didn't start this, stop here."* A page that asks for your words without it, or because a message told you to, is not Forge.
- For CI, give a pipeline its own limited key: `dg auth export --new-key --budget 0.5 --expires 365d --format dfk1 --reveal-secrets -o runner.dfk1` makes one, and the file's one line is the `DASH_FORGE_KEY` secret.
- Prefer a copy of the web app that you [serve yourself](verify-forge.md#run-your-own-copy-of-the-web-app) if you do not want to trust the one on forge.dashhq.org.
@@ -120,7 +122,9 @@ 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 keys rotate --encryption [--keep-old] # replace the ENCRYPTION key and move your private repos to it
dg auth logout [--disable] # forget the key here (and disable it on chain)
```
@@ -128,7 +132,7 @@ dg auth logout [--disable] # forget the key here (and disable it o
When to rotate:
-- a laptop or CI secret that held a key was lost or leaked: **disable that key**;
+- a laptop or CI secret that held a key was lost or leaked: **disable that key**, and if it also held the encryption key (any `dg auth login` with private repos, a browser with private repos enabled), **replace the encryption key** too;
- a limited key's budget is nearly spent or it is about to expire: `dg auth keys add` registers a fresh one and disables this computer's current key in the same update (`--replace ` names another key to disable, `--keep-current` keeps the current one live on chain, though this computer no longer stores it; `dg auth login … --replace ` does the same at sign-in).
A browser's own key is managed in the web app: **Settings → This browser's key** can top it up, renew it or revoke it ([below](#limited-keys)).
@@ -155,6 +159,21 @@ dg auth keys add --encryption
**What it can read.** This key can read every private repo you're a member of, and every key you've handed out as a maintainer. Keep it as carefully as your signing keys.
+### Replacing it after a lost device
+
+```sh
+dg auth keys rotate --encryption [--master ] [--keep-old]
+```
+
+It runs the rekey of [private-repos.md §5.2](../security/private-repos.md#52-encryption-keys-derivation-custody-blast-radius-rekey), in this order, and prints the plan and its cost before anything is signed:
+
+1. Adds a new ENCRYPTION key, derived from the recovery phrase at the next key id, so the words alone recover it (one identity update, signed by the MASTER key).
+2. Rotates the key of every private repository you **maintain**: a new key epoch, wrapped to every member, you first, to your new key. Each costs one wrap per member plus one anchor.
+3. Names the private repositories where you are only a writer, triage or reader. You cannot rotate those. A maintainer's next visit (or `dg repo keys repair `) wraps the current key to your new one. Until then, new content there is sealed for the old key.
+4. Disables the old key, unless `--keep-old` is given or a repository failed to rotate. A disabled key still opens what was sealed for it, so nothing you could read is lost. Whoever holds the old key keeps what was sealed before, but nothing sealed from now on.
+
+The key `dg` stores beside your limited key (`dg auth login`) gets the new key too. A repository counts as moved only when a fresh read shows your wrap for its current epoch on the new key. If one is not, every old key stays enabled and nothing is lost. Run the command again: each run adds a fresh key and treats every enabled encryption key as old, since a lost device may have held an earlier run's key too. Other computers and browsers need the new key: sign in again with the words, or in the web app add it from **Settings → Private repos**.
+
**In the web app** this will be **Settings → Keys → Enable private repos**, with the web release of private repositories.
---
@@ -170,7 +189,7 @@ A limited key is an identity key with four restrictions:
| Where | Budget | Expires |
|---|---|---|
-| Browser | 0.05 DASH | 90 days |
+| Browser | 0.05 DASH | 90 days (30 days to 1 year) |
| CLI (`dg auth new` / `login` / `keys add`) | 0.25 DASH | 180 days |
| CI runner (`dg auth export --new-key`, Mirror Action) | 0.5 DASH | 365 days |
@@ -196,11 +215,27 @@ dg auth name register # a DPNS username
`dg auth new` shows the 12 words once and asks you to type three of them back. It then shows the deposit address as a QR code and as text. Fund it from any Dash wallet (the faucet on devnets), and `dg` does the rest: the asset lock, its proof (InstantSend where the network offers one, else a chain lock), and one IdentityCreate that registers the standard keys plus this computer's limited key. The limited key is stored in the keychain *before* the identity exists, so an interruption never leaves a key nobody holds. An interrupted run resumes with `dg auth new --resume` (type the words again); the deposit address stays the same. The words are shown only in a terminal, and never with `--json` or in CI. Without a terminal, `--backup-file ` is required: the words and keys go only to that passphrase-sealed file (0600, `DASH_FORGE_PASSPHRASE` without a terminal or with `--json`) and only its path is printed. `--skip-backup-check` skips the three-word check in a terminal and needs `--backup-file`; it never prints or writes the words anywhere else.
+### A browser key from dg
+
+On a computer where `dg` is signed in, a browser can get its key without the recovery phrase:
+
+1. In the web app, **Sign in → Use dg on your computer** (or **Settings → This browser's key → Renew key → With dg**). Pick how long the key lives (30 days to a year) and whether the browser should also open private repos. The page shows a command with a one-time request in it:
+
+ ```sh
+ dg auth keys add --devnet-name sakura --for-browser dfkr1:devnet-sakura:Ap… --budget 0.05 --expires 365d [--replace 7] [--with-encryption-key]
+ ```
+
+2. Run it. `dg` shows what the key can spend and what the update costs, asks, signs with your master key (the stored identity file, `--master `, or your words), and prints one line starting with `dfkh1:`.
+3. Paste that line into the page and choose a passphrase or passkey. The browser checks the key on chain and keeps it in its vault.
+
+When the page knows your identity (a renewal, or a key this browser already holds), the command carries `--for-identity ` and `--replace `, and `dg` refuses before signing if it would make the key for another identity. The printed line is sealed to the tab that showed the request: anyone else who sees it cannot open it, and it opens on that network only. `--replace ` (filled in by Renew) disables the browser's old key in the same update; `--with-encryption-key` hands over the identity's encryption key too, for private repos. This computer keeps signing with its own key. A key that came from `dg` renews with `dg` by default, so renewing never asks for the recovery phrase.
+
Ways to get one in the web app (**Sign in**):
| Route | What happens |
|---|---|
-| Import an identity file or recovery phrase | Your master key signs one IdentityUpdate that adds the limited key. It is used once and not retained. |
+| Use dg on your computer | `dg` registers the key and prints it sealed to this tab ([above](#a-browser-key-from-dg)). The recovery phrase stays out of the browser. |
+| Import an identity file or recovery phrase | Your master key signs one IdentityUpdate that adds the limited key. It is used once and not retained. You choose how long the key lives: 30 days, 90 days (the default), 6 months or 1 year. |
| Create a new identity | 12 words, a check on three of them, a choice of passkey or passphrase, then a deposit from any Dash wallet (the faucet on devnets). One IdentityCreate registers the standard key set plus this browser's limited key, so no second signature is needed. The key is stored in the vault *before* it is registered, and an interrupted creation resumes when you type the same words again. |
| Use my Dash wallet | **Not a limited key**, and **testnet only**: Dash Wallet's sign-in feature (DashConnect, More → Tools → Connections in the DashPay app) answers on testnet, is not in a released version yet, and Forge is not on testnet yet. On sakura only an internal iOS build with the login contract entered by hand can answer ([below](#signing-in-with-the-dash-wallet-app-what-works-today)). Scan the QR code with the wallet (or tap **Open in DashPay (Dash Wallet)** on the phone) and approve; the first time, scan (or open) a second code, and the wallet adds Forge's key to your identity (iOS asks for your PIN). Your wallet hands the key over encrypted. **Check that the username and identity shown match what your wallet showed**: a response does not prove who answered, and anyone who saw the QR code could answer. On the App Connect contract the app refuses if more than one identity answers; on the key-exchange contract today's wallets use, the first answer wins. Today's Dash Wallet grants a key with **no spending limit or expiry** (on iOS, for one contract per approval, so issues and pull requests take one more approval), and Settings offers to replace the key with a limited one or disable it. See [wallet-login](../design/wallet-login.md). |
| Advanced: paste a key | A HIGH or CRITICAL key, for this tab only, lost on reload. It has no limits Forge set. Never paste a master key. |
@@ -208,7 +243,7 @@ Ways to get one in the web app (**Sign in**):
The header shows your balance and the key's remaining budget. It turns amber when the budget drops under 20 % or expiry is less than 7 days away, and red when the key is spent or expired. A write that would overrun either is refused before it is signed, and the sheet that opens says which one blocks. **Settings → This browser's key** shows the budget and expiry and has these actions:
- **Top up key budget** adds budget to the same key (0.05 DASH by default) and can push its expiry out, up to 365 days. It is an `IdentityKeyLimitsUpdate` (Dash Platform v5), signed once by your master key from the identity file or recovery phrase, and costs about 0.00002 DASH.
-- **Renew key** opens **Renew this browser's key**: your identity file or recovery phrase registers a fresh key and disables the previous one in the same update (about 0.00028 DASH). An encryption key this browser holds moves to the new key.
+- **Renew key** opens **Renew this browser's key**: **With dg** (the default for a key that came from `dg`) or **With identity file or phrase** registers a fresh key and disables the previous one in the same update (about 0.00028 DASH). An encryption key this browser holds moves to the new key.
- **Lock** drops the unlocked key in every open tab and ends the kept session; unlock again with the passkey or passphrase.
- **Settings → Security → Stay signed in for public repos (up to 12 h)** (on by default): reloads and new tabs keep only the spend-capped signing key, for up to 12 hours after the unlock and until 4 hours pass without use. Private repos, storage credentials and wallet grants still ask you to unlock, once per tab. Turn it off and every reload or new tab starts locked.
- **Revoke on chain** disables this browser's key (about 0.00002 DASH). It needs your identity file or recovery phrase once. After a reload it first asks you to unlock this tab, so it can disable every key the browser holds.
@@ -244,6 +279,14 @@ CI gets one pasteable value, `DASH_FORGE_KEY=dfk1:::
+
+
+
+
+ Settings
+ {' '}
+ / Devices & keys
+
+
+
+ Devices & keys
+
+
+ Every key on your identity, as the network has it. Each browser, computer and CI runner you sign in from adds one. Lost a device? Disable
+ its key here.
+
+
+ {!isForgeDeployed() ? (
+
+ ) : identity ? (
+
+ ) : (
+
}
+ />
+ )}
+
+
+ )
+}
diff --git a/forge-web/components/app-shell.tsx b/forge-web/components/app-shell.tsx
index 42c2e4396..32b1ad6ba 100644
--- a/forge-web/components/app-shell.tsx
+++ b/forge-web/components/app-shell.tsx
@@ -10,6 +10,7 @@ import type { ReactNode } from 'react'
import { AppHeader } from '@/components/app-header'
import { AppFooter } from '@/components/app-footer'
import { DevnetNoticeBanner } from '@/components/devnet-notice-banner'
+import { NewKeyAlert } from '@/components/new-key-alert'
import { ContractsMissingState } from '@/components/ui/contracts-missing'
import { useContractsMissing } from '@/hooks/use-sdk'
import { useOfflineNavigation } from '@/hooks/use-offline-navigation'
@@ -45,6 +46,7 @@ export function AppShell({
+
void }): JSX.Elem
An identity creation is in progress on this device (deposit address {address} ). Type
your 12 words to finish it.
+
diff --git a/forge-web/components/auth/dg-handoff-flow.tsx b/forge-web/components/auth/dg-handoff-flow.tsx
new file mode 100644
index 000000000..32927273c
--- /dev/null
+++ b/forge-web/components/auth/dg-handoff-flow.tsx
@@ -0,0 +1,201 @@
+'use client'
+
+/**
+ * Sign in (or renew this browser's key) with `dg`, so the recovery phrase never enters the page
+ * (TS-06; `lib/auth/key-handoff.ts`). The tab shows a one-time request inside a `dg` command;
+ * `dg` registers a limited key with the master key on the terminal and prints it sealed to this
+ * tab; the tab opens it, checks it on chain and keeps it in the vault.
+ *
+ * The one-time private key lives in a ref for as long as the view is open and is wiped when it
+ * closes or once a reply was opened: a reply only opens in the tab that asked for it.
+ */
+
+import { useCallback, useEffect, useRef, useState } from 'react'
+import { useAuth } from '@/contexts/auth-context'
+import { Button } from '@/components/ui/button'
+import { Field, Textarea } from '@/components/ui/input'
+import { CopyBlock } from '@/components/storage/copy-block'
+import { ErrorBox, useProtection } from '@/components/auth/protection-fields'
+import { KeyLifetimeSelect } from '@/components/auth/key-lifetime'
+import { UnlockMore } from '@/components/auth/unlock-more'
+import { UnlockNeededError } from '@/lib/auth/controller'
+import { ACTIVE_NETWORK } from '@/lib/constants'
+import { BROWSER_KEY_DEFAULTS } from '@/lib/auth'
+import { handoffCommand, handoffRequest, type HandoffRequest } from '@/lib/auth/key-handoff'
+import { errorMessage } from '@/lib/utils'
+
+/** A key this browser holds, which the new key replaces (disabled in the same update). */
+export interface HandoffTarget {
+ readonly identityId: string
+ readonly keyId: number
+}
+
+/**
+ * `renew`: replace the signed-in identity's key. `target`: a key this browser holds but cannot
+ * unlock (an expired or forgotten-passphrase key). Otherwise, when this browser holds keys, the
+ * user picks the one to replace, or none (another identity).
+ */
+export function DgHandoffFlow({ onDone, renew = false, target }: { readonly onDone: () => void; readonly renew?: boolean; readonly target?: HandoffTarget }): JSX.Element {
+ const { adoptHandoffKey, isLoading, step, keyId, vaults, identity, unlockScope, controller } = useAuth()
+ const requestRef = useRef(null)
+ const [requestText, setRequestText] = useState(null)
+ const fresh = useCallback(() => {
+ requestRef.current?.wipe()
+ requestRef.current = handoffRequest(ACTIVE_NETWORK.key)
+ setRequestText(requestRef.current.text)
+ }, [])
+ useEffect(() => {
+ fresh()
+ return () => {
+ requestRef.current?.wipe()
+ requestRef.current = null
+ }
+ }, [fresh])
+ const [days, setDays] = useState(BROWSER_KEY_DEFAULTS.days)
+ // A renewal that drops the encryption key this browser holds brings it again by default.
+ const held = vaults.find((v) => v.identityId === identity)
+ const [withEncryption, setWithEncryption] = useState(renew && held?.encryptionKey === true)
+ const replyRef = useRef(null)
+ const [hasReply, setHasReply] = useState(false)
+ const [error, setError] = useState(null)
+ const submitRef = useRef<() => void>(() => undefined)
+ const { fields, protection, problem } = useProtection({
+ onSubmit: () => submitRef.current(),
+ })
+
+ // The key the new one replaces. Never left implicit: a key this browser holds and dg does not
+ // disable would stay live with nothing holding it (the controller refuses such a reply).
+ const stored = vaults.filter((v) => v.staged !== true)
+ const [picked, setPicked] = useState(() => stored[0]?.identityId ?? '')
+ const pickedVault = stored.find((v) => v.identityId === picked)
+ const replace: HandoffTarget | undefined =
+ renew && identity !== null && keyId !== null
+ ? { identityId: identity, keyId }
+ : (target ?? (pickedVault ? { identityId: pickedVault.identityId, keyId: pickedVault.keyId } : undefined))
+ // Wallet keys can't be replaced from dg: say so before dg is asked to pay for a key.
+ const [blocker, setBlocker] = useState(null)
+ const replaceIdentity = replace?.identityId
+ useEffect(() => {
+ let cancelled = false
+ setBlocker(null)
+ if (replaceIdentity === undefined) return
+ controller.handoffBlocker(replaceIdentity).then(
+ (b) => !cancelled && setBlocker(b),
+ () => undefined,
+ )
+ return () => {
+ cancelled = true
+ }
+ }, [controller, replaceIdentity])
+ const command =
+ requestRef.current && requestText
+ ? handoffCommand(requestRef.current, {
+ days,
+ budgetDash: BROWSER_KEY_DEFAULTS.budgetDash,
+ withEncryptionKey: withEncryption,
+ ...(replace !== undefined ? { replaceKeyId: replace.keyId, identityId: replace.identityId } : {}),
+ })
+ : null
+ const ready = protection !== null && hasReply && !isLoading && requestRef.current !== null
+ const submit = async (): Promise => {
+ const request = requestRef.current
+ if (!ready || request === null || protection === null) return
+ setError(null)
+ try {
+ await adoptHandoffKey(replyRef.current?.value ?? '', request, protection, { renew, ...(replace !== undefined ? { identityId: replace.identityId } : {}) })
+ if (replyRef.current) replyRef.current.value = ''
+ onDone()
+ } catch (e) {
+ // A reloaded tab holds the signing key only: replacing the vault must carry over what it
+ // seals, so unlock it here first, then carry on.
+ if (e instanceof UnlockNeededError) setUnlockFirst(true)
+ else setError(errorMessage(e))
+ }
+ }
+ const [unlockFirst, setUnlockFirst] = useState(false)
+ submitRef.current = () => {
+ if (ready) void submit()
+ }
+
+ // A reloaded tab holds the signing key only, and a renewal must carry over what the vault
+ // seals: unlock first, before dg is asked to pay for a key.
+ if (renew && unlockScope === 'signing') {
+ return (
+
+
+
+ )
+ }
+
+ return (
+
+
+ On a computer where dg is signed in as your identity, run this command. It uses your master key there, once, and prints a key that only
+ this tab can open.
+
+ {!renew && target === undefined && stored.length > 0 ? (
+
+ setPicked(e.target.value)}
+ className="w-full rounded-md border border-anvil-300 bg-transparent px-2 py-1.5 font-mono text-dense coarse:h-11 coarse:text-base dark:border-anvil-700"
+ >
+ {stored.map((v) => (
+
+ {v.identityId.slice(0, 10)}… (key #{v.keyId})
+
+ ))}
+ None: another identity
+
+
+ ) : null}
+ {blocker !== null ? (
+
+ {blocker}
+
+ ) : null}
+
+
+
+ setWithEncryption(e.target.checked)} data-testid="dg-with-encryption" />
+ Also open private repos here
+
+
+ {command && blocker === null ?
: null}
+
+ {replace !== undefined ? `Key #${replace.keyId} is disabled in the same update. ` : ''}
+ The new key can spend at most {BROWSER_KEY_DEFAULTS.budgetDash} DASH, only on Forge. dg shows the cost and asks before it signs.
+
+
+ {/* Uncontrolled: what it opens to is a key, and the field is cleared after use. */}
+
+ {fields}
+
+
void submit()} loading={isLoading} disabled={!ready}>
+ {isLoading && step ? `${step}…` : renew ? <>Renew this browser's key> : <>Use this key>}
+
+ {problem && hasReply ?
{problem}
: null}
+ {unlockFirst ? (
+
{
+ setUnlockFirst(false)
+ void submit()
+ }}
+ />
+ ) : null}
+
+ )
+}
diff --git a/forge-web/components/auth/key-lifetime.tsx b/forge-web/components/auth/key-lifetime.tsx
new file mode 100644
index 000000000..48af3883a
--- /dev/null
+++ b/forge-web/components/auth/key-lifetime.tsx
@@ -0,0 +1,23 @@
+/** How long a new browser key lives: 30 days to a year (TS-06: a longer key means rarer renewals). */
+
+import { KEY_LIFETIME_DAYS, lifetimeLabel } from '@/lib/auth'
+import { Field } from '@/components/ui/input'
+
+export function KeyLifetimeSelect({ id, value, onChange }: { readonly id: string; readonly value: number; readonly onChange: (days: number) => void }): JSX.Element {
+ return (
+
+ onChange(Number(e.target.value))}
+ className="w-full rounded-md border border-anvil-300 bg-transparent px-2 py-1.5 text-dense coarse:h-11 coarse:text-base dark:border-anvil-700"
+ >
+ {KEY_LIFETIME_DAYS.map((d) => (
+
+ {lifetimeLabel(d)}
+
+ ))}
+
+
+ )
+}
diff --git a/forge-web/components/auth/master-key-input.tsx b/forge-web/components/auth/master-key-input.tsx
index d23914cf9..53ea71612 100644
--- a/forge-web/components/auth/master-key-input.tsx
+++ b/forge-web/components/auth/master-key-input.tsx
@@ -16,6 +16,7 @@ import { Field, Textarea } from '@/components/ui/input'
import { masterMaterialFromFile, type MasterInput } from '@/lib/auth'
import { otherIdentityFileMessage } from '@/lib/auth/controller'
import { cn, errorMessage } from '@/lib/utils'
+import { PhraseWarning } from '@/components/auth/phrase-warning'
export interface MasterKeyInput {
/** The fieldset to render. */
@@ -114,17 +115,20 @@ export function useMasterKeyInput(identityId: string | null, { id, fileLabel }:
/>
>
) : (
-
-
+ <>
+
+
+
+ >
)}
)
diff --git a/forge-web/components/auth/phrase-warning.tsx b/forge-web/components/auth/phrase-warning.tsx
new file mode 100644
index 000000000..e62b9b1b8
--- /dev/null
+++ b/forge-web/components/auth/phrase-warning.tsx
@@ -0,0 +1,22 @@
+/**
+ * The fixed warning before every recovery-phrase prompt (TS-06). One text, everywhere: the web
+ * app and `dg` show the same words (`RECOVERY_PHRASE_WARNING`, vector `copy__recovery_phrase_warning`),
+ * so a page that asks for the phrase without them stands out.
+ */
+
+import { ShieldAlert } from 'lucide-react'
+import { RECOVERY_PHRASE_WARNING } from '@/lib/auth/key-handoff'
+import { cn } from '@/lib/utils'
+
+export function PhraseWarning({ className }: { readonly className?: string }): JSX.Element {
+ return (
+
+
+ {RECOVERY_PHRASE_WARNING}
+
+ )
+}
diff --git a/forge-web/components/devices-keys.tsx b/forge-web/components/devices-keys.tsx
new file mode 100644
index 000000000..3bb7e0462
--- /dev/null
+++ b/forge-web/components/devices-keys.tsx
@@ -0,0 +1,315 @@
+'use client'
+
+/**
+ * Settings → Devices & keys (TS-07): every key of the identity as the chain has it, labelled
+ * locally, with Disable for a lost device's key (the master key signs once). Also whether this
+ * browser's storage is kept (TS-17).
+ */
+
+import { useCallback, useEffect, useState } from 'react'
+import { Copy, HardDrive, KeyRound, LifeBuoy, Pencil, ShieldOff } from 'lucide-react'
+import { useAuth } from '@/contexts/auth-context'
+import { Dialog } from '@/components/ui/dialog'
+import { Button } from '@/components/ui/button'
+import { Input } from '@/components/ui/input'
+import { CostPreview } from '@/components/ui/cost-preview'
+import { ErrorBox } from '@/components/auth/protection-fields'
+import { useMasterKeyInput } from '@/components/auth/master-key-input'
+import { StepFailed } from '@/components/auth/step-status'
+import { Spinner } from '@/components/ui/states'
+import { ACTIVE_NETWORK } from '@/lib/constants'
+import { DOCS } from '@/lib/docs-links'
+import { useCopy } from '@/hooks/use-copy'
+import { ROLE_TEXT, disableRefusal, readKeyLabels, requestPersistence, storagePersistence, writeKeyLabel, type KeyRow, type StoragePersistence } from '@/lib/auth/devices'
+import { keyKind } from '@/lib/auth/key-watch'
+import { IdentityUpdateNotSentError, WrongMasterKeyError } from '@/lib/auth/limited-key'
+import { KEY_DISABLE_CREDITS, previewCredits } from '@/lib/sdk'
+import { readLedger } from '@/lib/spend'
+import { creditsAsDash, formatDate } from '@/lib/view/format'
+import { cn, errorMessage } from '@/lib/utils'
+
+export function DevicesKeys(): JSX.Element {
+ const { identity, controller, newKeys } = useAuth()
+ const [rows, setRows] = useState(null)
+ const [error, setError] = useState(null)
+ const [labels, setLabels] = useState>({})
+ const [disabling, setDisabling] = useState(null)
+ const load = useCallback(() => {
+ setError(null)
+ controller.identityKeys().then(setRows, (e: unknown) => setError(errorMessage(e)))
+ }, [controller])
+ useEffect(() => {
+ if (identity === null) return
+ setLabels(readKeyLabels(ACTIVE_NETWORK.network, identity))
+ load()
+ }, [identity, load])
+ const isNew = (id: number): boolean => newKeys.some((k) => k.keyId === id)
+
+ if (identity === null) return <>>
+ return (
+
+ {error !== null ?
: null}
+ {rows === null && error === null ?
: null}
+ {rows !== null ? (
+
+ {rows.map((r) => (
+ setLabels(writeKeyLabel(ACTIVE_NETWORK.network, identity, r.keyId, text))}
+ onDisable={() => setDisabling(r)}
+ />
+ ))}
+
+ ) : null}
+
+ Labels stay in this browser. Platform doesn't record when a key was last used: a budget that went down was used, and this browser's last
+ write is below.
+
+
+
+ {disabling !== null ? (
+
setDisabling(null)}
+ onDone={() => {
+ setDisabling(null)
+ load()
+ }}
+ />
+ ) : null}
+
+ )
+}
+
+function KeyRowItem({
+ row,
+ label,
+ fresh,
+ onLabel,
+ onDisable,
+}: {
+ row: KeyRow
+ label: string
+ fresh: boolean
+ onLabel: (text: string) => void
+ onDisable: () => void
+}): JSX.Element {
+ const [editing, setEditing] = useState(false)
+ const [draft, setDraft] = useState(label)
+ const refusal = disableRefusal(row)
+ const disabled = row.disabledAt !== null
+ const expired = row.expiresAt !== null && row.expiresAt <= Date.now()
+ return (
+
+
+
+
#{row.keyId}
+ {editing ? (
+
+ ) : (
+ <>
+ {label ?
{label} : null}
+
{
+ setDraft(label)
+ setEditing(true)
+ }}
+ className="hit-area inline-flex items-center gap-1 text-[12px] text-anvil-600 underline dark:text-anvil-300"
+ >
+ {label ? 'Rename' : 'Name it'}
+
+ >
+ )}
+ {row.thisBrowser ?
This browser : null}
+ {fresh ?
New : null}
+ {disabled ?
Disabled {formatDate(row.disabledAt as number)} : expired ?
Expired : null}
+
+
+ {ROLE_TEXT[row.role]} ({keyKind(row)})
+
+ {row.budgetTotal !== null || row.expiresAt !== null ? (
+
+ {row.budgetTotal !== null
+ ? `${row.budgetLeft !== null ? creditsAsDash(Number(row.budgetLeft)) : '?'} of ${creditsAsDash(Number(row.budgetTotal))} DASH left`
+ : 'No budget'}
+ {' · '}
+ {row.expiresAt !== null ? `${expired ? 'expired' : 'expires'} ${formatDate(row.expiresAt)}` : 'never expires'}
+
+ ) : null}
+ {!disabled ? (
+ refusal === null ? (
+
+ Disable
+
+ ) : (
+ {refusal}
+ )
+ ) : null}
+
+ )
+}
+
+function Chip({ tone, children }: { tone: 'accent' | 'danger' | 'muted'; children: React.ReactNode }): JSX.Element {
+ return (
+
+ {children}
+
+ )
+}
+
+function DisableKeyDialog({ row, label, onClose, onDone }: { row: KeyRow; label: string; onClose: () => void; onDone: () => void }): JSX.Element {
+ const { identity, controller, isLoading } = useAuth()
+ const master = useMasterKeyInput(identity, { id: 'disable-key', fileLabel: 'Identity file to disable the key with' })
+ const [submitError, setError] = useState(null)
+ const error = master.error ?? submitError
+ const name = label ? `key #${row.keyId} (${label})` : `key #${row.keyId}`
+ const submit = async (): Promise => {
+ if (!master.ready || isLoading) return
+ setError(null)
+ try {
+ await controller.disableIdentityKey(master.take({ keep: true }), row.keyId)
+ master.clear()
+ onDone()
+ } catch (e) {
+ if (!(e instanceof WrongMasterKeyError || e instanceof IdentityUpdateNotSentError)) master.clear()
+ setError(errorMessage(e))
+ }
+ }
+ return (
+
+
+
+ )
+}
+
+/** The rekey command (private-repos.md §5.2), run where the recovery words are. */
+const ENCRYPTION_ROTATE_COMMAND = 'dg auth keys rotate --encryption'
+
+/** What to do when a device is lost: its signing key, then the encryption key it held. */
+function LostDevice(): JSX.Element {
+ const [copied, copy] = useCopy(ENCRYPTION_ROTATE_COMMAND)
+ return (
+
+
+ Lost a device?
+
+
+ Disable its key above. It can no longer write as you.
+
+ If it could open your private repos, it also held your encryption key. Replace that key in a terminal, with your recovery phrase:{' '}
+
+ {ENCRYPTION_ROTATE_COMMAND}
+ void copy()}
+ className="hit-area text-anvil-500 hover:text-anvil-800 dark:text-anvil-400 dark:hover:text-anvil-100"
+ aria-label="Copy the command"
+ >
+
+
+
+ {copied ? ' Copied.' : null}
+
+ It adds a new key, moves the private repos you maintain to it and names the ones a maintainer must move, then disables the old key. The
+ browser can't do this yet.
+
+
+ On your other devices, sign in again or add the new encryption key from your recovery phrase (Settings → Private repos).
+
+
+ What replacing the encryption key does →
+
+
+ )
+}
+
+/** This browser: whether its storage is kept (TS-17), and when it last wrote. */
+function ThisBrowser({ identity }: { identity: string }): JSX.Element {
+ const [persistence, setPersistence] = useState(null)
+ const [lastWrite, setLastWrite] = useState(null)
+ useEffect(() => {
+ void storagePersistence().then(setPersistence)
+ readLedger(ACTIVE_NETWORK.network, identity).then(
+ (rows) => setLastWrite(rows.reduce((m, r) => (m === null || r.at > m ? r.at : m), null)),
+ () => undefined,
+ )
+ }, [identity])
+ return (
+
+
+ This browser
+
+ Last write from this browser: {lastWrite === null ? 'none recorded' : formatDate(lastWrite)}
+
+ Storage:{' '}
+ {persistence === 'persistent'
+ ? 'kept. The browser will not clear your key on its own.'
+ : persistence === 'may-clear'
+ ? 'may be cleared. The browser can delete your stored key under storage pressure, and Safari does after 7 days without a visit.'
+ : persistence === 'unknown'
+ ? "this browser doesn't say whether it keeps it."
+ : 'checking…'}
+
+ {persistence === 'may-clear' ? (
+
+ void requestPersistence().then(setPersistence)} data-testid="storage-persist">
+ Ask the browser to keep it
+
+ If it is cleared, sign in again with dg, your identity file or your recovery phrase.
+
+ ) : null}
+
+ )
+}
diff --git a/forge-web/components/encryption-key-panel.tsx b/forge-web/components/encryption-key-panel.tsx
index 70c7812f4..983825090 100644
--- a/forge-web/components/encryption-key-panel.tsx
+++ b/forge-web/components/encryption-key-panel.tsx
@@ -39,6 +39,7 @@ import { Button } from '@/components/ui/button'
import { UnlockMore } from '@/components/auth/unlock-more'
import { Field, Input, Textarea } from '@/components/ui/input'
import { useConfirmAction } from '@/components/ui/confirm-action'
+import { PhraseWarning } from '@/components/auth/phrase-warning'
type Mode = 'phrase' | 'file' | 'paste' | 'register'
@@ -160,6 +161,8 @@ export function EncryptionKeyPanel(): JSX.Element | null {
keyId = r.keyId
return r.registered
})
+ // Added here: the new-key alert does not name it on the next sign-in.
+ controller.noteOwnKey(identity, keyId)
return keyId
})
}
@@ -230,6 +233,7 @@ export function EncryptionKeyPanel(): JSX.Element | null {
{mode === 'phrase' ? (
+
Only for an identity with no encryption key yet. If yours has one, use Recovery phrase above: it is free.
+
> = {
'waiting-deposit': 'Watching for your deposit…',
@@ -229,6 +230,7 @@ export function IdentityTopUpFlow({ faucet }: { faucet: string | null }): JSX.El
finish it.
) : null}
+
>
)}
+ {storage !== 'session' ? (
+
+
+ Devices & keys
+
+ : every key on your identity. Disable a lost device's key there.
+
+ ) : null}
{topUpOpen ? setTopUpOpen(false)} /> : null}
{revokeOpen ? setRevokeOpen(false)} /> : null}
{confirmDialog}
diff --git a/forge-web/components/login-modal.tsx b/forge-web/components/login-modal.tsx
index c9e0bc5fb..fdde9edcb 100644
--- a/forge-web/components/login-modal.tsx
+++ b/forge-web/components/login-modal.tsx
@@ -19,7 +19,7 @@
import { useCallback, useEffect, useRef, useState } from 'react'
import Link from 'next/link'
-import { ArrowLeft, Fingerprint, KeyRound, Lock, Plus, RotateCw, Upload, Wallet } from 'lucide-react'
+import { ArrowLeft, Fingerprint, KeyRound, Lock, Plus, RotateCw, SquareTerminal, Upload, Wallet } from 'lucide-react'
import { useAuth } from '@/contexts/auth-context'
import { useUiStore, type LoginView } from '@/hooks/use-ui-store'
import { Dialog } from '@/components/ui/dialog'
@@ -28,6 +28,9 @@ import { Field, Input, Textarea } from '@/components/ui/input'
import { ErrorBox, GroupNotice, useProtection } from '@/components/auth/protection-fields'
import { CreateIdentityFlow } from '@/components/auth/create-identity-flow'
import { WalletConnectFlow } from '@/components/auth/wallet-connect-flow'
+import { DgHandoffFlow, type HandoffTarget } from '@/components/auth/dg-handoff-flow'
+import { KeyLifetimeSelect } from '@/components/auth/key-lifetime'
+import { PhraseWarning } from '@/components/auth/phrase-warning'
import { StepFailed } from '@/components/auth/step-status'
import { forgetConfirm } from '@/components/keys-panel'
import { otherIdentityFileMessage } from '@/lib/auth/controller'
@@ -35,7 +38,7 @@ import { useConfirmAction } from '@/components/ui/confirm-action'
import { ACTIVE_NETWORK, networkName } from '@/lib/constants'
import { GRANT_COPY } from '@/lib/auth/key-registration'
import { NotDeployedState } from '@/components/ui/network-badge'
-import { BROWSER_KEY_DEFAULTS, masterMaterialFromFile } from '@/lib/auth'
+import { BROWSER_KEY_DEFAULTS, lifetimeLabel, limitsFor, masterMaterialFromFile, type VaultInfo } from '@/lib/auth'
import { AlreadyStoredError, UnlockNeededError } from '@/lib/auth/controller'
import { UnlockMore } from '@/components/auth/unlock-more'
import { Spinner } from '@/components/ui/states'
@@ -65,6 +68,8 @@ export function LoginModal(): JSX.Element {
const { vaults, vaultsLoaded, vaultsError, reloadVaults, limitedKeys } = useAuth()
const [view, setView] = useState(null)
const [unlockFor, setUnlockFor] = useState(null)
+ // The locked key a dg handoff replaces (Unlock → "Replace this key with dg").
+ const [dgReplace, setDgReplace] = useState(null)
const hasVault = vaults.length > 0
// Pick the view when the sheet opens: once the stored-key list has been read, so a returning
@@ -86,6 +91,7 @@ export function LoginModal(): JSX.Element {
opened.current = { hasVault }
setView(requested ?? (hasVault ? 'unlock' : 'choose'))
setUnlockFor(null)
+ setDgReplace(null)
return
}
if (!opened.current.hasVault && hasVault && requested === null) {
@@ -100,6 +106,11 @@ export function LoginModal(): JSX.Element {
if (open && view === 'unlock' && vaultsLoaded && !vaultsError && !hasVault) setView('choose')
}, [open, view, vaultsLoaded, vaultsError, hasVault])
+ // A key this device already holds: unlock it instead.
+ const toUnlock = (id: string): void => {
+ setUnlockFor(id)
+ setView('unlock')
+ }
const back = view === null || view === 'choose' || view === 'unlock' || view === 'grant' || view === 'renew' ? null : () => setView('choose')
// Before the stored-key list is read (a few ms, or storage blocked): the Unlock line, the
// likelier view for someone opening the sheet on a device that holds a key.
@@ -107,7 +118,17 @@ export function LoginModal(): JSX.Element {
// A write asked for the sheet: say which, and what it costs once signed in (L-62).
// Creating an identity is sign-up, and says so on every step (QW4-022), as GitHub's "Create your account" does.
const title =
- view === 'grant' ? grantTitle : view === 'renew' ? "Renew this browser's key" : view === 'create' ? 'Create your identity' : intent ? `Sign in to ${intent.action}` : 'Sign in to Dash Forge'
+ view === 'grant'
+ ? grantTitle
+ : view === 'renew'
+ ? "Renew this browser's key"
+ : view === 'create'
+ ? 'Create your identity'
+ : view === 'dg'
+ ? 'Sign in with dg'
+ : intent
+ ? `Sign in to ${intent.action}`
+ : 'Sign in to Dash Forge'
return (
@@ -132,22 +153,38 @@ export function LoginModal(): JSX.Element {
) : null}
{view === null && !vaultsError ? : null}
- {view === 'unlock' ? setView('choose')} onRenew={() => setView('import')} /> : null}
- {view === 'choose' ? : null}
+ {view === 'unlock' ? (
+ setView('choose')}
+ onRenew={(v) => {
+ // A key that came from dg is replaced with dg: the recovery phrase is not asked for.
+ setDgReplace(v?.fromDg === true ? { identityId: v.identityId, keyId: v.keyId } : null)
+ setView(v?.fromDg === true ? 'dg' : 'import')
+ }}
+ />
+ ) : null}
+ {view === 'choose' ? (
+ {
+ setDgReplace(null)
+ setView(v)
+ }}
+ />
+ ) : null}
{view === 'import' || view === 'renew' ? (
limitedKeys ? (
- {
- setUnlockFor(id)
- setView('unlock')
- }}
- />
+ view === 'renew' ? (
+
+ ) : (
+
+ )
) : (
)
) : null}
+ {view === 'dg' ? limitedKeys ? : : null}
{view === 'create' ? : null}
{view === 'wallet' ? : null}
{view === 'grant' ? : null}
@@ -161,8 +198,9 @@ function describeView(view: View, limitedKeys: boolean): string {
if (view === 'advanced') return 'A pasted key signs for this tab only, with whatever power it has.'
if (view === 'wallet' || view === 'grant') return 'Your wallet sends this browser a key it derives for Dash Forge. Your recovery phrase and master key stay on the phone.'
if (!limitedKeys) return `Dash Forge isn't available on ${networkName()} yet, so there's nothing to sign in to here.`
- const limits = `at most ${BROWSER_KEY_DEFAULTS.budgetDash} DASH, only on Forge, for ${BROWSER_KEY_DEFAULTS.days} days`
+ const limits = `at most ${BROWSER_KEY_DEFAULTS.budgetDash} DASH, only on Forge, for up to a year`
if (view === 'renew') return `A new key for this browser (${limits}) replaces the current one, which is disabled in the same update.`
+ if (view === 'dg') return `dg registers a limited key for this browser (${limits}). Your recovery phrase stays out of the browser.`
if (view === 'create' || view === 'import') return `Forge signs with a limited key: ${limits}.`
if (view === 'unlock') return 'Unlock the key this browser already holds.'
// The tile list: a wallet's key comes with no limits (docs/design/wallet-login.md).
@@ -273,6 +311,14 @@ function ChooseView({ onPick }: { onPick: (v: View) => void }): JSX.Element {
onClick={() => onPick('import')}
pausedReason={pausedReason}
/>
+ onPick('dg')}
+ pausedReason={pausedReason}
+ />
{walletFirst ? null : walletTile}
setAdvanced((a) => !a)} className="hit-area text-[12px] text-anvil-500 dark:text-anvil-400 underline hover:text-anvil-800 dark:hover:text-anvil-100">
@@ -369,7 +415,17 @@ function FilePicker({ label, detail, onFile, disabled }: { label: string; detail
)
}
-function UnlockView({ initial, onDone, onOther, onRenew }: { initial: string | null; onDone: () => void; onOther: () => void; onRenew: () => void }): JSX.Element {
+function UnlockView({
+ initial,
+ onDone,
+ onOther,
+ onRenew,
+}: {
+ initial: string | null
+ onDone: () => void
+ onOther: () => void
+ onRenew: (v?: VaultInfo) => void
+}): JSX.Element {
const { vaults, unlock, forget, isLoading, step, lastIdentity } = useAuth()
const [confirm, confirmDialog] = useConfirmAction()
// The identity asked for, else the one signed in last (QW2-025), as an account switcher does.
@@ -457,7 +513,7 @@ function UnlockView({ initial, onDone, onOther, onRenew }: { initial: string | n
) : null}
{expired ? (
-
+ onRenew(v)}>
Renew this browser's key
) : null}
@@ -465,8 +521,8 @@ function UnlockView({ initial, onDone, onOther, onRenew }: { initial: string | n
registers a new key for this browser and disables the one it cannot open. */}
{v.methods.includes('passphrase') ? 'Forgot the passphrase' : 'Lost the passkey'}?{' '}
-
- Replace this key with your recovery phrase or identity file
+ onRenew(v)} className="hit-area text-forge-700 underline dark:text-forge-400">
+ {v.fromDg ? 'Replace this key with dg' : 'Replace this key with your recovery phrase or identity file'}
@@ -495,6 +551,41 @@ function UnlockView({ initial, onDone, onOther, onRenew }: { initial: string | n
)
}
+/**
+ * Renew: with `dg` (no recovery phrase in the browser) or with the identity file or phrase. A key
+ * that came from `dg` renews with `dg` by default (TS-06), so the phrase is asked for only when
+ * the user picks it.
+ */
+function RenewView({ onDone, onStored }: { onDone: () => void; onStored: (identityId: string) => void }): JSX.Element {
+ const { vaults, identity } = useAuth()
+ const fromDg = vaults.find((v) => v.identityId === identity)?.fromDg === true
+ const [how, setHow] = useState<'dg' | 'master'>(fromDg ? 'dg' : 'master')
+ const options = [
+ ['dg', 'With dg'],
+ ['master', 'With identity file or phrase'],
+ ] as const
+ return (
+
+
+ {options.map(([m, label]) => (
+ setHow(m)}
+ className={cn('rounded px-3 py-1.5 text-dense font-medium coarse:min-h-11', how === m ? 'bg-forge-500/15 text-forge-800 dark:text-forge-400' : 'text-anvil-500 dark:text-anvil-400')}
+ >
+ {label}
+
+ ))}
+
+ {how === 'dg' ?
:
}
+
+ )
+}
+
function ImportView({ onDone, onStored, renew = false }: { onDone: () => void; onStored: (identityId: string) => void; renew?: boolean }): JSX.Element {
const { importIdentity, isLoading, step, vaults, identity, controller, unlockScope, storage, keyId } = useAuth()
const wantsPrivate = useUiStore((s) => s.loginIntent?.privateRepo === true)
@@ -525,6 +616,7 @@ function ImportView({ onDone, onStored, renew = false }: { onDone: () => void; o
// A renewal is of the signed-in identity's key: its words are checked against it (QW3-031).
const [identityId, setIdentityId] = useState(renew && identity !== null ? identity : '')
const [error, setError] = useState
(null)
+ const [days, setDays] = useState(BROWSER_KEY_DEFAULTS.days)
// Errors show beside the button that caused them, scrolled into view: in a tall sheet the
// button can sit at the bottom edge of a phone (or a 800 px laptop) screen.
const errorRef = useRef(null)
@@ -598,7 +690,7 @@ function ImportView({ onDone, onStored, renew = false }: { onDone: () => void; o
try {
const text = fileRef.current
if (mode === 'file' && text === null) return
- await importIdentity(mode === 'file' ? { fileText: text as string } : { mnemonic, identityId }, protection, undefined, {
+ await importIdentity(mode === 'file' ? { fileText: text as string } : { mnemonic, identityId }, protection, limitsFor(days), {
enablePrivateRepos: enablePrivate && !carriesEncryption,
// Signed in as the identity being imported: this is a renewal of its key.
renew: identity !== null,
@@ -654,6 +746,7 @@ function ImportView({ onDone, onStored, renew = false }: { onDone: () => void; o
/>
) : (
<>
+
{/* Uncontrolled: a controlled textarea's value is also its DOM text content. */}
) : null}
{fields}
+
{carriesEncryption ? (
Private repos stay enabled. {' '}
@@ -754,7 +848,7 @@ function ImportView({ onDone, onStored, renew = false }: { onDone: () => void; o
)}
- {renew && keyId !== null ? `Disables key #${keyId} and registers` : 'Registers'} a key that can spend at most {BROWSER_KEY_DEFAULTS.budgetDash} DASH, only on Forge, for {BROWSER_KEY_DEFAULTS.days} days
+ {renew && keyId !== null ? `Disables key #${keyId} and registers` : 'Registers'} a key that can spend at most {BROWSER_KEY_DEFAULTS.budgetDash} DASH, only on Forge, for {lifetimeLabel(days)}
{renewing
? ` (renewing: ~${creditsAsDash(KEY_RENEW_CREDITS)} DASH, one master-key signature; the old key is disabled in the same update).`
: // Platform meters the update: an identity that already holds a Forge key (from another
diff --git a/forge-web/components/new-key-alert.tsx b/forge-web/components/new-key-alert.tsx
new file mode 100644
index 000000000..31e5f135a
--- /dev/null
+++ b/forge-web/components/new-key-alert.tsx
@@ -0,0 +1,43 @@
+'use client'
+
+/**
+ * The new-key alert (TS-07): a key was added to the signed-in identity since this device last
+ * looked, and this device did not add it. Whoever holds the master key or the recovery phrase
+ * can add keys, so a key nobody here expected is the first sign of a leak. "It was me" stops the
+ * alert for these keys; Review opens Devices & keys, where any of them can be disabled.
+ */
+
+import Link from 'next/link'
+import { ShieldAlert } from 'lucide-react'
+import { useAuth } from '@/contexts/auth-context'
+import { Button, buttonClass } from '@/components/ui/button'
+import { keyKind } from '@/lib/auth/key-watch'
+
+export function NewKeyAlert(): JSX.Element | null {
+ const { newKeys, controller } = useAuth()
+ if (newKeys.length === 0) return null
+ const one = newKeys.length === 1
+ const list = newKeys.map((k) => `#${k.keyId} (${keyKind(k)})`).join(', ')
+ const master = newKeys.some((k) => k.level === 0)
+ return (
+
+
+
+
+ {one ? 'A key was' : `${newKeys.length} keys were`} added to your identity since this device last checked: {list}.{' '}
+ {master
+ ? 'A new master key means someone else may control your identity.'
+ : `If you didn't add ${one ? 'it' : 'them'} yourself, with dg or in another browser, disable ${one ? 'it' : 'them'} now.`}
+
+
+
+ Review keys
+
+ controller.acknowledgeNewKeys()} data-testid="new-key-mine">
+ It was me
+
+
+
+
+ )
+}
diff --git a/forge-web/contexts/auth-context.tsx b/forge-web/contexts/auth-context.tsx
index 24d2215d6..373896071 100644
--- a/forge-web/contexts/auth-context.tsx
+++ b/forge-web/contexts/auth-context.tsx
@@ -9,6 +9,8 @@
* spend ledger, a toast shows what it actually cost, and the balance is re-read.
*/
+import type { HandoffRequest } from '@/lib/auth/key-handoff'
+import type { WatchedKey } from '@/lib/auth/key-watch'
import React, { createContext, useCallback, useContext, useEffect, useMemo, useRef, useState } from 'react'
import {
@@ -99,6 +101,8 @@ interface AuthContextValue {
* unlock; null when signed out.
*/
readonly unlockScope: 'full' | 'signing' | null
+ /** Keys added to the identity since this device last looked, other than its own (the new-key alert). */
+ readonly newKeys: readonly WatchedKey[]
/** The limited-key ceremony: import an identity file or a mnemonic once. */
importIdentity: (
input: { fileText: string } | { mnemonic: string; identityId: string },
@@ -107,6 +111,8 @@ interface AuthContextValue {
options?: { readonly enablePrivateRepos?: boolean; readonly renew?: boolean },
) => Promise
adoptLimitedKey: (identityId: string, key: LimitedKey, protection: Protection) => Promise
+ /** Keep the key `dg auth keys add --for-browser` sealed to this tab's request (`lib/auth/key-handoff`). */
+ adoptHandoffKey: (reply: string, request: HandoffRequest, protection: Protection, options?: { readonly renew?: boolean }) => Promise
/** Store the keys a wallet granted (verified on chain) and open the session. */
adoptWalletKeys: (identityId: string, keys: readonly WalletKey[], protection: Protection, options?: Parameters[3]) => Promise
/** Add a wallet grant for another Forge contract to the signed-in identity. */
@@ -134,6 +140,8 @@ interface AuthContextValue {
readonly controller: AuthController
}
+const NO_KEYS: readonly WatchedKey[] = []
+
const AuthContext = createContext(undefined)
export function AuthProvider({
@@ -214,6 +222,7 @@ export function AuthProvider({
() => ({
importIdentity: withReload(controller.importIdentity.bind(controller)),
adoptLimitedKey: withReload(controller.adoptLimitedKey.bind(controller)),
+ adoptHandoffKey: withReload(controller.adoptHandoffKey.bind(controller)),
adoptWalletKeys: withReload(controller.adoptWalletKeys.bind(controller)),
addWalletGrant: withReload(controller.addWalletGrant.bind(controller)),
unlock: withReload(controller.unlock.bind(controller)),
@@ -317,11 +326,12 @@ export function AuthProvider({
lastIdentity,
lockedIdentity: locked ? lockedIdentityOf(vaults, lastIdentity) : null,
unlockScope: session === null ? null : state.scope ?? null,
+ newKeys: session === null ? NO_KEYS : state.newKeys ?? NO_KEYS,
reloadVaults,
controller,
...actions,
}),
- [actions, controller, funds, keyLimits, lastIdentity, locked, reloadVaults, resuming, session, signer, state.error, state.isLoading, state.scope, state.step, vaults, vaultsError, vaultsLoaded],
+ [actions, controller, funds, keyLimits, lastIdentity, locked, reloadVaults, resuming, session, signer, state.error, state.isLoading, state.newKeys, state.scope, state.step, vaults, vaultsError, vaultsLoaded],
)
return {children}
diff --git a/forge-web/hooks/use-ui-store.ts b/forge-web/hooks/use-ui-store.ts
index 12d44a4ad..09e9f86c1 100644
--- a/forge-web/hooks/use-ui-store.ts
+++ b/forge-web/hooks/use-ui-store.ts
@@ -18,7 +18,7 @@ export type { TopUpReason }
* as a renewal of the signed-in identity's key, QW3-031; `grant` asks the signed-in identity's
* wallet for a key on the contract named with it, when the session lacks one).
*/
-export type LoginView = 'import' | 'renew' | 'create' | 'wallet' | 'grant' | 'unlock'
+export type LoginView = 'import' | 'renew' | 'create' | 'wallet' | 'grant' | 'unlock' | 'dg'
/**
* What a signed-out click asked to do (L-62): the sheet says "Sign in to star this repo" and what
diff --git a/forge-web/lib/auth/auth-v2.test.ts b/forge-web/lib/auth/auth-v2.test.ts
index be995c754..9bc849134 100644
--- a/forge-web/lib/auth/auth-v2.test.ts
+++ b/forge-web/lib/auth/auth-v2.test.ts
@@ -10,6 +10,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { idbEntries, resetMemoryStores } from '../idb'
import {
+ VaultChangedError,
VaultLockedError,
forgetVault,
listVaults,
@@ -57,6 +58,18 @@ describe('vault', () => {
expect(unlockedSecret('devnet', ID)).toBeNull()
}, 60_000)
+ it('refuses to store when another tab stored a key after the caller looked (CodeRabbit, PR #375)', async () => {
+ const protection = { passphrase: 'correct horse battery' }
+ // The caller saw no key, but one is there by the time it writes: nothing changes.
+ await storeInVault('devnet', SECRET, protection)
+ await expect(storeInVault('devnet', { ...SECRET, keyId: 6 }, protection, { expectHeldKeyId: null })).rejects.toBeInstanceOf(VaultChangedError)
+ expect((await listVaults('devnet')).map((v) => v.keyId)).toEqual([5])
+ expect(unlockedSecret('devnet', ID)?.keyId).toBe(5)
+ // The caller saw key 5 and it is still there: the write goes ahead.
+ await storeInVault('devnet', { ...SECRET, keyId: 6 }, protection, { expectHeldKeyId: 5 })
+ expect((await listVaults('devnet')).map((v) => v.keyId)).toEqual([6])
+ }, 60_000)
+
it('refuses short passphrases and an unprotected vault', async () => {
await expect(storeInVault('devnet', SECRET, { passphrase: 'short' })).rejects.toThrow(/at least/)
await expect(storeInVault('devnet', SECRET, {})).rejects.toThrow(/passphrase or a passkey/)
diff --git a/forge-web/lib/auth/controller.ts b/forge-web/lib/auth/controller.ts
index fff99b256..ac7640d02 100644
--- a/forge-web/lib/auth/controller.ts
+++ b/forge-web/lib/auth/controller.ts
@@ -33,7 +33,7 @@ import { DEPLOYMENTS, FORGE_CONTRACT_KINDS, contractKind, groupTrust, type Forge
import { assertGroupHolds, type GroupCheck } from './group-trust'
import { SECURITY_LEVEL, WriteAuthError, assertWritesAllowed, balanceBeforeWrite, findSigningKey, measureActual, readIdentityBalance, serialized, type SpendEvent, type WriteAuth } from '../sdk/write'
import { KEY_ADD_FLOOR_CREDITS, KEY_DISABLE_CREDITS, KEY_LIMITS_UPDATE_CREDITS, KEY_REGISTER_CREDITS, KEY_RENEW_CREDITS } from '../sdk/cost'
-import { authSdk, type WasmIdentity } from '../sdk/facade'
+import { authSdk, type WasmIdentity, type WasmKey } from '../sdk/facade'
import type { HeldBrowserKey } from './create-identity'
import type { KeyLimits } from '../view/funds'
import { controlsKey, normalizeToWif } from './wif'
@@ -49,12 +49,18 @@ import { clearInbox } from '../view/inbox'
import { clearDrafts } from '../view/draft-text'
import { forgetLastIdentity, rememberLastIdentity } from './last-identity'
import { checkWalletKey, hasNoLimits, isForgeContract, keyScope, scopeCovers, type KeyScope, type WalletKey } from './key-registration'
-import { PRIVATE_REPOS_FLOW, encryptionMaterialFromFile, importEncryptionKey, wipeMaterial, type EncryptionMaterial } from './encryption-key'
+import { PRIVATE_REPOS_FLOW, adoptEncryptionKey, encryptionMaterialFromFile, importEncryptionKey, wipeMaterial, type EncryptionMaterial } from './encryption-key'
+import { openHandoffReply, parseHandoffPayload, type HandoffRequest } from './key-handoff'
+import { acknowledgeKeys, checkKeys, forgetKeySnapshot, type WatchedKey } from './key-watch'
+import { DISABLEABLE, keyRole, keyRows, type KeyRow } from './devices'
+import { hexToBytes } from '@noble/hashes/utils.js'
import {
WrongMasterKeyError,
disableHeldKeys,
+ disableIdentityKeys,
isForgeBrowserKey,
readKeyLimits,
+ verifyLimitedKey,
registerLimitedKey,
revokeLimitedKey,
topUpLimitedKey,
@@ -86,6 +92,7 @@ import {
watchOtherTabs,
clearSignedWrites,
storeInVault,
+ VaultChangedError,
stageInVault,
hasStaged,
recoverStaged,
@@ -106,6 +113,11 @@ import {
type VaultSecret,
} from './vault'
+/** A chain key as the new-key alert reads it. */
+function watched(k: WasmKey): WatchedKey {
+ return { keyId: k.keyId, purpose: k.purposeNumber, level: k.securityLevelNumber, disabled: k.disabledAt !== undefined }
+}
+
/** The notice when a renewal could not carry the encryption key over. */
const ENCRYPTION_KEY_DROPPED =
'Your encryption key for private repos was sealed with the previous key, which was locked when you renewed it, so it was not carried over. Add it again in Settings → Private repos.'
@@ -183,6 +195,11 @@ export interface AuthState {
* (public-repo writes only), `full` after an interactive unlock; null when signed out.
*/
readonly scope?: 'full' | 'signing' | null
+ /**
+ * Keys added to the signed-in identity since this device last looked, other than its own
+ * (`./key-watch`, TS-07): a leaked master key shows up as a key nobody here added.
+ */
+ readonly newKeys?: readonly WatchedKey[]
}
type Listener = (state: AuthState) => void
@@ -556,7 +573,14 @@ export class AuthController {
* Open a session for an unlocked secret: re-verify the key on chain, load balance + limits.
* On failure the unlocked key is dropped again, so no key sits in memory without a session.
*/
- private async open(secret: VaultSecret, storage: AuthSession['storage'], knownLimits?: KeyLimits, releaseOnFailure = true): Promise {
+ private async open(
+ secret: VaultSecret,
+ storage: AuthSession['storage'],
+ knownLimits?: KeyLimits,
+ releaseOnFailure = true,
+ /** Keys a wallet just registered for this browser: each came with its encryption key. */
+ walletKeys: readonly number[] = [],
+ ): Promise {
const generation = vaultLockGeneration()
try {
const sdk = await this.getSdk()
@@ -589,7 +613,12 @@ export class AuthController {
}
// Locked (here or in another tab) while this ran: the lock wins.
if (generation !== vaultLockGeneration()) throw new VaultLockedError('this browser locked while signing in — unlock to continue')
- this.setState({ session, scope: unlockScope(this.network, secret.identityId) })
+ // The identity just read is compared with what this device saw last: no read of its own.
+ // A wallet registers its encryption key in the same update, right after the auth key.
+ const companions = walletKeys.filter((id) => identity.publicKeys.some((k) => k.keyId === id + 1 && k.purposeNumber === 1)).map((id) => id + 1)
+ const own = [match.keyId, ...(secret.extra ?? []).map((e) => e.keyId), ...companions]
+ const newKeys = storage === 'vault' ? checkKeys(this.network, secret.identityId, identity.publicKeys.map(watched), own) : []
+ this.setState({ session, scope: unlockScope(this.network, secret.identityId), newKeys })
if (storage === 'vault') void this.keep(session).catch(() => undefined)
return session
} catch (e) {
@@ -759,10 +788,11 @@ export class AuthController {
* Move a registered key into the vault's main record. Registered and staged (D-016) but not
* moved: the key is safe on this device, and the next unlock finishes the move.
*/
- private async commitKey(secret: VaultSecret, protection: Protection): Promise {
+ private async commitKey(secret: VaultSecret, protection: Protection, options: Parameters[3] = {}): Promise {
try {
- return await storeInVault(this.network, secret, protection)
+ return await storeInVault(this.network, secret, protection, options)
} catch (e) {
+ if (e instanceof VaultChangedError) throw e
if (await hasStaged(this.network, secret.identityId).catch(() => false)) {
throw new Error(`The new key is registered and saved on this device, but finishing sign-in failed (${errorMessage(e)}). Unlock to continue.`)
}
@@ -956,6 +986,97 @@ export class AuthController {
}
}
+ /**
+ * Adopt the limited key `dg auth keys add --for-browser` sealed to `request` (TS-06,
+ * `./key-handoff`): open the reply, check the key on chain (live, Forge-bound, limited, and
+ * controlled by the private key it carries) before anything is stored, then keep it in the
+ * vault like an imported key. Nothing is signed here: dg paid for and registered the key.
+ * Renewing (`renew`) takes only a key for the signed-in identity, and `identityId` (the key
+ * the page asked dg to replace) only a key for that identity.
+ */
+ async adoptHandoffKey(reply: string, request: HandoffRequest, protection: Protection, options: { readonly renew?: boolean; readonly identityId?: string } = {}): Promise {
+ return this.run(async () => {
+ const network = NETWORKS[this.network].key
+ const payload = parseHandoffPayload(await openHandoffReply(reply, network, request.secret), network)
+ const { identityId } = payload
+ const signedIn = this.state.session?.identityId ?? null
+ if (options.renew === true && signedIn !== null && identityId !== signedIn) {
+ throw new WriteAuthError(`dg made this key for ${shortId(identityId)}, but you are renewing the key of ${shortId(signedIn)}. Sign dg in as ${shortId(signedIn)} (or pass --master with its identity file) and run the command again.`)
+ }
+ if (options.identityId !== undefined && identityId !== options.identityId) {
+ throw new WriteAuthError(
+ `dg made this key for ${shortId(identityId)}, but this page asked for one for ${shortId(options.identityId)}. Nothing was stored. Disable the new key with "dg auth keys disable ${payload.keyId}", then run the command shown here again.`,
+ )
+ }
+ this.requireFullUnlock(identityId)
+ const sdk = await this.getSdk()
+ // A key this browser holds for the identity must be the one dg replaced: otherwise it
+ // would stay live on chain with nothing holding it. Checked before anything is stored.
+ const previous = (await listVaults(this.network)).find((v) => v.identityId === identityId && v.staged !== true)
+ if (previous !== undefined && payload.replacedKeyId !== previous.keyId) {
+ throw new WriteAuthError(
+ `This browser already holds key #${previous.keyId} for ${shortId(identityId)}, and dg did not disable it. Nothing was stored. Disable the new key with "dg auth keys disable ${payload.keyId}", then renew from Settings (or Unlock → Replace this key with dg).`,
+ )
+ }
+ const blocker = previous !== undefined ? await this.handoffBlocker(identityId) : null
+ if (blocker !== null) throw new WriteAuthError(`${blocker} Nothing was stored; disable the new key with "dg auth keys disable ${payload.keyId}".`)
+ this.step('Checking the key on Platform')
+ let limits: KeyLimits
+ try {
+ limits = await verifyLimitedKey(sdk, identityId, payload.keyId, this.group(), this.network, payload.wif)
+ } catch (e) {
+ throw new WriteAuthError(`This key can't be used here: ${errorMessage(e)}. Nothing was stored.`)
+ }
+ this.step(protection.passkey ? 'Saving the key with your passkey' : 'Saving the key in this browser')
+ const key: LimitedKey = { keyId: payload.keyId, wif: payload.wif, limits }
+ // Checked again in the vault write's own transaction: another tab may have stored a key
+ // for the identity since `previous` was read.
+ let committed: StoreOutcome
+ try {
+ committed = await this.commitKey({ identityId, keyId: key.keyId, wif: key.wif }, protection, { origin: 'dg', expectHeldKeyId: previous?.keyId ?? null })
+ } catch (e) {
+ if (!(e instanceof VaultChangedError)) throw e
+ throw new WriteAuthError(`Another tab changed the key stored for ${shortId(identityId)} meanwhile. Nothing was stored; disable the new key with "dg auth keys disable ${payload.keyId}".`)
+ }
+ const core = NETWORKS[this.network].v2?.core
+ const bringsEncryption = payload.encryptionKey !== undefined && core !== undefined
+ // A reply that brings the encryption key again: the copy the replacement could not carry
+ // over is reported only if that one cannot be kept either (below).
+ const session = await this.adopt(identityId, key, protection, bringsEncryption ? { ...committed, encryptionKeyDropped: false } : committed)
+ if (bringsEncryption && payload.encryptionKey !== undefined && core !== undefined) {
+ this.step('Enabling private repos')
+ try {
+ await adoptEncryptionKey(sdk, this.network, identityId, core, hexToBytes(payload.encryptionKey.privateKeyHex))
+ } catch (e) {
+ const dropped = committed.encryptionKeyDropped ? ` ${ENCRYPTION_KEY_DROPPED}` : ''
+ this.setState({ notice: `Signed in, but private repos could not be enabled: ${errorMessage(e)}.${dropped}` })
+ }
+ }
+ // Kept: the request is spent. Until then a failed check can be retried with the same reply.
+ request.wipe()
+ return session
+ })
+ }
+
+ /**
+ * Why a key from dg can't replace the key this browser holds for `identityId`, or null: dg
+ * disables one Forge limited key by id, so wallet keys (the main key, or grants beside it)
+ * would stay live after this device forgets them. Those renew with the identity file or phrase.
+ */
+ async handoffBlocker(identityId: string): Promise {
+ const stored = (await listVaults(this.network)).find((v) => v.identityId === identityId && v.staged !== true)
+ if (stored === undefined) return null
+ let wallet = await hasExtraKeys(this.network, identityId)
+ if (!wallet) {
+ const identity = await authSdk(await this.getSdk()).identities.fetch(identityId)
+ const k = identity?.publicKeys.find((x) => x.keyId === stored.keyId)
+ wallet = k !== undefined && k.disabledAt === undefined && !isForgeBrowserKey(k)
+ }
+ return wallet
+ ? 'This browser holds wallet keys for this identity, which a key from dg cannot disable. Replace them with your identity file or recovery phrase instead, so they are disabled in the same update.'
+ : null
+ }
+
/** Adopt a limited key obtained elsewhere (identity creation). */
async adoptLimitedKey(identityId: string, key: LimitedKey, protection: Protection): Promise {
return this.run(() => this.adopt(identityId, key, protection))
@@ -1033,7 +1154,7 @@ export class AuthController {
'Your storage settings could not be carried over to the new key. Add your storage again in Settings → Storage.',
)
try {
- return await this.open(secret, 'vault', main.limits ?? undefined)
+ return await this.open(secret, 'vault', main.limits ?? undefined, true, [main.keyId, ...rest.map((k) => k.keyId)])
} catch (e) {
throw new Error(`Key saved on this device, but signing in did not finish (${errorMessage(e)}). Unlock to continue.`)
}
@@ -1056,7 +1177,7 @@ export class AuthController {
const secret = unlockedSecret(this.network, identityId)
if (!secret) throw new VaultLockedError('unlock to continue')
try {
- const opened = await this.open(secret, 'vault', session.keyLimits ?? undefined, false)
+ const opened = await this.open(secret, 'vault', session.keyLimits ?? undefined, false, [key.keyId])
const want = contractKind(forge, requested)
if (want === null || !opened.grants?.[want]) throw new Error('the granted key is not live on the identity yet')
return opened
@@ -1374,11 +1495,13 @@ export class AuthController {
if (!identityId) throw new Error('sign in first')
const masterWif = await this.masterWifFor(identityId, input)
const sdk = await this.getSdk()
- return this.wordedMasterError(identityId, 'mnemonic' in input ? input.mnemonic : null, 'signed-in', () =>
+ const key = await this.wordedMasterError(identityId, 'mnemonic' in input ? input.mnemonic : null, 'signed-in', () =>
this.charged(identityId, 'key:runner', (k) => k?.keyId ?? null, () =>
registerLimitedKey(sdk, { network: this.network, identityId, masterWif, group: this.group(), trust: this.groupTrust(), request }),
),
)
+ this.noteOwnKey(identityId, key.keyId)
+ return key
})
}
@@ -1474,6 +1597,64 @@ export class AuthController {
return masterWif
}
+ /**
+ * Every key of the signed-in identity for Devices & keys: one identity read and one read of the
+ * remaining budgets.
+ */
+ async identityKeys(): Promise {
+ const session = this.state.session
+ if (session === null) throw new Error('sign in first')
+ const sdk = await this.getSdk()
+ const identity = await withPlatformRead(authSdk(sdk).identities.fetch(session.identityId), 'Reading your keys')
+ if (!identity) throw new Error(`identity ${session.identityId} not found on ${NETWORKS[this.network].key}`)
+ const budgeted = identity.publicKeys.filter((k) => k.totalBudget !== undefined).map((k) => k.keyId)
+ const budgets = budgeted.length ? await withPlatformRead(authSdk(sdk).identities.keysRemainingBudgets(session.identityId, budgeted), 'Reading key budgets') : new Map()
+ return keyRows(identity.publicKeys, budgets, NETWORKS[this.network].v2 ?? undefined, this.browserKeyIds())
+ }
+
+ /** The keys this browser holds for the signed-in identity: its signing key and wallet grants. */
+ private browserKeyIds(): number[] {
+ const session = this.state.session
+ if (session === null) return []
+ return [...(session.keyId !== undefined ? [session.keyId] : []), ...this.heldKeys(session.identityId).map((k) => k.keyId)]
+ }
+
+ /**
+ * Disable one of the identity's keys (a lost device's, a key nobody here added) with the master
+ * key, from the identity file or the recovery phrase. This browser's own key goes through
+ * {@link revokeStored}, which also forgets it here.
+ */
+ async disableIdentityKey(input: MasterInput, keyId: number): Promise {
+ return this.run(async () => {
+ const session = this.state.session
+ if (session === null) throw new Error('sign in first')
+ if (this.browserKeyIds().includes(keyId)) throw new WriteAuthError('This browser holds that key: use Revoke on Platform in Settings, which also forgets it here.')
+ const forge = NETWORKS[this.network].v2
+ if (!forge) throw new Error(`Dash Forge is not deployed on ${NETWORKS[this.network].key}`)
+ const { identityId } = session
+ const masterWif = await this.masterWifFor(identityId, input)
+ const sdk = await this.getSdk()
+ const sent = await this.wordedMasterError(identityId, 'mnemonic' in input ? input.mnemonic : null, 'signed-in', () =>
+ this.charged(identityId, 'key:revoke', () => keyId, () => disableIdentityKeys(sdk, { network: this.network, identityId, masterWif, keyIds: [keyId], allowed: (k) => DISABLEABLE.has(keyRole(k, forge)) })),
+ )
+ if (this.state.newKeys?.some((k) => k.keyId === keyId)) this.setState({ newKeys: this.state.newKeys.filter((k) => k.keyId !== keyId) })
+ return sent
+ })
+ }
+
+ /** The user saw the keys the new-key alert named (or disabled them): it stops naming them. */
+ acknowledgeNewKeys(): void {
+ const session = this.state.session
+ if (session === null || !this.state.newKeys?.length) return
+ acknowledgeKeys(this.network, session.identityId, this.state.newKeys.map((k) => k.keyId))
+ this.setState({ newKeys: [] })
+ }
+
+ /** A key this browser registered itself (a CI runner key, an encryption key): no alert for it. */
+ noteOwnKey(identityId: string, keyId: number): void {
+ acknowledgeKeys(this.network, identityId, [keyId])
+ }
+
/**
* Delete the stored key of `identityId` from this device (ending its session if open), and
* what this browser recorded for the identity: its spend ledger, its notifications inbox, its
@@ -1483,6 +1664,7 @@ export class AuthController {
*/
async forget(identityId: string): Promise {
if (this.state.session?.identityId === identityId) this.logout()
+ forgetKeySnapshot(this.network, identityId)
await forgetVault(this.network, identityId)
forgetLastIdentity(this.network, identityId)
clearDrafts(identityId)
diff --git a/forge-web/lib/auth/devices.test.ts b/forge-web/lib/auth/devices.test.ts
new file mode 100644
index 000000000..a3950f535
--- /dev/null
+++ b/forge-web/lib/auth/devices.test.ts
@@ -0,0 +1,70 @@
+// @vitest-environment jsdom
+import { beforeEach, describe, expect, it } from 'vitest'
+
+import { disableRefusal, keyRole, keyRows, readKeyLabels, writeKeyLabel } from './devices'
+import type { WasmKey } from '../sdk/facade'
+
+const forge = { core: 'C', collab: 'L', community: 'M', group: 'G' } as never
+const key = (keyId: number, o: Partial & { bounds?: { $type: string; id: string } } = {}): WasmKey =>
+ ({
+ keyId,
+ purposeNumber: 0,
+ securityLevelNumber: 2,
+ validatePrivateKey: () => false,
+ ...o,
+ ...(o.bounds ? { contractBounds: { toJSON: () => o.bounds } } : {}),
+ }) as WasmKey
+
+describe('Devices & keys', () => {
+ beforeEach(() => localStorage.clear())
+
+ it('tells keys apart', () => {
+ expect(keyRole(key(0, { securityLevelNumber: 0 }), forge)).toBe('master')
+ expect(keyRole(key(4, { purposeNumber: 1, securityLevelNumber: 3 }), forge)).toBe('encryption')
+ expect(keyRole(key(3, { purposeNumber: 3, securityLevelNumber: 1 }), forge)).toBe('transfer')
+ expect(keyRole(key(5, { bounds: { $type: 'contractGroup', id: 'G' } }), forge)).toBe('forge')
+ expect(keyRole(key(8, { bounds: { $type: 'contractGroup', id: 'OTHER' } }), forge)).toBe('other')
+ expect(keyRole(key(6, { bounds: { $type: 'singleContract', id: 'L' } }), forge)).toBe('forge-contract')
+ expect(keyRole(key(7, { bounds: { $type: 'singleContract', id: 'X' } }), forge)).toBe('other')
+ expect(keyRole(key(1), forge)).toBe('signing')
+ })
+
+ it('lists live keys first, newest first, with budgets and this browser marked', () => {
+ const rows = keyRows(
+ [key(1), key(5, { totalBudget: 100n, expiresAt: 9n, disabledAt: 3n }), key(6, { totalBudget: 100n, expiresAt: 9n })],
+ new Map([[6, 40n]]),
+ forge,
+ [6],
+ )
+ expect(rows.map((r) => r.keyId)).toEqual([6, 1, 5])
+ expect(rows[0]).toMatchObject({ budgetLeft: 40n, budgetTotal: 100n, thisBrowser: true })
+ expect(rows[2]?.disabledAt).toBe(3)
+ })
+
+ it('disables only what is safe to disable from here', () => {
+ const g = { bounds: { $type: 'contractGroup', id: 'G' } }
+ const order = [9, 7, 8, 1, 0, 4, 2]
+ const [mine, grant, other, wallet, master, enc, gone] = keyRows(
+ [key(9, g), key(7, { bounds: { $type: 'singleContract', id: 'L' } }), key(8, g), key(1), key(0, { securityLevelNumber: 0 }), key(4, { purposeNumber: 1 }), key(2, { ...g, disabledAt: 1n })],
+ new Map(),
+ forge,
+ [9, 7],
+ ).sort((a, b) => order.indexOf(a.keyId) - order.indexOf(b.keyId))
+ expect(disableRefusal(mine!)).toMatch(/Revoke/)
+ expect(disableRefusal(grant!)).toMatch(/Revoke/)
+ expect(disableRefusal(other!)).toBeNull()
+ expect(disableRefusal(wallet!)).toMatch(/--force/)
+ expect(disableRefusal(master!)).toMatch(/master/)
+ expect(disableRefusal(enc!)).toMatch(/Lost a device/)
+ expect(disableRefusal(gone!)).toMatch(/Already/)
+ })
+
+ it('keeps labels in this browser, per identity', () => {
+ writeKeyLabel('devnet', 'a', 5, ' work laptop ')
+ writeKeyLabel('devnet', 'a', 6, 'x'.repeat(60))
+ expect(readKeyLabels('devnet', 'a')).toEqual({ 5: 'work laptop', 6: 'x'.repeat(40) })
+ expect(readKeyLabels('devnet', 'b')).toEqual({})
+ writeKeyLabel('devnet', 'a', 5, '')
+ expect(readKeyLabels('devnet', 'a')).toEqual({ 6: 'x'.repeat(40) })
+ })
+})
diff --git a/forge-web/lib/auth/devices.ts b/forge-web/lib/auth/devices.ts
new file mode 100644
index 000000000..472cf8567
--- /dev/null
+++ b/forge-web/lib/auth/devices.ts
@@ -0,0 +1,144 @@
+/**
+ * Devices & keys (trust and safety TS-07): every key of the signed-in identity as the chain has
+ * it, what each one is for, what is left of its budget and when it expires, with local labels
+ * ("work laptop") that never leave this browser. A lost device's key is disabled from here.
+ *
+ * Platform keeps no "last used" per key: what the page can say is how much of a budget is spent
+ * (the chain's remaining budget) and when this browser last wrote (its own spend ledger).
+ */
+
+import type { Network } from '../constants'
+import type { ForgeIds } from '../deployments'
+import type { WasmKey } from '../sdk/facade'
+import { keyScope } from './key-registration'
+
+/** What a key is, in the words Devices & keys uses. */
+export type KeyRole = 'master' | 'forge' | 'forge-contract' | 'signing' | 'encryption' | 'transfer' | 'other'
+
+export interface KeyRow {
+ readonly keyId: number
+ readonly role: KeyRole
+ readonly purpose: number
+ readonly level: number
+ /** When it was disabled (ms), or null while live. */
+ readonly disabledAt: number | null
+ readonly budgetTotal: bigint | null
+ readonly budgetLeft: bigint | null
+ readonly expiresAt: number | null
+ /** A key this browser holds (its signing key, a wallet grant, a key held to be disabled). */
+ readonly thisBrowser: boolean
+}
+
+/** Classify a chain key for the page (Forge's bounds as `keyScope` reads them). */
+export function keyRole(k: Pick, forge: ForgeIds | undefined): KeyRole {
+ if (k.securityLevelNumber === 0) return 'master'
+ if (k.purposeNumber === 1) return 'encryption'
+ if (k.purposeNumber === 3) return 'transfer'
+ if (k.purposeNumber !== 0) return 'other'
+ if (forge === undefined) return 'other'
+ const scope = keyScope(k, forge)
+ if (scope === null) return 'other'
+ if (scope.unbounded) return 'signing'
+ return scope.core && scope.collab && scope.community ? 'forge' : 'forge-contract'
+}
+
+/** Roles Devices & keys may disable: keys bound to Forge, which nothing else signs with. */
+export const DISABLEABLE: ReadonlySet = new Set(['forge', 'forge-contract'])
+
+/** One line on what a key is for. */
+export const ROLE_TEXT: Readonly> = {
+ master: 'Master key. Adds and disables keys; never used to sign here.',
+ forge: 'Forge key with a budget and an expiry: a browser, dg or a CI runner.',
+ 'forge-contract': 'Key for one Forge contract (a wallet sign-in or a CI runner).',
+ signing: 'Signing key with no contract limits: your wallet and other apps may sign with it.',
+ encryption: 'Encryption key for private repos.',
+ transfer: 'Transfer key. Moves credits out of the identity.',
+ other: 'Key for another app or contract.',
+}
+
+/** The rows for an identity's keys, newest first, live before disabled. */
+export function keyRows(keys: readonly WasmKey[], budgets: ReadonlyMap, forge: ForgeIds | undefined, held: readonly number[]): KeyRow[] {
+ return keys
+ .map((k) => ({
+ keyId: k.keyId,
+ role: keyRole(k, forge),
+ purpose: k.purposeNumber,
+ level: k.securityLevelNumber,
+ disabledAt: k.disabledAt === undefined ? null : Number(k.disabledAt),
+ budgetTotal: k.totalBudget ?? null,
+ budgetLeft: k.totalBudget === undefined ? null : (budgets.get(k.keyId) ?? null),
+ expiresAt: k.expiresAt === undefined ? null : Number(k.expiresAt),
+ thisBrowser: held.includes(k.keyId),
+ }))
+ .sort((a, b) => Number(a.disabledAt !== null) - Number(b.disabledAt !== null) || b.keyId - a.keyId)
+}
+
+/**
+ * Why this page can't disable `row`, or null when it can. The master key can't be disabled at
+ * all; this browser's own keys go through Revoke (which also forgets them here); the encryption
+ * key is never disabled here (private repos open with it); unbounded signing keys (a wallet's), transfer and other apps'
+ * keys are left to `dg auth keys disable --force`, where their effect is spelled out.
+ */
+export function disableRefusal(row: KeyRow): string | null {
+ if (row.disabledAt !== null) return 'Already disabled.'
+ if (row.role === 'master') return "The master key can't be disabled."
+ if (row.thisBrowser) return 'This browser holds it: use Revoke on Platform in Settings.'
+ if (row.role === 'encryption') return 'Your private repos open with it. To replace it, see Lost a device? below.'
+ if (!DISABLEABLE.has(row.role)) return `Not a Forge key: other apps may rely on it. Use dg auth keys disable ${row.keyId} --force.`
+ return null
+}
+
+const labelsKey = (network: Network, identityId: string): string => `forge:key-labels:${network}:${identityId}`
+
+/** The labels this browser gave the identity's keys ("work laptop"). Never sent anywhere. */
+export function readKeyLabels(network: Network, identityId: string): Record {
+ try {
+ const v: unknown = JSON.parse(globalThis.localStorage?.getItem(labelsKey(network, identityId)) ?? '{}')
+ if (typeof v !== 'object' || v === null) return {}
+ return Object.fromEntries(Object.entries(v).filter(([k, x]) => /^\d+$/.test(k) && typeof x === 'string')) as Record
+ } catch {
+ return {}
+ }
+}
+
+/** Label a key on this browser (empty clears it). At most 40 characters. */
+export function writeKeyLabel(network: Network, identityId: string, keyId: number, label: string): Record {
+ const labels = { ...readKeyLabels(network, identityId) }
+ const text = label.trim().slice(0, 40)
+ if (text === '') delete labels[keyId]
+ else labels[keyId] = text
+ try {
+ globalThis.localStorage?.setItem(labelsKey(network, identityId), JSON.stringify(labels))
+ } catch {
+ /* storage blocked: the label lasts for this page */
+ }
+ return labels
+}
+
+/**
+ * Whether this browser's storage is persistent (TS-17): the vault, journals and spend ledger
+ * live in IndexedDB, which a browser may clear under storage pressure, and Safari clears after
+ * seven days without a visit unless the site's storage is persistent.
+ */
+export type StoragePersistence = 'persistent' | 'may-clear' | 'unknown'
+
+export async function storagePersistence(): Promise {
+ const storage = globalThis.navigator?.storage
+ if (storage?.persisted === undefined) return 'unknown'
+ try {
+ return (await storage.persisted()) ? 'persistent' : 'may-clear'
+ } catch {
+ return 'unknown'
+ }
+}
+
+/** Ask the browser to keep this site's storage (no prompt in most browsers). */
+export async function requestPersistence(): Promise {
+ const storage = globalThis.navigator?.storage
+ if (storage?.persist === undefined) return 'unknown'
+ try {
+ return (await storage.persist()) ? 'persistent' : 'may-clear'
+ } catch {
+ return 'unknown'
+ }
+}
diff --git a/forge-web/lib/auth/index.ts b/forge-web/lib/auth/index.ts
index c7ad951d8..9567d9542 100644
--- a/forge-web/lib/auth/index.ts
+++ b/forge-web/lib/auth/index.ts
@@ -39,10 +39,13 @@ export {
} from './vault'
export {
BROWSER_KEY_DEFAULTS,
+ KEY_LIFETIME_DAYS,
TOP_UP_DEFAULTS,
TOP_UP_MAX_DAYS,
TopUpPendingError,
defaultLimits,
+ lifetimeLabel,
+ limitsFor,
parseDashAmount,
topUpExpiry,
type LimitedKey,
diff --git a/forge-web/lib/auth/key-handoff.test.ts b/forge-web/lib/auth/key-handoff.test.ts
new file mode 100644
index 000000000..ad8d06f55
--- /dev/null
+++ b/forge-web/lib/auth/key-handoff.test.ts
@@ -0,0 +1,75 @@
+import { describe, expect, it } from 'vitest'
+import { readFileSync } from 'node:fs'
+import { resolve } from 'node:path'
+
+import { HandoffError, base64urlDecode, base64urlEncode, handoffCommand, handoffRequest, networkFlag, openHandoffReply, parseHandoffPayload } from './key-handoff'
+
+const vector = (name: string): { input: Record; expected: Record } =>
+ JSON.parse(readFileSync(resolve(__dirname, '../../../forge-contracts/vectors', `${name}.json`), 'utf8'))
+
+const hex = (h: string): Uint8Array => Uint8Array.from(h.match(/../g) ?? [], (b) => parseInt(b, 16))
+const enc = (s: string): Uint8Array => new TextEncoder().encode(s)
+
+describe('base64url', () => {
+ it('round-trips every length', () => {
+ for (let n = 0; n < 40; n++) {
+ const bytes = Uint8Array.from({ length: n }, (_, i) => (i * 37 + n) & 0xff)
+ expect(base64urlDecode(base64urlEncode(bytes))).toEqual(bytes)
+ }
+ })
+ it('decodes strictly, as Rust URL_SAFE_NO_PAD does', () => {
+ expect(base64urlDecode('AA==')).toBeNull()
+ expect(base64urlDecode('A')).toBeNull()
+ expect(base64urlDecode('AB')).toBeNull() // stray bits in the last character
+ expect(base64urlDecode('a+b/')).toBeNull()
+ expect(base64urlDecode('AA')).toEqual(new Uint8Array([0]))
+ })
+})
+
+describe('key handoff', () => {
+ const v = vector('key_handoff__limited_key')
+
+ it('opens the reply dg sealed, and only for its network', async () => {
+ const plain = await openHandoffReply(v.expected.reply as string, 'sakura', hex(v.input.browserSecret as string))
+ const p = parseHandoffPayload(plain, 'sakura')
+ expect(p).toMatchObject({ identityId: '8hJmcHWTsdvkHyCrk4UgjbyugDAmE7QfuCTQXpXAc7nB', keyId: 7, replacedKeyId: 5 })
+ expect(plain.every((b) => b === 0)).toBe(true)
+ await expect(openHandoffReply(v.expected.reply as string, 'testnet', hex(v.input.browserSecret as string))).rejects.toMatchObject({ kind: 'network' })
+ })
+
+ it('refuses a payload it does not know, or for another network', () => {
+ const ok = { v: 1, network: 'sakura', identityId: 'x', keyId: 3, wif: 'w' }
+ expect(parseHandoffPayload(enc(JSON.stringify(ok)), 'sakura').keyId).toBe(3)
+ for (const bad of [
+ { ...ok, v: 2 },
+ { ...ok, network: 'testnet' },
+ { ...ok, keyId: -1 },
+ { ...ok, extra: true },
+ { ...ok, encryptionKey: { keyId: 4, privateKeyHex: 'zz' } },
+ { ...ok, encryptionKey: { keyId: 4, privateKeyHex: '0'.repeat(64), more: 1 } },
+ ]) {
+ expect(() => parseHandoffPayload(enc(JSON.stringify(bad)), 'sakura')).toThrow(HandoffError)
+ }
+ expect(() => parseHandoffPayload(enc('not json'), 'sakura')).toThrow(HandoffError)
+ })
+
+ it('builds the dg command the tab shows', () => {
+ const r = handoffRequest('sakura', hex(v.input.browserSecret as string))
+ expect(handoffCommand(r, { days: 365, budgetDash: 0.05, withEncryptionKey: true, replaceKeyId: 5 })).toBe(
+ `dg auth keys add --network sakura --for-browser ${v.expected.request} --budget 0.05 --expires 365d --replace 5 --with-encryption-key`,
+ )
+ expect(handoffCommand(r, { days: 90, budgetDash: 0.05, withEncryptionKey: false, identityId: 'AbC', replaceKeyId: 7 })).toContain('--for-identity AbC --budget 0.05 --expires 90d --replace 7')
+ r.wipe()
+ expect(r.secret.every((b) => b === 0)).toBe(true)
+ })
+
+ it('names the network the way dg takes it', () => {
+ expect(networkFlag('devnet-sakura')).toBe('--devnet-name sakura')
+ expect(networkFlag('testnet')).toBe('--network testnet')
+ })
+
+ it('makes a fresh one-time key for every request', () => {
+ expect(handoffRequest('sakura').text).not.toBe(handoffRequest('sakura').text)
+ expect(() => handoffRequest('sa kura')).toThrow()
+ })
+})
diff --git a/forge-web/lib/auth/key-handoff.ts b/forge-web/lib/auth/key-handoff.ts
new file mode 100644
index 000000000..c541b45a1
--- /dev/null
+++ b/forge-web/lib/auth/key-handoff.ts
@@ -0,0 +1,241 @@
+/**
+ * Getting a limited key from `dg` without typing the recovery phrase into a web page (trust and
+ * safety TS-06; `docs/contracts/forge-v2.md` "Key handoff"). The Rust side is
+ * `crates/forge-core/src/browser_key.rs`; both run the `key_handoff_*` conformance vectors.
+ *
+ * 1. This tab draws a one-time secp256k1 key pair and shows its public half as a request,
+ * `dfkr1::`, inside a `dg` command.
+ * 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. This tab opens the reply with its one-time private key, checks the key on chain and keeps it
+ * in the vault. The one-time private key never leaves memory and is wiped once used.
+ *
+ * AES key: HKDF-SHA256(ikm = x(ECDH), salt = ephemeral public ‖ request public,
+ * info = "dash-forge/key-handoff/1"). Associated data: "dfkh1:" ‖ network.
+ */
+
+import * as secp from '@noble/secp256k1'
+import { hkdf } from '@noble/hashes/hkdf.js'
+import { sha256 } from '@noble/hashes/sha2.js'
+import { concatBytes } from '@noble/hashes/utils.js'
+
+export const REQUEST_PREFIX = 'dfkr1:'
+export const REPLY_PREFIX = 'dfkh1:'
+const INFO = new TextEncoder().encode('dash-forge/key-handoff/1')
+
+/**
+ * The fixed warning shown before every recovery-phrase prompt, in the web app and in `dg`
+ * (vector `copy__recovery_phrase_warning`; Rust `browser_key::RECOVERY_PHRASE_WARNING`).
+ */
+export const RECOVERY_PHRASE_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."
+
+/** Why a reply does not open. */
+export type HandoffOpenError = 'malformed' | 'network' | 'unreadable'
+
+export class HandoffError extends Error {
+ constructor(
+ readonly kind: HandoffOpenError | 'payload',
+ message: string,
+ ) {
+ super(message)
+ this.name = 'HandoffError'
+ }
+}
+
+const B64 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_'
+
+/** base64url without padding. */
+export function base64urlEncode(bytes: Uint8Array): string {
+ let out = ''
+ for (let i = 0; i < bytes.length; i += 3) {
+ const n = ((bytes[i] ?? 0) << 16) | ((bytes[i + 1] ?? 0) << 8) | (bytes[i + 2] ?? 0)
+ const chars = Math.min(4, Math.ceil(((bytes.length - i) * 8) / 6))
+ for (let j = 0; j < chars; j++) out += B64[(n >> (18 - 6 * j)) & 63]
+ }
+ return out
+}
+
+/**
+ * Strict base64url without padding, as Rust's `URL_SAFE_NO_PAD` decodes: no `=`, no characters
+ * outside the alphabet, no impossible length, no stray bits in the last character. Null if not.
+ */
+export function base64urlDecode(text: string): Uint8Array | null {
+ if (text.length % 4 === 1) return null
+ const out = new Uint8Array(Math.floor((text.length * 6) / 8))
+ let acc = 0
+ let bits = 0
+ let o = 0
+ for (const c of text) {
+ const v = B64.indexOf(c)
+ if (v < 0) return null
+ acc = (acc << 6) | v
+ bits += 6
+ if (bits >= 8) {
+ bits -= 8
+ out[o++] = (acc >> bits) & 0xff
+ }
+ acc &= (1 << bits) - 1
+ }
+ return acc === 0 ? out : null
+}
+
+function validNetwork(n: string): boolean {
+ return n.length > 0 && n.length <= 32 && /^[A-Za-z0-9-]+$/.test(n)
+}
+
+/** A one-time request: its text, and the private key that opens the reply (wipe with {@link HandoffRequest.wipe}). */
+export interface HandoffRequest {
+ readonly network: string
+ readonly text: string
+ readonly secret: Uint8Array
+ wipe(): void
+}
+
+/** A request for `network` from `secret` (fixed in the vectors; random otherwise). */
+export function handoffRequest(network: string, secret: Uint8Array = secp.utils.randomSecretKey()): HandoffRequest {
+ if (!validNetwork(network)) throw new Error(`not a network name: ${network}`)
+ const pub = secp.getPublicKey(secret, true)
+ return {
+ network,
+ text: `${REQUEST_PREFIX}${network}:${base64urlEncode(pub)}`,
+ secret,
+ wipe: () => secret.fill(0),
+ }
+}
+
+/** The AES key of a reply between `ephemeralPub` (dg's) and `requestPub` (this tab's) keys. */
+function replyKey(shared: Uint8Array, ephemeralPub: Uint8Array, requestPub: Uint8Array): Uint8Array {
+ return hkdf(sha256, shared, concatBytes(ephemeralPub, requestPub), INFO, 32)
+}
+
+/**
+ * Open a `dfkh1:` reply with the request's one-time `secret`: the plaintext bytes (the caller
+ * wipes them). Throws {@link HandoffError} with the vectors' error kinds.
+ */
+export async function openHandoffReply(reply: string, network: string, secret: Uint8Array): Promise {
+ const bad = (kind: HandoffOpenError): HandoffError => new HandoffError(kind, OPEN_ERROR_TEXT[kind])
+ const trimmed = reply.trim()
+ if (!trimmed.startsWith(REPLY_PREFIX)) throw bad('malformed')
+ const rest = trimmed.slice(REPLY_PREFIX.length)
+ const colon = rest.indexOf(':')
+ if (colon < 0) throw bad('malformed')
+ const net = rest.slice(0, colon)
+ if (!validNetwork(net)) throw bad('malformed')
+ if (net !== network) throw new HandoffError('network', `This key was made for ${net}, but this site is on ${network}. Run the command shown here, with ${networkFlag(network)}.`)
+ const bytes = base64urlDecode(rest.slice(colon + 1))
+ if (bytes === null || bytes.length < 33 + 12 + 16) throw bad('malformed')
+ const ephemeralPub = bytes.slice(0, 33)
+ let shared: Uint8Array
+ try {
+ shared = secp.getSharedSecret(secret, ephemeralPub, true).slice(1, 33)
+ } catch {
+ throw bad('malformed')
+ }
+ const raw = replyKey(shared, ephemeralPub, secp.getPublicKey(secret, true))
+ shared.fill(0)
+ let key: CryptoKey
+ try {
+ key = await crypto.subtle.importKey('raw', raw as Uint8Array, { name: 'AES-GCM' }, false, ['decrypt'])
+ } finally {
+ raw.fill(0)
+ }
+ try {
+ const plain = await crypto.subtle.decrypt(
+ {
+ name: 'AES-GCM',
+ iv: bytes.slice(33, 45),
+ additionalData: new TextEncoder().encode(`${REPLY_PREFIX}${net}`),
+ },
+ key,
+ bytes.slice(45),
+ )
+ return new Uint8Array(plain)
+ } catch {
+ throw bad('unreadable')
+ }
+}
+
+const OPEN_ERROR_TEXT: Readonly> = {
+ malformed: "That isn't the key dg printed. Copy the whole line that starts with dfkh1: and paste it here.",
+ network: 'This key was made for another network.',
+ unreadable: 'This key was made for another request, or it was changed on the way. Run the command shown here again; each request works once.',
+}
+
+/** What a reply carries (Rust `browser_key::Payload`). */
+export interface HandoffPayload {
+ readonly network: string
+ readonly identityId: string
+ readonly keyId: number
+ readonly wif: string
+ readonly replacedKeyId?: number
+ readonly encryptionKey?: {
+ readonly keyId: number
+ readonly privateKeyHex: string
+ }
+}
+
+const KEY_ID = (n: unknown): n is number => typeof n === 'number' && Number.isInteger(n) && n >= 0 && n <= 0xffffffff
+
+/** Parse a reply's plaintext (wiped here); refuses anything but a version-1 payload for `network`. */
+export function parseHandoffPayload(plain: Uint8Array, network: string): HandoffPayload {
+ const refuse = (): HandoffError => new HandoffError('payload', "dg sent a key this version of Forge can't read. Update dg and try again.")
+ let p: Record
+ try {
+ p = JSON.parse(new TextDecoder().decode(plain)) as Record
+ } catch {
+ throw refuse()
+ } finally {
+ plain.fill(0)
+ }
+ if (typeof p !== 'object' || p === null || p.v !== 1) throw refuse()
+ const allowed = new Set(['v', 'network', 'identityId', 'keyId', 'wif', 'replacedKeyId', 'encryptionKey'])
+ if (Object.keys(p).some((k) => !allowed.has(k))) throw refuse()
+ if (p.network !== network || typeof p.identityId !== 'string' || !KEY_ID(p.keyId) || typeof p.wif !== 'string') throw refuse()
+ if (p.replacedKeyId !== undefined && !KEY_ID(p.replacedKeyId)) throw refuse()
+ let encryptionKey: HandoffPayload['encryptionKey']
+ if (p.encryptionKey !== undefined) {
+ const e = p.encryptionKey as Record | null
+ if (typeof e !== 'object' || e === null || !KEY_ID(e.keyId) || typeof e.privateKeyHex !== 'string' || !/^[0-9a-f]{64}$/.test(e.privateKeyHex)) throw refuse()
+ if (Object.keys(e).some((k) => k !== 'keyId' && k !== 'privateKeyHex')) throw refuse()
+ encryptionKey = { keyId: e.keyId, privateKeyHex: e.privateKeyHex }
+ }
+ return {
+ network,
+ identityId: p.identityId,
+ keyId: p.keyId,
+ wif: p.wif,
+ ...(p.replacedKeyId !== undefined ? { replacedKeyId: p.replacedKeyId as number } : {}),
+ ...(encryptionKey ? { encryptionKey } : {}),
+ }
+}
+
+/** What the `dg` command asks for: its network, limits, the key it replaces, whether to bring the encryption key. */
+export interface HandoffOptions {
+ /** The identity the key is for, when this tab knows it: dg refuses to make it for another. */
+ readonly identityId?: string
+ readonly replaceKeyId?: number
+ readonly days: number
+ readonly budgetDash: number
+ readonly withEncryptionKey: boolean
+}
+
+/** The `dg` flag that selects a network key (`testnet`, `mainnet`, `devnet-`). */
+export function networkFlag(network: string): string {
+ return network.startsWith('devnet-') ? `--devnet-name ${network.slice('devnet-'.length)}` : `--network ${network}`
+}
+
+/** The `dg` command that answers `request`. */
+export function handoffCommand(request: HandoffRequest, o: HandoffOptions): string {
+ return [
+ 'dg auth keys add',
+ networkFlag(request.network),
+ `--for-browser ${request.text}`,
+ ...(o.identityId !== undefined ? [`--for-identity ${o.identityId}`] : []),
+ `--budget ${o.budgetDash}`,
+ `--expires ${o.days}d`,
+ ...(o.replaceKeyId !== undefined ? [`--replace ${o.replaceKeyId}`] : []),
+ ...(o.withEncryptionKey ? ['--with-encryption-key'] : []),
+ ].join(' ')
+}
diff --git a/forge-web/lib/auth/key-watch.test.ts b/forge-web/lib/auth/key-watch.test.ts
new file mode 100644
index 000000000..40d73c628
--- /dev/null
+++ b/forge-web/lib/auth/key-watch.test.ts
@@ -0,0 +1,51 @@
+// @vitest-environment jsdom
+import { beforeEach, describe, expect, it } from 'vitest'
+
+import { acknowledgeKeys, checkKeys, forgetKeySnapshot, keyKind, newKeysSince, type WatchedKey } from './key-watch'
+
+const k = (keyId: number, o: Partial = {}): WatchedKey => ({ keyId, purpose: 0, level: 2, disabled: false, ...o })
+
+describe('new-key alert', () => {
+ beforeEach(() => localStorage.clear())
+
+ it('says nothing on the first look, and records what it saw', () => {
+ expect(checkKeys('devnet', 'id', [k(0, { level: 0 }), k(5)], [5])).toEqual([])
+ expect(checkKeys('devnet', 'id', [k(0, { level: 0 }), k(5)], [5])).toEqual([])
+ })
+
+ it('names a live key this device did not add, until it is acknowledged', () => {
+ checkKeys('devnet', 'id', [k(0, { level: 0 }), k(5)], [5])
+ const keys = [k(0, { level: 0 }), k(5), k(6), k(7, { disabled: true })]
+ expect(checkKeys('devnet', 'id', keys, [5]).map((x) => x.keyId)).toEqual([6])
+ // Still there after a reload: the snapshot only moves on once seen.
+ expect(checkKeys('devnet', 'id', keys, [5]).map((x) => x.keyId)).toEqual([6])
+ acknowledgeKeys('devnet', 'id', [6])
+ expect(checkKeys('devnet', 'id', keys, [5])).toEqual([])
+ })
+
+ it("never names this device's own keys, nor another identity's or network's snapshot", () => {
+ checkKeys('devnet', 'id', [k(5)], [5])
+ expect(checkKeys('devnet', 'id', [k(5), k(8)], [8])).toEqual([])
+ expect(checkKeys('testnet', 'id', [k(9)], [])).toEqual([])
+ expect(checkKeys('devnet', 'other', [k(9)], [])).toEqual([])
+ forgetKeySnapshot('devnet', 'id')
+ expect(checkKeys('devnet', 'id', [k(5), k(10)], [])).toEqual([])
+ })
+
+ it('never starts a snapshot from an acknowledgement', () => {
+ acknowledgeKeys('devnet', 'id', [9])
+ expect(checkKeys('devnet', 'id', [k(0, { level: 0 }), k(5), k(9)], [9])).toEqual([])
+ expect(checkKeys('devnet', 'id', [k(0, { level: 0 }), k(5), k(9)], [9])).toEqual([])
+ })
+
+ it('compares against nothing when there is no snapshot', () => {
+ expect(newKeysSince(null, [k(1)], [])).toEqual([])
+ expect(newKeysSince([1], [k(1), k(2)], []).map((x) => x.keyId)).toEqual([2])
+ })
+
+ it('words keys plainly', () => {
+ expect(keyKind({ purpose: 0, level: 0 })).toBe('master key')
+ expect(keyKind({ purpose: 0, level: 2 })).toBe('high signing key')
+ expect(keyKind({ purpose: 1, level: 3 })).toBe('medium encryption key')
+ })
+})
diff --git a/forge-web/lib/auth/key-watch.ts b/forge-web/lib/auth/key-watch.ts
new file mode 100644
index 000000000..6c7256a95
--- /dev/null
+++ b/forge-web/lib/auth/key-watch.ts
@@ -0,0 +1,99 @@
+/**
+ * The new-key alert (trust and safety TS-07): each device remembers which keys the identity had
+ * when it last looked, and says so when a key appears that it did not add itself. A leaked
+ * master key or recovery phrase shows up here first: whoever holds it adds a key of their own.
+ *
+ * Costs no read of its own: the session's identity fetch (every sign-in, unlock and resumed
+ * session) is compared against the snapshot. The snapshot holds key ids only (no secrets), in
+ * localStorage per network and identity, and moves on only when the user has seen the change.
+ */
+
+import type { Network } from '../constants'
+
+/** What the alert says about a key (from the identity on chain). */
+export interface WatchedKey {
+ readonly keyId: number
+ readonly purpose: number
+ readonly level: number
+ readonly disabled: boolean
+}
+
+/** The ids the device knew when it last looked. */
+interface Snapshot {
+ readonly v: 1
+ readonly ids: readonly number[]
+ readonly at: number
+}
+
+const key = (network: Network, identityId: string): string => `forge:seen-keys:${network}:${identityId}`
+
+function read(network: Network, identityId: string): Snapshot | null {
+ try {
+ const raw = globalThis.localStorage?.getItem(key(network, identityId))
+ if (!raw) return null
+ const s = JSON.parse(raw) as Snapshot
+ return s.v === 1 && Array.isArray(s.ids) && s.ids.every((n) => Number.isInteger(n)) ? s : null
+ } catch {
+ return null
+ }
+}
+
+function write(network: Network, identityId: string, ids: readonly number[], now: number): void {
+ try {
+ globalThis.localStorage?.setItem(key(network, identityId), JSON.stringify({ v: 1, ids: [...ids].sort((a, b) => a - b), at: now } satisfies Snapshot))
+ } catch {
+ /* storage blocked: the alert cannot remember, and says nothing rather than repeat */
+ }
+}
+
+/**
+ * The live keys added since this device last looked, other than `own` (the keys this device
+ * holds, which it added itself). The first look records the keys silently: there is nothing
+ * to compare with, and a fresh sign-in is the user adding a key.
+ */
+export function newKeysSince(prev: readonly number[] | null, keys: readonly WatchedKey[], own: readonly number[]): WatchedKey[] {
+ if (prev === null) return []
+ const known = new Set([...prev, ...own])
+ return keys.filter((k) => !k.disabled && !known.has(k.keyId))
+}
+
+/**
+ * Compare the identity's keys with this device's snapshot. Returns the new keys to tell the user
+ * about (the snapshot stays until {@link acknowledgeKeys}); with none, the snapshot moves on.
+ */
+export function checkKeys(network: Network, identityId: string, keys: readonly WatchedKey[], own: readonly number[], now = Date.now()): WatchedKey[] {
+ const prev = read(network, identityId)
+ const added = newKeysSince(prev?.ids ?? null, keys, own)
+ if (added.length === 0) write(network, identityId, keys.map((k) => k.keyId), now)
+ return added
+}
+
+/**
+ * The user has seen these keys, disabled them, or this device added them: stop telling. Never
+ * starts a snapshot: one holding only these ids would make the next first look name every other
+ * key (the master key included) as new.
+ */
+export function acknowledgeKeys(network: Network, identityId: string, keyIds: readonly number[], now = Date.now()): void {
+ const prev = read(network, identityId)
+ if (prev === null) return
+ write(network, identityId, [...new Set([...prev.ids, ...keyIds])], now)
+}
+
+/** Forget the snapshot (sign out and forget). */
+export function forgetKeySnapshot(network: Network, identityId: string): void {
+ try {
+ globalThis.localStorage?.removeItem(key(network, identityId))
+ } catch {
+ /* nothing to forget */
+ }
+}
+
+const PURPOSES: Readonly> = { 0: 'signing', 1: 'encryption', 2: 'decryption', 3: 'transfer', 4: 'system', 5: 'voting', 6: 'owner' }
+const LEVELS: Readonly> = { 0: 'master', 1: 'critical', 2: 'high', 3: 'medium' }
+
+/** "a high-level signing key" — how a key reads in the alert and on Devices & keys. */
+export function keyKind(k: Pick): string {
+ const level = LEVELS[k.level] ?? 'unknown-level'
+ const purpose = PURPOSES[k.purpose] ?? 'other'
+ return k.level === 0 ? 'master key' : `${level} ${purpose} key`
+}
diff --git a/forge-web/lib/auth/limited-key.ts b/forge-web/lib/auth/limited-key.ts
index cb6245f94..ae561b106 100644
--- a/forge-web/lib/auth/limited-key.ts
+++ b/forge-web/lib/auth/limited-key.ts
@@ -48,6 +48,19 @@ export function defaultLimits(now = Date.now()): LimitedKeyRequest {
}
}
+/** How long a new browser key may live, in days: renewals stay rare, and no key lives past a year (TS-06). */
+export const KEY_LIFETIME_DAYS = [30, 90, 180, 365] as const
+
+/** A lifetime as the picker words it. */
+export function lifetimeLabel(days: number): string {
+ return days === 365 ? '1 year' : days === 180 ? '6 months' : `${days} days`
+}
+
+/** The default budget for `days` from `now`. */
+export function limitsFor(days: number, now = Date.now()): LimitedKeyRequest {
+ return { ...defaultLimits(now), expiresAt: now + days * DAY_MS }
+}
+
/**
* The master key given is not a live MASTER key of the identity (QW3-028: the update was refused
* as "that key is not this identity's master key", or by the SDK's "Signer does not have a
@@ -292,6 +305,39 @@ export async function disableHeldKeys(
return true
}
+/**
+ * Disable keys of an identity with its master key (Devices & keys): AUTHENTICATION keys below
+ * MASTER that `allowed` accepts (the caller passes the page's rule, `./devices` `disableRefusal`,
+ * checked again here against the identity just read). Returns whether an update was sent (false
+ * when every key was already disabled).
+ */
+export async function disableIdentityKeys(
+ sdk: EvoSDK,
+ params: {
+ readonly network: Network
+ readonly identityId: string
+ readonly masterWif: string
+ readonly keyIds: readonly number[]
+ readonly allowed: (k: WasmKey) => boolean
+ },
+): Promise {
+ const identity = await authSdk(sdk).identities.fetch(params.identityId)
+ if (!identity) throw new Error(`identity ${params.identityId} not found`)
+ const ids: number[] = []
+ for (const id of params.keyIds) {
+ const k = identity.publicKeys.find((x) => x.keyId === id)
+ if (!k) throw new Error(`key ${id} is not on this identity`)
+ if (k.securityLevelNumber === 0 || k.purposeNumber !== 0 || !params.allowed(k)) throw new Error(`key ${id} is not a Forge signing key below master; refusing to disable it here`)
+ if (k.disabledAt === undefined) ids.push(id)
+ }
+ if (ids.length === 0) return false
+ await assertMasterKeyOf(identity, params.identityId, params.masterWif, params.network)
+ await withMasterSigner(params.masterWif, (signer) =>
+ sendIdentityUpdate(sdk, params.identityId, () => authSdk(sdk).identities.update({ identity, disablePublicKeys: ids, signer })),
+ )
+ return true
+}
+
/** Run `fn` with an IdentitySigner holding only the master key; both are freed after. */
async function withMasterSigner(masterWif: string, fn: (signer: unknown) => Promise): Promise {
const { IdentitySigner, PrivateKey } = await import('@dashevo/evo-sdk')
diff --git a/forge-web/lib/auth/vault.ts b/forge-web/lib/auth/vault.ts
index fba3a6710..a5509bd7c 100644
--- a/forge-web/lib/auth/vault.ts
+++ b/forge-web/lib/auth/vault.ts
@@ -42,6 +42,7 @@ import { sha256 } from '@noble/hashes/sha2.js'
import type { Network } from '../constants'
import { idbDelete, idbEntries, idbGet, idbPut, idbUpdate } from '../idb'
import { withTimeout } from '../timeout'
+import { requestPersistence } from './devices'
import {
KEPT_TTL_MS,
LOCKED_AT_KEY,
@@ -149,6 +150,8 @@ interface VaultRecord {
* when there was none (a first import). Finishing it replaces only that record.
*/
readonly replaces?: number | null
+ /** The key came from `dg auth keys add --for-browser` (`./key-handoff`): renew it the same way. */
+ readonly origin?: 'dg'
}
/** What the UI may know about a stored vault (no secrets). */
@@ -164,6 +167,8 @@ export interface VaultInfo {
* it first drops that blob (it cannot be opened), so the import form says so beforehand.
*/
readonly encryptionKey?: true
+ /** The key came from `dg` (a key handoff): Renew offers `dg` first, not the recovery phrase. */
+ readonly fromDg?: true
}
const enc = new TextEncoder()
@@ -638,6 +643,14 @@ export async function stageInVault(network: Network, secret: VaultSecret, protec
}
}
+/** Another tab stored or removed a key for the identity after the caller checked ({@link storeInVault}). */
+export class VaultChangedError extends Error {
+ constructor() {
+ super('Another tab changed the key stored for this identity meanwhile.')
+ this.name = 'VaultChangedError'
+ }
+}
+
/** A key renewal on this device may have landed and is not finished: unlock to finish it first. */
export class PendingRenewalError extends VaultLockedError {
constructor() {
@@ -905,6 +918,13 @@ export async function storeInVault(
* gave up, its key carried in `secret.extra`): it is never gone before its key is stored.
*/
readonly dropStagedKeyId?: number
+ /** Where the key came from ({@link VaultRecord.origin}). */
+ readonly origin?: 'dg'
+ /**
+ * The key id of the record the caller found for this identity (null: none), checked in the
+ * write's own transaction: a key another tab stored meanwhile aborts it ({@link VaultChangedError}).
+ */
+ readonly expectHeldKeyId?: number | null
} = {},
): Promise {
const lockMarkerAt = lockMarker()
@@ -926,7 +946,8 @@ export async function storeInVault(
// The extra grants live in their own blob, so a later grant can be added without the data key.
const { extra, ...main } = secret
try {
- const record = await sealRecord(network, main, protection, dataKey)
+ const sealed = await sealRecord(network, main, protection, dataKey)
+ const record: VaultRecord = options.origin ? { ...sealed, origin: options.origin } : sealed
storageKey = await deriveStorageKey(dataKey, network, identityId)
const blob = carried !== null ? await sealBlob(storageKey, network, identityId, carried) : undefined
const extraBlob = extra?.length ? await sealBlob(storageKey, network, identityId, extra, 'extra') : undefined
@@ -944,13 +965,23 @@ export async function storeInVault(
// THIS key (the renewal that registered it) is done; a stage of another key (a renewal
// from another tab, not finished) stays, for its unlock to finish.
const at = stagedKey(network, identityId)
- await idbUpdate('vault', at, (staged) => [
- [key(network, identityId), record],
- [storageBlobKey(network, identityId), blob],
- [extraBlobKey(network, identityId), extraBlob],
- [encryptionBlobKey(network, identityId), encBlob],
- ...(staged !== undefined && (staged.keyId === secret.keyId || staged.keyId === options.dropStagedKeyId) ? ([[at, undefined]] as const) : []),
- ])
+ await idbUpdate(
+ 'vault',
+ at,
+ (staged, [held]) => {
+ if (options.expectHeldKeyId !== undefined && ((held as VaultRecord | undefined)?.keyId ?? null) !== options.expectHeldKeyId) {
+ throw new VaultChangedError()
+ }
+ return [
+ [key(network, identityId), record],
+ [storageBlobKey(network, identityId), blob],
+ [extraBlobKey(network, identityId), extraBlob],
+ [encryptionBlobKey(network, identityId), encBlob],
+ ...(staged !== undefined && (staged.keyId === secret.keyId || staged.keyId === options.dropStagedKeyId) ? ([[at, undefined]] as const) : []),
+ ]
+ },
+ [key(network, identityId)],
+ )
// The key is on chain and was staged and read back first: a failed read-back here is not a
// reason to fail the sign-in (the staged copy, when there was one, is still the safe copy).
readBackOk = await readsBack(network, key(network, identityId), main, dataKey).catch(() => false)
@@ -958,6 +989,10 @@ export async function storeInVault(
dataKey.fill(0)
}
setUnlocked(network, secret, { storage: storageKey, encryption: encryptionKey }, { lockMarkerAt })
+ // TS-17: ask the browser to keep the vault (Safari clears a site's storage after 7 days
+ // without a visit otherwise). Most browsers answer without a prompt; a refusal is shown in
+ // Settings → Devices & keys.
+ void requestPersistence()
return {
storageSettingsDropped: hadBlob && carried === null,
encryptionKeyDropped: hadEnc && carriedEnc === null,
@@ -1049,6 +1084,7 @@ export async function listVaults(network: Network): Promise {
createdAt: r.createdAt,
methods: r.slots.map((s) => s.kind),
...(withEnc.has(encryptionBlobKey(network, r.identityId)) ? { encryptionKey: true as const } : {}),
+ ...(r.origin === 'dg' ? { fromDg: true as const } : {}),
}))
// An identity with only a staged key (a first import whose tab closed after registering,
// D-016) must still be offered for unlock, or the key it paid for is unreachable.
diff --git a/forge-web/lib/rules/conformance.test.ts b/forge-web/lib/rules/conformance.test.ts
index 96d14874c..a1e1545a1 100644
--- a/forge-web/lib/rules/conformance.test.ts
+++ b/forge-web/lib/rules/conformance.test.ts
@@ -39,6 +39,7 @@ import { rerunCounts, rerunFields, rerunRequest, type RerunEvent } from './ci-re
import { avatarSpec, checkProfile, type ProfileInput } from './profile'
import { backlinkFile, readBacklink } from './mirror-backlink'
import { readPubkeyEntry, verifyCommitSignature, type Signer } from './signature'
+import { HandoffError, RECOVERY_PHRASE_WARNING, handoffRequest, openHandoffReply } from '../auth/key-handoff'
import { planRefs, syncDecision } from '../repo/fork'
import { webhookUrlSecret } from '../repo/webhooks'
import { matchesText, mentions } from '../repo/issue-index'
@@ -724,6 +725,49 @@ async function runSignatureVector(v: Vector): Promise {
expect(await verifyCommitSignature(new TextEncoder().encode(inp.commit), inp.signers)).toEqual(v.expected)
}
+/** The key handoff cases (`../auth/key-handoff`): asynchronous, since WebCrypto is. */
+const HANDOFF_CASES: ReadonlySet = new Set(['key_handoff', 'key_handoff_open', 'copy'])
+
+interface KeyHandoffInput {
+ readonly network: string
+ readonly browserSecret: string
+ readonly ephemeralSecret?: string
+ readonly nonce?: string
+ readonly plaintext?: string
+ readonly reply?: string
+}
+
+async function runHandoffVector(v: Vector): Promise {
+ if (v.case === 'copy') {
+ onlyKeys(v, ['id'])
+ const texts: Readonly> = { recoveryPhraseWarning: RECOVERY_PHRASE_WARNING }
+ const text = texts[(v.input as { readonly id: string }).id]
+ expect(text, `vector ${v.name}: unknown copy`).toBeDefined()
+ expect({ text }).toEqual(v.expected)
+ return
+ }
+ const inp = v.input as KeyHandoffInput
+ const opened = async (reply: string): Promise => {
+ try {
+ return { plaintext: new TextDecoder().decode(await openHandoffReply(reply, inp.network, hexToBytes(inp.browserSecret))) }
+ } catch (e) {
+ if (e instanceof HandoffError) return { error: e.kind }
+ throw e
+ }
+ }
+ if (v.case === 'key_handoff_open') {
+ onlyKeys(v, ['network', 'browserSecret', 'reply'])
+ expect(await opened(inp.reply as string)).toEqual(v.expected)
+ return
+ }
+ // Sealing is dg's half (Rust checks the reply byte for byte); this side checks the request it
+ // would show and that the reply opens to exactly the plaintext sealed.
+ onlyKeys(v, ['network', 'browserSecret', 'ephemeralSecret', 'nonce', 'plaintext'])
+ const expected = v.expected as { readonly request: string; readonly reply: string }
+ expect(handoffRequest(inp.network, hexToBytes(inp.browserSecret)).text).toBe(expected.request)
+ expect(await opened(expected.reply)).toEqual({ plaintext: inp.plaintext })
+}
+
describe('FORGE_RULES conformance vectors', () => {
const vectors = loadVectors()
const base = vectors.filter((v) => v.rules === undefined)
@@ -758,6 +802,7 @@ describe('FORGE_RULES conformance vectors', () => {
for (const v of v2Vectors) {
it(`v2 ${v.case} :: ${v.name}`, async () => {
if (SIGNATURE_CASES.has(v.case)) await runSignatureVector(v)
+ else if (HANDOFF_CASES.has(v.case)) await runHandoffVector(v)
else runVector(v)
})
}