use serde_json::Value;
use vta_sdk::prelude::*;
use vtc_client::VtcClient;
pub use vtc_client::rooms::body::RecordBasis;
use vtc_client::rooms::body::{
RecordLocation, SealedRecordBody, VerifiedRecordBody, verify_record_body,
};
use vtc_client::rooms::{CleartextContent, RoomSession, SealedContent, Visibility};
use vti_specs::vault::credentials::get::v0_2 as vault_get;
pub struct RoomTarget<'a> {
pub host_url: &'a str,
pub host_did: Option<&'a str>,
pub room_id: &'a str,
}
impl RoomTarget<'_> {
fn client(&self) -> VtcClient {
VtcClient::anonymous(self.host_url, self.host_did.unwrap_or("did:key:zHost"))
}
}
async fn present(
client: &VtaClient,
target: &RoomTarget<'_>,
action: &str,
) -> Result<RoomSession, Box<dyn std::error::Error>> {
let minted = client.room_present(target.room_id, action).await?;
session_from_minted(target.room_id, &minted)
}
pub fn session_from_minted(
room_id: &str,
minted: &Value,
) -> Result<RoomSession, Box<dyn std::error::Error>> {
let presentation = minted
.get("presentation")
.ok_or_else(|| format!("the VTA's reply carried no presentation: {minted}"))?;
let membership = presentation
.get("membership")
.and_then(Value::as_str)
.ok_or("the minted presentation carried no membership credential")?;
let authority_values = presentation
.get("authority")
.and_then(Value::as_array)
.ok_or("the minted presentation carried no authority chain")?;
let authority: Vec<String> = authority_values
.iter()
.filter_map(|v| v.as_str().map(str::to_string))
.collect();
if authority.len() != authority_values.len() {
return Err("the minted authority chain contained a non-string link".into());
}
let mut session = RoomSession::new(room_id, membership, authority)?;
if let Some(binding) = presentation.get("subjectBinding").and_then(Value::as_str) {
session = session.with_subject_binding(binding);
}
Ok(session)
}
async fn act_and_send(
client: &VtaClient,
target: &RoomTarget<'_>,
type_uri: &str,
payload: Value,
) -> Result<(String, Value), Box<dyn std::error::Error>> {
act_and_send_as(client, target, type_uri, payload, None).await
}
#[allow(deprecated)] async fn act_and_send_as(
client: &VtaClient,
target: &RoomTarget<'_>,
type_uri: &str,
payload: Value,
issuer: Option<&str>,
) -> Result<(String, Value), Box<dyn std::error::Error>> {
let host_did = target.host_did.unwrap_or("did:key:zHost");
let document = vta_sdk::client::unsigned_room_request(type_uri, host_did, issuer, payload)?;
let completed = client.room_act(&document).await.map_err(act_refusal)?;
let principal = completed.principal.to_string();
let document = serde_json::to_value(&completed.document)?;
let reply = target.client().send_signed_room_document(&document).await?;
Ok((principal, reply))
}
#[allow(deprecated)] async fn act_and_send_newest(
client: &VtaClient,
target: &RoomTarget<'_>,
newest: (&str, Value),
older: Option<(&str, Value)>,
) -> Result<(String, Value, bool), Box<dyn std::error::Error>> {
let (new_type, new_payload) = newest;
let host_did = target.host_did.unwrap_or("did:key:zHost");
let document =
vta_sdk::client::unsigned_room_request_v0_11(new_type, host_did, None, new_payload)?;
let fall_back = |why: String| -> Result<(&str, Value), Box<dyn std::error::Error>> {
older.clone().ok_or_else(|| why.into())
};
let (old_type, old_payload) = match client.room_act_v0_11(&document).await {
Ok(completed) => {
let principal = completed.principal.to_string();
let document = serde_json::to_value(&completed.document)?;
match newest_answer(target.client().send_signed_room_document(&document).await)? {
Some(reply) => return Ok((principal, reply, true)),
None => fall_back(format!(
"the room's host does not serve `{new_type}`, which this record needs: \
it predates it. Write the record without the members only that \
version carries, or ask the host's operator to upgrade."
))?,
}
}
Err(VtaError::UnsupportedTaskType { .. }) => fall_back(format!(
"your VTA does not serve `rooms/keys/act/0.11`, which completes `{new_type}`: \
upgrade it, or write the record without the members only that version carries."
))?,
Err(e) => return Err(act_refusal(e).into()),
};
let (principal, reply) = act_and_send(client, target, old_type, old_payload).await?;
Ok((principal, reply, false))
}
fn newest_answer(
sent: Result<Value, vtc_client::VtcError>,
) -> Result<Option<Value>, vtc_client::VtcError> {
match sent {
Ok(reply) => Ok(Some(reply)),
Err(e)
if vtc_client::git_ns::task_error(&e)
.is_some_and(|(code, _)| code == "unsupportedType") =>
{
Ok(None)
}
Err(e) => Err(e),
}
}
fn act_refusal(e: VtaError) -> String {
let text = e.to_string();
let hint = if text.contains("principalAmbiguous") {
"\n\nYou may act as more than one member of this room: act from the context of \
the one you mean."
} else if text.contains("notAMember") {
"\n\nYour VTA holds no credential this room issued to a persona you may act as. \
The owner issues them with `pnm rooms owner issue-membership` and \
`issue-authority --store`."
} else if text.contains("actionNotHeld") {
"\n\nYour own credentials for this room do not confer that action."
} else {
""
};
format!("{e}{hint}")
}
#[derive(Debug, Clone, Default)]
pub struct RecordThread {
pub kind: Option<String>,
pub reply_to: Option<String>,
}
impl RecordThread {
pub fn members(&self) -> Result<serde_json::Map<String, Value>, String> {
let mut m = serde_json::Map::new();
if let Some(k) = &self.kind {
m.insert("kind".into(), serde_json::json!(k));
}
if let Some(r) = &self.reply_to {
let (key, version) = match r.rsplit_once('@') {
Some((k, v)) => (
k,
Some(v.parse::<u64>().map_err(|_| {
format!("--reply-to {r}: the version after `@` is not a number")
})?),
),
None => (r.as_str(), None),
};
let mut reference = serde_json::json!({ "key": key });
if let Some(v) = version {
reference["version"] = serde_json::json!(v);
}
m.insert("inReplyTo".into(), reference);
}
vti_rooms::record_members::check(&m)?;
Ok(m)
}
}
async fn writer_members(
client: &VtaClient,
target: &RoomTarget<'_>,
wanted: serde_json::Map<String, Value>,
) -> Result<serde_json::Map<String, Value>, Box<dyn std::error::Error>> {
let Some(host_did) = target.host_did else {
if wanted.is_empty() {
return Ok(wanted);
}
return Err(format!(
"{} may be written only where the room's profile lists {}, and reading the \
profile takes the host's DID: pass --host-did.",
wanted.keys().cloned().collect::<Vec<_>>().join(" and "),
if wanted.len() == 1 { "it" } else { "them" }
)
.into());
};
let (listed, unresolved) = match client
.room_record_members(target.room_id, host_did, None)
.await
{
Ok(l) => (l, None),
Err(e) => (None, Some(e.to_string())),
};
if !wanted.is_empty() {
vta_sdk::client::check_record_members(
target.room_id,
&Value::Object(wanted.clone()),
listed.as_deref(),
unresolved,
)
.map_err(|e| record_members_refused(e, target))?;
}
let mut out = wanted;
if listed
.as_ref()
.is_some_and(|l| l.iter().any(|m| m == "writtenAt"))
{
out.insert(
"writtenAt".into(),
serde_json::json!(
chrono::Utc::now().to_rfc3339_opts(chrono::SecondsFormat::Secs, true)
),
);
}
Ok(out)
}
fn record_members_refused(e: VtaError, target: &RoomTarget<'_>) -> Box<dyn std::error::Error> {
let VtaError::RecordMembersNotPermitted {
refused, listed, ..
} = &e
else {
return e.into();
};
let mut all = listed.clone();
for r in refused {
if !all.contains(r) {
all.push(r.clone());
}
}
format!(
"{e}\n\nNothing was written. A curator of the room permits them with:\n\n \
pnm rooms profile set --room {} --host-did {} --record-members {}\n\n\
or write the record without --kind, --reply-to and --react.",
target.room_id,
target.host_did.unwrap_or("<host-did>"),
all.join(",")
)
.into()
}
pub(crate) async fn act_and_send_parsed<T: serde::de::DeserializeOwned>(
client: &VtaClient,
target: &RoomTarget<'_>,
type_uri: &str,
payload: Value,
) -> Result<T, Box<dyn std::error::Error>> {
let (_, reply) = act_and_send(client, target, type_uri, payload).await?;
parse_reply(type_uri, reply)
}
fn parse_reply<T: serde::de::DeserializeOwned>(
what: &str,
value: Value,
) -> Result<T, Box<dyn std::error::Error>> {
serde_json::from_value(value)
.map_err(|e| format!("the host's {what} response is not one this client reads: {e}").into())
}
pub fn pinned_from_flags(pin: bool, unpin: bool) -> Option<bool> {
if pin {
Some(true)
} else if unpin {
Some(false)
} else {
None
}
}
pub struct RoomSigner<'a> {
pub did: &'a str,
pub key_multibase: &'a str,
}
fn inert(text: &str) -> String {
text.chars()
.filter(|c| !c.is_control() || *c == '\n' || *c == '\t')
.collect()
}
fn opaque_key() -> String {
let bytes: [u8; 16] = rand::random();
base64::Engine::encode(&base64::engine::general_purpose::URL_SAFE_NO_PAD, bytes)
}
fn wire_str<T: serde::Serialize>(value: &T) -> String {
serde_json::to_value(value)
.ok()
.and_then(|v| v.as_str().map(str::to_string))
.unwrap_or_default()
}
fn capitalised(word: &str) -> String {
let mut chars = word.chars();
chars
.next()
.map(|c| c.to_uppercase().chain(chars).collect())
.unwrap_or_default()
}
fn one_line(text: &str) -> String {
text.chars()
.map(|c| if c.is_control() { ' ' } else { c })
.collect::<String>()
.trim()
.to_string()
}
fn shell_word(value: &str) -> String {
let plain = !value.is_empty()
&& value
.chars()
.all(|c| c.is_ascii_alphanumeric() || ":/._%@+=,-".contains(c));
if plain {
value.to_string()
} else {
format!("'{}'", inert(value).replace('\'', r"'\''"))
}
}
mod admin;
mod files;
mod memberships;
mod offers;
mod owner;
mod records;
#[cfg(test)]
mod test_support;
mod watch;
pub use admin::*;
pub use files::*;
pub use memberships::*;
pub use offers::*;
pub use owner::*;
pub use records::*;
pub use watch::*;
#[cfg(test)]
mod newest_version_tests {
use super::*;
use serde_json::json;
fn refusal(code: &str) -> vtc_client::VtcError {
vtc_client::VtcError::Refused {
document: json!({
"type": "https://trusttasks.org/spec/trust-task-error/0.6",
"payload": { "code": code, "message": "no" },
})
.to_string(),
}
}
#[test]
fn only_an_unserved_version_falls_back() {
let reply = json!({ "key": "k", "version": 3 });
assert_eq!(newest_answer(Ok(reply.clone())).unwrap(), Some(reply));
assert_eq!(
newest_answer(Err(refusal("unsupportedType"))).unwrap(),
None
);
for code in [
"permissionDenied",
"notFound",
"rooms/records/get:recordNotFound",
] {
let err = newest_answer(Err(refusal(code))).unwrap_err();
assert_eq!(
vtc_client::git_ns::task_error(&err).map(|(c, _)| c),
Some(code.to_string())
);
}
}
#[test]
#[allow(deprecated)] fn a_record_reads_as_the_version_that_answered() {
let v2 = json!({
"key": "k1", "version": 4, "author": "did:example:alice",
"cleartext": { "file": { "name": "a.txt" } },
"blobs": ["zQmBLobRefer3nce123456789abcdefgh"],
});
let mut v3 = v2.clone();
v3["createdAt"] = json!("2026-11-25T00:00:00Z");
v3["createdBy"] = json!("did:example:alice");
v3["bodyStoredAt"] = json!("2026-11-25T00:00:01Z");
let r3: vti_specs::rooms::records::get::v0_3::Response =
parse_reply("rooms/records/get", v3.clone()).unwrap();
assert_eq!(r3.version.get(), 4);
assert!(r3.cleartext.get("file").is_some());
assert!(r3.sealed.is_none());
let r2: vtc_client::rooms::files::GetRecordV2Response =
parse_reply("rooms/records/get", v2).unwrap();
assert_eq!(r2.author.as_deref(), Some("did:example:alice"));
assert!(
parse_reply::<vtc_client::rooms::files::GetRecordV2Response>("rooms/records/get", v3)
.is_err()
);
}
}