交付双端基础、实时联系人和隔离浏览器

This commit is contained in:
xhgit committed 2026-11-13 18:03:32 +08:00
1 parent 43687d5e7e
commit 67fef3ff87
59 files changed
+5094 -1

No files matched your search

+57
View File
@@ -0,0 +1,57 @@
package account
import (
"crypto/ed25519"
"crypto/rand"
"crypto/subtle"
"encoding/base64"
"fmt"
"strings"
"golang.org/x/crypto/argon2"
)
const deviceProof = "XHChat device authentication v1\n"
var Encoding = base64.RawURLEncoding
func Secret() string {
var bytes [32]byte
rand.Read(bytes[:])
return Encoding.EncodeToString(bytes[:])
}
func Proof(publicKey, challenge, signature string) ([]byte, bool) {
key, keyErr := Encoding.DecodeString(publicKey)
sig, sigErr := Encoding.DecodeString(signature)
nonce, nonceErr := Encoding.DecodeString(challenge)
if keyErr != nil || sigErr != nil || nonceErr != nil || len(key) != ed25519.PublicKeySize || len(nonce) != 32 {
return nil, false
}
return key, ed25519.Verify(key, []byte(deviceProof+challenge), sig)
}
func PasswordHash(password string) string {
var salt [16]byte
rand.Read(salt[:])
key := derive(password, salt[:])
return fmt.Sprintf("$argon2id$v=19$m=65536,t=3,p=2$%s$%s",
base64.RawStdEncoding.EncodeToString(salt[:]), base64.RawStdEncoding.EncodeToString(key))
}
func VerifyPassword(password, hash string) bool {
fields := strings.Split(hash, "$")
if len(fields) != 6 || strings.Join(fields[:4], "$") != "$argon2id$v=19$m=65536,t=3,p=2" {
return false
}
salt, saltErr := base64.RawStdEncoding.DecodeString(fields[4])
key, keyErr := base64.RawStdEncoding.DecodeString(fields[5])
if saltErr != nil || keyErr != nil || len(salt) != 16 || len(key) != 32 {
return false
}
return subtle.ConstantTimeCompare(derive(password, salt), key) == 1
}
func derive(password string, salt []byte) []byte {
return argon2.IDKey([]byte(password), salt, 3, 64*1024, 2, 32)
}
+37
View File
@@ -0,0 +1,37 @@
package account
import (
"crypto/ed25519"
"crypto/rand"
"testing"
)
func TestDeviceProof(t *testing.T) {
public, private, err := ed25519.GenerateKey(rand.Reader)
if err != nil {
t.Fatal(err)
}
challenge := Secret()
signature := Encoding.EncodeToString(ed25519.Sign(private, []byte(deviceProof+challenge)))
key := Encoding.EncodeToString(public)
if _, ok := Proof(key, challenge, signature); !ok {
t.Fatal("valid signature rejected")
}
if _, ok := Proof(key, Secret(), signature); ok {
t.Fatal("signature accepted for a different challenge")
}
if _, ok := Proof("invalid", challenge, signature); ok {
t.Fatal("invalid public key accepted")
}
}
func TestPasswordHash(t *testing.T) {
const password = "test password with sufficient length"
hash := PasswordHash(password)
if hash == PasswordHash(password) {
t.Fatal("salt was reused")
}
if !VerifyPassword(password, hash) || VerifyPassword("wrong", hash) || VerifyPassword(password, "malformed") {
t.Fatal("unexpected password verification result")
}
}
+210
View File
@@ -0,0 +1,210 @@
package account
import (
"context"
"crypto/sha256"
"errors"
"time"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgconn"
"github.com/jackc/pgx/v5/pgxpool"
)
var (
ErrCredentials = errors.New("invalid credentials")
ErrDuplicate = errors.New("username already in use")
ErrRevoked = errors.New("device revoked")
)
type User struct {
ID string `json:"id"`
Username string `json:"username"`
}
type Device struct {
ID string `json:"id"`
Name string `json:"name"`
Platform string `json:"platform"`
CreatedAt time.Time `json:"createdAt"`
LastActiveAt time.Time `json:"lastActiveAt"`
RevokedAt *time.Time `json:"revokedAt,omitempty"`
SignedIn bool `json:"signedIn"`
}
type Identity struct {
User User `json:"user"`
Device Device `json:"device"`
}
type Auth struct {
Identity
Token string `json:"token"`
}
type Store struct {
db *pgxpool.Pool
ttl time.Duration
dummyHash string
}
func New(db *pgxpool.Pool, ttl time.Duration) *Store {
return &Store{db: db, ttl: ttl, dummyHash: PasswordHash(Secret())}
}
func (s *Store) Open(ctx context.Context, register bool, username, password, name, platform string, publicKey []byte) (Auth, error) {
var result Auth
result.User.Username = username
var hash string
if register {
hash = PasswordHash(password)
} else {
err := s.db.QueryRow(ctx, "SELECT id, password_hash FROM users WHERE username=$1", username).Scan(&result.User.ID, &hash)
if errors.Is(err, pgx.ErrNoRows) {
VerifyPassword(password, s.dummyHash)
return Auth{}, ErrCredentials
}
if err != nil {
return Auth{}, err
}
if !VerifyPassword(password, hash) {
return Auth{}, ErrCredentials
}
}
tx, err := s.db.Begin(ctx)
if err != nil {
return Auth{}, err
}
defer tx.Rollback(ctx)
if register {
err = tx.QueryRow(ctx, "INSERT INTO users(username,password_hash) VALUES ($1,$2) RETURNING id", username, hash).Scan(&result.User.ID)
var pgErr *pgconn.PgError
if errors.As(err, &pgErr) && pgErr.Code == "23505" {
return Auth{}, ErrDuplicate
}
if err != nil {
return Auth{}, err
}
}
row := tx.QueryRow(ctx, `
INSERT INTO devices(user_id, public_key, name, platform)
VALUES ($1,$2,$3,$4)
ON CONFLICT (user_id, public_key) DO UPDATE
SET last_active_at=now(), name=EXCLUDED.name
WHERE devices.revoked_at IS NULL AND devices.platform=EXCLUDED.platform
RETURNING id, name, platform, created_at, last_active_at, revoked_at
`, result.User.ID, publicKey, name, platform)
if err = scanDevice(row, &result.Device); errors.Is(err, pgx.ErrNoRows) {
return Auth{}, ErrRevoked
}
if err != nil {
return Auth{}, err
}
result.Token = Secret()
digest := sha256.Sum256([]byte(result.Token))
if _, err = tx.Exec(ctx, "INSERT INTO sessions VALUES ($1,$2,$3)", digest[:], result.Device.ID, time.Now().Add(s.ttl)); err != nil {
return Auth{}, err
}
result.Device.SignedIn = true
return result, tx.Commit(ctx)
}
func (s *Store) Session(ctx context.Context, token string) (Identity, error) {
digest, err := SessionDigest(token)
if err != nil {
return Identity{}, err
}
return s.SessionByDigest(ctx, digest[:])
}
func SessionDigest(token string) ([32]byte, error) {
raw, err := Encoding.Strict().DecodeString(token)
if err != nil || len(raw) != 32 {
return [32]byte{}, ErrCredentials
}
return sha256.Sum256([]byte(token)), nil
}
func (s *Store) SessionByDigest(ctx context.Context, digest []byte) (Identity, error) {
var identity Identity
d := &identity.Device
err := s.db.QueryRow(ctx, `
SELECT u.id, u.username, d.id, d.name, d.platform, d.created_at, d.last_active_at, d.revoked_at
FROM sessions s JOIN devices d ON d.id=s.device_id JOIN users u ON u.id=d.user_id
WHERE token_hash=$1 AND expires_at > now() AND d.revoked_at IS NULL
`, digest).Scan(&identity.User.ID, &identity.User.Username, &d.ID, &d.Name, &d.Platform, &d.CreatedAt, &d.LastActiveAt, &d.RevokedAt)
if errors.Is(err, pgx.ErrNoRows) {
return Identity{}, ErrCredentials
}
d.SignedIn = err == nil
return identity, err
}
func (s *Store) Logout(ctx context.Context, token string) error {
digest := sha256.Sum256([]byte(token))
_, err := s.db.Exec(ctx, "DELETE FROM sessions WHERE token_hash=$1", digest[:])
return err
}
func (s *Store) Devices(ctx context.Context, user string) ([]Device, error) {
rows, err := s.db.Query(ctx, `
SELECT id, name, platform, created_at, last_active_at, revoked_at,
revoked_at IS NULL AND EXISTS (
SELECT 1 FROM sessions WHERE device_id=devices.id AND expires_at > now()
)
FROM devices
WHERE user_id=$1 ORDER BY created_at DESC
`, user)
if err != nil {
return nil, err
}
defer rows.Close()
devices := make([]Device, 0)
for rows.Next() {
var device Device
if err := rows.Scan(&device.ID, &device.Name, &device.Platform, &device.CreatedAt,
&device.LastActiveAt, &device.RevokedAt, &device.SignedIn); err != nil {
return nil, err
}
devices = append(devices, device)
}
return devices, rows.Err()
}
func (s *Store) TouchDevice(ctx context.Context, device string) error {
_, err := s.db.Exec(ctx, `
UPDATE devices SET last_active_at=now()
WHERE id=$1 AND revoked_at IS NULL AND last_active_at < now() - interval '1 minute'
`, device)
return err
}
func (s *Store) Revoke(ctx context.Context, user, device string) error {
tx, err := s.db.Begin(ctx)
if err != nil {
return err
}
defer tx.Rollback(ctx)
result, err := tx.Exec(ctx, "UPDATE devices SET revoked_at=COALESCE(revoked_at,now()) WHERE user_id=$1 AND id=$2", user, device)
if err != nil {
return err
}
if result.RowsAffected() == 0 {
return pgx.ErrNoRows
}
if _, err := tx.Exec(ctx, "DELETE FROM sessions WHERE device_id=$1", device); err != nil {
return err
}
return tx.Commit(ctx)
}
func (s *Store) Cleanup(ctx context.Context) error {
_, err := s.db.Exec(ctx, "DELETE FROM sessions WHERE expires_at <= now()")
return err
}
func scanDevice(row pgx.Row, d *Device) error {
return row.Scan(&d.ID, &d.Name, &d.Platform, &d.CreatedAt, &d.LastActiveAt, &d.RevokedAt)
}
+36
View File
@@ -0,0 +1,36 @@
package config
import (
"errors"
"os"
"strings"
"time"
)
type Config struct {
Addr, DatabaseURL, RedisURL string
Origins map[string]bool
SessionTTL time.Duration
}
func Load() (Config, error) {
c := Config{
Addr: os.Getenv("XHCHAT_ADDR"),
DatabaseURL: os.Getenv("DATABASE_URL"),
RedisURL: os.Getenv("REDIS_URL"),
Origins: make(map[string]bool),
SessionTTL: 12 * time.Hour,
}
if c.Addr == "" {
c.Addr = "127.0.0.1:8080"
}
for _, origin := range strings.Split(os.Getenv("XHCHAT_ORIGINS"), ",") {
if origin = strings.TrimSpace(origin); origin != "" {
c.Origins[origin] = true
}
}
if c.DatabaseURL == "" || c.RedisURL == "" || len(c.Origins) == 0 {
return Config{}, errors.New("DATABASE_URL, REDIS_URL and XHCHAT_ORIGINS are required")
}
return c, nil
}
+165
View File
@@ -0,0 +1,165 @@
package contacts
import (
"context"
"errors"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgxpool"
)
var ErrUnavailable = errors.New("contact action unavailable")
type Contact struct {
ID string `json:"id"`
Username string `json:"username"`
State string `json:"state"`
Alias string `json:"alias"`
Category string `json:"category"`
}
type Store struct{ db *pgxpool.Pool }
func New(db *pgxpool.Pool) *Store { return &Store{db: db} }
const selectContact = `
SELECT u.id, u.username,
CASE WHEN mine.owner_id IS NOT NULL THEN 'blocked'
WHEN r.status = 'accepted' THEN 'friend'
WHEN r.requested_by = $1 THEN 'outgoing'
WHEN r.status = 'pending' THEN 'incoming'
ELSE 'none' END,
COALESCE(p.alias,''), COALESCE(p.category,'')
FROM users u
LEFT JOIN contact_relationships r ON r.first_user = LEAST($1::uuid, u.id)
AND r.second_user = GREATEST($1::uuid, u.id)
LEFT JOIN contact_blocks mine ON mine.owner_id=$1 AND mine.blocked_id=u.id
LEFT JOIN contact_blocks theirs ON theirs.owner_id=u.id AND theirs.blocked_id=$1
LEFT JOIN contact_preferences p ON p.owner_id=$1 AND p.contact_id=u.id
WHERE u.id <> $1 AND (theirs.owner_id IS NULL OR mine.owner_id IS NOT NULL)
`
func (s *Store) Search(ctx context.Context, owner, username string) (Contact, error) {
var c Contact
err := s.db.QueryRow(ctx, selectContact+" AND u.username=$2", owner, username).
Scan(&c.ID, &c.Username, &c.State, &c.Alias, &c.Category)
return c, err
}
func (s *Store) List(ctx context.Context, owner string) ([]Contact, error) {
rows, err := s.db.Query(ctx, selectContact+`
AND (mine.owner_id IS NOT NULL OR r.status IS NOT NULL)
ORDER BY u.username LIMIT 1000`, owner)
if err != nil {
return nil, err
}
defer rows.Close()
result := make([]Contact, 0)
for rows.Next() {
var c Contact
if err := rows.Scan(&c.ID, &c.Username, &c.State, &c.Alias, &c.Category); err != nil {
return nil, err
}
result = append(result, c)
}
return result, rows.Err()
}
func (s *Store) Change(ctx context.Context, owner, target, action, alias, category string) error {
tx, err := s.db.Begin(ctx)
if err != nil {
return err
}
defer tx.Rollback(ctx)
// Lock the same two rows in the same order for all transitions of a pair.
var count int
err = tx.QueryRow(ctx, `
SELECT count(*) FROM (
SELECT id FROM users WHERE id IN ($1,$2) ORDER BY id FOR UPDATE
) AS participants`, owner, target).Scan(&count)
if err != nil {
return err
}
if count != 2 {
return ErrUnavailable
}
const pair = "first_user=LEAST($1::uuid,$2::uuid) AND second_user=GREATEST($1::uuid,$2::uuid)"
const remove = "DELETE FROM contact_relationships WHERE " + pair
switch action {
case "request":
var blocked bool
err = tx.QueryRow(ctx, `
SELECT EXISTS(SELECT 1 FROM contact_blocks
WHERE (owner_id=$1 AND blocked_id=$2) OR (owner_id=$2 AND blocked_id=$1))
`, owner, target).Scan(&blocked)
if err != nil {
return err
}
if blocked {
return ErrUnavailable
}
var state string
err = tx.QueryRow(ctx, `
INSERT INTO contact_relationships(first_user,second_user,requested_by,status)
VALUES(LEAST($1::uuid,$2::uuid),GREATEST($1::uuid,$2::uuid),$1,'pending')
ON CONFLICT(first_user,second_user) DO UPDATE
SET updated_at=contact_relationships.updated_at
WHERE contact_relationships.requested_by=$1 AND contact_relationships.status='pending'
RETURNING status`, owner, target).Scan(&state)
if errors.Is(err, pgx.ErrNoRows) {
return ErrUnavailable
}
case "accept":
tag, updateErr := tx.Exec(ctx, "UPDATE contact_relationships SET status='accepted',updated_at=now() WHERE "+pair+" AND requested_by=$2 AND status='pending'", owner, target)
err = updateErr
if err == nil && tag.RowsAffected() == 0 {
return ErrUnavailable
}
case "reject":
_, err = tx.Exec(ctx, remove+" AND requested_by=$2 AND status='pending'", owner, target)
case "cancel":
_, err = tx.Exec(ctx, remove+" AND requested_by=$1 AND status='pending'", owner, target)
case "delete":
tag, deleteErr := tx.Exec(ctx, remove+" AND status='accepted'", owner, target)
err = deleteErr
if err == nil && tag.RowsAffected() > 0 {
err = clearPreferences(ctx, tx, owner, target)
}
case "block":
_, err = tx.Exec(ctx, "INSERT INTO contact_blocks VALUES($1,$2) ON CONFLICT DO NOTHING", owner, target)
if err == nil {
_, err = tx.Exec(ctx, remove, owner, target)
}
if err == nil {
err = clearPreferences(ctx, tx, owner, target)
}
case "unblock":
_, err = tx.Exec(ctx, "DELETE FROM contact_blocks WHERE owner_id=$1 AND blocked_id=$2", owner, target)
case "preferences":
tag, writeErr := tx.Exec(ctx, `
INSERT INTO contact_preferences(owner_id,contact_id,alias,category)
SELECT $1,$2,$3,$4 FROM contact_relationships WHERE `+pair+` AND status='accepted'
ON CONFLICT (owner_id,contact_id) DO UPDATE SET alias=EXCLUDED.alias,category=EXCLUDED.category
`, owner, target, alias, category)
err = writeErr
if err == nil && tag.RowsAffected() == 0 {
return ErrUnavailable
}
default:
return ErrUnavailable
}
if err != nil {
return err
}
return tx.Commit(ctx)
}
func clearPreferences(ctx context.Context, tx pgx.Tx, owner, target string) error {
_, err := tx.Exec(ctx, `
DELETE FROM contact_preferences WHERE
(owner_id=$1 AND contact_id=$2) OR (owner_id=$2 AND contact_id=$1)
`, owner, target)
return err
}
+27
View File
@@ -0,0 +1,27 @@
CREATE TABLE users (
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
username text UNIQUE NOT NULL CHECK (username ~ '^[a-z0-9_]{3,32}$'),
password_hash text NOT NULL,
created_at timestamptz NOT NULL DEFAULT now()
);
CREATE TABLE devices (
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
user_id uuid NOT NULL REFERENCES users(id) ON DELETE CASCADE,
public_key bytea NOT NULL CHECK (octet_length(public_key) = 32),
name text NOT NULL,
platform text NOT NULL CHECK (platform IN ('web', 'windows')),
created_at timestamptz NOT NULL DEFAULT now(),
last_active_at timestamptz NOT NULL DEFAULT now(),
revoked_at timestamptz,
UNIQUE (user_id, public_key)
);
CREATE TABLE sessions (
token_hash bytea PRIMARY KEY CHECK (octet_length(token_hash) = 32),
device_id uuid NOT NULL REFERENCES devices(id) ON DELETE CASCADE,
expires_at timestamptz NOT NULL
);
CREATE INDEX sessions_device ON sessions(device_id);
CREATE INDEX sessions_expiry ON sessions(expires_at);
+28
View File
@@ -0,0 +1,28 @@
CREATE TABLE contact_relationships (
first_user uuid NOT NULL REFERENCES users(id) ON DELETE CASCADE,
second_user uuid NOT NULL REFERENCES users(id) ON DELETE CASCADE,
requested_by uuid NOT NULL REFERENCES users(id) ON DELETE CASCADE,
status text NOT NULL CHECK (status IN ('pending','accepted')),
updated_at timestamptz NOT NULL DEFAULT now(),
PRIMARY KEY (first_user, second_user),
CHECK (first_user < second_user),
CHECK (requested_by IN (first_user, second_user))
);
CREATE INDEX contact_relationships_second_user ON contact_relationships(second_user);
CREATE TABLE contact_blocks (
owner_id uuid NOT NULL REFERENCES users(id) ON DELETE CASCADE,
blocked_id uuid NOT NULL REFERENCES users(id) ON DELETE CASCADE,
PRIMARY KEY (owner_id, blocked_id),
CHECK (owner_id <> blocked_id)
);
CREATE TABLE contact_preferences (
owner_id uuid NOT NULL REFERENCES users(id) ON DELETE CASCADE,
contact_id uuid NOT NULL REFERENCES users(id) ON DELETE CASCADE,
alias text NOT NULL,
category text NOT NULL,
PRIMARY KEY (owner_id, contact_id),
CHECK (owner_id <> contact_id)
);
+45
View File
@@ -0,0 +1,45 @@
package database
import (
"context"
_ "embed"
"github.com/jackc/pgx/v5/pgxpool"
)
//go:embed 001_identity.sql
var identityMigration string
//go:embed 002_contacts.sql
var contactsMigration string
func Migrate(ctx context.Context, pool *pgxpool.Pool) error {
tx, err := pool.Begin(ctx)
if err != nil {
return err
}
defer tx.Rollback(ctx)
if _, err = tx.Exec(ctx, "SELECT pg_advisory_xact_lock(749109272)"); err != nil {
return err
}
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} {
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 {
return err
}
if applied {
continue
}
if _, err = tx.Exec(ctx, migration); err != nil {
return err
}
if _, err = tx.Exec(ctx, "INSERT INTO schema_migrations VALUES ($1)", version); err != nil {
return err
}
}
return tx.Commit(ctx)
}
+261
View File
@@ -0,0 +1,261 @@
package httpapi
import (
"context"
"encoding/json"
"errors"
"io"
"log/slog"
"net/http"
"regexp"
"strings"
"time"
"unicode"
"unicode/utf8"
"xhchat/server/internal/account"
"xhchat/server/internal/contacts"
"github.com/jackc/pgx/v5"
"github.com/redis/go-redis/v9"
)
type API struct {
accounts *account.Store
contacts *contacts.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}
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)
mux.HandleFunc("POST /api/v1/auth/challenge", a.challenge)
mux.HandleFunc("POST /api/v1/auth/register", a.auth(true))
mux.HandleFunc("POST /api/v1/auth/login", a.auth(false))
mux.HandleFunc("POST /api/v1/auth/logout", a.authorized(a.logout))
mux.HandleFunc("GET /api/v1/me", a.authorized(a.me))
mux.HandleFunc("GET /api/v1/devices", a.authorized(a.devices))
mux.HandleFunc("DELETE /api/v1/devices/{id}", a.authorized(a.revoke))
mux.HandleFunc("POST /api/v1/realtime/ticket", a.authorized(a.ticket))
mux.HandleFunc("GET /api/v1/realtime", a.realtime)
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))
return a.boundary(mux)
}
func (a *API) boundary(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Cache-Control", "no-store")
w.Header().Set("X-Content-Type-Options", "nosniff")
w.Header().Add("Vary", "Origin")
if origin := r.Header.Get("Origin"); origin != "" {
if !a.origins[origin] {
problem(w, 403, "origin_denied", "此来源未获授权")
return
}
w.Header().Set("Access-Control-Allow-Origin", origin)
}
if r.Method == http.MethodOptions && r.Header.Get("Origin") != "" {
w.Header().Set("Access-Control-Allow-Methods", "GET, POST, DELETE")
w.Header().Set("Access-Control-Allow-Headers", "Authorization, Content-Type")
w.WriteHeader(http.StatusNoContent)
return
}
next.ServeHTTP(w, r)
})
}
func (a *API) readiness(w http.ResponseWriter, r *http.Request) {
ctx, cancel := context.WithTimeout(r.Context(), 2*time.Second)
defer cancel()
if a.ready(ctx) != nil {
problem(w, 503, "unavailable", "服务暂不可用")
return
}
respond(w, 200, map[string]string{"status": "ready"})
}
func (a *API) challenge(w http.ResponseWriter, r *http.Request) {
if !a.limit(w, r, "challenge", 300) {
return
}
challenge := account.Secret()
if err := a.redis.Set(r.Context(), "xhchat:challenge:"+challenge, "1", 2*time.Minute).Err(); err != nil {
unavailable(w, err)
return
}
respond(w, 200, map[string]string{"challenge": challenge})
}
type credentials struct {
Username, Password, DeviceName, Platform, PublicKey, Challenge, Signature string
}
var usernamePattern = regexp.MustCompile(`^[a-z0-9_]{3,32}$`)
var uuidPattern = regexp.MustCompile(`^[0-9a-fA-F]{8}(-[0-9a-fA-F]{4}){3}-[0-9a-fA-F]{12}$`)
func (a *API) auth(register bool) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
var input credentials
if !parse(w, r, &input) {
return
}
input.Username = strings.ToLower(strings.TrimSpace(input.Username))
input.DeviceName = strings.TrimSpace(input.DeviceName)
if !usernamePattern.MatchString(input.Username) ||
len(input.Password) > 256 || utf8.RuneCountInString(input.Password) < 12 ||
len(input.DeviceName) == 0 || utf8.RuneCountInString(input.DeviceName) > 64 ||
strings.ContainsFunc(input.DeviceName, unicode.IsControl) ||
(input.Platform != "web" && input.Platform != "windows") {
problem(w, 400, "invalid_credentials_format", "请检查用户名、密码和设备名称的格式")
return
}
key, ok := account.Proof(input.PublicKey, input.Challenge, input.Signature)
if !ok {
problem(w, 400, "invalid_device_proof", "设备签名验证失败")
return
}
if !a.limit(w, r, "auth", 120) || !a.limit(w, r, "account:"+input.Username, 10) {
return
}
err := a.redis.GetDel(r.Context(), "xhchat:challenge:"+input.Challenge).Err()
if errors.Is(err, redis.Nil) {
problem(w, 400, "expired_challenge", "设备验证已失效,请重试")
return
}
if err != nil {
unavailable(w, err)
return
}
select {
case a.hashSlots <- struct{}{}:
defer func() { <-a.hashSlots }()
default:
problem(w, 429, "busy", "登录服务繁忙,请稍后重试")
return
}
result, err := a.accounts.Open(r.Context(), register, input.Username, input.Password, input.DeviceName, input.Platform, key)
switch {
case errors.Is(err, account.ErrCredentials):
problem(w, 401, "invalid_credentials", "用户名或密码错误")
case errors.Is(err, account.ErrDuplicate):
problem(w, 409, "duplicate_username", "用户名已被使用")
case errors.Is(err, account.ErrRevoked):
problem(w, 403, "device_revoked", "此设备已撤销")
case err != nil:
unavailable(w, err)
case register:
respond(w, 201, result)
default:
respond(w, 200, result)
}
}
}
type sessionHandler func(http.ResponseWriter, *http.Request, string, account.Identity)
func (a *API) authorized(next sessionHandler) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
token, _ := strings.CutPrefix(r.Header.Get("Authorization"), "Bearer ")
identity, err := a.accounts.Session(r.Context(), token)
if errors.Is(err, account.ErrCredentials) {
problem(w, 401, "unauthorized", "登录会话已失效")
return
}
if err != nil {
unavailable(w, err)
return
}
next(w, r, token, identity)
}
}
func (a *API) me(w http.ResponseWriter, _ *http.Request, _ string, identity account.Identity) {
respond(w, 200, identity)
}
func (a *API) devices(w http.ResponseWriter, r *http.Request, _ string, identity account.Identity) {
devices, err := a.accounts.Devices(r.Context(), identity.User.ID)
if err != nil {
unavailable(w, err)
return
}
respond(w, 200, devices)
}
func (a *API) logout(w http.ResponseWriter, r *http.Request, token string, _ account.Identity) {
if err := a.accounts.Logout(r.Context(), token); err != nil {
unavailable(w, err)
return
}
w.WriteHeader(204)
}
func (a *API) revoke(w http.ResponseWriter, r *http.Request, _ string, identity account.Identity) {
id := r.PathValue("id")
if !uuidPattern.MatchString(id) {
problem(w, 404, "device_not_found", "设备不存在")
return
}
err := a.accounts.Revoke(r.Context(), identity.User.ID, id)
if errors.Is(err, pgx.ErrNoRows) {
problem(w, 404, "device_not_found", "设备不存在")
return
}
if err != nil {
unavailable(w, err)
return
}
w.WriteHeader(204)
}
var increment = redis.NewScript(`
local count = redis.call('INCR', KEYS[1])
if count == 1 then redis.call('EXPIRE', KEYS[1], 60) end
return count
`)
func (a *API) limit(w http.ResponseWriter, r *http.Request, key string, max int) bool {
count, err := increment.Run(r.Context(), a.redis, []string{"xhchat:limit:" + key}).Int()
if err != nil {
unavailable(w, err)
return false
}
if count > max {
w.Header().Set("Retry-After", "60")
problem(w, 429, "rate_limited", "操作过于频繁,请稍后重试")
return false
}
return true
}
func parse(w http.ResponseWriter, r *http.Request, value any) bool {
decoder := json.NewDecoder(http.MaxBytesReader(w, r.Body, 4096))
decoder.DisallowUnknownFields()
if err := decoder.Decode(value); err != nil || decoder.Decode(new(any)) != io.EOF {
problem(w, 400, "invalid_json", "请求格式错误")
return false
}
return true
}
func respond(w http.ResponseWriter, status int, value any) {
w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.WriteHeader(status)
_ = json.NewEncoder(w).Encode(value)
}
func problem(w http.ResponseWriter, status int, code, message string) {
respond(w, status, map[string]any{"error": map[string]string{"code": code, "message": message}})
}
func unavailable(w http.ResponseWriter, err error) {
slog.Error("request dependency failed", "error_type", errorType(err))
problem(w, 503, "unavailable", "服务暂不可用")
}
+86
View File
@@ -0,0 +1,86 @@
package httpapi
import (
"errors"
"net/http"
"strings"
"unicode"
"unicode/utf8"
"xhchat/server/internal/account"
"xhchat/server/internal/contacts"
"github.com/jackc/pgx/v5"
)
func (a *API) listContacts(w http.ResponseWriter, r *http.Request, _ string, identity account.Identity) {
result, err := a.contacts.List(r.Context(), identity.User.ID)
if err != nil {
unavailable(w, err)
return
}
respond(w, 200, result)
}
func (a *API) searchContact(w http.ResponseWriter, r *http.Request, _ string, identity account.Identity) {
username := strings.ToLower(strings.TrimSpace(r.URL.Query().Get("username")))
if !usernamePattern.MatchString(username) {
problem(w, 400, "invalid_username", "请输入完整用户名")
return
}
if !a.limit(w, r, "contact-search:"+identity.User.ID, 60) {
return
}
result, err := a.contacts.Search(r.Context(), identity.User.ID, username)
if errors.Is(err, pgx.ErrNoRows) {
problem(w, 404, "contact_not_found", "找不到该用户")
return
}
if err != nil {
unavailable(w, err)
return
}
respond(w, 200, result)
}
func (a *API) changeContact(w http.ResponseWriter, r *http.Request, _ string, identity account.Identity) {
target := r.PathValue("id")
if !uuidPattern.MatchString(target) {
problem(w, 404, "contact_not_found", "找不到该用户")
return
}
var input struct {
Action string `json:"action"`
Alias string `json:"alias"`
Category string `json:"category"`
}
if !parse(w, r, &input) {
return
}
input.Alias = strings.TrimSpace(input.Alias)
input.Category = strings.TrimSpace(input.Category)
if utf8.RuneCountInString(input.Alias) > 64 || utf8.RuneCountInString(input.Category) > 32 ||
strings.ContainsFunc(input.Alias, unicode.IsControl) || strings.ContainsFunc(input.Category, unicode.IsControl) {
problem(w, 400, "invalid_contact_preferences", "请检查备注和分组")
return
}
if !a.limit(w, r, "contact-change:"+identity.User.ID, 60) {
return
}
err := a.contacts.Change(r.Context(), identity.User.ID, target, input.Action, input.Alias, input.Category)
if errors.Is(err, contacts.ErrUnavailable) {
problem(w, 409, "contact_action_unavailable", "当前无法执行此联系人操作,请刷新后重试")
return
}
if err != nil {
unavailable(w, err)
return
}
pipe := a.redis.Pipeline()
pipe.Publish(r.Context(), "xhchat:contacts:"+identity.User.ID, "changed")
if input.Action != "preferences" {
pipe.Publish(r.Context(), "xhchat:contacts:"+strings.ToLower(target), "changed")
}
_, _ = pipe.Exec(r.Context())
w.WriteHeader(204)
}
+135
View File
@@ -0,0 +1,135 @@
package httpapi
import (
"context"
"errors"
"fmt"
"net/http"
"strings"
"time"
"xhchat/server/internal/account"
"github.com/coder/websocket"
"github.com/coder/websocket/wsjson"
"github.com/redis/go-redis/v9"
)
func errorType(err error) string { return fmt.Sprintf("%T", err) }
func (a *API) ticket(w http.ResponseWriter, r *http.Request, token string, identity account.Identity) {
if !a.limit(w, r, "ticket:"+identity.Device.ID, 30) {
return
}
ticket := account.Secret()
digest, _ := account.SessionDigest(token)
if err := a.redis.Set(r.Context(), "xhchat:ticket:"+ticket, digest[:], 30*time.Second).Err(); err != nil {
unavailable(w, err)
return
}
respond(w, 200, map[string]string{"ticket": ticket})
}
func (a *API) realtime(w http.ResponseWriter, r *http.Request) {
if !a.origins[r.Header.Get("Origin")] {
problem(w, 403, "origin_denied", "此来源未获授权")
return
}
protocols := strings.Split(r.Header.Get("Sec-WebSocket-Protocol"), ",")
var ticket string
if len(protocols) == 2 && strings.TrimSpace(protocols[0]) == "xhchat.v1" {
ticket, _ = strings.CutPrefix(strings.TrimSpace(protocols[1]), "ticket.")
}
raw, err := account.Encoding.DecodeString(ticket)
if err != nil || len(raw) != 32 {
problem(w, 401, "invalid_ticket", "连接凭据无效")
return
}
digest, err := a.redis.GetDel(r.Context(), "xhchat:ticket:"+ticket).Bytes()
if errors.Is(err, redis.Nil) {
problem(w, 401, "invalid_ticket", "连接凭据已失效")
return
}
if err != nil {
unavailable(w, err)
return
}
identity, err := a.accounts.SessionByDigest(r.Context(), digest)
if errors.Is(err, account.ErrCredentials) {
problem(w, 401, "unauthorized", "登录会话已失效")
return
}
if err != nil {
unavailable(w, err)
return
}
subscription := a.redis.Subscribe(r.Context(), "xhchat:contacts:"+identity.User.ID)
defer subscription.Close()
if _, err = subscription.Receive(r.Context()); err != nil {
unavailable(w, err)
return
}
changes := subscription.Channel()
// The exact Origin was checked before consuming the ticket.
conn, err := websocket.Accept(w, r, &websocket.AcceptOptions{
Subprotocols: []string{"xhchat.v1"}, InsecureSkipVerify: true,
})
if err != nil {
return
}
defer conn.CloseNow()
conn.SetReadLimit(1024)
ctx := conn.CloseRead(r.Context())
writeCtx, cancel := context.WithTimeout(ctx, 5*time.Second)
err = wsjson.Write(writeCtx, conn, map[string]string{"type": "ready", "deviceId": identity.Device.ID})
cancel()
if err != nil {
return
}
ticker := time.NewTicker(5 * time.Second)
defer ticker.Stop()
heartbeat := time.NewTicker(30 * time.Second)
defer heartbeat.Stop()
for {
select {
case <-ctx.Done():
return
case _, ok := <-changes:
if !ok {
return
}
writeCtx, cancel := context.WithTimeout(ctx, 5*time.Second)
err := wsjson.Write(writeCtx, conn, map[string]string{"type": "contacts_changed"})
cancel()
if err != nil {
return
}
case <-heartbeat.C:
pingCtx, cancel := context.WithTimeout(ctx, 5*time.Second)
err := conn.Ping(pingCtx)
cancel()
if err != nil {
return
}
updateCtx, cancel := context.WithTimeout(ctx, 3*time.Second)
err = a.accounts.TouchDevice(updateCtx, identity.Device.ID)
cancel()
if err != nil {
_ = conn.Close(websocket.StatusInternalError, "dependency unavailable")
return
}
case <-ticker.C:
checkCtx, cancel := context.WithTimeout(ctx, 3*time.Second)
_, err := a.accounts.SessionByDigest(checkCtx, digest)
cancel()
if errors.Is(err, account.ErrCredentials) {
_ = conn.Close(websocket.StatusPolicyViolation, "session ended")
return
}
if err != nil {
_ = conn.Close(websocket.StatusInternalError, "dependency unavailable")
return
}
}
}
}