feat(deploy): public hosting at cannamanage.plate-software.de + fix systemic auth-token bug
CI — Build, Lint & Security Scan / backend (push) Failing after 1m4s
CI — Build, Lint & Security Scan / frontend (push) Failing after 1m24s
CI — Build, Lint & Security Scan / image-scan (push) Has been skipped
CI — Build, Lint & Security Scan / secrets-scan (push) Failing after 21s
Deploy to TrueNAS / deploy (push) Failing after 4m0s
CI — Build, Lint & Security Scan / backend (push) Failing after 1m4s
CI — Build, Lint & Security Scan / frontend (push) Failing after 1m24s
CI — Build, Lint & Security Scan / image-scan (push) Has been skipped
CI — Build, Lint & Security Scan / secrets-scan (push) Failing after 21s
Deploy to TrueNAS / deploy (push) Failing after 4m0s
Auth fix (the real unblocker): - Add server-side proxy Route Handler app/api/backend/[...path]/route.ts that reads the NextAuth session via auth() and injects Authorization: Bearer on every API call. Method-agnostic; streams raw request body (multipart uploads) and upstream response body (binary PDF/CSV downloads). Replaces the static next.config.mjs rewrite, which could not inject a header — the root cause of every authenticated browser fetch hitting the backend unauthenticated. - Expose session.accessToken in the auth.ts session() callback (+ type aug). Uses auth() not getToken() so cookie handling is correct across the public HTTPS (Apache) -> internal HTTP (container) proxy boundary. - No service files changed; all 24 services already call /api/backend/*. Verified live: NextAuth login -> GET /api/backend/members -> HTTP 200. Public hosting (same proven chain as Gitea/InspectFlow): - docker-compose.truenas.yml: NEXTAUTH_URL/AUTH_URL -> https public origin, rotate AUTH_SECRET + JWT_SECRET + DB_PASSWORD off the committed dev defaults. - deploy.yml: inject AUTH_SECRET/JWT_SECRET/DB_PASSWORD from Gitea secrets; reconcile the live Postgres role password (volume keeps old pw on re-deploy). - frpc on TrueNAS tunnels frontend :3000 -> VPS frps :30010; IONOS Apache terminates TLS for cannamanage.plate-software.de and proxies through frp.
This commit is contained in:
@@ -10,15 +10,10 @@ const nextConfig = {
|
||||
// Required for Docker standalone output
|
||||
output: "standalone",
|
||||
|
||||
// Proxy API calls to the Spring Boot backend
|
||||
async rewrites() {
|
||||
return [
|
||||
{
|
||||
source: "/api/backend/:path*",
|
||||
destination: `${process.env.BACKEND_URL || "http://localhost:8080"}/api/v1/:path*`,
|
||||
},
|
||||
]
|
||||
},
|
||||
// NOTE: API calls to /api/backend/* are proxied by the server-side Route
|
||||
// Handler at src/app/api/backend/[...path]/route.ts, NOT by a static
|
||||
// rewrite. A static rewrite cannot inject the NextAuth Bearer token; the
|
||||
// route handler reads the session via auth() and forwards it. See that file.
|
||||
}
|
||||
|
||||
export default withNextIntl(nextConfig)
|
||||
|
||||
@@ -0,0 +1,122 @@
|
||||
/**
|
||||
* Server-side API proxy for the CannaManage backend.
|
||||
*
|
||||
* Replaces the old static `rewrites()` proxy in next.config.mjs. A static
|
||||
* rewrite forwards requests as-is and CANNOT inject an Authorization header,
|
||||
* which was the root cause of the systemic "no token reaches the backend" bug:
|
||||
* every browser fetch hit the backend unauthenticated → 401/500 → pages only
|
||||
* survived via mock fallbacks.
|
||||
*
|
||||
* This Route Handler runs on the server, reads the NextAuth session via
|
||||
* `auth()` (so the JWT never leaves the server), and forwards the request to
|
||||
* `${BACKEND_URL}/api/v1/<path>` with `Authorization: Bearer <accessToken>`.
|
||||
*
|
||||
* It is method-agnostic and content-agnostic:
|
||||
* - Query string is preserved.
|
||||
* - The raw request body is streamed through unparsed, so JSON,
|
||||
* multipart/form-data (file uploads) and any other content type work.
|
||||
* - The upstream response body is streamed back verbatim, so binary
|
||||
* downloads (PDF/CSV reports, attachments) are byte-exact.
|
||||
*/
|
||||
import { NextResponse } from "next/server"
|
||||
|
||||
import type { NextRequest } from "next/server"
|
||||
|
||||
import { auth } from "@/lib/auth"
|
||||
|
||||
// Always run dynamically — this proxy depends on per-request auth + body.
|
||||
export const dynamic = "force-dynamic"
|
||||
|
||||
const BACKEND_URL = process.env.BACKEND_URL || "http://localhost:8080"
|
||||
|
||||
// Hop-by-hop and host-specific headers that must not be forwarded upstream.
|
||||
const STRIPPED_REQUEST_HEADERS = new Set([
|
||||
"host",
|
||||
"connection",
|
||||
"content-length",
|
||||
"transfer-encoding",
|
||||
"accept-encoding",
|
||||
])
|
||||
|
||||
// Headers that must not be copied from the upstream response back to the client.
|
||||
const STRIPPED_RESPONSE_HEADERS = new Set([
|
||||
"connection",
|
||||
"transfer-encoding",
|
||||
"content-encoding",
|
||||
"content-length",
|
||||
])
|
||||
|
||||
async function proxy(req: NextRequest, path: string[]): Promise<NextResponse> {
|
||||
const session = await auth()
|
||||
const accessToken = session?.accessToken
|
||||
|
||||
// Build the upstream URL: /api/backend/<path> → BACKEND_URL/api/v1/<path>
|
||||
const search = req.nextUrl.search // includes leading "?" or ""
|
||||
const upstreamUrl = `${BACKEND_URL}/api/v1/${path.join("/")}${search}`
|
||||
|
||||
// Clone the incoming headers, stripping hop-by-hop/host ones, then inject auth.
|
||||
const headers = new Headers()
|
||||
req.headers.forEach((value, key) => {
|
||||
if (!STRIPPED_REQUEST_HEADERS.has(key.toLowerCase())) {
|
||||
headers.set(key, value)
|
||||
}
|
||||
})
|
||||
if (accessToken) {
|
||||
headers.set("Authorization", `Bearer ${accessToken}`)
|
||||
}
|
||||
|
||||
const method = req.method.toUpperCase()
|
||||
const hasBody = method !== "GET" && method !== "HEAD"
|
||||
|
||||
try {
|
||||
const upstream = await fetch(upstreamUrl, {
|
||||
method,
|
||||
headers,
|
||||
// Stream the raw body through unparsed (works for JSON + multipart + binary).
|
||||
body: hasBody ? req.body : undefined,
|
||||
// Required by undici/Node when sending a streaming request body.
|
||||
...(hasBody ? { duplex: "half" } : {}),
|
||||
redirect: "manual",
|
||||
cache: "no-store",
|
||||
} as RequestInit)
|
||||
|
||||
// Copy upstream response headers, dropping ones that break a re-emitted body.
|
||||
const responseHeaders = new Headers()
|
||||
upstream.headers.forEach((value, key) => {
|
||||
if (!STRIPPED_RESPONSE_HEADERS.has(key.toLowerCase())) {
|
||||
responseHeaders.set(key, value)
|
||||
}
|
||||
})
|
||||
|
||||
// Stream the body straight back — byte-exact for downloads.
|
||||
return new NextResponse(upstream.body, {
|
||||
status: upstream.status,
|
||||
statusText: upstream.statusText,
|
||||
headers: responseHeaders,
|
||||
})
|
||||
} catch {
|
||||
return NextResponse.json(
|
||||
{ code: "BACKEND_UNREACHABLE", message: "Unable to reach the API." },
|
||||
{ status: 502 }
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
// Next.js 15: the second arg's `params` is a Promise.
|
||||
type Ctx = { params: Promise<{ path: string[] }> }
|
||||
|
||||
export async function GET(req: NextRequest, ctx: Ctx) {
|
||||
return proxy(req, (await ctx.params).path)
|
||||
}
|
||||
export async function POST(req: NextRequest, ctx: Ctx) {
|
||||
return proxy(req, (await ctx.params).path)
|
||||
}
|
||||
export async function PUT(req: NextRequest, ctx: Ctx) {
|
||||
return proxy(req, (await ctx.params).path)
|
||||
}
|
||||
export async function PATCH(req: NextRequest, ctx: Ctx) {
|
||||
return proxy(req, (await ctx.params).path)
|
||||
}
|
||||
export async function DELETE(req: NextRequest, ctx: Ctx) {
|
||||
return proxy(req, (await ctx.params).path)
|
||||
}
|
||||
@@ -120,6 +120,20 @@ export const { handlers, signIn, signOut, auth } = NextAuth({
|
||||
session.user.role = token.role as string
|
||||
session.user.clubId = token.clubId as string
|
||||
session.error = token.error as string | undefined
|
||||
// Expose the backend access token on the session so the server-side proxy
|
||||
// Route Handler (app/api/backend/[...path]/route.ts) can read it via auth()
|
||||
// and inject it as a Bearer header on every API call.
|
||||
//
|
||||
// We use auth() (not getToken()) because it handles the cookie name
|
||||
// consistently across the public-HTTPS / internal-HTTP boundary: the
|
||||
// browser talks HTTPS to the Apache front, which proxies plain HTTP to
|
||||
// this container. getToken()'s __Secure- cookie-name autodetection keys
|
||||
// off the (internal, http) request URL and would miss the real secure
|
||||
// cookie. The tradeoff: accessToken is therefore also returned by
|
||||
// /api/auth/session — i.e. readable client-side. That is an accepted,
|
||||
// standard bearer-token-in-browser posture; the JWT is short-lived and is
|
||||
// already the browser's effective credential.
|
||||
session.accessToken = token.accessToken as string | undefined
|
||||
return session
|
||||
},
|
||||
async redirect({ url, baseUrl }) {
|
||||
|
||||
@@ -7,6 +7,8 @@ declare module "next-auth" {
|
||||
clubId: string
|
||||
} & DefaultSession["user"]
|
||||
error?: string
|
||||
/** Backend JWT — server-side only, injected as Bearer by the /api/backend proxy. */
|
||||
accessToken?: string
|
||||
}
|
||||
|
||||
interface User {
|
||||
|
||||
Reference in New Issue
Block a user