110 Commits
Author SHA1 Message Date
Gabriel20xx 7fd2f14f91 refactor!: remove UserManagement and internalize media controls 2026-10-16 16:27:34 +00:00
Gabriel20xx 521603188d docs: group web-ui components by purpose 2026-10-16 14:53:27 +00:00
Gabriel20xx 6be3f90afa chore: remove legacy assets package and CSS enforcement script 2026-10-15 13:52:39 +00:00
Gabriel20xx c9fc3abcad feat(media): support project-mounted thumbnail storage
- Store thumbnails in project mounts
- Fall back to legacy paths when reading or deleting
- Use original images when stored thumbnails are missing
2026-10-14 09:25:40 +00:00
Gabriel20xx 0783b74da7 feat: assign custom roles in user management 2026-10-13 18:08:42 +00:00
Gabriel20xx 6388efd6d6 feat(styles): add shared dashboard and pagination components 2026-10-10 10:42:24 +00:00
Gabriel20xx e1805c8fc3 fix: remove excess top padding on small screens 2026-10-09 14:29:31 +00:00
Gabriel20xx 52316e99a2 refactor(web-ui)!: remove PageHeader and AppShell integration 2026-10-08 12:57:31 +00:00
Gabriel20xx a14187a621 fix: report mount not found only when all instances return 404 2026-10-08 11:28:14 +00:00
Gabriel20xx c7a3796f26 fix: improve notification stacking and text wrapping 2026-10-03 10:39:08 +00:00
Gabriel20xx 58b40fa340 style: stack section titles and tighten subtitle spacing 2026-10-02 08:43:16 +00:00
Gabriel20xx 6ef2335731 feat: add generic CarrierNode mount client 2026-09-29 22:23:11 +02:00
Gabriel20xx 64607f7e7a Fix ty suppression for auth router 2026-09-28 22:28:53 +02:00
Gabriel20xx db14c02558 Adjust shared media player controls 2026-09-25 11:28:19 +02:00
Gabriel20xx 44518b955e Fix shared media controls auto-hide 2026-09-24 20:14:21 +02:00
Gabriel20xx a348409993 Restore shared media metadata contract 2026-09-23 15:48:17 +02:00
Gabriel20xx 356b43b59e Share custom media player controls 2026-09-23 06:00:15 +02:00
Gabriel20xx 764593254e feat: add shared media player components 2026-09-23 05:35:28 +02:00
Gabriel20xx cb23889dba docs: document shared web-ui components 2026-09-23 05:34:02 +02:00
Gabriel20xx b85601ae32 fix: standardize startup database retries 2026-09-23 04:56:32 +02:00
Gabriel20xx c743ee7f5b fix-wide-header 2026-09-23 15:41:46 +02:00
Gabriel20xx 170a25188b Resolve imported thumbnail mappings 2026-09-18 15:58:57 +02:00
Gabriel20xx 389dd8649d Extend core config for ContentScanner sync 2026-09-18 15:54:39 +02:00
Gabriel20xx 8bbaf3c70b Format Python backend sources 2026-09-18 13:11:49 +02:00
Gabriel20xx 2d8f138215 Add CarrierNode project attribution 2026-09-18 11:21:06 +02:00
Gabriel20xx 87cb39c04c feat: allow project selection when creating users 2026-09-17 00:15:19 +02:00
Gabriel20xx 51eef30971 feat: honor project login requirement in shared auth 2026-09-17 00:14:56 +02:00
Gabriel20xx 78067cc890 feat: use dropdown for primary color setting 2026-09-16 23:58:00 +02:00
Gabriel20xx 94a5c0b9ae fix: make wide page preference affect shared shell 2026-09-16 23:38:03 +02:00
Gabriel20xx e4c1826d6a Support pushed CarrierNode credentials 2026-09-16 19:52:57 +02:00
Gabriel20xx 4b0566ea46 Share optional ComfyUI endpoint in core config 2026-09-16 11:50:55 +02:00
Gabriel20xx b012d585f8 Expose ProjectConfigurator URL in core config 2026-09-16 10:54:19 +02:00
Gabriel20xx ddcf2fd78d Show missing SECRET in auth status 2026-09-15 23:26:02 +02:00
Gabriel20xx 0e450d53de feat: migrate project secrets and user-scoped colors 2026-09-15 13:23:17 +02:00
Gabriel20xxandClaude Sonnet 5 dcfdb3d7af Make AuthGuard integration decouple from knowing the URL at startup
Every language's AuthGuard client/service used "no URL at construction"
to mean "auth disabled forever" - a live SetBaseUrl/setBaseUrl push from
ProjectConfigurator could only ever retarget an *already-enabled* client,
never turn one on for the first time. That made AUTHGUARD_URL a de-facto
required env var everywhere, even though ProjectConfigurator can push it
live after startup.

- Go: shared/backend/auth's New/NewWithStore now default to a "pending"
  Service (still enabled, fails closed until a URL arrives) instead of
  disabled when authGuardURL is empty; add an explicit Disabled() option
  for the genuine standalone/local-dev opt-out.
- Python/Node/Java: add setBaseUrl/set_base_url to each AuthClient so a
  client built with an empty base URL can be retargeted in place once a
  URL is pushed, the same as the Go client already supported.
- Python/Node: add a coreconfig module (Info/Store), the framework-agnostic
  equivalent of shared/backend/coreconfig (Go), for services in those
  languages to receive ProjectConfigurator's core-services push at all.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-14 09:35:45 +02:00
Gabriel20xxandClaude Sonnet 5 c09957189f Add shared_backend.authproxy: FastAPI AuthGuard-proxy engine
Extracted from three near-identical bespoke implementations (Heretic,
HordeWorker, InfiniteVideo), each ~800-1000 lines hand-rolling the same
status/setup/login/logout/TOTP/admin-user-CRUD proxy around AuthClient.
build_auth_router(get_client, get_store) returns a ready-to-mount
APIRouter matching shared/backend/auth (Go)'s Service response shapes.
Gated behind an optional `fastapi` extra so the rest of this
framework-agnostic package is unaffected. 18 new tests, including a
regression test for a real bug this had (request models nested inside
build_auth_router silently broke under `from __future__ import
annotations`, misrouting every JSON body as a missing query param).

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-13 21:27:54 +02:00
Gabriel20xxandClaude Sonnet 5 f58579290d Add project-key support to Python/Node/Java AuthClient equivalents
Mirrors Go's authclient.WithProjectKey: each client now accepts a
project_key/projectKey and sends it as X-Project-Key on every request,
so AuthGuard can enforce per-user project-access restriction for
consumers written in these languages too.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-13 21:08:49 +02:00
Gabriel20xxandClaude Sonnet 5 5364588ba0 Merge mediaauth into shared/backend/auth as the unified auth-proxy engine
mediaauth was its own package only because "auth" was already taken by
this package's lower-level Store/User/Role layer. Since mediaauth is no
longer media-family-specific (see the earlier "unified auth proxy"
generalization), it now lives directly in this package instead, renamed
where it collided with existing exports: mediaauth.User -> ProxyUser,
mediaauth.Store -> ProxyStore (this package's own local-account Store is
unrelated and keeps its name). Service/New/NewWithStore/UserFromContext
and the rest keep their names. mediacore.go updated to match.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-13 18:43:16 +02:00
Gabriel20xxandClaude Sonnet 5 c9737d1f9f mediaauth: expose SetAuthGuardBaseURL for live AuthGuard-URL retargeting
A project built via NewWithStore previously had no way to react to
ProjectConfigurator's live authguard_url push (coreconfig.Store.OnUpdate)
the way a project holding its own *authclient.Client directly could via
SetBaseURL - this closes that gap without exposing the client itself.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-13 12:30:19 +02:00
Gabriel20xxandClaude Sonnet 5 a5eb37a823 Add changeset for UserManagement's project-access picker
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-13 12:20:56 +02:00
Gabriel20xxandClaude Sonnet 5 663d498a03 Add per-user project-access restriction; generalize mediaauth into a unified auth proxy
shared/backend/auth: adds SchemaOptions.ProjectScoping and Store methods
(SetUserProjects/UserProjects/UserProjectsByUser/IsProjectAllowed,
SetKnownProjects/KnownProjects) backing AuthGuard's new per-user
project-access restriction.

shared/backend/authclient: Client can now identify its calling project to
AuthServer via WithProjectKey (sent as X-Project-Key on every request), so
AuthServer can enforce the restriction above per project.

shared/backend/mediaauth: generalized from a media-family-only package
into the one shared auth-proxy engine every AuthGuard-integrated project
should use. New accepts a projectKey; the login-required/setup-claim
storage it needs is now expressed as a small Store interface
(NewWithStore lets any project's own storage satisfy it, not just the
media family's shared `settings` table, which pgSettingsStore still backs
for existing callers). ManagedUpdateUser/ManagedDeleteUser now resolve
their {id} path param via chi.URLParam OR the stdlib 1.22+ ServeMux's
PathValue, so non-chi consumers work unchanged.

packages/web-ui: UserManagement gains an optional `projects` prop (a
per-account project-access picker), used only by AuthGuard's own admin UI.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-13 12:16:17 +02:00
Gabriel20xx 6ac2fcefeb Normalize all button/input/select/dropdown heights to 2.5rem
Button size variants (sm 2rem, lg 2.875rem), sc-input/sc-select (2.6rem),
and the pagination controls (2.1rem/2.25rem) each rendered at a different
height, so any row mixing them (a select next to a button, a page-size
dropdown next to pagination buttons) was visibly misaligned. Textarea
keeps its own min-height since it's multi-line by design.
2026-09-13 10:47:00 +02:00
Gabriel20xxandClaude Sonnet 5 d4d2c49538 Fix mobile header menu button jumping position on toggle
The button's top offset was unset, so its absolute-position static
position was recomputed from the flex-wrap layout whenever .sc-nav
wrapped onto its own row on open, causing a visible vertical jump.
Pinning top to the header's mobile padding keeps it stationary.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-12 23:03:36 +02:00
Gabriel20xxandClaude Sonnet 5 9f64bdc591 Fix pagination page-size dropdown showing blank on load
The select's value was coerced to a string via String(pageSize) while
the <option> values are numbers. Svelte 5 matches a non-bound <select>
value against each option's stored value with Object.is, so "24"
never matched 24 and the dropdown rendered with no option selected.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-12 16:29:25 +02:00
Gabriel20xxandClaude Sonnet 5 a675899c7d Rename MediaKiosk references to KioskDisplay
The service was renamed but comments and a couple of legacy project-name
lists in the shared library still referred to it as MediaKiosk.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-12 15:48:17 +02:00
Gabriel20xxandClaude Sonnet 5 a998844c11 Add missing sc-pagination styles for the shared Pagination component
The component's markup used sc-pagination* classes that had no
matching rules anywhere in the shared stylesheet, so it rendered
unstyled in every consumer.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-11 23:40:08 +02:00
Gabriel20xxandClaude Sonnet 5 965910eecc Add pagination controls to UserManagement
Uses the shared Pagination component instead of rendering every
fetched user in one unpaginated list.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-11 23:25:25 +02:00
Gabriel20xxandClaude Sonnet 5 097442f4b0 Make carriernodeclient.Client.Proxy fail over across CarrierNode instances
Proxy (streaming playback/thumbnails straight through) was left primary-only
when NewMulti was added, but it's a per-file read like Probe/FetchToScratch/
ProbeMedia, not a write - a file living only on a non-primary CarrierNode
instance couldn't actually be played back. Try each configured instance in
order and stream from the first one that doesn't answer with an error,
forwarding the last instance's response (success or error) if none do.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-11 11:56:55 +02:00
Gabriel20xxandClaude Sonnet 5 9f78995d03 Support multiple CarrierNode instances in carriernodeclient/coreconfig/mediacore
ProjectConfigurator's Projects workspace already lets an operator register more
than one CarrierNode instance (separate storage backends, HA/failover replicas,
or a mix), but every consumer only ever read a single carriernode_url. Add
carriernodeclient.NewMulti (ListFiles merges across instances, Probe/
FetchToScratch/ProbeMedia try each in order, writes stay primary-only),
coreconfig.Info.CarrierNodeURLs for pushed consumers, and
mediacore.CarrierNodeURLs for the 7 services that read settings directly.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-11 11:37:56 +02:00
Gabriel20xxandClaude Sonnet 5 87ac5ed25a Fix header profile dropdown About link showing default anchor color
The About item falls back to an <a> when no onAbout handler is wired.
The :visited fix only covered post-click state; the unvisited a:link
pseudo-class still beat the .sc-profile-menu-item class in specificity,
making the item look lighter/whiter than the button-based items until
clicked once.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-11 09:16:11 +02:00
Gabriel20xxandClaude Sonnet 5 f00f9f3c03 Add coreconfig package and authclient.SetBaseURL for ProjectConfigurator's core-services push
ProjectConfigurator now pushes AuthGuard's/CarrierNode's current URLs to
every project it registers instead of each hardcoding them forever.
coreconfig.Store/Handler is the receiving end any Go service vendors;
authclient.Client.SetBaseURL lets an existing client be retargeted live
when a fresh push arrives, with no restart.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-10 11:53:04 +02:00
Gabriel20xxandClaude Sonnet 5 3131937af2 Add mediaauth.Service.SetLoginRequired for cross-service login pushes
Lets a trusted internal caller (ProjectConfigurator's central "Require
Login" toggle) set a service's auth_required flag directly, without an
admin session - UpdateAccessSettings now delegates to it too.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-09 22:24:03 +02:00
Gabriel20xxandClaude Sonnet 5 8d7d6ee35b Add a 32-color curated brand palette reference
Documents the hue-spaced palette used to give every project in the
workspace a unique webui primary color: which colors are claimed by
which project, and which remain reserved for future projects.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-09 20:48:52 +02:00
Gabriel20xxandClaude Sonnet 5 56e2f60531 Make the auth screen's password field optional; catch up UserManagement drift
AuthPage's password (and, in setup mode, confirm-password) field no
longer forces a non-empty value client-side -- the server already
enforces the real rules (a correct password to log in, >=8 chars to
register/bootstrap), so this only replaces a native browser validation
popup with the server's own error message.

Also bring UserManagement in line with an AuthGuard-only edit that had
drifted ahead of this source (username/email/password relaxed to "at
least one of username/email, password optional" for admin-created
users) so the next consumer sync doesn't silently revert it.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-09 16:52:45 +02:00
Gabriel20xxandClaude Sonnet 5 ae792cbf43 Add OmniLogger as a sync-consumers.ps1 consumer project
OmniLogger now vendors shared/ (webui, auth, authclient, authproxy), so it
needs to receive updates the same way Core/AuthGuard and the other Go+Svelte
consumers do.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-08 17:10:34 +02:00
Gabriel20xxandClaude Sonnet 5 992fbda39c Finish Forks->Fork rename: HordeWorker moved to Fork/HordeWorker
The directory was locked by two stray python http.server processes
and a hung git push waiting on GitHub credentials, all left over from
earlier work in this session - killed with the user's approval, which
freed it up to move like the other three fork projects already had.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-07 16:20:29 +02:00
Gabriel20xxandClaude Sonnet 5 c5c3ec3d9f Update path references for Central->Core, Forks->Fork rename
The workspace's Central/ and Forks/ parent folders were renamed to
Core/ and Fork/ (singular) - a pure local filesystem reorganization,
git repos don't care about their own absolute path. Updates
sync-consumers.ps1's consumer list and workspace-root detection, plus
doc-comment/README cross-references that hardcoded the old paths.

HordeWorker's entry stays at the old 'Forks/HordeWorker' path for now:
a long-running process holds that directory open, so it couldn't be
moved to Fork/HordeWorker in this pass.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-07 16:00:08 +02:00
Gabriel20xxandClaude Sonnet 5 d1a02a8c4d Extract shared media backend library; remove dead multi-flavor app/binary
Adds mediaauth/mediacore/carriernodeclient/syncsocket packages under
backend/, extracting everything genuinely cross-service (auth, shared
media/tags/playlists/sync/profile routes, the CarrierNode HTTP client,
the playback-sync websocket hub) out of the old media-backend monolith.

The 7 media-family services (CarrierNode, ContentScanner, CraftStudio,
MediaViewer, MediaKiosk, ModerationHub, ProjectConfigurator) each now
have their own independent frontend and backend built on this library,
instead of sharing one generic multi-flavor webui/media-backend
selected by a MEDIA_SERVICE/VITE_MEDIA_APP flag. That generic app and
binary (webui/, media-backend/) are now dead and removed here, along
with their dedicated CI workflows. sync-consumers.ps1 and README.md
updated to describe the new architecture.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-07 15:06:06 +02:00
Gabriel20xxandClaude Sonnet 5 2e6baaa70c Add wide-page layout toggle; rename MediaAnalyzer/MediaTools/LoggingServer
Adds a new persisted "wide page" preference (theme/language-style store,
settings-dialog checkbox, main-content width override) alongside the
existing theme switcher and language selector.

Also completes three project renames throughout the shared source:
MediaAnalyzer -> ContentScanner, MediaTools -> CraftStudio, and
LoggingServer -> OmniLogger, across the Go media-backend service enum,
webui AppId/app-config/project-icons, renamed feature components, and
the sync-consumers.ps1 consumer list.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-06 22:50:38 +02:00
Gabriel20xxandClaude Sonnet 5 4cca0ddf72 Fix stale MediaServant project entry surviving the CarrierNode rename
The configured_central/main rename to CarrierNode only ran when both
lists were still empty, so an already-populated list kept the old
MediaServant entry and gained a duplicate CarrierNode one. Also
migrate the per-project JSON blobs (labels, login, mounts, tab meta)
keyed by the old name so their data isn't orphaned.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-06 21:02:27 +02:00
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 npm packages / Publish shared npm packages (push) Failing after 39s
Publish Python package / Publish shared Python package (push) Successful in 12s
Publish Go package / Publish shared Go module (push) Successful in 57s
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
107 changed files with 17316 additions and 777 deletions

No files matched your search

+5
View File
@@ -0,0 +1,5 @@
---
"@gabriel20xx/node-backend": patch
---
`AuthClient` accepts a `projectKey` option, sent as `X-Project-Key` on every request, so AuthGuard can enforce per-user project-access restriction for Node consumers the same way the Go and Python clients already do.
@@ -0,0 +1,5 @@
---
"@gabriel20xx/node-backend": minor
---
Add a `coreconfig` module (`Info`/`Store`), the Node equivalent of `shared/backend/coreconfig` (Go) and `shared_backend.coreconfig` (Python): lets a service receive AuthGuard's/CarrierNode's current URL(s) pushed live from ProjectConfigurator instead of hardcoding them in its own env vars. `AuthClient` also gains `setBaseUrl(url)`, mirroring the Go/Python/Java clients, so a service can construct it once with an empty/unknown base URL and retarget it live once a URL is pushed, rather than needing the URL to be known at construction time.
@@ -0,0 +1,5 @@
---
"@gabriel20xx/web-ui": patch
---
Fix the primary color chosen in `PrimaryColorPicker` not reaching the app's UI. The choice is now applied through a stylesheet that also targets `[data-theme]` elements, such as the `AppShell` root, so it takes effect immediately everywhere instead of being hidden by those elements' own theme tokens. The picker also sets the `--sc-*` primary, accent, and hover tokens the shared components read.
+5
View File
@@ -0,0 +1,5 @@
---
"@gabriel20xx/web-ui": minor
---
Remove the `PageHeader` title card. `AppShell` no longer renders a per-page title/description card, and its `showPageHeader` and `pageHeaderActions` props are gone, as are the `PageHeader` export and the `.sc-page-header` styles. Buttons or status pills that lived in the title card now belong in a card inside the page content.
+5
View File
@@ -0,0 +1,5 @@
---
"@gabriel20xx/web-ui": minor
---
`UserManagement` is removed from the package, along with its `UserListRequest`, `UserCreateRequest`, `UserUpdateRequest`, and `UserDeleteRequest` types and its `.sc-user-*` styles. The component was only used by AuthGuard, which now owns a copy in `features/users`. Applications that still render it should keep their own copy or build their own user table. `KnownRole`, `ManagedUser`, `UserCreateInput`, and `UserUpdateInput` remain exported.
+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.
+23 -5
View File
@@ -38,9 +38,10 @@ jobs:
RELEASE_TAG: ${{ github.event_name == 'release' && github.event.release.tag_name || github.ref_name }}
run: |
package_directory='gitea-go-package'
rm -rf "$package_directory"
mkdir -p "$package_directory"
bash scripts/package-go-module.sh "$RELEASE_TAG" "$package_directory"
mkdir -p "$RUNNER_TEMP/gitea-go-package"
cp "$package_directory"/*.zip "$RUNNER_TEMP/gitea-go-package/"
find "$package_directory" -maxdepth 1 -type f -name '*.zip' -print -quit | grep -q .
- name: Publish to Gitea Package Registry
env:
@@ -53,8 +54,25 @@ jobs:
echo 'PACKAGE_REGISTRY_USERNAME and PACKAGE_REGISTRY_TOKEN secrets are required.' >&2
exit 1
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"
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" \
"$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
+30 -3
View File
@@ -50,17 +50,44 @@ jobs:
- 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:]')"
if npm view "$package@$version" version --registry="$NPM_REGISTRY" >/dev/null 2>&1; then
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."
else
npm publish --workspace="$package" --registry="$NPM_REGISTRY"
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
+33 -1
View File
@@ -37,6 +37,38 @@ jobs:
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 --skip-existing "$package_directory"/*
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
+1 -1
View File
@@ -78,6 +78,6 @@ jobs:
with:
python-version: '3.12'
- name: Install package
run: python -m pip install --upgrade pip -e packages/python-backend
run: python -m pip install --upgrade pip -e "packages/python-backend[fastapi]"
- name: Run Python tests
run: python -m unittest discover -s packages/python-backend/tests -p 'test_*.py'
+2
View File
@@ -1,9 +1,11 @@
node_modules/
packages/*/dist/
packages/*/.svelte-kit/
webui/.svelte-kit/
*.tgz
.npm/
__pycache__/
*.py[cod]
*.egg-info/
.venv/
packages/*/target/
+90
View File
@@ -0,0 +1,90 @@
# Performance Report — shared
- **Project:** shared
- **Path:** /workspace/Personal/Web/shared
- **Analyzed:** 2026-10-16
- **Commit:** 5216031 on main
- **Working tree:** 9 uncommitted change(s): `.changeset/user-management-roles.md` and `packages/web-ui/src/lib/components/UserManagement.svelte` deleted; `.changeset/remove-user-management.md` untracked; `README.md`, `MediaPlayerControls.svelte`, `packages/web-ui/src/lib/index.ts`, `packages/web-ui/src/lib/styles.css`, `packages/web-ui/src/lib/types.ts`, `shared-styles.css` modified. Findings reflect the working tree.
- **Stack:** Go 1.25 (`backend/`, module `repos.gfranz.ch/Gabriel20xx/shared/backend`, pgx, chi, coder/websocket, goose); Node.js ESM with `pg` (`packages/node-backend`); Python 3.10+ with asyncpg, bcrypt and optional FastAPI (`packages/python-backend`); Java 8 target with Jackson (`packages/java-backend`); Svelte 5 and TypeScript (`packages/web-ui`); PostgreSQL; PowerShell and Node scripts; Gitea and GitHub Actions. No Dockerfile, compose file or `.dockerignore` exists in the repo.
- **Scope:** This is a shared library consumed by other projects (vendored snapshot), not an application. Read: all first-party Go packages except `backend/auth/*` and `backend/config` (reviewed in a separate pass), the Node, Python and Java AuthGuard clients and stores, the web-ui components that perform I/O or timers, root manifests, `.github` and `.gitea` workflows, and `scripts/`. Excluded: `node_modules`, `packages/web-ui/dist` and `.svelte-kit` (gitignored, not tracked), `package-lock.json` and `go.sum` (versions only), and test bodies (used only for coverage notes). Paths below are relative to the repo root. Backend findings come from read-only static review passes; the highest-severity citations were re-checked in the code. Nothing was built, run or profiled.
## Summary
| Severity | Count |
|---|---:|
| Critical | 0 |
| High | 1 |
| Medium | 4 |
| Low | 4 |
| Info | 1 |
The auth code has no obvious SQL N+1 outside the playlist reorder path, and most outbound calls have timeouts. The main performance risks are unbounded in-memory state in the sync websocket hub, a per-request AuthGuard round trip with no caching, blocking CPU work (password hashing) on event loops, and a media lookup that defeats its index.
## Issues
### P-001 · Unbounded per-session timing maps and no connection cap in the sync hub · **High**
- **Location:** `backend/syncsocket/syncsocket.go:443` (sync:update handler), `backend/syncsocket/syncsocket.go:446-455` (writes to `playAt`, `playAtLocalMs`, `capturedAtMs` keyed by session ID), `backend/syncsocket/syncsocket.go:457-463` (eviction covers only `states`), `backend/syncsocket/syncsocket.go:293` (`ServeWebSocket` accepts unlimited connections)
- **Description:** The three timing maps are written per session ID and are cleared only in narrow branches. The 1000-session cap on `states` does not touch them, so the maps grow for every new session ID ever seen. `ServeWebSocket` has no peer or connection limit, and each connection holds a goroutine and buffers.
- **Impact:** Memory grows without bound in a long-running process, and one client sending `sync:update` with fresh session IDs can drive that growth. Exposure depends on whether consumers gate `/ws` with authentication (see Security S-003; needs verification in consumers).
- **Recommendation:** Remove timing entries when a session is evicted or loses its last peer. Apply the same cap to all per-session maps. Add a maximum connection count and per-IP and per-peer message-rate limits.
### P-002 · Sync fan-out runs on the HTTP request path and writes to peers one at a time · **Medium**
- **Location:** `backend/syncsocket/syncsocket.go:234` (`Broadcast`), `backend/syncsocket/syncsocket.go:247-261` (serial per-peer writes, 2 s timeout each; JSON marshalled once per peer), `backend/mediacore/mediacore.go:150` (`PUT /sync` calls `Broadcast` inline), `backend/syncsocket/syncsocket.go:486` (each `sync:update` fans out to the whole session)
- **Description:** `Broadcast` marshals the payload once per peer and writes to peers sequentially, each with up to a 2 s deadline. The HTTP handler for `PUT /sync` calls it on the request goroutine, so one slow peer can hold the HTTP response for up to 2 s per peer. Peers may send `sync:update` at any rate, and each message is fanned out to the entire session.
- **Impact:** Slow or hostile peers add latency to unrelated HTTP responses, and one client can multiply its traffic across every peer in its session.
- **Recommendation:** Marshal once per broadcast, send through per-peer buffered queues written concurrently, and drop peers whose queue is full. Move HTTP-triggered broadcasts off the request goroutine. Add per-peer message-rate limits.
### P-003 · Media lookup defeats the `media_key` index, and playlist reorder issues one UPDATE per id · **Medium**
- **Location:** `backend/mediacore/mediacore.go:735` (`findMedia`: `WHERE media_key=$1 OR CAST(id AS TEXT)=$1`), `backend/mediacore/mediacore.go:210` (thumbnail join with the same OR pattern), `backend/mediacore/mediacore.go:711-713` (reorder loop, one UPDATE per id, errors discarded, no transaction)
- **Description:** An OR with a cast on `id` makes the planner unlikely to use the `media_key` index alone. Stream and thumbnail requests call this path on every request (`mediacore.go:181`, `194-224`). The reorder handler issues one statement per submitted id without a transaction and ignores errors; the 512 KB body cap allows tens of thousands of ids.
- **Impact:** Each media request can cost a sequential scan on a large `media` table, and a single reorder call can issue tens of thousands of statements and report success after a partial failure. Plan impact was not measured (no database access).
- **Recommendation:** Look up by `media_key` only, and try the numeric id only when the input is all digits. Replace the loop with one `UPDATE ... FROM unnest(...)` inside a transaction, check errors, and cap the id count. Confirm with `EXPLAIN` on a populated table.
### P-004 · Password hashing blocks the event loop · **Medium**
- **Location:** `packages/node-backend/src/auth.js:61` and `:69` (`crypto.pbkdf2Sync` in `hashPassword` and `verifyPassword`), `packages/python-backend/src/shared_backend/auth.py:126` and `:131` (`bcrypt.hashpw` and `bcrypt.checkpw` called synchronously inside an otherwise async module)
- **Description:** Both runtimes perform deliberately expensive hashing synchronously on the thread that serves requests. Node uses 100,000 PBKDF2 iterations; Python uses bcrypt defaults. Each call takes tens to hundreds of milliseconds of CPU.
- **Impact:** A burst of login or signup attempts stalls every other request in the process, which makes this a cheap denial-of-service lever as well as a latency problem.
- **Recommendation:** In Node, use the async `crypto.pbkdf2` or `scrypt`. In Python, wrap the bcrypt calls in `asyncio.to_thread` or expose async variants and use them from async handlers.
### P-005 · Every authenticated request costs a fresh AuthGuard round trip, and the login-required flag is re-read per request · **Medium**
- **Location:** `backend/auth/proxy.go:504` (`CurrentUser` calls AuthGuard `/api/me` on each request), `backend/auth/proxy.go:512`, `:566`, `:598`, `:651`, `:733`, `:773`, `:848` (each re-reads the login-required setting from the store), `packages/node-backend/src/authclient.js:167` (`validate` per request), `packages/python-backend/src/shared_backend/authclient.py:254` (same), `backend/authclient/client.go:265-285` (middleware validates per request)
- **Description:** No client caches validated sessions, and the Go proxy re-reads the login-required flag from Postgres in each middleware and handler. A request carrying an invalid token still triggers an outbound call. The clients are otherwise correct about timeouts and context propagation.
- **Impact:** Every request pays an AuthGuard round trip and at least one database read, so latency and load on AuthGuard and Postgres scale directly with traffic. Invalid tokens can be used to drive outbound calls.
- **Recommendation:** Cache the login-required flag in memory with a short TTL, passing the resolved value down the request. Add a short-TTL session cache keyed by a SHA-256 of the token, storing both positive and negative results and bounded in size. Keep connections pooled in every client.
### P-006 · Outbound AuthGuard calls use blocking `urllib` on the default thread pool · **Low**
- **Location:** `packages/python-backend/src/shared_backend/authclient.py:265` (`asyncio.to_thread`), `:276` (`urllib.request.urlopen`), `packages/node-backend/src/authclient.js:177` (abort timer)
- **Description:** The Python client performs blocking `urllib` calls through `asyncio.to_thread`, which uses the event loop's default executor shared with other `to_thread` users, and opens a new connection per call. In Node the abort timer is set at line 177; the review pass reports it is cleared once headers arrive, which would leave the body read without a deadline (needs verification at `authclient.js:186-188`).
- **Impact:** A slow AuthGuard can exhaust executor threads needed elsewhere in the process, and a stalled response body can hang a request.
- **Recommendation:** Use a pooled async HTTP client (httpx or aiohttp in Python; undici or a reused agent in Node), and keep the timeout active until the body is fully read, or apply an overall deadline.
### P-007 · Admin user operations over-fetch and make sequential calls; the Go store lists all users · **Low**
- **Location:** `packages/python-backend/src/shared_backend/authproxy.py:644-652` (updating one user lists all users to find it), `packages/python-backend/src/shared_backend/authproxy.py:406-416` (`/status` makes two sequential AuthGuard calls), `backend/auth/store.go:294` (`ListUsers` returns every row with no limit)
- **Description:** After a user update the Python handler fetches the entire user list to locate one row. The status endpoint makes two independent AuthGuard calls one after the other. The Go store's `ListUsers` has no `LIMIT`, and the client list calls have no pagination.
- **Impact:** Latency and memory grow with the number of accounts.
- **Recommendation:** Add a get-by-id method (or return the updated record from the update call), run independent calls concurrently, and add pagination to the list endpoints.
### P-008 · CarrierNode client has no transport timeout; the media proxy depends on caller deadlines · **Low**
- **Location:** `backend/carriernodeclient/carriernodeclient.go:28-30` (package-level `http.Client` with no `Timeout`; the comment says callers set context deadlines), `backend/carriernodeclient/carriernodeclient.go:171-213` (`Proxy` uses the incoming request context), `backend/carriernodeclient/carriernodeclient.go:510-522` (thumbnail HEAD probe on the same client)
- **Description:** The shared client is deliberately timeout-free so that large media streams are not cut off. Control calls and the proxy paths rely on each caller to attach a deadline. Where a caller does not, a hung CarrierNode holds the request open indefinitely.
- **Impact:** Goroutines and client connections can be tied up by a slow upstream. The severity depends on consumers' server-level timeouts (needs verification).
- **Recommendation:** Set a `ResponseHeaderTimeout` on the transport so that stalled upstreams fail quickly while streams still work. Attach deadlines to control calls, and document the requirement for callers that use the proxy paths.
### P-009 · Status widget polls two endpoints every 15 seconds regardless of tab visibility · **Low**
- **Location:** `packages/web-ui/src/lib/components/StatusWidget.svelte:76-79` (`onMount` starts a 15 s interval that issues `/healthz` and `/ready` requests)
- **Description:** Each mounted `StatusWidget` polls both probes on a fixed interval, with no check for `document.hidden`. Consumers may mount the widget on several pages or in several open tabs. The cleanup on unmount is correct.
- **Impact:** Background tabs and multiple widgets add steady load to every backend that exposes these probes.
- **Recommendation:** Pause polling while `document.hidden` is true and refresh on `visibilitychange`. Consider a longer interval for `/ready`, which may query the database.
### P-010 · Info: the root `prepare` script builds on install, and CI runs the build twice · **Info**
- **Location:** `package.json` (`prepare` runs `npm run build` and `build-root-styles`; `test` runs `npm run build` before `test:node-backend`), `.github/workflows/tests.yml` (`npm ci` followed by `npm test`)
- **Description:** `npm ci` runs the root `prepare` script, which builds the web-ui package, and then `npm test` builds it again.
- **Impact:** Extra CI time on every run. No runtime impact.
- **Recommendation:** Either skip the duplicate build in `test`, or move the build out of `prepare` into an explicit CI step.
## Notes
- **Docker:** No Dockerfile, compose file or `.dockerignore` exists in this repository, so image size, multi-stage builds and base-image checks do not apply here. Consumer projects that build images from the vendored snapshot should be reviewed separately.
- **Frontend checks:** No whole-library imports were found; `@lucide/svelte` is imported by name in every component. No `{@html}`, unbounded caches or leaked intervals were found in the web-ui, and the timers and listeners in `MediaPlayer`, `MediaPlayerControls`, `StatusWidget`, `AppShell` and `notifications.svelte.ts` are cleaned up. `shared-styles.css` (1134 lines, about 21 KB) is loaded in full by consumers. As a component library it has no route-level code-splitting, which is expected rather than a defect. Four of seven `{#each}` blocks in the components are keyed; the remaining ones are listed under quality findings.
- **HTTP caching and compression:** Not applicable to the library code; the backends are API services and the static styles are shipped to consumers' own build pipelines.
- **Not verified:** No query plans (no database access), no benchmarks or profiling, no build or test runs. Counts and ordering are based on code reading only.
- **Excluded from analysis:** `packages/web-ui/dist` and `.svelte-kit` (gitignored, not tracked), `package-lock.json` and `go.sum` (used for versions only).
+127
View File
@@ -0,0 +1,127 @@
# Code Quality Report — shared
- **Project:** shared
- **Path:** /workspace/Personal/Web/shared
- **Analyzed:** 2026-10-16
- **Commit:** 5216031 on main
- **Working tree:** 9 uncommitted change(s): `.changeset/user-management-roles.md` and `packages/web-ui/src/lib/components/UserManagement.svelte` deleted; `.changeset/remove-user-management.md` untracked; `README.md`, `MediaPlayerControls.svelte`, `packages/web-ui/src/lib/index.ts`, `packages/web-ui/src/lib/styles.css`, `packages/web-ui/src/lib/types.ts`, `shared-styles.css` modified. Findings reflect the working tree (for example, README component count, Q-014).
- **Stack:** Go 1.25 (`backend/`); Node.js ESM with `pg` (`packages/node-backend`); Python 3.10+ with asyncpg, bcrypt and optional FastAPI (`packages/python-backend`, ruff configured); Java 8 target with Jackson and JUnit 5 (`packages/java-backend`); Svelte 5 and TypeScript with svelte-check (`packages/web-ui`); PowerShell and Node build and sync scripts; Gitea and GitHub Actions.
- **Scope:** A shared library consumed by other projects as a vendored snapshot. Read: root manifests and changesets, `.github` and `.gitea` workflows, `.githooks`, `scripts/` (sync, build, and the `scripts/media` tooling), all four language packages (AuthGuard clients, stores, TOTP, config, coreconfig, proxies), Go packages under `backend/` (auth read in a separate pass), and the web-ui library source (barrel, styles, primary-color, notifications, components that do I/O or timers). Excluded: `node_modules`, `packages/web-ui/dist` and `.svelte-kit` (gitignored, not tracked), `package-lock.json` and `go.sum` (versions only), and test bodies except for coverage notes. Backend findings come from read-only static review passes; the highest-impact citations were re-checked in the code. No lint, build or test was executed.
## Summary
| Severity | Count |
|---|---:|
| Critical | 0 |
| High | 0 |
| Medium | 9 |
| Low | 7 |
| Info | 0 |
The code is generally tidy: no TODO, FIXME or HACK markers in first-party non-test code, no `any` or `@ts-ignore` in the web-ui, and parameterised SQL throughout. The weak spots are operational: several scripts and workflows no longer match the repository layout, Java and most Go packages are not tested in CI, the publish pipeline skips the checks that exist for pull requests, and the four AuthGuard clients have drifted apart in behaviour.
## Issues
### Q-001 · Node database wrapper: no pool `error` listener, and writes are retried blindly · **Medium**
- **Location:** `packages/node-backend/src/db.js:43` (`new Pool(...)` with no `'error'` handler; grep of the package finds none), `packages/node-backend/src/db.js:80-88` (`query()` retries once on any transient error)
- **Description:** `pg` emits `'error'` on the pool when an idle client fails, for example after a database restart. With no listener, that event is thrown and can terminate the process. Separately, `query()` retries once on any transient error for every statement, including `INSERT` and `UPDATE`, so a write that committed before the connection dropped can be applied twice.
- **Impact:** A database restart can crash a service that uses this wrapper, and non-idempotent writes can be duplicated.
- **Recommendation:** Attach a logging `pool.on('error', ...)` handler. Retry only reads, or require the caller to opt in to retrying a specific statement.
### Q-002 · Repo-level media lint and test tooling points at directories that no longer exist · **Medium**
- **Location:** `scripts/media/lint-all.mjs:26` (package list `webui`) and `:51` (fails with "directory not found"), `scripts/media/enforce-no-skipped-tests.mjs:18-20` (roots `tests`, `webui/src`, `shared/packages`) and `:99-102` (prints OK when nothing is scanned), `scripts/media/upgrade-deps.mjs:102-104` (comment asserts there is no root `package.json`, which is false), `package.json:49-65` (`media:*` scripts)
- **Description:** This tooling was carried over from a monorepo. `webui/`, `media-backend/` and `shared/packages` do not exist here; the real package is `packages/web-ui`. `media:lint:all` fails immediately, and `media:enforce:no-skipped-tests` scans zero files and still reports success, which gives false confidence. None of these scripts runs in CI.
- **Impact:** Dead tooling that either fails or passes vacuously, and misleading comments about the repository layout.
- **Recommendation:** Delete the unused scripts, or repoint them at `packages/web-ui` and `packages/*/test(s)`. Make the no-skipped-tests check fail when it scans zero files, and wire any script that is kept into CI.
### Q-003 · Java package has tests, but no CI job runs them · **Medium**
- **Location:** `packages/java-backend/pom.xml`, `packages/java-backend/src/test/java/com/gabriel20xx/shared/auth/AuthClientTest.java`, `.github/workflows/tests.yml`, `.github/workflows/lint.yml` (neither mentions Java or Maven)
- **Description:** The only Java test class is `AuthClientTest`. `Totp`, `ResetManager`, `Roles` and cookie extraction have no direct tests. The package is compiled into a consuming project as source, so a regression here reaches that project without any signal in this repository.
- **Impact:** Java changes can break without detection.
- **Recommendation:** Add a Java job (`mvn -B test` on a JDK matching the target) to `tests.yml`, and add unit tests for `Totp`, `ResetManager`, `Roles` and cookie extraction.
### Q-004 · Go test coverage is absent for several packages, including the media core and the sync hub · **Medium**
- **Location:** `backend/mediacore/mediacore.go` (1107 lines, no tests), `backend/syncsocket/syncsocket.go` (581 lines, no tests), `backend/logshipper/shipper.go` (438 lines, no tests), `backend/config/config.go` and `backend/migrate/migrate.go` (no tests), `backend/auth/proxy.go` (1525 lines; `proxy_test.go` covers constructors, middleware gating and normalizers only)
- **Description:** `git ls-files` shows no `_test.go` file in `mediacore`, `syncsocket`, `logshipper`, `config` or `migrate`. In `backend/auth`, the handler-level behaviour of Signup, Login, Logout, UpdateMe, the managed-user endpoints, the TOTP endpoints and the platform-user SQL is untested (per review pass).
- **Impact:** The largest and most security-relevant code paths (media routes, websocket hub message handling, log redaction) change without tests.
- **Recommendation:** Add `httptest` handler tests for the auth-gated routes and for websocket message handling, and table tests for the path helpers (`SafeRelative`, `ResolveUnderRoots`, `thumbnailFile`).
### Q-005 · The generated root stylesheet keeps a package import that the build was meant to strip · **Medium**
- **Location:** `scripts/build-root-styles.mjs:4` (token import as a single-quoted string) and `:7` (filter compares exact text), `shared-styles.css:3` (`@import "@gabriel20xx/design-tokens/theme.css";` kept)
- **Description:** The build removes the token import only when it matches the single-quoted string. `packages/web-ui/src/lib/styles.css:1` uses double quotes, so the filter misses it. The generated `shared-styles.css` keeps a bare package import on line 3 beside the relative import on line 1. This was already present at HEAD. No CI step checks that the committed generated file matches the build output.
- **Impact:** Consumers that vendor this file must resolve a package they may not install, or their bundler fails. The duplicated import also shows that the generation step is not verified.
- **Recommendation:** Normalise quotes in the filter (or match both forms), then add a CI step that rebuilds and runs `git diff --exit-code shared-styles.css`.
### Q-006 · The sync script can overwrite consumer changes, and the post-commit hook commits into consumer repositories · **Medium**
- **Location:** `scripts/sync-consumers.ps1:273` (dirty-destination check bypassed by `-Force`), `scripts/sync-consumers.ps1:291` (stale files removed) and `:301` (files overwritten), `.githooks/post-commit:8-10` (runs the sync with `-Commit` after every commit), `scripts/install-sync-hook.ps1` (enables the hook)
- **Description:** With `-Force`, uncommitted changes inside a consumer's `shared/` folder are deleted or overwritten with no backup. The hook, once installed, runs the sync with `-Commit` after every commit in this repository, which creates commits in each registered consumer repository (22 entries in `$consumerProjects`).
- **Impact:** Possible loss of uncommitted consumer work, and unexpected commits in other projects after an unrelated commit here.
- **Recommendation:** Make destructive overwrite require an explicit flag that first stashes or backs up the destination. Make the hook opt-in, or have it report what would change instead of committing. Document the behaviour in the README.
### Q-007 · Publish workflows release without running the checks that exist for pull requests · **Medium**
- **Location:** `.gitea/workflows/publish-npm.yml:27-49` (builds, then publishes; no lint or test step), `.gitea/workflows/publish-python.yml:26-39` (builds and uploads; no ruff or unittest), `.gitea/workflows/publish-go.yml:29-31` (runs `go test` only; no `go vet` or gofmt)
- **Description:** A `v*` tag or a published release publishes whatever is tagged, without the lint and test jobs in `.github/workflows` that gate changes. The publish workflows run in a separate system, so the same checks are not enforced at release time.
- **Impact:** Broken or unlinted code can reach the shared registries that projects consume.
- **Recommendation:** Make each publish job run the same checks as CI (`npm run lint` and `npm test`, `ruff check`, `python -m unittest`, `go vet` and gofmt) before upload, or depend on a prior successful workflow run.
### Q-008 · The four AuthGuard clients diverge in behaviour and in the stored password-hash format · **Medium**
- **Location:** `packages/node-backend/src/auth.js:56-81` (PBKDF2 `salt:hex` hashes) vs `packages/python-backend/src/shared_backend/auth.py:123-133` (bcrypt hashes) in the same `auth_users.password_hash` column; `packages/python-backend/src/shared_backend/auth.py:225-240` (`list_users` and `create_managed_user` return `password_hash`) vs `packages/node-backend/src/auth.js:221-233` (excludes it); `packages/java-backend/src/main/java/com/gabriel20xx/shared/auth/AuthClient.java:195` (`IllegalStateException` escapes `middleware` while Node returns 401); `packages/node-backend/src/db.js:69-74` (retries only transient errors) vs `packages/python-backend/src/shared_backend/postgres.py:63` (retries every exception); `packages/java-backend/src/main/java/com/gabriel20xx/shared/auth/Totp.java:80` (`String.equals`) vs constant-time comparison in Node and Python
- **Description:** Node and Python write incompatible hash formats into the same column, so a database shared between them cannot be verified by both. Python's list and create paths return the hash in their payloads; Node's do not. Java's middleware lets an unchecked exception escape where Node returns 401. The startup retry policy differs, so Python retries forever on errors that Node would surface immediately.
- **Impact:** A service behaves differently depending on which runtime serves it, and a password hash can reach an API response in Python.
- **Recommendation:** Standardise the hash format (or rehash on login), strip `password_hash` from every DTO, align the retry policy and the middleware failure modes, and add cross-language contract tests that run the same fixtures against each client.
### Q-009 · The Node and web-ui code has no linter, formatter or component tests · **Medium**
- **Location:** `.github/workflows/lint.yml` (Node job runs `npm run lint`, which is svelte-check and `node --check` only), `scripts/media/lint-all.mjs:57-64` (expects ESLint and Prettier configs in a package that does not have them), `packages/web-ui/` (no test files and no test script), `packages/node-backend/package.json` (no lint script)
- **Description:** No ESLint, Prettier or Stylelint configuration is tracked for `packages/web-ui` or `packages/node-backend`. Lint covers type checks and syntax only. `packages/web-ui` has no tests, so components such as `AuthPage`, `MediaPlayer` and the notification and primary-color stores are unverified.
- **Impact:** Style drift and behavioural regressions in a UI library that several applications consume.
- **Recommendation:** Add ESLint (with `eslint-plugin-svelte`) and Prettier configuration at package level, and a small Vitest and `@testing-library/svelte` suite covering `AuthPage`, the notification store and the primary-color helpers.
### Q-010 · Errors on security paths are masked as invalid codes or swallowed · **Low**
- **Location:** `packages/python-backend/src/shared_backend/authproxy.py:723` and `:740` (`except Exception` returns "Invalid authenticator code"), `packages/python-backend/src/shared_backend/authproxy.py:506-507` (logout ignores `APIError` but clears the cookie), `backend/auth/proxy.go:1232-1235` (`TOTPVerify` maps every error to 401 invalid code), `packages/java-backend/src/main/java/com/gabriel20xx/shared/auth/AuthClient.java:282-284` (`IOException` discarded without logging)
- **Description:** An AuthGuard outage looks like a wrong authenticator code, so operators and users cannot tell the two apart. Logout clears the browser cookie even when the upstream call fails, which can leave a valid server-side session behind.
- **Impact:** Harder debugging, misleading user feedback, and possible sessions that survive a logout.
- **Recommendation:** Catch the specific error classes. Return 502 or 503 for upstream failures, log transport errors at warning level, and clear local cookies only after the upstream logout succeeds or fails in a known way.
### Q-011 · Node version drift between publish and CI · **Low**
- **Location:** `.gitea/workflows/publish-npm.yml:24` (`node-version: 22`), `.github/workflows/lint.yml` and `.github/workflows/tests.yml` (`node-version: '24'`), `packages/node-backend/package.json` (`engines` `>=20`)
- **Description:** The packages are published from a build on Node 22, while lint and tests run on Node 24, and the package claims support from Node 20.
- **Impact:** The published artifacts are built with a different toolchain from the one that is tested, and the supported range is not exercised.
- **Recommendation:** Use one Node version for build and publish that matches what CI tests, and add a matrix entry for the minimum supported version.
### Q-012 · Package export maps are incomplete, and the root `.` export points at the README · **Low**
- **Location:** `package.json:19` (`"." : "./README.md"`), `package.json:28-33` (no `./node-backend/coreconfig` export, though the file ships in `files`), `packages/node-backend/package.json` `exports` (no `./totp` or `./authclient`, although both files exist and are re-exported from `src/index.js`), `packages/python-backend/src/shared_backend/__init__.py` (does not re-export `APIError`)
- **Description:** The root package's main entry resolves to a documentation file. Subpath imports for `totp` and `authclient` fail with `ERR_PACKAGE_PATH_NOT_EXPORTED` even though the modules exist, and the root export map omits `coreconfig`.
- **Impact:** Consumers cannot import documented modules, and tooling that resolves the package main gets the README.
- **Recommendation:** Point `.` at a real index module or remove it, add the missing subpath exports, and add a smoke test that imports every exported path.
### Q-013 · Versioning and changeset hygiene · **Low**
- **Location:** `.changeset/config.json:11` (ignores `@gabriel20xx/shared-workspace`, which does not exist; the root package is `@gabriel20xx/shared-code`), `packages/java-backend/pom.xml:6` (`0.1.0`, while the npm and Python packages are `0.1.1`), `packages/python-backend/pyproject.toml` (`0.1.1`, versioned by hand)
- **Description:** Changesets cover only the npm packages. Python and Java versions are maintained by hand, and recent changes to those packages (for example commits `f5a20b7`, `de9b599` and `97a5ecd`) have no changeset. The ignore entry names a package that does not exist.
- **Impact:** Release notes and version numbers can drift between runtimes.
- **Recommendation:** Correct the ignore entry. Either add changesets for the Python and Java packages, or document that they are versioned by tag and record the tag in the changelog.
### Q-014 · Stale README and comments after the component removal and the monorepo extraction · **Low**
- **Location:** `README.md:31` ("22 components"; the working-tree removal leaves 20 exports in `packages/web-ui/src/lib/index.ts`), `README.md:24` (names a `mediaauth` package that is not in `backend/`), `backend/authproxy/authproxy.go:9` and `backend/mediacore/migrate.go:15` (refer to `mediaauth`), `.gitignore:4` (`webui/.svelte-kit/` targets a directory that was removed)
- **Description:** Documentation names a package and a count that no longer match the tree, and a `.gitignore` entry targets a directory that no longer exists.
- **Impact:** Misleading documentation for consumers and maintainers.
- **Recommendation:** Update the component count to match `index.ts` when the removal is committed, delete the `mediaauth` references, and remove the stale ignore entry.
### Q-015 · Go code hygiene: dead code, an oversized file, duplicated helpers and nil-dependency constructors · **Low**
- **Location:** `backend/auth/reset.go` (`ResetManager` has no non-test consumer in this repository), `backend/auth/totp.go:23` (`TOTPSecretLength` unused), `backend/auth/proxy.go` (1525 lines mixing middleware, handlers and platform-user SQL), `backend/mediacore/mediacore.go:76-78` (`New` accepts nil CarrierNode or Sync; needs verification in the code), `backend/authclient/client.go:270-278` (two identical branches where the comment says there is a distinction), `writeJSON` and `writeError` duplicated across three packages
- **Description:** Exported helpers with no in-repository callers, a 1525-line file that mixes concerns, duplicated HTTP helpers, a constructor that accepts nil dependencies (which panics on first use rather than at startup), and a branch that is meant to separate transport failures from invalid sessions but returns the same result either way.
- **Impact:** Maintenance cost, and a misconfigured service fails on the first request rather than at startup.
- **Recommendation:** Remove or move unused code. Split `proxy.go` into middleware, handlers and persistence files. Validate constructor arguments. Share one JSON helper package, and make the authclient branches distinct or merge them.
### Q-016 · Web UI: an unkeyed `{#each}` over a prop, and a login-field length rule that also applies to sign-in · **Low**
- **Location:** `packages/web-ui/src/lib/components/Header.svelte:168` (`{#each navItems as item}` with no key), `packages/web-ui/src/lib/components/AuthPage.svelte:202` (`minlength="8"` on the sign-in password field, not only on setup)
- **Description:** The navigation list comes from a prop and is rendered without a key, so Svelte reconciles it by index. The sign-in field applies the setup minimum, so an account whose existing password is shorter cannot sign in through this form. Whether such accounts exist needs verification; the server enforces eight characters at setup (`backend/auth/proxy.go:1460`, `packages/node-backend/src/auth.js:57`, `packages/python-backend/src/shared_backend/auth.py:124`).
- **Impact:** Minor re-render inefficiency, and a possible lockout of legacy accounts.
- **Recommendation:** Key the each block by `item.href`, and apply `minlength` only when setup is required.
## Notes
- **Checked, clean:** No `TODO`, `FIXME`, `HACK` or `XXX` markers in first-party non-test code. No `any`, `@ts-ignore`, `@ts-expect-error` or `svelte-ignore` in `packages/web-ui/src`. No `{@html}`, `innerHTML`, `eval` or `new Function` in the web-ui or scripts. External links use `rel="noreferrer"`. Timers and document listeners are cleaned up in `StatusWidget`, `MediaPlayer`, `MediaPlayerControls`, `PrimaryColorPicker` and `notifications.svelte.ts`.
- **Checked, consistent:** Go code is gofmt-checked and `go vet`-checked in CI. Python code is ruff-checked (`E`, `F`, `I`). Node syntax is checked for `packages/node-backend`. Parameterised SQL is used across the Go, Node and Python stores.
- **Duplication by design:** The AuthGuard client exists in four languages on purpose. Q-008 covers where the behaviour has drifted.
- **Not run:** No lint, build, test, `go vet`, `ruff`, `svelte-check` or `npm` command was executed. All findings are from reading the code.
- **Not verified:** Whether consumers depend on the removed `UserManagement` export or the `MediaPlayerControls` barrel removal (the changeset says only AuthGuard used it). Whether the `packages/media-shared-assets` and `media-backend` paths in history were ever shipped.
- **Excluded from analysis:** `packages/web-ui/dist` and `.svelte-kit` (gitignored, not tracked), `package-lock.json` and `go.sum` (versions only), test bodies beyond coverage notes.
+143 -211
View File
@@ -1,194 +1,152 @@
# 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, and backend helpers (Postgres access, config, auth/session persistence, an AuthGuard client, log shipping) in four languages. Every project that consumes this repo — including the media-family services (CarrierNode, ContentScanner, CraftStudio, MediaViewer, KioskDisplay, ModerationHub, ProjectConfigurator) — is its own independent frontend/backend; none of them share a generic multi-flavor binary or app anymore.
The first packages are:
---
- `@gabriel20xx/design-tokens` — colors, typography, spacing, radii, shadows, and light/dark theme variables.
- `@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.
## Tech Stack
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 | Shared application shell and reusable UI components. The complete public component inventory is documented below. |
| `repos.gfranz.ch/Gabriel20xx/shared/backend` | Go | Env config, `pgx` pools/transactions, auth persistence, an AuthGuard client (`authclient`), log shipping (`logshipper`), embedded Goose migrations, and the media-family's shared route/table surface (`mediaauth`, `mediacore`, `carriernodeclient`, `syncsocket`). |
| `@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. |
### Public `web-ui` components
These are the complete Svelte component exports from `packages/web-ui/src/lib/index.ts` (22 components), grouped by purpose.
#### Layout and navigation
| Component | Includes |
|---|---|
| `AppShell` | Application layout that composes the header, notification stack, theme, and primary-color handling. |
| `Header` | Branded application header with navigation, icons, actions, profile/settings menus, and logout. |
#### Buttons and controls
| Component | Includes |
|---|---|
| `Button` | Button with primary, secondary, outline, ghost, and danger variants; multiple sizes and full-width mode. |
| `Pagination` | Page navigation and page-size selection with total/item counts. |
| `PrimaryColorPicker` | Per-project primary-color selector backed by the shared color persistence helpers. |
#### Dialogs
| Component | Includes |
|---|---|
| `AboutDialog` | About modal with application branding, description, version, links, and custom content. |
| `Dialog` | Generic modal dialog with title, description, body, footer, and bindable open state. |
| `SettingsDialog` | Generic settings modal with custom content or a default empty-settings message. |
#### Content and data display
| Component | Includes |
|---|---|
| `Badge` | Small inline label with default, primary, success, warning, and danger variants. |
| `Card` | Styled content section for grouping application content. |
| `EmptyState` | Empty-content message with an inbox icon, title, and description. |
| `Metric` | Labeled metric/value display with optional detail and semantic variants. |
| `SectionTitle` | Section heading with optional description. |
#### Feedback and status
| Component | Includes |
|---|---|
| `NotificationStack` | Global stack of dismissible success, error, warning, and informational notifications. |
| `StatusDialog` | Detailed service health/readiness status modal with refresh support. |
| `StatusWidget` | Header-friendly health/readiness indicator that polls `/healthz` and `/ready` and opens `StatusDialog`. |
#### Media
| Component | Includes |
|---|---|
| `MediaPlayer` | Audio/video player with playback, seeking, volume, quality, fullscreen, keyboard controls, and custom end controls. |
#### Accounts and access
| Component | Includes |
|---|---|
| `AuthPage` | Login, first-time setup, password-reset, and optional TOTP authentication flows. |
| `ProfileDialog` | Profile username/email/password editing and TOTP settings. |
| `TotpSettings` | TOTP status, setup, enable, and disable controls. |
This inventory describes the public component API only; the package also exports notification helpers, primary-color helpers, and TypeScript types. When a public component is added, removed, renamed, or materially changes responsibility, update the matching category table in the same change as `packages/web-ui/src/lib/index.ts`. Keep the tables aligned with that barrel file, place each component in the category that matches its primary purpose, and do not add internal or generated components to them.
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/` 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 `shared/` folder, regenerates any `package-lock.json` that depends on a local `file:` package, and commits/pushes only if something actually changed ("Sync shared snapshot from `<short-sha>`"). Consumers are registered in the script's `$consumerProjects` list. 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
npm install
npm run check
npm run build
npm run build # builds packages/web-ui/dist (gitignored, not committed)
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
cd backend
go test ./...
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
npm install --save-exact git+https://repos.gfranz.ch/Gabriel20xx/shared#<commit>
```
Use the shared UI from the root package:
```ts
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. The `publish-npm.yml` and
`publish-python.yml` Gitea workflows publish the packages when a `v*` tag is pushed or a
matching Gitea release is published. Configure `PACKAGE_REGISTRY_USERNAME` and
`PACKAGE_REGISTRY_TOKEN` as user Actions secrets before publishing.
The npm workflow publishes `design-tokens` first because `web-ui` depends on it. It also
skips an npm version that is already present, so retrying a partially completed release is safe.
The Python workflow uses Twine's `--skip-existing` option for the same reason.
## Install individual packages from a registry
From a project's frontend directory, install the published UI package from Gitea:
```bash
npm config set @gabriel20xx:registry https://repos.gfranz.ch/api/packages/Gabriel20xx/npm/
npm config set //repos.gfranz.ch/api/packages/Gabriel20xx/npm/:_authToken "$PACKAGE_REGISTRY_TOKEN"
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. The workflow also listens for Gitea's `release.published` event, so a release can be published from the Gitea Releases page to manually retry a failed upload for an existing tag. Never reuse a package version that was already uploaded successfully.
For Node services, install the shared package after publishing it:
```bash
npm install @gabriel20xx/node-backend@0.1.0
```
For Python services, configure the Gitea index and install the published wheel:
```bash
python -m pip install \
--index-url "https://$PACKAGE_REGISTRY_USERNAME:$PACKAGE_REGISTRY_TOKEN@repos.gfranz.ch/api/packages/Gabriel20xx/pypi/simple" \
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
## Typical `web-ui` wiring
```svelte
<script lang="ts">
import {
AboutDialog,
AppShell,
ProfileDialog,
SettingsDialog
} from '@gabriel20xx/web-ui';
import { AboutDialog, AppShell, ProfileDialog, SettingsDialog } from '@gabriel20xx/web-ui';
import { page } from '$app/state';
let aboutOpen = $state(false);
let profileOpen = $state(false);
let settingsOpen = $state(false);
const navItems = [
{ href: '/', label: 'Dashboard' },
{ href: '/about', label: 'About' }
];
</script>
<AppShell
brand="My application"
currentPath={page.url.pathname}
navItems={navItems}
navItems={[{ href: '/', label: 'Dashboard' }]}
onLogout={() => auth.logout()}
onProfile={() => (profileOpen = true)}
onSettings={() => (settingsOpen = true)}
@@ -198,70 +156,44 @@ The Node and Python packages intentionally expose the same infrastructure concep
<slot />
{/snippet}
</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
<AuthPage
brand="My application"
onLogin={(credentials) => auth.login(credentials.identifier, credentials.password)}
onSetup={(credentials) => auth.setup(credentials)}
onRequestReset={() => auth.requestAdminReset()}
onConfirmReset={(code) => auth.confirmAdminReset(code)}
setupRequired={setupRequired}
tagline="Your project tagline"
/>
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 `Core/AuthGuard/README.md` for the identity service this whole authentication surface is built to work with.
---
## Using the Go backend package
```go
import (
"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
`showTotp` and forward `credentials.totpToken` to their login endpoint. The base layout and reset
controls remain the same as every other shared auth screen.
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.
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
Before publishing, build the packages and install them from the local workspace in a frontend project:
## Publishing
```bash
# From Web/shared
npm run build
# From a project frontend directory; do not commit this file dependency for CI
npm install ../../../shared/packages/design-tokens ../../../shared/packages/web-ui
npm run changeset # describe the change
npm run version-packages # bump versions, commit the changelog
npm run release # publishes npm packages in dependency order (design-tokens first)
```
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.
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.
`lint.yml` and `tests.yml` each run three jobs — Node/Svelte, Go, and Python. `publish-npm.yml`, `publish-go.yml`, and `publish-python.yml` handle registry publishing as described above.
+163
View File
@@ -0,0 +1,163 @@
# Security Report — shared
- **Project:** shared
- **Path:** /workspace/Personal/Web/shared
- **Analyzed:** 2026-10-16
- **Commit:** 5216031 on main
- **Working tree:** 9 uncommitted change(s): `.changeset/user-management-roles.md` and `packages/web-ui/src/lib/components/UserManagement.svelte` deleted; `.changeset/remove-user-management.md` untracked; `README.md`, `MediaPlayerControls.svelte`, `packages/web-ui/src/lib/index.ts`, `packages/web-ui/src/lib/styles.css`, `packages/web-ui/src/lib/types.ts`, `shared-styles.css` modified. None of them touches authentication code.
- **Stack:** Go 1.25 (`backend/`: session proxy, AuthGuard client, websocket sync hub, media core, CarrierNode client, log shipper, Postgres helpers, goose migrations); Node.js ESM with `pg` (`packages/node-backend`); Python 3.10+ with asyncpg, bcrypt and optional FastAPI (`packages/python-backend`); Java 8 target with Jackson (`packages/java-backend`); Svelte 5 and TypeScript (`packages/web-ui`); PostgreSQL; Gitea and GitHub Actions. No Dockerfile is present.
- **Scope:** A shared library that other projects vendor as a snapshot. The AuthGuard identity service itself is not in this repository, so every finding that depends on AuthGuard's cookie attributes, rate limits or role enforcement is marked "needs verification". Read: all first-party code in the four languages (the Go auth package was read in a separate pass), the web-ui library source, workflows, scripts and manifests; git history was searched for credential-shaped content. Excluded: `node_modules`, `packages/web-ui/dist` and `.svelte-kit` (gitignored, not tracked), `package-lock.json` and `go.sum` (versions only), test bodies except to look for fixtures. Backend findings come from read-only static review passes, and the highest-severity citations were re-checked in the code. Nothing was built, run, audited or sent to the network.
## Summary
| Severity | Count |
|---|---:|
| Critical | 1 |
| High | 3 |
| Medium | 13 |
| Low | 5 |
| Info | 0 |
The most serious issue is a Python router route that lets an anonymous caller switch off login for everything guarded by `require_session`. Beyond it, the common themes are fail-open defaults, a websocket hub with no identity, credential endpoints with no throttling, and weaker-than-intended hashing and second-factor controls. No live secrets were found in the current tree or in git history. Most findings that depend on AuthGuard need confirmation against that service.
## Issues
### S-001 · Anonymous `PUT /access` switches off login for every guarded route · **Critical**
- **Location:** `packages/python-backend/src/shared_backend/authproxy.py:561-569` (`PUT /access` has no session or role dependency; `GET /access` at `:557-559` is also open), `packages/python-backend/src/shared_backend/authproxy.py:313-320` (`require_session` returns the local superadmin profile once login is not required), `packages/python-backend/src/shared_backend/authproxy.py:103-105` (`_LOCAL_PROFILE`), `packages/python-backend/tests/test_authproxy.py:116-122` (asserts the unauthenticated PUT succeeds)
- **Description:** The public `PUT /access` only depends on the store, so any anonymous request with `{"loginRequired": false}` disables authentication. Once the flag is off, `require_session` returns the superadmin profile for every request. The internal variant at `authproxy.py:570-584` correctly requires `X-Internal-Auth`; the public one does not. The Go equivalent, `backend/auth/proxy.go:781`, is documented as manager-only (`proxy.go:796`).
- **Impact:** Anyone who can reach a service that mounts `build_auth_router` can remove authentication from every route guarded by `require_session`. This is the documented usage (`packages/python-backend/README.md:123-133`), so exposure is likely in consumers. Consumer wiring was not reviewed.
- **Recommendation:** Require a user-manager session for `PUT /access`, and for `GET` unless the value is intentionally public. Add a `require_admin` dependency, mirroring the Go `RequireAdmin`. Change the test at `test_authproxy.py:116-122` to expect 401 without a session, and confirm no consumer exposes the router without this change.
### S-002 · Malformed cookies crash the Node middleware and fail requests in Java · **High**
- **Location:** `packages/node-backend/src/authclient.js:214` (`tokenFromRequest` runs before the `try` block), `packages/node-backend/src/authclient.js:239` (`decodeURIComponent` on the cookie value), `packages/java-backend/src/main/java/com/gabriel20xx/shared/auth/AuthClient.java:718-721` (`URLDecoder.decode` with only an `UnsupportedEncodingException` catch), `packages/java-backend/src/main/java/com/gabriel20xx/shared/auth/AuthClient.java:278` (`extractToken` called from `middleware`)
- **Description:** In Node, the async middleware calls `tokenFromRequest` before its `try`. `decodeURIComponent` throws `URIError` on a malformed escape such as a bare `%`, so the middleware rejects. Express 4 does not catch async rejections, and Node's default unhandled-rejection mode terminates the process. In Java, `URLDecoder.decode` throws `IllegalArgumentException` on a malformed escape; the only catch is for a different exception type, so the request fails with an error rather than a 401. `URLDecoder` also turns `+` into a space, which alters valid tokens.
- **Impact:** A single unauthenticated request with a crafted cookie can crash a Node service (the package requires Node 20 or newer, `packages/node-backend/package.json` `engines`). Java returns server errors instead of 401 and can mangle tokens containing `+`.
- **Recommendation:** Move token extraction inside the `try` in Node, and make `tokenFromRequest` return `''` on decode errors. In Java, catch `IllegalArgumentException` and percent-decode without treating `+` as a space. Add tests for malformed cookies in both packages.
### S-003 · The websocket sync hub has no identity, and self-asserted client IDs gate remote control · **High**
- **Location:** `backend/syncsocket/syncsocket.go:293` (`ServeWebSocket` accepts any connection), `backend/syncsocket/syncsocket.go:109` (client ID assigned from the message), `backend/syncsocket/syncsocket.go:366-369` (`control:claim` and `control:release` compare the requester against the same self-asserted ID), `backend/syncsocket/syncsocket.go:146-150` (every peer's ID and `remoteControlEnabled` is broadcast to all members)
- **Description:** The hub does not authenticate the connection. A client chooses its `clientId` in `sync:hello` or `client:status`, with no uniqueness or ownership check. Peers can see each other's IDs and control state, so a new client can adopt the ID of a peer that has remote control enabled and then claim or release that control.
- **Impact:** Any client that can reach `/ws` and join a session can take over playback control or impersonate another device. Exposure depends on whether each consumer gates `/ws` with authentication (not verifiable here; the package's own example wires it with no middleware).
- **Recommendation:** Bind each connection to a server-issued identity (an authenticated user or a signed session token) at upgrade time. Reject duplicate client IDs within a session. Require authentication on the `/ws` route in every consumer, and show that in the package documentation.
### S-004 · Anonymous `PUT /sync` writes unvalidated JSON into shared session state · **High**
- **Location:** `backend/mediacore/mediacore.go:88` (`r.With(c.auth.Optional).Put("/sync", ...)`), `backend/mediacore/mediacore.go:124-152` (`putSyncState`, which does not check the caller), `backend/mediacore/mediacore.go:135` (session ID defaults to `"default"`), `backend/mediacore/mediacore.go:138` and `:146-148` (raw `mediaId` and `playAt` stored), `backend/mediacore/mediacore.go:1049` (512 KB body cap), `backend/syncsocket/syncsocket.go:204-213` (1000-session cap, no per-entry size limit)
- **Description:** The route uses `Optional`, so anonymous callers reach `putSyncState`, which never checks who they are. Any caller can overwrite any session's playback state, including the shared `"default"` session. Values are stored without the type checks that the websocket path applies (`syncsocket.go:489-498`). This assumes `Optional` admits anonymous requests; `backend/auth` was not read in this pass (needs verification).
- **Impact:** Anonymous clients can overwrite shared playback state, and can pin substantial memory by filling many sessions with large bodies.
- **Recommendation:** Require authentication, or a session-scoped token, for `PUT /sync`. Validate `mediaId` and `playAt` types the way the websocket path does, and cap the stored size per session.
### S-005 · The Python proxy fails open to superadmin when AuthGuard is not configured, and the login override is per process · **Medium**
- **Location:** `packages/python-backend/src/shared_backend/authproxy.py:313-320` (`require_session` returns `_LOCAL_PROFILE` when `get_client` returns `None` or login is off), `packages/python-backend/src/shared_backend/authproxy.py:349` and `:389` (the configuration check runs only in `get_me` and `get_status`), `packages/python-backend/src/shared_backend/authproxy.py:255` and `:308-311` (process-local override that is never refreshed from the store), `packages/python-backend/src/shared_backend/authproxy.py:565-567` and `:582-583` (set the override). The Go handler has the same override pattern (`backend/auth/proxy.go:759-811`, per review).
- **Description:** A missing or unset AuthGuard URL silently makes every guarded route public with a superadmin identity, because the configuration error is enforced on only two routes. Separately, once a process has seen a login-required change, it keeps its own value and never re-reads the store, so other workers or replicas can disagree.
- **Impact:** A missing environment variable in production silently removes authentication. A worker can stay unauthenticated after login has been re-enabled elsewhere, until it restarts.
- **Recommendation:** Make auth-disabled mode an explicit opt-in flag that must be set, and apply the configuration check inside `require_session`. Remove the process-local override and read the store on each call, with a short-TTL cache if needed.
### S-006 · The documented core-config push guard fails open when the secret is unset, and the pushed AuthGuard URL is not validated · **Medium**
- **Location:** `packages/node-backend/README.md:50` (documented handler), `packages/node-backend/src/coreconfig.js:121` (same check, inside a JSDoc example), `packages/node-backend/src/coreconfig.js:67` (URL normalised, with no scheme or host check), `packages/python-backend/README.md:104` and `packages/python-backend/src/shared_backend/coreconfig.py:111` (same comparison in the Python example), `backend/coreconfig/coreconfig.go:182` (fails closed on an empty secret but compares with `!=`; per review), `backend/auth/proxy.go:819` (`r.Header.Get("X-Internal-Auth") != secret`)
- **Description:** The documented guard is `req.get('X-Internal-Auth') !== process.env.SECRET` (and the Python equivalent). If `SECRET` is unset and the header is absent, both sides are `undefined`, so the check passes. The examples do not reject an empty secret, and every comparison is non-constant-time. The store accepts any `authGuardUrl` and forwards it to `AuthClient.setBaseUrl`, so an accepted push can point session validation at a server the attacker controls. The Python internal route at `authproxy.py:576-581` does reject an empty secret, which is the correct pattern.
- **Impact:** A consumer that copies the example gets an authentication bypass through a push that controls the AuthGuard target. The timing difference is small in practice but is avoidable.
- **Recommendation:** Reject an empty configured secret in every handler. Compare with `crypto.timingSafeEqual` or `hmac.compare_digest`. Validate the scheme and host in the store before accepting a URL. Correct the examples.
### S-007 · Go proxy routes that change state accept any Content-Type and Origin · **Medium**
- **Location:** `backend/auth/proxy.go:1509` (`decodeProxyJSON` does not check `Content-Type`, `Origin` or `Sec-Fetch-Site`), state-changing handlers including `UpdateAccessSettings` (`proxy.go:781`), `UpdateMe` (`proxy.go:664`), managed-user create, update and delete (around `proxy.go:920`, `:951`, `:994`), `TOTPDisable` (`proxy.go:1239`) and `Logout` (`proxy.go:1144`)
- **Description:** There is no CSRF protection in the proxy. A cross-site form submission with a `text/plain` body is decoded just like a JSON request, so protection rests entirely on the `SameSite` attribute of the session cookie. That attribute is set by AuthGuard and forwarded here. `backend/authclient/client.go:324` notes that the cookie can be domain-scoped (`AUTH_COOKIE_DOMAIN`) for cross-project SSO, which makes sibling subdomains same-site.
- **Impact:** If a session cookie is domain-scoped and a sibling application is compromised or hostile, it can forge admin actions against this proxy. Needs verification of AuthGuard's cookie attributes.
- **Recommendation:** On non-GET routes, require `Content-Type: application/json` and check `Origin` or `Sec-Fetch-Site` against an allowlist, or require a custom header that cross-site forms cannot set. Confirm AuthGuard's `SameSite` setting.
### S-008 · Signup and first-run setup are not gated on the login setting, and the oldest user is re-promoted to superadmin on restart · **Medium**
- **Location:** `backend/auth/proxy.go:1014` (`Signup` checks only whether the service is enabled; no login-required check before forwarding), `backend/auth/proxy.go:724` (`AdminNeeded`), `backend/auth/store.go:92-94` (`EnsureSchema` promotes the oldest user when no superadmin exists), `backend/auth/store.go:237` (first account becomes superadmin)
- **Description:** When login is not required, `AdminNeeded` reports no setup is needed, but `Signup` does not check the setting. On a fresh AuthGuard the first caller to sign up becomes superadmin, and there is no bootstrap secret. Separately, at each schema initialisation, if no superadmin exists, the oldest user is promoted. Deleting or demoting the superadmin and then restarting elevates whoever is oldest, possibly an ordinary user.
- **Impact:** On a service with login disabled and no accounts, an anonymous visitor could register as superadmin of the shared AuthGuard (needs verification of AuthGuard's behaviour). Restarts can silently escalate privileges.
- **Recommendation:** Reject `Signup` when login is not required, or require a one-time setup token. Run the promotion only when the table is created, and otherwise require an explicit administrator action.
### S-009 · Login and TOTP endpoints have no attempt limiting, and the client's IP address is not forwarded · **Medium**
- **Location:** `backend/auth/proxy.go:1093` (`Login`), `backend/auth/proxy.go:1210` (`TOTPVerify`), `backend/auth/proxy.go:1239` (`TOTPDisable`), `backend/authclient/client.go:426-459` (outbound headers are bearer token, content type and project key only), `packages/python-backend/src/shared_backend/authclient.py` and `packages/node-backend/src/authclient.js` (same pattern; per review)
- **Description:** The proxy adds no throttling or lockout to password or six-digit TOTP attempts. The AuthGuard clients do not send the end user's IP address, so any per-IP limit that AuthGuard applies sees the proxy's address for every user.
- **Impact:** Password and TOTP guessing is limited only by AuthGuard, whose behaviour is not in this repository. A per-IP limit at AuthGuard either does nothing or locks out all users together. Needs verification of AuthGuard's limiter.
- **Recommendation:** Add a per-identifier and per-client-IP limiter in the proxy. Forward the client IP over a trusted channel using trusted-proxy-aware extraction, and confirm how AuthGuard limits attempts.
### S-010 · Self-service profile update changes the password without re-authentication · **Medium**
- **Location:** `backend/auth/proxy.go:664-712` (`UpdateMe` accepts `password` at `:700-709` and forwards it with only the session cookie)
- **Description:** A new password is validated and forwarded to AuthGuard without asking for the current password or a TOTP code.
- **Impact:** A stolen or fixated session cookie becomes permanent account takeover, because the attacker can set a new password. Needs verification of whether AuthGuard revokes other sessions on password change.
- **Recommendation:** Require the current password (and a TOTP code when enabled) for password or email changes, and revoke other sessions when the password changes.
### S-011 · TOTP codes can be replayed within their validity window in every runtime · **Medium**
- **Location:** `backend/auth/totp.go:56` (`VerifyTOTP` returns only a bool and does not report the matched step), `backend/auth/store.go:70-84` (no last-used-step column), `packages/node-backend/src/totp.js:26-53`, `packages/python-backend/src/shared_backend/totp.py:38-66`, `packages/java-backend/src/main/java/com/gabriel20xx/shared/auth/Totp.java:44-88` (per review)
- **Description:** Verification accepts the current and adjacent 30-second steps and records nothing about use. A code that an attacker observes stays valid for about 90 seconds and can be submitted repeatedly within that window.
- **Impact:** A phished or shoulder-surfed code can be reused.
- **Recommendation:** Return the matched time step, persist `last_used_step` per user, and reject any step less than or equal to it, updating it atomically.
### S-012 · The Java client parses the authentication decision with unanchored regular expressions · **Medium**
- **Location:** `packages/java-backend/src/main/java/com/gabriel20xx/shared/auth/AuthClient.java:109-112` (patterns for `valid`, `user_id`, `username`, `role`), with the parsing in `validate` (around lines 829-851, per review)
- **Description:** The values are extracted from the raw response body with `Matcher.find()`, which returns the first match anywhere in the text, including inside nested objects. The class already depends on Jackson (`packages/java-backend/pom.xml`), so a real parser is available.
- **Impact:** A change to AuthGuard's response shape, or a nested field with the same name, could make the client accept a session for the wrong user or role.
- **Recommendation:** Parse the response with Jackson and read top-level fields only. Add tests with nested and reordered fields.
### S-013 · Password hashing is below the intended settings in two runtimes · **Medium**
- **Location:** `packages/node-backend/src/auth.js:3` and `:56` (100,000 PBKDF2-SHA256 iterations, with an `iterations` option), `packages/node-backend/src/auth.js:61` and `:69-72` (verification always uses the constant, and the stored `salt:hash` format records no parameters), `backend/auth/proxy.go:1344` and `:1417` (`bcrypt.DefaultCost`, which is 10, for platform users) vs `backend/auth/password.go:7` (`BcryptCost = 12`, described as the one policy), `backend/auth/proxy.go:1460` (accepts up to 1024 runes, but bcrypt uses only the first 72 bytes)
- **Description:** The Node PBKDF2 count is fixed at 100,000 iterations. OWASP's current guidance for PBKDF2-HMAC-SHA256 is 600,000 (confirm against the current cheat sheet). A caller passing a different `iterations` value produces hashes that can never verify, and because the format stores no parameters the cost cannot be raised without a migration. Go's platform-user path hashes at cost 10 rather than the package's stated cost of 12. Bcrypt ignores bytes beyond 72, so long passwords are silently truncated, which the current validation does not prevent.
- **Impact:** Stored hashes are cheaper to crack than the package intends, and the cost cannot be upgraded.
- **Recommendation:** Store the algorithm and parameters with each hash and rehash on login. Raise the PBKDF2 count, or move to scrypt or argon2id. Call `HashPassword` everywhere in Go, and reject or pre-hash passwords longer than 72 bytes with a clear message.
### S-014 · Websocket origin verification is disabled when the allowed origin is `*` · **Medium**
- **Location:** `backend/syncsocket/syncsocket.go:267-270` (`websocketAcceptOptions` sets `InsecureSkipVerify = true` when `allowedOrigin == "*"`)
- **Description:** In `coder/websocket`, that option disables the Origin check. It is not TLS verification, despite the name. With the wildcard setting, any web page can open a sync socket from a visitor's browser, which combines with S-003 to let cross-site pages act as peers.
- **Impact:** A page on any origin can connect to a LAN-hosted sync hub, read session state and send control messages if identity is not enforced.
- **Recommendation:** Remove the wildcard escape hatch, or require an explicit origin list. Never map `"*"` to `InsecureSkipVerify`.
### S-015 · Peer IP addresses and user agents are broadcast to all session members, and X-Forwarded-For is trusted unconditionally · **Medium**
- **Location:** `backend/syncsocket/syncsocket.go:301` (first `X-Forwarded-For` value used with no trusted-proxy check), `backend/syncsocket/syncsocket.go:146-150` (IP address and user agent sent to every peer in the session)
- **Description:** The client's address is taken from the first `X-Forwarded-For` value whenever that header is present, and it is shared with every session member along with the user agent.
- **Impact:** Any session member can see the addresses and user agents of other members, and a client can spoof the address that others see.
- **Recommendation:** Honour `X-Forwarded-For` only from configured trusted proxies, and remove IP address and user agent from broadcast payloads.
### S-016 · Store primitives allow identity confusion and silently disable TOTP · **Medium**
- **Location:** `backend/auth/store.go:261` (`WHERE username = $1 OR lower(email) = lower($1)`, with no ordering), `backend/auth/store.go:72` (username is unique only case-sensitively), `backend/auth/store.go:184` (`SetTOTPSecret` sets `totp_enabled = false`), `backend/auth/store.go:277-285` (`UpdateCredentials` writes whatever `passwordHash` it receives, per review)
- **Description:** The identifier lookup matches a username against any account's email, so a username can equal another account's email and make the match ambiguous. Usernames are unique only case-sensitively, so `Admin` and `admin` can both exist. `SetTOTPSecret` silently disables an enabled second factor if it is called. Credential updates accept an empty hash.
- **Impact:** Ambiguous logins that can route a sign-in to the wrong account, and silent second-factor removal if a caller makes a mistake.
- **Recommendation:** Add a unique index on `lower(username)`. Reject usernames containing `@`. Look up usernames and emails separately with a deterministic order. Refuse `SetTOTPSecret` while TOTP is enabled, and reject empty password hashes.
### S-017 · Stored paths and caller-supplied names are concatenated into CarrierNode URLs without escaping or validation · **Medium**
- **Location:** `backend/mediacore/mediacore.go:187` and `:224` (`"/media/" + urlPath(record.FilePath)` from the database), `backend/mediacore/mediacore.go:992-997` (`urlPath` strips only leading slashes and a `media/` prefix), `backend/carriernodeclient/carriernodeclient.go:144` (path concatenated without escaping), `backend/carriernodeclient/carriernodeclient.go:673-719` (`PushThumbnail`, `DeleteThumbnail`, `PushOutput`, `PushInput`, `PushCopy` use `url.PathEscape` only, which leaves `.` and `..` unchanged), `backend/carriernodeclient/carriernodeclient.go:453-458` (a strict `thumbnailFile` check exists for thumbnails only), `backend/carriernodeclient/carriernodeclient.go:228-246` (`MountPath` escapes segments and rejects `..` correctly)
- **Description:** A stored `file_path` containing `?`, `#` or `..` is parsed by CarrierNode as a query, a fragment, or a traversal. `SafeRelative` is applied to IDs but not to stored paths. The push and delete helpers escape `/` but not `.` or `..`, and no name validation runs for them.
- **Impact:** A malformed stored path or caller-supplied name can address a different upstream resource, or write or delete outside the intended root, depending on CarrierNode's own checks (not in this repository; needs verification).
- **Recommendation:** Apply `SafeRelative` to stored paths, escape each segment as `MountPath` does, and reject query and fragment characters. Validate names in every push and delete helper the way `thumbnailFile` does (reject `.`, `..` and path separators).
### S-018 · The role vocabulary is defined three ways, and role assignments are not checked locally · **Low**
- **Location:** `backend/auth/proxy.go:629-634` (`IsAdmin` treats `moderator` as admin), `backend/auth/roles.go:13-32` (`NormalizeRole`, `CanManageUsers`, `CanAssignRole`; `CanAssignRole` is not called from the handlers), `backend/auth/proxy.go:935-938` and `:965-971` (client-supplied role forwarded to AuthGuard)
- **Description:** `IsAdmin` admits moderators while `NormalizeRole` and `CanManageUsers` do not. The assignment check exists but is not used, and roles from requests are forwarded without a local check.
- **Impact:** Moderators may receive access that the other definitions do not grant, and an escalation becomes possible if AuthGuard or the calling service does not enforce role rules (needs verification).
- **Recommendation:** Use one typed role set. Call `CanAssignRole` in the managed-user handlers as defence in depth, and restrict or document what moderators can do.
### S-019 · Reset codes are weak and unlimited, and TOTP secrets are stored in plaintext · **Low**
- **Location:** `backend/auth/reset.go:37` (four random bytes, so 32 bits), `backend/auth/reset.go:48` (code printed to stdout), `packages/node-backend/src/auth.js:106` (`randomBytes(4)`), `packages/python-backend/src/shared_backend/auth.py:83` and `:101` (`token_hex(4)` with `compare_digest`), `packages/java-backend/src/main/java/com/gabriel20xx/shared/auth/ResetManager.java` (per review), `backend/auth/store.go:84` (`totp_secret TEXT`), `packages/node-backend/src/auth.js:30` (`totp_secret TEXT`)
- **Description:** Administrator reset codes are 32-bit values. They can be guessed with unlimited attempts during their five-minute life, and calling `request` again rotates them. The code is printed to stdout, where log shipping may capture it. TOTP seeds are stored in plaintext in `auth_users`.
- **Impact:** A reset code can be brute-forced within its lifetime, and second-factor seeds are exposed if the database leaks.
- **Recommendation:** Add an attempt counter with lockout, and require an authenticated caller to request a code. Do not print codes to stdout in production. Encrypt TOTP secrets at rest with an application key kept outside the database.
### S-020 · Insecure-by-configuration options: secure cookies off by default, and database certificate verification can be disabled · **Low**
- **Location:** `packages/python-backend/src/shared_backend/authproxy.py:244` (`secure_cookie` defaults to `False`), `packages/python-backend/src/shared_backend/authproxy.py:276` (`Secure` applied to cleared cookies), `packages/python-backend/src/shared_backend/authproxy.py:279-281` (AuthGuard `Set-Cookie` values forwarded unchanged), `packages/node-backend/src/config.js:48-51` (`DATABASE_SSL_ALLOW_INVALID` sets `rejectUnauthorized: false`)
- **Description:** The Python proxy does not set or validate `Secure`, `HttpOnly` or `SameSite` on forwarded session cookies, and `Secure` defaults to off. The Node configuration lets an environment flag turn off database certificate verification. Both are opt-in, but the defaults are the unsafe choice.
- **Impact:** Session cookies can travel over cleartext behind an HTTPS misconfiguration, and database connections can be made without certificate checks.
- **Recommendation:** Default `secure_cookie` to true, or derive it from the request scheme. Rewrite forwarded cookie attributes, and log a warning when database TLS verification is disabled.
### S-021 · CI workflows and repository hygiene need hardening, and history contains an example file with embedded database credentials · **Low**
- **Location:** `.github/workflows/lint.yml:37`, `:39`, `:59`, `:61` and `.github/workflows/tests.yml` (actions referenced by mutable tags such as `actions/checkout@v4`), `.gitea/workflows/publish-npm.yml:71`, `.gitea/workflows/publish-go.yml:61`, `.gitea/workflows/publish-python.yml:43` (registry token passed as a `curl --user` argument, so it is visible in process listings on the runner), `.gitignore` (no rules for `.env*`, `*.pem`, `*.key` or `.npmrc`), git history: commit `acde180` added `media-backend/.env.example`, which the working tree no longer contains; its `DATABASE_URL` line contains embedded credentials (value redacted, needs verification of whether it was ever valid)
- **Description:** Action references are mutable tags rather than commit SHAs. Workflow permissions are correctly `contents: read`. Registry credentials appear on command lines during upload, although the npm workflow correctly writes its token to a file. The ignore rules do not block common secret files, so an accidental commit would not be stopped. The removed example file shows that a connection string with credentials was committed once.
- **Impact:** Supply-chain exposure from tag changes, credential exposure to other processes on a shared runner, and a higher chance of future secret commits.
- **Recommendation:** Pin actions to commit SHAs. Pass registry credentials through a netrc or header file rather than argv. Add `.env*`, `*.pem`, `*.key` and `.npmrc` to `.gitignore`. Confirm that the historical credential is not live, and rotate it if it is.
### S-022 · Media stream and thumbnail routes are unauthenticated, and upstream content types reach the app origin unchecked · **Low**
- **Location:** `backend/mediacore/mediacore.go:95-97` (`/media/stream` and `/media/thumb` registered without an auth wrapper, unlike the other media routes), `backend/carriernodeclient/carriernodeclient.go:202-206` (upstream `Content-Type` and `Content-Disposition` copied, with no `X-Content-Type-Options` or CSP), `backend/mediacore/mediacore.go:957-960` (`ServeFile` maps extensions such as `.html` and `.svg` to active types)
- **Description:** Anyone who knows a media key can download the file, and the list endpoints return those keys. Proxied responses keep the upstream content type without `nosniff` or a restrictive CSP, so a file stored with an HTML or SVG type would render on the application origin. This module has no upload handler, so whether such files can exist depends on CarrierNode and its writers (needs verification).
- **Impact:** Public access to media if the library is meant to be private, and stored XSS if active content can be placed under a media path.
- **Recommendation:** Add `Optional` or `Require` to these routes unless public access is intended, and document the choice. Set `X-Content-Type-Options: nosniff` and a restrictive CSP on proxied and served media, and force attachment or an allowlisted type for non-media extensions. Also check `backend/mediacore/mediacore.go:723`, which returns the full `*sharedauth.User` struct from the request context; whether that exposes secrets depends on its JSON tags in `backend/auth` (not reviewed).
## Notes
- **Positive checks:** No live credentials were found in the current tracked files. The only credential-shaped matches are identifiers (fields named `password`, `secret` or `token`), environment-variable references in `.gitea/workflows/publish-python.yml`, and test fixtures: `packages/node-backend/test/auth.test.js:37` uses the public RFC 6238 test secret, and `packages/python-backend/tests/test_core.py:38` and `backend/coreconfig/coreconfig_test.go:38,132-133` use short placeholder values. In git history, about twenty commits matched credential-shaped patterns; all were code identifiers or test fixtures, except the example file described in S-021. Values were masked during the review and are not reproduced here.
- **Web UI:** No `{@html}`, `innerHTML`, `eval` or `new Function` was found. External links use `rel="noreferrer"`. `fetch` is used only in `StatusWidget.svelte` (same-origin relative paths with credentials included); auth requests are delegated to the consuming application through callbacks, so CSRF and session handling live in the backend. The primary-color writer builds CSS only from palette values.
- **Checked, no issue found:** SQL is parameterised in the Go, Node and Python stores and in the mediacore queries; dynamic `SET` fragments use fixed column names. Tokens and secrets come from `crypto/rand`, `crypto.randomBytes`, Python `secrets` and `SecureRandom`; no `math/rand`, `Math.random`, `random.` or `java.util.Random` was found. Session tokens are 256-bit and stored as SHA-256 hashes, and no JWT is used. No `eval`, `pickle`, `yaml.load`, `shell=True`, `os.system` or `exec.Command` appears in scope. No `InsecureSkipVerify` on any TLS configuration; the only use is the websocket origin option (S-014). The Go request bodies are capped (512 KB for mediacore, 4 KB for coreconfig, 128 KB for the proxy). Outbound clients have timeouts. Logout clears cookies with `HttpOnly` and `SameSite` in the Python proxy. No CORS configuration or debug mode was found.
- **Dependencies (not audited):** No known-vulnerable version is asserted in this report, since no audit tool or network access was used. Versions to confirm: Go `coder/websocket` v1.8.15, `go-chi/chi` v5.3.1, `pgx` v5.10.0, `goose` v3.27.3, `golang.org/x/crypto` v0.54.0 (`backend/go.mod`); Node `pg` 8.22.0 (locked in `package-lock.json`, declared `^8.17.2`); Python `bcrypt>=4.2` and `asyncpg>=0.30` with no upper bounds (`packages/python-backend/pyproject.toml`); Java Jackson 2.18.6, JUnit 5.10.2 (`packages/java-backend/pom.xml`). Run `govulncheck`, `npm audit`, `pip-audit` and an OWASP dependency check.
- **Not verified / coverage gaps:** AuthGuard's own server code (cookie attributes, rate limiting, role enforcement, session revocation on password change) is not in this repository, so every finding marked "needs verification" depends on it. Consumer wiring of `/ws`, `/media/*`, `/access` and the core-config route was not reviewed. `backend/auth` and `backend/config` were covered by a separate pass. CarrierNode-side path validation and the file types it stores are outside the repository. Java `AuthClient` cookie and redirect behaviour was assessed from code only. Test bodies were not run, and no server was started.
- **Excluded from analysis:** `packages/web-ui/dist` and `.svelte-kit` (gitignored, not tracked), `package-lock.json` and `go.sum` (versions only), and `node_modules`.
+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.
- `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.
- `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.
- `logshipper` — client adapter for OmniLogger (Web/OmniLogger): 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
`repos.gfranz.ch/Gabriel20xx/shared/backend`; change it if the shared folder is
File diff suppressed because it is too large. Load diff
+134
View File
@@ -0,0 +1,134 @@
package auth
import (
"context"
"net/http"
"net/http/httptest"
"testing"
)
// fakeProxyStore is a minimal in-memory ProxyStore for constructing a
// Service in tests without a real database.
type fakeProxyStore struct {
loginRequired bool
setupClaimed bool
}
func (s *fakeProxyStore) LoginRequired(context.Context) (bool, error) { return s.loginRequired, nil }
func (s *fakeProxyStore) SetLoginRequired(_ context.Context, v bool) error {
s.loginRequired = v
return nil
}
func (s *fakeProxyStore) IsSetupClaimed(context.Context) (bool, error) { return s.setupClaimed, nil }
func (s *fakeProxyStore) TryClaimSetup(context.Context) (bool, error) {
if s.setupClaimed {
return false, nil
}
s.setupClaimed = true
return true, nil
}
func (s *fakeProxyStore) UnclaimSetup(context.Context) error {
s.setupClaimed = false
return nil
}
type noOpLoginProxyStore struct{ fakeProxyStore }
func (s *noOpLoginProxyStore) SetLoginRequired(context.Context, bool) error { return nil }
// TestPendingModeStillGatesRequests locks in the fix that made an empty
// authGuardURL at construction mean "pending" (auth still enabled, calls
// fail closed until a real URL arrives via SetAuthGuardBaseURL) instead of
// "disabled" (nothing gated, a fixed superadmin identity) - the bug that
// made AUTHGUARD_URL a de-facto requirement even though ProjectConfigurator
// can push it live after startup.
func TestPendingModeStillGatesRequests(t *testing.T) {
service := NewWithStore(&fakeProxyStore{loginRequired: true}, "session", false, "", "testproject")
if !service.enabled() {
t.Fatal("Service with no authGuardURL and no Disabled() option should still be enabled (pending), not disabled")
}
req := httptest.NewRequest(http.MethodGet, "/", nil)
req.AddCookie(&http.Cookie{Name: "auth_session", Value: "sometoken"})
if _, err := service.CurrentUser(req); err == nil {
t.Fatal("pending Service (no AuthGuard URL yet) should fail closed on a real session cookie, not silently resolve a user")
}
}
// TestDisabledOptionSkipsGating confirms the explicit opt-out still works
// exactly like the old "empty authGuardURL" behavior.
func TestDisabledOptionSkipsGating(t *testing.T) {
service := NewWithStore(&fakeProxyStore{}, "session", false, "", "testproject", Disabled())
if service.enabled() {
t.Fatal("Service built with Disabled() should report enabled() == false")
}
req := httptest.NewRequest(http.MethodGet, "/", nil)
user, err := service.CurrentUser(req)
if err != nil || user == nil || user.Username != "Admin" || !IsAdmin(user) {
t.Fatalf("Disabled() Service should resolve the fixed Admin superadmin profile, got user=%+v err=%v", user, err)
}
}
func TestLoginDisabledUsesAdminIdentityWithoutCredentials(t *testing.T) {
store := &fakeProxyStore{loginRequired: false}
service := NewWithStore(store, "session", false, "", "testproject")
req := httptest.NewRequest(http.MethodGet, "/", nil)
user, err := service.CurrentUser(req)
if err != nil || user == nil || user.Username != "Admin" || !IsAdmin(user) {
t.Fatalf("login-disabled Service should resolve the Admin identity, got user=%+v err=%v", user, err)
}
called := false
handler := service.RequireAdminIfLoginRequired(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
called = true
contextUser := UserFromContext(r.Context())
if contextUser == nil || contextUser.Username != "Admin" || !IsAdmin(contextUser) {
t.Errorf("middleware context user = %+v, want Admin superadmin", contextUser)
}
w.WriteHeader(http.StatusNoContent)
}))
response := httptest.NewRecorder()
handler.ServeHTTP(response, req)
if response.Code != http.StatusNoContent || !called {
t.Fatalf("login-disabled admin middleware status = %d/called=%v, want %d/true", response.Code, called, http.StatusNoContent)
}
}
func TestInternalLoginOverrideWorksWithNoOpStore(t *testing.T) {
store := &noOpLoginProxyStore{fakeProxyStore: fakeProxyStore{loginRequired: true}}
service := NewWithStore(store, "session", false, "", "testproject")
if err := service.SetLoginRequired(context.Background(), false); err != nil {
t.Fatalf("SetLoginRequired() error = %v", err)
}
user, err := service.CurrentUser(httptest.NewRequest(http.MethodGet, "/", nil))
if err != nil || user == nil || user.Username != "Admin" {
t.Fatalf("no-op store override resolved user=%+v err=%v, want Admin", user, err)
}
}
func TestNormalizeProxyCredentials(t *testing.T) {
email, username, password, err := normalizeProxyCredentials(" 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 TestNormalizeProxyCredentialsAllowsAdminEmailOnly(t *testing.T) {
if _, _, _, err := normalizeProxyCredentials("admin@example.com", "", "correct horse battery staple"); err != nil {
t.Fatalf("empty optional username rejected: %v", err)
}
}
func TestNormalizePlatformRole(t *testing.T) {
if normalizePlatformRole("MODERATOR") != "moderator" {
t.Fatal("moderator role was not normalized")
}
if normalizePlatformRole("unknown") != "user" {
t.Fatal("unknown role was not reduced to user")
}
}
+225 -11
View File
@@ -7,6 +7,7 @@ import (
"context"
"errors"
"fmt"
"strings"
"time"
"github.com/jackc/pgx/v5"
@@ -24,6 +25,9 @@ type User struct {
Role Role
CreatedAt 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.
@@ -43,6 +47,11 @@ type SchemaOptions struct {
SingleUser bool
// APITokens creates the optional per-user API token table.
APITokens bool
// ProjectScoping creates auth_known_projects/auth_user_projects, backing per-user
// project-access restriction (see Store.SetUserProjects/IsProjectAllowed). Only AuthGuard
// itself needs this - every other project only ever calls AuthGuard's own API, never these
// tables directly.
ProjectScoping bool
}
// DefaultSchemaOptions returns the single-account schema used by most small
@@ -67,7 +76,8 @@ func EnsureSchema(ctx context.Context, pool *pgxpool.Pool, options SchemaOptions
totp_secret TEXT NOT NULL DEFAULT '',
totp_enabled BOOLEAN NOT NULL DEFAULT FALSE,
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 role TEXT NOT NULL DEFAULT 'user';
@@ -75,6 +85,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 created_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'
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');
@@ -105,6 +119,24 @@ func EnsureSchema(ctx context.Context, pool *pgxpool.Pool, options SchemaOptions
return fmt.Errorf("remove single-user auth constraint: %w", err)
}
if options.ProjectScoping {
if _, err := pool.Exec(ctx, `
CREATE TABLE IF NOT EXISTS auth_known_projects (
project TEXT PRIMARY KEY,
label TEXT NOT NULL DEFAULT '',
updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
CREATE TABLE IF NOT EXISTS auth_user_projects (
user_id BIGINT NOT NULL REFERENCES auth_users(id) ON DELETE CASCADE,
project TEXT NOT NULL,
PRIMARY KEY (user_id, project)
);
CREATE INDEX IF NOT EXISTS auth_user_projects_project_idx ON auth_user_projects (project);
`); err != nil {
return fmt.Errorf("ensure project-scoping schema: %w", err)
}
}
if options.APITokens {
if _, err := pool.Exec(ctx, `
CREATE TABLE IF NOT EXISTS auth_api_tokens (
@@ -204,9 +236,9 @@ func (s *Store) CreateUser(ctx context.Context, username, email, passwordHash st
VALUES ($1, $2, $3,
CASE WHEN EXISTS (SELECT 1 FROM auth_users) THEN 'user' ELSE 'superadmin' END,
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(
&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 {
var pgErr *pgconn.PgError
@@ -224,7 +256,7 @@ func (s *Store) FindByIdentifier(ctx context.Context, identifier string) (*User,
return nil, err
}
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 username = $1 OR lower(email) = lower($1)
`, identifier)
@@ -236,7 +268,7 @@ func (s *Store) FindByID(ctx context.Context, id int64) (*User, error) {
return nil, err
}
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
`, id)
}
@@ -264,7 +296,7 @@ func (s *Store) ListUsers(ctx context.Context) ([]User, error) {
return nil, err
}
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
`)
if err != nil {
@@ -274,7 +306,7 @@ func (s *Store) ListUsers(ctx context.Context) ([]User, error) {
users := make([]User, 0)
for rows.Next() {
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)
}
users = append(users, user)
@@ -292,9 +324,9 @@ func (s *Store) CreateManagedUser(ctx context.Context, username, email, password
err := s.pool.QueryRow(ctx, `
INSERT INTO auth_users (username, email, password_hash, role, updated_at)
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(
&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 {
var pgErr *pgconn.PgError
@@ -326,6 +358,20 @@ func (s *Store) UpdateUser(ctx context.Context, id int64, username, email, passw
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.
func (s *Store) DeleteUser(ctx context.Context, id int64) error {
if err := s.validate(); err != nil {
@@ -358,7 +404,7 @@ func (s *Store) FindSessionUser(ctx context.Context, tokenHash string) (*User, e
return nil, err
}
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
JOIN auth_users u ON u.id = s.user_id
WHERE s.token_hash = $1 AND s.expires_at > now()
@@ -411,6 +457,174 @@ func (s *Store) DeleteExpiredSessions(ctx context.Context) error {
return nil
}
// KnownProject is one project ProjectConfigurator has registered, pushed to AuthGuard so its
// admin UI can offer real, live project keys instead of free-form text - see SetKnownProjects.
type KnownProject struct {
Key string
Label string
}
// SetKnownProjects replaces the full set of known projects (pushed by ProjectConfigurator's
// PUT /api/projects/internal whenever its registered-project list changes). A project no longer
// registered is dropped, so the admin UI never offers a stale key; existing auth_user_projects
// rows for a removed project are left alone (harmless - IsProjectAllowed only ever compares
// against a user's own rows, never against auth_known_projects).
func (s *Store) SetKnownProjects(ctx context.Context, projects []KnownProject) error {
if err := s.validate(); err != nil {
return err
}
tx, err := s.pool.Begin(ctx)
if err != nil {
return fmt.Errorf("set known projects: %w", err)
}
defer tx.Rollback(ctx)
if _, err := tx.Exec(ctx, `DELETE FROM auth_known_projects`); err != nil {
return fmt.Errorf("set known projects: %w", err)
}
for _, project := range projects {
key := strings.ToLower(strings.TrimSpace(project.Key))
if key == "" {
continue
}
if _, err := tx.Exec(ctx, `
INSERT INTO auth_known_projects (project, label, updated_at) VALUES ($1, $2, now())
ON CONFLICT (project) DO UPDATE SET label = EXCLUDED.label, updated_at = now()
`, key, strings.TrimSpace(project.Label)); err != nil {
return fmt.Errorf("set known projects: %w", err)
}
}
if err := tx.Commit(ctx); err != nil {
return fmt.Errorf("set known projects: %w", err)
}
return nil
}
// KnownProjects returns every registered project, ordered by key.
func (s *Store) KnownProjects(ctx context.Context) ([]KnownProject, error) {
if err := s.validate(); err != nil {
return nil, err
}
rows, err := s.pool.Query(ctx, `SELECT project, label FROM auth_known_projects ORDER BY project`)
if err != nil {
return nil, fmt.Errorf("list known projects: %w", err)
}
defer rows.Close()
projects := make([]KnownProject, 0)
for rows.Next() {
var project KnownProject
if err := rows.Scan(&project.Key, &project.Label); err != nil {
return nil, fmt.Errorf("scan known project: %w", err)
}
projects = append(projects, project)
}
return projects, rows.Err()
}
// SetUserProjects replaces the full set of projects userID is restricted to. An empty projects
// list means unrestricted (see IsProjectAllowed) - the default for every account until an
// administrator explicitly scopes it, so this feature is opt-in and never breaks an existing
// deployment's accounts on upgrade.
func (s *Store) SetUserProjects(ctx context.Context, userID int64, projects []string) error {
if err := s.validate(); err != nil {
return err
}
tx, err := s.pool.Begin(ctx)
if err != nil {
return fmt.Errorf("set user projects: %w", err)
}
defer tx.Rollback(ctx)
if _, err := tx.Exec(ctx, `DELETE FROM auth_user_projects WHERE user_id = $1`, userID); err != nil {
return fmt.Errorf("set user projects: %w", err)
}
seen := map[string]bool{}
for _, project := range projects {
key := strings.ToLower(strings.TrimSpace(project))
if key == "" || seen[key] {
continue
}
seen[key] = true
if _, err := tx.Exec(ctx, `INSERT INTO auth_user_projects (user_id, project) VALUES ($1, $2)`, userID, key); err != nil {
return fmt.Errorf("set user projects: %w", err)
}
}
if err := tx.Commit(ctx); err != nil {
return fmt.Errorf("set user projects: %w", err)
}
return nil
}
// UserProjects returns the projects userID is restricted to, or an empty slice when unrestricted.
func (s *Store) UserProjects(ctx context.Context, userID int64) ([]string, error) {
if err := s.validate(); err != nil {
return nil, err
}
rows, err := s.pool.Query(ctx, `SELECT project FROM auth_user_projects WHERE user_id = $1 ORDER BY project`, userID)
if err != nil {
return nil, fmt.Errorf("list user projects: %w", err)
}
defer rows.Close()
projects := make([]string, 0)
for rows.Next() {
var project string
if err := rows.Scan(&project); err != nil {
return nil, fmt.Errorf("scan user project: %w", err)
}
projects = append(projects, project)
}
return projects, rows.Err()
}
// UserProjectsByUser bulk-loads every user's project restrictions in one query, for the admin
// user list screen (avoids one query per row).
func (s *Store) UserProjectsByUser(ctx context.Context) (map[int64][]string, error) {
if err := s.validate(); err != nil {
return nil, err
}
rows, err := s.pool.Query(ctx, `SELECT user_id, project FROM auth_user_projects ORDER BY user_id, project`)
if err != nil {
return nil, fmt.Errorf("list user projects: %w", err)
}
defer rows.Close()
result := map[int64][]string{}
for rows.Next() {
var userID int64
var project string
if err := rows.Scan(&userID, &project); err != nil {
return nil, fmt.Errorf("scan user project: %w", err)
}
result[userID] = append(result[userID], project)
}
return result, rows.Err()
}
// IsProjectAllowed reports whether userID may authenticate against project: true when the
// account has no project restrictions at all (the default for every account), or when project is
// one of its assigned projects. An empty project (a caller that sent no project-key header - a
// service not yet migrated to identify itself, or a browser request straight to AuthGuard's own
// web UI, which is not itself a "project" another service authenticates against) is always
// allowed; restriction only ever applies once a caller actually identifies itself.
func (s *Store) IsProjectAllowed(ctx context.Context, userID int64, project string) (bool, error) {
project = strings.ToLower(strings.TrimSpace(project))
if project == "" {
return true, nil
}
if err := s.validate(); err != nil {
return false, err
}
var total int
if err := s.pool.QueryRow(ctx, `SELECT count(*) FROM auth_user_projects WHERE user_id = $1`, userID).Scan(&total); err != nil {
return false, fmt.Errorf("count user projects: %w", err)
}
if total == 0 {
return true, nil
}
var allowed bool
if err := s.pool.QueryRow(ctx, `SELECT EXISTS(SELECT 1 FROM auth_user_projects WHERE user_id = $1 AND project = $2)`, userID, project).Scan(&allowed); err != nil {
return false, fmt.Errorf("check user project: %w", err)
}
return allowed, nil
}
var ErrUserExists = errors.New("auth user already exists")
func (s *Store) validate() error {
@@ -423,7 +637,7 @@ func (s *Store) validate() error {
func (s *Store) find(ctx context.Context, query string, arg any) (*User, error) {
var user User
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) {
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)
}
}
+633
View File
@@ -0,0 +1,633 @@
// 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"
"sync"
"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 {
// baseURLMu guards baseURL so SetBaseURL can be called concurrently with
// Validate/Middleware/the rest of the API surface - see SetBaseURL.
baseURLMu sync.RWMutex
// baseURL is AuthServer's base URL, e.g. "https://auth.example.com" (no
// trailing slash required). Read/written only through getBaseURL/
// SetBaseURL once construction is done.
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
// projectKey identifies the calling project to AuthServer (sent as the
// ProjectKeyHeader on every request) so per-user project-access
// restrictions can be enforced. Empty means "don't identify" - the
// caller is treated as unrestricted; see AuthServer's project-scoping
// feature and WithProjectKey.
projectKey string
}
// ProjectKeyHeader is the header Client attaches to every request identifying
// which project is calling, so AuthServer can enforce per-user project-access
// restriction (see WithProjectKey). AuthServer treats a missing/empty header
// the same as "this caller has no project identity": never restricted.
const ProjectKeyHeader = "X-Project-Key"
// 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 }
}
// WithProjectKey identifies this Client's project to AuthServer (see
// ProjectKeyHeader), enabling per-user project-access restriction. key is
// normally a project's own lowercase identifier, matching the same key
// ProjectConfigurator's Projects workspace registers it under (e.g.
// "carriernode", "gamestream", "omnilogger") - see AuthServer's project-scope
// admin UI, which assigns users access using these same keys.
func WithProjectKey(key string) Option {
return func(c *Client) { c.projectKey = strings.ToLower(strings.TrimSpace(key)) }
}
// 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
}
// SetBaseURL atomically replaces the AuthServer base URL this Client calls,
// normalizing it the same way New does. Safe to call concurrently with
// Validate/Middleware/any other method on this Client - the intended use is
// a service wiring this up as a coreconfig.Store's OnUpdate callback, so a
// fresh authguard_url pushed from ProjectConfigurator takes effect on this
// Client's very next call with no restart. A blank baseURL is ignored
// (leaving the previous value in place) rather than leaving the client
// unable to reach AuthServer at all.
func (c *Client) SetBaseURL(baseURL string) {
normalized := normalizeBaseURL(baseURL)
if normalized == "" {
return
}
c.baseURLMu.Lock()
c.baseURL = normalized
c.baseURLMu.Unlock()
}
func (c *Client) getBaseURL() string {
c.baseURLMu.RLock()
defer c.baseURLMu.RUnlock()
return c.baseURL
}
// setProjectKeyHeader attaches ProjectKeyHeader when this Client was built
// with WithProjectKey; a no-op otherwise, so an unconfigured Client behaves
// exactly as it did before project scoping existed.
func (c *Client) setProjectKeyHeader(req *http.Request) {
if c.projectKey != "" {
req.Header.Set(ProjectKeyHeader, c.projectKey)
}
}
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 {
return nil, errors.New("authclient: client has no base URL")
}
baseURL := c.getBaseURL()
if 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, baseURL+"/api/session/validate", nil)
if err != nil {
return nil, fmt.Errorf("authclient: build request: %w", err)
}
req.Header.Set("Authorization", "Bearer "+token)
c.setProjectKeyHeader(req)
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 {
return nil, errors.New("authclient: client has no base URL")
}
baseURL := c.getBaseURL()
if 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, 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)
}
c.setProjectKeyHeader(req)
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
}
+112
View File
@@ -0,0 +1,112 @@
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")
}
}
func TestSetBaseURLRetargetsSubsequentCalls(t *testing.T) {
client := New("http://127.0.0.1:0")
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(map[string]bool{"setup_required": true})
}))
defer server.Close()
client.SetBaseURL(server.URL)
got, err := client.SetupStatus(context.Background())
if err != nil {
t.Fatalf("SetupStatus() after SetBaseURL error = %v", err)
}
if !got {
t.Fatalf("SetupStatus() = %v, want true", got)
}
}
func TestSetBaseURLIgnoresBlank(t *testing.T) {
client := New("https://auth.example.com")
client.SetBaseURL(" ")
if got := client.getBaseURL(); got != "https://auth.example.com" {
t.Fatalf("SetBaseURL(blank) changed baseURL to %q, want unchanged", got)
}
}
+137
View File
@@ -0,0 +1,137 @@
// 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 (Fork/Bitmagnet/backend/internal/auth/service.go,
// Original/GameStream/backend/cmd/gamestreamd/auth.go,
// this same module's own mediaauth/auth.go, formerly
// Core/shared/media-backend/internal/auth/auth.go before that generic
// multi-service binary was split up — 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")
}
})
}
@@ -0,0 +1,900 @@
// Package carriernodeclient is the HTTP client non-CarrierNode services use
// to access CarrierNode's media and project-specific mount APIs. Existing
// media services use it for central file storage; other projects use its
// generic project/type methods after preferring their local volumes.
// CarrierNode's own backend keeps resolving and serving configured roots -
// this client is never used from CarrierNode's own code path.
//
// Promoted unchanged (aside from being detached from a shared *Server type)
// from each service's own internal carriernode_client.go into this shared
// library, so all 6 callers use one copy instead of duplicating it.
package carriernodeclient
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"net/url"
"os"
"strconv"
"strings"
"time"
)
// httpClient has no blanket timeout since it streams large media files;
// callers bound individual calls with a context deadline instead.
var httpClient = &http.Client{}
var forwardRequestHeaders = []string{"Range", "If-Modified-Since", "If-None-Match", "If-Range"}
var forwardResponseHeaders = []string{"Content-Type", "Content-Length", "Content-Range", "Accept-Ranges", "Last-Modified", "ETag", "Content-Disposition"}
// Client calls CarrierNode's HTTP API on behalf of another workspace service.
type Client struct {
// ProjectKey identifies the service making a request to CarrierNode. It is
// optional for backwards compatibility, but when set it lets CarrierNode
// attribute internal transfers to the originating project on its traffic
// dashboard instead of combining every service under one bucket.
ProjectKey string
// InternalServiceSecret is sent as the X-Internal-Auth header on every
// request, so CarrierNode can distinguish trusted service-to-service
// calls from public traffic. Empty means no header is sent.
InternalServiceSecret string
// InternalServiceSecretFunc, when set, resolves the current secret for
// each request. This lets callers use ProjectConfigurator's live
// per-service secret while retaining InternalServiceSecret as the
// bootstrap/fallback value.
InternalServiceSecretFunc func(ctx context.Context) string
// BaseURL resolves CarrierNode's current base URL for a request. It is a
// function rather than a fixed string because CarrierNode's URL is
// configured live through ProjectConfigurator's Projects workspace
// (stored in the shared `settings` table under the "carriernode_url"
// key) - a change there takes effect on this client's very next call
// with no restart needed. Callers typically wire this as a closure over
// their own settings lookup, falling back to a static CARRIERNODE_URL
// env var default when no setting has been saved yet.
//
// Set exactly one of BaseURL or BaseURLs (New/NewMulti do this for you).
// When BaseURLs is set it takes priority.
BaseURL func(ctx context.Context) string
// BaseURLs resolves every configured CarrierNode instance's base URL, in
// priority order, for a request - see NewMulti's doc comment for how the
// multiple candidates are actually used (union for discovery, first-match
// for reads, primary-only for writes).
BaseURLs func(ctx context.Context) []string
}
// New returns a Client backed by a single CarrierNode instance. baseURL is
// called fresh on every request (see Client.BaseURL's doc comment for why).
func New(internalServiceSecret string, baseURL func(ctx context.Context) string) *Client {
return &Client{InternalServiceSecret: internalServiceSecret, BaseURL: baseURL}
}
// NewMulti returns a Client backed by every CarrierNode instance configured
// in ProjectConfigurator (its Projects workspace supports registering more
// than one CarrierNode instance - separate storage backends, HA/failover
// replicas of the same storage, or a mix of both). baseURLs is called fresh
// on every request and should return them in priority order (the first
// non-empty entry is treated as the primary instance).
//
// The candidates are used differently depending on the operation:
// - ListFiles (discovery) queries every instance and merges the results,
// so files living on distinct storage backends are all found.
// - Read operations tied to one file (Proxy, Probe, FetchToScratch,
// ProbeMedia) try each instance in order and use the first one that
// actually has the file, so playback/thumbnails/metadata for a file
// living on a non-primary storage backend still work, and a replica
// standing in for a downed primary is still found.
// - Writes (PushThumbnail, DeleteThumbnail, PushOutput, PushInput,
// PushCopy, UploadDownload, StoreDownload) always target the primary
// instance (the first candidate), matching single-instance behavior.
func NewMulti(internalServiceSecret string, baseURLs func(ctx context.Context) []string) *Client {
return &Client{InternalServiceSecret: internalServiceSecret, BaseURLs: baseURLs}
}
// candidateBaseURLs returns every configured CarrierNode base URL in
// priority order, trimmed and with blanks dropped. A single-instance Client
// (BaseURLs unset) always returns exactly one (possibly empty) entry.
func (c *Client) candidateBaseURLs(ctx context.Context) []string {
if c.BaseURLs != nil {
var cleaned []string
for _, candidate := range c.BaseURLs(ctx) {
if candidate = strings.TrimSpace(candidate); candidate != "" {
cleaned = append(cleaned, candidate)
}
}
return cleaned
}
base := ""
if c.BaseURL != nil {
base = c.BaseURL(ctx)
}
return []string{base}
}
// primaryBaseURL is the instance every write/streaming operation targets -
// see NewMulti's doc comment.
func (c *Client) primaryBaseURL(ctx context.Context) string {
if candidates := c.candidateBaseURLs(ctx); len(candidates) > 0 {
return candidates[0]
}
return ""
}
// Configured reports whether the client currently has at least one non-empty
// CarrierNode URL. It is useful when a caller has another local fallback it
// can try if shared storage has not been configured.
func (c *Client) Configured(ctx context.Context) bool {
for _, baseURL := range c.candidateBaseURLs(ctx) {
if strings.TrimSpace(baseURL) != "" {
return true
}
}
return false
}
func (c *Client) newRequest(ctx context.Context, baseURL, method, path string, body io.Reader) (*http.Request, error) {
request, err := http.NewRequestWithContext(ctx, method, strings.TrimRight(baseURL, "/")+path, body)
if err != nil {
return nil, err
}
secret := c.InternalServiceSecret
if c.InternalServiceSecretFunc != nil {
secret = strings.TrimSpace(c.InternalServiceSecretFunc(ctx))
}
if secret != "" {
request.Header.Set("X-Internal-Auth", secret)
}
if project := strings.TrimSpace(c.ProjectKey); project != "" {
request.Header.Set("X-Project-Key", project)
}
return request, nil
}
// Proxy 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. Every
// configured instance is tried in order (see NewMulti's doc comment); the
// first one that doesn't answer with an error is the one actually streamed,
// so a file living on a non-primary instance still plays and a downed
// primary doesn't block a replica from serving it. The last candidate's
// response (success or error) is always the one forwarded, matching
// single-instance Proxy's behavior of passing even an error status through
// to the caller rather than swallowing it.
func (c *Client) Proxy(w http.ResponseWriter, r *http.Request, carrierNodePath string) {
candidates := c.candidateBaseURLs(r.Context())
if len(candidates) == 0 {
candidates = []string{""}
}
for i, baseURL := range candidates {
last := i == len(candidates)-1
request, err := c.newRequest(r.Context(), baseURL, r.Method, carrierNodePath, nil)
if err != nil {
if last {
writeError(w, http.StatusBadGateway, "media service unavailable")
}
continue
}
for _, header := range forwardRequestHeaders {
if value := r.Header.Get(header); value != "" {
request.Header.Set(header, value)
}
}
response, err := httpClient.Do(request)
if err != nil {
if last {
writeError(w, http.StatusBadGateway, "media service unavailable")
}
continue
}
if response.StatusCode >= 400 && !last {
response.Body.Close()
continue
}
defer response.Body.Close()
for _, header := range forwardResponseHeaders {
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)
}
return
}
}
// MountFileEntry describes one direct child returned from CarrierNode's
// project-specific mount listing endpoint. Path is relative to the requested
// directory and Directory is true for folders.
type MountFileEntry struct {
Name string `json:"name"`
Path string `json:"path"`
Directory bool `json:"directory"`
Size int64 `json:"size"`
Modified time.Time `json:"modifiedAt"`
}
// MountPath builds a project/type-specific CarrierNode API path. It escapes
// each path segment independently so directory separators remain separators.
func MountPath(project, mountType, relative string) string {
if strings.TrimSpace(project) == "" || strings.TrimSpace(mountType) == "" {
return ""
}
parts := []string{"api", "mount", project, mountType}
for _, segment := range strings.Split(strings.Trim(relative, "/\\"), "/") {
if segment == "" || segment == "." {
continue
}
if segment == ".." {
return ""
}
parts = append(parts, segment)
}
for i := range parts {
parts[i] = url.PathEscape(parts[i])
}
return "/" + strings.Join(parts, "/")
}
// ProxyMount streams a file from a project/type mount to the original client,
// preserving HTTP range and conditional headers. It is intended as a fallback
// after the caller's local volume has been checked.
func (c *Client) ProxyMount(w http.ResponseWriter, r *http.Request, project, mountType, relative string) {
if strings.Trim(strings.TrimSpace(relative), "/\\") == "" {
writeError(w, http.StatusNotFound, "file not found")
return
}
path := MountPath(project, mountType, relative)
if path == "" {
writeError(w, http.StatusNotFound, "file not found")
return
}
if !c.Configured(r.Context()) {
writeError(w, http.StatusNotFound, "file not found")
return
}
c.Proxy(w, r, path)
}
// ErrMountNotFound is returned by ListMountFiles when every CarrierNode
// instance that answered said the directory does not exist and none failed
// some other way. It is a definitive "not there", unlike an unreachable
// instance or an error response, where the directory may well exist but could
// not be checked - callers can use errors.Is to tell the two apart.
var ErrMountNotFound = errors.New("carriernode mount directory not found")
// ListMountFiles lists the direct children of a project/type mount directory.
// An empty relative path lists the mount root. The CarrierNode endpoint
// returns both files and directories so callers can build directory browsers.
// When no instance can list the directory, the error wraps ErrMountNotFound
// only if every instance answered 404; any unreachable instance or other
// failure yields a plain error instead, since the directory may live there.
func (c *Client) ListMountFiles(ctx context.Context, project, mountType, relative string) ([]MountFileEntry, error) {
candidates := c.candidateBaseURLs(ctx)
if len(candidates) == 0 {
return nil, fmt.Errorf("carriernode is not configured")
}
path := MountPath(project, mountType, "")
if path == "" {
return nil, fmt.Errorf("invalid mount path")
}
query := url.Values{}
if strings.TrimSpace(relative) != "" {
query.Set("path", relative)
}
if encoded := query.Encode(); encoded != "" {
path += "?" + encoded
}
var entries []MountFileEntry
var lastErr error
loaded := false
missing := false
for _, baseURL := range candidates {
request, err := c.newRequest(ctx, baseURL, http.MethodGet, path, nil)
if err != nil {
lastErr = err
continue
}
response, err := httpClient.Do(request)
if err != nil {
lastErr = err
continue
}
if response.StatusCode == http.StatusNotFound {
response.Body.Close()
missing = true
continue
}
if response.StatusCode != http.StatusOK {
response.Body.Close()
lastErr = fmt.Errorf("carriernode mount listing failed: %s", response.Status)
continue
}
var payload struct {
Files []MountFileEntry `json:"files"`
}
decodeErr := json.NewDecoder(response.Body).Decode(&payload)
response.Body.Close()
if decodeErr != nil {
lastErr = decodeErr
continue
}
loaded = true
entries = append(entries, payload.Files...)
}
if !loaded {
if lastErr != nil {
return nil, lastErr
}
if missing {
return nil, ErrMountNotFound
}
}
unique := make([]MountFileEntry, 0, len(entries))
seen := make(map[string]struct{}, len(entries))
for _, entry := range entries {
key := entry.Path
if key == "" {
key = entry.Name
}
if _, exists := seen[key]; exists {
continue
}
seen[key] = struct{}{}
unique = append(unique, entry)
}
return unique, nil
}
// UploadMountFile streams a local file into a project/type mount on the
// primary CarrierNode. Writes intentionally target only the primary instance.
func (c *Client) UploadMountFile(ctx context.Context, project, mountType, relative, localPath string) error {
if strings.Trim(strings.TrimSpace(relative), "/\\") == "" {
return fmt.Errorf("invalid mount path")
}
path := MountPath(project, mountType, relative)
if path == "" {
return fmt.Errorf("invalid mount path")
}
response, err := c.push(ctx, http.MethodPost, path, localPath)
if err != nil {
return err
}
response.Body.Close()
return nil
}
// FetchMountToScratch downloads a project/type mount file to an ephemeral
// local file for callers that need to inspect or transform it. Callers must
// invoke cleanup once done.
func (c *Client) FetchMountToScratch(ctx context.Context, project, mountType, relative, suffix string) (string, func(), error) {
if strings.Trim(strings.TrimSpace(relative), "/\\") == "" {
return "", nil, fmt.Errorf("invalid mount path")
}
if len(c.candidateBaseURLs(ctx)) == 0 {
return "", nil, fmt.Errorf("carriernode is not configured")
}
path := MountPath(project, mountType, relative)
if path == "" {
return "", nil, fmt.Errorf("invalid mount path")
}
return c.FetchToScratch(ctx, path, suffix)
}
// UploadMountBytes writes a byte slice to a project/type mount on the primary
// CarrierNode. Callers should prefer this for bounded request bodies; large
// files should use UploadMountFile to avoid buffering them in memory.
func (c *Client) UploadMountBytes(ctx context.Context, project, mountType, relative string, data []byte) error {
if strings.Trim(strings.TrimSpace(relative), "/\\") == "" {
return fmt.Errorf("invalid mount path")
}
path := MountPath(project, mountType, relative)
if path == "" {
return fmt.Errorf("invalid mount path")
}
request, err := c.newRequest(ctx, c.primaryBaseURL(ctx), http.MethodPost, path, bytes.NewReader(data))
if err != nil {
return err
}
request.ContentLength = int64(len(data))
response, err := httpClient.Do(request)
if err != nil {
return err
}
defer response.Body.Close()
if response.StatusCode >= 400 {
body, _ := io.ReadAll(io.LimitReader(response.Body, 4096))
return fmt.Errorf("carriernode mount upload failed: %s: %s", response.Status, strings.TrimSpace(string(body)))
}
return nil
}
// DeleteMountFile removes one file from a project/type mount on the primary
// CarrierNode. A missing file is treated as already deleted.
func (c *Client) DeleteMountFile(ctx context.Context, project, mountType, relative string) error {
if strings.Trim(strings.TrimSpace(relative), "/\\") == "" {
return fmt.Errorf("invalid mount path")
}
path := MountPath(project, mountType, relative)
if path == "" {
return fmt.Errorf("invalid mount path")
}
request, err := c.newRequest(ctx, c.primaryBaseURL(ctx), http.MethodDelete, path, nil)
if err != nil {
return err
}
response, err := httpClient.Do(request)
if err != nil {
return err
}
defer response.Body.Close()
if response.StatusCode >= 400 && response.StatusCode != http.StatusNotFound {
return fmt.Errorf("carriernode mount delete failed: %s", response.Status)
}
return nil
}
// ThumbnailMountType is the mount type ProjectConfigurator configures for a project's
// generated thumbnails. Each thumbnail is one "<id>.jpg" file under that mount.
const ThumbnailMountType = "thumbnails"
// thumbnailFile is the file name a thumbnail id is stored under. Ids are UUIDs that
// ContentScanner generates, so anything that could name a path outside the thumbnails
// directory is refused.
func thumbnailFile(id string) (string, error) {
if id == "" || id == "." || id == ".." || strings.ContainsAny(id, `/\`) {
return "", fmt.Errorf("invalid thumbnail id %q", id)
}
return id + ".jpg", nil
}
// thumbnailPaths lists every CarrierNode path a thumbnail may live at, in lookup order: the
// project's thumbnails mount first, then CarrierNode's legacy thumbnail root. Thumbnails
// stored before the mount existed sit in the legacy root, and reads keep finding them there
// until they are regenerated or deleted.
func thumbnailPaths(project, id string) ([]string, error) {
file, err := thumbnailFile(id)
if err != nil {
return nil, err
}
var paths []string
if path := MountPath(project, ThumbnailMountType, file); path != "" {
paths = append(paths, path)
}
return append(paths, "/thumbnails/"+file), nil
}
// StoreThumbnail uploads a generated thumbnail into the project's thumbnails mount on the
// primary CarrierNode and returns its size in bytes. CarrierNode only accepts mount writes
// under its /mount volume, so the configured thumbnails path has to be there.
func (c *Client) StoreThumbnail(ctx context.Context, project, id, localPath string) (int64, error) {
file, err := thumbnailFile(id)
if err != nil {
return 0, err
}
info, err := os.Stat(localPath)
if err != nil {
return 0, err
}
if err := c.UploadMountFile(ctx, project, ThumbnailMountType, file, localPath); err != nil {
return 0, err
}
return info.Size(), nil
}
// DeleteStoredThumbnail removes a thumbnail from the project's thumbnails mount and from the
// legacy root, since one stored before the mount existed may still be there. A thumbnail
// missing from both is already deleted.
func (c *Client) DeleteStoredThumbnail(ctx context.Context, project, id string) error {
file, err := thumbnailFile(id)
if err != nil {
return err
}
mountErr := c.DeleteMountFile(ctx, project, ThumbnailMountType, file)
legacyErr := c.DeleteThumbnail(ctx, id)
return errors.Join(mountErr, legacyErr)
}
// ProxyThumbnail streams a stored thumbnail to the original client, looking in the project's
// thumbnails mount and then the legacy root. It reports false without writing anything when
// neither holds the thumbnail, so the caller can fall back to another source.
func (c *Client) ProxyThumbnail(w http.ResponseWriter, r *http.Request, project, id string) bool {
paths, err := thumbnailPaths(project, id)
if err != nil {
return false
}
for _, path := range paths {
if exists, _, _, probeErr := c.Probe(r.Context(), path); probeErr == nil && exists {
c.Proxy(w, r, path)
return true
}
}
return false
}
// FetchThumbnailToScratch downloads a stored thumbnail into an ephemeral local file, looking
// in the project's thumbnails mount and then the legacy root. Callers must invoke the returned
// cleanup once done.
func (c *Client) FetchThumbnailToScratch(ctx context.Context, project, id, suffix string) (string, func(), error) {
paths, err := thumbnailPaths(project, id)
if err != nil {
return "", nil, err
}
var lastErr error
for _, path := range paths {
scratch, cleanup, fetchErr := c.FetchToScratch(ctx, path, suffix)
if fetchErr == nil {
return scratch, cleanup, nil
}
lastErr = fetchErr
}
return "", nil, lastErr
}
// probeOne runs Probe's HEAD request against a single base URL.
func (c *Client) probeOne(ctx context.Context, baseURL, carrierNodePath string) (exists bool, size int64, modTime time.Time, err error) {
request, err := c.newRequest(ctx, baseURL, http.MethodHead, carrierNodePath, nil)
if err != nil {
return false, 0, time.Time{}, err
}
response, err := httpClient.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
}
// Probe checks whether a CarrierNode-served path exists without fetching its
// bytes. Every configured instance is tried in order; the first one
// reporting the file exists wins. A path missing from every instance is
// reported as exists=false with a nil error, not a failure - only a
// transport/5xx problem on every instance is surfaced as an error.
func (c *Client) Probe(ctx context.Context, carrierNodePath string) (exists bool, size int64, modTime time.Time, err error) {
var lastErr error
for _, baseURL := range c.candidateBaseURLs(ctx) {
found, foundSize, foundModTime, probeErr := c.probeOne(ctx, baseURL, carrierNodePath)
if probeErr != nil {
lastErr = probeErr
continue
}
if found {
return true, foundSize, foundModTime, nil
}
lastErr = nil // a clean 404 from a reachable instance is a real answer, not a failure
}
return false, 0, time.Time{}, lastErr
}
// fetchOne runs FetchToScratch's GET request against a single base URL.
func (c *Client) fetchOne(ctx context.Context, baseURL, carrierNodePath, suffix string) (path string, cleanup func(), err error) {
request, err := c.newRequest(ctx, baseURL, http.MethodGet, carrierNodePath, nil)
if err != nil {
return "", nil, err
}
response, err := httpClient.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
}
// FetchToScratch 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. Every configured instance is tried in
// order; the first one that actually serves the file wins.
func (c *Client) FetchToScratch(ctx context.Context, carrierNodePath, suffix string) (path string, cleanup func(), err error) {
var lastErr error
for _, baseURL := range c.candidateBaseURLs(ctx) {
scratchPath, scratchCleanup, fetchErr := c.fetchOne(ctx, baseURL, carrierNodePath, suffix)
if fetchErr != nil {
lastErr = fetchErr
continue
}
return scratchPath, scratchCleanup, nil
}
return "", nil, lastErr
}
// push streams a local file as the request body without buffering it in
// memory. Always targets the primary instance - see NewMulti's doc comment.
func (c *Client) push(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 := c.newRequest(ctx, c.primaryBaseURL(ctx), method, carrierNodePath, file)
if err != nil {
return nil, err
}
if info, statErr := file.Stat(); statErr == nil {
request.ContentLength = info.Size()
}
response, err := httpClient.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 pushedSize(response *http.Response) int64 {
defer response.Body.Close()
var payload struct {
Size int64 `json:"size"`
}
_ = json.NewDecoder(response.Body).Decode(&payload)
return payload.Size
}
// PushThumbnail uploads a locally-generated thumbnail to CarrierNode.
func (c *Client) PushThumbnail(ctx context.Context, id, localPath string) (int64, error) {
response, err := c.push(ctx, http.MethodPost, "/api/thumbnails/"+url.PathEscape(id), localPath)
if err != nil {
return 0, err
}
return pushedSize(response), nil
}
// DeleteThumbnail removes a thumbnail from CarrierNode. A 404 is treated as
// already-deleted, not an error. Always targets the primary instance.
func (c *Client) DeleteThumbnail(ctx context.Context, id string) error {
request, err := c.newRequest(ctx, c.primaryBaseURL(ctx), http.MethodDelete, "/api/thumbnails/"+url.PathEscape(id), nil)
if err != nil {
return err
}
response, err := httpClient.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
}
// PushOutput uploads a locally-produced output file (e.g. a converted or
// generated media file) to CarrierNode's OutputRoot.
func (c *Client) PushOutput(ctx context.Context, name, localPath string) (int64, error) {
response, err := c.push(ctx, http.MethodPost, "/api/outputs/"+url.PathEscape(name), localPath)
if err != nil {
return 0, err
}
return pushedSize(response), nil
}
// PushInput uploads a local file to CarrierNode's InputRoot.
func (c *Client) PushInput(ctx context.Context, name, localPath string) (int64, error) {
response, err := c.push(ctx, http.MethodPost, "/api/inputs/"+url.PathEscape(name), localPath)
if err != nil {
return 0, err
}
return pushedSize(response), nil
}
// PushCopy uploads a local file to CarrierNode's CopyRoot.
func (c *Client) PushCopy(ctx context.Context, name, localPath string) (int64, error) {
response, err := c.push(ctx, http.MethodPost, "/api/copies/"+url.PathEscape(name), localPath)
if err != nil {
return 0, err
}
return pushedSize(response), nil
}
// UploadDownload streams a locally-produced file (e.g. a completed yt-dlp
// download staged in a scratch dir) into CarrierNode's DownloadsRoot via its
// raw-upload endpoint.
func (c *Client) UploadDownload(ctx context.Context, localPath, filename string) (map[string]any, error) {
response, err := c.push(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
}
// StoreDownload catalogs an already-uploaded file into CarrierNode's
// media/downloaded_media tables via its /api/store endpoint. Always targets
// the primary instance.
func (c *Client) StoreDownload(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 := c.newRequest(ctx, c.primaryBaseURL(ctx), http.MethodPost, "/api/store", bytes.NewReader(body))
if err != nil {
return nil, err
}
request.Header.Set("Content-Type", "application/json")
response, err := httpClient.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
}
// FileEntry describes one file CarrierNode reports via /api/files(/recent).
type FileEntry struct {
Rel string `json:"rel"`
Path string `json:"path"`
Type string `json:"type"`
Size int64 `json:"size"`
Mtime int64 `json:"mtime"`
}
func (c *Client) listFilesOne(ctx context.Context, baseURL, 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 := c.newRequest(ctx, baseURL, http.MethodGet, endpoint, nil)
if err != nil {
return nil, err
}
response, err := httpClient.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
}
// ListFiles lists files under every configured CarrierNode instance's
// MediaRoots via its /api/files (recent=false) or /api/files/recent
// (recent=true) endpoints - the replacement for a local filepath.WalkDir
// over MediaRoots. With more than one instance configured, every reachable
// one is queried and the results are merged (each instance is a distinct
// storage backend, or a failover replica reporting the same files as its
// peers - either way, merging is correct); an unreachable instance is
// skipped rather than failing the whole listing, unless none of them
// answered at all.
func (c *Client) ListFiles(ctx context.Context, relative string, recent bool, limit int) ([]FileEntry, error) {
var files []FileEntry
var lastErr error
reachable := false
for _, baseURL := range c.candidateBaseURLs(ctx) {
found, err := c.listFilesOne(ctx, baseURL, relative, recent, limit)
if err != nil {
lastErr = err
continue
}
reachable = true
files = append(files, found...)
}
if !reachable && lastErr != nil {
return nil, lastErr
}
return files, nil
}
// ProbeResult is the ffprobe-derived metadata CarrierNode's /api/probe
// endpoint reports for a media file.
type ProbeResult struct {
DurationMs int64 `json:"durationMs"`
Width int `json:"width"`
Height int `json:"height"`
IsVR bool `json:"isVr"`
// Pointers keep the distinction between a newer CarrierNode explicitly
// reporting false and an older one that does not return these fields yet.
HasVideo *bool `json:"hasVideo"`
HasAudio *bool `json:"hasAudio"`
}
func (c *Client) probeMediaOne(ctx context.Context, baseURL, relative string) (ProbeResult, error) {
query := url.Values{}
query.Set("path", relative)
request, err := c.newRequest(ctx, baseURL, http.MethodGet, "/api/probe?"+query.Encode(), nil)
if err != nil {
return ProbeResult{}, err
}
response, err := httpClient.Do(request)
if err != nil {
return ProbeResult{}, err
}
defer response.Body.Close()
if response.StatusCode != http.StatusOK {
return ProbeResult{}, fmt.Errorf("carriernode probe failed: %s", response.Status)
}
var result ProbeResult
if err := json.NewDecoder(response.Body).Decode(&result); err != nil {
return ProbeResult{}, err
}
return result, nil
}
// ProbeMedia runs ffprobe on CarrierNode against a MediaRoots-relative path
// and returns just the metadata fields - bytes never leave CarrierNode,
// unlike every other method on Client. Every configured instance is tried in
// order; the first one that actually has the file wins.
func (c *Client) ProbeMedia(ctx context.Context, relative string) (ProbeResult, error) {
var lastErr error
for _, baseURL := range c.candidateBaseURLs(ctx) {
result, err := c.probeMediaOne(ctx, baseURL, relative)
if err != nil {
lastErr = err
continue
}
return result, nil
}
return ProbeResult{}, lastErr
}
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})
}
@@ -0,0 +1,265 @@
package carriernodeclient
import (
"context"
"errors"
"net/http"
"net/http/httptest"
"testing"
)
func TestListFilesMergesAcrossInstances(t *testing.T) {
first := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
_, _ = w.Write([]byte(`{"files":[{"rel":"a.mp4"}]}`))
}))
defer first.Close()
second := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
_, _ = w.Write([]byte(`{"files":[{"rel":"b.mp4"}]}`))
}))
defer second.Close()
client := NewMulti("", func(ctx context.Context) []string { return []string{first.URL, second.URL} })
files, err := client.ListFiles(context.Background(), "", false, 0)
if err != nil {
t.Fatalf("ListFiles error: %v", err)
}
if len(files) != 2 {
t.Fatalf("ListFiles returned %d files, want 2: %+v", len(files), files)
}
}
func TestRequestsCarryProjectAttribution(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if got := r.Header.Get("X-Internal-Auth"); got != "secret" {
t.Fatalf("X-Internal-Auth = %q, want secret", got)
}
if got := r.Header.Get("X-Project-Key"); got != "ContentScanner" {
t.Fatalf("X-Project-Key = %q, want ContentScanner", got)
}
w.Header().Set("Content-Type", "application/json")
_, _ = w.Write([]byte(`{"files":[]}`))
}))
defer server.Close()
client := New("secret", func(ctx context.Context) string { return server.URL })
client.ProjectKey = "ContentScanner"
if _, err := client.ListFiles(context.Background(), "", false, 0); err != nil {
t.Fatalf("ListFiles error: %v", err)
}
}
func TestListFilesSkipsUnreachableInstance(t *testing.T) {
up := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
_, _ = w.Write([]byte(`{"files":[{"rel":"a.mp4"}]}`))
}))
defer up.Close()
down := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusInternalServerError)
}))
down.Close() // closed immediately so requests to it fail outright
client := NewMulti("", func(ctx context.Context) []string { return []string{down.URL, up.URL} })
files, err := client.ListFiles(context.Background(), "", false, 0)
if err != nil {
t.Fatalf("ListFiles error: %v", err)
}
if len(files) != 1 || files[0].Rel != "a.mp4" {
t.Fatalf("ListFiles = %+v, want just the reachable instance's file", files)
}
}
func TestListFilesErrorsWhenNoInstanceReachable(t *testing.T) {
down := httptest.NewServer(nil)
down.Close()
client := NewMulti("", func(ctx context.Context) []string { return []string{down.URL} })
if _, err := client.ListFiles(context.Background(), "", false, 0); err == nil {
t.Fatal("ListFiles error = nil, want an error when every instance is unreachable")
}
}
func TestProbeFallsBackToNextInstance(t *testing.T) {
notFound := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusNotFound)
}))
defer notFound.Close()
found := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Length", "42")
w.WriteHeader(http.StatusOK)
}))
defer found.Close()
client := NewMulti("", func(ctx context.Context) []string { return []string{notFound.URL, found.URL} })
exists, size, _, err := client.Probe(context.Background(), "/media/a.mp4")
if err != nil {
t.Fatalf("Probe error: %v", err)
}
if !exists {
t.Fatal("Probe exists = false, want true (second instance has it)")
}
if size != 42 {
t.Fatalf("Probe size = %d, want 42", size)
}
}
func TestProbeExistsFalseWhenNoInstanceHasFile(t *testing.T) {
notFound := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusNotFound)
}))
defer notFound.Close()
client := NewMulti("", func(ctx context.Context) []string { return []string{notFound.URL, notFound.URL} })
exists, _, _, err := client.Probe(context.Background(), "/media/missing.mp4")
if err != nil {
t.Fatalf("Probe error: %v", err)
}
if exists {
t.Fatal("Probe exists = true, want false")
}
}
func TestProxyPrefersPrimaryInstanceWhenItHasTheFile(t *testing.T) {
var primaryHit, secondaryHit bool
primary := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
primaryHit = true
w.WriteHeader(http.StatusOK)
}))
defer primary.Close()
secondary := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
secondaryHit = true
w.WriteHeader(http.StatusOK)
}))
defer secondary.Close()
client := NewMulti("", func(ctx context.Context) []string { return []string{primary.URL, secondary.URL} })
req := httptest.NewRequest(http.MethodGet, "/thumbnails/x.jpg", nil)
rec := httptest.NewRecorder()
client.Proxy(rec, req, "/thumbnails/x.jpg")
if !primaryHit {
t.Fatal("Proxy did not hit the primary instance")
}
if secondaryHit {
t.Fatal("Proxy hit the secondary instance even though the primary had the file")
}
}
func TestProxyFallsBackToSecondaryInstanceWhenPrimaryMisses(t *testing.T) {
primary := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusNotFound)
}))
defer primary.Close()
secondary := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "video/mp4")
w.WriteHeader(http.StatusOK)
_, _ = w.Write([]byte("video bytes"))
}))
defer secondary.Close()
client := NewMulti("", func(ctx context.Context) []string { return []string{primary.URL, secondary.URL} })
req := httptest.NewRequest(http.MethodGet, "/media/a.mp4", nil)
rec := httptest.NewRecorder()
client.Proxy(rec, req, "/media/a.mp4")
if rec.Code != http.StatusOK {
t.Fatalf("status = %d, want 200 from the secondary instance", rec.Code)
}
if rec.Body.String() != "video bytes" {
t.Fatalf("body = %q, want secondary instance's bytes", rec.Body.String())
}
}
func TestProxyForwardsLastInstanceErrorWhenNoneHaveTheFile(t *testing.T) {
notFound := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusNotFound)
}))
defer notFound.Close()
client := NewMulti("", func(ctx context.Context) []string { return []string{notFound.URL, notFound.URL} })
req := httptest.NewRequest(http.MethodGet, "/media/missing.mp4", nil)
rec := httptest.NewRecorder()
client.Proxy(rec, req, "/media/missing.mp4")
if rec.Code != http.StatusNotFound {
t.Fatalf("status = %d, want 404 forwarded from the last instance", rec.Code)
}
}
func mountListingServer(status int, body string) *httptest.Server {
return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(status)
_, _ = w.Write([]byte(body))
}))
}
func TestListMountFilesReportsNotFoundWhenEveryInstanceMisses(t *testing.T) {
first := mountListingServer(http.StatusNotFound, `{"error":"mount directory not found"}`)
defer first.Close()
second := mountListingServer(http.StatusNotFound, `{"error":"mount directory not found"}`)
defer second.Close()
client := NewMulti("", func(ctx context.Context) []string { return []string{first.URL, second.URL} })
_, err := client.ListMountFiles(context.Background(), "autocode", "repos", "gone")
if !errors.Is(err, ErrMountNotFound) {
t.Fatalf("ListMountFiles error = %v, want ErrMountNotFound", err)
}
}
func TestListMountFilesDoesNotReportNotFoundWhenAnInstanceIsUnreachable(t *testing.T) {
missing := mountListingServer(http.StatusNotFound, `{"error":"mount directory not found"}`)
defer missing.Close()
down := httptest.NewServer(nil)
down.Close() // closed immediately so requests to it fail outright
client := NewMulti("", func(ctx context.Context) []string { return []string{missing.URL, down.URL} })
_, err := client.ListMountFiles(context.Background(), "autocode", "repos", "maybe-on-the-down-instance")
if err == nil {
t.Fatal("ListMountFiles succeeded, want an error")
}
if errors.Is(err, ErrMountNotFound) {
t.Fatalf("ListMountFiles error = %v, must not claim the directory is missing when an instance could not be checked", err)
}
}
func TestListMountFilesDoesNotReportNotFoundOnServerError(t *testing.T) {
broken := mountListingServer(http.StatusInternalServerError, `{"error":"boom"}`)
defer broken.Close()
client := NewMulti("", func(ctx context.Context) []string { return []string{broken.URL} })
_, err := client.ListMountFiles(context.Background(), "autocode", "repos", "")
if err == nil || errors.Is(err, ErrMountNotFound) {
t.Fatalf("ListMountFiles error = %v, want a non-ErrMountNotFound failure", err)
}
}
func TestListMountFilesUsesTheInstanceThatHasTheDirectory(t *testing.T) {
missing := mountListingServer(http.StatusNotFound, `{"error":"mount directory not found"}`)
defer missing.Close()
present := mountListingServer(http.StatusOK, `{"files":[{"name":"repo","path":"repo","directory":true}]}`)
defer present.Close()
client := NewMulti("", func(ctx context.Context) []string { return []string{missing.URL, present.URL} })
files, err := client.ListMountFiles(context.Background(), "autocode", "repos", "")
if err != nil {
t.Fatalf("ListMountFiles error: %v", err)
}
if len(files) != 1 || files[0].Name != "repo" || !files[0].Directory {
t.Fatalf("ListMountFiles = %+v, want the one directory from the instance that has it", files)
}
}
@@ -0,0 +1,183 @@
package carriernodeclient
import (
"context"
"io"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"slices"
"strings"
"sync"
"testing"
)
const testThumbnailID = "3f1c2a9e-6b1d-4e8a-9f0e-2d7c5b4a1e00"
// recordingCarrierNode serves bodies at the paths it is given, accepts every write, and
// records each request so a test can see which CarrierNode paths were touched.
type recordingCarrierNode struct {
mu sync.Mutex
bodies map[string]string
requests []string
}
func (n *recordingCarrierNode) ServeHTTP(w http.ResponseWriter, r *http.Request) {
n.mu.Lock()
n.requests = append(n.requests, r.Method+" "+r.URL.Path)
body, found := n.bodies[r.URL.Path]
n.mu.Unlock()
if r.Method == http.MethodPost || r.Method == http.MethodDelete {
w.WriteHeader(http.StatusOK)
return
}
if !found {
w.WriteHeader(http.StatusNotFound)
return
}
w.Header().Set("Content-Type", "image/jpeg")
w.WriteHeader(http.StatusOK)
if r.Method != http.MethodHead {
_, _ = io.WriteString(w, body)
}
}
func (n *recordingCarrierNode) seen() []string {
n.mu.Lock()
defer n.mu.Unlock()
return append([]string(nil), n.requests...)
}
func newThumbnailTestClient(t *testing.T, bodies map[string]string) (*Client, *recordingCarrierNode) {
t.Helper()
node := &recordingCarrierNode{bodies: bodies}
server := httptest.NewServer(node)
t.Cleanup(server.Close)
return New("", func(context.Context) string { return server.URL }), node
}
func thumbnailRequest() *http.Request {
return httptest.NewRequest(http.MethodGet, "/api/media/thumb", nil)
}
func TestStoreThumbnailWritesToProjectThumbnailsMount(t *testing.T) {
client, node := newThumbnailTestClient(t, nil)
local := filepath.Join(t.TempDir(), "thumb.jpg")
if err := os.WriteFile(local, []byte("jpeg bytes"), 0o600); err != nil {
t.Fatal(err)
}
size, err := client.StoreThumbnail(context.Background(), "ContentScanner", testThumbnailID, local)
if err != nil {
t.Fatalf("StoreThumbnail error: %v", err)
}
if size != int64(len("jpeg bytes")) {
t.Fatalf("StoreThumbnail size = %d, want %d", size, len("jpeg bytes"))
}
want := []string{"POST /api/mount/ContentScanner/thumbnails/" + testThumbnailID + ".jpg"}
if got := node.seen(); !slices.Equal(got, want) {
t.Fatalf("requests = %v, want %v", got, want)
}
}
func TestProxyThumbnailPrefersProjectMount(t *testing.T) {
mount := "/api/mount/MediaViewer/thumbnails/" + testThumbnailID + ".jpg"
legacy := "/thumbnails/" + testThumbnailID + ".jpg"
client, node := newThumbnailTestClient(t, map[string]string{mount: "from mount", legacy: "from legacy"})
rec := httptest.NewRecorder()
if !client.ProxyThumbnail(rec, thumbnailRequest(), "MediaViewer", testThumbnailID) {
t.Fatal("ProxyThumbnail missed although the mount holds the thumbnail")
}
if rec.Body.String() != "from mount" {
t.Fatalf("body = %q, want the mount copy", rec.Body.String())
}
for _, request := range node.seen() {
if !strings.Contains(request, "/api/mount/") {
t.Fatalf("legacy root was consulted although the mount had the thumbnail: %v", node.seen())
}
}
}
func TestProxyThumbnailFallsBackToLegacyRoot(t *testing.T) {
legacy := "/thumbnails/" + testThumbnailID + ".jpg"
client, _ := newThumbnailTestClient(t, map[string]string{legacy: "from legacy"})
rec := httptest.NewRecorder()
if !client.ProxyThumbnail(rec, thumbnailRequest(), "ContentScanner", testThumbnailID) {
t.Fatal("ProxyThumbnail missed although the legacy root holds the thumbnail")
}
if rec.Body.String() != "from legacy" {
t.Fatalf("body = %q, want the legacy copy", rec.Body.String())
}
}
func TestProxyThumbnailReportsMissingWithoutWriting(t *testing.T) {
client, _ := newThumbnailTestClient(t, nil)
rec := httptest.NewRecorder()
if client.ProxyThumbnail(rec, thumbnailRequest(), "ContentScanner", testThumbnailID) {
t.Fatal("ProxyThumbnail reported a hit for a thumbnail neither location holds")
}
if rec.Body.Len() != 0 {
t.Fatalf("ProxyThumbnail wrote %q on a miss; the caller needs a clean fallback", rec.Body.String())
}
}
func TestFetchThumbnailToScratchFallsBackToLegacyRoot(t *testing.T) {
legacy := "/thumbnails/" + testThumbnailID + ".jpg"
client, _ := newThumbnailTestClient(t, map[string]string{legacy: "from legacy"})
path, cleanup, err := client.FetchThumbnailToScratch(context.Background(), "ContentScanner", testThumbnailID, ".jpg")
if err != nil {
t.Fatalf("FetchThumbnailToScratch error: %v", err)
}
defer cleanup()
data, err := os.ReadFile(path)
if err != nil {
t.Fatal(err)
}
if string(data) != "from legacy" {
t.Fatalf("scratch contents = %q, want the legacy copy", data)
}
}
func TestDeleteStoredThumbnailRemovesMountAndLegacyCopies(t *testing.T) {
client, node := newThumbnailTestClient(t, nil)
if err := client.DeleteStoredThumbnail(context.Background(), "ContentScanner", testThumbnailID); err != nil {
t.Fatalf("DeleteStoredThumbnail error: %v", err)
}
want := []string{
"DELETE /api/mount/ContentScanner/thumbnails/" + testThumbnailID + ".jpg",
"DELETE /api/thumbnails/" + testThumbnailID,
}
if got := node.seen(); !slices.Equal(got, want) {
t.Fatalf("requests = %v, want %v", got, want)
}
}
func TestThumbnailIDsCannotEscapeTheThumbnailsDirectory(t *testing.T) {
client, node := newThumbnailTestClient(t, nil)
ctx := context.Background()
for _, id := range []string{"", ".", "..", "../secret", "nested/id"} {
if client.ProxyThumbnail(httptest.NewRecorder(), thumbnailRequest(), "ContentScanner", id) {
t.Errorf("ProxyThumbnail accepted id %q", id)
}
if _, _, err := client.FetchThumbnailToScratch(ctx, "ContentScanner", id, ".jpg"); err == nil {
t.Errorf("FetchThumbnailToScratch accepted id %q", id)
}
if _, err := client.StoreThumbnail(ctx, "ContentScanner", id, filepath.Join(t.TempDir(), "x.jpg")); err == nil {
t.Errorf("StoreThumbnail accepted id %q", id)
}
if err := client.DeleteStoredThumbnail(ctx, "ContentScanner", id); err == nil {
t.Errorf("DeleteStoredThumbnail accepted id %q", id)
}
}
if got := node.seen(); len(got) != 0 {
t.Fatalf("invalid thumbnail ids reached CarrierNode: %v", got)
}
}
+209
View File
@@ -0,0 +1,209 @@
// Package coreconfig lets any service in this workspace receive AuthGuard's, CarrierNode's,
// ComfyUI's, and
// ProjectConfigurator's current base URL(s) pushed from ProjectConfigurator, instead of each service hardcoding them in
// its own env vars. ProjectConfigurator's Projects workspace is the operator-facing source of
// truth for both (its authguard_url/carriernode_url(_N) settings); it pushes a fresh copy to every
// project it has registered whenever either changes, and again on a periodic tick, so a service
// that restarted (and lost its in-memory copy) converges again within a couple of minutes with no
// manual step. See ProjectConfigurator/README.md's "Pushing core service info to other projects"
// section for the wire contract this package implements both ends of (Store/Handler on the
// receiving side; ProjectConfigurator's own settings.go on the sending side).
package coreconfig
import (
"encoding/json"
"net/http"
"strings"
"sync"
)
// Info is AuthGuard's, CarrierNode's, and ProjectConfigurator's current base URL(s), as pushed by
// ProjectConfigurator.
type Info struct {
AuthGuardURL string `json:"authGuardUrl"`
// ComfyUIURL is the configured ComfyUI endpoint for services that use the
// generator. It is optional so services that do not use ComfyUI can ignore it.
ComfyUIURL string `json:"comfyUiUrl,omitempty"`
// ProjectConfiguratorURL is the ProjectConfigurator instance that owns the current workspace
// configuration. Consumers with independent databases can use it to read settings such as the
// configured mount mappings.
ProjectConfiguratorURL string `json:"projectConfiguratorUrl"`
// ContentScannerURL and ContentScannerSecret let services with independent databases import
// the scanner's successfully discovered media without connecting to its PostgreSQL database.
ContentScannerURL string `json:"contentScannerUrl,omitempty"`
ContentScannerSecret string `json:"contentScannerSecret,omitempty"`
// CarrierNodeURL is the primary CarrierNode instance's URL (CarrierNodeURLs[0], if any) - kept
// for the services that only ever talk to one CarrierNode instance via
// carriernodeclient.New(secret, store.CarrierNodeURL).
CarrierNodeURL string `json:"carrierNodeUrl"`
// CarrierNodeURLs is every CarrierNode instance ProjectConfigurator has registered, in
// priority order (the first entry is the same as CarrierNodeURL) - services that want to
// discover files across every configured storage backend / fail over between replicas wire
// this through carriernodeclient.NewMulti(secret, store.CarrierNodeURLs) instead.
CarrierNodeURLs []string `json:"carrierNodeUrls"`
// CarrierNodeSecret is the credential CarrierNode expects in X-Internal-Auth.
// ProjectConfigurator includes it so consumers with independent databases can
// authenticate storage requests without falling back to their own SECRET.
CarrierNodeSecret string `json:"carrierNodeSecret,omitempty"`
}
// Store holds the most recently pushed Info, defaulting to whatever fallback NewStore was given
// (typically this service's own AUTHGUARD_URL/CARRIERNODE_URL env vars) until ProjectConfigurator's
// first push arrives - or forever, if this deployment isn't registered with a ProjectConfigurator
// instance at all, in which case those env vars keep working exactly as before.
type Store struct {
mu sync.RWMutex
info Info
onUpdate func(Info)
}
// NewStore returns a Store seeded with fallback.
func NewStore(fallback Info) *Store {
return &Store{info: normalizeInfo(fallback)}
}
// Get returns the current Info.
func (s *Store) Get() Info {
s.mu.RLock()
defer s.mu.RUnlock()
return s.info
}
// AuthGuardURL is a convenience accessor for Get().AuthGuardURL - the natural value to feed an
// authclient.Client's SetBaseURL, or (via OnUpdate) to keep one continuously up to date.
func (s *Store) AuthGuardURL() string { return s.Get().AuthGuardURL }
// ComfyUIURL is a convenience accessor for Get().ComfyUIURL.
func (s *Store) ComfyUIURL() string { return s.Get().ComfyUIURL }
// ProjectConfiguratorURL is a convenience accessor for Get().ProjectConfiguratorURL.
func (s *Store) ProjectConfiguratorURL() string { return s.Get().ProjectConfiguratorURL }
// ContentScannerURL is a convenience accessor for Get().ContentScannerURL.
func (s *Store) ContentScannerURL() string { return s.Get().ContentScannerURL }
// ContentScannerSecret is the credential the scanner expects on internal sync requests.
func (s *Store) ContentScannerSecret() string { return s.Get().ContentScannerSecret }
// CarrierNodeURL is a convenience accessor for Get().CarrierNodeURL - the natural closure to wire
// as a single-instance carriernodeclient.Client's BaseURL: carriernodeclient.New(secret, func(ctx
// context.Context) string { return store.CarrierNodeURL() }).
func (s *Store) CarrierNodeURL() string { return s.Get().CarrierNodeURL }
// CarrierNodeURLs is a convenience accessor for Get().CarrierNodeURLs - the natural closure to
// wire as a multi-instance carriernodeclient.Client's BaseURLs:
// carriernodeclient.NewMulti(secret, func(ctx context.Context) []string { return
// store.CarrierNodeURLs() }).
func (s *Store) CarrierNodeURLs() []string { return s.Get().CarrierNodeURLs }
// CarrierNodeSecret is a convenience accessor for Get().CarrierNodeSecret.
func (s *Store) CarrierNodeSecret() string { return s.Get().CarrierNodeSecret }
// OnUpdate registers fn to be called (synchronously, so keep it fast) with the new Info after
// every Set - e.g. client.SetBaseURL for an authclient.Client that isn't already reading through
// Store on every call. Only one callback is kept; a second registration replaces the first, which
// is enough for every current caller (one authclient.Client per service).
func (s *Store) OnUpdate(fn func(Info)) {
s.mu.Lock()
s.onUpdate = fn
s.mu.Unlock()
}
// Set replaces the current Info, field by field, ignoring a blank/empty field so a partial push
// (e.g. only carrierNodeUrl(s) changed) never clobbers the other value.
func (s *Store) Set(next Info) {
next = normalizeInfo(next)
s.mu.Lock()
if url := strings.TrimSpace(next.AuthGuardURL); url != "" {
s.info.AuthGuardURL = url
}
if url := strings.TrimRight(strings.TrimSpace(next.ComfyUIURL), "/"); url != "" {
s.info.ComfyUIURL = url
}
if url := strings.TrimRight(strings.TrimSpace(next.ProjectConfiguratorURL), "/"); url != "" {
s.info.ProjectConfiguratorURL = url
}
if url := strings.TrimRight(strings.TrimSpace(next.ContentScannerURL), "/"); url != "" {
s.info.ContentScannerURL = url
}
if secret := strings.TrimSpace(next.ContentScannerSecret); secret != "" {
s.info.ContentScannerSecret = secret
}
if secret := strings.TrimSpace(next.CarrierNodeSecret); secret != "" {
s.info.CarrierNodeSecret = secret
}
if len(next.CarrierNodeURLs) > 0 {
s.info.CarrierNodeURLs = next.CarrierNodeURLs
s.info.CarrierNodeURL = next.CarrierNodeURLs[0]
}
current := s.info
callback := s.onUpdate
s.mu.Unlock()
if callback != nil {
callback(current)
}
}
// normalizeInfo trims/drops blank CarrierNodeURLs entries and fills in CarrierNodeURLs from a
// lone legacy CarrierNodeURL (or vice versa), so every caller - old pushes that only ever set
// CarrierNodeURL, and new ones that set CarrierNodeURLs - sees both fields populated consistently.
func normalizeInfo(info Info) Info {
var cleaned []string
for _, url := range info.CarrierNodeURLs {
if url = strings.TrimSpace(url); url != "" {
cleaned = append(cleaned, url)
}
}
if len(cleaned) == 0 {
if url := strings.TrimSpace(info.CarrierNodeURL); url != "" {
cleaned = []string{url}
}
}
info.CarrierNodeURLs = cleaned
if len(cleaned) > 0 {
info.CarrierNodeURL = cleaned[0]
} else {
info.CarrierNodeURL = ""
}
return info
}
// Handler is the X-Internal-Auth-gated PUT /api/core-services/internal endpoint
// ProjectConfigurator calls to push a fresh Info: mount it at that path (see
// ProjectConfigurator/README.md) behind a secret check for this service's own
// SECRET (the same value ProjectConfigurator and CarrierNode were configured
// with - an empty secret refuses every caller, the same fail-closed default ProjectConfigurator's
// own internal-auth-gated routes use).
func Handler(secret string, store *Store) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
if secret == "" || r.Header.Get("X-Internal-Auth") != secret {
writeError(w, http.StatusUnauthorized, "internal service authentication required")
return
}
var input Info
if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, 4<<10)).Decode(&input); err != nil {
writeError(w, http.StatusBadRequest, "invalid JSON body")
return
}
store.Set(input)
// Do not echo service credentials to the caller. The push is authenticated, but
// these credentials are needed only by the recipient.
info := store.Get()
info.CarrierNodeSecret = ""
info.ContentScannerSecret = ""
writeJSON(w, http.StatusOK, map[string]any{"ok": true, "info": info})
}
}
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})
}
+151
View File
@@ -0,0 +1,151 @@
package coreconfig
import (
"bytes"
"encoding/json"
"net/http"
"net/http/httptest"
"strings"
"testing"
)
func TestStoreSetIgnoresBlankFields(t *testing.T) {
store := NewStore(Info{AuthGuardURL: "http://auth.example.com", CarrierNodeURL: "http://carrier.example.com"})
store.Set(Info{CarrierNodeURL: "http://carrier2.example.com"})
got := store.Get()
if got.AuthGuardURL != "http://auth.example.com" {
t.Fatalf("AuthGuardURL = %q, want unchanged", got.AuthGuardURL)
}
if got.CarrierNodeURL != "http://carrier2.example.com" {
t.Fatalf("CarrierNodeURL = %q, want updated", got.CarrierNodeURL)
}
}
func TestStoreSetComfyUIURL(t *testing.T) {
store := NewStore(Info{})
store.Set(Info{ComfyUIURL: "http://comfyui:8188/"})
if got := store.ComfyUIURL(); got != "http://comfyui:8188" {
t.Fatalf("ComfyUIURL = %q, want trimmed URL", got)
}
}
func TestStoreSetCarrierNodeSecret(t *testing.T) {
store := NewStore(Info{})
store.Set(Info{CarrierNodeSecret: " carrier-secret "})
if got := store.CarrierNodeSecret(); got != "carrier-secret" {
t.Fatalf("CarrierNodeSecret = %q, want trimmed pushed secret", got)
}
store.Set(Info{})
if got := store.CarrierNodeSecret(); got != "carrier-secret" {
t.Fatalf("blank push cleared CarrierNodeSecret to %q", got)
}
}
func TestStoreOnUpdateFiresWithNewInfo(t *testing.T) {
store := NewStore(Info{})
var got Info
calls := 0
store.OnUpdate(func(info Info) {
calls++
got = info
})
store.Set(Info{AuthGuardURL: "http://auth.example.com"})
if calls != 1 {
t.Fatalf("OnUpdate called %d times, want 1", calls)
}
if got.AuthGuardURL != "http://auth.example.com" {
t.Fatalf("OnUpdate saw AuthGuardURL = %q, want http://auth.example.com", got.AuthGuardURL)
}
}
func TestHandlerRejectsMissingOrWrongSecret(t *testing.T) {
store := NewStore(Info{})
handler := Handler("s3cret", store)
body, _ := json.Marshal(Info{AuthGuardURL: "http://auth.example.com"})
cases := []string{"", "wrong"}
for _, header := range cases {
req := httptest.NewRequest(http.MethodPut, "/api/core-services/internal", bytes.NewReader(body))
if header != "" {
req.Header.Set("X-Internal-Auth", header)
}
rec := httptest.NewRecorder()
handler(rec, req)
if rec.Code != http.StatusUnauthorized {
t.Fatalf("status = %d, want 401 for X-Internal-Auth=%q", rec.Code, header)
}
}
if got := store.Get(); got.AuthGuardURL != "" {
t.Fatalf("store was updated despite auth failure: %+v", got)
}
}
func TestStoreSetPopulatesCarrierNodeURLsFromLegacyField(t *testing.T) {
store := NewStore(Info{})
store.Set(Info{CarrierNodeURL: "http://carrier.example.com"})
got := store.Get()
if want := []string{"http://carrier.example.com"}; !equalStrings(got.CarrierNodeURLs, want) {
t.Fatalf("CarrierNodeURLs = %v, want %v", got.CarrierNodeURLs, want)
}
}
func TestStoreSetCarrierNodeURLsAlsoUpdatesPrimary(t *testing.T) {
store := NewStore(Info{})
store.Set(Info{CarrierNodeURLs: []string{"http://primary.example.com", "http://replica.example.com"}})
got := store.Get()
if got.CarrierNodeURL != "http://primary.example.com" {
t.Fatalf("CarrierNodeURL = %q, want first CarrierNodeURLs entry", got.CarrierNodeURL)
}
want := []string{"http://primary.example.com", "http://replica.example.com"}
if !equalStrings(got.CarrierNodeURLs, want) {
t.Fatalf("CarrierNodeURLs = %v, want %v", got.CarrierNodeURLs, want)
}
}
func equalStrings(got, want []string) bool {
if len(got) != len(want) {
return false
}
for i := range got {
if got[i] != want[i] {
return false
}
}
return true
}
func TestHandlerAppliesPushedInfo(t *testing.T) {
store := NewStore(Info{})
handler := Handler("s3cret", store)
body, _ := json.Marshal(Info{
AuthGuardURL: "http://auth.example.com", CarrierNodeURL: "http://carrier.example.com", CarrierNodeSecret: "carrier-secret",
ContentScannerURL: "http://scanner.example.com/", ContentScannerSecret: "scanner-secret",
})
req := httptest.NewRequest(http.MethodPut, "/api/core-services/internal", bytes.NewReader(body))
req.Header.Set("X-Internal-Auth", "s3cret")
rec := httptest.NewRecorder()
handler(rec, req)
if rec.Code != http.StatusOK {
t.Fatalf("status = %d, want 200: %s", rec.Code, rec.Body.String())
}
got := store.Get()
if got.AuthGuardURL != "http://auth.example.com" || got.CarrierNodeURL != "http://carrier.example.com" || got.CarrierNodeSecret != "carrier-secret" || got.ContentScannerURL != "http://scanner.example.com" || got.ContentScannerSecret != "scanner-secret" {
t.Fatalf("store = %+v, want pushed values applied", got)
}
if strings.Contains(rec.Body.String(), "scanner-secret") {
t.Fatal("response echoed the ContentScanner secret")
}
}
+2
View File
@@ -3,6 +3,8 @@ module repos.gfranz.ch/Gabriel20xx/shared/backend
go 1.25.7
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
github.com/pressly/goose/v3 v3.27.3
golang.org/x/crypto v0.54.0
+4
View File
@@ -1,8 +1,12 @@
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/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY=
github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto=
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/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsIM=
+438
View File
@@ -0,0 +1,438 @@
// Package logshipper is the client-side adapter for OmniLogger
// (Web/OmniLogger), 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 OmniLogger/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
// OmniLogger. Nothing is lost if OmniLogger 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 OmniLogger'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 OmniLogger's base URL, e.g. "http://omnilogger:8090".
// Required.
BaseURL string
// IngestToken is the shared INGEST_TOKEN bearer secret OmniLogger
// requires (see OmniLogger/README.md). Required.
IngestToken string
// Service is this process's service name as reported to OmniLogger,
// 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 OmniLogger differently
// than normal — see Debug/InfoCtx doc comments).
LogAll bool
// FlushInterval is how often buffered entries are sent to OmniLogger.
// 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 OmniLogger.
// Defaults to a client with a 5s timeout.
HTTPClient *http.Client
}
// wireEntry mirrors OmniLogger's POST /api/logs request shape
// (OmniLogger/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 OmniLogger 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 OmniLogger 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: OmniLogger 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 OmniLogger 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 OmniLogger 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...) }
File diff suppressed because it is too large. Load diff
+187
View File
@@ -0,0 +1,187 @@
package mediacore
import "context"
// Migrate creates every table (and its indexes) mediacore's shared routes
// read or write, using CREATE TABLE/INDEX IF NOT EXISTS so whichever
// media-family service starts first against a fresh database creates them
// and every other service's own startup is a no-op. Statements are copied
// verbatim from the pre-split monolith's
// internal/database/migrations/001_initial.sql, limited to the tables
// mediacore itself owns (media, media_stats, media_view_sessions,
// media_tags, media_tag_votes, settings, playlists, playlist_items,
// workflow_jobs, thumbnails) plus `users`, which several of those
// reference via foreign key even though identity itself now lives in
// AuthGuard (see mediaauth's package doc comment) - the column is kept for
// FK integrity, not queried by mediacore.
//
// Each per-service backend additionally runs its own migration for tables
// it exclusively owns (e.g. ContentScanner's media_worker_jobs/
// media_analysis_tasks, CraftStudio's generated_media/downloaded_media,
// ProjectConfigurator's mount_paths) - those are NOT run here.
func (c *Core) Migrate(ctx context.Context) error {
for _, statement := range migrationStatements {
if _, err := c.db.Exec(ctx, statement); err != nil {
return err
}
}
return nil
}
var migrationStatements = []string{
`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()
)`,
`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 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,
funscript_action_count INT,
funscript_avg_speed REAL,
funscript_max_speed REAL,
speed REAL,
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
modified_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
)`,
`ALTER TABLE media ADD COLUMN IF NOT EXISTS funscript_action_count INT`,
`ALTER TABLE media ADD COLUMN IF NOT EXISTS funscript_avg_speed REAL`,
`ALTER TABLE media ADD COLUMN IF NOT EXISTS funscript_max_speed REAL`,
`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 INDEX IF NOT EXISTS media_active_type_idx ON media (active, media_type)`,
`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()
)`,
`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_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)`,
// 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`,
`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 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 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()
)`,
}
+101
View File
@@ -6,6 +6,7 @@ import (
"context"
"errors"
"fmt"
"log"
"strings"
"time"
@@ -28,6 +29,87 @@ type Config struct {
ConnectTimeout time.Duration
}
// StartupRetryOptions controls retries while a service is waiting for
// PostgreSQL to become reachable during startup.
type StartupRetryOptions struct {
Interval time.Duration
MaxAttempts int64
}
const (
defaultStartupRetryInterval = 5 * time.Second
defaultStartupRetryAttempts = 0 // 0 = retry indefinitely
minimumStartupRetryInterval = 250 * time.Millisecond
)
// StartupRetryOptionsFromEnv loads the common startup retry policy. The
// database has to be reachable before settings stored in it can be read, so
// these options intentionally come from the environment.
func StartupRetryOptionsFromEnv() StartupRetryOptions {
intervalMs := config.Int("DB_INIT_RETRY_INTERVAL_MS", int(defaultStartupRetryInterval/time.Millisecond))
if intervalMs < int(minimumStartupRetryInterval/time.Millisecond) {
intervalMs = int(minimumStartupRetryInterval / time.Millisecond)
}
maxAttempts := int64(config.Int("DB_INIT_RETRY_MAX_ATTEMPTS", defaultStartupRetryAttempts))
if maxAttempts < 0 {
maxAttempts = defaultStartupRetryAttempts
}
return StartupRetryOptions{
Interval: time.Duration(intervalMs) * time.Millisecond,
MaxAttempts: maxAttempts,
}
}
// RetryStartup reruns fn until it succeeds, the configured attempt limit is
// reached, or ctx is canceled.
func RetryStartup(ctx context.Context, fn func() error) error {
return RetryStartupWithOptions(ctx, StartupRetryOptionsFromEnv(), fn)
}
// RetryStartupWithOptions is the configurable form of RetryStartup, useful
// when a caller has already loaded the startup options.
func RetryStartupWithOptions(ctx context.Context, options StartupRetryOptions, fn func() error) error {
if fn == nil {
return errors.New("startup retry callback is nil")
}
if options.Interval < minimumStartupRetryInterval {
options.Interval = minimumStartupRetryInterval
}
if options.MaxAttempts < 0 {
options.MaxAttempts = defaultStartupRetryAttempts
}
var lastErr error
for attempt := int64(1); ; attempt++ {
if err := ctx.Err(); err != nil {
return err
}
if err := fn(); err == nil {
return nil
} else {
lastErr = err
}
if options.MaxAttempts > 0 && attempt >= options.MaxAttempts {
return lastErr
}
log.Printf("[postgres] startup attempt %d failed: %v; retrying in %s", attempt, lastErr, options.Interval)
timer := time.NewTimer(options.Interval)
select {
case <-ctx.Done():
if !timer.Stop() {
<-timer.C
}
return ctx.Err()
case <-timer.C:
}
}
}
// DefaultConfig returns sensible defaults for a small self-hosted service.
func DefaultConfig(url string) Config {
return Config{
@@ -111,6 +193,25 @@ func Open(ctx context.Context, cfg Config) (*pgxpool.Pool, error) {
return pool, nil
}
// OpenWithRetry opens and verifies a PostgreSQL pool using the common startup
// retry policy.
func OpenWithRetry(ctx context.Context, cfg Config) (*pgxpool.Pool, error) {
var pool *pgxpool.Pool
err := RetryStartup(ctx, func() error {
if pool != nil {
pool.Close()
pool = nil
}
var err error
pool, err = Open(ctx, cfg)
return err
})
if err != nil {
return nil, err
}
return pool, nil
}
// WithTx runs fn in a transaction and rolls back on all error paths.
func WithTx(ctx context.Context, pool *pgxpool.Pool, fn func(pgx.Tx) error) error {
if pool == nil {
+581
View File
@@ -0,0 +1,581 @@
// Package syncsocket is the media-backend family's cross-device playback-sync
// websocket hub: multiple clients viewing the same media session (identified
// by a caller-chosen sessionId) see each other's play/pause/seek/remote-control
// state live. Promoted unchanged from each service's own internal sync.go into
// this shared library so the 6 media-family backends that mount it (every one
// except KioskDisplay) use one copy instead of duplicating it.
//
// A service wires this up as:
//
// hub := syncsocket.NewHub()
// router.HandleFunc("/ws", func(w http.ResponseWriter, r *http.Request) {
// hub.ServeWebSocket(w, r, cfg.AllowedOrigin)
// })
//
// and mediacore's shared GET/PUT /sync HTTP routes call hub.HTTPState/
// SetHTTPState/Broadcast to read and mutate the same session state the
// websocket peers see.
package syncsocket
import (
"context"
"encoding/json"
"math"
"net/http"
"net/url"
"strings"
"sync"
"time"
"github.com/coder/websocket"
)
const (
maxSyncIdentifier = 128
maxSyncSessions = 1000
)
type peer struct {
conn *websocket.Conn
writeMu sync.Mutex
clientID string
sessionID string
userAgent string
ipAddress string
remoteControlEnabled bool
uiView string
uiMediaID any
uiMediaIDSet bool
}
// Hub tracks every connected sync websocket peer and the last-known playback
// state per session, broadcasting updates to every peer sharing a session.
type Hub struct {
mu sync.Mutex
peers map[*peer]struct{}
states map[string]map[string]any
playAt map[string]string
playAtLocalMs map[string]int64
capturedAtMs map[string]int64
controlOwners map[string]string
}
// NewHub returns an empty Hub ready to accept websocket connections and
// serve/mutate HTTP sync state.
func NewHub() *Hub {
return &Hub{
peers: make(map[*peer]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 *Hub) add(p *peer) {
h.mu.Lock()
h.peers[p] = struct{}{}
h.mu.Unlock()
}
func (h *Hub) remove(p *peer) string {
h.mu.Lock()
defer h.mu.Unlock()
delete(h.peers, p)
if p.clientID != "" && !h.hasClientLocked(p.clientID) {
delete(h.controlOwners, p.clientID)
for targetID, ownerID := range h.controlOwners {
if ownerID == p.clientID {
delete(h.controlOwners, targetID)
}
}
}
return p.sessionID
}
func (h *Hub) hasClientLocked(clientID string) bool {
for p := range h.peers {
if p.clientID == clientID {
return true
}
}
return false
}
func (h *Hub) updatePeer(p *peer, clientID, sessionID string) {
h.mu.Lock()
if clientID != "" {
p.clientID = clientID
}
if sessionID != "" {
p.sessionID = sessionID
}
h.mu.Unlock()
}
func (h *Hub) clientStatus(p *peer, sessionID, view string, mediaID any, mediaIDSet bool, remoteSet, remote bool) {
h.mu.Lock()
defer h.mu.Unlock()
if sessionID != "" {
p.sessionID = sessionID
}
if view != "" {
p.uiView = view
}
if mediaIDSet {
p.uiMediaID = mediaID
p.uiMediaIDSet = true
}
if remoteSet {
p.remoteControlEnabled = remote
if !remote && h.controlOwners[p.clientID] != "" {
delete(h.controlOwners, p.clientID)
}
}
}
func (h *Hub) clientsLocked(sessionID string) []map[string]any {
byID := make(map[string]map[string]any)
for p := range h.peers {
if p.sessionID != sessionID || p.clientID == "" {
continue
}
entry, exists := byID[p.clientID]
if !exists {
entry = map[string]any{
"clientId": p.clientID,
"userAgent": p.userAgent,
"ipAddress": p.ipAddress,
"remoteControlEnabled": p.remoteControlEnabled,
"controlOwnerClientId": nil,
}
byID[p.clientID] = entry
} else if p.remoteControlEnabled {
entry["remoteControlEnabled"] = true
}
if p.uiView != "" {
entry["uiView"] = p.uiView
}
if p.uiMediaIDSet {
entry["uiMediaId"] = p.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 *Hub) 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)
}
// HTTPState returns the current playback state for a session, as seen by the
// GET /sync HTTP endpoint (mounted by mediacore).
func (h *Hub) HTTPState(sessionID string) map[string]any {
h.mu.Lock()
defer h.mu.Unlock()
return h.timingLocked(sessionID, h.stateLocked(sessionID))
}
// SetHTTPState overwrites a session's playback state, as driven by the
// PUT /sync HTTP endpoint (mounted by mediacore) - callers should follow this
// with Broadcast to notify connected websocket peers.
func (h *Hub) 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 *Hub) 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
}
// Broadcast pushes the current state of sessionID to every connected
// websocket peer sharing that session.
func (h *Hub) Broadcast(sessionID string) {
h.mu.Lock()
state := h.timingLocked(sessionID, h.stateLocked(sessionID))
clients := h.clientsLocked(sessionID)
peers := make([]*peer, 0)
for p := range h.peers {
if p.sessionID == sessionID {
peers = append(peers, p)
}
}
h.mu.Unlock()
message := map[string]any{"type": "sync:state", "state": state, "clients": clients}
for _, p := range peers {
if err := p.send(message); err != nil {
_ = p.conn.Close(websocket.StatusGoingAway, "write failed")
}
}
}
func (p *peer) send(message any) error {
data, err := json.Marshal(message)
if err != nil {
return err
}
p.writeMu.Lock()
defer p.writeMu.Unlock()
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
defer cancel()
return p.conn.Write(ctx, websocket.MessageText, data)
}
func websocketAcceptOptions(r *http.Request, allowedOrigin string) *websocket.AcceptOptions {
options := &websocket.AcceptOptions{}
if 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(allowedOrigin)
scheme := "http"
if r.TLS != nil {
scheme = "https"
}
addOrigin(scheme + "://" + r.Host)
options.OriginPatterns = patterns
return options
}
// ServeWebSocket upgrades the request to a websocket connection and services
// it until the client disconnects. allowedOrigin should be the service's own
// CORS_ORIGIN config value (or "*" to accept any origin).
func (h *Hub) ServeWebSocket(w http.ResponseWriter, r *http.Request, allowedOrigin string) {
conn, err := websocket.Accept(w, r, websocketAcceptOptions(r, allowedOrigin))
if err != nil {
return
}
p := &peer{
conn: conn,
userAgent: firstNonEmpty(r.Header.Get("User-Agent"), "Unknown"),
ipAddress: firstNonEmpty(strings.Split(r.Header.Get("X-Forwarded-For"), ",")[0], r.RemoteAddr, "Unknown"),
}
h.add(p)
defer func() {
sessionID := h.remove(p)
_ = conn.Close(websocket.StatusNormalClosure, "")
if sessionID != "" {
h.Broadcast(sessionID)
}
}()
_ = p.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
}
h.handleMessage(p, message)
}
}
func (h *Hub) handleMessage(p *peer, message map[string]any) {
typ, _ := message["type"].(string)
switch typ {
case "ws:ping":
_ = p.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
}
h.updatePeer(p, clientID, sessionID)
h.Broadcast(sessionID)
case "client:status":
clientID := boundedSyncString(firstNonEmpty(syncString(message, "clientId"), p.clientID))
sessionID := boundedSyncString(firstNonEmpty(syncString(message, "sessionId"), p.sessionID, "default"))
if clientID == "" {
return
}
h.updatePeer(p, clientID, sessionID)
mediaID, mediaIDSet := syncMediaID(message)
remote, remoteSet := message["remoteControlEnabled"].(bool)
h.clientStatus(p, sessionID, boundedSyncString(syncString(message, "uiView")), mediaID, mediaIDSet, remoteSet, remote)
h.Broadcast(sessionID)
case "control:claim", "control:release":
h.handleControlMessage(p, typ, message)
case "sync:update":
h.handleSyncUpdate(p, message)
}
}
func (h *Hub) handleControlMessage(p *peer, typ string, message map[string]any) {
requesterID := boundedSyncString(firstNonEmpty(syncString(message, "clientId"), p.clientID))
sessionID := boundedSyncString(firstNonEmpty(syncString(message, "sessionId"), p.sessionID, "default"))
targetID := boundedSyncString(syncString(message, "targetClientId"))
if requesterID == "" || targetID == "" || requesterID != p.clientID {
return
}
h.mu.Lock()
owner := h.controlOwners[targetID]
ok := false
reason := ""
if typ == "control:claim" {
enabled := false
for candidate := range h.peers {
if candidate.clientID == targetID && candidate.remoteControlEnabled {
enabled = true
break
}
}
switch {
case !enabled:
reason = "disabled"
case owner != "" && owner != requesterID:
reason = "busy"
default:
h.controlOwners[targetID] = requesterID
owner = requesterID
ok = true
}
} else if owner != "" && owner != requesterID {
reason = "not-owner"
} else {
delete(h.controlOwners, targetID)
owner = ""
ok = true
}
h.mu.Unlock()
_ = p.send(map[string]any{
"type": "control:ack",
"ok": ok,
"action": strings.TrimPrefix(typ, "control:"),
"targetClientId": targetID,
"ownerClientId": nullableString(owner),
"reason": nullableString(reason),
})
h.Broadcast(sessionID)
}
func (h *Hub) handleSyncUpdate(p *peer, message map[string]any) {
clientID := boundedSyncString(firstNonEmpty(syncString(message, "clientId"), p.clientID))
sessionID := boundedSyncString(firstNonEmpty(syncString(message, "sessionId"), p.sessionID, "default"))
if clientID == "" || clientID != p.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"]
h.mu.Lock()
if paused || !hasPlayAt || strings.TrimSpace(syncStringValue(playAtRaw)) == "" {
delete(h.playAt, sessionID)
delete(h.playAtLocalMs, sessionID)
} else if parsed, err := time.Parse(time.RFC3339Nano, strings.TrimSpace(syncStringValue(playAtRaw))); err == nil {
h.playAt[sessionID] = parsed.UTC().Format(time.RFC3339Nano)
if local := syncInt(message, "playAtLocalMs", 0); local > 0 {
h.playAtLocalMs[sessionID] = local
} else {
delete(h.playAtLocalMs, sessionID)
}
}
if captured := syncInt(message, "capturedAtLocalMs", 0); captured > 0 {
h.capturedAtMs[sessionID] = captured
}
if toClientID == "" {
h.states[sessionID] = cloneMap(state)
if len(h.states) > maxSyncSessions {
for key := range h.states {
delete(h.states, key)
break
}
}
}
state = h.timingLocked(sessionID, state)
clients := h.clientsLocked(sessionID)
peers := make([]*peer, 0)
if toClientID != "" {
for candidate := range h.peers {
if candidate.sessionID == sessionID && candidate.clientID == toClientID {
peers = append(peers, candidate)
}
}
}
h.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
}
h.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
}
func firstNonEmpty(values ...string) string {
for _, value := range values {
if strings.TrimSpace(value) != "" {
return value
}
}
return ""
}
+16 -26
View File
@@ -1,12 +1,12 @@
{
"name": "@gabriel20xx/shared-code",
"version": "0.1.0",
"version": "0.1.1",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "@gabriel20xx/shared-code",
"version": "0.1.0",
"version": "0.1.1",
"license": "MIT",
"workspaces": [
"packages/*"
@@ -776,7 +776,6 @@
"version": "0.3.13",
"resolved": "https://registry.npmjs.org/@jridgewell/gen-mapping/-/gen-mapping-0.3.13.tgz",
"integrity": "sha512-2kkt/7niJ6MgEPxF0bYdQ6etZaA+fQvDcLKckhy1yIQOzaoKjBBjSj63/aLVjYE3qhRt5dvM+uUyfCg6UKCBbA==",
"dev": true,
"license": "MIT",
"dependencies": {
"@jridgewell/sourcemap-codec": "^1.5.0",
@@ -787,7 +786,6 @@
"version": "2.3.5",
"resolved": "https://registry.npmjs.org/@jridgewell/remapping/-/remapping-2.3.5.tgz",
"integrity": "sha512-LI9u/+laYG4Ds1TDKSJW2YPrIlcVYOwi2fUC6xB43lueCjgxV4lffOCZCtYFiH6TNOX+tQKXx97T4IKHbhyHEQ==",
"dev": true,
"license": "MIT",
"dependencies": {
"@jridgewell/gen-mapping": "^0.3.5",
@@ -798,7 +796,6 @@
"version": "3.1.2",
"resolved": "https://registry.npmjs.org/@jridgewell/resolve-uri/-/resolve-uri-3.1.2.tgz",
"integrity": "sha512-bRISgCIjP20/tbWSPWMEi54QVPRZExkuD9lJL+UIxUKtwVJA8wW1Trb1jMs1RFXo1CBTNZ/5hpC9QvmKWdopKw==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">=6.0.0"
@@ -808,20 +805,27 @@
"version": "1.5.5",
"resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.5.5.tgz",
"integrity": "sha512-cYQ9310grqxueWbl+WuIUIaiUaDcj7WOq5fVhEljNVgRfOUhY9fy2zTvfoqWsnebh8Sl70VScFbICvJnLKB0Og==",
"dev": true,
"license": "MIT"
},
"node_modules/@jridgewell/trace-mapping": {
"version": "0.3.31",
"resolved": "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.31.tgz",
"integrity": "sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw==",
"dev": true,
"license": "MIT",
"dependencies": {
"@jridgewell/resolve-uri": "^3.1.0",
"@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": {
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/@manypkg/find-root/-/find-root-1.1.0.tgz",
@@ -1371,7 +1375,6 @@
"version": "1.0.11",
"resolved": "https://registry.npmjs.org/@sveltejs/acorn-typescript/-/acorn-typescript-1.0.11.tgz",
"integrity": "sha512-LFuZUkjJ9iF7JZye/aG5XM0SFcQ5VyL0oVX4WJ9dc0Va3R3s0OauX1BESVCb+YN/ol8TAfqGDDAQsTG627Y5kw==",
"dev": true,
"license": "MIT",
"peerDependencies": {
"acorn": "^8.9.0"
@@ -1453,21 +1456,18 @@
"version": "1.0.9",
"resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.9.tgz",
"integrity": "sha512-GhdPgy1el4/ImP05X05Uw4cw2/M93BCUmnEvWZNStlCzEKME4Fkk+YpoA5OiHNQmoS7Cafb8Xa3Pya8m1Qrzeg==",
"dev": true,
"license": "MIT"
},
"node_modules/@types/trusted-types": {
"version": "2.0.7",
"resolved": "https://registry.npmjs.org/@types/trusted-types/-/trusted-types-2.0.7.tgz",
"integrity": "sha512-ScaPdn1dQczgbl0QFTeTOmVHFULt394XJgOQNoyVhZ6r2vLnMLJfBPd53SB52T/3G36VI1/g2MZaX0cwDuXsfw==",
"dev": true,
"license": "MIT"
},
"node_modules/acorn": {
"version": "8.18.0",
"resolved": "https://registry.npmjs.org/acorn/-/acorn-8.18.0.tgz",
"integrity": "sha512-lGq+9yr1/GuAWaVYIHRjvvySG5/4VfKIvC8EWxStPdcDh/Ka7FG3twP6v4d5BkravUilhIAsG4Qj83t02LWUPQ==",
"dev": true,
"license": "MIT",
"bin": {
"acorn": "bin/acorn"
@@ -1507,7 +1507,6 @@
"version": "5.3.1",
"resolved": "https://registry.npmjs.org/aria-query/-/aria-query-5.3.1.tgz",
"integrity": "sha512-Z/ZeOgVl7bcSYZ/u/rh0fOpvEpq//LZmdbkXyc7syVzjPAhfOa9ebsdTSjEBDU4vs5nC98Kfduj1uFo0qyET3g==",
"dev": true,
"license": "Apache-2.0",
"engines": {
"node": ">= 0.4"
@@ -1527,7 +1526,6 @@
"version": "4.1.0",
"resolved": "https://registry.npmjs.org/axobject-query/-/axobject-query-4.1.0.tgz",
"integrity": "sha512-qIj0G9wZbMGNLjLmg1PT6v2mE9AH2zlnADJD/2tC6E00hgmhUOfEB6greHPAfLRSufHqROIUTkw6E+M3lH0PTQ==",
"dev": true,
"license": "Apache-2.0",
"engines": {
"node": ">= 0.4"
@@ -1586,7 +1584,6 @@
"version": "2.1.1",
"resolved": "https://registry.npmjs.org/clsx/-/clsx-2.1.1.tgz",
"integrity": "sha512-eYm0QWBtUrBWZWG0d386OGAw16Z995PiOVo2B7bjWSbHedGl5e0ZWaq65kOGgUSNesEIDkB9ISbTg/JK9dhCZA==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">=6"
@@ -1638,7 +1635,6 @@
"version": "5.9.0",
"resolved": "https://registry.npmjs.org/devalue/-/devalue-5.9.0.tgz",
"integrity": "sha512-RWrqdArjvPbsATEhOPUo6Wndc/iWnkWKlhIrdlF3zMMYo/c3CVtoaVAyLtWxz5h8nSlkHzxnzV2uLydPXmtF+A==",
"dev": true,
"license": "MIT"
},
"node_modules/dir-glob": {
@@ -1715,7 +1711,6 @@
"version": "1.2.2",
"resolved": "https://registry.npmjs.org/esm-env/-/esm-env-1.2.2.tgz",
"integrity": "sha512-Epxrv+Nr/CaL4ZcFGPJIYLWFom+YeV1DqMLHJoEd9SYRxNbaFruBwfEX/kkHUJf55j2+TUbmDcmuilbP1TmXHA==",
"dev": true,
"license": "MIT"
},
"node_modules/esprima": {
@@ -1736,7 +1731,6 @@
"version": "2.3.0",
"resolved": "https://registry.npmjs.org/esrap/-/esrap-2.3.0.tgz",
"integrity": "sha512-GQ/7RN8uOtEfNpzZzBMTzW9JBcX42oaSVtPzdF+6cEL8pqIL094iUpr9jzYGn4O4P/1S60dJ6izyT8F4LYARng==",
"dev": true,
"license": "MIT",
"dependencies": {
"@jridgewell/sourcemap-codec": "^1.4.15"
@@ -1975,7 +1969,6 @@
"version": "3.0.3",
"resolved": "https://registry.npmjs.org/is-reference/-/is-reference-3.0.3.tgz",
"integrity": "sha512-ixkJoqQvAP88E6wLydLGGqCJsrFUnqoH6HnaczB8XmDH1oaWU+xxdptvikTgaEhtZ53Ky6YXiBuUI2WXLMCwjw==",
"dev": true,
"license": "MIT",
"dependencies": {
"@types/estree": "^1.0.6"
@@ -2058,7 +2051,6 @@
"version": "3.0.0",
"resolved": "https://registry.npmjs.org/locate-character/-/locate-character-3.0.0.tgz",
"integrity": "sha512-SW13ws7BjaeJ6p7Q6CO2nchbYEc3X3J6WrmTTDto7yMPqVSZTUyY5Tjbid+Ab8gLnATtygYtiDIJGQRRn2ZOiA==",
"dev": true,
"license": "MIT"
},
"node_modules/locate-path": {
@@ -2085,7 +2077,6 @@
"version": "0.30.21",
"resolved": "https://registry.npmjs.org/magic-string/-/magic-string-0.30.21.tgz",
"integrity": "sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ==",
"dev": true,
"license": "MIT",
"dependencies": {
"@jridgewell/sourcemap-codec": "^1.5.5"
@@ -2821,7 +2812,6 @@
"version": "5.56.8",
"resolved": "https://registry.npmjs.org/svelte/-/svelte-5.56.8.tgz",
"integrity": "sha512-PY8LOw7xP6c8IOiVqdo0sbbZVYhXRSfklOQLAUyGBKqjTX0wx/z4l/9J+PmBpmlLnxzEb1NqltxQ5/wZme/Cmg==",
"dev": true,
"license": "MIT",
"dependencies": {
"@jridgewell/remapping": "^2.3.4",
@@ -3108,17 +3098,16 @@
"version": "1.1.4",
"resolved": "https://registry.npmjs.org/zimmerframe/-/zimmerframe-1.1.4.tgz",
"integrity": "sha512-B58NGBEoc8Y9MWWCQGl/gq9xBCe4IiKM0a2x7GZdQKOW5Exr8S1W24J6OgM1njK8xCRGvAJIL/MxXHf6SkmQKQ==",
"dev": true,
"license": "MIT"
},
"packages/design-tokens": {
"name": "@gabriel20xx/design-tokens",
"version": "0.1.0",
"version": "0.1.1",
"license": "MIT"
},
"packages/node-backend": {
"name": "@gabriel20xx/node-backend",
"version": "0.1.0",
"version": "0.1.1",
"license": "MIT",
"dependencies": {
"pg": "^8.17.2"
@@ -3129,10 +3118,11 @@
},
"packages/web-ui": {
"name": "@gabriel20xx/web-ui",
"version": "0.1.0",
"version": "0.1.1",
"license": "MIT",
"dependencies": {
"@gabriel20xx/design-tokens": "0.1.0"
"@gabriel20xx/design-tokens": "0.1.1",
"@lucide/svelte": "1.28.0"
},
"devDependencies": {
"@sveltejs/package": "^2.5.0",
+14 -2
View File
@@ -1,6 +1,6 @@
{
"name": "@gabriel20xx/shared-code",
"version": "0.1.0",
"version": "0.1.1",
"description": "Shared UI and backend packages for Gabriel20xx projects.",
"license": "MIT",
"repository": {
@@ -45,7 +45,19 @@
"prepare": "npm run build && node scripts/build-root-styles.mjs",
"changeset": "changeset",
"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: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": {
"pg": "^8.17.2"
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@gabriel20xx/design-tokens",
"version": "0.1.0",
"version": "0.1.1",
"description": "Shared visual tokens for Gabriel20xx web projects.",
"license": "MIT",
"files": [
+37
View File
@@ -0,0 +1,37 @@
{
"$comment": "Canonical 32-color brand palette. Each entry: hue (deg), dark-theme primary/fg, light-theme primary/fg. Formula: dark = hsl(h,85%,73%) [hsl(h,80%,40%) if 35<=h<=100], light = hsl(h,72%,50%) [hsl(h,80%,40%) if 35<=h<=100], dark_fg = hsl(h,55%,11%), light_fg = #ffffff.",
"colors": [
{ "name": "Vermilion", "hue": 8.5, "dark": "#f59080", "light": "#db3e24", "dark_fg": "#2b110d", "light_fg": "#ffffff", "status": "reserved" },
{ "name": "Tangerine", "hue": 17.5, "dark": "#fb923c", "light": "#c2410c", "dark_fg": "#2b1206", "light_fg": "#ffffff", "status": "used", "project": "Fork/Heretic" },
{ "name": "Marigold", "hue": 26.5, "dark": "#f5b380", "light": "#db7524", "dark_fg": "#2b1a0d", "light_fg": "#ffffff", "status": "used", "project": "Original/GameStream" },
{ "name": "Amber", "hue": 38.3, "dark": "#f5ca80", "light": "#b87d14", "dark_fg": "#2b200d", "light_fg": "#ffffff", "status": "used", "project": "Original/UnraidMonitor" },
{ "name": "Gold", "hue": 50.2, "dark": "#f5e280", "light": "#b89d14", "dark_fg": "#2b260d", "light_fg": "#ffffff", "status": "used", "project": "Core/OmniLogger" },
{ "name": "Honey", "hue": 62.0, "dark": "#f1f580", "light": "#b2b814", "dark_fg": "#2a2b0d", "light_fg": "#ffffff", "status": "used", "project": "Original/CraftStudio" },
{ "name": "Chartreuse", "hue": 73.9, "dark": "#daf580", "light": "#92b814", "dark_fg": "#242b0d", "light_fg": "#ffffff", "status": "reserved" },
{ "name": "Lime", "hue": 85.7, "dark": "#c3f580", "light": "#72b814", "dark_fg": "#1e2b0d", "light_fg": "#ffffff", "status": "used", "project": "Original/OutdoorGames" },
{ "name": "Spring Green","hue": 97.6, "dark": "#abf580", "light": "#51b814", "dark_fg": "#182b0d", "light_fg": "#ffffff", "status": "used", "project": "Core/ContentScanner" },
{ "name": "Shamrock", "hue": 109.4, "dark": "#94f580", "light": "#44db24", "dark_fg": "#122b0d", "light_fg": "#ffffff", "status": "used", "project": "Original/KioskDisplay" },
{ "name": "Emerald", "hue": 121.3, "dark": "#80f582", "light": "#24db28", "dark_fg": "#0d2b0d", "light_fg": "#ffffff", "status": "used", "project": "Fork/HordeWorker" },
{ "name": "Jade", "hue": 133.1, "dark": "#80f599", "light": "#24db4c", "dark_fg": "#0d2b13", "light_fg": "#ffffff", "status": "reserved" },
{ "name": "Clover", "hue": 142.1, "dark": "#22c55e", "light": "#16a34a", "dark_fg": "#052e14", "light_fg": "#ffffff", "status": "used", "project": "Original/SimpleCollection" },
{ "name": "Mint", "hue": 151.1, "dark": "#80f5bc", "light": "#24db83", "dark_fg": "#0d2b1d", "light_fg": "#ffffff", "status": "used", "project": "Original/MediaDesktop" },
{ "name": "Seafoam", "hue": 163.3, "dark": "#80f5d4", "light": "#24dba8", "dark_fg": "#0d2b23", "light_fg": "#ffffff", "status": "reserved" },
{ "name": "Turquoise", "hue": 175.5, "dark": "#80f5ec", "light": "#24dbce", "dark_fg": "#0d2b29", "light_fg": "#ffffff", "status": "used", "project": "Original/AutoCode" },
{ "name": "Aqua", "hue": 187.8, "dark": "#80e5f5", "light": "#24c3db", "dark_fg": "#0d272b", "light_fg": "#ffffff", "status": "reserved" },
{ "name": "Cyan", "hue": 200.0, "dark": "#80cef5", "light": "#249edb", "dark_fg": "#0d212b", "light_fg": "#ffffff", "status": "used", "project": "Core/CarrierNode" },
{ "name": "Sky Blue", "hue": 212.2, "dark": "#80b6f5", "light": "#2479db", "dark_fg": "#0d1b2b", "light_fg": "#ffffff", "status": "used", "project": "Original/MediaViewer" },
{ "name": "Cornflower", "hue": 221.2, "dark": "#3b82f6", "light": "#2563eb", "dark_fg": "#0a1733", "light_fg": "#ffffff", "status": "used", "project": "Original/CollabTable" },
{ "name": "Indigo", "hue": 230.8, "dark": "#99a1d7", "light": "#4355b9", "dark_fg": "#12162b", "light_fg": "#ffffff", "status": "used", "project": "Fork/Bitmagnet" },
{ "name": "Iris", "hue": 243.4, "dark": "#818cf8", "light": "#4f46e5", "dark_fg": "#12102e", "light_fg": "#ffffff", "status": "used", "project": "Original/PubliSafe" },
{ "name": "Periwinkle", "hue": 252.4, "dark": "#9880f5", "light": "#4a24db", "dark_fg": "#130d2b", "light_fg": "#ffffff", "status": "reserved" },
{ "name": "Violet", "hue": 264.0, "dark": "#ae80f5", "light": "#6d24db", "dark_fg": "#190d2b", "light_fg": "#ffffff", "status": "used", "project": "Original/InfiniteVideo" },
{ "name": "Purple", "hue": 275.6, "dark": "#c580f5", "light": "#9124db", "dark_fg": "#1f0d2b", "light_fg": "#ffffff", "status": "used", "project": "Core/ProjectConfigurator" },
{ "name": "Orchid", "hue": 287.2, "dark": "#dc80f5", "light": "#b424db", "dark_fg": "#250d2b", "light_fg": "#ffffff", "status": "reserved" },
{ "name": "Magenta", "hue": 298.8, "dark": "#f280f5", "light": "#d824db", "dark_fg": "#2b0d2b", "light_fg": "#ffffff", "status": "used", "project": "Fork/MegaBasterd" },
{ "name": "Fuchsia", "hue": 310.4, "dark": "#f580e0", "light": "#db24bb", "dark_fg": "#2b0d26", "light_fg": "#ffffff", "status": "reserved" },
{ "name": "Pink", "hue": 322.1, "dark": "#f580ca", "light": "#db2498", "dark_fg": "#2b0d20", "light_fg": "#ffffff", "status": "used", "project": "Core/ModerationHub" },
{ "name": "Rose", "hue": 333.7, "dark": "#f580b3", "light": "#db2474", "dark_fg": "#2b0d1a", "light_fg": "#ffffff", "status": "used", "project": "Original/SyncServer" },
{ "name": "Ruby", "hue": 345.3, "dark": "#f5809c", "light": "#db2451", "dark_fg": "#2b0d14", "light_fg": "#ffffff", "status": "reserved" },
{ "name": "Crimson", "hue": 356.9, "dark": "#f58086", "light": "#db242d", "dark_fg": "#2b0d0e", "light_fg": "#ffffff", "status": "used", "project": "Core/AuthGuard" }
]
}
+57
View File
@@ -0,0 +1,57 @@
# Brand color palette
Canonical 32-color palette for every webui in this workspace. Each project gets one unique
color (hue) as its default `--color-primary` / `--sc-primary`; no two projects share a hue.
14 colors are still unassigned — reserved for future projects.
Generation formula (given hue `h` in degrees):
- Dark-theme primary: `hsl(h, 85%, 73%)`, except `hsl(h, 80%, 40%)` for `35 <= h <= 100` (yellow/lime band, kept less washed-out)
- Light-theme primary: `hsl(h, 72%, 50%)`, except `hsl(h, 80%, 40%)` for `35 <= h <= 100`
- Dark-theme primary-fg (text on primary): `hsl(h, 55%, 11%)`
- Light-theme primary-fg: `#ffffff`
- Favicon: the dark-theme primary hex (matches this workspace's existing favicon convention)
The 5 colors marked "used, pre-existing" were already unique and good-looking before this
palette was formalized, so their exact original hex values were kept as-is (not
re-derived from the formula) and slotted into the nearest free hue.
| Name | Hue | Dark | Light | Status | Project |
|---|---|---|---|---|---|
| Vermilion | 8.5 | `#f59080` | `#db3e24` | reserved | — |
| Tangerine | 17.5 | `#fb923c` | `#c2410c` | used (pre-existing) | Fork/Heretic |
| Marigold | 26.5 | `#f5b380` | `#db7524` | used | Original/GameStream |
| Amber | 38.3 | `#f5ca80` | `#b87d14` | used | Original/UnraidMonitor |
| Gold | 50.2 | `#f5e280` | `#b89d14` | used | Core/OmniLogger |
| Honey | 62.0 | `#f1f580` | `#b2b814` | used | Original/CraftStudio |
| Chartreuse | 73.9 | `#daf580` | `#92b814` | reserved | — |
| Lime | 85.7 | `#c3f580` | `#72b814` | used | Original/OutdoorGames |
| Spring Green | 97.6 | `#abf580` | `#51b814` | used | Core/ContentScanner |
| Shamrock | 109.4 | `#94f580` | `#44db24` | used | Original/KioskDisplay |
| Emerald | 121.3 | `#80f582` | `#24db28` | used | Fork/HordeWorker |
| Jade | 133.1 | `#80f599` | `#24db4c` | reserved | — |
| Clover | 142.1 | `#22c55e` | `#16a34a` | used (pre-existing) | Original/SimpleCollection |
| Mint | 151.1 | `#80f5bc` | `#24db83` | used | Original/MediaDesktop |
| Seafoam | 163.3 | `#80f5d4` | `#24dba8` | reserved | — |
| Turquoise | 175.5 | `#80f5ec` | `#24dbce` | used | Original/AutoCode |
| Aqua | 187.8 | `#80e5f5` | `#24c3db` | reserved | — |
| Cyan | 200.0 | `#80cef5` | `#249edb` | used | Core/CarrierNode |
| Sky Blue | 212.2 | `#80b6f5` | `#2479db` | used | Original/MediaViewer |
| Cornflower | 221.2 | `#3b82f6` | `#2563eb` | used (pre-existing) | Original/CollabTable |
| Indigo | 230.8 | `#99a1d7` | `#4355b9` | used (pre-existing) | Fork/Bitmagnet |
| Iris | 243.4 | `#818cf8` | `#4f46e5` | used (pre-existing) | Original/PubliSafe |
| Periwinkle | 252.4 | `#9880f5` | `#4a24db` | reserved | — |
| Violet | 264.0 | `#ae80f5` | `#6d24db` | used | Original/InfiniteVideo |
| Purple | 275.6 | `#c580f5` | `#9124db` | used | Core/ProjectConfigurator |
| Orchid | 287.2 | `#dc80f5` | `#b424db` | reserved | — |
| Magenta | 298.8 | `#f280f5` | `#d824db` | used | Fork/MegaBasterd |
| Fuchsia | 310.4 | `#f580e0` | `#db24bb` | reserved | — |
| Pink | 322.1 | `#f580ca` | `#db2498` | used | Core/ModerationHub |
| Rose | 333.7 | `#f580b3` | `#db2474` | used | Original/SyncServer |
| Ruby | 345.3 | `#f5809c` | `#db2451` | reserved | — |
| Crimson | 356.9 | `#f58086` | `#db242d` | used | Core/AuthGuard |
Machine-readable version: `palette.json` in this directory.
When starting a new project, claim the next unclaimed reserved color (or generate a new
hue with the same formula, keeping at least ~10° of hue separation from every existing
entry above) and flip its status to "used" here.
+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. `setBaseUrl(url)` retargets an existing client's AuthGuard URL in place - the natural target for a ProjectConfigurator core-services push handler - so a client can be constructed with `new AuthClient("")` (usable right away, failing closed with `IllegalStateException` until a real URL arrives) rather than needing one known up front. Unlike the Go/Python/Node siblings, this package has no `coreconfig` module of its own: MegaBasterd, its only consumer, wires the `PUT /api/core-services/internal` route directly against a plain field holding the current `AuthGuardUrl`.
## 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](../../../../Fork/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,896 @@
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;
/**
* Header attached to every request when the client is constructed with a projectKey,
* identifying the calling project to AuthGuard so it can enforce per-user project-access
* restriction (see AuthGuard's project-scope admin UI). Mirrors Go's
* {@code authclient.ProjectKeyHeader}.
*/
public static final String PROJECT_KEY_HEADER = "X-Project-Key";
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();
/**
* Not final: {@link #setBaseUrl} retargets it live (e.g. from a project's own
* coreconfig-equivalent push handler), so a Service holding this client can start with
* baseUrl empty ("pending" - see {@link #setBaseUrl}'s doc comment) and still be usable
* once a URL is pushed, without discarding and rebuilding the whole client. {@code volatile}
* since HTTP requests happen on arbitrary threads and String is immutable, so a plain
* volatile field is enough for safe publication without a lock.
*/
private volatile String baseUrl;
private final String cookieName;
private final int timeoutMillis;
private final String projectKey;
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, cookieName, timeoutMillis, "");
}
/**
* @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)}.
* @param projectKey identifies this project to AuthGuard on every request (see
* {@link #PROJECT_KEY_HEADER}), enabling per-user project-access
* restriction. Normally a project's own lowercase identifier, matching
* the key ProjectConfigurator registers it under. Blank/null disables it.
*/
public AuthClient(String baseUrl, String cookieName, int timeoutMillis, String projectKey) {
this.baseUrl = normalizeBaseUrl(baseUrl);
this.cookieName = cookieName == null || cookieName.trim().isEmpty() ? DEFAULT_COOKIE_NAME : cookieName.trim();
this.timeoutMillis = timeoutMillis;
this.projectKey = projectKey == null ? "" : projectKey.trim().toLowerCase();
}
/**
* Atomically replaces the AuthGuard base URL this client calls, normalizing it the same way
* the constructor does. Mirrors Go's {@code authclient.Client.SetBaseURL} and Python's
* {@code AuthClient.set_base_url}: the intended use is a project's own coreconfig-equivalent
* push handler calling this on its live {@code AuthClient} instance so a freshly pushed
* AuthGuard URL takes effect on the client's very next call with no restart - including the
* very first URL a client constructed with {@code baseUrl == ""} (a "pending" client, not yet
* configured but still meant to be used, as opposed to one a project deliberately built with
* no AuthGuard integration at all) ever receives. A blank {@code baseUrl} is ignored (leaving
* the previous value in place) rather than leaving the client unable to reach AuthGuard at all.
*/
public void setBaseUrl(String baseUrl) {
String normalized = normalizeBaseUrl(baseUrl);
if (!normalized.isEmpty()) {
this.baseUrl = normalized;
}
}
/**
* 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 {
String currentBaseUrl = baseUrl;
if (currentBaseUrl.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(currentBaseUrl, 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 {
String currentBaseUrl = baseUrl;
if (currentBaseUrl.isEmpty()) {
throw new IllegalStateException("authclient: client has no base URL");
}
URL url = new URL(currentBaseUrl + path);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod(method);
connection.setConnectTimeout(timeoutMillis);
connection.setReadTimeout(timeoutMillis);
if (!projectKey.isEmpty()) {
connection.setRequestProperty(PROJECT_KEY_HEADER, projectKey);
}
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 currentBaseUrl, String token) throws IOException {
URL url = new URL(currentBaseUrl + "/api/session/validate");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
if (!projectKey.isEmpty()) {
connection.setRequestProperty(PROJECT_KEY_HEADER, projectKey);
}
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,295 @@
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 validateFailsClosedOnAClientWithNoBaseUrlYet() {
// A client constructed with "" (pending - no AuthGuard URL known yet, e.g. before a
// coreconfig-equivalent push arrives) must fail closed rather than silently letting
// every request through; see AuthClient's setBaseUrl doc comment.
AuthClient client = new AuthClient("");
assertThrows(IllegalStateException.class, () -> client.validate("some-token"));
}
@Test
void setBaseUrlRetargetsAPendingClientToItsFirstRealUrl() throws Exception {
server = fakeAuthGuard(200, "{\"valid\":true,\"user_id\":7,\"username\":\"gabriel\",\"role\":\"admin\"}");
AuthClient client = new AuthClient("");
assertThrows(IllegalStateException.class, () -> client.validate("good-token"));
client.setBaseUrl(baseUrl(server));
AuthClient.User user = client.validate("good-token");
assertEquals("gabriel", user.username);
}
@Test
void setBaseUrlIgnoresABlankValue() {
AuthClient client = new AuthClient("https://auth.example.com");
client.setBaseUrl(" ");
assertEquals("https://auth.example.com", client.baseUrlForTest());
}
@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();
}
}
+37 -1
View File
@@ -17,4 +17,40 @@ legacy package as a compatibility layer until every consumer has moved.
Pass a service-specific `tableName` to `runMigrations` when multiple services
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`.
Database startup uses `DB_INIT_RETRY_INTERVAL_MS` (default `5000`, minimum
`250`) and `DB_INIT_RETRY_MAX_ATTEMPTS` (default `0`, retry indefinitely).
Run `npm test` from this package or `npm run test --workspace=@gabriel20xx/node-backend` from `shared`.
## `authclient`/`coreconfig`: adopting AuthGuard instead of local auth
`AuthClient` (`src/authclient.js`) trades a service's own local user table for
HTTP calls to a centralized AuthGuard instance, mirroring the Go/Python/Java
clients. `client.setBaseUrl(url)` retargets an existing client's AuthGuard
URL in place, so a client can be constructed with `new AuthClient('')`
(usable right away, failing closed until a real URL arrives) and be handed a
URL later, rather than needing one known up front.
`coreconfig` (`src/coreconfig.js`, the Node equivalent of
`shared/backend/coreconfig` and `shared_backend.coreconfig`) is a small
`Store` that holds AuthGuard's/CarrierNode's current base URL(s) and updates
live whenever ProjectConfigurator pushes a fresh
`PUT /api/core-services/internal` - wire `store.onUpdate` to
`authClient.setBaseUrl` so a project never needs to hardcode `AUTHGUARD_URL`:
```js
import { AuthClient, CoreConfigStore } from '@gabriel20xx/node-backend';
const authClient = new AuthClient('');
const coreConfig = new CoreConfigStore({ authGuardUrl: '' });
coreConfig.onUpdate((info) => authClient.setBaseUrl(info.authGuardUrl));
// in your own route for PUT /api/core-services/internal:
app.put('/api/core-services/internal', (req, res) => {
if (req.get('X-Internal-Auth') !== process.env.SECRET) {
return res.status(401).json({ error: 'internal service authentication required' });
}
const info = coreConfig.set(req.body);
res.json({ ok: true, info: info.toJSON() });
});
```
+2 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@gabriel20xx/node-backend",
"version": "0.1.0",
"version": "0.1.1",
"description": "Shared PostgreSQL, configuration, migration, and authentication primitives for Node.js services.",
"license": "MIT",
"type": "module",
@@ -14,6 +14,7 @@
"./config": "./src/config.js",
"./db": "./src/db.js",
"./auth": "./src/auth.js",
"./coreconfig": "./src/coreconfig.js",
"./migrate": "./src/migrate.js",
"./package.json": "./package.json"
},
+495
View File
@@ -0,0 +1,495 @@
// 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;
// PROJECT_KEY_HEADER is the header AuthClient attaches to every request when
// constructed with a projectKey, identifying the calling project to
// AuthGuard so it can enforce per-user project-access restriction (see
// AuthGuard's project-scope admin UI). Mirrors Go's authclient.ProjectKeyHeader.
export const PROJECT_KEY_HEADER = 'X-Project-Key';
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, projectKey?: string}} [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;
// projectKey identifies this project to AuthGuard on every request (see
// PROJECT_KEY_HEADER), enabling per-user project-access restriction.
// Normally a project's own lowercase identifier, matching the key
// ProjectConfigurator registers it under.
this.projectKey = String(options.projectKey ?? '').trim().toLowerCase();
}
_projectKeyHeaders() {
return this.projectKey ? { [PROJECT_KEY_HEADER]: this.projectKey } : {};
}
/**
* Atomically replaces the AuthGuard base URL this client calls,
* normalizing it the same way the constructor does. Mirrors Go's
* authclient.Client.SetBaseURL / Python's AuthClient.set_base_url / Java's
* AuthClient#setBaseUrl: the intended use is a project's own
* coreconfig-equivalent push handler calling this on its live AuthClient
* instance so a freshly pushed AuthGuard URL takes effect on the client's
* very next call with no restart - including the very first URL a client
* constructed with baseUrl "" (a "pending" client, not yet configured but
* still meant to be used) ever receives. A blank baseUrl is ignored
* (leaving the previous value in place) rather than leaving the client
* unable to reach AuthGuard at all.
* @param {string} baseUrl
*/
setBaseUrl(baseUrl) {
const normalized = AuthClient._normalizeBaseUrl(baseUrl);
if (normalized) {
this.baseUrl = normalized;
}
}
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}`, ...this._projectKeyHeaders() },
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 = { ...this._projectKeyHeaders() };
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);
}
+145
View File
@@ -0,0 +1,145 @@
/**
* Lets any Node service in this workspace receive AuthGuard's and
* CarrierNode's current base URL(s) pushed from ProjectConfigurator, instead
* of hardcoding them in its own env vars. Mirrors shared/backend/coreconfig
* (Go) and shared/packages/python-backend/src/shared_backend/coreconfig.py
* (Python) exactly - same Info shape, same Store semantics - translated to
* Node idioms; keep all three in sync if any changes shape. See
* ProjectConfigurator/README.md's "Pushing core service info to other
* projects" section for the wire contract this module implements the
* receiving end of.
*
* Framework-agnostic: this module has no HTTP server of its own. A service
* wires the actual `PUT /api/core-services/internal` route in its own
* framework (Express, plain `http`, ...), gated behind its own
* SECRET check the same way its other internal-service
* routes already are, decodes the JSON body with `Info.fromJSON`, and calls
* `store.set(info)` - see `Store.set`'s doc comment for a minimal Express
* example.
*/
/**
* @typedef {{authGuardUrl?: string, carrierNodeUrl?: string, carrierNodeUrls?: string[]}} InfoLike
*/
export class Info {
/**
* @param {InfoLike} [fields]
*/
constructor({ authGuardUrl = '', carrierNodeUrl = '', carrierNodeUrls = [] } = {}) {
this.authGuardUrl = authGuardUrl;
this.carrierNodeUrl = carrierNodeUrl;
this.carrierNodeUrls = carrierNodeUrls;
}
/** Decodes the JSON body ProjectConfigurator's push carries (coreServiceInfo). */
static fromJSON(data) {
const raw = data ?? {};
let urls = Array.isArray(raw.carrierNodeUrls)
? raw.carrierNodeUrls.map((u) => String(u ?? '').trim()).filter(Boolean)
: [];
if (urls.length === 0) {
const single = String(raw.carrierNodeUrl ?? '').trim();
if (single) urls = [single];
}
return new Info({
authGuardUrl: String(raw.authGuardUrl ?? '').trim(),
carrierNodeUrl: urls[0] ?? '',
carrierNodeUrls: urls,
});
}
toJSON() {
return {
authGuardUrl: this.authGuardUrl,
carrierNodeUrl: this.carrierNodeUrl,
carrierNodeUrls: [...this.carrierNodeUrls],
};
}
}
function normalize(info) {
let cleaned = (info.carrierNodeUrls ?? []).map((u) => String(u ?? '').trim()).filter(Boolean);
if (cleaned.length === 0 && String(info.carrierNodeUrl ?? '').trim()) {
cleaned = [String(info.carrierNodeUrl).trim()];
}
return new Info({
authGuardUrl: String(info.authGuardUrl ?? '').trim(),
carrierNodeUrl: cleaned[0] ?? '',
carrierNodeUrls: cleaned,
});
}
export class Store {
/**
* Holds the most recently pushed Info, defaulting to whatever fallback was
* given (typically this service's own AUTHGUARD_URL/CARRIERNODE_URL env
* vars, or "" now that they're optional) until ProjectConfigurator's first
* push arrives - or forever, if this deployment isn't registered with a
* ProjectConfigurator instance at all, in which case those env vars (if
* set) keep working exactly as before.
* @param {InfoLike} [fallback]
*/
constructor(fallback = {}) {
this._info = normalize(fallback instanceof Info ? fallback : new Info(fallback));
this._onUpdate = null;
}
get() {
return this._info;
}
get authGuardUrl() {
return this._info.authGuardUrl;
}
get carrierNodeUrl() {
return this._info.carrierNodeUrl;
}
get carrierNodeUrls() {
return this._info.carrierNodeUrls;
}
/**
* Registers fn to be called (synchronously, so keep it fast) with the new
* Info after every set() - e.g. an AuthClient's setBaseUrl for a client
* that isn't already reading through Store on every call. Only one
* callback is kept; a second registration replaces the first.
* @param {(info: Info) => void} fn
*/
onUpdate(fn) {
this._onUpdate = fn;
}
/**
* Replaces the current Info, field by field, ignoring a blank/empty field
* so a partial push (e.g. only carrierNodeUrl(s) changed) never clobbers
* the other value. Returns the resulting Info. Minimal Express usage:
*
* app.put('/api/core-services/internal', (req, res) => {
* if (req.get('X-Internal-Auth') !== process.env.SECRET) {
* return res.status(401).json({ error: 'internal service authentication required' });
* }
* const info = coreConfigStore.set(Info.fromJSON(req.body));
* res.json({ ok: true, info: info.toJSON() });
* });
*
* @param {InfoLike | Info} nextInfo
* @returns {Info}
*/
set(nextInfo) {
const next = normalize(nextInfo instanceof Info ? nextInfo : new Info(nextInfo));
if (next.authGuardUrl) {
this._info.authGuardUrl = next.authGuardUrl;
}
if (next.carrierNodeUrls.length > 0) {
this._info.carrierNodeUrls = next.carrierNodeUrls;
this._info.carrierNodeUrl = next.carrierNodeUrls[0];
}
if (this._onUpdate) {
this._onUpdate(this._info);
}
return this._info;
}
}
+37 -9
View File
@@ -3,9 +3,28 @@ import { databaseConfigFromEnv } from './config.js';
const { Pool } = pg;
const TRANSIENT_CODES = new Set(['ECONNRESET', 'EPIPE', '57P01', '08006', '08003']);
const DEFAULT_STARTUP_RETRY_INTERVAL_MS = 5000;
const DEFAULT_STARTUP_RETRY_MAX_ATTEMPTS = 0;
const TRANSIENT_CODES = new Set(['ECONNREFUSED', 'ECONNRESET', 'EPIPE', '57P01', '08006', '08003']);
const TRANSIENT_MESSAGE = /connection terminated|connection reset|econnreset|epipe|server closed the connection/i;
function nonNegativeInteger(value, fallback) {
const parsed = Number.parseInt(value, 10);
return Number.isFinite(parsed) ? Math.max(0, parsed) : fallback;
}
export function startupRetryOptionsFromEnv(env = process.env) {
const intervalMs = Math.max(
250,
nonNegativeInteger(env.DB_INIT_RETRY_INTERVAL_MS, DEFAULT_STARTUP_RETRY_INTERVAL_MS)
);
const maxAttempts = nonNegativeInteger(
env.DB_INIT_RETRY_MAX_ATTEMPTS,
DEFAULT_STARTUP_RETRY_MAX_ATTEMPTS
);
return { intervalMs, maxAttempts };
}
export function isTransientConnectionError(error) {
return Boolean(
error &&
@@ -30,23 +49,32 @@ export class Database {
return new Database(databaseConfigFromEnv(env));
}
async connect({ retries = 10, retryDelayMs = 2000 } = {}) {
async connect(options = {}) {
if (this.ready) return this;
let lastError;
for (let attempt = 1; attempt <= Math.max(1, retries); attempt += 1) {
const defaults = startupRetryOptionsFromEnv();
const maxAttempts = options.maxAttempts ?? options.retries ?? defaults.maxAttempts;
const retryIntervalMs = Math.max(
250,
options.retryIntervalMs ?? options.retryDelayMs ?? defaults.intervalMs
);
let attempt = 0;
while (true) {
attempt += 1;
try {
await this.pool.query('SELECT 1');
this.ready = true;
return this;
} catch (error) {
lastError = error;
if (attempt >= retries || !isTransientConnectionError(error)) throw error;
const delay = Math.min(Math.max(100, retryDelayMs) * 2 ** (attempt - 1), 30000);
await new Promise(resolve => setTimeout(resolve, delay));
if (
(maxAttempts > 0 && attempt >= maxAttempts) ||
!isTransientConnectionError(error)
) {
throw error;
}
await new Promise(resolve => setTimeout(resolve, retryIntervalMs));
}
}
throw lastError;
}
async query(text, values = []) {
+2
View File
@@ -31,3 +31,5 @@ export {
verifyTotp,
} from './totp.js';
export { runMigrations } from './migrate.js';
export { APIError, AuthClient, InvalidSessionError, createAuthClient } from './authclient.js';
export { Info as CoreConfigInfo, Store as CoreConfigStore } from './coreconfig.js';
@@ -0,0 +1,340 @@
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('setBaseUrl retargets a pending client (constructed with "") to its first real URL', async () => {
const client = new AuthClient('', {
fetchImpl: fakeFetch([{ status: 200, body: { valid: true, user_id: 7, username: 'gabriel', role: 'admin' } }]),
});
await assert.rejects(() => client.validate('good-token'), /no base URL/);
client.setBaseUrl('https://auth.example.com');
assert.equal(client.baseUrl, 'https://auth.example.com');
const user = await client.validate('good-token');
assert.deepEqual(user, { id: 7, username: 'gabriel', role: 'admin' });
});
test('setBaseUrl ignores a blank value, leaving the previous URL in place', () => {
const client = new AuthClient('https://auth.example.com');
client.setBaseUrl(' ');
assert.equal(client.baseUrl, 'https://auth.example.com');
});
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');
});
@@ -0,0 +1,50 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { Info, Store } from '../src/coreconfig.js';
test('store seeds from the fallback Info', () => {
const store = new Store({ authGuardUrl: 'http://auth.example.com', carrierNodeUrl: 'http://carrier.example.com' });
assert.equal(store.authGuardUrl, 'http://auth.example.com');
assert.equal(store.carrierNodeUrl, 'http://carrier.example.com');
assert.deepEqual(store.carrierNodeUrls, ['http://carrier.example.com']);
});
test('store defaults to empty with no fallback', () => {
const store = new Store();
assert.equal(store.authGuardUrl, '');
assert.deepEqual(store.carrierNodeUrls, []);
});
test('set ignores a blank authGuardUrl rather than clobbering the existing one', () => {
const store = new Store({ authGuardUrl: 'http://auth.example.com' });
store.set({ authGuardUrl: '', carrierNodeUrl: 'http://carrier.example.com' });
assert.equal(store.authGuardUrl, 'http://auth.example.com');
assert.equal(store.carrierNodeUrl, 'http://carrier.example.com');
});
test('set only replaces carrierNodeUrls when the push actually carries one', () => {
const store = new Store({ carrierNodeUrl: 'http://carrier.example.com' });
store.set({ authGuardUrl: 'http://auth.example.com' });
assert.equal(store.carrierNodeUrl, 'http://carrier.example.com');
assert.equal(store.authGuardUrl, 'http://auth.example.com');
});
test('onUpdate is called with the resulting Info after set', () => {
const store = new Store();
const seen = [];
store.onUpdate((info) => seen.push(info));
store.set({ authGuardUrl: 'http://auth.example.com' });
assert.equal(seen.length, 1);
assert.equal(seen[0].authGuardUrl, 'http://auth.example.com');
});
test('Info.fromJSON/toJSON round-trip the wire shape', () => {
const payload = {
authGuardUrl: 'http://auth.example.com',
carrierNodeUrl: 'http://carrier.example.com',
carrierNodeUrls: ['http://carrier.example.com', 'http://carrier2.example.com'],
};
const info = Info.fromJSON(payload);
assert.deepEqual(info.carrierNodeUrls, ['http://carrier.example.com', 'http://carrier2.example.com']);
assert.equal(info.toJSON().carrierNodeUrl, 'http://carrier.example.com');
});
+153 -3
View File
@@ -3,15 +3,165 @@
Shared Python backend infrastructure for services using `asyncpg`:
- validated `DATABASE_URL` and pool settings;
- one async pool owner with ping and graceful shutdown;
- one async pool owner with startup retry, ping, and graceful shutdown;
- bcrypt password and secure session-token helpers;
- 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
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:
```bash
pip install "git+https://repos.gfranz.ch/Gabriel20xx/shared@v0.1.0#subdirectory=packages/python-backend"
```
Database startup uses `DB_INIT_RETRY_INTERVAL_MS` (default `5000`, minimum
`250`) and `DB_INIT_RETRY_MAX_ATTEMPTS` (default `0`, retry indefinitely).
## `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)])
...
```
`auth_client.set_base_url(url)` retargets an existing client's AuthGuard
base URL in place — the natural callback for `coreconfig.Store.on_update`
(see below), so a live `authGuardUrl` push from ProjectConfigurator takes
effect on the client's very next call with no restart. This also means a
service no longer needs to know its AuthGuard URL at construction time: a
client built with `AuthClient("")` is usable right away (it just fails
closed, with a clear error, until a real URL arrives), so a service that
gets its `AUTHGUARD_URL` from ProjectConfigurator's push doesn't need the
env var set at all — see `coreconfig` below.
## `coreconfig`: receiving AuthGuard's/CarrierNode's URL(s) from ProjectConfigurator
`shared_backend.coreconfig` is the Python equivalent of
`shared/backend/coreconfig` (Go): a small, framework-agnostic `Store` that
holds AuthGuard's and CarrierNode's current base URL(s), seeded from
whatever fallback (e.g. this service's own env vars, or nothing at all) you
give it, and updated live whenever ProjectConfigurator pushes a fresh
`PUT /api/core-services/internal`. A service wires the actual route itself:
```python
from shared_backend import AuthClient, CoreConfigInfo, CoreConfigStore
auth_client = AuthClient("") # pending: no URL yet, still safe to use
core_config = CoreConfigStore(CoreConfigInfo(auth_guard_url=""))
core_config.on_update(lambda info: auth_client.set_base_url(info.auth_guard_url))
# in your framework's route for PUT /api/core-services/internal:
async def push_core_services(request):
if request.headers.get("X-Internal-Auth") != SECRET:
raise HTTPException(status_code=401)
body = await request.json()
info = core_config.set(CoreConfigInfo.from_json(body))
return {"ok": True, "info": info.to_json()}
```
## `authproxy`: a ready-to-mount FastAPI router (optional)
Wiring up `authclient` still leaves each service reimplementing the same
~800-1000 lines of status/setup/login/logout/TOTP/admin-user-CRUD
boilerplate around it — three projects in this workspace independently did
exactly that before `shared_backend.authproxy` was extracted from them.
Unlike the rest of this package, `authproxy` is a deliberate, narrow
exception to "HTTP framework adapters stay in each service": it hard-depends
on FastAPI and Pydantic, and is only pulled in if you install the optional
`fastapi` extra:
```bash
pip install "gabriel20xx-shared-backend[fastapi]"
```
A service implements a small `ProxyStore` (two independent, genuinely
local concerns: a one-time "has this deployment's setup screen been
completed" claim flag, and optionally a "require login" toggle) and calls
`build_auth_router` once to get a fully-formed `APIRouter`:
```python
from shared_backend.authclient import AuthClient
from shared_backend.authproxy import ProxyStore, build_auth_router
class MyStore(ProxyStore):
async def login_required(self) -> bool:
return True
async def set_login_required(self, required: bool) -> None:
pass
async def is_setup_claimed(self) -> bool: ... # your own table
async def try_claim_setup(self) -> bool: ... # your own table
async def unclaim_setup(self) -> None: ... # your own table
def get_client(request):
return request.app.state.auth_client # AuthClient | None, or None in auth-disabled mode
def get_store(request):
return request.app.state.auth_store
app.include_router(
build_auth_router(get_client, get_store, legacy_cookie_name="myproject_session"),
prefix="/api/auth",
)
```
This mounts `/status`, `/me` (GET/PUT), `/admin-needed`, `/setup`, `/login`,
`/logout`, `/access` (GET/PUT, the login-required toggle), `/users`
(GET/POST), `/users/{id}` (PUT/PATCH/DELETE), and `/totp/status|initiate|verify|disable`
— the same URL paths and JSON response shapes as `shared/backend/auth`
(Go)'s `Service`, so a project migrating onto this module gets the same
standardized wire format that Go consumers of that engine already have.
+10 -1
View File
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
[project]
name = "gabriel20xx-shared-backend"
version = "0.1.0"
version = "0.1.1"
description = "Shared PostgreSQL and authentication primitives for Python services."
readme = "README.md"
requires-python = ">=3.10"
@@ -14,6 +14,15 @@ dependencies = [
"bcrypt>=4.2",
]
# Optional: only shared_backend.authproxy needs these (a FastAPI-specific
# AuthGuard-proxy router builder). The rest of this package stays
# framework-agnostic by design - see authclient.py's module docstring.
# Install with `pip install gabriel20xx-shared-backend[fastapi]`; a consumer
# that already depends on FastAPI directly (as every current authproxy
# consumer does) satisfies this from its own requirements regardless.
[project.optional-dependencies]
fastapi = ["fastapi>=0.100", "pydantic>=2"]
[tool.setuptools.packages.find]
where = ["src"]
@@ -14,7 +14,17 @@ from .auth import (
normalize_role,
verify_password,
)
from .authclient import (
AuthClient,
AuthClientError,
AuthGuardUser,
InvalidSessionError,
resolve_user,
token_from_request,
)
from .config import DatabaseConfig, database_url_from_env
from .coreconfig import Info as CoreConfigInfo
from .coreconfig import Store as CoreConfigStore
from .postgres import Database
from .tokens import hash_token, new_session_token
from .totp import generate_totp_secret, totp_provisioning_uri, verify_totp
@@ -22,6 +32,14 @@ from .totp import generate_totp_secret, totp_provisioning_uri, verify_totp
__all__ = [
"AuthStore",
"AuthUser",
"AuthClient",
"AuthClientError",
"AuthGuardUser",
"InvalidSessionError",
"resolve_user",
"token_from_request",
"CoreConfigInfo",
"CoreConfigStore",
"ROLE_ADMIN",
"ROLE_SUPERADMIN",
"ROLE_USER",
@@ -0,0 +1,606 @@
"""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 "
# PROJECT_KEY_HEADER is the header AuthClient attaches to every request when
# constructed with project_key, identifying the calling project to AuthGuard
# so it can enforce per-user project-access restriction (see AuthGuard's
# project-scope admin UI). Mirrors Go's authclient.ProjectKeyHeader.
PROJECT_KEY_HEADER = "X-Project-Key"
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,
project_key: str = "",
) -> 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
# project_key identifies this project to AuthGuard on every request
# (see PROJECT_KEY_HEADER), enabling per-user project-access
# restriction. Normally a project's own lowercase identifier,
# matching the key ProjectConfigurator registers it under.
self.project_key = (project_key or "").strip().lower()
def set_base_url(self, base_url: str) -> None:
"""Atomically replaces the AuthGuard base URL this client calls,
normalizing it the same way __init__ does. Mirrors Go's
authclient.Client.SetBaseURL: the intended use is a project's own
coreconfig-equivalent push handler calling this on its live
AuthClient instance so a freshly pushed authGuardUrl takes effect on
the client's very next call with no restart -- including the very
first URL a client constructed with base_url="" (a "pending" client,
not yet configured but still meant to be used) ever receives. A
blank base_url is ignored (leaving the previous value in place)
rather than leaving the client unable to reach AuthGuard at all."""
normalized = _normalize_base_url(base_url)
if normalized:
self.base_url = normalized
# --- 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:
headers = {"Authorization": f"{_BEARER_PREFIX}{token}"}
if self.project_key:
headers[PROJECT_KEY_HEADER] = self.project_key
request = urllib.request.Request(
f"{self.base_url}/api/session/validate",
headers=headers,
)
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 self.project_key:
headers[PROJECT_KEY_HEADER] = self.project_key
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)
@@ -0,0 +1,749 @@
"""shared_backend.authproxy: the Python equivalent of shared/backend/auth's
Service/New/NewWithStore (Go) - the ONE shared AuthGuard-proxy engine for
every FastAPI-based project in this workspace that centralizes identity
through AuthGuard, instead of each project hand-rolling its own
status/setup/login/logout/TOTP/admin-user-CRUD proxy around AuthClient.
Extracted 2026-09-13 from three near-identical ~800-1000 line
implementations (Heretic, HordeWorker, InfiniteVideo), each explicitly
documented as mirroring the others and, ultimately, the reference Go
implementation (Original/GameStream/backend/cmd/gamestreamd/auth.go before
its own migration onto shared/backend/auth). Read any of those three
projects' pre-migration auth.py (or their own project's post-migration
git history) for the fuller narrative rationale behind each design choice
below - it is intentionally not repeated at length here.
Usage
-----
A project builds a `ProxyStore` implementation over whatever local
persistence it already has for two small, genuinely independent concerns:
a one-time "has this deployment's setup screen been completed" claim flag,
and (optionally) a "require login" toggle. It then calls `build_auth_router`
once, passing:
- `get_client(request) -> AuthClient | None`: resolve this request's
AuthClient from wherever the project stores it (typically
`request.app.state.auth_client`); `None` means AUTHGUARD_URL was unset
(auth-disabled mode - see `_LOCAL_PROFILE`'s doc comment below).
- `get_store(request) -> ProxyStore`: resolve this request's ProxyStore
the same way.
- `project_key`: this project's own lowercase identifier, passed to
`AuthClient(..., project_key=...)` by the project itself when
constructing its client - NOT re-passed here; this module never
constructs an AuthClient itself. Mentioned here only so a project
wiring this up remembers to set it.
- `legacy_cookie_name`: the project's own pre-migration session cookie
name, if any, cleared alongside AuthGuard's on logout for browsers that
still hold one.
- `secure_cookie`: whether cookies this router sets/clears should carry
the `Secure` attribute (mirror the project's own COOKIE_SECURE-style
setting).
and mounts the resulting `APIRouter` at `/api/auth` (the prefix every
existing consumer already uses - this module's own routes are declared
without a prefix, so a project could choose a different one, but doing so
would be a project-specific behavior change, not part of this migration).
Response shapes deliberately match shared/backend/auth (Go)'s: a nested
`user` object rather than flat fields, TOTP payloads nested under `data`,
etc. - the same standardization already applied when GameStream, OmniLogger,
and several other Go projects were migrated onto that engine. A project
adopting this module updates its own frontend to match; this is intentional,
not a bug.
"""
from __future__ import annotations
import abc
import os
from typing import Any, Callable, Optional
from fastapi import APIRouter, Depends, HTTPException, Request, Response
from pydantic import BaseModel
from .auth import ROLE_SUPERADMIN, can_manage_users, normalize_role
from .authclient import (
DEFAULT_COOKIE_NAME,
APIError,
AuthClient,
AuthClientError,
ManagedUser,
PublicUser,
)
__all__ = ["ProxyStore", "build_auth_router"]
MIN_PASSWORD_LEN = 8
MAX_USERNAME_LEN = 64
MAX_EMAIL_LEN = 254
ERR_AUTH_REQUIRED = "Authentication required."
ERR_SETUP_COMPLETE = "Setup has already been completed."
ERR_INVALID_CREDENTIALS = "Invalid username or password."
ERR_INVALID_INPUT = "Invalid authentication input."
ERR_SELF_SERVICE_PROFILE = (
"Self-service profile editing is only available to administrator accounts; "
"ask an administrator to update this account."
)
# Returned by handlers that need a real backing identity (not just an access
# gate) when AUTHGUARD_URL is unset; see _LOCAL_PROFILE's doc comment.
ERR_FEATURE_REQUIRES_AUTHGUARD = "This feature requires AUTHGUARD_URL to be configured."
# Raised whenever AuthGuard could not be reached or gave an unusable response
# - a real "invalid or expired session" always resolves to None instead,
# never this error - so every caller can safely report this same message
# rather than a generic "internal error" indistinguishable from any other bug.
ERR_AUTHGUARD_UNAVAILABLE = "Unable to reach the authentication service. Please try again shortly."
ERR_SECRET_NOT_SET = "SECRET environment variable is not set."
# _LOCAL_PROFILE is the fixed placeholder identity every handler reports when
# authentication is disabled, either because AUTHGUARD_URL is disabled or
# because ProjectConfigurator has turned off this project's login requirement.
# Role is superadmin so all application routes see the same Admin identity even
# though no credentials were supplied.
_LOCAL_PROFILE = PublicUser(
id=0, username="Admin", email="", role=ROLE_SUPERADMIN, totp_enabled=False
)
class ProxyStore(abc.ABC):
"""The small piece of local, project-owned persistence build_auth_router
needs beyond AuthGuard itself: the independent "require login" toggle
and the one-time "has this deployment's setup screen been completed"
claim flag. Mirrors Go's sharedauth.ProxyStore exactly (same five
operations); a project with no "require login" concept of its own can
make login_required always return True and set_login_required a no-op.
"""
@abc.abstractmethod
async def login_required(self) -> bool: ...
@abc.abstractmethod
async def set_login_required(self, required: bool) -> None: ...
@abc.abstractmethod
async def is_setup_claimed(self) -> bool: ...
@abc.abstractmethod
async def try_claim_setup(self) -> bool: ...
@abc.abstractmethod
async def unclaim_setup(self) -> None: ...
ClientGetter = Callable[[Request], Optional[AuthClient]]
StoreGetter = Callable[[Request], ProxyStore]
# Request/response models are declared at module level (not inside
# build_auth_router) deliberately: this file uses `from __future__ import
# annotations` (PEP 563), which turns every annotation into a string
# resolved later via the function's *module* globals - a class nested
# inside build_auth_router's local scope is invisible to that resolution,
# which silently breaks FastAPI's body-vs-query-param detection (a
# nested-class version of this router mistook every JSON body for a
# missing query parameter). Keeping these as plain module-level classes
# avoids that trap entirely.
class SetupRequest(BaseModel):
username: str
email: str
password: str
class LoginRequest(BaseModel):
identifier: Optional[str] = None
username: Optional[str] = None
email: Optional[str] = None
password: str
totpToken: str = ""
class UpdateMeRequest(BaseModel):
email: str = ""
username: str = ""
password: str = ""
class UpdateAccessRequest(BaseModel):
loginRequired: bool
class ManagedUserRequest(BaseModel):
username: str = ""
email: str = ""
password: str = ""
role: Optional[str] = None
class TotpTokenRequest(BaseModel):
token: str = ""
totpToken: str = ""
def _normalize_username(username: str) -> str:
username = (username or "").strip()
if not username or len(username) > MAX_USERNAME_LEN:
raise HTTPException(status_code=400, detail="Username is required.")
return username
def _normalize_email(email: str) -> str:
email = (email or "").strip().lower()
if not email or len(email) > MAX_EMAIL_LEN or email.count("@") != 1:
raise HTTPException(status_code=400, detail="Email is required and must be valid.")
local, domain = email.split("@", 1)
if not local or not domain or "." not in domain:
raise HTTPException(status_code=400, detail="Email is required and must be valid.")
return email
def _validate_password(password: str) -> None:
if len(password or "") < MIN_PASSWORD_LEN:
raise HTTPException(status_code=400, detail="Password must be at least 8 characters.")
def _raise_authguard_error(err: Exception, fallback: str) -> None:
"""Translates an authclient error into a FastAPI HTTPException. AuthGuard's
own httpapi handlers were built from this workspace's various original
local implementations, so their status codes and messages already match
closely - AuthGuard's APIError is forwarded close to verbatim rather than
re-mapped by hand. A non-APIError (a transport failure actually reaching
AuthGuard) falls back to a generic 500 with `fallback`."""
if isinstance(err, APIError):
raise HTTPException(status_code=err.status_code, detail=err.message) from err
raise HTTPException(status_code=500, detail=fallback) from err
def _user_payload(user: PublicUser) -> dict[str, Any]:
return {
"id": user.id,
"username": user.username,
"email": user.email,
"role": normalize_role(user.role),
"canManageUsers": can_manage_users(user.role),
"mfaEnabled": user.totp_enabled,
}
def _managed_user_payload(user: ManagedUser) -> dict[str, Any]:
return {
"id": user.id,
"username": user.username,
"email": user.email,
"role": normalize_role(user.role),
"createdAt": user.created_at,
}
def build_auth_router(
get_client: ClientGetter,
get_store: StoreGetter,
*,
legacy_cookie_name: str = "",
secure_cookie: bool = False,
cookie_name: str = DEFAULT_COOKIE_NAME,
configuration_error: str | None = None,
internal_secret: str | None = None,
) -> APIRouter:
"""Builds a ready-to-mount APIRouter implementing the full standardized
AuthGuard-proxy surface (no prefix baked in - mount it at "/api/auth",
matching every existing consumer). See the module docstring for the
`get_client`/`get_store` contract."""
router = APIRouter()
login_required_override: bool | None = None
configured_internal_secret = (
os.environ.get("SECRET", "") if internal_secret is None else internal_secret
).strip()
def _ensure_configured() -> None:
if configuration_error:
raise HTTPException(status_code=500, detail=configuration_error)
def _enabled(client: Optional[AuthClient]) -> bool:
return client is not None
def _session_token(request: Request) -> str:
return request.cookies.get(cookie_name, "") or ""
def _clear_session_cookies(response: Response) -> None:
names = [cookie_name]
if legacy_cookie_name and legacy_cookie_name != cookie_name:
names.append(legacy_cookie_name)
for name in names:
response.delete_cookie(
key=name, path="/", secure=secure_cookie, httponly=True, samesite="lax"
)
def _forward_cookies(response: Response, cookies: list[str]) -> None:
for cookie in cookies:
response.headers.append("set-cookie", cookie)
async def _current_profile(
request: Request, client: AuthClient
) -> tuple[Optional[PublicUser], str]:
token = _session_token(request)
if not token:
return None, ""
try:
user = await client.me(token)
except APIError as exc:
if exc.status_code == 401:
return None, ""
raise
return user, token
async def _current_profile_or_401(
request: Request, client: AuthClient
) -> tuple[PublicUser, str]:
try:
profile, token = await _current_profile(request, client)
except AuthClientError as exc:
raise HTTPException(status_code=500, detail=ERR_AUTHGUARD_UNAVAILABLE) from exc
if profile is None:
raise HTTPException(status_code=401, detail=ERR_AUTH_REQUIRED)
return profile, token
async def _login_required(store: ProxyStore) -> bool:
if login_required_override is not None:
return login_required_override
return await store.login_required()
async def require_session(
request: Request,
store: ProxyStore = Depends(get_store), # noqa: B008
client: Optional[AuthClient] = Depends(get_client), # noqa: B008
) -> PublicUser:
"""FastAPI dependency gating a route behind a valid session."""
if not _enabled(client) or not await _login_required(store):
return _LOCAL_PROFILE
assert client is not None
profile, _ = await _current_profile_or_401(request, client)
return profile
async def _require_user_manager(
request: Request,
store: ProxyStore = Depends(get_store), # noqa: B008
client: Optional[AuthClient] = Depends(get_client), # noqa: B008
) -> str:
"""Returns the caller's session token, or "" in auth-disabled mode
(each handler decides its own auth-disabled response). Authorization
(can_manage_users, "protect the superadmin") is enforced by
AuthGuard itself from the forwarded token."""
if not _enabled(client) or not await _login_required(store):
return ""
token = _session_token(request)
if not token:
raise HTTPException(status_code=401, detail=ERR_AUTH_REQUIRED)
return token
# --- status / me -------------------------------------------------------
@router.get("/me")
async def get_me(
request: Request,
store: ProxyStore = Depends(get_store), # noqa: B008
client: Optional[AuthClient] = Depends(get_client), # noqa: B008
) -> dict[str, Any]:
_ensure_configured()
login_required = await _login_required(store)
if not _enabled(client):
return {"user": _user_payload(_LOCAL_PROFILE), "authRequired": False}
if not login_required:
return {"user": _user_payload(_LOCAL_PROFILE), "authRequired": False}
assert client is not None
try:
profile, _ = await _current_profile(request, client)
except AuthClientError as exc:
raise HTTPException(status_code=500, detail=ERR_AUTHGUARD_UNAVAILABLE) from exc
return {
"user": _user_payload(profile) if profile else None,
"authRequired": login_required,
}
@router.get("/admin-needed")
async def get_admin_needed(
store: ProxyStore = Depends(get_store), # noqa: B008
client: Optional[AuthClient] = Depends(get_client), # noqa: B008
) -> dict[str, bool]:
if not _enabled(client):
return {"adminNeeded": False}
if not await _login_required(store):
return {"adminNeeded": False}
assert client is not None
if await store.is_setup_claimed():
return {"adminNeeded": False}
try:
setup_required = await client.setup_status()
except AuthClientError as exc:
raise HTTPException(status_code=500, detail=ERR_AUTHGUARD_UNAVAILABLE) from exc
return {"adminNeeded": setup_required}
@router.get("/status")
async def get_status(
request: Request,
store: ProxyStore = Depends(get_store), # noqa: B008
client: Optional[AuthClient] = Depends(get_client), # noqa: B008
) -> dict[str, Any]:
_ensure_configured()
if not _enabled(client):
return {
"setupRequired": False,
"authenticated": True,
"authRequired": False,
"user": _user_payload(_LOCAL_PROFILE),
}
assert client is not None
login_required = await _login_required(store)
if not login_required:
return {
"setupRequired": False,
"authenticated": True,
"authRequired": False,
"user": _user_payload(_LOCAL_PROFILE),
}
claimed = await store.is_setup_claimed()
setup_required = False
if not claimed:
try:
setup_required = await client.setup_status()
except AuthClientError as exc:
raise HTTPException(status_code=500, detail=ERR_AUTHGUARD_UNAVAILABLE) from exc
try:
profile, _ = await _current_profile(request, client)
except AuthClientError as exc:
raise HTTPException(status_code=500, detail=ERR_AUTHGUARD_UNAVAILABLE) from exc
return {
"setupRequired": setup_required,
"authenticated": profile is not None,
"authRequired": login_required,
"user": _user_payload(profile) if profile else None,
}
# --- setup / login / logout ---------------------------------------------
@router.post("/setup", status_code=201)
async def setup(
req: SetupRequest,
response: Response,
store: ProxyStore = Depends(get_store), # noqa: B008
client: Optional[AuthClient] = Depends(get_client), # noqa: B008
) -> dict[str, Any]:
if not _enabled(client):
return {"user": _user_payload(_LOCAL_PROFILE)}
assert client is not None
username = _normalize_username(req.username)
email = _normalize_email(req.email)
_validate_password(req.password)
if not await store.try_claim_setup():
raise HTTPException(status_code=409, detail=ERR_SETUP_COMPLETE)
try:
setup_required = await client.setup_status()
except AuthClientError as exc:
await store.unclaim_setup()
raise HTTPException(status_code=500, detail=ERR_AUTHGUARD_UNAVAILABLE) from exc
if not setup_required:
await store.unclaim_setup()
raise HTTPException(status_code=409, detail=ERR_SETUP_COMPLETE)
try:
result = await client.register(username, email, req.password)
except AuthClientError as exc:
await store.unclaim_setup()
_raise_authguard_error(exc, "Could not create account.")
raise # unreachable
_forward_cookies(response, result.cookies)
return {"user": _user_payload(result.user)}
@router.post("/login")
async def login(
req: LoginRequest,
response: Response,
client: Optional[AuthClient] = Depends(get_client), # noqa: B008
) -> dict[str, Any]:
if not _enabled(client):
return {"user": _user_payload(_LOCAL_PROFILE)}
assert client is not None
identifier = (req.identifier or req.username or req.email or "").strip()
if not identifier or len(identifier) > MAX_EMAIL_LEN:
raise HTTPException(status_code=401, detail=ERR_INVALID_CREDENTIALS)
try:
result = await client.login(identifier, req.password, req.totpToken)
except APIError as exc:
if exc.totp_required:
raise HTTPException(
status_code=401,
detail={
"error": "Two-factor authentication code required.",
"mfaRequired": True,
},
) from exc
if exc.status_code == 401:
raise HTTPException(status_code=401, detail=ERR_INVALID_CREDENTIALS) from exc
_raise_authguard_error(exc, "Could not authenticate.")
raise # unreachable
except AuthClientError as exc:
raise HTTPException(status_code=500, detail=ERR_AUTHGUARD_UNAVAILABLE) from exc
_forward_cookies(response, result.cookies)
return {"user": _user_payload(result.user)}
@router.post("/logout")
async def logout(
request: Request,
response: Response,
client: Optional[AuthClient] = Depends(get_client), # noqa: B008
) -> dict[str, bool]:
if _enabled(client):
assert client is not None
token = _session_token(request)
if token:
try:
cookies = await client.logout(token)
except APIError:
cookies = []
except AuthClientError as exc:
raise HTTPException(status_code=500, detail="Internal error.") from exc
else:
_forward_cookies(response, cookies)
_clear_session_cookies(response)
return {"ok": True}
# --- self-service profile editing ---------------------------------------
@router.put("/me")
@router.post("/me")
async def update_me(
req: UpdateMeRequest,
request: Request,
client: Optional[AuthClient] = Depends(get_client), # noqa: B008
) -> dict[str, Any]:
if not _enabled(client):
raise HTTPException(status_code=409, detail=ERR_FEATURE_REQUIRES_AUTHGUARD)
assert client is not None
current, token = await _current_profile_or_401(request, client)
if not can_manage_users(current.role):
raise HTTPException(status_code=403, detail=ERR_SELF_SERVICE_PROFILE)
email = _normalize_email(req.email)
username = _normalize_username(req.username)
password = None
if req.password:
_validate_password(req.password)
password = req.password
try:
await client.update_managed_user(
token, current.id, username=username, email=email, password=password
)
except AuthClientError as exc:
_raise_authguard_error(exc, "Profile could not be updated.")
raise # unreachable
try:
updated = await client.me(token)
except AuthClientError as exc:
raise HTTPException(status_code=500, detail="Profile could not be loaded.") from exc
return {"user": _user_payload(updated)}
# --- login-required toggle (only meaningful for a project that already
# has this concept locally; ProxyStore.login_required/set_login_required
# stub to (True, no-op) otherwise) --------------------------------------
@router.get("/access")
async def access_settings(store: ProxyStore = Depends(get_store)) -> dict[str, bool]: # noqa: B008
return {"loginRequired": await _login_required(store)}
@router.put("/access")
async def update_access_settings(
req: UpdateAccessRequest,
store: ProxyStore = Depends(get_store), # noqa: B008
) -> dict[str, bool]:
nonlocal login_required_override
await store.set_login_required(req.loginRequired)
login_required_override = req.loginRequired
return {"loginRequired": req.loginRequired}
@router.put("/access/internal")
async def update_access_settings_internal(
req: UpdateAccessRequest,
request: Request,
store: ProxyStore = Depends(get_store), # noqa: B008
) -> dict[str, bool]:
nonlocal login_required_override
if (
not configured_internal_secret
or request.headers.get("X-Internal-Auth") != configured_internal_secret
):
raise HTTPException(status_code=401, detail="internal service authentication required")
await store.set_login_required(req.loginRequired)
login_required_override = req.loginRequired
return {"loginRequired": req.loginRequired}
# --- admin user management ----------------------------------------------
@router.get("/users")
async def list_users(
client: Optional[AuthClient] = Depends(get_client), # noqa: B008
token: str = Depends(_require_user_manager), # noqa: B008
) -> list[dict[str, Any]]:
if not _enabled(client):
return []
assert client is not None
try:
users = await client.list_managed_users(token)
except AuthClientError as exc:
_raise_authguard_error(exc, "Users unavailable.")
raise # unreachable
return [_managed_user_payload(u) for u in users]
@router.post("/users", status_code=201)
async def create_managed_user(
req: ManagedUserRequest,
client: Optional[AuthClient] = Depends(get_client), # noqa: B008
token: str = Depends(_require_user_manager), # noqa: B008
) -> dict[str, Any]:
if not _enabled(client):
raise HTTPException(status_code=409, detail=ERR_FEATURE_REQUIRES_AUTHGUARD)
assert client is not None
try:
created = await client.create_managed_user(
token, username=req.username, email=req.email, password=req.password, role=req.role
)
except AuthClientError as exc:
_raise_authguard_error(exc, "User could not be created.")
raise # unreachable
return _managed_user_payload(created)
@router.put("/users/{user_id}")
@router.patch("/users/{user_id}")
async def update_managed_user(
user_id: int,
req: ManagedUserRequest,
client: Optional[AuthClient] = Depends(get_client), # noqa: B008
token: str = Depends(_require_user_manager), # noqa: B008
) -> dict[str, Any]:
if not _enabled(client):
raise HTTPException(status_code=409, detail=ERR_FEATURE_REQUIRES_AUTHGUARD)
assert client is not None
try:
await client.update_managed_user(
token,
user_id,
username=req.username or None,
email=req.email or None,
password=req.password or None,
role=req.role,
)
except AuthClientError as exc:
_raise_authguard_error(exc, "User could not be updated.")
raise # unreachable
try:
users = await client.list_managed_users(token)
except AuthClientError as exc:
_raise_authguard_error(exc, "User could not be loaded.")
raise # unreachable
updated = next((u for u in users if u.id == user_id), None)
if updated is None:
raise HTTPException(status_code=404, detail="User not found.")
return _managed_user_payload(updated)
@router.delete("/users/{user_id}")
async def delete_managed_user(
user_id: int,
client: Optional[AuthClient] = Depends(get_client), # noqa: B008
token: str = Depends(_require_user_manager), # noqa: B008
) -> dict[str, bool]:
if not _enabled(client):
raise HTTPException(status_code=409, detail=ERR_FEATURE_REQUIRES_AUTHGUARD)
assert client is not None
try:
await client.delete_managed_user(token, user_id)
except AuthClientError as exc:
_raise_authguard_error(exc, "User could not be deleted.")
raise # unreachable
return {"ok": True}
# --- TOTP ----------------------------------------------------------------
@router.get("/totp/status")
async def get_totp_status(
request: Request,
client: Optional[AuthClient] = Depends(get_client), # noqa: B008
) -> dict[str, bool]:
if not _enabled(client):
return {"enabled": False, "mfaEnabled": False}
assert client is not None
profile, _ = await _current_profile_or_401(request, client)
return {"enabled": bool(profile.totp_enabled), "mfaEnabled": bool(profile.totp_enabled)}
@router.post("/totp/initiate")
async def initiate_totp(
request: Request,
client: Optional[AuthClient] = Depends(get_client), # noqa: B008
) -> dict[str, Any]:
if not _enabled(client):
raise HTTPException(status_code=409, detail=ERR_FEATURE_REQUIRES_AUTHGUARD)
assert client is not None
profile, token = await _current_profile_or_401(request, client)
if profile.totp_enabled:
raise HTTPException(
status_code=409, detail="Two-factor authentication is already enabled."
)
try:
result = await client.totp_enable(token)
except AuthClientError as exc:
_raise_authguard_error(exc, "Could not create authenticator secret.")
raise # unreachable
return {
"data": {
"secret": result.secret,
"otpauth": result.otpauth_url,
"otpauthUrl": result.otpauth_url,
"enabled": result.enabled,
}
}
@router.post("/totp/verify")
async def verify_totp(
req: TotpTokenRequest,
request: Request,
client: Optional[AuthClient] = Depends(get_client), # noqa: B008
) -> dict[str, Any]:
if not _enabled(client):
raise HTTPException(status_code=409, detail=ERR_FEATURE_REQUIRES_AUTHGUARD)
assert client is not None
_, token = await _current_profile_or_401(request, client)
code = req.totpToken or req.token
try:
await client.totp_verify(token, code)
except Exception as exc:
raise HTTPException(status_code=401, detail="Invalid authenticator code.") from exc
return {"data": {"mfaEnabled": True, "enabled": True, "backupCodes": []}}
@router.post("/totp/disable")
async def disable_totp(
req: TotpTokenRequest,
request: Request,
client: Optional[AuthClient] = Depends(get_client), # noqa: B008
) -> dict[str, Any]:
if not _enabled(client):
raise HTTPException(status_code=409, detail=ERR_FEATURE_REQUIRES_AUTHGUARD)
assert client is not None
_, token = await _current_profile_or_401(request, client)
code = req.totpToken or req.token
try:
await client.totp_disable(token, code)
except Exception as exc:
raise HTTPException(status_code=401, detail="Invalid authenticator code.") from exc
return {"data": {"mfaEnabled": False, "enabled": False}}
# Expose the session dependency for the project's own non-auth routes to
# reuse (mirrors Go's Service.Require/RequireAdmin being usable as
# middleware on any route, not just this router's own).
router.require_session = require_session # ty: ignore[unresolved-attribute]
return router
@@ -43,7 +43,5 @@ class DatabaseConfig:
min_size=min_size,
max_size=max_size,
timeout=float(_int_value(source, "DATABASE_CONNECT_TIMEOUT_SECONDS", 5, 1)),
command_timeout=float(
_int_value(source, "DATABASE_COMMAND_TIMEOUT_SECONDS", 15, 1)
),
command_timeout=float(_int_value(source, "DATABASE_COMMAND_TIMEOUT_SECONDS", 15, 1)),
)
@@ -0,0 +1,139 @@
"""Lets any Python service in this workspace receive AuthGuard's and
CarrierNode's current base URL(s) pushed from ProjectConfigurator, instead of
hardcoding them in its own env vars. Mirrors shared/backend/coreconfig (Go)
exactly -- same Info shape, same Store semantics -- translated to Python
idioms; keep both in sync if either changes shape. See
ProjectConfigurator/README.md's "Pushing core service info to other
projects" section for the wire contract this module implements the
receiving end of.
Framework-agnostic, like the rest of this package (see the top-level
README's "HTTP framework adapters stay in each service" note): this module
has no HTTP server of its own. A service wires the actual
PUT /api/core-services/internal route in its own framework (FastAPI,
aiohttp, ...), gated behind its own SECRET check the same
way its other internal-service routes already are, decodes the JSON body
into an `Info`, and calls `Store.set(info)` -- see `Store.set`'s doc comment
for a minimal FastAPI example.
"""
from __future__ import annotations
import threading
from dataclasses import dataclass, field
from typing import Callable, Optional
@dataclass
class Info:
"""AuthGuard's and CarrierNode's current base URL(s), as pushed by
ProjectConfigurator. Field names match the JSON wire shape
(coreServiceInfo in ProjectConfigurator/backend/cmd/projectconfigurator/settings.go
and coreconfig.Info in shared/backend/coreconfig) exactly."""
auth_guard_url: str = ""
# carrier_node_url is the primary CarrierNode instance's URL
# (carrier_node_urls[0], if any) -- kept for a service that only ever
# talks to one CarrierNode instance.
carrier_node_url: str = ""
# carrier_node_urls is every CarrierNode instance ProjectConfigurator has
# registered, in priority order (the first entry is the same as
# carrier_node_url).
carrier_node_urls: list = field(default_factory=list)
@classmethod
def from_json(cls, data: dict) -> "Info":
urls = [str(u).strip() for u in (data.get("carrierNodeUrls") or []) if str(u).strip()]
if not urls:
single = str(data.get("carrierNodeUrl") or "").strip()
if single:
urls = [single]
return cls(
auth_guard_url=str(data.get("authGuardUrl") or "").strip(),
carrier_node_url=urls[0] if urls else "",
carrier_node_urls=urls,
)
def to_json(self) -> dict:
return {
"authGuardUrl": self.auth_guard_url,
"carrierNodeUrl": self.carrier_node_url,
"carrierNodeUrls": list(self.carrier_node_urls),
}
class Store:
"""Holds the most recently pushed Info, defaulting to whatever fallback
__init__ was given (typically this service's own AUTHGUARD_URL/
CARRIERNODE_URL env vars, or "" now that they're optional) until
ProjectConfigurator's first push arrives -- or forever, if this
deployment isn't registered with a ProjectConfigurator instance at all,
in which case those env vars (if set) keep working exactly as before."""
def __init__(self, fallback: Optional[Info] = None) -> None:
self._lock = threading.Lock()
self._info = _normalize(fallback or Info())
self._on_update: Optional[Callable[[Info], None]] = None
def get(self) -> Info:
with self._lock:
return self._info
@property
def auth_guard_url(self) -> str:
return self.get().auth_guard_url
@property
def carrier_node_url(self) -> str:
return self.get().carrier_node_url
@property
def carrier_node_urls(self) -> list:
return self.get().carrier_node_urls
def on_update(self, fn: Callable[[Info], None]) -> None:
"""Registers fn to be called (synchronously, so keep it fast) with
the new Info after every set() -- e.g. an AuthClient's set_base_url
for a client that isn't already reading through Store on every call.
Only one callback is kept; a second registration replaces the
first."""
with self._lock:
self._on_update = fn
def set(self, next_info: Info) -> Info:
"""Replaces the current Info, field by field, ignoring a
blank/empty field so a partial push (e.g. only carrierNodeUrl(s)
changed) never clobbers the other value. Returns the resulting
Info. Minimal FastAPI usage:
@app.put("/api/core-services/internal")
async def push_core_services(request: Request):
if request.headers.get("X-Internal-Auth") != SECRET:
raise HTTPException(status_code=401)
body = await request.json()
info = core_config_store.set(Info.from_json(body))
return {"ok": True, "info": info.to_json()}
"""
next_info = _normalize(next_info)
with self._lock:
if next_info.auth_guard_url:
self._info.auth_guard_url = next_info.auth_guard_url
if next_info.carrier_node_urls:
self._info.carrier_node_urls = next_info.carrier_node_urls
self._info.carrier_node_url = next_info.carrier_node_urls[0]
current = self._info
callback = self._on_update
if callback is not None:
callback(current)
return current
def _normalize(info: Info) -> Info:
cleaned = [str(u).strip() for u in (info.carrier_node_urls or []) if str(u).strip()]
if not cleaned and info.carrier_node_url.strip():
cleaned = [info.carrier_node_url.strip()]
return Info(
auth_guard_url=info.auth_guard_url.strip(),
carrier_node_url=cleaned[0] if cleaned else "",
carrier_node_urls=cleaned,
)
@@ -2,13 +2,75 @@
from __future__ import annotations
import asyncio
import logging
import os
from contextlib import asynccontextmanager
from typing import Any, AsyncIterator, Awaitable, Callable
from dataclasses import dataclass
from typing import Any, AsyncIterator, Awaitable, Callable, Mapping
import asyncpg
from .config import DatabaseConfig
_logger = logging.getLogger(__name__)
@dataclass(frozen=True, slots=True)
class StartupRetryOptions:
"""Common startup retry policy used by database-backed services."""
interval_seconds: float = 5.0
max_attempts: int = 0
def startup_retry_options_from_env(env: Mapping[str, str] | None = None) -> StartupRetryOptions:
"""Load the common startup retry policy from environment variables."""
source = os.environ if env is None else env
try:
interval_ms = int(source.get("DB_INIT_RETRY_INTERVAL_MS", "5000"))
except (TypeError, ValueError):
interval_ms = 5000
interval_ms = max(250, interval_ms)
try:
max_attempts = int(source.get("DB_INIT_RETRY_MAX_ATTEMPTS", "0"))
except (TypeError, ValueError):
max_attempts = 0
max_attempts = max(0, max_attempts)
return StartupRetryOptions(
interval_seconds=interval_ms / 1000,
max_attempts=max_attempts,
)
async def retry_startup(
operation: Callable[[], Awaitable[Any]],
options: StartupRetryOptions | None = None,
) -> Any:
"""Retry a startup operation until it succeeds or the context is cancelled."""
policy = options or startup_retry_options_from_env()
attempt = 0
while True:
attempt += 1
try:
return await operation()
except asyncio.CancelledError:
raise
except Exception as exc:
if policy.max_attempts and attempt >= policy.max_attempts:
raise
_logger.warning(
"database startup attempt %d failed: %s; retrying in %.3fs",
attempt,
exc,
policy.interval_seconds,
)
await asyncio.sleep(policy.interval_seconds)
class Database:
"""Own one asyncpg pool and expose common lifecycle/query operations."""
@@ -19,6 +81,8 @@ class Database:
@classmethod
async def connect(cls, config: DatabaseConfig | str) -> "Database":
settings = config if isinstance(config, DatabaseConfig) else DatabaseConfig(dsn=config)
async def connect_once() -> "Database":
pool = await asyncpg.create_pool(
dsn=settings.dsn,
min_size=settings.min_size,
@@ -33,6 +97,8 @@ class Database:
raise
return cls(pool)
return await retry_startup(connect_once)
async def ping(self) -> None:
await self.pool.fetchval("SELECT 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()
@@ -0,0 +1,261 @@
import unittest
from fastapi import FastAPI, Request
from fastapi.testclient import TestClient
from shared_backend import authproxy as ap
from shared_backend.authclient import APIError, AuthClient, PublicUser, SessionResult
class _FakeStore(ap.ProxyStore):
"""In-memory ProxyStore covering both flags build_auth_router needs."""
def __init__(self, *, claimed: bool = False, login_required: bool = True) -> None:
self.claimed = claimed
self._login_required = login_required
async def login_required(self) -> bool:
return self._login_required
async def set_login_required(self, required: bool) -> None:
self._login_required = required
async def is_setup_claimed(self) -> bool:
return self.claimed
async def try_claim_setup(self) -> bool:
if self.claimed:
return False
self.claimed = True
return True
async def unclaim_setup(self) -> None:
self.claimed = False
def _build_app(
store: ap.ProxyStore,
client: AuthClient | None = None,
*,
internal_secret: str | None = None,
) -> FastAPI:
def get_client(request: Request) -> AuthClient | None:
return client
def get_store(request: Request) -> ap.ProxyStore:
return store
app = FastAPI()
app.include_router(
ap.build_auth_router(get_client, get_store, internal_secret=internal_secret),
prefix="/api/auth",
)
return app
class AuthDisabledModeTests(unittest.TestCase):
"""client=None (AUTHGUARD_URL unset) - every route reports the fixed
placeholder superadmin identity and nothing is gated. This is also a
regression test for a real bug this module had: request/response models
declared *inside* build_auth_router, combined with `from __future__
import annotations`, made FastAPI silently misparse every JSON body as a
missing query parameter (all these POST/PUT calls would 422 on that
bug)."""
def setUp(self) -> None:
self.client = TestClient(_build_app(_FakeStore()))
def test_status_reports_local_superadmin(self) -> None:
response = self.client.get("/api/auth/status")
self.assertEqual(response.status_code, 200)
body = response.json()
self.assertTrue(body["authenticated"])
self.assertFalse(body["setupRequired"])
self.assertEqual(body["user"]["role"], "superadmin")
self.assertTrue(body["user"]["canManageUsers"])
def test_me_reports_local_superadmin(self) -> None:
body = self.client.get("/api/auth/me").json()
self.assertEqual(body["user"]["username"], "Admin")
def test_setup_succeeds_as_a_no_op(self) -> None:
response = self.client.post(
"/api/auth/setup",
json={"username": "a", "email": "a@b.com", "password": "password123"},
)
self.assertEqual(response.status_code, 201)
self.assertEqual(response.json()["user"]["role"], "superadmin")
def test_login_succeeds_as_a_no_op(self) -> None:
response = self.client.post(
"/api/auth/login", json={"identifier": "anyone", "password": "whatever"}
)
self.assertEqual(response.status_code, 200)
def test_logout_always_ok(self) -> None:
self.assertEqual(self.client.post("/api/auth/logout").json(), {"ok": True})
def test_list_users_returns_empty_list_not_an_error(self) -> None:
self.assertEqual(self.client.get("/api/auth/users").json(), [])
def test_mutating_admin_routes_require_authguard(self) -> None:
response = self.client.post(
"/api/auth/users",
json={"username": "b", "email": "b@c.com", "password": "password123"},
)
self.assertEqual(response.status_code, 409)
def test_totp_initiate_requires_authguard(self) -> None:
self.assertEqual(self.client.post("/api/auth/totp/initiate").status_code, 409)
def test_update_me_requires_authguard(self) -> None:
self.assertEqual(self.client.put("/api/auth/me", json={}).status_code, 409)
class AccessSettingsTests(unittest.TestCase):
def test_get_and_put_round_trip_through_the_store(self) -> None:
store = _FakeStore(login_required=True)
client = TestClient(_build_app(store))
self.assertEqual(client.get("/api/auth/access").json(), {"loginRequired": True})
response = client.put("/api/auth/access", json={"loginRequired": False})
self.assertEqual(response.json(), {"loginRequired": False})
self.assertEqual(client.get("/api/auth/access").json(), {"loginRequired": False})
def test_internal_update_disables_login_and_uses_admin_identity(self) -> None:
store = _FakeStore(login_required=True)
client = TestClient(
_build_app(store, _FakeClient(setup_required=False), internal_secret="secret")
)
response = client.put(
"/api/auth/access/internal",
headers={"X-Internal-Auth": "secret"},
json={"loginRequired": False},
)
self.assertEqual(response.status_code, 200)
self.assertEqual(response.json(), {"loginRequired": False})
body = client.get("/api/auth/me").json()
self.assertFalse(body["authRequired"])
self.assertEqual(body["user"]["username"], "Admin")
class _FakeClient(AuthClient):
"""Overrides just the methods build_auth_router calls, bypassing real
HTTP entirely - AuthClient.__init__ never needs a reachable base_url for
these tests since nothing here calls the real _call/_validate_sync."""
def __init__(self, *, setup_required: bool = True) -> None:
super().__init__("http://authguard.test")
self.setup_required = setup_required
self.registered: list[tuple[str, str, str]] = []
self.logged_out: list[str] = []
async def setup_status(self) -> bool:
return self.setup_required
async def register(self, username: str, email: str, password: str) -> SessionResult:
self.registered.append((username, email, password))
self.setup_required = False
return SessionResult(
user=PublicUser(id=1, username=username, email=email, role="superadmin"),
cookies=["auth_session=tok1; Path=/"],
)
async def login(self, username_or_email: str, password: str, totp_token: str = ""):
if password == "wrong":
raise APIError(401, "invalid credentials")
return SessionResult(
user=PublicUser(id=1, username=username_or_email, email="a@b.com", role="user"),
cookies=["auth_session=tok1; Path=/"],
)
async def me(self, token: str) -> PublicUser:
if not token:
raise APIError(401, "unauthenticated")
return PublicUser(id=1, username="a", email="a@b.com", role="user")
async def logout(self, token: str) -> list[str]:
self.logged_out.append(token)
return ["auth_session=; Path=/; Max-Age=0"]
class EnabledModeSetupAndLoginTests(unittest.TestCase):
"""Exercises the real (client is not None) path, including the
setup-claim flag's interaction with the store."""
def test_setup_claims_the_flag_and_registers_against_authguard(self) -> None:
store = _FakeStore(claimed=False)
fake_client = _FakeClient(setup_required=True)
client = TestClient(_build_app(store, fake_client))
response = client.post(
"/api/auth/setup",
json={"username": "admin", "email": "admin@example.com", "password": "password123"},
)
self.assertEqual(response.status_code, 201)
self.assertTrue(store.claimed)
self.assertEqual(fake_client.registered, [("admin", "admin@example.com", "password123")])
self.assertIn("set-cookie", response.headers)
def test_setup_refuses_a_second_claim(self) -> None:
store = _FakeStore(claimed=True)
client = TestClient(_build_app(store, _FakeClient()))
response = client.post(
"/api/auth/setup",
json={"username": "admin", "email": "admin@example.com", "password": "password123"},
)
self.assertEqual(response.status_code, 409)
def test_setup_unclaims_when_authguard_already_has_an_account(self) -> None:
# claimed=False locally, but AuthGuard itself reports no setup is
# needed (e.g. another project already created the first account) -
# the local claim slot must be released again, not left stuck.
store = _FakeStore(claimed=False)
client = TestClient(_build_app(store, _FakeClient(setup_required=False)))
response = client.post(
"/api/auth/setup",
json={"username": "admin", "email": "admin@example.com", "password": "password123"},
)
self.assertEqual(response.status_code, 409)
self.assertFalse(store.claimed)
def test_login_success_forwards_cookies(self) -> None:
client = TestClient(_build_app(_FakeStore(), _FakeClient()))
response = client.post(
"/api/auth/login", json={"identifier": "a@b.com", "password": "correct"}
)
self.assertEqual(response.status_code, 200)
self.assertEqual(response.json()["user"]["username"], "a@b.com")
def test_login_invalid_credentials_surfaces_401(self) -> None:
client = TestClient(_build_app(_FakeStore(), _FakeClient()))
response = client.post(
"/api/auth/login", json={"identifier": "a@b.com", "password": "wrong"}
)
self.assertEqual(response.status_code, 401)
def test_me_without_session_cookie_reports_no_user(self) -> None:
client = TestClient(_build_app(_FakeStore(), _FakeClient()))
body = client.get("/api/auth/me").json()
self.assertIsNone(body["user"])
class RequestValidationTests(unittest.TestCase):
"""Every JSON-body route must actually parse its body (see the docstring
on AuthDisabledModeTests for the regression this guards against)."""
def setUp(self) -> None:
self.client = TestClient(_build_app(_FakeStore()))
def test_setup_rejects_missing_fields_with_422_not_500(self) -> None:
response = self.client.post("/api/auth/setup", json={})
self.assertEqual(response.status_code, 422)
def test_login_rejects_missing_password_with_422_not_500(self) -> None:
response = self.client.post("/api/auth/login", json={"identifier": "a"})
self.assertEqual(response.status_code, 422)
if __name__ == "__main__":
unittest.main()
@@ -0,0 +1,66 @@
import unittest
from shared_backend.coreconfig import Info, Store
class StoreDefaultsTests(unittest.TestCase):
def test_seeds_from_fallback(self):
store = Store(
Info(
auth_guard_url="http://auth.example.com",
carrier_node_url="http://carrier.example.com",
)
)
info = store.get()
self.assertEqual(info.auth_guard_url, "http://auth.example.com")
self.assertEqual(info.carrier_node_url, "http://carrier.example.com")
self.assertEqual(info.carrier_node_urls, ["http://carrier.example.com"])
def test_defaults_to_empty(self):
store = Store()
info = store.get()
self.assertEqual(info.auth_guard_url, "")
self.assertEqual(info.carrier_node_urls, [])
class StoreSetTests(unittest.TestCase):
def test_partial_push_does_not_clobber_other_field(self):
store = Store(
Info(
auth_guard_url="http://auth.example.com",
carrier_node_url="http://carrier.example.com",
)
)
store.set(Info(carrier_node_url="http://carrier2.example.com"))
info = store.get()
self.assertEqual(info.auth_guard_url, "http://auth.example.com")
self.assertEqual(info.carrier_node_url, "http://carrier2.example.com")
def test_blank_auth_guard_url_ignored(self):
store = Store(Info(auth_guard_url="http://auth.example.com"))
store.set(Info(auth_guard_url=""))
self.assertEqual(store.auth_guard_url, "http://auth.example.com")
def test_on_update_called_with_resulting_info(self):
store = Store()
seen = []
store.on_update(seen.append)
store.set(Info(auth_guard_url="http://auth.example.com"))
self.assertEqual(len(seen), 1)
self.assertEqual(seen[0].auth_guard_url, "http://auth.example.com")
def test_from_json_round_trip(self):
payload = {
"authGuardUrl": "http://auth.example.com",
"carrierNodeUrl": "http://carrier.example.com",
"carrierNodeUrls": ["http://carrier.example.com", "http://carrier2.example.com"],
}
info = Info.from_json(payload)
self.assertEqual(
info.carrier_node_urls, ["http://carrier.example.com", "http://carrier2.example.com"]
)
self.assertEqual(info.to_json()["carrierNodeUrl"], "http://carrier.example.com")
if __name__ == "__main__":
unittest.main()
+3 -2
View File
@@ -1,6 +1,6 @@
{
"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.",
"license": "MIT",
"type": "module",
@@ -15,7 +15,8 @@
"svelte": "^5.0.0"
},
"dependencies": {
"@gabriel20xx/design-tokens": "0.1.0"
"@gabriel20xx/design-tokens": "0.1.1",
"@lucide/svelte": "1.28.0"
},
"devDependencies": {
"@sveltejs/package": "^2.5.0",
@@ -7,22 +7,37 @@
brand = 'Application',
children,
description = '',
icon,
links = [],
onClose,
open = $bindable(false),
version = ''
}: {
brand?: string;
children?: Snippet;
description?: string;
icon?: Snippet;
links?: AboutLink[];
onClose?: () => void | Promise<void>;
open?: boolean;
version?: string;
} = $props();
let wasOpen = false;
$effect(() => {
if (wasOpen && !open) void onClose?.();
wasOpen = open;
});
</script>
<Dialog bind:open title={`About ${brand}`}>
<div class="sc-auth-brand">
{#if icon}
{@render icon()}
{:else}
<span aria-hidden="true" class="sc-brand-mark">{brand.slice(0, 1).toUpperCase()}</span>
{/if}
<strong>{brand}</strong>
</div>
@@ -1,31 +1,40 @@
<script lang="ts">
import { onMount } from 'svelte';
import type { Snippet } from 'svelte';
import type { NavItem } from '../types';
import Header from './Header.svelte';
import NotificationStack from './NotificationStack.svelte';
import { initPrimaryColor, setPrimaryColorUser } from '../primary-color.svelte';
let {
aboutHref,
brand = 'Application',
brandHref = '/',
children,
class: className = '',
currentPath = '',
faviconHref = '/favicon.svg',
headerActions,
navItems = [],
onAbout,
onLogout,
onNavigate,
onProfile,
onSettings,
showSettings = true,
theme = 'dark',
username = ''
username = '',
}: {
aboutHref?: string;
brand?: string;
brandHref?: string;
children?: Snippet;
class?: string;
currentPath?: string;
faviconHref?: string;
headerActions?: Snippet;
navItems?: NavItem[];
onAbout?: () => void | Promise<void>;
onLogout?: () => void | Promise<void>;
onNavigate?: (item: NavItem) => void;
onProfile?: () => void;
@@ -34,15 +43,26 @@
theme?: 'dark' | 'light' | 'system';
username?: string;
} = $props();
$effect(() => {
setPrimaryColorUser(username);
});
onMount(() => initPrimaryColor(brand, username));
</script>
<div class={`sc-root sc-app-shell ${className}`} data-theme={theme === 'system' ? undefined : theme}>
<NotificationStack />
<Header
aboutHref={aboutHref ?? navItems.find((item) => item.label.toLowerCase() === 'about')?.href ?? '/about'}
{brand}
{brandHref}
{currentPath}
{faviconHref}
actions={headerActions}
{navItems}
{onAbout}
{onLogout}
{onNavigate}
{onProfile}
@@ -12,6 +12,7 @@
brand = 'Application',
children,
error = '',
faviconHref = '/favicon.svg',
loading = false,
onLogin,
onConfirmReset,
@@ -24,6 +25,7 @@
brand?: string;
children?: Snippet;
error?: string;
faviconHref?: string;
loading?: boolean;
onLogin?: (input: AuthLoginInput) => void | Promise<void>;
onConfirmReset?: AuthResetConfirm;
@@ -39,6 +41,7 @@
let identifier = $state('');
let password = $state('');
let totpToken = $state('');
let totpRequired = $state(false);
let confirmPassword = $state('');
let submitError = $state('');
let submitting = $state(false);
@@ -47,11 +50,27 @@
let resetOpen = $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> {
event.preventDefault();
submitError = '';
if (setupRequired && password !== confirmPassword) {
if (effectiveSetupRequired && password !== confirmPassword) {
submitError = 'Passwords do not match.';
return;
}
@@ -59,15 +78,28 @@
submitting = true;
try {
if (setupRequired) {
if (effectiveSetupRequired) {
if (!onSetup) throw new Error('The application has not configured its setup handler.');
await onSetup({ username, email, password });
} else {
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() });
}
} catch (caught) {
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 {
submitting = false;
}
@@ -107,19 +139,24 @@
</script>
<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">
<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>
</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}
<p class="sc-auth-subtitle">{tagline}</p>
{/if}
<form class="sc-form sc-auth-form" onsubmit={submit}>
{#if setupRequired}
{#if effectiveSetupRequired}
<label class="sc-field">
<span class="sc-label">Username</span>
<input
@@ -160,19 +197,18 @@
<label class="sc-field">
<span class="sc-label">Password</span>
<input
autocomplete={setupRequired ? 'new-password' : 'current-password'}
autocomplete={effectiveSetupRequired ? 'new-password' : 'current-password'}
class="sc-input"
minlength="8"
name="password"
required
type="password"
bind:value={password}
/>
</label>
{#if showTotp && !setupRequired}
{#if showTotp && !effectiveSetupRequired && totpRequired}
<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
autocomplete="one-time-code"
class="sc-input"
@@ -184,7 +220,7 @@
</label>
{/if}
{#if setupRequired}
{#if effectiveSetupRequired}
<label class="sc-field">
<span class="sc-label">Confirm password</span>
<input
@@ -192,7 +228,6 @@
class="sc-input"
minlength="8"
name="confirmPassword"
required
type="password"
bind:value={confirmPassword}
/>
@@ -204,7 +239,7 @@
{/if}
<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>
</form>
@@ -212,7 +247,7 @@
<div class="sc-auth-extra">{@render children()}</div>
{/if}
{#if !setupRequired && onRequestReset && onConfirmReset}
{#if !effectiveSetupRequired && onRequestReset && onConfirmReset}
{#if resetOpen}
<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>
@@ -241,5 +276,6 @@
</button>
{/if}
{/if}
{/if}
</section>
</div>
@@ -1,19 +1,21 @@
<script lang="ts">
import type { HTMLAttributes } from 'svelte/elements';
import type { Snippet } from 'svelte';
type BadgeVariant = 'default' | 'success' | 'warning' | 'danger';
type BadgeVariant = 'default' | 'primary' | 'success' | 'warning' | 'danger';
let {
children,
class: className = '',
variant = 'default'
}: {
variant = 'default',
...rest
}: Omit<HTMLAttributes<HTMLSpanElement>, 'class'> & {
children?: Snippet;
class?: string;
variant?: BadgeVariant;
} = $props();
</script>
<span class={`sc-badge ${className}`} data-variant={variant}>
<span class={`sc-badge ${className}`} data-variant={variant} {...rest}>
{@render children?.()}
</span>
@@ -1,8 +1,9 @@
<script lang="ts">
import type { HTMLButtonAttributes } from 'svelte/elements';
import type { Snippet } from 'svelte';
type ButtonVariant = 'primary' | 'secondary' | 'ghost' | 'danger';
type ButtonSize = 'sm' | 'md' | 'lg';
type ButtonVariant = 'primary' | 'secondary' | 'outline' | 'ghost' | 'danger';
type ButtonSize = 'sm' | 'md' | 'lg' | 'icon';
let {
children,
@@ -12,8 +13,9 @@
onclick,
size = 'md',
type = 'button',
variant = 'primary'
}: {
variant = 'primary',
...rest
}: Omit<HTMLButtonAttributes, 'class' | 'disabled' | 'onclick' | 'type'> & {
children?: Snippet;
class?: string;
disabled?: boolean;
@@ -30,6 +32,7 @@
{disabled}
{onclick}
{type}
{...rest}
>
{@render children?.()}
</button>
@@ -0,0 +1,13 @@
<script lang="ts">
import { Inbox } from '@lucide/svelte';
let { title, message }: { title: string; message: string } = $props();
</script>
<div class="sc-empty-state">
<Inbox aria-hidden="true" class="sc-empty-state-icon" size={32} />
<div>
<p class="sc-empty-state-title">{title}</p>
<p class="sc-empty-state-message">{message}</p>
</div>
</div>
+204 -11
View File
@@ -1,34 +1,153 @@
<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 { 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 {
aboutHref = '/about',
brand = 'Application',
brandHref = '/',
currentPath = '',
faviconHref = '/favicon.svg',
navItems = [],
actions,
onAbout,
onLogout,
onNavigate,
onProfile,
onSettings,
showSettings = true,
username = ''
username = '',
}: {
aboutHref?: string;
brand?: string;
brandHref?: string;
currentPath?: string;
faviconHref?: string;
navItems?: NavItem[];
actions?: Snippet;
onAbout?: () => void | Promise<void>;
onLogout?: () => void | Promise<void>;
onNavigate?: (item: NavItem) => void;
onProfile?: () => void;
onSettings?: () => void;
onProfile?: () => void | Promise<void>;
onSettings?: () => void | Promise<void>;
showSettings?: boolean;
username?: string;
} = $props();
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 {
return item.href === '/'
@@ -37,14 +156,17 @@
}
</script>
<svelte:window onclick={handleWindowClick} onkeydown={handleWindowKeydown} />
<header class="sc-header">
<a class="sc-brand" href={brandHref} onclick={() => (navOpen = false)}>
<span aria-hidden="true" class="sc-brand-mark">{brand.slice(0, 1).toUpperCase()}</span>
<a class="sc-brand" href={brandHref} onclick={closeMenus}>
<img alt="" class="sc-brand-icon" src={faviconHref} />
<span>{brand}</span>
</a>
<nav aria-label="Primary navigation" class="sc-nav" data-open={navOpen}>
{#each navItems as item}
{@const Icon = iconFor(item)}
<a
aria-current={isActive(item) ? 'page' : undefined}
class="sc-nav-link"
@@ -55,9 +177,10 @@
event.preventDefault();
onNavigate(item);
}
navOpen = false;
closeMenus();
}}
>
<Icon aria-hidden="true" class="sc-nav-icon" size={16} strokeWidth={2} />
{item.label}
</a>
{/each}
@@ -66,19 +189,89 @@
<div class="sc-header-actions">
{#if actions}{@render actions()}{/if}
{#if showSettings && onSettings}
<button aria-label="Open settings" class="sc-icon-button" type="button" onclick={onSettings}>⚙</button>
{#if hasProfileMenu}
<div class="sc-profile-menu" data-profile-menu>
<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 profileOpen}
<div aria-label="Account menu" class="sc-profile-dropdown" role="menu">
{#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 username && onProfile}
<button class="sc-profile-button" type="button" onclick={onProfile}>{username}</button>
{#if showSettings && onSettings}
<button
class="sc-profile-menu-item"
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-button sc-button-ghost sc-button-sm" type="button" onclick={() => void 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}
<button
aria-expanded={navOpen}
@@ -0,0 +1,465 @@
<script lang="ts">
import { Music2 } from '@lucide/svelte'
import { onMount } from 'svelte'
import type { Snippet } from 'svelte'
import MediaPlayerControls, {
type MediaPlayerKind,
type MediaPlayerQualityOption,
} from './MediaPlayerControls.svelte'
let {
kind = 'video',
src = '',
poster = '',
title = '',
autoplay = false,
class: className = '',
mediaClass = '',
showSeekButtons: _showSeekButtons = true,
showVolume = true,
showFullscreen = true,
showGraph = false,
graphVisible = false,
qualityOptions = [],
selectedQuality = '',
currentTime: externalCurrentTime = null,
duration: externalDuration = null,
onError,
onPlay,
onPause,
onTimeUpdate,
onLoadedMetadata,
onEnded,
onSeek,
onSkip,
onQualityChange,
onToggleGraph,
endControls,
}: {
kind?: MediaPlayerKind
src?: string
poster?: string
title?: string
autoplay?: boolean
class?: string
mediaClass?: string
/** @deprecated Seeking is available with the arrow keys and mobile double-tap. */
showSeekButtons?: boolean
showVolume?: boolean
showFullscreen?: boolean
showGraph?: boolean
graphVisible?: boolean
qualityOptions?: MediaPlayerQualityOption[]
selectedQuality?: string
currentTime?: number | null
duration?: number | null
onError?: () => void
onPlay?: (event: Event) => void
onPause?: (event: Event) => void
onTimeUpdate?: (event: Event) => void
onLoadedMetadata?: (event: Event) => void
onEnded?: (event: Event) => void
onSeek?: (value: number) => void
onSkip?: (seconds: number) => void
onQualityChange?: (value: string) => void
onToggleGraph?: () => void
endControls?: Snippet
} = $props()
let playerFrame = $state<HTMLDivElement | null>(null)
let mediaElement = $state<HTMLMediaElement | null>(null)
let internalTime = $state(0)
let internalDuration = $state(0)
let playing = $state(false)
let volume = $state(1)
let muted = $state(false)
let fullscreen = $state(false)
let controlsVisible = $state(true)
let orientationLocked = $state(false)
let controlsHideTimeout: ReturnType<typeof setTimeout> | null = null
let orientationLockRequest = 0
const currentTime = $derived(externalCurrentTime ?? internalTime)
const duration = $derived(externalDuration ?? internalDuration)
const audio = $derived(kind === 'audio')
const controlsHideDelay = 2500
function clearControlsHideTimer() {
if (controlsHideTimeout === null) return
clearTimeout(controlsHideTimeout)
controlsHideTimeout = null
}
function scheduleControlsHide() {
clearControlsHideTimer()
if (audio || !playing) return
controlsHideTimeout = setTimeout(() => {
controlsVisible = false
controlsHideTimeout = null
}, controlsHideDelay)
}
function handlePlayerActivity() {
if (audio) return
controlsVisible = true
scheduleControlsHide()
}
function togglePlayback() {
if (!mediaElement) return
if (mediaElement.paused) void mediaElement.play().catch(() => undefined)
else mediaElement.pause()
}
function handleSurfaceClick() {
togglePlayback()
}
function handleKeydown(event: KeyboardEvent) {
const target = event.target as HTMLElement | null
if (target?.closest('button, input, select, textarea, a')) return
const key = event.key.toLowerCase()
if (key === ' ' || key === 'k') {
event.preventDefault()
togglePlayback()
} else if (key === 'arrowleft') {
event.preventDefault()
skip(-10)
} else if (key === 'arrowright') {
event.preventDefault()
skip(10)
} else if (key === 'm') {
event.preventDefault()
toggleMute()
} else if (key === 'f') {
event.preventDefault()
void toggleFullscreen()
}
}
function isMobileDevice() {
return (
typeof window !== 'undefined' &&
(window.matchMedia?.('(pointer: coarse)').matches === true || navigator.maxTouchPoints > 0)
)
}
function isWideVideo() {
return Boolean(
mediaElement &&
!audio &&
mediaElement instanceof HTMLVideoElement &&
mediaElement.videoWidth > mediaElement.videoHeight,
)
}
async function syncScreenOrientation(nextFullscreen: boolean) {
const request = ++orientationLockRequest
const orientation =
typeof window !== 'undefined'
? (window.screen?.orientation as
| (ScreenOrientation & {
lock: (orientation: 'landscape') => Promise<void>
})
| undefined)
: undefined
const shouldLock = nextFullscreen && isMobileDevice() && isWideVideo()
if (!shouldLock) {
if (orientationLocked) orientation?.unlock()
orientationLocked = false
return
}
if (!orientation?.lock) return
try {
await orientation.lock('landscape')
if (request !== orientationLockRequest) {
orientation.unlock()
return
}
orientationLocked = true
} catch {
// Orientation locking is not available in every mobile browser.
}
}
function handleVideoDoubleTap(event: MouseEvent) {
if (audio || !isMobileDevice()) return
const target = event.currentTarget as HTMLVideoElement
const bounds = target.getBoundingClientRect()
skip(event.clientX - bounds.left < bounds.width / 2 ? -10 : 10)
}
function handlePlay(event: Event) {
playing = true
onPlay?.(event)
}
function handlePause(event: Event) {
playing = false
controlsVisible = true
onPause?.(event)
}
function handleTimeUpdate(event: Event) {
if (mediaElement) internalTime = mediaElement.currentTime || 0
onTimeUpdate?.(event)
}
function handleLoadedMetadata(event: Event) {
if (!mediaElement) return
internalDuration = Number.isFinite(mediaElement.duration) ? mediaElement.duration : 0
volume = mediaElement.volume
muted = mediaElement.muted || mediaElement.volume === 0
void syncScreenOrientation(fullscreen)
onLoadedMetadata?.(event)
}
function handleEnded(event: Event) {
playing = false
controlsVisible = true
onEnded?.(event)
}
function handleError() {
onError?.()
}
function seek(value: number) {
if (!Number.isFinite(value)) return
if (onSeek) {
onSeek(value)
return
}
if (!mediaElement) return
const nextTime = Math.min(Math.max(0, value), duration > 0 ? duration : value)
mediaElement.currentTime = nextTime
internalTime = nextTime
}
function skip(seconds: number) {
if (onSkip) {
onSkip(seconds)
return
}
seek((mediaElement?.currentTime || currentTime) + seconds)
}
function toggleMute() {
if (!mediaElement) return
if (muted || mediaElement.muted) {
mediaElement.muted = false
muted = false
if (mediaElement.volume === 0) mediaElement.volume = volume || 1
volume = mediaElement.volume
return
}
volume = mediaElement.volume || volume || 1
mediaElement.muted = true
muted = true
}
function changeVolume(value: number) {
if (!mediaElement || !Number.isFinite(value)) return
volume = Math.min(1, Math.max(0, value))
mediaElement.volume = volume
mediaElement.muted = volume === 0
muted = volume === 0
}
function handleVolumeChange() {
if (!mediaElement) return
volume = mediaElement.volume
muted = mediaElement.muted || mediaElement.volume === 0
}
async function toggleFullscreen() {
if (document.fullscreenElement) {
await document.exitFullscreen().catch(() => undefined)
return
}
if (playerFrame) await playerFrame.requestFullscreen().catch(() => undefined)
}
function handleFullscreenChange() {
fullscreen = Boolean(document.fullscreenElement)
void syncScreenOrientation(fullscreen)
}
$effect(() => {
const nextSource = src
if (!mediaElement || !nextSource) return
mediaElement.load()
if (autoplay) void mediaElement.play().catch(() => undefined)
})
$effect(() => {
if (audio || !playing) {
clearControlsHideTimer()
controlsVisible = true
return
}
scheduleControlsHide()
return clearControlsHideTimer
})
onMount(() => {
if (!playerFrame) return
const activityEvents = ['mousemove', 'click', 'keydown', 'focusin', 'touchstart'] as const
for (const eventName of activityEvents) playerFrame.addEventListener(eventName, handlePlayerActivity)
return () => {
for (const eventName of activityEvents) playerFrame?.removeEventListener(eventName, handlePlayerActivity)
orientationLockRequest += 1
if (orientationLocked) {
window.screen?.orientation?.unlock()
orientationLocked = false
}
}
})
</script>
<svelte:window onfullscreenchange={handleFullscreenChange} />
<div bind:this={playerFrame} class={`media-player ${className}`}>
{#if audio}
<div
class="media-player-audio-surface"
role="button"
tabindex="0"
aria-label={title ? `Audio player for ${title}` : 'Audio player'}
onclick={handleSurfaceClick}
onkeydown={handleKeydown}
>
<Music2 class="media-player-audio-icon" />
{#if title}<span>{title}</span>{/if}
</div>
<audio
bind:this={mediaElement}
{src}
{autoplay}
preload="auto"
tabindex="-1"
aria-hidden="true"
onplay={handlePlay}
onpause={handlePause}
ontimeupdate={handleTimeUpdate}
onloadedmetadata={handleLoadedMetadata}
onended={handleEnded}
onvolumechange={handleVolumeChange}
onerror={handleError}
></audio>
{:else}
<!-- The empty caption track keeps the custom player accessible without requiring callers to
invent a caption URL for streams that do not provide captions. -->
<video
bind:this={mediaElement}
{src}
{poster}
{autoplay}
preload="auto"
playsinline
tabindex="0"
class={`media-player-video ${mediaClass}`}
aria-label={title ? `Video player for ${title}` : 'Video player'}
onclick={handleSurfaceClick}
ondblclick={handleVideoDoubleTap}
onkeydown={handleKeydown}
onplay={handlePlay}
onpause={handlePause}
ontimeupdate={handleTimeUpdate}
onloadedmetadata={handleLoadedMetadata}
onended={handleEnded}
onvolumechange={handleVolumeChange}
onerror={handleError}
>
<track kind="captions" srclang="en" label="Captions" src="data:text/vtt,WEBVTT%0A" />
</video>
{/if}
<MediaPlayerControls
{kind}
{currentTime}
{duration}
{playing}
{volume}
{muted}
{fullscreen}
{controlsVisible}
onTogglePlayback={togglePlayback}
onSeek={seek}
onToggleMute={toggleMute}
onVolumeChange={changeVolume}
onToggleFullscreen={toggleFullscreen}
{showVolume}
{showFullscreen}
{showGraph}
{graphVisible}
{qualityOptions}
{selectedQuality}
{onQualityChange}
{onToggleGraph}
{endControls}
overlay
/>
</div>
<style>
.media-player {
position: relative;
display: flex;
width: 100%;
min-width: 0;
aspect-ratio: 16 / 9;
overflow: hidden;
background: black;
color: white;
}
.media-player:fullscreen {
width: 100vw;
height: 100vh;
aspect-ratio: auto;
border-radius: 0;
}
.media-player-video {
width: 100%;
height: 100%;
object-fit: contain;
touch-action: manipulation;
}
.media-player-audio-surface {
display: flex;
width: 100%;
height: 100%;
flex-direction: column;
align-items: center;
justify-content: center;
gap: 1.5rem;
padding: 1.5rem;
cursor: pointer;
}
.media-player-audio-icon {
width: 4rem;
height: 4rem;
padding: 1rem;
border-radius: 9999px;
color: var(--sc-primary, #80b6f5);
background: color-mix(in srgb, var(--sc-primary, #80b6f5) 15%, transparent);
}
.media-player-audio-surface span {
max-width: 100%;
overflow: hidden;
color: rgb(255 255 255 / 0.75);
font-size: 0.875rem;
text-overflow: ellipsis;
white-space: nowrap;
}
</style>
@@ -0,0 +1,500 @@
<!--
Internal to MediaPlayer. Not exported from the package barrel; do not re-export.
-->
<script lang="ts">
import { Maximize2, Minimize2, Pause, Play, Settings, Volume2, VolumeX } from '@lucide/svelte'
import { onMount } from 'svelte'
import type { Snippet } from 'svelte'
export type MediaPlayerKind = 'audio' | 'video'
export interface MediaPlayerQualityOption {
value: string
label: string
}
let {
kind = 'video',
currentTime = 0,
duration = 0,
playing = false,
volume = 1,
muted = false,
fullscreen = false,
disabled = false,
overlay = false,
controlsVisible = true,
showSeekButtons: _showSeekButtons = true,
showVolume = true,
showFullscreen = true,
showGraph = false,
graphVisible = false,
qualityOptions = [],
selectedQuality = '',
onTogglePlayback,
onSeek,
onSkip: _onSkip,
onToggleMute,
onVolumeChange,
onToggleFullscreen,
onToggleGraph,
onQualityChange,
endControls,
}: {
kind?: MediaPlayerKind
currentTime?: number
duration?: number
playing?: boolean
volume?: number
muted?: boolean
fullscreen?: boolean
disabled?: boolean
overlay?: boolean
controlsVisible?: boolean
/** @deprecated Seeking is available with the arrow keys and mobile double-tap. */
showSeekButtons?: boolean
showVolume?: boolean
showFullscreen?: boolean
showGraph?: boolean
graphVisible?: boolean
qualityOptions?: MediaPlayerQualityOption[]
selectedQuality?: string
onTogglePlayback?: () => void
onSeek?: (value: number) => void
/** @deprecated Seeking is handled by the player surface. */
onSkip?: (seconds: number) => void
onToggleMute?: () => void
onVolumeChange?: (value: number) => void
onToggleFullscreen?: () => void | Promise<void>
onToggleGraph?: () => void
onQualityChange?: (value: string) => void
endControls?: Snippet
} = $props()
let settingsMenu = $state<HTMLDivElement | null>(null)
let settingsOpen = $state(false)
const progress = $derived(duration > 0 ? `${Math.min(100, Math.max(0, (currentTime / duration) * 100))}%` : '0%')
const displayVolume = $derived(muted ? 0 : Math.min(1, Math.max(0, volume)))
const label = $derived(kind === 'audio' ? 'audio' : 'video')
function formatTime(value: number) {
const seconds = Math.max(0, Math.floor(Number(value) || 0))
const hours = Math.floor(seconds / 3600)
const minutes = Math.floor((seconds % 3600) / 60)
const remainder = seconds % 60
if (hours > 0) return `${hours}:${String(minutes).padStart(2, '0')}:${String(remainder).padStart(2, '0')}`
return `${minutes}:${String(remainder).padStart(2, '0')}`
}
function handleSeek(event: Event) {
onSeek?.(Number((event.currentTarget as HTMLInputElement).value))
}
function handleVolume(event: Event) {
onVolumeChange?.(Number((event.currentTarget as HTMLInputElement).value))
}
function handleQuality(event: Event) {
onQualityChange?.((event.currentTarget as HTMLSelectElement).value)
settingsOpen = false
}
function handleDocumentPointerDown(event: PointerEvent) {
if (settingsOpen && !settingsMenu?.contains(event.target as Node)) settingsOpen = false
}
function handleDocumentKeydown(event: KeyboardEvent) {
if (event.key === 'Escape') settingsOpen = false
}
onMount(() => {
document.addEventListener('pointerdown', handleDocumentPointerDown)
document.addEventListener('keydown', handleDocumentKeydown)
return () => {
document.removeEventListener('pointerdown', handleDocumentPointerDown)
document.removeEventListener('keydown', handleDocumentKeydown)
}
})
</script>
<div
class:media-player-controls-overlay={overlay}
class:media-player-controls-fullscreen={fullscreen}
class:media-player-controls-hidden={!controlsVisible}
class="media-player-controls"
>
<input
class="media-player-progress"
style={`--media-player-progress: ${progress}`}
type="range"
min="0"
max={Math.max(duration, 0.1)}
step="0.1"
value={currentTime}
disabled={disabled || !duration}
aria-label={`Seek ${label}`}
aria-valuetext={`${formatTime(currentTime)} of ${formatTime(duration)}`}
oninput={handleSeek}
/>
<div class="media-player-control-row">
<button
type="button"
class="media-player-control"
aria-label={playing ? `Pause ${label}` : `Play ${label}`}
title={playing ? 'Pause (K or Space)' : 'Play (K or Space)'}
{disabled}
onclick={onTogglePlayback}
>
{#if playing}<Pause class="media-player-icon-large" />{:else}<Play class="media-player-icon-large" />{/if}
</button>
{#if showVolume}
<button
type="button"
class="media-player-control"
aria-label={muted ? `Unmute ${label}` : `Mute ${label}`}
title={muted ? 'Unmute (M)' : 'Mute (M)'}
{disabled}
onclick={onToggleMute}
>
{#if muted}<VolumeX class="media-player-icon" />{:else}<Volume2 class="media-player-icon" />{/if}
</button>
<input
class="media-player-volume"
style={`--media-player-volume: ${displayVolume * 100}%`}
type="range"
min="0"
max="1"
step="0.05"
value={displayVolume}
aria-label="Volume"
{disabled}
oninput={handleVolume}
/>
{/if}
<span class="media-player-time">{formatTime(currentTime)} / {formatTime(duration)}</span>
<div class="media-player-control-trailing">
{@render endControls?.()}
{#if showGraph || qualityOptions.length > 0}
<div bind:this={settingsMenu} class="media-player-settings">
<button
type="button"
class="media-player-control"
aria-label="Player settings"
aria-expanded={settingsOpen}
aria-haspopup="dialog"
title="Player settings"
{disabled}
onclick={() => (settingsOpen = !settingsOpen)}
>
<Settings class="media-player-icon" />
</button>
{#if settingsOpen}
<div class="media-player-settings-menu" role="dialog" aria-label="Player settings">
{#if showGraph}
<button
type="button"
class="media-player-settings-toggle"
role="switch"
aria-checked={graphVisible}
{disabled}
onclick={onToggleGraph}
>
<span>Funscript graph</span>
<span class="media-player-settings-status">{graphVisible ? 'On' : 'Off'}</span>
</button>
{/if}
{#if qualityOptions.length > 0}
<label class="media-player-settings-quality">
<span>Quality</span>
<select value={selectedQuality} aria-label="Video quality" {disabled} onchange={handleQuality}>
{#each qualityOptions as option (option.value)}
<option value={option.value}>{option.label}</option>
{/each}
</select>
</label>
{/if}
</div>
{/if}
</div>
{/if}
{#if showFullscreen}
<button
type="button"
class="media-player-control"
aria-label={fullscreen ? 'Exit fullscreen' : 'Enter fullscreen'}
title={fullscreen ? 'Exit fullscreen (F)' : 'Enter fullscreen (F)'}
{disabled}
onclick={() => void onToggleFullscreen?.()}
>
{#if fullscreen}<Minimize2 class="media-player-icon" />{:else}<Maximize2 class="media-player-icon" />{/if}
</button>
{/if}
</div>
</div>
</div>
<style>
.media-player-controls {
display: block;
width: 100%;
padding: 0.75rem 1rem 1rem;
color: white;
background: linear-gradient(to top, rgb(0 0 0 / 0.95), rgb(0 0 0 / 0.7) 55%, transparent);
}
.media-player-controls-overlay {
position: absolute;
right: 0;
bottom: 0;
left: 0;
z-index: 20;
padding-top: 3rem;
pointer-events: none;
transition: opacity 180ms ease;
}
.media-player-controls-hidden {
opacity: 0;
pointer-events: none;
}
.media-player-controls-hidden > * {
pointer-events: none;
}
.media-player-controls-overlay > * {
pointer-events: auto;
}
.media-player-progress,
.media-player-volume {
display: block;
appearance: none;
border-radius: 9999px;
background: transparent;
cursor: pointer;
}
.media-player-progress {
width: 100%;
height: 1.25rem;
padding: 0.45rem 0;
background: linear-gradient(
to right,
var(--sc-primary, #80b6f5) 0%,
var(--sc-primary, #80b6f5) var(--media-player-progress),
rgb(255 255 255 / 0.3) var(--media-player-progress),
rgb(255 255 255 / 0.3) 100%
);
background-clip: content-box;
}
.media-player-volume {
width: 5.5rem;
height: 1.25rem;
padding: 0.45rem 0;
background: linear-gradient(
to right,
rgb(255 255 255 / 0.85) 0%,
rgb(255 255 255 / 0.85) var(--media-player-volume),
rgb(255 255 255 / 0.3) var(--media-player-volume),
rgb(255 255 255 / 0.3) 100%
);
background-clip: content-box;
}
.media-player-progress::-webkit-slider-runnable-track,
.media-player-volume::-webkit-slider-runnable-track {
height: 0.375rem;
border-radius: 9999px;
background: transparent;
}
.media-player-progress::-moz-range-track,
.media-player-volume::-moz-range-track {
height: 0.375rem;
border-radius: 9999px;
background: transparent;
}
.media-player-progress::-webkit-slider-thumb,
.media-player-volume::-webkit-slider-thumb {
width: 0.85rem;
height: 0.85rem;
margin-top: -0.21875rem;
appearance: none;
border: 2px solid white;
border-radius: 9999px;
background: var(--sc-primary, #80b6f5);
box-shadow: 0 1px 5px rgb(0 0 0 / 0.35);
}
.media-player-volume::-webkit-slider-thumb {
background: white;
}
.media-player-progress::-moz-range-thumb,
.media-player-volume::-moz-range-thumb {
width: 0.85rem;
height: 0.85rem;
border: 2px solid white;
border-radius: 9999px;
background: var(--sc-primary, #80b6f5);
box-shadow: 0 1px 5px rgb(0 0 0 / 0.35);
}
.media-player-volume::-moz-range-thumb {
background: white;
}
.media-player-control-row,
.media-player-control-trailing {
display: flex;
align-items: center;
gap: 0.25rem;
}
.media-player-control-row {
margin-top: 0.25rem;
}
.media-player-control-trailing {
margin-left: auto;
gap: 0.25rem;
}
.media-player-control {
display: inline-flex;
width: 2.25rem;
height: 2.25rem;
flex: 0 0 auto;
align-items: center;
justify-content: center;
border: 1px solid rgb(255 255 255 / 0.18);
border-radius: 0.5rem;
background: rgb(0 0 0 / 0.42);
color: rgb(255 255 255 / 0.92);
cursor: pointer;
transition:
background-color 120ms ease,
border-color 120ms ease,
color 120ms ease;
}
.media-player-control:hover:not(:disabled) {
border-color: rgb(255 255 255 / 0.35);
background: rgb(255 255 255 / 0.16);
color: white;
}
.media-player-control:disabled,
.media-player-progress:disabled,
.media-player-volume:disabled {
cursor: not-allowed;
opacity: 0.45;
}
.media-player-time {
margin-left: 0.25rem;
color: rgb(255 255 255 / 0.85);
font-size: 0.75rem;
font-variant-numeric: tabular-nums;
white-space: nowrap;
}
.media-player-settings {
position: relative;
}
.media-player-settings-menu {
position: absolute;
right: 0;
bottom: calc(100% + 0.5rem);
z-index: 30;
display: grid;
min-width: 13rem;
gap: 0.25rem;
padding: 0.4rem;
border: 1px solid rgb(255 255 255 / 0.18);
border-radius: 0.6rem;
background: rgb(16 18 23 / 0.96);
box-shadow: 0 0.5rem 1.5rem rgb(0 0 0 / 0.35);
color: white;
}
.media-player-settings-toggle,
.media-player-settings-quality {
display: flex;
width: 100%;
min-height: 2.25rem;
align-items: center;
justify-content: space-between;
gap: 1rem;
border-radius: 0.4rem;
padding: 0.35rem 0.5rem;
color: rgb(255 255 255 / 0.9);
font-size: 0.75rem;
text-align: left;
}
.media-player-settings-toggle {
border: 0;
background: transparent;
cursor: pointer;
}
.media-player-settings-toggle:hover:not(:disabled) {
background: rgb(255 255 255 / 0.12);
}
.media-player-settings-status {
color: var(--sc-primary, #80b6f5);
font-weight: 600;
}
.media-player-settings-quality select {
max-width: 7rem;
border: 1px solid rgb(255 255 255 / 0.18);
border-radius: 0.35rem;
background: rgb(0 0 0 / 0.42);
padding: 0.25rem 0.35rem;
color: inherit;
font-size: inherit;
}
.media-player-settings-quality option {
background: var(--sc-surface, #1b1f27);
color: var(--sc-fg, white);
}
.media-player-control:focus-visible,
.media-player-progress:focus-visible,
.media-player-volume:focus-visible,
.media-player-settings-toggle:focus-visible,
.media-player-settings-quality select:focus-visible {
outline: 2px solid var(--sc-ring, var(--sc-primary, #80b6f5));
outline-offset: 2px;
}
:global(.media-player-icon) {
width: 1rem;
height: 1rem;
}
:global(.media-player-icon-large) {
width: 1.25rem;
height: 1.25rem;
}
@media (max-width: 639px) {
.media-player-volume {
display: none;
}
.media-player-controls-fullscreen .media-player-volume {
display: block;
}
}
</style>
@@ -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>
@@ -1,35 +0,0 @@
<script lang="ts">
import type { Snippet } from 'svelte';
let {
actions,
children,
description = '',
subtitle = '',
title
}: {
actions?: Snippet;
children?: Snippet;
description?: string;
subtitle?: string;
title: string;
} = $props();
const supportingText = $derived(description || subtitle);
</script>
<div class="sc-page-header">
<div>
<h1>{title}</h1>
{#if supportingText}
<p>{supportingText}</p>
{/if}
{@render children?.()}
</div>
{#if actions}
<div>
{@render actions()}
</div>
{/if}
</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={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>
@@ -0,0 +1,52 @@
<script lang="ts">
import { onMount } from 'svelte'
import {
PRIMARY_COLOR_PALETTE,
initPrimaryColor,
setPrimaryColor,
storedPrimaryColor,
} from '../primary-color.svelte'
let {
projectKey,
label = 'Primary color',
}: {
projectKey: string
label?: string
} = $props()
let selected = $state('')
onMount(() => {
selected = storedPrimaryColor(projectKey)
const stop = initPrimaryColor(projectKey)
return stop
})
function choose(name: string) {
selected = name
setPrimaryColor(projectKey, name)
}
</script>
<div class="sc-primary-color">
<span class="sc-label">{label}</span>
<select
class="sc-input"
aria-label={label}
value={selected}
onchange={(event) => choose(event.currentTarget.value)}
>
<option value="">Default</option>
{#each PRIMARY_COLOR_PALETTE as color (color.name)}
<option value={color.name}>{color.name}</option>
{/each}
</select>
</div>
<style>
.sc-primary-color {
display: grid;
gap: 0.5rem;
}
</style>
@@ -1,51 +1,27 @@
<script lang="ts">
import type {
ProfileUpdateInput,
TotpSetupRequest,
TotpStatusRequest,
TotpTokenAction,
UserCreateRequest,
UserDeleteRequest,
UserId,
UserListRequest,
UserRole,
UserUpdateRequest
} from '../types';
import type { ProfileUpdateInput, TotpSetupRequest, TotpStatusRequest, TotpTokenAction } from '../types';
import Button from './Button.svelte';
import Dialog from './Dialog.svelte';
import TotpSettings from './TotpSettings.svelte';
import UserManagement from './UserManagement.svelte';
let {
currentEmail = '',
currentRole = 'user',
currentUserId,
onCreateUser,
onDeleteUser,
onListUsers,
currentUsername = '',
onSave,
onTotpDisable,
onTotpEnable,
onTotpSetup,
onTotpStatus,
onUpdateUser,
totpEnabled = false,
open = $bindable(false)
}: {
currentEmail?: string;
currentRole?: UserRole;
currentUserId?: UserId;
onCreateUser?: UserCreateRequest;
onDeleteUser?: UserDeleteRequest;
onListUsers?: UserListRequest;
currentUsername?: string;
onSave?: (input: ProfileUpdateInput) => void | Promise<void>;
onTotpDisable?: TotpTokenAction;
onTotpEnable?: TotpTokenAction;
onTotpSetup?: TotpSetupRequest;
onTotpStatus?: TotpStatusRequest;
onUpdateUser?: UserUpdateRequest;
totpEnabled?: boolean;
open?: boolean;
} = $props();
@@ -158,13 +134,4 @@
enabled={totpEnabled}
/>
{/if}
<UserManagement
currentRole={currentRole}
currentUserId={currentUserId}
onCreate={onCreateUser}
onDelete={onDeleteUser}
onList={onListUsers}
onUpdate={onUpdateUser}
/>
</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">
import type { Snippet } from 'svelte';
import type {
UserCreateRequest,
UserDeleteRequest,
UserId,
UserListRequest,
UserRole,
UserUpdateRequest
} from '../types';
import Dialog from './Dialog.svelte';
import UserManagement from './UserManagement.svelte';
let {
children,
description = '',
currentRole = 'user',
currentUserId,
onCreateUser,
onDeleteUser,
onListUsers,
onUpdateUser,
open = $bindable(false),
title = 'Settings'
}: {
children?: Snippet;
description?: string;
currentRole?: UserRole;
currentUserId?: UserId;
onCreateUser?: UserCreateRequest;
onDeleteUser?: UserDeleteRequest;
onListUsers?: UserListRequest;
onUpdateUser?: UserUpdateRequest;
open?: boolean;
title?: string;
} = $props();
@@ -42,12 +21,4 @@
{:else}
<p class="sc-muted">No settings have been configured for this application yet.</p>
{/if}
<UserManagement
currentRole={currentRole}
currentUserId={currentUserId}
onCreate={onCreateUser}
onDelete={onDeleteUser}
onList={onListUsers}
onUpdate={onUpdateUser}
/>
</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} />
@@ -1,196 +0,0 @@
<script lang="ts">
import type {
ManagedUser,
UserCreateInput,
UserCreateRequest,
UserDeleteRequest,
UserId,
UserListRequest,
UserRole,
UserUpdateInput,
UserUpdateRequest
} from '../types';
import Button from './Button.svelte';
let {
currentRole = 'user',
currentUserId,
onCreate,
onDelete,
onList,
onUpdate
}: {
currentRole?: UserRole;
currentUserId?: UserId;
onCreate?: UserCreateRequest;
onDelete?: UserDeleteRequest;
onList?: UserListRequest;
onUpdate?: UserUpdateRequest;
} = $props();
let users = $state<ManagedUser[]>([]);
let loading = $state(false);
let saving = $state(false);
let error = $state('');
let notice = $state('');
let loaded = $state(false);
let newUser = $state<UserCreateInput>({ username: '', email: '', password: '', role: 'user' });
let editingId = $state<UserId | null>(null);
let editUser = $state<UserUpdateInput>({});
const canManage = $derived(currentRole === 'admin' || currentRole === 'superadmin');
const canAssignAdmin = $derived(currentRole === 'superadmin');
function roleForForm(role: UserRole | undefined): UserRole {
return canAssignAdmin && role ? role : 'user';
}
async function loadUsers(): Promise<void> {
if (!onList || !canManage) return;
loading = true;
error = '';
try {
users = await onList();
loaded = true;
} catch (caught) {
error = caught instanceof Error ? caught.message : 'Unable to load users.';
} finally {
loading = false;
}
}
$effect(() => {
if (canManage && onList && !loaded) void loadUsers();
});
async function createUser(event: SubmitEvent): Promise<void> {
event.preventDefault();
if (!onCreate) return;
saving = true;
error = '';
notice = '';
try {
await onCreate({ ...newUser, role: roleForForm(newUser.role) });
newUser = { username: '', email: '', password: '', role: 'user' };
notice = 'User created.';
await loadUsers();
} catch (caught) {
error = caught instanceof Error ? caught.message : 'Unable to create user.';
} finally {
saving = false;
}
}
function startEditing(user: ManagedUser): void {
editingId = user.id;
editUser = { username: user.username, email: user.email, role: roleForForm(user.role) };
error = '';
notice = '';
}
function stopEditing(): void {
editingId = null;
editUser = {};
}
async function updateUser(event: SubmitEvent): Promise<void> {
event.preventDefault();
if (!onUpdate || editingId === null) return;
saving = true;
error = '';
notice = '';
try {
const input = { ...editUser, role: roleForForm(editUser.role) };
if (!input.password) delete input.password;
await onUpdate(editingId, input);
stopEditing();
notice = 'User updated.';
await loadUsers();
} catch (caught) {
error = caught instanceof Error ? caught.message : 'Unable to update user.';
} finally {
saving = false;
}
}
async function deleteUser(user: ManagedUser): Promise<void> {
if (!onDelete || String(user.id) === String(currentUserId)) return;
if (!window.confirm(`Delete user ${user.username}?`)) return;
saving = true;
error = '';
notice = '';
try {
await onDelete(user.id);
notice = 'User deleted.';
await loadUsers();
} catch (caught) {
error = caught instanceof Error ? caught.message : 'Unable to delete user.';
} finally {
saving = false;
}
}
</script>
{#if canManage && onList && onCreate && onUpdate && onDelete}
<section class="sc-user-management" aria-labelledby="sc-user-management-title">
<div class="sc-user-management-header">
<div>
<h3 id="sc-user-management-title">User management</h3>
<p class="sc-muted">Add, edit, or remove accounts for this project.</p>
</div>
<Button disabled={loading || saving} size="sm" type="button" variant="secondary" onclick={() => void loadUsers()}>
Refresh
</Button>
</div>
<form class="sc-user-form" onsubmit={createUser}>
<strong>Add user</strong>
<div class="sc-user-grid">
<input aria-label="New username" class="sc-input" placeholder="Username" required type="text" bind:value={newUser.username} />
<input aria-label="New email" class="sc-input" placeholder="Email" required type="email" bind:value={newUser.email} />
<input aria-label="New password" class="sc-input" minlength="8" placeholder="Password" required type="password" bind:value={newUser.password} />
<select aria-label="New role" class="sc-input" disabled={!canAssignAdmin} bind:value={newUser.role}>
<option value="user">User</option>
{#if canAssignAdmin}<option value="admin">Admin</option>{/if}
</select>
</div>
<div class="sc-form-actions"><Button disabled={saving} type="submit">Add user</Button></div>
</form>
{#if error}<p aria-live="polite" class="sc-error">{error}</p>{/if}
{#if notice}<p aria-live="polite" class="sc-success">{notice}</p>{/if}
{#if loading && users.length === 0}
<p class="sc-muted">Loading users...</p>
{:else if users.length === 0}
<p class="sc-muted">No users found.</p>
{:else}
<div class="sc-user-list">
{#each users as user (user.id)}
{#if String(editingId) === String(user.id)}
<form class="sc-user-row sc-user-edit-row" onsubmit={updateUser}>
<input aria-label="Username" class="sc-input" required type="text" bind:value={editUser.username} />
<input aria-label="Email" class="sc-input" required type="email" bind:value={editUser.email} />
<input aria-label="New password" class="sc-input" minlength="8" placeholder="Keep password" type="password" bind:value={editUser.password} />
<select aria-label="Role" class="sc-input" disabled={!canAssignAdmin || user.role === 'superadmin'} bind:value={editUser.role}>
<option value="user">User</option>
{#if canAssignAdmin}<option value="admin">Admin</option>{/if}
{#if user.role === 'superadmin'}<option value="superadmin">Superadmin</option>{/if}
</select>
<div class="sc-user-actions"><Button disabled={saving} size="sm" type="submit">Save</Button><Button disabled={saving} size="sm" type="button" variant="secondary" onclick={stopEditing}>Cancel</Button></div>
</form>
{:else}
<div class="sc-user-row">
<div><strong>{user.username}</strong><span>{user.email}</span></div>
<span class="sc-user-role">{user.role}</span>
<div class="sc-user-actions">
<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>
</div>
</div>
{/if}
{/each}
</div>
{/if}
</section>
{/if}
+26 -6
View File
@@ -5,12 +5,31 @@ export { default as Badge } from './components/Badge.svelte';
export { default as Button } from './components/Button.svelte';
export { default as Card } from './components/Card.svelte';
export { default as Dialog } from './components/Dialog.svelte';
export { default as EmptyState } from './components/EmptyState.svelte';
export { default as Header } from './components/Header.svelte';
export { default as PageHeader } from './components/PageHeader.svelte';
export { default as Metric } from './components/Metric.svelte';
export { default as MediaPlayer } from './components/MediaPlayer.svelte';
export { default as NotificationStack } from './components/NotificationStack.svelte';
export { default as Pagination } from './components/Pagination.svelte';
export { default as ProfileDialog } from './components/ProfileDialog.svelte';
export { default as PrimaryColorPicker } from './components/PrimaryColorPicker.svelte';
export { default as SectionTitle } from './components/SectionTitle.svelte';
export { default as SettingsDialog } from './components/SettingsDialog.svelte';
export { default as StatusDialog } from './components/StatusDialog.svelte';
export { default as StatusWidget } from './components/StatusWidget.svelte';
export { default as TotpSettings } from './components/TotpSettings.svelte';
export { default as UserManagement } from './components/UserManagement.svelte';
export { notifications, notify } from './notifications.svelte';
export {
PRIMARY_COLOR_PALETTE,
applyPrimaryColor,
initPrimaryColor,
primaryColorByName,
setPrimaryColor,
setPrimaryColorUser,
storedPrimaryColor,
} from './primary-color.svelte';
export type { PaletteColor } from './primary-color.svelte';
export type { NotificationEntry, NotificationVariant } from './notifications.svelte';
export type {
AboutLink,
AsyncAction,
@@ -19,17 +38,18 @@ export type {
AuthResetRequest,
AuthSetupInput,
ContentSnippet,
KnownProject,
KnownRole,
NavItem,
ProfileUpdateInput,
ManagedUser,
StatusLevel,
StatusProbe,
StatusSnapshot,
UserCreateInput,
UserCreateRequest,
UserDeleteRequest,
UserId,
UserListRequest,
UserRole,
UserUpdateInput,
UserUpdateRequest,
TotpSetupRequest,
TotpSetupResponse,
TotpStatusRequest,
@@ -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,
};
@@ -0,0 +1,146 @@
export type PaletteColor = { name: string; dark: string; light: string; darkFg: string }
export const PRIMARY_COLOR_PALETTE: PaletteColor[] = [
{ name: 'Vermilion', dark: '#f59080', light: '#db3e24', darkFg: '#2b110d' },
{ name: 'Tangerine', dark: '#fb923c', light: '#c2410c', darkFg: '#2b1206' },
{ name: 'Marigold', dark: '#f5b380', light: '#db7524', darkFg: '#2b1a0d' },
{ name: 'Amber', dark: '#f5ca80', light: '#b87d14', darkFg: '#2b200d' },
{ name: 'Gold', dark: '#f5e280', light: '#b89d14', darkFg: '#2b260d' },
{ name: 'Honey', dark: '#f1f580', light: '#b2b814', darkFg: '#2a2b0d' },
{ name: 'Chartreuse', dark: '#daf580', light: '#92b814', darkFg: '#242b0d' },
{ name: 'Lime', dark: '#c3f580', light: '#72b814', darkFg: '#1e2b0d' },
{ name: 'Spring Green', dark: '#abf580', light: '#51b814', darkFg: '#182b0d' },
{ name: 'Shamrock', dark: '#94f580', light: '#44db24', darkFg: '#122b0d' },
{ name: 'Emerald', dark: '#80f582', light: '#24db28', darkFg: '#0d2b0d' },
{ name: 'Jade', dark: '#80f599', light: '#24db4c', darkFg: '#0d2b13' },
{ name: 'Clover', dark: '#22c55e', light: '#16a34a', darkFg: '#052e14' },
{ name: 'Mint', dark: '#80f5bc', light: '#24db83', darkFg: '#0d2b1d' },
{ name: 'Seafoam', dark: '#80f5d4', light: '#24dba8', darkFg: '#0d2b23' },
{ name: 'Turquoise', dark: '#80f5ec', light: '#24dbce', darkFg: '#0d2b29' },
{ name: 'Aqua', dark: '#80e5f5', light: '#24c3db', darkFg: '#0d272b' },
{ name: 'Cyan', dark: '#80cef5', light: '#249edb', darkFg: '#0d212b' },
{ name: 'Sky Blue', dark: '#80b6f5', light: '#2479db', darkFg: '#0d1b2b' },
{ name: 'Cornflower', dark: '#3b82f6', light: '#2563eb', darkFg: '#0a1733' },
{ name: 'Indigo', dark: '#99a1d7', light: '#4355b9', darkFg: '#12162b' },
{ name: 'Iris', dark: '#818cf8', light: '#4f46e5', darkFg: '#12102e' },
{ name: 'Periwinkle', dark: '#9880f5', light: '#4a24db', darkFg: '#130d2b' },
{ name: 'Violet', dark: '#ae80f5', light: '#6d24db', darkFg: '#190d2b' },
{ name: 'Purple', dark: '#c580f5', light: '#9124db', darkFg: '#1f0d2b' },
{ name: 'Orchid', dark: '#dc80f5', light: '#b424db', darkFg: '#250d2b' },
{ name: 'Magenta', dark: '#f280f5', light: '#d824db', darkFg: '#2b0d2b' },
{ name: 'Fuchsia', dark: '#f580e0', light: '#db24bb', darkFg: '#2b0d26' },
{ name: 'Pink', dark: '#f580ca', light: '#db2498', darkFg: '#2b0d20' },
{ name: 'Rose', dark: '#f580b3', light: '#db2474', darkFg: '#2b0d1a' },
{ name: 'Ruby', dark: '#f5809c', light: '#db2451', darkFg: '#2b0d14' },
{ name: 'Crimson', dark: '#f58086', light: '#db242d', darkFg: '#2b0d0e' },
]
const paletteByName = Object.fromEntries(PRIMARY_COLOR_PALETTE.map((color) => [color.name, color])) as Record<
string,
PaletteColor
>
const primaryVars = ['--color-primary', '--color-accent', '--color-ring', '--sc-primary', '--sc-accent', '--sc-ring']
const foregroundVars = ['--color-primary-fg', '--color-accent-fg', '--sc-primary-fg', '--sc-accent-fg']
const activeUserAttribute = 'data-primary-color-user'
const styleElementId = 'sc-primary-color'
const activeProjects = new Set<string>()
function normalizeUserKey(userKey: string): string {
return userKey.trim().toLowerCase() || 'anonymous'
}
function activeUserKey(): string {
if (typeof document === 'undefined') return 'anonymous'
return normalizeUserKey(document.documentElement.getAttribute(activeUserAttribute) || '')
}
function storageKey(projectKey: string, userKey = activeUserKey()): string {
const project = encodeURIComponent(projectKey.trim().toLowerCase() || 'application')
const user = encodeURIComponent(normalizeUserKey(userKey))
return `primary-color:${project}:${user}`
}
function readStoredColor(projectKey: string): string {
try {
return localStorage.getItem(storageKey(projectKey)) || ''
} catch {
return ''
}
}
// Moves a #rrggbb color a fraction of the way toward a channel value (0 = black, 255 = white).
function mixHex(hex: string, towards: number, weight: number): string {
const channels = [1, 3, 5].map((start) => parseInt(hex.slice(start, start + 2), 16))
return `#${channels.map((c) => Math.round(c + (towards - c) * weight).toString(16).padStart(2, '0')).join('')}`
}
// The color is written to a stylesheet rather than inline on <html>. Shared and app CSS re-declare these
// tokens on every [data-theme] element (the AppShell root, for one), and that declaration hides the value
// <html> would pass down, so the choice never reached the app's UI. Targeting [data-theme] elements with
// !important makes it win everywhere, and the dark/light split is left to the selectors.
function primaryDeclarations(color: PaletteColor, dark: boolean): string {
const primary = dark ? color.dark : color.light
// Hover is lighter on dark and darker on light, as in the shared theme. It is a hex value, not color-mix(),
// because consumers such as the terminal read these tokens as plain colors.
const hover = dark ? mixHex(primary, 255, 0.15) : mixHex(primary, 0, 0.15)
const foreground = dark ? color.darkFg : '#ffffff'
return [
...primaryVars.map((name) => `${name}: ${primary} !important;`),
`--sc-primary-hover: ${hover} !important;`,
...foregroundVars.map((name) => `${name}: ${foreground} !important;`),
].join(' ')
}
export function applyPrimaryColor(_projectKey: string, colorName: string): void {
if (typeof document === 'undefined') return
const color = paletteByName[colorName]
let style = document.getElementById(styleElementId) as HTMLStyleElement | null
if (!color) {
style?.remove()
return
}
if (!style) {
style = document.createElement('style')
style.id = styleElementId
document.head.append(style)
}
style.textContent = `:root, [data-theme] { ${primaryDeclarations(color, false)} }
[data-theme='dark'] { ${primaryDeclarations(color, true)} }
`
}
export function setPrimaryColor(projectKey: string, colorName: string): void {
try {
const key = storageKey(projectKey)
if (colorName) localStorage.setItem(key, colorName)
else localStorage.removeItem(key)
} catch {
// The current page still receives the selected color if storage is unavailable.
}
applyPrimaryColor(projectKey, colorName)
}
export function setPrimaryColorUser(userKey: string): void {
if (typeof document === 'undefined') return
document.documentElement.setAttribute(activeUserAttribute, normalizeUserKey(userKey))
for (const projectKey of activeProjects) {
applyPrimaryColor(projectKey, readStoredColor(projectKey))
}
}
export function initPrimaryColor(projectKey: string, userKey = ''): () => void {
if (typeof document === 'undefined') return () => undefined
if (userKey) setPrimaryColorUser(userKey)
activeProjects.add(projectKey.trim().toLowerCase() || 'application')
applyPrimaryColor(projectKey, readStoredColor(projectKey))
return () => undefined
}
export function storedPrimaryColor(projectKey: string): string {
const stored = readStoredColor(projectKey)
return paletteByName[stored] ? stored : ''
}
export function primaryColorByName(name: string): PaletteColor | undefined {
return paletteByName[name]
}
+491 -114
View File
@@ -1,4 +1,4 @@
@import '@gabriel20xx/design-tokens/theme.css';
@import "@gabriel20xx/design-tokens/theme.css";
:where(.sc-root, .sc-root *) {
box-sizing: border-box;
@@ -31,7 +31,19 @@
.sc-main {
width: min(100% - 2rem, 90rem);
margin: 0 auto;
padding: 2rem 0 3rem;
padding: 1rem 0 1rem;
}
/* The page-width preference is owned by each consumer application. The shared shell only
provides the common width cap, so this global hook lets the current app widen that shell as
soon as its settings checkbox updates the document attribute. */
html[data-wide-layout='true'] .sc-main {
width: calc(100% - 2rem);
}
html[data-wide-layout='true'] .sc-header {
width: calc(100% - 2rem);
margin-inline: auto;
}
.sc-header {
@@ -62,6 +74,7 @@
}
.sc-brand-mark {
overflow: hidden;
display: grid;
width: 2rem;
height: 2rem;
@@ -73,6 +86,18 @@
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 {
display: flex;
flex: 1 1 auto;
@@ -85,7 +110,17 @@
.sc-icon-button {
border: 1px solid transparent;
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 {
@@ -96,7 +131,7 @@
}
.sc-nav-link:hover,
.sc-nav-link[data-active='true'] {
.sc-nav-link[data-active="true"] {
color: var(--sc-fg);
background: var(--sc-surface-hover);
border-color: var(--sc-border);
@@ -129,6 +164,56 @@
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:link/a:visited color (higher
specificity than the class color above) makes it drift from the other dropdown items' color,
both before and after it's been clicked. */
.sc-profile-menu-item:link,
.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-profile-button:hover {
color: var(--sc-fg);
@@ -140,16 +225,6 @@
display: none;
}
.sc-page-header {
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 1rem;
margin-bottom: 1.5rem;
}
.sc-page-header h1,
.sc-page-header h2,
.sc-dialog-title,
.sc-auth-card h1 {
margin: 0;
@@ -158,11 +233,6 @@
letter-spacing: -0.025em;
}
.sc-page-header h1 {
font-size: clamp(1.5rem, 3vw, 2.25rem);
}
.sc-page-header p,
.sc-dialog-description,
.sc-auth-subtitle,
.sc-muted {
@@ -209,19 +279,25 @@
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);
background: var(--sc-success);
border-color: transparent;
}
.sc-badge[data-variant='warning'] {
.sc-badge[data-variant="warning"] {
color: var(--sc-warning-fg);
background: var(--sc-warning);
border-color: transparent;
}
.sc-badge[data-variant='danger'] {
.sc-badge[data-variant="danger"] {
color: var(--sc-danger-fg);
background: var(--sc-danger);
border-color: transparent;
@@ -232,7 +308,7 @@
align-items: center;
justify-content: center;
gap: 0.5rem;
min-height: 2.5rem;
height: 2.5rem;
padding: 0.625rem 1rem;
border: 1px solid transparent;
border-radius: var(--sc-radius-md);
@@ -240,7 +316,11 @@
font-weight: 650;
line-height: 1;
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) {
@@ -255,6 +335,7 @@
.sc-button:focus-visible,
.sc-icon-button:focus-visible,
.sc-profile-button:focus-visible,
.sc-profile-menu-item:focus-visible,
.sc-nav-link:focus-visible,
.sc-dialog-close:focus-visible {
outline: 3px solid color-mix(in srgb, var(--sc-ring) 45%, transparent);
@@ -299,17 +380,207 @@
background: var(--sc-danger-hover);
}
.sc-button-outline {
color: var(--sc-fg);
background: transparent;
border-color: var(--sc-border);
}
.sc-button-outline:hover:not(:disabled) {
background: var(--sc-surface-hover);
}
.sc-button-sm {
min-height: 2rem;
height: 2.5rem;
padding: 0.45rem 0.75rem;
font-size: 0.8125rem;
}
.sc-button-lg {
min-height: 2.875rem;
height: 2.5rem;
padding: 0.75rem 1.25rem;
}
.sc-button-icon {
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;
flex-direction: column;
gap: 0.25rem;
}
.sc-section-title h2 {
margin: 0;
font-size: 0.9rem;
font-weight: 650;
color: var(--sc-fg);
}
.sc-section-title p {
margin: 0;
}
.sc-metric {
padding: 1rem;
border: 1px solid var(--sc-border);
border-radius: var(--sc-radius-lg);
background: var(--sc-surface);
}
.sc-metric-label {
margin: 0;
font-size: 0.6875rem;
font-weight: 650;
letter-spacing: 0.06em;
text-transform: uppercase;
color: var(--sc-muted-fg);
}
.sc-metric-value {
margin: 0.5rem 0 0;
font-size: 1.5rem;
font-weight: 650;
letter-spacing: -0.01em;
color: var(--sc-fg);
}
.sc-metric-value[data-variant="primary"] {
color: var(--sc-primary);
}
.sc-metric-value[data-variant="success"] {
color: var(--sc-success);
}
.sc-metric-value[data-variant="warning"] {
color: var(--sc-warning);
}
.sc-metric-value[data-variant="danger"] {
color: var(--sc-danger);
}
.sc-metric-detail {
margin: 0.25rem 0 0;
font-size: 0.8125rem;
color: var(--sc-muted-fg);
}
.sc-status-icon {
color: var(--sc-muted-fg);
}
.sc-status-summary[data-level="healthy"] .sc-status-icon,
.sc-status-summary[data-level="healthy"] .sc-status-summary-label {
color: var(--sc-success);
}
.sc-status-summary[data-level="degraded"] .sc-status-icon,
.sc-status-summary[data-level="degraded"] .sc-status-summary-label {
color: var(--sc-warning);
}
.sc-status-summary[data-level="offline"] .sc-status-icon,
.sc-status-summary[data-level="offline"] .sc-status-summary-label {
color: var(--sc-danger);
}
.sc-status-spin {
animation: sc-spin 900ms linear infinite;
}
@keyframes sc-spin {
to {
transform: rotate(360deg);
}
}
.sc-status-summary {
display: flex;
align-items: center;
gap: 0.75rem;
margin-bottom: 1.25rem;
padding: 0.75rem;
border: 1px solid var(--sc-border);
border-radius: var(--sc-radius-md);
background: var(--sc-surface);
}
.sc-status-summary-label {
font-weight: 650;
}
.sc-status-summary-time {
margin-left: auto;
font-size: 0.75rem;
color: var(--sc-muted-fg);
}
.sc-status-probes {
display: flex;
flex-direction: column;
gap: 0.5rem;
font-size: 0.875rem;
}
.sc-status-probe {
display: flex;
align-items: center;
justify-content: space-between;
gap: 1rem;
padding: 0.5rem 0.75rem;
border: 1px solid var(--sc-border);
border-radius: var(--sc-radius-sm);
}
.sc-status-probe span[data-ok="true"] {
color: var(--sc-success);
}
.sc-status-probe span[data-ok="false"] {
color: var(--sc-danger);
}
.sc-status-service {
margin-top: 1rem;
}
.sc-button-full {
width: 100%;
}
@@ -399,14 +670,20 @@
.sc-select,
.sc-textarea {
width: 100%;
min-height: 2.6rem;
padding: 0.625rem 0.75rem;
color: var(--sc-fg);
background: var(--sc-bg);
border: 1px solid var(--sc-border);
border-radius: var(--sc-radius-md);
outline: none;
transition: border-color 140ms ease, box-shadow 140ms ease;
transition:
border-color 140ms ease,
box-shadow 140ms ease;
}
.sc-input,
.sc-select {
height: 2.5rem;
}
.sc-textarea {
@@ -426,6 +703,27 @@
box-shadow: 0 0 0 3px color-mix(in srgb, var(--sc-ring) 22%, transparent);
}
/* Checkboxes and radios share one look across apps. The box takes each app's primary color,
so it follows that app's light and dark theme. Sizes match the legacy shared sheet. The rule
sits in the base layer so Tailwind utilities (size-*, accent-*) still override it per element. */
@layer base {
input[type='checkbox'],
input[type='radio'] {
accent-color: var(--sc-primary);
width: 1.05rem;
height: 1.05rem;
flex: 0 0 auto;
}
input[type='checkbox'] {
border-radius: 4px;
}
input[type='radio'] {
border-radius: 9999px;
}
}
.sc-form-actions,
.sc-dialog-footer {
display: flex;
@@ -448,106 +746,78 @@
color: var(--sc-success);
}
.sc-user-management {
display: grid;
gap: 1rem;
margin-top: 1.5rem;
padding-top: 1.5rem;
border-top: 1px solid var(--sc-border);
}
.sc-user-management-header,
.sc-user-row,
.sc-user-edit-row {
.sc-pagination {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 0.75rem;
}
.sc-user-management-header {
justify-content: space-between;
}
.sc-user-management-header h3 {
margin: 0;
}
.sc-user-management-header p {
margin: 0.25rem 0 0;
}
.sc-user-form,
.sc-user-list {
display: grid;
gap: 0.75rem;
margin-top: 1rem;
}
.sc-user-form {
padding: 0.9rem;
.sc-pagination-page-size {
width: auto;
height: 2.5rem;
padding: 0.375rem 0.6rem;
color: var(--sc-fg);
background: var(--sc-bg);
border: 1px solid var(--sc-border);
border-radius: 0.6rem;
background: var(--sc-surface-raised);
border-radius: var(--sc-radius-sm);
font-size: 0.8rem;
}
.sc-user-grid {
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr));
gap: 0.6rem;
}
.sc-user-row {
min-width: 0;
justify-content: space-between;
padding: 0.7rem 0;
border-bottom: 1px solid var(--sc-border);
}
.sc-user-row > div:first-child {
display: grid;
min-width: 0;
}
.sc-user-row > div:first-child span {
overflow: hidden;
.sc-pagination-info {
margin: 0;
color: var(--sc-muted-fg);
text-overflow: ellipsis;
font-size: 0.8rem;
white-space: nowrap;
}
.sc-user-role {
color: var(--sc-muted-fg);
font-size: 0.8rem;
text-transform: capitalize;
}
.sc-user-actions {
.sc-pagination-controls {
display: flex;
flex-shrink: 0;
gap: 0.4rem;
align-items: center;
gap: 0.25rem;
margin-left: auto;
}
.sc-user-edit-row {
align-items: stretch;
flex-wrap: wrap;
.sc-pagination-button {
display: grid;
width: 2.5rem;
height: 2.5rem;
place-items: center;
color: var(--sc-muted-fg);
background: transparent;
border: 1px solid var(--sc-border);
border-radius: var(--sc-radius-sm);
cursor: pointer;
transition:
color 140ms ease,
background 140ms ease,
border-color 140ms ease;
}
.sc-user-edit-row .sc-input {
flex: 1 1 10rem;
min-width: 8rem;
.sc-pagination-button:hover:not(:disabled) {
color: var(--sc-fg);
background: var(--sc-surface-hover);
}
.sc-pagination-button:focus-visible {
outline: 3px solid color-mix(in srgb, var(--sc-ring) 45%, transparent);
outline-offset: 2px;
}
.sc-pagination-button:disabled {
cursor: not-allowed;
opacity: 0.4;
}
@media (max-width: 620px) {
.sc-user-grid {
grid-template-columns: 1fr;
.sc-pagination {
justify-content: center;
}
.sc-user-row {
align-items: flex-start;
flex-wrap: wrap;
}
.sc-user-actions {
width: 100%;
.sc-pagination-controls {
margin-left: 0;
}
}
@@ -558,7 +828,11 @@
padding: 1.5rem;
color: var(--sc-fg);
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);
}
@@ -579,6 +853,14 @@
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 {
font-size: 1.7rem;
}
@@ -622,6 +904,99 @@
color: var(--sc-fg);
}
.sc-notification-stack {
position: fixed;
z-index: 200;
top: 1rem;
right: 1rem;
display: flex;
flex-direction: column;
width: min(100% - 2rem, 24rem);
pointer-events: none;
}
.sc-notification {
position: relative;
display: flex;
align-items: flex-start;
gap: 0.625rem;
min-width: 0;
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 + .sc-notification {
margin-block-start: -0.875rem;
}
.sc-notification:hover,
.sc-notification:focus-within {
z-index: 1;
}
.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;
min-width: 0;
margin: 0;
font-size: 0.875rem;
line-height: 1.45;
overflow-wrap: anywhere;
}
.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 {
position: fixed;
z-index: 100;
@@ -726,13 +1101,20 @@
padding: 0.75rem 1rem;
}
/* top is pinned explicitly: with it unset, the button's static-position offset is
recomputed from the flex-wrap layout, which changes height once .sc-nav wraps onto
its own row on open - so the button visibly jumps vertically on click. */
.sc-mobile-menu-button {
position: absolute;
top: 0.75rem;
left: 50%;
display: grid;
order: 3;
width: 2.25rem;
height: 2.25rem;
margin-left: auto;
margin-left: 0;
place-items: center;
transform: translateX(-50%);
}
.sc-nav {
@@ -744,7 +1126,7 @@
padding-bottom: 0.25rem;
}
.sc-nav[data-open='true'] {
.sc-nav[data-open="true"] {
display: flex;
}
@@ -753,7 +1135,7 @@
}
.sc-header-actions {
margin-left: 0;
margin-left: auto;
}
.sc-profile-button {
@@ -767,10 +1149,5 @@
@media (max-width: 30rem) {
.sc-main {
width: min(100% - 1.25rem, 90rem);
padding-top: 1.25rem;
}
.sc-page-header {
flex-direction: column;
}
}
+64 -11
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 interface NavItem {
href: string;
label: string;
icon?: string;
description?: string;
}
export interface AuthSetupInput {
@@ -27,7 +29,8 @@ export interface TotpSetupResponse {
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>;
@@ -41,7 +44,7 @@ export interface ProfileUpdateInput {
password?: string;
}
export type UserRole = 'superadmin' | 'admin' | 'user';
export type UserRole = "superadmin" | "admin" | "user";
export type UserId = string | number;
@@ -53,13 +56,47 @@ export interface ManagedUser {
totpEnabled?: boolean;
createdAt?: string;
updatedAt?: string;
/** Null/undefined means the account has never completed a login. */
lastLoginAt?: string | null;
/**
* Ids of the custom roles this account belongs to. Those roles decide which
* projects the account may log into (AuthGuard's role-based project access);
* an empty array means no custom role, which keeps every project open.
* Undefined on a backend that doesn't report roles at all.
*/
roleIds?: number[];
}
/** One registered project an administrator can pick from. */
export interface KnownProject {
key: string;
label: string;
}
/** One custom role an administrator may assign to a user. */
export interface KnownRole {
id: number;
name: string;
}
/**
* username/email are plain (never undefined) so <input> bindings stay simple
* -- an empty string, not an absent key, is how this form represents "not
* provided". At least one of username/email must be non-empty, and password
* may be left empty entirely; AuthGuard's POST /api/admin/users derives
* whichever of username/password is omitted (see its handleCreateUser).
*/
export interface UserCreateInput {
username: string;
email: string;
password: string;
role?: UserRole;
/**
* Ids of the custom roles this new account belongs to. An empty array means
* no custom role (every project); omitted when the host application does not
* expose roles.
*/
roleIds?: number[];
}
export interface UserUpdateInput {
@@ -67,19 +104,35 @@ export interface UserUpdateInput {
email?: string;
password?: string;
role?: UserRole;
/**
* Replaces the account's full set of custom roles when present (an empty
* array removes it from every role); omitted (undefined) leaves them
* untouched.
*/
roleIds?: number[];
}
export type UserListRequest = () => ManagedUser[] | Promise<ManagedUser[]>;
export type UserCreateRequest = (input: UserCreateInput) => void | Promise<void | ManagedUser>;
export type UserUpdateRequest = (id: UserId, input: UserUpdateInput) => void | Promise<void | ManagedUser>;
export type UserDeleteRequest = (id: UserId) => void | Promise<void>;
export interface AboutLink {
label: string;
href: string;
}
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, KioskDisplay, 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', 'CraftStudio', 'KioskDisplay', '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);
+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: 'CraftStudio', publicDir: 'CraftStudio/public' },
{ name: 'CraftStudio Converter', publicDir: 'CraftStudio/public/converter' },
{ name: 'CraftStudio Generator', publicDir: 'CraftStudio/generator/public' },
{ name: 'CraftStudio Downloader', publicDir: 'CraftStudio/downloader/public' },
{ name: 'KioskDisplay', publicDir: 'KioskDisplay/public' },
{ name: 'MediaViewer', publicDir: 'MediaViewer/public' },
{ name: 'ContentScanner', publicDir: 'ContentScanner/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);
Loaded 100 of 107 files, more files were not shown because too many files have changed in this diff. Show more