Files
tenant-registry/internal/erp/webhook.go
sharang 209524e5ac
ci / shared (push) Successful in 14s
ci / test (push) Successful in 22m28s
ci / image (push) Successful in 28s
feat(erp): always-on ERP link, usage events, outbox, CLI licences (#25)
2026-09-12 08:35:13 +00:00

73 lines
2.3 KiB
Go

package erp
import (
"crypto/hmac"
"crypto/sha256"
"encoding/base64"
"encoding/hex"
"strings"
)
// Webhook headers. Frappe's Webhook doctype signs the JSON body with
// HMAC-SHA256 and sends it base64-encoded in X-Frappe-Webhook-Signature;
// the mock adds X-Frappe-Event-Id so receipts are idempotent by id.
const (
HeaderSignature = "X-Frappe-Webhook-Signature"
HeaderEventID = "X-Frappe-Event-Id"
HeaderEvent = "X-Frappe-Event"
)
// Webhook events the registry maps onto the tenant ladder (ERP/02).
const (
EventSalesOrderSubmit = "sales_order.submit"
EventInvoiceOverdue = "sales_invoice.overdue"
EventPaymentEntrySubmit = "payment_entry.submit"
EventSubscriptionCancel = "subscription.cancel"
)
// WebhookEvent is the payload shape both the mock and the live Frappe
// Webhook configuration (ERP/03) deliver.
type WebhookEvent struct {
Event string `json:"event"`
Doctype string `json:"doctype"`
Name string `json:"name"`
Modified string `json:"modified,omitempty"`
Customer string `json:"customer,omitempty"`
TenantID string `json:"tenant_id,omitempty"`
Items []WebhookItem `json:"items,omitempty"`
DaysOverdue int `json:"days_overdue,omitempty"`
Subscription string `json:"subscription,omitempty"`
Invoice string `json:"invoice,omitempty"`
Amount float64 `json:"amount,omitempty"`
}
type WebhookItem struct {
ItemCode string `json:"item_code"`
Qty float64 `json:"qty"`
}
// Sign returns the base64 HMAC-SHA256 of body.
func Sign(secret string, body []byte) string {
mac := hmac.New(sha256.New, []byte(secret))
mac.Write(body)
return base64.StdEncoding.EncodeToString(mac.Sum(nil))
}
// VerifySignature accepts the Frappe base64 form and the GitHub-style
// "sha256=<hex>" form.
func VerifySignature(secret string, body []byte, header string) bool {
header = strings.TrimSpace(header)
if secret == "" || header == "" {
return false
}
mac := hmac.New(sha256.New, []byte(secret))
mac.Write(body)
sum := mac.Sum(nil)
if hexSig, ok := strings.CutPrefix(header, "sha256="); ok {
want, err := hex.DecodeString(hexSig)
return err == nil && hmac.Equal(want, sum)
}
want, err := base64.StdEncoding.DecodeString(header)
return err == nil && hmac.Equal(want, sum)
}