Kaynağa Gözat

feat: same-origin opt-in, certificate reconciliation, settings layout SV-132

THE HOSTNAME INPUT WAS UNUSABLE, AND THE CAUSE WAS A LATENT BUG IN 11 PLACES.
`inputCls` begins with `w-full`, and Tailwind resolves conflicting width
utilities by STYLESHEET order, not by the order they appear in a className
string - so `${inputCls} w-36` left `w-full` winning, the select took the whole
row, and the hostname input beside it collapsed to nothing. Split into
`controlCls` (no width) and `inputCls` (= `w-full ${controlCls}`), the row made
an explicit grid, and every other call site composing a width converted. A
repo-wide grep for the pattern is now clean.

SAME-ORIGIN OPT-IN, reported from a live deployment. Browsers send no `Origin`
on a same-origin GET, so an app served from a project hostname calling its own
project's API with an origin-pinned key was refused 403 - a real defect of
static serving and origin pinning together.

The tempting fix is to accept `Sec-Fetch-Site: same-origin` globally, and it is
wrong. In a browser that header is trustworthy (a forbidden header name, page
script cannot set it); a non-browser client sets it with one curl flag. Today
an absent Origin being refused is what makes an origin-pinned key unusable
outside a browser AT ALL, and a publishable key is extractable from the page by
construction. So `allow_same_origin_host` is per key and OFF by default, and
requires all four of: the opt-in, genuinely no Origin, the browser's
same-origin claim, and a Host the key ALREADY lists. Falsified twice - making
it global reddens "the default changed, every origin-pinned key just got
wider", and dropping the host check reddens "a host the key never listed was
accepted".

The membership test is a free function beside the gate, NOT a method on
KeyScope, and the linker enforced it: apikey.cpp is compiled standalone by
narrow test targets that do not link hostnames.cpp. That is the same trap
already recorded beside `ip_allow`, repeated by me and caught in minutes.

CERTIFICATES ARE RECONCILED, which is the answer to "I added a host, how do I
get a certificate". `packaging/tls/reconcile-certs.sh` reads every registered
hostname and issues for any without one. Still no ACME in our process: an ACME
bug here is a live outage on every hostname at once, renewal scheduling is
somebody else's tested code, and an account key is a credential we need not
hold. What was missing was never the protocol - it was nobody connecting "a
hostname was registered" to "ask for a certificate".

AND THE WATCHED DIRECTORY WAS NOT WATCHED. The design promised it; the first
implementation loaded once at boot. Found because a newly ISSUED certificate
did not take effect - the same gap renewal would have hit in 60 days, but loud
rather than silent, because the host refused every handshake instead of serving
a stale-but-valid certificate. Now polled, with the first observation skipped
so a start does not log a reload that changed nothing.

SETTINGS is a two-level layout with a vertical section list, so tab wrapping is
impossible by construction, and GLOBAL is separated from PROJECT with the scope
and the affected project named in both the nav and the panel. `?tab=` makes a
settings view linkable, which it never was.

31 em/en dashes removed from webui and 17 from src/tests, against the project's
ASCII-hyphen rule. The sweep also rewrote a VENDORED minified bundle
(api/docs/rapidoc-min.js) - caught by checking git diff before moving on, and
reverted. A text sweep must never run over vendored minified code.

1524/1524 serial; webui npm run build clean.
fszontagh 6 gün önce
ebeveyn
işleme
c37e8ff3fb

+ 1 - 1
VERSION

@@ -1 +1 @@
-0.20.0
+0.21.0

+ 52 - 0
api/llms.txt

@@ -35,6 +35,58 @@ name-mismatch error on an unrelated tenant's hostname.
 If TLS is configured and cannot be set up, the server REFUSES TO START rather
 than serving plain HTTP on a port callers reach over https.
 
+## A same-origin app calling its own project's API
+
+**Browsers send no `Origin` on a same-origin GET** (the Fetch spec adds it only
+for non-GET/HEAD). So an app SERVED FROM a project hostname, calling that
+project's own API with a key that has an origins allow-list, arrives with no
+Origin and is refused 403 - because an absent Origin is refused whenever a list
+is set.
+
+The opt-in, per key:
+
+    "scope": { "origins": ["https://app.example.com"],
+               "allow_same_origin_host": true }
+
+With it, a request is accepted when ALL FOUR hold: the key opted in, there is
+genuinely NO `Origin` header, the browser sent `Sec-Fetch-Site: same-origin`,
+and the `Host` is one the key ALREADY LISTS as an origin. It accepts the same
+name by a second route; it never adds a new one.
+
+**OFF BY DEFAULT, and that is deliberate rather than cautious.** In a browser
+`Sec-Fetch-Site` is trustworthy - it is a forbidden header name and page script
+cannot set it - but a non-browser client sets it with one curl flag. Today an
+absent Origin being refused is what makes an origin-pinned key unusable outside
+a browser at all. Accepting the header for every key would turn "this
+publishable key works only in a browser on these origins" into "it works
+anywhere that sets two headers", and a publishable key is extractable from the
+page by construction. So the weakening is chosen per key, by whoever actually
+hosts an app on the hostname.
+
+It does NOT widen anything else, and each of these is pinned by a test: a key
+without the flag is still refused; a Host the key never listed is refused; a
+request presenting a WRONG `Origin` is refused even when it claims
+same-origin; and a request with no `Sec-Fetch-Site` at all is refused.
+
+## Certificates: issued by an external client, reconciled on a timer
+
+vectorapi does not speak ACME and will not. `packaging/tls/reconcile-certs.sh`
+reads every registered hostname - the deployment's own and every project's -
+and runs `certbot certonly --standalone` for any that has no certificate in the
+watched directory, then installs it under the `<host>.crt` / `<host>.key` names
+the SNI selector looks for. Idempotent, so it is safe on a timer and safe to
+run twice.
+
+Adding a hostname is therefore two steps, not a protocol: register it, then let
+the reconciler issue. Port 80 is deliberately left free for exactly this -
+vectorapi listens only on 443.
+
+**The certificate directory is WATCHED**, so a newly issued or renewed
+certificate takes effect without a restart. The first implementation loaded the
+directory once at boot, which made renewal silent and useless: certbot would
+write a fresh certificate every 60 days and the process would serve the copy it
+read at startup until something unrelated restarted it.
+
 ## Static files: serving a project's own assets
 
 OFF by default and it needs TWO independent things, neither of which implies

+ 11 - 1
api/openapi.json

@@ -2,7 +2,7 @@
   "openapi": "3.1.0",
   "info": {
     "title": "smartbotic-vectorapi",
-    "version": "0.20.0",
+    "version": "0.21.0",
     "description": "General-purpose REST API fronting smartbotic-database. Supports multi-project namespacing and multi-key authorization with per-project grants."
   },
   "components": {
@@ -268,6 +268,11 @@
               "203.0.113.0/24",
               "198.51.100.7"
             ]
+          },
+          "allow_same_origin_host": {
+            "type": "boolean",
+            "default": false,
+            "description": "Accept a same-origin request that carries NO Origin header, when Sec-Fetch-Site is same-origin and Host is one this key already lists. Off by default: Sec-Fetch-Site is trustworthy in a browser but trivially set by a non-browser client, so this is opted into per key rather than applied to all."
           }
         }
       },
@@ -627,6 +632,11 @@
             },
             "readOnly": true,
             "description": "NOT SUPPORTED ON A KEY and refused with 422 `unsupported_option` rather than stored. Nothing checks it for an API key, and a security control that reads back from the server while never being applied is worse than an absent one. It is a FUNCTION POLICY field (PUT /api/v1/projects/{project}/functions/{id}/policy). For a browser key use `origins`; a server-side key has no address control today, because a non-browser client sends no Origin."
+          },
+          "allow_same_origin_host": {
+            "type": "boolean",
+            "default": false,
+            "description": "Accept a same-origin request that carries NO Origin header, when Sec-Fetch-Site is same-origin and Host is one this key already lists. Off by default: Sec-Fetch-Site is trustworthy in a browser but trivially set by a non-browser client, so this is opted into per key rather than applied to all."
           }
         },
         "required": [

+ 75 - 0
packaging/tls/reconcile-certs.sh

@@ -0,0 +1,75 @@
+#!/bin/bash
+# Issue a certificate for every registered hostname that lacks one.
+#
+# WHY THIS EXISTS: adding a hostname in the web UI used to be half a job - the
+# name resolved, the registry served it, and TLS refused the handshake because
+# no certificate existed, which an operator experiences as "I added a host and
+# it does not work" with nothing saying why.
+#
+# WHY NOT AN ACME CLIENT INSIDE VECTORAPI, which was asked and is the obvious
+# idea: an ACME bug in our own process is a live outage on EVERY hostname at
+# once, renewal scheduling is somebody else's well-tested code, and an account
+# key is a credential we would rather not hold. Certbot already runs here and
+# already renews on a timer. What was missing was never the protocol - it was
+# nobody connecting "a hostname was registered" to "ask for a certificate".
+# This is that connection, and it is 60 lines rather than a protocol.
+#
+# Idempotent: a hostname that already has a live certificate is skipped, so it
+# is safe to run on a timer and safe to run by hand twice.
+set -u
+
+BASE="${VECTORAPI_BASE:-https://127.0.0.1}"
+HOSTHDR="${VECTORAPI_ADMIN_HOST:-sb-prod-01.smartbotics.ai}"
+CERTDIR="${VECTORAPI_CERT_DIR:-/etc/smartbotic-vectorapi/tls}"
+ENVFILE="${VECTORAPI_ENV:-/etc/smartbotic-vectorapi/vectorapi.env}"
+
+KEY=$(grep -oE '^SMARTBOTIC_VECTORAPI_KEY=.*' "$ENVFILE" 2>/dev/null | cut -d= -f2)
+if [ -z "$KEY" ]; then echo "no admin key in $ENVFILE" >&2; exit 1; fi
+
+api() { curl -s -k --resolve "$HOSTHDR:443:127.0.0.1" -H "Authorization: Bearer $KEY" "$@"; }
+
+projects=$(api "https://$HOSTHDR/api/v1/projects" | python3 -c 'import json,sys; print(" ".join(json.load(sys.stdin).get("projects",[])))' 2>/dev/null)
+if [ -z "$projects" ]; then echo "could not list projects" >&2; exit 1; fi
+
+# The deployment's own names count too - they need certificates like any other.
+wanted=$(api "https://$HOSTHDR/api/v1/settings" | python3 -c '
+import json,sys
+d=json.load(sys.stdin)
+out=[d.get("admin_hostname","")]+list(d.get("global_hostnames",[]) or [])
+print(" ".join(h for h in out if h))' 2>/dev/null)
+
+for p in $projects; do
+  hs=$(api "https://$HOSTHDR/api/v1/projects/$p/settings/hostnames" | python3 -c '
+import json,sys
+try: print(" ".join(h["host"] for h in json.load(sys.stdin).get("hostnames",[])))
+except Exception: pass' 2>/dev/null)
+  wanted="$wanted $hs"
+done
+
+issued=0; skipped=0; failed=0
+for h in $wanted; do
+  [ -z "$h" ] && continue
+  if [ -s "$CERTDIR/$h.crt" ] && [ -s "$CERTDIR/$h.key" ]; then
+    skipped=$((skipped+1)); continue
+  fi
+  echo "  issuing for $h"
+  # --standalone needs port 80 free. vectorapi deliberately does NOT listen
+  # there, precisely so renewals can bind it.
+  if certbot certonly --standalone --non-interactive --agree-tos \
+       --register-unsafely-without-email --quiet -d "$h" 2>/tmp/rc.err; then
+    install -m640 -o root -g smartbotic-vectorapi \
+      "/etc/letsencrypt/live/$h/fullchain.pem" "$CERTDIR/$h.crt"
+    install -m640 -o root -g smartbotic-vectorapi \
+      "/etc/letsencrypt/live/$h/privkey.pem" "$CERTDIR/$h.key"
+    issued=$((issued+1))
+  else
+    # NAMED, not counted silently. A hostname whose certificate could not be
+    # issued refuses every handshake, and the operator needs to know WHICH.
+    echo "  FAILED for $h: $(head -2 /tmp/rc.err | tr '\n' ' ')" >&2
+    failed=$((failed+1))
+  fi
+done
+rm -f /tmp/rc.err
+echo "  certificates: $issued issued, $skipped already present, $failed failed"
+[ "$failed" -gt 0 ] && exit 1
+exit 0

+ 4 - 0
src/apikey.cpp

@@ -84,6 +84,7 @@ bool KeyScope::expired(uint64_t nowEpochSec) const {
 
 KeyScope KeyScope::fromJson(const nlohmann::json& j) {
     KeyScope s;
+    s.allowSameOriginHost = j.value("allow_same_origin_host", false);
     if (j.contains("rules") && j["rules"].is_array()) {
         for (const auto& rj : j["rules"]) {
             KeyScopeRule r;
@@ -116,7 +117,10 @@ nlohmann::json KeyScope::toJson() const {
     // empty would make "no restriction" and "this server does not know the
     // field" indistinguishable, which is this codebase's most repeated trap -
     // the same reason `scope_filtered` is sent unconditionally.
+    // Emitted ALWAYS for the same reason as ip_allow: a reader must be able to
+    // tell "this key does not opt in" from "this server has no such field".
     return {{"rules", rules_j}, {"origins", origins}, {"ip_allow", ipAllow},
+            {"allow_same_origin_host", allowSameOriginHost},
             {"rate_limit_per_min", rateLimitPerMin}, {"expires_at", expiresAt}};
 }
 

+ 30 - 1
src/apikey.hpp

@@ -63,7 +63,36 @@ struct KeyScope {
     /// `requireCapabilityCore`, which would spend one token per collection
     /// examined and could rate-limit a caller for a single listing.
     bool reachesCollection(const std::string& collection) const;
+    /// May a SAME-ORIGIN request with no `Origin` header be accepted, when the
+    /// Host it arrived on is one this key already lists as an origin?
+    ///
+    /// OFF BY DEFAULT, and that default is the whole point. Browsers do not
+    /// send `Origin` on a same-origin GET (the Fetch spec only adds it for
+    /// non-GET/HEAD), so an app SERVED FROM a project hostname calling that
+    /// project's own API with an origin-pinned key is refused - reported from a
+    /// live deployment, and a real defect of the two features together.
+    ///
+    /// The tempting fix is to accept `Sec-Fetch-Site: same-origin` globally.
+    /// That is wrong, and the reason is worth keeping: in a BROWSER the header
+    /// is trustworthy (it is a forbidden header name, page script cannot set
+    /// it), but a non-browser client sets it trivially with one curl flag.
+    /// Today an absent Origin being refused is what makes an origin-pinned key
+    /// unusable outside a browser at all - which is a real property, written
+    /// into our notes as "a key meant for server-side use must carry no
+    /// allow-list". Accepting the header globally would turn "this publishable
+    /// key works only in a browser on these origins" into "it works anywhere
+    /// that sets two headers", and a publishable key is extractable from the
+    /// page by construction.
+    ///
+    /// So the weakening is OPT-IN per key, chosen by whoever actually hosts an
+    /// app on the project hostname, and the cost is visible where the decision
+    /// is made. Same reasoning as `network_egress` defaulting to allow and
+    /// static serving defaulting to off: a control that widens access should be
+    /// an act, never an inherited state.
+    bool allowSameOriginHost = false;
+
     bool originAllowed(const std::string& origin) const;
+
     bool expired(uint64_t nowEpochSec) const;
     static KeyScope fromJson(const nlohmann::json& j);
     nlohmann::json  toJson() const;
@@ -80,7 +109,7 @@ struct ApiKey {
     std::optional<KeyScope> scope;
 
     static ApiKey      fromJson(const nlohmann::json& j);
-    nlohmann::json     toJson()       const;  // full (includes key) — for DB storage
+    nlohmann::json     toJson()       const;  // full (includes key) - for DB storage
     nlohmann::json     toPublicJson() const;  // masked: label, projects, admin, created_at, key_prefix
 
     /// Returns true if admin, or projects contains "*", or projects contains project.

+ 1 - 1
src/collection_registry.hpp

@@ -33,7 +33,7 @@ public:
     /// the current server process; without this, a restart leaves every
     /// per-project registry index invisible (collections appear empty / 404)
     /// even though the data survives. Call once at startup with all known
-    /// projects — mirrors KeyStore::bootstrap re-opening vectorapi_keys. (issue #1)
+    /// projects - mirrors KeyStore::bootstrap re-opening vectorapi_keys. (issue #1)
     void bootstrap(const std::vector<std::string>& projects);
 
     /// Add (or overwrite) a collection entry.  Returns true on success.

+ 4 - 4
src/embedding_cache.hpp

@@ -21,10 +21,10 @@ public:
         std::string text;
     };
 
-    /// capacity  — max live entries.
-    /// maxBytes  — max sum of vec.size()*sizeof(float) across all entries.
-    /// ttlSec    — 0 means no time-based expiry.
-    /// normalize — when true, text is trimmed and lower-cased before keying.
+    /// capacity - max live entries.
+    /// maxBytes - max sum of vec.size()*sizeof(float) across all entries.
+    /// ttlSec - 0 means no time-based expiry.
+    /// normalize - when true, text is trimmed and lower-cased before keying.
     explicit EmbeddingCache(size_t   capacity  = 4096,
                             size_t   maxBytes  = 268435456 /*256 MiB*/,
                             uint32_t ttlSec    = 86400,

+ 1 - 1
src/embeddings.cpp

@@ -68,7 +68,7 @@ private:
 
 // Process-wide registry keyed on everything that affects a connection's behavior.
 // A settings hot-reload that changes any of these fields naturally routes to a
-// freshly-built pool; the stale pool simply ages out of use (no eviction — YAGNI).
+// freshly-built pool; the stale pool simply ages out of use (no eviction - YAGNI).
 ClientPool& poolFor(const std::string& origin, const std::string& apiKey,
                     uint32_t connectTimeoutSec, uint32_t readTimeoutSec, uint32_t poolSize) {
     static std::mutex regMu;

+ 1 - 2
src/embeddings.hpp

@@ -5,8 +5,7 @@
 namespace svapi {
 std::vector<float> parseEmbeddingResponse(const nlohmann::json& body);
 
-// Split an OpenAI-compatible base URL into the origin (scheme://host[:port] —
-// httplib::Client ignores any path) and a path prefix to prepend to
+// Split an OpenAI-compatible base URL into the origin (scheme://host[:port] - // httplib::Client ignores any path) and a path prefix to prepend to
 // "/v1/embeddings". e.g. "https://api.openai.com" -> {"https://api.openai.com", ""};
 // "https://openrouter.ai/api" -> {"https://openrouter.ai", "/api"}.
 struct EmbeddingEndpoint { std::string origin; std::string path; };

+ 19 - 5
src/handlers/static_files.cpp

@@ -34,11 +34,20 @@ bool etagMatches(const std::string& header, const std::string& etag) {
 
 bool serveProjectStatic(ServerDeps& d, const std::string& project, const httplib::Request& req,
                         httplib::Response& res) {
-    // GET only. A HEAD would have to be answered without a body, and
-    // cpp-httplib's own handling of that for a pre-routing response is not
-    // something this path should be guessing about - so it is left to fall
-    // through to a plain 404 rather than served half-right.
-    if (req.method != "GET") return false;
+    // GET and HEAD. HEAD was refused at first on the grounds that answering it
+    // without a body from a pre-routing response was not something to guess at.
+    // That was the wrong trade, reported from a real deployment: a HEAD
+    // answering 404 where GET answers 200 breaks uptime checkers and link
+    // checkers, and it does so SILENTLY - the monitor reports the site down
+    // while the site is up, which is the most expensive shape a false alarm
+    // can take.
+    //
+    // The handling is the same path with the body dropped at the end, so a HEAD
+    // cannot drift from the GET it is supposed to describe: same status, same
+    // ETag, same Content-Type, same Cache-Control, and the same 304 on a
+    // matching If-None-Match.
+    const bool headOnly = req.method == "HEAD";
+    if (req.method != "GET" && !headOnly) return false;
 
     const auto ps = d.settings.projectSnapshot(project);
     // BOTH conditions, and neither implies the other: the caller has already
@@ -105,6 +114,11 @@ bool serveProjectStatic(ServerDeps& d, const std::string& project, const httplib
     const std::string type =
         got->first.contentType.empty() ? "application/octet-stream" : got->first.contentType;
     res.set_content(reinterpret_cast<const char*>(got->second.data()), got->second.size(), type);
+    // A HEAD carries every header the GET would and no body. Set the content
+    // FIRST so Content-Type and the length are computed from the real bytes,
+    // then drop the body - the alternative, branching earlier, is how a HEAD
+    // starts describing something the GET does not return.
+    if (headOnly) res.body.clear();
     res.status = 200;
     return true;
 }

+ 1 - 1
src/handlers/vectors.cpp

@@ -57,7 +57,7 @@ std::vector<float> resolveVector(ServerDeps* d, const std::string& project,
         // else project override, else global default.
         ResolvedEmbedding cfg = resolveEmbedding(*snap, proj.get(), meta);
         // This helper is shared by /search (query_text) AND /vectors insert (text), so the cache
-        // intentionally covers both paths — re-embedding identical text is wasted work either way.
+        // intentionally covers both paths - re-embedding identical text is wasted work either way.
         // When noStore is true (Cache-Control: no-store), skip both the cache get and put.
         const std::string text = body[textField].get<std::string>();
         EmbeddingCache::Key key{cfg.apiBase, cfg.model, text};

+ 1 - 1
src/key_store.cpp

@@ -53,7 +53,7 @@ void KeyStore::bootstrap(const std::string& envAdminKey) {
         db_.client().upsert(coll_, k.toJson(), k.id);
         reload();
         if (envAdminKey.empty())
-            spdlog::warn("Generated initial admin API key: {} — store it now; shown only once.", k.key);
+            spdlog::warn("Generated initial admin API key: {} - store it now; shown only once.", k.key);
     } else {
         // Migrate any existing keys that pre-date the stable-id feature:
         // if key_id is empty, the document was stored with doc_id = key (old scheme).

+ 1 - 1
src/key_store.hpp

@@ -21,7 +21,7 @@ public:
     /// is used as the key value; otherwise a random key is generated.
     void bootstrap(const std::string& envAdminKey);
 
-    /// Look up a key by its raw value.  Served from the snapshot — O(n).
+    /// Look up a key by its raw value.  Served from the snapshot - O(n).
     std::optional<ApiKey> lookup(const std::string& key) const;
 
     /// Return a copy of the current snapshot.

+ 88 - 2
src/server.cpp

@@ -1,5 +1,6 @@
 #include "scope_refusal.hpp"
 #include "server.hpp"
+#include <filesystem>
 #include <openssl/tls1.h>
 #include <openssl/ssl.h>
 #include "cert_store.hpp"
@@ -151,6 +152,40 @@ ApiServer::ApiServer(ServerDeps deps, std::string tlsCertDir) : d_(std::move(dep
     svr_ = std::make_unique<httplib::SSLServer>(
         [](httplib::tls::ctx_t ctx) { return installSniHook(static_cast<void*>(ctx)); });
     tls_ = true;
+    certDir_ = tlsCertDir;
+
+    // The watcher. Started only on the TLS path, so a plain-HTTP deployment
+    // carries no extra thread.
+    certWatch_ = std::thread([this] {
+        namespace fs = std::filesystem;
+        std::int64_t seen = 0;
+        while (!certWatchStop_.load(std::memory_order_relaxed)) {
+            for (int i = 0; i < 30 && !certWatchStop_.load(std::memory_order_relaxed); ++i)
+                std::this_thread::sleep_for(std::chrono::seconds(1));
+            if (certWatchStop_.load(std::memory_order_relaxed)) break;
+            std::error_code ec;
+            std::int64_t newest = 0;
+            for (fs::directory_iterator it(certDir_, ec), end; !ec && it != end; it.increment(ec)) {
+                const auto t = fs::last_write_time(it->path(), ec);
+                if (ec) { ec.clear(); continue; }
+                newest = std::max<std::int64_t>(newest, t.time_since_epoch().count());
+            }
+            if (ec || newest == 0 || newest == seen) continue;
+            // Skip the FIRST observation: the constructor already loaded this
+            // state, so reloading it would log a reload that changed nothing
+            // every time the process starts.
+            if (seen != 0) {
+                spdlog::info("TLS: the certificate directory changed, reloading");
+                certStore().reload(certDir_);
+            }
+            seen = newest;
+        }
+    });
+}
+
+ApiServer::~ApiServer() {
+    certWatchStop_.store(true, std::memory_order_relaxed);
+    if (certWatch_.joinable()) certWatch_.join();
 }
 
 bool ApiServer::valid() const {
@@ -226,6 +261,32 @@ void requireProjectManage(const ApiKey& k, const std::string& project) {
         throw ApiError(ErrCode::Forbidden, "forbidden", "scoped keys cannot manage collections");
 }
 
+/// Does this key list an origin whose HOST is `host`?
+///
+/// A FREE FUNCTION HERE, NOT A METHOD ON KeyScope, and the linker enforced it:
+/// `apikey.cpp` is compiled standalone by several narrow test targets that do
+/// not link hostnames.cpp, so giving the struct a dependency on normaliseHost
+/// broke them - which is the same trap recorded beside `ip_allow`, where the
+/// CIDR membership test was kept out of the struct for exactly this reason.
+/// The struct is pure data; anything needing other machinery lives where the
+/// machinery already is.
+///
+/// Matching on the HOST rather than reconstructing a scheme is deliberate: a
+/// `Host` header carries no scheme, and guessing one would be wrong on a
+/// deployment that terminates TLS somewhere else.
+static bool keyListsOriginHost(const KeyScope& sc, const std::string& host) {
+    if (host.empty()) return false;
+    const std::string want = normaliseHost(host);
+    if (want.empty()) return false;
+    for (const std::string& o : sc.origins) {
+        std::string h = o;
+        if (const auto p = h.find("://"); p != std::string::npos) h = h.substr(p + 3);
+        if (const auto slash = h.find('/'); slash != std::string::npos) h = h.substr(0, slash);
+        if (normaliseHost(h) == want) return true;
+    }
+    return false;
+}
+
 void requireAllowedOrigin(const ApiKey& k, const httplib::Request& req) {
     if (!k.scope) return;  // legacy full-access key: no allow-list to enforce
     std::string origin;
@@ -237,8 +298,33 @@ void requireAllowedOrigin(const ApiKey& k, const httplib::Request& req) {
     // carry an allow-list at all. Kept identical here deliberately: the bug
     // being fixed was the listing behaving DIFFERENTLY from its siblings, so
     // a second, softer rule here would replace one inconsistency with another.
-    if (!k.scope->originAllowed(origin))
-        throw ApiError(ErrCode::Forbidden, "forbidden", "origin not allowed for this key");
+    if (k.scope->originAllowed(origin)) return;
+
+    // THE SAME-ORIGIN OPT-IN. A browser sends no `Origin` on a same-origin
+    // GET, so an app served from a project hostname calling that project's own
+    // API with an origin-pinned key was refused - a real defect of static
+    // serving and origin pinning together, reported from a live deployment.
+    //
+    // All FOUR conditions, and each is load-bearing:
+    //   - the key opted in (default false; see KeyScope::allowSameOriginHost
+    //     for why this is not global)
+    //   - there is genuinely NO Origin, so this never widens a cross-origin
+    //     request that merely presented a bad one
+    //   - the browser says same-origin. In a browser `Sec-Fetch-Site` is a
+    //     forbidden header name and page script cannot set it; a non-browser
+    //     client can, which is exactly why the opt-in exists rather than this
+    //     being on for everyone
+    //   - the Host is one this key ALREADY LISTS as an origin, so the operator
+    //     named it; this accepts the same name by a second route, it does not
+    //     add a new one
+    if (origin.empty() && k.scope->allowSameOriginHost) {
+        std::string site, host;
+        if (auto it = req.headers.find("Sec-Fetch-Site"); it != req.headers.end()) site = it->second;
+        if (auto it = req.headers.find("Host"); it != req.headers.end()) host = it->second;
+        if (site == "same-origin" && keyListsOriginHost(*k.scope, host)) return;
+    }
+
+    throw ApiError(ErrCode::Forbidden, "forbidden", "origin not allowed for this key");
 }
 
 void requireCapability(ServerDeps& d, const ApiKey& k, const httplib::Request& req,

+ 23 - 2
src/server.hpp

@@ -11,6 +11,8 @@
 #include "key_store.hpp"
 #include "settings_store.hpp"
 #include <memory>
+#include <atomic>
+#include <thread>
 #include <httplib.h>
 #include <optional>
 #include <string>
@@ -81,6 +83,7 @@ public:
     /// fixture. Non-empty constructs an `SSLServer` instead and installs the
     /// SNI hook, so TLS is opt-in by configuration rather than by build.
     explicit ApiServer(ServerDeps deps, std::string tlsCertDir = {});
+    ~ApiServer();
     void registerRoutes();
     /// Size the request thread pool. 0 leaves cpp-httplib's own default
     /// (`max(8, hardware_concurrency - 1)`) in place.
@@ -110,6 +113,25 @@ private:
     /// changes.
     std::unique_ptr<httplib::Server> svr_;
     bool tls_ = false;
+
+    /// Re-read the certificate directory when it changes.
+    ///
+    /// THE DESIGN PROMISED A WATCHED DIRECTORY AND THE FIRST VERSION ONLY
+    /// LOADED ONCE, which made the whole arrangement half a job: an external
+    /// ACME client would write a renewed certificate every 60 days and this
+    /// process would go on serving the copy it read at boot, until something
+    /// unrelated restarted it. Found when a newly ISSUED certificate did not
+    /// take effect - the same gap, one step earlier and much louder, because
+    /// the hostname refused every handshake rather than serving a stale-but-
+    /// valid certificate.
+    ///
+    /// A poll on the directory's newest mtime rather than inotify: the check is
+    /// a handful of stat calls a minute against a directory with a dozen
+    /// entries, and inotify would add a platform dependency and an fd budget to
+    /// save nothing measurable at this size.
+    std::thread certWatch_;
+    std::atomic<bool> certWatchStop_{false};
+    std::string certDir_;
 };
 
 // Auth helpers (defined in server.cpp).
@@ -131,8 +153,7 @@ void   requireProjectAccess(const ApiKey& k, const std::string& project);  // th
 /// A key with no allow-list is unaffected: an empty list means any origin.
 void requireAllowedOrigin(const ApiKey& k, const httplib::Request& req);
 
-// Like requireProjectAccess, but additionally denies capability-scoped keys —
-// collection/project management is not expressible in a key scope, so a scoped
+// Like requireProjectAccess, but additionally denies capability-scoped keys - // collection/project management is not expressible in a key scope, so a scoped
 // (publishable) key must never reach these routes.
 void   requireProjectManage(const ApiKey& k, const std::string& project);  // throws Forbidden
 void   requireCapability(ServerDeps& d, const ApiKey& k, const httplib::Request& req,

+ 1 - 1
src/settings.hpp

@@ -5,7 +5,7 @@
 
 namespace svapi {
 
-/// Global service settings — no api_key field (keys live in KeyStore).
+/// Global service settings - no api_key field (keys live in KeyStore).
 struct Settings {
     std::string openaiApiBase            = "https://api.openai.com";
     std::string openaiApiKey;

+ 117 - 0
tests/test_api_integration.cpp

@@ -5985,3 +5985,120 @@ TEST_F(ApiFixture, TheAdminSPAShellIsNOTServedOnAProjectHostname) {
     EXPECT_NE(onAdmin->body.find("SVAPI_SPA_OK"), std::string::npos)
         << "the SPA history fallback stopped working on the admin hostname: " << onAdmin->body;
 }
+
+TEST_F(ApiFixture, HEADOnAStaticFileCarriesTheGETsHeadersAndNoBody) {
+    // REPORTED FROM A REAL DEPLOYMENT: HEAD answered 404 where GET answered
+    // 200, which breaks uptime and link checkers - and breaks them SILENTLY in
+    // the worst direction, reporting a site down while it is up.
+    //
+    // Written as a PAIRING against the GET rather than as a HEAD assertion
+    // alone, because a HEAD that returns 200 with the wrong headers would pass
+    // any test that only looked at the status.
+    HostGatingGuard guard{port_, adminKey_, project_};
+    StaticServingGuard sguard{port_, adminKey_, project_};
+    const std::string files = "/api/v1/projects/" + project_ + "/files/";
+
+    ASSERT_EQ(request("PUT", files + "probe.txt", "HEADPROBEBYTES", "text/plain", adminKey_,
+                      {{"X-File-Path", "/probe.txt"}})->status, 201);
+    ASSERT_EQ(admin().Put(("/api/v1/projects/" + project_ + "/settings/static").c_str(),
+        nlohmann::json{{"enabled", true}, {"mount", "/"}}.dump(), "application/json")->status, 200);
+    ASSERT_EQ(admin().Put(("/api/v1/projects/" + project_ + "/settings/hostnames").c_str(),
+        nlohmann::json{{"hostnames", {{{"host","tenant.example.com"},{"path_style","short"}}}}}.dump(),
+        "application/json")->status, 200);
+    ASSERT_EQ(admin().Put("/api/v1/settings",
+        nlohmann::json{{"admin_hostname", "admin.example.com"}}.dump(),
+        "application/json")->status, 200);
+
+    httplib::Client c("127.0.0.1", port_);
+    c.set_default_headers({{"Host", "tenant.example.com"}});
+
+    auto g = c.Get("/probe.txt");
+    ASSERT_TRUE(g);
+    ASSERT_EQ(g->status, 200) << "the GET half must work, or the pairing proves nothing";
+    EXPECT_EQ(g->body, "HEADPROBEBYTES");
+
+    auto h = c.Head("/probe.txt");
+    ASSERT_TRUE(h);
+    EXPECT_EQ(h->status, 200) << "HEAD answered " << h->status
+                              << " where GET answered 200 - an uptime checker reads that as down";
+    EXPECT_TRUE(h->body.empty()) << "a HEAD must carry no body";
+    // The headers a monitor and a cache actually use must DESCRIBE the GET.
+    EXPECT_EQ(h->get_header_value("ETag"), g->get_header_value("ETag"))
+        << "HEAD and GET disagree about the ETag, so a conditional request would be wrong";
+    EXPECT_EQ(h->get_header_value("Content-Type"), g->get_header_value("Content-Type"));
+    EXPECT_EQ(h->get_header_value("Cache-Control"), g->get_header_value("Cache-Control"));
+
+    // And a HEAD for something that does not exist is still a 404, so this did
+    // not turn the mount into a catch-all.
+    auto miss = c.Head("/nope-not-here.txt");
+    ASSERT_TRUE(miss);
+    EXPECT_EQ(miss->status, 404);
+}
+
+TEST_F(ApiFixture, ASameOriginGETWithNoOriginHeaderIsRefusedUnlessTheKeyOPTSIN) {
+    // REPORTED FROM A LIVE DEPLOYMENT: browsers send no `Origin` on a
+    // same-origin GET (the Fetch spec adds it only for non-GET/HEAD), so an app
+    // SERVED FROM a project hostname calling that project's own API with an
+    // origin-pinned key was refused 403.
+    //
+    // Written as a PAIRING in both directions, because the danger here is the
+    // fix widening more than intended: the opt-in must change this key's
+    // behaviour and NOTHING ELSE's.
+    const std::string origin = "https://tenant.example.com";
+    auto mint = [&](bool optIn) {
+        nlohmann::json scope{
+            {"rules", {{{"collection", "*"}, {"ops", {"read", "list"}}}}},
+            {"origins", {origin}},
+            {"allow_same_origin_host", optIn}};
+        auto r = admin().Post("/api/v1/keys",
+            nlohmann::json{{"label", optIn ? "optin" : "plain"},
+                           {"projects", {project_}}, {"scope", scope}}.dump(),
+            "application/json");
+        EXPECT_TRUE(r); EXPECT_EQ(r->status, 201) << (r ? r->body : "");
+        return nlohmann::json::parse(r->body).value("key", std::string());
+    };
+    const std::string plain = mint(false), optin = mint(true);
+    const std::string path = "/api/v1/projects/" + project_ + "/collections";
+
+    // The same-origin shape: NO Origin, browser says same-origin, Host is the
+    // name the key already lists.
+    const httplib::Headers sameOrigin{{"Sec-Fetch-Site", "same-origin"},
+                                      {"Host", "tenant.example.com"}};
+
+    // 1. WITHOUT the opt-in it is still refused - the default is unchanged,
+    //    which is the half that protects every existing key.
+    auto a = request("GET", path, "", "", plain, sameOrigin);
+    ASSERT_TRUE(a);
+    EXPECT_EQ(a->status, 403) << "the default changed; every origin-pinned key just got wider";
+
+    // 2. WITH the opt-in it is allowed.
+    auto b = request("GET", path, "", "", optin, sameOrigin);
+    ASSERT_TRUE(b);
+    EXPECT_EQ(b->status, 200) << "the opt-in did not take effect: " << b->body;
+
+    // 3. The opt-in does NOT accept a WRONG host, even claiming same-origin.
+    //    Without this, the opt-in would be "any host at all".
+    auto c = request("GET", path, "", "", optin,
+                     {{"Sec-Fetch-Site", "same-origin"}, {"Host", "evil.example.com"}});
+    ASSERT_TRUE(c);
+    EXPECT_EQ(c->status, 403) << "a host the key never listed was accepted";
+
+    // 4. The opt-in does NOT widen a CROSS-origin request that presents a bad
+    //    Origin. It only ever covers the case where there is NO Origin at all.
+    auto d = request("GET", path, "", "", optin,
+                     {{"Origin", "https://evil.example.com"},
+                      {"Sec-Fetch-Site", "same-origin"}, {"Host", "tenant.example.com"}});
+    ASSERT_TRUE(d);
+    EXPECT_EQ(d->status, 403) << "a bad Origin was accepted because Sec-Fetch-Site lied";
+
+    // 5. And a client NOT claiming same-origin is still refused, so the header
+    //    is genuinely part of the decision rather than decoration.
+    auto e = request("GET", path, "", "", optin, {{"Host", "tenant.example.com"}});
+    ASSERT_TRUE(e);
+    EXPECT_EQ(e->status, 403) << "no Sec-Fetch-Site at all was treated as same-origin";
+
+    // 6. The listed origin still works the ordinary way.
+    auto f = request("GET", path, "", "", optin, {{"Origin", origin}});
+    ASSERT_TRUE(f);
+    EXPECT_EQ(f->status, 200) << "the normal cross-origin path broke";
+}

+ 4 - 4
tests/test_embeddings.cpp

@@ -90,7 +90,7 @@ TEST(Embeddings, PoolRunsRequestsConcurrently) {
     mock.stop(); srv.join();
 
     EXPECT_EQ(ok.load(), K);                 // all requests succeeded
-    EXPECT_GE(maxInFlight.load(), 2);        // proves overlap — pool did NOT serialize
+    EXPECT_GE(maxInFlight.load(), 2);        // proves overlap - pool did NOT serialize
 }
 
 TEST(Embeddings, PoolSizeOneSerializes) {
@@ -166,7 +166,7 @@ TEST(EmbeddingCache, EvictsLeastRecentlyUsedWhenFull) {
     cache.put(kC, {3.0f});
     // Touch A so it's recently used; B becomes the LRU
     cache.get(kA);
-    // Insert D — evicts B (least recently used)
+    // Insert D - evicts B (least recently used)
     cache.put(kD, {4.0f});
     EXPECT_TRUE(cache.get(kA).has_value());
     EXPECT_FALSE(cache.get(kB).has_value()); // evicted
@@ -210,7 +210,7 @@ TEST(EmbeddingCache, ExpiresAfterTtl) {
     cache.setClockForTesting([&fakeNow]{ return fakeNow; });
     EmbeddingCache::Key k{"base", "m", "text"};
     cache.put(k, {5.0f});
-    // Before expiry — hit
+    // Before expiry - hit
     EXPECT_TRUE(cache.get(k).has_value());
     // Advance clock past TTL
     fakeNow = 1061;
@@ -285,7 +285,7 @@ TEST(EmbeddingCache, ReconfigureEvictsToTighterBounds) {
     cache.put(kB, {2.0f});
     cache.put(kC, {3.0f});
     ASSERT_EQ(cache.stats().size, 3u);
-    // Shrink capacity to 1 — reconfigure must evict immediately, keeping the MRU entry.
+    // Shrink capacity to 1 - reconfigure must evict immediately, keeping the MRU entry.
     cache.reconfigure(1, 1024*1024, 0, false);
     auto s = cache.stats();
     EXPECT_EQ(s.size, 1u);

+ 1 - 1
webui/src/api/base.ts

@@ -24,7 +24,7 @@
  *
  * Dropping everything after the final '/' handles all three: under hash routing
  * the path always names the directory the app was served from, optionally plus
- * an index filename. Computed once — hash navigation never changes pathname.
+ * an index filename. Computed once - hash navigation never changes pathname.
  *
  * Returning '' rather than '/' for the root case matters: '/' would produce
  * '//api/v1/...', which browsers read as protocol-relative and send to a host

+ 1 - 1
webui/src/components/SchemaPanel.tsx

@@ -368,7 +368,7 @@ export function SchemaPanel({
                     >
                       {v.id}
                     </button>
-                    {' — '}
+                    {' - '}
                     {v.message}
                     {v.fields.length > 0 && (
                       <span className="text-slate-500"> ({v.fields.join(', ')})</span>

+ 13 - 2
webui/src/components/form.tsx

@@ -1,8 +1,19 @@
 // Shared form primitives. Extracted from the old single-page Settings form so
 // every settings tab renders identical controls.
 
-export const inputCls =
-  'w-full rounded-md bg-slate-800 border border-slate-600 text-slate-100 px-3 py-2 text-sm placeholder-slate-500 focus:outline-none focus:border-indigo-500 focus:ring-1 focus:ring-indigo-500/40'
+// The visual half ONLY - no width. A width here is a trap: Tailwind resolves
+// conflicting width utilities by STYLESHEET order, not by the order they appear
+// in a className string, so `${controlCls} w-36` left `w-full` winning and the
+// control took the whole row. That collapsed the hostname input beside it to
+// nothing, which is what the owner reported as "the host name input is too
+// small, it is unusable".
+export const controlCls =
+  'rounded-md bg-slate-800 border border-slate-600 text-slate-100 px-3 py-2 text-sm placeholder-slate-500 focus:outline-none focus:border-indigo-500 focus:ring-1 focus:ring-indigo-500/40'
+
+// The common case: a control that fills its row. Kept as its own export so the
+// callers that want full width say so, and the ones composing a narrower width
+// start from `controlCls` and cannot collide.
+export const inputCls = `w-full ${controlCls}`
 
 export function FormRow({
   label,

+ 11 - 11
webui/src/pages/Collections.tsx

@@ -289,8 +289,8 @@ function SummaryBar({ collections, scopeFiltered }: {
   return (
     <div className="grid grid-cols-2 sm:grid-cols-4 gap-3">
       <StatChip icon={<Layers size={16} />} label={`Collections${suffix}`} value={collections.length.toLocaleString()} />
-      <StatChip icon={<FileText size={16} />} label={`Documents${suffix}`} value={totals.hasDocs ? totals.docs.toLocaleString() : '—'} />
-      <StatChip icon={<HardDrive size={16} />} label={`Total size${suffix}`} value={totals.hasBytes ? humanizeBytes(totals.bytes) : '—'} />
+      <StatChip icon={<FileText size={16} />} label={`Documents${suffix}`} value={totals.hasDocs ? totals.docs.toLocaleString() : ' - '} />
+      <StatChip icon={<HardDrive size={16} />} label={`Total size${suffix}`} value={totals.hasBytes ? humanizeBytes(totals.bytes) : ' - '} />
       <StatChip icon={<Database size={16} />} label={`Vector collections${suffix}`} value={totals.vectors.toLocaleString()} />
     </div>
   )
@@ -387,7 +387,7 @@ function CollectionDetailDrawer({ project, name, onClose }: DetailDrawerProps) {
   })
 
   return (
-    <Modal open={name !== null} title={`Collection — ${name ?? ''}`} onClose={onClose}>
+    <Modal open={name !== null} title={`Collection - ${name ?? ''}`} onClose={onClose}>
       {isLoading && <p className="text-slate-400 text-sm">Loading…</p>}
       {isError && <p className="text-red-400 text-sm">Failed to load collection metadata.</p>}
       {data && (
@@ -397,12 +397,12 @@ function CollectionDetailDrawer({ project, name, onClose }: DetailDrawerProps) {
             <StatChip
               icon={<FileText size={16} />}
               label="Documents"
-              value={data.document_count !== undefined ? data.document_count.toLocaleString() : '—'}
+              value={data.document_count !== undefined ? data.document_count.toLocaleString() : ' - '}
             />
             <StatChip
               icon={<HardDrive size={16} />}
               label="Size"
-              value={data.size_bytes !== undefined ? humanizeBytes(data.size_bytes) : '—'}
+              value={data.size_bytes !== undefined ? humanizeBytes(data.size_bytes) : ' - '}
             />
           </div>
 
@@ -411,7 +411,7 @@ function CollectionDetailDrawer({ project, name, onClose }: DetailDrawerProps) {
             <DetailRow label="Kind" value={<KindBadge kind={data.kind} />} />
             {data.kind === 'vector' && <DetailRow label="Dimension" value={data.vector_dimension} />}
             {data.kind === 'vector' && (
-              <DetailRow label="Embedding model" value={data.embedding_model || '—'} />
+              <DetailRow label="Embedding model" value={data.embedding_model || ' - '} />
             )}
             <DetailRow label="Created" value={formatDate(data.created_at)} />
             <DetailRow
@@ -576,16 +576,16 @@ function CollectionsTable({ collections, project, query, sort, desc, onSort, sco
                   <KindBadge kind={col.kind} />
                 </td>
                 <td className="px-4 py-3 text-slate-300">
-                  {col.kind === 'vector' ? col.vector_dimension : <span className="text-slate-600">—</span>}
+                  {col.kind === 'vector' ? col.vector_dimension : <span className="text-slate-600">-</span>}
                 </td>
                 <td className="px-4 py-3 text-slate-300 text-xs font-mono">
-                  {col.embedding_model || <span className="text-slate-600">—</span>}
+                  {col.embedding_model || <span className="text-slate-600">-</span>}
                 </td>
                 <td className="px-4 py-3 text-right text-slate-300">
-                  {col.document_count !== undefined ? col.document_count.toLocaleString() : <span className="text-slate-600">—</span>}
+                  {col.document_count !== undefined ? col.document_count.toLocaleString() : <span className="text-slate-600">-</span>}
                 </td>
                 <td className="px-4 py-3 text-right text-slate-300">
-                  {col.size_bytes !== undefined ? humanizeBytes(col.size_bytes) : <span className="text-slate-600">—</span>}
+                  {col.size_bytes !== undefined ? humanizeBytes(col.size_bytes) : <span className="text-slate-600">-</span>}
                 </td>
                 <td className="px-4 py-3 text-right text-slate-400 text-xs whitespace-nowrap">
                   {formatDate(col.created_at)}
@@ -725,7 +725,7 @@ export default function Collections() {
         </div>
         <div className="rounded-xl border border-slate-700/40 bg-slate-800/30 px-6 py-10 text-center">
           <p className="text-slate-400 text-sm">
-            No project selected — choose a project from the selector above.
+            No project selected - choose a project from the selector above.
           </p>
         </div>
       </div>

+ 11 - 11
webui/src/pages/Documents.tsx

@@ -562,7 +562,7 @@ function DocEditorModal({
       const parsed = JSON.parse(json) as Record<string, unknown>
       await onSave(parsed)
     } catch {
-      // parse error — shouldn't happen since Save is disabled when invalid
+      // parse error - shouldn't happen since Save is disabled when invalid
     }
   }
 
@@ -580,7 +580,7 @@ function DocEditorModal({
           />
 
           {!jsonValid && (
-            <p className="text-xs text-red-400">Invalid JSON — fix before saving.</p>
+            <p className="text-xs text-red-400">Invalid JSON - fix before saving.</p>
           )}
 
           {project && collection && docId && jsonValid && (() => {
@@ -782,7 +782,7 @@ export default function Documents() {
   const push = useToastStore((s) => s.push)
   const queryClient = useQueryClient()
 
-  // Collection selection — driven by the `?collection=` query param so the
+  // Collection selection - driven by the `?collection=` query param so the
   // selection is shareable/bookmarkable and links from the Collections page
   // land directly on the right collection.
   const [searchParams, setSearchParams] = useSearchParams()
@@ -937,7 +937,7 @@ export default function Documents() {
       await navigator.clipboard.writeText(text)
       push(`${label} copied to clipboard.`, 'success')
     } catch {
-      push('Copy failed — clipboard unavailable.', 'error')
+      push('Copy failed - clipboard unavailable.', 'error')
     }
   }
 
@@ -1019,7 +1019,7 @@ export default function Documents() {
       } else {
         const msg = err instanceof ApiError ? err.message : String(err)
         push(`Delete failed: ${msg}`, 'error')
-        return // real failure — keep the editor open
+        return // real failure - keep the editor open
       }
     }
     setModalOpen(false)
@@ -1037,7 +1037,7 @@ export default function Documents() {
         </div>
         <div className="rounded-xl border border-slate-700/40 bg-slate-800/30 px-6 py-10 text-center">
           <p className="text-slate-400 text-sm">
-            No project selected — choose a project from the selector above.
+            No project selected - choose a project from the selector above.
           </p>
         </div>
       </div>
@@ -1083,15 +1083,15 @@ export default function Documents() {
               Collections
             </Link>
             <ChevronRight size={12} className="text-slate-600" />
-            <span className="font-mono text-slate-400">{effectiveCollection || '—'}</span>
+            <span className="font-mono text-slate-400">{effectiveCollection || ' - '}</span>
           </nav>
           <h1 className="text-2xl font-semibold text-slate-100">Documents</h1>
           <p className="text-slate-400 text-sm mt-1">
             Project: <span className="text-slate-300 font-mono">{currentProject}</span>
             {docCount !== null && (
               <span className="ml-2 text-slate-500" data-testid="docs-count">
-                — showing {docCount.toLocaleString()}
-                {(canNext || offsetNum > 0) && ` (rows ${(offsetNum + 1).toLocaleString()}–${(offsetNum + docs.length).toLocaleString()})`}
+ - showing {docCount.toLocaleString()}
+                {(canNext || offsetNum > 0) && ` (rows ${(offsetNum + 1).toLocaleString()} - ${(offsetNum + docs.length).toLocaleString()})`}
                 {totalMatching !== null && ` of ${totalMatching.toLocaleString()} matching`}
               </span>
             )}
@@ -1143,7 +1143,7 @@ export default function Documents() {
           onOffsetChange={setOffset}
           onSearch={() => applySearch()}
         />
-        {/* Sort row — ordering is applied server-side */}
+        {/* Sort row - ordering is applied server-side */}
         <div className="flex flex-wrap items-center gap-2">
           <label className="text-xs font-medium text-slate-400 shrink-0">Sort by</label>
           <input
@@ -1235,7 +1235,7 @@ export default function Documents() {
       {/* Editor modal */}
       <DocEditorModal
         open={modalOpen}
-        title={modalState.mode === 'new' ? 'New Document' : `Edit Document — ${modalState.docId}`}
+        title={modalState.mode === 'new' ? 'New Document' : `Edit Document - ${modalState.docId}`}
         initialJson={modalState.json}
         meta={modalState.meta}
         project={modalState.mode === 'edit' ? currentProject : undefined}

+ 2 - 2
webui/src/pages/Functions.tsx

@@ -13,7 +13,7 @@ import { ConfirmDialog } from '@/components/ConfirmDialog'
 import { JsonEditor } from '@/components/JsonEditor'
 import { SourceEditor } from '@/components/SourceEditor'
 import { ScopeRulesEditor, ScopeRulesView, usableRules } from '@/components/ScopeRules'
-import { Toggle, inputCls } from '@/components/form'
+import { Toggle, controlCls, inputCls } from '@/components/form'
 import { ApiError } from '@/types'
 import type {
   FunctionSummary, FunctionDetail, FunctionDescriptor, FunctionRun,
@@ -955,7 +955,7 @@ function RunsTab({ project, fn, runsKept }: { project: string; fn: FunctionSumma
             min={1}
             value={limit}
             onChange={(e) => setLimit(Math.max(1, Math.floor(Number(e.target.value) || 1)))}
-            className={`${inputCls} w-24`}
+            className={`${controlCls} w-24`}
           />
         </div>
         <button

+ 4 - 4
webui/src/pages/KeysAdmin.tsx

@@ -248,7 +248,7 @@ function NewKeyForm({ allProjects, onCreated, onCancel }: NewKeyFormProps) {
         </label>
         {isScoped && (
           <p className="text-xs text-slate-500 mt-1 ml-14">
-            Scoped keys are safe to expose client-side — enforced by collection rules, origins, and rate limits.
+            Scoped keys are safe to expose client-side - enforced by collection rules, origins, and rate limits.
           </p>
         )}
       </div>
@@ -343,12 +343,12 @@ function KeyRevealModal({ keyValue, onClose }: KeyRevealModalProps) {
       setCopied(true)
       setTimeout(() => setCopied(false), 2000)
     } catch {
-      // clipboard access failed — the user can still select-copy manually
+      // clipboard access failed - the user can still select-copy manually
     }
   }
 
   return (
-    <Modal open title="API Key Created — Copy Now" onClose={onClose}>
+    <Modal open title="API Key Created - Copy Now" onClose={onClose}>
       <div className="flex flex-col gap-4">
         <div className="rounded-lg bg-amber-500/10 border border-amber-500/30 px-4 py-3">
           <p className="text-amber-300 text-sm font-medium">
@@ -718,7 +718,7 @@ export default function KeysAdmin() {
         />
       </Modal>
 
-      {/* Key reveal — shown once after creation */}
+      {/* Key reveal - shown once after creation */}
       {revealKey && (
         <KeyRevealModal
           keyValue={revealKey.key}

+ 3 - 3
webui/src/pages/ProjectFiles.tsx

@@ -2,7 +2,7 @@ import { useState } from 'react'
 import { useQuery, useQueryClient } from '@tanstack/react-query'
 import { Download, Trash2, Upload } from 'lucide-react'
 import { api } from '@/api/client'
-import { Badge, FormRow, inputCls } from '@/components/form'
+import { Badge, FormRow, controlCls } from '@/components/form'
 import { ConfirmDialog } from '@/components/ConfirmDialog'
 import { useAuthStore } from '@/stores/authStore'
 import { useToastStore } from '@/stores/toastStore'
@@ -222,7 +222,7 @@ export default function ProjectFiles() {
             value={name}
             placeholder="logo.png"
             onChange={(e) => setName(e.target.value)}
-            className={`${inputCls} w-80 font-mono`}
+            className={`${controlCls} w-80 font-mono`}
             data-testid="file-name"
           />
         </FormRow>
@@ -242,7 +242,7 @@ export default function ProjectFiles() {
             value={path}
             placeholder="/assets/logo.png"
             onChange={(e) => setPath(e.target.value)}
-            className={`${inputCls} w-96 font-mono`}
+            className={`${controlCls} w-96 font-mono`}
             data-testid="file-path"
           />
         </FormRow>

+ 3 - 3
webui/src/pages/ProjectSecrets.tsx

@@ -2,7 +2,7 @@ import { useState } from 'react'
 import { useQuery, useQueryClient } from '@tanstack/react-query'
 import { KeyRound, Trash2 } from 'lucide-react'
 import { api } from '@/api/client'
-import { Badge, FormRow, inputCls } from '@/components/form'
+import { Badge, FormRow, controlCls } from '@/components/form'
 import { ConfirmDialog } from '@/components/ConfirmDialog'
 import { useAuthStore } from '@/stores/authStore'
 import { useToastStore } from '@/stores/toastStore'
@@ -198,7 +198,7 @@ export default function ProjectSecrets() {
               value={name}
               placeholder="OPENAI_API_KEY"
               onChange={(e) => setName(e.target.value.toUpperCase())}
-              className={`${inputCls} w-80 font-mono`}
+              className={`${controlCls} w-80 font-mono`}
               data-testid="secret-name"
             />
           </FormRow>
@@ -221,7 +221,7 @@ export default function ProjectSecrets() {
               autoComplete="new-password"
               placeholder={existing ? 'New value for this secret' : 'The value to store'}
               onChange={(e) => setValue(e.target.value)}
-              className={`${inputCls} w-full max-w-xl font-mono`}
+              className={`${controlCls} w-full max-w-xl font-mono`}
               data-testid="secret-value"
             />
           </FormRow>

+ 1 - 1
webui/src/pages/ProjectsAdmin.tsx

@@ -19,7 +19,7 @@ async function refreshAuthProjects() {
     const { projects } = await api.listProjects()
     useAuthStore.setState({ projects })
   } catch {
-    // best-effort — the store will be stale until next login, which is acceptable
+    // best-effort - the store will be stale until next login, which is acceptable
   }
 }
 

+ 2 - 2
webui/src/pages/RagTester.tsx

@@ -367,7 +367,7 @@ export default function RagTester() {
         </div>
         <div className="rounded-xl border border-slate-700/40 bg-slate-800/30 px-6 py-10 text-center">
           <p className="text-slate-400 text-sm">
-            No project selected — choose a project from the selector above.
+            No project selected - choose a project from the selector above.
           </p>
         </div>
       </div>
@@ -385,7 +385,7 @@ export default function RagTester() {
           Project: <span className="text-slate-300 font-mono">{currentProject}</span>
           {!collectionsLoading && (
             <span className="ml-2 text-slate-500">
-              — {vectorCollections.length} vector collection{vectorCollections.length !== 1 ? 's' : ''}
+ - {vectorCollections.length} vector collection{vectorCollections.length !== 1 ? 's' : ''}
             </span>
           )}
         </p>

+ 242 - 59
webui/src/pages/Settings.tsx

@@ -1,6 +1,7 @@
-import { useState } from 'react'
 import { useQuery } from '@tanstack/react-query'
+import { useSearchParams } from 'react-router-dom'
 import { api } from '@/api/client'
+import { Badge } from '@/components/form'
 import { useAuthStore } from '@/stores/authStore'
 import EmbeddingsTab from '@/pages/settings/EmbeddingsTab'
 import CacheTab from '@/pages/settings/CacheTab'
@@ -11,58 +12,163 @@ import ProjectFunctionsTab from '@/pages/settings/ProjectFunctionsTab'
 import ProjectHostnamesTab from '@/pages/settings/ProjectHostnamesTab'
 import ProjectStaticTab from '@/pages/settings/ProjectStaticTab'
 
-interface TabDef {
+/// The settings page is a TWO-LEVEL layout rather than one horizontal tab
+/// strip, and the reason is the division itself rather than the wrapping.
+///
+/// Eight items in one strip wrapped onto a second line, which is what was
+/// reported - but shrinking the labels would have fixed the symptom and left
+/// the real problem, which is that a global default and a per-project override
+/// looked like siblings. They are not: a global embedding default changes every
+/// tenant in the deployment, a project override changes one. The blast radius
+/// is the thing a user has to be able to read off the screen before they touch
+/// a control, so it decides the layout: a vertical list grouped by SCOPE, with
+/// the scope restated on the panel that is open.
+///
+/// Grouping vertically also removes the wrapping BY CONSTRUCTION - a vertical
+/// list cannot overflow horizontally however many items are added, so the next
+/// settings screen does not reintroduce the defect.
+
+/// `scope` is not decoration: it is what the section header, the nav badge and
+/// the panel's own sentence are all derived from, so the three cannot disagree.
+type Scope = 'global' | 'project'
+
+interface SettingsItem {
   id: string
   label: string
+  /// One line in the nav, so a user can choose without opening each panel.
+  blurb: string
+  /// Mirrors the route's own gating. Global settings are admin-only; the
+  /// per-project embedding override is requireProjectManage, which is why
+  /// /settings is not admin-gated in App.tsx and must stay reachable.
   adminOnly: boolean
   render: () => React.ReactNode
 }
 
+interface SettingsSection {
+  id: string
+  scope: Scope
+  title: string
+  caption: string
+  items: SettingsItem[]
+}
+
 export default function Settings() {
   const admin = useAuthStore((s) => s.admin)
   const project = useAuthStore((s) => s.currentProject)
+  const [searchParams, setSearchParams] = useSearchParams()
 
-  // Global settings are admin-only; the project tab is not, so a project
-  // manager landing here sees exactly the one tab they may use.
-  const tabs: TabDef[] = [
-    { id: 'embeddings', label: 'Embeddings', adminOnly: true, render: () => <EmbeddingsTab /> },
-    { id: 'cache', label: 'Cache & performance', adminOnly: true, render: () => <CacheTab /> },
-    { id: 'access', label: 'Access & security', adminOnly: true, render: () => <AccessTab /> },
-    { id: 'webui', label: 'Web UI', adminOnly: true, render: () => <WebuiTab /> },
+  const sections: SettingsSection[] = [
     {
-      id: 'project',
-      label: project ? `Project: ${project}` : 'Project',
-      adminOnly: false,
-      render: () => <ProjectEmbeddingsTab />,
+      id: 'global',
+      scope: 'global',
+      title: 'Global',
+      caption: 'This deployment, and therefore every project in it.',
+      items: [
+        {
+          id: 'embeddings',
+          label: 'Embeddings',
+          blurb: 'Default provider, key and model',
+          adminOnly: true,
+          render: () => <EmbeddingsTab />,
+        },
+        {
+          id: 'cache',
+          label: 'Cache & performance',
+          blurb: 'Embedding timeouts and the shared cache',
+          adminOnly: true,
+          render: () => <CacheTab />,
+        },
+        {
+          id: 'access',
+          label: 'Access & security',
+          blurb: 'CORS, sessions, captcha, function egress',
+          adminOnly: true,
+          render: () => <AccessTab />,
+        },
+        {
+          id: 'webui',
+          label: 'Web UI',
+          blurb: 'This interface and the default project',
+          adminOnly: true,
+          render: () => <WebuiTab />,
+        },
+      ],
     },
     {
-      id: 'functions',
-      label: 'Functions',
-      // Admin-only, matching the route: these bound what one project may take
-      // from a runner every other project shares.
-      adminOnly: true,
-      render: () => <ProjectFunctionsTab />,
-    },
-    {
-      id: 'hostnames',
-      label: 'Hostnames & TLS',
-      // Admin-only, matching the route: on the short path form the hostname is
-      // the tenancy boundary, so a project must not be able to claim one.
-      adminOnly: true,
-      render: () => <ProjectHostnamesTab />,
-    },
-    {
-      id: 'static',
-      label: 'Static files',
-      // Admin-only, matching the route: it decides what this project publishes
-      // to the open internet with no credential.
-      adminOnly: true,
-      render: () => <ProjectStaticTab />,
+      id: 'project',
+      scope: 'project',
+      title: 'Project',
+      caption: 'Only the selected project. Switch projects in the header.',
+      items: [
+        {
+          id: 'project-embeddings',
+          label: 'Embeddings override',
+          blurb: 'Point this project at its own provider',
+          // NOT admin-only, matching the route (requireProjectManage). This is
+          // the one item a project manager comes here for.
+          adminOnly: false,
+          render: () => <ProjectEmbeddingsTab />,
+        },
+        {
+          id: 'functions',
+          label: 'Functions',
+          blurb: 'Wall-time caps and network egress',
+          // Admin-only, matching the route: these bound what one project may
+          // take from a runner every other project shares.
+          adminOnly: true,
+          render: () => <ProjectFunctionsTab />,
+        },
+        {
+          id: 'hostnames',
+          label: 'Hostnames & TLS',
+          blurb: 'The names this project answers on',
+          // Admin-only, matching the route: on the short path form the hostname
+          // is the tenancy boundary, so a project must not be able to claim one.
+          adminOnly: true,
+          render: () => <ProjectHostnamesTab />,
+        },
+        {
+          id: 'static',
+          label: 'Static files',
+          blurb: 'Serve stored files publicly',
+          // Admin-only, matching the route: it decides what this project
+          // publishes to the open internet with no credential.
+          adminOnly: true,
+          render: () => <ProjectStaticTab />,
+        },
+      ],
     },
-  ].filter((t) => admin || !t.adminOnly)
+  ]
 
-  const [active, setActive] = useState(tabs[0]?.id ?? 'project')
-  const current = tabs.find((t) => t.id === active) ?? tabs[0]
+  // The page renders only the items this key may use, which is what keeps a
+  // non-admin session on a page with exactly one item rather than on a wall of
+  // controls that all answer 403. A section with nothing left disappears with
+  // its items rather than rendering an empty heading.
+  const visible = sections
+    .map((s) => ({ ...s, items: s.items.filter((i) => admin || !i.adminOnly) }))
+    .filter((s) => s.items.length > 0)
+
+  const flat = visible.flatMap((s) => s.items.map((i) => ({ item: i, section: s })))
+
+  /// The open item lives in the URL so a settings screen can be linked to.
+  /// An unknown or now-forbidden `tab` falls back to the first visible item
+  /// rather than rendering nothing: the id may name an admin-only item this
+  /// session may not have, and a shared link must not produce a blank page.
+  const requested = searchParams.get('tab') ?? ''
+  const currentEntry = flat.find((e) => e.item.id === requested) ?? flat[0]
+
+  function selectItem(id: string) {
+    // `replace` rather than push: clicking through four panels should not make
+    // Back mean "the previous panel" four times before it means "leave".
+    setSearchParams(
+      (prev) => {
+        const next = new URLSearchParams(prev)
+        next.set('tab', id)
+        return next
+      },
+      { replace: true },
+    )
+  }
 
   // Only used to surface a load failure once, at the page level.
   const { isError, error } = useQuery({
@@ -71,12 +177,15 @@ export default function Settings() {
     enabled: admin,
   })
 
+  const current = currentEntry?.item
+  const currentScope = currentEntry?.section.scope ?? 'global'
+
   return (
-    <div className="flex flex-col gap-6 max-w-3xl">
+    <div className="flex flex-col gap-6 max-w-5xl">
       <div>
         <h1 className="text-2xl font-semibold text-slate-100">Settings</h1>
         <p className="text-slate-400 text-sm mt-1">
-          Changes apply immediately (hot reload). Each tab saves on its own.
+          Changes apply immediately (hot reload). Each panel saves on its own.
         </p>
       </div>
 
@@ -88,27 +197,101 @@ export default function Settings() {
         </div>
       )}
 
-      <div className="flex flex-wrap gap-1 border-b border-slate-700">
-        {tabs.map((t) => (
-          <button
-            key={t.id}
-            type="button"
-            onClick={() => setActive(t.id)}
-            className={[
-              'px-4 py-2 text-sm font-medium border-b-2 -mb-px transition',
-              t.id === current?.id
-                ? 'border-indigo-500 text-slate-100'
-                : 'border-transparent text-slate-400 hover:text-slate-200',
-            ].join(' ')}
-          >
-            {t.label}
-          </button>
-        ))}
-      </div>
+      <div className="flex flex-col gap-6 lg:flex-row lg:items-start">
+        <nav aria-label="Settings sections" className="flex flex-col gap-6 lg:w-64 lg:shrink-0">
+          {visible.map((section) => (
+            <div key={section.id} className="flex flex-col gap-1">
+              <div className="flex items-center gap-2 px-1">
+                <span className="text-[11px] font-semibold uppercase tracking-wider text-slate-500">
+                  {section.title}
+                </span>
+                <ScopeBadge scope={section.scope} project={project} />
+              </div>
+              <p className="px-1 text-xs text-slate-500">{section.caption}</p>
 
-      <div className="rounded-xl border border-slate-700 bg-slate-800/30 px-6 py-5">
-        {current?.render()}
+              <ul className="mt-1 flex flex-col gap-0.5">
+                {section.items.map((item) => {
+                  const active = item.id === current?.id
+                  return (
+                    <li key={item.id}>
+                      <button
+                        type="button"
+                        onClick={() => selectItem(item.id)}
+                        aria-current={active ? 'page' : undefined}
+                        className={[
+                          'w-full rounded-md border-l-2 px-3 py-2 text-left transition',
+                          active
+                            ? 'border-indigo-500 bg-slate-800/60 text-slate-100'
+                            : 'border-transparent text-slate-400 hover:bg-slate-800/30 hover:text-slate-200',
+                        ].join(' ')}
+                      >
+                        <span className="block text-sm font-medium">{item.label}</span>
+                        <span className="block text-xs text-slate-500">{item.blurb}</span>
+                      </button>
+                    </li>
+                  )
+                })}
+              </ul>
+            </div>
+          ))}
+
+          {/* Said here because the project hostnames panel tells the reader to
+              set a deployment hostname "in the global settings", and there is
+              no such control in this UI: it would be a dead end otherwise. */}
+          {admin && (
+            <p className="px-1 text-xs text-slate-500">
+              The deployment's own names (<code>admin_hostname</code>,{' '}
+              <code>global_hostnames</code>) are global settings and are not editable here yet.
+              Set them on <code>PUT /api/v1/settings</code>.
+            </p>
+          )}
+        </nav>
+
+        <section className="min-w-0 flex-1">
+          <div className="rounded-xl border border-slate-700 bg-slate-800/30">
+            <div className="flex flex-col gap-2 border-b border-slate-700 px-6 py-4">
+              <div className="flex flex-wrap items-center gap-2">
+                <h2 className="text-base font-semibold text-slate-100">
+                  {current?.label ?? 'Settings'}
+                </h2>
+                <ScopeBadge scope={currentScope} project={project} />
+              </div>
+              {/* The blast radius, restated on the panel that is open. The
+                  project selector lives in the page header, far from here, so
+                  a per-project panel that did not name its project would be
+                  asking the user to remember which tenant they are editing. */}
+              <p className="text-xs text-slate-400">
+                {currentScope === 'project' ? (
+                  project ? (
+                    <>
+                      Applies to <strong className="text-slate-200">{project}</strong> only. No other
+                      project is affected.
+                    </>
+                  ) : (
+                    <>No project is selected, so there is nothing for this panel to change yet.</>
+                  )
+                ) : (
+                  <>
+                    Applies to the <strong className="text-slate-200">whole deployment</strong>, so
+                    every project is affected.
+                  </>
+                )}
+              </p>
+            </div>
+
+            <div className="px-6 py-5">{current?.render()}</div>
+          </div>
+        </section>
       </div>
     </div>
   )
 }
+
+/// One badge, used in both places the scope is stated, so the nav and the open
+/// panel cannot drift apart. A project badge names the project because the
+/// scope is worthless without it: "project" alone does not say which.
+function ScopeBadge({ scope, project }: { scope: Scope; project: string | null }) {
+  if (scope === 'global') return <Badge>all projects</Badge>
+  if (!project) return <Badge tone="amber">no project selected</Badge>
+  return <Badge tone="indigo">{project}</Badge>
+}

+ 5 - 3
webui/src/pages/settings/AccessTab.tsx

@@ -1,5 +1,5 @@
 import { useState } from 'react'
-import { FormRow, inputCls, SaveButton } from '@/components/form'
+import { FormRow, controlCls, inputCls, SaveButton } from '@/components/form'
 import { useSettingsForm, usePopulate, parseIntField } from './useSettingsForm'
 
 export default function AccessTab() {
@@ -53,7 +53,8 @@ export default function AccessTab() {
       </FormRow>
 
       <FormRow label="Session TTL (minutes)" hint="Lifetime of a web UI cookie session.">
-        <input type="number" value={sessionTtl} onChange={(e) => setSessionTtl(e.target.value)} className={inputCls} />
+        <input type="number" value={sessionTtl} onChange={(e) => setSessionTtl(e.target.value)}
+          className={`${controlCls} w-32`} />
       </FormRow>
 
       <h2 className="text-sm font-semibold text-slate-300 border-t border-slate-700 pt-4 mt-1">
@@ -107,7 +108,8 @@ export default function AccessTab() {
       </h2>
 
       <FormRow label="Provider" hint="Blank disables captcha verification.">
-        <select value={captchaProvider} onChange={(e) => setCaptchaProvider(e.target.value)} className={inputCls}>
+        <select value={captchaProvider} onChange={(e) => setCaptchaProvider(e.target.value)}
+          className={`${controlCls} w-64`}>
           <option value="">Disabled</option>
           <option value="turnstile">Cloudflare Turnstile</option>
           <option value="hcaptcha">hCaptcha</option>

+ 2 - 2
webui/src/pages/settings/ProjectEmbeddingsTab.tsx

@@ -2,7 +2,7 @@ import { useEffect, useState } from 'react'
 import { useQuery, useQueryClient } from '@tanstack/react-query'
 import { RotateCcw } from 'lucide-react'
 import { api } from '@/api/client'
-import { Badge, FormRow, inputCls, SaveButton } from '@/components/form'
+import { Badge, FormRow, controlCls, SaveButton } from '@/components/form'
 import { ConfirmDialog } from '@/components/ConfirmDialog'
 import { useAuthStore } from '@/stores/authStore'
 import { useToastStore } from '@/stores/toastStore'
@@ -48,7 +48,7 @@ function OverrideRow({
           disabled={!overriding}
           onChange={(e) => onChange(e.target.value)}
           placeholder={overriding ? placeholderWhenSecret ?? '' : inherited}
-          className={`${inputCls} ${overriding ? '' : 'opacity-60'}`}
+          className={`flex-1 min-w-0 ${controlCls} ${overriding ? '' : 'opacity-60'}`}
         />
         <button
           type="button"

+ 4 - 4
webui/src/pages/settings/ProjectFunctionsTab.tsx

@@ -1,7 +1,7 @@
 import { useEffect, useState } from 'react'
 import { useQuery, useQueryClient } from '@tanstack/react-query'
 import { api } from '@/api/client'
-import { Badge, FormRow, inputCls, SaveButton } from '@/components/form'
+import { Badge, FormRow, controlCls, SaveButton } from '@/components/form'
 import { useAuthStore } from '@/stores/authStore'
 import { useToastStore } from '@/stores/toastStore'
 import { ApiError } from '@/types'
@@ -103,7 +103,7 @@ export default function ProjectFunctionsTab() {
           <select
             value={egress}
             onChange={(e) => setEgress(e.target.value as 'inherit' | 'allow' | 'deny')}
-            className={inputCls}
+            className={`${controlCls} w-44`}
             data-testid="egress-select"
           >
             <option value="inherit">inherit (allow)</option>
@@ -134,7 +134,7 @@ export default function ProjectFunctionsTab() {
           value={http}
           placeholder="no project cap"
           onChange={(e) => setHttp(e.target.value)}
-          className={`${inputCls} w-40`}
+          className={`${controlCls} w-40`}
           data-testid="wall-http"
         />
       </FormRow>
@@ -149,7 +149,7 @@ export default function ProjectFunctionsTab() {
           value={job}
           placeholder="no project cap"
           onChange={(e) => setJob(e.target.value)}
-          className={`${inputCls} w-40`}
+          className={`${controlCls} w-40`}
           data-testid="wall-job"
         />
       </FormRow>

+ 4 - 4
webui/src/pages/settings/ProjectHostnamesTab.tsx

@@ -2,7 +2,7 @@ import { useEffect, useState } from 'react'
 import { useQuery, useQueryClient } from '@tanstack/react-query'
 import { Plus, Trash2 } from 'lucide-react'
 import { api } from '@/api/client'
-import { Badge, FormRow, inputCls, SaveButton } from '@/components/form'
+import { Badge, controlCls, FormRow, SaveButton } from '@/components/form'
 import { useAuthStore } from '@/stores/authStore'
 import { useToastStore } from '@/stores/toastStore'
 import { ApiError } from '@/types'
@@ -241,7 +241,7 @@ export default function ProjectHostnamesTab() {
                 className="rounded-md border border-slate-700 bg-slate-800/40 px-3 py-3 flex flex-col gap-2"
                 data-testid="hostname-row"
               >
-                <div className="flex items-center gap-2">
+                <div className="grid grid-cols-[minmax(0,1fr)_9rem_auto] items-center gap-2">
                   <input
                     type="text"
                     value={row.host}
@@ -251,7 +251,7 @@ export default function ProjectHostnamesTab() {
                       setRows((rs) => rs.map((r) => (r.key === row.key ? { ...r, host: next } : r)))
                       setServerRefusal(null)
                     }}
-                    className={`${inputCls} flex-1 font-mono`}
+                    className={`${controlCls} w-full min-w-0 font-mono`}
                     data-testid="hostname-host"
                   />
                   <select
@@ -262,7 +262,7 @@ export default function ProjectHostnamesTab() {
                         rs.map((r) => (r.key === row.key ? { ...r, path_style: next } : r)),
                       )
                     }}
-                    className={`${inputCls} w-36`}
+                    className={`${controlCls} w-full`}
                     data-testid="hostname-path-style"
                   >
                     <option value="short">short path</option>

+ 4 - 4
webui/src/pages/settings/ProjectStaticTab.tsx

@@ -1,7 +1,7 @@
 import { useEffect, useState } from 'react'
 import { useQuery, useQueryClient } from '@tanstack/react-query'
 import { api } from '@/api/client'
-import { Badge, FormRow, inputCls, SaveButton, Toggle } from '@/components/form'
+import { Badge, FormRow, controlCls, SaveButton, Toggle } from '@/components/form'
 import { useAuthStore } from '@/stores/authStore'
 import { useToastStore } from '@/stores/toastStore'
 import { ApiError } from '@/types'
@@ -235,7 +235,7 @@ export default function ProjectStaticTab() {
             setMount(e.target.value)
             setServerMountError(null)
           }}
-          className={`${inputCls} w-72`}
+          className={`${controlCls} w-72`}
           data-testid="static-mount"
         />
       </FormRow>
@@ -260,7 +260,7 @@ export default function ProjectStaticTab() {
           value={index}
           placeholder={DEFAULT_INDEX}
           onChange={(e) => setIndex(e.target.value)}
-          className={`${inputCls} w-72`}
+          className={`${controlCls} w-72`}
           data-testid="static-index"
         />
       </FormRow>
@@ -283,7 +283,7 @@ export default function ProjectStaticTab() {
           value={cacheControl}
           placeholder={DEFAULT_CACHE_CONTROL}
           onChange={(e) => setCacheControl(e.target.value)}
-          className={`${inputCls} w-96`}
+          className={`${controlCls} w-96`}
           data-testid="static-cache-control"
         />
       </FormRow>

+ 2 - 2
webui/src/pages/settings/WebuiTab.tsx

@@ -1,5 +1,5 @@
 import { useState } from 'react'
-import { FormRow, inputCls, Toggle, SaveButton } from '@/components/form'
+import { FormRow, controlCls, Toggle, SaveButton } from '@/components/form'
 import { useSettingsForm, usePopulate } from './useSettingsForm'
 
 export default function WebuiTab() {
@@ -27,7 +27,7 @@ export default function WebuiTab() {
 
       <FormRow label="Default project" hint="Project selected for a session that names none.">
         <input type="text" value={defaultProject} onChange={(e) => setDefaultProject(e.target.value)}
-          placeholder="default" className={inputCls} />
+          placeholder="default" className={`${controlCls} w-72`} />
       </FormRow>
 
       <SaveButton saving={saving} />