292 lines
11 KiB
Go
292 lines
11 KiB
Go
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"
|
|
"xhchat/server/internal/delivery"
|
|
"xhchat/server/internal/groups"
|
|
|
|
"github.com/jackc/pgx/v5"
|
|
"github.com/redis/go-redis/v9"
|
|
)
|
|
|
|
type API struct {
|
|
accounts *account.Store
|
|
contacts *contacts.Store
|
|
delivery *delivery.Store
|
|
groups *groups.Store
|
|
redis *redis.Client
|
|
origins map[string]bool
|
|
hashSlots chan struct{}
|
|
ready func(context.Context) error
|
|
}
|
|
|
|
func New(accounts *account.Store, contactStore *contacts.Store, envelopeStore *delivery.Store, groupStore *groups.Store, cache *redis.Client, origins map[string]bool, ready func(context.Context) error) http.Handler {
|
|
a := &API{accounts: accounts, contacts: contactStore, delivery: envelopeStore, groups: groupStore, 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))
|
|
mux.HandleFunc("GET /api/v1/inbox", a.authorized(a.inbox))
|
|
mux.HandleFunc("POST /api/v1/inbox", a.authorized(a.sendEnvelope))
|
|
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("GET /api/v1/key-packages", a.authorized(a.packageStatus))
|
|
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))
|
|
mux.HandleFunc("GET /api/v1/groups", a.authorized(a.listGroups))
|
|
mux.HandleFunc("POST /api/v1/groups", a.authorized(a.createGroup))
|
|
mux.HandleFunc("GET /api/v1/groups/{id}", a.authorized(a.groupDetail))
|
|
mux.HandleFunc("POST /api/v1/groups/{id}", a.authorized(a.changeGroup))
|
|
mux.HandleFunc("GET /api/v1/groups/{id}/epochs", a.authorized(a.groupEpochs))
|
|
mux.HandleFunc("POST /api/v1/groups/{id}/epochs", a.authorized(a.publishGroupEpoch))
|
|
mux.HandleFunc("GET /api/v1/groups/{id}/messages", a.authorized(a.groupInbox))
|
|
mux.HandleFunc("POST /api/v1/groups/{id}/messages", a.authorized(a.sendGroupMessage))
|
|
mux.HandleFunc("POST /api/v1/groups/{id}/attachments/{attachment}", a.authorized(a.uploadGroupAttachment))
|
|
mux.HandleFunc("GET /api/v1/groups/{id}/attachments/{attachment}", a.authorized(a.downloadGroupAttachment))
|
|
mux.HandleFunc("GET /api/v1/groups/{id}/devices", a.authorized(a.groupDevices))
|
|
mux.HandleFunc("POST /api/v1/groups/{id}/devices/{device}/claim", a.authorized(a.claimGroupPackage))
|
|
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 {
|
|
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", "请求格式错误")
|
|
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", "服务暂不可用")
|
|
}
|