diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 0000000..80e6878 --- /dev/null +++ b/.dockerignore @@ -0,0 +1,9 @@ +node_modules +**/node_modules +**/dist +.git +docs/screenshots +.superpowers +.claude +**/.env* +**/*.local diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 48579ec..d5b21c1 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -16,53 +16,29 @@ permissions: contents: read jobs: - # Typecheck ("lint"): the workspace has no ESLint — the static-analysis gate - # is the TypeScript compiler, run via each package's `build` (tsc -p ...). - # This also validates the vite builds for the apps. - typecheck: - name: Typecheck & build + # Typecheck, build and unit tests run through the shared node-ci workflow. + # The workspace has no ESLint or `typecheck` script: the static-analysis gate + # is the TypeScript compiler, run via each package's `build` (tsc -p ...), so + # the build step is the typecheck. It also validates the vite app bundles. + ci: + uses: xraph/workflows/.github/workflows/node-ci.yml@v1 + with: + scripts: '["test","build"]' + + # Container image: the entrypoint script tests need no docker, then the smoke + # script builds the image and runs it read-only beside an echo upstream. + image: + name: Container image runs-on: ubuntu-latest steps: - name: Checkout uses: actions/checkout@v4 - - name: Set up pnpm - uses: pnpm/action-setup@v4 - with: - version: 9.12.0 + - name: Entrypoint tests + run: sh deploy/docker/entrypoint_test.sh - - name: Set up Node - uses: actions/setup-node@v4 - with: - node-version: 20 - cache: pnpm + - name: Set up Docker Buildx + uses: docker/setup-buildx-action@v3 - - name: Install dependencies - run: pnpm install --frozen-lockfile - - - name: Build (tsc typecheck + app bundles) - run: pnpm -r build - - test: - name: Unit tests - runs-on: ubuntu-latest - steps: - - name: Checkout - uses: actions/checkout@v4 - - - name: Set up pnpm - uses: pnpm/action-setup@v4 - with: - version: 9.12.0 - - - name: Set up Node - uses: actions/setup-node@v4 - with: - node-version: 20 - cache: pnpm - - - name: Install dependencies - run: pnpm install --frozen-lockfile - - - name: Test (vitest) - run: pnpm test + - name: Smoke test + run: sh deploy/docker/smoke.sh diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 3776a94..8cdc507 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -1,12 +1,15 @@ name: Release -# Tag-triggered npm release for the @fabriq-ai/* packages. +# Tag-triggered release: the @fabriq-ai/* npm packages, and the console +# container image on ghcr.io (ghcr.io/xraph/fabriq-admin). # -# Lockstep versioning: pushing a `vX.Y.Z` tag stamps EVERY publishable -# workspace package (packages/* + plugins/*) to that version and publishes -# them together to the public npm registry under the @fabriq-ai scope. The -# two apps (apps/host, apps/remote-example) are `private: true` and are -# skipped automatically by `pnpm -r publish`. +# Lockstep versioning: pushing a `vX.Y.Z` tag runs the shared CI workflow +# (test + build) on the tagged commit. Once it passes, every publishable +# workspace package (packages/* + plugins/*) is stamped to that version and +# published to the public npm registry under the @fabriq-ai scope, in +# dependency order, through xraph/workflows' npm-publish.yml. The two apps +# (apps/host, apps/remote-example) are `private: true` and are not in the +# `packages` list, so they are never published. # # git tag v0.2.0 && git push origin v0.2.0 # @@ -15,9 +18,15 @@ name: Release # # Pre-release suffixes (v0.2.0-rc.1) publish under the `next` dist-tag instead # of `latest`, so `npm install @fabriq-ai/ui` never resolves a pre-release. +# Every version is published with an npm provenance attestation. A re-run skips +# versions already on the registry, so a half-finished release can be resumed. +# +# The image is built for linux/amd64 and linux/arm64 and tagged :X.Y.Z, plus +# :X.Y for stable releases (no pre-release suffix). It runs independently of +# CI and the npm publish, so a failure in one does not block the other. # # Requires an NPM_TOKEN secret: an npm automation token with publish rights to -# the @fabriq-ai org. +# the @fabriq-ai org. The image push uses the workflow's own GITHUB_TOKEN. on: push: tags: @@ -32,67 +41,141 @@ permissions: contents: read jobs: - npm: + # Same gate as ci.yml, run on the tagged commit before anything is published. + ci: + uses: xraph/workflows/.github/workflows/node-ci.yml@v1 + with: + scripts: '["test","build"]' + + # The expression language has no string replace, and npm-publish.yml refuses + # a version with a leading v, so the tag is trimmed here. The dist-tag is + # picked here too: npm 11 won't publish a pre-release without one. + prepare: + name: Resolve version and dist-tag + runs-on: ubuntu-latest + outputs: + version: ${{ steps.resolve.outputs.version }} + dist-tag: ${{ steps.resolve.outputs.dist_tag }} + steps: + - id: resolve + shell: bash + run: | + set -euo pipefail + version="${GITHUB_REF_NAME#v}" + echo "version=${version}" >> "$GITHUB_OUTPUT" + + # A '-' before any '+build' metadata marks a pre-release in semver. + # Build metadata is cut first so 1.2.3+build-7 still counts as stable. + case "${version%%+*}" in + *-*) echo "dist_tag=next" >> "$GITHUB_OUTPUT" ;; + *) echo "dist_tag=latest" >> "$GITHUB_OUTPUT" ;; + esac + echo "Releasing ${version}" + + publish: name: Publish @fabriq-ai packages + needs: [ci, prepare] + # Provenance mints an OIDC token, and a called workflow only gets the + # permissions its caller grants, so id-token: write has to be granted here. + permissions: + contents: read + id-token: write + uses: xraph/workflows/.github/workflows/npm-publish.yml@v1 + with: + package-manager: pnpm + # Every publishable package under packages/* and plugins/* (25), with + # dependencies first. Derived by topologically sorting each package.json's + # dependencies and peerDependencies on other @fabriq-ai packages: ui, then + # admin-sdk (which needs ui), then the plugins (which need both), + # alphabetically. Add a new package here, after anything it depends on. + packages: |- + [ + "packages/ui", + "packages/admin-sdk", + "plugins/analytics", + "plugins/api-console", + "plugins/cache", + "plugins/commands", + "plugins/connection", + "plugins/crdt", + "plugins/distill", + "plugins/entity-browser", + "plugins/events", + "plugins/files", + "plugins/graph", + "plugins/live", + "plugins/migrations", + "plugins/overview", + "plugins/plugins-manager", + "plugins/projections", + "plugins/query", + "plugins/recall", + "plugins/search", + "plugins/spatial", + "plugins/telemetry", + "plugins/tenants", + "plugins/types" + ] + version: ${{ needs.prepare.outputs.version }} + dist-tag: ${{ needs.prepare.outputs.dist-tag }} + # Each package.json has a repository field naming this repository. + provenance: true + dry-run: false + build-script: build + # Lets a re-run finish a release that died part way through the list. + skip-existing: true + secrets: + NPM_TOKEN: ${{ secrets.NPM_TOKEN }} + + image: + name: Publish container image runs-on: ubuntu-latest permissions: contents: read - id-token: write # npm provenance (--provenance) attestation + packages: write # push to ghcr.io steps: - name: Checkout uses: actions/checkout@v4 - - name: Set up pnpm - uses: pnpm/action-setup@v4 - with: - version: 9.12.0 + - name: Set up QEMU + uses: docker/setup-qemu-action@v3 - - name: Set up Node - uses: actions/setup-node@v4 - with: - node-version: 20 - registry-url: "https://registry.npmjs.org" - cache: pnpm + - name: Set up Docker Buildx + uses: docker/setup-buildx-action@v3 - - name: Install dependencies - run: pnpm install --frozen-lockfile + - name: Log in to ghcr.io + uses: docker/login-action@v3 + with: + registry: ghcr.io + username: ${{ github.actor }} + password: ${{ secrets.GITHUB_TOKEN }} - - name: Resolve version + dist-tag from the tag + - name: Resolve image tags from the tag id: ver run: | set -euo pipefail VERSION="${GITHUB_REF_NAME#v}" - echo "version=${VERSION}" >> "$GITHUB_OUTPUT" - # Anything with a pre-release suffix (contains a '-') ships as `next`. - if printf '%s' "$VERSION" | grep -q '-'; then - echo "dist_tag=next" >> "$GITHUB_OUTPUT" - else - echo "dist_tag=latest" >> "$GITHUB_OUTPUT" - fi - echo "Releasing ${VERSION}" - - - name: Build - run: pnpm -r build - - - name: Test - run: pnpm test + MAJOR_MINOR="$(printf '%s' "$VERSION" | cut -d. -f1,2)" + { + echo "version=${VERSION}" + echo "tags<> "$GITHUB_OUTPUT" - - name: Stamp workspace versions to the tag (lockstep) - run: | - set -euo pipefail - # Bump every workspace package to the tag version. Private apps are - # bumped too but harmless — they are never published. workspace:* - # deps are rewritten to the concrete version by pnpm at publish time. - pnpm -r exec npm version "${{ steps.ver.outputs.version }}" \ - --no-git-tag-version --allow-same-version + - name: Build and push + uses: docker/build-push-action@v6 + with: + context: . + platforms: linux/amd64,linux/arm64 + push: true + provenance: false + sbom: false + tags: ${{ steps.ver.outputs.tags }} - - name: Publish to npm - env: - NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }} - NPM_CONFIG_PROVENANCE: "true" - run: | - set -euo pipefail - pnpm -r publish \ - --access public \ - --tag "${{ steps.ver.outputs.dist_tag }}" \ - --no-git-checks + - name: Inspect the pushed image + run: docker buildx imagetools inspect "ghcr.io/xraph/fabriq-admin:${{ steps.ver.outputs.version }}" diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..2880177 --- /dev/null +++ b/Dockerfile @@ -0,0 +1,24 @@ +# syntax=docker/dockerfile:1 + +# The build stage always runs on the builder's own architecture. The output is +# static files, so both image platforms share one build. +FROM --platform=$BUILDPLATFORM node:20.18-alpine AS build +WORKDIR /src +RUN corepack enable && corepack prepare pnpm@9.12.0 --activate +COPY . . +RUN pnpm install --frozen-lockfile +RUN pnpm -r build + +FROM nginxinc/nginx-unprivileged:1.27-alpine +LABEL org.opencontainers.image.source=https://github.com/xraph/fabriq-admin + +USER root +RUN apk add --no-cache jq +USER 101 + +COPY --from=build /src/apps/host/dist /usr/share/nginx/html +COPY deploy/docker/default.conf /etc/nginx/conf.d/default.conf +COPY --chmod=0755 deploy/docker/40-fabriq-admin-runtime.sh /docker-entrypoint.d/40-fabriq-admin-runtime.sh + +# Only /tmp needs to be writable (run with --read-only --tmpfs /tmp). +EXPOSE 8080 diff --git a/README.md b/README.md index 23dc036..4b156f8 100644 --- a/README.md +++ b/README.md @@ -171,6 +171,42 @@ Then add its `remoteEntry.js` URL from the **Plugins** page to load it into the --- +## Run the container + +Every release tag publishes an image to `ghcr.io/xraph/fabriq-admin` for `linux/amd64` and `linux/arm64`, tagged `X.Y.Z` and (for stable releases) `X.Y`. Point it at your Fabriq admin backend and open the port: + +```bash +docker run --rm -p 8081:8080 \ + --add-host=host.docker.internal:host-gateway \ + -e FABRIQ_ADMIN_UPSTREAM=http://host.docker.internal:8080 \ + ghcr.io/xraph/fabriq-admin:X.Y.Z +``` + +The `--add-host` line is for Linux engines, where `host.docker.internal` doesn't exist unless you add it. Docker Desktop already has it, and the flag does no harm there. + +The console is now on http://localhost:8081. The browser talks to `/admin` on that same origin, and nginx forwards it to your backend, so there's no CORS to sort out. + +Nothing is baked in at build time. The container reads its settings when it starts, writes the console's `config.js` into `/tmp`, and then hands over to nginx. Bad values stop it right there: the message goes to stderr and the exit code is 1. + +The upstream hostname has to resolve when the container starts. If it doesn't, nginx fails and the container exits 1 before it serves anything. The address it finds is then pinned until the container restarts, so restart the console whenever the Fabriq server is recreated. In Compose that's `depends_on: {fabriq: {condition: service_started, restart: true}}` on the console service. On Kubernetes, point the upstream at a Service and not at a pod. + +| Variable | Default | What it does | +|---|---|---| +| `FABRIQ_ADMIN_UPSTREAM` | unset | Origin of the admin backend, such as `http://fabriq:8081`, with no path. When set, `/admin/` is proxied there, with the browser's `Cookie` header dropped and no body size limit (file uploads are base64 JSON). | +| `FABRIQ_ADMIN_UPSTREAM_KEY` | unset | A Fabriq key (`fq_` plus 32 or more letters and digits). nginx sends it as `Authorization: Bearer` and replaces any header the browser sent. It never reaches `config.js`. While a key is set, requests the browser marks as cross-site or same-site get a 403. Needs `FABRIQ_ADMIN_UPSTREAM`. | +| `FABRIQ_ADMIN_BASE_PATH` | `/` | The path prefix the browser sees, such as `/console/`. Start and end with `/`. | +| `FABRIQ_ADMIN_API_URL` | `admin` when an upstream is set | Where the browser sends API calls. A path starting with `/`, or an `http://` or `https://` URL. | +| `FABRIQ_ADMIN_DEFAULT_TENANT` | unset | Tenant to select when the browser has none stored yet. Up to 64 letters, digits, `-` and `_`. | +| `FABRIQ_ADMIN_MAP_STYLE_URL` | unset | Style URL for the Spatial map. `http://` or `https://`. | + +The container always serves from `/`. If you run it behind a proxy under a prefix, let the proxy strip the prefix before forwarding and set `FABRIQ_ADMIN_BASE_PATH` to the same prefix, so links and assets resolve in the browser. + +It listens on 8080, runs as uid 101, and only needs `/tmp` to be writable, so `--read-only --tmpfs /tmp` works. `GET /healthz` returns `ok`. + +To build it yourself, run `docker build -t fabriq-admin .` from the repo root. `sh deploy/docker/smoke.sh` builds the image and checks the whole contract against an echo server. + +--- + ## Embedding in your app ```tsx diff --git a/apps/host/index.html b/apps/host/index.html index dc75ffe..601545f 100644 --- a/apps/host/index.html +++ b/apps/host/index.html @@ -1,12 +1,14 @@ + Fabriq Admin
+ diff --git a/apps/host/public/config.js b/apps/host/public/config.js new file mode 100644 index 0000000..976608e --- /dev/null +++ b/apps/host/public/config.js @@ -0,0 +1 @@ +window.__FABRIQ_ADMIN_CONFIG__ = window.__FABRIQ_ADMIN_CONFIG__ || {}; diff --git a/apps/host/src/App.tsx b/apps/host/src/App.tsx index 2012300..0e93de5 100644 --- a/apps/host/src/App.tsx +++ b/apps/host/src/App.tsx @@ -3,6 +3,7 @@ import { FabriqAdmin, FabriqClient, createTenantStore, + readRuntimeConfig, loadRemotePlugin, compositePluginStore, httpPluginStore, @@ -50,6 +51,11 @@ const federationRuntime = { const tenantStore = createTenantStore() +// Seed the active tenant from runtime config on first load only; an existing +// (persisted) selection always wins. +const { defaultTenant } = readRuntimeConfig() +if (defaultTenant && !tenantStore.get()) tenantStore.set(defaultTenant) + // Builtin plugins — always mounted. Overview is first (order 0 / index route ""). const plugins = [ overviewPlugin, @@ -100,6 +106,7 @@ function Console({ client }: { client: FabriqClient }) { return ( // routing="path": real URLs; production static hosting needs an SPA rewrite to index.html (Vite dev already SPA-falls-back). + // path comes from runtime config (config.js) so one bundle can mount under any prefix. ) } diff --git a/apps/host/src/AuthGate.test.tsx b/apps/host/src/AuthGate.test.tsx index 536fcf4..f68f2a2 100644 --- a/apps/host/src/AuthGate.test.tsx +++ b/apps/host/src/AuthGate.test.tsx @@ -36,6 +36,7 @@ beforeEach(() => { afterEach(() => { vi.unstubAllGlobals() vi.unstubAllEnvs() + delete window.__FABRIQ_ADMIN_CONFIG__ }) describe("AuthGate", () => { @@ -147,6 +148,38 @@ describe("AuthGate", () => { expect(getSessionToken()).toBeNull() }) + it("runtime apiUrl is used for the /meta probe", async () => { + window.__FABRIQ_ADMIN_CONFIG__ = { apiUrl: "http://fabriq.test/admin" } + const fetchSpy = vi.fn(async (input: RequestInfo | URL) => { + const url = String(input) + if (url.endsWith("/meta")) return jsonResponse(META) + throw new Error(`unexpected fetch: ${url}`) + }) + vi.stubGlobal("fetch", fetchSpy) + + render({() =>
console-children
}
) + + expect(await screen.findByText("console-children")).toBeInTheDocument() + expect(String(fetchSpy.mock.calls[0]![0])).toBe("http://fabriq.test/admin/meta") + }) + + it("a relative runtime apiUrl probes /meta once, under the page origin", async () => { + window.__FABRIQ_ADMIN_CONFIG__ = { apiUrl: "/console/admin" } + const fetchSpy = vi.fn(async (input: RequestInfo | URL) => { + const url = String(input) + if (url.endsWith("/meta")) return jsonResponse(META) + throw new Error(`unexpected fetch: ${url}`) + }) + vi.stubGlobal("fetch", fetchSpy) + + render({() =>
console-children
}
) + + expect(await screen.findByText("console-children")).toBeInTheDocument() + expect(String(fetchSpy.mock.calls[0]![0])).toBe( + `${window.location.origin}/console/admin/meta`, + ) + }) + it("VITE_FABRIQ_DSN set → renders children, no login, no /meta probe", async () => { vi.stubEnv("VITE_FABRIQ_DSN", "fabriq://testkey@localhost:8080/acme") const fetchSpy = vi.fn(async () => jsonResponse(META)) diff --git a/apps/host/src/AuthGate.tsx b/apps/host/src/AuthGate.tsx index 755ecc5..7fdea3b 100644 --- a/apps/host/src/AuthGate.tsx +++ b/apps/host/src/AuthGate.tsx @@ -5,6 +5,7 @@ import { createHttpTransport, createTenantStore, getSessionToken, + readRuntimeConfig, setSessionToken, clearSessionToken, HttpTransportError, @@ -73,22 +74,11 @@ function withUnauthorizedHandler( // --------------------------------------------------------------------------- // Client construction // -// Env vars are read lazily (inside the component, not at module scope) so -// that tests can flip VITE_FABRIQ_DSN between cases via vi.stubEnv without -// needing to re-import the module. +// Configuration is read lazily (inside the component, not at module scope) so +// that tests can flip VITE_FABRIQ_DSN or window.__FABRIQ_ADMIN_CONFIG__ +// between cases without needing to re-import the module. // --------------------------------------------------------------------------- -function readBaseUrl(): string { - return ( - (import.meta.env as Record)["VITE_FABRIQ_API_URL"] ?? - "http://localhost:8080/admin" - ) -} - -function readDsn(): string | undefined { - return (import.meta.env as Record)["VITE_FABRIQ_DSN"] -} - // Which branch of the precedence built the current authenticated client. // Only "token" has a real session to log out of — see AuthActionsContext. type AuthMode = "dsn" | "token" | "keyless" @@ -131,7 +121,7 @@ export interface AuthGateProps { */ export function AuthGate({ children, tenantStore }: AuthGateProps) { const store = useMemo(() => tenantStore ?? createTenantStore(), [tenantStore]) - const baseUrl = useMemo(readBaseUrl, []) + const baseUrl = useMemo(() => readRuntimeConfig().apiUrl, []) const [state, setState] = useState({ kind: "loading" }) // Avoids setting state after unmount (probe resolves after navigation away). const mountedRef = useRef(true) @@ -145,7 +135,7 @@ export function AuthGate({ children, tenantStore }: AuthGateProps) { useEffect(() => { // 1. DSN branch — fully determines the client; auth is out of band (the // DSN carries its own key), so never gate behind a login screen. - const dsn = readDsn() + const dsn = readRuntimeConfig().dsn if (dsn) { setState({ kind: "authenticated", client: connect(dsn), mode: "dsn" }) return diff --git a/apps/host/vite.config.ts b/apps/host/vite.config.ts index 951cae2..765e450 100644 --- a/apps/host/vite.config.ts +++ b/apps/host/vite.config.ts @@ -21,6 +21,9 @@ import tailwindcss from "@tailwindcss/vite" * remotes are registered at runtime by URL. */ export default defineConfig({ + // Relative asset URLs: the container rewrites to the deployment + // prefix, so the same bundle works under any path. + base: "./", resolve: { alias: { // @fabriq-ai/ui's source uses the shadcn "@/..." convention for its own diff --git a/deploy/docker/40-fabriq-admin-runtime.sh b/deploy/docker/40-fabriq-admin-runtime.sh new file mode 100755 index 0000000..e97d1d8 --- /dev/null +++ b/deploy/docker/40-fabriq-admin-runtime.sh @@ -0,0 +1,134 @@ +#!/bin/sh +# Runs from the stock nginx /docker-entrypoint.d before nginx starts. Turns the +# FABRIQ_ADMIN_* environment into three files in a writable runtime dir: +# +# config.js window.__FABRIQ_ADMIN_CONFIG__ for the console +# index.html the built index.html with set to the base path +# upstream.conf nginx location block proxying /admin/ (empty without upstream) +# +# Any invalid value prints to stderr and exits 1, which stops the container +# before nginx starts. POSIX sh; runs the same under busybox, GNU and BSD tools. +set -eu + +RUNTIME_DIR=${FABRIQ_ADMIN_RUNTIME_DIR:-/tmp/fabriq-admin} +HTML_DIR=${FABRIQ_ADMIN_HTML_DIR:-/usr/share/nginx/html} + +BASE_PATH=${FABRIQ_ADMIN_BASE_PATH:-/} +UPSTREAM=${FABRIQ_ADMIN_UPSTREAM:-} +UPSTREAM_KEY=${FABRIQ_ADMIN_UPSTREAM_KEY:-} +API_URL=${FABRIQ_ADMIN_API_URL:-} +DEFAULT_TENANT=${FABRIQ_ADMIN_DEFAULT_TENANT:-} +MAP_STYLE_URL=${FABRIQ_ADMIN_MAP_STYLE_URL:-} + +NL=' +' + +fail() { + echo "fabriq-admin: $*" >&2 + exit 1 +} + +# check +# grep works line by line, so a value with a newline could pass on one good +# line and smuggle the rest into the nginx config. Reject newlines first. +check() { + case $2 in + *"$NL"*) fail "$1 must not contain a newline" ;; + esac + printf '%s\n' "$2" | grep -Eq "$3" || fail "$1 must be $4" +} + +check FABRIQ_ADMIN_BASE_PATH "$BASE_PATH" '^/([A-Za-z0-9._~-]+/)*$' \ + 'a path that starts and ends with / (for example /console/)' +# The regex allows dots inside names; reject whole . and .. segments. +case $BASE_PATH in + */./* | */../*) fail "FABRIQ_ADMIN_BASE_PATH must not contain . or .. segments" ;; +esac + +if [ -n "$UPSTREAM" ]; then + check FABRIQ_ADMIN_UPSTREAM "$UPSTREAM" '^https?://[A-Za-z0-9.-]+(:[0-9]{1,5})?$' \ + 'an origin like http://host:port, with no path' +fi + +if [ -n "$UPSTREAM_KEY" ]; then + [ -n "$UPSTREAM" ] || fail "FABRIQ_ADMIN_UPSTREAM_KEY requires FABRIQ_ADMIN_UPSTREAM" + check FABRIQ_ADMIN_UPSTREAM_KEY "$UPSTREAM_KEY" '^fq_[0-9A-Za-z]{32,}$' \ + 'fq_ followed by at least 32 letters or digits' +fi + +if [ -n "$API_URL" ]; then + check FABRIQ_ADMIN_API_URL "$API_URL" '^(/|https?://)' 'a path starting with / or an http(s) URL' + case $API_URL in + //*) fail "FABRIQ_ADMIN_API_URL must not start with // (protocol-relative)" ;; + esac +fi + +if [ -n "$DEFAULT_TENANT" ]; then + check FABRIQ_ADMIN_DEFAULT_TENANT "$DEFAULT_TENANT" '^[a-zA-Z0-9_-]{1,64}$' \ + '1 to 64 letters, digits, - or _' +fi + +if [ -n "$MAP_STYLE_URL" ]; then + check FABRIQ_ADMIN_MAP_STYLE_URL "$MAP_STYLE_URL" '^https?://' 'an http(s) URL' +fi + +# With an upstream the console talks to the proxy under admin. +if [ -z "$API_URL" ] && [ -n "$UPSTREAM" ]; then + API_URL="${BASE_PATH}admin" +fi + +grep -Fq ' to rewrite" + +mkdir -p "$RUNTIME_DIR" + +# config.js +CONFIG=$(jq -cn \ + --arg basePath "$BASE_PATH" \ + --arg apiUrl "$API_URL" \ + --arg defaultTenant "$DEFAULT_TENANT" \ + --arg mapStyleUrl "$MAP_STYLE_URL" \ + '{basePath: $basePath} + + (if $apiUrl != "" then {apiUrl: $apiUrl} else {} end) + + (if $defaultTenant != "" then {defaultTenant: $defaultTenant} else {} end) + + (if $mapStyleUrl != "" then {mapStyleUrl: $mapStyleUrl} else {} end)') +printf 'window.__FABRIQ_ADMIN_CONFIG__ = %s;\n' "$CONFIG" > "$RUNTIME_DIR/config.js" + +# index.html: the base path only holds [A-Za-z0-9._~/-], so | is a safe delimiter. +sed "s| "$RUNTIME_DIR/index.html" + +# upstream.conf: empty unless an upstream is set. +# +# The block is hardened for a bearer-only API behind a browser console: +# - Cookie is always cleared, so a session cookie from a fronting proxy never +# reaches Fabriq. +# - Uploads are base64 JSON, so the body size limit and request buffering are +# off (the 1 MB default would answer 413). +# - With a key, Authorization is always replaced, so a client cannot send its +# own credentials through, and requests the browser marks as cross-site or +# same-site are refused (403), so another site cannot borrow the key. +: > "$RUNTIME_DIR/upstream.conf" +if [ -n "$UPSTREAM" ]; then + { + printf 'location /admin/ {\n' + printf ' proxy_pass %s;\n' "$UPSTREAM" + case $UPSTREAM in + https://*) printf ' proxy_ssl_server_name on;\n' ;; + esac + printf ' proxy_http_version 1.1;\n' + printf ' proxy_set_header Host $proxy_host;\n' + printf ' proxy_set_header Connection "";\n' + printf ' proxy_set_header Cookie "";\n' + printf ' proxy_buffering off;\n' + printf ' proxy_request_buffering off;\n' + printf ' client_max_body_size 0;\n' + printf ' proxy_read_timeout 3600s;\n' + if [ -n "$UPSTREAM_KEY" ]; then + printf ' if ($http_sec_fetch_site ~ "^(cross-site|same-site)$") {\n' + printf ' return 403;\n' + printf ' }\n' + printf ' proxy_set_header Authorization "Bearer %s";\n' "$UPSTREAM_KEY" + fi + printf '}\n' + } > "$RUNTIME_DIR/upstream.conf" +fi diff --git a/deploy/docker/default.conf b/deploy/docker/default.conf new file mode 100644 index 0000000..8fee3ea --- /dev/null +++ b/deploy/docker/default.conf @@ -0,0 +1,36 @@ +server { + listen 8080; + server_name _; + + root /usr/share/nginx/html; + + location = /healthz { + access_log off; + return 200 "ok\n"; + } + + # Written at container start by 40-fabriq-admin-runtime.sh. Only /tmp is + # writable in the image, so these two come from there instead of from root. + location = /config.js { + alias /tmp/fabriq-admin/config.js; + add_header Cache-Control "no-store"; + } + + location = /index.html { + alias /tmp/fabriq-admin/index.html; + add_header Cache-Control "no-store"; + } + + # Vite fingerprints everything under assets/. + location /assets/ { + add_header Cache-Control "public, max-age=31536000, immutable"; + } + + # SPA fallback: any other path serves the rewritten index.html. + location / { + try_files $uri /index.html; + } + + # Empty, or the /admin/ proxy block when FABRIQ_ADMIN_UPSTREAM is set. + include /tmp/fabriq-admin/upstream.conf; +} diff --git a/deploy/docker/entrypoint_test.sh b/deploy/docker/entrypoint_test.sh new file mode 100755 index 0000000..8d14e6f --- /dev/null +++ b/deploy/docker/entrypoint_test.sh @@ -0,0 +1,170 @@ +#!/bin/sh +# Tests for 40-fabriq-admin-runtime.sh. Runs the script against a fixture +# index.html with the test seams pointed at temp dirs. No docker needed. +# +# sh deploy/docker/entrypoint_test.sh +set -u + +HERE=$(cd "$(dirname "$0")" && pwd) +SCRIPT="$HERE/40-fabriq-admin-runtime.sh" +TMP=$(mktemp -d) +trap 'rm -rf "$TMP"' EXIT INT TERM + +PASS=0 +FAIL=0 +RC=0 +RUNTIME="" + +ok() { PASS=$((PASS + 1)); printf 'PASS %s\n' "$1"; } +bad() { FAIL=$((FAIL + 1)); printf 'FAIL %s\n' "$1"; } + +# run_script : fresh html and runtime dirs, then the script +# under a clean environment. Sets RC, RUNTIME and $TMP/stderr. +run_script() { + rm -rf "$TMP/html" "$TMP/runtime" + mkdir -p "$TMP/html" + printf '%s\n' "${FIXTURE_HEAD-}" > "$TMP/html/index.html" + RUNTIME="$TMP/runtime" + env -i PATH="$PATH" \ + FABRIQ_ADMIN_RUNTIME_DIR="$RUNTIME" \ + FABRIQ_ADMIN_HTML_DIR="$TMP/html" \ + "$@" sh "$SCRIPT" > "$TMP/stdout" 2> "$TMP/stderr" + RC=$? +} + +expect_exit() { # ; a failure must also name the offending variable + if [ "$RC" -ne "$2" ]; then bad "$1: exit $RC, wanted $2 ($(cat "$TMP/stderr"))" + elif [ "$2" -ne 0 ] && ! grep -Fq 'FABRIQ_ADMIN_' "$TMP/stderr"; then bad "$1: exit $2 but stderr names no variable ($(cat "$TMP/stderr"))" + else ok "$1: exit $2"; fi +} +expect_has() { # + if grep -Fq -- "$3" "$2" 2>/dev/null; then ok "$1: $(basename "$2") has $3"; else bad "$1: $(basename "$2") lacks $3"; fi +} +expect_lacks() { # + if grep -Fq -- "$3" "$2" 2>/dev/null; then bad "$1: $(basename "$2") has $3"; else ok "$1: $(basename "$2") lacks $3"; fi +} +expect_empty() { # + if [ -f "$2" ] && [ ! -s "$2" ]; then ok "$1: $(basename "$2") is empty"; else bad "$1: $(basename "$2") is not empty"; fi +} + +VALID_KEY=fq_0123456789abcdefghijklmnopqrstuv + +# defaults +run_script +expect_exit defaults 0 +expect_has defaults "$RUNTIME/config.js" '"basePath":"/"' +expect_lacks defaults "$RUNTIME/config.js" '"apiUrl"' +expect_empty defaults "$RUNTIME/upstream.conf" +expect_has defaults "$RUNTIME/index.html" ' cannot be rewritten +FIXTURE_HEAD='x' +run_script +unset FIXTURE_HEAD +expect_exit no-base-href 1 + +printf '\n%s passed, %s failed\n' "$PASS" "$FAIL" +[ "$FAIL" -eq 0 ] diff --git a/deploy/docker/smoke.sh b/deploy/docker/smoke.sh new file mode 100755 index 0000000..0327b46 --- /dev/null +++ b/deploy/docker/smoke.sh @@ -0,0 +1,146 @@ +#!/bin/sh +# End-to-end check of the console image. Builds it, runs it read-only next to +# an echo server standing in for the Fabriq admin API, and asserts the image +# contract: health, runtime config, base path, SPA fallback, upstream proxy +# with key injection, and a hard stop on invalid env. +# +# sh deploy/docker/smoke.sh +# +# Everything it creates is named fabriq-admin-smoke-* and removed on exit. +set -eu + +ROOT=$(cd "$(dirname "$0")/../.." && pwd) +PORT=${SMOKE_PORT:-18080} +TAG=$$ +IMAGE=fabriq-admin-smoke:$TAG +NET=fabriq-admin-smoke-net-$TAG +UPSTREAM=fabriq-admin-smoke-upstream-$TAG +CONSOLE=fabriq-admin-smoke-console-$TAG +BAD=fabriq-admin-smoke-bad-$TAG +KEY=fq_$(openssl rand -hex 20) +URL=http://127.0.0.1:$PORT + +fail() { + echo "smoke: FAIL: $*" >&2 + exit 1 +} + +cleanup() { + status=$? + if [ "$status" -ne 0 ]; then + for c in "$CONSOLE" "$BAD" "$UPSTREAM"; do + if docker inspect "$c" >/dev/null 2>&1; then + echo "--- logs: $c" >&2 + docker logs "$c" >&2 2>&1 || true + fi + done + fi + docker rm -f "$CONSOLE" "$BAD" "$UPSTREAM" >/dev/null 2>&1 || true + docker network rm "$NET" >/dev/null 2>&1 || true + docker rmi "$IMAGE" >/dev/null 2>&1 || true + exit "$status" +} +trap cleanup EXIT +trap 'exit 1' INT TERM + +echo "smoke: building $IMAGE" +docker build -q -t "$IMAGE" "$ROOT" >/dev/null + +docker network create "$NET" >/dev/null +docker run -d --name "$UPSTREAM" --network "$NET" --network-alias upstream \ + mendhak/http-https-echo:34 >/dev/null + +docker run -d --name "$CONSOLE" --network "$NET" --read-only --tmpfs /tmp \ + -p "127.0.0.1:$PORT:8080" \ + -e FABRIQ_ADMIN_UPSTREAM=http://upstream:8080 \ + -e FABRIQ_ADMIN_UPSTREAM_KEY="$KEY" \ + -e FABRIQ_ADMIN_BASE_PATH=/console/ \ + -e FABRIQ_ADMIN_DEFAULT_TENANT=acme \ + "$IMAGE" >/dev/null + +# /healthz only proves nginx is up. The echo server may still be starting, so +# the proxy checks below retry (see proxy_get). +i=0 +until curl -fsS "$URL/healthz" >/dev/null 2>&1; do + i=$((i + 1)) + [ "$i" -le 30 ] || fail "console did not become healthy within 30s" + sleep 1 +done + +# proxy_get : GET through the console, retrying for up to 15s +# while the upstream answers 502/503/504 or refuses connections. +proxy_get() { + n=0 + until out=$(curl -fsS "$@" 2>/dev/null); do + n=$((n + 1)) + [ "$n" -le 15 ] || fail "no 2xx from the proxy within 15s: curl $*" + sleep 1 + done + printf '%s' "$out" +} + +# status_of : HTTP status code only +status_of() { + curl -s -o /dev/null -w '%{http_code}' "$@" +} + +# healthz +[ "$(curl -sS "$URL/healthz")" = "ok" ] || fail "/healthz body is not ok" +echo "smoke: ok /healthz" + +# uid and read-only root +[ "$(docker exec "$CONSOLE" id -u)" = "101" ] || fail "console does not run as uid 101" +echo "smoke: ok uid 101 on a read-only root" + +# runtime config +CONFIG=$(curl -fsS "$URL/config.js") +case $CONFIG in *'"apiUrl":"/console/admin"'*) ;; *) fail "config.js lacks apiUrl: $CONFIG" ;; esac +case $CONFIG in *'"defaultTenant":"acme"'*) ;; *) fail "config.js lacks defaultTenant: $CONFIG" ;; esac +case $CONFIG in *"$KEY"*) fail "config.js leaks the upstream key" ;; esac +curl -fsSI "$URL/config.js" | grep -qi '^cache-control: no-store' || fail "config.js is cacheable" +echo "smoke: ok /config.js" + +# base path and SPA fallback +for p in / /entities/x; do + BODY=$(curl -fsS "$URL$p") + case $BODY in *'" ;; esac +done +curl -fsSI "$URL/entities/x" | grep -qi '^cache-control: no-store' || fail "the SPA fallback is cacheable" +echo "smoke: ok base path and no-store on / and /entities/x" + +# built assets +ASSET=$(curl -fsS "$URL/" | grep -o 'assets/[A-Za-z0-9._-]*\.js' | head -n 1) +[ -n "$ASSET" ] || fail "no asset found in index.html" +[ "$(curl -s -o /dev/null -w '%{http_code}' "$URL/$ASSET")" = "200" ] || fail "$ASSET is not served" +curl -fsSI "$URL/$ASSET" | grep -qi '^cache-control: public, max-age=31536000, immutable' || fail "$ASSET is not immutable" +echo "smoke: ok $ASSET" + +# proxy: path kept, client Authorization replaced by the configured key, and +# the client's Cookie never forwarded +ECHO=$(proxy_get -H 'Authorization: Bearer wrong' -H 'Cookie: s=secret' "$URL/admin/meta") +[ "$(printf '%s' "$ECHO" | jq -r .path)" = "/admin/meta" ] || fail "upstream saw the wrong path: $ECHO" +[ "$(printf '%s' "$ECHO" | jq -r .headers.authorization)" = "Bearer $KEY" ] || fail "upstream saw the wrong authorization: $ECHO" +[ "$(printf '%s' "$ECHO" | jq -r .headers.cookie)" = "null" ] || fail "upstream saw a cookie: $ECHO" +echo "smoke: ok /admin/ proxy with key injection and no cookies" + +# cross-site and same-site requests are refused while a key is injected +[ "$(status_of -H 'Sec-Fetch-Site: cross-site' "$URL/admin/meta")" = "403" ] || fail "cross-site request was not refused" +[ "$(status_of -H 'Sec-Fetch-Site: same-site' "$URL/admin/meta")" = "403" ] || fail "same-site request was not refused" +proxy_get -H 'Sec-Fetch-Site: same-origin' "$URL/admin/meta" >/dev/null +proxy_get "$URL/admin/meta" >/dev/null +echo "smoke: ok Sec-Fetch-Site 403 for cross-site and same-site, 200 for same-origin and none" + +# invalid env must stop the container before nginx starts +docker run -d --name "$BAD" -e FABRIQ_ADMIN_BASE_PATH=bad "$IMAGE" >/dev/null +i=0 +until [ "$(docker inspect -f '{{.State.Status}}' "$BAD")" = "exited" ]; do + i=$((i + 1)) + [ "$i" -le 10 ] || fail "container with an invalid base path was still running after 10s" + sleep 1 +done +CODE=$(docker inspect -f '{{.State.ExitCode}}' "$BAD") +[ "$CODE" = "1" ] || fail "container with an invalid base path exited $CODE, wanted 1" +docker logs "$BAD" 2>&1 | grep -q FABRIQ_ADMIN_BASE_PATH || fail "the logs do not name FABRIQ_ADMIN_BASE_PATH" +echo "smoke: ok invalid FABRIQ_ADMIN_BASE_PATH exits 1 and is named in the logs" + +echo "smoke: ok" diff --git a/packages/admin-sdk/src/client.test.ts b/packages/admin-sdk/src/client.test.ts index 4a6f99b..f352902 100644 --- a/packages/admin-sdk/src/client.test.ts +++ b/packages/admin-sdk/src/client.test.ts @@ -1163,6 +1163,26 @@ describe("FabriqClient — tenants", () => { expect(transport.lastRequest?.path).toBe("http://localhost:9000/tenants") }) + it("listTenants reads the { tenants } envelope", async () => { + const transport = new FakeTransport() + const tenants = [ + { + tenantId: "acme", + clusterId: "c1", + database: "tnt_acme", + state: "active", + version: 3, + label: "Acme", + mode: "catalog", + createdAt: "2026-01-01T00:00:00Z", + }, + ] + transport.setRequestResponse({ tenants }) + + const client = new FabriqClient({ baseUrl: "http://localhost:9000", transport }) + expect(await client.listTenants()).toEqual(tenants) + }) + it("listTenants — tolerates a bare array response", async () => { const transport = new FakeTransport() const items = [ diff --git a/packages/admin-sdk/src/client.ts b/packages/admin-sdk/src/client.ts index 3615533..b8f6cd1 100644 --- a/packages/admin-sdk/src/client.ts +++ b/packages/admin-sdk/src/client.ts @@ -862,6 +862,9 @@ export interface TenantSummary { state: TenantState /** Schema/migration version the tenant's database is at. */ version: number + label?: string + mode?: "static" | "catalog" + createdAt?: string } /** Where a tenant's database physically lives. */ @@ -2060,16 +2063,19 @@ export class FabriqClient { // ------------------------------------------------------------------------- /** - * GET /tenants — list the tenant catalog. Tolerates both an envelope - * (`{items}`) and a bare array. A backend without the tenants.admin capability - * surfaces as a thrown HttpTransportError (404/501). + * GET /tenants: list the tenant catalog. Tolerates the `{tenants}` envelope + * the server returns, an `{items}` envelope, and a bare array. A backend + * without the tenants.admin capability surfaces as a thrown + * HttpTransportError (404/501). */ async listTenants(): Promise { - const res = await this.transport.request<{ items?: TenantSummary[] } | TenantSummary[]>({ + const res = await this.transport.request< + { tenants?: TenantSummary[]; items?: TenantSummary[] } | TenantSummary[] + >({ method: "GET", path: `${this.baseUrl}/tenants`, }) - return Array.isArray(res) ? res : (res?.items ?? []) + return Array.isArray(res) ? res : (res?.tenants ?? res?.items ?? []) } /** GET /tenants/:id — one tenant's state, version, and placement. */ diff --git a/packages/admin-sdk/src/index.ts b/packages/admin-sdk/src/index.ts index 3289b2d..abbc6af 100644 --- a/packages/admin-sdk/src/index.ts +++ b/packages/admin-sdk/src/index.ts @@ -1,6 +1,8 @@ export const SDK_VERSION = "0.0.0" export * from "./plugin" export * from "./client" +export { readRuntimeConfig } from "./runtimeConfig" +export type { RuntimeConfig } from "./runtimeConfig" export { CapabilityBadges } from "./CapabilityBadges" export type { CapabilityBadgesProps } from "./CapabilityBadges" export * from "./provider" diff --git a/packages/admin-sdk/src/runtimeConfig.test.ts b/packages/admin-sdk/src/runtimeConfig.test.ts new file mode 100644 index 0000000..09ef97d --- /dev/null +++ b/packages/admin-sdk/src/runtimeConfig.test.ts @@ -0,0 +1,69 @@ +import { describe, it, expect, afterEach, vi } from "vitest" +import { readRuntimeConfig } from "./runtimeConfig" + +afterEach(() => { + delete window.__FABRIQ_ADMIN_CONFIG__ + vi.unstubAllEnvs() +}) + +describe("readRuntimeConfig", () => { + it("window value wins over env", () => { + vi.stubEnv("VITE_FABRIQ_API_URL", "http://env.test/admin") + window.__FABRIQ_ADMIN_CONFIG__ = { apiUrl: "http://win.test/admin", basePath: "/console/" } + const cfg = readRuntimeConfig() + expect(cfg.apiUrl).toBe("http://win.test/admin") + expect(cfg.basePath).toBe("/console/") + }) + + it("env wins over default", () => { + vi.stubEnv("VITE_FABRIQ_API_URL", "http://env.test/admin") + vi.stubEnv("VITE_FABRIQ_BASE_PATH", "/env/") + vi.stubEnv("VITE_FABRIQ_DEFAULT_TENANT", "env-tenant") + vi.stubEnv("VITE_FABRIQ_MAP_STYLE_URL", "http://env.test/style.json") + vi.stubEnv("VITE_FABRIQ_DSN", "fabriq://k@localhost:8080/acme") + expect(readRuntimeConfig()).toEqual({ + apiUrl: "http://env.test/admin", + basePath: "/env/", + defaultTenant: "env-tenant", + mapStyleUrl: "http://env.test/style.json", + dsn: "fabriq://k@localhost:8080/acme", + }) + }) + + it("empty window string falls through", () => { + vi.stubEnv("VITE_FABRIQ_API_URL", "http://env.test/admin") + window.__FABRIQ_ADMIN_CONFIG__ = { apiUrl: "", basePath: "" } + const cfg = readRuntimeConfig() + expect(cfg.apiUrl).toBe("http://env.test/admin") + expect(cfg.basePath).toBe("/") + }) + + it("defaults are localhost admin and /", () => { + vi.stubEnv("VITE_FABRIQ_API_URL", "") + vi.stubEnv("VITE_FABRIQ_BASE_PATH", "") + const cfg = readRuntimeConfig() + expect(cfg.apiUrl).toBe("http://localhost:8080/admin") + expect(cfg.basePath).toBe("/") + expect(cfg.dsn).toBeUndefined() + expect(cfg.defaultTenant).toBeUndefined() + expect(cfg.mapStyleUrl).toBeUndefined() + }) + + it("resolves a relative apiUrl against the page location", () => { + window.__FABRIQ_ADMIN_CONFIG__ = { apiUrl: "/console/admin" } + expect(readRuntimeConfig().apiUrl).toBe(`${window.location.origin}/console/admin`) + }) + + it("leaves an absolute apiUrl unchanged", () => { + window.__FABRIQ_ADMIN_CONFIG__ = { apiUrl: "https://api.example.com:9443/admin" } + expect(readRuntimeConfig().apiUrl).toBe("https://api.example.com:9443/admin") + }) + + it("window dsn is ignored", () => { + vi.stubEnv("VITE_FABRIQ_DSN", "") + window.__FABRIQ_ADMIN_CONFIG__ = { dsn: "fabriq://leak@host/x" } as never + expect(readRuntimeConfig().dsn).toBeUndefined() + vi.stubEnv("VITE_FABRIQ_DSN", "fabriq://env@host/x") + expect(readRuntimeConfig().dsn).toBe("fabriq://env@host/x") + }) +}) diff --git a/packages/admin-sdk/src/runtimeConfig.ts b/packages/admin-sdk/src/runtimeConfig.ts new file mode 100644 index 0000000..a896bb6 --- /dev/null +++ b/packages/admin-sdk/src/runtimeConfig.ts @@ -0,0 +1,73 @@ +/** + * Runtime configuration for the console. + * + * A static host (or the container entrypoint) writes `config.js`, which sets + * `window.__FABRIQ_ADMIN_CONFIG__` before the app boots. That lets one built + * bundle serve any API URL and any URL prefix. Build-time `VITE_*` env stays + * as a fallback for local development. + */ +export interface RuntimeConfig { + /** + * Admin API base URL. Always absolute when a window exists: a relative value + * (e.g. "/console/admin") is resolved against the page location, because the + * HTTP transport would otherwise prefix its base onto the path twice. + */ + apiUrl: string + /** Router mount path, e.g. "/" or "/console/". */ + basePath: string + /** Connection DSN. Build-time env only; never read from the served file. */ + dsn?: string + defaultTenant?: string + mapStyleUrl?: string +} + +declare global { + interface Window { + __FABRIQ_ADMIN_CONFIG__?: Partial> + } +} + +const DEFAULT_API_URL = "http://localhost:8080/admin" +const DEFAULT_BASE_PATH = "/" + +function toAbsoluteUrl(url: string): string { + if (typeof window === "undefined" || /^https?:\/\//i.test(url)) return url + return new URL(url, window.location.href).href +} + +function nonEmpty(v: unknown): string | undefined { + return typeof v === "string" && v !== "" ? v : undefined +} + +/** + * Resolves the current configuration. Reads on every call (no caching) so + * tests can stub env and the window object between cases. + * + * Precedence per field: window object, then `import.meta.env`, then default. + * + * `apiUrl` comes back absolute when a window exists (a relative value is + * resolved against `window.location.href`); absolute inputs are unchanged. + * Without a window the raw value is returned. + */ +export function readRuntimeConfig(): RuntimeConfig { + const win: Partial> = + typeof window !== "undefined" ? (window.__FABRIQ_ADMIN_CONFIG__ ?? {}) : {} + // Written as a literal `import.meta.env` so Vite and Vitest can substitute it. + // This package has no vite/client types, hence the ignore (consumers that do + // have them would reject an @ts-expect-error as unused). + // @ts-ignore + const env = (import.meta.env ?? {}) as Record + + return { + apiUrl: toAbsoluteUrl( + nonEmpty(win["apiUrl"]) ?? nonEmpty(env["VITE_FABRIQ_API_URL"]) ?? DEFAULT_API_URL, + ), + basePath: + nonEmpty(win["basePath"]) ?? nonEmpty(env["VITE_FABRIQ_BASE_PATH"]) ?? DEFAULT_BASE_PATH, + // A dsn on the window object is deliberately ignored so a key can never + // ride in the served file. + dsn: nonEmpty(env["VITE_FABRIQ_DSN"]), + defaultTenant: nonEmpty(win["defaultTenant"]) ?? nonEmpty(env["VITE_FABRIQ_DEFAULT_TENANT"]), + mapStyleUrl: nonEmpty(win["mapStyleUrl"]) ?? nonEmpty(env["VITE_FABRIQ_MAP_STYLE_URL"]), + } +} diff --git a/plugins/connection/src/ConnectionInfoCard.tsx b/plugins/connection/src/ConnectionInfoCard.tsx index b86d99b..8ea1f7a 100644 --- a/plugins/connection/src/ConnectionInfoCard.tsx +++ b/plugins/connection/src/ConnectionInfoCard.tsx @@ -1,15 +1,19 @@ -import { getSessionToken, buildDsn, type FabriqClient } from "@fabriq-ai/admin-sdk" +import { getSessionToken, buildDsn, readRuntimeConfig, type FabriqClient } from "@fabriq-ai/admin-sdk" import { Card, CardHeader, CardTitle, CardDescription, CardContent, Badge } from "@fabriq-ai/ui" import { CopyField, maskDsnCredential } from "./CopyField" -/** Parse an HTTP base URL (e.g. http://localhost:8080/admin) into DSN parts. */ +/** + * Parse an HTTP base URL (e.g. http://localhost:8080/admin) into DSN parts. + * A relative base (e.g. /console/admin, as written by the container) is + * resolved against the page location. + */ export function connectionFromBaseUrl(baseUrl: string): { host: string port: number tls: boolean basePath: string } { - const u = new URL(baseUrl) + const u = new URL(baseUrl, window.location.href) const tls = u.protocol === "https:" const port = u.port ? Number(u.port) : tls ? 443 : 80 const basePath = u.pathname.replace(/\/$/, "") || "/admin" @@ -17,8 +21,7 @@ export function connectionFromBaseUrl(baseUrl: string): { } function readEnvDsn(): string | undefined { - const env = (import.meta as unknown as { env?: Record }).env - return env?.["VITE_FABRIQ_DSN"] + return readRuntimeConfig().dsn } function authMode(): "dsn" | "session" | "none" { diff --git a/plugins/connection/src/connection.test.tsx b/plugins/connection/src/connection.test.tsx index 85d6dce..48b9011 100644 --- a/plugins/connection/src/connection.test.tsx +++ b/plugins/connection/src/connection.test.tsx @@ -9,6 +9,7 @@ import { type FabriqTransport, } from "@fabriq-ai/admin-sdk" import { connectionPlugin } from "./index" +import { connectionFromBaseUrl } from "./ConnectionInfoCard" function makeClient(handler: (o: any) => unknown) { const request = vi.fn(async (o: any) => handler(o)) @@ -45,6 +46,23 @@ describe("connection plugin", () => { expect(screen.getByText("/admin")).toBeTruthy() }) + it("connectionFromBaseUrl resolves a relative base against the page origin", () => { + // jsdom's default location is http://localhost:3000/ + const c = connectionFromBaseUrl("/console/admin") + expect(c).toEqual({ + host: window.location.hostname, + port: Number(window.location.port) || (window.location.protocol === "https:" ? 443 : 80), + tls: window.location.protocol === "https:", + basePath: "/console/admin", + }) + expect(connectionFromBaseUrl("https://api.example.com:9443/admin/")).toEqual({ + host: "api.example.com", + port: 9443, + tls: true, + basePath: "/admin", + }) + }) + it("shows a keyless connection string (base URL, no credential) when auth is off", async () => { const client = makeClient((o) => { if ((o.path as string).endsWith("/keys")) return { keys: [] } diff --git a/plugins/spatial/src/SpatialMap.tsx b/plugins/spatial/src/SpatialMap.tsx index 140fa6a..f970863 100644 --- a/plugins/spatial/src/SpatialMap.tsx +++ b/plugins/spatial/src/SpatialMap.tsx @@ -1,13 +1,12 @@ import { useEffect, useRef } from "react" import maplibregl from "maplibre-gl" import "maplibre-gl/dist/maplibre-gl.css" -import type { SpatialMatch } from "@fabriq-ai/admin-sdk" +import { readRuntimeConfig, type SpatialMatch } from "@fabriq-ai/admin-sdk" const DEFAULT_STYLE = "https://demotiles.maplibre.org/style.json" function styleUrl(): string { - const env = (import.meta as unknown as { env?: Record }).env - return env?.["VITE_FABRIQ_MAP_STYLE_URL"] || DEFAULT_STYLE + return readRuntimeConfig().mapStyleUrl || DEFAULT_STYLE } // Nearest (green) → farthest (red).