Add path-prefix deployment support for migrating to podsteadr's domain

Regress needs to live at podsteadr.atobitcoin.io/regress/ since / is
already podsteadr. Two coordinated pieces:
- VITE_BASE build arg (frontend asset/script paths, %BASE_URL% in
  index.html for the nostr-provider.js script tag)
- ROUTE_PREFIX runtime env (backend routes registered under the prefix
  via Fastify's plugin-encapsulation, including /api/health)

The nginx location must forward the prefix unstripped (proxy_pass with
no trailing path) — NIP-98 login signs the exact URL it calls, so a
stripped prefix makes the backend reconstruct a different URL than what
was signed and every login fails. Caught this with a real nginx+docker
integration test locally before it could break the live migration, then
fixed a matching bug in auth.ts (it was signing the unprefixed URL while
api.ts fetched the prefixed one). New routePrefix.test.ts proves the
prefix is actually enforced, including a negative case. 40 tests passing.

Also fixes a latent bug: import.meta.env usage had no vite/client type
reference, so it only ever passed typecheck by accident in earlier local
runs — added the standard vite-env.d.ts.
This commit is contained in:
2026-08-05 14:58:43 +00:00
parent df9a4ae74b
commit 517186ac55
11 changed files with 214 additions and 61 deletions
+6 -3
View File
@@ -1,10 +1,11 @@
# ---- frontend ---- # ---- frontend ----
FROM node:22-bookworm-slim AS frontend-build FROM node:22-bookworm-slim AS frontend-build
ARG VITE_BASE=/
WORKDIR /build/frontend WORKDIR /build/frontend
COPY frontend/package*.json ./ COPY frontend/package*.json ./
RUN npm ci RUN npm ci
COPY frontend/ ./ COPY frontend/ ./
RUN npm run build RUN VITE_BASE=$VITE_BASE npm run build
# ---- server ---- # ---- server ----
FROM node:22-bookworm-slim AS server-build FROM node:22-bookworm-slim AS server-build
@@ -16,6 +17,7 @@ RUN npm run build && npm prune --omit=dev
# ---- runtime ---- # ---- runtime ----
FROM node:22-bookworm-slim FROM node:22-bookworm-slim
ARG ROUTE_PREFIX=
RUN apt-get update \ RUN apt-get update \
&& apt-get install -y --no-install-recommends curl \ && apt-get install -y --no-install-recommends curl \
&& rm -rf /var/lib/apt/lists/* && rm -rf /var/lib/apt/lists/*
@@ -29,8 +31,9 @@ USER node
ENV NODE_ENV=production \ ENV NODE_ENV=production \
PORT=8199 \ PORT=8199 \
DATA_DIR=/data \ DATA_DIR=/data \
STATIC_DIR=/app/public STATIC_DIR=/app/public \
ROUTE_PREFIX=${ROUTE_PREFIX}
EXPOSE 8199 EXPOSE 8199
HEALTHCHECK --interval=30s --timeout=5s --retries=3 \ HEALTHCHECK --interval=30s --timeout=5s --retries=3 \
CMD curl -fsS http://localhost:8199/api/health || exit 1 CMD curl -fsS http://localhost:8199${ROUTE_PREFIX}/api/health || exit 1
CMD ["node", "dist/index.js"] CMD ["node", "dist/index.js"]
+57 -37
View File
@@ -60,47 +60,67 @@ npm test
## Deployment ## Deployment
Live at **`https://archy-x250-dev3.tail08d8f2.ts.net:8543`** (Tailscale-only — Live at **`https://podsteadr.atobitcoin.io/regress/`** — same public host as
this node has no public IP, so it isn't reachable from the open internet like [podsteadr](http://146.59.87.168:3000/ssmithx/podsteadr), reached via a path
podsteadr is; anyone playing needs to be on the same tailnet). prefix under the existing domain/cert rather than its own subdomain (no DNS
access to add one). Migrated here from an earlier `archy-x250-dev3` trial
deploy (Tailscale-only Archipelago node) — see git history for that phase.
- Single container (`Dockerfile`, server + built frontend in one image), - Single container (`Dockerfile`, server + built frontend in one image),
`podman run --restart unless-stopped`, data on a bind-mounted volume at `podman run --restart unless-stopped`, data bind-mounted at
`/var/lib/archipelago/regress-data` on the node. `/var/lib/archipelago/regress-data` on the host, internal port **8199**
- Fronted by a dedicated nginx server block, `deploy/nginx-archy-node.conf`, (bound to `127.0.0.1` only — nginx is the only way in).
on its own port (**8543**) rather than being proxied under the node's main - `deploy/nginx-podsteadr-regress.conf` — the `location /regress/` block
dashboard (80/443). added to podsteadr's existing nginx site.
**Why a dedicated port, not `/app/regress/` like other installed apps:** ### Path-prefix deployment (`ROUTE_PREFIX` / `VITE_BASE`)
archipelago's own nginx config sets `Permissions-Policy:
geolocation=()` server-wide on its 80/443 blocks — inherited by every
`location` under them that doesn't set its own `add_header`s. Regress's
entire claim/link mechanic depends on `navigator.geolocation`, so being
proxied under those blocks would silently break the core game with no
clear error. A separate server block sidesteps this entirely and sets
`Permissions-Policy: geolocation=(self)` explicitly.
**Also found, not yet fixed:** the Archipelago dashboard's own app-iframe Since `/` on this domain is already podsteadr, Regress needed to support
element (`neode-ui/src/views/appSession/AppSessionFrame.vue`) has no being served from a path prefix — this took two coordinated changes, both
`allow="geolocation"` attribute, so even a geolocation-permitting app would required together:
have geolocation blocked by the browser's default iframe permission
delegation if launched *inside* the dashboard iframe. This isn't
Regress-specific — it'd affect any app needing geolocation. Until that's
patched (a shared-component change, out of scope for this deploy), players
should open Regress directly (the URL above, or "open in new tab" from the
dashboard) rather than through the in-dashboard iframe.
- Non-standard port gotcha: nginx's `$host` variable strips the port before 1. **Frontend build**: `VITE_BASE=/regress/` (Vite's `base` config) so built
forwarding, which breaks NIP-98 login (`u` tag URL won't match). Use asset URLs and the vendored `nostr-provider.js` script tag/data
`proxy_set_header Host $http_host;` (preserves the original port) — already attributes (via `%BASE_URL%` in `index.html`) resolve under the prefix.
set correctly in `deploy/nginx-archy-node.conf`. 2. **Backend runtime**: `ROUTE_PREFIX=/regress` env var — every route
- `PUBLIC_URL` passed to the container must include the `:8543` for the same (including `/api/health`) is registered under this prefix via Fastify's
reason. plugin-encapsulation `{ prefix }` option (`app.ts`).
**The nginx location must forward the full prefixed path unchanged — do
NOT strip it**, unlike podsteadr's own `/player/`, `/hls/`, etc. blocks
which all strip their prefix (`proxy_pass http://127.0.0.1:PORT/;` with a
trailing slash). Regress's NIP-98 login signs the *exact* URL it's about to
call, prefix included (`frontend/src/lib/api.ts#apiUrl`); if nginx stripped
the prefix before forwarding, the backend would reconstruct a different
(unprefixed) URL to check the signature against, and every login would fail
with "u tag does not match the request URL". So the location block uses
`proxy_pass http://127.0.0.1:8199;`**no trailing path at all** — which
tells nginx to forward the original URI verbatim, prefix included. This is
covered by `server/src/routePrefix.test.ts`, including a negative test that
a signed-for-the-unprefixed-URL login is correctly rejected (proving the
prefix check is real, not accidentally bypassed).
Deploying at root (no prefix) needs neither variable — both default to `''`/`'/'`.
### Migrating the SQLite database between hosts
The whole game state (places/claims/links/users) is one file,
`regress.sqlite3`. To move it: stop the container, copy the file (plus its
`-wal`/`-shm` siblings if present, or checkpoint first), start the new
container pointed at the copy. No export/import tooling needed — see git
history for the exact commands used for the archy-x250-dev3 → podsteadr
machine move.
To redeploy after a code change: `git pull` in To redeploy after a code change: `git pull` in
`/var/lib/archipelago/regress-src` on the node, `podman build -t `/var/lib/archipelago/regress-src` on the host, then:
localhost/regress:latest .`, then `podman run -d --name regress-app --replace
--restart unless-stopped -p 127.0.0.1:8199:8199 -v ```bash
/var/lib/archipelago/regress-data:/data -e podman build --build-arg VITE_BASE=/regress/ --build-arg ROUTE_PREFIX=/regress \
PUBLIC_URL=https://archy-x250-dev3.tail08d8f2.ts.net:8543 -t localhost/regress:latest .
localhost/regress:latest`. podman run -d --name regress-app --replace --restart unless-stopped \
-p 127.0.0.1:8199:8199 \
-v /var/lib/archipelago/regress-data:/data \
-e ROUTE_PREFIX=/regress \
-e PUBLIC_URL=https://podsteadr.atobitcoin.io \
localhost/regress:latest
```
+18
View File
@@ -0,0 +1,18 @@
# Snippet added to podsteadr's existing /etc/nginx/sites-enabled/podsteadr,
# inside the existing `server { listen 443 ssl; ... }` block, alongside its
# /blossom/, /player/, /hls/, /whip/ locations.
#
# Unlike those locations, this one must NOT strip the /regress/ prefix —
# proxy_pass has no trailing path component, which tells nginx to forward
# the original request URI verbatim (prefix included). See README.md
# "Path-prefix deployment" for why: Regress's NIP-98 login signs the exact
# URL it calls, prefix included, and the backend (ROUTE_PREFIX=/regress)
# expects to see that same prefixed path.
location /regress/ {
proxy_pass http://127.0.0.1:8199;
proxy_http_version 1.1;
proxy_set_header Host $http_host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
+1 -1
View File
@@ -14,7 +14,7 @@
window === window.top guard) — safe to always include. Provides window === window.top guard) — safe to always include. Provides
window.nostr + auto sign-in via the node's selected nostr identity window.nostr + auto sign-in via the node's selected nostr identity
when opened inside the Archipelago shell. --> when opened inside the Archipelago shell. -->
<script src="/nostr-provider.js" data-session-url="/api/auth/login" data-session-mode="cookie" data-me-url="/api/auth/me" data-health-url="/api/health"></script> <script src="%BASE_URL%nostr-provider.js" data-session-url="%BASE_URL%api/auth/login" data-session-mode="cookie" data-me-url="%BASE_URL%api/auth/me" data-health-url="%BASE_URL%api/health"></script>
</head> </head>
<body> <body>
<div id="app"></div> <div id="app"></div>
+19 -1
View File
@@ -6,8 +6,26 @@ export class ApiError extends Error {
} }
} }
// import.meta.env.BASE_URL is Vite's configured `base` (e.g. "/" or
// "/regress/") — API paths must resolve under it too when this app is
// deployed under a path prefix, not just its own static assets.
export function withBase(path: string): string {
const base = import.meta.env.BASE_URL.replace(/\/$/, '');
return `${base}${path}`;
}
/**
* Full absolute URL for a given API path, base-prefix included. NIP-98 login
* must sign exactly this — the same URL that will actually be requested —
* or the reverse proxy's forwarded path won't match the signature and every
* login under a path-prefixed deployment fails.
*/
export function apiUrl(path: string): string {
return `${location.origin}${withBase(path)}`;
}
async function request<T>(method: string, path: string, body?: unknown, headers?: Record<string, string>): Promise<T> { async function request<T>(method: string, path: string, body?: unknown, headers?: Record<string, string>): Promise<T> {
const res = await fetch(path, { const res = await fetch(withBase(path), {
method, method,
credentials: 'same-origin', credentials: 'same-origin',
headers: { headers: {
+3 -3
View File
@@ -1,5 +1,5 @@
import { defineStore } from 'pinia'; import { defineStore } from 'pinia';
import { api, ApiError } from '../lib/api'; import { api, apiUrl, ApiError } from '../lib/api';
import { buildNip98Header, hasNip07 } from '../lib/nip07'; import { buildNip98Header, hasNip07 } from '../lib/nip07';
import { buildNip98HeaderWithNsec, isValidNsec } from '../lib/nsec'; import { buildNip98HeaderWithNsec, isValidNsec } from '../lib/nsec';
@@ -34,7 +34,7 @@ export const useAuthStore = defineStore('auth', {
}, },
async login() { async login() {
if (!hasNip07()) throw new Error('No nostr extension found — install Alby or nos2x first.'); if (!hasNip07()) throw new Error('No nostr extension found — install Alby or nos2x first.');
const url = `${location.origin}/api/auth/login`; const url = apiUrl('/api/auth/login');
const header = await buildNip98Header(url, 'POST'); const header = await buildNip98Header(url, 'POST');
const res = await api.post<{ pubkey: string; team: Team | null }>( const res = await api.post<{ pubkey: string; team: Team | null }>(
'/api/auth/login', '/api/auth/login',
@@ -53,7 +53,7 @@ export const useAuthStore = defineStore('auth', {
*/ */
async loginWithNsec(nsec: string) { async loginWithNsec(nsec: string) {
if (!isValidNsec(nsec)) throw new Error('That doesn\'t look like a valid nsec.'); if (!isValidNsec(nsec)) throw new Error('That doesn\'t look like a valid nsec.');
const url = `${location.origin}/api/auth/login`; const url = apiUrl('/api/auth/login');
const header = buildNip98HeaderWithNsec(nsec, url, 'POST'); const header = buildNip98HeaderWithNsec(nsec, url, 'POST');
const res = await api.post<{ pubkey: string; team: Team | null }>( const res = await api.post<{ pubkey: string; team: Team | null }>(
'/api/auth/login', '/api/auth/login',
+1
View File
@@ -0,0 +1 @@
/// <reference types="vite/client" />
+1
View File
@@ -2,6 +2,7 @@ import { defineConfig } from 'vite';
import vue from '@vitejs/plugin-vue'; import vue from '@vitejs/plugin-vue';
export default defineConfig({ export default defineConfig({
base: process.env.VITE_BASE || '/',
plugins: [vue()], plugins: [vue()],
server: { server: {
proxy: { proxy: {
+26 -16
View File
@@ -44,25 +44,35 @@ export async function buildApp(opts: BuildAppOptions): Promise<FastifyInstance>
await app.register(cors, { origin: true, credentials: true, methods: ['GET', 'POST', 'DELETE'] }); await app.register(cors, { origin: true, credentials: true, methods: ['GET', 'POST', 'DELETE'] });
await app.register(nostrAuth, { db, config }); await app.register(nostrAuth, { db, config });
app.get('/api/health', async () => ({ status: 'ok' })); // Everything below is mounted under ROUTE_PREFIX (empty by default, i.e.
// root) so a single build can be deployed either standalone or under a
// shared domain's path — see config.ts for why the prefix must be
// preserved end-to-end rather than stripped by the reverse proxy.
const prefix = config.ROUTE_PREFIX;
await app.register(
async (scoped) => {
scoped.get('/api/health', async () => ({ status: 'ok' }));
await app.register(authRoutes); await scoped.register(authRoutes);
await app.register(placesRoutes); await scoped.register(placesRoutes);
await app.register(claimsRoutes); await scoped.register(claimsRoutes);
await app.register(linksRoutes); await scoped.register(linksRoutes);
await app.register(fieldsRoutes); await scoped.register(fieldsRoutes);
await app.register(syncRoutes); await scoped.register(syncRoutes);
const staticDir = config.STATIC_DIR; const staticDir = config.STATIC_DIR;
if (staticDir && existsSync(staticDir)) { if (staticDir && existsSync(staticDir)) {
await app.register(fastifyStatic, { root: staticDir }); await scoped.register(fastifyStatic, { root: staticDir, prefix: '/' });
app.setNotFoundHandler((req, reply) => { scoped.setNotFoundHandler((req, reply) => {
if (req.raw.url?.startsWith('/api/')) { if (req.raw.url?.startsWith(`${prefix}/api/`)) {
return reply.code(404).send({ error: 'not found' }); return reply.code(404).send({ error: 'not found' });
}
return reply.sendFile('index.html');
});
} }
return reply.sendFile('index.html'); },
}); { prefix },
} );
app.addHook('onClose', async () => { app.addHook('onClose', async () => {
db.close(); db.close();
+7
View File
@@ -6,6 +6,13 @@ const envSchema = z.object({
DATA_DIR: z.string().default('./data'), DATA_DIR: z.string().default('./data'),
STATIC_DIR: z.string().optional(), STATIC_DIR: z.string().optional(),
PUBLIC_URL: z.string().url().default('http://localhost:8096'), PUBLIC_URL: z.string().url().default('http://localhost:8096'),
// Set when this instance is deployed under a path prefix on a shared domain
// (e.g. "/regress" on podsteadr.atobitcoin.io/regress/) rather than at
// root. Must match nginx's location block, which must NOT strip the
// prefix — the NIP-98 `u` tag the frontend signs includes it, so the
// backend needs to see (and route) the same full path. Leave unset ("") to
// deploy at root, e.g. its own dedicated host/port.
ROUTE_PREFIX: z.string().default(''),
NIP98_MAX_SKEW_SECS: z.coerce.number().default(60), NIP98_MAX_SKEW_SECS: z.coerce.number().default(60),
SESSION_TTL_DAYS: z.coerce.number().default(30), SESSION_TTL_DAYS: z.coerce.number().default(30),
// Default sync area: Madeira, Portugal (Funchal-centered radius covering the whole island). // Default sync area: Madeira, Portugal (Funchal-centered radius covering the whole island).
+75
View File
@@ -0,0 +1,75 @@
import { mkdtempSync, rmSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { afterAll, beforeAll, describe, expect, it } from 'vitest';
import { finalizeEvent, generateSecretKey, getPublicKey } from 'nostr-tools/pure';
import type { FastifyInstance } from 'fastify';
import { buildApp } from './app.js';
import { loadConfig } from './config.js';
// Mirrors deploying under e.g. podsteadr.atobitcoin.io/regress/, where nginx
// forwards the full prefixed path unchanged (not stripped) — see config.ts.
const sk = generateSecretKey();
const pk = getPublicKey(sk);
let app: FastifyInstance;
let dataDir: string;
function nip98Header(url: string, method: string): string {
const event = finalizeEvent(
{
kind: 27235,
created_at: Math.floor(Date.now() / 1000),
content: '',
tags: [['u', url], ['method', method]],
},
sk,
);
return `Nostr ${Buffer.from(JSON.stringify(event)).toString('base64')}`;
}
beforeAll(async () => {
dataDir = mkdtempSync(join(tmpdir(), 'regress-prefix-test-'));
const config = loadConfig({
DATA_DIR: dataDir,
PUBLIC_URL: 'https://podsteadr.atobitcoin.io',
ROUTE_PREFIX: '/regress',
} as NodeJS.ProcessEnv);
app = await buildApp({ config, dbPath: ':memory:', logger: false });
});
afterAll(async () => {
await app.close();
rmSync(dataDir, { recursive: true, force: true });
});
describe('ROUTE_PREFIX deployment', () => {
it('serves health under the prefix, not at root', async () => {
const prefixed = await app.inject({ method: 'GET', url: '/regress/api/health' });
expect(prefixed.statusCode).toBe(200);
const atRoot = await app.inject({ method: 'GET', url: '/api/health' });
expect(atRoot.statusCode).toBe(404);
});
it('accepts a NIP-98 login signed for the full prefixed URL (matching what nginx forwards unstripped)', async () => {
const url = 'https://podsteadr.atobitcoin.io/regress/api/auth/login';
const res = await app.inject({
method: 'POST',
url: '/regress/api/auth/login',
headers: { authorization: nip98Header(url, 'POST') },
});
expect(res.statusCode).toBe(200);
expect(res.json().pubkey).toBe(pk);
});
it('rejects a login signed for the unprefixed URL — proves the prefix is actually enforced, not incidentally ignored', async () => {
const unprefixedUrl = 'https://podsteadr.atobitcoin.io/api/auth/login';
const res = await app.inject({
method: 'POST',
url: '/regress/api/auth/login',
headers: { authorization: nip98Header(unprefixedUrl, 'POST') },
});
expect(res.statusCode).toBe(401);
});
});