54 Commits
Author SHA1 Message Date
Gabriel20xxandClaude Sonnet 5 ee59571552 Rename ProjectConfigurator, restructure Projects workspace, retire MediaCollection naming
- Rename MediaConfig -> ProjectConfigurator throughout; drop the Parameters
  tab/page; rename the Mounts tab to Projects and restructure it into three
  sections: Central services, Main services, Third-party services
- Add a self-describe contract (GET /api/info returning name/tabs/mountTypes)
  and a server-side discovery proxy (POST /api/discover-service) so adding a
  main service only requires a URL
- Add ProjectConfigurator HA: multiple instances now sync their settings with
  each other (GET /api/settings/export, POST /api/settings/sync, a periodic
  background puller), last-write-wins per key by updated_at
- Add a generic, project-agnostic file-storage API on CarrierNode
  (GET/POST/DELETE /api/mount/{project}/{type}[/*]) driven by the same
  configured_mounts data the Projects workspace already writes, usable by any
  registered project, not just the media family
- Add last_login_at tracking to the shared auth Store/User (schema, queries,
  UpdateLastLogin) and surface it through the shared web-ui ManagedUser type
  and UserManagement component
- Retire the "MediaCollection" name: Go module -> repos.gfranz.ch/Gabriel20xx/shared/media-backend,
  binary -> mediabackend, session cookie default -> "session", media-webui
  merged into webui, media-shared-assets renamed to legacy-assets and pruned
  to the one file MediaDesktop still uses

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-04 15:02:16 +02:00
Gabriel20xxandClaude Sonnet 5 07cf3308da Remove Admin option from header profile dropdown
User management is now centralized in AuthGuard's webui, so the
per-project Admin dialog (user CRUD + require-login toggle) is
redundant. The require-login toggle will move to ProjectConfigurator
in the future.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-04 09:29:23 +02:00
Gabriel20xxandClaude Sonnet 5 72c3ba028c Fix ruff formatting in authclient test_authclient.py
Reformat the new scheme-detection test cases with `ruff format` (line
length) so `ruff format --check .` passes in consumers that lint the
whole repo, e.g. Heretic/HordeWorker's CI.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-03 22:22:21 +02:00
Gabriel20xxandClaude Sonnet 5 449bb6fd6a Auto-detect scheme for AUTHGUARD_URL instead of always assuming https
A bare host:port (e.g. a LAN AuthGuard reachable only over plain HTTP)
was always defaulting to https, so a TLS handshake against a plain-HTTP
AuthGuard failed at the transport level. Now a loopback, RFC1918/RFC4193
private, or link-local host (or a .local name) defaults to http instead;
an explicit http:// or https:// is still always honored as-is.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-03 21:46:53 +02:00
Gabriel20xx 730bf0463f Double sc-page-header bottom margin 2026-09-03 19:56:56 +02:00
Gabriel20xx 7b5a4e6c2c Merge media-webui/media-backend into the general shared component/backend system
Extracts a new backend/authproxy package for the AuthGuard-proxy helper
functions (session cookie handling, input normalization, error
translation) that Bitmagnet/GameStream/media-backend/AutoCode/
CollabTable/PubliSafe/SimpleCollection/SyncServer/UnraidMonitor/
OutdoorGames were each independently reimplementing, and repoints all
of them onto it.

Extends packages/web-ui's Button/Badge with the variants media-webui
needed (outline, icon size, primary badge) and promotes EmptyState/
SectionTitle/Metric/StatusWidget/StatusDialog into the shared library,
then migrates media-webui off its own diverged ui/{button,card,badge,
metric} components and local duplicates of the promoted components
onto @gabriel20xx/web-ui, so media-webui is a proper consumer of the
same design system every other project already uses instead of a
parallel fork.

Also removes the dead `desktop`/MediaDesktop service variant from
media-backend and media-webui (MediaDesktop is an Electron client that
never actually runs this stack).
2026-09-03 00:14:01 +02:00
Gabriel20xx 9589d07baf media-backend/media-webui: proxy admin login identity to AuthGuard
The media-collection family (KioskDisplay, MediaAnalyzer, MediaTools,
MediaViewer, MediaServant, ModerationHub, ProjectConfigurator) shared one
standalone local single-admin auth implementation with no AuthGuard
connection, including its own local "reset admin account" flow - the same
situation the recently-migrated forks were in. Proxies every /auth/... and
/api/auth/... admin-identity operation to AuthGuard via the existing Go
authclient, forwards its Set-Cookie, keeps a local one-time setup-claim flag
(reusing the existing settings table, no schema change), and drops the local
reset flow entirely (only AuthGuard's own web UI keeps one now).

Deliberately left untouched: the separate "moderator manages platform
users" surface (admin_storage.go's mountModeratorRoutes) and the
independent loginRequired/auth_required public-install toggle, both of
which are unrelated to this service's own admin login identity despite
superficially sharing code style/table with the migrated pieces.
2026-09-02 21:45:19 +02:00
Gabriel20xx de9b599232 authclient: auto-detect https for a bare AUTHGUARD_URL host, extend Java client to full surface
AUTHGUARD_URL only needs to name a host/IP now - all four language
clients (Go/Node/Python/Java) assume https:// when no scheme is given,
so a bare value like 192.168.1.50:8080 works instead of failing
outright; an explicit http://scheme is still left alone for local/LAN
deployments.

Java's AuthClient was validate-only; it now mirrors the Go/Node/Python
clients' full surface (register/login/logout/me/totp*/passwordReset*/
managedUsers*/setupStatus) using Jackson for the request/response JSON
this larger surface has to build and parse, since MegaBasterd (this
package's only verified consumer) already depends on Jackson.
2026-09-02 20:49:29 +02:00
Gabriel20xxandClaude Sonnet 5 f164e0d0d2 Halve sc-page-header gap to the content below it
margin-bottom: 1rem left too much empty space between the title card
and the cards/content on the page. Reduce to 0.5rem.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-02 17:35:26 +02:00
Gabriel20xxandClaude Sonnet 5 f5a20b72af Extend Go/Python/Node authclient with the full AuthGuard API surface
Previously each authclient only supported GET /api/session/validate - the
"just gate requests behind a valid session" case. A service that runs its
own login/register/admin-user-management screens proxied to AuthGuard
(GameStream's pattern, now also used by InfiniteVideo and OutdoorGames)
needs much more: register, login, logout, me, totp_enable/verify/disable,
password-reset request/confirm, and managed-user list/create/update/delete.

The Go client already had this full surface from GameStream's original
migration; Python and Node only had validate(), so both gained the same
method set as Go, mirroring its behavior and JSON wire shapes exactly
(register/login/logout return the raw Set-Cookie values to forward,
totp_required surfaces on a 401 from login, etc). Also adds a SetupStatus/
setup_status/setupStatus method (GET /api/setup-status) so a service's own
first-launch flow can tell whether AuthGuard already has an account before
showing its own account-creation form, and adds totp_enabled to the Go
client's PublicUser (AuthGuard has reported it for a while; the client
just hadn't picked it up).

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-02 10:37:21 +02:00
Gabriel20xxandClaude Sonnet 5 db733a6bf4 Fix critical login/session bug: Store.find() Scan missing Role column
Store.find() (backing FindByIdentifier - used by login - FindByID, and
FindSessionUser, used on every authenticated request) selected 7 columns
but only Scan()'d 6 destinations, missing &user.Role entirely:

  find user: find auth user: number of field descriptions must equal
  number of destinations, got 7 and 6

This broke essentially all login and session validation, in every project
vendoring this package, against a real Postgres database. It went
undetected because the existing test suite uses a hand-written fake store
in each consumer's own httpapi package that never exercises the real
query/Scan pair - only a real driver round-trip surfaces a
destination-count mismatch like this.

Adds backend/auth/store_integration_test.go (skipped unless DATABASE_URL
is set, so it never runs in default CI) covering create, find-by-identifier,
find-by-id, find-by-session, and list-users against a real database, to
catch this class of regression going forward. Verified against a real
Postgres container: reproduced the exact reported error before the fix,
passes after.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-01 21:51:15 +02:00
Gabriel20xxandClaude Sonnet 5 bdcdfc2dbe Add Central/AuthGuard to sync-consumers.ps1
AuthGuard grew its own web UI (@gabriel20xx/web-ui-based admin dashboard),
so it now vendors the full shared snapshot the same way every other
consumer with a frontend does, not just shared/backend.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-01 17:38:22 +02:00
Gabriel20xxandClaude Sonnet 5 a2454812f9 Rewrite README for consistency and accuracy across the workspace
Brings this repo's README in line with a shared house style (Tech
Stack table, Repository Layout, Configuration table, Quick Start,
Development, Testing, CI/CD) and fixes staleness accumulated since it
was last written - outdated auth model descriptions, stale directory
names, dead references to removed code, and CI details that no longer
matched the actual workflow files.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-01 16:11:58 +02:00
Gabriel20xxandClaude Sonnet 5 d2ad20e0f8 Fix ty type error in authclient test: HTTPError needs a Message, not None
urllib.error.HTTPError's stub declares hdrs: Message (non-optional);
passing None works at runtime but fails strict type checking. Heretic's
lint workflow runs ty over its full tree including the vendored shared/
snapshot, which is what caught this - construct an empty Message()
instead, identical runtime behavior.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-01 11:23:21 +02:00
Gabriel20xxandClaude Sonnet 5 170076ef4d Support a per-project destination folder in sync-consumers.ps1
The engine/media-backend family (KioskDisplay, MediaAnalyzer,
MediaTools, MediaViewer, MediaServant, ModerationHub,
ProjectConfigurator) mounted this same snapshot via a git submodule at
'engine' instead of 'shared' - which broke in CI, since Gitea Actions'
injected token doesn't cover cross-repo submodule auth for a private
repo. Converting them to the same vendored-copy pattern every other
consumer already uses needed the destination folder name to be
per-project instead of hardcoded to 'shared'.

Also adds MediaDesktop, which previously tried to check out this repo
as a sibling directory in CI (outside the job's workspace root - Gitea
Actions rejects that outright) instead of vendoring a copy.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-01 11:21:21 +02:00
Gabriel20xxandClaude Sonnet 5 43d77dd47c Regenerate package-lock.json to include media-shared-assets
packages/media-shared-assets (added earlier, version 2.0.0, with a
vitest devDependency) was never reflected in the root lockfile - it
looks like npm install was never re-run at the workspace root after
the package was added. `npm ci` therefore failed everywhere with
"Missing: @gabriel20xx/media-shared-assets@2.0.0 from lock file" plus
a cascade of missing vitest/chai transitive deps.

This is the shared source of truth every consumer project vendors a
snapshot of via sync-consumers.ps1, so the stale lockfile was breaking
`npm ci` in every consumer's CI too (confirmed via GameStream's Tests
workflow, which has been red since the media-shared-assets sync
landed). Regenerated with `npm install`; verified `npm ci`
(both with and without --omit=dev) and the full lint/test suite
(Node/Svelte, Go x2, Python) all pass clean.

Next: re-sync this fixed shared/ snapshot into every consumer via
sync-consumers.ps1 -Commit -Push.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-01 08:43:25 +02:00
Gabriel20xxandClaude Sonnet 5 97a5ecdf83 Extend authclient with the full AuthGuard API surface
Adds Register/Login/Logout/Me/TOTP(Enable/Verify/Disable)/password-reset/
admin-user-management (List/Create/Update/DeleteManagedUser) methods,
APIError, SessionResult, and ForwardCookies - everything a Go service
needs to fully retire its own local auth in favor of proxying to
AuthGuard, not just validate an existing session.

Cookie-forwarding pattern: a service passes AuthGuard's own Set-Cookie
straight through via ForwardCookies rather than minting its own session
token, so the browser holds one real AuthGuard cookie under whatever
AUTH_COOKIE_DOMAIN scope was configured - no double session-mapping,
correct cross-project SSO for free. Documented in the package doc comment.

First real consumer: GameStream's cutover (separate commit, that repo).

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-31 23:49:21 +02:00
Gabriel20xxandClaude Sonnet 5 5bf8ec5cee Add Java authclient module (mirrors the Go/Node/Python authclient)
Java 8-compatible (not 11+/records as originally suggested) - verified
MegaBasterd's pom.xml compiles this source directly via
build-helper-maven-plugin rather than depending on a packaged jar, and
is pinned to source/target 1.8, so newer APIs would have broken its
real build. Uses HttpURLConnection instead of java.net.http.HttpClient,
a plain final class instead of a record.

No JSON dependency added (defensive regex parsing of AuthGuard's small
fixed response shape) - java-backend has zero runtime dependencies
today and this is the only class that would need one otherwise.

Also added this package's first pom.xml, README.md, and test directory
- none existed before.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-31 23:09:52 +02:00
Gabriel20xxandClaude Sonnet 5 ac516a7dc8 Add Python authclient module (mirrors the Go/Node authclient)
Async (asyncpg-consistent with the rest of this package), stdlib-only
HTTP via urllib + asyncio.to_thread (no new dependency for one GET
call). Framework-agnostic by design: read the two real consumers
(HordeWorker's aiohttp webui, Heretic's FastAPI app) and they don't
share a framework, so token_from_request/resolve_user work over plain
headers/cookies mappings rather than shipping a framework adapter.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-31 23:06:07 +02:00
Gabriel20xxandClaude Sonnet 5 7c813cce9e Remove deleted MediaCollection from sync-consumers.ps1's consumer list
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-31 22:32:10 +02:00
Gabriel20xxandClaude Sonnet 5 858cc1ac63 Add Node.js authclient (mirrors the Go shared/backend/authclient)
Lets any Node service validate requests against AuthGuard instead of
maintaining its own local user table - the missing piece needed to
wire AuthGuard into OutdoorGamesPlatform/server-node and any other
Node service, matching what authclient already provides for Go.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-31 22:31:46 +02:00
Gabriel20xxandClaude Sonnet 5 51a8e11ef6 Add stylelint config to media-shared-assets (was relying on the monorepo root's)
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-31 22:23:34 +02:00
Gabriel20xxandClaude Sonnet 5 1347b671e0 Add configuration reference table to media-backend README
Merged from MediaCollection's root README.md before deleting that repo -
the rest of that README (repository layout, docker build commands)
described the now-superseded monorepo structure and would be misleading
to keep verbatim.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-31 22:22:14 +02:00
Gabriel20xxandClaude Sonnet 5 00359c538b Merge unique content from docs/media-shared.md before deleting MediaCollection
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-31 22:21:30 +02:00
Gabriel20xxandClaude Sonnet 5 38a349eb52 Fix media-backend/media-webui: re-copy from post-revert MediaCollection
The original MediaEngine extraction (later folded into this repo) had
been done BEFORE the owner's decision to revert the MediaViewer/Forge/
etc. rename, and was never re-extracted afterward like the other 7
service repos were - it silently carried stale renamed-era text
(e.g. 'Porter' instead of 'MediaServant') into Go doc comments, WebUI
prose, project-icons.json, and app-config.ts. Re-copied both directories
fresh from the current (correctly reverted) MediaCollection/backend and
MediaCollection/WebUI, then re-applied the go.mod replace-directive fix
and re-added SECURITY_AUDIT.md (also newly migrated from MediaCollection
root - a real deployment security checklist that would otherwise have
been lost when MediaCollection is deleted).

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-31 22:19:58 +02:00
Gabriel20xxandClaude Sonnet 5 acde180086 Fold MediaEngine (media-backend, media-webui) into this repo
Per owner decision: MediaEngine (the Media product family's Go backend
and SvelteKit frontend, previously its own repo referenced by 7 thin
service repos via git submodule) is folded directly into shared/ as
media-backend/ and media-webui/, rather than staying separate.

media-backend/go.mod's replace directive now points at ../backend (a
true sibling within this repo) instead of a vendored ../shared/backend
copy, since there's no more nested vendoring - it's the real thing.

Also moved MediaEngine's own CI (media-backend-lint.yml,
media-backend-tests.yml) and dev tooling scripts (scripts/media/*,
audit/lint/enforce scripts for the media-backend+media-webui content),
fixing their path assumptions for the new layout, and dropped
scripts/media/sync-shared.mjs (confirmed dead code, and now doubly
obsolete since there's no more vendored shared/ subfolder for it to
check). Added media:* script aliases to package.json for the moved
tooling, namespaced to avoid colliding with this repo's own scripts.

Also fixed sync-consumers.ps1's workspace-root resolution to walk up
until it finds a directory containing both Original/ and Forks/,
instead of assuming shared/ is always a direct child of the workspace
root - it broke when shared/ moved from Web/shared to Web/Central/shared
earlier in this same restructuring. Removed the now-obsolete
Original/MediaEngine entry from its consumer list.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-31 22:06:29 +02:00
Gabriel20xxandClaude Sonnet 5 79d9461769 Add media-shared-assets package (from MediaCollection/MediaShared)
Browser theme CSS/JS assets shared across MediaCollection's client apps,
moved here per owner request to centralize shared components. The
build:theme sync script now lives inside the package itself rather than
assuming a monorepo-root scripts/ sibling; its 'test' script is a no-op
placeholder since the package has no tests of its own yet.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-31 21:45:47 +02:00
Gabriel20xxandClaude Sonnet 5 94af6d7601 feat: support pageHeaderActions in AppShell
Wires a pageHeaderActions snippet prop through to PageHeader's actions
slot, so consumers can render content (e.g. stats, buttons) in the
page title container alongside the title/description.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-31 17:17:52 +02:00
Gabriel20xx fa69e6ef3c feat: add Pagination component to shared web-ui
AutoCode's actions page depends on a Pagination component that only
ever existed in its consumer-side shared/ snapshot, never in this
canonical repo. Every sync-consumers.ps1 run deleted it as stale,
repeatedly breaking AutoCode's lint and Docker builds. Adding it here
makes the sync idempotent instead of destructive.
2026-08-29 12:58:27 +02:00
Gabriel20xx 91f372612a Fix stale consumer project path for HordeWorker
The folder was renamed from HordeWorkerReGen to HordeWorker; the sync
script's project list still pointed at the old name, so that consumer
silently stopped receiving shared-package syncs.
2026-08-29 12:42:48 +02:00
Gabriel20xx 3f5ff73a49 Standardize AppShell container gaps to 16px
The page title box and the content below it (e.g. a search/filter
panel) were separated by 24px, and main had 32px/48px top/bottom
padding around that stack. Both now use a consistent 16px.
2026-08-29 12:31:15 +02:00
Gabriel20xx fc0e376df8 feat: add NotificationStack component and notify API for toast notifications 2026-08-27 13:32:13 +02:00
Gabriel20xx d005ee6f51 feat: implement notification system with customizable message handling 2026-08-27 13:29:34 +02:00
Gabriel20xx e8a9b25037 fix: update setup handling logic to improve account creation flow 2026-08-23 22:18:20 +02:00
Gabriel20xx 4227293345 fix: adjust visited color for profile menu items to maintain consistency 2026-08-20 17:03:14 +02:00
Gabriel20xxandClaude Sonnet 5 a53bafff3f feat: add admin dialog and move user management out of settings/profile modals
- Add a dedicated admin entry (with icon) to the header profile dropdown, visible only to admins
- Move all user-management settings from SettingsDialog/ProfileDialog into a new AdminDialog
- Export AdminDialog from the package index

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-20 14:02:16 +02:00
Gabriel20xx c94f749430 fix: reformat config.py to match its declared 100-column line length
One line was wrapped as if for an 88-column budget, violating the
100-column ruff line-length this package declares in its own
pyproject.toml - ruff format (which respects that nested config)
correctly flagged it as unformatted.
2026-08-19 13:04:17 +02:00
Gabriel20xx a90f4eb71f fix: give header brand icon a fixed size
The brand <img> sized itself with width/height:100%, but it isn't
wrapped in a sized container like the fallback letter-mark is, and its
flex-item parent has no definite size for the percentage to resolve
against - so it rendered at whatever intrinsic size the favicon
happened to report instead of a consistent icon size.
2026-08-19 12:06:17 +02:00
Gabriel20xx 6c364623fd feat: add icons to profile menu items
- Simplify brand logo markup
- Add profile, settings, and about icons
2026-08-14 07:33:11 +00:00
Gabriel20xx 5ebaafc113 fix: center mobile menu button in header 2026-08-12 06:57:12 +00:00
Gabriel20xx 61bed33c8a Reading additional input from stdin...
OpenAI Codex v0.147.0
--------
workdir: /workspace/Personal/Web/shared
model: gpt-5.6-luna
provider: openai
approval: never
sandbox: read-only
reasoning effort: xhigh
reasoning summaries: none
session id: 019febcc-0ed6-7d22-87cb-e6ad13926ec6
--------
user
Write a concise git commit message for the following diff. Use the Conventional Commits style (e.g. "feat: ...", "fix: ..."), a summary line under 72 characters, optionally followed by a blank line and up to 3 short bullet points for notable details. Output only the commit message itself - no preamble, no explanation, no markdown fences.

diff --git a/scripts/sync-consumers.ps1 b/scripts/sync-consumers.ps1
index fd6591f..1895c21 100644
--- a/scripts/sync-consumers.ps1
+++ b/scripts/sync-consumers.ps1
@@ -103,7 +103,12 @@ function Convert-ToConsumerWebUiPackage {

     $manifest = Get-Content -LiteralPath $PackagePath -Raw | ConvertFrom-Json
     $manifest.files = @('src', 'README.md')
-    $manifest.dependencies = [pscustomobject]@{}
+    if ($null -ne $manifest.dependencies) {
+        $designTokensDependency = $manifest.dependencies.PSObject.Properties['@gabriel20xx/design-tokens']
+        if ($null -ne $designTokensDependency) {
+            $manifest.dependencies.PSObject.Properties.Remove('@gabriel20xx/design-tokens')
+        }
+    }
     $manifest.svelte = './src/index.ts'
     $manifest.types = './src/index.ts'

@@ -133,6 +138,7 @@ function Convert-ToConsumerWebUiSources {
     if (Test-Path -LiteralPath $stylesPath) {
         $styles = Get-Content -LiteralPath $stylesPath -Raw
         $styles = $styles.Replace("@import '@gabriel20xx/design-tokens/theme.css';", "@import '../../../design-tokens/theme.css';")
+        $styles = $styles.Replace('@import "@gabriel20xx/design-tokens/theme.css";', "@import '../../../design-tokens/theme.css';")
         Write-Utf8NoBom -Path $stylesPath -Content $styles
     }

warning: Codex could not find bubblewrap on PATH. Install bubblewrap with your OS package manager. See the sandbox prerequisites: https://developers.openai.com/codex/concepts/sandboxing#prerequisites. Codex will use the bundled bubblewrap in the meantime.
codex
fix: preserve consumer dependencies and rewrite token imports

- Remove only the design-tokens dependency
- Support single- and double-quoted CSS imports
tokens used
10,345
fix: preserve consumer dependencies and rewrite token imports

- Remove only the design-tokens dependency
- Support single- and double-quoted CSS imports
2026-08-10 13:10:54 +00:00
Gabriel20xx 81077527ac Add favicon support and loading state to authentication components 2026-08-10 10:42:40 +02:00
Gabriel20xx d0b18a4902 Update shared web UI auth and profile menu 2026-08-09 10:34:06 +02:00
Gabriel20xx e3544617e1 Enhance web-ui components and styles with new features and dependencies
- Added @lucide/svelte as a dependency for icon support in various components.
- Updated AboutDialog, AppShell, AuthPage, Header, SettingsDialog, and styles for improved functionality and UI consistency.
- Introduced new props and state management for better user experience.
- Refactored CSS for cleaner styling and improved layout.
2026-08-07 15:18:50 +02:00
Gabriel20xx ce6db8a457 Bump package versions to 0.1.1 and update npm publish workflow with registry authentication 2026-08-06 21:35:49 +02:00
Gabriel20xx da1cdca3b2 Rename shared code references 2026-08-06 16:55:51 +02:00
Gabriel20xx df68167d04 Fix Windows Git hook launcher 2026-08-06 16:09:51 +02:00
Gabriel20xx 9a79e6f649 Add automatic SharedCode consumer synchronization 2026-08-06 16:09:41 +02:00
Gabriel20xx dfae1cb572 Bump Go and Python package release to 0.1.1
Publish Go package / Publish shared Go module (push) Successful in 57s
Publish npm packages / Publish shared npm packages (push) Failing after 39s
Publish Python package / Publish shared Python package (push) Successful in 12s
2026-08-06 12:12:04 +02:00
Gabriel20xx 752f3ba433 Fix Go and Python package publishing workflows 2026-08-06 12:07:26 +02:00
Gabriel20xx 72a5e289f6 Add npm and Python package publishing workflows
Publish npm packages / Publish shared npm packages (push) Successful in 16s
Publish Python package / Publish shared Python package (push) Failing after 16s
2026-08-06 11:34:52 +02:00
Gabriel20xx 01401cb1cd Make release retry independent of tag script version 2026-08-06 10:59:26 +02:00
Gabriel20xx d3cb76dc32 Add Gitea release trigger for Go package publishing 2026-08-06 10:58:20 +02:00
Gabriel20xx 61b1eda37d Fix Go package output path handling 2026-08-06 10:40:23 +02:00
149 changed files with 32057 additions and 401 deletions

No files matched your search

+5
View File
@@ -0,0 +1,5 @@
---
"@gabriel20xx/web-ui": minor
---
Add a shared `NotificationStack` component and `notify` API (`notify.success/error/warning/info`) for toast-style action feedback. `AppShell` now mounts `NotificationStack` automatically, so any application using `AppShell` gets it without further wiring.
+30 -5
View File
@@ -4,6 +4,9 @@ on:
push: push:
tags: tags:
- 'backend/v*' - 'backend/v*'
release:
types:
- published
jobs: jobs:
publish: publish:
@@ -32,8 +35,13 @@ jobs:
- name: Package Go module - name: Package Go module
env: env:
RELEASE_TAG: ${{ github.ref_name }} RELEASE_TAG: ${{ github.event_name == 'release' && github.event.release.tag_name || github.ref_name }}
run: bash scripts/package-go-module.sh "$RELEASE_TAG" "$RUNNER_TEMP/gitea-go-package" run: |
package_directory='gitea-go-package'
rm -rf "$package_directory"
mkdir -p "$package_directory"
bash scripts/package-go-module.sh "$RELEASE_TAG" "$package_directory"
find "$package_directory" -maxdepth 1 -type f -name '*.zip' -print -quit | grep -q .
- name: Publish to Gitea Package Registry - name: Publish to Gitea Package Registry
env: env:
@@ -46,8 +54,25 @@ jobs:
echo 'PACKAGE_REGISTRY_USERNAME and PACKAGE_REGISTRY_TOKEN secrets are required.' >&2 echo 'PACKAGE_REGISTRY_USERNAME and PACKAGE_REGISTRY_TOKEN secrets are required.' >&2
exit 1 exit 1
fi fi
package_file="$(find "$RUNNER_TEMP/gitea-go-package" -maxdepth 1 -type f -name '*.zip' -print -quit)" package_file="$(find gitea-go-package -maxdepth 1 -type f -name '*.zip' -print -quit)"
test -n "$package_file" test -n "$package_file"
curl --fail-with-body --user "$PACKAGE_REGISTRY_USERNAME:$PACKAGE_REGISTRY_TOKEN" \ response_file="$(mktemp)"
http_status="$(curl --silent --show-error --fail-with-body \
--user "$PACKAGE_REGISTRY_USERNAME:$PACKAGE_REGISTRY_TOKEN" \
--output "$response_file" \
--write-out '%{http_code}' \
--upload-file "$package_file" \ --upload-file "$package_file" \
"$GITEA_GO_REGISTRY" "$GITEA_GO_REGISTRY" || true)"
case "$http_status" in
201)
echo 'Go package published.'
;;
409)
echo 'Go package version already exists; leaving the immutable package unchanged.'
;;
*)
cat "$response_file" >&2
echo "Gitea Go package upload failed with HTTP status $http_status." >&2
exit 1
;;
esac
+93
View File
@@ -0,0 +1,93 @@
name: Publish npm packages
on:
push:
tags:
- 'v*'
release:
types:
- published
jobs:
publish:
name: Publish shared npm packages
runs-on: ubuntu-latest
permissions:
contents: read
steps:
- name: Checkout source
uses: actions/checkout@v4
- name: Set up Node.js
uses: actions/setup-node@v4
with:
node-version: 22
cache: npm
- name: Install and build packages
run: |
npm ci
npm run build
- name: Configure Gitea npm registry
env:
PACKAGE_REGISTRY_USERNAME: ${{ secrets.PACKAGE_REGISTRY_USERNAME }}
PACKAGE_REGISTRY_TOKEN: ${{ secrets.PACKAGE_REGISTRY_TOKEN }}
run: |
set -euo pipefail
if [ -z "$PACKAGE_REGISTRY_USERNAME" ] || [ -z "$PACKAGE_REGISTRY_TOKEN" ]; then
echo 'PACKAGE_REGISTRY_USERNAME and PACKAGE_REGISTRY_TOKEN secrets are required.' >&2
exit 1
fi
npmrc_path="$RUNNER_TEMP/gitea-npmrc"
umask 077
{
printf '@gabriel20xx:registry=https://repos.gfranz.ch/api/packages/Gabriel20xx/npm/\n'
printf '//repos.gfranz.ch/api/packages/Gabriel20xx/npm/:_authToken=%s\n' "$PACKAGE_REGISTRY_TOKEN"
printf 'always-auth=true\n'
} > "$npmrc_path"
printf 'NPM_CONFIG_USERCONFIG=%s\n' "$npmrc_path" >> "$GITHUB_ENV"
- name: Publish npm packages
env:
PACKAGE_REGISTRY_USERNAME: ${{ secrets.PACKAGE_REGISTRY_USERNAME }}
PACKAGE_REGISTRY_TOKEN: ${{ secrets.PACKAGE_REGISTRY_TOKEN }}
NPM_REGISTRY: https://repos.gfranz.ch/api/packages/Gabriel20xx/npm/
run: |
set -euo pipefail
if [ -z "$PACKAGE_REGISTRY_USERNAME" ] || [ -z "$PACKAGE_REGISTRY_TOKEN" ]; then
echo 'PACKAGE_REGISTRY_USERNAME and PACKAGE_REGISTRY_TOKEN secrets are required.' >&2
exit 1
fi
for package in \
@gabriel20xx/design-tokens \
@gabriel20xx/web-ui \
@gabriel20xx/node-backend; do
version="$(npm pkg get version --workspace="$package" | tr -d '"[:space:]')"
package_path="${package//@/%40}"
package_path="${package_path//\//%2f}"
metadata_file="$(mktemp)"
metadata_status="$(curl --silent --show-error --fail-with-body \
--user "$PACKAGE_REGISTRY_USERNAME:$PACKAGE_REGISTRY_TOKEN" \
--output "$metadata_file" \
--write-out '%{http_code}' \
"${NPM_REGISTRY}${package_path}" || true)"
case "$metadata_status" in
200)
if grep -Fq "\"$version\"" "$metadata_file"; then
echo "$package@$version is already published; skipping."
rm -f "$metadata_file"
continue
fi
;;
404)
;;
*)
cat "$metadata_file" >&2
echo "Gitea npm metadata lookup failed with HTTP status $metadata_status." >&2
exit 1
;;
esac
npm publish --workspace="$package" --registry="$NPM_REGISTRY"
rm -f "$metadata_file"
done
+74
View File
@@ -0,0 +1,74 @@
name: Publish Python package
on:
push:
tags:
- 'v*'
release:
types:
- published
jobs:
publish:
name: Publish shared Python package
runs-on: ubuntu-latest
permissions:
contents: read
steps:
- name: Checkout source
uses: actions/checkout@v4
- name: Set up Python
uses: actions/setup-python@v5
with:
python-version: '3.12'
- name: Build and publish package
env:
PACKAGE_REGISTRY_USERNAME: ${{ secrets.PACKAGE_REGISTRY_USERNAME }}
PACKAGE_REGISTRY_TOKEN: ${{ secrets.PACKAGE_REGISTRY_TOKEN }}
TWINE_REPOSITORY_URL: https://repos.gfranz.ch/api/packages/Gabriel20xx/pypi
run: |
set -euo pipefail
if [ -z "$PACKAGE_REGISTRY_USERNAME" ] || [ -z "$PACKAGE_REGISTRY_TOKEN" ]; then
echo 'PACKAGE_REGISTRY_USERNAME and PACKAGE_REGISTRY_TOKEN secrets are required.' >&2
exit 1
fi
python -m pip install --disable-pip-version-check --no-cache-dir build twine
package_directory="$RUNNER_TEMP/gitea-pypi-package"
python -m build packages/python-backend --outdir "$package_directory"
package_index_url="${TWINE_REPOSITORY_URL%/}/simple/gabriel20xx-shared-backend/"
package_index_file="$(mktemp)"
package_index_status="$(curl --silent --show-error --fail-with-body \
--user "$PACKAGE_REGISTRY_USERNAME:$PACKAGE_REGISTRY_TOKEN" \
--output "$package_index_file" \
--write-out '%{http_code}' \
"$package_index_url" || true)"
package_files=("$package_directory"/*)
files_to_upload=()
case "$package_index_status" in
200)
for package_file in "${package_files[@]}"; do
if ! grep -Fq "$(basename "$package_file")" "$package_index_file"; then
files_to_upload+=("$package_file")
fi
done
;;
404)
files_to_upload=("${package_files[@]}")
;;
*)
cat "$package_index_file" >&2
echo "Gitea PyPI package lookup failed with HTTP status $package_index_status." >&2
exit 1
;;
esac
if [ "${#files_to_upload[@]}" -eq 0 ]; then
echo 'Python package version already exists with all build artifacts; leaving it unchanged.'
exit 0
fi
TWINE_USERNAME="$PACKAGE_REGISTRY_USERNAME" \
TWINE_PASSWORD="$PACKAGE_REGISTRY_TOKEN" \
python -m twine upload --non-interactive \
--repository-url "$TWINE_REPOSITORY_URL" \
"${files_to_upload[@]}"
+14
View File
@@ -0,0 +1,14 @@
#!/bin/sh
set -euo pipefail
repo_root="$(git rev-parse --show-toplevel)"
sync_script="$repo_root/scripts/sync-consumers.ps1"
if command -v pwsh >/dev/null 2>&1; then
pwsh -NoProfile -NonInteractive -ExecutionPolicy Bypass -File "$sync_script" -Commit
elif command -v powershell.exe >/dev/null 2>&1; then
powershell.exe -NoProfile -NonInteractive -ExecutionPolicy Bypass -File "$sync_script" -Commit
else
echo "shared synchronization requires pwsh or powershell.exe." >&2
exit 1
fi
+32
View File
@@ -0,0 +1,32 @@
name: Lint (media-backend)
on:
push:
branches: ['**']
paths:
- 'media-backend/**'
- '.github/workflows/media-backend-lint.yml'
pull_request:
branches: [main, master]
paths:
- 'media-backend/**'
- '.github/workflows/media-backend-lint.yml'
workflow_dispatch: {}
jobs:
vet:
name: Lint
runs-on: ubuntu-latest
permissions:
contents: read
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Set up Go
uses: actions/setup-go@v5
with:
go-version: '1.26.x'
cache-dependency-path: media-backend/go.sum
- name: Vet backend
working-directory: media-backend
run: go vet ./...
+32
View File
@@ -0,0 +1,32 @@
name: Tests (media-backend)
on:
push:
branches: ['**']
paths:
- 'media-backend/**'
- '.github/workflows/media-backend-tests.yml'
pull_request:
branches: [main, master]
paths:
- 'media-backend/**'
- '.github/workflows/media-backend-tests.yml'
workflow_dispatch: {}
jobs:
test:
name: Tests
runs-on: ubuntu-latest
permissions:
contents: read
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Set up Go
uses: actions/setup-go@v5
with:
go-version: '1.26.x'
cache-dependency-path: media-backend/go.sum
- name: Test backend
working-directory: media-backend
run: go test ./...
+2
View File
@@ -1,9 +1,11 @@
node_modules/ node_modules/
packages/*/dist/ packages/*/dist/
packages/*/.svelte-kit/ packages/*/.svelte-kit/
webui/.svelte-kit/
*.tgz *.tgz
.npm/ .npm/
__pycache__/ __pycache__/
*.py[cod] *.py[cod]
*.egg-info/ *.egg-info/
.venv/ .venv/
packages/*/target/
+87 -210
View File
@@ -1,196 +1,99 @@
# SharedCode packages # shared
This folder is the single source of truth for reusable web UI across the projects in this workspace. The single source of truth for code reused across every project in this workspace: a Svelte design system and application shell, backend helpers (Postgres access, config, auth/session persistence, an AuthGuard client, log shipping) in four languages, and the Go media-backend/webui powering the whole `MEDIA_SERVICE`-family of projects.
The first packages are: ---
- `@gabriel20xx/design-tokens` — colors, typography, spacing, radii, shadows, and light/dark theme variables. ## Tech Stack
- `@gabriel20xx/web-ui` — Svelte components for the application shell, header/navigation, authentication, dialogs, profile/settings/about windows, buttons, cards, badges, and page headers.
- `repos.gfranz.ch/Gabriel20xx/shared/backend` — Go helpers for environment configuration, `pgx` PostgreSQL pools, transactions, common auth persistence/passwords/tokens, and embedded Goose migrations.
- `@gabriel20xx/node-backend` — Node.js `pg` pool/configuration, transactions, migrations, and auth/session persistence.
- `gabriel20xx-shared-backend` — Python `asyncpg` pool/configuration and auth/session persistence.
The components do not import `$app/state`, `$lib` stores, or a project-specific API. Applications provide those things through props and callbacks. | Layer | Technology |
|-------|------------|
| Web UI | Svelte, TypeScript |
| Backend helpers | Go, Node.js, Python, Java |
| Database | PostgreSQL (via `pgx`, `pg`, or `asyncpg`) |
| Package registry | Gitea npm / Go / PyPI registries |
## Build and check the packages ---
Run these commands from this directory: ## Packages
| Package | Language | Purpose |
|---|---|---|
| `@gabriel20xx/design-tokens` | CSS | Colors, typography, spacing, radii, shadows, light/dark theme variables. |
| `@gabriel20xx/web-ui` | Svelte | Application shell, header/navigation, auth screens, dialogs, buttons, cards, badges. |
| `@gabriel20xx/legacy-assets` | Browser JS/CSS | Legacy client-side assets for the media-backend/`MEDIA_SERVICE` family. |
| `repos.gfranz.ch/Gabriel20xx/shared/backend` | Go | Env config, `pgx` pools/transactions, auth persistence, an AuthGuard client (`authclient`), log shipping (`logshipper`), embedded Goose migrations. |
| `@gabriel20xx/node-backend` | Node.js | `pg` pool/config/transactions/migrations, auth/session persistence, an AuthGuard client. |
| `gabriel20xx-shared-backend` | Python | `asyncpg` pool/config, auth/session persistence, an AuthGuard client. |
| `com.gabriel20xx.shared.auth` | Java | An AuthGuard client, mirroring the Go/Node/Python ones. |
| `media-backend` / `webui` | Go / Svelte | The Go binary and web UI powering the `MEDIA_SERVICE`-family projects (see below). |
The `web-ui` components don't import `$app/state`, `$lib` stores, or a project-specific API — applications provide those through props and callbacks.
---
## How consumers actually use this
There are two different distribution paths in this workspace, used for different things:
### Vendored snapshot (the one every project actually uses)
Every consumer project vendors a full copy of this repo's tracked files into its own `shared/` (or, for the `media-backend` family, `engine/`) directory, committed directly rather than installed from a registry. This exists because none of these projects are meant to resolve a private registry dependency in a fresh CI checkout without extra credentials, and because a git submodule pointing at this (private) repo breaks the same way — see `scripts/sync-consumers.ps1`'s own comments for the full history.
To pull the latest snapshot into every registered consumer:
```powershell
# from this repo
.\scripts\sync-consumers.ps1 -Commit -Push
```
The script copies every tracked file in this repo into each consumer's destination folder, regenerates any `package-lock.json` that depends on a local `file:` package, and commits/pushes only if something actually changed ("Sync shared/engine snapshot from `<short-sha>`"). Consumers are registered in the script's `$consumerProjects` list, each with a destination folder (`shared` by default, `engine` for the media-backend family). A `post-commit` hook (installed via `scripts/install-sync-hook.ps1`) runs this automatically — with `-Commit` only, never `-Push` — after every commit to this repo, so pushing the sync commits it creates to each consumer is still a manual follow-up step.
### Published registry packages (for standalone/external use)
The npm, Go, and Python packages are also published to this Gitea instance's package registries, for a project that genuinely wants a version-pinned dependency rather than a vendored snapshot. `.gitea/workflows/publish-*.yml` publish on a `v*` tag push or a matching Gitea release; `PACKAGE_REGISTRY_USERNAME`/`PACKAGE_REGISTRY_TOKEN` must be configured as Actions secrets. See "Publishing" below for the details. No project in this workspace currently consumes a package this way — it exists for future/external use.
---
## Development
```bash ```bash
npm install npm install
npm run check npm run check
npm run build npm run build # builds packages/web-ui/dist (gitignored, not committed)
npm run test:node-backend npm run test:node-backend
``` ```
`npm run build` creates the distributable package in `packages/web-ui/dist`. The generated `dist` directory is intentionally ignored by the package configuration and should not be committed.
Validate the Go backend package from `shared/backend`:
```bash ```bash
cd backend cd backend
go test ./... go test ./...
go vet ./... go vet ./...
``` ```
## Consume from the Gitea repository
The repository is the canonical source and is installable directly from Gitea. The root package
builds the Svelte package during installation and exposes the runtime packages as subpaths:
```bash ```bash
npm install --save-exact git+https://repos.gfranz.ch/Gabriel20xx/shared#<commit> cd media-backend
go test ./...
go vet ./...
``` ```
Use the shared UI from the root package: ---
```ts ## Typical `web-ui` wiring
import { AppShell, AuthPage, Header, SettingsDialog } from '@gabriel20xx/shared-code/web-ui';
```
Import the shared stylesheet once from the application's global stylesheet:
```css
@import '@gabriel20xx/shared-code/web-ui/styles.css';
```
The dependency should be pinned to a commit in application lockfiles. Update it when a new
SharedCode version has been validated.
## Publish the individual packages
The package names use the `@gabriel20xx` npm scope. That scope must belong to the npm account used to publish. If a different scope is preferred, replace the scope consistently in both package manifests and imports before publishing.
Publish the tokens first because `web-ui` depends on them:
```bash
npm login
npm publish --workspace=@gabriel20xx/design-tokens --access public
npm publish --workspace=@gabriel20xx/web-ui --access public
npm publish --workspace=@gabriel20xx/node-backend --access public
```
For a private registry, configure that registry and omit `--access public` if the registry does not use npm's public scoped-package rules.
## Install individual packages from a registry
From a project's frontend directory, install the published UI package:
```bash
npm install @gabriel20xx/web-ui@^0.1.0
```
The design-token package is installed transitively. Install it directly only when an application needs to reference its theme file itself:
```bash
npm install @gabriel20xx/design-tokens@^0.1.0
```
Import the shared stylesheet once from the application's global stylesheet, before project-specific overrides:
```css
@import '@gabriel20xx/web-ui/styles.css';
```
The stylesheet imports the design tokens and uses an `sc-` prefix, so it does not require Tailwind and does not collide with existing project class names. Set `data-theme="light"` or `data-theme="dark"` on the application root to select a theme. Dark is the default.
## Use the shared Go backend package
The Go module is published to the private Gitea Go Package Registry. Configure a
read-only package token in the consuming workflow as `PACKAGE_REGISTRY_USERNAME`
and `PACKAGE_REGISTRY_TOKEN`, then configure Go to use the registry before running
`go get`, `go test`, or `go build`:
```bash
export GOPROXY=https://repos.gfranz.ch/api/packages/Gabriel20xx/go,https://proxy.golang.org
export GONOSUMDB=repos.gfranz.ch/Gabriel20xx/shared/*
```
From a Go backend directory, add the released module (the module is a subdirectory of the shared repository):
```bash
go get repos.gfranz.ch/Gabriel20xx/shared/backend@v0.1.0
```
Then initialize the pool and shared auth store at startup:
```go
import (
"context"
"log"
"repos.gfranz.ch/Gabriel20xx/shared/backend/auth"
"repos.gfranz.ch/Gabriel20xx/shared/backend/postgres"
)
cfg, err := postgres.FromEnv()
if err != nil {
log.Fatal(err)
}
pool, err := postgres.Open(context.Background(), cfg)
if err != nil {
log.Fatal(err)
}
defer pool.Close()
if err := auth.EnsureSchema(context.Background(), pool, auth.DefaultSchemaOptions()); err != nil {
log.Fatal(err)
}
authStore := auth.NewStore(pool)
```
Use `auth.SchemaOptions{SingleUser: false, APITokens: true}` for a multi-user service that needs API tokens. The shared package owns persistence primitives and password/token utilities; each application still owns authorization rules, cookies, HTTP handlers, roles, and domain tables.
For embedded SQL migrations, use `migrate.Up(ctx, databaseURL, embeddedMigrations, "migrations")`. The package does not contain application tables, so migrations remain versioned with the service that owns those tables.
The Go module lives under `backend`, so its release tag must use the submodule prefix (`backend/v0.1.0`). The consuming `go.mod` uses the normal module version (`v0.1.0`). To publish a release, push a tag such as `backend/v0.1.0`; the Gitea workflow packages the module and uploads it to the private registry. Never reuse an existing package version.
For Node services, install the shared package after publishing it:
```bash
npm install @gabriel20xx/node-backend@^0.1.0
```
For Python services, build and publish the wheel to the Python package index used by the projects, then install it normally:
```bash
python -m pip install build
python -m build packages/python-backend
python -m pip install gabriel20xx-shared-backend==0.1.0
```
The Node and Python packages intentionally expose the same infrastructure concepts but use their native database drivers. This is the safe way to share behavior across the polyglot services; a Go package cannot be imported by the Python or Node applications.
## Existing MediaCollection shared package
`Original/MediaCollection/MediaShared` is an existing, larger media-specific package. It remains in place for media workflows and startup integration, while the MediaCollection WebUI authentication surface and admin-reset code use this shared package. Its remaining generic responsibilities can be migrated independently without introducing another authentication screen.
## Typical application wiring
```svelte ```svelte
<script lang="ts"> <script lang="ts">
import { import { AboutDialog, AppShell, ProfileDialog, SettingsDialog } from '@gabriel20xx/web-ui';
AboutDialog,
AppShell,
ProfileDialog,
SettingsDialog
} from '@gabriel20xx/web-ui';
import { page } from '$app/state'; import { page } from '$app/state';
let aboutOpen = $state(false); let aboutOpen = $state(false);
let profileOpen = $state(false); let profileOpen = $state(false);
let settingsOpen = $state(false); let settingsOpen = $state(false);
const navItems = [
{ href: '/', label: 'Dashboard' },
{ href: '/about', label: 'About' }
];
</script> </script>
<AppShell <AppShell
brand="My application" brand="My application"
currentPath={page.url.pathname} currentPath={page.url.pathname}
navItems={navItems} navItems={[{ href: '/', label: 'Dashboard' }]}
onLogout={() => auth.logout()} onLogout={() => auth.logout()}
onProfile={() => (profileOpen = true)} onProfile={() => (profileOpen = true)}
onSettings={() => (settingsOpen = true)} onSettings={() => (settingsOpen = true)}
@@ -200,70 +103,44 @@ The Node and Python packages intentionally expose the same infrastructure concep
<slot /> <slot />
{/snippet} {/snippet}
</AppShell> </AppShell>
<AboutDialog
bind:open={aboutOpen}
brand="My application"
description="A short description supplied by this project."
version="1.0.0"
/>
<SettingsDialog bind:open={settingsOpen}>
{#snippet children()}
<!-- Project-specific settings controls go here. -->
{/snippet}
</SettingsDialog>
<ProfileDialog
bind:open={profileOpen}
currentEmail={auth.user?.email ?? ''}
currentUsername={auth.user?.username ?? ''}
onSave={(profile) => auth.updateProfile(profile)}
/>
``` ```
For authentication, use the same shell with `AuthPage` and connect the callbacks to the application's existing auth service: Import the stylesheet once, before project-specific overrides: `@import '@gabriel20xx/web-ui/styles.css';`. It uses an `sc-` class prefix, so it doesn't require Tailwind and doesn't collide with existing project classes. Set `data-theme="light"` or `data-theme="dark"` on the application root; dark is the default.
```svelte For authentication, use `AuthPage` and wire its callbacks to the project's auth service — every project in this workspace either talks to AuthGuard directly or proxies through its own backend to AuthGuard. See `Central/AuthGuard/README.md` for the identity service this whole authentication surface is built to work with.
<AuthPage
brand="My application" ---
onLogin={(credentials) => auth.login(credentials.identifier, credentials.password)}
onSetup={(credentials) => auth.setup(credentials)} ## Using the Go backend package
onRequestReset={() => auth.requestAdminReset()}
onConfirmReset={(code) => auth.confirmAdminReset(code)} ```go
setupRequired={setupRequired} import (
tagline="Your project tagline" "repos.gfranz.ch/Gabriel20xx/shared/backend/auth"
/> "repos.gfranz.ch/Gabriel20xx/shared/backend/authclient"
"repos.gfranz.ch/Gabriel20xx/shared/backend/postgres"
)
pool, _ := postgres.Open(ctx, postgres.FromEnv())
authStore := auth.NewStore(pool) // local Postgres-backed accounts
client := authclient.New(authGuardURL) // or proxy to AuthGuard instead
``` ```
Applications that support MFA can enable the shared optional authenticator-code field with Use `auth.SchemaOptions{SingleUser: false, APITokens: true}` for a multi-user service that needs API tokens. This package owns persistence primitives and password/token utilities; each application still owns authorization rules, cookies, HTTP handlers, roles, and domain tables. For embedded SQL migrations, use `migrate.Up(ctx, databaseURL, embeddedMigrations, "migrations")` — this package has no application tables of its own, so migrations stay versioned with the service that owns those tables.
`showTotp` and forward `credentials.totpToken` to their login endpoint. The base layout and reset
controls remain the same as every other shared auth screen.
The shared reset controls request a short-lived code printed by the server-side auth package and consume it once after confirmation. The package handles form state, validation attributes, loading state, and error presentation. The application remains responsible for deciding where to navigate after a successful action and how errors are returned. ---
## Local package development ## Publishing
Before publishing, build the packages and install them from the local workspace in a frontend project:
```bash ```bash
# From Web/shared npm run changeset # describe the change
npm run build npm run version-packages # bump versions, commit the changelog
npm run release # publishes npm packages in dependency order (design-tokens first)
# From a project frontend directory; do not commit this file dependency for CI
npm install ../../../shared/packages/design-tokens ../../../shared/packages/web-ui
``` ```
For CI and normal development, use the published version instead of a `file:` dependency. A local file dependency only works when the checkout also contains the sibling `shared` directory. The Go module lives under `backend`, so its release tag uses the submodule prefix (`backend/v0.1.0`); push that tag and the Gitea workflow packages and uploads the module. The npm and Python workflows both skip a version already present in the registry, so retrying a partially completed release is safe.
## Updating the design system ---
When a component or token changes: ## CI/CD
1. Run `npm run changeset` and describe the change. `lint.yml` and `tests.yml` each run three jobs — Node/Svelte, Go, and Python — plus dedicated `media-backend-lint.yml`/`media-backend-tests.yml` for the `media-backend` Go module. `publish-npm.yml`, `publish-go.yml`, and `publish-python.yml` handle registry publishing as described above.
2. Run `npm run version-packages` and commit the generated version/changelog files.
3. Run `npm install`, `npm run check`, `npm run build`, and `npm run test:node-backend`.
4. Run `npm run release`; Changesets publishes the npm packages in dependency order.
5. Update each project with `npm install @gabriel20xx/web-ui@<new-version>` and commit its lockfile.
The package boundary is intentional: application-specific screens stay in their project, while repeated visual language and account/layout infrastructure stays here.
+2
View File
@@ -6,7 +6,9 @@ services, not application-specific SQL or HTTP handlers.
- `config` — environment string, required value, boolean, integer, and duration helpers. - `config` — environment string, required value, boolean, integer, and duration helpers.
- `postgres` — validated `DATABASE_URL` configuration, `pgxpool` creation/ping, transaction wrapper, and PostgreSQL error classification. - `postgres` — validated `DATABASE_URL` configuration, `pgxpool` creation/ping, transaction wrapper, and PostgreSQL error classification.
- `auth` — shared bcrypt policy, secure token generation/hashing, account/session schema, and account/session persistence. - `auth` — shared bcrypt policy, secure token generation/hashing, account/session schema, and account/session persistence.
- `authclient` — HTTP client and `net/http` middleware for services that adopt the centralized AuthServer instead of embedding `auth` against their own database.
- `migrate` — embedded filesystem adapter for Goose migrations. - `migrate` — embedded filesystem adapter for Goose migrations.
- `logshipper` — client adapter for LoggingServer (Web/LoggingServer): batches and ships log entries centrally while mirroring the same human-readable output and Debug/Info/Warn/Error/Critical/Audit/*Ctx method surface as each project's local internal/logging package.
Run `go test ./...` and `go vet ./...` from this directory. The module path is Run `go test ./...` and `go vet ./...` from this directory. The module path is
`repos.gfranz.ch/Gabriel20xx/shared/backend`; change it if the shared folder is `repos.gfranz.ch/Gabriel20xx/shared/backend`; change it if the shared folder is
+33 -11
View File
@@ -24,6 +24,9 @@ type User struct {
Role Role Role Role
CreatedAt time.Time CreatedAt time.Time
UpdatedAt time.Time UpdatedAt time.Time
// LastLoginAt is nil until the account's first successful POST
// /api/login (registration alone does not set it - see UpdateLastLogin).
LastLoginAt *time.Time
} }
// Store performs common auth persistence against a caller-owned pool. // Store performs common auth persistence against a caller-owned pool.
@@ -67,7 +70,8 @@ func EnsureSchema(ctx context.Context, pool *pgxpool.Pool, options SchemaOptions
totp_secret TEXT NOT NULL DEFAULT '', totp_secret TEXT NOT NULL DEFAULT '',
totp_enabled BOOLEAN NOT NULL DEFAULT FALSE, totp_enabled BOOLEAN NOT NULL DEFAULT FALSE,
created_at TIMESTAMPTZ NOT NULL DEFAULT now(), created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
updated_at TIMESTAMPTZ NOT NULL DEFAULT now() updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),
last_login_at TIMESTAMPTZ
); );
ALTER TABLE auth_users ADD COLUMN IF NOT EXISTS email TEXT NOT NULL DEFAULT ''; ALTER TABLE auth_users ADD COLUMN IF NOT EXISTS email TEXT NOT NULL DEFAULT '';
ALTER TABLE auth_users ADD COLUMN IF NOT EXISTS role TEXT NOT NULL DEFAULT 'user'; ALTER TABLE auth_users ADD COLUMN IF NOT EXISTS role TEXT NOT NULL DEFAULT 'user';
@@ -75,6 +79,10 @@ func EnsureSchema(ctx context.Context, pool *pgxpool.Pool, options SchemaOptions
ALTER TABLE auth_users ADD COLUMN IF NOT EXISTS totp_enabled BOOLEAN NOT NULL DEFAULT FALSE; ALTER TABLE auth_users ADD COLUMN IF NOT EXISTS totp_enabled BOOLEAN NOT NULL DEFAULT FALSE;
ALTER TABLE auth_users ADD COLUMN IF NOT EXISTS created_at TIMESTAMPTZ NOT NULL DEFAULT now(); ALTER TABLE auth_users ADD COLUMN IF NOT EXISTS created_at TIMESTAMPTZ NOT NULL DEFAULT now();
ALTER TABLE auth_users ADD COLUMN IF NOT EXISTS updated_at TIMESTAMPTZ NOT NULL DEFAULT now(); ALTER TABLE auth_users ADD COLUMN IF NOT EXISTS updated_at TIMESTAMPTZ NOT NULL DEFAULT now();
-- last_login_at is nullable (NULL means "never logged in" - registration
-- alone does not count, only a successful POST /api/login) and has no
-- DEFAULT, unlike every other column here.
ALTER TABLE auth_users ADD COLUMN IF NOT EXISTS last_login_at TIMESTAMPTZ;
UPDATE auth_users SET role = 'superadmin' UPDATE auth_users SET role = 'superadmin'
WHERE id = (SELECT id FROM auth_users ORDER BY created_at, id LIMIT 1) WHERE id = (SELECT id FROM auth_users ORDER BY created_at, id LIMIT 1)
AND NOT EXISTS (SELECT 1 FROM auth_users WHERE role = 'superadmin'); AND NOT EXISTS (SELECT 1 FROM auth_users WHERE role = 'superadmin');
@@ -204,9 +212,9 @@ func (s *Store) CreateUser(ctx context.Context, username, email, passwordHash st
VALUES ($1, $2, $3, VALUES ($1, $2, $3,
CASE WHEN EXISTS (SELECT 1 FROM auth_users) THEN 'user' ELSE 'superadmin' END, CASE WHEN EXISTS (SELECT 1 FROM auth_users) THEN 'user' ELSE 'superadmin' END,
now()) now())
RETURNING id, username, email, password_hash, role, created_at, updated_at RETURNING id, username, email, password_hash, role, created_at, updated_at, last_login_at
`, username, email, passwordHash).Scan( `, username, email, passwordHash).Scan(
&user.ID, &user.Username, &user.Email, &user.PasswordHash, &user.Role, &user.CreatedAt, &user.UpdatedAt, &user.ID, &user.Username, &user.Email, &user.PasswordHash, &user.Role, &user.CreatedAt, &user.UpdatedAt, &user.LastLoginAt,
) )
if err != nil { if err != nil {
var pgErr *pgconn.PgError var pgErr *pgconn.PgError
@@ -224,7 +232,7 @@ func (s *Store) FindByIdentifier(ctx context.Context, identifier string) (*User,
return nil, err return nil, err
} }
return s.find(ctx, ` return s.find(ctx, `
SELECT id, username, email, password_hash, role, created_at, updated_at SELECT id, username, email, password_hash, role, created_at, updated_at, last_login_at
FROM auth_users FROM auth_users
WHERE username = $1 OR lower(email) = lower($1) WHERE username = $1 OR lower(email) = lower($1)
`, identifier) `, identifier)
@@ -236,7 +244,7 @@ func (s *Store) FindByID(ctx context.Context, id int64) (*User, error) {
return nil, err return nil, err
} }
return s.find(ctx, ` return s.find(ctx, `
SELECT id, username, email, password_hash, role, created_at, updated_at SELECT id, username, email, password_hash, role, created_at, updated_at, last_login_at
FROM auth_users WHERE id = $1 FROM auth_users WHERE id = $1
`, id) `, id)
} }
@@ -264,7 +272,7 @@ func (s *Store) ListUsers(ctx context.Context) ([]User, error) {
return nil, err return nil, err
} }
rows, err := s.pool.Query(ctx, ` rows, err := s.pool.Query(ctx, `
SELECT id, username, email, role, created_at, updated_at SELECT id, username, email, role, created_at, updated_at, last_login_at
FROM auth_users ORDER BY created_at, id FROM auth_users ORDER BY created_at, id
`) `)
if err != nil { if err != nil {
@@ -274,7 +282,7 @@ func (s *Store) ListUsers(ctx context.Context) ([]User, error) {
users := make([]User, 0) users := make([]User, 0)
for rows.Next() { for rows.Next() {
var user User var user User
if err := rows.Scan(&user.ID, &user.Username, &user.Email, &user.Role, &user.CreatedAt, &user.UpdatedAt); err != nil { if err := rows.Scan(&user.ID, &user.Username, &user.Email, &user.Role, &user.CreatedAt, &user.UpdatedAt, &user.LastLoginAt); err != nil {
return nil, fmt.Errorf("scan auth user: %w", err) return nil, fmt.Errorf("scan auth user: %w", err)
} }
users = append(users, user) users = append(users, user)
@@ -292,9 +300,9 @@ func (s *Store) CreateManagedUser(ctx context.Context, username, email, password
err := s.pool.QueryRow(ctx, ` err := s.pool.QueryRow(ctx, `
INSERT INTO auth_users (username, email, password_hash, role, updated_at) INSERT INTO auth_users (username, email, password_hash, role, updated_at)
VALUES ($1, $2, $3, $4, now()) VALUES ($1, $2, $3, $4, now())
RETURNING id, username, email, password_hash, role, created_at, updated_at RETURNING id, username, email, password_hash, role, created_at, updated_at, last_login_at
`, username, email, passwordHash, role).Scan( `, username, email, passwordHash, role).Scan(
&user.ID, &user.Username, &user.Email, &user.PasswordHash, &user.Role, &user.CreatedAt, &user.UpdatedAt, &user.ID, &user.Username, &user.Email, &user.PasswordHash, &user.Role, &user.CreatedAt, &user.UpdatedAt, &user.LastLoginAt,
) )
if err != nil { if err != nil {
var pgErr *pgconn.PgError var pgErr *pgconn.PgError
@@ -326,6 +334,20 @@ func (s *Store) UpdateUser(ctx context.Context, id int64, username, email, passw
return nil return nil
} }
// UpdateLastLogin stamps last_login_at to now(). Callers should treat this as
// best-effort: an already-successful login (the session is live) shouldn't
// fail because this update didn't - see AuthGuard's handleLogin for the
// intended "log and continue" pattern.
func (s *Store) UpdateLastLogin(ctx context.Context, id int64) error {
if err := s.validate(); err != nil {
return err
}
if _, err := s.pool.Exec(ctx, `UPDATE auth_users SET last_login_at = now() WHERE id = $1`, id); err != nil {
return fmt.Errorf("update last login: %w", err)
}
return nil
}
// DeleteUser removes one account. Callers enforce the superadmin/self policy. // DeleteUser removes one account. Callers enforce the superadmin/self policy.
func (s *Store) DeleteUser(ctx context.Context, id int64) error { func (s *Store) DeleteUser(ctx context.Context, id int64) error {
if err := s.validate(); err != nil { if err := s.validate(); err != nil {
@@ -358,7 +380,7 @@ func (s *Store) FindSessionUser(ctx context.Context, tokenHash string) (*User, e
return nil, err return nil, err
} }
return s.find(ctx, ` return s.find(ctx, `
SELECT u.id, u.username, u.email, u.password_hash, u.role, u.created_at, u.updated_at SELECT u.id, u.username, u.email, u.password_hash, u.role, u.created_at, u.updated_at, u.last_login_at
FROM auth_sessions s FROM auth_sessions s
JOIN auth_users u ON u.id = s.user_id JOIN auth_users u ON u.id = s.user_id
WHERE s.token_hash = $1 AND s.expires_at > now() WHERE s.token_hash = $1 AND s.expires_at > now()
@@ -423,7 +445,7 @@ func (s *Store) validate() error {
func (s *Store) find(ctx context.Context, query string, arg any) (*User, error) { func (s *Store) find(ctx context.Context, query string, arg any) (*User, error) {
var user User var user User
err := s.pool.QueryRow(ctx, query, arg).Scan( err := s.pool.QueryRow(ctx, query, arg).Scan(
&user.ID, &user.Username, &user.Email, &user.PasswordHash, &user.CreatedAt, &user.UpdatedAt, &user.ID, &user.Username, &user.Email, &user.PasswordHash, &user.Role, &user.CreatedAt, &user.UpdatedAt, &user.LastLoginAt,
) )
if errors.Is(err, pgx.ErrNoRows) { if errors.Is(err, pgx.ErrNoRows) {
return nil, nil return nil, nil
+121
View File
@@ -0,0 +1,121 @@
package auth
import (
"context"
"os"
"testing"
"time"
"repos.gfranz.ch/Gabriel20xx/shared/backend/postgres"
)
// TestStoreIntegration exercises Store against a real PostgreSQL database,
// covering exactly what the fake stores unit tests (in each consumer's own
// httpapi package) use instead cannot: a mismatch between a query's column
// list and Scan's destination count only surfaces against a real driver
// round-trip. Skipped unless DATABASE_URL points at a scratch database -
// never run by default in CI; point it at a local/throwaway database to run
// it, e.g.:
//
// DATABASE_URL=postgres://user:pass@localhost:5432/scratch?sslmode=disable go test ./auth/... -run TestStoreIntegration
func TestStoreIntegration(t *testing.T) {
url := os.Getenv("DATABASE_URL")
if url == "" {
t.Skip("DATABASE_URL not set; skipping Postgres integration test")
}
ctx := context.Background()
pool, err := postgres.Open(ctx, postgres.DefaultConfig(url))
if err != nil {
t.Fatalf("open pool: %v", err)
}
// Registered before the DeleteAllUsers cleanup below so it runs after
// that one (t.Cleanup runs in LIFO order).
t.Cleanup(pool.Close)
if err := EnsureSchema(ctx, pool, SchemaOptions{SingleUser: false, APITokens: true}); err != nil {
t.Fatalf("EnsureSchema() error = %v", err)
}
store := NewStore(pool)
if err := store.DeleteAllUsers(ctx); err != nil {
t.Fatalf("DeleteAllUsers() (pre-test cleanup) error = %v", err)
}
t.Cleanup(func() {
if err := store.DeleteAllUsers(context.Background()); err != nil {
t.Logf("cleanup: DeleteAllUsers() error = %v", err)
}
})
hash, err := HashPassword("correct horse battery staple")
if err != nil {
t.Fatalf("HashPassword() error = %v", err)
}
// The very first account is promoted to superadmin; this also exercises
// CreateUser's own Scan (7 RETURNING columns), separately from find's.
created, err := store.CreateUser(ctx, "root", "root@example.com", hash)
if err != nil {
t.Fatalf("CreateUser() error = %v", err)
}
if created.Role != RoleSuperAdmin {
t.Fatalf("first CreateUser() role = %q, want %q", created.Role, RoleSuperAdmin)
}
if created.LastLoginAt != nil {
t.Fatalf("CreateUser() LastLoginAt = %v, want nil before any login", created.LastLoginAt)
}
byIdentifier, err := store.FindByIdentifier(ctx, "root")
if err != nil {
t.Fatalf("FindByIdentifier() error = %v", err)
}
if byIdentifier == nil || byIdentifier.ID != created.ID || byIdentifier.Role != RoleSuperAdmin {
t.Fatalf("FindByIdentifier() = %+v, want a superadmin match for %+v", byIdentifier, created)
}
byID, err := store.FindByID(ctx, created.ID)
if err != nil {
t.Fatalf("FindByID() error = %v", err)
}
if byID == nil || byID.Username != "root" || byID.Role != RoleSuperAdmin {
t.Fatalf("FindByID() = %+v, want username %q and superadmin role", byID, "root")
}
_, hashedToken, err := NewSessionToken()
if err != nil {
t.Fatalf("NewSessionToken() error = %v", err)
}
if err := store.CreateSession(ctx, created.ID, hashedToken, time.Now().Add(time.Hour)); err != nil {
t.Fatalf("CreateSession() error = %v", err)
}
bySession, err := store.FindSessionUser(ctx, hashedToken)
if err != nil {
t.Fatalf("FindSessionUser() error = %v", err)
}
if bySession == nil || bySession.ID != created.ID {
t.Fatalf("FindSessionUser() = %+v, want a match for %+v", bySession, created)
}
users, err := store.ListUsers(ctx)
if err != nil {
t.Fatalf("ListUsers() error = %v", err)
}
if len(users) != 1 || users[0].ID != created.ID {
t.Fatalf("ListUsers() = %+v, want exactly the created user", users)
}
if users[0].LastLoginAt != nil {
t.Fatalf("ListUsers()[0].LastLoginAt = %v, want nil before any login", users[0].LastLoginAt)
}
if err := store.UpdateLastLogin(ctx, created.ID); err != nil {
t.Fatalf("UpdateLastLogin() error = %v", err)
}
afterLogin, err := store.FindByID(ctx, created.ID)
if err != nil {
t.Fatalf("FindByID() after UpdateLastLogin error = %v", err)
}
if afterLogin == nil || afterLogin.LastLoginAt == nil {
t.Fatalf("FindByID() after UpdateLastLogin = %+v, want LastLoginAt set", afterLogin)
}
}
+563
View File
@@ -0,0 +1,563 @@
// Package authclient is how any Go service in this workspace adopts a
// centralized AuthServer (see the AuthServer project, a sibling of this
// shared/backend module) instead of embedding shared/backend/auth's
// Store directly against its own private database.
//
// A service that switches to AuthServer trades "its own local user table"
// for "one HTTP call per request to AuthServer's /api/session/validate",
// gaining a single shared identity across every project that does the
// same. This package is additive: it does not change how
// shared/backend/auth works, and no project in this workspace is wired up
// to use it yet — that migration is a deliberate per-project decision, not
// something this package does automatically. See AuthServer/README.md's
// "Migration notes" section.
package authclient
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net"
"net/http"
"strings"
"time"
)
// User is the account AuthServer resolved for a validated session. It
// mirrors the fields returned by GET /api/session/validate.
type User struct {
ID int64 `json:"user_id"`
Username string `json:"username"`
Role string `json:"role"`
}
// ErrInvalidSession is returned by Validate when AuthServer reports the
// token/cookie as not currently valid (expired, unknown, or missing).
var ErrInvalidSession = errors.New("authclient: invalid or missing session")
// DefaultCookieName is the session cookie AuthServer sets and reads
// (AuthServer's own httpapi.SessionCookieName). A service that forwards
// AuthServer's Set-Cookie header straight through to its own browser client
// (see the "Cookie forwarding" note below) ends up reading this same cookie
// name back off incoming requests, so it is exported here rather than left
// as an unexported default only Middleware can see.
const DefaultCookieName = "auth_session"
// Client calls a centralized AuthServer instance over HTTP.
type Client struct {
// BaseURL is AuthServer's base URL, e.g. "https://auth.example.com"
// (no trailing slash required).
baseURL string
// HTTPClient is used for every request; defaults to a client with a
// short timeout suitable for a per-request auth check.
httpClient *http.Client
// CookieName is the cookie this client looks for on incoming requests
// when Middleware has no Authorization header to use. Defaults to
// "auth_session", matching AuthServer's SessionCookieName.
cookieName string
}
// Option configures optional Client behavior.
type Option func(*Client)
// WithHTTPClient overrides the default HTTP client (e.g. to tune timeouts
// or transport pooling).
func WithHTTPClient(hc *http.Client) Option {
return func(c *Client) { c.httpClient = hc }
}
// WithCookieName overrides the cookie name Middleware reads from incoming
// requests. Only needed if the AuthServer deployment was configured with a
// non-default session cookie name.
func WithCookieName(name string) Option {
return func(c *Client) { c.cookieName = name }
}
// 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")
// - the scheme is then inferred from the host: a loopback, RFC1918/RFC4193
// private, or link-local address, or a ".local" name, defaults to "http://"
// (a plain-HTTP AuthServer on a local network is the common case for those),
// anything else defaults to "https://". An explicit "http://" or "https://"
// is always left as-is, overriding the inference.
func New(baseURL string, opts ...Option) *Client {
c := &Client{
baseURL: normalizeBaseURL(baseURL),
httpClient: &http.Client{Timeout: 5 * time.Second},
cookieName: DefaultCookieName,
}
for _, opt := range opts {
opt(c)
}
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
}
if isPrivateHost(trimmed) {
return "http://" + trimmed
}
return "https://" + trimmed
}
// isPrivateHost reports whether hostport (a bare "host" or "host:port", no
// scheme) names a loopback, RFC1918/RFC4193 private, or link-local address,
// or a ".local" mDNS name -- the kind of host a plain-HTTP AuthServer is
// typically reachable at on a local network, as opposed to a public hostname
// expected to terminate TLS itself. Never performs DNS resolution: only
// literal IPs and the "localhost"/".local" names are recognized, so a real
// public hostname that merely happens to resolve to a private address still
// defaults to https.
func isPrivateHost(hostport string) bool {
host := hostport
if h, _, err := net.SplitHostPort(hostport); err == nil {
host = h
}
host = strings.Trim(host, "[]")
lower := strings.ToLower(host)
if lower == "localhost" || strings.HasSuffix(lower, ".local") {
return true
}
ip := net.ParseIP(host)
if ip == nil {
return false
}
return ip.IsLoopback() || ip.IsPrivate() || ip.IsLinkLocalUnicast()
}
// 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
// valid, and a plain error for any transport/decoding failure.
func (c *Client) Validate(ctx context.Context, token string) (*User, error) {
if c == nil || c.baseURL == "" {
return nil, errors.New("authclient: client has no base URL")
}
token = strings.TrimSpace(token)
if token == "" {
return nil, ErrInvalidSession
}
req, err := http.NewRequestWithContext(ctx, http.MethodGet, c.baseURL+"/api/session/validate", nil)
if err != nil {
return nil, fmt.Errorf("authclient: build request: %w", err)
}
req.Header.Set("Authorization", "Bearer "+token)
resp, err := c.httpClient.Do(req)
if err != nil {
return nil, fmt.Errorf("authclient: call AuthServer: %w", err)
}
defer resp.Body.Close()
var payload struct {
Valid bool `json:"valid"`
UserID int64 `json:"user_id"`
Username string `json:"username"`
Role string `json:"role"`
}
if err := json.NewDecoder(resp.Body).Decode(&payload); err != nil {
if resp.StatusCode == http.StatusUnauthorized {
return nil, ErrInvalidSession
}
return nil, fmt.Errorf("authclient: decode AuthServer response: %w", err)
}
if resp.StatusCode != http.StatusOK || !payload.Valid {
return nil, ErrInvalidSession
}
return &User{ID: payload.UserID, Username: payload.Username, Role: payload.Role}, nil
}
// contextKey is unexported so only this package can set/read the resolved
// user on a request context.
type contextKey struct{}
var userContextKey contextKey
// UserFromContext returns the user Middleware attached to the request
// context, or nil if none is present (e.g. called outside Middleware).
func UserFromContext(ctx context.Context) *User {
user, _ := ctx.Value(userContextKey).(*User)
return user
}
// Middleware extracts the session token from an incoming request — the
// cookie named by WithCookieName (default "auth_session"), falling back to
// an Authorization: Bearer header — validates it against AuthServer, and
// either responds 401 or attaches the resolved *User to the request
// context (retrieve it with UserFromContext) before calling next.
func (c *Client) Middleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
token := c.tokenFromRequest(r)
user, err := c.Validate(r.Context(), token)
if err != nil {
status := http.StatusUnauthorized
if !errors.Is(err, ErrInvalidSession) {
// A transport/decoding failure talking to AuthServer is not
// the same as "this visitor is unauthenticated"; still fail
// closed (401) rather than letting the request through, but
// keep the two cases distinguishable for callers that want
// to log or alert differently.
status = http.StatusUnauthorized
}
http.Error(w, "authentication required", status)
return
}
r = r.WithContext(context.WithValue(r.Context(), userContextKey, user))
next.ServeHTTP(w, r)
})
}
func (c *Client) tokenFromRequest(r *http.Request) string {
if header := r.Header.Get("Authorization"); header != "" {
if token, ok := strings.CutPrefix(header, "Bearer "); ok {
if token = strings.TrimSpace(token); token != "" {
return token
}
}
}
if cookie, err := r.Cookie(c.cookieName); err == nil {
return cookie.Value
}
return ""
}
// --- Full API surface -------------------------------------------------------
//
// Validate/Middleware above are all a service needs when it only ever
// forwards an already-established AuthServer 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 (backed by its own copy of
// shared/backend/auth's Store) and is migrating that flow onto AuthServer
// instead needs to originate those same calls itself — that's what the rest
// of this file adds. Every method mirrors one of AuthServer's
// internal/httpapi handlers exactly (method, path, request/response JSON
// shape); see AuthServer/README.md's HTTP API table and
// AuthServer/internal/httpapi/*.go for the source of truth this was written
// against.
//
// # Cookie forwarding
//
// Register and Login both return the Set-Cookie header(s) AuthServer's
// response carried, as SessionResult.Cookies (Logout returns them directly).
// A service proxying its own e.g. POST /login to AuthServer's POST
// /api/login should generally pass these straight through to its own
// http.ResponseWriter with ForwardCookies (or by hand with http.SetCookie):
// the browser then transparently holds AuthServer's own auth_session cookie
// under whatever Domain/Secure/SameSite/Max-Age AuthServer was configured
// with (see AUTH_COOKIE_DOMAIN in AuthServer's README for the cross-project
// SSO implications of that Domain scope), 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 AuthServer 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 does (see tokenFromRequest).
// PublicUser is the account payload register/login/me return: {"id",
// "username", "email", "role", "totp_enabled"}. It is deliberately distinct
// from the slimmer User type Validate/Middleware use (which mirrors GET
// /api/session/validate's {"user_id", "username", "role"} instead, and does
// not carry TOTP status at all).
type PublicUser struct {
ID int64 `json:"id"`
Username string `json:"username"`
Email string `json:"email"`
Role string `json:"role"`
TOTPEnabled bool `json:"totp_enabled"`
}
// ManagedUser is one row of GET /api/admin/users, and the payload returned
// by CreateManagedUser. It additionally carries CreatedAt, which PublicUser
// does not.
type ManagedUser struct {
ID int64 `json:"id"`
Username string `json:"username"`
Email string `json:"email"`
Role string `json:"role"`
CreatedAt time.Time `json:"created_at"`
}
// SessionResult is returned by Register and Login: the account AuthServer
// resolved, plus the Set-Cookie header(s) its response carried. See the
// "Cookie forwarding" note above.
type SessionResult struct {
User PublicUser
Cookies []*http.Cookie
}
// TOTPEnableResult is returned by TOTPEnable: a freshly provisioned, not yet
// active TOTP secret and its otpauth:// URI for a QR code / authenticator
// app. Confirm it with TOTPVerify.
type TOTPEnableResult struct {
Secret string `json:"secret"`
OTPAuthURL string `json:"otpauth_url"`
Enabled bool `json:"enabled"`
}
// ManagedUserInput is the body of CreateManagedUser (POST /api/admin/users)
// and UpdateManagedUser (PUT /api/admin/users/{id}). On update, a zero-value
// Username/Email/Password field means "leave unchanged" (AuthServer applies
// only non-empty fields), and Role is only honored when AuthServer's own
// authorization rules let the caller reassign it (only a superadmin actor,
// and never onto/away from a superadmin target) — see AuthServer's
// admin_users.go doc comments for the exact rules, which this client does
// not re-implement or pre-validate.
type ManagedUserInput struct {
Username string `json:"username,omitempty"`
Email string `json:"email,omitempty"`
Password string `json:"password,omitempty"`
Role *string `json:"role,omitempty"`
}
// APIError is returned when AuthServer responds with a non-2xx status. It
// carries the status code and (when AuthServer's JSON body decoded
// successfully) its {"error": "..."} message, so a caller can map it back
// onto its own service's response shape/status code rather than exposing
// AuthServer's wording verbatim. Use errors.As to recover it.
type APIError struct {
StatusCode int
Message string
// TOTPRequired is set only by Login, mirroring AuthServer's
// {"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.
TOTPRequired bool
}
func (e *APIError) Error() string {
return fmt.Sprintf("authclient: authserver responded %d: %s", e.StatusCode, e.Message)
}
// ForwardCookies re-sets each cookie (typically SessionResult.Cookies or
// Logout's return value) on w. This is the mechanical half of the "cookie
// forwarding" pattern described above.
func ForwardCookies(w http.ResponseWriter, cookies []*http.Cookie) {
for _, cookie := range cookies {
if cookie != nil {
http.SetCookie(w, cookie)
}
}
}
// call is the shared request/response plumbing for every method below: it
// builds a JSON request (skipped when body is nil), attaches token as a
// Bearer credential (skipped when token is ""), and on a 2xx response
// decodes the JSON body into out (skipped when out is nil). A non-2xx
// response is translated into *APIError. The returned *http.Response (nil
// on a transport-level failure) is provided so callers can read Cookies();
// its Body is always already fully read and closed.
func (c *Client) call(ctx context.Context, method, path, token string, body, out any) (*http.Response, error) {
if c == nil || c.baseURL == "" {
return nil, errors.New("authclient: client has no base URL")
}
var reader io.Reader
if body != nil {
data, err := json.Marshal(body)
if err != nil {
return nil, fmt.Errorf("authclient: encode request body: %w", err)
}
reader = bytes.NewReader(data)
}
req, err := http.NewRequestWithContext(ctx, method, c.baseURL+path, reader)
if err != nil {
return nil, fmt.Errorf("authclient: build request: %w", err)
}
if body != nil {
req.Header.Set("Content-Type", "application/json")
}
if token != "" {
req.Header.Set("Authorization", "Bearer "+token)
}
resp, err := c.httpClient.Do(req)
if err != nil {
return nil, fmt.Errorf("authclient: call AuthServer: %w", err)
}
defer resp.Body.Close()
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
var payload struct {
Error string `json:"error"`
TOTPRequired bool `json:"totp_required"`
}
_ = json.NewDecoder(io.LimitReader(resp.Body, 64*1024)).Decode(&payload)
message := payload.Error
if message == "" {
message = resp.Status
}
return resp, &APIError{StatusCode: resp.StatusCode, Message: message, TOTPRequired: payload.TOTPRequired}
}
if out != nil {
if err := json.NewDecoder(io.LimitReader(resp.Body, 1<<20)).Decode(out); err != nil {
return resp, fmt.Errorf("authclient: decode AuthServer response: %w", err)
}
}
return resp, nil
}
// SetupStatus calls GET /api/setup-status, an unauthenticated endpoint that
// reports whether AuthServer has any account at all. Accounts are
// centralized in AuthServer, so a caller with its own "first launch, create
// the initial admin" flow should consult this first: when it reports false,
// some account already exists (possibly created by a different project, or
// directly against AuthServer), and the caller should show its ordinary
// login screen instead of its own account-creation form.
func (c *Client) SetupStatus(ctx context.Context) (bool, error) {
var out struct {
SetupRequired bool `json:"setup_required"`
}
if _, err := c.call(ctx, http.MethodGet, "/api/setup-status", "", nil, &out); err != nil {
return false, err
}
return out.SetupRequired, nil
}
// Register calls POST /api/register, creating a new AuthServer account and
// starting a session for it.
func (c *Client) Register(ctx context.Context, username, email, password string) (*SessionResult, error) {
var out struct {
User PublicUser `json:"user"`
}
body := map[string]string{"username": username, "email": email, "password": password}
resp, err := c.call(ctx, http.MethodPost, "/api/register", "", body, &out)
if err != nil {
return nil, err
}
return &SessionResult{User: out.User, Cookies: resp.Cookies()}, nil
}
// Login calls POST /api/login. totpToken may be empty; AuthServer returns an
// *APIError with TOTPRequired set when the account has two-factor auth
// enabled and no valid code was supplied.
func (c *Client) Login(ctx context.Context, usernameOrEmail, password, totpToken string) (*SessionResult, error) {
var out struct {
User PublicUser `json:"user"`
}
body := map[string]string{"username_or_email": usernameOrEmail, "password": password}
if totpToken != "" {
body["totp_token"] = totpToken
}
resp, err := c.call(ctx, http.MethodPost, "/api/login", "", body, &out)
if err != nil {
return nil, err
}
return &SessionResult{User: out.User, Cookies: resp.Cookies()}, nil
}
// Logout calls POST /api/logout, deleting the session identified by token
// server-side. It returns the (cookie-clearing) Set-Cookie header(s)
// AuthServer's response carried; see ForwardCookies.
func (c *Client) Logout(ctx context.Context, token string) ([]*http.Cookie, error) {
resp, err := c.call(ctx, http.MethodPost, "/api/logout", token, nil, nil)
if err != nil {
return nil, err
}
return resp.Cookies(), nil
}
// Me calls GET /api/me, resolving token to its account.
func (c *Client) Me(ctx context.Context, token string) (*PublicUser, error) {
var out struct {
User PublicUser `json:"user"`
}
if _, err := c.call(ctx, http.MethodGet, "/api/me", token, nil, &out); err != nil {
return nil, err
}
return &out.User, nil
}
// TOTPEnable calls POST /api/totp/enable, provisioning (or re-provisioning)
// a pending TOTP secret for token's account. The secret is not active until
// TOTPVerify confirms a generated code.
func (c *Client) TOTPEnable(ctx context.Context, token string) (*TOTPEnableResult, error) {
var out TOTPEnableResult
if _, err := c.call(ctx, http.MethodPost, "/api/totp/enable", token, nil, &out); err != nil {
return nil, err
}
return &out, nil
}
// TOTPVerify calls POST /api/totp/verify, confirming code against the
// pending secret TOTPEnable provisioned and activating two-factor auth.
func (c *Client) TOTPVerify(ctx context.Context, token, code string) error {
_, err := c.call(ctx, http.MethodPost, "/api/totp/verify", token, map[string]string{"token": code}, nil)
return err
}
// TOTPDisable calls POST /api/totp/disable, turning two-factor auth off for
// token's account. AuthServer requires code to be one last valid TOTP code
// as proof of possession.
func (c *Client) TOTPDisable(ctx context.Context, token, code string) error {
_, err := c.call(ctx, http.MethodPost, "/api/totp/disable", token, map[string]string{"token": code}, nil)
return err
}
// RequestPasswordReset calls POST /api/password-reset/request. See
// AuthServer's README for an important caveat: this is not an "email me a
// link" flow — AuthServer prints a one-time code to its own process
// console, and only an operator with access to that console can relay it to
// the user. The response never reveals whether usernameOrEmail matched an
// account.
func (c *Client) RequestPasswordReset(ctx context.Context, usernameOrEmail string) error {
_, err := c.call(ctx, http.MethodPost, "/api/password-reset/request", "", map[string]string{"username_or_email": usernameOrEmail}, nil)
return err
}
// ConfirmPasswordReset calls POST /api/password-reset/confirm with the code
// an operator relayed out-of-band (see RequestPasswordReset) and a new
// password, and invalidates every existing session for that account.
func (c *Client) ConfirmPasswordReset(ctx context.Context, code, newPassword string) error {
_, err := c.call(ctx, http.MethodPost, "/api/password-reset/confirm", "", map[string]string{"code": code, "password": newPassword}, nil)
return err
}
// ListManagedUsers calls GET /api/admin/users. token's account must satisfy
// AuthServer's CanManageUsers check (admin or superadmin), or this returns
// an *APIError with StatusCode 401/403.
func (c *Client) ListManagedUsers(ctx context.Context, token string) ([]ManagedUser, error) {
var out struct {
Users []ManagedUser `json:"users"`
}
if _, err := c.call(ctx, http.MethodGet, "/api/admin/users", token, nil, &out); err != nil {
return nil, err
}
return out.Users, nil
}
// CreateManagedUser calls POST /api/admin/users. Only honored when token's
// account can manage users; see ManagedUserInput's doc comment for the Role
// authorization rule.
func (c *Client) CreateManagedUser(ctx context.Context, token string, input ManagedUserInput) (*ManagedUser, error) {
var out struct {
User ManagedUser `json:"user"`
}
if _, err := c.call(ctx, http.MethodPost, "/api/admin/users", token, input, &out); err != nil {
return nil, err
}
return &out.User, nil
}
// UpdateManagedUser calls PUT /api/admin/users/{id}.
func (c *Client) UpdateManagedUser(ctx context.Context, token string, id int64, input ManagedUserInput) error {
_, err := c.call(ctx, http.MethodPut, fmt.Sprintf("/api/admin/users/%d", id), token, input, nil)
return err
}
// DeleteManagedUser calls DELETE /api/admin/users/{id}.
func (c *Client) DeleteManagedUser(ctx context.Context, token string, id int64) error {
_, err := c.call(ctx, http.MethodDelete, fmt.Sprintf("/api/admin/users/%d", id), token, nil, nil)
return err
}
+85
View File
@@ -0,0 +1,85 @@
package authclient
import (
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"testing"
)
func TestNewNormalizesBaseURL(t *testing.T) {
cases := []struct {
name string
input string
want string
}{
{name: "bare public host gets https", input: "auth.example.com", want: "https://auth.example.com"},
{name: "bare private host:port gets http", input: "192.168.1.50:8080", want: "http://192.168.1.50:8080"},
{name: "bare public host:port gets https", input: "auth.example.com:8080", want: "https://auth.example.com:8080"},
{name: "loopback IPv4 gets http", input: "127.0.0.1:8080", want: "http://127.0.0.1:8080"},
{name: "10/8 private range gets http", input: "10.1.2.3:8080", want: "http://10.1.2.3:8080"},
{name: "172.16/12 private range gets http", input: "172.20.0.5:8080", want: "http://172.20.0.5:8080"},
{name: "172.x outside the 16-31 private range gets https", input: "172.32.0.5:8080", want: "https://172.32.0.5:8080"},
{name: "link-local IPv4 gets http", input: "169.254.1.1:8080", want: "http://169.254.1.1:8080"},
{name: "localhost name gets http", input: "localhost:8080", want: "http://localhost:8080"},
{name: ".local mDNS name gets http", input: "authguard.local:8080", want: "http://authguard.local:8080"},
{name: "loopback IPv6 gets http", input: "[::1]:8080", want: "http://[::1]:8080"},
{name: "unique-local IPv6 gets http", input: "[fd00::1]:8080", want: "http://[fd00::1]:8080"},
{name: "explicit http is left alone even for a public host", input: "http://auth.example.com", want: "http://auth.example.com"},
{name: "explicit https is left alone even for a private host", input: "https://192.168.1.50:8080", want: "https://192.168.1.50:8080"},
{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
response any
want bool
}{
{name: "no accounts yet", response: map[string]bool{"setup_required": true}, want: true},
{name: "an account already exists", response: map[string]bool{"setup_required": false}, want: false},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodGet || r.URL.Path != "/api/setup-status" {
t.Fatalf("unexpected request: %s %s", r.Method, r.URL.Path)
}
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(tc.response)
}))
defer server.Close()
client := New(server.URL)
got, err := client.SetupStatus(context.Background())
if err != nil {
t.Fatalf("SetupStatus() error = %v", err)
}
if got != tc.want {
t.Fatalf("SetupStatus() = %v, want %v", got, tc.want)
}
})
}
}
func TestSetupStatusPropagatesTransportError(t *testing.T) {
client := New("http://127.0.0.1:0")
if _, err := client.SetupStatus(context.Background()); err == nil {
t.Fatal("SetupStatus() expected an error against an unreachable server, got nil")
}
}
+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")
}
})
}
+438
View File
@@ -0,0 +1,438 @@
// Package logshipper is the client-side adapter for LoggingServer
// (Web/LoggingServer), the workspace's centralized log sink. It is the
// logging equivalent of the authclient package added alongside AuthServer:
// each service currently owns its own local internal/logging package (see
// Original/OutdoorGames/OutdoorGamesServerGo/internal/logging/logging.go for
// the canonical shape — a Logger tagged by module name, an env-driven level
// threshold, Debug/Info/Warn/Error/Critical/Audit/*Ctx methods, and an
// optional verbose JSON context dump gated by LOG_ALL). Shipper exposes that
// exact same method surface so a project can eventually swap its local
// logging.New(...) call for logshipper.New(...) with no call-site changes,
// once the owner decides to migrate a given service.
//
// No project imports this yet — see LoggingServer/README.md's "Migration
// notes" for the deliberate, per-project follow-up this requires.
//
// Shipper always writes the same human-readable line to stdout/stderr that
// the local loggers write today, in addition to batching entries off to
// LoggingServer. Nothing is lost if LoggingServer is never wired up, never
// reachable, or removed later — this is a mirror, not a replacement, for the
// container's own stdout/stderr logs.
package logshipper
import (
"bytes"
"context"
"encoding/json"
"fmt"
"net/http"
"os"
"strings"
"sync"
"time"
)
// Level mirrors internal/logging's severity scale in every service's local
// logger, so a threshold configured via the same LOG env var behaves
// identically whether it gates a local Logger or a Shipper.
type Level int
const (
LevelDebug Level = 10
LevelInfo Level = 20
LevelWarn Level = 30
LevelError Level = 40
LevelCritical Level = 50
LevelSilent Level = 100
)
func levelOf(s string) Level {
switch strings.ToLower(strings.TrimSpace(s)) {
case "debug":
return LevelDebug
case "warn", "warning":
return LevelWarn
case "error":
return LevelError
case "critical":
return LevelCritical
case "silent", "none", "off":
return LevelSilent
default:
return LevelInfo
}
}
// sevName is the canonical, lowercase level name LoggingServer's ingest API
// expects (debug/info/warn/error/critical), independent of the uppercase
// name used in the local stdout/stderr line.
func sevName(sev Level) (upper, lower string) {
switch sev {
case LevelDebug:
return "DEBUG", "debug"
case LevelWarn:
return "WARN", "warn"
case LevelError:
return "ERROR", "error"
case LevelCritical:
return "CRITICAL", "critical"
default:
return "INFO", "info"
}
}
const (
defaultFlushInterval = 2 * time.Second
defaultMaxBatchSize = 100
defaultBufferCapacity = 2000
defaultHTTPTimeout = 5 * time.Second
defaultWarnInterval = time.Minute
)
// Config configures a Shipper. Only BaseURL, IngestToken, and Service are
// normally set by a caller; everything else has a workable default.
type Config struct {
// BaseURL is LoggingServer's base URL, e.g. "http://loggingserver:8090".
// Required.
BaseURL string
// IngestToken is the shared INGEST_TOKEN bearer secret LoggingServer
// requires (see LoggingServer/README.md). Required.
IngestToken string
// Service is this process's service name as reported to LoggingServer,
// e.g. "playhouse" or "outdoorgames-server-go". Required.
Service string
// Module is the local tag included in the human-readable stdout/stderr
// line, mirroring internal/logging.New's module argument. Defaults to
// Service when empty.
Module string
// Level is the severity threshold, same values/aliases as the LOG env
// var (debug/info/warn/error/critical/silent). Defaults to "info".
Level string
// LogAll mirrors the LOG_ALL env var: when true, a verbose JSON context
// dump is also printed locally (never sent to LoggingServer differently
// than normal — see Debug/InfoCtx doc comments).
LogAll bool
// FlushInterval is how often buffered entries are sent to LoggingServer.
// Defaults to 2s.
FlushInterval time.Duration
// MaxBatchSize triggers an out-of-band flush as soon as the buffer
// reaches this many entries, instead of waiting for FlushInterval.
// Defaults to 100.
MaxBatchSize int
// BufferCapacity is the maximum number of not-yet-flushed entries held
// in memory. Once full, new entries are dropped (oldest-first callers
// are not blocked) rather than applying backpressure to the caller.
// Defaults to 2000.
BufferCapacity int
// HTTPClient overrides the client used to POST to LoggingServer.
// Defaults to a client with a 5s timeout.
HTTPClient *http.Client
}
// wireEntry mirrors LoggingServer's POST /api/logs request shape
// (LoggingServer/internal/httpapi.LogEntryInput) field-for-field.
type wireEntry struct {
Service string `json:"service"`
Level string `json:"level"`
Message string `json:"message"`
Context json.RawMessage `json:"context,omitempty"`
OccurredAt time.Time `json:"occurred_at"`
}
// Shipper batches log entries in memory and flushes them to LoggingServer on
// a background goroutine, while also behaving like a local
// internal/logging.Logger (same method surface, same stdout/stderr output).
// A Shipper is safe for concurrent use.
type Shipper struct {
module string
threshold Level
logAll bool
service string
url string
token string
client *http.Client
maxBatch int
bufCap int
mu sync.Mutex
buffer []wireEntry
flushSignal chan struct{}
closeOnce sync.Once
closeCh chan struct{}
doneCh chan struct{}
warnMu sync.Mutex
lastWarn time.Time
}
// New creates a Shipper. It starts a background flush goroutine immediately;
// call Close (or Flush, for a one-off synchronous flush) during shutdown to
// avoid losing buffered entries.
func New(cfg Config) *Shipper {
module := cfg.Module
if module == "" {
module = cfg.Service
}
flushInterval := cfg.FlushInterval
if flushInterval <= 0 {
flushInterval = defaultFlushInterval
}
maxBatch := cfg.MaxBatchSize
if maxBatch <= 0 {
maxBatch = defaultMaxBatchSize
}
bufCap := cfg.BufferCapacity
if bufCap <= 0 {
bufCap = defaultBufferCapacity
}
client := cfg.HTTPClient
if client == nil {
client = &http.Client{Timeout: defaultHTTPTimeout}
}
s := &Shipper{
module: module,
threshold: levelOf(cfg.Level),
logAll: cfg.LogAll,
service: cfg.Service,
url: strings.TrimRight(cfg.BaseURL, "/") + "/api/logs",
token: cfg.IngestToken,
client: client,
maxBatch: maxBatch,
bufCap: bufCap,
flushSignal: make(chan struct{}, 1),
closeCh: make(chan struct{}),
doneCh: make(chan struct{}),
}
go s.loop(flushInterval)
return s
}
func (s *Shipper) loop(flushInterval time.Duration) {
defer close(s.doneCh)
ticker := time.NewTicker(flushInterval)
defer ticker.Stop()
for {
select {
case <-ticker.C:
s.flush()
case <-s.flushSignal:
s.flush()
case <-s.closeCh:
s.flush() // final, best-effort flush of whatever is left
return
}
}
}
// requestFlush asks the background loop to flush soon, without blocking the
// caller: if a flush is already pending the request is simply dropped.
func (s *Shipper) requestFlush() {
select {
case s.flushSignal <- struct{}{}:
default:
}
}
// enqueue appends one entry to the buffer, dropping the incoming entry
// (rather than blocking the caller or evicting older entries) once the
// buffer is full. This is the sole non-blocking guarantee this package
// makes: a caller's Debug/Info/... call never waits on network I/O.
func (s *Shipper) enqueue(entry wireEntry) {
s.mu.Lock()
full := len(s.buffer) >= s.bufCap
if !full {
s.buffer = append(s.buffer, entry)
}
atCap := len(s.buffer) >= s.maxBatch
s.mu.Unlock()
if full {
s.warnOnce(fmt.Errorf("logshipper: buffer full (cap=%d), dropping log entries for service %q", s.bufCap, s.service))
return
}
if atCap {
s.requestFlush()
}
}
// flush sends every currently buffered entry to LoggingServer in one
// request. Failures are swallowed (beyond a rate-limited local warning) by
// design: a host application must never fail, panic, or slow down because
// its log sink is unreachable.
func (s *Shipper) flush() {
s.mu.Lock()
if len(s.buffer) == 0 {
s.mu.Unlock()
return
}
batch := s.buffer
s.buffer = nil
s.mu.Unlock()
body, err := json.Marshal(batch)
if err != nil {
s.warnOnce(fmt.Errorf("logshipper: marshal batch: %w", err))
return
}
ctx, cancel := context.WithTimeout(context.Background(), defaultHTTPTimeout)
defer cancel()
req, err := http.NewRequestWithContext(ctx, http.MethodPost, s.url, bytes.NewReader(body))
if err != nil {
s.warnOnce(fmt.Errorf("logshipper: build request: %w", err))
return
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Authorization", "Bearer "+s.token)
resp, err := s.client.Do(req)
if err != nil {
s.warnOnce(fmt.Errorf("logshipper: send %d entries to %s: %w", len(batch), s.url, err))
return
}
defer resp.Body.Close()
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
s.warnOnce(fmt.Errorf("logshipper: LoggingServer rejected %d entries: HTTP %d", len(batch), resp.StatusCode))
}
}
// warnOnce prints a local stderr warning at most once per minute, no matter
// how many sends fail in that window, so an unreachable LoggingServer cannot
// itself become a log-spam problem.
func (s *Shipper) warnOnce(err error) {
s.warnMu.Lock()
defer s.warnMu.Unlock()
if time.Since(s.lastWarn) < defaultWarnInterval {
return
}
s.lastWarn = time.Now()
fmt.Fprintf(os.Stderr, "[%s] [logshipper] %s\n", time.Now().Format("2006-01-02 15:04:05.000"), err.Error())
}
// Flush synchronously sends any currently buffered entries. It never blocks
// longer than the underlying HTTP client's timeout and never returns an
// error to the caller (failures are reported via the same rate-limited
// stderr warning as background flushes) — this mirrors the "never block or
// panic the host app" guarantee the background path makes.
func (s *Shipper) Flush() {
s.flush()
}
// Close stops the background flush goroutine after performing one final
// flush of any buffered entries, and waits for that flush to finish. Call it
// during graceful shutdown so the last few log lines before exit are not
// silently dropped.
func (s *Shipper) Close() error {
s.closeOnce.Do(func() { close(s.closeCh) })
<-s.doneCh
return nil
}
// ---- Logger-shaped methods -------------------------------------------------
//
// Everything below matches internal/logging.Logger's method surface
// (Debug/Info/Warn/Error/Critical/Audit/*Ctx) so a Shipper can act as a
// near drop-in replacement for a project's local logger.
func (s *Shipper) emit(sev Level, ctx map[string]any, args ...any) {
if sev < s.threshold {
return
}
now := time.Now()
msg := formatArgs(args)
upper, lower := sevName(sev)
line := fmt.Sprintf("[%s] [%s] [%s] [%s] %s",
now.Format("2006-01-02"), now.Format("15:04:05.000"), upper, s.module, msg)
switch sev {
case LevelError, LevelCritical, LevelWarn:
fmt.Fprintln(os.Stderr, line)
default:
fmt.Fprintln(os.Stdout, line)
}
if s.logAll && ctx != nil {
if b, err := json.Marshal(scrubIDs(ctx)); err == nil {
fmt.Fprintf(os.Stdout, "[%s] [%s] [DEBUG] [%s] [DETAILS] %s\n",
now.Format("2006-01-02"), now.Format("15:04:05.000"), s.module, string(b))
}
}
// Unlike the local-only verbose dump above (which scrubs IDs for
// readability), the context shipped to LoggingServer is sent unscrubbed:
// the whole point of centralizing logs is cross-service correlation by
// request/user/entity ID, so stripping IDs here would defeat that.
var rawCtx json.RawMessage
if ctx != nil {
if b, err := json.Marshal(ctx); err == nil {
rawCtx = b
}
}
s.enqueue(wireEntry{
Service: s.service,
Level: lower,
Message: msg,
Context: rawCtx,
OccurredAt: now,
})
}
func formatArgs(args []any) string {
parts := make([]string, 0, len(args))
for _, a := range args {
switch v := a.(type) {
case error:
parts = append(parts, v.Error())
case string:
parts = append(parts, v)
default:
if b, err := json.Marshal(v); err == nil {
parts = append(parts, string(b))
} else {
parts = append(parts, fmt.Sprintf("%v", v))
}
}
}
return strings.Join(parts, " ")
}
// scrubIDs drops raw identifier fields from the verbose local-only context
// dump, matching internal/logging.Logger's behavior.
func scrubIDs(ctx map[string]any) map[string]any {
out := make(map[string]any, len(ctx))
for k, v := range ctx {
lower := strings.ToLower(k)
if lower == "id" || strings.HasSuffix(lower, "id") || strings.HasSuffix(lower, "_id") {
continue
}
out[k] = v
}
return out
}
func (s *Shipper) Debug(args ...any) { s.emit(LevelDebug, nil, args...) }
func (s *Shipper) Info(args ...any) { s.emit(LevelInfo, nil, args...) }
func (s *Shipper) Warn(args ...any) { s.emit(LevelWarn, nil, args...) }
func (s *Shipper) Error(args ...any) { s.emit(LevelError, nil, args...) }
func (s *Shipper) Critical(args ...any) { s.emit(LevelCritical, nil, args...) }
// Audit logs a structured audit-trail event at info level, matching
// internal/logging.Logger.Audit.
func (s *Shipper) Audit(event string, details map[string]any) {
s.emit(LevelInfo, details, "audit:"+event, details)
}
func (s *Shipper) DebugCtx(ctx map[string]any, args ...any) { s.emit(LevelDebug, ctx, args...) }
func (s *Shipper) InfoCtx(ctx map[string]any, args ...any) { s.emit(LevelInfo, ctx, args...) }
func (s *Shipper) WarnCtx(ctx map[string]any, args ...any) { s.emit(LevelWarn, ctx, args...) }
func (s *Shipper) ErrorCtx(ctx map[string]any, args ...any) { s.emit(LevelError, ctx, args...) }
+23
View File
@@ -0,0 +1,23 @@
DATABASE_URL=postgresql://media:media@127.0.0.1:5432/mediadb
MEDIA_SERVICE=viewer
PORT=3000
WEB_ROOT=../WebUI/build
MEDIA_ROOTS=../media
INPUT_DIR=../input
UPLOAD_COPY_DIR=../copy
OUTPUT_DIR=../output
DOWNLOADS_DIR=../downloads
THUMBNAIL_DIR=../thumbnails
MODEL_CACHE_DIR=../models
WORKFLOWS_DIR=../MediaTools/public/workflows
FFMPEG_PATH=ffmpeg
FFPROBE_PATH=ffprobe
YT_DLP_PATH=yt-dlp
COMFYUI_URL=http://127.0.0.1:8188
ANALYZER_MODELS_URL=http://127.0.0.1:8801
CORS_ORIGIN=http://localhost:5173
SESSION_COOKIE=session
COOKIE_SECURE=false
AUTHGUARD_URL=
INTERNAL_SERVICE_SECRET=
MAX_UPLOAD_BYTES=50gb
+53
View File
@@ -0,0 +1,53 @@
# Shared media backend
The backend is one Go module, shared across every `MEDIA_SERVICE` instance in the workspace. Set `MEDIA_SERVICE` to `viewer`, `tools`, `analyzer`, `config`, `moderator`, `kiosk`, or `carriernode` to select the route set while keeping the same auth, database, migration, file-safety, and worker implementation.
From this directory:
```bash
go mod download
MEDIA_SERVICE=viewer \
DATABASE_URL=postgresql://media:media@localhost:5432/mediadb \
WEB_ROOT=../WebUI/build \
go run ./cmd/mediabackend
```
Important settings:
- `MEDIA_ROOTS` is a comma- or semicolon-separated list of media roots. CarrierNode also walks
every path saved under a `media`/`images`/`videos`/`audios`/`funscripts` mount in
ProjectConfigurator's Projects workspace (the `configured_mounts` setting) regardless of which
project's tab it was entered under - see `effectiveMediaRoots` in
`internal/server/admin_storage.go`. `MEDIA_ROOTS` is only needed for a root that isn't already
configured there.
- `INPUT_DIR`, `UPLOAD_COPY_DIR`, `THUMBNAIL_DIR`, `OUTPUT_DIR`, `DOWNLOADS_DIR`, and `MODEL_CACHE_DIR` control writable storage.
- `WORKFLOWS_DIR` points to the built-in ComfyUI workflow definitions.
- `FFMPEG_PATH`, `FFPROBE_PATH`, and `YT_DLP_PATH` select workflow executables.
- `COMFYUI_URL` configures the generator service.
- `CARRIERNODE_URL` is only the bootstrap fallback for CarrierNode's URL - once configured through
ProjectConfigurator it's read from the `carriernode_url` row in the `settings` table instead
(see `carrierNodeBaseURL` in `internal/server/carriernode_client.go`).
- `INTERNAL_SERVICE_SECRET` protects service-to-service mount and media-proxy APIs.
Run `go test ./...` before packaging. Each service repo's Dockerfile builds this module (via the
`engine/` submodule) and copies `webui` into the final image; no Node server runs at runtime.
### Configuration reference
| Variable | Default | Purpose |
| --- | --- | --- |
| `DATABASE_URL` | required | PostgreSQL connection string |
| `MEDIA_SERVICE` | `viewer` | Route/service selection |
| `PORT` | service-specific | HTTP port |
| `WEB_ROOT` | service web root | Built webui directory |
| `MEDIA_ROOTS` | `./media` | Comma/semicolon-separated media roots |
| `THUMBNAIL_DIR` | `./thumbnails` | Thumbnail storage |
| `INPUT_DIR` | `./input` | Workflow input storage |
| `UPLOAD_COPY_DIR` | `./copy` | Generator copy-upload storage |
| `OUTPUT_DIR` | `./output` | Generated and converted output |
| `DOWNLOADS_DIR` | `./downloads` | yt-dlp/download storage |
| `WORKFLOWS_DIR` | service-specific | ComfyUI workflow JSON files |
| `INTERNAL_SERVICE_SECRET` | empty | Shared-secret service authentication |
| `CORS_ORIGIN` | `http://localhost:5173` | Allowed browser origin |
See `.env.example` for the complete list.
+19
View File
@@ -0,0 +1,19 @@
# Shared media backend security notes
The backend rewrite consolidates the security boundary in `internal/`.
Implemented controls include:
- bcrypt passwords, PostgreSQL cookie sessions, TOTP verification, role checks, and disabled-user checks;
- explicit CORS and WebSocket origin validation, security headers, and bounded request bodies;
- additive PostgreSQL migrations with a startup advisory lock;
- traversal, absolute-path, drive-path, and symlink-escape protection for every configured media root;
- fixed ffmpeg argument construction and bounded workflow workers;
- HTTPS-only downloader URLs with credential, private-IP, link-local, metadata-host, and DNS-rebinding checks;
- internal-service secret checks for mount, download, reload, upload, and catalog mutation routes;
- non-root Docker images and no Node server runtime.
Before deployment, set a unique `INTERNAL_SERVICE_SECRET`, use a strong database password, configure
`CORS_ORIGIN` to the real frontend origin, and enable TLS so `COOKIE_SECURE` can remain enabled.
Review the canonical Go routes when adding a capability; do not reintroduce the removed JavaScript
server paths or Socket.IO transport.
+42
View File
@@ -0,0 +1,42 @@
package main
import (
"context"
"errors"
"flag"
"log"
"net/http"
"os"
"os/signal"
"syscall"
"repos.gfranz.ch/Gabriel20xx/shared/media-backend/internal/config"
"repos.gfranz.ch/Gabriel20xx/shared/media-backend/internal/database"
"repos.gfranz.ch/Gabriel20xx/shared/media-backend/internal/server"
)
func main() {
service := flag.String("service", "", "service route set to run")
flag.Parse()
if *service != "" {
_ = os.Setenv("MEDIA_SERVICE", *service)
}
cfg, err := config.Load()
if err != nil {
log.Fatalf("config: %v", err)
}
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
defer stop()
pool, err := database.Open(ctx, cfg.DatabaseURL)
if err != nil {
log.Fatalf("database: %v", err)
}
defer pool.Close()
if err := database.Migrate(ctx, pool); err != nil {
log.Fatalf("migrate: %v", err)
}
app := server.New(cfg, pool)
if err := app.Run(ctx); err != nil && !errors.Is(err, http.ErrServerClosed) {
log.Fatalf("server: %v", err)
}
}
+21
View File
@@ -0,0 +1,21 @@
module repos.gfranz.ch/Gabriel20xx/shared/media-backend
go 1.26.5
require (
github.com/coder/websocket v1.8.15
github.com/go-chi/chi/v5 v5.3.1
github.com/jackc/pgx/v5 v5.10.0
golang.org/x/crypto v0.54.0
repos.gfranz.ch/Gabriel20xx/shared/backend v0.1.1
)
replace repos.gfranz.ch/Gabriel20xx/shared/backend => ../backend
require (
github.com/jackc/pgpassfile v1.0.0 // indirect
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect
github.com/jackc/puddle/v2 v2.2.2 // indirect
golang.org/x/sync v0.22.0 // indirect
golang.org/x/text v0.40.0 // indirect
)
+32
View File
@@ -0,0 +1,32 @@
github.com/coder/websocket v1.8.15 h1:6B2JPeOGlpff2Uz6vOEH1Vzpi0iUz20A+lPVhPHtNUA=
github.com/coder/websocket v1.8.15/go.mod h1:NX3SzP+inril6yawo5CQXx8+fk145lPDC6pumgx0mVg=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/go-chi/chi/v5 v5.3.1 h1:3j4HZLGZQ3JpMCrPJF/Jl3mYJfWLKBfNJ6quurUGCf8=
github.com/go-chi/chi/v5 v5.3.1/go.mod h1:R+tYY2hNuVUUjxoPtqUdgBqevM9s9njzkTLutVsOCto=
github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsIM=
github.com/jackc/pgpassfile v1.0.0/go.mod h1:CEx0iS5ambNFdcRtxPj5JhEz+xB6uRky5eyVu/W2HEg=
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 h1:iCEnooe7UlwOQYpKFhBabPMi4aNAfoODPEFNiAnClxo=
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761/go.mod h1:5TJZWKEWniPve33vlWYSoGYefn3gLQRzjfDlhSJ9ZKM=
github.com/jackc/pgx/v5 v5.10.0 h1:VhSvgU2jSli8o3AqIEOTJr7rZwAEUVo4E4XhR94Zfr0=
github.com/jackc/pgx/v5 v5.10.0/go.mod h1:mal1tBGAFfLHvZzaYh77YS/eC6IX9OWbRV1QIIM0Jn4=
github.com/jackc/puddle/v2 v2.2.2 h1:PR8nw+E/1w0GLuRFSmiioY6UooMp6KJv0/61nB7icHo=
github.com/jackc/puddle/v2 v2.2.2/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=
github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=
golang.org/x/crypto v0.54.0 h1:YLIA59K4fiNzHzjnZt2tUJQjQtUWfWbeHBqKtk3eScw=
golang.org/x/crypto v0.54.0/go.mod h1:KWL8ny2AZdGR2cWmzeHrp2azQPGogOv+HeQaVEXC2dk=
golang.org/x/sync v0.22.0 h1:SZjpbeLmrCk4xhRSZFNZW5gFUeCeFgjekvI/+gfScek=
golang.org/x/sync v0.22.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0=
golang.org/x/text v0.40.0 h1:Ub2Z6/xjgF1WrYQz2nuITOEegKFtiIy+rieRJ5lHZKs=
golang.org/x/text v0.40.0/go.mod h1:hpnzDAfGV753zIKo+wk3u1bVKCGPbrnF7+7LBF/UHVY=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
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"
"repos.gfranz.ch/Gabriel20xx/shared/media-backend/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, "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, "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, "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, "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 ""
}
+28
View File
@@ -0,0 +1,28 @@
package auth
import "testing"
func TestNormalizeCredentials(t *testing.T) {
email, username, password, err := normalizeCredentials(" User@Example.com ", "user", "correct horse battery staple")
if err != nil {
t.Fatal(err)
}
if email != "user@example.com" || username != "user" || password == "" {
t.Fatalf("normalized credentials = %q, %q, %q", email, username, password)
}
}
func TestNormalizeCredentialsAllowsAdminEmailOnly(t *testing.T) {
if _, _, _, err := normalizeCredentials("admin@example.com", "", "correct horse battery staple"); err != nil {
t.Fatalf("empty optional username rejected: %v", err)
}
}
func TestNormalizeRole(t *testing.T) {
if normalizeRole("MODERATOR") != "moderator" {
t.Fatal("moderator role was not normalized")
}
if normalizeRole("unknown") != "user" {
t.Fatal("unknown role was not reduced to user")
}
}
+238
View File
@@ -0,0 +1,238 @@
package config
import (
"fmt"
"os"
"path/filepath"
"strconv"
"strings"
)
type Service string
const (
Viewer Service = "viewer"
Tools Service = "tools"
Analyzer Service = "analyzer"
ConfigService Service = "config"
Moderator Service = "moderator"
Kiosk Service = "kiosk"
CarrierNode Service = "carriernode"
)
type Config struct {
Port string
DatabaseURL string
Service Service
ServiceName string
WebRoot string
MediaRoots []string
InputRoot string
CopyRoot string
WorkflowsRoot string
ThumbnailRoot string
OutputRoot string
DownloadsRoot string
ModelsRoot string
AllowedOrigin string
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
YTDLP string
ComfyURL string
AnalyzerModelsURL string
CarrierNodeURL string
MaxUploadBytes int64
TLSCertFile string
TLSKeyFile string
}
func Load() (*Config, error) {
service := normalizeService(os.Getenv("MEDIA_SERVICE"))
if service == "" {
service = normalizeService(os.Getenv("SERVICE"))
}
if service == "" {
service = Viewer
}
name := serviceName(service)
port := envOr("PORT", defaultPort(service))
root := envOr("MEDIA_ROOT", envOr("MEDIA_PATH", "./media"))
roots := splitPaths(os.Getenv("MEDIA_ROOTS"))
if len(roots) == 0 {
roots = []string{root}
}
for i := range roots {
roots[i] = filepath.Clean(roots[i])
}
maxUpload, err := parseBytes(envOr("MAX_UPLOAD_BYTES", "53687091200"))
if err != nil {
return nil, fmt.Errorf("MAX_UPLOAD_BYTES: %w", err)
}
cfg := &Config{
Port: port,
DatabaseURL: strings.TrimSpace(os.Getenv("DATABASE_URL")),
Service: service,
ServiceName: name,
WebRoot: resolveWebRoot(service),
MediaRoots: roots,
InputRoot: filepath.Clean(envOr("INPUT_DIR", "./input")),
CopyRoot: filepath.Clean(envOr("UPLOAD_COPY_DIR", "./copy")),
WorkflowsRoot: filepath.Clean(envOr("WORKFLOWS_DIR", filepath.Join("..", "MediaTools", "public", "workflows"))),
ThumbnailRoot: filepath.Clean(envOr("THUMBNAIL_DIR", "./thumbnails")),
OutputRoot: filepath.Clean(envOr("OUTPUT_DIR", "./output")),
DownloadsRoot: filepath.Clean(envOr("DOWNLOADS_DIR", "./downloads")),
ModelsRoot: filepath.Clean(envOr("MODEL_CACHE_DIR", "./models")),
AllowedOrigin: envOr("CORS_ORIGIN", "http://localhost:5173"),
PublicURL: strings.TrimRight(strings.TrimSpace(os.Getenv("PUBLIC_URL")), "/"),
SessionCookie: envOr("SESSION_COOKIE", "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"),
YTDLP: envOr("YT_DLP_PATH", "yt-dlp"),
ComfyURL: strings.TrimRight(envOr("COMFYUI_URL", "http://127.0.0.1:8188"), "/"),
AnalyzerModelsURL: strings.TrimRight(envOr("ANALYZER_MODELS_URL", "http://127.0.0.1:8801"), "/"),
CarrierNodeURL: strings.TrimRight(envOr("CARRIERNODE_URL", "http://127.0.0.1:3003"), "/"),
MaxUploadBytes: maxUpload,
TLSCertFile: strings.TrimSpace(os.Getenv("TLS_CERT_FILE")),
TLSKeyFile: strings.TrimSpace(os.Getenv("TLS_KEY_FILE")),
}
if cfg.DatabaseURL == "" {
return nil, fmt.Errorf("DATABASE_URL is required")
}
if (cfg.TLSCertFile == "") != (cfg.TLSKeyFile == "") {
return nil, fmt.Errorf("TLS_CERT_FILE and TLS_KEY_FILE must be set together")
}
return cfg, nil
}
func normalizeService(value string) Service {
switch strings.ToLower(strings.TrimSpace(value)) {
case "viewer", "mediaviewer":
return Viewer
case "tools", "mediatools":
return Tools
case "analyzer", "mediaanalyzer":
return Analyzer
case "config", "mediaconfig", "projectconfigurator":
return ConfigService
case "moderator", "mediamoderator":
return Moderator
case "kiosk", "mediakiosk":
return Kiosk
case "carriernode":
return CarrierNode
default:
return ""
}
}
func serviceName(service Service) string {
switch service {
case Viewer:
return "MediaViewer"
case Tools:
return "MediaTools"
case Analyzer:
return "MediaAnalyzer"
case ConfigService:
return "ProjectConfigurator"
case Moderator:
return "MediaModerator"
case Kiosk:
return "MediaKiosk"
case CarrierNode:
return "CarrierNode"
default:
return "Shared Service"
}
}
func defaultPort(service Service) string {
switch service {
case ConfigService:
return "3005"
case Moderator:
return "8090"
case CarrierNode:
return "3003"
default:
return "3000"
}
}
func resolveWebRoot(_ Service) string {
if value := strings.TrimSpace(os.Getenv("WEB_ROOT")); value != "" {
return filepath.Clean(value)
}
return filepath.Join("..", "WebUI", "build")
}
func splitPaths(value string) []string {
parts := strings.FieldsFunc(value, func(r rune) bool { return r == ',' || r == ';' })
result := make([]string, 0, len(parts))
for _, part := range parts {
if trimmed := strings.TrimSpace(part); trimmed != "" {
result = append(result, trimmed)
}
}
return result
}
func parseBytes(value string) (int64, error) {
value = strings.TrimSpace(strings.ToLower(value))
if value == "" {
return 0, nil
}
multiplier := int64(1)
suffixes := []struct {
suffix string
factor int64
}{
{"gb", 1 << 30},
{"mb", 1 << 20},
{"kb", 1 << 10},
{"b", 1},
}
for _, s := range suffixes {
if strings.HasSuffix(value, s.suffix) {
value = strings.TrimSpace(strings.TrimSuffix(value, s.suffix))
multiplier = s.factor
break
}
}
n, err := strconv.ParseInt(value, 10, 64)
if err != nil || n < 0 {
return 0, fmt.Errorf("must be a non-negative byte count")
}
return n * multiplier, nil
}
func envOr(key, fallback string) string {
if value := strings.TrimSpace(os.Getenv(key)); value != "" {
return value
}
return fallback
}
func envBool(key string, fallback bool) bool {
value := strings.ToLower(strings.TrimSpace(os.Getenv(key)))
if value == "" {
return fallback
}
return value == "1" || value == "true" || value == "yes" || value == "on"
}
@@ -0,0 +1,43 @@
package config
import (
"testing"
)
func TestLoadDefaultsAndServiceSelection(t *testing.T) {
t.Setenv("DATABASE_URL", "postgres://media:media@localhost/mediadb")
t.Setenv("MEDIA_SERVICE", "MediaKiosk")
t.Setenv("SERVICE", "viewer")
t.Setenv("MEDIA_ROOTS", `./media;./other-media`)
t.Setenv("MAX_UPLOAD_BYTES", "2mb")
t.Setenv("WEB_ROOT", "./webui")
cfg, err := Load()
if err != nil {
t.Fatalf("Load() error = %v", err)
}
if cfg.Service != Kiosk {
t.Fatalf("service = %q, want %q", cfg.Service, Kiosk)
}
if len(cfg.MediaRoots) != 2 {
t.Fatalf("media roots = %#v, want two roots", cfg.MediaRoots)
}
if cfg.MaxUploadBytes != 2*1024*1024 {
t.Fatalf("max upload bytes = %d", cfg.MaxUploadBytes)
}
}
func TestLoadRequiresDatabase(t *testing.T) {
t.Setenv("DATABASE_URL", "")
if _, err := Load(); err == nil {
t.Fatal("Load() succeeded without DATABASE_URL")
}
}
func TestParseBytesRejectsInvalidValues(t *testing.T) {
for _, value := range []string{"-1", "nope", "1tb"} {
if _, err := parseBytes(value); err == nil {
t.Errorf("parseBytes(%q) succeeded", value)
}
}
}
@@ -0,0 +1,55 @@
package database
import (
"context"
"embed"
"fmt"
"time"
"github.com/jackc/pgx/v5/pgxpool"
)
//go:embed migrations/001_initial.sql
var migrations embed.FS
func Open(ctx context.Context, databaseURL string) (*pgxpool.Pool, error) {
cfg, err := pgxpool.ParseConfig(databaseURL)
if err != nil {
return nil, fmt.Errorf("parse database URL: %w", err)
}
cfg.MaxConns = 20
cfg.MinConns = 1
cfg.MaxConnLifetime = 30 * time.Minute
cfg.MaxConnIdleTime = 5 * time.Minute
pool, err := pgxpool.NewWithConfig(ctx, cfg)
if err != nil {
return nil, fmt.Errorf("open database: %w", err)
}
if err := pool.Ping(ctx); err != nil {
pool.Close()
return nil, fmt.Errorf("ping database: %w", err)
}
return pool, nil
}
func Migrate(ctx context.Context, pool *pgxpool.Pool) error {
data, err := migrations.ReadFile("migrations/001_initial.sql")
if err != nil {
return fmt.Errorf("read migration: %w", err)
}
lockCtx, cancel := context.WithTimeout(ctx, 5*time.Minute)
defer cancel()
conn, err := pool.Acquire(lockCtx)
if err != nil {
return fmt.Errorf("acquire migration connection: %w", err)
}
defer conn.Release()
if _, err := conn.Exec(lockCtx, `SELECT pg_advisory_lock(42424242)`); err != nil {
return fmt.Errorf("acquire migration lock: %w", err)
}
defer func() { _, _ = conn.Exec(context.Background(), `SELECT pg_advisory_unlock(42424242)`) }()
if _, err := conn.Exec(lockCtx, string(data)); err != nil {
return fmt.Errorf("run migration: %w", err)
}
return nil
}
@@ -0,0 +1,321 @@
CREATE EXTENSION IF NOT EXISTS pgcrypto;
CREATE EXTENSION IF NOT EXISTS pg_trgm;
CREATE TABLE IF NOT EXISTS users (
id BIGSERIAL PRIMARY KEY,
email TEXT NOT NULL UNIQUE,
username TEXT,
password_hash TEXT NOT NULL,
avatar_url TEXT,
bio TEXT,
role TEXT NOT NULL DEFAULT 'user',
permissions JSONB NOT NULL DEFAULT '{}'::jsonb,
disabled BOOLEAN NOT NULL DEFAULT FALSE,
totp_secret TEXT,
mfa_enabled BOOLEAN NOT NULL DEFAULT FALSE,
mfa_backup_codes JSONB,
password_reset_token TEXT,
password_reset_expires TIMESTAMPTZ,
last_login_at TIMESTAMPTZ,
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);
ALTER TABLE users ADD COLUMN IF NOT EXISTS username TEXT;
ALTER TABLE users ADD COLUMN IF NOT EXISTS role TEXT NOT NULL DEFAULT 'user';
UPDATE users SET role = 'superadmin'
WHERE id = (SELECT id FROM users ORDER BY created_at, id LIMIT 1)
AND NOT EXISTS (SELECT 1 FROM users WHERE role = 'superadmin');
ALTER TABLE users ADD COLUMN IF NOT EXISTS permissions JSONB NOT NULL DEFAULT '{}'::jsonb;
ALTER TABLE users ADD COLUMN IF NOT EXISTS disabled BOOLEAN NOT NULL DEFAULT FALSE;
ALTER TABLE users ADD COLUMN IF NOT EXISTS last_login_at TIMESTAMPTZ;
CREATE UNIQUE INDEX IF NOT EXISTS users_username_unique ON users (LOWER(username)) WHERE username IS NOT NULL;
CREATE INDEX IF NOT EXISTS users_email_idx ON users (LOWER(email));
CREATE TABLE IF NOT EXISTS go_sessions (
token_hash TEXT PRIMARY KEY,
user_id BIGINT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
expires_at TIMESTAMPTZ NOT NULL,
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);
CREATE INDEX IF NOT EXISTS go_sessions_expiry_idx ON go_sessions (expires_at);
CREATE TABLE IF NOT EXISTS media (
id BIGSERIAL PRIMARY KEY,
user_id BIGINT REFERENCES users(id) ON DELETE SET NULL,
media_key TEXT NOT NULL UNIQUE,
media_type TEXT NOT NULL DEFAULT 'unknown',
app TEXT,
source TEXT NOT NULL DEFAULT 'Filesystem',
title TEXT,
description TEXT,
category TEXT,
file_path TEXT,
original_filename TEXT,
active BOOLEAN NOT NULL DEFAULT TRUE,
metadata JSONB NOT NULL DEFAULT '{}'::jsonb,
width INT,
height INT,
duration_ms BIGINT,
size_bytes BIGINT,
is_vr BOOLEAN NOT NULL DEFAULT FALSE,
has_funscript BOOLEAN NOT NULL DEFAULT FALSE,
speed REAL,
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
modified_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);
ALTER TABLE media ADD COLUMN IF NOT EXISTS file_path TEXT;
ALTER TABLE media ADD COLUMN IF NOT EXISTS source TEXT NOT NULL DEFAULT 'Filesystem';
ALTER TABLE media ADD COLUMN IF NOT EXISTS title TEXT;
ALTER TABLE media ADD COLUMN IF NOT EXISTS description TEXT;
ALTER TABLE media ADD COLUMN IF NOT EXISTS category TEXT;
ALTER TABLE media ADD COLUMN IF NOT EXISTS original_filename TEXT;
ALTER TABLE media ADD COLUMN IF NOT EXISTS active BOOLEAN NOT NULL DEFAULT TRUE;
ALTER TABLE media ADD COLUMN IF NOT EXISTS metadata JSONB NOT NULL DEFAULT '{}'::jsonb;
ALTER TABLE media ADD COLUMN IF NOT EXISTS created_at TIMESTAMPTZ NOT NULL DEFAULT NOW();
ALTER TABLE media ADD COLUMN IF NOT EXISTS media_type TEXT NOT NULL DEFAULT 'unknown';
ALTER TABLE media ADD COLUMN IF NOT EXISTS width INT;
ALTER TABLE media ADD COLUMN IF NOT EXISTS height INT;
ALTER TABLE media ADD COLUMN IF NOT EXISTS duration_ms BIGINT;
ALTER TABLE media ADD COLUMN IF NOT EXISTS size_bytes BIGINT;
ALTER TABLE media ADD COLUMN IF NOT EXISTS is_vr BOOLEAN NOT NULL DEFAULT FALSE;
ALTER TABLE media ADD COLUMN IF NOT EXISTS has_funscript BOOLEAN NOT NULL DEFAULT FALSE;
ALTER TABLE media ADD COLUMN IF NOT EXISTS speed REAL;
ALTER TABLE media ADD COLUMN IF NOT EXISTS modified_at TIMESTAMPTZ NOT NULL DEFAULT NOW();
CREATE INDEX IF NOT EXISTS media_active_idx ON media (active);
CREATE INDEX IF NOT EXISTS media_file_path_idx ON media (file_path);
CREATE INDEX IF NOT EXISTS media_search_idx ON media USING GIN (to_tsvector('simple', COALESCE(title, '') || ' ' || COALESCE(original_filename, '') || ' ' || COALESCE(file_path, '')));
CREATE TABLE IF NOT EXISTS media_stats (
id BIGSERIAL PRIMARY KEY,
media_id BIGINT REFERENCES media(id) ON DELETE CASCADE,
media_key TEXT NOT NULL,
user_id BIGINT REFERENCES users(id) ON DELETE SET NULL,
stat_type TEXT NOT NULL,
app TEXT,
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);
ALTER TABLE media_stats ADD COLUMN IF NOT EXISTS media_id BIGINT;
ALTER TABLE media_stats ADD COLUMN IF NOT EXISTS media_key TEXT;
ALTER TABLE media_stats ADD COLUMN IF NOT EXISTS user_id BIGINT;
ALTER TABLE media_stats ADD COLUMN IF NOT EXISTS stat_type TEXT;
ALTER TABLE media_stats ADD COLUMN IF NOT EXISTS app TEXT;
ALTER TABLE media_stats ADD COLUMN IF NOT EXISTS created_at TIMESTAMPTZ NOT NULL DEFAULT NOW();
CREATE UNIQUE INDEX IF NOT EXISTS media_stats_like_unique ON media_stats (user_id, media_key) WHERE stat_type = 'like' AND user_id IS NOT NULL;
CREATE INDEX IF NOT EXISTS media_stats_key_idx ON media_stats (media_key, stat_type);
CREATE TABLE IF NOT EXISTS media_view_sessions (
id BIGSERIAL PRIMARY KEY,
media_id BIGINT REFERENCES media(id) ON DELETE CASCADE,
media_key TEXT NOT NULL,
user_id BIGINT REFERENCES users(id) ON DELETE SET NULL,
duration_ms BIGINT NOT NULL DEFAULT 0,
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);
CREATE TABLE IF NOT EXISTS media_metrics (
id BIGSERIAL PRIMARY KEY,
media_id BIGINT REFERENCES media(id) ON DELETE CASCADE,
media_key TEXT NOT NULL,
user_id BIGINT REFERENCES users(id) ON DELETE SET NULL,
elapsed_ms BIGINT NOT NULL DEFAULT 0,
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);
CREATE TABLE IF NOT EXISTS media_tags (
id BIGSERIAL PRIMARY KEY,
media_id BIGINT REFERENCES media(id) ON DELETE CASCADE,
media_key TEXT NOT NULL,
tag TEXT NOT NULL,
user_id BIGINT REFERENCES users(id) ON DELETE SET NULL,
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
UNIQUE (media_key, tag, user_id)
);
CREATE INDEX IF NOT EXISTS media_tags_tag_idx ON media_tags (LOWER(tag));
CREATE INDEX IF NOT EXISTS media_tags_media_idx ON media_tags (media_key);
CREATE TABLE IF NOT EXISTS media_tag_votes (
id BIGSERIAL PRIMARY KEY,
media_key TEXT NOT NULL,
tag TEXT NOT NULL,
user_id BIGINT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
vote SMALLINT NOT NULL CHECK (vote IN (-1, 1)),
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
UNIQUE (media_key, tag, user_id)
);
CREATE TABLE IF NOT EXISTS playlists (
id BIGSERIAL PRIMARY KEY,
user_id BIGINT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
name TEXT NOT NULL,
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
UNIQUE (user_id, name)
);
CREATE TABLE IF NOT EXISTS playlist_items (
id BIGSERIAL PRIMARY KEY,
playlist_id BIGINT NOT NULL REFERENCES playlists(id) ON DELETE CASCADE,
media_id BIGINT REFERENCES media(id) ON DELETE CASCADE,
media_key TEXT NOT NULL,
position INT,
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
UNIQUE (playlist_id, media_key)
);
CREATE TABLE IF NOT EXISTS settings (
key TEXT PRIMARY KEY,
value TEXT,
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);
INSERT INTO settings (key, value)
VALUES ('auth_required', 'true')
ON CONFLICT (key) DO NOTHING;
CREATE TABLE IF NOT EXISTS media_worker_jobs (
id BIGSERIAL PRIMARY KEY,
media_id BIGINT REFERENCES media(id) ON DELETE SET NULL,
media_key TEXT,
file_path TEXT NOT NULL,
file_name TEXT NOT NULL DEFAULT '',
media_type TEXT NOT NULL DEFAULT 'unknown',
status TEXT NOT NULL DEFAULT 'queued',
progress INT NOT NULL DEFAULT 0,
queued_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
started_at TIMESTAMPTZ,
finished_at TIMESTAMPTZ,
duration_ms INT,
error_message TEXT,
extracted_data JSONB,
file_size_bytes BIGINT,
scan_batch_id TEXT,
tags TEXT[],
title TEXT,
description TEXT,
has_funscript BOOLEAN NOT NULL DEFAULT FALSE,
is_vr BOOLEAN NOT NULL DEFAULT FALSE,
vr_fov INT,
vr_stereo TEXT,
data_outcome TEXT,
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);
CREATE INDEX IF NOT EXISTS media_worker_jobs_status_idx ON media_worker_jobs (status, queued_at DESC);
CREATE UNIQUE INDEX IF NOT EXISTS media_worker_jobs_file_path_unique ON media_worker_jobs (file_path);
CREATE TABLE IF NOT EXISTS generated_media (
id BIGSERIAL PRIMARY KEY,
media_id BIGINT REFERENCES media(id) ON DELETE SET NULL,
user_id BIGINT REFERENCES users(id) ON DELETE SET NULL,
workflow TEXT,
prompt TEXT,
parameters JSONB,
output_filename TEXT,
output_path TEXT,
elapsed_ms INT,
status TEXT NOT NULL DEFAULT 'completed',
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);
CREATE TABLE IF NOT EXISTS downloaded_media (
id BIGSERIAL PRIMARY KEY,
media_id BIGINT REFERENCES media(id) ON DELETE SET NULL,
user_id BIGINT REFERENCES users(id) ON DELETE SET NULL,
job_id BIGINT,
source_url TEXT NOT NULL,
tool TEXT,
file_path TEXT,
file_name TEXT,
file_size_bytes BIGINT,
status TEXT NOT NULL DEFAULT 'completed',
error_message TEXT,
started_at TIMESTAMPTZ,
finished_at TIMESTAMPTZ,
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);
CREATE TABLE IF NOT EXISTS workflow_jobs (
id TEXT PRIMARY KEY,
service TEXT NOT NULL,
tool TEXT NOT NULL,
status TEXT NOT NULL DEFAULT 'queued',
progress INT NOT NULL DEFAULT 0,
request JSONB NOT NULL DEFAULT '{}'::jsonb,
result JSONB NOT NULL DEFAULT '{}'::jsonb,
error_message TEXT,
user_id BIGINT REFERENCES users(id) ON DELETE SET NULL,
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
started_at TIMESTAMPTZ,
finished_at TIMESTAMPTZ
);
CREATE INDEX IF NOT EXISTS workflow_jobs_service_idx ON workflow_jobs (service, created_at DESC);
CREATE TABLE IF NOT EXISTS workflow_schedules (
id TEXT PRIMARY KEY,
service TEXT NOT NULL,
tool TEXT NOT NULL,
name TEXT NOT NULL,
interval_minutes INT NOT NULL DEFAULT 60,
enabled BOOLEAN NOT NULL DEFAULT TRUE,
settings JSONB NOT NULL DEFAULT '{}'::jsonb,
last_run_at TIMESTAMPTZ,
last_status TEXT,
next_run_at TIMESTAMPTZ,
user_id BIGINT REFERENCES users(id) ON DELETE CASCADE,
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);
CREATE TABLE IF NOT EXISTS thumbnails (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
media_id BIGINT REFERENCES media(id) ON DELETE SET NULL,
source_path TEXT UNIQUE,
width INT,
height INT,
file_size_bytes BIGINT,
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);
CREATE TABLE IF NOT EXISTS mount_paths (
project TEXT NOT NULL,
function_name TEXT NOT NULL,
path TEXT NOT NULL,
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
PRIMARY KEY (project, function_name)
);
-- Per-step status tracking for metadata extraction and thumbnail generation, independent of the
-- legacy `status`/`error_message` columns above (which track the overall discovery row).
ALTER TABLE media_worker_jobs ADD COLUMN IF NOT EXISTS metadata_status TEXT NOT NULL DEFAULT 'queued';
ALTER TABLE media_worker_jobs ADD COLUMN IF NOT EXISTS metadata_error TEXT;
ALTER TABLE media_worker_jobs ADD COLUMN IF NOT EXISTS thumbnail_status TEXT NOT NULL DEFAULT 'queued';
ALTER TABLE media_worker_jobs ADD COLUMN IF NOT EXISTS thumbnail_error TEXT;
CREATE INDEX IF NOT EXISTS media_worker_jobs_metadata_status_idx ON media_worker_jobs (media_type, metadata_status);
CREATE INDEX IF NOT EXISTS media_worker_jobs_thumbnail_status_idx ON media_worker_jobs (media_type, thumbnail_status);
-- One row per (file, AI task) since a single image can have up to six independently toggleable
-- AI tasks (tags/title/description/age/gender/nsfw), which doesn't fit the one-row-per-file shape
-- of media_worker_jobs.
CREATE TABLE IF NOT EXISTS media_analysis_tasks (
id BIGSERIAL PRIMARY KEY,
media_key TEXT NOT NULL,
media_type TEXT NOT NULL,
task TEXT NOT NULL,
model TEXT NOT NULL,
status TEXT NOT NULL DEFAULT 'queued',
result JSONB,
error_message TEXT,
started_at TIMESTAMPTZ,
finished_at TIMESTAMPTZ,
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
UNIQUE (media_key, task)
);
CREATE INDEX IF NOT EXISTS media_analysis_tasks_status_idx ON media_analysis_tasks (media_type, status);
-- AI-attributed tags are inserted with user_id NULL; a plain UNIQUE(media_key, tag, user_id)
-- constraint does not dedupe NULLs against each other, so a dedicated partial index is required
-- to make repeated analysis runs idempotent instead of piling up duplicate tag rows.
CREATE UNIQUE INDEX IF NOT EXISTS media_tags_ai_tag_unique ON media_tags (media_key, tag) WHERE user_id IS NULL;
-- Speeds up the MediaAnalyzer dashboard/pipelines/history/live-status queries: analyzerStats and
-- analyzerPipelineBreakdown group active media by type (and join it against thumbnails), and
-- analyzerHistory sorts media_worker_jobs by queued_at with no status filter, none of which the
-- existing media/media_worker_jobs indexes above actually cover.
CREATE INDEX IF NOT EXISTS media_active_type_idx ON media (active, media_type);
CREATE INDEX IF NOT EXISTS media_worker_jobs_queued_at_idx ON media_worker_jobs (queued_at DESC);
CREATE INDEX IF NOT EXISTS media_worker_jobs_media_type_status_idx ON media_worker_jobs (media_type, status);
CREATE INDEX IF NOT EXISTS media_worker_jobs_funscript_status_idx ON media_worker_jobs (status) WHERE has_funscript = TRUE;
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,710 @@
package server
import (
"bytes"
"context"
"encoding/json"
"fmt"
"image"
_ "image/gif"
_ "image/jpeg"
_ "image/png"
"io"
"log"
"net/http"
"os"
"os/exec"
"path/filepath"
"strings"
"time"
)
// analysisState tracks the currently-running AI analysis pass, mirroring thumbnailGenerationState.
type analysisState struct {
Running bool
State string
Total int
Completed int
Failed int
Current string
CurrentType string
StartedAt *time.Time
FinishedAt *time.Time
LastError string
}
// analyzerTasksByMediaType mirrors WebUI/src/lib/features/MediaTypePipeline.svelte's stagesForType -
// the set of AI tasks that exist for each media type.
var analyzerTasksByMediaType = map[string][]string{
"image": {"tags", "title", "description", "age", "gender", "nsfw"},
"video": {"tags"},
"audio": {"tags"},
"funscript": {},
}
func (s *Server) analyzerAnalyzeStatus(w http.ResponseWriter, r *http.Request) {
s.analysisMu.Lock()
state := s.analysis
s.analysisMu.Unlock()
writeJSON(w, http.StatusOK, map[string]any{
"ok": true,
"status": map[string]any{
"running": state.Running,
"state": firstNonEmpty(state.State, "idle"),
"total": state.Total,
"completed": state.Completed,
"failed": state.Failed,
"current": state.Current,
"startedAt": state.StartedAt,
"finishedAt": state.FinishedAt,
"lastError": state.LastError,
},
})
}
func (s *Server) analyzerAnalyzeStart(w http.ResponseWriter, r *http.Request) {
selected := parseMediaTypesPayload(r, false)
s.analysisMu.Lock()
if s.analysis.Running {
s.analysisMu.Unlock()
writeError(w, http.StatusConflict, "AI analysis is already running")
return
}
ctx, cancel := context.WithCancel(context.Background())
now := time.Now().UTC()
s.analysis = analysisState{Running: true, State: "running", StartedAt: &now}
s.analysisCancel = cancel
s.analysisMu.Unlock()
go s.runAiAnalysis(ctx, mediaTypesList(selected))
writeJSON(w, http.StatusAccepted, map[string]any{"ok": true, "state": "running"})
}
func (s *Server) analyzerAnalyzeStop(w http.ResponseWriter, r *http.Request) {
s.analysisMu.Lock()
cancel := s.analysisCancel
running := s.analysis.Running
s.analysisMu.Unlock()
if !running || cancel == nil {
writeJSON(w, http.StatusOK, map[string]any{"ok": true, "state": "idle"})
return
}
log.Printf("analyzer: AI analysis stop requested")
cancel()
writeJSON(w, http.StatusAccepted, map[string]any{"ok": true, "state": "stopping"})
}
// runAiAnalysis queues any AI task that isn't already completed under the currently-configured
// model, then works through everything queued. mediaTypeFilters scopes both stages to a subset of
// media types (empty means every type) - used both by the dashboard's media-type selector and by
// the per-media-type retry-errors action (which passes a single-element list) so a scoped run
// never kicks off a full-library pass.
func (s *Server) runAiAnalysis(ctx context.Context, mediaTypeFilters []string) {
if err := s.syncAnalysisTasks(ctx, mediaTypeFilters); err != nil && ctx.Err() == nil {
log.Printf("analyzer: AI analysis: failed to sync tasks: %v", err)
s.finishAnalysis(err)
return
}
s.processAnalysisTasks(ctx, mediaTypeFilters)
}
type modelStageConfig struct {
Primary string
Enabled bool
}
// parseModelStageConfig mirrors MediaTypePipeline.svelte's own leniency: older saves stored the
// model as a bare string rather than {primary, fallback, enabled}.
func parseModelStageConfig(raw json.RawMessage) modelStageConfig {
var asString string
if json.Unmarshal(raw, &asString) == nil {
if asString == "" || asString == "disabled" {
return modelStageConfig{}
}
return modelStageConfig{Primary: asString, Enabled: true}
}
var asObject struct {
Primary string `json:"primary"`
Enabled bool `json:"enabled"`
}
if json.Unmarshal(raw, &asObject) == nil {
return modelStageConfig{Primary: asObject.Primary, Enabled: asObject.Enabled}
}
return modelStageConfig{}
}
// enabledAnalysisTasks reads the analyzer_model_config setting (the same one the model-config
// endpoints already read/write) and returns, per media type, the task->model pairs the user has
// actually turned on.
func (s *Server) enabledAnalysisTasks(ctx context.Context, mediaTypeFilters []string) map[string]map[string]string {
value := s.settingValue(ctx, "analyzer_model_config", "{}")
var wrapper struct {
Config map[string]map[string]json.RawMessage `json:"config"`
}
if json.Unmarshal([]byte(value), &wrapper) != nil {
return nil
}
filterSet := make(map[string]bool, len(mediaTypeFilters))
for _, mediaType := range mediaTypeFilters {
filterSet[mediaType] = true
}
result := make(map[string]map[string]string)
for mediaType, tasks := range analyzerTasksByMediaType {
if len(filterSet) > 0 && !filterSet[mediaType] {
continue
}
section, ok := wrapper.Config[mediaType]
if !ok {
continue
}
enabled := make(map[string]string)
for _, task := range tasks {
raw, ok := section[task]
if !ok {
continue
}
stage := parseModelStageConfig(raw)
if stage.Enabled && stage.Primary != "" && stage.Primary != "disabled" {
enabled[task] = stage.Primary
}
}
if len(enabled) > 0 {
result[mediaType] = enabled
}
}
return result
}
// syncAnalysisTasks upserts one media_analysis_tasks row per (active media file, enabled task).
// A file whose task previously errored, or whose configured model has since changed, is put back
// on the queue - mirroring how thumbnails/metadata already retry automatically on every run
// rather than requiring the dedicated retry-errors action.
func (s *Server) syncAnalysisTasks(ctx context.Context, mediaTypeFilters []string) error {
tasksByType := s.enabledAnalysisTasks(ctx, mediaTypeFilters)
if len(tasksByType) == 0 {
return nil
}
query := `SELECT media_key, LOWER(COALESCE(media_type, '')) FROM media WHERE active = TRUE`
args := []any{}
if len(mediaTypeFilters) > 0 {
query += ` AND LOWER(COALESCE(media_type, '')) = ANY($1)`
args = append(args, mediaTypeFilters)
}
rows, err := s.db.Query(ctx, query, args...)
if err != nil {
return err
}
type mediaItem struct{ key, mediaType string }
items := make([]mediaItem, 0)
for rows.Next() {
var item mediaItem
if rows.Scan(&item.key, &item.mediaType) == nil {
items = append(items, item)
}
}
rows.Close()
if err := rows.Err(); err != nil {
return err
}
for _, item := range items {
tasks, ok := tasksByType[item.mediaType]
if !ok {
continue
}
for task, model := range tasks {
if ctx.Err() != nil {
return nil
}
_, _ = s.db.Exec(ctx, `
INSERT INTO media_analysis_tasks (media_key, media_type, task, model, status)
VALUES ($1,$2,$3,$4,'queued')
ON CONFLICT (media_key, task) DO UPDATE SET
model = EXCLUDED.model,
status = 'queued',
error_message = NULL,
updated_at = NOW()
WHERE media_analysis_tasks.status = 'error'
OR (media_analysis_tasks.status = 'completed' AND media_analysis_tasks.model <> EXCLUDED.model)`,
item.key, item.mediaType, task, model)
}
}
return nil
}
type pendingAnalysisTask struct {
id int64
mediaKey, mediaType string
task, model, filePath string
}
func (s *Server) processAnalysisTasks(ctx context.Context, mediaTypeFilters []string) {
query := `
SELECT t.id, t.media_key, t.media_type, t.task, t.model, COALESCE(NULLIF(m.file_path, ''), m.media_key)
FROM media_analysis_tasks t
JOIN media m ON m.media_key = t.media_key
WHERE t.status = 'queued' AND m.active = TRUE`
args := []any{}
if len(mediaTypeFilters) > 0 {
query += ` AND t.media_type = ANY($1)`
args = append(args, mediaTypeFilters)
}
query += ` ORDER BY t.id ASC`
rows, err := s.db.Query(ctx, query, args...)
if err != nil {
if ctx.Err() != nil {
s.finishAnalysis(nil)
} else {
log.Printf("analyzer: AI analysis: failed to load queued tasks: %v", err)
s.finishAnalysis(err)
}
return
}
items := make([]pendingAnalysisTask, 0)
for rows.Next() {
var item pendingAnalysisTask
if rows.Scan(&item.id, &item.mediaKey, &item.mediaType, &item.task, &item.model, &item.filePath) == nil {
items = append(items, item)
}
}
rows.Close()
log.Printf("analyzer: AI analysis started: %d tasks queued", len(items))
s.analysisMu.Lock()
s.analysis.Total = len(items)
s.analysisMu.Unlock()
for _, item := range items {
if ctx.Err() != nil {
s.finishAnalysis(nil)
return
}
s.analysisMu.Lock()
s.analysis.Current = item.filePath
s.analysis.CurrentType = item.mediaType
s.analysisMu.Unlock()
_, _ = s.db.Exec(ctx, `UPDATE media_analysis_tasks SET status='processing', started_at=NOW() WHERE id=$1`, item.id)
result, runErr := s.runAnalysisTask(ctx, item)
s.analysisMu.Lock()
if runErr != nil {
s.analysis.Failed++
s.analysis.LastError = runErr.Error()
} else {
s.analysis.Completed++
}
s.analysisMu.Unlock()
if runErr != nil {
_, _ = s.db.Exec(ctx, `UPDATE media_analysis_tasks SET status='error', error_message=$2, finished_at=NOW() WHERE id=$1`, item.id, runErr.Error())
continue
}
_, _ = s.db.Exec(ctx, `UPDATE media_analysis_tasks SET status='completed', error_message=NULL, result=$2, finished_at=NOW() WHERE id=$1`, item.id, mustJSON(result))
s.applyAnalysisResult(ctx, item.mediaKey, result)
}
s.finishAnalysis(nil)
}
func (s *Server) finishAnalysis(runErr error) {
now := time.Now().UTC()
s.analysisMu.Lock()
defer s.analysisMu.Unlock()
s.analysis.Running = false
s.analysisCancel = nil
s.analysis.Current = ""
s.analysis.CurrentType = ""
s.analysis.FinishedAt = &now
if runErr != nil {
s.analysis.State = "error"
s.analysis.LastError = runErr.Error()
} else if s.analysis.Completed+s.analysis.Failed < s.analysis.Total {
s.analysis.State = "stopped"
} else if s.analysis.Failed > 0 {
s.analysis.State = "completed_with_errors"
} else {
s.analysis.State = "completed"
s.analysis.LastError = ""
}
log.Printf("analyzer: AI analysis finished: %d/%d done, %d failed, state=%s", s.analysis.Completed, s.analysis.Total, s.analysis.Failed, s.analysis.State)
if s.analysis.LastError != "" {
log.Printf("analyzer: AI analysis last error: %s", s.analysis.LastError)
}
}
// runAnalysisTask dispatches one (file, task, model) unit of work. Every model produces a fixed
// output shape regardless of which task slot it was assigned to in the UI (the model dropdown
// isn't filtered per task), so storage in applyAnalysisResult is driven by what a model actually
// returns, not by the task key it ran under.
func (s *Server) runAnalysisTask(ctx context.Context, item pendingAnalysisTask) (map[string]any, error) {
sourcePath := filepath.ToSlash(item.filePath)
// Video frames come from an existing thumbnail when possible (see videoAnalysisFrame) rather
// than always fetching the whole video across the wire to CarrierNode just to grab one frame.
if item.mediaType == "video" && item.model != "laplacian" {
framePath, cleanup, err := s.videoAnalysisFrame(ctx, sourcePath)
if err != nil {
return nil, err
}
if cleanup != nil {
defer cleanup()
}
return s.callAnalyzerModelsService(ctx, item.mediaType, item.task, item.model, framePath)
}
scratchPath, cleanup, err := s.fetchCarrierNodeToScratch(ctx, "/media/"+urlPath(sourcePath), filepath.Ext(sourcePath))
if err != nil {
return nil, fmt.Errorf("fetch %s: %w", item.filePath, err)
}
defer cleanup()
if item.model == "laplacian" {
if item.mediaType != "image" {
return nil, fmt.Errorf("laplacian quality scoring only supports images")
}
variance, err := computeLaplacianVariance(scratchPath)
if err != nil {
return nil, err
}
return map[string]any{"quality": map[string]any{"laplacianVariance": variance}}, nil
}
return s.callAnalyzerModelsService(ctx, item.mediaType, item.task, item.model, scratchPath)
}
// videoAnalysisFrame reuses an already-generated thumbnail as the representative frame for
// image-shaped models when one exists, fetching the source video and extracting a temporary
// frame otherwise so AI analysis doesn't depend on the thumbnails stage being enabled. Both paths
// return a scratch file the AnalyzerModels sidecar (co-located in this container - see
// callAnalyzerModelsService) can read directly.
func (s *Server) videoAnalysisFrame(ctx context.Context, sourcePath string) (string, func(), error) {
var thumbnailID string
if err := s.db.QueryRow(ctx, `SELECT id FROM thumbnails WHERE source_path = $1`, sourcePath).Scan(&thumbnailID); err == nil {
if scratchPath, cleanup, fetchErr := s.fetchCarrierNodeToScratch(ctx, "/thumbnails/"+thumbnailID+".jpg", ".jpg"); fetchErr == nil {
return scratchPath, cleanup, nil
}
}
videoScratch, cleanupVideo, err := s.fetchCarrierNodeToScratch(ctx, "/media/"+urlPath(sourcePath), filepath.Ext(sourcePath))
if err != nil {
return "", nil, fmt.Errorf("fetch %s: %w", sourcePath, err)
}
defer cleanupVideo()
temporary, err := os.CreateTemp("", "analysis-frame-*.jpg")
if err != nil {
return "", nil, fmt.Errorf("create temporary frame: %w", err)
}
temporaryPath := temporary.Name()
if err := temporary.Close(); err != nil {
_ = os.Remove(temporaryPath)
return "", nil, err
}
frameCtx, cancel := context.WithTimeout(ctx, 2*time.Minute)
defer cancel()
args := []string{"-hide_banner", "-loglevel", "error", "-y", "-ss", "0", "-i", videoScratch, "-vf", "scale=320:-2:force_original_aspect_ratio=decrease", "-frames:v", "1", "-q:v", "3", temporaryPath}
command := exec.CommandContext(frameCtx, s.cfg.FFmpeg, args...)
var stderr bytes.Buffer
command.Stderr = &stderr
if err := command.Run(); err != nil {
_ = os.Remove(temporaryPath)
detail := strings.TrimSpace(stderr.String())
if len(detail) > 300 {
detail = detail[len(detail)-300:]
}
if detail != "" {
return "", nil, fmt.Errorf("ffmpeg: %s", detail)
}
return "", nil, err
}
return temporaryPath, func() { _ = os.Remove(temporaryPath) }, nil
}
type analysisSidecarRequest struct {
Task string `json:"task"`
Model string `json:"model"`
Path string `json:"path"`
}
// callAnalyzerModelsService calls the AnalyzerModels sidecar (a separate process in the same
// container, not baked into this binary - see ANALYZER_MODELS_URL and MediaAnalyzer/Dockerfile),
// the same way executeGeneration already calls out to ComfyUI for image generation. Video frames
// are analyzed through the image endpoint since by the time this runs the video has already been
// reduced to a still frame.
func (s *Server) callAnalyzerModelsService(ctx context.Context, mediaType, task, model, path string) (map[string]any, error) {
endpoint, ok := map[string]string{"image": "/analyze/image", "video": "/analyze/image", "audio": "/analyze/audio"}[mediaType]
if !ok {
return nil, fmt.Errorf("unsupported media type for AI analysis: %s", mediaType)
}
body, err := json.Marshal(analysisSidecarRequest{Task: task, Model: model, Path: path})
if err != nil {
return nil, err
}
// Some models (florence2 especially) run several seconds per file on CPU - generous timeout
// so a slow model doesn't get mistaken for a hung one.
requestCtx, cancel := context.WithTimeout(ctx, 5*time.Minute)
defer cancel()
request, err := http.NewRequestWithContext(requestCtx, http.MethodPost, s.cfg.AnalyzerModelsURL+endpoint, bytes.NewReader(body))
if err != nil {
return nil, err
}
request.Header.Set("Content-Type", "application/json")
response, err := http.DefaultClient.Do(request)
if err != nil {
return nil, fmt.Errorf("analyzer models service request failed: %w", err)
}
defer response.Body.Close()
var payload struct {
Result map[string]any `json:"result"`
// FastAPI's HTTPException serializes as {"detail": "..."} , not {"error": "..."}.
Detail string `json:"detail"`
}
if err := json.NewDecoder(io.LimitReader(response.Body, 1<<20)).Decode(&payload); err != nil {
return nil, fmt.Errorf("invalid analyzer models response: %w", err)
}
if response.StatusCode >= 300 {
if payload.Detail == "" {
payload.Detail = response.Status
}
return nil, fmt.Errorf("analyzer models service: %s", payload.Detail)
}
return payload.Result, nil
}
// applyAnalysisResult writes a completed task's output into the tables the rest of the app
// actually reads, not just the analyzer's own history - tags into media_tags (user_id NULL marks
// them as AI-attributed), title/description onto media (never overwriting a value that's already
// set, whether user-edited or from an earlier analysis run), everything else into media.metadata.
func (s *Server) applyAnalysisResult(ctx context.Context, mediaKey string, result map[string]any) {
if result == nil {
return
}
if tagsRaw, ok := result["tags"].([]any); ok {
for _, tagValue := range tagsRaw {
tag, ok := tagValue.(string)
tag = strings.ToLower(strings.TrimSpace(tag))
if !ok || tag == "" {
continue
}
_, _ = s.db.Exec(ctx, `
INSERT INTO media_tags (media_key, tag, user_id) VALUES ($1, $2, NULL)
ON CONFLICT (media_key, tag) WHERE user_id IS NULL DO NOTHING`, mediaKey, tag)
}
}
title, _ := result["title"].(string)
description, _ := result["description"].(string)
if strings.TrimSpace(title) != "" || strings.TrimSpace(description) != "" {
_, _ = s.db.Exec(ctx, `
UPDATE media SET
title = COALESCE(NULLIF(media.title, ''), NULLIF($2, '')),
description = COALESCE(NULLIF(media.description, ''), NULLIF($3, ''))
WHERE media_key = $1`, mediaKey, title, description)
}
extra := map[string]any{}
for _, key := range []string{"age", "gender", "nsfwLabel", "nsfwScore", "quality"} {
if value, ok := result[key]; ok {
extra[key] = value
}
}
if len(extra) > 0 {
_, _ = s.db.Exec(ctx, `UPDATE media SET metadata = metadata || $2::jsonb WHERE media_key = $1`, mediaKey, mustJSON(extra))
}
}
// computeLaplacianVariance measures image sharpness/blur without any external model: convert to
// grayscale, convolve with the standard 4-neighbor Laplacian kernel, and take the variance of the
// result - a low variance means a flat/blurry image, a high variance means a lot of sharp edges.
// Only the image formats Go's standard library can decode (JPEG/PNG/GIF) are supported; anything
// else surfaces as a normal per-file error rather than silently skipping.
func computeLaplacianVariance(fullPath string) (float64, error) {
file, err := os.Open(fullPath)
if err != nil {
return 0, err
}
defer file.Close()
img, _, err := image.Decode(file)
if err != nil {
return 0, fmt.Errorf("decode image: %w", err)
}
bounds := img.Bounds()
width, height := bounds.Dx(), bounds.Dy()
if width < 3 || height < 3 {
return 0, fmt.Errorf("image too small for quality analysis")
}
gray := make([]float64, width*height)
for y := 0; y < height; y++ {
for x := 0; x < width; x++ {
r, g, b, _ := img.At(bounds.Min.X+x, bounds.Min.Y+y).RGBA()
gray[y*width+x] = 0.299*float64(r>>8) + 0.587*float64(g>>8) + 0.114*float64(b>>8)
}
}
at := func(x, y int) float64 {
if x < 0 {
x = 0
} else if x >= width {
x = width - 1
}
if y < 0 {
y = 0
} else if y >= height {
y = height - 1
}
return gray[y*width+x]
}
var sum, sumSquares float64
count := float64(width * height)
for y := 0; y < height; y++ {
for x := 0; x < width; x++ {
laplacian := at(x-1, y) + at(x+1, y) + at(x, y-1) + at(x, y+1) - 4*at(x, y)
sum += laplacian
sumSquares += laplacian * laplacian
}
}
mean := sum / count
return sumSquares/count - mean*mean, nil
}
// retryPipelineErrors resets one media type's failed items for one stage back onto the queue and
// immediately re-runs that stage for just that type, rather than requiring a full "Run pipeline".
func (s *Server) retryPipelineErrors(w http.ResponseWriter, r *http.Request, mediaType, stage string) {
ctx := r.Context()
log.Printf("analyzer: retry errors requested (mediaType=%s, stage=%s)", mediaType, stage)
switch stage {
case "metadata":
go s.retryMetadataErrors(mediaType)
case "thumbnails":
go s.retryThumbnailErrors(mediaType)
case "analyze":
go s.runAiAnalysis(context.Background(), []string{mediaType})
default:
writeError(w, http.StatusBadRequest, "unknown pipeline stage")
return
}
_ = ctx
writeJSON(w, http.StatusAccepted, map[string]any{"ok": true, "mediaType": mediaType, "stage": stage, "started": true})
}
// mediaTypeErrorCondition returns a media_worker_jobs WHERE fragment for one media type, and the
// single arg it needs (if any) - the same "funscript" special-case analyzerHistory and
// parseMediaTypesPayload use, since it isn't a real media_type value on that table, just the
// has_funscript flag on a video/audio row.
func mediaTypeErrorCondition(mediaType string) (string, []any) {
if mediaType == "funscript" {
return "has_funscript = TRUE", nil
}
return "LOWER(COALESCE(media_type, '')) = $1", []any{mediaType}
}
type pipelineStageError struct {
FilePath string `json:"filePath"`
Error string `json:"error"`
}
// pipelineStageErrors returns the most recent error messages recorded for one media type's one
// pipeline stage, so the "Show errors" button next to Retry (see PipelineFlowDiagram.svelte) can
// display what's actually failing instead of just the count already shown in the breakdown.
func (s *Server) pipelineStageErrors(w http.ResponseWriter, r *http.Request, mediaType, stage string) {
ctx := r.Context()
limit := optionalInt(r.URL.Query().Get("limit"), 20, 1, 100)
items := make([]pipelineStageError, 0)
var query string
var args []any
switch stage {
case "metadata":
condition, condArgs := mediaTypeErrorCondition(mediaType)
query = fmt.Sprintf(`SELECT file_path, COALESCE(metadata_error, '') FROM media_worker_jobs
WHERE metadata_status = 'error' AND %s ORDER BY finished_at DESC NULLS LAST LIMIT $%d`, condition, len(condArgs)+1)
args = append(condArgs, limit)
case "thumbnails":
condition, condArgs := mediaTypeErrorCondition(mediaType)
query = fmt.Sprintf(`SELECT file_path, COALESCE(thumbnail_error, '') FROM media_worker_jobs
WHERE thumbnail_status = 'error' AND %s ORDER BY finished_at DESC NULLS LAST LIMIT $%d`, condition, len(condArgs)+1)
args = append(condArgs, limit)
case "analyze":
query = `SELECT media_key, COALESCE(error_message, '') FROM media_analysis_tasks
WHERE status = 'error' AND LOWER(media_type) = $1 ORDER BY finished_at DESC NULLS LAST LIMIT $2`
args = []any{mediaType, limit}
default:
writeError(w, http.StatusBadRequest, "unknown pipeline stage")
return
}
rows, err := s.db.Query(ctx, query, args...)
if err != nil {
writeError(w, http.StatusInternalServerError, "pipeline errors unavailable")
return
}
defer rows.Close()
for rows.Next() {
var item pipelineStageError
if rows.Scan(&item.FilePath, &item.Error) == nil && item.Error != "" {
items = append(items, item)
}
}
writeJSON(w, http.StatusOK, map[string]any{"ok": true, "mediaType": mediaType, "stage": stage, "errors": items})
}
func (s *Server) retryMetadataErrors(mediaType string) {
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Minute)
defer cancel()
rows, err := s.db.Query(ctx, `
SELECT file_path FROM media_worker_jobs
WHERE LOWER(COALESCE(media_type, '')) = $1 AND metadata_status = 'error'`, mediaType)
if err != nil {
return
}
filePaths := make([]string, 0)
for rows.Next() {
var filePath string
if rows.Scan(&filePath) == nil {
filePaths = append(filePaths, filePath)
}
}
rows.Close()
for _, filePath := range filePaths {
if ctx.Err() != nil {
return
}
if probe, probeErr := s.carrierNodeProbe(ctx, filepath.ToSlash(filePath)); probeErr != nil {
_, _ = s.db.Exec(ctx, `UPDATE media_worker_jobs SET metadata_status='error', metadata_error=$2 WHERE file_path=$1`, filePath, probeErr.Error())
} else {
duration := nullableInt64(probe.DurationMs)
width, height := probe.Width, probe.Height
_, _ = s.db.Exec(ctx, `UPDATE media SET duration_ms = COALESCE($2, duration_ms), width = COALESCE($3, width), height = COALESCE($4, height) WHERE file_path = $1`, filePath, duration, nullableInt(width), nullableInt(height))
_, _ = s.db.Exec(ctx, `UPDATE media_worker_jobs SET metadata_status='completed', metadata_error=NULL WHERE file_path=$1`, filePath)
}
}
}
func (s *Server) retryThumbnailErrors(mediaType string) {
s.thumbnailMu.Lock()
if s.thumbnail.Running {
s.thumbnailMu.Unlock()
return
}
ctx, cancel := context.WithCancel(context.Background())
now := time.Now().UTC()
s.thumbnail = thumbnailGenerationState{Running: true, State: "running", StartedAt: &now}
s.thumbnailCancel = cancel
s.thumbnailMu.Unlock()
candidates, err := s.thumbnailCandidatesWithErrors(ctx, mediaType)
if err != nil {
s.finishThumbnailGeneration(err)
return
}
s.runThumbnailCandidates(ctx, candidates)
}
@@ -0,0 +1,139 @@
package server
import (
"context"
"encoding/json"
"fmt"
"log"
"time"
)
// runAnalyzerScheduler polls due, enabled workflow_schedules for this service and runs them. It's
// deliberately a simple poll loop rather than a precise cron: schedules only ever run on
// minute-scale intervals, so "checked every 30s, run when due" is accurate enough and far simpler
// than tracking individual timers per schedule.
func (s *Server) runAnalyzerScheduler(ctx context.Context) {
ticker := time.NewTicker(30 * time.Second)
defer ticker.Stop()
for {
select {
case <-ctx.Done():
return
case <-ticker.C:
s.runDueAnalyzerSchedules(ctx)
}
}
}
func (s *Server) runDueAnalyzerSchedules(ctx context.Context) {
rows, err := s.db.Query(ctx, `
SELECT id, tool, settings
FROM workflow_schedules
WHERE service = $1 AND enabled = TRUE AND (next_run_at IS NULL OR next_run_at <= NOW())`, s.cfg.ServiceName)
if err != nil {
log.Printf("analyzer: schedule poll: failed to load due schedules: %v", err)
return
}
type due struct {
id, tool string
settings []byte
}
items := make([]due, 0)
for rows.Next() {
var item due
if rows.Scan(&item.id, &item.tool, &item.settings) == nil {
items = append(items, item)
}
}
rows.Close()
for _, item := range items {
if ctx.Err() != nil {
return
}
var parsed struct {
Types []string `json:"types"`
}
_ = json.Unmarshal(item.settings, &parsed)
types := normalizeMediaTypes(parsed.Types, true)
status := "started"
started, err := s.startAnalyzerScheduledRun(item.tool, types)
switch {
case err != nil:
status = "error: " + err.Error()
case !started:
status = "skipped: busy"
}
log.Printf("analyzer: automation schedule %s fired (tool=%s): %s", item.id, item.tool, status)
// Always advance next_run_at, even on skip/error, so a busy or misconfigured schedule
// doesn't get retried on every single tick - it just waits for its normal interval instead.
_, _ = s.db.Exec(ctx, `
UPDATE workflow_schedules
SET last_run_at = NOW(), last_status = $2, next_run_at = NOW() + make_interval(mins => interval_minutes), updated_at = NOW()
WHERE id = $1`, item.id, status)
}
}
// startAnalyzerScheduledRun dispatches one schedule's action exactly the way its corresponding
// manual-trigger HTTP handler does: guard the relevant busy-state slot, then hand off to the same
// background worker function used everywhere else. "started" is false (not an error) when that
// slot was already busy - the schedule just waits for its next tick rather than queuing up or
// failing loudly, mirroring how the dashboard's own buttons behave under the same condition.
func (s *Server) startAnalyzerScheduledRun(tool string, types map[string]bool) (bool, error) {
now := time.Now().UTC()
switch tool {
case "discover":
s.scanMu.Lock()
if s.scan.Running {
s.scanMu.Unlock()
return false, nil
}
s.scan = scanState{Running: true, Mode: "discover", StartedAt: &now}
s.scanMu.Unlock()
go s.scanMediaFiles(types)
case "metadata":
s.scanMu.Lock()
if s.scan.Running {
s.scanMu.Unlock()
return false, nil
}
s.scan = scanState{Running: true, Mode: "metadata", StartedAt: &now}
s.scanMu.Unlock()
go s.refreshMetadataForTypes(types)
case "cleanup":
s.scanMu.Lock()
if s.scan.Running {
s.scanMu.Unlock()
return false, nil
}
s.scan = scanState{Running: true, Mode: "cleanup", StartedAt: &now}
s.scanMu.Unlock()
go s.cleanupStaleMedia()
case "thumbnails":
s.thumbnailMu.Lock()
if s.thumbnail.Running {
s.thumbnailMu.Unlock()
return false, nil
}
runCtx, cancel := context.WithCancel(context.Background())
s.thumbnail = thumbnailGenerationState{Running: true, State: "running", StartedAt: &now}
s.thumbnailCancel = cancel
s.thumbnailMu.Unlock()
go s.generateThumbnails(runCtx, types)
case "analyze":
s.analysisMu.Lock()
if s.analysis.Running {
s.analysisMu.Unlock()
return false, nil
}
runCtx, cancel := context.WithCancel(context.Background())
s.analysis = analysisState{Running: true, State: "running", StartedAt: &now}
s.analysisCancel = cancel
s.analysisMu.Unlock()
go s.runAiAnalysis(runCtx, mediaTypesList(types))
default:
return false, fmt.Errorf("unsupported schedule action: %s", tool)
}
return true, nil
}
@@ -0,0 +1,331 @@
package server
// CarrierNode client: every non-CarrierNode service serves and stores media by calling CarrierNode's
// HTTP API through the helpers in this file instead of touching MediaRoots/ThumbnailRoot/
// OutputRoot/DownloadsRoot/InputRoot/CopyRoot locally. CarrierNode's own handlers keep using those
// roots directly (see media.go, admin_storage.go) - this file is never called from CarrierNode's
// own code path.
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"net/url"
"os"
"strconv"
"strings"
"time"
)
// carrierNodeHTTPClient has no blanket timeout since it streams large media files; callers bound
// individual calls with a context deadline instead.
var carrierNodeHTTPClient = &http.Client{}
func (s *Server) carrierNodeClient() *http.Client {
return carrierNodeHTTPClient
}
// carrierNodeBaseURL is configured in ProjectConfigurator and stored in the settings table (key
// "carriernode_url", the same "{projectKey}_url" convention ConfigWorkspace.svelte uses for
// every project's connection URL) - not a static env var, so a change in ProjectConfigurator
// takes effect on every service's very next request without a restart. CARRIERNODE_URL is only the
// bootstrap fallback before that setting has ever been saved.
func (s *Server) carrierNodeBaseURL(ctx context.Context) string {
return strings.TrimRight(s.settingValue(ctx, "carriernode_url", s.cfg.CarrierNodeURL), "/")
}
func (s *Server) newCarrierNodeRequest(ctx context.Context, method, path string, body io.Reader) (*http.Request, error) {
request, err := http.NewRequestWithContext(ctx, method, s.carrierNodeBaseURL(ctx)+path, body)
if err != nil {
return nil, err
}
if s.cfg.InternalServiceSecret != "" {
request.Header.Set("X-Internal-Auth", s.cfg.InternalServiceSecret)
}
return request, nil
}
var carrierNodeForwardRequestHeaders = []string{"Range", "If-Modified-Since", "If-None-Match", "If-Range"}
var carrierNodeForwardResponseHeaders = []string{"Content-Type", "Content-Length", "Content-Range", "Accept-Ranges", "Last-Modified", "ETag", "Content-Disposition"}
// proxyCarrierNode streams a CarrierNode response straight through to the original client, preserving
// range/conditional-request semantics so video scrubbing keeps working without reimplementing
// http.ServeContent on this side.
func (s *Server) proxyCarrierNode(w http.ResponseWriter, r *http.Request, carrierNodePath string) {
request, err := s.newCarrierNodeRequest(r.Context(), r.Method, carrierNodePath, nil)
if err != nil {
writeError(w, http.StatusBadGateway, "media service unavailable")
return
}
for _, header := range carrierNodeForwardRequestHeaders {
if value := r.Header.Get(header); value != "" {
request.Header.Set(header, value)
}
}
response, err := s.carrierNodeClient().Do(request)
if err != nil {
writeError(w, http.StatusBadGateway, "media service unavailable")
return
}
defer response.Body.Close()
for _, header := range carrierNodeForwardResponseHeaders {
if value := response.Header.Get(header); value != "" {
w.Header().Set(header, value)
}
}
w.WriteHeader(response.StatusCode)
if r.Method != http.MethodHead {
_, _ = io.Copy(w, response.Body)
}
}
// probeCarrierNode checks whether a CarrierNode-served path exists without fetching its bytes.
// A 404 is reported as exists=false with a nil error, not a failure - only transport/5xx
// problems are surfaced as errors.
func (s *Server) probeCarrierNode(ctx context.Context, carrierNodePath string) (bool, int64, time.Time, error) {
request, err := s.newCarrierNodeRequest(ctx, http.MethodHead, carrierNodePath, nil)
if err != nil {
return false, 0, time.Time{}, err
}
response, err := s.carrierNodeClient().Do(request)
if err != nil {
return false, 0, time.Time{}, err
}
defer response.Body.Close()
if response.StatusCode == http.StatusNotFound {
return false, 0, time.Time{}, nil
}
if response.StatusCode >= 400 {
return false, 0, time.Time{}, fmt.Errorf("carriernode probe failed: %s", response.Status)
}
size, _ := strconv.ParseInt(response.Header.Get("Content-Length"), 10, 64)
modTime, _ := http.ParseTime(response.Header.Get("Last-Modified"))
return true, size, modTime, nil
}
// fetchCarrierNodeToScratch downloads a CarrierNode-served path into an ephemeral temp file for local
// processing (ffmpeg/ffprobe/yt-dlp all need a real file handle). Callers must invoke the
// returned cleanup once done; it removes the scratch file unconditionally.
func (s *Server) fetchCarrierNodeToScratch(ctx context.Context, carrierNodePath, suffix string) (string, func(), error) {
request, err := s.newCarrierNodeRequest(ctx, http.MethodGet, carrierNodePath, nil)
if err != nil {
return "", nil, err
}
response, err := s.carrierNodeClient().Do(request)
if err != nil {
return "", nil, err
}
defer response.Body.Close()
if response.StatusCode != http.StatusOK {
return "", nil, fmt.Errorf("carriernode fetch failed: %s", response.Status)
}
scratch, err := os.CreateTemp("", "carriernode-src-*"+suffix)
if err != nil {
return "", nil, err
}
cleanup := func() { _ = os.Remove(scratch.Name()) }
if _, err := io.Copy(scratch, response.Body); err != nil {
scratch.Close()
cleanup()
return "", nil, err
}
if err := scratch.Close(); err != nil {
cleanup()
return "", nil, err
}
return scratch.Name(), cleanup, nil
}
// pushToCarrierNode streams a local file as the request body without buffering it in memory.
func (s *Server) pushToCarrierNode(ctx context.Context, method, carrierNodePath, localPath string) (*http.Response, error) {
file, err := os.Open(localPath)
if err != nil {
return nil, err
}
defer file.Close()
request, err := s.newCarrierNodeRequest(ctx, method, carrierNodePath, file)
if err != nil {
return nil, err
}
if info, statErr := file.Stat(); statErr == nil {
request.ContentLength = info.Size()
}
response, err := s.carrierNodeClient().Do(request)
if err != nil {
return nil, err
}
if response.StatusCode >= 400 {
body, _ := io.ReadAll(io.LimitReader(response.Body, 4096))
response.Body.Close()
return nil, fmt.Errorf("carriernode push failed: %s: %s", response.Status, string(body))
}
return response, nil
}
func carrierNodePushedSize(response *http.Response) int64 {
defer response.Body.Close()
var payload struct {
Size int64 `json:"size"`
}
_ = json.NewDecoder(response.Body).Decode(&payload)
return payload.Size
}
func (s *Server) carrierNodePushThumbnail(ctx context.Context, id, localPath string) (int64, error) {
response, err := s.pushToCarrierNode(ctx, http.MethodPost, "/api/thumbnails/"+url.PathEscape(id), localPath)
if err != nil {
return 0, err
}
return carrierNodePushedSize(response), nil
}
func (s *Server) carrierNodeDeleteThumbnail(ctx context.Context, id string) error {
request, err := s.newCarrierNodeRequest(ctx, http.MethodDelete, "/api/thumbnails/"+url.PathEscape(id), nil)
if err != nil {
return err
}
response, err := s.carrierNodeClient().Do(request)
if err != nil {
return err
}
defer response.Body.Close()
if response.StatusCode >= 400 && response.StatusCode != http.StatusNotFound {
return fmt.Errorf("carriernode delete thumbnail failed: %s", response.Status)
}
return nil
}
func (s *Server) carrierNodePushOutput(ctx context.Context, name, localPath string) (int64, error) {
response, err := s.pushToCarrierNode(ctx, http.MethodPost, "/api/outputs/"+url.PathEscape(name), localPath)
if err != nil {
return 0, err
}
return carrierNodePushedSize(response), nil
}
func (s *Server) carrierNodePushInput(ctx context.Context, name, localPath string) (int64, error) {
response, err := s.pushToCarrierNode(ctx, http.MethodPost, "/api/inputs/"+url.PathEscape(name), localPath)
if err != nil {
return 0, err
}
return carrierNodePushedSize(response), nil
}
func (s *Server) carrierNodePushCopy(ctx context.Context, name, localPath string) (int64, error) {
response, err := s.pushToCarrierNode(ctx, http.MethodPost, "/api/copies/"+url.PathEscape(name), localPath)
if err != nil {
return 0, err
}
return carrierNodePushedSize(response), nil
}
// carrierNodeUploadDownload streams a locally-produced file (e.g. a completed yt-dlp download
// staged in a scratch dir) into CarrierNode's DownloadsRoot via its existing raw-upload endpoint.
func (s *Server) carrierNodeUploadDownload(ctx context.Context, localPath, filename string) (map[string]any, error) {
response, err := s.pushToCarrierNode(ctx, http.MethodPost, "/api/upload?filename="+url.QueryEscape(filename), localPath)
if err != nil {
return nil, err
}
defer response.Body.Close()
var payload map[string]any
_ = json.NewDecoder(response.Body).Decode(&payload)
return payload, nil
}
// carrierNodeStoreDownload catalogs an already-uploaded file into CarrierNode's media/downloaded_media
// tables via its existing /api/store endpoint - callers should stop duplicating that DB write
// locally once they migrate to this.
func (s *Server) carrierNodeStoreDownload(ctx context.Context, filePath, sourceURL, tool, status string) (map[string]any, error) {
body, err := json.Marshal(map[string]any{"filePath": filePath, "sourceUrl": sourceURL, "tool": tool, "status": status})
if err != nil {
return nil, err
}
request, err := s.newCarrierNodeRequest(ctx, http.MethodPost, "/api/store", bytes.NewReader(body))
if err != nil {
return nil, err
}
request.Header.Set("Content-Type", "application/json")
response, err := s.carrierNodeClient().Do(request)
if err != nil {
return nil, err
}
defer response.Body.Close()
if response.StatusCode >= 400 {
errorBody, _ := io.ReadAll(io.LimitReader(response.Body, 4096))
return nil, fmt.Errorf("carriernode store failed: %s: %s", response.Status, string(errorBody))
}
var payload map[string]any
_ = json.NewDecoder(response.Body).Decode(&payload)
return payload, nil
}
// carrierNodeListFiles lists files under CarrierNode's MediaRoots via its existing /api/files(/recent)
// endpoints - the replacement for a local filepath.WalkDir over MediaRoots.
func (s *Server) carrierNodeListFiles(ctx context.Context, relative string, recent bool, limit int) ([]fileEntry, error) {
endpoint := "/api/files"
if recent {
endpoint = "/api/files/recent"
}
query := url.Values{}
if relative != "" {
query.Set("path", relative)
}
if limit > 0 {
query.Set("limit", strconv.Itoa(limit))
}
if encoded := query.Encode(); encoded != "" {
endpoint += "?" + encoded
}
request, err := s.newCarrierNodeRequest(ctx, http.MethodGet, endpoint, nil)
if err != nil {
return nil, err
}
response, err := s.carrierNodeClient().Do(request)
if err != nil {
return nil, err
}
defer response.Body.Close()
if response.StatusCode != http.StatusOK {
return nil, fmt.Errorf("carriernode file listing failed: %s", response.Status)
}
var payload struct {
Files []fileEntry `json:"files"`
}
if err := json.NewDecoder(response.Body).Decode(&payload); err != nil {
return nil, err
}
return payload.Files, nil
}
type carrierNodeProbeResult struct {
DurationMs int64 `json:"durationMs"`
Width int `json:"width"`
Height int `json:"height"`
}
// carrierNodeProbe runs ffprobe on CarrierNode against a MediaRoots-relative path and returns just the
// metadata fields - bytes never leave CarrierNode, unlike every other helper in this file.
func (s *Server) carrierNodeProbe(ctx context.Context, relative string) (carrierNodeProbeResult, error) {
query := url.Values{}
query.Set("path", relative)
request, err := s.newCarrierNodeRequest(ctx, http.MethodGet, "/api/probe?"+query.Encode(), nil)
if err != nil {
return carrierNodeProbeResult{}, err
}
response, err := s.carrierNodeClient().Do(request)
if err != nil {
return carrierNodeProbeResult{}, err
}
defer response.Body.Close()
if response.StatusCode != http.StatusOK {
return carrierNodeProbeResult{}, fmt.Errorf("carriernode probe failed: %s", response.Status)
}
var result carrierNodeProbeResult
if err := json.NewDecoder(response.Body).Decode(&result); err != nil {
return carrierNodeProbeResult{}, err
}
return result, nil
}
+195
View File
@@ -0,0 +1,195 @@
package server
import (
"context"
"encoding/json"
"fmt"
"net/http"
"sort"
"strconv"
"strings"
"time"
"github.com/coder/websocket"
"github.com/go-chi/chi/v5"
"repos.gfranz.ch/Gabriel20xx/shared/media-backend/internal/config"
)
type kioskMessage struct {
Type string `json:"type"`
QueueMode string `json:"queueMode,omitempty"`
DisplayDuration int64 `json:"displayDuration,omitempty"`
}
func (s *Server) kioskWebsocket(w http.ResponseWriter, r *http.Request) {
options := s.websocketAcceptOptions(r)
conn, err := websocket.Accept(w, r, options)
if err != nil {
return
}
defer conn.Close(websocket.StatusNormalClosure, "")
updates := make(chan []byte, 16)
s.kioskMu.Lock()
s.kioskClients[updates] = struct{}{}
latest := s.kioskLatest
s.kioskMu.Unlock()
defer func() {
s.kioskMu.Lock()
delete(s.kioskClients, updates)
s.kioskMu.Unlock()
}()
if latest != "" {
s.kioskSend(updates, map[string]any{"type": "new-image", "path": latest})
}
s.kioskSend(updates, map[string]any{
"type": "settings-updated",
"queueMode": s.settingValue(r.Context(), "kiosk_queue_mode", "client"),
"serverDisplayDuration": kioskDuration(s.settingValue(r.Context(), "server_display_duration", "5000")),
})
ctx := r.Context()
writeCtx, cancelWrite := context.WithCancel(ctx)
defer cancelWrite()
go func() {
for {
select {
case <-writeCtx.Done():
return
case data := <-updates:
if err := conn.Write(writeCtx, websocket.MessageText, data); err != nil {
return
}
}
}
}()
s.startKioskPoll()
for {
messageType, payload, readErr := conn.Read(ctx)
if readErr != nil {
return
}
if messageType != websocket.MessageText {
continue
}
var message kioskMessage
if json.Unmarshal(payload, &message) != nil || message.Type != "update-settings" {
continue
}
if message.QueueMode != "" && (message.QueueMode == "client" || message.QueueMode == "server") {
_ = s.saveSetting(ctx, "kiosk_queue_mode", message.QueueMode)
}
if message.DisplayDuration >= 0 && message.DisplayDuration <= 24*60*60*1000 {
_ = s.saveSetting(ctx, "server_display_duration", formatInt(message.DisplayDuration))
}
s.kioskBroadcast(map[string]any{
"type": "settings-updated",
"queueMode": s.settingValue(ctx, "kiosk_queue_mode", "client"),
"serverDisplayDuration": kioskDuration(s.settingValue(ctx, "server_display_duration", "5000")),
})
}
}
func (s *Server) startKioskPoll() {
s.kioskMu.Lock()
if s.kioskPolling {
s.kioskMu.Unlock()
return
}
s.kioskPolling = true
s.kioskMu.Unlock()
go s.kioskPoll(context.Background())
}
func (s *Server) kioskPoll(ctx context.Context) {
if s.cfg.Service != config.Kiosk {
return
}
ticker := time.NewTicker(3 * time.Second)
defer ticker.Stop()
for {
s.kioskPollOnce(ctx)
select {
case <-ctx.Done():
return
case <-ticker.C:
}
}
}
func (s *Server) kioskPollOnce(ctx context.Context) {
files, err := s.carrierNodeListFiles(ctx, "", false, 0)
if err != nil {
return
}
images := make([]fileEntry, 0, len(files))
for _, file := range files {
if file.Type == "image" {
images = append(images, file)
}
}
if len(images) == 0 {
return
}
sort.Slice(images, func(i, j int) bool { return images[i].Mtime > images[j].Mtime })
latest := images[0].Rel
s.kioskMu.Lock()
changed := latest != s.kioskLatest
s.kioskLatest = latest
s.kioskMu.Unlock()
if changed {
s.kioskBroadcast(map[string]any{"type": "new-image", "path": latest})
}
}
func (s *Server) kioskBroadcast(message any) {
data, err := json.Marshal(message)
if err != nil {
return
}
s.kioskMu.Lock()
defer s.kioskMu.Unlock()
for client := range s.kioskClients {
select {
case client <- data:
default:
}
}
}
func (s *Server) kioskSend(client chan []byte, message any) {
data, err := json.Marshal(message)
if err != nil {
return
}
select {
case client <- data:
default:
}
}
func (s *Server) kioskImage(w http.ResponseWriter, r *http.Request) {
relative := chi.URLParam(r, "*")
if relative == "" {
relative = strings.TrimPrefix(r.URL.Path, "/api/images/")
}
if !safeRelative(relative) || !isImagePath(relative) {
writeError(w, http.StatusNotFound, "image not found")
return
}
s.proxyCarrierNode(w, r, "/media/"+urlPath(relative))
}
func kioskDuration(value string) int64 {
var duration int64
if _, err := fmt.Sscanf(value, "%d", &duration); err != nil || duration < 0 {
return 5000
}
return duration
}
func formatInt(value int64) string {
return strconv.FormatInt(value, 10)
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,83 @@
package server
import (
"net"
"os"
"path/filepath"
"strings"
"testing"
)
func TestSafeRelativeRejectsTraversal(t *testing.T) {
for _, value := range []string{"", ".", "..", "../secret", `..\secret`, `/etc/passwd`, "a/../../b"} {
if safeRelative(value) {
t.Errorf("safeRelative(%q) = true", value)
}
}
for _, value := range []string{"video.mp4", "nested/image.webp", "funscript.json"} {
if !safeRelative(value) {
t.Errorf("safeRelative(%q) = false", value)
}
}
}
func TestSameRealRootRejectsSymlinkEscape(t *testing.T) {
root := t.TempDir()
inside := filepath.Join(root, "inside.txt")
if err := os.WriteFile(inside, []byte("ok"), 0o600); err != nil {
t.Fatal(err)
}
if !sameRealRoot(root, inside) {
t.Fatal("sameRealRoot rejected a file inside the root")
}
outside := t.TempDir()
outsideFile := filepath.Join(outside, "outside.txt")
if err := os.WriteFile(outsideFile, []byte("secret"), 0o600); err != nil {
t.Fatal(err)
}
link := filepath.Join(root, "link.txt")
if err := os.Symlink(outsideFile, link); err != nil {
t.Skipf("symlink unavailable: %v", err)
}
if sameRealRoot(root, link) {
t.Fatal("sameRealRoot accepted a symlink outside the root")
}
}
func TestConversionArgsDoNotAcceptArbitraryEncoderFlags(t *testing.T) {
args := strings.Join(conversionArgs("input.mp4", "output.mp4", "mp4", "-filter_complex malicious"), " ")
if strings.Contains(args, "malicious") || !strings.Contains(args, "libx264") {
t.Fatalf("conversion args = %q", args)
}
}
func TestHasFunscriptSidecar(t *testing.T) {
root := t.TempDir()
mediaPath := filepath.Join(root, "clip.mp4")
if os.WriteFile(mediaPath, []byte("media"), 0o600) != nil {
t.Fatal("could not create media fixture")
}
if hasFunscriptSidecar(mediaPath) {
t.Fatal("media without a sidecar was marked as having a funscript")
}
if os.WriteFile(filepath.Join(root, "clip.funscript"), []byte("{}"), 0o600) != nil {
t.Fatal("could not create funscript fixture")
}
if !hasFunscriptSidecar(mediaPath) {
t.Fatal("funscript sidecar was not detected")
}
}
func TestDownloadURLValidation(t *testing.T) {
for _, value := range []string{"file:///etc/passwd", "http://127.0.0.1/x", "http://169.254.169.254/", "https://user:pass@example.com/x"} {
if err := validateDownloadURL(value); err == nil {
t.Errorf("validateDownloadURL(%q) succeeded", value)
}
}
if err := validateDownloadURL("https://example.com/video"); err != nil {
t.Fatalf("public URL rejected: %v", err)
}
if !isPrivateIP(net.ParseIP("127.0.0.1")) {
t.Fatal("loopback was not classified as private")
}
}
+432
View File
@@ -0,0 +1,432 @@
package server
import (
"context"
"encoding/json"
"fmt"
"io/fs"
"log"
"net/http"
"os"
"path"
"runtime"
"strings"
"sync"
"time"
"github.com/go-chi/chi/v5"
chimiddleware "github.com/go-chi/chi/v5/middleware"
"github.com/jackc/pgx/v5/pgxpool"
"repos.gfranz.ch/Gabriel20xx/shared/media-backend/internal/auth"
"repos.gfranz.ch/Gabriel20xx/shared/media-backend/internal/config"
)
type Server struct {
cfg *config.Config
db *pgxpool.Pool
auth *auth.Service
startedAt time.Time
mediaMu sync.RWMutex
media map[string]MediaRecord
jobsMu sync.RWMutex
jobs map[string]*WorkflowJob
workflowSem chan struct{}
sync *syncHub
thumbnailMu sync.Mutex
thumbnail thumbnailGenerationState
thumbnailCancel context.CancelFunc
clearMu sync.Mutex
clear databaseClearState
scanMu sync.Mutex
scan scanState
scanCancel context.CancelFunc
analysisMu sync.Mutex
analysis analysisState
analysisCancel context.CancelFunc
kioskMu sync.Mutex
kioskClients map[chan []byte]struct{}
kioskLatest string
kioskPolling bool
}
type MediaRecord struct {
ID int64
MediaKey string
MediaType string
Title *string
Description *string
FilePath string
OriginalName string
Source string
Width *int
Height *int
DurationMs *int64
SizeBytes *int64
IsVR bool
HasFunscript bool
Speed *float32
ModifiedAt time.Time
}
type WorkflowJob struct {
ID string `json:"id"`
Service string `json:"service"`
Tool string `json:"tool"`
Status string `json:"status"`
Progress int `json:"progress"`
Request map[string]any `json:"request,omitempty"`
Result map[string]any `json:"result,omitempty"`
Error string `json:"error,omitempty"`
CreatedAt time.Time `json:"createdAt"`
StartedAt *time.Time `json:"startedAt,omitempty"`
FinishedAt *time.Time `json:"finishedAt,omitempty"`
}
type thumbnailGenerationState struct {
Running bool
State string
Total int
Completed int
Failed int
Current string
CurrentType string
StartedAt *time.Time
FinishedAt *time.Time
LastError string
}
// databaseClearState tracks a dashboard/per-media-type reset so it can be reported through the
// same live status endpoint as the analyzer workers. The reset itself is deliberately kept
// synchronous from the HTTP caller's perspective, but large libraries still need an honest state
// while their thumbnail files and database rows are being removed.
type databaseClearState struct {
Running bool
State string
Total int
Completed int
Failed int
Current string
CurrentType string
StartedAt *time.Time
FinishedAt *time.Time
LastError string
}
// scanState tracks the currently-running discover/metadata walk so the analyzer UI can show
// which media type is actively being indexed right now - scanMediaFiles has no separate queue,
// it indexes (and, per pipelineStageEnabled, extracts metadata for) each file synchronously as
// it's found, so "active" here is the closest honest signal to a live "processing" state.
type scanState struct {
Running bool
Mode string // "discover" (filesystem walk), "metadata" (refresh), or "cleanup" (stale sweep)
CurrentType string
CurrentFile string
FilesIndexed int64
// Total is only known upfront for metadata/cleanup - both pre-fetch their full row list before
// looping. discover has no total (a live filesystem walk doesn't know its own size in advance)
// and leaves this at zero, which the UI treats as "not available".
Total int64
StartedAt *time.Time
// LastError survives the end-of-run reset (unlike every other field here) so a run that
// failed fast - e.g. CarrierNode unreachable - doesn't just look like it silently reverted
// to idle; analyzerStatus reports it until the next run overwrites or clears it.
LastError string
}
func New(cfg *config.Config, db *pgxpool.Pool) *Server {
return &Server{
cfg: cfg,
db: db,
auth: auth.New(db, cfg.SessionCookie, cfg.SecureCookies, cfg.AuthGuardURL),
startedAt: time.Now(),
media: make(map[string]MediaRecord),
jobs: make(map[string]*WorkflowJob),
workflowSem: make(chan struct{}, 2),
sync: newSyncHub(),
thumbnail: thumbnailGenerationState{State: "idle"},
analysis: analysisState{State: "idle"},
kioskClients: make(map[chan []byte]struct{}),
}
}
func (s *Server) Handler() http.Handler {
router := chi.NewRouter()
router.Use(chimiddleware.RequestID)
router.Use(chimiddleware.Recoverer)
router.Use(s.securityHeadersMiddleware)
router.Use(s.cors)
router.Get("/healthz", s.health)
router.Get("/health", s.health)
router.Get("/ready", s.ready)
router.With(s.auth.RequireIfLoginRequired).Get("/api/tech-stack", s.techStack)
router.Get("/__cache-policy", s.cachePolicy)
router.Route("/auth", func(r chi.Router) {
r.Post("/signup", s.auth.Signup)
r.Post("/login", s.auth.Login)
r.Post("/logout", s.auth.Logout)
r.Get("/me", s.auth.Me)
r.With(s.auth.Require).Put("/me", s.auth.UpdateMe)
r.Get("/status", s.auth.Status)
r.Get("/bootstrap/admin-needed", s.auth.AdminNeeded)
})
router.Route("/api/auth", func(r chi.Router) {
manager := r.With(s.auth.RequireUserManager)
manager.Get("/access", s.auth.AccessSettings)
manager.Put("/access", s.auth.UpdateAccessSettings)
manager.Get("/users", s.auth.ManagedUsers)
manager.Post("/users", s.auth.ManagedCreateUser)
manager.Put("/users/{id}", s.auth.ManagedUpdateUser)
manager.Patch("/users/{id}", s.auth.ManagedUpdateUser)
manager.Delete("/users/{id}", s.auth.ManagedDeleteUser)
})
router.Route("/api", func(r chi.Router) {
s.mountServiceRoutes(r)
})
if s.cfg.Service == config.Kiosk {
s.mountKioskSocket(router)
}
if s.cfg.Service != config.Kiosk {
router.HandleFunc("/ws", s.syncWebsocket)
}
if s.cfg.Service == config.CarrierNode {
internal := s.internalServiceAuth
router.Handle("/media/downloads/*", internal(http.HandlerFunc(s.carrierNodeDownloadMedia)))
router.Handle("/mount/generated/*", internal(http.HandlerFunc(s.carrierNodeGeneratedMedia)))
router.Handle("/mount/inputs/*", internal(http.HandlerFunc(s.carrierNodeInputMedia)))
router.Handle("/mount/copies/*", internal(http.HandlerFunc(s.carrierNodeCopyMedia)))
router.Handle("/media/*", internal(http.HandlerFunc(s.carrierNodeMedia)))
router.Handle("/thumbnails/*", internal(http.HandlerFunc(s.carrierNodeThumbnail)))
}
router.NotFound(s.staticHandler)
return router
}
func (s *Server) mountServiceRoutes(r chi.Router) {
s.mountSharedRoutes(r)
switch s.cfg.Service {
case config.Viewer:
s.mountViewerRoutes(r)
case config.Tools:
s.mountToolsRoutes(r)
case config.Analyzer:
s.mountAnalyzerRoutes(r)
case config.ConfigService:
s.mountConfigRoutes(r)
case config.Moderator:
s.mountModeratorRoutes(r)
case config.Kiosk:
s.mountKioskRoutes(r)
case config.CarrierNode:
s.mountCarrierNodeRoutes(r)
}
}
func (s *Server) securityHeadersMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("X-Content-Type-Options", "nosniff")
w.Header().Set("X-Frame-Options", "DENY")
w.Header().Set("Referrer-Policy", "same-origin")
w.Header().Set("Permissions-Policy", "camera=(), microphone=(), geolocation=()")
w.Header().Set("Content-Security-Policy", "default-src 'self'; base-uri 'self'; object-src 'none'; frame-ancestors 'none'; img-src 'self' data: blob:; media-src 'self' blob:; style-src 'self' 'unsafe-inline'; script-src 'self' 'unsafe-inline'; connect-src 'self' ws: wss:")
next.ServeHTTP(w, r)
})
}
func (s *Server) cors(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
origin := r.Header.Get("Origin")
if origin != "" && (s.cfg.AllowedOrigin == "*" || origin == s.cfg.AllowedOrigin) {
w.Header().Set("Access-Control-Allow-Origin", origin)
w.Header().Set("Access-Control-Allow-Credentials", "true")
w.Header().Add("Vary", "Origin")
}
if r.Method == http.MethodOptions {
w.Header().Set("Access-Control-Allow-Methods", "GET, POST, PUT, PATCH, DELETE, OPTIONS")
w.Header().Set("Access-Control-Allow-Headers", "Content-Type, Authorization, X-Internal-Auth")
w.WriteHeader(http.StatusNoContent)
return
}
next.ServeHTTP(w, r)
})
}
func (s *Server) health(w http.ResponseWriter, _ *http.Request) {
writeJSON(w, http.StatusOK, map[string]any{"ok": true, "service": s.cfg.ServiceName, "uptimeSeconds": int(time.Since(s.startedAt).Seconds())})
}
func (s *Server) ready(w http.ResponseWriter, r *http.Request) {
if s.db == nil {
writeJSON(w, http.StatusServiceUnavailable, map[string]any{"ok": false, "service": s.cfg.ServiceName, "error": "database unavailable"})
return
}
ctx, cancel := context.WithTimeout(r.Context(), 2*time.Second)
defer cancel()
if err := s.db.Ping(ctx); err != nil {
writeJSON(w, http.StatusServiceUnavailable, map[string]any{"ok": false, "service": s.cfg.ServiceName, "error": "database unavailable"})
return
}
writeJSON(w, http.StatusOK, map[string]any{"ok": true, "service": s.cfg.ServiceName})
}
func (s *Server) techStack(w http.ResponseWriter, _ *http.Request) {
appVersion := os.Getenv("APP_VERSION")
if appVersion == "" {
appVersion = "go-rewrite"
}
writeJSON(w, http.StatusOK, map[string]any{
"appVersion": appVersion,
"stack": []map[string]string{
{"label": "Runtime", "value": runtime.Version()},
{"label": "HTTP", "value": "net/http + chi"},
{"label": "Database", "value": "PostgreSQL + pgx"},
{"label": "Authentication", "value": "bcrypt + PostgreSQL sessions"},
},
})
}
func (s *Server) cachePolicy(w http.ResponseWriter, _ *http.Request) {
writeJSON(w, http.StatusOK, map[string]any{"service": s.cfg.ServiceName, "policies": map[string]string{"static": "public, max-age=3600", "media": "private, max-age=0, must-revalidate"}})
}
func (s *Server) staticHandler(w http.ResponseWriter, r *http.Request) {
root := os.DirFS(s.cfg.WebRoot)
if _, err := fs.Stat(root, "."); err != nil {
writeJSON(w, http.StatusNotFound, map[string]string{"error": "frontend build not found"})
return
}
requested := strings.TrimPrefix(path.Clean("/"+r.URL.Path), "/")
if requested == "." || requested == "" {
requested = "index.html"
}
if info, err := fs.Stat(root, requested); err == nil && !info.IsDir() {
http.FileServer(http.FS(root)).ServeHTTP(w, r)
return
}
if path.Ext(requested) != "" {
http.NotFound(w, r)
return
}
index, err := fs.ReadFile(root, "index.html")
if err != nil {
http.NotFound(w, r)
return
}
w.Header().Set("Content-Type", "text/html; charset=utf-8")
_, _ = w.Write(index)
}
func (s *Server) listenAndServe(ctx context.Context) error {
server := &http.Server{Addr: ":" + s.cfg.Port, Handler: s.Handler(), ReadHeaderTimeout: 10 * time.Second, ReadTimeout: 30 * time.Second, WriteTimeout: 0, IdleTimeout: 60 * time.Second}
go func() {
<-ctx.Done()
shutdownCtx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
_ = server.Shutdown(shutdownCtx)
}()
log.Printf("%s listening on http://:%s (Go)", s.cfg.ServiceName, s.cfg.Port)
if s.cfg.TLSCertFile != "" {
return server.ListenAndServeTLS(s.cfg.TLSCertFile, s.cfg.TLSKeyFile)
}
return server.ListenAndServe()
}
func (s *Server) Run(ctx context.Context) error {
go s.resumeWorkflowJobs(ctx)
if s.cfg.Service == config.Analyzer {
go s.runAnalyzerScheduler(ctx)
}
if s.cfg.Service == config.ConfigService {
go s.runSettingsSyncScheduler(ctx)
}
return s.listenAndServe(ctx)
}
func writeJSON(w http.ResponseWriter, status int, value any) {
w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.WriteHeader(status)
_ = json.NewEncoder(w).Encode(value)
}
func writeError(w http.ResponseWriter, status int, message string) {
writeJSON(w, status, map[string]string{"error": message, "message": message})
}
func stringValue(value *string) string {
if value == nil {
return ""
}
return *value
}
func intValue(value *int) any {
if value == nil {
return nil
}
return *value
}
func int64Value(value *int64) any {
if value == nil {
return nil
}
return *value
}
func floatValue(value *float32) any {
if value == nil {
return nil
}
return *value
}
func boolQuery(value string) *bool {
switch strings.ToLower(strings.TrimSpace(value)) {
case "1", "true", "yes", "on":
result := true
return &result
case "0", "false", "no", "off":
result := false
return &result
default:
return nil
}
}
func (s *Server) internalServiceAuth(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if s.cfg.InternalServiceSecret == "" || r.Header.Get("X-Internal-Auth") != s.cfg.InternalServiceSecret {
writeError(w, http.StatusUnauthorized, "internal service authentication required")
return
}
next.ServeHTTP(w, r)
})
}
func (s *Server) requireAdminOrInternal(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if auth.IsAdmin(auth.UserFromContext(r.Context())) || (s.cfg.InternalServiceSecret != "" && r.Header.Get("X-Internal-Auth") == s.cfg.InternalServiceSecret) {
next.ServeHTTP(w, r)
return
}
writeError(w, http.StatusUnauthorized, "administrator or internal service authentication required")
})
}
func optionalInt(value string, fallback, minimum, maximum int) int {
var parsed int
if _, err := fmt.Sscanf(strings.TrimSpace(value), "%d", &parsed); err != nil {
return fallback
}
if parsed < minimum {
return minimum
}
if parsed > maximum {
return maximum
}
return parsed
}
+541
View File
@@ -0,0 +1,541 @@
package server
import (
"context"
"encoding/json"
"math"
"net/http"
"net/url"
"strings"
"sync"
"time"
"github.com/coder/websocket"
)
const (
maxSyncIdentifier = 128
maxSyncSessions = 1000
)
type syncPeer struct {
conn *websocket.Conn
writeMu sync.Mutex
clientID string
sessionID string
userAgent string
ipAddress string
remoteControlEnabled bool
uiView string
uiMediaID any
uiMediaIDSet bool
}
type syncHub struct {
mu sync.Mutex
peers map[*syncPeer]struct{}
states map[string]map[string]any
playAt map[string]string
playAtLocalMs map[string]int64
capturedAtMs map[string]int64
controlOwners map[string]string
}
func newSyncHub() *syncHub {
return &syncHub{
peers: make(map[*syncPeer]struct{}),
states: make(map[string]map[string]any),
playAt: make(map[string]string),
playAtLocalMs: make(map[string]int64),
capturedAtMs: make(map[string]int64),
controlOwners: make(map[string]string),
}
}
func (h *syncHub) add(peer *syncPeer) {
h.mu.Lock()
h.peers[peer] = struct{}{}
h.mu.Unlock()
}
func (h *syncHub) remove(peer *syncPeer) string {
h.mu.Lock()
defer h.mu.Unlock()
delete(h.peers, peer)
if peer.clientID != "" && !h.hasClientLocked(peer.clientID) {
delete(h.controlOwners, peer.clientID)
for targetID, ownerID := range h.controlOwners {
if ownerID == peer.clientID {
delete(h.controlOwners, targetID)
}
}
}
return peer.sessionID
}
func (h *syncHub) hasClientLocked(clientID string) bool {
for peer := range h.peers {
if peer.clientID == clientID {
return true
}
}
return false
}
func (h *syncHub) updatePeer(peer *syncPeer, clientID, sessionID string) {
h.mu.Lock()
if clientID != "" {
peer.clientID = clientID
}
if sessionID != "" {
peer.sessionID = sessionID
}
h.mu.Unlock()
}
func (h *syncHub) clientStatus(peer *syncPeer, sessionID, view string, mediaID any, mediaIDSet bool, remoteSet, remote bool) {
h.mu.Lock()
defer h.mu.Unlock()
if sessionID != "" {
peer.sessionID = sessionID
}
if view != "" {
peer.uiView = view
}
if mediaIDSet {
peer.uiMediaID = mediaID
peer.uiMediaIDSet = true
}
if remoteSet {
peer.remoteControlEnabled = remote
if !remote && h.controlOwners[peer.clientID] != "" {
delete(h.controlOwners, peer.clientID)
}
}
}
func (h *syncHub) clientsLocked(sessionID string) []map[string]any {
byID := make(map[string]map[string]any)
for peer := range h.peers {
if peer.sessionID != sessionID || peer.clientID == "" {
continue
}
entry, exists := byID[peer.clientID]
if !exists {
entry = map[string]any{
"clientId": peer.clientID,
"userAgent": peer.userAgent,
"ipAddress": peer.ipAddress,
"remoteControlEnabled": peer.remoteControlEnabled,
"controlOwnerClientId": nil,
}
byID[peer.clientID] = entry
} else if peer.remoteControlEnabled {
entry["remoteControlEnabled"] = true
}
if peer.uiView != "" {
entry["uiView"] = peer.uiView
}
if peer.uiMediaIDSet {
entry["uiMediaId"] = peer.uiMediaID
}
}
for clientID, entry := range byID {
if owner := h.controlOwners[clientID]; owner != "" {
entry["controlOwnerClientId"] = owner
}
}
clients := make([]map[string]any, 0, len(byID))
for _, entry := range byID {
clients = append(clients, entry)
}
return clients
}
func (h *syncHub) stateLocked(sessionID string) map[string]any {
state, ok := h.states[sessionID]
if !ok {
return map[string]any{
"sessionId": sessionID,
"mediaId": nil,
"timeMs": int64(0),
"paused": true,
"fps": 30,
"frame": int64(0),
"fromClientId": "",
"updatedAt": time.Unix(0, 0).UTC().Format(time.RFC3339Nano),
}
}
return cloneMap(state)
}
func (h *syncHub) httpState(sessionID string) map[string]any {
h.mu.Lock()
defer h.mu.Unlock()
return h.timingLocked(sessionID, h.stateLocked(sessionID))
}
func (h *syncHub) setHTTPState(sessionID string, state map[string]any) {
h.mu.Lock()
defer h.mu.Unlock()
h.states[sessionID] = cloneMap(state)
if len(h.states) > maxSyncSessions {
for key := range h.states {
delete(h.states, key)
break
}
}
}
func (h *syncHub) timingLocked(sessionID string, state map[string]any) map[string]any {
paused, _ := state["paused"].(bool)
if !paused {
if value := h.playAt[sessionID]; value != "" {
state["playAt"] = value
}
}
if value, ok := h.playAtLocalMs[sessionID]; ok {
state["playAtLocalMs"] = value
}
if value, ok := h.capturedAtMs[sessionID]; ok {
state["capturedAtLocalMs"] = value
}
return state
}
func (h *syncHub) broadcast(sessionID string) {
h.mu.Lock()
state := h.timingLocked(sessionID, h.stateLocked(sessionID))
clients := h.clientsLocked(sessionID)
peers := make([]*syncPeer, 0)
for peer := range h.peers {
if peer.sessionID == sessionID {
peers = append(peers, peer)
}
}
h.mu.Unlock()
message := map[string]any{"type": "sync:state", "state": state, "clients": clients}
for _, peer := range peers {
if err := peer.send(message); err != nil {
_ = peer.conn.Close(websocket.StatusGoingAway, "write failed")
}
}
}
func (peer *syncPeer) send(message any) error {
data, err := json.Marshal(message)
if err != nil {
return err
}
peer.writeMu.Lock()
defer peer.writeMu.Unlock()
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
defer cancel()
return peer.conn.Write(ctx, websocket.MessageText, data)
}
func (s *Server) websocketAcceptOptions(r *http.Request) *websocket.AcceptOptions {
options := &websocket.AcceptOptions{}
if s.cfg.AllowedOrigin == "*" {
options.InsecureSkipVerify = true
return options
}
patterns := make([]string, 0, 2)
addOrigin := func(value string) {
parsed, err := url.Parse(strings.TrimSpace(value))
if err == nil && parsed.Scheme != "" && parsed.Host != "" {
patterns = append(patterns, parsed.Scheme+"://"+parsed.Host)
}
}
addOrigin(s.cfg.AllowedOrigin)
scheme := "http"
if r.TLS != nil {
scheme = "https"
}
addOrigin(scheme + "://" + r.Host)
options.OriginPatterns = patterns
return options
}
func (s *Server) syncWebsocket(w http.ResponseWriter, r *http.Request) {
conn, err := websocket.Accept(w, r, s.websocketAcceptOptions(r))
if err != nil {
return
}
peer := &syncPeer{
conn: conn,
userAgent: firstNonEmpty(r.Header.Get("User-Agent"), "Unknown"),
ipAddress: firstNonEmpty(strings.Split(r.Header.Get("X-Forwarded-For"), ",")[0], r.RemoteAddr, "Unknown"),
}
s.sync.add(peer)
defer func() {
sessionID := s.sync.remove(peer)
_ = conn.Close(websocket.StatusNormalClosure, "")
if sessionID != "" {
s.sync.broadcast(sessionID)
}
}()
_ = peer.send(map[string]any{"type": "hello", "ts": time.Now().UnixMilli()})
for {
messageType, payload, readErr := conn.Read(r.Context())
if readErr != nil {
return
}
if messageType != websocket.MessageText {
continue
}
var message map[string]any
if json.Unmarshal(payload, &message) != nil {
continue
}
s.handleSyncMessage(peer, message)
}
}
func (s *Server) handleSyncMessage(peer *syncPeer, message map[string]any) {
typ, _ := message["type"].(string)
switch typ {
case "ws:ping":
_ = peer.send(map[string]any{
"type": "ws:pong",
"nonce": syncString(message, "nonce"),
"clientSentAt": syncNumberValue(message, "clientSentAt"),
"serverReceivedAt": time.Now().UnixMilli(),
})
case "sync:hello":
clientID := boundedSyncString(syncString(message, "clientId"))
sessionID := boundedSyncString(firstNonEmpty(syncString(message, "sessionId"), "default"))
if clientID == "" || sessionID == "" {
return
}
s.sync.updatePeer(peer, clientID, sessionID)
s.sync.broadcast(sessionID)
case "client:status":
clientID := boundedSyncString(firstNonEmpty(syncString(message, "clientId"), peer.clientID))
sessionID := boundedSyncString(firstNonEmpty(syncString(message, "sessionId"), peer.sessionID, "default"))
if clientID == "" {
return
}
s.sync.updatePeer(peer, clientID, sessionID)
mediaID, mediaIDSet := syncMediaID(message)
remote, remoteSet := message["remoteControlEnabled"].(bool)
s.sync.clientStatus(peer, sessionID, boundedSyncString(syncString(message, "uiView")), mediaID, mediaIDSet, remoteSet, remote)
s.sync.broadcast(sessionID)
case "control:claim", "control:release":
s.handleControlMessage(peer, typ, message)
case "sync:update":
s.handleSyncUpdate(peer, message)
}
}
func (s *Server) handleControlMessage(peer *syncPeer, typ string, message map[string]any) {
requesterID := boundedSyncString(firstNonEmpty(syncString(message, "clientId"), peer.clientID))
sessionID := boundedSyncString(firstNonEmpty(syncString(message, "sessionId"), peer.sessionID, "default"))
targetID := boundedSyncString(syncString(message, "targetClientId"))
if requesterID == "" || targetID == "" || requesterID != peer.clientID {
return
}
s.sync.mu.Lock()
owner := s.sync.controlOwners[targetID]
ok := false
reason := ""
if typ == "control:claim" {
enabled := false
for candidate := range s.sync.peers {
if candidate.clientID == targetID && candidate.remoteControlEnabled {
enabled = true
break
}
}
switch {
case !enabled:
reason = "disabled"
case owner != "" && owner != requesterID:
reason = "busy"
default:
s.sync.controlOwners[targetID] = requesterID
owner = requesterID
ok = true
}
} else if owner != "" && owner != requesterID {
reason = "not-owner"
} else {
delete(s.sync.controlOwners, targetID)
owner = ""
ok = true
}
s.sync.mu.Unlock()
_ = peer.send(map[string]any{
"type": "control:ack",
"ok": ok,
"action": strings.TrimPrefix(typ, "control:"),
"targetClientId": targetID,
"ownerClientId": nullableString(owner),
"reason": nullableString(reason),
})
s.sync.broadcast(sessionID)
}
func (s *Server) handleSyncUpdate(peer *syncPeer, message map[string]any) {
clientID := boundedSyncString(firstNonEmpty(syncString(message, "clientId"), peer.clientID))
sessionID := boundedSyncString(firstNonEmpty(syncString(message, "sessionId"), peer.sessionID, "default"))
if clientID == "" || clientID != peer.clientID {
return
}
mediaID, _ := syncMediaID(message)
paused := syncBool(message, "paused")
state := map[string]any{
"sessionId": sessionID,
"mediaId": mediaID,
"timeMs": syncInt(message, "timeMs", 0),
"paused": paused,
"fps": syncFPS(message),
"frame": syncInt(message, "frame", 0),
"fromClientId": clientID,
"updatedAt": time.Now().UTC().Format(time.RFC3339Nano),
}
for _, key := range []string{"openInUi", "seekToken", "seekPhase", "seekWantPlay", "seekTargetClientId", "fullscreen", "goToGrid"} {
if value, ok := message[key]; ok {
state[key] = value
}
}
toClientID := boundedSyncString(syncString(message, "toClientId"))
playAtRaw, hasPlayAt := message["playAt"]
s.sync.mu.Lock()
if paused || !hasPlayAt || strings.TrimSpace(syncStringValue(playAtRaw)) == "" {
delete(s.sync.playAt, sessionID)
delete(s.sync.playAtLocalMs, sessionID)
} else if parsed, err := time.Parse(time.RFC3339Nano, strings.TrimSpace(syncStringValue(playAtRaw))); err == nil {
s.sync.playAt[sessionID] = parsed.UTC().Format(time.RFC3339Nano)
if local := syncInt(message, "playAtLocalMs", 0); local > 0 {
s.sync.playAtLocalMs[sessionID] = local
} else {
delete(s.sync.playAtLocalMs, sessionID)
}
}
if captured := syncInt(message, "capturedAtLocalMs", 0); captured > 0 {
s.sync.capturedAtMs[sessionID] = captured
}
if toClientID == "" {
s.sync.states[sessionID] = cloneMap(state)
if len(s.sync.states) > maxSyncSessions {
for key := range s.sync.states {
delete(s.sync.states, key)
break
}
}
}
state = s.sync.timingLocked(sessionID, state)
clients := s.sync.clientsLocked(sessionID)
peers := make([]*syncPeer, 0)
if toClientID != "" {
for candidate := range s.sync.peers {
if candidate.sessionID == sessionID && candidate.clientID == toClientID {
peers = append(peers, candidate)
}
}
}
s.sync.mu.Unlock()
messageOut := map[string]any{"type": "sync:state", "state": state, "clients": clients}
if toClientID != "" {
for _, target := range peers {
if err := target.send(messageOut); err != nil {
_ = target.conn.Close(websocket.StatusGoingAway, "write failed")
}
}
return
}
s.sync.broadcast(sessionID)
}
func syncMediaID(message map[string]any) (any, bool) {
value, ok := message["mediaId"]
if !ok {
return nil, false
}
if value == nil {
return nil, true
}
return boundedSyncString(syncStringValue(value)), true
}
func syncString(message map[string]any, key string) string {
return syncStringValue(message[key])
}
func syncStringValue(value any) string {
if value == nil {
return ""
}
if text, ok := value.(string); ok {
return strings.TrimSpace(text)
}
return ""
}
func boundedSyncString(value string) string {
value = strings.TrimSpace(value)
if len(value) > maxSyncIdentifier {
return value[:maxSyncIdentifier]
}
return value
}
func syncBool(message map[string]any, key string) bool {
value, _ := message[key].(bool)
return value
}
func syncNumberValue(message map[string]any, key string) any {
if value, ok := message[key]; ok {
return value
}
return nil
}
func syncInt(message map[string]any, key string, fallback int64) int64 {
value, ok := message[key].(float64)
if !ok || math.IsNaN(value) || math.IsInf(value, 0) {
return fallback
}
if value < 0 {
return 0
}
if value > float64(^uint64(0)>>1) {
return int64(^uint64(0) >> 1)
}
return int64(math.Round(value))
}
func syncFPS(message map[string]any) int64 {
fps := syncInt(message, "fps", 30)
if fps < 1 {
return 1
}
if fps > 240 {
return 240
}
return fps
}
func nullableString(value string) any {
if value == "" {
return nil
}
return value
}
func cloneMap(value map[string]any) map[string]any {
result := make(map[string]any, len(value))
for key, item := range value {
result[key] = item
}
return result
}
File diff suppressed because it is too large. Load diff
+24 -26
View File
@@ -1,12 +1,12 @@
{ {
"name": "@gabriel20xx/shared-code", "name": "@gabriel20xx/shared-code",
"version": "0.1.0", "version": "0.1.1",
"lockfileVersion": 3, "lockfileVersion": 3,
"requires": true, "requires": true,
"packages": { "packages": {
"": { "": {
"name": "@gabriel20xx/shared-code", "name": "@gabriel20xx/shared-code",
"version": "0.1.0", "version": "0.1.1",
"license": "MIT", "license": "MIT",
"workspaces": [ "workspaces": [
"packages/*" "packages/*"
@@ -742,6 +742,10 @@
"resolved": "packages/design-tokens", "resolved": "packages/design-tokens",
"link": true "link": true
}, },
"node_modules/@gabriel20xx/legacy-assets": {
"resolved": "packages/legacy-assets",
"link": true
},
"node_modules/@gabriel20xx/node-backend": { "node_modules/@gabriel20xx/node-backend": {
"resolved": "packages/node-backend", "resolved": "packages/node-backend",
"link": true "link": true
@@ -776,7 +780,6 @@
"version": "0.3.13", "version": "0.3.13",
"resolved": "https://registry.npmjs.org/@jridgewell/gen-mapping/-/gen-mapping-0.3.13.tgz", "resolved": "https://registry.npmjs.org/@jridgewell/gen-mapping/-/gen-mapping-0.3.13.tgz",
"integrity": "sha512-2kkt/7niJ6MgEPxF0bYdQ6etZaA+fQvDcLKckhy1yIQOzaoKjBBjSj63/aLVjYE3qhRt5dvM+uUyfCg6UKCBbA==", "integrity": "sha512-2kkt/7niJ6MgEPxF0bYdQ6etZaA+fQvDcLKckhy1yIQOzaoKjBBjSj63/aLVjYE3qhRt5dvM+uUyfCg6UKCBbA==",
"dev": true,
"license": "MIT", "license": "MIT",
"dependencies": { "dependencies": {
"@jridgewell/sourcemap-codec": "^1.5.0", "@jridgewell/sourcemap-codec": "^1.5.0",
@@ -787,7 +790,6 @@
"version": "2.3.5", "version": "2.3.5",
"resolved": "https://registry.npmjs.org/@jridgewell/remapping/-/remapping-2.3.5.tgz", "resolved": "https://registry.npmjs.org/@jridgewell/remapping/-/remapping-2.3.5.tgz",
"integrity": "sha512-LI9u/+laYG4Ds1TDKSJW2YPrIlcVYOwi2fUC6xB43lueCjgxV4lffOCZCtYFiH6TNOX+tQKXx97T4IKHbhyHEQ==", "integrity": "sha512-LI9u/+laYG4Ds1TDKSJW2YPrIlcVYOwi2fUC6xB43lueCjgxV4lffOCZCtYFiH6TNOX+tQKXx97T4IKHbhyHEQ==",
"dev": true,
"license": "MIT", "license": "MIT",
"dependencies": { "dependencies": {
"@jridgewell/gen-mapping": "^0.3.5", "@jridgewell/gen-mapping": "^0.3.5",
@@ -798,7 +800,6 @@
"version": "3.1.2", "version": "3.1.2",
"resolved": "https://registry.npmjs.org/@jridgewell/resolve-uri/-/resolve-uri-3.1.2.tgz", "resolved": "https://registry.npmjs.org/@jridgewell/resolve-uri/-/resolve-uri-3.1.2.tgz",
"integrity": "sha512-bRISgCIjP20/tbWSPWMEi54QVPRZExkuD9lJL+UIxUKtwVJA8wW1Trb1jMs1RFXo1CBTNZ/5hpC9QvmKWdopKw==", "integrity": "sha512-bRISgCIjP20/tbWSPWMEi54QVPRZExkuD9lJL+UIxUKtwVJA8wW1Trb1jMs1RFXo1CBTNZ/5hpC9QvmKWdopKw==",
"dev": true,
"license": "MIT", "license": "MIT",
"engines": { "engines": {
"node": ">=6.0.0" "node": ">=6.0.0"
@@ -808,20 +809,27 @@
"version": "1.5.5", "version": "1.5.5",
"resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.5.5.tgz", "resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.5.5.tgz",
"integrity": "sha512-cYQ9310grqxueWbl+WuIUIaiUaDcj7WOq5fVhEljNVgRfOUhY9fy2zTvfoqWsnebh8Sl70VScFbICvJnLKB0Og==", "integrity": "sha512-cYQ9310grqxueWbl+WuIUIaiUaDcj7WOq5fVhEljNVgRfOUhY9fy2zTvfoqWsnebh8Sl70VScFbICvJnLKB0Og==",
"dev": true,
"license": "MIT" "license": "MIT"
}, },
"node_modules/@jridgewell/trace-mapping": { "node_modules/@jridgewell/trace-mapping": {
"version": "0.3.31", "version": "0.3.31",
"resolved": "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.31.tgz", "resolved": "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.31.tgz",
"integrity": "sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw==", "integrity": "sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw==",
"dev": true,
"license": "MIT", "license": "MIT",
"dependencies": { "dependencies": {
"@jridgewell/resolve-uri": "^3.1.0", "@jridgewell/resolve-uri": "^3.1.0",
"@jridgewell/sourcemap-codec": "^1.4.14" "@jridgewell/sourcemap-codec": "^1.4.14"
} }
}, },
"node_modules/@lucide/svelte": {
"version": "1.28.0",
"resolved": "https://registry.npmjs.org/@lucide/svelte/-/svelte-1.28.0.tgz",
"integrity": "sha512-C1Ge84KW2z4q44/WDIEo/2KC2jby5u6mSlta7q+p6g7u0ld8sC/w1fMBiSswF+4bxAl9jlzzaVTpp79qqkiy5g==",
"license": "ISC",
"peerDependencies": {
"svelte": "^5"
}
},
"node_modules/@manypkg/find-root": { "node_modules/@manypkg/find-root": {
"version": "1.1.0", "version": "1.1.0",
"resolved": "https://registry.npmjs.org/@manypkg/find-root/-/find-root-1.1.0.tgz", "resolved": "https://registry.npmjs.org/@manypkg/find-root/-/find-root-1.1.0.tgz",
@@ -1371,7 +1379,6 @@
"version": "1.0.11", "version": "1.0.11",
"resolved": "https://registry.npmjs.org/@sveltejs/acorn-typescript/-/acorn-typescript-1.0.11.tgz", "resolved": "https://registry.npmjs.org/@sveltejs/acorn-typescript/-/acorn-typescript-1.0.11.tgz",
"integrity": "sha512-LFuZUkjJ9iF7JZye/aG5XM0SFcQ5VyL0oVX4WJ9dc0Va3R3s0OauX1BESVCb+YN/ol8TAfqGDDAQsTG627Y5kw==", "integrity": "sha512-LFuZUkjJ9iF7JZye/aG5XM0SFcQ5VyL0oVX4WJ9dc0Va3R3s0OauX1BESVCb+YN/ol8TAfqGDDAQsTG627Y5kw==",
"dev": true,
"license": "MIT", "license": "MIT",
"peerDependencies": { "peerDependencies": {
"acorn": "^8.9.0" "acorn": "^8.9.0"
@@ -1453,21 +1460,18 @@
"version": "1.0.9", "version": "1.0.9",
"resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.9.tgz", "resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.9.tgz",
"integrity": "sha512-GhdPgy1el4/ImP05X05Uw4cw2/M93BCUmnEvWZNStlCzEKME4Fkk+YpoA5OiHNQmoS7Cafb8Xa3Pya8m1Qrzeg==", "integrity": "sha512-GhdPgy1el4/ImP05X05Uw4cw2/M93BCUmnEvWZNStlCzEKME4Fkk+YpoA5OiHNQmoS7Cafb8Xa3Pya8m1Qrzeg==",
"dev": true,
"license": "MIT" "license": "MIT"
}, },
"node_modules/@types/trusted-types": { "node_modules/@types/trusted-types": {
"version": "2.0.7", "version": "2.0.7",
"resolved": "https://registry.npmjs.org/@types/trusted-types/-/trusted-types-2.0.7.tgz", "resolved": "https://registry.npmjs.org/@types/trusted-types/-/trusted-types-2.0.7.tgz",
"integrity": "sha512-ScaPdn1dQczgbl0QFTeTOmVHFULt394XJgOQNoyVhZ6r2vLnMLJfBPd53SB52T/3G36VI1/g2MZaX0cwDuXsfw==", "integrity": "sha512-ScaPdn1dQczgbl0QFTeTOmVHFULt394XJgOQNoyVhZ6r2vLnMLJfBPd53SB52T/3G36VI1/g2MZaX0cwDuXsfw==",
"dev": true,
"license": "MIT" "license": "MIT"
}, },
"node_modules/acorn": { "node_modules/acorn": {
"version": "8.18.0", "version": "8.18.0",
"resolved": "https://registry.npmjs.org/acorn/-/acorn-8.18.0.tgz", "resolved": "https://registry.npmjs.org/acorn/-/acorn-8.18.0.tgz",
"integrity": "sha512-lGq+9yr1/GuAWaVYIHRjvvySG5/4VfKIvC8EWxStPdcDh/Ka7FG3twP6v4d5BkravUilhIAsG4Qj83t02LWUPQ==", "integrity": "sha512-lGq+9yr1/GuAWaVYIHRjvvySG5/4VfKIvC8EWxStPdcDh/Ka7FG3twP6v4d5BkravUilhIAsG4Qj83t02LWUPQ==",
"dev": true,
"license": "MIT", "license": "MIT",
"bin": { "bin": {
"acorn": "bin/acorn" "acorn": "bin/acorn"
@@ -1507,7 +1511,6 @@
"version": "5.3.1", "version": "5.3.1",
"resolved": "https://registry.npmjs.org/aria-query/-/aria-query-5.3.1.tgz", "resolved": "https://registry.npmjs.org/aria-query/-/aria-query-5.3.1.tgz",
"integrity": "sha512-Z/ZeOgVl7bcSYZ/u/rh0fOpvEpq//LZmdbkXyc7syVzjPAhfOa9ebsdTSjEBDU4vs5nC98Kfduj1uFo0qyET3g==", "integrity": "sha512-Z/ZeOgVl7bcSYZ/u/rh0fOpvEpq//LZmdbkXyc7syVzjPAhfOa9ebsdTSjEBDU4vs5nC98Kfduj1uFo0qyET3g==",
"dev": true,
"license": "Apache-2.0", "license": "Apache-2.0",
"engines": { "engines": {
"node": ">= 0.4" "node": ">= 0.4"
@@ -1527,7 +1530,6 @@
"version": "4.1.0", "version": "4.1.0",
"resolved": "https://registry.npmjs.org/axobject-query/-/axobject-query-4.1.0.tgz", "resolved": "https://registry.npmjs.org/axobject-query/-/axobject-query-4.1.0.tgz",
"integrity": "sha512-qIj0G9wZbMGNLjLmg1PT6v2mE9AH2zlnADJD/2tC6E00hgmhUOfEB6greHPAfLRSufHqROIUTkw6E+M3lH0PTQ==", "integrity": "sha512-qIj0G9wZbMGNLjLmg1PT6v2mE9AH2zlnADJD/2tC6E00hgmhUOfEB6greHPAfLRSufHqROIUTkw6E+M3lH0PTQ==",
"dev": true,
"license": "Apache-2.0", "license": "Apache-2.0",
"engines": { "engines": {
"node": ">= 0.4" "node": ">= 0.4"
@@ -1586,7 +1588,6 @@
"version": "2.1.1", "version": "2.1.1",
"resolved": "https://registry.npmjs.org/clsx/-/clsx-2.1.1.tgz", "resolved": "https://registry.npmjs.org/clsx/-/clsx-2.1.1.tgz",
"integrity": "sha512-eYm0QWBtUrBWZWG0d386OGAw16Z995PiOVo2B7bjWSbHedGl5e0ZWaq65kOGgUSNesEIDkB9ISbTg/JK9dhCZA==", "integrity": "sha512-eYm0QWBtUrBWZWG0d386OGAw16Z995PiOVo2B7bjWSbHedGl5e0ZWaq65kOGgUSNesEIDkB9ISbTg/JK9dhCZA==",
"dev": true,
"license": "MIT", "license": "MIT",
"engines": { "engines": {
"node": ">=6" "node": ">=6"
@@ -1638,7 +1639,6 @@
"version": "5.9.0", "version": "5.9.0",
"resolved": "https://registry.npmjs.org/devalue/-/devalue-5.9.0.tgz", "resolved": "https://registry.npmjs.org/devalue/-/devalue-5.9.0.tgz",
"integrity": "sha512-RWrqdArjvPbsATEhOPUo6Wndc/iWnkWKlhIrdlF3zMMYo/c3CVtoaVAyLtWxz5h8nSlkHzxnzV2uLydPXmtF+A==", "integrity": "sha512-RWrqdArjvPbsATEhOPUo6Wndc/iWnkWKlhIrdlF3zMMYo/c3CVtoaVAyLtWxz5h8nSlkHzxnzV2uLydPXmtF+A==",
"dev": true,
"license": "MIT" "license": "MIT"
}, },
"node_modules/dir-glob": { "node_modules/dir-glob": {
@@ -1715,7 +1715,6 @@
"version": "1.2.2", "version": "1.2.2",
"resolved": "https://registry.npmjs.org/esm-env/-/esm-env-1.2.2.tgz", "resolved": "https://registry.npmjs.org/esm-env/-/esm-env-1.2.2.tgz",
"integrity": "sha512-Epxrv+Nr/CaL4ZcFGPJIYLWFom+YeV1DqMLHJoEd9SYRxNbaFruBwfEX/kkHUJf55j2+TUbmDcmuilbP1TmXHA==", "integrity": "sha512-Epxrv+Nr/CaL4ZcFGPJIYLWFom+YeV1DqMLHJoEd9SYRxNbaFruBwfEX/kkHUJf55j2+TUbmDcmuilbP1TmXHA==",
"dev": true,
"license": "MIT" "license": "MIT"
}, },
"node_modules/esprima": { "node_modules/esprima": {
@@ -1736,7 +1735,6 @@
"version": "2.3.0", "version": "2.3.0",
"resolved": "https://registry.npmjs.org/esrap/-/esrap-2.3.0.tgz", "resolved": "https://registry.npmjs.org/esrap/-/esrap-2.3.0.tgz",
"integrity": "sha512-GQ/7RN8uOtEfNpzZzBMTzW9JBcX42oaSVtPzdF+6cEL8pqIL094iUpr9jzYGn4O4P/1S60dJ6izyT8F4LYARng==", "integrity": "sha512-GQ/7RN8uOtEfNpzZzBMTzW9JBcX42oaSVtPzdF+6cEL8pqIL094iUpr9jzYGn4O4P/1S60dJ6izyT8F4LYARng==",
"dev": true,
"license": "MIT", "license": "MIT",
"dependencies": { "dependencies": {
"@jridgewell/sourcemap-codec": "^1.4.15" "@jridgewell/sourcemap-codec": "^1.4.15"
@@ -1975,7 +1973,6 @@
"version": "3.0.3", "version": "3.0.3",
"resolved": "https://registry.npmjs.org/is-reference/-/is-reference-3.0.3.tgz", "resolved": "https://registry.npmjs.org/is-reference/-/is-reference-3.0.3.tgz",
"integrity": "sha512-ixkJoqQvAP88E6wLydLGGqCJsrFUnqoH6HnaczB8XmDH1oaWU+xxdptvikTgaEhtZ53Ky6YXiBuUI2WXLMCwjw==", "integrity": "sha512-ixkJoqQvAP88E6wLydLGGqCJsrFUnqoH6HnaczB8XmDH1oaWU+xxdptvikTgaEhtZ53Ky6YXiBuUI2WXLMCwjw==",
"dev": true,
"license": "MIT", "license": "MIT",
"dependencies": { "dependencies": {
"@types/estree": "^1.0.6" "@types/estree": "^1.0.6"
@@ -2058,7 +2055,6 @@
"version": "3.0.0", "version": "3.0.0",
"resolved": "https://registry.npmjs.org/locate-character/-/locate-character-3.0.0.tgz", "resolved": "https://registry.npmjs.org/locate-character/-/locate-character-3.0.0.tgz",
"integrity": "sha512-SW13ws7BjaeJ6p7Q6CO2nchbYEc3X3J6WrmTTDto7yMPqVSZTUyY5Tjbid+Ab8gLnATtygYtiDIJGQRRn2ZOiA==", "integrity": "sha512-SW13ws7BjaeJ6p7Q6CO2nchbYEc3X3J6WrmTTDto7yMPqVSZTUyY5Tjbid+Ab8gLnATtygYtiDIJGQRRn2ZOiA==",
"dev": true,
"license": "MIT" "license": "MIT"
}, },
"node_modules/locate-path": { "node_modules/locate-path": {
@@ -2085,7 +2081,6 @@
"version": "0.30.21", "version": "0.30.21",
"resolved": "https://registry.npmjs.org/magic-string/-/magic-string-0.30.21.tgz", "resolved": "https://registry.npmjs.org/magic-string/-/magic-string-0.30.21.tgz",
"integrity": "sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ==", "integrity": "sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ==",
"dev": true,
"license": "MIT", "license": "MIT",
"dependencies": { "dependencies": {
"@jridgewell/sourcemap-codec": "^1.5.5" "@jridgewell/sourcemap-codec": "^1.5.5"
@@ -2821,7 +2816,6 @@
"version": "5.56.8", "version": "5.56.8",
"resolved": "https://registry.npmjs.org/svelte/-/svelte-5.56.8.tgz", "resolved": "https://registry.npmjs.org/svelte/-/svelte-5.56.8.tgz",
"integrity": "sha512-PY8LOw7xP6c8IOiVqdo0sbbZVYhXRSfklOQLAUyGBKqjTX0wx/z4l/9J+PmBpmlLnxzEb1NqltxQ5/wZme/Cmg==", "integrity": "sha512-PY8LOw7xP6c8IOiVqdo0sbbZVYhXRSfklOQLAUyGBKqjTX0wx/z4l/9J+PmBpmlLnxzEb1NqltxQ5/wZme/Cmg==",
"dev": true,
"license": "MIT", "license": "MIT",
"dependencies": { "dependencies": {
"@jridgewell/remapping": "^2.3.4", "@jridgewell/remapping": "^2.3.4",
@@ -3108,17 +3102,20 @@
"version": "1.1.4", "version": "1.1.4",
"resolved": "https://registry.npmjs.org/zimmerframe/-/zimmerframe-1.1.4.tgz", "resolved": "https://registry.npmjs.org/zimmerframe/-/zimmerframe-1.1.4.tgz",
"integrity": "sha512-B58NGBEoc8Y9MWWCQGl/gq9xBCe4IiKM0a2x7GZdQKOW5Exr8S1W24J6OgM1njK8xCRGvAJIL/MxXHf6SkmQKQ==", "integrity": "sha512-B58NGBEoc8Y9MWWCQGl/gq9xBCe4IiKM0a2x7GZdQKOW5Exr8S1W24J6OgM1njK8xCRGvAJIL/MxXHf6SkmQKQ==",
"dev": true,
"license": "MIT" "license": "MIT"
}, },
"packages/design-tokens": { "packages/design-tokens": {
"name": "@gabriel20xx/design-tokens", "name": "@gabriel20xx/design-tokens",
"version": "0.1.0", "version": "0.1.1",
"license": "MIT" "license": "MIT"
}, },
"packages/legacy-assets": {
"name": "@gabriel20xx/legacy-assets",
"version": "3.0.0"
},
"packages/node-backend": { "packages/node-backend": {
"name": "@gabriel20xx/node-backend", "name": "@gabriel20xx/node-backend",
"version": "0.1.0", "version": "0.1.1",
"license": "MIT", "license": "MIT",
"dependencies": { "dependencies": {
"pg": "^8.17.2" "pg": "^8.17.2"
@@ -3129,10 +3126,11 @@
}, },
"packages/web-ui": { "packages/web-ui": {
"name": "@gabriel20xx/web-ui", "name": "@gabriel20xx/web-ui",
"version": "0.1.0", "version": "0.1.1",
"license": "MIT", "license": "MIT",
"dependencies": { "dependencies": {
"@gabriel20xx/design-tokens": "0.1.0" "@gabriel20xx/design-tokens": "0.1.1",
"@lucide/svelte": "1.28.0"
}, },
"devDependencies": { "devDependencies": {
"@sveltejs/package": "^2.5.0", "@sveltejs/package": "^2.5.0",
+15 -2
View File
@@ -1,6 +1,6 @@
{ {
"name": "@gabriel20xx/shared-code", "name": "@gabriel20xx/shared-code",
"version": "0.1.0", "version": "0.1.1",
"description": "Shared UI and backend packages for Gabriel20xx projects.", "description": "Shared UI and backend packages for Gabriel20xx projects.",
"license": "MIT", "license": "MIT",
"repository": { "repository": {
@@ -45,7 +45,20 @@
"prepare": "npm run build && node scripts/build-root-styles.mjs", "prepare": "npm run build && node scripts/build-root-styles.mjs",
"changeset": "changeset", "changeset": "changeset",
"version-packages": "changeset version", "version-packages": "changeset version",
"release": "npm run build && npm run test:node-backend && changeset publish" "release": "npm run build && npm run test:node-backend && changeset publish",
"media:audit:html-js": "node scripts/media/audit-html-js.mjs",
"media:audit:layout": "node scripts/media/audit-inline-layout.mjs",
"media:audit:layout:strict": "node scripts/media/audit-inline-layout.mjs --strict",
"media:clean:test-artifacts": "node scripts/media/clean-test-artifacts.mjs",
"media:enforce:css-design-system": "node scripts/media/enforce-design-system-css.mjs",
"media:enforce:js-mapping": "node scripts/media/enforce-js-mapping.mjs",
"media:enforce:no-skipped-tests": "node scripts/media/enforce-no-skipped-tests.mjs",
"media:lint:all": "node scripts/media/lint-all.mjs",
"media:lint:all:json": "node scripts/media/lint-all-json.mjs",
"media:test:list-skipped": "node scripts/media/list-skipped-tests.mjs",
"media:test:timings": "node scripts/media/report-test-timings.mjs",
"media:vitest:inspect-exports": "node scripts/media/inspect-vitest-exports.mjs",
"media:deps:upgrade": "node scripts/media/upgrade-deps.mjs"
}, },
"dependencies": { "dependencies": {
"pg": "^8.17.2" "pg": "^8.17.2"
+1 -1
View File
@@ -1,6 +1,6 @@
{ {
"name": "@gabriel20xx/design-tokens", "name": "@gabriel20xx/design-tokens",
"version": "0.1.0", "version": "0.1.1",
"description": "Shared visual tokens for Gabriel20xx web projects.", "description": "Shared visual tokens for Gabriel20xx web projects.",
"license": "MIT", "license": "MIT",
"files": [ "files": [
+18
View File
@@ -0,0 +1,18 @@
# `com.gabriel20xx.shared:java-backend`
Shared account-management, TOTP, admin reset-code, and AuthGuard client primitives for Java services:
- `Roles` - shared account-management roles (`superadmin`/`admin`/`user`) and permission checks;
- `Totp` - RFC 6238 TOTP secret generation, provisioning URIs, and verification;
- `ResetManager` - a short-lived, one-time admin reset-code primitive printed to the server console;
- `AuthClient` - a client for a centralized AuthGuard instance's `GET /api/session/validate`, for services that want one shared identity instead of their own local user table. Mirrors `shared/backend/authclient` (Go) and `shared/packages/node-backend/src/authclient.js` (Node) - keep the three in sync if any of them changes shape. Additive: no project is wired up to use it just because this class exists.
## How this package is actually consumed
Unlike its `node-backend`/`python-backend` siblings, this package is not published and installed as a dependency. Its real, already-identified consumer - [MegaBasterd](../../../../Forks/MegaBasterd) - instead adds this package's `src/main/java` as an extra source directory of its *own* Maven build, via the `build-helper-maven-plugin` "add-shared-java-auth" execution in `MegaBasterd/pom.xml`, and compiles these `.java` files straight into its own jar. That pom pins `<maven.compiler.source>`/`<target>` to `1.8`, which is why every class in this package targets Java 8 and none of them (including `AuthClient`) take on a dependency beyond the JDK - both would break that real build.
This package's own `pom.xml` exists only so it can be built and tested in isolation during development; it plays no part in how MegaBasterd (or any future consumer that adopts the same source-inclusion approach) actually builds.
## Testing
Run `mvn test` from this package.
+58
View File
@@ -0,0 +1,58 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.gabriel20xx.shared</groupId>
<artifactId>java-backend</artifactId>
<version>0.1.0</version>
<packaging>jar</packaging>
<name>java-backend</name>
<description>Shared account-management, TOTP, admin reset-code, and AuthGuard client primitives for Java services.</description>
<!--
This pom.xml exists only so this package can be built and tested on
its own (mirroring @gabriel20xx/node-backend's package.json and
python-backend's pyproject.toml). It is not how the real,
already-identified consumer of this package - MegaBasterd - uses it:
MegaBasterd/pom.xml instead adds src/main/java as an extra source
directory of its own build via build-helper-maven-plugin, compiling
this source straight into its jar with no dependency on this
artifact. That is also why maven.compiler.source/target below is
pinned to 1.8 - it must match MegaBasterd/pom.xml's
<maven.compiler.source>/<target>, since both poms compile the exact
same .java files.
-->
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<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>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>3.2.5</version>
</plugin>
</plugins>
</build>
</project>
@@ -0,0 +1,838 @@
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;
import java.util.regex.Pattern;
/**
* AuthClient is how any Java service in this workspace adopts a centralized
* AuthGuard instance instead of embedding its own local user table.
*
* <p>A service that switches to AuthGuard trades "its own local user table"
* 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.
*
* <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 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.
*
* <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 {
/** Matches the Go/Node default; override via the constructor if a deployment renamed the cookie. */
public static final String DEFAULT_COOKIE_NAME = "auth_session";
public static final int DEFAULT_TIMEOUT_MILLIS = 5000;
private static final Pattern VALID_PATTERN = Pattern.compile("\"valid\"\\s*:\\s*(true|false)");
private static final Pattern USER_ID_PATTERN = Pattern.compile("\"user_id\"\\s*:\\s*(-?\\d+)");
private static final Pattern USERNAME_PATTERN = Pattern.compile("\"username\"\\s*:\\s*\"((?:[^\"\\\\]|\\\\.)*)\"");
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;
public AuthClient(String baseUrl) {
this(baseUrl, DEFAULT_COOKIE_NAME, DEFAULT_TIMEOUT_MILLIS);
}
public AuthClient(String baseUrl, String cookieName) {
this(baseUrl, cookieName, DEFAULT_TIMEOUT_MILLIS);
}
/**
* @param baseUrl AuthGuard's base URL (e.g. {@code https://auth.example.com}), no trailing slash required.
* @param cookieName cookie {@link #extractToken} falls back to when there is no Authorization header;
* blank/null defaults to {@link #DEFAULT_COOKIE_NAME}.
* @param timeoutMillis connect and read timeout used by {@link #validate(String)}.
*/
public AuthClient(String baseUrl, String cookieName, int timeoutMillis) {
this.baseUrl = normalizeBaseUrl(baseUrl);
this.cookieName = cookieName == null || cookieName.trim().isEmpty() ? DEFAULT_COOKIE_NAME : cookieName.trim();
this.timeoutMillis = timeoutMillis;
}
/**
* Calls AuthGuard's {@code GET /api/session/validate} with {@code token} as a Bearer credential and
* returns the resolved user. Throws {@link InvalidSessionException} when AuthGuard reports the session
* as not valid (including an empty/missing token, checked before any network call), and a plain
* {@link IOException} for any transport/decoding failure - that failure is intentionally left to
* propagate rather than being folded into {@link InvalidSessionException}, since "AuthGuard is down"
* is not the same fact as "this visitor is unauthenticated".
*/
public User validate(String token) throws IOException {
if (baseUrl.isEmpty()) {
throw new IllegalStateException("authclient: client has no base URL");
}
String trimmed = token == null ? "" : token.trim();
if (trimmed.isEmpty()) {
throw new InvalidSessionException();
}
HttpURLConnection connection = openConnection(trimmed);
int status;
String body;
try {
status = connection.getResponseCode();
InputStream stream = status >= 400 ? connection.getErrorStream() : connection.getInputStream();
body = readAll(stream);
} catch (IOException ex) {
throw new IOException("authclient: call AuthGuard: " + ex.getMessage(), ex);
} finally {
connection.disconnect();
}
RawPayload payload;
try {
payload = parsePayload(body);
} catch (RuntimeException ex) {
if (status == 401) {
throw new InvalidSessionException();
}
throw new IOException("authclient: decode AuthGuard response: " + ex.getMessage(), ex);
}
if (status != 200 || !payload.valid) {
throw new InvalidSessionException();
}
return new User(payload.userId, payload.username, payload.role);
}
/**
* Extracts the session token from an incoming request: an
* {@code Authorization: Bearer} header first, falling back to the cookie
* named by the constructor (default {@value #DEFAULT_COOKIE_NAME}).
* Mirrors {@code Client.tokenFromRequest} (Go) and
* {@code AuthClient#tokenFromRequest} (Node).
*
* <p>Deliberately framework-agnostic: rather than accepting a specific
* request type (a servlet {@code HttpServletRequest}, the JDK's
* {@code com.sun.net.httpserver.HttpExchange}, or anything else), this
* takes a header-lookup function and the raw {@code Cookie} header value
* so it works with whatever HTTP layer a given consumer already has,
* without this package taking on a dependency on any one of them. (The
* one Java consumer of this package identified so far, MegaBasterd's
* {@code WebServer}, happens to use the JDK-builtin
* {@code com.sun.net.httpserver}, but nothing here assumes that.)
*
* @param headerLookup case-sensitive header lookup, e.g.
* {@code exchange.getRequestHeaders()::getFirst}; may be null.
* @param cookieHeader the raw {@code Cookie} request header value, e.g. {@code "a=1; auth_session=tok"}; may be null.
* @return the extracted token, or {@code ""} if neither source has one.
*/
public String extractToken(Function<String, String> headerLookup, String cookieHeader) {
if (headerLookup != null) {
String header = headerLookup.apply("Authorization");
if (header != null && header.startsWith(BEARER_PREFIX)) {
String token = header.substring(BEARER_PREFIX.length()).trim();
if (!token.isEmpty()) {
return token;
}
}
}
return extractCookieToken(cookieHeader);
}
/**
* Validates the token extracted via {@link #extractToken}, and either returns what
* {@code onAuthenticated} produces for the resolved {@link User}, or falls back to
* {@code onUnauthorized} - failing closed on both an invalid session and a
* transport/decoding failure talking to AuthGuard, since a service outage should not be
* treated as "this visitor is authenticated". Mirrors {@code Client.Middleware} (Go) and
* {@code AuthClient#middleware} (Node); kept generic over the handler's return type and
* over how the request is shaped (see {@link #extractToken}) so it isn't tied to one web
* framework.
*/
public <T> T middleware(Function<String, String> headerLookup, String cookieHeader,
Handler<T> onAuthenticated, Supplier<T> onUnauthorized) throws Exception {
String token = extractToken(headerLookup, cookieHeader);
User user;
try {
user = validate(token);
} catch (InvalidSessionException | IOException ex) {
return onUnauthorized.get();
}
return onAuthenticated.handle(user);
}
/** A request handler gated on a resolved {@link User}; see {@link #middleware}. */
@FunctionalInterface
public interface Handler<T> {
T handle(User user) throws Exception;
}
/** The account AuthGuard resolved for a validated session. Immutable; mirrors Go's {@code User} / Node's plain object. */
public static final class User {
public final long id;
public final String username;
public final String role;
public User(long id, String username, String role) {
this.id = id;
this.username = username == null ? "" : username;
this.role = role == null ? "" : role;
}
}
// --- 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 "";
}
String prefix = cookieName + "=";
for (String part : cookieHeader.split(";")) {
String candidate = part.trim();
if (candidate.startsWith(prefix)) {
String value = candidate.substring(prefix.length());
try {
return URLDecoder.decode(value, StandardCharsets.UTF_8.name());
} catch (UnsupportedEncodingException ex) {
return value;
}
}
}
return "";
}
private HttpURLConnection openConnection(String token) throws IOException {
URL url = new URL(baseUrl + "/api/session/validate");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setRequestProperty("Authorization", BEARER_PREFIX + token);
connection.setConnectTimeout(timeoutMillis);
connection.setReadTimeout(timeoutMillis);
return connection;
}
/**
* Trims {@code baseUrl}, strips a trailing slash, and - if the result has
* no scheme - infers one from the host: a loopback, RFC1918/RFC4193
* private, or link-local address, or a {@code ".local"} name, defaults to
* {@code http://} (a plain-HTTP AuthGuard on a local network is the
* common case for those); anything else, including a plain hostname like
* {@code "auth.example.com"}, defaults to {@code https://}. An explicit
* {@code http://} or {@code https://} is always left as-is, overriding
* the inference.
*/
private static String normalizeBaseUrl(String baseUrl) {
String trimmed = baseUrl == null ? "" : baseUrl.trim();
while (trimmed.endsWith("/")) {
trimmed = trimmed.substring(0, trimmed.length() - 1);
}
if (trimmed.isEmpty()) {
return trimmed;
}
String lower = trimmed.toLowerCase(Locale.ROOT);
if (lower.startsWith("http://") || lower.startsWith("https://")) {
return trimmed;
}
return (isPrivateHost(trimmed) ? "http://" : "https://") + trimmed;
}
private static final Pattern IPV4_PATTERN = Pattern.compile("^(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})$");
private static final Pattern IPV6_UNIQUE_LOCAL_PATTERN = Pattern.compile("^f[cd][0-9a-f]{2}:.*$");
/**
* Reports whether {@code hostPort} (a bare {@code "host"} or
* {@code "host:port"}, no scheme) names a loopback, RFC1918/RFC4193
* private, or link-local address, or a {@code ".local"} mDNS name - the
* kind of host a plain-HTTP AuthGuard is typically reachable at on a
* local network, as opposed to a public hostname expected to terminate
* TLS itself. Never performs DNS resolution: only literal IPs and the
* {@code "localhost"}/{@code ".local"} names are recognized, so a real
* public hostname that merely happens to resolve to a private address
* still defaults to https.
*/
private static boolean isPrivateHost(String hostPort) {
String host = hostPort;
if (host.startsWith("[")) {
int end = host.indexOf(']');
if (end != -1) {
host = host.substring(1, end);
}
} else {
int idx = host.indexOf(':');
if (idx != -1 && idx == host.lastIndexOf(':')) {
String portPart = host.substring(idx + 1);
if (!portPart.isEmpty() && portPart.chars().allMatch(Character::isDigit)) {
host = host.substring(0, idx);
}
}
}
String lower = host.toLowerCase(Locale.ROOT);
if (lower.equals("localhost") || lower.endsWith(".local")) {
return true;
}
Matcher ipv4Matcher = IPV4_PATTERN.matcher(lower);
if (ipv4Matcher.matches()) {
int a = Integer.parseInt(ipv4Matcher.group(1));
int b = Integer.parseInt(ipv4Matcher.group(2));
return a == 127 || a == 10 || (a == 172 && b >= 16 && b <= 31) || (a == 192 && b == 168) || (a == 169 && b == 254);
}
if (lower.equals("::1")) {
return true;
}
return lower.startsWith("fe80:") || IPV6_UNIQUE_LOCAL_PATTERN.matcher(lower).matches();
}
private static String readAll(InputStream in) throws IOException {
if (in == null) {
return "";
}
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
try {
byte[] chunk = new byte[4096];
int read;
while ((read = in.read(chunk)) != -1) {
buffer.write(chunk, 0, read);
}
} finally {
in.close();
}
return buffer.toString(StandardCharsets.UTF_8.name());
}
/** Defensively hand-parses AuthGuard's small, fixed response shape - see the class javadoc for why. */
private static RawPayload parsePayload(String body) {
if (body == null || body.isEmpty()) {
throw new IllegalArgumentException("empty AuthGuard response body");
}
Matcher validMatcher = VALID_PATTERN.matcher(body);
if (!validMatcher.find()) {
throw new IllegalArgumentException("missing \"valid\" field in AuthGuard response");
}
boolean valid = Boolean.parseBoolean(validMatcher.group(1));
long userId = 0L;
Matcher userIdMatcher = USER_ID_PATTERN.matcher(body);
if (userIdMatcher.find()) {
userId = Long.parseLong(userIdMatcher.group(1));
}
return new RawPayload(valid, userId, extractString(USERNAME_PATTERN, body), extractString(ROLE_PATTERN, body));
}
private static String extractString(Pattern pattern, String body) {
Matcher matcher = pattern.matcher(body);
return matcher.find() ? unescapeJson(matcher.group(1)) : "";
}
private static String unescapeJson(String raw) {
StringBuilder result = new StringBuilder(raw.length());
for (int index = 0; index < raw.length(); index++) {
char current = raw.charAt(index);
if (current != '\\' || index + 1 >= raw.length()) {
result.append(current);
continue;
}
char next = raw.charAt(++index);
switch (next) {
case '"': result.append('"'); break;
case '\\': result.append('\\'); break;
case '/': result.append('/'); break;
case 'n': result.append('\n'); break;
case 't': result.append('\t'); break;
case 'r': result.append('\r'); break;
case 'b': result.append('\b'); break;
case 'f': result.append('\f'); break;
case 'u':
if (index + 4 < raw.length()) {
result.append((char) Integer.parseInt(raw.substring(index + 1, index + 5), 16));
index += 4;
}
break;
default: result.append(next);
}
}
return result.toString();
}
private static final class RawPayload {
private final boolean valid;
private final long userId;
private final String username;
private final String role;
private RawPayload(boolean valid, long userId, String username, String role) {
this.valid = valid;
this.userId = userId;
this.username = username;
this.role = role;
}
}
}
@@ -0,0 +1,38 @@
package com.gabriel20xx.shared.auth;
/**
* Thrown by {@link AuthClient#validate(String)} when AuthGuard reports the
* token/cookie as not currently valid (expired, unknown, or missing) - as
* opposed to a transport/decoding failure talking to AuthGuard, which
* propagates as a plain {@link java.io.IOException}. Mirrors
* {@code ErrInvalidSession} (Go, shared/backend/authclient/client.go) and
* {@code InvalidSessionError} (Node, shared/packages/node-backend/src/authclient.js) -
* keep the three in sync if any of them changes shape.
*
* <p>This package (java-backend) has no prior custom-exception precedent of
* its own - {@code ResetManager}/{@code Roles}/{@code Totp} throw nothing
* project-specific. Unchecked was chosen to mirror the Node equivalent and
* the idiom already used by this class's real, already-identified consumer
* (MegaBasterd's {@code WebAuthStore}, which signals authentication failure
* with the unchecked {@link SecurityException}) - it keeps
* {@code validate(String)} usable without forcing every future caller,
* across however many independent projects adopt this package, to declare
* or catch a checked exception just to say "respond 401".
*/
public final class InvalidSessionException extends RuntimeException {
private static final long serialVersionUID = 1L;
private static final String DEFAULT_MESSAGE = "authclient: invalid or missing session";
public InvalidSessionException() {
super(DEFAULT_MESSAGE);
}
public InvalidSessionException(String message) {
super(message);
}
public InvalidSessionException(String message, Throwable cause) {
super(message, cause);
}
}
@@ -0,0 +1,264 @@
package com.gabriel20xx.shared.auth;
import com.sun.net.httpserver.HttpServer;
import java.io.IOException;
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,
* translated to Java idioms. Since AuthClient does not take an injectable
* HTTP client (see AuthClient's class javadoc for why it uses plain
* java.net.HttpURLConnection), AuthGuard is faked with a real local
* com.sun.net.httpserver.HttpServer bound to an ephemeral port rather than
* a mock/DI seam.
*/
class AuthClientTest {
private HttpServer server;
@AfterEach
void stopServer() {
if (server != null) {
server.stop(0);
server = null;
}
}
@Test
void constructorAssumesHttpsForABarePublicHost() {
assertEquals("https://auth.example.com", new AuthClient("auth.example.com").baseUrlForTest());
assertEquals("https://auth.example.com:8080", new AuthClient("auth.example.com:8080").baseUrlForTest());
}
@Test
void constructorAssumesHttpForABarePrivateHost() {
assertEquals("http://192.168.1.50:8080", new AuthClient("192.168.1.50:8080").baseUrlForTest());
assertEquals("http://10.1.2.3:8080", new AuthClient("10.1.2.3:8080").baseUrlForTest());
assertEquals("http://172.20.0.5:8080", new AuthClient("172.20.0.5:8080").baseUrlForTest());
assertEquals("http://127.0.0.1:8080", new AuthClient("127.0.0.1:8080").baseUrlForTest());
assertEquals("http://169.254.1.1:8080", new AuthClient("169.254.1.1:8080").baseUrlForTest());
assertEquals("http://localhost:8080", new AuthClient("localhost:8080").baseUrlForTest());
assertEquals("http://authguard.local:8080", new AuthClient("authguard.local:8080").baseUrlForTest());
assertEquals("http://[::1]:8080", new AuthClient("[::1]:8080").baseUrlForTest());
assertEquals("http://[fd00::1]:8080", new AuthClient("[fd00::1]:8080").baseUrlForTest());
}
@Test
void constructorAssumesHttpsFor172RangeOutsidePrivateBlock() {
assertEquals("https://172.32.0.5:8080", new AuthClient("172.32.0.5: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());
assertEquals("https://192.168.1.50:8080", new AuthClient("https://192.168.1.50:8080").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\"}");
AuthClient client = new AuthClient(baseUrl(server));
AuthClient.User user = client.validate("good-token");
assertEquals(7L, user.id);
assertEquals("gabriel", user.username);
assertEquals("admin", user.role);
}
@Test
void validateThrowsInvalidSessionOnEmptyOrMissingTokenWithoutANetworkCall() {
// No server is started here. A base URL pointing at a port nothing
// listens on makes any real network attempt fail with an IOException,
// so InvalidSessionException below can only mean validate() returned
// before making a call.
AuthClient client = new AuthClient("http://127.0.0.1:1", AuthClient.DEFAULT_COOKIE_NAME, 200);
assertThrows(InvalidSessionException.class, () -> client.validate(""));
assertThrows(InvalidSessionException.class, () -> client.validate(" "));
assertThrows(InvalidSessionException.class, () -> client.validate(null));
}
@Test
void validateThrowsInvalidSessionWhenAuthGuardReportsInvalid() throws Exception {
server = fakeAuthGuard(401, "{\"valid\":false}");
AuthClient client = new AuthClient(baseUrl(server));
assertThrows(InvalidSessionException.class, () -> client.validate("bad-token"));
}
@Test
void extractTokenPrefersAuthorizationHeaderOverCookie() {
AuthClient client = new AuthClient("https://auth.example.com");
Map<String, String> headers = new HashMap<>();
headers.put("Authorization", "Bearer header-token");
String token = client.extractToken(headers::get, "auth_session=cookie-token; other=1");
assertEquals("header-token", token);
}
@Test
void extractTokenFallsBackToTheConfiguredCookieWhenNoHeaderIsPresent() {
AuthClient client = new AuthClient("https://auth.example.com");
String token = client.extractToken(name -> null, "other=1; auth_session=cookie-token");
assertEquals("cookie-token", token);
}
@Test
void extractTokenHonorsACustomCookieName() {
AuthClient client = new AuthClient("https://auth.example.com", "session_id");
String token = client.extractToken(name -> null, "auth_session=wrong; session_id=right");
assertEquals("right", token);
}
@Test
void middlewareFailsClosedAndDoesNotInvokeTheHandlerOnAnInvalidSession() throws Exception {
server = fakeAuthGuard(401, "{\"valid\":false}");
AuthClient client = new AuthClient(baseUrl(server));
Function<String, String> headerLookup = name -> "Authorization".equals(name) ? "Bearer bad-token" : null;
String result = client.middleware(headerLookup, null,
user -> {
throw new AssertionError("handler should not run on an invalid session");
},
() -> "unauthorized");
assertEquals("unauthorized", result);
}
@Test
void middlewareAttachesTheResolvedUserOnSuccess() throws Exception {
server = fakeAuthGuard(200, "{\"valid\":true,\"user_id\":1,\"username\":\"a\",\"role\":\"user\"}");
AuthClient client = new AuthClient(baseUrl(server));
Function<String, String> headerLookup = name -> "Authorization".equals(name) ? "Bearer good-token" : null;
AuthClient.User result = client.middleware(headerLookup, null,
user -> user,
() -> {
throw new AssertionError("unauthorized branch should not run on a valid session");
});
assertEquals(1L, result.id);
assertEquals("a", result.username);
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 -> {
byte[] bytes = body.getBytes(StandardCharsets.UTF_8);
exchange.getResponseHeaders().add("Content-Type", "application/json");
exchange.sendResponseHeaders(status, bytes.length);
try (OutputStream out = exchange.getResponseBody()) {
out.write(bytes);
}
});
httpServer.start();
return httpServer;
}
private static String baseUrl(HttpServer httpServer) {
return "http://127.0.0.1:" + httpServer.getAddress().getPort();
}
}
+15
View File
@@ -0,0 +1,15 @@
{
"extends": ["stylelint-config-standard"],
"ignoreFiles": ["public/css/index.css", "**/*.min.css"],
"rules": {
"at-rule-no-unknown": [true, { "ignoreAtRules": ["layer", "apply", "config"] }],
"selector-class-pattern": null,
"keyframes-name-pattern": null,
"custom-property-pattern": null,
"no-descending-specificity": null,
"import-notation": null,
"comment-empty-line-before": null,
"declaration-property-value-no-unknown": null,
"value-keyword-case": ["lower", { "camelCaseSvgKeywords": true }]
}
}
+16
View File
@@ -0,0 +1,16 @@
# @gabriel20xx/legacy-assets
This package now contains exactly one file: `public/css/index.css`, a static (pre-Tailwind-v4)
theme stylesheet. Its only remaining consumer is `Original/MediaDesktop`'s Electron renderer,
which still uses the old `--color-*` utility-class theme rather than the current `--sc-*`
design-token system in `packages/design-tokens`. It's a `file:` dependency there
(`scripts/copy-assets.mjs` copies `index.css` into `MediaDesktop/public/` at build time) - do not
delete this package without first migrating MediaDesktop off the old stylesheet.
Everything else that used to live here (the pre-SvelteKit `public/js/*` auth/layout/media
utilities, an orphaned `MediaDesktop/assets/icon.png` copy, and the broken monorepo-era
`build:theme` script) was removed: nothing else in the workspace referenced any of it.
Originally `MediaCollection/MediaShared`, moved here to centralize shared components. Both the
`MediaCollection` and `MediaShared` umbrella names are retired - everything here is just part of
`shared` now, workspace-wide.
+13
View File
@@ -0,0 +1,13 @@
{
"name": "@gabriel20xx/legacy-assets",
"version": "3.0.0",
"private": true,
"description": "Legacy pre-SvelteKit theme CSS, kept only for MediaDesktop's Electron renderer (file: dependency)",
"scripts": {
"lint:css": "stylelint \"public/**/*.css\""
},
"exports": {
"./index.css": "./public/css/index.css"
},
"files": ["public/**"]
}
File diff suppressed because it is too large. Load diff
+1 -1
View File
@@ -17,4 +17,4 @@ legacy package as a compatibility layer until every consumer has moved.
Pass a service-specific `tableName` to `runMigrations` when multiple services Pass a service-specific `tableName` to `runMigrations` when multiple services
share one PostgreSQL database, so their migration histories cannot collide. share one PostgreSQL database, so their migration histories cannot collide.
Run `npm test` from this package or `npm run test --workspace=@gabriel20xx/node-backend` from `SharedCode`. Run `npm test` from this package or `npm run test --workspace=@gabriel20xx/node-backend` from `shared`.
+1 -1
View File
@@ -1,6 +1,6 @@
{ {
"name": "@gabriel20xx/node-backend", "name": "@gabriel20xx/node-backend",
"version": "0.1.0", "version": "0.1.1",
"description": "Shared PostgreSQL, configuration, migration, and authentication primitives for Node.js services.", "description": "Shared PostgreSQL, configuration, migration, and authentication primitives for Node.js services.",
"license": "MIT", "license": "MIT",
"type": "module", "type": "module",
+459
View File
@@ -0,0 +1,459 @@
// authclient.js is how any Node service in this workspace adopts a
// centralized AuthGuard instance instead of embedding auth.js's AuthStore
// directly against its own private database.
//
// A service that switches to AuthGuard trades "its own local user table"
// for "HTTP calls to AuthGuard's API", gaining a single shared identity
// across every project that does the same. Mirrors shared/backend/authclient
// (the Go equivalent) and shared/packages/python-backend/src/shared_backend/authclient.py
// (the Python equivalent) - keep all three in sync if any changes shape.
//
// Two kinds of consumer, two parts of this module:
//
// - A service that only needs to gate requests behind "is this a valid
// AuthGuard session" uses `AuthClient.validate` / `tokenFromRequest` /
// `middleware()`, calling only GET /api/session/validate. This is the
// original, minimal surface of this module.
// - A service that runs its own login/register/admin-user-management
// screens proxied to AuthGuard (mirroring shared/backend/authclient's full
// method set - see e.g. Original/GameStream/backend/cmd/gamestreamd/auth.go
// for the reference Go implementation of this pattern) uses the additional
// methods below: register, login, logout, me, totpEnable/Verify/Disable,
// requestPasswordReset/confirmPasswordReset, list/create/update/delete
// ManagedUser(s), setupStatus.
const DEFAULT_COOKIE_NAME = 'auth_session';
const DEFAULT_TIMEOUT_MS = 5000;
export class InvalidSessionError extends Error {
constructor(message = 'authclient: invalid or missing session') {
super(message);
this.name = 'InvalidSessionError';
}
}
// APIError is raised when AuthGuard responds with a non-2xx status to one of
// the register/login/.../setupStatus methods below (not raised by
// validate(), which uses InvalidSessionError for its one specific non-2xx
// case). Mirrors Go's *authclient.APIError / Python's APIError - carries the
// status code and (when AuthGuard's JSON body decoded successfully) its
// {"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.
export class APIError extends Error {
constructor(statusCode, message, { totpRequired = false } = {}) {
super(`authclient: authguard responded ${statusCode}: ${message}`);
this.name = 'APIError';
this.statusCode = statusCode;
this.detailMessage = message;
// Mirrors AuthGuard's {"totp_required": true} flag on a 401 from
// POST /api/login 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.
this.totpRequired = totpRequired;
}
}
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") -
* the scheme is then inferred from the host: a loopback, RFC1918/RFC4193 private,
* or link-local address, or a ".local" name, defaults to "http://" (a plain-HTTP
* AuthGuard on a local network is the common case for those), anything else
* defaults to "https://". An explicit "http://" or "https://" is always left
* as-is, overriding the inference.
* @param {{cookieName?: string, timeoutMs?: number, fetchImpl?: typeof fetch}} [options]
*/
constructor(baseUrl, options = {}) {
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;
if (/^https?:\/\//i.test(trimmed)) return trimmed;
return AuthClient._isPrivateHost(trimmed) ? `http://${trimmed}` : `https://${trimmed}`;
}
/**
* Reports whether hostport (a bare "host" or "host:port", no scheme) names
* a loopback, RFC1918/RFC4193 private, or link-local address, or a
* ".local" mDNS name - the kind of host a plain-HTTP AuthGuard is
* typically reachable at on a local network, as opposed to a public
* hostname expected to terminate TLS itself. Never performs DNS
* resolution: only literal IPs and the "localhost"/".local" names are
* recognized, so a real public hostname that merely happens to resolve to
* a private address still defaults to https.
*/
static _isPrivateHost(hostport) {
let host = hostport;
if (host.startsWith('[')) {
const end = host.indexOf(']');
if (end !== -1) host = host.slice(1, end);
} else {
const parts = host.split(':');
if (parts.length === 2 && /^\d+$/.test(parts[1])) host = parts[0];
}
host = host.toLowerCase();
if (host === 'localhost' || host.endsWith('.local')) return true;
const ipv4 = host.match(/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/);
if (ipv4) {
const a = Number(ipv4[1]);
const b = Number(ipv4[2]);
return (
a === 127 ||
a === 10 ||
(a === 172 && b >= 16 && b <= 31) ||
(a === 192 && b === 168) ||
(a === 169 && b === 254)
);
}
if (host === '::1') return true;
if (/^fe80:/.test(host)) return true;
if (/^f[cd][0-9a-f]{2}:/.test(host)) return true;
return false;
}
// --- session validation (the original, minimal surface) -----------------
/**
* Calls AuthGuard's GET /api/session/validate with token as a Bearer
* credential and returns the resolved user. Throws InvalidSessionError
* when AuthGuard reports the session as not valid, and a plain Error for
* any transport/decoding failure.
* @param {string} token
* @returns {Promise<{id: number, username: string, role: string}>}
*/
async validate(token) {
if (!this.baseUrl) {
throw new Error('authclient: client has no base URL');
}
const trimmed = String(token ?? '').trim();
if (!trimmed) {
throw new InvalidSessionError();
}
const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), this.timeoutMs);
let response;
try {
response = await this.fetchImpl(`${this.baseUrl}/api/session/validate`, {
headers: { Authorization: `Bearer ${trimmed}` },
signal: controller.signal,
});
} catch (err) {
throw new Error(`authclient: call AuthGuard: ${err.message}`, { cause: err });
} finally {
clearTimeout(timer);
}
let payload;
try {
payload = await response.json();
} catch (err) {
if (response.status === 401) {
throw new InvalidSessionError();
}
throw new Error(`authclient: decode AuthGuard response: ${err.message}`, { cause: err });
}
if (response.status !== 200 || !payload?.valid) {
throw new InvalidSessionError();
}
return { id: payload.user_id, username: payload.username, role: payload.role };
}
/**
* Express middleware: extracts the session token from an incoming
* request (the configured cookie, falling back to an Authorization:
* Bearer header), validates it against AuthGuard, and either responds
* 401 or attaches the resolved user to req.authUser before calling next.
*/
middleware() {
return async (req, res, next) => {
const token = this.tokenFromRequest(req);
try {
req.authUser = await this.validate(token);
next();
} catch {
// Fail closed on both an invalid session and a transport/decoding
// failure talking to AuthGuard - a service outage should not be
// treated as "this visitor is authenticated".
res.status(401).json({ error: 'authentication required' });
}
};
}
tokenFromRequest(req) {
const header = req.headers?.authorization;
if (header?.startsWith('Bearer ')) {
const token = header.slice('Bearer '.length).trim();
if (token) return token;
}
const cookieHeader = req.headers?.cookie;
if (cookieHeader) {
const match = cookieHeader
.split(';')
.map(part => part.trim())
.find(part => part.startsWith(`${this.cookieName}=`));
if (match) return decodeURIComponent(match.slice(this.cookieName.length + 1));
}
return '';
}
// --- shared request/response plumbing for everything below --------------
/**
* Runs one JSON request/response round trip against AuthGuard. Returns
* the decoded JSON body (an empty object for a 2xx response with no
* body) and the raw Set-Cookie header value(s) the response carried.
* Throws APIError for a non-2xx response, a plain Error for a
* transport/decoding failure - mirrors Go's Client.call / Python's
* AuthClient._call exactly.
* @returns {Promise<{payload: any, cookies: string[]}>}
*/
async _call(method, path, { token = '', body } = {}) {
if (!this.baseUrl) {
throw new Error('authclient: client has no base URL');
}
const headers = {};
if (body !== undefined) headers['Content-Type'] = 'application/json';
if (token) headers.Authorization = `Bearer ${token}`;
const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), this.timeoutMs);
let response;
try {
response = await this.fetchImpl(`${this.baseUrl}${path}`, {
method,
headers,
body: body !== undefined ? JSON.stringify(body) : undefined,
signal: controller.signal,
});
} catch (err) {
throw new Error(`authclient: call AuthGuard: ${err.message}`, { cause: err });
} finally {
clearTimeout(timer);
}
// fetch's Headers.getSetCookie() (Node >= 18.14 / undici) returns every
// Set-Cookie header value separately, unlike .get('set-cookie') which
// would fold them into one comma-joined string and break parsing.
const cookies = typeof response.headers.getSetCookie === 'function'
? response.headers.getSetCookie()
: [];
let payload = {};
const text = await response.text();
if (text) {
try {
payload = JSON.parse(text);
} catch (err) {
if (!response.ok) {
throw new APIError(response.status, `request failed (${response.status})`);
}
throw new Error(`authclient: decode AuthGuard response: ${err.message}`, { cause: err });
}
}
if (!response.ok) {
const message = payload?.error || `request failed (${response.status})`;
throw new APIError(response.status, message, { totpRequired: Boolean(payload?.totp_required) });
}
return { payload, cookies };
}
static _publicUser(payload) {
const user = payload?.user ?? {};
return {
id: user.id,
username: user.username ?? '',
email: user.email ?? '',
role: user.role ?? '',
totpEnabled: Boolean(user.totp_enabled),
};
}
static _managedUser(user) {
return {
id: user?.id,
username: user?.username ?? '',
email: user?.email ?? '',
role: user?.role ?? '',
createdAt: user?.created_at ?? '',
};
}
// --- setup / registration -------------------------------------------------
/**
* Calls 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 returns 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.
* @returns {Promise<boolean>}
*/
async setupStatus() {
const { payload } = await this._call('GET', '/api/setup-status');
return Boolean(payload.setup_required);
}
/**
* Calls POST /api/register, creating a new AuthGuard account and
* starting a session for it.
* @returns {Promise<{user: object, cookies: string[]}>}
*/
async register(username, email, password) {
const { payload, cookies } = await this._call('POST', '/api/register', {
body: { username, email, password },
});
return { user: AuthClient._publicUser(payload), cookies };
}
/**
* Calls POST /api/login. totpToken may be empty; AuthGuard raises an
* APIError with totpRequired set when the account has two-factor auth
* enabled and no valid code was supplied.
* @returns {Promise<{user: object, cookies: string[]}>}
*/
async login(usernameOrEmail, password, totpToken = '') {
const body = { username_or_email: usernameOrEmail, password };
if (totpToken) body.totp_token = totpToken;
const { payload, cookies } = await this._call('POST', '/api/login', { body });
return { user: AuthClient._publicUser(payload), cookies };
}
/**
* Calls POST /api/logout, deleting the session identified by token
* server-side. Returns the (cookie-clearing) Set-Cookie header value(s)
* AuthGuard's response carried.
* @returns {Promise<string[]>}
*/
async logout(token) {
const { cookies } = await this._call('POST', '/api/logout', { token });
return cookies;
}
/** Calls GET /api/me, resolving token to its account. */
async me(token) {
const { payload } = await this._call('GET', '/api/me', { token });
return AuthClient._publicUser(payload);
}
// --- TOTP -----------------------------------------------------------------
/**
* Calls POST /api/totp/enable, provisioning (or re-provisioning) a
* pending TOTP secret for token's account. The secret is not active
* until totpVerify confirms a generated code.
* @returns {Promise<{secret: string, otpauthUrl: string, enabled: boolean}>}
*/
async totpEnable(token) {
const { payload } = await this._call('POST', '/api/totp/enable', { token });
return {
secret: payload.secret ?? '',
otpauthUrl: payload.otpauth_url ?? '',
enabled: Boolean(payload.enabled),
};
}
/**
* Calls POST /api/totp/verify, confirming code against the pending
* secret totpEnable provisioned and activating two-factor auth.
*/
async totpVerify(token, code) {
await this._call('POST', '/api/totp/verify', { token, body: { token: code } });
}
/**
* Calls POST /api/totp/disable, turning two-factor auth off for token's
* account. AuthGuard requires code to be one last valid TOTP code as
* proof of possession.
*/
async totpDisable(token, code) {
await this._call('POST', '/api/totp/disable', { token, body: { token: code } });
}
// --- password reset ("break glass", console-only - see AuthGuard's README) --
/**
* Calls 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 no usernameOrEmail, the
* target is AuthGuard's superadmin account - AuthGuard's own web UI is
* the intended place to drive this, not an individual project (see
* AuthGuard's README's "Web UI" section).
*/
async requestPasswordReset(usernameOrEmail = '') {
const body = usernameOrEmail ? { username_or_email: usernameOrEmail } : {};
await this._call('POST', '/api/password-reset/request', { body });
}
/**
* Calls 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.
*/
async confirmPasswordReset(code, newPassword) {
await this._call('POST', '/api/password-reset/confirm', {
body: { code, password: newPassword },
});
}
// --- admin user management --------------------------------------------------
/**
* Calls GET /api/admin/users. token's account must satisfy AuthGuard's
* CanManageUsers check (admin or superadmin), or this throws an
* APIError with statusCode 401/403.
* @returns {Promise<object[]>}
*/
async listManagedUsers(token) {
const { payload } = await this._call('GET', '/api/admin/users', { token });
return (payload.users ?? []).map(AuthClient._managedUser);
}
/**
* Calls POST /api/admin/users. Only a superadmin actor may set role to
* anything other than "user"; anyone else's requested role is silently
* ignored by AuthGuard.
* @param {{username: string, email: string, password: string, role?: string}} input
*/
async createManagedUser(token, input) {
const { payload } = await this._call('POST', '/api/admin/users', { token, body: input });
return AuthClient._managedUser(payload.user);
}
/**
* Calls PUT /api/admin/users/{id}. An omitted field means "leave
* unchanged" (AuthGuard applies only non-empty fields); role is only
* honored per AuthGuard's own authorization rules (only a superadmin
* actor, and never onto/away from a superadmin target) - this client
* does not re-implement or pre-validate those rules.
* @param {{username?: string, email?: string, password?: string, role?: string}} input
*/
async updateManagedUser(token, id, input) {
await this._call('PUT', `/api/admin/users/${encodeURIComponent(id)}`, { token, body: input });
}
/** Calls DELETE /api/admin/users/{id}. */
async deleteManagedUser(token, id) {
await this._call('DELETE', `/api/admin/users/${encodeURIComponent(id)}`, { token });
}
}
/**
* @param {string} baseUrl
* @param {{cookieName?: string, timeoutMs?: number, fetchImpl?: typeof fetch}} [options]
*/
export function createAuthClient(baseUrl, options) {
return new AuthClient(baseUrl, options);
}
+1
View File
@@ -31,3 +31,4 @@ export {
verifyTotp, verifyTotp,
} from './totp.js'; } from './totp.js';
export { runMigrations } from './migrate.js'; export { runMigrations } from './migrate.js';
export { APIError, AuthClient, InvalidSessionError, createAuthClient } from './authclient.js';
@@ -0,0 +1,321 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { APIError, AuthClient, InvalidSessionError } from '../src/authclient.js';
function fakeFetch(responses) {
let call = 0;
return async () => {
const res = responses[Math.min(call, responses.length - 1)];
call += 1;
const bodyText = res.body === undefined ? '' : JSON.stringify(res.body);
return {
status: res.status,
ok: res.status >= 200 && res.status < 300,
json: async () => res.body,
text: async () => bodyText,
headers: { getSetCookie: () => res.cookies ?? [] },
};
};
}
// Records every (url, init) pair a fakeFetch call received, for assertions
// on method/headers/body without a full fetch mock library.
function recordingFetch(responses) {
const calls = [];
const inner = fakeFetch(responses);
const wrapped = async (url, init) => {
calls.push({ url, init });
return inner(url, init);
};
wrapped.calls = calls;
return wrapped;
}
test('constructor assumes https for a bare public host', () => {
assert.equal(new AuthClient('auth.example.com').baseUrl, 'https://auth.example.com');
assert.equal(new AuthClient('auth.example.com:8080').baseUrl, 'https://auth.example.com:8080');
});
test('constructor assumes http for a bare private/loopback/link-local host', () => {
assert.equal(new AuthClient('192.168.1.50:8080').baseUrl, 'http://192.168.1.50:8080');
assert.equal(new AuthClient('10.1.2.3:8080').baseUrl, 'http://10.1.2.3:8080');
assert.equal(new AuthClient('172.20.0.5:8080').baseUrl, 'http://172.20.0.5:8080');
assert.equal(new AuthClient('127.0.0.1:8080').baseUrl, 'http://127.0.0.1:8080');
assert.equal(new AuthClient('169.254.1.1:8080').baseUrl, 'http://169.254.1.1:8080');
assert.equal(new AuthClient('localhost:8080').baseUrl, 'http://localhost:8080');
assert.equal(new AuthClient('authguard.local:8080').baseUrl, 'http://authguard.local:8080');
assert.equal(new AuthClient('[::1]:8080').baseUrl, 'http://[::1]:8080');
assert.equal(new AuthClient('[fd00::1]:8080').baseUrl, 'http://[fd00::1]:8080');
});
test('constructor assumes https for a 172.x address outside the 16-31 private range', () => {
assert.equal(new AuthClient('172.32.0.5:8080').baseUrl, 'https://172.32.0.5: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');
assert.equal(new AuthClient('https://192.168.1.50:8080').baseUrl, 'https://192.168.1.50:8080');
});
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' } }]),
});
const user = await client.validate('good-token');
assert.deepEqual(user, { id: 7, username: 'gabriel', role: 'admin' });
});
test('validate throws InvalidSessionError on an empty token', async () => {
const client = new AuthClient('https://auth.example.com', { fetchImpl: fakeFetch([{ status: 200, body: {} }]) });
await assert.rejects(() => client.validate(''), InvalidSessionError);
await assert.rejects(() => client.validate(' '), InvalidSessionError);
});
test('validate throws InvalidSessionError when AuthGuard reports invalid', async () => {
const client = new AuthClient('https://auth.example.com', {
fetchImpl: fakeFetch([{ status: 401, body: { valid: false } }]),
});
await assert.rejects(() => client.validate('bad-token'), InvalidSessionError);
});
test('tokenFromRequest prefers the Authorization header over the cookie', () => {
const client = new AuthClient('https://auth.example.com');
const req = {
headers: {
authorization: 'Bearer header-token',
cookie: 'auth_session=cookie-token; other=1',
},
};
assert.equal(client.tokenFromRequest(req), 'header-token');
});
test('tokenFromRequest falls back to the auth_session cookie', () => {
const client = new AuthClient('https://auth.example.com');
const req = { headers: { cookie: 'other=1; auth_session=cookie-token' } };
assert.equal(client.tokenFromRequest(req), 'cookie-token');
});
test('middleware attaches authUser on success and 401s on failure', async () => {
const okClient = new AuthClient('https://auth.example.com', {
fetchImpl: fakeFetch([{ status: 200, body: { valid: true, user_id: 1, username: 'a', role: 'user' } }]),
});
const req = { headers: { authorization: 'Bearer t' } };
let nextCalled = false;
await okClient.middleware()(req, { status: () => ({ json: () => {} }) }, () => {
nextCalled = true;
});
assert.equal(nextCalled, true);
assert.deepEqual(req.authUser, { id: 1, username: 'a', role: 'user' });
const badClient = new AuthClient('https://auth.example.com', {
fetchImpl: fakeFetch([{ status: 401, body: { valid: false } }]),
});
let statusCode = null;
let jsonBody = null;
const res = {
status(code) {
statusCode = code;
return { json: (body) => (jsonBody = body) };
},
};
await badClient.middleware()({ headers: {} }, res, () => {
throw new Error('next should not be called');
});
assert.equal(statusCode, 401);
assert.deepEqual(jsonBody, { error: 'authentication required' });
});
// --- register/login/.../setupStatus: the additional surface a service that
// runs its own login/admin screens proxied to AuthGuard needs, beyond the
// original validate()-only surface. ---
test('setupStatus reflects AuthGuard setup_required', async () => {
for (const setupRequired of [true, false]) {
const client = new AuthClient('https://auth.example.com', {
fetchImpl: fakeFetch([{ status: 200, body: { setup_required: setupRequired } }]),
});
assert.equal(await client.setupStatus(), setupRequired);
}
});
test('register returns the user and forwards Set-Cookie values', async () => {
const fetchImpl = recordingFetch([
{
status: 201,
body: { user: { id: 1, username: 'root', email: 'root@example.com', role: 'superadmin', totp_enabled: false } },
cookies: ['auth_session=abc; HttpOnly'],
},
]);
const client = new AuthClient('https://auth.example.com', { fetchImpl });
const result = await client.register('root', 'root@example.com', 'correct horse battery staple');
assert.deepEqual(result.user, {
id: 1,
username: 'root',
email: 'root@example.com',
role: 'superadmin',
totpEnabled: false,
});
assert.deepEqual(result.cookies, ['auth_session=abc; HttpOnly']);
const sent = JSON.parse(fetchImpl.calls[0].init.body);
assert.deepEqual(sent, { username: 'root', email: 'root@example.com', password: 'correct horse battery staple' });
});
test('login success reports totpEnabled from AuthGuard', async () => {
const client = new AuthClient('https://auth.example.com', {
fetchImpl: fakeFetch([
{
status: 200,
body: { user: { id: 2, username: 'alice', email: 'alice@example.com', role: 'user', totp_enabled: true } },
cookies: ['auth_session=xyz'],
},
]),
});
const result = await client.login('alice', 'correct horse battery staple', '123456');
assert.equal(result.user.username, 'alice');
assert.equal(result.user.totpEnabled, true);
assert.deepEqual(result.cookies, ['auth_session=xyz']);
});
test('login raises APIError with totpRequired on a 401 asking for a code', async () => {
const client = new AuthClient('https://auth.example.com', {
fetchImpl: fakeFetch([
{ status: 401, body: { error: 'two-factor authentication code required', totp_required: true } },
]),
});
await assert.rejects(
() => client.login('alice', 'correct horse battery staple'),
(err) => err instanceof APIError && err.statusCode === 401 && err.totpRequired === true,
);
});
test('login raises APIError without totpRequired on invalid credentials', async () => {
const client = new AuthClient('https://auth.example.com', {
fetchImpl: fakeFetch([{ status: 401, body: { error: 'invalid username/email or password' } }]),
});
await assert.rejects(
() => client.login('alice', 'wrong password'),
(err) => err instanceof APIError && err.totpRequired === false && err.detailMessage === 'invalid username/email or password',
);
});
test('logout returns the clearing cookies', async () => {
const fetchImpl = recordingFetch([{ status: 200, body: { ok: true }, cookies: ['auth_session=; Max-Age=0'] }]);
const client = new AuthClient('https://auth.example.com', { fetchImpl });
const cookies = await client.logout('a-token');
assert.deepEqual(cookies, ['auth_session=; Max-Age=0']);
assert.equal(fetchImpl.calls[0].init.headers.Authorization, 'Bearer a-token');
});
test('me resolves the public user', async () => {
const client = new AuthClient('https://auth.example.com', {
fetchImpl: fakeFetch([
{ status: 200, body: { user: { id: 3, username: 'bob', email: 'bob@example.com', role: 'admin', totp_enabled: false } } },
]),
});
const user = await client.me('a-token');
assert.equal(user.id, 3);
assert.equal(user.role, 'admin');
});
test('totpEnable returns the provisioned secret', async () => {
const client = new AuthClient('https://auth.example.com', {
fetchImpl: fakeFetch([{ status: 200, body: { secret: 'SECRET', otpauth_url: 'otpauth://...', enabled: false } }]),
});
const result = await client.totpEnable('a-token');
assert.equal(result.secret, 'SECRET');
assert.equal(result.enabled, false);
});
test('totpVerify and totpDisable send the code as {token}', async () => {
let fetchImpl = recordingFetch([{ status: 200, body: { enabled: true } }]);
let client = new AuthClient('https://auth.example.com', { fetchImpl });
await client.totpVerify('a-token', '123456');
assert.deepEqual(JSON.parse(fetchImpl.calls[0].init.body), { token: '123456' });
fetchImpl = recordingFetch([{ status: 200, body: { enabled: false } }]);
client = new AuthClient('https://auth.example.com', { fetchImpl });
await client.totpDisable('a-token', '654321');
assert.deepEqual(JSON.parse(fetchImpl.calls[0].init.body), { token: '654321' });
});
test('requestPasswordReset with no identifier sends an empty body (targets the superadmin)', async () => {
const fetchImpl = recordingFetch([{ status: 200, body: { ok: true } }]);
const client = new AuthClient('https://auth.example.com', { fetchImpl });
await client.requestPasswordReset();
assert.deepEqual(JSON.parse(fetchImpl.calls[0].init.body), {});
});
test('confirmPasswordReset sends the code and new password', async () => {
const fetchImpl = recordingFetch([{ status: 200, body: { ok: true } }]);
const client = new AuthClient('https://auth.example.com', { fetchImpl });
await client.confirmPasswordReset('ABCD1234', 'a brand new passphrase');
assert.deepEqual(JSON.parse(fetchImpl.calls[0].init.body), { code: 'ABCD1234', password: 'a brand new passphrase' });
});
test('listManagedUsers maps every row', async () => {
const client = new AuthClient('https://auth.example.com', {
fetchImpl: fakeFetch([
{
status: 200,
body: {
users: [
{ id: 1, username: 'root', email: 'root@example.com', role: 'superadmin', created_at: '2026-01-01T00:00:00Z' },
{ id: 2, username: 'bob', email: 'bob@example.com', role: 'user', created_at: '2026-01-02T00:00:00Z' },
],
},
},
]),
});
const users = await client.listManagedUsers('a-token');
assert.equal(users.length, 2);
assert.deepEqual(users[0], {
id: 1,
username: 'root',
email: 'root@example.com',
role: 'superadmin',
createdAt: '2026-01-01T00:00:00Z',
});
});
test('createManagedUser sends only the given fields', async () => {
const fetchImpl = recordingFetch([
{ status: 201, body: { user: { id: 4, username: 'carol', email: 'carol@example.com', role: 'user', created_at: '' } } },
]);
const client = new AuthClient('https://auth.example.com', { fetchImpl });
const created = await client.createManagedUser('a-token', {
username: 'carol',
email: 'carol@example.com',
password: 'correct horse battery staple',
});
assert.equal(created.username, 'carol');
const sent = JSON.parse(fetchImpl.calls[0].init.body);
assert.equal('role' in sent, false);
});
test('updateManagedUser PUTs to /api/admin/users/{id}', async () => {
const fetchImpl = recordingFetch([{ status: 200, body: { ok: true } }]);
const client = new AuthClient('https://auth.example.com', { fetchImpl });
await client.updateManagedUser('a-token', 5, { email: 'new@example.com' });
assert.equal(fetchImpl.calls[0].init.method, 'PUT');
assert.equal(fetchImpl.calls[0].url, 'https://auth.example.com/api/admin/users/5');
assert.deepEqual(JSON.parse(fetchImpl.calls[0].init.body), { email: 'new@example.com' });
});
test('deleteManagedUser DELETEs /api/admin/users/{id}', async () => {
const fetchImpl = recordingFetch([{ status: 200, body: { ok: true } }]);
const client = new AuthClient('https://auth.example.com', { fetchImpl });
await client.deleteManagedUser('a-token', 6);
assert.equal(fetchImpl.calls[0].init.method, 'DELETE');
assert.equal(fetchImpl.calls[0].url, 'https://auth.example.com/api/admin/users/6');
});
+55 -2
View File
@@ -6,12 +6,65 @@ Shared Python backend infrastructure for services using `asyncpg`:
- one async pool owner with ping and graceful shutdown; - one async pool owner with ping and graceful shutdown;
- bcrypt password and secure session-token helpers; - bcrypt password and secure session-token helpers;
- short-lived, one-time admin reset codes printed to the server console; - short-lived, one-time admin reset codes printed to the server console;
- common account/session persistence for the single-admin or optional multi-user model. - common account/session persistence for the single-admin or optional multi-user model;
- an `authclient` module for services that adopt AuthGuard, the centralized
identity service, instead of this package's own local Postgres-backed
auth (see below).
HTTP framework adapters stay in each service. Install this package from the HTTP framework adapters stay in each service. Install this package from the
published index or directly from the SharedCode repository with a subdirectory published index or directly from the shared repository with a subdirectory
install during development: install during development:
```bash ```bash
pip install "git+https://repos.gfranz.ch/Gabriel20xx/shared@v0.1.0#subdirectory=packages/python-backend" pip install "git+https://repos.gfranz.ch/Gabriel20xx/shared@v0.1.0#subdirectory=packages/python-backend"
``` ```
## `authclient`: adopting AuthGuard instead of local auth
`shared_backend.authclient` is how a service trades its own local user table
for one HTTP call per request to a centralized AuthGuard instance's
`GET /api/session/validate`, gaining a single shared identity across every
project that does the same. It mirrors `shared/backend/authclient` (Go) and
`shared/packages/node-backend/src/authclient.js` (Node) — same shape,
translated to Python idioms. It's additive: switching to it is a deliberate
per-project decision, and no project is wired up to it automatically.
`AuthClient.validate` is `async` (stdlib `urllib` under the hood, run off
the event loop via `asyncio.to_thread`, so no new HTTP dependency), for the
same reason the Go/Node versions are async — it composes with an async
request handler instead of blocking it:
```python
from shared_backend import AuthClient, AuthClientError, InvalidSessionError
auth_client = AuthClient("https://authguard.example.com")
try:
user = await auth_client.validate(token) # AuthGuardUser(id, username, role)
except InvalidSessionError:
... # no/expired/unknown session - fail closed (401)
except AuthClientError:
... # AuthGuard unreachable or returned something unexpected - also fail closed
```
`token_from_request(headers, cookies)` extracts a token the same way the
Go/Node versions do — an `Authorization: Bearer <token>` header first,
falling back to a cookie (`auth_session` by default) — and `resolve_user`
combines that with `validate`. Both are plain functions over
headers/cookies mappings, not tied to any web framework (this package's
adapters stay in each service, per the note above); wire them into whatever
your framework's request pipeline looks like, e.g. as a FastAPI dependency:
```python
from fastapi import Depends, HTTPException, Request
from shared_backend.authclient import resolve_user
async def require_session(request: Request):
try:
return await resolve_user(auth_client, request.headers, request.cookies)
except Exception as exc:
raise HTTPException(status_code=401, detail="authentication required") from exc
@app.get("/me", dependencies=[Depends(require_session)])
...
```
+1 -1
View File
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
[project] [project]
name = "gabriel20xx-shared-backend" name = "gabriel20xx-shared-backend"
version = "0.1.0" version = "0.1.1"
description = "Shared PostgreSQL and authentication primitives for Python services." description = "Shared PostgreSQL and authentication primitives for Python services."
readme = "README.md" readme = "README.md"
requires-python = ">=3.10" requires-python = ">=3.10"
@@ -14,6 +14,14 @@ from .auth import (
normalize_role, normalize_role,
verify_password, verify_password,
) )
from .authclient import (
AuthClient,
AuthClientError,
AuthGuardUser,
InvalidSessionError,
resolve_user,
token_from_request,
)
from .config import DatabaseConfig, database_url_from_env from .config import DatabaseConfig, database_url_from_env
from .postgres import Database from .postgres import Database
from .tokens import hash_token, new_session_token from .tokens import hash_token, new_session_token
@@ -22,6 +30,12 @@ from .totp import generate_totp_secret, totp_provisioning_uri, verify_totp
__all__ = [ __all__ = [
"AuthStore", "AuthStore",
"AuthUser", "AuthUser",
"AuthClient",
"AuthClientError",
"AuthGuardUser",
"InvalidSessionError",
"resolve_user",
"token_from_request",
"ROLE_ADMIN", "ROLE_ADMIN",
"ROLE_SUPERADMIN", "ROLE_SUPERADMIN",
"ROLE_USER", "ROLE_USER",
@@ -0,0 +1,574 @@
"""HTTP client for a centralized AuthGuard instance (see the AuthGuard project,
a sibling of this shared/python-backend package) instead of embedding this
package's own asyncpg-backed AuthStore against a service's private database.
A service that switches to AuthGuard trades "its own local user table" for
"HTTP calls to AuthGuard's API", gaining a single shared identity across
every project that does the same. This module is additive: it does not
change how shared_backend.auth works. Mirrors shared/backend/authclient/client.go
and shared/packages/node-backend/src/authclient.js (the Go and Node
equivalents) -- keep all three in sync if any changes shape.
Two kinds of consumer, two parts of this module:
- A service that only needs to gate requests behind "is this a valid
AuthGuard session" (HordeWorker, Heretic) uses `AuthClient.validate` /
`token_from_request` / `resolve_user`, calling only GET
/api/session/validate. This is the original, minimal surface of this
module.
- A service that runs its own login/register/admin-user-management screens
proxied to AuthGuard (mirroring shared/backend/authclient/client.go's
full method set -- see e.g. Original/GameStream/backend/cmd/gamestreamd/auth.go
for the reference Go implementation of this pattern) uses the additional
methods below: register, login, logout, me, totp_*, *_password_reset,
*_managed_user(s), setup_status.
Sync vs. async: every other I/O-bound module in this package (auth.py,
postgres.py) is async, built on asyncpg, because a service using this
package already runs its own request handling on an async event loop. Every
method here is `async` for the same reason. This package's dependency list
(asyncpg, bcrypt) has no async HTTP client, and adding one (aiohttp, httpx)
just for occasional small JSON requests is more than this needs. Instead,
the actual HTTP calls are plain blocking `urllib.request.urlopen`, run off
the event loop via `asyncio.to_thread` -- stdlib-only, and the awkwardness
of raw async stdlib sockets/TLS/redirects is not worth it here.
Framework-agnostic vs. framework-specific: this package's own README says
"HTTP framework adapters stay in each service". `token_from_request`/
`resolve_user` are plain functions over headers/cookies mappings (which is
all `aiohttp.web.Request` and FastAPI/Starlette's `Request` both expose),
and each service wires those into its own framework's idiom (an aiohttp
`@web.middleware`, a FastAPI `Depends`, etc.) the same way it already owns
its own routing. The register/login/logout methods return the raw
Set-Cookie header values AuthGuard's response carried rather than trying to
set them on a framework-specific response object -- see SessionResult --
for the same reason: each service's own route handler already owns the
concrete Response object and knows how to attach headers to it.
"""
from __future__ import annotations
import asyncio
import ipaddress
import json
import urllib.error
import urllib.request
from dataclasses import dataclass, field
from typing import Any, Mapping
DEFAULT_COOKIE_NAME = "auth_session"
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"http://{trimmed}" if _is_private_host(trimmed) else f"https://{trimmed}"
def _is_private_host(hostport: str) -> bool:
"""Reports whether hostport (a bare "host" or "host:port", no scheme)
names a loopback, RFC1918/RFC4193 private, or link-local address, or a
".local" mDNS name -- the kind of host a plain-HTTP AuthGuard is
typically reachable at on a local network, as opposed to a public
hostname expected to terminate TLS itself. Never performs DNS
resolution: only literal IPs and the "localhost"/".local" names are
recognized, so a real public hostname that merely happens to resolve to
a private address still defaults to https.
"""
host = hostport
if host.startswith("["):
end = host.find("]")
if end != -1:
host = host[1:end]
elif host.count(":") == 1:
host = host.split(":", 1)[0]
host = host.strip().lower()
if host == "localhost" or host.endswith(".local"):
return True
try:
ip = ipaddress.ip_address(host)
except ValueError:
return False
return ip.is_loopback or ip.is_private or ip.is_link_local
class InvalidSessionError(Exception):
"""Raised by validate() / resolve_user() when AuthGuard reports the
token/cookie as not currently valid (expired, unknown, or missing)."""
def __init__(self, message: str = "authclient: invalid or missing session") -> None:
super().__init__(message)
class AuthClientError(Exception):
"""Raised for a transport or decoding failure talking to AuthGuard --
kept distinct from InvalidSessionError so callers can tell "AuthGuard is
unreachable/misbehaving" apart from "this visitor is unauthenticated" if
they want to log or alert differently. Either way, callers should still
fail closed (401) on both."""
class APIError(AuthClientError):
"""Raised when AuthGuard responds with a non-2xx status to one of the
register/login/.../setup_status methods below (not raised by validate(),
which uses InvalidSessionError for its one specific non-2xx case).
Mirrors Go's *authclient.APIError -- carries the status code and (when
AuthGuard's JSON body decoded successfully) its {"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."""
def __init__(self, status_code: int, message: str, *, totp_required: bool = False) -> None:
self.status_code = status_code
self.message = message
# Mirrors AuthGuard's {"totp_required": true} flag on a 401 from
# POST /api/login 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.
self.totp_required = totp_required
super().__init__(f"authclient: authguard responded {status_code}: {message}")
@dataclass(frozen=True, slots=True)
class AuthGuardUser:
"""The account AuthGuard resolved for a validated session. Mirrors the
fields returned by GET /api/session/validate (and the Go/Node User
types) -- deliberately not the local shared_backend.auth.AuthUser
dataclass, which carries columns (email, password_hash, timestamps) that
only exist for this package's own local Postgres-backed auth."""
id: int
username: str
role: str
@dataclass(frozen=True, slots=True)
class PublicUser:
"""The account object AuthGuard returns from POST /api/register,
POST /api/login, and GET /api/me. Mirrors AuthGuard's publicUser (see
internal/httpapi/server.go's toPublicUser) -- includes totp_enabled,
which AuthGuardUser (from /api/session/validate) does not carry."""
id: int
username: str
email: str
role: str
totp_enabled: bool = False
@dataclass(frozen=True, slots=True)
class ManagedUser:
"""One row of GET /api/admin/users, and the payload returned by
create_managed_user. Additionally carries created_at, which PublicUser
does not."""
id: int
username: str
email: str
role: str
created_at: str = ""
@dataclass(frozen=True, slots=True)
class SessionResult:
"""Returned by register() and login(): the account AuthGuard resolved,
plus the raw Set-Cookie header value(s) its response carried. A caller
forwards these onto its own framework's response object, e.g. in
FastAPI: `for cookie in result.cookies: response.headers.append("set-cookie", cookie)`."""
user: PublicUser
cookies: list[str] = field(default_factory=list)
@dataclass(frozen=True, slots=True)
class TOTPEnableResult:
"""Returned by totp_enable(): a freshly provisioned, not yet active TOTP
secret and its otpauth:// URI for a QR code / authenticator app. Confirm
it with totp_verify()."""
secret: str
otpauth_url: str
enabled: bool = False
class AuthClient:
"""Calls a centralized AuthGuard instance over HTTP."""
def __init__(
self,
base_url: str,
*,
cookie_name: str = DEFAULT_COOKIE_NAME,
timeout: float = DEFAULT_TIMEOUT,
) -> None:
"""base_url is AuthGuard's base URL, e.g. "https://auth.example.com"
(no trailing slash required). May be given without a scheme (e.g.
"auth.example.com" or "192.168.1.50:8080") -- the scheme is then
inferred from the host: a loopback, RFC1918/RFC4193 private, or
link-local address, or a ".local" name, defaults to "http://" (a
plain-HTTP AuthGuard on a local network is the common case for
those), anything else defaults to "https://". An explicit "http://"
or "https://" is always left as-is, overriding the inference.
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 = _normalize_base_url(base_url)
self.cookie_name = cookie_name
self.timeout = timeout
# --- session validation (the original, minimal surface) ----------------
async def validate(self, token: str) -> AuthGuardUser:
"""Calls AuthGuard's GET /api/session/validate with token as a Bearer
credential and returns the resolved user. Raises InvalidSessionError
when AuthGuard reports the session as not valid (or token is
empty/missing -- checked locally, without a network call), and
AuthClientError for any transport/decoding failure."""
if not self.base_url:
raise AuthClientError("authclient: client has no base URL")
trimmed = (token or "").strip()
if not trimmed:
raise InvalidSessionError()
return await asyncio.to_thread(self._validate_sync, trimmed)
def _validate_sync(self, token: str) -> AuthGuardUser:
request = urllib.request.Request(
f"{self.base_url}/api/session/validate",
headers={"Authorization": f"{_BEARER_PREFIX}{token}"},
)
try:
with urllib.request.urlopen(request, timeout=self.timeout) as response:
status = response.status
body = response.read()
except urllib.error.HTTPError as exc:
# A non-2xx status still carries a body (AuthGuard's {"valid":
# false, ...} JSON, typically on a 401); read it the same way a
# normal response would be before falling through to decoding.
status = exc.code
body = exc.read()
except urllib.error.URLError as exc:
raise AuthClientError(f"authclient: call AuthGuard: {exc}") from exc
except OSError as exc:
raise AuthClientError(f"authclient: call AuthGuard: {exc}") from exc
try:
payload = json.loads(body)
if not isinstance(payload, dict):
raise TypeError(f"expected a JSON object, got {type(payload).__name__}")
except (ValueError, TypeError, UnicodeDecodeError) as exc:
if status == 401:
raise InvalidSessionError() from exc
raise AuthClientError(f"authclient: decode AuthGuard response: {exc}") from exc
if status != 200 or not payload.get("valid"):
raise InvalidSessionError()
return AuthGuardUser(
id=int(payload.get("user_id") or 0),
username=str(payload.get("username") or ""),
role=str(payload.get("role") or ""),
)
# --- shared request/response plumbing for everything below -------------
async def _call(
self,
method: str,
path: str,
*,
token: str = "",
body: Any = None,
) -> tuple[dict[str, Any], list[str]]:
"""Runs one JSON request/response round trip against AuthGuard, off
the event loop. Returns the decoded JSON body (an empty dict for a
2xx response with no body) and the raw Set-Cookie header value(s)
the response carried. Raises APIError for a non-2xx response,
AuthClientError for a transport/decoding failure -- mirroring Go's
Client.call exactly, just spread across two return values instead
of one (Go, request, out any)."""
if not self.base_url:
raise AuthClientError("authclient: client has no base URL")
return await asyncio.to_thread(self._call_sync, method, path, token, body)
def _call_sync(
self, method: str, path: str, token: str, body: Any
) -> tuple[dict[str, Any], list[str]]:
data = None
headers: dict[str, str] = {}
if body is not None:
data = json.dumps(body).encode()
headers["Content-Type"] = "application/json"
if token:
headers["Authorization"] = f"{_BEARER_PREFIX}{token}"
request = urllib.request.Request(
f"{self.base_url}{path}", data=data, headers=headers, method=method
)
try:
with urllib.request.urlopen(request, timeout=self.timeout) as response:
status = response.status
raw = response.read()
cookies = response.headers.get_all("Set-Cookie") or []
except urllib.error.HTTPError as exc:
status = exc.code
raw = exc.read()
cookies = []
except urllib.error.URLError as exc:
raise AuthClientError(f"authclient: call AuthGuard: {exc}") from exc
except OSError as exc:
raise AuthClientError(f"authclient: call AuthGuard: {exc}") from exc
payload: dict[str, Any] = {}
if raw:
try:
decoded = json.loads(raw)
if isinstance(decoded, dict):
payload = decoded
except (ValueError, TypeError, UnicodeDecodeError) as exc:
if not (200 <= status < 300):
raise APIError(status, f"request failed ({status})") from exc
raise AuthClientError(f"authclient: decode AuthGuard response: {exc}") from exc
if not (200 <= status < 300):
message = str(payload.get("error") or f"request failed ({status})")
raise APIError(status, message, totp_required=bool(payload.get("totp_required")))
return payload, list(cookies)
@staticmethod
def _public_user(payload: dict[str, Any]) -> PublicUser:
user = payload.get("user") or {}
return PublicUser(
id=int(user.get("id") or 0),
username=str(user.get("username") or ""),
email=str(user.get("email") or ""),
role=str(user.get("role") or ""),
totp_enabled=bool(user.get("totp_enabled")),
)
@staticmethod
def _managed_user(user: dict[str, Any]) -> ManagedUser:
return ManagedUser(
id=int(user.get("id") or 0),
username=str(user.get("username") or ""),
email=str(user.get("email") or ""),
role=str(user.get("role") or ""),
created_at=str(user.get("created_at") or ""),
)
# --- setup / registration ------------------------------------------------
async def setup_status(self) -> bool:
"""Calls 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
returns 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."""
payload, _ = await self._call("GET", "/api/setup-status")
return bool(payload.get("setup_required"))
async def register(self, username: str, email: str, password: str) -> SessionResult:
"""Calls POST /api/register, creating a new AuthGuard account and
starting a session for it."""
payload, cookies = await self._call(
"POST",
"/api/register",
body={"username": username, "email": email, "password": password},
)
return SessionResult(user=self._public_user(payload), cookies=cookies)
async def login(
self, username_or_email: str, password: str, totp_token: str = ""
) -> SessionResult:
"""Calls POST /api/login. totp_token may be empty; AuthGuard raises
an APIError with totp_required set when the account has two-factor
auth enabled and no valid code was supplied."""
body: dict[str, str] = {"username_or_email": username_or_email, "password": password}
if totp_token:
body["totp_token"] = totp_token
payload, cookies = await self._call("POST", "/api/login", body=body)
return SessionResult(user=self._public_user(payload), cookies=cookies)
async def logout(self, token: str) -> list[str]:
"""Calls POST /api/logout, deleting the session identified by token
server-side. Returns the (cookie-clearing) Set-Cookie header
value(s) AuthGuard's response carried."""
_, cookies = await self._call("POST", "/api/logout", token=token)
return cookies
async def me(self, token: str) -> PublicUser:
"""Calls GET /api/me, resolving token to its account."""
payload, _ = await self._call("GET", "/api/me", token=token)
return self._public_user(payload)
# --- TOTP ------------------------------------------------------------------
async def totp_enable(self, token: str) -> TOTPEnableResult:
"""Calls POST /api/totp/enable, provisioning (or re-provisioning) a
pending TOTP secret for token's account. The secret is not active
until totp_verify confirms a generated code."""
payload, _ = await self._call("POST", "/api/totp/enable", token=token)
return TOTPEnableResult(
secret=str(payload.get("secret") or ""),
otpauth_url=str(payload.get("otpauth_url") or ""),
enabled=bool(payload.get("enabled")),
)
async def totp_verify(self, token: str, code: str) -> None:
"""Calls POST /api/totp/verify, confirming code against the pending
secret totp_enable provisioned and activating two-factor auth."""
await self._call("POST", "/api/totp/verify", token=token, body={"token": code})
async def totp_disable(self, token: str, code: str) -> None:
"""Calls POST /api/totp/disable, turning two-factor auth off for
token's account. AuthGuard requires code to be one last valid TOTP
code as proof of possession."""
await self._call("POST", "/api/totp/disable", token=token, body={"token": code})
# --- password reset ("break glass", console-only -- see AuthGuard's README) --
async def request_password_reset(self, username_or_email: str = "") -> None:
"""Calls 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. Sent with no
username_or_email, the target is AuthGuard's superadmin account --
AuthGuard's own web UI is the intended place to drive this, not an
individual project (see AuthGuard's README's "Web UI" section)."""
body = {"username_or_email": username_or_email} if username_or_email else {}
await self._call("POST", "/api/password-reset/request", body=body)
async def confirm_password_reset(self, code: str, new_password: str) -> None:
"""Calls 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."""
await self._call(
"POST",
"/api/password-reset/confirm",
body={"code": code, "password": new_password},
)
# --- admin user management --------------------------------------------------
async def list_managed_users(self, token: str) -> list[ManagedUser]:
"""Calls GET /api/admin/users. token's account must satisfy
AuthGuard's CanManageUsers check (admin or superadmin), or this
raises an APIError with status_code 401/403."""
payload, _ = await self._call("GET", "/api/admin/users", token=token)
return [self._managed_user(u) for u in payload.get("users") or []]
async def create_managed_user(
self,
token: str,
*,
username: str,
email: str,
password: str,
role: str | None = None,
) -> ManagedUser:
"""Calls POST /api/admin/users. Only a superadmin actor may set role
to anything other than "user"; anyone else's requested role is
silently ignored by AuthGuard."""
body: dict[str, Any] = {"username": username, "email": email, "password": password}
if role is not None:
body["role"] = role
payload, _ = await self._call("POST", "/api/admin/users", token=token, body=body)
return self._managed_user(payload.get("user") or {})
async def update_managed_user(
self,
token: str,
user_id: int,
*,
username: str | None = None,
email: str | None = None,
password: str | None = None,
role: str | None = None,
) -> None:
"""Calls PUT /api/admin/users/{id}. A None field means "leave
unchanged" (AuthGuard applies only non-empty fields); role is only
honored per AuthGuard's own authorization rules (only a superadmin
actor, and never onto/away from a superadmin target) -- this client
does not re-implement or pre-validate those rules."""
body: dict[str, Any] = {}
if username is not None:
body["username"] = username
if email is not None:
body["email"] = email
if password is not None:
body["password"] = password
if role is not None:
body["role"] = role
await self._call("PUT", f"/api/admin/users/{user_id}", token=token, body=body)
async def delete_managed_user(self, token: str, user_id: int) -> None:
"""Calls DELETE /api/admin/users/{id}."""
await self._call("DELETE", f"/api/admin/users/{user_id}", token=token)
def token_from_request(
headers: Mapping[str, str],
cookies: Mapping[str, str] | None = None,
*,
cookie_name: str = DEFAULT_COOKIE_NAME,
) -> str:
"""Extracts a session token the same way the Go and Node authclient
versions do: an `Authorization: Bearer <token>` header first, falling
back to a cookie named cookie_name. Returns "" if neither is present.
Framework-agnostic by design (see the module docstring): pass whatever
your framework's request object exposes as headers/cookies mappings,
e.g. aiohttp's `request.headers` / `request.cookies`, or FastAPI's/
Starlette's `request.headers` / `request.cookies`. headers is looked up
case-insensitively when the mapping supports it (both frameworks'
header types do); a plain dict must already use the "Authorization" key.
"""
header = headers.get("Authorization") or headers.get("authorization") or ""
if header.startswith(_BEARER_PREFIX):
token = header[len(_BEARER_PREFIX) :].strip()
if token:
return token
if cookies:
token = (cookies.get(cookie_name) or "").strip()
if token:
return token
return ""
async def resolve_user(
client: AuthClient,
headers: Mapping[str, str],
cookies: Mapping[str, str] | None = None,
) -> AuthGuardUser:
"""Extracts a token from headers/cookies with token_from_request (using
client.cookie_name) and validates it against AuthGuard, returning the
resolved user or raising InvalidSessionError / AuthClientError exactly
like validate() does.
This is the framework-agnostic building block every consumer wires into
its own request pipeline, failing closed (401) on any exception from
this call. For example, in an aiohttp `@web.middleware`:
try:
request["user"] = await resolve_user(auth_client, request.headers, request.cookies)
except Exception:
raise web.HTTPUnauthorized(reason="authentication required")
Or as a FastAPI dependency:
async def require_session(request: Request) -> AuthGuardUser:
try:
return await resolve_user(auth_client, request.headers, request.cookies)
except Exception as exc:
raise HTTPException(status_code=401, detail="authentication required") from exc
"""
token = token_from_request(headers, cookies, cookie_name=client.cookie_name)
return await client.validate(token)
@@ -43,7 +43,5 @@ class DatabaseConfig:
min_size=min_size, min_size=min_size,
max_size=max_size, max_size=max_size,
timeout=float(_int_value(source, "DATABASE_CONNECT_TIMEOUT_SECONDS", 5, 1)), timeout=float(_int_value(source, "DATABASE_CONNECT_TIMEOUT_SECONDS", 5, 1)),
command_timeout=float( command_timeout=float(_int_value(source, "DATABASE_COMMAND_TIMEOUT_SECONDS", 15, 1)),
_int_value(source, "DATABASE_COMMAND_TIMEOUT_SECONDS", 15, 1)
),
) )
@@ -0,0 +1,456 @@
import io
import json
import unittest
import urllib.error
from email.message import Message
from unittest.mock import patch
from shared_backend.authclient import (
APIError,
AuthClient,
AuthClientError,
AuthGuardUser,
InvalidSessionError,
ManagedUser,
PublicUser,
resolve_user,
token_from_request,
)
class _FakeResponse:
"""Minimal stand-in for the context manager urllib.request.urlopen returns."""
def __init__(self, status: int, payload: dict, cookies: list[str] | None = None) -> None:
self.status = status
self._body = json.dumps(payload).encode("utf-8")
self.headers = Message()
for cookie in cookies or []:
self.headers.add_header("Set-Cookie", cookie)
def __enter__(self) -> "_FakeResponse":
return self
def __exit__(self, *exc_info) -> bool:
return False
def read(self) -> bytes:
return self._body
def _fake_http_error(status: int, payload: dict) -> urllib.error.HTTPError:
body = json.dumps(payload).encode("utf-8")
return urllib.error.HTTPError(
url="http://authguard.example/api/session/validate",
code=status,
msg="error",
hdrs=Message(),
fp=io.BytesIO(body),
)
class AuthClientBaseUrlTests(unittest.TestCase):
def test_bare_public_host_assumes_https(self) -> None:
self.assertEqual(AuthClient("auth.example.com").base_url, "https://auth.example.com")
self.assertEqual(
AuthClient("auth.example.com:8080").base_url, "https://auth.example.com:8080"
)
def test_bare_private_host_assumes_http(self) -> None:
self.assertEqual(AuthClient("192.168.1.50:8080").base_url, "http://192.168.1.50:8080")
self.assertEqual(AuthClient("10.1.2.3:8080").base_url, "http://10.1.2.3:8080")
self.assertEqual(AuthClient("172.20.0.5:8080").base_url, "http://172.20.0.5:8080")
self.assertEqual(AuthClient("127.0.0.1:8080").base_url, "http://127.0.0.1:8080")
self.assertEqual(AuthClient("169.254.1.1:8080").base_url, "http://169.254.1.1:8080")
self.assertEqual(AuthClient("localhost:8080").base_url, "http://localhost:8080")
self.assertEqual(AuthClient("authguard.local:8080").base_url, "http://authguard.local:8080")
self.assertEqual(AuthClient("[::1]:8080").base_url, "http://[::1]:8080")
self.assertEqual(AuthClient("[fd00::1]:8080").base_url, "http://[fd00::1]:8080")
def test_172_range_outside_private_block_assumes_https(self) -> None:
self.assertEqual(AuthClient("172.32.0.5:8080").base_url, "https://172.32.0.5: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")
self.assertEqual(
AuthClient("https://192.168.1.50:8080").base_url, "https://192.168.1.50:8080"
)
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")
async def test_valid_session_resolves_user(self) -> None:
payload = {"valid": True, "user_id": 42, "username": "alice", "role": "admin"}
response = _FakeResponse(200, payload)
with patch(
"shared_backend.authclient.urllib.request.urlopen", return_value=response
) as urlopen:
user = await self.client.validate("a-token")
self.assertEqual(user, AuthGuardUser(id=42, username="alice", role="admin"))
urlopen.assert_called_once()
request = urlopen.call_args.args[0]
self.assertEqual(request.get_header("Authorization"), "Bearer a-token")
async def test_empty_token_raises_without_network_call(self) -> None:
with patch("shared_backend.authclient.urllib.request.urlopen") as urlopen:
with self.assertRaises(InvalidSessionError):
await self.client.validate("")
with self.assertRaises(InvalidSessionError):
await self.client.validate(" ")
urlopen.assert_not_called()
async def test_missing_base_url_raises_client_error_without_network_call(self) -> None:
client = AuthClient(" ")
with patch("shared_backend.authclient.urllib.request.urlopen") as urlopen:
with self.assertRaises(AuthClientError):
await client.validate("a-token")
urlopen.assert_not_called()
async def test_authguard_reports_invalid_raises_invalid_session_error(self) -> None:
response = _FakeResponse(200, {"valid": False})
with patch("shared_backend.authclient.urllib.request.urlopen", return_value=response):
with self.assertRaises(InvalidSessionError):
await self.client.validate("a-token")
async def test_authguard_401_raises_invalid_session_error(self) -> None:
error = _fake_http_error(401, {"valid": False})
with patch("shared_backend.authclient.urllib.request.urlopen", side_effect=error):
with self.assertRaises(InvalidSessionError):
await self.client.validate("a-token")
async def test_transport_error_propagates_as_auth_client_error(self) -> None:
transport_error = urllib.error.URLError("connection refused")
with patch("shared_backend.authclient.urllib.request.urlopen", side_effect=transport_error):
with self.assertRaises(AuthClientError) as ctx:
await self.client.validate("a-token")
# Distinct from InvalidSessionError - a service outage is not the same
# as "this visitor is unauthenticated".
self.assertNotIsInstance(ctx.exception, InvalidSessionError)
self.assertIs(ctx.exception.__cause__, transport_error)
async def test_decode_failure_propagates_as_auth_client_error(self) -> None:
class _BadResponse(_FakeResponse):
def read(self) -> bytes:
return b"not json"
with patch(
"shared_backend.authclient.urllib.request.urlopen",
return_value=_BadResponse(200, {}),
):
with self.assertRaises(AuthClientError):
await self.client.validate("a-token")
class TokenFromRequestTests(unittest.TestCase):
def test_prefers_authorization_header_over_cookie(self) -> None:
headers = {"Authorization": "Bearer header-token"}
cookies = {"auth_session": "cookie-token"}
self.assertEqual(token_from_request(headers, cookies), "header-token")
def test_falls_back_to_cookie_when_no_header(self) -> None:
self.assertEqual(
token_from_request({}, {"auth_session": "cookie-token"}),
"cookie-token",
)
def test_uses_configured_cookie_name(self) -> None:
self.assertEqual(
token_from_request({}, {"session": "cookie-token"}, cookie_name="session"),
"cookie-token",
)
def test_returns_empty_string_when_neither_present(self) -> None:
self.assertEqual(token_from_request({}, {}), "")
def test_ignores_non_bearer_authorization_header(self) -> None:
headers = {"Authorization": "Basic dXNlcjpwYXNz"}
cookies = {"auth_session": "cookie-token"}
self.assertEqual(token_from_request(headers, cookies), "cookie-token")
class ResolveUserTests(unittest.IsolatedAsyncioTestCase):
async def test_resolves_user_from_header(self) -> None:
client = AuthClient("https://authguard.example")
payload = {"valid": True, "user_id": 7, "username": "bob", "role": "user"}
response = _FakeResponse(200, payload)
with patch("shared_backend.authclient.urllib.request.urlopen", return_value=response):
user = await resolve_user(client, {"Authorization": "Bearer a-token"}, {})
self.assertEqual(user, AuthGuardUser(id=7, username="bob", role="user"))
async def test_no_token_anywhere_raises_invalid_session_without_network_call(self) -> None:
client = AuthClient("https://authguard.example")
with patch("shared_backend.authclient.urllib.request.urlopen") as urlopen:
with self.assertRaises(InvalidSessionError):
await resolve_user(client, {}, {})
urlopen.assert_not_called()
class AuthClientProxyMethodTests(unittest.IsolatedAsyncioTestCase):
"""Covers the register/login/.../setup_status surface: the additional
methods a service that runs its own login/admin screens proxied to
AuthGuard needs, beyond the original validate()-only surface."""
def setUp(self) -> None:
self.client = AuthClient("https://authguard.example")
async def test_setup_status_true_and_false(self) -> None:
for setup_required in (True, False):
response = _FakeResponse(200, {"setup_required": setup_required})
with patch(
"shared_backend.authclient.urllib.request.urlopen", return_value=response
) as urlopen:
result = await self.client.setup_status()
self.assertEqual(result, setup_required)
request = urlopen.call_args.args[0]
self.assertEqual(request.get_method(), "GET")
self.assertTrue(request.full_url.endswith("/api/setup-status"))
async def test_register_returns_user_and_forwards_cookies(self) -> None:
payload = {
"user": {
"id": 1,
"username": "root",
"email": "root@example.com",
"role": "superadmin",
"totp_enabled": False,
}
}
response = _FakeResponse(201, payload, cookies=["auth_session=abc; HttpOnly"])
with patch(
"shared_backend.authclient.urllib.request.urlopen", return_value=response
) as urlopen:
result = await self.client.register(
"root", "root@example.com", "correct horse battery staple"
)
self.assertEqual(
result.user,
PublicUser(
id=1,
username="root",
email="root@example.com",
role="superadmin",
totp_enabled=False,
),
)
self.assertEqual(result.cookies, ["auth_session=abc; HttpOnly"])
request = urlopen.call_args.args[0]
self.assertEqual(request.get_method(), "POST")
sent = json.loads(request.data)
self.assertEqual(
sent,
{
"username": "root",
"email": "root@example.com",
"password": "correct horse battery staple",
},
)
async def test_login_success(self) -> None:
payload = {
"user": {
"id": 2,
"username": "alice",
"email": "alice@example.com",
"role": "user",
"totp_enabled": True,
}
}
response = _FakeResponse(200, payload, cookies=["auth_session=xyz"])
with patch("shared_backend.authclient.urllib.request.urlopen", return_value=response):
result = await self.client.login("alice", "correct horse battery staple", "123456")
self.assertEqual(result.user.username, "alice")
self.assertTrue(result.user.totp_enabled)
self.assertEqual(result.cookies, ["auth_session=xyz"])
async def test_login_totp_required_raises_api_error_with_flag(self) -> None:
error = _fake_http_error(
401, {"error": "two-factor authentication code required", "totp_required": True}
)
with patch("shared_backend.authclient.urllib.request.urlopen", side_effect=error):
with self.assertRaises(APIError) as ctx:
await self.client.login("alice", "correct horse battery staple")
self.assertEqual(ctx.exception.status_code, 401)
self.assertTrue(ctx.exception.totp_required)
async def test_login_invalid_credentials_raises_api_error_without_totp_flag(self) -> None:
error = _fake_http_error(401, {"error": "invalid username/email or password"})
with patch("shared_backend.authclient.urllib.request.urlopen", side_effect=error):
with self.assertRaises(APIError) as ctx:
await self.client.login("alice", "wrong password")
self.assertFalse(ctx.exception.totp_required)
self.assertEqual(ctx.exception.message, "invalid username/email or password")
async def test_logout_returns_clearing_cookies(self) -> None:
response = _FakeResponse(200, {"ok": True}, cookies=["auth_session=; Max-Age=0"])
with patch(
"shared_backend.authclient.urllib.request.urlopen", return_value=response
) as urlopen:
cookies = await self.client.logout("a-token")
self.assertEqual(cookies, ["auth_session=; Max-Age=0"])
request = urlopen.call_args.args[0]
self.assertEqual(request.get_header("Authorization"), "Bearer a-token")
async def test_me_resolves_public_user(self) -> None:
payload = {
"user": {
"id": 3,
"username": "bob",
"email": "bob@example.com",
"role": "admin",
"totp_enabled": False,
}
}
response = _FakeResponse(200, payload)
with patch("shared_backend.authclient.urllib.request.urlopen", return_value=response):
user = await self.client.me("a-token")
self.assertEqual(user.id, 3)
self.assertEqual(user.role, "admin")
async def test_totp_enable_returns_secret(self) -> None:
payload = {"secret": "SECRET", "otpauth_url": "otpauth://...", "enabled": False}
response = _FakeResponse(200, payload)
with patch("shared_backend.authclient.urllib.request.urlopen", return_value=response):
result = await self.client.totp_enable("a-token")
self.assertEqual(result.secret, "SECRET")
self.assertFalse(result.enabled)
async def test_totp_verify_and_disable_send_token(self) -> None:
response = _FakeResponse(200, {"enabled": True})
with patch(
"shared_backend.authclient.urllib.request.urlopen", return_value=response
) as urlopen:
await self.client.totp_verify("a-token", "123456")
sent = json.loads(urlopen.call_args.args[0].data)
self.assertEqual(sent, {"token": "123456"})
response = _FakeResponse(200, {"enabled": False})
with patch(
"shared_backend.authclient.urllib.request.urlopen", return_value=response
) as urlopen:
await self.client.totp_disable("a-token", "654321")
sent = json.loads(urlopen.call_args.args[0].data)
self.assertEqual(sent, {"token": "654321"})
async def test_request_password_reset_targets_superadmin_by_default(self) -> None:
response = _FakeResponse(200, {"ok": True})
with patch(
"shared_backend.authclient.urllib.request.urlopen", return_value=response
) as urlopen:
await self.client.request_password_reset()
sent = json.loads(urlopen.call_args.args[0].data)
self.assertEqual(sent, {})
async def test_confirm_password_reset_sends_code_and_password(self) -> None:
response = _FakeResponse(200, {"ok": True})
with patch(
"shared_backend.authclient.urllib.request.urlopen", return_value=response
) as urlopen:
await self.client.confirm_password_reset("ABCD1234", "a brand new passphrase")
sent = json.loads(urlopen.call_args.args[0].data)
self.assertEqual(sent, {"code": "ABCD1234", "password": "a brand new passphrase"})
async def test_list_managed_users(self) -> None:
payload = {
"users": [
{
"id": 1,
"username": "root",
"email": "root@example.com",
"role": "superadmin",
"created_at": "2026-01-01T00:00:00Z",
},
{
"id": 2,
"username": "bob",
"email": "bob@example.com",
"role": "user",
"created_at": "2026-01-02T00:00:00Z",
},
]
}
response = _FakeResponse(200, payload)
with patch("shared_backend.authclient.urllib.request.urlopen", return_value=response):
users = await self.client.list_managed_users("a-token")
self.assertEqual(len(users), 2)
self.assertEqual(
users[0],
ManagedUser(
id=1,
username="root",
email="root@example.com",
role="superadmin",
created_at="2026-01-01T00:00:00Z",
),
)
async def test_create_managed_user_omits_role_when_not_given(self) -> None:
payload = {
"user": {
"id": 4,
"username": "carol",
"email": "carol@example.com",
"role": "user",
"created_at": "",
}
}
response = _FakeResponse(201, payload)
with patch(
"shared_backend.authclient.urllib.request.urlopen", return_value=response
) as urlopen:
created = await self.client.create_managed_user(
"a-token",
username="carol",
email="carol@example.com",
password="correct horse battery staple",
)
self.assertEqual(created.username, "carol")
sent = json.loads(urlopen.call_args.args[0].data)
self.assertNotIn("role", sent)
async def test_update_managed_user_only_sends_provided_fields(self) -> None:
response = _FakeResponse(200, {"ok": True})
with patch(
"shared_backend.authclient.urllib.request.urlopen", return_value=response
) as urlopen:
await self.client.update_managed_user("a-token", 5, email="new@example.com")
request = urlopen.call_args.args[0]
self.assertEqual(request.get_method(), "PUT")
self.assertTrue(request.full_url.endswith("/api/admin/users/5"))
sent = json.loads(request.data)
self.assertEqual(sent, {"email": "new@example.com"})
async def test_delete_managed_user(self) -> None:
response = _FakeResponse(200, {"ok": True})
with patch(
"shared_backend.authclient.urllib.request.urlopen", return_value=response
) as urlopen:
await self.client.delete_managed_user("a-token", 6)
request = urlopen.call_args.args[0]
self.assertEqual(request.get_method(), "DELETE")
self.assertTrue(request.full_url.endswith("/api/admin/users/6"))
async def test_transport_error_raises_auth_client_error_not_api_error(self) -> None:
transport_error = urllib.error.URLError("connection refused")
with patch("shared_backend.authclient.urllib.request.urlopen", side_effect=transport_error):
with self.assertRaises(AuthClientError) as ctx:
await self.client.setup_status()
self.assertNotIsInstance(ctx.exception, APIError)
if __name__ == "__main__":
unittest.main()
+3 -2
View File
@@ -1,6 +1,6 @@
{ {
"name": "@gabriel20xx/web-ui", "name": "@gabriel20xx/web-ui",
"version": "0.1.0", "version": "0.1.1",
"description": "Shared Svelte UI, layout, authentication, and account components for Gabriel20xx web projects.", "description": "Shared Svelte UI, layout, authentication, and account components for Gabriel20xx web projects.",
"license": "MIT", "license": "MIT",
"type": "module", "type": "module",
@@ -15,7 +15,8 @@
"svelte": "^5.0.0" "svelte": "^5.0.0"
}, },
"dependencies": { "dependencies": {
"@gabriel20xx/design-tokens": "0.1.0" "@gabriel20xx/design-tokens": "0.1.1",
"@lucide/svelte": "1.28.0"
}, },
"devDependencies": { "devDependencies": {
"@sveltejs/package": "^2.5.0", "@sveltejs/package": "^2.5.0",
@@ -7,22 +7,37 @@
brand = 'Application', brand = 'Application',
children, children,
description = '', description = '',
icon,
links = [], links = [],
onClose,
open = $bindable(false), open = $bindable(false),
version = '' version = ''
}: { }: {
brand?: string; brand?: string;
children?: Snippet; children?: Snippet;
description?: string; description?: string;
icon?: Snippet;
links?: AboutLink[]; links?: AboutLink[];
onClose?: () => void | Promise<void>;
open?: boolean; open?: boolean;
version?: string; version?: string;
} = $props(); } = $props();
let wasOpen = false;
$effect(() => {
if (wasOpen && !open) void onClose?.();
wasOpen = open;
});
</script> </script>
<Dialog bind:open title={`About ${brand}`}> <Dialog bind:open title={`About ${brand}`}>
<div class="sc-auth-brand"> <div class="sc-auth-brand">
<span aria-hidden="true" class="sc-brand-mark">{brand.slice(0, 1).toUpperCase()}</span> {#if icon}
{@render icon()}
{:else}
<span aria-hidden="true" class="sc-brand-mark">{brand.slice(0, 1).toUpperCase()}</span>
{/if}
<strong>{brand}</strong> <strong>{brand}</strong>
</div> </div>
@@ -2,47 +2,70 @@
import type { Snippet } from 'svelte'; import type { Snippet } from 'svelte';
import type { NavItem } from '../types'; import type { NavItem } from '../types';
import Header from './Header.svelte'; import Header from './Header.svelte';
import NotificationStack from './NotificationStack.svelte';
import PageHeader from './PageHeader.svelte';
let { let {
aboutHref,
brand = 'Application', brand = 'Application',
brandHref = '/', brandHref = '/',
children, children,
class: className = '', class: className = '',
currentPath = '', currentPath = '',
faviconHref = '/favicon.svg',
headerActions, headerActions,
navItems = [], navItems = [],
onAbout,
onLogout, onLogout,
onNavigate, onNavigate,
onProfile, onProfile,
onSettings, onSettings,
pageHeaderActions,
showPageHeader = true,
showSettings = true, showSettings = true,
theme = 'dark', theme = 'dark',
username = '' username = '',
}: { }: {
aboutHref?: string;
brand?: string; brand?: string;
brandHref?: string; brandHref?: string;
children?: Snippet; children?: Snippet;
class?: string; class?: string;
currentPath?: string; currentPath?: string;
faviconHref?: string;
headerActions?: Snippet; headerActions?: Snippet;
navItems?: NavItem[]; navItems?: NavItem[];
onAbout?: () => void | Promise<void>;
onLogout?: () => void | Promise<void>; onLogout?: () => void | Promise<void>;
onNavigate?: (item: NavItem) => void; onNavigate?: (item: NavItem) => void;
onProfile?: () => void; onProfile?: () => void;
onSettings?: () => void; onSettings?: () => void;
pageHeaderActions?: Snippet;
showPageHeader?: boolean;
showSettings?: boolean; showSettings?: boolean;
theme?: 'dark' | 'light' | 'system'; theme?: 'dark' | 'light' | 'system';
username?: string; username?: string;
} = $props(); } = $props();
const activeNavItem = $derived(
navItems.find((item) =>
item.href === '/' ? currentPath === '/' : currentPath === item.href || currentPath.startsWith(`${item.href}/`),
),
);
</script> </script>
<div class={`sc-root sc-app-shell ${className}`} data-theme={theme === 'system' ? undefined : theme}> <div class={`sc-root sc-app-shell ${className}`} data-theme={theme === 'system' ? undefined : theme}>
<NotificationStack />
<Header <Header
aboutHref={aboutHref ?? navItems.find((item) => item.label.toLowerCase() === 'about')?.href ?? '/about'}
{brand} {brand}
{brandHref} {brandHref}
{currentPath} {currentPath}
{faviconHref}
actions={headerActions} actions={headerActions}
{navItems} {navItems}
{onAbout}
{onLogout} {onLogout}
{onNavigate} {onNavigate}
{onProfile} {onProfile}
@@ -52,6 +75,14 @@
/> />
<main class="sc-main"> <main class="sc-main">
{#if showPageHeader && activeNavItem?.href !== '/about'}
<PageHeader
title={activeNavItem?.label ?? brand}
description={activeNavItem?.description ??
`Explore the ${activeNavItem?.label?.toLowerCase() ?? 'application'} section.`}
actions={pageHeaderActions}
/>
{/if}
{@render children?.()} {@render children?.()}
</main> </main>
</div> </div>
@@ -12,6 +12,7 @@
brand = 'Application', brand = 'Application',
children, children,
error = '', error = '',
faviconHref = '/favicon.svg',
loading = false, loading = false,
onLogin, onLogin,
onConfirmReset, onConfirmReset,
@@ -24,6 +25,7 @@
brand?: string; brand?: string;
children?: Snippet; children?: Snippet;
error?: string; error?: string;
faviconHref?: string;
loading?: boolean; loading?: boolean;
onLogin?: (input: AuthLoginInput) => void | Promise<void>; onLogin?: (input: AuthLoginInput) => void | Promise<void>;
onConfirmReset?: AuthResetConfirm; onConfirmReset?: AuthResetConfirm;
@@ -39,6 +41,7 @@
let identifier = $state(''); let identifier = $state('');
let password = $state(''); let password = $state('');
let totpToken = $state(''); let totpToken = $state('');
let totpRequired = $state(false);
let confirmPassword = $state(''); let confirmPassword = $state('');
let submitError = $state(''); let submitError = $state('');
let submitting = $state(false); let submitting = $state(false);
@@ -47,11 +50,27 @@
let resetOpen = $state(false); let resetOpen = $state(false);
let resetting = $state(false); let resetting = $state(false);
// A failed status fetch tells us nothing about whether setup is actually required —
// defaulting to the setup view in that case would wrongly invite creating a new
// account when the real problem is that the server couldn't be reached.
let effectiveSetupRequired = $derived(error ? false : setupRequired);
function isTotpChallenge(caught: unknown): boolean {
if (!(caught instanceof Error)) return false;
const message = caught.message.toLowerCase();
return (
message.includes('two-factor authentication code required') ||
message.includes('multi-factor authentication code required') ||
(message.includes('totp') && message.includes('required')) ||
(message.includes('mfa') && message.includes('required'))
);
}
async function submit(event: SubmitEvent): Promise<void> { async function submit(event: SubmitEvent): Promise<void> {
event.preventDefault(); event.preventDefault();
submitError = ''; submitError = '';
if (setupRequired && password !== confirmPassword) { if (effectiveSetupRequired && password !== confirmPassword) {
submitError = 'Passwords do not match.'; submitError = 'Passwords do not match.';
return; return;
} }
@@ -59,15 +78,28 @@
submitting = true; submitting = true;
try { try {
if (setupRequired) { if (effectiveSetupRequired) {
if (!onSetup) throw new Error('The application has not configured its setup handler.'); if (!onSetup) throw new Error('The application has not configured its setup handler.');
await onSetup({ username, email, password }); await onSetup({ username, email, password });
} else { } else {
if (!onLogin) throw new Error('The application has not configured its login handler.'); if (!onLogin) throw new Error('The application has not configured its login handler.');
if (totpRequired && !totpToken.trim()) {
submitError = 'Enter the six-digit authenticator code to continue.';
return;
}
await onLogin({ identifier, password, totpToken: totpToken.trim() }); await onLogin({ identifier, password, totpToken: totpToken.trim() });
} }
} catch (caught) { } catch (caught) {
submitError = caught instanceof Error ? caught.message : 'Authentication failed.'; if (!effectiveSetupRequired && showTotp && isTotpChallenge(caught)) {
totpRequired = true;
submitError = 'Enter the six-digit authenticator code to continue.';
} else {
if (!effectiveSetupRequired) {
totpRequired = false;
totpToken = '';
}
submitError = caught instanceof Error ? caught.message : 'Authentication failed.';
}
} finally { } finally {
submitting = false; submitting = false;
} }
@@ -107,19 +139,24 @@
</script> </script>
<div class="sc-root sc-auth-page"> <div class="sc-root sc-auth-page">
<section aria-labelledby="sc-auth-title" class="sc-auth-card"> <section aria-busy={loading} aria-labelledby="sc-auth-title" class="sc-auth-card">
<div class="sc-auth-brand"> <div class="sc-auth-brand">
<span aria-hidden="true" class="sc-brand-mark">{brand.slice(0, 1).toUpperCase()}</span> <img alt="" aria-hidden="true" class="sc-auth-brand-icon" src={faviconHref} />
<span>{brand}</span> <span>{brand}</span>
</div> </div>
<h1 id="sc-auth-title">{setupRequired ? 'Create your account' : 'Welcome back'}</h1> {#if loading}
<h1 id="sc-auth-title">Loading...</h1>
{:else}
<h1 id="sc-auth-title">{effectiveSetupRequired ? 'Create your account' : 'Welcome back'}</h1>
{/if}
{#if !loading}
{#if tagline} {#if tagline}
<p class="sc-auth-subtitle">{tagline}</p> <p class="sc-auth-subtitle">{tagline}</p>
{/if} {/if}
<form class="sc-form sc-auth-form" onsubmit={submit}> <form class="sc-form sc-auth-form" onsubmit={submit}>
{#if setupRequired} {#if effectiveSetupRequired}
<label class="sc-field"> <label class="sc-field">
<span class="sc-label">Username</span> <span class="sc-label">Username</span>
<input <input
@@ -160,7 +197,7 @@
<label class="sc-field"> <label class="sc-field">
<span class="sc-label">Password</span> <span class="sc-label">Password</span>
<input <input
autocomplete={setupRequired ? 'new-password' : 'current-password'} autocomplete={effectiveSetupRequired ? 'new-password' : 'current-password'}
class="sc-input" class="sc-input"
minlength="8" minlength="8"
name="password" name="password"
@@ -170,9 +207,9 @@
/> />
</label> </label>
{#if showTotp && !setupRequired} {#if showTotp && !effectiveSetupRequired && totpRequired}
<label class="sc-field"> <label class="sc-field">
<span class="sc-label">Authenticator code <span class="sc-label-optional">(if enabled)</span></span> <span class="sc-label">Authenticator code</span>
<input <input
autocomplete="one-time-code" autocomplete="one-time-code"
class="sc-input" class="sc-input"
@@ -184,7 +221,7 @@
</label> </label>
{/if} {/if}
{#if setupRequired} {#if effectiveSetupRequired}
<label class="sc-field"> <label class="sc-field">
<span class="sc-label">Confirm password</span> <span class="sc-label">Confirm password</span>
<input <input
@@ -204,7 +241,7 @@
{/if} {/if}
<Button disabled={loading || submitting} fullWidth size="lg" type="submit"> <Button disabled={loading || submitting} fullWidth size="lg" type="submit">
{loading || submitting ? 'Please wait…' : setupRequired ? 'Create account' : 'Log in'} {loading || submitting ? 'Please wait…' : effectiveSetupRequired ? 'Create account' : 'Log in'}
</Button> </Button>
</form> </form>
@@ -212,7 +249,7 @@
<div class="sc-auth-extra">{@render children()}</div> <div class="sc-auth-extra">{@render children()}</div>
{/if} {/if}
{#if !setupRequired && onRequestReset && onConfirmReset} {#if !effectiveSetupRequired && onRequestReset && onConfirmReset}
{#if resetOpen} {#if resetOpen}
<div class="sc-auth-reset" aria-live="polite"> <div class="sc-auth-reset" aria-live="polite">
<p class="sc-auth-reset-hint">A reset code has been printed to the server console.</p> <p class="sc-auth-reset-hint">A reset code has been printed to the server console.</p>
@@ -241,5 +278,6 @@
</button> </button>
{/if} {/if}
{/if} {/if}
{/if}
</section> </section>
</div> </div>
@@ -1,19 +1,21 @@
<script lang="ts"> <script lang="ts">
import type { HTMLAttributes } from 'svelte/elements';
import type { Snippet } from 'svelte'; import type { Snippet } from 'svelte';
type BadgeVariant = 'default' | 'success' | 'warning' | 'danger'; type BadgeVariant = 'default' | 'primary' | 'success' | 'warning' | 'danger';
let { let {
children, children,
class: className = '', class: className = '',
variant = 'default' variant = 'default',
}: { ...rest
}: Omit<HTMLAttributes<HTMLSpanElement>, 'class'> & {
children?: Snippet; children?: Snippet;
class?: string; class?: string;
variant?: BadgeVariant; variant?: BadgeVariant;
} = $props(); } = $props();
</script> </script>
<span class={`sc-badge ${className}`} data-variant={variant}> <span class={`sc-badge ${className}`} data-variant={variant} {...rest}>
{@render children?.()} {@render children?.()}
</span> </span>
@@ -1,8 +1,9 @@
<script lang="ts"> <script lang="ts">
import type { HTMLButtonAttributes } from 'svelte/elements';
import type { Snippet } from 'svelte'; import type { Snippet } from 'svelte';
type ButtonVariant = 'primary' | 'secondary' | 'ghost' | 'danger'; type ButtonVariant = 'primary' | 'secondary' | 'outline' | 'ghost' | 'danger';
type ButtonSize = 'sm' | 'md' | 'lg'; type ButtonSize = 'sm' | 'md' | 'lg' | 'icon';
let { let {
children, children,
@@ -12,8 +13,9 @@
onclick, onclick,
size = 'md', size = 'md',
type = 'button', type = 'button',
variant = 'primary' variant = 'primary',
}: { ...rest
}: Omit<HTMLButtonAttributes, 'class' | 'disabled' | 'onclick' | 'type'> & {
children?: Snippet; children?: Snippet;
class?: string; class?: string;
disabled?: boolean; disabled?: boolean;
@@ -30,6 +32,7 @@
{disabled} {disabled}
{onclick} {onclick}
{type} {type}
{...rest}
> >
{@render children?.()} {@render children?.()}
</button> </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>
+209 -16
View File
@@ -1,34 +1,153 @@
<script lang="ts"> <script lang="ts">
import {
Activity,
Archive,
BarChart3,
Bot,
Box,
CircleAlert,
CircleHelp,
CircleUserRound,
CloudDownload,
Database,
FileCog,
FolderOpen,
Gamepad2,
GalleryHorizontalEnd,
HardDrive,
Image,
Info,
LayoutDashboard,
ListVideo,
LogOut,
Logs,
Magnet,
Map,
MapPinned,
MessageCircle,
MonitorPlay,
Play,
Plug,
RefreshCw,
ScanSearch,
ScrollText,
Send,
Server,
Settings2,
ShieldCheck,
SlidersHorizontal,
Sparkles,
Tags,
Upload,
Users,
WandSparkles,
Workflow,
Wrench,
} from '@lucide/svelte';
import type { Snippet } from 'svelte'; import type { Snippet } from 'svelte';
import type { NavItem } from '../types'; import type { NavItem } from '../types';
const icons: Record<string, typeof LayoutDashboard> = {
activity: Activity,
archive: Archive,
'bar-chart-3': BarChart3,
bot: Bot,
box: Box,
'circle-alert': CircleAlert,
'circle-help': CircleHelp,
'cloud-download': CloudDownload,
database: Database,
'file-cog': FileCog,
'folder-open': FolderOpen,
gamepad: Gamepad2,
'gallery-horizontal-end': GalleryHorizontalEnd,
'hard-drive': HardDrive,
image: Image,
info: Info,
'layout-dashboard': LayoutDashboard,
'list-video': ListVideo,
logs: Logs,
magnet: Magnet,
map: Map,
'map-pinned': MapPinned,
'message-circle': MessageCircle,
'monitor-play': MonitorPlay,
play: Play,
plug: Plug,
'refresh-cw': RefreshCw,
'scan-search': ScanSearch,
'scroll-text': ScrollText,
send: Send,
server: Server,
'settings-2': Settings2,
'shield-check': ShieldCheck,
'sliders-horizontal': SlidersHorizontal,
sparkles: Sparkles,
tags: Tags,
upload: Upload,
users: Users,
'wand-sparkles': WandSparkles,
workflow: Workflow,
wrench: Wrench,
};
let { let {
aboutHref = '/about',
brand = 'Application', brand = 'Application',
brandHref = '/', brandHref = '/',
currentPath = '', currentPath = '',
faviconHref = '/favicon.svg',
navItems = [], navItems = [],
actions, actions,
onAbout,
onLogout, onLogout,
onNavigate, onNavigate,
onProfile, onProfile,
onSettings, onSettings,
showSettings = true, showSettings = true,
username = '' username = '',
}: { }: {
aboutHref?: string;
brand?: string; brand?: string;
brandHref?: string; brandHref?: string;
currentPath?: string; currentPath?: string;
faviconHref?: string;
navItems?: NavItem[]; navItems?: NavItem[];
actions?: Snippet; actions?: Snippet;
onAbout?: () => void | Promise<void>;
onLogout?: () => void | Promise<void>; onLogout?: () => void | Promise<void>;
onNavigate?: (item: NavItem) => void; onNavigate?: (item: NavItem) => void;
onProfile?: () => void; onProfile?: () => void | Promise<void>;
onSettings?: () => void; onSettings?: () => void | Promise<void>;
showSettings?: boolean; showSettings?: boolean;
username?: string; username?: string;
} = $props(); } = $props();
let navOpen = $state(false); let navOpen = $state(false);
let profileOpen = $state(false);
const hasProfileMenu = $derived(
Boolean(username && (onProfile || (showSettings && onSettings) || onAbout || aboutHref || onLogout)),
);
function closeMenus(): void {
navOpen = false;
profileOpen = false;
}
function handleWindowKeydown(event: KeyboardEvent): void {
if (event.key === 'Escape') closeMenus();
}
function handleWindowClick(event: MouseEvent): void {
if (event.target instanceof Element && !event.target.closest('[data-profile-menu]')) {
profileOpen = false;
}
}
function iconFor(item: NavItem) {
return icons[item.icon ?? 'layout-dashboard'] ?? LayoutDashboard;
}
function isActive(item: NavItem): boolean { function isActive(item: NavItem): boolean {
return item.href === '/' return item.href === '/'
@@ -37,14 +156,17 @@
} }
</script> </script>
<svelte:window onclick={handleWindowClick} onkeydown={handleWindowKeydown} />
<header class="sc-header"> <header class="sc-header">
<a class="sc-brand" href={brandHref} onclick={() => (navOpen = false)}> <a class="sc-brand" href={brandHref} onclick={closeMenus}>
<span aria-hidden="true" class="sc-brand-mark">{brand.slice(0, 1).toUpperCase()}</span> <img alt="" class="sc-brand-icon" src={faviconHref} />
<span>{brand}</span> <span>{brand}</span>
</a> </a>
<nav aria-label="Primary navigation" class="sc-nav" data-open={navOpen}> <nav aria-label="Primary navigation" class="sc-nav" data-open={navOpen}>
{#each navItems as item} {#each navItems as item}
{@const Icon = iconFor(item)}
<a <a
aria-current={isActive(item) ? 'page' : undefined} aria-current={isActive(item) ? 'page' : undefined}
class="sc-nav-link" class="sc-nav-link"
@@ -55,9 +177,10 @@
event.preventDefault(); event.preventDefault();
onNavigate(item); onNavigate(item);
} }
navOpen = false; closeMenus();
}} }}
> >
<Icon aria-hidden="true" class="sc-nav-icon" size={16} strokeWidth={2} />
{item.label} {item.label}
</a> </a>
{/each} {/each}
@@ -66,18 +189,88 @@
<div class="sc-header-actions"> <div class="sc-header-actions">
{#if actions}{@render actions()}{/if} {#if actions}{@render actions()}{/if}
{#if showSettings && onSettings} {#if hasProfileMenu}
<button aria-label="Open settings" class="sc-icon-button" type="button" onclick={onSettings}>⚙</button> <div class="sc-profile-menu" data-profile-menu>
{/if} <button
aria-expanded={profileOpen}
aria-haspopup="menu"
class="sc-profile-button"
type="button"
onclick={() => (profileOpen = !profileOpen)}
>
<CircleUserRound aria-hidden="true" class="sc-profile-icon" size={16} strokeWidth={2} />
<span>{username}</span>
</button>
{#if username && onProfile} {#if profileOpen}
<button class="sc-profile-button" type="button" onclick={onProfile}>{username}</button> <div aria-label="Account menu" class="sc-profile-dropdown" role="menu">
{/if} {#if onProfile}
<button
class="sc-profile-menu-item"
role="menuitem"
type="button"
onclick={() => {
profileOpen = false;
void onProfile?.();
}}
>
<CircleUserRound aria-hidden="true" size={15} strokeWidth={2} />
Profile
</button>
{/if}
{#if onLogout} {#if showSettings && onSettings}
<button class="sc-button sc-button-ghost sc-button-sm" type="button" onclick={() => void onLogout?.()}> <button
Log out class="sc-profile-menu-item"
</button> role="menuitem"
type="button"
onclick={() => {
profileOpen = false;
void onSettings?.();
}}
>
<Settings2 aria-hidden="true" size={15} strokeWidth={2} />
Settings
</button>
{/if}
{#if onAbout}
<button
class="sc-profile-menu-item"
role="menuitem"
type="button"
onclick={() => {
profileOpen = false;
void onAbout?.();
}}
>
<Info aria-hidden="true" size={15} strokeWidth={2} />
About
</button>
{:else if aboutHref}
<a class="sc-profile-menu-item" href={aboutHref} role="menuitem" onclick={() => (profileOpen = false)}>
<Info aria-hidden="true" size={15} strokeWidth={2} />
About
</a>
{/if}
{#if onLogout}
<button
class="sc-profile-menu-item"
role="menuitem"
type="button"
onclick={() => {
profileOpen = false;
void onLogout?.();
}}
>
<LogOut aria-hidden="true" size={15} strokeWidth={2} />
Log out
</button>
{/if}
</div>
{/if}
</div>
{/if} {/if}
<button <button
@@ -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,31 @@
<script lang="ts">
import { CircleAlert, CircleCheck, Info, OctagonAlert, X } from '@lucide/svelte';
import { fly } from 'svelte/transition';
import { notifications } from '../notifications.svelte';
import type { NotificationVariant } from '../notifications.svelte';
const icons: Record<NotificationVariant, typeof Info> = {
success: CircleCheck,
error: OctagonAlert,
warning: CircleAlert,
info: Info
};
</script>
<div aria-live="polite" class="sc-notification-stack" role="status">
{#each notifications.entries as entry (entry.id)}
{@const Icon = icons[entry.variant]}
<div class="sc-notification" data-variant={entry.variant} transition:fly={{ y: -12, duration: 180 }}>
<Icon aria-hidden="true" class="sc-notification-icon" size={18} />
<p class="sc-notification-message">{entry.message}</p>
<button
aria-label="Dismiss notification"
class="sc-notification-close"
type="button"
onclick={() => notifications.dismiss(entry.id)}
>
<X aria-hidden="true" size={16} />
</button>
</div>
{/each}
</div>
@@ -0,0 +1,100 @@
<script lang="ts">
import { ChevronFirst, ChevronLast, ChevronLeft, ChevronRight } from '@lucide/svelte';
const PAGE_SIZE_OPTIONS = [12, 24, 48, 96];
export type PaginationChange = {
page: number;
pageSize: number;
};
let {
page,
pageSize = 24,
pageLength = 0,
totalLength = 0,
onPaging
}: {
page: number;
pageSize?: number;
pageLength?: number;
totalLength?: number;
onPaging: (change: PaginationChange) => void;
} = $props();
const pageCount = $derived(Math.max(1, Math.ceil(totalLength / pageSize)));
const currentPage = $derived(Math.min(Math.max(1, page), pageCount));
const firstItemIndex = $derived(totalLength === 0 ? 0 : (currentPage - 1) * pageSize + 1);
const lastItemIndex = $derived(
totalLength === 0 ? 0 : Math.min(totalLength, (currentPage - 1) * pageSize + pageLength)
);
const hasPreviousPage = $derived(currentPage > 1);
const hasNextPage = $derived(currentPage < pageCount);
function goToPage(nextPage: number) {
onPaging({ page: Math.min(pageCount, Math.max(1, nextPage)), pageSize });
}
function changePageSize(event: Event) {
const nextPageSize = Number((event.currentTarget as HTMLSelectElement).value);
if (PAGE_SIZE_OPTIONS.includes(nextPageSize)) {
onPaging({ page: 1, pageSize: nextPageSize });
}
}
</script>
<nav class="sc-pagination" aria-label="Pagination">
<select
class="sc-pagination-page-size"
aria-label="Items per page"
value={String(pageSize)}
onchange={changePageSize}
>
{#each PAGE_SIZE_OPTIONS as option}
<option value={option}>{option}</option>
{/each}
</select>
<p class="sc-pagination-info">
{firstItemIndex.toLocaleString()}–{lastItemIndex.toLocaleString()} of {totalLength.toLocaleString()}
</p>
<div class="sc-pagination-controls">
<button
type="button"
class="sc-pagination-button"
aria-label="First page"
disabled={!hasPreviousPage}
onclick={() => goToPage(1)}
>
<ChevronFirst aria-hidden="true" size={16} />
</button>
<button
type="button"
class="sc-pagination-button"
aria-label="Previous page"
disabled={!hasPreviousPage}
onclick={() => goToPage(currentPage - 1)}
>
<ChevronLeft aria-hidden="true" size={16} />
</button>
<button
type="button"
class="sc-pagination-button"
aria-label="Next page"
disabled={!hasNextPage}
onclick={() => goToPage(currentPage + 1)}
>
<ChevronRight aria-hidden="true" size={16} />
</button>
<button
type="button"
class="sc-pagination-button"
aria-label="Last page"
disabled={!hasNextPage}
onclick={() => goToPage(pageCount)}
>
<ChevronLast aria-hidden="true" size={16} />
</button>
</div>
</nav>
@@ -1,51 +1,27 @@
<script lang="ts"> <script lang="ts">
import type { import type { ProfileUpdateInput, TotpSetupRequest, TotpStatusRequest, TotpTokenAction } from '../types';
ProfileUpdateInput,
TotpSetupRequest,
TotpStatusRequest,
TotpTokenAction,
UserCreateRequest,
UserDeleteRequest,
UserId,
UserListRequest,
UserRole,
UserUpdateRequest
} from '../types';
import Button from './Button.svelte'; import Button from './Button.svelte';
import Dialog from './Dialog.svelte'; import Dialog from './Dialog.svelte';
import TotpSettings from './TotpSettings.svelte'; import TotpSettings from './TotpSettings.svelte';
import UserManagement from './UserManagement.svelte';
let { let {
currentEmail = '', currentEmail = '',
currentRole = 'user',
currentUserId,
onCreateUser,
onDeleteUser,
onListUsers,
currentUsername = '', currentUsername = '',
onSave, onSave,
onTotpDisable, onTotpDisable,
onTotpEnable, onTotpEnable,
onTotpSetup, onTotpSetup,
onTotpStatus, onTotpStatus,
onUpdateUser,
totpEnabled = false, totpEnabled = false,
open = $bindable(false) open = $bindable(false)
}: { }: {
currentEmail?: string; currentEmail?: string;
currentRole?: UserRole;
currentUserId?: UserId;
onCreateUser?: UserCreateRequest;
onDeleteUser?: UserDeleteRequest;
onListUsers?: UserListRequest;
currentUsername?: string; currentUsername?: string;
onSave?: (input: ProfileUpdateInput) => void | Promise<void>; onSave?: (input: ProfileUpdateInput) => void | Promise<void>;
onTotpDisable?: TotpTokenAction; onTotpDisable?: TotpTokenAction;
onTotpEnable?: TotpTokenAction; onTotpEnable?: TotpTokenAction;
onTotpSetup?: TotpSetupRequest; onTotpSetup?: TotpSetupRequest;
onTotpStatus?: TotpStatusRequest; onTotpStatus?: TotpStatusRequest;
onUpdateUser?: UserUpdateRequest;
totpEnabled?: boolean; totpEnabled?: boolean;
open?: boolean; open?: boolean;
} = $props(); } = $props();
@@ -158,13 +134,4 @@
enabled={totpEnabled} enabled={totpEnabled}
/> />
{/if} {/if}
<UserManagement
currentRole={currentRole}
currentUserId={currentUserId}
onCreate={onCreateUser}
onDelete={onDeleteUser}
onList={onListUsers}
onUpdate={onUpdateUser}
/>
</Dialog> </Dialog>
@@ -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>
@@ -1,36 +1,15 @@
<script lang="ts"> <script lang="ts">
import type { Snippet } from 'svelte'; import type { Snippet } from 'svelte';
import type {
UserCreateRequest,
UserDeleteRequest,
UserId,
UserListRequest,
UserRole,
UserUpdateRequest
} from '../types';
import Dialog from './Dialog.svelte'; import Dialog from './Dialog.svelte';
import UserManagement from './UserManagement.svelte';
let { let {
children, children,
description = '', description = '',
currentRole = 'user',
currentUserId,
onCreateUser,
onDeleteUser,
onListUsers,
onUpdateUser,
open = $bindable(false), open = $bindable(false),
title = 'Settings' title = 'Settings'
}: { }: {
children?: Snippet; children?: Snippet;
description?: string; description?: string;
currentRole?: UserRole;
currentUserId?: UserId;
onCreateUser?: UserCreateRequest;
onDeleteUser?: UserDeleteRequest;
onListUsers?: UserListRequest;
onUpdateUser?: UserUpdateRequest;
open?: boolean; open?: boolean;
title?: string; title?: string;
} = $props(); } = $props();
@@ -42,12 +21,4 @@
{:else} {:else}
<p class="sc-muted">No settings have been configured for this application yet.</p> <p class="sc-muted">No settings have been configured for this application yet.</p>
{/if} {/if}
<UserManagement
currentRole={currentRole}
currentUserId={currentUserId}
onCreate={onCreateUser}
onDelete={onDeleteUser}
onList={onListUsers}
onUpdate={onUpdateUser}
/>
</Dialog> </Dialog>
@@ -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} />
@@ -45,6 +45,12 @@
return canAssignAdmin && role ? role : 'user'; return canAssignAdmin && role ? role : 'user';
} }
function formatLastLogin(value: string | null | undefined): string {
if (!value) return 'Never';
const parsed = new Date(value);
return Number.isNaN(parsed.getTime()) ? 'Never' : parsed.toLocaleString();
}
async function loadUsers(): Promise<void> { async function loadUsers(): Promise<void> {
if (!onList || !canManage) return; if (!onList || !canManage) return;
loading = true; loading = true;
@@ -183,6 +189,7 @@
<div class="sc-user-row"> <div class="sc-user-row">
<div><strong>{user.username}</strong><span>{user.email}</span></div> <div><strong>{user.username}</strong><span>{user.email}</span></div>
<span class="sc-user-role">{user.role}</span> <span class="sc-user-role">{user.role}</span>
<span class="sc-muted sc-user-last-login" title="Last login">{formatLastLogin(user.lastLoginAt)}</span>
<div class="sc-user-actions"> <div class="sc-user-actions">
<Button disabled={saving} size="sm" type="button" variant="secondary" onclick={() => startEditing(user)}>Edit</Button> <Button disabled={saving} size="sm" type="button" variant="secondary" onclick={() => startEditing(user)}>Edit</Button>
<Button disabled={saving || String(user.id) === String(currentUserId) || user.role === 'superadmin'} size="sm" type="button" variant="danger" onclick={() => void deleteUser(user)}>Remove</Button> <Button disabled={saving || String(user.id) === String(currentUserId) || user.role === 'superadmin'} size="sm" type="button" variant="danger" onclick={() => void deleteUser(user)}>Remove</Button>
+12
View File
@@ -5,12 +5,21 @@ export { default as Badge } from './components/Badge.svelte';
export { default as Button } from './components/Button.svelte'; export { default as Button } from './components/Button.svelte';
export { default as Card } from './components/Card.svelte'; export { default as Card } from './components/Card.svelte';
export { default as Dialog } from './components/Dialog.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 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 PageHeader } from './components/PageHeader.svelte';
export { default as Pagination } from './components/Pagination.svelte';
export { default as ProfileDialog } from './components/ProfileDialog.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 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 TotpSettings } from './components/TotpSettings.svelte';
export { default as UserManagement } from './components/UserManagement.svelte'; export { default as UserManagement } from './components/UserManagement.svelte';
export { notifications, notify } from './notifications.svelte';
export type { NotificationEntry, NotificationVariant } from './notifications.svelte';
export type { export type {
AboutLink, AboutLink,
AsyncAction, AsyncAction,
@@ -22,6 +31,9 @@ export type {
NavItem, NavItem,
ProfileUpdateInput, ProfileUpdateInput,
ManagedUser, ManagedUser,
StatusLevel,
StatusProbe,
StatusSnapshot,
UserCreateInput, UserCreateInput,
UserCreateRequest, UserCreateRequest,
UserDeleteRequest, UserDeleteRequest,
@@ -0,0 +1,54 @@
export type NotificationVariant = "success" | "error" | "warning" | "info";
export interface NotificationEntry {
id: number;
variant: NotificationVariant;
message: string;
duration: number;
}
const DEFAULT_DURATION = 5000;
let entries = $state<NotificationEntry[]>([]);
let nextId = 0;
const timeouts = new Map<number, ReturnType<typeof setTimeout>>();
function dismissNotification(id: number): void {
const timeout = timeouts.get(id);
if (timeout !== undefined) {
clearTimeout(timeout);
timeouts.delete(id);
}
entries = entries.filter((entry) => entry.id !== id);
}
function pushNotification(
variant: NotificationVariant,
message: string,
duration: number = DEFAULT_DURATION,
): number {
const id = ++nextId;
entries = [...entries, { id, variant, message, duration }];
if (duration > 0) {
timeouts.set(
id,
setTimeout(() => dismissNotification(id), duration),
);
}
return id;
}
export const notifications = {
get entries() {
return entries;
},
dismiss: dismissNotification,
};
export const notify = {
success: (message: string, duration?: number) => pushNotification("success", message, duration),
error: (message: string, duration?: number) => pushNotification("error", message, duration),
warning: (message: string, duration?: number) => pushNotification("warning", message, duration),
info: (message: string, duration?: number) => pushNotification("info", message, duration),
dismiss: dismissNotification,
};
+395 -14
View File
@@ -1,4 +1,4 @@
@import '@gabriel20xx/design-tokens/theme.css'; @import "@gabriel20xx/design-tokens/theme.css";
:where(.sc-root, .sc-root *) { :where(.sc-root, .sc-root *) {
box-sizing: border-box; box-sizing: border-box;
@@ -31,7 +31,7 @@
.sc-main { .sc-main {
width: min(100% - 2rem, 90rem); width: min(100% - 2rem, 90rem);
margin: 0 auto; margin: 0 auto;
padding: 2rem 0 3rem; padding: 1rem 0 1rem;
} }
.sc-header { .sc-header {
@@ -62,6 +62,7 @@
} }
.sc-brand-mark { .sc-brand-mark {
overflow: hidden;
display: grid; display: grid;
width: 2rem; width: 2rem;
height: 2rem; height: 2rem;
@@ -73,6 +74,18 @@
font-weight: 800; font-weight: 800;
} }
.sc-brand-icon {
/* Fixed instead of percentage-based: the icon isn't wrapped in a sized container (unlike
.sc-brand-mark, which this rule mirrors), and .sc-brand's own width is content-driven, so
a percentage here has no definite box to resolve against and lets the image render at
whatever intrinsic size its source happens to have. */
width: 2rem;
height: 2rem;
padding: 0.25rem;
object-fit: contain;
border-radius: var(--sc-radius-md);
}
.sc-nav { .sc-nav {
display: flex; display: flex;
flex: 1 1 auto; flex: 1 1 auto;
@@ -85,7 +98,17 @@
.sc-icon-button { .sc-icon-button {
border: 1px solid transparent; border: 1px solid transparent;
border-radius: var(--sc-radius-md); border-radius: var(--sc-radius-md);
transition: color 140ms ease, background 140ms ease, border-color 140ms ease; transition:
color 140ms ease,
background 140ms ease,
border-color 140ms ease;
}
.sc-nav-link,
.sc-profile-button {
display: inline-flex;
align-items: center;
gap: 0.4rem;
} }
.sc-nav-link { .sc-nav-link {
@@ -96,7 +119,7 @@
} }
.sc-nav-link:hover, .sc-nav-link:hover,
.sc-nav-link[data-active='true'] { .sc-nav-link[data-active="true"] {
color: var(--sc-fg); color: var(--sc-fg);
background: var(--sc-surface-hover); background: var(--sc-surface-hover);
border-color: var(--sc-border); border-color: var(--sc-border);
@@ -129,6 +152,54 @@
font-size: 0.875rem; font-size: 0.875rem;
} }
.sc-profile-menu {
position: relative;
}
.sc-profile-dropdown {
position: absolute;
top: calc(100% + 0.5rem);
right: 0;
z-index: 20;
display: grid;
min-width: 11rem;
gap: 0.125rem;
padding: 0.375rem;
background: var(--sc-surface);
border: 1px solid var(--sc-border);
border-radius: var(--sc-radius-md);
box-shadow: var(--sc-shadow-lg);
}
.sc-profile-menu-item {
display: flex;
width: 100%;
align-items: center;
gap: 0.5rem;
padding: 0.625rem 0.75rem;
color: var(--sc-muted-fg);
background: transparent;
border: 0;
border-radius: var(--sc-radius-sm);
font: inherit;
font-size: 0.875rem;
text-align: left;
text-decoration: none;
cursor: pointer;
}
/* The About item falls back to an <a> when no onAbout handler is wired, unlike the other
button-based items - without this, the browser's default a:visited color (higher specificity
than the class color above) makes it drift from the other dropdown items' color once clicked. */
.sc-profile-menu-item:visited {
color: var(--sc-muted-fg);
}
.sc-profile-menu-item:hover {
color: var(--sc-fg);
background: var(--sc-surface-hover);
}
.sc-icon-button:hover, .sc-icon-button:hover,
.sc-profile-button:hover { .sc-profile-button:hover {
color: var(--sc-fg); color: var(--sc-fg);
@@ -145,7 +216,12 @@
align-items: flex-start; align-items: flex-start;
justify-content: space-between; justify-content: space-between;
gap: 1rem; gap: 1rem;
margin-bottom: 1.5rem; margin-bottom: 1rem;
padding: 1rem 1.25rem;
background: var(--sc-surface);
border: 1px solid var(--sc-border);
border-radius: var(--sc-radius-lg);
box-shadow: var(--sc-shadow-sm);
} }
.sc-page-header h1, .sc-page-header h1,
@@ -209,19 +285,25 @@
font-weight: 650; font-weight: 650;
} }
.sc-badge[data-variant='success'] { .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); color: var(--sc-success-fg);
background: var(--sc-success); background: var(--sc-success);
border-color: transparent; border-color: transparent;
} }
.sc-badge[data-variant='warning'] { .sc-badge[data-variant="warning"] {
color: var(--sc-warning-fg); color: var(--sc-warning-fg);
background: var(--sc-warning); background: var(--sc-warning);
border-color: transparent; border-color: transparent;
} }
.sc-badge[data-variant='danger'] { .sc-badge[data-variant="danger"] {
color: var(--sc-danger-fg); color: var(--sc-danger-fg);
background: var(--sc-danger); background: var(--sc-danger);
border-color: transparent; border-color: transparent;
@@ -240,7 +322,11 @@
font-weight: 650; font-weight: 650;
line-height: 1; line-height: 1;
cursor: pointer; cursor: pointer;
transition: color 140ms ease, background 140ms ease, border-color 140ms ease, opacity 140ms ease; transition:
color 140ms ease,
background 140ms ease,
border-color 140ms ease,
opacity 140ms ease;
} }
.sc-button:hover:not(:disabled) { .sc-button:hover:not(:disabled) {
@@ -255,6 +341,7 @@
.sc-button:focus-visible, .sc-button:focus-visible,
.sc-icon-button:focus-visible, .sc-icon-button:focus-visible,
.sc-profile-button:focus-visible, .sc-profile-button:focus-visible,
.sc-profile-menu-item:focus-visible,
.sc-nav-link:focus-visible, .sc-nav-link:focus-visible,
.sc-dialog-close:focus-visible { .sc-dialog-close:focus-visible {
outline: 3px solid color-mix(in srgb, var(--sc-ring) 45%, transparent); outline: 3px solid color-mix(in srgb, var(--sc-ring) 45%, transparent);
@@ -299,6 +386,16 @@
background: var(--sc-danger-hover); 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 { .sc-button-sm {
min-height: 2rem; min-height: 2rem;
padding: 0.45rem 0.75rem; padding: 0.45rem 0.75rem;
@@ -310,6 +407,187 @@
padding: 0.75rem 1.25rem; 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 { .sc-button-full {
width: 100%; width: 100%;
} }
@@ -406,7 +684,9 @@
border: 1px solid var(--sc-border); border: 1px solid var(--sc-border);
border-radius: var(--sc-radius-md); border-radius: var(--sc-radius-md);
outline: none; outline: none;
transition: border-color 140ms ease, box-shadow 140ms ease; transition:
border-color 140ms ease,
box-shadow 140ms ease;
} }
.sc-textarea { .sc-textarea {
@@ -520,6 +800,12 @@
text-transform: capitalize; text-transform: capitalize;
} }
.sc-user-last-login {
flex-shrink: 0;
font-size: 0.8rem;
white-space: nowrap;
}
.sc-user-actions { .sc-user-actions {
display: flex; display: flex;
flex-shrink: 0; flex-shrink: 0;
@@ -558,7 +844,11 @@
padding: 1.5rem; padding: 1.5rem;
color: var(--sc-fg); color: var(--sc-fg);
background: background:
radial-gradient(circle at 15% 10%, color-mix(in srgb, var(--sc-primary) 18%, transparent), transparent 35%), radial-gradient(
circle at 15% 10%,
color-mix(in srgb, var(--sc-primary) 18%, transparent),
transparent 35%
),
var(--sc-bg); var(--sc-bg);
} }
@@ -579,6 +869,14 @@
font-weight: 750; font-weight: 750;
} }
.sc-auth-brand-icon {
display: block;
width: 2rem;
height: 2rem;
object-fit: contain;
border-radius: var(--sc-radius-md);
}
.sc-auth-card h1 { .sc-auth-card h1 {
font-size: 1.7rem; font-size: 1.7rem;
} }
@@ -622,6 +920,86 @@
color: var(--sc-fg); color: var(--sc-fg);
} }
.sc-notification-stack {
position: fixed;
z-index: 200;
top: 1rem;
right: 1rem;
display: grid;
gap: 0.625rem;
width: min(100% - 2rem, 24rem);
pointer-events: none;
}
.sc-notification {
display: flex;
align-items: flex-start;
gap: 0.625rem;
padding: 0.875rem 1rem;
color: var(--sc-fg);
background: var(--sc-surface-raised);
border: 1px solid var(--sc-border);
border-radius: var(--sc-radius-md);
box-shadow: var(--sc-shadow-lg);
pointer-events: auto;
}
.sc-notification-icon {
flex: 0 0 auto;
margin-top: 0.125rem;
color: var(--sc-muted-fg);
}
.sc-notification[data-variant="success"] .sc-notification-icon {
color: var(--sc-success);
}
.sc-notification[data-variant="error"] .sc-notification-icon {
color: var(--sc-danger);
}
.sc-notification[data-variant="warning"] .sc-notification-icon {
color: var(--sc-warning);
}
.sc-notification[data-variant="info"] .sc-notification-icon {
color: var(--sc-primary);
}
.sc-notification-message {
flex: 1 1 auto;
margin: 0;
font-size: 0.875rem;
line-height: 1.45;
}
.sc-notification-close {
display: grid;
flex: 0 0 auto;
width: 1.5rem;
height: 1.5rem;
place-items: center;
color: var(--sc-muted-fg);
background: transparent;
border: 0;
border-radius: var(--sc-radius-sm);
cursor: pointer;
}
.sc-notification-close:hover {
color: var(--sc-fg);
background: var(--sc-surface-hover);
}
@media (max-width: 30rem) {
.sc-notification-stack {
top: 0.75rem;
right: 0.75rem;
left: 0.75rem;
width: auto;
}
}
.sc-dialog-backdrop { .sc-dialog-backdrop {
position: fixed; position: fixed;
z-index: 100; z-index: 100;
@@ -727,12 +1105,15 @@
} }
.sc-mobile-menu-button { .sc-mobile-menu-button {
position: absolute;
left: 50%;
display: grid; display: grid;
order: 3; order: 3;
width: 2.25rem; width: 2.25rem;
height: 2.25rem; height: 2.25rem;
margin-left: auto; margin-left: 0;
place-items: center; place-items: center;
transform: translateX(-50%);
} }
.sc-nav { .sc-nav {
@@ -744,7 +1125,7 @@
padding-bottom: 0.25rem; padding-bottom: 0.25rem;
} }
.sc-nav[data-open='true'] { .sc-nav[data-open="true"] {
display: flex; display: flex;
} }
@@ -753,7 +1134,7 @@
} }
.sc-header-actions { .sc-header-actions {
margin-left: 0; margin-left: auto;
} }
.sc-profile-button { .sc-profile-button {
+33 -5
View File
@@ -1,10 +1,12 @@
import type { Snippet } from 'svelte'; import type { Snippet } from "svelte";
export type AsyncAction<T = void> = (value: T) => void | Promise<void>; export type AsyncAction<T = void> = (value: T) => void | Promise<void>;
export interface NavItem { export interface NavItem {
href: string; href: string;
label: string; label: string;
icon?: string;
description?: string;
} }
export interface AuthSetupInput { export interface AuthSetupInput {
@@ -27,7 +29,8 @@ export interface TotpSetupResponse {
export type TotpStatusRequest = () => boolean | Promise<boolean>; export type TotpStatusRequest = () => boolean | Promise<boolean>;
export type TotpSetupRequest = () => TotpSetupResponse | Promise<TotpSetupResponse>; export type TotpSetupRequest = () =>
TotpSetupResponse | Promise<TotpSetupResponse>;
export type TotpTokenAction = (token: string) => void | Promise<void>; export type TotpTokenAction = (token: string) => void | Promise<void>;
@@ -41,7 +44,7 @@ export interface ProfileUpdateInput {
password?: string; password?: string;
} }
export type UserRole = 'superadmin' | 'admin' | 'user'; export type UserRole = "superadmin" | "admin" | "user";
export type UserId = string | number; export type UserId = string | number;
@@ -53,6 +56,8 @@ export interface ManagedUser {
totpEnabled?: boolean; totpEnabled?: boolean;
createdAt?: string; createdAt?: string;
updatedAt?: string; updatedAt?: string;
/** Null/undefined means the account has never completed a login. */
lastLoginAt?: string | null;
} }
export interface UserCreateInput { export interface UserCreateInput {
@@ -71,9 +76,14 @@ export interface UserUpdateInput {
export type UserListRequest = () => ManagedUser[] | Promise<ManagedUser[]>; export type UserListRequest = () => ManagedUser[] | Promise<ManagedUser[]>;
export type UserCreateRequest = (input: UserCreateInput) => void | Promise<void | ManagedUser>; export type UserCreateRequest = (
input: UserCreateInput,
) => void | Promise<void | ManagedUser>;
export type UserUpdateRequest = (id: UserId, input: UserUpdateInput) => void | Promise<void | ManagedUser>; export type UserUpdateRequest = (
id: UserId,
input: UserUpdateInput,
) => void | Promise<void | ManagedUser>;
export type UserDeleteRequest = (id: UserId) => void | Promise<void>; export type UserDeleteRequest = (id: UserId) => void | Promise<void>;
@@ -83,3 +93,21 @@ export interface AboutLink {
} }
export type ContentSnippet = Snippet; 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;
}
+13
View File
@@ -0,0 +1,13 @@
$ErrorActionPreference = 'Stop'
$repositoryRoot = (& git -C $PSScriptRoot rev-parse --show-toplevel).Trim()
if ($LASTEXITCODE -ne 0 -or [string]::IsNullOrWhiteSpace($repositoryRoot)) {
throw 'Could not locate the shared Git repository.'
}
& git -C $repositoryRoot config core.hooksPath .githooks
if ($LASTEXITCODE -ne 0) {
throw 'Could not configure the shared Git hooks path.'
}
Write-Host "Installed shared post-commit synchronization hook in $repositoryRoot."
+29
View File
@@ -0,0 +1,29 @@
import { readFileSync, readdirSync, existsSync } from 'fs';
import { join } from 'path';
// TODO(shared extraction): this audits legacy pre-SvelteKit `<project>/public/*.html`
// script tags. this repo's webui/ is SvelteKit-based (no per-service `public/` HTML pages), and
// none of the sibling monorepo service directories below live inside this repo anymore (they're
// now separate repos: MediaModerator, MediaTools, MediaKiosk, MediaViewer). The existsSync guard
// below means this currently no-ops safely (nothing to audit) rather than erroring. Left as-is
// rather than guessing at a SvelteKit-equivalent audit — remove or repurpose if useful.
const projects = ['MediaModerator', 'MediaTools', 'MediaKiosk', 'MediaViewer'];
const scriptSrcRe = /<script[^>]+src="([^"]+)"[^>]*>/g;
projects.forEach(proj => {
const pubDir = join(proj, 'public');
if (!existsSync(pubDir)) return;
const htmlFiles = readdirSync(pubDir)
.filter(f => f.endsWith('.html'))
.sort();
console.log(`=== ${proj} ===`);
htmlFiles.forEach(htmlFile => {
const content = readFileSync(join(pubDir, htmlFile), 'utf8');
const scripts = [];
let m;
scriptSrcRe.lastIndex = 0;
while ((m = scriptSrcRe.exec(content)) !== null) scripts.push(m[1]);
console.log(` ${htmlFile} -> ${scripts.join(', ')}`);
});
console.log();
});
+89
View File
@@ -0,0 +1,89 @@
import fs from 'node:fs/promises';
import path from 'node:path';
const repoRoot = process.cwd();
const strict = process.argv.includes('--strict');
const includeExt = new Set(['.js', '.ejs', '.html']);
const skipDirs = new Set(['node_modules', '.git', 'dist', 'release', 'coverage']);
const styleDisplayAssign = /style\.display\s*=\s*['"](?:flex|grid)['"]/gi;
const inlineDisplayStyle = /style\s*=\s*['"][^'"]*display\s*:\s*(?:flex|grid)[^'"]*['"]/gi;
async function walk(dir, out = []) {
const entries = await fs.readdir(dir, { withFileTypes: true });
for (const entry of entries) {
const full = path.join(dir, entry.name);
if (entry.isDirectory()) {
if (skipDirs.has(entry.name)) continue;
await walk(full, out);
continue;
}
if (!includeExt.has(path.extname(entry.name))) continue;
out.push(full);
}
return out;
}
function lineNumberAt(content, index) {
let line = 1;
for (let i = 0; i < index; i += 1) {
if (content.charCodeAt(i) === 10) line += 1;
}
return line;
}
function collectMatches(content, regex, type) {
const rows = [];
regex.lastIndex = 0;
let match;
while ((match = regex.exec(content)) !== null) {
rows.push({
type,
line: lineNumberAt(content, match.index),
snippet: match[0],
});
}
return rows;
}
const allFiles = await walk(repoRoot);
const violations = [];
// After folding media-backend/webui directly into the shared repo, this filter targets
// the frontend directories where inline HTML/CSS layout violations are actually possible
// (the plain Go backend/ and Go media-backend/ have none; there is no more nested shared/).
const includedTopLevelDirs = ['webui/', 'scripts/media/'];
for (const filePath of allFiles) {
const rel = path.relative(repoRoot, filePath).replaceAll('\\', '/');
if (!includedTopLevelDirs.some(prefix => rel.startsWith(prefix))) continue;
const content = await fs.readFile(filePath, 'utf8');
const hits = [
...collectMatches(content, styleDisplayAssign, 'js-style-display'),
...collectMatches(content, inlineDisplayStyle, 'inline-style-display'),
];
if (hits.length) {
violations.push({ file: rel, hits });
}
}
const total = violations.reduce((sum, row) => sum + row.hits.length, 0);
console.log(
JSON.stringify(
{
ok: strict ? total === 0 : true,
strict,
files: violations.length,
violations: total,
entries: violations,
},
null,
2
)
);
if (strict && total > 0) {
process.exitCode = 1;
}
+153
View File
@@ -0,0 +1,153 @@
#!/usr/bin/env node
import fs from 'fs';
import path from 'path';
import { fileURLToPath } from 'url';
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const repoRoot = path.resolve(__dirname, '..', '..');
// After a test run we want certain scratch roots removed entirely.
// NOTE: These are repo-root directories.
const DELETE_DIRS = [
'avatars',
'thumbnails',
'downloads',
'logs',
'output',
'input',
'loras',
'copy',
'database',
];
// Some roots are expected to remain present but empty.
// Keep this list lean to avoid surprising destructive behavior.
const EMPTY_DIRS = [
// (intentionally empty)
];
function rimrafChildren(dir) {
if (!fs.existsSync(dir)) return { skipped: true };
let removed = 0;
for (const entry of fs.readdirSync(dir)) {
const full = path.join(dir, entry);
try {
fs.rmSync(full, { recursive: true, force: true });
removed++;
} catch (e) {
console.error('[CLEAN] Failed removing', full, e.message);
}
}
return { removed };
}
function rimrafDir(dir) {
if (!fs.existsSync(dir)) return { skipped: true };
try {
fs.rmSync(dir, { recursive: true, force: true });
return { deleted: true };
} catch (e) {
console.error('[CLEAN] Failed removing dir', dir, e.message);
return { deleted: false, error: e.message };
}
}
function ensureDir(dir) {
if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true });
}
const results = [];
for (const rel of EMPTY_DIRS) {
const abs = path.join(repoRoot, rel);
ensureDir(abs);
const res = rimrafChildren(abs);
results.push({ dir: rel, mode: 'empty', ...res });
}
const deleted = [];
for (const rel of DELETE_DIRS) {
const abs = path.join(repoRoot, rel);
const res = rimrafDir(abs);
deleted.push({ dir: rel, mode: 'delete', ...res });
}
function removeFallbackDirs(baseDir) {
let removed = 0;
if (!fs.existsSync(baseDir)) return removed;
for (const entry of fs.readdirSync(baseDir)) {
if (entry.startsWith('tmp-fallback-')) {
const full = path.join(baseDir, entry);
try {
fs.rmSync(full, { recursive: true, force: true });
removed++;
} catch (e) {
console.error('[CLEAN] Failed removing fallback dir', full, e.message);
}
}
}
return removed;
}
// Remove tmp-fallback-* directories from known roots.
// Tests can create these in repo root.
let fallbackRemoved = 0;
fallbackRemoved += removeFallbackDirs(repoRoot);
// Sweep tests/ folder for orphaned ephemeral Postgres artifacts left behind by crashed runs
// or CWD-relative path.resolve('tests').
// Pattern: shared-media-embedded-pg-* dirs, shared-media-test-postgres-*.json state files.
// NOTE: no top-level tests/ dir currently exists and no embedded-postgres JS test tooling was
// found anywhere in this repo — this sweep is a harmless no-op today but kept for forward
// compatibility / parity with the source script. The former sweep of a nested shared/tests/
// was dropped: after folding media-backend/webui directly into the shared repo (no more
// vendored shared/ copy), there is no longer a nested "shared" subdirectory to sweep.
const pgSweepDirs = [path.join(repoRoot, 'tests')];
let pgArtifactsRemoved = 0;
for (const sweepDir of pgSweepDirs) {
try {
for (const name of fs.readdirSync(sweepDir)) {
if (
name.startsWith('shared-media-embedded-pg-') ||
(name.startsWith('shared-media-test-postgres-') &&
(name.endsWith('.json') || name.endsWith('.json.lock'))) ||
name.startsWith('media-analyzer-test-')
) {
const full = path.join(sweepDir, name);
try {
fs.rmSync(full, { recursive: true, force: true });
pgArtifactsRemoved++;
} catch (e) {
console.error('[CLEAN] Failed removing artifact', full, e.message);
}
}
}
// If sweepDir is outside the canonical tests/ dir and now empty, remove it entirely.
if (sweepDir !== path.join(repoRoot, 'tests')) {
try {
const remaining = fs.readdirSync(sweepDir);
if (remaining.length === 0) {
fs.rmdirSync(sweepDir);
}
} catch {
/* ignore */
}
}
} catch {
/* ignore scan errors */
}
}
const summary = { ok: true, cleaned: results, fallbackRemoved, pgArtifactsRemoved };
summary.deleted = deleted;
console.log(JSON.stringify(summary, null, 2));
// Windows occasionally reports a native module handle crash (exit code 3221225477) after
// synchronous fs.rmSync bursts. Yield event loop once and exit 0 explicitly to stabilize CI.
setTimeout(() => {
try {
process.exitCode = 0; // be explicit
} catch {
/* noop */
}
}, 10);
+117
View File
@@ -0,0 +1,117 @@
#!/usr/bin/env node
/**
* Enforce design-system CSS constraints for shared theme files.
*
* Rules enforced:
* - Theme CSS must not contain project/service-coupled selector tokens.
* - Theme CSS must not contain route-coupled panel IDs in selectors.
*
* TODO(shared extraction): the original monorepo version of this script also asserted that
* MediaShared/public/css/index.css and MediaDesktop/public/index.css stayed byte-for-byte synced.
* That check is no longer possible from inside this repo: MediaDesktop is now a fully separate
* repo (Original/MediaDesktop) and isn't checked out alongside this one, so there is nothing here
* to diff it against. The desktop-vs-shared theme sync check has been dropped rather than pointed
* at a nonexistent path; if that guarantee still matters, it belongs in MediaDesktop's own CI
* (comparing its vendored shared/ copy's theme file against its own), not here.
*/
import fs from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
const __dirname = path.dirname(fileURLToPath(import.meta.url));
const repoRoot = path.resolve(__dirname, '..', '..');
// MediaShared/public/css/index.css became packages/legacy-assets/public/css/index.css once
// media-backend/webui were folded directly into the shared repo (no more vendored copy).
const sharedThemePath = path.join(
repoRoot,
'packages',
'legacy-assets',
'public',
'css',
'index.css'
);
const bannedSelectorRules = [
{
name: 'project-coupled service token',
regex: /\b(?:kiosk|viewer|moderator|generator|library|analyzer|downloader|carriernode)-page\b/i,
},
{
name: 'project-coupled state class token',
regex:
/\b(?:viewer|kiosk|moderator|generator|library|analyzer|downloader|carriernode)-(?:home|page|stage|mode|active|panel)\b/i,
},
{
name: 'project-prefixed keyframe name',
regex:
/@keyframes\s+nc-(?:viewer|kiosk|moderator|generator|library|analyzer|downloader|carriernode)/i,
},
{
name: 'project-coupled data attribute',
regex:
/\[data-(?:kiosk|viewer|moderator|generator|library|analyzer|downloader|carriernode)[^\]]*\]/i,
},
{
name: 'route-coupled panel selector',
regex: /#panel-[a-z0-9_-]+/i,
},
];
function readUtf8(filePath) {
return fs.readFileSync(filePath, 'utf8');
}
function stripCssComments(text) {
return text.replace(/\/\*[\s\S]*?\*\//g, '');
}
function findViolations(filePath, content) {
const cleaned = stripCssComments(content);
const lines = cleaned.split(/\r?\n/);
const violations = [];
for (let i = 0; i < lines.length; i += 1) {
const line = lines[i];
for (const rule of bannedSelectorRules) {
if (rule.regex.test(line)) {
violations.push({
filePath,
line: i + 1,
rule: rule.name,
snippet: line.trim(),
});
}
}
}
return violations;
}
function main() {
if (!fs.existsSync(sharedThemePath)) {
console.error('[enforce-design-system-css] Missing expected theme file:');
console.error(` - ${path.relative(repoRoot, sharedThemePath)}`);
process.exit(1);
}
const sharedTheme = readUtf8(sharedThemePath);
const allViolations = findViolations(sharedThemePath, sharedTheme);
if (allViolations.length > 0) {
console.error('[enforce-design-system-css] Design-system CSS violations found:');
for (const v of allViolations) {
const rel = path.isAbsolute(v.filePath) ? path.relative(repoRoot, v.filePath) : v.filePath;
console.error(` - ${rel}:${v.line} [${v.rule}] ${v.snippet}`);
}
console.error('[enforce-design-system-css] Fix violations before running lint/test.');
process.exit(1);
}
console.log(
'[enforce-design-system-css] OK: shared theme is free of project-coupled selectors.'
);
}
main();
+129
View File
@@ -0,0 +1,129 @@
/**
* enforce-js-mapping.mjs
* Enforces the 1:1 HTML→JS naming rule per §7.1:
* public/ must contain exactly as many .js files as .html files,
* with matching names (index.html → index.js; all others name.html → name.js).
*
* Run: node scripts/shared/enforce-js-mapping.mjs
*
* TODO(shared extraction): §7.1's 1:1 HTML/JS rule applied to the legacy pre-SvelteKit
* `<project>/public/*.html` + `*.js` pages below. this repo's webui/ is SvelteKit-based (routes
* under webui/src/routes, no public/*.html+*.js pairs), and none of the other project directories
* listed below live inside this repo anymore (they're now separate repos). The existsSync guard
* per project means this currently no-ops safely (nothing found to check). Left as-is rather than
* inventing a SvelteKit-equivalent rule — remove or repurpose if useful.
*/
import fs from 'fs';
import path from 'path';
import { fileURLToPath } from 'url';
const __dirname = path.dirname(fileURLToPath(import.meta.url));
const ROOT = path.resolve(__dirname, '..', '..');
const log = (...args) => console.log('[enforce-js-mapping]', ...args);
function readFile(p) {
return fs.readFileSync(p, 'utf8');
}
function writeFile(p, content) {
fs.writeFileSync(p, content, 'utf8');
}
// eslint-disable-next-line no-unused-vars
function moveFile(src, dst) {
fs.mkdirSync(path.dirname(dst), { recursive: true });
fs.renameSync(src, dst);
}
// eslint-disable-next-line no-unused-vars
function deleteFile(p) {
if (fs.existsSync(p)) fs.unlinkSync(p);
}
// eslint-disable-next-line no-unused-vars
function ensureDir(p) {
fs.mkdirSync(p, { recursive: true });
}
// Replace a src path in an HTML file (exact string match on the attribute value)
// eslint-disable-next-line no-unused-vars
function replaceSrc(htmlPath, oldSrc, newSrc) {
let content = readFile(htmlPath);
// Match both quoted variants, relative and absolute
const escaped = oldSrc.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
const re = new RegExp(`(src=["'])${escaped}(["'])`, 'g');
if (!re.test(content)) {
log(` WARN: could not find src="${oldSrc}" in ${path.relative(ROOT, htmlPath)}`);
return;
}
content = content.replace(re, `$1${newSrc}$2`);
writeFile(htmlPath, content);
log(` HTML: ${oldSrc} → ${newSrc}`);
}
// Remove an entire <script ... src="..."> line from an HTML file
// eslint-disable-next-line no-unused-vars
function removeScriptLine(htmlPath, srcValue) {
let content = readFile(htmlPath);
const escaped = srcValue.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
const re = new RegExp(`[ \t]*<script[^>]*src=["']${escaped}["'][^>]*>[ \t]*\n?`, 'g');
if (!re.test(content)) {
log(` WARN: could not find script src="${srcValue}" in ${path.relative(ROOT, htmlPath)}`);
return;
}
content = content.replace(re, '');
writeFile(htmlPath, content);
log(` HTML: removed script src="${srcValue}"`);
}
// Append content (from init file) to end of another JS file
// eslint-disable-next-line no-unused-vars
function appendContent(targetPath, appendContent) {
const existing = readFile(targetPath);
writeFile(targetPath, existing.trimEnd() + '\n\n' + appendContent.trimStart());
}
// ─── Verification ─────────────────────────────────────────────────────────────
log('\n── Verification ──');
const projects = [
{ name: 'MediaModerator', publicDir: 'MediaModerator/public' },
{ name: 'MediaTools', publicDir: 'MediaTools/public' },
{ name: 'MediaTools Converter', publicDir: 'MediaTools/public/converter' },
{ name: 'MediaTools Generator', publicDir: 'MediaTools/generator/public' },
{ name: 'MediaTools Downloader', publicDir: 'MediaTools/downloader/public' },
{ name: 'MediaKiosk', publicDir: 'MediaKiosk/public' },
{ name: 'MediaViewer', publicDir: 'MediaViewer/public' },
{ name: 'MediaAnalyzer', publicDir: 'MediaAnalyzer/public' },
{ name: 'MediaDesktop', publicDir: 'MediaDesktop/public' },
];
let allOk = true;
for (const { name, publicDir } of projects) {
const pd = path.join(ROOT, publicDir);
if (!fs.existsSync(pd)) continue;
const htmlFiles = fs
.readdirSync(pd)
.filter(f => f.endsWith('.html'))
.map(f => f.replace(/\.html$/, ''));
const jsFiles = fs
.readdirSync(pd)
.filter(f => f.endsWith('.js'))
.map(f => f.replace(/\.js$/, ''));
// Expected mapping: name.html → name (index.html → index.js, no special case)
const expectedJs = htmlFiles.map(h => h).sort();
const actualJs = jsFiles.sort();
const missing = expectedJs.filter(j => !actualJs.includes(j));
const extra = actualJs.filter(j => !expectedJs.includes(j));
const ok = missing.length === 0 && extra.length === 0;
if (!ok) allOk = false;
const status = ok ? '✅' : '❌';
log(` ${status} ${name}: HTML=[${htmlFiles.sort().join(', ')}] JS=[${actualJs.join(', ')}]`);
if (missing.length) log(` MISSING JS: ${missing.join(', ')}`);
if (extra.length) log(` EXTRA JS: ${extra.join(', ')}`);
}
log(
allOk
? '\n✅ All projects satisfy the 1:1 HTML↔JS mapping rule.'
: '\n❌ Some projects have violations — review above.'
);
+102
View File
@@ -0,0 +1,102 @@
#!/usr/bin/env node
import fs from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
const __dirname = path.dirname(fileURLToPath(import.meta.url));
const repoRoot = path.resolve(__dirname, '..', '..');
// The monorepo kept its canonical JS/TS test sources under a single repo-root tests/ dir, which
// doesn't exist in this repo. Scan the real locations JS/TS test files can currently live in
// this repo instead: webui/src (SvelteKit app) and shared/packages/*/test(s) (vendored from the
// shared repo). repoRoot/tests is kept as a forward-compatible root in case one is added later.
// As of this repo's extraction, none of these contain vitest/mocha/jest-style test files yet
// (shared/packages/node-backend/test/auth.test.js uses plain `node --test`, which shares the same
// describe/it/test .skip API surface these patterns already match), so this currently passes
// trivially rather than being a dead check.
const testsRoots = [
path.join(repoRoot, 'tests'),
path.join(repoRoot, 'webui', 'src'),
path.join(repoRoot, 'shared', 'packages'),
];
const TEST_FILE_EXTENSIONS = new Set(['.js', '.mjs', '.cjs']);
const DISALLOWED_LINE_PATTERNS = [
{
name: 'skip/todo/runIf declaration',
regex: /^\s*(?:await\s+)?(?:it|test|describe)\s*\.\s*(?:skip|todo|skipIf|runIf)\b/,
},
{
name: 'this.skip invocation',
regex: /\bthis\s*\.\s*skip\s*\(/,
},
];
const SKIP_DIR_NAMES = new Set(['node_modules', '.git', 'dist', 'build', '.svelte-kit']);
function listTestFiles(dir) {
if (!fs.existsSync(dir)) return [];
const out = [];
const stack = [dir];
while (stack.length) {
const current = stack.pop();
const entries = fs.readdirSync(current, { withFileTypes: true });
for (const entry of entries) {
const full = path.join(current, entry.name);
if (entry.isDirectory()) {
if (SKIP_DIR_NAMES.has(entry.name)) continue;
stack.push(full);
} else if (entry.isFile()) {
const ext = path.extname(entry.name).toLowerCase();
if (TEST_FILE_EXTENSIONS.has(ext)) {
out.push(full);
}
}
}
}
return out.sort();
}
function collectViolations(filePath) {
const src = fs.readFileSync(filePath, 'utf8');
const lines = src.split(/\r?\n/);
const violations = [];
for (let i = 0; i < lines.length; i += 1) {
const line = lines[i];
for (const pattern of DISALLOWED_LINE_PATTERNS) {
if (pattern.regex.test(line)) {
violations.push({
line: i + 1,
name: pattern.name,
text: line.trim(),
});
}
}
}
return violations;
}
const files = testsRoots.flatMap(listTestFiles).sort();
const failures = [];
for (const filePath of files) {
const violations = collectViolations(filePath);
if (violations.length) {
failures.push({ filePath, violations });
}
}
if (failures.length) {
console.error('[enforce-no-skipped-tests] Found disallowed skip-style test usage.');
for (const entry of failures) {
const rel = path.relative(repoRoot, entry.filePath).replace(/\\/g, '/');
for (const v of entry.violations) {
console.error(` - ${rel}:${v.line} (${v.name}) -> ${v.text}`);
}
}
process.exit(1);
}
console.log('[enforce-no-skipped-tests] OK: no skipped/pending test declarations found.');
+3
View File
@@ -0,0 +1,3 @@
import * as v from 'vitest';
console.log('vitest exports sample:', Object.keys(v).slice(0, 20));
console.log('has test:', typeof v.test);
+99
View File
@@ -0,0 +1,99 @@
#!/usr/bin/env node
/**
* Run eslint for each JS/TS package and emit a single JSON summary.
* Does NOT print per-file diagnostics unless a failure occurs; keeps CI logs lean while enabling
* machine parsing. Exit code is non-zero if any package reports errors or warnings (configurable).
*
* Shared extraction note: the monorepo version of this script discovered the monorepo root by
* walking up for a MediaShared/package.json marker and iterated MediaShared/MediaModerator/
* MediaViewer/MediaTools using a shared root eslint.config.mjs. None of those sibling packages or
* the root config exist in this repo — webui/ is the only JS/TS package here, and it already
* ships its own local eslint.config.js (picked up automatically, no --config override needed).
*/
import { spawnSync } from 'node:child_process';
import { fileURLToPath } from 'node:url';
import { dirname, resolve, join } from 'node:path';
import { existsSync } from 'node:fs';
const __dirname = dirname(fileURLToPath(import.meta.url));
const root = resolve(__dirname, '..', '..');
const packages = [{ name: 'webui', path: 'webui' }];
function resolveEslintInvocation({ pkgDir }) {
const pkgEslintJs = resolve(pkgDir, 'node_modules', 'eslint', 'bin', 'eslint.js');
if (existsSync(pkgEslintJs)) {
return { cmd: process.execPath, argsPrefix: [pkgEslintJs] };
}
return null;
}
function spawnCrossPlatform(cmd, args, opts) {
if (process.platform === 'win32' && cmd.toLowerCase().endsWith('.cmd')) {
return spawnSync('cmd.exe', ['/d', '/s', '/c', cmd, ...args], opts);
}
return spawnSync(cmd, args, opts);
}
const summary = { timestamp: new Date().toISOString(), packages: [], ok: true };
let hadFailure = false;
for (const pkg of packages) {
const pkgDir = resolve(root, pkg.path);
const resolved = resolveEslintInvocation({ pkgDir });
let result;
if (resolved) {
result = spawnCrossPlatform(
resolved.cmd,
[...resolved.argsPrefix, '.', '--format', 'json', '--max-warnings=0'],
{
cwd: pkgDir,
encoding: 'utf8',
}
);
} else {
const npxCmd = process.platform === 'win32' ? 'npx.cmd' : 'npx';
result = spawnCrossPlatform(npxCmd, ['eslint', '.', '--format', 'json', '--max-warnings=0'], {
cwd: pkgDir,
encoding: 'utf8',
});
}
if (result.error) {
summary.packages.push({ name: pkg.name, error: result.error.message, ok: false });
hadFailure = true;
continue;
}
let parsed = [];
try {
parsed = JSON.parse(result.stdout || '[]');
} catch (e) {
summary.packages.push({
name: pkg.name,
parseError: e.message,
raw: (result.stdout || '').slice(0, 2000),
ok: false,
});
hadFailure = true;
continue;
}
let errorCount = 0;
let warningCount = 0;
let fileCount = 0;
for (const file of parsed) {
fileCount++;
errorCount += file.errorCount || 0;
warningCount += file.warningCount || 0;
}
const ok = errorCount === 0 && warningCount === 0; // treat warnings as failures for consistency with --max-warnings=0
if (!ok) hadFailure = true;
summary.packages.push({ name: pkg.name, fileCount, errorCount, warningCount, ok });
}
summary.ok = !hadFailure;
const json = JSON.stringify(summary, null, 2);
console.log(json);
if (hadFailure) process.exit(1);
+112
View File
@@ -0,0 +1,112 @@
#!/usr/bin/env node
/**
* Lint all JS/TS packages sequentially with clear section headers, plus a repo-wide Prettier
* format check.
* Exits non‑zero if any package fails its lint step.
*
* Shared extraction note: the monorepo version of this script discovered the monorepo root
* by walking up for a MediaShared/package.json marker, iterated nine sibling Media* packages
* against a shared root eslint.config.mjs/.stylelintrc.json, and ran Prettier/Stylelint out of
* MediaShared/node_modules (npm workspace hoisting). None of that exists in this repo: there is
* no root package.json, no shared devDependency hoisting, and webui/ is the only JS/TS package —
* it already ships its own local eslint.config.js and prettier.config.js. The Stylelint section
* has been dropped entirely rather than pointed at a nonexistent .stylelintrc.json: webui has no
* stylelint devDependency and its CSS is Tailwind-authored, so there was nothing equivalent to
* carry over. If CSS linting is wanted later, it would need its own stylelint config added to
* webui/ (or a new root package.json) first.
*/
import { spawnSync } from 'node:child_process';
import { fileURLToPath } from 'node:url';
import { dirname, resolve } from 'node:path';
import { existsSync } from 'node:fs';
const __dirname = dirname(fileURLToPath(import.meta.url));
const root = resolve(__dirname, '..', '..');
const packages = [{ name: 'webui', path: 'webui' }];
function resolveEslintInvocation({ pkgDir }) {
const pkgEslintJs = resolve(pkgDir, 'node_modules', 'eslint', 'bin', 'eslint.js');
if (existsSync(pkgEslintJs)) {
return { cmd: process.execPath, argsPrefix: [pkgEslintJs] };
}
return null;
}
function spawnCrossPlatform(cmd, args, opts) {
// On Windows, running .cmd directly without a shell can fail. Use cmd.exe wrapper.
if (process.platform === 'win32' && cmd.toLowerCase().endsWith('.cmd')) {
return spawnSync('cmd.exe', ['/d', '/s', '/c', cmd, ...args], opts);
}
return spawnSync(cmd, args, opts);
}
let failures = 0;
for (const pkg of packages) {
const pkgDir = resolve(root, pkg.path);
console.log(`\n===== LINT: ${pkg.name} (${pkg.path}) =====`);
if (!existsSync(pkgDir)) {
failures++;
console.error(`✖ Lint failed for ${pkg.name} (directory not found at ${pkgDir})`);
continue;
}
const resolved = resolveEslintInvocation({ pkgDir });
let result;
if (resolved) {
result = spawnCrossPlatform(resolved.cmd, [...resolved.argsPrefix, '.', '--max-warnings=0'], {
cwd: pkgDir,
stdio: 'inherit',
env: process.env,
});
} else {
const npxCmd = process.platform === 'win32' ? 'npx.cmd' : 'npx';
result = spawnCrossPlatform(npxCmd, ['eslint', '.', '--max-warnings=0'], {
cwd: pkgDir,
stdio: 'inherit',
env: process.env,
});
}
if (result.error) {
failures++;
console.error(`✖ Lint failed for ${pkg.name}: ${result.error.message}`);
continue;
}
if (result.status !== 0) {
failures++;
console.error(`✖ Lint failed for ${pkg.name}`);
} else {
console.log(`✔ Lint passed for ${pkg.name}`);
}
}
// ===== webui: Prettier format check =====
console.log('\n===== FORMAT CHECK (Prettier, webui) =====');
{
const webuiDir = resolve(root, 'webui');
const prettierBin = resolve(webuiDir, 'node_modules', 'prettier', 'bin', 'prettier.cjs');
const npxCmd = process.platform === 'win32' ? 'npx.cmd' : 'npx';
const fmtResult = existsSync(prettierBin)
? spawnCrossPlatform(process.execPath, [prettierBin, '--check', '.'], {
cwd: webuiDir,
stdio: 'inherit',
env: process.env,
})
: spawnCrossPlatform(npxCmd, ['prettier', '--check', '.'], {
cwd: webuiDir,
stdio: 'inherit',
env: process.env,
});
if (fmtResult.error || fmtResult.status !== 0) {
failures++;
console.error('✖ Format check failed');
} else {
console.log('✔ Format check passed');
}
}
if (failures > 0) {
console.error(`\nLint completed with ${failures} failing check(s).`);
process.exit(1);
}
console.log('\nAll lint checks passed.');
+104
View File
@@ -0,0 +1,104 @@
#!/usr/bin/env node
import { spawn } from 'node:child_process';
import { createRequire } from 'node:module';
import path from 'node:path';
// Run vitest with JSON reporter and parse skipped tests/suites.
// Usage: node scripts/list-skipped-tests.mjs
// Exits with code 0 if none skipped, 1 if any skipped.
//
// TODO(shared extraction): as of this repo's extraction from the old monorepo, it has no
// vitest suite anywhere (webui/ has no vitest devDependency/config; shared/packages/node-backend
// uses plain `node --test`; backend/ is Go), so `require.resolve('vitest/package.json')` below
// will fail immediately. The hardcoded `--config ../vitest.config.mjs` below also assumed this
// script runs from a subdirectory (e.g. the old repo-root tests/ dir) one level below a
// vitest.config.mjs — that layout does not exist in this repo either. Left unfixed rather than
// guessed at: revisit once/if a real vitest suite is introduced in this repo, and point the
// --config flag at wherever that config actually lives.
// Resolve local vitest binary (avoid relying on npx which can be absent in some CI / shells)
function resolveVitestBin() {
try {
const require = createRequire(import.meta.url);
const pkgPath = require.resolve('vitest/package.json');
const binDir = path.dirname(pkgPath);
// Vitest exposes a bin field pointing to dist/cli.js; require it to ensure path stability
const pkg = require('vitest/package.json');
if (pkg && pkg.bin && pkg.bin.vitest) {
return path.join(binDir, pkg.bin.vitest);
}
// Fallback: common location
return path.join(binDir, 'dist', 'cli.js');
} catch (err) {
console.error('[list-skipped-tests] Unable to resolve vitest binary:', err.message);
process.exit(2);
}
}
const vitestBin = resolveVitestBin();
const nodeExec = process.execPath; // Use current Node runtime
// Always pass explicit config to ensure identical file set as normal test run.
// Use 'run' subcommand to execute once (no watch) and JSON reporter for machine parsing.
const args = [vitestBin, 'run', '--config', '../vitest.config.mjs', '--reporter=json'];
const child = spawn(nodeExec, args, { stdio: ['ignore', 'pipe', 'inherit'] });
let jsonBlock = '';
child.stdout.on('data', d => {
const text = d.toString();
// Capture last JSON object emitted by vitest reporter (it prints progress lines + final JSON)
jsonBlock += text;
});
// eslint-disable-next-line no-unused-vars
child.on('close', _code => {
// Attempt to find the final JSON object (Vitest prints *only* JSON in our current mode but be defensive)
const match = jsonBlock.match(/(\{[\s\S]*\})\s*$/);
if (!match) {
console.error('[list-skipped-tests] Failed to parse Vitest JSON output');
process.exit(2);
}
let report;
try {
report = JSON.parse(match[1]);
} catch (e) {
console.error('[list-skipped-tests] JSON parse error', e);
process.exit(2);
}
// Vitest JSON reporter structure (observed):
// { numTotalTests, testResults: [ { name, assertionResults: [ { title, status } ] } ] }
// Legacy / alternative structure: { testFiles: [ { file, tests:[{ state }] } ] }
const skipped = [];
let totalFiles = 0;
if (Array.isArray(report.testResults)) {
totalFiles = report.testResults.length;
for (const tr of report.testResults) {
const filePath = tr.name || tr.file || 'unknown';
(tr.assertionResults || []).forEach(ar => {
// Vitest marks skipped tests with status === 'skipped'. Support 'todo' & 'pending' for completeness.
if (ar.status === 'skipped' || ar.status === 'todo' || ar.status === 'pending') {
skipped.push({ file: filePath, test: ar.fullName || ar.title, state: ar.status });
}
});
}
} else if (Array.isArray(report.testFiles)) {
// fallback structure
totalFiles = report.testFiles.length;
for (const f of report.testFiles) {
if (!f) continue;
const filePath = f.file || f.name || 'unknown';
(f.tests || []).forEach(t => {
if (t.state === 'skip' || t.state === 'todo' || t.state === 'pending') {
skipped.push({ file: filePath, test: t.name, state: t.state });
}
});
}
} else {
console.error('[list-skipped-tests] Unrecognized Vitest JSON structure');
process.exit(2);
}
const summary = { totalFiles, skippedCount: skipped.length, skipped };
console.log(JSON.stringify(summary, null, 2));
process.exit(skipped.length > 0 ? 1 : 0);
});
+47
View File
@@ -0,0 +1,47 @@
#!/usr/bin/env node
// Simple timing harness: runs vitest in JSON reporter mode and summarizes collection vs test execution time.
//
// TODO(shared extraction): this script assumes a vitest test suite is configured in whatever
// directory it's invoked from. As of this repo's extraction from the old monorepo, it has no vitest
// suite anywhere (webui/ has no vitest devDependency or config; shared/packages/node-backend uses
// plain `node --test`; backend/ is Go). This is a generic, path-assumption-free script (no fix
// needed for this repo's layout), but it currently has nothing to run against — it will fail
// with "vitest not found" / no config until a vitest suite is introduced somewhere in this repo.
import { spawn } from 'node:child_process';
const args = ['vitest', 'run', '--reporter=json'];
const child = spawn(process.platform === 'win32' ? 'npx.cmd' : 'npx', args, {
stdio: ['ignore', 'pipe', 'inherit'],
});
let json = '';
child.stdout.on('data', d => {
json += d.toString();
});
child.on('close', code => {
if (code !== 0) {
console.error('vitest exited with code', code);
process.exit(code);
}
// Vitest JSON reporter may output multiple JSON objects; take last complete JSON object.
const matches = json.trim().match(/\{[\s\S]*$/); // naive: last JSON-like block
let data;
try {
data = JSON.parse(matches ? matches[0] : json);
} catch {
console.error('Failed to parse vitest JSON output');
process.exit(1);
}
const summary = data?.summary || {};
const out = {
testFiles: summary.testFiles ?? summary.files ?? 'n/a',
tests: summary.tests ?? 'n/a',
durationMs: summary.duration ?? 'n/a',
failed: summary.failed ?? 0,
skipped: summary.skipped ?? 0,
passed: summary.passed ?? 0,
// Vitest does not expose collect vs run granularly in JSON; we could extend later by parsing stdout.
note: 'For deeper phase timing, run "npx vitest run --reporter basic" and inspect breakdown.',
};
console.log(JSON.stringify(out, null, 2));
});
@@ -0,0 +1,5 @@
#!/usr/bin/env node
const out = { ok: false, error: 'simulate-category-removal removed' };
console.error('[simulate-category-removal] removed');
console.log(JSON.stringify(out));
process.exit(0);
+142
View File
@@ -0,0 +1,142 @@
#!/usr/bin/env node
import fs from 'node:fs/promises';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const repoRoot = path.resolve(__dirname, '..', '..');
const registryBase = 'https://registry.npmjs.org';
const sections = ['dependencies', 'devDependencies', 'optionalDependencies', 'peerDependencies'];
function shouldSkipSpec(spec) {
if (!spec) return true;
const lower = spec.toLowerCase();
return (
lower.startsWith('file:') ||
lower.startsWith('workspace:') ||
lower.startsWith('link:') ||
lower.startsWith('github:') ||
lower.startsWith('git+') ||
lower.startsWith('http://') ||
lower.startsWith('https://') ||
lower.startsWith('npm:')
);
}
function isSimpleRange(spec) {
if (!spec) return false;
if (spec === '*' || spec === 'latest') return true;
if (spec.includes(' ') || spec.includes('||')) return false;
return /^[~^]?\d+(\.\d+){0,2}([-.][0-9A-Za-z-.]+)?$/.test(spec);
}
function buildNextSpec(currentSpec, latest) {
if (currentSpec === '*' || currentSpec === 'latest') {
return `^${latest}`;
}
if (currentSpec.startsWith('~')) return `~${latest}`;
if (currentSpec.startsWith('^')) return `^${latest}`;
return `^${latest}`;
}
async function fetchLatestVersion(pkgName) {
const encoded = encodeURIComponent(pkgName);
const res = await fetch(`${registryBase}/${encoded}`);
if (!res.ok) {
throw new Error(`Failed to fetch ${pkgName}: ${res.status} ${res.statusText}`);
}
const data = await res.json();
const latest = data?.['dist-tags']?.latest;
if (!latest) {
throw new Error(`Missing dist-tags.latest for ${pkgName}`);
}
return latest;
}
async function loadJson(filePath) {
const raw = await fs.readFile(filePath, 'utf8');
return JSON.parse(raw);
}
async function saveJson(filePath, data) {
const next = JSON.stringify(data, null, 2) + '\n';
await fs.writeFile(filePath, next, 'utf8');
}
async function updatePackageJson(packageJsonPath) {
const pkg = await loadJson(packageJsonPath);
let changed = false;
const changes = [];
for (const section of sections) {
const deps = pkg[section];
if (!deps) continue;
const entries = Object.entries(deps);
for (const [name, spec] of entries) {
if (shouldSkipSpec(spec) || !isSimpleRange(spec)) continue;
let latest;
try {
latest = await fetchLatestVersion(name);
} catch (err) {
console.warn(`[skip] ${name}: ${err.message}`);
continue;
}
const nextSpec = buildNextSpec(spec, latest);
if (nextSpec !== spec) {
deps[name] = nextSpec;
changed = true;
changes.push({ name, from: spec, to: nextSpec, section });
}
}
}
if (changed) {
await saveJson(packageJsonPath, pkg);
}
return { changed, changes };
}
// this repo has no root package.json / npm workspaces (unlike the monorepo this was extracted
// from), so there's no "workspaces" array to discover packages from. webui/ is the only local npm
// package whose dependency versions this repo owns and should bump directly. shared/package.json
// is intentionally excluded: it's a vendored, byte-for-byte copy synced in from the separate
// shared repo (see scripts/sync-shared.mjs) and any local edit to it would just be overwritten by
// the next sync — dependency bumps for shared/ belong upstream in that repo instead.
const LOCAL_PACKAGE_DIRS = ['webui'];
async function main() {
const packageJsonPaths = LOCAL_PACKAGE_DIRS.map(dir => path.join(repoRoot, dir, 'package.json'));
const results = [];
for (const pkgPath of packageJsonPaths) {
try {
const result = await updatePackageJson(pkgPath);
results.push({ pkgPath, ...result });
} catch (err) {
console.error(`[error] ${pkgPath}: ${err.message}`);
}
}
const updated = results.filter(r => r.changed);
const totalChanges = updated.reduce((sum, r) => sum + r.changes.length, 0);
console.log(`Updated ${updated.length} package.json file(s).`);
console.log(`Total dependency updates: ${totalChanges}`);
for (const { pkgPath, changes } of updated) {
const rel = path.relative(repoRoot, pkgPath);
console.log(`\n${rel}`);
for (const change of changes) {
console.log(` ${change.section}: ${change.name} ${change.from} -> ${change.to}`);
}
}
}
main().catch(err => {
console.error(err);
process.exitCode = 1;
});
+7 -2
View File
@@ -33,8 +33,13 @@ git archive --format=tar "$release_tag" "$module_directory" \
test -f "$module_root/go.mod" test -f "$module_root/go.mod"
grep -Fxq "module $module_path" "$module_root/go.mod" grep -Fxq "module $module_path" "$module_root/go.mod"
mkdir -p "$repository_root/$output_directory" if [[ "$output_directory" = /* ]]; then
zip_file="$repository_root/$output_directory/${module_path//\//_}@${version}.zip" output_path="$output_directory"
else
output_path="$repository_root/$output_directory"
fi
mkdir -p "$output_path"
zip_file="$output_path/${module_path//\//_}@${version}.zip"
rm -f "$zip_file" rm -f "$zip_file"
( (
Loaded 100 of 149 files, more files were not shown because too many files have changed in this diff. Show more