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

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

+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
}
}
}
}