feat: V2 microservices stack — backend services, gateway, JWT auth
Add full V2 architecture: identity, content, studio (.NET 10) and file, render, notification, gateway (Go) services with vendored deps, plus DB migrations, event/API contracts, and an init-db script. Wire the Next.js frontend to the gateway: server-side JWT auth routes (login/register/refresh/logout/me), gateway fetch helper, and session/ cookie/jwt helpers under src/lib. Containerize the stack via docker-compose.v2.yml and per-service Dockerfiles. Base images resolve through a Nexus mirror (Docker Hub) and MCR directly; npm/NuGet pull from Nexus groups. Self-host fonts via next/font/local to avoid Google Fonts (geo-blocked). Add CI workflow and ignore .env.v2, *.stackdump, and .NET bin/obj. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,33 @@
|
||||
/**
|
||||
* Server-side helper for calling the FlatRender V2 API gateway.
|
||||
*
|
||||
* The gateway is the single public entrypoint to all microservices. All .NET service
|
||||
* payloads are snake_case, so callers send/receive snake_case JSON.
|
||||
*
|
||||
* Local dev: http://localhost:8088 (see GATEWAY_PORT in .env.v2).
|
||||
* In Docker: set API_GATEWAY_URL=http://gateway:8080.
|
||||
*/
|
||||
const GATEWAY_URL = (process.env.API_GATEWAY_URL ?? "http://localhost:8088").replace(
|
||||
/\/$/,
|
||||
""
|
||||
);
|
||||
|
||||
export function gatewayUrl(path: string): string {
|
||||
return `${GATEWAY_URL}${path.startsWith("/") ? path : `/${path}`}`;
|
||||
}
|
||||
|
||||
export async function gatewayFetch(
|
||||
path: string,
|
||||
init?: RequestInit
|
||||
): Promise<Response> {
|
||||
return fetch(gatewayUrl(path), {
|
||||
...init,
|
||||
// Never cache auth/data calls that flow through here.
|
||||
cache: "no-store",
|
||||
headers: {
|
||||
Accept: "application/json",
|
||||
"Content-Type": "application/json",
|
||||
...(init?.headers ?? {}),
|
||||
},
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
// Auth constants shared across route handlers, middleware, and server helpers.
|
||||
|
||||
/** httpOnly cookie holding the short-lived (15 min) Identity access JWT. */
|
||||
export const ACCESS_TOKEN_COOKIE = "fr_access";
|
||||
|
||||
/** httpOnly cookie holding the long-lived (30 day) rotating refresh token. */
|
||||
export const REFRESH_TOKEN_COOKIE = "fr_refresh";
|
||||
|
||||
/**
|
||||
* Tenant the public site authenticates against. FlatRender's own users live in the
|
||||
* default tenant (slug `flatrender`). Overridable for white-label deployments.
|
||||
*/
|
||||
export const DEFAULT_TENANT_SLUG =
|
||||
process.env.NEXT_PUBLIC_TENANT_SLUG ?? "flatrender";
|
||||
@@ -0,0 +1,33 @@
|
||||
import { type NextResponse } from "next/server";
|
||||
|
||||
import { ACCESS_TOKEN_COOKIE, REFRESH_TOKEN_COOKIE } from "@/lib/auth/constants";
|
||||
|
||||
const REFRESH_MAX_AGE = 60 * 60 * 24 * 30; // 30 days, matches Identity refresh TTL
|
||||
|
||||
/** Write the Identity access + refresh tokens as httpOnly cookies on a response. */
|
||||
export function setAuthCookies(
|
||||
res: NextResponse,
|
||||
accessToken: string,
|
||||
refreshToken: string,
|
||||
accessExpiresIn: number
|
||||
): NextResponse {
|
||||
const secure = process.env.NODE_ENV === "production";
|
||||
const base = { httpOnly: true, sameSite: "lax", secure, path: "/" } as const;
|
||||
res.cookies.set(ACCESS_TOKEN_COOKIE, accessToken, {
|
||||
...base,
|
||||
maxAge: accessExpiresIn,
|
||||
});
|
||||
res.cookies.set(REFRESH_TOKEN_COOKIE, refreshToken, {
|
||||
...base,
|
||||
maxAge: REFRESH_MAX_AGE,
|
||||
});
|
||||
return res;
|
||||
}
|
||||
|
||||
/** Expire both auth cookies (logout / failed refresh). */
|
||||
export function clearAuthCookies(res: NextResponse): NextResponse {
|
||||
for (const name of [ACCESS_TOKEN_COOKIE, REFRESH_TOKEN_COOKIE]) {
|
||||
res.cookies.set(name, "", { httpOnly: true, path: "/", maxAge: 0 });
|
||||
}
|
||||
return res;
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
// Edge-safe JWT payload decoding. We never verify the signature here — these helpers
|
||||
// only read claims from our own httpOnly cookie (presence/expiry for route guards).
|
||||
// The gateway verifies the signature on every real API call.
|
||||
|
||||
export interface JwtClaims {
|
||||
sub?: string;
|
||||
email?: string;
|
||||
tenant_id?: string;
|
||||
tenant_slug?: string;
|
||||
is_admin?: string | boolean;
|
||||
is_tenant_admin?: string | boolean;
|
||||
exp?: number;
|
||||
[key: string]: unknown;
|
||||
}
|
||||
|
||||
function base64UrlDecode(input: string): string {
|
||||
const b64 = input.replace(/-/g, "+").replace(/_/g, "/");
|
||||
const pad = b64.length % 4 === 0 ? "" : "=".repeat(4 - (b64.length % 4));
|
||||
const raw =
|
||||
typeof atob === "function"
|
||||
? atob(b64 + pad)
|
||||
: Buffer.from(b64 + pad, "base64").toString("binary");
|
||||
// Reinterpret the binary string as UTF-8 so non-ASCII claims (names) survive.
|
||||
return decodeURIComponent(
|
||||
raw
|
||||
.split("")
|
||||
.map((c) => "%" + ("00" + c.charCodeAt(0).toString(16)).slice(-2))
|
||||
.join("")
|
||||
);
|
||||
}
|
||||
|
||||
export function decodeJwt(token: string): JwtClaims | null {
|
||||
try {
|
||||
const part = token.split(".")[1];
|
||||
if (!part) return null;
|
||||
return JSON.parse(base64UrlDecode(part)) as JwtClaims;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/** True when the token is missing an exp or is at/past expiry. */
|
||||
export function isJwtExpired(claims: JwtClaims | null): boolean {
|
||||
if (!claims?.exp) return true;
|
||||
return claims.exp * 1000 <= Date.now();
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
import { cookies } from "next/headers";
|
||||
|
||||
import { gatewayFetch } from "@/lib/api/gateway";
|
||||
import { ACCESS_TOKEN_COOKIE } from "@/lib/auth/constants";
|
||||
import { decodeJwt, isJwtExpired, type JwtClaims } from "@/lib/auth/jwt";
|
||||
|
||||
export interface Session {
|
||||
userId: string;
|
||||
email?: string;
|
||||
tenantId?: string;
|
||||
isAdmin: boolean;
|
||||
claims: JwtClaims;
|
||||
}
|
||||
|
||||
/** Raw access token from the httpOnly cookie (for proxying to the gateway). */
|
||||
export async function getAccessToken(): Promise<string | null> {
|
||||
const store = await cookies();
|
||||
return store.get(ACCESS_TOKEN_COOKIE)?.value ?? null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Decode the current session from the access-token cookie. Returns null when there is
|
||||
* no token, it is malformed, or it has expired. Use in server components / layouts to
|
||||
* guard rendering; the gateway is still the authority on every API call.
|
||||
*/
|
||||
export async function getSession(): Promise<Session | null> {
|
||||
const token = await getAccessToken();
|
||||
if (!token) return null;
|
||||
const claims = decodeJwt(token);
|
||||
if (!claims || isJwtExpired(claims) || !claims.sub) return null;
|
||||
return {
|
||||
userId: String(claims.sub),
|
||||
email: claims.email ? String(claims.email) : undefined,
|
||||
tenantId: claims.tenant_id ? String(claims.tenant_id) : undefined,
|
||||
isAdmin: String(claims.is_admin) === "true",
|
||||
claims,
|
||||
};
|
||||
}
|
||||
|
||||
export interface IdentityUser {
|
||||
id: string;
|
||||
email?: string | null;
|
||||
full_name?: string | null;
|
||||
avatar_url?: string | null;
|
||||
is_admin?: boolean;
|
||||
[key: string]: unknown;
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetch the full current-user profile from Identity (`/v1/users/me`) using the access
|
||||
* cookie. Returns null when signed out or the token is rejected — use this as the
|
||||
* authoritative server-side guard (it validates the token against the service).
|
||||
*/
|
||||
export async function getCurrentUser(): Promise<IdentityUser | null> {
|
||||
const token = await getAccessToken();
|
||||
if (!token) return null;
|
||||
const res = await gatewayFetch("/v1/users/me", {
|
||||
headers: { Authorization: `Bearer ${token}` },
|
||||
});
|
||||
if (!res.ok) return null;
|
||||
return (await res.json().catch(() => null)) as IdentityUser | null;
|
||||
}
|
||||
Reference in New Issue
Block a user