engawa-chat 0.6.0

A peer-to-peer chat lobby for editors and browsers
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
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
//! Shared room identities, signed records, and gossip payloads.

use anyhow::{Result, ensure};
use ed25519_dalek::{Signature, Signer, SigningKey, VerifyingKey};
use icu_properties::props::{DefaultIgnorableCodePoint, GeneralCategory};
use icu_properties::{CodePointMapData, CodePointSetData};
use serde::{Deserialize, Serialize};

pub(crate) const WEEK: i64 = 7 * 24 * 60 * 60 * 1000;
pub(crate) const SKEW: i64 = 60_000;
pub(crate) const POSTS: usize = 200;
pub(crate) const FRAME: usize = 3600;
pub(crate) const PAGE: usize = 20;
pub(crate) const ROOM_TRAILER: usize = 16;
pub(crate) const MAX_ROOM_FRAME: usize = 4096;
pub(crate) const PRESENCE: i64 = 90_000;
pub(crate) const ROOMS: usize = 512;
pub(crate) const DEFAULTS: [(&str, &str, bool); 3] = [
    ("雑談", "lounge", true),
    ("もくもく", "focus", false),
    ("質問", "questions", true),
];

pub(crate) fn public_relay(url: &url::Url) -> bool {
    let Some(domain) = url.domain() else {
        return false;
    };
    let host = domain.strip_suffix('.').unwrap_or(domain);
    url.scheme() == "https"
        && url.username().is_empty()
        && url.password().is_none()
        && url.port() != Some(0)
        && url.query().is_none()
        && url.fragment().is_none()
        && url.path() == "/"
        && host.len() <= 253
        && host.contains('.')
        && host.split('.').all(|label| {
            !label.is_empty()
                && label.len() <= 63
                && !label.starts_with('-')
                && !label.ends_with('-')
                && label
                    .bytes()
                    .all(|c| c.is_ascii_alphanumeric() || c == b'-')
        })
        && !matches!(
            host.rsplit('.').next(),
            Some(
                "localhost"
                    | "local"
                    | "localdomain"
                    | "internal"
                    | "test"
                    | "invalid"
                    | "example"
                    | "onion"
                    | "arpa"
                    | "home"
                    | "lan"
                    | "corp"
                    | "alt"
            )
        )
}

pub(crate) fn digest(domain: &'static str, fields: &[&[u8]]) -> blake3::Hash {
    let mut h = blake3::Hasher::new_derive_key(domain);
    for field in fields {
        h.update(&(field.len() as u64).to_be_bytes());
        h.update(field);
    }
    h.finalize()
}

pub(crate) fn is_hex(s: &str, len: usize) -> bool {
    s.len() == len
        && s.bytes()
            .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))
}

#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(deny_unknown_fields)]
pub(crate) struct Room {
    pub id: String,
    pub name: String,
    pub history: bool,
}

impl Room {
    pub(crate) fn identity(name: &str, history: bool) -> Result<blake3::Hash> {
        ensure!(
            !name.is_empty()
                && name.len() <= 96
                && name.trim() == name
                && !name.starts_with('#')
                && !name.chars().any(char::is_control),
            "部屋名は空白だけにせず、96バイト以内で入力してください"
        );
        let builtin = DEFAULTS
            .iter()
            .find(|(n, _, h)| *n == name && *h == history);
        let (kind, key) = builtin.map_or(("custom", name), |(_, slug, _)| ("builtin", *slug));
        Ok(digest(
            "engawa/v1/room",
            &[kind.as_bytes(), key.as_bytes(), &[u8::from(history)]],
        ))
    }

    pub(crate) fn new(name: &str, history: bool) -> Result<Self> {
        Ok(Self {
            id: Self::identity(name, history)?.to_hex().to_string(),
            name: name.into(),
            history,
        })
    }

    pub(crate) fn consistent(&self) -> bool {
        Self::identity(&self.name, self.history).is_ok_and(|hash| hash.to_hex().as_str() == self.id)
    }
}

#[derive(Clone, Deserialize, Serialize)]
#[serde(deny_unknown_fields)]
pub(crate) struct Identity {
    name: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    trip: Option<Trip>,
}

#[derive(Clone, Deserialize, Serialize)]
#[serde(deny_unknown_fields)]
struct Trip {
    key: String,
    signature: String,
}

#[derive(Clone, Deserialize, Serialize)]
#[serde(rename_all = "snake_case", deny_unknown_fields)]
pub(crate) enum Body {
    Message {
        nonce: String,
        text: String,
        #[serde(skip_serializing_if = "Option::is_none")]
        identity: Option<Identity>,
    },
    Withdrawal {
        signature: String,
    },
}

#[derive(Clone, Deserialize, Serialize)]
#[serde(deny_unknown_fields)]
pub(crate) struct Record {
    pub author: String,
    pub stamp: i64,
    // The original post signature identifies it even when its nonce and text are erased.
    pub reference: String,
    pub body: Body,
}

pub(crate) fn valid_handle(name: &str) -> bool {
    !name.is_empty()
        && name.len() <= 48
        && name.trim() == name
        && name.chars().all(|c| {
            !matches!(
                c,
                '◆' | '◇' | '♦' | '♢' | '⬥' | '⬩' | '🔶' | '🔷' | '🔸' | '🔹' | '\u{2800}'
            ) && !CodePointSetData::new::<DefaultIgnorableCodePoint>().contains(c)
                && !matches!(
                    CodePointMapData::<GeneralCategory>::new().get(c),
                    GeneralCategory::Control
                        | GeneralCategory::Format
                        | GeneralCategory::LineSeparator
                        | GeneralCategory::ParagraphSeparator
                )
        })
}

fn verify_signature(key: &str, sig: &str, data: blake3::Hash) -> bool {
    if !is_hex(key, 64) || !is_hex(sig, 128) {
        return false;
    }
    let mut key_bytes = [0; 32];
    let mut sig_bytes = [0; 64];
    hex::decode_to_slice(key, &mut key_bytes).is_ok()
        && hex::decode_to_slice(sig, &mut sig_bytes).is_ok()
        && VerifyingKey::from_bytes(&key_bytes).is_ok_and(|k| {
            k.verify_strict(data.as_bytes(), &Signature::from_bytes(&sig_bytes))
                .is_ok()
        })
}

fn valid_text(text: &str) -> bool {
    !text.trim().is_empty()
        && text.len() <= 1024
        && !text
            .chars()
            .any(|c| c.is_control() && c != '\n' && c != '\t')
}

impl Record {
    fn post_digest(room: &str, stamp: i64, nonce: &str, text: &str) -> blake3::Hash {
        digest(
            "engawa/v1/post",
            &[
                room.as_bytes(),
                &stamp.to_be_bytes(),
                nonce.as_bytes(),
                text.as_bytes(),
            ],
        )
    }

    fn named_digest(
        room: &str,
        stamp: i64,
        nonce: &str,
        text: &str,
        author: &str,
        name: &str,
        trip_key: &str,
    ) -> blake3::Hash {
        digest(
            "engawa/v1/named-post",
            &[
                room.as_bytes(),
                &stamp.to_be_bytes(),
                nonce.as_bytes(),
                text.as_bytes(),
                author.as_bytes(),
                name.as_bytes(),
                trip_key.as_bytes(),
            ],
        )
    }

    fn trip_proof(post: blake3::Hash) -> blake3::Hash {
        digest("engawa/v1/trip-proof", &[post.as_bytes()])
    }

    // Commit the room author's reference to the exact trip proof (or its absence).
    fn named_reference(post: blake3::Hash, signature: &str) -> blake3::Hash {
        digest(
            "engawa/v1/named-reference",
            &[post.as_bytes(), signature.as_bytes()],
        )
    }

    pub(crate) fn new(key: &SigningKey, room: &str, stamp: i64, text: &str) -> Result<Self> {
        Self::post(key, room, stamp, text, None)
    }

    pub(crate) fn named(
        key: &SigningKey,
        room: &str,
        stamp: i64,
        text: &str,
        name: &str,
        trip: Option<&SigningKey>,
    ) -> Result<Self> {
        ensure!(valid_handle(name), "コテハンに使えない名前です");
        Self::post(key, room, stamp, text, Some((name, trip)))
    }

    fn post(
        key: &SigningKey,
        room: &str,
        stamp: i64,
        text: &str,
        identity: Option<(&str, Option<&SigningKey>)>,
    ) -> Result<Self> {
        ensure!(
            valid_text(text),
            "本文は空白だけにせず、1024バイト以内で入力してください"
        );
        let mut nonce = [0u8; 16];
        getrandom::fill(&mut nonce)?;
        let nonce = hex::encode(nonce);
        let author = hex::encode(key.verifying_key().to_bytes());
        let (message, identity) = if let Some((name, trip)) = identity {
            let trip_key =
                trip.map_or_else(String::new, |k| hex::encode(k.verifying_key().to_bytes()));
            let post = Self::named_digest(room, stamp, &nonce, text, &author, name, &trip_key);
            let trip = trip.map(|k| Trip {
                key: trip_key,
                signature: hex::encode(k.sign(Self::trip_proof(post).as_bytes()).to_bytes()),
            });
            let reference = Self::named_reference(
                post,
                trip.as_ref().map_or("", |trip| trip.signature.as_str()),
            );
            (
                reference,
                Some(Identity {
                    name: name.into(),
                    trip,
                }),
            )
        } else {
            (Self::post_digest(room, stamp, &nonce, text), None)
        };
        Ok(Self {
            author,
            stamp,
            reference: hex::encode(key.sign(message.as_bytes()).to_bytes()),
            body: Body::Message {
                nonce,
                text: text.into(),
                identity,
            },
        })
    }

    pub(crate) fn display_author(&self) -> Option<String> {
        let Body::Message {
            identity: Some(identity),
            ..
        } = &self.body
        else {
            return None;
        };
        Some(match &identity.trip {
            None => identity.name.clone(),
            Some(trip) => {
                let hash = digest("engawa/v1/trip-fingerprint", &[trip.key.as_bytes()]).to_hex();
                format!("{} ◆{}", identity.name, &hash.as_str()[..16])
            }
        })
    }

    pub(crate) fn id(&self, room: &str) -> String {
        digest(
            "engawa/v1/post-id",
            &[
                room.as_bytes(),
                self.author.as_bytes(),
                &self.stamp.to_be_bytes(),
                self.reference.as_bytes(),
            ],
        )
        .to_hex()
        .to_string()
    }

    pub(crate) fn erase(&mut self, key: &SigningKey, room: &str) -> Result<()> {
        ensure!(
            self.author == hex::encode(key.verifying_key().to_bytes()) && !self.dead(),
            "このセッションの発言だけ取り消せます"
        );
        let proof = digest("engawa/v1/withdraw", &[self.id(room).as_bytes()]);
        self.body = Body::Withdrawal {
            signature: hex::encode(key.sign(proof.as_bytes()).to_bytes()),
        };
        Ok(())
    }

    pub(crate) fn dead(&self) -> bool {
        matches!(self.body, Body::Withdrawal { .. })
    }

    pub(crate) fn verified(&self, room: &str, oldest: i64, time: i64) -> bool {
        if self.stamp <= oldest || self.stamp > time + SKEW {
            return false;
        }
        let (sig, data) = match &self.body {
            Body::Message {
                nonce,
                text,
                identity,
            } if valid_text(text) && is_hex(nonce, 32) => {
                let data = if let Some(identity) = identity {
                    if !valid_handle(&identity.name) {
                        return false;
                    }
                    let trip_key = identity.trip.as_ref().map_or("", |trip| trip.key.as_str());
                    let post = Self::named_digest(
                        room,
                        self.stamp,
                        nonce,
                        text,
                        &self.author,
                        &identity.name,
                        trip_key,
                    );
                    let signature = if let Some(trip) = &identity.trip {
                        if !verify_signature(&trip.key, &trip.signature, Self::trip_proof(post)) {
                            return false;
                        }
                        trip.signature.as_str()
                    } else {
                        ""
                    };
                    Self::named_reference(post, signature)
                } else {
                    Self::post_digest(room, self.stamp, nonce, text)
                };
                (&self.reference, data)
            }
            Body::Withdrawal { signature } if is_hex(&self.reference, 128) => (
                signature,
                digest("engawa/v1/withdraw", &[self.id(room).as_bytes()]),
            ),
            _ => return false,
        };
        verify_signature(&self.author, sig, data)
    }
}

#[derive(Deserialize, Serialize)]
#[serde(rename_all = "snake_case")]
pub(crate) enum Packet {
    Item(Record),
    Hello,
    Offer(Vec<(String, bool)>),
    Need(Vec<(String, bool)>),
}

impl Packet {
    pub(crate) fn encode(&self) -> Result<Vec<u8>> {
        let bytes = serde_json::to_vec(self)?;
        ensure!(bytes.len() <= FRAME, "パケットが大きすぎます");
        Ok(bytes)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use serde_json::{Value, json};

    #[test]
    fn handle_validation_bounds_bytes_and_reserves_trip_display() {
        for name in ["ゆき", "Alice 2", "e\u{0301}", &"猫".repeat(16)] {
            assert!(valid_handle(name), "{name:?}");
        }
        for name in [
            "",
            " ",
            " bob",
            "a ",
            "a\tb",
            "a\nb",
            "a\u{2028}b",
            "a\u{202e}b",
            "a\u{2066}b",
            "a\u{200b}b",
            "a\u{0600}b",
            "a\u{fe0f}",
            "a\u{e0100}",
            "a ◆0000000000000000",
            "a ♦0000000000000000",
            &"猫".repeat(17),
        ] {
            assert!(!valid_handle(name), "{name:?}");
        }
    }

    #[test]
    fn anonymous_wire_remains_v1_and_named_withdrawal_erases_identity() -> Result<()> {
        let key = SigningKey::from_bytes(&[1; 32]);
        let author = hex::encode(key.verifying_key().to_bytes());
        let nonce = "12".repeat(16);
        let stamp: i64 = 10;
        let post = digest(
            "engawa/v1/post",
            &[b"room", &stamp.to_be_bytes(), nonce.as_bytes(), b"text"],
        );
        let wire = json!({
            "author": author,
            "stamp": stamp,
            "reference": hex::encode(key.sign(post.as_bytes()).to_bytes()),
            "body": {"message": {"nonce": nonce, "text": "text"}}
        });
        let record: Record = serde_json::from_value(wire.clone())?;
        assert!(record.verified("room", 0, stamp));
        assert_eq!(record.display_author(), None);
        assert_eq!(serde_json::to_value(&record)?, wire);
        let fresh = Record::new(&key, "room", stamp, "text")?;
        assert!(
            serde_json::to_value(fresh)?["body"]["message"]
                .get("identity")
                .is_none()
        );

        let trip = SigningKey::from_bytes(&[2; 32]);
        let mut named = Record::named(&key, "room", stamp, "text", "ゆき", Some(&trip))?;
        let id = named.id("room");
        assert!(named.erase(&trip, "room").is_err());
        named.erase(&key, "room")?;
        assert_eq!(id, named.id("room"));
        assert_eq!(named.display_author(), None);
        let withdrawal = serde_json::to_value(&named)?;
        assert_eq!(
            withdrawal["body"]["withdrawal"].as_object().unwrap().len(),
            1
        );
        assert!(named.verified("room", 0, stamp));
        Ok(())
    }

    #[test]
    fn trip_label_follows_trip_key_not_room_author_or_nonce() -> Result<()> {
        let key = SigningKey::from_bytes(&[1; 32]);
        let trip = SigningKey::from_bytes(&[2; 32]);
        let other = SigningKey::from_bytes(&[3; 32]);
        let a = Record::named(&key, "a", 10, "first", "ゆき", Some(&trip))?;
        let b = Record::named(&other, "b", 20, "second", "ゆき", Some(&trip))?;
        let c = Record::named(&key, "a", 10, "first", "ゆき", Some(&other))?;
        let plain = Record::named(&key, "a", 10, "first", "ゆき", None)?;
        assert!(a.verified("a", 0, 10));
        assert!(b.verified("b", 0, 20));
        assert!(c.verified("a", 0, 10));
        assert!(plain.verified("a", 0, 10));
        let label = a.display_author().unwrap();
        assert!(is_hex(label.strip_prefix("ゆき ◆").unwrap(), 16));
        assert_eq!(b.display_author().as_ref(), Some(&label));
        assert_ne!(c.display_author().as_ref(), Some(&label));
        assert_eq!(plain.display_author().as_deref(), Some("ゆき"));
        let largest = Record::named(
            &key,
            "a",
            10,
            &"\"".repeat(1024),
            &"\\".repeat(48),
            Some(&trip),
        )?;
        Packet::Item(largest).encode()?;
        Ok(())
    }

    #[test]
    fn author_signature_prevents_adding_or_stripping_identity() -> Result<()> {
        let key = SigningKey::from_bytes(&[1; 32]);
        let trip = SigningKey::from_bytes(&[2; 32]);
        let named = Record::named(&key, "a", 10, "text", "ゆき", Some(&trip))?;
        let plain = Record::named(&key, "a", 10, "text", "ゆき", None)?;
        let anonymous = Record::new(&key, "a", 10, "text")?;
        let (mut named, mut plain, mut anon) = (
            serde_json::to_value(named)?,
            serde_json::to_value(plain)?,
            serde_json::to_value(anonymous)?,
        );
        let message = &mut named["body"]["message"];
        let identity = message.as_object_mut().unwrap().remove("identity").unwrap();
        anon["body"]["message"]["identity"] = identity.clone();
        plain["body"]["message"]["identity"]["trip"] = identity["trip"].clone();
        let mut stripped = named.clone();
        stripped["body"]["message"]["identity"] = json!({"name": "ゆき"});
        for wire in [named, stripped, plain, anon] {
            assert!(!serde_json::from_value::<Record>(wire)?.verified("a", 0, 10));
        }
        Ok(())
    }

    #[test]
    fn trip_proof_cannot_be_transplanted_even_with_a_fresh_author_signature() -> Result<()> {
        let key = SigningKey::from_bytes(&[1; 32]);
        let trip = SigningKey::from_bytes(&[2; 32]);
        let other = SigningKey::from_bytes(&[3; 32]);
        let record = Record::named(&key, "a", 10, "text", "ゆき", Some(&trip))?;
        let original = serde_json::to_value(record)?;
        for (field, value) in [
            ("room", json!("b")),
            ("/stamp", json!(11)),
            (
                "/author",
                json!(hex::encode(other.verifying_key().to_bytes())),
            ),
            ("/body/message/nonce", json!("ab".repeat(16))),
            ("/body/message/text", json!("changed")),
            ("/body/message/identity/name", json!("other")),
            (
                "/body/message/identity/trip/key",
                json!(hex::encode(other.verifying_key().to_bytes())),
            ),
            (
                "/body/message/identity/trip/signature",
                json!("00".repeat(64)),
            ),
        ] {
            let mut wire = original.clone();
            let room = if field == "room" { "b" } else { "a" };
            if field != "room" {
                *wire.pointer_mut(field).unwrap() = value;
            }
            let signer = if field == "/author" { &other } else { &key };
            let message = &wire["body"]["message"];
            let identity = &message["identity"];
            let post = Record::named_digest(
                room,
                wire["stamp"].as_i64().unwrap(),
                message["nonce"].as_str().unwrap(),
                message["text"].as_str().unwrap(),
                wire["author"].as_str().unwrap(),
                identity["name"].as_str().unwrap(),
                identity["trip"]["key"].as_str().unwrap(),
            );
            let reference =
                Record::named_reference(post, identity["trip"]["signature"].as_str().unwrap());
            wire["reference"] =
                Value::String(hex::encode(signer.sign(reference.as_bytes()).to_bytes()));
            assert!(
                !serde_json::from_value::<Record>(wire)?.verified(room, 0, 11),
                "{field}"
            );
        }
        Ok(())
    }

    #[test]
    fn correctly_signed_post_with_forged_display_marker_is_rejected_on_receipt() -> Result<()> {
        let key = SigningKey::from_bytes(&[1; 32]);
        let fake = "ゆき ◆1234567890abcdef";
        assert!(Record::named(&key, "room", 10, "text", fake, None).is_err());
        let mut record = Record::named(&key, "room", 10, "text", "ゆき", None)?;
        let Body::Message {
            nonce,
            text,
            identity: Some(identity),
        } = &mut record.body
        else {
            unreachable!()
        };
        identity.name = fake.into();
        let post = Record::named_digest("room", 10, nonce, text, &record.author, fake, "");
        let reference = Record::named_reference(post, "");
        record.reference = hex::encode(key.sign(reference.as_bytes()).to_bytes());
        assert!(!record.verified("room", 0, 10));
        Ok(())
    }
}