touchque (Ruby)
The official Ruby server SDK for Touchque: push approvals with number matching, passkeys, silent sign-ins, offline codes, verified webhooks, Touchque Actions, AI agent approvals, Touchque Login (hosted sign-in and the Management API) and the server side of the Mobile SDK. Rails integration included (a Railtie and controller concerns), plus a Rack relay for Sinatra and any Rack app.
Ruby 3.1+, no runtime dependencies beyond the standard library (net/http, openssl, json).
๐ Full docs: support.touchque.com
Install
# Gemfile
gem "touchque"Setup
Get an API key and secret from your Touchque dashboard:
export TQ_API_KEY=tq_auth_your_key
export TQ_API_SECRET=your_api_secretThe secret signs every request: it belongs on your server only, never in a browser or an app.
tq = Touchque.client # from the environment, shared
tq = Touchque::Client.new(api_key: "tq_...", api_secret: "...") # explicitIn Rails the Railtie reads config.touchque (or credentials.touchque, then the environment):
# config/application.rb
config.touchque.api_key = Rails.application.credentials.dig(:touchque, :api_key)
config.touchque.api_secret = Rails.application.credentials.dig(:touchque, :api_secret)Quick start (Rails)
One line per protected action:
class TransfersController < ApplicationController
include Touchque::Rails::Guard
require_touchque "SEND_MONEY", only: :create,
details: -> { { "Amount" => params.require(:amount), "To" => params.require(:to) } }
def create
touchque_approval # only reached once the user approved on their phone
end
endUntil the user approves on their phone the action answers
202 {"touchque": step, "token": "..."}. Your page shows step in its own design (the
matching number, or a QR code the first time the user links the app) and sends the same request
again with header X-Touchque-Token: <token>; @touchque/web
does this loop for you. Once approved the action runs once. Refusals answer 403 (rejected,
blocked), 408 (expired), 423 (frozen) or 429 (rate limited) with Retry-After.
A frontend of your own: while the first-time QR is up, polls answer {"state": "enroll", "expiresAt": ...}
without enroll, so keep showing the QR you have. About 15 s before it expires a new QR comes with
enroll.qrCodeDataUrl and new recovery codes: the old QR and the old codes stop working. The other states
are listed under Guard inside your handler.
The approving user is current_user's email (else id, else username). For your login action
(nobody is signed in yet) pass user: -> { session[:password_verified_user] }.
The end user's address. The risk checks (Tor, location, impossible travel) and the location
shown on the phone use request.remote_ip: configure config.action_dispatch.trusted_proxies
behind a load balancer.
A missing key. Touchque.client is built on the first guarded request, inside the guard.
Without TQ_API_KEY / TQ_API_SECRET (or config.touchque) nothing raises: the action answers
500 with Cache-Control: no-store and the body
{"touchque":{"state":"blocked","reason":"misconfigured"},"error":{"code":"misconfigured","message":"Two-factor approval is not configured correctly."}}
(401 unauthenticated when nobody is signed in), and never runs. It is logged once, through
Touchque.logger (in Rails, Rails.logger unless you set one): [Touchque] TQ_API_KEY and TQ_API_SECRET are not set: routes guarded by Touchque answer 500 misconfigured. A 500 rather than a
503: it is a deploy mistake for your monitoring to catch, not an outage to retry. @touchque/web shows
"Approvals are not set up correctly on this site."
Refusal headers. Every answer of 400 and above carries X-Touchque-State: <state>, plus
X-Touchque-Reason: <reason> when the step has one; @touchque/web 2.1.0 reads the step from them when
the body has no touchque key. A frontend on another origin must list them in
Access-Control-Expose-Headers.
Your own error shape (error_body:)
Refusals (403, 408, 423, 429) answer {"touchque": step, "token": "..."}; the guard's own errors (401,
500, 503) answer {"touchque": step, "error": {"code", "message"}}. To answer in your API's own error
shape, pass error_body::
require_touchque "SEND_MONEY", only: :create,
error_body: ->(r) { { message: r[:message], code: r[:code] } }It is called for every answer of 400 and above (401, 403, 408, 423, 429, 500, 503), never for a 202 step or an approval, with the refusal, a Hash:
-
status:; -
code:: the error's code, else the step'sreason, else itsstate; -
message:: the error's message, else by state: "The approval was rejected.", "The approval expired. Try again.", "Too many rejected approvals. Try again later." (frozen), "Too many attempts. Try again later." (rate_limited), "The approval was refused." (anything else); -
touchque:: the step as it would be sent.
The proc runs in the controller (request and t(...) work there), or name a method:
error_body: :touchque_error. What the result encodes to as JSON decides. A JSON object (a Hash, a
Struct or Data, an object with to_hash or whose as_json is a Hash) is sent with "touchque" set to
the step, replacing yours, so @touchque/web still sees the state: 403
{"message":"The approval was rejected.","code":"rejected","touchque":{"state":"rejected",...}}. No
token is added. Anything else (a String, a number, an Array, nil) is sent as it is, as JSON. The
proc gets a copy of the step. The status and the headers stay the same (JSON, Cache-Control: no-store,
Retry-After, X-Touchque-State). One that raises, or a result that cannot be encoded, is logged
([Touchque] errorBody failed: <message>) and the default body is sent.
Action types
"SEND_MONEY" above is an action type: one kind of approval, with the title the phone shows and
whether it is critical. Define each one once, in the dashboard (Developers โ Action types)
or from code:
tq.action_types.define("SEND_MONEY", name: "Send money", critical: true)The guard refuses what is not ready. A name that is not defined is a setup error
(Touchque::ConfigError, "Unknown action โฆ"): the guard answers 500 with reason: "misconfigured". A type
turned off in the dashboard answers 403 with reason: "action_disabled", which stops that kind of
approval at once, without a deploy.
Guard inside your handler
When your own checks come first (the balance, who owns the account), run the guard in your action,
after them, with Touchque::Guard.run: the same two-phase contract as require_touchque, for Rails,
Sinatra, Hanami or plain Rack.
def create
# Your checks first, on every request (each poll comes back through them).
account = current_user.accounts.find(params.require(:from))
return render(json: { error: "insufficient_funds" }, status: 422) if account.balance < amount
input = Touchque::Guard.input_from_headers(->(name) { request.headers[name] })
result = Touchque::Guard.run(
nil, # the client: Touchque.client, built on this request, then kept
current_user.email, "SEND_MONEY",
details: { "Amount" => "#{amount} EUR", "To" => account.iban }, # shown on the phone, bound to the approval
ip: request.remote_ip, user_agent: request.user_agent, **input
)
if result[:approved]
Transfers.send!(account, amount) # approved: runs once
return render(json: { sent: true })
end
# Not approved (yet): what require_touchque sends for the same result.
status, headers, body = Touchque::Guard.response(result)
response.headers.merge!(headers)
render json: body, status: status
endIn Sinatra or plain Rack, status, headers, body = Touchque::Guard.response(result) and answer
[status, headers, [body]].
-
The client.
nilisTouchque::Guard.default_client:Touchque.client, built fromconfig.touchqueorTQ_API_KEY/TQ_API_SECRETon the first request that needs it and kept once built, so nothing raises at boot or in a request. While a key is missing the answer is 500misconfigured(401unauthenticatedwithout a user), logged once throughTouchque.logger, and a later request tries again. Do not passTouchque.clientitself: it raisesTouchque::ConfigErrorwithout keys.Touchque::Guard.status_poll?takesnilthe same way. -
Your own client for
nil(yourbase_url:, say):Touchque::Guard.default_client = Touchque::Client.new(...)once at boot;Touchque::Guard.default_client = nilforgets it, and the next call builds fromconfig.touchque/ the environment again. The SDK logs throughTouchque.logger(in Rails,Rails.loggerunless you set one). To fail fast at boot instead of answering 500, callTouchque.clientthere: it raisesTouchque::ConfigError, naming what is missing (Touchque::Guard.default_clientanswersnilinstead, and logs it once). -
202
{"touchque": step, "token": "..."}: show the step and send the same request again withX-Touchque-Token: <token>until it is approved (@touchque/webdoes this loop). While it waits (waiting,passkey_required), every answer carries the request'sexpiresAt, as Touchque has it now (a push moved to a passkey during a call gets more time): stop polling once it is past. -
200 with
result[:approved]: run the action once. The approval is used up there: the same token never approves twice.Touchque::Guard.responseraisesArgumentErrorfor it. -
401, 403, 408, 423, 429, 500, 503:
Touchque::Guard.response(result)gives[status, headers, body], Rack style: the body as JSON text, the headers with lower-case names (content-type,cache-control: no-store,retry-afteron 423 and 429,x-touchque-stateandx-touchque-reason). For your own error shape pass a callable,Touchque::Guard.response(result, error_body: ->(r) { { message: r[:message], code: r[:code] } }): the rules ofrequire_touchque'serror_body:; one that raises, or a result that cannot be encoded, is logged and the default body sent. -
First-time QR: a user with no phone linked gets the step
enrollwithenroll.qrCodeDataUrl, the recovery codes andenroll.expiresAt. While the first-time QR is up, polls answer{state: "enroll", expiresAt}withoutenroll: keep showing the QR you have. About 15 s before it expires a poll brings a new QR withenroll.qrCodeDataUrland new recovery codes: the old QR and the old codes stop working. Pages on@touchque/webneed 2.1.0. -
No linking QR (
enroll: false, onTouchque::Guard.runorrequire_touchque; the relay's pre-authPOST /loginand its passkey registration do the same): a user with no phone gets 202{"touchque": {"state": "enroll", "reason": "enrollment_off"}}. It is final: stop polling and tell them to link the Touchque app first. -
Other 202 states (
passkey_required,offline, anenrollwith areason) need@touchque/web, or your own UI following the contract. -
Rate limits:
Touchque::Guard.status_poll?tells a poll from a new attempt (a poll only reads the status). If you count attempts per user, passTouchque::Guard.runbefore_start:, a callable it calls when a first-time QR poll starts after all (the user linked, or the QR is gone or within about 15 s of expiring), to charge that start; return a result to answer instead, or nil or false to go on (anything else answers 503). The relay does this forPOST /login.
Where a first-time QR was asked for
Before it links, the Touchque app shows where the linking QR was asked for (the city, the browser and
device, the time), so someone tricked into scanning another person's QR sees that person's place and
device. Touchque records it from the request that made the QR, generate_secret or reset_secret (a new
QR in place of the last one), and keeps it on its servers, never in the QR; with neither an IP nor a
User-Agent the QR has none (a reset does not carry the last one's over). require_touchque and the relay
send the browser's IP and User-Agent with the QR and its renewal as with the push, and
Touchque::Guard.run and tq.start send the ip: and user_agent: you give them; when you make the QR
yourself, pass them as you do for login.request. They go as given: Touchque keeps an IP address without
its port (a loopback address, or anything that is not an IP address, is dropped) and the User-Agent
without control characters, at most 512 characters, and never refuses the QR over them.
validate_secret is the phone's call: the Touchque app makes it after scanning, and the answer carries
"setupContext", a Touchque::SetupContext (a Hash with a reader per field, any of them nil), or nil
when none was recorded (a QR asked for without a browser, or an older QR). Its "farFromPhone" compares
the QR's place with the address of whoever calls validate_secret: called from your server (a test, a
support tool), it compares with your server, not with the phone.
qr = tq.auth.generate_secret(user, client_ip: request.remote_ip, user_agent: request.user_agent)
# Show qr["qrCodeDataUrl"]; tq.auth.reset_secret takes the same client_ip: and user_agent: for a new QR.
# What the phone is shown when it scans that QR, here asked from your server:
ctx = tq.auth.validate_secret(qr["secret"])["setupContext"] # nil: none recorded
ctx&.location&.city # "Berlin"; also ctx.ip, ctx.device&.browser, ctx.requested_at
ctx&.far_from_phone # measured from your server's address here, not the phone'sThe three primitives (any framework)
step = tq.start("SEND_MONEY", "jane@acme.com", details: { "Amount" => "250 EUR" })
# step["state"]: waiting (show step["number"]) | enroll (show step["enroll"]["qrCodeDataUrl"]) | passkey_required | blocked | frozen | rate_limited
now = tq.check(step["requestId"])
approval = tq.complete(step["requestId"], "jane@acme.com", "SEND_MONEY", details: { "Amount" => "250 EUR" })
# uses the approval once, and only for this user, action and amountTouchque::Guard.run(nil, user, action, token:, offline:, code:, ...) is the whole two-phase
contract for Sinatra, Hanami or plain Rack: see "Guard inside your handler".
Waiting in one call
result = tq.login.verify("jane@acme.com", type: "LOGIN", client_ip: request.remote_ip, user_agent: request.user_agent) do |c|
# Number matching: show the number now; the phone asks for it.
notify("Pick #{c["challengeCode"]} on your phone") if c["challengeCode"]
endverify raises Touchque::RejectedError, Touchque::TimeoutError or
Touchque::PasskeyRequiredError (reason "policy": approve with a passkey; "step_up": the user
tapped Approve during a call and the request now waits for a passkey).
Relay routes for @touchque/web
# config/routes.rb
mount Touchque::Rack::Relay.new(
get_user_id: ->(req) { req.session["user_email"] },
# The user who already passed your password step. Binds /login and the offline routes to them.
get_login_user: ->(req) { req.session["password_verified_user"] },
on_authenticated: ->(req, response, info) { req.session["user_email"] = info["externalUsername"] },
silent_sign_in: true # a known browser with nothing new skips the push
) => "/touchque"Routes: POST /login, /enroll/start, GET /enroll/status, /offline/challenge|verify|totp,
/passkey/authenticate/options|verify, /passkey/login/options|verify,
/passkey/register/options|verify, GET /passkey/credentials, DELETE /passkey/credentials/:id.
Pre-auth routes are rate limited (20 per IP, 5 per username a minute; pass rate_limit: { store: }
for Redis across processes). Polls of an approval on its way have their own per-IP budget; a
first-time QR poll that starts after all (the user linked, or the QR is gone or within about 15 s of
expiring) counts against the username's budget like a new attempt. Guard answers of 400 and above carry X-Touchque-State (and
X-Touchque-Reason). The offline routes stay off until get_login_user is set, and without it
POST /login never shows the linking QR: a user with no phone gets 202
{"touchque": {"state": "enroll", "reason": "enrollment_off"}}. Adding a passkey for a user with a
linked phone waits for the phone first.
Webhooks
class TouchqueWebhooksController < ActionController::API
include Touchque::Rails::Webhook
verify_touchque_webhook
def create
EndSession.call(touchque_webhook["requestId"]) if touchque_webhook["event"] == Touchque::Resources::Webhook::EVENT_APPROVAL_REVOKED
head :ok
end
endThe signature (your API secret over the canonical JSON), the signed timestamp (5 minutes) and the
jti are checked first: a bad one answers 401, a replay 200 without running your action again.
Touchque.replay_cache is in-process by default; with several Puma workers or hosts set one over
Redis (check_and_set(jti, ttl_seconds) with SET NX EX). Anywhere else:
tq.webhook.verify(raw_body, signature_header, replay_cache: cache).
Silent sign-ins
risk = tq.risk.check(user, browser_proof: request.headers["X-Touchque-Browser"], client_ip: request.remote_ip)
sign_in(user) if risk["prompt"] == false # a known browser, nothing new: no pushFails closed: only an answer of exactly prompt: false skips the phone. tq.risk.browsers(user)
lists a user's known browsers; forget_browsers(user) forgets them (after a password reset).
Passkeys, offline codes, recovery, help desk
-
tq.webauthn: registration, second factor and passwordless sign-in options/verify, list and delete passkeys. -
tq.offline: QR challenge and typed codes with the phone offline;totp_verifiers+Touchque::Resources::Offline.match_totp_verifiercheck time-based codes while Touchque is unreachable. -
tq.recovery(Never Locked Out): vouchers,start(showbindUrias a QR),status,veto. -
tq.assist(help desk):open,verify(a 2-digit code the agent reads to the person),spend,unfreeze,end. -
Touchque::ApprovalProof.verify(proof, request_id:, type:, details:, expected_public_key:): the phone's own signature over what it showed ("what you see is what you sign").
Touchque Actions
tq.actions.deploy("night-alert", trigger: "approval.decided",
template: { id: "alert", params: { channel: "slack", when: { countries: ["TR"] } } })
replay = tq.actions.dry_run(trigger: "login.request", code: code, limit: 500)Plus test, rollback, logs, metrics, templates, secrets. Action code is JavaScript run
by Touchque in a sandbox, whatever language your server is in. Action types:
tq.action_types.define("SEND_MONEY", name: "Send money", critical: true).
AI agents
Your server registers agents (public key only) and checks their approvals; the agent signs in with its own key:
keys = Touchque::AgentKeys.generate # where the agent runs; "ES256" or "EdDSA"
agent = tq.agents.create("Invoice bot", ["PAY_INVOICE"], public_key: keys["publicJwk"])
# The agent (TQ_AGENT_ID, TQ_AGENT_KEY): private_key_jwt + DPoP, never your API key.
bot = Touchque::Agent.new
approved = bot.require_approval("ayse@acme.com", "PAY_INVOICE", [payment]) { |s| say "Type #{s["challengeCode"]} on your phone" }
# Your server, right before it pays:
tq.agents.redeem_approval(approved["approvalToken"], user: "ayse@acme.com", authorization_details: payment)Also: mandates (request_mandate), the token vault (tq.agents.vault, bot.get_connection_token),
policies, blocks, the kill switch, offline token checks (verify_approval_token).
Touchque::OrgAgent is an organization's agent on Touchque SSO (DPoP tokens for one app, token
exchange, CIBA, the token vault, shared accounts; GitHub Actions and Kubernetes tokens instead of
a stored key). Touchque::McpAuth protects an MCP server whose authorization server is Touchque SSO.
Cross App Access (ID-JAG) and A2A agent cards
An organization's identity provider (Touchque SSO) can let one of its apps reach another service for a member with no consent screen (Cross App Access, ID-JAG, an open IETF draft): the app trades the member's ID token for an ID-JAG, then the ID-JAG for an access token at the other service. If you run an authorization server, the verifier checks an ID-JAG (issuer, single audience, your client, expiry, typ) and uses it once. Before your agent trusts another agent's A2A card, check its signatures (A2A 1.0 ยง8.4: JWS over the RFC 8785 canonical card); keys named by jku are only fetched from the card's own host or hosts you trust.
jag = Touchque::CrossAppAccess.request_id_jag(issuer: "https://sso.touchque.com", client_id: client_id, client_secret: secret,
id_token: id_token, audience: "https://auth.files.example")
tokens = Touchque::CrossAppAccess.redeem_id_jag(token_endpoint: "https://auth.files.example/token", client_id: "acme",
client_secret: files_secret, assertion: jag["assertion"])
# Your own authorization server (jwt-bearer grant). One verifier per process (an initializer): it
# remembers the jtis it accepted (first_use: for a store several processes share) and caches the keys.
ID_JAGS = Touchque::IdJagVerifier.new(issuer: "https://sso.touchque.com", audience: "https://auth.files.example")
claims = ID_JAGS.verify(params[:assertion], client_id: authenticated_client_id)
Touchque::AgentCard.verify(card_json, card_url: "https://agent.example/.well-known/agent-card.json")A refused call raises Touchque::IdJagError. For any answer but 2xx (a redirect too: it is never followed), its error is the error of the token endpoint's JSON answer, or server_error when that names none, and status is the answer's status. invalid_response is a 2xx answer that is not a JSON object (or, from the identity provider, holds no ID-JAG). temporarily_unavailable means the token endpoint could not be reached or its answer read: no status, the Touchque::NetworkError (or the error of a body that does not decompress) as cause, worth another try later.
Optional DPoP binding (RFC 9449): give one key to both calls and the ID-JAG is bound to it (cnf.jkt), useless to anyone who copies it without the key. A token endpoint that asks for a nonce (use_dpop_nonce with one valid DPoP-Nonce header) gets the same request once more, with a new proof that carries it; Touchque::IdJagError#dpop_nonce is the latest valid nonce the server sent during the call. When the access token comes back DPoP-bound ("token_type" => "DPoP"), send it as Authorization: DPoP <token> with a DPoP proof for that method and URL that carries the token: id_jag_dpop_proof(dpop_key, url, method:, access_token:), plus nonce: when the service asks for one (put in the proof as given). A proof's htu is the URL with scheme and host in lower case, the default port dropped, / for an empty path, the path as given (dot segments are not removed) and no query or fragment.
Another company's authorization server that accepts Touchque ID-JAGs must verify the DPoP proof itself (typ dpop+jwt, the signature with the jwk in it, htm, htu, iat, each jti once, and the nonce when it requires one) before it calls IdJagVerifier#verify, because the verifier uses up the ID-JAG's jti: checked the other way round, a proof refused with use_dpop_nonce would leave the client's retry with the same ID-JAG refused as already used. It must also check cnf.jkt, refusing a bound ID-JAG unless the proof key's thumbprint equals it; IdJagVerifier#verify does the cnf.jkt part when you pass that thumbprint as dpop_jkt:.
dpop_key = Touchque::CrossAppAccess.create_id_jag_dpop_key # keep it in this process
jag = Touchque::CrossAppAccess.request_id_jag(issuer: "https://sso.touchque.com", client_id: client_id, client_secret: secret,
id_token: id_token, audience: "https://auth.files.example", dpop_key: dpop_key)
jag["dpop_bound"] # true when the returned ID-JAG carries dpop_key.thumbprint as cnf.jkt
tokens = Touchque::CrossAppAccess.redeem_id_jag(token_endpoint: "https://auth.files.example/token", client_id: "acme",
client_secret: files_secret, assertion: jag["assertion"], dpop_key: dpop_key)
# Each call with a DPoP-bound access token: a new proof for its method and URL.
url = "https://api.files.example/v1/files"
headers = { "Authorization" => "DPoP #{tokens["access_token"]}",
"DPoP" => Touchque::CrossAppAccess.id_jag_dpop_proof(dpop_key, url, method: "GET", access_token: tokens["access_token"]) }
# Your authorization server, once the request's DPoP proof has checked out (proof_jwk: the jwk in its header):
claims = ID_JAGS.verify(params[:assertion], client_id: authenticated_client_id, dpop_jkt: Touchque::AgentKeys.thumbprint(proof_jwk))
claims["cnf_jkt"] # the bound key's thumbprint; nil for an unbound ID-JAGShared Signals (security events from Touchque SSO)
When something happens to a member's account after sign-in (sessions revoked, credentials changed or compromised, a device out of compliance, the account disabled), Touchque SSO sends a Security Event Token (OpenID Shared Signals Framework 1.0) to the receivers the organization's admin adds (Organization > Continuous access). Your app ends the person's sessions or asks them to sign in again. The verifier reads the keys from the issuer's /.well-known/ssf-configuration and checks the signature, typ, issuer, audience and the one event. A SET does not expire: keep the jtis you handled and skip a repeat.
SSF = Touchque::SecurityEventVerifier.new(issuer: "https://sso.touchque.com", audience: "https://app.example.com")
# Push (RFC 8935): the SET is the request body (application/secevent+jwt).
def create
event = SSF.verify(request.raw_post) # "name": session-revoked, credential-change, account-disabled...
end_sessions_of(event["subject"]["email"]) if event["name"] == "session-revoked"
head :accepted
rescue Touchque::SecurityEventError => e
render json: { err: e.error, description: e.message }, status: e.error == "temporarily_unavailable" ? 503 : 400
end
# Poll (RFC 8936): acknowledge what you handled on the next call.
ack = []
loop do
out = Touchque::SecurityEvents.poll(url: poll_url, token: stream_token, ack: ack, max_events: 50, return_immediately: true)
ack = out["sets"].map do |jti, set|
handle(SSF.verify(set))
jti
end
break if ack.empty? && !out["more_available"]
endverify returns "jti", "issuer", "audience", "issued_at", "txn" (the case code of Touchque's decision), "subject", "type", "name" and "claims", or raises Touchque::SecurityEventError whose error is the RFC 8935 code to answer (invalid_request, invalid_key, invalid_issuer, invalid_audience; temporarily_unavailable when the issuer's keys could not be read). Report a SET you refuse while polling with set_errs: { jti => { "err" => e.error, "description" => e.message } }.
Touchque Login (hosted sign-in)
# config/application.rb
config.touchque.login = { domain: "acme.login.touchque.com", client_id: "...", client_secret: "...",
scope: "openid profile email offline_access" }
# config/routes.rb
Touchque::Rails.login_routes(self) # GET /login, /callback, /logout
class AccountController < ApplicationController
include Touchque::Rails::HostedLogin
before_action :require_touchque_sign_in
def show = render(json: touchque_session["user"])
endThe session lives in encrypted cookies (AES-256-GCM, split when large, no session store needed;
keyed from config.touchque.session_secret or secret_key_base) and is refreshed before the
access token expires. Touchque::HostedLogin is the OpenID Connect client underneath (PKCE, ID
and access token checks, refresh, token exchange, CIBA, the token vault, client credentials,
logout); your API checks access tokens with verify_access_token(token, audience:, required_scopes:).
login.my_account(access_token) is the customer's own account API. The Management API is
tq.identity (users, roles, organizations, apps, connections, imports and exports, attack
protection, email and SMS providers, custom domains, the passkey domain, your user store).
Its refusals are Touchque::APIError with the reason in error (not_enabled, invalid_request
with data["field"]...).
Custom domains
d = tq.identity.custom_domains.create(domain: "login.acme.com") # d["records"]: the DNS records to add
tq.identity.custom_domains.verify(d["id"]) # checks the TXT record and the DNS now; returns the domain
tq.identity.custom_domains.get(d["id"]) # found in the list (the API has no read by id)
tq.identity.custom_domains.overview # { "domains", "verifiedDomains", "slugPasskeys" }list returns the domains alone; overview the whole answer, always with its three keys:
"verifiedDomains" (your organization's verified domains, nil when they could not be read) and
"slugPasskeys" (customer passkeys made on {slug}.login.touchque.com). A domain your organization
verified, or one under it (Organization โ Domains: login.acme.com under acme.com), is verified
when added and needs only its CNAME. Each domain carries dns (the last DNS check) and
autoCheckUntil: Touchque checks a new domain by itself every 5 minutes for 72 hours. get raises
Touchque::APIError 404 not_found for an id you do not have, as the API does.
update(id, primary: true) makes a verified domain the issuer.
Passkey domain
tq.identity.set_passkey_domain("acme.com") # nil: each sign-in address keeps its ownA passkey works only on the domain it was made for (its relying party ID) and the hosts under it.
Without a passkey domain a customer's passkey belongs to the address it was made on
(acme.login.touchque.com, login.acme.com); with one, passkeys made on it or on a host under it
belong to it and keep working when sign-in moves to another host under it. Only a domain you proved:
one of your verified custom domains, or a domain above one that your organization verified
(Organization โ Domains: acme.com for login.acme.com). Anything else is refused (409
not_your_domain; 400 invalid_request with data["field"] "passkeyDomain" for what is not a
domain): a TXT record on login.acme.com proves nothing about acme.com. {slug}.login.touchque.com
keeps its own passkeys: tq.identity.custom_domains.overview counts them ("slugPasskeys") and lists
your organization's verified domains ("verifiedDomains"). Set it before customers make passkeys: a
passkey belongs to its domain for good, so a change that would leave existing customer passkeys behind
is refused (409 passkeys_exist, how many in data["count"]). 409 organization_unavailable: your
organization's verified domains could not be read; try again. Before Touchque Login is set up for the
workspace the answer is 400 invalid_request with data["field"] "slug": set it up first
(tq.identity.update_tenant(slug: "acme", displayName: "Acme")).
Moving customers in from your user database
Your customers sign in with the password they already have. Until one has a Touchque Login account, Touchque asks your endpoint about that address:
tq.identity.set_user_store(url: "https://api.acme.com/touchque/user-store", enabled: true)
tq.identity.test_user_store # one signed user_store.ping: { "ok" => true, "error" => nil, "ms" => 84 }
tq.identity.get_user_store # url, enabled, active, movedIn, lastCall, paused
tq.identity.remove_user_store # stop asking; accounts moved in stay
class UserStoreController < ActionController::API
include Touchque::Rails::Webhook
verify_touchque_webhook # signed like a webhook: signature, timestamp, jti
def create
e = touchque_webhook
user = User.find_by(email: e["email"]) if e["email"]
user = nil unless e["event"] == "user_store.get_user" || user&.authenticate(e["password"].to_s)
render json: { user: user && { id: user.id, email: user.email, name: user.name } }
end
enduser_store.verify_password { email, password } comes at a password sign-in, user_store.get_user
{ email } at "forgot password", an email code or a sign-up. Answer 200 { "user": { "id", "email" } }
or { "user": null } (404 counts as null) within 5 seconds, the same for an unknown address and a
wrong password. id is yours (kept as externalId), email the address asked about; optional:
emailVerified, name, givenName, familyName, nickname, picture (https), locale, phone,
userMetadata, appMetadata. A password you confirm is kept by Touchque (Argon2id) and that customer
is never asked about again. Anything else (another status, a redirect, a body that is not JSON, a user
without id or with another address) or no answer in 5 seconds counts as unavailable, never as a wrong
password; 5 in a row leave your endpoint alone for a minute (paused). The request carries the
password the customer typed: never log it. It may hold any text, even an unpaired UTF-16 surrogate
(JavaScript writes one as \ud800): the signature is checked over the body as sent, and the payload
comes back with U+FFFD in its place, so every String in it is valid UTF-8.
set_user_store takes an https URL; an argument left nil keeps its value. Asking needs passwords on
(409 passwords_off), and while it is on passwords cannot be turned off (409 user_store_on).
test_user_store(url: ...) pings a URL before you set it; a failing endpoint is "ok" => false with
the reason in "error", not an exception. remove_user_store answers 204 whether or not one was set (a
404 is not_enabled).
Mobile SDK (your own app approves)
e = tq.mobile.create_enrollment(user_id) # the app spends e["enrollmentToken"]
push = Touchque::Resources::Mobile.push_from_webhook(event) # a MOBILE_PUSH webhook โ APNs payload / FCM dataOr give Touchque your APNs key / FCM service account (update_settings(apns:, fcm:)) and it pushes for you.
Pairing 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, with number matching. Your page sends the thumbprint of its browser key (@touchque/web browserKey.thumbprint()); the nonce in the QR never leaves your server (Touchque keeps its hash).
p = tq.qr_pairings.create(key_thumbprint, client_ip: request.remote_ip, user_agent: request.user_agent)
# show p["uri"] (touchque://pair-browser?...) as a QR code; poll:
now = tq.qr_pairings.get(p["pairingId"]) # waiting -> scanned -> confirmed
tq.login.request(now["externalUsername"], qr_pairing: p["pairingId"]) if now["state"] == "confirmed"
# or: tq.qr_pairings.refuse(p["pairingId"], reason: "device_not_approved", message: "Ask IT to approve this computer.")get says scanned / confirmed once a phone holding one of your users' accounts read it (with proximity: same network, same country), reported when the person said someone told them to scan it (their 2FA freezes). refuse tells the phone why your own checks said no.
A code typed back on the phone
When a sign-in needs a code another service sent the person (a text message, WhatsApp, e-mail), ask them to type it on the phone instead. The phone encrypts it to a one-time key you made for this request: Touchque only ever holds the ciphertext. Such a request lives 5 minutes.
key = Touchque::CodeReply.new_key # keep key["privateKey"] for this request
sent = tq.login.request(user, reply: { kind: "code", key: key["publicKey"], channel: "sms", target: "+**********26" })
status = tq.login.status(sent["requestId"]) # once CONFIRMED
code = status["reply"] && Touchque::CodeReply.open(key["privateKey"], sent["requestId"], status["reply"]["ct"])Safe Guard (Safe transactions approved on the phone)
TouchqueSafeGuard is a transaction guard for a Safe: a transaction runs only with approvals signed by the P-256 keys on its approvers' phones. You send the raw transaction; the phone decodes it itself, shows its own rows and signs what it computed with a key only its biometrics unlock. Delegatecalls, changes to the Safe and proxy upgrades are governance: scheduled, time-locked and vetoable. A phone without that key yet gets 409 crypto_key_missing.
target = { "chainId" => 1, "safe" => safe, "guard" => guard,
"tx" => { "to" => to, "value" => 0, "data" => data, "operation" => 0, "nonce" => 42 } }
sent = tq.safe_guard.request("treasurer@acme.com", "safe_payment", target.merge( # an action type from your dashboard
"config" => { "threshold" => 2, "govThreshold" => 3, "govDelay" => 172_800, "exitDelay" => 259_200 },
"batchTargets" => [multi_send_call_only],
"approverIndex" => 0 # this approver's index in the guard
))
done = tq.safe_guard.wait_for_approval(sent["requestId"]) # 5 minutes at most
approval = done["safeTx"]["approval"]
# Check it yourself: your own transaction, the approver's key from the guard on chain, and what
# you are about to do with it: "approve" runs this transaction, "schedule" starts a governance change.
purpose = done["safeTx"]["purpose"] == "schedule" ? "schedule" : "approve"
check = Touchque::SafeApproval.verify(target, approval, approver_key, purpose: purpose, approver_index: 0)
raise "approval refused: #{check["reason"]}" unless check["valid"]
if purpose == "approve"
signatures = Touchque::SafeApproval.with_approvals(owner_signatures, [approval]) # execTransaction(..., signatures)
else
data = Touchque::SafeApproval.schedule_call(safe, check["governanceHash"], [approval]) # a call to the guard; runs after govDelay
endTouchque::SafeApproval.verify makes the guard's check off chain, so a co-signer or your own server never has to trust Touchque: it computes the Safe transaction hash (EIP-712) and the governance hash from the raw fields, rebuilds the 149-byte message the phone signed and checks the P-256 signature. purpose: defaults to "approve": a schedule approval covers no Safe nonce or gas fields, so it is accepted only when you pass purpose: "schedule", never as permission to execute. It refuses a high s, an approval that expired or is valid for more than a day, another approver index, and, when you pass rows: or display_digest: from your own decoding, rows the phone did not show. "reason" is approval_malformed, public_key_invalid, approver_index_mismatch, approval_expired, rows_differ, high_s or signature_invalid. safe_tx_hash, governance_hash, message and display_digest are public too.
Testing your routes
Touchque::Testing::FakeTouchque (require "touchque/testing") is a Touchque::Client that answers in
memory: no network, no API keys, no Node.js. The real guard runs, so your routes answer what they answer
in production, and your test plays the phone. A Rails request test:
# test/integration/transfers_test.rb
require "test_helper"
require "touchque/testing"
class TransfersTest < ActionDispatch::IntegrationTest
setup { @tq = Touchque::Testing::FakeTouchque.new.install } # now Touchque.client
teardown { @tq.uninstall }
test "a transfer needs an approval on the phone" do
sign_in_as users(:jane) # your own sign-in helper
post transfers_path, params: { amount: 5 }, as: :json
assert_response :accepted # 202: the step and a token
token = response.parsed_body["token"]
@tq.approve # the person approves on the phone
post transfers_path, params: { amount: 5 }, as: :json, headers: { "X-Touchque-Token" => token }
assert_response :success
assert_equal [{ "label" => "Amount", "value" => "5 EUR" }], @tq.requests.last["details"]
end
endSinatra or plain Rack, with rack-test:
require "rack/test"
require "touchque/testing"
class TransferTest < Minitest::Test
include Rack::Test::Methods
def app = MyApp # Touchque::Guard.run(nil, ...) in its route
def test_a_transfer_needs_an_approval
Touchque::Testing::FakeTouchque.new.install do |tq| # the default client inside the block
post "/transfer", JSON.generate(amount: 5), "CONTENT_TYPE" => "application/json"
assert_equal 202, last_response.status
tq.approve
header "X-Touchque-Token", JSON.parse(last_response.body)["token"]
post "/transfer", JSON.generate(amount: 5), "CONTENT_TYPE" => "application/json"
assert_equal 200, last_response.status
end
end
end-
installmakes the fake the default client (Touchque::Guard.default_client = tq, soTouchque.client), whichrequire_touchque,Touchque::Guard.run(nil, ...)and a relay given noclient:use, untiluninstall; with a block, for the block only. Install it after your app configured Touchque (Touchque.configuredrops it). ATouchque::Rack::Relaykeeps the client of its first request: give itclient: tqin a test that builds it. -
tq.approve,tq.reject,tq.expire: the latest request, or one by its id (tq.approve(request_id);via: "WEBAUTHN"approves with a passkey). -
FakeTouchque.new(auto_approve: true)(ortq.auto_approve = true): every request is approved as it is made. The first request still answers 202; the next one runs the action. - Every user has a phone linked.
tq.unlink(user)shows them the first-time QR instead (FakeTouchque.new(linked: false): nobody has one);tq.link(user)is the phone scanning it.tq.secret_ttl_msis how long a QR works (5 minutes). -
tq.setups: every first-time QR made (generate_secretandreset_secret, the guard's and the relay's too), oldest first, each with"user","secret","clientIp"and"userAgent"as your app sent them (nilwhen it sent none or not a String),"requestedAt","expiresAt", and"usedAt"oncevalidate_secretsaw its user linked.tq.auth.validate_secret(secret)answers like the API for the phone that scanned it: only the user's newest QR works (an older one answers 404), with the"setupContext"the phone is shown, made from what your app sent as the API makes it: 203.0.113.7 is Berlin and 198.51.100.23 New York, a loopback address (a test request's127.0.0.1) is not kept, a private one is not shown, and"farFromPhone"isnil. -
FakeTouchque.new(number_match: true): pushes ask for the number47. -
tq.requests("id","user","type","details","referenceId","status","expiresAt", answered on each status check) andtq.calls("method","path","body"): what your app asked Touchque, in order. - Offline approval: the code is
ABCD123(FakeTouchque::OFFLINE_CODE), the time-based code123456(FakeTouchque::TOTP_CODE). Calls outside the step-up (recovery, agents โฆ) raiseTouchque::APIError404.Touchque::Testing::FakeClientis another name for it.
Errors, case codes and retries
| Error | When |
|---|---|
Touchque::APIError |
Touchque answered with an error: status, code (device_not_linked, already_used...), case_code, retry_after, data
|
Touchque::NetworkError |
the request never reached Touchque (safe to retry) |
Touchque::RejectedError, TimeoutError, PasskeyRequiredError
|
verify outcomes |
Touchque::WebhookSignatureError, WebhookReplayError
|
webhooks |
Touchque::ApprovalError, ApprovalMismatchError
|
agent approvals |
Touchque::ConfigError |
a missing key, an unknown action type, a wrong argument |
A feature your organization cannot use here raises a Touchque::FeatureError (still an APIError, status 403) with feature (device_risk, ai_agentsโฆ) and feature_reason: FeatureNotInPlanError, FeatureReadOnlyError or FeatureOffError โ not in its plan (an owner or admin adds it in the Touchque dashboard), being turned off (reads work for 14 days, changes are refused) or switched off on this Touchque deployment.
"Why?" case codes. Refusals and pushes carry a 6-character case code (K7P-2QX): show it
("Tell your support team: K7P-2QX"); your team opens the whole decision by it in the dashboard.
Retries. Every request is signed with a one-time nonce, so the SDK never replays one. Retry
Touchque::NetworkError at the call site; on 429 / 423 wait retry_after seconds. The client
never follows redirects and refuses plain http:// except for localhost.
Logging
The SDK writes nothing to $stderr on its own. To see its own problems (a misconfigured guard, a failed on_challenge, a relay without get_login_user), set a logger: Touchque.logger = Logger.new($stdout) (or any Logger). In Rails the Railtie sets it to Rails.logger when your app set none; set your own in an initializer (nil for none). Lines carry an error's class and message, never the request.
Development
bundle install
bundle exec rake test # needs Node.js: the tests run against testing/fake-touchque-api.mjs and fixtures/
gem build touchque.gemspecLicense
MIT