接通 Windows 与 Web 设备间加密文字聊天

This commit is contained in:
xhgit committed 2026-11-13 18:43:04 +08:00
1 parent b04034ee89
commit d1efdedc57
27 files changed
+880 -22

No files matched your search

@@ -0,0 +1,5 @@
CREATE TABLE device_mls_credentials (
device_id uuid PRIMARY KEY REFERENCES devices(id) ON DELETE CASCADE,
public_key bytea NOT NULL CHECK (octet_length(public_key)=32),
signature bytea NOT NULL CHECK (octet_length(signature)=64)
);
+4 -1
View File
@@ -19,6 +19,9 @@ var deliveryMigration string
//go:embed 004_key_packages.sql
var keyPackagesMigration string
//go:embed 005_mls_credentials.sql
var mlsCredentialsMigration string
func Migrate(ctx context.Context, pool *pgxpool.Pool) error {
tx, err := pool.Begin(ctx)
if err != nil {
@@ -31,7 +34,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} {
for index, migration := range []string{identityMigration, contactsMigration, deliveryMigration, keyPackagesMigration, mlsCredentialsMigration} {
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 {
+56 -4
View File
@@ -10,9 +10,15 @@ import (
)
type DirectoryDevice struct {
ID string `json:"id"`
Name string `json:"name"`
ID string `json:"id"`
Name string `json:"name"`
PublicKey []byte `json:"publicKey"`
MLS *Credential `json:"mls,omitempty"`
}
type Credential struct {
PublicKey []byte `json:"publicKey"`
Signature []byte `json:"signature"`
}
type KeyPackage struct {
@@ -23,6 +29,15 @@ type KeyPackage struct {
var ErrSignature = errors.New("invalid key package device signature")
var ErrPackageLimit = errors.New("device key package limit reached")
func (s *Store) LocalIdentityKey(ctx context.Context, device string) ([]byte, error) {
var key []byte
err := s.db.QueryRow(ctx, "SELECT public_key FROM devices WHERE id=$1 AND revoked_at IS NULL", device).Scan(&key)
if errors.Is(err, pgx.ErrNoRows) {
return nil, ErrUnavailable
}
return key, err
}
const acceptedContact = `
EXISTS (SELECT 1 FROM contact_relationships
WHERE first_user=LEAST($1::uuid,$2::uuid) AND second_user=GREATEST($1::uuid,$2::uuid)
@@ -31,7 +46,8 @@ const acceptedContact = `
func (s *Store) Directory(ctx context.Context, owner, contact string) ([]DirectoryDevice, error) {
rows, err := s.db.Query(ctx, `
SELECT id,name,public_key FROM devices
SELECT id,name,devices.public_key, m.public_key, m.signature FROM devices
LEFT JOIN device_mls_credentials m ON m.device_id=devices.id
WHERE user_id=$2 AND revoked_at IS NULL AND `+acceptedContact+`
ORDER BY id LIMIT 128`, owner, contact)
if err != nil {
@@ -41,14 +57,50 @@ func (s *Store) Directory(ctx context.Context, owner, contact string) ([]Directo
result := make([]DirectoryDevice, 0)
for rows.Next() {
var device DirectoryDevice
if err := rows.Scan(&device.ID, &device.Name, &device.PublicKey); err != nil {
var credential Credential
if err := rows.Scan(&device.ID, &device.Name, &device.PublicKey, &credential.PublicKey, &credential.Signature); err != nil {
return nil, err
}
if credential.PublicKey != nil {
device.MLS = &credential
}
result = append(result, device)
}
return result, rows.Err()
}
func (s *Store) PublishCredential(ctx context.Context, owner, device string, credential Credential) error {
tx, err := s.db.Begin(ctx)
if err != nil {
return err
}
defer tx.Rollback(ctx)
var public []byte
err = tx.QueryRow(ctx, "SELECT public_key FROM devices WHERE id=$1 AND user_id=$2 AND revoked_at IS NULL FOR UPDATE", device, owner).Scan(&public)
if errors.Is(err, pgx.ErrNoRows) {
return ErrUnavailable
}
if err != nil {
return err
}
binding := append([]byte("XHChat MLS credential v1\n"+owner+"\n"+device+"\n"), credential.PublicKey...)
if !ed25519.Verify(public, binding, credential.Signature) {
return ErrSignature
}
tag, err := tx.Exec(ctx, `
INSERT INTO device_mls_credentials VALUES($1,$2,$3)
ON CONFLICT(device_id) DO UPDATE SET signature=EXCLUDED.signature
WHERE device_mls_credentials.public_key=EXCLUDED.public_key
`, device, credential.PublicKey, credential.Signature)
if err != nil {
return err
}
if tag.RowsAffected() == 0 {
return ErrConflict
}
return tx.Commit(ctx)
}
func (s *Store) PublishPackage(ctx context.Context, owner, device string, item KeyPackage) error {
tx, err := s.db.Begin(ctx)
if err != nil {
+2
View File
@@ -53,6 +53,8 @@ func New(accounts *account.Store, contactStore *contacts.Store, envelopeStore *d
mux.HandleFunc("GET /api/v1/contacts/{id}/devices", a.authorized(a.contactDevices))
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("GET /api/v1/mls-local-key", a.authorized(a.localMLSKey))
return a.boundary(mux)
}
@@ -0,0 +1,46 @@
package httpapi
import (
"errors"
"net/http"
"xhchat/server/internal/account"
"xhchat/server/internal/delivery"
)
func (a *API) localMLSKey(w http.ResponseWriter, r *http.Request, _ string, identity account.Identity) {
key, err := a.delivery.LocalIdentityKey(r.Context(), identity.Device.ID)
if errors.Is(err, delivery.ErrUnavailable) {
problem(w, 404, "device_not_found", "设备不可用")
return
}
if err != nil {
unavailable(w, err)
return
}
respond(w, 200, map[string][]byte{"publicKey": key})
}
func (a *API) publishCredential(w http.ResponseWriter, r *http.Request, _ string, identity account.Identity) {
var input delivery.Credential
if !parse(w, r, &input) {
return
}
if len(input.PublicKey) != 32 || len(input.Signature) != 64 {
problem(w, 400, "invalid_credential", "MLS 设备凭据格式无效")
return
}
err := a.delivery.PublishCredential(r.Context(), identity.User.ID, identity.Device.ID, input)
switch {
case errors.Is(err, delivery.ErrSignature):
problem(w, 400, "invalid_credential_signature", "MLS 设备凭据签名无效")
case errors.Is(err, delivery.ErrConflict):
problem(w, 409, "credential_changed", "该设备已绑定其他 MLS 密钥")
case errors.Is(err, delivery.ErrUnavailable):
problem(w, 404, "device_not_found", "设备不可用")
case err != nil:
unavailable(w, err)
default:
w.WriteHeader(204)
}
}