formist-cli 0.1.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.
formist_cli/login.py ADDED
@@ -0,0 +1,615 @@
1
+ """`fm login` - the CLI as an OAuth client of the authorization server.
2
+
3
+ This file implements no protocol of its own: the authorization server used
4
+ here is the same one an MCP connector uses, and the CLI is just another
5
+ registered client of it. It is a textbook RFC 8252 native-app client:
6
+
7
+ 1. Discover: ``GET {api}/.well-known/oauth-authorization-server``. One
8
+ request that also produces the only honest error message when a
9
+ deployment has no authorization server mounted (see
10
+ :class:`LoginError` on ``MCP_OAUTH_ENABLED``).
11
+ 2. Register: DCR (RFC 7591) as a public client,
12
+ ``token_endpoint_auth_method = "none"``, because a client distributed
13
+ on PyPI has no secret it could keep. Registration happens per login
14
+ because the loopback port is ephemeral and redirect URIs must match
15
+ exactly.
16
+ 3. Authorize: open ``{authorization_endpoint}`` in a browser. The user
17
+ signs in with the ordinary product login.
18
+ 4. Receive the code: the browser is redirected to
19
+ ``http://127.0.0.1:<ephemeral>/callback``; or, with ``--no-browser``,
20
+ to a page on the API that displays the code for the user to paste.
21
+ 5. Exchange: ``POST {token_endpoint}`` with the PKCE verifier, form-encoded.
22
+
23
+ Three local defences, none of which a server can provide:
24
+
25
+ * The verifier never leaves this process. Whoever ends up holding the code
26
+ (a local process watching the loopback port, a human reading a screen)
27
+ cannot exchange it. This is what makes the paste mode survivable at all.
28
+ * The listener is one-shot, on 127.0.0.1, on an ephemeral port, and is
29
+ closed before the exchange.
30
+ * ``state`` is checked in both modes: in the loopback mode it stops another
31
+ local process answering the listener; in the paste mode it stops a code
32
+ from somebody else's authorization from being pasted into this terminal.
33
+ The manual page prints ``code:state`` for exactly this.
34
+
35
+ There is no ``--token`` flag. The one non-interactive credential path is the
36
+ ``$EVANE_TOKEN`` environment variable, for CI and other unattended callers
37
+ that cannot complete a browser flow. Its value must be a token `fm login`
38
+ itself minted, an opaque bearer value; a value shaped like a pasted browser
39
+ session token is refused rather than silently accepted
40
+ (:func:`formist_cli.tokens.env_token`). It is read fresh from the
41
+ environment on every invocation and never written to disk, so a leaked
42
+ shell environment leaks one process's credential rather than a file that
43
+ outlives the process. It is never refreshed by `fm` itself: an expired CI
44
+ token fails loudly and must be re-issued by whoever owns it. It carries
45
+ whatever scopes it was issued with, unchanged, so a non-admin token still
46
+ gets the server's ``fm login --admin`` refusal.
47
+ """
48
+
49
+ from __future__ import annotations
50
+
51
+ import base64
52
+ import hashlib
53
+ import http.server
54
+ import platform
55
+ import secrets
56
+ import socket
57
+ import sys
58
+ import threading
59
+ import urllib.parse
60
+ import webbrowser
61
+
62
+ from formist_cli import api, tokens
63
+ from formist_cli.targets import REGION_AE, Target, TargetError, resolve
64
+
65
+ #: How long the loopback listener waits before falling back to "paste the code".
66
+ CALLBACK_TIMEOUT_SECONDS = 300
67
+
68
+ #: RFC 8414 discovery. The SDK mounts it; a deployment with the authorization
69
+ #: server switched off does not, which is the distinction :func:`discover` reports.
70
+ DISCOVERY_PATH = "/.well-known/oauth-authorization-server"
71
+
72
+ _CALLBACK_PATH = "/callback"
73
+
74
+ _DONE_PAGE = """<!doctype html><meta charset="utf-8">
75
+ <title>{product} CLI connected</title>
76
+ <body style="font:16px system-ui;margin:4rem auto;max-width:32rem;text-align:center">
77
+ <h1 style="font-size:1.25rem">{product} CLI connected</h1>
78
+ <p>You can close this window and go back to your terminal.</p>
79
+ </body>"""
80
+
81
+ _FAIL_PAGE = """<!doctype html><meta charset="utf-8">
82
+ <title>{product} CLI</title>
83
+ <body style="font:16px system-ui;margin:4rem auto;max-width:32rem;text-align:center">
84
+ <h1 style="font-size:1.25rem">That did not come from your terminal</h1>
85
+ <p>The authorization did not match the request this machine started.
86
+ Close this window and run <code>fm login</code> again.</p>
87
+ </body>"""
88
+
89
+
90
+ class LoginError(Exception):
91
+ """A refusal or failure during login. The message is written for a human."""
92
+
93
+
94
+ # --- PKCE ----------------------------------------------------------------------
95
+ def generate_pkce() -> tuple[str, str]:
96
+ """``(verifier, challenge)`` for PKCE S256 (RFC 7636).
97
+
98
+ 96 random bytes produce 128 base64url characters, the maximum the RFC
99
+ allows: there is no reason to pick anything smaller for a value that
100
+ lives for one exchange inside one process.
101
+ """
102
+ verifier = base64.urlsafe_b64encode(secrets.token_bytes(96)).rstrip(b"=").decode()
103
+ challenge = (
104
+ base64.urlsafe_b64encode(hashlib.sha256(verifier.encode()).digest())
105
+ .rstrip(b"=")
106
+ .decode()
107
+ )
108
+ return verifier, challenge
109
+
110
+
111
+ def device_label() -> str:
112
+ """A human-recognisable name for this machine, shown on the consent screen and
113
+ in Settings > Connected apps, so "revoke the one from the old laptop" is
114
+ something a person can actually do."""
115
+ host = ""
116
+ try:
117
+ host = socket.gethostname().split(".")[0]
118
+ except OSError:
119
+ pass
120
+ system = platform.system() or "unknown"
121
+ return f"{host} - {system}" if host else f"fm on {system}"
122
+
123
+
124
+ #: Fallback when `fm` is not running from an installed distribution, which is
125
+ #: every run out of a git checkout.
126
+ _UNPACKAGED_VERSION = "dev"
127
+
128
+
129
+ def cli_version() -> str:
130
+ """The `fm` build that asked for a credential, recorded on the registered client
131
+ so an old one can be spotted in Settings > Connected apps and revoked.
132
+
133
+ Read from the package's own metadata, not from an environment variable:
134
+ a version an operator can set is a version that can lie, and the only
135
+ thing this field is for is telling the truth about what is installed.
136
+ `importlib.metadata` is the one source that cannot disagree with the
137
+ code actually running.
138
+
139
+ Falls back to ``"dev"`` when there is no distribution to ask, which is every run
140
+ from a git checkout. Stdlib only, so it carries no extra dependency.
141
+ """
142
+ from importlib.metadata import PackageNotFoundError, version
143
+
144
+ for dist in ("formist-cli",):
145
+ try:
146
+ return version(dist)
147
+ except PackageNotFoundError:
148
+ continue
149
+ except Exception: # noqa: BLE001 - a broken metadata dir must not break login
150
+ break
151
+ return _UNPACKAGED_VERSION
152
+
153
+
154
+ def client_version() -> str:
155
+ return f"fm/{cli_version()}"
156
+
157
+
158
+ # --- the loopback listener -------------------------------------------------------
159
+ class _Callback:
160
+ """A one-shot 127.0.0.1 listener that captures ``?code=&state=`` exactly once.
161
+
162
+ Not a context manager by accident: `fm login` closes this socket before the
163
+ token exchange, so a failure in the exchange cannot leave a port open on a
164
+ developer's machine waiting for anything at all.
165
+ """
166
+
167
+ def __init__(self, product: str = "") -> None:
168
+ #: The product the page names ("<product> CLI connected"), from the
169
+ #: target (:func:`target_product_name`), not from whatever product
170
+ #: this checkout runs as.
171
+ self.product = product or target_product_name(None)
172
+ self.code: str | None = None
173
+ self.state: str | None = None
174
+ self._event = threading.Event()
175
+ outer = self
176
+
177
+ class Handler(http.server.BaseHTTPRequestHandler):
178
+ def do_GET(self): # noqa: N802 - BaseHTTPRequestHandler's spelling
179
+ parsed = urllib.parse.urlparse(self.path)
180
+ params = urllib.parse.parse_qs(parsed.query)
181
+ code = (params.get("code") or [""])[0]
182
+ state = (params.get("state") or [""])[0]
183
+ ok = parsed.path == _CALLBACK_PATH and bool(code)
184
+ body = (_DONE_PAGE if ok else _FAIL_PAGE).format(product=outer.product).encode()
185
+ self.send_response(200 if ok else 400)
186
+ self.send_header("Content-Type", "text/html; charset=utf-8")
187
+ self.send_header("Content-Length", str(len(body)))
188
+ self.send_header("Cache-Control", "no-store")
189
+ self.end_headers()
190
+ self.wfile.write(body)
191
+ if ok:
192
+ outer.code, outer.state = code, state
193
+ outer._event.set()
194
+
195
+ def log_message(self, *args): # keep the terminal clean
196
+ return
197
+
198
+ self._server = http.server.HTTPServer(("127.0.0.1", 0), Handler)
199
+ self.port: int = self._server.server_address[1]
200
+ self._thread = threading.Thread(target=self._server.serve_forever, daemon=True)
201
+ self._thread.start()
202
+
203
+ @property
204
+ def redirect_uri(self) -> str:
205
+ return f"http://127.0.0.1:{self.port}{_CALLBACK_PATH}"
206
+
207
+ def wait(self, timeout: float) -> bool:
208
+ return self._event.wait(timeout)
209
+
210
+ def close(self) -> None:
211
+ try:
212
+ self._server.shutdown()
213
+ self._server.server_close()
214
+ except OSError:
215
+ pass
216
+
217
+
218
+ # --- where login talks to ---------------------------------------------------------
219
+ def auth_target(target: Target) -> Target:
220
+ """The target the login itself is performed against (also used for the
221
+ token refresh and the ``/auth/me`` lookup).
222
+
223
+ Evane's AE region has no authorization server of its own: the user
224
+ tables live in Global, which serves the auth surface for it. So
225
+ `fm login --env ae` signs in against ``api.evane.ai``; the credential
226
+ then works at ``ae.api.evane.ai`` unchanged, because the OAuth token is
227
+ looked up across regions rather than being bound to the database that
228
+ issued it.
229
+
230
+ Only ``ae`` maps to Global. Every other target, including ``global``,
231
+ ``local``, and a standalone product deployment such as ``formist``
232
+ (its own database, its own user tables, its own authorization server
233
+ at ``api.formist.ai``), authenticates against itself.
234
+ """
235
+ if target.env == REGION_AE:
236
+ return resolve("evane")
237
+ return target
238
+
239
+
240
+ def discover(auth: Target) -> dict:
241
+ """The authorization server's RFC 8414 metadata, or a LoginError that says why.
242
+
243
+ The likeliest failure here is not a network one: a deployment can have
244
+ the authorization server switched off entirely (``MCP_OAUTH_ENABLED``),
245
+ which serves no ``/authorize``, no ``/token`` and no ``/register`` and
246
+ produces a 404 on discovery. A bare "404" would send an operator
247
+ looking for a typo in a URL this file constructed correctly, so this
248
+ says the real thing instead.
249
+ """
250
+ try:
251
+ payload = api.get(auth, DISCOVERY_PATH)
252
+ except api.ApiError as exc:
253
+ if getattr(exc, "status", None) == 404:
254
+ raise LoginError(
255
+ f"{auth.api_base} is not serving an OAuth authorization server.\n"
256
+ "`fm login` signs in through the same OAuth flow an MCP "
257
+ "connector uses, and that server is mounted only when "
258
+ "MCP_OAUTH_ENABLED is set. It is set in every deployment; a "
259
+ "local dev server needs `MCP_OAUTH_ENABLED=1` in its environment.\n"
260
+ f"(Checked {auth.api_base}{DISCOVERY_PATH}.)"
261
+ ) from exc
262
+ raise LoginError(f"could not read the authorization server metadata: {exc}") from exc
263
+ if not isinstance(payload, dict):
264
+ raise LoginError(f"unexpected discovery document: {payload!r}")
265
+ for key in ("authorization_endpoint", "token_endpoint", "registration_endpoint"):
266
+ if not payload.get(key):
267
+ raise LoginError(
268
+ f"the authorization server at {auth.api_base} advertises no "
269
+ f"{key}, so `fm login` cannot complete. Dynamic client registration "
270
+ "is required (RFC 7591)."
271
+ )
272
+ return payload
273
+
274
+
275
+ def _path_of(auth: Target, url: str) -> str:
276
+ """An absolute endpoint URL reduced to a path on ``auth``.
277
+
278
+ Discovery returns absolute URLs. They must be sent through
279
+ ``formist_cli.api`` (host allow-list, error translation) rather than
280
+ opened directly, and the refusal has to happen here if the metadata
281
+ names another host: a discovery document is attacker-influenceable in
282
+ exactly the way an allow-list exists for.
283
+ """
284
+ parsed = urllib.parse.urlparse(url)
285
+ if not parsed.netloc:
286
+ return url if url.startswith("/") else f"/{url}"
287
+ base = urllib.parse.urlparse(auth.api_base)
288
+ if (parsed.scheme, parsed.netloc) != (base.scheme, base.netloc):
289
+ raise LoginError(
290
+ f"the authorization server metadata points at {parsed.scheme}://"
291
+ f"{parsed.netloc}, which is not {auth.api_base}. Refusing to follow it."
292
+ )
293
+ return parsed.path or "/"
294
+
295
+
296
+ # --- the flow ---------------------------------------------------------------------
297
+ def target_product_name(target: Target | None) -> str:
298
+ """The product a target deployment is ("Formist" for ``--host formist``,
299
+ "Evane" for ``global``/``ae``). A local/override target (or none) is
300
+ whatever product this checkout runs as.
301
+
302
+ The client name a CLI registers is shown on the deployment's own
303
+ consent screen and Settings > Connected apps, so it must be that
304
+ deployment's product, never the local checkout's default.
305
+ """
306
+ return (getattr(target, "product", None) or "fm") if target is not None else "fm"
307
+
308
+
309
+ def register_client(auth: Target, meta: dict, redirect_uris: list[str], scopes: list[str]) -> dict:
310
+ """Register this `fm` as a public OAuth client (RFC 7591), named after the
311
+ product of the deployment it registers with (:func:`target_product_name`)."""
312
+ from formist_cli import privileges
313
+
314
+ body = {
315
+ "client_name": f"{target_product_name(auth)} CLI - {device_label()}",
316
+ "redirect_uris": redirect_uris,
317
+ "grant_types": ["authorization_code", "refresh_token"],
318
+ "response_types": ["code"],
319
+ "token_endpoint_auth_method": "none",
320
+ "scope": " ".join(scopes),
321
+ "software_id": privileges.CLI_SOFTWARE_ID,
322
+ "software_version": client_version(),
323
+ }
324
+ payload = api.post(auth, _path_of(auth, meta["registration_endpoint"]), body)
325
+ if not isinstance(payload, dict) or not payload.get("client_id"):
326
+ raise LoginError(f"client registration failed: {payload!r}")
327
+ return payload
328
+
329
+
330
+ def authorize_url(auth: Target, meta: dict, *, client_id: str, redirect_uri: str,
331
+ challenge: str, state: str, scopes: list[str]) -> str:
332
+ query = urllib.parse.urlencode(
333
+ {
334
+ "response_type": "code",
335
+ "client_id": client_id,
336
+ "redirect_uri": redirect_uri,
337
+ "state": state,
338
+ "code_challenge": challenge,
339
+ "code_challenge_method": "S256",
340
+ "scope": " ".join(scopes),
341
+ }
342
+ )
343
+ return f"{auth.api_base.rstrip('/')}{_path_of(auth, meta['authorization_endpoint'])}?{query}"
344
+
345
+
346
+ def exchange(auth: Target, meta: dict, *, client_id: str, code: str,
347
+ redirect_uri: str, verifier: str) -> dict:
348
+ payload = api.post_form(
349
+ auth,
350
+ _path_of(auth, meta["token_endpoint"]),
351
+ {
352
+ "grant_type": "authorization_code",
353
+ "code": code,
354
+ "redirect_uri": redirect_uri,
355
+ "client_id": client_id,
356
+ "code_verifier": verifier,
357
+ },
358
+ )
359
+ if not isinstance(payload, dict) or not payload.get("access_token"):
360
+ raise LoginError(f"the token exchange returned no access token: {payload!r}")
361
+ return payload
362
+
363
+
364
+ def refresh(auth: Target, meta: dict, *, client_id: str, refresh_token: str) -> dict:
365
+ """Trade a refresh token for a fresh pair. The access token is short-lived
366
+ (``MCP_OAUTH_ACCESS_TTL``, 1h) while the refresh token lasts ~30 days, so this
367
+ is what stops `fm` asking for a browser every hour."""
368
+ payload = api.post_form(
369
+ auth,
370
+ _path_of(auth, meta["token_endpoint"]),
371
+ {
372
+ "grant_type": "refresh_token",
373
+ "refresh_token": refresh_token,
374
+ "client_id": client_id,
375
+ },
376
+ )
377
+ if not isinstance(payload, dict) or not payload.get("access_token"):
378
+ raise LoginError(f"the refresh exchange returned no access token: {payload!r}")
379
+ return payload
380
+
381
+
382
+ def _prompt_code(url: str, state: str) -> str:
383
+ print("", file=sys.stderr)
384
+ print("Open this page and sign in:", file=sys.stderr)
385
+ print(f" {url}", file=sys.stderr)
386
+ print("", file=sys.stderr)
387
+ print("The page will show a code of the form <code>:<state>", file=sys.stderr)
388
+ print(f"its state must be {state}", file=sys.stderr)
389
+ print("If it is not, that page belongs to somebody else's login. Refuse it.", file=sys.stderr)
390
+ print("", file=sys.stderr)
391
+ try:
392
+ return input("Paste the code from the page: ").strip()
393
+ except (EOFError, KeyboardInterrupt):
394
+ raise LoginError("cancelled") from None
395
+
396
+
397
+ def _split_pasted(pasted: str) -> tuple[str, str]:
398
+ """``code:state`` as the manual page prints it. A bare code is accepted,
399
+ and the state check simply cannot run; the caller says so out loud."""
400
+ if ":" in pasted:
401
+ code, _, state = pasted.rpartition(":")
402
+ return code.strip(), state.strip()
403
+ return pasted.strip(), ""
404
+
405
+
406
+ def perform_login(
407
+ env: str | None, *, no_browser: bool = False, admin: bool = False
408
+ ) -> dict:
409
+ """Perform the whole flow. Returns ``{**token_response, "client_id": ...}``.
410
+
411
+ Not called ``run``: every module in this package that binds a top-level
412
+ ``run`` means "this is a subcommand's entry point", and this module is
413
+ not one (``cli.py::cmd_login`` is).
414
+
415
+ Storing is the caller's job (``cli.py::cmd_login``), so this can be
416
+ exercised end to end without writing to anybody's config directory.
417
+ """
418
+ from formist_cli.privileges import SCOPE_ADMIN, SCOPE_CLI, SCOPE_KB
419
+
420
+ target = env if isinstance(env, Target) else resolve(env)
421
+ auth = auth_target(target)
422
+ meta = discover(auth)
423
+
424
+ scopes = [SCOPE_KB, SCOPE_CLI] + ([SCOPE_ADMIN] if admin else [])
425
+ verifier, challenge = generate_pkce()
426
+ state = secrets.token_urlsafe(24)
427
+
428
+ callback = None
429
+ if not no_browser:
430
+ try:
431
+ callback = _Callback()
432
+ callback.product = target_product_name(auth)
433
+ except OSError:
434
+ # No loopback socket available (a locked-down box, a sandbox). Not a
435
+ # failure: it is exactly the case --no-browser exists for.
436
+ callback = None
437
+
438
+ manual_uri = f"{auth.api_base.rstrip('/')}/oauth/cli/code"
439
+ redirect_uri = callback.redirect_uri if callback else manual_uri
440
+ # BOTH are registered even when only one is used: the loopback listener can time
441
+ # out and fall back to the paste flow, and re-registering mid-login would mean a
442
+ # second client row and a second authorize hop for the same human.
443
+ redirect_uris = [manual_uri] if callback is None else [callback.redirect_uri, manual_uri]
444
+
445
+ try:
446
+ client = register_client(auth, meta, redirect_uris, scopes)
447
+ url = authorize_url(
448
+ auth, meta, client_id=str(client["client_id"]), redirect_uri=redirect_uri,
449
+ challenge=challenge, state=state, scopes=scopes,
450
+ )
451
+
452
+ code = ""
453
+ if callback is not None:
454
+ print(f"Opening {url}", file=sys.stderr)
455
+ opened = False
456
+ try:
457
+ opened = webbrowser.open(url)
458
+ except Exception: # noqa: BLE001 - a headless box raises all sorts
459
+ opened = False
460
+ if not opened:
461
+ print("Could not open a browser. Open the URL above yourself.", file=sys.stderr)
462
+ if callback.wait(CALLBACK_TIMEOUT_SECONDS):
463
+ if (callback.state or "") != state:
464
+ raise LoginError(
465
+ "the callback's state did not match this login. Something "
466
+ "else answered the loopback port; nothing was exchanged."
467
+ )
468
+ code = callback.code or ""
469
+ else:
470
+ print("", file=sys.stderr)
471
+ print(
472
+ "No callback received. If the page finished but nothing came "
473
+ "back, the browser could not reach this machine's loopback "
474
+ "port. Paste the code from the page instead:",
475
+ file=sys.stderr,
476
+ )
477
+ pasted, pasted_state = _split_pasted(_prompt_code(url, state))
478
+ _check_state(pasted_state, state)
479
+ code, redirect_uri = pasted, redirect_uri
480
+ else:
481
+ pasted, pasted_state = _split_pasted(_prompt_code(url, state))
482
+ _check_state(pasted_state, state)
483
+ code = pasted
484
+
485
+ if not code:
486
+ raise LoginError("no authorization code received")
487
+ finally:
488
+ # Closed before the exchange, unconditionally: a failure in the exchange
489
+ # must not leave a listening socket behind.
490
+ if callback is not None:
491
+ callback.close()
492
+
493
+ tokens_payload = exchange(
494
+ auth, meta, client_id=str(client["client_id"]), code=code,
495
+ redirect_uri=redirect_uri, verifier=verifier,
496
+ )
497
+ tokens_payload["client_id"] = str(client["client_id"])
498
+ tokens_payload["client_name"] = str(client.get("client_name") or "")
499
+ return tokens_payload
500
+
501
+
502
+ def _check_state(got: str, expected: str) -> None:
503
+ """Refuse a pasted code whose state is not ours; say so when there is none.
504
+
505
+ A missing state is not treated as a failure (the user may have copied
506
+ only the first half), but it is not treated as a pass either: the check
507
+ that would have caught a phished code did not run, and the operator is
508
+ told, because a security control that silently did not happen is worse
509
+ than one that is absent.
510
+ """
511
+ if not got:
512
+ print(
513
+ " the pasted value carried no state, so `fm` could not check that "
514
+ "this code came from the page it opened.",
515
+ file=sys.stderr,
516
+ )
517
+ return
518
+ if got != expected:
519
+ raise LoginError(
520
+ "that code came from a different authorization request. Nothing was "
521
+ "exchanged. Run `fm login` again and use the page it opens."
522
+ )
523
+
524
+
525
+ def store_payload(
526
+ env: str, payload: dict, *, client_id: str, client_name: str | None = None
527
+ ) -> str:
528
+ """Persist a token response at 0600 and return the access token to use now.
529
+
530
+ The one place a token response becomes a file, called by both `fm login`
531
+ and the transparent token refresh. Two copies of "which fields go on
532
+ disk" is how a refresh ends up dropping the ``client_id`` that the next
533
+ refresh needs, a failure that appears 30 days later as "please log in
534
+ again" with no explanation.
535
+
536
+ ``expires_in`` is turned into an absolute ``expires_at`` here. A
537
+ duration is only meaningful next to the instant it was measured from,
538
+ and that instant is now; storing the duration would make every later
539
+ reader re-derive it from a file mtime, which is not the same thing.
540
+ """
541
+ from datetime import datetime, timedelta, timezone
542
+
543
+ now = datetime.now(timezone.utc)
544
+ try:
545
+ lifetime = int(payload.get("expires_in") or 0)
546
+ except (TypeError, ValueError):
547
+ lifetime = 0
548
+ meta = {
549
+ "client_id": client_id,
550
+ "client_name": client_name or payload.get("client_name") or "",
551
+ "scopes": str(payload.get("scope") or "").split(),
552
+ "grant_id": payload.get("grant_id"),
553
+ "obtained_at": now.isoformat(),
554
+ "expires_at": (now + timedelta(seconds=lifetime)).isoformat() if lifetime else None,
555
+ }
556
+ refresh_token = payload.get("refresh_token")
557
+ if refresh_token:
558
+ meta["refresh_token"] = str(refresh_token)
559
+ access = str(payload["access_token"])
560
+ tokens.store(env, access, meta)
561
+ return access
562
+
563
+
564
+ def token_metadata(payload: dict) -> dict:
565
+ """The non-secret facts about a token response, for printing."""
566
+ return {
567
+ "client_id": payload.get("client_id"),
568
+ "client_name": payload.get("client_name"),
569
+ "scopes": str(payload.get("scope") or "").split(),
570
+ "expires_in": payload.get("expires_in"),
571
+ }
572
+
573
+
574
+ def list_apps(target: Target, token: str) -> list[dict]:
575
+ """The caller's connected apps, as the server sees them."""
576
+ payload = api.get(auth_target(target), "/auth/apps", token=token)
577
+ if isinstance(payload, dict) and isinstance(payload.get("apps"), list):
578
+ return [a for a in payload["apps"] if isinstance(a, dict)]
579
+ return []
580
+
581
+
582
+ def revoke(target: Target, token: str, grant_id: str | None) -> bool:
583
+ """Revoke a grant SERVER-SIDE. True if the server confirmed.
584
+
585
+ Best-effort by design: `fm logout` must still delete the local file when the
586
+ server is unreachable, or an offline laptop would keep a credential it believes
587
+ it has thrown away. The caller says which happened.
588
+ """
589
+ if not grant_id:
590
+ return False
591
+ try:
592
+ payload = api.post(
593
+ auth_target(target), "/auth/apps/revoke", {"grant_id": grant_id}, token=token
594
+ )
595
+ except (api.ApiError, TargetError, OSError):
596
+ return False
597
+ return isinstance(payload, dict) and bool(payload.get("ok"))
598
+
599
+
600
+ __all__ = [
601
+ "CALLBACK_TIMEOUT_SECONDS",
602
+ "LoginError",
603
+ "auth_target",
604
+ "device_label",
605
+ "discover",
606
+ "exchange",
607
+ "generate_pkce",
608
+ "list_apps",
609
+ "refresh",
610
+ "register_client",
611
+ "revoke",
612
+ "perform_login",
613
+ "store_payload",
614
+ "token_metadata",
615
+ ]