feat(push): Web Push — VAPID, подписки устройств и отправка (AGENT.md 7.16)

Уведомления в браузере и на телефоне: сервер сам решает, кому их слать, и
подписывает запрос VAPID-ключом, поэтому уведомление приходит, даже когда
клиент закрыт.

Сервер:
- миграция 00021: `push_subscriptions` (эндпоинт уникален, ключи, счётчик
  неудач, время последней доставки);
- `internal/push` — VAPID-ключи (приватный PKCS#8 из конфига, публичный
  выводится из него), правила уведомлений повторяют
  `web/src/lib/desktopNotifications.ts` (упоминания и личные беседы, без своих
  и системных сообщений), очередь доставки, TTL 12 часов, Topic по комнате;
- 404/410 от push-сервиса удаляют подписку сразу, 5 неудач подряд — тоже,
  иначе копились бы мёртвые эндпоинты; retention чистит «молчащие» подписки;
- `internal/httpx/safeurl.go` — общий запрет внутренних адресов с проверкой
  адреса в момент подключения (DNS rebinding): эндпоинт подписки приходит от
  клиента, и без проверки сервер сам себе организует SSRF;
- `internal/gateway/presence.go` — `IsUserOnline`: если получатель в клиенте,
  уведомление покажет клиент, дублировать на телефон не нужно;
- ручки `GET /push/config`, `GET|POST|DELETE /push/subscriptions`, лимиты
  10 подписок и 20 уведомлений в минуту; ключ p256dh проверяется как настоящая
  точка P-256;
- установщик генерирует `VAPID_PRIVATE_KEY` (openssl, PKCS#8 DER в base64) и
  `VAPID_SUBJECT`, ключ переиспользуется при переустановке; для ручной установки
  есть `glchat vapid-keys`; `features.web_push_enabled` виден в `/meta`.

Тесты: правила и VAPID, доставка с поддельным push-эндпоинтом (шифрование,
заголовки VAPID/TTL/Topic, очистка мёртвых подписок), ручки и лимиты, отправка
при личном сообщении и упоминании, пропуск онлайн-получателей, миграция на
чистой БД.
This commit is contained in:
2026-09-26 16:14:20 +03:00
parent f9464130cd
commit 7afd23d6d4
27 changed files with 3157 additions and 7 deletions
+3
View File
@@ -222,6 +222,9 @@ func (s *Server) registerMessageRoutes(api huma.API) {
} else {
s.dispatchChannelEvent(ctx, channelID, "MESSAGE_CREATE", payload)
}
// Web Push (Фаза 7): упоминания и личные беседы уходят на устройства
// тех, кто не в клиенте — тем же правилам, что у desktop-уведомлений.
s.notifyPushAboutMessage(ctx, message, channel, displayNameOf(user))
output := &messageOutput{}
output.Body.Message = payload
return output, nil
+255
View File
@@ -0,0 +1,255 @@
package server
import (
"context"
"crypto/ecdsa"
"crypto/elliptic"
"encoding/base64"
"net/http"
"strconv"
"strings"
"github.com/danielgtaylor/huma/v2"
"glchat/internal/httpx"
"glchat/internal/store"
)
// Web Push (AGENT.md 7.16, Фаза 7): подписка устройства, отписка и параметры
// для клиента. VAPID-ключ приватный живёт в конфиге инстанса, наружу уходит
// только публичный — он и нужен браузеру как `applicationServerKey`.
// Лимиты подписок: устройств на пользователя и длины полей от клиента.
const (
maxPushSubscriptionsPerUser = 10
maxPushEndpointLength = 1024
maxPushKeyLength = 128
maxPushUserAgentLength = 200
)
type pushConfigOutput struct {
Body struct {
Enabled bool `json:"enabled"`
PublicKey string `json:"public_key,omitempty"`
}
}
type pushSubscriptionPayload struct {
ID string `json:"id"`
Endpoint string `json:"endpoint"`
UserAgent string `json:"user_agent,omitempty"`
CreatedAt string `json:"created_at"`
}
type pushSubscriptionListOutput struct {
Body struct {
Subscriptions []pushSubscriptionPayload `json:"subscriptions"`
// Limit — сколько устройств можно подписать (для интерфейса).
Limit int `json:"limit"`
}
}
type pushOKOutput struct {
Body struct {
OK bool `json:"ok"`
}
}
// registerPushRoutes описывает ручки Web Push.
func (s *Server) registerPushRoutes(api huma.API) {
security := []map[string][]string{{"sessionCookie": {}}, {"bearerAuth": {}}}
huma.Register(api, huma.Operation{
OperationID: "getPushConfig",
Method: http.MethodGet,
Path: "/push/config",
Summary: "Параметры Web Push для клиента",
Tags: []string{"Push"},
Security: security,
}, func(ctx context.Context, _ *struct{}) (*pushConfigOutput, error) {
if _, _, err := requireUser(ctx); err != nil {
return nil, err
}
output := &pushConfigOutput{}
output.Body.Enabled = s.push.Enabled()
output.Body.PublicKey = s.push.PublicKey()
return output, nil
})
huma.Register(api, huma.Operation{
OperationID: "listPushSubscriptions",
Method: http.MethodGet,
Path: "/push/subscriptions",
Summary: "Подписки устройств текущего пользователя",
Tags: []string{"Push"},
Security: security,
}, func(ctx context.Context, _ *struct{}) (*pushSubscriptionListOutput, error) {
user, _, err := requireUser(ctx)
if err != nil {
return nil, err
}
subscriptions, err := s.store.ListPushSubscriptions(ctx, user.ID)
if err != nil {
return nil, humaError(err)
}
output := &pushSubscriptionListOutput{}
output.Body.Limit = maxPushSubscriptionsPerUser
output.Body.Subscriptions = make([]pushSubscriptionPayload, 0, len(subscriptions))
for i := range subscriptions {
output.Body.Subscriptions = append(output.Body.Subscriptions, pushSubscriptionPayload{
ID: formatSnowflake(subscriptions[i].ID),
Endpoint: subscriptions[i].Endpoint,
UserAgent: subscriptions[i].UserAgent,
CreatedAt: s.store.Timestamp(subscriptions[i].CreatedAt),
})
}
return output, nil
})
huma.Register(api, huma.Operation{
OperationID: "subscribePush",
Method: http.MethodPost,
Path: "/push/subscriptions",
Summary: "Подписать устройство на Web Push",
Tags: []string{"Push"},
Security: security,
}, func(ctx context.Context, input *struct {
UserAgent string `header:"User-Agent"`
Body struct {
Endpoint string `json:"endpoint" maxLength:"1024" minLength:"8"`
Keys struct {
P256dh string `json:"p256dh" maxLength:"128"`
Auth string `json:"auth" maxLength:"128"`
} `json:"keys"`
}
},
) (*pushOKOutput, error) {
user, _, err := requireUser(ctx)
if err != nil {
return nil, err
}
if !s.push.Enabled() {
return nil, humaErrorStatus(http.StatusServiceUnavailable, "push.disabled",
"web push is not configured on this instance")
}
if allowed, retryAfter := s.pushLimiter.Allow(pushLimitKey(user.ID)); !allowed {
return nil, rateLimitedError(retryAfter)
}
endpoint, err := validatePushEndpoint(input.Body.Endpoint)
if err != nil {
return nil, err
}
if err := validatePushKey("p256dh", input.Body.Keys.P256dh, 65); err != nil {
return nil, err
}
if err := validatePushKey("auth", input.Body.Keys.Auth, 16); err != nil {
return nil, err
}
count, err := s.store.CountPushSubscriptions(ctx, user.ID)
if err != nil {
return nil, humaError(err)
}
// Повторная подписка с того же устройства обновляет запись, поэтому
// лимит проверяем только для новой.
if count >= maxPushSubscriptionsPerUser {
existing, err := s.store.GetPushSubscriptionByEndpoint(ctx, endpoint)
if err != nil || existing.UserID != user.ID {
return nil, humaErrorStatus(http.StatusConflict, "push.too_many_subscriptions",
"too many subscribed devices")
}
}
if _, err := s.store.SavePushSubscription(ctx, store.SavePushSubscriptionParams{
UserID: user.ID,
Endpoint: endpoint,
P256dh: input.Body.Keys.P256dh,
Auth: input.Body.Keys.Auth,
UserAgent: truncate(input.UserAgent, maxPushUserAgentLength),
}); err != nil {
return nil, humaError(err)
}
output := &pushOKOutput{}
output.Body.OK = true
return output, nil
})
huma.Register(api, huma.Operation{
OperationID: "unsubscribePush",
Method: http.MethodDelete,
Path: "/push/subscriptions",
Summary: "Отписать устройство (или все) от Web Push",
Tags: []string{"Push"},
Security: security,
}, func(ctx context.Context, input *struct {
Endpoint string `query:"endpoint,omitempty" maxLength:"1024"`
},
) (*pushOKOutput, error) {
user, _, err := requireUser(ctx)
if err != nil {
return nil, err
}
endpoint := strings.TrimSpace(input.Endpoint)
if endpoint != "" {
if _, err := validatePushEndpoint(endpoint); err != nil {
return nil, err
}
}
if _, err := s.store.DeletePushSubscription(ctx, user.ID, endpoint); err != nil {
return nil, humaError(err)
}
output := &pushOKOutput{}
output.Body.OK = true
return output, nil
})
}
// validatePushEndpoint проверяет эндпоинт подписки: http не допускаем, а
// литеральный внутренний адрес отсекаем сразу — иначе сервер сам себе
// организует SSRF, отправляя подписанный VAPID-запрос во внутреннюю сеть.
func validatePushEndpoint(raw string) (string, error) {
trimmed := strings.TrimSpace(raw)
if trimmed == "" || len(trimmed) > maxPushEndpointLength {
return "", humaErrorStatus(http.StatusUnprocessableEntity, "push.invalid_endpoint",
"push endpoint is empty or too long")
}
if _, err := httpx.ValidatePublicURL(trimmed, false); err != nil {
return "", humaErrorStatus(http.StatusUnprocessableEntity, "push.invalid_endpoint",
"push endpoint must be a public https url")
}
return trimmed, nil
}
// validatePushKey проверяет ключ подписки: base64url, длину и — для p256dh —
// что это действительно точка P-256. Без второй проверки мусор от клиента
// доходил бы до шифрования и падал уже в очереди доставки.
func validatePushKey(name, value string, wantBytes int) error {
trimmed := strings.TrimSpace(value)
if trimmed == "" || len(trimmed) > maxPushKeyLength {
return humaErrorStatus(http.StatusUnprocessableEntity, "push.invalid_keys",
name+" key is missing or too long")
}
decoded, err := base64.RawURLEncoding.DecodeString(strings.TrimRight(trimmed, "="))
if err != nil || len(decoded) != wantBytes {
return humaErrorStatus(http.StatusUnprocessableEntity, "push.invalid_keys",
name+" key must be base64url of "+strconv.Itoa(wantBytes)+" bytes")
}
if name == "p256dh" {
if _, err := ecdsa.ParseUncompressedPublicKey(elliptic.P256(), decoded); err != nil {
return humaErrorStatus(http.StatusUnprocessableEntity, "push.invalid_keys",
"p256dh key is not a P-256 point")
}
}
return nil
}
// pushLimitKey — ключ лимита подписок: 10 запросов в минуту на пользователя.
func pushLimitKey(userID uint64) string { return "user:" + formatSnowflake(userID) }
// truncate обрезает пользовательский текст до лимита (User-Agent устройства).
func truncate(value string, limit int) string {
trimmed := strings.TrimSpace(value)
runes := []rune(trimmed)
if len(runes) <= limit {
return trimmed
}
return string(runes[:limit])
}
+354
View File
@@ -0,0 +1,354 @@
package server
import (
"context"
"crypto/ecdsa"
"crypto/elliptic"
"crypto/rand"
"crypto/x509"
"encoding/base64"
"fmt"
"log/slog"
"net/http"
"path/filepath"
"testing"
"time"
"glchat/internal/auth"
"glchat/internal/config"
"glchat/internal/database"
"glchat/internal/gateway"
"glchat/internal/httpx"
"glchat/internal/permissions"
"glchat/internal/source"
"glchat/internal/store"
)
// newPushTestServer поднимает тестовый сервер с настроенным VAPID-ключом:
// newTestServer из server_test.go о push ничего не знает, а ручки обязаны
// работать и с ключом, и без него.
func newPushTestServer(t *testing.T, withKeys bool) (*Server, *store.Store) {
t.Helper()
ctx := context.Background()
db, err := database.Open(ctx, database.Options{
Path: filepath.Join(t.TempDir(), "glchat.db"),
ReadPool: 2,
Migrate: true,
})
if err != nil {
t.Fatalf("open test database: %v", err)
}
t.Cleanup(func() {
if err := db.Close(); err != nil {
t.Errorf("close test database: %v", err)
}
})
cfg := config.Config{
DataDir: t.TempDir(),
Domain: "gl.mhspx.su",
WebRoot: filepath.Join("testdata", "web"),
FilesDomain: "files.gl.mhspx.su",
InstanceName: "glchat",
ListenAddr: "127.0.0.1:0",
Version: "v0.1.0-test",
Commit: "deadbee",
BuildDate: "2026-09-19T00:00:00Z",
MaxUploadSize: 26214400,
TLSEnabled: true,
SessionPepper: "test-pepper",
MasterKey: "00112233445566778899aabbccddeeff00112233445566778899aabbccddeeff",
Argon2MemoryKiB: 1024,
Argon2Iterations: 1,
Argon2Parallelism: 1,
LogLevel: "error",
LogFormat: "json",
}
if withKeys {
cfg.VAPIDPrivateKey = testVAPIDPrivateKey(t)
cfg.VAPIDSubject = "mailto:admin@gl.mhspx.su"
}
logger := slog.New(slog.DiscardHandler)
st := store.New(db)
authService, err := auth.New(context.Background(), cfg, st, logger)
if err != nil {
t.Fatalf("initialize authentication: %v", err)
}
calculator := permissions.NewCalculator(source.New(st))
gatewayService := gateway.New(st, authService, gateway.NewSnapshot(st, calculator), logger, cfg.AllowedOrigins())
return New(cfg, db, logger, Deps{
Store: st, Auth: authService, Gateway: gatewayService, Permissions: calculator,
}), st
}
func testVAPIDPrivateKey(t *testing.T) string {
t.Helper()
key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
if err != nil {
t.Fatalf("generate key: %v", err)
}
der, err := x509.MarshalPKCS8PrivateKey(key)
if err != nil {
t.Fatalf("marshal PKCS#8: %v", err)
}
return base64.StdEncoding.EncodeToString(der)
}
// testPushKeys возвращает корректные ключи подписки (65-байтовая точка P-256
// и 16 байт auth) в base64url — как их отдаёт PushSubscription.toJSON().
func testPushKeys(t *testing.T) (string, string) {
t.Helper()
key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
if err != nil {
t.Fatalf("generate subscription key: %v", err)
}
point, err := key.PublicKey.Bytes()
if err != nil {
t.Fatalf("public key bytes: %v", err)
}
auth := make([]byte, 16)
if _, err := rand.Read(auth); err != nil {
t.Fatalf("auth: %v", err)
}
return base64.RawURLEncoding.EncodeToString(point), base64.RawURLEncoding.EncodeToString(auth)
}
// testAuthKey — корректный auth-ключ подписки (16 байт).
func testAuthKey(t *testing.T) string {
t.Helper()
_, auth := testPushKeys(t)
return auth
}
func pushSubscribeBody(t *testing.T, endpoint string) string {
t.Helper()
p256dh, auth := testPushKeys(t)
return fmt.Sprintf(`{"endpoint":%q,"keys":{"p256dh":%q,"auth":%q}}`, endpoint, p256dh, auth)
}
func TestPushConfigDisabledWithoutKeys(t *testing.T) {
srv, _ := newPushTestServer(t, false)
cookie := registerAndLogin(t, srv, "push_off", "push-off@example.com")
rec := doJSON(t, srv, http.MethodGet, "/api/v1/push/config", "", cookie)
if rec.Code != http.StatusOK {
t.Fatalf("GET /push/config = %d, body = %s", rec.Code, rec.Body.String())
}
payload := decodeResponse[struct {
Enabled bool `json:"enabled"`
PublicKey string `json:"public_key"`
}](t, rec)
if payload.Enabled || payload.PublicKey != "" {
t.Fatalf("без ключей push должен быть выключен: %+v", payload)
}
// Подписка на инстансе без ключей — честная ошибка, а не молчаливый успех.
rec = doJSON(t, srv, http.MethodPost, "/api/v1/push/subscriptions",
pushSubscribeBody(t, "https://fcm.googleapis.com/fcm/send/disabled"), cookie)
if rec.Code != http.StatusServiceUnavailable {
t.Fatalf("подписка без ключей = %d, ожидалось 503", rec.Code)
}
if code := errorCodeOf(t, rec); code != "push.disabled" {
t.Fatalf("код ошибки = %q, ожидался push.disabled", code)
}
}
func TestPushSubscribeFlow(t *testing.T) {
srv, st := newPushTestServer(t, true)
cookie := registerAndLogin(t, srv, "push_on", "push-on@example.com")
user, err := srv.auth.UserByEmail(t.Context(), "push-on@example.com")
if err != nil {
t.Fatalf("UserByEmail: %v", err)
}
config := decodeResponse[struct {
Enabled bool `json:"enabled"`
PublicKey string `json:"public_key"`
}](t, doJSON(t, srv, http.MethodGet, "/api/v1/push/config", "", cookie))
if !config.Enabled || config.PublicKey == "" {
t.Fatalf("push должен быть включён: %+v", config)
}
decoded, err := base64.RawURLEncoding.DecodeString(config.PublicKey)
if err != nil || len(decoded) != 65 {
t.Fatalf("публичный ключ не годится для applicationServerKey: %v", err)
}
endpoint := "https://fcm.googleapis.com/fcm/send/device-one"
rec := doJSON(t, srv, http.MethodPost, "/api/v1/push/subscriptions",
pushSubscribeBody(t, endpoint), cookie)
if rec.Code != http.StatusOK {
t.Fatalf("подписка = %d, body = %s", rec.Code, rec.Body.String())
}
subscriptions, err := st.ListPushSubscriptions(t.Context(), user.ID)
if err != nil || len(subscriptions) != 1 {
t.Fatalf("подписок в базе %d (%v), ожидалась 1", len(subscriptions), err)
}
if subscriptions[0].Endpoint != endpoint {
t.Fatalf("эндпоинт = %q", subscriptions[0].Endpoint)
}
// Список для интерфейса отдаёт устройства и лимит.
list := decodeResponse[struct {
Subscriptions []struct {
ID string `json:"id"`
Endpoint string `json:"endpoint"`
} `json:"subscriptions"`
Limit int `json:"limit"`
}](t, doJSON(t, srv, http.MethodGet, "/api/v1/push/subscriptions", "", cookie))
if len(list.Subscriptions) != 1 || list.Limit != maxPushSubscriptionsPerUser {
t.Fatalf("неожиданный список подписок: %+v", list)
}
// Отписка устройства.
rec = doJSON(t, srv, http.MethodDelete,
"/api/v1/push/subscriptions?endpoint="+endpoint, "", cookie)
if rec.Code != http.StatusOK {
t.Fatalf("отписка = %d, body = %s", rec.Code, rec.Body.String())
}
if count, err := st.CountPushSubscriptions(t.Context(), user.ID); err != nil || count != 0 {
t.Fatalf("после отписки подписок %d (%v)", count, err)
}
}
func TestPushSubscribeValidation(t *testing.T) {
srv, _ := newPushTestServer(t, true)
cookie := registerAndLogin(t, srv, "push_bad", "push-bad@example.com")
cases := []struct {
name string
body string
code string
}{
{
name: "http вместо https",
body: pushSubscribeBody(t, "http://fcm.googleapis.com/fcm/send/x"),
code: "push.invalid_endpoint",
},
{
name: "внутренний адрес",
body: pushSubscribeBody(t, "https://10.0.0.5/push"),
code: "push.invalid_endpoint",
},
{
name: "метаданные облака",
body: pushSubscribeBody(t, "https://169.254.169.254/latest/meta-data"),
code: "push.invalid_endpoint",
},
{
name: "loopback",
body: pushSubscribeBody(t, "https://127.0.0.1:8443/push"),
code: "push.invalid_endpoint",
},
{
name: "p256dh не точка кривой",
body: fmt.Sprintf(`{"endpoint":"https://fcm.googleapis.com/fcm/send/x","keys":{"p256dh":%q,"auth":%q}}`,
base64.RawURLEncoding.EncodeToString(make([]byte, 65)), testAuthKey(t)),
code: "push.invalid_keys",
},
{
name: "битый ключ шифрования",
body: `{"endpoint":"https://fcm.googleapis.com/fcm/send/x","keys":{"p256dh":"AAAA","auth":"AAAA"}}`,
code: "push.invalid_keys",
},
{
name: "пустой ключ",
body: `{"endpoint":"https://fcm.googleapis.com/fcm/send/x","keys":{"p256dh":"","auth":""}}`,
code: "push.invalid_keys",
},
}
for _, testCase := range cases {
t.Run(testCase.name, func(t *testing.T) {
rec := doJSON(t, srv, http.MethodPost, "/api/v1/push/subscriptions", testCase.body, cookie)
if rec.Code != http.StatusUnprocessableEntity {
t.Fatalf("код ответа = %d, ожидался 422 (body = %s)", rec.Code, rec.Body.String())
}
if code := errorCodeOf(t, rec); code != testCase.code {
t.Fatalf("код ошибки = %q, ожидался %q", code, testCase.code)
}
})
}
}
func TestPushSubscribeLimit(t *testing.T) {
srv, _ := newPushTestServer(t, true)
cookie := registerAndLogin(t, srv, "push_limit", "push-limit@example.com")
// Лимит частоты проверяется отдельно: здесь важно дойти до предела
// устройств на пользователя.
srv.pushLimiter = httpx.NewRateLimiterWindow(100, time.Minute, 100)
for i := 0; i < maxPushSubscriptionsPerUser; i++ {
endpoint := fmt.Sprintf("https://fcm.googleapis.com/fcm/send/device-%d", i)
rec := doJSON(t, srv, http.MethodPost, "/api/v1/push/subscriptions",
pushSubscribeBody(t, endpoint), cookie)
if rec.Code != http.StatusOK {
t.Fatalf("подписка %d = %d, body = %s", i, rec.Code, rec.Body.String())
}
}
rec := doJSON(t, srv, http.MethodPost, "/api/v1/push/subscriptions",
pushSubscribeBody(t, "https://fcm.googleapis.com/fcm/send/device-over-limit"), cookie)
if rec.Code != http.StatusConflict {
t.Fatalf("подписка сверх лимита = %d, ожидалось 409 (body = %s)", rec.Code, rec.Body.String())
}
if code := errorCodeOf(t, rec); code != "push.too_many_subscriptions" {
t.Fatalf("код ошибки = %q", code)
}
}
// Подписки ограничены и по частоте: перебор устройств не должен превращаться
// в поток запросов (AGENT.md 8.6).
func TestPushSubscribeRateLimited(t *testing.T) {
srv, _ := newPushTestServer(t, true)
cookie := registerAndLogin(t, srv, "push_flood", "push-flood@example.com")
var limited bool
for i := 0; i < 40; i++ {
endpoint := fmt.Sprintf("https://fcm.googleapis.com/fcm/send/flood-%d", i)
rec := doJSON(t, srv, http.MethodPost, "/api/v1/push/subscriptions",
pushSubscribeBody(t, endpoint), cookie)
if rec.Code == http.StatusTooManyRequests {
limited = true
break
}
}
if !limited {
t.Fatal("лимит частоты подписок не сработал")
}
}
func TestPushRoutesRequireSession(t *testing.T) {
srv, _ := newPushTestServer(t, true)
body := pushSubscribeBody(t, "https://fcm.googleapis.com/fcm/send/no-session")
for _, request := range []struct {
method string
path string
body string
}{
{http.MethodGet, "/api/v1/push/config", ""},
{http.MethodGet, "/api/v1/push/subscriptions", ""},
{http.MethodPost, "/api/v1/push/subscriptions", body},
{http.MethodDelete, "/api/v1/push/subscriptions", ""},
} {
rec := doJSON(t, srv, request.method, request.path, request.body)
if rec.Code != http.StatusUnauthorized {
t.Errorf("%s %s без сессии = %d, ожидалось 401", request.method, request.path, rec.Code)
}
}
}
// Публичный ключ в /meta виден до входа: клиент решает, показывать ли раздел.
func TestMetaExposesWebPushFlag(t *testing.T) {
srv, _ := newPushTestServer(t, true)
rec := doJSON(t, srv, http.MethodGet, "/api/v1/meta", "")
if rec.Code != http.StatusOK {
t.Fatalf("GET /meta = %d", rec.Code)
}
payload := decodeResponse[struct {
Features struct {
WebPushEnabled bool `json:"web_push_enabled"`
} `json:"features"`
}](t, rec)
if !payload.Features.WebPushEnabled {
t.Fatal("meta не сообщает о включённом Web Push")
}
}
+128
View File
@@ -0,0 +1,128 @@
package server
import (
"context"
"log/slog"
"glchat/internal/push"
"glchat/internal/store"
)
// Web Push о новых сообщениях (AGENT.md 7.16, Фаза 7).
//
// Правила те же, что у нативных уведомлений desktop-обёртки
// (web/src/lib/desktopNotifications.ts): упоминания и личные беседы, без своих
// и системных сообщений. Отличие одно: сервер не знает про фокус окна, поэтому
// вместо «комната открыта и окно активно» проверяется наличие соединения
// шлюза — если пользователь в приложении, уведомление покажет клиент.
// pushSender — то, что серверу нужно от Web Push. Интерфейс позволяет
// подменить отправителя в тестах: доставка идёт в фоне и наружу не видна.
type pushSender interface {
Enabled() bool
PublicKey() string
Enqueue(subscription store.PushSubscription, payload push.Payload) bool
}
// displayNameOf — имя автора для уведомления: display_name, а при пустом —
// логин (у новых аккаунтов display_name заполняется логином, но вебхуки и
// ручные данные могут его не иметь).
func displayNameOf(user *store.User) string {
if user == nil {
return ""
}
if user.DisplayName != "" {
return user.DisplayName
}
return user.Username
}
// notifyPushAboutMessage ставит уведомления в очередь push-сервиса.
//
// authorName — отображаемое имя автора: в личной беседе 1:1 оно и есть имя
// «комнаты» (отдельного названия у неё нет).
func (s *Server) notifyPushAboutMessage(ctx context.Context, message *store.Message, channel *store.Channel, authorName string) {
if !s.push.Enabled() || channel == nil {
return
}
recipients := s.pushRecipients(ctx, message, channel)
if len(recipients) == 0 {
return
}
authorID := uint64(0)
if message.AuthorID != nil {
authorID = *message.AuthorID
}
guildID := uint64(0)
guildName := ""
if channel.GuildID != nil {
guildID = *channel.GuildID
if guild, err := s.store.GetGuild(ctx, guildID); err == nil {
guildName = guild.Name
}
}
channelName := s.pushChannelName(channel, authorName)
for _, recipient := range recipients {
if recipient == 0 || recipient == authorID {
continue
}
// Получатель в приложении: уведомление покажет клиент, а не телефон.
if s.gateway.IsUserOnline(recipient) {
continue
}
// Лимит на получателя: массовые упоминания не должны превращаться в
// поток push-сообщений (AGENT.md 8.6).
if allowed, _ := s.pushNotifyLimiter.Allow(pushLimitKey(recipient)); !allowed {
continue
}
payload := push.NotificationFor(push.NotificationInput{
MessageType: message.Type,
Content: message.Content,
Mentions: message.Mentions,
AuthorID: authorID,
MeID: recipient,
IsDirect: channel.GuildID == nil,
ChannelName: channelName,
ChannelID: message.ChannelID,
MessageID: message.ID,
GuildID: guildID,
GuildName: guildName,
AuthorName: authorName,
})
if payload == nil {
continue
}
subscriptions, err := s.store.ListPushSubscriptions(ctx, recipient)
if err != nil {
s.logger.WarnContext(ctx, "push subscriptions read failed", slog.Any("error", err))
continue
}
for i := range subscriptions {
s.push.Enqueue(subscriptions[i], *payload)
}
}
}
// pushRecipients перечисляет, кому адресовано уведомление: в комнате сервера —
// упомянутым, в личной беседе — всем остальным участникам.
func (s *Server) pushRecipients(ctx context.Context, message *store.Message, channel *store.Channel) []uint64 {
if channel.GuildID != nil {
return message.Mentions
}
participants, err := s.store.DMParticipants(ctx, channel.ID)
if err != nil {
s.logger.WarnContext(ctx, "dm participants read failed", slog.Any("error", err))
return nil
}
return participants
}
// pushChannelName подбирает название для заголовка уведомления: у групповой
// беседы — её имя, у 1:1 своего имени нет, поэтому берём имя собеседника
// (автора сообщения).
func (s *Server) pushChannelName(channel *store.Channel, authorName string) string {
if channel.GuildID == nil && channel.DMOwnerID == nil {
return authorName
}
return channel.Name
}
+221
View File
@@ -0,0 +1,221 @@
package server
import (
"context"
"net/http"
"net/http/httptest"
"strings"
"testing"
"glchat/internal/push"
"glchat/internal/store"
)
// recordingPush — подмена отправителя: запоминает, что сервер поставил в
// очередь. Реальная доставка идёт в фоне и в тесте не наблюдаема.
type recordingPush struct {
enabled bool
publicKey string
jobs []recordedPush
}
type recordedPush struct {
subscription store.PushSubscription
payload push.Payload
}
func (r *recordingPush) Enabled() bool { return r.enabled }
func (r *recordingPush) PublicKey() string { return r.publicKey }
func (r *recordingPush) Enqueue(subscription store.PushSubscription, payload push.Payload) bool {
r.jobs = append(r.jobs, recordedPush{subscription: subscription, payload: payload})
return true
}
// createTestDM открывает личную беседу между автором и указанным участником
// и возвращает идентификатор комнаты.
func createTestDM(t *testing.T, srv *Server, cookie *http.Cookie, userID string) string {
t.Helper()
rec := doJSON(t, srv, http.MethodPost, "/api/v1/users/@me/channels",
`{"recipient_id":"`+userID+`"}`, cookie)
if rec.Code != http.StatusOK {
t.Fatalf("открыть личную беседу = %d, body = %s", rec.Code, rec.Body.String())
}
payload := decodeResponse[struct {
Channel struct {
ID string `json:"id"`
} `json:"channel"`
}](t, rec)
if payload.Channel.ID == "" {
t.Fatalf("беседа без идентификатора: %s", rec.Body.String())
}
return payload.Channel.ID
}
// savePushSubscription заводит подписку устройства напрямую в БД.
func savePushSubscription(t *testing.T, st *store.Store, userID uint64, endpoint string) store.PushSubscription {
t.Helper()
subscription, err := st.SavePushSubscription(context.Background(), store.SavePushSubscriptionParams{
UserID: userID,
Endpoint: endpoint,
P256dh: "p256dh",
Auth: "auth",
})
if err != nil {
t.Fatalf("save subscription: %v", err)
}
return *subscription
}
// TestPushNotifiesDirectMessage: личное сообщение уходит на устройство
// получателя, если он не в клиенте (AGENT.md 7.16, Фаза 7).
func TestPushNotifiesDirectMessage(t *testing.T) {
srv, st := newPushTestServer(t, true)
recorder := &recordingPush{enabled: true, publicKey: "key"}
srv.push = recorder
authorCookie := registerAndLogin(t, srv, "push_author", "push-author@example.com")
registerAndLogin(t, srv, "push_target", "push-target@example.com")
targetID := mustUserID(t, srv, "push-target@example.com")
savePushSubscription(t, st, targetID, "https://fcm.googleapis.com/fcm/send/target")
channelID := createTestDM(t, srv, authorCookie, formatSnowflake(targetID))
rec := doJSON(t, srv, http.MethodPost, "/api/v1/channels/"+channelID+"/messages",
`{"content":"привет, это личное"}`, authorCookie)
if rec.Code != http.StatusOK {
t.Fatalf("отправка сообщения = %d, body = %s", rec.Code, rec.Body.String())
}
if len(recorder.jobs) != 1 {
t.Fatalf("поставлено уведомлений %d, ожидалось 1", len(recorder.jobs))
}
job := recorder.jobs[0]
if job.payload.Kind != "direct" || job.payload.Body != "привет, это личное" {
t.Fatalf("неожиданное уведомление: %+v", job.payload)
}
if job.payload.ChannelID != channelID {
t.Fatalf("комната уведомления %q, ожидалась %q", job.payload.ChannelID, channelID)
}
if job.payload.URL != "/app/friends/"+channelID {
t.Fatalf("ссылка = %q", job.payload.URL)
}
if job.subscription.Endpoint != "https://fcm.googleapis.com/fcm/send/target" {
t.Fatalf("подписка = %q", job.subscription.Endpoint)
}
}
// TestPushNotifiesMention: упоминание в комнате сервера уходит получателю;
// обычное сообщение — нет.
func TestPushNotifiesMention(t *testing.T) {
fixture := newMessagingFixture(t)
recorder := &recordingPush{enabled: true, publicKey: "key"}
fixture.srv.push = recorder
savePushSubscription(t, fixture.srv.store, guildIDOf(t, fixture.memberID), "https://fcm.googleapis.com/fcm/send/member")
// Обычное сообщение: упоминаний нет — push не нужен.
rec := doJSON(t, fixture.srv, http.MethodPost, "/api/v1/channels/"+fixture.openChannel+"/messages",
`{"content":"просто сообщение"}`, fixture.ownerCookie)
if rec.Code != http.StatusOK {
t.Fatalf("отправка сообщения = %d, body = %s", rec.Code, rec.Body.String())
}
if len(recorder.jobs) != 0 {
t.Fatalf("без упоминания поставлено уведомлений %d", len(recorder.jobs))
}
// Упоминание: уведомление уходит со ссылкой на комнату сервера.
rec = doJSON(t, fixture.srv, http.MethodPost, "/api/v1/channels/"+fixture.openChannel+"/messages",
`{"content":"<@`+fixture.memberID+`> посмотри"}`, fixture.ownerCookie)
if rec.Code != http.StatusOK {
t.Fatalf("отправка упоминания = %d, body = %s", rec.Code, rec.Body.String())
}
if len(recorder.jobs) != 1 {
t.Fatalf("поставлено уведомлений %d, ожидалось 1", len(recorder.jobs))
}
payload := recorder.jobs[0].payload
if payload.Kind != "mention" {
t.Fatalf("вид уведомления = %q", payload.Kind)
}
if !strings.Contains(payload.Body, "посмотри") {
t.Fatalf("тело уведомления = %q", payload.Body)
}
if payload.ChannelID != fixture.openChannel {
t.Fatalf("комната уведомления %q, ожидалась %q", payload.ChannelID, fixture.openChannel)
}
if payload.URL != "/app/"+fixture.guildID+"/"+fixture.openChannel {
t.Fatalf("ссылка = %q", payload.URL)
}
if payload.Title == "" || !strings.Contains(payload.Title, "#") {
t.Fatalf("заголовок уведомления = %q", payload.Title)
}
}
// TestPushSkipsOwnMessages: свои сообщения уведомлений не порождают — как в
// desktopNotifications.ts.
func TestPushSkipsOwnMessages(t *testing.T) {
srv, st := newPushTestServer(t, true)
recorder := &recordingPush{enabled: true, publicKey: "key"}
srv.push = recorder
cookie := registerAndLogin(t, srv, "push_self", "push-self@example.com")
selfID := mustUserID(t, srv, "push-self@example.com")
savePushSubscription(t, st, selfID, "https://fcm.googleapis.com/fcm/send/self")
otherCookie := registerAndLogin(t, srv, "push_other", "push-other@example.com")
otherID := mustUserID(t, srv, "push-other@example.com")
channelID := createTestDM(t, srv, cookie, formatSnowflake(otherID))
// Отправляем другому, но получатель — тоже автор? Нет: подписка только у
// автора, а сообщение уходит второму участнику — уведомлений быть не должно.
rec := doJSON(t, srv, http.MethodPost, "/api/v1/channels/"+channelID+"/messages",
`{"content":"<@`+formatSnowflake(selfID)+`> себе"}`, cookie)
if rec.Code != http.StatusOK {
t.Fatalf("отправка = %d, body = %s", rec.Code, rec.Body.String())
}
if len(recorder.jobs) != 0 {
t.Fatalf("своё сообщение дало уведомления: %+v", recorder.jobs)
}
_ = otherCookie
}
// TestPushSkipsOnlineUsers: если получатель в клиенте (есть соединение шлюза),
// уведомление покажет сам клиент — push не отправляем.
func TestPushSkipsOnlineUsers(t *testing.T) {
srv, st := newPushTestServer(t, true)
recorder := &recordingPush{enabled: true, publicKey: "key"}
srv.push = recorder
authorCookie := registerAndLogin(t, srv, "push_online_author", "push-online-author@example.com")
targetCookie := registerAndLogin(t, srv, "push_online_target", "push-online-target@example.com")
targetID := mustUserID(t, srv, "push-online-target@example.com")
savePushSubscription(t, st, targetID, "https://fcm.googleapis.com/fcm/send/online")
channelID := createTestDM(t, srv, authorCookie, formatSnowflake(targetID))
// Настоящее соединение шлюза за получателя: он «в клиенте».
httpServer := httptest.NewServer(srv.Handler())
t.Cleanup(httpServer.Close)
dialGateway(t, httpServer, targetCookie)
rec := doJSON(t, srv, http.MethodPost, "/api/v1/channels/"+channelID+"/messages",
`{"content":"он в клиенте"}`, authorCookie)
if rec.Code != http.StatusOK {
t.Fatalf("отправка = %d, body = %s", rec.Code, rec.Body.String())
}
if len(recorder.jobs) != 0 {
t.Fatalf("пользователю в клиенте отправлен push: %+v", recorder.jobs)
}
}
// TestPushSkippedWhenDisabled: без VAPID-ключа сервер не трогает подписки.
func TestPushSkippedWhenDisabled(t *testing.T) {
fixture := newMessagingFixture(t)
recorder := &recordingPush{enabled: false}
fixture.srv.push = recorder
savePushSubscription(t, fixture.srv.store, guildIDOf(t, fixture.memberID), "https://fcm.googleapis.com/fcm/send/off")
rec := doJSON(t, fixture.srv, http.MethodPost, "/api/v1/channels/"+fixture.openChannel+"/messages",
`{"content":"<@`+fixture.memberID+`> привет"}`, fixture.ownerCookie)
if rec.Code != http.StatusOK {
t.Fatalf("отправка = %d, body = %s", rec.Code, rec.Body.String())
}
if len(recorder.jobs) != 0 {
t.Fatalf("выключенный push всё равно отправил: %+v", recorder.jobs)
}
}
+25 -3
View File
@@ -20,6 +20,7 @@ import (
"glchat/internal/httpx"
"glchat/internal/meta"
"glchat/internal/permissions"
"glchat/internal/push"
"glchat/internal/source"
"glchat/internal/store"
"glchat/internal/sysinfo"
@@ -71,6 +72,12 @@ type Server struct {
// 10 запросов в минуту на IP — с запасом на пару begin/finish.
passkeyLimiter *httpx.RateLimiter
oauthLimiter *httpx.RateLimiter
// pushLimiter ограничивает подписки на Web Push, pushNotifyLimiter — сами
// уведомления на получателя (Фаза 7, AGENT.md 7.16, 8.6).
pushLimiter *httpx.RateLimiter
pushNotifyLimiter *httpx.RateLimiter
// push отправляет Web Push; nil, если ключи не настроены.
push pushSender
// slowmode — время последней отправки в комнату для режима медленной
// отправки; словарь ограничен по размеру (AGENT.md 7.5).
slowmodeMu sync.Mutex
@@ -130,9 +137,13 @@ func New(cfg config.Config, db *database.DB, logger *slog.Logger, deps Deps) *Se
reactionLimiter: httpx.NewRateLimiter(20, 20),
passkeyLimiter: httpx.NewRateLimiterWindow(10, time.Minute, 10),
oauthLimiter: httpx.NewRateLimiterWindow(10, time.Minute, 10),
slowmode: map[string]time.Time{},
presence: map[uint64]time.Time{},
webhookSeen: map[string]time.Time{},
pushLimiter: httpx.NewRateLimiterWindow(10, time.Minute, 10),
// Уведомления на получателя: 20 в минуту с запасом 20 — массовые
// упоминания не должны заваливать устройство.
pushNotifyLimiter: httpx.NewRateLimiter(20, 20),
slowmode: map[string]time.Time{},
presence: map[uint64]time.Time{},
webhookSeen: map[string]time.Time{},
// Дашборд опрашивает метрики раз в секунду: 120/мин с запасом.
metricsLimiter: httpx.NewRateLimiter(120, 30),
sysinfoPaths: sysinfo.DefaultPaths(),
@@ -147,6 +158,16 @@ func New(cfg config.Config, db *database.DB, logger *slog.Logger, deps Deps) *Se
case deps.Store != nil:
s.perms = permissions.NewCalculator(source.New(deps.Store))
}
// Web Push (Фаза 7): неверный VAPID-ключ не должен мешать инстансу
// подняться — пишем предупреждение и работаем без push.
if deps.Store != nil {
sender, err := push.New(cfg, deps.Store, logger)
if err != nil {
logger.Error("web push is disabled", slog.Any("error", err))
} else {
s.push = sender
}
}
router := chi.NewRouter()
router.Route("/api/v1", func(apiRouter chi.Router) {
@@ -182,6 +203,7 @@ func New(cfg config.Config, db *database.DB, logger *slog.Logger, deps Deps) *Se
s.registerChannelBackgroundRoutes(apiRouter)
s.registerInviteBackgroundRoutes(apiRouter)
s.registerVoiceWebhook(apiRouter)
s.registerPushRoutes(s.api)
}
apiRouter.Get("/openapi.json", s.handleOpenAPI)
})