1use core::fmt;
2use core::str::FromStr;
3
4use serde::{Deserialize, Deserializer, Serialize, Serializer};
5use thiserror::Error;
6use wire_mesh_wire::DecodeError;
7use wire_mesh_wire::identity::DeviceId;
8use wire_mesh_wire::minicbor::{Decode, Decoder, Encode, Encoder};
9use wire_mesh_wire::strict;
10
11pub const DOMAIN_ID: &str = "exadev.io/gitiverse";
13
14pub const CAP_READ: &str = "exadev.io/gitiverse:read";
16
17pub const CAP_WRITE: &str = "exadev.io/gitiverse:write";
19
20pub const CAP_MAINTAIN: &str = "exadev.io/gitiverse:maintain";
22
23pub const CAP_CI: &str = "exadev.io/gitiverse:ci";
25
26pub const REPO_ID_PREFIX: &str = "gitiverse:";
28
29const ID_BYTE_LEN: usize = 32;
30const ID_HEX_LEN: usize = ID_BYTE_LEN * 2;
31
32#[derive(Debug, Clone, PartialEq, Eq, Error)]
34pub enum IdParseError {
35 #[error("repository identifier must start with 'gitiverse:'")]
36 MissingPrefix,
37 #[error("expected {expected} lowercase hex characters, found {found}")]
38 InvalidHexLength { expected: usize, found: usize },
39 #[error("identifier contains non-hex or uppercase characters")]
40 InvalidHex,
41}
42
43fn parse_lowercase_hex_32(s: &str) -> Result<[u8; ID_BYTE_LEN], IdParseError> {
44 if s.len() != ID_HEX_LEN {
45 return Err(IdParseError::InvalidHexLength {
46 expected: ID_HEX_LEN,
47 found: s.len(),
48 });
49 }
50 if !s
51 .bytes()
52 .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))
53 {
54 return Err(IdParseError::InvalidHex);
55 }
56 let decoded = hex::decode(s).map_err(|_| IdParseError::InvalidHex)?;
57 let arr: [u8; ID_BYTE_LEN] =
58 decoded
59 .try_into()
60 .map_err(|v: Vec<u8>| IdParseError::InvalidHexLength {
61 expected: ID_HEX_LEN,
62 found: v.len() * 2,
63 })?;
64 Ok(arr)
65}
66
67#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
69pub struct RepoId(pub [u8; ID_BYTE_LEN]);
70
71impl RepoId {
72 pub const SIZE: usize = ID_BYTE_LEN;
73
74 #[must_use]
75 pub const fn from_bytes(bytes: [u8; ID_BYTE_LEN]) -> Self {
76 Self(bytes)
77 }
78
79 #[must_use]
80 pub const fn as_bytes(&self) -> &[u8; ID_BYTE_LEN] {
81 &self.0
82 }
83
84 #[must_use]
85 pub fn to_hex(&self) -> String {
86 hex::encode(self.0)
87 }
88
89 pub fn from_hex(hex_str: &str) -> Result<Self, IdParseError> {
90 parse_lowercase_hex_32(hex_str).map(Self)
91 }
92}
93
94impl AsRef<[u8]> for RepoId {
95 fn as_ref(&self) -> &[u8] {
96 &self.0
97 }
98}
99
100impl fmt::Display for RepoId {
101 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
102 write!(f, "{REPO_ID_PREFIX}{}", self.to_hex())
103 }
104}
105
106impl FromStr for RepoId {
107 type Err = IdParseError;
108
109 fn from_str(s: &str) -> Result<Self, Self::Err> {
110 let hex_part = s
111 .strip_prefix(REPO_ID_PREFIX)
112 .ok_or(IdParseError::MissingPrefix)?;
113 Self::from_hex(hex_part)
114 }
115}
116
117impl Serialize for RepoId {
118 fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
119 serializer.collect_str(self)
120 }
121}
122
123impl<'de> Deserialize<'de> for RepoId {
124 fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
125 let s = String::deserialize(deserializer)?;
126 Self::from_str(&s).map_err(serde::de::Error::custom)
127 }
128}
129
130impl Encode<()> for RepoId {
131 fn encode<W: wire_mesh_wire::minicbor::encode::Write>(
132 &self,
133 e: &mut Encoder<W>,
134 _ctx: &mut (),
135 ) -> Result<(), wire_mesh_wire::minicbor::encode::Error<W::Error>> {
136 e.bytes(&self.0)?.ok()
137 }
138}
139
140impl Decode<'_, ()> for RepoId {
141 fn decode(
142 d: &mut Decoder<'_>,
143 _ctx: &mut (),
144 ) -> Result<Self, wire_mesh_wire::minicbor::decode::Error> {
145 decode_repo_id(d).map_err(wire_mesh_wire::minicbor::decode::Error::custom)
146 }
147}
148
149pub(crate) fn decode_repo_id(d: &mut Decoder<'_>) -> Result<RepoId, DecodeError> {
150 let bytes = strict::bytes_value(d)?;
151 let arr: [u8; ID_BYTE_LEN] =
152 bytes
153 .try_into()
154 .map_err(|v: Vec<u8>| DecodeError::InvalidLength {
155 field: "repo-id",
156 expected: ID_BYTE_LEN,
157 found: v.len(),
158 })?;
159 Ok(RepoId(arr))
160}
161
162#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
164pub struct ActorId(pub DeviceId);
165
166impl ActorId {
167 pub const SIZE: usize = DeviceId::SIZE;
168
169 #[must_use]
170 pub const fn from_device_id(device_id: DeviceId) -> Self {
171 Self(device_id)
172 }
173
174 #[must_use]
175 pub const fn from_bytes(bytes: [u8; ID_BYTE_LEN]) -> Self {
176 Self(DeviceId(bytes))
177 }
178
179 #[must_use]
180 pub const fn as_device_id(&self) -> &DeviceId {
181 &self.0
182 }
183
184 #[must_use]
185 pub const fn as_bytes(&self) -> &[u8; ID_BYTE_LEN] {
186 &self.0.0
187 }
188
189 #[must_use]
190 pub fn to_hex(&self) -> String {
191 hex::encode(self.0.0)
192 }
193
194 pub fn from_hex(hex_str: &str) -> Result<Self, IdParseError> {
195 parse_lowercase_hex_32(hex_str).map(|arr| Self(DeviceId(arr)))
196 }
197}
198
199impl From<DeviceId> for ActorId {
200 fn from(value: DeviceId) -> Self {
201 Self(value)
202 }
203}
204
205impl From<ActorId> for DeviceId {
206 fn from(value: ActorId) -> Self {
207 value.0
208 }
209}
210
211impl AsRef<[u8]> for ActorId {
212 fn as_ref(&self) -> &[u8] {
213 &self.0.0
214 }
215}
216
217impl fmt::Display for ActorId {
218 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
219 f.write_str(&self.to_hex())
220 }
221}
222
223impl FromStr for ActorId {
224 type Err = IdParseError;
225
226 fn from_str(s: &str) -> Result<Self, Self::Err> {
227 Self::from_hex(s)
228 }
229}
230
231impl Serialize for ActorId {
232 fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
233 serializer.collect_str(self)
234 }
235}
236
237impl<'de> Deserialize<'de> for ActorId {
238 fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
239 let s = String::deserialize(deserializer)?;
240 Self::from_str(&s).map_err(serde::de::Error::custom)
241 }
242}
243
244impl Encode<()> for ActorId {
245 fn encode<W: wire_mesh_wire::minicbor::encode::Write>(
246 &self,
247 e: &mut Encoder<W>,
248 ctx: &mut (),
249 ) -> Result<(), wire_mesh_wire::minicbor::encode::Error<W::Error>> {
250 self.0.encode(e, ctx)
251 }
252}
253
254impl Decode<'_, ()> for ActorId {
255 fn decode(
256 d: &mut Decoder<'_>,
257 ctx: &mut (),
258 ) -> Result<Self, wire_mesh_wire::minicbor::decode::Error> {
259 DeviceId::decode(d, ctx).map(Self)
260 }
261}
262
263pub mod serde_device_id {
265 use super::*;
266
267 pub fn serialize<S: Serializer>(id: &DeviceId, serializer: S) -> Result<S::Ok, S::Error> {
268 serializer.serialize_str(&hex::encode(id.0))
269 }
270
271 pub fn deserialize<'de, D: Deserializer<'de>>(deserializer: D) -> Result<DeviceId, D::Error> {
272 let s = String::deserialize(deserializer)?;
273 parse_lowercase_hex_32(&s)
274 .map(DeviceId)
275 .map_err(serde::de::Error::custom)
276 }
277}
278
279pub mod serde_identity_key {
281 use super::*;
282 use wire_mesh_wire::identity::IdentityKey;
283
284 #[derive(Serialize, Deserialize)]
285 struct WireIdentityKey<'a> {
286 alg: i64,
287 #[serde(borrow)]
288 public_key: &'a str,
289 }
290
291 #[derive(Serialize)]
292 struct WireIdentityKeyOwned {
293 alg: i64,
294 public_key: String,
295 }
296
297 pub fn serialize<S: Serializer>(key: &IdentityKey, serializer: S) -> Result<S::Ok, S::Error> {
298 let repr = WireIdentityKeyOwned {
299 alg: key.alg,
300 public_key: hex::encode(&key.public_key),
301 };
302 repr.serialize(serializer)
303 }
304
305 pub fn deserialize<'de, D: Deserializer<'de>>(
306 deserializer: D,
307 ) -> Result<IdentityKey, D::Error> {
308 let repr = WireIdentityKey::deserialize(deserializer)?;
309 if !repr
310 .public_key
311 .bytes()
312 .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))
313 {
314 return Err(serde::de::Error::custom("public_key must be lowercase hex"));
315 }
316 let public_key = hex::decode(repr.public_key).map_err(serde::de::Error::custom)?;
317 Ok(IdentityKey {
318 alg: repr.alg,
319 public_key,
320 })
321 }
322}
323
324pub mod serde_hex_bytes {
326 use super::*;
327
328 pub fn serialize<S: Serializer>(bytes: &[u8], serializer: S) -> Result<S::Ok, S::Error> {
329 serializer.serialize_str(&hex::encode(bytes))
330 }
331
332 pub fn deserialize<'de, D: Deserializer<'de>>(deserializer: D) -> Result<Vec<u8>, D::Error> {
333 let s = String::deserialize(deserializer)?;
334 if !s
335 .bytes()
336 .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))
337 {
338 return Err(serde::de::Error::custom("expected lowercase hex string"));
339 }
340 hex::decode(&s).map_err(serde::de::Error::custom)
341 }
342}
343
344#[cfg(test)]
345mod tests {
346 use super::*;
347 use wire_mesh_wire::tokens::CapabilityVerb;
348 use wire_mesh_wire::{decode_exact, to_vec};
349
350 #[test]
351 fn capability_verbs_pass_wire_mesh_grammar() {
352 for verb in [CAP_READ, CAP_WRITE, CAP_MAINTAIN, CAP_CI] {
353 assert_eq!(CapabilityVerb::validate(verb), Ok(()), "{verb}");
354 }
355 }
356
357 #[test]
358 fn repo_id_display_parse_and_cbor_round_trip() {
359 let id = RepoId::from_bytes([0xAB; 32]);
360 let formatted = id.to_string();
361 assert_eq!(formatted, format!("gitiverse:{}", "ab".repeat(32)));
362 assert_eq!(RepoId::from_str(&formatted).unwrap(), id);
363
364 let json = serde_json::to_string(&id).unwrap();
365 assert_eq!(serde_json::from_str::<RepoId>(&json).unwrap(), id);
366
367 let cbor = to_vec(&id);
368 assert_eq!(decode_exact::<RepoId>(&cbor).unwrap(), id);
369 }
370
371 #[test]
372 fn repo_id_rejects_malformed_inputs() {
373 let valid_hex = "ab".repeat(32);
374 assert_eq!(
375 RepoId::from_str(&valid_hex),
376 Err(IdParseError::MissingPrefix)
377 );
378 assert_eq!(
379 RepoId::from_str(&format!("gitiverse:{}", "AB".repeat(32))),
380 Err(IdParseError::InvalidHex)
381 );
382 assert_eq!(
383 RepoId::from_str("gitiverse:abcd"),
384 Err(IdParseError::InvalidHexLength {
385 expected: 64,
386 found: 4,
387 })
388 );
389 }
390
391 #[test]
392 fn actor_id_round_trips_text_json_and_cbor() {
393 let actor = ActorId::from_bytes([0x42; 32]);
394 let text = actor.to_string();
395 assert_eq!(text, "42".repeat(32));
396 assert_eq!(ActorId::from_str(&text).unwrap(), actor);
397 assert_eq!(
398 ActorId::from_str(&"42".repeat(31)),
399 Err(IdParseError::InvalidHexLength {
400 expected: 64,
401 found: 62
402 })
403 );
404
405 let json = serde_json::to_string(&actor).unwrap();
406 assert_eq!(serde_json::from_str::<ActorId>(&json).unwrap(), actor);
407
408 let cbor = to_vec(&actor);
409 assert_eq!(decode_exact::<ActorId>(&cbor).unwrap(), actor);
410 }
411}