1use serde::{Deserialize, Serialize};
15use serde_json::json;
16
17use crate::domains::AgentType;
18
19const NS_QDP: &str = "https://webcivics.github.io/QDP/ontdev/QDP#";
20
21#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
23pub struct QdpService {
24 pub kind: String,
26 pub value: String,
27}
28
29#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
31pub struct FrontDoorRecord {
32 pub domain: String,
33 pub agent_type: AgentType,
34 pub front_door_did: String,
36 #[serde(default)]
37 pub name: Option<String>,
38 #[serde(default)]
39 pub webid: Option<String>,
40 #[serde(default)]
42 pub services: Vec<QdpService>,
43 #[serde(default)]
45 pub identity_pubkey_hex: Option<String>,
46 #[serde(default)]
47 pub wireguard_pubkey_hex: Option<String>,
48 #[serde(default)]
49 pub overlay_addr: Option<String>,
50 #[serde(default)]
52 pub nym_address: Option<String>,
53 #[serde(default)]
55 pub profile_url: Option<String>,
56}
57
58pub fn dns_record_name(domain: &str) -> String {
60 format!("_qdp.{domain}")
61}
62
63fn agent_type_token(t: &AgentType) -> &'static str {
64 match t {
65 AgentType::NaturalPerson => "person",
66 AgentType::Organization => "org",
67 AgentType::AiAgent => "ai",
68 AgentType::HumanitarianService => "service",
69 AgentType::ContentProvider => "content",
70 AgentType::Group => "group",
71 }
72}
73fn agent_type_from_token(s: &str) -> AgentType {
74 match s {
75 "org" => AgentType::Organization,
76 "ai" => AgentType::AiAgent,
77 "service" => AgentType::HumanitarianService,
78 "content" => AgentType::ContentProvider,
79 "group" => AgentType::Group,
80 _ => AgentType::NaturalPerson,
81 }
82}
83fn agent_type_class(t: &AgentType) -> &'static str {
85 match t {
86 AgentType::NaturalPerson => "foaf:Person",
87 AgentType::Organization | AgentType::Group => "schema:Organization",
88 AgentType::AiAgent => "QDP:AIAgent",
89 AgentType::HumanitarianService => "QDP:EssentialService",
90 AgentType::ContentProvider => "QDP:ContentProvider",
91 }
92}
93
94fn ecash(rec: &FrontDoorRecord) -> Option<&str> {
95 rec.services
96 .iter()
97 .find(|s| s.kind == "ecash")
98 .map(|s| s.value.as_str())
99}
100
101impl FrontDoorRecord {
102 pub fn to_dns_txt(&self) -> String {
105 let mut parts = vec![
106 format!("qdp:signer <{}>", self.front_door_did),
107 format!("qdp:agentType \"{}\"", agent_type_token(&self.agent_type)),
108 ];
109 if let Some(k) = &self.identity_pubkey_hex {
110 parts.push(format!("qdp:identityKey \"{k}\""));
111 }
112 if let Some(w) = &self.wireguard_pubkey_hex {
113 parts.push(format!("qdp:wireguard \"{w}\""));
114 }
115 if let Some(o) = &self.overlay_addr {
116 parts.push(format!("qdp:overlay \"{o}\""));
117 }
118 if let Some(n) = &self.nym_address {
119 parts.push(format!("qdp:nym \"{n}\""));
120 }
121 if let Some(e) = ecash(self) {
122 parts.push(format!("qdp:ecash \"{e}\""));
123 }
124 if let Some(u) = &self.profile_url {
125 parts.push(format!("qdp:profile <{u}>"));
126 }
127 parts.join(" ; ")
128 }
129
130 pub fn from_dns_txt(domain: &str, txt: &str) -> Result<Self, String> {
132 let mut rec = FrontDoorRecord {
133 domain: domain.to_string(),
134 agent_type: AgentType::NaturalPerson,
135 front_door_did: String::new(),
136 name: None,
137 webid: None,
138 services: vec![],
139 identity_pubkey_hex: None,
140 wireguard_pubkey_hex: None,
141 overlay_addr: None,
142 nym_address: None,
143 profile_url: None,
144 };
145 for clause in txt.split(';') {
146 let clause = clause.trim();
147 let Some((pred, obj)) = clause.split_once(char::is_whitespace) else {
148 continue;
149 };
150 let obj = obj.trim();
151 let uri = || {
152 obj.trim_start_matches('<')
153 .trim_end_matches('>')
154 .to_string()
155 };
156 let lit = || obj.trim_matches('"').to_string();
157 match pred.trim() {
158 "qdp:signer" => rec.front_door_did = uri(),
159 "qdp:agentType" => rec.agent_type = agent_type_from_token(&lit()),
160 "qdp:identityKey" => rec.identity_pubkey_hex = Some(lit()),
161 "qdp:wireguard" => rec.wireguard_pubkey_hex = Some(lit()),
162 "qdp:overlay" => rec.overlay_addr = Some(lit()),
163 "qdp:nym" => rec.nym_address = Some(lit()),
164 "qdp:ecash" => rec.services.push(QdpService {
165 kind: "ecash".into(),
166 value: lit(),
167 }),
168 "qdp:profile" => rec.profile_url = Some(uri()),
169 _ => {}
170 }
171 }
172 if rec.front_door_did.is_empty() {
173 return Err("front-door record has no qdp:signer".into());
174 }
175 Ok(rec)
176 }
177
178 pub fn to_turtle(&self) -> String {
180 use std::fmt::Write as _;
181 let mut t = String::new();
182 let _ = writeln!(t, "@prefix QDP: <{NS_QDP}> .");
183 let _ = writeln!(
184 t,
185 "@prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> ."
186 );
187 let _ = writeln!(t, "@prefix foaf: <http://xmlns.com/foaf/0.1/> .");
188 let _ = writeln!(t, "@prefix schema: <https://schema.org/> .");
189 let _ = writeln!(t);
190 let _ = writeln!(t, "<#this> a {} ;", agent_type_class(&self.agent_type));
191 let _ = writeln!(t, " schema:domain \"{}\" ;", self.domain);
192 let _ = writeln!(t, " QDP:signer <{}> ;", self.front_door_did);
193 if let Some(w) = &self.webid {
194 let _ = writeln!(t, " QDP:webid <{w}> ;");
195 }
196 if let Some(n) = &self.name {
197 let _ = writeln!(t, " foaf:name \"{n}\" ;");
198 }
199 if let Some(nym) = &self.nym_address {
200 let _ = writeln!(t, " QDP:nymAddress \"{nym}\" ;");
201 }
202 for s in &self.services {
203 match s.kind.as_str() {
204 "ecash" => {
205 let _ = writeln!(t, " QDP:hasEcashAccount \"{}\" ;", s.value);
206 }
207 "solidpod" => {
208 let _ = writeln!(t, " QDP:hasSolidPod <{}> ;", s.value);
209 }
210 "sparql" => {
211 let _ = writeln!(t, " QDP:sparqlEndpoint <{}> ;", s.value);
212 }
213 _ => {
214 let _ = writeln!(t, " QDP:serviceEndpoint <{}> ;", s.value);
215 }
216 }
217 }
218 let _ = writeln!(t, " QDP:hasMetadata [ QDP:metadataType \"profile\" ] .");
220 t
221 }
222
223 pub fn to_json_ld(&self) -> serde_json::Value {
225 let mut node = json!({
226 "@context": {
227 "QDP": NS_QDP,
228 "foaf": "http://xmlns.com/foaf/0.1/",
229 "schema": "https://schema.org/",
230 },
231 "@id": "#this",
232 "@type": agent_type_class(&self.agent_type),
233 "schema:domain": self.domain,
234 "QDP:signer": { "@id": self.front_door_did },
235 });
236 let obj = node.as_object_mut().unwrap();
237 if let Some(w) = &self.webid {
238 obj.insert("QDP:webid".into(), json!({ "@id": w }));
239 }
240 if let Some(n) = &self.name {
241 obj.insert("foaf:name".into(), json!(n));
242 }
243 if let Some(nym) = &self.nym_address {
244 obj.insert("QDP:nymAddress".into(), json!(nym));
245 }
246 if let Some(e) = ecash(self) {
247 obj.insert("QDP:hasEcashAccount".into(), json!(e));
248 }
249 if let Some(s) = self.services.iter().find(|s| s.kind == "solidpod") {
250 obj.insert("QDP:hasSolidPod".into(), json!({ "@id": s.value }));
251 }
252 obj.insert(
253 "QDP:hasMetadata".into(),
254 json!({ "QDP:metadataType": "profile" }),
255 );
256 node
257 }
258
259 pub fn to_cbor_ld(&self) -> Result<Vec<u8>, String> {
262 let mut buf = Vec::new();
263 ciborium::into_writer(&self.to_json_ld(), &mut buf).map_err(|e| e.to_string())?;
264 Ok(buf)
265 }
266
267 pub fn from_cbor_ld(bytes: &[u8]) -> Result<serde_json::Value, String> {
269 ciborium::from_reader(bytes).map_err(|e| e.to_string())
270 }
271}
272
273#[cfg(test)]
274mod tests {
275 use super::*;
276
277 fn sample() -> FrontDoorRecord {
278 FrontDoorRecord {
279 domain: "alice.example".into(),
280 agent_type: AgentType::NaturalPerson,
281 front_door_did: "did:qdp:alice-frontdoor".into(),
282 name: Some("Alice".into()),
283 webid: Some("https://alice.example/profile#me".into()),
284 services: vec![
285 QdpService {
286 kind: "ecash".into(),
287 value: "ecash:qq123".into(),
288 },
289 QdpService {
290 kind: "solidpod".into(),
291 value: "https://alice.example/pod/".into(),
292 },
293 ],
294 identity_pubkey_hex: Some("aa".repeat(32)),
295 wireguard_pubkey_hex: Some("bb".repeat(32)),
296 overlay_addr: Some("fd00::1".into()),
297 nym_address: None,
298 profile_url: Some("https://alice.example/.well-known/QDP".into()),
299 }
300 }
301
302 #[test]
303 fn nym_address_roundtrips_dns_txt_and_jsonld() {
304 let mut rec = sample();
305 rec.nym_address = Some("alice_id.sphinx_key@gateway_id".into());
306 let txt = rec.to_dns_txt();
307 assert!(txt.contains("qdp:nym \"alice_id.sphinx_key@gateway_id\""));
308
309 let back = FrontDoorRecord::from_dns_txt("alice.example", &txt).unwrap();
310 assert_eq!(
311 back.nym_address,
312 Some("alice_id.sphinx_key@gateway_id".into())
313 );
314
315 let turtle = rec.to_turtle();
316 assert!(turtle.contains("QDP:nymAddress \"alice_id.sphinx_key@gateway_id\""));
317
318 let jsonld = rec.to_json_ld();
319 assert_eq!(jsonld["QDP:nymAddress"], "alice_id.sphinx_key@gateway_id");
320 }
321
322 #[test]
323 fn dns_record_name_is_underscore_qdp() {
324 assert_eq!(dns_record_name("alice.example"), "_qdp.alice.example");
325 }
326
327 #[test]
328 fn dns_txt_roundtrips_the_no_hosting_anchor() {
329 let rec = sample();
330 let txt = rec.to_dns_txt();
331 assert!(txt.contains("qdp:signer <did:qdp:alice-frontdoor>"));
332 assert!(txt.contains("qdp:wireguard"));
333 let back = FrontDoorRecord::from_dns_txt("alice.example", &txt).unwrap();
334 assert_eq!(back.front_door_did, rec.front_door_did);
336 assert_eq!(back.agent_type, rec.agent_type);
337 assert_eq!(back.wireguard_pubkey_hex, rec.wireguard_pubkey_hex);
338 assert_eq!(back.overlay_addr, rec.overlay_addr);
339 assert_eq!(back.profile_url, rec.profile_url);
340 assert_eq!(ecash(&back), Some("ecash:qq123"));
341 }
342
343 #[test]
344 fn from_dns_txt_requires_a_signer() {
345 assert!(FrontDoorRecord::from_dns_txt("x.example", "qdp:agentType \"person\"").is_err());
346 }
347
348 #[test]
349 fn turtle_has_qdp_mandatory_fields() {
350 let t = sample().to_turtle();
351 assert!(t.contains("@prefix QDP:"));
352 assert!(t.contains("a foaf:Person"));
353 assert!(t.contains("schema:domain \"alice.example\""));
354 assert!(t.contains("QDP:signer <did:qdp:alice-frontdoor>"));
355 assert!(t.contains("QDP:hasEcashAccount \"ecash:qq123\""));
356 assert!(t.contains("QDP:hasMetadata"));
357 }
358
359 #[test]
360 fn jsonld_has_type_domain_and_ecash() {
361 let j = sample().to_json_ld();
362 assert_eq!(j["@type"], "foaf:Person");
363 assert_eq!(j["schema:domain"], "alice.example");
364 assert_eq!(j["QDP:hasEcashAccount"], "ecash:qq123");
365 assert_eq!(j["QDP:signer"]["@id"], "did:qdp:alice-frontdoor");
366 }
367
368 #[test]
369 fn cbor_ld_roundtrips_the_jsonld() {
370 let rec = sample();
371 let bytes = rec.to_cbor_ld().unwrap();
372 let back = FrontDoorRecord::from_cbor_ld(&bytes).unwrap();
373 assert_eq!(
374 back,
375 rec.to_json_ld(),
376 "CBOR-LD is a lossless encoding of the JSON-LD"
377 );
378 }
379
380 #[test]
381 fn org_and_ai_map_to_qdp_types() {
382 let mut r = sample();
383 r.agent_type = AgentType::Organization;
384 assert!(r.to_turtle().contains("a schema:Organization"));
385 r.agent_type = AgentType::AiAgent;
386 assert!(r.to_turtle().contains("a QDP:AIAgent"));
387 }
388}