chattermate-cli 0.7.0__tar.gz → 0.8.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 (40) hide show
  1. {chattermate_cli-0.7.0 → chattermate_cli-0.8.1}/PKG-INFO +5 -1
  2. {chattermate_cli-0.7.0 → chattermate_cli-0.8.1}/README.md +4 -0
  3. {chattermate_cli-0.7.0 → chattermate_cli-0.8.1}/chattermate_cli/__init__.py +1 -1
  4. chattermate_cli-0.8.1/chattermate_cli/agent_env.py +42 -0
  5. {chattermate_cli-0.7.0 → chattermate_cli-0.8.1}/chattermate_cli/client.py +5 -1
  6. {chattermate_cli-0.7.0 → chattermate_cli-0.8.1}/chattermate_cli/commands/auth.py +57 -12
  7. {chattermate_cli-0.7.0 → chattermate_cli-0.8.1}/chattermate_cli/commands/widget.py +26 -3
  8. {chattermate_cli-0.7.0 → chattermate_cli-0.8.1}/chattermate_cli.egg-info/PKG-INFO +5 -1
  9. {chattermate_cli-0.7.0 → chattermate_cli-0.8.1}/chattermate_cli.egg-info/SOURCES.txt +3 -0
  10. {chattermate_cli-0.7.0 → chattermate_cli-0.8.1}/pyproject.toml +1 -1
  11. chattermate_cli-0.8.1/tests/test_auth.py +142 -0
  12. chattermate_cli-0.8.1/tests/test_signup_attribution.py +114 -0
  13. {chattermate_cli-0.7.0 → chattermate_cli-0.8.1}/tests/test_widget.py +17 -0
  14. {chattermate_cli-0.7.0 → chattermate_cli-0.8.1}/LICENSE +0 -0
  15. {chattermate_cli-0.7.0 → chattermate_cli-0.8.1}/chattermate_cli/commands/__init__.py +0 -0
  16. {chattermate_cli-0.7.0 → chattermate_cli-0.8.1}/chattermate_cli/commands/agent.py +0 -0
  17. {chattermate_cli-0.7.0 → chattermate_cli-0.8.1}/chattermate_cli/commands/ai.py +0 -0
  18. {chattermate_cli-0.7.0 → chattermate_cli-0.8.1}/chattermate_cli/commands/customization.py +0 -0
  19. {chattermate_cli-0.7.0 → chattermate_cli-0.8.1}/chattermate_cli/commands/help_center.py +0 -0
  20. {chattermate_cli-0.7.0 → chattermate_cli-0.8.1}/chattermate_cli/commands/knowledge.py +0 -0
  21. {chattermate_cli-0.7.0 → chattermate_cli-0.8.1}/chattermate_cli/commands/lead_capture.py +0 -0
  22. {chattermate_cli-0.7.0 → chattermate_cli-0.8.1}/chattermate_cli/commands/ticketing.py +0 -0
  23. {chattermate_cli-0.7.0 → chattermate_cli-0.8.1}/chattermate_cli/commands/workflow.py +0 -0
  24. {chattermate_cli-0.7.0 → chattermate_cli-0.8.1}/chattermate_cli/config.py +0 -0
  25. {chattermate_cli-0.7.0 → chattermate_cli-0.8.1}/chattermate_cli/context.py +0 -0
  26. {chattermate_cli-0.7.0 → chattermate_cli-0.8.1}/chattermate_cli/main.py +0 -0
  27. {chattermate_cli-0.7.0 → chattermate_cli-0.8.1}/chattermate_cli/mcp_server.py +0 -0
  28. {chattermate_cli-0.7.0 → chattermate_cli-0.8.1}/chattermate_cli.egg-info/dependency_links.txt +0 -0
  29. {chattermate_cli-0.7.0 → chattermate_cli-0.8.1}/chattermate_cli.egg-info/entry_points.txt +0 -0
  30. {chattermate_cli-0.7.0 → chattermate_cli-0.8.1}/chattermate_cli.egg-info/requires.txt +0 -0
  31. {chattermate_cli-0.7.0 → chattermate_cli-0.8.1}/chattermate_cli.egg-info/top_level.txt +0 -0
  32. {chattermate_cli-0.7.0 → chattermate_cli-0.8.1}/setup.cfg +0 -0
  33. {chattermate_cli-0.7.0 → chattermate_cli-0.8.1}/tests/test_ai.py +0 -0
  34. {chattermate_cli-0.7.0 → chattermate_cli-0.8.1}/tests/test_client.py +0 -0
  35. {chattermate_cli-0.7.0 → chattermate_cli-0.8.1}/tests/test_customization.py +0 -0
  36. {chattermate_cli-0.7.0 → chattermate_cli-0.8.1}/tests/test_help_center.py +0 -0
  37. {chattermate_cli-0.7.0 → chattermate_cli-0.8.1}/tests/test_knowledge.py +0 -0
  38. {chattermate_cli-0.7.0 → chattermate_cli-0.8.1}/tests/test_lead_capture.py +0 -0
  39. {chattermate_cli-0.7.0 → chattermate_cli-0.8.1}/tests/test_mcp.py +0 -0
  40. {chattermate_cli-0.7.0 → chattermate_cli-0.8.1}/tests/test_ticketing.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: chattermate-cli
3
- Version: 0.7.0
3
+ Version: 0.8.1
4
4
  Summary: ChatterMate CLI and MCP server — sign up, authenticate, and configure agents, workflows and knowledge from the terminal or an AI agent.
5
5
  Author: ChatterMate
6
6
  License: AGPL-3.0-or-later
@@ -48,6 +48,8 @@ local or self-hosted backend, set `CHATTERMATE_API_URL=http://localhost:8000` (o
48
48
  # Create an organization + admin (community signup), or log in to an existing one
49
49
  chattermate signup
50
50
  chattermate login --email you@acme.com
51
+ # Signed up with Google or Microsoft? Create a token in Settings → CLI & API tokens, then:
52
+ chattermate login --token
51
53
 
52
54
  chattermate whoami
53
55
 
@@ -83,6 +85,8 @@ Two credentials are supported:
83
85
  the `CHATTERMATE_TOKEN` environment variable. Long-lived and revocable.
84
86
  - **JWT login** — `chattermate login` stores access + refresh tokens in
85
87
  `~/.chattermate/config.json` (mode `600`) and refreshes automatically.
88
+ `chattermate login --token` stores a PAT there instead, read from a hidden prompt —
89
+ the way to log in for accounts that use Google or Microsoft sign-in.
86
90
 
87
91
  ## MCP server (AI agents)
88
92
 
@@ -30,6 +30,8 @@ local or self-hosted backend, set `CHATTERMATE_API_URL=http://localhost:8000` (o
30
30
  # Create an organization + admin (community signup), or log in to an existing one
31
31
  chattermate signup
32
32
  chattermate login --email you@acme.com
33
+ # Signed up with Google or Microsoft? Create a token in Settings → CLI & API tokens, then:
34
+ chattermate login --token
33
35
 
34
36
  chattermate whoami
35
37
 
@@ -65,6 +67,8 @@ Two credentials are supported:
65
67
  the `CHATTERMATE_TOKEN` environment variable. Long-lived and revocable.
66
68
  - **JWT login** — `chattermate login` stores access + refresh tokens in
67
69
  `~/.chattermate/config.json` (mode `600`) and refreshes automatically.
70
+ `chattermate login --token` stores a PAT there instead, read from a hidden prompt —
71
+ the way to log in for accounts that use Google or Microsoft sign-in.
68
72
 
69
73
  ## MCP server (AI agents)
70
74
 
@@ -16,4 +16,4 @@ You should have received a copy of the GNU Affero General Public License
16
16
  along with this program. If not, see <https://www.gnu.org/licenses/>
17
17
  """
18
18
 
19
- __version__ = "0.7.0"
19
+ __version__ = "0.8.1"
@@ -0,0 +1,42 @@
1
+ """
2
+ ChatterMate CLI
3
+ Copyright (C) 2024 ChatterMate
4
+
5
+ This program is free software: you can redistribute it and/or modify
6
+ it under the terms of the GNU Affero General Public License as
7
+ published by the Free Software Foundation, either version 3 of the
8
+ License, or (at your option) any later version.
9
+
10
+ This program is distributed in the hope that it will be useful,
11
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
12
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13
+ GNU Affero General Public License for more details.
14
+
15
+ You should have received a copy of the GNU Affero General Public License
16
+ along with this program. If not, see <https://www.gnu.org/licenses/>
17
+
18
+ Which AI coding tool, if any, is running the CLI: read from the environment
19
+ variable each tool sets for the commands it runs. Sent with a signup so the
20
+ reports can tell agent-driven signups apart; nothing else uses it. Cursor
21
+ sets its variable in every terminal it opens, so a person typing in Cursor's
22
+ own terminal counts as "cursor" too.
23
+ """
24
+
25
+ import os
26
+ from typing import Mapping, Optional
27
+
28
+ # Environment variable the tool sets -> the name recorded for it
29
+ AGENT_ENV_VARS = {
30
+ "CLAUDECODE": "claude-code",
31
+ "CURSOR_TRACE_ID": "cursor",
32
+ "CODEX_SANDBOX": "codex",
33
+ }
34
+
35
+
36
+ def detect_agent(environ: Optional[Mapping[str, str]] = None) -> Optional[str]:
37
+ """The AI coding tool running this process, or None."""
38
+ env = os.environ if environ is None else environ
39
+ for var, name in AGENT_ENV_VARS.items():
40
+ if env.get(var):
41
+ return name
42
+ return None
@@ -175,14 +175,18 @@ class Client:
175
175
  def signup_verify_otp(
176
176
  self, email: str, otp: str, admin_name: str, admin_password: str,
177
177
  organization_name: str, domain: str, colorcode: Optional[str] = None,
178
+ attribution: Optional[Dict[str, str]] = None,
178
179
  ) -> Dict[str, Any]:
179
- """Enterprise signup step 2: verify OTP and create the org + admin."""
180
+ """Enterprise signup step 2: verify OTP and create the org + admin.
181
+ `attribution` says where the signup came from (client, ref, agent)."""
180
182
  body = {
181
183
  "email": email, "otp": otp, "name": admin_name, "password": admin_password,
182
184
  "organization_name": organization_name, "domain": domain,
183
185
  }
184
186
  if colorcode:
185
187
  body["colorcode"] = colorcode
188
+ if attribution:
189
+ body["attribution"] = attribution
186
190
  data = self.request("POST", "/enterprise/signup/verify-otp", json=body, auth=False)
187
191
  if isinstance(data, dict) and data.get("access_token"):
188
192
  self.token = data.get("access_token")
@@ -23,7 +23,9 @@ from typing import Optional
23
23
  import typer
24
24
  from rich.table import Table
25
25
 
26
- from .. import config
26
+ from .. import __version__, config
27
+ from ..agent_env import detect_agent
28
+ from ..client import PAT_PREFIX
27
29
  from ..context import console, get_client, output, print_error, run
28
30
 
29
31
  token_app = typer.Typer(no_args_is_help=True, help="Manage personal access tokens (PATs).")
@@ -41,13 +43,24 @@ def _store_session(client, user: dict) -> None:
41
43
 
42
44
 
43
45
  def login(
44
- email: str = typer.Option(..., "--email", "-e", prompt=True, help="Account email."),
45
- password: str = typer.Option(
46
- ..., "--password", "-p", prompt=True, hide_input=True, help="Account password."
46
+ email: Optional[str] = typer.Option(None, "--email", "-e", help="Account email."),
47
+ password: Optional[str] = typer.Option(None, "--password", "-p", help="Account password."),
48
+ with_token: bool = typer.Option(
49
+ False, "--token",
50
+ help="Log in with a personal access token (cmat_...) from the dashboard. "
51
+ "For accounts that sign in with Google or Microsoft.",
47
52
  ),
48
53
  as_json: bool = typer.Option(False, "--json", help="Output raw JSON."),
49
54
  ):
50
- """Log in and store JWT credentials in ~/.chattermate/config.json."""
55
+ """Log in and store credentials in ~/.chattermate/config.json."""
56
+ if with_token:
57
+ if email or password:
58
+ print_error("--token can't be combined with --email or --password.")
59
+ raise typer.Exit(code=1)
60
+ _login_with_token(as_json)
61
+ return
62
+ email = email or typer.prompt("Email")
63
+ password = password or typer.prompt("Password", hide_input=True)
51
64
  client = get_client(require_auth=False)
52
65
  data = run(lambda: client.login(email, password))
53
66
  user = data.get("user", {}) if isinstance(data, dict) else {}
@@ -59,6 +72,35 @@ def login(
59
72
  console.print("Tip: create a long-lived token for AI agents with 'chattermate token create'.")
60
73
 
61
74
 
75
+ def _login_with_token(as_json: bool) -> None:
76
+ """Store a personal access token once the API accepts it.
77
+
78
+ The token is read from a hidden prompt (never argv, so it stays out of shell
79
+ history and process listings) and checked with whoami before it is saved.
80
+ """
81
+ token = typer.prompt("Access token", hide_input=True).strip()
82
+ if not token.startswith(PAT_PREFIX):
83
+ print_error(f"That doesn't look like an access token (they start with '{PAT_PREFIX}').")
84
+ raise typer.Exit(code=1)
85
+ client = get_client(require_auth=False)
86
+ client.token, client.refresh_token = token, None
87
+ user = run(client.whoami)
88
+ # Drop any JWT session first: a leftover refresh token must not outlive the switch.
89
+ config.clear_auth()
90
+ _store_session(client, user if isinstance(user, dict) else {})
91
+ if as_json:
92
+ output(user, True)
93
+ else:
94
+ console.print(f"[green]Logged in[/green] as {user.get('email')}")
95
+
96
+
97
+ def signup_attribution(ref: Optional[str]) -> dict:
98
+ """Where this signup came from: the CLI and its version, the --ref it was
99
+ given and the AI coding tool running it, when there is one."""
100
+ values = {"client": f"cli/{__version__}", "ref": ref, "agent": detect_agent()}
101
+ return {key: value for key, value in values.items() if value}
102
+
103
+
62
104
  def signup(
63
105
  name: str = typer.Option(..., "--name", prompt=True, help="Organization name."),
64
106
  domain: str = typer.Option(..., "--domain", prompt=True, help="Organization domain, e.g. acme.com."),
@@ -76,8 +118,12 @@ def signup(
76
118
  ),
77
119
  otp: Optional[str] = typer.Option(
78
120
  None, "--otp",
79
- help="One-time code emailed to the admin address (on a localhost instance the test "
80
- "code is 123456). If omitted you'll be prompted. Ignored with --community.",
121
+ help="One-time code emailed to the admin address. If omitted you'll be prompted. "
122
+ "Ignored with --community.",
123
+ ),
124
+ ref: Optional[str] = typer.Option(
125
+ None, "--ref",
126
+ help="Where you found this signup, e.g. the prompt you pasted (website-ai-prompt).",
81
127
  ),
82
128
  as_json: bool = typer.Option(False, "--json", help="Output raw JSON."),
83
129
  ):
@@ -93,8 +139,8 @@ def signup(
93
139
  client = get_client(require_auth=False)
94
140
 
95
141
  if not community:
96
- # Only request a fresh OTP when the caller hasn't already supplied one.
97
- # Requesting again would email a NEW code and invalidate the --otp passed in.
142
+ # Only request a code when the caller hasn't already supplied one.
143
+ # (Requesting again re-sends the same code while it is still valid.)
98
144
  if not otp:
99
145
  run(lambda: client.signup_request_otp(admin_email))
100
146
  if not sys.stdin.isatty():
@@ -105,12 +151,11 @@ def signup(
105
151
  f"Re-run this command with --otp <code> to complete signup."
106
152
  )
107
153
  raise typer.Exit(1)
108
- is_local = any(h in client.api_url for h in ("localhost", "127.0.0.1", "0.0.0.0"))
109
- hint = " (localhost test code: 123456)" if is_local else ""
110
- otp = typer.prompt(f"Enter the one-time code emailed to {admin_email}{hint}")
154
+ otp = typer.prompt(f"Enter the one-time code emailed to {admin_email}")
111
155
  data = run(lambda: client.signup_verify_otp(
112
156
  email=admin_email, otp=otp, admin_name=admin_name,
113
157
  admin_password=admin_password, organization_name=name, domain=domain,
158
+ attribution=signup_attribution(ref),
114
159
  ))
115
160
  user = data.get("user", {}) if isinstance(data, dict) else {}
116
161
  if client.token:
@@ -16,18 +16,41 @@ You should have received a copy of the GNU Affero General Public License
16
16
  along with this program. If not, see <https://www.gnu.org/licenses/>
17
17
  """
18
18
 
19
+ from typing import Optional
20
+
19
21
  import typer
20
22
  from rich.table import Table
21
23
 
24
+ from ..client import API_PREFIX
22
25
  from ..context import console, get_client, output, run
23
26
 
27
+ # The cloud dashboard, which serves the widget loader
28
+ CLOUD_APP_URL = "https://app.chattermate.chat"
29
+
24
30
  widget_app = typer.Typer(no_args_is_help=True, help="Manage embeddable chat widgets.")
25
31
 
26
32
 
33
+ def embed_snippet(widget_id: str, api_url: str, app_url: Optional[str] = None) -> str:
34
+ """The embed code the dashboard shows: the widget id, the API it talks to,
35
+ and the loader from the dashboard that serves it (the cloud's by default)."""
36
+ loader_origin = (app_url or CLOUD_APP_URL).rstrip("/")
37
+ return "\n".join([
38
+ "<script>",
39
+ f" window.chattermateId = '{widget_id}';",
40
+ f" window.chattermateBaseUrl = '{api_url.rstrip('/')}{API_PREFIX}';",
41
+ "</script>",
42
+ f'<script src="{loader_origin}/webclient/chattermate.min.js"></script>',
43
+ ])
44
+
45
+
27
46
  @widget_app.command("create")
28
47
  def create_widget(
29
48
  agent_id: str = typer.Option(..., "--agent-id", help="Agent to attach the widget to."),
30
49
  name: str = typer.Option("Website widget", "--name", help="Widget name."),
50
+ app_url: Optional[str] = typer.Option(
51
+ None, "--app-url",
52
+ help="Where your ChatterMate dashboard runs, on a self-hosted install (it serves the widget loader).",
53
+ ),
31
54
  as_json: bool = typer.Option(False, "--json", help="Output raw JSON."),
32
55
  ):
33
56
  """Create an embeddable widget for an agent and print its widget id + embed snippet."""
@@ -38,9 +61,9 @@ def create_widget(
38
61
  return
39
62
  widget_id = data.get("id") if isinstance(data, dict) else None
40
63
  console.print(f"[green]Created widget[/green] {widget_id}")
41
- console.print("Embed it on your site:")
42
- console.print(f" <script>window.chattermateId='{widget_id}';</script>")
43
- console.print(' <script src="https://app.chattermate.chat/webclient/chattermate.min.js"></script>')
64
+ console.print("Embed it on your site, just before </body>:")
65
+ # Plain echo: rich would wrap long lines and read [...] as markup
66
+ typer.echo(embed_snippet(widget_id, client.api_url, app_url))
44
67
 
45
68
 
46
69
  @widget_app.command("list")
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: chattermate-cli
3
- Version: 0.7.0
3
+ Version: 0.8.1
4
4
  Summary: ChatterMate CLI and MCP server — sign up, authenticate, and configure agents, workflows and knowledge from the terminal or an AI agent.
5
5
  Author: ChatterMate
6
6
  License: AGPL-3.0-or-later
@@ -48,6 +48,8 @@ local or self-hosted backend, set `CHATTERMATE_API_URL=http://localhost:8000` (o
48
48
  # Create an organization + admin (community signup), or log in to an existing one
49
49
  chattermate signup
50
50
  chattermate login --email you@acme.com
51
+ # Signed up with Google or Microsoft? Create a token in Settings → CLI & API tokens, then:
52
+ chattermate login --token
51
53
 
52
54
  chattermate whoami
53
55
 
@@ -83,6 +85,8 @@ Two credentials are supported:
83
85
  the `CHATTERMATE_TOKEN` environment variable. Long-lived and revocable.
84
86
  - **JWT login** — `chattermate login` stores access + refresh tokens in
85
87
  `~/.chattermate/config.json` (mode `600`) and refreshes automatically.
88
+ `chattermate login --token` stores a PAT there instead, read from a hidden prompt —
89
+ the way to log in for accounts that use Google or Microsoft sign-in.
86
90
 
87
91
  ## MCP server (AI agents)
88
92
 
@@ -2,6 +2,7 @@ LICENSE
2
2
  README.md
3
3
  pyproject.toml
4
4
  chattermate_cli/__init__.py
5
+ chattermate_cli/agent_env.py
5
6
  chattermate_cli/client.py
6
7
  chattermate_cli/config.py
7
8
  chattermate_cli/context.py
@@ -25,11 +26,13 @@ chattermate_cli/commands/ticketing.py
25
26
  chattermate_cli/commands/widget.py
26
27
  chattermate_cli/commands/workflow.py
27
28
  tests/test_ai.py
29
+ tests/test_auth.py
28
30
  tests/test_client.py
29
31
  tests/test_customization.py
30
32
  tests/test_help_center.py
31
33
  tests/test_knowledge.py
32
34
  tests/test_lead_capture.py
33
35
  tests/test_mcp.py
36
+ tests/test_signup_attribution.py
34
37
  tests/test_ticketing.py
35
38
  tests/test_widget.py
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "chattermate-cli"
7
- version = "0.7.0"
7
+ version = "0.8.1"
8
8
  description = "ChatterMate CLI and MCP server — sign up, authenticate, and configure agents, workflows and knowledge from the terminal or an AI agent."
9
9
  readme = "README.md"
10
10
  requires-python = ">=3.10"
@@ -0,0 +1,142 @@
1
+ """
2
+ ChatterMate - CLI Auth Command Tests
3
+ Copyright (C) 2024 ChatterMate
4
+
5
+ This program is free software: you can redistribute it and/or modify
6
+ it under the terms of the GNU Affero General Public License as
7
+ published by the Free Software Foundation, either version 3 of the
8
+ License, or (at your option) any later version.
9
+
10
+ This program is distributed in the hope that it will be useful,
11
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
12
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13
+ GNU Affero General Public License for more details.
14
+
15
+ You should have received a copy of the GNU Affero General Public License
16
+ along with this program. If not, see <https://www.gnu.org/licenses/>
17
+ """
18
+
19
+ import httpx
20
+ import pytest
21
+ from typer.testing import CliRunner
22
+
23
+ from chattermate_cli import config, context
24
+ from chattermate_cli.commands import auth as auth_cmd
25
+ from chattermate_cli.main import app
26
+
27
+ runner = CliRunner()
28
+
29
+ TOKEN = "cmat_live_secret_123"
30
+ USER = {"id": "u1", "email": "sso@acme.com", "organization_id": "o1", "role": {"name": "Admin"}}
31
+
32
+
33
+ @pytest.fixture
34
+ def api(monkeypatch, tmp_path):
35
+ """Isolated config dir plus a fake API that accepts only TOKEN.
36
+
37
+ Commands still build their client through the real get_client, so token
38
+ resolution from config is exercised; only the HTTP transport is faked.
39
+ """
40
+ monkeypatch.setenv(config.ENV_CONFIG_DIR, str(tmp_path))
41
+ monkeypatch.delenv(config.ENV_TOKEN, raising=False)
42
+ monkeypatch.setenv(config.ENV_API_URL, "http://test")
43
+ seen = []
44
+
45
+ def handler(request):
46
+ seen.append(request)
47
+ if request.headers.get("Authorization") != f"Bearer {TOKEN}":
48
+ return httpx.Response(401, json={"detail": "Could not validate credentials"})
49
+ assert (request.method, request.url.path) == ("PATCH", "/api/v1/users/me")
50
+ return httpx.Response(200, json=USER)
51
+
52
+ def mocked_client(require_auth=True):
53
+ client = context.get_client(require_auth)
54
+ client._http = httpx.Client(transport=httpx.MockTransport(handler))
55
+ return client
56
+
57
+ monkeypatch.setattr(auth_cmd, "get_client", mocked_client)
58
+ return seen
59
+
60
+
61
+ def test_login_token_stores_token_and_whoami_uses_it(api):
62
+ result = runner.invoke(app, ["login", "--token"], input=f"{TOKEN}\n")
63
+ assert result.exit_code == 0, result.output
64
+ assert "Logged in as sso@acme.com" in result.output
65
+ # Hidden prompt: the secret is never echoed back.
66
+ assert TOKEN not in result.output
67
+
68
+ cfg = config.load_config()
69
+ assert cfg["access_token"] == TOKEN
70
+ assert cfg["email"] == "sso@acme.com"
71
+ assert cfg["organization_id"] == "o1"
72
+
73
+ result = runner.invoke(app, ["whoami", "--json"])
74
+ assert result.exit_code == 0, result.output
75
+ assert "sso@acme.com" in result.output
76
+ assert api[-1].headers["Authorization"] == f"Bearer {TOKEN}"
77
+
78
+
79
+ def test_login_token_replaces_a_password_session(api):
80
+ config.update_config(access_token="jwt-old", refresh_token="jwt-refresh", email="old@acme.com")
81
+ result = runner.invoke(app, ["login", "--token"], input=f"{TOKEN}\n")
82
+ assert result.exit_code == 0, result.output
83
+ cfg = config.load_config()
84
+ assert cfg["access_token"] == TOKEN
85
+ assert "refresh_token" not in cfg
86
+ assert cfg["email"] == "sso@acme.com"
87
+
88
+
89
+ def test_login_token_rejected_by_api_stores_nothing(api):
90
+ config.update_config(access_token="jwt-old")
91
+ result = runner.invoke(app, ["login", "--token"], input="cmat_revoked\n")
92
+ assert result.exit_code == 1
93
+ assert "Could not validate credentials" in result.output
94
+ assert config.load_config()["access_token"] == "jwt-old"
95
+
96
+
97
+ def test_login_token_refuses_something_that_is_not_a_token(api):
98
+ result = runner.invoke(app, ["login", "--token"], input="hunter2\n")
99
+ assert result.exit_code == 1
100
+ assert "cmat_" in result.output
101
+ assert api == [] # never sent anywhere
102
+ assert config.load_config() == {}
103
+
104
+
105
+ def test_login_token_takes_no_value_on_the_command_line(api):
106
+ # --token is a flag; a secret passed after it is an unexpected argument.
107
+ result = runner.invoke(app, ["login", "--token", TOKEN])
108
+ assert result.exit_code != 0
109
+ assert config.load_config() == {}
110
+
111
+
112
+ def test_login_token_refuses_email_or_password_alongside(api):
113
+ result = runner.invoke(app, ["login", "--token", "--email", "a@acme.com"], input=f"{TOKEN}\n")
114
+ assert result.exit_code == 1
115
+ assert "can't be combined" in result.output
116
+ assert api == []
117
+ assert config.load_config() == {}
118
+
119
+
120
+ def test_password_login_still_prompts(monkeypatch, tmp_path):
121
+ monkeypatch.setenv(config.ENV_CONFIG_DIR, str(tmp_path))
122
+ monkeypatch.setenv(config.ENV_API_URL, "http://test")
123
+
124
+ def handler(request):
125
+ assert request.url.path == "/api/v1/users/login"
126
+ assert b"username=admin%40acme.com" in request.content
127
+ assert b"password=pw" in request.content
128
+ return httpx.Response(200, json={
129
+ "access_token": "jwt-access", "refresh_token": "jwt-refresh",
130
+ "user": {"id": "u1", "email": "admin@acme.com", "organization_id": "o1"},
131
+ })
132
+
133
+ def mocked_client(require_auth=True):
134
+ client = context.get_client(require_auth)
135
+ client._http = httpx.Client(transport=httpx.MockTransport(handler))
136
+ return client
137
+
138
+ monkeypatch.setattr(auth_cmd, "get_client", mocked_client)
139
+ result = runner.invoke(app, ["login"], input="admin@acme.com\npw\n")
140
+ assert result.exit_code == 0, result.output
141
+ assert "Logged in as admin@acme.com" in result.output
142
+ assert config.load_config()["refresh_token"] == "jwt-refresh"
@@ -0,0 +1,114 @@
1
+ """
2
+ ChatterMate CLI
3
+ Copyright (C) 2024 ChatterMate
4
+
5
+ This program is free software: you can redistribute it and/or modify
6
+ it under the terms of the GNU Affero General Public License as
7
+ published by the Free Software Foundation, either version 3 of the
8
+ License, or (at your option) any later version.
9
+
10
+ This program is distributed in the hope that it will be useful,
11
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
12
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13
+ GNU Affero General Public License for more details.
14
+
15
+ You should have received a copy of the GNU Affero General Public License
16
+ along with this program. If not, see <https://www.gnu.org/licenses/>
17
+
18
+ A CLI signup tells the API where it came from: the CLI and its version,
19
+ the --ref it was given and the AI coding tool running it.
20
+ """
21
+
22
+ import json
23
+
24
+ import httpx
25
+ from typer.testing import CliRunner
26
+
27
+ from chattermate_cli import __version__
28
+ from chattermate_cli.agent_env import AGENT_ENV_VARS, detect_agent
29
+ from chattermate_cli.client import Client
30
+ from chattermate_cli.commands import auth
31
+ from chattermate_cli.main import app
32
+
33
+
34
+ def make_client(handler):
35
+ client = Client(api_url="http://test")
36
+ client._http = httpx.Client(transport=httpx.MockTransport(handler))
37
+ return client
38
+
39
+
40
+ def test_detects_each_coding_tool():
41
+ for var, name in AGENT_ENV_VARS.items():
42
+ assert detect_agent({var: "1"}) == name
43
+
44
+
45
+ def test_no_coding_tool():
46
+ assert detect_agent({}) is None
47
+ assert detect_agent({"CLAUDECODE": ""}) is None
48
+
49
+
50
+ def test_verify_otp_sends_attribution():
51
+ sent = {}
52
+
53
+ def handler(request):
54
+ sent.update(json.loads(request.content))
55
+ return httpx.Response(200, json={"access_token": "a", "refresh_token": "r"})
56
+
57
+ make_client(handler).signup_verify_otp(
58
+ email="o@acme.com", otp="123456", admin_name="Owner", admin_password="pw",
59
+ organization_name="Acme", domain="acme.com",
60
+ attribution={"client": "cli/0.8.0", "ref": "website-ai-prompt"},
61
+ )
62
+ assert sent["attribution"] == {"client": "cli/0.8.0", "ref": "website-ai-prompt"}
63
+
64
+
65
+ def test_verify_otp_without_attribution_sends_none():
66
+ sent = {}
67
+
68
+ def handler(request):
69
+ sent.update(json.loads(request.content))
70
+ return httpx.Response(200, json={})
71
+
72
+ make_client(handler).signup_verify_otp(
73
+ email="o@acme.com", otp="123456", admin_name="Owner", admin_password="pw",
74
+ organization_name="Acme", domain="acme.com",
75
+ )
76
+ assert "attribution" not in sent
77
+
78
+
79
+ def test_attribution_for_a_signup(monkeypatch):
80
+ for var in AGENT_ENV_VARS:
81
+ monkeypatch.delenv(var, raising=False)
82
+ assert auth.signup_attribution(None) == {"client": f"cli/{__version__}"}
83
+
84
+ monkeypatch.setenv("CLAUDECODE", "1")
85
+ assert auth.signup_attribution("website-ai-prompt") == {
86
+ "client": f"cli/{__version__}", "ref": "website-ai-prompt", "agent": "claude-code",
87
+ }
88
+
89
+
90
+ def test_signup_command_passes_ref_and_tool(monkeypatch, tmp_path):
91
+ monkeypatch.setenv("HOME", str(tmp_path))
92
+ monkeypatch.setenv("CURSOR_TRACE_ID", "trace")
93
+ for var in AGENT_ENV_VARS:
94
+ if var != "CURSOR_TRACE_ID":
95
+ monkeypatch.delenv(var, raising=False)
96
+ calls = {}
97
+
98
+ class FakeClient:
99
+ token = None
100
+
101
+ def signup_verify_otp(self, **kwargs):
102
+ calls.update(kwargs)
103
+ return {}
104
+
105
+ monkeypatch.setattr(auth, "get_client", lambda require_auth=False: FakeClient())
106
+ result = CliRunner().invoke(app, [
107
+ "signup", "--name", "Acme", "--domain", "acme.com", "--admin-email", "o@acme.com",
108
+ "--admin-name", "Owner", "--admin-password", "Secret123!", "--otp", "123456",
109
+ "--ref", "signup-ai-prompt",
110
+ ])
111
+ assert result.exit_code == 0, result.output
112
+ assert calls["attribution"] == {
113
+ "client": f"cli/{__version__}", "ref": "signup-ai-prompt", "agent": "cursor",
114
+ }
@@ -51,3 +51,20 @@ def test_list_widgets_for_agent_gets_by_agent():
51
51
 
52
52
  assert seen["path"] == "/api/v1/widgets/agent/ag-1"
53
53
  assert rows[0]["id"] == "w-1"
54
+
55
+
56
+ def test_embed_snippet_on_the_cloud():
57
+ from chattermate_cli.commands.widget import embed_snippet
58
+
59
+ snippet = embed_snippet("w-1", "https://api.chattermate.chat")
60
+ assert "window.chattermateId = 'w-1';" in snippet
61
+ assert "window.chattermateBaseUrl = 'https://api.chattermate.chat/api/v1';" in snippet
62
+ assert '<script src="https://app.chattermate.chat/webclient/chattermate.min.js"></script>' in snippet
63
+
64
+
65
+ def test_embed_snippet_on_a_self_hosted_install():
66
+ from chattermate_cli.commands.widget import embed_snippet
67
+
68
+ snippet = embed_snippet("w-1", "https://support.acme.com/", app_url="https://chat.acme.com/")
69
+ assert "window.chattermateBaseUrl = 'https://support.acme.com/api/v1';" in snippet
70
+ assert '<script src="https://chat.acme.com/webclient/chattermate.min.js"></script>' in snippet
File without changes