feat(apps): call the API through a same-origin /api rewrite

- next.config rewrites /api/:path* to API_INTERNAL_ORIGIN, with a 120 s proxy timeout for uploads; NEXT_PUBLIC_API_ORIGIN is gone.
- The browser HTTP base is /api/v1; media, avatars and uploads load through /api (market env `apiBaseUrl`), so private media gets the session cookie.
- toApiUrl keeps a narrow rule for uploads stored with a host before the back end stored paths.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Amiram_se 2026-10-06 21:47:18 +04:00
parent 0e8347d6d3
commit ed6ddc05b1
23 changed files with 166 additions and 100 deletions

View File

@ -1,13 +1,13 @@
# Copy to .env.local. Public variables are inlined into the browser bundle: never put a secret in one.
# The API's public origin; routes live under /v1, uploads under /files.
NEXT_PUBLIC_API_ORIGIN=http://localhost:3000
NEXT_PUBLIC_SITE_URL=http://localhost:3002
NEXT_PUBLIC_SITE_URL=http://localhost:7001
NEXT_PUBLIC_BALE_HANDLE=lumina_support
NEXT_PUBLIC_TELEGRAM_HANDLE=lumina_support
NEXT_PUBLIC_SUPPORT_HOURS=شنبه تا پنجشنبه، ۹ تا ۱۸
# Server only: the API origin from inside the deployment network.
# Server only: the gateway's origin from inside the deployment network. Server requests go
# there, and so does the browser's /api proxy (next.config rewrite, fixed at build time).
API_INTERNAL_ORIGIN=http://localhost:3000
# Only for steps that run without the real env (lint, type-check, image build).
# Only for steps that run without the real env (lint, type-check). A build still needs
# API_INTERNAL_ORIGIN: the /api rewrite keeps the value it was built with.
SKIP_ENV_VALIDATION=false

View File

@ -2,6 +2,9 @@ import { withFontCopy } from '@lumina/island/tools/font-copy-plugin';
import { withIconSprite } from '@lumina/island/tools/icon-sprite-plugin';
import type { NextConfig } from 'next';
import { API_PROXY_PATH, API_PROXY_TIMEOUT_MS } from './src/constants';
import { apiInternalUrl } from './src/env/env.config';
// Fonts and the icon sprite keep fixed names; a changed font gets a new name, and the sprite a new
// ?v= (0011, 0012). Next serves public/ with max-age=0, so without this every visit asks for them again.
const immutable = [
@ -9,6 +12,8 @@ const immutable = [
];
const nextConfig: NextConfig = {
// The `/api` proxy's wait for the gateway (0018); uploads outlast Next.js's 30-second default.
experimental: { proxyTimeout: API_PROXY_TIMEOUT_MS },
// Workspace packages export TypeScript source, so Next.js compiles them.
transpilePackages: [
'@lumina/market',
@ -20,8 +25,16 @@ const nextConfig: NextConfig = {
// `/@{username}` is the public channel URL. A folder named `@…` is a
// parallel-route slot in the App Router, so the routes live under
// `channels/[username]` and the public URL is rewritten onto them.
//
// The browser calls the API on this site's origin (`/api/v1/…`, `/api/files/…`), and the API
// calls are proxied to the gateway, so there is no CORS and the session cookies are this site's
// (0018).
async rewrites() {
return [
{
source: `${API_PROXY_PATH}/:path*`,
destination: `${apiInternalUrl()}/:path*`,
},
{
source: '/@:username/:path*',
destination: '/channels/:username/:path*',

View File

@ -5,22 +5,23 @@ import { mapApiErrorBody } from '@lumina/market/app/http';
import { setEnv as setMarketEnv } from '@lumina/market/env';
import { AUTH_ENDPOINTS, AUTH_EVENTS } from '@lumina/market/features/auth';
import { API_VERSION_PATH } from '../constants';
import { API_PROXY_PATH, API_VERSION_PATH } from '../constants';
import { clientEnv } from '../env';
import { ERROR_HANDLER_CONFIG } from './error-reporting';
// Fills the client module graph with public values only, before client components render (during
// SSR and in the browser). Idempotent: safe to run again.
setMarketEnv({
apiOrigin: clientEnv.NEXT_PUBLIC_API_ORIGIN,
apiBaseUrl: API_PROXY_PATH,
baleHandle: clientEnv.NEXT_PUBLIC_BALE_HANDLE,
telegramHandle: clientEnv.NEXT_PUBLIC_TELEGRAM_HANDLE,
supportHours: clientEnv.NEXT_PUBLIC_SUPPORT_HOURS,
});
// The session lives in HttpOnly cookies the browser sends itself. A 401 runs one refresh for the
// whole app; when that fails the session is over and the shell signs the user out.
// The browser calls the API on this site's origin, proxied to the gateway (0018). The session
// lives in HttpOnly cookies the browser sends itself. A 401 runs one refresh for the whole app;
// when that fails the session is over and the shell signs the user out.
http.configure({
baseUrl: `${clientEnv.NEXT_PUBLIC_API_ORIGIN}${API_VERSION_PATH}`,
baseUrl: `${API_PROXY_PATH}${API_VERSION_PATH}`,
refresh: {
endpoint: AUTH_ENDPOINTS.refresh,
onFailure: () =>

View File

@ -7,14 +7,18 @@ import { mapApiErrorBody } from '@lumina/market/app/http';
import { setEnv as setMarketEnv } from '@lumina/market/env';
import { cookies } from 'next/headers';
import { API_VERSION_PATH, FORWARDED_COOKIES } from '../constants';
import {
API_PROXY_PATH,
API_VERSION_PATH,
FORWARDED_COOKIES,
} from '../constants';
import { clientEnv } from '../env';
import { serverEnv } from '../env/server';
import { ERROR_HANDLER_CONFIG } from './error-reporting';
// Fills the server module graph once, before rendering. Idempotent: safe to run again.
setMarketEnv({
apiOrigin: clientEnv.NEXT_PUBLIC_API_ORIGIN,
apiBaseUrl: API_PROXY_PATH,
baleHandle: clientEnv.NEXT_PUBLIC_BALE_HANDLE,
telegramHandle: clientEnv.NEXT_PUBLIC_TELEGRAM_HANDLE,
supportHours: clientEnv.NEXT_PUBLIC_SUPPORT_HOURS,

View File

@ -1,2 +1,16 @@
/** Every gateway route except `/files/*` sits under this prefix. */
export const API_VERSION_PATH = '/v1';
/**
* Where the browser reaches the API: this site's own origin, under this path. next.config.ts
* rewrites it to the gateway (`API_INTERNAL_ORIGIN`), so no browser request is cross-origin and
* the session cookies belong to this site (0018). The server render calls the gateway directly.
*/
export const API_PROXY_PATH = '/api';
/**
* How long the `/api` proxy waits for the gateway. Next.js stops at 30 seconds by default; an
* upload (two 5 MB ID images, post media) on a slow connection takes longer, and the HTTP lib
* sets no timeout for uploads.
*/
export const API_PROXY_TIMEOUT_MS = 120_000;

View File

@ -1,2 +1,2 @@
export { API_VERSION_PATH } from './api';
export { API_PROXY_PATH, API_PROXY_TIMEOUT_MS, API_VERSION_PATH } from './api';
export { FORWARDED_COOKIES } from './cookies';

View File

@ -1,31 +1,19 @@
import { createClientEnv } from '@lumina/libs/env';
import * as v from 'valibot';
import { isOrigin } from './is-origin';
const required = v.pipe(v.string(), v.nonEmpty());
const url = v.pipe(v.string(), v.url());
/** Scheme and host only: request paths and media URLs are joined to it, so `https://api.lumina.ir/` would give `//v1`. */
const origin = v.pipe(
url,
v.check(
isOrigin,
'Must be an origin such as https://api.lumina.ir, with no path or trailing slash.',
),
);
/** Public variables, inlined into the browser bundle. Next.js inlines only literal reads. */
export const clientEnv = createClientEnv({
prefix: 'NEXT_PUBLIC_',
schema: {
NEXT_PUBLIC_API_ORIGIN: origin,
NEXT_PUBLIC_SITE_URL: url,
NEXT_PUBLIC_BALE_HANDLE: required,
NEXT_PUBLIC_TELEGRAM_HANDLE: required,
NEXT_PUBLIC_SUPPORT_HOURS: required,
},
runtimeEnv: {
NEXT_PUBLIC_API_ORIGIN: process.env.NEXT_PUBLIC_API_ORIGIN,
NEXT_PUBLIC_SITE_URL: process.env.NEXT_PUBLIC_SITE_URL,
NEXT_PUBLIC_BALE_HANDLE: process.env.NEXT_PUBLIC_BALE_HANDLE,
NEXT_PUBLIC_TELEGRAM_HANDLE: process.env.NEXT_PUBLIC_TELEGRAM_HANDLE,

16
apps/bear/src/env/env.config.ts vendored Normal file
View File

@ -0,0 +1,16 @@
import { origin } from '@lumina/libs/env';
import * as v from 'valibot';
/**
* For next.config.ts only: the gateway the `/api` rewrite proxies to. No `server-only` here, as
* the config loads outside React. `next build` writes rewrites into its output, so the value is
* the one at build time (0018) and `SKIP_ENV_VALIDATION` can't skip it: a build without it fails
* here, rather than shipping a proxy to the wrong gateway.
*/
export function apiInternalUrl(): string {
const result = v.safeParse(origin, process.env.API_INTERNAL_ORIGIN);
if (result.success) return result.output;
throw new Error(
`API_INTERNAL_ORIGIN is needed to build: next.config rewrites /api to it and next build keeps the value (0018). ${result.issues[0].message}`,
);
}

View File

@ -1,22 +1,13 @@
import 'server-only';
import { origin } from '@lumina/libs/env';
import { createServerEnv } from '@lumina/libs/env/server';
import * as v from 'valibot';
import { isOrigin } from './is-origin';
/** Server variables; only server code imports them, through `env/server`. */
export const serverEnv = createServerEnv({
schema: {
// Scheme and host only, as NEXT_PUBLIC_API_ORIGIN: request paths are joined to it.
API_INTERNAL_ORIGIN: v.pipe(
v.string(),
v.url(),
v.check(
isOrigin,
'Must be an origin such as http://gateway:3000, with no path or trailing slash.',
),
),
/** The gateway from inside the deployment network: server requests and the `/api` proxy. */
API_INTERNAL_ORIGIN: origin,
},
runtimeEnv: process.env,
skipValidation: process.env.SKIP_ENV_VALIDATION === 'true',

View File

@ -1,8 +0,0 @@
/** `https://api.lumina.ir`, not `https://api.lumina.ir/` or `https://api.lumina.ir/v1`. */
export function isOrigin(value: string): boolean {
try {
return new URL(value).origin === value;
} catch {
return false;
}
}

View File

@ -1,13 +1,13 @@
# Copy to .env.local. Public variables are inlined into the browser bundle: never put a secret in one.
# The API's public origin; routes live under /v1, uploads under /files.
NEXT_PUBLIC_API_ORIGIN=http://localhost:3000
NEXT_PUBLIC_SITE_URL=http://localhost:3001
NEXT_PUBLIC_SITE_URL=http://localhost:7000
NEXT_PUBLIC_BALE_HANDLE=lumina_support
NEXT_PUBLIC_TELEGRAM_HANDLE=lumina_support
NEXT_PUBLIC_SUPPORT_HOURS=شنبه تا پنجشنبه، ۹ تا ۱۸
# Server only: the API origin from inside the deployment network.
# Server only: the gateway's origin from inside the deployment network. Server requests go
# there, and so does the browser's /api proxy (next.config rewrite, fixed at build time).
API_INTERNAL_ORIGIN=http://localhost:3000
# Only for steps that run without the real env (lint, type-check, image build).
# Only for steps that run without the real env (lint, type-check). A build still needs
# API_INTERNAL_ORIGIN: the /api rewrite keeps the value it was built with.
SKIP_ENV_VALIDATION=false

View File

@ -2,6 +2,9 @@ import { withFontCopy } from '@lumina/island/tools/font-copy-plugin';
import { withIconSprite } from '@lumina/island/tools/icon-sprite-plugin';
import type { NextConfig } from 'next';
import { API_PROXY_PATH, API_PROXY_TIMEOUT_MS } from './src/constants';
import { apiInternalUrl } from './src/env/env.config';
// Fonts and the icon sprite keep fixed names; a changed font gets a new name, and the sprite a new
// ?v= (0011, 0012). Next serves public/ with max-age=0, so without this every visit asks for them again.
const immutable = [
@ -9,6 +12,8 @@ const immutable = [
];
const nextConfig: NextConfig = {
// The `/api` proxy's wait for the gateway (0018); uploads outlast Next.js's 30-second default.
experimental: { proxyTimeout: API_PROXY_TIMEOUT_MS },
// Workspace packages export TypeScript source, so Next.js compiles them.
transpilePackages: [
'@lumina/market',
@ -20,8 +25,16 @@ const nextConfig: NextConfig = {
// `/@{username}` is the public channel URL. A folder named `@…` is a
// parallel-route slot in the App Router, so the routes live under
// `channels/[username]` and the public URL is rewritten onto them.
//
// The browser calls the API on this site's origin (`/api/v1/…`, `/api/files/…`), and the API
// calls are proxied to the gateway, so there is no CORS and the session cookies are this site's
// (0018).
async rewrites() {
return [
{
source: `${API_PROXY_PATH}/:path*`,
destination: `${apiInternalUrl()}/:path*`,
},
{
source: '/@:username/:path*',
destination: '/channels/:username/:path*',

View File

@ -5,22 +5,23 @@ import { mapApiErrorBody } from '@lumina/market/app/http';
import { setEnv as setMarketEnv } from '@lumina/market/env';
import { AUTH_ENDPOINTS, AUTH_EVENTS } from '@lumina/market/features/auth';
import { API_VERSION_PATH } from '../constants';
import { API_PROXY_PATH, API_VERSION_PATH } from '../constants';
import { clientEnv } from '../env';
import { ERROR_HANDLER_CONFIG } from './error-reporting';
// Fills the client module graph with public values only, before client components render (during
// SSR and in the browser). Idempotent: safe to run again.
setMarketEnv({
apiOrigin: clientEnv.NEXT_PUBLIC_API_ORIGIN,
apiBaseUrl: API_PROXY_PATH,
baleHandle: clientEnv.NEXT_PUBLIC_BALE_HANDLE,
telegramHandle: clientEnv.NEXT_PUBLIC_TELEGRAM_HANDLE,
supportHours: clientEnv.NEXT_PUBLIC_SUPPORT_HOURS,
});
// The session lives in HttpOnly cookies the browser sends itself. A 401 runs one refresh for the
// whole app; when that fails the session is over and the shell signs the user out.
// The browser calls the API on this site's origin, proxied to the gateway (0018). The session
// lives in HttpOnly cookies the browser sends itself. A 401 runs one refresh for the whole app;
// when that fails the session is over and the shell signs the user out.
http.configure({
baseUrl: `${clientEnv.NEXT_PUBLIC_API_ORIGIN}${API_VERSION_PATH}`,
baseUrl: `${API_PROXY_PATH}${API_VERSION_PATH}`,
refresh: {
endpoint: AUTH_ENDPOINTS.refresh,
onFailure: () =>

View File

@ -7,14 +7,18 @@ import { mapApiErrorBody } from '@lumina/market/app/http';
import { setEnv as setMarketEnv } from '@lumina/market/env';
import { cookies } from 'next/headers';
import { API_VERSION_PATH, FORWARDED_COOKIES } from '../constants';
import {
API_PROXY_PATH,
API_VERSION_PATH,
FORWARDED_COOKIES,
} from '../constants';
import { clientEnv } from '../env';
import { serverEnv } from '../env/server';
import { ERROR_HANDLER_CONFIG } from './error-reporting';
// Fills the server module graph once, before rendering. Idempotent: safe to run again.
setMarketEnv({
apiOrigin: clientEnv.NEXT_PUBLIC_API_ORIGIN,
apiBaseUrl: API_PROXY_PATH,
baleHandle: clientEnv.NEXT_PUBLIC_BALE_HANDLE,
telegramHandle: clientEnv.NEXT_PUBLIC_TELEGRAM_HANDLE,
supportHours: clientEnv.NEXT_PUBLIC_SUPPORT_HOURS,

View File

@ -1,2 +1,16 @@
/** Every gateway route except `/files/*` sits under this prefix. */
export const API_VERSION_PATH = '/v1';
/**
* Where the browser reaches the API: this site's own origin, under this path. next.config.ts
* rewrites it to the gateway (`API_INTERNAL_ORIGIN`), so no browser request is cross-origin and
* the session cookies belong to this site (0018). The server render calls the gateway directly.
*/
export const API_PROXY_PATH = '/api';
/**
* How long the `/api` proxy waits for the gateway. Next.js stops at 30 seconds by default; an
* upload (two 5 MB ID images, post media) on a slow connection takes longer, and the HTTP lib
* sets no timeout for uploads.
*/
export const API_PROXY_TIMEOUT_MS = 120_000;

View File

@ -1,2 +1,2 @@
export { API_VERSION_PATH } from './api';
export { API_PROXY_PATH, API_PROXY_TIMEOUT_MS, API_VERSION_PATH } from './api';
export { FORWARDED_COOKIES } from './cookies';

View File

@ -1,31 +1,19 @@
import { createClientEnv } from '@lumina/libs/env';
import * as v from 'valibot';
import { isOrigin } from './is-origin';
const required = v.pipe(v.string(), v.nonEmpty());
const url = v.pipe(v.string(), v.url());
/** Scheme and host only: request paths and media URLs are joined to it, so `https://api.lumina.ir/` would give `//v1`. */
const origin = v.pipe(
url,
v.check(
isOrigin,
'Must be an origin such as https://api.lumina.ir, with no path or trailing slash.',
),
);
/** Public variables, inlined into the browser bundle. Next.js inlines only literal reads. */
export const clientEnv = createClientEnv({
prefix: 'NEXT_PUBLIC_',
schema: {
NEXT_PUBLIC_API_ORIGIN: origin,
NEXT_PUBLIC_SITE_URL: url,
NEXT_PUBLIC_BALE_HANDLE: required,
NEXT_PUBLIC_TELEGRAM_HANDLE: required,
NEXT_PUBLIC_SUPPORT_HOURS: required,
},
runtimeEnv: {
NEXT_PUBLIC_API_ORIGIN: process.env.NEXT_PUBLIC_API_ORIGIN,
NEXT_PUBLIC_SITE_URL: process.env.NEXT_PUBLIC_SITE_URL,
NEXT_PUBLIC_BALE_HANDLE: process.env.NEXT_PUBLIC_BALE_HANDLE,
NEXT_PUBLIC_TELEGRAM_HANDLE: process.env.NEXT_PUBLIC_TELEGRAM_HANDLE,

16
apps/bull/src/env/env.config.ts vendored Normal file
View File

@ -0,0 +1,16 @@
import { origin } from '@lumina/libs/env';
import * as v from 'valibot';
/**
* For next.config.ts only: the gateway the `/api` rewrite proxies to. No `server-only` here, as
* the config loads outside React. `next build` writes rewrites into its output, so the value is
* the one at build time (0018) and `SKIP_ENV_VALIDATION` can't skip it: a build without it fails
* here, rather than shipping a proxy to the wrong gateway.
*/
export function apiInternalUrl(): string {
const result = v.safeParse(origin, process.env.API_INTERNAL_ORIGIN);
if (result.success) return result.output;
throw new Error(
`API_INTERNAL_ORIGIN is needed to build: next.config rewrites /api to it and next build keeps the value (0018). ${result.issues[0].message}`,
);
}

View File

@ -1,22 +1,13 @@
import 'server-only';
import { origin } from '@lumina/libs/env';
import { createServerEnv } from '@lumina/libs/env/server';
import * as v from 'valibot';
import { isOrigin } from './is-origin';
/** Server variables; only server code imports them, through `env/server`. */
export const serverEnv = createServerEnv({
schema: {
// Scheme and host only, as NEXT_PUBLIC_API_ORIGIN: request paths are joined to it.
API_INTERNAL_ORIGIN: v.pipe(
v.string(),
v.url(),
v.check(
isOrigin,
'Must be an origin such as http://gateway:3000, with no path or trailing slash.',
),
),
/** The gateway from inside the deployment network: server requests and the `/api` proxy. */
API_INTERNAL_ORIGIN: origin,
},
runtimeEnv: process.env,
skipValidation: process.env.SKIP_ENV_VALIDATION === 'true',

View File

@ -1,8 +0,0 @@
/** `https://api.lumina.ir`, not `https://api.lumina.ir/` or `https://api.lumina.ir/v1`. */
export function isOrigin(value: string): boolean {
try {
return new URL(value).origin === value;
} catch {
return false;
}
}

View File

@ -1,10 +1,11 @@
/** The platform's own settings, named for what they are, not for the variables behind them. */
export type MarketEnv = {
/**
* The API's public origin (`https://api.lumina.ir`), for what the browser loads straight from it:
* post media, avatars and uploads (`/files/*` sits outside `/v1`).
* Where the browser loads the API from: a path on this site (`/api`) that the app proxies to the
* gateway (0018). For what the browser loads itself: post media, avatars and uploads (`/files/*`
* sits outside `/v1`). A relative URL, so the server render writes the same address.
*/
apiOrigin: string;
apiBaseUrl: string;
/** Support chat handles and hours: config values, never hard-coded in a component. */
baleHandle: string;
telegramHandle: string;

View File

@ -4,5 +4,7 @@ import { getEnv } from '../../env';
export const postHttp = http.extend({});
/** `/files/*` sits outside `/v1`, on the API origin itself. */
export const postFilesHttp = http.extend({ baseUrl: () => getEnv().apiOrigin });
/** `/files/*` sits outside `/v1`: straight under the API's base (`/api/files/…`). Browser only. */
export const postFilesHttp = http.extend({
baseUrl: () => getEnv().apiBaseUrl,
});

View File

@ -1,12 +1,37 @@
import { getEnv } from '../../env';
/**
* A path the API returns (`/v1/posts/…/media/…`, `/files/…`) → an absolute URL the browser can
* load. Absolute URLs (legacy avatars carry the gateway's own host) pass through; empty stays
* `null`. Reads env inside the call, so bootstrap has always run.
* Uploads the gateway stored with a host before it stored paths (`/uploads/…`). That host is the
* gateway's or, behind the proxy, an app's, so the path is what counts. Remove once the back
* end's `scripts/migrate-upload-urls-to-relative.js --apply` has run everywhere.
*/
const LEGACY_UPLOAD_PATH = /^\/uploads\//;
/** An absolute address's path and query when it is a legacy upload, else `null`. */
function legacyUploadPath(address: string): string | null {
try {
const url = new URL(address);
return LEGACY_UPLOAD_PATH.test(url.pathname)
? `${url.pathname}${url.search}`
: null;
} catch {
return null;
}
}
/**
* A path the API returns (`/v1/posts/…/media/…`, `/files/…`, `/uploads/…`) → the URL the browser
* loads it from, through this site's API proxy (0018), so private media gets the session cookie:
* `/api/v1/posts/…`. Other absolute addresses (another site's, a CDN's) pass through, as does one
* that isn't a valid URL; empty stays `null`. Reads env inside the call, so bootstrap has always
* run.
*/
export function toApiUrl(path: string | null | undefined): string | null {
if (!path) return null;
if (/^https?:\/\//.test(path)) return path;
return `${getEnv().apiOrigin}${path.startsWith('/') ? '' : '/'}${path}`;
const { apiBaseUrl } = getEnv();
if (/^[a-z][a-z\d+\-.]*:/i.test(path)) {
const legacy = legacyUploadPath(path);
return legacy ? `${apiBaseUrl}${legacy}` : path;
}
return `${apiBaseUrl}${path.startsWith('/') ? '' : '/'}${path}`;
}