- Rust 98.2%
- Python 1.1%
- Shell 0.7%
| Filename | Latest commit message | Latest commit date |
|---|---|---|
velrix-app 0.10.0: the privacy helpers — private, private_column and the title walker — mirroring the kernel, so an app marks a value and proves it never reaches a title, label or notice. Co-Authored-By: Claude Code <noreply@anthropic.com> |
||
| .forgejo/workflows | ||
| ci | ||
| src | ||
| vectors | ||
| .gitignore | ||
| Cargo.lock | ||
| Cargo.toml | ||
| LICENSE-APACHE | ||
| LICENSE-MIT | ||
| README.md | ||
| rustfmt.toml | ||
Velrix SDK
Build native apps for Velrix: your own service, running on a Velrix realm, with the realm's people, permissions, views and storage, without writing a platform module.
This repository holds the SDK for the app's own process, the workload. The Rust crate is
velrix-app.
- Trust every call you answer. The realm signs each call it forwards to your workload, for
that one copy of your app.
velrix-appchecks the signature, the copy, the time window and the nonce before your handler runs. Anything else gets refused, including a request that only claims to come from the realm. - Keep records nobody can quietly rewrite.
velrix_app::chainseals your records into a signed hash chain (Ed25519 and ML-DSA-65 together). The bytes are the same ones the Velrix kernel writes, so your realm can witness your chain's head, and a later rewrite is caught.
Install
[dependencies]
velrix-app = { git = "https://forge.velrix.com/velrix/sdk", tag = "v0.8.0" }
Answer a signed call
Your app declares an endpoint in its velrix.json ("native": { "endpoint": "/.velrix/call", "port": 8080, … }).
The realm sends every event there as an HTTP POST. Build the channel once at start, then check
each request before you handle it:
use velrix_app::{now_ms, Call, Channel};
fn handle(event: &str, by: &str, scope: &str, body: &[u8]) -> (u16, String) {
let _ = (by, scope, body);
(200, format!(r#"{{"ok":true,"event":"{event}"}}"#))
}
fn main() {
// No channel in the env means this copy was not started by a realm: refuse every call.
let Some(channel) = Channel::from_env() else { return };
// In your HTTP server, for each request:
let answer = |method: &str, path: &str, headers: &[(String, String)], body: &[u8]| {
let header = |name: &str| {
headers.iter().find(|(key, _)| key.eq_ignore_ascii_case(name)).map(|(_, value)| value.as_str())
};
match channel.verify(method, path, header, body, now_ms()) {
Ok(Call { by, scope, event, .. }) => handle(&event, &by, &scope, body),
Err(refused) => (401, format!(r#"{{"ok":false,"error":"unsigned","why":"{refused:?}"}}"#)),
}
};
let _ = answer;
}
by is the person who acted, already authenticated by the realm. scope is the app's owner
(user:…, org:…, or a project inside one). event is the event they asked for.
What verify checks
| Check | Refused as |
|---|---|
| The signature matches this app's key, over the method, path, app, copy, caller, scope, event, time, nonce and the body's SHA-256 | Unsigned |
| The call names this app and this copy (a call signed for another copy is never accepted here) | OtherCopy |
| It was signed inside the window, and not before this process started | OutsideWindow |
| Its nonce was not used before | Replayed |
Comparisons are constant-time. A restart forgets the nonces it has seen, so the rule "not signed before this process started" closes that gap. The only slack is clock skew between the realm's host and this copy's host, bounded by the window.
What the realm gives each copy
| Variable | Meaning |
|---|---|
VELRIX_APP_ID |
your app's id |
VELRIX_COPY_ID |
this copy's id |
VELRIX_APP_SECRET |
this app's signing key (hex), derived by the realm, never stored |
VELRIX_CALL_WINDOW_MS |
how far a call's time may be from this copy's clock |
VELRIX_TRANSFER_IDLE_MS |
how long a transfer nobody sends to is kept before you drop it |
| VELRIX_APP_TOKEN | this app's own credential for calls out, derived by the realm, never stored |
| VELRIX_API_URL | the realm's edge API (https://<realm>/api) |
An app can't set these names itself: VELRIX_ is reserved. The names are velrix_app::env, and
the headers of a signed call velrix_app::header; the realm builds its calls from the same
constants.
Call the realm as your app
use serde_json::json;
use velrix_app::client::Client;
let client = Client::new("https://realm.example/api", "vlxa_a-books_…");
let answer = client.call("compute:app.native.storage", &json!({ "id": "a-books", "op": "get", "key": "notes/1" }), |request| {
assert_eq!(request.url, "https://realm.example/api/compute/app.native.storage");
Ok::<_, String>((200, br#"{"ok":true,"result":{"ok":true,"found":false}}"#.to_vec()))
});
assert_eq!(answer.expect("answered")["found"], false);
Client::from_env() reads VELRIX_API_URL and VELRIX_APP_TOKEN. The crate carries no HTTP
client: call hands you a Request (URL, headers, JSON body) to send with the one your app
already uses, and reads the answer; async apps call request and Client::answer around their own
send. The token is a bearer secret: keep it out of your logs. Request and Client print it as
<redacted>, and Request::headers() is the one way to read it, for your HTTP client.
What the token may call is decided by the realm, call by call: the events your velrix.json lists
under native.wants, once consent holds a grant for them from your app's owner, and only events
whose spec admits app callers. It acts as your app (app:<id>), pinned to your app's owner.
Book a contributor's journal exactly once
use velrix_app::{client::Client, journal};
let client = Client::new("https://realm.example/api", "vlxa_a-books_…");
let cursor = 0; // read from your own database
let page = journal::pull(&client, "billing:journal.since", "org:acme", cursor, 500, |_request| {
Ok::<_, String>((200, br#"{"ok":true,"result":{"ok":true,"entries":[{"seq":1,"id":"billing/org:acme/1","seller":"org:acme"}],"next":1}}"#.to_vec()))
})
.expect("pulled");
let booked = |_id: &str| false; // an entry id your database already holds
let fresh: Vec<_> = page.unbooked(booked).collect();
assert_eq!((fresh.len(), page.next), (1, 1));
Exactly once is your transaction, not the delivery: fetch first, then in one database
transaction book the entries unbooked leaves, record their ids, and store page.next as the
cursor. A crash before the commit books nothing and the next pull fetches the same entries; a
cursor that went back books nothing twice, because the ids decide. Keep one cursor per contributor
event. Pull until next equals the cursor you asked from. List the event under native.wants; the
contributor answers only for the organisation your app belongs to, once that organisation allowed
it (asked in its consent prompt the first time you pull). billing:journal.appended {seller, next}
in native.subscribes wakes you when there is more; it can be lost, so pull on a schedule too
(native.schedules).
pull checks the page before you book it: every entry names the seller you asked for and has an
id, the seqs rise strictly after your cursor and stop at next, and there are no more entries than
your limit. A page that breaks any of these is CallError::Answer, and nothing in it is handed to
you.
Keep a signed chain
use serde_json::json;
use velrix_app::{chain, now_ms};
let keys = chain::generate_keys().expect("a key pair");
let signer = chain::Signer { instance: "books".into(), private_key: keys.private_key.clone() };
let mut head = chain::Head::zero();
let record = chain::seal(&head, now_ms(), json!({ "voucher": "V-0001", "amount": 125000 }), &signer, "books");
head = chain::Head::of(&record).expect("a sealed record");
let trusted = std::collections::BTreeMap::from([("books".to_string(), vec![keys.public_key.clone()])]);
let problems = chain::verify_records(&[record], &chain::Head::zero(), &trusted, "books");
assert!(problems.is_empty());
Keep the private key in your app's sealed environment and the chain in your own storage. A record
that was changed, removed or reordered shows up in verify_records as a problem. The domain
string separates your chain's signatures from any other use of the same key.
Have the realm witness your chain
Your app keeps its chain and its key; the realm keeps a witnessed record of the chain's head, so
a later rewrite is caught even by someone who holds your key and your database. Declare the chain
in velrix.json ("native": { "chains": ["vouchers"], "wants": ["compute:app.native.checkpoint", "compute:app.native.checkpoints"], … }), then send each new head:
use serde_json::json;
use velrix_app::{chain, client::Client, now_ms};
let keys = chain::generate_keys().expect("a key pair");
let signer = chain::Signer { instance: "books".into(), private_key: keys.private_key.clone() };
let record = chain::seal(&chain::Head::zero(), now_ms(), json!({ "voucher": "V-0001" }), &signer, "books");
let head = chain::Head::of(&record).expect("a sealed record");
let client = Client::new("https://realm.example/api", "vlxa_a-books_…");
let asked = chain::checkpoint("a-books", "vouchers", &head, &keys.private_key).expect("a readable key");
let answer = client.call("compute:app.native.checkpoint", &asked, |_request| {
Ok::<_, String>((200, br#"{"ok":true,"result":{"ok":true,"recorded":"appended","witnessed":true}}"#.to_vec()))
});
assert_eq!(answer.expect("answered")["recorded"], "appended");
// Later, to verify: read the realm's records and compare them with yours.
let witnessed = vec![json!({ "appSeq": 1, "appHash": head.hash })];
assert!(chain::compare(&[record], &witnessed).is_empty());
compute:app.native.checkpoints {id, chain, after, limit} answers the realm's records
(appSeq, appHash, …) and its own check of them (verify.issues empty, verify.witnessed above
zero). compare then names every witnessed head your records no longer match: witness (the
record at that seq has another hash), truncated (your chain stops before it) or missing (you
passed records with a gap there). Pass every record from the oldest witnessed seq you compare.
The answers to a checkpoint:
| Answer | Meaning |
|---|---|
recorded: appended |
a newer head, recorded; witnessed once a witness kept it (otherwise the realm retries) |
recorded: same |
this head was already recorded |
error: busy |
sooner than the realm's interval (an hour by default) after your last head: send it after retryAfterMs |
error: diverged |
a head at or below the last one recorded, with another hash: your history changed. Your owner is told |
error: signature |
sig is not your chain key's signature over this head |
error: key |
another key than the one the realm holds for this chain, without that key's handover |
checkpoint signs the head with your chain key (domain chain::HEAD_DOMAIN, over the app id, the
chain, seq, hash and at) and sends the public key with it. The realm checks the signature
and keeps the first key it sees for each chain, so a stolen app token alone can no longer move
your chain's head. To rotate, sign the handover with the old key:
use velrix_app::chain;
let (old, new) = (chain::generate_keys().expect("a key pair"), chain::generate_keys().expect("a key pair"));
let head = chain::Head { seq: 2, hash: "ab".repeat(32), at: 1 };
let asked = chain::checkpoint("a-books", "vouchers", &head, &new.private_key).expect("a readable key");
let asked = chain::rekeyed(asked, &old.private_key);
assert!(asked["keySig"].as_str().is_some_and(|signature| !signature.is_empty()));
The realm appends it marked keyChanged and tells your owner. A lost key can't hand over: declare
a new chain in native.chains and start it with the new key; the old chain's witnessed heads stay.
chain::fingerprint(public_key) is the key's short id (the first 16 hex of the SHA-256 of its DER,
as the realm shows it in key).
Take and hand over files
An event that takes a file declares "transfer": { "in": { "maxBytes": 52428800, "accept": ".csv" } }
in native.events; one that hands one over declares "transfer": { "out": {} }. A view you draw
offers them as { "upload": { "event": "import" } } and { "receive": { "event": "export" } }. The
realm checks the person's permission and the size of every piece, then sends each piece to your
endpoint as a signed call with transfer in the body. It keeps no transfer state: you hold the
bytes, and your answer's next comes back with the following piece.
use serde_json::json;
use velrix_app::transfer::{self, Taken};
use velrix_app::{Call, Channel};
let channel = Channel::new(b"from VELRIX_APP_SECRET".to_vec(), "a-books".into(), "a-books-1".into(), 60_000, 0);
// What `channel.verify` answered for this request.
let call = Call { app: "a-books".into(), copy: "a-books-1".into(), by: "alice".into(), scope: "org:acme".into(), event: "import".into() };
// One piece of an upload, as your endpoint receives it.
let body = json!({ "event": "import", "input": {}, "transfer": {
"name": "bank.csv", "content": "aGVsbG8=", "offset": 0, "done": true, "next": {} } });
let piece = transfer::piece(&body).expect("a piece");
let transfer_id = match channel.open_next(&call, &piece.next) {
Ok(Some(id)) => id, // a transfer this person started with this event
Ok(None) => "t-1".to_string(), // no next: a new transfer, named by you
Err(_) => return, // a next you never sealed for this person: refuse the piece
};
let next = channel.seal_next(&call, &transfer_id).expect("a sealable id");
let mut held: Vec<u8> = Vec::new(); // read from your database by `transfer_id`
let answer = match piece.taken(held.len() as u64) {
Taken::Append => {
held.extend_from_slice(&piece.content); // and store it, in the same transaction as the length
transfer::held(next, held.len() as u64, piece.done)
}
Taken::Already => transfer::held(next, held.len() as u64, piece.done),
Taken::Gap => transfer::gap(next, held.len() as u64),
};
assert_eq!(answer["result"]["size"], 5);
// One ask of a download: answer the bytes in the range the realm asked for.
let file = b"#FLAGGA 0\n";
let asked = transfer::ask(&json!({ "transfer": { "offset": 0, "pieceBytes": 524288, "next": {} } })).expect("an ask");
let range = asked.range(file.len() as u64);
let piece = &file[range.start as usize..range.end as usize];
let export = Call { event: "export".into(), ..call };
let answer = transfer::handed("books.se", range.start, piece, file.len() as u64, channel.seal_next(&export, "e-1").expect("sealed"));
assert_eq!(answer["result"]["done"], true);
Seal every next. It travels through the person's browser and comes back with the next piece,
so a bare {"transfer": "t-1"} lets one person name another person's transfer and append to their
upload or read their export. seal_next binds the id to the app, the person (by) and the event
with your channel secret; open_next answers the id only for that same person and event, and
Err for anything else.
A piece at the length you hold is appended; one you already hold (sent again) is answered without
storing it twice; anything else is refused offset with the length you hold. Name a transfer in
your first answer's next and keep it in your own database with its length. Drop transfers nobody
sent to for VELRIX_TRANSFER_IDLE_MS (transfer::idle_ms()); the bytes count against your own
storage. A download that is not ready yet answers transfer::preparing(), and is asked again.
Reach an outside account through the realm
Fortnox, a bank through Enable Banking, Stripe, PayPal, Blesta: the realm holds the credential, never your app (native-parity Q4, Emilio's ruling of 2026-11-13). Declare the connection, the provider instance the owner set up for it, and who may connect it:
"native": {
"connections": { "fortnox": { "instance": "fortnox", "permission": "books.manage" } },
"wants": ["connections:fetch", "connections:status"]
}
A person connects it from your view with { "event": "compute:app.native.connect", "payload": { "connection": "fortnox" } } (add "options": { "aspsp": "Nordea", "country": "FI" } for a bank).
The realm sends them to the service or its own form, keeps the state, the code and the tokens,
refreshes and rotates them under one claim per connection, and audits every use. Your app asks
the realm to make each call:
use velrix_app::client::Client;
use velrix_app::connections::{self, FetchError, Outside, Refused};
let client = Client::new("https://realm.example/api", "vlxa_a-books_…");
let invoices = connections::fetch(&client, "fortnox", &Outside::get("https://api.fortnox.se/3/invoices"), |_request| {
Ok::<_, String>((200, br#"{"ok":true,"result":{"ok":true,"status":200,"headers":{},"body":"e30="}}"#.to_vec()))
});
match invoices {
Ok(answer) => assert_eq!(answer.status, 200),
Err(FetchError::Refused(Refused::Reconnect)) => { /* show a Connect button again */ }
Err(FetchError::Refused(Refused::Busy)) => { /* another call is refreshing: ask again later */ }
Err(other) => panic!("{other:?}"),
}
- Only the connection's own addresses are reached (the instance's API base; for a bank, the
session's own accounts). Anything else is
Address. connections::statusanswers the state, the account's label and what the provider lets you see (a bank connection's account ids, names and currencies), never a token.Reconnect: the service refused the credential for good, or the consent ended. The person who connected it is told; show your Connect button again.Ungranted: the owner has not yet let your app use its connections (consent asks them).
Keep a secret of your own
secrets hold your app's own private values: a key it generated, a webhook signing secret,
a seed. Never a token for someone else's service: that is a connection. A blueprint whose secret
is named like a declared connection (fortnox, or fortnox.anything) is refused at create.
Declare the name in velrix.json ("native": { "secrets": ["webhook.key"], "wants": ["compute:app.native.secret"], … }). The realm seals each value for your app and that name,
never logs or shows it, and audits every call. Your owner's operators may set or clear a value,
never read it.
use velrix_app::client::Client;
use velrix_app::secrets::{self, Written};
let client = Client::new("https://realm.example/api", "vlxa_a-books_…");
let held = secrets::get(&client, "a-books", "webhook.key", |_request| {
Ok::<_, String>((200, br#"{"ok":true,"result":{"ok":true,"found":true,"version":3,"value":"k-1"}}"#.to_vec()))
})
.expect("read");
let written = secrets::put(&client, "a-books", "webhook.key", "k-2", held.version, |_request| {
Ok::<_, String>((200, br#"{"ok":true,"result":{"ok":false,"error":"conflict","version":4}}"#.to_vec()))
})
.expect("answered");
assert_eq!(written, Written::Conflict(4)); // another copy rotated first: read again and use its value
Every write names the version it read, so of two copies that rotate at once only one stores its
value; the other gets Conflict with the current version, reads it, and uses that. An operator's
change moves the version too. clear drops the value and keeps the version counting. Secret
prints its value as <redacted>. A value is at most the owner's policy
compute.native-secret-bytes (8 KiB by default).
Keep files
files::FileStore keeps files on your app's own volume, named by their SHA-256: payslip PDFs,
SRU and AGI files, receipts. Your records name a file by that hash; the bytes are written once
and never change.
use velrix_app::files::FileStore;
let dir = std::env::temp_dir().join("velrix-app-readme-files");
let store = FileStore::open(&dir).expect("opened");
let stored = store.put(b"%PDF-1.7 ...").expect("stored");
assert_eq!(store.size(&stored.sha256).expect("read"), Some(stored.size));
// At start, before you serve: remove files no record names and uploads left behind.
let swept = store.sweep(|sha256| sha256 == stored.sha256, std::time::SystemTime::now()).expect("swept");
assert_eq!(swept.files, 0);
put(bytes)writes once (the same bytes again are the same file): a temporary file,fsync, rename,fsyncof the directory.append(transfer, piece)takes an upload's pieces (transfer::piece), each appended once, andfinish(transfer, expected_sha256)names it by its hash, refusing a mismatch.hand(sha256, name, ask, next)answers one piece of areceive, the download your views offer with{ "receive": { "event": … } }.- There is no remove.
sweep(known, incoming_before)removes what no record names, and is meant to run once at start, before serving: write the file before the record that names it, and a record never names a missing file.
The volume's size (under your owner's storage quota) bounds the store; a full volume is an I/O
error. A retention policy (native.retention in your blueprint, compute:app.native.hold) holds
the volume, and so every file on it, for the years the law says.
Compatibility
Realms are dated releases; what an app depends on is the spec of the capability it calls. The
column says which spec versions each release of this crate speaks (compute, billing) and the
call signature it checks.
| velrix-app | Specs it speaks | What changed |
|---|---|---|
| 0.9 | compute 6.1 and later 6.x, connections 1, billing 7, call v1 |
outside accounts through the realm's connections (NPR6); browser callbacks (NS2) removed (the realm finishes every flow); secrets for app-private values only |
| 0.8 | compute 6.1 (unreleased NS build), billing 7, call v1 |
sealed secrets the app rotates (NS1), browser callbacks (NS2), a content-addressed file store (NS3) |
| 0.7 | compute 6 (from 6.0), billing 7, call v1 |
signed checkpoints and key handover (NA11), sealed transfer next (NA9), journal pages checked, canonical JSON with sorted keys, DER key fingerprint, redacted secrets; not for compute 5 (realm 2026.11.18 and before) |
| 0.6 | compute 5.5–5.x, billing 7, call v1 |
files in and out in pieces (NA9) |
| 0.5 | compute 5.4, call v1 |
the realm witnessing an app's chain heads (NA11) |
| 0.4 | billing 7 (journal.since), call v1 |
pulling a contributor's journal by cursor (NA7) |
| 0.3 | call v1 |
the app's own credential out (NA3b) |
| 0.2 | call v1 |
app chains (NA11) |
| 0.1 | call v1 |
signed calls (NA3a) |
The call signature is versioned (X-Velrix-Signature: v1=…). vectors/chain.json is a shared test
vector: this crate and the Velrix kernel both verify it and reseal it to the same bytes, and both
check its key fingerprint and its canonical-JSON cases, so the two can't drift apart. The canonical
form sorts keys itself, so an app whose dependency tree turns on serde_json's preserve_order
hashes the same bytes; cargo test --features serde_json/preserve_order proves it.
Develop
cargo test
cargo clippy --all-targets -- -D warnings
Licence
Licensed under either of Apache License, Version 2.0 or MIT license, at your option. Copyright Hypefox AB.
Unless you explicitly state otherwise, any contribution you intentionally submit for inclusion in this crate shall be dual licensed as above, without any additional terms or conditions.