From 4a673ebb289ead0d912c1ad838b2e29f02d524c7 Mon Sep 17 00:00:00 2001 From: Loma Bot Ops Date: Sun, 22 Nov 2026 16:48:42 +0700 Subject: [PATCH] Support sub-path deploy via NEXT_PUBLIC_BASE_PATH (loma.chat/pagiva) Adds basePath config, withBase/appUrl helpers, base-path-aware cookies, OAuth redirects, manifest, service worker and cron runner. Co-Authored-By: Claude Opus 5.5 --- .env.example | 3 +++ Dockerfile | 6 ++++++ docker-compose.yml | 5 ++++- next.config.ts | 4 ++++ public/sw.js | 10 ++++++---- scripts/cron-runner.mjs | 3 ++- src/app/api/auth/change-password/route.ts | 3 ++- src/app/api/auth/logout/route.ts | 3 ++- .../api/auth/oauth/[provider]/start/route.ts | 3 ++- src/app/api/facebook/oauth/callback/route.ts | 3 ++- src/app/api/facebook/oauth/start/route.ts | 8 +++++--- src/app/api/upload/route.ts | 3 ++- src/app/change-password/page.tsx | 5 +++-- src/app/layout.tsx | 3 ++- src/app/manifest.ts | 19 +++++++++--------- src/components/AccountForm.tsx | 3 ++- src/components/AnalysisView.tsx | 3 ++- src/components/CaptionAssistant.tsx | 3 ++- src/components/InboxView.tsx | 3 ++- src/components/LoginForm.tsx | 5 +++-- src/components/PagesManager.tsx | 5 +++-- src/components/PostCheck.tsx | 3 ++- src/components/PostEditor.tsx | 3 ++- src/components/ProfileForm.tsx | 3 ++- src/components/RefreshInsightsButton.tsx | 3 ++- src/components/ReplyDrafts.tsx | 3 ++- src/components/RulesManager.tsx | 7 ++++--- src/components/ServiceWorker.tsx | 3 ++- src/components/Shell.tsx | 5 +++-- src/components/UsersManager.tsx | 3 ++- src/components/WeekBoard.tsx | 3 ++- src/components/WeekPlanAssistant.tsx | 5 +++-- src/lib/auth/session.ts | 3 ++- src/lib/auth/social.ts | 5 +++-- src/lib/base-path.ts | 20 +++++++++++++++++++ src/lib/facebook/oauth.ts | 3 ++- src/lib/http.ts | 3 ++- src/proxy.ts | 9 ++++++--- 38 files changed, 130 insertions(+), 57 deletions(-) create mode 100644 src/lib/base-path.ts diff --git a/.env.example b/.env.example index 602fd8e..8e51e2d 100644 --- a/.env.example +++ b/.env.example @@ -10,7 +10,10 @@ META_OAUTH_SCOPES="" # optional — override Facebook Login scopes (comm META_WEBHOOK_VERIFY_TOKEN="" # any random string, same value in App Dashboard CRON_SECRET="" # also authenticates scripts/cron-runner.mjs inside the container UPLOAD_DIR="" # optional — defaults to /app/.data/uploads; mount as a persistent volume +# Public URL incl. base path, no trailing slash (OAuth redirect URIs, webhook URL, upload URLs). NEXT_PUBLIC_APP_URL="http://localhost:3000" +# Optional sub-path deploy, e.g. "/pagiva" for https://loma.chat/pagiva. Build-time: rebuild after changing. +NEXT_PUBLIC_BASE_PATH="" # Optional — "เข้าสู่ระบบด้วย Google" on /login (button hidden when empty). # "เข้าสู่ระบบด้วย Facebook" uses META_APP_ID / META_APP_SECRET above. diff --git a/Dockerfile b/Dockerfile index 6e9dd35..d3433fc 100644 --- a/Dockerfile +++ b/Dockerfile @@ -5,10 +5,16 @@ COPY package.json package-lock.json ./ COPY prisma ./prisma RUN npm ci COPY . . +# Sub-path deploy (e.g. /pagiva) — inlined at build time, so changing it needs a rebuild. +ARG NEXT_PUBLIC_BASE_PATH= +ARG NEXT_PUBLIC_APP_URL= +ENV NEXT_PUBLIC_BASE_PATH=$NEXT_PUBLIC_BASE_PATH NEXT_PUBLIC_APP_URL=$NEXT_PUBLIC_APP_URL RUN npm run build FROM node:22-bookworm-slim WORKDIR /app +ARG NEXT_PUBLIC_BASE_PATH= +ENV NEXT_PUBLIC_BASE_PATH=$NEXT_PUBLIC_BASE_PATH ENV NODE_ENV=production HOSTNAME=0.0.0.0 PORT=3000 NEXT_TELEMETRY_DISABLED=1 RUN apt-get update && apt-get install -y --no-install-recommends openssl ca-certificates curl && rm -rf /var/lib/apt/lists/* COPY --from=build /app/.next/standalone ./ diff --git a/docker-compose.yml b/docker-compose.yml index fe67738..c179cba 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -2,6 +2,9 @@ services: web: build: context: . + args: + NEXT_PUBLIC_BASE_PATH: ${NEXT_PUBLIC_BASE_PATH:-} + NEXT_PUBLIC_APP_URL: ${NEXT_PUBLIC_APP_URL:-} environment: DATABASE_URL: postgresql://app:${SERVICE_PASSWORD_POSTGRES}@db:5432/app SESSION_SECRET: ${SERVICE_PASSWORD_64_SESSION} @@ -13,7 +16,7 @@ services: db: condition: service_healthy healthcheck: - test: ["CMD", "curl", "-fsS", "-o", "/dev/null", "http://127.0.0.1:3000/api/health"] + test: ["CMD", "curl", "-fsS", "-o", "/dev/null", "http://127.0.0.1:3000${NEXT_PUBLIC_BASE_PATH:-}/api/health"] interval: 30s timeout: 5s retries: 5 diff --git a/next.config.ts b/next.config.ts index 0871781..b80693b 100644 --- a/next.config.ts +++ b/next.config.ts @@ -1,7 +1,11 @@ import type { NextConfig } from "next"; +// Sub-path deploy (e.g. "/pagiva" for https://loma.chat/pagiva). Build-time only. +const basePath = (process.env.NEXT_PUBLIC_BASE_PATH ?? "").replace(/\/+$/, ""); + const nextConfig: NextConfig = { output: "standalone", + ...(basePath ? { basePath } : {}), outputFileTracingIncludes: { // Prisma 7 generates a hash-named client module that @vercel/nft can't // discover via static analysis — force-include it everywhere Prisma is used. diff --git a/public/sw.js b/public/sw.js index e5f5224..ff67779 100644 --- a/public/sw.js +++ b/public/sw.js @@ -1,11 +1,13 @@ // Service worker: installable app shell + offline fallback. // Never caches API responses or page HTML — they carry per-user, per-page data. -const VERSION = "pm-v4"; +const VERSION = "pm-v5"; const STATIC_CACHE = `${VERSION}-static`; -const OFFLINE_URL = "/offline.html"; +// Base path ("" or "/pagiva") comes from the registration scope. +const BASE = new URL(self.registration.scope).pathname.replace(/\/$/, ""); +const OFFLINE_URL = `${BASE}/offline.html`; self.addEventListener("install", (event) => { - event.waitUntil(caches.open(STATIC_CACHE).then((c) => c.addAll([OFFLINE_URL, "/icons/192"]))); + event.waitUntil(caches.open(STATIC_CACHE).then((c) => c.addAll([OFFLINE_URL, `${BASE}/icons/192`]))); self.skipWaiting(); }); @@ -29,7 +31,7 @@ self.addEventListener("fetch", (event) => { } // Build assets are content-hashed: cache-first is safe. - if (url.pathname.startsWith("/_next/static/") || url.pathname.startsWith("/icons/")) { + if (url.pathname.startsWith(`${BASE}/_next/static/`) || url.pathname.startsWith(`${BASE}/icons/`)) { event.respondWith( caches.match(req).then( (hit) => diff --git a/scripts/cron-runner.mjs b/scripts/cron-runner.mjs index 23fecaf..2f2b9c1 100644 --- a/scripts/cron-runner.mjs +++ b/scripts/cron-runner.mjs @@ -3,7 +3,8 @@ import "dotenv/config"; const PORT = process.env.PORT || 3000; -const BASE = `http://127.0.0.1:${PORT}`; +const BASE_PATH = (process.env.NEXT_PUBLIC_BASE_PATH ?? "").replace(/\/+$/, ""); +const BASE = `http://127.0.0.1:${PORT}${BASE_PATH}`; const SECRET = process.env.CRON_SECRET; if (!SECRET) { diff --git a/src/app/api/auth/change-password/route.ts b/src/app/api/auth/change-password/route.ts index 1b93838..24e586a 100644 --- a/src/app/api/auth/change-password/route.ts +++ b/src/app/api/auth/change-password/route.ts @@ -1,3 +1,4 @@ +import { BASE_PATH } from "@/lib/base-path"; import { NextResponse } from "next/server"; import { prisma } from "@/lib/db"; import { requireUser } from "@/lib/auth/user"; @@ -39,7 +40,7 @@ export async function POST(req: Request) { httpOnly: true, secure: process.env.NODE_ENV === "production", sameSite: "strict", - path: "/", + path: BASE_PATH || "/", maxAge: SESSION_DURATION_SECONDS, }); return res; diff --git a/src/app/api/auth/logout/route.ts b/src/app/api/auth/logout/route.ts index dd4c87a..aaa5c5b 100644 --- a/src/app/api/auth/logout/route.ts +++ b/src/app/api/auth/logout/route.ts @@ -1,8 +1,9 @@ +import { BASE_PATH } from "@/lib/base-path"; import { NextResponse } from "next/server"; import { COOKIE_NAME } from "@/lib/auth/session"; export async function POST() { const res = NextResponse.json({ ok: true }); - res.cookies.delete(COOKIE_NAME); + res.cookies.delete({ name: COOKIE_NAME, path: BASE_PATH || "/" }); return res; } diff --git a/src/app/api/auth/oauth/[provider]/start/route.ts b/src/app/api/auth/oauth/[provider]/start/route.ts index c2ed10d..4af624e 100644 --- a/src/app/api/auth/oauth/[provider]/start/route.ts +++ b/src/app/api/auth/oauth/[provider]/start/route.ts @@ -1,3 +1,4 @@ +import { appUrl } from "@/lib/base-path"; import { NextResponse } from "next/server"; import { authorizeUrl, @@ -19,7 +20,7 @@ export async function GET(req: Request, ctx: RouteContext<"/api/auth/oauth/[prov const url = new URL(req.url); const provider = parseProvider(raw); if (!provider || !enabledProviders().includes(provider)) { - return NextResponse.redirect(new URL("/login?error=not_configured", url.origin)); + return NextResponse.redirect(`${appUrl(url.origin)}/login?error=not_configured`); } const { nonce, cookie } = await createSocialState(provider, { diff --git a/src/app/api/facebook/oauth/callback/route.ts b/src/app/api/facebook/oauth/callback/route.ts index 1a7b613..3a0dd41 100644 --- a/src/app/api/facebook/oauth/callback/route.ts +++ b/src/app/api/facebook/oauth/callback/route.ts @@ -1,3 +1,4 @@ +import { BASE_PATH } from "@/lib/base-path"; import { cookies } from "next/headers"; import { prisma } from "@/lib/db"; import { encryptToken } from "@/lib/crypto/tokenBox"; @@ -22,7 +23,7 @@ export async function GET(req: Request) { const url = new URL(req.url); const jar = await cookies(); const stateCookie = jar.get(OAUTH_STATE_COOKIE)?.value; - jar.delete({ name: OAUTH_STATE_COOKIE, path: "/api/facebook/oauth" }); + jar.delete({ name: OAUTH_STATE_COOKIE, path: `${BASE_PATH}/api/facebook/oauth` }); const userId = await verifyOAuthState(stateCookie, url.searchParams.get("state")); if (!userId) return hop(`/pages?fb_error=${encodeURIComponent("ลิงก์เชื่อมหมดอายุหรือไม่ถูกต้อง ลองกดเชื่อมใหม่")}`); diff --git a/src/app/api/facebook/oauth/start/route.ts b/src/app/api/facebook/oauth/start/route.ts index 72db386..cd55131 100644 --- a/src/app/api/facebook/oauth/start/route.ts +++ b/src/app/api/facebook/oauth/start/route.ts @@ -1,3 +1,4 @@ +import { BASE_PATH, appUrl } from "@/lib/base-path"; import { NextResponse } from "next/server"; import { getCurrentUser, isSuperadmin } from "@/lib/auth/user"; import { authorizeUrl, createOAuthState, OAUTH_STATE_COOKIE } from "@/lib/facebook/oauth"; @@ -6,8 +7,9 @@ import { safeFacebookErrorMessage } from "@/lib/facebook/client"; /** SUPERADMIN only: redirects to the Facebook consent dialog. */ export async function GET(req: Request) { const origin = new URL(req.url).origin; + const root = appUrl(origin); const user = await getCurrentUser(); - if (!user || !isSuperadmin(user)) return NextResponse.redirect(new URL("/pages?fb_error=forbidden", origin)); + if (!user || !isSuperadmin(user)) return NextResponse.redirect(`${root}/pages?fb_error=forbidden`); try { const { nonce, cookie } = await createOAuthState(user.id); @@ -17,12 +19,12 @@ export async function GET(req: Request) { secure: process.env.NODE_ENV === "production", // Lax: must survive the top-level redirect back from facebook.com. sameSite: "lax", - path: "/api/facebook/oauth", + path: `${BASE_PATH}/api/facebook/oauth`, maxAge: 600, }); return res; } catch (e) { const msg = safeFacebookErrorMessage(e, "fb:oauth:start"); - return NextResponse.redirect(new URL(`/pages?fb_error=${encodeURIComponent(msg)}`, origin)); + return NextResponse.redirect(`${root}/pages?fb_error=${encodeURIComponent(msg)}`); } } diff --git a/src/app/api/upload/route.ts b/src/app/api/upload/route.ts index b11c798..5786d75 100644 --- a/src/app/api/upload/route.ts +++ b/src/app/api/upload/route.ts @@ -1,3 +1,4 @@ +import { appUrl } from "@/lib/base-path"; import { NextResponse } from "next/server"; import { putBlob } from "@/lib/storage/blob"; import { requirePageAction } from "@/lib/auth/user"; @@ -26,7 +27,7 @@ export async function POST(req: Request) { try { const ext = file.type === "image/png" ? "png" : "jpg"; - const baseUrl = process.env.NEXT_PUBLIC_APP_URL || new URL(req.url).origin; + const baseUrl = appUrl(new URL(req.url).origin); const blob = await putBlob(`posts/${pageId}/image.${ext}`, file, { contentType: file.type }, baseUrl); return NextResponse.json({ url: blob.url }); } catch (e) { diff --git a/src/app/change-password/page.tsx b/src/app/change-password/page.tsx index b142c68..9806b75 100644 --- a/src/app/change-password/page.tsx +++ b/src/app/change-password/page.tsx @@ -1,4 +1,5 @@ "use client"; +import { withBase } from "@/lib/base-path"; import { useState } from "react"; import { useRouter } from "next/navigation"; @@ -17,7 +18,7 @@ export default function ChangePasswordPage() { if (newPassword !== confirm) return setError("รหัสผ่านใหม่ทั้งสองช่องไม่ตรงกัน"); setBusy(true); setError(null); - const res = await fetch("/api/auth/change-password", { + const res = await fetch(withBase("/api/auth/change-password"), { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ currentPassword, newPassword }), @@ -30,7 +31,7 @@ export default function ChangePasswordPage() { } async function logout() { - await fetch("/api/auth/logout", { method: "POST" }); + await fetch(withBase("/api/auth/logout"), { method: "POST" }); router.replace("/login"); } diff --git a/src/app/layout.tsx b/src/app/layout.tsx index 3f95cd7..46b94e6 100644 --- a/src/app/layout.tsx +++ b/src/app/layout.tsx @@ -1,3 +1,4 @@ +import { withBase } from "@/lib/base-path"; import type { Metadata, Viewport } from "next"; import localFont from "next/font/local"; import { ServiceWorker } from "@/components/ServiceWorker"; @@ -17,7 +18,7 @@ export const metadata: Metadata = { description: "วางแผน อนุมัติ และเผยแพร่โพสต์ของเพจ Facebook และ Instagram ในพื้นที่ทำงานเดียว", applicationName: "จัดการเพจ", appleWebApp: { capable: true, title: "จัดการเพจ", statusBarStyle: "default" }, - icons: { icon: "/icons/192", apple: "/icons/apple" }, + icons: { icon: withBase("/icons/192"), apple: withBase("/icons/apple") }, formatDetection: { telephone: false }, }; diff --git a/src/app/manifest.ts b/src/app/manifest.ts index 80771f2..46ea919 100644 --- a/src/app/manifest.ts +++ b/src/app/manifest.ts @@ -1,27 +1,28 @@ +import { withBase } from "@/lib/base-path"; import type { MetadataRoute } from "next"; export default function manifest(): MetadataRoute.Manifest { return { - id: "/", + id: withBase("/"), name: "ระบบจัดการเพจ", short_name: "จัดการเพจ", description: "โพสต์ อนุมัติ ตอบแชท และดู insights ของเพจ Facebook และ Instagram", - start_url: "/", - scope: "/", + start_url: withBase("/"), + scope: withBase("/"), display: "standalone", orientation: "portrait", background_color: "#eef8ff", theme_color: "#e0f2fe", lang: "th", icons: [ - { src: "/icons/192", sizes: "192x192", type: "image/png", purpose: "any" }, - { src: "/icons/512", sizes: "512x512", type: "image/png", purpose: "any" }, - { src: "/icons/maskable-512", sizes: "512x512", type: "image/png", purpose: "maskable" }, + { src: withBase("/icons/192"), sizes: "192x192", type: "image/png", purpose: "any" }, + { src: withBase("/icons/512"), sizes: "512x512", type: "image/png", purpose: "any" }, + { src: withBase("/icons/maskable-512"), sizes: "512x512", type: "image/png", purpose: "maskable" }, ], shortcuts: [ - { name: "สร้างโพสต์", short_name: "สร้างโพสต์", url: "/posts/new" }, - { name: "Inbox", url: "/inbox" }, - { name: "ปฏิทิน", url: "/calendar" }, + { name: "สร้างโพสต์", short_name: "สร้างโพสต์", url: withBase("/posts/new") }, + { name: "Inbox", url: withBase("/inbox") }, + { name: "ปฏิทิน", url: withBase("/calendar") }, ], }; } diff --git a/src/components/AccountForm.tsx b/src/components/AccountForm.tsx index fbc6054..768ebd6 100644 --- a/src/components/AccountForm.tsx +++ b/src/components/AccountForm.tsx @@ -1,4 +1,5 @@ "use client"; +import { withBase } from "@/lib/base-path"; import { useEffect, useState } from "react"; import { useRouter } from "next/navigation"; @@ -29,7 +30,7 @@ export function AccountForm({ initial }: { initial: { name: string; email: strin form.set("removeAvatar", String(removeAvatar)); if (file) form.set("avatar", file); try { - const response = await fetch("/api/account", { method: "PUT", body: form }); + const response = await fetch(withBase("/api/account"), { method: "PUT", body: form }); const json = await response.json().catch(() => ({})); if (!response.ok) throw new Error(json.error ?? "บันทึกไม่สำเร็จ"); toast.show("บันทึกโปรไฟล์แล้ว"); diff --git a/src/components/AnalysisView.tsx b/src/components/AnalysisView.tsx index fd6995d..635a500 100644 --- a/src/components/AnalysisView.tsx +++ b/src/components/AnalysisView.tsx @@ -1,4 +1,5 @@ "use client"; +import { withBase } from "@/lib/base-path"; import { useEffect, useState } from "react"; import Link from "next/link"; @@ -138,7 +139,7 @@ function BriefForm({ e.preventDefault(); setError(null); setBusy(true); - const res = await fetch("/api/analysis", { + const res = await fetch(withBase("/api/analysis"), { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ pageId, business, audience, goal, budgetBaht: Number(budget.replace(/,/g, "")), days: Number(days) }), diff --git a/src/components/CaptionAssistant.tsx b/src/components/CaptionAssistant.tsx index 540587a..c861b5d 100644 --- a/src/components/CaptionAssistant.tsx +++ b/src/components/CaptionAssistant.tsx @@ -1,4 +1,5 @@ "use client"; +import { withBase } from "@/lib/base-path"; import { useState } from "react"; import Link from "next/link"; @@ -40,7 +41,7 @@ export function CaptionAssistant({ const label = "refine" in input ? input.refine : "draft"; setBusy(label); setError(null); - const res = await fetch("/api/ai/caption", { + const res = await fetch(withBase("/api/ai/caption"), { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ pageId, targets, caption, ...input }), diff --git a/src/components/InboxView.tsx b/src/components/InboxView.tsx index 2f56871..475329f 100644 --- a/src/components/InboxView.tsx +++ b/src/components/InboxView.tsx @@ -1,4 +1,5 @@ "use client"; +import { withBase } from "@/lib/base-path"; /* eslint-disable @next/next/no-img-element -- Graph CDN attachment URLs */ import { useCallback, useEffect, useState } from "react"; @@ -49,7 +50,7 @@ export function InboxView({ pageId, pageName, hasInstagram, canReply }: { pageId const [error, setError] = useState(null); const [sending, setSending] = useState(false); - const base = `/api/inbox/${pageId}/conversations`; + const base = withBase(`/api/inbox/${pageId}/conversations`); // Fetchers return data; state is only set in their promise callbacks. const fetchList = useCallback(async (): Promise<{ conversations: Conversation[]; error?: string }> => { diff --git a/src/components/LoginForm.tsx b/src/components/LoginForm.tsx index f6a854f..c2cb138 100644 --- a/src/components/LoginForm.tsx +++ b/src/components/LoginForm.tsx @@ -1,4 +1,5 @@ "use client"; +import { withBase } from "@/lib/base-path"; import { useState } from "react"; import { useRouter, useSearchParams } from "next/navigation"; @@ -75,7 +76,7 @@ export function LoginForm({ providers }: { providers: Provider[] }) { e.preventDefault(); setBusy(true); setError(null); - const res = await fetch("/api/auth/login", { + const res = await fetch(withBase("/api/auth/login"), { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ email, password, remember }), @@ -92,7 +93,7 @@ export function LoginForm({ providers }: { providers: Provider[] }) { function socialHref(p: Provider): string { const q = new URLSearchParams({ from, remember: remember ? "1" : "0" }); - return `/api/auth/oauth/${p}/start?${q}`; + return withBase(`/api/auth/oauth/${p}/start?${q}`); } return ( diff --git a/src/components/PagesManager.tsx b/src/components/PagesManager.tsx index b764e3a..d46cd2d 100644 --- a/src/components/PagesManager.tsx +++ b/src/components/PagesManager.tsx @@ -1,4 +1,5 @@ "use client"; +import { withBase } from "@/lib/base-path"; import { useEffect, useState } from "react"; import { useRouter } from "next/navigation"; @@ -42,7 +43,7 @@ interface Member { } async function api(url: string, init?: RequestInit): Promise<{ ok: true; data: T } | { ok: false; error: string }> { - const res = await fetch(url, { ...init, headers: { "Content-Type": "application/json" } }); + const res = await fetch(withBase(url), { ...init, headers: { "Content-Type": "application/json" } }); const body = await res.json().catch(() => ({})); return res.ok ? { ok: true, data: body as T } : { ok: false, error: body.error ?? "ทำรายการไม่สำเร็จ" }; } @@ -211,7 +212,7 @@ export function PagesManager({

บัญชี Facebook

{appConfigured ? ( // Full navigation (not ): the start route redirects to facebook.com. - + {connections.length ? "เชื่อมบัญชีเพิ่ม / ขอสิทธิ์ใหม่" : "เข้าสู่ระบบด้วย Facebook"} ) : ( diff --git a/src/components/PostCheck.tsx b/src/components/PostCheck.tsx index 5ab6b4f..fe03848 100644 --- a/src/components/PostCheck.tsx +++ b/src/components/PostCheck.tsx @@ -1,4 +1,5 @@ "use client"; +import { withBase } from "@/lib/base-path"; import { useState } from "react"; import { Icon } from "./Icon"; @@ -28,7 +29,7 @@ export function PostCheck({ pageId, caption, targets, hasImage }: { pageId: stri async function run() { setBusy(true); setError(null); - const res = await fetch("/api/ai/check", { + const res = await fetch(withBase("/api/ai/check"), { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ pageId, caption, targets, hasImage }), diff --git a/src/components/PostEditor.tsx b/src/components/PostEditor.tsx index f988f67..c9aee63 100644 --- a/src/components/PostEditor.tsx +++ b/src/components/PostEditor.tsx @@ -1,4 +1,5 @@ "use client"; +import { withBase } from "@/lib/base-path"; /* eslint-disable @next/next/no-img-element -- Blob URLs and Graph CDN images, not optimisable */ import { useRef, useState } from "react"; @@ -124,7 +125,7 @@ export function PostEditor({ setBusy(label); setError(null); try { - const res = await fetch(url, { ...init, headers: init.body instanceof FormData ? undefined : { "Content-Type": "application/json" } }); + const res = await fetch(withBase(url), { ...init, headers: init.body instanceof FormData ? undefined : { "Content-Type": "application/json" } }); const body = await res.json().catch(() => ({})); if (!res.ok) { setError(body.error ?? "ทำรายการไม่สำเร็จ"); diff --git a/src/components/ProfileForm.tsx b/src/components/ProfileForm.tsx index 2269b62..3b8cbea 100644 --- a/src/components/ProfileForm.tsx +++ b/src/components/ProfileForm.tsx @@ -1,4 +1,5 @@ "use client"; +import { withBase } from "@/lib/base-path"; import { useState } from "react"; import { useRouter } from "next/navigation"; @@ -29,7 +30,7 @@ export function ProfileForm({ const [error, setError] = useState(null); async function request(path: string, method: string, body?: ShopProfile) { - const res = await fetch(path, { method, headers: { "Content-Type": "application/json" }, body: body ? JSON.stringify(body) : undefined }).catch(() => null); + const res = await fetch(withBase(path), { method, headers: { "Content-Type": "application/json" }, body: body ? JSON.stringify(body) : undefined }).catch(() => null); const json = res ? await res.json().catch(() => ({})) : {}; return { ok: Boolean(res?.ok), json }; } diff --git a/src/components/RefreshInsightsButton.tsx b/src/components/RefreshInsightsButton.tsx index 4ae3415..9377f5e 100644 --- a/src/components/RefreshInsightsButton.tsx +++ b/src/components/RefreshInsightsButton.tsx @@ -1,4 +1,5 @@ "use client"; +import { withBase } from "@/lib/base-path"; import { useState } from "react"; import { useRouter } from "next/navigation"; @@ -12,7 +13,7 @@ export function RefreshInsightsButton({ pageId, variant = "on-band" }: { pageId: async function refresh() { setBusy(true); - const res = await fetch("/api/insights/refresh", { + const res = await fetch(withBase("/api/insights/refresh"), { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ pageId }), diff --git a/src/components/ReplyDrafts.tsx b/src/components/ReplyDrafts.tsx index 0d165d6..a903f94 100644 --- a/src/components/ReplyDrafts.tsx +++ b/src/components/ReplyDrafts.tsx @@ -1,4 +1,5 @@ "use client"; +import { withBase } from "@/lib/base-path"; import { useState } from "react"; import Link from "next/link"; @@ -15,7 +16,7 @@ export function ReplyDrafts({ pageId, conversationId, onPick }: { pageId: string async function draft() { setBusy(true); setError(null); - const res = await fetch("/api/ai/reply", { + const res = await fetch(withBase("/api/ai/reply"), { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ pageId, conversationId }), diff --git a/src/components/RulesManager.tsx b/src/components/RulesManager.tsx index 54b173a..b0eff8a 100644 --- a/src/components/RulesManager.tsx +++ b/src/components/RulesManager.tsx @@ -1,4 +1,5 @@ "use client"; +import { withBase } from "@/lib/base-path"; import { useState } from "react"; import { useRouter } from "next/navigation"; @@ -41,7 +42,7 @@ export function RulesManager({ pageId, canEdit, rules }: { pageId: string; canEd if (!editing) return; setBusy(true); setError(null); - const res = await fetch("/api/reply-rules", { + const res = await fetch(withBase("/api/reply-rules"), { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ ...editing, pageId, keywords: keywordsText }), @@ -54,7 +55,7 @@ export function RulesManager({ pageId, canEdit, rules }: { pageId: string; canEd } async function toggle(rule: Rule) { - await fetch("/api/reply-rules", { + await fetch(withBase("/api/reply-rules"), { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ ...rule, pageId, isActive: !rule.isActive }), @@ -64,7 +65,7 @@ export function RulesManager({ pageId, canEdit, rules }: { pageId: string; canEd async function remove(rule: Rule) { if (!window.confirm(`ลบกฎ "${rule.name}"?`)) return; - await fetch(`/api/reply-rules?id=${rule.id}`, { method: "DELETE" }); + await fetch(withBase(`/api/reply-rules?id=${rule.id}`), { method: "DELETE" }); router.refresh(); } diff --git a/src/components/ServiceWorker.tsx b/src/components/ServiceWorker.tsx index 513a458..ab39b6b 100644 --- a/src/components/ServiceWorker.tsx +++ b/src/components/ServiceWorker.tsx @@ -1,4 +1,5 @@ "use client"; +import { withBase } from "@/lib/base-path"; import { useEffect } from "react"; @@ -6,7 +7,7 @@ import { useEffect } from "react"; export function ServiceWorker() { useEffect(() => { if (process.env.NODE_ENV !== "production" || !("serviceWorker" in navigator)) return; - navigator.serviceWorker.register("/sw.js").catch((e) => console.error("[sw] register failed", e)); + navigator.serviceWorker.register(withBase("/sw.js"), { scope: withBase("/") }).catch((e) => console.error("[sw] register failed", e)); }, []); return null; } diff --git a/src/components/Shell.tsx b/src/components/Shell.tsx index 548649f..77521d0 100644 --- a/src/components/Shell.tsx +++ b/src/components/Shell.tsx @@ -1,4 +1,5 @@ "use client"; +import { withBase } from "@/lib/base-path"; import Link from "next/link"; import { usePathname, useRouter } from "next/navigation"; @@ -127,7 +128,7 @@ export function Shell({ } async function logout() { - await fetch("/api/auth/logout", { method: "POST" }); + await fetch(withBase("/api/auth/logout"), { method: "POST" }); router.replace("/login"); router.refresh(); } @@ -162,7 +163,7 @@ export function Shell({
{/* eslint-disable-next-line @next/next/no-img-element -- generated app icon route */} - +
ระบบจัดการเพจ
diff --git a/src/components/UsersManager.tsx b/src/components/UsersManager.tsx index ff6dfdf..260507c 100644 --- a/src/components/UsersManager.tsx +++ b/src/components/UsersManager.tsx @@ -1,4 +1,5 @@ "use client"; +import { withBase } from "@/lib/base-path"; import { useState } from "react"; import { useRouter } from "next/navigation"; @@ -29,7 +30,7 @@ export function UsersManager({ users, currentUserId }: { users: UserRow[]; curre setBusy(true); setError(null); setFlash(null); - const res = await fetch(url, { method, headers: { "Content-Type": "application/json" }, body: JSON.stringify(body) }); + const res = await fetch(withBase(url), { method, headers: { "Content-Type": "application/json" }, body: JSON.stringify(body) }); const data = await res.json().catch(() => ({})); setBusy(false); if (!res.ok) { diff --git a/src/components/WeekBoard.tsx b/src/components/WeekBoard.tsx index 62a0e51..e2dcc73 100644 --- a/src/components/WeekBoard.tsx +++ b/src/components/WeekBoard.tsx @@ -1,4 +1,5 @@ "use client"; +import { withBase } from "@/lib/base-path"; import Link from "next/link"; import { useState } from "react"; @@ -41,7 +42,7 @@ export function WeekBoard({ week, today, posts, tray, editablePageIds, nextId }: if (busy || !post || !canMove(post) || post.day === day) return; setBusy(true); try { - const res = await fetch(`/api/posts/${id}`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ action: "plan", plannedAt: day ? bkkMidnight(day).toISOString() : null }) }); + const res = await fetch(withBase(`/api/posts/${id}`), { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ action: "plan", plannedAt: day ? bkkMidnight(day).toISOString() : null }) }); const body = await res.json(); if (!res.ok) throw new Error(body.error ?? "วางวันไม่สำเร็จ"); toast.show(day ? "วางวันแล้ว · ยังไม่ได้ตั้งเวลาเผยแพร่" : "ย้ายกลับคิวที่ยังไม่วางแผนแล้ว"); diff --git a/src/components/WeekPlanAssistant.tsx b/src/components/WeekPlanAssistant.tsx index 9d0e41f..f64318b 100644 --- a/src/components/WeekPlanAssistant.tsx +++ b/src/components/WeekPlanAssistant.tsx @@ -1,4 +1,5 @@ "use client"; +import { withBase } from "@/lib/base-path"; import { useState } from "react"; import Link from "next/link"; @@ -36,7 +37,7 @@ export function WeekPlanAssistant({ pageId, pageName, week, openDays }: { pageId async function plan() { setBusy("plan"); setError(null); - const res = await fetch("/api/ai/week-plan", { + const res = await fetch(withBase("/api/ai/week-plan"), { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ pageId, week, goal, count }), @@ -56,7 +57,7 @@ export function WeekPlanAssistant({ pageId, pageName, week, openDays }: { pageId let created = 0; let firstError: string | null = null; for (const p of chosen) { - const res = await fetch("/api/posts", { + const res = await fetch(withBase("/api/posts"), { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ pageId, title: p.title, caption: p.caption, targets: ["FACEBOOK"], aiAssisted: true, plannedAt: bkkMidnight(p.day).toISOString() }), diff --git a/src/lib/auth/session.ts b/src/lib/auth/session.ts index e9a3148..7ecf1d5 100644 --- a/src/lib/auth/session.ts +++ b/src/lib/auth/session.ts @@ -1,3 +1,4 @@ +import { BASE_PATH } from "@/lib/base-path"; import { SignJWT, jwtVerify } from "jose"; import type { GlobalRole } from "@prisma/client"; @@ -64,7 +65,7 @@ export function sessionCookieOptions(remember: boolean) { httpOnly: true, secure: process.env.NODE_ENV === "production", sameSite: "strict" as const, - path: "/", + path: BASE_PATH || "/", ...(remember ? { maxAge: SESSION_DURATION_SECONDS } : {}), }; } diff --git a/src/lib/auth/social.ts b/src/lib/auth/social.ts index 27c5888..451e2a1 100644 --- a/src/lib/auth/social.ts +++ b/src/lib/auth/social.ts @@ -1,3 +1,4 @@ +import { BASE_PATH, appUrl } from "@/lib/base-path"; import { SignJWT, jwtVerify } from "jose"; import type { AuthProvider } from "@prisma/client"; import { prisma } from "@/lib/db"; @@ -16,7 +17,7 @@ export const SOCIAL_PROVIDERS = ["google", "facebook"] as const; export type SocialProvider = (typeof SOCIAL_PROVIDERS)[number]; export const SOCIAL_STATE_COOKIE = "pm_social_oauth"; -export const SOCIAL_STATE_PATH = "/api/auth/oauth"; +export const SOCIAL_STATE_PATH = `${BASE_PATH}/api/auth/oauth`; export const SOCIAL_STATE_TTL_SECONDS = 10 * 60; const DB_PROVIDER: Record = { google: "GOOGLE", facebook: "FACEBOOK" }; @@ -75,7 +76,7 @@ export function safeRedirectPath(raw: string | null | undefined): string { } function redirectUri(provider: SocialProvider, origin: string): string { - return `${process.env.NEXT_PUBLIC_APP_URL || origin}/api/auth/oauth/${provider}/callback`; + return `${appUrl(origin)}/api/auth/oauth/${provider}/callback`; } // ---------- state ---------- diff --git a/src/lib/base-path.ts b/src/lib/base-path.ts new file mode 100644 index 0000000..f1f080b --- /dev/null +++ b/src/lib/base-path.ts @@ -0,0 +1,20 @@ +/** + * The app can be served under a sub-path (e.g. https://loma.chat/pagiva). + * `NEXT_PUBLIC_BASE_PATH` is inlined at build time and also feeds + * `basePath` in next.config.ts — changing it requires a rebuild. + * + * Next.js prefixes , router.push/replace and redirect() itself; this + * helper is for everything it does not touch: fetch(), plain /, + * cookie paths and URLs built for third parties. + */ +export const BASE_PATH = (process.env.NEXT_PUBLIC_BASE_PATH ?? "").replace(/\/+$/, ""); + +/** Prefixes an absolute app path ("/api/...") with the base path. */ +export function withBase(path: string): string { + return `${BASE_PATH}${path}`; +} + +/** Public URL of the app root (origin + base path), no trailing slash. */ +export function appUrl(origin: string): string { + return (process.env.NEXT_PUBLIC_APP_URL || `${origin}${BASE_PATH}`).replace(/\/+$/, ""); +} diff --git a/src/lib/facebook/oauth.ts b/src/lib/facebook/oauth.ts index 50507dc..4fb0b8e 100644 --- a/src/lib/facebook/oauth.ts +++ b/src/lib/facebook/oauth.ts @@ -1,3 +1,4 @@ +import { appUrl } from "@/lib/base-path"; import { SignJWT, jwtVerify } from "jose"; import { GRAPH_API_VERSION, graphGet, UserFacingError } from "./client"; @@ -40,7 +41,7 @@ export function appAccessToken(): string | null { } export function oauthRedirectUri(origin: string): string { - return `${process.env.NEXT_PUBLIC_APP_URL || origin}/api/facebook/oauth/callback`; + return `${appUrl(origin)}/api/facebook/oauth/callback`; } export function oauthScopes(): string[] { diff --git a/src/lib/http.ts b/src/lib/http.ts index 49d3263..16af744 100644 --- a/src/lib/http.ts +++ b/src/lib/http.ts @@ -1,3 +1,4 @@ +import { withBase } from "@/lib/base-path"; import { NextResponse } from "next/server"; import { safeFacebookErrorMessage, UserFacingError, FacebookApiError } from "@/lib/facebook/client"; @@ -23,7 +24,7 @@ export function errorResponse(e: unknown, context: string): NextResponse { * this page is same-site. `path` must already be a validated same-origin path. */ export function htmlRedirect(path: string): Response { - const safe = path.replace(/&/g, "&").replace(/"/g, """).replace(//g, ">"); + const safe = withBase(path).replace(/&/g, "&").replace(/"/g, """).replace(//g, ">"); const html = `กำลังกลับสู่ระบบ…

กำลังกลับสู่ระบบ… ไปต่อ

`; return new Response(html, { headers: { "content-type": "text/html; charset=utf-8", "cache-control": "no-store" } }); } diff --git a/src/proxy.ts b/src/proxy.ts index 43e5b63..c53881f 100644 --- a/src/proxy.ts +++ b/src/proxy.ts @@ -1,5 +1,6 @@ import { NextResponse } from "next/server"; import type { NextRequest } from "next/server"; +import { BASE_PATH } from "@/lib/base-path"; import { COOKIE_NAME, verifySessionToken } from "@/lib/auth/session"; const PUBLIC_PATHS = [ @@ -57,10 +58,12 @@ export async function proxy(request: NextRequest) { if (pathname.startsWith("/api/")) { return NextResponse.json({ error: "unauthenticated" }, { status: 401 }); } - const loginUrl = new URL("/login", request.url); + const loginUrl = request.nextUrl.clone(); + loginUrl.pathname = "/login"; + loginUrl.search = ""; loginUrl.searchParams.set("from", pathname); const res = NextResponse.redirect(loginUrl); - if (token) res.cookies.delete(COOKIE_NAME); // stale/invalid cookie — clear it + if (token) res.cookies.delete({ name: COOKIE_NAME, path: BASE_PATH || "/" }); // stale/invalid cookie — clear it return res; } @@ -68,7 +71,7 @@ export async function proxy(request: NextRequest) { if (pathname.startsWith("/api/")) { return NextResponse.json({ error: "ต้องเปลี่ยนรหัสผ่านก่อนใช้งานต่อ" }, { status: 403 }); } - return NextResponse.redirect(new URL("/change-password", request.url)); + return NextResponse.redirect(Object.assign(request.nextUrl.clone(), { pathname: "/change-password", search: "" })); } return NextResponse.next();