Implement end-to-end encrypted buyer/seller messaging
Wire format (internal/message): sealed boxes to the listing's device key (X25519 + HKDF + ChaCha20-Poly1305), padded, proof-of-work stamped, with signed owner replies and address grants. Relay validation, bounded queues, gossip on per-region message topics and sync (store, p2p). Owner side (internal/inbox, API): inbox with hidden link messages and a per-day new-thread limit, replies, grants, and a private per-listing address. Public POST/GET /api/v1/messages for buyers. Browser: noble-based sealing and reply verification checked against a Go fixture, contact form, conversation view, message list, de/en strings. Docs: PROTOCOL.md messaging section matches the implementation. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,153 @@
|
||||
package message
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"crypto/ecdh"
|
||||
"crypto/ed25519"
|
||||
"crypto/hkdf"
|
||||
"crypto/rand"
|
||||
"crypto/sha256"
|
||||
"crypto/sha512"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
|
||||
"filippo.io/edwards25519"
|
||||
"golang.org/x/crypto/chacha20poly1305"
|
||||
)
|
||||
|
||||
const sealInfo = "allmende-seal-v1"
|
||||
|
||||
var x25519 = ecdh.X25519()
|
||||
|
||||
// entropy is where ephemeral keys come from. Tests replace it to produce the
|
||||
// deterministic golden fixture the browser implementation is checked against.
|
||||
var entropy io.Reader = rand.Reader
|
||||
|
||||
// paddingBuckets are the sizes plaintexts are padded to, so the ciphertext
|
||||
// length reveals little about a message.
|
||||
var paddingBuckets = []int{512, 1024, 2048, 4096}
|
||||
|
||||
// MaxPlain is the largest plaintext before padding. One byte is reserved for
|
||||
// the padding marker so the largest padded plaintext is 4096 bytes.
|
||||
const MaxPlain = 4095
|
||||
|
||||
// ed25519PublicToX25519 converts a device's signing key to the X25519 key
|
||||
// used to seal messages to it (the birational map libsodium uses for
|
||||
// crypto_sign_ed25519_pk_to_curve25519).
|
||||
func ed25519PublicToX25519(pub ed25519.PublicKey) (*ecdh.PublicKey, error) {
|
||||
p, err := new(edwards25519.Point).SetBytes(pub)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("message: bad device key: %w", err)
|
||||
}
|
||||
return x25519.NewPublicKey(p.BytesMontgomery())
|
||||
}
|
||||
|
||||
// ed25519SecretToX25519 derives the X25519 secret matching
|
||||
// ed25519PublicToX25519 of the corresponding public key.
|
||||
func ed25519SecretToX25519(priv ed25519.PrivateKey) (*ecdh.PrivateKey, error) {
|
||||
h := sha512.Sum512(priv.Seed())
|
||||
return x25519.NewPrivateKey(h[:32])
|
||||
}
|
||||
|
||||
func newEphemeral() (*ecdh.PrivateKey, error) {
|
||||
var b [32]byte
|
||||
if _, err := io.ReadFull(entropy, b[:]); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return x25519.NewPrivateKey(b[:])
|
||||
}
|
||||
|
||||
func sealKey(shared, epk, rpk []byte) ([]byte, error) {
|
||||
salt := append(append([]byte{}, epk...), rpk...)
|
||||
return hkdf.Key(sha256.New, shared, salt, sealInfo, 32)
|
||||
}
|
||||
|
||||
// seal encrypts padded plaintext to rpk. aadFor receives the hex of the fresh
|
||||
// ephemeral public key and returns the header bytes that are authenticated.
|
||||
func seal(rpk *ecdh.PublicKey, aadFor func(epk string) ([]byte, error), plain []byte) (epk string, ct []byte, err error) {
|
||||
esk, err := newEphemeral()
|
||||
if err != nil {
|
||||
return "", nil, err
|
||||
}
|
||||
shared, err := esk.ECDH(rpk) // rejects the all-zero result of low-order points
|
||||
if err != nil {
|
||||
return "", nil, err
|
||||
}
|
||||
epkBytes := esk.PublicKey().Bytes()
|
||||
key, err := sealKey(shared, epkBytes, rpk.Bytes())
|
||||
if err != nil {
|
||||
return "", nil, err
|
||||
}
|
||||
epk = hex.EncodeToString(epkBytes)
|
||||
aad, err := aadFor(epk)
|
||||
if err != nil {
|
||||
return "", nil, err
|
||||
}
|
||||
padded, err := pad(plain)
|
||||
if err != nil {
|
||||
return "", nil, err
|
||||
}
|
||||
aead, err := chacha20poly1305.New(key)
|
||||
if err != nil {
|
||||
return "", nil, err
|
||||
}
|
||||
// A zero nonce is safe: the key is unique to this envelope (fresh esk).
|
||||
return epk, aead.Seal(nil, make([]byte, aead.NonceSize()), padded, aad), nil
|
||||
}
|
||||
|
||||
// open decrypts ct with the recipient's secret key.
|
||||
func open(sk *ecdh.PrivateKey, epkHex string, aad, ct []byte) ([]byte, error) {
|
||||
epkBytes, err := hex.DecodeString(epkHex)
|
||||
if err != nil {
|
||||
return nil, errors.New("message: bad ephemeral key")
|
||||
}
|
||||
epk, err := x25519.NewPublicKey(epkBytes)
|
||||
if err != nil {
|
||||
return nil, errors.New("message: bad ephemeral key")
|
||||
}
|
||||
shared, err := sk.ECDH(epk)
|
||||
if err != nil {
|
||||
return nil, errors.New("message: bad ephemeral key")
|
||||
}
|
||||
key, err := sealKey(shared, epkBytes, sk.PublicKey().Bytes())
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
aead, err := chacha20poly1305.New(key)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
padded, err := aead.Open(nil, make([]byte, aead.NonceSize()), ct, aad)
|
||||
if err != nil {
|
||||
return nil, errors.New("message: cannot decrypt")
|
||||
}
|
||||
return unpad(padded)
|
||||
}
|
||||
|
||||
// pad appends 0x80 and zeros up to the next bucket size.
|
||||
func pad(b []byte) ([]byte, error) {
|
||||
if len(b) > MaxPlain {
|
||||
return nil, fmt.Errorf("message: plaintext of %d bytes exceeds %d", len(b), MaxPlain)
|
||||
}
|
||||
size := paddingBuckets[len(paddingBuckets)-1]
|
||||
for _, s := range paddingBuckets {
|
||||
if len(b)+1 <= s {
|
||||
size = s
|
||||
break
|
||||
}
|
||||
}
|
||||
out := make([]byte, size)
|
||||
copy(out, b)
|
||||
out[len(b)] = 0x80
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func unpad(b []byte) ([]byte, error) {
|
||||
b = bytes.TrimRight(b, "\x00")
|
||||
if len(b) == 0 || b[len(b)-1] != 0x80 {
|
||||
return nil, errors.New("message: bad padding")
|
||||
}
|
||||
return b[:len(b)-1], nil
|
||||
}
|
||||
Reference in New Issue
Block a user