termigent 0.1.0__tar.gz → 0.2.0__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 (27) hide show
  1. {termigent-0.1.0 → termigent-0.2.0}/LICENSE +1 -1
  2. termigent-0.2.0/PKG-INFO +156 -0
  3. termigent-0.2.0/README.md +123 -0
  4. termigent-0.2.0/assets/terminal.png +0 -0
  5. {termigent-0.1.0 → termigent-0.2.0}/pyproject.toml +6 -0
  6. termigent-0.2.0/termigent/auth.py +274 -0
  7. termigent-0.2.0/termigent/cli.py +150 -0
  8. termigent-0.2.0/termigent/server.py +266 -0
  9. termigent-0.2.0/termigent/tls.py +385 -0
  10. termigent-0.2.0/termigent.egg-info/PKG-INFO +156 -0
  11. {termigent-0.1.0 → termigent-0.2.0}/termigent.egg-info/SOURCES.txt +3 -0
  12. {termigent-0.1.0 → termigent-0.2.0}/termigent.egg-info/requires.txt +1 -0
  13. {termigent-0.1.0 → termigent-0.2.0}/termigent.egg-info/scm_file_list.json +4 -1
  14. termigent-0.2.0/termigent.egg-info/scm_version.json +8 -0
  15. termigent-0.1.0/PKG-INFO +0 -136
  16. termigent-0.1.0/README.md +0 -107
  17. termigent-0.1.0/termigent/cli.py +0 -93
  18. termigent-0.1.0/termigent/server.py +0 -50
  19. termigent-0.1.0/termigent.egg-info/PKG-INFO +0 -136
  20. termigent-0.1.0/termigent.egg-info/scm_version.json +0 -8
  21. {termigent-0.1.0 → termigent-0.2.0}/.gitignore +0 -0
  22. {termigent-0.1.0 → termigent-0.2.0}/setup.cfg +0 -0
  23. {termigent-0.1.0 → termigent-0.2.0}/termigent/__init__.py +0 -0
  24. {termigent-0.1.0 → termigent-0.2.0}/termigent/__main__.py +0 -0
  25. {termigent-0.1.0 → termigent-0.2.0}/termigent.egg-info/dependency_links.txt +0 -0
  26. {termigent-0.1.0 → termigent-0.2.0}/termigent.egg-info/entry_points.txt +0 -0
  27. {termigent-0.1.0 → termigent-0.2.0}/termigent.egg-info/top_level.txt +0 -0
@@ -1,6 +1,6 @@
1
1
  MIT License
2
2
 
3
- Copyright (c) 2026 Fortune
3
+ Copyright (c) 2026 Fortune Osokor
4
4
 
5
5
  Permission is hereby granted, free of charge, to any person obtaining a copy
6
6
  of this software and associated documentation files (the "Software"), to deal
@@ -0,0 +1,156 @@
1
+ Metadata-Version: 2.4
2
+ Name: termigent
3
+ Version: 0.2.0
4
+ Summary: Universal MCP server that exposes a system terminal over SSE.
5
+ Author: Fortune
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://github.com/Re4lLife/Termigent
8
+ Project-URL: Repository, https://github.com/Re4lLife/Termigent
9
+ Project-URL: Issues, https://github.com/Re4lLife/Termigent/issues
10
+ Keywords: mcp,model-context-protocol,sse,terminal,shell,ai,llm
11
+ Classifier: Development Status :: 4 - Beta
12
+ Classifier: Environment :: Console
13
+ Classifier: Intended Audience :: Developers
14
+ Classifier: Programming Language :: Python :: 3
15
+ Classifier: Programming Language :: Python :: 3 :: Only
16
+ Classifier: Programming Language :: Python :: 3.10
17
+ Classifier: Programming Language :: Python :: 3.11
18
+ Classifier: Programming Language :: Python :: 3.12
19
+ Classifier: Programming Language :: Python :: 3.13
20
+ Classifier: Programming Language :: Python :: 3.14
21
+ Classifier: Topic :: System :: Shells
22
+ Requires-Python: >=3.10
23
+ Description-Content-Type: text/markdown
24
+ License-File: LICENSE
25
+ Requires-Dist: fastapi>=0.110
26
+ Requires-Dist: uvicorn>=0.27
27
+ Requires-Dist: mcp<2,>=1.2
28
+ Requires-Dist: cryptography>=42
29
+ Provides-Extra: dev
30
+ Requires-Dist: build>=1.0; extra == "dev"
31
+ Requires-Dist: twine>=5.0; extra == "dev"
32
+ Dynamic: license-file
33
+
34
+ # Termigent
35
+
36
+ A universal [Model Context Protocol](https://modelcontextprotocol.io) (MCP) server that exposes a system terminal over Server-Sent Events (SSE).
37
+
38
+ ## Who it is for
39
+
40
+ Termigent is for people who prefer to stay in a graphical MCP client such as the Claude Desktop app and still want the assistant to run real shell commands, either on the local machine or on a remote server.
41
+
42
+ - **Local execution** — run `termigent` next to Claude Desktop and let Claude inspect files, run tools, and automate tasks on that machine.
43
+ - **Remote execution** — install `termigent` on a remote host, start it with `--host 0.0.0.0`, and let Claude operate that server through the same GUI.
44
+
45
+
46
+ Any GUI MCP client that supports remote SSE, or a stdio bridge such as `mcp-remote`, can use it.
47
+
48
+ ## Requirements
49
+
50
+ - Python 3.10+
51
+
52
+ ## Install
53
+
54
+ ```bash
55
+ pip install termigent
56
+ ```
57
+
58
+
59
+ ## Usage
60
+
61
+ ```bash
62
+ termigent # http://127.0.0.1:8000
63
+ termigent --port 3000
64
+ termigent --host 0.0.0.0 --port 8000 # HTTPS is set up automatically
65
+ ```
66
+
67
+ | Flag | Default | Description |
68
+ | --- | --- | --- |
69
+ | `--host` | `127.0.0.1` | Interface to bind |
70
+ | `--port` | `8000` | Port to listen on |
71
+ | `--tls` | `auto` | Beyond loopback: `auto` (free trusted Let's Encrypt certificate for the public IP, else self-signed), `acme`, `self-signed`, or `off` (plain HTTP behind your own proxy) |
72
+ | `--public-url` | detected | URL clients use. Only needed behind a reverse proxy, with `--tls off`, or to use a domain name |
73
+ | `--version` | | Print version |
74
+
75
+ The MCP endpoint is `http://<host>:<port>/mcp` (Streamable HTTP). The legacy SSE endpoint `/sse` is still served.
76
+
77
+ ## Preview
78
+
79
+ ![Termigent terminal showing the green prompt, white command, and light-gray output](https://raw.githubusercontent.com/Re4lLife/Termigent/main/assets/terminal.png)
80
+
81
+ ## Tools
82
+
83
+ - `run_command(command)` — runs the command with the shell and returns combined stdout/stderr. A non-zero exit status is appended as `[exit code: N]`.
84
+ - `command_output(job_id, wait=45)` — commands run as background jobs, so there is no time limit. If a command is still running after ~45 s, `run_command` returns the output so far plus a `job_id`; call `command_output` until it finishes. This keeps every MCP request well under client timeouts.
85
+ - `kill_command(job_id)` — stop a running command.
86
+
87
+ Set `TERMIGENT_WAIT` (seconds, default `45`; keep it under your client's tool timeout, e.g. Codex defaults to 60 s) to change how long one call waits.
88
+
89
+ In the server terminal, each call is shown as a green `agent@termigent:~$` prompt, a white command, and light-gray output:
90
+
91
+ ```
92
+ agent@termigent:~$ pwd
93
+ /home/user
94
+ ```
95
+
96
+
97
+ ## Connect Claude Desktop
98
+
99
+ Claude Desktop brokers remote connectors through Anthropic's cloud, so a connector URL cannot reach your loopback address. Bridge the endpoint through `mcp-remote` in the Desktop config instead. This requires Node.js, which provides `npx`.
100
+
101
+ **On the local machine** — start `termigent`, then add this to `claude_desktop_config.json`:
102
+
103
+ ```json
104
+ {
105
+ "mcpServers": {
106
+ "termigent": {
107
+ "command": "npx",
108
+ "args": ["-y", "mcp-remote", "http://127.0.0.1:8000/mcp"]
109
+ }
110
+ }
111
+ }
112
+ ```
113
+
114
+ **On a remote server** — install termigent there and bind it to all interfaces:
115
+
116
+ ```bash
117
+ termigent --host 0.0.0.0 --port 8000
118
+ ```
119
+
120
+ It prints the endpoint, e.g. `https://SERVER_IP:8000/mcp`. Then, on the machine running Claude Desktop, point the bridge at the server:
121
+
122
+ ```json
123
+ {
124
+ "mcpServers": {
125
+ "termigent": {
126
+ "command": "npx",
127
+ "args": ["-y", "mcp-remote", "https://SERVER_IP:8000/mcp"]
128
+ }
129
+ }
130
+ }
131
+ ```
132
+
133
+
134
+ Restart Claude Desktop after changing its config so it initializes a new MCP session.
135
+
136
+ ## Security
137
+
138
+ Termigent runs commands with the privileges of the user that started it, so every connection must be paired. Pairing is automatic; there is no key to generate or paste into a config.
139
+
140
+ 1. A client connects. `mcp-remote` opens a browser page (OAuth with dynamic client registration and PKCE).
141
+ 2. Termigent prints a one-time pairing code in its terminal (`🔐 Pairing request ... Code: 1234-5678`).
142
+ 3. Type the code into the page. Done: the client stores its token and reconnects (and refreshes) silently, including after restarts.
143
+
144
+ Requests without a valid token get `401`. Codes expire after 5 minutes and are cancelled after 5 wrong attempts. Tokens are stored hashed in `~/.termigent/auth.json` (mode `0600`; override the directory with `TERMIGENT_HOME`). To revoke all clients, delete that file.
145
+
146
+ - **Encryption:** beyond loopback Termigent serves HTTPS automatically. It generates a fresh key, obtains a free, publicly trusted [Let's Encrypt IP-address certificate](https://letsencrypt.org/2026/01/15/6day-and-ip-general-availability.html) (6-day, renewed in the background) and reloads it without restarting, so clients trust it with no setup. This needs inbound ports 80 (certificate challenge) and your Termigent port, and permission to bind port 80 (root, or `sudo sysctl net.ipv4.ip_unprivileged_port_start=80`).
147
+ - **Fallback:** if a trusted certificate can't be obtained (NAT, closed ports), Termigent falls back to an ephemeral self-signed certificate and prints its fingerprint; clients must trust it (e.g. `NODE_EXTRA_CA_CERTS`). Alternatively keep the loopback bind and use an SSH tunnel: `ssh -N -L 8000:127.0.0.1:8000 user@server`.
148
+ - **Headless servers:** no GUI is needed on the server. The pairing page opens on the machine running the MCP client; the server only prints the code.
149
+ - Keep the default loopback bind for local use.
150
+ - Termigent is not a sandbox; commands can read, modify, and delete anything the host user can.
151
+
152
+ Only run it on systems you control and with clients you trust.
153
+
154
+ ## License
155
+
156
+ MIT
@@ -0,0 +1,123 @@
1
+ # Termigent
2
+
3
+ A universal [Model Context Protocol](https://modelcontextprotocol.io) (MCP) server that exposes a system terminal over Server-Sent Events (SSE).
4
+
5
+ ## Who it is for
6
+
7
+ Termigent is for people who prefer to stay in a graphical MCP client such as the Claude Desktop app and still want the assistant to run real shell commands, either on the local machine or on a remote server.
8
+
9
+ - **Local execution** — run `termigent` next to Claude Desktop and let Claude inspect files, run tools, and automate tasks on that machine.
10
+ - **Remote execution** — install `termigent` on a remote host, start it with `--host 0.0.0.0`, and let Claude operate that server through the same GUI.
11
+
12
+
13
+ Any GUI MCP client that supports remote SSE, or a stdio bridge such as `mcp-remote`, can use it.
14
+
15
+ ## Requirements
16
+
17
+ - Python 3.10+
18
+
19
+ ## Install
20
+
21
+ ```bash
22
+ pip install termigent
23
+ ```
24
+
25
+
26
+ ## Usage
27
+
28
+ ```bash
29
+ termigent # http://127.0.0.1:8000
30
+ termigent --port 3000
31
+ termigent --host 0.0.0.0 --port 8000 # HTTPS is set up automatically
32
+ ```
33
+
34
+ | Flag | Default | Description |
35
+ | --- | --- | --- |
36
+ | `--host` | `127.0.0.1` | Interface to bind |
37
+ | `--port` | `8000` | Port to listen on |
38
+ | `--tls` | `auto` | Beyond loopback: `auto` (free trusted Let's Encrypt certificate for the public IP, else self-signed), `acme`, `self-signed`, or `off` (plain HTTP behind your own proxy) |
39
+ | `--public-url` | detected | URL clients use. Only needed behind a reverse proxy, with `--tls off`, or to use a domain name |
40
+ | `--version` | | Print version |
41
+
42
+ The MCP endpoint is `http://<host>:<port>/mcp` (Streamable HTTP). The legacy SSE endpoint `/sse` is still served.
43
+
44
+ ## Preview
45
+
46
+ ![Termigent terminal showing the green prompt, white command, and light-gray output](https://raw.githubusercontent.com/Re4lLife/Termigent/main/assets/terminal.png)
47
+
48
+ ## Tools
49
+
50
+ - `run_command(command)` — runs the command with the shell and returns combined stdout/stderr. A non-zero exit status is appended as `[exit code: N]`.
51
+ - `command_output(job_id, wait=45)` — commands run as background jobs, so there is no time limit. If a command is still running after ~45 s, `run_command` returns the output so far plus a `job_id`; call `command_output` until it finishes. This keeps every MCP request well under client timeouts.
52
+ - `kill_command(job_id)` — stop a running command.
53
+
54
+ Set `TERMIGENT_WAIT` (seconds, default `45`; keep it under your client's tool timeout, e.g. Codex defaults to 60 s) to change how long one call waits.
55
+
56
+ In the server terminal, each call is shown as a green `agent@termigent:~$` prompt, a white command, and light-gray output:
57
+
58
+ ```
59
+ agent@termigent:~$ pwd
60
+ /home/user
61
+ ```
62
+
63
+
64
+ ## Connect Claude Desktop
65
+
66
+ Claude Desktop brokers remote connectors through Anthropic's cloud, so a connector URL cannot reach your loopback address. Bridge the endpoint through `mcp-remote` in the Desktop config instead. This requires Node.js, which provides `npx`.
67
+
68
+ **On the local machine** — start `termigent`, then add this to `claude_desktop_config.json`:
69
+
70
+ ```json
71
+ {
72
+ "mcpServers": {
73
+ "termigent": {
74
+ "command": "npx",
75
+ "args": ["-y", "mcp-remote", "http://127.0.0.1:8000/mcp"]
76
+ }
77
+ }
78
+ }
79
+ ```
80
+
81
+ **On a remote server** — install termigent there and bind it to all interfaces:
82
+
83
+ ```bash
84
+ termigent --host 0.0.0.0 --port 8000
85
+ ```
86
+
87
+ It prints the endpoint, e.g. `https://SERVER_IP:8000/mcp`. Then, on the machine running Claude Desktop, point the bridge at the server:
88
+
89
+ ```json
90
+ {
91
+ "mcpServers": {
92
+ "termigent": {
93
+ "command": "npx",
94
+ "args": ["-y", "mcp-remote", "https://SERVER_IP:8000/mcp"]
95
+ }
96
+ }
97
+ }
98
+ ```
99
+
100
+
101
+ Restart Claude Desktop after changing its config so it initializes a new MCP session.
102
+
103
+ ## Security
104
+
105
+ Termigent runs commands with the privileges of the user that started it, so every connection must be paired. Pairing is automatic; there is no key to generate or paste into a config.
106
+
107
+ 1. A client connects. `mcp-remote` opens a browser page (OAuth with dynamic client registration and PKCE).
108
+ 2. Termigent prints a one-time pairing code in its terminal (`🔐 Pairing request ... Code: 1234-5678`).
109
+ 3. Type the code into the page. Done: the client stores its token and reconnects (and refreshes) silently, including after restarts.
110
+
111
+ Requests without a valid token get `401`. Codes expire after 5 minutes and are cancelled after 5 wrong attempts. Tokens are stored hashed in `~/.termigent/auth.json` (mode `0600`; override the directory with `TERMIGENT_HOME`). To revoke all clients, delete that file.
112
+
113
+ - **Encryption:** beyond loopback Termigent serves HTTPS automatically. It generates a fresh key, obtains a free, publicly trusted [Let's Encrypt IP-address certificate](https://letsencrypt.org/2026/01/15/6day-and-ip-general-availability.html) (6-day, renewed in the background) and reloads it without restarting, so clients trust it with no setup. This needs inbound ports 80 (certificate challenge) and your Termigent port, and permission to bind port 80 (root, or `sudo sysctl net.ipv4.ip_unprivileged_port_start=80`).
114
+ - **Fallback:** if a trusted certificate can't be obtained (NAT, closed ports), Termigent falls back to an ephemeral self-signed certificate and prints its fingerprint; clients must trust it (e.g. `NODE_EXTRA_CA_CERTS`). Alternatively keep the loopback bind and use an SSH tunnel: `ssh -N -L 8000:127.0.0.1:8000 user@server`.
115
+ - **Headless servers:** no GUI is needed on the server. The pairing page opens on the machine running the MCP client; the server only prints the code.
116
+ - Keep the default loopback bind for local use.
117
+ - Termigent is not a sandbox; commands can read, modify, and delete anything the host user can.
118
+
119
+ Only run it on systems you control and with clients you trust.
120
+
121
+ ## License
122
+
123
+ MIT
Binary file
@@ -29,11 +29,17 @@ dependencies = [
29
29
  "fastapi>=0.110",
30
30
  "uvicorn>=0.27",
31
31
  "mcp>=1.2,<2",
32
+ "cryptography>=42",
32
33
  ]
33
34
 
34
35
  [project.optional-dependencies]
35
36
  dev = ["build>=1.0", "twine>=5.0"]
36
37
 
38
+ [project.urls]
39
+ Homepage = "https://github.com/Re4lLife/Termigent"
40
+ Repository = "https://github.com/Re4lLife/Termigent"
41
+ Issues = "https://github.com/Re4lLife/Termigent/issues"
42
+
37
43
  [project.scripts]
38
44
  termigent = "termigent.cli:main"
39
45
 
@@ -0,0 +1,274 @@
1
+ """Zero-config pairing auth for Termigent.
2
+
3
+ Termigent acts as a minimal OAuth 2.1 authorization server (dynamic client
4
+ registration + PKCE). MCP clients/bridges that support OAuth (e.g. mcp-remote)
5
+ run the flow automatically: the first connection opens a browser page asking
6
+ for a pairing code that is printed in the Termigent terminal. After pairing,
7
+ tokens are stored by the client and reused (and refreshed) with no user action.
8
+ Nobody has to generate or copy a key into a config file.
9
+ """
10
+
11
+ import hashlib
12
+ import hmac
13
+ import html
14
+ import json
15
+ import os
16
+ import secrets
17
+ import time
18
+ from pathlib import Path
19
+ from urllib.parse import parse_qs
20
+
21
+ from mcp.server.auth.provider import (
22
+ AccessToken,
23
+ AuthorizationCode,
24
+ AuthorizationParams,
25
+ AuthorizeError,
26
+ RefreshToken,
27
+ TokenError,
28
+ construct_redirect_uri,
29
+ )
30
+ from mcp.shared.auth import OAuthClientInformationFull, OAuthToken
31
+ from starlette.requests import Request
32
+ from starlette.responses import HTMLResponse, RedirectResponse, Response
33
+
34
+ ACCESS_TTL = 7 * 24 * 3600
35
+ REFRESH_TTL = 90 * 24 * 3600
36
+ CODE_TTL = 300
37
+ PAIR_TTL = 300
38
+ MAX_ATTEMPTS = 5
39
+ MAX_PENDING = 10
40
+ MAX_CLIENTS = 100
41
+
42
+ YELLOW = "\033[33m"
43
+ GREEN = "\033[32m"
44
+ RESET = "\033[0m"
45
+
46
+
47
+ def _h(token: str) -> str:
48
+ return hashlib.sha256(token.encode()).hexdigest()
49
+
50
+
51
+ def _clean(text: str, limit: int = 60) -> str:
52
+ return "".join(c for c in text if c.isprintable())[:limit] or "unknown client"
53
+
54
+
55
+ def _state_path() -> Path:
56
+ base = os.environ.get("TERMIGENT_HOME") or str(Path.home() / ".termigent")
57
+ return Path(base) / "auth.json"
58
+
59
+
60
+ class _Pending:
61
+ def __init__(self, client, params, code):
62
+ self.client = client
63
+ self.params = params
64
+ self.code = code
65
+ self.attempts = 0
66
+ self.expires = time.time() + PAIR_TTL
67
+
68
+
69
+ class PairingProvider:
70
+ def __init__(self, public_url: str, path: Path | None = None):
71
+ self.public_url = public_url
72
+ self._path = path or _state_path()
73
+ self._pending: dict[str, _Pending] = {}
74
+ self._codes: dict[str, AuthorizationCode] = {}
75
+ self._s = {"clients": {}, "access": {}, "refresh": {}}
76
+ try:
77
+ data = json.loads(self._path.read_text())
78
+ for k in self._s:
79
+ self._s[k] = data.get(k, {})
80
+ except (OSError, ValueError):
81
+ pass
82
+
83
+ # ---- persistence -------------------------------------------------
84
+ def _save(self) -> None:
85
+ now = time.time()
86
+ for kind in ("access", "refresh"):
87
+ self._s[kind] = {
88
+ k: v for k, v in self._s[kind].items() if v["expires_at"] > now
89
+ }
90
+ self._path.parent.mkdir(parents=True, exist_ok=True)
91
+ tmp = self._path.with_suffix(".tmp")
92
+ fd = os.open(tmp, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
93
+ with os.fdopen(fd, "w") as f:
94
+ json.dump(self._s, f)
95
+ os.replace(tmp, self._path)
96
+
97
+ def _expire(self) -> None:
98
+ now = time.time()
99
+ self._pending = {k: v for k, v in self._pending.items() if v.expires > now}
100
+ self._codes = {k: v for k, v in self._codes.items() if v.expires_at > now}
101
+
102
+ # ---- client registration ----------------------------------------
103
+ async def get_client(self, client_id: str):
104
+ data = self._s["clients"].get(client_id)
105
+ return OAuthClientInformationFull(**data) if data else None
106
+
107
+ async def register_client(self, client_info: OAuthClientInformationFull) -> None:
108
+ clients = self._s["clients"]
109
+ clients[client_info.client_id] = client_info.model_dump(
110
+ mode="json", exclude_none=True
111
+ )
112
+ while len(clients) > MAX_CLIENTS:
113
+ clients.pop(next(iter(clients)))
114
+ self._save()
115
+
116
+ # ---- authorization (pairing) ------------------------------------
117
+ async def authorize(self, client, params: AuthorizationParams) -> str:
118
+ self._expire()
119
+ if len(self._pending) >= MAX_PENDING:
120
+ raise AuthorizeError(
121
+ "temporarily_unavailable", "Too many pending pairing requests"
122
+ )
123
+ pid = secrets.token_urlsafe(24)
124
+ code = f"{secrets.randbelow(10**8):08d}"
125
+ self._pending[pid] = _Pending(client, params, code)
126
+ name = _clean(client.client_name or "")
127
+ print(
128
+ f"{YELLOW}🔐 Pairing request from \"{name}\". "
129
+ f"Code: {code[:4]}-{code[4:]} (valid {PAIR_TTL // 60} min){RESET}",
130
+ flush=True,
131
+ )
132
+ return f"{self.public_url}/approve?pid={pid}"
133
+
134
+ async def approve(self, request: Request) -> Response:
135
+ self._expire()
136
+ if request.method == "POST":
137
+ body = parse_qs((await request.body()).decode(errors="ignore"))
138
+ pid = (body.get("pid") or [""])[0]
139
+ entered = "".join(c for c in (body.get("code") or [""])[0] if c.isdigit())
140
+ else:
141
+ pid = request.query_params.get("pid", "")
142
+ entered = None
143
+ pending = self._pending.get(pid)
144
+ if pending is None:
145
+ return _page("Request expired", "<p>Start the connection again from your client.</p>", 410)
146
+
147
+ name = html.escape(_clean(pending.client.client_name or ""))
148
+ if entered is not None:
149
+ pending.attempts += 1
150
+ if hmac.compare_digest(entered, pending.code):
151
+ del self._pending[pid]
152
+ return self._grant(pending)
153
+ if pending.attempts >= MAX_ATTEMPTS:
154
+ del self._pending[pid]
155
+ print(f"{YELLOW}Pairing request cancelled: too many wrong codes.{RESET}", flush=True)
156
+ return _page("Cancelled", "<p>Too many wrong codes. Start again from your client.</p>", 403)
157
+ err = "<p style='color:#b00'>Wrong code, try again.</p>"
158
+ else:
159
+ err = ""
160
+ form = (
161
+ f"<p><b>{name}</b> wants to run shell commands on this machine.</p>"
162
+ "<p>Enter the pairing code shown in the Termigent terminal.</p>"
163
+ f"{err}<form method='post'><input type='hidden' name='pid' value='{html.escape(pid)}'>"
164
+ "<input name='code' inputmode='numeric' autocomplete='off' autofocus "
165
+ "style='font-size:1.4em;width:9em'> <button style='font-size:1.2em'>Pair</button></form>"
166
+ )
167
+ return _page("Pair with Termigent", form)
168
+
169
+ def _grant(self, p: _Pending) -> Response:
170
+ code = secrets.token_urlsafe(32)
171
+ self._codes[code] = AuthorizationCode(
172
+ code=code,
173
+ scopes=p.params.scopes or [],
174
+ expires_at=time.time() + CODE_TTL,
175
+ client_id=p.client.client_id,
176
+ code_challenge=p.params.code_challenge,
177
+ redirect_uri=p.params.redirect_uri,
178
+ redirect_uri_provided_explicitly=p.params.redirect_uri_provided_explicitly,
179
+ resource=p.params.resource,
180
+ )
181
+ print(f"{GREEN}✅ Paired with \"{_clean(p.client.client_name or '')}\"{RESET}", flush=True)
182
+ url = construct_redirect_uri(
183
+ str(p.params.redirect_uri), code=code, state=p.params.state
184
+ )
185
+ return RedirectResponse(url, status_code=302, headers={"Cache-Control": "no-store"})
186
+
187
+ # ---- code / token exchange --------------------------------------
188
+ async def load_authorization_code(self, client, authorization_code: str):
189
+ self._expire()
190
+ c = self._codes.get(authorization_code)
191
+ return c if c and c.client_id == client.client_id else None
192
+
193
+ def _issue(self, client_id: str, scopes: list[str], resource: str | None) -> OAuthToken:
194
+ gid = secrets.token_hex(8)
195
+ access, refresh = secrets.token_urlsafe(32), secrets.token_urlsafe(32)
196
+ now = time.time()
197
+ base = {"client_id": client_id, "scopes": scopes, "resource": resource, "gid": gid}
198
+ self._s["access"][_h(access)] = {**base, "expires_at": int(now + ACCESS_TTL)}
199
+ self._s["refresh"][_h(refresh)] = {**base, "expires_at": int(now + REFRESH_TTL)}
200
+ self._save()
201
+ return OAuthToken(
202
+ access_token=access,
203
+ token_type="Bearer",
204
+ expires_in=ACCESS_TTL,
205
+ scope=" ".join(scopes) or None,
206
+ refresh_token=refresh,
207
+ )
208
+
209
+ def _drop_gid(self, gid: str) -> None:
210
+ for kind in ("access", "refresh"):
211
+ self._s[kind] = {k: v for k, v in self._s[kind].items() if v["gid"] != gid}
212
+
213
+ async def exchange_authorization_code(self, client, authorization_code) -> OAuthToken:
214
+ self._codes.pop(authorization_code.code, None)
215
+ return self._issue(client.client_id, authorization_code.scopes, authorization_code.resource)
216
+
217
+ async def load_refresh_token(self, client, refresh_token: str):
218
+ e = self._s["refresh"].get(_h(refresh_token))
219
+ if not e or e["client_id"] != client.client_id or e["expires_at"] <= time.time():
220
+ return None
221
+ return RefreshToken(
222
+ token=refresh_token,
223
+ client_id=e["client_id"],
224
+ scopes=e["scopes"],
225
+ expires_at=e["expires_at"],
226
+ resource=e["resource"],
227
+ )
228
+
229
+ async def exchange_refresh_token(self, client, refresh_token, scopes: list[str]) -> OAuthToken:
230
+ e = self._s["refresh"].get(_h(refresh_token.token))
231
+ if not e:
232
+ raise TokenError("invalid_grant", "unknown refresh token")
233
+ self._drop_gid(e["gid"])
234
+ granted = [s for s in scopes if s in refresh_token.scopes] or refresh_token.scopes
235
+ return self._issue(client.client_id, granted, refresh_token.resource)
236
+
237
+ async def load_access_token(self, token: str):
238
+ e = self._s["access"].get(_h(token))
239
+ if not e or e["expires_at"] <= time.time():
240
+ return None
241
+ return AccessToken(
242
+ token=token,
243
+ client_id=e["client_id"],
244
+ scopes=e["scopes"],
245
+ expires_at=e["expires_at"],
246
+ resource=e["resource"],
247
+ )
248
+
249
+ async def revoke_token(self, token) -> None:
250
+ h = _h(token.token)
251
+ for kind in ("access", "refresh"):
252
+ e = self._s[kind].get(h)
253
+ if e:
254
+ self._drop_gid(e["gid"])
255
+ break
256
+ self._save()
257
+
258
+
259
+ def _page(title: str, body: str, status: int = 200) -> HTMLResponse:
260
+ doc = (
261
+ f"<!doctype html><meta charset=utf-8><meta name=viewport content='width=device-width'>"
262
+ f"<title>{html.escape(title)}</title>"
263
+ f"<body style='font-family:sans-serif;max-width:32em;margin:3em auto;padding:0 1em'>"
264
+ f"<h2>{html.escape(title)}</h2>{body}</body>"
265
+ )
266
+ return HTMLResponse(
267
+ doc,
268
+ status_code=status,
269
+ headers={
270
+ "Cache-Control": "no-store",
271
+ "X-Frame-Options": "DENY",
272
+ "Content-Security-Policy": "default-src 'none'; style-src 'unsafe-inline'; frame-ancestors 'none'",
273
+ },
274
+ )