Add Web App settings to the API Server panel

Mirror the PocketBase settings card with a superadmin-only Web App
section: it edits the Web App base URL (the address /api/status already
probed) and the CORS allowed origins, applying both at runtime and
persisting them to .env so they survive a restart.

The CORS middleware previously built its allow-list once, when Handler()
was constructed, so an edited origin list would not have taken effect
until a restart — which would have made the new field quietly lie. Move
the lookup into a per-request originAllowed helper reading under the
existing lock. Verified behaviour is unchanged: an allowed origin still
gets the headers plus Vary: Origin, an unknown origin gets none, and
preflight still returns 204.

PUT rejects an empty origin list rather than silently keeping the old
one, since an empty list would lock out every browser client.

The authenticated round trip (loading and saving real settings) is not
verified here — it needs a superadmin login.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
tajniak81
2026-07-17 12:09:52 +02:00
co-authored by Claude Opus 4.8
parent 21c99ad762
commit 98acd7d121
8 changed files with 309 additions and 42 deletions
+4 -2
View File
@@ -19,10 +19,12 @@ POCKETBASE_ADMIN_EMAIL=
POCKETBASE_ADMIN_PASSWORD=
# CORS allowed origins for browser clients (comma separated, or * for any).
# Native mobile apps are not subject to CORS.
# Native mobile apps are not subject to CORS. Editable at runtime from the panel
# (Web App section), which writes the change back into this file.
CORS_ALLOW_ORIGINS=http://localhost:5173
# Web App address, probed by GET /api/status and shown on the panel.
# Web App address, probed by GET /api/status and shown on the panel. Editable at
# runtime from the panel (Web App section).
WEBAPP_URL=http://localhost:5173
# PocketBase auth collection holding app users (default: users).
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
+1 -1
View File
@@ -6,7 +6,7 @@
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta name="theme-color" content="#2563eb" />
<title>DriverVault · API Server</title>
<script type="module" crossorigin src="/assets/index-DKHgRvVM.js"></script>
<script type="module" crossorigin src="/assets/index-OENR1RVj.js"></script>
<link rel="stylesheet" crossorigin href="/assets/index-i1JZk1ZM.css">
</head>
<body>
+42 -7
View File
@@ -37,6 +37,8 @@
// # superadmin
// GET /api/admin/pb-config PUT /api/admin/pb-config
// POST /api/admin/pb-config/test
// GET /api/admin/webapp-config PUT /api/admin/webapp-config
// POST /api/admin/webapp-config/test
// GET /api/admin/plugins POST /api/admin/plugins
// GET /api/admin/plugins/{name} PUT /api/admin/plugins/{name}
// DELETE /api/admin/plugins/{name} POST /api/admin/plugins/{name}/health
@@ -157,6 +159,22 @@ func (s *Server) webAppURL() string {
return s.cfg.WebAppURL
}
// webAppSettings snapshots the Web App settings for the settings endpoints.
func (s *Server) webAppSettings() (url string, allowOrigins []string) {
s.mu.RLock()
defer s.mu.RUnlock()
return s.cfg.WebAppURL, append([]string(nil), s.cfg.AllowOrigins...)
}
// setWebAppConfig applies new Web App settings at runtime. The CORS middleware
// reads the origin list per request, so the new list is live immediately.
func (s *Server) setWebAppConfig(url string, allowOrigins []string) {
s.mu.Lock()
defer s.mu.Unlock()
s.cfg.WebAppURL = url
s.cfg.AllowOrigins = append([]string(nil), allowOrigins...)
}
// pbSettings snapshots the PocketBase connection for the settings endpoints.
func (s *Server) pbSettings() (url, adminEmail, adminPassword string) {
s.mu.RLock()
@@ -234,6 +252,12 @@ func (s *Server) Handler() http.Handler {
mux.HandleFunc("POST /api/admin/pb-config/test", s.requireSuperadminAuth(s.handleTestPBConfig))
mux.HandleFunc("PUT /api/admin/pb-config", s.requireSuperadminAuth(s.handleUpdatePBConfig))
// Web App settings — superadmin only. Where the Web App lives (probed by
// /api/status) and which browser origins CORS admits.
mux.HandleFunc("GET /api/admin/webapp-config", s.requireSuperadminAuth(s.handleGetWebAppConfig))
mux.HandleFunc("POST /api/admin/webapp-config/test", s.requireSuperadminAuth(s.handleTestWebAppConfig))
mux.HandleFunc("PUT /api/admin/webapp-config", s.requireSuperadminAuth(s.handleUpdateWebAppConfig))
// Plugins — external-service integrations, managed by a superadmin.
mux.HandleFunc("GET /api/admin/plugins", s.requireSuperadminAuth(s.handleListPlugins))
mux.HandleFunc("POST /api/admin/plugins", s.requireSuperadminAuth(s.handleRegisterPlugin))
@@ -351,18 +375,28 @@ func (s *Server) recoverer(next http.Handler) http.Handler {
})
}
func (s *Server) cors(next http.Handler) http.Handler {
allowed := map[string]bool{}
wildcard := false
// originAllowed reports whether origin may call this server, and whether it was
// the wildcard that allowed it. The allow-list is consulted per request rather
// than captured once, so editing it from the panel takes effect without a
// restart.
func (s *Server) originAllowed(origin string) (allowed, wildcard bool) {
s.mu.RLock()
defer s.mu.RUnlock()
for _, o := range s.cfg.AllowOrigins {
if o == "*" {
wildcard = true
return true, true
}
allowed[o] = true
if o == origin {
allowed = true
}
}
return allowed, false
}
func (s *Server) cors(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
origin := r.Header.Get("Origin")
if origin != "" && (wildcard || allowed[origin]) {
if origin := r.Header.Get("Origin"); origin != "" {
if allowed, wildcard := s.originAllowed(origin); allowed {
if wildcard {
w.Header().Set("Access-Control-Allow-Origin", "*")
} else {
@@ -372,6 +406,7 @@ func (s *Server) cors(next http.Handler) http.Handler {
w.Header().Set("Access-Control-Allow-Methods", "GET, POST, PATCH, DELETE, OPTIONS")
w.Header().Set("Access-Control-Allow-Headers", "Authorization, Content-Type")
}
}
if r.Method == http.MethodOptions {
w.WriteHeader(http.StatusNoContent)
return
+104 -4
View File
@@ -55,8 +55,8 @@ func probePB(ctx context.Context, url, email, password string) pbProbe {
return p
}
// normalizePBURL trims, defaults the scheme to http, and drops a trailing slash.
func normalizePBURL(u string) string {
// normalizeURL trims, defaults the scheme to http, and drops a trailing slash.
func normalizeURL(u string) string {
u = strings.TrimSpace(u)
if u == "" {
return ""
@@ -95,7 +95,7 @@ type pbConfigBody struct {
// keep-current semantics for blank fields.
func (s *Server) resolve(b pbConfigBody) (url, email, password string) {
curURL, curEmail, curPassword := s.pbSettings()
url = normalizePBURL(b.URL)
url = normalizeURL(b.URL)
if url == "" {
url = curURL
}
@@ -130,7 +130,7 @@ func (s *Server) handleUpdatePBConfig(w http.ResponseWriter, r *http.Request) {
writeError(w, http.StatusBadRequest, "invalid json")
return
}
if normalizePBURL(b.URL) == "" {
if normalizeURL(b.URL) == "" {
writeError(w, http.StatusBadRequest, "a PocketBase URL is required")
return
}
@@ -157,3 +157,103 @@ func (s *Server) handleUpdatePBConfig(w http.ResponseWriter, r *http.Request) {
"config": viewFor(r.Context(), url, email, password),
})
}
// webAppConfigView is the Web App shape returned to the panel: where the Web App
// lives (the address /api/status probes) and which browser origins CORS lets
// call this server.
type webAppConfigView struct {
URL string `json:"url"`
AllowOrigins []string `json:"allowOrigins"`
Probe svcHealth `json:"probe"`
}
// webAppViewFor builds the panel's Web App view, including a live probe.
func webAppViewFor(ctx context.Context, url string, origins []string) webAppConfigView {
return webAppConfigView{
URL: url,
AllowOrigins: origins,
Probe: probe(ctx, url+"/healthz"),
}
}
// GET /api/admin/webapp-config — current Web App settings + a live probe.
func (s *Server) handleGetWebAppConfig(w http.ResponseWriter, r *http.Request) {
url, origins := s.webAppSettings()
writeJSON(w, http.StatusOK, webAppViewFor(r.Context(), url, origins))
}
// webAppConfigBody is the editable Web App payload. A blank url means "keep the
// current one"; allowOrigins is taken as sent (it is a complete list, not a
// patch), so it may only be omitted, never emptied.
type webAppConfigBody struct {
URL string `json:"url"`
AllowOrigins []string `json:"allowOrigins"`
}
// POST /api/admin/webapp-config/test — probe a candidate Web App address WITHOUT
// applying it. CORS origins are not probeable, so this only checks the URL.
func (s *Server) handleTestWebAppConfig(w http.ResponseWriter, r *http.Request) {
var b webAppConfigBody
if err := json.NewDecoder(r.Body).Decode(&b); err != nil {
writeError(w, http.StatusBadRequest, "invalid json")
return
}
url := normalizeURL(b.URL)
if url == "" {
url, _ = s.webAppSettings()
}
writeJSON(w, http.StatusOK, probe(r.Context(), url+"/healthz"))
}
// PUT /api/admin/webapp-config — apply new Web App settings at runtime and
// persist them to .env. The CORS middleware re-reads the origin list on every
// request, so a change here takes effect without a restart.
func (s *Server) handleUpdateWebAppConfig(w http.ResponseWriter, r *http.Request) {
var b webAppConfigBody
if err := json.NewDecoder(r.Body).Decode(&b); err != nil {
writeError(w, http.StatusBadRequest, "invalid json")
return
}
url := normalizeURL(b.URL)
if url == "" {
writeError(w, http.StatusBadRequest, "a Web App URL is required")
return
}
origins := cleanOrigins(b.AllowOrigins)
if len(origins) == 0 {
writeError(w, http.StatusBadRequest, "at least one allowed origin is required (use * for any)")
return
}
// Apply at runtime, then persist so the change survives a restart.
s.setWebAppConfig(url, origins)
if err := config.UpdateEnvFile(config.EnvFile, map[string]string{
"WEBAPP_URL": url,
"CORS_ALLOW_ORIGINS": strings.Join(origins, ","),
}); err != nil {
// The runtime change already took effect; report that persistence failed.
log.Printf("webapp-config: persist to %s failed: %v", config.EnvFile, err)
writeJSON(w, http.StatusOK, map[string]any{
"config": webAppViewFor(r.Context(), url, origins),
"warning": "applied for this session, but could not be saved to .env: " + err.Error(),
})
return
}
log.Printf("webapp-config: Web App updated to %s, origins %s (by superadmin)", url, strings.Join(origins, ","))
writeJSON(w, http.StatusOK, map[string]any{
"config": webAppViewFor(r.Context(), url, origins),
})
}
// cleanOrigins trims each origin and drops the blanks, so a trailing comma or a
// stray space in the panel's text field can't register an unmatchable origin.
func cleanOrigins(in []string) []string {
out := make([]string, 0, len(in))
for _, o := range in {
if o = strings.TrimSpace(o); o != "" {
out = append(out, o)
}
}
return out
}
+13 -4
View File
@@ -5,6 +5,7 @@ import { me, token, restore, logout, isManager, isSuperadmin } from "./api";
import LoginView from "./components/LoginView.vue";
import StatusCard from "./components/StatusCard.vue";
import PocketBaseCard from "./components/PocketBaseCard.vue";
import WebAppCard from "./components/WebAppCard.vue";
import PluginsCard from "./components/PluginsCard.vue";
import UsersCard from "./components/UsersCard.vue";
import OrgsCard from "./components/OrgsCard.vue";
@@ -18,16 +19,20 @@ onMounted(async () => {
booting.value = false;
});
// Cards are gated by role: management needs a manager, PocketBase + plugins need
// a superadmin. The server enforces the same rules — this only hides what the
// caller could not use anyway.
// Cards are gated by role: management needs a manager, PocketBase, Web App +
// plugins need a superadmin. The server enforces the same rules — this only
// hides what the caller could not use anyway.
const sections = computed(() => {
const out = [{ id: "overview", label: "Overview" }];
if (isManager.value) {
out.push({ id: "users", label: "Users" }, { id: "orgs", label: "Organizations" });
}
if (isSuperadmin.value) {
out.push({ id: "pocketbase", label: "PocketBase" }, { id: "plugins", label: "Plugins" });
out.push(
{ id: "pocketbase", label: "PocketBase" },
{ id: "webapp", label: "Web App" },
{ id: "plugins", label: "Plugins" },
);
}
out.push({ id: "api", label: "API" });
return out;
@@ -118,6 +123,9 @@ const superadminApi = [
{ method: "GET", path: "/api/admin/pb-config", desc: "PocketBase connection + live probe" },
{ method: "POST", path: "/api/admin/pb-config/test", desc: "Probe a candidate connection" },
{ method: "PUT", path: "/api/admin/pb-config", desc: "Apply + persist a connection" },
{ method: "GET", path: "/api/admin/webapp-config", desc: "Web App URL + CORS origins, with a live probe" },
{ method: "POST", path: "/api/admin/webapp-config/test", desc: "Probe a candidate Web App address" },
{ method: "PUT", path: "/api/admin/webapp-config", desc: "Apply + persist Web App settings" },
{ method: "GET", path: "/api/admin/plugins", desc: "List plugins (secrets masked)" },
{ method: "POST", path: "/api/admin/plugins", desc: "Register an external plugin" },
{ method: "GET", path: "/api/admin/plugins/{name}", desc: "Fetch one plugin" },
@@ -207,6 +215,7 @@ const superadminApi = [
<UsersCard v-else-if="section === 'users'" />
<OrgsCard v-else-if="section === 'orgs'" />
<PocketBaseCard v-else-if="section === 'pocketbase'" />
<WebAppCard v-else-if="section === 'webapp'" />
<PluginsCard v-else-if="section === 'plugins'" />
<template v-else-if="section === 'api'">
@@ -0,0 +1,121 @@
<script setup>
import { ref, onMounted } from "vue";
import { request } from "../api";
// Superadmin-only: where the Web App lives (the address /api/status probes) and
// which browser origins CORS admits. Like the PocketBase card, the change is
// applied at runtime AND persisted to the server's .env, so it survives a
// restart. Origins are edited as a comma-separated list.
const cfg = ref(null);
const form = ref({ url: "", origins: "" });
const probe = ref(null);
const error = ref("");
const notice = ref("");
const busy = ref(false);
// The panel sends the origin list as an array; the field edits it as CSV.
const splitOrigins = (s) => s.split(",").map((o) => o.trim()).filter(Boolean);
function apply(view) {
cfg.value = view;
form.value = { url: view.url, origins: (view.allowOrigins || []).join(", ") };
probe.value = view.probe;
}
async function load() {
try {
apply(await request("/api/admin/webapp-config"));
} catch (e) {
error.value = e.message;
}
}
onMounted(load);
async function test() {
error.value = "";
notice.value = "";
busy.value = true;
try {
probe.value = await request("/api/admin/webapp-config/test", {
method: "POST",
body: { url: form.value.url },
});
notice.value =
probe.value.status === "ok"
? "Web App is reachable."
: "Web App did not answer its health check at that address.";
} catch (e) {
error.value = e.message;
} finally {
busy.value = false;
}
}
async function save() {
error.value = "";
notice.value = "";
busy.value = true;
try {
const out = await request("/api/admin/webapp-config", {
method: "PUT",
body: { url: form.value.url, allowOrigins: splitOrigins(form.value.origins) },
});
apply(out.config);
notice.value = out.warning || "Saved. New origins apply to the next request.";
} catch (e) {
error.value = e.message;
} finally {
busy.value = false;
}
}
</script>
<template>
<div class="dh-card overflow-hidden">
<div class="flex items-center justify-between border-b border-subtle px-5 py-4">
<div>
<div class="text-base font-bold tracking-[-0.02em] text-strong">Web App</div>
<p class="mt-0.5 text-xs text-muted">Address probed by the status check, and who may call this API from a browser</p>
</div>
<span
v-if="probe"
class="dh-pill"
:class="probe.status === 'ok' ? 'bg-success-soft text-success' : 'bg-danger-soft text-danger'"
>
<span class="h-1.5 w-1.5 rounded-full bg-current"></span>
{{ probe.status === "ok" ? "reachable" : "unreachable" }}
</span>
</div>
<div class="flex flex-col gap-4 px-5 py-4">
<div>
<label class="dh-label" for="web-url">Base URL</label>
<input id="web-url" v-model="form.url" class="dh-input" placeholder="http://localhost:5173" />
</div>
<div>
<label class="dh-label" for="web-origins">Allowed origins</label>
<input
id="web-origins"
v-model="form.origins"
class="dh-input"
placeholder="http://localhost:5173, https://app.example.com"
/>
<p class="mt-1 text-xs text-muted">
Comma separated, or <span class="data">*</span> for any. Native mobile apps are not subject to CORS.
</p>
</div>
<p v-if="probe?.error" class="data text-xs text-muted">{{ probe.error }}</p>
<p v-if="notice" class="rounded-control bg-info-soft px-3 py-2 text-xs text-info">{{ notice }}</p>
<p v-if="error" class="rounded-control bg-danger-soft px-3 py-2 text-xs text-danger">{{ error }}</p>
<div class="flex items-center gap-2">
<button class="dh-btn" :disabled="busy" @click="save">Save &amp; apply</button>
<button class="dh-btn-ghost" :disabled="busy" @click="test">Test connection</button>
<span class="flex-1"></span>
<span class="eyebrow">persisted to .env</span>
</div>
</div>
</div>
</template>