xiii-cli-core 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.
@@ -0,0 +1,527 @@
1
+ import json
2
+ import math
3
+ import os
4
+ import tomllib
5
+ from dataclasses import dataclass
6
+ from enum import Enum
7
+ from importlib.resources.abc import Traversable
8
+ from ipaddress import ip_address
9
+ from pathlib import Path
10
+ from typing import Any
11
+ from urllib.parse import urlparse
12
+
13
+ import keyring
14
+ from keyring.errors import KeyringError, PasswordDeleteError
15
+
16
+ from xiii_cli_core.errors import AuthenticationError, ConfigurationError
17
+
18
+ # Which workspace each remote is currently pointed at, plus the names needed to
19
+ # resolve `workspace use <name>` without a server call. Deliberately not in the
20
+ # OS keyring: a workspace id is not a secret, and the keyring cannot be
21
+ # enumerated portably, so `auth status` could otherwise not list what is stored.
22
+ STATE_FILENAME = "state.json"
23
+ STATE_VERSION = 1
24
+ # Seconds an API request may take; --request-timeout or <PRODUCT>_TIMEOUT
25
+ # override it.
26
+ DEFAULT_TIMEOUT = 15.0
27
+
28
+
29
+ @dataclass(frozen=True)
30
+ class Product:
31
+ """Everything the CLI knows about the product it is the front door of.
32
+
33
+ The entrypoint builds it; nothing below it knows which products exist.
34
+ """
35
+
36
+ # The command name. It also names the environment variables, the keyring
37
+ # service, the state directory and the project file.
38
+ name: str
39
+ display_name: str
40
+ # The API an invocation talks to unless --api-url, the environment or the
41
+ # project file says otherwise.
42
+ api_url: str
43
+ # Registered with the product's authorization server.
44
+ oauth_client_id: str
45
+ # The generated command manifest (`openapi.write_command_manifest`).
46
+ manifest: Traversable
47
+ version: str
48
+ # A Claude Code skill shipped with the entrypoint; `claude-code install`
49
+ # copies it into a skills directory. None registers no such command.
50
+ skill: Traversable | None = None
51
+
52
+ @property
53
+ def env_prefix(self) -> str:
54
+ return self.name.upper().replace("-", "_")
55
+
56
+ @property
57
+ def keyring_service(self) -> str:
58
+ return f"{self.name}-cli"
59
+
60
+ @property
61
+ def project_config_filename(self) -> str:
62
+ return f".{self.name}.toml"
63
+
64
+
65
+ class Surface(str, Enum):
66
+ """Which entrypoint is asking, because they default to different APIs."""
67
+
68
+ CUSTOMER = "customer"
69
+ DEVELOPMENT = "development"
70
+
71
+
72
+ @dataclass(frozen=True)
73
+ class WorkspaceRef:
74
+ """A workspace this machine holds a token for."""
75
+
76
+ id: str
77
+ name: str
78
+
79
+
80
+ @dataclass(frozen=True)
81
+ class ProductConfig:
82
+ product: Product
83
+ surface: Surface
84
+ base_url: str
85
+ token_env: str
86
+ keyring_service: str
87
+ base_url_source: str = "default"
88
+ config_file: Path | None = None
89
+ # Name or id passed with `--workspace` or the product's workspace
90
+ # environment variable. Overrides the stored active workspace for this
91
+ # invocation only, the way `gh --repo` or `aws --profile` do.
92
+ workspace: str | None = None
93
+ workspace_source: str = "active workspace"
94
+ timeout: float = DEFAULT_TIMEOUT
95
+
96
+ @property
97
+ def entrypoint(self) -> str:
98
+ if self.surface is Surface.DEVELOPMENT:
99
+ return f"{self.product.name}-dev"
100
+ return self.product.name
101
+
102
+ @property
103
+ def workspace_env(self) -> str:
104
+ """Per-invocation workspace override, e.g. EXAMPLE_WORKSPACE."""
105
+ return f"{self.product.env_prefix}_WORKSPACE"
106
+
107
+ @property
108
+ def user_agent(self) -> str:
109
+ return f"{self.product.name}/{self.product.version}"
110
+
111
+
112
+ def product_config(
113
+ product: Product,
114
+ *,
115
+ surface: Surface,
116
+ api_url: str | None = None,
117
+ config_file: Path | None = None,
118
+ start_dir: Path | None = None,
119
+ workspace: str | None = None,
120
+ timeout: float | None = None,
121
+ ) -> ProductConfig:
122
+ env_prefix = product.env_prefix
123
+ api_url_env = f"{env_prefix}_API_URL"
124
+ workspace_env = f"{env_prefix}_WORKSPACE"
125
+ timeout_env = f"{env_prefix}_TIMEOUT"
126
+ resolved_file = _resolve_config_file(product, config_file, start_dir=start_dir)
127
+ file_url = _read_api_url(resolved_file)
128
+ if api_url is not None:
129
+ base_url, source = api_url, "--api-url"
130
+ elif env_url := os.getenv(api_url_env):
131
+ base_url, source = env_url, api_url_env
132
+ elif file_url is not None:
133
+ base_url, source = file_url, str(resolved_file)
134
+ else:
135
+ base_url, source = product.api_url, "default"
136
+ base_url = validate_api_url(base_url)
137
+ if workspace is not None:
138
+ selector, workspace_source = workspace, "--workspace"
139
+ elif env_workspace := os.getenv(workspace_env):
140
+ selector, workspace_source = env_workspace, workspace_env
141
+ else:
142
+ selector, workspace_source = None, "active workspace"
143
+ return ProductConfig(
144
+ product=product,
145
+ surface=surface,
146
+ base_url=base_url,
147
+ token_env=f"{env_prefix}_API_TOKEN",
148
+ keyring_service=product.keyring_service,
149
+ base_url_source=source,
150
+ config_file=resolved_file,
151
+ workspace=selector,
152
+ workspace_source=workspace_source,
153
+ timeout=_resolve_timeout(timeout, timeout_env),
154
+ )
155
+
156
+
157
+ def _resolve_timeout(explicit: float | None, env_name: str) -> float:
158
+ if explicit is not None:
159
+ value, source = explicit, "--request-timeout"
160
+ elif raw := os.getenv(env_name):
161
+ try:
162
+ value = float(raw)
163
+ except ValueError as exc:
164
+ raise ConfigurationError(f"{env_name} must be a number of seconds") from exc
165
+ source = env_name
166
+ else:
167
+ return DEFAULT_TIMEOUT
168
+ if not math.isfinite(value) or value <= 0:
169
+ raise ConfigurationError(f"{source} must be a positive number of seconds")
170
+ return value
171
+
172
+
173
+ def validate_api_url(url: str) -> str:
174
+ normalized = url.strip().rstrip("/")
175
+ if any(ord(char) <= 32 or char == "\\" for char in normalized):
176
+ raise ConfigurationError("API URL must not contain whitespace or backslashes")
177
+ try:
178
+ parsed = urlparse(normalized)
179
+ port = parsed.port
180
+ except ValueError as exc:
181
+ raise ConfigurationError("API URL is not a valid absolute http(s) URL") from exc
182
+ if parsed.scheme not in {"http", "https"} or not parsed.hostname:
183
+ raise ConfigurationError("API URL must be an absolute http(s) URL")
184
+ if port == 0:
185
+ raise ConfigurationError("API URL port must be between 1 and 65535")
186
+ if parsed.username or parsed.password:
187
+ raise ConfigurationError("API URL must not contain credentials")
188
+ if parsed.query or parsed.fragment:
189
+ raise ConfigurationError("API URL must not contain a query or fragment")
190
+ if parsed.scheme != "https" and not is_loopback_url(normalized):
191
+ raise ConfigurationError(
192
+ "Non-loopback API URLs must use HTTPS to protect bearer tokens"
193
+ )
194
+ return normalized
195
+
196
+
197
+ def is_loopback_url(url: str) -> bool:
198
+ hostname = urlparse(url).hostname
199
+ if hostname == "localhost":
200
+ return True
201
+ if hostname is None:
202
+ return False
203
+ try:
204
+ return ip_address(hostname).is_loopback
205
+ except ValueError:
206
+ return False
207
+
208
+
209
+ def _resolve_config_file(
210
+ product: Product, explicit: Path | None, *, start_dir: Path | None
211
+ ) -> Path | None:
212
+ if explicit is not None:
213
+ path = explicit.expanduser().resolve()
214
+ if not path.is_file():
215
+ raise ConfigurationError(f"Config file not found: {path}")
216
+ return path
217
+ current = (start_dir or Path.cwd()).resolve()
218
+ for directory in (current, *current.parents):
219
+ candidate = directory / product.project_config_filename
220
+ if candidate.is_file():
221
+ return candidate
222
+ return None
223
+
224
+
225
+ def _read_api_url(path: Path | None) -> str | None:
226
+ if path is None:
227
+ return None
228
+ try:
229
+ with path.open("rb") as file:
230
+ payload: Any = tomllib.load(file)
231
+ except (OSError, tomllib.TOMLDecodeError) as exc:
232
+ raise ConfigurationError(f"Could not read config file {path}: {exc}") from exc
233
+ api_url = payload.get("api_url")
234
+ if api_url is None:
235
+ return None
236
+ if not isinstance(api_url, str) or not api_url.strip():
237
+ raise ConfigurationError(f"api_url must be a non-empty string in {path}")
238
+ return api_url
239
+
240
+
241
+ def state_path(product: Product) -> Path:
242
+ """Where the active workspace and the known workspace names are recorded."""
243
+ base = os.getenv("XDG_CONFIG_HOME")
244
+ root = Path(base).expanduser() if base else Path.home() / ".config"
245
+ return root / product.name / STATE_FILENAME
246
+
247
+
248
+ def _remote_key(config: ProductConfig) -> str:
249
+ """State is keyed per product *and* API, so a dev and a prod login coexist."""
250
+ return f"{config.product.name}|{config.base_url}"
251
+
252
+
253
+ def _read_state(product: Product) -> dict[str, Any]:
254
+ path = state_path(product)
255
+ try:
256
+ payload: Any = json.loads(path.read_text(encoding="utf-8"))
257
+ except FileNotFoundError:
258
+ return {"version": STATE_VERSION, "remotes": {}}
259
+ except (OSError, json.JSONDecodeError) as exc:
260
+ raise ConfigurationError(f"Could not read CLI state {path}: {exc}") from exc
261
+ if not isinstance(payload, dict) or payload.get("version") != STATE_VERSION:
262
+ raise ConfigurationError(
263
+ f"Unsupported CLI state version in {path}. Remove the file to start over."
264
+ )
265
+ remotes = payload.get("remotes")
266
+ if not isinstance(remotes, dict):
267
+ raise ConfigurationError(f"CLI state {path} has no remotes table")
268
+ return payload
269
+
270
+
271
+ def _write_state(product: Product, state: dict[str, Any]) -> None:
272
+ path = state_path(product)
273
+ try:
274
+ path.parent.mkdir(parents=True, exist_ok=True)
275
+ # Written through a sibling and renamed so an interrupted write cannot
276
+ # leave a half-file that every later invocation refuses to parse.
277
+ temporary = path.with_name(f"{path.name}.tmp")
278
+ temporary.write_text(
279
+ json.dumps(state, indent=2, sort_keys=True) + "\n", encoding="utf-8"
280
+ )
281
+ temporary.replace(path)
282
+ except OSError as exc:
283
+ raise ConfigurationError(f"Could not write CLI state {path}: {exc}") from exc
284
+
285
+
286
+ def _remote_state(config: ProductConfig) -> dict[str, Any]:
287
+ remote = _read_state(config.product)["remotes"].get(_remote_key(config))
288
+ return remote if isinstance(remote, dict) else {}
289
+
290
+
291
+ def known_workspaces(config: ProductConfig) -> list[WorkspaceRef]:
292
+ """Workspaces this machine has logged in to for this product and API."""
293
+ entries = _remote_state(config).get("workspaces")
294
+ if not isinstance(entries, list):
295
+ return []
296
+ return [
297
+ WorkspaceRef(id=str(entry["id"]), name=str(entry.get("name", entry["id"])))
298
+ for entry in entries
299
+ if isinstance(entry, dict) and entry.get("id")
300
+ ]
301
+
302
+
303
+ def active_workspace_id(config: ProductConfig) -> str | None:
304
+ active = _remote_state(config).get("active_workspace_id")
305
+ return str(active) if active else None
306
+
307
+
308
+ def remember_workspace(
309
+ config: ProductConfig, workspace: WorkspaceRef, *, activate: bool = True
310
+ ) -> None:
311
+ """Record a workspace this machine now holds a token for."""
312
+ state = _read_state(config.product)
313
+ remote = state["remotes"].setdefault(_remote_key(config), {})
314
+ entries = [entry for entry in known_workspaces(config) if entry.id != workspace.id]
315
+ entries.append(workspace)
316
+ remote["workspaces"] = [
317
+ {"id": entry.id, "name": entry.name}
318
+ for entry in sorted(entries, key=lambda entry: entry.name.casefold())
319
+ ]
320
+ if activate or not remote.get("active_workspace_id"):
321
+ remote["active_workspace_id"] = workspace.id
322
+ _write_state(config.product, state)
323
+
324
+
325
+ def set_active_workspace(config: ProductConfig, workspace_id: str) -> None:
326
+ state = _read_state(config.product)
327
+ remote = state["remotes"].setdefault(_remote_key(config), {})
328
+ remote["active_workspace_id"] = workspace_id
329
+ _write_state(config.product, state)
330
+
331
+
332
+ def forget_workspace(config: ProductConfig, workspace_id: str) -> None:
333
+ """Drop one workspace from the state file, after its token is gone."""
334
+ state = _read_state(config.product)
335
+ remote = state["remotes"].get(_remote_key(config))
336
+ if not isinstance(remote, dict):
337
+ return
338
+ remote["workspaces"] = [
339
+ {"id": entry.id, "name": entry.name}
340
+ for entry in known_workspaces(config)
341
+ if entry.id != workspace_id
342
+ ]
343
+ if remote.get("active_workspace_id") == workspace_id:
344
+ remaining = remote["workspaces"]
345
+ remote["active_workspace_id"] = remaining[0]["id"] if remaining else None
346
+ _write_state(config.product, state)
347
+
348
+
349
+ def match_workspace(config: ProductConfig, selector: str) -> WorkspaceRef:
350
+ """Resolve a `<name|id>` selector against what this machine already knows.
351
+
352
+ Name matching is what makes `workspace use` a local operation: the names
353
+ were recorded at login, so switching needs no server call and no re-login.
354
+ """
355
+ known = known_workspaces(config)
356
+ for workspace in known:
357
+ if workspace.id == selector:
358
+ return workspace
359
+ matches = [
360
+ workspace
361
+ for workspace in known
362
+ if workspace.name.casefold() == selector.casefold()
363
+ ]
364
+ if len(matches) == 1:
365
+ return matches[0]
366
+ if len(matches) > 1:
367
+ raise ConfigurationError(
368
+ f"{selector!r} matches more than one workspace. Use the workspace id: "
369
+ + ", ".join(workspace.id for workspace in matches)
370
+ )
371
+ if not known:
372
+ raise AuthenticationError(
373
+ f"No workspace is logged in for {config.base_url}. "
374
+ f"Run `{config.entrypoint} login`."
375
+ )
376
+ raise ConfigurationError(
377
+ f"Unknown workspace {selector!r}. Logged in: "
378
+ + ", ".join(f"{workspace.name} ({workspace.id})" for workspace in known)
379
+ )
380
+
381
+
382
+ def resolve_workspace(config: ProductConfig) -> WorkspaceRef | None:
383
+ """Which workspace this invocation acts as, override first."""
384
+ if config.workspace is not None:
385
+ return match_workspace(config, config.workspace)
386
+ active = active_workspace_id(config)
387
+ known = known_workspaces(config)
388
+ for workspace in known:
389
+ if workspace.id == active:
390
+ return workspace
391
+ return known[0] if len(known) == 1 else None
392
+
393
+
394
+ def keyring_username(config: ProductConfig, workspace_id: str) -> str:
395
+ """Keyring slot for one workspace at one API.
396
+
397
+ A PAT is audience-restricted to the workspace it was minted for, so the slot
398
+ carries the workspace id — otherwise a second login overwrites the first and
399
+ only one workspace can be driven at a time.
400
+ """
401
+ return f"{config.base_url}#{workspace_id}"
402
+
403
+
404
+ @dataclass(frozen=True)
405
+ class StoredLogin:
406
+ """What the keyring holds for one workspace.
407
+
408
+ A PAT pasted with `auth login` is only a token. A browser or device login
409
+ also holds the refresh token that replaces its hour-long bearer token, and
410
+ the epoch second that bearer token stops working. Either is one keyring
411
+ entry, so a workspace never has half a credential.
412
+ """
413
+
414
+ access_token: str
415
+ refresh_token: str | None = None
416
+ access_expires_at: float | None = None
417
+
418
+
419
+ def _encode_login(login: StoredLogin) -> str:
420
+ if login.refresh_token is None:
421
+ return login.access_token
422
+ return json.dumps(
423
+ {
424
+ "access_token": login.access_token,
425
+ "refresh_token": login.refresh_token,
426
+ "access_expires_at": login.access_expires_at,
427
+ },
428
+ sort_keys=True,
429
+ )
430
+
431
+
432
+ def _decode_login(value: str) -> StoredLogin:
433
+ # A PAT is `<product>_sk_…` and never starts with a brace, so the two shapes
434
+ # cannot be mistaken for each other.
435
+ if not value.startswith("{"):
436
+ return StoredLogin(access_token=value)
437
+ try:
438
+ payload: Any = json.loads(value)
439
+ login = StoredLogin(
440
+ access_token=str(payload["access_token"]),
441
+ refresh_token=str(payload["refresh_token"]),
442
+ access_expires_at=float(payload["access_expires_at"]),
443
+ )
444
+ except (ValueError, TypeError, KeyError) as exc:
445
+ raise AuthenticationError(
446
+ "The stored login is unreadable. Run `login` again."
447
+ ) from exc
448
+ return login
449
+
450
+
451
+ def read_login(config: ProductConfig, workspace: WorkspaceRef) -> StoredLogin:
452
+ try:
453
+ value = keyring.get_password(
454
+ config.keyring_service, keyring_username(config, workspace.id)
455
+ )
456
+ except KeyringError as exc:
457
+ raise AuthenticationError(f"OS keyring unavailable: {exc}") from exc
458
+ if not value:
459
+ raise AuthenticationError(
460
+ f"Not authenticated for workspace {workspace.name}. "
461
+ f"Run `{config.entrypoint} login` or set {config.token_env}."
462
+ )
463
+ return _decode_login(value)
464
+
465
+
466
+ def require_explicit_secret_endpoint(
467
+ config: ProductConfig, credential_source: str
468
+ ) -> None:
469
+ """Refuse a credential operation against a project-config-only remote API.
470
+
471
+ A checked-in project file must not be able to choose where credentials are
472
+ sent (a pasted PAT) or minted (the browser login, whose consent page is
473
+ named by that API's discovery document).
474
+ """
475
+ if (
476
+ config.config_file is not None
477
+ and config.base_url_source == str(config.config_file)
478
+ and not is_loopback_url(config.base_url)
479
+ ):
480
+ api_url_env = f"{config.product.env_prefix}_API_URL"
481
+ raise AuthenticationError(
482
+ f"Refusing to use {credential_source} with an API URL sourced only "
483
+ f"from {config.config_file}. Set {api_url_env} or pass --api-url "
484
+ "explicitly."
485
+ )
486
+
487
+
488
+ def store_token(
489
+ config: ProductConfig,
490
+ token: str,
491
+ workspace_id: str,
492
+ *,
493
+ refresh_token: str | None = None,
494
+ access_expires_at: float | None = None,
495
+ ) -> None:
496
+ if (refresh_token is None) != (access_expires_at is None):
497
+ raise ValueError("A refresh token is stored together with its deadline")
498
+ login = StoredLogin(
499
+ access_token=token,
500
+ refresh_token=refresh_token,
501
+ access_expires_at=access_expires_at,
502
+ )
503
+ try:
504
+ keyring.set_password(
505
+ config.keyring_service,
506
+ keyring_username(config, workspace_id),
507
+ _encode_login(login),
508
+ )
509
+ except KeyringError as exc:
510
+ raise AuthenticationError(
511
+ f"Could not store token in OS keyring: {exc}"
512
+ ) from exc
513
+
514
+
515
+ def delete_token(config: ProductConfig, workspace_id: str) -> bool:
516
+ """Remove one workspace's token, leaving the other workspaces signed in."""
517
+ try:
518
+ username = keyring_username(config, workspace_id)
519
+ if keyring.get_password(config.keyring_service, username) is None:
520
+ return False
521
+ try:
522
+ keyring.delete_password(config.keyring_service, username)
523
+ except PasswordDeleteError:
524
+ return False
525
+ return True
526
+ except KeyringError as exc:
527
+ raise AuthenticationError(f"Could not access OS keyring: {exc}") from exc