The integration cascade stored its top layer differently from the two below it: org (L2) and user (L3) plugin config lived in PocketBase, in a pluginSettings field, while the global (L1) layer sat in a plugins.json next to the binary. That split was accretion rather than design - the file was the whole store in the v1 MVP, and the per-tenant layers were later built on PocketBase and layered on top of it instead of replacing it. It also cost something real. plugins.json was a second state store with different durability from pb_data: its own volume, its own ownership, its own backup. Losing pb_data is unmissable; losing api_data was silent, which is how "every plugin comes back disabled after a redeploy" happened. L1 now lives in the app_settings collection - one record keyed "global", holding its settings in a pluginSettings field, the same mechanism and the same field name the layers below use. The documents still differ in shape, because only L1 carries enable state and the registration of external plugins, but the storage is no longer a special case. The Manager grows a Store seam (PocketBase in production, file for the import, memory for tests) and, more importantly, a loaded gate. Settings in a database mean the store can be unreachable at boot - a cold stack, or a service account still to be set from the panel. That must not read as "no plugins configured", or the first save would write emptiness over real settings. So until a read succeeds the Manager stays unloaded, every mutation is refused, /api/admin/plugins* answers 503, and a background retry backs off to two minutes. The same gate covers a document that will not parse: it is never replaced by one built from an empty map, which is a stronger guarantee than the .corrupt backup it replaces. Writing to a store also revealed a hole in the previous fix. Classifying a save failure as errPersist was left to each Store, and a store that returned a plain error would fall through to the "saved, but the plugin failed to start" branch and be reported as a 200 - the same silent-success bug through a different door. The Manager now classifies, whatever the Store returns; a test pins it. Upgrades are automatic: on the first boot that finds no settings in the database, an existing plugins.json is imported and renamed to plugins.json.migrated. The import is refused if the store is merely unreachable, or if the file does not parse, so a stale or broken file can never overwrite live settings. /data is still needed - the panel rewrites .env there when it retargets PocketBase - but plugin settings no longer depend on it. 21 tests in internal/plugins cover both stores, including the production path against a fake PocketBase: create-then-update of the singleton, round-trip across a restart, an outage that leaves settings intact, a missing collection reading as not-ready rather than empty, and the import running exactly once. go build, go vet and go test ./... pass. Schema changes are mirrored into scripts/setup-pocketbase.mjs as that file requires. Not verified: no Docker CLI here, so no image was built and the bootstrap of app_settings against a real PocketBase is untested outside the fake. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
220 lines
7.3 KiB
Go
220 lines
7.3 KiB
Go
// Package config loads server configuration from environment variables,
|
|
// optionally seeded from a .env file in the working directory. The PocketBase
|
|
// connection is also editable at runtime from the panel, which persists the
|
|
// change back into the same .env via UpdateEnvFile.
|
|
package config
|
|
|
|
import (
|
|
"os"
|
|
"strings"
|
|
)
|
|
|
|
// Config holds all runtime configuration for the API Server.
|
|
type Config struct {
|
|
Addr string
|
|
PocketBaseURL string
|
|
WebAppURL string
|
|
AllowOrigins []string
|
|
|
|
// UsersCollection is the PocketBase auth collection holding app users.
|
|
UsersCollection string
|
|
|
|
// PluginsFile is the pre-PocketBase JSON store for the global plugin layer.
|
|
// Those settings now live in the database (the app_settings singleton), so
|
|
// this path is read once — to import an existing file on the first boot
|
|
// after the upgrade — and renamed to *.migrated afterwards.
|
|
PluginsFile string
|
|
|
|
// Superuser service account. Every privileged flow (user/organization
|
|
// management, all car-domain database access) runs through it. Optional at
|
|
// startup: when unset those endpoints return 503 and a superadmin can still
|
|
// log in to the panel to configure it.
|
|
PocketBaseAdminEmail string
|
|
PocketBaseAdminPassword string
|
|
|
|
// OCPP control endpoint (Anker Solix charger control). OCPPRequireTLS rejects
|
|
// charger connections that did not arrive over TLS (a plaintext ws:// carries
|
|
// the charger's Basic-auth token in the clear); disable only for local dev.
|
|
// OCPPPublicURL, when set, is the canonical ws(s):// base an operator points
|
|
// the charger at, instead of deriving it from request headers.
|
|
OCPPRequireTLS bool
|
|
OCPPPublicURL string
|
|
|
|
// Bootstrap controls the on-startup PocketBase schema setup: when true (the
|
|
// default) the server creates any missing collections and reconciles existing
|
|
// ones against the desired schema, then ensures the super-admin below exists.
|
|
// It requires a configured service account; without one it is a no-op.
|
|
Bootstrap bool
|
|
|
|
// Super-admin account created during bootstrap when both fields are set and no
|
|
// user with that email exists yet. Existing accounts are left untouched.
|
|
SuperAdminEmail string
|
|
SuperAdminPassword string
|
|
SuperAdminName string
|
|
}
|
|
|
|
// EnvFile is the .env path (relative to the working directory) that Load reads
|
|
// and that runtime settings changes persist back into.
|
|
const EnvFile = ".env"
|
|
|
|
// AdminConfigured reports whether a service account has been supplied.
|
|
func (c Config) AdminConfigured() bool {
|
|
return c.PocketBaseAdminEmail != "" && c.PocketBaseAdminPassword != ""
|
|
}
|
|
|
|
// Load reads configuration from environment variables, applying sensible
|
|
// defaults. A .env file, if present in the working directory, is loaded first.
|
|
func Load() Config {
|
|
loadDotEnv(EnvFile)
|
|
|
|
return Config{
|
|
Addr: normalizeAddr(firstEnv("API_ADDR", "PORT"), ":8080"),
|
|
PocketBaseURL: strings.TrimRight(firstEnvOr("http://10.2.1.10:8027", "POCKETBASE_URL", "PB_URL"), "/"),
|
|
WebAppURL: strings.TrimRight(getenv("WEBAPP_URL", "http://localhost:8090"), "/"),
|
|
AllowOrigins: splitCSV(firstEnvOr("*", "CORS_ALLOW_ORIGINS", "CORS_ORIGINS")),
|
|
UsersCollection: getenv("AUTH_USERS_COLLECTION", "users"),
|
|
PluginsFile: getenv("PLUGINS_FILE", "plugins.json"),
|
|
PocketBaseAdminEmail: firstEnv("POCKETBASE_ADMIN_EMAIL", "PB_ADMIN_EMAIL"),
|
|
PocketBaseAdminPassword: firstEnv("POCKETBASE_ADMIN_PASSWORD", "PB_ADMIN_PASSWORD"),
|
|
OCPPRequireTLS: boolEnv("OCPP_REQUIRE_TLS", true),
|
|
OCPPPublicURL: strings.TrimRight(getenv("OCPP_PUBLIC_URL", ""), "/"),
|
|
Bootstrap: boolEnv("PB_BOOTSTRAP", true),
|
|
SuperAdminEmail: firstEnv("DRIVERVAULT_SUPERADMIN_EMAIL", "SUPERADMIN_EMAIL"),
|
|
SuperAdminPassword: firstEnv("DRIVERVAULT_SUPERADMIN_PASSWORD", "SUPERADMIN_PASSWORD"),
|
|
SuperAdminName: getenv("DRIVERVAULT_SUPERADMIN_NAME", "Administrator"),
|
|
}
|
|
}
|
|
|
|
// boolEnv reads a boolean environment variable, accepting the common truthy and
|
|
// falsey spellings and falling back to def when unset or unrecognized.
|
|
func boolEnv(key string, def bool) bool {
|
|
switch strings.ToLower(strings.TrimSpace(os.Getenv(key))) {
|
|
case "":
|
|
return def
|
|
case "1", "true", "yes", "on":
|
|
return true
|
|
case "0", "false", "no", "off":
|
|
return false
|
|
default:
|
|
return def
|
|
}
|
|
}
|
|
|
|
// normalizeAddr accepts either a full listen address (":8080") or a bare port
|
|
// ("8080", which is what the legacy PORT variable held) and returns a listen
|
|
// address.
|
|
func normalizeAddr(v, def string) string {
|
|
if v == "" {
|
|
return def
|
|
}
|
|
if strings.Contains(v, ":") {
|
|
return v
|
|
}
|
|
return ":" + v
|
|
}
|
|
|
|
// UpdateEnvFile persists the given KEY=VALUE pairs into the .env file at path,
|
|
// replacing existing keys in place and appending new ones, while preserving all
|
|
// other lines (comments, ordering, unrelated keys). The file is created if it
|
|
// does not exist. Written with 0600 perms since it holds secrets.
|
|
func UpdateEnvFile(path string, updates map[string]string) error {
|
|
existing, _ := os.ReadFile(path) // missing file → start empty
|
|
|
|
remaining := make(map[string]string, len(updates))
|
|
for k, v := range updates {
|
|
remaining[k] = v
|
|
}
|
|
|
|
var out []string
|
|
for _, line := range strings.Split(string(existing), "\n") {
|
|
trimmed := strings.TrimSpace(line)
|
|
if trimmed == "" || strings.HasPrefix(trimmed, "#") {
|
|
out = append(out, line)
|
|
continue
|
|
}
|
|
key, _, ok := strings.Cut(trimmed, "=")
|
|
key = strings.TrimSpace(key)
|
|
if ok {
|
|
if v, found := remaining[key]; found {
|
|
out = append(out, key+"="+v)
|
|
delete(remaining, key)
|
|
continue
|
|
}
|
|
}
|
|
out = append(out, line)
|
|
}
|
|
// Append any keys that weren't already present.
|
|
for k, v := range remaining {
|
|
out = append(out, k+"="+v)
|
|
}
|
|
|
|
content := strings.Join(out, "\n")
|
|
if !strings.HasSuffix(content, "\n") {
|
|
content += "\n"
|
|
}
|
|
return os.WriteFile(path, []byte(content), 0o600)
|
|
}
|
|
|
|
func getenv(key, def string) string {
|
|
if v := os.Getenv(key); v != "" {
|
|
return v
|
|
}
|
|
return def
|
|
}
|
|
|
|
// firstEnv returns the first of keys that is set to a non-empty value. It lets
|
|
// the modern POCKETBASE_* names take precedence while the legacy PB_* names from
|
|
// older deployments keep working.
|
|
func firstEnv(keys ...string) string {
|
|
for _, k := range keys {
|
|
if v := os.Getenv(k); v != "" {
|
|
return v
|
|
}
|
|
}
|
|
return ""
|
|
}
|
|
|
|
// firstEnvOr is firstEnv with a fallback when none of the keys are set.
|
|
func firstEnvOr(def string, keys ...string) string {
|
|
if v := firstEnv(keys...); v != "" {
|
|
return v
|
|
}
|
|
return def
|
|
}
|
|
|
|
func splitCSV(s string) []string {
|
|
parts := strings.Split(s, ",")
|
|
out := make([]string, 0, len(parts))
|
|
for _, p := range parts {
|
|
if p = strings.TrimSpace(p); p != "" {
|
|
out = append(out, p)
|
|
}
|
|
}
|
|
return out
|
|
}
|
|
|
|
// loadDotEnv loads KEY=VALUE pairs from a .env file into the process env if they
|
|
// are not already set. It is intentionally minimal (no quoting rules beyond
|
|
// trimming surrounding quotes).
|
|
func loadDotEnv(path string) {
|
|
data, err := os.ReadFile(path)
|
|
if err != nil {
|
|
return // .env is optional
|
|
}
|
|
for _, line := range strings.Split(string(data), "\n") {
|
|
line = strings.TrimSpace(line)
|
|
if line == "" || strings.HasPrefix(line, "#") {
|
|
continue
|
|
}
|
|
key, val, ok := strings.Cut(line, "=")
|
|
if !ok {
|
|
continue
|
|
}
|
|
key = strings.TrimSpace(key)
|
|
val = strings.Trim(strings.TrimSpace(val), `"'`)
|
|
if _, exists := os.LookupEnv(key); !exists {
|
|
_ = os.Setenv(key, val)
|
|
}
|
|
}
|
|
}
|