Rename shared snapshot directory
Docker / Docker Build & Push (push) Failing after 56s
Lint / Lint (push) Successful in 13s
Tests / Go backend (push) Successful in 15s
Tests / Dashboard checks (push) Successful in 17s

This commit is contained in:
Gabriel20xx committed 2026-08-06 16:55:37 +02:00
1 parent 06efc832ca
commit 5f13c2d347
82 files changed
+6 -10021

No files matched your search

+2 -2
View File
@@ -5,7 +5,7 @@ on:
branches:
- "**"
paths:
- 'SharedCode/**'
- 'shared/**'
- 'backend/**'
- 'frontend/**'
- 'docker/**'
@@ -15,7 +15,7 @@ on:
- main
- master
paths:
- 'SharedCode/**'
- 'shared/**'
- 'backend/**'
- 'frontend/**'
- 'docker/**'
-13
View File
@@ -1,13 +0,0 @@
# Release notes
Run `npm run changeset` to create a release note for the npm packages. Commit
the generated markdown file, then run:
```bash
npm run version-packages
npm install
npm run release
```
The Go and Python packages are released separately using their native module
and wheel workflows.
-13
View File
@@ -1,13 +0,0 @@
{
"$schema": "https://unpkg.com/@changesets/config@3.1.1/schema.json",
"changelog": "@changesets/cli/changelog",
"commit": false,
"fixed": [],
"linked": [],
"access": "public",
"baseBranch": "main",
"updateInternalDependencies": "patch",
"ignore": [
"@gabriel20xx/shared-workspace"
]
}
@@ -1,78 +0,0 @@
name: Publish Go package
on:
push:
tags:
- 'backend/v*'
release:
types:
- published
jobs:
publish:
name: Publish shared Go module
runs-on: ubuntu-latest
permissions:
contents: read
steps:
- name: Checkout source
uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Set up Go
uses: actions/setup-go@v5
with:
go-version-file: backend/go.mod
cache: false
- name: Test Go module
working-directory: backend
run: go test ./...
- name: Install ZIP tools
run: sudo apt-get update && sudo apt-get install --no-install-recommends -y zip
- name: Package Go module
env:
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"
find "$package_directory" -maxdepth 1 -type f -name '*.zip' -print -quit | grep -q .
- name: Publish to Gitea Package Registry
env:
PACKAGE_REGISTRY_USERNAME: ${{ secrets.PACKAGE_REGISTRY_USERNAME }}
PACKAGE_REGISTRY_TOKEN: ${{ secrets.PACKAGE_REGISTRY_TOKEN }}
GITEA_GO_REGISTRY: https://repos.gfranz.ch/api/packages/Gabriel20xx/go/upload
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
package_file="$(find gitea-go-package -maxdepth 1 -type f -name '*.zip' -print -quit)"
test -n "$package_file"
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" || 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
@@ -1,93 +0,0 @@
name: Publish npm packages
on:
push:
tags:
- 'v*'
release:
types:
- published
jobs:
publish:
name: Publish shared npm packages
runs-on: ubuntu-latest
permissions:
contents: read
steps:
- name: Checkout source
uses: actions/checkout@v4
- name: Set up Node.js
uses: actions/setup-node@v4
with:
node-version: 22
cache: npm
- name: Install and build packages
run: |
npm ci
npm run build
- name: Configure Gitea npm registry
env:
PACKAGE_REGISTRY_USERNAME: ${{ secrets.PACKAGE_REGISTRY_USERNAME }}
PACKAGE_REGISTRY_TOKEN: ${{ secrets.PACKAGE_REGISTRY_TOKEN }}
run: |
set -euo pipefail
if [ -z "$PACKAGE_REGISTRY_USERNAME" ] || [ -z "$PACKAGE_REGISTRY_TOKEN" ]; then
echo 'PACKAGE_REGISTRY_USERNAME and PACKAGE_REGISTRY_TOKEN secrets are required.' >&2
exit 1
fi
npmrc_path="$RUNNER_TEMP/gitea-npmrc"
umask 077
{
printf '@gabriel20xx:registry=https://repos.gfranz.ch/api/packages/Gabriel20xx/npm/\n'
printf '//repos.gfranz.ch/api/packages/Gabriel20xx/npm/:_authToken=%s\n' "$PACKAGE_REGISTRY_TOKEN"
printf 'always-auth=true\n'
} > "$npmrc_path"
printf 'NPM_CONFIG_USERCONFIG=%s\n' "$npmrc_path" >> "$GITHUB_ENV"
- name: Publish npm packages
env:
PACKAGE_REGISTRY_USERNAME: ${{ secrets.PACKAGE_REGISTRY_USERNAME }}
PACKAGE_REGISTRY_TOKEN: ${{ secrets.PACKAGE_REGISTRY_TOKEN }}
NPM_REGISTRY: https://repos.gfranz.ch/api/packages/Gabriel20xx/npm/
run: |
set -euo pipefail
if [ -z "$PACKAGE_REGISTRY_USERNAME" ] || [ -z "$PACKAGE_REGISTRY_TOKEN" ]; then
echo 'PACKAGE_REGISTRY_USERNAME and PACKAGE_REGISTRY_TOKEN secrets are required.' >&2
exit 1
fi
for package in \
@gabriel20xx/design-tokens \
@gabriel20xx/web-ui \
@gabriel20xx/node-backend; do
version="$(npm pkg get version --workspace="$package" | tr -d '"[:space:]')"
package_path="${package//@/%40}"
package_path="${package_path//\//%2f}"
metadata_file="$(mktemp)"
metadata_status="$(curl --silent --show-error --fail-with-body \
--user "$PACKAGE_REGISTRY_USERNAME:$PACKAGE_REGISTRY_TOKEN" \
--output "$metadata_file" \
--write-out '%{http_code}' \
"${NPM_REGISTRY}${package_path}" || true)"
case "$metadata_status" in
200)
if grep -Fq "\"$version\"" "$metadata_file"; then
echo "$package@$version is already published; skipping."
rm -f "$metadata_file"
continue
fi
;;
404)
;;
*)
cat "$metadata_file" >&2
echo "Gitea npm metadata lookup failed with HTTP status $metadata_status." >&2
exit 1
;;
esac
npm publish --workspace="$package" --registry="$NPM_REGISTRY"
rm -f "$metadata_file"
done
@@ -1,74 +0,0 @@
name: Publish Python package
on:
push:
tags:
- 'v*'
release:
types:
- published
jobs:
publish:
name: Publish shared Python package
runs-on: ubuntu-latest
permissions:
contents: read
steps:
- name: Checkout source
uses: actions/checkout@v4
- name: Set up Python
uses: actions/setup-python@v5
with:
python-version: '3.12'
- name: Build and publish package
env:
PACKAGE_REGISTRY_USERNAME: ${{ secrets.PACKAGE_REGISTRY_USERNAME }}
PACKAGE_REGISTRY_TOKEN: ${{ secrets.PACKAGE_REGISTRY_TOKEN }}
TWINE_REPOSITORY_URL: https://repos.gfranz.ch/api/packages/Gabriel20xx/pypi
run: |
set -euo pipefail
if [ -z "$PACKAGE_REGISTRY_USERNAME" ] || [ -z "$PACKAGE_REGISTRY_TOKEN" ]; then
echo 'PACKAGE_REGISTRY_USERNAME and PACKAGE_REGISTRY_TOKEN secrets are required.' >&2
exit 1
fi
python -m pip install --disable-pip-version-check --no-cache-dir build twine
package_directory="$RUNNER_TEMP/gitea-pypi-package"
python -m build packages/python-backend --outdir "$package_directory"
package_index_url="${TWINE_REPOSITORY_URL%/}/simple/gabriel20xx-shared-backend/"
package_index_file="$(mktemp)"
package_index_status="$(curl --silent --show-error --fail-with-body \
--user "$PACKAGE_REGISTRY_USERNAME:$PACKAGE_REGISTRY_TOKEN" \
--output "$package_index_file" \
--write-out '%{http_code}' \
"$package_index_url" || true)"
package_files=("$package_directory"/*)
files_to_upload=()
case "$package_index_status" in
200)
for package_file in "${package_files[@]}"; do
if ! grep -Fq "$(basename "$package_file")" "$package_index_file"; then
files_to_upload+=("$package_file")
fi
done
;;
404)
files_to_upload=("${package_files[@]}")
;;
*)
cat "$package_index_file" >&2
echo "Gitea PyPI package lookup failed with HTTP status $package_index_status." >&2
exit 1
;;
esac
if [ "${#files_to_upload[@]}" -eq 0 ]; then
echo 'Python package version already exists with all build artifacts; leaving it unchanged.'
exit 0
fi
TWINE_USERNAME="$PACKAGE_REGISTRY_USERNAME" \
TWINE_PASSWORD="$PACKAGE_REGISTRY_TOKEN" \
python -m twine upload --non-interactive \
--repository-url "$TWINE_REPOSITORY_URL" \
"${files_to_upload[@]}"
-14
View File
@@ -1,14 +0,0 @@
#!/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 "SharedCode synchronization requires pwsh or powershell.exe." >&2
exit 1
fi
-90
View File
@@ -1,90 +0,0 @@
name: Lint
on:
push:
branches:
- "**"
paths:
- '.changeset/**'
- '.github/workflows/**'
- 'backend/**'
- 'packages/**'
- 'scripts/**'
- 'package.json'
- 'package-lock.json'
pull_request:
branches:
- main
- master
paths:
- '.changeset/**'
- '.github/workflows/**'
- 'backend/**'
- 'packages/**'
- 'scripts/**'
- 'package.json'
- 'package-lock.json'
workflow_dispatch: {}
jobs:
node:
name: Lint (Node/Svelte)
runs-on: ubuntu-latest
permissions:
contents: read
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Set up Node.js
uses: actions/setup-node@v4
with:
node-version: '24'
cache: npm
cache-dependency-path: package-lock.json
- name: Install dependencies
run: npm ci
- name: Run Node/Svelte lint checks
run: npm run lint
go:
name: Lint (Go)
runs-on: ubuntu-latest
permissions:
contents: read
defaults:
run:
working-directory: backend
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Set up Go
uses: actions/setup-go@v5
with:
go-version-file: backend/go.mod
cache: true
- name: Check gofmt
shell: bash
run: |
mapfile -d '' go_files < <(find . -type f -name '*.go' -print0)
if ((${#go_files[@]})); then
test -z "$(gofmt -l "${go_files[@]}")"
fi
- name: Run go vet
run: go vet ./...
python:
name: Lint (Python)
runs-on: ubuntu-latest
permissions:
contents: read
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Set up Python
uses: actions/setup-python@v5
with:
python-version: '3.12'
- name: Install package and Ruff
run: python -m pip install --upgrade pip ruff -e packages/python-backend
- name: Run Ruff
run: ruff check packages/python-backend/src packages/python-backend/tests
-83
View File
@@ -1,83 +0,0 @@
name: Tests
on:
push:
branches:
- "**"
paths:
- '.changeset/**'
- '.github/workflows/**'
- 'backend/**'
- 'packages/**'
- 'scripts/**'
- 'package.json'
- 'package-lock.json'
pull_request:
branches:
- main
- master
paths:
- '.changeset/**'
- '.github/workflows/**'
- 'backend/**'
- 'packages/**'
- 'scripts/**'
- 'package.json'
- 'package-lock.json'
workflow_dispatch: {}
jobs:
node:
name: Test (Node/Svelte)
runs-on: ubuntu-latest
permissions:
contents: read
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Set up Node.js
uses: actions/setup-node@v4
with:
node-version: '24'
cache: npm
cache-dependency-path: package-lock.json
- name: Install dependencies
run: npm ci
- name: Build and test Node/Svelte packages
run: npm test
go:
name: Test (Go)
runs-on: ubuntu-latest
permissions:
contents: read
defaults:
run:
working-directory: backend
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Set up Go
uses: actions/setup-go@v5
with:
go-version-file: backend/go.mod
cache: true
- name: Run Go tests
run: go test ./...
python:
name: Test (Python)
runs-on: ubuntu-latest
permissions:
contents: read
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Set up Python
uses: actions/setup-python@v5
with:
python-version: '3.12'
- name: Install package
run: python -m pip install --upgrade pip -e packages/python-backend
- name: Run Python tests
run: python -m unittest discover -s packages/python-backend/tests -p 'test_*.py'
-9
View File
@@ -1,9 +0,0 @@
node_modules/
packages/*/dist/
packages/*/.svelte-kit/
*.tgz
.npm/
__pycache__/
*.py[cod]
*.egg-info/
.venv/
-243
View File
@@ -1,243 +0,0 @@
# SharedCode packages
This folder is the single source of truth for reusable web UI across the projects in this workspace.
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.
The components do not import `$app/state`, `$lib` stores, or a project-specific API. Applications provide those things through props and callbacks.
## Build and check the packages
Run these commands from this directory:
```bash
npm install
npm run check
npm run build
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 ./...
```
## 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
```svelte
<script lang="ts">
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}
onLogout={() => auth.logout()}
onProfile={() => (profileOpen = true)}
onSettings={() => (settingsOpen = true)}
username={auth.user?.username ?? ''}
>
{#snippet children()}
<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:
```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"
/>
```
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.
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:
```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
```
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.
## Updating the design system
When a component or token changes:
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.
-17
View File
@@ -1,17 +0,0 @@
# Shared Go backend packages
The Go packages under this directory hold infrastructure shared by the
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.
- `migrate` — embedded filesystem adapter for Goose migrations.
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
hosted under a different repository path.
Application-specific table definitions and HTTP behavior stay in the service.
That lets a service reuse reliable connection/auth plumbing without coupling
its domain model to another project.
-21
View File
@@ -1,21 +0,0 @@
package auth
import "golang.org/x/crypto/bcrypt"
// BcryptCost is kept in one place so all services use the same password
// storage policy. Existing hashes remain valid when this value is raised.
const BcryptCost = 12
// HashPassword returns a bcrypt password hash suitable for storage.
func HashPassword(password string) (string, error) {
hash, err := bcrypt.GenerateFromPassword([]byte(password), BcryptCost)
if err != nil {
return "", err
}
return string(hash), nil
}
// VerifyPassword checks a plaintext password against a stored bcrypt hash.
func VerifyPassword(hash, password string) bool {
return bcrypt.CompareHashAndPassword([]byte(hash), []byte(password)) == nil
}
-80
View File
@@ -1,80 +0,0 @@
package auth
import (
"crypto/rand"
"crypto/subtle"
"encoding/hex"
"fmt"
"strings"
"sync"
"time"
)
// ResetCodeTTL is the amount of time a printed admin reset code remains valid.
const ResetCodeTTL = 5 * time.Minute
// ResetManager creates and validates the short-lived, one-time code used by
// the public "reset admin account" flow. Account deletion remains owned by
// each application because its account table and session policy may differ.
type ResetManager struct {
mu sync.Mutex
code string
expiresAt time.Time
}
// NewResetManager creates an independent reset-code manager for one server.
func NewResetManager() *ResetManager {
return &ResetManager{}
}
// Request creates a reset code and prints it to the server console. A new
// request invalidates any code previously issued by this manager.
func (m *ResetManager) Request() (string, error) {
if m == nil {
return "", fmt.Errorf("auth reset manager is nil")
}
raw := make([]byte, 4)
if _, err := rand.Read(raw); err != nil {
return "", fmt.Errorf("generate auth reset code: %w", err)
}
code := strings.ToUpper(hex.EncodeToString(raw))
m.mu.Lock()
m.code = code
m.expiresAt = time.Now().Add(ResetCodeTTL)
m.mu.Unlock()
fmt.Printf("\n%s\nADMIN RESET CODE: %s\nExpires in 5 minutes. Enter it on the login page.\n%s\n\n", strings.Repeat("=", 50), code, strings.Repeat("=", 50))
return code, nil
}
// Confirm validates a code and consumes it on success. Invalid codes do not
// consume the pending code, while expired codes are cleared immediately.
func (m *ResetManager) Confirm(candidate string) bool {
if m == nil {
return false
}
m.mu.Lock()
defer m.mu.Unlock()
if m.code == "" {
return false
}
if time.Now().After(m.expiresAt) {
m.code = ""
m.expiresAt = time.Time{}
return false
}
want := []byte(m.code)
got := []byte(strings.ToUpper(strings.TrimSpace(candidate)))
if len(want) != len(got) || subtle.ConstantTimeCompare(want, got) != 1 {
return false
}
m.code = ""
m.expiresAt = time.Time{}
return true
}
-34
View File
@@ -1,34 +0,0 @@
package auth
// Role is the shared account-management role used by the web applications.
type Role string
const (
RoleSuperAdmin Role = "superadmin"
RoleAdmin Role = "admin"
RoleUser Role = "user"
)
// NormalizeRole keeps persisted role values inside the shared contract.
func NormalizeRole(value string) Role {
switch Role(value) {
case RoleSuperAdmin:
return RoleSuperAdmin
case RoleAdmin:
return RoleAdmin
default:
return RoleUser
}
}
// CanManageUsers is the common authorization gate for account CRUD.
func CanManageUsers(role string) bool {
role = string(NormalizeRole(role))
return role == string(RoleSuperAdmin) || role == string(RoleAdmin)
}
// CanAssignRole prevents an administrator from creating or promoting another
// administrator. Only the first-created superadmin can delegate admin access.
func CanAssignRole(actorRole, targetRole string) bool {
return NormalizeRole(actorRole) == RoleSuperAdmin && NormalizeRole(targetRole) != RoleSuperAdmin
}
-435
View File
@@ -1,435 +0,0 @@
// Package auth contains the shared single-account/session persistence used by
// the self-hosted web services. HTTP handlers, cookies, authorization policy,
// and application-specific roles remain in each service.
package auth
import (
"context"
"errors"
"fmt"
"time"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgconn"
"github.com/jackc/pgx/v5/pgxpool"
)
// User is the shared account record. PasswordHash should never be serialized
// into an API response.
type User struct {
ID int64
Username string
Email string
PasswordHash string
Role Role
CreatedAt time.Time
UpdatedAt time.Time
}
// Store performs common auth persistence against a caller-owned pool.
type Store struct {
pool *pgxpool.Pool
}
// NewStore creates an auth store. The pool remains owned by the caller.
func NewStore(pool *pgxpool.Pool) *Store {
return &Store{pool: pool}
}
// SchemaOptions controls optional auth schema features.
type SchemaOptions struct {
// SingleUser adds a constraint that allows exactly one account. This is the
// default model for GameStream, SimpleCollection, and home-server tools.
SingleUser bool
// APITokens creates the optional per-user API token table.
APITokens bool
}
// DefaultSchemaOptions returns the single-account schema used by most small
// self-hosted services.
func DefaultSchemaOptions() SchemaOptions {
return SchemaOptions{SingleUser: true}
}
// EnsureSchema creates the shared auth tables and indexes idempotently.
func EnsureSchema(ctx context.Context, pool *pgxpool.Pool, options SchemaOptions) error {
if pool == nil {
return errors.New("auth postgres pool is nil")
}
_, err := pool.Exec(ctx, `
CREATE TABLE IF NOT EXISTS auth_users (
id BIGSERIAL PRIMARY KEY,
username TEXT NOT NULL UNIQUE,
email TEXT NOT NULL DEFAULT '',
password_hash TEXT NOT NULL,
role TEXT NOT NULL DEFAULT 'user',
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()
);
ALTER TABLE auth_users ADD COLUMN IF NOT EXISTS email TEXT NOT NULL DEFAULT '';
ALTER TABLE auth_users ADD COLUMN IF NOT EXISTS role TEXT NOT NULL DEFAULT 'user';
ALTER TABLE auth_users ADD COLUMN IF NOT EXISTS totp_secret TEXT NOT NULL DEFAULT '';
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();
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');
CREATE UNIQUE INDEX IF NOT EXISTS auth_users_email_idx
ON auth_users (lower(email)) WHERE email <> '';
CREATE TABLE IF NOT EXISTS auth_sessions (
id BIGSERIAL PRIMARY KEY,
user_id BIGINT NOT NULL REFERENCES auth_users(id) ON DELETE CASCADE,
token_hash TEXT NOT NULL UNIQUE,
expires_at TIMESTAMPTZ NOT NULL,
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
CREATE INDEX IF NOT EXISTS auth_sessions_expiry_idx ON auth_sessions (expires_at);
CREATE INDEX IF NOT EXISTS auth_sessions_user_idx ON auth_sessions (user_id);
`)
if err != nil {
return fmt.Errorf("ensure auth schema: %w", err)
}
if options.SingleUser {
if _, err := pool.Exec(ctx, `
CREATE UNIQUE INDEX IF NOT EXISTS auth_users_singleton_idx ON auth_users ((true));
`); err != nil {
return fmt.Errorf("ensure single-user auth constraint: %w", err)
}
} else if _, err := pool.Exec(ctx, `DROP INDEX IF EXISTS auth_users_singleton_idx`); err != nil {
return fmt.Errorf("remove single-user auth constraint: %w", err)
}
if options.APITokens {
if _, err := pool.Exec(ctx, `
CREATE TABLE IF NOT EXISTS auth_api_tokens (
id BIGSERIAL PRIMARY KEY,
user_id BIGINT NOT NULL REFERENCES auth_users(id) ON DELETE CASCADE,
token_hash TEXT NOT NULL UNIQUE,
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
CREATE INDEX IF NOT EXISTS auth_api_tokens_user_idx ON auth_api_tokens (user_id);
`); err != nil {
return fmt.Errorf("ensure auth API-token schema: %w", err)
}
}
return nil
}
// TOTPState is the private provisioning state for one account. Secret must
// never be included in an API response.
type TOTPState struct {
Secret string
Enabled bool
}
// GetTOTPState reads the stored TOTP provisioning state for an account.
func (s *Store) GetTOTPState(ctx context.Context, userID int64) (TOTPState, error) {
if err := s.validate(); err != nil {
return TOTPState{}, err
}
var state TOTPState
err := s.pool.QueryRow(ctx, `SELECT COALESCE(totp_secret, ''), COALESCE(totp_enabled, false) FROM auth_users WHERE id = $1`, userID).Scan(&state.Secret, &state.Enabled)
if errors.Is(err, pgx.ErrNoRows) {
return TOTPState{}, nil
}
if err != nil {
return TOTPState{}, fmt.Errorf("get TOTP state: %w", err)
}
return state, nil
}
// SetTOTPSecret stores a pending secret without enabling two-factor auth.
func (s *Store) SetTOTPSecret(ctx context.Context, userID int64, secret string) error {
if err := s.validate(); err != nil {
return err
}
_, err := s.pool.Exec(ctx, `UPDATE auth_users SET totp_secret = $1, totp_enabled = false, updated_at = now() WHERE id = $2`, secret, userID)
if err != nil {
return fmt.Errorf("set TOTP secret: %w", err)
}
return nil
}
// EnableTOTP marks a previously provisioned secret as active.
func (s *Store) EnableTOTP(ctx context.Context, userID int64) error {
if err := s.validate(); err != nil {
return err
}
_, err := s.pool.Exec(ctx, `UPDATE auth_users SET totp_enabled = true, updated_at = now() WHERE id = $1 AND totp_secret <> ''`, userID)
if err != nil {
return fmt.Errorf("enable TOTP: %w", err)
}
return nil
}
// DisableTOTP clears both the active and pending TOTP secret.
func (s *Store) DisableTOTP(ctx context.Context, userID int64) error {
if err := s.validate(); err != nil {
return err
}
_, err := s.pool.Exec(ctx, `UPDATE auth_users SET totp_secret = '', totp_enabled = false, updated_at = now() WHERE id = $1`, userID)
if err != nil {
return fmt.Errorf("disable TOTP: %w", err)
}
return nil
}
// CountUsers returns the number of configured accounts.
func (s *Store) CountUsers(ctx context.Context) (int, error) {
if err := s.validate(); err != nil {
return 0, err
}
var count int
if err := s.pool.QueryRow(ctx, `SELECT count(*) FROM auth_users`).Scan(&count); err != nil {
return 0, fmt.Errorf("count auth users: %w", err)
}
return count, nil
}
// CreateUser inserts an account and returns ErrUserExists for a uniqueness
// conflict, including the single-user constraint.
func (s *Store) CreateUser(ctx context.Context, username, email, passwordHash string) (*User, error) {
if err := s.validate(); err != nil {
return nil, err
}
var user User
err := s.pool.QueryRow(ctx, `
INSERT INTO auth_users (username, email, password_hash, role, updated_at)
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
`, username, email, passwordHash).Scan(
&user.ID, &user.Username, &user.Email, &user.PasswordHash, &user.Role, &user.CreatedAt, &user.UpdatedAt,
)
if err != nil {
var pgErr *pgconn.PgError
if errors.As(err, &pgErr) && pgErr.Code == "23505" {
return nil, ErrUserExists
}
return nil, fmt.Errorf("create auth user: %w", err)
}
return &user, nil
}
// FindByIdentifier looks up a user by exact username or case-insensitive email.
func (s *Store) FindByIdentifier(ctx context.Context, identifier string) (*User, error) {
if err := s.validate(); err != nil {
return nil, err
}
return s.find(ctx, `
SELECT id, username, email, password_hash, role, created_at, updated_at
FROM auth_users
WHERE username = $1 OR lower(email) = lower($1)
`, identifier)
}
// FindByID looks up a user by primary key.
func (s *Store) FindByID(ctx context.Context, id int64) (*User, error) {
if err := s.validate(); err != nil {
return nil, err
}
return s.find(ctx, `
SELECT id, username, email, password_hash, role, created_at, updated_at
FROM auth_users WHERE id = $1
`, id)
}
// UpdateCredentials updates the normalized account fields and password hash.
func (s *Store) UpdateCredentials(ctx context.Context, id int64, username, email, passwordHash string) error {
if err := s.validate(); err != nil {
return err
}
_, err := s.pool.Exec(ctx, `
UPDATE auth_users
SET username = $1, email = $2, password_hash = $3, updated_at = now()
WHERE id = $4
`, username, email, passwordHash, id)
if err != nil {
return fmt.Errorf("update auth credentials: %w", err)
}
return nil
}
// ListUsers returns the non-secret account fields used by the shared user
// management screen.
func (s *Store) ListUsers(ctx context.Context) ([]User, error) {
if err := s.validate(); err != nil {
return nil, err
}
rows, err := s.pool.Query(ctx, `
SELECT id, username, email, role, created_at, updated_at
FROM auth_users ORDER BY created_at, id
`)
if err != nil {
return nil, fmt.Errorf("list auth users: %w", err)
}
defer rows.Close()
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 {
return nil, fmt.Errorf("scan auth user: %w", err)
}
users = append(users, user)
}
return users, rows.Err()
}
// CreateManagedUser creates a user with an explicit, already-authorized role.
func (s *Store) CreateManagedUser(ctx context.Context, username, email, passwordHash string, role Role) (*User, error) {
if err := s.validate(); err != nil {
return nil, err
}
role = NormalizeRole(string(role))
var user User
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
`, username, email, passwordHash, role).Scan(
&user.ID, &user.Username, &user.Email, &user.PasswordHash, &user.Role, &user.CreatedAt, &user.UpdatedAt,
)
if err != nil {
var pgErr *pgconn.PgError
if errors.As(err, &pgErr) && pgErr.Code == "23505" {
return nil, ErrUserExists
}
return nil, fmt.Errorf("create managed auth user: %w", err)
}
return &user, nil
}
// UpdateUser updates account fields and, when supplied, its role.
func (s *Store) UpdateUser(ctx context.Context, id int64, username, email, passwordHash string, role *Role) error {
if err := s.validate(); err != nil {
return err
}
if role == nil {
return s.UpdateCredentials(ctx, id, username, email, passwordHash)
}
*role = NormalizeRole(string(*role))
_, err := s.pool.Exec(ctx, `
UPDATE auth_users
SET username = $1, email = $2, password_hash = $3, role = $4, updated_at = now()
WHERE id = $5
`, username, email, passwordHash, *role, id)
if err != nil {
return fmt.Errorf("update managed auth user: %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 {
return err
}
if _, err := s.pool.Exec(ctx, `DELETE FROM auth_users WHERE id = $1`, id); err != nil {
return fmt.Errorf("delete auth user: %w", err)
}
return nil
}
// CreateSession stores a hash of a session token until expiresAt.
func (s *Store) CreateSession(ctx context.Context, userID int64, tokenHash string, expiresAt time.Time) error {
if err := s.validate(); err != nil {
return err
}
_, err := s.pool.Exec(ctx, `
INSERT INTO auth_sessions (user_id, token_hash, expires_at)
VALUES ($1, $2, $3)
`, userID, tokenHash, expiresAt)
if err != nil {
return fmt.Errorf("create auth session: %w", err)
}
return nil
}
// FindSessionUser resolves an unexpired session to its user.
func (s *Store) FindSessionUser(ctx context.Context, tokenHash string) (*User, error) {
if err := s.validate(); err != nil {
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
FROM auth_sessions s
JOIN auth_users u ON u.id = s.user_id
WHERE s.token_hash = $1 AND s.expires_at > now()
`, tokenHash)
}
// DeleteSession removes one session, typically during logout.
func (s *Store) DeleteSession(ctx context.Context, tokenHash string) error {
if err := s.validate(); err != nil {
return err
}
if _, err := s.pool.Exec(ctx, `DELETE FROM auth_sessions WHERE token_hash = $1`, tokenHash); err != nil {
return fmt.Errorf("delete auth session: %w", err)
}
return nil
}
// DeleteSessionsForUser invalidates all sessions after credential changes.
func (s *Store) DeleteSessionsForUser(ctx context.Context, userID int64) error {
if err := s.validate(); err != nil {
return err
}
if _, err := s.pool.Exec(ctx, `DELETE FROM auth_sessions WHERE user_id = $1`, userID); err != nil {
return fmt.Errorf("delete auth sessions for user: %w", err)
}
return nil
}
// DeleteAllUsers removes every shared account. The auth schema's foreign keys
// cascade this to browser sessions and API tokens, allowing a fresh bootstrap.
func (s *Store) DeleteAllUsers(ctx context.Context) error {
if err := s.validate(); err != nil {
return err
}
if _, err := s.pool.Exec(ctx, `DELETE FROM auth_users`); err != nil {
return fmt.Errorf("delete all auth users: %w", err)
}
return nil
}
// DeleteExpiredSessions performs the periodic session cleanup shared by the
// services. A caller can run it from its own scheduler.
func (s *Store) DeleteExpiredSessions(ctx context.Context) error {
if err := s.validate(); err != nil {
return err
}
if _, err := s.pool.Exec(ctx, `DELETE FROM auth_sessions WHERE expires_at < now()`); err != nil {
return fmt.Errorf("delete expired auth sessions: %w", err)
}
return nil
}
var ErrUserExists = errors.New("auth user already exists")
func (s *Store) validate() error {
if s == nil || s.pool == nil {
return errors.New("auth store has no postgres pool")
}
return nil
}
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,
)
if errors.Is(err, pgx.ErrNoRows) {
return nil, nil
}
if err != nil {
return nil, fmt.Errorf("find auth user: %w", err)
}
return &user, nil
}
-69
View File
@@ -1,69 +0,0 @@
package auth
import (
"strings"
"testing"
"time"
"golang.org/x/crypto/bcrypt"
)
func TestPasswordRoundTrip(t *testing.T) {
hash, err := HashPassword("correct horse battery staple")
if err != nil {
t.Fatalf("HashPassword() error = %v", err)
}
if !VerifyPassword(hash, "correct horse battery staple") {
t.Fatal("VerifyPassword() rejected the original password")
}
if VerifyPassword(hash, "wrong password") {
t.Fatal("VerifyPassword() accepted the wrong password")
}
if cost, err := bcrypt.Cost([]byte(hash)); err != nil || cost != BcryptCost {
t.Fatalf("bcrypt cost = %d, error = %v; want %d", cost, err, BcryptCost)
}
}
func TestNewSessionToken(t *testing.T) {
raw, hash, err := NewSessionToken()
if err != nil {
t.Fatalf("NewSessionToken() error = %v", err)
}
if raw == "" || hash == "" {
t.Fatal("NewSessionToken() returned an empty token or hash")
}
if got := HashToken(raw); got != hash {
diff := got
t.Fatalf("HashToken(raw) = %q, want %q", diff, hash)
}
}
func TestResetManagerRoundTrip(t *testing.T) {
manager := NewResetManager()
code, err := manager.Request()
if err != nil {
t.Fatalf("Request() error = %v", err)
}
if len(code) != 8 || strings.ToUpper(code) != code {
t.Fatalf("reset code = %q, want eight uppercase characters", code)
}
if !manager.Confirm(" " + strings.ToLower(code) + " ") {
t.Fatal("Confirm() rejected a valid reset code")
}
if manager.Confirm(code) {
t.Fatal("Confirm() accepted a reset code twice")
}
}
func TestResetManagerExpiresCode(t *testing.T) {
manager := NewResetManager()
if _, err := manager.Request(); err != nil {
t.Fatalf("Request() error = %v", err)
}
manager.mu.Lock()
manager.expiresAt = time.Now().Add(-time.Second)
manager.mu.Unlock()
if manager.Confirm("anything") {
t.Fatal("Confirm() accepted an expired reset code")
}
}
-25
View File
@@ -1,25 +0,0 @@
package auth
import (
"crypto/rand"
"crypto/sha256"
"encoding/base64"
)
// NewSessionToken creates a random bearer token and its SHA-256 storage hash.
// Store only the hash; return the raw token to the caller that sets the cookie
// or authorization header.
func NewSessionToken() (raw string, hash string, err error) {
bytes := make([]byte, 32)
if _, err := rand.Read(bytes); err != nil {
return "", "", err
}
raw = base64.RawURLEncoding.EncodeToString(bytes)
return raw, HashToken(raw), nil
}
// HashToken creates the stable database key for a raw session/API token.
func HashToken(raw string) string {
sum := sha256.Sum256([]byte(raw))
return base64.RawURLEncoding.EncodeToString(sum[:])
}
-104
View File
@@ -1,104 +0,0 @@
package auth
import (
"crypto/hmac"
"crypto/rand"
"crypto/sha1"
"crypto/subtle"
"encoding/base32"
"encoding/binary"
"fmt"
"net/url"
"strconv"
"strings"
"time"
)
// TOTP follows RFC 6238's default interoperable profile.
const (
TOTPPeriod = 30 * time.Second
TOTPDigits = 6
TOTPSecretBytes = 20
TOTPWindow = 1
TOTPSecretLength = 32
)
// GenerateTOTPSecret returns a base32 secret suitable for authenticator apps.
func GenerateTOTPSecret() (string, error) {
raw := make([]byte, TOTPSecretBytes)
if _, err := rand.Read(raw); err != nil {
return "", fmt.Errorf("generate TOTP secret: %w", err)
}
return base32.StdEncoding.WithPadding(base32.NoPadding).EncodeToString(raw), nil
}
// TOTPProvisioningURI builds the otpauth URI accepted by common authenticator apps.
func TOTPProvisioningURI(issuer, account, secret string) string {
issuer = strings.TrimSpace(issuer)
account = strings.TrimSpace(account)
secret = normalizeTOTPSecret(secret)
label := account
if issuer != "" {
label = issuer + ":" + account
}
query := url.Values{}
query.Set("secret", secret)
if issuer != "" {
query.Set("issuer", issuer)
}
query.Set("algorithm", "SHA1")
query.Set("digits", strconv.Itoa(TOTPDigits))
query.Set("period", strconv.Itoa(int(TOTPPeriod/time.Second)))
return "otpauth://totp/" + url.PathEscape(label) + "?" + query.Encode()
}
// VerifyTOTP checks a six-digit token with a one-period clock-skew window.
func VerifyTOTP(secret, token string, now time.Time) bool {
secret = normalizeTOTPSecret(secret)
token = normalizeTOTPToken(token)
if secret == "" || len(token) != TOTPDigits {
return false
}
key, err := base32.StdEncoding.WithPadding(base32.NoPadding).DecodeString(secret)
if err != nil || len(key) == 0 {
return false
}
period := now.Unix() / int64(TOTPPeriod/time.Second)
for offset := int64(-TOTPWindow); offset <= TOTPWindow; offset++ {
if period+offset < 0 {
continue
}
var counter [8]byte
binary.BigEndian.PutUint64(counter[:], uint64(period+offset))
hash := hmac.New(sha1.New, key)
_, _ = hash.Write(counter[:])
digest := hash.Sum(nil)
index := digest[len(digest)-1] & 0x0f
value := (uint32(digest[index])&0x7f)<<24 |
uint32(digest[index+1])<<16 |
uint32(digest[index+2])<<8 |
uint32(digest[index+3])
candidate := fmt.Sprintf("%06d", value%1000000)
if subtle.ConstantTimeCompare([]byte(candidate), []byte(token)) == 1 {
return true
}
}
return false
}
func normalizeTOTPSecret(value string) string {
return strings.TrimRight(strings.ReplaceAll(strings.ToUpper(strings.TrimSpace(value)), " ", ""), "=")
}
func normalizeTOTPToken(value string) string {
value = strings.TrimSpace(value)
if len(value) > TOTPDigits {
return ""
}
for _, character := range value {
if character < '0' || character > '9' {
return ""
}
}
return value
}
-32
View File
@@ -1,32 +0,0 @@
package auth
import (
"testing"
"time"
)
func TestVerifyTOTPRFC6238SHA1Vectors(t *testing.T) {
secret := "GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ"
cases := []struct {
unix int64
code string
}{
{unix: 59, code: "287082"},
{unix: 1111111109, code: "081804"},
{unix: 1111111111, code: "050471"},
{unix: 1234567890, code: "005924"},
{unix: 2000000000, code: "279037"},
}
for _, testCase := range cases {
if !VerifyTOTP(secret, testCase.code, time.Unix(testCase.unix, 0)) {
t.Errorf("VerifyTOTP(%d, %q) = false", testCase.unix, testCase.code)
}
}
}
func TestTOTPProvisioningURI(t *testing.T) {
uri := TOTPProvisioningURI("Example App", "admin@example.com", "abc123")
if uri == "" || len(uri) < len("otpauth://totp/") || uri[:15] != "otpauth://totp/" {
t.Fatalf("unexpected provisioning URI: %q", uri)
}
}
-71
View File
@@ -1,71 +0,0 @@
// Package config contains small, dependency-free environment helpers shared
// by the Go services. It intentionally does not define an application's full
// configuration struct.
package config
import (
"fmt"
"os"
"strconv"
"strings"
"time"
)
// String returns the environment value or fallback when the variable is empty.
func String(key, fallback string) string {
if value := strings.TrimSpace(os.Getenv(key)); value != "" {
return value
}
return fallback
}
// Required returns a trimmed environment value or an actionable error.
func Required(key string) (string, error) {
value := strings.TrimSpace(os.Getenv(key))
if value == "" {
return "", fmt.Errorf("%s is required", key)
}
return value, nil
}
// Bool returns a parsed boolean environment value or fallback for an unset or
// invalid value. Invalid values are deliberately non-fatal for optional flags.
func Bool(key string, fallback bool) bool {
value := strings.TrimSpace(os.Getenv(key))
if value == "" {
return fallback
}
parsed, err := strconv.ParseBool(value)
if err != nil {
return fallback
}
return parsed
}
// Int returns a parsed integer environment value or fallback for an unset or
// invalid value. Callers should validate application-specific ranges.
func Int(key string, fallback int) int {
value := strings.TrimSpace(os.Getenv(key))
if value == "" {
return fallback
}
parsed, err := strconv.Atoi(value)
if err != nil {
return fallback
}
return parsed
}
// Duration returns a parsed duration environment value or fallback for an
// unset or invalid value.
func Duration(key string, fallback time.Duration) time.Duration {
value := strings.TrimSpace(os.Getenv(key))
if value == "" {
return fallback
}
parsed, err := time.ParseDuration(value)
if err != nil {
return fallback
}
return parsed
}
-20
View File
@@ -1,20 +0,0 @@
module repos.gfranz.ch/Gabriel20xx/shared/backend
go 1.25.7
require (
github.com/jackc/pgx/v5 v5.10.0
github.com/pressly/goose/v3 v3.27.3
golang.org/x/crypto v0.54.0
)
require (
github.com/jackc/pgpassfile v1.0.0 // indirect
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect
github.com/jackc/puddle/v2 v2.2.2 // indirect
github.com/mfridman/interpolate v0.0.2 // indirect
github.com/sethvargo/go-retry v0.4.0 // indirect
go.uber.org/multierr v1.11.0 // indirect
golang.org/x/sync v0.22.0 // indirect
golang.org/x/text v0.40.0 // indirect
)
-56
View File
@@ -1,56 +0,0 @@
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/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=
github.com/jackc/pgpassfile v1.0.0/go.mod h1:CEx0iS5ambNFdcRtxPj5JhEz+xB6uRky5eyVu/W2HEg=
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 h1:iCEnooe7UlwOQYpKFhBabPMi4aNAfoODPEFNiAnClxo=
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761/go.mod h1:5TJZWKEWniPve33vlWYSoGYefn3gLQRzjfDlhSJ9ZKM=
github.com/jackc/pgx/v5 v5.10.0 h1:VhSvgU2jSli8o3AqIEOTJr7rZwAEUVo4E4XhR94Zfr0=
github.com/jackc/pgx/v5 v5.10.0/go.mod h1:mal1tBGAFfLHvZzaYh77YS/eC6IX9OWbRV1QIIM0Jn4=
github.com/jackc/puddle/v2 v2.2.2 h1:PR8nw+E/1w0GLuRFSmiioY6UooMp6KJv0/61nB7icHo=
github.com/jackc/puddle/v2 v2.2.2/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4=
github.com/mattn/go-isatty v0.0.23 h1:cYwCQTQf3HB6xUC+BtyCLZNr7IzbOmoZbmssVNzSyiQ=
github.com/mattn/go-isatty v0.0.23/go.mod h1:nMCL3Zebbrt45jsMDgnfIwz6ydEQApk5oEI3HqDio6A=
github.com/mfridman/interpolate v0.0.2 h1:pnuTK7MQIxxFz1Gr+rjSIx9u7qVjf5VOoM/u6BbAxPY=
github.com/mfridman/interpolate v0.0.2/go.mod h1:p+7uk6oE07mpE/Ik1b8EckO0O4ZXiGAfshKBWLUM9Xg=
github.com/ncruces/go-strftime v1.0.0 h1:HMFp8mLCTPp341M/ZnA4qaf7ZlsbTc+miZjCLOFAw7w=
github.com/ncruces/go-strftime v1.0.0/go.mod h1:Fwc5htZGVVkseilnfgOVb9mKy6w1naJmn9CehxcKcls=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/pressly/goose/v3 v3.27.3 h1:pIglVHjw99r4e/hDHHwbl9vfOsDMqUokfkXo6+n/RxA=
github.com/pressly/goose/v3 v3.27.3/go.mod h1:Dag+xpV6o20HR2LFY1j0q6MDwc3f7vPUFDA77R+0yGY=
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec h1:W09IVJc94icq4NjY3clb7Lk8O1qJ8BdBEF8z0ibU0rE=
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo=
github.com/sethvargo/go-retry v0.4.0 h1:9qy1OoIAxBL+gBYnkTnTnWle5wlfsXQlwRzIbbpdqPw=
github.com/sethvargo/go-retry v0.4.0/go.mod h1:tvsjdKG6xfiCx4LSiUZ06kcv38xvdVQwv8R6/VnnVWg=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=
github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=
go.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0=
go.uber.org/multierr v1.11.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y=
golang.org/x/crypto v0.54.0 h1:YLIA59K4fiNzHzjnZt2tUJQjQtUWfWbeHBqKtk3eScw=
golang.org/x/crypto v0.54.0/go.mod h1:KWL8ny2AZdGR2cWmzeHrp2azQPGogOv+HeQaVEXC2dk=
golang.org/x/sync v0.22.0 h1:SZjpbeLmrCk4xhRSZFNZW5gFUeCeFgjekvI/+gfScek=
golang.org/x/sync v0.22.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0=
golang.org/x/sys v0.47.0 h1:o7XGOvZQCADBQQ4Y7VNq2dRWQR7JmOUW8Kxx4ZsNgWs=
golang.org/x/sys v0.47.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
golang.org/x/text v0.40.0 h1:Ub2Z6/xjgF1WrYQz2nuITOEegKFtiIy+rieRJ5lHZKs=
golang.org/x/text v0.40.0/go.mod h1:hpnzDAfGV753zIKo+wk3u1bVKCGPbrnF7+7LBF/UHVY=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
modernc.org/libc v1.74.3 h1:a4J+Z8aVaxPyjyxRAdJzw246PqpcFGvVPnfT/AuM5Ws=
modernc.org/libc v1.74.3/go.mod h1:4H7h/MJ8wnjL8RAbp9v3OXgnk22X7MouHIhDbvP3gj4=
modernc.org/mathutil v1.7.1 h1:GCZVGXdaN8gTqB1Mf/usp1Y/hSqgI2vAGGP4jZMCxOU=
modernc.org/mathutil v1.7.1/go.mod h1:4p5IwJITfppl0G4sUEDtCr4DthTaT47/N3aT6MhfgJg=
modernc.org/memory v1.11.0 h1:o4QC8aMQzmcwCK3t3Ux/ZHmwFPzE6hf2Y5LbkRs+hbI=
modernc.org/memory v1.11.0/go.mod h1:/JP4VbVC+K5sU2wZi9bHoq2MAkCnrt2r98UGeSK7Mjw=
modernc.org/sqlite v1.54.0 h1:JCxR4qwkJvOaqAoYcgDoO25Nc+ROg6EJ2LfBVzdrgog=
modernc.org/sqlite v1.54.0/go.mod h1:4ntCLuNmnH8+GNqjka1wNg7KJd5/Hi5FYp8K+XQ7GZw=
-42
View File
@@ -1,42 +0,0 @@
// Package migrate provides a small embedded-filesystem wrapper around Goose.
// Applications still own their SQL files and migration policy.
package migrate
import (
"context"
"database/sql"
"fmt"
"io/fs"
_ "github.com/jackc/pgx/v5/stdlib"
"github.com/pressly/goose/v3"
)
// Up applies all pending PostgreSQL migrations in migrationsFS/dir. The
// filesystem is normally an embed.FS supplied by the consuming application.
func Up(ctx context.Context, databaseURL string, migrationsFS fs.FS, dir string) error {
if databaseURL == "" {
return fmt.Errorf("database URL is required")
}
if migrationsFS == nil {
return fmt.Errorf("migration filesystem is required")
}
db, err := sql.Open("pgx", databaseURL)
if err != nil {
return fmt.Errorf("open migration database: %w", err)
}
defer db.Close()
if err := db.PingContext(ctx); err != nil {
return fmt.Errorf("ping migration database: %w", err)
}
goose.SetBaseFS(migrationsFS)
if err := goose.SetDialect("postgres"); err != nil {
return fmt.Errorf("set migration dialect: %w", err)
}
if err := goose.UpContext(ctx, db, dir); err != nil {
return fmt.Errorf("run migrations: %w", err)
}
return nil
}
-153
View File
@@ -1,153 +0,0 @@
// Package postgres centralizes PostgreSQL pool creation and the small pieces
// of error/transaction handling that are repeated by the Go services.
package postgres
import (
"context"
"errors"
"fmt"
"strings"
"time"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgconn"
"github.com/jackc/pgx/v5/pgxpool"
"repos.gfranz.ch/Gabriel20xx/shared/backend/config"
)
// Config controls a shared pgx connection pool. URL is normally read from
// DATABASE_URL with FromEnv.
type Config struct {
URL string
MaxConns int32
MinConns int32
MaxConnLifetime time.Duration
MaxConnIdleTime time.Duration
HealthCheckPeriod time.Duration
ConnectTimeout time.Duration
}
// DefaultConfig returns sensible defaults for a small self-hosted service.
func DefaultConfig(url string) Config {
return Config{
URL: strings.TrimSpace(url),
MaxConns: 20,
MinConns: 0,
MaxConnLifetime: time.Hour,
MaxConnIdleTime: 30 * time.Minute,
HealthCheckPeriod: 30 * time.Second,
ConnectTimeout: 10 * time.Second,
}
}
// FromEnv loads DATABASE_URL and optional pool settings. Duration values use
// Go duration syntax, for example 30s or 1h. Invalid optional values fall back
// to defaults; the URL is the only required setting.
func FromEnv() (Config, error) {
url, err := config.Required("DATABASE_URL")
if err != nil {
return Config{}, err
}
cfg := DefaultConfig(url)
cfg.MaxConns = int32(config.Int("DATABASE_MAX_CONNS", int(cfg.MaxConns)))
cfg.MinConns = int32(config.Int("DATABASE_MIN_CONNS", int(cfg.MinConns)))
cfg.MaxConnLifetime = config.Duration("DATABASE_MAX_CONN_LIFETIME", cfg.MaxConnLifetime)
cfg.MaxConnIdleTime = config.Duration("DATABASE_MAX_CONN_IDLE_TIME", cfg.MaxConnIdleTime)
cfg.HealthCheckPeriod = config.Duration("DATABASE_HEALTH_CHECK_PERIOD", cfg.HealthCheckPeriod)
cfg.ConnectTimeout = config.Duration("DATABASE_CONNECT_TIMEOUT", cfg.ConnectTimeout)
if cfg.MaxConns < 1 {
return Config{}, fmt.Errorf("DATABASE_MAX_CONNS must be at least 1")
}
if cfg.MinConns < 0 || cfg.MinConns > cfg.MaxConns {
return Config{}, fmt.Errorf("DATABASE_MIN_CONNS must be between 0 and DATABASE_MAX_CONNS")
}
if cfg.ConnectTimeout <= 0 {
return Config{}, fmt.Errorf("DATABASE_CONNECT_TIMEOUT must be greater than 0")
}
return cfg, nil
}
// Open creates and verifies a PostgreSQL pool. A failed ping closes the pool
// before returning so callers do not leak connections during startup errors.
func Open(ctx context.Context, cfg Config) (*pgxpool.Pool, error) {
if strings.TrimSpace(cfg.URL) == "" {
return nil, errors.New("postgres URL is required")
}
poolConfig, err := pgxpool.ParseConfig(cfg.URL)
if err != nil {
return nil, fmt.Errorf("parse postgres URL: %w", err)
}
if cfg.MaxConns > 0 {
poolConfig.MaxConns = cfg.MaxConns
}
if cfg.MinConns >= 0 {
poolConfig.MinConns = cfg.MinConns
}
if cfg.MaxConnLifetime > 0 {
poolConfig.MaxConnLifetime = cfg.MaxConnLifetime
}
if cfg.MaxConnIdleTime > 0 {
poolConfig.MaxConnIdleTime = cfg.MaxConnIdleTime
}
if cfg.HealthCheckPeriod > 0 {
poolConfig.HealthCheckPeriod = cfg.HealthCheckPeriod
}
if cfg.ConnectTimeout > 0 {
poolConfig.ConnConfig.ConnectTimeout = cfg.ConnectTimeout
}
pool, err := pgxpool.NewWithConfig(ctx, poolConfig)
if err != nil {
return nil, fmt.Errorf("create postgres pool: %w", err)
}
if err := pool.Ping(ctx); err != nil {
pool.Close()
return nil, fmt.Errorf("ping postgres: %w", 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 {
return errors.New("postgres pool is nil")
}
if fn == nil {
return errors.New("postgres transaction callback is nil")
}
tx, err := pool.Begin(ctx)
if err != nil {
return fmt.Errorf("begin postgres transaction: %w", err)
}
defer func() { _ = tx.Rollback(ctx) }()
if err := fn(tx); err != nil {
return err
}
if err := tx.Commit(ctx); err != nil {
return fmt.Errorf("commit postgres transaction: %w", err)
}
return nil
}
// IsNoRows reports whether err is pgx's not-found sentinel.
func IsNoRows(err error) bool {
return errors.Is(err, pgx.ErrNoRows)
}
// IsUniqueViolation reports a PostgreSQL unique/exclusion constraint error.
func IsUniqueViolation(err error) bool {
var pgErr *pgconn.PgError
return errors.As(err, &pgErr) && (pgErr.Code == "23505" || pgErr.Code == "23P01")
}
// IsForeignKeyViolation reports a PostgreSQL foreign-key constraint error.
func IsForeignKeyViolation(err error) bool {
var pgErr *pgconn.PgError
return errors.As(err, &pgErr) && pgErr.Code == "23503"
}
@@ -1,31 +0,0 @@
package postgres
import (
"os"
"testing"
)
func TestFromEnvRequiresDatabaseURL(t *testing.T) {
t.Setenv("DATABASE_URL", "")
if _, err := FromEnv(); err == nil {
t.Fatal("FromEnv() returned nil error without DATABASE_URL")
}
}
func TestFromEnvLoadsPoolSettings(t *testing.T) {
t.Setenv("DATABASE_URL", "postgres://user:password@localhost:5432/app")
t.Setenv("DATABASE_MAX_CONNS", "7")
t.Setenv("DATABASE_MIN_CONNS", "2")
defer func() {
_ = os.Unsetenv("DATABASE_MAX_CONNS")
_ = os.Unsetenv("DATABASE_MIN_CONNS")
}()
cfg, err := FromEnv()
if err != nil {
t.Fatalf("FromEnv() error = %v", err)
}
if cfg.MaxConns != 7 || cfg.MinConns != 2 {
t.Fatalf("pool limits = (%d, %d), want (7, 2)", cfg.MaxConns, cfg.MinConns)
}
}
-3149
View File
File diff suppressed because it is too large. Load diff
-56
View File
@@ -1,56 +0,0 @@
{
"name": "@gabriel20xx/shared-code",
"version": "0.1.1",
"description": "Shared UI and backend packages for Gabriel20xx projects.",
"license": "MIT",
"repository": {
"type": "git",
"url": "https://repos.gfranz.ch/Gabriel20xx/shared"
},
"type": "module",
"files": [
"README.md",
"shared-styles.css",
"packages/web-ui/dist",
"packages/design-tokens",
"packages/node-backend/src"
],
"exports": {
".": "./README.md",
"./web-ui": {
"types": "./packages/web-ui/dist/index.d.ts",
"svelte": "./packages/web-ui/dist/index.js",
"import": "./packages/web-ui/dist/index.js"
},
"./web-ui/styles.css": "./shared-styles.css",
"./design-tokens": "./packages/design-tokens/theme.css",
"./design-tokens/theme.css": "./packages/design-tokens/theme.css",
"./node-backend": "./packages/node-backend/src/index.js",
"./node-backend/config": "./packages/node-backend/src/config.js",
"./node-backend/db": "./packages/node-backend/src/db.js",
"./node-backend/auth": "./packages/node-backend/src/auth.js",
"./node-backend/migrate": "./packages/node-backend/src/migrate.js"
},
"workspaces": [
"packages/*"
],
"scripts": {
"check": "npm run check --workspace=@gabriel20xx/web-ui",
"build": "npm run package --workspace=@gabriel20xx/web-ui",
"package": "npm run package --workspace=@gabriel20xx/web-ui",
"lint": "npm run check && npm run lint:node",
"lint:node": "node scripts/check-node-syntax.mjs",
"test": "npm run build && npm run test:node-backend",
"test:node-backend": "npm test --workspace=@gabriel20xx/node-backend",
"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"
},
"dependencies": {
"pg": "^8.17.2"
},
"devDependencies": {
"@changesets/cli": "^2.29.8"
}
}
@@ -1,3 +0,0 @@
# `@gabriel20xx/design-tokens`
The package exports `theme.css`. Import it directly when an application needs only the shared tokens, or use `@gabriel20xx/web-ui/styles.css`, which imports it automatically.
@@ -1,17 +0,0 @@
{
"name": "@gabriel20xx/design-tokens",
"version": "0.1.1",
"description": "Shared visual tokens for Gabriel20xx web projects.",
"license": "MIT",
"files": [
"theme.css",
"README.md"
],
"exports": {
".": {
"default": "./theme.css"
},
"./theme.css": "./theme.css",
"./package.json": "./package.json"
}
}
@@ -1,68 +0,0 @@
:root,
[data-theme='dark'] {
color-scheme: dark;
--sc-bg: #0b1020;
--sc-surface: #121a2d;
--sc-surface-raised: #18233b;
--sc-surface-hover: #202d49;
--sc-border: #2d3b59;
--sc-border-strong: #405273;
--sc-fg: #f4f7fb;
--sc-muted-fg: #a8b4c7;
--sc-subtle-fg: #74839d;
--sc-primary: #7c9cff;
--sc-primary-hover: #94adff;
--sc-primary-fg: #081127;
--sc-secondary: #253452;
--sc-secondary-hover: #304363;
--sc-secondary-fg: #e8eefb;
--sc-accent: #61d5c7;
--sc-accent-fg: #06201d;
--sc-danger: #ef767a;
--sc-danger-hover: #f58d90;
--sc-danger-fg: #2d0809;
--sc-success: #70d69d;
--sc-success-fg: #062012;
--sc-warning: #f3c969;
--sc-warning-fg: #241a02;
--sc-ring: #9fb4ff;
--sc-backdrop: rgb(2 6 23 / 72%);
--sc-radius-sm: 0.375rem;
--sc-radius-md: 0.625rem;
--sc-radius-lg: 0.875rem;
--sc-radius-xl: 1.125rem;
--sc-font-sans: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
--sc-font-mono: "SFMono-Regular", Consolas, "Liberation Mono", monospace;
--sc-shadow-sm: 0 2px 8px rgb(0 0 0 / 14%);
--sc-shadow-lg: 0 20px 60px rgb(0 0 0 / 32%);
}
[data-theme='light'] {
color-scheme: light;
--sc-bg: #f5f7fb;
--sc-surface: #ffffff;
--sc-surface-raised: #ffffff;
--sc-surface-hover: #eef2f8;
--sc-border: #d7deea;
--sc-border-strong: #b7c2d4;
--sc-fg: #172033;
--sc-muted-fg: #53627a;
--sc-subtle-fg: #74839d;
--sc-primary: #466ee8;
--sc-primary-hover: #345bd4;
--sc-primary-fg: #ffffff;
--sc-secondary: #e7edf8;
--sc-secondary-hover: #dbe4f3;
--sc-secondary-fg: #1d2b44;
--sc-accent: #168f83;
--sc-accent-fg: #ffffff;
--sc-danger: #cf3d45;
--sc-danger-hover: #b93139;
--sc-danger-fg: #ffffff;
--sc-success: #208751;
--sc-success-fg: #ffffff;
--sc-warning: #a66e00;
--sc-warning-fg: #ffffff;
--sc-ring: #466ee8;
--sc-backdrop: rgb(15 23 42 / 42%);
}
@@ -1,58 +0,0 @@
package com.gabriel20xx.shared.auth;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.SecureRandom;
import java.util.Locale;
/** Shared short-lived, one-time admin reset-code primitive for Java services. */
public final class ResetManager {
private static final long RESET_CODE_TTL_MILLIS = 5L * 60L * 1000L;
private static final SecureRandom RANDOM = new SecureRandom();
private String code;
private long expiresAtMillis;
/** Creates and prints a new reset code, invalidating any previous code. */
public synchronized String request() {
byte[] raw = new byte[4];
RANDOM.nextBytes(raw);
StringBuilder generated = new StringBuilder(raw.length * 2);
for (byte value : raw) {
generated.append(String.format(Locale.ROOT, "%02X", value & 0xff));
}
code = generated.toString();
expiresAtMillis = System.currentTimeMillis() + RESET_CODE_TTL_MILLIS;
System.out.println("\n==================================================\n"
+ "ADMIN RESET CODE: " + code + "\n"
+ "Expires in 5 minutes. Enter it on the login page.\n"
+ "==================================================\n");
return code;
}
/** Validates and consumes the current code. Invalid codes remain retryable. */
public synchronized boolean confirm(String candidate) {
if (code == null) {
return false;
}
if (System.currentTimeMillis() > expiresAtMillis) {
clear();
return false;
}
String normalized = candidate == null ? "" : candidate.trim().toUpperCase(Locale.ROOT);
boolean matches = MessageDigest.isEqual(
code.getBytes(StandardCharsets.US_ASCII),
normalized.getBytes(StandardCharsets.US_ASCII));
if (matches) {
clear();
}
return matches;
}
private void clear() {
code = null;
expiresAtMillis = 0L;
}
}
@@ -1,29 +0,0 @@
package com.gabriel20xx.shared.auth;
import java.util.Locale;
/** Shared account-management roles used by Java web services. */
public final class Roles {
public static final String SUPERADMIN = "superadmin";
public static final String ADMIN = "admin";
public static final String USER = "user";
private Roles() {
}
public static String normalize(String value) {
String normalized = value == null ? "" : value.trim().toLowerCase(Locale.ROOT);
if (SUPERADMIN.equals(normalized)) return SUPERADMIN;
if (ADMIN.equals(normalized)) return ADMIN;
return USER;
}
public static boolean canManageUsers(String role) {
String normalized = normalize(role);
return SUPERADMIN.equals(normalized) || ADMIN.equals(normalized);
}
public static boolean canAssignRole(String actorRole, String targetRole) {
return SUPERADMIN.equals(normalize(actorRole)) && !SUPERADMIN.equals(normalize(targetRole));
}
}
@@ -1,143 +0,0 @@
package com.gabriel20xx.shared.auth;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.security.SecureRandom;
import java.util.Locale;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
/** RFC 6238 TOTP primitives shared by Java services. */
public final class Totp {
private static final String BASE32 = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";
private static final int SECRET_BYTES = 20;
private static final int PERIOD_SECONDS = 30;
private static final int WINDOW = 1;
private static final int DIGITS = 6;
private static final SecureRandom RANDOM = new SecureRandom();
private Totp() {
}
public static String generateSecret() {
byte[] raw = new byte[SECRET_BYTES];
RANDOM.nextBytes(raw);
return encodeBase32(raw);
}
public static String provisioningUri(String issuer, String account, String secret) {
String normalizedIssuer = issuer == null ? "" : issuer.trim();
String normalizedAccount = account == null ? "" : account.trim();
String label = normalizedIssuer.isEmpty()
? normalizedAccount
: normalizedIssuer + ":" + normalizedAccount;
StringBuilder uri = new StringBuilder("otpauth://totp/")
.append(urlEncode(label))
.append("?secret=").append(normalizeSecret(secret));
if (!normalizedIssuer.isEmpty()) {
uri.append("&issuer=").append(urlEncode(normalizedIssuer));
}
return uri.append("&algorithm=SHA1&digits=").append(DIGITS)
.append("&period=").append(PERIOD_SECONDS).toString();
}
public static boolean verify(String secret, String token, long nowMillis) {
String normalizedSecret = normalizeSecret(secret);
String normalizedToken = token == null ? "" : token.trim();
if (normalizedSecret.isEmpty() || !normalizedToken.matches("\\d{" + DIGITS + "}")) {
return false;
}
byte[] key;
try {
key = decodeBase32(normalizedSecret);
} catch (IllegalArgumentException ex) {
return false;
}
if (key.length == 0) {
return false;
}
long counter = Math.floorDiv(nowMillis, PERIOD_SECONDS * 1000L);
for (long offset = -WINDOW; offset <= WINDOW; offset++) {
if (counter + offset < 0) {
continue;
}
try {
byte[] message = new byte[8];
long value = counter + offset;
for (int index = 7; index >= 0; index--) {
message[index] = (byte) (value & 0xff);
value >>>= 8;
}
Mac mac = Mac.getInstance("HmacSHA1");
mac.init(new SecretKeySpec(key, "HmacSHA1"));
byte[] hash = mac.doFinal(message);
int index = hash[hash.length - 1] & 0x0f;
int code = ((hash[index] & 0x7f) << 24)
| ((hash[index + 1] & 0xff) << 16)
| ((hash[index + 2] & 0xff) << 8)
| (hash[index + 3] & 0xff);
String candidate = String.format(Locale.ROOT, "%06d", code % 1_000_000);
if (candidate.equals(normalizedToken)) {
return true;
}
} catch (Exception ex) {
return false;
}
}
return false;
}
private static String normalizeSecret(String value) {
return value == null ? "" : value.trim().replace(" ", "").replace("=", "").toUpperCase(Locale.ROOT);
}
private static String encodeBase32(byte[] bytes) {
StringBuilder result = new StringBuilder((bytes.length * 8 + 4) / 5);
int buffer = 0;
int bits = 0;
for (byte value : bytes) {
buffer = (buffer << 8) | (value & 0xff);
bits += 8;
while (bits >= 5) {
bits -= 5;
result.append(BASE32.charAt((buffer >>> bits) & 31));
}
}
if (bits > 0) {
result.append(BASE32.charAt((buffer << (5 - bits)) & 31));
}
return result.toString();
}
private static byte[] decodeBase32(String value) {
int outputLength = value.length() * 5 / 8;
byte[] result = new byte[outputLength];
int buffer = 0;
int bits = 0;
int output = 0;
for (int index = 0; index < value.length(); index++) {
int digit = BASE32.indexOf(value.charAt(index));
if (digit < 0) {
throw new IllegalArgumentException("Invalid base32 secret");
}
buffer = (buffer << 5) | digit;
bits += 5;
while (bits >= 8) {
bits -= 8;
if (output < result.length) {
result[output++] = (byte) ((buffer >>> bits) & 0xff);
}
}
buffer &= bits == 0 ? 0 : (1 << bits) - 1;
}
return result;
}
private static String urlEncode(String value) {
try {
return URLEncoder.encode(value, StandardCharsets.UTF_8.name()).replace("+", "%20");
} catch (Exception ex) {
throw new IllegalArgumentException("Unable to encode provisioning URI", ex);
}
}
}
@@ -1,20 +0,0 @@
# `@gabriel20xx/node-backend`
Shared Node.js backend infrastructure for services that use PostgreSQL:
- validated `DATABASE_URL` and pool settings;
- one pool owner with startup retry, transient query retry, transactions, and shutdown;
- PBKDF2 password hashing and secure session-token helpers;
- short-lived, one-time admin reset codes printed to the server console;
- common account/session persistence;
- transaction-locked ordered migrations.
The package does not depend on Express. Each service keeps its own routes,
cookies, roles, validation policy, and domain repositories. Existing
`MediaShared` code can be migrated into this package incrementally; keep the
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`.
@@ -1,29 +0,0 @@
{
"name": "@gabriel20xx/node-backend",
"version": "0.1.1",
"description": "Shared PostgreSQL, configuration, migration, and authentication primitives for Node.js services.",
"license": "MIT",
"type": "module",
"files": [
"src",
"test",
"README.md"
],
"exports": {
".": "./src/index.js",
"./config": "./src/config.js",
"./db": "./src/db.js",
"./auth": "./src/auth.js",
"./migrate": "./src/migrate.js",
"./package.json": "./package.json"
},
"dependencies": {
"pg": "^8.17.2"
},
"scripts": {
"test": "node --test"
},
"engines": {
"node": ">=20"
}
}
@@ -1,303 +0,0 @@
import crypto from 'node:crypto';
const PASSWORD_ITERATIONS = 100000;
const PASSWORD_KEY_LENGTH = 32;
const PASSWORD_DIGEST = 'sha256';
export const RESET_CODE_TTL_MS = 5 * 60 * 1000;
export const USER_ROLES = Object.freeze({ SUPERADMIN: 'superadmin', ADMIN: 'admin', USER: 'user' });
export function normalizeRole(value) {
const normalized = String(value ?? '').trim().toLowerCase();
return normalized === USER_ROLES.SUPERADMIN || normalized === USER_ROLES.ADMIN ? normalized : USER_ROLES.USER;
}
export function canManageUsers(role) {
const normalized = normalizeRole(role);
return normalized === USER_ROLES.SUPERADMIN || normalized === USER_ROLES.ADMIN;
}
export function canAssignRole(actorRole, targetRole) {
return normalizeRole(actorRole) === USER_ROLES.SUPERADMIN && normalizeRole(targetRole) !== USER_ROLES.SUPERADMIN;
}
export const AUTH_SCHEMA = `
CREATE TABLE IF NOT EXISTS auth_users (
id BIGSERIAL PRIMARY KEY,
username TEXT NOT NULL UNIQUE,
email TEXT NOT NULL DEFAULT '',
password_hash TEXT NOT NULL,
role TEXT NOT NULL DEFAULT 'user',
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()
);
ALTER TABLE auth_users ADD COLUMN IF NOT EXISTS email TEXT NOT NULL DEFAULT '';
ALTER TABLE auth_users ADD COLUMN IF NOT EXISTS role TEXT NOT NULL DEFAULT 'user';
ALTER TABLE auth_users ADD COLUMN IF NOT EXISTS totp_secret TEXT NOT NULL DEFAULT '';
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();
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');
CREATE UNIQUE INDEX IF NOT EXISTS auth_users_email_idx ON auth_users (lower(email)) WHERE email <> '';
CREATE TABLE IF NOT EXISTS auth_sessions (
id BIGSERIAL PRIMARY KEY,
user_id BIGINT NOT NULL REFERENCES auth_users(id) ON DELETE CASCADE,
token_hash TEXT NOT NULL UNIQUE,
expires_at TIMESTAMPTZ NOT NULL,
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
CREATE INDEX IF NOT EXISTS auth_sessions_expiry_idx ON auth_sessions (expires_at);
CREATE INDEX IF NOT EXISTS auth_sessions_user_idx ON auth_sessions (user_id);
`;
export function hashPassword(password, { iterations = PASSWORD_ITERATIONS } = {}) {
if (typeof password !== 'string' || password.length < 8) {
throw new Error('Password must be at least 8 characters');
}
const salt = crypto.randomBytes(16).toString('hex');
const hash = crypto.pbkdf2Sync(password, salt, iterations, PASSWORD_KEY_LENGTH, PASSWORD_DIGEST);
return `${salt}:${hash.toString('hex')}`;
}
export function verifyPassword(password, stored) {
try {
const [salt, expected] = String(stored).split(':');
if (!salt || !expected) return false;
const actual = crypto.pbkdf2Sync(
String(password),
salt,
PASSWORD_ITERATIONS,
PASSWORD_KEY_LENGTH,
PASSWORD_DIGEST
);
const expectedBytes = Buffer.from(expected, 'hex');
return expectedBytes.length === actual.length && crypto.timingSafeEqual(expectedBytes, actual);
} catch {
return false;
}
}
export function createSessionToken() {
const token = crypto.randomBytes(32).toString('base64url');
return { token, tokenHash: hashToken(token) };
}
export function hashToken(token) {
return crypto.createHash('sha256').update(String(token)).digest('hex');
}
/**
* Creates and validates the short-lived, one-time code used by the public
* "reset admin account" flow. Account deletion stays with the application
* because its account table and session policy may differ.
*/
export class ResetManager {
constructor({ ttlMs = RESET_CODE_TTL_MS, log = console.log } = {}) {
this.ttlMs = ttlMs;
this.log = log;
this.code = null;
this.expiresAt = 0;
}
request() {
this.code = crypto.randomBytes(4).toString('hex').toUpperCase();
this.expiresAt = Date.now() + this.ttlMs;
this.log(
`\n${'='.repeat(50)}\nADMIN RESET CODE: ${this.code}\nExpires in 5 minutes. Enter it on the login page.\n${'='.repeat(50)}\n`,
);
return this.code;
}
confirm(candidate) {
if (!this.code) return false;
if (Date.now() > this.expiresAt) {
this.code = null;
this.expiresAt = 0;
return false;
}
const normalized = String(candidate ?? '').trim().toUpperCase();
const expected = Buffer.from(this.code);
const actual = Buffer.from(normalized);
const valid = expected.length === actual.length && crypto.timingSafeEqual(expected, actual);
if (!valid) return false;
this.code = null;
this.expiresAt = 0;
return true;
}
}
/** Persistence-only auth store; cookies, roles, and HTTP policy stay in the app. */
export class AuthStore {
constructor(database, { singleUser = true } = {}) {
if (!database || typeof database.query !== 'function') {
throw new TypeError('AuthStore requires a Database-like query object');
}
this.database = database;
this.singleUser = singleUser;
}
async ensureSchema() {
await this.database.query(AUTH_SCHEMA);
if (this.singleUser) {
await this.database.query('CREATE UNIQUE INDEX IF NOT EXISTS auth_users_singleton_idx ON auth_users ((true))');
} else {
await this.database.query('DROP INDEX IF EXISTS auth_users_singleton_idx');
}
}
async countUsers() {
const result = await this.database.query('SELECT count(*)::int AS count FROM auth_users');
return result.rows[0].count;
}
async createUser(username, email, passwordHash) {
try {
const result = await this.database.query(
`INSERT INTO auth_users (username, email, password_hash, role, updated_at)
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`,
[username, email, passwordHash]
);
return result.rows[0];
} catch (error) {
if (error?.code === '23505') {
const duplicate = new Error('auth user already exists');
duplicate.code = 'AUTH_USER_EXISTS';
throw duplicate;
}
throw error;
}
}
async findByIdentifier(identifier) {
const result = await this.database.query(
`SELECT id, username, email, password_hash, role, created_at, updated_at
FROM auth_users WHERE username = $1 OR lower(email) = lower($1)`,
[identifier]
);
return result.rows[0] || null;
}
async updateCredentials(id, username, email, passwordHash) {
await this.database.query(
`UPDATE auth_users SET username = $1, email = $2, password_hash = $3, updated_at = now()
WHERE id = $4`,
[username, email, passwordHash, id]
);
}
async createSession(userId, tokenHash, expiresAt) {
await this.database.query(
'INSERT INTO auth_sessions (user_id, token_hash, expires_at) VALUES ($1, $2, $3)',
[userId, tokenHash, expiresAt]
);
}
async findSessionUser(tokenHash) {
const result = await this.database.query(
`SELECT u.id, u.username, u.email, u.password_hash, u.role, u.created_at, u.updated_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()`,
[tokenHash]
);
return result.rows[0] || null;
}
async deleteSession(tokenHash) {
await this.database.query('DELETE FROM auth_sessions WHERE token_hash = $1', [tokenHash]);
}
async deleteSessionsForUser(userId) {
await this.database.query('DELETE FROM auth_sessions WHERE user_id = $1', [userId]);
}
async listUsers() {
const result = await this.database.query(
'SELECT id, username, email, role, created_at, updated_at FROM auth_users ORDER BY created_at, id',
);
return result.rows;
}
async createManagedUser(username, email, passwordHash, role = USER_ROLES.USER) {
try {
const result = await this.database.query(
`INSERT INTO auth_users (username, email, password_hash, role, updated_at)
VALUES ($1, $2, $3, $4, now())
RETURNING id, username, email, role, created_at, updated_at`,
[username, email, passwordHash, normalizeRole(role)],
);
return result.rows[0];
} catch (error) {
if (error?.code === '23505') {
const duplicate = new Error('auth user already exists');
duplicate.code = 'AUTH_USER_EXISTS';
throw duplicate;
}
throw error;
}
}
async updateUser(id, { username, email, passwordHash, role } = {}) {
const fields = [];
const values = [];
const add = (sql, value) => { fields.push(sql); values.push(value); };
if (username !== undefined) add(`username = $${values.length + 1}`, username);
if (email !== undefined) add(`email = $${values.length + 1}`, email);
if (passwordHash !== undefined) add(`password_hash = $${values.length + 1}`, passwordHash);
if (role !== undefined) add(`role = $${values.length + 1}`, normalizeRole(role));
if (fields.length === 0) return;
values.push(id);
await this.database.query(
`UPDATE auth_users SET ${fields.join(', ')}, updated_at = now() WHERE id = $${values.length}`,
values,
);
}
async deleteUser(id) {
await this.database.query('DELETE FROM auth_users WHERE id = $1', [id]);
}
async deleteAllUsers() {
await this.database.query('DELETE FROM auth_users');
}
async getTotpState(userId) {
const result = await this.database.query(
'SELECT COALESCE(totp_secret, \'\') AS secret, COALESCE(totp_enabled, false) AS enabled FROM auth_users WHERE id = $1',
[userId],
);
return result.rows[0] || { secret: '', enabled: false };
}
async setTotpSecret(userId, secret) {
await this.database.query(
'UPDATE auth_users SET totp_secret = $1, totp_enabled = false, updated_at = now() WHERE id = $2',
[secret, userId],
);
}
async enableTotp(userId) {
await this.database.query(
"UPDATE auth_users SET totp_enabled = true, updated_at = now() WHERE id = $1 AND totp_secret <> ''",
[userId],
);
}
async disableTotp(userId) {
await this.database.query(
"UPDATE auth_users SET totp_secret = '', totp_enabled = false, updated_at = now() WHERE id = $1",
[userId],
);
}
async pruneExpiredSessions() {
await this.database.query('DELETE FROM auth_sessions WHERE expires_at < now()');
}
}
@@ -1,55 +0,0 @@
const DEFAULTS = Object.freeze({
max: 20,
min: 0,
connectionTimeoutMillis: 5000,
idleTimeoutMillis: 30000,
queryTimeout: 15000,
});
function positiveInt(value, fallback, minimum = 0) {
const parsed = Number.parseInt(String(value ?? ''), 10);
return Number.isInteger(parsed) && parsed >= minimum ? parsed : fallback;
}
/** Return DATABASE_URL or throw an actionable startup error. */
export function databaseUrlFromEnv(env = process.env) {
const url = String(env.DATABASE_URL || '').trim();
if (!url) {
const error = new Error('DATABASE_URL is required');
error.code = 'DB_NOT_CONFIGURED';
throw error;
}
return url;
}
/** Build a pg.Pool-compatible configuration from environment variables. */
export function databaseConfigFromEnv(env = process.env) {
const max = positiveInt(env.DATABASE_MAX_CONNS, DEFAULTS.max, 1);
const min = positiveInt(env.DATABASE_MIN_CONNS, DEFAULTS.min, 0);
if (min > max) {
throw new Error('DATABASE_MIN_CONNS must not exceed DATABASE_MAX_CONNS');
}
return {
connectionString: databaseUrlFromEnv(env),
max,
min,
connectionTimeoutMillis: positiveInt(
env.DATABASE_CONNECT_TIMEOUT_MS,
DEFAULTS.connectionTimeoutMillis,
1
),
idleTimeoutMillis: positiveInt(
env.DATABASE_IDLE_TIMEOUT_MS,
DEFAULTS.idleTimeoutMillis,
0
),
query_timeout: positiveInt(env.DATABASE_QUERY_TIMEOUT_MS, DEFAULTS.queryTimeout, 1),
ssl:
/^(true|require|1)$/i.test(String(env.DATABASE_SSL || ''))
? { rejectUnauthorized: !/^(true|1)$/i.test(String(env.DATABASE_SSL_ALLOW_INVALID || '')) }
: undefined,
};
}
export { DEFAULTS as DATABASE_DEFAULTS };
@@ -1,92 +0,0 @@
import pg from 'pg';
import { databaseConfigFromEnv } from './config.js';
const { Pool } = pg;
const TRANSIENT_CODES = new Set(['ECONNRESET', 'EPIPE', '57P01', '08006', '08003']);
const TRANSIENT_MESSAGE = /connection terminated|connection reset|econnreset|epipe|server closed the connection/i;
export function isTransientConnectionError(error) {
return Boolean(
error &&
(TRANSIENT_CODES.has(error.code) || TRANSIENT_MESSAGE.test(String(error.message || '')))
);
}
/**
* Owns one pg pool and exposes bounded startup, retry, transaction, and
* shutdown behavior. Domain repositories should depend on this abstraction
* instead of creating independent pools.
*/
export class Database {
constructor(options = {}) {
const { pool, ...poolOptions } = options;
this.pool = pool || new Pool(poolOptions);
this.ownsPool = !pool;
this.ready = false;
}
static fromEnv(env = process.env) {
return new Database(databaseConfigFromEnv(env));
}
async connect({ retries = 10, retryDelayMs = 2000 } = {}) {
if (this.ready) return this;
let lastError;
for (let attempt = 1; attempt <= Math.max(1, retries); 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));
}
}
throw lastError;
}
async query(text, values = []) {
await this.connect();
try {
return await this.pool.query(text, values);
} catch (error) {
if (!isTransientConnectionError(error)) throw error;
return this.pool.query(text, values);
}
}
async transaction(callback) {
if (typeof callback !== 'function') throw new TypeError('transaction callback is required');
await this.connect();
const client = await this.pool.connect();
try {
await client.query('BEGIN');
const result = await callback(client);
await client.query('COMMIT');
return result;
} catch (error) {
try {
await client.query('ROLLBACK');
} catch {
// Preserve the original application error.
}
throw error;
} finally {
client.release();
}
}
async close() {
if (!this.pool || !this.ownsPool) return;
await this.pool.end();
this.ready = false;
}
}
export function createDatabaseFromEnv(env = process.env) {
return Database.fromEnv(env);
}
@@ -1,33 +0,0 @@
export {
databaseConfigFromEnv,
databaseUrlFromEnv,
DATABASE_DEFAULTS,
} from './config.js';
export {
Database,
createDatabaseFromEnv,
isTransientConnectionError,
} from './db.js';
export {
AUTH_SCHEMA,
AuthStore,
RESET_CODE_TTL_MS,
ResetManager,
createSessionToken,
hashPassword,
hashToken,
USER_ROLES,
canAssignRole,
canManageUsers,
normalizeRole,
verifyPassword,
} from './auth.js';
export {
TOTP_DIGITS,
TOTP_PERIOD_SECONDS,
TOTP_WINDOW,
generateTotpSecret,
totpProvisioningUri,
verifyTotp,
} from './totp.js';
export { runMigrations } from './migrate.js';
@@ -1,42 +0,0 @@
/**
* Apply ordered SQL migrations using the shared Database transaction wrapper.
* Each migration is { id: string, up: async (client) => void }.
*/
export async function runMigrations(
database,
migrations,
{ lockKey = 70420320, tableName = 'schema_migrations' } = {}
) {
if (!database || typeof database.transaction !== 'function') {
throw new TypeError('runMigrations requires a Database-like transaction object');
}
if (!Array.isArray(migrations)) throw new TypeError('migrations must be an array');
if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(tableName)) {
throw new TypeError('migration tableName must be a simple SQL identifier');
}
const table = `"${tableName}"`;
const ordered = [...migrations].sort((left, right) => String(left.id).localeCompare(String(right.id)));
await database.transaction(async client => {
await client.query('SELECT pg_advisory_xact_lock($1)', [lockKey]);
await client.query(`
CREATE TABLE IF NOT EXISTS ${table} (
id TEXT PRIMARY KEY,
applied_at TIMESTAMPTZ NOT NULL DEFAULT now()
)
`);
for (const migration of ordered) {
if (!migration?.id || typeof migration.up !== 'function') {
throw new TypeError('each migration requires an id and up(client) function');
}
const existing = await client.query(
`SELECT 1 FROM ${table} WHERE id = $1`,
[migration.id]
);
if (existing.rowCount > 0) continue;
await migration.up(client);
await client.query(`INSERT INTO ${table} (id) VALUES ($1)`, [migration.id]);
}
});
}
@@ -1,96 +0,0 @@
import crypto from 'node:crypto';
export const TOTP_PERIOD_SECONDS = 30;
export const TOTP_DIGITS = 6;
export const TOTP_WINDOW = 1;
const BASE32_ALPHABET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567';
export function generateTotpSecret() {
return encodeBase32(crypto.randomBytes(20));
}
export function totpProvisioningUri(issuer, account, secret) {
const normalizedIssuer = String(issuer ?? '').trim();
const normalizedAccount = String(account ?? '').trim();
const label = normalizedIssuer ? `${normalizedIssuer}:${normalizedAccount}` : normalizedAccount;
const params = new URLSearchParams({
secret: normalizeSecret(secret),
algorithm: 'SHA1',
digits: String(TOTP_DIGITS),
period: String(TOTP_PERIOD_SECONDS),
});
if (normalizedIssuer) params.set('issuer', normalizedIssuer);
return `otpauth://totp/${encodeURIComponent(label)}?${params.toString()}`;
}
export function verifyTotp(secret, token, now = Date.now()) {
const normalizedSecret = normalizeSecret(secret);
const normalizedToken = normalizeToken(token);
if (!normalizedSecret || normalizedToken.length !== TOTP_DIGITS) return false;
let key;
try {
key = decodeBase32(normalizedSecret);
} catch {
return false;
}
if (key.length === 0) return false;
const period = Math.floor(now / 1000 / TOTP_PERIOD_SECONDS);
for (let offset = -TOTP_WINDOW; offset <= TOTP_WINDOW; offset += 1) {
if (period + offset < 0) continue;
const counter = Buffer.alloc(8);
counter.writeBigUInt64BE(BigInt(period + offset));
const digest = crypto.createHmac('sha1', key).update(counter).digest();
const index = digest[digest.length - 1] & 0x0f;
const value = ((digest[index] & 0x7f) << 24)
| (digest[index + 1] << 16)
| (digest[index + 2] << 8)
| digest[index + 3];
const candidate = String(value % 1000000).padStart(TOTP_DIGITS, '0');
if (crypto.timingSafeEqual(Buffer.from(candidate), Buffer.from(normalizedToken))) return true;
}
return false;
}
function normalizeSecret(value) {
return String(value ?? '').trim().toUpperCase().replaceAll(' ', '').replaceAll('=', '');
}
function normalizeToken(value) {
const token = String(value ?? '').trim();
return /^\d{6}$/.test(token) ? token : '';
}
function encodeBase32(buffer) {
let output = '';
let bits = 0;
let value = 0;
for (const byte of buffer) {
value = (value << 8) | byte;
bits += 8;
while (bits >= 5) {
output += BASE32_ALPHABET[(value >>> (bits - 5)) & 31];
bits -= 5;
}
}
if (bits > 0) output += BASE32_ALPHABET[(value << (5 - bits)) & 31];
return output;
}
function decodeBase32(value) {
let bits = 0;
let buffer = 0;
const output = [];
for (const character of value) {
const index = BASE32_ALPHABET.indexOf(character);
if (index < 0) throw new Error('invalid base32 secret');
buffer = (buffer << 5) | index;
bits += 5;
while (bits >= 8) {
bits -= 8;
output.push((buffer >>> bits) & 255);
}
buffer &= bits === 0 ? 0 : (1 << bits) - 1;
}
return Buffer.from(output);
}
@@ -1,55 +0,0 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import {
ResetManager,
createSessionToken,
hashPassword,
hashToken,
verifyPassword,
} from '../src/auth.js';
import { totpProvisioningUri, verifyTotp } from '../src/totp.js';
test('reset codes are printed, case-insensitive, expiring, and one-time', () => {
const messages = [];
const manager = new ResetManager({ log: (message) => messages.push(message) });
const code = manager.request();
assert.equal(code.length, 8);
assert.equal(messages.length, 1);
assert.match(messages[0], new RegExp(`ADMIN RESET CODE: ${code}`));
assert.equal(manager.confirm(` ${code.toLowerCase()} `), true);
assert.equal(manager.confirm(code), false);
});
test('expired reset codes are rejected', () => {
const manager = new ResetManager({ ttlMs: -1, log: () => {} });
const code = manager.request();
assert.equal(manager.confirm(code), false);
});
test('password hashes verify and reject a different password', () => {
const hash = hashPassword('correct horse battery staple');
assert.equal(verifyPassword('correct horse battery staple', hash), true);
assert.equal(verifyPassword('wrong password', hash), false);
});
test('TOTP verifies RFC 6238 SHA-1 vectors', () => {
const secret = 'GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ';
const vectors = [
[59, '287082'],
[1111111109, '081804'],
[1111111111, '050471'],
[1234567890, '005924'],
[2000000000, '279037'],
];
for (const [seconds, code] of vectors) {
assert.equal(verifyTotp(secret, code, seconds * 1000), true);
}
assert.match(totpProvisioningUri('Example App', 'admin@example.com', secret), /^otpauth:\/\/totp\//);
});
test('session token hashes are not the raw token', () => {
const { token, tokenHash } = createSessionToken();
assert.notEqual(token, tokenHash);
assert.equal(hashToken(token), tokenHash);
});
@@ -1,17 +0,0 @@
# `gabriel20xx-shared-backend`
Shared Python backend infrastructure for services using `asyncpg`:
- validated `DATABASE_URL` and pool settings;
- one async pool owner with 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.
HTTP framework adapters stay in each service. Install this package from the
published index or directly from the SharedCode repository with a subdirectory
install during development:
```bash
pip install "git+https://repos.gfranz.ch/Gabriel20xx/shared@v0.1.0#subdirectory=packages/python-backend"
```
@@ -1,25 +0,0 @@
[build-system]
requires = ["setuptools>=68"]
build-backend = "setuptools.build_meta"
[project]
name = "gabriel20xx-shared-backend"
version = "0.1.1"
description = "Shared PostgreSQL and authentication primitives for Python services."
readme = "README.md"
requires-python = ">=3.10"
license = { text = "MIT" }
dependencies = [
"asyncpg>=0.30",
"bcrypt>=4.2",
]
[tool.setuptools.packages.find]
where = ["src"]
[tool.ruff]
target-version = "py310"
line-length = 100
[tool.ruff.lint]
select = ["E", "F", "I"]
@@ -1,43 +0,0 @@
"""Shared PostgreSQL and authentication primitives for Python services."""
from .auth import (
RESET_CODE_TTL,
ROLE_ADMIN,
ROLE_SUPERADMIN,
ROLE_USER,
AuthStore,
AuthUser,
ResetManager,
can_assign_role,
can_manage_users,
hash_password,
normalize_role,
verify_password,
)
from .config import DatabaseConfig, database_url_from_env
from .postgres import Database
from .tokens import hash_token, new_session_token
from .totp import generate_totp_secret, totp_provisioning_uri, verify_totp
__all__ = [
"AuthStore",
"AuthUser",
"ROLE_ADMIN",
"ROLE_SUPERADMIN",
"ROLE_USER",
"RESET_CODE_TTL",
"ResetManager",
"can_assign_role",
"can_manage_users",
"Database",
"DatabaseConfig",
"database_url_from_env",
"generate_totp_secret",
"hash_password",
"hash_token",
"new_session_token",
"normalize_role",
"totp_provisioning_uri",
"verify_password",
"verify_totp",
]
@@ -1,318 +0,0 @@
"""Shared account/session persistence and password helpers."""
from __future__ import annotations
import secrets
import threading
from dataclasses import dataclass
from datetime import datetime, timedelta
import asyncpg
import bcrypt
from .postgres import Database
_SCHEMA = """
CREATE TABLE IF NOT EXISTS auth_users (
id BIGSERIAL PRIMARY KEY,
username TEXT NOT NULL UNIQUE,
email TEXT NOT NULL DEFAULT '',
password_hash TEXT NOT NULL,
role TEXT NOT NULL DEFAULT 'user',
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()
);
ALTER TABLE auth_users ADD COLUMN IF NOT EXISTS email TEXT NOT NULL DEFAULT '';
ALTER TABLE auth_users ADD COLUMN IF NOT EXISTS role TEXT NOT NULL DEFAULT 'user';
ALTER TABLE auth_users ADD COLUMN IF NOT EXISTS totp_secret TEXT NOT NULL DEFAULT '';
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();
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');
CREATE UNIQUE INDEX IF NOT EXISTS auth_users_email_idx
ON auth_users (lower(email)) WHERE email <> '';
CREATE TABLE IF NOT EXISTS auth_sessions (
id BIGSERIAL PRIMARY KEY,
user_id BIGINT NOT NULL REFERENCES auth_users(id) ON DELETE CASCADE,
token_hash TEXT NOT NULL UNIQUE,
expires_at TIMESTAMPTZ NOT NULL,
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
CREATE INDEX IF NOT EXISTS auth_sessions_expiry_idx ON auth_sessions (expires_at);
CREATE INDEX IF NOT EXISTS auth_sessions_user_idx ON auth_sessions (user_id);
"""
RESET_CODE_TTL = timedelta(minutes=5)
ROLE_SUPERADMIN = "superadmin"
ROLE_ADMIN = "admin"
ROLE_USER = "user"
def normalize_role(value: str | None) -> str:
normalized = str(value or "").strip().lower()
return normalized if normalized in {ROLE_SUPERADMIN, ROLE_ADMIN} else ROLE_USER
def can_manage_users(role: str | None) -> bool:
return normalize_role(role) in {ROLE_SUPERADMIN, ROLE_ADMIN}
def can_assign_role(actor_role: str | None, target_role: str | None) -> bool:
return (
normalize_role(actor_role) == ROLE_SUPERADMIN
and normalize_role(target_role) != ROLE_SUPERADMIN
)
class ResetManager:
"""Creates and validates the short-lived, one-time admin reset code."""
def __init__(self, *, ttl: timedelta = RESET_CODE_TTL, log=print) -> None:
self._ttl = ttl
self._log = log
self._code: str | None = None
self._expires_at: datetime | None = None
self._lock = threading.Lock()
def request(self) -> str:
code = secrets.token_hex(4).upper()
with self._lock:
self._code = code
self._expires_at = datetime.now().astimezone() + self._ttl
self._log(
f"\n{'=' * 50}\nADMIN RESET CODE: {code}\n"
f"Expires in 5 minutes. Enter it on the login page.\n{'=' * 50}\n"
)
return code
def confirm(self, candidate: str) -> bool:
with self._lock:
if self._code is None or self._expires_at is None:
return False
if datetime.now().astimezone() > self._expires_at:
self._code = None
self._expires_at = None
return False
valid = secrets.compare_digest(self._code, str(candidate or "").strip().upper())
if valid:
self._code = None
self._expires_at = None
return valid
@dataclass(frozen=True, slots=True)
class AuthUser:
id: int
username: str
email: str
password_hash: str
role: str = ROLE_USER
created_at: datetime | None = None
updated_at: datetime | None = None
class UserExistsError(Exception):
"""Raised when a user violates a unique or single-user constraint."""
def hash_password(password: str) -> str:
if len(password) < 8:
raise ValueError("Password must be at least 8 characters")
return bcrypt.hashpw(password.encode("utf-8"), bcrypt.gensalt()).decode("utf-8")
def verify_password(password: str, stored_hash: str) -> bool:
try:
return bcrypt.checkpw(password.encode("utf-8"), stored_hash.encode("utf-8"))
except (ValueError, TypeError):
return False
class AuthStore:
def __init__(self, database: Database, *, single_user: bool = True) -> None:
self.database = database
self.single_user = single_user
async def ensure_schema(self) -> None:
await self.database.execute(_SCHEMA)
if self.single_user:
await self.database.execute(
"CREATE UNIQUE INDEX IF NOT EXISTS auth_users_singleton_idx ON auth_users ((true))"
)
else:
await self.database.execute("DROP INDEX IF EXISTS auth_users_singleton_idx")
async def count_users(self) -> int:
return int(await self.database.fetchval("SELECT count(*) FROM auth_users"))
async def create_user(self, username: str, email: str, password_hash: str) -> AuthUser:
try:
row = await self.database.fetchrow(
"""
INSERT INTO auth_users (username, email, password_hash, role, updated_at)
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
""",
username,
email,
password_hash,
)
except asyncpg.UniqueViolationError as exc:
raise UserExistsError from exc
assert row is not None
return AuthUser(**dict(row))
async def find_by_identifier(self, identifier: str) -> AuthUser | None:
row = await self.database.fetchrow(
"""
SELECT id, username, email, password_hash, role, created_at, updated_at
FROM auth_users
WHERE username = $1 OR lower(email) = lower($1)
""",
identifier,
)
return AuthUser(**dict(row)) if row else None
async def update_credentials(
self, user_id: int, username: str, email: str, password_hash: str
) -> None:
await self.database.execute(
"""
UPDATE auth_users
SET username = $1, email = $2, password_hash = $3, updated_at = now()
WHERE id = $4
""",
username,
email,
password_hash,
user_id,
)
async def create_session(self, user_id: int, token_hash: str, expires_at: datetime) -> None:
await self.database.execute(
"INSERT INTO auth_sessions (user_id, token_hash, expires_at) VALUES ($1, $2, $3)",
user_id,
token_hash,
expires_at,
)
async def find_session_user(self, token_hash: str) -> AuthUser | None:
row = await self.database.fetchrow(
"""
SELECT u.id, u.username, u.email, u.password_hash, u.role, u.created_at, u.updated_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()
""",
token_hash,
)
return AuthUser(**dict(row)) if row else None
async def delete_session(self, token_hash: str) -> None:
await self.database.execute("DELETE FROM auth_sessions WHERE token_hash = $1", token_hash)
async def delete_sessions_for_user(self, user_id: int) -> None:
await self.database.execute("DELETE FROM auth_sessions WHERE user_id = $1", user_id)
async def list_users(self) -> list[AuthUser]:
rows = await self.database.fetch(
"SELECT id, username, email, role, password_hash, created_at, updated_at "
"FROM auth_users ORDER BY created_at, id"
)
return [AuthUser(**dict(row)) for row in rows]
async def create_managed_user(
self, username: str, email: str, password_hash: str, role: str = ROLE_USER
) -> AuthUser:
try:
row = await self.database.fetchrow(
"""
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
""",
username,
email,
password_hash,
normalize_role(role),
)
except asyncpg.UniqueViolationError as exc:
raise UserExistsError from exc
assert row is not None
return AuthUser(**dict(row))
async def update_user(
self,
user_id: int,
*,
username: str | None = None,
email: str | None = None,
password_hash: str | None = None,
role: str | None = None,
) -> None:
fields: list[str] = []
values: list[object] = []
for column, value in (
("username", username),
("email", email),
("password_hash", password_hash),
("role", normalize_role(role) if role is not None else None),
):
if value is not None:
fields.append(f"{column} = ${len(values) + 1}")
values.append(value)
if not fields:
return
values.append(user_id)
query = (
f"UPDATE auth_users SET {', '.join(fields)}, "
f"updated_at = now() WHERE id = ${len(values)}"
)
await self.database.execute(query, *values)
async def delete_user(self, user_id: int) -> None:
await self.database.execute("DELETE FROM auth_users WHERE id = $1", user_id)
async def delete_all_users(self) -> None:
await self.database.execute("DELETE FROM auth_users")
async def get_totp_state(self, user_id: int) -> dict[str, object]:
row = await self.database.fetchrow(
"SELECT COALESCE(totp_secret, '') AS secret, COALESCE(totp_enabled, false) AS enabled "
"FROM auth_users WHERE id = $1",
user_id,
)
return dict(row) if row else {"secret": "", "enabled": False}
async def set_totp_secret(self, user_id: int, secret: str) -> None:
await self.database.execute(
"UPDATE auth_users SET totp_secret = $1, totp_enabled = false, "
"updated_at = now() WHERE id = $2",
secret,
user_id,
)
async def enable_totp(self, user_id: int) -> None:
await self.database.execute(
"UPDATE auth_users SET totp_enabled = true, updated_at = now() "
"WHERE id = $1 AND totp_secret <> ''",
user_id,
)
async def disable_totp(self, user_id: int) -> None:
await self.database.execute(
"UPDATE auth_users SET totp_secret = '', totp_enabled = false, "
"updated_at = now() WHERE id = $1",
user_id,
)
async def prune_expired_sessions(self) -> None:
await self.database.execute("DELETE FROM auth_sessions WHERE expires_at < now()")
@@ -1,49 +0,0 @@
"""Dependency-free environment configuration helpers."""
from __future__ import annotations
import os
from dataclasses import dataclass
from typing import Mapping
def _int_value(env: Mapping[str, str], key: str, fallback: int, minimum: int) -> int:
try:
value = int(env.get(key, ""))
except (TypeError, ValueError):
return fallback
return value if value >= minimum else fallback
def database_url_from_env(env: Mapping[str, str] | None = None) -> str:
source = os.environ if env is None else env
value = str(source.get("DATABASE_URL", "")).strip()
if not value:
raise RuntimeError("DATABASE_URL environment variable is required")
return value
@dataclass(frozen=True, slots=True)
class DatabaseConfig:
dsn: str
min_size: int = 0
max_size: int = 20
timeout: float = 5.0
command_timeout: float = 15.0
@classmethod
def from_env(cls, env: Mapping[str, str] | None = None) -> "DatabaseConfig":
source = os.environ if env is None else env
max_size = _int_value(source, "DATABASE_MAX_CONNS", 20, 1)
min_size = _int_value(source, "DATABASE_MIN_CONNS", 0, 0)
if min_size > max_size:
raise ValueError("DATABASE_MIN_CONNS must not exceed DATABASE_MAX_CONNS")
return cls(
dsn=database_url_from_env(source),
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)
),
)
@@ -1,65 +0,0 @@
"""Shared asyncpg pool and transaction wrapper."""
from __future__ import annotations
from contextlib import asynccontextmanager
from typing import Any, AsyncIterator, Awaitable, Callable
import asyncpg
from .config import DatabaseConfig
class Database:
"""Own one asyncpg pool and expose common lifecycle/query operations."""
def __init__(self, pool: asyncpg.Pool) -> None:
self.pool = pool
@classmethod
async def connect(cls, config: DatabaseConfig | str) -> "Database":
settings = config if isinstance(config, DatabaseConfig) else DatabaseConfig(dsn=config)
pool = await asyncpg.create_pool(
dsn=settings.dsn,
min_size=settings.min_size,
max_size=settings.max_size,
timeout=settings.timeout,
command_timeout=settings.command_timeout,
)
try:
await pool.fetchval("SELECT 1")
except Exception:
await pool.close()
raise
return cls(pool)
async def ping(self) -> None:
await self.pool.fetchval("SELECT 1")
async def close(self) -> None:
await self.pool.close()
async def execute(self, query: str, *args: Any) -> str:
return await self.pool.execute(query, *args)
async def fetch(self, query: str, *args: Any) -> list[asyncpg.Record]:
return await self.pool.fetch(query, *args)
async def fetchrow(self, query: str, *args: Any) -> asyncpg.Record | None:
return await self.pool.fetchrow(query, *args)
async def fetchval(self, query: str, *args: Any) -> Any:
return await self.pool.fetchval(query, *args)
@asynccontextmanager
async def transaction(self) -> AsyncIterator[asyncpg.Connection]:
async with self.pool.acquire() as connection:
async with connection.transaction():
yield connection
async def with_transaction(
self,
callback: Callable[[asyncpg.Connection], Awaitable[Any]],
) -> Any:
async with self.transaction() as connection:
return await callback(connection)
@@ -1,15 +0,0 @@
"""Opaque session-token generation and storage hashing."""
from __future__ import annotations
import hashlib
import secrets
def new_session_token() -> tuple[str, str]:
token = secrets.token_urlsafe(32)
return token, hash_token(token)
def hash_token(token: str) -> str:
return hashlib.sha256(token.encode("utf-8")).hexdigest()
@@ -1,75 +0,0 @@
"""RFC 6238 TOTP helpers shared by Python auth services."""
from __future__ import annotations
import base64
import binascii
import hashlib
import hmac
import secrets
import struct
import time
from urllib.parse import quote, urlencode
TOTP_PERIOD_SECONDS = 30
TOTP_DIGITS = 6
TOTP_WINDOW = 1
def generate_totp_secret() -> str:
return base64.b32encode(secrets.token_bytes(20)).decode("ascii").rstrip("=")
def totp_provisioning_uri(issuer: str, account: str, secret: str) -> str:
normalized_issuer = str(issuer or "").strip()
normalized_account = str(account or "").strip()
label = f"{normalized_issuer}:{normalized_account}" if normalized_issuer else normalized_account
params = {
"secret": _normalize_secret(secret),
"algorithm": "SHA1",
"digits": str(TOTP_DIGITS),
"period": str(TOTP_PERIOD_SECONDS),
}
if normalized_issuer:
params["issuer"] = normalized_issuer
return f"otpauth://totp/{quote(label, safe='')}?{urlencode(params)}"
def verify_totp(secret: str, token: str, now: float | None = None) -> bool:
normalized_secret = _normalize_secret(secret)
normalized_token = _normalize_token(token)
if not normalized_secret or len(normalized_token) != TOTP_DIGITS:
return False
try:
key = base64.b32decode(normalized_secret + "=" * ((8 - len(normalized_secret) % 8) % 8))
except (ValueError, binascii.Error):
return False
if not key:
return False
period = int((time.time() if now is None else now) // TOTP_PERIOD_SECONDS)
for offset in range(-TOTP_WINDOW, TOTP_WINDOW + 1):
counter = period + offset
if counter < 0:
continue
digest = hmac.new(key, struct.pack(">Q", counter), hashlib.sha1).digest()
index = digest[-1] & 0x0F
value = (
((digest[index] & 0x7F) << 24)
| (digest[index + 1] << 16)
| (digest[index + 2] << 8)
| digest[index + 3]
)
candidate = f"{value % 1_000_000:06d}"
if hmac.compare_digest(candidate, normalized_token):
return True
return False
def _normalize_secret(value: str) -> str:
return str(value or "").strip().upper().replace(" ", "").rstrip("=")
def _normalize_token(value: str) -> str:
token = str(value or "").strip()
return token if len(token) == TOTP_DIGITS and token.isdigit() else ""
@@ -1,68 +0,0 @@
import os
import unittest
from datetime import timedelta
from shared_backend.auth import ResetManager, hash_password, verify_password
from shared_backend.config import DatabaseConfig
from shared_backend.tokens import hash_token, new_session_token
from shared_backend.totp import totp_provisioning_uri, verify_totp
class SharedBackendTests(unittest.TestCase):
def test_password_round_trip(self):
password_hash = hash_password("correct horse battery staple")
self.assertTrue(verify_password("correct horse battery staple", password_hash))
self.assertFalse(verify_password("wrong password", password_hash))
def test_session_token_hash(self):
token, token_hash = new_session_token()
self.assertNotEqual(token, token_hash)
self.assertEqual(hash_token(token), token_hash)
def test_reset_manager_round_trip_and_one_time_use(self):
messages = []
manager = ResetManager(log=messages.append)
code = manager.request()
self.assertEqual(len(code), 8)
self.assertIn(f"ADMIN RESET CODE: {code}", messages[0])
self.assertTrue(manager.confirm(f" {code.lower()} "))
self.assertFalse(manager.confirm(code))
def test_reset_manager_expires(self):
manager = ResetManager(ttl=timedelta(seconds=-1), log=lambda _message: None)
code = manager.request()
self.assertFalse(manager.confirm(code))
def test_totp_rfc6238_sha1_vectors(self):
secret = "GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ"
vectors = [
(59, "287082"),
(1111111109, "081804"),
(1111111111, "050471"),
(1234567890, "005924"),
(2000000000, "279037"),
]
for timestamp, code in vectors:
self.assertTrue(verify_totp(secret, code, timestamp))
self.assertTrue(
totp_provisioning_uri("Example App", "admin@example.com", secret).startswith(
"otpauth://totp/"
)
)
def test_database_config_from_environment(self):
config = DatabaseConfig.from_env(
{
**os.environ,
"DATABASE_URL": "postgresql://user:password@localhost:5432/app",
"DATABASE_MAX_CONNS": "7",
"DATABASE_MIN_CONNS": "2",
}
)
self.assertEqual(config.max_size, 7)
self.assertEqual(config.min_size, 2)
if __name__ == "__main__":
unittest.main()
-3
View File
@@ -1,3 +0,0 @@
# `@gabriel20xx/web-ui`
Reusable Svelte 5 components for the shared application shell and account UI. See the workspace [README](../../README.md) for installation, publishing, and integration examples.
-42
View File
@@ -1,42 +0,0 @@
{
"name": "@gabriel20xx/web-ui",
"version": "0.1.1",
"description": "Shared Svelte UI, layout, authentication, and account components for Gabriel20xx web projects.",
"license": "MIT",
"type": "module",
"files": [
"src",
"README.md"
],
"sideEffects": [
"**/*.css"
],
"peerDependencies": {
"svelte": "^5.0.0"
},
"dependencies": {
},
"devDependencies": {
"@sveltejs/package": "^2.5.0",
"@sveltejs/vite-plugin-svelte": "^6.0.0",
"svelte": "^5.0.0",
"svelte-check": "^4.0.0",
"typescript": "^5.0.0"
},
"scripts": {
"check": "svelte-check --tsconfig ./tsconfig.json",
"package": "svelte-package"
},
"svelte": "./src/index.ts",
"types": "./src/index.ts",
"exports": {
".": {
"types": "./src/index.ts",
"svelte": "./src/index.ts",
"import": "./src/index.ts"
},
"./styles.css": "./src/lib/styles.css",
"./package.json": "./package.json"
}
}
-1
View File
@@ -1 +0,0 @@
export * from './lib/index.js';
@@ -1,48 +0,0 @@
<script lang="ts">
import type { Snippet } from 'svelte';
import type { AboutLink } from '../types';
import Dialog from './Dialog.svelte';
let {
brand = 'Application',
children,
description = '',
links = [],
open = $bindable(false),
version = ''
}: {
brand?: string;
children?: Snippet;
description?: string;
links?: AboutLink[];
open?: boolean;
version?: string;
} = $props();
</script>
<Dialog bind:open title={`About ${brand}`}>
<div class="sc-auth-brand">
<span aria-hidden="true" class="sc-brand-mark">{brand.slice(0, 1).toUpperCase()}</span>
<strong>{brand}</strong>
</div>
{#if version}
<p class="sc-muted">Version {version}</p>
{/if}
{#if description}
<p class="sc-muted">{description}</p>
{/if}
{#if children}
{@render children()}
{/if}
{#if links.length > 0}
<div class="sc-about-links">
{#each links as link}
<a href={link.href} rel="noreferrer" target="_blank">{link.label}</a>
{/each}
</div>
{/if}
</Dialog>
@@ -1,57 +0,0 @@
<script lang="ts">
import type { Snippet } from 'svelte';
import type { NavItem } from '../types';
import Header from './Header.svelte';
let {
brand = 'Application',
brandHref = '/',
children,
class: className = '',
currentPath = '',
headerActions,
navItems = [],
onLogout,
onNavigate,
onProfile,
onSettings,
showSettings = true,
theme = 'dark',
username = ''
}: {
brand?: string;
brandHref?: string;
children?: Snippet;
class?: string;
currentPath?: string;
headerActions?: Snippet;
navItems?: NavItem[];
onLogout?: () => void | Promise<void>;
onNavigate?: (item: NavItem) => void;
onProfile?: () => void;
onSettings?: () => void;
showSettings?: boolean;
theme?: 'dark' | 'light' | 'system';
username?: string;
} = $props();
</script>
<div class={`sc-root sc-app-shell ${className}`} data-theme={theme === 'system' ? undefined : theme}>
<Header
{brand}
{brandHref}
{currentPath}
actions={headerActions}
{navItems}
{onLogout}
{onNavigate}
{onProfile}
{onSettings}
{showSettings}
{username}
/>
<main class="sc-main">
{@render children?.()}
</main>
</div>
@@ -1,245 +0,0 @@
<script lang="ts">
import type { Snippet } from 'svelte';
import type {
AuthLoginInput,
AuthResetConfirm,
AuthResetRequest,
AuthSetupInput
} from '../types';
import Button from './Button.svelte';
let {
brand = 'Application',
children,
error = '',
loading = false,
onLogin,
onConfirmReset,
onRequestReset,
onSetup,
showTotp = true,
setupRequired = false,
tagline = ''
}: {
brand?: string;
children?: Snippet;
error?: string;
loading?: boolean;
onLogin?: (input: AuthLoginInput) => void | Promise<void>;
onConfirmReset?: AuthResetConfirm;
onRequestReset?: AuthResetRequest;
onSetup?: (input: AuthSetupInput) => void | Promise<void>;
showTotp?: boolean;
setupRequired?: boolean;
tagline?: string;
} = $props();
let username = $state('');
let email = $state('');
let identifier = $state('');
let password = $state('');
let totpToken = $state('');
let confirmPassword = $state('');
let submitError = $state('');
let submitting = $state(false);
let resetCode = $state('');
let resetError = $state('');
let resetOpen = $state(false);
let resetting = $state(false);
async function submit(event: SubmitEvent): Promise<void> {
event.preventDefault();
submitError = '';
if (setupRequired && password !== confirmPassword) {
submitError = 'Passwords do not match.';
return;
}
submitting = true;
try {
if (setupRequired) {
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.');
await onLogin({ identifier, password, totpToken: totpToken.trim() });
}
} catch (caught) {
submitError = caught instanceof Error ? caught.message : 'Authentication failed.';
} finally {
submitting = false;
}
}
async function requestReset(): Promise<void> {
resetError = '';
resetCode = '';
resetOpen = true;
try {
if (!onRequestReset) throw new Error('The application has not configured its reset handler.');
await onRequestReset();
} catch (caught) {
resetError = caught instanceof Error ? caught.message : 'Unable to request an account reset.';
}
}
async function confirmReset(): Promise<void> {
resetError = '';
const code = resetCode.trim();
if (!code) {
resetError = 'Enter the code printed in the server console.';
return;
}
resetting = true;
try {
if (!onConfirmReset) throw new Error('The application has not configured its reset handler.');
await onConfirmReset(code);
} catch (caught) {
resetError = caught instanceof Error ? caught.message : 'Unable to reset the admin account.';
} finally {
resetting = false;
}
}
</script>
<div class="sc-root sc-auth-page">
<section 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>
<span>{brand}</span>
</div>
<h1 id="sc-auth-title">{setupRequired ? 'Create your account' : 'Welcome back'}</h1>
{#if tagline}
<p class="sc-auth-subtitle">{tagline}</p>
{/if}
<form class="sc-form sc-auth-form" onsubmit={submit}>
{#if setupRequired}
<label class="sc-field">
<span class="sc-label">Username</span>
<input
autocomplete="username"
class="sc-input"
name="username"
required
type="text"
bind:value={username}
/>
</label>
<label class="sc-field">
<span class="sc-label">Email</span>
<input
autocomplete="email"
class="sc-input"
name="email"
required
type="email"
bind:value={email}
/>
</label>
{:else}
<label class="sc-field">
<span class="sc-label">Username or email</span>
<input
autocomplete="username"
class="sc-input"
name="identifier"
required
type="text"
bind:value={identifier}
/>
</label>
{/if}
<label class="sc-field">
<span class="sc-label">Password</span>
<input
autocomplete={setupRequired ? 'new-password' : 'current-password'}
class="sc-input"
minlength="8"
name="password"
required
type="password"
bind:value={password}
/>
</label>
{#if showTotp && !setupRequired}
<label class="sc-field">
<span class="sc-label">Authenticator code <span class="sc-label-optional">(if enabled)</span></span>
<input
autocomplete="one-time-code"
class="sc-input"
inputmode="numeric"
name="totpToken"
type="text"
bind:value={totpToken}
/>
</label>
{/if}
{#if setupRequired}
<label class="sc-field">
<span class="sc-label">Confirm password</span>
<input
autocomplete="new-password"
class="sc-input"
minlength="8"
name="confirmPassword"
required
type="password"
bind:value={confirmPassword}
/>
</label>
{/if}
{#if error || submitError}
<p aria-live="polite" class="sc-error">{submitError || error}</p>
{/if}
<Button disabled={loading || submitting} fullWidth size="lg" type="submit">
{loading || submitting ? 'Please wait…' : setupRequired ? 'Create account' : 'Log in'}
</Button>
</form>
{#if children}
<div class="sc-auth-extra">{@render children()}</div>
{/if}
{#if !setupRequired && 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>
<input
aria-label="Reset code"
autocomplete="off"
class="sc-input"
placeholder="Enter reset code"
type="text"
bind:value={resetCode}
/>
{#if resetError}<p class="sc-error">{resetError}</p>{/if}
<Button
disabled={resetting}
fullWidth
size="sm"
variant="danger"
onclick={() => void confirmReset()}
>
{resetting ? 'Resetting…' : 'Confirm reset'}
</Button>
</div>
{:else}
<button class="sc-auth-reset-link" type="button" onclick={() => void requestReset()}>
Reset admin account
</button>
{/if}
{/if}
</section>
</div>
@@ -1,19 +0,0 @@
<script lang="ts">
import type { Snippet } from 'svelte';
type BadgeVariant = 'default' | 'success' | 'warning' | 'danger';
let {
children,
class: className = '',
variant = 'default'
}: {
children?: Snippet;
class?: string;
variant?: BadgeVariant;
} = $props();
</script>
<span class={`sc-badge ${className}`} data-variant={variant}>
{@render children?.()}
</span>
@@ -1,35 +0,0 @@
<script lang="ts">
import type { Snippet } from 'svelte';
type ButtonVariant = 'primary' | 'secondary' | 'ghost' | 'danger';
type ButtonSize = 'sm' | 'md' | 'lg';
let {
children,
class: className = '',
disabled = false,
fullWidth = false,
onclick,
size = 'md',
type = 'button',
variant = 'primary'
}: {
children?: Snippet;
class?: string;
disabled?: boolean;
fullWidth?: boolean;
onclick?: (event: MouseEvent) => void;
size?: ButtonSize;
type?: 'button' | 'submit' | 'reset';
variant?: ButtonVariant;
} = $props();
</script>
<button
class={`sc-button sc-button-${variant} sc-button-${size}${fullWidth ? ' sc-button-full' : ''} ${className}`}
{disabled}
{onclick}
{type}
>
{@render children?.()}
</button>
@@ -1,15 +0,0 @@
<script lang="ts">
import type { Snippet } from 'svelte';
let {
children,
class: className = ''
}: {
children?: Snippet;
class?: string;
} = $props();
</script>
<section class={`sc-card ${className}`}>
{@render children?.()}
</section>
@@ -1,54 +0,0 @@
<script lang="ts">
import type { Snippet } from 'svelte';
let {
children,
description = '',
footer,
open = $bindable(false),
title
}: {
children?: Snippet;
description?: string;
footer?: Snippet;
open?: boolean;
title: string;
} = $props();
function close(): void {
open = false;
}
</script>
{#if open}
<div
aria-label={title}
class="sc-dialog-backdrop"
role="presentation"
onclick={(event) => {
if (event.target === event.currentTarget) close();
}}
>
<section aria-modal="true" class="sc-dialog" role="dialog">
<div class="sc-dialog-header">
<div>
<h2 class="sc-dialog-title">{title}</h2>
{#if description}
<p class="sc-dialog-description">{description}</p>
{/if}
</div>
<button aria-label="Close" class="sc-dialog-close" type="button" onclick={close}>×</button>
</div>
<div class="sc-dialog-body">
{@render children?.()}
</div>
{#if footer}
<div class="sc-dialog-footer">
{@render footer()}
</div>
{/if}
</section>
</div>
{/if}
@@ -1,93 +0,0 @@
<script lang="ts">
import type { Snippet } from 'svelte';
import type { NavItem } from '../types';
let {
brand = 'Application',
brandHref = '/',
currentPath = '',
navItems = [],
actions,
onLogout,
onNavigate,
onProfile,
onSettings,
showSettings = true,
username = ''
}: {
brand?: string;
brandHref?: string;
currentPath?: string;
navItems?: NavItem[];
actions?: Snippet;
onLogout?: () => void | Promise<void>;
onNavigate?: (item: NavItem) => void;
onProfile?: () => void;
onSettings?: () => void;
showSettings?: boolean;
username?: string;
} = $props();
let navOpen = $state(false);
function isActive(item: NavItem): boolean {
return item.href === '/'
? currentPath === '/'
: currentPath === item.href || currentPath.startsWith(`${item.href}/`);
}
</script>
<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>
<span>{brand}</span>
</a>
<nav aria-label="Primary navigation" class="sc-nav" data-open={navOpen}>
{#each navItems as item}
<a
aria-current={isActive(item) ? 'page' : undefined}
class="sc-nav-link"
data-active={isActive(item)}
href={item.href}
onclick={(event) => {
if (onNavigate) {
event.preventDefault();
onNavigate(item);
}
navOpen = false;
}}
>
{item.label}
</a>
{/each}
</nav>
<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}
{#if username && onProfile}
<button class="sc-profile-button" type="button" onclick={onProfile}>{username}</button>
{/if}
{#if onLogout}
<button class="sc-button sc-button-ghost sc-button-sm" type="button" onclick={() => void onLogout?.()}>
Log out
</button>
{/if}
<button
aria-expanded={navOpen}
aria-label={navOpen ? 'Close navigation menu' : 'Open navigation menu'}
class="sc-icon-button sc-mobile-menu-button"
type="button"
onclick={() => (navOpen = !navOpen)}
>
{navOpen ? '×' : '☰'}
</button>
</div>
</header>
@@ -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>
@@ -1,170 +0,0 @@
<script lang="ts">
import type {
ProfileUpdateInput,
TotpSetupRequest,
TotpStatusRequest,
TotpTokenAction,
UserCreateRequest,
UserDeleteRequest,
UserId,
UserListRequest,
UserRole,
UserUpdateRequest
} 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();
let username = $state('');
let email = $state('');
let password = $state('');
let confirmPassword = $state('');
let error = $state('');
let saving = $state(false);
$effect(() => {
if (open) {
username = currentUsername;
email = currentEmail;
password = '';
confirmPassword = '';
error = '';
}
});
async function save(event: SubmitEvent): Promise<void> {
event.preventDefault();
error = '';
if (password && password !== confirmPassword) {
error = 'Passwords do not match.';
return;
}
if (!onSave) {
error = 'The application has not configured its profile update handler.';
return;
}
saving = true;
try {
await onSave({ username, email, password: password || undefined });
open = false;
} catch (caught) {
error = caught instanceof Error ? caught.message : 'Profile update failed.';
} finally {
saving = false;
}
}
</script>
<Dialog bind:open title="Profile">
<div class="sc-profile-summary">
<strong>{currentUsername || 'Your profile'}</strong>
{#if currentEmail}
<span>{currentEmail}</span>
{/if}
</div>
<form class="sc-form" onsubmit={save}>
<label class="sc-field">
<span class="sc-label">Username</span>
<input autocomplete="username" class="sc-input" required type="text" bind:value={username} />
</label>
<label class="sc-field">
<span class="sc-label">Email</span>
<input autocomplete="email" class="sc-input" required type="email" bind:value={email} />
</label>
<label class="sc-field">
<span class="sc-label">New password</span>
<input
autocomplete="new-password"
class="sc-input"
minlength="8"
placeholder="Leave blank to keep the current password"
type="password"
bind:value={password}
/>
</label>
{#if password}
<label class="sc-field">
<span class="sc-label">Confirm new password</span>
<input
autocomplete="new-password"
class="sc-input"
minlength="8"
required
type="password"
bind:value={confirmPassword}
/>
</label>
{/if}
{#if error}
<p aria-live="polite" class="sc-error">{error}</p>
{/if}
<div class="sc-form-actions">
<Button variant="secondary" type="button" onclick={() => (open = false)}>Cancel</Button>
<Button disabled={saving} type="submit">{saving ? 'Saving…' : 'Save changes'}</Button>
</div>
</form>
{#if onTotpSetup && onTotpEnable && onTotpDisable}
<TotpSettings
{open}
onDisable={onTotpDisable}
onEnable={onTotpEnable}
onSetup={onTotpSetup}
onStatus={onTotpStatus}
enabled={totpEnabled}
/>
{/if}
<UserManagement
currentRole={currentRole}
currentUserId={currentUserId}
onCreate={onCreateUser}
onDelete={onDeleteUser}
onList={onListUsers}
onUpdate={onUpdateUser}
/>
</Dialog>
@@ -1,53 +0,0 @@
<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();
</script>
<Dialog bind:open {description} {title}>
{#if children}
{@render children()}
{: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>
@@ -1,167 +0,0 @@
<script lang="ts">
import type {
TotpSetupRequest,
TotpStatusRequest,
TotpTokenAction,
TotpSetupResponse
} from '../types';
import Button from './Button.svelte';
let {
enabled = false,
onDisable,
onEnable,
onSetup,
onStatus,
open = false
}: {
enabled?: boolean;
onDisable?: TotpTokenAction;
onEnable?: TotpTokenAction;
onSetup?: TotpSetupRequest;
onStatus?: TotpStatusRequest;
open?: boolean;
} = $props();
let currentEnabled = $state(false);
let setup = $state<TotpSetupResponse | null>(null);
let token = $state('');
let error = $state('');
let busy = $state(false);
$effect(() => {
currentEnabled = enabled;
});
$effect(() => {
if (!open || !onStatus) return;
void refreshStatus();
});
async function refreshStatus(): Promise<void> {
try {
currentEnabled = await onStatus?.() ?? currentEnabled;
} catch {
// The explicit setup controls remain usable if status is unavailable.
}
}
async function beginSetup(): Promise<void> {
if (!onSetup) return;
error = '';
busy = true;
try {
setup = await onSetup();
token = '';
} catch (caught) {
error = caught instanceof Error ? caught.message : 'Unable to start two-factor setup.';
} finally {
busy = false;
}
}
async function confirmEnable(): Promise<void> {
const normalized = token.trim();
if (!/^\d{6}$/.test(normalized)) {
error = 'Enter the six-digit code from your authenticator app.';
return;
}
if (!onEnable) return;
error = '';
busy = true;
try {
await onEnable(normalized);
currentEnabled = true;
setup = null;
token = '';
} catch (caught) {
error = caught instanceof Error ? caught.message : 'Unable to enable two-factor authentication.';
} finally {
busy = false;
}
}
async function disable(): Promise<void> {
const normalized = token.trim();
if (!/^\d{6}$/.test(normalized)) {
error = 'Enter the current six-digit authenticator code.';
return;
}
if (!onDisable) return;
error = '';
busy = true;
try {
await onDisable(normalized);
currentEnabled = false;
token = '';
} catch (caught) {
error = caught instanceof Error ? caught.message : 'Unable to disable two-factor authentication.';
} finally {
busy = false;
}
}
</script>
<section class="sc-totp-settings" aria-labelledby="sc-totp-title">
<div class="sc-totp-heading">
<div>
<h3 id="sc-totp-title">Two-factor authentication</h3>
<p class="sc-muted">Protect sign-in with a time-based authenticator code.</p>
</div>
<span class:sc-totp-enabled={currentEnabled} class="sc-totp-status">
{currentEnabled ? 'Enabled' : 'Optional'}
</span>
</div>
{#if currentEnabled}
<label class="sc-field">
<span class="sc-label">Current authenticator code</span>
<input
autocomplete="one-time-code"
class="sc-input"
inputmode="numeric"
maxlength="6"
pattern="[0-9]{6}"
placeholder="123456"
type="text"
bind:value={token}
/>
</label>
<Button disabled={busy} variant="danger" onclick={() => void disable()}>
{busy ? 'Disabling…' : 'Disable two-factor authentication'}
</Button>
{:else if setup}
<div class="sc-totp-secret">
<p>Scan this address in your authenticator app, or enter the secret manually.</p>
<code>{setup.otpauthUrl}</code>
<p><span class="sc-label">Manual secret:</span> <code>{setup.secret}</code></p>
</div>
<label class="sc-field">
<span class="sc-label">Authenticator code</span>
<input
autocomplete="one-time-code"
class="sc-input"
inputmode="numeric"
maxlength="6"
pattern="[0-9]{6}"
placeholder="123456"
type="text"
bind:value={token}
/>
</label>
<div class="sc-form-actions">
<Button disabled={busy} variant="secondary" onclick={() => (setup = null)}>Cancel</Button>
<Button disabled={busy} onclick={() => void confirmEnable()}>
{busy ? 'Enabling…' : 'Enable two-factor authentication'}
</Button>
</div>
{:else}
<Button disabled={busy} onclick={() => void beginSetup()}>
{busy ? 'Preparing…' : 'Set up authenticator'}
</Button>
{/if}
{#if error}
<p aria-live="polite" class="sc-error">{error}</p>
{/if}
</section>
@@ -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}
@@ -1,37 +0,0 @@
export { default as AboutDialog } from './components/AboutDialog.svelte';
export { default as AppShell } from './components/AppShell.svelte';
export { default as AuthPage } from './components/AuthPage.svelte';
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 Header } from './components/Header.svelte';
export { default as PageHeader } from './components/PageHeader.svelte';
export { default as ProfileDialog } from './components/ProfileDialog.svelte';
export { default as SettingsDialog } from './components/SettingsDialog.svelte';
export { default as TotpSettings } from './components/TotpSettings.svelte';
export { default as UserManagement } from './components/UserManagement.svelte';
export type {
AboutLink,
AsyncAction,
AuthLoginInput,
AuthResetConfirm,
AuthResetRequest,
AuthSetupInput,
ContentSnippet,
NavItem,
ProfileUpdateInput,
ManagedUser,
UserCreateInput,
UserCreateRequest,
UserDeleteRequest,
UserId,
UserListRequest,
UserRole,
UserUpdateInput,
UserUpdateRequest,
TotpSetupRequest,
TotpSetupResponse,
TotpStatusRequest,
TotpTokenAction
} from './types';
@@ -1,776 +0,0 @@
@import '../../../design-tokens/theme.css';
:where(.sc-root, .sc-root *) {
box-sizing: border-box;
}
.sc-root {
min-height: 100%;
color: var(--sc-fg);
background: var(--sc-bg);
font-family: var(--sc-font-sans);
}
.sc-root button,
.sc-root input,
.sc-root textarea,
.sc-root select {
font: inherit;
}
.sc-root a {
color: inherit;
}
.sc-app-shell {
min-height: 100vh;
color: var(--sc-fg);
background: var(--sc-bg);
}
.sc-main {
width: min(100% - 2rem, 90rem);
margin: 0 auto;
padding: 2rem 0 3rem;
}
.sc-header {
position: sticky;
z-index: 20;
top: 0;
display: flex;
align-items: center;
gap: 1.25rem;
min-height: 4rem;
padding: 0 1rem;
color: var(--sc-fg);
background: color-mix(in srgb, var(--sc-surface) 92%, transparent);
border-bottom: 1px solid var(--sc-border);
backdrop-filter: blur(14px);
}
.sc-brand {
display: inline-flex;
flex: 0 0 auto;
align-items: center;
gap: 0.625rem;
color: var(--sc-fg);
font-size: 1rem;
font-weight: 750;
text-decoration: none;
letter-spacing: -0.01em;
}
.sc-brand-mark {
display: grid;
width: 2rem;
height: 2rem;
place-items: center;
color: var(--sc-primary-fg);
background: var(--sc-primary);
border-radius: var(--sc-radius-md);
font-size: 0.875rem;
font-weight: 800;
}
.sc-nav {
display: flex;
flex: 1 1 auto;
align-items: center;
gap: 0.25rem;
}
.sc-nav-link,
.sc-profile-button,
.sc-icon-button {
border: 1px solid transparent;
border-radius: var(--sc-radius-md);
transition: color 140ms ease, background 140ms ease, border-color 140ms ease;
}
.sc-nav-link {
padding: 0.5rem 0.75rem;
color: var(--sc-muted-fg);
font-size: 0.9rem;
text-decoration: none;
}
.sc-nav-link:hover,
.sc-nav-link[data-active='true'] {
color: var(--sc-fg);
background: var(--sc-surface-hover);
border-color: var(--sc-border);
}
.sc-header-actions {
display: flex;
align-items: center;
gap: 0.5rem;
margin-left: auto;
}
.sc-icon-button,
.sc-profile-button {
color: var(--sc-muted-fg);
background: transparent;
cursor: pointer;
}
.sc-icon-button {
display: grid;
width: 2.25rem;
height: 2.25rem;
place-items: center;
font-size: 1.15rem;
}
.sc-profile-button {
padding: 0.5rem 0.75rem;
font-size: 0.875rem;
}
.sc-icon-button:hover,
.sc-profile-button:hover {
color: var(--sc-fg);
background: var(--sc-surface-hover);
border-color: var(--sc-border);
}
.sc-mobile-menu-button {
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;
color: var(--sc-fg);
font-weight: 750;
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 {
margin: 0.5rem 0 0;
color: var(--sc-muted-fg);
line-height: 1.55;
}
.sc-card {
padding: 1.25rem;
color: var(--sc-fg);
background: var(--sc-surface);
border: 1px solid var(--sc-border);
border-radius: var(--sc-radius-lg);
box-shadow: var(--sc-shadow-sm);
}
.sc-card-header {
margin-bottom: 1rem;
}
.sc-card-header h2,
.sc-card-header h3 {
margin: 0;
font-size: 1.05rem;
}
.sc-card-header p {
margin: 0.375rem 0 0;
color: var(--sc-muted-fg);
font-size: 0.9rem;
}
.sc-badge {
display: inline-flex;
align-items: center;
min-height: 1.5rem;
padding: 0.125rem 0.5rem;
color: var(--sc-secondary-fg);
background: var(--sc-secondary);
border: 1px solid var(--sc-border);
border-radius: 999px;
font-size: 0.75rem;
font-weight: 650;
}
.sc-badge[data-variant='success'] {
color: var(--sc-success-fg);
background: var(--sc-success);
border-color: transparent;
}
.sc-badge[data-variant='warning'] {
color: var(--sc-warning-fg);
background: var(--sc-warning);
border-color: transparent;
}
.sc-badge[data-variant='danger'] {
color: var(--sc-danger-fg);
background: var(--sc-danger);
border-color: transparent;
}
.sc-button {
display: inline-flex;
align-items: center;
justify-content: center;
gap: 0.5rem;
min-height: 2.5rem;
padding: 0.625rem 1rem;
border: 1px solid transparent;
border-radius: var(--sc-radius-md);
font-size: 0.9rem;
font-weight: 650;
line-height: 1;
cursor: pointer;
transition: color 140ms ease, background 140ms ease, border-color 140ms ease, opacity 140ms ease;
}
.sc-button:hover:not(:disabled) {
transform: translateY(-1px);
}
.sc-button:disabled {
cursor: not-allowed;
opacity: 0.55;
}
.sc-button:focus-visible,
.sc-icon-button:focus-visible,
.sc-profile-button:focus-visible,
.sc-nav-link:focus-visible,
.sc-dialog-close:focus-visible {
outline: 3px solid color-mix(in srgb, var(--sc-ring) 45%, transparent);
outline-offset: 2px;
}
.sc-button-primary {
color: var(--sc-primary-fg);
background: var(--sc-primary);
}
.sc-button-primary:hover:not(:disabled) {
background: var(--sc-primary-hover);
}
.sc-button-secondary {
color: var(--sc-secondary-fg);
background: var(--sc-secondary);
border-color: var(--sc-border);
}
.sc-button-secondary:hover:not(:disabled) {
background: var(--sc-secondary-hover);
}
.sc-button-ghost {
color: var(--sc-muted-fg);
background: transparent;
}
.sc-button-ghost:hover:not(:disabled) {
color: var(--sc-fg);
background: var(--sc-surface-hover);
}
.sc-button-danger {
color: var(--sc-danger-fg);
background: var(--sc-danger);
}
.sc-button-danger:hover:not(:disabled) {
background: var(--sc-danger-hover);
}
.sc-button-sm {
min-height: 2rem;
padding: 0.45rem 0.75rem;
font-size: 0.8125rem;
}
.sc-button-lg {
min-height: 2.875rem;
padding: 0.75rem 1.25rem;
}
.sc-button-full {
width: 100%;
}
.sc-form {
display: grid;
gap: 1rem;
}
.sc-field {
display: grid;
gap: 0.4rem;
}
.sc-label {
color: var(--sc-fg);
font-size: 0.85rem;
font-weight: 650;
}
.sc-label-optional {
color: var(--sc-muted-fg);
font-weight: 400;
}
.sc-totp-settings {
display: grid;
gap: 0.75rem;
margin-top: 1.5rem;
padding-top: 1.25rem;
border-top: 1px solid var(--sc-border);
}
.sc-totp-heading {
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 1rem;
}
.sc-totp-heading h3 {
margin: 0;
font-size: 0.95rem;
}
.sc-totp-heading p {
margin: 0.25rem 0 0;
}
.sc-totp-status {
flex: 0 0 auto;
border: 1px solid var(--sc-border);
border-radius: 999px;
padding: 0.2rem 0.55rem;
color: var(--sc-muted-fg);
font-size: 0.75rem;
font-weight: 600;
}
.sc-totp-status.sc-totp-enabled {
border-color: var(--sc-success);
color: var(--sc-success);
}
.sc-totp-secret {
display: grid;
gap: 0.5rem;
color: var(--sc-muted-fg);
font-size: 0.8rem;
overflow-wrap: anywhere;
}
.sc-totp-secret p {
margin: 0;
}
.sc-totp-secret code {
display: block;
border-radius: 0.4rem;
background: var(--sc-input-bg);
padding: 0.6rem;
color: var(--sc-fg);
font-size: 0.7rem;
}
.sc-input,
.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;
}
.sc-textarea {
min-height: 7rem;
resize: vertical;
}
.sc-input::placeholder,
.sc-textarea::placeholder {
color: var(--sc-subtle-fg);
}
.sc-input:focus,
.sc-select:focus,
.sc-textarea:focus {
border-color: var(--sc-ring);
box-shadow: 0 0 0 3px color-mix(in srgb, var(--sc-ring) 22%, transparent);
}
.sc-form-actions,
.sc-dialog-footer {
display: flex;
justify-content: flex-end;
gap: 0.625rem;
margin-top: 0.5rem;
}
.sc-error {
padding: 0.75rem;
color: var(--sc-danger);
background: color-mix(in srgb, var(--sc-danger) 12%, transparent);
border: 1px solid color-mix(in srgb, var(--sc-danger) 35%, transparent);
border-radius: var(--sc-radius-md);
font-size: 0.875rem;
line-height: 1.45;
}
.sc-success {
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 {
display: flex;
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;
}
.sc-user-form {
padding: 0.9rem;
border: 1px solid var(--sc-border);
border-radius: 0.6rem;
background: var(--sc-surface-raised);
}
.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;
color: var(--sc-muted-fg);
text-overflow: ellipsis;
white-space: nowrap;
}
.sc-user-role {
color: var(--sc-muted-fg);
font-size: 0.8rem;
text-transform: capitalize;
}
.sc-user-actions {
display: flex;
flex-shrink: 0;
gap: 0.4rem;
}
.sc-user-edit-row {
align-items: stretch;
flex-wrap: wrap;
}
.sc-user-edit-row .sc-input {
flex: 1 1 10rem;
min-width: 8rem;
}
@media (max-width: 620px) {
.sc-user-grid {
grid-template-columns: 1fr;
}
.sc-user-row {
align-items: flex-start;
flex-wrap: wrap;
}
.sc-user-actions {
width: 100%;
}
}
.sc-auth-page {
display: grid;
min-height: 100vh;
place-items: center;
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%),
var(--sc-bg);
}
.sc-auth-card {
width: min(100%, 28rem);
padding: clamp(1.5rem, 5vw, 2.5rem);
background: var(--sc-surface);
border: 1px solid var(--sc-border);
border-radius: var(--sc-radius-xl);
box-shadow: var(--sc-shadow-lg);
}
.sc-auth-brand {
display: flex;
align-items: center;
gap: 0.75rem;
margin-bottom: 1.5rem;
font-weight: 750;
}
.sc-auth-card h1 {
font-size: 1.7rem;
}
.sc-auth-form {
margin-top: 1.5rem;
}
.sc-auth-extra {
margin-top: 1rem;
}
.sc-auth-reset {
display: grid;
gap: 0.625rem;
margin-top: 1.25rem;
padding-top: 1rem;
border-top: 1px solid var(--sc-border);
}
.sc-auth-reset-hint {
color: var(--sc-subtle-fg);
font-size: 0.75rem;
line-height: 1.45;
}
.sc-auth-reset-link {
display: block;
margin: 1.25rem auto 0;
padding: 0;
color: var(--sc-subtle-fg);
font: inherit;
font-size: 0.75rem;
text-decoration: underline;
background: none;
border: 0;
cursor: pointer;
}
.sc-auth-reset-link:hover {
color: var(--sc-fg);
}
.sc-dialog-backdrop {
position: fixed;
z-index: 100;
inset: 0;
display: grid;
place-items: center;
padding: 1rem;
background: var(--sc-backdrop);
backdrop-filter: blur(5px);
}
.sc-dialog {
width: min(100%, 34rem);
max-height: min(90vh, 48rem);
overflow: auto;
color: var(--sc-fg);
background: var(--sc-surface-raised);
border: 1px solid var(--sc-border);
border-radius: var(--sc-radius-xl);
box-shadow: var(--sc-shadow-lg);
}
.sc-dialog-header {
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 1rem;
padding: 1.25rem 1.25rem 0;
}
.sc-dialog-title {
font-size: 1.25rem;
}
.sc-dialog-close {
display: grid;
width: 2rem;
height: 2rem;
place-items: center;
color: var(--sc-muted-fg);
background: transparent;
border: 1px solid transparent;
border-radius: var(--sc-radius-sm);
font-size: 1.35rem;
line-height: 1;
cursor: pointer;
}
.sc-dialog-close:hover {
color: var(--sc-fg);
background: var(--sc-surface-hover);
border-color: var(--sc-border);
}
.sc-dialog-body {
padding: 1.25rem;
}
.sc-dialog-footer {
padding: 0 1.25rem 1.25rem;
}
.sc-about-links {
display: grid;
gap: 0.5rem;
margin-top: 1rem;
}
.sc-about-links a {
color: var(--sc-primary);
text-decoration: none;
}
.sc-about-links a:hover {
color: var(--sc-primary-hover);
text-decoration: underline;
}
.sc-profile-summary {
display: grid;
gap: 0.25rem;
margin-bottom: 1.25rem;
padding: 0.875rem;
background: var(--sc-bg);
border: 1px solid var(--sc-border);
border-radius: var(--sc-radius-md);
}
.sc-profile-summary strong {
color: var(--sc-fg);
}
.sc-profile-summary span {
color: var(--sc-muted-fg);
font-size: 0.875rem;
}
@media (max-width: 45rem) {
.sc-header {
flex-wrap: wrap;
gap: 0.75rem;
padding: 0.75rem 1rem;
}
.sc-mobile-menu-button {
display: grid;
order: 3;
width: 2.25rem;
height: 2.25rem;
margin-left: auto;
place-items: center;
}
.sc-nav {
display: none;
flex-basis: 100%;
order: 4;
flex-direction: column;
align-items: stretch;
padding-bottom: 0.25rem;
}
.sc-nav[data-open='true'] {
display: flex;
}
.sc-nav-link {
width: 100%;
}
.sc-header-actions {
margin-left: 0;
}
.sc-profile-button {
max-width: 9rem;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
}
@media (max-width: 30rem) {
.sc-main {
width: min(100% - 1.25rem, 90rem);
padding-top: 1.25rem;
}
.sc-page-header {
flex-direction: column;
}
}
@@ -1,85 +0,0 @@
import type { Snippet } from 'svelte';
export type AsyncAction<T = void> = (value: T) => void | Promise<void>;
export interface NavItem {
href: string;
label: string;
}
export interface AuthSetupInput {
username: string;
email: string;
password: string;
}
export interface AuthLoginInput {
identifier: string;
password: string;
totpToken?: string;
}
export interface TotpSetupResponse {
secret: string;
otpauthUrl: string;
enabled?: boolean;
}
export type TotpStatusRequest = () => boolean | Promise<boolean>;
export type TotpSetupRequest = () => TotpSetupResponse | Promise<TotpSetupResponse>;
export type TotpTokenAction = (token: string) => void | Promise<void>;
export type AuthResetRequest = () => void | Promise<unknown>;
export type AuthResetConfirm = (code: string) => void | Promise<unknown>;
export interface ProfileUpdateInput {
username: string;
email: string;
password?: string;
}
export type UserRole = 'superadmin' | 'admin' | 'user';
export type UserId = string | number;
export interface ManagedUser {
id: UserId;
username: string;
email: string;
role: UserRole;
totpEnabled?: boolean;
createdAt?: string;
updatedAt?: string;
}
export interface UserCreateInput {
username: string;
email: string;
password: string;
role?: UserRole;
}
export interface UserUpdateInput {
username?: string;
email?: string;
password?: string;
role?: UserRole;
}
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;
@@ -1 +0,0 @@
export default {};
-18
View File
@@ -1,18 +0,0 @@
{
"compilerOptions": {
"allowJs": true,
"checkJs": true,
"esModuleInterop": true,
"forceConsistentCasingInFileNames": true,
"moduleResolution": "bundler",
"skipLibCheck": true,
"strict": true,
"target": "ES2022",
"verbatimModuleSyntax": true
},
"include": [
"src/**/*.d.ts",
"src/**/*.ts",
"src/**/*.svelte"
]
}
-15
View File
@@ -1,15 +0,0 @@
import { readFile, writeFile } from 'node:fs/promises';
const source = await readFile(new URL('../packages/web-ui/dist/styles.css', import.meta.url), 'utf8');
const tokenImport = "@import '@gabriel20xx/design-tokens/theme.css';";
const componentStyles = source
.split(/\r?\n/)
.filter((line) => line.trim() !== tokenImport)
.join('\n')
.trimStart();
await writeFile(
new URL('../shared-styles.css', import.meta.url),
`@import './packages/design-tokens/theme.css';\n\n${componentStyles}`,
'utf8'
);
-26
View File
@@ -1,26 +0,0 @@
import { execFileSync } from 'node:child_process';
import { readdirSync, statSync } from 'node:fs';
import { join, relative } from 'node:path';
import { fileURLToPath } from 'node:url';
const root = fileURLToPath(new URL('..', import.meta.url));
const directories = ['packages/node-backend/src', 'packages/node-backend/test'];
function javascriptFiles(directory) {
const absoluteDirectory = join(root, directory);
const files = [];
for (const entry of readdirSync(absoluteDirectory)) {
const absolutePath = join(absoluteDirectory, entry);
if (statSync(absolutePath).isFile() && /\.(?:c|m)?js$/.test(entry)) {
files.push(absolutePath);
}
}
return files;
}
for (const directory of directories) {
for (const file of javascriptFiles(directory)) {
execFileSync(process.execPath, ['--check', file], { stdio: 'inherit' });
console.log(`Syntax OK: ${relative(root, file)}`);
}
}
-13
View File
@@ -1,13 +0,0 @@
$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."
-51
View File
@@ -1,51 +0,0 @@
#!/usr/bin/env bash
set -euo pipefail
readonly module_path='repos.gfranz.ch/Gabriel20xx/shared/backend'
readonly module_directory='backend'
release_tag="${1:?usage: package-go-module.sh backend/vX.Y.Z [output-directory]}"
output_directory="${2:-dist}"
version="${release_tag#backend/}"
if [[ "$release_tag" != backend/v* ]] || [[ ! "$version" =~ ^v[0-9]+\.[0-9]+\.[0-9]+([.-][0-9A-Za-z.-]+)?$ ]]; then
echo "Expected a release tag such as backend/v0.1.0; got: $release_tag" >&2
exit 1
fi
repository_root="$(git rev-parse --show-toplevel)"
git rev-parse --verify --quiet "${release_tag}^{commit}" >/dev/null || {
echo "Release tag does not resolve to a commit: $release_tag" >&2
exit 1
}
stage_directory="$(mktemp -d)"
trap 'rm -rf "$stage_directory"' EXIT
module_root="$stage_directory/${module_path}@${version}"
mkdir -p "$module_root"
# Go module ZIP files must contain <module>@<version>/ at their root. The
# module is stored in the backend/ subdirectory of the shared repository,
# so strip that repository directory while extracting the tagged source.
git archive --format=tar "$release_tag" "$module_directory" \
| tar -x --strip-components=1 -C "$module_root"
test -f "$module_root/go.mod"
grep -Fxq "module $module_path" "$module_root/go.mod"
if [[ "$output_directory" = /* ]]; then
output_path="$output_directory"
else
output_path="$repository_root/$output_directory"
fi
mkdir -p "$output_path"
zip_file="$output_path/${module_path//\//_}@${version}.zip"
rm -f "$zip_file"
(
cd "$stage_directory"
zip -qr "$zip_file" "${module_path}@${version}"
)
unzip -tq "$zip_file" >/dev/null
echo "Created $zip_file"
-324
View File
@@ -1,324 +0,0 @@
[CmdletBinding()]
param(
[string]$SourceRepository,
[switch]$Force,
[switch]$Commit,
[switch]$Push
)
$ErrorActionPreference = 'Stop'
if ($Push -and -not $Commit) {
throw 'The -Push switch requires -Commit so that only generated synchronization changes are pushed.'
}
$consumerProjects = @(
'Original/SimpleCollection',
'Original/CollabTable',
'Original/GameStream',
'Original/SyncServer',
'Original/UnraidMonitor',
'Original/PubliSafe',
'Original/MediaCollection',
'Forks/Bitmagnet',
'Forks/Heretic',
'Original/InfiniteVideo',
'Forks/MegaBasterd',
'Forks/HordeWorkerReGen',
'Original/OutdoorGames'
)
function Invoke-GitText {
param(
[Parameter(Mandatory = $true)]
[string]$WorkingDirectory,
[Parameter(Mandatory = $true)]
[string[]]$Arguments
)
$output = & git -C $WorkingDirectory @Arguments 2>&1
$exitCode = $LASTEXITCODE
if ($exitCode -ne 0) {
$diagnostics = @($output | ForEach-Object { [string]$_ } | Where-Object { -not [string]::IsNullOrWhiteSpace($_) })
$blockingDiagnostics = @($diagnostics | Where-Object { $_ -notmatch '^\s*(warning|hint):' })
if ($blockingDiagnostics.Count -eq 0) {
$diagnostics | ForEach-Object { Write-Warning $_ }
}
else {
$details = $diagnostics -join [Environment]::NewLine
throw "git $($Arguments -join ' ') failed in '$WorkingDirectory'. $details"
}
}
return @($output | ForEach-Object { [string]$_ })
}
function Resolve-FullPath {
param(
[Parameter(Mandatory = $true)]
[string]$Path
)
return (Resolve-Path -LiteralPath $Path -ErrorAction Stop).Path
}
function Get-RelativePath {
param(
[Parameter(Mandatory = $true)]
[string]$BasePath,
[Parameter(Mandatory = $true)]
[string]$TargetPath
)
$base = (Resolve-FullPath $BasePath).TrimEnd('\') + '\'
$target = Resolve-FullPath $TargetPath
if (-not $target.StartsWith($base, [System.StringComparison]::OrdinalIgnoreCase)) {
throw "'$TargetPath' is not inside '$BasePath'."
}
return $target.Substring($base.Length).Replace('\', '/')
}
function Write-Utf8NoBom {
param(
[Parameter(Mandatory = $true)]
[string]$Path,
[Parameter(Mandatory = $true)]
[string]$Content
)
$encoding = New-Object System.Text.UTF8Encoding($false)
$normalizedContent = $Content.Replace("`r`n", "`n").Replace("`r", "`n")
[System.IO.File]::WriteAllText($Path, $normalizedContent, $encoding)
}
function Convert-ToConsumerWebUiPackage {
param(
[Parameter(Mandatory = $true)]
[string]$PackagePath
)
$manifest = Get-Content -LiteralPath $PackagePath -Raw | ConvertFrom-Json
$manifest.files = @('src', 'README.md')
$manifest.dependencies = [pscustomobject]@{}
$manifest.svelte = './src/index.ts'
$manifest.types = './src/index.ts'
$rootExport = $manifest.exports.PSObject.Properties | Where-Object { $_.Name -eq '.' }
if ($null -ne $rootExport) {
$rootExport.Value.types = './src/index.ts'
$rootExport.Value.svelte = './src/index.ts'
$rootExport.Value.import = './src/index.ts'
}
$stylesExport = $manifest.exports.PSObject.Properties | Where-Object { $_.Name -eq './styles.css' }
if ($null -ne $stylesExport) {
$stylesExport.Value = './src/lib/styles.css'
}
$json = $manifest | ConvertTo-Json -Depth 20
Write-Utf8NoBom -Path $PackagePath -Content ($json + [Environment]::NewLine)
}
function Convert-ToConsumerWebUiSources {
param(
[Parameter(Mandatory = $true)]
[string]$WebUiRoot
)
$stylesPath = Join-Path $WebUiRoot 'src/lib/styles.css'
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';")
Write-Utf8NoBom -Path $stylesPath -Content $styles
}
$svelteConfigPath = Join-Path $WebUiRoot 'svelte.config.js'
if (Test-Path -LiteralPath $svelteConfigPath) {
Write-Utf8NoBom -Path $svelteConfigPath -Content "export default {};`n"
}
}
function Test-LocalSharedDependency {
param(
[Parameter(Mandatory = $true)]
$PackageManifest
)
$localPackageNames = @(
'@gabriel20xx/web-ui',
'@gabriel20xx/node-backend'
)
foreach ($sectionName in @('dependencies', 'devDependencies', 'optionalDependencies')) {
$sectionProperty = $PackageManifest.PSObject.Properties[$sectionName]
if ($null -eq $sectionProperty -or $null -eq $sectionProperty.Value) {
continue
}
foreach ($dependency in $sectionProperty.Value.PSObject.Properties) {
if ($dependency.Name -in $localPackageNames -and ([string]$dependency.Value).StartsWith('file:')) {
return $true
}
}
}
return $false
}
if ([string]::IsNullOrWhiteSpace($SourceRepository)) {
$scriptParent = Resolve-FullPath (Join-Path $PSScriptRoot '..')
if ((Split-Path -Leaf $scriptParent) -ieq 'shared') {
$SourceRepository = $scriptParent
}
else {
$consumerRoot = Resolve-FullPath (Join-Path $PSScriptRoot '..\..')
$SourceRepository = Join-Path $consumerRoot '..\..\shared'
}
}
$sourceRoot = Resolve-FullPath $SourceRepository
$sourceRepositoryRoot = (Invoke-GitText -WorkingDirectory $sourceRoot -Arguments @('rev-parse', '--show-toplevel') | Select-Object -First 1).Trim()
$sourceRoot = Resolve-FullPath $sourceRepositoryRoot
$workspaceRoot = Split-Path -Parent $sourceRoot
$sourceCommit = (Invoke-GitText -WorkingDirectory $sourceRoot -Arguments @('rev-parse', '--short', 'HEAD') | Select-Object -First 1).Trim()
$sourceFiles = @(Invoke-GitText -WorkingDirectory $sourceRoot -Arguments @('ls-files') | Where-Object { -not [string]::IsNullOrWhiteSpace($_) })
$sourceFileSet = @{}
foreach ($sourceFile in $sourceFiles) {
$sourceFileSet[$sourceFile.Replace('\', '/')] = $true
}
Write-Host "Synchronizing $($sourceFiles.Count) tracked SharedCode files from $sourceCommit."
$failures = New-Object 'System.Collections.Generic.List[string]'
foreach ($relativeProject in $consumerProjects) {
$projectRoot = Join-Path $workspaceRoot ($relativeProject -replace '/', '\')
if (-not (Test-Path -LiteralPath $projectRoot -PathType Container)) {
$failures.Add("${relativeProject}: project directory not found")
continue
}
try {
$projectRoot = Resolve-FullPath $projectRoot
$destinationRoot = Join-Path $projectRoot 'SharedCode'
$dirtySharedCode = @(Invoke-GitText -WorkingDirectory $projectRoot -Arguments @('status', '--porcelain', '--', 'SharedCode'))
if ($dirtySharedCode.Count -gt 0 -and -not $Force) {
throw "SharedCode has local changes. Commit them or rerun with -Force."
}
New-Item -ItemType Directory -Force -Path $destinationRoot | Out-Null
$existingSharedFiles = @(Invoke-GitText -WorkingDirectory $projectRoot -Arguments @('ls-files', '--', 'SharedCode') | Where-Object { $_ -like 'SharedCode/*' })
foreach ($existingSharedFile in $existingSharedFiles) {
$relativeSharedFile = $existingSharedFile.Substring('SharedCode/'.Length).Replace('\', '/')
if (-not $sourceFileSet.ContainsKey($relativeSharedFile)) {
$stalePath = Join-Path $destinationRoot ($relativeSharedFile -replace '/', '\')
if (Test-Path -LiteralPath $stalePath -PathType Leaf) {
Remove-Item -LiteralPath $stalePath -Force
}
}
}
foreach ($sourceFile in $sourceFiles) {
$sourcePath = Join-Path $sourceRoot ($sourceFile -replace '/', '\')
$destinationPath = Join-Path $destinationRoot ($sourceFile -replace '/', '\')
$destinationDirectory = Split-Path -Parent $destinationPath
New-Item -ItemType Directory -Force -Path $destinationDirectory | Out-Null
Copy-Item -LiteralPath $sourcePath -Destination $destinationPath -Force
}
$webUiPackagePath = Join-Path $destinationRoot 'packages/web-ui/package.json'
if (Test-Path -LiteralPath $webUiPackagePath) {
Convert-ToConsumerWebUiPackage -PackagePath $webUiPackagePath
Convert-ToConsumerWebUiSources -WebUiRoot (Join-Path $destinationRoot 'packages/web-ui')
}
$lockFiles = @()
$sharedCodePrefix = ((Resolve-FullPath $destinationRoot).TrimEnd('\') + '\')
$packageFiles = @(Get-ChildItem -LiteralPath $projectRoot -Recurse -File -Filter 'package.json' -Force |
Where-Object {
$_.FullName -notlike "$sharedCodePrefix*" -and
$_.FullName -notmatch '\\node_modules\\'
})
foreach ($packageFile in $packageFiles) {
$packageManifest = Get-Content -LiteralPath $packageFile.FullName -Raw | ConvertFrom-Json
if (-not (Test-LocalSharedDependency -PackageManifest $packageManifest)) {
continue
}
$lockPath = Join-Path $packageFile.DirectoryName 'package-lock.json'
if (-not (Test-Path -LiteralPath $lockPath -PathType Leaf)) {
continue
}
$relativeLockPath = Get-RelativePath -BasePath $projectRoot -TargetPath $lockPath
$trackedLock = @(Invoke-GitText -WorkingDirectory $projectRoot -Arguments @('ls-files', '--', $relativeLockPath))
$shouldStageLock = $trackedLock.Count -gt 0
Write-Host " Updating $relativeProject/$(Get-RelativePath -BasePath $projectRoot -TargetPath $lockPath)"
Push-Location -LiteralPath $packageFile.DirectoryName
try {
& npm install --package-lock-only --ignore-scripts --prefer-offline
if ($LASTEXITCODE -ne 0) {
throw "npm install --package-lock-only failed with exit code $LASTEXITCODE."
}
}
finally {
Pop-Location
}
if ($shouldStageLock -and $lockFiles -notcontains $relativeLockPath) {
$lockFiles += $relativeLockPath
}
elseif (-not $shouldStageLock) {
Write-Host " Leaving untracked/ignored lockfile out of the generated commit: $relativeLockPath"
}
}
$null = Invoke-GitText -WorkingDirectory $projectRoot -Arguments @('add', '--', 'SharedCode')
foreach ($lockFile in $lockFiles) {
$null = Invoke-GitText -WorkingDirectory $projectRoot -Arguments @('add', '--', $lockFile)
}
$targetPaths = @('SharedCode') + $lockFiles
$stagedChanges = @(Invoke-GitText -WorkingDirectory $projectRoot -Arguments (@('diff', '--cached', '--name-only', '--') + $targetPaths))
if ($Commit -and $stagedChanges.Count -gt 0) {
$commitMessage = "Sync SharedCode snapshot from $sourceCommit"
$commitArguments = @('commit', '--only', '-m', $commitMessage, '--') + $targetPaths
$commitOutput = @(Invoke-GitText -WorkingDirectory $projectRoot -Arguments $commitArguments)
$commitOutput | ForEach-Object { Write-Host " $_" }
$remainingStagedChanges = @(Invoke-GitText -WorkingDirectory $projectRoot -Arguments (@('diff', '--cached', '--name-only', '--') + $targetPaths))
if ($remainingStagedChanges.Count -gt 0) {
throw 'The generated synchronization changes remain staged after the commit.'
}
}
if ($Push) {
$pushOutput = @(Invoke-GitText -WorkingDirectory $projectRoot -Arguments @('push', 'origin', 'main'))
$pushOutput | ForEach-Object { Write-Host " $_" }
}
if ($stagedChanges.Count -gt 0) {
Write-Host "Synced $relativeProject."
}
else {
Write-Host "$relativeProject is already synchronized."
}
}
catch {
$message = "${relativeProject}: $($_.Exception.Message)"
$failures.Add($message)
Write-Warning $message
}
}
if ($failures.Count -gt 0) {
throw "SharedCode synchronization failed for $($failures.Count) project(s): $($failures -join '; ')"
}
Write-Host 'SharedCode synchronization completed.'
-613
View File
@@ -1,613 +0,0 @@
@import './packages/design-tokens/theme.css';
:where(.sc-root, .sc-root *) {
box-sizing: border-box;
}
.sc-root {
min-height: 100%;
color: var(--sc-fg);
background: var(--sc-bg);
font-family: var(--sc-font-sans);
}
.sc-root button,
.sc-root input,
.sc-root textarea,
.sc-root select {
font: inherit;
}
.sc-root a {
color: inherit;
}
.sc-app-shell {
min-height: 100vh;
color: var(--sc-fg);
background: var(--sc-bg);
}
.sc-main {
width: min(100% - 2rem, 90rem);
margin: 0 auto;
padding: 2rem 0 3rem;
}
.sc-header {
position: sticky;
z-index: 20;
top: 0;
display: flex;
align-items: center;
gap: 1.25rem;
min-height: 4rem;
padding: 0 1rem;
color: var(--sc-fg);
background: color-mix(in srgb, var(--sc-surface) 92%, transparent);
border-bottom: 1px solid var(--sc-border);
backdrop-filter: blur(14px);
}
.sc-brand {
display: inline-flex;
flex: 0 0 auto;
align-items: center;
gap: 0.625rem;
color: var(--sc-fg);
font-size: 1rem;
font-weight: 750;
text-decoration: none;
letter-spacing: -0.01em;
}
.sc-brand-mark {
display: grid;
width: 2rem;
height: 2rem;
place-items: center;
color: var(--sc-primary-fg);
background: var(--sc-primary);
border-radius: var(--sc-radius-md);
font-size: 0.875rem;
font-weight: 800;
}
.sc-nav {
display: flex;
flex: 1 1 auto;
align-items: center;
gap: 0.25rem;
}
.sc-nav-link,
.sc-profile-button,
.sc-icon-button {
border: 1px solid transparent;
border-radius: var(--sc-radius-md);
transition: color 140ms ease, background 140ms ease, border-color 140ms ease;
}
.sc-nav-link {
padding: 0.5rem 0.75rem;
color: var(--sc-muted-fg);
font-size: 0.9rem;
text-decoration: none;
}
.sc-nav-link:hover,
.sc-nav-link[data-active='true'] {
color: var(--sc-fg);
background: var(--sc-surface-hover);
border-color: var(--sc-border);
}
.sc-header-actions {
display: flex;
align-items: center;
gap: 0.5rem;
margin-left: auto;
}
.sc-icon-button,
.sc-profile-button {
color: var(--sc-muted-fg);
background: transparent;
cursor: pointer;
}
.sc-icon-button {
display: grid;
width: 2.25rem;
height: 2.25rem;
place-items: center;
font-size: 1.15rem;
}
.sc-profile-button {
padding: 0.5rem 0.75rem;
font-size: 0.875rem;
}
.sc-icon-button:hover,
.sc-profile-button:hover {
color: var(--sc-fg);
background: var(--sc-surface-hover);
border-color: var(--sc-border);
}
.sc-mobile-menu-button {
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;
color: var(--sc-fg);
font-weight: 750;
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 {
margin: 0.5rem 0 0;
color: var(--sc-muted-fg);
line-height: 1.55;
}
.sc-card {
padding: 1.25rem;
color: var(--sc-fg);
background: var(--sc-surface);
border: 1px solid var(--sc-border);
border-radius: var(--sc-radius-lg);
box-shadow: var(--sc-shadow-sm);
}
.sc-card-header {
margin-bottom: 1rem;
}
.sc-card-header h2,
.sc-card-header h3 {
margin: 0;
font-size: 1.05rem;
}
.sc-card-header p {
margin: 0.375rem 0 0;
color: var(--sc-muted-fg);
font-size: 0.9rem;
}
.sc-badge {
display: inline-flex;
align-items: center;
min-height: 1.5rem;
padding: 0.125rem 0.5rem;
color: var(--sc-secondary-fg);
background: var(--sc-secondary);
border: 1px solid var(--sc-border);
border-radius: 999px;
font-size: 0.75rem;
font-weight: 650;
}
.sc-badge[data-variant='success'] {
color: var(--sc-success-fg);
background: var(--sc-success);
border-color: transparent;
}
.sc-badge[data-variant='warning'] {
color: var(--sc-warning-fg);
background: var(--sc-warning);
border-color: transparent;
}
.sc-badge[data-variant='danger'] {
color: var(--sc-danger-fg);
background: var(--sc-danger);
border-color: transparent;
}
.sc-button {
display: inline-flex;
align-items: center;
justify-content: center;
gap: 0.5rem;
min-height: 2.5rem;
padding: 0.625rem 1rem;
border: 1px solid transparent;
border-radius: var(--sc-radius-md);
font-size: 0.9rem;
font-weight: 650;
line-height: 1;
cursor: pointer;
transition: color 140ms ease, background 140ms ease, border-color 140ms ease, opacity 140ms ease;
}
.sc-button:hover:not(:disabled) {
transform: translateY(-1px);
}
.sc-button:disabled {
cursor: not-allowed;
opacity: 0.55;
}
.sc-button:focus-visible,
.sc-icon-button:focus-visible,
.sc-profile-button:focus-visible,
.sc-nav-link:focus-visible,
.sc-dialog-close:focus-visible {
outline: 3px solid color-mix(in srgb, var(--sc-ring) 45%, transparent);
outline-offset: 2px;
}
.sc-button-primary {
color: var(--sc-primary-fg);
background: var(--sc-primary);
}
.sc-button-primary:hover:not(:disabled) {
background: var(--sc-primary-hover);
}
.sc-button-secondary {
color: var(--sc-secondary-fg);
background: var(--sc-secondary);
border-color: var(--sc-border);
}
.sc-button-secondary:hover:not(:disabled) {
background: var(--sc-secondary-hover);
}
.sc-button-ghost {
color: var(--sc-muted-fg);
background: transparent;
}
.sc-button-ghost:hover:not(:disabled) {
color: var(--sc-fg);
background: var(--sc-surface-hover);
}
.sc-button-danger {
color: var(--sc-danger-fg);
background: var(--sc-danger);
}
.sc-button-danger:hover:not(:disabled) {
background: var(--sc-danger-hover);
}
.sc-button-sm {
min-height: 2rem;
padding: 0.45rem 0.75rem;
font-size: 0.8125rem;
}
.sc-button-lg {
min-height: 2.875rem;
padding: 0.75rem 1.25rem;
}
.sc-button-full {
width: 100%;
}
.sc-form {
display: grid;
gap: 1rem;
}
.sc-field {
display: grid;
gap: 0.4rem;
}
.sc-label {
color: var(--sc-fg);
font-size: 0.85rem;
font-weight: 650;
}
.sc-label-optional {
color: var(--sc-muted-fg);
font-weight: 400;
}
.sc-input,
.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;
}
.sc-textarea {
min-height: 7rem;
resize: vertical;
}
.sc-input::placeholder,
.sc-textarea::placeholder {
color: var(--sc-subtle-fg);
}
.sc-input:focus,
.sc-select:focus,
.sc-textarea:focus {
border-color: var(--sc-ring);
box-shadow: 0 0 0 3px color-mix(in srgb, var(--sc-ring) 22%, transparent);
}
.sc-form-actions,
.sc-dialog-footer {
display: flex;
justify-content: flex-end;
gap: 0.625rem;
margin-top: 0.5rem;
}
.sc-error {
padding: 0.75rem;
color: var(--sc-danger);
background: color-mix(in srgb, var(--sc-danger) 12%, transparent);
border: 1px solid color-mix(in srgb, var(--sc-danger) 35%, transparent);
border-radius: var(--sc-radius-md);
font-size: 0.875rem;
line-height: 1.45;
}
.sc-success {
color: var(--sc-success);
}
.sc-auth-page {
display: grid;
min-height: 100vh;
place-items: center;
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%),
var(--sc-bg);
}
.sc-auth-card {
width: min(100%, 28rem);
padding: clamp(1.5rem, 5vw, 2.5rem);
background: var(--sc-surface);
border: 1px solid var(--sc-border);
border-radius: var(--sc-radius-xl);
box-shadow: var(--sc-shadow-lg);
}
.sc-auth-brand {
display: flex;
align-items: center;
gap: 0.75rem;
margin-bottom: 1.5rem;
font-weight: 750;
}
.sc-auth-card h1 {
font-size: 1.7rem;
}
.sc-auth-form {
margin-top: 1.5rem;
}
.sc-auth-extra {
margin-top: 1rem;
}
.sc-auth-reset {
display: grid;
gap: 0.625rem;
margin-top: 1.25rem;
padding-top: 1rem;
border-top: 1px solid var(--sc-border);
}
.sc-auth-reset-hint {
color: var(--sc-subtle-fg);
font-size: 0.75rem;
line-height: 1.45;
}
.sc-auth-reset-link {
display: block;
margin: 1.25rem auto 0;
padding: 0;
color: var(--sc-subtle-fg);
font: inherit;
font-size: 0.75rem;
text-decoration: underline;
background: none;
border: 0;
cursor: pointer;
}
.sc-auth-reset-link:hover {
color: var(--sc-fg);
}
.sc-dialog-backdrop {
position: fixed;
z-index: 100;
inset: 0;
display: grid;
place-items: center;
padding: 1rem;
background: var(--sc-backdrop);
backdrop-filter: blur(5px);
}
.sc-dialog {
width: min(100%, 34rem);
max-height: min(90vh, 48rem);
overflow: auto;
color: var(--sc-fg);
background: var(--sc-surface-raised);
border: 1px solid var(--sc-border);
border-radius: var(--sc-radius-xl);
box-shadow: var(--sc-shadow-lg);
}
.sc-dialog-header {
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 1rem;
padding: 1.25rem 1.25rem 0;
}
.sc-dialog-title {
font-size: 1.25rem;
}
.sc-dialog-close {
display: grid;
width: 2rem;
height: 2rem;
place-items: center;
color: var(--sc-muted-fg);
background: transparent;
border: 1px solid transparent;
border-radius: var(--sc-radius-sm);
font-size: 1.35rem;
line-height: 1;
cursor: pointer;
}
.sc-dialog-close:hover {
color: var(--sc-fg);
background: var(--sc-surface-hover);
border-color: var(--sc-border);
}
.sc-dialog-body {
padding: 1.25rem;
}
.sc-dialog-footer {
padding: 0 1.25rem 1.25rem;
}
.sc-about-links {
display: grid;
gap: 0.5rem;
margin-top: 1rem;
}
.sc-about-links a {
color: var(--sc-primary);
text-decoration: none;
}
.sc-about-links a:hover {
color: var(--sc-primary-hover);
text-decoration: underline;
}
.sc-profile-summary {
display: grid;
gap: 0.25rem;
margin-bottom: 1.25rem;
padding: 0.875rem;
background: var(--sc-bg);
border: 1px solid var(--sc-border);
border-radius: var(--sc-radius-md);
}
.sc-profile-summary strong {
color: var(--sc-fg);
}
.sc-profile-summary span {
color: var(--sc-muted-fg);
font-size: 0.875rem;
}
@media (max-width: 45rem) {
.sc-header {
flex-wrap: wrap;
gap: 0.75rem;
padding: 0.75rem 1rem;
}
.sc-mobile-menu-button {
display: grid;
order: 3;
width: 2.25rem;
height: 2.25rem;
margin-left: auto;
place-items: center;
}
.sc-nav {
display: none;
flex-basis: 100%;
order: 4;
flex-direction: column;
align-items: stretch;
padding-bottom: 0.25rem;
}
.sc-nav[data-open='true'] {
display: flex;
}
.sc-nav-link {
width: 100%;
}
.sc-header-actions {
margin-left: 0;
}
.sc-profile-button {
max-width: 9rem;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
}
@media (max-width: 30rem) {
.sc-main {
width: min(100% - 1.25rem, 90rem);
padding-top: 1.25rem;
}
.sc-page-header {
flex-direction: column;
}
}
+1 -1
View File
@@ -7,7 +7,7 @@ require (
github.com/joho/godotenv v1.5.1
)
replace repos.gfranz.ch/Gabriel20xx/shared/backend => ../SharedCode/backend
replace repos.gfranz.ch/Gabriel20xx/shared/backend => ../shared/backend
require golang.org/x/crypto v0.54.0 // indirect
+2 -2
View File
@@ -1,7 +1,7 @@
FROM node:22-alpine AS frontend-builder
WORKDIR /frontend
COPY frontend/package*.json ./
COPY SharedCode/packages/web-ui /SharedCode/packages/web-ui
COPY shared/packages/web-ui /shared/packages/web-ui
RUN --mount=type=cache,target=/root/.npm \
for attempt in 1 2 3 4 5; do \
npm ci && break; \
@@ -16,7 +16,7 @@ RUN npm run build
FROM golang:1.26-alpine AS builder
WORKDIR /app
COPY backend/go.mod backend/go.sum ./
COPY SharedCode/backend/ /SharedCode/backend/
COPY shared/backend/ /shared/backend/
RUN go mod download
COPY backend/*.go ./
COPY --from=frontend-builder /frontend/build ./web
+1 -1
View File
@@ -30,7 +30,7 @@
"vite": "latest"
},
"dependencies": {
"@gabriel20xx/web-ui": "file:../SharedCode/packages/web-ui",
"@gabriel20xx/web-ui": "file:../shared/packages/web-ui",
"@lucide/svelte": "latest",
"@tanstack/svelte-query": "latest",
"bits-ui": "latest",