fingerly

package module
v0.4.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 17, 2026 License: Apache-2.0 Imports: 21 Imported by: 0

README

Fingerly

Fingerly for Go
Read events, verify webhooks and serve a first-party proxy from your Go backend, using only the standard library.

Latest version CI status Go 1.22 or newer Apache-2.0 licence Documentation

Fingerly

What is this

fingerly-go is the server-side Go package for Fingerly, which identifies the device behind every web and app session and scores how suspicious it is. Use it to protect signups, logins and payments: read the event the browser SDK produced with a server-only secret key, verify webhook signatures, and relay the browser SDK's traffic through your own domain.

Go 1.22 or newer. No dependencies outside the standard library.

Getting started

1. Prerequisites. A Fingerly account and a secret key (see API keys and environments). A webhook signing secret to verify webhooks, and a proxy key (see Proxy integrations) for the proxy.

2. Install.

go get github.com/fingerly-io/fingerly-go@v0.4.1

3. Read an event.

import fingerly "github.com/fingerly-io/fingerly-go"

client := fingerly.New(os.Getenv("FINGERLY_SECRET_KEY"))

event, err := client.Events.Get(ctx, requestID)
page, err := client.Events.List(ctx, &fingerly.EventListParams{Level: fingerly.SuspectLevelHigh, Limit: 50})

4. Verify a webhook.

body, _ := io.ReadAll(r.Body)
ok := fingerly.VerifyWebhook(
	os.Getenv("FINGERLY_WEBHOOK_SECRET"),
	body,
	r.Header.Get("X-Fingerly-Timestamp"),
	r.Header.Get("X-Fingerly-Signature"),
)

Full documentation: docs.fingerly.io/docs/sdks/go.

Choose what you need

I want to Go to
Read an event, or verify and consume it for a backend action Read events, Verify a backend action
Handle errors, deadlines and unscored events Errors, Deadlines and cancellation, Unscored events
Read or write an iOS device's DeviceCheck bits DeviceCheck bits on iOS
Check a webhook signature Verify webhooks
Keep identification working behind content blockers First-party proxy

Contents

Read events

Event reads require fly_sk_{production|staging|development}_… keys. Requests go to https://api.fingerly.io; WithEndpoint overrides that for a local API. The endpoint must be a bare https:// origin: scheme, host and optional port, with no path, query, fragment, credentials, space or control byte. A plain http:// endpoint is accepted only for 127.0.0.1, localhost or [::1], and only together with WithAllowInsecureLoopback(), which is meant for a local test harness. Configuration errors never repeat the endpoint or the key. Public, proxy, management, malformed and unsupported keys are rejected before network access. Requests do not follow redirects. Get and List each perform one request and never retry.

New returns only a client, so it composes in a package-level var. An invalid key or option is reported by the first call, before anything is sent.

Every Client and Proxy in the process shares one connection pool, which keeps 256 idle connections per host and is replaced every five minutes so a DNS change is picked up. There is nothing to tune for a busy server. Pass WithHTTPClient or ProxyOptions.Transport only for a custom HTTP stack; an http.Client with a nil Transport still gets the shared pool.

Deadlines and cancellation

Every call takes a context.Context, and a Go request context governs the whole exchange, so the deadline covers reading the response body too. The client applies WithTimeout (10s by default) on top of whatever the caller's context already carries, whichever is sooner. Cancelling the context stops the request.

Errors

Any response outside 2xx, redirects included, returns an *APIError with Status, and optional Code, Details, RequestID and RetryAfter. The secret key is stripped from all of them, and the response body is never echoed. RetryAfter is the number of seconds from the Retry-After header, or nil when there was none; the SDK never retries a read itself.

var apiErr *fingerly.APIError
if errors.As(err, &apiErr) && apiErr.Status == http.StatusTooManyRequests && apiErr.RetryAfter != nil {
	wait := time.Duration(*apiErr.RetryAfter) * time.Second
	_ = wait // back off for at least this long
}

A 404 from Events.Get carries one of two codes, each with a sentinel, so neither needs a status check:

Sentinel Meaning
fingerly.ErrEventPending Accepted but not recorded yet: retry after apiErr.RetryAfter seconds.
fingerly.ErrEventNotFound Never issued for this key's environment, or past the 30-day retention.
switch {
case errors.Is(err, fingerly.ErrEventPending):
	// Accepted but not recorded yet: retry after apiErr.RetryAfter seconds.
case errors.Is(err, fingerly.ErrEventNotFound):
	// Never issued for this key's environment, or past the 30-day retention.
}

A read that got no complete answer (refused, reset, timed out, or broken off mid-body) returns a *fingerly.ConnectionError, and errors.Is(err, fingerly.ErrTimeout) is true when a deadline passed. Its message names neither the key nor the endpoint. An answer over 4 MiB returns fingerly.ErrResponseTooLarge.

Printing a Client, Proxy or ProxyOptions with any fmt verb, slog or encoding/json shows the keys as [redacted].

Unscored events

Event.SuspectScore is a *int because nil means unscored, which must never be read as zero: a visitor about whom nothing fired scores 0, while a submission that was never enriched has no score at all. Scored() and Score() state that distinction at the call site.

score, ok := event.Score()
if !ok {
	// Unscored. Decide on something else; do not treat it as clean.
}

Event.Raw and EventPage.Raw keep the response body exactly as it arrived, so a field the API adds later is reachable without an SDK upgrade.

Read an event you just identified

event, err := client.Events.Get(ctx, requestID)

If the event is not recorded yet, the error matches ErrEventPending and its *APIError carries RetryAfter. That is not a verdict: try again after that many seconds, or verify asynchronously, for example from a webhook. The SDK never retries on its own. ErrEventNotFound means the request id was never issued or the event is past retention.

The archived Document arrives moments after the event itself, so check HasDocument rather than assuming it is there, and call event.ParseDocument() to decode it into a typed *EventDocument (including *Attestation and *EventRiskReport). When a submission is unidentifiable (!event.Identifiable(), such as insufficient entropy, a genuine embedded WebView, or an unmatched high-risk Web payload), event.VisitorID is ""; there are no deferred_token, deferred_signals or supplements fields in v: 3.

Every closed set the API reports is a named string type with a constant per value, so compare against the constants rather than string literals:

Type Fields Constants
Signal EventTrigger.Signal (groups), EventRiskTrigger.Signal (raw detectors) SignalVPN, SignalBot, SignalFingerprintSuppressed, SignalAttestationFailed, SignalVPNPublic, ... (every group and detector)
SuspectLevel Event.SuspectLevel, EventRiskReport.Level, EventListParams.Level SuspectLevelLow, SuspectLevelMedium, SuspectLevelHigh
Confidence EventTrigger.Confidence, EventRiskTrigger.Confidence ConfidenceLow, ConfidenceMedium, ConfidenceHigh
AttestationState Attestation.State AttestationStateAttested, AttestationStateNotAttested, AttestationStateFailed
AttestationStatus Attestation.Status AttestationStatusVerified, AttestationStatusIndeterminate, AttestationStatusInvalid, AttestationStatusAbsent, AttestationStatusUnconfigured
AttestSkippedReason Attestation.AttestSkipped AttestSkippedNotOffered, AttestSkippedUnsupported, AttestSkippedChallengeUnavailable, AttestSkippedKeyError, AttestSkippedTimeout, AttestSkippedBackoff, AttestSkippedInstallUnavailable
EventState Event.State EventStatePending, EventStateEnriched, EventStateUnavailable
AnonymityNetwork Event.AnonymityNetwork AnonymityNetworkTor, AnonymityNetworkRelay, AnonymityNetworkVPN, AnonymityNetworkProxy, AnonymityNetworkHosting
Environment Event.Environment EnvironmentProduction, EnvironmentStaging, EnvironmentDevelopment
RiskPlatform Event.Platform, EventRiskReport.Platform RiskPlatformWeb, RiskPlatformIOS, RiskPlatformAndroid
RiskSource EventRiskReport.Source RiskSourceKey, RiskSourceOrganization, RiskSourceDefault
VerifyReason VerifyResult.Reason VerifyReasonOK (""), VerifyNotFound, VerifyTooOld, VerifyTagMismatch, VerifyUnidentifiable, VerifyUnscored, VerifyAlreadyConsumed
WebhookEventType WebhookEvent.Type WebhookIdentificationCompleted, WebhookIdentificationRefused, WebhookVisitorSuspect, WebhookBillingStatusChanged, WebhookUsageDailySettled, WebhookTest
WebhookEnvironment WebhookEvent.Environment WebhookEnvironmentLive, WebhookEnvironmentTest

A value the server adds after this release still decodes, as a value no constant names. A string variable needs a conversion to compare, such as fingerly.Signal(name).

A native Attestation also carries AttestSkipped (the app's reason for sending no proof) and Downgrade (the report named an install an attested device owns).

Verify a backend action

Verify the event with a server-only key, then apply your own policy to the server's verdict. Do not authorize an action using scores or visitor identifiers supplied by the browser. Tags correlate events; they do not replace your application's authentication or replay protection. Never put a personal identifier (user ID, email, install ID, advertising ID) in a tag: the server keeps tag values in long-lived rollups.

client.Events.Verify reads the event and runs these checks in order, stopping at the first that fails, whose VerifyReason it reports:

  1. VerifyNotFound ("not_found"): the event does not exist. VerifyResult.Event is nil only for this reason.
  2. VerifyTooOld ("too_old"): it occurred more than MaxAgeSeconds ago (300 by default, DefaultVerifyMaxAge), or its occurred_at is missing or unreadable.
  3. VerifyTagMismatch ("tag_mismatch"): Tag was given and the event's tag is not exactly that. A nil Tag skips this check; an empty one is refused.
  4. VerifyUnidentifiable ("unidentifiable"): the event has no VisitorID.
  5. VerifyUnscored ("unscored"): the event has no suspect score.
  6. VerifyAlreadyConsumed ("already_consumed"): every check above passed, but the event was already consumed.

Only when every other check passes does Verify consume the event, last, so one event backs one decision and a replayed request id fails. Set SkipConsume: true to check without consuming. When everything passes, OK is true and Reason is VerifyReasonOK (""). A negative MaxAgeSeconds or an empty Tag returns ErrInvalidVerifyOptions before any request.

A failed check is a result, not an error. Every other failure is returned unchanged as the error, including ErrEventPending, which is not a verdict. Verify never looks at the score's value, the level or the triggers: that policy stays with you.

Event.ProjectID is the Fingerly project the event belongs to, on both Events.Get and every row of Events.List. It is empty when an older server does not send it.

Complete verification server
package main

import (
	"errors"
	"log"
	"net/http"
	"os"
	"strconv"

	"github.com/fingerly-io/fingerly-go"
)

var client = fingerly.New(os.Getenv("FINGERLY_SECRET_KEY"))

// POST /checkout/{request_id}
func checkout(w http.ResponseWriter, r *http.Request) {
	tag := "checkout"
	result, err := client.Events.Verify(r.Context(), r.PathValue("request_id"),
		&fingerly.VerifyOptions{Tag: &tag})
	var apiErr *fingerly.APIError
	switch {
	case errors.Is(err, fingerly.ErrEventPending) && errors.As(err, &apiErr):
		// Not decided yet, not fraud: ask the caller to come back.
		wait := 2
		if apiErr.RetryAfter != nil {
			wait = *apiErr.RetryAfter
		}
		w.Header().Set("Retry-After", strconv.Itoa(wait))
		http.Error(w, "verification pending", http.StatusServiceUnavailable)
		return
	case err != nil:
		http.Error(w, "verification unavailable", http.StatusBadGateway)
		return
	case !result.OK:
		// not_found, too_old, tag_mismatch, unidentifiable, unscored or
		// already_consumed.
		http.Error(w, "verification failed: "+string(result.Reason), http.StatusForbidden)
		return
	}
	// The event is recent, tagged, identified, scored and now consumed. The
	// score policy is yours: result.Event.SuspectLevel, Score(), triggers and
	// ParseDocument().
	event := result.Event
	if event.SuspectLevel == fingerly.SuspectLevelHigh {
		http.Error(w, "checkout refused", http.StatusForbidden)
		return
	}
	for _, trigger := range event.Triggers {
		if trigger.Signal == fingerly.SignalAttestationFailed {
			http.Error(w, "attestation failed", http.StatusForbidden)
			return
		}
	}
	if doc, err := event.ParseDocument(); err == nil && doc != nil && doc.Attestation != nil &&
		doc.Attestation.State == fingerly.AttestationStateFailed {
		http.Error(w, "attestation failed", http.StatusForbidden)
		return
	}
	_, _ = w.Write([]byte("ok"))
}

func main() {
	http.HandleFunc("POST /checkout/{request_id}", checkout)
	log.Fatal(http.ListenAndServe(":8080", nil))
}

To consume an event on its own, call client.Events.Consume. It is a POST with no body and is never retried. The first call returns a *ConsumeResult with ConsumedAt and First; any later call returns an *EventAlreadyConsumedError, which matches ErrEventAlreadyConsumed with errors.Is, reaches its *APIError (status 409, code event_already_consumed) with errors.As, and carries ConsumedAt from the first call, or "" when the answer did not say.

_, err := client.Events.Consume(ctx, requestID)
var consumed *fingerly.EventAlreadyConsumedError
if errors.As(err, &consumed) {
	// Already used at consumed.ConsumedAt: refuse the replay.
}

DeviceCheck bits on iOS

When DeviceCheck is turned on for the project's Apple key, Fingerly holds the Apple DeviceCheck token of an iOS identification for one hour. client.DeviceCheck spends it, once, to read or to write the two bits Apple keeps for the device. The bits survive a reinstall and mean what you decide.

bits, err := client.DeviceCheck.Query(ctx, requestID)
// bits.Found, bits.Bit0, bits.Bit1, bits.LastUpdate ("YYYY-MM")

_, err = client.DeviceCheck.Write(ctx, requestID, fingerly.DeviceCheckWrite{Bit0: fingerly.Bool(true)})

Apple treats a DeviceCheck token as single-use, so a read and a write each need their own identification. A once-per-device free trial takes two:

  1. On the identification that asks for the trial, call Query. If the bits say the device already had one, refuse it.
  2. Otherwise grant the trial and record the grant in your own data, with the device not yet marked.
  3. On the next identification from that install (the app can identify again right after the grant), call Write with the bit, then mark the record. Until the write lands, your own record is what stops a second trial.

Each answer has a sentinel for errors.Is; the concrete error is an *APIError:

Sentinel Status and code What to do
ErrDeviceCheckNotHeld 404 device_check_not_held No token for that event. Decide without the bits.
ErrDeviceCheckSpent 409 device_check_spent Already used, or not the request it was first used for. Use another identification.
ErrDeviceCheckBusy 409 device_check_busy Another call is using it. Retry in a moment.
ErrCredentialUnavailable 409 credential_unavailable Fix the Apple key, then retry within the hour.
ErrBitsRequired 422 bits_required Name Bit0, Bit1 or both. Also returned, without a request, by a Write naming neither.
ErrAppleRejected 422 apple_rejected Apple rejected the token; APIError.AppleStatus holds Apple's HTTP status.
ErrDeviceCheckUnavailable 503 device_check_unavailable The token is kept. Retry the same call within the hour.

A retry must be the same request: while a token is kept after an answer that was not definite, the API accepts only the operation and bits it was first used for, and answers anything else with device_check_spent. The SDK retries a 503 or a call that got no complete answer up to twice, with the identical request, and nothing else. When you retry later yourself, repeat the same call with the same bits.

Verify webhooks

The example under Getting started calls fingerly.VerifyWebhook.

Verify the exact raw bytes before decoding them. Signatures cover the timestamp and body. The default replay tolerance is five minutes; persist processed WebhookEvent.ID values to deduplicate deliveries. During signing-secret rotation, any matching signature among the first 32 in the comma-separated header is accepted. Malformed or missing input is a false result, never a panic.

WebhookEvent decodes the envelope every delivery shares and leaves Data raw, so a new event type needs no SDK upgrade. Switch on Type with the WebhookEventType constants, such as fingerly.WebhookIdentificationCompleted. The identification.completed and visitor.suspect payloads carry data.project_id, the project the event belongs to; identification.refused carries it only when the refused request named a known key.

First-party proxy

Content blockers refuse browser requests to third-party APIs, and a refused identification is a visitor never identified. Mount the proxy on a path of your own site and those requests become first-party. The proxy key is what lets that hop declare the visitor's real address, origin and user agent; a public key alone never can, so nobody can spoof them.

Create a proxy in the dashboard (Integration > Proxy keys) and mount the handler at the path it issued, here /k7x2qm4a:

package main

import (
	"log"
	"net"
	"net/http"
	"os"

	fingerly "github.com/fingerly-io/fingerly-go"
)

func main() {
	proxy, err := fingerly.NewProxy(fingerly.ProxyOptions{
		ProxyKey: os.Getenv("FINGERLY_PROXY_KEY"),
		Path:     "/k7x2qm4a",
		ClientIP: func(r *http.Request) string {
			// The header your load balancer or CDN sets, else the TCP peer.
			if address := r.Header.Get("X-Real-IP"); address != "" {
				return address
			}
			host, _, _ := net.SplitHostPort(r.RemoteAddr)
			return host
		},
	})
	if err != nil {
		log.Fatal(err)
	}

	mux := http.NewServeMux()
	mux.Handle("/k7x2qm4a", proxy)
	log.Fatal(http.ListenAndServe(":8080", mux))
}

Trust that header only when traffic can reach the server through that load balancer or CDN alone; otherwise a visitor can set it. Proxy implements http.Handler, so every router built on net/http takes it directly, and fiber through its adaptor:

Router Mount
net/http mux.Handle("/k7x2qm4a", proxy)
gorilla/mux router.Handle("/k7x2qm4a", proxy)
chi r.Handle("/k7x2qm4a", proxy)
gin router.Any("/k7x2qm4a", gin.WrapH(proxy))
echo e.Any("/k7x2qm4a", echo.WrapHandler(proxy))
fiber app.All("/k7x2qm4a", adaptor.HTTPHandler(proxy))

Then point the client SDK at the same path. Browser and proxied native SDKs post a single v: 3 identification envelope there, with nothing appended:

const fingerly = await load({ apiKey: 'fly_pk_…', endpoints: '/k7x2qm4a' })

Unlike New, NewProxy reports configuration errors immediately: a proxy is wired up once at start-up, where an error is natural to handle.

What the proxy does

With Path set it answers only that path, matched exactly: a trailing or doubled slash, a dot segment, an encoded character, a different case or a path under it (including retired /supplement paths) all get 404. Path is optional: leave it empty when the route already sends only that path to the handler, and behind http.StripPrefix, which changes the path the handler sees. It must be an absolute path such as /k7x2qm4a, or NewProxy returns an error. Only POST (plus OPTIONS when AllowedOrigins is configured) is accepted, compared case-sensitively; any other method, post included, gets 405. Every answer the proxy writes itself, 404 and 405 included, carries Cache-Control: no-store.

Every forwarded request goes with its raw body bytes untouched (never JSON re-encoded) to one URL, https://api.fingerly.io/api/v1/ingest (APIVersion and Upstream change its version and origin). Event reads need a secret key and stay unreachable from a browser by construction.

Upstream must be a bare https:// origin: scheme, host and optional port, with no path, query, fragment, credentials, space or control byte, or NewProxy returns an error. A plain http:// upstream is accepted only for 127.0.0.1, localhost or [::1], and only with AllowInsecureLoopback: true, which is meant for a local test harness. Redirects are never followed, with the shared pool or your own Transport; an upstream 3xx, or a status outside 200 to 599, gets 502.

Situation Answer
Path other than the configured one 404
Method other than POST (or OPTIONS with AllowedOrigins configured) 405
Neither an Origin nor a validated X-Fingerly-SDK-Platform 400 (missing_origin)
Public key from a different environment than the proxy key 401
Body over 1 MiB 413
Timeout passed 504
Upstream 3xx or a status outside 200 to 599 502
Any other upstream failure: refused, reset, DNS, a truncated or malformed answer, an answer over 4 MiB 502
ClientIP returns no valid address 500 with "The client IP callback returned no valid address"

The caller must present a public key from the same environment as the proxy key, or the request gets 401. Incoming headers follow the sanitize-and-restore sequence: all incoming X-Fingerly-*, Cookie and Authorization headers are stripped, restoring X-Fingerly-SDK-Platform only if it matched an exact lowercase native or bridge platform (ios, android, react-native, react-native-ios, react-native-android, flutter, flutter-ios, flutter-android, lynx-ios, lynx-android, capacitor, kotlin-multiplatform). A request carries one channel upstream: with an Origin it goes as a browser request (X-Fingerly-Origin) and the platform header is not forwarded; without one, the validated platform is. When both Origin and a validated X-Fingerly-SDK-Platform are absent, the proxy rejects locally with 400 (missing_origin), and it never synthesizes X-Fingerly-Origin from Host, Referer or the request URL. Bodies over 1 MiB get 413. Alongside verified proxy metadata (X-Fingerly-Host included), only Content-Type, X-Api-Key, User-Agent, Idempotency-Key, Sec-Fetch-* and Sec-CH-UA-* are forwarded. The proxy reports itself upstream as go/0.4.1, which the dashboard shows per proxy.

One deadline, Timeout (5 seconds by default), covers the whole upstream exchange, body included, so a trickling answer cannot stretch it. When it passes the browser gets 504; any other upstream failure (refused, reset, DNS, a truncated or malformed answer, an answer over 4 MiB) gets 502. Both carry a short text/plain body and Cache-Control: no-store. The answer is read in full before anything is written, so a broken upstream never reaches the browser as a 200. A visitor who disconnects cancels the upstream call, except under fiber, whose adaptor has no disconnect signal, so the call runs to Timeout.

Timeout bounds the upstream call, not the visitor's upload: a client that trickles its request body holds a handler until your http.Server gives up, so set ReadHeaderTimeout and ReadTimeout on it. A bare http.ListenAndServe has neither.

Each failure is reported once: to ProxyOptions.OnError if you set it, otherwise as one line through slog.Default(). failure.Err names the kind of failure only (a timeout, an unreachable upstream, a TLS failure, an unrelayable status or answer), never the upstream host, port or URL, and never a key.

OnError: func(r *http.Request, failure *fingerly.ProxyError) {
	log.Printf("identification proxy answered %d: %v", failure.Status, failure.Err)
},

Responses are marked no-store, and the only upstream headers relayed back are Content-Type, X-Request-Id, RateLimit-Limit, RateLimit-Remaining and Retry-After, so nothing on the response names Fingerly. Use the path the dashboard issued: blockers look for words such as fingerprint, tracking, analytics and fingerly in the URL.

ClientIP is the one thing you must get right. Resolve it from a header your own infrastructure sets, such as your load balancer's or CDN's, and fall back to r.RemoteAddr. Never read the left-most X-Forwarded-For value: the visitor writes it. It must return exactly one IPv4 or IPv6 address. Anything else (empty, a list, a port) is a configuration error: the proxy answers 500 with "The client IP callback returned no valid address", calls nothing upstream, and reports it once.

Development and release preparation

gofmt -l .
go vet ./...
go test -race -cover ./...
go run tools/synccontract.go     # refresh the vendored contract snapshot

The vendored synthetic contract snapshot makes tests independent of sibling repositories. To update it from the integration workspace, set FINGERLY_CONTRACT_DIR to its contract directory. The snapshot's hashes are checked by go test, so there is no separate check step. Never put production secrets in fixtures.

Source structure

fingerly.go holds the Client and its options. transport.go performs authenticated requests and maps failures to *APIError. events.go owns the event reads and the list filters; models.go owns the types they decode into. verify.go verifies and consumes an event for a backend decision. device_check.go reads and writes an event's DeviceCheck bits. webhooks.go verifies signatures. proxy.go is the same-origin handler. config.go validates every caller-supplied option: keys, origins, API versions and durations, all before any network access. errors.go holds the error type and its sentinels.

Requirements

  • Go 1.22 or newer (go 1.22 in go.mod; CI runs Go 1.22, 1.24 and 1.25).
  • No dependencies outside the standard library.

Documentation

Help

Open an issue on this repository, or write to support@fingerly.io. Security issues: security@fingerly.io.

Licence

Apache-2.0. See LICENSE.

Documentation

Overview

Package fingerly is the server-side Fingerly SDK.

It reads stored identification events with a secret key, verifies signed webhooks, and serves the browser SDK's requests from a route on your own domain. It has no dependencies outside the standard library.

client := fingerly.New(os.Getenv("FINGERLY_SECRET_KEY"))
event, err := client.Events.Get(ctx, requestID)

Secret keys and webhook secrets belong in server-side code only. A browser must never see either.

Index

Examples

Constants

View Source
const DefaultVerifyMaxAge = 300

DefaultVerifyMaxAge is the age, in seconds, past which Verify reports an event as too old when VerifyOptions.MaxAgeSeconds is zero.

View Source
const DefaultWebhookTolerance = 5 * time.Minute

DefaultWebhookTolerance is how far a delivery's timestamp may be from now before it is refused as a replay.

View Source
const Version = "0.4.1"

Version is the SDK version, reported to the API on every request.

Variables

View Source
var (
	// ErrDeviceCheckNotHeld (404 device_check_not_held): no token is held for
	// that event. Not a verdict: decide without the bits.
	ErrDeviceCheckNotHeld = errors.New("fingerly: no device check token is held for that event")
	// ErrDeviceCheckSpent (409 device_check_spent): the token was already
	// used, or this call is not the request the token was first used for.
	ErrDeviceCheckSpent = errors.New("fingerly: the event's device check token was already used")
	// ErrDeviceCheckBusy (409 device_check_busy): another call is using the
	// token right now.
	ErrDeviceCheckBusy = errors.New("fingerly: the event's device check token is being used")
	// ErrCredentialUnavailable (409 credential_unavailable): the project's
	// Apple key is missing, refused by Apple, or has DeviceCheck off. The
	// token is kept.
	ErrCredentialUnavailable = errors.New("fingerly: the project's Apple credential is unavailable")
	// ErrBitsRequired (422 bits_required): a write named neither bit.
	ErrBitsRequired = errors.New("fingerly: name bit0, bit1 or both")
	// ErrAppleRejected (422 apple_rejected): Apple rejected the token, which
	// is now used. APIError.AppleStatus holds Apple's HTTP status.
	ErrAppleRejected = errors.New("fingerly: Apple rejected the device check request")
	// ErrDeviceCheckUnavailable (503 device_check_unavailable): Apple or
	// Fingerly's storage could not answer, after the SDK's own retries. The
	// token is kept; retry the same call within the hour.
	ErrDeviceCheckUnavailable = errors.New("fingerly: device check is unavailable just now")
)

The DeviceCheck answers, one sentinel per code. Compare with errors.Is; the concrete error is always an *APIError, except ErrBitsRequired, which a write naming neither bit returns before anything is sent.

View Source
var ErrEventAlreadyConsumed = errors.New("fingerly: event already consumed")

ErrEventAlreadyConsumed matches a consume of an event that was already consumed (409 event_already_consumed). Compare with errors.Is; the concrete error is an *EventAlreadyConsumedError, which also matches *APIError with errors.As.

View Source
var ErrEventNotFound = errors.New("fingerly: event not found")

ErrEventNotFound matches a read for an event that does not exist: the request id was never issued for this key's environment, or the event is past retention. An event that is still being recorded matches ErrEventPending instead.

Compare with errors.Is; the concrete error is always an *APIError.

View Source
var ErrEventPending = errors.New("fingerly: event pending")

ErrEventPending matches a read for an event whose request id was accepted but which is not recorded yet (404 event_pending). It is not a verdict: try again after APIError.RetryAfter seconds, or verify asynchronously. The SDK never retries on its own.

Compare with errors.Is; the concrete error is always an *APIError.

View Source
var ErrInvalidRequestID = errors.New("fingerly: request id is not a Fingerly request id")

ErrInvalidRequestID is returned by EventsService.Get, before any request is made, for a request id that cannot name one event: the empty string, "." or "..". The id usually comes from the browser, so treat it as bad input.

View Source
var ErrInvalidVerifyOptions = errors.New("fingerly: invalid verify options")

ErrInvalidVerifyOptions is returned by EventsService.Verify, before any request is made, for a negative MaxAgeSeconds or an empty Tag. Compare with errors.Is.

View Source
var ErrResponseTooLarge = errors.New("fingerly: response body exceeds 4 MiB")

ErrResponseTooLarge is returned for an API answer over 4 MiB, which no event read produces. The body is not read past the limit.

View Source
var ErrTimeout = errors.New("fingerly: request timed out")

ErrTimeout matches a read whose deadline passed, whether the caller's or WithTimeout's. Compare with errors.Is.

Functions

func Bool added in v0.3.0

func Bool(v bool) *bool

Bool returns a pointer to v, for DeviceCheckWrite.

func VerifyWebhook

func VerifyWebhook(secret string, payload []byte, timestamp, signature string, opts ...WebhookOption) bool

VerifyWebhook reports whether a delivery came from Fingerly and is recent.

Pass the exact bytes received, before any JSON decoding: re-encoding them changes the digest. During a signing-secret rotation Fingerly sends several comma-separated signatures, and any one of the first 32 matching is accepted.

body, _ := io.ReadAll(r.Body)
ok := fingerly.VerifyWebhook(secret, body,
	r.Header.Get("X-Fingerly-Timestamp"),
	r.Header.Get("X-Fingerly-Signature"))

Verification proves authenticity and freshness. It does not deduplicate, so persist processed WebhookEvent.ID values as well.

Malformed or missing input is a false result, never a panic.

Example

Verify the raw bytes before decoding them: re-encoding changes the digest.

package main

import (
	"encoding/json"
	"io"
	"net/http"
	"os"

	fingerly "github.com/fingerly-io/fingerly-go"
)

func main() {
	http.HandleFunc("/webhooks/fingerly", func(w http.ResponseWriter, r *http.Request) {
		body, err := io.ReadAll(r.Body)
		if err != nil {
			http.Error(w, "unreadable body", http.StatusBadRequest)
			return
		}
		if !fingerly.VerifyWebhook(
			os.Getenv("FINGERLY_WEBHOOK_SECRET"),
			body,
			r.Header.Get("X-Fingerly-Timestamp"),
			r.Header.Get("X-Fingerly-Signature"),
		) {
			http.Error(w, "invalid signature", http.StatusBadRequest)
			return
		}

		var event fingerly.WebhookEvent
		if err := json.Unmarshal(body, &event); err != nil {
			http.Error(w, "unreadable event", http.StatusBadRequest)
			return
		}
		// Deduplicate on the event ID: a delivery may arrive more than once.
		enqueue(event.ID, body)
		w.WriteHeader(http.StatusNoContent)
	})
}

func enqueue(id string, body []byte) {}

Types

type APIError

type APIError struct {
	// Status is the HTTP status code.
	Status int
	// Code is the stable machine-readable code, such as "event_not_found".
	Code string
	// Details carries extra context; its shape depends on Code.
	Details any
	// RequestID is the server-side trace id to quote in support requests.
	RequestID string
	// RetryAfter is how many seconds the API asked the caller to wait, from
	// its Retry-After header, or nil when it sent none. The SDK never retries
	// a read itself.
	RetryAfter *int
	// AppleStatus is Apple's HTTP status on an apple_rejected answer from a
	// DeviceCheck call, read from the details entry named apple_status, and 0
	// on any other error.
	AppleStatus int
	// contains filtered or unexported fields
}

APIError is returned for any non-2xx response from the Fingerly API.

The message carries only the HTTP status. Response bodies are never echoed, and any occurrence of the secret key in the metadata is redacted.

Match it with errors.As:

var apiErr *fingerly.APIError
if errors.As(err, &apiErr) && apiErr.Status == http.StatusNotFound {
	// ...
}
Example

Decide on the server's verdict, never on a score the browser supplied.

package main

import (
	"context"
	"errors"
	"fmt"
	"log"
	"net/http"
	"os"
	"time"

	fingerly "github.com/fingerly-io/fingerly-go"
)

func main() {
	client := fingerly.New(os.Getenv("FINGERLY_SECRET_KEY"))

	decide := func(ctx context.Context, orderID, requestID string) (string, error) {
		event, err := client.Events.Get(ctx, requestID)
		var apiErr *fingerly.APIError
		switch {
		case errors.Is(err, fingerly.ErrEventPending):
			// Not decided yet, not fraud: retry after apiErr.RetryAfter
			// seconds or verify asynchronously.
			return "pending", nil
		case errors.As(err, &apiErr) && apiErr.Status == http.StatusNotFound:
			return "refuse", nil
		case err != nil:
			return "", err
		}

		if event.Tag != "checkout:"+orderID || time.Since(event.OccurredAt) > 2*time.Minute {
			return "refuse", nil
		}
		// An unscored event is not a clean one; treat it as unknown.
		if !event.Scored() {
			return "challenge", nil
		}
		switch event.SuspectLevel {
		case fingerly.SuspectLevelHigh:
			return "review", nil
		case fingerly.SuspectLevelMedium:
			return "challenge", nil
		}
		return "allow", nil
	}

	verdict, err := decide(context.Background(), "8412", "01a0a84b-e6a2-7c09-9f51-0b3d7a26c8e4")
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(verdict)
}

func (*APIError) Error

func (e *APIError) Error() string

Error implements error. It reports the status only, never the body.

func (*APIError) Is

func (e *APIError) Is(target error) bool

Is reports whether this error matches a sentinel, so a caller can write errors.Is(err, fingerly.ErrEventNotFound) or errors.Is(err, fingerly.ErrDeviceCheckSpent) without unwrapping the status.

type AnonymityNetwork added in v0.4.0

type AnonymityNetwork string

AnonymityNetwork is the kind of network that hid the visitor's address. An ordinary consumer connection has none, which Event reports as "".

const (
	AnonymityNetworkTor     AnonymityNetwork = "tor"
	AnonymityNetworkRelay   AnonymityNetwork = "relay"
	AnonymityNetworkVPN     AnonymityNetwork = "vpn"
	AnonymityNetworkProxy   AnonymityNetwork = "proxy"
	AnonymityNetworkHosting AnonymityNetwork = "hosting"
)

type AttestSkippedReason added in v0.4.0

type AttestSkippedReason string

AttestSkippedReason is the app's own reason for sending no hardware attestation. Diagnostic only: it never lowers the score.

const (
	// AttestSkippedNotOffered means the challenge offered no attestation: on iOS
	// the SDK key has no Apple app ID for App Attest, on Android the app's
	// transport returned no challenge offer.
	AttestSkippedNotOffered AttestSkippedReason = "not_offered"
	// AttestSkippedUnsupported means the device cannot make an attested key: App
	// Attest is not supported on the iOS device, or Android is older than 7.0
	// (API 24).
	AttestSkippedUnsupported AttestSkippedReason = "unsupported"
	// AttestSkippedChallengeUnavailable means there was no usable challenge
	// ticket: the challenge request failed, or on Android the ticket it
	// returned was malformed.
	AttestSkippedChallengeUnavailable AttestSkippedReason = "challenge_unavailable"
	// AttestSkippedKeyError means the platform key store failed to create, attest
	// or sign with the key, or on Android the stored key record could not be
	// read.
	AttestSkippedKeyError AttestSkippedReason = "key_error"
	// AttestSkippedTimeout means attestation did not finish in time: a key store
	// call ran past its budget, or another identification held the
	// attestation step too long.
	AttestSkippedTimeout AttestSkippedReason = "timeout"
	// AttestSkippedBackoff means the server rejected a new key from this install
	// (on iOS, also when it asked for a replacement), and the SDK is waiting
	// out a backoff before it registers another.
	AttestSkippedBackoff AttestSkippedReason = "backoff"
	// AttestSkippedInstallUnavailable means the report has no usable install ID,
	// or on iOS the stored key record could not be read or saved.
	AttestSkippedInstallUnavailable AttestSkippedReason = "install_unavailable"
)

type Attestation added in v0.3.0

type Attestation struct {
	// State is AttestationStateAttested, AttestationStateNotAttested or
	// AttestationStateFailed.
	State    AttestationState `json:"state"`
	Platform string           `json:"platform,omitempty"`
	// Status is AttestationStatusVerified, AttestationStatusIndeterminate,
	// AttestationStatusInvalid, AttestationStatusAbsent or
	// AttestationStatusUnconfigured.
	Status AttestationStatus `json:"status"`
	Reason string            `json:"reason,omitempty"`

	ChainLength              int    `json:"chain_length,omitempty"`
	AttestationSecurityLevel string `json:"attestation_security_level,omitempty"`
	KeyMintSecurityLevel     string `json:"keymint_security_level,omitempty"`
	DeviceLocked             *bool  `json:"device_locked,omitempty"`
	VerifiedBootState        string `json:"verified_boot_state,omitempty"`
	Nonce                    string `json:"nonce,omitempty"`
	RevocationChecked        bool   `json:"revocation_checked"`
	PackageBound             bool   `json:"package_bound"`
	SignerBound              bool   `json:"signer_bound"`

	// AttestSkipped is the app's own reason for sending no attestation, such
	// as AttestSkippedNotOffered, AttestSkippedUnsupported or
	// AttestSkippedTimeout. Diagnostic only; it never lowers the score.
	AttestSkipped AttestSkippedReason `json:"attest_skipped,omitempty"`
	// Downgrade is true when an unproven or rejected report named an install
	// an attested device owns, so it was answered unidentifiable.
	Downgrade bool `json:"downgrade,omitempty"`

	Mode        string `json:"mode,omitempty"`
	AppID       string `json:"app_id,omitempty"`
	Environment string `json:"environment,omitempty"`

	Receipt        string          `json:"receipt,omitempty"`
	RiskMetric     *int            `json:"risk_metric,omitempty"`
	RiskMetricAgeH *int            `json:"risk_metric_age_h,omitempty"`
	DeviceCheck    string          `json:"device_check,omitempty"`
	PlayIntegrity  json.RawMessage `json:"play_integrity,omitempty"`
}

Attestation is the platform-neutral hardware attestation verdict inside an archived event document.

type AttestationState added in v0.4.0

type AttestationState string

AttestationState is the server's single verdict on a native event's hardware evidence.

const (
	AttestationStateAttested    AttestationState = "attested"
	AttestationStateNotAttested AttestationState = "not_attested"
	AttestationStateFailed      AttestationState = "failed"
)

type AttestationStatus added in v0.4.0

type AttestationStatus string

AttestationStatus is the detail behind an AttestationState.

const (
	AttestationStatusVerified      AttestationStatus = "verified"
	AttestationStatusIndeterminate AttestationStatus = "indeterminate"
	AttestationStatusInvalid       AttestationStatus = "invalid"
	AttestationStatusAbsent        AttestationStatus = "absent"
	AttestationStatusUnconfigured  AttestationStatus = "unconfigured"
)

type Client

type Client struct {
	// Events reads stored events under this client's secret key.
	Events *EventsService
	// DeviceCheck spends an iOS event's held DeviceCheck token to read or
	// write the device's two bits.
	DeviceCheck *DeviceCheckService
	// contains filtered or unexported fields
}

Client reads events for one organization and environment.

Build one with New and reuse it: it holds a pooled HTTP connection and is safe for concurrent use.

func New

func New(secretKey string, opts ...Option) *Client

New builds a client for a server-only secret key, fly_sk_{environment}_…, whose prefix selects the environment read.

New never returns an error, so it composes in a package-level var. An invalid key or option is reported by the first call made on the client, before any request is sent.

Example

Build one client and reuse it: it holds a pooled connection and is safe for concurrent use.

package main

import (
	"context"
	"fmt"
	"log"
	"os"

	fingerly "github.com/fingerly-io/fingerly-go"
)

func main() {
	client := fingerly.New(os.Getenv("FINGERLY_SECRET_KEY"))

	event, err := client.Events.Get(context.Background(), "01a0a84b-e6a2-7c09-9f51-0b3d7a26c8e4")
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(event.VisitorID, event.SuspectLevel)
}

func (Client) Format

func (c Client) Format(f fmt.State, _ rune)

Format keeps the secret key out of every fmt verb. Without it, fmt prints the struct's unexported fields, key included, for %v, %+v, %#v and %s.

type Confidence added in v0.4.0

type Confidence string

Confidence is how sure one detection is.

const (
	ConfidenceLow    Confidence = "low"
	ConfidenceMedium Confidence = "medium"
	ConfidenceHigh   Confidence = "high"
)

type ConnectionError

type ConnectionError struct {
	// Timeout reports whether a deadline passed.
	Timeout bool
	// contains filtered or unexported fields
}

ConnectionError reports a read that got no complete answer from the API: the connection was refused, reset or timed out, or the body broke off. Its message names neither the secret key nor the endpoint; the transport error stays reachable through errors.Unwrap for a caller that wants it.

errors.Is(err, fingerly.ErrTimeout) is true when Timeout is, and the cause stays reachable, so errors.Is(err, context.Canceled) still works.

func (*ConnectionError) Error

func (e *ConnectionError) Error() string

Error implements error.

func (*ConnectionError) Is

func (e *ConnectionError) Is(target error) bool

Is matches ErrTimeout for a timed-out read.

func (*ConnectionError) Unwrap

func (e *ConnectionError) Unwrap() error

Unwrap returns the cause.

type ConsumeResult added in v0.3.0

type ConsumeResult struct {
	RequestID string `json:"request_id"`
	// ConsumedAt is when the event was consumed, RFC 3339 as the API sent it.
	ConsumedAt string `json:"consumed_at"`
	// First is true on the call that consumed the event.
	First bool `json:"first"`
}

ConsumeResult is the answer to a first consume of an event.

type DeviceCheckBits added in v0.3.0

type DeviceCheckBits struct {
	// Found is false when Apple holds no bits for the device yet; both bits
	// are then false.
	Found bool `json:"found"`
	Bit0  bool `json:"bit0"`
	Bit1  bool `json:"bit1"`
	// LastUpdate is when the bits last changed, as YYYY-MM, or empty.
	LastUpdate string `json:"last_update,omitempty"`
}

DeviceCheckBits is what Apple holds for the device behind an event.

type DeviceCheckService added in v0.3.0

type DeviceCheckService struct {
	// contains filtered or unexported fields
}

DeviceCheckService spends the Apple DeviceCheck token that Fingerly holds for an iOS event, for one hour after the identification, to read or to write the device's two bits. Reach it as client.DeviceCheck.

Apple treats a token as single-use: each held token pays for one call, a read or a write, never both. To read and then mark a device, read on one identification and write on the next.

func (*DeviceCheckService) Query added in v0.3.0

func (s *DeviceCheckService) Query(ctx context.Context, requestID string) (*DeviceCheckBits, error)

Query spends the event's held token to read the device's two bits.

Errors match ErrDeviceCheckNotHeld, ErrDeviceCheckSpent, ErrDeviceCheckBusy, ErrCredentialUnavailable, ErrAppleRejected or ErrDeviceCheckUnavailable with errors.Is. A 503 or a call that got no complete answer is retried, with the identical request, up to twice.

Example

A once-per-device free trial on iOS spends two identifications, because Apple treats each DeviceCheck token as single-use: read the bits on the identification that asks for the trial, record the grant in your own data, then write the bit on the device's next identification.

package main

import (
	"context"
	"errors"
	"fmt"
	"log"
	"os"

	fingerly "github.com/fingerly-io/fingerly-go"
)

func main() {
	client := fingerly.New(os.Getenv("FINGERLY_SECRET_KEY"))
	ctx := context.Background()

	// 1. The identification that asks for the trial.
	bits, err := client.DeviceCheck.Query(ctx, "01a0a84b-e6a2-7c09-9f51-0b3d7a26c8e4")
	switch {
	case errors.Is(err, fingerly.ErrDeviceCheckNotHeld), errors.Is(err, fingerly.ErrDeviceCheckSpent):
		// No answer, not a verdict: decide on your own records alone.
	case err != nil:
		log.Fatal(err)
	case bits.Found && bits.Bit0:
		fmt.Println("this device already had a trial")
		return
	}
	// 2. Grant the trial and record it in your own data, with the device
	// not yet marked.

	// 3. The next identification from that install marks the device.
	if _, err := client.DeviceCheck.Write(ctx, "01a0a84b-f1c3-7d10-8a62-1c4e8b37d9f5",
		fingerly.DeviceCheckWrite{Bit0: fingerly.Bool(true)}); err != nil {
		// Keep the device unmarked and write again on a later identification.
		log.Print(err)
	}
}

func (*DeviceCheckService) Write added in v0.3.0

Write spends the event's held token to set bit0, bit1 or both. A write naming neither bit returns ErrBitsRequired without sending anything.

Errors are the same as for Query, plus ErrBitsRequired. A 503 or a call that got no complete answer is retried, with the identical request, up to twice.

type DeviceCheckWrite added in v0.3.0

type DeviceCheckWrite struct {
	Bit0 *bool `json:"bit0,omitempty"`
	Bit1 *bool `json:"bit1,omitempty"`
}

DeviceCheckWrite names the bits to set. A nil bit keeps its value; at least one must be set. fingerly.Bool makes the pointer.

type DeviceCheckWriteResult added in v0.3.0

type DeviceCheckWriteResult struct {
	Bit0 *bool `json:"bit0,omitempty"`
	Bit1 *bool `json:"bit1,omitempty"`
}

DeviceCheckWriteResult repeats the bits Apple accepted; a bit left out of the write is nil.

type Environment added in v0.4.0

type Environment string

Environment is the deployment an event was recorded in, set by the key that submitted it.

const (
	EnvironmentProduction  Environment = "production"
	EnvironmentStaging     Environment = "staging"
	EnvironmentDevelopment Environment = "development"
)

type Event

type Event struct {
	RequestID string `json:"request_id"`
	// ProjectID is the Fingerly project the event belongs to. Empty when the
	// server predates projects and did not send it.
	ProjectID string `json:"project_id,omitempty"`
	// VisitorID is the stable project-scoped visitor identifier, or "" when
	// the submission was unidentifiable (identifiable == false).
	VisitorID  string    `json:"visitor_id"`
	OccurredAt time.Time `json:"occurred_at"`
	// State is EventStateEnriched, or EventStateUnavailable when the network
	// lookup could not run.
	State EventState `json:"state"`
	// Reason explains why enrichment did not happen on an unavailable event.
	Reason string `json:"reason,omitempty"`

	// Environment is the deployment the event was recorded in.
	Environment Environment `json:"environment"`
	// Platform is the scoring profile applied; SDKPlatform is what the SDK
	// called itself. They differ: react-native-ios reports itself as such and
	// is scored as RiskPlatformIOS.
	Platform    RiskPlatform `json:"platform"`
	SDKPlatform string       `json:"sdk_platform"`
	SDKVersion  string       `json:"sdk_version"`

	Origin  string `json:"origin,omitempty"`
	URLHost string `json:"url_host,omitempty"`
	URLPath string `json:"url_path,omitempty"`
	// Tag is your own reference, as the client sent it.
	Tag string `json:"tag,omitempty"`

	// IPNetwork is the network the request came from: an IPv4 /24 or an IPv6
	// /40, such as 203.0.113.0/24. The API never returns the address itself.
	// Empty when unknown.
	IPNetwork   string `json:"ip_network,omitempty"`
	CountryCode string `json:"country_code,omitempty"`
	CountryName string `json:"country_name,omitempty"`
	ASN         string `json:"asn,omitempty"`
	ASNName     string `json:"asn_name,omitempty"`
	// AnonymityNetwork is AnonymityNetworkTor, AnonymityNetworkRelay,
	// AnonymityNetworkVPN, AnonymityNetworkProxy or AnonymityNetworkHosting.
	// Empty on an ordinary consumer connection, which is most of them.
	AnonymityNetwork AnonymityNetwork `json:"anonymity_network,omitempty"`

	Agent        string `json:"agent,omitempty"`
	AgentVersion string `json:"agent_version,omitempty"`
	OS           string `json:"os,omitempty"`
	DeviceKind   string `json:"device_kind,omitempty"`
	VisitorKind  string `json:"visitor_kind,omitempty"`

	// SuspectScore is nil when the request was not scored. Never read nil as 0.
	SuspectScore *int `json:"suspect_score"`
	// SuspectLevel is SuspectLevelLow, SuspectLevelMedium or
	// SuspectLevelHigh. Empty when not scored.
	SuspectLevel SuspectLevel `json:"suspect_level,omitempty"`

	// Triggers is never nil from the API: an event about which nothing fired
	// carries an empty list.
	Triggers []EventTrigger `json:"triggers"`

	// HasDocument says whether the full submission was archived.
	HasDocument bool `json:"has_document"`

	// Document is an allow-listed view of the archived submission: schema,
	// request id, time, SDK platform and version, IP network, the classified
	// IP (network, city-level location, detections) or IP error, risk,
	// attestation and velocity flags. It carries no raw signals, no user agent
	// and no IP address. Present when HasDocument is true and the archive could
	// be read. Its contents are deliberately opaque, not a public contract.
	Document json.RawMessage `json:"document,omitempty"`

	// Raw is the response body exactly as it arrived, so a field the API adds
	// after this SDK was released is still reachable without an upgrade.
	Raw json.RawMessage `json:"-"`
}

Event is a stored identification event.

SuspectScore is a pointer because nil means unscored, which must not be read as zero: an ordinary visitor about whom nothing fired scores 0, while a submission that was never enriched has no score at all.

func (*Event) Identifiable added in v0.3.0

func (e *Event) Identifiable() bool

Identifiable reports whether the event resolved to a visitor identifier.

func (*Event) ParseDocument added in v0.3.0

func (e *Event) ParseDocument() (*EventDocument, error)

ParseDocument decodes Event.Document into a typed EventDocument when present.

func (*Event) Score

func (e *Event) Score() (int, bool)

Score returns the suspect score and whether the event was scored at all.

score, ok := event.Score()
if !ok { /* unscored, decide on something else */ }

func (*Event) Scored

func (e *Event) Scored() bool

Scored reports whether the API assigned this event a suspect score.

Prefer it to a nil check: it states the question being asked.

type EventAlreadyConsumedError added in v0.3.0

type EventAlreadyConsumedError struct {
	*APIError
	// ConsumedAt is when the event was first consumed, RFC 3339 as the API
	// sent it, or "" when the answer did not say.
	ConsumedAt string
}

EventAlreadyConsumedError is returned by EventsService.Consume for an event that was already consumed (409 event_already_consumed). It carries everything the *APIError does, which errors.As also reaches, plus when the event was first consumed.

var consumed *fingerly.EventAlreadyConsumedError
if errors.As(err, &consumed) {
	// consumed.ConsumedAt, consumed.Status (409), consumed.Code
}

func (*EventAlreadyConsumedError) Unwrap added in v0.3.0

func (e *EventAlreadyConsumedError) Unwrap() error

Unwrap returns the underlying *APIError.

type EventDocument added in v0.3.0

type EventDocument struct {
	Schema      int              `json:"schema"`
	RequestID   string           `json:"request_id"`
	OccurredAt  time.Time        `json:"occurred_at"`
	SDK         EventDocumentSDK `json:"sdk"`
	IPNetwork   string           `json:"ip_network,omitempty"`
	IP          json.RawMessage  `json:"ip,omitempty"`
	IPError     string           `json:"ip_error,omitempty"`
	Risk        *EventRiskReport `json:"risk,omitempty"`
	Attestation *Attestation     `json:"attestation,omitempty"`
	Velocity    json.RawMessage  `json:"velocity,omitempty"`
}

EventDocument is the allow-listed view of an archived identification submission returned when Event.HasDocument is true.

type EventDocumentSDK added in v0.3.0

type EventDocumentSDK struct {
	Platform string `json:"platform"`
	Version  string `json:"version"`
}

EventDocumentSDK identifies the client SDK recorded in an archived document.

type EventListParams

type EventListParams struct {
	// From and To bound the window. The default is the last 24 hours; it may
	// be at most 30 days wide and start at most 30 days ago.
	From time.Time
	To   time.Time
	// Page is one-based. Limit is capped at 200 by the server.
	Page  int
	Limit int
	// Visitor restricts the listing to one exact visitor id.
	Visitor string
	// Level restricts it to SuspectLevelLow, SuspectLevelMedium or
	// SuspectLevelHigh.
	Level SuspectLevel
}

EventListParams filters a listing. A zero field is not sent, so the server applies its own default.

type EventPage

type EventPage struct {
	Rows     []Event `json:"rows"`
	Page     int     `json:"page"`
	PageSize int     `json:"page_size"`

	// Raw is the response body exactly as it arrived.
	Raw json.RawMessage `json:"-"`
}

EventPage is one page of events, newest first.

type EventRiskReport added in v0.3.0

type EventRiskReport struct {
	Platform  RiskPlatform       `json:"platform"`
	Score     int                `json:"score"`
	Level     SuspectLevel       `json:"level"`
	Threshold int                `json:"threshold"`
	Source    RiskSource         `json:"source"`
	Revision  int64              `json:"revision,omitempty"`
	Triggers  []EventRiskTrigger `json:"triggers"`
}

EventRiskReport is the scoring assessment recorded inside an archived document.

type EventRiskTrigger added in v0.3.0

type EventRiskTrigger struct {
	// Signal is the raw detector, such as SignalVPNPublic.
	Signal     Signal     `json:"signal"`
	Weight     int        `json:"weight"`
	Confidence Confidence `json:"confidence,omitempty"`
	Reason     string     `json:"reason,omitempty"`
}

EventRiskTrigger is one raw detector recorded inside an archived risk report.

type EventState added in v0.4.0

type EventState string

EventState says whether an event was enriched.

const (
	// EventStatePending is accepted and not written yet. A read answers it
	// with ErrEventPending rather than an event, so a read Event is never in
	// it.
	EventStatePending EventState = "pending"
	// EventStateEnriched is an event whose network lookup ran.
	EventStateEnriched EventState = "enriched"
	// EventStateUnavailable is an event whose network lookup could not run;
	// Event.Reason says why.
	EventStateUnavailable EventState = "unavailable"
)

type EventTrigger

type EventTrigger struct {
	// Signal is the signal group, such as SignalVPN, SignalBot or
	// SignalAttestationFailed.
	Signal Signal `json:"signal"`
	// Weight is the group's combined weight in this score.
	Weight int `json:"weight"`
	// Confidence is ConfidenceLow, ConfidenceMedium or ConfidenceHigh.
	Confidence Confidence `json:"confidence,omitempty"`
}

EventTrigger is one signal group that contributed to an event's score.

type EventsService

type EventsService struct {
	// contains filtered or unexported fields
}

EventsService reads events stored for the organization and environment of the client's secret key. Reach it as client.Events.

func (*EventsService) Consume added in v0.3.0

func (s *EventsService) Consume(ctx context.Context, requestID string) (*ConsumeResult, error)

Consume marks an event as used, once, so it can back only one decision. It is a POST with no body and is never retried.

Consuming an event a second time returns an *EventAlreadyConsumedError, which matches ErrEventAlreadyConsumed with errors.Is and carries when it was first consumed. An unknown event matches ErrEventNotFound. An invalid request id returns ErrInvalidRequestID without sending anything.

func (EventsService) Format

func (s EventsService) Format(f fmt.State, _ rune)

Format keeps the client's key out of every fmt verb; the service holds the client in an unexported field, which fmt prints without its methods.

func (*EventsService) Get

func (s *EventsService) Get(ctx context.Context, requestID string) (*Event, error)

Get fetches one event by request id.

An error matching ErrEventPending means the request id was accepted but the event is not recorded yet; APIError.RetryAfter says when to try again. One matching ErrEventNotFound means it was never issued or is past retention. Neither is retried.

An empty request id, "." or ".." returns ErrInvalidRequestID without sending anything.

func (*EventsService) List

func (s *EventsService) List(ctx context.Context, params *EventListParams) (*EventPage, error)

List returns events within the retention window, newest first.

A nil params, or a zero field within it, leaves that filter unset so the server applies its own default.

Example

A zero field is not sent, so the server applies its own default.

package main

import (
	"context"
	"fmt"
	"log"
	"os"
	"time"

	fingerly "github.com/fingerly-io/fingerly-go"
)

func main() {
	client := fingerly.New(os.Getenv("FINGERLY_SECRET_KEY"))

	page, err := client.Events.List(context.Background(), &fingerly.EventListParams{
		Level: fingerly.SuspectLevelHigh,
		Limit: 50,
		From:  time.Now().Add(-24 * time.Hour),
	})
	if err != nil {
		log.Fatal(err)
	}
	for _, event := range page.Rows {
		fmt.Println(event.RequestID, event.IPNetwork)
	}
}

func (*EventsService) Verify added in v0.3.0

func (s *EventsService) Verify(ctx context.Context, requestID string, opts *VerifyOptions) (*VerifyResult, error)

Verify reads an event and checks, in this order, stopping at the first failure, that it exists, is no older than MaxAgeSeconds, carries Tag when one is given, is identifiable and is scored. When every check passes it consumes the event, unless SkipConsume is set, so one event backs one decision; an event consumed before reports VerifyAlreadyConsumed.

A failed check is a VerifyResult, not an error. Any other failure, including ErrEventPending, a rate limit, a server error or a timeout, is returned unchanged as the error. Verify never reads the score's value, the level or the triggers: that policy stays with the caller.

A negative MaxAgeSeconds or an empty Tag returns ErrInvalidVerifyOptions, and an invalid request id ErrInvalidRequestID, without sending anything.

Example

Verify checks the event and consumes it last, so a replayed request id fails with already_consumed. The score policy stays with the caller.

package main

import (
	"context"
	"errors"
	"fmt"
	"log"
	"os"

	fingerly "github.com/fingerly-io/fingerly-go"
)

func main() {
	client := fingerly.New(os.Getenv("FINGERLY_SECRET_KEY"))

	tag := "checkout"
	result, err := client.Events.Verify(context.Background(), "01a0a84b-e6a2-7c09-9f51-0b3d7a26c8e4",
		&fingerly.VerifyOptions{Tag: &tag})
	switch {
	case errors.Is(err, fingerly.ErrEventPending):
		// Not a verdict: ask the caller to try again shortly.
	case err != nil:
		log.Fatal(err)
	case !result.OK:
		fmt.Println("refused:", result.Reason)
	case result.Event.SuspectLevel == fingerly.SuspectLevelHigh:
		fmt.Println("refused: high risk")
	default:
		fmt.Println("allowed")
	}
}

type Option

type Option func(*clientConfig)

Option configures a Client. Pass options to New.

func WithAPIVersion

func WithAPIVersion(version string) Option

WithAPIVersion selects a route version, such as "v2". The default is "v1", and the server must support whichever is chosen.

func WithAllowInsecureLoopback added in v0.3.0

func WithAllowInsecureLoopback() Option

WithAllowInsecureLoopback accepts a plain http:// endpoint on 127.0.0.1, localhost or [::1], for a local test harness only. Any other http:// host is refused with or without it.

func WithEndpoint

func WithEndpoint(endpoint string) Option

WithEndpoint overrides the default API origin, for a local or self-hosted API. It must be a bare https:// origin: scheme, host and optional port, with no path, query, fragment, credentials, space or control byte. The key still decides which kind of key is accepted.

func WithHTTPClient

func WithHTTPClient(httpClient *http.Client) Option

WithHTTPClient supplies the HTTP client, for a custom transport or for tests.

The client is copied and its CheckRedirect replaced, so a redirect can never replay the secret key to another host. Its Transport is used as given; a nil Transport means the SDK's shared connection pool rather than http.DefaultTransport, which keeps too few idle connections for a busy server.

func WithTimeout

func WithTimeout(timeout time.Duration) Option

WithTimeout sets the deadline for each request, covering the response body. The default is 10 seconds. A deadline already on the caller's context still applies, whichever is sooner.

type Proxy

type Proxy struct {
	// contains filtered or unexported fields
}

Proxy serves the browser SDK from a path on your own domain, so content blockers cannot refuse its calls as third-party.

It implements http.Handler, so every router built on net/http takes it directly:

proxy, err := fingerly.NewProxy(fingerly.ProxyOptions{
	ProxyKey: os.Getenv("FINGERLY_PROXY_KEY"),
	Path:     "/k7x2qm4a",
	ClientIP: func(r *http.Request) string { return r.Header.Get("X-Real-IP") },
})
mux.Handle("/k7x2qm4a", proxy)

The browser SDK posts both of its calls to that one path, and the proxy forwards each to Fingerly's one ingest URL, never anywhere else and never to event reads: reading events needs a secret key and must stay unreachable from a browser. Customer cookies and authorization headers are never passed on, and nothing relayed back names Fingerly.

func NewProxy

func NewProxy(options ProxyOptions) (*Proxy, error)

NewProxy validates every option and builds the handler.

Unlike New, this reports configuration errors immediately: a proxy is wired up once at start-up, where an error is natural to handle.

Example

The proxy is an http.Handler, so every router takes it directly.

package main

import (
	"log"
	"net"
	"net/http"
	"os"

	fingerly "github.com/fingerly-io/fingerly-go"
)

func main() {
	proxy, err := fingerly.NewProxy(fingerly.ProxyOptions{
		ProxyKey: os.Getenv("FINGERLY_PROXY_KEY"),
		Path:     "/k7x2qm4a",
		ClientIP: func(r *http.Request) string {
			// The header your load balancer or CDN sets. Trust it only when
			// traffic can reach this server through that hop alone; never
			// trust the left-most X-Forwarded-For value, which the visitor
			// writes.
			if address := r.Header.Get("X-Real-IP"); address != "" {
				return address
			}
			host, _, _ := net.SplitHostPort(r.RemoteAddr)
			return host
		},
	})
	if err != nil {
		log.Fatal(err)
	}

	mux := http.NewServeMux()
	mux.Handle("/k7x2qm4a", proxy)
	log.Fatal(http.ListenAndServe(":8080", mux))
}

func (Proxy) Format

func (p Proxy) Format(f fmt.State, _ rune)

Format keeps the proxy key out of every fmt verb. A value receiver, so that printing a dereferenced Proxy is covered too.

func (*Proxy) ServeHTTP

func (p *Proxy) ServeHTTP(w http.ResponseWriter, r *http.Request)

ServeHTTP implements http.Handler.

type ProxyError

type ProxyError struct {
	// Status is what the browser was answered: 502, 504 or 500.
	Status int
	// Err is the kind of failure: a timeout, an unreachable upstream, a TLS
	// failure, an unrelayable status or answer. It never names the upstream
	// host, port or URL.
	Err error
}

ProxyError is an upstream failure the proxy answered for. It never carries a key or a response body.

func (*ProxyError) Error

func (e *ProxyError) Error() string

Error implements error.

func (*ProxyError) Unwrap

func (e *ProxyError) Unwrap() error

Unwrap returns the underlying cause.

type ProxyOptions

type ProxyOptions struct {
	// ProxyKey is a write-only credential, fly_px_…, held only on your server.
	ProxyKey string

	// ClientIP resolves the visitor's address, which must be exactly one IPv4
	// or IPv6 literal. Read it from a header your own infrastructure sets,
	// such as your load balancer's or CDN's, and fall back to the TCP peer in
	// r.RemoteAddr. Never use the left-most X-Forwarded-For value: the visitor
	// writes it. Anything that is not one address is a configuration error:
	// the proxy answers 500 without calling upstream and reports it once.
	ClientIP func(*http.Request) string

	// Path is the path the dashboard issued for this proxy, such as
	// "/k7x2qm4a", matched exactly: any other path gets 404. Leave it empty
	// when the route already sends only that path to the handler, and behind
	// http.StripPrefix, which changes the path the handler sees.
	Path string
	// APIVersion selects the upstream ingest URL. Defaults to "v1".
	APIVersion string
	// Upstream overrides the API origin. It must be a bare https:// origin:
	// scheme, host and optional port, with no path, query, fragment,
	// credentials, space or control byte.
	Upstream string
	// AllowInsecureLoopback accepts a plain http:// Upstream on 127.0.0.1,
	// localhost or [::1], for a local test harness only. Any other http://
	// host is refused whatever this is set to.
	AllowInsecureLoopback bool
	// MaxBodyBytes refuses larger request bodies with 413. Defaults to 1 MiB.
	MaxBodyBytes int64
	// Timeout bounds the upstream call. Defaults to 5 seconds.
	Timeout time.Duration
	// AllowedOrigins lists origins permitted to make cross-origin browser
	// requests to this proxy. Leave empty for same-origin routes.
	AllowedOrigins []string
	// OnError is called once for every request the proxy answered with a 5xx
	// of its own: 504 when the upstream deadline passed, 502 for any other
	// upstream failure, 500 for a ClientIP that returned no valid address.
	// Leave it nil to log one line per failure through slog.Default(). A
	// visitor who disconnects is not a failure and is not reported.
	OnError func(*http.Request, *ProxyError)
	// Transport supplies the upstream round tripper, for tests or a custom
	// HTTP stack. Left nil, the SDK's shared connection pool is used, sized
	// for hundreds of requests in flight. Redirects are never followed either
	// way.
	Transport http.RoundTripper
}

ProxyOptions configures a Proxy. ProxyKey and ClientIP are required.

func (ProxyOptions) Format

func (o ProxyOptions) Format(f fmt.State, _ rune)

Format keeps the keys out of every fmt verb, so logging the options a proxy was built with is safe.

func (ProxyOptions) GobEncode

func (o ProxyOptions) GobEncode() ([]byte, error)

GobEncode refuses to serialise the options: gob skips the callbacks but would copy the keys in the clear.

func (ProxyOptions) MarshalJSON

func (o ProxyOptions) MarshalJSON() ([]byte, error)

MarshalJSON keeps the keys out of JSON, and leaves out the callbacks, which cannot be encoded.

type RiskPlatform added in v0.4.0

type RiskPlatform string

RiskPlatform is the scoring profile an event was scored under. It is coarser than the SDK platform: a React Native app on iOS is scored as RiskPlatformIOS.

const (
	RiskPlatformWeb     RiskPlatform = "web"
	RiskPlatformIOS     RiskPlatform = "ios"
	RiskPlatformAndroid RiskPlatform = "android"
)

type RiskSource added in v0.4.0

type RiskSource string

RiskSource says which risk profile scored an event.

const (
	// RiskSourceKey is the SDK key's own profile.
	RiskSourceKey RiskSource = "key"
	// RiskSourceOrganization is the organization's profile.
	RiskSourceOrganization RiskSource = "organization"
	// RiskSourceDefault is the weights the platform ships with.
	RiskSourceDefault RiskSource = "default"
)

type Signal added in v0.4.0

type Signal string

Signal is a signal group or raw detector identifier. An event's Triggers carry signal groups, the names a console shows, such as SignalVPN; an archived risk report's Triggers carry the raw detectors behind them, such as SignalVPNPublic. Some names, such as SignalDeviceFarm, are both.

const (
	SignalTor                   Signal = "tor"
	SignalDatacenterProxy       Signal = "datacenter_proxy"
	SignalResidentialProxy      Signal = "residential_proxy"
	SignalVPN                   Signal = "vpn"
	SignalIPBlocklist           Signal = "ip_blocklist"
	SignalIPReputation          Signal = "ip_reputation"
	SignalNetworkAnomaly        Signal = "network_anomaly"
	SignalLocationSpoofing      Signal = "location_spoofing"
	SignalIOSSimulator          Signal = "ios_simulator"
	SignalAndroidEmulator       Signal = "android_emulator"
	SignalVirtualMachine        Signal = "virtual_machine"
	SignalJailbrokenDevice      Signal = "jailbroken_device"
	SignalRootedDevice          Signal = "rooted_device"
	SignalClonedApp             Signal = "cloned_app"
	SignalDeviceFarm            Signal = "device_farm"
	SignalMITMAttack            Signal = "mitm_attack"
	SignalFridaDetected         Signal = "frida_detected"
	SignalBrowserTampering      Signal = "browser_tampering"
	SignalFingerprintSuppressed Signal = "fingerprint_suppressed"
	SignalDeveloperTools        Signal = "developer_tools"
	SignalRemoteControl         Signal = "remote_control"
	SignalBot                   Signal = "bot"
	SignalHighActivity          Signal = "high_activity"
	SignalIncognitoMode         Signal = "incognito_mode"
	SignalPrivacySettings       Signal = "privacy_settings"
	SignalEmbeddedWebView       Signal = "embedded_web_view"
	SignalActiveCall            Signal = "active_call"
	SignalAttestationMissing    Signal = "attestation_missing"
	SignalAttestationFailed     Signal = "attestation_failed"
	SignalDeviceInconsistent    Signal = "device_inconsistent"
	SignalReportIncomplete      Signal = "report_incomplete"
	SignalCustomRootCA          Signal = "custom_root_ca"
	SignalSecondaryUserProfile  Signal = "secondary_user_profile"
)

Signal groups, reported on Event.Triggers.

const (
	SignalProxy                            Signal = "proxy"
	SignalDatacenterIP                     Signal = "datacenter_ip"
	SignalResidentialProxyLowConfidence    Signal = "residential_proxy_low_confidence"
	SignalResidentialProxyMediumConfidence Signal = "residential_proxy_medium_confidence"
	SignalResidentialProxyHighConfidence   Signal = "residential_proxy_high_confidence"
	SignalVPNPublic                        Signal = "vpn_public"
	SignalVPNTimezone                      Signal = "vpn_timezone"
	SignalVPNRelay                         Signal = "vpn_relay"
	SignalVPNMobile                        Signal = "vpn_mobile"
	SignalVPNOSMismatch                    Signal = "vpn_os_mismatch"
	SignalVPNLowConfidence                 Signal = "vpn_low_confidence"
	SignalVPNMediumConfidence              Signal = "vpn_medium_confidence"
	SignalVPNHighConfidence                Signal = "vpn_high_confidence"
	SignalIPBlocklistEmailSpam             Signal = "ip_blocklist_email_spam"
	SignalIPBlocklistAttackSource          Signal = "ip_blocklist_attack_source"
	SignalIPAbuser                         Signal = "ip_abuser"
	SignalBogonIP                          Signal = "bogon_ip"
	SignalAnycastIP                        Signal = "anycast_ip"
	SignalGeoMismatch                      Signal = "geo_mismatch"
	SignalSimulator                        Signal = "simulator"
	SignalEmulator                         Signal = "emulator"
	SignalJailbreak                        Signal = "jailbreak"
	SignalRootApps                         Signal = "root_apps"
	SignalPlayDeviceIntegrityFailed        Signal = "play_device_integrity_failed"
	SignalAppCloner                        Signal = "app_cloner"
	SignalPlayAppUnrecognized              Signal = "play_app_unrecognized"
	SignalRepeatedReinstall                Signal = "repeated_reinstall"
	SignalDeviceActivityHigh               Signal = "device_activity_high"
	SignalDeviceActivityVeryHigh           Signal = "device_activity_very_high"
	SignalFrida                            Signal = "frida"
	SignalTampering                        Signal = "tampering"
	SignalAntidetectBrowser                Signal = "antidetect_browser"
	SignalAutomation                       Signal = "automation"
	SignalBadBot                           Signal = "bad_bot"
	SignalFetchMetadataMissing             Signal = "fetch_metadata_missing"
	SignalWebTicketMissing                 Signal = "web_ticket_missing"
	SignalWebTicketInvalid                 Signal = "web_ticket_invalid"
	SignalIncognito                        Signal = "incognito"
	SignalAttestationDowngrade             Signal = "attestation_downgrade"
	SignalProbeErrors                      Signal = "probe_errors"
)

Raw detectors, reported on an archived EventRiskReport. A group above whose name is also a detector, such as SignalTor or SignalDeviceFarm, is not repeated here.

type SuspectLevel added in v0.4.0

type SuspectLevel string

SuspectLevel is the band a suspect score falls into.

const (
	SuspectLevelLow    SuspectLevel = "low"
	SuspectLevelMedium SuspectLevel = "medium"
	SuspectLevelHigh   SuspectLevel = "high"
)

type VerifyOptions added in v0.3.0

type VerifyOptions struct {
	// MaxAgeSeconds is how old, in seconds, the event may be. Zero means
	// DefaultVerifyMaxAge (300); a negative value is an error.
	MaxAgeSeconds int
	// Tag, when not nil, is the tag the event must carry exactly. Nil skips
	// the tag check. An empty tag is an error, because it would match an
	// untagged event.
	Tag *string
	// SkipConsume leaves the event unconsumed after the checks pass. By
	// default Verify consumes it, so one event backs one decision.
	SkipConsume bool
}

VerifyOptions tunes EventsService.Verify. A nil *VerifyOptions, or a zero field within it, takes the default.

type VerifyReason added in v0.3.0

type VerifyReason string

VerifyReason says which check of EventsService.Verify failed. Its values are the API's wire strings; it is "" when every check passed.

const (
	// VerifyReasonOK: every check passed. It is the zero value.
	VerifyReasonOK VerifyReason = ""
	// VerifyNotFound: the event does not exist, or was gone when consumed.
	// VerifyResult.Event is nil.
	VerifyNotFound VerifyReason = "not_found"
	// VerifyTooOld: the event is older than MaxAgeSeconds, or its
	// occurred_at is missing or unreadable.
	VerifyTooOld VerifyReason = "too_old"
	// VerifyTagMismatch: a Tag was asked for and the event's tag differs.
	VerifyTagMismatch VerifyReason = "tag_mismatch"
	// VerifyUnidentifiable: the event has no visitor identifier.
	VerifyUnidentifiable VerifyReason = "unidentifiable"
	// VerifyUnscored: the event has no suspect score.
	VerifyUnscored VerifyReason = "unscored"
	// VerifyAlreadyConsumed: every other check passed, but the event was
	// already consumed, so it already backed a decision.
	VerifyAlreadyConsumed VerifyReason = "already_consumed"
)

The reasons Verify reports, in the order it checks them.

type VerifyResult added in v0.3.0

type VerifyResult struct {
	// OK is true when every check passed and, unless skipped, the event was
	// consumed by this call.
	OK bool
	// Reason is the first check that failed, or "" when OK.
	Reason VerifyReason
	// Event is the event read. It is nil only for VerifyNotFound.
	Event *Event
}

VerifyResult is the outcome of EventsService.Verify.

type WebhookEnvironment added in v0.4.0

type WebhookEnvironment string

WebhookEnvironment is the Environment of a webhook delivery: live for production keys, test for every other environment.

const (
	WebhookEnvironmentLive WebhookEnvironment = "live"
	WebhookEnvironmentTest WebhookEnvironment = "test"
)

type WebhookEvent

type WebhookEvent struct {
	// ID identifies this delivery. Persist it to deduplicate: a webhook may
	// arrive more than once.
	ID string `json:"id"`
	// Type is the event name, such as WebhookIdentificationCompleted.
	Type WebhookEventType `json:"type"`
	// Version is the envelope version.
	Version int `json:"version"`
	// OrganizationID is the organization the event belongs to.
	OrganizationID string `json:"organization_id"`
	// Environment is WebhookEnvironmentLive for production keys and
	// WebhookEnvironmentTest for every other environment.
	Environment WebhookEnvironment `json:"environment"`
	// CreatedAt is when Fingerly recorded the event.
	CreatedAt time.Time `json:"created_at"`
	// Data is the event-specific payload.
	Data json.RawMessage `json:"data"`
}

WebhookEvent is the envelope every webhook delivery shares.

Data holds the event-specific payload, left raw so a new event type needs no SDK upgrade. Unmarshal it into the shape the event documents.

type WebhookEventType added in v0.4.0

type WebhookEventType string

WebhookEventType is the Type of a webhook delivery.

const (
	WebhookIdentificationCompleted WebhookEventType = "identification.completed"
	WebhookIdentificationRefused   WebhookEventType = "identification.refused"
	WebhookVisitorSuspect          WebhookEventType = "visitor.suspect"
	WebhookBillingStatusChanged    WebhookEventType = "billing.status_changed"
	WebhookUsageDailySettled       WebhookEventType = "usage.daily_settled"
	// WebhookTest is sent when a test delivery is requested for one endpoint.
	// Nobody subscribes to it.
	WebhookTest WebhookEventType = "webhook.test"
)

type WebhookOption

type WebhookOption func(*webhookConfig)

WebhookOption configures VerifyWebhook.

func WithWebhookTime

func WithWebhookTime(now time.Time) WebhookOption

WithWebhookTime fixes the current time. Override it only in tests.

func WithWebhookTolerance

func WithWebhookTolerance(tolerance time.Duration) WebhookOption

WithWebhookTolerance sets the replay window. The default is five minutes.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL