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 ¶
- Constants
- Variables
- func Bool(v bool) *bool
- func VerifyWebhook(secret string, payload []byte, timestamp, signature string, ...) bool
- type APIError
- type AnonymityNetwork
- type AttestSkippedReason
- type Attestation
- type AttestationState
- type AttestationStatus
- type Client
- type Confidence
- type ConnectionError
- type ConsumeResult
- type DeviceCheckBits
- type DeviceCheckService
- type DeviceCheckWrite
- type DeviceCheckWriteResult
- type Environment
- type Event
- type EventAlreadyConsumedError
- type EventDocument
- type EventDocumentSDK
- type EventListParams
- type EventPage
- type EventRiskReport
- type EventRiskTrigger
- type EventState
- type EventTrigger
- type EventsService
- func (s *EventsService) Consume(ctx context.Context, requestID string) (*ConsumeResult, error)
- func (s EventsService) Format(f fmt.State, _ rune)
- func (s *EventsService) Get(ctx context.Context, requestID string) (*Event, error)
- func (s *EventsService) List(ctx context.Context, params *EventListParams) (*EventPage, error)
- func (s *EventsService) Verify(ctx context.Context, requestID string, opts *VerifyOptions) (*VerifyResult, error)
- type Option
- type Proxy
- type ProxyError
- type ProxyOptions
- type RiskPlatform
- type RiskSource
- type Signal
- type SuspectLevel
- type VerifyOptions
- type VerifyReason
- type VerifyResult
- type WebhookEnvironment
- type WebhookEvent
- type WebhookEventType
- type WebhookOption
Examples ¶
Constants ¶
const DefaultVerifyMaxAge = 300
DefaultVerifyMaxAge is the age, in seconds, past which Verify reports an event as too old when VerifyOptions.MaxAgeSeconds is zero.
const DefaultWebhookTolerance = 5 * time.Minute
DefaultWebhookTolerance is how far a delivery's timestamp may be from now before it is refused as a replay.
const Version = "0.4.0"
Version is the SDK version, reported to the API on every request.
Variables ¶
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") // 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") // 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.
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.
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.
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.
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.
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.
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.
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 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) {}
Output:
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)
}
Output:
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 AttestSkippedReason = "not_offered" AttestSkippedUnsupported AttestSkippedReason = "unsupported" AttestSkippedKeyError AttestSkippedReason = "key_error" AttestSkippedTimeout AttestSkippedReason = "timeout" AttestSkippedBackoff AttestSkippedReason = "backoff" )
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 ¶
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)
}
Output:
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) Is ¶
func (e *ConnectionError) Is(target error) bool
Is matches ErrTimeout for a timed-out read.
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)
}
}
Output:
func (*DeviceCheckService) Write ¶ added in v0.3.0
func (s *DeviceCheckService) Write(ctx context.Context, requestID string, bits DeviceCheckWrite) (*DeviceCheckWriteResult, error)
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
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.
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
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" // 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 ¶
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)
}
}
Output:
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")
}
}
Output:
type Option ¶
type Option func(*clientConfig)
Option configures a Client. Pass options to New.
func WithAPIVersion ¶
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 ¶
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 ¶
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 ¶
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))
}
Output:
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) 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.
