Compare commits

..
5 Commits
Author SHA1 Message Date
Gabriel20xx b412ca0f69 Adopt shared authproxy helpers for the AuthGuard-proxy auth service
Lint / Lint (push) Successful in 20s
Tests / Go backend (push) Successful in 1m1s
Docker / Docker Build & Push (push) Successful in 2m37s
Tests / Dashboard checks (push) Successful in 37s
Replaces locally-duplicated session-cookie handling, input
normalization, and AuthGuard-error translation with
shared/backend/authproxy, shared with Bitmagnet/GameStream/media-backend
and others doing the same AuthGuard-proxy pattern.
2026-09-03 08:24:06 +02:00
Gabriel20xx 68f6dd5a87 Sync shared snapshot from 7b5a4e6 2026-09-03 00:16:55 +02:00
Gabriel20xx 695ff742d6 Sync shared snapshot from 7b5a4e6 2026-09-03 00:15:58 +02:00
Gabriel20xx d3fff0a495 Sync shared snapshot from 9589d07 2026-09-02 21:45:45 +02:00
Gabriel20xx 49e3c7d561 Sync shared snapshot from de9b599 2026-09-02 20:50:21 +02:00
63 changed files with 2620 additions and 1341 deletions

No files matched your search

+12 -27
View File
@@ -13,6 +13,7 @@ import (
sharedauth "repos.gfranz.ch/Gabriel20xx/shared/backend/auth"
authclient "repos.gfranz.ch/Gabriel20xx/shared/backend/authclient"
"repos.gfranz.ch/Gabriel20xx/shared/backend/authproxy"
)
// AuthGuard migration
@@ -221,27 +222,23 @@ func newAuthService(authGuard *authclient.Client, db *DB, secureCookie bool) *Au
}
func normalizeUsername(value string) (string, error) {
value = strings.TrimSpace(value)
if value == "" || len([]rune(value)) > maxUsernameLength {
normalized, ok := authproxy.NormalizeUsername(value, maxUsernameLength)
if !ok {
return "", errUsernameRequired
}
return value, nil
return normalized, nil
}
func normalizeEmail(value string) (string, error) {
value = strings.ToLower(strings.TrimSpace(value))
if value == "" || len([]rune(value)) > maxEmailLength || strings.Count(value, "@") != 1 {
normalized, ok := authproxy.NormalizeEmail(value, maxEmailLength)
if !ok {
return "", errEmailRequired
}
parts := strings.SplitN(value, "@", 2)
if parts[0] == "" || parts[1] == "" || !strings.Contains(parts[1], ".") {
return "", errEmailRequired
}
return value, nil
return normalized, nil
}
func validatePassword(value string) error {
if len([]rune(value)) < minPasswordLength {
if !authproxy.ValidPassword(value, minPasswordLength) {
return errPasswordTooShort
}
return nil
@@ -269,25 +266,14 @@ func (a *AuthService) enabled() bool {
// sessionToken reads the AuthGuard session cookie off the incoming request.
// See the top-of-file doc comment's "Session cookie / token model" section.
func (a *AuthService) sessionToken(r *http.Request) string {
cookie, err := r.Cookie(authclient.DefaultCookieName)
if err != nil || cookie.Value == "" {
return ""
}
return cookie.Value
return authproxy.SessionToken(r)
}
// clearSessionCookies clears both the AuthGuard cookie (as a fallback --
// normally AuthGuard's own Set-Cookie, forwarded via authclient.ForwardCookies,
// already does this) and the pre-migration CollabTable cookie name.
func (a *AuthService) clearSessionCookies(w http.ResponseWriter) {
http.SetCookie(w, &http.Cookie{
Name: authclient.DefaultCookieName, Value: "", Path: "/", HttpOnly: true,
Secure: a.secureCookie, SameSite: http.SameSiteLaxMode, MaxAge: -1,
})
http.SetCookie(w, &http.Cookie{
Name: legacySessionCookieName, Value: "", Path: "/", HttpOnly: true,
Secure: a.secureCookie, SameSite: http.SameSiteLaxMode, MaxAge: -1,
})
authproxy.ClearSessionCookies(w, legacySessionCookieName, a.secureCookie)
}
// currentUser resolves the request's AuthGuard session cookie via the
@@ -943,9 +929,8 @@ func (a *AuthService) managedUserView(ctx context.Context, user authclient.Manag
// failure actually reaching AuthGuard) falls back to a generic 500 with
// fallbackMessage.
func writeAuthGuardError(w http.ResponseWriter, err error, fallbackMessage string) {
var apiErr *authclient.APIError
if errors.As(err, &apiErr) {
writeJSONError(w, apiErr.StatusCode, apiErr.Message)
if statusCode, message, ok := authproxy.APIErrorResponse(err); ok {
writeJSONError(w, statusCode, message)
return
}
writeJSONError(w, http.StatusInternalServerError, fallbackMessage)
+18 -2
View File
@@ -75,10 +75,14 @@ func WithCookieName(name string) Option {
return func(c *Client) { c.cookieName = name }
}
// New creates a Client for the AuthServer instance at baseURL.
// New creates a Client for the AuthServer instance at baseURL. baseURL may
// be given without a scheme (e.g. "auth.example.com" or "192.168.1.50:8080")
// - "https://" is assumed in that case, so a deployment only needs to name
// the host, not repeat the scheme; an explicit "http://" (for a plain-HTTP
// local/LAN AuthServer) is left as-is.
func New(baseURL string, opts ...Option) *Client {
c := &Client{
baseURL: strings.TrimRight(strings.TrimSpace(baseURL), "/"),
baseURL: normalizeBaseURL(baseURL),
httpClient: &http.Client{Timeout: 5 * time.Second},
cookieName: DefaultCookieName,
}
@@ -88,6 +92,18 @@ func New(baseURL string, opts ...Option) *Client {
return c
}
func normalizeBaseURL(baseURL string) string {
trimmed := strings.TrimRight(strings.TrimSpace(baseURL), "/")
if trimmed == "" {
return trimmed
}
lower := strings.ToLower(trimmed)
if strings.HasPrefix(lower, "http://") || strings.HasPrefix(lower, "https://") {
return trimmed
}
return "https://" + trimmed
}
// Validate calls AuthServer's GET /api/session/validate with token as a
// Bearer credential and returns the resolved user. It returns
// ErrInvalidSession (wrapped) when AuthServer reports the session as not
+26
View File
@@ -8,6 +8,32 @@ import (
"testing"
)
func TestNewNormalizesBaseURL(t *testing.T) {
cases := []struct {
name string
input string
want string
}{
{name: "bare host gets https", input: "auth.example.com", want: "https://auth.example.com"},
{name: "bare host:port gets https", input: "192.168.1.50:8080", want: "https://192.168.1.50:8080"},
{name: "explicit http is left alone", input: "http://auth.example.com", want: "http://auth.example.com"},
{name: "explicit https is left alone", input: "https://auth.example.com", want: "https://auth.example.com"},
{name: "scheme match is case-insensitive", input: "HTTP://auth.example.com", want: "HTTP://auth.example.com"},
{name: "trailing slash stripped before scheme check", input: "auth.example.com/", want: "https://auth.example.com"},
{name: "surrounding whitespace trimmed", input: " auth.example.com ", want: "https://auth.example.com"},
{name: "empty stays empty", input: "", want: ""},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
client := New(tc.input)
if got := client.baseURL; got != tc.want {
t.Fatalf("New(%q).baseURL = %q, want %q", tc.input, got, tc.want)
}
})
}
}
func TestSetupStatus(t *testing.T) {
cases := []struct {
name string
+135
View File
@@ -0,0 +1,135 @@
// Package authproxy holds small helpers shared by every Go service in this
// workspace that proxies its own /auth/... (or /api/auth/...) HTTP surface
// to a centralized AuthGuard instance via shared/backend/authclient, instead
// of embedding its own local user table.
//
// Three services independently reimplemented the same handful of pieces
// below before this package existed (Forks/Bitmagnet/backend/internal/auth/service.go,
// Original/GameStream/backend/cmd/gamestreamd/auth.go,
// Central/shared/media-backend/internal/auth/auth.go — read any one of
// their top-of-file doc comments for the fuller AuthGuard-migration
// rationale: session cookie forwarding, the local one-time setup-claim
// flag, "auth disabled" mode, etc.). Those pieces stay project-specific
// (they depend on each project's own storage/framework/response shape) —
// only the pieces below were duplicated near-verbatim everywhere:
//
// - SessionToken / ClearSessionCookies: reading and clearing AuthGuard's
// own session cookie is identical logic in every caller, since none of
// them mint a session token of their own anymore.
// - NormalizeUsername / NormalizeEmail / ValidPassword: the same
// trim+shape checks, just with different max/min lengths and (kept
// deliberately un-touched by this package) different caller-owned
// error messages — see each function's doc comment for why this
// package returns a plain (value, bool) rather than an error.
// - APIErrorResponse: unwrapping an authclient.APIError into the
// (status code, message) pair every caller's own writeError-equivalent
// forwards close to verbatim.
package authproxy
import (
"errors"
"net/http"
"strings"
"unicode/utf8"
authclient "repos.gfranz.ch/Gabriel20xx/shared/backend/authclient"
)
// CookieReader is the minimal interface SessionToken needs from an incoming
// request — just *http.Request.Cookie's signature, not the whole request.
// *http.Request satisfies this trivially; a caller (like Bitmagnet's own
// internal/auth.HTTPContext) that deliberately abstracts its request behind
// a narrower interface of its own, e.g. for testability, can pass that
// directly instead of needing a concrete *http.Request.
type CookieReader interface {
Cookie(name string) (*http.Cookie, error)
}
// SessionToken reads AuthGuard's own session cookie
// (authclient.DefaultCookieName) off an incoming request, returning "" if
// it is absent or empty. Every AuthGuard-proxying service in this workspace
// mints no session token of its own — AuthGuard's cookie *is* the session —
// so this same read is duplicated in every one of them.
func SessionToken(r CookieReader) string {
cookie, err := r.Cookie(authclient.DefaultCookieName)
if err != nil || cookie.Value == "" {
return ""
}
return cookie.Value
}
// ClearSessionCookies clears AuthGuard's own session cookie plus one
// legacy, pre-migration cookie name a caller's browser might still be
// holding (each project's own cookie name from before it adopted
// AuthGuard — e.g. "gamestream_session", "bitmagnet_session",
// "mediacollection_session"; pass "" if a given caller has none). Normally
// AuthGuard's own Set-Cookie header, forwarded via authclient.ForwardCookies,
// already clears its cookie on logout — every project's own Logout handler
// also calls this explicitly as a fallback and to clear the legacy cookie,
// which AuthGuard has no way to know about.
func ClearSessionCookies(w http.ResponseWriter, legacyCookieName string, secure bool) {
http.SetCookie(w, &http.Cookie{
Name: authclient.DefaultCookieName, Value: "", Path: "/", HttpOnly: true,
Secure: secure, SameSite: http.SameSiteLaxMode, MaxAge: -1,
})
if legacyCookieName != "" && legacyCookieName != authclient.DefaultCookieName {
http.SetCookie(w, &http.Cookie{
Name: legacyCookieName, Value: "", Path: "/", HttpOnly: true,
Secure: secure, SameSite: http.SameSiteLaxMode, MaxAge: -1,
})
}
}
// NormalizeUsername reports whether value, once trimmed, is non-empty and
// no longer than maxLen runes, and returns the trimmed value either way.
//
// This returns (value, bool) rather than (value, error) deliberately: every
// existing caller already owns its own error value/message for this
// failure (e.g. "username is required", "invalid authentication input:
// username must be between 1 and 64 characters") as part of its public API
// response shape, and unifying those messages was not part of what made
// this duplicated — only the trim+shape check was. A caller with "empty
// means leave this field unchanged" update semantics (a partial-update
// endpoint) should special-case an empty value itself before calling this,
// since this function always reports false for one.
func NormalizeUsername(value string, maxLen int) (normalized string, ok bool) {
normalized = strings.TrimSpace(value)
return normalized, normalized != "" && utf8.RuneCountInString(normalized) <= maxLen
}
// NormalizeEmail reports whether value, once lowercased and trimmed, looks
// like a valid email address (exactly one "@", a non-empty local part, and
// a domain part containing at least one ".") and is no longer than maxLen
// runes, and returns the normalized value either way. Same (value, bool)
// shape and rationale as NormalizeUsername.
func NormalizeEmail(value string, maxLen int) (normalized string, ok bool) {
normalized = strings.ToLower(strings.TrimSpace(value))
if normalized == "" || utf8.RuneCountInString(normalized) > maxLen || strings.Count(normalized, "@") != 1 {
return normalized, false
}
local, domain, _ := strings.Cut(normalized, "@")
if local == "" || domain == "" || !strings.Contains(domain, ".") {
return normalized, false
}
return normalized, true
}
// ValidPassword reports whether password is at least minLen runes long.
func ValidPassword(password string, minLen int) bool {
return utf8.RuneCountInString(password) >= minLen
}
// APIErrorResponse extracts the HTTP status code and message an
// authclient.APIError carries, for a caller's own writeError-equivalent to
// forward. ok is false when err is not an *authclient.APIError (a
// transport failure actually reaching AuthGuard, as opposed to AuthGuard
// giving a real answer the caller didn't like) — callers should fall back
// to a generic 500 with their own message in that case, matching every
// existing writeAuthGuardError implementation's behavior.
func APIErrorResponse(err error) (statusCode int, message string, ok bool) {
var apiErr *authclient.APIError
if errors.As(err, &apiErr) {
return apiErr.StatusCode, apiErr.Message, true
}
return 0, "", false
}
+150
View File
@@ -0,0 +1,150 @@
package authproxy
import (
"errors"
"net/http"
"net/http/httptest"
"testing"
authclient "repos.gfranz.ch/Gabriel20xx/shared/backend/authclient"
)
func TestSessionToken(t *testing.T) {
cases := []struct {
name string
cookie *http.Cookie
want string
}{
{name: "no cookie", want: ""},
{name: "present", cookie: &http.Cookie{Name: authclient.DefaultCookieName, Value: "tok123"}, want: "tok123"},
{name: "empty value", cookie: &http.Cookie{Name: authclient.DefaultCookieName, Value: ""}, want: ""},
{name: "wrong cookie name", cookie: &http.Cookie{Name: "other", Value: "tok123"}, want: ""},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
r := httptest.NewRequest(http.MethodGet, "/", nil)
if tc.cookie != nil {
r.AddCookie(tc.cookie)
}
if got := SessionToken(r); got != tc.want {
t.Fatalf("SessionToken() = %q, want %q", got, tc.want)
}
})
}
}
func TestClearSessionCookies(t *testing.T) {
w := httptest.NewRecorder()
ClearSessionCookies(w, "legacy_session", true)
resp := w.Result()
cookies := resp.Cookies()
if len(cookies) != 2 {
t.Fatalf("got %d Set-Cookie headers, want 2: %+v", len(cookies), cookies)
}
byName := map[string]*http.Cookie{}
for _, c := range cookies {
byName[c.Name] = c
}
for _, name := range []string{authclient.DefaultCookieName, "legacy_session"} {
c, ok := byName[name]
if !ok {
t.Fatalf("missing Set-Cookie for %q", name)
}
if c.Value != "" || c.MaxAge != -1 || !c.HttpOnly || !c.Secure {
t.Fatalf("cookie %q not cleared correctly: %+v", name, c)
}
}
}
func TestClearSessionCookiesNoLegacyName(t *testing.T) {
w := httptest.NewRecorder()
ClearSessionCookies(w, "", false)
if got := len(w.Result().Cookies()); got != 1 {
t.Fatalf("got %d Set-Cookie headers, want 1 (no legacy name given)", got)
}
}
func TestClearSessionCookiesLegacyEqualsDefault(t *testing.T) {
w := httptest.NewRecorder()
ClearSessionCookies(w, authclient.DefaultCookieName, false)
if got := len(w.Result().Cookies()); got != 1 {
t.Fatalf("got %d Set-Cookie headers, want 1 (legacy name equals AuthGuard's own)", got)
}
}
func TestNormalizeUsername(t *testing.T) {
cases := []struct {
name string
input string
want string
ok bool
}{
{name: "valid", input: " gabriel ", want: "gabriel", ok: true},
{name: "empty", input: " ", want: "", ok: false},
{name: "too long", input: string(make([]byte, 65)), want: string(make([]byte, 65)), ok: false},
{name: "exactly max", input: "1234567890", want: "1234567890", ok: true},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
got, ok := NormalizeUsername(tc.input, 10)
if got != tc.want || ok != tc.ok {
t.Fatalf("NormalizeUsername(%q, 10) = (%q, %v), want (%q, %v)", tc.input, got, ok, tc.want, tc.ok)
}
})
}
}
func TestNormalizeEmail(t *testing.T) {
cases := []struct {
name string
input string
want string
ok bool
}{
{name: "valid", input: " Gabriel@Example.COM ", want: "gabriel@example.com", ok: true},
{name: "empty", input: "", want: "", ok: false},
{name: "no at", input: "gabriel.example.com", want: "gabriel.example.com", ok: false},
{name: "two ats", input: "a@b@c.com", want: "a@b@c.com", ok: false},
{name: "empty local part", input: "@example.com", want: "@example.com", ok: false},
{name: "empty domain", input: "gabriel@", want: "gabriel@", ok: false},
{name: "domain without dot", input: "gabriel@localhost", want: "gabriel@localhost", ok: false},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
got, ok := NormalizeEmail(tc.input, 254)
if got != tc.want || ok != tc.ok {
t.Fatalf("NormalizeEmail(%q, 254) = (%q, %v), want (%q, %v)", tc.input, got, ok, tc.want, tc.ok)
}
})
}
}
func TestValidPassword(t *testing.T) {
if ValidPassword("short", 8) {
t.Fatal("expected 5-char password to fail an 8-char minimum")
}
if !ValidPassword("longenough", 8) {
t.Fatal("expected 10-char password to pass an 8-char minimum")
}
}
func TestAPIErrorResponse(t *testing.T) {
t.Run("api error", func(t *testing.T) {
apiErr := &authclient.APIError{StatusCode: http.StatusConflict, Message: "already exists"}
status, message, ok := APIErrorResponse(apiErr)
if !ok || status != http.StatusConflict || message != "already exists" {
t.Fatalf("APIErrorResponse() = (%d, %q, %v), want (409, %q, true)", status, message, ok, "already exists")
}
})
t.Run("non-api error", func(t *testing.T) {
_, _, ok := APIErrorResponse(errors.New("transport failure"))
if ok {
t.Fatal("expected ok=false for a non-APIError")
}
})
}
+1
View File
@@ -18,5 +18,6 @@ ANALYZER_MODELS_URL=http://127.0.0.1:8801
CORS_ORIGIN=http://localhost:5173
SESSION_COOKIE=mediacollection_session
COOKIE_SECURE=false
AUTHGUARD_URL=
INTERNAL_SERVICE_SECRET=
MAX_UPLOAD_BYTES=50gb
+1 -1
View File
@@ -1,6 +1,6 @@
# MediaCollection Go backend
The backend is one Go module. Set `MEDIA_SERVICE` to `viewer`, `tools`, `analyzer`, `config`, `moderator`, `kiosk`, `servant`, or `desktop` to select the route set while keeping the same auth, database, migration, file-safety, and worker implementation.
The backend is one Go module. Set `MEDIA_SERVICE` to `viewer`, `tools`, `analyzer`, `config`, `moderator`, `kiosk`, or `servant` to select the route set while keeping the same auth, database, migration, file-safety, and worker implementation.
From this directory:
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,252 @@
package auth
import (
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"os"
"strings"
"testing"
"github.com/jackc/pgx/v5/pgxpool"
"mediacollection/internal/database"
)
// testPool returns a connection pool against a real (throwaway) Postgres
// instance, and a cleanup function. DATABASE_URL is expected to point at
// one - these tests are skipped (not failed) when it is unset, mirroring
// the workspace's existing convention for DB-backed test suites (see
// Forks/HordeWorker/tests/conftest.py's identical approach).
func testPool(t *testing.T) *pgxpool.Pool {
t.Helper()
dsn := strings.TrimSpace(os.Getenv("DATABASE_URL"))
if dsn == "" {
t.Skip("DATABASE_URL not set; skipping AuthGuard-proxy auth tests that need a real Postgres")
}
ctx := context.Background()
pool, err := database.Open(ctx, dsn)
if err != nil {
t.Fatalf("open test database: %v", err)
}
if err := database.Migrate(ctx, pool); err != nil {
t.Fatalf("migrate test database: %v", err)
}
if _, err := pool.Exec(ctx, `DELETE FROM settings`); err != nil {
t.Fatalf("reset settings table: %v", err)
}
if _, err := pool.Exec(ctx, `DELETE FROM users`); err != nil {
t.Fatalf("reset users table: %v", err)
}
t.Cleanup(pool.Close)
return pool
}
// fakeAuthGuard is a minimal stateful in-memory AuthGuard double: enough of
// setup-status/register/login/me/logout to exercise Service's proxy
// behavior end-to-end, mirroring the httptest-server pattern already used
// by shared/backend/authclient's own tests.
type fakeAuthGuard struct {
server *httptest.Server
hasAccount bool
username string
email string
role string
password string
sessions map[string]bool
}
func newFakeAuthGuard() *fakeAuthGuard {
f := &fakeAuthGuard{sessions: map[string]bool{}}
mux := http.NewServeMux()
mux.HandleFunc("GET /api/setup-status", func(w http.ResponseWriter, r *http.Request) {
writeJSON(w, http.StatusOK, map[string]bool{"setup_required": !f.hasAccount})
})
mux.HandleFunc("POST /api/register", func(w http.ResponseWriter, r *http.Request) {
if f.hasAccount {
writeJSON(w, http.StatusConflict, map[string]string{"error": "setup already completed"})
return
}
var body struct{ Username, Email, Password string }
_ = json.NewDecoder(r.Body).Decode(&body)
f.hasAccount = true
f.username, f.email, f.role, f.password = body.Username, body.Email, "superadmin", body.Password
token := "tok-" + body.Username
f.sessions[token] = true
http.SetCookie(w, &http.Cookie{Name: "auth_session", Value: token})
writeJSON(w, http.StatusOK, map[string]any{"user": map[string]any{
"id": 1, "username": f.username, "email": f.email, "role": f.role, "totp_enabled": false,
}})
})
mux.HandleFunc("POST /api/login", func(w http.ResponseWriter, r *http.Request) {
var body struct {
UsernameOrEmail string `json:"username_or_email"`
Password string `json:"password"`
}
_ = json.NewDecoder(r.Body).Decode(&body)
if !f.hasAccount || body.UsernameOrEmail != f.username && body.UsernameOrEmail != f.email || body.Password != f.password {
writeJSON(w, http.StatusUnauthorized, map[string]string{"error": "Invalid username or password."})
return
}
token := "tok-" + f.username
f.sessions[token] = true
http.SetCookie(w, &http.Cookie{Name: "auth_session", Value: token})
writeJSON(w, http.StatusOK, map[string]any{"user": map[string]any{
"id": 1, "username": f.username, "email": f.email, "role": f.role, "totp_enabled": false,
}})
})
mux.HandleFunc("GET /api/me", func(w http.ResponseWriter, r *http.Request) {
token := strings.TrimPrefix(r.Header.Get("Authorization"), "Bearer ")
if !f.sessions[token] {
writeJSON(w, http.StatusUnauthorized, map[string]string{"error": "invalid session"})
return
}
writeJSON(w, http.StatusOK, map[string]any{"user": map[string]any{
"id": 1, "username": f.username, "email": f.email, "role": f.role, "totp_enabled": false,
}})
})
mux.HandleFunc("POST /api/logout", func(w http.ResponseWriter, r *http.Request) {
token := strings.TrimPrefix(r.Header.Get("Authorization"), "Bearer ")
delete(f.sessions, token)
http.SetCookie(w, &http.Cookie{Name: "auth_session", Value: "", MaxAge: -1})
writeJSON(w, http.StatusOK, map[string]any{})
})
f.server = httptest.NewServer(mux)
return f
}
func (f *fakeAuthGuard) close() { f.server.Close() }
func newRequest(method, target string, body string) *http.Request {
var r *http.Request
if body != "" {
r = httptest.NewRequest(method, target, strings.NewReader(body))
} else {
r = httptest.NewRequest(method, target, nil)
}
return r
}
func TestCurrentUserDisabledModeReturnsLocalSuperadmin(t *testing.T) {
svc := New(nil, "mediacollection_session", false, "")
user, err := svc.CurrentUser(httptest.NewRequest(http.MethodGet, "/", nil))
if err != nil {
t.Fatalf("CurrentUser() error = %v", err)
}
if user == nil || user.Role != "superadmin" || !user.CanManageUsers {
t.Fatalf("CurrentUser() = %+v, want local superadmin placeholder", user)
}
}
func TestSignupLoginLogoutProxyToAuthGuard(t *testing.T) {
pool := testPool(t)
guard := newFakeAuthGuard()
defer guard.close()
svc := New(pool, "mediacollection_session", false, guard.server.URL)
ctx := context.Background()
// Signup
req := newRequest(http.MethodPost, "/auth/signup", `{"email":"a@example.com","username":"admin","password":"correct horse battery staple"}`)
rec := httptest.NewRecorder()
svc.Signup(rec, req)
if rec.Code != http.StatusCreated {
t.Fatalf("Signup() status = %d, body = %s", rec.Code, rec.Body.String())
}
cookie := firstSetCookie(t, rec)
if cookie == "" {
t.Fatal("Signup() did not forward AuthGuard's Set-Cookie")
}
claimed, err := svc.isSetupClaimed(ctx)
if err != nil || !claimed {
t.Fatalf("isSetupClaimed() = %v, %v, want true, nil", claimed, err)
}
// A second signup attempt must be rejected (setup already completed).
req2 := newRequest(http.MethodPost, "/auth/signup", `{"email":"b@example.com","username":"other","password":"correct horse battery staple"}`)
rec2 := httptest.NewRecorder()
svc.Signup(rec2, req2)
if rec2.Code != http.StatusConflict {
t.Fatalf("second Signup() status = %d, want 409", rec2.Code)
}
// CurrentUser resolves via the forwarded cookie.
authedReq := httptest.NewRequest(http.MethodGet, "/auth/me", nil)
authedReq.Header.Set("Cookie", "auth_session="+cookie)
user, err := svc.CurrentUser(authedReq)
if err != nil {
t.Fatalf("CurrentUser() error = %v", err)
}
if user == nil || user.Username != "admin" || user.Role != "superadmin" {
t.Fatalf("CurrentUser() = %+v, want the AuthGuard-registered admin", user)
}
// Login with wrong password is rejected.
badLogin := newRequest(http.MethodPost, "/auth/login", `{"identifier":"admin","password":"wrong"}`)
badRec := httptest.NewRecorder()
svc.Login(badRec, badLogin)
if badRec.Code != http.StatusUnauthorized {
t.Fatalf("Login() with wrong password status = %d, want 401", badRec.Code)
}
// Logout clears the session.
logoutReq := httptest.NewRequest(http.MethodPost, "/auth/logout", nil)
logoutReq.Header.Set("Cookie", "auth_session="+cookie)
logoutRec := httptest.NewRecorder()
svc.Logout(logoutRec, logoutReq)
if logoutRec.Code != http.StatusOK {
t.Fatalf("Logout() status = %d", logoutRec.Code)
}
}
func TestSecondProjectSetupIsRejectedWhenAuthGuardAlreadyHasAnAccount(t *testing.T) {
pool := testPool(t)
guard := newFakeAuthGuard()
defer guard.close()
guard.hasAccount = true // simulate a different project (or AuthGuard's own web UI) having already created one
guard.username, guard.email, guard.role, guard.password = "existing", "existing@example.com", "superadmin", "hunter2!!"
svc := New(pool, "mediacollection_session", false, guard.server.URL)
req := newRequest(http.MethodPost, "/auth/signup", `{"email":"new@example.com","username":"new","password":"correct horse battery staple"}`)
rec := httptest.NewRecorder()
svc.Signup(rec, req)
if rec.Code != http.StatusConflict {
t.Fatalf("Signup() status = %d, body = %s, want 409 (AuthGuard already has an account)", rec.Code, rec.Body.String())
}
// The local claim must have been released again so a later legitimate flow isn't locked out.
claimed, err := svc.isSetupClaimed(context.Background())
if err != nil || claimed {
t.Fatalf("isSetupClaimed() = %v, %v, want false after a rejected signup", claimed, err)
}
}
func TestLoginRequiredToggleIsIndependentOfAuthGuard(t *testing.T) {
pool := testPool(t)
svc := New(pool, "mediacollection_session", false, "")
required, err := svc.LoginRequired(context.Background())
if err != nil || !required {
t.Fatalf("LoginRequired() default = %v, %v, want true, nil", required, err)
}
rec := httptest.NewRecorder()
svc.UpdateAccessSettings(rec, newRequest(http.MethodPut, "/api/auth/access", `{"loginRequired":false}`))
if rec.Code != http.StatusOK {
t.Fatalf("UpdateAccessSettings() status = %d", rec.Code)
}
required, err = svc.LoginRequired(context.Background())
if err != nil || required {
t.Fatalf("LoginRequired() after disabling = %v, %v, want false, nil", required, err)
}
}
func firstSetCookie(t *testing.T, rec *httptest.ResponseRecorder) string {
t.Helper()
for _, raw := range rec.Result().Cookies() {
if raw.Name == "auth_session" && raw.Value != "" {
return raw.Value
}
}
return ""
}
@@ -18,7 +18,6 @@ const (
Moderator Service = "moderator"
Kiosk Service = "kiosk"
Servant Service = "servant"
Desktop Service = "desktop"
)
type Config struct {
@@ -39,6 +38,11 @@ type Config struct {
PublicURL string
SessionCookie string
SecureCookies bool
// AuthGuardURL is AuthGuard's base URL (see Web/Central/AuthGuard);
// empty means auth-disabled mode (see internal/auth's package doc
// comment). Read raw via os.Getenv rather than envOr since "" is a
// meaningful, distinct value here (not a fallback-worthy blank).
AuthGuardURL string
InternalServiceSecret string
FFmpeg string
FFprobe string
@@ -94,6 +98,7 @@ func Load() (*Config, error) {
PublicURL: strings.TrimRight(strings.TrimSpace(os.Getenv("PUBLIC_URL")), "/"),
SessionCookie: envOr("SESSION_COOKIE", "mediacollection_session"),
SecureCookies: envBool("COOKIE_SECURE", os.Getenv("TLS_CERT_FILE") != ""),
AuthGuardURL: strings.TrimSpace(os.Getenv("AUTHGUARD_URL")),
InternalServiceSecret: strings.TrimSpace(os.Getenv("INTERNAL_SERVICE_SECRET")),
FFmpeg: envOr("FFMPEG_PATH", "ffmpeg"),
FFprobe: envOr("FFPROBE_PATH", "ffprobe"),
@@ -131,8 +136,6 @@ func normalizeService(value string) Service {
return Kiosk
case "servant", "mediaservant":
return Servant
case "desktop", "mediadesktop":
return Desktop
default:
return ""
}
@@ -154,8 +157,6 @@ func serviceName(service Service) string {
return "MediaKiosk"
case Servant:
return "MediaServant"
case Desktop:
return "MediaDesktop"
default:
return "MediaCollection"
}
@@ -1060,12 +1060,6 @@ func (s *Server) kioskStatus(w http.ResponseWriter, r *http.Request) {
writeJSON(w, http.StatusOK, map[string]any{"ok": true, "latestImage": latest, "queueLength": 0})
}
func (s *Server) mountDesktopRoutes(r chi.Router) {
r.Get("/status", func(w http.ResponseWriter, _ *http.Request) {
writeJSON(w, http.StatusOK, map[string]any{"ok": true, "service": "MediaDesktop", "native": true})
})
}
func (s *Server) mountKioskSocket(r chi.Router) {
r.Get("/ws", s.kioskWebsocket)
}
@@ -138,7 +138,7 @@ func New(cfg *config.Config, db *pgxpool.Pool) *Server {
return &Server{
cfg: cfg,
db: db,
auth: auth.New(db, cfg.SessionCookie, cfg.SecureCookies),
auth: auth.New(db, cfg.SessionCookie, cfg.SecureCookies, cfg.AuthGuardURL),
startedAt: time.Now(),
media: make(map[string]MediaRecord),
jobs: make(map[string]*WorkflowJob),
@@ -167,8 +167,6 @@ func (s *Server) Handler() http.Handler {
r.Post("/signup", s.auth.Signup)
r.Post("/login", s.auth.Login)
r.Post("/logout", s.auth.Logout)
r.Post("/reset/request", s.auth.RequestAdminReset)
r.Post("/reset/confirm", s.auth.ConfirmAdminReset)
r.Get("/me", s.auth.Me)
r.With(s.auth.Require).Put("/me", s.auth.UpdateMe)
r.Get("/status", s.auth.Status)
@@ -225,8 +223,6 @@ func (s *Server) mountServiceRoutes(r chi.Router) {
s.mountKioskRoutes(r)
case config.Servant:
s.mountServantRoutes(r)
case config.Desktop:
s.mountDesktopRoutes(r)
}
}
-1
View File
@@ -14,7 +14,6 @@
"build:moderator": "node scripts/build-all.mjs moderator",
"build:kiosk": "node scripts/build-all.mjs kiosk",
"build:servant": "node scripts/build-all.mjs servant",
"build:desktop": "node scripts/build-all.mjs desktop",
"check": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json",
"lint": "eslint .",
"format": "prettier --write .",
+1 -2
View File
@@ -5,6 +5,5 @@
"config": { "name": "MediaConfig", "icon": "settings-2" },
"moderator": { "name": "MediaModerator", "icon": "shield-check" },
"kiosk": { "name": "MediaKiosk", "icon": "image" },
"servant": { "name": "MediaServant", "icon": "server" },
"desktop": { "name": "MediaViewer Desktop", "icon": "monitor-play" }
"servant": { "name": "MediaServant", "icon": "server" }
}
-1
View File
@@ -12,7 +12,6 @@ const targets = {
moderator: 'MediaModerator',
kiosk: 'MediaKiosk',
servant: 'MediaServant',
desktop: 'MediaDesktop',
}
const requested = process.argv.slice(2)
-23
View File
@@ -238,29 +238,6 @@ const configs: Record<AppId, AppConfig> = {
},
],
},
desktop: {
id: 'desktop',
name: 'MediaViewer Desktop',
icon: projectIcon('desktop'),
eyebrow: 'Connected player',
description: 'Control playback, funscripts, and connected devices from your desktop.',
nav: [
{
label: 'Player',
panel: 'player',
path: '/',
icon: 'monitor-play',
description: 'Control playback and connected desktop devices.',
},
{
label: 'Devices',
panel: 'devices',
path: '/devices',
icon: 'box',
description: 'Manage connected playback and funscript devices.',
},
],
},
}
export function getAppConfig(id: string): AppConfig {
@@ -1,11 +1,7 @@
<script lang="ts">
import { onMount } from 'svelte'
import { get } from '$lib/api'
import EmptyState from '$lib/components/EmptyState.svelte'
import SectionTitle from '$lib/components/SectionTitle.svelte'
import Badge from '$lib/components/ui/badge.svelte'
import Button from '$lib/components/ui/button.svelte'
import Card from '$lib/components/ui/card.svelte'
import { Badge, Button, Card, EmptyState, SectionTitle } from '@gabriel20xx/web-ui'
type Json = Record<string, unknown>
type MediaType = 'image' | 'video' | 'audio' | 'funscript'
@@ -63,14 +59,14 @@
return fallback
}
function statusTone(status: string): 'neutral' | 'primary' | 'success' | 'warning' | 'danger' {
function statusTone(status: string): 'default' | 'primary' | 'success' | 'warning' | 'danger' {
const normalized = status.toLowerCase()
if (normalized.includes('error') || normalized.includes('fail')) return 'danger'
if (normalized.includes('process') || normalized.includes('running')) return 'primary'
if (normalized.includes('queue') || normalized.includes('pending')) return 'warning'
if (normalized.includes('done') || normalized.includes('complete') || normalized.includes('success'))
return 'success'
return 'neutral'
return 'default'
}
async function load({ background = false } = {}) {
@@ -183,7 +179,7 @@
<p class="truncate text-sm font-medium text-fg">{name}</p>
{#if path}<p class="mt-1 truncate text-xs text-muted-fg">{path}</p>{/if}
</div>
<Badge tone={statusTone(status)}>{status}</Badge>
<Badge variant={statusTone(status)}>{status}</Badge>
</div>
<div class="mt-2 flex flex-wrap gap-x-3 gap-y-1 text-xs text-muted-fg">
{#if entryMediaType}<span>{entryMediaType}</span>{/if}
@@ -1,13 +1,9 @@
<script lang="ts">
import { notify } from '@gabriel20xx/web-ui'
import { Badge, Button, Card, notify, SectionTitle } from '@gabriel20xx/web-ui'
import { post } from '$lib/api'
import SectionTitle from '$lib/components/SectionTitle.svelte'
import Badge from '$lib/components/ui/badge.svelte'
import Button from '$lib/components/ui/button.svelte'
import Card from '$lib/components/ui/card.svelte'
type Json = Record<string, unknown>
type StatusTone = 'neutral' | 'primary' | 'success' | 'warning' | 'danger'
type StatusTone = 'default' | 'primary' | 'success' | 'warning' | 'danger'
let {
status = {},
@@ -74,7 +70,7 @@
if (running) return paused ? 'warning' : 'primary'
if (label.includes('error') || label.includes('failed')) return 'danger'
if (['idle', 'completed', 'complete', 'done'].includes(label)) return 'success'
return 'neutral'
return 'default'
}
const extractionProgress = $derived(asRecord(status.extractionProgress))
@@ -155,7 +151,7 @@
<div class="flex items-center justify-between gap-3">
<span class="text-sm text-muted-fg">State</span>
<div class="flex items-center gap-2">
<Badge {tone}>{stateLabel}</Badge>
<Badge variant={tone}>{stateLabel}</Badge>
{#if canStop}
<Button variant="danger" size="sm" disabled={stopping} onclick={() => void stopAction()}>
{stopping ? 'Stopping…' : 'Stop'}
@@ -1,6 +1,5 @@
<script lang="ts">
import SectionTitle from '$lib/components/SectionTitle.svelte'
import Card from '$lib/components/ui/card.svelte'
import { Card, SectionTitle } from '@gabriel20xx/web-ui'
type Json = Record<string, unknown>
@@ -139,13 +139,6 @@
auth = { ...auth, user: data.user, setupRequired: false, loading: false, error: null }
}
const requestReset = () => post('/auth/reset/request')
async function confirmReset(code: string) {
await post('/auth/reset/confirm', { code })
window.location.reload()
}
async function logout() {
try {
await post('/auth/logout')
@@ -199,8 +192,6 @@
error={auth.error || ''}
onLogin={login}
onSetup={setup}
onRequestReset={requestReset}
onConfirmReset={confirmReset}
/>
{:else}
<div class="sc-root sc-app-shell min-h-screen bg-bg text-fg mediacollection-shell">
@@ -1,43 +1,22 @@
<script lang="ts">
import {
AuthPage as SharedAuthPage,
type AuthLoginInput,
type AuthResetConfirm,
type AuthResetRequest,
type AuthSetupInput,
} from '@gabriel20xx/web-ui'
import { AuthPage as SharedAuthPage, type AuthLoginInput, type AuthSetupInput } from '@gabriel20xx/web-ui'
import type { AppConfig } from '$lib/types'
let {
app,
error = '',
loading = false,
onConfirmReset,
onLogin,
onRequestReset,
onSetup,
setupRequired,
}: {
app: AppConfig
error?: string
loading?: boolean
onConfirmReset: AuthResetConfirm
onLogin: (input: AuthLoginInput) => void | Promise<void>
onRequestReset: AuthResetRequest
onSetup: (input: AuthSetupInput) => void | Promise<void>
setupRequired: boolean
} = $props()
</script>
<SharedAuthPage
brand={app.name}
tagline={app.eyebrow}
{setupRequired}
{loading}
{error}
showTotp
{onLogin}
{onSetup}
{onRequestReset}
{onConfirmReset}
/>
<SharedAuthPage brand={app.name} tagline={app.eyebrow} {setupRequired} {loading} {error} showTotp {onLogin} {onSetup} />
@@ -1,14 +0,0 @@
<script lang="ts">
import { Inbox } from '@lucide/svelte'
let { title, message }: { title: string; message: string } = $props()
</script>
<div
class="flex min-h-40 flex-col items-center justify-center gap-3 rounded-lg border border-dashed border-border bg-surface/50 px-5 py-8 text-center"
>
<Inbox class="size-8 text-muted-fg" />
<div>
<p class="text-sm font-medium text-fg">{title}</p>
<p class="mt-1 max-w-sm text-xs text-muted-fg">{message}</p>
</div>
</div>
@@ -1,6 +1,6 @@
<script lang="ts">
import { ArrowDown, ArrowRight, ChevronDown, FileCog, Image as ImageIcon, Search, Sparkles } from '@lucide/svelte'
import Badge from '$lib/components/ui/badge.svelte'
import { Badge } from '@gabriel20xx/web-ui'
import { cn } from '$lib/utils/cn'
type StageStatus = { pending: number; processing: number; processed: number; errors: number; active: boolean }
@@ -220,9 +220,9 @@
<span class="text-sm font-semibold text-fg">Metadata</span>
</div>
{#if metadataStatus.active}
<Badge tone="primary" class="animate-pulse">Active</Badge>
<Badge variant="primary" class="animate-pulse">Active</Badge>
{:else}
<Badge tone="neutral">Idle</Badge>
<Badge>Idle</Badge>
{/if}
</div>
<p class="text-xs text-muted-fg">{metadataDescription}</p>
@@ -249,9 +249,9 @@
<span class="text-sm font-semibold text-fg">Thumbnails</span>
</div>
{#if thumbnailsStatus.active}
<Badge tone="primary" class="animate-pulse">Active</Badge>
<Badge variant="primary" class="animate-pulse">Active</Badge>
{:else}
<Badge tone="neutral">Idle</Badge>
<Badge>Idle</Badge>
{/if}
</div>
<p class="text-xs text-muted-fg">{thumbnailsDescription}</p>
@@ -279,9 +279,9 @@
<span class="text-sm font-semibold text-fg">AI analysis</span>
</div>
{#if analysisStatus.active}
<Badge tone="primary" class="animate-pulse">Active</Badge>
<Badge variant="primary" class="animate-pulse">Active</Badge>
{:else}
<Badge tone="neutral">Idle</Badge>
<Badge>Idle</Badge>
{/if}
</div>
<p class="text-xs text-muted-fg">
@@ -1,10 +0,0 @@
<script lang="ts">
let { title, description = '' }: { title: string; description?: string } = $props()
</script>
<div class="flex items-start justify-between gap-3">
<div>
<h2 class="text-sm font-semibold text-fg">{title}</h2>
{#if description}<p class="mt-1 text-xs text-muted-fg">{description}</p>{/if}
</div>
</div>
@@ -1,6 +1,6 @@
<script lang="ts">
import { Moon, Sun, SunMoon } from '@lucide/svelte'
import Button from '$lib/components/ui/button.svelte'
import { Button, SettingsDialog as SharedSettingsDialog } from '@gabriel20xx/web-ui'
import { currentLanguage, languages, setLanguage } from '$lib/language.svelte'
import { themeState } from '$lib/theme.svelte'
@@ -21,77 +21,62 @@
})
</script>
{#if open}
<div
class="fixed inset-0 z-50 grid place-items-center bg-black/70 p-4 backdrop-blur-sm"
role="presentation"
onclick={(event) => {
if (event.target === event.currentTarget) open = false
}}
>
<div
class="w-full max-w-lg rounded-xl border border-border bg-surface p-6 shadow-xl"
role="dialog"
aria-modal="true"
aria-label="Settings"
tabindex="-1"
>
<div class="flex items-start justify-between gap-4">
<h2 class="text-xl font-semibold">Settings</h2>
<button
class="rounded-md px-2 py-1 text-2xl leading-none text-muted-fg hover:bg-surface-hover hover:text-fg"
<SharedSettingsDialog bind:open title="Settings">
<div class="sc-form">
<div>
<span class="sc-label">Theme</span>
<div class="mediacollection-settings-theme-row">
<Button
type="button"
aria-label="Close"
onclick={() => (open = false)}>×</button
variant={themeState.mode === 'light' ? 'secondary' : 'ghost'}
size="sm"
fullWidth
onclick={() => themeState.setMode('light')}
>
</div>
<div class="mt-6 space-y-5">
<div>
<span class="mb-2 block text-sm font-medium">Theme</span>
<div class="flex w-full rounded-md border border-border p-1">
<Button
type="button"
variant={themeState.mode === 'light' ? 'secondary' : 'ghost'}
size="sm"
class="flex-1 gap-1.5"
onclick={() => themeState.setMode('light')}
>
<Sun class="size-4" />
Light
</Button>
<Button
type="button"
variant={themeState.mode === 'dark' ? 'secondary' : 'ghost'}
size="sm"
class="flex-1 gap-1.5"
onclick={() => themeState.setMode('dark')}
>
<Moon class="size-4" />
Dark
</Button>
<Button
type="button"
variant={themeState.mode === 'system' ? 'secondary' : 'ghost'}
size="sm"
class="flex-1 gap-1.5"
onclick={() => themeState.setMode('system')}
>
<SunMoon class="size-4" />
System
</Button>
</div>
</div>
<label class="block">
<span class="mb-2 block text-sm font-medium">Language</span>
<select class="field" value={currentLanguage()} onchange={(event) => setLanguage(event.currentTarget.value)}>
{#each languageItems as item (item.value)}
<option value={item.value}>{item.label}</option>
{/each}
</select>
</label>
<Sun size={16} />
Light
</Button>
<Button
type="button"
variant={themeState.mode === 'dark' ? 'secondary' : 'ghost'}
size="sm"
fullWidth
onclick={() => themeState.setMode('dark')}
>
<Moon size={16} />
Dark
</Button>
<Button
type="button"
variant={themeState.mode === 'system' ? 'secondary' : 'ghost'}
size="sm"
fullWidth
onclick={() => themeState.setMode('system')}
>
<SunMoon size={16} />
System
</Button>
</div>
</div>
<label class="sc-field">
<span class="sc-label">Language</span>
<select class="sc-input" value={currentLanguage()} onchange={(event) => setLanguage(event.currentTarget.value)}>
{#each languageItems as item (item.value)}
<option value={item.value}>{item.label}</option>
{/each}
</select>
</label>
</div>
{/if}
</SharedSettingsDialog>
<style>
.mediacollection-settings-theme-row {
display: flex;
width: 100%;
gap: 0.25rem;
padding: 0.25rem;
border: 1px solid var(--sc-border);
border-radius: var(--sc-radius-md);
}
</style>
@@ -1,102 +0,0 @@
<script lang="ts">
import { AlertCircle, AlertTriangle, CheckCircle2, CircleHelp, LoaderCircle, RefreshCw, X } from '@lucide/svelte'
import Button from '$lib/components/ui/button.svelte'
import type { StatusProbe, StatusSnapshot } from '$lib/status'
let {
open = $bindable(false),
status,
onRefresh,
}: {
open?: boolean
status: StatusSnapshot
onRefresh: () => Promise<void>
} = $props()
const levelLabel = {
checking: 'Checking',
healthy: 'Healthy',
degraded: 'Degraded',
offline: 'Offline',
}
const levelClass = {
checking: 'text-muted-fg',
healthy: 'text-success',
degraded: 'text-warning',
offline: 'text-danger',
}
function probeLabel(probe: StatusProbe | null) {
if (!probe) return 'Not checked'
if (probe.ok) return 'OK'
if (probe.error) return probe.error
return probe.httpStatus ? `HTTP ${probe.httpStatus}` : 'Unavailable'
}
</script>
{#if open}
<div
class="fixed inset-0 z-50 grid place-items-center bg-black/70 px-4"
role="presentation"
onclick={(event) => event.target === event.currentTarget && (open = false)}
>
<div
class="w-full max-w-lg rounded-xl border border-border bg-bg p-6 text-fg shadow-2xl"
role="dialog"
aria-modal="true"
aria-labelledby="status-dialog-title"
>
<div class="mb-5 flex items-start justify-between gap-3">
<div>
<h2 id="status-dialog-title" class="text-xl font-semibold">Service status</h2>
<p class="mt-1 text-sm text-muted-fg">Live liveness and database readiness checks.</p>
</div>
<Button variant="ghost" size="icon" aria-label="Close" onclick={() => (open = false)}>
<X class="size-4" />
</Button>
</div>
<div class="mb-5 flex items-center gap-3 rounded-lg border border-border bg-surface p-3" aria-live="polite">
{#if status.loading && status.level === 'checking'}
<LoaderCircle class="size-5 animate-spin text-muted-fg" />
{:else if status.level === 'healthy'}
<CheckCircle2 class="size-5 text-success" />
{:else if status.level === 'degraded'}
<AlertTriangle class="size-5 text-warning" />
{:else if status.level === 'offline'}
<AlertCircle class="size-5 text-danger" />
{:else}
<CircleHelp class="size-5 text-muted-fg" />
{/if}
<span class={`font-medium ${levelClass[status.level]}`}>{levelLabel[status.level]}</span>
{#if status.checkedAt}
<span class="ml-auto text-xs text-muted-fg">{new Date(status.checkedAt).toLocaleTimeString()}</span>
{/if}
</div>
<div class="space-y-2 text-sm">
{#each [{ label: 'Liveness', probe: status.health }, { label: 'Readiness / database', probe: status.readiness }] as item (item.label)}
<div class="flex items-center justify-between gap-4 rounded-md border border-border px-3 py-2">
<span>{item.label}</span>
<span class={item.probe?.ok ? 'text-success' : 'text-danger'}>{probeLabel(item.probe)}</span>
</div>
{/each}
</div>
{#if status.health?.service || status.readiness?.service}
<p class="mt-4 text-xs text-muted-fg">
Service: {status.health?.service || status.readiness?.service}
</p>
{/if}
<div class="mt-6 flex justify-end gap-2">
<Button variant="outline" disabled={status.loading} onclick={() => void onRefresh()}>
<RefreshCw class={status.loading ? 'animate-spin' : ''} />
Refresh
</Button>
<Button variant="secondary" onclick={() => (open = false)}>Dismiss</Button>
</div>
</div>
</div>
{/if}
@@ -1,97 +0,0 @@
<script lang="ts">
import { AlertCircle, AlertTriangle, CheckCircle2, CircleHelp, LoaderCircle } from '@lucide/svelte'
import { onMount } from 'svelte'
import Button from '$lib/components/ui/button.svelte'
import StatusDialog from '$lib/components/StatusDialog.svelte'
import type { StatusProbe, StatusSnapshot } from '$lib/status'
const initialStatus: StatusSnapshot = {
level: 'checking',
health: null,
readiness: null,
checkedAt: null,
loading: false,
}
let status = $state<StatusSnapshot>(initialStatus)
let open = $state(false)
let requestInFlight = false
async function probe(path: string): Promise<StatusProbe> {
try {
const response = await fetch(path, {
credentials: 'include',
headers: { Accept: 'application/json' },
})
const payload = (await response.json().catch(() => null)) as {
ok?: boolean
service?: string
error?: string
} | null
return {
path,
ok: response.ok && payload?.ok !== false,
httpStatus: response.status,
service: payload?.service || null,
error: response.ok ? null : payload?.error || response.statusText || `HTTP ${response.status}`,
}
} catch (error) {
return {
path,
ok: false,
httpStatus: null,
service: null,
error: error instanceof Error ? error.message : 'Unavailable',
}
}
}
async function refresh() {
if (requestInFlight) return
requestInFlight = true
status = { ...status, loading: true, level: status.health || status.readiness ? status.level : 'checking' }
try {
const [health, readiness] = await Promise.all([probe('/healthz'), probe('/ready')])
const level = health.ok && readiness.ok ? 'healthy' : health.ok ? 'degraded' : 'offline'
status = {
level,
health,
readiness,
checkedAt: new Date().toISOString(),
loading: false,
}
} finally {
requestInFlight = false
if (status.loading) status = { ...status, loading: false }
}
}
onMount(() => {
void refresh()
const timer = window.setInterval(() => void refresh(), 15_000)
return () => window.clearInterval(timer)
})
</script>
<Button
variant="ghost"
size="icon"
aria-label="Service status"
title={`Service status: ${status.level}`}
onclick={() => (open = true)}
>
{#if status.loading && status.level === 'checking'}
<LoaderCircle class="size-5 animate-spin text-muted-fg" />
{:else if status.level === 'healthy'}
<CheckCircle2 class="size-5 text-success" />
{:else if status.level === 'degraded'}
<AlertTriangle class="size-5 text-warning" />
{:else if status.level === 'offline'}
<AlertCircle class="size-5 text-danger" />
{:else}
<CircleHelp class="size-5 text-muted-fg" />
{/if}
</Button>
<StatusDialog bind:open {status} onRefresh={refresh} />
@@ -3,7 +3,6 @@
import { getAppConfig, getPanelForPath, getPathForPanel } from '$lib/app-config'
import AnalyzerWorkspace from '$lib/features/AnalyzerWorkspace.svelte'
import ConfigWorkspace from '$lib/features/ConfigWorkspace.svelte'
import DesktopWorkspace from '$lib/features/DesktopWorkspace.svelte'
import FeedWorkspace from '$lib/features/FeedWorkspace.svelte'
import KioskWorkspace from '$lib/features/KioskWorkspace.svelte'
import MediaTypePipeline from '$lib/features/MediaTypePipeline.svelte'
@@ -82,6 +81,4 @@
<KioskWorkspace {panel} />
{:else if app.id === 'servant'}
<ServantWorkspace {panel} />
{:else}
<DesktopWorkspace {panel} />
{/if}
@@ -1,32 +0,0 @@
<script lang="ts">
import type { HTMLAttributes } from 'svelte/elements'
import { cn } from '$lib/utils/cn'
let {
class: className,
tone = 'neutral',
children,
...rest
}: HTMLAttributes<HTMLSpanElement> & {
tone?: 'neutral' | 'primary' | 'success' | 'warning' | 'danger'
children?: import('svelte').Snippet
} = $props()
const toneClasses = {
neutral: 'border-border bg-surface-hover text-muted-fg',
primary: 'border-primary/30 bg-primary/15 text-primary',
success: 'border-success/30 bg-success/15 text-success',
warning: 'border-warning/30 bg-warning/15 text-warning',
danger: 'border-danger/30 bg-danger/15 text-danger',
}
</script>
<span
class={cn(
'inline-flex items-center rounded-full border px-2 py-0.5 text-xs font-medium',
toneClasses[tone],
className,
)}
{...rest}
>
{@render children?.()}
</span>
@@ -1,43 +0,0 @@
<script lang="ts">
import { cva, type VariantProps } from 'class-variance-authority'
import type { HTMLButtonAttributes } from 'svelte/elements'
import { cn } from '$lib/utils/cn'
export const buttonVariants = cva(
'inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-50 [&_svg]:size-4 [&_svg]:shrink-0',
{
variants: {
variant: {
default: 'bg-primary text-primary-fg hover:opacity-90',
secondary: 'border border-border bg-surface text-fg hover:bg-surface-hover',
outline: 'border border-border bg-transparent text-fg hover:bg-surface-hover',
ghost: 'text-fg hover:bg-surface-hover',
danger: 'bg-danger text-danger-fg hover:opacity-90',
success: 'bg-success text-success-fg hover:opacity-90',
link: 'text-primary underline-offset-4 hover:underline',
},
size: {
default: 'h-9 px-4 py-2',
sm: 'h-8 rounded-md px-3 text-xs',
lg: 'h-10 rounded-md px-6',
icon: 'h-9 w-9',
},
},
defaultVariants: { variant: 'default', size: 'default' },
},
)
type Variant = VariantProps<typeof buttonVariants>
let {
class: className,
variant = 'default',
size = 'default',
type = 'button',
children,
...rest
}: HTMLButtonAttributes & Variant & { children?: import('svelte').Snippet } = $props()
</script>
<button {type} class={cn(buttonVariants({ variant, size }), className)} {...rest}>
{@render children?.()}
</button>
@@ -1,14 +0,0 @@
<script lang="ts">
import type { HTMLAttributes } from 'svelte/elements'
import { cn } from '$lib/utils/cn'
let {
class: className,
children,
...rest
}: HTMLAttributes<HTMLDivElement> & { children?: import('svelte').Snippet } = $props()
</script>
<div class={cn('rounded-lg border border-border bg-surface p-4 shadow-sm', className)} {...rest}>
{@render children?.()}
</div>
@@ -1,32 +0,0 @@
<script lang="ts">
import { cn } from '$lib/utils/cn'
let {
label,
value,
detail = '',
tone = 'default',
}: {
label: string
value: string | number
detail?: string
tone?: 'default' | 'primary' | 'success' | 'warning' | 'danger'
} = $props()
</script>
<div class="rounded-lg border border-border bg-surface p-4">
<p class="text-xs font-medium uppercase tracking-wider text-muted-fg">{label}</p>
<p
class={cn(
'mt-2 text-2xl font-semibold tracking-tight',
tone === 'primary' && 'text-primary',
tone === 'success' && 'text-success',
tone === 'warning' && 'text-warning',
tone === 'danger' && 'text-danger',
tone === 'default' && 'text-fg',
)}
>
{value}
</p>
{#if detail}<p class="mt-1 text-xs text-muted-fg">{detail}</p>{/if}
</div>
@@ -2,17 +2,11 @@
import { AlertTriangle, Play, Plus, RefreshCw, Trash2 } from '@lucide/svelte'
import { onMount } from 'svelte'
import { SvelteSet } from 'svelte/reactivity'
import { notify } from '@gabriel20xx/web-ui'
import { Badge, Button, Card, EmptyState, Metric, notify, SectionTitle } from '@gabriel20xx/web-ui'
import { del, get, post } from '$lib/api'
import AnalyzerHistory from '$lib/components/AnalyzerHistory.svelte'
import AnalyzerLiveStatus from '$lib/components/AnalyzerLiveStatus.svelte'
import AnalyzerPipelineBreakdown from '$lib/components/AnalyzerPipelineBreakdown.svelte'
import SectionTitle from '$lib/components/SectionTitle.svelte'
import Card from '$lib/components/ui/card.svelte'
import Button from '$lib/components/ui/button.svelte'
import Badge from '$lib/components/ui/badge.svelte'
import Metric from '$lib/components/ui/metric.svelte'
import EmptyState from '$lib/components/EmptyState.svelte'
import { cn } from '$lib/utils/cn'
type Json = Record<string, unknown>
@@ -407,18 +401,18 @@
label="Pending"
value={numeric('queued', numeric('queueLength'))}
detail="Waiting for a worker"
tone="warning"
variant="warning"
/><Metric
label="Processing"
value={numeric('processing', numeric('activeJobs'))}
detail="Active jobs"
tone="primary"
variant="primary"
/><Metric
label="Completed"
value={numeric('completed', numeric('processed'))}
detail="Current history window"
tone="success"
/><Metric label="Errors" value={numeric('errors', numeric('failed'))} detail="Needs attention" tone="danger" />
variant="success"
/><Metric label="Errors" value={numeric('errors', numeric('failed'))} detail="Needs attention" variant="danger" />
</div>
<AnalyzerPipelineBreakdown pipeline={asRecord(stats.pipeline)} />
<div class="grid gap-4 lg:grid-cols-[minmax(0,1.25fr)_minmax(280px,.75fr)]">
@@ -476,18 +470,18 @@
label="Pending"
value={numeric('queued', numeric('queueLength'))}
detail="Waiting for a worker"
tone="warning"
variant="warning"
/><Metric
label="Processing"
value={numeric('processing', numeric('activeJobs'))}
detail="Active jobs"
tone="primary"
variant="primary"
/><Metric
label="Completed"
value={numeric('completed', numeric('processed'))}
detail="Current history window"
tone="success"
/><Metric label="Errors" value={numeric('errors', numeric('failed'))} detail="Needs attention" tone="danger" />
variant="success"
/><Metric label="Errors" value={numeric('errors', numeric('failed'))} detail="Needs attention" variant="danger" />
</div>
<AnalyzerLiveStatus {status} {stats} {loading} description="Current analyzer schedule and worker state." />
<Card class="space-y-5"
@@ -567,7 +561,7 @@
</p>{/if}
</div>
<div class="flex shrink-0 items-center gap-2">
<Badge tone={schedule.enabled === false ? 'neutral' : 'success'}
<Badge variant={schedule.enabled === false ? 'default' : 'success'}
>{schedule.enabled === false ? 'Paused' : 'Enabled'}</Badge
><Button variant="outline" size="sm" onclick={() => void runScheduleNow(String(schedule.id))}
>Run now</Button
@@ -14,17 +14,12 @@
Trash2,
} from '@lucide/svelte'
import { onDestroy, onMount } from 'svelte'
import { notify } from '@gabriel20xx/web-ui'
import { Badge, Button, Card, EmptyState, notify, SectionTitle } from '@gabriel20xx/web-ui'
import { get, post } from '$lib/api'
import SectionTitle from '$lib/components/SectionTitle.svelte'
import { pageActions } from '$lib/stores/page-actions.svelte'
import Card from '$lib/components/ui/card.svelte'
import Button from '$lib/components/ui/button.svelte'
import Badge from '$lib/components/ui/badge.svelte'
import EmptyState from '$lib/components/EmptyState.svelte'
type Json = Record<string, unknown>
type StatusTone = 'neutral' | 'primary' | 'success' | 'warning' | 'danger'
type StatusTone = 'default' | 'primary' | 'success' | 'warning' | 'danger'
type ConnectionStatus = { label: string; tone: StatusTone; title?: string }
type MountEntry = { type: string; path: string }
type TransferLimit = { uploadKbps: string; downloadKbps: string }
@@ -584,7 +579,7 @@
}
function statusFor(key: string): ConnectionStatus {
return statuses[key] || { label: 'Unknown', tone: 'neutral' }
return statuses[key] || { label: 'Unknown', tone: 'default' }
}
async function checkTarget(key: string, rawUrl: string, project: string | null, id: string) {
@@ -593,7 +588,7 @@
urls = { ...urls, [id]: url }
}
if (!url) {
statuses = { ...statuses, [key]: { label: 'No URL', tone: 'neutral' } }
statuses = { ...statuses, [key]: { label: 'No URL', tone: 'default' } }
return
}
@@ -845,7 +840,7 @@
<p class="mt-1 text-xs text-muted-fg">The image-generation service used by MediaTools.</p>
</div>
<div class="flex items-center gap-2">
<Badge tone={statusFor('comfyui').tone} title={statusFor('comfyui').title}
<Badge variant={statusFor('comfyui').tone} title={statusFor('comfyui').title}
>{statusFor('comfyui').label}</Badge
>
<Button variant="secondary" size="sm" onclick={() => void checkConnection('comfyui')}>Check</Button>
@@ -883,7 +878,7 @@
{connection.label || `External Connection ${index + 1}`}
</p>
<Badge
tone={statusFor(`external:${connection.id}`).tone}
variant={statusFor(`external:${connection.id}`).tone}
title={statusFor(`external:${connection.id}`).title}
>
{statusFor(`external:${connection.id}`).label}
@@ -1007,13 +1002,13 @@
<div class="flex items-center gap-2">
<p class="text-sm font-semibold text-fg">{labels.mediaconfig || 'MediaConfig'}</p>
{#if labels.mediaconfig}<span class="text-xs text-muted-fg">(MediaConfig)</span>{/if}
<Badge tone={statusFor('mediaconfig').tone} title={statusFor('mediaconfig').title}
<Badge variant={statusFor('mediaconfig').tone} title={statusFor('mediaconfig').title}
>{statusFor('mediaconfig').label}</Badge
>
</div>
<div class="flex items-center gap-2">
<Button variant="secondary" size="sm" onclick={() => void checkConnection('mediaconfig')}>Check</Button>
<Badge tone="primary"><Check class="size-3" />Self</Badge>
<Badge variant="primary"><Check class="size-3" />Self</Badge>
</div>
</div>
<div class="mt-4 grid gap-4 md:grid-cols-2">
@@ -1068,7 +1063,7 @@
{#if labels[projectKey(project)]}<span class="text-xs text-muted-fg"
>({getInstanceLabel(project)})</span
>{/if}
<Badge tone={statusFor(projectKey(project)).tone} title={statusFor(projectKey(project)).title}
<Badge variant={statusFor(projectKey(project)).tone} title={statusFor(projectKey(project)).title}
>{statusFor(projectKey(project)).label}</Badge
>
</div>
@@ -1167,7 +1162,7 @@
<div class="flex min-w-0 flex-wrap items-center gap-2">
<p class="truncate text-sm font-semibold text-fg">{labels[key] || getInstanceLabel(project)}</p>
{#if labels[key]}<span class="text-xs text-muted-fg">({getInstanceLabel(project)})</span>{/if}
<Badge tone={statusFor(key).tone} title={statusFor(key).title}>{statusFor(key).label}</Badge>
<Badge variant={statusFor(key).tone} title={statusFor(key).title}>{statusFor(key).label}</Badge>
</div>
</div>
<div class="flex shrink-0 items-center gap-1">
@@ -1,99 +0,0 @@
<script lang="ts">
import { Bluetooth, Cable, CheckCircle2, MonitorPlay, Settings2, SlidersHorizontal } from '@lucide/svelte'
import SectionTitle from '$lib/components/SectionTitle.svelte'
import Card from '$lib/components/ui/card.svelte'
import Button from '$lib/components/ui/button.svelte'
import Badge from '$lib/components/ui/badge.svelte'
import EmptyState from '$lib/components/EmptyState.svelte'
let { panel = 'player' }: { panel?: string } = $props()
</script>
<div class="space-y-4">
{#if panel === 'devices'}
<div class="grid gap-4 lg:grid-cols-2">
<Card class="space-y-5"
><SectionTitle title="Device connections" description="Connect hardware through the native desktop bridge." />
<div class="space-y-3">
<div class="flex items-center gap-3 rounded-md border border-border bg-bg p-3">
<Cable class="size-4 text-primary" />
<div class="flex-1">
<p class="text-sm font-medium text-fg">Serial / TCode</p>
<p class="text-xs text-muted-fg">Waiting for a local driver</p>
</div>
<Badge>Offline</Badge>
</div>
<div class="flex items-center gap-3 rounded-md border border-border bg-bg p-3">
<Bluetooth class="size-4 text-primary" />
<div class="flex-1">
<p class="text-sm font-medium text-fg">Bluetooth devices</p>
<p class="text-xs text-muted-fg">Native discovery is available after launch</p>
</div>
<Badge>Offline</Badge>
</div>
</div></Card
><Card class="space-y-5"
><SectionTitle
title="Safety"
description="The desktop client keeps device output disabled until a connection is explicitly enabled."
/>
<div class="flex items-start gap-3 rounded-md border border-success/25 bg-success/10 p-3">
<CheckCircle2 class="mt-0.5 size-4 text-success" />
<p class="text-sm leading-6 text-fg">
No device is currently receiving output. Connect a driver from the native controls to enable playback
synchronization.
</p>
</div></Card
>
</div>
{:else if panel === 'settings'}
<Card class="space-y-5"
><SectionTitle
title="Application preferences"
description="Native renderer settings remain available from the desktop client bridge."
/>
<div class="grid gap-4 sm:grid-cols-2">
<label class="space-y-2 text-sm"
><span class="font-medium text-fg">Theme</span><select class="field"
><option>System</option><option>Dark</option><option>Light</option></select
></label
><label class="space-y-2 text-sm"
><span class="font-medium text-fg">Control mode</span><select class="field"
><option>Local player</option><option>Remote player</option></select
></label
>
</div>
<Button variant="secondary"><Settings2 class="size-4" />Open native preferences</Button></Card
>
{:else}
<div class="grid gap-4 xl:grid-cols-[minmax(0,1fr)_340px]">
<Card class="space-y-5"
><SectionTitle
title="Embedded player"
description="The desktop shell embeds MediaViewer when a server is connected."
/>
<div class="flex min-h-[420px] items-center justify-center rounded-lg border border-dashed border-border bg-bg">
<EmptyState
title="Connect a MediaViewer server"
message="Enter a server URL in the native desktop panel to load the library and player."
/>
</div></Card
><Card class="space-y-5"
><SectionTitle
title="Playback status"
description="The native bridge reports the active media and sync state here."
/>
<div class="space-y-3">
<div class="flex items-center gap-3 rounded-md border border-border bg-bg p-3">
<MonitorPlay class="size-4 text-primary" />
<div>
<p class="text-sm font-medium text-fg">No active media</p>
<p class="text-xs text-muted-fg">Player status will appear after connection.</p>
</div>
</div>
<Button variant="secondary" class="w-full"><SlidersHorizontal class="size-4" />Open player controls</Button>
</div></Card
>
</div>
{/if}
</div>
@@ -2,10 +2,7 @@
import { page } from '$app/state'
import { Film, Music2, Play } from '@lucide/svelte'
import { get } from '$lib/api'
import EmptyState from '$lib/components/EmptyState.svelte'
import Badge from '$lib/components/ui/badge.svelte'
import Button from '$lib/components/ui/button.svelte'
import Card from '$lib/components/ui/card.svelte'
import { Badge, Button, Card, EmptyState } from '@gabriel20xx/web-ui'
interface FeedItem {
mediaKey?: string
@@ -104,7 +101,7 @@
{item.title || item.name || item.filename || 'Untitled media'}
</p>
<div class="mt-1 flex flex-wrap items-center gap-2 text-xs text-muted-fg">
{#if item.mediaType}<Badge tone="neutral">{item.mediaType}</Badge>{/if}
{#if item.mediaType}<Badge>{item.mediaType}</Badge>{/if}
{#if item.category}<span>{item.category}</span>{/if}
{#if item.filename}<span class="truncate">{item.filename}</span>{/if}
</div>
@@ -2,11 +2,7 @@
import { Maximize2, Pause, Play, Settings2, Wifi, WifiOff } from '@lucide/svelte'
import { onMount } from 'svelte'
import { get } from '$lib/api'
import SectionTitle from '$lib/components/SectionTitle.svelte'
import Card from '$lib/components/ui/card.svelte'
import Button from '$lib/components/ui/button.svelte'
import Badge from '$lib/components/ui/badge.svelte'
import Metric from '$lib/components/ui/metric.svelte'
import { Badge, Button, Card, Metric, SectionTitle } from '@gabriel20xx/web-ui'
type KioskConfig = {
defaultDisplayDuration?: number
@@ -126,7 +122,7 @@
class="flex flex-wrap justify-end gap-2"
aria-label={panel === 'kiosk' ? 'Kiosk controls' : 'Kiosk display controls'}
>
<Badge tone={connected ? 'success' : 'warning'}
<Badge variant={connected ? 'success' : 'warning'}
>{#if connected}<Wifi class="mr-1 size-3" />Connected{:else}<WifiOff class="mr-1 size-3" />Waiting{/if}</Badge
>
<Button variant="secondary" size="sm" onclick={() => void fullscreen()}
@@ -137,7 +133,7 @@
{error}
</div>{/if}
<div class="grid gap-4 sm:grid-cols-3">
<Metric label="Queue" value={queueLength} detail="Images waiting to display" tone="primary" /><Metric
<Metric label="Queue" value={queueLength} detail="Images waiting to display" variant="primary" /><Metric
label="Display time"
value={durationLabel}
detail="Current server interval"
@@ -2,14 +2,10 @@
import { AlertTriangle, Play, RefreshCw, Trash2 } from '@lucide/svelte'
import { onDestroy, onMount } from 'svelte'
import { SvelteSet } from 'svelte/reactivity'
import { notify } from '@gabriel20xx/web-ui'
import { Button, Card, Metric, notify, SectionTitle } from '@gabriel20xx/web-ui'
import { get, post } from '$lib/api'
import AnalyzerHistory from '$lib/components/AnalyzerHistory.svelte'
import PipelineFlowDiagram from '$lib/components/PipelineFlowDiagram.svelte'
import SectionTitle from '$lib/components/SectionTitle.svelte'
import Card from '$lib/components/ui/card.svelte'
import Button from '$lib/components/ui/button.svelte'
import Metric from '$lib/components/ui/metric.svelte'
import { cn } from '$lib/utils/cn'
type MediaType = 'image' | 'video' | 'audio' | 'funscript'
@@ -412,7 +408,7 @@
label="Errors"
value={stageSummaries.reduce((sum, stage) => sum + stage.errors, 0)}
detail="Needs attention"
tone="danger"
variant="danger"
/>
</div>
@@ -1,14 +1,8 @@
<script lang="ts">
import { BarChart3, Check, Pencil, ShieldCheck, Trash2, UserCheck, Users } from '@lucide/svelte'
import { onMount } from 'svelte'
import { notify } from '@gabriel20xx/web-ui'
import { Badge, Button, Card, EmptyState, Metric, notify, SectionTitle } from '@gabriel20xx/web-ui'
import { get, post, put } from '$lib/api'
import SectionTitle from '$lib/components/SectionTitle.svelte'
import Card from '$lib/components/ui/card.svelte'
import Button from '$lib/components/ui/button.svelte'
import Badge from '$lib/components/ui/badge.svelte'
import Metric from '$lib/components/ui/metric.svelte'
import EmptyState from '$lib/components/EmptyState.svelte'
interface UserRow {
id: string | number
@@ -183,11 +177,11 @@
<Metric label="Users" value={users.length} detail="Loaded from admin catalog" /><Metric
label="Active users"
value={users.filter((user) => !user.disabled).length}
tone="success"
variant="success"
/><Metric label="Media records" value={media.length} detail="Catalog window" /><Metric
label="Flagged / inactive"
value={media.filter((item) => item.active === false).length}
tone="warning"
variant="warning"
/>
</div>
<div class="grid gap-4 lg:grid-cols-2">
@@ -231,7 +225,7 @@
</div>
</div>
<div class="flex flex-wrap gap-2 border-y border-border py-3">
<Badge tone="primary">{selectedUsers.length} selected</Badge><Button
<Badge variant="primary">{selectedUsers.length} selected</Badge><Button
size="sm"
variant="secondary"
disabled={!selectedUsers.length}
@@ -329,11 +323,11 @@
><p class="text-sm font-medium text-fg">{user.username || user.email || `User ${user.id}`}</p>
<p class="mt-1 text-xs text-muted-fg">{user.email || 'No email'}</p></td
><td class="py-3"
><Badge tone={user.role === 'admin' || user.role === 'superadmin' ? 'primary' : 'neutral'}
><Badge variant={user.role === 'admin' || user.role === 'superadmin' ? 'primary' : 'default'}
>{user.role || 'user'}</Badge
></td
><td class="py-3"
><Badge tone={user.disabled ? 'danger' : 'success'}>{user.disabled ? 'Disabled' : 'Active'}</Badge
><Badge variant={user.disabled ? 'danger' : 'success'}>{user.disabled ? 'Disabled' : 'Active'}</Badge
></td
><td class="py-3 text-xs text-muted-fg">{user.mfaEnabled ? 'MFA enabled' : 'MFA not enabled'}</td><td
class="py-3 text-right"
@@ -445,7 +439,7 @@
</div>
</div>
<div class="flex flex-wrap gap-2 border-y border-border py-3">
<Badge tone="primary">{selectedMedia.length} selected</Badge><Button
<Badge variant="primary">{selectedMedia.length} selected</Badge><Button
size="sm"
variant="secondary"
disabled={!selectedMedia.length}
@@ -489,7 +483,7 @@
><td class="py-3 text-xs text-muted-fg">{item.source || '—'}</td><td
class="py-3 text-xs text-muted-fg">{item.generatorUsername || '—'}</td
><td class="py-3"
><Badge tone={item.active === false ? 'danger' : 'success'}
><Badge variant={item.active === false ? 'danger' : 'success'}
>{item.active === false ? 'Hidden' : 'Visible'}</Badge
></td
></tr
@@ -2,11 +2,7 @@
import { Database, FileClock, FolderOpen, HardDrive, Server, ShieldAlert } from '@lucide/svelte'
import { onMount } from 'svelte'
import { get } from '$lib/api'
import SectionTitle from '$lib/components/SectionTitle.svelte'
import Card from '$lib/components/ui/card.svelte'
import Badge from '$lib/components/ui/badge.svelte'
import Metric from '$lib/components/ui/metric.svelte'
import EmptyState from '$lib/components/EmptyState.svelte'
import { Badge, Card, EmptyState, Metric, SectionTitle } from '@gabriel20xx/web-ui'
type Json = Record<string, unknown>
type FileRow = { rel?: string; name?: string; path?: string; mtime?: number; size?: number; type?: string }
@@ -92,7 +88,7 @@
label="Requests"
value={value(stats, 'requests', 'totalRequests')}
detail="Tracked requests"
tone="primary"
variant="primary"
/><Metric
label="Active mounts"
value={value(mounts, 'count', 'total', 'active')}
@@ -101,7 +97,7 @@
label="Bytes out"
value={formatBytes(bandwidth.bytesOut || bandwidth.egress)}
detail="Current tracker window"
tone="success"
variant="success"
/><Metric label="Updated" value={lastUpdated || '--'} detail={loading ? 'Refreshing' : 'Live snapshot'} />
</div>
@@ -150,7 +146,7 @@
</p>
</div>
</div>
<Badge tone="success">Mapped</Badge>
<Badge variant="success">Mapped</Badge>
</div>{/each}
</div>{/if}</Card
><Card class="space-y-5"
@@ -3,10 +3,7 @@
import { ArrowLeft, ChevronLeft, ChevronRight, Image, Search, Tags as TagsIcon } from '@lucide/svelte'
import { onMount } from 'svelte'
import { get } from '$lib/api'
import EmptyState from '$lib/components/EmptyState.svelte'
import Badge from '$lib/components/ui/badge.svelte'
import Button from '$lib/components/ui/button.svelte'
import Card from '$lib/components/ui/card.svelte'
import { Badge, Button, Card, EmptyState } from '@gabriel20xx/web-ui'
interface TagSummary {
tag: string
@@ -169,7 +166,7 @@
{:else}
<Image class="size-10 text-muted-fg" />
{/if}
{#if media.mediaType}<Badge tone="neutral" class="absolute left-2 top-2">{media.mediaType}</Badge>{/if}
{#if media.mediaType}<Badge class="absolute left-2 top-2">{media.mediaType}</Badge>{/if}
</div>
<div class="p-3">
<p class="truncate text-sm font-medium text-fg">{media.name || media.filename || 'Untitled media'}</p>
@@ -1,14 +1,8 @@
<script lang="ts">
import { Activity, ArrowRight, CheckCircle2, CloudDownload, Film, Upload, WandSparkles, X } from '@lucide/svelte'
import { onMount } from 'svelte'
import { notify } from '@gabriel20xx/web-ui'
import { Badge, Button, Card, EmptyState, Metric, notify, SectionTitle } from '@gabriel20xx/web-ui'
import { get, post } from '$lib/api'
import SectionTitle from '$lib/components/SectionTitle.svelte'
import Card from '$lib/components/ui/card.svelte'
import Button from '$lib/components/ui/button.svelte'
import Badge from '$lib/components/ui/badge.svelte'
import Metric from '$lib/components/ui/metric.svelte'
import EmptyState from '$lib/components/EmptyState.svelte'
type Json = Record<string, unknown>
@@ -258,7 +252,7 @@
label="Active queue"
value={queue.length}
detail="Waiting or running"
tone={queue.length ? 'warning' : 'default'}
variant={queue.length ? 'warning' : 'default'}
/><Metric label="Recent jobs" value={jobs.length} detail="Retained workflow history" /><Metric
label="Schedules"
value={schedules.length}
@@ -286,7 +280,7 @@
<div>
<div class="flex items-center gap-2">
<p class="text-sm font-medium text-fg">{schedule.name || schedule.tool || 'Workflow schedule'}</p>
<Badge tone={schedule.enabled === false ? 'neutral' : 'success'}
<Badge variant={schedule.enabled === false ? 'default' : 'success'}
>{schedule.enabled === false ? 'Paused' : 'Enabled'}</Badge
>
</div>
@@ -456,7 +450,7 @@
<div class="flex items-center justify-between gap-2">
<p class="truncate text-sm font-medium text-fg">{job.tool || 'workflow'}</p>
<Badge
tone={job.status === 'completed' || job.status === 'complete'
variant={job.status === 'completed' || job.status === 'complete'
? 'success'
: job.status === 'error'
? 'danger'
@@ -2,9 +2,7 @@
import { ArrowLeft, Film, Maximize2, Minimize2, Pause, Play, Wifi, WifiOff } from '@lucide/svelte'
import { onMount } from 'svelte'
import { get } from '$lib/api'
import Badge from '$lib/components/ui/badge.svelte'
import Button from '$lib/components/ui/button.svelte'
import Card from '$lib/components/ui/card.svelte'
import { Badge, Button, Card } from '@gabriel20xx/web-ui'
type SyncMode = 'none' | 'local' | 'master' | 'slave'
@@ -770,9 +768,9 @@
<track kind="captions" srclang="en" label="Captions" src="data:text/vtt,WEBVTT" />
</video>
<div class="absolute left-3 top-3 z-10 flex flex-wrap gap-2">
{#if info.isVr}<Badge tone="primary">VR</Badge>{/if}
{#if hasFunscript}<Badge tone="success">Funscript</Badge>{/if}
{#if syncMode === 'slave'}<Badge tone="warning">Slave</Badge>{/if}
{#if info.isVr}<Badge variant="primary">VR</Badge>{/if}
{#if hasFunscript}<Badge variant="success">Funscript</Badge>{/if}
{#if syncMode === 'slave'}<Badge variant="warning">Slave</Badge>{/if}
</div>
{#if graphPath}
<div
@@ -836,7 +834,7 @@
<h2 class="text-sm font-medium text-fg">Funscript Info</h2>
<p class="mt-1 text-xs text-muted-fg">Action data and playback position for this video.</p>
</div>
{#if hasFunscript}<Badge tone="success">Available</Badge>{:else}<Badge tone="neutral">None</Badge>{/if}
{#if hasFunscript}<Badge variant="success">Available</Badge>{:else}<Badge>None</Badge>{/if}
</div>
{#if hasFunscript}
<div class="grid gap-2 sm:grid-cols-2">
@@ -954,8 +952,8 @@
<h2 class="text-sm font-medium text-fg">Sync Info</h2>
<p class="mt-1 text-xs text-muted-fg">Connect this player to other MediaViewer endpoints.</p>
</div>
{#if syncConnected}<Badge tone="success"><Wifi class="mr-1 size-3" />Connected</Badge>{:else}<Badge
tone="warning"><WifiOff class="mr-1 size-3" />Disconnected</Badge
{#if syncConnected}<Badge variant="success"><Wifi class="mr-1 size-3" />Connected</Badge>{:else}<Badge
variant="warning"><WifiOff class="mr-1 size-3" />Disconnected</Badge
>{/if}
</div>
@@ -5,10 +5,7 @@
import { onMount } from 'svelte'
import { SvelteURLSearchParams } from 'svelte/reactivity'
import { get } from '$lib/api'
import EmptyState from '$lib/components/EmptyState.svelte'
import Button from '$lib/components/ui/button.svelte'
import Card from '$lib/components/ui/card.svelte'
import Badge from '$lib/components/ui/badge.svelte'
import { Badge, Button, Card, EmptyState } from '@gabriel20xx/web-ui'
interface MediaItem {
id: string
@@ -279,7 +276,7 @@
<div class="min-w-0">
<div class="flex flex-wrap items-center gap-2">
<p class="text-sm font-medium text-fg">Filters</p>
{#if activeFilterCount() > 0}<Badge tone="primary">{activeFilterCount()} active</Badge>{/if}
{#if activeFilterCount() > 0}<Badge variant="primary">{activeFilterCount()} active</Badge>{/if}
</div>
<p class="mt-1 text-xs text-muted-fg">
{activeFilterCount() > 0
@@ -462,8 +459,8 @@
/>{:else}<div class="flex h-full items-center justify-center text-muted-fg">
{#if item.mediaType === 'audio'}<Music2 class="size-10" />{:else}<Film class="size-10" />{/if}
</div>{/if}
<span class="absolute left-2 top-2"><Badge tone="neutral">{item.mediaType}</Badge></span>
{#if item.isVr}<span class="absolute right-2 top-2"><Badge tone="primary">VR</Badge></span>{/if}
<span class="absolute left-2 top-2"><Badge>{item.mediaType}</Badge></span>
{#if item.isVr}<span class="absolute right-2 top-2"><Badge variant="primary">VR</Badge></span>{/if}
<span class="absolute bottom-2 right-2 rounded bg-black/70 px-1.5 py-0.5 text-[11px] text-white"
>{formatDuration(item.durationMs)}</span
>
-17
View File
@@ -1,17 +0,0 @@
export type StatusLevel = 'checking' | 'healthy' | 'degraded' | 'offline'
export interface StatusProbe {
path: string
ok: boolean
httpStatus: number | null
service: string | null
error: string | null
}
export interface StatusSnapshot {
level: StatusLevel
health: StatusProbe | null
readiness: StatusProbe | null
checkedAt: string | null
loading: boolean
}
+1 -1
View File
@@ -1,4 +1,4 @@
export type AppId = 'viewer' | 'tools' | 'analyzer' | 'config' | 'moderator' | 'kiosk' | 'servant' | 'desktop'
export type AppId = 'viewer' | 'tools' | 'analyzer' | 'config' | 'moderator' | 'kiosk' | 'servant'
export type ProjectIconName =
'image' | 'monitor-play' | 'play' | 'scan-search' | 'server' | 'settings-2' | 'shield-check' | 'wand-sparkles'
+9
View File
@@ -26,9 +26,18 @@
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
<junit.version>5.10.2</junit.version>
<!-- Pinned to match MegaBasterd/pom.xml's jackson-databind version - both
poms compile the exact same AuthClient.java, which now builds/parses
JSON via Jackson for its full (non-validate-only) method surface. -->
<jackson.version>2.18.6</jackson.version>
</properties>
<dependencies>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>${jackson.version}</version>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
@@ -1,13 +1,21 @@
package com.gabriel20xx.shared.auth;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.function.Function;
import java.util.function.Supplier;
import java.util.regex.Matcher;
@@ -18,49 +26,71 @@ import java.util.regex.Pattern;
* AuthGuard instance instead of embedding its own local user table.
*
* <p>A service that switches to AuthGuard trades "its own local user table"
* for "one HTTP call per request to AuthGuard's {@code /api/session/validate}",
* gaining a single shared identity across every project that does the same.
* Mirrors {@code shared/backend/authclient} (Go, {@code client.go}) and
* {@code shared/packages/node-backend/src/authclient.js} (Node) - keep the
* three in sync if any of them changes shape. This package is additive: no
* project is wired up to use it automatically just because this class
* exists.
* for "HTTP calls to AuthGuard's API", gaining a single shared identity
* across every project that does the same. Mirrors
* {@code shared/backend/authclient} (Go, {@code client.go}),
* {@code shared/packages/node-backend/src/authclient.js} (Node), and
* {@code shared/packages/python-backend/src/shared_backend/authclient.py}
* (Python) - keep all four in sync if any of them changes shape.
*
* <h2>Two deliberate deviations from the task-literal Java 11+/record design</h2>
* <p>Two kinds of consumer, two parts of this class:
* <ul>
* <li>A service that only needs to gate requests behind "is this a valid
* AuthGuard session" uses {@link #validate(String)} /
* {@link #extractToken} / {@link #middleware}, calling only
* {@code GET /api/session/validate}. This is the original, minimal
* surface of this class.</li>
* <li>A service that runs its own login/register/admin-user-management
* screens proxied to AuthGuard (mirroring the Go/Node/Python clients'
* full method set - see e.g.
* {@code Original/GameStream/backend/cmd/gamestreamd/auth.go} for the
* reference Go implementation of this pattern; MegaBasterd's own
* migration, {@code WebServer.java}, is the reference Java one) uses
* the additional methods below: {@link #register}, {@link #login},
* {@link #logout}, {@link #me}, {@code totpEnable}/{@code Verify}/
* {@code Disable}, {@code requestPasswordReset}/
* {@code confirmPasswordReset}, {@code list}/{@code create}/
* {@code update}/{@code deleteManagedUser}, {@link #setupStatus}.</li>
* </ul>
*
* <h2>Deliberate deviations from the task-literal Java 11+/record design</h2>
*
* <p>This class intentionally targets Java 8 source/binary compatibility -
* it uses {@link java.net.HttpURLConnection} rather than
* {@code java.net.http.HttpClient} (added in Java 11), and a plain nested
* final class ({@link User}) rather than a Java {@code record} (added in
* Java 16) - and hand-parses AuthGuard's small, fixed JSON response shape
* rather than depending on Jackson/Gson. Both choices are ground-truth
* driven, not stylistic:
* {@code java.net.http.HttpClient} (added in Java 11), and plain nested
* final classes ({@link User}, {@link PublicUser}, etc.) rather than a Java
* {@code record} (added in Java 16). This is ground-truth driven, not
* stylistic: java-backend has no build file of its own (unlike its
* {@code node-backend}/{@code python-backend} siblings, which have a
* {@code package.json}/{@code pyproject.toml}). Its <em>only</em> verified
* real consumer, MegaBasterd, compiles this exact source directory straight
* into its own build via the {@code build-helper-maven-plugin}
* "add-shared-java-auth" execution in {@code MegaBasterd/pom.xml}, which
* pins {@code <maven.compiler.source>}/{@code <target>} to {@code 1.8}. Java
* 11 APIs or {@code record} syntax here would fail to compile in that real
* build, or fail at runtime on an actual Java 8 JVM even if it happened to
* compile. A standalone {@code pom.xml} was added to this package purely so
* this class can be built and tested in isolation (see this package's
* README); it targets Java 8 for the same reason.
*
* <ul>
* <li>java-backend has no build file of its own (unlike its
* {@code node-backend}/{@code python-backend} siblings, which have a
* {@code package.json}/{@code pyproject.toml}). Its <em>only</em>
* verified real consumer, MegaBasterd, compiles this exact source
* directory straight into its own build via the
* {@code build-helper-maven-plugin} "add-shared-java-auth" execution
* in {@code MegaBasterd/pom.xml}, which pins
* {@code <maven.compiler.source>}/{@code <target>} to {@code 1.8}.
* Java 11 APIs or {@code record} syntax here would fail to compile in
* that real build, or fail at runtime on an actual Java 8 JVM even if
* it happened to compile. A standalone {@code pom.xml} was added to
* this package purely so this class can be built and tested in
* isolation (see this package's README); it targets Java 8 for the
* same reason.</li>
* <li>{@code ResetManager}, {@code Roles}, and {@code Totp} - the only
* other classes in this package - have zero runtime dependencies
* beyond the JDK. Requiring Jackson/Gson here would make this the one
* class in java-backend that forces a dependency onto every consumer,
* even ones (unlike MegaBasterd) that don't already carry a JSON
* library. AuthGuard's response shape is small and fixed
* ({@code {"valid":bool,"user_id":number,"username":string,"role":string}}),
* so it is parsed defensively with a few targeted regular expressions
* instead.</li>
* </ul>
* <p>{@link #validate(String)} still hand-parses AuthGuard's small, fixed
* {@code GET /api/session/validate} response shape with a few targeted
* regular expressions rather than Jackson, keeping the minimal
* validate-only surface dependency-free beyond the JDK - {@code ResetManager},
* {@code Roles}, and {@code Totp}, the other classes in this package, stay
* that way too. The full-proxy methods added below (register/login/setup/
* reset/admin-user-management) are a different tradeoff: they must both
* build and parse a handful of small JSON request/response bodies, which
* would be considerably worse hand-rolled than {@code validate}'s
* fixed-shape parsing, so they use Jackson ({@code jackson-databind})
* instead. This makes {@code jackson-databind} a compile-time dependency of
* this whole class (Java has no way to make an import conditional on which
* methods a given consumer actually calls) - acceptable here because
* MegaBasterd, this package's only verified consumer, already depends on
* Jackson for its own code. A hypothetical future consumer that only ever
* calls {@code validate}/{@code middleware} and doesn't already carry
* Jackson would need to add it just to compile this file; that tradeoff was
* chosen deliberately over hand-rolling JSON request bodies with regex.
*/
public final class AuthClient {
@@ -74,6 +104,9 @@ public final class AuthClient {
private static final Pattern ROLE_PATTERN = Pattern.compile("\"role\"\\s*:\\s*\"((?:[^\"\\\\]|\\\\.)*)\"");
private static final String BEARER_PREFIX = "Bearer ";
/** Used only by the full-proxy methods below; see the class javadoc's Jackson tradeoff note. */
private static final ObjectMapper JSON = new ObjectMapper();
private final String baseUrl;
private final String cookieName;
private final int timeoutMillis;
@@ -220,6 +253,403 @@ public final class AuthClient {
}
}
// --- Full API surface ---------------------------------------------------
//
// validate/middleware above are all a service needs when it only ever
// forwards an already-established AuthGuard session to check it's still
// valid. A service that used to run its own local register/login/logout/
// TOTP/password-reset/admin-user-management flow and is migrating that
// flow onto AuthGuard instead needs to originate those same calls
// itself - that's what the rest of this class adds. Every method mirrors
// one of AuthGuard's internal/httpapi handlers exactly (method, path,
// request/response JSON shape) - see the Go client (client.go) this was
// ported from for the source of truth.
//
// Cookie forwarding: register() and login() both return the Set-Cookie
// header value(s) AuthGuard's response carried, as SessionResult.cookies
// (logout() returns them directly). A service proxying its own e.g.
// POST /login to AuthGuard's POST /api/login should generally pass these
// straight through to its own response (e.g.
// exchange.getResponseHeaders().add("Set-Cookie", cookie) for each
// value): the browser then transparently holds AuthGuard's own
// auth_session cookie, and every subsequent request's session token is
// that same cookie value - no separate mapping between "the proxying
// service's own session cookie" and "the AuthGuard token" is needed
// anywhere. A service adopting this pattern should stop minting a
// session cookie of its own and read/forward the incoming auth_session
// cookie the same way middleware/extractToken does.
/**
* The account {@link #register}/{@link #login}/{@link #me} return. Deliberately
* distinct from the slimmer {@link User} type {@link #validate}/{@link #middleware}
* use (which mirrors {@code GET /api/session/validate}'s smaller shape and does not
* carry TOTP status at all).
*/
public static final class PublicUser {
public final long id;
public final String username;
public final String email;
public final String role;
public final boolean totpEnabled;
public PublicUser(long id, String username, String email, String role, boolean totpEnabled) {
this.id = id;
this.username = username == null ? "" : username;
this.email = email == null ? "" : email;
this.role = role == null ? "" : role;
this.totpEnabled = totpEnabled;
}
}
/** One row of {@code GET /api/admin/users}, and the payload {@link #createManagedUser} returns. */
public static final class ManagedUser {
public final long id;
public final String username;
public final String email;
public final String role;
/** Raw ISO-8601 timestamp string as AuthGuard returns it - not parsed, to avoid a java.time/Jackson-datatype dependency for one display field. */
public final String createdAt;
public ManagedUser(long id, String username, String email, String role, String createdAt) {
this.id = id;
this.username = username == null ? "" : username;
this.email = email == null ? "" : email;
this.role = role == null ? "" : role;
this.createdAt = createdAt == null ? "" : createdAt;
}
}
/** Returned by {@link #register} and {@link #login}: the resolved account, plus the Set-Cookie header value(s) the response carried. */
public static final class SessionResult {
public final PublicUser user;
public final List<String> cookies;
public SessionResult(PublicUser user, List<String> cookies) {
this.user = user;
this.cookies = cookies;
}
}
/** Returned by {@link #totpEnable}: a freshly provisioned, not yet active TOTP secret and its otpauth:// URI. Confirm it with {@link #totpVerify}. */
public static final class TOTPEnableResult {
public final String secret;
public final String otpauthUrl;
public final boolean enabled;
public TOTPEnableResult(String secret, String otpauthUrl, boolean enabled) {
this.secret = secret == null ? "" : secret;
this.otpauthUrl = otpauthUrl == null ? "" : otpauthUrl;
this.enabled = enabled;
}
}
/**
* Body of {@link #createManagedUser} ({@code POST /api/admin/users}) and
* {@link #updateManagedUser} ({@code PUT /api/admin/users/{id}}). On update, a
* {@code null}/blank {@code username}/{@code email}/{@code password} field means
* "leave unchanged" (AuthGuard applies only non-empty fields); {@code role} is
* only honored when {@code null} is not passed and AuthGuard's own authorization
* rules let the caller reassign it (only a superadmin actor, and never onto/away
* from a superadmin target) - this class does not re-implement or pre-validate
* those rules.
*/
public static final class ManagedUserInput {
public final String username;
public final String email;
public final String password;
public final String role;
public ManagedUserInput(String username, String email, String password, String role) {
this.username = username;
this.email = email;
this.password = password;
this.role = role;
}
}
/**
* Thrown when AuthGuard responds with a non-2xx status to one of the
* register/login/.../setupStatus methods (not thrown by {@link #validate}, which
* uses {@link InvalidSessionException} for its one specific non-2xx case). Carries
* the status code and (when AuthGuard's JSON body decoded successfully) its
* {@code {"error": "..."}} message, so a caller can map it back onto its own
* service's response shape/status code rather than exposing AuthGuard's wording
* verbatim.
*/
public static final class APIError extends IOException {
public final int statusCode;
/**
* Set only by {@link #login}, mirroring AuthGuard's {@code {"totp_required": true}}
* flag on a 401 that means "credentials were correct, but this account has
* two-factor auth enabled and no (or an incorrect) code was supplied" - distinct
* from a plain invalid-credentials 401.
*/
public final boolean totpRequired;
public APIError(int statusCode, String message, boolean totpRequired) {
super("authclient: authguard responded " + statusCode + ": " + message);
this.statusCode = statusCode;
this.totpRequired = totpRequired;
}
}
/**
* Calls {@code GET /api/setup-status}, an unauthenticated endpoint that reports
* whether AuthGuard has any account at all. Accounts are centralized in AuthGuard,
* so a caller with its own "first launch, create the initial admin" flow should
* consult this first: when it reports {@code false}, some account already exists
* (possibly created by a different project, or directly against AuthGuard), and the
* caller should show its ordinary login screen instead of its own account-creation form.
*/
public boolean setupStatus() throws IOException {
JsonNode node = JSON.readTree(call("GET", "/api/setup-status", "", null).body);
return node.path("setup_required").asBoolean(false);
}
/** Calls {@code POST /api/register}, creating a new AuthGuard account and starting a session for it. */
public SessionResult register(String username, String email, String password) throws IOException {
ObjectNode body = JSON.createObjectNode();
body.put("username", username);
body.put("email", email);
body.put("password", password);
CallResult result = call("POST", "/api/register", "", body);
return new SessionResult(parsePublicUser(JSON.readTree(result.body).path("user")), result.cookies);
}
/**
* Calls {@code POST /api/login}. {@code totpToken} may be empty; AuthGuard raises an
* {@link APIError} with {@link APIError#totpRequired} set when the account has
* two-factor auth enabled and no valid code was supplied.
*/
public SessionResult login(String usernameOrEmail, String password, String totpToken) throws IOException {
ObjectNode body = JSON.createObjectNode();
body.put("username_or_email", usernameOrEmail);
body.put("password", password);
if (totpToken != null && !totpToken.isEmpty()) {
body.put("totp_token", totpToken);
}
CallResult result = call("POST", "/api/login", "", body);
return new SessionResult(parsePublicUser(JSON.readTree(result.body).path("user")), result.cookies);
}
/**
* Calls {@code POST /api/logout}, deleting the session identified by {@code token}
* server-side. Returns the (cookie-clearing) Set-Cookie header value(s) AuthGuard's
* response carried.
*/
public List<String> logout(String token) throws IOException {
return call("POST", "/api/logout", token, null).cookies;
}
/** Calls {@code GET /api/me}, resolving {@code token} to its account. */
public PublicUser me(String token) throws IOException {
return parsePublicUser(JSON.readTree(call("GET", "/api/me", token, null).body).path("user"));
}
/**
* Calls {@code POST /api/totp/enable}, provisioning (or re-provisioning) a pending
* TOTP secret for {@code token}'s account. The secret is not active until
* {@link #totpVerify} confirms a generated code.
*/
public TOTPEnableResult totpEnable(String token) throws IOException {
JsonNode node = JSON.readTree(call("POST", "/api/totp/enable", token, null).body);
return new TOTPEnableResult(node.path("secret").asText(""), node.path("otpauth_url").asText(""), node.path("enabled").asBoolean(false));
}
/** Calls {@code POST /api/totp/verify}, confirming {@code code} against the pending secret {@link #totpEnable} provisioned and activating two-factor auth. */
public void totpVerify(String token, String code) throws IOException {
ObjectNode body = JSON.createObjectNode();
body.put("token", code);
call("POST", "/api/totp/verify", token, body);
}
/** Calls {@code POST /api/totp/disable}, turning two-factor auth off for {@code token}'s account. AuthGuard requires {@code code} to be one last valid TOTP code as proof of possession. */
public void totpDisable(String token, String code) throws IOException {
ObjectNode body = JSON.createObjectNode();
body.put("token", code);
call("POST", "/api/totp/disable", token, body);
}
/**
* Calls {@code POST /api/password-reset/request}. AuthGuard prints a one-time code
* to its own process console; only an operator with access to that console can relay
* it onward. Called with a blank {@code usernameOrEmail}, the target is AuthGuard's
* superadmin account - AuthGuard's own web UI is the intended place to drive this,
* not an individual project.
*/
public void requestPasswordReset(String usernameOrEmail) throws IOException {
ObjectNode body = JSON.createObjectNode();
body.put("username_or_email", usernameOrEmail == null ? "" : usernameOrEmail);
call("POST", "/api/password-reset/request", "", body);
}
/** Calls {@code POST /api/password-reset/confirm} with the code an operator relayed out-of-band and a new password, and invalidates every existing session for that account. */
public void confirmPasswordReset(String code, String newPassword) throws IOException {
ObjectNode body = JSON.createObjectNode();
body.put("code", code);
body.put("password", newPassword);
call("POST", "/api/password-reset/confirm", "", body);
}
/** Calls {@code GET /api/admin/users}. {@code token}'s account must satisfy AuthGuard's CanManageUsers check (admin or superadmin), or this throws an {@link APIError} with statusCode 401/403. */
public List<ManagedUser> listManagedUsers(String token) throws IOException {
JsonNode usersNode = JSON.readTree(call("GET", "/api/admin/users", token, null).body).path("users");
List<ManagedUser> users = new ArrayList<ManagedUser>();
if (usersNode.isArray()) {
for (JsonNode node : usersNode) {
users.add(parseManagedUser(node));
}
}
return users;
}
/** Calls {@code POST /api/admin/users}. Only a superadmin actor may set {@code role} to anything other than "user"; anyone else's requested role is silently ignored by AuthGuard. */
public ManagedUser createManagedUser(String token, ManagedUserInput input) throws IOException {
CallResult result = call("POST", "/api/admin/users", token, managedUserInputToJson(input));
return parseManagedUser(JSON.readTree(result.body).path("user"));
}
/** Calls {@code PUT /api/admin/users/{id}}; see {@link ManagedUserInput}'s doc comment. */
public void updateManagedUser(String token, long id, ManagedUserInput input) throws IOException {
call("PUT", "/api/admin/users/" + id, token, managedUserInputToJson(input));
}
/** Calls {@code DELETE /api/admin/users/{id}}. */
public void deleteManagedUser(String token, long id) throws IOException {
call("DELETE", "/api/admin/users/" + id, token, null);
}
private static PublicUser parsePublicUser(JsonNode node) {
return new PublicUser(
node.path("id").asLong(0),
node.path("username").asText(""),
node.path("email").asText(""),
node.path("role").asText(""),
node.path("totp_enabled").asBoolean(false));
}
private static ManagedUser parseManagedUser(JsonNode node) {
return new ManagedUser(
node.path("id").asLong(0),
node.path("username").asText(""),
node.path("email").asText(""),
node.path("role").asText(""),
node.path("created_at").asText(""));
}
private static ObjectNode managedUserInputToJson(ManagedUserInput input) {
ObjectNode body = JSON.createObjectNode();
if (input.username != null && !input.username.isEmpty()) {
body.put("username", input.username);
}
if (input.email != null && !input.email.isEmpty()) {
body.put("email", input.email);
}
if (input.password != null && !input.password.isEmpty()) {
body.put("password", input.password);
}
if (input.role != null) {
body.put("role", input.role);
}
return body;
}
/** The decoded JSON response body plus any Set-Cookie header value(s); see {@link #call}. */
private static final class CallResult {
private final String body;
private final List<String> cookies;
private CallResult(String body, List<String> cookies) {
this.body = body;
this.cookies = cookies;
}
}
/**
* Runs one JSON request/response round trip against AuthGuard: builds a JSON request
* (skipped when {@code body} is {@code null}), attaches {@code token} as a Bearer
* credential (skipped when {@code token} is blank), and returns the decoded response
* body text plus any Set-Cookie header value(s). Throws {@link APIError} for a
* non-2xx response, a plain {@link IOException} for a transport failure - mirrors Go's
* {@code Client.call}/Node's {@code AuthClient#_call}/Python's {@code AuthClient._call} exactly.
*/
private CallResult call(String method, String path, String token, Object body) throws IOException {
if (baseUrl.isEmpty()) {
throw new IllegalStateException("authclient: client has no base URL");
}
URL url = new URL(baseUrl + path);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod(method);
connection.setConnectTimeout(timeoutMillis);
connection.setReadTimeout(timeoutMillis);
if (token != null && !token.isEmpty()) {
connection.setRequestProperty("Authorization", BEARER_PREFIX + token);
}
byte[] payload = null;
if (body != null) {
connection.setRequestProperty("Content-Type", "application/json");
payload = JSON.writeValueAsBytes(body);
connection.setDoOutput(true);
}
int status;
String responseBody;
List<String> cookies;
try {
if (payload != null) {
OutputStream out = connection.getOutputStream();
try {
out.write(payload);
} finally {
out.close();
}
}
status = connection.getResponseCode();
InputStream stream = status >= 400 ? connection.getErrorStream() : connection.getInputStream();
responseBody = readAll(stream);
cookies = new ArrayList<String>();
for (Map.Entry<String, List<String>> entry : connection.getHeaderFields().entrySet()) {
if (entry.getKey() != null && entry.getKey().equalsIgnoreCase("Set-Cookie")) {
cookies.addAll(entry.getValue());
}
}
} catch (IOException ex) {
throw new IOException("authclient: call AuthGuard: " + ex.getMessage(), ex);
} finally {
connection.disconnect();
}
if (status < 200 || status >= 300) {
String message = null;
boolean totpRequired = false;
if (responseBody != null && !responseBody.isEmpty()) {
try {
JsonNode node = JSON.readTree(responseBody);
if (node.hasNonNull("error")) {
message = node.get("error").asText();
}
if (node.hasNonNull("totp_required")) {
totpRequired = node.get("totp_required").asBoolean();
}
} catch (IOException ignored) {
// Fall through to the generic message below.
}
}
if (message == null || message.isEmpty()) {
message = "request failed (" + status + ")";
}
throw new APIError(status, message, totpRequired);
}
return new CallResult(responseBody, cookies);
}
/** Package-private accessor for {@link #normalizeBaseUrl}'s scheme-detection test coverage; not part of the public API. */
String baseUrlForTest() {
return baseUrl;
}
private String extractCookieToken(String cookieHeader) {
if (cookieHeader == null || cookieHeader.isEmpty()) {
return "";
@@ -249,12 +679,26 @@ public final class AuthClient {
return connection;
}
/**
* Trims {@code baseUrl}, strips a trailing slash, and - if the result has
* no scheme - assumes {@code https://}, so a deployment only needs to
* name the host (e.g. {@code "auth.example.com"} or
* {@code "192.168.1.50:8080"}), not repeat the scheme. An explicit
* {@code http://} (for a plain-HTTP local/LAN AuthGuard) is left as-is.
*/
private static String normalizeBaseUrl(String baseUrl) {
String trimmed = baseUrl == null ? "" : baseUrl.trim();
while (trimmed.endsWith("/")) {
trimmed = trimmed.substring(0, trimmed.length() - 1);
}
return trimmed;
if (trimmed.isEmpty()) {
return trimmed;
}
String lower = trimmed.toLowerCase(Locale.ROOT);
if (lower.startsWith("http://") || lower.startsWith("https://")) {
return trimmed;
}
return "https://" + trimmed;
}
private static String readAll(InputStream in) throws IOException {
@@ -6,13 +6,16 @@ import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* Mirrors shared/packages/node-backend/test/authclient.test.js's coverage,
@@ -34,6 +37,75 @@ class AuthClientTest {
}
}
@Test
void constructorAssumesHttpsForABareHost() {
assertEquals("https://auth.example.com", new AuthClient("auth.example.com").baseUrlForTest());
assertEquals("https://192.168.1.50:8080", new AuthClient("192.168.1.50:8080").baseUrlForTest());
}
@Test
void constructorLeavesAnExplicitSchemeAlone() {
assertEquals("http://auth.example.com", new AuthClient("http://auth.example.com").baseUrlForTest());
assertEquals("https://auth.example.com", new AuthClient("https://auth.example.com").baseUrlForTest());
assertEquals("HTTP://auth.example.com", new AuthClient("HTTP://auth.example.com").baseUrlForTest());
}
@Test
void constructorStripsTrailingSlashBeforeCheckingScheme() {
assertEquals("https://auth.example.com", new AuthClient("auth.example.com/").baseUrlForTest());
}
@Test
void setupStatusReflectsAuthGuardSetupRequired() throws Exception {
server = fakeEndpoint("/api/setup-status", 200, "{\"setup_required\":true}");
AuthClient client = new AuthClient(baseUrl(server));
assertTrue(client.setupStatus());
}
@Test
void registerReturnsTheUserAndForwardsSetCookieValues() throws Exception {
server = fakeEndpointCapturingRequest(
"/api/register",
200,
"{\"user\":{\"id\":7,\"username\":\"gabriel\",\"email\":\"g@example.com\",\"role\":\"superadmin\",\"totp_enabled\":false}}",
new String[] {"auth_session=abc123; HttpOnly; Path=/"});
AuthClient client = new AuthClient(baseUrl(server));
AuthClient.SessionResult result = client.register("gabriel", "g@example.com", "hunter2!!");
assertEquals(7L, result.user.id);
assertEquals("gabriel", result.user.username);
assertFalse(result.user.totpEnabled);
assertEquals(List.of("auth_session=abc123; HttpOnly; Path=/"), result.cookies);
}
@Test
void loginRaisesApiErrorWithTotpRequiredOnA401AskingForACode() throws Exception {
server = fakeEndpoint("/api/login", 401, "{\"error\":\"two-factor authentication code required\",\"totp_required\":true}");
AuthClient client = new AuthClient(baseUrl(server));
AuthClient.APIError error = assertThrows(AuthClient.APIError.class, () -> client.login("gabriel", "hunter2", ""));
assertEquals(401, error.statusCode);
assertTrue(error.totpRequired);
}
@Test
void listManagedUsersMapsEveryRow() throws Exception {
server = fakeEndpoint(
"/api/admin/users",
200,
"{\"users\":[{\"id\":1,\"username\":\"a\",\"email\":\"a@x.com\",\"role\":\"admin\",\"created_at\":\"2026-01-01T00:00:00Z\"}]}");
AuthClient client = new AuthClient(baseUrl(server));
List<AuthClient.ManagedUser> users = client.listManagedUsers("token");
assertEquals(1, users.size());
assertEquals("a", users.get(0).username);
assertEquals("2026-01-01T00:00:00Z", users.get(0).createdAt);
}
@Test
void validateResolvesUserOnValidSession() throws Exception {
server = fakeAuthGuard(200, "{\"valid\":true,\"user_id\":7,\"username\":\"gabriel\",\"role\":\"admin\"}");
@@ -128,6 +200,31 @@ class AuthClientTest {
assertEquals("user", result.role);
}
/** Like fakeAuthGuard, but for one arbitrary path instead of the fixed /api/session/validate one. */
private static HttpServer fakeEndpoint(String path, int status, String body) throws IOException {
return fakeEndpointCapturingRequest(path, status, body, new String[0]);
}
/** Like fakeEndpoint, but also sets the given Set-Cookie header value(s) on the response. */
private static HttpServer fakeEndpointCapturingRequest(String path, int status, String body, String[] setCookies) throws IOException {
HttpServer httpServer = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);
httpServer.createContext(path, exchange -> {
// Drain the request body so the client's write doesn't block/fail.
exchange.getRequestBody().readAllBytes();
byte[] bytes = body.getBytes(StandardCharsets.UTF_8);
exchange.getResponseHeaders().add("Content-Type", "application/json");
for (String cookie : setCookies) {
exchange.getResponseHeaders().add("Set-Cookie", cookie);
}
exchange.sendResponseHeaders(status, bytes.length);
try (OutputStream out = exchange.getResponseBody()) {
out.write(bytes);
}
});
httpServer.start();
return httpServer;
}
private static HttpServer fakeAuthGuard(int status, String body) throws IOException {
HttpServer httpServer = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);
httpServer.createContext("/api/session/validate", exchange -> {
+11 -1
View File
@@ -57,15 +57,25 @@ export class APIError extends Error {
export class AuthClient {
/**
* @param {string} baseUrl - AuthGuard's base URL (e.g. from AUTHGUARD_URL), no trailing slash required.
* May be given without a scheme (e.g. "auth.example.com" or "192.168.1.50:8080") -
* "https://" is assumed in that case, so a deployment only needs to name the
* host, not repeat the scheme; an explicit "http://" (for a plain-HTTP
* local/LAN AuthGuard) is left as-is.
* @param {{cookieName?: string, timeoutMs?: number, fetchImpl?: typeof fetch}} [options]
*/
constructor(baseUrl, options = {}) {
this.baseUrl = String(baseUrl ?? '').trim().replace(/\/+$/, '');
this.baseUrl = AuthClient._normalizeBaseUrl(baseUrl);
this.cookieName = options.cookieName ?? DEFAULT_COOKIE_NAME;
this.timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
this.fetchImpl = options.fetchImpl ?? fetch;
}
static _normalizeBaseUrl(baseUrl) {
const trimmed = String(baseUrl ?? '').trim().replace(/\/+$/, '');
if (!trimmed) return trimmed;
return /^https?:\/\//i.test(trimmed) ? trimmed : `https://${trimmed}`;
}
// --- session validation (the original, minimal surface) -----------------
/**
@@ -31,6 +31,26 @@ function recordingFetch(responses) {
return wrapped;
}
test('constructor assumes https for a bare host', () => {
assert.equal(new AuthClient('auth.example.com').baseUrl, 'https://auth.example.com');
assert.equal(new AuthClient('192.168.1.50:8080').baseUrl, 'https://192.168.1.50:8080');
});
test('constructor leaves an explicit scheme alone', () => {
assert.equal(new AuthClient('http://auth.example.com').baseUrl, 'http://auth.example.com');
assert.equal(new AuthClient('https://auth.example.com').baseUrl, 'https://auth.example.com');
assert.equal(new AuthClient('HTTP://auth.example.com').baseUrl, 'HTTP://auth.example.com');
});
test('constructor strips a trailing slash before checking the scheme', () => {
assert.equal(new AuthClient('auth.example.com/').baseUrl, 'https://auth.example.com');
});
test('constructor trims whitespace and leaves an empty base URL empty', () => {
assert.equal(new AuthClient(' auth.example.com ').baseUrl, 'https://auth.example.com');
assert.equal(new AuthClient('').baseUrl, '');
});
test('validate resolves the user on a valid session', async () => {
const client = new AuthClient('https://auth.example.com', {
fetchImpl: fakeFetch([{ status: 200, body: { valid: true, user_id: 7, username: 'gabriel', role: 'admin' } }]),
@@ -61,6 +61,15 @@ DEFAULT_TIMEOUT = 5.0
_BEARER_PREFIX = "Bearer "
def _normalize_base_url(base_url: str) -> str:
trimmed = str(base_url or "").strip().rstrip("/")
if not trimmed:
return trimmed
if trimmed.lower().startswith(("http://", "https://")):
return trimmed
return f"https://{trimmed}"
class InvalidSessionError(Exception):
"""Raised by validate() / resolve_user() when AuthGuard reports the
token/cookie as not currently valid (expired, unknown, or missing)."""
@@ -170,11 +179,15 @@ class AuthClient:
timeout: float = DEFAULT_TIMEOUT,
) -> None:
"""base_url is AuthGuard's base URL, e.g. "https://auth.example.com"
(no trailing slash required). cookie_name is the cookie
(no trailing slash required). May be given without a scheme (e.g.
"auth.example.com" or "192.168.1.50:8080") -- "https://" is assumed
in that case, so a deployment only needs to name the host, not repeat
the scheme; an explicit "http://" (for a plain-HTTP local/LAN
AuthGuard) is left as-is. cookie_name is the cookie
token_from_request looks for when there is no Authorization header;
it must match AuthGuard's SessionCookieName. timeout is the request
timeout in seconds for the underlying blocking HTTP call."""
self.base_url = str(base_url or "").strip().rstrip("/")
self.base_url = _normalize_base_url(base_url)
self.cookie_name = cookie_name
self.timeout = timeout
@@ -49,6 +49,24 @@ def _fake_http_error(status: int, payload: dict) -> urllib.error.HTTPError:
)
class AuthClientBaseUrlTests(unittest.TestCase):
def test_bare_host_assumes_https(self) -> None:
self.assertEqual(AuthClient("auth.example.com").base_url, "https://auth.example.com")
self.assertEqual(AuthClient("192.168.1.50:8080").base_url, "https://192.168.1.50:8080")
def test_explicit_scheme_left_alone(self) -> None:
self.assertEqual(AuthClient("http://auth.example.com").base_url, "http://auth.example.com")
self.assertEqual(AuthClient("https://auth.example.com").base_url, "https://auth.example.com")
self.assertEqual(AuthClient("HTTP://auth.example.com").base_url, "HTTP://auth.example.com")
def test_trailing_slash_stripped_before_scheme_check(self) -> None:
self.assertEqual(AuthClient("auth.example.com/").base_url, "https://auth.example.com")
def test_whitespace_trimmed_and_empty_stays_empty(self) -> None:
self.assertEqual(AuthClient(" auth.example.com ").base_url, "https://auth.example.com")
self.assertEqual(AuthClient("").base_url, "")
class AuthClientValidateTests(unittest.IsolatedAsyncioTestCase):
def setUp(self) -> None:
self.client = AuthClient("https://authguard.example")
@@ -1,19 +1,21 @@
<script lang="ts">
import type { HTMLAttributes } from 'svelte/elements';
import type { Snippet } from 'svelte';
type BadgeVariant = 'default' | 'success' | 'warning' | 'danger';
type BadgeVariant = 'default' | 'primary' | 'success' | 'warning' | 'danger';
let {
children,
class: className = '',
variant = 'default'
}: {
variant = 'default',
...rest
}: Omit<HTMLAttributes<HTMLSpanElement>, 'class'> & {
children?: Snippet;
class?: string;
variant?: BadgeVariant;
} = $props();
</script>
<span class={`sc-badge ${className}`} data-variant={variant}>
<span class={`sc-badge ${className}`} data-variant={variant} {...rest}>
{@render children?.()}
</span>
@@ -1,8 +1,9 @@
<script lang="ts">
import type { HTMLButtonAttributes } from 'svelte/elements';
import type { Snippet } from 'svelte';
type ButtonVariant = 'primary' | 'secondary' | 'ghost' | 'danger';
type ButtonSize = 'sm' | 'md' | 'lg';
type ButtonVariant = 'primary' | 'secondary' | 'outline' | 'ghost' | 'danger';
type ButtonSize = 'sm' | 'md' | 'lg' | 'icon';
let {
children,
@@ -12,8 +13,9 @@
onclick,
size = 'md',
type = 'button',
variant = 'primary'
}: {
variant = 'primary',
...rest
}: Omit<HTMLButtonAttributes, 'class' | 'disabled' | 'onclick' | 'type'> & {
children?: Snippet;
class?: string;
disabled?: boolean;
@@ -30,6 +32,7 @@
{disabled}
{onclick}
{type}
{...rest}
>
{@render children?.()}
</button>
@@ -0,0 +1,13 @@
<script lang="ts">
import { Inbox } from '@lucide/svelte';
let { title, message }: { title: string; message: string } = $props();
</script>
<div class="sc-empty-state">
<Inbox aria-hidden="true" class="sc-empty-state-icon" size={32} />
<div>
<p class="sc-empty-state-title">{title}</p>
<p class="sc-empty-state-message">{message}</p>
</div>
</div>
@@ -0,0 +1,21 @@
<script lang="ts">
type MetricVariant = 'default' | 'primary' | 'success' | 'warning' | 'danger';
let {
detail = '',
label,
value,
variant = 'default'
}: {
detail?: string;
label: string;
value: string | number;
variant?: MetricVariant;
} = $props();
</script>
<div class="sc-metric">
<p class="sc-metric-label">{label}</p>
<p class="sc-metric-value" data-variant={variant}>{value}</p>
{#if detail}<p class="sc-metric-detail">{detail}</p>{/if}
</div>
@@ -0,0 +1,8 @@
<script lang="ts">
let { title, description = '' }: { title: string; description?: string } = $props();
</script>
<div class="sc-section-title">
<h2>{title}</h2>
{#if description}<p class="sc-muted">{description}</p>{/if}
</div>
@@ -0,0 +1,71 @@
<script lang="ts">
import { AlertCircle, AlertTriangle, CheckCircle2, CircleHelp, LoaderCircle, RefreshCw } from '@lucide/svelte';
import Button from './Button.svelte';
import Dialog from './Dialog.svelte';
import type { StatusProbe, StatusSnapshot } from '../types';
let {
onRefresh,
open = $bindable(false),
status
}: {
onRefresh: () => void | Promise<void>;
open?: boolean;
status: StatusSnapshot;
} = $props();
const levelLabel: Record<StatusSnapshot['level'], string> = {
checking: 'Checking',
healthy: 'Healthy',
degraded: 'Degraded',
offline: 'Offline'
};
function probeLabel(probe: StatusProbe | null): string {
if (!probe) return 'Not checked';
if (probe.ok) return 'OK';
if (probe.error) return probe.error;
return probe.httpStatus ? `HTTP ${probe.httpStatus}` : 'Unavailable';
}
</script>
<Dialog bind:open description="Live liveness and database readiness checks." title="Service status">
<div aria-live="polite" class="sc-status-summary" data-level={status.level}>
{#if status.loading && status.level === 'checking'}
<LoaderCircle aria-hidden="true" class="sc-status-icon sc-status-spin" size={20} />
{:else if status.level === 'healthy'}
<CheckCircle2 aria-hidden="true" class="sc-status-icon" size={20} />
{:else if status.level === 'degraded'}
<AlertTriangle aria-hidden="true" class="sc-status-icon" size={20} />
{:else if status.level === 'offline'}
<AlertCircle aria-hidden="true" class="sc-status-icon" size={20} />
{:else}
<CircleHelp aria-hidden="true" class="sc-status-icon" size={20} />
{/if}
<span class="sc-status-summary-label">{levelLabel[status.level]}</span>
{#if status.checkedAt}
<span class="sc-status-summary-time">{new Date(status.checkedAt).toLocaleTimeString()}</span>
{/if}
</div>
<div class="sc-status-probes">
{#each [{ label: 'Liveness', probe: status.health }, { label: 'Readiness / database', probe: status.readiness }] as item (item.label)}
<div class="sc-status-probe">
<span>{item.label}</span>
<span data-ok={item.probe?.ok ?? false}>{probeLabel(item.probe)}</span>
</div>
{/each}
</div>
{#if status.health?.service || status.readiness?.service}
<p class="sc-muted sc-status-service">Service: {status.health?.service || status.readiness?.service}</p>
{/if}
{#snippet footer()}
<Button disabled={status.loading} variant="outline" onclick={() => void onRefresh()}>
<RefreshCw aria-hidden="true" class={status.loading ? 'sc-status-spin' : ''} size={16} />
Refresh
</Button>
<Button variant="secondary" onclick={() => (open = false)}>Dismiss</Button>
{/snippet}
</Dialog>
@@ -0,0 +1,103 @@
<script lang="ts">
import { AlertCircle, AlertTriangle, CheckCircle2, CircleHelp, LoaderCircle } from '@lucide/svelte';
import { onMount } from 'svelte';
import Button from './Button.svelte';
import StatusDialog from './StatusDialog.svelte';
import type { StatusProbe, StatusSnapshot } from '../types';
// Polls this service's own /healthz (liveness) and /ready (readiness,
// typically including a database check) endpoints - the convention every
// Go/Node/Python backend in this workspace already serves - and shows the
// combined result as a small header icon that opens StatusDialog for
// detail on click. Both paths are relative, so this widget can drop into
// any app without configuration as long as it follows that convention.
const initialStatus: StatusSnapshot = {
level: 'checking',
health: null,
readiness: null,
checkedAt: null,
loading: false
};
let status = $state<StatusSnapshot>(initialStatus);
let open = $state(false);
let requestInFlight = false;
async function probe(path: string): Promise<StatusProbe> {
try {
const response = await fetch(path, {
credentials: 'include',
headers: { Accept: 'application/json' }
});
const payload = (await response.json().catch(() => null)) as {
ok?: boolean;
service?: string;
error?: string;
} | null;
return {
path,
ok: response.ok && payload?.ok !== false,
httpStatus: response.status,
service: payload?.service || null,
error: response.ok ? null : payload?.error || response.statusText || `HTTP ${response.status}`
};
} catch (error) {
return {
path,
ok: false,
httpStatus: null,
service: null,
error: error instanceof Error ? error.message : 'Unavailable'
};
}
}
async function refresh(): Promise<void> {
if (requestInFlight) return;
requestInFlight = true;
status = { ...status, loading: true, level: status.health || status.readiness ? status.level : 'checking' };
try {
const [health, readiness] = await Promise.all([probe('/healthz'), probe('/ready')]);
const level = health.ok && readiness.ok ? 'healthy' : health.ok ? 'degraded' : 'offline';
status = {
level,
health,
readiness,
checkedAt: new Date().toISOString(),
loading: false
};
} finally {
requestInFlight = false;
if (status.loading) status = { ...status, loading: false };
}
}
onMount(() => {
void refresh();
const timer = window.setInterval(() => void refresh(), 15_000);
return () => window.clearInterval(timer);
});
</script>
<Button
aria-label="Service status"
onclick={() => (open = true)}
size="icon"
title={`Service status: ${status.level}`}
variant="ghost"
>
{#if status.loading && status.level === 'checking'}
<LoaderCircle aria-hidden="true" class="sc-status-icon sc-status-spin" size={20} />
{:else if status.level === 'healthy'}
<CheckCircle2 aria-hidden="true" class="sc-status-icon" size={20} />
{:else if status.level === 'degraded'}
<AlertTriangle aria-hidden="true" class="sc-status-icon" size={20} />
{:else if status.level === 'offline'}
<AlertCircle aria-hidden="true" class="sc-status-icon" size={20} />
{:else}
<CircleHelp aria-hidden="true" class="sc-status-icon" size={20} />
{/if}
</Button>
<StatusDialog bind:open {status} onRefresh={refresh} />
+8
View File
@@ -6,12 +6,17 @@ export { default as Badge } from './components/Badge.svelte';
export { default as Button } from './components/Button.svelte';
export { default as Card } from './components/Card.svelte';
export { default as Dialog } from './components/Dialog.svelte';
export { default as EmptyState } from './components/EmptyState.svelte';
export { default as Header } from './components/Header.svelte';
export { default as Metric } from './components/Metric.svelte';
export { default as NotificationStack } from './components/NotificationStack.svelte';
export { default as PageHeader } from './components/PageHeader.svelte';
export { default as Pagination } from './components/Pagination.svelte';
export { default as ProfileDialog } from './components/ProfileDialog.svelte';
export { default as SectionTitle } from './components/SectionTitle.svelte';
export { default as SettingsDialog } from './components/SettingsDialog.svelte';
export { default as StatusDialog } from './components/StatusDialog.svelte';
export { default as StatusWidget } from './components/StatusWidget.svelte';
export { default as TotpSettings } from './components/TotpSettings.svelte';
export { default as UserManagement } from './components/UserManagement.svelte';
export { notifications, notify } from './notifications.svelte';
@@ -27,6 +32,9 @@ export type {
NavItem,
ProfileUpdateInput,
ManagedUser,
StatusLevel,
StatusProbe,
StatusSnapshot,
UserCreateInput,
UserCreateRequest,
UserDeleteRequest,
+197
View File
@@ -285,6 +285,12 @@
font-weight: 650;
}
.sc-badge[data-variant="primary"] {
color: var(--sc-primary-fg);
background: var(--sc-primary);
border-color: transparent;
}
.sc-badge[data-variant="success"] {
color: var(--sc-success-fg);
background: var(--sc-success);
@@ -380,6 +386,16 @@
background: var(--sc-danger-hover);
}
.sc-button-outline {
color: var(--sc-fg);
background: transparent;
border-color: var(--sc-border);
}
.sc-button-outline:hover:not(:disabled) {
background: var(--sc-surface-hover);
}
.sc-button-sm {
min-height: 2rem;
padding: 0.45rem 0.75rem;
@@ -391,6 +407,187 @@
padding: 0.75rem 1.25rem;
}
.sc-button-icon {
min-height: 2.5rem;
width: 2.5rem;
padding: 0;
}
.sc-empty-state {
display: flex;
min-height: 10rem;
flex-direction: column;
align-items: center;
justify-content: center;
gap: 0.75rem;
padding: 2rem 1.25rem;
text-align: center;
border: 1px dashed var(--sc-border);
border-radius: var(--sc-radius-lg);
background: color-mix(in srgb, var(--sc-surface) 50%, transparent);
}
.sc-empty-state-icon {
color: var(--sc-muted-fg);
}
.sc-empty-state-title {
margin: 0;
font-size: 0.9rem;
font-weight: 600;
color: var(--sc-fg);
}
.sc-empty-state-message {
margin: 0.25rem 0 0;
max-width: 24rem;
font-size: 0.8125rem;
color: var(--sc-muted-fg);
}
.sc-section-title {
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 0.75rem;
}
.sc-section-title h2 {
margin: 0;
font-size: 0.9rem;
font-weight: 650;
color: var(--sc-fg);
}
.sc-section-title p {
margin: 0.25rem 0 0;
}
.sc-metric {
padding: 1rem;
border: 1px solid var(--sc-border);
border-radius: var(--sc-radius-lg);
background: var(--sc-surface);
}
.sc-metric-label {
margin: 0;
font-size: 0.6875rem;
font-weight: 650;
letter-spacing: 0.06em;
text-transform: uppercase;
color: var(--sc-muted-fg);
}
.sc-metric-value {
margin: 0.5rem 0 0;
font-size: 1.5rem;
font-weight: 650;
letter-spacing: -0.01em;
color: var(--sc-fg);
}
.sc-metric-value[data-variant="primary"] {
color: var(--sc-primary);
}
.sc-metric-value[data-variant="success"] {
color: var(--sc-success);
}
.sc-metric-value[data-variant="warning"] {
color: var(--sc-warning);
}
.sc-metric-value[data-variant="danger"] {
color: var(--sc-danger);
}
.sc-metric-detail {
margin: 0.25rem 0 0;
font-size: 0.8125rem;
color: var(--sc-muted-fg);
}
.sc-status-icon {
color: var(--sc-muted-fg);
}
.sc-status-summary[data-level="healthy"] .sc-status-icon,
.sc-status-summary[data-level="healthy"] .sc-status-summary-label {
color: var(--sc-success);
}
.sc-status-summary[data-level="degraded"] .sc-status-icon,
.sc-status-summary[data-level="degraded"] .sc-status-summary-label {
color: var(--sc-warning);
}
.sc-status-summary[data-level="offline"] .sc-status-icon,
.sc-status-summary[data-level="offline"] .sc-status-summary-label {
color: var(--sc-danger);
}
.sc-status-spin {
animation: sc-spin 900ms linear infinite;
}
@keyframes sc-spin {
to {
transform: rotate(360deg);
}
}
.sc-status-summary {
display: flex;
align-items: center;
gap: 0.75rem;
margin-bottom: 1.25rem;
padding: 0.75rem;
border: 1px solid var(--sc-border);
border-radius: var(--sc-radius-md);
background: var(--sc-surface);
}
.sc-status-summary-label {
font-weight: 650;
}
.sc-status-summary-time {
margin-left: auto;
font-size: 0.75rem;
color: var(--sc-muted-fg);
}
.sc-status-probes {
display: flex;
flex-direction: column;
gap: 0.5rem;
font-size: 0.875rem;
}
.sc-status-probe {
display: flex;
align-items: center;
justify-content: space-between;
gap: 1rem;
padding: 0.5rem 0.75rem;
border: 1px solid var(--sc-border);
border-radius: var(--sc-radius-sm);
}
.sc-status-probe span[data-ok="true"] {
color: var(--sc-success);
}
.sc-status-probe span[data-ok="false"] {
color: var(--sc-danger);
}
.sc-status-service {
margin-top: 1rem;
}
.sc-button-full {
width: 100%;
}
+18
View File
@@ -91,3 +91,21 @@ export interface AboutLink {
}
export type ContentSnippet = Snippet;
export type StatusLevel = "checking" | "healthy" | "degraded" | "offline";
export interface StatusProbe {
path: string;
ok: boolean;
httpStatus: number | null;
service: string | null;
error: string | null;
}
export interface StatusSnapshot {
level: StatusLevel;
health: StatusProbe | null;
readiness: StatusProbe | null;
checkedAt: string | null;
loading: boolean;
}