maximem-synap-cli 0.3.5__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.
@@ -0,0 +1,1277 @@
1
+ """`maximem-synap auth ...` — gcloud-style login, logout, and account switching."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json as _json
6
+ import os
7
+ import re
8
+ import socket
9
+ import sys
10
+ import time
11
+ import webbrowser
12
+ from urllib.parse import urlsplit
13
+ from datetime import datetime, timedelta, timezone
14
+ from typing import Optional
15
+
16
+ import typer
17
+
18
+ from synap.cli import interactive, render
19
+ from synap.cli.api import (
20
+ EXIT_AUTH, EXIT_CONFLICT, EXIT_REVOCATION_PENDING, EXIT_SERVER, EXIT_TIMEOUT, EXIT_USAGE,
21
+ ApiClient, CliError,
22
+ )
23
+ from synap.cli.config import DEFAULT_PROFILE, Profile, dashboard_base, dashboard_urls, environments
24
+
25
+ app = typer.Typer(no_args_is_help=True)
26
+
27
+
28
+ def _ctx(ctx: typer.Context):
29
+ return ctx.obj
30
+
31
+
32
+ def _mask_key(key: Optional[str]) -> str:
33
+ if not key:
34
+ return "—"
35
+ return f"{key[:10]}…{key[-4:]}" if len(key) > 16 else "synap_…"
36
+
37
+
38
+ def _repoint_warning(
39
+ profile_name: str,
40
+ existing_api_base: Optional[str],
41
+ target: str,
42
+ *,
43
+ explicit: bool,
44
+ exists: bool,
45
+ ) -> Optional[str]:
46
+ """Warn when `auth login` will silently ignore/overwrite a profile's server.
47
+
48
+ `login` always targets the default (prod) unless `--env`/`--api-base` is
49
+ given, so logging into a staging/custom profile without those flags would
50
+ quietly repoint it. Say so, so it's a choice and not a surprise.
51
+ """
52
+ if explicit or not exists:
53
+ return None
54
+ if existing_api_base and existing_api_base != target:
55
+ return (
56
+ f"Profile '{profile_name}' is configured for {existing_api_base}, but "
57
+ f"login targets {target} and will repoint it. Pass --env/--api-base "
58
+ f"to log into a different server."
59
+ )
60
+ return None
61
+
62
+
63
+ def _slug(name: Optional[str]) -> str:
64
+ """Workspace name to a profile name: lowercase a-z0-9-, at most 30 chars."""
65
+ slug = re.sub(r"[^a-z0-9]+", "-", (name or "").lower()).strip("-")
66
+ return slug[:30].strip("-")
67
+
68
+
69
+ def _norm_env(env: Optional[str]) -> str:
70
+ env = (env or "").strip().lower()
71
+ return "production" if env == "prod" else env
72
+
73
+
74
+ def _env_note(environment: str) -> str:
75
+ """", staging" for a non-production environment, "" for production.
76
+
77
+ Customers only ever see Synap, so production is never named in human output.
78
+ """
79
+ return f", {environment}" if environment and environment != "production" else ""
80
+
81
+
82
+ def _env_paren(environment: str) -> str:
83
+ return f" ({environment})" if _env_note(environment) else ""
84
+
85
+
86
+ def _profile_env(p: Profile) -> str:
87
+ return _norm_env(_environment_label(p.api_base, p.runtime))
88
+
89
+
90
+ def _same_target(p: Profile, client_id: Optional[str], environment: str) -> bool:
91
+ return bool(p.api_key) and bool(client_id) and p.client_id == client_id \
92
+ and _profile_env(p) == environment
93
+
94
+
95
+ def _session_profile_name(store, workspace_name: Optional[str], client_id, session_id: str) -> str:
96
+ """``<workspace>-onboarding-<first 6 of the session id>``, at most 30 characters.
97
+
98
+ One name per session, so a second agent's login in the same workspace on the
99
+ same machine can never replace the first one's key, and either logout ends
100
+ only its own."""
101
+ short = "".join(ch for ch in session_id.lower() if ch.isalnum())[:6] or "session"
102
+ suffix = f"-onboarding-{short}"
103
+ base = (_slug(workspace_name) or "workspace")[: 30 - len(suffix)].rstrip("-") or "ws"
104
+ name = base + suffix
105
+ n = 1
106
+ while store.has_profile(name) and store.get_profile(name).api_key:
107
+ n += 1
108
+ extra = f"-{n}"
109
+ name = (base + suffix)[: 30 - len(extra)] + extra
110
+ return name
111
+
112
+
113
+ def _pick_profile_name(cc, client_id, environment, workspace_name, *, force: bool,
114
+ onboarding: bool = False, session_id: Optional[str] = None):
115
+ """Choose the profile a login writes to without clobbering another workspace.
116
+
117
+ Returns (name, in_place). An explicit --profile always means that name: it
118
+ is refused (exit 6) when it holds a different workspace or environment,
119
+ unless force. Without one, the same workspace+environment is updated in
120
+ place, otherwise a new name is derived from the workspace.
121
+
122
+ An onboarding-code login (``onboarding=True``) only ever updates a profile
123
+ that already holds an onboarding key. It never replaces a normal renewable
124
+ profile of the same workspace with a 7-day non-renewable key: that one goes
125
+ under a separate ``<workspace>-onboarding`` name instead.
126
+ """
127
+ store = cc.store
128
+ if cc.profile_explicit:
129
+ name = cc.profile_name
130
+ existing = store.get_profile(name)
131
+ if not store.has_profile(name) or not existing.api_key:
132
+ return name, False
133
+ if _same_target(existing, client_id, environment):
134
+ if onboarding and existing.key_origin != ONBOARDING_KEY_ORIGIN and not force:
135
+ raise CliError(
136
+ f"Profile '{name}' holds a normal renewable key for workspace "
137
+ f"'{existing.client_name or existing.client_id}'; this onboarding login "
138
+ f"would replace it with a 7-day key that cannot be renewed. Nothing was changed.",
139
+ code="profile_conflict", exit_code=EXIT_CONFLICT,
140
+ hint="Omit `--profile` (the onboarding key is then stored under its own "
141
+ "profile), pick another name, or pass `--force` to replace it.",
142
+ )
143
+ return name, True
144
+ if force:
145
+ return name, False
146
+ raise CliError(
147
+ f"Profile '{name}' already exists for workspace "
148
+ f"'{existing.client_name or existing.client_id or 'unknown'}'"
149
+ f"{_env_paren(_profile_env(existing))}; "
150
+ f"this login is for workspace '{workspace_name or client_id}'"
151
+ f"{_env_paren(environment)}. Nothing was changed.",
152
+ code="profile_conflict", exit_code=EXIT_CONFLICT,
153
+ hint=f"Pass `--force` to overwrite profile '{name}', pick another name with "
154
+ f"`--profile <name>`, or omit `--profile` to name it after the workspace.",
155
+ )
156
+ if onboarding and session_id:
157
+ # A session is one pasted prompt: it gets its own profile, always.
158
+ return _session_profile_name(store, workspace_name, client_id, session_id), False
159
+ names = store.profile_names()
160
+ matches = [n for n in names if _same_target(store.get_profile(n), client_id, environment)]
161
+ base = _slug(workspace_name) or "workspace"
162
+ if onboarding:
163
+ # Keep a renewable profile; only refresh an earlier onboarding profile.
164
+ matches = [n for n in matches
165
+ if store.get_profile(n).key_origin == ONBOARDING_KEY_ORIGIN]
166
+ if not matches and any(_same_target(store.get_profile(n), client_id, environment)
167
+ for n in names):
168
+ base = (base[: 30 - len("-onboarding")].rstrip("-") + "-onboarding")
169
+ if matches:
170
+ active = store.default_profile
171
+ return (active if active in matches else matches[0]), True
172
+ name, n = base, 1
173
+ while store.has_profile(name) and store.get_profile(name).api_key:
174
+ n += 1
175
+ suffix = f"-{n}"
176
+ name = base[: 30 - len(suffix)].rstrip("-") + suffix
177
+ return name, False
178
+
179
+
180
+ def _finish_login(cc, name, profile, *, agent: bool, workspace: str, environment: str) -> Optional[str]:
181
+ """Save the profile and decide which profile is active. Returns the previous
182
+ active profile's name when it was left behind or replaced, else None."""
183
+ store = cc.store
184
+ prev = store.default_profile
185
+ prev_profile = store.get_profile(prev) if store.has_profile(prev) else None
186
+ had_active = bool(prev_profile and prev_profile.api_key)
187
+ if agent:
188
+ # Remember who was active so `auth logout` can hand the slot back. A
189
+ # repeat code login on the same profile keeps the first answer.
190
+ if had_active and prev != name:
191
+ profile.previous_profile = prev
192
+ elif prev == name and prev_profile is not None:
193
+ profile.previous_profile = prev_profile.previous_profile
194
+ store.set_profile(name, profile)
195
+ other = prev if (had_active and prev != name) else None
196
+ same_client = bool(prev_profile and prev_profile.client_id
197
+ and prev_profile.client_id == profile.client_id)
198
+ if agent or not had_active or same_client or prev == name:
199
+ store.default_profile = name
200
+ activated = True
201
+ else:
202
+ activated = False
203
+ store.save()
204
+ if other and activated and not same_client:
205
+ render.warn(
206
+ f"Your previous active profile was '{other}'. Profile '{name}' is active now. "
207
+ f"To switch back run `maximem-synap auth use {other}`, or pass `--profile {other}`."
208
+ )
209
+ elif other and not activated:
210
+ render.warn(
211
+ f"Logged in as profile {name} (workspace {workspace}{_env_note(environment)}). "
212
+ f"Your active profile is still {other}. Use `--profile {name}` on each command, "
213
+ f"or run `maximem-synap auth use {name}` to switch."
214
+ )
215
+ cc.profile_name = name if activated else cc.profile_name
216
+ return other
217
+
218
+
219
+ @app.command()
220
+ def login(
221
+ ctx: typer.Context,
222
+ no_browser: bool = typer.Option(
223
+ False, "--no-browser",
224
+ help="Don't auto-open the browser; print the URL and code to stderr and wait for "
225
+ "approval from any device. Works without a terminal (agents, ssh, CI) and never "
226
+ "prompts. Also enabled by SYNAP_LOGIN_NO_BROWSER=1.",
227
+ ),
228
+ code: Optional[str] = typer.Option(
229
+ None, "--code",
230
+ help="One-time onboarding code from the dashboard (syn_ob_...); no browser. "
231
+ "Also read from SYNAP_ONBOARDING_CODE.",
232
+ ),
233
+ agent_name: Optional[str] = typer.Option(
234
+ None, "--agent-name",
235
+ help="Name of the coding agent signing in (shown on the dashboard). "
236
+ "Also read from SYNAP_AGENT_NAME.",
237
+ ),
238
+ force: bool = typer.Option(
239
+ False, "--force",
240
+ help="With --profile NAME: overwrite NAME even if it belongs to another "
241
+ "workspace or environment.",
242
+ ),
243
+ purpose: str = typer.Option(
244
+ "login", "--purpose",
245
+ help="`login` (default) or `onboarding`: a browser approval that hands the agent the "
246
+ "one-time setup prompt and code (stdout), then exits. Stores no profile; the agent "
247
+ "then runs `auth login --code`.",
248
+ ),
249
+ email: Optional[str] = typer.Option(
250
+ None, "--email", help="With --purpose onboarding: the email the human should sign in with (a hint).",
251
+ ),
252
+ source: Optional[str] = typer.Option(
253
+ None, "--source", help="With --purpose onboarding: short label of where this came from "
254
+ "(lowercase letters, digits, - and _; at most 30).",
255
+ ),
256
+ ) -> None:
257
+ """Log in via the browser (device pairing), or with `--code` (no browser).
258
+
259
+ With `--no-browser` the URL and short code go to stderr (with `-o json`, also one JSON
260
+ line on stderr: {"event": "pairing_started", "verification_uri_complete": ..., "code": ...,
261
+ "expires_at": ...}); stdout carries only the final result. Waits up to ~10 minutes.
262
+ """
263
+ cc = _ctx(ctx)
264
+ no_browser = no_browser or os.getenv(NO_BROWSER_ENV, "").strip().lower() in ("1", "true", "yes", "on")
265
+ profile_name = cc.profile_name
266
+ api_base = cc.login_api_base()
267
+
268
+ purpose = (purpose or "login").strip().lower()
269
+ if purpose not in ("login", "onboarding"):
270
+ raise CliError("--purpose must be `login` or `onboarding`.", code="invalid_purpose", exit_code=EXIT_USAGE)
271
+ if purpose == "login" and (email or source):
272
+ raise CliError("--email and --source only apply with --purpose onboarding.",
273
+ code="invalid_option", exit_code=EXIT_USAGE)
274
+ if purpose == "onboarding":
275
+ if code or os.getenv(ONBOARDING_CODE_ENV):
276
+ raise CliError("--purpose onboarding cannot be combined with --code.",
277
+ code="invalid_option", exit_code=EXIT_USAGE)
278
+ _login_onboarding_pairing(
279
+ cc, api_base, agent_name or os.getenv("SYNAP_AGENT_NAME") or None, email, source,
280
+ )
281
+ return
282
+
283
+ onboarding_code = (code or os.getenv(ONBOARDING_CODE_ENV) or "").strip()
284
+ if onboarding_code:
285
+ _login_with_code(
286
+ cc, api_base, onboarding_code,
287
+ agent_name or os.getenv("SYNAP_AGENT_NAME") or None, force,
288
+ )
289
+ return
290
+
291
+ if interactive.is_non_interactive() and not no_browser:
292
+ # Without a terminal and without --no-browser, nobody is told where to approve,
293
+ # so fail fast instead of hanging ~10 min. --no-browser opts in to waiting.
294
+ raise CliError(
295
+ "No onboarding code given, and the browser login cannot run non-interactively.",
296
+ code="onboarding_code_required", exit_code=EXIT_AUTH,
297
+ hint="Pass `--code <code>` or set SYNAP_ONBOARDING_CODE (ask the human for a "
298
+ "fresh prompt; it contains a new one-time code), or pass `--no-browser` to "
299
+ "print a URL and code that a human approves from another device.",
300
+ )
301
+
302
+ client = ApiClient(api_base, verbose=cc.verbose)
303
+
304
+ hostname = socket.gethostname() or "cli"
305
+
306
+ # 1. Start a pairing session.
307
+ start = client.post(
308
+ "/cli/pair/start", auth=False, json={"hostname": hostname},
309
+ )
310
+ code = start["code"]
311
+ poll_token = start["poll_token"]
312
+ verify_url = start["verification_uri_complete"]
313
+ interval = int(start.get("interval", 2))
314
+
315
+ # 2. Show the code + open the browser. All interactive chatter goes to
316
+ # stderr so stdout stays clean for `--output json` (and pipes/CI).
317
+ render.err_console.print()
318
+ render.err_console.print(f" Your pairing code is: [bold cyan]{code}[/bold cyan]")
319
+ render.err_console.print(f" Approve this login at: [underline]{verify_url}[/underline]")
320
+ render.err_console.print()
321
+ if no_browser and render.is_json():
322
+ sys.stderr.write(_json.dumps({
323
+ "event": "pairing_started", "verification_uri_complete": verify_url,
324
+ "code": code, "expires_at": start.get("expires_at"),
325
+ }) + "\n")
326
+ sys.stderr.flush()
327
+ opened = False
328
+ if not no_browser:
329
+ try:
330
+ opened = webbrowser.open(verify_url)
331
+ except Exception:
332
+ opened = False
333
+ if opened:
334
+ render.err_console.print(" [dim]Opened your browser. Confirm the code matches, then approve.[/dim]")
335
+ else:
336
+ render.err_console.print(" [dim]Open the URL above in your browser to approve.[/dim]")
337
+ render.err_console.print()
338
+
339
+ # 3. Poll until approved / denied / expired.
340
+ expires_at = _parse_dt(start.get("expires_at"))
341
+ with render.err_console.status("[bold]Waiting for approval…", spinner="dots"):
342
+ result = _poll(client, code, poll_token, interval, expires_at)
343
+
344
+ # 4. Look up the workspace, then pick a profile that clobbers nobody.
345
+ api_key = result["api_key"]
346
+ try:
347
+ me = ApiClient(api_base, api_key, verbose=cc.verbose).get("/whoami")
348
+ except CliError:
349
+ me = None
350
+ client_id = result.get("client_id") or (me or {}).get("client_id")
351
+ client_name = (me or {}).get("client_name")
352
+ environment = _norm_env(_environment_label(api_base, None))
353
+ cc.store.reload() # minutes may have passed waiting for the approval
354
+ profile_name, _in_place = _pick_profile_name(
355
+ cc, client_id, environment, client_name, force=force,
356
+ )
357
+ profile = Profile()
358
+ profile.api_base = api_base
359
+ profile.api_key = api_key
360
+ profile.api_key_expires_at = result.get("expires_at")
361
+ profile.api_key_issued_at = _now_iso()
362
+ profile.client_id = client_id
363
+ profile.client_name = client_name
364
+ profile.scopes = result.get("scopes")
365
+ workspace = client_name or client_id
366
+ previous = _finish_login(
367
+ cc, profile_name, profile, agent=False, workspace=workspace, environment=environment,
368
+ )
369
+ active = cc.store.default_profile
370
+
371
+ render.success(
372
+ f"Logged in to client [bold]{workspace}[/bold] · profile [bold]{profile_name}[/bold]"
373
+ )
374
+ if render.is_json():
375
+ render.print_json({
376
+ "profile": profile_name,
377
+ "client_id": profile.client_id,
378
+ "client_name": profile.client_name,
379
+ "workspace": workspace,
380
+ "environment": environment,
381
+ "scopes": profile.scopes,
382
+ "expires_at": profile.api_key_expires_at,
383
+ "active": active == profile_name,
384
+ "previous_active_profile": previous,
385
+ })
386
+
387
+
388
+ ONBOARDING_CODE_ENV = "SYNAP_ONBOARDING_CODE"
389
+ NO_BROWSER_ENV = "SYNAP_LOGIN_NO_BROWSER"
390
+ ONBOARDING_KEY_ORIGIN = "onboarding-code"
391
+ RENEWABLE_WARN_WINDOW = timedelta(days=14)
392
+
393
+ _NOT_RENEWABLE = (
394
+ "This key cannot be renewed. Ask the developer for a fresh prompt from the "
395
+ "dashboard (it carries a new one-time code), then run "
396
+ "`maximem-synap auth login --code <code>`."
397
+ )
398
+
399
+ _CODE_HINT = (
400
+ "Copy a fresh prompt from the dashboard (Connect your coding agent). "
401
+ "Codes work once and expire after 10 minutes. A code is only known to the region that "
402
+ "created it: if the dashboard was opened from a different network than this machine "
403
+ "(VPN, cloud IDE, ssh), open the dashboard from this machine's network and copy the prompt again."
404
+ )
405
+
406
+
407
+ def _normalise_code(code: str) -> str:
408
+ """Accept the code in any letter case: prefix lowercase, body uppercase."""
409
+ code = (code or "").strip()
410
+ prefix = "syn_ob_"
411
+ if code.lower().startswith(prefix):
412
+ return prefix + code[len(prefix):].upper()
413
+ return code
414
+
415
+
416
+ def _revoke_fresh_key(api_base: str, api_key: str, verbose: bool) -> bool:
417
+ """Best-effort self-revoke of a key that was minted but will not be saved."""
418
+ try:
419
+ c = ApiClient(api_base, api_key, verbose=verbose)
420
+ cred_id = (c.get("/whoami") or {}).get("credential_id")
421
+ if not cred_id:
422
+ return False
423
+ c.delete(f"/api_keys/{cred_id}")
424
+ return True
425
+ except Exception:
426
+ return False
427
+
428
+
429
+ def _login_with_code(cc, api_base: str, code: str, agent_name: Optional[str],
430
+ force: bool = False) -> None:
431
+ """Exchange a one-time onboarding code for a key and store it like browser login.
432
+
433
+ The code is never printed or logged, and is kept out of error messages.
434
+ """
435
+ code = _normalise_code(code)
436
+ if not code.startswith("syn_ob_"):
437
+ raise CliError(
438
+ "That does not look like an onboarding code (expected syn_ob_XXXX-XXXX-XXXX).",
439
+ code="invalid_onboarding_code", exit_code=EXIT_USAGE, hint=_CODE_HINT,
440
+ )
441
+ client = ApiClient(api_base, verbose=cc.verbose)
442
+ body = {"code": code, "hostname": socket.gethostname() or "cli"}
443
+ if agent_name:
444
+ body["agent_name"] = agent_name
445
+ try:
446
+ result = client.post("/cli/onboard/exchange", auth=False, json=body)
447
+ except CliError as e:
448
+ # The server answers wrong, expired and used identically. Say one thing.
449
+ if e.status_code is not None and e.status_code in (400, 401, 403, 404, 410, 422):
450
+ raise CliError(
451
+ "The onboarding code is invalid, expired or already used.",
452
+ status_code=e.status_code, code="invalid_onboarding_code",
453
+ exit_code=EXIT_AUTH, hint=_CODE_HINT,
454
+ )
455
+ raise
456
+ if not isinstance(result, dict) or not result.get("api_key"):
457
+ raise CliError(
458
+ "The server returned no key for that code.",
459
+ code="invalid_onboarding_code", exit_code=EXIT_AUTH, hint=_CODE_HINT,
460
+ )
461
+
462
+ runtime = result.get("runtime")
463
+ runtime = runtime if isinstance(runtime, dict) else None
464
+ environment = _norm_env(_environment_label(api_base, runtime))
465
+ workspace = result.get("workspace_name") or result.get("client_id")
466
+ # The exchange took a network round trip. Another terminal may have logged in
467
+ # meanwhile (two agents started together); pick the name from, and save over,
468
+ # the file as it is NOW, not the copy read at start-up.
469
+ cc.store.reload()
470
+ try:
471
+ profile_name, _in_place = _pick_profile_name(
472
+ cc, result.get("client_id"), environment, result.get("workspace_name"), force=force,
473
+ onboarding=True, session_id=result.get("session_id"),
474
+ )
475
+ except CliError as e:
476
+ if e.code != "profile_conflict":
477
+ raise
478
+ # The target workspace is only known after the exchange, so the code is
479
+ # already spent. Revoke the key it minted and say exactly that.
480
+ revoked = _revoke_fresh_key(api_base, result["api_key"], cc.verbose)
481
+ key_line = ("The key it created was revoked." if revoked else
482
+ "The key it created could not be revoked automatically; it expires on its own.")
483
+ raise CliError(
484
+ f"{e.message.replace(' Nothing was changed.', '')} The one-time code was used "
485
+ f"and nothing was saved. {key_line}",
486
+ code="profile_conflict", exit_code=EXIT_CONFLICT,
487
+ hint="Get a fresh code, then sign in again with `--force` to overwrite the profile, "
488
+ "a different `--profile <name>`, or no `--profile` to store it under its own name.",
489
+ detail={"code_consumed": True, "key_revoked": revoked},
490
+ )
491
+ profile = Profile()
492
+ profile.api_base = api_base
493
+ profile.api_key = result["api_key"]
494
+ profile.api_key_expires_at = result.get("expires_at")
495
+ profile.api_key_issued_at = _now_iso()
496
+ profile.client_id = result.get("client_id")
497
+ profile.client_name = result.get("workspace_name")
498
+ profile.scopes = result.get("scopes")
499
+ profile.key_origin = ONBOARDING_KEY_ORIGIN
500
+ profile.runtime = runtime
501
+ profile.session_id = result.get("session_id")
502
+ profile.tool_name = agent_name
503
+ # Other setup sessions already saved for this workspace on this machine.
504
+ siblings = [
505
+ n for n in cc.store.profile_names()
506
+ if n != profile_name and cc.store.get_profile(n).session_id
507
+ and cc.store.get_profile(n).client_id == profile.client_id
508
+ and cc.store.get_profile(n).is_logged_in()
509
+ ]
510
+ # The onboarding agent runs later commands without --profile, so a code
511
+ # login always becomes active; the previous one is named loudly.
512
+ previous = _finish_login(
513
+ cc, profile_name, profile, agent=True, workspace=workspace, environment=environment,
514
+ )
515
+
516
+ render.success(
517
+ f"Logged in to workspace [bold]{workspace}[/bold] "
518
+ f"· profile [bold]{profile_name}[/bold]"
519
+ + (f" · environment [bold]{environment}[/bold] ({api_base})"
520
+ if environment and environment != "production" else "")
521
+ )
522
+ pin_note = (
523
+ f"Pin this session: add `--profile {profile_name}` to every command, or run "
524
+ f"`export SYNAP_PROFILE={profile_name}` in a shell that persists."
525
+ )
526
+ if siblings:
527
+ render.warn(
528
+ f"Another setup session is saved on this machine for this workspace ({', '.join(siblings)}). "
529
+ f"{pin_note} Never log out or delete a profile that is not yours."
530
+ )
531
+ elif not render.is_json():
532
+ render.info(f"[dim]{pin_note}[/dim]")
533
+ if render.is_json():
534
+ out = {
535
+ "profile": profile_name,
536
+ "session_id": profile.session_id,
537
+ "pin": {"flag": f"--profile {profile_name}", "env": f"SYNAP_PROFILE={profile_name}"},
538
+ "other_session_profiles": siblings,
539
+ "client_id": profile.client_id,
540
+ "client_name": profile.client_name,
541
+ "workspace": workspace,
542
+ "environment": environment,
543
+ "scopes": profile.scopes,
544
+ "expires_at": profile.api_key_expires_at,
545
+ "active": True,
546
+ "previous_active_profile": previous,
547
+ }
548
+ if profile.runtime:
549
+ out["api_base"] = api_base
550
+ render.print_json(out)
551
+
552
+
553
+ ONBOARDING_POLL_PATH = "/api/v1/management/cli/pair/poll"
554
+ _PAIR_CODE_RE = re.compile(r"^[A-HJKMNP-Z2-9]{4}-[A-HJKMNP-Z2-9]{4}$")
555
+ _SOURCE_RE = re.compile(r"^[a-z0-9_-]{1,30}$")
556
+ _EMAIL_RE = re.compile(r"^[^@\s<>]+@[^@\s<>]+\.[^@\s<>]+$")
557
+ # The longest a setup pairing is waited for even if the server says otherwise (server TTL is 30 minutes).
558
+ ONBOARDING_WAIT_CAP = timedelta(minutes=35)
559
+ _POLL_TOLERATED_FAILURES = 10
560
+
561
+
562
+ def _origin(url) -> tuple:
563
+ port = url.port or (443 if url.scheme == "https" else 80 if url.scheme == "http" else None)
564
+ return (url.scheme, (url.hostname or "").lower(), port)
565
+
566
+
567
+ def _expected_dashboard(api_base: str) -> str:
568
+ """The dashboard base URL for THIS environment, from the CLI's own configuration.
569
+
570
+ Known environments use the built-in mapping only. A custom server (local, self-hosted)
571
+ has none, so the human must name it with SYNAP_DASHBOARD_URL; it is never read from the
572
+ server's reply."""
573
+ known = (api_base or "").rstrip("/") in dashboard_urls()
574
+ base = dashboard_base(api_base) if known else (os.getenv("SYNAP_DASHBOARD_URL") or "").strip().rstrip("/")
575
+ if not base:
576
+ raise CliError(
577
+ f"The CLI does not know which dashboard belongs to {api_base}, so it cannot check the approval link.",
578
+ code="dashboard_host_unknown", exit_code=EXIT_USAGE,
579
+ hint="Set SYNAP_DASHBOARD_URL to this server's dashboard address (for example "
580
+ "https://synap-staging.maximem.ai), or use --env prod or --env staging.",
581
+ )
582
+ return base
583
+
584
+
585
+ def _refuse_server_reply(why: str) -> CliError:
586
+ return CliError(
587
+ f"The server's pairing reply was refused: {why}. Nothing was started and nothing was sent.",
588
+ code="pairing_refused", exit_code=EXIT_AUTH,
589
+ hint="Do not show the human any link from this reply. Tell them the sign-in could not be "
590
+ "started safely, and stop.",
591
+ )
592
+
593
+
594
+ def _checked_poll_target(api_base: str, poll_url: Optional[str]) -> tuple:
595
+ """(origin, path) to poll. The poll token is only ever sent to the API host we were
596
+ configured for, or, for the built-in environments, another *.maximem.ai host over https
597
+ (the region that issued the code)."""
598
+ if not poll_url or not isinstance(poll_url, str):
599
+ raise _refuse_server_reply("it carries no poll_url, so this server cannot start a setup sign-in")
600
+ u, b = urlsplit(poll_url), urlsplit(api_base)
601
+ if u.username or u.password or u.query or u.fragment or u.path != ONBOARDING_POLL_PATH:
602
+ raise _refuse_server_reply("poll_url is not the pairing poll endpoint")
603
+ known = (api_base or "").rstrip("/") in dashboard_urls()
604
+ sibling = known and u.scheme == "https" and u.port in (None, 443) and (u.hostname or "").lower().endswith(".maximem.ai")
605
+ if _origin(u) != _origin(b) and not sibling:
606
+ raise _refuse_server_reply("poll_url points at a host this CLI is not configured for")
607
+ return f"{u.scheme}://{u.netloc}", u.path
608
+
609
+
610
+ def _login_onboarding_pairing(cc, api_base: str, agent_name: Optional[str], email: Optional[str],
611
+ source: Optional[str]) -> None:
612
+ """`auth login --purpose onboarding`: browser approval -> the dashboard's setup prompt.
613
+
614
+ Never opens a browser (the human does, with the link printed here). On approval the poll
615
+ returns a one-time code and the dashboard's own prompt; both go to stdout and the command
616
+ exits 0 with NO profile and NO key stored. The agent then follows the prompt, which runs
617
+ `auth login --code <code>` exactly as the dashboard flow does. The printed link is built
618
+ from the configured dashboard host, and the server's reply is refused if it names another.
619
+ """
620
+ email = (email or "").strip() or None
621
+ source = (source or "").strip() or None
622
+ if email and (len(email) > 254 or not _EMAIL_RE.match(email)):
623
+ raise CliError("--email must look like an email address.", code="invalid_option", exit_code=EXIT_USAGE)
624
+ if source and not _SOURCE_RE.match(source):
625
+ raise CliError("--source may use lowercase letters, digits, - and _ (at most 30).",
626
+ code="invalid_option", exit_code=EXIT_USAGE)
627
+ dashboard = _expected_dashboard(api_base)
628
+ client = ApiClient(api_base, verbose=cc.verbose)
629
+ body = {"purpose": "onboarding", "hostname": socket.gethostname() or "cli"}
630
+ if agent_name:
631
+ body["tool_name"] = agent_name[:60]
632
+ if email:
633
+ body["login_hint"] = email
634
+ if source:
635
+ body["source"] = source
636
+ try:
637
+ start = client.post("/cli/pair/start", auth=False, json=body)
638
+ except CliError as e:
639
+ detail = e.detail if isinstance(e.detail, dict) else {}
640
+ if e.status_code == 503 and detail.get("error") in (
641
+ "onboarding_pairing_not_enabled", "onboarding_pairing_unavailable"):
642
+ # Not retried: the server said it does not offer this, so asking again changes nothing.
643
+ raise CliError(
644
+ "Setup sign-in is not available on this server yet. Nothing was started.",
645
+ status_code=503, detail=detail, code="onboarding_pairing_not_enabled", exit_code=EXIT_SERVER,
646
+ hint="Do not retry in a loop. Tell the human it is not available yet.",
647
+ )
648
+ raise
649
+ if not isinstance(start, dict):
650
+ raise _refuse_server_reply("it was not a JSON object")
651
+ code, poll_token = start.get("code"), start.get("poll_token")
652
+ if not isinstance(code, str) or not _PAIR_CODE_RE.match(code) or not isinstance(poll_token, str) or not poll_token:
653
+ raise _refuse_server_reply("the code or poll token is missing or malformed")
654
+ # The link the server named must be on the dashboard this CLI is configured for. What we
655
+ # print is built from our own configuration, never copied from the reply.
656
+ named = urlsplit(str(start.get("verification_uri_complete") or ""))
657
+ want = urlsplit(dashboard)
658
+ if (_origin(named) != _origin(want) or named.username or named.password
659
+ or named.path != "/cli/pair" or named.query != f"code={code}"):
660
+ raise _refuse_server_reply(
661
+ f"its approval link is not on this environment's dashboard ({want.hostname})")
662
+ poll_origin, poll_path = _checked_poll_target(api_base, start.get("poll_url"))
663
+ verify_url = f"{dashboard}/cli/pair?code={code}"
664
+ interval = max(1, int(start.get("interval", 2) or 2))
665
+
666
+ render.err_console.print()
667
+ render.err_console.print(f" Your pairing code is: [bold cyan]{code}[/bold cyan]")
668
+ render.err_console.print(f" Approve this setup at: [underline]{verify_url}[/underline]")
669
+ render.err_console.print(
670
+ " [dim]Open the link, sign in or sign up, check that the code matches, then click Approve once.[/dim]")
671
+ render.err_console.print()
672
+ if render.is_json():
673
+ sys.stderr.write(_json.dumps({
674
+ "event": "pairing_started", "purpose": "onboarding", "verification_uri_complete": verify_url,
675
+ "code": code, "expires_at": start.get("expires_at"),
676
+ }) + "\n")
677
+ sys.stderr.flush()
678
+
679
+ deadline = min(
680
+ (_parse_dt(start.get("expires_at")) or datetime.now(timezone.utc) + timedelta(minutes=30)) + timedelta(seconds=5),
681
+ datetime.now(timezone.utc) + ONBOARDING_WAIT_CAP,
682
+ )
683
+ poller = ApiClient(poll_origin, verbose=cc.verbose)
684
+ failures = 0
685
+ with render.err_console.status("[bold]Waiting for approval…", spinner="dots"):
686
+ while True:
687
+ if datetime.now(timezone.utc).timestamp() > deadline.timestamp():
688
+ raise CliError(
689
+ "Setup sign-in timed out before it was approved. Nothing was stored.",
690
+ code="pairing_timeout", exit_code=EXIT_TIMEOUT,
691
+ hint="Run `maximem-synap auth login --purpose onboarding` again for a new link.",
692
+ )
693
+ try:
694
+ result = poller.get(poll_path, auth=False, prefix="",
695
+ params={"code": code, "poll_token": poll_token})
696
+ failures = 0
697
+ except CliError as e:
698
+ if e.status_code == 403:
699
+ if "token_mismatch" in (e.message or ""):
700
+ raise CliError("Pairing token mismatch. Run the login command again.",
701
+ code="pairing_failed", exit_code=EXIT_AUTH)
702
+ if "no_longer_authorised" in (e.message or ""):
703
+ raise CliError("The person who approved this setup is no longer an owner or admin of the "
704
+ "workspace, so nothing was issued. Run the login command again.",
705
+ code="pairing_failed", exit_code=EXIT_AUTH)
706
+ raise CliError("The setup was denied in the browser.", code="pairing_failed", exit_code=EXIT_AUTH)
707
+ if e.status_code == 404:
708
+ raise CliError("The setup link expired. Run the login command again.",
709
+ code="pairing_failed", exit_code=EXIT_AUTH)
710
+ if e.status_code == 410:
711
+ raise CliError("This setup link was already used.", code="pairing_failed", exit_code=EXIT_AUTH)
712
+ # Busy server, rate limit or a network blip during a 30 minute wait: keep waiting.
713
+ if e.status_code is not None and e.status_code < 500 and e.status_code != 429:
714
+ raise
715
+ failures += 1
716
+ if failures > _POLL_TOLERATED_FAILURES:
717
+ raise
718
+ time.sleep(max(interval, 10) if e.status_code == 429 else interval)
719
+ continue
720
+ if isinstance(result, dict) and result.get("status") == "confirmed":
721
+ break
722
+ time.sleep(interval)
723
+
724
+ one_time, prompt = result.get("code"), result.get("prompt")
725
+ if not isinstance(one_time, str) or not one_time or not isinstance(prompt, str) or not prompt:
726
+ raise CliError(
727
+ "The server approved the setup but returned no setup prompt.",
728
+ code="pairing_failed", exit_code=EXIT_AUTH,
729
+ hint="Run `maximem-synap auth login --purpose onboarding` again.",
730
+ )
731
+ # Nothing is stored: there is no key yet. The prompt's own `auth login --code` creates the profile.
732
+ if render.is_json():
733
+ render.print_json({
734
+ "prompt": prompt, "code": one_time, "client_id": result.get("client_id"),
735
+ "expires_at": result.get("expires_at"),
736
+ })
737
+ else:
738
+ print(prompt)
739
+ print(f"Code: {one_time}")
740
+
741
+
742
+ def _poll(client: ApiClient, code: str, poll_token: str, interval: int, expires_at):
743
+ """Poll the pair endpoint until a terminal state. Returns the confirmed body."""
744
+ deadline = None
745
+ if expires_at is not None:
746
+ deadline = expires_at.timestamp() + 5
747
+ while True:
748
+ if deadline and time.time() > deadline:
749
+ raise CliError(
750
+ "Pairing timed out. Re-run `maximem-synap auth login`.",
751
+ code="pairing_timeout", exit_code=EXIT_TIMEOUT,
752
+ )
753
+ try:
754
+ body = client.get(
755
+ "/cli/pair/poll", auth=False,
756
+ params={"code": code, "poll_token": poll_token},
757
+ )
758
+ except CliError as e:
759
+ if e.status_code == 403:
760
+ # 403 covers both an explicit deny and a poll_token mismatch;
761
+ # only the former is a user action.
762
+ if "token_mismatch" in (e.message or ""):
763
+ raise CliError(
764
+ "Pairing token mismatch — re-run `maximem-synap auth login`.", code="pairing_failed", exit_code=EXIT_AUTH,
765
+ )
766
+ raise CliError("Login was denied in the browser.", code="pairing_failed", exit_code=EXIT_AUTH)
767
+ if e.status_code == 404:
768
+ raise CliError("Pairing expired. Re-run `maximem-synap auth login`.", code="pairing_failed", exit_code=EXIT_AUTH)
769
+ if e.status_code == 410:
770
+ raise CliError("This pairing code was already used.", code="pairing_failed", exit_code=EXIT_AUTH)
771
+ raise
772
+ if isinstance(body, dict) and body.get("status") == "confirmed":
773
+ return body
774
+ time.sleep(interval)
775
+
776
+
777
+ @app.command()
778
+ def activate(
779
+ ctx: typer.Context,
780
+ api_key: str = typer.Option(
781
+ ..., "--key", "-k",
782
+ help="An existing synap_ API key to store (no browser — for CI/servers).",
783
+ ),
784
+ ) -> None:
785
+ """Log in with an existing API key — no browser (CI/servers).
786
+
787
+ Validates the key against the server, then stores it under the active
788
+ profile exactly like `auth login`. For ephemeral CI, prefer the
789
+ `SYNAP_API_KEY` env var instead (no file written).
790
+ """
791
+ cc = _ctx(ctx)
792
+ profile_name = cc.profile_name or DEFAULT_PROFILE
793
+ api_base = cc.login_api_base()
794
+
795
+ # Validate + enrich via whoami; an invalid key surfaces a clean error here.
796
+ me = ApiClient(api_base, api_key, verbose=cc.verbose).get("/whoami")
797
+
798
+ profile = cc.store.get_profile(profile_name)
799
+ profile.api_base = api_base
800
+ profile.api_key = api_key
801
+ profile.client_id = me.get("client_id")
802
+ profile.client_name = me.get("client_name")
803
+ profile.scopes = me.get("scopes")
804
+ profile.api_key_expires_at = me.get("expires_at")
805
+ profile.api_key_issued_at = _now_iso()
806
+ profile.key_origin = me.get("origin")
807
+ profile.runtime = None
808
+ cc.store.set_profile(profile_name, profile)
809
+ cc.store.default_profile = profile_name
810
+ cc.store.save()
811
+
812
+ render.success(
813
+ f"Activated key for client [bold]{me.get('client_name') or me.get('client_id')}[/bold] "
814
+ f"· profile [bold]{profile_name}[/bold]."
815
+ )
816
+ if render.is_json():
817
+ render.print_json({
818
+ "profile": profile_name,
819
+ "client_id": profile.client_id,
820
+ "client_name": profile.client_name,
821
+ "scopes": profile.scopes,
822
+ "expires_at": profile.api_key_expires_at,
823
+ })
824
+
825
+
826
+ @app.command()
827
+ def refresh(ctx: typer.Context) -> None:
828
+ """Renew the active key before it expires — no browser.
829
+
830
+ Not available for onboarding keys (from `login --code`): they last 7 days
831
+ and then a fresh prompt is needed. Mints a fresh key with the same scopes and revokes the current one, then
832
+ updates the stored profile. Must run while the current key is still valid.
833
+ """
834
+ cc = _ctx(ctx)
835
+ if os.getenv("SYNAP_API_KEY"):
836
+ raise CliError(
837
+ "`auth refresh` can't run with SYNAP_API_KEY set — it can't update the "
838
+ "env var. Unset it and refresh a stored profile, or mint a new key."
839
+ )
840
+ profile_name = cc.profile_name
841
+ if not cc.active_profile().is_logged_in():
842
+ raise CliError(
843
+ "Not logged in.",
844
+ code="not_authenticated", exit_code=EXIT_AUTH,
845
+ hint="Ask the human for a fresh onboarding prompt, then run "
846
+ "`maximem-synap auth login --code <code>`.",
847
+ )
848
+
849
+ try:
850
+ resp = cc.client().post("/auth/refresh")
851
+ except CliError as e:
852
+ detail = e.detail if isinstance(e.detail, dict) else {}
853
+ if e.status_code == 403 and detail.get("error") == "onboarding_key_not_refreshable":
854
+ # Remember it, so later warnings stop suggesting a renewal.
855
+ profile = cc.store.get_profile(profile_name)
856
+ profile.key_origin = ONBOARDING_KEY_ORIGIN
857
+ cc.store.set_profile(profile_name, profile)
858
+ cc.store.save()
859
+ raise CliError(
860
+ detail.get("message") or "This key cannot be renewed.",
861
+ status_code=403, detail=detail,
862
+ code="onboarding_key_not_refreshable", exit_code=EXIT_AUTH,
863
+ hint=detail.get("hint") or _NOT_RENEWABLE,
864
+ )
865
+ raise
866
+
867
+ profile = cc.store.get_profile(profile_name)
868
+ profile.key_origin = "cli-refresh"
869
+ profile.api_key = resp["api_key"]
870
+ profile.api_key_expires_at = resp.get("expires_at")
871
+ profile.api_key_issued_at = _now_iso()
872
+ profile.scopes = resp.get("scopes")
873
+ profile.client_id = resp.get("client_id")
874
+ cc.store.set_profile(profile_name, profile)
875
+ cc.store.save()
876
+
877
+ render.success(f"Key refreshed for profile [bold]{profile_name}[/bold].")
878
+ render.print_detail({
879
+ "credential_id": resp.get("credential_id"),
880
+ "scopes": resp.get("scopes"),
881
+ "expires_at": resp.get("expires_at"),
882
+ })
883
+
884
+
885
+ _ISOLATION_MODES = {"equals_customer": "b2c", "strict": "b2b", "b2c": "b2c", "b2b": "b2b"}
886
+
887
+
888
+ def _isolation_mode(raw) -> Optional[str]:
889
+ if not raw or not isinstance(raw, str):
890
+ return None
891
+ return _ISOLATION_MODES.get(raw.strip().lower(), raw.strip())
892
+
893
+
894
+ def _find_isolation(data) -> Optional[str]:
895
+ """user_context_isolation from a whoami/instance body, top level or in its config.
896
+
897
+ An instance body from the server carries no isolation mode, only the instance's declared
898
+ ``user_relationship`` (b2c or b2b), which is what the mode falls back to. A mode set in a
899
+ config always wins over the relationship.
900
+ """
901
+ if not isinstance(data, dict):
902
+ return None
903
+ found = _find_isolation_mode(data)
904
+ if found:
905
+ return found
906
+ meta = data.get("metadata")
907
+ relationship = data.get("user_relationship") or (
908
+ meta.get("user_relationship") if isinstance(meta, dict) else None)
909
+ if isinstance(relationship, str) and relationship.strip().lower() in ("b2c", "b2b"):
910
+ return relationship.strip().lower()
911
+ return None
912
+
913
+
914
+ def _find_isolation_mode(data) -> Optional[str]:
915
+ if not isinstance(data, dict):
916
+ return None
917
+ for src in (data, data.get("config"), data.get("instance")):
918
+ if isinstance(src, dict):
919
+ if src.get("user_context_isolation"):
920
+ return _isolation_mode(src["user_context_isolation"])
921
+ scoping = (src.get("storage_architecture") or {}).get("scoping") \
922
+ if isinstance(src.get("storage_architecture"), dict) else None
923
+ if isinstance(scoping, dict) and scoping.get("user_context_isolation"):
924
+ return _isolation_mode(scoping["user_context_isolation"])
925
+ cfg = src.get("config")
926
+ if isinstance(cfg, dict):
927
+ found = _find_isolation_mode(cfg)
928
+ if found:
929
+ return found
930
+ return None
931
+
932
+
933
+ def _user_context_isolation(cc, me: dict) -> str:
934
+ """b2c or b2b from /whoami; else from the one instance in scope; else 'unknown'."""
935
+ found = _find_isolation(me)
936
+ if found:
937
+ return found
938
+ instance_id = (me or {}).get("instance_id")
939
+ if instance_id: # the key is scoped to exactly one instance
940
+ try:
941
+ found = _find_isolation(cc.client().get(f"/instances/{instance_id}"))
942
+ except CliError:
943
+ found = None
944
+ if found:
945
+ return found
946
+ return "unknown"
947
+
948
+
949
+ @app.command()
950
+ def whoami(ctx: typer.Context) -> None:
951
+ """Show which account/client the active profile is logged into."""
952
+ cc = _ctx(ctx)
953
+ me = cc.client().get("/whoami")
954
+ detail = {
955
+ "profile": cc.profile_name,
956
+ "client_name": me.get("client_name"),
957
+ "client_id": me.get("client_id"),
958
+ "scopes": me.get("scopes"),
959
+ "credential_id": me.get("credential_id"),
960
+ "expires_at": me.get("expires_at"),
961
+ "origin": me.get("origin"),
962
+ "user_context_isolation": _user_context_isolation(cc, me),
963
+ "environment": _environment_label(cc.api_base(), cc.active_profile().runtime),
964
+ "api_base": cc.api_base(),
965
+ }
966
+ if not render.is_machine() and detail["environment"] == "production":
967
+ del detail["environment"] # customers just see Synap; JSON/CSV keep the field
968
+ render.print_detail(detail, title="Logged in as")
969
+ issued = None if os.getenv("SYNAP_API_KEY") else cc.active_profile().api_key_issued_at
970
+ profile = cc.active_profile()
971
+ onboarding = (me.get("origin") or (None if os.getenv("SYNAP_API_KEY") else profile.key_origin)) == ONBOARDING_KEY_ORIGIN
972
+ note = _expiry_note(me.get("expires_at"), issued_at=issued, onboarding=onboarding)
973
+ if note:
974
+ render.warn(note)
975
+
976
+
977
+ def _session_label(p: Profile) -> str:
978
+ """``Claude Code -> BillingAgent`` for a setup-session profile, else empty."""
979
+ if not p.session_id:
980
+ return ""
981
+ tool = p.tool_name or "Agent"
982
+ return f"{tool} -> {p.target_agent}" if p.target_agent else f"{tool} (agent not set)"
983
+
984
+
985
+ @app.command(name="list")
986
+ def list_accounts(ctx: typer.Context) -> None:
987
+ """List configured accounts/profiles (active one starred), like `gcloud auth list`."""
988
+ cc = _ctx(ctx)
989
+ active = cc.store.default_profile
990
+ rows = []
991
+ for name in cc.store.profile_names():
992
+ p = cc.store.get_profile(name)
993
+ rows.append({
994
+ "active": "*" if name == active else "",
995
+ "profile": name,
996
+ "client": p.client_name or p.client_id or "—",
997
+ "environment": _profile_env(p),
998
+ "key": _mask_key(p.api_key),
999
+ "api_base": p.api_base,
1000
+ "expires_at": p.api_key_expires_at or "—",
1001
+ "session": _session_label(p),
1002
+ })
1003
+ if not rows:
1004
+ render.info("No accounts yet. Run `maximem-synap auth login --code <code>`.")
1005
+ return
1006
+ columns = [
1007
+ ("active", ""),
1008
+ ("profile", "PROFILE"),
1009
+ ("client", "WORKSPACE"),
1010
+ ("environment", "ENVIRONMENT"),
1011
+ ("key", "KEY"),
1012
+ ("api_base", "SERVER"),
1013
+ ("expires_at", "EXPIRES"),
1014
+ ("session", "SESSION"),
1015
+ ]
1016
+ if not any(r["session"] for r in rows):
1017
+ columns = [c for c in columns if c[0] != "session"]
1018
+ # Production is the default and is never named for customers: the column
1019
+ # appears only when some profile points at a non-production environment.
1020
+ if all(r["environment"] == "production" for r in rows):
1021
+ columns = [c for c in columns if c[0] != "environment"]
1022
+ else:
1023
+ for r in rows:
1024
+ if r["environment"] == "production" and not render.is_machine():
1025
+ r["environment"] = ""
1026
+ render.print_table(rows, columns)
1027
+
1028
+
1029
+ @app.command()
1030
+ def use(ctx: typer.Context, profile: str = typer.Argument(...)) -> None:
1031
+ """Set the active account/profile."""
1032
+ cc = _ctx(ctx)
1033
+ if not cc.store.has_profile(profile):
1034
+ raise CliError(f"No such profile '{profile}'. See `maximem-synap auth list`.")
1035
+ cc.store.default_profile = profile
1036
+ cc.store.save()
1037
+ render.success(f"Active profile is now [bold]{profile}[/bold].")
1038
+
1039
+
1040
+ REVOKE_TRIES = 3
1041
+ REVOKE_TIMEOUT = 10.0
1042
+ REVOKE_BACKOFF = (1.0, 3.0) # seconds slept before try 2 and try 3
1043
+
1044
+
1045
+ def _transient(e: CliError) -> bool:
1046
+ return e.code in ("timeout", "network_error") or (e.status_code or 0) >= 500 \
1047
+ or e.status_code == 429
1048
+
1049
+
1050
+ def _with_retries(fn):
1051
+ """Run fn up to REVOKE_TRIES times, retrying only transient failures."""
1052
+ for attempt in range(REVOKE_TRIES):
1053
+ try:
1054
+ return fn()
1055
+ except CliError as e:
1056
+ if attempt + 1 >= REVOKE_TRIES or not _transient(e):
1057
+ raise
1058
+ time.sleep(REVOKE_BACKOFF[min(attempt, len(REVOKE_BACKOFF) - 1)])
1059
+
1060
+
1061
+ def _revoke_key(client: ApiClient, credential_id: Optional[str]):
1062
+ """Revoke the key the client authenticates with. Returns (done, credential_id, why).
1063
+
1064
+ Idempotent: a 401 (key already dead) or 404 (already revoked) counts as done.
1065
+ ``done`` is ``None`` when the server refuses for good (403 ``missing_scope``: this key
1066
+ may not revoke itself on that server), so retrying can never work.
1067
+ """
1068
+ try:
1069
+ if not credential_id:
1070
+ me = _with_retries(lambda: client.get("/whoami"))
1071
+ credential_id = (me or {}).get("credential_id")
1072
+ if not credential_id:
1073
+ return False, None, "the server did not return the key id"
1074
+ _with_retries(lambda: client.delete(f"/api_keys/{credential_id}"))
1075
+ return True, credential_id, None
1076
+ except CliError as e:
1077
+ if e.status_code in (401, 404):
1078
+ return True, credential_id, None
1079
+ if e.status_code == 403 and isinstance(e.detail, dict) and e.detail.get("error") == "missing_scope":
1080
+ return None, credential_id, e.message
1081
+ return False, credential_id, e.message
1082
+
1083
+
1084
+ @app.command()
1085
+ def logout(ctx: typer.Context) -> None:
1086
+ """Revoke the active profile's key server-side and remove it locally.
1087
+
1088
+ Retries the revoke (3 tries, short timeouts). If the server cannot be
1089
+ reached, the profile is KEPT marked "revocation pending" and the command
1090
+ exits 9; run `auth logout` again to retry. With `-o json`, stdout has
1091
+ `revoked` and `pending`.
1092
+ """
1093
+ cc = _ctx(ctx)
1094
+ profile = cc.active_profile()
1095
+ profile_name = cc.profile_name
1096
+ if not profile.is_logged_in():
1097
+ render.info(f"Profile '{profile_name}' is not logged in.")
1098
+ return
1099
+
1100
+ # Several setup sessions can live on one machine. Without a pinned profile the
1101
+ # active one is merely the LAST login, which may be another agent's: refuse to
1102
+ # guess, so one session can never end another.
1103
+ if not cc.profile_explicit and profile.session_id:
1104
+ others = [
1105
+ n for n in cc.store.profile_names()
1106
+ if n != profile_name and cc.store.get_profile(n).session_id
1107
+ and cc.store.get_profile(n).is_logged_in()
1108
+ ]
1109
+ if others:
1110
+ raise CliError(
1111
+ f"More than one setup session is saved on this machine ({profile_name}, "
1112
+ f"{', '.join(others)}), and no profile is pinned. Nothing was changed.",
1113
+ code="profile_not_pinned", exit_code=EXIT_USAGE,
1114
+ hint=f"Log out of YOUR session explicitly: `maximem-synap auth logout --profile <your profile>` "
1115
+ f"(the profile `auth login --code` printed). See `maximem-synap auth list`.",
1116
+ )
1117
+
1118
+ client = cc.client()
1119
+ client.timeout = REVOKE_TIMEOUT
1120
+ revoked, cred_id, why = _revoke_key(client, profile.credential_id)
1121
+ cc.store.reload() # the revoke retried over several seconds; keep other terminals' changes
1122
+ refused = revoked is None
1123
+ if refused:
1124
+ # The server will not let this key revoke itself, now or on a retry. Keeping the
1125
+ # profile "pending" would only make `auth logout` fail the same way forever, so end
1126
+ # the local login and say plainly that the key is still live.
1127
+ until = profile.api_key_expires_at or "its expiry date"
1128
+ render.warn(
1129
+ f"The server does not allow this key to revoke itself, so it is still active until {until}. "
1130
+ "The local login was removed. To end it sooner, an admin can revoke it in the dashboard "
1131
+ "(API keys page)."
1132
+ )
1133
+ elif not revoked:
1134
+ profile.revocation_pending = True
1135
+ profile.credential_id = cred_id or profile.credential_id
1136
+ cc.store.set_profile(profile_name, profile)
1137
+ cc.store.save()
1138
+ until = profile.api_key_expires_at or "its expiry date (7 days after it was issued)"
1139
+ if render.is_json():
1140
+ render.print_json({
1141
+ "profile": profile_name, "revoked": False, "pending": True,
1142
+ "key_active_until": profile.api_key_expires_at, "credential_id": profile.credential_id,
1143
+ })
1144
+ raise CliError(
1145
+ f"The setup key could NOT be revoked ({why}). It is still active until {until}.",
1146
+ code="revocation_pending", exit_code=EXIT_REVOCATION_PENDING,
1147
+ hint="Run `maximem-synap auth logout` again to retry; the profile was kept so the "
1148
+ "retry can authenticate. Or a human can revoke it now in the dashboard: "
1149
+ "API keys page, find the key and revoke it.",
1150
+ detail={"revoked": False, "pending": True, "key_active_until": profile.api_key_expires_at},
1151
+ )
1152
+
1153
+ previous = profile.previous_profile
1154
+ was_active = cc.store.default_profile == profile_name
1155
+ cc.store.delete_profile(profile_name)
1156
+ restored = None
1157
+ # Only touch the active slot when the profile we removed held it. Then the
1158
+ # profile that was active before the onboarding login comes back; if there
1159
+ # is none, nothing is active (never an alphabetical pick of another workspace).
1160
+ if was_active and previous and cc.store.has_profile(previous) \
1161
+ and cc.store.get_profile(previous).is_logged_in():
1162
+ cc.store.default_profile = previous
1163
+ restored = previous
1164
+ cc.store.save()
1165
+ if refused:
1166
+ render.success(f"Logged out of '{profile_name}' (key NOT revoked).")
1167
+ else:
1168
+ render.success(f"Logged out of '{profile_name}' (key revoked).")
1169
+ if render.is_json():
1170
+ render.print_json({
1171
+ "profile": profile_name, "revoked": not refused, "pending": False,
1172
+ **({"key_active_until": profile.api_key_expires_at, "credential_id": cred_id} if refused else {}),
1173
+ })
1174
+ if restored:
1175
+ render.info(f"Active profile is back to [bold]{restored}[/bold].")
1176
+ elif was_active and not cc.store.default_profile and cc.store.profile_names():
1177
+ render.warn(
1178
+ "No profile is active now. Other saved profiles: "
1179
+ f"{', '.join(cc.store.profile_names())}. Run `maximem-synap auth use <name>` "
1180
+ "or pass `--profile <name>`; commands will not pick one for you."
1181
+ )
1182
+
1183
+
1184
+ @app.command(name="print-access-token")
1185
+ def print_access_token(ctx: typer.Context) -> None:
1186
+ """Print the active profile's API key (for scripts/CI piping)."""
1187
+ cc = _ctx(ctx)
1188
+ env_key = os.getenv("SYNAP_API_KEY")
1189
+ if env_key:
1190
+ print(env_key)
1191
+ return
1192
+ profile = cc.active_profile()
1193
+ if not profile.is_logged_in():
1194
+ raise CliError(
1195
+ "Not logged in. Run `maximem-synap auth login --code <code>`, or set SYNAP_API_KEY.",
1196
+ code="not_authenticated", exit_code=EXIT_AUTH,
1197
+ )
1198
+ # Raw print (no styling) so it pipes cleanly.
1199
+ print(profile.api_key)
1200
+
1201
+
1202
+ def _environment_label(api_base: str, runtime: Optional[dict]) -> str:
1203
+ """production/staging/dev for the server being talked to."""
1204
+ named = (runtime or {}).get("environment")
1205
+ if named and (runtime or {}).get("base_url", "").rstrip("/") == (api_base or "").rstrip("/"):
1206
+ return named
1207
+ base = (api_base or "").rstrip("/")
1208
+ for name, url in environments().items():
1209
+ if url == base:
1210
+ return "production" if name == "prod" else name
1211
+ return "custom"
1212
+
1213
+
1214
+ def _parse_dt(value: Optional[str]) -> Optional[datetime]:
1215
+ if not value:
1216
+ return None
1217
+ try:
1218
+ return datetime.fromisoformat(value.replace("Z", "+00:00")).astimezone(timezone.utc)
1219
+ except ValueError:
1220
+ return None
1221
+
1222
+
1223
+ def _now_iso() -> str:
1224
+ return datetime.now(timezone.utc).isoformat()
1225
+
1226
+
1227
+ def _expiry_note(
1228
+ expires_at: Optional[str],
1229
+ *,
1230
+ issued_at: Optional[str] = None,
1231
+ now: Optional[datetime] = None,
1232
+ onboarding: bool = False,
1233
+ ) -> Optional[str]:
1234
+ """Return a nudge if the key is expired or about to expire, else None.
1235
+
1236
+ Renewable keys (90 days) warn in the last 14 days, so there is time to run
1237
+ `auth refresh`. A 7-day onboarding key cannot be renewed and is short-lived
1238
+ by design, so it warns only in its last 24 hours (and never more than the
1239
+ last 20 percent of its life). When the issue time is unknown the full window
1240
+ applies. Onboarding notes say a fresh prompt is needed and never mention
1241
+ `auth refresh`. The advice never mentions the browser login.
1242
+ """
1243
+ exp = _parse_dt(expires_at)
1244
+ if exp is None:
1245
+ return None
1246
+ now = now or datetime.now(timezone.utc)
1247
+ left = exp - now
1248
+ if left.total_seconds() <= 0 and onboarding:
1249
+ return (
1250
+ "This key has EXPIRED and cannot be renewed. Ask the developer for a fresh "
1251
+ "prompt from the dashboard (new one-time code), then run "
1252
+ "`maximem-synap auth login --code <code>`."
1253
+ )
1254
+ if left.total_seconds() <= 0:
1255
+ return (
1256
+ "This key has EXPIRED. Ask the human for a fresh onboarding prompt, then "
1257
+ "run `maximem-synap auth login --code <code>`."
1258
+ )
1259
+ window = timedelta(hours=24) if onboarding else RENEWABLE_WARN_WINDOW
1260
+ issued = _parse_dt(issued_at)
1261
+ if issued is not None and exp > issued:
1262
+ window = min(window, (exp - issued) * 0.2)
1263
+ if left <= window:
1264
+ hours = int(left.total_seconds() // 3600)
1265
+ when = (f"{hours // 24} day(s)" if hours >= 48 else f"{hours} hour(s)") if hours >= 1 else f"{max(1, int(left.total_seconds() // 60))} minute(s)"
1266
+ if onboarding:
1267
+ return (
1268
+ f"This key expires in {when} and cannot be renewed. When it does, ask the "
1269
+ f"developer for a fresh prompt from the dashboard (new one-time code), then "
1270
+ f"run `maximem-synap auth login --code <code>`. Setup and the profile "
1271
+ f"already on disk are kept."
1272
+ )
1273
+ return (
1274
+ f"This key expires in {when}. Run `maximem-synap auth refresh` to renew it "
1275
+ f"in place; if that fails, ask the human for a fresh onboarding prompt."
1276
+ )
1277
+ return None