diff --git a/Dockerfile b/Dockerfile index b4ece033..6e0389e8 100644 --- a/Dockerfile +++ b/Dockerfile @@ -7,24 +7,19 @@ RUN find . -type f \! -name 'package.json' \! -name 'pnpm-workspace.yaml' \! -na # Stage 1: Install ALL dependencies (needed for build) FROM node:22-alpine AS deps -RUN corepack enable pnpm +RUN npm install -g pnpm@9.15.0 RUN apk add --no-cache python3 make g++ WORKDIR /app # Copy only the extracted package.jsons COPY --from=extractor /app ./ # Install dependencies with cache mount for pnpm store -RUN --mount=type=cache,id=pnpm,target=/root/.local/share/pnpm/store pnpm install --frozen-lockfile +RUN --mount=type=cache,id=pnpm,target=/root/.local/share/pnpm/store pnpm install # Stage 3: Build the application FROM deps AS builder # Copy full source code COPY . . -RUN DATABASE_URL="file:./data/wwv.db" npx prisma generate - -# Create an empty SQLite database with all tables applied -RUN mkdir -p ./data && DATABASE_URL=file:./data/wwv.db npx prisma migrate deploy - # Next.js inlines NEXT_PUBLIC_* vars at build time — must be declared as ARGs ARG NEXT_PUBLIC_CESIUM_ION_TOKEN ARG NEXT_PUBLIC_GOOGLE_MAPS_API_KEY @@ -35,6 +30,13 @@ ARG NEXT_PUBLIC_ADSENSE_CLIENT_ID ARG NEXT_PUBLIC_SUPABASE_URL ARG NEXT_PUBLIC_SUPABASE_ANON_KEY +# Run our pregenerate schema swap script and then generate Prisma client +RUN npx prisma generate + +# Create an empty SQLite database with all tables applied ONLY IF NOT CLOUD +# (For cloud, we'll run migrations against Postgres at runtime) +RUN if [ "$NEXT_PUBLIC_WWV_EDITION" != "cloud" ]; then mkdir -p ./data && DATABASE_URL=file:./data/wwv.db npx prisma migrate deploy; fi + # Run Next.js build with Webpack cache mounted RUN --mount=type=cache,target=/app/.next/cache NODE_OPTIONS="--max_old_space_size=3072" pnpm run build RUN node scripts/copy-cesium.mjs @@ -43,6 +45,8 @@ RUN node scripts/copy-cesium.mjs FROM node:22-alpine AS runner WORKDIR /app +RUN apk add --no-cache openssl + ENV NODE_ENV=production ENV HOSTNAME=0.0.0.0 ENV PORT=3000 @@ -65,14 +69,16 @@ COPY --from=builder /app/.next/standalone ./ # Copy static assets that standalone mode does NOT include COPY --from=builder /app/.next/static ./.next/static COPY --from=builder /app/public ./public +COPY --from=builder /app/scripts/https-proxy.mjs ./scripts/https-proxy.mjs # Entrypoint: migrate DB on first run, then start server COPY docker-entrypoint.sh ./docker-entrypoint.sh +RUN sed -i 's/\r$//' ./docker-entrypoint.sh RUN chmod +x ./docker-entrypoint.sh # Declare /app/data as a persistent volume mount point. VOLUME ["/app/data"] -EXPOSE 3000 +EXPOSE 3000 3001 ENTRYPOINT ["./docker-entrypoint.sh"] diff --git a/docker-entrypoint.sh b/docker-entrypoint.sh index bbcf0b9b..97d0bfd1 100644 --- a/docker-entrypoint.sh +++ b/docker-entrypoint.sh @@ -11,4 +11,15 @@ echo "[entrypoint] Running database migrations..." npx -y prisma migrate deploy echo "[entrypoint] Migrations complete." +# Generate self-signed SSL certificates for local HTTPS bridging if they don't exist +if [ ! -f "./data/localhost.crt" ] || [ ! -f "./data/localhost.key" ]; then + echo "[entrypoint] Generating self-signed SSL certificates for port 3001..." + openssl req -nodes -new -x509 -keyout ./data/localhost.key -out ./data/localhost.crt -days 365 -subj "/CN=localhost" 2>/dev/null +fi + +# Start the HTTPS proxy in the background +if [ -f "./scripts/https-proxy.mjs" ]; then + node ./scripts/https-proxy.mjs & +fi + exec node server.js diff --git a/package.json b/package.json index 7322f921..f3942aac 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "worldwideview", - "version": "1.20.1", + "version": "1.20.3", "private": true, "packageManager": "pnpm@9.15.4", "scripts": { diff --git a/scripts/https-proxy.mjs b/scripts/https-proxy.mjs new file mode 100644 index 00000000..df7b65c5 --- /dev/null +++ b/scripts/https-proxy.mjs @@ -0,0 +1,51 @@ +import https from 'https'; +import http from 'http'; +import fs from 'fs'; +import path from 'path'; +import { fileURLToPath } from 'url'; + +const __dirname = path.dirname(fileURLToPath(import.meta.url)); + +const targetPort = 3000; +const listenPort = 3001; +const certPath = path.join(process.cwd(), 'data', 'localhost.crt'); +const keyPath = path.join(process.cwd(), 'data', 'localhost.key'); + +if (!fs.existsSync(certPath) || !fs.existsSync(keyPath)) { + console.error('[HTTPS Proxy] Certificates not found. Proxy will not start.'); + process.exit(1); +} + +const options = { + key: fs.readFileSync(keyPath), + cert: fs.readFileSync(certPath) +}; + +const server = https.createServer(options, (req, res) => { + const proxyReq = http.request({ + hostname: '127.0.0.1', + port: targetPort, + path: req.url, + method: req.method, + headers: { + ...req.headers, + 'x-forwarded-proto': 'https', + 'x-forwarded-port': String(listenPort) + } + }, (proxyRes) => { + res.writeHead(proxyRes.statusCode || 500, proxyRes.headers); + proxyRes.pipe(res, { end: true }); + }); + + proxyReq.on('error', (e) => { + console.error(`[HTTPS Proxy] Error proxying request to ${req.url}:`, e.message); + res.writeHead(502); + res.end('Bad Gateway'); + }); + + req.pipe(proxyReq, { end: true }); +}); + +server.listen(listenPort, '0.0.0.0', () => { + console.log(`[HTTPS Proxy] Secure bridge listening on https://0.0.0.0:${listenPort} (forwarding to http://127.0.0.1:${targetPort})`); +}); diff --git a/src/app/api/marketplace/grant-token/route.ts b/src/app/api/marketplace/grant-token/route.ts index 42116985..a7c0828b 100644 --- a/src/app/api/marketplace/grant-token/route.ts +++ b/src/app/api/marketplace/grant-token/route.ts @@ -5,6 +5,7 @@ import { issueMarketplaceToken } from "@/lib/marketplace/marketplaceToken"; import { grantTokenLimiter } from "@/lib/rateLimiters"; import { getClientIp } from "@/lib/rateLimit"; import { isPluginInstallEnabled, isDemo, isDemoAdmin } from "@/core/edition"; +import { getRequestOrigin } from "@/lib/origin"; const ALLOWED_REDIRECT_HOSTS = new Set([ "localhost", @@ -50,8 +51,7 @@ export async function GET(request: NextRequest) { const session = await auth(); if (!session?.user) { - // Use configured app URL to prevent Host header injection open redirects - const origin = process.env.NEXT_PUBLIC_APP_URL || process.env.APP_URL || request.nextUrl.origin; + const origin = getRequestOrigin(request); const loginUrl = new URL("/login", origin); // Construct a relative path for callback to ensure it redirects back to the identical host diff --git a/src/app/api/marketplace/install-redirect/route.ts b/src/app/api/marketplace/install-redirect/route.ts index 44625335..e7b8e3cd 100644 --- a/src/app/api/marketplace/install-redirect/route.ts +++ b/src/app/api/marketplace/install-redirect/route.ts @@ -9,6 +9,7 @@ import { installLimiter } from "@/lib/rateLimiters"; import { getClientIp } from "@/lib/rateLimit"; import { isPluginInstallEnabled, isDemo, isDemoAdmin } from "@/core/edition"; import { getVerifiedPluginIds } from "@/lib/marketplace/registryClient"; +import { getRequestOrigin } from "@/lib/origin"; const ALLOWED_REDIRECT_HOSTS = new Set([ "localhost", @@ -49,7 +50,8 @@ export async function GET(request: NextRequest) { // Not logged in — send to login with this URL as callbackUrl if (!session?.user) { - const origin = process.env.NEXT_PUBLIC_APP_URL || process.env.APP_URL || request.nextUrl.origin; + const origin = getRequestOrigin(request); + const loginUrl = new URL("/login", origin); const callbackPath = request.nextUrl.pathname + request.nextUrl.search; loginUrl.searchParams.set("callbackUrl", callbackPath); diff --git a/src/lib/origin.ts b/src/lib/origin.ts new file mode 100644 index 00000000..abd109c7 --- /dev/null +++ b/src/lib/origin.ts @@ -0,0 +1,48 @@ +import type { NextRequest } from "next/server"; + +/** + * Robustly determines the public-facing origin of a request. + * Useful for building absolute redirect URLs when running behind Docker/Coolify proxies + * where request.nextUrl.origin might incorrectly resolve to an internal 0.0.0.0 binding. + */ +export function getRequestOrigin(request: NextRequest): string { + const envOrigin = process.env.NEXT_PUBLIC_APP_URL || process.env.APP_URL || process.env.AUTH_URL; + const forwardedHost = request.headers.get("x-forwarded-host"); + const forwardedProto = request.headers.get("x-forwarded-proto") ?? "http"; + const host = request.headers.get("host"); + const nextUrlOrigin = request.nextUrl.origin; + + console.log("[Origin Debug] Headers & Env:", { + envOrigin, + forwardedHost, + forwardedProto, + host, + nextUrlOrigin, + requestUrl: request.url, + }); + + let finalOrigin = nextUrlOrigin; + + if (envOrigin) { + console.log(`[Origin Debug] Resolving to envOrigin: ${envOrigin}`); + finalOrigin = envOrigin; + } else if (forwardedHost) { + const resolved = `${forwardedProto}://${forwardedHost}`; + console.log(`[Origin Debug] Resolving to forwardedHost: ${resolved}`); + finalOrigin = resolved; + } else if (host && !host.includes("0.0.0.0")) { + const resolved = `${forwardedProto}://${host}`; + console.log(`[Origin Debug] Resolving to host header: ${resolved}`); + finalOrigin = resolved; + } else { + console.log(`[Origin Debug] Falling back to NextUrl origin: ${nextUrlOrigin}`); + } + + // Safety net: Browsers will instantly block 0.0.0.0. Replace with localhost. + if (finalOrigin.includes("0.0.0.0")) { + console.warn("[Origin Debug] FATAL: Origin resolved to 0.0.0.0. Replacing with localhost as a last resort."); + finalOrigin = finalOrigin.replace("0.0.0.0", "localhost"); + } + + return finalOrigin; +}