diff --git a/backend/auth.go b/backend/auth.go index 5d4c1f2..764688a 100644 --- a/backend/auth.go +++ b/backend/auth.go @@ -210,15 +210,10 @@ type AuthService struct { db *DB authGuard *authclient.Client secureCookie bool - // reset backs CollabTable's own local break-glass recovery flow (see - // handleResetRequest/handleResetConfirm); it is unrelated to AuthGuard, - // which runs its own separate instance of the same ResetManager type for - // its own recovery flow. - reset *sharedauth.ResetManager } func newAuthService(authGuard *authclient.Client, db *DB, secureCookie bool) *AuthService { - return &AuthService{db: db, authGuard: authGuard, secureCookie: secureCookie, reset: sharedauth.NewResetManager()} + return &AuthService{db: db, authGuard: authGuard, secureCookie: secureCookie} } func normalizeUsername(value string) (string, error) { @@ -472,68 +467,6 @@ func (a *AuthService) handleStatus(w http.ResponseWriter, r *http.Request) { writeJSON(w, http.StatusOK, a.statusResponse(r.Context(), *profile)) } -// handleResetRequest and handleResetConfirm are CollabTable's own local -// "break glass" account recovery: an operator with shell/log access to this -// container (not to AuthGuard) can recover access to CollabTable's UI -// without knowing the current AuthGuard account's password. This is -// deliberately NOT proxied to AuthGuard's own POST -// /api/password-reset/request|confirm -- a break-glass flow should never -// depend on the very identity service it exists to recover access to, and -// (like GameStream before it) CollabTable's existing frontend only ever -// sends {code}, not a new password, so it was built for a "wipe and redo -// setup" recovery model rather than AuthGuard's "set a specific new -// password" one in any case. -func (a *AuthService) handleResetRequest(w http.ResponseWriter, r *http.Request) { - if r.Method != http.MethodPost { - w.WriteHeader(http.StatusMethodNotAllowed) - return - } - if _, err := a.reset.Request(); err != nil { - writeJSONError(w, http.StatusInternalServerError, "Unable to create reset code") - return - } - writeJSON(w, http.StatusOK, map[string]bool{"ok": true}) -} - -// handleResetConfirm validates the one-time code handleResetRequest printed -// to this process's own stdout and, on success, resets the local "setup -// completed" flag so CollabTable's setup screen reappears. -// -// This intentionally does NOT touch the underlying AuthGuard account at all -// (does not delete it, does not change its password): CollabTable's local -// console-access recovery is only ever allowed to affect CollabTable's own -// claim on an identity, never to reach into and mutate the centralized -// identity store other projects may come to share. Concretely, this means -// the account AuthGuard already has is left behind (orphaned, from -// CollabTable's perspective) once this runs; re-running setup with the same -// username/email will hit AuthGuard's own 409 "already in use" and the -// operator will need to either choose a different identity at the setup -// screen or resolve the original account directly against AuthGuard (which -// has its own equivalent break-glass recovery). -func (a *AuthService) handleResetConfirm(w http.ResponseWriter, r *http.Request) { - if r.Method != http.MethodPost { - w.WriteHeader(http.StatusMethodNotAllowed) - return - } - var request struct { - Code string `json:"code"` - } - if err := decodeJSON(r, &request); err != nil || strings.TrimSpace(request.Code) == "" { - writeJSONError(w, http.StatusBadRequest, "Code required") - return - } - if !a.reset.Confirm(request.Code) { - writeJSONError(w, http.StatusUnauthorized, "Invalid or expired reset code.") - return - } - if err := a.db.ClearSetupClaim(r.Context()); err != nil { - writeJSONError(w, http.StatusInternalServerError, "Reset failed") - return - } - a.clearSessionCookies(w) - writeJSON(w, http.StatusOK, map[string]bool{"ok": true}) -} - // handleSetup registers CollabTable's first account against AuthGuard's // POST /api/register. See the top-of-file doc comment's "Setup flow" section // for why this needs a small local claim flag instead of a count-based diff --git a/backend/db.go b/backend/db.go index ef50202..313f86c 100644 --- a/backend/db.go +++ b/backend/db.go @@ -276,14 +276,6 @@ func (d *DB) UnclaimSetup(ctx context.Context) error { return nil } -// ClearSetupClaim resets the local "setup completed" flag so the setup screen -// reappears. Used by the local break-glass password-reset flow (see -// handleResetConfirm in auth.go) -- it deliberately does not touch the -// underlying AuthGuard account at all. -func (d *DB) ClearSetupClaim(ctx context.Context) error { - return d.UnclaimSetup(ctx) -} - // GetCachedTOTPEnabled returns the best-effort locally-cached TOTP-enabled // state for an AuthGuard account, or false if this instance has never // observed that account's TOTP state. See handleTOTPStatus's doc comment in diff --git a/backend/server.go b/backend/server.go index c9b934b..b3230b0 100644 --- a/backend/server.go +++ b/backend/server.go @@ -132,8 +132,6 @@ func (s *Server) registerRoutes(mux *http.ServeMux, webRoot fs.FS) { // Health and auth bootstrap routes are intentionally public. mux.HandleFunc("GET /health", s.handleHealth) mux.HandleFunc("GET /api/auth/status", s.auth.handleStatus) - mux.HandleFunc("POST /api/auth/reset/request", s.auth.handleResetRequest) - mux.HandleFunc("POST /api/auth/reset/confirm", s.auth.handleResetConfirm) mux.HandleFunc("POST /api/auth/setup", s.auth.handleSetup) mux.HandleFunc("POST /api/auth/login", s.auth.handleLogin) mux.Handle("POST /api/auth/logout", s.auth.requireSession(http.HandlerFunc(s.auth.handleLogout))) diff --git a/frontend/src/lib/api.js b/frontend/src/lib/api.js index 54711a8..9bb3abe 100644 --- a/frontend/src/lib/api.js +++ b/frontend/src/lib/api.js @@ -1,46 +1,46 @@ -async function request(url, options) { - const res = await fetch(url, { - ...options, - headers: options?.body ? { 'Content-Type': 'application/json', ...options?.headers } : options?.headers, - }); - if (!res.ok) { - let message = `HTTP ${res.status}`; - try { - const body = await res.json(); - // This backend's error responses are { error: "", message: "" } - - // message is the human-readable text; error is just a category label (e.g. "Unauthorized"). - if (body?.message) message = body.message; - else if (body?.error) message = body.error; - } catch { - // Response body wasn't JSON (or was empty) - keep the generic status message. - } - throw new Error(message); - } - if (res.status === 204) return undefined; - return res.json(); -} - -async function getJson(url) { - return request(url); -} - -export async function fetchOverview() { - return getJson('/web/data'); -} - -export async function fetchTechStack() { - return getJson('/api/tech-stack'); -} - -export async function fetchHealth() { - const res = await fetch('/health'); - return { up: res.ok }; -} - -export async function fetchAuthStatus() { - return getJson('/api/auth/status'); -} - +async function request(url, options) { + const res = await fetch(url, { + ...options, + headers: options?.body ? { 'Content-Type': 'application/json', ...options?.headers } : options?.headers, + }); + if (!res.ok) { + let message = `HTTP ${res.status}`; + try { + const body = await res.json(); + // This backend's error responses are { error: "", message: "" } - + // message is the human-readable text; error is just a category label (e.g. "Unauthorized"). + if (body?.message) message = body.message; + else if (body?.error) message = body.error; + } catch { + // Response body wasn't JSON (or was empty) - keep the generic status message. + } + throw new Error(message); + } + if (res.status === 204) return undefined; + return res.json(); +} + +async function getJson(url) { + return request(url); +} + +export async function fetchOverview() { + return getJson('/web/data'); +} + +export async function fetchTechStack() { + return getJson('/api/tech-stack'); +} + +export async function fetchHealth() { + const res = await fetch('/health'); + return { up: res.ok }; +} + +export async function fetchAuthStatus() { + return getJson('/api/auth/status'); +} + export async function setupAccount(username, email, password) { return request('/api/auth/setup', { method: 'POST', body: JSON.stringify({ username, email, password }) }); } @@ -65,23 +65,10 @@ export async function disableTotp(token) { return request('/api/auth/totp/disable', { method: 'POST', body: JSON.stringify({ token }) }); } -export async function requestAdminReset() { - return request('/api/auth/reset/request', { method: 'POST' }); +export async function logout() { + return request('/api/auth/logout', { method: 'POST' }); } -export async function confirmAdminReset(code) { - const result = await request('/api/auth/reset/confirm', { - method: 'POST', - body: JSON.stringify({ code }), - }); - window.location.reload(); - return result; -} - -export async function logout() { - return request('/api/auth/logout', { method: 'POST' }); -} - export async function updateCredentials({ newUsername, newEmail, newPassword }) { return request('/api/auth/credentials', { method: 'POST', diff --git a/frontend/src/lib/features/auth/AuthPage.svelte b/frontend/src/lib/features/auth/AuthPage.svelte index b48fa66..49cb944 100644 --- a/frontend/src/lib/features/auth/AuthPage.svelte +++ b/frontend/src/lib/features/auth/AuthPage.svelte @@ -7,8 +7,6 @@ const onLogin = (input) => auth.login(input.identifier, input.password, input.totpToken); const onSetup = (input) => auth.setup(input.username, input.email, input.password); - const onRequestReset = () => auth.requestAdminReset(); - const onConfirmReset = (code) => auth.confirmAdminReset(code); diff --git a/frontend/src/lib/features/auth/auth.svelte.js b/frontend/src/lib/features/auth/auth.svelte.js index a6f9e0d..a2d96bf 100644 --- a/frontend/src/lib/features/auth/auth.svelte.js +++ b/frontend/src/lib/features/auth/auth.svelte.js @@ -1,7 +1,6 @@ -import { createMutation, createQuery, useQueryClient } from '@tanstack/svelte-query'; -import { getContext, setContext } from 'svelte'; +import { createMutation, createQuery, useQueryClient } from '@tanstack/svelte-query'; +import { getContext, setContext } from 'svelte'; import { - confirmAdminReset, createUser, deleteUser, disableTotp, @@ -11,52 +10,51 @@ import { login, listUsers, logout, - requestAdminReset, setupTotp, setupAccount, updateCredentials, updateUser, } from '$lib/api.js'; - -const AUTH_STATUS_KEY = ['AuthStatus']; -const AUTH_CONTEXT_KEY = Symbol('auth'); - -export function createAuthStore() { - const queryClient = useQueryClient(); - - const statusQuery = createQuery(() => ({ - queryKey: AUTH_STATUS_KEY, - queryFn: fetchAuthStatus, - })); + +const AUTH_STATUS_KEY = ['AuthStatus']; +const AUTH_CONTEXT_KEY = Symbol('auth'); + +export function createAuthStore() { + const queryClient = useQueryClient(); + + const statusQuery = createQuery(() => ({ + queryKey: AUTH_STATUS_KEY, + queryFn: fetchAuthStatus, + })); const setupMutation = createMutation(() => ({ mutationFn: ({ username, email, password }) => setupAccount(username, email, password), })); const loginMutation = createMutation(() => ({ mutationFn: ({ identifier, password, totpToken }) => login(identifier, password, totpToken), - })); - const logoutMutation = createMutation(() => ({ - mutationFn: () => logout(), - })); - const updateCredentialsMutation = createMutation(() => ({ - mutationFn: (input) => updateCredentials(input), - })); - - const refresh = () => queryClient.invalidateQueries({ queryKey: AUTH_STATUS_KEY }); - - const store = { - get status() { - return statusQuery.data; - }, - get loading() { - return statusQuery.isLoading; - }, - get error() { - return statusQuery.error; - }, + })); + const logoutMutation = createMutation(() => ({ + mutationFn: () => logout(), + })); + const updateCredentialsMutation = createMutation(() => ({ + mutationFn: (input) => updateCredentials(input), + })); + + const refresh = () => queryClient.invalidateQueries({ queryKey: AUTH_STATUS_KEY }); + + const store = { + get status() { + return statusQuery.data; + }, + get loading() { + return statusQuery.isLoading; + }, + get error() { + return statusQuery.error; + }, async setup(username, email, password) { await setupMutation.mutateAsync({ username, email, password }); - await refresh(); - }, + await refresh(); + }, async login(identifier, password, totpToken = '') { await loginMutation.mutateAsync({ identifier, password, totpToken }); await refresh(); @@ -76,16 +74,10 @@ export function createAuthStore() { await disableTotp(token); await refresh(); }, - async requestAdminReset() { - await requestAdminReset(); + async logout() { + await logoutMutation.mutateAsync(); + await refresh(); }, - async confirmAdminReset(code) { - await confirmAdminReset(code); - }, - async logout() { - await logoutMutation.mutateAsync(); - await refresh(); - }, async updateCredentials(input) { await updateCredentialsMutation.mutateAsync(input); await refresh(); @@ -102,16 +94,16 @@ export function createAuthStore() { async deleteUser(id) { await deleteUser(id); }, - }; - - setContext(AUTH_CONTEXT_KEY, store); - return store; -} - -export function useAuth() { - const ctx = getContext(AUTH_CONTEXT_KEY); - if (!ctx) { - throw new Error('useAuth() must be called within the root layout that calls createAuthStore()'); - } - return ctx; -} + }; + + setContext(AUTH_CONTEXT_KEY, store); + return store; +} + +export function useAuth() { + const ctx = getContext(AUTH_CONTEXT_KEY); + if (!ctx) { + throw new Error('useAuth() must be called within the root layout that calls createAuthStore()'); + } + return ctx; +}