[share] Share links and the browser build: custos-share (blob v1, key in the fragment, optional password), custos-wasm (JSON ABI, no wasm-bindgen), docs/SHARE.md, threat model (v0.3.0)
This commit is contained in:
@@ -0,0 +1,24 @@
|
||||
[package]
|
||||
name = "custos-wasm"
|
||||
description = "Custos in the browser: the web vault's and the share page's crypto, compiled to WebAssembly"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
repository.workspace = true
|
||||
|
||||
[lib]
|
||||
crate-type = ["cdylib", "rlib"]
|
||||
|
||||
[dependencies]
|
||||
custos-vault = { path = "../custos-vault" }
|
||||
custos-share = { path = "../custos-share" }
|
||||
custos-totp = { path = "../custos-totp" }
|
||||
custos-qr = { path = "../custos-qr" }
|
||||
serde.workspace = true
|
||||
serde_json.workspace = true
|
||||
data-encoding.workspace = true
|
||||
zeroize.workspace = true
|
||||
qrcode = { version = "0.14", default-features = false, features = ["svg"] }
|
||||
|
||||
[target.'cfg(target_arch = "wasm32")'.dependencies]
|
||||
getrandom = "0.4"
|
||||
@@ -0,0 +1,46 @@
|
||||
// The whole JavaScript side of custos-wasm (see src/lib.rs, "ABI"): load the module, give it the
|
||||
// browser's CSPRNG, and pass JSON requests in and out. The vault key never leaves WebAssembly memory.
|
||||
|
||||
/** @param {BufferSource | Response | Promise<Response>} source the custos_wasm.wasm bytes or a fetch of them */
|
||||
export async function loadCustos(source) {
|
||||
let memory;
|
||||
const env = {
|
||||
random_fill(ptr, len) {
|
||||
// getRandomValues fills at most 65,536 bytes per call.
|
||||
for (let off = 0; off < len; off += 65536) {
|
||||
crypto.getRandomValues(new Uint8Array(memory.buffer, ptr + off, Math.min(65536, len - off)));
|
||||
}
|
||||
},
|
||||
};
|
||||
const { instance } =
|
||||
source instanceof Response || source instanceof Promise
|
||||
? await WebAssembly.instantiateStreaming(source, { env })
|
||||
: await WebAssembly.instantiate(source, { env });
|
||||
const x = instance.exports;
|
||||
memory = x.memory;
|
||||
const enc = new TextEncoder();
|
||||
const dec = new TextDecoder();
|
||||
|
||||
/** Sends one request; resolves to the parsed response ({ok: true, …} or {ok: false, error}). */
|
||||
function call(request) {
|
||||
const bytes = enc.encode(JSON.stringify(request));
|
||||
const ptr = x.alloc(bytes.length);
|
||||
new Uint8Array(memory.buffer, ptr, bytes.length).set(bytes);
|
||||
bytes.fill(0);
|
||||
const packed = x.call(ptr, bytes.length); // frees and zeroes the request
|
||||
const outPtr = Number(packed >> 32n);
|
||||
const outLen = Number(packed & 0xffffffffn);
|
||||
const out = new Uint8Array(memory.buffer, outPtr, outLen);
|
||||
const text = dec.decode(out);
|
||||
x.dealloc(outPtr, outLen); // zeroes the response in WebAssembly memory
|
||||
return JSON.parse(text);
|
||||
}
|
||||
return { call };
|
||||
}
|
||||
|
||||
/** Base64 of bytes, for the `open` and `share_open` requests. */
|
||||
export function toBase64(bytes) {
|
||||
let s = '';
|
||||
for (let i = 0; i < bytes.length; i += 0x8000) s += String.fromCharCode(...bytes.subarray(i, i + 0x8000));
|
||||
return btoa(s);
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
// node test.mjs <custos_wasm.wasm> [<vault file> <password>]: the JS loader against the real build.
|
||||
import fs from 'node:fs';
|
||||
import { loadCustos, toBase64 } from './custos.mjs';
|
||||
|
||||
const [wasmPath, vaultPath, password] = process.argv.slice(2);
|
||||
const c = await loadCustos(fs.readFileSync(wasmPath));
|
||||
const assert = (ok, msg) => { if (!ok) { console.error('FAIL', msg); process.exit(1); } };
|
||||
|
||||
const bad = c.call({ op: 'share_open', blob: 'Q1NIMQA=', fragment: 'k=x' });
|
||||
assert(!bad.ok && bad.code === 'Malformed', JSON.stringify(bad));
|
||||
assert(c.call({ op: 'items' }).error === 'The vault is locked.', 'locked');
|
||||
|
||||
if (vaultPath) {
|
||||
const t0 = performance.now();
|
||||
const r = c.call({ op: 'open', vault: toBase64(fs.readFileSync(vaultPath)), password });
|
||||
const ms = Math.round(performance.now() - t0);
|
||||
assert(r.ok, r.error);
|
||||
console.log(`unlocked ${r.items.length} items in ${ms} ms (WebAssembly, default KDF)`);
|
||||
const item = r.items.find((i) => i.hasMainSecret);
|
||||
for (const pw of [null, 'by-phone']) {
|
||||
const t1 = performance.now();
|
||||
const s = c.call({ op: 'share_seal', id: item.id, password: pw });
|
||||
assert(s.ok, s.error);
|
||||
const o = c.call({ op: 'share_open', blob: s.blob, fragment: s.fragment, password: pw });
|
||||
assert(o.ok && o.payload.title === item.title, JSON.stringify(o.error));
|
||||
console.log(`share ${pw ? 'with' : 'without'} password: sealed and opened in ${Math.round(performance.now() - t1)} ms`);
|
||||
}
|
||||
const fresh = new Set(Array.from({ length: 100 }, () => c.call({ op: 'share_seal', id: item.id }).fragment));
|
||||
assert(fresh.size === 100, 'link keys repeat: random_fill is broken');
|
||||
c.call({ op: 'lock' });
|
||||
}
|
||||
console.log('ok');
|
||||
@@ -0,0 +1,315 @@
|
||||
//! Custos in the browser. The web vault and the share recipient page load this crate compiled to
|
||||
//! `wasm32-unknown-unknown`; everything that touches a key or plaintext happens here, in code from this
|
||||
//! public repository. The page's JavaScript only moves JSON in and out.
|
||||
//!
|
||||
//! # ABI (no wasm-bindgen)
|
||||
//! Exports:
|
||||
//! - `memory`
|
||||
//! - `alloc(len) -> ptr` and `dealloc(ptr, len)`; `dealloc` zeroes the bytes before freeing them.
|
||||
//! - `call(ptr, len) -> u64`: takes a JSON request the caller wrote into an `alloc`ed buffer (and frees it,
|
||||
//! zeroed), returns `(response_ptr << 32) | response_len`. The caller reads the JSON response and gives it
|
||||
//! back with `dealloc`.
|
||||
//!
|
||||
//! Import: `env.random_fill(ptr, len)`, which must fill the bytes from `crypto.getRandomValues`
|
||||
//! (getrandom's custom backend; `.cargo/config.toml` selects it for this target).
|
||||
//!
|
||||
//! Requests are `{"op": …, …}`; responses `{"ok": true, …}` or `{"ok": false, "error": "<message>"}`.
|
||||
//! See [`handle`] for the operations. One vault at a time is held here while unlocked; `lock` drops it
|
||||
//! (and with it the key, wiped).
|
||||
|
||||
use custos_share::{Payload, ShareError};
|
||||
use custos_vault::{Item, ItemType, SecretString, Vault};
|
||||
use data_encoding::BASE64;
|
||||
use qrcode::render::svg;
|
||||
use qrcode::{EcLevel, QrCode};
|
||||
use serde::Deserialize;
|
||||
use serde_json::{Value, json};
|
||||
use std::cell::RefCell;
|
||||
use zeroize::Zeroizing;
|
||||
|
||||
thread_local! {
|
||||
static VAULT: RefCell<Option<Vault>> = const { RefCell::new(None) };
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(tag = "op", rename_all = "snake_case", rename_all_fields = "camelCase")]
|
||||
enum Request {
|
||||
/// `vault`: the `.custos` file, base64.
|
||||
Open {
|
||||
vault: String,
|
||||
password: SecretString,
|
||||
},
|
||||
Lock,
|
||||
Items,
|
||||
/// A field's value by name and index among fields of that name, or `name: "notes"`.
|
||||
Reveal {
|
||||
id: String,
|
||||
name: String,
|
||||
#[serde(default)]
|
||||
index: usize,
|
||||
},
|
||||
/// `now`: Unix seconds (WebAssembly has no clock of its own).
|
||||
Totp {
|
||||
id: String,
|
||||
now: u64,
|
||||
},
|
||||
/// A Wi-Fi item gives its join code, anything else its main secret.
|
||||
Qr {
|
||||
id: String,
|
||||
},
|
||||
ShareSeal {
|
||||
id: String,
|
||||
password: Option<SecretString>,
|
||||
},
|
||||
/// `blob`: base64, as the share server returned it.
|
||||
ShareOpen {
|
||||
blob: String,
|
||||
fragment: String,
|
||||
password: Option<SecretString>,
|
||||
},
|
||||
}
|
||||
|
||||
fn err(msg: impl ToString) -> Value {
|
||||
json!({ "ok": false, "error": msg.to_string() })
|
||||
}
|
||||
|
||||
/// The field *Copy* and the QR code use for each type (the desktop app's choice).
|
||||
pub fn primary_secret(kind: ItemType) -> &'static str {
|
||||
match kind {
|
||||
ItemType::WebLogin | ItemType::LocalApp | ItemType::Wifi => "password",
|
||||
ItemType::ApiCredential => "secret",
|
||||
ItemType::Card => "number",
|
||||
ItemType::SecureNote => "notes",
|
||||
}
|
||||
}
|
||||
|
||||
fn primary_user(kind: ItemType) -> Option<&'static str> {
|
||||
match kind {
|
||||
ItemType::WebLogin | ItemType::LocalApp => Some("username"),
|
||||
ItemType::ApiCredential => Some("key-id"),
|
||||
ItemType::Wifi => Some("ssid"),
|
||||
ItemType::Card => Some("cardholder"),
|
||||
ItemType::SecureNote => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn plain<'a>(item: &'a Item, name: &str) -> Option<&'a str> {
|
||||
item.field(name).filter(|f| !f.secret).map(|f| f.value.expose()).filter(|v| !v.is_empty())
|
||||
}
|
||||
|
||||
fn value<'a>(item: &'a Item, name: &str, index: usize) -> Option<&'a SecretString> {
|
||||
if name == "notes" {
|
||||
return Some(&item.notes);
|
||||
}
|
||||
item.fields.iter().filter(|f| f.name == name).nth(index).map(|f| &f.value)
|
||||
}
|
||||
|
||||
/// An item for the page: non-secret field values, secret ones only as "has a value".
|
||||
fn view(item: &Item) -> Value {
|
||||
let urls: Vec<&str> =
|
||||
item.fields.iter().filter(|f| f.name == "url" && !f.value.is_empty()).map(|f| f.value.expose()).collect();
|
||||
let subtitle = primary_user(item.kind)
|
||||
.and_then(|n| plain(item, n))
|
||||
.or(plain(item, "service"))
|
||||
.or(plain(item, "target"))
|
||||
.or(urls.first().copied())
|
||||
.unwrap_or("");
|
||||
let mut seen = std::collections::HashMap::<&str, usize>::new();
|
||||
let fields: Vec<Value> = item
|
||||
.fields
|
||||
.iter()
|
||||
.map(|f| {
|
||||
let n = seen.entry(f.name.as_str()).or_default();
|
||||
let index = *n;
|
||||
*n += 1;
|
||||
json!({
|
||||
"name": f.name,
|
||||
"index": index,
|
||||
"secret": f.secret,
|
||||
"hasValue": !f.value.is_empty(),
|
||||
"value": if f.secret { Value::Null } else { Value::from(f.value.expose()) },
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
let main = primary_secret(item.kind);
|
||||
json!({
|
||||
"id": item.id,
|
||||
"kind": item.kind,
|
||||
"title": item.title,
|
||||
"subtitle": subtitle,
|
||||
"urls": urls,
|
||||
"tags": item.tags,
|
||||
"fields": fields,
|
||||
"hasNotes": !item.notes.is_empty(),
|
||||
"mainSecret": main,
|
||||
"hasMainSecret": value(item, main, 0).is_some_and(|v| !v.is_empty()),
|
||||
"hasTotp": item.field("totp").is_some_and(|f| !f.value.is_empty()),
|
||||
"modified": item.modified,
|
||||
})
|
||||
}
|
||||
|
||||
fn items(v: &Vault) -> Value {
|
||||
json!({ "ok": true, "items": v.items().iter().map(view).collect::<Vec<_>>() })
|
||||
}
|
||||
|
||||
fn with_item(id: &str, f: impl FnOnce(&Item) -> Value) -> Value {
|
||||
VAULT.with_borrow(|v| match v {
|
||||
None => err("The vault is locked."),
|
||||
Some(v) => match v.item(id) {
|
||||
None => err("Item not found."),
|
||||
Some(item) => f(item),
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
fn qr_svg(payload: &str) -> Result<String, String> {
|
||||
let code = QrCode::with_error_correction_level(payload.as_bytes(), EcLevel::M).map_err(|e| e.to_string())?;
|
||||
Ok(code.render::<svg::Color>().min_dimensions(320, 320).quiet_zone(true).build())
|
||||
}
|
||||
|
||||
fn payload_json(p: &Payload) -> Value {
|
||||
json!({
|
||||
"title": p.title,
|
||||
"kind": p.kind,
|
||||
"fields": p.fields.iter().map(|f| json!({ "name": f.name, "value": f.value.expose(), "secret": f.secret })).collect::<Vec<_>>(),
|
||||
"notes": p.notes.as_ref().map(|n| n.expose()),
|
||||
})
|
||||
}
|
||||
|
||||
fn share_error(e: ShareError) -> Value {
|
||||
json!({ "ok": false, "error": e.to_string(), "code": format!("{e:?}") })
|
||||
}
|
||||
|
||||
/// Handles one request. Native code (and the tests) call this directly; the browser goes through `call`.
|
||||
pub fn handle(request: &[u8]) -> Value {
|
||||
let req: Request = match serde_json::from_slice(request) {
|
||||
Ok(r) => r,
|
||||
// serde's message can quote the input, which may hold a password: say only what failed.
|
||||
Err(_) => return err("Bad request."),
|
||||
};
|
||||
match req {
|
||||
Request::Open { vault, password } => {
|
||||
let Ok(bytes) = BASE64.decode(vault.as_bytes()) else { return err("The vault file is damaged.") };
|
||||
match Vault::open(&bytes, &password) {
|
||||
Ok(v) => {
|
||||
let out = items(&v);
|
||||
VAULT.set(Some(v));
|
||||
out
|
||||
}
|
||||
Err(e) => err(e),
|
||||
}
|
||||
}
|
||||
Request::Lock => {
|
||||
VAULT.set(None);
|
||||
json!({ "ok": true })
|
||||
}
|
||||
Request::Items => VAULT.with_borrow(|v| v.as_ref().map(items).unwrap_or_else(|| err("The vault is locked."))),
|
||||
Request::Reveal { id, name, index } => with_item(&id, |item| match value(item, &name, index) {
|
||||
Some(v) => json!({ "ok": true, "value": v.expose() }),
|
||||
None => err("No such field."),
|
||||
}),
|
||||
Request::Totp { id, now } => with_item(&id, |item| {
|
||||
let Some(f) = item.field("totp").filter(|f| !f.value.is_empty()) else { return err("No 2FA code here.") };
|
||||
match custos_totp::Totp::parse(f.value.expose()) {
|
||||
Ok(t) => {
|
||||
json!({ "ok": true, "code": t.code_at(now), "secondsLeft": t.seconds_left(now), "period": t.period() })
|
||||
}
|
||||
Err(e) => err(e),
|
||||
}
|
||||
}),
|
||||
Request::Qr { id } => with_item(&id, |item| {
|
||||
let f = |n: &str| item.field(n).map(|f| f.value.expose()).unwrap_or("");
|
||||
let (payload, wifi) = if item.kind == ItemType::Wifi {
|
||||
let p = custos_qr::wifi_payload(
|
||||
f("ssid"),
|
||||
f("password"),
|
||||
custos_qr::WifiSecurity::parse(f("security")),
|
||||
f("hidden") == "true",
|
||||
);
|
||||
(Zeroizing::new(p), true)
|
||||
} else {
|
||||
match value(item, primary_secret(item.kind), 0).filter(|v| !v.is_empty()) {
|
||||
Some(v) => (Zeroizing::new(custos_qr::secret_payload(v.expose())), false),
|
||||
None => return err("Nothing to show."),
|
||||
}
|
||||
};
|
||||
match qr_svg(&payload) {
|
||||
Ok(svg) => json!({ "ok": true, "svg": svg, "wifi": wifi }),
|
||||
Err(e) => err(e),
|
||||
}
|
||||
}),
|
||||
Request::ShareSeal { id, password } => with_item(&id, |item| {
|
||||
let password = password.filter(|p| !p.is_empty());
|
||||
match custos_share::seal(&Payload::from_item(item), password.as_ref()) {
|
||||
Ok(s) => json!({ "ok": true, "blob": BASE64.encode(&s.blob), "fragment": s.fragment.as_str() }),
|
||||
Err(e) => share_error(e),
|
||||
}
|
||||
}),
|
||||
Request::ShareOpen { blob, fragment, password } => {
|
||||
let Ok(bytes) = BASE64.decode(blob.as_bytes()) else { return share_error(ShareError::Malformed) };
|
||||
match custos_share::open(&bytes, &fragment, password.as_ref()) {
|
||||
Ok(p) => json!({ "ok": true, "payload": payload_json(&p) }),
|
||||
Err(e) => share_error(e),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ---------- the WebAssembly ABI ----------
|
||||
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
mod abi {
|
||||
use std::alloc::{Layout, alloc as raw_alloc, dealloc as raw_dealloc};
|
||||
use zeroize::Zeroize;
|
||||
|
||||
#[link(wasm_import_module = "env")]
|
||||
unsafe extern "C" {
|
||||
fn random_fill(ptr: *mut u8, len: usize);
|
||||
}
|
||||
|
||||
/// getrandom's custom backend: the browser's CSPRNG.
|
||||
#[unsafe(no_mangle)]
|
||||
unsafe extern "Rust" fn __getrandom_v03_custom(dest: *mut u8, len: usize) -> Result<(), getrandom::Error> {
|
||||
unsafe { random_fill(dest, len) };
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[unsafe(no_mangle)]
|
||||
pub extern "C" fn alloc(len: usize) -> *mut u8 {
|
||||
if len == 0 {
|
||||
return std::ptr::NonNull::dangling().as_ptr();
|
||||
}
|
||||
unsafe { raw_alloc(Layout::from_size_align(len, 1).expect("layout")) }
|
||||
}
|
||||
|
||||
/// # Safety
|
||||
/// `ptr` and `len` must come from `alloc` or `call`, and be given back once.
|
||||
#[unsafe(no_mangle)]
|
||||
pub unsafe extern "C" fn dealloc(ptr: *mut u8, len: usize) {
|
||||
if len == 0 {
|
||||
return;
|
||||
}
|
||||
unsafe {
|
||||
std::slice::from_raw_parts_mut(ptr, len).zeroize();
|
||||
raw_dealloc(ptr, Layout::from_size_align(len, 1).expect("layout"));
|
||||
}
|
||||
}
|
||||
|
||||
/// # Safety
|
||||
/// `ptr`/`len` must be a buffer from `alloc` holding the request; `call` frees it.
|
||||
#[unsafe(no_mangle)]
|
||||
pub unsafe extern "C" fn call(ptr: *mut u8, len: usize) -> u64 {
|
||||
let response = {
|
||||
let request = unsafe { std::slice::from_raw_parts(ptr, len) };
|
||||
super::handle(request)
|
||||
};
|
||||
unsafe { dealloc(ptr, len) };
|
||||
let mut bytes = serde_json::to_vec(&response).unwrap_or_else(|_| b"{\"ok\":false}".to_vec());
|
||||
drop(response);
|
||||
let out = alloc(bytes.len());
|
||||
unsafe { std::ptr::copy_nonoverlapping(bytes.as_ptr(), out, bytes.len()) };
|
||||
let packed = ((out as u64) << 32) | bytes.len() as u64;
|
||||
bytes.zeroize();
|
||||
packed
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,112 @@
|
||||
//! The JSON operations the browser calls, run natively.
|
||||
|
||||
use custos_vault::{Field, Item, ItemType, KdfParams, SecretString, Vault};
|
||||
use data_encoding::BASE64;
|
||||
use serde_json::{Value, json};
|
||||
|
||||
const FAST: KdfParams = KdfParams { m_cost_kib: 64, t_cost: 1, p_cost: 1 };
|
||||
const PASSWORD: &str = "Test4-Vault7-Only2";
|
||||
const SECRET: &str = "s3cret-Ž!";
|
||||
|
||||
fn call(v: Value) -> Value {
|
||||
custos_wasm::handle(v.to_string().as_bytes())
|
||||
}
|
||||
|
||||
fn vault_b64() -> (String, String, String) {
|
||||
let mut v = Vault::create(&SecretString::from(PASSWORD), FAST).unwrap();
|
||||
let mut login = Item::new(ItemType::WebLogin, "GitHub", 0);
|
||||
login.set("username", "mark", 0);
|
||||
login.set("password", SECRET, 0);
|
||||
login.set("url", "https://github.com", 0);
|
||||
login.set("totp", "JBSWY3DPEHPK3PXP", 0);
|
||||
let login_id = login.id.clone();
|
||||
let mut wifi = Item::new(ItemType::Wifi, "Home", 0);
|
||||
wifi.set("ssid", "Domov", 0);
|
||||
wifi.set("password", SECRET, 0);
|
||||
wifi.set("security", "WPA", 0);
|
||||
wifi.add_field(Field::text("note", "2.4 GHz"));
|
||||
let wifi_id = wifi.id.clone();
|
||||
v.add(login);
|
||||
v.add(wifi);
|
||||
(BASE64.encode(&v.to_bytes().unwrap()), login_id, wifi_id)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn open_list_reveal_lock() {
|
||||
let (vault, login, _) = vault_b64();
|
||||
let bad = call(json!({ "op": "open", "vault": vault, "password": "wrong" }));
|
||||
assert_eq!(bad["ok"], false);
|
||||
assert_eq!(bad["error"], "wrong password");
|
||||
|
||||
let r = call(json!({ "op": "open", "vault": vault, "password": PASSWORD }));
|
||||
assert_eq!(r["ok"], true, "{r}");
|
||||
let text = r.to_string();
|
||||
assert!(!text.contains(SECRET) && !text.contains("JBSWY3DP"), "the list holds no secret values");
|
||||
let items = r["items"].as_array().unwrap();
|
||||
assert_eq!(items.len(), 2);
|
||||
let gh = items.iter().find(|i| i["id"] == login.as_str()).unwrap();
|
||||
assert_eq!(
|
||||
(gh["subtitle"].as_str(), gh["hasTotp"].as_bool(), gh["mainSecret"].as_str()),
|
||||
(Some("mark"), Some(true), Some("password"))
|
||||
);
|
||||
|
||||
let rv = call(json!({ "op": "reveal", "id": login, "name": "password" }));
|
||||
assert_eq!(rv["value"], SECRET);
|
||||
assert_eq!(call(json!({ "op": "reveal", "id": login, "name": "password", "index": 1 }))["ok"], false);
|
||||
|
||||
assert_eq!(call(json!({ "op": "lock" }))["ok"], true);
|
||||
let locked = call(json!({ "op": "reveal", "id": login, "name": "password" }));
|
||||
assert_eq!(locked["error"], "The vault is locked.");
|
||||
assert_eq!(call(json!({ "op": "items" }))["ok"], false);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn totp_and_qr() {
|
||||
let (vault, login, wifi) = vault_b64();
|
||||
call(json!({ "op": "open", "vault": vault, "password": PASSWORD }));
|
||||
let now = 1_800_000_000u64;
|
||||
let t = call(json!({ "op": "totp", "id": login, "now": now }));
|
||||
let expected = custos_totp::Totp::parse("JBSWY3DPEHPK3PXP").unwrap();
|
||||
assert_eq!(t["code"], expected.code_at(now));
|
||||
assert_eq!(t["secondsLeft"], expected.seconds_left(now));
|
||||
let q = call(json!({ "op": "qr", "id": wifi }));
|
||||
assert_eq!((q["ok"].as_bool(), q["wifi"].as_bool()), (Some(true), Some(true)));
|
||||
assert!(q["svg"].as_str().unwrap().starts_with("<?xml"));
|
||||
let q = call(json!({ "op": "qr", "id": login }));
|
||||
assert_eq!(q["wifi"], false);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn share_seal_and_open() {
|
||||
let (vault, login, _) = vault_b64();
|
||||
call(json!({ "op": "open", "vault": vault, "password": PASSWORD }));
|
||||
for password in [None, Some("by-phone")] {
|
||||
let s = call(json!({ "op": "share_seal", "id": login, "password": password }));
|
||||
assert_eq!(s["ok"], true, "{s}");
|
||||
let (blob, fragment) = (s["blob"].as_str().unwrap(), s["fragment"].as_str().unwrap());
|
||||
assert!(!blob.contains(SECRET));
|
||||
let o = call(json!({ "op": "share_open", "blob": blob, "fragment": fragment, "password": password }));
|
||||
assert_eq!(o["ok"], true, "{o}");
|
||||
let fields = o["payload"]["fields"].as_array().unwrap();
|
||||
let names: Vec<_> = fields.iter().map(|f| f["name"].as_str().unwrap()).collect();
|
||||
assert_eq!(names, ["username", "password", "url"], "no TOTP seed in a share");
|
||||
assert_eq!(fields[1]["value"], SECRET);
|
||||
if password.is_some() {
|
||||
let w = call(json!({ "op": "share_open", "blob": blob, "fragment": fragment, "password": "nope" }));
|
||||
assert_eq!(w["code"], "DecryptFailed");
|
||||
let w = call(json!({ "op": "share_open", "blob": blob, "fragment": fragment }));
|
||||
assert_eq!(w["code"], "PasswordRequired");
|
||||
}
|
||||
}
|
||||
// An empty password means none.
|
||||
let s = call(json!({ "op": "share_seal", "id": login, "password": "" }));
|
||||
assert!(!s["fragment"].as_str().unwrap().contains("p=1"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bad_requests_never_echo_their_input() {
|
||||
let r = custos_wasm::handle(br#"{"op":"open","vault":"x","password":"hunter2","extra":"#);
|
||||
assert_eq!(r["error"], "Bad request.");
|
||||
let r = call(json!({ "op": "share_open", "blob": "!!", "fragment": "k=hunter2" }));
|
||||
assert!(!r.to_string().contains("hunter2"));
|
||||
}
|
||||
Reference in New Issue
Block a user