Skip to content

ServerKit is a lightweight, modern server control panel for managing web applications, databases, and services on your VPS or dedicated server. Built with Python/Flask backend and React frontend.

Serve the panel through the Cloud relay tunnel

Juan Denisc7b6f145d1ae
diff --git a/backend/app/__init__.py b/backend/app/__init__.py
index 6c09f0b0..fa74428a 100644
--- a/backend/app/__init__.py
+++ b/backend/app/__init__.py
@@ -499,11 +499,20 @@ def create_app(config_name=None):
# path-prefix exceptions can turn a pending token into a full session.
# Serve frontend for root path
+ def _spa_page():
+ # Opened from ServerKit Cloud, the page is served under the relay's
+ # path prefix (app/services/connect_session.py).
+ from app.services import connect_session
+ prefix = connect_session.tunnel_prefix(request)
+ if prefix:
+ return connect_session.index_under_prefix(app.static_folder, prefix)
+ return send_from_directory(app.static_folder, 'index.html')
+
@app.route('/')
def serve_index():
index = os.path.join(app.static_folder, 'index.html') if app.static_folder else None
if index and os.path.isfile(index):
- return send_from_directory(app.static_folder, 'index.html')
+ return _spa_page()
return {'message': 'ServerKit API is running', 'docs': '/api/v1/'}, 200
# Expected application failures. Services raise these typed errors and the
@@ -574,7 +583,7 @@ def create_app(config_name=None):
# Serve SPA index.html if it exists, otherwise JSON 404
index = os.path.join(app.static_folder, 'index.html') if app.static_folder else None
if index and os.path.isfile(index):
- return send_from_directory(app.static_folder, 'index.html')
+ return _spa_page()
return {'error': 'Not found'}, 404
return app
diff --git a/backend/app/api/auth.py b/backend/app/api/auth.py
index 0cf18efc..fa1b810a 100644
--- a/backend/app/api/auth.py
+++ b/backend/app/api/auth.py
@@ -454,6 +454,38 @@ def redeem_login_link():
}), 200
+# ==========================================
+# SERVERKIT CLOUD (the relay tunnel)
+# ==========================================
+@auth_bp.route('/connect-session', methods=['POST'])
[email protected]("30 per minute")
+def connect_session():
+ """Sign in somebody who opened this panel from ServerKit Cloud.
+
+ The relay brought Cloud's signed grant with the request; it is verified
+ here against Cloud's JWKS and mapped to the panel user with the same
+ email (app/services/connect_session.py). Anybody else gets the normal
+ login page, which is what the 4xx tells the SPA.
+ """
+ from app.services import connect_session as cs
+ try:
+ user, claims = cs.user_for_request(request)
+ except cs.ConnectSessionRefused as exc:
+ logger.info('ServerKit Cloud sign-in refused (%s)', exc.code)
+ raise AuthenticationError(exc.message, code=f'auth.connect_{exc.code}')
+ # The panel's own second factor still applies: Cloud vouches for the
+ # email, not for this panel's authenticator.
+ if user.totp_enabled:
+ raise AuthenticationError('This account uses two-factor authentication. '
+ 'Sign in with the panel login.', code='auth.connect_2fa')
+ access_token, refresh_token = cs.sign_in(user, claims)
+ return jsonify({
+ 'user': user.to_dict(),
+ 'access_token': access_token,
+ 'refresh_token': refresh_token
+ }), 200
+
+
# ==========================================
# DEMO MODE
# ==========================================
diff --git a/backend/app/middleware/demo.py b/backend/app/middleware/demo.py
index f3453a6e..722850b8 100644
--- a/backend/app/middleware/demo.py
+++ b/backend/app/middleware/demo.py
@@ -18,6 +18,7 @@ ALLOWLIST = {
'/api/v1/auth/refresh',
'/api/v1/auth/logout',
'/api/v1/auth/login-links/redeem',
+ '/api/v1/auth/connect-session',
}
diff --git a/backend/app/services/connect_client.py b/backend/app/services/connect_client.py
index 237038f2..7976e273 100644
--- a/backend/app/services/connect_client.py
+++ b/backend/app/services/connect_client.py
@@ -674,6 +674,8 @@ class RelayClient:
self._thread = None
self._stop = threading.Event()
self._ws = None
+ # The browser tunnel for the live connection (connect_tunnel.py).
+ self._tunnel = None
self._attempts_at = collections.deque()
self._flap_logged = False
self._last_written = None # (state, reason, transport) transition dedup
@@ -852,6 +854,7 @@ class RelayClient:
return f'refused:{_classify_ws_failure(exc)}'
self._ws = ws
+ self._tunnel = self._new_tunnel(ws)
try:
# Consent is connection-scoped. Reconnect using empty probes.
if self._diagnostics_collect:
@@ -905,6 +908,9 @@ class RelayClient:
return f'drop:{_classify_ws_failure(exc)}'
finally:
self._ws = None
+ if self._tunnel is not None:
+ self._tunnel.shutdown()
+ self._tunnel = None
for batch in reversed(list(self._logs_inflight.values())):
self._logs.requeue(batch)
self._logs_inflight.clear()
@@ -1007,11 +1013,24 @@ class RelayClient:
self._metrics.requeue(samples)
logger.debug('Connect metrics: send failed, samples kept', exc_info=True)
+ def _new_tunnel(self, ws):
+ """The browser tunnel for this connection (connect_tunnel.py)."""
+ from app.services import cli_api_client, connect_tunnel
+ return connect_tunnel.Tunnel(lambda frame: self._send(ws, frame),
+ cli_api_client.resolve_port())
+
def _handle_frame(self, ws, raw):
try:
frame = json.loads(raw)
except ValueError:
return
+ tunnel = getattr(self, '_tunnel', None)
+ if frame.get('t') == 'data':
+ if tunnel is not None:
+ tunnel.data(frame)
+ return
+ if frame.get('t') == 'close' and tunnel is not None and tunnel.close(frame):
+ return
if frame.get('t') == 'close':
stream_id = frame.get('s')
if stream_id is None:
@@ -1051,6 +1070,10 @@ class RelayClient:
if frame.get('k') == 'command':
self._run_command(ws, frame)
return
+ # "Open panel" in ServerKit Cloud: a browser request or its
+ # Socket.IO socket, replayed on this panel's own port.
+ if tunnel is not None and tunnel.open(frame):
+ return
# Anything else is a stream this client version does not speak.
# Refusing honestly is what stops the relay holding it open.
ws.send(json.dumps({
diff --git a/backend/app/services/connect_session.py b/backend/app/services/connect_session.py
new file mode 100644
index 00000000..750294d8
--- /dev/null
+++ b/backend/app/services/connect_session.py
@@ -0,0 +1,170 @@
+"""Signing in somebody who opened this panel from ServerKit Cloud.
+
+The relay passes Cloud's session grant beside every tunnelled request, and
+connect_tunnel.py hands it to the panel as ``X-ServerKit-Connect-Grant``.
+Here it is checked the whole way — nothing about the header is trusted:
+
+- the request came over the loopback listener, which is the only way the
+ tunnel reaches the panel;
+- this panel is paired, and the grant names this device;
+- the signature holds against Cloud's JWKS, with a key Cloud published for
+ session grants (a command key cannot sign somebody in);
+- it has not expired.
+
+The grant says who opened the panel (Cloud user email). If this panel has an
+active user with that email, that user is signed in; otherwise the panel's
+own login page shows, exactly as it would have.
+
+This module also serves the SPA's page under the tunnel's path prefix, so
+the panel's absolute asset URLs keep working behind the relay.
+"""
+
+import base64
+import json
+import logging
+import os
+import re
+import time
+
+logger = logging.getLogger(__name__)
+
+GRANT_HEADER = 'X-ServerKit-Connect-Grant'
+PREFIX_HEADER = 'X-ServerKit-Prefix'
+PREFIX = re.compile(r'^/t/dev_[A-Za-z0-9_-]+$')
+LOOPBACK = ('127.0.0.1', '::1', '::ffff:127.0.0.1')
+JWKS_TTL_S = 600
+
+
+class ConnectSessionRefused(Exception):
+ def __init__(self, code: str, message: str):
+ super().__init__(message)
+ self.code = code
+ self.message = message
+
+
+def from_loopback(request) -> bool:
+ # `remote_addr` before any proxy fix: the tunnel's requests are made on
+ # this machine, and connect_tunnel.py strips the browser's X-Forwarded-*.
+ orig = request.environ.get('werkzeug.proxy_fix.orig') or {}
+ addr = orig.get('REMOTE_ADDR') or request.remote_addr
+ return addr in LOOPBACK
+
+
+_jwks_cache = {'at': 0.0, 'jwks': None}
+
+
+def _jwks(cloud_url: str, refresh: bool = False):
+ now = time.time()
+ if not refresh and _jwks_cache['jwks'] and now - _jwks_cache['at'] < JWKS_TTL_S:
+ return _jwks_cache['jwks']
+ from app.services.connect_updates import fetch_jwks
+ jwks = fetch_jwks(cloud_url)
+ if jwks:
+ _jwks_cache.update(at=now, jwks=jwks)
+ return jwks or _jwks_cache['jwks']
+
+
+def verify_grant(token: str, device_id: str, jwks: dict, now: float = None) -> dict:
+ """The grant's claims, or ConnectSessionRefused with why not."""
+ import jwt
+ from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PublicKey
+
+ if not token:
+ raise ConnectSessionRefused('no_grant', 'This request did not come from ServerKit Cloud.')
+ if not jwks or not jwks.get('keys'):
+ raise ConnectSessionRefused('no_keys', "This panel could not read ServerKit Cloud's keys.")
+ try:
+ kid = jwt.get_unverified_header(token).get('kid')
+ except Exception:
+ raise ConnectSessionRefused('bad_grant', 'The grant is not readable.')
+ key = next((k for k in jwks['keys'] if k.get('kid') == kid), None)
+ # Keys carry their purpose; one published for anything else (signed
+ # commands) is not accepted as a sign-in.
+ if key is None or key.get('crv') != 'Ed25519' or key.get('purpose', 'session') != 'session':
+ raise ConnectSessionRefused('unknown_key', 'The grant was signed with a key this panel does not trust.')
+ try:
+ raw = base64.urlsafe_b64decode(key['x'] + '=' * (-len(key['x']) % 4))
+ claims = jwt.decode(token, Ed25519PublicKey.from_public_bytes(raw),
+ algorithms=['EdDSA'], options={'verify_exp': False})
+ except Exception:
+ raise ConnectSessionRefused('bad_signature', 'The grant signature did not verify.')
+ if claims.get('dev') != device_id:
+ raise ConnectSessionRefused('wrong_device', 'The grant is for a different server.')
+ now = now if now is not None else time.time()
+ if not claims.get('exp') or float(claims['exp']) < now:
+ raise ConnectSessionRefused('expired', 'The grant has expired. Open the panel again from ServerKit Cloud.')
+ if not claims.get('email'):
+ raise ConnectSessionRefused('no_email', 'The grant does not say who opened the panel.')
+ return claims
+
+
+def user_for_request(request):
+ """The panel user to sign in, and the grant's claims."""
+ from sqlalchemy import func
+
+ from app.models import User
+ from app.services.connect_client import _read_connect_file, resolve_cloud_url
+
+ if not from_loopback(request):
+ raise ConnectSessionRefused('not_tunnel', 'This request did not come through the ServerKit Cloud tunnel.')
+ cfg = _read_connect_file()
+ device_id = cfg.get('device_id')
+ if not device_id:
+ raise ConnectSessionRefused('not_paired', 'This panel is not connected to ServerKit Cloud.')
+ token = request.headers.get(GRANT_HEADER)
+ cloud_url = cfg.get('cloud_url') or resolve_cloud_url()
+ try:
+ claims = verify_grant(token, device_id, _jwks(cloud_url))
+ except ConnectSessionRefused as exc:
+ # Cloud mints and rotates keys on its own schedule: one refetch.
+ if exc.code != 'unknown_key':
+ raise
+ claims = verify_grant(token, device_id, _jwks(cloud_url, refresh=True))
+ user = User.query.filter(func.lower(User.email) == claims['email'].lower()).first()
+ if user is None or not user.is_active:
+ raise ConnectSessionRefused(
+ 'no_user', f"This panel has no active user with the email {claims['email']}. "
+ f"Sign in with a panel account instead.")
+ return user, claims
+
+
+def sign_in(user, claims):
+ """Record the sign-in and issue the panel's own session tokens."""
+ from datetime import datetime
+
+ from app import db
+ from app.middleware.session_auth import issue_session_tokens
+ from app.services.audit_service import AuditService
+
+ user.reset_failed_login()
+ user.last_login_at = datetime.utcnow()
+ db.session.commit()
+ AuditService.log_login(user.id, success=True, details={
+ 'method': 'serverkit_cloud', 'cloud_org': claims.get('org'),
+ 'grant': claims.get('jti')})
+ db.session.commit()
+ return issue_session_tokens(user.id)
+
+
+# ---------- the SPA page under the tunnel's prefix ----------
+
+def tunnel_prefix(request) -> str:
+ """The path the panel is mounted under behind the relay, or ''."""
+ prefix = request.headers.get(PREFIX_HEADER) or ''
+ return prefix if PREFIX.match(prefix) and from_loopback(request) else ''
+
+
+def index_under_prefix(static_folder: str, prefix: str):
+ """index.html with its root-relative asset URLs moved under `prefix`,
+ and the prefix announced to the SPA (frontend/src/services/tunnelBase.js)."""
+ from flask import Response
+
+ with open(os.path.join(static_folder, 'index.html'), encoding='utf-8') as fh:
+ page = fh.read()
+ # src="/x" and href="/x", never a protocol-relative "//host/x".
+ page = re.sub(r'(?<![\w-])(src|href)="/(?!/)', lambda m: f'{m.group(1)}="{prefix}/', page)
+ # The import map for runtime-loaded extensions.
+ page = page.replace('"/serverkit-vendor/', f'"{prefix}/serverkit-vendor/')
+ announce = f'<script>window.__SERVERKIT_BASE__={json.dumps(prefix)};</script>'
+ page = page.replace('<head>', '<head>' + announce, 1)
+ return Response(page, mimetype='text/html', headers={'Cache-Control': 'no-store'})
diff --git a/backend/app/services/connect_tunnel.py b/backend/app/services/connect_tunnel.py
new file mode 100644
index 00000000..31b8c5ec
--- /dev/null
+++ b/backend/app/services/connect_tunnel.py
@@ -0,0 +1,267 @@
+"""The browser tunnel, panel side (ServerKit Cloud plan 01 M3).
+
+When somebody presses "Open panel" in ServerKit Cloud, their browser talks
+to the relay, and the relay opens streams down this panel's connection:
+
+- ``http``: one request. This module replays it against the panel's own
+ loopback listener and streams the answer back as ``data`` frames, then a
+ ``close`` frame carrying the status and headers.
+- ``sio``: one Socket.IO WebSocket. This module opens the same WebSocket on
+ the loopback listener and pumps messages both ways until either side ends.
+
+Both arrive with Cloud's signed session grant beside them. It is passed on
+as ``X-ServerKit-Connect-Grant``, and the panel verifies it itself against
+Cloud's JWKS before it signs anybody in (app/services/connect_session.py) —
+nothing here trusts it.
+
+Frames (protocol/__init__.py in serverkit-cloud):
+ open {"s", "t": "open", "k": "http", "p": {method, path, headers,
+ body_b64?, grant?, prefix?}}
+ data {"s", "t": "data", "p": <base64 bytes>}
+ close {"s", "t": "close", "p": {status, headers}} (or "reason" on refusal)
+"""
+
+import base64
+import logging
+import queue
+import re
+import threading
+from concurrent.futures import ThreadPoolExecutor
+
+logger = logging.getLogger(__name__)
+
+# The relay caps a frame at 256 KB; base64 grows a chunk by a third.
+CHUNK_BYTES = 96 * 1024
+HTTP_TIMEOUT_S = 30
+MAX_HTTP_WORKERS = 16
+
+GRANT_HEADER = 'X-ServerKit-Connect-Grant'
+PREFIX_HEADER = 'X-ServerKit-Prefix'
+PREFIX = re.compile(r'^/t/dev_[A-Za-z0-9_-]+$')
+
+HOP_BY_HOP = {'connection', 'keep-alive', 'transfer-encoding', 'upgrade',
+ 'proxy-authorization', 'proxy-authenticate', 'te', 'trailer',
+ 'content-length', 'host'}
+# Who the browser is, as the edge in front of the relay saw it. On the
+# loopback leg they are not true: this request comes from this machine, and
+# a panel with TRUST_PROXY_HEADERS on would otherwise believe them.
+NOT_FORWARDED = HOP_BY_HOP | {'x-forwarded-for', 'x-forwarded-proto', 'x-forwarded-host',
+ 'x-forwarded-port', 'x-forwarded-prefix', 'forwarded',
+ 'x-real-ip', 'cf-connecting-ip', 'true-client-ip',
+ GRANT_HEADER.lower(), PREFIX_HEADER.lower()}
+
+
+def _b64e(data: bytes) -> str:
+ return base64.b64encode(data).decode()
+
+
+def _b64d(text) -> bytes:
+ return base64.b64decode((text or '').encode())
+
+
+def loopback_headers(payload: dict) -> dict:
+ """The browser's headers as the loopback listener should see them, plus
+ the grant and the prefix the relay says the panel is mounted under."""
+ out = {k: v for k, v in (payload.get('headers') or {}).items()
+ if k.lower() not in NOT_FORWARDED}
+ if payload.get('grant'):
+ out[GRANT_HEADER] = payload['grant']
+ prefix = payload.get('prefix') or ''
+ if PREFIX.match(prefix):
+ out[PREFIX_HEADER] = prefix
+ return out
+
+
+# The browser's own WebSocket handshake. The loopback leg is a new
+# handshake with its own key and origin; sending the browser's as well makes
+# the panel refuse it with a 400.
+HANDSHAKE = {'sec-websocket-key', 'sec-websocket-version', 'sec-websocket-extensions',
+ 'sec-websocket-protocol', 'sec-websocket-accept', 'origin'}
+
+
+def _response_headers(resp, prefix: str) -> dict:
+ headers = {}
+ for k, v in resp.headers.items():
+ if k.lower() in HOP_BY_HOP:
+ continue
+ # A redirect to a root-relative path stays under the prefix.
+ if k.lower() == 'location' and prefix and v.startswith('/') and not v.startswith('//'):
+ v = prefix + v
+ headers[k] = v
+ return headers
+
+
+class Tunnel:
+ """The streams one relay connection is carrying. `send(frame)` puts a
+ frame on that connection; it is safe to call from any thread."""
+
+ def __init__(self, send, port: int):
+ self._send = send
+ self._port = port
+ self._pool = ThreadPoolExecutor(max_workers=MAX_HTTP_WORKERS,
+ thread_name_prefix='connect-http')
+ self._sio = {}
+ self._lock = threading.Lock()
+
+ # -- dispatch --------------------------------------------------------
+
+ def open(self, frame: dict) -> bool:
+ """Take an `open` frame. False when it is not a tunnel stream."""
+ kind = frame.get('k')
+ sid = frame.get('s')
+ payload = frame.get('p') or {}
+ if kind == 'http':
+ self._pool.submit(self._serve_http, sid, payload)
+ return True
+ if kind == 'sio':
+ stream = SioStream(self._send, sid, payload, self._port, self._forget)
+ with self._lock:
+ self._sio[sid] = stream
+ stream.start()
+ return True
+ return False
+
+ def data(self, frame: dict) -> bool:
+ with self._lock:
+ stream = self._sio.get(frame.get('s'))
+ if stream is None:
+ return False
+ stream.feed(_b64d(frame.get('p')))
+ return True
+
+ def close(self, frame: dict) -> bool:
+ with self._lock:
+ stream = self._sio.pop(frame.get('s'), None)
+ if stream is None:
+ return False
+ stream.stop(notify=False)
+ return True
+
+ def shutdown(self):
+ """The relay connection is gone: so is every stream on it."""
+ with self._lock:
+ streams = list(self._sio.values())
+ self._sio.clear()
+ for stream in streams:
+ stream.stop(notify=False)
+ self._pool.shutdown(wait=False, cancel_futures=True)
+
+ def _forget(self, sid):
+ with self._lock:
+ self._sio.pop(sid, None)
+
+ # -- http ------------------------------------------------------------
+
+ def _serve_http(self, sid, payload):
+ import requests
+
+ path = payload.get('path') or '/'
+ if not path.startswith('/'):
+ self._send({'s': sid, 't': 'close', 'reason': 'bad_request',
+ 'detail': 'The tunnel only carries paths on this panel.'})
+ return
+ prefix = payload.get('prefix') or ''
+ prefix = prefix if PREFIX.match(prefix) else ''
+ try:
+ resp = requests.request(
+ payload.get('method') or 'GET',
+ f'http://127.0.0.1:{self._port}{path}',
+ headers=loopback_headers(payload),
+ data=_b64d(payload.get('body_b64')) if payload.get('body_b64') else None,
+ stream=True, allow_redirects=False, timeout=HTTP_TIMEOUT_S)
+ except Exception as exc:
+ logger.warning('Connect tunnel: the panel did not answer %s: %s', path, exc)
+ self._send({'s': sid, 't': 'close', 'reason': 'panel_unreachable',
+ 'detail': 'The panel on this server did not answer on its own port.'})
+ return
+ try:
+ # Raw bytes: a gzip body stays gzip, and so does its header.
+ for chunk in resp.raw.stream(CHUNK_BYTES, decode_content=False):
+ if chunk:
+ self._send({'s': sid, 't': 'data', 'p': _b64e(chunk)})
+ self._send({'s': sid, 't': 'close',
+ 'p': {'status': resp.status_code,
+ 'headers': _response_headers(resp, prefix)}})
+ except Exception as exc:
+ logger.warning('Connect tunnel: answer for %s broke off: %s', path, exc)
+ self._send({'s': sid, 't': 'close', 'reason': 'panel_error',
+ 'detail': 'The panel stopped answering part-way through.'})
+ finally:
+ resp.close()
+
+
+class SioStream:
+ """One browser Socket.IO WebSocket, replayed on the loopback listener."""
+
+ def __init__(self, send, sid, payload, port, forget):
+ self._send = send
+ self._sid = sid
+ self._payload = payload
+ self._port = port
+ self._forget = forget
+ self._inbox = queue.Queue()
+ self._ws = None
+ self._stopped = threading.Event()
+
+ def start(self):
+ threading.Thread(target=self._run, daemon=True,
+ name=f'connect-sio-{self._sid}').start()
+
+ def feed(self, data: bytes):
+ self._inbox.put(data)
+
+ def stop(self, notify=True):
+ if self._stopped.is_set():
+ return
+ self._stopped.set()
+ self._inbox.put(None)
+ try:
+ if self._ws is not None:
+ self._ws.close()
+ except Exception:
+ pass
+ if notify:
+ self._send({'s': self._sid, 't': 'close'})
+ self._forget(self._sid)
+
+ def _run(self):
+ from websockets.sync.client import connect
+
+ path = self._payload.get('path') or '/socket.io/'
+ if not path.startswith('/socket.io/'):
+ self.stop()
+ return
+ origin = f'http://127.0.0.1:{self._port}'
+ try:
+ # Same-origin on the loopback leg, so a panel that restricts
+ # CORS origins still accepts it.
+ headers = {k: v for k, v in loopback_headers(self._payload).items()
+ if k.lower() not in HANDSHAKE}
+ self._ws = connect(f'ws://127.0.0.1:{self._port}{path}', origin=origin,
+ additional_headers=headers, open_timeout=10)
+ except Exception as exc:
+ logger.warning('Connect tunnel: Socket.IO did not open on the panel: %s', exc)
+ self.stop()
+ return
+ threading.Thread(target=self._pump_in, daemon=True,
+ name=f'connect-sio-in-{self._sid}').start()
+ try:
+ for message in self._ws:
+ if self._stopped.is_set():
+ break
+ data = message.encode() if isinstance(message, str) else message
+ self._send({'s': self._sid, 't': 'data', 'p': _b64e(data)})
+ except Exception:
+ pass
+ self.stop()
+
+ def _pump_in(self):
+ while not self._stopped.is_set():
+ data = self._inbox.get()
+ if data is None:
+ return
+ try:
+ self._ws.send(data.decode('utf-8', errors='replace'))
+ except Exception:
+ self.stop()
+ return
diff --git a/backend/tests/test_connect_tunnel.py b/backend/tests/test_connect_tunnel.py
new file mode 100644
index 00000000..7f54605e
--- /dev/null
+++ b/backend/tests/test_connect_tunnel.py
@@ -0,0 +1,294 @@
+"""ServerKit Cloud's "Open panel": the browser tunnel, panel side.
+
+The relay opens `http` and `sio` streams down the panel's connection; the
+panel replays them on its own loopback port (connect_tunnel.py), serves its
+page under the relay's path prefix, and signs in the Cloud user whose email
+matches a panel user (connect_session.py).
+"""
+
+import base64
+import json
+import threading
+import time
+import types
+from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
+
+import pytest
+
+from app.services import connect_client, connect_session, connect_tunnel
+
+DEVICE = 'dev_Tunnel1'
+PREFIX = f'/t/{DEVICE}'
+
+
+# ---------- a signer standing in for ServerKit Cloud ----------
+
+def _signer(purpose='session'):
+ from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey
+ from cryptography.hazmat.primitives.serialization import Encoding, PublicFormat
+
+ key = Ed25519PrivateKey.generate()
+ raw = key.public_key().public_bytes(Encoding.Raw, PublicFormat.Raw)
+ jwks = {'keys': [{'kty': 'OKP', 'crv': 'Ed25519', 'kid': f'k-{purpose}', 'purpose': purpose,
+ 'x': base64.urlsafe_b64encode(raw).rstrip(b'=').decode()}]}
+
+ def sign(**claims):
+ import jwt
+ body = {'sub': '7', 'email': '[email protected]', 'dev': DEVICE, 'org': 'acme',
+ 'role': 'owner', 'jti': 'g1', 'exp': int(time.time()) + 600, **claims}
+ return jwt.encode(body, key, algorithm='EdDSA', headers={'kid': f'k-{purpose}'})
+
+ return sign, jwks
+
+
+# ---------- the loopback leg ----------
+
+def test_the_loopback_request_carries_the_grant_but_not_the_edge_headers():
+ headers = connect_tunnel.loopback_headers({
+ 'headers': {'Authorization': 'Bearer panel', 'X-Forwarded-For': '203.0.113.9',
+ 'CF-Connecting-IP': '203.0.113.9', 'Host': 'relay.serverkit.ai',
+ 'X-ServerKit-Connect-Grant': 'forged-by-the-browser'},
+ 'grant': 'from-the-relay', 'prefix': PREFIX})
+ assert headers['Authorization'] == 'Bearer panel'
+ assert headers['X-ServerKit-Connect-Grant'] == 'from-the-relay'
+ assert headers['X-ServerKit-Prefix'] == PREFIX
+ lowered = {k.lower() for k in headers}
+ assert not lowered & {'x-forwarded-for', 'cf-connecting-ip', 'host'}
+
+
+def test_the_socket_io_leg_makes_its_own_handshake(monkeypatch):
+ # Forwarding the browser's Sec-WebSocket-* and Origin next to the loopback
+ # client's own made the panel answer 400 and every socket close at once.
+ seen = {}
+
+ def fake_connect(url, origin=None, additional_headers=None, open_timeout=None):
+ seen.update(url=url, origin=origin, headers=additional_headers)
+ raise OSError('stop here')
+
+ import websockets.sync.client
+ monkeypatch.setattr(websockets.sync.client, 'connect', fake_connect)
+ sent = []
+ stream = connect_tunnel.SioStream(sent.append, 's1', {
+ 'path': '/socket.io/?EIO=4&transport=websocket', 'grant': 'g',
+ 'headers': {'Sec-WebSocket-Key': 'abc', 'Sec-WebSocket-Version': '13',
+ 'Sec-WebSocket-Extensions': 'permessage-deflate',
+ 'Origin': 'https://relay.serverkit.ai', 'User-Agent': 'Chrome'}},
+ 5000, lambda sid: None)
+ stream._run()
+ lowered = {k.lower() for k in seen['headers']}
+ assert not lowered & connect_tunnel.HANDSHAKE
+ assert seen['headers']['User-Agent'] == 'Chrome'
+ assert seen['headers']['X-ServerKit-Connect-Grant'] == 'g'
+ assert seen['origin'] == 'http://127.0.0.1:5000'
+ assert sent[-1] == {'s': 's1', 't': 'close'}
+
+
+def test_a_prefix_that_is_not_a_device_path_is_dropped():
+ headers = connect_tunnel.loopback_headers({'headers': {}, 'prefix': '/evil'})
+ assert 'X-ServerKit-Prefix' not in headers
+
+
+class _Panel(BaseHTTPRequestHandler):
+ seen = []
+
+ def do_GET(self):
+ _Panel.seen.append((self.path, dict(self.headers)))
+ if self.path == '/old':
+ self.send_response(302)
+ self.send_header('Location', '/new')
+ self.end_headers()
+ return
+ body = b'x' * (connect_tunnel.CHUNK_BYTES + 10)
+ self.send_response(200)
+ self.send_header('Content-Type', 'text/plain')
+ self.send_header('Content-Length', str(len(body)))
+ self.end_headers()
+ self.wfile.write(body)
+
+ def log_message(self, *args):
+ pass
+
+
+def local_panel():
+ server = ThreadingHTTPServer(('127.0.0.1', 0), _Panel)
+ threading.Thread(target=server.serve_forever, daemon=True).start()
+ _Panel.seen = []
+ yield server.server_address[1]
+ server.shutdown()
+
+
+def _run_http(port, payload):
+ frames = []
+ done = threading.Event()
+
+ def send(frame):
+ frames.append(frame)
+ if frame['t'] == 'close':
+ done.set()
+ return True
+
+ tunnel = connect_tunnel.Tunnel(send, port)
+ assert tunnel.open({'s': 's1', 't': 'open', 'k': 'http', 'p': payload})
+ assert done.wait(10)
+ tunnel.shutdown()
+ return frames
+
+
+def test_an_http_stream_is_replayed_on_the_panel_port_and_streamed_back(local_panel):
+ frames = _run_http(local_panel, {'method': 'GET', 'path': '/assets/app.js',
+ 'headers': {}, 'grant': 'g', 'prefix': PREFIX})
+ data = b''.join(base64.b64decode(f['p']) for f in frames if f['t'] == 'data')
+ close = frames[-1]
+ assert close['p']['status'] == 200
+ assert close['p']['headers']['Content-Type'] == 'text/plain'
+ assert len(data) == connect_tunnel.CHUNK_BYTES + 10
+ # More than one frame: a big answer is chunked under the relay's cap.
+ assert sum(1 for f in frames if f['t'] == 'data') >= 2
+ path, headers = _Panel.seen[0]
+ assert path == '/assets/app.js'
+ assert headers['X-ServerKit-Connect-Grant'] == 'g'
+
+
+def test_a_redirect_stays_under_the_prefix(local_panel):
+ frames = _run_http(local_panel, {'method': 'GET', 'path': '/old', 'headers': {},
+ 'prefix': PREFIX})
+ assert frames[-1]['p']['status'] == 302
+ assert frames[-1]['p']['headers']['Location'] == f'{PREFIX}/new'
+
+
+def test_a_panel_that_does_not_answer_is_a_refusal_not_a_blank_page():
+ frames = _run_http(1, {'method': 'GET', 'path': '/', 'headers': {}})
+ assert frames[-1]['reason'] == 'panel_unreachable'
+
+
+def test_the_client_hands_tunnel_streams_to_the_tunnel(monkeypatch):
+ client = connect_client.RelayClient()
+ opened = []
+ client._tunnel = types.SimpleNamespace(open=lambda f: opened.append(f) or True,
+ data=lambda f: True, close=lambda f: False)
+ sent = []
+ ws = types.SimpleNamespace(send=sent.append)
+ client._handle_frame(ws, json.dumps({'s': 's9', 't': 'open', 'k': 'http', 'p': {}}))
+ assert opened and not sent # no "unsupported" refusal any more
+
+
+def test_without_a_live_tunnel_an_http_stream_is_still_refused_honestly():
+ client = connect_client.RelayClient()
+ sent = []
+ client._handle_frame(types.SimpleNamespace(send=sent.append),
+ json.dumps({'s': 's9', 't': 'open', 'k': 'http', 'p': {}}))
+ assert json.loads(sent[0])['reason'] == 'unsupported'
+
+
+# ---------- the grant ----------
+
+def test_a_valid_grant_verifies():
+ sign, jwks = _signer()
+ claims = connect_session.verify_grant(sign(), DEVICE, jwks)
+ assert claims['email'] == '[email protected]'
+
+
[email protected]('mutate, code', [
+ (lambda sign: sign(dev='dev_Other'), 'wrong_device'),
+ (lambda sign: sign(exp=int(time.time()) - 5), 'expired'),
+ (lambda sign: sign(email=None), 'no_email'),
+])
+def test_a_grant_that_does_not_hold_is_refused(mutate, code):
+ sign, jwks = _signer()
+ with pytest.raises(connect_session.ConnectSessionRefused) as exc:
+ connect_session.verify_grant(mutate(sign), DEVICE, jwks)
+ assert exc.value.code == code
+
+
+def test_a_command_key_cannot_sign_somebody_in():
+ sign, jwks = _signer(purpose='command')
+ with pytest.raises(connect_session.ConnectSessionRefused) as exc:
+ connect_session.verify_grant(sign(), DEVICE, jwks)
+ assert exc.value.code == 'unknown_key'
+
+
+# ---------- signing in ----------
+
+def paired(monkeypatch):
+ sign, jwks = _signer()
+ monkeypatch.setattr(connect_client, '_read_connect_file',
+ lambda: {'device_id': DEVICE, 'cloud_url': 'https://cloud.test'})
+ monkeypatch.setattr(connect_session, '_jwks', lambda url, refresh=False: jwks)
+ return sign
+
+
+def _owner(app, email='[email protected]', totp=False):
+ from app import db
+ from app.models import User
+ from werkzeug.security import generate_password_hash
+ with app.app_context():
+ user = User(email=email, username=email.split('@')[0],
+ password_hash=generate_password_hash('pw'), role=User.ROLE_ADMIN,
+ is_active=True)
+ user.totp_enabled = totp
+ db.session.add(user)
+ db.session.commit()
+
+
+def test_the_cloud_user_with_a_matching_email_is_signed_in(app, client, paired):
+ _owner(app)
+ res = client.post('/api/v1/auth/connect-session',
+ headers={'X-ServerKit-Connect-Grant': paired()})
+ assert res.status_code == 200, res.get_json()
+ body = res.get_json()
+ assert body['access_token'] and body['user']['email'] == '[email protected]'
+
+
+def test_nobody_with_that_email_gets_the_normal_login(app, client, paired):
+ res = client.post('/api/v1/auth/connect-session',
+ headers={'X-ServerKit-Connect-Grant': paired(email='[email protected]')})
+ assert res.status_code == 401
+ assert res.get_json()['code'] == 'auth.connect_no_user'
+
+
+def test_a_grant_from_off_the_machine_is_not_accepted(app, client, paired):
+ _owner(app)
+ res = client.post('/api/v1/auth/connect-session',
+ headers={'X-ServerKit-Connect-Grant': paired()},
+ environ_base={'REMOTE_ADDR': '203.0.113.9'})
+ assert res.status_code == 401
+ assert res.get_json()['code'] == 'auth.connect_not_tunnel'
+
+
+def test_the_panels_own_second_factor_still_applies(app, client, paired):
+ _owner(app, totp=True)
+ res = client.post('/api/v1/auth/connect-session',
+ headers={'X-ServerKit-Connect-Grant': paired()})
+ assert res.status_code == 401
+ assert res.get_json()['code'] == 'auth.connect_2fa'
+
+
+# ---------- the page under the prefix ----------
+
+def test_the_page_moves_under_the_prefix(tmp_path):
+ (tmp_path / 'index.html').write_text(
+ '<html><head><link rel="icon" href="/favicon.svg">'
+ '<script type="importmap">{"imports":{"react":"/serverkit-vendor/react.mjs"}}</script>'
+ '<script type="module" src="/assets/index.js"></script>'
+ '<link href="//fonts.example/x.css"></head></html>', encoding='utf-8')
+ res = connect_session.index_under_prefix(str(tmp_path), PREFIX)
+ page = res.get_data(as_text=True)
+ assert f'href="{PREFIX}/favicon.svg"' in page
+ assert f'src="{PREFIX}/assets/index.js"' in page
+ assert f'"{PREFIX}/serverkit-vendor/react.mjs"' in page
+ assert 'href="//fonts.example/x.css"' in page
+ assert f'window.__SERVERKIT_BASE__="{PREFIX}"' in page
+ assert res.headers['Cache-Control'] == 'no-store'
+
+
+def test_the_prefix_header_counts_only_from_the_loopback(app):
+ with app.test_request_context('/', headers={'X-ServerKit-Prefix': PREFIX},
+ environ_base={'REMOTE_ADDR': '127.0.0.1'}):
+ from flask import request
+ assert connect_session.tunnel_prefix(request) == PREFIX
+ with app.test_request_context('/', headers={'X-ServerKit-Prefix': PREFIX},
+ environ_base={'REMOTE_ADDR': '203.0.113.9'}):
+ from flask import request
+ assert connect_session.tunnel_prefix(request) == ''
diff --git a/docs/API_SURFACE.md b/docs/API_SURFACE.md
index f081db10..71c078cd 100644
--- a/docs/API_SURFACE.md
+++ b/docs/API_SURFACE.md
@@ -809,6 +809,7 @@ Regenerate (backend/):
- `POST /auth/2fa/setup/confirm`
- `POST /auth/2fa/verify`
- `POST /auth/complete-onboarding`
+- `POST /auth/connect-session`
- `POST /auth/login`
- `POST /auth/login-links`
- `POST /auth/login-links/redeem`
diff --git a/frontend/src/App.jsx b/frontend/src/App.jsx
index 2c7d3672..6fd24da3 100644
--- a/frontend/src/App.jsx
+++ b/frontend/src/App.jsx
@@ -10,6 +10,7 @@ import { ResourceTierProvider } from './contexts/ResourceTierContext';
import { NotificationsProvider } from './contexts/NotificationsContext';
import { WorkspaceProvider } from './contexts/WorkspaceContext';
import { rememberRedirect } from './utils/redirectAfterLogin';
+import { TUNNEL_BASE } from './services/tunnelBase.js';
import { Toaster } from './components/ui/sonner';
import ThemeSync from './components/ThemeSync';
import LocaleSync from './components/LocaleSync';
@@ -247,7 +248,7 @@ function AppRoutes() {
function App() {
return (
- <Router>
+ <Router basename={TUNNEL_BASE || undefined}>
{/* Outermost: a toast raised while the theme or workspace is still
initialising must already be translatable (plan 79 B1). */}
<LocaleProvider>
diff --git a/frontend/src/contexts/AuthContext.jsx b/frontend/src/contexts/AuthContext.jsx
index 8a7c568d..62f34669 100644
--- a/frontend/src/contexts/AuthContext.jsx
+++ b/frontend/src/contexts/AuthContext.jsx
@@ -1,5 +1,6 @@
import { useCallback, useState, useEffect } from 'react';
import api from '../services/api';
+import { inTunnel, storageKey } from '../services/tunnelBase.js';
import { presetForUseCases } from '../components/sidebarItems';
import { AuthContext } from './useAuth.js';
@@ -29,7 +30,18 @@ export function AuthProvider({ children }) {
});
const checkAuth = useCallback(async () => {
- const token = localStorage.getItem('access_token');
+ let token = localStorage.getItem(storageKey('access_token'));
+ if (!token && inTunnel) {
+ // Opened from ServerKit Cloud: the relay brought a grant that says
+ // who is asking. If this panel has a user with that email, sign
+ // them in; otherwise the normal login page shows.
+ try {
+ const data = await api.connectSession();
+ if (data?.access_token) token = data.access_token;
+ } catch {
+ // No matching user, or a grant this panel does not accept.
+ }
+ }
if (token) {
try {
const data = await api.getCurrentUser();
diff --git a/frontend/src/services/api/auth.js b/frontend/src/services/api/auth.js
index 7084f088..68ae0cb5 100644
--- a/frontend/src/services/api/auth.js
+++ b/frontend/src/services/api/auth.js
@@ -89,6 +89,16 @@ export async function redeemLoginLink(token) {
return data;
}
+// Opened from ServerKit Cloud through its relay: the relay hands the panel
+// Cloud's signed grant, and the panel signs in the user with that email.
+export async function connectSession() {
+ const data = await this.request('/auth/connect-session', { method: 'POST' });
+ if (data.access_token) {
+ this.setTokens(data.access_token, data.refresh_token);
+ }
+ return data;
+}
+
// Demo mode
export async function getDemoInfo() {
return this.request('/auth/demo-info');
diff --git a/frontend/src/services/api/client.js b/frontend/src/services/api/client.js
index ac233f1f..13584224 100644
--- a/frontend/src/services/api/client.js
+++ b/frontend/src/services/api/client.js
@@ -1,6 +1,7 @@
// Base HTTP client - constructor, token management, core request methods
import { workspaceStore } from '../workspaceStore.js';
import { translateServerError } from './errorCodes.js';
+import { TUNNEL_BASE, storageKey } from '../tunnelBase.js';
const AUTH_EXPIRED_EVENT = 'serverkit:auth-expired';
@@ -32,9 +33,14 @@ const normalizeApiBaseUrl = (url) => {
// on window.location.origin in dev (see services/socket.js) because a WebSocket
// upgrades out of the HTTP connection pool anyway.
const viteEnv = import.meta.env || {};
-const API_BASE_URL = (viteEnv.DEV && viteEnv.VITE_API_PROXY === 'true')
+const configuredBase = (viteEnv.DEV && viteEnv.VITE_API_PROXY === 'true')
? '/api/v1'
: normalizeApiBaseUrl(viteEnv.VITE_API_URL);
+// Opened through ServerKit Cloud's relay, a root-relative API path has to
+// carry the panel's prefix (services/tunnelBase.js).
+const API_BASE_URL = (TUNNEL_BASE && configuredBase.startsWith('/'))
+ ? `${TUNNEL_BASE}${configuredBase}`
+ : configuredBase;
// Requests that are safe to share with a concurrent identical caller: a plain
// GET with no body, no custom headers (X-DB-Password and friends change what
@@ -83,17 +89,17 @@ class ApiClient {
}
getToken() {
- return localStorage.getItem('access_token');
+ return localStorage.getItem(storageKey('access_token'));
}
setTokens(accessToken, refreshToken) {
- localStorage.setItem('access_token', accessToken);
- localStorage.setItem('refresh_token', refreshToken);
+ localStorage.setItem(storageKey('access_token'), accessToken);
+ localStorage.setItem(storageKey('refresh_token'), refreshToken);
}
clearTokens() {
- localStorage.removeItem('access_token');
- localStorage.removeItem('refresh_token');
+ localStorage.removeItem(storageKey('access_token'));
+ localStorage.removeItem(storageKey('refresh_token'));
this.workspace.clearActiveWorkspace(); // drop workspace context on logout
}
@@ -217,7 +223,7 @@ class ApiClient {
}
async refreshToken() {
- const refreshToken = localStorage.getItem('refresh_token');
+ const refreshToken = localStorage.getItem(storageKey('refresh_token'));
if (!refreshToken) return false;
try {
@@ -231,7 +237,7 @@ class ApiClient {
if (response.ok) {
const data = await response.json();
- localStorage.setItem('access_token', data.access_token);
+ localStorage.setItem(storageKey('access_token'), data.access_token);
return true;
}
return false;
diff --git a/frontend/src/services/socket.js b/frontend/src/services/socket.js
index bf26fd6b..3d0afacb 100644
--- a/frontend/src/services/socket.js
+++ b/frontend/src/services/socket.js
@@ -1,5 +1,6 @@
import { io } from 'socket.io-client';
import { SOCKET_EVENTS } from '../constants/events';
+import { TUNNEL_BASE, storageKey } from './tunnelBase.js';
const getSocketUrl = () => {
if (import.meta.env.DEV) return window.location.origin;
@@ -15,7 +16,7 @@ class SocketService {
}
connect() {
- const token = localStorage.getItem('access_token');
+ const token = localStorage.getItem(storageKey('access_token'));
if (!token) {
console.warn('No token available for WebSocket connection');
return;
@@ -27,6 +28,9 @@ class SocketService {
this.socket = io(SOCKET_URL, {
auth: { token },
+ // Through ServerKit Cloud's relay the panel lives under a prefix,
+ // and so does its Socket.IO endpoint.
+ ...(TUNNEL_BASE ? { path: `${TUNNEL_BASE}/socket.io` } : {}),
transports: ['websocket', 'polling'],
reconnection: true,
reconnectionAttempts: 5,
diff --git a/frontend/src/services/tunnelBase.js b/frontend/src/services/tunnelBase.js
new file mode 100644
index 00000000..01547ec3
--- /dev/null
+++ b/frontend/src/services/tunnelBase.js
@@ -0,0 +1,29 @@
+// Where this panel is mounted.
+//
+// Normally at the root of its own host. When ServerKit Cloud opens it
+// through the relay, it lives under a path instead —
+// https://relay.serverkit.ai/t/dev_ABC123/ — and every absolute URL the SPA
+// builds (router, API, Socket.IO) has to carry that prefix, or it lands on
+// the relay's root where no server answers.
+//
+// The panel's own server says which prefix it was reached through by
+// setting `window.__SERVERKIT_BASE__` in the page it serves; the path itself
+// is the fallback.
+const PREFIX = /^\/t\/dev_[A-Za-z0-9_-]+/;
+
+function detect() {
+ if (typeof window === 'undefined') return '';
+ const injected = window.__SERVERKIT_BASE__;
+ if (typeof injected === 'string' && PREFIX.test(injected)) return injected.replace(/\/+$/, '');
+ const match = window.location.pathname.match(PREFIX);
+ return match ? match[0] : '';
+}
+
+export const TUNNEL_BASE = detect();
+
+export const inTunnel = TUNNEL_BASE !== '';
+
+// Every server opened through the relay shares the relay's origin, and with
+// it localStorage. Keys are namespaced by prefix so two panels open in one
+// browser do not overwrite each other's sign-in.
+export const storageKey = (name) => (TUNNEL_BASE ? `${name}@${TUNNEL_BASE}` : name);