package message import ( "bytes" "encoding/hex" "encoding/json" "errors" "fmt" "regexp" "strings" "time" "git.stinnesbeck.com/nils/allmende/internal/identity" "git.stinnesbeck.com/nils/allmende/internal/jcs" "git.stinnesbeck.com/nils/allmende/internal/listing" ) const ( TypeText = "text" TypeGrant = "grant" // Limits are in UTF-8 bytes. MaxFirstText = 1000 MaxText = 2000 MaxAddress = 300 MaxPhone = 40 MaxEmail = 120 MaxNote = 1000 // MaxGrantValidity bounds valid_until. MaxGrantValidity = 30 * 24 * time.Hour replyContext = "allmende-reply-v1\n" ) // Plain is what an envelope carries inside its ciphertext. type Plain struct { Type string `json:"t"` // "text" or "grant" Thread string `json:"thread"` // thread public key, hex N int64 `json:"n"` // sender's counter in this thread, from 1 SentAt int64 `json:"sent_at"` Text string `json:"text,omitempty"` Address string `json:"address,omitempty"` // grant only Phone string `json:"phone,omitempty"` Email string `json:"email,omitempty"` Note string `json:"note,omitempty"` // ValidUntil is when a grant stops being shown (advisory). ValidUntil int64 `json:"valid_until,omitempty"` // Owner replies are signed; buyer messages carry none of these. Listing *Ref `json:"listing,omitempty"` Device string `json:"device,omitempty"` Cert *identity.Cert `json:"cert,omitempty"` Sig string `json:"sig,omitempty"` } func decodePlain(body []byte) (*Plain, error) { var p Plain if err := json.Unmarshal(body, &p); err != nil { return nil, errors.New("message: malformed plaintext") } // Re-encoding must reproduce the input exactly, so unknown fields, // non-canonical spelling and duplicates are all rejected. again, err := jcs.Marshal(&p) if err != nil || !bytes.Equal(again, body) { return nil, errors.New("message: plaintext is not canonical") } return &p, nil } func (p *Plain) unsignedBytes() ([]byte, error) { c := *p c.Sig = "" return jcs.Marshal(&c) } func (p *Plain) signOwner(dev *identity.Device, ref Ref) { p.Listing = &Ref{Author: ref.Author, ID: ref.ID} p.Device = dev.Cert.Device p.Cert = dev.Cert p.Sig = "" b, _ := p.unsignedBytes() // cannot fail for the types in Plain p.Sig = hex.EncodeToString(dev.Key.Sign(append([]byte(replyContext), b...))) } // verifyOwner checks that the reply was signed by a device certified by the // author of the listing it names. It cannot know about later revocations. func (p *Plain) verifyOwner() error { if p.Cert == nil || p.Listing == nil { return errors.New("message: reply is not signed") } if err := p.Cert.Check(); err != nil { return fmt.Errorf("message: %w", err) } if p.Cert.Author != p.Listing.Author || p.Cert.Device != p.Device { return errors.New("message: certificate does not match the listing's author and the device") } if !p.Cert.Covers(p.SentAt) { return errors.New("message: sent outside the certificate's validity") } b, err := p.unsignedBytes() if err != nil { return err } sig, err := hex.DecodeString(p.Sig) if err != nil || len(sig) != 64 { return errors.New("message: malformed signature") } if !identity.Verify(p.Device, append([]byte(replyContext), b...), sig) { return errors.New("message: bad signature") } return nil } // validate checks structure for a plaintext travelling in direction to. func (p *Plain) validate(to string) error { if !isHex(p.Thread, 64) { return errors.New("message: thread must be 64 hex characters") } if p.N < 1 || p.N > maxSafeInt || p.SentAt <= 0 || p.SentAt > maxSafeInt { return errors.New("message: n or sent_at out of range") } owner := to == ToBuyer if owner { if p.Listing == nil || !isHex(p.Listing.Author, 64) || !isHex(p.Listing.ID, 32) || !isHex(p.Device, 64) || p.Cert == nil || !isHex(p.Sig, 128) { return errors.New("message: owner reply must be signed") } } else if p.Listing != nil || p.Device != "" || p.Cert != nil || p.Sig != "" { return errors.New("message: buyer messages are not signed") } switch p.Type { case TypeText: if p.Address != "" || p.Phone != "" || p.Email != "" || p.Note != "" || p.ValidUntil != 0 { return errors.New("message: text must not carry grant fields") } return checkText(p.Text, 1, MaxText, true) case TypeGrant: if !owner { return errors.New("message: only the owner can release an address") } if p.Text != "" { return errors.New("message: a grant carries its words in note") } if err := checkText(p.Address, 1, MaxAddress, true); err != nil { return fmt.Errorf("address: %w", err) } if err := checkText(p.Phone, 0, MaxPhone, false); err != nil { return fmt.Errorf("phone: %w", err) } if err := checkText(p.Email, 0, MaxEmail, false); err != nil { return fmt.Errorf("email: %w", err) } if err := checkText(p.Note, 0, MaxNote, true); err != nil { return fmt.Errorf("note: %w", err) } if p.ValidUntil <= p.SentAt || time.Duration(p.ValidUntil-p.SentAt)*time.Second > MaxGrantValidity { return errors.New("message: valid_until must be within 30 days after sent_at") } return nil default: return fmt.Errorf("message: unknown type %q", p.Type) } } // checkText limits s to maxBytes of UTF-8 and applies the listing text rules. // The rune limit passed on is maxBytes too: runes never outnumber bytes. func checkText(s string, min, maxBytes int, newlines bool) error { if len(s) > maxBytes { return fmt.Errorf("longer than %d bytes", maxBytes) } return listing.ValidText(s, min, maxBytes, newlines) } // CheckBuyerFirst applies the extra rules for a buyer's messages before the // owner has replied: shorter, and no links. Relays cannot enforce this (the // text is encrypted), so the owner's node and the buyer's browser do. func (p *Plain) CheckBuyerFirst() error { if len(p.Text) > MaxFirstText { return fmt.Errorf("a first message may have at most %d bytes", MaxFirstText) } if ContainsLink(p.Text) { return errors.New("a first message must not contain links") } return nil } // hostname matches label.tld, in any script, so "example.com" and // "Beispiel.de" are caught but "z. B." and "etc." are not. var hostname = regexp.MustCompile(`[\p{L}\p{N}-]+\.\p{L}{2,}`) // ContainsLink is a heuristic for URLs and addresses: a scheme separator, // "www.", or a hostname-like word. It also flags "Hallo.Ich" typed without a // space; the message is then hidden, not lost, and the browser asks the buyer // to fix it. It is a speed bump against scams, not a guarantee. func ContainsLink(s string) bool { l := strings.ToLower(s) return strings.Contains(l, "://") || strings.Contains(l, "www.") || hostname.MatchString(l) }