Compare commits

..

7 Commits

Author SHA1 Message Date
Loma Bot Ops 4a673ebb28 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 <noreply@anthropic.com>
2026-11-22 16:48:42 +07:00
chaloemphong 9d5a029fa5 Disable Facebook social login permanently
Facebook Login for Business (the only Login product a Business-type
app gets, needed here for Page/Messenger/Instagram) has no
email/public_profile permission to request, only business asset
permissions - there is no config_id that can resolve a user's
identity. credentials() now always returns null for facebook so the
button stays hidden; Google login is unaffected.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-11-22 16:17:36 +07:00
chaloemphong 025ed6cc57 Add Vercel deploy support alongside Coolify
Storage now picks Vercel Blob when a store is connected (BLOB_STORE_ID
or BLOB_READ_WRITE_TOKEN), falling back to local disk for self-hosted
runs. Adds vercel.json cron schedule for the existing cron routes
(ig-publisher capped to once/day on Hobby plan).

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-11-22 15:16:08 +07:00
chaloemphong 32c121a85a Copy the full scripts/ directory into the runtime image
Only cron-runner.mjs was copied, so scripts/create-user.mjs (needed to
bootstrap the first login account on a fresh deploy) was missing from
the container entirely.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-11-22 14:45:43 +07:00
chaloemphong fd33d5c987 Copy prisma.config.ts into the runtime image
Prisma 7 reads datasource.url from prisma.config.ts, not schema.prisma.
The final Docker stage copied prisma/ but not the root config file, so
`prisma migrate deploy` always failed with "datasource.url property is
required" regardless of DATABASE_URL being set correctly.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-11-22 14:29:57 +07:00
chaloemphong 53b8c3cbf7 Add docker-compose deploy path with Coolify-managed secrets
Adds docker-compose.yml so Coolify can provision Postgres and generate
DATABASE_URL/SESSION_SECRET/TOKEN_ENCRYPTION_KEY/CRON_SECRET itself via
its SERVICE_PASSWORD_* magic variables, instead of an operator typing
them into the dashboard by hand.

TOKEN_ENCRYPTION_KEY now derives its AES-256 key via SHA-256 instead of
requiring exactly 32 raw bytes in base64, so a generated magic variable
works regardless of its format.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-11-22 12:45:57 +07:00
chaloemphong 1cb75a163f Self-host Anuphan font instead of next/font/google
The Coolify build server has no outbound access to fonts.googleapis.com,
which crashed `npm run build` inside the Docker build with a next/font
google-loader TypeError. Switch to next/font/local with the variable TTF
fetched from the Google Fonts GitHub repo (same OFL-licensed font, no
build-time network dependency).

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-11-22 12:31:13 +07:00
47 changed files with 609 additions and 70 deletions
+4 -1
View File
@@ -2,7 +2,7 @@ DATABASE_URL="postgresql://user:pass@localhost:5432/page_manager"
# For prisma dev, use its separate shadow port; never point this at DATABASE_URL. # For prisma dev, use its separate shadow port; never point this at DATABASE_URL.
SHADOW_DATABASE_URL="" SHADOW_DATABASE_URL=""
SESSION_SECRET="" # long random string (jose HS256) SESSION_SECRET="" # long random string (jose HS256)
TOKEN_ENCRYPTION_KEY="" # npm run gen-key (32 bytes base64) TOKEN_ENCRYPTION_KEY="" # any random string (hashed to a 32-byte key) — npm run gen-key works too
META_APP_ID="" META_APP_ID=""
META_APP_SECRET="" # verifies webhook X-Hub-Signature-256 META_APP_SECRET="" # verifies webhook X-Hub-Signature-256
META_SYSTEM_USER_TOKEN="" # optional — pages can be connected via "Login with Facebook" instead META_SYSTEM_USER_TOKEN="" # optional — pages can be connected via "Login with Facebook" instead
@@ -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 META_WEBHOOK_VERIFY_TOKEN="" # any random string, same value in App Dashboard
CRON_SECRET="" # also authenticates scripts/cron-runner.mjs inside the container CRON_SECRET="" # also authenticates scripts/cron-runner.mjs inside the container
UPLOAD_DIR="" # optional — defaults to /app/.data/uploads; mount as a persistent volume 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" 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). # Optional — "เข้าสู่ระบบด้วย Google" on /login (button hidden when empty).
# "เข้าสู่ระบบด้วย Facebook" uses META_APP_ID / META_APP_SECRET above. # "เข้าสู่ระบบด้วย Facebook" uses META_APP_ID / META_APP_SECRET above.
+3
View File
@@ -17,3 +17,6 @@ output/
# Local tool scratch state # Local tool scratch state
.impeccable/ .impeccable/
.vercel
.env*
+10 -1
View File
@@ -5,10 +5,16 @@ COPY package.json package-lock.json ./
COPY prisma ./prisma COPY prisma ./prisma
RUN npm ci RUN npm ci
COPY . . 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 RUN npm run build
FROM node:22-bookworm-slim FROM node:22-bookworm-slim
WORKDIR /app 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 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/* 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 ./ COPY --from=build /app/.next/standalone ./
@@ -18,7 +24,10 @@ COPY --from=build /app/node_modules ./node_modules
COPY --from=build /app/.next/static ./.next/static COPY --from=build /app/.next/static ./.next/static
COPY --from=build /app/public ./public COPY --from=build /app/public ./public
COPY --from=build /app/prisma ./prisma COPY --from=build /app/prisma ./prisma
COPY scripts/cron-runner.mjs ./scripts/cron-runner.mjs # Prisma 7 reads datasource.url from this file, not schema.prisma — required
# for `prisma migrate deploy` at container start.
COPY --from=build /app/prisma.config.ts ./prisma.config.ts
COPY --from=build /app/scripts ./scripts
RUN mkdir -p /app/.data/uploads && chown -R node:node /app RUN mkdir -p /app/.data/uploads && chown -R node:node /app
USER node USER node
EXPOSE 3000 EXPOSE 3000
+1 -1
View File
@@ -63,7 +63,7 @@ npm run dev # http://localhost:3000
### ปุ่มเข้าสู่ระบบด้วย Facebook / Google (หน้า /login) ### ปุ่มเข้าสู่ระบบด้วย Facebook / Google (หน้า /login)
- **Facebook** — แอป Meta เดียวกัน: เพิ่ม `https://<domain>/api/auth/oauth/facebook/callback` ใน Valid OAuth Redirect URIs. ขอแค่ `email` + `public_profile` (Standard Access ไม่ต้อง App Review) แต่โหมด Development คนที่ login ได้ต้องมี role ในแอป — เปิดให้ทุกคนต้องสลับแอปเป็น Live - **Facebook** — ปิดถาวร: แอปประเภทธุรกิจ (จำเป็นสำหรับ Page/Messenger/Instagram) ได้แค่ product "Facebook Login for Business" ซึ่งไม่มี permission `email`/`public_profile` ให้ขอเลย (มีแต่ asset permission เช่น `pages_show_list`) จึงเอาข้อมูลตัวตนผู้ใช้มา resolve ไม่ได้ — `credentials()` ใน `src/lib/auth/social.ts` return null ให้ facebook เสมอ ปุ่มเลยไม่โชว์ใน `/login`
- **Google** — Google Cloud Console → APIs & Services → Credentials → Create OAuth client ID (Web application) → Authorized redirect URI: `https://<domain>/api/auth/oauth/google/callback` (local: `http://localhost:3000/api/auth/oauth/google/callback`) → ใส่ `GOOGLE_CLIENT_ID` / `GOOGLE_CLIENT_SECRET`. OAuth consent screen สถานะ Testing ใช้ได้เฉพาะ test users ที่เพิ่มไว้ — กด Publish app ให้ทุกคนใช้ได้ (scope `openid email profile` ไม่ต้อง verify) - **Google** — Google Cloud Console → APIs & Services → Credentials → Create OAuth client ID (Web application) → Authorized redirect URI: `https://<domain>/api/auth/oauth/google/callback` (local: `http://localhost:3000/api/auth/oauth/google/callback`) → ใส่ `GOOGLE_CLIENT_ID` / `GOOGLE_CLIENT_SECRET`. OAuth consent screen สถานะ Testing ใช้ได้เฉพาะ test users ที่เพิ่มไว้ — กด Publish app ให้ทุกคนใช้ได้ (scope `openid email profile` ไม่ต้อง verify)
ทางเลือก: ใส่ `META_SYSTEM_USER_TOKEN` (system user ใน Business Manager ที่ assign เพจไว้) แล้วเพจจะขึ้นในรายการเหมือนกัน ทางเลือก: ใส่ `META_SYSTEM_USER_TOKEN` (system user ใน Business Manager ที่ assign เพจไว้) แล้วเพจจะขึ้นในรายการเหมือนกัน
+41
View File
@@ -0,0 +1,41 @@
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}
TOKEN_ENCRYPTION_KEY: ${SERVICE_PASSWORD_64_TOKENKEY}
CRON_SECRET: ${SERVICE_PASSWORD_64_CRON}
volumes:
- web-data:/app/.data
depends_on:
db:
condition: service_healthy
healthcheck:
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
start_period: 20s
db:
image: postgres:17-alpine
environment:
POSTGRES_USER: app
POSTGRES_PASSWORD: ${SERVICE_PASSWORD_POSTGRES}
POSTGRES_DB: app
volumes:
- pg-data:/var/lib/postgresql/data
healthcheck:
test: ["CMD-SHELL", "pg_isready -U app -d app"]
interval: 10s
timeout: 5s
retries: 10
volumes:
web-data:
pg-data:
+4
View File
@@ -1,7 +1,11 @@
import type { NextConfig } from "next"; 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 = { const nextConfig: NextConfig = {
output: "standalone", output: "standalone",
...(basePath ? { basePath } : {}),
outputFileTracingIncludes: { outputFileTracingIncludes: {
// Prisma 7 generates a hash-named client module that @vercel/nft can't // Prisma 7 generates a hash-named client module that @vercel/nft can't
// discover via static analysis — force-include it everywhere Prisma is used. // discover via static analysis — force-include it everywhere Prisma is used.
+287
View File
@@ -12,6 +12,7 @@
"@anthropic-ai/sdk": "^1.12.0", "@anthropic-ai/sdk": "^1.12.0",
"@prisma/adapter-pg": "^7.9.1", "@prisma/adapter-pg": "^7.9.1",
"@prisma/client": "^7.9.1", "@prisma/client": "^7.9.1",
"@vercel/blob": "^2.9.0",
"dotenv": "^17.3.1", "dotenv": "^17.3.1",
"jose": "^6.2.8", "jose": "^6.2.8",
"next": "16.3.0", "next": "16.3.0",
@@ -2944,6 +2945,77 @@
"win32" "win32"
] ]
}, },
"node_modules/@vercel/blob": {
"version": "2.9.0",
"resolved": "https://registry.npmjs.org/@vercel/blob/-/blob-2.9.0.tgz",
"integrity": "sha512-o+1CMRlT8/RvGo1aGkFv40F7v3MLdSOaVaIccepBXWrXgonKId3hHKSKGQ+iBDPoSe03crmHfhpHtTs0CCXiig==",
"license": "Apache-2.0",
"dependencies": {
"@vercel/oidc": "^3.6.1",
"async-retry": "^1.3.3",
"is-buffer": "^2.0.5",
"is-node-process": "^1.2.0",
"throttleit": "^2.1.0",
"undici": "^6.23.0"
},
"engines": {
"node": ">=20.0.0"
}
},
"node_modules/@vercel/cli-config": {
"version": "0.3.1",
"resolved": "https://registry.npmjs.org/@vercel/cli-config/-/cli-config-0.3.1.tgz",
"integrity": "sha512-sISbygqlFXYb8qfPu/+2Cf/A8IjrlAuZePdag3EDQr2PRA455s7UZtl9Ro674CWsB/saBRmz3jEkw0YsQs8OoQ==",
"license": "Apache-2.0",
"dependencies": {
"xdg-app-paths": "5",
"zod": "4.1.11"
}
},
"node_modules/@vercel/cli-config/node_modules/zod": {
"version": "4.1.11",
"resolved": "https://registry.npmjs.org/zod/-/zod-4.1.11.tgz",
"integrity": "sha512-WPsqwxITS2tzx1bzhIKsEs19ABD5vmCVa4xBo2tq/SrV4RNZtfws1EnCWQXM6yh8bD08a1idvkB5MZSBiZsjwg==",
"license": "MIT",
"funding": {
"url": "https://github.com/sponsors/colinhacks"
}
},
"node_modules/@vercel/cli-exec": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/@vercel/cli-exec/-/cli-exec-1.0.1.tgz",
"integrity": "sha512-g9XerViJ/paZujufXYcu5XYI2vU2rtB4sgdpjUHde5RnOkdmpu0ngH46LCFGHoPXO/C+qDPSczIHIRN+8Q2YKQ==",
"license": "Apache-2.0",
"dependencies": {
"execa": "5.1.1"
},
"engines": {
"node": ">= 18"
}
},
"node_modules/@vercel/oidc": {
"version": "3.8.10",
"resolved": "https://registry.npmjs.org/@vercel/oidc/-/oidc-3.8.10.tgz",
"integrity": "sha512-sPw1kIfQEA6/2dB+zlAJHnhhNBRJ8t/t4HfFvKO+g0EPBA7NbCKyGovuhgAV6Mnl865ka7HqCEguIy596czdAw==",
"license": "Apache-2.0",
"dependencies": {
"@vercel/cli-config": "0.3.1",
"@vercel/cli-exec": "1.0.1",
"jose": "^5.9.6"
},
"engines": {
"node": ">= 20"
}
},
"node_modules/@vercel/oidc/node_modules/jose": {
"version": "5.10.0",
"resolved": "https://registry.npmjs.org/jose/-/jose-5.10.0.tgz",
"integrity": "sha512-s+3Al/p9g32Iq+oqXxkW//7jk2Vig6FF1CFqzVXoTUXt2qz89YWbL+OwS17NFYEvxC35n0FKeGO2LGYSxeM2Gg==",
"license": "MIT",
"funding": {
"url": "https://github.com/sponsors/panva"
}
},
"node_modules/@visx/curve": { "node_modules/@visx/curve": {
"version": "4.0.1-alpha.0", "version": "4.0.1-alpha.0",
"resolved": "https://registry.npmjs.org/@visx/curve/-/curve-4.0.1-alpha.0.tgz", "resolved": "https://registry.npmjs.org/@visx/curve/-/curve-4.0.1-alpha.0.tgz",
@@ -3383,6 +3455,15 @@
"node": ">= 0.4" "node": ">= 0.4"
} }
}, },
"node_modules/async-retry": {
"version": "1.3.3",
"resolved": "https://registry.npmjs.org/async-retry/-/async-retry-1.3.3.tgz",
"integrity": "sha512-wfr/jstw9xNi/0teMHrRW7dsz3Lt5ARhYNZ2ewpadnhaIp5mbALhOAP+EAdsC7t4Z6wqsDVv9+W6gm1Dk9mEyw==",
"license": "MIT",
"dependencies": {
"retry": "0.13.1"
}
},
"node_modules/available-typed-arrays": { "node_modules/available-typed-arrays": {
"version": "1.0.7", "version": "1.0.7",
"resolved": "https://registry.npmjs.org/available-typed-arrays/-/available-typed-arrays-1.0.7.tgz", "resolved": "https://registry.npmjs.org/available-typed-arrays/-/available-typed-arrays-1.0.7.tgz",
@@ -4873,6 +4954,35 @@
"integrity": "sha512-mlsTRyGaPBjPedk6Bvw+aqbsXDtoAyAzm5MO7JgU+yVRyMQ5O8bD4Kcci7BS85f93veegeCPkL8R4GLClnjLFw==", "integrity": "sha512-mlsTRyGaPBjPedk6Bvw+aqbsXDtoAyAzm5MO7JgU+yVRyMQ5O8bD4Kcci7BS85f93veegeCPkL8R4GLClnjLFw==",
"license": "MIT" "license": "MIT"
}, },
"node_modules/execa": {
"version": "5.1.1",
"resolved": "https://registry.npmjs.org/execa/-/execa-5.1.1.tgz",
"integrity": "sha512-8uSpZZocAZRBAPIEINJj3Lo9HyGitllczc27Eh5YYojjMFMn8yHMDMaUHE2Jqfq05D/wucwI4JGURyXt1vchyg==",
"license": "MIT",
"dependencies": {
"cross-spawn": "^7.0.3",
"get-stream": "^6.0.0",
"human-signals": "^2.1.0",
"is-stream": "^2.0.0",
"merge-stream": "^2.0.0",
"npm-run-path": "^4.0.1",
"onetime": "^5.1.2",
"signal-exit": "^3.0.3",
"strip-final-newline": "^2.0.0"
},
"engines": {
"node": ">=10"
},
"funding": {
"url": "https://github.com/sindresorhus/execa?sponsor=1"
}
},
"node_modules/execa/node_modules/signal-exit": {
"version": "3.0.7",
"resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-3.0.7.tgz",
"integrity": "sha512-wnD2ZE+l+SPC/uoS0vXeE9L1+0wuaMqKlfz9AMUo38JsyLSBWSFcHR1Rri62LZc12vLr1gb3jl7iwQhgwpAbGQ==",
"license": "ISC"
},
"node_modules/exsolve": { "node_modules/exsolve": {
"version": "1.2.0", "version": "1.2.0",
"resolved": "https://registry.npmjs.org/exsolve/-/exsolve-1.2.0.tgz", "resolved": "https://registry.npmjs.org/exsolve/-/exsolve-1.2.0.tgz",
@@ -5279,6 +5389,18 @@
"node": ">= 0.4" "node": ">= 0.4"
} }
}, },
"node_modules/get-stream": {
"version": "6.0.1",
"resolved": "https://registry.npmjs.org/get-stream/-/get-stream-6.0.1.tgz",
"integrity": "sha512-ts6Wi+2j3jQjqi70w5AlN8DFnkSwC+MqmxEzdEALB2qXZYV3X/b1CTfgPLGJNMeAWxdPfU8FO1ms3NUfaHCPYg==",
"license": "MIT",
"engines": {
"node": ">=10"
},
"funding": {
"url": "https://github.com/sponsors/sindresorhus"
}
},
"node_modules/get-symbol-description": { "node_modules/get-symbol-description": {
"version": "1.1.0", "version": "1.1.0",
"resolved": "https://registry.npmjs.org/get-symbol-description/-/get-symbol-description-1.1.0.tgz", "resolved": "https://registry.npmjs.org/get-symbol-description/-/get-symbol-description-1.1.0.tgz",
@@ -5504,6 +5626,15 @@
"hermes-estree": "0.25.1" "hermes-estree": "0.25.1"
} }
}, },
"node_modules/human-signals": {
"version": "2.1.0",
"resolved": "https://registry.npmjs.org/human-signals/-/human-signals-2.1.0.tgz",
"integrity": "sha512-B4FFZ6q/T2jhhksgkbEW3HBvWIfDW85snkQgawt07S7J5QXTk6BkNV+0yAeZrM5QpMAdYlocGoljn0sJ/WQkFw==",
"license": "Apache-2.0",
"engines": {
"node": ">=10.17.0"
}
},
"node_modules/iconv-lite": { "node_modules/iconv-lite": {
"version": "0.7.3", "version": "0.7.3",
"resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.7.3.tgz", "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.7.3.tgz",
@@ -5675,6 +5806,29 @@
"url": "https://github.com/sponsors/ljharb" "url": "https://github.com/sponsors/ljharb"
} }
}, },
"node_modules/is-buffer": {
"version": "2.0.5",
"resolved": "https://registry.npmjs.org/is-buffer/-/is-buffer-2.0.5.tgz",
"integrity": "sha512-i2R6zNFDwgEHJyQUtJEk0XFi1i0dPFn/oqjK3/vPCcDeJvW5NQ83V8QbicfF1SupOaB0h8ntgBC2YiE7dfyctQ==",
"funding": [
{
"type": "github",
"url": "https://github.com/sponsors/feross"
},
{
"type": "patreon",
"url": "https://www.patreon.com/feross"
},
{
"type": "consulting",
"url": "https://feross.org/support"
}
],
"license": "MIT",
"engines": {
"node": ">=4"
}
},
"node_modules/is-bun-module": { "node_modules/is-bun-module": {
"version": "2.0.0", "version": "2.0.0",
"resolved": "https://registry.npmjs.org/is-bun-module/-/is-bun-module-2.0.0.tgz", "resolved": "https://registry.npmjs.org/is-bun-module/-/is-bun-module-2.0.0.tgz",
@@ -5863,6 +6017,12 @@
"url": "https://github.com/sponsors/ljharb" "url": "https://github.com/sponsors/ljharb"
} }
}, },
"node_modules/is-node-process": {
"version": "1.2.0",
"resolved": "https://registry.npmjs.org/is-node-process/-/is-node-process-1.2.0.tgz",
"integrity": "sha512-Vg4o6/fqPxIjtxgUH5QLJhwZ7gW5diGCVlXpuUfELC62CuxM1iHcRe51f2W1FDy04Ai4KJkagKjx3XaqyfRKXw==",
"license": "MIT"
},
"node_modules/is-number": { "node_modules/is-number": {
"version": "7.0.0", "version": "7.0.0",
"resolved": "https://registry.npmjs.org/is-number/-/is-number-7.0.0.tgz", "resolved": "https://registry.npmjs.org/is-number/-/is-number-7.0.0.tgz",
@@ -5944,6 +6104,18 @@
"url": "https://github.com/sponsors/ljharb" "url": "https://github.com/sponsors/ljharb"
} }
}, },
"node_modules/is-stream": {
"version": "2.0.1",
"resolved": "https://registry.npmjs.org/is-stream/-/is-stream-2.0.1.tgz",
"integrity": "sha512-hFoiJiTl63nn+kstHGBtewWSKnQLpyb155KHheA1l39uvtO9nWIop1p3udqPcUd/xbF1VLMO4n7OI6p7RbngDg==",
"license": "MIT",
"engines": {
"node": ">=8"
},
"funding": {
"url": "https://github.com/sponsors/sindresorhus"
}
},
"node_modules/is-string": { "node_modules/is-string": {
"version": "1.1.1", "version": "1.1.1",
"resolved": "https://registry.npmjs.org/is-string/-/is-string-1.1.1.tgz", "resolved": "https://registry.npmjs.org/is-string/-/is-string-1.1.1.tgz",
@@ -6601,6 +6773,12 @@
"node": ">= 0.4" "node": ">= 0.4"
} }
}, },
"node_modules/merge-stream": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/merge-stream/-/merge-stream-2.0.0.tgz",
"integrity": "sha512-abv/qOcuPfk3URPfDzmZU1LKmuw8kT+0nIHvKrKgFrwifol/doWcdA4ZqsWQ8ENrFKkd67Mfpo/LovbIUsbt3w==",
"license": "MIT"
},
"node_modules/merge2": { "node_modules/merge2": {
"version": "1.4.1", "version": "1.4.1",
"resolved": "https://registry.npmjs.org/merge2/-/merge2-1.4.1.tgz", "resolved": "https://registry.npmjs.org/merge2/-/merge2-1.4.1.tgz",
@@ -6625,6 +6803,15 @@
"node": ">=8.6" "node": ">=8.6"
} }
}, },
"node_modules/mimic-fn": {
"version": "2.1.0",
"resolved": "https://registry.npmjs.org/mimic-fn/-/mimic-fn-2.1.0.tgz",
"integrity": "sha512-OqbOk5oEQeAZ8WXWydlu9HJjz9WVdEIvamMCcXmuqUYjTknH/sqsWvhQ3vgwKFRR1HpjvNBKQ37nbJgYzGqGcg==",
"license": "MIT",
"engines": {
"node": ">=6"
}
},
"node_modules/minimatch": { "node_modules/minimatch": {
"version": "3.1.5", "version": "3.1.5",
"resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.5.tgz", "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.5.tgz",
@@ -6850,6 +7037,18 @@
"node": ">=0.10.0" "node": ">=0.10.0"
} }
}, },
"node_modules/npm-run-path": {
"version": "4.0.1",
"resolved": "https://registry.npmjs.org/npm-run-path/-/npm-run-path-4.0.1.tgz",
"integrity": "sha512-S48WzZW777zhNIrn7gxOlISNAqi9ZC/uQFnRdbeIHhZhCA6UqpkOT8T1G7BvfdgP4Er8gF4sUbaS0i7QvIfCWw==",
"license": "MIT",
"dependencies": {
"path-key": "^3.0.0"
},
"engines": {
"node": ">=8"
}
},
"node_modules/object-assign": { "node_modules/object-assign": {
"version": "4.1.1", "version": "4.1.1",
"resolved": "https://registry.npmjs.org/object-assign/-/object-assign-4.1.1.tgz", "resolved": "https://registry.npmjs.org/object-assign/-/object-assign-4.1.1.tgz",
@@ -6979,6 +7178,21 @@
"integrity": "sha512-65S/5gk9YSsaRjcyf7Nfa6h/d3E8/1gslpXfI4W7Dxn/oap8IKRuNT5VXkLQ1YFKIEg4apRY4Pj6aiwFzrDdmw==", "integrity": "sha512-65S/5gk9YSsaRjcyf7Nfa6h/d3E8/1gslpXfI4W7Dxn/oap8IKRuNT5VXkLQ1YFKIEg4apRY4Pj6aiwFzrDdmw==",
"license": "MIT" "license": "MIT"
}, },
"node_modules/onetime": {
"version": "5.1.2",
"resolved": "https://registry.npmjs.org/onetime/-/onetime-5.1.2.tgz",
"integrity": "sha512-kbpaSSGJTWdAY5KPVeMOKXSrPtr8C8C7wodJbcsd51jRnmD+GZu8Y0VoU6Dm5Z4vWr0Ig/1NKuWRKf7j5aaYSg==",
"license": "MIT",
"dependencies": {
"mimic-fn": "^2.1.0"
},
"engines": {
"node": ">=6"
},
"funding": {
"url": "https://github.com/sponsors/sindresorhus"
}
},
"node_modules/optionator": { "node_modules/optionator": {
"version": "0.9.4", "version": "0.9.4",
"resolved": "https://registry.npmjs.org/optionator/-/optionator-0.9.4.tgz", "resolved": "https://registry.npmjs.org/optionator/-/optionator-0.9.4.tgz",
@@ -6997,6 +7211,15 @@
"node": ">= 0.8.0" "node": ">= 0.8.0"
} }
}, },
"node_modules/os-paths": {
"version": "4.4.0",
"resolved": "https://registry.npmjs.org/os-paths/-/os-paths-4.4.0.tgz",
"integrity": "sha512-wrAwOeXp1RRMFfQY8Sy7VaGVmPocaLwSFOYCGKSyo8qmJ+/yaafCl5BCA1IQZWqFSRBrKDYFeR9d/VyQzfH/jg==",
"license": "MIT",
"engines": {
"node": ">= 6.0"
}
},
"node_modules/own-keys": { "node_modules/own-keys": {
"version": "1.0.2", "version": "1.0.2",
"resolved": "https://registry.npmjs.org/own-keys/-/own-keys-1.0.2.tgz", "resolved": "https://registry.npmjs.org/own-keys/-/own-keys-1.0.2.tgz",
@@ -7814,6 +8037,15 @@
"node": ">=10" "node": ">=10"
} }
}, },
"node_modules/retry": {
"version": "0.13.1",
"resolved": "https://registry.npmjs.org/retry/-/retry-0.13.1.tgz",
"integrity": "sha512-XQBQ3I8W1Cge0Seh+6gjj03LbmRFWuoszgK9ooCpwYIrhhoO80pfq4cUkU5DkknwfOfFteRwlZ56PYOGYyFWdg==",
"license": "MIT",
"engines": {
"node": ">= 4"
}
},
"node_modules/reusify": { "node_modules/reusify": {
"version": "1.1.0", "version": "1.1.0",
"resolved": "https://registry.npmjs.org/reusify/-/reusify-1.1.0.tgz", "resolved": "https://registry.npmjs.org/reusify/-/reusify-1.1.0.tgz",
@@ -8388,6 +8620,15 @@
"node": ">=4" "node": ">=4"
} }
}, },
"node_modules/strip-final-newline": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/strip-final-newline/-/strip-final-newline-2.0.0.tgz",
"integrity": "sha512-BrpvfNAE3dcvq7ll3xVumzjKjZQ5tI1sEUIKr3Uoks0XUl45St3FlatVqef9prk4jRDzhW6WZg+3bk93y6pLjA==",
"license": "MIT",
"engines": {
"node": ">=6"
}
},
"node_modules/strip-json-comments": { "node_modules/strip-json-comments": {
"version": "3.1.1", "version": "3.1.1",
"resolved": "https://registry.npmjs.org/strip-json-comments/-/strip-json-comments-3.1.1.tgz", "resolved": "https://registry.npmjs.org/strip-json-comments/-/strip-json-comments-3.1.1.tgz",
@@ -8471,6 +8712,18 @@
"url": "https://opencollective.com/webpack" "url": "https://opencollective.com/webpack"
} }
}, },
"node_modules/throttleit": {
"version": "2.1.0",
"resolved": "https://registry.npmjs.org/throttleit/-/throttleit-2.1.0.tgz",
"integrity": "sha512-nt6AMGKW1p/70DF/hGBdJB57B8Tspmbp5gfJ8ilhLnt7kkr2ye7hzD6NVG8GGErk2HWF34igrL2CXmNIkzKqKw==",
"license": "MIT",
"engines": {
"node": ">=18"
},
"funding": {
"url": "https://github.com/sponsors/sindresorhus"
}
},
"node_modules/tiny-invariant": { "node_modules/tiny-invariant": {
"version": "1.3.3", "version": "1.3.3",
"resolved": "https://registry.npmjs.org/tiny-invariant/-/tiny-invariant-1.3.3.tgz", "resolved": "https://registry.npmjs.org/tiny-invariant/-/tiny-invariant-1.3.3.tgz",
@@ -8765,6 +9018,15 @@
"url": "https://github.com/sponsors/ljharb" "url": "https://github.com/sponsors/ljharb"
} }
}, },
"node_modules/undici": {
"version": "6.29.1",
"resolved": "https://registry.npmjs.org/undici/-/undici-6.29.1.tgz",
"integrity": "sha512-EvRlUt/QqAEvXdQeRMYUfwOQsfzpDztykrG2owGEE/rBOBoYv9uF39ZzsNDh4lTFHhTr2XOZjKkYgueD12ZmGA==",
"license": "MIT",
"engines": {
"node": ">=18.17"
}
},
"node_modules/undici-types": { "node_modules/undici-types": {
"version": "6.21.0", "version": "6.21.0",
"resolved": "https://registry.npmjs.org/undici-types/-/undici-types-6.21.0.tgz", "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-6.21.0.tgz",
@@ -9029,6 +9291,31 @@
} }
} }
}, },
"node_modules/xdg-app-paths": {
"version": "5.5.1",
"resolved": "https://registry.npmjs.org/xdg-app-paths/-/xdg-app-paths-5.5.1.tgz",
"integrity": "sha512-hI3flOB4PLZIy5prbtTpirobtPE2ZtZ52szO+2mM9Efp6ErM398La+C1lIpNWDfNoQk+6Lsi6nMcCwVB7pxeMQ==",
"license": "MIT",
"dependencies": {
"os-paths": "^4.0.1",
"xdg-portable": "^7.2.0"
},
"engines": {
"node": ">= 6.0"
}
},
"node_modules/xdg-portable": {
"version": "7.3.0",
"resolved": "https://registry.npmjs.org/xdg-portable/-/xdg-portable-7.3.0.tgz",
"integrity": "sha512-sqMMuL1rc0FmMBOzCpd0yuy9trqF2yTTVe+E9ogwCSWQCdDEtQUwrZPT6AxqtsFGRNxycgncbP/xmOOSPw5ZUw==",
"license": "MIT",
"dependencies": {
"os-paths": "^4.0.1"
},
"engines": {
"node": ">= 6.0"
}
},
"node_modules/xtend": { "node_modules/xtend": {
"version": "4.0.2", "version": "4.0.2",
"resolved": "https://registry.npmjs.org/xtend/-/xtend-4.0.2.tgz", "resolved": "https://registry.npmjs.org/xtend/-/xtend-4.0.2.tgz",
+1
View File
@@ -21,6 +21,7 @@
"@anthropic-ai/sdk": "^1.12.0", "@anthropic-ai/sdk": "^1.12.0",
"@prisma/adapter-pg": "^7.9.1", "@prisma/adapter-pg": "^7.9.1",
"@prisma/client": "^7.9.1", "@prisma/client": "^7.9.1",
"@vercel/blob": "^2.9.0",
"dotenv": "^17.3.1", "dotenv": "^17.3.1",
"jose": "^6.2.8", "jose": "^6.2.8",
"next": "16.3.0", "next": "16.3.0",
+6 -4
View File
@@ -1,11 +1,13 @@
// Service worker: installable app shell + offline fallback. // Service worker: installable app shell + offline fallback.
// Never caches API responses or page HTML — they carry per-user, per-page data. // 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 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) => { 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(); self.skipWaiting();
}); });
@@ -29,7 +31,7 @@ self.addEventListener("fetch", (event) => {
} }
// Build assets are content-hashed: cache-first is safe. // 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( event.respondWith(
caches.match(req).then( caches.match(req).then(
(hit) => (hit) =>
+2 -1
View File
@@ -3,7 +3,8 @@
import "dotenv/config"; import "dotenv/config";
const PORT = process.env.PORT || 3000; 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; const SECRET = process.env.CRON_SECRET;
if (!SECRET) { if (!SECRET) {
+2 -1
View File
@@ -1,3 +1,4 @@
import { BASE_PATH } from "@/lib/base-path";
import { NextResponse } from "next/server"; import { NextResponse } from "next/server";
import { prisma } from "@/lib/db"; import { prisma } from "@/lib/db";
import { requireUser } from "@/lib/auth/user"; import { requireUser } from "@/lib/auth/user";
@@ -39,7 +40,7 @@ export async function POST(req: Request) {
httpOnly: true, httpOnly: true,
secure: process.env.NODE_ENV === "production", secure: process.env.NODE_ENV === "production",
sameSite: "strict", sameSite: "strict",
path: "/", path: BASE_PATH || "/",
maxAge: SESSION_DURATION_SECONDS, maxAge: SESSION_DURATION_SECONDS,
}); });
return res; return res;
+2 -1
View File
@@ -1,8 +1,9 @@
import { BASE_PATH } from "@/lib/base-path";
import { NextResponse } from "next/server"; import { NextResponse } from "next/server";
import { COOKIE_NAME } from "@/lib/auth/session"; import { COOKIE_NAME } from "@/lib/auth/session";
export async function POST() { export async function POST() {
const res = NextResponse.json({ ok: true }); const res = NextResponse.json({ ok: true });
res.cookies.delete(COOKIE_NAME); res.cookies.delete({ name: COOKIE_NAME, path: BASE_PATH || "/" });
return res; return res;
} }
@@ -1,3 +1,4 @@
import { appUrl } from "@/lib/base-path";
import { NextResponse } from "next/server"; import { NextResponse } from "next/server";
import { import {
authorizeUrl, authorizeUrl,
@@ -19,7 +20,7 @@ export async function GET(req: Request, ctx: RouteContext<"/api/auth/oauth/[prov
const url = new URL(req.url); const url = new URL(req.url);
const provider = parseProvider(raw); const provider = parseProvider(raw);
if (!provider || !enabledProviders().includes(provider)) { 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, { const { nonce, cookie } = await createSocialState(provider, {
+2 -1
View File
@@ -1,3 +1,4 @@
import { BASE_PATH } from "@/lib/base-path";
import { cookies } from "next/headers"; import { cookies } from "next/headers";
import { prisma } from "@/lib/db"; import { prisma } from "@/lib/db";
import { encryptToken } from "@/lib/crypto/tokenBox"; import { encryptToken } from "@/lib/crypto/tokenBox";
@@ -22,7 +23,7 @@ export async function GET(req: Request) {
const url = new URL(req.url); const url = new URL(req.url);
const jar = await cookies(); const jar = await cookies();
const stateCookie = jar.get(OAUTH_STATE_COOKIE)?.value; 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")); const userId = await verifyOAuthState(stateCookie, url.searchParams.get("state"));
if (!userId) return hop(`/pages?fb_error=${encodeURIComponent("ลิงก์เชื่อมหมดอายุหรือไม่ถูกต้อง ลองกดเชื่อมใหม่")}`); if (!userId) return hop(`/pages?fb_error=${encodeURIComponent("ลิงก์เชื่อมหมดอายุหรือไม่ถูกต้อง ลองกดเชื่อมใหม่")}`);
+5 -3
View File
@@ -1,3 +1,4 @@
import { BASE_PATH, appUrl } from "@/lib/base-path";
import { NextResponse } from "next/server"; import { NextResponse } from "next/server";
import { getCurrentUser, isSuperadmin } from "@/lib/auth/user"; import { getCurrentUser, isSuperadmin } from "@/lib/auth/user";
import { authorizeUrl, createOAuthState, OAUTH_STATE_COOKIE } from "@/lib/facebook/oauth"; 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. */ /** SUPERADMIN only: redirects to the Facebook consent dialog. */
export async function GET(req: Request) { export async function GET(req: Request) {
const origin = new URL(req.url).origin; const origin = new URL(req.url).origin;
const root = appUrl(origin);
const user = await getCurrentUser(); 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 { try {
const { nonce, cookie } = await createOAuthState(user.id); const { nonce, cookie } = await createOAuthState(user.id);
@@ -17,12 +19,12 @@ export async function GET(req: Request) {
secure: process.env.NODE_ENV === "production", secure: process.env.NODE_ENV === "production",
// Lax: must survive the top-level redirect back from facebook.com. // Lax: must survive the top-level redirect back from facebook.com.
sameSite: "lax", sameSite: "lax",
path: "/api/facebook/oauth", path: `${BASE_PATH}/api/facebook/oauth`,
maxAge: 600, maxAge: 600,
}); });
return res; return res;
} catch (e) { } catch (e) {
const msg = safeFacebookErrorMessage(e, "fb:oauth:start"); 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)}`);
} }
} }
+4 -3
View File
@@ -1,5 +1,6 @@
import { appUrl } from "@/lib/base-path";
import { NextResponse } from "next/server"; import { NextResponse } from "next/server";
import { putLocalBlob } from "@/lib/storage/local-blob"; import { putBlob } from "@/lib/storage/blob";
import { requirePageAction } from "@/lib/auth/user"; import { requirePageAction } from "@/lib/auth/user";
import { errorResponse } from "@/lib/http"; import { errorResponse } from "@/lib/http";
@@ -26,8 +27,8 @@ export async function POST(req: Request) {
try { try {
const ext = file.type === "image/png" ? "png" : "jpg"; 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 putLocalBlob(`posts/${pageId}/image.${ext}`, file, { contentType: file.type }, baseUrl); const blob = await putBlob(`posts/${pageId}/image.${ext}`, file, { contentType: file.type }, baseUrl);
return NextResponse.json({ url: blob.url }); return NextResponse.json({ url: blob.url });
} catch (e) { } catch (e) {
return errorResponse(e, "upload"); return errorResponse(e, "upload");
+3 -2
View File
@@ -1,4 +1,5 @@
"use client"; "use client";
import { withBase } from "@/lib/base-path";
import { useState } from "react"; import { useState } from "react";
import { useRouter } from "next/navigation"; import { useRouter } from "next/navigation";
@@ -17,7 +18,7 @@ export default function ChangePasswordPage() {
if (newPassword !== confirm) return setError("รหัสผ่านใหม่ทั้งสองช่องไม่ตรงกัน"); if (newPassword !== confirm) return setError("รหัสผ่านใหม่ทั้งสองช่องไม่ตรงกัน");
setBusy(true); setBusy(true);
setError(null); setError(null);
const res = await fetch("/api/auth/change-password", { const res = await fetch(withBase("/api/auth/change-password"), {
method: "POST", method: "POST",
headers: { "Content-Type": "application/json" }, headers: { "Content-Type": "application/json" },
body: JSON.stringify({ currentPassword, newPassword }), body: JSON.stringify({ currentPassword, newPassword }),
@@ -30,7 +31,7 @@ export default function ChangePasswordPage() {
} }
async function logout() { async function logout() {
await fetch("/api/auth/logout", { method: "POST" }); await fetch(withBase("/api/auth/logout"), { method: "POST" });
router.replace("/login"); router.replace("/login");
} }
+93
View File
@@ -0,0 +1,93 @@
Copyright 2019 The Anuphan Project Authors (https://github.com/cadsondemak/Anuphan)
This Font Software is licensed under the SIL Open Font License, Version 1.1.
This license is copied below, and is also available with a FAQ at:
https://scripts.sil.org/OFL
-----------------------------------------------------------
SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
-----------------------------------------------------------
PREAMBLE
The goals of the Open Font License (OFL) are to stimulate worldwide
development of collaborative font projects, to support the font creation
efforts of academic and linguistic communities, and to provide a free and
open framework in which fonts may be shared and improved in partnership
with others.
The OFL allows the licensed fonts to be used, studied, modified and
redistributed freely as long as they are not sold by themselves. The
fonts, including any derivative works, can be bundled, embedded,
redistributed and/or sold with any software provided that any reserved
names are not used by derivative works. The fonts and derivatives,
however, cannot be released under any other type of license. The
requirement for fonts to remain under this license does not apply
to any document created using the fonts or their derivatives.
DEFINITIONS
"Font Software" refers to the set of files released by the Copyright
Holder(s) under this license and clearly marked as such. This may
include source files, build scripts and documentation.
"Reserved Font Name" refers to any names specified as such after the
copyright statement(s).
"Original Version" refers to the collection of Font Software components as
distributed by the Copyright Holder(s).
"Modified Version" refers to any derivative made by adding to, deleting,
or substituting -- in part or in whole -- any of the components of the
Original Version, by changing formats or by porting the Font Software to a
new environment.
"Author" refers to any designer, engineer, programmer, technical
writer or other person who contributed to the Font Software.
PERMISSION & CONDITIONS
Permission is hereby granted, free of charge, to any person obtaining
a copy of the Font Software, to use, study, copy, merge, embed, modify,
redistribute, and sell modified and unmodified copies of the Font
Software, subject to the following conditions:
1) Neither the Font Software nor any of its individual components,
in Original or Modified Versions, may be sold by itself.
2) Original or Modified Versions of the Font Software may be bundled,
redistributed and/or sold with any software, provided that each copy
contains the above copyright notice and this license. These can be
included either as stand-alone text files, human-readable headers or
in the appropriate machine-readable metadata fields within text or
binary files as long as those fields can be easily viewed by the user.
3) No Modified Version of the Font Software may use the Reserved Font
Name(s) unless explicit written permission is granted by the corresponding
Copyright Holder. This restriction only applies to the primary font name as
presented to the users.
4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
Software shall not be used to promote, endorse or advertise any
Modified Version, except to acknowledge the contribution(s) of the
Copyright Holder(s) and the Author(s) or with their explicit written
permission.
5) The Font Software, modified or unmodified, in part or in whole,
must be distributed entirely under this license, and must not be
distributed under any other license. The requirement for fonts to
remain under this license does not apply to any document created
using the Font Software.
TERMINATION
This license becomes null and void if any of the above conditions are
not met.
DISCLAIMER
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
OTHER DEALINGS IN THE FONT SOFTWARE.
Binary file not shown.
+8 -5
View File
@@ -1,11 +1,14 @@
import { withBase } from "@/lib/base-path";
import type { Metadata, Viewport } from "next"; import type { Metadata, Viewport } from "next";
import { Anuphan } from "next/font/google"; import localFont from "next/font/local";
import { ServiceWorker } from "@/components/ServiceWorker"; import { ServiceWorker } from "@/components/ServiceWorker";
import "./globals.css"; import "./globals.css";
const anuphan = Anuphan({ // Self-hosted (not next/font/google): the Coolify build server has no egress
subsets: ["thai", "latin"], // to fonts.googleapis.com, which crashed `npm run build` there.
weight: ["400", "500", "600", "700"], const anuphan = localFont({
src: "./fonts/Anuphan-Variable.ttf",
weight: "100 700",
variable: "--font-anuphan", variable: "--font-anuphan",
display: "swap", display: "swap",
}); });
@@ -15,7 +18,7 @@ export const metadata: Metadata = {
description: "วางแผน อนุมัติ และเผยแพร่โพสต์ของเพจ Facebook และ Instagram ในพื้นที่ทำงานเดียว", description: "วางแผน อนุมัติ และเผยแพร่โพสต์ของเพจ Facebook และ Instagram ในพื้นที่ทำงานเดียว",
applicationName: "จัดการเพจ", applicationName: "จัดการเพจ",
appleWebApp: { capable: true, title: "จัดการเพจ", statusBarStyle: "default" }, 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 }, formatDetection: { telephone: false },
}; };
+10 -9
View File
@@ -1,27 +1,28 @@
import { withBase } from "@/lib/base-path";
import type { MetadataRoute } from "next"; import type { MetadataRoute } from "next";
export default function manifest(): MetadataRoute.Manifest { export default function manifest(): MetadataRoute.Manifest {
return { return {
id: "/", id: withBase("/"),
name: "ระบบจัดการเพจ", name: "ระบบจัดการเพจ",
short_name: "จัดการเพจ", short_name: "จัดการเพจ",
description: "โพสต์ อนุมัติ ตอบแชท และดู insights ของเพจ Facebook และ Instagram", description: "โพสต์ อนุมัติ ตอบแชท และดู insights ของเพจ Facebook และ Instagram",
start_url: "/", start_url: withBase("/"),
scope: "/", scope: withBase("/"),
display: "standalone", display: "standalone",
orientation: "portrait", orientation: "portrait",
background_color: "#eef8ff", background_color: "#eef8ff",
theme_color: "#e0f2fe", theme_color: "#e0f2fe",
lang: "th", lang: "th",
icons: [ icons: [
{ src: "/icons/192", sizes: "192x192", type: "image/png", purpose: "any" }, { src: withBase("/icons/192"), sizes: "192x192", type: "image/png", purpose: "any" },
{ src: "/icons/512", sizes: "512x512", type: "image/png", purpose: "any" }, { src: withBase("/icons/512"), sizes: "512x512", type: "image/png", purpose: "any" },
{ src: "/icons/maskable-512", sizes: "512x512", type: "image/png", purpose: "maskable" }, { src: withBase("/icons/maskable-512"), sizes: "512x512", type: "image/png", purpose: "maskable" },
], ],
shortcuts: [ shortcuts: [
{ name: "สร้างโพสต์", short_name: "สร้างโพสต์", url: "/posts/new" }, { name: "สร้างโพสต์", short_name: "สร้างโพสต์", url: withBase("/posts/new") },
{ name: "Inbox", url: "/inbox" }, { name: "Inbox", url: withBase("/inbox") },
{ name: "ปฏิทิน", url: "/calendar" }, { name: "ปฏิทิน", url: withBase("/calendar") },
], ],
}; };
} }
+2 -1
View File
@@ -1,4 +1,5 @@
"use client"; "use client";
import { withBase } from "@/lib/base-path";
import { useEffect, useState } from "react"; import { useEffect, useState } from "react";
import { useRouter } from "next/navigation"; import { useRouter } from "next/navigation";
@@ -29,7 +30,7 @@ export function AccountForm({ initial }: { initial: { name: string; email: strin
form.set("removeAvatar", String(removeAvatar)); form.set("removeAvatar", String(removeAvatar));
if (file) form.set("avatar", file); if (file) form.set("avatar", file);
try { 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(() => ({})); const json = await response.json().catch(() => ({}));
if (!response.ok) throw new Error(json.error ?? "บันทึกไม่สำเร็จ"); if (!response.ok) throw new Error(json.error ?? "บันทึกไม่สำเร็จ");
toast.show("บันทึกโปรไฟล์แล้ว"); toast.show("บันทึกโปรไฟล์แล้ว");
+2 -1
View File
@@ -1,4 +1,5 @@
"use client"; "use client";
import { withBase } from "@/lib/base-path";
import { useEffect, useState } from "react"; import { useEffect, useState } from "react";
import Link from "next/link"; import Link from "next/link";
@@ -138,7 +139,7 @@ function BriefForm({
e.preventDefault(); e.preventDefault();
setError(null); setError(null);
setBusy(true); setBusy(true);
const res = await fetch("/api/analysis", { const res = await fetch(withBase("/api/analysis"), {
method: "POST", method: "POST",
headers: { "Content-Type": "application/json" }, headers: { "Content-Type": "application/json" },
body: JSON.stringify({ pageId, business, audience, goal, budgetBaht: Number(budget.replace(/,/g, "")), days: Number(days) }), body: JSON.stringify({ pageId, business, audience, goal, budgetBaht: Number(budget.replace(/,/g, "")), days: Number(days) }),
+2 -1
View File
@@ -1,4 +1,5 @@
"use client"; "use client";
import { withBase } from "@/lib/base-path";
import { useState } from "react"; import { useState } from "react";
import Link from "next/link"; import Link from "next/link";
@@ -40,7 +41,7 @@ export function CaptionAssistant({
const label = "refine" in input ? input.refine : "draft"; const label = "refine" in input ? input.refine : "draft";
setBusy(label); setBusy(label);
setError(null); setError(null);
const res = await fetch("/api/ai/caption", { const res = await fetch(withBase("/api/ai/caption"), {
method: "POST", method: "POST",
headers: { "Content-Type": "application/json" }, headers: { "Content-Type": "application/json" },
body: JSON.stringify({ pageId, targets, caption, ...input }), body: JSON.stringify({ pageId, targets, caption, ...input }),
+2 -1
View File
@@ -1,4 +1,5 @@
"use client"; "use client";
import { withBase } from "@/lib/base-path";
/* eslint-disable @next/next/no-img-element -- Graph CDN attachment URLs */ /* eslint-disable @next/next/no-img-element -- Graph CDN attachment URLs */
import { useCallback, useEffect, useState } from "react"; import { useCallback, useEffect, useState } from "react";
@@ -49,7 +50,7 @@ export function InboxView({ pageId, pageName, hasInstagram, canReply }: { pageId
const [error, setError] = useState<string | null>(null); const [error, setError] = useState<string | null>(null);
const [sending, setSending] = useState(false); 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. // Fetchers return data; state is only set in their promise callbacks.
const fetchList = useCallback(async (): Promise<{ conversations: Conversation[]; error?: string }> => { const fetchList = useCallback(async (): Promise<{ conversations: Conversation[]; error?: string }> => {
+3 -2
View File
@@ -1,4 +1,5 @@
"use client"; "use client";
import { withBase } from "@/lib/base-path";
import { useState } from "react"; import { useState } from "react";
import { useRouter, useSearchParams } from "next/navigation"; import { useRouter, useSearchParams } from "next/navigation";
@@ -75,7 +76,7 @@ export function LoginForm({ providers }: { providers: Provider[] }) {
e.preventDefault(); e.preventDefault();
setBusy(true); setBusy(true);
setError(null); setError(null);
const res = await fetch("/api/auth/login", { const res = await fetch(withBase("/api/auth/login"), {
method: "POST", method: "POST",
headers: { "Content-Type": "application/json" }, headers: { "Content-Type": "application/json" },
body: JSON.stringify({ email, password, remember }), body: JSON.stringify({ email, password, remember }),
@@ -92,7 +93,7 @@ export function LoginForm({ providers }: { providers: Provider[] }) {
function socialHref(p: Provider): string { function socialHref(p: Provider): string {
const q = new URLSearchParams({ from, remember: remember ? "1" : "0" }); 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 ( return (
+3 -2
View File
@@ -1,4 +1,5 @@
"use client"; "use client";
import { withBase } from "@/lib/base-path";
import { useEffect, useState } from "react"; import { useEffect, useState } from "react";
import { useRouter } from "next/navigation"; import { useRouter } from "next/navigation";
@@ -42,7 +43,7 @@ interface Member {
} }
async function api<T>(url: string, init?: RequestInit): Promise<{ ok: true; data: T } | { ok: false; error: string }> { async function api<T>(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(() => ({})); const body = await res.json().catch(() => ({}));
return res.ok ? { ok: true, data: body as T } : { ok: false, error: body.error ?? "ทำรายการไม่สำเร็จ" }; return res.ok ? { ok: true, data: body as T } : { ok: false, error: body.error ?? "ทำรายการไม่สำเร็จ" };
} }
@@ -211,7 +212,7 @@ export function PagesManager({
<h2>บัญชี Facebook</h2> <h2>บัญชี Facebook</h2>
{appConfigured ? ( {appConfigured ? (
// Full navigation (not <Link>): the start route redirects to facebook.com. // Full navigation (not <Link>): the start route redirects to facebook.com.
<a href="/api/facebook/oauth/start" className="btn btn-primary btn-sm ml-auto"> <a href={withBase("/api/facebook/oauth/start")} className="btn btn-primary btn-sm ml-auto">
<Icon name="link" size={14} /> {connections.length ? "เชื่อมบัญชีเพิ่ม / ขอสิทธิ์ใหม่" : "เข้าสู่ระบบด้วย Facebook"} <Icon name="link" size={14} /> {connections.length ? "เชื่อมบัญชีเพิ่ม / ขอสิทธิ์ใหม่" : "เข้าสู่ระบบด้วย Facebook"}
</a> </a>
) : ( ) : (
+2 -1
View File
@@ -1,4 +1,5 @@
"use client"; "use client";
import { withBase } from "@/lib/base-path";
import { useState } from "react"; import { useState } from "react";
import { Icon } from "./Icon"; import { Icon } from "./Icon";
@@ -28,7 +29,7 @@ export function PostCheck({ pageId, caption, targets, hasImage }: { pageId: stri
async function run() { async function run() {
setBusy(true); setBusy(true);
setError(null); setError(null);
const res = await fetch("/api/ai/check", { const res = await fetch(withBase("/api/ai/check"), {
method: "POST", method: "POST",
headers: { "Content-Type": "application/json" }, headers: { "Content-Type": "application/json" },
body: JSON.stringify({ pageId, caption, targets, hasImage }), body: JSON.stringify({ pageId, caption, targets, hasImage }),
+2 -1
View File
@@ -1,4 +1,5 @@
"use client"; "use client";
import { withBase } from "@/lib/base-path";
/* eslint-disable @next/next/no-img-element -- Blob URLs and Graph CDN images, not optimisable */ /* eslint-disable @next/next/no-img-element -- Blob URLs and Graph CDN images, not optimisable */
import { useRef, useState } from "react"; import { useRef, useState } from "react";
@@ -124,7 +125,7 @@ export function PostEditor({
setBusy(label); setBusy(label);
setError(null); setError(null);
try { 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(() => ({})); const body = await res.json().catch(() => ({}));
if (!res.ok) { if (!res.ok) {
setError(body.error ?? "ทำรายการไม่สำเร็จ"); setError(body.error ?? "ทำรายการไม่สำเร็จ");
+2 -1
View File
@@ -1,4 +1,5 @@
"use client"; "use client";
import { withBase } from "@/lib/base-path";
import { useState } from "react"; import { useState } from "react";
import { useRouter } from "next/navigation"; import { useRouter } from "next/navigation";
@@ -29,7 +30,7 @@ export function ProfileForm({
const [error, setError] = useState<string | null>(null); const [error, setError] = useState<string | null>(null);
async function request(path: string, method: string, body?: ShopProfile) { 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(() => ({})) : {}; const json = res ? await res.json().catch(() => ({})) : {};
return { ok: Boolean(res?.ok), json }; return { ok: Boolean(res?.ok), json };
} }
+2 -1
View File
@@ -1,4 +1,5 @@
"use client"; "use client";
import { withBase } from "@/lib/base-path";
import { useState } from "react"; import { useState } from "react";
import { useRouter } from "next/navigation"; import { useRouter } from "next/navigation";
@@ -12,7 +13,7 @@ export function RefreshInsightsButton({ pageId, variant = "on-band" }: { pageId:
async function refresh() { async function refresh() {
setBusy(true); setBusy(true);
const res = await fetch("/api/insights/refresh", { const res = await fetch(withBase("/api/insights/refresh"), {
method: "POST", method: "POST",
headers: { "Content-Type": "application/json" }, headers: { "Content-Type": "application/json" },
body: JSON.stringify({ pageId }), body: JSON.stringify({ pageId }),
+2 -1
View File
@@ -1,4 +1,5 @@
"use client"; "use client";
import { withBase } from "@/lib/base-path";
import { useState } from "react"; import { useState } from "react";
import Link from "next/link"; import Link from "next/link";
@@ -15,7 +16,7 @@ export function ReplyDrafts({ pageId, conversationId, onPick }: { pageId: string
async function draft() { async function draft() {
setBusy(true); setBusy(true);
setError(null); setError(null);
const res = await fetch("/api/ai/reply", { const res = await fetch(withBase("/api/ai/reply"), {
method: "POST", method: "POST",
headers: { "Content-Type": "application/json" }, headers: { "Content-Type": "application/json" },
body: JSON.stringify({ pageId, conversationId }), body: JSON.stringify({ pageId, conversationId }),
+4 -3
View File
@@ -1,4 +1,5 @@
"use client"; "use client";
import { withBase } from "@/lib/base-path";
import { useState } from "react"; import { useState } from "react";
import { useRouter } from "next/navigation"; import { useRouter } from "next/navigation";
@@ -41,7 +42,7 @@ export function RulesManager({ pageId, canEdit, rules }: { pageId: string; canEd
if (!editing) return; if (!editing) return;
setBusy(true); setBusy(true);
setError(null); setError(null);
const res = await fetch("/api/reply-rules", { const res = await fetch(withBase("/api/reply-rules"), {
method: "POST", method: "POST",
headers: { "Content-Type": "application/json" }, headers: { "Content-Type": "application/json" },
body: JSON.stringify({ ...editing, pageId, keywords: keywordsText }), 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) { async function toggle(rule: Rule) {
await fetch("/api/reply-rules", { await fetch(withBase("/api/reply-rules"), {
method: "POST", method: "POST",
headers: { "Content-Type": "application/json" }, headers: { "Content-Type": "application/json" },
body: JSON.stringify({ ...rule, pageId, isActive: !rule.isActive }), 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) { async function remove(rule: Rule) {
if (!window.confirm(`ลบกฎ "${rule.name}"?`)) return; 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(); router.refresh();
} }
+2 -1
View File
@@ -1,4 +1,5 @@
"use client"; "use client";
import { withBase } from "@/lib/base-path";
import { useEffect } from "react"; import { useEffect } from "react";
@@ -6,7 +7,7 @@ import { useEffect } from "react";
export function ServiceWorker() { export function ServiceWorker() {
useEffect(() => { useEffect(() => {
if (process.env.NODE_ENV !== "production" || !("serviceWorker" in navigator)) return; 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; return null;
} }
+3 -2
View File
@@ -1,4 +1,5 @@
"use client"; "use client";
import { withBase } from "@/lib/base-path";
import Link from "next/link"; import Link from "next/link";
import { usePathname, useRouter } from "next/navigation"; import { usePathname, useRouter } from "next/navigation";
@@ -127,7 +128,7 @@ export function Shell({
} }
async function logout() { async function logout() {
await fetch("/api/auth/logout", { method: "POST" }); await fetch(withBase("/api/auth/logout"), { method: "POST" });
router.replace("/login"); router.replace("/login");
router.refresh(); router.refresh();
} }
@@ -162,7 +163,7 @@ export function Shell({
<div className="flex items-center gap-3 px-1.5 pb-2"> <div className="flex items-center gap-3 px-1.5 pb-2">
<span className="w-9 h-9 rounded-[10px] overflow-hidden shrink-0 shadow-sm"> <span className="w-9 h-9 rounded-[10px] overflow-hidden shrink-0 shadow-sm">
{/* eslint-disable-next-line @next/next/no-img-element -- generated app icon route */} {/* eslint-disable-next-line @next/next/no-img-element -- generated app icon route */}
<img src="/icons/192" alt="" width={36} height={36} /> <img src={withBase("/icons/192")} alt="" width={36} height={36} />
</span> </span>
<div className="leading-tight flex-1 min-w-0"> <div className="leading-tight flex-1 min-w-0">
<div className="font-bold">ระบบจัดการเพจ</div> <div className="font-bold">ระบบจัดการเพจ</div>
+2 -1
View File
@@ -1,4 +1,5 @@
"use client"; "use client";
import { withBase } from "@/lib/base-path";
import { useState } from "react"; import { useState } from "react";
import { useRouter } from "next/navigation"; import { useRouter } from "next/navigation";
@@ -29,7 +30,7 @@ export function UsersManager({ users, currentUserId }: { users: UserRow[]; curre
setBusy(true); setBusy(true);
setError(null); setError(null);
setFlash(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(() => ({})); const data = await res.json().catch(() => ({}));
setBusy(false); setBusy(false);
if (!res.ok) { if (!res.ok) {
+2 -1
View File
@@ -1,4 +1,5 @@
"use client"; "use client";
import { withBase } from "@/lib/base-path";
import Link from "next/link"; import Link from "next/link";
import { useState } from "react"; 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; if (busy || !post || !canMove(post) || post.day === day) return;
setBusy(true); setBusy(true);
try { 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(); const body = await res.json();
if (!res.ok) throw new Error(body.error ?? "วางวันไม่สำเร็จ"); if (!res.ok) throw new Error(body.error ?? "วางวันไม่สำเร็จ");
toast.show(day ? "วางวันแล้ว · ยังไม่ได้ตั้งเวลาเผยแพร่" : "ย้ายกลับคิวที่ยังไม่วางแผนแล้ว"); toast.show(day ? "วางวันแล้ว · ยังไม่ได้ตั้งเวลาเผยแพร่" : "ย้ายกลับคิวที่ยังไม่วางแผนแล้ว");
+3 -2
View File
@@ -1,4 +1,5 @@
"use client"; "use client";
import { withBase } from "@/lib/base-path";
import { useState } from "react"; import { useState } from "react";
import Link from "next/link"; import Link from "next/link";
@@ -36,7 +37,7 @@ export function WeekPlanAssistant({ pageId, pageName, week, openDays }: { pageId
async function plan() { async function plan() {
setBusy("plan"); setBusy("plan");
setError(null); setError(null);
const res = await fetch("/api/ai/week-plan", { const res = await fetch(withBase("/api/ai/week-plan"), {
method: "POST", method: "POST",
headers: { "Content-Type": "application/json" }, headers: { "Content-Type": "application/json" },
body: JSON.stringify({ pageId, week, goal, count }), body: JSON.stringify({ pageId, week, goal, count }),
@@ -56,7 +57,7 @@ export function WeekPlanAssistant({ pageId, pageName, week, openDays }: { pageId
let created = 0; let created = 0;
let firstError: string | null = null; let firstError: string | null = null;
for (const p of chosen) { for (const p of chosen) {
const res = await fetch("/api/posts", { const res = await fetch(withBase("/api/posts"), {
method: "POST", method: "POST",
headers: { "Content-Type": "application/json" }, headers: { "Content-Type": "application/json" },
body: JSON.stringify({ pageId, title: p.title, caption: p.caption, targets: ["FACEBOOK"], aiAssisted: true, plannedAt: bkkMidnight(p.day).toISOString() }), body: JSON.stringify({ pageId, title: p.title, caption: p.caption, targets: ["FACEBOOK"], aiAssisted: true, plannedAt: bkkMidnight(p.day).toISOString() }),
+2 -1
View File
@@ -1,3 +1,4 @@
import { BASE_PATH } from "@/lib/base-path";
import { SignJWT, jwtVerify } from "jose"; import { SignJWT, jwtVerify } from "jose";
import type { GlobalRole } from "@prisma/client"; import type { GlobalRole } from "@prisma/client";
@@ -64,7 +65,7 @@ export function sessionCookieOptions(remember: boolean) {
httpOnly: true, httpOnly: true,
secure: process.env.NODE_ENV === "production", secure: process.env.NODE_ENV === "production",
sameSite: "strict" as const, sameSite: "strict" as const,
path: "/", path: BASE_PATH || "/",
...(remember ? { maxAge: SESSION_DURATION_SECONDS } : {}), ...(remember ? { maxAge: SESSION_DURATION_SECONDS } : {}),
}; };
} }
+10 -4
View File
@@ -1,3 +1,4 @@
import { BASE_PATH, appUrl } from "@/lib/base-path";
import { SignJWT, jwtVerify } from "jose"; import { SignJWT, jwtVerify } from "jose";
import type { AuthProvider } from "@prisma/client"; import type { AuthProvider } from "@prisma/client";
import { prisma } from "@/lib/db"; 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 type SocialProvider = (typeof SOCIAL_PROVIDERS)[number];
export const SOCIAL_STATE_COOKIE = "pm_social_oauth"; 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; export const SOCIAL_STATE_TTL_SECONDS = 10 * 60;
const DB_PROVIDER: Record<SocialProvider, AuthProvider> = { google: "GOOGLE", facebook: "FACEBOOK" }; const DB_PROVIDER: Record<SocialProvider, AuthProvider> = { google: "GOOGLE", facebook: "FACEBOOK" };
@@ -50,8 +51,13 @@ export interface SocialProfile {
} }
function credentials(provider: SocialProvider): { id: string; secret: string } | null { function credentials(provider: SocialProvider): { id: string; secret: string } | null {
const id = provider === "google" ? process.env.GOOGLE_CLIENT_ID : process.env.META_APP_ID; // Facebook Login for Business (the only Login product available to a Business-type
const secret = provider === "google" ? process.env.GOOGLE_CLIENT_SECRET : process.env.META_APP_SECRET; // app, which this project needs for Page/Messenger/Instagram) has no email/public_profile
// permission to request — only business asset permissions (pages_show_list, etc).
// There is no config_id that grants identity data, so this button stays disabled.
if (provider === "facebook") return null;
const id = process.env.GOOGLE_CLIENT_ID;
const secret = process.env.GOOGLE_CLIENT_SECRET;
return id && secret ? { id, secret } : null; return id && secret ? { id, secret } : null;
} }
@@ -70,7 +76,7 @@ export function safeRedirectPath(raw: string | null | undefined): string {
} }
function redirectUri(provider: SocialProvider, origin: string): 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 ---------- // ---------- state ----------
+20
View File
@@ -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 <Link>, router.push/replace and redirect() itself; this
* helper is for everything it does not touch: fetch(), plain <a>/<img>,
* 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(/\/+$/, "");
}
+4 -3
View File
@@ -5,12 +5,13 @@ import crypto from "node:crypto";
// yielding a garbage token. // yielding a garbage token.
const VERSION = "v1"; const VERSION = "v1";
// Derived via SHA-256 (always 32 bytes) rather than requiring the operator to
// supply exactly 32 raw bytes in base64 — any sufficiently random string works,
// including one a host platform (e.g. Coolify's SERVICE_PASSWORD_64_*) generates.
function key(): Buffer { function key(): Buffer {
const raw = process.env.TOKEN_ENCRYPTION_KEY; const raw = process.env.TOKEN_ENCRYPTION_KEY;
if (!raw) throw new Error("TOKEN_ENCRYPTION_KEY env var is not set"); if (!raw) throw new Error("TOKEN_ENCRYPTION_KEY env var is not set");
const buf = Buffer.from(raw, "base64"); return crypto.createHash("sha256").update(raw).digest();
if (buf.length !== 32) throw new Error("TOKEN_ENCRYPTION_KEY must be 32 bytes (base64)");
return buf;
} }
export function encryptToken(plain: string): string { export function encryptToken(plain: string): string {
+2 -1
View File
@@ -1,3 +1,4 @@
import { appUrl } from "@/lib/base-path";
import { SignJWT, jwtVerify } from "jose"; import { SignJWT, jwtVerify } from "jose";
import { GRAPH_API_VERSION, graphGet, UserFacingError } from "./client"; import { GRAPH_API_VERSION, graphGet, UserFacingError } from "./client";
@@ -40,7 +41,7 @@ export function appAccessToken(): string | null {
} }
export function oauthRedirectUri(origin: string): string { 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[] { export function oauthScopes(): string[] {
+2 -1
View File
@@ -1,3 +1,4 @@
import { withBase } from "@/lib/base-path";
import { NextResponse } from "next/server"; import { NextResponse } from "next/server";
import { safeFacebookErrorMessage, UserFacingError, FacebookApiError } from "@/lib/facebook/client"; 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. * this page is same-site. `path` must already be a validated same-origin path.
*/ */
export function htmlRedirect(path: string): Response { export function htmlRedirect(path: string): Response {
const safe = path.replace(/&/g, "&amp;").replace(/"/g, "&quot;").replace(/</g, "&lt;").replace(/>/g, "&gt;"); const safe = withBase(path).replace(/&/g, "&amp;").replace(/"/g, "&quot;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
const html = `<!doctype html><meta charset="utf-8"><meta http-equiv="refresh" content="0;url=${safe}"><title>กำลังกลับสู่ระบบ…</title><p style="font-family:system-ui;padding:24px">กำลังกลับสู่ระบบ… <a href="${safe}">ไปต่อ</a></p>`; const html = `<!doctype html><meta charset="utf-8"><meta http-equiv="refresh" content="0;url=${safe}"><title>กำลังกลับสู่ระบบ…</title><p style="font-family:system-ui;padding:24px">กำลังกลับสู่ระบบ… <a href="${safe}">ไปต่อ</a></p>`;
return new Response(html, { headers: { "content-type": "text/html; charset=utf-8", "cache-control": "no-store" } }); return new Response(html, { headers: { "content-type": "text/html; charset=utf-8", "cache-control": "no-store" } });
} }
+25
View File
@@ -0,0 +1,25 @@
import { putLocalBlob } from "./local-blob";
/**
* Picks the storage driver by env: Vercel Blob when a store is connected
* (`BLOB_STORE_ID` from OIDC-mode `vercel storage connect`, or a static
* `BLOB_READ_WRITE_TOKEN`), local disk otherwise (Coolify self-host, see
* local-blob.ts).
*/
export async function putBlob(
key: string,
file: File,
opts: { contentType: string },
baseUrl: string
): Promise<{ url: string }> {
if (process.env.BLOB_STORE_ID || process.env.BLOB_READ_WRITE_TOKEN) {
const { put } = await import("@vercel/blob");
const blob = await put(key, file, {
access: "public",
contentType: opts.contentType,
addRandomSuffix: true,
});
return { url: blob.url };
}
return putLocalBlob(key, file, opts, baseUrl);
}
+6 -3
View File
@@ -1,5 +1,6 @@
import { NextResponse } from "next/server"; import { NextResponse } from "next/server";
import type { NextRequest } from "next/server"; import type { NextRequest } from "next/server";
import { BASE_PATH } from "@/lib/base-path";
import { COOKIE_NAME, verifySessionToken } from "@/lib/auth/session"; import { COOKIE_NAME, verifySessionToken } from "@/lib/auth/session";
const PUBLIC_PATHS = [ const PUBLIC_PATHS = [
@@ -57,10 +58,12 @@ export async function proxy(request: NextRequest) {
if (pathname.startsWith("/api/")) { if (pathname.startsWith("/api/")) {
return NextResponse.json({ error: "unauthenticated" }, { status: 401 }); 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); loginUrl.searchParams.set("from", pathname);
const res = NextResponse.redirect(loginUrl); 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; return res;
} }
@@ -68,7 +71,7 @@ export async function proxy(request: NextRequest) {
if (pathname.startsWith("/api/")) { if (pathname.startsWith("/api/")) {
return NextResponse.json({ error: "ต้องเปลี่ยนรหัสผ่านก่อนใช้งานต่อ" }, { status: 403 }); 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(); return NextResponse.next();
+8
View File
@@ -0,0 +1,8 @@
{
"crons": [
{ "path": "/api/cron/insights-snapshot", "schedule": "0 2 * * *" },
{ "path": "/api/cron/reconcile-scheduled", "schedule": "0 3 * * *" },
{ "path": "/api/cron/token-health", "schedule": "30 3 * * *" },
{ "path": "/api/cron/ig-publisher", "schedule": "0 9 * * *" }
]
}