feat: improve navigation and add security scans
Security / Secrets (gitleaks) (push) Successful in 1m29s
Lint / Lint (push) Successful in 1m43s
Security / Dependencies (Trivy) (push) Successful in 1m59s
Security / Code (Semgrep) (push) Successful in 3m34s
Tests / Dashboard checks (push) Successful in 1m2s
Tests / Go backend (push) Successful in 3m13s
Docker / Docker Build & Push (push) Successful in 8m15s

- Hide the lone navigation tab and show mobile menus as overlays
- Add secret, code, and dependency scanning to CI
- Update test workflows and remove an unused frontend dependency
This commit is contained in:
Gabriel20xx committed 2026-10-27 09:54:10 +00:00
1 parent 85e6db67b5
commit 817236f349
23 files changed
+299 -74

No files matched your search

-1
View File
@@ -45,7 +45,6 @@
"version": "0.1.1",
"license": "MIT",
"dependencies": {
"@gabriel20xx/design-tokens": "0.1.1",
"@lucide/svelte": "1.28.0"
},
"devDependencies": {
+5
View File
@@ -0,0 +1,5 @@
---
"@gabriel20xx/web-ui": patch
---
`Header` no longer renders the primary navigation tab, or the mobile menu toggle, when `navItems` has only one entry. A lone item is just the app's home page, so projects like OmniLogger and OutdoorGames no longer show a single "Dashboard" tab in the header.
@@ -0,0 +1,5 @@
---
"@gabriel20xx/web-ui": patch
---
Open the mobile navigation menu as an overlay below the header instead of inserting it into the header row. Opening the menu no longer pushes the page content down, and long menus scroll within the viewport.
+143
View File
@@ -0,0 +1,143 @@
name: Security
on:
push:
branches: ['**']
pull_request:
branches: [main, master]
schedule:
# Weekly, so advisories published after the last push still get reported.
- cron: '23 5 * * 1'
workflow_dispatch: {}
jobs:
secrets:
name: Secrets (gitleaks)
runs-on: ubuntu-latest
permissions:
contents: read
steps:
- name: Checkout code
uses: actions/checkout@v7
with:
# Full history, so a secret that was committed and later removed is still found.
fetch-depth: 0
submodules: false
- name: Set up Go
uses: actions/setup-go@v5
with:
go-version: stable
# gitleaks runs at a pinned version. go run checks the module against the Go checksum
# database. Known false positives go in .gitleaks.toml at the repo root, which gitleaks reads
# on its own.
- name: Scan git history for secrets
run: go run github.com/zricethezav/gitleaks/v8@v8.30.1 git --no-banner --redact --exit-code 1 .
code:
name: Code (Semgrep)
runs-on: ubuntu-latest
permissions:
contents: read
steps:
- name: Checkout code
uses: actions/checkout@v7
with:
submodules: false
- name: Set up Python
uses: actions/setup-python@v5
with:
python-version: '3.12'
- name: Install Semgrep
run: pip install semgrep==1.182.1
# Fails on ERROR findings from Semgrep's default rules. WARNING findings are not gated.
- name: Scan code
run: semgrep scan --config p/default --severity ERROR --error --metrics=off .
dependencies:
name: Dependencies (Trivy)
runs-on: ubuntu-latest
permissions:
contents: read
env:
TRIVY_VERSION: '0.76.1'
steps:
- name: Checkout code
uses: actions/checkout@v7
with:
submodules: false
- name: Set up Node
uses: actions/setup-node@v4
with:
node-version: 24
- name: Set up Python
uses: actions/setup-python@v5
with:
python-version: '3.12'
- name: Install uv
run: pip install uv==0.13.5
- name: Install Trivy
# Downloaded from the release and checked against its published checksums. The
# aquasecurity/trivy-action version tags were repointed to malicious commits in March 2026,
# so that action is not used.
shell: bash
run: |
archive="trivy_${TRIVY_VERSION}_Linux-64bit.tar.gz"
base_url="https://github.com/aquasecurity/trivy/releases/download/v${TRIVY_VERSION}"
curl --fail --location --retry 5 --retry-delay 2 \
--output "$RUNNER_TEMP/$archive" "$base_url/$archive"
curl --fail --location --retry 5 --retry-delay 2 \
--output "$RUNNER_TEMP/trivy_checksums.txt" "$base_url/trivy_${TRIVY_VERSION}_checksums.txt"
(cd "$RUNNER_TEMP" && grep -F " $archive" trivy_checksums.txt > trivy_checksum.txt \
&& sha256sum -c trivy_checksum.txt)
tar -xzf "$RUNNER_TEMP/$archive" -C "$RUNNER_TEMP" trivy
echo "$RUNNER_TEMP" >> "$GITHUB_PATH"
"$RUNNER_TEMP/trivy" --version
# Trivy audits lockfiles and skips bare manifests. For each manifest with no lockfile in its
# own folder or any parent folder, resolve one here so its dependencies get scanned. These
# lockfiles are made only for this run and are not committed.
- name: Resolve manifests that have no lockfile
shell: bash
run: |
has_lockfile() {
local dir=$1
shift
while true; do
for lockfile in "$@"; do
if [ -f "$dir/$lockfile" ]; then
return 0
fi
done
if [ "$dir" = "." ]; then
return 1
fi
dir=$(dirname "$dir")
done
}
while IFS= read -r -d '' manifest; do
dir=$(dirname "$manifest")
if ! has_lockfile "$dir" package-lock.json yarn.lock pnpm-lock.yaml; then
echo "Resolving npm dependencies in $dir"
(cd "$dir" && npm install --package-lock-only --ignore-scripts --no-audit --no-fund)
fi
done < <(find . -name node_modules -prune -o -name package.json -print0)
while IFS= read -r -d '' manifest; do
dir=$(dirname "$manifest")
if ! has_lockfile "$dir" uv.lock poetry.lock Pipfile.lock; then
echo "Resolving Python dependencies in $dir"
(cd "$dir" && uv lock)
fi
done < <(find . -name node_modules -prune -o -name .venv -prune -o -name pyproject.toml -print0)
# Fails on HIGH and CRITICAL vulnerabilities that have a fixed version. Vulnerabilities with no
# fix are left out, because nothing can be changed to clear them. Development dependencies are
# included, since build and test tooling runs in CI.
# --offline-scan: Maven Central rate-limits the lookups Trivy makes for pom.xml, so Maven
# dependencies are read from their declared versions only. Transitive ones are not resolved.
- name: Scan dependencies for known vulnerabilities
run: >-
trivy fs --scanners vuln --severity HIGH,CRITICAL --ignore-unfixed --include-dev-deps
--offline-scan --exit-code 1 --timeout 15m .
+12 -5
View File
@@ -65,15 +65,15 @@ jobs:
POSTGRES_PASSWORD: postgres
POSTGRES_DB: scratch
ports:
- 5432:5432
- 5432/tcp
options: >-
--health-cmd "pg_isready -U postgres"
--health-interval 5s
--health-timeout 5s
--health-retries 10
env:
DATABASE_URL: postgres://postgres:postgres@localhost:5432/scratch?sslmode=disable
SHARED_TEST_DATABASE_URL: postgres://postgres:postgres@localhost:5432/scratch?sslmode=disable
DATABASE_URL: postgres://postgres:postgres@localhost:${{ job.services.postgres.ports['5432'] }}/scratch?sslmode=disable
SHARED_TEST_DATABASE_URL: postgres://postgres:postgres@localhost:${{ job.services.postgres.ports['5432'] }}/scratch?sslmode=disable
steps:
- name: Checkout
uses: actions/checkout@v4
@@ -84,7 +84,14 @@ jobs:
cache: true
# -p 1 runs one package at a time, because the database tests share one scratch database.
- name: Run Go tests
run: go test -p 1 ./...
shell: bash
run: |
# Gitea Actions runs jobs in a container, where the service is reached by its label.
if [ "${GITEA_ACTIONS:-}" = "true" ]; then
export DATABASE_URL="postgres://postgres:postgres@postgres:5432/scratch?sslmode=disable"
export SHARED_TEST_DATABASE_URL="postgres://postgres:postgres@postgres:5432/scratch?sslmode=disable"
fi
go test -p 1 ./...
python:
name: Test (Python)
@@ -99,7 +106,7 @@ jobs:
with:
python-version: '3.12'
- name: Install package
run: python -m pip install --upgrade pip -e "packages/python-backend[fastapi]"
run: python -m pip install --upgrade pip -e "packages/python-backend[fastapi,test]"
- name: Run Python tests
run: python -m unittest discover -s packages/python-backend/tests -p 'test_*.py'
+16
View File
@@ -0,0 +1,16 @@
# gitleaks configuration. gitleaks reads this file from the repository root.
[extend]
useDefault = true
[allowlist]
description = "Test fixtures that contain placeholder credentials, not real secrets"
paths = [
'''(^|/)(tests?|__tests__)/''',
'''_test\.go$''',
'''\.test\.[jt]sx?$''',
'''\.spec\.[jt]sx?$''',
'''(^|/)test_[^/]*\.py$''',
'''Test\.java$''',
'''(^|/)contract/auth-contract\.json$''',
]
+14
View File
@@ -0,0 +1,14 @@
# Semgrep skips test code and fixtures. Tests hold placeholder credentials on purpose.
# auth-contract.json holds bcrypt hashes of test passwords shared by every service's tests.
auth-contract.json
test/
tests/
__tests__/
*_test.go
*.test.js
*.test.ts
*.test.tsx
*.spec.js
*.spec.ts
test_*.py
*Test.java
+1 -1
View File
@@ -92,5 +92,5 @@ The auth code has no obvious SQL N+1 outside the playlist reorder path, and most
- **Docker:** No Dockerfile, compose file or `.dockerignore` exists in this repository, so image size, multi-stage builds and base-image checks do not apply here. Consumer projects that build images from the vendored snapshot should be reviewed separately.
- **Frontend checks:** No whole-library imports were found; `@lucide/svelte` is imported by name in every component. No `{@html}`, unbounded caches or leaked intervals were found in the web-ui, and the timers and listeners in `MediaPlayer`, `MediaPlayerControls`, `StatusWidget`, `AppShell` and `notifications.svelte.ts` are cleaned up. `shared-styles.css` (1134 lines, about 21 KB) is loaded in full by consumers. As a component library it has no route-level code-splitting, which is expected rather than a defect. Four of seven `{#each}` blocks in the components are keyed; the remaining ones are listed under quality findings.
- **HTTP caching and compression:** Not applicable to the library code; the backends are API services and the static styles are shipped to consumers' own build pipelines.
- **Not verified:** No query plans (no database access), benchmarks or profiling. Node, Python and web-ui test suites and the web-ui package build passed; Go and Java checks were unavailable because their toolchains are absent.
- **Not verified:** No query plans (no database access), benchmarks or profiling. Node, Python, web-ui and Go checks passed; Java checks were unavailable because no JDK or Maven is installed.
- **Excluded from analysis:** `packages/web-ui/dist` and `.svelte-kit` (gitignored, not tracked), `package-lock.json` and `go.sum` (used for versions only).
+3 -3
View File
@@ -6,7 +6,7 @@
- **Commit:** 22887fe on main
- **Working tree:** Contains uncommitted changes from the earlier finding pass and this continuation; no changes have been committed.
- **Stack:** Go 1.25 (`backend/`: session proxy, AuthGuard client, websocket sync hub, media core, CarrierNode client, log shipper, Postgres helpers, goose migrations); Node.js ESM with `pg` (`packages/node-backend`); Python 3.10+ with asyncpg, bcrypt and optional FastAPI (`packages/python-backend`); Java 8 target with Jackson (`packages/java-backend`); Svelte 5 and TypeScript (`packages/web-ui`); PostgreSQL; Gitea and GitHub Actions. No Dockerfile is present.
- **Scope:** A shared library that other projects vendor as a snapshot. The AuthGuard identity service itself is not in this repository, so every finding that depends on AuthGuard's cookie attributes, rate limits or role enforcement is marked "needs verification". Read: all first-party code in the four languages (the Go auth package was read in a separate pass), the web-ui library source, workflows, scripts and manifests; git history was searched for credential-shaped content. Excluded: `node_modules`, `packages/web-ui/dist` and `.svelte-kit` (gitignored, not tracked), `package-lock.json` and `go.sum` (versions only), test bodies except to look for fixtures. Backend findings came from read-only static review passes, and the highest-severity citations were re-checked in the code. Available checks run during this continuation: shared Node/Python/web-ui suites, Svelte check, Node lint, Ruff, formatting and web-ui package build. Go and Java toolchains are absent; no production service or real database was used.
- **Scope:** A shared library that other projects vendor as a snapshot. The AuthGuard identity service itself is not in this repository, so every finding that depends on AuthGuard's cookie attributes, rate limits or role enforcement is marked "needs verification". Read: all first-party code in the four languages (the Go auth package was read in a separate pass), the web-ui library source, workflows, scripts and manifests; git history was searched for credential-shaped content. Excluded: `node_modules`, `packages/web-ui/dist` and `.svelte-kit` (gitignored, not tracked), `package-lock.json` and `go.sum` (versions only), test bodies except to look for fixtures. Backend findings came from read-only static review passes, and the highest-severity citations were re-checked in the code. Available checks run during this continuation: shared Node/Python/Go/web-ui suites, Svelte check, Node lint, Ruff, formatting and web-ui package build. Java tools remain unavailable; no production service or real database was used.
- **Updated:** 2026-10-20 — shared decisions implemented in the working tree: S-011 fixed; S-010 partly fixed with its undecided session-revocation portion left open. Available Node and web-ui checks pass; Python, Go and Java verification limits are recorded below.
## Summary
@@ -98,7 +98,7 @@ The most serious issue is a Python router route that lets an anonymous caller sw
- **Description:** Verification accepts the current and adjacent 30-second steps and records nothing about use. A code that an attacker observes stays valid for about 90 seconds and can be submitted repeatedly within that window.
- **Impact:** A phished or shoulder-surfed code can be reused.
- **Recommendation:** Return the matched time step, persist `last_used_step` per user, and reject any step less than or equal to it, updating it atomically.
- **Status:** Fixed 2026-10-20 — verifiers return the matched time step; Go, Node and Python stores add `last_used_step` through additive schema changes and atomically advance it only when the step is newer. AuthGuard consumes steps for login, enrollment and disable, so a code already used in its validity window is refused. Files: `backend/auth/{totp.go,store.go}`, `Central/AuthGuard/internal/httpapi/{auth.go,totp.go,server.go}`, `packages/{node-backend/src/{auth.js,totp.js},python-backend/src/shared_backend/{auth.py,totp.py},java-backend/src/main/java/com/gabriel20xx/shared/auth/Totp.java}`. Node/backend and web-ui checks passed; Go, Java and Python runtime tests could not run in this environment.
- **Status:** Fixed 2026-10-20 — verifiers return the matched time step; Go, Node and Python stores add `last_used_step` through additive schema changes and atomically advance it only when the step is newer. AuthGuard consumes steps for login, enrollment and disable, so a code already used in its validity window is refused. Files: `backend/auth/{totp.go,store.go}`, `Central/AuthGuard/internal/httpapi/{auth.go,totp.go,server.go}`, `packages/{node-backend/src/{auth.js,totp.js},python-backend/src/shared_backend/{auth.py,totp.py},java-backend/src/main/java/com/gabriel20xx/shared/auth/Totp.java}`. Go, Node, Python and web-ui checks passed; Java tests could not run because no JDK or Maven is available.
### S-012 · The Java client parses the authentication decision with unanchored regular expressions · **Medium** · Fixed
- **Location:** `packages/java-backend/src/main/java/com/gabriel20xx/shared/auth/AuthClient.java:109-112` (patterns for `valid`, `user_id`, `username`, `role`), with the parsing in `validate` (around lines 829-851, per review)
@@ -178,5 +178,5 @@ The most serious issue is a Python router route that lets an anonymous caller sw
- **Web UI:** No `{@html}`, `innerHTML`, `eval` or `new Function` was found. External links use `rel="noreferrer"`. `fetch` is used only in `StatusWidget.svelte` (same-origin relative paths with credentials included); auth requests are delegated to the consuming application through callbacks, so CSRF and session handling live in the backend. The primary-color writer builds CSS only from palette values.
- **Checked, no issue found:** SQL is parameterised in the Go, Node and Python stores and in the mediacore queries; dynamic `SET` fragments use fixed column names. Tokens and secrets come from `crypto/rand`, `crypto.randomBytes`, Python `secrets` and `SecureRandom`; no `math/rand`, `Math.random`, `random.` or `java.util.Random` was found. Session tokens are 256-bit and stored as SHA-256 hashes, and no JWT is used. No `eval`, `pickle`, `yaml.load`, `shell=True`, `os.system` or `exec.Command` appears in scope. No `InsecureSkipVerify` on any TLS configuration; the only use is the websocket origin option (S-014). The Go request bodies are capped (512 KB for mediacore, 4 KB for coreconfig, 128 KB for the proxy). Outbound clients have timeouts. Logout clears cookies with `HttpOnly` and `SameSite` in the Python proxy. No CORS configuration or debug mode was found.
- **Dependencies (not audited):** No known-vulnerable version is asserted in this report, since no audit tool or network access was used. Versions to confirm: Go `coder/websocket` v1.8.15, `go-chi/chi` v5.3.1, `pgx` v5.10.0, `goose` v3.27.3, `golang.org/x/crypto` v0.54.0 (`backend/go.mod`); Node `pg` 8.22.0 (locked in `package-lock.json`, declared `^8.17.2`); Python `bcrypt>=4.2` and `asyncpg>=0.30` with no upper bounds (`packages/python-backend/pyproject.toml`); Java Jackson 2.18.6, JUnit 5.10.2 (`packages/java-backend/pom.xml`). Run `govulncheck`, `npm audit`, `pip-audit` and an OWASP dependency check.
- **Not verified / coverage gaps:** AuthGuard's own server code (cookie attributes, rate limiting, role enforcement, session revocation on password change) is not in this repository, so every finding marked "needs verification" depends on it. Consumer wiring of `/ws`, `/media/*`, `/access` and the core-config route was not reviewed. `backend/auth` and `backend/config` were covered by a separate pass. CarrierNode-side path validation and the file types it stores are outside the repository. Java `AuthClient` cookie and redirect behaviour was assessed from code only. The shared Node (73 tests), Python (122 tests), and web-ui (29 tests) suites were run; Go and Java suites were unavailable because their toolchains are absent. No server was started.
- **Not verified / coverage gaps:** AuthGuard's own server code (cookie attributes, rate limiting, role enforcement, session revocation on password change) is not in this repository, so every finding marked "needs verification" depends on it. Consumer wiring of `/ws`, `/media/*`, `/access` and the core-config route was not reviewed. `backend/auth` and `backend/config` were covered by a separate pass. CarrierNode-side path validation and the file types it stores are outside the repository. Java `AuthClient` cookie and redirect behaviour was assessed from code only. The shared Node (73 tests), Python (122 tests), and web-ui (29 tests) suites plus Go `go test ./...`, `go vet ./...` and `gofmt -l` passed; Java tests were unavailable because no JDK or Maven is installed. No server was started.
- **Excluded from analysis:** `packages/web-ui/dist` and `.svelte-kit` (gitignored, not tracked), `package-lock.json` and `go.sum` (versions only), and `node_modules`.
+12 -12
View File
@@ -19,12 +19,12 @@ type authContract struct {
Plaintext string `json:"plaintext"`
WrongPassword string `json:"wrongPassword"`
Hashes []struct {
Name string `json:"name"`
Hash string `json:"hash"`
Password string `json:"password"`
WrongPassword string `json:"wrongPassword"`
Verifies map[string]bool `json:"verifies"`
NeedsUpgrade map[string]bool `json:"needsUpgrade"`
Name string `json:"name"`
Hash string `json:"hash"`
Password string `json:"password"`
WrongPassword string `json:"wrongPassword"`
Verifies map[string]bool `json:"verifies"`
NeedsUpgrade map[string]bool `json:"needsUpgrade"`
} `json:"hashes"`
TooLongToHash struct {
Bytes int `json:"bytes"`
@@ -34,12 +34,12 @@ type authContract struct {
TOTP struct {
Secret string `json:"secret"`
Cases []struct {
Name string `json:"name"`
Unix int64 `json:"unix"`
Code string `json:"code"`
Secret *string `json:"secret"`
MatchedStep *int64 `json:"matchedStep"`
Valid bool `json:"valid"`
Name string `json:"name"`
Unix int64 `json:"unix"`
Code string `json:"code"`
Secret *string `json:"secret"`
MatchedStep *int64 `json:"matchedStep"`
Valid bool `json:"valid"`
} `json:"cases"`
} `json:"totp"`
ClientAddress struct {
+1 -1
View File
@@ -26,7 +26,7 @@ const bcryptScheme = "bcrypt$"
const bcryptSHA256Scheme = "bcrypt-sha256$"
const (
maxPasswordBytes = 72
maxPasswordBytes = 72
legacyPBKDF2Iterations = 100000
maxPBKDF2Iterations = 10000000
)
+13 -13
View File
@@ -291,10 +291,10 @@ type Service struct {
// allowed email-only edits without the current password. Password changes
// always require current credentials in UpdateMe.
reauthenticateEmailChanges bool
loginCacheMu sync.Mutex
loginCacheValue bool
loginCacheSet bool
loginCacheExpires time.Time
loginCacheMu sync.Mutex
loginCacheValue bool
loginCacheSet bool
loginCacheExpires time.Time
// Attempt counters for the credential endpoints; see ratelimit.go.
loginAccountAttempts *attemptLimiter
loginClientAttempts *attemptLimiter
@@ -397,16 +397,16 @@ func NewWithStore(store ProxyStore, cookieName string, secureCookies bool, authG
configurationError = errSecretNotUsable
}
return &Service{
store: store,
cookieName: cookieName,
secureCookies: secureCookies,
authGuard: client,
configurationError: configurationError,
store: store,
cookieName: cookieName,
secureCookies: secureCookies,
authGuard: client,
configurationError: configurationError,
reauthenticateEmailChanges: options.reauthenticateEmailChanges,
loginAccountAttempts: newAttemptLimiter(attemptWindow, loginAccountLimit),
loginClientAttempts: newAttemptLimiter(attemptWindow, loginClientLimit),
totpAttempts: newAttemptLimiter(attemptWindow, totpAttemptLimit),
trustedProxies: options.trustedProxies,
loginAccountAttempts: newAttemptLimiter(attemptWindow, loginAccountLimit),
loginClientAttempts: newAttemptLimiter(attemptWindow, loginClientLimit),
totpAttempts: newAttemptLimiter(attemptWindow, totpAttemptLimit),
trustedProxies: options.trustedProxies,
}
}
+6 -6
View File
@@ -433,13 +433,13 @@ func TestUpdateMeValidatesAndForwardsToAuthGuard(t *testing.T) {
t.Fatalf("ordinary user: status = %d, want 403", rec.Code)
}
for name, body := range map[string]string{
"bad email": `{"email":"nope","username":"boss"}`,
"at in username": `{"email":"a@b.com","username":"a@b.com"}`,
"short password": `{"email":"a@b.com","username":"boss","password":"short"}`,
"long password": `{"email":"a@b.com","username":"boss","password":"` + strings.Repeat("a", 73) + `"}`,
"bad email": `{"email":"nope","username":"boss"}`,
"at in username": `{"email":"a@b.com","username":"a@b.com"}`,
"short password": `{"email":"a@b.com","username":"boss","password":"short"}`,
"long password": `{"email":"a@b.com","username":"boss","password":"` + strings.Repeat("a", 73) + `"}`,
"missing current password": `{"email":"a@b.com","username":"boss","password":"new-password"}`,
"missing current totp": `{"email":"a@b.com","username":"boss","password":"new-password","currentPassword":"current-password"}`,
"not JSON": `nope`,
"missing current totp": `{"email":"a@b.com","username":"boss","password":"new-password","currentPassword":"current-password"}`,
"not JSON": `nope`,
} {
if rec := update(manager, body); rec.Code != http.StatusBadRequest {
t.Errorf("%s: status = %d, want 400", name, rec.Code)
+4 -4
View File
@@ -16,10 +16,10 @@ import (
// TOTP follows RFC 6238's default interoperable profile.
const (
TOTPPeriod = 30 * time.Second
TOTPDigits = 6
TOTPSecretBytes = 20
TOTPWindow = 1
TOTPPeriod = 30 * time.Second
TOTPDigits = 6
TOTPSecretBytes = 20
TOTPWindow = 1
)
// GenerateTOTPSecret returns a base32 secret suitable for authenticator apps.
@@ -3,11 +3,7 @@ import assert from 'node:assert/strict';
import { existsSync, readFileSync } from 'node:fs';
import { hashPassword, passwordHashNeedsUpgrade, verifyAndUpgradePasswordAsync, verifyPassword } from '../src/auth.js';
import { verifyTotp, verifyTotpStep } from '../src/totp.js';
import {
EXAMPLE_INTERNAL_SECRETS,
MIN_INTERNAL_SECRET_LENGTH,
internalSecretMatches,
} from '../src/coreconfig.js';
import { EXAMPLE_INTERNAL_SECRETS, MIN_INTERNAL_SECRET_LENGTH, internalSecretMatches } from '../src/coreconfig.js';
// The Go, Node and Python auth helpers load the same fixtures; see "description" in the file.
const contractUrl = new URL('../../../contract/auth-contract.json', import.meta.url);
@@ -22,6 +22,7 @@ dependencies = [
# consumer does) satisfies this from its own requirements regardless.
[project.optional-dependencies]
fastapi = ["fastapi>=0.100", "pydantic>=2"]
test = ["httpx2>=2"]
[tool.setuptools.packages.find]
where = ["src"]
+7 -8
View File
@@ -5,7 +5,7 @@
"license": "MIT",
"type": "module",
"files": [
"dist",
"src",
"README.md"
],
"sideEffects": [
@@ -15,7 +15,6 @@
"svelte": "^5.0.0"
},
"dependencies": {
"@gabriel20xx/design-tokens": "0.1.1",
"@lucide/svelte": "1.28.0"
},
"devDependencies": {
@@ -31,15 +30,15 @@
"package": "svelte-package",
"test": "vitest run"
},
"svelte": "./dist/index.js",
"types": "./dist/index.d.ts",
"svelte": "./src/index.ts",
"types": "./src/index.ts",
"exports": {
".": {
"types": "./dist/index.d.ts",
"svelte": "./dist/index.js",
"import": "./dist/index.js"
"types": "./src/index.ts",
"svelte": "./src/index.ts",
"import": "./src/index.ts"
},
"./styles.css": "./dist/styles.css",
"./styles.css": "./src/lib/styles.css",
"./package.json": "./package.json"
}
}
@@ -74,6 +74,21 @@ function mixHex(hex: string, towards: number, weight: number): string {
return `#${channels.map((c) => Math.round(c + (towards - c) * weight).toString(16).padStart(2, '0')).join('')}`
}
// WCAG relative luminance of a #rrggbb color, from 0 (black) to 1 (white).
function luminance(hex: string): number {
const [red, green, blue] = [1, 3, 5].map((start) => {
const channel = parseInt(hex.slice(start, start + 2), 16) / 255
return channel <= 0.03928 ? channel / 12.92 : ((channel + 0.055) / 1.055) ** 2.4
})
return 0.2126 * red + 0.7152 * green + 0.0722 * blue
}
// WCAG contrast ratio between two #rrggbb colors, from 1 (no contrast) to 21 (black on white).
function contrastRatio(a: string, b: string): number {
const [lighter, darker] = [luminance(a), luminance(b)].sort((x, y) => y - x)
return (lighter + 0.05) / (darker + 0.05)
}
// The color is written to a stylesheet rather than inline on <html>. Shared and app CSS re-declare these
// tokens on every [data-theme] element (the AppShell root, for one), and that declaration hides the value
// <html> would pass down, so the choice never reached the app's UI. Targeting [data-theme] elements with
@@ -83,7 +98,9 @@ function primaryDeclarations(color: PaletteColor, dark: boolean): string {
// Hover is lighter on dark and darker on light, as in the shared theme. It is a hex value, not color-mix(),
// because consumers such as the terminal read these tokens as plain colors.
const hover = dark ? mixHex(primary, 255, 0.15) : mixHex(primary, 0, 0.15)
const foreground = dark ? color.darkFg : '#ffffff'
// Text on the primary is white or the palette's dark text, whichever reads better. Mid-tone light colors
// are too light for white text, so the choice follows the color rather than the theme.
const foreground = contrastRatio(primary, '#ffffff') >= contrastRatio(primary, color.darkFg) ? '#ffffff' : color.darkFg
return [
...primaryVars.map((name) => `${name}: ${primary} !important;`),
`--sc-primary-hover: ${hover} !important;`,
+14 -4
View File
@@ -1,4 +1,4 @@
@import "@gabriel20xx/design-tokens/theme.css";
@import '../../../design-tokens/theme.css';
:where(.sc-root, .sc-root *) {
box-sizing: border-box;
@@ -1111,13 +1111,23 @@ html[data-wide-layout='true'] .sc-main {
transform: translateX(-50%);
}
/* Overlay the page below the header instead of wrapping onto a new row, so opening the menu
doesn't push the content down. */
.sc-nav {
display: none;
flex-basis: 100%;
order: 4;
position: absolute;
top: 100%;
right: 0;
left: 0;
z-index: 20;
flex-direction: column;
align-items: stretch;
padding-bottom: 0.25rem;
max-height: calc(100dvh - 4rem);
padding: 0.5rem 1rem 0.75rem;
overflow-y: auto;
background: var(--sc-surface);
border-bottom: 1px solid var(--sc-border);
box-shadow: var(--sc-shadow-lg);
}
.sc-nav[data-open="true"] {
+1 -5
View File
@@ -1,5 +1 @@
import { vitePreprocess } from '@sveltejs/vite-plugin-svelte';
export default {
preprocess: vitePreprocess()
};
export default {};
@@ -36,12 +36,12 @@ describe('ProfileDialog password changes', () => {
await submit();
expect(onSave).not.toHaveBeenCalled();
expect(screen.getByText('Enter your current password to change it.')).toBeTruthy();
expect(screen.getByText('Enter your current password to change your email or password.')).toBeTruthy();
await fill('currentPassword', 'old-password');
await submit();
expect(onSave).not.toHaveBeenCalled();
expect(screen.getByText('Enter a current authenticator code to change your password.')).toBeTruthy();
expect(screen.getByText('Enter a current authenticator code to change your email or password.')).toBeTruthy();
await fill('totpToken', '123456');
await submit();
@@ -54,6 +54,13 @@ describe('primary color', () => {
expect(styleText()).not.toContain('#db3e24');
});
it('uses dark text on light colors where white would be hard to read', () => {
applyPrimaryColor('app', 'Honey');
const [light] = styleText().split("[data-theme='dark']");
expect(light).toContain('--sc-primary-fg: #2a2b0d !important;');
expect(light).not.toContain('--sc-primary-fg: #ffffff !important;');
});
it('makes the hover lighter on dark and darker on light', () => {
applyPrimaryColor('app', 'Clover');
const [light, dark] = styleText().split("[data-theme='dark']");
+13 -3
View File
@@ -1111,13 +1111,23 @@ html[data-wide-layout='true'] .sc-main {
transform: translateX(-50%);
}
/* Overlay the page below the header instead of wrapping onto a new row, so opening the menu
doesn't push the content down. */
.sc-nav {
display: none;
flex-basis: 100%;
order: 4;
position: absolute;
top: 100%;
right: 0;
left: 0;
z-index: 20;
flex-direction: column;
align-items: stretch;
padding-bottom: 0.25rem;
max-height: calc(100dvh - 4rem);
padding: 0.5rem 1rem 0.75rem;
overflow-y: auto;
background: var(--sc-surface);
border-bottom: 1px solid var(--sc-border);
box-shadow: var(--sc-shadow-lg);
}
.sc-nav[data-open="true"] {