Files
JesseMarkowitz 8c65ae99de M2: cut the hosted product away from the local one
94 files, +1,395 -6,578. Three files are new; twenty-four are gone. The
milestone is subtraction, and what is left is the single-user local
storyteller the specification describes.

Removed in full: campaign scripting and its QuickJS sandbox; multi-user
accounts, guest sessions, login, registration and the shared demo key;
the visitor-analytics tables, dashboard and page beacon; the access log
of sign-ins, addresses and devices; per-IP and per-user rate limiting
and quotas; Render deployment config; Postgres and psycopg; cloud
inference providers, the API-key field and the key encryption that
existed to store it; session-cookie signing. None of it was hidden
behind a flag — the routes are gone and answer 404.

Two things were kept that the brief allowed keeping. The `users` table
and its foreign keys stay as an internal ownership detail, because
rewriting them out means a migration across most of the schema to
delete a column that costs nothing; nothing creates a second user and
no request carries an identity. Five inert tables and four inert
columns stay for the same reason, so an M1 campaign database opens
unchanged.

The one addition is app/endpoints.py, which decides where a story may
be sent. Loopback, RFC1918, link-local, unique-local and CGNAT — an
explicit allowlist of networks, not a guess at what `ipaddress` means
by "private", which calls the documentation ranges private and IPv6
loopback reserved. Every address a hostname resolves to must be in it,
so a split answer does not squeak through, and the rule runs both when
the endpoint is saved and before every outbound request, because a name
that resolved to the LAN this morning can resolve elsewhere this
afternoon. Known cloud hosts are named in the refusal so the error says
why rather than looking like broken DNS. TLS is never traded against
it: M1's shared trust context is intact on all four clients and there
is no way to skip verification.

The hardcoded 120-second model timeout is now a setting. That was not
theoretical — on this GPU-less four-core host a cold load of
qwen2.5:3b-instruct took 648.9 seconds to produce the first turn, while
turns 2 to 5 of the same campaign took 3.6 to 13.1. Connect stays short
at 10s so a wrong address still fails fast; the read timeout defaults
to 300s and is bounded at 3600, because "wait longer" must stay a
number.

Two defects found while testing and fixed here. An unknown /api path
fell through the SPA catch-all and came back as HTML with status 200,
so a client asking for JSON parsed a web page instead of learning the
route was gone. And AIDND_CORS_ORIGINS accepted "*", which on an
unauthenticated loopback API would hand every page on the Internet a
write handle on the campaign database; it now refuses to start.

Verified rather than assumed. Offline, on a network with no route out
and no DNS: five turns, retry with both takes retained, restart with an
identical transcript digest, a failed model call leaving the accepted
AI-turn count untouched, and a capture with zero non-loopback unicast
packets. Against a real second machine on the LAN over HTTPS with a
private CA: four turns, restart, and a capture showing 289 packets to
the approved host, 344 loopback, zero anywhere else, zero DNS queries.
Cloud and public endpoints refused with their reasons; no API key
settable; every removed route 404.

604 backend tests pass, down from 648 by the fifteen retired with the
subsystems they tested and up by the twenty-nine added for the endpoint
policy and the removed surface. The scripting tests were not deleted:
eight files used a JavaScript counter as instrumentation for the state
snapshot and rollback machinery, which M2 does not touch, so the
counter moved to the world-state engine and those tests still assert
what they always did. Frontend lint and build are clean; the image
builds, and its wheel-building stage is gone with quickjs.

No M3 work. Undo is still destructive and there is still no Redo.
2026-09-02 11:27:14 -04:00

180 lines
6.8 KiB
Python

"""Which inference endpoints this product is willing to talk to.
The Adventure Storyteller sends the player's prose, the assembled context, the
retrieved memories, and the embedding inputs to whatever address the model
endpoint names. That makes the endpoint the single most consequential setting
in the application: point it somewhere else and the whole campaign goes there.
The v1 rule (`planning/DECISIONS/002-ollama-only-v1.md`, ADR 004) is that
inference runs on user-controlled local infrastructure. Two deployments are
supported and no third is:
* **same-host** — Ollama on loopback, the default;
* **explicitly configured trusted LAN** — Ollama on another machine the user
controls, named by them, reached over HTTP or over HTTPS with a certificate
their machine trusts.
Everything on the public Internet is refused. Not discouraged in the UI, not
absent from a dropdown — refused, here, on the way out, so that a hand-edited
database row or a hostname that starts resolving somewhere new cannot quietly
turn a local install into an exfiltration path.
## How the line is drawn
By **address**, not by name, and against an explicit allowlist of networks:
loopback, the three RFC1918 ranges, link-local, IPv6 unique-local, and
carrier-grade NAT — the last of which is what a mesh VPN such as Tailscale
hands out and is as user-controlled as a LAN.
Every address the host resolves to must be in one of them. One address outside
is enough to refuse the endpoint, so a name resolving to both a private and a
public address does not squeak through.
The networks are spelled out rather than inferred from `ipaddress`'s own
classifications, which do not mean what this rule needs: `is_private` is true
of the documentation ranges and of `0.0.0.0/8`, and `is_reserved` is true of
IPv6 loopback — so a rule written around it refuses `http://[::1]:11434/v1`,
which is an ordinary same-host Ollama. Naming the networks keeps the policy
readable and makes anything unnamed refused by default.
Checking addresses rather than hostnames is what makes the rule hard to talk
around. A cloud provider cannot be reached by spelling its name differently,
and `localhost.` or a DNS entry pointing at a public host is judged on where it
actually goes.
## What this is not
It is not a general network-policy framework, and there is nothing to configure.
There is one predicate, and it is applied in two places: when the endpoint is
saved, so the user gets a clear error immediately, and again before every
outbound request, because a name that resolved to `192.168.1.50` this morning
can resolve to something else this afternoon.
TLS is a separate matter and is never traded against this one. See
`tlstrust.py`: certificates are verified in full, and no endpoint — however
private its address — may skip that.
"""
import ipaddress
import socket
from urllib.parse import urlparse
#: The networks an inference endpoint may live on. Anything else is refused.
ALLOWED_NETWORKS = tuple(
ipaddress.ip_network(cidr)
for cidr in (
"127.0.0.0/8", # this machine
"10.0.0.0/8", # RFC1918
"172.16.0.0/12", # RFC1918
"192.168.0.0/16", # RFC1918
"169.254.0.0/16", # link-local
"100.64.0.0/10", # carrier-grade NAT, which mesh VPNs use
"::1/128", # this machine, v6
"fc00::/7", # unique-local, v6
"fe80::/10", # link-local, v6
)
)
def _is_local(ip) -> bool:
return any(ip in net for net in ALLOWED_NETWORKS)
#: Hosts that are only ever a cloud inference service. The address rule below
#: already refuses every one of them, because they all resolve to public
#: addresses; this list exists solely so the error says *why* rather than
#: leaving the user to wonder whether their DNS is broken.
CLOUD_HOSTS = (
"openrouter.ai",
"api.openai.com",
"api.anthropic.com",
"api.groq.com",
"api.mistral.ai",
"api.together.xyz",
"api.deepseek.com",
"generativelanguage.googleapis.com",
"api.cohere.ai",
"api.perplexity.ai",
)
_CLOUD_REASON = (
"this build talks to Ollama on your own machine or on your own network, "
"and has no cloud provider support"
)
def _cloud_host(host: str) -> bool:
host = host.lower().rstrip(".")
return any(host == h or host.endswith("." + h) for h in CLOUD_HOSTS)
def rejection_reason(url: str) -> str | None:
"""Why this endpoint may not be used, or None if it may.
The string is shown to the user, so it says what to do rather than what
went wrong internally.
"""
parsed = urlparse((url or "").strip())
if parsed.scheme not in ("http", "https"):
return "the endpoint URL must start with http:// or https://"
host = parsed.hostname
if not host:
return "the endpoint URL has no host"
if _cloud_host(host):
return f"{host} is a cloud inference service — {_CLOUD_REASON}"
port = parsed.port or (443 if parsed.scheme == "https" else 80)
try:
infos = socket.getaddrinfo(host, port, type=socket.SOCK_STREAM)
except socket.gaierror:
return (
f"the host {host!r} could not be resolved — check the address, and "
"that the machine running Ollama is reachable from here"
)
for info in infos:
try:
ip = ipaddress.ip_address(info[4][0])
except ValueError:
return "the endpoint host resolved to an address that could not be read"
if _is_local(ip):
continue
if ip.is_global:
return (
f"{host} resolves to {ip}, which is a public Internet address — "
f"{_CLOUD_REASON}. Use Ollama on this machine "
"(http://127.0.0.1:11434/v1) or on a machine on your own network"
)
return (
f"{host} resolves to {ip}, which is not on this machine and not on "
"your own network. Use http://127.0.0.1:11434/v1, or the address of "
"a machine on your network"
)
return None
def check(url: str) -> None:
"""Raises `EndpointRejected` if this endpoint is outside the policy."""
reason = rejection_reason(url)
if reason is not None:
raise EndpointRejected(reason)
class EndpointRejected(Exception):
"""The configured endpoint is not one this product will send a story to."""
def is_loopback(url: str) -> bool:
"""Whether this endpoint is on this machine. Used for reporting, not for
gating: a trusted-LAN endpoint is equally allowed."""
host = urlparse((url or "").strip()).hostname
if not host:
return False
try:
infos = socket.getaddrinfo(host, None, type=socket.SOCK_STREAM)
except socket.gaierror:
return False
try:
return all(ipaddress.ip_address(i[4][0]).is_loopback for i in infos)
except ValueError:
return False