uppercut-loopback-api 1.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,43 @@
1
+ """A small JSON API on 127.0.0.1 for a private app that a reverse proxy such as Tailscale Serve publishes."""
2
+
3
+ from ._icon import GLYPHS, pixel_mark_png
4
+ from ._server import (
5
+ LOOPBACK,
6
+ ApiError,
7
+ LoopbackApp,
8
+ LoopbackHandler,
9
+ LoopbackServer,
10
+ Route,
11
+ Routes,
12
+ health_route,
13
+ host_name,
14
+ log_line,
15
+ make_handler,
16
+ make_server,
17
+ manifest_of,
18
+ require_bearer,
19
+ serve,
20
+ tailnet_hosts,
21
+ )
22
+
23
+ __all__ = [
24
+ "GLYPHS",
25
+ "LOOPBACK",
26
+ "ApiError",
27
+ "LoopbackApp",
28
+ "LoopbackHandler",
29
+ "LoopbackServer",
30
+ "Route",
31
+ "Routes",
32
+ "health_route",
33
+ "host_name",
34
+ "log_line",
35
+ "make_handler",
36
+ "make_server",
37
+ "manifest_of",
38
+ "pixel_mark_png",
39
+ "require_bearer",
40
+ "serve",
41
+ "tailnet_hosts",
42
+ ]
43
+ __version__ = "1.0.0"
@@ -0,0 +1,61 @@
1
+ """The pixel mark: up to four letters or digits in a 5x7 pixel font, written as a PNG."""
2
+
3
+ import struct
4
+ import zlib
5
+ from typing import Sequence
6
+
7
+ # Each glyph is seven rows of five pixels, top to bottom.
8
+ GLYPHS = {
9
+ "A": "01110 10001 10001 11111 10001 10001 10001", "B": "11110 10001 10001 11110 10001 10001 11110",
10
+ "C": "01111 10000 10000 10000 10000 10000 01111", "D": "11110 10001 10001 10001 10001 10001 11110",
11
+ "E": "11111 10000 10000 11110 10000 10000 11111", "F": "11111 10000 10000 11110 10000 10000 10000",
12
+ "G": "01111 10000 10000 10011 10001 10001 01111", "H": "10001 10001 10001 11111 10001 10001 10001",
13
+ "I": "11111 00100 00100 00100 00100 00100 11111", "J": "00111 00010 00010 00010 00010 10010 01100",
14
+ "K": "10001 10010 10100 11000 10100 10010 10001", "L": "10000 10000 10000 10000 10000 10000 11111",
15
+ "M": "10001 11011 10101 10101 10001 10001 10001", "N": "10001 11001 10101 10011 10001 10001 10001",
16
+ "O": "01110 10001 10001 10001 10001 10001 01110", "P": "11110 10001 10001 11110 10000 10000 10000",
17
+ "Q": "01110 10001 10001 10001 10101 10010 01101", "R": "11110 10001 10001 11110 10100 10010 10001",
18
+ "S": "01111 10000 10000 01110 00001 00001 11110", "T": "11111 00100 00100 00100 00100 00100 00100",
19
+ "U": "10001 10001 10001 10001 10001 10001 01110", "V": "10001 10001 10001 10001 01010 01010 00100",
20
+ "W": "10001 10001 10001 10101 10101 10101 01010", "X": "10001 10001 01010 00100 01010 10001 10001",
21
+ "Y": "10001 10001 01010 00100 00100 00100 00100", "Z": "11111 00001 00010 00100 01000 10000 11111",
22
+ "0": "01110 10001 10011 10101 11001 10001 01110", "1": "00100 01100 00100 00100 00100 00100 01110",
23
+ "2": "01110 10001 00001 00010 00100 01000 11111", "3": "11110 00001 00001 01110 00001 00001 11110",
24
+ "4": "00010 00110 01010 10010 11111 00010 00010", "5": "11111 10000 11110 00001 00001 10001 01110",
25
+ "6": "01110 10000 10000 11110 10001 10001 01110", "7": "11111 00001 00010 00100 01000 01000 01000",
26
+ "8": "01110 10001 10001 01110 10001 10001 01110", "9": "01110 10001 10001 01111 00001 00001 01110",
27
+ }
28
+
29
+
30
+ def pixel_mark_png(text: str, size: int, background: Sequence[int], foreground: Sequence[int]) -> bytes:
31
+ """A square RGB PNG, `size` pixels wide, with `text` centered in the 5x7 pixel font.
32
+
33
+ Only A-Z and 0-9 are drawn, at most four of them; lower case is raised. Text with none
34
+ of those characters gives a plain tile. No image library is needed.
35
+ """
36
+ text = "".join(ch for ch in text.upper() if ch in GLYPHS)[:4]
37
+ columns = max(1, len(text)) * 6 - 1
38
+ cell = max(1, size // (columns + 7))
39
+ ox, oy = (size - columns * cell) // 2, (size - 7 * cell) // 2
40
+ lit = set()
41
+ for i, ch in enumerate(text):
42
+ for r, row in enumerate(GLYPHS[ch].split()):
43
+ for c, bit in enumerate(row):
44
+ if bit == "1":
45
+ lit.add((i * 6 + c, r))
46
+ bg, fg = bytes(background), bytes(foreground)
47
+ rows = []
48
+ for y in range(size):
49
+ row = bytearray([0])
50
+ for x in range(size):
51
+ gx, gy = x - ox, y - oy
52
+ row += fg if gx >= 0 and gy >= 0 and (gx // cell, gy // cell) in lit else bg
53
+ rows.append(bytes(row))
54
+
55
+ def chunk(kind: bytes, body: bytes) -> bytes:
56
+ return struct.pack(">I", len(body)) + kind + body + struct.pack(">I", zlib.crc32(kind + body))
57
+
58
+ return (b"\x89PNG\r\n\x1a\n"
59
+ + chunk(b"IHDR", struct.pack(">IIBBBBB", size, size, 8, 2, 0, 0, 0))
60
+ + chunk(b"IDAT", zlib.compress(b"".join(rows), 9))
61
+ + chunk(b"IEND", b""))
@@ -0,0 +1,372 @@
1
+ """A small JSON API on 127.0.0.1 for a private app that a reverse proxy publishes."""
2
+
3
+ import gzip
4
+ import hmac
5
+ import json
6
+ import os
7
+ import socket
8
+ import sys
9
+ import threading
10
+ from dataclasses import dataclass
11
+ from datetime import datetime
12
+ from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
13
+ from pathlib import Path
14
+ from typing import Callable, Dict, FrozenSet, Iterable, Optional, Tuple, Union
15
+ from urllib.parse import parse_qs
16
+
17
+ from ._icon import pixel_mark_png
18
+
19
+ LOOPBACK = "127.0.0.1"
20
+ LOOPBACK_NAMES = frozenset({LOOPBACK, "localhost"})
21
+ METHODS = ("GET", "PUT", "POST", "DELETE")
22
+ STATIC_PATHS = ("/", "/manifest.webmanifest", "/icon-180.png", "/icon-512.png")
23
+ DEFAULT_INDEX_CSP = (
24
+ "default-src 'self'; script-src 'unsafe-inline'; style-src 'unsafe-inline'; "
25
+ "img-src 'self' data:; connect-src 'self'; manifest-src 'self'; frame-ancestors 'none'"
26
+ )
27
+
28
+
29
+ class ApiError(Exception):
30
+ """Raise from a route to answer with `{"error": message, **extra}` and `status`."""
31
+
32
+ def __init__(self, status: int, message: str, **extra: object) -> None:
33
+ super().__init__(message)
34
+ self.status = status
35
+ self.body = {"error": message, **extra}
36
+
37
+
38
+ def tailnet_hosts(tailnet: str, *names: str) -> FrozenSet[str]:
39
+ """Each name and `name.tailnet`, lower case: the Host headers a tailnet proxy sends.
40
+
41
+ `tailnet_hosts("tailnet.example", "studio", "notes")` accepts `studio`,
42
+ `studio.tailnet.example`, `notes` and `notes.tailnet.example`.
43
+ """
44
+ tailnet = tailnet.strip(".").lower()
45
+ hosts = set()
46
+ for name in names:
47
+ name = name.strip(".").lower()
48
+ hosts |= {name, f"{name}.{tailnet}"}
49
+ return frozenset(hosts)
50
+
51
+
52
+ @dataclass
53
+ class LoopbackApp:
54
+ """One app's configuration.
55
+
56
+ allowed_hosts: Host header names (without port) the app answers. 127.0.0.1 and
57
+ localhost are always accepted; every other Host gets 403, which stops DNS
58
+ rebinding from a web page reaching the loopback port.
59
+ mount: path prefix the proxy publishes the app under, such as "/notes", or "" for
60
+ the root. Requests work with or without it, and a bare "/notes" redirects to "/notes/".
61
+ web_client: serve index.html at "/", a web manifest and two pixel-mark icons.
62
+ log_path / log: where the request log goes (a file, a callable, both or neither).
63
+ Lines hold the method, a known path or "<unknown>", and the status; never query
64
+ strings, bodies, headers or unknown paths.
65
+ gzip_min_bytes: gzip JSON responses at least this long when the client accepts gzip.
66
+ """
67
+
68
+ name: str
69
+ port: int
70
+ allowed_hosts: Iterable[str] = ()
71
+ mount: str = ""
72
+ short_name: str = ""
73
+ web_client: bool = True
74
+ index_html: Union[Path, bytes, None] = None
75
+ index_csp: str = DEFAULT_INDEX_CSP
76
+ background: Tuple[int, int, int] = (17, 19, 24)
77
+ accent: Tuple[int, int, int] = (110, 231, 183)
78
+ log_path: Optional[Path] = None
79
+ log: Optional[Callable[[str], None]] = None
80
+ max_body_bytes: int = 64 * 1024
81
+ gzip_min_bytes: Optional[int] = None
82
+ server_version: str = "loopback-api"
83
+
84
+ def __post_init__(self) -> None:
85
+ mount = self.mount.strip()
86
+ if mount in ("", "/"):
87
+ mount = ""
88
+ else:
89
+ mount = "/" + mount.strip("/")
90
+ if "?" in mount or "#" in mount:
91
+ raise ValueError("mount must be a plain path such as /notes")
92
+ self.mount = mount
93
+ self.allowed_hosts = frozenset(h.strip(".").lower() for h in self.allowed_hosts)
94
+
95
+ @property
96
+ def accepted_hosts(self) -> FrozenSet[str]:
97
+ return frozenset(self.allowed_hosts) | LOOPBACK_NAMES
98
+
99
+
100
+ _log_lock = threading.Lock()
101
+
102
+
103
+ def log_line(app: LoopbackApp, line: str) -> None:
104
+ """Write one line to the app's log. Never pass request bodies, query strings or secrets."""
105
+ if app.log is not None:
106
+ try:
107
+ app.log(line)
108
+ except Exception: # noqa: BLE001 - logging must never break a request
109
+ pass
110
+ if app.log_path is not None:
111
+ stamp = datetime.now().isoformat(timespec="seconds")
112
+ try:
113
+ with _log_lock, open(app.log_path, "a", encoding="utf-8") as fh:
114
+ fh.write(f"{stamp} {line}\n")
115
+ except OSError:
116
+ pass
117
+
118
+
119
+ def _hex(rgb: Tuple[int, int, int]) -> str:
120
+ return "#%02x%02x%02x" % tuple(rgb)
121
+
122
+
123
+ def manifest_of(app: LoopbackApp) -> bytes:
124
+ """The web app manifest: standalone display, the app's colors and its two icons."""
125
+ return json.dumps({
126
+ "name": app.name, "short_name": app.short_name or app.name,
127
+ "start_url": "./", "scope": "./", "display": "standalone",
128
+ "background_color": _hex(app.background), "theme_color": _hex(app.background),
129
+ "icons": [
130
+ {"src": "icon-180.png", "sizes": "180x180", "type": "image/png"},
131
+ {"src": "icon-512.png", "sizes": "512x512", "type": "image/png"},
132
+ ],
133
+ }).encode()
134
+
135
+
136
+ def host_name(header: str) -> str:
137
+ """The host part of a Host header, lower case, without port, brackets or a final dot."""
138
+ value = header.strip().lower()
139
+ if value.startswith("["):
140
+ end = value.find("]")
141
+ return value[1:end] if end > 0 else ""
142
+ if value.count(":") == 1:
143
+ value = value.split(":", 1)[0]
144
+ return value.rstrip(".")
145
+
146
+
147
+ Payload = object
148
+ Route = Callable[["LoopbackHandler", Optional[dict]], Tuple[int, Payload]]
149
+ Routes = Dict[Tuple[str, str], Route]
150
+
151
+
152
+ class LoopbackHandler(BaseHTTPRequestHandler):
153
+ """Request handler for one app. Build it with make_handler(); routes do the app's work."""
154
+
155
+ app: LoopbackApp
156
+ routes: Routes = {}
157
+ index_bytes: bytes = b""
158
+ icons: Dict[str, bytes] = {}
159
+ manifest: bytes = b""
160
+ sys_version = ""
161
+
162
+ # The base class would log raw request lines and parser errors, which can hold secrets.
163
+ def log_message(self, format: str, *args: object) -> None: # noqa: A002 - stdlib signature
164
+ pass
165
+
166
+ def log_request(self, code: object = "-", size: object = "-") -> None:
167
+ command = getattr(self, "command", None)
168
+ method = command if command in METHODS + ("HEAD", "OPTIONS") else "OTHER"
169
+ shown = "<unknown>"
170
+ if hasattr(self, "path"):
171
+ sub = self.sub_path()
172
+ if sub == "redirect":
173
+ shown = self.app.mount
174
+ elif sub in self.known_paths():
175
+ shown = self.app.mount + sub
176
+ log_line(self.app, f"{self.address_string()} {method} {shown} {code}")
177
+
178
+ def known_paths(self) -> set:
179
+ paths = {path for _, path in self.routes}
180
+ return paths | set(STATIC_PATHS) if self.app.web_client else paths
181
+
182
+ def host_ok(self) -> bool:
183
+ hosts = self.headers.get_all("Host", [])
184
+ return len(hosts) == 1 and host_name(hosts[0]) in self.app.accepted_hosts
185
+
186
+ def sub_path(self) -> str:
187
+ """The request path below the mount, or "redirect" for the bare mount."""
188
+ path = self.path.split("?", 1)[0]
189
+ mount = self.app.mount
190
+ if not mount:
191
+ return path
192
+ if path == mount:
193
+ return "redirect"
194
+ return path[len(mount):] if path.startswith(mount + "/") else path
195
+
196
+ def query(self) -> Dict[str, str]:
197
+ """Query parameters, first value of each. Query strings are never logged."""
198
+ raw = self.path.split("?", 1)[1] if "?" in self.path else ""
199
+ return {key: values[0] for key, values in parse_qs(raw, keep_blank_values=True).items()}
200
+
201
+ def accepts_gzip(self) -> bool:
202
+ for part in (self.headers.get("Accept-Encoding") or "").split(","):
203
+ coding, *params = part.split(";")
204
+ if coding.strip().lower() != "gzip":
205
+ continue
206
+ quality = 1.0
207
+ for param in params:
208
+ key, _, value = param.partition("=")
209
+ if key.strip().lower() == "q":
210
+ try:
211
+ quality = float(value)
212
+ except ValueError:
213
+ quality = 0.0
214
+ return quality > 0
215
+ return False
216
+
217
+ def send(self, status: int, body: object, ctype: str = "application/json",
218
+ extra: Optional[Dict[str, str]] = None) -> None:
219
+ """Send a response with no-store caching and the security headers."""
220
+ headers = dict(extra or {})
221
+ if not isinstance(body, (bytes, bytearray)):
222
+ body = json.dumps(body).encode()
223
+ limit = self.app.gzip_min_bytes
224
+ if limit is not None and len(body) >= limit and self.accepts_gzip():
225
+ body = gzip.compress(body, compresslevel=6)
226
+ headers["Content-Encoding"] = "gzip"
227
+ headers["Vary"] = "Accept-Encoding"
228
+ self.send_response(status)
229
+ self.send_header("Content-Type", ctype)
230
+ self.send_header("Content-Length", str(len(body)))
231
+ self.send_header("Cache-Control", "no-store")
232
+ self.send_header("X-Content-Type-Options", "nosniff")
233
+ self.send_header("Referrer-Policy", "no-referrer")
234
+ for key, value in headers.items():
235
+ self.send_header(key, value)
236
+ self.end_headers()
237
+ self.wfile.write(body)
238
+
239
+ def read_json(self) -> dict:
240
+ """One Content-Length, no Transfer-Encoding, a JSON object within app.max_body_bytes."""
241
+ lengths = self.headers.get_all("Content-Length", [])
242
+ if self.headers.get("Transfer-Encoding") is not None or len(lengths) != 1:
243
+ raise ApiError(400, "one Content-Length is required; Transfer-Encoding is unsupported")
244
+ raw = lengths[0].strip()
245
+ if not (raw.isascii() and raw.isdecimal()):
246
+ raise ApiError(400, "bad body size")
247
+ length = int(raw)
248
+ if length > self.app.max_body_bytes:
249
+ raise ApiError(413, "body too large")
250
+ if length <= 0:
251
+ raise ApiError(400, "bad body size")
252
+ payload = self.rfile.read(length)
253
+ if len(payload) != length:
254
+ raise ApiError(400, "body ended early")
255
+ try:
256
+ body = json.loads(payload)
257
+ except (ValueError, RecursionError):
258
+ raise ApiError(400, "body must be JSON") from None
259
+ if not isinstance(body, dict):
260
+ raise ApiError(400, "body must be a JSON object")
261
+ return body
262
+
263
+ def dispatch(self) -> None:
264
+ if not self.host_ok():
265
+ return self.send(403, {"error": "host not allowed"})
266
+ sub = self.sub_path()
267
+ if sub == "redirect":
268
+ return self.send(301, b"", "text/plain", {"Location": self.app.mount + "/"})
269
+ if self.app.web_client and self.command == "GET" and sub in STATIC_PATHS:
270
+ if sub == "/":
271
+ return self.send(200, self.index_bytes, "text/html; charset=utf-8",
272
+ {"Content-Security-Policy": self.app.index_csp})
273
+ if sub == "/manifest.webmanifest":
274
+ return self.send(200, self.manifest, "application/manifest+json")
275
+ return self.send(200, self.icons[sub], "image/png")
276
+ route = self.routes.get((self.command, sub))
277
+ if route is None:
278
+ known = any(path == sub for _, path in self.routes)
279
+ return self.send(405 if known else 404,
280
+ {"error": "method not allowed" if known else "not found"})
281
+ try:
282
+ body = self.read_json() if self.command in ("PUT", "POST") else None
283
+ status, result = route(self, body)
284
+ except ApiError as error:
285
+ return self.send(error.status, error.body)
286
+ except OSError as error:
287
+ log_line(self.app, f"{self.command} {self.app.mount}{sub} failed: {type(error).__name__}")
288
+ return self.send(500, {"error": f"server could not do that: {error.strerror or type(error).__name__}"})
289
+ except Exception as error: # noqa: BLE001 - a bug in a route still gets a JSON answer
290
+ log_line(self.app, f"{self.command} {self.app.mount}{sub} failed: {type(error).__name__}")
291
+ return self.send(500, {"error": "internal error"})
292
+ return self.send(status, result)
293
+
294
+ do_GET = do_PUT = do_POST = do_DELETE = dispatch
295
+
296
+
297
+ def make_handler(app: LoopbackApp, routes: Routes) -> type:
298
+ """Build the handler class for one app. Routes are keyed by (method, path below the mount)."""
299
+ for method, path in routes:
300
+ if method not in METHODS or not path.startswith("/"):
301
+ raise ValueError(f"bad route {(method, path)}: method must be one of {METHODS}, path must start with /")
302
+ index = app.index_html
303
+ if isinstance(index, Path):
304
+ index = index.read_bytes() if index.exists() else None
305
+ if index is None:
306
+ index = f"<!doctype html><title>{app.name}</title><p>{app.name} has no web client yet.</p>".encode()
307
+ mark = app.short_name or app.name
308
+ icons = {f"/icon-{s}.png": pixel_mark_png(mark, s, app.background, app.accent) for s in (180, 512)} \
309
+ if app.web_client else {}
310
+ return type("Handler", (LoopbackHandler,), {
311
+ "app": app, "routes": dict(routes), "index_bytes": bytes(index),
312
+ "icons": icons, "manifest": manifest_of(app) if app.web_client else b"",
313
+ "server_version": app.server_version,
314
+ })
315
+
316
+
317
+ def health_route(check: Optional[Callable[[], dict]] = None, **fields: object) -> Route:
318
+ """GET route answering `{"ok": true, **fields, **check()}`. Clients and installers poll it."""
319
+ def route(_handler: LoopbackHandler, _body: Optional[dict]) -> Tuple[int, dict]:
320
+ return 200, {"ok": True, **fields, **(check() if check else {})}
321
+ return route
322
+
323
+
324
+ def require_bearer(token: str, route: Route) -> Route:
325
+ """Wrap a route so it answers 401 unless `Authorization: Bearer <token>` matches."""
326
+ if not token:
327
+ raise ValueError("token must not be empty")
328
+ expected = token.encode()
329
+
330
+ def guarded(handler: LoopbackHandler, body: Optional[dict]) -> Tuple[int, Payload]:
331
+ supplied = handler.headers.get("Authorization") or ""
332
+ if supplied.startswith("Bearer "):
333
+ supplied = supplied[len("Bearer "):]
334
+ if not hmac.compare_digest(supplied.strip().encode(), expected):
335
+ raise ApiError(401, "unauthorized")
336
+ return route(handler, body)
337
+ return guarded
338
+
339
+
340
+ class LoopbackServer(ThreadingHTTPServer):
341
+ """ThreadingHTTPServer that owns its port alone.
342
+
343
+ The stdlib server sets SO_REUSEADDR, and on Windows that lets a second server bind
344
+ the same port with no error and take some of the first one's requests. On Windows
345
+ this sets SO_EXCLUSIVEADDRUSE instead, so a second bind fails; elsewhere SO_REUSEADDR
346
+ already refuses a second listener.
347
+ """
348
+
349
+ allow_reuse_address = os.name != "nt"
350
+
351
+ def server_bind(self) -> None:
352
+ if os.name == "nt" and hasattr(socket, "SO_EXCLUSIVEADDRUSE"):
353
+ self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_EXCLUSIVEADDRUSE, 1)
354
+ super().server_bind()
355
+
356
+
357
+ def make_server(app: LoopbackApp, routes: Routes, port: Optional[int] = None) -> LoopbackServer:
358
+ """Bind 127.0.0.1 only (port 0 picks a free one) and return the server, not yet serving."""
359
+ return LoopbackServer((LOOPBACK, app.port if port is None else port), make_handler(app, routes))
360
+
361
+
362
+ def serve(app: LoopbackApp, routes: Routes, port: Optional[int] = None) -> None:
363
+ """Bind 127.0.0.1 only and serve until stopped. A taken port raises OSError."""
364
+ server = make_server(app, routes, port)
365
+ address = f"http://{LOOPBACK}:{server.server_address[1]}{app.mount}/"
366
+ log_line(app, f"listening on {address}")
367
+ if sys.stdout:
368
+ print(f"{app.name} on {address}", flush=True)
369
+ try:
370
+ server.serve_forever()
371
+ finally:
372
+ server.server_close()
File without changes
@@ -0,0 +1,107 @@
1
+ Metadata-Version: 2.5
2
+ Name: uppercut-loopback-api
3
+ Version: 1.0.0
4
+ Summary: A small JSON API on 127.0.0.1 for a private app behind Tailscale Serve or another reverse proxy: Host allowlist, strict bodies, redacted logs, exclusive port bind.
5
+ Project-URL: Source, https://github.com/uppercut-labs/py-kit/tree/main/packages/uppercut-loopback-api
6
+ Author-email: Uppercut Labs <packages@uppercut-labs.com>
7
+ License-Expression: MIT
8
+ Keywords: dns-rebinding,http,json-api,loopback,pwa,reverse-proxy,tailscale
9
+ Classifier: Development Status :: 5 - Production/Stable
10
+ Classifier: Intended Audience :: Developers
11
+ Classifier: Operating System :: MacOS
12
+ Classifier: Operating System :: Microsoft :: Windows
13
+ Classifier: Operating System :: POSIX
14
+ Classifier: Programming Language :: Python :: 3
15
+ Classifier: Programming Language :: Python :: 3.9
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 :: Internet :: WWW/HTTP :: HTTP Servers
22
+ Classifier: Typing :: Typed
23
+ Requires-Python: >=3.9
24
+ Description-Content-Type: text/markdown
25
+
26
+ # uppercut-loopback-api
27
+
28
+ A small JSON API server for a private app that runs on one machine and is reached through a reverse proxy, such as Tailscale Serve, from phones and other computers. It binds 127.0.0.1 only and owns its port alone, refuses Host headers it doesn't know, reads request bodies strictly, answers every error as JSON, and keeps secrets out of its request log. It can also serve a single-page web client with a web manifest and generated icons, so the app installs as a PWA. Standard library only, Python 3.9 or later.
29
+
30
+ ```sh
31
+ pip install uppercut-loopback-api
32
+ ```
33
+
34
+ ```python
35
+ from pathlib import Path
36
+ from uppercut_loopback_api import ApiError, LoopbackApp, health_route, serve, tailnet_hosts
37
+
38
+ APP = LoopbackApp(
39
+ name="Notes Remote",
40
+ short_name="NTS", # drawn on the icons in a 5x7 pixel font
41
+ mount="/notes", # the path the proxy publishes the app under
42
+ port=8890,
43
+ allowed_hosts=tailnet_hosts("tailnet.example", "studio"),
44
+ index_html=Path("web/index.html"),
45
+ log_path=Path("notes-remote.log"),
46
+ )
47
+
48
+ NOTES = {"a": "first note"}
49
+
50
+
51
+ def get_note(handler, _body):
52
+ note_id = handler.query().get("id", "")
53
+ if note_id not in NOTES:
54
+ raise ApiError(404, "no such note")
55
+ return 200, {"id": note_id, "text": NOTES[note_id]}
56
+
57
+
58
+ def put_note(_handler, body):
59
+ if not isinstance(body.get("id"), str) or not isinstance(body.get("text"), str):
60
+ raise ApiError(400, 'body must be {"id": str, "text": str}')
61
+ NOTES[body["id"]] = body["text"]
62
+ return 200, {"saved": True}
63
+
64
+
65
+ ROUTES = {
66
+ ("GET", "/api/health"): health_route(lambda: {"notes": len(NOTES)}, app="notes"),
67
+ ("GET", "/api/note"): get_note,
68
+ ("PUT", "/api/note"): put_note,
69
+ }
70
+
71
+ if __name__ == "__main__":
72
+ serve(APP, ROUTES)
73
+ ```
74
+
75
+ Then publish it to your tailnet, for example with `tailscale serve --bg --set-path=/notes http://127.0.0.1:8890/notes`.
76
+
77
+ ## What it does for every request
78
+
79
+ - **Host check.** Only the names in `allowed_hosts`, plus `127.0.0.1` and `localhost`, are answered; anything else, a missing Host or two Host headers get `403`. This stops a web page from reaching the loopback port through DNS rebinding.
80
+ - **Mount.** Routes work under the mount (`/notes/api/note`) and without it (`/api/note`), so a dedicated hostname can proxy to the root. A bare `/notes` redirects to `/notes/`. Use `mount=""` for an app at the root.
81
+ - **Strict bodies.** `PUT` and `POST` need exactly one decimal `Content-Length` within `max_body_bytes`, no `Transfer-Encoding`, and a JSON object. Anything else is `400` (or `413` when too long) before your route runs.
82
+ - **JSON errors.** Raise `ApiError(status, message, **extra)` for `{"error": message, **extra}`. An `OSError` becomes `500` with its reason; any other exception becomes `500 {"error": "internal error"}` and only its type is logged.
83
+ - **Headers.** Every response has `Cache-Control: no-store`, `X-Content-Type-Options: nosniff` and `Referrer-Policy: no-referrer`; the web client also gets a Content-Security-Policy (`index_csp`).
84
+ - **Request log.** One line per request: client address, method, the mount plus a known path (or `<unknown>`), and the status. Query strings, bodies, headers, unknown paths and parser error text are never written.
85
+ - **Exclusive port.** On Windows the stdlib server sets `SO_REUSEADDR`, which lets a second copy bind the same port without an error and take some of the first one's requests. `LoopbackServer` sets `SO_EXCLUSIVEADDRUSE` instead, so a second copy fails to start.
86
+
87
+ ## API
88
+
89
+ | Name | What it is |
90
+ | --- | --- |
91
+ | `LoopbackApp(name, port, allowed_hosts=(), mount="", short_name="", web_client=True, index_html=None, index_csp=..., background=(17, 19, 24), accent=(110, 231, 183), log_path=None, log=None, max_body_bytes=65536, gzip_min_bytes=None, server_version="loopback-api")` | One app's configuration. `index_html` is a path or bytes; a missing file serves a placeholder. `log` is a callable that gets each log line, for example a `logging` method. `gzip_min_bytes` turns on gzip for JSON responses at least that long when the client accepts it. |
92
+ | `tailnet_hosts(tailnet, *names)` | `{name, name.tailnet}` for each name, for `allowed_hosts` |
93
+ | `serve(app, routes, port=None)` | Bind 127.0.0.1 and serve until stopped |
94
+ | `make_server(app, routes, port=None)` | The bound `LoopbackServer`, not yet serving (port `0` picks a free one; useful in tests) |
95
+ | `make_handler(app, routes)` | The request handler class |
96
+ | `health_route(check=None, **fields)` | A route answering `{"ok": true, **fields, **check()}` |
97
+ | `require_bearer(token, route)` | Wraps a route so it answers `401` unless `Authorization: Bearer <token>` matches (constant-time compare) |
98
+ | `ApiError(status, message, **extra)` | Raise from a route for a JSON error |
99
+ | `log_line(app, line)` | Write a line to the app's log yourself; never pass secrets |
100
+ | `pixel_mark_png(text, size, background, foreground)` | A square PNG with up to four letters or digits in the pixel font |
101
+ | `LoopbackServer`, `LoopbackHandler`, `host_name`, `manifest_of`, `GLYPHS`, `LOOPBACK` | The pieces the above are built from |
102
+
103
+ Routes are a dict keyed by `(method, path)`, where the method is `GET`, `PUT`, `POST` or `DELETE` and the path is below the mount. A route is called as `route(handler, body)`, where `body` is the parsed JSON object for `PUT` and `POST` and `None` otherwise, and returns `(status, payload)` with a JSON-serializable payload. The handler gives routes `handler.query()` (first value of each query parameter) and `handler.headers`.
104
+
105
+ ## License
106
+
107
+ MIT
@@ -0,0 +1,7 @@
1
+ uppercut_loopback_api/__init__.py,sha256=nHo0buhGj16g_KdknW5Mc9lOrkNFq2S1NVRMd7GOabE,799
2
+ uppercut_loopback_api/_icon.py,sha256=9tFMfJzKGX8l6R_eXWPbrk6L_oZZCIp7JI5jzhPH9D0,3563
3
+ uppercut_loopback_api/_server.py,sha256=kRYn5lYrmlKcnXaQutOCFcdse1v5Mwathf2S5aKpvM0,15661
4
+ uppercut_loopback_api/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
5
+ uppercut_loopback_api-1.0.0.dist-info/METADATA,sha256=IKRTWcBZ-ug-h5uGGFijBrj0lMQnOtiCVZYVz1RH_-o,6823
6
+ uppercut_loopback_api-1.0.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
7
+ uppercut_loopback_api-1.0.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.33.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any