# knownprint in the backend: Go

Part of the knownprint quickstart for AI coding agents, Step 6. Read
https://knownprint.com/quickstart.md first: it holds the rules that apply here (never read or print
secrets, ask before touching a live server, an unknown result is never a pass). This file covers the
module that reads the event, runs the six checks and decides, and how to call it from a handler. The
checks and rules it implements are written out in https://knownprint.com/quickstart/other.md.

Use the module as written. It reads `KNOWNPRINT_API`, `KNOWNPRINT_SECRET_KEY` and
`KNOWNPRINT_SITE_ORIGINS`, never logs a request id, an address or a secret, and turns every failure
into an "unknown" result that takes the challenge path.

## The module

Go 1.21 or later, standard library only; swap the in-memory map for Redis `SET key 1 PX 70000 NX`
when several instances run:

```go
// knownprint.go
package knownprint

import (
	"bytes"
	"context"
	"encoding/json"
	"fmt"
	"log"
	"net/http"
	"net/netip"
	"os"
	"regexp"
	"strings"
	"sync"
	"time"
)

var (
	requestIDPattern = regexp.MustCompile(`^evt_[a-z2-7]{26}$`)
	httpClient       = &http.Client{Timeout: 5 * time.Second}
	siteOrigins      = splitOrigins(os.Getenv("KNOWNPRINT_SITE_ORIGINS"))
	usedMu           sync.Mutex
	used             = map[string]time.Time{}
)

const (
	maxAge    = 10 * time.Second
	clockSkew = 60 * time.Second
)

type Signal struct {
	Value any `json:"value"`
}

type Event struct {
	RequestID  string  `json:"request_id"`
	ReceivedAt string  `json:"received_at"`
	Confidence float64 `json:"confidence"`
	Integrity  struct {
		Origin   string `json:"origin"`
		Replayed bool   `json:"replayed"`
	} `json:"integrity"`
	Network struct {
		IP *string `json:"ip"`
	} `json:"network"`
	Signals map[string]*Signal `json:"signals"`
}

type Result struct {
	OK     bool
	Reason string
	Event  *Event
}

func splitOrigins(list string) map[string]bool {
	origins := map[string]bool{}
	for _, origin := range strings.Split(list, ",") {
		if origin = strings.TrimSpace(origin); origin != "" {
			origins[origin] = true
		}
	}
	return origins
}

func useOnce(id string) bool {
	usedMu.Lock()
	defer usedMu.Unlock()
	now := time.Now()
	for key, until := range used {
		if !until.After(now) {
			delete(used, key)
		}
	}
	if _, seen := used[id]; seen {
		return false
	}
	used[id] = now.Add(maxAge + clockSkew)
	return true
}

// CanonicalIP writes an address as knownprint does: IPv4 dotted quad, IPv6 short and lower case.
func CanonicalIP(text string) string {
	addr, err := netip.ParseAddr(strings.TrimSpace(text))
	if err != nil {
		return ""
	}
	return addr.Unmap().String()
}

// ClientIP is the last X-Forwarded-For entry when the peer is the site's own proxy on this host,
// else the peer itself. Never the first entry.
func ClientIP(r *http.Request) string {
	peer := ""
	if addrPort, err := netip.ParseAddrPort(r.RemoteAddr); err == nil {
		peer = addrPort.Addr().Unmap().String()
	}
	if peer == "127.0.0.1" || peer == "::1" {
		if header := strings.TrimSpace(r.Header.Get("X-Forwarded-For")); header != "" {
			parts := strings.Split(header, ",")
			return CanonicalIP(parts[len(parts)-1])
		}
	}
	return peer
}

func call(ctx context.Context, method, path string, body any, out any) (bool, error) {
	var payload []byte
	if body != nil {
		var err error
		if payload, err = json.Marshal(body); err != nil {
			return false, err
		}
	}
	req, err := http.NewRequestWithContext(ctx, method, os.Getenv("KNOWNPRINT_API")+path, bytes.NewReader(payload))
	if err != nil {
		return false, err
	}
	req.Header.Set("Authorization", "Bearer "+os.Getenv("KNOWNPRINT_SECRET_KEY"))
	req.Header.Set("Accept", "application/json")
	if body != nil {
		req.Header.Set("Content-Type", "application/json")
	}
	res, err := httpClient.Do(req)
	if err != nil {
		return false, err
	}
	defer res.Body.Close()
	if res.StatusCode == http.StatusNotFound || res.StatusCode == http.StatusConflict {
		return false, nil
	}
	if res.StatusCode < 200 || res.StatusCode > 299 {
		return false, fmt.Errorf("knownprint answered %d", res.StatusCode)
	}
	if out != nil {
		return true, json.NewDecoder(res.Body).Decode(out)
	}
	return true, nil
}

// VerifyRequestID never returns an error: a failure is a Result with OK false.
func VerifyRequestID(ctx context.Context, requestID, ip string) Result {
	if !requestIDPattern.MatchString(requestID) {
		return Result{Reason: "missing"}
	}
	if !useOnce(requestID) {
		return Result{Reason: "used"}
	}
	var event Event
	found, err := call(ctx, http.MethodGet, "/v1/events/"+requestID, nil, &event)
	if err != nil {
		log.Printf("knownprint: %v", err) // never the request id or the address
		return Result{Reason: "error"}
	}
	if !found {
		return Result{Reason: "not_found"}
	}
	received, err := time.Parse(time.RFC3339Nano, event.ReceivedAt)
	age := time.Since(received)
	if err != nil || age > maxAge || age < -clockSkew {
		return Result{Reason: "stale"}
	}
	if event.Integrity.Replayed {
		return Result{Reason: "replayed"}
	}
	if !siteOrigins[event.Integrity.Origin] {
		return Result{Reason: "origin"}
	}
	if event.Network.IP == nil || *event.Network.IP != CanonicalIP(ip) {
		return Result{Reason: "address"}
	}
	return Result{OK: true, Event: &event}
}

// Decide returns allow, challenge, review or block. Example thresholds: tune them.
func Decide(r Result) string {
	if !r.OK {
		return "challenge" // unknown: never allow, never block on this alone
	}
	s := r.Event.Signals
	if bot := s["bot"]; bot != nil && bot.Value == "bad" {
		return "block"
	}
	score, known := 0.0, false
	if ss := s["suspect_score"]; ss != nil {
		score, known = ss.Value.(float64)
	}
	if !known {
		return "challenge"
	}
	if t := s["tampering"]; (t != nil && t.Value == true) || score >= 60 {
		return "review"
	}
	if score >= 30 {
		return "challenge"
	}
	return "allow"
}

// LinkAccount attaches your account id to the event once the account exists. It only logs a
// failure, so a signup never fails because of it.
func LinkAccount(ctx context.Context, requestID, accountID string) {
	body := map[string]string{"linked_id": accountID}
	if _, err := call(ctx, http.MethodPatch, "/v1/events/"+requestID, body, nil); err != nil {
		log.Printf("knownprint link: %v", err)
	}
}
```

In a handler: `result := knownprint.VerifyRequestID(r.Context(), r.FormValue("kp_request_id"), knownprint.ClientIP(r))`,
then `knownprint.Decide(result)`.

Next: https://knownprint.com/quickstart.md, the end of Step 6.
