frontend 이미지는 nginx 공식 이미지라 root로 시작해 80번을 열고 worker를 nginx 사용자로 내린다. 그래서 Kubernetes에서 runAsNonRoot와 drop ALL을 둘 수 없다(k3s 성숙도 점검 2026-11-11, 7.5절). 운영 매니페스트는 allowPrivilegeEscalation: false만 두고 PSA restricted 경고를 낸다. runtime base를 nginxinc/nginx-unprivileged:1.27.5-alpine(digest 고정)으로 바꾼다. 예전 base와 같은 NGINX 1.27.5·Alpine이고 wget도 있어 HEALTHCHECK가 그대로 돈다. 파일을 고치는 동안만 root로 있다가 USER 101로 돌아간다. 생성되는 server 블록은 listen 8080이고, EXPOSE·HEALTHCHECK·dev-stack 포트 매핑도 8080으로 맞춘다. 버린 대안: Debian판 nginx-unprivileged. wget이 없어 HEALTHCHECK가 늘 실패한다. 80번을 그대로 두고 NET_BIND_SERVICE만 남기는 안도 버렸다. drop ALL을 못 하고 PSA restricted도 통과하지 못한다. 위험·한계: 이 이미지는 8080을 열므로 운영 매니페스트의 포트를 같이 바꿔야 한다. deploy/production/frontend-nonroot가 그 일을 하고, 기본 경로에는 넣지 않는다. dev-stack의 443·/etc/nginx/tls 부분은 이미지에 없는 파일을 쓰는 예전 상태 그대로다. 이 repo의 pnpm 게이트와 전체 docker build는 돌리지 않았다(heavy lock 대기가 길어 취소). 검증: desktop에서 이 Dockerfile의 runtime 단계를 그대로 쓰고, 빌드 단계만 운영 이미지 7a4e201의 dist와 conf(listen 8080으로 바꿈)로 대신해 이미지를 만들었다. --user 101 --cap-drop ALL --security-opt no-new-privileges --sysctl net.ipv4.ip_unprivileged_port_start=1024로 띄우면 GET /config.json 200, GET / 200, CapEff 0, NoNewPrivs 1이고, Docker health는 healthy다.
245 lines
9.0 KiB
TypeScript
245 lines
9.0 KiB
TypeScript
import { readFile, writeFile } from "node:fs/promises";
|
|
import path from "node:path";
|
|
|
|
/**
|
|
* Emits the nginx configuration the deployed frontend is served with.
|
|
*
|
|
* Generated rather than hand-written because three files already decide what it
|
|
* must say, and a copy of them would drift: `dist/tech-log-serving-contract.json`
|
|
* (which paths are SPA routes and what a miss answers with),
|
|
* `config/hosting/security-headers.json`, and `config/hosting/cache-policy.json`.
|
|
* The repository had no frontend deployment artifact at all — no Dockerfile, no
|
|
* server config — so those two hosting files described a contract nothing
|
|
* fulfilled: `dist/server.mjs` applies neither, answering `no-cache` for hashed
|
|
* assets and sending no security headers.
|
|
*
|
|
* This serves static files only. TLS and the BFF paths belong to the edge: the
|
|
* deployment's own nginx terminates HTTPS and sends `/api`, the OIDC redirect
|
|
* chain and the identity provider to the backend directly (in Kubernetes,
|
|
* Traefik does). A second proxy hop here would only add a place for the two
|
|
* routing tables to disagree.
|
|
*
|
|
* The base path comes from `VITE_ROUTER_BASE_PATH`, the same value the bundle is
|
|
* built with: served under a prefix, every route and asset lives under it too.
|
|
*/
|
|
|
|
const DIST = "dist";
|
|
const OUT = path.join(DIST, "nginx.conf");
|
|
|
|
type ServingContract = Readonly<{
|
|
publicSpaPathPatterns: readonly string[];
|
|
studioPathPrefix: string;
|
|
studioSpaPathPatterns: readonly string[];
|
|
notFound: Readonly<{ status: number; contentType: string; body: string }>;
|
|
}>;
|
|
|
|
type HostingHeaders = Readonly<{ headers: Readonly<Record<string, string>> }>;
|
|
|
|
type CachePolicy = Readonly<{
|
|
surfaces: Readonly<
|
|
Record<
|
|
string,
|
|
Readonly<{
|
|
path?: string;
|
|
pathPattern?: string;
|
|
cacheControl?: string;
|
|
securityHeaders?: boolean;
|
|
}>
|
|
>
|
|
>;
|
|
}>;
|
|
|
|
async function readJson<T>(file: string): Promise<T> {
|
|
return JSON.parse(await readFile(file, "utf8")) as T;
|
|
}
|
|
|
|
/** nginx location matching is not regex-escaped for us; only `=` exact paths are literal. */
|
|
function exactLocation(pathname: string): string {
|
|
return pathname;
|
|
}
|
|
|
|
/**
|
|
* A JS regex from the contract translated for nginx. Both use PCRE-ish syntax
|
|
* for what the contract uses (`^`, `$`, `[^/]+`, alternation), so the pattern
|
|
* carries over unchanged — asserted rather than assumed, because a pattern that
|
|
* silently failed to translate would open a Studio route to the 404 branch.
|
|
*/
|
|
function studioRegex(pattern: string): string {
|
|
// nginx uses PCRE, so anchors, character classes, alternation and plain groups
|
|
// carry over as written. Lookaround and backreferences do not translate the
|
|
// same way and would silently change which paths match, so they are refused.
|
|
if (/\(\?[=!<]|\\[1-9]/.test(pattern)) {
|
|
throw new Error(
|
|
`studio SPA pattern uses a construct this generator does not translate: ${pattern}`,
|
|
);
|
|
}
|
|
return pattern;
|
|
}
|
|
|
|
function headerDirectives(
|
|
headers: Readonly<Record<string, string>>,
|
|
indent: string,
|
|
): string {
|
|
return Object.entries(headers)
|
|
.map(([name, value]) => `${indent}add_header ${name} "${value}" always;`)
|
|
.join("\n");
|
|
}
|
|
|
|
async function main(): Promise<void> {
|
|
const contract = await readJson<ServingContract>(
|
|
path.join(DIST, "tech-log-serving-contract.json"),
|
|
);
|
|
const security = await readJson<HostingHeaders>(
|
|
"config/hosting/security-headers.json",
|
|
);
|
|
const cache = await readJson<CachePolicy>("config/hosting/cache-policy.json");
|
|
|
|
const surfaces = cache.surfaces;
|
|
const indexCache = surfaces["index"]?.cacheControl ?? "no-cache";
|
|
const configCache = surfaces["runtimeConfig"]?.cacheControl ?? "no-store";
|
|
const manifestCache = surfaces["releaseManifest"]?.cacheControl ?? "no-store";
|
|
const assetCache = surfaces["hashedAsset"]?.cacheControl ?? "no-cache";
|
|
|
|
const secure = headerDirectives(security.headers, " ");
|
|
|
|
// The bundle's own base path. `/` for a deployment at the domain root, `/dev/`
|
|
// for one served under a prefix — the routes below have to carry it or nginx
|
|
// matches paths the browser never asks for.
|
|
const rawBase = process.env["VITE_ROUTER_BASE_PATH"] ?? "/";
|
|
const basePath = rawBase.endsWith("/") ? rawBase.slice(0, -1) : rawBase;
|
|
|
|
// Regex locations now, matching the Studio half: the contract declares which
|
|
// paths the router serves, not which ones the fixture happened to contain, so
|
|
// a record published after this build is served instead of 404ed at the edge.
|
|
const publicLocations = contract.publicSpaPathPatterns
|
|
.map(
|
|
(pattern: string) => ` location ~ ^${basePath}${studioRegex(pattern).slice(1)} {
|
|
${secure}
|
|
add_header Cache-Control "${indexCache}" always;
|
|
try_files /index.html =404;
|
|
}`,
|
|
)
|
|
.join("\n\n");
|
|
|
|
const studioLocations = contract.studioSpaPathPatterns
|
|
.map(
|
|
(pattern) => ` location ~ ^${basePath}${studioRegex(pattern).slice(1)} {
|
|
${secure}
|
|
add_header Cache-Control "${indexCache}" always;
|
|
try_files /index.html =404;
|
|
}`,
|
|
)
|
|
.join("\n\n");
|
|
|
|
const conf = `# Generated by scripts/generate-nginx-config.ts — do not edit.
|
|
# Sources: dist/tech-log-serving-contract.json, config/hosting/security-headers.json,
|
|
# config/hosting/cache-policy.json
|
|
#
|
|
# Plain HTTP on purpose: the edge terminates TLS and this container is only ever
|
|
# reached from inside the deployment network. 8080, not 80: the runtime image is
|
|
# unprivileged NGINX, which cannot bind a port below 1024 without a capability.
|
|
|
|
server {
|
|
listen 8080;
|
|
server_name _;
|
|
root /usr/share/nginx/html;
|
|
index index.html;
|
|
|
|
|
|
# The bundle is small and already compressed at rest by the build; gzip here
|
|
# covers the JSON surfaces and index.html.
|
|
gzip on;
|
|
gzip_types text/css application/javascript text/javascript application/json;
|
|
gzip_min_length 1024;
|
|
|
|
# Static surfaces, per config/hosting/cache-policy.json
|
|
# ---------------------------------------------------------------------------
|
|
location = ${basePath}/config.json {
|
|
alias /usr/share/nginx/html/config.json;
|
|
${secure}
|
|
add_header Cache-Control "${configCache}" always;
|
|
}
|
|
|
|
location = ${basePath}/release-manifest.json {
|
|
alias /usr/share/nginx/html/release-manifest.json;
|
|
${secure}
|
|
add_header Cache-Control "${manifestCache}" always;
|
|
}
|
|
|
|
# Content-hashed filenames, so the long TTL is safe and revalidation is waste.
|
|
location ${basePath}/assets/ {
|
|
# alias, not root + URI: under a base path the request is /dev/assets/x.js
|
|
# while the file is dist/assets/x.js, so root would look for
|
|
# dist/dev/assets/x.js and answer 404 for every script on the page.
|
|
alias /usr/share/nginx/html/assets/;
|
|
add_header Cache-Control "${assetCache}" always;
|
|
}
|
|
|
|
# Source maps are not published (cache-policy sourceMap.public = false).
|
|
location ~ \\.map$ {
|
|
return 404;
|
|
}
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# SPA routes. Enumerated from the serving contract rather than a catch-all:
|
|
# a path that is not a real route answers 404 instead of a 200 shell, which is
|
|
# what tells a crawler the difference.
|
|
# ---------------------------------------------------------------------------
|
|
${publicLocations}
|
|
|
|
${studioLocations}
|
|
|
|
location = ${basePath}/favicon.svg {
|
|
alias /usr/share/nginx/html/favicon.svg;
|
|
add_header Cache-Control "${assetCache}" always;
|
|
}
|
|
|
|
# 크롤러가 처음 찾는 파일이다. 여기 없으면 SPA 폴백이 index.html 을 주고,
|
|
# 크롤러는 그것을 규칙으로 읽을 수 없어 결국 아무 규칙도 없는 것과 같아진다.
|
|
location = ${basePath}/robots.txt {
|
|
alias /usr/share/nginx/html/robots.txt;
|
|
default_type text/plain;
|
|
add_header Cache-Control "${indexCache}" always;
|
|
}
|
|
|
|
location = ${basePath}/media/ {
|
|
return 404;
|
|
}
|
|
|
|
location ${basePath}/media/ {
|
|
alias /usr/share/nginx/html/media/;
|
|
add_header Cache-Control "${assetCache}" always;
|
|
}
|
|
|
|
# 이 배포가 서비스하는 라우트가 아닌 주소.
|
|
#
|
|
# 상태 코드는 404 그대로 둔다 — 크롤러와 우리에게 링크가 깨졌다고 말해 주는 것이 그것이고,
|
|
# 200 껍데기를 주면 그 신호가 사라진다. 다만 본문은 앱을 준다. 예전에는 nginx 의 맨
|
|
# "Not Found" 가 흰 화면으로 나가서, 오타 링크 하나에 헤더도 내비도 없는 막다른 길이 됐다.
|
|
# 앱에는 path "*" 로 선언된 404 라우트가 이미 있고 청크도 빌드되는데 닿을 길이 없었다.
|
|
#
|
|
# error_page 404 @not_found 는 "=" 없이 쓰면 원래 상태 코드를 유지한다.
|
|
error_page 404 @not_found;
|
|
|
|
location @not_found {
|
|
${secure}
|
|
add_header Cache-Control "${indexCache}" always;
|
|
# index.html 이 없으면 여기서 끝난다. recursive_error_pages 는 기본이 off 라 되돌지 않는다.
|
|
try_files /index.html =404;
|
|
}
|
|
|
|
location / {
|
|
return ${contract.notFound.status};
|
|
}
|
|
}
|
|
`;
|
|
|
|
await writeFile(OUT, conf, "utf8");
|
|
process.stdout.write(
|
|
`nginx config: ${OUT} (${contract.publicSpaPathPatterns.length} public routes, ` +
|
|
`${contract.studioSpaPathPatterns.length} studio patterns)\n`,
|
|
);
|
|
}
|
|
|
|
await main();
|