ermes-cli 1.3.0__tar.gz → 1.5.1__tar.gz

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 (76) hide show
  1. {ermes_cli-1.3.0 → ermes_cli-1.5.1}/PKG-INFO +15 -8
  2. {ermes_cli-1.3.0 → ermes_cli-1.5.1}/README.md +12 -6
  3. ermes_cli-1.5.1/ermes_cli/__init__.py +1 -0
  4. {ermes_cli-1.3.0 → ermes_cli-1.5.1}/ermes_cli/auth0.py +1 -1
  5. {ermes_cli-1.3.0 → ermes_cli-1.5.1}/ermes_cli/client.py +15 -10
  6. {ermes_cli-1.3.0 → ermes_cli-1.5.1}/ermes_cli/commands/auth_cmds.py +6 -7
  7. {ermes_cli-1.3.0 → ermes_cli-1.5.1}/ermes_cli/commands/campaigns.py +114 -0
  8. {ermes_cli-1.3.0 → ermes_cli-1.5.1}/ermes_cli/commands/export.py +9 -0
  9. {ermes_cli-1.3.0 → ermes_cli-1.5.1}/ermes_cli/config.py +7 -8
  10. {ermes_cli-1.3.0 → ermes_cli-1.5.1}/ermes_cli/export_utils.py +24 -0
  11. ermes_cli-1.5.1/ermes_cli/keyring_store.py +204 -0
  12. {ermes_cli-1.3.0 → ermes_cli-1.5.1}/ermes_cli/main.py +9 -4
  13. {ermes_cli-1.3.0 → ermes_cli-1.5.1}/ermes_cli/skill/SKILL.md +22 -0
  14. {ermes_cli-1.3.0 → ermes_cli-1.5.1}/pyproject.toml +6 -2
  15. {ermes_cli-1.3.0 → ermes_cli-1.5.1}/tests/conftest.py +5 -34
  16. {ermes_cli-1.3.0 → ermes_cli-1.5.1}/tests/test_auth_cmds.py +49 -11
  17. {ermes_cli-1.3.0 → ermes_cli-1.5.1}/tests/test_commands/test_campaigns.py +160 -0
  18. {ermes_cli-1.3.0 → ermes_cli-1.5.1}/tests/test_commands/test_export.py +66 -0
  19. {ermes_cli-1.3.0 → ermes_cli-1.5.1}/tests/test_commands/test_projects.py +2 -2
  20. ermes_cli-1.5.1/tests/test_connection_errors.py +40 -0
  21. ermes_cli-1.5.1/tests/test_keyring_store.py +217 -0
  22. {ermes_cli-1.3.0 → ermes_cli-1.5.1}/tests/test_write_mode.py +4 -4
  23. ermes_cli-1.3.0/ermes_cli/__init__.py +0 -1
  24. ermes_cli-1.3.0/ermes_cli/keyring_store.py +0 -145
  25. ermes_cli-1.3.0/tests/test_keyring_store.py +0 -185
  26. {ermes_cli-1.3.0 → ermes_cli-1.5.1}/.gitignore +0 -0
  27. {ermes_cli-1.3.0 → ermes_cli-1.5.1}/ermes_cli/admin_api.py +0 -0
  28. {ermes_cli-1.3.0 → ermes_cli-1.5.1}/ermes_cli/commands/__init__.py +0 -0
  29. {ermes_cli-1.3.0 → ermes_cli-1.5.1}/ermes_cli/commands/config_cmd.py +0 -0
  30. {ermes_cli-1.3.0 → ermes_cli-1.5.1}/ermes_cli/commands/data_paths.py +0 -0
  31. {ermes_cli-1.3.0 → ermes_cli-1.5.1}/ermes_cli/commands/ingest.py +0 -0
  32. {ermes_cli-1.3.0 → ermes_cli-1.5.1}/ermes_cli/commands/journeys.py +0 -0
  33. {ermes_cli-1.3.0 → ermes_cli-1.5.1}/ermes_cli/commands/keys.py +0 -0
  34. {ermes_cli-1.3.0 → ermes_cli-1.5.1}/ermes_cli/commands/lists.py +0 -0
  35. {ermes_cli-1.3.0 → ermes_cli-1.5.1}/ermes_cli/commands/metrics.py +0 -0
  36. {ermes_cli-1.3.0 → ermes_cli-1.5.1}/ermes_cli/commands/projects.py +0 -0
  37. {ermes_cli-1.3.0 → ermes_cli-1.5.1}/ermes_cli/commands/providers.py +0 -0
  38. {ermes_cli-1.3.0 → ermes_cli-1.5.1}/ermes_cli/commands/skill.py +0 -0
  39. {ermes_cli-1.3.0 → ermes_cli-1.5.1}/ermes_cli/commands/subscriptions.py +0 -0
  40. {ermes_cli-1.3.0 → ermes_cli-1.5.1}/ermes_cli/commands/tags.py +0 -0
  41. {ermes_cli-1.3.0 → ermes_cli-1.5.1}/ermes_cli/commands/templates.py +0 -0
  42. {ermes_cli-1.3.0 → ermes_cli-1.5.1}/ermes_cli/commands/users.py +0 -0
  43. {ermes_cli-1.3.0 → ermes_cli-1.5.1}/ermes_cli/commands/write_cmds.py +0 -0
  44. {ermes_cli-1.3.0 → ermes_cli-1.5.1}/ermes_cli/errors.py +0 -0
  45. {ermes_cli-1.3.0 → ermes_cli-1.5.1}/ermes_cli/output.py +0 -0
  46. {ermes_cli-1.3.0 → ermes_cli-1.5.1}/ermes_cli/rules.py +0 -0
  47. {ermes_cli-1.3.0 → ermes_cli-1.5.1}/ermes_cli/update.py +0 -0
  48. {ermes_cli-1.3.0 → ermes_cli-1.5.1}/ermes_cli/write_mode.py +0 -0
  49. {ermes_cli-1.3.0 → ermes_cli-1.5.1}/scripts/install-cli.sh +0 -0
  50. {ermes_cli-1.3.0 → ermes_cli-1.5.1}/tests/__init__.py +0 -0
  51. {ermes_cli-1.3.0 → ermes_cli-1.5.1}/tests/test_admin_api.py +0 -0
  52. {ermes_cli-1.3.0 → ermes_cli-1.5.1}/tests/test_auth0.py +0 -0
  53. {ermes_cli-1.3.0 → ermes_cli-1.5.1}/tests/test_client.py +0 -0
  54. {ermes_cli-1.3.0 → ermes_cli-1.5.1}/tests/test_commands/__init__.py +0 -0
  55. {ermes_cli-1.3.0 → ermes_cli-1.5.1}/tests/test_commands/test_data_paths.py +0 -0
  56. {ermes_cli-1.3.0 → ermes_cli-1.5.1}/tests/test_commands/test_ingest.py +0 -0
  57. {ermes_cli-1.3.0 → ermes_cli-1.5.1}/tests/test_commands/test_journeys.py +0 -0
  58. {ermes_cli-1.3.0 → ermes_cli-1.5.1}/tests/test_commands/test_keys.py +0 -0
  59. {ermes_cli-1.3.0 → ermes_cli-1.5.1}/tests/test_commands/test_lists.py +0 -0
  60. {ermes_cli-1.3.0 → ermes_cli-1.5.1}/tests/test_commands/test_metrics.py +0 -0
  61. {ermes_cli-1.3.0 → ermes_cli-1.5.1}/tests/test_commands/test_projects_list.py +0 -0
  62. {ermes_cli-1.3.0 → ermes_cli-1.5.1}/tests/test_commands/test_providers.py +0 -0
  63. {ermes_cli-1.3.0 → ermes_cli-1.5.1}/tests/test_commands/test_subscriptions.py +0 -0
  64. {ermes_cli-1.3.0 → ermes_cli-1.5.1}/tests/test_commands/test_tags.py +0 -0
  65. {ermes_cli-1.3.0 → ermes_cli-1.5.1}/tests/test_commands/test_templates.py +0 -0
  66. {ermes_cli-1.3.0 → ermes_cli-1.5.1}/tests/test_commands/test_users.py +0 -0
  67. {ermes_cli-1.3.0 → ermes_cli-1.5.1}/tests/test_config.py +0 -0
  68. {ermes_cli-1.3.0 → ermes_cli-1.5.1}/tests/test_export_utils.py +0 -0
  69. {ermes_cli-1.3.0 → ermes_cli-1.5.1}/tests/test_output.py +0 -0
  70. {ermes_cli-1.3.0 → ermes_cli-1.5.1}/tests/test_projects_config.py +0 -0
  71. {ermes_cli-1.3.0 → ermes_cli-1.5.1}/tests/test_rules.py +0 -0
  72. {ermes_cli-1.3.0 → ermes_cli-1.5.1}/tests/test_skill_command.py +0 -0
  73. {ermes_cli-1.3.0 → ermes_cli-1.5.1}/tests/test_update.py +0 -0
  74. {ermes_cli-1.3.0 → ermes_cli-1.5.1}/tests/test_version.py +0 -0
  75. {ermes_cli-1.3.0 → ermes_cli-1.5.1}/tests/test_whoami.py +0 -0
  76. {ermes_cli-1.3.0 → ermes_cli-1.5.1}/tests/test_write_cmds.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: ermes-cli
3
- Version: 1.3.0
3
+ Version: 1.5.1
4
4
  Summary: CLI-first access to Ermes marketing automation with Auth0 multi-project auth.
5
5
  Project-URL: Homepage, https://ermes.publinker.com
6
6
  Project-URL: Repository, https://github.com/Martech-DM/ermes
@@ -14,8 +14,9 @@ Classifier: Programming Language :: Python :: 3
14
14
  Classifier: Programming Language :: Python :: 3 :: Only
15
15
  Classifier: Topic :: Communications :: Email
16
16
  Requires-Python: >=3.10
17
+ Requires-Dist: cryptography<49,>=42.0; sys_platform == 'darwin' and platform_machine == 'x86_64'
18
+ Requires-Dist: cryptography>=42.0; sys_platform != 'darwin' or platform_machine != 'x86_64'
17
19
  Requires-Dist: httpx>=0.28
18
- Requires-Dist: keyring>=24.0
19
20
  Requires-Dist: pyyaml>=6.0
20
21
  Requires-Dist: requests>=2.31
21
22
  Requires-Dist: rich>=14.0
@@ -31,7 +32,9 @@ Description-Content-Type: text/markdown
31
32
 
32
33
  This package gives Ermes operators a CLI surface for explicit-project API reads and guarded writes.
33
34
 
34
- Version 1.2.0. It adds `ermes skill install` (DEV-2329). 1.1.0 removed the `ermes-mcp`
35
+ Version 1.4.0. It moves Auth0 tokens off the OS keychain into an encrypted 0600 file,
36
+ `~/.ermes/ermes-cli-token.json` (DEV-2392); run `ermes login` once after upgrading.
37
+ 1.2.0 added `ermes skill install` (DEV-2329). 1.1.0 removed the `ermes-mcp`
35
38
  compatibility server that 1.0.0 shipped (DEV-2326); a machine that registered it must drop that
36
39
  registration (e.g. `claude mcp remove ermes`).
37
40
 
@@ -101,7 +104,7 @@ one JSON document.
101
104
  `pipx install ermes-cli`) upgrades itself. `pipx upgrade` keeps the old venv if pip fails, so a
102
105
  failed upgrade never leaves you without a CLI. Editable checkouts (`git pull`), git or local-dir
103
106
  installs, non-pipx environments and an `ermes` that is not the venv pipx manages get the manual
104
- command instead of a prompt. Keychain tokens and `~/.ermes` are untouched.
107
+ command instead of a prompt. `~/.ermes` (tokens and projects) is untouched.
105
108
 
106
109
  ## Auth — Auth0 device login (recommended)
107
110
 
@@ -111,7 +114,7 @@ ermes projects list # show cached projects; keys stay masked
111
114
  ermes use <project-name-or-id> # interactive active-project selection
112
115
  ermes whoami # local selection only; not API liveness
113
116
  ermes projects refresh # re-sync after admins add you to new projects
114
- ermes logout # delete Keychain tokens + projects.yml
117
+ ermes logout # delete the token file + projects.yml
115
118
  ```
116
119
 
117
120
  `ermes login` runs an Auth0 Device Authorization Flow (RFC 8628) against the
@@ -128,9 +131,12 @@ authenticated user is your Auth0 identity). After authentication:
128
131
  admin account (revoked when you are removed from the project). Keys from the old
129
132
  `cli-managed-<hostname>` scheme are ignored.
130
133
 
131
- Auth0 tokens live in the OS keychain (`ermes-cli` service). On a headless box with no keyring
132
- backend they fall back to `~/.ermes/auth0-tokens.json` (chmod 600). Per-project `sk_` keys live
133
- in `~/.ermes/projects.yml`.
134
+ Auth0 tokens live in `~/.ermes/ermes-cli-token.json` (chmod 600), encrypted with a key derived
135
+ from this machine's id and your OS user, so a copied file is useless elsewhere. It is not the OS
136
+ keychain on purpose: macOS re-prompts "python3.x wants to use your confidential information" after
137
+ every Python upgrade, and Linux secret-service can pop an unlock dialog. **Upgrading from a version
138
+ below 1.4.0? Run `ermes login` once**; the old keychain item is never read (reading is what
139
+ prompts). Per-project `sk_` keys live in `~/.ermes/projects.yml`.
134
140
 
135
141
  For interactive work, `ermes use <project-name-or-id>` persists the active project. For every script
136
142
  or agent command, pin scope without changing that shared default:
@@ -262,6 +268,7 @@ is legible.
262
268
  | Group | Commands |
263
269
  |---|---|
264
270
  | `campaigns` | list, get, create, update, delete, trigger (`--external-id`, optional `--email`/`--phone`/`--device-token`/`--locale`/`--timezone`) |
271
+ | `campaigns split-test` | set (`--percent`/`--window`/`--metric open\|click`), disable (`--yes`), results — A/B tests on draft blasts; `export campaigns` adds per-variant `split_test` |
265
272
  | `templates` | list, get, create, update, delete |
266
273
  | `lists` | list, get, create, update, delete |
267
274
  | `journeys` | list, get, create, update, delete |
@@ -2,7 +2,9 @@
2
2
 
3
3
  This package gives Ermes operators a CLI surface for explicit-project API reads and guarded writes.
4
4
 
5
- Version 1.2.0. It adds `ermes skill install` (DEV-2329). 1.1.0 removed the `ermes-mcp`
5
+ Version 1.4.0. It moves Auth0 tokens off the OS keychain into an encrypted 0600 file,
6
+ `~/.ermes/ermes-cli-token.json` (DEV-2392); run `ermes login` once after upgrading.
7
+ 1.2.0 added `ermes skill install` (DEV-2329). 1.1.0 removed the `ermes-mcp`
6
8
  compatibility server that 1.0.0 shipped (DEV-2326); a machine that registered it must drop that
7
9
  registration (e.g. `claude mcp remove ermes`).
8
10
 
@@ -72,7 +74,7 @@ one JSON document.
72
74
  `pipx install ermes-cli`) upgrades itself. `pipx upgrade` keeps the old venv if pip fails, so a
73
75
  failed upgrade never leaves you without a CLI. Editable checkouts (`git pull`), git or local-dir
74
76
  installs, non-pipx environments and an `ermes` that is not the venv pipx manages get the manual
75
- command instead of a prompt. Keychain tokens and `~/.ermes` are untouched.
77
+ command instead of a prompt. `~/.ermes` (tokens and projects) is untouched.
76
78
 
77
79
  ## Auth — Auth0 device login (recommended)
78
80
 
@@ -82,7 +84,7 @@ ermes projects list # show cached projects; keys stay masked
82
84
  ermes use <project-name-or-id> # interactive active-project selection
83
85
  ermes whoami # local selection only; not API liveness
84
86
  ermes projects refresh # re-sync after admins add you to new projects
85
- ermes logout # delete Keychain tokens + projects.yml
87
+ ermes logout # delete the token file + projects.yml
86
88
  ```
87
89
 
88
90
  `ermes login` runs an Auth0 Device Authorization Flow (RFC 8628) against the
@@ -99,9 +101,12 @@ authenticated user is your Auth0 identity). After authentication:
99
101
  admin account (revoked when you are removed from the project). Keys from the old
100
102
  `cli-managed-<hostname>` scheme are ignored.
101
103
 
102
- Auth0 tokens live in the OS keychain (`ermes-cli` service). On a headless box with no keyring
103
- backend they fall back to `~/.ermes/auth0-tokens.json` (chmod 600). Per-project `sk_` keys live
104
- in `~/.ermes/projects.yml`.
104
+ Auth0 tokens live in `~/.ermes/ermes-cli-token.json` (chmod 600), encrypted with a key derived
105
+ from this machine's id and your OS user, so a copied file is useless elsewhere. It is not the OS
106
+ keychain on purpose: macOS re-prompts "python3.x wants to use your confidential information" after
107
+ every Python upgrade, and Linux secret-service can pop an unlock dialog. **Upgrading from a version
108
+ below 1.4.0? Run `ermes login` once**; the old keychain item is never read (reading is what
109
+ prompts). Per-project `sk_` keys live in `~/.ermes/projects.yml`.
105
110
 
106
111
  For interactive work, `ermes use <project-name-or-id>` persists the active project. For every script
107
112
  or agent command, pin scope without changing that shared default:
@@ -233,6 +238,7 @@ is legible.
233
238
  | Group | Commands |
234
239
  |---|---|
235
240
  | `campaigns` | list, get, create, update, delete, trigger (`--external-id`, optional `--email`/`--phone`/`--device-token`/`--locale`/`--timezone`) |
241
+ | `campaigns split-test` | set (`--percent`/`--window`/`--metric open\|click`), disable (`--yes`), results — A/B tests on draft blasts; `export campaigns` adds per-variant `split_test` |
236
242
  | `templates` | list, get, create, update, delete |
237
243
  | `lists` | list, get, create, update, delete |
238
244
  | `journeys` | list, get, create, update, delete |
@@ -0,0 +1 @@
1
+ __version__ = "1.5.1"
@@ -12,7 +12,7 @@ Three operations:
12
12
  access token (Auth0 rotates the refresh token; we carry the old one
13
13
  forward if the response omits a new one).
14
14
 
15
- All three are pure: no keychain writes. The caller decides what to persist.
15
+ All three are pure: no token-file writes. The caller decides what to persist.
16
16
  """
17
17
 
18
18
  from __future__ import annotations
@@ -50,32 +50,37 @@ class ErmesClient:
50
50
  raise ErmesAPIError(f"{label}: {detail}", status)
51
51
  raise ErmesAPIError(f"Server error: {status}", status)
52
52
 
53
- def get(self, path: str, params: dict | None = None) -> Any:
54
- response = self._client.get(path, params=params)
53
+ def _send(self, method: str, path: str, **kwargs: Any) -> Any:
54
+ try:
55
+ response = getattr(self._client, method)(path, **kwargs)
56
+ except httpx.TransportError as e:
57
+ # Type name + host only: the exception text can echo the Bearer header (DEV-2261).
58
+ url = self._client.base_url
59
+ host = f"{url.host}:{url.port}" if url.port else url.host
60
+ raise ErmesAPIError(f"could not reach {host}: {type(e).__name__}") from None
55
61
  return self._handle_response(response)
56
62
 
63
+ def get(self, path: str, params: dict | None = None) -> Any:
64
+ return self._send("get", path, params=params)
65
+
57
66
  def post(self, path: str, json: dict | None = None, *, read_only: bool = False) -> Any:
58
67
  # read_only: a POST the server treats as a pure read (e.g. template preview),
59
68
  # so the write guard has nothing to protect.
60
69
  if not read_only:
61
70
  assert_writes_allowed("POST", path)
62
- response = self._client.post(path, json=json)
63
- return self._handle_response(response)
71
+ return self._send("post", path, json=json)
64
72
 
65
73
  def patch(self, path: str, json: dict | None = None) -> Any:
66
74
  assert_writes_allowed("PATCH", path)
67
- response = self._client.patch(path, json=json)
68
- return self._handle_response(response)
75
+ return self._send("patch", path, json=json)
69
76
 
70
77
  def put(self, path: str, json: dict | None = None) -> Any:
71
78
  assert_writes_allowed("PUT", path)
72
- response = self._client.put(path, json=json)
73
- return self._handle_response(response)
79
+ return self._send("put", path, json=json)
74
80
 
75
81
  def delete(self, path: str) -> Any:
76
82
  assert_writes_allowed("DELETE", path)
77
- response = self._client.delete(path)
78
- return self._handle_response(response)
83
+ return self._send("delete", path)
79
84
 
80
85
  MAX_PAGES = 500
81
86
 
@@ -5,7 +5,6 @@ from __future__ import annotations
5
5
  import re
6
6
  import socket
7
7
 
8
- import keyring
9
8
  import typer
10
9
  from rich.console import Console
11
10
  from rich.table import Table
@@ -143,7 +142,7 @@ def _ensure_admin_session(
143
142
  ) -> tuple[str, admin_api.ExchangeResult]:
144
143
  """Return `(api_base, exchange_result)` using cached Auth0 tokens.
145
144
 
146
- Loads the keychain bundle, transparently refreshes the Auth0 access token
145
+ Loads the token-file bundle, transparently refreshes the Auth0 access token
147
146
  via the cached refresh_token when it has expired, then exchanges it for an
148
147
  Ermes admin JWT via `/api/cli/exchange`. Exits (code 1) with an actionable
149
148
  message when the user isn't logged in, the refresh token is dead, or the
@@ -230,7 +229,7 @@ def login(
230
229
 
231
230
  What this does:
232
231
  1. Starts an Auth0 device flow against the shared `dev-hqiwr-re` tenant.
233
- 2. Stores the resulting Auth0 tokens in your OS keychain (`ermes-cli` service).
232
+ 2. Stores the resulting Auth0 tokens encrypted in `~/.ermes/ermes-cli-token.json` (chmod 600).
234
233
  3. Trades the Auth0 access token for an Ermes admin JWT via /api/cli/exchange.
235
234
  4. Calls /api/admin/projects/all to enumerate every project you can see.
236
235
  5. Caches the list in `~/.ermes/projects.yml` (chmod 600).
@@ -250,7 +249,7 @@ def login(
250
249
 
251
250
  bundle.base_url = base_url
252
251
  keyring_store.save(bundle)
253
- console.print("[green]✓[/green] Auth0 tokens stored in OS keychain.")
252
+ console.print("[green]✓[/green] Auth0 tokens stored in ~/.ermes/ermes-cli-token.json (encrypted, 0600).")
254
253
 
255
254
  try:
256
255
  result = admin_api.exchange_auth0_token(
@@ -269,7 +268,7 @@ def login(
269
268
  stored.get("auth0_email") != result.admin_email
270
269
  or str(stored.get("base_url") or "").rstrip("/") != base_url.rstrip("/")
271
270
  ):
272
- # The keyring now holds this admin's tokens; the previous admin's cached
271
+ # The token file now holds this admin's tokens; the previous admin's cached
273
272
  # keys must not outlive the login even if discovery stops early.
274
273
  clear_projects_file()
275
274
  console.print()
@@ -326,8 +325,8 @@ def logout() -> None:
326
325
  console.print("[yellow]Could not revoke the refresh token at Auth0; it expires on its own.[/yellow]")
327
326
  try:
328
327
  keyring_store.clear()
329
- except keyring.errors.KeyringError as exc:
330
- console.print(f"[red]Could not remove the Auth0 tokens from the keyring:[/red] {exc}")
328
+ except OSError as exc:
329
+ console.print(f"[red]Could not remove the Auth0 token file:[/red] {exc}")
331
330
  raise typer.Exit(code=1)
332
331
  finally:
333
332
  clear_projects_file()
@@ -319,3 +319,117 @@ def campaigns_trigger(
319
319
  except ErmesAPIError as e:
320
320
  typer.echo(str(e), err=True)
321
321
  raise typer.Exit(code=1)
322
+
323
+
324
+ split_test_app = typer.Typer(help="A/B split tests on blasts", no_args_is_help=True)
325
+ campaigns_app.add_typer(split_test_app, name="split-test")
326
+
327
+ SPLIT_TEST_DEFAULTS = {"percent": 10, "window_minutes": 60, "metric": "email_open"}
328
+ _METRICS = {"open": "email_open", "click": "email_click"}
329
+ _RESULT_COLUMNS = ["label", "template_id", "subject", "assigned", "sent", "opens", "clicks", "open_rate", "click_rate", "winner"]
330
+
331
+
332
+ @split_test_app.command("set")
333
+ def split_test_set(
334
+ campaign_id: int = typer.Argument(..., help="Blast campaign ID (must be a draft)"),
335
+ percent: Optional[int] = typer.Option(None, "--percent", min=1, max=50, help="Test group size, % of the list split between A and B (default 10)"),
336
+ window: Optional[int] = typer.Option(None, "--window", help="Minutes before the winner is picked: 30, 60, 90, 120, 150 or 180 (default 60)"),
337
+ metric: Optional[str] = typer.Option(None, "--metric", help="Winner metric: open or click (default open)"),
338
+ ):
339
+ """Enable or change a split test. Enabling creates variant A (current template) and B (a copy to edit)."""
340
+ client, st, _, _, _ = _get_deps()
341
+ if metric is not None and metric not in _METRICS:
342
+ typer.echo("--metric must be 'open' or 'click'", err=True)
343
+ raise typer.Exit(code=1)
344
+ if window is not None and window not in (30, 60, 90, 120, 150, 180):
345
+ typer.echo("--window must be one of 30, 60, 90, 120, 150, 180", err=True)
346
+ raise typer.Exit(code=1)
347
+ try:
348
+ campaign = client.get(f"/campaigns/{campaign_id}")
349
+ if campaign.get("type") != "blast":
350
+ typer.echo(f"Split tests run on blasts only; campaign {campaign_id} is a {campaign.get('type')}.", err=True)
351
+ raise typer.Exit(code=1)
352
+ current = campaign.get("split_test_config") or {}
353
+ base = current if current.get("enabled") else SPLIT_TEST_DEFAULTS
354
+ config = {
355
+ "enabled": True,
356
+ "percent": percent if percent is not None else base["percent"],
357
+ "window_minutes": window if window is not None else base["window_minutes"],
358
+ "metric": _METRICS[metric] if metric else base["metric"],
359
+ # Server-managed: the API overwrites these from the stored row.
360
+ "picker_state": current.get("picker_state") or "pending",
361
+ "extended_once": bool(current.get("extended_once")),
362
+ }
363
+ result = client.patch(f"/campaigns/{campaign_id}", json={"split_test_config": config})
364
+ except ErmesAPIError as e:
365
+ typer.echo(str(e), err=True)
366
+ raise typer.Exit(code=1)
367
+ variants = [
368
+ {"label": v.get("label"), "variant_id": v.get("id"), "template_id": v.get("template_id")}
369
+ for v in result.get("variants") or []
370
+ ]
371
+ if st.use_json:
372
+ print(json_lib.dumps({"split_test_config": result.get("split_test_config"), "variants": variants}, indent=2))
373
+ return
374
+ cfg = result.get("split_test_config") or config
375
+ typer.echo(f"Split test on campaign {campaign_id}: {cfg['percent']}% test group, {cfg['window_minutes']} min window, winner by {cfg['metric']}.")
376
+ for v in variants:
377
+ typer.echo(f" {v['label']}: variant {v['variant_id']}, template {v['template_id']}")
378
+ b = next((v for v in variants if v["label"] == "B"), None)
379
+ if b:
380
+ typer.echo(f"Edit B with: ermes templates update {b['template_id']} --type email --data '{{...}}'")
381
+
382
+
383
+ @split_test_app.command("disable")
384
+ def split_test_disable(
385
+ campaign_id: int = typer.Argument(..., help="Blast campaign ID (must be a draft)"),
386
+ yes: bool = typer.Option(False, "--yes", help="Confirm: disabling deletes variant B and its template"),
387
+ ):
388
+ """Disable a split test. Deletes variant B and its template; A stays as the campaign template."""
389
+ client, st, _, _, render_message = _get_deps()
390
+ if not yes:
391
+ typer.echo("Disabling deletes variant B and its template (any edits to B are lost). Re-run with --yes.", err=True)
392
+ raise typer.Exit(code=1)
393
+ try:
394
+ current = client.get(f"/campaigns/{campaign_id}").get("split_test_config") or {}
395
+ if not current.get("enabled"):
396
+ render_message(f"Campaign {campaign_id} has no split test enabled.", use_json=st.use_json)
397
+ return
398
+ config = {
399
+ "enabled": False,
400
+ "percent": current["percent"],
401
+ "window_minutes": current["window_minutes"],
402
+ "metric": current["metric"],
403
+ "picker_state": current.get("picker_state") or "pending",
404
+ "extended_once": bool(current.get("extended_once")),
405
+ }
406
+ client.patch(f"/campaigns/{campaign_id}", json={"split_test_config": config})
407
+ render_message(f"Split test disabled on campaign {campaign_id}.", use_json=st.use_json)
408
+ except ErmesAPIError as e:
409
+ typer.echo(str(e), err=True)
410
+ raise typer.Exit(code=1)
411
+
412
+
413
+ @split_test_app.command("results")
414
+ def split_test_results(campaign_id: int = typer.Argument(..., help="Campaign ID")):
415
+ """Per-variant sends, opens and clicks for the test group, plus the rest of the list (sent the winner)."""
416
+ from ermes_cli.export_utils import summarize_split_test
417
+
418
+ client, st, render, _, render_message = _get_deps()
419
+ try:
420
+ summary = summarize_split_test(client.get(f"/campaigns/{campaign_id}/split-test/results"))
421
+ except ErmesAPIError as e:
422
+ typer.echo(str(e), err=True)
423
+ raise typer.Exit(code=1)
424
+ if st.use_json:
425
+ print(json_lib.dumps(summary, indent=2, default=str))
426
+ return
427
+ if not summary["enabled"]:
428
+ render_message(f"Campaign {campaign_id} has no split test enabled.", use_json=False)
429
+ return
430
+ rows = summary["variants"] + [{"label": "rest", **summary["remainder"]}]
431
+ cfg = summary["config"] or {}
432
+ title = f"{cfg.get('percent')}% test group, winner by {cfg.get('metric')} ({cfg.get('picker_state')}). Rates are % of sent."
433
+ title += ' "rest" = the rest of the list, sent the winner.'
434
+ labels = {"label": "variant", "template_id": "template", "open_rate": "open %", "click_rate": "click %"}
435
+ render(rows, columns=_RESULT_COLUMNS, use_json=False, title=title, column_labels=labels)
@@ -9,6 +9,7 @@ from ermes_cli.client import ErmesAPIError, ErmesClient
9
9
  from ermes_cli.export_utils import (
10
10
  extract_campaign_record,
11
11
  is_within_date_range,
12
+ summarize_split_test,
12
13
  )
13
14
 
14
15
  export_app = typer.Typer(
@@ -79,6 +80,14 @@ def _enrich_campaigns(
79
80
  detail = client.get(f"/campaigns/{c['id']}")
80
81
  record = extract_campaign_record(detail, project_timezone)
81
82
  if record:
83
+ # Per-variant counts cost one extra request, so only split-test blasts pay it.
84
+ if (detail.get("split_test_config") or {}).get("enabled"):
85
+ try:
86
+ results = client.get(f"/campaigns/{c['id']}/split-test/results")
87
+ record["split_test"] = summarize_split_test(results)
88
+ except ErmesAPIError as e:
89
+ # Keep the campaign row; only its per-variant block is missing.
90
+ record["split_test"] = {"error": str(e)}
82
91
  enriched.append(record)
83
92
  except ErmesAPIError:
84
93
  skipped += 1
@@ -34,6 +34,7 @@ from __future__ import annotations
34
34
  import contextlib
35
35
  import os
36
36
  import sys
37
+ import tempfile
37
38
  from pathlib import Path
38
39
  from typing import Any
39
40
 
@@ -84,17 +85,15 @@ def load_config() -> dict:
84
85
  def _open_private(path: Path):
85
86
  """Write `path` atomically as a fresh 0600 file.
86
87
 
87
- The bytes go to a sibling temp file opened O_EXCL|O_NOFOLLOW (a planted
88
- symlink or stale temp is never followed), then `os.replace` swaps it in: a
89
- reader sees the old file or the new one, never a truncated one, and a
88
+ The bytes go to a uniquely named sibling temp file from `mkstemp` (0600,
89
+ O_EXCL, so a planted symlink is never followed and two concurrent writers
90
+ never share a temp — DEV-2404), then `os.replace` swaps it in: a reader
91
+ sees the old file or the new one, never a truncated one, and a
90
92
  pre-existing wide-mode file or symlink is replaced by a fresh 0600 inode.
91
93
  """
92
- tmp = path.with_name(path.name + ".tmp")
93
- tmp.unlink(missing_ok=True)
94
- fd = os.open(tmp, os.O_WRONLY | os.O_CREAT | os.O_EXCL | getattr(os, "O_NOFOLLOW", 0), 0o600)
94
+ fd, tmp_name = tempfile.mkstemp(dir=path.parent, prefix=path.name + ".", suffix=".tmp")
95
+ tmp = Path(tmp_name)
95
96
  try:
96
- if hasattr(os, "fchmod"): # absent on Windows < 3.13; the 0o600 at open still applies
97
- os.fchmod(fd, 0o600)
98
97
  f = os.fdopen(fd, "w")
99
98
  except OSError:
100
99
  os.close(fd)
@@ -261,3 +261,27 @@ def sanitize_filename(subject: str, date_str: str) -> str:
261
261
 
262
262
  return f"blast_{date_formatted}_{clean}.html" if clean else f"blast_{date_formatted}.html"
263
263
 
264
+
265
+ def _with_rates(counts: dict) -> dict:
266
+ sent = counts.get("sent", 0) or 0
267
+ opens = counts.get("opens", 0) or 0
268
+ clicks = counts.get("clicks", 0) or 0
269
+ return {
270
+ **counts,
271
+ "open_rate": round(opens / sent * 100, 2) if sent else 0,
272
+ "click_rate": round(clicks / sent * 100, 2) if sent else 0,
273
+ }
274
+
275
+
276
+ def summarize_split_test(results: dict) -> dict:
277
+ """Add open/click rates (percent of sent) to a split-test results payload.
278
+
279
+ `variants` are the test group only; `remainder` is the rest of the list,
280
+ sent the winner after the decision, so it never counts toward a variant.
281
+ """
282
+ return {
283
+ "enabled": results.get("enabled", False),
284
+ "config": results.get("config"),
285
+ "variants": [_with_rates(v) for v in results.get("variants", [])],
286
+ "remainder": _with_rates(results.get("remainder") or {}),
287
+ }
@@ -0,0 +1,204 @@
1
+ """Auth0 token storage: one encrypted JSON file, mode 0600, in `~/.ermes`.
2
+
3
+ Not the OS vault. macOS ties a Keychain item to the exact Python binary that
4
+ wrote it, so every Python upgrade made the next command ask "python3.x wants
5
+ to use your confidential information stored in 'ermes-cli'", and Linux
6
+ secret-service can pop an unlock dialog. A 0600 file is the same trade-off as
7
+ ~/.aws/credentials and gcloud, and never prompts. Tokens an older version left
8
+ in the vault are not read (reading prompts); users run `ermes login` once.
9
+
10
+ The bundle is Fernet-encrypted with a key derived from this machine's id and
11
+ the OS user, so a copy of the file (a backup, a dotfile sync, a leaked
12
+ archive) is useless elsewhere. It does not stop a process running as the same
13
+ user on the same machine; nothing short of an OS vault does. (DEV-2392, same
14
+ design as publinker-cli DEV-2388.)
15
+
16
+ This module ONLY deals with Auth0 tokens. Per-project Ermes API keys live in
17
+ `~/.ermes/projects.yml` (managed by `config.py`).
18
+ """
19
+
20
+ from __future__ import annotations
21
+
22
+ import base64
23
+ import functools
24
+ import json
25
+ import os
26
+ import re
27
+ import subprocess # nosec B404
28
+ import sys
29
+ import time
30
+ import uuid
31
+ from dataclasses import asdict, dataclass
32
+ from pathlib import Path
33
+
34
+ from cryptography.fernet import Fernet, InvalidToken
35
+ from cryptography.hazmat.primitives import hashes
36
+ from cryptography.hazmat.primitives.kdf.hkdf import HKDF
37
+
38
+ from ermes_cli.config import _config_dir, _open_private
39
+
40
+ KEYRING_SERVICE = "ermes-cli" # kept: names the token file
41
+
42
+
43
+ def _token_file() -> Path:
44
+ return _config_dir() / f"{KEYRING_SERVICE}-token.json"
45
+
46
+
47
+ def _legacy_plaintext_file() -> Path:
48
+ """Pre-1.4 headless fallback: the bundle in clear text. Never read, always removed."""
49
+ return _config_dir() / "auth0-tokens.json"
50
+
51
+
52
+ @dataclass
53
+ class TokenBundle:
54
+ access_token: str
55
+ refresh_token: str
56
+ id_token: str
57
+ expires_at: int # unix epoch seconds
58
+ base_url: str = "" # the Ermes host these tokens were obtained for (DEV-2261)
59
+
60
+ @classmethod
61
+ def from_token_response(
62
+ cls, body: dict, now: int | None = None
63
+ ) -> TokenBundle:
64
+ """Build a bundle from Auth0's `/oauth/token` response."""
65
+ now = now if now is not None else int(time.time())
66
+ return cls(
67
+ access_token=body["access_token"],
68
+ refresh_token=body.get("refresh_token", ""),
69
+ id_token=body.get("id_token", ""),
70
+ expires_at=now + int(body.get("expires_in", 0)),
71
+ )
72
+
73
+ def is_expired(self, now: int | None = None, leeway: int = 60) -> bool:
74
+ """True if the access token OR the id_token has expired (with `leeway` seconds buffer).
75
+
76
+ The id_token counts because `/api/cli/exchange` verifies it to read the admin's
77
+ email (the access token has no email claim), and Auth0 issues it for 10h against
78
+ the access token's 24h. Checking only the access token made every admin command
79
+ fail with 1010 from hour 10 to hour 24 after login (DEV-2497).
80
+ """
81
+ now = now if now is not None else int(time.time())
82
+ id_exp = _jwt_exp(self.id_token)
83
+ deadline = min(self.expires_at, id_exp) if id_exp is not None else self.expires_at
84
+ return now + leeway >= deadline
85
+
86
+
87
+ def _jwt_exp(token: str) -> int | None:
88
+ """The unverified `exp` claim of a JWT, or None if it can't be read.
89
+
90
+ Only a local "time to refresh?" hint; the server still verifies the signature.
91
+ """
92
+ try:
93
+ payload = token.split(".")[1]
94
+ exp = json.loads(base64.urlsafe_b64decode(payload + "=" * (-len(payload) % 4))).get("exp")
95
+ # bool is an int subclass: `"exp": true` would read as epoch 1 and refresh every command.
96
+ return int(exp) if isinstance(exp, (int, float)) and not isinstance(exp, bool) else None
97
+ except (IndexError, ValueError, AttributeError, OverflowError, RecursionError):
98
+ # int(inf) -> OverflowError, int(nan) -> ValueError, deeply nested JSON -> RecursionError
99
+ return None
100
+
101
+
102
+ @functools.cache
103
+ def _machine_id() -> str:
104
+ """A stable per-machine id; falls back to the MAC address."""
105
+ try:
106
+ if sys.platform == "darwin":
107
+ out = subprocess.run( # nosec B603
108
+ ["/usr/sbin/ioreg", "-rd1", "-c", "IOPlatformExpertDevice"],
109
+ check=False,
110
+ capture_output=True,
111
+ text=True,
112
+ timeout=5,
113
+ ).stdout
114
+ found = re.search(r'"IOPlatformUUID" = "([^"]+)"', out)
115
+ if found:
116
+ return found.group(1)
117
+ elif sys.platform == "win32":
118
+ import winreg
119
+
120
+ with winreg.OpenKey(
121
+ winreg.HKEY_LOCAL_MACHINE, r"SOFTWARE\Microsoft\Cryptography"
122
+ ) as key:
123
+ return str(winreg.QueryValueEx(key, "MachineGuid")[0])
124
+ else:
125
+ for candidate in ("/etc/machine-id", "/var/lib/dbus/machine-id"):
126
+ try:
127
+ value = Path(candidate).read_text().strip()
128
+ except OSError:
129
+ continue
130
+ if value:
131
+ return value
132
+ except (OSError, subprocess.SubprocessError):
133
+ pass
134
+ return _generated_machine_id()
135
+
136
+
137
+ def _generated_machine_id() -> str:
138
+ """No OS id (slim containers): keep one generated id next to the token.
139
+ `uuid.getnode()` is random per process on a host without a NIC, so a
140
+ token saved under it could never be read back."""
141
+ path = _config_dir() / "machine-id"
142
+ try:
143
+ value = path.read_text().strip()
144
+ except OSError:
145
+ value = ""
146
+ if value:
147
+ return value
148
+ try:
149
+ path.parent.mkdir(parents=True, exist_ok=True)
150
+ value = uuid.uuid4().hex
151
+ with _open_private(path) as f:
152
+ f.write(value)
153
+ return value
154
+ except OSError:
155
+ return str(uuid.getnode()) # read-only home: survives this process only
156
+
157
+
158
+ def _fernet(salt: bytes) -> Fernet:
159
+ user = str(os.getuid()) if hasattr(os, "getuid") else os.environ.get("USERNAME", "")
160
+ key = HKDF(
161
+ algorithm=hashes.SHA256(),
162
+ length=32,
163
+ salt=salt,
164
+ info=b"ermes-cli token v1",
165
+ ).derive(f"{_machine_id()}:{user}".encode())
166
+ return Fernet(base64.urlsafe_b64encode(key))
167
+
168
+
169
+ def save(bundle: TokenBundle) -> None:
170
+ path = _token_file()
171
+ path.parent.mkdir(parents=True, exist_ok=True)
172
+ salt = os.urandom(16)
173
+ token = _fernet(salt).encrypt(json.dumps(asdict(bundle)).encode())
174
+ # _open_private: fresh 0600 inode swapped in atomically, so a pre-existing
175
+ # wide-mode file or symlink never survives a save.
176
+ with _open_private(path) as f:
177
+ json.dump(
178
+ {"v": 1, "salt": base64.urlsafe_b64encode(salt).decode(), "token": token.decode()},
179
+ f,
180
+ )
181
+ try:
182
+ _legacy_plaintext_file().unlink(missing_ok=True)
183
+ except OSError:
184
+ pass # the new bundle is on disk; the legacy file is clear()'s job too
185
+
186
+
187
+ def load() -> TokenBundle | None:
188
+ try:
189
+ envelope = json.loads(_token_file().read_bytes())
190
+ salt = base64.urlsafe_b64decode(envelope["salt"])
191
+ data = _fernet(salt).decrypt(envelope["token"].encode())
192
+ return TokenBundle(**json.loads(data))
193
+ except (OSError, TypeError, KeyError, ValueError, AttributeError, InvalidToken):
194
+ # Corrupted, or copied from another machine/user — treat as logged out.
195
+ # The next login overwrites it.
196
+ return None
197
+
198
+
199
+ def clear() -> None:
200
+ """Remove the stored tokens. Raises `OSError` when the file cannot be
201
+ removed, so `logout` cannot report success while the token is still on
202
+ disk. An absent file is already cleared."""
203
+ _token_file().unlink(missing_ok=True)
204
+ _legacy_plaintext_file().unlink(missing_ok=True)