Files
tenant-registry/internal/erp/webhook.go
T
Sharang ParnerkarandClaude Fable 5.1 7b02cd1c21
ci / shared (pull_request) Successful in 12s
ci / test (pull_request) Failing after 14m32s
ci / image (pull_request) Skipped
feat(erp): always-on ERP link, usage events, outbox, CLI licences
M-MIG-7 (ERP/02, decisions 3, 12, 13, 18):

- migration 0004: subscriptions, usage_events, erp_outbox,
  erp_webhook_receipts, licences; tenants.status_changed_at (trigger)
- internal/erp: Frappe REST client (Customer upsert by tenant_id,
  Subscription list, Usage Record, Lead) + webhook signing/verification
- internal/erpmock + cmd/erpmock: ERPNext stand-in for staging —
  /api/resource/{doctype} with token auth, request log, /_mock/fire/*
  triggers that mutate docs and deliver signed webhooks
- POST /v1/internal/erp/webhook (HMAC, idempotent by event id):
  sales_order.submit → subscriptions + entitlements (SKU → product/plan,
  add-on SKUs → limits) + active; sales_invoice.overdue → warning /
  restricted / halted by days overdue; payment_entry.submit → active;
  subscription.cancel → halted
- outbox worker (customer.upsert on tenant create, usage.record,
  lead.create on catalog request) with backoff; reconcile job mirrors
  ERP subscriptions and applies the time-based ladder (trial expiry,
  warning→restricted 14 d, restricted→halted 30 d, halted→archived 30 d)
- POST/GET /v1/usage/events (idempotency_key, batch), GET
  /v1/subscriptions, GET /v1/internal/erp/status, POST
  /v1/internal/erp/reconcile
- CLI licences: Ed25519 signer (LICENCE_SIGNING_KEY), POST /v1/licences
  (entitlement-gated, expiry capped by the entitlement), GET
  /.well-known/licence-keys.json, POST /v1/licences/heartbeat (grace
  ladder, renewal past half-life, revoked), revoke/list
- authn Principal carries tenant-context claims (user tokens scope usage
  and licence calls to their own tenant); authz groups usage(.read)
- tests for every path (both stores), erpmock, erp client, licence pkg;
  openapi.yaml + README updated; Dockerfile ships /erpmock

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DmXxNULoSNPvjF7buKipsB
2026-09-12 09:45:05 +02: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)
}