zyonix-cli 0.1.13__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 (45) hide show
  1. zyonix_cli/__init__.py +2 -0
  2. zyonix_cli/agent_init.py +228 -0
  3. zyonix_cli/auth_cmd.py +499 -0
  4. zyonix_cli/auth_store.py +124 -0
  5. zyonix_cli/brief.py +271 -0
  6. zyonix_cli/checks_cmd.py +160 -0
  7. zyonix_cli/client.py +130 -0
  8. zyonix_cli/cmdkit.py +142 -0
  9. zyonix_cli/common.py +94 -0
  10. zyonix_cli/context_view.py +116 -0
  11. zyonix_cli/deploy_cmd.py +52 -0
  12. zyonix_cli/drafts_cmd.py +260 -0
  13. zyonix_cli/explain.py +283 -0
  14. zyonix_cli/fix_cmd.py +284 -0
  15. zyonix_cli/guard_cmd.py +125 -0
  16. zyonix_cli/helpview.py +171 -0
  17. zyonix_cli/importer.py +274 -0
  18. zyonix_cli/issues_cmd.py +597 -0
  19. zyonix_cli/jobs_cmd.py +71 -0
  20. zyonix_cli/junit.py +49 -0
  21. zyonix_cli/mcp_cmd.py +96 -0
  22. zyonix_cli/mcp_server.py +375 -0
  23. zyonix_cli/monitor_cmd.py +120 -0
  24. zyonix_cli/perf_view.py +51 -0
  25. zyonix_cli/progress.py +57 -0
  26. zyonix_cli/prompts_cmd.py +166 -0
  27. zyonix_cli/regression_cmd.py +216 -0
  28. zyonix_cli/render.py +313 -0
  29. zyonix_cli/replay_cmd.py +215 -0
  30. zyonix_cli/review_cmd.py +169 -0
  31. zyonix_cli/runner.py +213 -0
  32. zyonix_cli/runs_cmd.py +638 -0
  33. zyonix_cli/spec_cmd.py +74 -0
  34. zyonix_cli/status_cmd.py +488 -0
  35. zyonix_cli/term.py +206 -0
  36. zyonix_cli/test_cmd.py +248 -0
  37. zyonix_cli/triage.py +215 -0
  38. zyonix_cli/usage.py +172 -0
  39. zyonix_cli/verify.py +223 -0
  40. zyonix_cli/verify_view.py +87 -0
  41. zyonix_cli-0.1.13.dist-info/METADATA +58 -0
  42. zyonix_cli-0.1.13.dist-info/RECORD +45 -0
  43. zyonix_cli-0.1.13.dist-info/WHEEL +4 -0
  44. zyonix_cli-0.1.13.dist-info/entry_points.txt +21 -0
  45. zyonix_cli-0.1.13.dist-info/licenses/LICENSE +202 -0
zyonix_cli/auth_cmd.py ADDED
@@ -0,0 +1,499 @@
1
+ """Interactive person-level authentication. Passwords never appear in argv or output."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import getpass
7
+ import sys
8
+ from typing import Any
9
+
10
+ from zyonix._config import load_config
11
+ from zyonix.cli import console_safe
12
+
13
+ from zyonix_cli import auth_store, term
14
+ from zyonix_cli.client import ApiClient, CliError
15
+ from zyonix_cli.cmdkit import emit, group
16
+ from zyonix_cli.common import add_common_options
17
+ from zyonix_cli.render import next_steps, table
18
+
19
+
20
+ def _client(args: argparse.Namespace, authenticated: bool = True) -> ApiClient:
21
+ cfg = load_config(
22
+ args.config,
23
+ endpoint=args.endpoint,
24
+ api_key=args.api_key,
25
+ ca_file=getattr(args, "ca_file", None),
26
+ )
27
+ if not authenticated:
28
+ cfg.api_key = None # public signup/login do not need an existing machine credential
29
+ return ApiClient(cfg, require_credential=authenticated)
30
+
31
+
32
+ def _password(confirm: bool = False, prompt: str = "Password: ") -> str:
33
+ password = getpass.getpass(prompt)
34
+ if confirm and password != getpass.getpass("Confirm password: "):
35
+ raise CliError("passwords do not match")
36
+ return password
37
+
38
+
39
+ def _with_code(args: argparse.Namespace, client: ApiClient, path: str,
40
+ body: dict[str, Any]) -> Any:
41
+ """Sign in; when the account uses two-step sign-in, ask for the authenticator code (or a
42
+ recovery code) and try once more."""
43
+ try:
44
+ return client.post(path, {**body, "code": getattr(args, "code", None)})
45
+ except CliError as exc:
46
+ if "two_step_required" not in str(exc):
47
+ raise
48
+ code = getpass.getpass("Two-step code (or a recovery code): ").strip()
49
+ return client.post(path, {**body, "code": code})
50
+
51
+
52
+ def _save(args: argparse.Namespace, response: dict[str, Any]) -> None:
53
+ storage = auth_store.save(args.endpoint, response["session_token"])
54
+ if not emit(args, {"user": response["user"], "credential_storage": storage}):
55
+ user = response["user"]
56
+ print(f"Signed in as {user['display_name']} <{user['email']}> ({user['role']}).")
57
+ print(f"Session saved in {storage}. API keys still take precedence for CI.")
58
+
59
+
60
+ def _signup(args: argparse.Namespace) -> int:
61
+ email = args.email or input("Email: ").strip()
62
+ name = args.name or input("Your name: ").strip()
63
+ agent = args.agent
64
+ client = _client(args, authenticated=False)
65
+ try:
66
+ if not args.invite_token and not agent:
67
+ # the first administrator of an open-setup installation starts no agent of their own
68
+ status = client.get("/v1/auth/status")
69
+ first = status.get("setup_required") and status.get("open_setup")
70
+ if status.get("open_registration") and not first:
71
+ agent = input("What is your agent called? ").strip()
72
+ response = client.post(
73
+ "/v1/auth/signup",
74
+ {
75
+ "email": email,
76
+ "display_name": name,
77
+ "password": _password(confirm=True),
78
+ "invite_token": args.invite_token,
79
+ "agent_name": None if args.invite_token else agent,
80
+ "client": "cli",
81
+ },
82
+ )
83
+ # load_config normalizes the endpoint; use it rather than an unnormalized CLI alias.
84
+ args.endpoint = client.base
85
+ _save(args, response)
86
+ finally:
87
+ client.close()
88
+ if not args.json:
89
+ if key := response.get("sdk_key"):
90
+ print(f"Agent {response['agent']['name']} is ready. Its SDK key, shown once:")
91
+ print(key)
92
+ print(next_steps([("zyonix status", "open the reliability command center")]))
93
+ return 0
94
+
95
+
96
+ def _join(args: argparse.Namespace) -> int:
97
+ email = args.email or input("Email: ").strip()
98
+ client = _client(args, authenticated=False)
99
+ try:
100
+ response = _with_code(
101
+ args, client, "/v1/auth/join",
102
+ {"email": email, "password": _password(), "invite_token": args.invite_token,
103
+ "client": "cli"},
104
+ )
105
+ args.endpoint = client.base
106
+ _save(args, response)
107
+ finally:
108
+ client.close()
109
+ if not args.json:
110
+ print(next_steps([("zyonix auth agents", "see every agent of this sign-in")]))
111
+ return 0
112
+
113
+
114
+ def _agents(args: argparse.Namespace) -> int:
115
+ client = _client(args)
116
+ try:
117
+ response = client.get("/v1/auth/agents")
118
+ current = client.get("/v1/auth/session").get("project")
119
+ finally:
120
+ client.close()
121
+ if not emit(args, {**response, "current": current}):
122
+ print(
123
+ table(
124
+ ["", "ID", "NAME", "ROLE", "DOCUMENTS", "FAILED", "PROBLEMS"],
125
+ [
126
+ ["*" if a["id"] == current else "", a["id"], a["name"], a["role"], a["runs"],
127
+ a["failed"], a["open_problems"]]
128
+ for a in response["agents"]
129
+ ],
130
+ )
131
+ )
132
+ print(next_steps([("zyonix auth use <id>", "work on another agent")]))
133
+ return 0
134
+
135
+
136
+ def _use(args: argparse.Namespace) -> int:
137
+ client = _client(args)
138
+ try:
139
+ response = client.post("/v1/auth/switch", {"agent": args.agent})
140
+ finally:
141
+ client.close()
142
+ if not emit(args, response):
143
+ print(f"Now on {response['project']} ({response['role']}).")
144
+ return 0
145
+
146
+
147
+ def _add_agent(args: argparse.Namespace) -> int:
148
+ client = _client(args)
149
+ try:
150
+ response = client.post("/v1/auth/agents", {"name": args.name})
151
+ finally:
152
+ client.close()
153
+ if not emit(args, response):
154
+ print(f"Agent {response['agent']['name']} ({response['agent']['id']}) added; you are on "
155
+ "it now. Its SDK key, shown once:")
156
+ print(response["sdk_key"])
157
+ return 0
158
+
159
+
160
+ def _login(args: argparse.Namespace) -> int:
161
+ email = args.email or input("Email: ").strip()
162
+ client = _client(args, authenticated=False)
163
+ try:
164
+ response = _with_code(
165
+ args, client, "/v1/auth/login", {"email": email, "password": _password(),
166
+ "client": "cli"}
167
+ )
168
+ args.endpoint = client.base
169
+ _save(args, response)
170
+ finally:
171
+ client.close()
172
+ if not args.json:
173
+ print(next_steps([("zyonix status", "see what needs your attention")]))
174
+ return 0
175
+
176
+
177
+ def _whoami(args: argparse.Namespace) -> int:
178
+ client = _client(args)
179
+ try:
180
+ response = client.get("/v1/auth/session")
181
+ finally:
182
+ client.close()
183
+ if emit(args, response):
184
+ return 0
185
+ if user := response.get("user"):
186
+ print(f"{user['display_name']} <{user['email']}>")
187
+ print(f"role={user['role']} project={user['project_id']} auth=user-session")
188
+ else:
189
+ print(f"project={response['project']} auth={response['kind']}-api-key")
190
+ return 0
191
+
192
+
193
+ def _invite(args: argparse.Namespace) -> int:
194
+ client = _client(args)
195
+ try:
196
+ response = client.post("/v1/auth/invites", {"email": args.email, "role": args.role})
197
+ finally:
198
+ client.close()
199
+ if response.get("emailed"):
200
+ if not emit(args, response):
201
+ print(f"Invitation emailed to {response['email']} ({response['role']}); expires "
202
+ f"{response['expires_at']}.")
203
+ return 0
204
+ if not emit(args, response):
205
+ print(
206
+ f"Invitation for {response['email']} ({response['role']}); expires "
207
+ f"{response['expires_at']}. Shown once:"
208
+ )
209
+ print(response["invite_token"])
210
+ print(
211
+ "Share it only with that person. They can run `zyonix auth signup --invite-token ...` "
212
+ "(`zyonix auth join` if they already have an account)."
213
+ )
214
+ return 0
215
+
216
+
217
+ def _users(args: argparse.Namespace) -> int:
218
+ client = _client(args)
219
+ try:
220
+ response = client.get("/v1/auth/users")
221
+ finally:
222
+ client.close()
223
+ if not emit(args, response):
224
+ print(
225
+ table(
226
+ ["ID", "NAME", "EMAIL", "ROLE", "STATE"],
227
+ [
228
+ [u["id"], u["display_name"], u["email"], u["role"],
229
+ "active" if u["active"] else "disabled"]
230
+ for u in response["users"]
231
+ ],
232
+ )
233
+ )
234
+ return 0
235
+
236
+
237
+ def _set_access(args: argparse.Namespace) -> int:
238
+ active = {"disable": False, "enable": True}.get(args.action)
239
+ if args.role is None and active is None:
240
+ raise CliError("say what to change: --role, --disable or --enable")
241
+ client = _client(args)
242
+ try:
243
+ response = client.post(
244
+ f"/v1/auth/users/{args.user}/access", {"role": args.role, "active": active}
245
+ )
246
+ finally:
247
+ client.close()
248
+ if not emit(args, response):
249
+ user = response["user"]
250
+ state = "active" if user["active"] else "disabled, all sessions ended"
251
+ print(f"{user['email']}: {user['role']}, {state}.")
252
+ return 0
253
+
254
+
255
+ def _reset_link(args: argparse.Namespace) -> int:
256
+ client = _client(args)
257
+ try:
258
+ response = client.post(f"/v1/auth/users/{args.user}/reset-link", {})
259
+ url = f"{client.base}/forgot#token={response.get('reset_token')}"
260
+ finally:
261
+ client.close()
262
+ if response.get("emailed"):
263
+ if not emit(args, response):
264
+ print(f"A password link was emailed to {response['email']}; it works once, until "
265
+ f"{response['expires_at']}.")
266
+ return 0
267
+ if not emit(args, {**response, "url": url}):
268
+ print(f"Works once, until {response['expires_at']}. Shown once:")
269
+ print(url)
270
+ print("Send it only to that person: whoever opens it chooses the password.")
271
+ return 0
272
+
273
+
274
+ def _offboard(args: argparse.Namespace) -> int:
275
+ client = _client(args)
276
+ try:
277
+ response = client.post(f"/v1/auth/users/{args.user}/offboard", {})
278
+ finally:
279
+ client.close()
280
+ if not emit(args, response):
281
+ agents = ", ".join(response["removed_from"])
282
+ print(f"{response['email']}: removed from {agents}. Sessions, invitations they sent and "
283
+ "password links they made are gone.")
284
+ if response["still_on"]:
285
+ print(f"They still work on {response['still_on']} agent(s) you do not administer.")
286
+ for key in response.get("keys_stopping", []):
287
+ print(f"Key {key['prefix']}... ({key['kind']}) they created stops working at "
288
+ f"{key['until'][:16]} UTC: rotate it with `zyonix auth keys --rotate <id>`.")
289
+ print(next_steps([("zyonix auth keys", "rotate any key they had a copy of")]))
290
+ return 0
291
+
292
+
293
+ def _keys(args: argparse.Namespace) -> int:
294
+ client = _client(args)
295
+ try:
296
+ if args.create:
297
+ response = client.post("/v1/auth/keys", {"kind": args.create})
298
+ elif args.rotate is not None:
299
+ response = client.post(f"/v1/auth/keys/{args.rotate}/rotate",
300
+ {"grace_hours": args.grace_hours})
301
+ elif args.revoke is not None:
302
+ response = client.delete(f"/v1/auth/keys/{args.revoke}")
303
+ else:
304
+ response = client.get("/v1/auth/keys")
305
+ finally:
306
+ client.close()
307
+ if emit(args, response):
308
+ return 0
309
+ if "keys" in response:
310
+ print(table(["ID", "KEY", "KIND", "CREATED", "STATE"], [
311
+ [k["id"], k["prefix"] + "...", k["kind"], k["created_at"][:16],
312
+ "revoked" if not k["active"] else f"stops {k['revoked_at'][:16]}"
313
+ if k["revoked_at"] else "active"] for k in response["keys"]]))
314
+ print(next_steps([("zyonix auth keys --create sdk", "a new key (shown once)"),
315
+ ("zyonix auth keys --rotate <id>", "replace a key")]))
316
+ elif "key" in response:
317
+ print("New key (shown once):")
318
+ print(response["key"])
319
+ if args.rotate is not None:
320
+ print(f"The old key keeps working for {args.grace_hours:g} hour(s).")
321
+ else:
322
+ print("Key revoked; it stops working within 30 seconds.")
323
+ return 0
324
+
325
+
326
+ def _invites(args: argparse.Namespace) -> int:
327
+ client = _client(args)
328
+ try:
329
+ response = client.get("/v1/auth/invites")
330
+ finally:
331
+ client.close()
332
+ if not emit(args, response):
333
+ print(
334
+ table(
335
+ ["ID", "EMAIL", "ROLE", "EXPIRES", "STATE"],
336
+ [
337
+ [i["id"], i["email"], i["role"], i["expires_at"],
338
+ "accepted" if i["accepted"] else "expired" if i["expired"] else "pending"]
339
+ for i in response["invites"]
340
+ ],
341
+ )
342
+ )
343
+ return 0
344
+
345
+
346
+ def _cancel_invite(args: argparse.Namespace) -> int:
347
+ client = _client(args)
348
+ try:
349
+ response = client.delete(f"/v1/auth/invites/{args.invite}")
350
+ finally:
351
+ client.close()
352
+ if not emit(args, response):
353
+ print(f"Invitation {args.invite} cancelled.")
354
+ return 0
355
+
356
+
357
+ def _logout(args: argparse.Namespace) -> int:
358
+ cfg = load_config(args.config, endpoint=args.endpoint,
359
+ ca_file=getattr(args, "ca_file", None))
360
+ token = auth_store.get(cfg.endpoint)
361
+ if not args.local:
362
+ if not token:
363
+ raise CliError("no stored user session; use --local to clear any local credential")
364
+ cfg.api_key = token # revoke the user session even when ZYONIX_API_KEY is also set
365
+ client = ApiClient(cfg)
366
+ try:
367
+ response = client.post("/v1/auth/logout")
368
+ finally:
369
+ client.close()
370
+ else:
371
+ response = {"logged_out": True, "local_only": True}
372
+ auth_store.delete(cfg.endpoint)
373
+ if not emit(args, response):
374
+ print("Signed out and removed the local CLI session.")
375
+ return 0
376
+
377
+
378
+ def _change_password(args: argparse.Namespace) -> int:
379
+ current = _password(prompt="Current password: ")
380
+ fresh = _password(confirm=True, prompt="New password: ")
381
+ client = _client(args)
382
+ try:
383
+ response = client.post(
384
+ "/v1/auth/password", {"current_password": current, "new_password": fresh}
385
+ )
386
+ finally:
387
+ client.close()
388
+ if not emit(args, response):
389
+ print("Password changed. Other browser and CLI sessions were revoked.")
390
+ return 0
391
+
392
+
393
+ def _dispatch(args: argparse.Namespace) -> int:
394
+ console_safe()
395
+ try:
396
+ return int(args.auth_handler(args) or 0)
397
+ except (CliError, ValueError) as exc:
398
+ secrets = [getattr(args, "api_key", None)]
399
+ print(term.error_line("auth", exc, secrets), file=sys.stderr)
400
+ return 2
401
+
402
+
403
+ def _options(parser: argparse.ArgumentParser) -> None:
404
+ add_common_options(parser, step=False)
405
+ parser.add_argument(
406
+ "--json", action="store_true", help="print a JSON response (never a session token)"
407
+ )
408
+
409
+
410
+ def register(sub: Any) -> None:
411
+ _, actions = group(sub, "auth", "sign up, sign in, and manage your user session")
412
+ p = actions.add_parser("signup", help="create your account, with a new agent of your own or "
413
+ "through an invitation")
414
+ _options(p)
415
+ p.add_argument("--email")
416
+ p.add_argument("--name", help="display name (prompted when omitted)")
417
+ p.add_argument("--agent", help="name of your new agent (without an invitation)")
418
+ p.add_argument("--invite-token", help="single-use invitation from an administrator")
419
+ p.set_defaults(auth_handler=_signup, func=_dispatch)
420
+ p = actions.add_parser("join", help="accept an invitation to one more agent, with the account "
421
+ "you already have")
422
+ _options(p)
423
+ p.add_argument("--email")
424
+ p.add_argument("--invite-token", required=True, help="single-use invitation")
425
+ p.add_argument("--code", help="two-step code (prompted when the account needs one)")
426
+ p.set_defaults(auth_handler=_join, func=_dispatch)
427
+ p = actions.add_parser("agents", help="every agent of your sign-in, the last 7 days of each")
428
+ _options(p)
429
+ p.set_defaults(auth_handler=_agents, func=_dispatch)
430
+ p = actions.add_parser("use", help="work on another of your agents")
431
+ _options(p)
432
+ p.add_argument("agent", help="agent id from `zyonix auth agents`")
433
+ p.set_defaults(auth_handler=_use, func=_dispatch)
434
+ p = actions.add_parser("add-agent", help="add an agent (administrators); prints its SDK key")
435
+ _options(p)
436
+ p.add_argument("name", help="what the agent is called")
437
+ p.set_defaults(auth_handler=_add_agent, func=_dispatch)
438
+ p = actions.add_parser("login", help="sign in and save a session in the OS credential store")
439
+ _options(p)
440
+ p.add_argument("--email")
441
+ p.add_argument("--code", help="two-step code (prompted when the account needs one)")
442
+ p.set_defaults(auth_handler=_login, func=_dispatch)
443
+ for name, help_text, handler in (
444
+ ("whoami", "show the authenticated user or API-key identity", _whoami),
445
+ ("logout", "revoke the server session and remove the local credential", _logout),
446
+ ("change-password", "change password and revoke other sessions", _change_password),
447
+ ):
448
+ p = actions.add_parser(name, help=help_text)
449
+ _options(p)
450
+ if name == "logout":
451
+ p.add_argument(
452
+ "--local",
453
+ action="store_true",
454
+ help="only remove the local credential (use when the server is unreachable)",
455
+ )
456
+ p.set_defaults(auth_handler=handler, func=_dispatch)
457
+ p = actions.add_parser("invite", help="invite a teammate (user admin session required)")
458
+ _options(p)
459
+ p.add_argument("--email", required=True)
460
+ p.add_argument("--role", choices=["admin", "member", "viewer"], default="member")
461
+ p.set_defaults(auth_handler=_invite, func=_dispatch)
462
+ for name, help_text, handler in (
463
+ ("users", "list the people of this project (user admin session required)", _users),
464
+ ("invites", "list invitations (user admin session required)", _invites),
465
+ ):
466
+ p = actions.add_parser(name, help=help_text)
467
+ _options(p)
468
+ p.set_defaults(auth_handler=handler, func=_dispatch)
469
+ p = actions.add_parser("cancel-invite", help="cancel an open invitation")
470
+ _options(p)
471
+ p.add_argument("invite", type=int, help="invitation id from `zyonix auth invites`")
472
+ p.set_defaults(auth_handler=_cancel_invite, func=_dispatch)
473
+ p = actions.add_parser("access", help="change a person's role, or disable / enable them")
474
+ _options(p)
475
+ p.add_argument("user", type=int, help="user id from `zyonix auth users`")
476
+ p.add_argument("--role", choices=["admin", "member", "viewer"])
477
+ state = p.add_mutually_exclusive_group()
478
+ state.add_argument("--disable", dest="action", action="store_const", const="disable")
479
+ state.add_argument("--enable", dest="action", action="store_const", const="enable")
480
+ p.set_defaults(auth_handler=_set_access, func=_dispatch)
481
+ p = actions.add_parser("reset-link", help="create a one-time link to set a password")
482
+ _options(p)
483
+ p.add_argument("user", type=int, help="user id from `zyonix auth users`")
484
+ p.set_defaults(auth_handler=_reset_link, func=_dispatch)
485
+ p = actions.add_parser("offboard", help="someone leaves: remove them from every agent you "
486
+ "administer and end their sessions and links")
487
+ _options(p)
488
+ p.add_argument("user", type=int, help="user id from `zyonix auth users`")
489
+ p.set_defaults(auth_handler=_offboard, func=_dispatch)
490
+ p = actions.add_parser("keys", help="this agent's API keys: list, create, rotate, revoke "
491
+ "(administrators)")
492
+ _options(p)
493
+ act = p.add_mutually_exclusive_group()
494
+ act.add_argument("--create", choices=["sdk", "cli", "agent"], help="create a key of this kind")
495
+ act.add_argument("--rotate", type=int, metavar="ID", help="replace this key")
496
+ act.add_argument("--revoke", type=int, metavar="ID", help="stop this key working")
497
+ p.add_argument("--grace-hours", type=float, default=24.0,
498
+ help="with --rotate: how long the old key keeps working (0-168, default 24)")
499
+ p.set_defaults(auth_handler=_keys, func=_dispatch)
@@ -0,0 +1,124 @@
1
+ """Local storage for interactive CLI sessions (never used for SDK ingestion keys).
2
+
3
+ The OS credential store is preferred. POSIX can fall back to a 0600 JSON file when no secret
4
+ service is available; Windows requires its Credential Manager rather than pretending chmod
5
+ provides a secure ACL. Endpoint URLs are lookup names, never credentials.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import json
11
+ import os
12
+ import secrets
13
+ import stat
14
+ from pathlib import Path
15
+
16
+ import keyring
17
+
18
+ SERVICE = "dev.zyonix.cli"
19
+ FILE_NAME = "sessions.json"
20
+
21
+
22
+ def endpoint_name(endpoint: str) -> str:
23
+ return endpoint.strip().rstrip("/").lower()
24
+
25
+
26
+ def state_dir() -> Path:
27
+ if os.environ.get("ZYONIX_STATE_DIR"):
28
+ return Path(os.environ["ZYONIX_STATE_DIR"])
29
+ if os.name == "nt":
30
+ return Path(os.environ.get("LOCALAPPDATA", Path.home() / "AppData/Local")) / "zyonix"
31
+ return Path(os.environ.get("XDG_STATE_HOME", Path.home() / ".local/state")) / "zyonix"
32
+
33
+
34
+ def _path() -> Path:
35
+ return state_dir() / FILE_NAME
36
+
37
+
38
+ def _allow_file() -> bool:
39
+ return os.name == "posix"
40
+
41
+
42
+ def _read_file() -> dict[str, str]:
43
+ path = _path()
44
+ if not path.exists():
45
+ return {}
46
+ if os.name == "posix" and path.stat().st_mode & (stat.S_IRWXG | stat.S_IRWXO):
47
+ raise ValueError(f"{path} is readable by group/others; run chmod 600 on it")
48
+ try:
49
+ data = json.loads(path.read_text(encoding="utf-8"))
50
+ except (OSError, ValueError) as exc:
51
+ raise ValueError(
52
+ f"cannot read the CLI session store {path}: {type(exc).__name__}"
53
+ ) from None
54
+ if not isinstance(data, dict) or not all(
55
+ isinstance(k, str) and isinstance(v, str) for k, v in data.items()
56
+ ):
57
+ raise ValueError(f"the CLI session store {path} is invalid")
58
+ return data
59
+
60
+
61
+ def _write_file(data: dict[str, str]) -> None:
62
+ directory = state_dir()
63
+ directory.mkdir(parents=True, exist_ok=True, mode=0o700)
64
+ if os.name == "posix":
65
+ directory.chmod(0o700)
66
+ path = _path()
67
+ temporary = path.with_name(f".{path.name}.{secrets.token_hex(6)}.tmp")
68
+ try:
69
+ # O_EXCL + 0600: the plaintext token is never created with a permissive mode.
70
+ fd = os.open(temporary, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
71
+ with os.fdopen(fd, "w", encoding="utf-8") as stream:
72
+ json.dump(data, stream, separators=(",", ":"))
73
+ stream.flush()
74
+ os.fsync(stream.fileno())
75
+ os.replace(temporary, path)
76
+ finally:
77
+ temporary.unlink(missing_ok=True)
78
+
79
+
80
+ def get(endpoint: str) -> str | None:
81
+ name = endpoint_name(endpoint)
82
+ try:
83
+ token = keyring.get_password(SERVICE, name)
84
+ if token:
85
+ return token
86
+ except Exception:
87
+ pass # headless secret services fall through to the guarded file on POSIX
88
+ try:
89
+ return _read_file().get(name) if _allow_file() else None
90
+ except ValueError:
91
+ return None
92
+
93
+
94
+ def save(endpoint: str, token: str) -> str:
95
+ name = endpoint_name(endpoint)
96
+ try:
97
+ keyring.set_password(SERVICE, name, token)
98
+ # Remove a token left by an older fallback so there is one live local copy.
99
+ if _path().exists() and _allow_file():
100
+ data = _read_file()
101
+ data.pop(name, None)
102
+ _write_file(data)
103
+ return "OS credential store"
104
+ except Exception:
105
+ if not _allow_file():
106
+ raise ValueError(
107
+ "the OS credential store is unavailable; unlock it and try again"
108
+ ) from None
109
+ data = _read_file()
110
+ data[name] = token
111
+ _write_file(data)
112
+ return "permission-protected CLI state file"
113
+
114
+
115
+ def delete(endpoint: str) -> None:
116
+ name = endpoint_name(endpoint)
117
+ try:
118
+ keyring.delete_password(SERVICE, name)
119
+ except Exception:
120
+ pass
121
+ if _path().exists() and _allow_file():
122
+ data = _read_file()
123
+ data.pop(name, None)
124
+ _write_file(data)