Skip to content

flowsta-vault-client ​

The Rust counterpart of @flowsta/holochain: everything a desktop app's Rust process does with the person's Flowsta Vault.

It has no UI framework and no Holochain crates in its dependencies, so it fits any Rust desktop app. Every file, folder and name that is your app's own is passed in.

New here? The Rust side says what is required, what is optional, and when an app needs this library at all.

Install ​

toml
[dependencies]
flowsta-vault-client = { git = "https://github.com/WeAreFlowsta/flowsta-rust-sdk", rev = "<commit>" }

Version 0.2, MIT, Rust 1.93 or later. The interface can still change before 1.0, so pin a commit and read the repository's README when you move the pin.

What is in it ​

ModuleWhat it doesOptional?
vaultFinds the person's Vault, says which app each call is from, opens the Vault appThe base. Every other module that calls the Vault uses it
identityThe sign-in kept on the device, and the two checks a write goes throughOptional
device_seedYour app's own device key, in a file a backup can carryOptional
adoptReplaces the device key in a safe order, and holds back a backup that would replace a key the person still needsOptional; needs device_seed
profilesOne folder per Flowsta identity on one installOptional

The link itself is made from the page: the person approves it in their Vault after your page calls linkFlowstaIdentity. This library keeps what that sign-in produced and checks it.

Talk to the Vault from Rust ​

Make one client at startup and share it. Clones are cheap and share what was last found.

rust
use flowsta_vault_client::{vault, VaultClient, VaultConfig};

let vault = VaultClient::new(VaultConfig {
    // The same origin your app's window presents (see below).
    origin: vault::tauri_origin(tauri::is_dev(), "http://localhost:5173"),
    // None in a release. A test build can name one port.
    only_port: None,
    // Your client id from dev.flowsta.com.
    client_id: Some("flowsta_app_abc123".into()),
})?;

// The link token your page received when the person linked the app.
// Your app stores it; set it at each start and after each sign-in.
vault.set_link_token(stored_link_token);

// Is the person's Vault there, and is it unlocked?
if let Some(found) = vault.find(std::time::Duration::from_secs(2)).await {
    println!("Vault on port {}, unlocked: {}", found.port, found.unlocked);
}

Finding the Vault. The Vault listens on port 27777, or the next one or two up when that port is taken. find asks all three at once, leaves out a Vault that belongs to another user account on the same computer, and prefers an unlocked Vault over a locked one. base_url() gives the address to call, and live_identity() says whether a Vault is unlocked and as which identity.

Saying which app a call is from. The Vault tells apps apart by three things a call presents:

WhatWhere it comes fromWhat it does
The originVaultConfig.originThe Vault records the origin a link was made from, and accepts that link's token only from the same origin
The link tokenThe Vault's answer when the person links your appNames that one link, whatever else on the computer presents the same origin
The client iddev.flowsta.comWithout a token, picks your app among several that present one origin

vault.get(url) and vault.post(url, body) add the token and the client id for you: query parameters on a GET, fields of the JSON body on a POST. find, live_identity and the backup read in adopt go through them. vault.http() is the plain client, with the origin only.

Use the window's origin. When the page makes the link, the Vault records the origin of your app's window. vault::tauri_origin(is_dev, dev_url) returns that same origin for a Tauri v2 app: your dev server's URL in a dev build, http://tauri.localhost on Windows, tauri://localhost elsewhere. Every Tauri app's window presents those origins, so always set your client id and your link token with it. Register the origins your app uses.

linkFlowstaIdentity returns the token as linkToken. If your Rust side calls the Vault, pass it across and keep it in a file of your app's own (owner-only permissions, with the profile it belongs to):

typescript
const result = await linkFlowstaIdentity({ appName, clientId, localAgentPubKey });
await invoke('remember_link_token', { token: result.linkToken ?? null });
rust
#[tauri::command]
fn remember_link_token(token: Option<String>, vault: tauri::State<'_, VaultClient>) -> Result<(), String> {
    save_token_file(token.as_deref())?;   // your own storage
    vault.set_link_token(token);          // None forgets it
    Ok(())
}

Treat the token like a credential: do not log it, and do not put it in a backup.

When the Vault refuses a call ​

A refusal about which app is calling is a 403 with an error code. vault::Refused reads it:

rust
use flowsta_vault_client::vault::Refused;

match Refused::from_answer(status, &body) {
    Some(Refused::InvalidLinkToken) => {
        // The link is gone, or was made again. Forget the token
        // and offer the person the connect step.
        vault.set_link_token(None);
    }
    Some(Refused::LinkTokenRequired) => { /* this link expects its token: set it */ }
    Some(Refused::AppAmbiguous) => { /* several apps share this origin: set the client id */ }
    Some(Refused::OriginNotRegistered) => { /* add the origin at dev.flowsta.com */ }
    Some(Refused::NotAddressedHere) => { /* call the Vault at 127.0.0.1 or localhost */ }
    None => { /* another answer */ }
}

The codes are listed in the Vault IPC reference.

Check before a write ​

The Vault is needed for the sign-in itself. After that, a person expects your app to keep working with their Vault locked or closed. identity keeps the link on the device and gives two checks.

rust
use flowsta_vault_client::identity::{self, IdentityLinkData, Refusal};

// After the link is recorded on your network (create_external_link):
identity::save_identity_link(&profile_dir, &IdentityLinkData {
    vault_agent_pub_key,      // the identity's key, "uhCAk..."
    entry_action_hash,        // the link record's hash on your network
    linked_at,                // when
});

// Before an everyday write:
match identity::require_identity_link(&vault, &profile_dir).await {
    Ok(link) => { /* go ahead */ }
    Err(Refusal::NotLinked) => { /* not signed in */ }
    Err(Refusal::OtherIdentity) => { /* a different identity's Vault is open here */ }
    Err(_) => { /* does not happen for this check */ }
}
CheckUse it forPasses when
require_identity_linkEveryday writesThis install is signed in. The Vault can be locked or closed. The one refusal beyond "not signed in" is a different identity unlocked on this device
require_identity_matchThe few operations that copy from the live Vault or rebind to it (a restore, refreshing the profile)The Vault is reachable, unlocked, and holds the same identity. Refusals: NotLinked, VaultNotRunning, VaultLocked, OtherIdentity

Put the check in one place that every write command passes through, and say each refusal in your app's own words. See Sign-in UX for the wording that works.

Show who is signed in ​

identity::CachedProfile keeps the display name and picture on the device, so your app can show who is signed in while the Vault is closed. Save it when the Vault answers (VaultProbe.display_name, profile_picture), read it with load_cached_profile, and delete it on disconnect.

Disconnect ​

A disconnect has three parts, in this order:

  1. On your network: the revoke_link zome call.
  2. On the device: identity::delete_identity_link and identity::delete_cached_profile.
  3. In the Vault: revokeFlowstaIdentity from the page, which reports what the Vault did so your app can say so. Then forget the link token (vault.set_link_token(None) and your own file).

Open the Vault ​

rust
flowsta_vault_client::vault::launch_vault(&[])?;

Opens the Flowsta Vault app when it is installed and not running, so the person does not have to go and find it during sign-in. An error means it could not be found or started: ask the person to open it. On Linux, the Vault starts without the environment variables you name in the argument; an app that uses the Linux window fix passes flowsta_hc_lines::webview::set_here().

Keep the device key ​

Two kinds of key, kept apart. The person's Flowsta identity keys stay in their Vault; your app never holds them and no app backup carries them. Your app's agent key on its own network is a different key, your app's own. By default a Holochain key store creates that key and it never leaves the device, so a lost computer means a new author on your network.

device_seed gives you the other choice: your app creates the seed of its device key itself, keeps it in a file, and imports it into the key store. A Vault backup can then carry it, and a new computer can carry on as the same key.

rust
use flowsta_vault_client::device_seed;

// The seed on file, or a new one stored now.
let seed = device_seed::load_or_create(&profile_dir, "device-recovery.json")?;

// Import seed.seed_bytes()? into your key store, then check that the
// key store derived the same public key:
let expected = device_seed::public_key(&seed)?;

// The block for your backup payload's `app_keys` field:
let app_keys = device_seed::app_keys_json(
    &profile_dir,
    "device-recovery.json",
    "This install has no device key to include yet.",
)?;

Treat the file like a key: back it up through the Vault, let the person export it, never log it. A file that cannot be read is an error and is never replaced with a new seed.

This only matters on a shared network, where other people's records name your app's agent as an author. An app whose data is the person's alone can restore by replaying its backup under a new key and needs none of this.

Back up safely ​

Picture a new computer: the person installs your app and signs in. The install has a fresh key, and its first backup would replace the backup that holds the old computer's key, before the person ever sees an offer to restore. backup_escrow_gate holds that backup back.

rust
use flowsta_vault_client::adopt::{backup_escrow_gate, Held, VaultEscrowProbe};
use flowsta_vault_client::device_seed;

let probe = VaultEscrowProbe { vault: vault.clone(), client_id: CLIENT_ID.into() };
let local = device_seed::load(&profile_dir, "device-recovery.json");

match backup_escrow_gate(&probe, local).await {
    Ok(()) => { /* build and return the payload */ }
    Err(Held::OtherKey) => { /* the Vault holds another device's key: offer the restore */ }
    Err(held) => { /* could not check, or no local key: do not write */ }
}

Run it before every backup payload you build. It writes when the Vault holds no backup, a backup without a key, or a backup with this device's key; it holds back in every other case, including when the check itself could not be made. From the page, startAutoBackup({ getData }) calls your Rust command for the payload, which is where the gate belongs.

Carry on from a new computer ​

When the Vault backup holds a different device key than this install's, offer the person the choice to carry on as that key. run_adopt then replaces the device key in an order that cannot leave it half done:

  1. Revoke this install's own link while its outgoing key can still sign.
  2. Stop every process that holds the old key's files.
  3. Remove what was derived from the old key (the key store and conductor folders), with retries, and verify that it is gone.
  4. Only then store the new seed. The old seed file is kept beside it with a timestamp.
  5. Drop the old sign-in and leave a marker, so that after its restart your app walks the person through connecting again.

Your app supplies the effects through the AdoptSeams trait (how to stop your conductor, which folders to remove); the library owns the order. adopt::target_exists, remove_target and finish_binding_swap are ready-made file effects for it. classify_escrow_payload reads a retrieved backup's app_keys block, and VaultEscrowProbe::retrieve fetches the backup. After the restart, import the new seed into the key store as usual; on Holochain 0.7 the key's own history can then be restored from its peers.

The same engine with no local seed (local: None) gives an install that predates app-held seeds a key that a backup can carry.

One profile per identity ​

Two people who share a computer account, or one person with two Flowsta identities, should never share keys or data inside your app. profiles gives each identity its own folder under your app's data folder: profiles/<folder>/, with profiles.json beside it as the index. The folder name is derived from the identity's key; an install that has not linked yet uses local.

rust
use flowsta_vault_client::profiles::{self, Layout};

let layout = Layout {
    recovery_file: "device-recovery.json",
    files: &["lair-passphrase"],
    also: &|_name| false,
    dirs: &["conductor", "lair"],
    key_stores: &["lair"],
    conductor: "conductor",
    repoint_key_store: &|_new_place| Ok(()),
};

// At launch: which identity does the Vault hold right now?
let live = vault.live_identity().await.and_then(|(_unlocked, key)| key);
let profile_dir = profiles::select_profile_root(&app_data_dir, live.as_deref(), &layout);

// After a new link: this profile now belongs to that identity.
profiles::bind_profile(&app_data_dir, &profile_dir, &vault_agent_pub_key);

select_profile_root opens the profile of the identity the Vault holds, and otherwise the one last used. It also moves an install from before profiles into a profile, all or nothing. A key store keeps absolute paths in its config, so repoint_key_store is called with a moved store's new place; with flowsta-hc-lines, call keystore::repoint_config from it.

For "Open as this identity" (the person switches identity in the Vault and your app follows): call vault::write_relaunch_marker, restart, and read it once at launch with take_relaunch_marker. Identity Switching covers what the person should see.

On macOS and Linux a key store's socket path has a short length limit; profiles::lair_socket_path_fits and short_socket_path are there for data folders with long names.

Not in this library ​

  • The link record on your network, and reading which keys belong to one person. Both are zome calls to the flowsta-agent-linking zomes, made with your app's own Holochain client.
  • Making the link, backups, signing. Those are the page's job: @flowsta/holochain.
  • Running the conductor. That is flowsta-hc-lines.

A complete example ​

ProofPoll uses every module here. In its src-tauri/src/ folder: vault_probe.rs (the one shared client), link_token.rs (the token file and refusals), commands.rs (the write checks, the link commit, disconnect), device_seed.rs, seed_adopt.rs (the backup check and carrying on from a new computer) and profiles.rs.

Documentation licensed under CC BY-SA 4.0.