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,239 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
|
||||
"git.stinnesbeck.com/nils/allmende/internal/jcs"
|
||||
"git.stinnesbeck.com/nils/allmende/internal/listing"
|
||||
"git.stinnesbeck.com/nils/allmende/internal/message"
|
||||
)
|
||||
|
||||
// Directions of an InboxMessage.
|
||||
const (
|
||||
InboxIn = "in" // from a buyer
|
||||
InboxOut = "out" // our reply
|
||||
)
|
||||
|
||||
// InboxMessage is one decrypted message in the owner's conversations.
|
||||
type InboxMessage struct {
|
||||
Hash string // hash of the envelope that carried it
|
||||
Listing message.Ref
|
||||
Thread string
|
||||
Dir string
|
||||
Plain *message.Plain
|
||||
Hidden bool // a buyer message that broke the first-message rules
|
||||
ReceivedAt int64
|
||||
}
|
||||
|
||||
// ThreadSummary describes one conversation.
|
||||
type ThreadSummary struct {
|
||||
Listing message.Ref
|
||||
Thread string
|
||||
Messages int
|
||||
Hidden int
|
||||
Replied bool // we have answered at least once
|
||||
FirstAt int64
|
||||
LastAt int64
|
||||
}
|
||||
|
||||
// Address is the exact location and contact data of a listing. It is stored
|
||||
// only here and used only to prefill an address grant.
|
||||
type Address struct {
|
||||
Address string `json:"address"`
|
||||
Phone string `json:"phone,omitempty"`
|
||||
Email string `json:"email,omitempty"`
|
||||
}
|
||||
|
||||
// Region returns the gossip region of a listing, even if it is deleted or
|
||||
// expired but not yet purged, so replies can still be routed.
|
||||
func (s *Store) Region(ctx context.Context, author, id string) (string, error) {
|
||||
var geohash string
|
||||
err := s.db.QueryRowContext(ctx,
|
||||
`SELECT geohash FROM listings WHERE author = ? AND id = ?`, author, id).Scan(&geohash)
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
return "", ErrNotFound
|
||||
}
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return listing.Region(geohash), nil
|
||||
}
|
||||
|
||||
// SeenEnvelopes returns which of the given envelope hashes the owner's node
|
||||
// has already processed.
|
||||
func (s *Store) SeenEnvelopes(ctx context.Context, hashes []string) (map[string]bool, error) {
|
||||
seen := map[string]bool{}
|
||||
for _, h := range hashes {
|
||||
var n int
|
||||
if err := s.db.QueryRowContext(ctx, `SELECT COUNT(*) FROM inbox_seen WHERE hash = ?`, h).Scan(&n); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
seen[h] = n > 0
|
||||
}
|
||||
return seen, nil
|
||||
}
|
||||
|
||||
// MarkSeen records an envelope as processed until expiresAt.
|
||||
func (s *Store) MarkSeen(ctx context.Context, hash string, expiresAt int64) error {
|
||||
_, err := s.db.ExecContext(ctx, `INSERT OR IGNORE INTO inbox_seen (hash, expires_at) VALUES (?, ?)`, hash, expiresAt)
|
||||
return err
|
||||
}
|
||||
|
||||
// AddInbox stores a decrypted message and marks its envelope as seen, in one
|
||||
// transaction. Adding the same hash twice is a no-op.
|
||||
func (s *Store) AddInbox(ctx context.Context, m InboxMessage, seenUntil int64) error {
|
||||
data, err := jcs.Marshal(m.Plain)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
tx, err := s.db.BeginTx(ctx, nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer tx.Rollback()
|
||||
if _, err := tx.ExecContext(ctx, `
|
||||
INSERT OR IGNORE INTO inbox (hash, author, listing_id, thread, dir, n, sent_at, received_at, hidden, data)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
|
||||
m.Hash, m.Listing.Author, m.Listing.ID, m.Thread, m.Dir, m.Plain.N, m.Plain.SentAt, m.ReceivedAt,
|
||||
boolInt(m.Hidden), data); err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err := tx.ExecContext(ctx, `INSERT OR IGNORE INTO inbox_seen (hash, expires_at) VALUES (?, ?)`,
|
||||
m.Hash, seenUntil); err != nil {
|
||||
return err
|
||||
}
|
||||
return tx.Commit()
|
||||
}
|
||||
|
||||
// HasThread reports whether a conversation exists.
|
||||
func (s *Store) HasThread(ctx context.Context, ref message.Ref, thread string) (bool, error) {
|
||||
var n int
|
||||
err := s.db.QueryRowContext(ctx,
|
||||
`SELECT COUNT(*) FROM inbox WHERE author = ? AND listing_id = ? AND thread = ?`,
|
||||
ref.Author, ref.ID, thread).Scan(&n)
|
||||
return n > 0, err
|
||||
}
|
||||
|
||||
// Replied reports whether we have sent anything in the conversation.
|
||||
func (s *Store) Replied(ctx context.Context, ref message.Ref, thread string) (bool, error) {
|
||||
var n int
|
||||
err := s.db.QueryRowContext(ctx,
|
||||
`SELECT COUNT(*) FROM inbox WHERE author = ? AND listing_id = ? AND thread = ? AND dir = 'out'`,
|
||||
ref.Author, ref.ID, thread).Scan(&n)
|
||||
return n > 0, err
|
||||
}
|
||||
|
||||
// NewThreadsSince counts conversations of a listing that began (were first
|
||||
// received) at or after since.
|
||||
func (s *Store) NewThreadsSince(ctx context.Context, ref message.Ref, since int64) (int, error) {
|
||||
var n int
|
||||
err := s.db.QueryRowContext(ctx, `
|
||||
SELECT COUNT(*) FROM (
|
||||
SELECT MIN(received_at) AS first FROM inbox
|
||||
WHERE author = ? AND listing_id = ? GROUP BY thread
|
||||
) WHERE first >= ?`, ref.Author, ref.ID, since).Scan(&n)
|
||||
return n, err
|
||||
}
|
||||
|
||||
// NextOut returns the counter for our next message in a conversation.
|
||||
func (s *Store) NextOut(ctx context.Context, ref message.Ref, thread string) (int64, error) {
|
||||
var max sql.NullInt64
|
||||
err := s.db.QueryRowContext(ctx,
|
||||
`SELECT MAX(n) FROM inbox WHERE author = ? AND listing_id = ? AND thread = ? AND dir = 'out'`,
|
||||
ref.Author, ref.ID, thread).Scan(&max)
|
||||
return max.Int64 + 1, err
|
||||
}
|
||||
|
||||
// Threads lists the author's conversations, most recently active first.
|
||||
func (s *Store) Threads(ctx context.Context, author string) ([]ThreadSummary, error) {
|
||||
rows, err := s.db.QueryContext(ctx, `
|
||||
SELECT listing_id, thread, COUNT(*), SUM(hidden), SUM(dir = 'out'), MIN(received_at), MAX(sent_at)
|
||||
FROM inbox WHERE author = ?
|
||||
GROUP BY listing_id, thread
|
||||
ORDER BY MAX(sent_at) DESC, thread`, author)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
var out []ThreadSummary
|
||||
for rows.Next() {
|
||||
t := ThreadSummary{Listing: message.Ref{Author: author}}
|
||||
var replies int
|
||||
if err := rows.Scan(&t.Listing.ID, &t.Thread, &t.Messages, &t.Hidden, &replies, &t.FirstAt, &t.LastAt); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
t.Replied = replies > 0
|
||||
out = append(out, t)
|
||||
}
|
||||
return out, rows.Err()
|
||||
}
|
||||
|
||||
// ThreadMessages returns a conversation in order.
|
||||
func (s *Store) ThreadMessages(ctx context.Context, ref message.Ref, thread string) ([]InboxMessage, error) {
|
||||
rows, err := s.db.QueryContext(ctx, `
|
||||
SELECT hash, dir, hidden, received_at, data FROM inbox
|
||||
WHERE author = ? AND listing_id = ? AND thread = ?
|
||||
ORDER BY sent_at, dir, n, hash`, ref.Author, ref.ID, thread)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
var out []InboxMessage
|
||||
for rows.Next() {
|
||||
m := InboxMessage{Listing: ref, Thread: thread}
|
||||
var hidden int
|
||||
var data []byte
|
||||
if err := rows.Scan(&m.Hash, &m.Dir, &hidden, &m.ReceivedAt, &data); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
m.Hidden = hidden != 0
|
||||
m.Plain = &message.Plain{}
|
||||
if err := json.Unmarshal(data, m.Plain); err != nil {
|
||||
return nil, fmt.Errorf("store: corrupt inbox row: %w", err)
|
||||
}
|
||||
out = append(out, m)
|
||||
}
|
||||
return out, rows.Err()
|
||||
}
|
||||
|
||||
// DeleteThread erases a conversation from this node.
|
||||
func (s *Store) DeleteThread(ctx context.Context, ref message.Ref, thread string) (bool, error) {
|
||||
res, err := s.db.ExecContext(ctx,
|
||||
`DELETE FROM inbox WHERE author = ? AND listing_id = ? AND thread = ?`, ref.Author, ref.ID, thread)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
n, _ := res.RowsAffected()
|
||||
return n > 0, nil
|
||||
}
|
||||
|
||||
// SetAddress stores the exact address of one of the author's listings.
|
||||
func (s *Store) SetAddress(ctx context.Context, ref message.Ref, a Address) error {
|
||||
_, err := s.db.ExecContext(ctx, `
|
||||
INSERT OR REPLACE INTO addresses (author, listing_id, address, phone, email) VALUES (?, ?, ?, ?, ?)`,
|
||||
ref.Author, ref.ID, a.Address, a.Phone, a.Email)
|
||||
return err
|
||||
}
|
||||
|
||||
// GetAddress returns the stored address, or ErrNotFound.
|
||||
func (s *Store) GetAddress(ctx context.Context, ref message.Ref) (Address, error) {
|
||||
var a Address
|
||||
err := s.db.QueryRowContext(ctx,
|
||||
`SELECT address, phone, email FROM addresses WHERE author = ? AND listing_id = ?`,
|
||||
ref.Author, ref.ID).Scan(&a.Address, &a.Phone, &a.Email)
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
return a, ErrNotFound
|
||||
}
|
||||
return a, err
|
||||
}
|
||||
|
||||
// DeleteAddress erases the stored address.
|
||||
func (s *Store) DeleteAddress(ctx context.Context, ref message.Ref) error {
|
||||
_, err := s.db.ExecContext(ctx,
|
||||
`DELETE FROM addresses WHERE author = ? AND listing_id = ?`, ref.Author, ref.ID)
|
||||
return err
|
||||
}
|
||||
Reference in New Issue
Block a user