GHL Marketplace submission blockers resolved: - Add POST /api/ghl/v1/webhook/uninstall to delete token on app removal - Add in-memory messageId deduplication (10-min TTL) to prevent duplicate SMS sends on webhook retries - Handle ?error= param in OAuth callback for user-denied auth flows - Pass store to WebhookHandler; update tests accordingly Co-Authored-By: Paperclip <noreply@paperclip.ing>
216 lines
6.1 KiB
Go
216 lines
6.1 KiB
Go
package ghl
|
|
|
|
import (
|
|
"context"
|
|
"crypto/ecdsa"
|
|
"crypto/sha256"
|
|
"crypto/x509"
|
|
"encoding/base64"
|
|
"encoding/json"
|
|
"encoding/pem"
|
|
"fmt"
|
|
"io"
|
|
"log/slog"
|
|
"net/http"
|
|
"sync"
|
|
"time"
|
|
|
|
castclient "git.sds.dev/CAST/cast-ghl-plugin/internal/cast"
|
|
"git.sds.dev/CAST/cast-ghl-plugin/internal/phone"
|
|
)
|
|
|
|
const seenMessageTTL = 10 * time.Minute
|
|
|
|
type seenEntry struct {
|
|
at time.Time
|
|
}
|
|
|
|
type WebhookHandler struct {
|
|
webhookPubKey *ecdsa.PublicKey
|
|
castClient *castclient.Client
|
|
ghlAPI *APIClient
|
|
oauthHandler *OAuthHandler
|
|
store TokenStore
|
|
seenMu sync.Mutex
|
|
seenMessages map[string]seenEntry
|
|
}
|
|
|
|
func NewWebhookHandler(pubKeyPEM string, castClient *castclient.Client, ghlAPI *APIClient, oauth *OAuthHandler, store TokenStore) (*WebhookHandler, error) {
|
|
key, err := parseECDSAPublicKey(pubKeyPEM)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("failed to parse webhook public key: %w", err)
|
|
}
|
|
return &WebhookHandler{
|
|
webhookPubKey: key,
|
|
castClient: castClient,
|
|
ghlAPI: ghlAPI,
|
|
oauthHandler: oauth,
|
|
store: store,
|
|
seenMessages: make(map[string]seenEntry),
|
|
}, nil
|
|
}
|
|
|
|
// markSeen returns true if messageID was already seen within seenMessageTTL (duplicate).
|
|
// Otherwise records it and returns false.
|
|
func (h *WebhookHandler) markSeen(messageID string) bool {
|
|
h.seenMu.Lock()
|
|
defer h.seenMu.Unlock()
|
|
|
|
now := time.Now()
|
|
// Evict expired entries on every call to avoid unbounded growth.
|
|
for id, e := range h.seenMessages {
|
|
if now.Sub(e.at) > seenMessageTTL {
|
|
delete(h.seenMessages, id)
|
|
}
|
|
}
|
|
|
|
if _, exists := h.seenMessages[messageID]; exists {
|
|
return true
|
|
}
|
|
h.seenMessages[messageID] = seenEntry{at: now}
|
|
return false
|
|
}
|
|
|
|
func (h *WebhookHandler) HandleWebhook(w http.ResponseWriter, r *http.Request) {
|
|
sigHeader := r.Header.Get("x-wh-signature")
|
|
|
|
body, err := io.ReadAll(r.Body)
|
|
if err != nil {
|
|
slog.Error("webhook: failed to read body", "err", err)
|
|
http.Error(w, "failed to read request body", http.StatusInternalServerError)
|
|
return
|
|
}
|
|
|
|
if !h.verifySignature(body, sigHeader) {
|
|
slog.Warn("webhook: invalid signature")
|
|
http.Error(w, "invalid webhook signature", http.StatusUnauthorized)
|
|
return
|
|
}
|
|
|
|
var webhook OutboundMessageWebhook
|
|
if err := json.Unmarshal(body, &webhook); err != nil {
|
|
slog.Error("webhook: failed to parse payload", "err", err)
|
|
http.Error(w, "invalid payload", http.StatusBadRequest)
|
|
return
|
|
}
|
|
|
|
if webhook.Type != "SMS" {
|
|
slog.Debug("webhook: ignoring non-SMS webhook", "type", webhook.Type)
|
|
w.WriteHeader(http.StatusOK)
|
|
return
|
|
}
|
|
|
|
if h.markSeen(webhook.MessageID) {
|
|
slog.Warn("webhook: duplicate messageId ignored", "message_id", webhook.MessageID)
|
|
w.WriteHeader(http.StatusOK)
|
|
return
|
|
}
|
|
|
|
slog.Info("webhook: received outbound SMS", "message_id", webhook.MessageID, "location_id", webhook.LocationID)
|
|
w.WriteHeader(http.StatusOK)
|
|
|
|
go h.processOutbound(webhook)
|
|
}
|
|
|
|
func (h *WebhookHandler) processOutbound(webhook OutboundMessageWebhook) {
|
|
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
|
|
defer cancel()
|
|
|
|
localPhone, err := phone.ToLocal(webhook.Phone)
|
|
if err != nil {
|
|
slog.Error("webhook: phone normalization failed", "phone", webhook.Phone, "err", err)
|
|
h.updateStatus(ctx, webhook, "failed")
|
|
return
|
|
}
|
|
|
|
_, err = h.castClient.SendSMS(ctx, localPhone, webhook.Message)
|
|
if err != nil {
|
|
slog.Error("webhook: cast send failed", "message_id", webhook.MessageID, "err", err)
|
|
h.updateStatus(ctx, webhook, "failed")
|
|
return
|
|
}
|
|
|
|
slog.Info("webhook: cast send success", "message_id", webhook.MessageID)
|
|
h.updateStatus(ctx, webhook, "delivered")
|
|
}
|
|
|
|
func (h *WebhookHandler) updateStatus(ctx context.Context, webhook OutboundMessageWebhook, status string) {
|
|
token, err := h.oauthHandler.GetValidToken(ctx, webhook.LocationID)
|
|
if err != nil {
|
|
slog.Error("webhook: failed to get valid token for status update", "location_id", webhook.LocationID, "err", err)
|
|
return
|
|
}
|
|
|
|
if err := h.ghlAPI.UpdateMessageStatus(ctx, token, webhook.MessageID, status); err != nil {
|
|
slog.Error("webhook: failed to update message status", "message_id", webhook.MessageID, "status", status, "err", err)
|
|
return
|
|
}
|
|
slog.Info("webhook: message status updated", "message_id", webhook.MessageID, "status", status)
|
|
}
|
|
|
|
func (h *WebhookHandler) verifySignature(body []byte, signatureB64 string) bool {
|
|
if signatureB64 == "" {
|
|
return false
|
|
}
|
|
sigBytes, err := base64.StdEncoding.DecodeString(signatureB64)
|
|
if err != nil {
|
|
return false
|
|
}
|
|
hash := sha256.Sum256(body)
|
|
return ecdsa.VerifyASN1(h.webhookPubKey, hash[:], sigBytes)
|
|
}
|
|
|
|
func (h *WebhookHandler) HandleUninstall(w http.ResponseWriter, r *http.Request) {
|
|
body, err := io.ReadAll(r.Body)
|
|
if err != nil {
|
|
slog.Error("uninstall: failed to read body", "err", err)
|
|
http.Error(w, "failed to read request body", http.StatusInternalServerError)
|
|
return
|
|
}
|
|
|
|
if !h.verifySignature(body, r.Header.Get("x-wh-signature")) {
|
|
slog.Warn("uninstall: invalid signature")
|
|
http.Error(w, "invalid webhook signature", http.StatusUnauthorized)
|
|
return
|
|
}
|
|
|
|
var payload UninstallWebhook
|
|
if err := json.Unmarshal(body, &payload); err != nil {
|
|
slog.Error("uninstall: failed to parse payload", "err", err)
|
|
http.Error(w, "invalid payload", http.StatusBadRequest)
|
|
return
|
|
}
|
|
|
|
if payload.LocationID == "" {
|
|
slog.Error("uninstall: missing locationId")
|
|
http.Error(w, "missing locationId", http.StatusBadRequest)
|
|
return
|
|
}
|
|
|
|
ctx := r.Context()
|
|
if err := h.store.DeleteToken(ctx, payload.LocationID); err != nil {
|
|
slog.Error("uninstall: failed to delete token", "location_id", payload.LocationID, "err", err)
|
|
http.Error(w, "failed to process uninstall", http.StatusInternalServerError)
|
|
return
|
|
}
|
|
|
|
slog.Info("uninstall: token deleted", "location_id", payload.LocationID)
|
|
w.WriteHeader(http.StatusOK)
|
|
}
|
|
|
|
func parseECDSAPublicKey(pemStr string) (*ecdsa.PublicKey, error) {
|
|
block, _ := pem.Decode([]byte(pemStr))
|
|
if block == nil {
|
|
return nil, fmt.Errorf("failed to decode PEM block")
|
|
}
|
|
pub, err := x509.ParsePKIXPublicKey(block.Bytes)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("failed to parse public key: %w", err)
|
|
}
|
|
ecdsaPub, ok := pub.(*ecdsa.PublicKey)
|
|
if !ok {
|
|
return nil, fmt.Errorf("key is not ECDSA")
|
|
}
|
|
return ecdsaPub, nil
|
|
}
|