Files
server/internal/httpapi/server.go
T

300 lines
7.9 KiB
Go

package httpapi
import (
"context"
"crypto/rand"
"crypto/sha256"
"encoding/base64"
"encoding/hex"
"encoding/json"
"errors"
"io"
"log/slog"
"net/http"
"strings"
"time"
"unicode"
"unicode/utf8"
"git.asio.asia/TapRemly/server/internal/store"
)
const (
cookieName = "tapremly_session"
csrfHeader = "X-Tapremly-Request"
sessionTTL = 7 * 24 * time.Hour
maxLoginBody = 8 << 10
maxJSONBody = 1 << 20
)
type Handler struct {
store *store.Store
nix EndpointService
cookieSecure bool
log *slog.Logger
}
type EndpointService interface {
CreateEndpoint(ctx context.Context, name string) (id, password string, err error)
Lookup(ctx context.Context, id string) (found, online bool, err error)
DeleteEndpoint(ctx context.Context, id string) error
}
func New(st *store.Store, nix EndpointService, cookieSecure bool, log *slog.Logger) *Handler {
if log == nil {
log = slog.New(slog.NewJSONHandler(io.Discard, nil))
}
return &Handler{store: st, nix: nix, cookieSecure: cookieSecure, log: log}
}
func (h *Handler) Routes() http.Handler {
mux := http.NewServeMux()
mux.HandleFunc("GET /healthz", h.health)
mux.HandleFunc("GET /readyz", h.ready)
mux.HandleFunc("POST /api/register", h.register)
mux.HandleFunc("POST /api/login", h.login)
mux.HandleFunc("POST /api/logout", h.logout)
mux.HandleFunc("GET /api/me", h.me)
mux.HandleFunc("GET /api/devices", h.listDevices)
mux.HandleFunc("POST /api/devices", h.createDevice)
mux.HandleFunc("PATCH /api/devices/{id}", h.updateDevice)
mux.HandleFunc("DELETE /api/devices/{id}", h.deleteDevice)
mux.HandleFunc("GET /api/devices/{id}/command-logs", h.listLogs)
mux.HandleFunc("PUT /api/command-logs", h.replaceLogs)
mux.HandleFunc("POST /api/groups", h.createGroup)
mux.HandleFunc("PATCH /api/groups/{id}", h.renameGroup)
mux.HandleFunc("DELETE /api/groups/{id}", h.deleteGroup)
mux.HandleFunc("GET /api/admin/users", h.listUsers)
mux.HandleFunc("POST /api/admin/users/{id}/status", h.setUserStatus)
mux.HandleFunc("/api/", func(w http.ResponseWriter, r *http.Request) {
writeError(w, http.StatusNotFound, "not_found", "没有这个功能")
})
mux.Handle("/", h.spa())
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("X-Content-Type-Options", "nosniff")
w.Header().Set("Referrer-Policy", "same-origin")
w.Header().Set("X-Frame-Options", "DENY")
defer func() {
if rec := recover(); rec != nil {
h.log.Error("panic", "err", rec)
writeError(w, http.StatusInternalServerError, "internal", "出了点问题,请稍后再试")
}
}()
mux.ServeHTTP(w, r)
})
}
func (h *Handler) health(w http.ResponseWriter, _ *http.Request) {
writeJSON(w, http.StatusOK, map[string]any{"ok": true})
}
func (h *Handler) ready(w http.ResponseWriter, r *http.Request) {
if err := h.store.Ping(r.Context()); err != nil {
writeJSON(w, http.StatusServiceUnavailable, map[string]any{"ok": false})
return
}
writeJSON(w, http.StatusOK, map[string]any{"ok": true})
}
type publicUser struct {
ID int64 `json:"id"`
Username string `json:"username"`
Role string `json:"role"`
Enabled bool `json:"enabled"`
}
func toPublic(u store.User) publicUser {
return publicUser{ID: u.ID, Username: u.Username, Role: u.Role, Enabled: u.Enabled}
}
func (h *Handler) requireUser(w http.ResponseWriter, r *http.Request) (store.User, bool) {
if r.Method != http.MethodGet && r.Method != http.MethodHead {
if r.Header.Get(csrfHeader) != "1" {
writeError(w, http.StatusForbidden, "forbidden", "请从页面发起这个操作")
return store.User{}, false
}
}
c, err := r.Cookie(cookieName)
if err != nil || c.Value == "" {
writeError(w, http.StatusUnauthorized, "unauthorized", "请先登录")
return store.User{}, false
}
u, err := h.store.UserBySession(r.Context(), hashToken(c.Value), time.Now().UnixMilli())
if errors.Is(err, store.ErrForbidden) {
writeError(w, http.StatusForbidden, "forbidden", "账号已停用")
return store.User{}, false
}
if err != nil {
writeError(w, http.StatusUnauthorized, "unauthorized", "请先登录")
return store.User{}, false
}
return u, true
}
func (h *Handler) requireAdmin(w http.ResponseWriter, r *http.Request) (store.User, bool) {
u, ok := h.requireUser(w, r)
if !ok {
return store.User{}, false
}
if u.Role != "admin" {
writeError(w, http.StatusForbidden, "forbidden", "没有权限")
return store.User{}, false
}
return u, true
}
func (h *Handler) setSession(w http.ResponseWriter, r *http.Request, userID int64) error {
plain, hash, err := newToken()
if err != nil {
return err
}
exp := time.Now().Add(sessionTTL)
if err := h.store.CreateSession(r.Context(), userID, hash, exp.UnixMilli()); err != nil {
return err
}
http.SetCookie(w, &http.Cookie{
Name: cookieName,
Value: plain,
Path: "/",
HttpOnly: true,
SameSite: http.SameSiteLaxMode,
Secure: h.cookieSecure,
MaxAge: int(sessionTTL.Seconds()),
})
return nil
}
func (h *Handler) clearSession(w http.ResponseWriter, r *http.Request) {
if c, err := r.Cookie(cookieName); err == nil && c.Value != "" {
_ = h.store.DeleteSession(r.Context(), hashToken(c.Value))
}
http.SetCookie(w, &http.Cookie{
Name: cookieName,
Value: "",
Path: "/",
HttpOnly: true,
SameSite: http.SameSiteLaxMode,
Secure: h.cookieSecure,
MaxAge: -1,
})
}
func newToken() (plain, hash string, err error) {
buf := make([]byte, 32)
if _, err = rand.Read(buf); err != nil {
return "", "", err
}
plain = base64.RawURLEncoding.EncodeToString(buf)
return plain, hashToken(plain), nil
}
func hashToken(plain string) string {
sum := sha256.Sum256([]byte(plain))
return hex.EncodeToString(sum[:])
}
func decodeJSON(w http.ResponseWriter, r *http.Request, max int64, dest any) bool {
r.Body = http.MaxBytesReader(w, r.Body, max)
dec := json.NewDecoder(r.Body)
dec.DisallowUnknownFields()
if err := dec.Decode(dest); err != nil {
writeError(w, http.StatusBadRequest, "bad_request", "提交的内容不正确")
return false
}
if err := dec.Decode(&struct{}{}); !errors.Is(err, io.EOF) {
writeError(w, http.StatusBadRequest, "bad_request", "提交的内容不正确")
return false
}
return true
}
func writeOK(w http.ResponseWriter, data any) {
writeJSON(w, http.StatusOK, map[string]any{"ok": true, "data": data})
}
func writeError(w http.ResponseWriter, status int, code, message string) {
writeJSON(w, status, map[string]any{
"ok": false,
"error": map[string]string{
"code": code,
"message": message,
},
})
}
func writeJSON(w http.ResponseWriter, status int, v any) {
w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.Header().Set("Cache-Control", "no-store")
w.WriteHeader(status)
_ = json.NewEncoder(w).Encode(v)
}
func validUsername(s string) bool {
n := utf8.RuneCountInString(s)
if n < 2 || n > 32 {
return false
}
for _, r := range s {
if unicode.IsLetter(r) || unicode.IsDigit(r) || r == '_' || r == '-' {
continue
}
return false
}
return true
}
func validDisplayName(s string, max int) bool {
n := utf8.RuneCountInString(s)
if n < 1 || n > max {
return false
}
for _, r := range s {
if r < 0x20 || r == 0x7f {
return false
}
}
return true
}
func validEndpointID(s string) bool {
if len(s) < 1 || len(s) > 64 {
return false
}
for _, r := range s {
if (r >= 'a' && r <= 'z') || (r >= '0' && r <= '9') || r == '_' || r == '.' || r == '-' {
continue
}
return false
}
return true
}
func bearer(r *http.Request) string {
h := r.Header.Get("Authorization")
const prefix = "Bearer "
if len(h) <= len(prefix) || !strings.EqualFold(h[:len(prefix)], prefix) {
return ""
}
return strings.TrimSpace(h[len(prefix):])
}
func parseID(s string) (int64, bool) {
if s == "" {
return 0, false
}
var n int64
for _, r := range s {
if r < '0' || r > '9' {
return 0, false
}
n = n*10 + int64(r-'0')
if n < 0 {
return 0, false
}
}
if n == 0 {
return 0, false
}
return n, true
}