132 lines
3.9 KiB
Go
132 lines
3.9 KiB
Go
package delivery
|
|
|
|
import (
|
|
"bytes"
|
|
"context"
|
|
"errors"
|
|
"time"
|
|
|
|
"github.com/jackc/pgx/v5"
|
|
"github.com/jackc/pgx/v5/pgxpool"
|
|
)
|
|
|
|
var (
|
|
ErrUnavailable = errors.New("delivery unavailable")
|
|
ErrConflict = errors.New("message identifier already used for different bytes")
|
|
)
|
|
|
|
type Envelope struct {
|
|
Sequence string `json:"sequence"`
|
|
MessageID string `json:"messageId"`
|
|
SenderDevice string `json:"senderDevice"`
|
|
Ciphertext []byte `json:"ciphertext"`
|
|
CreatedAt time.Time `json:"createdAt"`
|
|
}
|
|
|
|
type Store struct{ db *pgxpool.Pool }
|
|
|
|
func New(db *pgxpool.Pool) *Store { return &Store{db: db} }
|
|
|
|
func (s *Store) Send(ctx context.Context, sender, recipient, message string, ciphertext []byte) (string, error) {
|
|
tx, err := s.db.Begin(ctx)
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
defer tx.Rollback(ctx)
|
|
|
|
var senderUser, recipientUser string
|
|
err = tx.QueryRow(ctx, `
|
|
SELECT sender.user_id, recipient.user_id FROM devices sender CROSS JOIN devices recipient
|
|
WHERE sender.id=$1 AND recipient.id=$2 AND sender.id<>recipient.id
|
|
`, sender, recipient).Scan(&senderUser, &recipientUser)
|
|
if errors.Is(err, pgx.ErrNoRows) {
|
|
return "", ErrUnavailable
|
|
}
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
|
|
// Use the same account lock order as contact changes. Locking both devices also
|
|
// serializes writes for each recipient and prevents a cursor passing an uncommitted write.
|
|
if _, err = tx.Exec(ctx, "SELECT id FROM users WHERE id IN ($1,$2) ORDER BY id FOR UPDATE", senderUser, recipientUser); err != nil {
|
|
return "", err
|
|
}
|
|
var active int
|
|
err = tx.QueryRow(ctx, `
|
|
SELECT count(*) FROM (
|
|
SELECT id FROM devices WHERE id IN ($1,$2) AND revoked_at IS NULL ORDER BY id FOR UPDATE
|
|
) AS active_devices
|
|
`, sender, recipient).Scan(&active)
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
if active != 2 {
|
|
return "", ErrUnavailable
|
|
}
|
|
|
|
// This direct-message endpoint only connects accepted contacts.
|
|
// A separate authorization flow is needed for same-account device transfers.
|
|
var friends bool
|
|
err = tx.QueryRow(ctx, `
|
|
SELECT EXISTS (SELECT 1 FROM contact_relationships
|
|
WHERE first_user=LEAST($1::uuid,$2::uuid) AND second_user=GREATEST($1::uuid,$2::uuid)
|
|
AND status='accepted')
|
|
`, senderUser, recipientUser).Scan(&friends)
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
if !friends {
|
|
return "", ErrUnavailable
|
|
}
|
|
|
|
var seq string
|
|
err = tx.QueryRow(ctx, `
|
|
INSERT INTO device_envelopes(message_id, sender_device, recipient_device, ciphertext)
|
|
VALUES ($1,$2,$3,$4)
|
|
ON CONFLICT (sender_device, recipient_device, message_id) DO NOTHING
|
|
RETURNING sequence::text
|
|
`, message, sender, recipient, ciphertext).Scan(&seq)
|
|
if errors.Is(err, pgx.ErrNoRows) {
|
|
var previous []byte
|
|
err = tx.QueryRow(ctx, `
|
|
SELECT sequence::text,ciphertext FROM device_envelopes
|
|
WHERE message_id=$1 AND sender_device=$2 AND recipient_device=$3
|
|
`, message, sender, recipient).Scan(&seq, &previous)
|
|
if err == nil && !bytes.Equal(previous, ciphertext) {
|
|
return "", ErrConflict
|
|
}
|
|
}
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
return seq, tx.Commit(ctx)
|
|
}
|
|
|
|
func (s *Store) Inbox(ctx context.Context, recipient string, after int64) ([]Envelope, error) {
|
|
rows, err := s.db.Query(ctx, `
|
|
SELECT e.sequence::text,e.message_id,e.sender_device,e.ciphertext,e.created_at
|
|
FROM device_envelopes e JOIN devices d ON e.recipient_device=d.id
|
|
WHERE d.id=$1 AND d.revoked_at IS NULL AND e.sequence>$2
|
|
ORDER BY e.sequence LIMIT 64
|
|
`, recipient, after)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
defer rows.Close()
|
|
envelopes := make([]Envelope, 0)
|
|
for rows.Next() {
|
|
var envelope Envelope
|
|
if err := rows.Scan(&envelope.Sequence, &envelope.MessageID, &envelope.SenderDevice,
|
|
&envelope.Ciphertext, &envelope.CreatedAt); err != nil {
|
|
return nil, err
|
|
}
|
|
envelopes = append(envelopes, envelope)
|
|
}
|
|
return envelopes, rows.Err()
|
|
}
|
|
|
|
func (s *Store) Cleanup(ctx context.Context, retention time.Duration) error {
|
|
_, err := s.db.Exec(ctx, "DELETE FROM device_envelopes WHERE created_at < $1", time.Now().Add(-retention))
|
|
return err
|
|
}
|