Rebuild API Server on the PilotVault structure
Mirror PilotVault's API Server layout and add the superadmin console,
plugin system, runtime PocketBase settings, and user/organization
management. The car domain (cars, service records, parts, sharing) is
carried over unchanged apart from the auth switch.
Layout: main.go -> cmd/server/main.go; module carcontrol/api ->
drivervault/apiserver. internal/api is split by concern (auth, users,
orgs, settings, plugins, status, health, respond).
Auth: replace the server-minted HS256 JWT and the sessions collection
with a PocketBase token proxy. /api/auth/login relays PocketBase's
{token, record}, and every protected request re-resolves that token
against PocketBase, so a role change or deletion takes effect at once
instead of waiting out a token. AUTH_SECRET is obsolete and internal/auth
is gone. Per-device session listing/revocation goes with it: PocketBase
tokens are stateless. Changing a password rotates the user's token key,
which invalidates every token already issued.
Roles: add superadmin alongside user/admin, plus an organizations
collection and users.organization. Admins are scoped to their own
organization; superadmins span all of them. Guards prevent changing your
own role, deleting your own account, an admin touching a superadmin, and
deleting an organization that still has members.
Plugins: new internal/plugins package with one contract over two kinds --
builtin (compiled in) and external (any HTTP service, registered at
runtime with no rebuild). State persists to plugins.json; secrets are
masked on read and preserved when saved back at the mask.
PocketBase settings: /api/admin/pb-config applies a new connection at
runtime and persists it to .env. It deliberately does not require a
working service account, so a wrong or unreachable connection can still
be fixed from the panel.
Panel: rebuilt as the superadmin console -- login gate, status, users,
organizations, PocketBase, plugins, and the endpoint reference.
Clients: update the Web App and Phone App for the PocketBase token shape,
the move of user management to /api/users ({users}/{user} envelopes, with
password resets folded into PATCH), and the removal of sessions. Both now
mirror the server's real guards rather than the old last-admin rule, and
parse PocketBase's field-level error shape.
Config: modern POCKETBASE_*/API_ADDR names with legacy PB_*/PORT
fallbacks, so existing .env files keep working. Also fixes /api/status
probing the Web App on 8090 instead of DriverVault's 5173.
Run scripts/setup-pocketbase.mjs to add the organizations collection and
grow users.role; every client must log in once more.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Opus 4.8
parent
7d55f0a4cd
commit
ae6ed4ac1e
@@ -1,65 +1,147 @@
|
||||
// Package config loads server configuration from environment variables,
|
||||
// optionally seeded from a .env file in the working directory.
|
||||
// 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 (
|
||||
"bufio"
|
||||
"fmt"
|
||||
"os"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// Config holds all runtime configuration for the API Server.
|
||||
type Config struct {
|
||||
Port string
|
||||
PBURL string
|
||||
PBAdminEmail string
|
||||
PBAdminPasswd string
|
||||
CORSOrigins []string
|
||||
AuthSecret string
|
||||
Addr string
|
||||
PocketBaseURL string
|
||||
WebAppURL string
|
||||
AllowOrigins []string
|
||||
|
||||
// UsersCollection is the PocketBase auth collection holding app users.
|
||||
UsersCollection string
|
||||
|
||||
// PluginsFile is the local JSON store for plugin enable-state + config.
|
||||
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
|
||||
}
|
||||
|
||||
// devAuthSecret is used only when AUTH_SECRET is unset, so the server still
|
||||
// runs out-of-the-box in development. Set AUTH_SECRET in production.
|
||||
const devAuthSecret = "dev-insecure-secret-change-me"
|
||||
// EnvFile is the .env path (relative to the working directory) that Load reads
|
||||
// and that runtime settings changes persist back into.
|
||||
const EnvFile = ".env"
|
||||
|
||||
// Load reads .env (if present) into the process environment, then builds a
|
||||
// Config from environment variables. Required values that are missing produce
|
||||
// an error so the server fails fast instead of misbehaving later.
|
||||
func Load() (*Config, error) {
|
||||
loadDotEnv(".env")
|
||||
// AdminConfigured reports whether a service account has been supplied.
|
||||
func (c Config) AdminConfigured() bool {
|
||||
return c.PocketBaseAdminEmail != "" && c.PocketBaseAdminPassword != ""
|
||||
}
|
||||
|
||||
cfg := &Config{
|
||||
Port: getenv("PORT", "8080"),
|
||||
PBURL: strings.TrimRight(getenv("PB_URL", "http://10.2.1.10:8027"), "/"),
|
||||
PBAdminEmail: os.Getenv("PB_ADMIN_EMAIL"),
|
||||
PBAdminPasswd: os.Getenv("PB_ADMIN_PASSWORD"),
|
||||
CORSOrigins: splitCSV(getenv("CORS_ORIGINS", "http://localhost:5173")),
|
||||
AuthSecret: getenv("AUTH_SECRET", devAuthSecret),
|
||||
UsersCollection: getenv("AUTH_USERS_COLLECTION", "users"),
|
||||
// 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:5173"), "/"),
|
||||
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"),
|
||||
}
|
||||
}
|
||||
|
||||
// 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
|
||||
}
|
||||
|
||||
if cfg.PBAdminEmail == "" || cfg.PBAdminPasswd == "" {
|
||||
return nil, fmt.Errorf("PB_ADMIN_EMAIL and PB_ADMIN_PASSWORD are required")
|
||||
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)
|
||||
}
|
||||
return cfg, nil
|
||||
// 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)
|
||||
}
|
||||
|
||||
// UsingDevAuthSecret reports whether the insecure development secret is in use.
|
||||
func (c *Config) UsingDevAuthSecret() bool {
|
||||
return c.AuthSecret == devAuthSecret
|
||||
}
|
||||
|
||||
func getenv(key, fallback string) string {
|
||||
func getenv(key, def string) string {
|
||||
if v := os.Getenv(key); v != "" {
|
||||
return v
|
||||
}
|
||||
return fallback
|
||||
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 {
|
||||
var out []string
|
||||
for _, p := range strings.Split(s, ",") {
|
||||
parts := strings.Split(s, ",")
|
||||
out := make([]string, 0, len(parts))
|
||||
for _, p := range parts {
|
||||
if p = strings.TrimSpace(p); p != "" {
|
||||
out = append(out, p)
|
||||
}
|
||||
@@ -67,18 +149,16 @@ func splitCSV(s string) []string {
|
||||
return out
|
||||
}
|
||||
|
||||
// loadDotEnv parses a simple KEY=VALUE file and sets any variables that are not
|
||||
// already present in the environment. Lines starting with # are comments.
|
||||
// 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) {
|
||||
f, err := os.Open(path)
|
||||
data, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
return // .env is optional
|
||||
}
|
||||
defer f.Close()
|
||||
|
||||
sc := bufio.NewScanner(f)
|
||||
for sc.Scan() {
|
||||
line := strings.TrimSpace(sc.Text())
|
||||
for _, line := range strings.Split(string(data), "\n") {
|
||||
line = strings.TrimSpace(line)
|
||||
if line == "" || strings.HasPrefix(line, "#") {
|
||||
continue
|
||||
}
|
||||
@@ -89,7 +169,7 @@ func loadDotEnv(path string) {
|
||||
key = strings.TrimSpace(key)
|
||||
val = strings.Trim(strings.TrimSpace(val), `"'`)
|
||||
if _, exists := os.LookupEnv(key); !exists {
|
||||
os.Setenv(key, val)
|
||||
_ = os.Setenv(key, val)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user