| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364 |
- package sender
- import (
- "bytes"
- "context"
- "crypto/hmac"
- "crypto/sha256"
- "encoding/base64"
- "encoding/json"
- "fmt"
- "net/http"
- "net/url"
- "strconv"
- "strings"
- "time"
- )
- // LoadSubscribePushFromGM fetches one startup snapshot. GM verifies token as
- // HMAC-SHA256(base64) over JSON.stringify(body without token).
- func LoadSubscribePushFromGM(ctx context.Context, endpoint, secret string) error {
- endpoint = strings.TrimSpace(endpoint)
- parsed, err := url.Parse(endpoint)
- if err != nil || (parsed.Scheme != "http" && parsed.Scheme != "https") || parsed.Host == "" {
- return fmt.Errorf("GM_SUBSCRIBE_PUSH_URL must be an absolute HTTP URL")
- }
- if strings.TrimSpace(secret) == "" {
- return fmt.Errorf("GM_INTERNAL_SECRET is required")
- }
- mac := hmac.New(sha256.New, []byte(secret))
- _, _ = mac.Write([]byte("{}"))
- requestBody, err := json.Marshal(map[string]string{"token": base64.StdEncoding.EncodeToString(mac.Sum(nil))})
- if err != nil {
- return err
- }
- request, err := http.NewRequestWithContext(ctx, http.MethodPost, endpoint, bytes.NewReader(requestBody))
- if err != nil {
- return err
- }
- request.Header.Set("Content-Type", "application/json")
- client := &http.Client{Timeout: 10 * time.Second}
- response, err := client.Do(request)
- if err != nil {
- return fmt.Errorf("fetch SubscribePush from GM: %w", err)
- }
- defer response.Body.Close()
- if response.StatusCode != http.StatusOK {
- return fmt.Errorf("fetch SubscribePush from GM: HTTP %d", response.StatusCode)
- }
- var table map[string]SubscribePushRow
- if err := json.NewDecoder(response.Body).Decode(&table); err != nil {
- return fmt.Errorf("decode SubscribePush from GM: %w", err)
- }
- rows := make([]SubscribePushRow, 0, len(table))
- for key, row := range table {
- id, err := strconv.Atoi(key)
- if err != nil || id <= 0 || row.ID != id {
- return fmt.Errorf("SubscribePush row ID does not match table key %q", key)
- }
- rows = append(rows, row)
- }
- return ConfigureSubscribePush(rows)
- }
|