subscribe_push_gm.go 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. package sender
  2. import (
  3. "bytes"
  4. "context"
  5. "crypto/hmac"
  6. "crypto/sha256"
  7. "encoding/base64"
  8. "encoding/json"
  9. "fmt"
  10. "net/http"
  11. "net/url"
  12. "strconv"
  13. "strings"
  14. "time"
  15. )
  16. // LoadSubscribePushFromGM fetches one startup snapshot. GM verifies token as
  17. // HMAC-SHA256(base64) over JSON.stringify(body without token).
  18. func LoadSubscribePushFromGM(ctx context.Context, endpoint, secret string) error {
  19. endpoint = strings.TrimSpace(endpoint)
  20. parsed, err := url.Parse(endpoint)
  21. if err != nil || (parsed.Scheme != "http" && parsed.Scheme != "https") || parsed.Host == "" {
  22. return fmt.Errorf("GM_SUBSCRIBE_PUSH_URL must be an absolute HTTP URL")
  23. }
  24. if strings.TrimSpace(secret) == "" {
  25. return fmt.Errorf("GM_INTERNAL_SECRET is required")
  26. }
  27. mac := hmac.New(sha256.New, []byte(secret))
  28. _, _ = mac.Write([]byte("{}"))
  29. requestBody, err := json.Marshal(map[string]string{"token": base64.StdEncoding.EncodeToString(mac.Sum(nil))})
  30. if err != nil {
  31. return err
  32. }
  33. request, err := http.NewRequestWithContext(ctx, http.MethodPost, endpoint, bytes.NewReader(requestBody))
  34. if err != nil {
  35. return err
  36. }
  37. request.Header.Set("Content-Type", "application/json")
  38. client := &http.Client{Timeout: 10 * time.Second}
  39. response, err := client.Do(request)
  40. if err != nil {
  41. return fmt.Errorf("fetch SubscribePush from GM: %w", err)
  42. }
  43. defer response.Body.Close()
  44. if response.StatusCode != http.StatusOK {
  45. return fmt.Errorf("fetch SubscribePush from GM: HTTP %d", response.StatusCode)
  46. }
  47. var table map[string]SubscribePushRow
  48. if err := json.NewDecoder(response.Body).Decode(&table); err != nil {
  49. return fmt.Errorf("decode SubscribePush from GM: %w", err)
  50. }
  51. rows := make([]SubscribePushRow, 0, len(table))
  52. for key, row := range table {
  53. id, err := strconv.Atoi(key)
  54. if err != nil || id <= 0 || row.ID != id {
  55. return fmt.Errorf("SubscribePush row ID does not match table key %q", key)
  56. }
  57. rows = append(rows, row)
  58. }
  59. return ConfigureSubscribePush(rows)
  60. }