chore: clean up backend code and build shared deps in CI
Lint / Lint (push) Successful in 1m5s
Tests / Go backend (push) Failing after 1m17s
Docker / Docker Build & Push (push) Failing after 4m28s
Tests / Dashboard checks (push) Successful in 1m6s

This commit is contained in:
Gabriel20xx committed 2026-10-20 19:31:16 +00:00
1 parent 97c237be80
commit 94d52c7622
10 files changed
+17 -150

No files matched your search

+5 -4
View File
@@ -6,7 +6,7 @@
- **Commit:** 22887fe on main
- **Working tree:** Contains uncommitted changes from the earlier finding pass and this continuation; no changes have been committed.
- **Stack:** Go 1.25 (`backend/`); Node.js ESM with `pg` (`packages/node-backend`); Python 3.10+ with asyncpg, bcrypt and optional FastAPI (`packages/python-backend`, ruff configured); Java 8 target with Jackson and JUnit 5 (`packages/java-backend`); Svelte 5 and TypeScript with svelte-check (`packages/web-ui`); PowerShell and Node build and sync scripts; Gitea and GitHub Actions.
- **Scope:** A shared library consumed by other projects as a vendored snapshot. Read: root manifests and changesets, `.github` and `.gitea` workflows, `.githooks`, `scripts/` (sync, build, and the `scripts/media` tooling), all four language packages (AuthGuard clients, stores, TOTP, config, coreconfig, proxies), Go packages under `backend/` (auth read in a separate pass), and the web-ui library source (barrel, styles, primary-color, notifications, components that do I/O or timers). Excluded: `node_modules`, `packages/web-ui/dist` and `.svelte-kit` (gitignored, not tracked), `package-lock.json` and `go.sum` (versions only), and test bodies except for coverage notes. Backend findings came from read-only static review passes; the highest-impact citations were re-checked in the code. The shared Node, Python and web-ui suites, web-ui package build and checks were run during this continuation; Go and Java toolchains are absent.
- **Scope:** A shared library consumed by other projects as a vendored snapshot. Read: root manifests and changesets, `.github` and `.gitea` workflows, `.githooks`, `scripts/` (sync, build, and the `scripts/media` tooling), all four language packages (AuthGuard clients, stores, TOTP, config, coreconfig, proxies), Go packages under `backend/` (auth read in a separate pass), and the web-ui library source (barrel, styles, primary-color, notifications, components that do I/O or timers). Excluded: `node_modules`, `packages/web-ui/dist` and `.svelte-kit` (gitignored, not tracked), `package-lock.json` and `go.sum` (versions only), and test bodies except for coverage notes. Backend findings came from read-only static review passes; the highest-impact citations were re-checked in the code. The shared Node, Python, web-ui and Go suites/checks, web-ui package build and checks were run during this continuation; Java tools remain unavailable.
- **Updated:** 2026-10-20 — Q-008 fixed in the working tree: all password writers use bcrypt cost 12, legacy PBKDF2 verifies and upgrades after a successful login, and shared contract fixtures cover all runtimes. Node tests, web-ui tests, package build, Svelte check and Node syntax check passed.
## Summary
@@ -117,10 +117,11 @@ The code is generally tidy: no TODO, FIXME or HACK markers in first-party non-te
- **Recommendation:** Update the component count to match `index.ts` when the removal is committed, delete the `mediaauth` references, and remove the stale ignore entry.
### Q-015 · Go code hygiene: dead code, an oversized file, duplicated helpers and nil-dependency constructors · **Low**
- **Location:** `backend/auth/reset.go` (`ResetManager` has no non-test consumer in this repository), `backend/auth/totp.go:23` (`TOTPSecretLength` unused), `backend/auth/proxy.go` (1525 lines mixing middleware, handlers and platform-user SQL), `backend/mediacore/mediacore.go:76-78` (`New` accepts nil CarrierNode or Sync; needs verification in the code), `backend/authclient/client.go:270-278` (two identical branches where the comment says there is a distinction), `writeJSON` and `writeError` duplicated across three packages
- **Description:** Exported helpers with no in-repository callers, a 1525-line file that mixes concerns, duplicated HTTP helpers, a constructor that accepts nil dependencies (which panics on first use rather than at startup), and a branch that is meant to separate transport failures from invalid sessions but returns the same result either way.
- **Location:** `backend/auth/reset.go` (`ResetManager` is used by AuthGuard outside this repository), `backend/auth/totp.go` (`TOTPSecretLength` unused), `backend/auth/store.go` (legacy per-user project APIs and expired-session cleanup helper), `backend/auth/proxy.go` (1525 lines mixing middleware, handlers and platform-user SQL), `backend/mediacore/mediacore.go:76-78` (`New` accepts nil CarrierNode or Sync; needs verification in the code), `backend/authclient/client.go:270-278` (two identical branches where the comment says there is a distinction), `writeJSON` and `writeError` duplicated across three packages
- **Description:** Exported helpers with no workspace callers, a 1525-line file that mixes concerns, duplicated HTTP helpers, a constructor that accepts nil dependencies (which panics on first use rather than at startup), and a branch that is meant to separate transport failures from invalid sessions but returns the same result either way.
- **Impact:** Maintenance cost, and a misconfigured service fails on the first request rather than at startup.
- **Recommendation:** Remove or move unused code. Split `proxy.go` into middleware, handlers and persistence files. Validate constructor arguments. Share one JSON helper package, and make the authclient branches distinct or merge them.
- **Status:** Partly fixed 2026-10-20 — removed the unused `TOTPSecretLength` constant, legacy per-user project APIs and their schema creation, and unused `DeleteExpiredSessions` helper. No table drop was added; AuthGuard's existing migration continues to transfer legacy restriction rows into roles before clearing them from the old table. `ResetManager` remains because AuthGuard uses it; file splitting, duplicated helpers, and the remaining findings are open.
### Q-016 · Web UI: an unkeyed `{#each}` over a prop, and a login-field length rule that also applies to sign-in · **Low**
- **Location:** `packages/web-ui/src/lib/components/Header.svelte:168` (`{#each navItems as item}` with no key), `packages/web-ui/src/lib/components/AuthPage.svelte:202` (`minlength="8"` on the sign-in password field, not only on setup)
@@ -132,6 +133,6 @@ The code is generally tidy: no TODO, FIXME or HACK markers in first-party non-te
- **Checked, clean:** No `TODO`, `FIXME`, `HACK` or `XXX` markers in first-party non-test code. No `any`, `@ts-ignore`, `@ts-expect-error` or `svelte-ignore` in `packages/web-ui/src`. No `{@html}`, `innerHTML`, `eval` or `new Function` in the web-ui or scripts. External links use `rel="noreferrer"`. Timers and document listeners are cleaned up in `StatusWidget`, `MediaPlayer`, `MediaPlayerControls`, `PrimaryColorPicker` and `notifications.svelte.ts`.
- **Checked, consistent:** Go code is gofmt-checked and `go vet`-checked in CI. Python code is ruff-checked (`E`, `F`, `I`). Node syntax is checked for `packages/node-backend`. Parameterised SQL is used across the Go, Node and Python stores.
- **Duplication by design:** The AuthGuard client exists in four languages on purpose. Q-008 covers where the behaviour has drifted.
- **Verification:** Node backend: 73 tests passed. Python backend: 122 tests and Ruff passed. Web-ui: 29 tests, package build, `svelte-check`, `npm run lint`, and `format:check` passed. Go test/gofmt and Java tests were not run because Go and Java tools are absent. No database-backed integration test ran.
- **Verification:** Node backend: 73 tests passed. Python backend: 122 tests and Ruff passed. Web-ui: 29 tests, package build, `svelte-check`, `npm run lint`, and `format:check` passed. Go: `gofmt -l`, `go test ./...` and `go vet ./...` passed. Java tests were not run because no JDK or Maven is available. No database-backed integration test ran.
- **Not verified:** Whether consumers depend on the removed `UserManagement` export or the `MediaPlayerControls` barrel removal (the changeset says only AuthGuard used it). Whether the `packages/media-shared-assets` and `media-backend` paths in history were ever shipped.
- **Excluded from analysis:** `packages/web-ui/dist` and `.svelte-kit` (gitignored, not tracked), `package-lock.json` and `go.sum` (versions only), test bodies beyond coverage notes.
+2 -130
View File
@@ -48,10 +48,7 @@ type SchemaOptions struct {
SingleUser bool
// APITokens creates the optional per-user API token table.
APITokens bool
// ProjectScoping creates auth_known_projects/auth_user_projects, backing per-user
// project-access restriction (see Store.SetUserProjects/IsProjectAllowed). Only AuthGuard
// itself needs this - every other project only ever calls AuthGuard's own API, never these
// tables directly.
// ProjectScoping creates auth_known_projects for AuthGuard's project catalog and admin UI.
ProjectScoping bool
}
@@ -151,12 +148,6 @@ func EnsureSchema(ctx context.Context, pool *pgxpool.Pool, options SchemaOptions
label TEXT NOT NULL DEFAULT '',
updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
CREATE TABLE IF NOT EXISTS auth_user_projects (
user_id BIGINT NOT NULL REFERENCES auth_users(id) ON DELETE CASCADE,
project TEXT NOT NULL,
PRIMARY KEY (user_id, project)
);
CREATE INDEX IF NOT EXISTS auth_user_projects_project_idx ON auth_user_projects (project);
`); err != nil {
return fmt.Errorf("ensure project-scoping schema: %w", err)
}
@@ -590,18 +581,6 @@ func (s *Store) DeleteAllUsers(ctx context.Context) error {
return nil
}
// DeleteExpiredSessions performs the periodic session cleanup shared by the
// services. A caller can run it from its own scheduler.
func (s *Store) DeleteExpiredSessions(ctx context.Context) error {
if err := s.validate(); err != nil {
return err
}
if _, err := s.pool.Exec(ctx, `DELETE FROM auth_sessions WHERE expires_at < now()`); err != nil {
return fmt.Errorf("delete expired auth sessions: %w", err)
}
return nil
}
// KnownProject is one project ProjectConfigurator has registered, pushed to AuthGuard so its
// admin UI can offer real, live project keys instead of free-form text - see SetKnownProjects.
type KnownProject struct {
@@ -611,9 +590,7 @@ type KnownProject struct {
// SetKnownProjects replaces the full set of known projects (pushed by ProjectConfigurator's
// PUT /api/projects/internal whenever its registered-project list changes). A project no longer
// registered is dropped, so the admin UI never offers a stale key; existing auth_user_projects
// rows for a removed project are left alone (harmless - IsProjectAllowed only ever compares
// against a user's own rows, never against auth_known_projects).
// registered is dropped, so the admin UI never offers a stale key.
func (s *Store) SetKnownProjects(ctx context.Context, projects []KnownProject) error {
if err := s.validate(); err != nil {
return err
@@ -665,111 +642,6 @@ func (s *Store) KnownProjects(ctx context.Context) ([]KnownProject, error) {
return projects, rows.Err()
}
// SetUserProjects replaces the full set of projects userID is restricted to. An empty projects
// list means unrestricted (see IsProjectAllowed) - the default for every account until an
// administrator explicitly scopes it, so this feature is opt-in and never breaks an existing
// deployment's accounts on upgrade.
func (s *Store) SetUserProjects(ctx context.Context, userID int64, projects []string) error {
if err := s.validate(); err != nil {
return err
}
tx, err := s.pool.Begin(ctx)
if err != nil {
return fmt.Errorf("set user projects: %w", err)
}
defer tx.Rollback(ctx)
if _, err := tx.Exec(ctx, `DELETE FROM auth_user_projects WHERE user_id = $1`, userID); err != nil {
return fmt.Errorf("set user projects: %w", err)
}
seen := map[string]bool{}
for _, project := range projects {
key := strings.ToLower(strings.TrimSpace(project))
if key == "" || seen[key] {
continue
}
seen[key] = true
if _, err := tx.Exec(ctx, `INSERT INTO auth_user_projects (user_id, project) VALUES ($1, $2)`, userID, key); err != nil {
return fmt.Errorf("set user projects: %w", err)
}
}
if err := tx.Commit(ctx); err != nil {
return fmt.Errorf("set user projects: %w", err)
}
return nil
}
// UserProjects returns the projects userID is restricted to, or an empty slice when unrestricted.
func (s *Store) UserProjects(ctx context.Context, userID int64) ([]string, error) {
if err := s.validate(); err != nil {
return nil, err
}
rows, err := s.pool.Query(ctx, `SELECT project FROM auth_user_projects WHERE user_id = $1 ORDER BY project`, userID)
if err != nil {
return nil, fmt.Errorf("list user projects: %w", err)
}
defer rows.Close()
projects := make([]string, 0)
for rows.Next() {
var project string
if err := rows.Scan(&project); err != nil {
return nil, fmt.Errorf("scan user project: %w", err)
}
projects = append(projects, project)
}
return projects, rows.Err()
}
// UserProjectsByUser bulk-loads every user's project restrictions in one query, for the admin
// user list screen (avoids one query per row).
func (s *Store) UserProjectsByUser(ctx context.Context) (map[int64][]string, error) {
if err := s.validate(); err != nil {
return nil, err
}
rows, err := s.pool.Query(ctx, `SELECT user_id, project FROM auth_user_projects ORDER BY user_id, project`)
if err != nil {
return nil, fmt.Errorf("list user projects: %w", err)
}
defer rows.Close()
result := map[int64][]string{}
for rows.Next() {
var userID int64
var project string
if err := rows.Scan(&userID, &project); err != nil {
return nil, fmt.Errorf("scan user project: %w", err)
}
result[userID] = append(result[userID], project)
}
return result, rows.Err()
}
// IsProjectAllowed reports whether userID may authenticate against project: true when the
// account has no project restrictions at all (the default for every account), or when project is
// one of its assigned projects. An empty project (a caller that sent no project-key header - a
// service not yet migrated to identify itself, or a browser request straight to AuthGuard's own
// web UI, which is not itself a "project" another service authenticates against) is always
// allowed; restriction only ever applies once a caller actually identifies itself.
func (s *Store) IsProjectAllowed(ctx context.Context, userID int64, project string) (bool, error) {
project = strings.ToLower(strings.TrimSpace(project))
if project == "" {
return true, nil
}
if err := s.validate(); err != nil {
return false, err
}
var total int
if err := s.pool.QueryRow(ctx, `SELECT count(*) FROM auth_user_projects WHERE user_id = $1`, userID).Scan(&total); err != nil {
return false, fmt.Errorf("count user projects: %w", err)
}
if total == 0 {
return true, nil
}
var allowed bool
if err := s.pool.QueryRow(ctx, `SELECT EXISTS(SELECT 1 FROM auth_user_projects WHERE user_id = $1 AND project = $2)`, userID, project).Scan(&allowed); err != nil {
return false, fmt.Errorf("check user project: %w", err)
}
return allowed, nil
}
var ErrUserExists = errors.New("auth user already exists")
// ErrTOTPAlreadyEnabled is returned by SetTOTPSecret while two-factor auth is on.
-1
View File
@@ -20,7 +20,6 @@ const (
TOTPDigits = 6
TOTPSecretBytes = 20
TOTPWindow = 1
TOTPSecretLength = 32
)
// GenerateTOTPSecret returns a base32 secret suitable for authenticator apps.
+4 -2
View File
@@ -17,8 +17,8 @@ import "context"
//
// Each per-service backend additionally runs its own migration for tables
// it exclusively owns (e.g. ContentScanner's media_worker_jobs/
// media_analysis_tasks, CraftStudio's generated_media/downloaded_media,
// ProjectConfigurator's mount_paths) - those are NOT run here.
// media_analysis_tasks, CraftStudio's generated_media/downloaded_media) -
// those are NOT run here.
func (c *Core) Migrate(ctx context.Context) error {
for _, statement := range migrationStatements {
if _, err := c.db.Exec(ctx, statement); err != nil {
@@ -67,6 +67,7 @@ var migrationStatements = []string{
file_path TEXT,
original_filename TEXT,
active BOOLEAN NOT NULL DEFAULT TRUE,
content_scanner_processed BOOLEAN NOT NULL DEFAULT FALSE,
metadata JSONB NOT NULL DEFAULT '{}'::jsonb,
width INT,
height INT,
@@ -81,6 +82,7 @@ var migrationStatements = []string{
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
modified_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
)`,
`ALTER TABLE media ADD COLUMN IF NOT EXISTS content_scanner_processed BOOLEAN NOT NULL DEFAULT FALSE`,
`ALTER TABLE media ADD COLUMN IF NOT EXISTS funscript_action_count INT`,
`ALTER TABLE media ADD COLUMN IF NOT EXISTS funscript_avg_speed REAL`,
`ALTER TABLE media ADD COLUMN IF NOT EXISTS funscript_max_speed REAL`,
@@ -255,6 +255,7 @@ func TestMediaStreamAndThumbnailAgainstPostgres(t *testing.T) {
func TestMediaStatsAndViewsAgainstPostgres(t *testing.T) {
h := newDBHarness(t)
h.insertMedia(t, "rt-stats", "video", "rt-stats.mp4", true)
state := func(token string) map[string]any {
return dataOf(t, h.do(http.MethodGet, "/media/state?mediaKey=rt-stats", token, ""))
}