touchque-authenticator 4.2.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (48) hide show
  1. touchque/__init__.py +148 -0
  2. touchque/agent.py +314 -0
  3. touchque/agent_card.py +190 -0
  4. touchque/agent_frameworks.py +215 -0
  5. touchque/approval_proof.py +104 -0
  6. touchque/approval_token.py +134 -0
  7. touchque/client.py +105 -0
  8. touchque/code_reply.py +75 -0
  9. touchque/config.py +56 -0
  10. touchque/contrib/__init__.py +4 -0
  11. touchque/contrib/django.py +175 -0
  12. touchque/contrib/fastapi.py +208 -0
  13. touchque/contrib/flask.py +154 -0
  14. touchque/cross_app_access.py +222 -0
  15. touchque/exceptions.py +170 -0
  16. touchque/guard.py +290 -0
  17. touchque/hosted_login.py +474 -0
  18. touchque/http_client.py +156 -0
  19. touchque/mcp_auth.py +256 -0
  20. touchque/my_account.py +173 -0
  21. touchque/org_agent.py +262 -0
  22. touchque/rate_limiter.py +56 -0
  23. touchque/relay.py +643 -0
  24. touchque/resources/__init__.py +1 -0
  25. touchque/resources/action_types.py +52 -0
  26. touchque/resources/actions.py +234 -0
  27. touchque/resources/agents.py +236 -0
  28. touchque/resources/assist.py +115 -0
  29. touchque/resources/auth.py +65 -0
  30. touchque/resources/device_risk.py +174 -0
  31. touchque/resources/identity.py +268 -0
  32. touchque/resources/login.py +296 -0
  33. touchque/resources/mobile.py +130 -0
  34. touchque/resources/offline.py +138 -0
  35. touchque/resources/qr_pairings.py +93 -0
  36. touchque/resources/recovery.py +118 -0
  37. touchque/resources/risk.py +141 -0
  38. touchque/resources/safe_guard.py +99 -0
  39. touchque/resources/webauthn.py +115 -0
  40. touchque/resources/webhook.py +258 -0
  41. touchque/safe_guard.py +308 -0
  42. touchque/security_events.py +205 -0
  43. touchque/steps.py +239 -0
  44. touchque_authenticator-4.2.0.dist-info/METADATA +630 -0
  45. touchque_authenticator-4.2.0.dist-info/RECORD +48 -0
  46. touchque_authenticator-4.2.0.dist-info/WHEEL +5 -0
  47. touchque_authenticator-4.2.0.dist-info/licenses/LICENSE +21 -0
  48. touchque_authenticator-4.2.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,630 @@
1
+ Metadata-Version: 2.4
2
+ Name: touchque-authenticator
3
+ Version: 4.2.0
4
+ Summary: Official Python SDK for Touchque Authenticator (2FA/MFA, passkeys, adaptive auth)
5
+ Home-page: https://touchque.com
6
+ Author: Touchque
7
+ Author-email: developer@touchque.com
8
+ Project-URL: Source, https://github.com/Touchque/touchque-python
9
+ Classifier: Programming Language :: Python :: 3
10
+ Classifier: License :: OSI Approved :: MIT License
11
+ Classifier: Operating System :: OS Independent
12
+ Classifier: Framework :: Django
13
+ Classifier: Framework :: Flask
14
+ Classifier: Framework :: FastAPI
15
+ Requires-Python: >=3.7
16
+ Description-Content-Type: text/markdown
17
+ License-File: LICENSE
18
+ Requires-Dist: requests>=2.25.1
19
+ Provides-Extra: dev
20
+ Requires-Dist: pytest>=7.0.0; extra == "dev"
21
+ Requires-Dist: cryptography>=3.1; extra == "dev"
22
+ Provides-Extra: proof
23
+ Requires-Dist: cryptography>=3.1; extra == "proof"
24
+ Provides-Extra: agent
25
+ Requires-Dist: cryptography>=3.1; extra == "agent"
26
+ Provides-Extra: flask
27
+ Requires-Dist: flask>=2.0; extra == "flask"
28
+ Provides-Extra: django
29
+ Requires-Dist: django>=3.2; extra == "django"
30
+ Provides-Extra: fastapi
31
+ Requires-Dist: fastapi>=0.100; extra == "fastapi"
32
+ Requires-Dist: anyio>=3.0; extra == "fastapi"
33
+ Dynamic: author
34
+ Dynamic: author-email
35
+ Dynamic: classifier
36
+ Dynamic: description
37
+ Dynamic: description-content-type
38
+ Dynamic: home-page
39
+ Dynamic: license-file
40
+ Dynamic: project-url
41
+ Dynamic: provides-extra
42
+ Dynamic: requires-dist
43
+ Dynamic: requires-python
44
+ Dynamic: summary
45
+
46
+ # touchque-authenticator
47
+
48
+ The official Python server SDK for [TouchQue](https://touchque.com) — biometric push
49
+ 2FA, passkeys, and offline approval codes, added to any backend with one
50
+ decorator per route. Adapters for Flask, Django and FastAPI included.
51
+
52
+ [![PyPI version](https://img.shields.io/pypi/v/touchque-authenticator.svg)](https://pypi.org/project/touchque-authenticator/)
53
+ [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
54
+
55
+ 📘 Full docs: **[support.touchque.com](https://support.touchque.com)**
56
+
57
+ ## Install
58
+
59
+ ```bash
60
+ pip install touchque-authenticator
61
+ # with a framework adapter:
62
+ pip install "touchque-authenticator[flask]" # or [django] / [fastapi]
63
+ ```
64
+
65
+ The importable package is `touchque` (`import touchque`).
66
+
67
+ ## Setup
68
+
69
+ Get an API key and secret from your [TouchQue Dashboard](https://dashboard.touchque.com):
70
+
71
+ ```bash
72
+ export TQ_API_KEY=tq_auth_your_key
73
+ export TQ_API_SECRET=your_api_secret
74
+ ```
75
+
76
+ `TouchQue()` with no arguments reads these automatically.
77
+
78
+ ## Quick start (Flask)
79
+
80
+ ```python
81
+ from flask import request, jsonify
82
+ from touchque.contrib.flask import require_touchque
83
+
84
+ @app.post('/transfer')
85
+ @require_touchque('SEND_MONEY', details=lambda: {'Amount': f'{request.json["amount"]} EUR'})
86
+ def transfer():
87
+ return jsonify(ok=True)
88
+ ```
89
+
90
+ Django and FastAPI look the same:
91
+
92
+ ```python
93
+ # Django
94
+ from touchque.contrib.django import require_touchque
95
+
96
+ @require_touchque('SEND_MONEY')
97
+ def transfer(request):
98
+ ...
99
+ ```
100
+
101
+ ```python
102
+ # FastAPI
103
+ from touchque.contrib.fastapi import RequireTouchQue, install_touchque_exception_handler
104
+
105
+ install_touchque_exception_handler(app) # optional: flattens the response shape
106
+
107
+ @app.post('/transfer')
108
+ def transfer(approval = Depends(RequireTouchQue('SEND_MONEY'))):
109
+ ...
110
+ ```
111
+
112
+ Until the user approves on their phone, the decorator answers
113
+ **`202 {"touchque": step, "token": "..."}`** instead of running your view.
114
+ Your frontend renders `step` in its own UI (a matching number, or a QR code
115
+ the first time the user links the app) and sends the same request again with
116
+ header `X-TouchQue-Token: <token>` — see
117
+ [`@touchque/web`](https://www.npmjs.com/package/@touchque/web), which does
118
+ this loop for you in the browser. Once approved, the retried request reaches
119
+ your view exactly once.
120
+
121
+ ## Relay routes (sign-in, enrollment, passkeys, offline)
122
+
123
+ Instead of hand-writing the routes a frontend such as `@touchque/web` calls,
124
+ mount the relay: `POST /login` (two-phase, same `202` + token contract as
125
+ above), `/enroll/start`, `/enroll/status`, `/offline/challenge|verify|totp`,
126
+ `/passkey/authenticate/*`, `/passkey/login/*`, `/passkey/register/*`,
127
+ `GET /passkey/credentials` and `DELETE /passkey/credentials/<id>`.
128
+ `POST /passkey/authenticate/options` with no `email` answers options for any
129
+ passkey of your site, for `@touchque/web`'s passkey autofill
130
+ (`webauthn.primary_options()` with no username does the same).
131
+
132
+ ```python
133
+ # Flask
134
+ from touchque.contrib.flask import touchque_relay_blueprint
135
+
136
+ def opened(request, response, info): # open YOUR session here
137
+ session['user'] = info['externalUsername'] # info: externalUsername, requestId, via
138
+
139
+ app.register_blueprint(touchque_relay_blueprint(
140
+ tq,
141
+ get_user_id=lambda req: session.get('user'),
142
+ # The user who already passed your password step. Binds POST /login and the
143
+ # offline routes to them; the offline routes stay off (403) without it.
144
+ get_login_user=lambda req: session.get('password_ok'),
145
+ on_authenticated=opened,
146
+ ), url_prefix='/touchque')
147
+ ```
148
+
149
+ ```python
150
+ # FastAPI (callbacks may be async)
151
+ from touchque.contrib.fastapi import touchque_relay_router
152
+ app.include_router(touchque_relay_router(tq, get_user_id=..., get_login_user=...), prefix='/touchque')
153
+
154
+ # Django (urls.py) - CSRF stays on: send X-CSRFToken from the page, or pass csrf_exempt=True
155
+ from touchque.contrib.django import touchque_relay_urls
156
+ urlpatterns = [path('touchque/', include(touchque_relay_urls(get_user_id=..., get_login_user=...)))]
157
+ ```
158
+
159
+ Every callback gets the framework's request; `on_authenticated(request,
160
+ response, info)` also gets the response that will be sent, so it can call
161
+ `response.set_cookie(...)`. Other options: `rate_limit` (on by default: 20 per
162
+ IP and 5 per username per route per minute; a dict with `window_ms` /
163
+ `per_ip` / `per_user`, or `False`), `action_type` (default `'LOGIN'`),
164
+ `get_details`, `allow_offline_without_first_factor` and `silent_sign_in` (see
165
+ [Silent sign-ins](#silent-sign-ins-stop-asking-when-nothing-is-new)). Without a framework,
166
+ call `touchque.RelayHandler(...).handle(method, path, body=..., ...)` and
167
+ send the `RelayResponse` it returns.
168
+
169
+ ## The three primitives, if you're not using a framework adapter
170
+
171
+ ```python
172
+ from touchque import TouchQue
173
+
174
+ tq = TouchQue() # from TQ_API_KEY / TQ_API_SECRET
175
+
176
+ step = tq.start('SEND_MONEY', user='jane@acme.com', details={'Amount': '250 EUR', 'To': 'DE89...'})
177
+ # step['state']: 'waiting' (show step['number']) | 'enroll' (show step['enroll']['qrCodeDataUrl'])
178
+ # | 'approved' | 'rejected' | 'expired' | 'passkey_required' | 'frozen' | 'blocked'
179
+
180
+ latest = tq.check(step['requestId'])
181
+
182
+ # Once approved, consume it exactly once, right before doing the protected thing:
183
+ approval = tq.complete(step['requestId'], user='jane@acme.com', action='SEND_MONEY',
184
+ details={'Amount': '250 EUR', 'To': 'DE89...'})
185
+ ```
186
+
187
+ `complete()` verifies the approval was actually issued for this user, action
188
+ and transaction, and can only be consumed once.
189
+
190
+ ## Passkeys (phishing-resistant)
191
+
192
+ Push approval and offline codes stop password reuse and push fatigue, but a
193
+ real-time phishing proxy can still relay them. A passkey can't be phished —
194
+ the browser signs your site's real origin, and TouchQue refuses any other
195
+ (NIST SP 800-63B-4 §3.2.5). Register one via `tq.webauthn` on the server and
196
+ `@touchque/web`'s `passkeys.register()` in the browser; optionally require it
197
+ for critical actions in the Dashboard's Security Policy.
198
+
199
+ ## Offline sign
200
+
201
+ ```python
202
+ ch = tq.offline.challenge(external_username='jane@acme.com', type='WITHDRAW',
203
+ details={'Amount': '1,250.00 USD', 'Recipient': 'Jane Doe'})
204
+ # show ch['qrDataUrl'] — the phone scans it offline and shows a 7-character code
205
+ result = tq.offline.verify(challenge_id=ch['challengeId'], code=code)
206
+ ```
207
+
208
+ **A QR that follows a push.** Pass the push's request id when the offline QR is the fallback for a push
209
+ the user already started (the guard does this for you):
210
+
211
+ ```python
212
+ ch = tq.offline.challenge(user, type='LOGIN', request_id=step['requestId'])
213
+ # ch.get('challengeCode') is the number to print under the QR when number matching applies.
214
+ ```
215
+
216
+ If the user **rejects the push on the phone, the offline QR dies with it**: no new QR is issued for that
217
+ sign-in (409 `request_rejected`), a code for a QR already on screen is refused (`reason: 'request_rejected'`)
218
+ and so is the time-based code (`verify_totp(..., request_id=...)`). With number matching, print `challengeCode`
219
+ under the QR: the phone shows it among two decoys and the user taps the match; a wrong tap yields a code that
220
+ fails verification.
221
+
222
+ ## Webhooks
223
+
224
+ ```python
225
+ from touchque import WebhookEvents, WebhookReasons
226
+ from touchque.exceptions import TouchQueWebhookSignatureException
227
+
228
+ try:
229
+ # raw_body is text: in Flask request.get_data(as_text=True), in Django request.body.decode('utf-8').
230
+ event = tq.webhook.verify(raw_body=request.get_data(as_text=True), signature=request.headers['X-Signature'])
231
+ except TouchQueWebhookSignatureException:
232
+ return '', 403 # not from TouchQue
233
+ if event.get('event') == WebhookEvents.APPROVAL_REVOKED:
234
+ end_sessions_built_on(event['requestId'])
235
+ ```
236
+
237
+ Login results carry `status` (`SUCCESS` | `REJECTED`) and, when rejected, a `reason` (`WebhookReasons`):
238
+ `user_rejected`, `user_reported_fraud`, `user_reported_coached` (the user said someone on the phone told
239
+ them to approve), `risk_reversed`, `risk_step_up`, `approval_signature_invalid`, `device_integrity_failed`,
240
+ `vishing_suspected` and `phishing_origin` (see Vishing Shield). Treat a reason you do not know as a rejection.
241
+ Event webhooks carry `event` (`WebhookEvents`): `DEVICE_LINKED`, `DEVICE_UNLINKED`, `PASSKEY_REGISTERED`,
242
+ `PASSKEY_DELETED`, `APPROVAL_RECONFIRMED`, `APPROVAL_REVOKED`. Ignore events you do not know.
243
+
244
+ ## Vishing Shield (someone on the phone guiding the user)
245
+
246
+ The phone tells TouchQue, signed with its hardware key, whether a call was active (or just ended), the screen
247
+ was shared or the phone remote-controlled when the user tapped Approve. Depending on the server's mode:
248
+
249
+ - **Passkey instead.** A user with a passkey finishes in the browser: the request stays open and turns into
250
+ `passkey_required` mid-flight. The step-up flow and the relay handle it; the blocking `login.verify` raises
251
+ `TouchQuePasskeyRequiredError` (`reason == 'step_up'`). No offline or recovery code can finish such a request.
252
+ - **Refused.** A critical action without a passkey is rejected (`reason: vishing_suspected`).
253
+ - **Provisional.** Anything else is approved with `provisional` set on the approval dict from `complete`. Let the user
254
+ in, but treat the session as limited: TouchQue refuses the user's critical actions (`blocked` / `provisional`)
255
+ until the phone re-confirms after the call (`APPROVAL_RECONFIRMED`). `APPROVAL_REVOKED` (`reason` `COACHED` or
256
+ `UNDO`) means end the session; an approval revoked before you consumed it can no longer be consumed
257
+ (409 `revoked`).
258
+
259
+ **Mirror Alarm.** The first waiting step carries `canary.url`. `@touchque/web` loads it on the page showing the
260
+ sign-in and sends a beacon to it, so a real-time phishing proxy in front of your site shows up as itself: the
261
+ approval is refused (`reason: phishing_origin`) and the phone warns the user. Allow the canary host in your
262
+ Content-Security-Policy (`img-src` and `connect-src`).
263
+
264
+ ## TouchQue Actions (your code in the approval pipeline)
265
+
266
+ Alerts, step-ups and refusals by country, local time, role or amount, passkeys
267
+ for admins — from a template or a few lines of JavaScript, replayed against your
268
+ real recent sign-ins before they go live. Full guide: [support.touchque.com/actions](https://support.touchque.com/actions).
269
+
270
+ ```python
271
+ tq.actions.deploy('night-alert', trigger='approval.decided',
272
+ template={'id': 'alert', 'params': {'channel': 'slack', 'when': {'countries': ['TR'], 'hours': {'from': 0, 'to': 6}}}})
273
+
274
+ draft = 'exports.onExecute = async (event, api) => { if (event.context?.amount > 10000) api.stepUp("Over 10,000"); };'
275
+ report = tq.actions.dry_run(trigger='login.request', code=draft) # report['transitions'] → {'push→number_match': 3}
276
+ tq.actions.deploy('big-transfers', trigger='login.request', code=draft)
277
+ ```
278
+
279
+ Give Actions what only your server knows with `context=` (never shown on the
280
+ phone): `@require_touchque('SEND_MONEY', context=lambda: {'amount': request.json['amount']})`.
281
+ Loosening calls need a capability an admin approves on their phone. Action types
282
+ moved to `tq.action_types` in 4.0.
283
+
284
+ ## AI agents (an identity per agent, never your API key)
285
+
286
+ Register each agent with its **public** key; the private key stays where the agent runs. The agent signs in
287
+ with its own key and gets a 10-minute token bound to that key (DPoP). `pip install "touchque-authenticator[agent]"`.
288
+
289
+ ```python
290
+ from touchque import TouchQue, TouchQueAgent, generate_agent_key
291
+
292
+ keys = generate_agent_key() # or where the agent runs
293
+ agent = client.agents.create('Invoice bot', ['PAY_INVOICE'], public_key=keys['public_jwk'],
294
+ owner_email='ada@acme.com', platform='langchain')
295
+ # store agent['id'] and keys['private_jwk'] in the agent's secrets (TQ_AGENT_ID, TQ_AGENT_KEY)
296
+
297
+ me = TouchQueAgent().me() # in the agent
298
+ ```
299
+
300
+ `client.agents.suspend(agent_id)` stops one agent at once, `client.agents.set_kill_switch(True)` every agent.
301
+
302
+ ```python
303
+ ask = agent.request_approval('jane@example.com', 'PAY_INVOICE', [{
304
+ 'type': 'payment_initiation', 'instructedAmount': {'currency': 'TRY', 'amount': '500.00'},
305
+ 'creditorName': 'Jane Doe', 'creditorAccount': {'iban': 'TR330006100519786457841326'}}], reason='October rent')
306
+ reply(f"Type {ask['challengeCode']} in the TouchQue app to approve.")
307
+ token = agent.wait_for_approval(ask['approvalId'])['approvalToken']
308
+
309
+ # in your executor, right before paying: used once, only for what you are about to do
310
+ approval = client.agents.redeem_approval(token, user='jane@example.com', type='PAY_INVOICE',
311
+ authorization_details={'type': 'payment_initiation', 'instructedAmount': {'currency': 'TRY', 'amount': '500.00'}})
312
+ ```
313
+
314
+ In an agent framework, a policy says who approves which tool calls and what their
315
+ phone shows; the tool runs only after the person approved, `current_approval()`
316
+ holds the approval token inside it, and the function keeps its signature (LangChain
317
+ `@tool`, LlamaIndex `FunctionTool.from_defaults`, OpenAI Agents SDK `@function_tool`):
318
+
319
+ ```python
320
+ from touchque import ApprovalPolicy, with_touchque_approval, current_approval, approve_interruptions_with_touchque, touchque_can_use_tool, guard_mcp_session
321
+
322
+ policy = ApprovalPolicy(agent, user='jane@example.com', type='PAY_INVOICE',
323
+ details=lambda a, tool: [{'type': 'payment_initiation', 'instructedAmount': {'currency': 'TRY', 'amount': a['amount']}, 'creditorAccount': {'iban': a['iban']}}],
324
+ on_challenge=lambda s, tool: reply(f"Type {s['challengeCode']} in the TouchQue app to approve."))
325
+
326
+ @tool
327
+ @with_touchque_approval(policy)
328
+ def pay_invoice(iban: str, amount: str) -> str:
329
+ return bank.pay(iban, amount, current_approval()['approvalToken'])
330
+
331
+ state = approve_interruptions_with_touchque(result, {'pay_invoice': policy}) # OpenAI Agents SDK
332
+ options = ClaudeAgentOptions(can_use_tool=touchque_can_use_tool({'pay_invoice': policy})) # Claude Agent SDK
333
+ session = guard_mcp_session(session, {'pay_invoice': policy}) # an MCP ClientSession
334
+ ```
335
+
336
+ Agents also stop when their review date passes and when their owner leaves the organization.
337
+
338
+ ### Cross App Access (ID-JAG) and A2A agent cards
339
+
340
+ 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.
341
+
342
+ ```python
343
+ from touchque import request_id_jag, redeem_id_jag, IdJagVerifier, verify_agent_card
344
+
345
+ jag = request_id_jag(issuer='https://sso.touchque.com', client_id=client_id, client_secret=secret,
346
+ id_token=id_token, audience='https://auth.files.example')
347
+ tokens = redeem_id_jag(token_endpoint='https://auth.files.example/token', client_id='acme',
348
+ client_secret=files_secret, assertion=jag['assertion'])
349
+
350
+ # Your own authorization server (jwt-bearer grant):
351
+ claims = IdJagVerifier(issuer='https://sso.touchque.com', audience='https://auth.files.example') \
352
+ .verify(form['assertion'], client_id=authenticated_client_id)
353
+
354
+ verify_agent_card(card, card_url='https://agent.example/.well-known/agent-card.json')
355
+ ```
356
+
357
+ ## Shared Signals (security events from Touchque SSO)
358
+
359
+ Touchque SSO tells your app when something happens to a member's account after sign-in, as Security Event Tokens
360
+ (OpenID Shared Signals Framework 1.0): CAEP `session-revoked`, `credential-change`, `device-compliance-change`; RISC
361
+ `account-disabled`, `credential-compromise`. The organization's admin adds your app as a receiver (Organization >
362
+ Continuous access), by push to your endpoint or by poll. The verifier finds the keys through the issuer's
363
+ `/.well-known/ssf-configuration` and checks the signature, `typ`, issuer, audience and that there is one event; `txn`
364
+ is the case code of Touchque's decision. A SET does not expire: keep the `jti`s you handled and skip a repeat.
365
+ `pip install "touchque-authenticator[agent]"`.
366
+
367
+ ```python
368
+ from touchque import SecurityEventVerifier, SecurityEventError, poll_security_events
369
+
370
+ verifier = SecurityEventVerifier(issuer='https://sso.touchque.com', audience='https://app.example.com')
371
+
372
+ # Push (RFC 8935): the SET is the request body (application/secevent+jwt).
373
+ @app.post('/ssf')
374
+ def ssf():
375
+ try:
376
+ event = verifier.verify(request.get_data(as_text=True))
377
+ except SecurityEventError as e: # e.code: invalid_request, invalid_key, invalid_issuer, invalid_audience
378
+ return {'err': e.code, 'description': str(e)}, 503 if e.code == 'temporarily_unavailable' else 400
379
+ if event.name == 'session-revoked':
380
+ end_sessions_of(event.subject.get('email'))
381
+ return '', 202
382
+
383
+ # Poll (RFC 8936): acknowledge what you handled on the next call.
384
+ out = poll_security_events(url=poll_url, token=stream_token, ack=handled_jtis, max_events=50)
385
+ for jti, token in out['sets'].items():
386
+ event = verifier.verify(token) # then act on it as above
387
+ ```
388
+
389
+ ## Silent sign-ins (stop asking when nothing is new)
390
+
391
+ A user who approved on their phone in this browser a little while ago, from the same phone, network and country,
392
+ with no risk signal since, does not need another push. TouchQue's risk engine decides; your server only skips the
393
+ push when it says so.
394
+
395
+ 1. In the browser, `@touchque/web` 1.4.0 with `createTouchQueWeb({ browserKey: true })` keeps a non-extractable
396
+ key for your site and sends a fresh, signed proof of it in the `X-TouchQue-Browser` header.
397
+ 2. On the server, turn on `silent_sign_in`:
398
+
399
+ ```python
400
+ # Flask (Django's require_touchque and FastAPI's RequireTouchQue take the same option)
401
+ @app.post('/login/2fa')
402
+ @require_touchque('LOGIN', user=lambda: session.get('password_ok'), silent_sign_in=True)
403
+ def login_2fa():
404
+ # g.touchque['assurance']['method'] is 'silent' when no push was needed.
405
+ return jsonify(ok=True)
406
+
407
+ # Relay POST /login
408
+ app.register_blueprint(touchque_relay_blueprint(
409
+ tq,
410
+ get_user_id=lambda req: session.get('user'),
411
+ get_login_user=lambda req: session.get('password_ok'),
412
+ silent_sign_in=True, # or {'max_age_seconds': 8 * 3600} for your own limit
413
+ ), url_prefix='/touchque')
414
+ ```
415
+
416
+ With it on, a new attempt that carries the header first calls `tq.risk.check`. Only an answer of exactly
417
+ `prompt: false` approves it at once, with nothing sent to the phone: the approval has
418
+ `assurance == {'phishingResistant': False, 'method': 'silent'}`, `confirmedVia == 'SILENT'`,
419
+ `requestId == 'silent'` and `reasons` (`known_browser`, `recent_approval`, `same_phone`, `familiar_network`,
420
+ `no_risk_signal`); the relay calls `on_authenticated` with `via: 'silent'`. Anything else, and any error in the
421
+ check, starts the usual push with the proof attached, so its approval makes the browser known. Polling with the
422
+ token never checks again. `run_guard(..., browser_proof=..., silent_sign_in=True)` does the same for your own
423
+ framework (`silent_input_from_headers` reads the header).
424
+
425
+ TouchQue only lets a sign-in through silently when all of this holds: the browser proved its key and was approved
426
+ on the phone (a confirmed push, not one approved during a call, or a passkey) within your `max_age_seconds` and at
427
+ most 7 days ago, by the phone that is linked now; the country and the network were seen in the user's earlier
428
+ approved sign-ins; the risk engine allows it with no risk signal; and the action is an everyday one. A critical
429
+ action always asks. In `shadow` mode (`silentMode`) it always asks and the reasons say what would have happened.
430
+
431
+ Without the adapters:
432
+
433
+ ```python
434
+ browser_proof = request.headers.get('X-TouchQue-Browser')
435
+ risk = tq.risk.check(user, type='LOGIN', client_ip=request.remote_addr, browser_proof=browser_proof)
436
+ if risk['prompt'] is False:
437
+ return open_session(user) # risk['reasons'] say why
438
+ step = tq.start('LOGIN', user, ip=request.remote_addr, browser_proof=browser_proof) # the approval makes the browser known
439
+
440
+ browsers = tq.risk.browsers(user)['browsers'] # for an "approved browsers" list
441
+ tq.risk.forget_browsers(user) # all; or thumbprint=... for one
442
+ ```
443
+
444
+ Forget a user's browsers after a password reset or a "sign out everywhere". `risk.check` reads the answer
445
+ fail-closed (`parse_risk_check`): `prompt` is `False` only when TouchQue answered the boolean `false`; malformed
446
+ `reasons` become `[]` and a missing `assurance` is `'normal'`.
447
+
448
+ ## Never Locked Out (lost, dead or new phone)
449
+
450
+ A user whose phone is gone moves to a new phone without a help desk. Colleagues they named beforehand vouch on their own
451
+ phones, each typing a number the user reads them on a call; then a cooling-off (default 60 minutes) lets the old phone, any
452
+ voucher or an admin stop it. The risk engine can refuse it or ask for more vouchers, and for 24 hours afterwards critical
453
+ actions are refused. It is an option: offer it next to passkeys and the old phone's transfer, never as the only way. Every
454
+ step is a hash-chained receipt (`receipts`); a voucher's step carries the signature of their phone's hardware key.
455
+
456
+ ```python
457
+ # Settings page, after an approval on the user's phone:
458
+ tq.recovery.set_vouchers(user, ['bo@acme.com', 'cy@acme.com'])
459
+
460
+ # "I lost my phone", after the password:
461
+ r = tq.recovery.start(user, client_ip=ip, display_name='Ada', fallback_vouchers=admins)
462
+ show_qr(r['bindUri']) # the TouchQue app on the new phone scans it
463
+ now = tq.recovery.status(r['recoveryId']) # each voucher's 'code' to read to them
464
+ # now['status']: AWAITING_DEVICE -> VOUCHING -> COOLING -> COMPLETED (or VETOED / EXPIRED / FAILED)
465
+
466
+ tq.recovery.veto(r['recoveryId'], by='admin@acme.com') # an admin who does not believe it
467
+ ```
468
+
469
+ ## "Why?": case codes instead of guesswork
470
+
471
+ Every approval decision names a short case code (`K7P-2QX`: 6 characters, no I, O, 0 or 1). A user who was asked to
472
+ match a number, needed a passkey or was refused reads it out to your support team, and the team opens the whole
473
+ decision by it in the TouchQue dashboard (Logs → Look up a case): what went in, each check's verdict (the access rule
474
+ that matched, the risk signals that were acted on and the ones only measured), and the single change that would have
475
+ let it through. No screenshots, no log digging. The code opens nothing on its own: only your workspace sees its
476
+ decisions.
477
+
478
+ ```python
479
+ step = client.start('WITHDRAW', user, ip=request.remote_addr)
480
+ # step['caseCode'] -> 'K7P-2QX'; step['reasons'] -> [{'code': 'critical_action', 'text': 'The action is marked critical'}]
481
+ try:
482
+ client.login.request(user, type='LOGIN')
483
+ except TouchQueAPIException as err:
484
+ if err.case_code:
485
+ show(f'Tell your support team: {err.case_code}')
486
+ ```
487
+
488
+ `caseCode` is in the `login.request` and `risk.check` answers and every step (the guard keeps it while it waits);
489
+ `TouchQueAPIException.case_code` carries it on refusals.
490
+
491
+ ## Blocking `verify()` and number matching
492
+
493
+ `tq.login.verify()` sends the request and waits for the phone in one call. With number matching (your option, a
494
+ workspace policy, a critical action or the risk engine can turn it on) the phone asks the user to pick a number,
495
+ and the call returns only after they have. Pass `on_challenge`: it runs once, right after the request is created
496
+ and before the wait. **Show `challengeCode` to the user now; the phone asks for it.**
497
+
498
+ ```python
499
+ def show(challenge):
500
+ if challenge.get('challengeCode'):
501
+ notify_user(f"Pick {challenge['challengeCode']} on your phone", case=challenge.get('caseCode'))
502
+
503
+ tq.login.verify(user, 'SEND_MONEY', on_challenge=show)
504
+ ```
505
+
506
+ It gets a dict with `requestId`, `expiresAt` and, when present, `challengeCode`, `reasons` and `caseCode`. It is
507
+ not called when only a passkey can approve (`verify()` raises `TouchQuePasskeyRequiredError` first). An exception it
508
+ raises is logged (`touchque` logger, warning) and ignored: `verify()` keeps waiting. In a web request, where the
509
+ page hears nothing until you answer, use the relay or `tq.start()`: their first answer already carries the number.
510
+
511
+ ## Verifying the device proof (no need to trust TouchQue)
512
+
513
+ Every approval from a phone with a hardware key carries `approvalProof`: the phone's own
514
+ signature over the request id, action, number-match code and the exact details it showed.
515
+ `pip install "touchque-authenticator[proof]"`, then:
516
+
517
+ ```python
518
+ from touchque import verify_approval_proof
519
+
520
+ ok = verify_approval_proof(
521
+ event['approvalProof'], request_id=request_id, type='WITHDRAW', details=details,
522
+ challenge_code=challenge_code,
523
+ expected_public_key=user.touchque_device_key, # stored from their first verified approval
524
+ )
525
+ ```
526
+
527
+ Without `expected_public_key` it returns `False` unless `allow_unpinned_key=True` (trust on first
528
+ use — store `proof['publicKey']`, then pin it).
529
+
530
+ ## Reporting fraud
531
+
532
+ Learned later that an approved request was fraud? Report it — it is the strongest signal
533
+ TouchQue's risk engine learns from, and it stays in your audit log:
534
+
535
+ ```python
536
+ tq.login.report_fraud(request_id, reason='chargeback', note='Disputed by card holder')
537
+ # reason: 'chargeback' | 'account_takeover' | 'social_engineering' | 'other'
538
+ ```
539
+
540
+ ## Pairing a browser by QR code
541
+
542
+ 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).
543
+
544
+ ```python
545
+ p = client.qr_pairings.create(key_thumbprint, client_ip=ip, user_agent=ua)
546
+ # show p['uri'] (touchque://pair-browser?...) as a QR code; poll:
547
+ now = client.qr_pairings.get(p['pairingId']) # waiting -> scanned -> confirmed
548
+ if now['state'] == 'confirmed':
549
+ client.login.request(now['externalUsername'], qr_pairing=p['pairingId'])
550
+ # or: client.qr_pairings.refuse(p['pairingId'], 'device_not_approved', 'Ask IT to approve this computer.')
551
+ ```
552
+
553
+ `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.
554
+
555
+ ## A code typed back on the phone
556
+
557
+ 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.
558
+
559
+ ```python
560
+ key = new_code_reply_key() # pip install "touchque-authenticator[proof]"; keep key['private_key']
561
+ sent = tq.login.request(user, reply={'kind': 'code', 'key': key['public_key'], 'channel': 'sms', 'target': '+**********26'})
562
+ status = tq.login.status(sent['requestId']) # once CONFIRMED
563
+ code = open_code_reply(key['private_key'], sent['requestId'], status['reply']['ct']) if 'reply' in status else None
564
+ ```
565
+
566
+ ## Safe Guard (Safe transactions approved on the phone)
567
+
568
+ 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`.
569
+
570
+ ```python
571
+ from touchque import verify_safe_approval, with_safe_approvals, safe_schedule_call # pip install "touchque-authenticator[proof]"
572
+
573
+ target = {'chainId': 1, 'safe': SAFE, 'guard': GUARD, 'tx': {'to': to, 'value': 0, 'data': data, 'operation': 0, 'nonce': 42}}
574
+ sent = tq.safe_guard.request('treasurer@acme.com', 'safe_payment', { # an action type from your dashboard
575
+ **target,
576
+ 'config': {'threshold': 2, 'govThreshold': 3, 'govDelay': 172800, 'exitDelay': 259200},
577
+ 'batchTargets': [MULTI_SEND_CALL_ONLY],
578
+ 'approverIndex': 0, # this approver's index in the guard
579
+ })
580
+ done = tq.safe_guard.wait_for_approval(sent['requestId']) # 5 minutes at most
581
+ approval = done['safeTx']['approval']
582
+
583
+ # Check it yourself: your own transaction, the approver's key from the guard on chain, and what you will do with it.
584
+ purpose = done['safeTx']['purpose'] # 'approve' (execute it) or 'schedule' (a governance change)
585
+ check = verify_safe_approval(target, approval, approver_key, purpose=purpose, approver_index=0)
586
+ if not check['valid']:
587
+ raise RuntimeError(f"approval refused: {check['reason']}")
588
+ if purpose == 'approve':
589
+ signatures = with_safe_approvals(owner_signatures, [approval]) # execTransaction(..., signatures)
590
+ else:
591
+ data = safe_schedule_call(SAFE, check['governanceHash'], [approval]) # a call to the guard; runs after govDelay
592
+ ```
593
+
594
+ `verify_safe_approval` 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. Without `purpose` it accepts only an approval to execute this exact transaction (`approve`); an approval that schedules a governance change covers neither the Safe nonce nor the gas fields, so it passes only when you name `purpose='schedule'`. 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`, `safe_governance_hash`, `safe_approval_message` and `safe_display_digest` are exported too.
595
+
596
+ ## Errors
597
+
598
+ All SDK errors extend `TouchQueException`: `TouchQueAPIException`,
599
+ `TouchQueNetworkException`, `TouchQueRejectedException`,
600
+ `TouchQueTimeoutException`, `TouchQueWebhookSignatureException`,
601
+ `TouchQueConfigException`.
602
+
603
+ A feature your organization cannot use here raises a `TouchQueFeatureException` (still a `TouchQueAPIException`, status 403) with `feature` (`device_risk`, `ai_agents`…) and `feature_reason`: `TouchQueFeatureNotInPlanException`, `TouchQueFeatureReadOnlyException` or `TouchQueFeatureOffException` — 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.
604
+
605
+ ## Security
606
+
607
+ - Every API request is signed HMAC-SHA256 (method, path+query, timestamp, nonce, body hash).
608
+ - The `X-TouchQue-Token` a frontend echoes back is itself signed and bound to
609
+ one user + action + transaction digest.
610
+ - An approval is consumed exactly once, server-side.
611
+ - Your API secret never leaves your server.
612
+
613
+ See [SECURITY.md](./SECURITY.md) to report a vulnerability.
614
+
615
+ ## Requirements
616
+
617
+ - Python 3.7+
618
+ - A [TouchQue Dashboard](https://dashboard.touchque.com) account
619
+
620
+ ## Logging
621
+
622
+ The SDK's own problems (a misconfigured guard, a failed `on_challenge`, a relay error) go to `logging.getLogger('touchque')`, which has a `NullHandler`: nothing is printed until your app configures logging (`logging.basicConfig()`, or a handler on `'touchque'`). Lines carry an error's class and message, never the request.
623
+
624
+ ## License
625
+
626
+ MIT © [TouchQue](https://touchque.com)
627
+
628
+ ## TouchQue Login (hosted sign-in)
629
+
630
+ Sign-up and sign-in pages for your own customers, on your brand, with OpenID Connect. See [support.touchque.com/touchque-login](https://support.touchque.com/touchque-login) for this SDK's client and a quickstart.