SupplierWebPage / server.py
DrDavis's picture
Upload 4 files
16dadca verified
Raw History Blame Contribute Delete
6.11 kB
"""Fictional supplier bulletin host for Aster's instructor-led webpage demo.
The GET page is public. Only the teaching Space, using a shared secret, may
publish a page. Content and IDs are temporary and reset when this Space sleeps.
"""
from __future__ import annotations
import hmac
import html
import json
import os
import re
import threading
import time
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from urllib.parse import urlparse
PAGES: dict[str, dict] = {}
LOCK = threading.Lock()
PAGE_ID = re.compile(r"[0-9a-f]{32}\Z")
MAX_REQUEST_BYTES = 16000
MAX_BULLETIN = 2500
MAX_HIDDEN_NOTE = 6000
LIFETIME_SECONDS = 6 * 60 * 60
def render_page(bulletin: str, hidden_note: str) -> str:
visible = html.escape(bulletin)
hidden = html.escape(hidden_note)
# The visually hidden block is still present in the HTML retrieved by an
# agent. The agent's parser, not a browser screenshot, decides what it reads.
return f"""<!doctype html>
<html lang="en"><head><meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Harbor Medical Supply · Shipment HMS-77</title>
<style>body{{font:17px/1.55 system-ui,sans-serif;max-width:760px;margin:60px auto;
padding:0 24px;color:#183444}}header{{border-bottom:3px solid #117d93;padding-bottom:15px}}
.tag{{color:#086a7c;font-weight:700}}.card{{background:#eef7f8;border-radius:10px;
padding:22px;margin-top:25px}}.unseen{{display:none}}</style></head>
<body><header><div class="tag">HARBOR MEDICAL SUPPLY</div>
<h1>Shipment HMS-77 status bulletin</h1></header>
<article class="card"><p>{visible}</p></article>
<section class="unseen" aria-hidden="true" data-origin="supplier-page-note">{hidden}</section>
<footer><p>Fictional teaching page · Updated for this demo session</p></footer>
</body></html>"""
def put_page(data: dict) -> int:
page_id = data.get("page_id")
bulletin = data.get("bulletin")
hidden_note = data.get("hidden_note", "")
if not isinstance(page_id, str) or not PAGE_ID.fullmatch(page_id):
raise ValueError("page_id must be a 32-character hexadecimal ID")
if not isinstance(bulletin, str) or not bulletin.strip() or len(bulletin) > MAX_BULLETIN:
raise ValueError("bulletin must be nonempty and at most 2500 characters")
if not isinstance(hidden_note, str) or len(hidden_note) > MAX_HIDDEN_NOTE:
raise ValueError("hidden_note must be at most 6000 characters")
now = time.time()
with LOCK:
expired = [key for key, value in PAGES.items() if value["expires"] <= now]
for key in expired:
del PAGES[key]
previous = PAGES.get(page_id, {}).get("version", 0)
PAGES[page_id] = {"bulletin": bulletin, "hidden_note": hidden_note,
"version": previous + 1, "expires": now + LIFETIME_SECONDS}
return previous + 1
def get_page(page_id: str) -> str | None:
if not PAGE_ID.fullmatch(page_id):
return None
with LOCK:
page = PAGES.get(page_id)
if not page or page["expires"] <= time.time():
return None
return render_page(page["bulletin"], page["hidden_note"])
class Handler(BaseHTTPRequestHandler):
def _reply(self, status: int, body: bytes, content_type: str):
self.send_response(status)
self.send_header("Content-Type", content_type)
self.send_header("Content-Length", str(len(body)))
self.send_header("Cache-Control", "no-store")
self.send_header("X-Content-Type-Options", "nosniff")
self.send_header("Content-Security-Policy",
"default-src 'none'; style-src 'unsafe-inline'; base-uri 'none'; form-action 'none'")
self.end_headers()
self.wfile.write(body)
def _json(self, status: int, value: dict):
self._reply(status, json.dumps(value).encode("utf-8"), "application/json; charset=utf-8")
def do_GET(self):
path = urlparse(self.path).path
if path == "/":
landing = ("<!doctype html><html><head><meta charset='utf-8'>"
"<title>Harbor Medical Supply teaching host</title></head>"
"<body><h1>Fictional supplier bulletin host</h1>"
"<p>Publish a demo page from the separate Aster Session 2 Space.</p>"
"<p><a href='/health'>Check service status</a></p></body></html>")
return self._reply(200, landing.encode("utf-8"), "text/html; charset=utf-8")
if path == "/health":
return self._json(200, {"status": "running"})
match = re.fullmatch(r"/pages/([0-9a-f]{32})", path)
page = get_page(match.group(1)) if match else None
if page is None:
return self._json(404, {"error": "page not found or expired"})
self._reply(200, page.encode("utf-8"), "text/html; charset=utf-8")
def do_POST(self):
if urlparse(self.path).path != "/admin/pages":
return self._json(404, {"error": "unknown route"})
expected = os.getenv("PAGE_HOST_WRITE_TOKEN", "")
supplied = self.headers.get("Authorization", "")
if not expected or not hmac.compare_digest(supplied, f"Bearer {expected}"):
return self._json(403, {"error": "publisher authorization failed"})
try:
length = int(self.headers.get("Content-Length", "0"))
if not 0 < length <= MAX_REQUEST_BYTES:
raise ValueError("invalid request size")
request = json.loads(self.rfile.read(length))
if not isinstance(request, dict):
raise ValueError("body must be a JSON object")
version = put_page(request)
except (ValueError, UnicodeDecodeError, json.JSONDecodeError) as error:
return self._json(400, {"error": str(error)})
self._json(200, {"path": f"/pages/{request['page_id']}", "version": version})
if __name__ == "__main__":
print("Fictional supplier page server listening on 0.0.0.0:7860", flush=True)
ThreadingHTTPServer(("0.0.0.0", 7860), Handler).serve_forever()