交付 Windows 与 Web 端到端加密附件预览

This commit is contained in:
xhgit committed 2026-11-13 19:14:44 +08:00
1 parent d1efdedc57
commit c24960d22a
19 files changed
+421 -58

No files matched your search

@@ -0,0 +1,10 @@
CREATE TABLE device_attachments (
id uuid PRIMARY KEY,
sender_device uuid NOT NULL REFERENCES devices(id) ON DELETE CASCADE,
recipient_device uuid NOT NULL REFERENCES devices(id) ON DELETE CASCADE,
ciphertext bytea NOT NULL CHECK (octet_length(ciphertext) BETWEEN 16 AND 8388624),
created_at timestamptz NOT NULL DEFAULT now(),
CHECK (sender_device <> recipient_device)
);
CREATE INDEX device_attachments_expiry ON device_attachments(created_at);
+4 -1
View File
@@ -22,6 +22,9 @@ var keyPackagesMigration string
//go:embed 005_mls_credentials.sql
var mlsCredentialsMigration string
//go:embed 006_attachments.sql
var attachmentsMigration string
func Migrate(ctx context.Context, pool *pgxpool.Pool) error {
tx, err := pool.Begin(ctx)
if err != nil {
@@ -34,7 +37,7 @@ func Migrate(ctx context.Context, pool *pgxpool.Pool) error {
if _, err = tx.Exec(ctx, "CREATE TABLE IF NOT EXISTS schema_migrations (version integer PRIMARY KEY)"); err != nil {
return err
}
for index, migration := range []string{identityMigration, contactsMigration, deliveryMigration, keyPackagesMigration, mlsCredentialsMigration} {
for index, migration := range []string{identityMigration, contactsMigration, deliveryMigration, keyPackagesMigration, mlsCredentialsMigration, attachmentsMigration} {
version := index + 1
var applied bool
if err = tx.QueryRow(ctx, "SELECT EXISTS (SELECT 1 FROM schema_migrations WHERE version=$1)", version).Scan(&applied); err != nil {
+55
View File
@@ -0,0 +1,55 @@
package delivery
import (
"bytes"
"context"
"errors"
"github.com/jackc/pgx/v5"
)
const AttachmentLimit = 8<<20 + 16
func (s *Store) UploadAttachment(ctx context.Context, sender, recipient, id string, ciphertext []byte) error {
tx, err := s.db.Begin(ctx)
if err != nil {
return err
}
defer tx.Rollback(ctx)
if err = authorizeDelivery(ctx, tx, sender, recipient); err != nil {
return err
}
result, err := tx.Exec(ctx, `
INSERT INTO device_attachments(id,sender_device,recipient_device,ciphertext)
VALUES($1,$2,$3,$4) ON CONFLICT(id) DO NOTHING
`, id, sender, recipient, ciphertext)
if err != nil {
return err
}
if result.RowsAffected() == 0 {
var stored []byte
err = tx.QueryRow(ctx, `
SELECT ciphertext FROM device_attachments WHERE id=$1 AND sender_device=$2 AND recipient_device=$3
`, id, sender, recipient).Scan(&stored)
if errors.Is(err, pgx.ErrNoRows) || err == nil && !bytes.Equal(stored, ciphertext) {
return ErrConflict
}
if err != nil {
return err
}
}
return tx.Commit(ctx)
}
func (s *Store) DownloadAttachment(ctx context.Context, device, id string) ([]byte, error) {
var ciphertext []byte
err := s.db.QueryRow(ctx, `
SELECT attachment.ciphertext FROM device_attachments attachment JOIN devices d ON d.id=$2
WHERE attachment.id=$1 AND d.revoked_at IS NULL
AND d.id IN (attachment.sender_device,attachment.recipient_device)
`, id, device).Scan(&ciphertext)
if errors.Is(err, pgx.ErrNoRows) {
return nil, ErrUnavailable
}
return ciphertext, err
}
+51 -39
View File
@@ -34,47 +34,10 @@ func (s *Store) Send(ctx context.Context, sender, recipient, message string, cip
}
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 {
if err = authorizeDelivery(ctx, tx, sender, recipient); 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 "+acceptedContact, 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)
@@ -122,10 +85,59 @@ func (s *Store) Inbox(ctx context.Context, recipient string, after int64) ([]Env
}
func (s *Store) Cleanup(ctx context.Context, retention time.Duration) error {
if _, err := s.db.Exec(ctx, "DELETE FROM device_envelopes WHERE created_at < $1", time.Now().Add(-retention)); err != nil {
cutoff := time.Now().Add(-retention)
if _, err := s.db.Exec(ctx, "DELETE FROM device_envelopes WHERE created_at < $1", cutoff); err != nil {
return err
}
if _, err := s.db.Exec(ctx, "DELETE FROM device_attachments WHERE created_at < $1", cutoff); err != nil {
return err
}
// Keep issued package hashes past the validity window of an individual upload.
_, err := s.db.Exec(ctx, "DELETE FROM device_key_packages WHERE created_at < now() - interval '90 days'")
return err
}
func authorizeDelivery(ctx context.Context, tx pgx.Tx, sender, recipient string) error {
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 "+acceptedContact, senderUser, recipientUser).Scan(&friends)
if err != nil {
return err
}
if !friends {
return ErrUnavailable
}
return nil
}
+2
View File
@@ -54,6 +54,8 @@ func New(accounts *account.Store, contactStore *contacts.Store, envelopeStore *d
mux.HandleFunc("POST /api/v1/contacts/{id}/devices/{device}/claim", a.authorized(a.claimPackage))
mux.HandleFunc("POST /api/v1/key-packages", a.authorized(a.publishPackage))
mux.HandleFunc("POST /api/v1/mls-credential", a.authorized(a.publishCredential))
mux.HandleFunc("POST /api/v1/attachments/{id}", a.authorized(a.uploadAttachment))
mux.HandleFunc("GET /api/v1/attachments/{id}", a.authorized(a.downloadAttachment))
mux.HandleFunc("GET /api/v1/mls-local-key", a.authorized(a.localMLSKey))
return a.boundary(mux)
}
+65
View File
@@ -0,0 +1,65 @@
package httpapi
import (
"errors"
"io"
"net/http"
"xhchat/server/internal/account"
"xhchat/server/internal/delivery"
)
func (a *API) uploadAttachment(w http.ResponseWriter, r *http.Request, _ string, identity account.Identity) {
id, recipient := r.PathValue("id"), r.URL.Query().Get("recipient")
if !uuidPattern.MatchString(id) || !uuidPattern.MatchString(recipient) ||
r.Header.Get("Content-Type") != "application/octet-stream" {
problem(w, 400, "invalid_attachment", "附件请求格式无效")
return
}
if !a.limit(w, r, "attachment-upload:"+identity.Device.ID, 12) {
return
}
body, err := io.ReadAll(http.MaxBytesReader(w, r.Body, delivery.AttachmentLimit))
var tooLarge *http.MaxBytesError
switch {
case errors.As(err, &tooLarge):
problem(w, 413, "attachment_too_large", "附件超过 8 MiB")
return
case err != nil || len(body) < 16:
problem(w, 400, "invalid_attachment", "附件请求格式无效")
return
}
err = a.delivery.UploadAttachment(r.Context(), identity.Device.ID, recipient, id, body)
switch {
case errors.Is(err, delivery.ErrUnavailable):
problem(w, 404, "attachment_unavailable", "无法向指定设备发送附件")
case errors.Is(err, delivery.ErrConflict):
problem(w, 409, "attachment_conflict", "附件 ID 已使用")
case err != nil:
unavailable(w, err)
default:
w.WriteHeader(204)
}
}
func (a *API) downloadAttachment(w http.ResponseWriter, r *http.Request, _ string, identity account.Identity) {
id := r.PathValue("id")
if !uuidPattern.MatchString(id) {
problem(w, 404, "attachment_unavailable", "附件不可用")
return
}
if !a.limit(w, r, "attachment-download:"+identity.Device.ID, 30) {
return
}
body, err := a.delivery.DownloadAttachment(r.Context(), identity.Device.ID, id)
switch {
case errors.Is(err, delivery.ErrUnavailable):
problem(w, 404, "attachment_unavailable", "附件不可用或已过期")
case err != nil:
unavailable(w, err)
default:
w.Header().Set("Content-Type", "application/octet-stream")
w.Header().Set("Content-Disposition", "attachment")
_, _ = w.Write(body)
}
}