gitiverse-core 0.3.0

Core domain identities, repository manifests, signed refs, capability access policy, and canonical CBOR protocol types for gitiverse
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
use sha2::{Digest, Sha256};
use thiserror::Error;
use wire_mesh_wire::minicbor::{Decode, Decoder, Encode, Encoder};
use wire_mesh_wire::value::CdeMapBuilder;
use wire_mesh_wire::{DecodeError, decode_exact, strict, to_vec};

use crate::ids::{ActorId, RepoId, decode_repo_id};
use crate::repo::decode_device_id;

/// Current version of compact magic-link invite payloads.
pub const INVITE_LINK_VERSION: u64 = 1;

/// Native custom URI scheme prefix for magic-link invitations.
pub const INVITE_SCHEME_PREFIX: &str = "gitiverse://invite#";

/// Default HTTPS static launcher base URL for clickable chat/email magic links.
pub const DEFAULT_HTTPS_LAUNCHER_BASE: &str = "https://exadev.github.io/gitiverse/open";

const INVITE_CODE_LEN: usize = 16;
const MAX_FRAGMENT_CHARS: usize = 2048;

/// Failure returned when encoding, decoding, or parsing a magic-link invitation.
#[derive(Debug, Clone, PartialEq, Eq, Error)]
pub enum InviteError {
    #[error("invalid invite encoding: {0}")]
    InvalidEncoding(&'static str),
    #[error("invalid invite link format: {0}")]
    InvalidLink(&'static str),
    #[error("unsupported invite link version {0}")]
    UnsupportedVersion(u64),
    #[error("invite payload CBOR decode error: {0}")]
    Decode(#[from] DecodeError),
    #[error("invalid invite code length: expected {expected} bytes, got {found}")]
    InvalidCodeLength { expected: usize, found: usize },
}

/// Compact magic-link payload carried inside URL `#fragment`s and never sent to HTTP servers.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct InvitePayload {
    pub version: u64,
    pub repo_id: RepoId,
    pub peer_actor: ActorId,
    pub invite_code: [u8; INVITE_CODE_LEN],
    pub direct_addr: Option<String>,
    pub hub_url: Option<String>,
    pub repo_name: Option<String>,
    pub capability: Option<String>,
}

impl InvitePayload {
    /// Constructs a v1 [`InvitePayload`] targeting `repo_id` hosted by `peer_actor`.
    #[must_use]
    pub fn new(
        repo_id: RepoId,
        peer_actor: ActorId,
        invite_code: [u8; INVITE_CODE_LEN],
        direct_addr: Option<String>,
        hub_url: Option<String>,
        repo_name: Option<String>,
        capability: Option<String>,
    ) -> Self {
        Self {
            version: INVITE_LINK_VERSION,
            repo_id,
            peer_actor,
            invite_code,
            direct_addr: direct_addr.filter(|s| !s.trim().is_empty()),
            hub_url: hub_url.filter(|s| !s.trim().is_empty()),
            repo_name: repo_name.filter(|s| !s.trim().is_empty()),
            capability: capability.filter(|s| !s.trim().is_empty()),
        }
    }

    /// Computes SHA-256 of the raw 128-bit invite secret for durable storage.
    #[must_use]
    pub fn invite_code_hash(code: &[u8; INVITE_CODE_LEN]) -> [u8; 32] {
        Sha256::digest(code).into()
    }

    /// Derives the non-secret 32-hex invite identifier (`hex(sha256(code)[..16])`).
    #[must_use]
    pub fn invite_id_hex_for_code(code: &[u8; INVITE_CODE_LEN]) -> String {
        let digest = Self::invite_code_hash(code);
        hex::encode(&digest[..16])
    }

    /// Returns this payload's non-secret invite identifier.
    #[must_use]
    pub fn invite_id_hex(&self) -> String {
        Self::invite_id_hex_for_code(&self.invite_code)
    }

    /// Encodes the payload into canonical CDE CBOR bytes.
    #[must_use]
    pub fn encode_cbor(&self) -> Vec<u8> {
        to_vec(self)
    }

    /// Decodes strict canonical CBOR bytes into [`InvitePayload`].
    pub fn decode_cbor(bytes: &[u8]) -> Result<Self, InviteError> {
        let payload: Self = decode_exact(bytes)?;
        if payload.version != INVITE_LINK_VERSION {
            return Err(InviteError::UnsupportedVersion(payload.version));
        }
        Ok(payload)
    }

    /// Encodes the payload as unpadded RFC 4648 base64url suitable for URL fragments.
    #[must_use]
    pub fn encode_fragment(&self) -> String {
        encode_base64url(&self.encode_cbor())
    }

    /// Decodes a base64url fragment produced by [`Self::encode_fragment`].
    pub fn decode_fragment(fragment: &str) -> Result<Self, InviteError> {
        let trimmed = fragment.trim();
        if trimmed.is_empty() || trimmed.len() > MAX_FRAGMENT_CHARS {
            return Err(InviteError::InvalidEncoding(
                "fragment empty or exceeds maximum length",
            ));
        }
        let bytes = decode_base64url(trimmed)?;
        Self::decode_cbor(&bytes)
    }

    /// Renders a native custom-scheme URI (`gitiverse://invite#<fragment>`).
    #[must_use]
    pub fn to_uri(&self) -> String {
        format!("{INVITE_SCHEME_PREFIX}{}", self.encode_fragment())
    }

    /// Renders a loopback Web UI URL (`<base>/#invite=<fragment>`).
    #[must_use]
    pub fn to_local_web_url(&self, base: &str) -> String {
        format!(
            "{}/#invite={}",
            base.trim_end_matches('/'),
            self.encode_fragment()
        )
    }

    /// Renders an HTTPS launcher URL (`<base>#<fragment>`).
    #[must_use]
    pub fn to_https_launcher_url(&self, base: &str) -> String {
        format!("{}#{}", base.trim_end_matches('/'), self.encode_fragment())
    }

    /// Parses any supported magic link form (`gitiverse://invite#...`, local Web UI `#invite=...`, HTTPS launcher `#...`, or bare fragment).
    pub fn parse_any_link(input: &str) -> Result<Self, InviteError> {
        let trimmed = input.trim();
        if trimmed.is_empty() {
            return Err(InviteError::InvalidLink("link cannot be empty"));
        }

        if let Some(rest) = strip_prefix_ci(trimmed, "gitiverse://") {
            if let Some(frag) = rest.strip_prefix("invite#") {
                let clean = frag.strip_prefix("invite=").unwrap_or(frag);
                return Self::decode_fragment(clean);
            }
            if let Some(after_slash) = rest.strip_prefix("invite/") {
                if let Some((_, frag)) = after_slash.split_once('#') {
                    let clean = frag.strip_prefix("invite=").unwrap_or(frag);
                    return Self::decode_fragment(clean);
                }
                let clean = after_slash
                    .strip_prefix("?invite=")
                    .unwrap_or(after_slash)
                    .trim_matches('/');
                return Self::decode_fragment(clean);
            }
            return Err(InviteError::InvalidLink(
                "gitiverse:// URL must begin with gitiverse://invite#",
            ));
        }

        if strip_prefix_ci(trimmed, "https://").is_some()
            || strip_prefix_ci(trimmed, "http://").is_some()
        {
            let Some((_, frag)) = trimmed.split_once('#') else {
                return Err(InviteError::InvalidLink(
                    "HTTP(S) magic link is missing #fragment payload",
                ));
            };
            let clean = frag.strip_prefix("invite=").unwrap_or(frag);
            return Self::decode_fragment(clean);
        }

        if let Some(frag) = trimmed.strip_prefix("invite=") {
            return Self::decode_fragment(frag);
        }

        if let Some(frag) = trimmed.strip_prefix('#') {
            let clean = frag.strip_prefix("invite=").unwrap_or(frag);
            return Self::decode_fragment(clean);
        }

        Self::decode_fragment(trimmed)
    }
}

impl Encode<()> for InvitePayload {
    fn encode<W: wire_mesh_wire::minicbor::encode::Write>(
        &self,
        e: &mut Encoder<W>,
        _ctx: &mut (),
    ) -> Result<(), wire_mesh_wire::minicbor::encode::Error<W::Error>> {
        let mut builder = CdeMapBuilder::new();
        builder.push("version", &self.version);
        builder.push("repo-id", &self.repo_id);
        builder.push("peer-actor", &self.peer_actor);
        builder.push_bytes("invite-code", &self.invite_code);
        if let Some(addr) = &self.direct_addr {
            builder.push("direct-addr", &addr.as_str());
        }
        if let Some(hub) = &self.hub_url {
            builder.push("hub-url", &hub.as_str());
        }
        if let Some(name) = &self.repo_name {
            builder.push("repo-name", &name.as_str());
        }
        if let Some(cap) = &self.capability {
            builder.push("capability", &cap.as_str());
        }
        builder.write(e)
    }
}

impl Decode<'_, ()> for InvitePayload {
    fn decode(
        d: &mut Decoder<'_>,
        _ctx: &mut (),
    ) -> Result<Self, wire_mesh_wire::minicbor::decode::Error> {
        decode_invite_payload(d).map_err(wire_mesh_wire::minicbor::decode::Error::custom)
    }
}

fn decode_invite_payload(d: &mut Decoder<'_>) -> Result<InvitePayload, DecodeError> {
    let mut map = strict::MapDecoder::new(d)?;
    let mut version: Option<u64> = None;
    let mut repo_id: Option<RepoId> = None;
    let mut peer_actor: Option<ActorId> = None;
    let mut invite_code: Option<[u8; INVITE_CODE_LEN]> = None;
    let mut direct_addr: Option<String> = None;
    let mut hub_url: Option<String> = None;
    let mut repo_name: Option<String> = None;
    let mut capability: Option<String> = None;

    while let Some(key) = map.next_key(d)? {
        match key {
            "version" => strict::set_once(&mut version, strict::uint_value(d)?)?,
            "repo-id" => strict::set_once(&mut repo_id, decode_repo_id(d)?)?,
            "peer-actor" => strict::set_once(&mut peer_actor, ActorId(decode_device_id(d)?))?,
            "invite-code" => {
                let raw = strict::bytes_value(d)?;
                let code: [u8; INVITE_CODE_LEN] =
                    raw.try_into().map_err(|_| DecodeError::InvalidLength {
                        field: "invite-code",
                        expected: INVITE_CODE_LEN,
                        found: 0,
                    })?;
                strict::set_once(&mut invite_code, code)?;
            }
            "direct-addr" => strict::set_once(&mut direct_addr, strict::text_value(d)?)?,
            "hub-url" => strict::set_once(&mut hub_url, strict::text_value(d)?)?,
            "repo-name" => strict::set_once(&mut repo_name, strict::text_value(d)?)?,
            "capability" => strict::set_once(&mut capability, strict::text_value(d)?)?,
            other => return Err(DecodeError::UnknownKey(other.to_owned())),
        }
    }

    Ok(InvitePayload {
        version: version.ok_or(DecodeError::MissingField("version"))?,
        repo_id: repo_id.ok_or(DecodeError::MissingField("repo-id"))?,
        peer_actor: peer_actor.ok_or(DecodeError::MissingField("peer-actor"))?,
        invite_code: invite_code.ok_or(DecodeError::MissingField("invite-code"))?,
        direct_addr,
        hub_url,
        repo_name,
        capability,
    })
}

fn strip_prefix_ci<'a>(input: &'a str, prefix: &str) -> Option<&'a str> {
    if input.len() >= prefix.len() && input.is_char_boundary(prefix.len()) {
        let (head, tail) = input.split_at(prefix.len());
        if head.eq_ignore_ascii_case(prefix) {
            return Some(tail);
        }
    }
    None
}

const BASE64URL_ALPHABET: &[u8; 64] =
    b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";

/// Encodes `bytes` as unpadded RFC 4648 base64url.
#[must_use]
pub fn encode_base64url(bytes: &[u8]) -> String {
    let mut out = String::with_capacity((bytes.len() * 4).div_ceil(3));
    for chunk in bytes.chunks(3) {
        let b0 = u32::from(chunk[0]);
        let b1 = chunk.get(1).copied().map_or(0, u32::from);
        let b2 = chunk.get(2).copied().map_or(0, u32::from);
        let triple = (b0 << 16) | (b1 << 8) | b2;
        out.push(char::from(
            BASE64URL_ALPHABET[((triple >> 18) & 0x3F) as usize],
        ));
        out.push(char::from(
            BASE64URL_ALPHABET[((triple >> 12) & 0x3F) as usize],
        ));
        if chunk.len() > 1 {
            out.push(char::from(
                BASE64URL_ALPHABET[((triple >> 6) & 0x3F) as usize],
            ));
        }
        if chunk.len() > 2 {
            out.push(char::from(BASE64URL_ALPHABET[(triple & 0x3F) as usize]));
        }
    }
    out
}

/// Decodes unpadded RFC 4648 base64url strings strictly (no whitespace or padding).
pub fn decode_base64url(input: &str) -> Result<Vec<u8>, InviteError> {
    if input.len() % 4 == 1 {
        return Err(InviteError::InvalidEncoding("invalid base64url length"));
    }
    let mut vals = Vec::with_capacity(input.len());
    for byte in input.bytes() {
        let v = match byte {
            b'A'..=b'Z' => byte - b'A',
            b'a'..=b'z' => byte - b'a' + 26,
            b'0'..=b'9' => byte - b'0' + 52,
            b'-' => 62,
            b'_' => 63,
            _ => return Err(InviteError::InvalidEncoding("invalid base64url character")),
        };
        vals.push(v);
    }

    let mut out = Vec::with_capacity((vals.len() * 3) / 4);
    for chunk in vals.chunks(4) {
        match chunk.len() {
            4 => {
                let n = (u32::from(chunk[0]) << 18)
                    | (u32::from(chunk[1]) << 12)
                    | (u32::from(chunk[2]) << 6)
                    | u32::from(chunk[3]);
                out.push((n >> 16) as u8);
                out.push(((n >> 8) & 0xFF) as u8);
                out.push((n & 0xFF) as u8);
            }
            3 => {
                if chunk[2] & 0x03 != 0 {
                    return Err(InviteError::InvalidEncoding(
                        "non-canonical trailing base64url bits",
                    ));
                }
                let n = (u32::from(chunk[0]) << 18)
                    | (u32::from(chunk[1]) << 12)
                    | (u32::from(chunk[2]) << 6);
                out.push((n >> 16) as u8);
                out.push(((n >> 8) & 0xFF) as u8);
            }
            2 => {
                if chunk[1] & 0x0F != 0 {
                    return Err(InviteError::InvalidEncoding(
                        "non-canonical trailing base64url bits",
                    ));
                }
                let n = (u32::from(chunk[0]) << 18) | (u32::from(chunk[1]) << 12);
                out.push((n >> 16) as u8);
            }
            _ => return Err(InviteError::InvalidEncoding("invalid base64url chunk")),
        }
    }
    Ok(out)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::ids::CAP_READ;

    #[test]
    fn base64url_round_trips_and_rejects_invalid_inputs() {
        for len in [0usize, 1, 2, 3, 4, 15, 16, 17, 63, 64] {
            let data: Vec<u8> = (0..len).map(|i| (i.wrapping_mul(37)) as u8).collect();
            let enc = encode_base64url(&data);
            assert!(!enc.contains('='));
            assert_eq!(decode_base64url(&enc).unwrap(), data);
        }
        assert!(decode_base64url("A").is_err());
        assert!(decode_base64url("AA==").is_err());
        assert!(decode_base64url("AB").is_err()); // non-zero unused low bits
    }

    #[test]
    fn invite_payload_round_trips_across_all_link_formats() {
        let payload = InvitePayload::new(
            RepoId::from_bytes([0x12; 32]),
            ActorId::from_bytes([0x34; 32]),
            [0x56; 16],
            Some("100.64.0.10:9418".to_owned()),
            Some("wss://mesh.exadev.io/".to_owned()),
            Some("secret-proj".to_owned()),
            Some(CAP_READ.to_owned()),
        );

        let uri = payload.to_uri();
        assert!(uri.starts_with(INVITE_SCHEME_PREFIX));
        assert_eq!(InvitePayload::parse_any_link(&uri).unwrap(), payload);

        let local_web = payload.to_local_web_url("http://127.0.0.1:9420/");
        assert!(local_web.starts_with("http://127.0.0.1:9420/#invite="));
        assert_eq!(InvitePayload::parse_any_link(&local_web).unwrap(), payload);

        let https_url = payload.to_https_launcher_url(DEFAULT_HTTPS_LAUNCHER_BASE);
        assert!(https_url.starts_with("https://exadev.github.io/gitiverse/open#"));
        assert_eq!(InvitePayload::parse_any_link(&https_url).unwrap(), payload);

        let frag = payload.encode_fragment();
        assert_eq!(InvitePayload::parse_any_link(&frag).unwrap(), payload);
        assert_eq!(
            payload.invite_id_hex(),
            InvitePayload::invite_id_hex_for_code(&payload.invite_code)
        );
        assert_eq!(payload.invite_id_hex().len(), 32);
    }

    #[test]
    fn rejects_plain_repo_urls_missing_fragments_and_bad_versions() {
        assert!(InvitePayload::parse_any_link("").is_err());
        assert!(
            InvitePayload::parse_any_link(
                "gitiverse://1111111111111111111111111111111111111111111111111111111111111111"
            )
            .is_err()
        );
        assert!(InvitePayload::parse_any_link("https://exadev.github.io/gitiverse/open").is_err());

        let mut bad_ver = InvitePayload::new(
            RepoId::from_bytes([0x01; 32]),
            ActorId::from_bytes([0x02; 32]),
            [0x03; 16],
            None,
            None,
            None,
            None,
        );
        bad_ver.version = 2;
        let encoded = encode_base64url(&bad_ver.encode_cbor());
        assert!(matches!(
            InvitePayload::decode_fragment(&encoded),
            Err(InviteError::UnsupportedVersion(2))
        ));
    }
}