touchque

package
v6.0.0 Latest Latest
Warning

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

Go to latest
Published: Nov 24, 2026 License: MIT Imports: 44 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Index

Constants

View Source
const (
	IDJAGTokenType     = "urn:ietf:params:oauth:token-type:id-jag"
	IDTokenTokenType   = "urn:ietf:params:oauth:token-type:id_token"
	TokenExchangeGrant = "urn:ietf:params:oauth:grant-type:token-exchange"
	JWTBearerGrant     = "urn:ietf:params:oauth:grant-type:jwt-bearer"
)
View Source
const (
	GuardTokenHeader    = "X-Touchque-Token"
	GuardOfflineHeader  = "X-Touchque-Offline"
	GuardCodeHeader     = "X-Touchque-Code"
	GuardCodeTypeHeader = "X-Touchque-Code-Type"
	// GuardBrowserHeader carries the browser's device-bound key proof
	// (silent sign-ins). Require and the relay read it only when their
	// SilentSignIn option is on.
	GuardBrowserHeader = "X-Touchque-Browser"
)

Guard header names the browser sends back while it waits.

View Source
const (
	FraudChargeback        = "chargeback"
	FraudAccountTakeover   = "account_takeover"
	FraudSocialEngineering = "social_engineering"
	FraudOther             = "other"
)

Fraud reasons accepted by ReportFraud.

View Source
const (
	ReasonUserRejected = "user_rejected"
	// ReasonUserReportedFraud: the user said "this wasn't me"; 2FA is frozen.
	ReasonUserReportedFraud = "user_reported_fraud"
	// ReasonUserReportedCoached: the user said someone on the phone told them
	// to approve; 2FA is frozen. Treat it as a takeover in progress.
	ReasonUserReportedCoached = "user_reported_coached"
	// ReasonUserBlockedAgent: an AI agent's request; the user said no and
	// blocked the agent from asking them again (no 2FA freeze).
	ReasonUserBlockedAgent         = "user_blocked_agent"
	ReasonRiskReversed             = "risk_reversed"
	ReasonRiskStepUp               = "risk_step_up"
	ReasonApprovalSignatureInvalid = "approval_signature_invalid"
	ReasonDeviceIntegrityFailed    = "device_integrity_failed"
	// ReasonVishingSuspected (Vishing Shield): approved during a call (or with
	// the screen shared / remote-controlled), critical, and no passkey.
	ReasonVishingSuspected = "vishing_suspected"
	// ReasonPhishingOrigin (Mirror Alarm): the sign-in page was not on your
	// site (a real-time phishing proxy).
	ReasonPhishingOrigin = "phishing_origin"
)

Reason values of a REJECTED login webhook. Treat a value you do not know as a rejection: new ones are added in minor versions.

View Source
const (
	EventDeviceLinked      = "DEVICE_LINKED"
	EventDeviceUnlinked    = "DEVICE_UNLINKED"
	EventPasskeyRegistered = "PASSKEY_REGISTERED"
	EventPasskeyDeleted    = "PASSKEY_DELETED"
	// EventApprovalReconfirmed: after the call, the user confirmed a
	// provisional approval was theirs; critical actions are allowed again.
	EventApprovalReconfirmed = "APPROVAL_RECONFIRMED"
	// EventApprovalRevoked: the user took an approval back (reason COACHED or
	// UNDO); end the session or stop the action built on it.
	EventApprovalRevoked = "APPROVAL_REVOKED"
	// EventMobilePush (Mobile SDK): send this push to your app with your own
	// APNs / FCM keys (MobilePushFromWebhook).
	EventMobilePush = "MOBILE_PUSH"

	// Never Locked Out (client.Recovery): each step of a recovery. Read
	// Recovery.Status for the truth; the event carries recoveryId and status.
	// EventRecoveryStarted: a recovery was started (Start).
	EventRecoveryStarted = "RECOVERY_STARTED"
	// EventRecoveryDeviceBound: the new phone was bound to the recovery.
	EventRecoveryDeviceBound = "RECOVERY_DEVICE_BOUND"
	// EventRecoveryCooling: the vouchers' quorum was reached; the cooling-off runs.
	EventRecoveryCooling = "RECOVERY_COOLING"
	// EventRecoveryCompleted: the account moved to the new phone (method vouch
	// or old_phone; probationUntil); DEVICE_LINKED with via "recovery" follows.
	EventRecoveryCompleted = "RECOVERY_COMPLETED"
	// EventRecoveryVetoed: stopped by you (Veto), a voucher or the old phone; nothing moved.
	EventRecoveryVetoed = "RECOVERY_VETOED"
	// EventRecoveryExpired: the new phone was not bound in time, or a newer recovery replaced it.
	EventRecoveryExpired = "RECOVERY_EXPIRED"
	// EventRecoveryFailed: it ended without a move (not enough approvals, the new phone's key changed …).
	EventRecoveryFailed = "RECOVERY_FAILED"

	// Help desk (client.Assist): the event carries assistId, agentRef and agentName.
	// EventAssistOpened: an assist session was opened (Open).
	EventAssistOpened = "ASSIST_OPENED"
	// EventAssistEnded: an assist session ended (reason: ended, expired, replaced …).
	EventAssistEnded = "ASSIST_ENDED"
	// EventAssistCheckPassed: the person approved the help desk's check on their phone.
	EventAssistCheckPassed = "ASSIST_CHECK_PASSED"
	// EventAssistCheckFailed: the check failed (outcome wrong_number, not_me,
	// coached or declined); page someone. Carries a case code.
	EventAssistCheckFailed = "ASSIST_CHECK_FAILED"
	// EventAssistUnfrozen: the help desk lifted the person's freeze after a passed check (Unfreeze).
	EventAssistUnfrozen = "ASSIST_UNFROZEN"
	// EventAssistClaimConfirmed: the person checked that the agent from IT is real.
	EventAssistClaimConfirmed = "ASSIST_CLAIM_CONFIRMED"
	// EventAssistClaimUnverified: someone said they were from IT and nobody was
	// working on the account (no assistId); page someone. Carries a case code.
	EventAssistClaimUnverified = "ASSIST_CLAIM_UNVERIFIED"

	// AI agents (client.Agents): changes partners may act on, and what Touchque noticed.
	// EventAgentCreated: an AI agent was registered.
	EventAgentCreated = "AGENT_CREATED"
	// EventAgentSuspended: an AI agent was suspended (through the API or the dashboard): its tokens stopped working.
	EventAgentSuspended = "AGENT_SUSPENDED"
	// EventAgentResumed: an AI agent may act again.
	EventAgentResumed = "AGENT_RESUMED"
	// EventAgentRevoked: an AI agent was revoked for good.
	EventAgentRevoked = "AGENT_REVOKED"
	// EventAgentKeyAdded: a key was added to an AI agent.
	EventAgentKeyAdded = "AGENT_KEY_ADDED"
	// EventAgentKeyRemoved: a key was removed from an AI agent; tokens bound to it stopped working.
	EventAgentKeyRemoved = "AGENT_KEY_REMOVED"
	// EventAgentsPaused: the kill switch stopped every AI agent of the workspace.
	EventAgentsPaused = "AGENTS_PAUSED"
	// EventAgentsResumed: the kill switch was turned off.
	EventAgentsResumed = "AGENTS_RESUMED"
	// EventAgentPolicyChanged: an AI agent's policy changed.
	EventAgentPolicyChanged = "AGENT_POLICY_CHANGED"
	// EventAgentWorkspacePolicyChanged: the workspace's agent policy (every agent's floor) changed.
	EventAgentWorkspacePolicyChanged = "AGENT_WORKSPACE_POLICY_CHANGED"
	// EventAgentApprovalRedeemed: an approval token was used.
	EventAgentApprovalRedeemed = "AGENT_APPROVAL_REDEEMED"
	// EventAgentBlockedByPerson: a person stopped an AI agent from asking them ("this wasn't me", coached, or three rejections).
	EventAgentBlockedByPerson = "AGENT_BLOCKED_BY_PERSON"
	// EventAgentUnblockedForPerson: an admin let an AI agent ask a person again.
	EventAgentUnblockedForPerson = "AGENT_UNBLOCKED_FOR_PERSON"
	// EventAgentLoopDetected: an AI agent sent the same request to the same person three times in 10 minutes.
	EventAgentLoopDetected = "AGENT_LOOP_DETECTED"
	// EventAgentMandateRequested: an AI agent asked a person for a mandate.
	EventAgentMandateRequested = "AGENT_MANDATE_REQUESTED"
	// EventAgentMandateRevoked: a mandate was ended.
	EventAgentMandateRevoked = "AGENT_MANDATE_REVOKED"
	// EventAgentInjectionSuspected: an AI agent's text carried an instruction to the model or a link that carries data; the request was refused.
	EventAgentInjectionSuspected = "AGENT_INJECTION_SUSPECTED"
	// EventAgentInhumanApproval: an approval came back sooner than a person can answer; it is never usable.
	EventAgentInhumanApproval = "AGENT_INHUMAN_APPROVAL"
	// EventAgentLookalikeName: a new or renamed AI agent's name read like another agent's; it was refused.
	EventAgentLookalikeName = "AGENT_LOOKALIKE_NAME"
)

Event values of Touchque's event webhooks. Ignore types you do not know.

View Source
const AgentAssertionType = "urn:ietf:params:oauth:client-assertion-type:jwt-bearer"

AgentAssertionType is the client_assertion_type of an agent's token request.

View Source
const ConnectionTokenType = "urn:touchque:params:oauth:token-type:connection-access-token"

ConnectionTokenType is the requested_token_type of the token vault (GetConnectionToken).

View Source
const DefaultBaseURL = "https://api.touchque.com"

DefaultBaseURL is used when Config.BaseURL and TQ_API_URL are both unset.

View Source
const DefaultSSOBaseURL = "https://sso.touchque.com"

DefaultSSOBaseURL is the Touchque SSO, where an organization's VPN (RADIUS) apps live. RadiusClient uses it when Config.BaseURL is empty.

Variables

View Source
var (
	ErrFeature          = errors.New("touchque: feature not available")
	ErrFeatureNotInPlan = errors.New("touchque: feature not in the organization's plan")
	ErrFeatureReadOnly  = errors.New("touchque: feature is being turned off (read-only)")
	ErrFeatureOff       = errors.New("touchque: feature switched off on this deployment")
)

The organization behind your workspace cannot use a feature here (HTTP 403). An *APIError matches one of these with errors.Is, and ErrFeature for any of the three; its Feature field names the feature:

  • ErrFeatureNotInPlan: not in its plan (feature_not_in_plan); an owner or admin adds it in the Touchque dashboard;
  • ErrFeatureReadOnly: being turned off (feature_read_only); reads still work for 14 days, changes are refused;
  • ErrFeatureOff: switched off on this Touchque deployment (feature_off).
View Source
var ErrOutagePageSignature = errors.New("touchque: the outage cache page is not signed with this proxy secret")

ErrOutagePageSignature: the page was not signed with this app's proxy secret (changed on the way or on disk, or the secret was renewed).

View Source
var QRPairingRefusalReasons = []string{"policy", "device_not_approved", "too_many_browsers", "rate_limited", "no_account", "other"}

QRPairingRefusalReasons is what Refuse may tell the phone.

View Source
var SecondThoughtQuestions = []string{
	"someone_guiding",
	"safe_account",
	"remote_access",
	"asked_for_code",
	"support_call",
	"met_online",
	"promised_return",
	"know_recipient",
	"sim_in_hand",
}

SecondThoughtQuestions are the questions an action type can ask (at most two).

View Source
var SecurityEventTypes = map[string]string{
	"session-revoked":          "https://schemas.openid.net/secevent/caep/event-type/session-revoked",
	"credential-change":        "https://schemas.openid.net/secevent/caep/event-type/credential-change",
	"device-compliance-change": "https://schemas.openid.net/secevent/caep/event-type/device-compliance-change",
	"account-disabled":         "https://schemas.openid.net/secevent/risc/event-type/account-disabled",
	"credential-compromise":    "https://schemas.openid.net/secevent/risc/event-type/credential-compromise",
	"verification":             "https://schemas.openid.net/secevent/ssf/event-type/verification",
	"stream-updated":           "https://schemas.openid.net/secevent/ssf/event-type/stream-updated",
}

SecurityEventTypes are the event types Touchque sends, by their short name.

Functions

func AssertApprovalMatches

func AssertApprovalMatches(claims map[string]interface{}, expect ApprovalExpectation) error

AssertApprovalMatches returns an *ApprovalMismatchError unless the claims say what expect says.

func CanonicalJSON

func CanonicalJSON(v interface{}) (string, error)

CanonicalJSON writes a JSON value in RFC 8785 form (sorted keys in UTF-16 order, no whitespace, ECMAScript numbers). Decode with UseNumber to keep numbers exact.

func DecodeApprovalToken

func DecodeApprovalToken(token string) (map[string]interface{}, map[string]interface{}, error)

DecodeApprovalToken returns the header and claims WITHOUT checking the signature.

func DetailsDigest

func DetailsDigest(details []LoginDetail) string

DetailsDigest is the SHA-256 hex of the details as displayed on the phone ("" when there are none) — the last line of the signed message.

func FileToken

func FileToken(path string) func() (string, error)

FileToken reads a token the platform writes to a file and renews (a Kubernetes projected service account token…).

func FormatDeviceCode

func FormatDeviceCode(code string) (string, bool)

FormatDeviceCode returns an offline sign-in code the way the phone shows it, "XXXXX-XXXXX", and true; "" and false unless NormalizeDeviceCode accepts it.

func GitHubActionsToken

func GitHubActionsToken(audience string) func() (string, error)

GitHubActionsToken is the token a GitHub Actions job may ask for (the job needs `permissions: id-token: write`).

func IDJAGDPoPProof

func IDJAGDPoPProof(key *IDJAGDPoPKey, target string) (string, error)

IDJAGDPoPProof is a DPoP proof for one POST to target (htu without query or fragment): the token-endpoint proof, IDJAGDPoPProofWith(key, "POST", target, IDJAGDPoPProofOptions{}).

func IDJAGDPoPProofWith

func IDJAGDPoPProofWith(key *IDJAGDPoPKey, method, target string, opts IDJAGDPoPProofOptions) (string, error)

IDJAGDPoPProofWith is a DPoP proof made with the key for one request: method to target, with the access token's hash (ath) and the server's nonce when opts has them. Each proof has a fresh jti and iat, and its header's jwk is the key's public half only (kty, crv, x, y). For a call with the DPoP-bound access token RedeemIDJAG returned (token_type DPoP), send Authorization: DPoP <token> and DPoP: a proof for that call's method and URL with AccessToken set.

htm is method with ASCII blanks (space, \t, \r, \n, \v, \f) trimmed, then uppercased; "" (or only those blanks) is POST, and a method with anything but RFC 9110 token characters left is a *ConfigError (a NUL or a non-ASCII space is not trimmed).

htu is target's scheme, host and path: scheme and host lowercased, the default port dropped, "/" for an empty path, no query or fragment. The path is the one Go's HTTP client sends, URL.EscapedPath: as written when that is a valid percent-encoding, otherwise re-escaped (a space becomes %20), never decoded, and with its "." and ".." segments kept as written (net/http sends them so). A target that is not an absolute http or https URL with a host, or has an invalid port, is a *ConfigError.

func IsStatusPoll

func IsStatusPoll(c *Client, in GuardInput) bool

IsStatusPoll reports whether in only polls an approval already on its way, or keeps the first-time QR (see RunGuard), so a rate limit you put in front of RunGuard may let it through; set GuardInput.BeforeStart to charge the polls that start something after all. A nil c is the default client, as for RunGuard: false while it cannot be built.

func JWKThumbprint

func JWKThumbprint(jwk map[string]interface{}) string

JWKThumbprint is the RFC 7638 thumbprint of a P-256 or Ed25519 public key (the default kid).

func MatchOutageCode

func MatchOutageCode(salt, digests string, fromStep, until int64, iterations, length int, stepSeconds int64, code string, at time.Time) (int64, bool)

MatchOutageCode checks a typed code against one run of digests (salt and digests as base64, as RadiusOutageUser has them), at the current step or one either side and never after until. It returns the step it belongs to. Accept each step once: refuse codes for a step at or before the last one accepted for the person. It reads two digests per step, as pages did before DigestsPerStep; use MatchOutageCodeN with the page's DigestsPerStep.

func MatchOutageCodeN

func MatchOutageCodeN(salt, digests string, fromStep, until int64, iterations, length, perStep int, stepSeconds int64, code string, at time.Time) (int64, bool)

MatchOutageCodeN is MatchOutageCode for a run with perStep digests per step (the page's DigestsPerStep; 0 means 2).

func MatchTotpVerifier

func MatchTotpVerifier(v *OfflineTotpVerifiers, user *OfflineTotpVerifierUser, code string, at time.Time) (int64, bool)

MatchTotpVerifier checks a typed code against one user's digests without calling Touchque. It returns the step the code belongs to (the current one or one either side) and true, or false. Accept each step once: remember the step you accepted for the user and refuse codes for it or an older one.

func MatchesAuthorizationDetails

func MatchesAuthorizationDetails(details interface{}, expected interface{}) bool

MatchesAuthorizationDetails says whether details (a token's authorization_details) say what expected says: a map (one entry) or a slice of maps (every entry, same length).

func NewRelayHandler

func NewRelayHandler(client *Client, opts RelayOptions) http.Handler

NewRelayHandler serves the relay routes every partner backend needs for classic push 2FA, offline sign and passkeys — the routes @touchque/web calls — so you do not hand-write them. Nothing here is partner-specific except how you resolve the signed-in user (UserID) and what you do once someone is authenticated (OnAuthenticated).

mux.Handle("/touchque/", http.StripPrefix("/touchque", touchque.NewRelayHandler(tq, touchque.RelayOptions{
    UserID:    func(r *http.Request) string { return sessionUser(r) },
    LoginUser: func(r *http.Request) string { return passwordVerifiedUser(r) },
    OnAuthenticated: func(w http.ResponseWriter, r *http.Request, info touchque.AuthenticatedInfo) error {
        return startSession(w, info.ExternalUsername)
    },
})))

Routes (relative to the mount point):

POST   /enroll/start                  (auth required) -> GenerateSecretResponse; sends the browser's IP (RelayOptions.IP)
                                      and User-Agent, as POST /login does, so the phone shows where the QR was asked for
GET    /enroll/status                 (auth required) -> {"linked", "used", "deviceId"}
POST   /login                         (pre-auth) -> 202 {"touchque": step, "token"} until approved (same contract as Require;
                                      with SilentSignIn, a known browser is approved at once)
POST   /offline/challenge             (pre-auth, body.externalUsername) -> QR for a phone with no internet
POST   /offline/verify                (pre-auth, body.challengeId/code)
POST   /offline/totp                  (pre-auth, body.externalUsername/code) -> time-based code fallback
POST   /passkey/authenticate/options  (pre-auth, body.email; none = any passkey, for autofill)
POST   /passkey/authenticate/verify   (pre-auth, body.attemptId/response)
POST   /passkey/login/options         (pre-auth, body.requestId — approve a pending 2FA request)
POST   /passkey/login/verify          (pre-auth, body.requestId/response)
POST   /passkey/register/options      (auth required)
POST   /passkey/register/verify       (auth required, body.response/label)
GET    /passkey/credentials           (auth required)
DELETE /passkey/credentials/{id}      (auth required)

"Auth required" routes answer 401 UNAUTHORIZED_FOR_2FA when UserID returns "" — put your own session middleware in front of the handler (or have UserID itself check and return "").

Pre-auth routes are rate limited per IP and per username by default (RateLimit), and Touchque itself caps approval pushes per user. Set LoginUser so POST /login and the offline routes only work for a user who already passed YOUR first factor (password step): then nobody can make Touchque push to, or lock out, an arbitrary user through your server. The offline routes are OFF until you do (or explicitly opt out with AllowOfflineWithoutFirstFactor): with the username taken from the body, anyone could burn a user's offline attempts and lock them out.

JSON request bodies are read only with Content-Type application/json and are limited to 100 KiB.

NewRelayHandler panics when opts.UserID is nil.

func NormalizeDeviceCode

func NormalizeDeviceCode(code string) (string, bool)

NormalizeDeviceCode returns a typed offline sign-in code in its canonical form (upper case, without spaces or dashes) and true, or "" and false unless it is exactly 10 characters of the codes' alphabet (A-Z and 2-9 without I and O).

func OpenCodeReply

func OpenCodeReply(privateKey, requestID, ct string) (string, bool)

OpenCodeReply returns the code the person typed, or false when ct does not open with this key for this request (or is not a code).

func QRPairingURI

func QRPairingURI(pairingID, nonce, keyThumbprint string) string

QRPairingURI is what the QR code says: touchque://pair-browser?v=1&p=<pairing>&n=<nonce>&k=<key thumbprint>.

func RedeemIDJAG

func RedeemIDJAG(ctx context.Context, p RedeemIDJAGParams) (map[string]interface{}, error)

RedeemIDJAG trades an ID-JAG for an access token at the other service (jwt-bearer): the token endpoint's JSON answer. A refusal, any other non-2xx answer (redirects are not followed with the default client) and a 2xx whose body is not a JSON object are an *IDJAGError, and so is no readable answer (temporarily_unavailable with net/http's error as Err), as in RequestIDJAG; when ctx ends (cancelled or past its deadline), its error comes back instead, for errors.Is.

func Require

func Require(client *Client, action string, next http.Handler, opts RequireOptions) http.Handler

Require wraps next with a one-line step-up guard:

mux.Handle("/transfer", touchque.Require(client, "SEND_MONEY", transferHandler, touchque.RequireOptions{
    User: func(r *http.Request) string { return sessionUser(r) },
    Details: func(r *http.Request) []touchque.LoginDetail {
        return []touchque.LoginDetail{{Label: "Amount", Value: r.FormValue("amount") + " EUR"}}
    },
}))

Until the user approves on their phone this answers 202 {"touchque": step, "token": "..."}. Your page shows the step in its own design and sends the same request again with header "X-Touchque-Token: <token>". Once approved, next runs exactly once, with the approval available via ApprovalFromContext(r.Context()).

A nil client is the default client, shared with RunGuard(ctx, nil, …): built from TQ_API_KEY / TQ_API_SECRET on the first request (New) and kept once built (SetDefaultClient replaces or forgets it). While it cannot be built, Require answers 500 misconfigured (401 when nobody is signed in) and next never runs; it never panics for it. Require panics only without RequireOptions.User. Its answers are written by WriteGuardResult.

func SafeApprovalMessage

func SafeApprovalMessage(m SafeApprovalMessageFields) (string, error)

SafeApprovalMessage is the 149-byte message the phone signs (its SHA-256 is what the guard verifies), as 0x hex.

func SafeDisplayDigest

func SafeDisplayDigest(rows []SafeDisplayRow) string

SafeDisplayDigest is the SHA-256 of the rows as "label\x1Fvalue" joined by "\x1E" (UTF-8), as 0x hex: the digest an approval carries.

func SafeGovernanceHash

func SafeGovernanceHash(t SafeTxTarget) (string, error)

SafeGovernanceHash is what the guard schedules a governance change under: the change itself, without the nonce or gas fields.

func SafeScheduleCall

func SafeScheduleCall(safe, governanceHash string, approvals []string) (string, error)

SafeScheduleCall is the call data of guard.schedule(safe, governanceHash, approvals), which starts a governance change's waiting time.

func SafeTxHash

func SafeTxHash(t SafeTxTarget) (string, error)

SafeTxHash is the Safe transaction hash (EIP-712, domain = chainId + the Safe): what the owners sign and an ordinary approval covers.

func SetDefaultClient

func SetDefaultClient(c *Client)

SetDefaultClient replaces the default client that Require(nil, …), RunGuard(ctx, nil, …) and IsStatusPoll(nil, …) share. The default one is built from the environment once per process; nil forgets it, so the next call builds it again from TQ_API_KEY / TQ_API_SECRET / TQ_API_URL (a test that changes them, a rotated key).

The startup check, to fail fast instead of answering 500 misconfigured:

tq, err := touchque.New() // or touchque.New(cfg)
if err != nil {
    log.Fatal(err) // the ConfigError names the missing keys
}
touchque.SetDefaultClient(tq)

It is also how the null-client path gets a logger: the client built from the environment has none, so build yours with New(cfg), cfg from ConfigFromEnv with cfg.Logger set. Safe for concurrent use.

func SignAgentCard

func SignAgentCard(card []byte, key crypto.Signer, kid, jku string) ([]byte, error)

SignAgentCard signs a card you publish (EC P-256, Ed25519 or RSA key): the card with one more entry in `signatures`, as JSON. key may be any crypto.Signer, e.g. one backed by a KMS or an HSM.

func SignGuardToken

func SignGuardToken(apiSecret string, claims GuardTokenClaims) string

SignGuardToken signs claims into a guard token ("v1.<body>.<mac>") with a key derived from apiSecret, for a guard you build yourself (RunGuard and Require issue their own). Set Exp: RunGuard's tokens live 10 minutes.

func VerifyApprovalProof

func VerifyApprovalProof(proof interface{}, opts VerifyApprovalProofOptions) bool

VerifyApprovalProof reports whether proof was signed by the device key over exactly the request, action type, challenge code and details in opts. proof may be an ApprovalProof, *ApprovalProof, the decoded JSON value from a webhook or status response (map[string]interface{}), json.RawMessage or []byte. Fails closed (no pin and no AllowUnpinnedKey -> false) and returns false for any malformed input.

func VerifyApprovalTokenWith

func VerifyApprovalTokenWith(token string, jwks JWKS, audience string, expect ApprovalExpectation, now time.Time) (map[string]interface{}, error)

VerifyApprovalTokenWith verifies an approval token offline: typ touchque-approval+jwt, ES256 by a key of jwks, not expired (30 s leeway), aud equal to audience, then expect. now: zero means the current time. audience is required: GET /agents/jwks.json is one key set for every Touchque workspace, so without it a token Touchque signed for another workspace would pass. Pass your own (Agents.ApprovalAudience, touchque:workspace:<id>), or use Agents.VerifyApprovalToken, which fills it in. It does not make the token single-use: Agents.RedeemApproval does.

func VerifyDeviceCode

func VerifyDeviceCode(kdf OfflineDeviceKDF, slot OfflineDeviceSlot, code string) bool

VerifyDeviceCode checks the code a person typed against one slot of an offline sign-in pack (the pack's KDF and one of its Slots), on the device and with no network: PBKDF2-SHA256(code, salt || ":" || index, kdf.Iterations, kdf.Length) compared in constant time with the slot's digest. Case, spaces and dashes are ignored; anything that is not 10 characters of the codes' alphabet is false without computing the digest, and so is a KDF other than pbkdf2-sha256. Check the lowest unused slot only. The digest takes a moment by design (600,000 iterations).

func WithSafeApprovals

func WithSafeApprovals(ownerSignatures string, approvals []string) (string, error)

WithSafeApprovals is the owners' Safe signatures with the approvals appended (approvals by index | count | "TQG1"): the signatures argument of execTransaction for an ordinary transaction.

func WriteGuardResult

func WriteGuardResult(w http.ResponseWriter, res GuardResult, errorBody func(GuardRefusal) any)

WriteGuardResult sends a RunGuard result that is not an approval, exactly as Require does: the headers (Content-Type: application/json, Cache-Control: no-store, Retry-After on 423 and 429, and on a refusal X-Touchque-State and X-Touchque-Reason), res.Status and the JSON body. Use it only when res.Approved is nil (an approval writes nothing: run your action instead).

errorBody (nil: the guard's own body) is RequireOptions.ErrorBody: your app's error shape for a refusal (status 400 and above), never called for a 202 step. A value that encodes to a JSON object is sent with "touchque" set to the step, anything else as it is. A panic, or a value encoding/json cannot encode (a cycle, nesting deeper than encoding/json reads), sends the default body and logs [Touchque] ErrorBody failed to the client's Config.Logger. The body is encoded before anything is written, so a status is never sent without it.

func WriteMcpAuthError

func WriteMcpAuthError(w http.ResponseWriter, err error)

WriteMcpAuthError answers a refusal (an *McpAuthError) with its status and WWW-Authenticate.

Types

type APIError

type APIError struct {
	StatusCode int
	Message    string
	// Code is the machine-readable error code (e.g. "device_not_linked",
	// "unknown_action"), when the API sent one.
	Code string
	// Reason: offline sign only — why a code was not approved.
	Reason string
	// AttemptsLeft: offline sign only — wrong codes left before the challenge locks.
	AttemptsLeft int
	// RetryAfter: seconds to wait before retrying (429 / 423).
	RetryAfter int
	// CaseCode is the "Why?" case code of a refusal (K7P-2QX): show it to the
	// user ("Tell your support team: K7P-2QX"); your team opens the decision by
	// it in the dashboard. Empty for other errors.
	CaseCode string
	// Feature is the catalog id (device_risk, ai_agents, mobile_sdk, ciam…) of
	// a feature refusal; see ErrFeatureNotInPlan. Empty for other errors.
	Feature string
	Data    map[string]interface{}
}

APIError represents an error returned by the Touchque API (status >= 400).

func (*APIError) Error

func (e *APIError) Error() string

func (*APIError) Is

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

Is lets errors.Is match the feature sentinels.

type ActionApproval

type ActionApproval struct {
	Required     bool     `json:"required"`
	Capabilities []string `json:"capabilities"`
	Message      string   `json:"message"`
}

ActionApproval is set when a version loosens security and waits for an admin's phone approval.

type ActionCall

type ActionCall struct {
	Kind   string `json:"kind"`
	Reason string `json:"reason"`
}

ActionCall is one decision call an Action made (deny, stepUp, …).

type ActionDeployResult

type ActionDeployResult struct {
	Action  ActionSummary `json:"action"`
	Version ActionVersion `json:"version"`
	// Deployed: this version runs now.
	Deployed bool            `json:"deployed"`
	Approval *ActionApproval `json:"approval"`
	Warnings []string        `json:"warnings"`
}

ActionDeployResult is Deploy's answer.

type ActionDetail

type ActionDetail struct {
	Action   ActionSummary   `json:"action"`
	Code     *string         `json:"code"`
	Versions []ActionVersion `json:"versions"`
}

ActionDetail is an Action with the active version's code and its versions.

type ActionDraft

type ActionDraft struct {
	Trigger      string
	Code         string
	Template     *ActionTemplateRef
	Slug         string
	Secrets      []string
	AllowedHosts []string
	// Capabilities: loosening powers (skip_number_match, override_block,
	// allow_silent); each needs an admin's phone approval in the dashboard.
	Capabilities []string
}

ActionDraft is code to deploy, test or replay: Code or Template (with Trigger), or Slug for the deployed version of an existing Action.

type ActionDryRunResult

type ActionDryRunResult struct {
	Trigger             string                   `json:"trigger"`
	Evaluated           int                      `json:"evaluated"`
	From                *string                  `json:"from"`
	To                  *string                  `json:"to"`
	Matched             int                      `json:"matched"`
	Changed             *int                     `json:"changed"`
	Transitions         map[string]int           `json:"transitions"`
	Notifications       map[string]int           `json:"notifications"`
	Errors              int                      `json:"errors"`
	Timeouts            int                      `json:"timeouts"`
	ErrorSamples        []map[string]interface{} `json:"errorSamples"`
	P50Ms               int                      `json:"p50Ms"`
	P95Ms               int                      `json:"p95Ms"`
	Samples             []map[string]interface{} `json:"samples"`
	AssumedCapabilities []string                 `json:"assumedCapabilities"`
}

ActionDryRunResult: how many decisions the draft would have changed, and how.

type ActionLogLine

type ActionLogLine struct {
	Level   string `json:"level"`
	Message string `json:"message"`
	At      int    `json:"at"`
}

ActionLogLine is one line of an Action's console output.

type ActionMetrics

type ActionMetrics struct {
	Window        string         `json:"window"`
	Runs          int            `json:"runs"`
	Errors        int            `json:"errors"`
	Timeouts      int            `json:"timeouts"`
	ErrorRate     float64        `json:"errorRate"`
	P50Ms         int            `json:"p50Ms"`
	P95Ms         int            `json:"p95Ms"`
	Decisions     map[string]int `json:"decisions"`
	Notifications map[string]int `json:"notifications"`
}

ActionMetrics are an Action's counts and timing over a window.

type ActionRollbackResult

type ActionRollbackResult struct {
	Action  ActionSummary `json:"action"`
	Version ActionVersion `json:"version"`
}

ActionRollbackResult is Rollback's answer.

type ActionRun

type ActionRun struct {
	ID            string                   `json:"id"`
	Time          string                   `json:"time"`
	Version       *int                     `json:"version"`
	EventID       *string                  `json:"eventId"`
	RequestID     *string                  `json:"requestId"`
	Outcome       string                   `json:"outcome"`
	Decision      *string                  `json:"decision"`
	Calls         []ActionCall             `json:"calls"`
	Notifications []map[string]interface{} `json:"notifications"`
	Logs          []ActionLogLine          `json:"logs"`
	Error         *string                  `json:"error"`
	DurationMs    int                      `json:"durationMs"`
}

ActionRun is one live run of an Action.

type ActionSecretInfo

type ActionSecretInfo struct {
	Name      string `json:"name"`
	CreatedAt string `json:"createdAt"`
	UpdatedAt string `json:"updatedAt"`
}

ActionSecretInfo is a secret's name and dates (never its value).

type ActionSecretsResource

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

ActionSecretsResource: values are encrypted and never readable again through the API.

func (*ActionSecretsResource) Delete

func (s *ActionSecretsResource) Delete(name string) error

Delete deletes a secret.

func (*ActionSecretsResource) List

List returns secret names only.

func (*ActionSecretsResource) Set

func (s *ActionSecretsResource) Set(name, value string) (*ActionSecretInfo, error)

Set stores a secret value.

type ActionSummary

type ActionSummary struct {
	Slug            string `json:"slug"`
	Name            string `json:"name"`
	Trigger         string `json:"trigger"`
	Enabled         bool   `json:"enabled"`
	Order           int    `json:"order"`
	OnFailure       string `json:"onFailure"`
	ActiveVersion   *int   `json:"activeVersion"`
	PendingApproval int    `json:"pendingApproval,omitempty"`
	CreatedAt       string `json:"createdAt,omitempty"`
	UpdatedAt       string `json:"updatedAt,omitempty"`
}

ActionSummary is one Action.

type ActionTemplateInfo

type ActionTemplateInfo struct {
	ID          string            `json:"id"`
	Name        string            `json:"name"`
	Description string            `json:"description"`
	Triggers    []string          `json:"triggers"`
	Params      map[string]string `json:"params"`
}

ActionTemplateInfo describes a no-code template.

type ActionTemplateRef

type ActionTemplateRef struct {
	ID     string                 `json:"id"`
	Params map[string]interface{} `json:"params,omitempty"`
}

ActionTemplateRef names a no-code template and its parameters.

type ActionTestResult

type ActionTestResult struct {
	Outcome             string                   `json:"outcome"` // ok, error, timeout
	Error               *string                  `json:"error"`
	DurationMs          int                      `json:"durationMs"`
	CPUMs               float64                  `json:"cpuMs"`
	Calls               []ActionCall             `json:"calls"`
	Notifications       []map[string]interface{} `json:"notifications"`
	Logs                []ActionLogLine          `json:"logs"`
	Reasons             []RiskReason             `json:"reasons"`
	WouldBe             map[string]interface{}   `json:"wouldBe"`
	EventID             *string                  `json:"eventId"`
	Event               map[string]interface{}   `json:"event"`
	AssumedCapabilities []string                 `json:"assumedCapabilities"`
}

ActionTestResult is what one test run did (nothing is sent).

type ActionType

type ActionType struct {
	ID          string `json:"id"`
	Type        string `json:"type"`
	Name        string `json:"name"`
	Description string `json:"description"`
	// Critical actions always use number matching and never accept recovery
	// / offline time-based codes.
	Critical bool `json:"critical"`
	Active   bool `json:"active"`
	// SecondThought is nil when the type asks no questions.
	SecondThought *SecondThought `json:"secondThought,omitempty"`
}

ActionType is one action type, as returned by Define / List.

type ActionTypesResource

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

ActionTypesResource manages action types ("LOGIN", "SEND_MONEY", …) — what a user is asked to approve. Define them from code at start-up instead of clicking them into the Dashboard. (Before v4 this was Client.Actions; Client.Actions is Touchque Actions now.)

func (*ActionTypesResource) Define

func (a *ActionTypesResource) Define(actionType string, opts DefineOptions) (*ActionType, error)

Define creates the action type, or updates its name, description, critical flag and Second Thought questions. Safe to call on every start-up: it never re-enables a type an admin disabled.

func (*ActionTypesResource) List

func (a *ActionTypesResource) List() ([]ActionType, error)

List returns every action type defined for this integration.

type ActionVersion

type ActionVersion struct {
	Number               int                `json:"number"`
	Status               string             `json:"status"` // ready, pending_approval, rejected
	Active               bool               `json:"active"`
	Capabilities         []string           `json:"capabilities"`
	ApprovedCapabilities []string           `json:"approvedCapabilities"`
	AllowedHosts         []string           `json:"allowedHosts"`
	Secrets              []string           `json:"secrets"`
	Template             *ActionTemplateRef `json:"template"`
	CodeHash             string             `json:"codeHash"`
	Code                 string             `json:"code,omitempty"`
	CreatedAt            string             `json:"createdAt"`
	CreatedBy            *string            `json:"createdBy"`
	ApprovedAt           *string            `json:"approvedAt"`
}

ActionVersion is one immutable version of an Action.

type ActionsResource

type ActionsResource struct {

	// Secrets your Actions read (event.secrets.NAME) or notify with.
	Secrets *ActionSecretsResource
	// contains filtered or unexported fields
}

ActionsResource is Touchque Actions: your own code at points of the approval pipeline (before the push is sent, the silent sign-in decision, after an approval, fraud reports, device and recovery events). Touchque runs it in a sandbox; this resource deploys, tests, replays and observes it.

client.Actions.Deploy("night-alert", touchque.DeployActionOptions{
	Trigger:  "approval.decided",
	Template: &touchque.ActionTemplateRef{ID: "alert", Params: map[string]interface{}{"channel": "slack"}},
})

Action code itself is JavaScript (exports.onExecute = async (event, api) => {...}), whatever language your server is written in.

func (*ActionsResource) Delete

func (a *ActionsResource) Delete(slug string) error

Delete deletes the Action and its versions.

func (*ActionsResource) Deploy

Deploy creates the Action or adds a version and makes it live (idempotent: the same code and settings change nothing). A version asking for a loosening capability waits for an admin's phone approval: then Deployed is false and Approval.Required true.

func (*ActionsResource) DryRun

DryRun replays a draft against recent real decisions: how many it would have changed (Changed, Transitions such as {"push→number_match": 12}), notifications it would have sent, errors and timing.

func (*ActionsResource) Events

func (a *ActionsResource) Events(trigger string, limit int) ([]RecordedActionEvent, error)

Events returns recorded events, newest first (trigger "" = all; limit 0 = the API's 20).

func (*ActionsResource) Get

func (a *ActionsResource) Get(slug string) (*ActionDetail, error)

Get returns the Action, the active version's code and its versions.

func (*ActionsResource) List

func (a *ActionsResource) List() ([]ActionSummary, error)

List returns the workspace's Actions.

func (*ActionsResource) Logs

func (a *ActionsResource) Logs(slug string, limit int, before *time.Time) ([]ActionRun, error)

Logs returns live runs of an Action (limit 0 = the API's 50; before nil = newest).

func (*ActionsResource) Metrics

func (a *ActionsResource) Metrics(slug string, window string) (*ActionMetrics, error)

Metrics returns an Action's metrics; window is 1h, 24h ("" = 24h), 7d or 30d.

func (*ActionsResource) RenderTemplate

func (a *ActionsResource) RenderTemplate(id, trigger string, params map[string]interface{}) (*RenderedTemplate, error)

RenderTemplate returns a template as plain code.

func (*ActionsResource) Rollback

func (a *ActionsResource) Rollback(slug string, version *int) (*ActionRollbackResult, error)

Rollback goes back to version, or (nil) to the newest runnable version before the active one. It takes effect at once.

func (*ActionsResource) Templates

func (a *ActionsResource) Templates() ([]ActionTemplateInfo, error)

Templates returns the no-code templates.

func (*ActionsResource) Test

Test runs a draft (or a deployed Action) once on a recorded, given or sample event. It sends no notification.

func (*ActionsResource) Triggers

func (a *ActionsResource) Triggers() (map[string]interface{}, error)

Triggers returns every trigger with its decisions, capabilities, notification types and a sample event.

func (*ActionsResource) Update

func (a *ActionsResource) Update(slug string, opts UpdateActionOptions) (*ActionSummary, error)

Update renames, turns on or off, reorders, or changes OnFailure.

func (*ActionsResource) Version

func (a *ActionsResource) Version(slug string, number int) (*ActionVersion, error)

Version returns one version with its code.

type Agent

type Agent struct {
	AgentID string
	// contains filtered or unexported fields
}

Agent is an AI agent's own Touchque client.

func NewAgent

func NewAgent(cfg AgentConfig) (*Agent, error)

NewAgent builds an Agent; it checks the configuration, it does not call Touchque.

func (*Agent) AccessToken

func (a *Agent) AccessToken() (string, error)

AccessToken returns the agent's current token, renewed a minute before it expires.

func (*Agent) GetApproval

func (a *Agent) GetApproval(approvalID string) (*AgentApprovalState, error)

GetApproval returns where an approval request is; ApprovalToken once approved.

func (*Agent) GetConnectionToken

func (a *Agent) GetConnectionToken(user, connection, scope string) (*AgentConnectionToken, error)

GetConnectionToken returns, from the token vault, a person's own access token at another service for a connection that names this agent (AgentsResource.Vault). Touchque refreshes it; the refresh token never leaves. scope may only narrow what the person granted (empty: all of it).

func (*Agent) GetMandate

func (a *Agent) GetMandate(mandateID string) (*Mandate, error)

GetMandate returns a mandate's state and what is left.

func (*Agent) Me

func (a *Agent) Me() (*AgentSelf, error)

Me returns the agent as Touchque sees it: its action types, owner, review date and workspace.

func (*Agent) RequestApproval

func (a *Agent) RequestApproval(p AgentApprovalParams) (*AgentApprovalState, error)

RequestApproval asks the person to approve on their Touchque phone. Show ChallengeCode in your conversation (interactive): the person types it on the phone.

func (*Agent) RequestMandate

func (a *Agent) RequestMandate(p MandateParams) (*Mandate, error)

RequestMandate asks the person for a mandate. Show ChallengeCode; once active, pass MandateID to RequestApproval and each request within it is approved without a push.

func (*Agent) RequireApproval

func (a *Agent) RequireApproval(ctx context.Context, p AgentApprovalParams, onChallenge func(*AgentApprovalState), timeout time.Duration) (*AgentApprovalState, error)

WaitForApproval polls until the person approves (the state holds ApprovalToken). It returns an *ApprovalError when the request ends otherwise and a *TimeoutError after timeout (0: 10 minutes). An approval given during a phone call stays provisional until the phone confirms it, and four eyes stay awaiting_second until the second person answers. RequireApproval asks the person's phone and waits for the answer: the approved state (holding ApprovalToken), an *ApprovalError when it ended otherwise, or a timeout. onChallenge (may be nil) gets the state while the phone waits: show its ChallengeCode in the conversation. Put it in front of any tool call an agent framework makes (LangChain, LlamaIndex, Eino, a custom loop) so the call runs only after the person approved.

func (*Agent) RevokeMandate

func (a *Agent) RevokeMandate(mandateID string) (*Mandate, error)

RevokeMandate gives up a mandate.

func (*Agent) WaitForApproval

func (a *Agent) WaitForApproval(ctx context.Context, approvalID string, timeout, interval time.Duration) (*AgentApprovalState, error)

type AgentApprovalParams

type AgentApprovalParams struct {
	// User is the person the agent acts for (their phone approves).
	User string
	// Type is one of the agent's allowed action types.
	Type string
	// AuthorizationDetails is what exactly to approve; Touchque draws the phone's rows from it.
	AuthorizationDetails []map[string]interface{}
	// Reason is the agent's own words, shown on the phone as unverified.
	Reason string
	// Presence: "interactive" (default; a person reads the number in your
	// conversation) or "background" (no number, never for critical types).
	Presence string
	// ExpiresIn: seconds the phone may approve it, 60-3600 (default 300).
	ExpiresIn   int
	Locale      string
	ReferenceID string
	ClientIP    string
	UserAgent   string
	// MandateID approves within this active mandate: no push (see RequestMandate).
	MandateID string
}

AgentApprovalParams asks a person to approve on their Touchque phone.

type AgentApprovalState

type AgentApprovalState struct {
	ApprovalID string `json:"approvalId"`
	// Status: pending, approved, rejected, blocked, expired, provisional, revoked, stale, redeemed.
	Status   string `json:"status"`
	Presence string `json:"presence"`
	// ChallengeCode: while pending and interactive, show it in the conversation.
	ChallengeCode string `json:"challengeCode"`
	// RequiresPasskey: over the policy's RequirePasskeyAbove the person approves with a
	// passkey on your page (<touchque-approval request-id="ApprovalID">), not on the phone.
	RequiresPasskey bool   `json:"requiresPasskey"`
	ExpiresAt       string `json:"expiresAt"`
	CaseCode        string `json:"caseCode"`
	Reason          string `json:"reason"`
	// ApprovalToken, once approved: hand it to the service that executes (it redeems it once).
	ApprovalToken  string `json:"approvalToken"`
	TokenExpiresIn int    `json:"tokenExpiresIn"`
	// Four eyes: who approves second, and the number they type when their action type needs one.
	SecondApprover      string `json:"secondApprover"`
	SecondChallengeCode string `json:"secondChallengeCode"`
	// MandateID and Mandate: approved within this mandate (no push).
	MandateID string   `json:"mandateId"`
	Mandate   *Mandate `json:"mandate"`
}

AgentApprovalState is where an approval request is.

type AgentBlock

type AgentBlock struct {
	ExternalUsername string `json:"externalUsername"`
	// Reason: not_me, coached or rejections.
	Reason     string `json:"reason"`
	ApprovalID string `json:"approvalId"`
	CreatedAt  string `json:"createdAt"`
}

AgentBlock is a person who stopped the agent asking them.

type AgentCardError

type AgentCardError struct {
	Code    string
	Message string
}

AgentCardError: Code is unsigned, malformed, untrusted_key, invalid_signature or keys_unavailable.

func (*AgentCardError) Error

func (e *AgentCardError) Error() string

type AgentCardVerification

type AgentCardVerification struct {
	KID       string
	Alg       string
	KeySource string
}

AgentCardVerification is the signature that verified; KeySource is "keys" or "jku".

func VerifyAgentCard

func VerifyAgentCard(ctx context.Context, card []byte, opts VerifyAgentCardOptions) (*AgentCardVerification, error)

VerifyAgentCard checks the card's signatures: the one that verified, or *AgentCardError.

type AgentConfig

type AgentConfig struct {
	AgentID string
	// PrivateKey: a JWK (map or JSON string), a PEM string, or an
	// *ecdsa.PrivateKey / ed25519.PrivateKey.
	PrivateKey interface{}
	// Kid it was registered with; default: the JWK's kid, else its RFC 7638 thumbprint.
	Kid     string
	BaseURL string
	// Scope: space-separated subset of "agent:read approvals:request approvals:read vault:read"; default all.
	Scope     string
	TimeoutMs int
}

AgentConfig configures an Agent. Empty fields fall back to the environment: TQ_AGENT_ID, TQ_AGENT_KEY (a JWK as JSON, or a PEM), TQ_API_URL.

type AgentConnectionToken

type AgentConnectionToken struct {
	AccessToken string `json:"access_token"`
	TokenType   string `json:"token_type"`
	// ExpiresIn is 0 when the service does not say.
	ExpiresIn  int    `json:"expires_in"`
	Scope      string `json:"scope"`
	Connection string `json:"connection"`
}

AgentConnectionToken is a person's own access token at another service (the token vault).

type AgentEvent

type AgentEvent struct {
	ID               string                 `json:"id"`
	Type             string                 `json:"type"`
	OccurredAt       string                 `json:"occurredAt"`
	Agent            *AgentEventAgent       `json:"agent"`
	ExternalUsername string                 `json:"externalUsername"`
	ApprovalID       string                 `json:"approvalId"`
	CaseCode         string                 `json:"caseCode"`
	IP               string                 `json:"ip"`
	Note             string                 `json:"note"`
	Data             map[string]interface{} `json:"data"`
}

AgentEvent is one of the workspace's agent events (AGENT_*, AGENTS_*) for a SIEM.

type AgentEventAgent

type AgentEventAgent struct {
	ID   string `json:"id"`
	Name string `json:"name"`
}

AgentEventAgent names the agent of an event.

type AgentEventOptions

type AgentEventOptions struct {
	After string
	Since string
	Limit int
}

AgentEventOptions: After (a cursor from Next), Since (ISO 8601, the first call; default the last 24 hours), Limit (1 to 500, default 100).

type AgentEventPage

type AgentEventPage struct {
	Events  []AgentEvent `json:"events"`
	Next    string       `json:"next"`
	HasMore bool         `json:"hasMore"`
}

AgentEventPage is a page of events, oldest first; ask again with After: Next (it stays the same while nothing new happened).

type AgentInfo

type AgentInfo struct {
	ID          string `json:"id"`
	Name        string `json:"name"`
	Description string `json:"description"`
	Platform    string `json:"platform"`
	Owner       struct {
		Email  string `json:"email"`
		UserID string `json:"userId"`
	} `json:"owner"`
	// Status is active, suspended or revoked.
	Status string `json:"status"`
	// StatusReason says why it is suspended or revoked; owner_left when its
	// owner left the organization.
	StatusReason string `json:"statusReason"`
	// Blocked is what stops it right now (workspace_paused, suspended,
	// revoked, review_overdue), or "" when it may act.
	Blocked      string   `json:"blocked"`
	AllowedTypes []string `json:"allowedTypes"`
	// Policy is the policy in force (defaults filled in).
	Policy AgentPolicy `json:"policy"`
	Keys   []struct {
		Kid     string `json:"kid"`
		Kty     string `json:"kty"`
		Crv     string `json:"crv"`
		Alg     string `json:"alg"`
		AddedAt string `json:"addedAt"`
	} `json:"keys"`
	// ReviewAt: after this the agent stops until renewed (Update with ReviewInDays).
	ReviewAt   string `json:"reviewAt"`
	LastUsedAt string `json:"lastUsedAt"`
	CreatedBy  string `json:"createdBy"`
	CreatedAt  string `json:"createdAt"`
	UpdatedAt  string `json:"updatedAt"`
}

AgentInfo is an agent as the partner API returns it.

type AgentKeyPair

type AgentKeyPair struct {
	PrivateJWK map[string]interface{}
	PublicJWK  map[string]interface{}
}

AgentKeyPair is a new agent key: register PublicJWK, keep PrivateJWK where the agent runs.

func GenerateAgentKey

func GenerateAgentKey(alg string) (*AgentKeyPair, error)

GenerateAgentKey makes a new key pair for an agent: "ES256" (P-256, default when empty) or "EdDSA" (Ed25519); kid = the RFC 7638 thumbprint.

type AgentKillSwitch

type AgentKillSwitch struct {
	Engaged bool   `json:"engaged"`
	Since   string `json:"since,omitempty"`
	By      string `json:"by,omitempty"`
	Reason  string `json:"reason,omitempty"`
}

AgentKillSwitch is the workspace's switch that stops every agent at once.

type AgentPolicy

type AgentPolicy struct {
	// RequestsPer10Min: every request of the agent (default 60).
	RequestsPer10Min int `json:"requestsPer10Min,omitempty"`
	// RequestsPerUserPer10Min: requests to one person (default 5).
	RequestsPerUserPer10Min int `json:"requestsPerUserPer10Min,omitempty"`
	// AmountPerRequest: {"TRY": "1000.00"}, the most one approval may move.
	AmountPerRequest map[string]string `json:"amountPerRequest,omitempty"`
	// AmountPerDay: over 24 hours, pending and approved requests together.
	AmountPerDay map[string]string `json:"amountPerDay,omitempty"`
	// Background: "non_critical" or "never"; critical types are never asked in the background.
	Background string `json:"background,omitempty"`
	// NewRecipients: "ask" or "deny" (a recipient this person never approved for this agent).
	NewRecipients string `json:"newRecipients,omitempty"`
	// RecipientAllowlist: IBANs / account numbers; any other is refused.
	RecipientAllowlist []string `json:"recipientAllowlist,omitempty"`
	// FourEyes: after the person, a second person approves (never the same one, never the owner).
	FourEyes *FourEyes `json:"fourEyes,omitempty"`
	// RequirePasskeyAbove: {"TRY": "10000.00"}; over it the person approves with a passkey on
	// your page (RequiresPasskey on the approval), never on the phone or with a mandate.
	RequirePasskeyAbove map[string]string `json:"requirePasskeyAbove,omitempty"`
}

AgentPolicy is what the agent may ask for beyond its action types; SetPolicy replaces it (left-out fields take the defaults).

type AgentSelf

type AgentSelf struct {
	Agent struct {
		ID           string   `json:"id"`
		Name         string   `json:"name"`
		Platform     string   `json:"platform"`
		AllowedTypes []string `json:"allowedTypes"`
		ReviewAt     string   `json:"reviewAt"`
		Owner        struct {
			Email string `json:"email"`
		} `json:"owner"`
	} `json:"agent"`
	Workspace struct {
		CompanyName string `json:"companyName"`
	} `json:"workspace"`
	Scope string `json:"scope"`
}

AgentSelf is the agent as Touchque sees it.

type AgentVaultAccount

type AgentVaultAccount struct {
	Connection       string   `json:"connection"`
	ExternalUsername string   `json:"externalUsername"`
	Scopes           []string `json:"scopes"`
	CanRefresh       bool     `json:"canRefresh"`
	LastUsedAt       *string  `json:"lastUsedAt"`
	LastAgentID      *string  `json:"lastAgentId"`
	CreatedAt        string   `json:"createdAt"`
	UpdatedAt        string   `json:"updatedAt"`
}

AgentVaultAccount is a person's account kept in the vault (never a token).

type AgentVaultConnection

type AgentVaultConnection struct {
	Name            string            `json:"name"`
	Provider        string            `json:"provider"`
	ClientID        string            `json:"clientId"`
	HasClientSecret bool              `json:"hasClientSecret"`
	Options         map[string]string `json:"options"`
	AgentIDs        []string          `json:"agentIds"`
	Connected       int               `json:"connected"`
	CreatedAt       string            `json:"createdAt"`
	UpdatedAt       string            `json:"updatedAt"`
}

AgentVaultConnection is a connection: your OAuth app at another service and the agents that may use it.

type AgentVaultConnectionParams

type AgentVaultConnectionParams struct {
	Provider     string   `json:"provider"`
	ClientID     string   `json:"clientId"`
	ClientSecret string   `json:"clientSecret,omitempty"`
	Tenant       string   `json:"tenant,omitempty"`
	Issuer       string   `json:"issuer,omitempty"`
	AgentIDs     []string `json:"agentIds"`
}

AgentVaultConnectionParams adds or replaces a connection; ClientSecret is kept when left empty in a replacement. Provider: google, microsoft, github, facebook, linkedin, x or oidc (with Issuer).

type AgentVaultDeposit

type AgentVaultDeposit struct {
	AccessToken  string `json:"accessToken"`
	RefreshToken string `json:"refreshToken,omitempty"`
	ExpiresIn    int    `json:"expiresIn,omitempty"`
	Scope        string `json:"scope,omitempty"`
}

AgentVaultDeposit is a person's tokens from your own OAuth flow with them.

type AgentVaultResource

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

AgentVaultResource is the token vault for your agents: after your own OAuth flow with a person, deposit their tokens; Touchque keeps them sealed and refreshes them, and the agents a connection names get a short-lived access token (Agent.GetConnectionToken), never the refresh token.

func (*AgentVaultResource) Deposit

func (v *AgentVaultResource) Deposit(connection, user string, d AgentVaultDeposit) (*AgentVaultAccount, error)

Deposit keeps a person's tokens (replacing earlier ones).

func (*AgentVaultResource) ListAccounts

func (v *AgentVaultResource) ListAccounts(user string) ([]AgentVaultAccount, error)

ListAccounts lists a person's accounts in the vault (never a token).

func (*AgentVaultResource) ListConnections

func (v *AgentVaultResource) ListConnections() ([]AgentVaultConnection, error)

ListConnections lists the vault's connections.

func (*AgentVaultResource) PutConnection

PutConnection adds or replaces a connection.

func (*AgentVaultResource) RemoveAccount

func (v *AgentVaultResource) RemoveAccount(connection, user string) error

RemoveAccount deletes a person's tokens: agents get nothing more for them there.

func (*AgentVaultResource) RemoveConnection

func (v *AgentVaultResource) RemoveConnection(name string) (map[string]interface{}, error)

RemoveConnection removes a connection and every person's tokens kept for it.

type AgentsResource

type AgentsResource struct {

	// Vault is the token vault: people's tokens at other services, for your agents.
	Vault *AgentVaultResource
	// contains filtered or unexported fields
}

AgentsResource manages AI agents as identities of their own (client.Agents): register an agent with its PUBLIC key, give it an accountable owner and the action types it may ask approvals for, suspend, revoke or stop every agent at once. The agent itself never gets your API key: it signs in with its own key (Agent, NewAgent).

keys, _ := touchque.GenerateAgentKey("ES256")       // where the agent runs
agent, err := client.Agents.Create(touchque.CreateAgentParams{
	Name: "Invoice bot", AllowedTypes: []string{"PAY_INVOICE"}, PublicKey: keys.PublicJWK,
})

func (*AgentsResource) AddKey

func (r *AgentsResource) AddKey(agentID string, publicKey map[string]interface{}) (*AgentInfo, error)

AddKey adds a key (rotation: add the new one, move the agent to it, then remove the old one).

func (*AgentsResource) ApprovalAudience

func (r *AgentsResource) ApprovalAudience() (string, error)

ApprovalAudience is the aud of this workspace's approval tokens (touchque:workspace:<id>), from GET /agents/approval-audience; asked once, then kept.

func (*AgentsResource) Create

Create registers an agent (needs the agents:write scope).

func (*AgentsResource) Get

func (r *AgentsResource) Get(agentID string) (*AgentInfo, error)

Get returns one agent.

func (*AgentsResource) GetWorkspacePolicy

func (r *AgentsResource) GetWorkspacePolicy() (*AgentPolicy, error)

GetWorkspacePolicy returns the workspace's policy: every agent's floor (an agent's own policy can only make it stricter).

func (*AgentsResource) LiftBlock

func (r *AgentsResource) LiftBlock(agentID, user string) error

LiftBlock lets the agent ask this person again (check with them first).

func (*AgentsResource) List

func (r *AgentsResource) List(status string) ([]AgentInfo, *AgentKillSwitch, error)

List returns the workspace's agents (only those in status, when given) and its kill switch.

func (*AgentsResource) ListBlocks

func (r *AgentsResource) ListBlocks(agentID string) ([]AgentBlock, error)

ListBlocks returns the people who stopped this agent asking them.

func (*AgentsResource) ListEvents

func (r *AgentsResource) ListEvents(opts AgentEventOptions) (*AgentEventPage, error)

ListEvents returns the workspace's agent events for a SIEM, oldest first.

func (*AgentsResource) ListMandates

func (r *AgentsResource) ListMandates(agentID, user string) ([]Mandate, error)

ListMandates returns an agent's mandates, only user's when not empty.

func (*AgentsResource) RedeemApproval

func (r *AgentsResource) RedeemApproval(token string, expect ApprovalExpectation) (*RedeemedApproval, error)

RedeemApproval uses an agent's approval exactly once, right before you execute: expect is checked against the token first (nothing is used on a mismatch), then Touchque checks the token and marks it used, and the answer is checked again. Errors: *ApprovalMismatchError, or an *APIError (already_redeemed, token_expired, provisional…).

func (*AgentsResource) RemoveKey

func (r *AgentsResource) RemoveKey(agentID, kid string) (*AgentInfo, error)

RemoveKey removes a key; tokens the agent got with it stop at once.

func (*AgentsResource) Resume

func (r *AgentsResource) Resume(agentID string) (*AgentInfo, error)

Resume lets a suspended agent act again.

func (*AgentsResource) Revoke

func (r *AgentsResource) Revoke(agentID string) (*AgentInfo, error)

Revoke revokes an agent for good (the record stays for the audit trail).

func (*AgentsResource) RevokeMandate

func (r *AgentsResource) RevokeMandate(agentID, mandateID string) (*Mandate, error)

RevokeMandate ends an agent's mandate at once.

func (*AgentsResource) SetKillSwitch

func (r *AgentsResource) SetKillSwitch(engaged bool, reason string) (*AgentKillSwitch, error)

SetKillSwitch stops (true) or restarts (false) every agent of the workspace at once.

func (*AgentsResource) SetPolicy

func (r *AgentsResource) SetPolicy(agentID string, policy AgentPolicy) (*AgentInfo, error)

SetPolicy sets the agent's budgets, amounts, recipients and background rule.

func (*AgentsResource) SetWorkspacePolicy

func (r *AgentsResource) SetWorkspacePolicy(policy AgentPolicy) (*AgentPolicy, error)

SetWorkspacePolicy replaces the workspace's policy (a field left out sets no floor).

func (*AgentsResource) Suspend

func (r *AgentsResource) Suspend(agentID, reason string) (*AgentInfo, error)

Suspend stops an agent at once (its tokens too) until resumed.

func (*AgentsResource) Update

func (r *AgentsResource) Update(agentID string, p UpdateAgentParams) (*AgentInfo, error)

Update changes, hands over or renews an agent.

func (*AgentsResource) VerifyApprovalToken

func (r *AgentsResource) VerifyApprovalToken(token, audience string, expect ApprovalExpectation) (map[string]interface{}, error)

VerifyApprovalToken verifies an approval token offline (Touchque's published keys, expiry, aud, expect). aud must be this workspace's: an empty audience means ApprovalAudience, and a token without aud or for another workspace is refused. It does not make the token single-use: RedeemApproval does.

type Approval

type Approval struct {
	RequestID     string      `json:"requestId"`
	User          string      `json:"user"`
	Action        string      `json:"action"`
	Assurance     *Assurance  `json:"assurance,omitempty"`
	ConfirmedVia  string      `json:"confirmedVia,omitempty"`
	ApprovalProof interface{} `json:"approvalProof,omitempty"`
	// Vishing Shield: Provisional means approved during a call. Let the user
	// in, but treat the session as limited: Touchque refuses their critical
	// actions until the phone re-confirms (EventApprovalReconfirmed), and
	// EventApprovalRevoked means end it.
	ShieldFields
	// Reasons is set on silent sign-ins only (Assurance.Method "silent",
	// ConfirmedVia "SILENT", RequestID "silent"): nothing was sent to the
	// phone, and these say why Touchque let this known browser in.
	Reasons []RiskReason `json:"reasons,omitempty"`
}

Approval is a request that was approved and consumed exactly once.

func ApprovalFromContext

func ApprovalFromContext(ctx context.Context) (*Approval, bool)

ApprovalFromContext returns the approval Require stored on the request context, once the protected handler is running.

type ApprovalError

type ApprovalError struct {
	ApprovalID string
	Status     string
	Reason     string
}

ApprovalError means an AI agent's approval ended without a usable approval: Status is rejected, blocked, revoked, expired, stale (approved too long ago) or redeemed (already used).

func (*ApprovalError) Error

func (e *ApprovalError) Error() string

type ApprovalExpectation

type ApprovalExpectation struct {
	User string
	Type string
	// AuthorizationDetails: one entry (a map, the token must hold exactly one) or every entry in order (a slice).
	AuthorizationDetails interface{}
}

ApprovalExpectation is what the executor is about to do; empty fields are not checked.

type ApprovalMismatchError

type ApprovalMismatchError struct {
	Message string
}

ApprovalMismatchError means an approval token does not say what you are about to execute (another person, action type, amount, recipient…), or it is not a valid token from Touchque. Do not execute.

func (*ApprovalMismatchError) Error

func (e *ApprovalMismatchError) Error() string

type ApprovalProof

type ApprovalProof struct {
	Version   string `json:"version"`
	Algorithm string `json:"algorithm"`
	// Message is the exact text the device signed.
	Message string `json:"message"`
	// Signature is the base64 DER ECDSA signature.
	Signature string `json:"signature"`
	// PublicKey is the base64 X9.63 (uncompressed) P-256 key of the device.
	PublicKey string `json:"publicKey"`
}

ApprovalProof is the device-signed proof of an approval ("what you see is what you sign"). When the user's phone holds a hardware key (Secure Enclave / Android Keystore), every approval is signed by it over the request id, the action type, the number-match code and a digest of the transaction details the user was shown. It arrives in the SUCCESS webhook ("approvalProof") and in the login status response. Verifying it does not require trusting Touchque: it proves the enrolled phone signed exactly these details.

type ApproveWithRecoveryCodeResponse

type ApproveWithRecoveryCodeResponse struct {
	Success bool   `json:"success"`
	Message string `json:"message"`
}

ApproveWithRecoveryCodeResponse represents the response when approving a request via recovery code

type AskMemberParams

type AskMemberParams struct {
	// LoginHint: the member's e-mail.
	LoginHint string
	// BindingMessage: up to 64 characters, shown on the phone marked unverified.
	BindingMessage string
	// AuthorizationDetails: RFC 9396 details the phone shows.
	AuthorizationDetails []map[string]interface{}
	Resource             string
	Scope                string
	// RequestedExpiry in seconds (30-600); the push lives at most as long as Touchque lets it.
	RequestedExpiry int
}

AskMemberParams asks a member to approve on their phone (CIBA).

type AskUserParams

type AskUserParams struct {
	LoginHint            string // the user's e-mail or usr_ id
	Scope                string
	Audience             string
	BindingMessage       string
	AuthorizationDetails []map[string]interface{}
	RequestedExpiry      int // seconds, 30 to 300 (default 300)
}

AskUserParams is a CIBA request: at least one of BindingMessage (at most 64 characters) and AuthorizationDetails (RFC 9396) says what it is for.

type AssistAgent

type AssistAgent struct {
	Ref   string `json:"ref,omitempty"`
	Name  string `json:"name"`
	Title string `json:"title,omitempty"`
}

AssistAgent is the signed-in agent: Name (and Title) are shown on the person's phone; Ref is your id for them (default Name).

type AssistCheck

type AssistCheck struct {
	RequestID  string  `json:"requestId"`
	Action     string  `json:"action"`
	ActionText string  `json:"actionText"`
	Outcome    string  `json:"outcome"`
	CreatedAt  string  `json:"createdAt"`
	SpentAt    *string `json:"spentAt"`
	ExpiresAt  *string `json:"expiresAt"`
}

AssistCheck is one check on the person's phone. Outcome: pending, verified, wrong_number, not_me, coached, declined or expired.

type AssistCheckStarted

type AssistCheckStarted struct {
	RequestID     string `json:"requestId"`
	ChallengeCode string `json:"challengeCode"`
	ExpiresAt     string `json:"expiresAt"`
	Action        string `json:"action"`
}

AssistCheckStarted carries the number to show the agent only.

type AssistResource

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

AssistResource is the help desk: IT working on a person's account in the open.

  1. Before your help desk acts on someone's account: Open with the person and the signed-in agent. The person's phone gets a calm notice ("<agent> from IT is working on your account now"); while the session is open, their "someone says they're from IT" button shows this agent, and with none open it tells them to hang up (webhook ASSIST_CLAIM_UNVERIFIED).
  2. Before a sensitive action (a factor or password reset, an activation or recovery link, an unlock, a new phone, removing a passkey): Verify. Show ChallengeCode to the agent only; they read it to the person, who types it on their phone and approves with Face ID. Default deny.
  3. Right before the action: Spend (a passed check, for that action, at most ten minutes old, once). Unfreeze lifts a freeze the same way.

No phone (Code "no_phone", Data["route"] "never_locked_out"): the person moves to a new phone with Never Locked Out (Recovery); the help desk cannot.

func (*AssistResource) End

func (ar *AssistResource) End(ctx context.Context, id, by, reason string) (*AssistSession, error)

End stops helping; checks still waiting on the phone expire.

func (*AssistResource) Get

func (ar *AssistResource) Get(ctx context.Context, id string) (*AssistSession, error)

Get returns the session and its checks. Poll it while a check is pending.

func (*AssistResource) List

func (ar *AssistResource) List(ctx context.Context, externalUsername string, openOnly bool) ([]AssistSession, error)

List returns a person's sessions, or every open one (openOnly), newest first.

func (*AssistResource) Open

Open starts helping a person. A session of the same agent for the same person is replaced.

func (*AssistResource) Spend

func (ar *AssistResource) Spend(ctx context.Context, id, requestID, action string) (*AssistSession, error)

Spend uses a passed check for its action, right before you take it; an *APIError with Code check_required (428) otherwise.

func (*AssistResource) Unfreeze

func (ar *AssistResource) Unfreeze(ctx context.Context, id, requestID string) (bool, *AssistSession, error)

Unfreeze lifts the person's approval freeze with a passed check for unlock.

func (*AssistResource) Verify

Verify asks the person's phone to confirm an action. An *APIError with Code no_phone (send them to Never Locked Out), assist_not_open or rate_limited says why not.

type AssistSession

type AssistSession struct {
	ID               string        `json:"id"`
	ExternalUsername string        `json:"externalUsername"`
	Status           string        `json:"status"`
	Agent            AssistAgent   `json:"agent"`
	Reason           *string       `json:"reason"`
	Notified         bool          `json:"notified"`
	OpenedAt         string        `json:"openedAt"`
	ExpiresAt        string        `json:"expiresAt"`
	EndedAt          *string       `json:"endedAt"`
	EndedReason      *string       `json:"endedReason"`
	Phone            bool          `json:"phone"`
	Frozen           bool          `json:"frozen"`
	Checks           []AssistCheck `json:"checks"`
}

AssistSession is IT working on a person's account: OPEN until ended, expired or replaced. Phone false: the person has no working Touchque phone to check on (Never Locked Out).

func (*AssistSession) CheckPassed

func (s *AssistSession) CheckPassed(requestID string) bool

CheckPassed reports whether the check of requestID passed on the person's phone and was not used yet.

type Assurance

type Assurance struct {
	PhishingResistant bool   `json:"phishingResistant"`
	Method            string `json:"method"`
}

Assurance describes how a request was approved. PhishingResistant is true only for a passkey approval.

type AuthResource

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

AuthResource handles authentication setup and secret management.

func (*AuthResource) GenerateSecret

func (a *AuthResource) GenerateSecret(externalUsername string) (*GenerateSecretResponse, error)

GenerateSecret creates a new setup secret for a user. It sends no client IP or User-Agent, so its QR has no setup context: use GenerateSecretWithOptions from a browser request.

func (*AuthResource) GenerateSecretWithOptions

func (a *AuthResource) GenerateSecretWithOptions(opts GenerateSecretOptions) (*GenerateSecretResponse, error)

GenerateSecretWithOptions creates a new setup secret for a user, with the end user's ClientIP and UserAgent: the phone shows where the QR was asked for before it links.

func (*AuthResource) GetUser

func (a *AuthResource) GetUser(externalUsername string) (*GetUserResponse, error)

GetUser looks up a user's link status without sending a push. Useful while polling during enrollment: Used flips true and DeviceID is set once the mobile app scans the setup secret. Returns an *APIError with StatusCode 404 if the user is unknown.

func (*AuthResource) ResetSecret

func (a *AuthResource) ResetSecret(externalUsername string) (*ResetSecretResponse, error)

ResetSecret regenerates a user's secret. It sends no client IP or User-Agent, so the new QR has no setup context (the old one's is cleared): use ResetSecretWithOptions from a browser request.

func (*AuthResource) ResetSecretWithOptions

func (a *AuthResource) ResetSecretWithOptions(opts ResetSecretOptions) (*ResetSecretResponse, error)

ResetSecretWithOptions regenerates a user's secret, with the end user's ClientIP and UserAgent from the request that asks for the new QR: Touchque records them for it, as GenerateSecretWithOptions does, and the phone shows where the QR was asked for before it links.

func (*AuthResource) ValidateSecret

func (a *AuthResource) ValidateSecret(secret string) (*ValidateSecretResponse, error)

ValidateSecret validates a setup secret code with POST /auth/secret/validate, the phone's public call: the Touchque app makes it after it scans the QR, before it links. Its SetupContext is where the QR was asked for, what the phone shows; nil when the request for the QR named no browser (no usable IP address or User-Agent), after a reset without them, and for older QRs and servers. Its FarFromPhone compares that place with the address of whoever calls validate: called from your server, it compares with your server, not the phone.

type AuthenticatedInfo

type AuthenticatedInfo struct {
	ExternalUsername string
	RequestID        string
	Via              AuthenticatedVia
}

AuthenticatedInfo is passed to RelayOptions.OnAuthenticated. ExternalUsername always comes from Touchque or your LoginUser func, never from the request body.

type AuthenticatedVia

type AuthenticatedVia string

AuthenticatedVia says which relay route authenticated the user.

const (
	ViaLogin       AuthenticatedVia = "login"
	ViaPasskey     AuthenticatedVia = "passkey"
	ViaOffline     AuthenticatedVia = "offline"
	ViaOfflineTotp AuthenticatedVia = "offline-totp"
	// ViaSilent: a silent sign-in (RelayOptions.SilentSignIn) — a known
	// browser, nothing sent to the phone; RequestID is "silent".
	ViaSilent AuthenticatedVia = "silent"
)

type AuthorizationOptions

type AuthorizationOptions struct {
	State, Nonce, CodeVerifier, RedirectURI, Scope, Audience string
	// Prompt: "login", "none", "consent", "select_account" or "create".
	Prompt string
	// LoginHint pre-fills the email; ScreenHint "signup" opens the sign-up page.
	LoginHint, ScreenHint, UILocales string
	// MaxAge in seconds; 0 means not sent, and a negative value sends
	// max_age=0: sign in again now (a step-up, see MyAccountError.StepUp).
	MaxAge                               int
	Connection, Organization, Invitation string
	ACRValues, ResponseMode              string
	ExtraParams                          map[string]string
}

AuthorizationOptions are the optional /authorize parameters.

type AuthorizationRequest

type AuthorizationRequest struct {
	URL, State, Nonce, CodeVerifier string
}

AuthorizationRequest is the URL to send the browser to and what to keep until the callback.

type CallbackChecks

type CallbackChecks struct {
	State, Nonce, CodeVerifier string
	RedirectURI                string
	// MaxAge rejects sign-ins older than this many seconds (0: no check;
	// negative: the sign-in must be new, as asked with max_age=0).
	MaxAge int
}

CallbackChecks are the values kept from AuthorizationURL.

type Canary

type Canary struct {
	URL string `json:"url"`
}

Canary is the Mirror Alarm probe of one login request.

type Client

type Client struct {
	Auth     *AuthResource
	Login    *LoginResource
	WebAuthn *WebAuthnResource
	Webhook  *WebhookResource
	Offline  *OfflineResource
	// ActionTypes: what users approve (LOGIN, SEND_MONEY…). Was Actions before v4.
	ActionTypes *ActionTypesResource
	// Actions is Touchque Actions: your own code in the approval pipeline.
	Actions *ActionsResource
	// Risk is silent sign-ins: should this sign-in ask the phone, and which
	// browsers Touchque knows.
	Risk *RiskResource
	// Recovery is Never Locked Out: move a user whose phone is gone to a new
	// phone, with colleagues vouching.
	Recovery *RecoveryResource
	// Assist is the help desk: IT working on a person's account in the open,
	// and checks on their phone before sensitive actions.
	Assist *AssistResource
	// Agents manages AI agents as identities of their own: register (public
	// key), suspend, revoke, kill switch. The agent itself uses NewAgent.
	Agents *AgentsResource
	// Identity is the Touchque Login Management API: your customers' accounts,
	// roles, organizations, apps and connections.
	Identity *IdentityResource
	// Mobile is the Mobile SDK: your own iOS/Android app approves for your
	// users (enrollment tokens, devices, settings).
	Mobile *MobileResource
	// QRPairings pairs a browser by QR code: the phone that scans it is the
	// one asked to approve.
	QRPairings *QRPairingsResource
	// SafeGuard is Safe Guard: Safe transactions approved on the approver's
	// phone, for TouchqueSafeGuard.
	SafeGuard *SafeGuardResource
	// contains filtered or unexported fields
}

Client is the main entry point for the Touchque Go SDK.

func New

func New(config ...*Config) (*Client, error)

New builds a Client from TQ_API_KEY / TQ_API_SECRET / TQ_API_URL, or from config if given (config[0], at most one).

func NewClient

func NewClient(config *Config) *Client

NewClient initializes a new Touchque SDK Client with the given configuration. Panics on invalid configuration (matches this SDK's long-standing behavior) — use New() for a version that returns an error instead.

func (*Client) Check

func (c *Client) Check(requestID string) (*Step, error)

Check reports where a started approval is now, with the request's live ExpiresAt when the API gives it (a Vishing Shield escalation to a passkey extends it).

func (*Client) Complete

func (c *Client) Complete(requestID, user, action string, expect CompleteExpect) (*Approval, error)

Complete uses an approved request exactly once, after checking it is for this user, action and transaction. Call it right before doing the protected thing.

func (*Client) Start

func (c *Client) Start(action, user string, opts StartOptions) (*Step, error)

Start starts an approval for action — never waits.

type CodeReplyKey

type CodeReplyKey struct {
	PublicKey  string
	PrivateKey string
}

CodeReplyKey is a one-time key pair for one request: send PublicKey (the uncompressed P-256 point, base64url) as LoginReplyRequest.Key, keep PrivateKey (PKCS#8 DER, base64url) server-side for this one request.

func NewCodeReplyKey

func NewCodeReplyKey() (CodeReplyKey, error)

NewCodeReplyKey makes a one-time key pair for LoginRequestOptions.Reply.

type CompleteExpect

type CompleteExpect struct {
	Details     []LoginDetail
	ReferenceID string
}

CompleteExpect is what Complete checks the approval is for.

type Config

type Config struct {
	APIKey    string
	APISecret string
	BaseURL   string
	TimeoutMs int
	// Logger receives the SDK's own problems: a misconfigured guard, a
	// failed OnChallenge, a relay without LoginUser. nil (the default) logs
	// nothing. Lines carry an error's type and text, never request data.
	Logger *slog.Logger
}

Config holds the configuration options for the Touchque SDK.

func ConfigFromEnv

func ConfigFromEnv() (*Config, error)

ConfigFromEnv builds a Config from TQ_API_KEY / TQ_API_SECRET / TQ_API_URL.

func DefaultConfig

func DefaultConfig(apiKey, apiSecret string) *Config

DefaultConfig creates a new Config with standard defaults.

func (*Config) Validate

func (c *Config) Validate() error

Validate checks the config and fills in defaults (BaseURL, TimeoutMs), without panicking.

type ConfigError

type ConfigError struct {
	Message string
}

ConfigError means invalid or missing configuration, or an undefined action type.

func (*ConfigError) Error

func (e *ConfigError) Error() string

type ConsumeResponse

type ConsumeResponse struct {
	Consumed         bool          `json:"consumed"`
	RequestID        string        `json:"requestId"`
	ExternalUsername string        `json:"externalUsername"`
	Type             string        `json:"type"`
	ReferenceID      string        `json:"referenceId,omitempty"`
	Details          []LoginDetail `json:"details,omitempty"`
	ConfirmedVia     string        `json:"confirmedVia,omitempty"`
	Assurance        *Assurance    `json:"assurance,omitempty"`
	ApprovalProof    interface{}   `json:"approvalProof,omitempty"`
	ShieldFields
}

ConsumeResponse is returned by Login.Consume: the approval, used exactly once.

type CreateAgentParams

type CreateAgentParams struct {
	Name         string
	AllowedTypes []string
	PublicKey    map[string]interface{}
	PublicKeys   []map[string]interface{}
	Description  string
	// OwnerEmail: the accountable member (default: the API key's creator);
	// the agent stops when they leave the organization.
	OwnerEmail string
	Platform   string
	// ReviewInDays: 1-365, default 90.
	ReviewInDays int
}

CreateAgentParams registers an agent. Set PublicKey (or PublicKeys, up to 3).

type CreateMobileEnrollmentOptions

type CreateMobileEnrollmentOptions struct {
	ExternalUsername string
	// Replace moves the user from the device they approve with today
	// (otherwise an APIError with Code "already_enrolled").
	Replace bool
	// TTLSeconds is 60-86400; 0 keeps the workspace's default (600).
	TTLSeconds int
}

CreateMobileEnrollmentOptions holds the POST /mobile/enrollments fields.

type CreateQRPairingOptions

type CreateQRPairingOptions struct {
	// KeyThumbprint is the RFC 7638 thumbprint of the browser's key, base64url.
	KeyThumbprint string
	// ClientIP and UserAgent are the end user's: the phone is told where the
	// browser is and whether it is on the same network.
	ClientIP  string
	UserAgent string
	// Browser ("Chrome 155") and OS ("macOS 15") are shown on the phone.
	Browser string
	OS      string
	// TTLSeconds is how long the QR code can be scanned: 30 to 300 (0 = 120).
	TTLSeconds int
}

CreateQRPairingOptions registers a pairing for one browser.

type CreatedQRPairing

type CreatedQRPairing struct {
	PairingID string `json:"pairingId"`
	ExpiresAt string `json:"expiresAt"`
	// Nonce is the one-time nonce in the QR code (Touchque keeps its SHA-256).
	Nonce string `json:"nonce"`
	// URI is what the QR code says: touchque://pair-browser?v=1&p=…&n=…&k=….
	URI string `json:"uri"`
}

CreatedQRPairing is a registered pairing: show URI as a QR code.

type CustomDomainsOverview

type CustomDomainsOverview struct {
	// Domains are the custom domains, each as List returns it: id, domain, status, primary, proof,
	// organizationDomain, certificate, records, dns (what its DNS said at the last check, nil
	// before the first), autoCheckUntil, createdAt. Empty, not nil, when there are none.
	Domains []map[string]interface{} `json:"domains"`
	// VerifiedDomains are the domains your organization verified (Organization → Domains): nil
	// when they could not be read, empty when it verified none.
	VerifiedDomains []string `json:"verifiedDomains"`
	// SlugPasskeys counts the customer passkeys made on {slug}.login.touchque.com: they belong to
	// that name and never work on a custom domain.
	SlugPasskeys int `json:"slugPasskeys"`
}

CustomDomainsOverview is GET /identity/custom-domains as the API answers it.

type DefineOptions

type DefineOptions struct {
	// Name shown on the phone and in the Dashboard (default: the slug).
	Name        string
	Description string
	// Critical: nil (the zero value pointer) keeps what the Dashboard has.
	Critical *bool
	// SecondThought: nil keeps what the Dashboard has; one without questions
	// turns them off.
	SecondThought *SecondThought
}

DefineOptions holds the optional fields for Define.

type DeployActionOptions

type DeployActionOptions struct {
	Trigger      string
	Name         string
	Code         string
	Template     *ActionTemplateRef
	Secrets      []string
	AllowedHosts []string
	Capabilities []string
	// OnFailure (pre triggers): "continue" (default, never blocks), "step_up" or "deny".
	OnFailure string
	Order     *int
	Enabled   *bool
	// Activate: false saves the version without making it live.
	Activate *bool
}

DeployActionOptions: Trigger is required for a new Action and cannot change later; Code or Template is required.

type Destination

type Destination struct {
	// Kind is iban, account, wallet, address or payee.
	Kind string `json:"kind"`
	// Value is the IBAN (its check digits must pass), account number, wallet
	// address, delivery address or payee name.
	Value string `json:"value"`
	// Known lists destinations of this kind the user already uses in your
	// system (saved payees, addresses); at most 50.
	Known []string `json:"known,omitempty"`
}

Destination is where an action sends money or value. The phone shows it in full in groups of four, with a warning when it looks like one the user used before but is not the same. Do not repeat it in Details.

type DestinationCheck

type DestinationCheck struct {
	Known     bool                   `json:"known"`
	Lookalike []DestinationLookalike `json:"lookalike"`
}

DestinationCheck is what Touchque made of a request's Destination.

type DestinationLookalike

type DestinationLookalike struct {
	Field string `json:"field"`
	// Reason is same_start_and_end, confusable, near_miss or mixed_script.
	Reason string `json:"reason"`
	// SimilarTo is the known destination, masked (TR33…1326).
	SimilarTo string `json:"similarTo,omitempty"`
}

DestinationLookalike is an earlier destination the request's one resembles.

type DevicePosture

type DevicePosture struct {
	// Platform is "ios" or "android".
	Platform string `json:"platform,omitempty"`
	// Model is the hardware model, e.g. "iPhone15,3" or "Pixel 8".
	Model string `json:"model,omitempty"`
	// OSVersion is e.g. "18.1" or "15".
	OSVersion string `json:"osVersion,omitempty"`
	// SecurityPatch is the Android security patch level (YYYY-MM-DD); empty on iOS.
	SecurityPatch string `json:"securityPatch,omitempty"`
	AppVersion    string `json:"appVersion,omitempty"`
	// ScreenLock is nil when the phone did not say whether a passcode, PIN,
	// pattern or password is set.
	ScreenLock *bool `json:"screenLock"`
	// Biometrics is "face", "touch", "fingerprint", "iris" or "none".
	Biometrics string `json:"biometrics,omitempty"`
	// Jailbroken: jailbroken or rooted, by the app's checks.
	Jailbroken bool `json:"jailbroken"`
	// Compromised: jailbroken/rooted or tampered; sticky until the phone
	// reports clean for a cool-down.
	Compromised bool `json:"compromised"`
	// HardwareKey: approvals are signed by a Secure Enclave / Keystore key that
	// still works.
	HardwareKey bool `json:"hardwareKey"`
	// Attestation is "apple-appattest" or "android-key", how the hardware key
	// was proven genuine; empty when it was not attested.
	Attestation string `json:"attestation,omitempty"`
	// Signed: the latest report was signed by the phone's hardware key.
	Signed bool `json:"signed"`
	// ReportedAt is the ISO date-time of the latest report.
	ReportedAt string   `json:"reportedAt,omitempty"`
	LastSeenAt string   `json:"lastSeenAt,omitempty"`
	LinkedAt   string   `json:"linkedAt,omitempty"`
	State      string   `json:"state"`
	Issues     []string `json:"issues"`
}

DevicePosture is what the Touchque app last reported about the phone it runs on, for device trust (GetUserResponse.Device). It is self-reported by the app; Signed says the phone's hardware approval key signed the latest report. An empty string means "not reported" (the API sends null).

State is "compromised" (jailbroken/rooted or tampered), "unknown" (no report, or one older than 14 days), "at_risk" (no screen lock, approval keys destroyed, no hardware key, debugger or developer mode) or "healthy". Issues lists the reasons: jailbroken, tampered, integrity_failed, no_report, stale_report, no_screen_lock, keys_lost, no_hardware_key, debugger, developer_mode.

type DryRunActionOptions

type DryRunActionOptions struct {
	ActionDraft
	// Replaces: the deployed Action this draft would replace (left out of the comparison).
	Replaces  string
	OnFailure string
	// Limit: how many recent events (1-1000; 0 = the API's 500).
	Limit int
	Since *time.Time
}

DryRunActionOptions replays a draft against recent real decisions.

type EnrollStep

type EnrollStep struct {
	QRCodeDataURL string   `json:"qrCodeDataUrl,omitempty"`
	RecoveryCodes []string `json:"recoveryCodes,omitempty"`
	// ExpiresAt is when the QR stops working (ISO 8601). Until about 15 s
	// before it, the guard's polls answer {state: "enroll", expiresAt} without
	// Enroll: keep showing this QR. Then a poll brings a new QR with new
	// recovery codes, and the old QR and the old codes stop working.
	ExpiresAt string `json:"expiresAt,omitempty"`
}

EnrollStep is shown when the user has not linked a phone yet.

type ForgetBrowsersOptions

type ForgetBrowsersOptions struct {
	ExternalUsername string
	// Thumbprint forgets one browser; leave it empty to forget every browser
	// of the user (e.g. after a password reset).
	Thumbprint string
}

ForgetBrowsersOptions selects the browsers ForgetBrowsers forgets.

type ForgetBrowsersResponse

type ForgetBrowsersResponse struct {
	Forgotten int `json:"forgotten"`
}

ForgetBrowsersResponse is the answer to ForgetBrowsers.

type FourEyes

type FourEyes struct {
	Approvers []string          `json:"approvers"`
	Above     map[string]string `json:"above,omitempty"`
	Types     []string          `json:"types,omitempty"`
}

FourEyes: a second approver for listed types or amounts over Above.

type GenerateSecretOptions

type GenerateSecretOptions struct {
	// ExternalUsername is the user's id in your system.
	ExternalUsername string
	// ClientIP and UserAgent are the end user's, from the request that asks
	// for the QR, as you send them on sign-in (LoginRequestOptions); "" leaves
	// each out. Touchque records them with the secret, never in the QR, and
	// the phone shows where the setup was started before it links
	// (ValidateSecretResponse.SetupContext). Touchque cleans them itself (a
	// port is dropped, a loopback or non-IP address is ignored, the
	// User-Agent loses control characters and is cut at 512 characters) and
	// never refuses the request over them; with neither usable, the QR has
	// no setup context.
	ClientIP  string
	UserAgent string
}

GenerateSecretOptions holds every POST /auth/generate-secret field. Use it with GenerateSecretWithOptions; GenerateSecret keeps its original signature.

type GenerateSecretResponse

type GenerateSecretResponse struct {
	Secret           string `json:"secret"`
	ExternalUsername string `json:"externalUsername"`
	ExpiresAt        string `json:"expiresAt"`
	TTLMs            int    `json:"ttlMs"`
	// QRCodeDataURL is a ready-to-render `data:image/png;base64,...` encoding
	// Secret for the Touchque mobile app to scan.
	QRCodeDataURL string   `json:"qrCodeDataUrl"`
	RecoveryCodes []string `json:"recoveryCodes"`
}

GenerateSecretResponse represents the response from generating a new secret

type GetUserResponse

type GetUserResponse struct {
	ExternalUsername string `json:"externalUsername"`
	DeviceID         string `json:"deviceId,omitempty"`
	Used             bool   `json:"used"`
	Frozen           bool   `json:"frozen"`
	CreatedAt        string `json:"createdAt"`
	ExpireAt         string `json:"expireAt,omitempty"`
	// Device is the linked phone's posture, or nil before a phone is linked.
	Device *DevicePosture `json:"device"`
}

GetUserResponse is the link status of a user (Auth.GetUser). used flips true and DeviceID is set once the mobile app scans the setup secret.

type GuardBody

type GuardBody struct {
	Touchque Step        `json:"touchque"`
	Token    string      `json:"token,omitempty"`
	Error    *GuardError `json:"error,omitempty"`
}

GuardBody is the JSON sent to the browser for every response except a successful approval.

type GuardError

type GuardError struct {
	Code    string `json:"code"`
	Message string `json:"message"`
}

GuardError is the machine-readable error alongside a refusal's body.

type GuardInput

type GuardInput struct {
	User string
	// NoEnroll: never issue a first-time linking QR (and recovery codes) for a
	// user without a phone. Set it whenever User is not proven by your own
	// sign-in, e.g. a typed username before the password step: the QR would
	// let anyone link their own phone to that account. Such a user gets 202
	// {"touchque": {"state": "enroll", "reason": "enrollment_off"}}: stop polling.
	NoEnroll    bool
	Action      string
	Details     []LoginDetail
	ReferenceID string
	IP          string
	UserAgent   string
	Token       string
	Offline     bool
	Code        string
	CodeType    string
	// BrowserProof (silent sign-ins): the browser's device-bound key proof
	// (X-Touchque-Browser), passed through untouched. Attached to the push,
	// so its approval makes the browser known.
	BrowserProof string
	// SilentSignIn (default off): a new attempt that carries BrowserProof
	// first asks Touchque (Risk.Check); when it answers prompt: false the
	// guard approves at once, with no push (Assurance.Method "silent",
	// ConfirmedVia "SILENT", RequestID "silent", Reasons). Otherwise, and on
	// any error, the usual push starts.
	SilentSignIn bool
	// SilentSignInMaxAgeSeconds is your own limit on how long ago the last
	// phone approval in this browser may be (0 = always ask). nil leaves it
	// to Touchque, which never goes beyond its own limit (7 days).
	SilentSignInMaxAgeSeconds *int
	// Context is for your Touchque Actions only (event.context). Never shown on the phone.
	Context map[string]interface{}
	// BeforeStart is for a rate limit in front of the guard. It is called at
	// most once, only for a first-time-QR token (an enroll step with its
	// expiry), right before the guard starts anything instead of keeping the
	// QR: a silent check or a push now that the phone is linked, or a new QR
	// (the old one expired, is about to, or is gone). Return a result to
	// answer it instead (your 429), or nil to go on. The relay charges its
	// per-user limit here, as for a fresh attempt.
	BeforeStart func() *GuardResult
}

GuardInput is what RunGuard needs from the current request — the same shape http_middleware.go's Require builds from a *http.Request.

type GuardRefusal

type GuardRefusal struct {
	// Status is what Require sends: 401, 403, 408, 423, 429, 500 or 503.
	Status int `json:"status"`
	// Code is the guard's error code when it set one (unauthenticated,
	// misconfigured, unavailable), else the step's Reason, else its State.
	Code string `json:"code"`
	// Message is the guard's error message when it set one, else "The
	// approval was rejected.", "The approval expired. Try again.", "Too many
	// rejected approvals. Try again later.", "Too many attempts. Try again
	// later." or "The approval was refused.", by state.
	Message string `json:"message"`
	// Touchque is a copy of the step as it would be sent.
	Touchque Step `json:"touchque"`
}

GuardRefusal is what RequireOptions.ErrorBody gets for an answer with status 400 or above.

type GuardResult

type GuardResult struct {
	Approved *Approval
	Status   int
	Body     *GuardBody
	// contains filtered or unexported fields
}

GuardResult is the outcome of one RunGuard call: either Approved is set (run the protected action) or Body/Status describe what to send instead (WriteGuardResult sends them).

func RunGuard

func RunGuard(ctx context.Context, c *Client, in GuardInput) GuardResult

RunGuard is the step-up guard behind Require and the relay, for a framework without an adapter (gin, echo, chi …) or inside your handler, after your own checks: build in from the request and its X-Touchque-* headers (GuardTokenHeader …), then run the protected action when Approved is set, else send the answer with WriteGuardResult (Status, the headers and Body as JSON). Same contract as Require; ctx (the request's) cancels the silent sign-in check. It never panics for Touchque: API errors answer 503 unavailable, a missing setup 500 misconfigured.

A nil c is the default client: built from TQ_API_KEY / TQ_API_SECRET / TQ_API_URL (New) on first use and shared with Require(nil, …) once built, so the environment is read once per process unless SetDefaultClient resets it. While it cannot be built, RunGuard answers 500 misconfigured (401 without a user) and the next call tries again. The default client built from the environment logs nothing: SetDefaultClient a client with Config.Logger to hear the guard's lines.

type GuardTokenClaims

type GuardTokenClaims struct {
	U   string `json:"u"`             // user
	A   string `json:"a"`             // action
	D   string `json:"d"`             // details digest (DetailsDigest)
	R   string `json:"r"`             // reference id
	St  string `json:"st"`            // step state (StepWaiting …)
	Rid string `json:"rid,omitempty"` // request id
	N   string `json:"n,omitempty"`   // matching number
	Oc  string `json:"oc,omitempty"`  // offline challenge id
	Cc  string `json:"cc,omitempty"`  // "Why?" case code, shown while waiting
	Ee  int64  `json:"ee,omitempty"`  // the first-time QR's expiry, ms since the epoch (enroll steps)
	Rx  int64  `json:"rx,omitempty"`  // the request's expiry, ms since the epoch (waiting / passkey_required steps)
	Exp int64  `json:"exp"`           // expiry, ms since the epoch
}

GuardTokenClaims are what a guard token carries (SignGuardToken / VerifyGuardToken): the user, action, details and reference id it is bound to, the step it was issued for and the request behind it.

func VerifyGuardToken

func VerifyGuardToken(apiSecret, token string) *GuardTokenClaims

VerifyGuardToken returns the claims of a guard token signed with apiSecret, or nil when it is malformed, signed with another key or expired. Compare U, A, D and R with the current request before you trust it.

type HostedLogin

type HostedLogin struct {
	Issuer string
	// contains filtered or unexported fields
}

HostedLogin is an OpenID Connect client for one Touchque Login tenant.

func NewHostedLogin

func NewHostedLogin(cfg HostedLoginConfig) (*HostedLogin, error)

NewHostedLogin checks the configuration. Domain must be https://, except on this machine (localhost, 127.0.0.1, ::1, *.localhost).

func (*HostedLogin) AccountURL

func (l *HostedLogin) AccountURL(section string) string

AccountURL is the hosted account page; section is "", "security", "devices" or "privacy".

func (*HostedLogin) AskUser

AskUser (CIBA) asks the user to approve on their phone.

func (*HostedLogin) AuthorizationURL

func (l *HostedLogin) AuthorizationURL(o AuthorizationOptions) (*AuthorizationRequest, error)

AuthorizationURL builds the /authorize URL with PKCE S256, state and nonce.

func (*HostedLogin) ClientCredentials

func (l *HostedLogin) ClientCredentials(ctx context.Context, audience, scope string) (*TokenSet, error)

ClientCredentials gets a machine-to-machine access token for your API.

func (*HostedLogin) ExchangeToken

func (l *HostedLogin) ExchangeToken(ctx context.Context, subjectToken, audience, scope string) (*TokenSet, error)

ExchangeToken (RFC 8693) trades a signed-in user's access token for one to call audience on their behalf (sub = the user, act.sub = this app). For a confidential app the API grants scopes to; never longer than the user's token.

func (*HostedLogin) GetConnectionToken

func (l *HostedLogin) GetConnectionToken(ctx context.Context, userAccessToken, connection, scope string) (*TokenSet, error)

GetConnectionToken (token vault) returns the provider's own access token (Google, Microsoft, GitHub…) for the signed-in user, from a connection that stores tokens. Touchque refreshes it; the refresh token never leaves. userAccessToken is the user's token for this app (or for an app the connection lists). A HostedLoginError invalid_grant means the user has not signed in with the connection since it started storing tokens, or they stopped app access.

func (*HostedLogin) HandleCallback

func (l *HostedLogin) HandleCallback(ctx context.Context, params url.Values, c CallbackChecks) (*TokenSet, error)

HandleCallback checks state (and iss), exchanges the code with the PKCE verifier and verifies the ID token. params is r.URL.Query() (or r.PostForm for response_mode=form_post).

func (*HostedLogin) LogoutURL

func (l *HostedLogin) LogoutURL(idTokenHint, postLogoutRedirectURI, state string) string

LogoutURL is where to send the browser to sign out of the hosted pages too.

func (*HostedLogin) MyAccount

func (l *HostedLogin) MyAccount(accessToken string) *MyAccount

MyAccount is the My Account API for the person holding accessToken.

func (*HostedLogin) MyAccountToken

func (l *HostedLogin) MyAccountToken(ctx context.Context, refreshToken, scope string) (*TokenSet, error)

MyAccountToken trades the refresh token a first-party app holds for a My Account API token. The refresh token rotates: keep the returned one. Scopes: read:me, update:me, manage:me:security, delete:me.

func (*HostedLogin) Refresh

func (l *HostedLogin) Refresh(ctx context.Context, refreshToken string) (*TokenSet, error)

Refresh returns a new access token and a rotated refresh token: keep the new one.

func (*HostedLogin) Revoke

func (l *HostedLogin) Revoke(ctx context.Context, token string) error

Revoke ends a refresh token and its rotated family.

func (*HostedLogin) Userinfo

func (l *HostedLogin) Userinfo(ctx context.Context, accessToken string) (map[string]interface{}, error)

Userinfo returns the signed-in user's claims for an access token.

func (*HostedLogin) VerifyAccessToken

func (l *HostedLogin) VerifyAccessToken(ctx context.Context, token, audience string, requiredScopes ...string) (map[string]interface{}, error)

VerifyAccessToken is for your API: signature, issuer, audience, expiry, typ at+jwt, scopes.

func (*HostedLogin) VerifyIDToken

func (l *HostedLogin) VerifyIDToken(ctx context.Context, idToken, nonce, accessToken string, maxAge int) (map[string]interface{}, error)

VerifyIDToken checks an ID token of this tenant for this app. nonce and accessToken are checked when not empty; maxAge when not 0 (negative: a sign-in just now, within the clock tolerance).

func (*HostedLogin) WaitForUser

func (l *HostedLogin) WaitForUser(ctx context.Context, r *UserApprovalRequest) (*TokenSet, error)

WaitForUser polls until the user answers: the tokens, or a *HostedLoginError with Code access_denied or expired_token.

type HostedLoginConfig

type HostedLoginConfig struct {
	// Domain is the tenant's sign-in domain (acme.login.touchque.com) or full issuer URL.
	Domain   string
	ClientID string
	// ClientSecret: apps with a server. SPAs and native apps leave it empty.
	ClientSecret string
	RedirectURI  string
	// Scope defaults to "openid profile email". Add offline_access for a refresh token.
	Scope string
	// Audience is your API's identifier, to get an access token for it.
	Audience string
	// ClockTolerance defaults to 60 seconds.
	ClockTolerance time.Duration
	HTTPClient     *http.Client
}

HostedLoginConfig configures a HostedLogin.

type HostedLoginError

type HostedLoginError struct {
	Code        string
	Description string
	Status      int
}

HostedLoginError is a failed sign-in or token check; Code is machine-readable.

func (*HostedLoginError) Error

func (e *HostedLoginError) Error() string

type IDJAG

type IDJAG struct {
	Assertion string
	ExpiresIn int
	Scope     string
	// DPoPBound: with a DPoPKey, whether the returned ID-JAG carries that key's thumbprint
	// (cnf.jkt); an identity provider without DPoP support ignores the proof.
	DPoPBound bool
}

IDJAG is the grant the identity provider issued.

func RequestIDJAG

func RequestIDJAG(ctx context.Context, p RequestIDJAGParams) (*IDJAG, error)

RequestIDJAG trades a member's ID token for an ID-JAG (token exchange, client_secret_basic). A token endpoint answer other than a 2xx with an ID-JAG is an *IDJAGError: a non-2xx (a 3xx too; redirects are not followed with the default client) with its Status and the body's error (server_error without a valid one), a 2xx without an ID-JAG invalid_response. No readable answer (not reached, reset, the HTTP client's timeout, an answer net/http refuses, a body that breaks off) is temporarily_unavailable with no Status and net/http's error as Err; when ctx ends (cancelled or past its deadline), its error comes back instead, for errors.Is. Every such *IDJAGError has the call's latest valid DPoPNonce.

type IDJAGClaims

type IDJAGClaims struct {
	Iss       string
	Sub       string // the member at the identity provider
	Aud       string
	ClientID  string // your client_id of the app that presented it
	JTI       string
	IssuedAt  int64
	ExpiresAt int64
	Scopes    []string
	Resource  string
	Tenant    string
	Email     string
	AuthTime  int64
	AMR       []string
	// CnfJKT is the DPoP key thumbprint the ID-JAG is bound to (cnf.jkt), when it is.
	CnfJKT string
	Claims map[string]interface{}
}

IDJAGClaims is a checked ID-JAG.

type IDJAGDPoPKey

type IDJAGDPoPKey struct {
	// PublicJWK is the public key (kty, crv, x, y) each proof carries; proofs make it from the
	// private key, never from this map.
	PublicJWK map[string]interface{}
	// Thumbprint is the RFC 7638 thumbprint: the ID-JAG's cnf.jkt.
	Thumbprint string
	// contains filtered or unexported fields
}

IDJAGDPoPKey is a DPoP key (RFC 9449, P-256) that binds an ID-JAG to its holder; keep it in this process. Make it with NewIDJAGDPoPKey or NewIDJAGDPoPKeyFrom. The private key is unexported (PrivateKey returns a copy), so encoding/json, fmt and log/slog never print it.

func NewIDJAGDPoPKey

func NewIDJAGDPoPKey() (*IDJAGDPoPKey, error)

NewIDJAGDPoPKey makes a fresh DPoP key for RequestIDJAG and RedeemIDJAG.

func NewIDJAGDPoPKeyFrom

func NewIDJAGDPoPKeyFrom(priv *ecdsa.PrivateKey) (*IDJAGDPoPKey, error)

NewIDJAGDPoPKeyFrom makes a DPoP key from a P-256 private key you keep yourself, for example to call with the DPoP-bound access token from another process. Any other key is a *ConfigError.

func (*IDJAGDPoPKey) PrivateKey

func (k *IDJAGDPoPKey) PrivateKey() *ecdsa.PrivateKey

PrivateKey returns a copy of the private key, to keep it yourself (NewIDJAGDPoPKeyFrom takes it back); nil for a key not made by NewIDJAGDPoPKey or NewIDJAGDPoPKeyFrom.

type IDJAGDPoPProofOptions

type IDJAGDPoPProofOptions struct {
	// AccessToken: a request that sends a DPoP-bound access token (Authorization: DPoP <token>)
	// carries its hash in the proof (ath).
	AccessToken string
	// Nonce: the DPoP-Nonce the server this request goes to asked for (RFC 9449 sections 8 and 9),
	// put in the proof as given (its syntax is not checked).
	Nonce string
}

IDJAGDPoPProofOptions are a DPoP proof's optional claims; "" leaves a claim out.

type IDJAGError

type IDJAGError struct {
	Code    string
	Message string
	// Status is the token endpoint's HTTP status; 0 when there was no answer (temporarily_unavailable)
	// or the error is the verifier's.
	Status int
	// DPoPNonce is the latest valid DPoP-Nonce (RFC 9449 section 8) the token endpoint sent in
	// any answer during this call (also the answer before an invalid_response or a body that
	// broke off): from the answer to the retry when that had one, else from the first answer; ""
	// when none was of valid syntax. With a DPoPKey, a token endpoint that asked for a nonce
	// (use_dpop_nonce) already got the request once more with a valid one; this field is for
	// diagnostics, and for resource requests (a proof's nonce is IDJAGDPoPProofOptions.Nonce).
	DPoPNonce string
	// Err is net/http's error when the token endpoint could not be reached or its answer read
	// (Code temporarily_unavailable); Unwrap returns it, for errors.Is and errors.As. nil otherwise.
	Err error
}

IDJAGError is a refused ID-JAG or exchange; Code is the OAuth error (invalid_grant for a bad ID-JAG; temporarily_unavailable when RequestIDJAG or RedeemIDJAG got no readable answer from the token endpoint, or the verifier could not read the identity provider's keys).

func (*IDJAGError) Error

func (e *IDJAGError) Error() string

func (*IDJAGError) Unwrap

func (e *IDJAGError) Unwrap() error

Unwrap returns Err, the transport error behind a temporarily_unavailable (nil otherwise).

type IDJAGVerifier

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

IDJAGVerifier checks the ID-JAG an authenticated client presents (jwt-bearer grant).

func NewIDJAGVerifier

func NewIDJAGVerifier(cfg IDJAGVerifierConfig) (*IDJAGVerifier, error)

NewIDJAGVerifier needs Issuer and Audience.

func (*IDJAGVerifier) Verify

func (v *IDJAGVerifier) Verify(ctx context.Context, assertion, clientID string) (*IDJAGClaims, error)

Verify checks the ID-JAG and uses it once: its claims, or *IDJAGError (Code invalid_grant). An ID-JAG bound to a DPoP key (cnf.jkt) is refused: use VerifyWithDPoP for those.

func (*IDJAGVerifier) VerifyWithDPoP

func (v *IDJAGVerifier) VerifyWithDPoP(ctx context.Context, assertion, clientID, dpopJKT string) (*IDJAGClaims, error)

VerifyWithDPoP is Verify with dpopJKT, the thumbprint of the DPoP proof you verified on this request ("" when none): an ID-JAG bound to a key (cnf.jkt) is refused without a matching one. Verify the proof, and the nonce when your server requires one, before calling it: a verified ID-JAG's jti is used up, so one spent on a request whose proof then fails cannot come again.

type IDJAGVerifierConfig

type IDJAGVerifierConfig struct {
	// Issuer is the identity provider, e.g. https://sso.touchque.com.
	Issuer string
	// Audience is your authorization server's issuer identifier (the ID-JAG's aud).
	Audience string
	// JWKSURI, when not found from the issuer's /.well-known/openid-configuration.
	JWKSURI string
	// ClockSkew allowed (default 60 s).
	ClockSkew time.Duration
	// FirstUse records an ID-JAG's jti and says whether it is new (each is used
	// once). Defaults to memory in this process; give a shared store (Redis SET
	// NX) when several processes take ID-JAGs.
	FirstUse   func(jti string, expiresAt int64) bool
	HTTPClient *http.Client
}

IDJAGVerifierConfig configures a verifier at your authorization server.

type IdentityCrud

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

IdentityCrud is list, get, create, update and delete for one kind of object.

func (*IdentityCrud) Create

func (c *IdentityCrud) Create(body map[string]interface{}) (map[string]interface{}, error)

func (*IdentityCrud) Delete

func (c *IdentityCrud) Delete(id string) (map[string]interface{}, error)

func (*IdentityCrud) Get

func (c *IdentityCrud) Get(id string) (map[string]interface{}, error)

func (*IdentityCrud) List

func (c *IdentityCrud) List(params map[string]string) ([]interface{}, error)

func (*IdentityCrud) Update

func (c *IdentityCrud) Update(id string, body map[string]interface{}) (map[string]interface{}, error)

type IdentityCustomDomains

type IdentityCustomDomains struct{ IdentityCrud }

IdentityCustomDomains is your own sign-in domains (login.acme.com): List, Overview, Get, Create ({"domain"}; the DNS records to add are in the answer), Verify, Update ({"primary": true} makes a verified domain the issuer) and Delete. CheckDomainCertificate (on client.Identity) checks a verified domain's certificate.

func (*IdentityCustomDomains) Get

func (d *IdentityCustomDomains) Get(id string) (map[string]interface{}, error)

Get returns the custom domain with this id, found in List: the API has no read by id. When there is none, the error is the API's own 404: an *APIError with StatusCode 404 and "not_found" in Data["error"] and Message.

func (*IdentityCustomDomains) Overview

Overview returns the custom domains with your organization's verified domains and the passkeys made on {slug}.login.touchque.com (GET /identity/custom-domains); List returns the domains alone.

func (*IdentityCustomDomains) Verify

func (d *IdentityCustomDomains) Verify(id string) (map[string]interface{}, error)

Verify checks the domain now (POST /identity/custom-domains/{id}/verify): its DNS TXT record until it is verified (a domain on one that your organization verified needs none) and what its DNS says (dns). The answer is the domain.

type IdentityJobs

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

IdentityJobs runs bulk imports and exports in the background.

func (*IdentityJobs) File

func (j *IdentityJobs) File(jobID string) (string, error)

File is the finished export (CSV or JSON lines), as text.

func (*IdentityJobs) Get

func (j *IdentityJobs) Get(jobID string) (map[string]interface{}, error)

func (*IdentityJobs) Start

func (j *IdentityJobs) Start(body map[string]interface{}) (map[string]interface{}, error)

Start: imports {users, upsert}; exports {format: "csv" | "json"}.

func (*IdentityJobs) Wait

func (j *IdentityJobs) Wait(jobID string, interval, timeout time.Duration) (map[string]interface{}, error)

Wait polls until the job is done or failed (or timeout passes).

type IdentityOrganizations

type IdentityOrganizations struct{ IdentityCrud }

IdentityOrganizations is business customers: members, connections, invitations.

func (*IdentityOrganizations) AddMembers

func (o *IdentityOrganizations) AddMembers(orgID string, userIDs []string) (map[string]interface{}, error)

func (*IdentityOrganizations) Invitations

func (o *IdentityOrganizations) Invitations(orgID string) (map[string]interface{}, error)

func (*IdentityOrganizations) Invite

func (o *IdentityOrganizations) Invite(orgID string, invitation map[string]interface{}) (map[string]interface{}, error)

Invite sends an invitation: {email, clientId, roleIds?, inviterName?, sendEmail?}. The link opens the app's sign-in route (initiateLoginUri) with organization and invitation.

func (*IdentityOrganizations) Members

func (o *IdentityOrganizations) Members(orgID string) (map[string]interface{}, error)

func (*IdentityOrganizations) RemoveMember

func (o *IdentityOrganizations) RemoveMember(orgID, userID string) (map[string]interface{}, error)

func (*IdentityOrganizations) RevokeInvitation

func (o *IdentityOrganizations) RevokeInvitation(orgID, invitationID string) (map[string]interface{}, error)

func (*IdentityOrganizations) SetConnections

func (o *IdentityOrganizations) SetConnections(orgID string, connections []map[string]interface{}) (map[string]interface{}, error)

type IdentityResource

type IdentityResource struct {
	Users         *IdentityUsers
	Imports       *IdentityJobs
	Exports       *IdentityJobs
	Roles         *IdentityCrud
	Organizations *IdentityOrganizations
	Clients       *IdentityCrud
	APIs          *IdentityCrud
	Connections   *IdentityCrud
	CustomDomains *IdentityCustomDomains
	// contains filtered or unexported fields
}

IdentityResource groups the Touchque Login Management API.

func (*IdentityResource) AttackEvents

func (r *IdentityResource) AttackEvents(params map[string]string) (map[string]interface{}, error)

AttackEvents lists what attack protection caught lately.

func (*IdentityResource) CheckDomainCertificate

func (r *IdentityResource) CheckDomainCertificate(domainID string) (map[string]interface{}, error)

CheckDomainCertificate checks a verified custom domain's certificate at the sign-in edge now (certificate: pending | active | error).

func (*IdentityResource) GetAttackProtection

func (r *IdentityResource) GetAttackProtection() (map[string]interface{}, error)

GetAttackProtection returns the attack protection settings: wrong passwords, suspicious addresses, bot challenge, breached passwords, new-browser notices, the risk engine.

func (*IdentityResource) GetCustomDomains

func (r *IdentityResource) GetCustomDomains() (*CustomDomainsOverview, error)

GetCustomDomains is an alias of CustomDomains.Overview: GET /identity/custom-domains as the API answers it, the domains with verifiedDomains and slugPasskeys.

func (*IdentityResource) GetDelivery

func (r *IdentityResource) GetDelivery() (map[string]interface{}, error)

GetDelivery returns the email and SMS providers; secrets never come back (secretsSet).

func (*IdentityResource) GetTenant

func (r *IdentityResource) GetTenant() (map[string]interface{}, error)

GetTenant returns the tenant (404 not_enabled until it is set up).

func (*IdentityResource) GetUserStore

func (r *IdentityResource) GetUserStore() (map[string]interface{}, error)

GetUserStore reads how your customers move in from your own user database (GET /identity/user-store): url (nil until set), enabled, active (asked: enabled and passwords on), movedIn (accounts made from it so far), lastCall ({at, event, ok, status, ms, error}, nil before the first), paused (5 failed calls in a row pause it for a minute), updatedAt and signing. For an address with no account yet, Touchque POSTs user_store.verify_password {email, password} (a password sign-in) or user_store.get_user {email} (a password reset, an email-code sign-in or a sign-up) to url, with tenant, timestamp and jti, signed like its webhooks: check each with Webhook.Verify. Answer 200 {"user": {"id", "email", "emailVerified", "name", …}} or {"user": null} (the same for an unknown address and a wrong password) within 5 seconds.

func (*IdentityResource) Outbox

func (r *IdentityResource) Outbox(params map[string]string) (map[string]interface{}, error)

Outbox is the delivery log. Message text only in the local dev inbox.

func (*IdentityResource) RemoveDelivery

func (r *IdentityResource) RemoveDelivery(channel string) (map[string]interface{}, error)

RemoveDelivery goes back to Touchque's transport.

func (*IdentityResource) RemoveUserStore

func (r *IdentityResource) RemoveUserStore() (map[string]interface{}, error)

RemoveUserStore stops asking your user database and forgets the endpoint (DELETE /identity/user-store); accounts already moved in stay. The answer is 204, so the map is nil, also when none was set: calling it again is no error. A 404 not_enabled means Touchque Login is not set up.

func (*IdentityResource) RotateClientSecret

func (r *IdentityResource) RotateClientSecret(clientID string) (map[string]interface{}, error)

RotateClientSecret gives a Touchque Login application a new client secret, shown once in the answer (clientSecret); the old one stops working.

func (*IdentityResource) RotateSigningKey

func (r *IdentityResource) RotateSigningKey() (map[string]interface{}, error)

RotateSigningKey retires the tenant's signing key and makes a new one active.

func (*IdentityResource) SetApproverAppName

func (r *IdentityResource) SetApproverAppName(name *string) (map[string]interface{}, error)

SetApproverAppName sets the phone app the hosted pages tell customers to approve on ("Approve on the Acme app"). nil: your brand name when the Mobile SDK is set up, else Touchque (approverApp in the tenant shows which).

func (*IdentityResource) SetAttackProtection

func (r *IdentityResource) SetAttackProtection(settings map[string]interface{}) (map[string]interface{}, error)

SetAttackProtection changes them (partial; the bot challenge's secret is write-only).

func (*IdentityResource) SetCustomDomainOnly

func (r *IdentityResource) SetCustomDomainOnly(on bool) (map[string]interface{}, error)

SetCustomDomainOnly serves sign-in only on the primary custom domain: {slug}.login.touchque.com redirects page loads there and refuses other calls. Turning it on needs a verified primary domain with a working certificate.

func (*IdentityResource) SetDelivery

func (r *IdentityResource) SetDelivery(channel string, provider map[string]interface{}) (map[string]interface{}, error)

SetDelivery sets your own provider for channel "email" (smtp, ses, postmark, sendgrid) or "sms" (twilio, netgsm): {"provider", "from", and its fields}. A secret left out keeps its stored value.

func (*IdentityResource) SetPasskeyDomain

func (r *IdentityResource) SetPasskeyDomain(domain string) (map[string]interface{}, error)

SetPasskeyDomain sets the domain customer passkeys are made for, their relying party ID (PUT /identity/tenant {"passkeyDomain"}): one of your verified custom domains, or a domain above one that your organization verified (Organization → Domains: "acme.com" for "login.acme.com"). Passkeys made on it or on a host under it belong to it, so they keep working when sign-in moves to another host under it. "" sends null: none, a passkey belongs to the host it was made on. The answer is the tenant, with the passkeyDomain in use. Set it before customers make passkeys on your custom domains: a change (also back to none) that would leave customer passkeys behind is refused.

Refusals are *APIError with the code in Data["error"] (also Message) and the field in Data["field"]:

  • 400 invalid_request, field passkeyDomain: not a domain;
  • 409 not_your_domain: neither a verified custom domain nor a domain above one that your organization verified;
  • 409 organization_unavailable: your organization's verified domains could not be read; try again;
  • 409 passkeys_exist: the change would leave customer passkeys behind (Data["count"]);
  • before Touchque Login is set up for the workspace: 400 invalid_request with field slug (a PUT /identity/tenant then sets it up, which needs a slug: see UpdateTenant).

func (*IdentityResource) SetUserStore

func (r *IdentityResource) SetUserStore(store map[string]interface{}) (map[string]interface{}, error)

SetUserStore sets the endpoint and whether it is asked (PUT /identity/user-store), both optional: "url" (https, no user name or password in it; left out, the one set stays) and "enabled" (left out, it keeps its value: true for a new endpoint). The answer is GetUserStore's. Refusals are *APIError with the code in Data["error"]: 409 passwords_off when it would be on while passwords are off, 400 invalid_request (Data["field"] url or enabled).

func (*IdentityResource) TestDelivery

func (r *IdentityResource) TestDelivery(channel, to string) (map[string]interface{}, error)

TestDelivery sends one test message through the provider in use.

func (*IdentityResource) TestUserStore

func (r *IdentityResource) TestUserStore(url string) (map[string]interface{}, error)

TestUserStore sends one signed user_store.ping to url, without saving it, or to the endpoint set when url is "" (POST /identity/user-store/test {"url"} or {}): {ok, error, ms}. A ping that failed is ok false with error ("answered 500", "no answer in 5 seconds"…), not a Go error; 400 invalid_request (Data["field"] url) when url is unusable, or "" with none set.

func (*IdentityResource) UpdateTenant

func (r *IdentityResource) UpdateTenant(body map[string]interface{}) (map[string]interface{}, error)

UpdateTenant turns Touchque Login on ({slug, displayName}) or changes its settings.

type IdentityUsers

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

IdentityUsers is a tenant's customer accounts.

func (*IdentityUsers) AddRoles

func (u *IdentityUsers) AddRoles(userID string, roleIDs []string, organizationID string) (map[string]interface{}, error)

AddRoles gives roles tenant-wide, or inside organizationID when it is not empty.

func (*IdentityUsers) Block

func (u *IdentityUsers) Block(userID, reason string) (map[string]interface{}, error)

Block signs the customer out everywhere and stops their sign-ins.

func (*IdentityUsers) ConnectedAccounts

func (u *IdentityUsers) ConnectedAccounts(userID string) (map[string]interface{}, error)

ConnectedAccounts lists accounts at providers whose tokens the vault keeps for the user (connections with tokenVault on).

func (*IdentityUsers) Create

func (u *IdentityUsers) Create(user map[string]interface{}) (map[string]interface{}, error)

Create adds a customer: email and password, passwordHash (bcrypt/argon2), customPasswordHash, emailVerified, name, givenName, familyName, phone, locale, userMetadata, appMetadata, sendVerificationEmail.

func (*IdentityUsers) Delete

func (u *IdentityUsers) Delete(userID string) (map[string]interface{}, error)

Delete erases the account and every workspace row that names it (KVKK/GDPR).

func (*IdentityUsers) DisconnectAccount

func (u *IdentityUsers) DisconnectAccount(userID, accountID string) (map[string]interface{}, error)

DisconnectAccount deletes the stored tokens: apps stop using the account for the user; signing in with it stays.

func (*IdentityUsers) EndSession

func (u *IdentityUsers) EndSession(userID, sessionID string) (map[string]interface{}, error)

EndSession signs the person out of one session (the others stay).

func (*IdentityUsers) Export

func (u *IdentityUsers) Export(userID string) (map[string]interface{}, error)

Export returns everything about the person (KVKK/GDPR access request); never hashes.

func (*IdentityUsers) Get

func (u *IdentityUsers) Get(userID string) (map[string]interface{}, error)

func (*IdentityUsers) List

func (u *IdentityUsers) List(params map[string]string) (map[string]interface{}, error)

List searches: q, blocked, emailVerified, connection, organization, limit, cursor.

func (*IdentityUsers) Logs

func (u *IdentityUsers) Logs(userID string) (map[string]interface{}, error)

func (*IdentityUsers) PasswordReset

func (u *IdentityUsers) PasswordReset(userID string, sendEmail bool) (map[string]interface{}, error)

PasswordReset emails a password link; with sendEmail false the link comes back for you to deliver.

func (*IdentityUsers) RemoveRole

func (u *IdentityUsers) RemoveRole(userID, roleID, organizationID string) (map[string]interface{}, error)

func (*IdentityUsers) ResetMFA

func (u *IdentityUsers) ResetMFA(userID string) (map[string]interface{}, error)

ResetMFA removes passkeys, unlinks the Touchque app, turns email codes off and signs out everywhere.

func (*IdentityUsers) Roles

func (u *IdentityUsers) Roles(userID string) (map[string]interface{}, error)

func (*IdentityUsers) SendVerificationEmail

func (u *IdentityUsers) SendVerificationEmail(userID, returnTo string) (map[string]interface{}, error)

func (*IdentityUsers) Sessions

func (u *IdentityUsers) Sessions(userID string) (map[string]interface{}, error)

func (*IdentityUsers) SignOutEverywhere

func (u *IdentityUsers) SignOutEverywhere(userID string) (map[string]interface{}, error)

func (*IdentityUsers) Unblock

func (u *IdentityUsers) Unblock(userID string) (map[string]interface{}, error)

func (*IdentityUsers) UnlinkIdentity

func (u *IdentityUsers) UnlinkIdentity(userID, identityID string, force bool) (map[string]interface{}, error)

func (*IdentityUsers) Update

func (u *IdentityUsers) Update(userID string, changes map[string]interface{}) (map[string]interface{}, error)

Update changes a customer; metadata is merged and a key set to nil is removed.

type JWKS

type JWKS struct {
	Keys []map[string]interface{} `json:"keys"`
}

JWKS is a JSON Web Key Set, as GET /agents/jwks.json answers.

type ListMobileDevicesOptions

type ListMobileDevicesOptions struct {
	ExternalUsername string
	Status           string
	Limit            int
	Cursor           string
}

ListMobileDevicesOptions filters ListDevices. Status: active (default), revoked or all.

type LoginDetail

type LoginDetail struct {
	Label string `json:"label"`
	Value string `json:"value"`
}

LoginDetail is one line of transaction context shown on the approval screen, e.g. {Label: "Amount", Value: "1,250.00 USD"}. Shown in order.

func NormalizeDetails

func NormalizeDetails(details []LoginDetail) []LoginDetail

NormalizeDetails trims each label and value the way the API does (nil in, nil out): the details a guard token and an approval are bound to.

type LoginReply

type LoginReply struct {
	CT string `json:"ct"`
	At string `json:"at,omitempty"`
}

LoginReply is what a request made with Reply holds once the person typed it back: the ciphertext only (open it with OpenCodeReply) and when.

type LoginReplyRequest

type LoginReplyRequest struct {
	Kind    string `json:"kind"`
	Key     string `json:"key"`
	Channel string `json:"channel,omitempty"`
	Target  string `json:"target,omitempty"`
}

LoginReplyRequest asks the person to type something back on the phone: today Kind "code", a sign-in code another service sent them. Key is a one-time P-256 public key (NewCodeReplyKey().PublicKey). Channel (sms, whatsapp, email, app, backup, other) and Target (the masked number or address, at most 40 characters) are shown on the phone.

type LoginRequestOptions

type LoginRequestOptions struct {
	ExternalUsername   string
	Type               string // defaults to "LOGIN"
	ReferenceID        string
	ClientIP           string // end user's IP: shown as "City, Country" on the phone
	UserAgent          string // end user's User-Agent: shown as browser + device
	RequireBiometric   bool
	RequireNumberMatch bool
	// ChallengeDigits: digits of the matching number when one is shown, 3
	// for 100-999 (0 leaves it to the workspace policy). The longer of this
	// and the workspace policy wins: a request can lengthen the number,
	// never shorten it.
	ChallengeDigits int
	// ExpiresIn: how long the push waits for the person, in seconds: 30
	// (default when 0) to 300. Longer suits a request the person has to read
	// first, such as an AI agent asking on their behalf.
	ExpiresIn int
	// QRPairing: a browser pairing by QR code (Client.QRPairings), scanned and
	// confirmed on the phone. Only the phone that scanned it is asked, once,
	// with number matching, for the user it scanned for.
	QRPairing string
	// Reply asks the person to type back on the phone a sign-in code another
	// service sent them; the phone encrypts it to Reply.Key and Status hands
	// back only the ciphertext (open it with OpenCodeReply). Such a request
	// lives 5 minutes. Not with QRPairing.
	Reply *LoginReplyRequest
	// ClientSignals: the end user's page check from @touchque/web
	// (startClientSignals().encode()), passed through untouched. A browser
	// driven by software asks with number matching, or is refused where the
	// workspace blocks it (403 automated_client).
	ClientSignals string
	// DeviceRisk: the Touchque Device Risk identification (from the Device
	// Risk SDK's tag or identify call); optional: the page's report, passed
	// through untouched. Its signals only ever ask for more, and a device your
	// admin marked "step up always" asks at once.
	DeviceRisk string
	// DeviceRiskRequestID: the Touchque Device Risk identification's requestId
	// (from the Device Risk SDK's tag or identify call); optional, preferred over DeviceRisk.
	DeviceRiskRequestID string
	// Details: transaction context for the approval screen. At most 8
	// entries, labels <= 40 and values <= 120 characters; the API rejects
	// (never truncates) anything outside those limits. Build it from
	// server-side state, never from browser input.
	Details []LoginDetail
	// BrowserProof (silent sign-ins): the browser's device-bound key proof,
	// exactly as the browser sent it (the X-Touchque-Browser header, made by
	// @touchque/web). When the user approves this request on the phone (or
	// with a passkey), Touchque remembers the browser, so a later Risk.Check
	// can let the same browser in without asking. Pass it through untouched;
	// an invalid proof only means "a browser Touchque does not know".
	BrowserProof string
	// Context is for your Touchque Actions only (event.context): roles, plan,
	// amount… Any JSON object up to 4 KB. Never shown on the phone.
	Context map[string]interface{}
	// SecurityChanges: when the user's sign-in security last changed in your system.
	SecurityChanges *SecurityChanges
	// Destination: where the action sends money or value (shown in full on the phone).
	Destination *Destination
	// Locale: "tr" (default) or "en", the language of the rows Touchque adds.
	Locale string
	// OnChallenge (VerifyWithOptions only) is called once, right after the
	// request is created and before any waiting: show ChallengeCode to the
	// user now; with number matching the phone asks for it. Not called when
	// only a passkey can approve. A panic in it is recovered and logged:
	// VerifyWithOptions keeps waiting.
	OnChallenge func(VerifyChallenge)
}

LoginRequestOptions holds every POST /login/request field. Use it with RequestWithOptions / VerifyWithOptions; Request and Verify keep their original positional signatures and cannot carry Details.

type LoginRequestResponse

type LoginRequestResponse struct {
	RequestID     string `json:"requestId"`
	ChallengeCode string `json:"challengeCode"`
	Message       string `json:"message"`
	ExpiresAt     string `json:"expiresAt"`
	// CaseCode is the "Why?" case code of this decision (K7P-2QX). Show it to
	// the user ("Tell your support team: K7P-2QX"); your team opens the whole
	// decision (each check, the rule that matched, what would have let it
	// through) by this code in the dashboard (Logs → Look up a case).
	CaseCode string `json:"caseCode,omitempty"`
	// Reasons say why number matching or a passkey is needed (a fixed list,
	// never a score); empty for a plain push.
	Reasons []RiskReason `json:"reasons,omitempty"`
	// RequiresPasskey is true when a phishing-resistant policy demands a
	// passkey approval — no push was sent for this request.
	RequiresPasskey bool `json:"requiresPasskey,omitempty"`
	// TelemetryToken is set only when the integration has behavioral biometrics
	// enabled (TenantPolicy.behavioralBiometricsEnabled). Pass it plus RequestID
	// to your frontend to initialize the @touchque/web behavioral widget
	// (tq.behavioral.attach(...)). There is no widget in this server SDK.
	TelemetryToken string `json:"telemetryToken,omitempty"`
	// Canary is the Mirror Alarm probe: the page that shows this sign-in loads
	// its URL and sends a beacon to it (@touchque/web does both), so a
	// real-time phishing proxy in front of your site gets the approval refused
	// (webhook reason phishing_origin). Allow its host in your CSP.
	Canary *Canary `json:"canary,omitempty"`
	// Destination is set only when the request had one: whether the user used
	// it before and the earlier destinations it looks like.
	Destination *DestinationCheck `json:"destination,omitempty"`
}

LoginRequestResponse represents the response from initiating a login request

type LoginResource

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

LoginResource handles sending 2FA requests and checking their status.

func (*LoginResource) ApproveWithRecoveryCode

func (l *LoginResource) ApproveWithRecoveryCode(requestID string, code string) (*ApproveWithRecoveryCodeResponse, error)

ApproveWithRecoveryCode approves a pending 2FA request using a Recovery Code (bypasses mobile device).

func (*LoginResource) Consume

func (l *LoginResource) Consume(requestID string) (*ConsumeResponse, error)

Consume uses an approved request exactly once. The first call on a CONFIRMED request wins atomically; every later call (a replayed token, a retried form post) returns an *APIError with Code "already_used" (409).

func (*LoginResource) ReportFraud

func (l *LoginResource) ReportFraud(requestID string, opts ReportFraudOptions) (*ReportFraudResponse, error)

ReportFraud reports a request you later learned was fraud — a chargeback, a confirmed account takeover, a scam the user was talked into. Touchque's risk engine learns from it (it is the strongest signal it gets) and the report is kept in your audit log. The request's status does not change. Safe to call more than once: a repeat answers AlreadyReported.

func (*LoginResource) Request

func (l *LoginResource) Request(externalUsername string, loginType string, referenceID string, clientIP string, userAgent string, requireBiometric bool, requireNumberMatch bool) (*LoginRequestResponse, error)

Request sends a 2FA login/approval request to the user's mobile device.

func (*LoginResource) RequestWithOptions

func (l *LoginResource) RequestWithOptions(opts LoginRequestOptions) (*LoginRequestResponse, error)

RequestWithOptions sends a 2FA login/approval request with every option, including Details.

func (*LoginResource) Status

func (l *LoginResource) Status(requestID string) (*LoginStatusResponse, error)

Status checks the current status of a login request.

func (*LoginResource) Verify

func (l *LoginResource) Verify(externalUsername string, loginType string, referenceID string, clientIP string, userAgent string, requireBiometric bool, requireNumberMatch bool, timeoutMs int) (*VerifyResponse, error)

Verify sends a request and waits (polls) until the user approves or rejects it.

func (*LoginResource) VerifyWithOptions

func (l *LoginResource) VerifyWithOptions(opts LoginRequestOptions, timeoutMs int) (*VerifyResponse, error)

VerifyWithOptions is Verify with every request option, including Details and OnChallenge. With number matching (your RequireNumberMatch, a workspace policy or the risk engine can turn it on) the user must pick a number on the phone: show it from OnChallenge, which runs before the wait.

client.Login.VerifyWithOptions(touchque.LoginRequestOptions{
	ExternalUsername: user, Type: "SEND_MONEY",
	OnChallenge: func(c touchque.VerifyChallenge) {
		if c.ChallengeCode != "" { show("Pick " + c.ChallengeCode + " on your phone") }
	},
}, 30000)

func (*LoginResource) WaitForApproval

func (l *LoginResource) WaitForApproval(ctx context.Context, requestID string, timeout, pollInterval time.Duration) (*VerifyResponse, error)

WaitForApproval polls a request you already sent (Request or RequestWithOptions) until the user answers on the phone: the approval, a *RejectedError when they said no, a *TimeoutError when it expired or timeout (0 = 30 seconds) ran out, or a *PasskeyRequiredError (Reason "step_up") when the Vishing Shield moved it to a passkey. pollInterval 0 is 400 ms.

sent, _ := client.Login.RequestWithOptions(touchque.LoginRequestOptions{ExternalUsername: user, Type: "SEND_MONEY"})
done, err := client.Login.WaitForApproval(ctx, sent.RequestID, 30*time.Second, 0)

type LoginStatusResponse

type LoginStatusResponse struct {
	Status           string        `json:"status"`
	ExternalUsername string        `json:"externalUsername,omitempty"`
	Type             string        `json:"type,omitempty"`
	ReferenceID      string        `json:"referenceId,omitempty"`
	Details          []LoginDetail `json:"details,omitempty"`
	Consumed         bool          `json:"consumed,omitempty"`
	// RequiresPasskey: only a passkey can approve it — a phishing-resistant
	// policy, or the Vishing Shield moved it to a passkey at the phone tap
	// because the user was on a call (it is still PENDING then).
	RequiresPasskey bool       `json:"requiresPasskey,omitempty"`
	ConfirmedVia    string     `json:"confirmedVia,omitempty"`
	Assurance       *Assurance `json:"assurance,omitempty"`
	// ExpiresAt is the request's live expiry (ISO 8601): a Vishing Shield
	// escalation to a passkey extends it.
	ExpiresAt string `json:"expiresAt,omitempty"`
	// Reply: a request made with Reply, once the person typed it back (the
	// ciphertext only; OpenCodeReply opens it). nil for a CONFIRMED request
	// approved without typing (an older app).
	Reply *LoginReply `json:"reply,omitempty"`
	ShieldFields
}

LoginStatusResponse represents the response from checking login status.

type Mandate

type Mandate struct {
	MandateID string `json:"mandateId"`
	// Status: pending, active, rejected, expired, provisional, revoked, exhausted.
	Status           string            `json:"status"`
	ExternalUsername string            `json:"externalUsername"`
	Type             string            `json:"type"`
	MaxCount         int               `json:"maxCount"`
	UsedCount        int               `json:"usedCount"`
	MaxTotal         map[string]string `json:"maxTotal"`
	Used             map[string]string `json:"used"`
	PerRequest       map[string]string `json:"perRequest"`
	Recipients       []string          `json:"recipients"`
	ValidUntil       string            `json:"validUntil"`
	ChallengeCode    string            `json:"challengeCode"`
	RevokedAt        string            `json:"revokedAt"`
}

Mandate is a mandate's state and what is left.

type MandateParams

type MandateParams struct {
	User     string
	Type     string
	MaxCount int
	// MaxTotal: {"currency": "TRY", "amount": "1000"}.
	MaxTotal   map[string]string
	PerRequest string
	// Recipients: IBANs / account numbers it may pay; none = any.
	Recipients []string
	// ValidFor: seconds it lasts (300-604800, default 86400).
	ValidFor  int
	Reason    string
	ExpiresIn int
	Locale    string
}

MandateParams asks a person for a mandate: one approval on the phone for a bounded series of requests.

type McpAuth

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

McpAuth verifies tokens Touchque SSO issued for one MCP server.

func NewMcpAuth

func NewMcpAuth(cfg McpAuthConfig) (*McpAuth, error)

NewMcpAuth needs Issuer and Resource.

func (*McpAuth) MetadataPaths

func (m *McpAuth) MetadataPaths() []string

MetadataPaths are where to serve ProtectedResourceMetadata.

func (*McpAuth) MetadataURL

func (m *McpAuth) MetadataURL() string

MetadataURL is the resource_metadata URL in WWW-Authenticate.

func (*McpAuth) Middleware

func (m *McpAuth) Middleware(next http.Handler) http.Handler

Middleware serves the protected resource metadata at MetadataPaths and verifies every other request; the claims are in McpClaimsFrom(r.Context()).

func (*McpAuth) ProtectedResourceMetadata

func (m *McpAuth) ProtectedResourceMetadata() map[string]interface{}

ProtectedResourceMetadata is this server's RFC 9728 document.

func (*McpAuth) RequireScope

func (m *McpAuth) RequireScope(c *McpClaims, scope string) error

RequireScope refuses with 403 insufficient_scope unless the token has scope.

func (*McpAuth) RequireTool

func (m *McpAuth) RequireTool(c *McpClaims, tool string) error

RequireTool refuses with 403 insufficient_scope unless the token has the tool's scope.

func (*McpAuth) Verify

func (m *McpAuth) Verify(r *http.Request) (*McpClaims, error)

Verify checks a request's token. The DPoP proof's htu is compared with Resource's origin plus the request path, so it holds behind a proxy that terminates TLS.

type McpAuthConfig

type McpAuthConfig struct {
	// Issuer is Touchque SSO's MCP issuer, e.g. https://sso.touchque.com/mcp.
	Issuer string
	// Resource is this MCP server's URL, exactly as registered in Touchque.
	Resource string
	// Tools maps a tool name to the scope it needs (also listed as scopes_supported).
	Tools map[string]string
	// ResourceName is a human-readable name for the metadata.
	ResourceName string
	// ClockSkew allowed (default 60 s).
	ClockSkew time.Duration
	// HTTPClient reads the issuer's metadata and JWKS (default: 5 s timeout).
	HTTPClient *http.Client
}

McpAuthConfig configures NewMcpAuth.

type McpAuthError

type McpAuthError struct {
	Status          int
	Code            string
	Message         string
	WWWAuthenticate string
}

McpAuthError is a refused request: answer with Status and the WWW-Authenticate header. Code is missing_token, invalid_token, invalid_dpop_proof or insufficient_scope.

func (*McpAuthError) Error

func (e *McpAuthError) Error() string

type McpClaims

type McpClaims struct {
	Sub       string
	Email     string
	ClientID  string
	Scopes    []string
	OrgID     string
	ExpiresAt time.Time
	DPoPBound bool
	Claims    map[string]interface{}
}

McpClaims is a verified token: the member (Sub, Email) an AI tool (ClientID, its client ID metadata document URL) acts for.

func McpClaimsFrom

func McpClaimsFrom(ctx context.Context) *McpClaims

McpClaimsFrom is the verified token Middleware put in the request context.

type MemberRequest

type MemberRequest struct {
	AuthReqID string
	ExpiresIn int
	Interval  int
	// BindingCode: show it in the conversation; the member picks it on the phone.
	BindingCode string
}

MemberRequest is a CIBA request waiting for the member.

type MemoryReplayCache

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

MemoryReplayCache is an in-process WebhookReplayCache. Entries expire after their TTL and the map is capped. Safe for concurrent use.

func NewMemoryReplayCache

func NewMemoryReplayCache() *MemoryReplayCache

NewMemoryReplayCache returns an in-process replay cache.

func (*MemoryReplayCache) CheckAndSet

func (c *MemoryReplayCache) CheckAndSet(jti string, ttl time.Duration) bool

CheckAndSet implements WebhookReplayCache.

type MobileDevice

type MobileDevice struct {
	DeviceID         string `json:"deviceId"`
	ExternalUsername string `json:"externalUsername"`
	Platform         string `json:"platform"`
	AppID            string `json:"appId,omitempty"`
	SDKVersion       string `json:"sdkVersion,omitempty"`
	// Attestation is "apple-appattest" / "android-key" when the app and its key were proven.
	Attestation   string `json:"attestation,omitempty"`
	Status        string `json:"status"`
	RevokedReason string `json:"revokedReason,omitempty"`
	RevokedAt     string `json:"revokedAt,omitempty"`
	EnrolledAt    string `json:"enrolledAt"`
	LastSeenAt    string `json:"lastSeenAt,omitempty"`
	// Linked (GetDevice only) says whether it is the user's approver right now.
	Linked      *bool `json:"linked,omitempty"`
	HardwareKey *struct {
		Registered  bool   `json:"registered"`
		Attestation string `json:"attestation,omitempty"`
		LostAt      string `json:"lostAt,omitempty"`
	} `json:"hardwareKey,omitempty"`
	PushToken bool                   `json:"pushToken"`
	Posture   map[string]interface{} `json:"posture,omitempty"`
}

MobileDevice is a device inside your app that approves for one of your users.

type MobileDevices

type MobileDevices struct {
	Devices    []MobileDevice `json:"devices"`
	NextCursor string         `json:"nextCursor,omitempty"`
}

MobileDevices is one page of devices.

type MobileEnrollment

type MobileEnrollment struct {
	EnrollmentID     string `json:"enrollmentId"`
	EnrollmentToken  string `json:"enrollmentToken"`
	ExternalUsername string `json:"externalUsername"`
	ExpiresAt        string `json:"expiresAt"`
	Replace          bool   `json:"replace"`
	// ReplacesDeviceID is, with Replace, the device that approves today.
	ReplacesDeviceID string `json:"replacesDeviceId,omitempty"`
}

MobileEnrollment is a one-time enrollment token. Hand EnrollmentToken to your app over your own signed-in API; never put it in a URL or QR code.

type MobilePush

type MobilePush struct {
	DeviceID         string
	ExternalUsername string
	Platform         string
	// PushToken is the token your app handed to the SDK; empty: send to the
	// user's devices by your own mapping.
	PushToken string
	RequestID string
	ExpiresAt string
	Kind      string
	// Alert is suggested text (English); translate or replace it.
	Alert map[string]string
	// APNs is the APNs payload: the alert plus the custom key "touchque".
	APNs map[string]interface{}
	// FCMData is the FCM data map (a data message; your app builds the notification).
	FCMData map[string]string
}

MobilePush is a MOBILE_PUSH webhook, ready to send with your own APNs / FCM credentials.

func MobilePushFromWebhook

func MobilePushFromWebhook(event map[string]interface{}) (push *MobilePush, ok bool)

MobilePushFromWebhook turns a verified MOBILE_PUSH webhook into the push to send; ok is false for any other event. The data carries no secret, no details and no matching number.

func (*MobilePush) Expired

func (p *MobilePush) Expired(now time.Time) bool

Expired reports whether the push is past its request's expiry (don't send it any more).

type MobilePushSettings

type MobilePushSettings struct {
	IOS     string `json:"ios"`
	Android string `json:"android"`
	APNs    *struct {
		KeyID      string `json:"keyId"`
		TeamID     string `json:"teamId"`
		Topic      string `json:"topic"`
		Production bool   `json:"production"`
	} `json:"apns"`
	FCM *struct {
		ProjectID   string `json:"projectId"`
		ClientEmail string `json:"clientEmail"`
	} `json:"fcm"`
}

MobilePushSettings says who sends the push per platform: "touchque" (with your own APNs key / FCM service account) or "webhook" (MOBILE_PUSH to you). The keys themselves are never shown back.

type MobileResource

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

MobileResource is the Touchque Mobile SDK, your backend's side: your own iOS/Android app is the approver of your users (white-label); they never install the Touchque app.

  1. A user signed in to your app turns approvals on: CreateEnrollment gives a one-time token; your app hands it to the SDK (Touchque.enroll).
  2. Ask for approvals as always (Login.Request, Start, the middleware...): they reach your app over the SDK's encrypted connection.
  3. Touchque holds no push key of your app. For each request it sends you a signed MOBILE_PUSH webhook: verify it (Webhook), then MobilePushFromWebhook gives the APNs payload / FCM data to send with your own credentials.

func (*MobileResource) CreateEnrollment

CreateEnrollment issues a one-time enrollment token for a user you signed in. Whoever spends it becomes the user's approver, so authenticate the user first.

func (*MobileResource) GetDevice

func (m *MobileResource) GetDevice(deviceID string) (*MobileDevice, error)

GetDevice reads one device inside your app.

func (*MobileResource) ListDevices

ListDevices lists the devices inside your app, newest first.

func (*MobileResource) RemoveDevice

func (m *MobileResource) RemoveDevice(deviceID string) (bool, error)

RemoveDevice stops a device from approving (the user has no approver until you enrol again). It reports whether the device was the user's approver.

func (*MobileResource) Settings

func (m *MobileResource) Settings() (*MobileSDKSettings, error)

Settings reads your Mobile SDK settings (defaults when never set).

func (*MobileResource) TestPush

func (m *MobileResource) TestPush(deviceID string) (*MobileTestPush, error)

TestPush sends a harmless push to the device, the way a request would reach it.

func (*MobileResource) UpdateSettings

func (m *MobileResource) UpdateSettings(changes map[string]interface{}) (*MobileSDKSettings, error)

UpdateSettings changes only the keys given: iosAppIds, androidPackages, androidCerts (package → SHA-256 of its signing certificate), attestation (off | optional | required), enrollTtlSeconds, apns ({keyId, teamId, topic, key: the .p8 text, production}: Touchque then sends the iOS push itself) and fcm ({serviceAccount: the JSON}: the Android push); nil removes a key.

type MobileSDKSettings

type MobileSDKSettings struct {
	IOSAppIDs        []string            `json:"iosAppIds"`
	AndroidPackages  []string            `json:"androidPackages"`
	AndroidCerts     map[string][]string `json:"androidCerts"`
	Attestation      string              `json:"attestation"`
	EnrollTTLSeconds int                 `json:"enrollTtlSeconds"`
	Push             MobilePushSettings  `json:"push"`
	UpdatedAt        string              `json:"updatedAt,omitempty"`
}

MobileSDKSettings says which apps may enrol and whether they must prove themselves.

type MobileTestPush

type MobileTestPush struct {
	Via    string `json:"via"`
	OK     bool   `json:"ok"`
	Reason string `json:"reason,omitempty"`
}

MobileTestPush says how a test push went: Via "touchque" (your key for the device's platform) or "webhook" (MOBILE_PUSH, kind "test"); OK when APNs / FCM accepted it (or the webhook left).

type MyAccount

type MyAccount struct {
	Issuer string
	// contains filtered or unexported fields
}

MyAccount calls /me/v1 for one person.

func NewMyAccount

func NewMyAccount(domain, accessToken string, client *http.Client) *MyAccount

NewMyAccount makes a client for the person holding accessToken (audience https://<domain>/me/).

func (*MyAccount) AccountPageURL

func (m *MyAccount) AccountPageURL(section string) string

AccountPageURL is the hosted account page; section is "", "security", "devices" or "privacy".

func (*MyAccount) Apps

func (m *MyAccount) Apps(ctx context.Context) (map[string]interface{}, error)

func (*MyAccount) AuthenticationMethods

func (m *MyAccount) AuthenticationMethods(ctx context.Context) (map[string]interface{}, error)

func (*MyAccount) ChangeEmail

func (m *MyAccount) ChangeEmail(ctx context.Context, email string) (map[string]interface{}, error)

ChangeEmail sends a confirmation link to the new address. Needs a recent sign-in.

func (*MyAccount) Consents

func (m *MyAccount) Consents(ctx context.Context) (map[string]interface{}, error)

func (*MyAccount) DeleteAccount

func (m *MyAccount) DeleteAccount(ctx context.Context) (map[string]interface{}, error)

DeleteAccount erases the account at once. Needs delete:me and a recent sign-in.

func (*MyAccount) EndOtherSessions

func (m *MyAccount) EndOtherSessions(ctx context.Context) (map[string]interface{}, error)

EndOtherSessions signs out every other device.

func (*MyAccount) EndSession

func (m *MyAccount) EndSession(ctx context.Context, id string) error

func (*MyAccount) ExportData

func (m *MyAccount) ExportData(ctx context.Context) (map[string]interface{}, error)

ExportData returns everything about the person (KVKK/GDPR). Needs a recent sign-in.

func (*MyAccount) Get

func (m *MyAccount) Get(ctx context.Context) (map[string]interface{}, error)

Get returns the profile, the sign-in methods and the account page URL.

func (*MyAccount) GetProfile

func (m *MyAccount) GetProfile(ctx context.Context) (map[string]interface{}, error)

func (*MyAccount) RemovePasskey

func (m *MyAccount) RemovePasskey(ctx context.Context, id string) error

RemovePasskey needs a recent sign-in.

func (*MyAccount) RemovePassword

func (m *MyAccount) RemovePassword(ctx context.Context) error

RemovePassword needs a recent sign-in and another way to sign in.

func (*MyAccount) RemoveSMSCodes

func (m *MyAccount) RemoveSMSCodes(ctx context.Context) error

RemoveSMSCodes needs a recent sign-in.

func (*MyAccount) RenamePasskey

func (m *MyAccount) RenamePasskey(ctx context.Context, id, label string) error

func (*MyAccount) RevokeApp

func (m *MyAccount) RevokeApp(ctx context.Context, clientID string) (map[string]interface{}, error)

func (*MyAccount) SendVerificationEmail

func (m *MyAccount) SendVerificationEmail(ctx context.Context) error

func (*MyAccount) Sessions

func (m *MyAccount) Sessions(ctx context.Context) (map[string]interface{}, error)

func (*MyAccount) SetEmailCodes

func (m *MyAccount) SetEmailCodes(ctx context.Context, enabled bool) error

SetEmailCodes turns email codes as a second step on or off. Needs a recent sign-in.

func (*MyAccount) SetMarketing

func (m *MyAccount) SetMarketing(ctx context.Context, granted bool) error

func (*MyAccount) SetPassword

func (m *MyAccount) SetPassword(ctx context.Context, password string) (map[string]interface{}, error)

SetPassword sets or changes the password; other sessions end. Needs a recent sign-in.

func (*MyAccount) StartSMSEnrollment

func (m *MyAccount) StartSMSEnrollment(ctx context.Context, phone string) (map[string]interface{}, error)

StartSMSEnrollment texts a code to a new number for text-message codes. Needs a recent sign-in.

func (*MyAccount) StopAppAccess

func (m *MyAccount) StopAppAccess(ctx context.Context, id string) error

StopAppAccess makes apps stop using a linked account for the person (token vault: the identity's appAccess id); signing in with it stays.

func (*MyAccount) UnlinkIdentity

func (m *MyAccount) UnlinkIdentity(ctx context.Context, id string) error

UnlinkIdentity disconnects a linked account. Needs a recent sign-in.

func (*MyAccount) UnlinkTouchqueApp

func (m *MyAccount) UnlinkTouchqueApp(ctx context.Context) error

UnlinkTouchqueApp needs a recent sign-in.

func (*MyAccount) UpdateProfile

func (m *MyAccount) UpdateProfile(ctx context.Context, changes map[string]interface{}) (map[string]interface{}, error)

UpdateProfile changes name, givenName, familyName, nickname, locale; userMetadata is merged and a key set to nil is removed.

func (*MyAccount) VerifySMSEnrollment

func (m *MyAccount) VerifySMSEnrollment(ctx context.Context, code string) (map[string]interface{}, error)

VerifySMSEnrollment checks the code from that text; text-message codes are then on. Needs a recent sign-in.

type MyAccountError

type MyAccountError struct {
	Code        string
	Description string
	Status      int
	// MaxAge is the sign-in age (seconds) the call needs, on a step-up answer.
	MaxAge int
}

MyAccountError is a failed My Account API call.

func (*MyAccountError) Error

func (e *MyAccountError) Error() string

func (*MyAccountError) StepUp

func (e *MyAccountError) StepUp() bool

StepUp is true when the sign-in is too old for this change (RFC 9470).

type NetworkError

type NetworkError struct {
	Message string
}

NetworkError means the request never reached the API (DNS, connection, timeout).

func (*NetworkError) Error

func (e *NetworkError) Error() string

type OfflineChallengeOptions

type OfflineChallengeOptions struct {
	ExternalUsername string
	Type             string // defaults to "LOGIN"
	// Details: shown on the phone (see LoginRequestOptions.Details). REQUIRED
	// for critical action types.
	Details    []LoginDetail
	ClientIP   string
	UserAgent  string
	TTLSeconds int // 30-300, default 120
	// SkipQRImage: set true to omit the ready-made QR image (QRDataURL comes
	// back empty) when you only need the raw QR text.
	SkipQRImage bool
	// RequestID is the push this QR is a fallback for: once the phone REJECTS
	// it the QR is dead (no new QR is issued, a code for the old one is refused
	// with reason "request_rejected"), and a push with number matching makes the
	// QR show the same number. Always set it when the QR follows a push.
	RequestID string
	// RequireNumberMatch asks for number matching on a standalone QR (implied
	// when RequestID points at a push that has one).
	RequireNumberMatch bool
	// QRFormat "compact" asks for a smaller QR (QR starts with "TQ3:") for
	// terminals and small screens: the same challenge and the same
	// 7-character code, without the location block, so put what the phone
	// should show in Details. Empty means "standard" (TQ2.…).
	QRFormat string
	// IncludeQRTerminal also returns QRTerminal: the QR drawn with Unicode
	// half blocks, ready to print in a terminal.
	IncludeQRTerminal bool
}

OfflineChallengeOptions holds every POST /offline/challenge field.

type OfflineChallengeResponse

type OfflineChallengeResponse struct {
	ChallengeID string `json:"challengeId"`
	// QR is the raw challenge text (TQ2.…, or TQ3:… for the compact format —
	// encrypted for the user's phone); draw it as a QR code yourself if you
	// don't use QRDataURL.
	QR string `json:"qr"`
	// QRFormat is the format of QR: "standard" or "compact".
	QRFormat string `json:"qrFormat,omitempty"`
	// QRDataURL is `data:image/png;base64,…`, ready for an <img> src; empty
	// when IncludeQRImage is false.
	QRDataURL string `json:"qrDataUrl"`
	// QRTerminal is the QR drawn with Unicode half blocks, lines separated by
	// "\n", ready to print in a terminal. Only with IncludeQRTerminal (empty
	// when it could not be drawn).
	QRTerminal       string `json:"qrTerminal,omitempty"`
	ExpiresAt        string `json:"expiresAt"`
	ExpiresInSeconds int    `json:"expiresInSeconds"`
	// TotpAvailable is true when the workspace allows the time-based code
	// fallback (no camera).
	TotpAvailable bool `json:"totpAvailable"`
	// ChallengeCode is the number to print under the QR (number matching).
	// Empty when the QR needs no number matching.
	ChallengeCode string `json:"challengeCode,omitempty"`
}

OfflineChallengeResponse is returned by Challenge.

type OfflineDeviceKDF

type OfflineDeviceKDF struct {
	Name       string `json:"name"`
	Iterations int    `json:"iterations"`
	Length     int    `json:"length"`
}

OfflineDeviceKDF is how the slot digests were made: PBKDF2-SHA256 with Iterations iterations and Length bytes.

type OfflineDevicePack

type OfflineDevicePack struct {
	// Scope is the scope as Touchque stored it (ID in lower case, Name
	// cleaned) with its Epoch.
	Scope   OfflineDeviceScope `json:"scope"`
	Account string             `json:"account"`
	// ValidUntil: the slots are not valid after this time.
	ValidUntil time.Time `json:"validUntil"`
	// CodeLength is the number of characters of a slot's code (10).
	CodeLength int                 `json:"codeLength"`
	KDF        OfflineDeviceKDF    `json:"kdf"`
	Slots      []OfflineDeviceSlot `json:"slots"`
}

OfflineDevicePack is a device's next offline sign-ins for one person. Nothing in it can produce a code.

type OfflineDevicePackOptions

type OfflineDevicePackOptions struct {
	ExternalUsername string
	// Scope is the device (ID and Name; Epoch is not sent).
	Scope OfflineDeviceScope
	// Account is the account the person signs in to on that device
	// (ACME\jane), 1-255 characters, shown on the phone.
	Account string
	// Count: how many new slots (offline sign-ins), 1-20 (0: the default, 10).
	Count int
	// ValidDays: how long the slots are valid for, from now, 1-30 days (0: the
	// default, 14).
	ValidDays int
}

OfflineDevicePackOptions holds the POST /offline/device-packs fields.

type OfflineDeviceReportOptions

type OfflineDeviceReportOptions struct {
	ScopeID          string
	ExternalUsername string
	// Used: 1-100 slots.
	Used []OfflineDeviceUse
}

OfflineDeviceReportOptions holds the POST /offline/device-packs/report fields.

type OfflineDeviceReportResult

type OfflineDeviceReportResult struct {
	Recorded int `json:"recorded"`
	Ignored  int `json:"ignored"`
}

OfflineDeviceReportResult says how many slots were recorded and how many were ignored (an index never issued or repeated, or a time more than 60 days ago or in the future).

type OfflineDeviceRevokeOptions

type OfflineDeviceRevokeOptions struct {
	// ScopeID is the device's scope id.
	ScopeID string
	// ExternalUsername: only this person's packs on the device (empty: every person's).
	ExternalUsername string
	// Reason: up to 64 characters, such as "lost", "stolen" or "reinstalled" (empty: "revoked").
	Reason string
}

OfflineDeviceRevokeOptions holds the POST /offline/device-packs/revoke fields.

type OfflineDeviceRevokeResult

type OfflineDeviceRevokeResult struct {
	Revoked int `json:"revoked"`
}

OfflineDeviceRevokeResult says how many packs (one per person on the device) were revoked.

type OfflineDeviceScope

type OfflineDeviceScope struct {
	// ID: 1-64 characters of a-z, 0-9, ".", "_", "-", starting with a letter
	// or a digit (compared in lower case). One id per device for as long as it
	// is installed; a reinstalled device gets a new one.
	ID string `json:"id"`
	// Name: 1-80 characters, the device's name shown on the person's phone.
	Name string `json:"name"`
	// Epoch is set in answers only: random per person and device.
	Epoch string `json:"epoch,omitempty"`
}

OfflineDeviceScope is the device an offline sign-in pack is for.

type OfflineDeviceSlot

type OfflineDeviceSlot struct {
	// Index is the slot number; Touchque never issues an index twice.
	Index int `json:"index"`
	// Salt: base64.
	Salt string `json:"salt"`
	// Digest: base64, PBKDF2-SHA256(code, salt || ":" || index, KDF.Iterations, KDF.Length).
	Digest string `json:"digest"`
	// QR is the slot QR (TQ4:...): show it on the device's screen.
	QR string `json:"qr"`
	// QRTerminal is the same QR drawn with Unicode half blocks, lines
	// separated by "\n", for a terminal (empty when it could not be drawn).
	QRTerminal string `json:"qrTerminal,omitempty"`
}

OfflineDeviceSlot is one offline sign-in: the slow digest of its 10-character code and the QR only the person's phone opens.

type OfflineDeviceUse

type OfflineDeviceUse struct {
	Index int
	// At is when the person signed in (within the last 60 days); sent in UTC.
	At time.Time
}

OfflineDeviceUse is a slot the device accepted while it had no network.

type OfflineOutageScope

type OfflineOutageScope struct {
	// ID: 1-64 characters of a-z, 0-9, ".", "_", "-" (compared in lower case). Keep it stable.
	ID string `json:"id"`
	// Name: 1-80 characters, shown on the user's phone under the normal
	// time-based code: "<name>: code for when Touchque can't be reached".
	Name string `json:"name"`
}

OfflineOutageScope is what outage codes are for: one organization, or your own outage server(s). Each scope has its own codes, so digests fetched for one scope are worthless for any other, and VerifyTotp never accepts an outage code.

type OfflineResource

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

OfflineResource is Offline Sign — QR challenge / typed code approvals that work with the phone offline (no internet on the device).

func (*OfflineResource) Challenge

Challenge issues an offline QR challenge.

func (*OfflineResource) IssueDevicePack

func (o *OfflineResource) IssueDevicePack(opts OfflineDevicePackOptions) (*OfflineDevicePack, error)

IssueDevicePack asks for the next offline sign-ins of a person on one device that must sign them in with no network. Ask only right after a sign-in the person approved on the phone at that device itself, never for a remote session. Each slot is the slow digest of a 10-character code and a QR (TQ4:) only the person's phone opens. Offline, the device shows the lowest unused slot's QR; the person scans it with the Touchque app, approves and types the code (XXXXX-XXXXX); check it with VerifyDeviceCode. Indexes continue from the device's last pack and are never issued twice. Requires the workspace policies offlineSignEnabled and offlineDevicePacksEnabled (403 offline_device_packs_disabled); refused under a passkey-only policy (403 phishing_resistant_required), for a phone not enrolled for offline sign (409 device_not_enrolled_for_offline), for a revoked device (409 scope_revoked) and after 12 packs an hour per person and device (429 too_many_packs).

func (*OfflineResource) ReportDevicePackUse

ReportDevicePackUse sends the slots a device accepted while it had no network, once it is back online: Touchque writes one log row per slot with the time it happened (404 unknown_scope when the device has no pack for that person).

func (*OfflineResource) RevokeDeviceScope

RevokeDeviceScope stops a device's offline sign-ins (lost, stolen, reinstalled): it gets no more packs, and the person's phone refuses its codes once it has the list. A reinstalled device needs a new scope id.

func (*OfflineResource) TotpVerifiers

TotpVerifiers is for checking typed codes while your server cannot reach Touchque (an outage): salted, slow digests of each user's next OUTAGE codes for one scope, never a key. Outage codes are not the normal time-based code: each scope (an organization, or your own outage server) has its own, the user's phone shows them under the normal code ("<name>: code for when Touchque can't be reached") once a call has named the scope for the user, and VerifyTotp never accepts them. Check a typed code with MatchTotpVerifier. Requires the workspace policies offlineTotpEnabled and outageVerifiersEnabled. Fetch again every few minutes from the step you have: removed and frozen users fall out. Quotas are per scope (429 scope_quota_exceeded) and per workspace.

func (*OfflineResource) Verify

func (o *OfflineResource) Verify(challengeID, code string) (*OfflineVerifyResult, error)

Verify checks the 7-character code shown on the phone.

func (*OfflineResource) VerifyTotp

func (o *OfflineResource) VerifyTotp(externalUsername, code, loginType, clientIP string) (*OfflineVerifyResult, error)

VerifyTotp checks the rolling time-based code (no QR scan needed). Refused for critical action types.

func (*OfflineResource) VerifyTotpFor

func (o *OfflineResource) VerifyTotpFor(externalUsername, code, loginType, clientIP, requestID string) (*OfflineVerifyResult, error)

VerifyTotpFor is VerifyTotp for a sign-in that started with a push: requestID is that push, and a code is refused (reason "request_rejected") once the phone rejected it.

type OfflineStep

type OfflineStep struct {
	ChallengeID   string `json:"challengeId,omitempty"`
	QRDataURL     string `json:"qrDataUrl,omitempty"`
	ExpiresAt     string `json:"expiresAt,omitempty"`
	TotpAvailable bool   `json:"totpAvailable,omitempty"`
	AttemptsLeft  int    `json:"attemptsLeft,omitempty"`
	// ChallengeCode is the number to print under the QR when number matching
	// applies: the phone offers it among two decoys and the user taps the match.
	ChallengeCode string `json:"challengeCode,omitempty"`
}

OfflineStep is shown while the user types the code from an offline challenge.

type OfflineTotpVerifierUser

type OfflineTotpVerifierUser struct {
	ExternalUsername string `json:"externalUsername"`
	// FromStep: this user's first step.
	FromStep int64 `json:"fromStep"`
	// Salt: base64, 16 bytes.
	Salt string `json:"salt"`
	// Digests: base64, KDF.Length bytes per digest, DigestsPerStep digests per
	// step from FromStep.
	Digests string `json:"digests"`
}

OfflineTotpVerifierUser is one user's digests.

type OfflineTotpVerifiers

type OfflineTotpVerifiers struct {
	StepSeconds  int64 `json:"stepSeconds"`
	FromStep     int64 `json:"fromStep"`
	Steps        int   `json:"steps"`
	NotAfterStep int64 `json:"notAfterStep"`
	// Scope is the scope as Touchque stored it (id in lower case, name cleaned).
	Scope *OfflineOutageScope `json:"scope,omitempty"`
	// DigestsPerStep: 1, the scope's outage code (answers without it, 0 here, had 2).
	DigestsPerStep int `json:"digestsPerStep"`
	KDF            struct {
		Name       string `json:"name"`
		Iterations int    `json:"iterations"`
		Length     int    `json:"length"`
	} `json:"kdf"`
	// Users: only those who can use time-based codes now and whose phone shows this scope.
	Users []OfflineTotpVerifierUser `json:"users"`
}

OfflineTotpVerifiers is returned by TotpVerifiers.

type OfflineTotpVerifiersOptions

type OfflineTotpVerifiersOptions struct {
	// ExternalUsernames: up to 1,000 users; users x steps at most 24,000 a call.
	ExternalUsernames []string
	// Scope is required: the organization or server these codes are for. The
	// user's phone shows this scope's code once a call has named it for them.
	Scope OfflineOutageScope
	// FromStep: the first 30-second step (0: the current one).
	FromStep int64
	// Steps: how many, 1-480 (0: 480, four hours).
	Steps int
}

OfflineTotpVerifiersOptions holds the POST /offline/totp/verifiers fields.

type OfflineVerifyResult

type OfflineVerifyResult struct {
	Approved         bool   `json:"approved"`
	Reason           string `json:"reason,omitempty"`
	AttemptsLeft     int    `json:"attemptsLeft,omitempty"`
	ChallengeID      string `json:"challengeId,omitempty"`
	ExternalUsername string `json:"externalUsername,omitempty"`
	Type             string `json:"type,omitempty"`
}

OfflineVerifyResult is common to Verify and VerifyTotp: never an error for a wrong/expired/used code — check Approved. Reason is one of invalid_code | locked | expired | used | unknown_challenge | request_rejected | too_many_failures | device_not_enrolled.

type OpenAssistOptions

type OpenAssistOptions struct {
	ExternalUsername string
	Agent            AssistAgent
	// Reason is a ticket or a few words, for the log.
	Reason string
	// TTLMinutes is 5–120; 0 means the default, 30.
	TTLMinutes int
	// NoNotice skips the calm notice on the person's phone.
	NoNotice bool
}

OpenAssistOptions starts helping a person.

type OrgAgent

type OrgAgent struct {
	AgentID string
	// contains filtered or unexported fields
}

OrgAgent is an organization's AI agent client.

func NewOrgAgent

func NewOrgAgent(cfg OrgAgentConfig) (*OrgAgent, error)

NewOrgAgent builds an OrgAgent; it checks the configuration, it does not call Touchque.

func (*OrgAgent) AskMember

func (a *OrgAgent) AskMember(p AskMemberParams) (*MemberRequest, error)

AskMember asks a member to approve on their phone (CIBA). Show BindingCode in the conversation, then WaitForMember.

func (*OrgAgent) AskToOpenSharedAccount

func (a *OrgAgent) AskToOpenSharedAccount(account, loginHint, message string) (*SharedAccountAsk, error)

AskToOpenSharedAccount asks to open a shared account (its key, from Organization → AI agents → Access) for a member. They open OpenURL in the browser where their Touchque extension is paired; their phone approves with this agent named and the extension signs in there. The agent never sees the password. message (at most 64 characters) is shown marked unverified.

func (*OrgAgent) Authorize

func (a *OrgAgent) Authorize(req *http.Request, resource, scope string) error

Authorize sets Authorization: DPoP <token> and a fresh DPoP proof on a request to the app.

func (*OrgAgent) DPoPProof

func (a *OrgAgent) DPoPProof(method, target, accessToken string) (string, error)

DPoPProof is a DPoP proof (RFC 9449) for one request: with the token, for a call to the app.

func (*OrgAgent) ExchangeToken

func (a *OrgAgent) ExchangeToken(subjectToken, resource, scope string) (*OrgAgentToken, error)

ExchangeToken returns a token for a member, with their own access token for one of the agent's apps (RFC 8693 token exchange): sub is the member, act the agent.

func (*OrgAgent) GetConnectionToken

func (a *OrgAgent) GetConnectionToken(subjectToken, connection, scope string) (*OrgAgentConnectionToken, error)

GetConnectionToken returns, from the token vault, a member's own access token at another service (Google, Microsoft 365, GitHub…) they connected on Touchque, for a connection that names this agent. subjectToken is the member's token, as for ExchangeToken; scope may only narrow what the member granted (empty: all of it). Touchque refreshes it; the refresh token never leaves. An APIError invalid_grant means the member has not connected it (or disconnected, or left).

func (*OrgAgent) GetToken

func (a *OrgAgent) GetToken(resource, scope string) (*OrgAgentToken, error)

GetToken returns a token for one app (renewed 30 seconds before it expires); empty resource and scope fall back to the configured ones.

func (*OrgAgent) SharedAccountAskStatus

func (a *OrgAgent) SharedAccountAskStatus(askID string) (*SharedAccountAskStatus, error)

SharedAccountAskStatus says where an ask stands; only whether it opened, never anything of the account.

func (*OrgAgent) WaitForMember

func (a *OrgAgent) WaitForMember(ctx context.Context, r *MemberRequest) (*OrgAgentToken, error)

WaitForMember polls for the member's answer (at the interval, slower when asked): the token once they approve; an *APIError access_denied or expired_token otherwise, a *TimeoutError after the request expired.

func (*OrgAgent) WaitForSharedAccount

func (a *OrgAgent) WaitForSharedAccount(ctx context.Context, ask *SharedAccountAsk) (*SharedAccountAskStatus, error)

WaitForSharedAccount polls an ask every three seconds until it ends (opened, refused, declined or expired) or ctx is done.

type OrgAgentConfig

type OrgAgentConfig struct {
	// AgentID: the oagt_… id; default TQ_ORG_AGENT_ID.
	AgentID string
	// Issuer: Touchque SSO; default TQ_SSO_URL or https://sso.touchque.com.
	Issuer string
	// PrivateKey: its own key (a JWK map or JSON, a PEM, or a Go private key); default TQ_ORG_AGENT_KEY.
	PrivateKey interface{}
	Kid        string
	// Assertion: instead of a key, the platform's token, asked for each time a token is needed.
	Assertion func() (string, error)
	// Resource and Scope used when a call does not name them.
	Resource  string
	Scope     string
	TimeoutMs int
}

OrgAgentConfig configures an organization's AI agent.

type OrgAgentConnectionToken

type OrgAgentConnectionToken struct {
	AccessToken string
	TokenType   string
	// ExpiresIn is 0 when the service does not say.
	ExpiresIn  int
	Scope      string
	Connection string
}

OrgAgentConnectionToken is a member's own access token at another service (the token vault): a Bearer token for that service's API.

type OrgAgentToken

type OrgAgentToken struct {
	AccessToken string
	TokenType   string
	ExpiresIn   int
	Scope       string
	// AuthorizationDetails: with CIBA, exactly what the member approved on the phone.
	AuthorizationDetails []map[string]interface{}
}

OrgAgentToken is a DPoP-bound access token for one app.

type PasskeyRequiredError

type PasskeyRequiredError struct {
	RequestID string
	Reason    string
}

PasskeyRequiredError means this request must be approved with a passkey. Reason is "" or "policy" when a phishing-resistant policy requires it (no push was sent), or "step_up" when the user tapped Approve on the phone during a call (Vishing Shield) and the request, still open, now waits for a passkey in the browser.

func (*PasskeyRequiredError) Error

func (e *PasskeyRequiredError) Error() string

type PollSecurityEventsParams

type PollSecurityEventsParams struct {
	// URL is the stream's poll endpoint (its delivery.endpoint_url).
	URL string
	// Token is the stream's token.
	Token string
	// Ack lists the jtis you handled since the last poll.
	Ack []string
	// SetErrs are the jtis you could not handle: {jti: {"err": ..., "description": ...}}.
	SetErrs           map[string]map[string]string
	MaxEvents         *int
	ReturnImmediately *bool
	HTTPClient        *http.Client
}

PollSecurityEventsParams is one poll (RFC 8936).

type PollSecurityEventsResult

type PollSecurityEventsResult struct {
	Sets          map[string]string `json:"sets"`
	MoreAvailable bool              `json:"moreAvailable"`
}

PollSecurityEventsResult holds the waiting SETs (jti → token).

func PollSecurityEvents

PollSecurityEvents acknowledges what you handled and returns the waiting SETs.

type QRPairing

type QRPairing struct {
	PairingID        string              `json:"pairingId"`
	State            string              `json:"state"`
	KeyThumbprint    string              `json:"keyThumbprint"`
	ExpiresAt        string              `json:"expiresAt"`
	RequestID        *string             `json:"requestId"`
	ExternalUsername string              `json:"externalUsername,omitempty"`
	ScannedAt        string              `json:"scannedAt,omitempty"`
	ConfirmedAt      *string             `json:"confirmedAt,omitempty"`
	Phone            *QRPairingPlace     `json:"phone,omitempty"`
	Browser          *QRPairingPlace     `json:"browser,omitempty"`
	Proximity        *QRPairingProximity `json:"proximity,omitempty"`
	Outcome          *QRPairingOutcome   `json:"outcome,omitempty"`
	// ReportedAt: the person said someone told them to scan it; their 2FA is frozen.
	ReportedAt string `json:"reportedAt,omitempty"`
}

QRPairing is where a pairing stands. State: waiting, scanned, confirmed, requested, approved, refused, reported or expired. ExternalUsername, Proximity, Phone and Browser are set once a phone scanned it.

type QRPairingOutcome

type QRPairingOutcome struct {
	Reason     string  `json:"reason"`
	Message    string  `json:"message"`
	CaseCode   *string `json:"caseCode"`
	DeviceCode *string `json:"deviceCode"`
	At         string  `json:"at"`
}

QRPairingOutcome is why a pairing was refused (by you, or declined on the phone).

type QRPairingPlace

type QRPairingPlace struct {
	Country  *string `json:"country"`
	Location *string `json:"location"`
}

QRPairingPlace is where the phone or the browser is.

type QRPairingProximity

type QRPairingProximity struct {
	SameNetwork *bool    `json:"sameNetwork"`
	SameCountry *bool    `json:"sameCountry"`
	Warnings    []string `json:"warnings"`
}

QRPairingProximity says how near the phone was to the browser; Warnings holds "different_country" and "different_network".

type QRPairingsResource

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

QRPairingsResource pairs a browser by QR code: your page shows a QR code, the person scans it with the Touchque app, and the phone that scanned is the one asked to approve.

  1. Your page gets the thumbprint of its browser key (@touchque/web browserKey.thumbprint()) and sends it to your server.
  2. Create registers a pairing and returns URI (touchque://pair-browser?…): show it as a QR code. It can be scanned once, for TTLSeconds (default 120). The nonce in it never leaves your server and the QR: Touchque keeps only its hash.
  3. Poll Get: "scanned" once a phone holding one of your users' accounts read it (ExternalUsername, Proximity), "confirmed" once the person went on, "reported" when they said someone told them to scan it (their 2FA freezes).
  4. Login.RequestWithOptions with QRPairing asks that phone, once, with number matching; the browser key's fingerprint is one of the rows the phone signs. When your own checks say no, Refuse, and the phone shows why.

func (*QRPairingsResource) Create

Create registers a pairing for one browser and returns the QR code's text.

func (*QRPairingsResource) Get

func (r *QRPairingsResource) Get(ctx context.Context, pairingID string) (*QRPairing, error)

Get says where a pairing stands; once scanned, who scanned it and how near the phone was.

func (*QRPairingsResource) Refuse

func (r *QRPairingsResource) Refuse(ctx context.Context, pairingID string, opts RefuseQRPairingOptions) (*QRPairing, error)

Refuse tells the phone that your own checks refused a scanned pairing. Only a scanned or confirmed pairing can be refused (409 not_open otherwise).

type RadiusApp

type RadiusApp struct {
	ID     string `json:"id"`
	Name   string `json:"name"`
	Status string `json:"status"` // "active" | "disabled"
	// Vendor is the VPN brand the admin picked (fortigate, cisco, paloalto,
	// openvpn, pfsense, opnsense, windows, other...).
	Vendor string `json:"vendor"`
	// PrimaryAuth: who checks the password. "directory" (the proxy, against
	// the company's RADIUS server or LDAP/Active Directory), "touchque" (the
	// Touchque account password) or "none" (the VPN checked it already).
	PrimaryAuth string `json:"primaryAuth"`
	// Challenge: how the phone is asked. "number" (the VPN shows a number in
	// an Access-Challenge and the user types it on the phone) or "push" (a
	// plain approval, for VPNs that cannot show a challenge).
	Challenge string `json:"challenge"`
	// AllowedNAS: addresses or CIDR ranges of the VPN devices that may ask.
	// Empty: any device the proxy's configuration lists.
	AllowedNAS []string `json:"allowedNas"`
	// OutagePolicy: what the proxy does while it cannot reach Touchque.
	// "closed" (refuse), "offline_codes" (accept a code from the Touchque app,
	// checked against the outage cache) or "password_only" (the password alone).
	OutagePolicy string `json:"outagePolicy"`
	// UsernameDomain: the domain added to a bare user name ("jdoe" → jdoe@domain).
	UsernameDomain string `json:"usernameDomain,omitempty"`
	// Organization is the organization's display name.
	Organization string `json:"organization"`
	// OfflinePacks: a Windows sign-in app's offline sign-in packs (nil: off).
	// After an approved sign-in on a computer's own screen, the connector asks
	// for the next Size offline sign-ins there, valid Days (OfflinePack).
	OfflinePacks *RadiusOfflinePacks `json:"offlinePacks,omitempty"`
}

RadiusApp is a VPN app's settings, managed in the dashboard.

type RadiusAuthRequest

type RadiusAuthRequest struct {
	// Username is the name typed on the VPN (jdoe, jdoe@example.com, CORP\jdoe).
	Username string `json:"username"`
	// Email is the person's address from the directory (an LDAP "mail"
	// attribute), when the proxy knows it; it wins over Username.
	Email string `json:"email,omitempty"`
	// Password: only when the app's PrimaryAuth is "touchque".
	Password string `json:"password,omitempty"`
	// PrimaryVerified: the proxy checked the password against the company's
	// directory (PrimaryAuth "directory").
	PrimaryVerified bool `json:"primaryVerified,omitempty"`
	// Passcode is a code from the Touchque app typed after the password
	// ("secret,123456"): no push is sent.
	Passcode string `json:"passcode,omitempty"`
	// ChallengeCapable false: this VPN device cannot show an Access-Challenge,
	// so it gets a plain push whatever the app's Challenge setting (nil: it can).
	ChallengeCapable *bool `json:"challengeCapable,omitempty"`
	// TerminalQR: the client draws a QR in a terminal (the Touchque PAM module
	// on a Linux server). Touchque then also returns QR and QRTerminal: a
	// compact QR for a phone without internet, whose 7-character code goes to
	// Passcode like a time-based code. Only for apps with vendor "linux".
	TerminalQR bool          `json:"terminalQr,omitempty"`
	NAS        RadiusNAS     `json:"nas"`
	Client     RadiusEndUser `json:"client"`
}

RadiusAuthRequest starts a VPN sign-in.

type RadiusClient

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

RadiusClient talks to the RADIUS API of Touchque SSO: the second factor for an organization's VPN and other RADIUS clients. The Touchque RADIUS proxy (a program the organization runs in its own network) uses it; you only need it to build your own RADIUS server.

The credential is the VPN app's proxy key and secret, created in the dashboard (Organization → VPN & RADIUS). Requests are signed with the secret like every Touchque API request, so the secret never travels.

func NewRadiusClient

func NewRadiusClient(config *Config) (*RadiusClient, error)

NewRadiusClient builds a RadiusClient. config.APIKey and config.APISecret are the VPN app's proxy key ("tq_rad_…") and secret; config.BaseURL is the Touchque SSO (DefaultSSOBaseURL when empty). TimeoutMs defaults to 35000, above the longest wait the API holds a request for (25 s).

func (*RadiusClient) Authenticate

func (r *RadiusClient) Authenticate(ctx context.Context, req RadiusAuthRequest) (*RadiusDecision, error)

Authenticate starts a VPN sign-in: Touchque checks the person, the app's groups and the organization's sign-in policy, then sends the push (or checks the passcode).

func (*RadiusClient) Config

func (r *RadiusClient) Config(ctx context.Context, info RadiusProxyInfo) (*RadiusApp, error)

Config fetches the app's settings (and tells Touchque the proxy is up).

func (*RadiusClient) OfflinePack

OfflinePack asks for a computer's offline sign-ins after an approved Windows sign-in there (a Windows sign-in app with OfflinePacks).

func (*RadiusClient) OfflinePackSync

OfflinePackSync sends the slots used offline and learns which packs the computer keeps.

func (*RadiusClient) OpenOutagePage

func (r *RadiusClient) OpenOutagePage(p *RadiusOutagePage) (*RadiusOutageCache, error)

OpenOutagePage checks a page's signature with the client's secret and reads it.

func (*RadiusClient) OutageCache

OutageCache fetches one page of the outage cache.

func (*RadiusClient) OutageLog

func (r *RadiusClient) OutageLog(ctx context.Context, events []RadiusOutageEvent) (*RadiusOutageLogResult, error)

OutageLog sends up to 200 decisions made during an outage.

func (*RadiusClient) Passcode

func (r *RadiusClient) Passcode(ctx context.Context, transactionID, passcode string) (*RadiusDecision, error)

Passcode finishes a transaction with a code from the Touchque app (when the phone has no internet) instead of the push.

func (*RadiusClient) Wait

func (r *RadiusClient) Wait(ctx context.Context, transactionID string, wait time.Duration) (*RadiusDecision, error)

Wait holds the request until the phone answers or wait runs out (at most 25 s): "pending" then means the phone has not answered yet.

type RadiusDecision

type RadiusDecision struct {
	// Decision: "accept", "reject", "challenge" (show Number and ask the user
	// to press OK; continue with Wait or Passcode), "pending" (a push was
	// sent; continue with Wait) or, only for a sign-in started with
	// TerminalQR, "retry" (the code was wrong: ask again and continue the
	// same transaction with Passcode or Wait).
	Decision      string `json:"decision"`
	TransactionID string `json:"transactionId,omitempty"`
	// Number is the number the user types on the phone (Decision "challenge").
	Number string `json:"number,omitempty"`
	// Reason is a machine-readable code (declined_on_phone, not_assigned,
	// number_match_needed, call_in_progress, ...).
	Reason string `json:"reason,omitempty"`
	// Message is English text for the user.
	Message string `json:"message,omitempty"`
	// CaseCode is the "Why?" case code (K7P-2QX) the user reads out to IT.
	CaseCode string `json:"caseCode,omitempty"`
	// Email is the Touchque account the sign-in was for, when known.
	Email string `json:"email,omitempty"`
	// ExpiresIn is how many seconds the transaction stays open.
	ExpiresIn int `json:"expiresIn,omitempty"`
	// QR is the compact QR text ("TQ3:...") for a phone without internet,
	// returned with "challenge" or "pending" when the sign-in asked for
	// TerminalQR and the person's phone can do offline approvals.
	QR string `json:"qr,omitempty"`
	// QRTerminal is QR drawn with Unicode half blocks, lines separated by
	// "\n": print it as it is.
	QRTerminal string `json:"qrTerminal,omitempty"`
	// AttemptsLeft: how many more codes the transaction takes ("retry").
	AttemptsLeft int `json:"attemptsLeft,omitempty"`
}

RadiusDecision is the answer to every RADIUS API call.

type RadiusEndUser

type RadiusEndUser struct {
	// IP is the person's public address, when Calling-Station-Id holds one.
	IP string `json:"ip,omitempty"`
	// CallingStationID is the raw Calling-Station-Id (an address or a MAC).
	CallingStationID string `json:"callingStationId,omitempty"`
}

RadiusEndUser is where the person signing in is, as the VPN reports it.

type RadiusNAS

type RadiusNAS struct {
	// IP is the address the request came from (or NAS-IP-Address).
	IP string `json:"ip"`
	// Identifier is NAS-Identifier, when sent.
	Identifier string `json:"identifier,omitempty"`
	// Name is the client's name in the proxy configuration.
	Name string `json:"name,omitempty"`
}

RadiusNAS is the VPN device that sent the RADIUS request.

type RadiusOfflineKDF

type RadiusOfflineKDF struct {
	Name       string `json:"name"`
	Iterations int    `json:"iterations"`
	Length     int    `json:"length"`
}

RadiusOfflineKDF is how the slot digests were made (PBKDF2-SHA256).

type RadiusOfflinePack

type RadiusOfflinePack struct {
	Email   string `json:"email"`
	Account string `json:"account"`
	Scope   struct {
		ID    string `json:"id"`
		Name  string `json:"name"`
		Epoch string `json:"epoch"`
	} `json:"scope"`
	ValidUntil time.Time           `json:"validUntil"`
	CodeLength int                 `json:"codeLength"`
	KDF        RadiusOfflineKDF    `json:"kdf"`
	Slots      []RadiusOfflineSlot `json:"slots"`
	Reason     string              `json:"reason,omitempty"`
}

RadiusOfflinePack is a computer's new offline sign-ins for a person (no slots, and Reason, when none were due or allowed).

type RadiusOfflinePackRequest

type RadiusOfflinePackRequest struct {
	// TransactionID is the accepted sign-in's transaction.
	TransactionID string `json:"transactionId"`
	// MachineID is the computer's id (16-32 hex characters, kept by the connector).
	MachineID string `json:"machineId"`
	Computer  string `json:"computer"`
	// Account is the Windows account the person signed in to.
	Account string `json:"account"`
	// Have is how many unused slots the computer still holds for the account.
	Have int `json:"have"`
}

RadiusOfflinePackRequest asks for a computer's offline sign-ins right after an approved Windows sign-in there.

type RadiusOfflinePackState

type RadiusOfflinePackState struct {
	Email   string             `json:"email"`
	Account string             `json:"account"`
	Used    []RadiusOfflineUse `json:"used,omitempty"`
}

RadiusOfflinePackState is one person's pack on the computer, for OfflinePackSync.

type RadiusOfflinePacks

type RadiusOfflinePacks struct {
	Size int `json:"size"`
	Days int `json:"days"`
}

RadiusOfflinePacks is how many offline sign-ins a computer keeps and for how long.

type RadiusOfflineSlot

type RadiusOfflineSlot struct {
	Index      int    `json:"index"`
	Salt       string `json:"salt"`
	Digest     string `json:"digest"`
	QR         string `json:"qr"`
	QRTerminal string `json:"qrTerminal"`
}

RadiusOfflineSlot is one offline sign-in: the slow digest of its 10-character code and the QR only the person's phone opens.

type RadiusOfflineSyncRequest

type RadiusOfflineSyncRequest struct {
	MachineID string                   `json:"machineId"`
	Computer  string                   `json:"computer"`
	Packs     []RadiusOfflinePackState `json:"packs"`
}

RadiusOfflineSyncRequest is what the computer holds and used.

type RadiusOfflineSyncResult

type RadiusOfflineSyncResult struct {
	Revoked bool `json:"revoked"`
	Packs   []struct {
		Email  string `json:"email"`
		Action string `json:"action"`
		Reason string `json:"reason,omitempty"`
	} `json:"packs"`
}

RadiusOfflineSyncResult says which packs the computer keeps ("keep") or drops ("delete"), and whether the computer was revoked.

type RadiusOfflineUse

type RadiusOfflineUse struct {
	Index   int       `json:"index"`
	At      time.Time `json:"at"`
	Session string    `json:"session,omitempty"`
}

RadiusOfflineUse is a slot the computer accepted while it had no network.

type RadiusOutageCache

type RadiusOutageCache struct {
	V   int    `json:"v"`
	App string `json:"app"`
	// Policy is the app's OutagePolicy when the page was made: "closed",
	// "offline_codes" or "password_only".
	Policy      string    `json:"policy"`
	IssuedAt    time.Time `json:"issuedAt"`
	StepSeconds int64     `json:"stepSeconds"`
	// Until is the last step any digest covers: nothing is accepted after it.
	Until int64 `json:"until"`
	// Domains are tried after a bare user name ("jdoe" → jdoe@domain).
	Domains []string `json:"domains"`
	KDF     *struct {
		Name       string `json:"name"`
		Iterations int    `json:"iterations"`
		Length     int    `json:"length"`
	} `json:"kdf"`
	// DigestsPerStep: digests per step in every user's Digests (1: the
	// organization's outage code; 0 in a page that predates it means 2).
	DigestsPerStep int `json:"digestsPerStep,omitempty"`
	// Members: on the first page only (nil on the others), everyone who may
	// sign in now. Drop anyone else at once.
	Members []string           `json:"members"`
	Users   []RadiusOutageUser `json:"users"`
	// Next is the After of the next page; empty: this was the last.
	Next string `json:"next"`
	// Unavailable: why no codes came (the workspace has outage codes turned off).
	Unavailable string `json:"unavailable,omitempty"`
}

RadiusOutageCache is an opened page.

func OpenOutagePage

func OpenOutagePage(secret string, p *RadiusOutagePage) (*RadiusOutageCache, error)

OpenOutagePage checks a page's signature with the proxy secret and reads it.

type RadiusOutageCacheRequest

type RadiusOutageCacheRequest struct {
	// HaveUntil is the last step the proxy holds for everyone in Have: they
	// get only the steps after it, everyone else the whole window.
	HaveUntil int64    `json:"haveUntil,omitempty"`
	Have      []string `json:"have,omitempty"`
	// After is the previous page's Next (empty: the first page).
	After string `json:"after,omitempty"`
}

RadiusOutageCacheRequest asks for one page of the outage cache.

type RadiusOutageEvent

type RadiusOutageEvent struct {
	// ID is random hex (16-64 characters): a resend writes nothing twice.
	ID       string    `json:"id"`
	At       time.Time `json:"at"`
	Username string    `json:"username"`
	UserID   string    `json:"userId,omitempty"`
	// Outcome: "accepted" or "rejected".
	Outcome string `json:"outcome"`
	// Reason for a refusal: outage_closed, outage_no_code, outage_unknown_user,
	// outage_cache_expired, outage_code_used, outage_locked, bad_passcode.
	Reason string `json:"reason,omitempty"`
	// Factor: "outage_code", "password_only" or "none".
	Factor string        `json:"factor"`
	Step   int64         `json:"step,omitempty"`
	NAS    RadiusNAS     `json:"nas"`
	Client RadiusEndUser `json:"client"`
}

RadiusOutageEvent is one decision the proxy made while Touchque could not be reached, sent when it can again.

type RadiusOutageLogResult

type RadiusOutageLogResult struct {
	Written    int `json:"written"`
	Duplicates int `json:"duplicates"`
	// Skipped: malformed, or older than 7 days.
	Skipped int `json:"skipped"`
}

RadiusOutageLogResult says what Touchque wrote.

type RadiusOutagePage

type RadiusOutagePage struct {
	Payload   string `json:"payload"`
	Signature string `json:"signature"`
}

RadiusOutagePage is one page as it arrives; keep it as it is to check it again later (OpenOutagePage).

type RadiusOutageUser

type RadiusOutageUser struct {
	ID       string `json:"id"`
	Email    string `json:"email"`
	FromStep int64  `json:"fromStep"`
	Salt     string `json:"salt"`
	// Digests: base64, KDF.Length bytes each, DigestsPerStep per step from FromStep.
	Digests string `json:"digests"`
}

RadiusOutageUser is one person's digests for the steps FromStep onwards.

type RadiusProxyInfo

type RadiusProxyInfo struct {
	Version string `json:"version"`
	Host    string `json:"host,omitempty"`
	// Clients is how many RADIUS clients (VPN devices) the proxy's own
	// configuration lists.
	Clients int `json:"clients"`
	// PrimaryAuth is what the proxy's configuration checks the password
	// against: "radius", "ldap", "touchque" or "none".
	PrimaryAuth string `json:"primaryAuth,omitempty"`
}

RadiusProxyInfo is what the proxy says about itself when it fetches its app's settings; the dashboard shows it ("Proxy online, version …").

type RateLimitOptions

type RateLimitOptions struct {
	// Disabled turns the built-in limiter off (e.g. you already rate limit
	// in front of the handler).
	Disabled bool
	// Window is the window length. Default 60 s.
	Window time.Duration
	// PerIP is the number of requests per client IP per route per window. Default 20.
	PerIP int
	// PerUser is the number of requests per username per route per window
	// (routes that name a user). Default 5.
	PerUser int
}

RateLimitOptions configures the relay handler's built-in limiter. Zero values mean the defaults.

type RecordedActionEvent

type RecordedActionEvent struct {
	ID        string                 `json:"id"`
	Trigger   string                 `json:"trigger"`
	Time      string                 `json:"time"`
	User      *string                `json:"user"`
	RequestID *string                `json:"requestId"`
	Outcome   map[string]interface{} `json:"outcome"`
	Event     map[string]interface{} `json:"event"`
}

RecordedActionEvent is an event a trigger fired with (kept 30 days).

type Recovery

type Recovery struct {
	RecoveryID       string `json:"recoveryId"`
	ExternalUsername string `json:"externalUsername"`
	Method           string `json:"method"`
	// Status: AWAITING_DEVICE, VOUCHING, COOLING, COMPLETED, VETOED, EXPIRED, FAILED.
	Status    string                 `json:"status"`
	Required  int                    `json:"required"`
	Approvals int                    `json:"approvals"`
	Vouchers  []RecoveryVoucherState `json:"vouchers"`
	OldPhone  struct {
		Notified bool   `json:"notified"`
		Code     string `json:"code,omitempty"`
	} `json:"oldPhone"`
	CoolOffMinutes int               `json:"coolOffMinutes"`
	CoolOffUntil   string            `json:"coolOffUntil,omitempty"`
	Elevated       bool              `json:"elevated"`
	Reasons        []string          `json:"reasons"`
	Location       string            `json:"location,omitempty"`
	NewPhoneBound  bool              `json:"newPhoneBound"`
	ExpiresAt      string            `json:"expiresAt,omitempty"`
	CompletedAt    string            `json:"completedAt,omitempty"`
	EndedReason    string            `json:"endedReason,omitempty"`
	EndedBy        string            `json:"endedBy,omitempty"`
	CreatedAt      string            `json:"createdAt,omitempty"`
	Receipts       []RecoveryReceipt `json:"receipts"`
	// BindCode and BindURI are set by Start only (shown once): show BindURI as a QR.
	BindCode string `json:"bindCode,omitempty"`
	BindURI  string `json:"bindUri,omitempty"`
}

Recovery is a recovery case.

func (*Recovery) Open

func (r *Recovery) Open() bool

Open reports whether the recovery still waits for the new phone, the vouchers or the cooling-off.

type RecoveryReceipt

type RecoveryReceipt struct {
	Seq   int                    `json:"seq"`
	At    string                 `json:"at"`
	Step  string                 `json:"step"`
	Actor map[string]interface{} `json:"actor"`
	Data  map[string]interface{} `json:"data"`
	Prev  string                 `json:"prev,omitempty"`
	Hash  string                 `json:"hash"`
}

RecoveryReceipt is one step of a recovery, hash-chained to the one before.

type RecoveryResource

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

RecoveryResource is Never Locked Out: move a user whose phone is lost, dead or replaced to a new phone without a help desk.

  1. Let users name colleagues who can vouch for them (SetVouchers), behind an approval on their phone.
  2. When the phone is gone, after the password (or your IdP): Start. Show BindURI as a QR for the Touchque app on the new phone, then poll Status and show each voucher's Code: the user reads it to the colleague on a call, who types it on their own phone.
  3. After the cooling-off nobody vetoed, the account is on the new phone (Status == "COMPLETED"); critical actions wait 24 h (probation).

Admins can stop a running recovery with Veto.

func (*RecoveryResource) List

func (rr *RecoveryResource) List(ctx context.Context, externalUsername string, open bool) ([]Recovery, error)

List returns a user's recoveries, or (open) every running one of your workspace.

func (*RecoveryResource) SetVouchers

func (rr *RecoveryResource) SetVouchers(ctx context.Context, externalUsername string, vouchers []string) (*RecoveryVouchers, error)

SetVouchers replaces the user's vouchers (at most 5 are kept). Ask for the user's phone first: whoever sets them chooses who may move the account.

func (*RecoveryResource) Start

Start starts moving the user to a new phone. Call it only after the first factor. An *APIError with Code not_enough_vouchers, recovery_in_progress, blocked, frozen or rate_limited says why not.

func (*RecoveryResource) Status

func (rr *RecoveryResource) Status(ctx context.Context, recoveryID string) (*Recovery, error)

Status returns the recovery now, with its receipt chain. Poll it while the user waits.

func (*RecoveryResource) Veto

func (rr *RecoveryResource) Veto(ctx context.Context, recoveryID, by, reason string) (*Recovery, error)

Veto stops a running recovery (e.g. an admin who does not believe it). It does not freeze the user. by is shown in the receipts; reason defaults to partner_veto.

func (*RecoveryResource) Vouchers

func (rr *RecoveryResource) Vouchers(ctx context.Context, externalUsername string) (*RecoveryVouchers, error)

Vouchers lists the colleagues a user named, and whether each can vouch today.

type RecoveryVoucherEligibility

type RecoveryVoucherEligibility struct {
	ExternalUsername string `json:"externalUsername"`
	Eligible         bool   `json:"eligible"`
	// Reason why not: no_phone, no_hardware_key, keys_lost, frozen,
	// on_probation, same_phone.
	Reason string `json:"reason,omitempty"`
}

RecoveryVoucherEligibility says whether a named colleague can vouch today.

type RecoveryVoucherState

type RecoveryVoucherState struct {
	ExternalUsername string `json:"externalUsername"`
	Source           string `json:"source,omitempty"`
	// State: waiting, pending, approved, expired, unreachable.
	State string `json:"state"`
	// Code is the number this voucher must type, while their request is open.
	Code string `json:"code,omitempty"`
}

RecoveryVoucherState is one voucher of a running recovery.

type RecoveryVouchers

type RecoveryVouchers struct {
	ExternalUsername string                       `json:"externalUsername"`
	Vouchers         []RecoveryVoucherEligibility `json:"vouchers"`
	UpdatedAt        string                       `json:"updatedAt,omitempty"`
	// ProbationUntil is set while the user's own account is on probation
	// after a vouch recovery.
	ProbationUntil string `json:"probationUntil,omitempty"`
}

RecoveryVouchers is a user's named vouchers.

type RedeemIDJAGParams

type RedeemIDJAGParams struct {
	TokenEndpoint string
	ClientID      string
	ClientSecret  string
	Assertion     string
	Resource      string
	Scope         string
	// DPoPKey is the key the ID-JAG is bound to: a DPoP proof goes along. An authorization server
	// that supports DPoP binds the access token to the key too (token_type DPoP); one that does
	// not issues a Bearer token.
	DPoPKey    *IDJAGDPoPKey
	HTTPClient *http.Client
}

RedeemIDJAGParams: the other service's token endpoint, your client there, the ID-JAG.

type RedeemedApproval

type RedeemedApproval struct {
	ID               string `json:"id"`
	ExternalUsername string `json:"externalUsername"`
	Type             string `json:"type"`
	Agent            struct {
		ID   string `json:"id"`
		Name string `json:"name"`
	} `json:"agent"`
	AuthorizationDetails []map[string]interface{} `json:"authorizationDetails"`
	// Details are the rows the phone showed.
	Details []struct {
		Label string `json:"label"`
		Value string `json:"value"`
	} `json:"details"`
	Presence      string `json:"presence"`
	NumberMatched bool   `json:"numberMatched"`
	DecidedAt     string `json:"decidedAt"`
	// ApprovalProof is the phone's hardware signature over the rows.
	ApprovalProof map[string]interface{} `json:"approvalProof"`
	CaseCode      string                 `json:"caseCode"`
}

RedeemedApproval is an agent's approval after RedeemApproval: what the person approved, now used.

type RefuseQRPairingOptions

type RefuseQRPairingOptions struct {
	Reason     string
	Message    string
	CaseCode   string
	DeviceCode string
}

RefuseQRPairingOptions is your own refusal: Message is what the phone shows (up to 300 characters); CaseCode and DeviceCode ("ABC-123") are optional.

type RejectedError

type RejectedError struct {
	Message string
}

RejectedError represents an explicit rejection by the user.

func (*RejectedError) Error

func (e *RejectedError) Error() string

type RelayOptions

type RelayOptions struct {
	// UserID resolves the signed-in user's identifier for the "auth required"
	// routes (enrollment, passkey registration/management). Return "" when
	// there is no signed-in user — the route answers 401. Required:
	// NewRelayHandler panics when it is nil.
	UserID func(*http.Request) string

	// LoginUser is STRONGLY RECOMMENDED: the user who has already passed your
	// first factor (e.g. the password step stored in the session). When set,
	// POST /login, POST /offline/challenge and POST /offline/totp use this
	// user and IGNORE any username in the request body; when it returns ""
	// they answer 401 FIRST_FACTOR_REQUIRED. POST /offline/verify and
	// POST /passkey/login/verify then only open a session when Touchque's
	// user matches it. Without it, anyone can type any user's email and make
	// Touchque push to that user's phone (push-bombing) or spend that user's
	// offline attempts.
	LoginUser func(*http.Request) string

	// RateLimit configures the built-in limits for the pre-auth routes (per
	// client IP and per username, per route). nil means the defaults: 20
	// requests per IP and 5 per username per minute. Set Disabled to turn it
	// off if you already rate limit in front of this handler. The IP func
	// must return the real client address.
	RateLimit *RateLimitOptions

	// AllowOfflineWithoutFirstFactor: the offline routes (/offline/challenge,
	// /offline/verify, /offline/totp) answer 403 OFFLINE_REQUIRES_FIRST_FACTOR
	// unless LoginUser is set. Set this to true only if you really want them
	// to trust the username in the request body (e.g. your own gateway
	// already authenticated the user).
	AllowOfflineWithoutFirstFactor bool

	// ActionType is the action type used by POST /login and the offline
	// routes. Default "LOGIN".
	ActionType string

	// Details is optional transaction context for the POST /login push and
	// the offline QR, shown on the approval screen. Build it from your own
	// server-side state — anything read from the request body is
	// attacker-controlled.
	Details func(*http.Request) []LoginDetail

	// OnAuthenticated is called right before the handler writes its own
	// success response for POST /login (once approved), the offline routes
	// and the passkey sign-in routes (once verified) — the one place a
	// partner almost always needs to do something (open a session cookie,
	// etc.). Set cookies/headers on w here; do not write the body — the
	// handler does that right after. A non-nil error aborts the success
	// response and is answered as an error instead.
	OnAuthenticated func(w http.ResponseWriter, r *http.Request, info AuthenticatedInfo) error

	// IP is the end user's address, used for the per-IP rate limit and shown
	// on the phone, with the push or as where a first-time QR was asked for
	// (default: the host part of r.RemoteAddr — set this explicitly behind a
	// reverse proxy, from your trusted X-Forwarded-For hop).
	IP func(*http.Request) string

	// SilentSignIn for POST /login (default off): a new sign-in whose browser
	// sent its device-bound key proof (X-Touchque-Browser, added by
	// @touchque/web with browserKey: true) first asks Touchque whether
	// anything about it is new. If nothing is, it succeeds at once with no
	// push (OnAuthenticated gets Via ViaSilent; the answer's assurance.method
	// is "silent"). Otherwise, and on any error, the usual push starts and its
	// approval makes the browser known. Set LoginUser too: the user must have
	// passed your password step.
	SilentSignIn bool
	// SilentSignInMaxAgeSeconds is your own limit on how long ago the last
	// phone approval in that browser may be (0 = always ask). nil leaves it
	// to Touchque, which never goes beyond its own limit (7 days).
	SilentSignInMaxAgeSeconds *int
}

RelayOptions configures NewRelayHandler.

type RenderedTemplate

type RenderedTemplate struct {
	Code         string   `json:"code"`
	Secrets      []string `json:"secrets"`
	AllowedHosts []string `json:"allowedHosts"`
	Capabilities []string `json:"capabilities"`
}

RenderedTemplate is a template as plain code.

type ReportFraudOptions

type ReportFraudOptions struct {
	// Reason is one of the Fraud* constants (default FraudOther).
	Reason string
	// Note is free text for your audit log, at most 500 characters.
	Note string
}

ReportFraudOptions describes why a request is being reported.

type ReportFraudResponse

type ReportFraudResponse struct {
	Reported bool `json:"reported"`
	// AlreadyReported is true when this request had already been reported.
	AlreadyReported bool   `json:"alreadyReported"`
	RequestID       string `json:"requestId"`
}

ReportFraudResponse is the answer to ReportFraud.

type RequestIDJAGParams

type RequestIDJAGParams struct {
	Issuer        string
	TokenEndpoint string
	ClientID      string
	ClientSecret  string
	IDToken       string
	Audience      string
	Resource      string
	Scope         string
	// DPoPKey binds the ID-JAG to this key (DPoP, RFC 9449); redeem it with the same key.
	DPoPKey    *IDJAGDPoPKey
	HTTPClient *http.Client
}

RequestIDJAGParams: the identity provider (Issuer, or TokenEndpoint), your app there and its secret, the member's ID token, and the other service's authorization server (Audience).

type RequireOptions

type RequireOptions struct {
	// User resolves who is approving from YOUR server-side state: the
	// signed-in session, or — for the login step — whoever just passed your
	// password check. Required: Require panics when it is nil. Never read it
	// from anything the client sends (a header, a form field): the client
	// could then name any user and trigger their approval.
	User func(*http.Request) string
	// Details: what the phone shows and the approval is bound to. Build it
	// from server-side state.
	Details func(*http.Request) []LoginDetail
	// ReferenceID: your own transaction id, bound to the approval.
	ReferenceID func(*http.Request) string
	// IP: end user's address, sent with the push and with a first-time QR
	// (default: the host part of r.RemoteAddr — set this explicitly behind a
	// reverse proxy, from your trusted X-Forwarded-For hop; never the
	// leftmost hop, which the client controls).
	IP func(*http.Request) string
	// SilentSignIn (default off): a new attempt whose browser sent its
	// device-bound key proof (X-Touchque-Browser, added by @touchque/web with
	// browserKey: true) first asks Touchque whether anything about it is new.
	// If nothing is, next runs at once with no push (the approval's
	// Assurance.Method is "silent", with Reasons). Otherwise, and on any
	// error, the usual push starts and its approval makes the browser known.
	SilentSignIn bool
	// SilentSignInMaxAgeSeconds is your own limit on how long ago the last
	// phone approval in that browser may be (0 = always ask). nil leaves it
	// to Touchque, which never goes beyond its own limit (7 days).
	SilentSignInMaxAgeSeconds *int
	// Context is for your Touchque Actions only (event.context): roles,
	// plan, amount… Never shown on the phone.
	Context func(*http.Request) map[string]interface{}
	// ErrorBody: your app's own error shape for the refusals Require sends
	// (401, 403, 408, 423, 429, 500, 503), e.g.
	//
	//	ErrorBody: func(r touchque.GuardRefusal) any {
	//	    return map[string]string{"message": r.Message, "code": r.Code}
	//	}
	//
	// A value that encodes to a JSON object is sent with "touchque" set to
	// the step (so @touchque/web still sees the state; no token is added),
	// anything else (a string, a number, a slice, nil) as it is. Status and
	// headers stay, and every refusal carries X-Touchque-State (and
	// X-Touchque-Reason). A panic, or a value that does not encode, sends the
	// default body and is logged. Never called for a 202 step or an approval.
	ErrorBody func(GuardRefusal) any
	// Logger receives Require's own lines (TQ_API_KEY / TQ_API_SECRET not set,
	// once per process; an ErrorBody that failed) and, with a nil client, the
	// guard's lines on this route (an API error). nil: the client's
	// Config.Logger; with a nil client, the default client's (see
	// SetDefaultClient), and nothing for the one built from the environment.
	Logger *slog.Logger
}

RequireOptions configures Require.

type ResetSecretOptions

type ResetSecretOptions struct {
	// ExternalUsername is the user's id in your system.
	ExternalUsername string
	// ClientIP and UserAgent are the end user's, from the request that asks
	// for the new QR, as in GenerateSecretOptions; "" leaves each out.
	// Touchque records them with the new secret too, as on generate. A reset
	// without them clears the old secret's, so the new QR has no setup
	// context.
	ClientIP  string
	UserAgent string
}

ResetSecretOptions holds every POST /auth/secret/reset field. Use it with ResetSecretWithOptions; ResetSecret keeps its original signature.

type ResetSecretResponse

type ResetSecretResponse struct {
	Message          string   `json:"message"`
	UserID           string   `json:"userId"`
	Secret           string   `json:"secret"`
	ExternalUsername string   `json:"externalUsername"`
	ExpiresAt        string   `json:"expiresAt"`
	TTLMs            int      `json:"ttlMs"`
	QRCodeDataURL    string   `json:"qrCodeDataUrl"`
	RecoveryCodes    []string `json:"recoveryCodes"`
}

ResetSecretResponse represents the response from resetting a secret

type RiskBrowser

type RiskBrowser struct {
	// Thumbprint is the RFC 7638 thumbprint of the browser's key: pass it to
	// ForgetBrowsers to forget this one.
	Thumbprint string `json:"thumbprint"`
	Label      string `json:"label,omitempty"`
	CreatedAt  string `json:"createdAt,omitempty"`
	// LastMfaAt is the last phone or passkey approval in this browser.
	LastMfaAt string `json:"lastMfaAt,omitempty"`
	// LastMfaMethod is how that approval was given, e.g. "push" or "passkey".
	LastMfaMethod string `json:"lastMfaMethod,omitempty"`
	LastSeenAt    string `json:"lastSeenAt,omitempty"`
	// LastSilentAt is the last sign-in Touchque let through without asking.
	LastSilentAt string `json:"lastSilentAt,omitempty"`
}

RiskBrowser is a browser Touchque knows for a user: one the user approved on the phone (or with a passkey). Times are ISO 8601; "" when unset.

type RiskBrowsersOptions

type RiskBrowsersOptions struct {
	ExternalUsername string
}

RiskBrowsersOptions selects whose browsers Browsers lists.

type RiskBrowsersResponse

type RiskBrowsersResponse struct {
	Browsers []RiskBrowser `json:"browsers"`
}

RiskBrowsersResponse is the answer to Browsers.

type RiskCheckOptions

type RiskCheckOptions struct {
	// ExternalUsername is the user in YOUR system. Required.
	ExternalUsername string
	// Type is the action the user is about to do (the API's default is
	// "LOGIN"). A critical action always asks.
	Type string
	// ClientIP is the end user's address: compared with the networks of the
	// user's earlier approved sign-ins.
	ClientIP  string
	UserAgent string
	// BrowserProof is the browser's device-bound key proof (the
	// X-Touchque-Browser header, made by @touchque/web), passed through
	// untouched.
	BrowserProof string
	// ClientSignals is the end user's page check from @touchque/web
	// (startClientSignals().encode()): software driving the browser is never silent.
	ClientSignals string
	// DeviceRisk is the Touchque Device Risk identification (from the Device
	// Risk SDK's tag or identify call); optional: the page's report, passed
	// through untouched. A device signal is never silent.
	DeviceRisk string
	// DeviceRiskRequestID: the Touchque Device Risk identification's requestId
	// (from the Device Risk SDK's tag or identify call); optional, preferred over DeviceRisk.
	DeviceRiskRequestID string
	// MaxAgeSeconds is your own limit on how long ago the last phone approval
	// in this browser may be, in seconds; 0 = always ask. nil leaves it to
	// Touchque, which never goes beyond its own limit (7 days).
	MaxAgeSeconds *int
	// Context is for your Touchque Actions only (event.context).
	Context map[string]interface{}
}

RiskCheckOptions holds every POST /risk/check field.

type RiskCheckResult

type RiskCheckResult struct {
	// Prompt is false only when Touchque answered exactly prompt: false:
	// nothing about this sign-in is new, let the user in without a push.
	// Anything else (including an unreadable answer) is true: ask on the
	// phone as usual.
	Prompt  bool         `json:"prompt"`
	Reasons []RiskReason `json:"reasons"`
	// Assurance is how sure Touchque is that this is the user: "high",
	// "normal" (the default) or "low".
	Assurance string `json:"assurance"`
	// SilentMode is "enforce" or "shadow". In shadow mode silent sign-ins are
	// only measured for this workspace: Prompt is always true and the
	// reasons say what would have happened.
	SilentMode string `json:"silentMode"`
	// CaseCode is the "Why?" case code of this check (K7P-2QX), to show the user.
	CaseCode string `json:"caseCode,omitempty"`
}

RiskCheckResult is the answer to Check.

type RiskReason

type RiskReason struct {
	Code string `json:"code"`
	// Text is English.
	Text string `json:"text"`
	// Action: with Code "action", the slug of the Touchque Action that asked.
	Action string `json:"action,omitempty"`
}

RiskReason is one reason behind a Check answer. Show Text or translate Code.

Why it was silent: known_browser, recent_approval, same_phone, familiar_network, no_risk_signal. Why it asks: no_browser_key, new_browser, approval_too_old, policy_every_sign_in, other_phone, new_country, new_network, network_unknown, hosting_network, critical_action, sensitive_action, risk_signal, push_fatigue, fraud_report, new_factor, vishing_shield, automated_client, checks_incomplete, silent_mode_shadow, phone_not_linked, frozen, and more: new codes are added in minor versions.

type RiskResource

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

RiskResource is silent sign-ins: ask Touchque's risk engine whether a sign-in needs the phone at all, and manage the browsers it knows for a user.

A browser becomes known when the user approves a request on the phone (or with a passkey) that carried the browser's device-bound key proof (LoginRequestOptions.BrowserProof). Later, Check with a fresh proof from the same browser answers Prompt == false when nothing about the sign-in is new. Check sends nothing to the phone.

func (*RiskResource) Browsers

Browsers lists the browsers Touchque knows for a user (for an "approved browsers" list in your settings page).

func (*RiskResource) Check

Check asks whether this sign-in needs the phone. It sends nothing to the phone. Skip the push only when Prompt is false; on any error, ask as usual.

proof := r.Header.Get(touchque.GuardBrowserHeader)
risk, err := tq.Risk.Check(r.Context(), touchque.RiskCheckOptions{ExternalUsername: user, ClientIP: ip, BrowserProof: proof})
if err == nil && !risk.Prompt {
    return openSession(user) // known browser, nothing new
}
step, err := tq.Start("LOGIN", user, touchque.StartOptions{IP: ip, BrowserProof: proof})

func (*RiskResource) ForgetBrowsers

ForgetBrowsers forgets one browser (Thumbprint) or all of a user's browsers: their next sign-in asks the phone again. Call it after a password reset or when the user signs out everywhere.

type SafeApprovalMessageFields

type SafeApprovalMessageFields struct {
	Purpose       string
	ChainID       string
	Guard         string
	Safe          string
	Subject       string
	ExpiresAt     uint64
	DisplayDigest string
}

SafeApprovalMessageFields are the parts of the message the phone signs. Purpose is "approve" or "schedule"; Subject the Safe transaction hash or the governance hash; ExpiresAt Unix seconds.

type SafeApprovalVerification

type SafeApprovalVerification struct {
	Valid          bool
	Reason         string
	Purpose        string
	ApproverIndex  int
	ExpiresAt      uint64
	DisplayDigest  string
	SafeTxHash     string
	GovernanceHash string
}

SafeApprovalVerification is VerifySafeApproval's verdict. Reason is "" when valid, else approval_malformed, public_key_invalid, approver_index_mismatch, approval_expired, rows_differ, high_s or signature_invalid. ApproverIndex, ExpiresAt (Unix seconds) and DisplayDigest are set once the approval parsed.

func VerifySafeApproval

func VerifySafeApproval(t SafeTxTarget, approval, publicKey string, opts VerifySafeApprovalOptions) (*SafeApprovalVerification, error)

VerifySafeApproval checks a phone's Safe Guard approval the way TouchqueSafeGuard does, without trusting the server that relayed it: the Safe and governance hashes come from t, the key from the guard's approver list on chain (x || y, 128 hex characters). The error is set only when t is not a Safe transaction; a refused approval is a verdict. Without opts.Purpose only an ordinary approval ("approve") is valid; pass Purpose "schedule" to check one for a governance change you will schedule.

status, _ := client.SafeGuard.Status(ctx, requestID)
check, err := touchque.VerifySafeApproval(myTx, status.SafeTx.Approval, approverKeyFromChain, touchque.VerifySafeApprovalOptions{ApproverIndex: &index})
if err != nil || !check.Valid { ... refuse ... }

type SafeDisplayRow

type SafeDisplayRow struct {
	Label string `json:"label"`
	Value string `json:"value"`
}

SafeDisplayRow is one row the phone showed, in order.

type SafeGuardApproval

type SafeGuardApproval struct {
	Class          string   `json:"class"`
	Flags          []string `json:"flags"`
	SafeTxHash     string   `json:"safeTxHash"`
	GovernanceHash *string  `json:"governanceHash"`
	Purpose        string   `json:"purpose"`
	ApproverIndex  int      `json:"approverIndex"`
	Approval       string   `json:"approval,omitempty"`
	ExpiresAt      int64    `json:"expiresAt,omitempty"`
}

SafeGuardApproval is where an approval stands. Purpose "approve": append to the owners' signatures; "schedule": send guard.schedule. Approval (105 bytes, 0x hex) and ExpiresAt (Unix seconds) are set once approved.

type SafeGuardConfig

type SafeGuardConfig struct {
	Threshold     int  `json:"threshold"`
	GovThreshold  int  `json:"govThreshold"`
	GovDelay      int  `json:"govDelay"`
	ExitDelay     int  `json:"exitDelay"`
	RecipientLock bool `json:"recipientLock,omitempty"`
}

SafeGuardConfig is the guard's settings for this Safe, as you read them from chain. With RecipientLock on, a payment or allowance outside the address book is a governance change.

type SafeGuardDecoded

type SafeGuardDecoded struct {
	Class          string           `json:"class"`
	Flags          []string         `json:"flags"`
	SafeTxHash     string           `json:"safeTxHash"`
	GovernanceHash *string          `json:"governanceHash"`
	Rows           []SafeDisplayRow `json:"rows"`
}

SafeGuardDecoded is Touchque's own decoding, for your logs and screens (the phone decodes for itself). Class: tighten, ordinary, governance or exit.

type SafeGuardRecipient

type SafeGuardRecipient struct {
	Address string `json:"address"`
	Label   string `json:"label,omitempty"`
}

SafeGuardRecipient is an entry of the guard's address book: the phone names the address with its label (at most 64 bytes, no control, bidi or invisible characters).

type SafeGuardRequestOptions

type SafeGuardRequestOptions struct {
	ExternalUsername string
	Type             string
	SafeTx           SafeGuardTx
	ReferenceID      string
	ExpiresIn        int
	ClientIP         string
	UserAgent        string
}

SafeGuardRequestOptions asks one approver's phone. Type is an action type from your dashboard; ExpiresIn is seconds, 30 to 300 (0 = 300).

type SafeGuardRequestResponse

type SafeGuardRequestResponse struct {
	RequestID string           `json:"requestId"`
	Message   string           `json:"message"`
	ExpiresAt string           `json:"expiresAt"`
	CaseCode  string           `json:"caseCode,omitempty"`
	SafeTx    SafeGuardDecoded `json:"safeTx"`
}

SafeGuardRequestResponse is a request on its way to the phone.

type SafeGuardResource

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

SafeGuardResource is Safe Guard: a Safe transaction approved on the approver's phone for TouchqueSafeGuard (the guard on your Safe). You send the raw transaction; the phone gets the raw fields only, decodes them itself, shows its own rows and signs, with a key only its biometrics unlock, a 105-byte approval of the hash it computed. Touchque never holds a key that can approve.

  1. Request asks the phone (same pipeline as Login.Request: risk engine, push limit, Vishing Shield, case code, always biometrics).
  2. WaitForApproval (or poll Status) until the phone answered.
  3. Check SafeTx.Approval yourself with VerifySafeApproval: it needs your own transaction and the approver's key from the guard, not this answer.
  4. Purpose "approve": WithSafeApprovals(ownerSignatures, approvals) as the signatures of execTransaction. "schedule": send SafeScheduleCall(safe, governanceHash, approvals) to the guard; the change runs once its waiting time is over.

func (*SafeGuardResource) Request

Request asks the approver's phone to approve a Safe transaction.

func (*SafeGuardResource) Status

func (r *SafeGuardResource) Status(ctx context.Context, requestID string) (*SafeGuardStatus, error)

Status is the request's status and, once approved, the approval.

func (*SafeGuardResource) WaitForApproval

func (r *SafeGuardResource) WaitForApproval(ctx context.Context, requestID string, timeout, pollInterval time.Duration) (*SafeGuardStatus, error)

WaitForApproval polls until the phone approved and returns the status with the approval: a *RejectedError when the person said no, a *TimeoutError when it expired or timeout (0 = 5 minutes, the request's own life) ran out. pollInterval 0 is 1.5 seconds.

type SafeGuardStatus

type SafeGuardStatus struct {
	RequestID        string             `json:"requestId"`
	ExternalUsername string             `json:"externalUsername"`
	Status           string             `json:"status"`
	Provisional      bool               `json:"provisional"`
	SafeTx           *SafeGuardApproval `json:"safeTx"`
}

SafeGuardStatus is a request's status. Provisional: given during a call or after a risky Second Thought answer; the person confirms it again later.

type SafeGuardTx

type SafeGuardTx struct {
	SafeTxTarget
	Config        SafeGuardConfig      `json:"config"`
	BatchTargets  []string             `json:"batchTargets,omitempty"`
	Recipients    []SafeGuardRecipient `json:"recipients,omitempty"`
	ApproverIndex int                  `json:"approverIndex"`
	Locale        string               `json:"locale,omitempty"`
}

SafeGuardTx is the raw Safe transaction and what the phone needs to decode it like the guard. BatchTargets are the MultiSendCallOnly contracts the guard opens call by call (at most 5); ApproverIndex is this approver's index in the guard; Locale is the language of the rows on the phone ("tr" by default, or "en").

type SafeTxCall

type SafeTxCall struct {
	To             string `json:"to"`
	Value          string `json:"value,omitempty"`
	Data           string `json:"data,omitempty"`
	Operation      int    `json:"operation"`
	SafeTxGas      string `json:"safeTxGas,omitempty"`
	BaseGas        string `json:"baseGas,omitempty"`
	GasPrice       string `json:"gasPrice,omitempty"`
	GasToken       string `json:"gasToken,omitempty"`
	RefundReceiver string `json:"refundReceiver,omitempty"`
	Nonce          string `json:"nonce"`
}

SafeTxCall is a Safe transaction: the fields the owners sign (Safe v1.3+ EIP-712 SafeTx). Integers are decimal strings ("" = 0); Data is 0x hex ("" = 0x); GasToken and RefundReceiver default to the zero address.

type SafeTxTarget

type SafeTxTarget struct {
	ChainID string     `json:"chainId"`
	Safe    string     `json:"safe"`
	Guard   string     `json:"guard"`
	Tx      SafeTxCall `json:"tx"`
}

SafeTxTarget is where the transaction runs: what the approval hashes cover. ChainID is a decimal string; Guard is the TouchqueSafeGuard on the Safe.

type SecondThought

type SecondThought struct {
	Questions []string `json:"questions"`
	// Locale is the language on the phone: "tr" (default) or "en".
	Locale string `json:"locale,omitempty"`
}

SecondThought: short yes/no questions the phone asks before Approve, for actions people get talked into. A risky answer never refuses: the approval comes back provisional, the user's critical actions wait, and the phone asks "Was this you?" later. Hold the action until it is reconfirmed.

type SecurityChanges

type SecurityChanges struct {
	Password time.Time
	MFA      time.Time
	Device   time.Time
	Email    time.Time
	Phone    time.Time
}

SecurityChanges says when the user's sign-in security last changed in your own system. A zero time is left out. Touchque adds what it saw itself; access rules and Actions read the minutes since each (minutesSince.mfaChange, .deviceChange, ...), e.g. refuse PAYOUT_CHANGE within 24 hours of a 2FA change.

type SecurityEvent

type SecurityEvent struct {
	JTI      string
	Issuer   string
	Audience []string
	// IssuedAt is seconds since the epoch.
	IssuedAt int64
	// TXN carries the case code of Touchque's decision ("Why?" in the dashboard); empty when none.
	TXN string
	// Subject is sub_id as sent: {"format": "email", "email": ...} for a person.
	Subject map[string]interface{}
	// Type is the event type URI.
	Type string
	// Name is its short name (session-revoked …) for CAEP, RISC and SSF types; empty for others.
	Name string
	// Claims are the event's own (event_timestamp, reason_admin, credential_type …).
	Claims map[string]interface{}
}

SecurityEvent is a verified SET.

type SecurityEventError

type SecurityEventError struct {
	Code    string
	Message string
}

SecurityEventError is a refused SET. Code is the RFC 8935 error to answer with (HTTP 400 {"err": Code}): invalid_request, invalid_key, invalid_issuer or invalid_audience; temporarily_unavailable when the issuer's keys could not be read (answer 503: the transmitter tries again).

func (*SecurityEventError) Error

func (e *SecurityEventError) Error() string

type SecurityEventVerifier

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

SecurityEventVerifier checks SETs: signature (RS256, the issuer's keys), typ, issuer, audience, one event.

func NewSecurityEventVerifier

func NewSecurityEventVerifier(cfg SecurityEventVerifierConfig) (*SecurityEventVerifier, error)

NewSecurityEventVerifier returns a verifier for one transmitter and audience.

func (*SecurityEventVerifier) Verify

func (v *SecurityEventVerifier) Verify(ctx context.Context, token string) (*SecurityEvent, error)

Verify checks a SET: the event, or *SecurityEventError.

type SecurityEventVerifierConfig

type SecurityEventVerifierConfig struct {
	// Issuer is the transmitter's issuer, e.g. https://sso.touchque.com.
	Issuer string
	// Audience is your stream's audience (aud), as the dashboard shows it.
	Audience string
	// JWKSURI, when not found from the issuer's /.well-known/ssf-configuration.
	JWKSURI string
	// JWKS fixes the keys instead (tests, or keys you pin): {"keys": [...]}.
	JWKS map[string]interface{}
	// ClockSkew allowed for iat (default 300 s).
	ClockSkew  time.Duration
	HTTPClient *http.Client
}

SecurityEventVerifierConfig configures a SecurityEventVerifier.

type SetupContext

type SetupContext struct {
	// IP is the public address the QR was asked from; "" when none was
	// given or it is not public (a private or carrier-grade NAT address).
	IP string `json:"ip,omitempty"`
	// Location is that address's place, by GeoIP.
	Location *SetupLocation `json:"location,omitempty"`
	// Device is the browser and device, from the User-Agent.
	Device *SetupDevice `json:"device,omitempty"`
	// RequestedAt is when the QR was asked for (ISO 8601).
	RequestedAt string `json:"requestedAt,omitempty"`
	// FarFromPhone says whether that place is far from whoever called POST
	// /auth/secret/validate. That is the phone's public call, so when the
	// Touchque app makes it, it is about the phone; called from your server
	// (ValidateSecret), it compares with your server's address and says
	// nothing about the phone. nil when Touchque cannot tell (an address
	// missing or not public, a place unknown).
	FarFromPhone *bool `json:"farFromPhone,omitempty"`
}

SetupContext is where a first-time linking QR was asked for: the address and User-Agent your server sent with the request for it (GenerateSecretOptions, or ResetSecretOptions for a reset) and when. The phone shows it before it links, so someone tricked into scanning another person's QR sees a place and device that are not theirs. What Touchque does not know is empty (nil for Location, Device and FarFromPhone).

type SetupDevice

type SetupDevice struct {
	Browser string `json:"browser,omitempty"`
	OS      string `json:"os,omitempty"`
	// Model is the device model, when the User-Agent names one: e.g.
	// "iPhone", "iPad", "Mac" or an Android model such as "Pixel 8". It may
	// be "" (null in the API's answer), as may Browser and OS.
	Model string `json:"model,omitempty"`
}

SetupDevice is the browser and device of a SetupContext, read from its User-Agent, e.g. "Safari", "iOS", "iPhone".

type SetupLocation

type SetupLocation struct {
	City    string `json:"city,omitempty"`
	Country string `json:"country,omitempty"`
	// CountryCode is the ISO 3166-1 alpha-2 code, e.g. "DE".
	CountryCode string `json:"countryCode,omitempty"`
}

SetupLocation is the place of a SetupContext's address, by GeoIP.

type SharedAccountAsk

type SharedAccountAsk struct {
	AskID string
	// OpenURL is the page the member opens in the browser where their Touchque extension is paired.
	OpenURL   string
	Status    string
	ExpiresIn int
}

SharedAccountAsk is an agent's ask to open a shared account for a member.

type SharedAccountAskStatus

type SharedAccountAskStatus struct {
	Status   string
	Reason   string
	CaseCode string
}

SharedAccountAskStatus says where an ask stands: waiting_member, asked_phone, opened, refused, declined or expired; Reason says why it was refused.

type ShieldFields

type ShieldFields struct {
	Provisional   bool   `json:"provisional,omitempty"`
	ReconfirmedAt string `json:"reconfirmedAt,omitempty"`
	Revoked       bool   `json:"revoked,omitempty"`
	RevokeReason  string `json:"revokeReason,omitempty"`
}

ShieldFields are the Vishing Shield fields of an approval. Provisional: it was given on the phone during a call; it stays CONFIRMED, but the user's critical actions are refused (blocked / provisional) until the phone re-confirms it after the call (ReconfirmedAt) or the user takes it back (Revoked, RevokeReason "COACHED" or "UNDO"). End what was built on a revoked approval.

type StartOptions

type StartOptions struct {
	// Details: shown on the phone and bound to the approval. Build it from server-side state.
	Details []LoginDetail
	// ReferenceID: your own transaction id, bound to the approval.
	ReferenceID string
	// IP / UserAgent: the end user's — shown on the phone, with the push or
	// as where a first-time QR was asked for.
	IP        string
	UserAgent string
	// NoEnroll: set true to get Step{State: StepEnroll, Reason:
	// "enrollment_off"} (no QR) instead of issuing one, when the user has no
	// linked phone.
	NoEnroll bool
	// BrowserProof (silent sign-ins): the browser's device-bound key proof
	// (X-Touchque-Browser), passed through untouched. Once the user approves,
	// Touchque knows this browser.
	BrowserProof string
	// Context is for your Touchque Actions only (event.context). Never shown on the phone.
	Context map[string]interface{}
}

StartOptions configures Start.

type StartRecoveryOptions

type StartRecoveryOptions struct {
	// ExternalUsername is the user in YOUR system. Required.
	ExternalUsername string
	// ClientIP is the user's address: the risk engine and the vouchers see it.
	ClientIP  string
	UserAgent string
	// DisplayName is how the vouchers know the user.
	DisplayName string
	// FallbackVouchers fill up a short named list, e.g. the organization's admins.
	FallbackVouchers []string
	// Required raises the floor of 2 vouchers; 0 keeps it.
	Required int
	// CoolOffMinutes raises the floor of 15 minutes (default 60); 0 keeps it.
	CoolOffMinutes int
	// Details is what the vouchers' phones show instead of the default English lines.
	Details []LoginDetail
	// NoticeDetails is what the old phone shows (approve to move now, reject
	// to stop) instead of the default English lines.
	NoticeDetails []LoginDetail
}

StartRecoveryOptions holds every POST /recovery/start field.

type Step

type Step struct {
	State     StepState     `json:"state"`
	RequestID string        `json:"requestId,omitempty"`
	Number    string        `json:"number,omitempty"`
	ExpiresAt string        `json:"expiresAt,omitempty"`
	Details   []LoginDetail `json:"details,omitempty"`
	Enroll    *EnrollStep   `json:"enroll,omitempty"`
	Offline   *OfflineStep  `json:"offline,omitempty"`
	Reason    string        `json:"reason,omitempty"`
	// CaseCode is the "Why?" case code of this decision (K7P-2QX): show it
	// with the step ("Tell your support team: K7P-2QX"). Safe for the browser.
	CaseCode string `json:"caseCode,omitempty"`
	// Reasons say why number matching, a passkey or a refusal (plain English,
	// a fixed list, never a score).
	Reasons    []RiskReason `json:"reasons,omitempty"`
	RetryAfter int          `json:"retryAfter,omitempty"`
	Assurance  *Assurance   `json:"assurance,omitempty"`
	// TelemetryToken is set only when the workspace collects behavioural
	// signals: it lets the browser post them for this one request
	// (@touchque/web does it when given `telemetry`). Not a credential.
	TelemetryToken string `json:"telemetryToken,omitempty"`
	// Canary (Mirror Alarm): the page showing this step loads it and beacons to
	// it (@touchque/web does it), so a phishing proxy in front of your site is
	// caught. Only on the first waiting step.
	Canary *Canary `json:"canary,omitempty"`
}

Step is what a headless approval currently looks like — safe to json.Marshal and send to the browser. It never contains API secrets.

type StepState

type StepState string

StepState is the state a headless approval is in.

const (
	StepWaiting         StepState = "waiting" // push sent — show Number (if any) and wait
	StepApproved        StepState = "approved"
	StepRejected        StepState = "rejected"
	StepExpired         StepState = "expired"
	StepEnroll          StepState = "enroll"           // no phone linked yet — show Enroll.QRCodeDataURL
	StepPasskeyRequired StepState = "passkey_required" // policy: approve with a passkey (browser ceremony)
	StepOffline         StepState = "offline"          // offline approval started — show Offline.QRDataURL, ask for the code
	StepBlocked         StepState = "blocked"          // refused by policy / risk / action disabled — see Reason
	StepFrozen          StepState = "frozen"           // too many rejections — see RetryAfter
	StepRateLimited     StepState = "rate_limited"     // too many requests — see RetryAfter
)

type TestActionOptions

type TestActionOptions struct {
	ActionDraft
	// EventID: a recorded event (Events()).
	EventID string
	// Event: your own event, merged over the trigger's sample.
	Event map[string]interface{}
	// Network: false turns api.fetch off (nil leaves it on).
	Network *bool
}

TestActionOptions runs a draft (or the deployed Action Slug) once.

type TimeoutError

type TimeoutError struct {
	Message string
}

TimeoutError represents a timeout during a polling operation, or a request that expired before it was approved.

func (*TimeoutError) Error

func (e *TimeoutError) Error() string

type TokenSet

type TokenSet struct {
	AccessToken  string
	TokenType    string
	ExpiresAt    time.Time
	Scope        string
	IDToken      string
	RefreshToken string
	Claims       map[string]interface{}
	// AuthorizationDetails is what the user approved on the phone (CIBA).
	AuthorizationDetails []map[string]interface{}
	// IssuedTokenType is set by token exchange (the access token type).
	IssuedTokenType string
	// Connection is set by GetConnectionToken: the connection the provider token is for.
	Connection string
}

TokenSet is what the token endpoint returned; Claims are the verified ID token's.

type UnlinkSecretResponse

type UnlinkSecretResponse struct {
	Success          bool   `json:"success"`
	ExternalUsername string `json:"externalUsername"`
	Message          string `json:"message"`
}

UnlinkSecretResponse represents the response from unlinking a device

type UpdateActionOptions

type UpdateActionOptions struct {
	Name      *string
	Enabled   *bool
	Order     *int
	OnFailure *string
}

UpdateActionOptions: nil fields are left as they are.

type UpdateAgentParams

type UpdateAgentParams struct {
	Name         string
	Description  *string
	OwnerEmail   string
	Platform     string
	AllowedTypes []string
	ReviewInDays int
}

UpdateAgentParams changes, hands over (OwnerEmail) or renews (ReviewInDays) an agent.

type UserApprovalRequest

type UserApprovalRequest struct {
	AuthReqID   string
	ExpiresAt   time.Time
	Interval    time.Duration
	BindingCode string
}

UserApprovalRequest is a pending CIBA request: show BindingCode, then WaitForUser.

type ValidateSecretResponse

type ValidateSecretResponse struct {
	Valid            bool   `json:"valid"`
	ExternalUsername string `json:"externalUsername,omitempty"`
	IntegrationID    string `json:"integrationId,omitempty"`
	Message          string `json:"message,omitempty"`
	Reason           string `json:"reason,omitempty"`
	UsedAt           string `json:"usedAt,omitempty"`
	ExpiredAt        string `json:"expiredAt,omitempty"`
	// SetupContext is where the QR was asked for, as Touchque recorded it
	// from the request that made the QR (GenerateSecretOptions, or
	// ResetSecretOptions for a reset; it is never in the QR). nil when that
	// request named no browser (no usable IP address or User-Agent), after a
	// reset without them, and for older QRs and servers.
	SetupContext *SetupContext `json:"setupContext,omitempty"`
}

ValidateSecretResponse represents the response from validating a setup secret

type VerifyAgentCardOptions

type VerifyAgentCardOptions struct {
	CardURL         string
	Keys            []map[string]interface{}
	TrustedJKUHosts []string
	HTTPClient      *http.Client
}

VerifyAgentCardOptions: where the card came from, keys you trust, other hosts a jku may name.

type VerifyApprovalProofOptions

type VerifyApprovalProofOptions struct {
	// RequestID returned by the login request.
	RequestID string
	// Type is the action type you sent (e.g. "WITHDRAW").
	Type string
	// Details you sent, exactly as you sent them (nil when none).
	Details []LoginDetail
	// ChallengeCode is the number-match code, when number matching was used.
	ChallengeCode string
	// ExpectedPublicKey pins the device: the base64 public key you stored for
	// this user (e.g. PublicKey of their first verified approval). A proof
	// from any other key is rejected. Required unless AllowUnpinnedKey.
	ExpectedPublicKey string
	// AllowUnpinnedKey accepts whatever key the proof carries. Without a pin
	// the proof only shows that *some* key signed these details. Only for
	// trust-on-first-use: store PublicKey after this first check, pin it after.
	AllowUnpinnedKey bool
}

VerifyApprovalProofOptions describes the transaction you expect the proof to cover.

type VerifyAssistOptions

type VerifyAssistOptions struct {
	Action     string
	ActionText string
	Details    []map[string]string
}

VerifyAssistOptions asks the person's phone to confirm Action: reset_2fa, reset_password, activation_link, recovery_link, unlock, new_phone, remove_passkey, or your own (lowercase, digits, underscores). ActionText is shown on the phone: "IT (<agent>) is about to <ActionText>".

type VerifyChallenge

type VerifyChallenge struct {
	RequestID string
	// ChallengeCode is the number to show when number matching is on ("" otherwise).
	ChallengeCode string
	ExpiresAt     string
	// Reasons say why number matching is needed (empty for a plain push).
	Reasons []RiskReason
	// CaseCode is the "Why?" case code of this decision.
	CaseCode string
}

VerifyChallenge is what OnChallenge receives as soon as the request exists.

type VerifyResponse

type VerifyResponse struct {
	Approved      bool       `json:"approved"`
	Status        string     `json:"status"`
	RequestID     string     `json:"requestId,omitempty"`
	ChallengeCode string     `json:"challengeCode,omitempty"`
	Assurance     *Assurance `json:"assurance,omitempty"`
	ConfirmedVia  string     `json:"confirmedVia,omitempty"`
	// Provisional: approved during a call (Vishing Shield); critical actions
	// wait until the phone re-confirms it.
	Provisional bool `json:"provisional,omitempty"`
}

VerifyResponse represents the response from verifying a login request.

type VerifySafeApprovalOptions

type VerifySafeApprovalOptions struct {
	// Purpose you expect ("approve" or "schedule"). Empty means "approve"
	// only: name "schedule" to accept an approval of a governance change,
	// which covers no Safe nonce and is never permission to execute.
	Purpose string
	// ApproverIndex is the approver's index in the guard: the approval must name it.
	ApproverIndex *int
	// DisplayDigest of the rows the phone must have shown (from your own
	// decoding), or the Rows themselves.
	DisplayDigest string
	Rows          []SafeDisplayRow
	// Now is the time to check the expiry against (zero: now).
	Now time.Time
}

VerifySafeApprovalOptions narrows what VerifySafeApproval accepts.

type WebAuthnAuthenticateVerifyResponse

type WebAuthnAuthenticateVerifyResponse struct {
	Success bool   `json:"success"`
	Message string `json:"message"`
	// ExternalUsername is the user whose login request was approved, as
	// reported by Touchque (never by the browser). Empty on older APIs.
	ExternalUsername string `json:"externalUsername,omitempty"`
	// RequestID is the approved login request, when Touchque reports it.
	RequestID string `json:"requestId,omitempty"`
}

WebAuthnAuthenticateVerifyResponse is returned by WebAuthn.AuthenticateVerify.

type WebAuthnCredentialSummary

type WebAuthnCredentialSummary struct {
	ID           string `json:"id"`
	CredentialID string `json:"credentialId"`
	DeviceType   string `json:"deviceType"`
	BackedUp     bool   `json:"backedUp"`
	Label        string `json:"label"`
	CreatedAt    string `json:"createdAt"`
	LastUsedAt   string `json:"lastUsedAt"`
}

WebAuthnCredentialSummary is one entry from WebAuthn.ListCredentials.

type WebAuthnDeleteCredentialResponse

type WebAuthnDeleteCredentialResponse struct {
	Deleted bool `json:"deleted"`
}

WebAuthnDeleteCredentialResponse is returned by WebAuthn.DeleteCredential.

type WebAuthnPrimaryAvailability

type WebAuthnPrimaryAvailability struct {
	Enabled          bool   `json:"enabled"`
	UserVerification string `json:"userVerification"`
}

WebAuthnPrimaryOptionsResponse is returned by WebAuthn.PrimaryOptions. WebAuthnPrimaryAvailability is returned by WebAuthn.PrimaryAvailability: whether passkey sign-in is on for your workspace. UserVerification is "required" or "preferred", or empty when Enabled is false.

type WebAuthnPrimaryOptionsResponse

type WebAuthnPrimaryOptionsResponse struct {
	AttemptID string                 `json:"attemptId"`
	Options   map[string]interface{} `json:"options"`
}

type WebAuthnPrimaryVerifyResponse

type WebAuthnPrimaryVerifyResponse struct {
	Success          bool    `json:"success"`
	RequiresStepUp   bool    `json:"requiresStepUp,omitempty"`
	ExternalUsername string  `json:"externalUsername"`
	RiskScore        float64 `json:"riskScore"`
	RequestID        string  `json:"requestId,omitempty"`
}

WebAuthnPrimaryVerifyResponse is returned by WebAuthn.PrimaryVerify. On Success the RequestID is a CONFIRMED LoginRequest; on !Success with RequiresStepUp, start the normal Login.Request / number-match flow instead.

type WebAuthnRegisterVerifyResponse

type WebAuthnRegisterVerifyResponse struct {
	Verified     bool   `json:"verified"`
	CredentialID string `json:"credentialId"`
}

WebAuthnRegisterVerifyResponse is returned by WebAuthn.RegisterVerify.

type WebAuthnResource

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

WebAuthnResource is the WebAuthn / FIDO2 (passkey) approval path, alongside the push + device flow (Login.Verify).

Server-to-server, like every other resource here: the passkey ceremony runs in the browser (navigator.credentials.create()/.get(), or @touchque/web); your backend collects that JSON and relays it through these methods. There is no client-side ceremony in this SDK.

func (*WebAuthnResource) AuthenticateOptions

func (w *WebAuthnResource) AuthenticateOptions(requestID string) (map[string]interface{}, error)

AuthenticateOptions is step 1 of approving a pending login with a passkey — options for navigator.credentials.get(), scoped to requestID.

func (*WebAuthnResource) AuthenticateVerify

func (w *WebAuthnResource) AuthenticateVerify(requestID string, response map[string]interface{}) (*WebAuthnAuthenticateVerifyResponse, error)

AuthenticateVerify is step 2 — verify the assertion, approving the LoginRequest.

func (*WebAuthnResource) DeleteCredential deprecated

func (w *WebAuthnResource) DeleteCredential(credentialRecordID string) (*WebAuthnDeleteCredentialResponse, error)

DeleteCredential removes a registered credential.

Deprecated: since API 3.3.0 the user is required and this call is refused (400). Use DeleteCredentialForUser.

func (*WebAuthnResource) DeleteCredentialForUser

func (w *WebAuthnResource) DeleteCredentialForUser(credentialRecordID, externalUsername string) (*WebAuthnDeleteCredentialResponse, error)

DeleteCredentialForUser removes a registered credential, scoped to externalUsername (recommended over DeleteCredential: without a scope, any credential id your API key can reach is deletable).

func (*WebAuthnResource) ListCredentials

func (w *WebAuthnResource) ListCredentials(externalUsername string) ([]WebAuthnCredentialSummary, error)

ListCredentials returns a user's registered credentials (metadata only).

func (*WebAuthnResource) PrimaryAvailability

func (w *WebAuthnResource) PrimaryAvailability() (*WebAuthnPrimaryAvailability, error)

PrimaryAvailability says whether passkey sign-in (TenantPolicy.passwordlessLoginEnabled) is on for your workspace. Ask before your sign-in page shows its passkey button and passkey autofill: when it is off, PrimaryOptions answers 403 passwordless_login_disabled. Read-only.

func (*WebAuthnResource) PrimaryOptions

func (w *WebAuthnResource) PrimaryOptions(externalUsername string) (*WebAuthnPrimaryOptionsResponse, error)

PrimaryOptions is step 1 of a passwordless-primary login. Requires TenantPolicy.passwordlessLoginEnabled. A 404 no_passkey_registered means the user has no passkey — fall back to password login.

An empty externalUsername asks for options that accept any passkey of your site (passkey autofill, where nobody has typed an email yet); PrimaryVerify then names the user the passkey belongs to.

func (*WebAuthnResource) PrimaryVerify

func (w *WebAuthnResource) PrimaryVerify(attemptID string, response map[string]interface{}) (*WebAuthnPrimaryVerifyResponse, error)

PrimaryVerify is step 2 of a passwordless-primary login.

func (*WebAuthnResource) RegisterOptions

func (w *WebAuthnResource) RegisterOptions(externalUsername string, discoverable bool) (map[string]interface{}, error)

RegisterOptions is step 1 of registering a passkey — options for navigator.credentials.create(). discoverable=true registers a resident credential (forced UV), the shape a passwordless-primary login uses. The raw options object is returned as-is for the browser.

func (*WebAuthnResource) RegisterOptionsWithApproval

func (w *WebAuthnResource) RegisterOptionsWithApproval(externalUsername string, discoverable bool, approvalRequestID string) (map[string]interface{}, error)

RegisterOptionsWithApproval is RegisterOptions for a user with a linked phone (the API answers 403 enrollment_approval_required otherwise): approvalRequestID is a PASSKEY_ENROLL request the user approved on the phone, at most 10 minutes old, used once. The relay's /passkey/register/options runs that approval for you.

func (*WebAuthnResource) RegisterVerify

func (w *WebAuthnResource) RegisterVerify(externalUsername string, response map[string]interface{}, label string) (*WebAuthnRegisterVerifyResponse, error)

RegisterVerify is step 2 — verify the browser's registration response and store the credential.

type WebhookReplayCache

type WebhookReplayCache interface {
	CheckAndSet(jti string, ttl time.Duration) bool
}

WebhookReplayCache stores webhook `jti`s already accepted. CheckAndSet must atomically record jti for ttl and return true if it was NOT seen before. Use NewMemoryReplayCache for a single process, or implement it over Redis / your database when you run several instances.

type WebhookReplayError

type WebhookReplayError struct {
	JTI string
}

WebhookReplayError means a correctly signed webhook with this `jti` was already accepted (see WebhookResource.VerifyWithOptions).

func (*WebhookReplayError) Error

func (e *WebhookReplayError) Error() string

type WebhookResource

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

WebhookResource handles incoming webhook signature verification.

func (*WebhookResource) Verify

func (w *WebhookResource) Verify(rawBody string, signature string, toleranceSeconds ...int) (map[string]interface{}, error)

Verify checks the signature of an incoming webhook and returns the decoded payload. `signature` is the x-signature header value; pass "" to fall back to the `signature` field carried inside the body.

The signature is checked over the raw text, exactly as Touchque signed it, so any string verifies, also one only JavaScript can hold: an unpaired surrogate, written as an escape, which the payload holds as U+FFFD. Every string handed back is valid UTF-8 (the password of a Touchque Login user-store request can be read and checked).

An optional toleranceSeconds overrides the 300s replay window (parity with the Node/PHP/Python SDKs); pass 0 to disable the freshness check.

func (*WebhookResource) VerifyWithOptions

func (w *WebhookResource) VerifyWithOptions(rawBody string, signature string, opts WebhookVerifyOptions) (map[string]interface{}, error)

VerifyWithOptions is Verify with a replay cache. A correctly signed delivery whose `jti` was already accepted returns *WebhookReplayError (usually a Touchque retry of something you processed: answer 200, but don't run your side effects again).

type WebhookSignatureError

type WebhookSignatureError struct {
	Message string
}

WebhookSignatureError represents an invalid or replayed webhook.

func (*WebhookSignatureError) Error

func (e *WebhookSignatureError) Error() string

type WebhookVerifyOptions

type WebhookVerifyOptions struct {
	// ToleranceSeconds is the freshness window; nil means 300, 0 disables it.
	ToleranceSeconds *int
	// ReplayCache, when set, rejects a second delivery of the same `jti` with
	// a *WebhookReplayError.
	ReplayCache WebhookReplayCache
}

WebhookVerifyOptions tunes VerifyWithOptions.

Jump to

Keyboard shortcuts

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