实现 MLS 设备封包投递与离线同步
This commit is contained in:
1 parent
53164d0fa8
commit
f30f01b699
15 files changed
+366
-16
No files matched your search
@@ -15,6 +15,7 @@ import (
|
||||
|
||||
"xhchat/server/internal/account"
|
||||
"xhchat/server/internal/contacts"
|
||||
"xhchat/server/internal/delivery"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/redis/go-redis/v9"
|
||||
@@ -23,14 +24,15 @@ import (
|
||||
type API struct {
|
||||
accounts *account.Store
|
||||
contacts *contacts.Store
|
||||
delivery *delivery.Store
|
||||
redis *redis.Client
|
||||
origins map[string]bool
|
||||
hashSlots chan struct{}
|
||||
ready func(context.Context) error
|
||||
}
|
||||
|
||||
func New(accounts *account.Store, contactStore *contacts.Store, cache *redis.Client, origins map[string]bool, ready func(context.Context) error) http.Handler {
|
||||
a := &API{accounts: accounts, contacts: contactStore, redis: cache, origins: origins, hashSlots: make(chan struct{}, 4), ready: ready}
|
||||
func New(accounts *account.Store, contactStore *contacts.Store, envelopeStore *delivery.Store, cache *redis.Client, origins map[string]bool, ready func(context.Context) error) http.Handler {
|
||||
a := &API{accounts: accounts, contacts: contactStore, delivery: envelopeStore, redis: cache, origins: origins, hashSlots: make(chan struct{}, 4), ready: ready}
|
||||
mux := http.NewServeMux()
|
||||
mux.HandleFunc("GET /healthz", func(w http.ResponseWriter, _ *http.Request) { respond(w, 200, map[string]string{"status": "ok"}) })
|
||||
mux.HandleFunc("GET /readyz", a.readiness)
|
||||
@@ -46,6 +48,8 @@ func New(accounts *account.Store, contactStore *contacts.Store, cache *redis.Cli
|
||||
mux.HandleFunc("GET /api/v1/contacts", a.authorized(a.listContacts))
|
||||
mux.HandleFunc("GET /api/v1/contacts/search", a.authorized(a.searchContact))
|
||||
mux.HandleFunc("POST /api/v1/contacts/{id}", a.authorized(a.changeContact))
|
||||
mux.HandleFunc("GET /api/v1/inbox", a.authorized(a.inbox))
|
||||
mux.HandleFunc("POST /api/v1/inbox", a.authorized(a.sendEnvelope))
|
||||
return a.boundary(mux)
|
||||
}
|
||||
|
||||
@@ -236,7 +240,11 @@ func (a *API) limit(w http.ResponseWriter, r *http.Request, key string, max int)
|
||||
}
|
||||
|
||||
func parse(w http.ResponseWriter, r *http.Request, value any) bool {
|
||||
decoder := json.NewDecoder(http.MaxBytesReader(w, r.Body, 4096))
|
||||
return parseLimit(w, r, value, 4096)
|
||||
}
|
||||
|
||||
func parseLimit(w http.ResponseWriter, r *http.Request, value any, maximum int64) bool {
|
||||
decoder := json.NewDecoder(http.MaxBytesReader(w, r.Body, maximum))
|
||||
decoder.DisallowUnknownFields()
|
||||
if err := decoder.Decode(value); err != nil || decoder.Decode(new(any)) != io.EOF {
|
||||
problem(w, 400, "invalid_json", "请求格式错误")
|
||||
|
||||
@@ -0,0 +1,70 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"xhchat/server/internal/account"
|
||||
"xhchat/server/internal/delivery"
|
||||
)
|
||||
|
||||
func (a *API) sendEnvelope(w http.ResponseWriter, r *http.Request, _ string, identity account.Identity) {
|
||||
var input struct {
|
||||
MessageID string `json:"messageId"`
|
||||
RecipientDevice string `json:"recipientDevice"`
|
||||
Ciphertext []byte `json:"ciphertext"`
|
||||
}
|
||||
if !parseLimit(w, r, &input, 96<<10) {
|
||||
return
|
||||
}
|
||||
if !uuidPattern.MatchString(input.MessageID) || !uuidPattern.MatchString(input.RecipientDevice) || !mlsFrame(input.Ciphertext) {
|
||||
problem(w, 400, "invalid_envelope", "请输入有效的 MLS 密文封包")
|
||||
return
|
||||
}
|
||||
if !a.limit(w, r, "envelope-send:"+identity.Device.ID, 180) {
|
||||
return
|
||||
}
|
||||
recipient := strings.ToLower(input.RecipientDevice)
|
||||
seq, err := a.delivery.Send(r.Context(), identity.Device.ID, recipient, input.MessageID, input.Ciphertext)
|
||||
switch {
|
||||
case errors.Is(err, delivery.ErrUnavailable):
|
||||
problem(w, 404, "delivery_unavailable", "无法向指定设备投递")
|
||||
case errors.Is(err, delivery.ErrConflict):
|
||||
problem(w, 409, "message_id_conflict", "消息 ID 已关联其他密文")
|
||||
case err != nil:
|
||||
unavailable(w, err)
|
||||
default:
|
||||
_ = a.redis.Publish(r.Context(), "xhchat:inbox:"+recipient, "changed").Err()
|
||||
respond(w, 200, map[string]string{"sequence": seq})
|
||||
}
|
||||
}
|
||||
|
||||
func mlsFrame(wire []byte) bool {
|
||||
// RFC 9420 MLSMessage header. The delivery service routes PrivateMessage and
|
||||
// Welcome. Recipients validate the complete message and authenticate its contents.
|
||||
return len(wire) >= 16 && len(wire) <= 65536 && wire[0] == 0 && wire[1] == 1 &&
|
||||
wire[2] == 0 && (wire[3] == 2 || wire[3] == 3)
|
||||
}
|
||||
|
||||
func (a *API) inbox(w http.ResponseWriter, r *http.Request, _ string, identity account.Identity) {
|
||||
var after int64
|
||||
if raw := r.URL.Query().Get("after"); raw != "" {
|
||||
var err error
|
||||
after, err = strconv.ParseInt(raw, 10, 64)
|
||||
if err != nil || after < 0 {
|
||||
problem(w, 400, "invalid_cursor", "无效的投递游标")
|
||||
return
|
||||
}
|
||||
}
|
||||
if !a.limit(w, r, "inbox:"+identity.Device.ID, 180) {
|
||||
return
|
||||
}
|
||||
items, err := a.delivery.Inbox(r.Context(), identity.Device.ID, after)
|
||||
if err != nil {
|
||||
unavailable(w, err)
|
||||
return
|
||||
}
|
||||
respond(w, 200, items)
|
||||
}
|
||||
@@ -63,7 +63,8 @@ func (a *API) realtime(w http.ResponseWriter, r *http.Request) {
|
||||
unavailable(w, err)
|
||||
return
|
||||
}
|
||||
subscription := a.redis.Subscribe(r.Context(), "xhchat:contacts:"+identity.User.ID)
|
||||
inboxChannel := "xhchat:inbox:" + identity.Device.ID
|
||||
subscription := a.redis.Subscribe(r.Context(), "xhchat:contacts:"+identity.User.ID, inboxChannel)
|
||||
defer subscription.Close()
|
||||
if _, err = subscription.Receive(r.Context()); err != nil {
|
||||
unavailable(w, err)
|
||||
@@ -94,12 +95,16 @@ func (a *API) realtime(w http.ResponseWriter, r *http.Request) {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case _, ok := <-changes:
|
||||
case change, ok := <-changes:
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
writeCtx, cancel := context.WithTimeout(ctx, 5*time.Second)
|
||||
err := wsjson.Write(writeCtx, conn, map[string]string{"type": "contacts_changed"})
|
||||
event := "contacts_changed"
|
||||
if change.Channel == inboxChannel {
|
||||
event = "inbox_changed"
|
||||
}
|
||||
err := wsjson.Write(writeCtx, conn, map[string]string{"type": event})
|
||||
cancel()
|
||||
if err != nil {
|
||||
return
|
||||
|
||||
Reference in new issue
Block a user