package integration
import (
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"os"
"regexp"
"sync"
"time"
"github.com/ShieldLabs-ai/shieldlabs-go/webhook"
)
var uuid = regexp.MustCompile(`^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$`)
var used sync.Map // demonstration only; use a shared durable store in production
type Card struct {
Raw json.RawMessage `json:"-"`
ID string `json:"id"`
DomainID string `json:"domain_id"`
Type string `json:"type"`
CreatedAt time.Time `json:"created_at"`
UserHID *string `json:"user_hid"`
Risk struct {
State string `json:"state"`
Score *int `json:"score"`
Band *string `json:"band"`
} `json:"risk"`
Signals struct {
State string `json:"state"`
Items *[]string `json:"items"`
} `json:"signals"`
}
func ReadIdentification(ctx context.Context, client *http.Client, id string) (*Card, error) {
domain := os.Getenv("SHIELDLABS_DOMAIN_ID")
if !uuid.MatchString(domain) || !uuid.MatchString(id) { return nil, errors.New("domain and identification must be UUIDs") }
endpoint := "https://account.shieldlabs.ai/api/v1/domains/" + domain + "/history/identifications/" + id
req, err := http.NewRequestWithContext(ctx, http.MethodGet, endpoint, nil)
if err != nil { return nil, err }
req.Header.Set("Authorization", "Bearer " + os.Getenv("SHIELDLABS_API_KEY"))
req.Header.Set("Accept", "application/json")
response, err := client.Do(req)
if err != nil { return nil, err }
defer response.Body.Close()
if response.StatusCode != 200 { return nil, fmt.Errorf("History status %d", response.StatusCode) }
var envelope struct { Data json.RawMessage `json:"data"` }
if err := json.NewDecoder(io.LimitReader(response.Body, 1<<20)).Decode(&envelope); err != nil { return nil, err }
var card *Card
if err := json.Unmarshal(envelope.Data, &card); err != nil { return nil, err }
if card == nil || card.ID != id || card.DomainID != domain || card.Type != "identification" { return nil, errors.New("History identity mismatch") }
card.Raw = append(json.RawMessage(nil), envelope.Data...)
return card, nil
}
func AllowSignup(card *Card, domain, id string, expectedUserHID *string) bool {
if card == nil || card.ID != id || card.DomainID != domain || card.Type != "identification" || card.Risk.State != "ok" || card.Signals.State != "ok" || card.Risk.Score == nil || card.Risk.Band == nil || card.Signals.Items == nil { return false }
score := *card.Risk.Score
if score < 0 || score > 100 { return false }
band := "trusted"
if score >= 60 { band = "dangerous" } else if score >= 30 { band = "suspicious" }
if *card.Risk.Band != band || score >= 60 { return false }
for _, signal := range *card.Signals.Items {
if signal == "banned_ip" || signal == "browser_automation" { return false }
}
age := time.Since(card.CreatedAt)
if age < 0 || age > 5*time.Minute { return false }
if expectedUserHID != nil && (card.UserHID == nil || *card.UserHID != *expectedUserHID) { return false }
_, alreadyUsed := used.LoadOrStore(domain+":"+id, struct{}{})
return !alreadyUsed
}
func VerifyWebhook(body []byte, signature string) (map[string]json.RawMessage, error) {
secret := os.Getenv("SHIELDLABS_WEBHOOK_SECRET")
if secret == "" { return nil, errors.New("webhook secret is not configured") }
if !webhook.VerifySignature(body, signature, secret) { return nil, errors.New("invalid signature") }
var event map[string]json.RawMessage
if err := json.Unmarshal(body, &event); err != nil { return nil, err }
var eventID string
if err := json.Unmarshal(event["event_id"], &eventID); err != nil || eventID == "" { return nil, errors.New("missing event_id") }
return event, nil
}