Compare commits

...

2 commits

Author SHA1 Message Date
Daniel Noulet
2967f1a5af refactor
Some checks are pending
Build, test, publish, deploy / build-test (push) Waiting to run
Build, test, publish, deploy / publish (push) Blocked by required conditions
Build, test, publish, deploy / deploy-prd (push) Blocked by required conditions
2026-10-10 02:30:01 +02:00
Daniel Noulet
d0ea6e9eec ci: add Forgejo build and deployment workflows 2026-10-08 10:36:32 +02:00
34 changed files with 775 additions and 183 deletions

View file

@ -55,7 +55,7 @@ BANANAS_PUBLIC_BASE_URL=http://localhost:8080
# The development realm. A production deployment points this at its own provider;
# only the issuer, client credentials and group mapping are provider-specific.
BANANAS_OIDC_ISSUER=https://auth-dev.urpi.be/realms/urpi
BANANAS_OIDC_ISSUER=https://auth.lcl-urpi.be/realms/urpi
BANANAS_OIDC_CLIENT_ID=go-bananas
# BANANAS_OIDC_CLIENT_SECRET=read-from-a-secret

View file

@ -0,0 +1,175 @@
#!/usr/bin/env bash
set -Eeuo pipefail
NAMESPACE=go-insane-prd
REGISTRY=nexus.urpi.be
CERT_MANAGER_VERSION=v1.19.1
LOCAL_PATH_VERSION=v0.0.37
LOCK_NAME=forgejo-prd-deploy-lock
if [[ $# -lt 4 ]]; then
echo "Usage: $0 <chart> <release> <image-name> <image-tag> [helm args...]" >&2
exit 2
fi
CHART=$1
RELEASE=$2
IMAGE_NAME=$3
IMAGE_TAG=$4
shift 4
: "${KUBECONFIG_PRD:?Set the Forgejo secret KUBECONFIG_PRD to the PRD kubeconfig contents}"
: "${NEXUS_USERNAME:?Set the Forgejo secret NEXUS_USERNAME}"
: "${NEXUS_PASSWORD:?Set the Forgejo secret NEXUS_PASSWORD}"
KUBECONFIG="${RUNNER_TEMP:-/tmp}/kubeconfig-prd-${GITHUB_RUN_ID:-$$}"
umask 077
printf '%s\n' "$KUBECONFIG_PRD" > "$KUBECONFIG"
export KUBECONFIG
LOCK_ACQUIRED=false
cleanup() {
if [[ "$LOCK_ACQUIRED" == true ]]; then kubectl -n "$NAMESPACE" delete configmap "$LOCK_NAME" --ignore-not-found --wait=false >/dev/null 2>&1 || true; fi
rm -f "$KUBECONFIG"
}
trap cleanup EXIT
secret_value() {
local name=$1 key=$2 encoded
encoded="$(kubectl -n "$NAMESPACE" get secret "$name" -o go-template="{{index .data \"${key}\"}}" 2>/dev/null || true)"
[[ -z "$encoded" || "$encoded" == "<no value>" ]] && return 0
printf '%s' "$encoded" | base64 -d 2>/dev/null || true
}
kubectl get --raw=/readyz >/dev/null
# Create the workload namespace and its Nexus pull credential idempotently.
kubectl create namespace "$NAMESPACE" --dry-run=client -o yaml | kubectl apply -f -
for attempt in {1..360}; do
if kubectl -n "$NAMESPACE" create configmap "$LOCK_NAME" --from-literal=owner="${GITHUB_REPOSITORY:-local}:${GITHUB_RUN_ID:-$$}" >/dev/null 2>&1; then LOCK_ACQUIRED=true; break; fi
sleep 5
done
if [[ "$LOCK_ACQUIRED" != true ]]; then echo "Timed out waiting for another go-insane-prd deploy to release its lock." >&2; exit 1; fi
kubectl -n "$NAMESPACE" create secret docker-registry nexus-registry \
--docker-server="$REGISTRY" \
--docker-username="$NEXUS_USERNAME" \
--docker-password="$NEXUS_PASSWORD" \
--dry-run=client -o yaml | kubectl apply -f -
# Stateful charts use the cluster default StorageClass. Install the Rancher local
# path provisioner only when the cluster has no default class at all.
DEFAULT_STORAGE_CLASS="$(kubectl get storageclass -o=jsonpath='{range .items[*]}{.metadata.name}{" "}{.metadata.annotations.storageclass\.kubernetes\.io/is-default-class}{"\n"}{end}' | awk '$2 == "true" { print $1; exit }')"
if [[ -z "$DEFAULT_STORAGE_CLASS" ]]; then
if ! kubectl get storageclass local-path >/dev/null 2>&1 || ! kubectl -n local-path-storage get deployment local-path-provisioner >/dev/null 2>&1; then
kubectl apply -f "https://raw.githubusercontent.com/rancher/local-path-provisioner/${LOCAL_PATH_VERSION}/deploy/local-path-storage.yaml"
kubectl -n local-path-storage rollout status deployment/local-path-provisioner --timeout=5m
fi
kubectl annotate storageclass local-path storageclass.kubernetes.io/is-default-class=true --overwrite
fi
# Applications' production charts request nginx ingress and Let's Encrypt TLS.
# Install only missing cluster prerequisites; leave existing installations intact.
if ! kubectl get ingressclass nginx >/dev/null 2>&1; then
helm repo add ingress-nginx https://kubernetes.github.io/ingress-nginx --force-update
helm repo update ingress-nginx
helm upgrade --install ingress-nginx ingress-nginx/ingress-nginx \
--namespace ingress-nginx --create-namespace \
--set controller.service.type=NodePort \
--set controller.hostPort.enabled=true \
--set controller.kind=DaemonSet \
--set controller.admissionWebhooks.enabled=false \
--wait --timeout 10m
fi
if ! kubectl get crd clusterissuers.cert-manager.io >/dev/null 2>&1 || ! kubectl -n cert-manager get deployment cert-manager >/dev/null 2>&1; then
kubectl apply --validate=false -f "https://github.com/cert-manager/cert-manager/releases/download/${CERT_MANAGER_VERSION}/cert-manager.yaml"
kubectl -n cert-manager rollout status deployment/cert-manager --timeout=5m
kubectl -n cert-manager rollout status deployment/cert-manager-cainjector --timeout=5m
kubectl -n cert-manager rollout status deployment/cert-manager-webhook --timeout=5m
fi
if ! kubectl get clusterissuer letsencrypt-prod >/dev/null 2>&1; then
kubectl apply -f - <<'ISSUER'
apiVersion: cert-manager.io/v1
kind: ClusterIssuer
metadata:
name: letsencrypt-prod
spec:
acme:
server: https://acme-v02.api.letsencrypt.org/directory
email: admin@urpi.be
privateKeySecretRef:
name: letsencrypt-prod
solvers:
- http01:
ingress:
class: nginx
ISSUER
fi
kubectl wait --for=condition=Ready clusterissuer/letsencrypt-prod --timeout=2m
if [[ ! -d "$CHART" ]]; then
echo "Helm chart not found: $CHART" >&2
exit 1
fi
if [[ -f "$CHART/Chart.lock" ]]; then helm dependency build "$CHART"; fi
HELM_ARGS=(
--namespace "$NAMESPACE"
--create-namespace
)
if [[ "$RELEASE" != go-guess ]]; then
HELM_ARGS+=(--set-string "image.repository=${REGISTRY}/docker-hosted/${IMAGE_NAME}" --set-string "image.tag=${IMAGE_TAG}")
fi
if [[ -f "$CHART/values-prd.yaml" ]]; then
HELM_ARGS+=(--values "$CHART/values-prd.yaml")
fi
case "$RELEASE" in
go-loose)
if ! kubectl -n "$NAMESPACE" get secret go-loose-runtime >/dev/null 2>&1; then
db_password="$(secret_value go-loose-postgresql postgres-password)"
if [[ -z "$db_password" ]] && kubectl -n "$NAMESPACE" get pvc -o name | grep -Eq 'go-loose.*postgresql|data-go-loose'; then
echo "Existing go-loose database storage has no recoverable password secret; refusing to rotate its credentials." >&2
exit 1
fi
[[ -n "$db_password" ]] || db_password="$(openssl rand -hex 24)"
session_secret="$(secret_value go-loose-env GO_LOOSE_SESSION_SECRET)"
[[ -n "$session_secret" ]] || session_secret="$(openssl rand -hex 32)"
kubectl -n "$NAMESPACE" create secret generic go-loose-runtime --from-literal=postgresql-password="$db_password" --from-literal=session-secret="$session_secret"
fi
db_password="$(secret_value go-loose-runtime postgresql-password)"
session_secret="$(secret_value go-loose-runtime session-secret)"
database_url="postgres://goloose:${db_password}@go-loose-postgresql:5432/goloose?sslmode=disable"
HELM_ARGS+=(--set-string "postgresql.auth.password=${db_password}" --set-string "envSecrets.GO_LOOSE_DATABASE_URL=${database_url}" --set-string "envSecrets.GO_LOOSE_SESSION_SECRET=${session_secret}")
;;
go-mad)
if ! kubectl -n "$NAMESPACE" get secret go-mad-runtime >/dev/null 2>&1; then
db_password="$(secret_value go-mad-postgresql password)"
[[ -n "$db_password" ]] || db_password="$(secret_value go-mad-postgresql postgres-password)"
if [[ -z "$db_password" ]] && kubectl -n "$NAMESPACE" get pvc -o name | grep -Eq 'go-mad.*postgresql|data-go-mad'; then
echo "Existing go-mad database storage has no recoverable password secret; refusing to rotate its credentials." >&2
exit 1
fi
[[ -n "$db_password" ]] || db_password="$(openssl rand -hex 24)"
kubectl -n "$NAMESPACE" create secret generic go-mad-runtime --from-literal=postgresql-password="$db_password" --from-literal=jwt-secret="$(openssl rand -hex 32)"
fi
db_password="$(secret_value go-mad-runtime postgresql-password)"
jwt_secret="$(secret_value go-mad-runtime jwt-secret)"
HELM_ARGS+=(--set-string "postgresql.auth.password=${db_password}" --set-string "go-mad.jwtSecret=${jwt_secret}")
;;
go-first)
if ! kubectl -n "$NAMESPACE" get secret go-first-runtime >/dev/null 2>&1; then
kubectl -n "$NAMESPACE" create secret generic go-first-runtime --from-literal=jwt-secret="$(openssl rand -hex 32)"
fi
;;
go-places)
: "${GO_LOOSE_JWT_SECRET:?Set Forgejo secret GO_LOOSE_JWT_SECRET to the same signing key used by go-loose}"
kubectl -n "$NAMESPACE" create secret generic go-loose-jwt --from-literal=secret="$GO_LOOSE_JWT_SECRET" --dry-run=client -o yaml | kubectl apply -f -
;;
go-bananas)
: "${GO_BANANAS_OIDC_CLIENT_SECRET:?Set Forgejo secret GO_BANANAS_OIDC_CLIENT_SECRET}"
session_secret="$(secret_value go-bananas-auth session-secret)"
if [[ -z "$session_secret" ]]; then session_secret="$(openssl rand -hex 32)"; fi
kubectl -n "$NAMESPACE" create secret generic go-bananas-auth --from-literal=session-secret="$session_secret" --from-literal=oidc-client-secret="$GO_BANANAS_OIDC_CLIENT_SECRET" --dry-run=client -o yaml | kubectl apply -f -
;;
esac
helm upgrade --install "$RELEASE" "$CHART" "${HELM_ARGS[@]}" "$@" --wait --timeout 15m
kubectl -n "$NAMESPACE" get deployments,statefulsets,pods,services,ingresses

View file

@ -0,0 +1,101 @@
name: Build, test, publish, deploy
on:
push:
pull_request:
workflow_dispatch:
env:
GO_VERSION: "1.27.1"
NODE_VERSION: "24"
REGISTRY: nexus.urpi.be
IMAGE_NAME: docker-hosted/go-bananas
jobs:
build-test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-go@v5
with:
go-version: ${{ env.GO_VERSION }}
cache: true
- uses: actions/setup-node@v4
with:
node-version: ${{ env.NODE_VERSION }}
cache: npm
cache-dependency-path: |
web/package-lock.json
sdk/package-lock.json
- name: Build and test Go server
run: |
go vet ./...
make test-go
make build-go
- name: Build and test admin UI
run: |
npm ci --no-audit --no-fund
npm run lint
npm test
npm run build
working-directory: web
- name: Build and test SDK
run: |
npm ci --no-audit --no-fund
npm run typecheck
npm test
npm run build
working-directory: sdk
- uses: azure/setup-helm@v4
with:
version: v3.18.6
- name: Validate production chart
run: helm lint --strict deploy/helm/go-bananas -f deploy/helm/go-bananas/values-prd.yaml
publish:
if: (github.event_name == 'push' && github.ref == 'refs/heads/main') || (github.event_name == 'workflow_dispatch' && github.ref == 'refs/heads/main')
needs: build-test
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: docker/setup-buildx-action@v3
- uses: docker/login-action@v3
with:
registry: ${{ env.REGISTRY }}
username: ${{ secrets.NEXUS_USERNAME }}
password: ${{ secrets.NEXUS_PASSWORD }}
- uses: docker/build-push-action@v6
with:
context: .
file: Dockerfile
push: true
tags: |
${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:${{ github.sha }}
${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:latest
deploy-prd:
if: (github.event_name == 'push' && github.ref == 'refs/heads/main') || (github.event_name == 'workflow_dispatch' && github.ref == 'refs/heads/main')
needs: publish
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: azure/setup-helm@v4
with:
version: v3.18.6
- uses: azure/setup-kubectl@v4
with:
version: v1.32.2
- name: Bootstrap resources and deploy go-bananas
env:
KUBECONFIG_PRD: ${{ secrets.KUBECONFIG_PRD }}
NEXUS_USERNAME: ${{ secrets.NEXUS_USERNAME }}
NEXUS_PASSWORD: ${{ secrets.NEXUS_PASSWORD }}
GO_BANANAS_OIDC_CLIENT_SECRET: ${{ secrets.GO_BANANAS_OIDC_CLIENT_SECRET }}
run: |
set -Eeuo pipefail
: "${GO_BANANAS_OIDC_CLIENT_SECRET:?Add Forgejo secret GO_BANANAS_OIDC_CLIENT_SECRET}"
bash .forgejo/scripts/deploy-prd.sh deploy/helm/go-bananas go-bananas go-bananas "${{ github.sha }}" \
--set-string identity.oidc.issuer=https://auth.urpi.be/realms/urpi \
--set-string identity.oidc.clientId=go-bananas \
--set-string identity.oidc.existingSecret=go-bananas-auth \
--set identity.oidc.generateSecret=false

View file

@ -32,7 +32,7 @@ VERSION ?= $(shell git describe --tags --always --dirty 2>/dev/null || echo
COMMIT ?= $(shell git rev-parse --short HEAD 2>/dev/null || echo unknown)
BUILD_DATE ?= $(shell date -u +%Y-%m-%dT%H:%M:%SZ)
REGISTRY ?= nexus.urpi.be
REGISTRY ?= nexus.urpi.be/docker-hosted
IMAGE_NAME ?= $(REGISTRY)/$(BINARY)
IMAGE_TAG ?= $(VERSION)
PLATFORM ?= linux/amd64,linux/arm64
@ -127,12 +127,13 @@ dev: ## Run the API with hot reload (Ctrl-C to stop)
air -c .air.toml
.PHONY: dev-api
dev-api: ## Run only the API server, no frontend
dev-api: ## Run the API (no SPA); Vite serves the UI, this serves the runtime SDK
@BANANAS_ENVIRONMENT=development \
BANANAS_AUTH_MODE=dev \
BANANAS_HTTP_ADDR=:8080 \
BANANAS_DATABASE_PATH=./data/go-bananas.db \
BANANAS_STATIC_DIR= BANANAS_SDK_DIR= \
BANANAS_STATIC_DIR= \
BANANAS_SDK_DIR=$(SDK_DIR)/dist \
$(GO) run -ldflags "$(LDFLAGS)" $(CMD)
.PHONY: dev-web
@ -140,7 +141,7 @@ dev-web: ## Run the Vite dev server for the admin UI, proxying the API
cd $(WEB_DIR) && $(NPM) run dev
.PHONY: dev-all
dev-all: ## Run the API and the frontend dev server together
dev-all: build-sdk ## Run the API and the frontend dev server together
@echo "API on http://localhost:8080, admin UI on http://localhost:5173"
@trap 'kill 0' EXIT; \
$(MAKE) dev-api & \
@ -375,7 +376,7 @@ helm-template: ## Render the chart with the default values
helm-template-auth: ## Render the chart configured for OIDC
$(HELM) template go-bananas deploy/helm/go-bananas \
--set identity.mode=oidc \
--set identity.oidc.issuer=https://auth-dev.urpi.be/realms/urpi \
--set identity.oidc.issuer=https://auth.lcl-urpi.be/realms/urpi \
--set identity.oidc.clientId=go-bananas \
--set identity.oidc.generateSecret=false \
--set identity.oidc.existingSecret=go-bananas-oidc \
@ -392,6 +393,61 @@ helm-install: ## Install the chart into the current kube context ##@destructive
helm-uninstall: ## Remove the release ##@destructive
$(HELM) uninstall go-bananas --namespace go-bananas
##@ Local (lcl)
# The lcl environment is the developer's local k3s cluster with a registry at
# localhost:5000 and a TLS edge serving *.intern-urpi.be. go-* apps deploy into the
# shared `go-insane-lcl` namespace. These targets use values-lcl.yaml.
#
# KUBECONFIG — the lcl kubeconfig. On this box the `local` kubecontext goes through a
# Rancher proxy that can 502; the direct k3s config is /etc/rancher/k3s/k3s.yaml.
# Set it to deploy without depending on the proxy: KUBECONFIG=/etc/rancher/k3s/k3s.yaml make deploy-lcl
# LCL_TAG — image tag. Defaults to a timestamp so a rebuild is always re-pulled;
# `IfNotPresent` would otherwise serve a stale `0.0.1` from the node cache.
LCL_REGISTRY ?= localhost:5000
LCL_REPO ?= go-bananas
LCL_TAG ?= $(shell date -u +%Y%m%d%H%M%S)
LCL_NAMESPACE ?= go-insane-lcl
LCL_VALUES = deploy/helm/go-bananas/values-lcl.yaml
.PHONY: image-lcl
image-lcl: ## Build and push the image to the local registry ##@destructive
$(DOCKER) buildx build \
--build-arg VERSION=$(VERSION) \
--build-arg COMMIT=$(COMMIT) \
--build-arg BUILD_DATE=$(BUILD_DATE) \
--tag $(LCL_REGISTRY)/$(LCL_REPO):$(LCL_TAG) \
--push \
.
.PHONY: helm-template-lcl
helm-template-lcl: ## Render the lcl Helm manifest
$(HELM) template go-bananas deploy/helm/go-bananas \
--namespace $(LCL_NAMESPACE) \
--values $(LCL_VALUES) \
--set-string image.tag=$(LCL_TAG)
.PHONY: helm-install-lcl
helm-install-lcl: ## Deploy go-bananas to the local (lcl) environment ##@destructive
$(HELM) upgrade --install go-bananas deploy/helm/go-bananas \
--namespace $(LCL_NAMESPACE) --create-namespace \
--values $(LCL_VALUES) \
--set-string image.tag=$(LCL_TAG) \
--wait --timeout 5m
.PHONY: helm-uninstall-lcl
helm-uninstall-lcl: ## Remove the lcl release ##@destructive
$(HELM) uninstall go-bananas --namespace $(LCL_NAMESPACE)
.PHONY: deploy-lcl
deploy-lcl: image-lcl helm-install-lcl ## Build, push, deploy to lcl, then verify ##@destructive
@echo "waiting for rollout ($(LCL_NAMESPACE)/go-bananas)..."
@kubectl -n $(LCL_NAMESPACE) rollout status deploy/go-bananas --timeout=120s
@echo "=== runtime manifest through the TLS edge ==="
@curl -sk https://bananas-lcl.intern-urpi.be/rt/v1/manifest.json -o /dev/null -w 'manifest.json -> %{http_code}\n' || true
@echo "deployed image: $(LCL_REGISTRY)/$(LCL_REPO):$(LCL_TAG)"
##@ Docs
.PHONY: docs-serve

View file

@ -82,7 +82,7 @@ helm upgrade --install go-bananas oci://ghcr.io/urpi/charts/go-bananas \
--set identity.oidc.existingSecret=go-bananas-auth
```
The chart defaults to the shared development realm at `auth-dev.urpi.be`. See
The chart defaults to the shared development realm at `auth.lcl-urpi.be`. See
[docs/deployment.md](docs/deployment.md) for the full production checklist.
---
@ -462,6 +462,7 @@ Requires Go 1.27 and Node 22 or later. `make tools` installs `air`,
| [docs/operations.md](docs/operations.md) | Monitoring, backup, runbook |
| [docs/security.md](docs/security.md) | Threat model and hardening |
| [docs/styling-contract.md](docs/styling-contract.md) | The shared styling contract, and how an application adopts it |
| [docs/dev-infrastructure.md](docs/dev-infrastructure.md) | **This machine's dev infrastructure: audit, port map, fixes, and the issue log to append to** |
| [docs/adr/](docs/adr/) | Architecture decision records |
## Licence

View file

@ -6,7 +6,7 @@
#
# The `oidc` profile adds a mock OpenID Connect provider, so the authentication
# flow can be exercised end to end without pointing at a real realm. The `oidc`
# profile uses the mock because auth-dev.urpi.be is a shared development realm and a
# profile uses the mock because auth.lcl-urpi.be is a shared development realm and a
# local stack should not depend on it being reachable.
#
# Usage:

View file

@ -21,12 +21,8 @@
# reproducible rather than "whatever worked when it was deployed".
image:
# The development cluster pulls from a private registry whose certificate is valid
# for a different name, so the host and the port have to stay in one piece: putting
# the port in `repository` renders an image reference without it, and the kubelet
# then resolves the registry over https on port 443.
registry: batty1039.startdedicated.net:5000
repository: go-bananas
registry: nexus.urpi.be
repository: docker-hosted/go-bananas
# The development registry is tagged `latest` rather than pinned to a version, to
# match every other release in this namespace. Consequently the pull policy must be
# Always: with IfNotPresent a node keeps serving the image it already has, and a
@ -39,7 +35,7 @@ config:
# refuses both of these outside a development environment, so this pair cannot be
# promoted to production by accident.
environment: development
publicBaseUrl: https://bananas-dev.urpi.be
publicBaseUrl: https://bananas.dev-urpi.be
identity:
# dev, not oidc.
@ -59,11 +55,11 @@ identity:
# helm upgrade ... --set identity.mode=oidc \
# --set identity.oidc.generateSecret=false \
# --set identity.oidc.existingSecret=go-bananas-auth \
# --set identity.oidc.issuer=https://auth-dev.urpi.be \
# --set identity.oidc.issuer=https://auth.dev-urpi.be \
# --set identity.oidc.clientId=go-bananas
mode: dev
oidc:
issuer: https://auth-dev.urpi.be
issuer: https://auth.dev-urpi.be
clientId: go-bananas
existingSecret: go-bananas-auth
generateSecret: false
@ -74,14 +70,14 @@ ingress:
cert-manager.io/cluster-issuer: letsencrypt-staging
nginx.ingress.kubernetes.io/ssl-redirect: "true"
hosts:
- host: bananas-dev.urpi.be
- host: bananas.dev-urpi.be
paths:
- path: /
pathType: Prefix
tls:
- secretName: go-bananas-tls
hosts:
- bananas-dev.urpi.be
- bananas.dev-urpi.be
deployment:
# One replica. The volume is ReadWriteOnce, so a second replica cannot mount it and

View file

@ -60,7 +60,7 @@ Authentication is set to "{{ .Values.identity.mode }}". Every request is current
treated as an administrator. Before exposing this to a network, set:
identity.mode=oidc
identity.oidc.issuer=https://auth-dev.urpi.be/realms/<realm>
identity.oidc.issuer=https://auth.dev-urpi.be/realms/<realm>
identity.oidc.clientId=go-bananas
identity.oidc.existingSecret=<secret-name>
{{- end }}

View file

@ -167,7 +167,7 @@ CrashLoopBackOff to diagnose. Each check names the value to change.
{{- if eq $mode "oidc" -}}
{{- if not .Values.identity.oidc.issuer -}}
{{- fail "identity.oidc.issuer is required when identity.mode is oidc. For the development realm this is https://auth-dev.urpi.be/realms/<realm>." -}}
{{- fail "identity.oidc.issuer is required when identity.mode is oidc. For the development realm this is https://auth.dev-urpi.be/realms/<realm>." -}}
{{- end -}}
{{- if not (regexMatch "^https?://" .Values.identity.oidc.issuer) -}}
{{- fail (printf "identity.oidc.issuer %q is not a URL. It must include the scheme." .Values.identity.oidc.issuer) -}}

View file

@ -52,9 +52,6 @@ spec:
{{- toYaml . | nindent 8 }}
{{- end }}
spec:
{{- with .Values.image.pullPolicy }}
imagePullPolicy: {{ . }}
{{- end }}
serviceAccountName: {{ include "go-bananas.serviceAccountName" . }}
automountServiceAccountToken: {{ .Values.serviceAccount.automountServiceAccountToken }}
{{- with .Values.serviceAccount.annotations }}
@ -75,19 +72,20 @@ spec:
securityContext:
{{- toYaml .Values.podSecurityContext | nindent 8 }}
terminationGracePeriodSeconds: {{ .Values.deployment.terminationGracePeriodSeconds }}
containers:
- name: go-bananas
image: {{ include "go-bananas.image" . }}
imagePullPolicy: {{ .Values.image.pullPolicy }}
{{- if .Values.deployment.lifecycle.preStop.enabled }}
# A preStop sleep gives the Service endpoints controller time to remove this
# pod from the endpoint list before the process starts refusing connections.
# Without it, a rolling update can drop requests that were already routed.
# lifecycle is a container field, not a podSpec field.
lifecycle:
preStop:
exec:
command: ["/bin/sh", "-c", "sleep {{ .Values.deployment.lifecycle.preStop.sleepSeconds }}"]
{{- end }}
containers:
- name: go-bananas
image: {{ include "go-bananas.image" . }}
imagePullPolicy: {{ .Values.image.pullPolicy }}
{{- with .Values.deployment.extraArgs }}
args:
{{- toYaml . | nindent 12 }}

View file

@ -2,7 +2,8 @@
nameOverride: ""
fullnameOverride: ""
replicaCount: 1
deployment:
replicaCount: 1
image:
repository: nexus.urpi.be/docker-hosted/go-bananas
@ -13,6 +14,16 @@ service:
type: ClusterIP
port: 80
# Spelled out here rather than inherited from values.yaml so the development
# issuer is stated where it is used.
identity:
mode: oidc
oidc:
issuer: https://auth.dev-urpi.be/realms/urpi
clientId: go-bananas
existingSecret: go-bananas-auth
generateSecret: false
ingress:
enabled: true
className: nginx
@ -20,20 +31,14 @@ ingress:
cert-manager.io/cluster-issuer: letsencrypt-staging
nginx.ingress.kubernetes.io/ssl-redirect: "true"
hosts:
- host: bananas-dev.intern-urpi.be
- host: bananas.dev-urpi.be
paths:
- path: /
pathType: Prefix
tls:
- secretName: go-bananas-tls
hosts:
- bananas-dev.intern-urpi.be
certManager:
enabled: true
issuerRef:
name: letsencrypt-staging
kind: ClusterIssuer
- bananas.dev-urpi.be
resources:
limits:

View file

@ -1,5 +1,5 @@
# Local (LCL) values for go-bananas.
# Served at https://bananas-lcl.intern-urpi.be by the docker TLS edge.
# Served at https://bananas.lcl-urpi.be by the docker TLS edge.
#
# NOTE: this chart validates values against values.schema.json, which allows
# only the keys defined there -- no certManager and no replicaCount here
@ -18,12 +18,12 @@ service:
port: 80
# Local environment: development unlocks the local authentication bypass, so
# the deployment works without the shared Keycloak realm at auth-dev.urpi.be
# the deployment works without the shared Keycloak realm at auth.dev-urpi.be
# (go-loose does not serve /realms/... endpoints, so the oidc default cannot
# be pointed at it either).
config:
environment: development
publicBaseUrl: "https://bananas-lcl.intern-urpi.be"
publicBaseUrl: "https://bananas.lcl-urpi.be"
identity:
mode: dev
@ -33,14 +33,14 @@ ingress:
className: traefik
annotations: {}
hosts:
- host: bananas-lcl.intern-urpi.be
- host: bananas.lcl-urpi.be
paths:
- path: /
pathType: Prefix
tls:
- secretName: local-dev-cert
hosts:
- bananas-lcl.intern-urpi.be
- bananas.lcl-urpi.be
resources:
limits:

View file

@ -1,20 +1,31 @@
# PRD values for go-bananas
nameOverride: ""
fullnameOverride: ""
replicaCount: 1
imagePullSecrets:
# Production values for go-bananas. Secret values remain in the Kubernetes Secret
# created by the Forgejo deployment job.
global:
imagePullSecrets:
- name: nexus-registry
deployment:
replicaCount: 1
image:
repository: nexus.urpi.be/docker-hosted/go-bananas
tag: "0.0.1"
registry: nexus.urpi.be
repository: docker-hosted/go-bananas
tag: latest
pullPolicy: Always
config:
environment: production
publicBaseUrl: https://bananas.urpi.be
persistence:
enabled: true
type: persistentVolumeClaim
size: 2Gi
service:
type: ClusterIP
port: 80
sessionSecure: true
ingress:
enabled: true
@ -32,16 +43,17 @@ ingress:
hosts:
- bananas.urpi.be
certManager:
enabled: true
issuerRef:
name: letsencrypt-prod
kind: ClusterIssuer
identity:
mode: oidc
oidc:
issuer: https://auth.urpi.be/realms/urpi
clientId: go-bananas
existingSecret: go-bananas-auth
generateSecret: false
resources:
limits:
cpu: 500m
memory: 512Mi
requests:
cpu: 100m
memory: 256Mi
memory: 128Mi
limits:
memory: 512Mi

View file

@ -2,7 +2,8 @@
nameOverride: ""
fullnameOverride: ""
replicaCount: 1
deployment:
replicaCount: 1
image:
repository: nexus.urpi.be/docker-hosted/go-bananas
@ -13,6 +14,17 @@ service:
type: ClusterIP
port: 80
# Spelled out here rather than inherited from values.yaml, whose default issuer
# points at the development realm: a missing key would otherwise make the
# testing release validate tokens against the development identity provider.
identity:
mode: oidc
oidc:
issuer: https://auth.tst-urpi.be/realms/urpi
clientId: go-bananas
existingSecret: go-bananas-auth
generateSecret: false
ingress:
enabled: true
className: nginx
@ -20,20 +32,14 @@ ingress:
cert-manager.io/cluster-issuer: letsencrypt-staging
nginx.ingress.kubernetes.io/ssl-redirect: "true"
hosts:
- host: bananas-tst.intern-urpi.be
- host: bananas.tst-urpi.be
paths:
- path: /
pathType: Prefix
tls:
- secretName: go-bananas-tls
hosts:
- bananas-tst.intern-urpi.be
certManager:
enabled: true
issuerRef:
name: letsencrypt-staging
kind: ClusterIssuer
- bananas.tst-urpi.be
resources:
limits:

View file

@ -197,7 +197,7 @@ config:
# replicaCount: 1, or a filesystem that permits multiple mounts.
persistence:
enabled: true
enabled: false
type: persistentVolumeClaim
accessMode: ReadWriteOnce
size: 2Gi
@ -288,7 +288,7 @@ identity:
# issuer: this string must match the `iss` claim in the ID token exactly,
# including a trailing slash if the provider emits one. A mismatch here is the
# single most common cause of "invalid issuer" at the callback.
issuer: "https://auth-dev.urpi.be/realms/urpi"
issuer: "https://auth.dev-urpi.be/realms/urpi"
# clientId is the client identifier registered with the provider.
clientId: "go-bananas"

View file

@ -10,6 +10,7 @@ Running go-bananas, from a laptop to a production cluster.
- [Configuration](#configuration)
- [Authentication](#authentication)
- [Helm](#helm)
- [Local deployment (lcl)](#local-deployment-lcl)
- [The production checklist](#the-production-checklist)
- [Scaling](#scaling)
- [Backup and restore](#backup-and-restore)
@ -127,7 +128,7 @@ is made impossible to construct.
### The shared development realm
The chart defaults to `https://auth-dev.urpi.be/realms/urpi`, so a development cluster
The chart defaults to `https://auth.lcl-urpi.be/realms/urpi`, so a development cluster
works with no identity configuration.
The realm path is part of the issuer. The value must match the `iss` claim in the ID
@ -260,6 +261,77 @@ helm lint deploy/helm/go-bananas --strict
---
## Local deployment (lcl)
The `lcl` environment is the developer's own single-node **k3s** cluster used for
local integration testing. It is defined by `deploy/helm/go-bananas/values-lcl.yaml`:
- `config.environment: development` so the local auth bypass is allowed.
- `identity.mode: dev` so you can sign in without an OIDC provider.
- `image.registry: localhost:5000` so the cluster pulls from a local registry.
- Ingress host `bananas-lcl.intern-urpi.be`, terminated by the local TLS edge.
All the `go-*` applications share the **`go-insane-lcl`** namespace; go-bananas is a
Helm release named `go-bananas` inside it.
### Prerequisites
1. A running local k3s cluster and a registry at `localhost:5000`.
2. `bananas-lcl.intern-urpi.be` resolving to the node (`/etc/hosts`) behind the TLS edge.
3. `docker buildx`, `helm` and `kubectl`.
> **Kubeconfig caveat.** On this machine the default `local` context goes through a
> Rancher proxy (`https://rancher.urpi.be/k8s/clusters/local`) which can 502. When it
> does, talk to k3s directly instead: `export KUBECONFIG=/etc/rancher/k3s/k3s.yaml`.
> Everything below respects that variable.
### One-shot build + deploy + verify
```bash
KUBECONFIG=/etc/rancher/k3s/k3s.yaml ./hack/deploy-lcl.sh
# or, equivalently:
KUBECONFIG=/etc/rancher/k3s/k3s.yaml make deploy-lcl
```
This builds a fresh image (with the web admin UI and runtime SDK compiled in), pushes
it to the local registry, runs `helm upgrade --install`, waits for the rollout, and
curls the runtime manifest through the TLS edge. The image tag defaults to a build
timestamp so a rebuild is always re-pulled (`IfNotPresent` would otherwise serve a
stale cached tag). Override it with `LCL_TAG=...`.
### Step by step
```bash
make install # Go and Node dependencies
make image-lcl # build + push to localhost:5000/go-bananas:<LCL_TAG>
make helm-template-lcl # sanity-check the rendered manifest
make helm-install-lcl # helm upgrade --install into go-insane-lcl
```
`LCL_TAG`, `LCL_REGISTRY` and `LCL_NAMESPACE` are overridable:
```bash
make deploy-lcl LCL_TAG=v1 LCL_REGISTRY=registry:5000 LCL_NAMESPACE=go-insane-lcl
```
### Sign in and verify
The release uses `dev` authentication, so any user is a local administrator. Open
`https://bananas-lcl.intern-urpi.be/?dev-user=you@example.test`, then:
```bash
curl -sk https://bananas-lcl.intern-urpi.be/readyz
curl -sk https://bananas-lcl.intern-urpi.be/rt/v1/manifest.json | jq '.themes[].slug'
```
### Remove
```bash
KUBECONFIG=/etc/rancher/k3s/k3s.yaml make helm-uninstall-lcl
```
---
## The production checklist
- [ ] `config.environment: production`

View file

@ -26,7 +26,7 @@ make tools # air, golangci-lint, sqlc
## Running
```bash
make dev-all # API on :8080, admin UI on :5173 with a proxy
make dev-all # API on :8080, admin UI on :5173 with a proxy (builds the SDK first)
```
Open <http://localhost:5173>. The Vite dev server proxies `/api`, `/rt` and `/auth`
@ -34,11 +34,18 @@ to the Go process, so the session cookie works exactly as it will in production.
Same-origin matters: a cross-origin setup would not authenticate at all, and the
problem would look like a bug rather than a topology difference.
The admin UI is itself a consumer of the runtime: the header theme selector and the
light/dark toggle are the shipped controls, loaded from `/rt/v1/components.js`, which
the **API** serves from `sdk/dist` (Vite proxies `/rt` to it). `make dev-all` builds
the SDK up front for exactly this reason — an unbuilt `sdk/dist` means those controls
never define and the switcher silently falls back.
Other entry points:
```bash
make dev-api # the API alone, with hot reload
make dev-web # the admin UI alone
make dev # the API with hot reload (air); serves web/dist and sdk/dist, so `make build` first
make dev-api # the API alone, no hot reload; serves the runtime SDK, Vite serves the UI
make dev-web # the admin UI alone (its /api and /rt proxy to :8080)
make run # build everything, run the real binary
```

View file

@ -22,7 +22,7 @@ import (
)
// OIDCProvider implements Resolver against any OpenID Connect provider,
// including the auth-dev.urpi.be realm used for local development.
// including the auth.lcl-urpi.be realm used for local development.
//
// Everything provider-specific comes from the issuer's discovery document, so
// the same code works against Keycloak, Authentik, Zitadel or Google without a

View file

@ -71,7 +71,7 @@ type Config struct {
// AuthMode is oidc, dev, or none.
AuthMode string
// OIDCIssuer is the issuer URL, e.g. https://auth-dev.urpi.be/realms/urpi.
// OIDCIssuer is the issuer URL, e.g. https://auth.lcl-urpi.be/realms/urpi.
OIDCIssuer string
// OIDCClientID is the client identifier registered with the provider.
OIDCClientID string

View file

@ -70,7 +70,7 @@ func newUnauthenticatedRouter(t *testing.T) http.Handler {
t.Helper()
cfg := testConfig(t)
cfg.AuthMode = config.AuthModeOIDC
cfg.OIDCIssuer = "https://auth-dev.urpi.be/realms/urpi"
cfg.OIDCIssuer = "https://auth.lcl-urpi.be/realms/urpi"
cfg.OIDCClientID = "go-bananas"
cfg.OIDCClientSecret = "test-client-secret"
cfg.SessionSecure = false
@ -278,7 +278,7 @@ func TestRuntimeIsReadableCrossOrigin(t *testing.T) {
// not testing the policy — it is testing the same-origin path under a
// misleading name.
req := httptest.NewRequestWithContext(context.Background(), http.MethodGet, path, nil)
req.Header.Set("Origin", "https://tell-dev.urpi.be")
req.Header.Set("Origin", "https://tell.lcl-urpi.be")
rec := httptest.NewRecorder()
router.ServeHTTP(rec, req)
@ -313,7 +313,7 @@ func TestAdminAPIIsNotOpenedByTheRuntimePolicy(t *testing.T) {
for _, path := range []string{"/api/v1/session", "/api/v1/themes"} {
t.Run(path, func(t *testing.T) {
req := httptest.NewRequestWithContext(t.Context(), http.MethodGet, path, nil)
req.Header.Set("Origin", "https://tell-dev.urpi.be")
req.Header.Set("Origin", "https://tell.lcl-urpi.be")
rec := httptest.NewRecorder()
router.ServeHTTP(rec, req)
@ -357,7 +357,7 @@ func TestAdminAPIAllowsAConfiguredOrigin(t *testing.T) {
func TestRuntimeAnswersPreflight(t *testing.T) {
req := httptest.NewRequestWithContext(
context.Background(), http.MethodOptions, "/rt/v1/contract.json", nil)
req.Header.Set("Origin", "https://tell-dev.urpi.be")
req.Header.Set("Origin", "https://tell.lcl-urpi.be")
// A real preflight names the method it wants to use. Without this header the
// request is not a preflight, and asserting 204 on it would be asserting on a
// case no browser ever sends — which is how this test passed against a 405.

View file

@ -207,8 +207,8 @@ func (s *Store) ListAudit(ctx context.Context, filter AuditFilter) ([]domain.Aud
args []any
)
if filter.Actor != "" {
where = append(where, `actor = ?`)
args = append(args, filter.Actor)
where = append(where, `actor_email LIKE ?`)
args = append(args, "%"+filter.Actor+"%")
}
if filter.Action != "" {
where = append(where, `action = ?`)

View file

@ -23,6 +23,7 @@
},
"include": [
"src/**/*.js",
"src/**/*.d.ts",
"vite.config.js",
"vitest.config.js"
]

View file

@ -28,7 +28,11 @@ export default tseslint.config(
{
languageOptions: {
parserOptions: {
projectService: true,
// The app build project excludes test files (so the production image build
// never compiles the SDK-coupled integration test). ESLint still needs type
// info for every file it lints, so point it at BOTH projects explicitly
// rather than relying on projectService to discover the test project.
project: ['./tsconfig.app.json', './tsconfig.test.json'],
tsconfigRootDir: import.meta.dirname,
},
globals: { ...globals.browser, ...globals.es2022 },

View file

@ -7,11 +7,11 @@
"license": "SEE LICENSE IN ../LICENSE",
"scripts": {
"dev": "vite",
"build": "tsc --build && vite build",
"build": "tsc -p tsconfig.app.json && vite build",
"preview": "vite preview",
"lint": "eslint . --max-warnings 0",
"lint:fix": "eslint . --fix",
"typecheck": "tsc --build --force",
"typecheck": "tsc -p tsconfig.app.json --noEmit && tsc -p tsconfig.test.json --noEmit",
"test": "vitest run",
"test:watch": "vitest",
"test:ui": "vitest --ui",

View file

@ -16,6 +16,11 @@ export type AdminThemeValue = {
previewSlug: string | null
setMode: (mode: AdminThemeMode) => void
setPreviewSlug: (slug: string | null) => void
/**
* Sets mode and preview slug atomically. Used by the shipped controls so that
* picking a theme does not race with picking its default appearance.
*/
choose: (choice: { mode: AdminThemeMode; slug: string | null }) => void
/** The slugs available to preview, from the runtime manifest. */
available: string[]
/** The runtime base URL, for building preview URLs. */

View file

@ -21,11 +21,27 @@ vi.mock('../lib/api', () => ({
resetPreferences: vi.fn(() => Promise.resolve({ selectedTheme: '', selectedAppearance: '' })),
}))
// Mock the control loader so the origin it is asked to load from can be asserted
// directly, rather than depending on the loader's module-level singleton promise.
vi.mock('../lib/runtime-controls', () => ({
loadRuntimeControls: vi.fn(() => new Promise<void>(() => undefined)),
}))
const api = await import('../lib/api')
const runtimeControls = await import('../lib/runtime-controls')
const THEME_ATTRIBUTE = 'data-bananas-theme'
const APPEARANCE_ATTRIBUTE = 'data-bananas-appearance'
const FULL_ENTRY = {
slug: 'midnight',
name: 'Midnight',
defaultAppearance: 'dark',
version: 1,
css: '/rt/v1/theme.css?slug=midnight',
tokens: '/rt/v1/theme.json?slug=midnight',
} as const
/** A probe that renders the current choice and exposes the setters. */
function Probe() {
const { mode, previewSlug, available, setMode, setPreviewSlug } = useAdminTheme()
@ -110,20 +126,26 @@ describe('with a stored preference', () => {
// knows that its own chrome is styled by the full variant of a theme.
await waitFor(() =>
expect(
document.querySelector('link[data-bananas-admin="bananas-admin-preview"]')?.getAttribute('href'),
document
.querySelector('link[data-bananas-admin="bananas-admin-preview"]')
?.getAttribute('href'),
).toBe('/rt/v1/theme.css?slug=midnight&variant=full'),
)
})
// The document attributes belong to the shipped control, so that there is one writer
// for them rather than two that can disagree. This test pins that division of
// responsibility: if the provider starts writing them again, it will fail.
it('leaves the document attributes to the shipped controls', async () => {
// While the shipped controls are not ready — in this file loadRuntimeControls is
// mocked and never resolves — the provider is the only writer, and the preview
// stylesheet is scoped to exactly these attributes. If the provider did not apply
// them, the fallback switcher would change state but repaint nothing, which is the
// "I can't select a theme / light-dark does nothing" bug. (The single-writer handoff,
// where the controls take over once loaded, is covered by the real-controls
// integration test.)
it('applies the document attributes itself while the controls are not ready', async () => {
renderProvider()
await waitFor(() => expect(screen.getByTestId('mode')).toHaveTextContent('theme-dark'))
await waitFor(() => expect(screen.getByTestId('slug')).toHaveTextContent('midnight'))
expect(document.documentElement.hasAttribute(THEME_ATTRIBUTE)).toBe(false)
expect(document.documentElement.hasAttribute(APPEARANCE_ATTRIBUTE)).toBe(false)
expect(document.documentElement.getAttribute(THEME_ATTRIBUTE)).toBe('midnight')
expect(document.documentElement.getAttribute(APPEARANCE_ATTRIBUTE)).toBe('dark')
})
it('writes the choice back to the API when the mode changes', async () => {
@ -186,3 +208,41 @@ describe('when persisting fails', () => {
expect(screen.getByTestId('mode')).toHaveTextContent('theme-dark')
})
})
// TestTheAdminConsumesItsRuntimeSameOrigin: a manifest (or config) that advertises a
// DIFFERENT absolute origin than the page itself — a CDN in front, a public host that
// is not the one you opened, `localhost` vs `127.0.0.1` — must not make the admin
// fetch its own controls and preview stylesheet from that other origin. The page's CSP
// is `script-src 'self'`, so a cross-origin `<script type=module>` and the module's
// dynamic `import()` of its chunk are blocked, `controlsReady` never becomes true, and
// the switcher silently falls back with no theme selectable. The admin must therefore
// always load `/rt/v1` from its own origin.
describe('the runtime is consumed same-origin', () => {
it('ignores the absolute public base when loading controls and the preview', async () => {
vi.mocked(api.getManifest).mockResolvedValue({
apiVersion: '1',
// An origin that is deliberately not the page's own.
baseUrl: 'https://themes.example.com/rt/v1',
themes: [FULL_ENTRY],
})
vi.mocked(api.getSession).mockResolvedValue({
authenticated: true,
mode: 'dev',
preferences: { selectedTheme: 'midnight', selectedAppearance: 'dark' },
} as unknown as Awaited<ReturnType<typeof api.getSession>>)
renderProvider()
// The shipped controls are requested from the admin's own origin, not the CDN.
await waitFor(() => expect(runtimeControls.loadRuntimeControls).toHaveBeenCalledWith('/rt/v1'))
// The previewed palette is loaded from the admin's own origin too.
await waitFor(() =>
expect(
document
.querySelector('link[data-bananas-admin="bananas-admin-preview"]')
?.getAttribute('href'),
).toBe('/rt/v1/theme.css?slug=midnight&variant=full'),
)
})
})

View file

@ -29,7 +29,6 @@ import { loadRuntimeControls } from '../lib/runtime-controls'
/** Which visual mode the admin chrome is in. */
export type AdminThemeMode = 'admin' | 'theme-light' | 'theme-dark'
/** The value used when a previewed theme has not been chosen yet. */
const DEFAULT_PREVIEW = 'midnight'
@ -103,7 +102,30 @@ export function AdminThemeProvider({ children }: { children: ReactNode }) {
const available = useMemo(() => manifest?.themes.map((theme) => theme.slug) ?? [], [manifest])
const runtimeBase = manifest?.baseUrl ?? '/rt/v1'
// The default appearance of each published theme, so that picking a theme in the
// fallback switcher previews it in the scheme its author chose — exactly what the
// shipped controls do. Without this, choosing a theme while in the admin chrome would
// set the slug but leave `mode: 'admin'`, so nothing repaints and the dropdown looks
// dead: the "I select a theme and nothing happens" symptom.
const defaultAppearanceOf = useMemo(() => {
const map = new Map<string, 'light' | 'dark'>()
for (const theme of manifest?.themes ?? []) {
map.set(theme.slug, theme.defaultAppearance === 'light' ? 'light' : 'dark')
}
return map
}, [manifest])
// The admin loads the shipped controls and the preview stylesheet from THIS
// origin, not from manifest.baseUrl / config.runtimeBase. Those are the absolute
// *public* origin (or the CDN) meant for consumers pasting a snippet; using them
// here would make the module script and its contract.json fetch cross-origin
// whenever the browser's origin differs from the configured public base — a
// localhost/127.0.0.1 mismatch, a Vite dev proxy, or a CDN in front — and the
// page's CSP (script-src 'self') would then block the controls from ever
// defining, which surfaces as a switcher that cannot pick a theme. apiBase()
// already derives the same-origin path from the optional base-path marker; do the
// same for /rt/v1 so a sub-path deployment resolves correctly too.
const runtimeBase = sameOriginRuntimeBase()
// Fetch the shipped controls from this service. A failure is not worth surfacing:
// the switcher keeps its previous control, and nothing else depends on this.
@ -140,26 +162,25 @@ export function AdminThemeProvider({ children }: { children: ReactNode }) {
writeStored(STORAGE_KEY, next.mode)
if (next.slug) {
writeStored(PREVIEW_KEY, next.slug)
persist(next.slug, next.mode === 'theme-dark' ? 'dark' : 'light')
} else {
window.localStorage?.removeItem(PREVIEW_KEY)
}
// The admin chrome is the absence of a theme, so returning to it forgets the
// preference rather than recording the slug that is still selected in the
// dropdown. Persisting the slug here would make the next browser open on a
// theme this person had just switched away from.
if (next.mode === 'admin') {
void resetPreferences().catch(() => undefined)
} else if (next.slug) {
persist(next.slug, next.mode === 'theme-dark' ? 'dark' : 'light')
}
},
[persist],
)
const setMode = useCallback(
(next: AdminThemeMode) => {
// The admin chrome is the absence of a theme, so returning to it forgets the
// preference rather than recording the slug that is still selected in the
// dropdown. Persisting the slug here would make the next browser open on a
// theme this person had just switched away from.
if (next === 'admin') {
setChoice({ mode: 'admin', slug: previewSlug })
writeStored(STORAGE_KEY, 'admin')
void resetPreferences().catch(() => undefined)
return
}
choose({ mode: next, slug: previewSlug })
},
[choose, previewSlug],
@ -167,36 +188,48 @@ export function AdminThemeProvider({ children }: { children: ReactNode }) {
const setPreviewSlug = useCallback(
(slug: string | null) => {
choose({ mode, slug })
// Choosing a concrete theme previews it; choosing none returns to the chrome.
// Used by the fallback switcher's dropdown, which has no separate appearance
// click, so it applies the theme's own default scheme the way the shipped
// controls do.
if (!slug) {
choose({ mode, slug: null })
return
}
const nextMode: AdminThemeMode =
defaultAppearanceOf.get(slug) === 'light' ? 'theme-light' : 'theme-dark'
choose({ mode: nextMode, slug })
},
[choose, mode],
[choose, mode, defaultAppearanceOf],
)
// The document attributes are no longer written from here. The shipped controls
// write them, including the prefixed names this stylesheet reads, so there is one
// writer and no chance of the two disagreeing. The admin state drives the elements
// instead; see the shell for the binding.
//
// The `go-bananas-admin` sentinel is gone with it. It was read by nothing at all:
// no rule in the stylesheet matched it and no component inspected it. "Admin
// chrome" is the state with no previewed palette applied, which is exactly what the
// appearance toggle's admin state produces.
// The injected stylesheet must follow the mode too, because a theme's light and
// dark schemes are two rules under the same scoped selector and the attribute
// decides which wins.
// The document attributes are owned by the shipped controls once they are ready,
// so there is one writer and the two can never disagree. BUT until the module has
// upgraded them — and in the fallback case where it never does — nothing else writes
// them. Because the preview stylesheet is scoped to exactly these attributes, leaving
// them unset means picking a theme or toggling light/dark changes state but repaints
// nothing. So while the controls are not ready the provider must apply them itself;
// once they are, it steps back and lets the controls own the attributes.
useEffect(() => {
if (controlsReady) return
const root = document.documentElement
if (mode === 'admin') {
root.removeAttribute('data-bananas-theme')
root.removeAttribute('data-bananas-appearance')
return
}
const slug = previewSlug ?? DEFAULT_PREVIEW
root.setAttribute('data-bananas-theme', slug)
root.setAttribute('data-bananas-appearance', mode === 'theme-dark' ? 'dark' : 'light')
}, [mode, previewSlug, controlsReady])
// The preview stylesheet is the one thing only this service knows it needs:
// the full variant of a published theme, scoped to the prefixed attributes the
// runtime emits.
useEffect(() => {
if (mode === 'admin') return
const slug = previewSlug ?? DEFAULT_PREVIEW
const id = 'bananas-admin-preview'
let link = document.querySelector<HTMLLinkElement>(`link[data-bananas-admin="${id}"]`)
if (!link) {
@ -217,21 +250,36 @@ export function AdminThemeProvider({ children }: { children: ReactNode }) {
}, [mode])
const value = useMemo<AdminThemeValue>(
() => ({ mode, previewSlug, setMode, setPreviewSlug, available, runtimeBase, controlsReady }),
[
() => ({
mode,
previewSlug,
setMode,
setPreviewSlug,
choose,
available,
runtimeBase,
controlsReady,
],
}),
[mode, previewSlug, setMode, setPreviewSlug, choose, available, runtimeBase, controlsReady],
)
return <AdminThemeContext.Provider value={value}>{children}</AdminThemeContext.Provider>
}
/**
* The same-origin runtime base the admin consumes for its own controls and preview.
*
* It mirrors `apiBase()` in `lib/api.ts`: both resolve against the page's own origin
* and honour the optional `data-bananas-base-path` marker, so a sub-path deployment
* prefixes `/rt/v1` the same way it prefixes `/api/v1`. Nothing here may point at the
* absolute public/CDN origin — that is cross-origin under CSP `script-src 'self'`.
*/
function sameOriginRuntimeBase(): string {
const configured = document.documentElement.getAttribute('data-bananas-base-path') ?? ''
const prefix = configured.replace(/\/+$/, '')
return `${prefix}/rt/v1`
}
/**
* Reads the persisted choice, tolerating storage being unavailable.
*

View file

@ -40,7 +40,11 @@ export function AppShell() {
const queryClient = useQueryClient()
const [navOpen, setNavOpen] = useState(false)
const { data: session, isLoading, error } = useQuery({
const {
data: session,
isLoading,
error,
} = useQuery({
queryKey: ['session'],
queryFn: ({ signal }) => getSession(signal),
staleTime: 60_000,
@ -117,7 +121,7 @@ export function AppShell() {
onClick={() => setNavOpen(false)}
className={({ isActive }) =>
cn(
'flex items-center gap-2.5 rounded-control px-2.5 py-2 text-sm transition-colors',
'rounded-control flex items-center gap-2.5 px-2.5 py-2 text-sm transition-colors',
isActive
? 'bg-brand-subtle text-brand font-medium'
: 'text-ink-muted hover:bg-raised hover:text-ink',
@ -159,7 +163,7 @@ export function AppShell() {
<button
type="button"
aria-label="Close navigation"
className="bg-black/60 fixed inset-0 z-30 lg:hidden"
className="fixed inset-0 z-30 bg-black/60 lg:hidden"
onClick={() => setNavOpen(false)}
/>
) : null}
@ -223,15 +227,19 @@ export function AppShell() {
/** The banana mark. Drawn inline so the shell needs no image asset. */
function BananasMark() {
return (
<svg
viewBox="0 0 24 24"
className="text-brand size-5 shrink-0"
fill="currentColor"
aria-hidden
>
<path d="M4 8c0-1.1.9-2 2-2h3c.6 0 1.1.2 1.5.6l7.2 6.4c.2.2.3.5.3.8V20a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V8Z" opacity=".9" />
<path d="M20 8c0-1.1-.9-2-2-2h-1.2c-.6 0-1.1.2-1.5.6L8.1 13c-.2.2-.3.5-.3.8V20a2 2 0 0 0 2 2H18a2 2 0 0 0 2-2V8Z" opacity=".55" />
<path d="M8 5c0-.6.4-1 1-1h1.5c.3 0 .6.1.8.4l.5.5c.2.2.2.5 0 .7-.2.2-.5.2-.7 0l-.4-.4H9.5a.5.5 0 0 1-.5-.5V5Z" opacity=".7" />
<svg viewBox="0 0 24 24" className="text-brand size-5 shrink-0" fill="currentColor" aria-hidden>
<path
d="M4 8c0-1.1.9-2 2-2h3c.6 0 1.1.2 1.5.6l7.2 6.4c.2.2.3.5.3.8V20a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V8Z"
opacity=".9"
/>
<path
d="M20 8c0-1.1-.9-2-2-2h-1.2c-.6 0-1.1.2-1.5.6L8.1 13c-.2.2-.3.5-.3.8V20a2 2 0 0 0 2 2H18a2 2 0 0 0 2-2V8Z"
opacity=".55"
/>
<path
d="M8 5c0-.6.4-1 1-1h1.5c.3 0 .6.1.8.4l.5.5c.2.2.2.5 0 .7-.2.2-.5.2-.7 0l-.4-.4H9.5a.5.5 0 0 1-.5-.5V5Z"
opacity=".7"
/>
</svg>
)
}
@ -297,9 +305,18 @@ function usePathSegments(): { label: string; to: string }[] {
* moving between machines expects to see the same preview. And the element persists
* locally under its own key; letting it win would silently outrank the account.
*/
function ThemeSwitcher() {
const { mode, previewSlug, setMode, setPreviewSlug, available, runtimeBase, controlsReady } =
useAdminThemeSafe()
/** Exported for integration tests. */
export function ThemeSwitcher() {
const {
mode,
previewSlug,
setMode,
setPreviewSlug,
choose,
available,
runtimeBase,
controlsReady,
} = useAdminThemeSafe()
const selector = useRef<BananasElement>(null)
const toggle = useRef<BananasElement>(null)
@ -314,16 +331,18 @@ function ThemeSwitcher() {
const slug = detail?.slug
// An empty slug is the control's "no theme" entry, which in the admin means
// the chrome, since that is what an unset preview already maps to.
setPreviewSlug(slug || null)
// Also apply the theme's default appearance mode so selecting a theme
// immediately shows it rather than leaving the chrome in 'admin' mode.
if (slug && detail?.mode) {
setMode(detail.mode === 'dark' ? 'theme-dark' : 'theme-light')
choose({
slug,
mode: detail.mode === 'dark' ? 'theme-dark' : 'theme-light',
})
} else {
choose({ slug: null, mode: 'admin' })
}
}
el.addEventListener('bananas:theme', handler)
return () => el.removeEventListener('bananas:theme', handler)
}, [setPreviewSlug, setMode, controlsReady])
}, [choose, controlsReady])
useEffect(() => {
const el = toggle.current
@ -404,12 +423,11 @@ function LegacyThemeSwitcher({
}) {
return (
<div className="flex items-center gap-1.5">
{mode !== 'admin' ? (
<select
aria-label="Preview theme"
value={previewSlug ?? ''}
onChange={(event) => setPreviewSlug(event.target.value)}
className="border-line bg-canvas text-ink-muted h-8 max-w-[10rem] rounded-control border px-2 text-xs"
className="border-line bg-canvas text-ink-muted rounded-control h-8 max-w-[10rem] border px-2 text-xs"
>
{available.length === 0 ? <option value="">no published themes</option> : null}
{available.map((slug) => (
@ -418,9 +436,8 @@ function LegacyThemeSwitcher({
</option>
))}
</select>
) : null}
<div
className="border-line bg-canvas flex rounded-control border p-0.5"
className="border-line bg-canvas rounded-control flex border p-0.5"
role="group"
aria-label="Interface theme"
>
@ -502,6 +519,7 @@ function useAdminThemeSafe() {
setMode: () => {},
previewSlug: null,
setPreviewSlug: () => {},
choose: () => {},
available: [] as string[],
runtimeBase: '/rt/v1',
// Without a provider the module is never asked for, so the fallback control

12
web/src/global.d.ts vendored
View file

@ -1,3 +1,5 @@
/* eslint-disable @typescript-eslint/consistent-type-definitions */
/**
* Global type augmentations for bananas runtime controls.
* This file must not have any imports/exports to be treated as a global script.
@ -6,13 +8,19 @@
declare global {
namespace JSX {
interface IntrinsicElements {
'bananas-theme-selector': React.DetailedHTMLProps<React.HTMLAttributes<HTMLElement>, HTMLElement> & {
'bananas-theme-selector': React.DetailedHTMLProps<
React.HTMLAttributes<HTMLElement>,
HTMLElement
> & {
base?: string
label?: string
compact?: boolean
'no-preview'?: boolean
}
'bananas-appearance-toggle': React.DetailedHTMLProps<React.HTMLAttributes<HTMLElement>, HTMLElement> & {
'bananas-appearance-toggle': React.DetailedHTMLProps<
React.HTMLAttributes<HTMLElement>,
HTMLElement
> & {
label?: string
'show-labels'?: boolean
}

View file

@ -71,7 +71,7 @@ export default function DashboardRoute() {
) : null}
{/* Counters. */}
<div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-4">
<div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-3">
<Stat
label="Themes"
icon={<Palette className="size-4" aria-hidden />}

View file

@ -1,3 +1,5 @@
/* eslint-disable @typescript-eslint/consistent-type-definitions */
/// <reference types="vite/client" />
/**

View file

@ -27,5 +27,11 @@
"types": ["vitest/globals", "@testing-library/jest-dom"],
"paths": { "@/*": ["./src/*"] }
},
"include": ["src"]
// The production build must not compile test files. One test imports the shipped
// SDK source across packages (`sdk/src/*.js`) to drive the real custom elements; that
// coupling belongs to the test project (tsconfig.test.json), not to the app image
// build, where the SDK may not even be on disk yet. `tsc -p tsconfig.app.json` is what
// the Dockerfile runs, so tests are simply out of this project's file set.
"include": ["src"],
"exclude": ["src/**/*.test.ts", "src/**/*.test.tsx", "src/test"]
}

View file

@ -36,11 +36,11 @@ export default defineConfig({
port: 5173,
strictPort: true,
proxy: {
'/api': { target: 'http://localhost:8081', changeOrigin: true },
'/rt': { target: 'http://localhost:8081', changeOrigin: true },
'/auth': { target: 'http://localhost:8081', changeOrigin: true },
'/healthz': { target: 'http://localhost:8081', changeOrigin: true },
'/readyz': { target: 'http://localhost:8081', changeOrigin: true },
'/api': { target: 'http://localhost:8080', changeOrigin: true },
'/rt': { target: 'http://localhost:8080', changeOrigin: true },
'/auth': { target: 'http://localhost:8080', changeOrigin: true },
'/healthz': { target: 'http://localhost:8080', changeOrigin: true },
'/readyz': { target: 'http://localhost:8080', changeOrigin: true },
},
},
test: {

View file

@ -1,3 +1,5 @@
import { fileURLToPath } from 'node:url'
import { defineConfig } from 'vitest/config'
/**
@ -7,6 +9,15 @@ import { defineConfig } from 'vitest/config'
* errors about the `test` key.
*/
export default defineConfig({
// The integration tests import the actual shipped SDK modules (sdk/src/*) to drive
// the real custom elements. Those live one directory up, outside the web package
// root, so Vite's default filesystem allow-list has to be widened to the repository
// root for the cross-package import to resolve.
server: {
fs: {
allow: [fileURLToPath(new URL('..', import.meta.url))],
},
},
test: {
// The admin interface is a browser application: components touch the DOM,
// localStorage and matchMedia, so jsdom is required rather than merely useful.