Initial commit: page-manager Next.js app with Coolify deploy support

Replace Vercel-specific infra (Cron, Blob) with self-hosted equivalents
for deployment to Coolify: in-container cron scheduler
(scripts/cron-runner.mjs) and disk-based upload storage served via
/api/uploads/[...path]. Add Dockerfile, .dockerignore, and /api/health
for container health checks.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
chaloemphong
2026-11-22 11:52:17 +07:00
commit 9d32552457
155 changed files with 22174 additions and 0 deletions
+23
View File
@@ -0,0 +1,23 @@
import sharp from "sharp";
import { z } from "zod";
export const accountProfileSchema = z.object({
name: z.string().trim().min(1, "กรอกชื่อที่แสดง").max(100, "ชื่อยาวเกิน 100 ตัวอักษร"),
bio: z.string().trim().max(500, "แนะนำตัวยาวเกิน 500 ตัวอักษร"),
}).strict();
export async function prepareAvatar(file: File): Promise<string> {
if (!["image/jpeg", "image/png", "image/webp"].includes(file.type)) {
throw new Error("รองรับรูป JPG, PNG และ WebP เท่านั้น");
}
if (!file.size || file.size > 2 * 1024 * 1024) throw new Error("รูปต้องมีขนาดไม่เกิน 2 MB");
try {
const image = sharp(Buffer.from(await file.arrayBuffer()), { limitInputPixels: 16_000_000 });
const metadata = await image.metadata();
if (!["jpeg", "png", "webp"].includes(metadata.format ?? "") || (metadata.pages ?? 1) > 1) throw new Error();
const buffer = await image.rotate().resize(256, 256, { fit: "cover" }).jpeg({ quality: 80 }).toBuffer();
return `data:image/jpeg;base64,${buffer.toString("base64")}`;
} catch {
throw new Error("อ่านรูปไม่ได้ ใช้รูป JPG, PNG หรือ WebP ที่ไม่ใช่ภาพเคลื่อนไหว");
}
}
+84
View File
@@ -0,0 +1,84 @@
import Anthropic from "@anthropic-ai/sdk";
import { zodOutputFormat } from "@anthropic-ai/sdk/helpers/zod";
import type * as z from "zod/v4";
import { prisma } from "@/lib/db";
import { UserFacingError } from "@/lib/facebook/client";
export const AI_MODEL = "claude-opus-5-5";
/** Successful AI calls allowed per page in any rolling 24 hours (cost guard). */
export const AI_DAILY_LIMIT_PER_PAGE = 30;
let client: Anthropic | null = null;
function getClient(): Anthropic {
if (!process.env.ANTHROPIC_API_KEY && !process.env.ANTHROPIC_AUTH_TOKEN) {
throw new UserFacingError("ยังไม่ได้ตั้งค่า AI — ผู้ดูแลระบบต้องใส่ ANTHROPIC_API_KEY ก่อน");
}
// Interactive routes: fail fast rather than hold the request for the SDK's 10-minute default.
client ??= new Anthropic({ timeout: 55_000, maxRetries: 1 });
return client;
}
function toUserFacing(e: unknown, kind: string): UserFacingError {
if (e instanceof UserFacingError) return e;
console.error(`[ai:${kind}] request failed`, e);
if (e instanceof Anthropic.AuthenticationError || e instanceof Anthropic.PermissionDeniedError) {
return new UserFacingError("API key ของ AI ใช้ไม่ได้ — ผู้ดูแลระบบต้องตรวจ ANTHROPIC_API_KEY");
}
if (e instanceof Anthropic.RateLimitError) return new UserFacingError("AI มีคนใช้มากหรือเกินโควตา ลองใหม่ในอีกสักครู่");
if (e instanceof Anthropic.APIConnectionError) return new UserFacingError("ติดต่อ AI ไม่ได้ ลองใหม่อีกครั้ง");
return new UserFacingError("AI ทำงานไม่สำเร็จ ลองใหม่อีกครั้ง");
}
/**
* One structured-output call to Claude, counted against the page's daily limit.
* Every failure becomes a UserFacingError with safe Thai text; details go to the server log.
*/
export async function generateStructured<S extends z.ZodType>(req: {
kind: "caption" | "profile" | "week-plan" | "check" | "reply";
pageId: string;
userId: string;
system: string;
prompt: string;
schema: S;
effort: "low" | "medium";
}): Promise<z.infer<S>> {
const since = new Date(Date.now() - 24 * 60 * 60 * 1000);
const used = await prisma.aiUsage.count({ where: { pageId: req.pageId, createdAt: { gte: since } } });
if (used >= AI_DAILY_LIMIT_PER_PAGE) {
throw new UserFacingError(`เพจนี้ใช้ AI ครบ ${AI_DAILY_LIMIT_PER_PAGE} ครั้งใน 24 ชั่วโมงแล้ว ลองใหม่ภายหลัง`);
}
let response;
try {
response = await getClient().messages.parse({
model: AI_MODEL,
max_tokens: 16000,
system: req.system,
output_config: { effort: req.effort, format: zodOutputFormat(req.schema) },
messages: [{ role: "user", content: req.prompt }],
});
} catch (e) {
throw toUserFacing(e, req.kind);
}
if (response.stop_reason === "refusal") {
console.warn(`[ai:${req.kind}] refused`, response.stop_details);
throw new UserFacingError("AI ไม่เขียนเนื้อหานี้ให้ ลองปรับหัวข้อหรือถ้อยคำ");
}
if (!response.parsed_output) {
console.error(`[ai:${req.kind}] no parsed output`, { stop_reason: response.stop_reason });
throw new UserFacingError("AI ตอบกลับไม่ครบ ลองใหม่อีกครั้ง");
}
await prisma.aiUsage.create({
data: {
pageId: req.pageId,
userId: req.userId,
kind: req.kind,
inputTokens: response.usage.input_tokens,
outputTokens: response.usage.output_tokens,
},
});
return response.parsed_output;
}
+13
View File
@@ -0,0 +1,13 @@
// Prompt text shared by the AI routes that write post captions.
export const CAPTION_RULES = `- Write natural, conversational Thai the way Thai shop owners post on Facebook. Brand or technical words may stay in English.
- Use only facts given in <shop_profile> and the request. Never invent prices, discounts, dates, phone numbers, URLs, statistics, awards or customer reviews. When a caption needs a missing fact, write a short Thai placeholder in square brackets, such as [ราคา] or [วันหมดโปร], for the owner to fill in.
- Follow the shop's tone, and never use anything listed under the shop's "ห้ามพูด" field.
- No exaggerated claims (cures, guaranteed results, before/after promises) — they break Meta's advertising policy and Thai FDA rules.
- Each caption is only the post text: no notes to the owner, no surrounding quotation marks.`;
export function platformRule(instagram: boolean): string {
return instagram
? "This caption is also posted to Instagram: end with 3-8 relevant hashtags, stay under 2,200 characters, and don't rely on clickable links — point people to the inbox or the link in the profile instead."
: "Facebook only: hashtags are optional (0-3).";
}
+44
View File
@@ -0,0 +1,44 @@
// Client-safe: no server imports. Shared by the AI routes and their UI.
export interface ShopProfile {
business: string;
audience: string;
tone: string;
avoid: string;
cta: string;
}
export const PROFILE_FIELDS: { key: keyof ShopProfile; label: string; hint: string; max: number; rows: number }[] = [
{ key: "business", label: "ขายอะไร / จุดเด่นของร้าน", hint: "สินค้าหรือบริการ ราคาโดยประมาณ ส่งที่ไหน ต่างจากร้านอื่นตรงไหน", max: 2000, rows: 4 },
{ key: "audience", label: "ลูกค้าหลักคือใคร", hint: "เช่น ผู้หญิงวัยทำงาน 25–40 ซื้อเป็นของขวัญ", max: 1000, rows: 2 },
{ key: "tone", label: "น้ำเสียงของเพจ", hint: "เช่น เป็นกันเอง เรียกลูกค้าว่า “คุณลูกค้า” ใช้ emoji พอประมาณ", max: 500, rows: 2 },
{ key: "avoid", label: "คำหรือเรื่องที่ห้ามพูด", hint: "เช่น ห้ามบอกว่ารักษาหาย ห้ามเทียบกับร้านอื่น ห้ามลงราคาส่ง", max: 1000, rows: 2 },
{ key: "cta", label: "ให้ลูกค้าติดต่อทางไหน", hint: "เช่น ทักแชทเพจ / โทร 08x-xxx-xxxx / LINE @shop", max: 500, rows: 2 },
];
export function parseProfile(body: Record<string, unknown>): { profile: ShopProfile } | { error: string } {
const profile = {} as ShopProfile;
for (const f of PROFILE_FIELDS) {
const value = typeof body[f.key] === "string" ? (body[f.key] as string).trim() : "";
if (value.length > f.max) return { error: `“${f.label}” ยาวเกิน ${f.max.toLocaleString("th-TH")} ตัวอักษร` };
profile[f.key] = value;
}
if (!profile.business) return { error: "กรอกว่าร้านขายอะไรก่อน" };
return { profile };
}
/** Profile as prompt text. The fields are written by the page's own team. */
export function profilePrompt(p: ShopProfile | null): string {
if (!p) return "<shop_profile>\n(No profile yet — keep shop facts generic and use placeholders.)\n</shop_profile>";
const lines = PROFILE_FIELDS.filter((f) => p[f.key]).map((f) => `${f.label}: ${p[f.key]}`);
return `<shop_profile>\n${lines.join("\n")}\n</shop_profile>`;
}
export const CAPTION_REFINEMENTS = {
shorter: { label: "สั้นลง", instruction: "make it noticeably shorter and punchier" },
friendlier: { label: "เป็นกันเองขึ้น", instruction: "make it warmer and more casual, like chatting with a regular customer" },
cta: { label: "เพิ่ม CTA", instruction: "add or strengthen one clear call to action, using the shop's usual contact channel" },
hashtags: { label: "ใส่ hashtag", instruction: "keep the text as it is and add fitting hashtags at the end" },
} as const;
export type CaptionRefinement = keyof typeof CAPTION_REFINEMENTS;
+52
View File
@@ -0,0 +1,52 @@
export const GOALS = {
MESSAGES: "เพิ่มข้อความสอบถาม",
SALES: "เพิ่มยอดขาย",
AWARENESS: "เพิ่มการรับรู้",
};
export function parseBrief(body) {
const business = typeof body.business === "string" ? body.business.trim() : "";
const audience = typeof body.audience === "string" ? body.audience.trim() : "";
if (!business || business.length > 1500) throw new Error("ระบุสินค้า/บริการ ไม่เกิน 1,500 ตัวอักษร");
if (audience.length > 1000) throw new Error("กลุ่มลูกค้ายาวเกิน 1,000 ตัวอักษร");
if (!Object.hasOwn(GOALS, body.goal)) throw new Error("เลือกเป้าหมายโฆษณา");
if (!Number.isSafeInteger(body.budgetBaht) || body.budgetBaht < 1 || body.budgetBaht > 10000000) throw new Error("งบต้องเป็นจำนวนเต็ม 1–10,000,000 บาท");
if (!Number.isSafeInteger(body.days) || body.days < 1 || body.days > 90) throw new Error("ระยะเวลาต้องเป็นจำนวนเต็ม 1–90 วัน");
return { business, audience, goal: body.goal, budgetBaht: body.budgetBaht, days: body.days };
}
/** Currency stays in whole baht; every allocated baht stays within the ceiling. */
export function budgetPlan(brief, split) {
const percentages = [split.testPercent, split.scalePercent, split.reservePercent];
if (percentages.some(n => !Number.isInteger(n) || n < 0 || n > 100) || percentages.reduce((a, b) => a + b, 0) !== 100) throw new Error("Invalid budget allocation");
if (split.testPercent === 0) throw new Error("A testing budget is required");
const testBaht = Math.floor(brief.budgetBaht * split.testPercent / 100);
const scaleBaht = Math.floor(brief.budgetBaht * split.scalePercent / 100);
const reserveBaht = brief.budgetBaht - testBaht - scaleBaht;
const spendable = testBaht + scaleBaht;
const base = Math.floor(spendable / brief.days);
const daily = Array.from({ length: brief.days }, (_, i) => base + (i < spendable % brief.days ? 1 : 0));
return { testBaht, scaleBaht, reserveBaht, daily };
}
/** Validate the Codex response independently of its output-schema option. */
export function validateReport(value, schema, path = "report") {
if (schema.type === "object") {
if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error(`Invalid ${path}`);
for (const key of schema.required) {
if (!(key in value)) throw new Error(`Missing ${path}.${key}`);
}
for (const [key, child] of Object.entries(value)) {
if (!(key in schema.properties)) throw new Error(`Unexpected ${path}.${key}`);
validateReport(child, schema.properties[key], `${path}.${key}`);
}
} else if (schema.type === "array") {
if (!Array.isArray(value) || value.length > 20 || value.length < 1) throw new Error(`Invalid ${path}`);
for (const child of value) validateReport(child, schema.items, path);
} else if (schema.type === "string") {
if (typeof value !== "string" || !value.trim() || value.length > 6000) throw new Error(`Invalid ${path}`);
} else if (schema.type === "integer" && !Number.isInteger(value)) {
throw new Error(`Invalid ${path}`);
}
return value;
}
+40
View File
@@ -0,0 +1,40 @@
{
"type": "object",
"additionalProperties": false,
"required": ["summary", "contentFindings", "contentIdeas", "adsPlan", "budgetSplit", "metricsToTrack", "limitations"],
"properties": {
"summary": { "type": "string" },
"contentFindings": {
"type": "array",
"items": {
"type": "object", "additionalProperties": false,
"required": ["finding", "evidence", "action"],
"properties": { "finding": { "type": "string" }, "evidence": { "type": "string" }, "action": { "type": "string" } }
}
},
"contentIdeas": {
"type": "array",
"items": {
"type": "object", "additionalProperties": false,
"required": ["title", "format", "hook", "cta"],
"properties": { "title": { "type": "string" }, "format": { "type": "string" }, "hook": { "type": "string" }, "cta": { "type": "string" } }
}
},
"adsPlan": {
"type": "object", "additionalProperties": false,
"required": ["objective", "audience", "creatives", "testPlan", "scaleRule", "stopRule"],
"properties": {
"objective": { "type": "string" }, "audience": { "type": "string" },
"creatives": { "type": "array", "items": { "type": "string" } },
"testPlan": { "type": "string" }, "scaleRule": { "type": "string" }, "stopRule": { "type": "string" }
}
},
"budgetSplit": {
"type": "object", "additionalProperties": false,
"required": ["testPercent", "scalePercent", "reservePercent"],
"properties": { "testPercent": { "type": "integer" }, "scalePercent": { "type": "integer" }, "reservePercent": { "type": "integer" } }
},
"metricsToTrack": { "type": "array", "items": { "type": "string" } },
"limitations": { "type": "array", "items": { "type": "string" } }
}
}
+43
View File
@@ -0,0 +1,43 @@
import { prisma } from "@/lib/db";
import { FacebookApiError, graphGetAll, UserFacingError } from "@/lib/facebook/client";
import { getPageCredentials } from "@/lib/facebook/tokens";
interface SourcePost {
id: string;
message?: string;
created_time: string;
reactions?: { summary?: { total_count?: number } };
comments?: { summary?: { total_count?: number } };
shares?: { count?: number };
}
export async function collectAnalysisSource(pageId: string) {
const page = await prisma.page.findUnique({ where: { id: pageId }, select: { name: true, status: true } });
if (!page || page.status !== "ACTIVE") throw new UserFacingError("เชื่อมเพจให้พร้อมใช้งานก่อนวิเคราะห์");
const credentials = await getPageCredentials(pageId);
const basicFields = "id,message,created_time";
const warnings: string[] = [];
let rows: SourcePost[];
try {
rows = await graphGetAll<SourcePost>(`/${credentials.fbPageId}/published_posts`, credentials.token, { fields: `${basicFields},reactions.limit(0).summary(true),comments.limit(0).summary(true),shares`, limit: 25 }, 2);
} catch (e) {
if (!(e instanceof FacebookApiError) || e.code !== 100) throw e;
rows = await graphGetAll<SourcePost>(`/${credentials.fbPageId}/published_posts`, credentials.token, { fields: basicFields, limit: 25 }, 2);
warnings.push("Facebook ไม่ส่งสถิติรายโพสต์มาให้ วิเคราะห์ได้เฉพาะเนื้อหาและ snapshot ที่มี");
}
const since = new Date(Date.now() - 90 * 86400000);
const posts = rows.filter(p => new Date(p.created_time) >= since).slice(0, 30).map(p => ({
id: p.id, text: (p.message ?? "").slice(0, 1800), publishedAt: p.created_time,
reactions: p.reactions?.summary?.total_count ?? null,
comments: p.comments?.summary?.total_count ?? null,
shares: p.shares?.count ?? null,
}));
if (posts.length === 0) throw new UserFacingError("ไม่พบโพสต์ Facebook ใน 90 วันที่ผ่านมา ยังไม่มีเนื้อหาให้วิเคราะห์");
const snapshots = await prisma.pageInsightSnapshot.findMany({
where: { pageId, date: { gte: since } }, orderBy: { date: "desc" }, take: 30,
select: { date: true, views: true, engagements: true, follows: true, followDelta: true },
});
if (!snapshots.length) warnings.push("ยังไม่มี snapshot Insights — กดดึงข้อมูลที่หน้า Insights เพื่อเพิ่มหลักฐานรอบถัดไป");
warnings.push("ไม่มีข้อมูลค่าโฆษณา Conversion หรือยอดขายจาก Ad Account จึงยังยืนยัน CPA/ROAS ไม่ได้");
return { pageName: page.name, collectedAt: new Date().toISOString(), lookbackDays: 90, postCount: posts.length, posts, snapshots: snapshots.map(s => ({ ...s, date: s.date.toISOString() })), warnings };
}
+28
View File
@@ -0,0 +1,28 @@
export interface AnalysisBrief {
business: string;
audience: string;
goal: "MESSAGES" | "SALES" | "AWARENESS";
budgetBaht: number;
days: number;
}
export interface AnalysisReport {
summary: string;
contentFindings: { finding: string; evidence: string; action: string }[];
contentIdeas: { title: string; format: string; hook: string; cta: string }[];
adsPlan: { objective: string; audience: string; creatives: string[]; testPlan: string; scaleRule: string; stopRule: string };
budgetSplit: { testPercent: number; scalePercent: number; reservePercent: number };
metricsToTrack: string[];
limitations: string[];
}
export interface AnalysisJob {
id: string;
status: "QUEUED" | "RUNNING" | "COMPLETED" | "FAILED";
brief: AnalysisBrief;
result: AnalysisReport | null;
error: string | null;
createdAt: string;
finishedAt: string | null;
source: { postCount: number; collectedAt: string; warnings: string[] };
}
+56
View File
@@ -0,0 +1,56 @@
import type { Prisma } from "@prisma/client";
import { prisma } from "@/lib/db";
export const SYSTEM_ACTOR = "ระบบ";
export type AuditAction =
| "META_LOGIN_CONNECTED"
| "META_LOGIN_REMOVED"
| "PAGE_CONNECTED"
| "PAGE_DISCONNECTED"
| "PAGE_WEBHOOK_SUBSCRIBED"
| "PAGE_TOKEN_INVALID"
| "PAGE_MEMBER_SET"
| "PAGE_MEMBER_REMOVED"
| "PAGE_ANALYSIS_REQUESTED"
| "PAGE_PROFILE_SAVED"
| "POST_CREATED"
| "POST_EDITED"
| "POST_PLANNED"
| "POST_SUBMITTED"
| "POST_APPROVED"
| "POST_REJECTED"
| "POST_SCHEDULED"
| "POST_PUBLISHED"
| "POST_FAILED"
| "POST_CANCELLED"
| "POST_DELETED"
| "RULE_SAVED"
| "RULE_DELETED"
| "USER_CREATED"
| "USER_UPDATED"
| "USER_IDENTITY_LINKED";
/** Append-only — AuditLog rows are never updated or deleted. */
export async function audit(
entry: {
action: AuditAction;
actorId?: string | null;
actorLabel: string;
pageId?: string | null;
postId?: string | null;
detail?: Prisma.InputJsonValue;
},
tx: Prisma.TransactionClient = prisma
) {
await tx.auditLog.create({
data: {
action: entry.action,
actorId: entry.actorId ?? null,
actorLabel: entry.actorLabel,
pageId: entry.pageId ?? null,
postId: entry.postId ?? null,
detail: entry.detail,
},
});
}
+46
View File
@@ -0,0 +1,46 @@
import crypto from "node:crypto";
import { promisify } from "node:util";
import { MIN_PASSWORD_LENGTH } from "@/lib/auth/policy";
const scrypt = promisify(crypto.scrypt) as (
password: string,
salt: Buffer,
keylen: number
) => Promise<Buffer>;
const KEY_LENGTH = 64;
const SALT_LENGTH = 16;
const PREFIX = "scrypt";
/** Stored form: "scrypt:<saltHex>:<hashHex>" */
export async function hashPassword(password: string): Promise<string> {
const salt = crypto.randomBytes(SALT_LENGTH);
const derived = await scrypt(password, salt, KEY_LENGTH);
return `${PREFIX}:${salt.toString("hex")}:${derived.toString("hex")}`;
}
export async function verifyPassword(password: string, stored: string): Promise<boolean> {
const [prefix, saltHex, hashHex] = stored.split(":");
if (prefix !== PREFIX || !saltHex || !hashHex) return false;
const expected = Buffer.from(hashHex, "hex");
if (expected.length !== KEY_LENGTH) return false;
const derived = await scrypt(password, Buffer.from(saltHex, "hex"), KEY_LENGTH);
return crypto.timingSafeEqual(derived, expected);
}
/**
* Run a throwaway hash so a login attempt for an unknown email costs the same
* as one for a real account — otherwise response time leaks which emails exist.
*/
export async function fakeVerifyDelay(): Promise<void> {
await scrypt("dummy-password", Buffer.alloc(SALT_LENGTH), KEY_LENGTH);
}
export function passwordProblem(password: unknown): string | null {
if (typeof password !== "string" || password.length < MIN_PASSWORD_LENGTH) {
return `รหัสผ่านต้องยาวอย่างน้อย ${MIN_PASSWORD_LENGTH} ตัวอักษร`;
}
return null;
}
+3
View File
@@ -0,0 +1,3 @@
// Shared between the client forms and the server validators. Kept out of
// password.ts so client components never pull node:crypto into their bundle.
export const MIN_PASSWORD_LENGTH = 10;
+44
View File
@@ -0,0 +1,44 @@
const MAX_ATTEMPTS = 5;
const WINDOW_MS = 15 * 60 * 1000;
const LOCKOUT_MS = 15 * 60 * 1000;
interface Entry {
count: number;
windowStart: number;
lockedUntil: number | null;
}
// เก็บใน memory ของ process เดียว — ไม่ persist ข้าม serverless instance/restart
// เพียงพอสำหรับกันการรัว password แบบง่ายในระบบ single-admin ภายในองค์กร
const attempts = new Map<string, Entry>();
export function checkRateLimit(ip: string): { allowed: boolean; retryAfterSeconds?: number } {
const entry = attempts.get(ip);
if (!entry) return { allowed: true };
const now = Date.now();
if (entry.lockedUntil) {
if (now < entry.lockedUntil) {
return { allowed: false, retryAfterSeconds: Math.ceil((entry.lockedUntil - now) / 1000) };
}
attempts.delete(ip);
}
return { allowed: true };
}
export function recordFailedAttempt(ip: string): void {
const now = Date.now();
const entry = attempts.get(ip);
if (!entry || now - entry.windowStart > WINDOW_MS) {
attempts.set(ip, { count: 1, windowStart: now, lockedUntil: null });
return;
}
entry.count += 1;
if (entry.count >= MAX_ATTEMPTS) {
entry.lockedUntil = now + LOCKOUT_MS;
}
}
export function resetAttempts(ip: string): void {
attempts.delete(ip);
}
+46
View File
@@ -0,0 +1,46 @@
import type { PageRole } from "@prisma/client";
// Client-safe: no Prisma runtime import, only types.
const RANK: Record<PageRole, number> = { VIEWER: 0, EDITOR: 1, APPROVER: 2, MANAGER: 3 };
export function roleAtLeast(role: PageRole | null | undefined, min: PageRole): boolean {
if (!role) return false;
return RANK[role] >= RANK[min];
}
export const PAGE_ROLE_LABEL: Record<PageRole, string> = {
VIEWER: "ดูอย่างเดียว",
EDITOR: "ผู้เขียน",
APPROVER: "ผู้อนุมัติ",
MANAGER: "ผู้จัดการเพจ",
};
export const PAGE_ROLES: PageRole[] = ["VIEWER", "EDITOR", "APPROVER", "MANAGER"];
/** Minimum page role per action — the single source of truth for the permission table in docs/ARCHITECTURE.md. */
export const ACTION_MIN_ROLE = {
view: "VIEWER",
editPost: "EDITOR",
replyInbox: "EDITOR",
approvePost: "APPROVER",
publishPost: "APPROVER",
editRules: "APPROVER",
editProfile: "APPROVER",
manageMembers: "MANAGER",
analyzePage: "MANAGER",
} as const satisfies Record<string, PageRole>;
export type PageAction = keyof typeof ACTION_MIN_ROLE;
export const ACTION_DENIED_MESSAGE: Record<PageAction, string> = {
view: "คุณไม่มีสิทธิ์เข้าถึงเพจนี้",
editPost: "ต้องเป็นผู้เขียนขึ้นไปถึงจะแก้โพสต์ได้",
replyInbox: "ต้องเป็นผู้เขียนขึ้นไปถึงจะตอบข้อความได้",
approvePost: "ต้องเป็นผู้อนุมัติขึ้นไปถึงจะอนุมัติได้",
publishPost: "ต้องเป็นผู้อนุมัติขึ้นไปถึงจะเผยแพร่ได้",
editRules: "ต้องเป็นผู้อนุมัติขึ้นไปถึงจะแก้ auto-reply ได้",
editProfile: "ต้องเป็นผู้อนุมัติขึ้นไปถึงจะแก้โปรไฟล์ร้านได้",
manageMembers: "ต้องเป็นผู้จัดการเพจถึงจะจัดการสมาชิกได้",
analyzePage: "ต้องเป็นผู้จัดการเพจถึงจะเริ่มวิเคราะห์และวางงบได้",
};
+72
View File
@@ -0,0 +1,72 @@
import { SignJWT, jwtVerify } from "jose";
import type { GlobalRole } from "@prisma/client";
const COOKIE_NAME = "pm_session";
const SESSION_DURATION_SECONDS = 60 * 60 * 24 * 90; // 90 days
export interface SessionClaims {
userId: string;
email: string;
name: string;
role: GlobalRole;
mustChangePassword: boolean;
}
function getSecret() {
const secret = process.env.SESSION_SECRET;
if (!secret) throw new Error("SESSION_SECRET env var is not set");
return new TextEncoder().encode(secret);
}
export async function createSessionToken(claims: SessionClaims): Promise<string> {
return new SignJWT({
email: claims.email,
name: claims.name,
role: claims.role,
mustChangePassword: claims.mustChangePassword,
})
.setProtectedHeader({ alg: "HS256" })
.setSubject(claims.userId)
.setIssuedAt()
.setExpirationTime(`${SESSION_DURATION_SECONDS}s`)
.sign(getSecret());
}
/**
* Signature/expiry check only — safe to call from the edge proxy where Prisma
* is unavailable. Role and active status are re-read from the database by
* lib/auth/user.ts before any privileged action, so a demoted or deactivated
* user cannot ride an old token.
*/
export async function verifySessionToken(token: string): Promise<SessionClaims | null> {
try {
const { payload } = await jwtVerify(token, getSecret());
if (!payload.sub || typeof payload.role !== "string") return null;
return {
userId: payload.sub,
email: typeof payload.email === "string" ? payload.email : "",
name: typeof payload.name === "string" ? payload.name : "",
role: payload.role as GlobalRole,
mustChangePassword: payload.mustChangePassword === true,
};
} catch {
return null;
}
}
/**
* Unchecking "remember me" drops maxAge so the cookie is session-only (cleared
* when the browser closes) while the signed token itself still expires after
* SESSION_DURATION_SECONDS either way.
*/
export function sessionCookieOptions(remember: boolean) {
return {
httpOnly: true,
secure: process.env.NODE_ENV === "production",
sameSite: "strict" as const,
path: "/",
...(remember ? { maxAge: SESSION_DURATION_SECONDS } : {}),
};
}
export { COOKIE_NAME, SESSION_DURATION_SECONDS };
+252
View File
@@ -0,0 +1,252 @@
import { SignJWT, jwtVerify } from "jose";
import type { AuthProvider } from "@prisma/client";
import { prisma } from "@/lib/db";
import { audit } from "@/lib/audit";
import { GRAPH_API_VERSION, graphGet } from "@/lib/facebook/client";
// "Sign in with Google / Facebook" for accounts that already exist. There is
// no self-signup: a SUPERADMIN creates the User, and the first social login
// whose verified email matches User.email links that provider identity
// (UserIdentity). Later logins match on the provider's stable user id.
//
// Facebook login reuses META_APP_ID but asks only for email + public_profile;
// it is separate from the page-connection flow in lib/facebook/oauth.ts.
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_TTL_SECONDS = 10 * 60;
const DB_PROVIDER: Record<SocialProvider, AuthProvider> = { google: "GOOGLE", facebook: "FACEBOOK" };
/** Codes travel to /login?error=…; the login page maps them to fixed Thai text. */
export type SocialErrorCode =
| "expired"
| "cancelled"
| "not_configured"
| "no_email"
| "no_account"
| "inactive"
| "linked_other"
| "failed";
export class SocialLoginError extends Error {
constructor(
public readonly code: SocialErrorCode,
public readonly email?: string
) {
super(code);
this.name = "SocialLoginError";
}
}
export interface SocialProfile {
providerUserId: string;
email: string | null;
emailVerified: boolean;
name: string;
}
function credentials(provider: SocialProvider): { id: string; secret: string } | null {
const id = provider === "google" ? process.env.GOOGLE_CLIENT_ID : process.env.META_APP_ID;
const secret = provider === "google" ? process.env.GOOGLE_CLIENT_SECRET : process.env.META_APP_SECRET;
return id && secret ? { id, secret } : null;
}
export function parseProvider(raw: string): SocialProvider | null {
return (SOCIAL_PROVIDERS as readonly string[]).includes(raw) ? (raw as SocialProvider) : null;
}
export function enabledProviders(): SocialProvider[] {
return SOCIAL_PROVIDERS.filter((p) => credentials(p) !== null);
}
/** Same-origin path only — rejects "//host" and "/\host", which browsers treat as another origin. */
export function safeRedirectPath(raw: string | null | undefined): string {
if (!raw || !raw.startsWith("/") || raw.startsWith("//") || raw.startsWith("/\\")) return "/";
return raw;
}
function redirectUri(provider: SocialProvider, origin: string): string {
return `${process.env.NEXT_PUBLIC_APP_URL || origin}/api/auth/oauth/${provider}/callback`;
}
// ---------- state ----------
function stateSecret() {
const s = process.env.SESSION_SECRET;
if (!s) throw new Error("SESSION_SECRET env var is not set");
return new TextEncoder().encode(s);
}
interface SocialState {
from: string;
remember: boolean;
}
/**
* CSRF state carried in a signed SameSite=Lax cookie (the Strict session
* cookie is not sent on the cross-site redirect back from the provider).
*/
export async function createSocialState(provider: SocialProvider, state: SocialState): Promise<{ nonce: string; cookie: string }> {
const nonce = crypto.randomUUID();
const cookie = await new SignJWT({ nonce, provider, from: state.from, remember: state.remember })
.setProtectedHeader({ alg: "HS256" })
.setIssuedAt()
.setExpirationTime(`${SOCIAL_STATE_TTL_SECONDS}s`)
.sign(stateSecret());
return { nonce, cookie };
}
export async function verifySocialState(cookie: string | undefined, nonce: string | null, provider: SocialProvider): Promise<SocialState | null> {
if (!cookie || !nonce) return null;
try {
const { payload } = await jwtVerify(cookie, stateSecret());
if (payload.nonce !== nonce || payload.provider !== provider) return null;
return { from: safeRedirectPath(typeof payload.from === "string" ? payload.from : null), remember: payload.remember !== false };
} catch {
return null;
}
}
// ---------- provider protocol ----------
export function authorizeUrl(provider: SocialProvider, origin: string, nonce: string): string {
const creds = credentials(provider);
if (!creds) throw new SocialLoginError("not_configured");
const url =
provider === "google"
? new URL("https://accounts.google.com/o/oauth2/v2/auth")
: new URL(`https://www.facebook.com/${GRAPH_API_VERSION}/dialog/oauth`);
url.searchParams.set("client_id", creds.id);
url.searchParams.set("redirect_uri", redirectUri(provider, origin));
url.searchParams.set("response_type", "code");
url.searchParams.set("state", nonce);
if (provider === "google") {
url.searchParams.set("scope", "openid email profile");
url.searchParams.set("prompt", "select_account");
} else {
url.searchParams.set("scope", "email,public_profile");
}
return url.toString();
}
async function readJsonOrFail(res: Response, context: string) {
const body = await res.json().catch(() => ({}));
if (!res.ok || body.error) {
// Provider error objects carry codes/descriptions only, never tokens.
console.error(`[auth:social] ${context} failed`, res.status, body.error ?? "");
throw new SocialLoginError("failed");
}
return body;
}
async function googleProfile(origin: string, code: string): Promise<SocialProfile> {
const creds = credentials("google")!;
const tokenRes = await fetch("https://oauth2.googleapis.com/token", {
method: "POST",
headers: { "Content-Type": "application/x-www-form-urlencoded" },
body: new URLSearchParams({
code,
client_id: creds.id,
client_secret: creds.secret,
redirect_uri: redirectUri("google", origin),
grant_type: "authorization_code",
}),
cache: "no-store",
});
const token = await readJsonOrFail(tokenRes, "google token exchange");
const infoRes = await fetch("https://openidconnect.googleapis.com/v1/userinfo", {
headers: { Authorization: `Bearer ${token.access_token}` },
cache: "no-store",
});
const info = await readJsonOrFail(infoRes, "google userinfo");
if (typeof info.sub !== "string") throw new SocialLoginError("failed");
return {
providerUserId: info.sub,
email: typeof info.email === "string" ? info.email : null,
emailVerified: info.email_verified === true,
name: typeof info.name === "string" ? info.name : "",
};
}
async function facebookProfile(origin: string, code: string): Promise<SocialProfile> {
const creds = credentials("facebook")!;
const url = new URL(`https://graph.facebook.com/${GRAPH_API_VERSION}/oauth/access_token`);
url.searchParams.set("client_id", creds.id);
url.searchParams.set("client_secret", creds.secret);
url.searchParams.set("redirect_uri", redirectUri("facebook", origin));
url.searchParams.set("code", code);
const token = await readJsonOrFail(await fetch(url, { cache: "no-store" }), "facebook token exchange");
let me;
try {
me = await graphGet("/me", token.access_token, { fields: "id,name,email" });
} catch (e) {
console.error("[auth:social] facebook /me failed", e instanceof Error ? e.message : e);
throw new SocialLoginError("failed");
}
return {
providerUserId: String(me.id),
email: typeof me.email === "string" ? me.email : null,
// Graph only returns `email` when the person has a confirmed address
// (the field is omitted otherwise); there is no separate verified flag.
emailVerified: typeof me.email === "string",
name: typeof me.name === "string" ? me.name : "",
};
}
/** Exchanges the authorization code and returns who signed in. The provider token is not kept. */
export function fetchSocialProfile(provider: SocialProvider, origin: string, code: string): Promise<SocialProfile> {
if (!credentials(provider)) throw new SocialLoginError("not_configured");
return provider === "google" ? googleProfile(origin, code) : facebookProfile(origin, code);
}
// ---------- account resolution ----------
const USER_SELECT = { id: true, email: true, name: true, globalRole: true, isActive: true } as const;
/** Linked identity → that user; otherwise link by verified email to an existing user. */
export async function resolveSocialUser(provider: SocialProvider, profile: SocialProfile) {
const dbProvider = DB_PROVIDER[provider];
const linked = await prisma.userIdentity.findUnique({
where: { provider_providerUserId: { provider: dbProvider, providerUserId: profile.providerUserId } },
select: { user: { select: USER_SELECT } },
});
if (linked) {
if (!linked.user.isActive) throw new SocialLoginError("inactive");
return linked.user;
}
if (!profile.email || !profile.emailVerified) throw new SocialLoginError("no_email");
const email = profile.email.trim().toLowerCase();
const user = await prisma.user.findUnique({
where: { email },
select: { ...USER_SELECT, identities: { where: { provider: dbProvider }, select: { id: true } } },
});
if (!user) throw new SocialLoginError("no_account", email);
if (!user.isActive) throw new SocialLoginError("inactive");
// Already linked to a different account of this provider (e.g. the email
// was later added to a second Google account) — don't silently re-link.
if (user.identities.length > 0) throw new SocialLoginError("linked_other");
await prisma.$transaction(async (tx) => {
await tx.userIdentity.create({
data: { userId: user.id, provider: dbProvider, providerUserId: profile.providerUserId, email },
});
await audit(
{
action: "USER_IDENTITY_LINKED",
actorId: user.id,
actorLabel: user.name || user.email,
detail: { provider: dbProvider, email },
},
tx
);
});
return { id: user.id, email: user.email, name: user.name, globalRole: user.globalRole, isActive: user.isActive };
}
+89
View File
@@ -0,0 +1,89 @@
import { cookies } from "next/headers";
import { NextResponse } from "next/server";
import type { PageRole, User } from "@prisma/client";
import { prisma } from "@/lib/db";
import { COOKIE_NAME, verifySessionToken } from "@/lib/auth/session";
import { ACTION_DENIED_MESSAGE, ACTION_MIN_ROLE, roleAtLeast, type PageAction } from "@/lib/auth/roles";
export type SessionUser = Pick<User, "id" | "email" | "name" | "avatarUrl" | "globalRole" | "isActive">;
const USER_SELECT = { id: true, email: true, name: true, avatarUrl: true, globalRole: true, isActive: true } as const;
/**
* The token only proves which account is calling. Role and active status are
* always re-read from the database so revoking access takes effect immediately.
*/
export async function getCurrentUser(): Promise<SessionUser | null> {
const token = (await cookies()).get(COOKIE_NAME)?.value;
if (!token) return null;
const claims = await verifySessionToken(token);
if (!claims) return null;
const user = await prisma.user.findUnique({ where: { id: claims.userId }, select: USER_SELECT });
if (!user || !user.isActive) return null;
return user;
}
export const isSuperadmin = (u: Pick<SessionUser, "globalRole">) => u.globalRole === "SUPERADMIN";
/** Effective role on a page. SUPERADMIN counts as MANAGER everywhere. */
export async function pageRoleOf(user: SessionUser, pageId: string): Promise<PageRole | null> {
if (isSuperadmin(user)) return "MANAGER";
const m = await prisma.pageMember.findUnique({
where: { userId_pageId: { userId: user.id, pageId } },
select: { role: true },
});
return m?.role ?? null;
}
/** Page ids the user can see (null = all pages, for SUPERADMIN). */
export async function accessiblePageIds(user: SessionUser): Promise<string[] | null> {
if (isSuperadmin(user)) return null;
const rows = await prisma.pageMember.findMany({ where: { userId: user.id }, select: { pageId: true } });
return rows.map((r) => r.pageId);
}
/** Prisma `where` fragment restricting to pages the user can see. */
export async function pageScope(user: SessionUser): Promise<{ id?: { in: string[] } }> {
const ids = await accessiblePageIds(user);
return ids === null ? {} : { id: { in: ids } };
}
export type AuthResult = { ok: true; user: SessionUser } | { ok: false; response: NextResponse };
export type PageAuthResult =
| { ok: true; user: SessionUser; role: PageRole }
| { ok: false; response: NextResponse };
export async function requireUser(): Promise<AuthResult> {
const user = await getCurrentUser();
if (!user) {
return { ok: false, response: NextResponse.json({ error: "กรุณาเข้าสู่ระบบใหม่" }, { status: 401 }) };
}
return { ok: true, user };
}
export async function requireSuperadmin(): Promise<AuthResult> {
const auth = await requireUser();
if (!auth.ok) return auth;
if (!isSuperadmin(auth.user)) {
return { ok: false, response: NextResponse.json({ error: "เฉพาะผู้ดูแลระบบเท่านั้น" }, { status: 403 }) };
}
return auth;
}
/** Every route handler touching page data calls this — the proxy only checks login. */
export async function requirePageAction(pageId: string, action: PageAction): Promise<PageAuthResult> {
const auth = await requireUser();
if (!auth.ok) return auth;
const role = await pageRoleOf(auth.user, pageId);
if (!roleAtLeast(role, ACTION_MIN_ROLE[action])) {
// 404 rather than 403 when the user has no membership at all, so page ids aren't probeable.
const status = role ? 403 : 404;
const error = role ? ACTION_DENIED_MESSAGE[action] : "ไม่พบเพจ";
return { ok: false, response: NextResponse.json({ error }, { status }) };
}
return { ok: true, user: auth.user, role: role! };
}
export function actorLabel(user: Pick<SessionUser, "name" | "email">): string {
return user.name || user.email;
}
+45
View File
@@ -0,0 +1,45 @@
// Week maths for the board, always in Bangkok time (UTC+7, no DST).
const TZ_OFFSET_MS = 7 * 60 * 60 * 1000;
const dayKeyFmt = new Intl.DateTimeFormat("en-CA", { year: "numeric", month: "2-digit", day: "2-digit", timeZone: "Asia/Bangkok" });
/** "YYYY-MM-DD" of an instant, in Bangkok. */
export function bkkDayKey(d: Date): string {
return dayKeyFmt.format(d);
}
/** UTC instant of 00:00 Bangkok on the given day key. */
export function bkkMidnight(dayKey: string): Date {
const [y, m, d] = dayKey.split("-").map(Number);
return new Date(Date.UTC(y, m - 1, d) - TZ_OFFSET_MS);
}
export function addDays(dayKey: string, n: number): string {
const [y, m, d] = dayKey.split("-").map(Number);
const t = new Date(Date.UTC(y, m - 1, d + n));
return t.toISOString().slice(0, 10);
}
/** Monday of the week containing dayKey. */
export function weekStartOf(dayKey: string): string {
const [y, m, d] = dayKey.split("-").map(Number);
const dow = new Date(Date.UTC(y, m - 1, d)).getUTCDay(); // 0 = Sunday
return addDays(dayKey, -((dow + 6) % 7));
}
export function parseWeekParam(w: string | undefined): string {
if (isDayKey(w)) return weekStartOf(w!);
return weekStartOf(bkkDayKey(new Date()));
}
export function isDayKey(value: string | undefined): boolean {
if (!value || !/^\d{4}-\d{2}-\d{2}$/.test(value)) return false;
const date = new Date(`${value}T00:00:00Z`);
return !Number.isNaN(date.getTime()) && date.toISOString().slice(0, 10) === value;
}
/** Actual publication takes precedence over the owner's provisional plan. */
export function postBoardDate(post: { status: string; scheduledPublishAt: Date | null; plannedAt: Date | null; updatedAt: Date }): Date | null {
if (post.status === "PUBLISHED") return post.scheduledPublishAt ?? post.updatedAt;
return post.scheduledPublishAt ?? post.plannedAt;
}
+58
View File
@@ -0,0 +1,58 @@
import { cache } from "react";
import { cookies } from "next/headers";
import { redirect } from "next/navigation";
import type { PageRole } from "@prisma/client";
import { prisma } from "@/lib/db";
import { getCurrentUser, isSuperadmin, type SessionUser } from "@/lib/auth/user";
export const SELECTED_PAGE_COOKIE = "pm_page";
export interface ConsolePage {
id: string;
fbPageId: string;
name: string;
pictureUrl: string | null;
igUsername: string | null;
status: "ACTIVE" | "TOKEN_INVALID" | "DISCONNECTED";
role: PageRole;
}
export interface ConsoleContext {
user: SessionUser;
pages: ConsolePage[];
/** null = "ทุกเพจ" */
selected: ConsolePage | null;
}
/** Per-request context for console pages: user, visible pages, the page picked in the rail switcher. */
export const getConsoleContext = cache(async (): Promise<ConsoleContext> => {
const user = await getCurrentUser();
if (!user) redirect("/login");
const where = { status: { not: "DISCONNECTED" as const } };
let pages: ConsolePage[];
if (isSuperadmin(user)) {
const rows = await prisma.page.findMany({
where,
select: { id: true, fbPageId: true, name: true, pictureUrl: true, igUsername: true, status: true },
orderBy: { name: "asc" },
});
pages = rows.map((p) => ({ ...p, role: "MANAGER" as const }));
} else {
const rows = await prisma.pageMember.findMany({
where: { userId: user.id, page: where },
select: { role: true, page: { select: { id: true, fbPageId: true, name: true, pictureUrl: true, igUsername: true, status: true } } },
orderBy: { page: { name: "asc" } },
});
pages = rows.map((r) => ({ ...r.page, role: r.role }));
}
const selectedId = (await cookies()).get(SELECTED_PAGE_COOKIE)?.value;
const selected = pages.find((p) => p.id === selectedId) ?? null;
return { user, pages, selected };
});
/** Page ids to query for the current switcher selection. */
export function scopedPageIds(ctx: ConsoleContext): string[] {
return ctx.selected ? [ctx.selected.id] : ctx.pages.map((p) => p.id);
}
+30
View File
@@ -0,0 +1,30 @@
import crypto from "node:crypto";
// Page access tokens are stored encrypted at rest. Format: "v1:<iv>:<tag>:<ciphertext>",
// each part base64url. AES-256-GCM so a tampered row fails to decrypt instead of
// yielding a garbage token.
const VERSION = "v1";
function key(): Buffer {
const raw = process.env.TOKEN_ENCRYPTION_KEY;
if (!raw) throw new Error("TOKEN_ENCRYPTION_KEY env var is not set");
const buf = Buffer.from(raw, "base64");
if (buf.length !== 32) throw new Error("TOKEN_ENCRYPTION_KEY must be 32 bytes (base64)");
return buf;
}
export function encryptToken(plain: string): string {
const iv = crypto.randomBytes(12);
const cipher = crypto.createCipheriv("aes-256-gcm", key(), iv);
const enc = Buffer.concat([cipher.update(plain, "utf8"), cipher.final()]);
const tag = cipher.getAuthTag();
return [VERSION, iv.toString("base64url"), tag.toString("base64url"), enc.toString("base64url")].join(":");
}
export function decryptToken(boxed: string): string {
const [version, iv, tag, enc] = boxed.split(":");
if (version !== VERSION || !iv || !tag || !enc) throw new Error("Unrecognised token cipher format");
const decipher = crypto.createDecipheriv("aes-256-gcm", key(), Buffer.from(iv, "base64url"));
decipher.setAuthTag(Buffer.from(tag, "base64url"));
return Buffer.concat([decipher.update(Buffer.from(enc, "base64url")), decipher.final()]).toString("utf8");
}
+17
View File
@@ -0,0 +1,17 @@
import { PrismaClient } from "@prisma/client";
import { PrismaPg } from "@prisma/adapter-pg";
const globalForPrisma = globalThis as unknown as {
prisma: PrismaClient | undefined;
};
function createClient() {
const adapter = new PrismaPg({ connectionString: process.env.DATABASE_URL });
return new PrismaClient({ adapter });
}
export const prisma = globalForPrisma.prisma ?? createClient();
if (process.env.NODE_ENV !== "production") {
globalForPrisma.prisma = prisma;
}
+130
View File
@@ -0,0 +1,130 @@
// Thin Graph API wrapper. Every call takes an explicit access token: page-level
// endpoints need that page's token (lib/facebook/tokens.ts); /me/accounts uses a
// token source (Facebook login or system user); /debug_token uses the app token.
// Single place to bump the Graph version. Check Meta's changelog for the
// currently supported versions before raising it.
export const GRAPH_API_VERSION = "v21.0";
const GRAPH_BASE = `https://graph.facebook.com/${GRAPH_API_VERSION}`;
export class FacebookApiError extends Error {
constructor(
message: string,
public readonly code?: number,
public readonly subcode?: number,
public readonly type?: string,
public readonly raw?: unknown
) {
super(message);
this.name = "FacebookApiError";
}
}
type Params = Record<string, string | number | boolean | undefined>;
function buildUrl(path: string, accessToken: string, params: Params = {}): string {
const url = new URL(`${GRAPH_BASE}${path}`);
url.searchParams.set("access_token", accessToken);
for (const [k, v] of Object.entries(params)) {
if (v !== undefined) url.searchParams.set(k, String(v));
}
return url.toString();
}
async function parse(res: Response) {
const body = await res.json().catch(() => ({}));
if (!res.ok || body.error) {
const err = body.error ?? {};
throw new FacebookApiError(
err.message ?? `Graph API request failed (${res.status})`,
err.code,
err.error_subcode,
err.type,
body
);
}
return body;
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export type GraphBody = any;
export async function graphGet(path: string, accessToken: string, params: Params = {}): Promise<GraphBody> {
const res = await fetch(buildUrl(path, accessToken, params), { cache: "no-store" });
return parse(res);
}
export async function graphPostJson(path: string, accessToken: string, body: Record<string, unknown>): Promise<GraphBody> {
const res = await fetch(buildUrl(path, accessToken), {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(body),
});
return parse(res);
}
export async function graphDelete(path: string, accessToken: string): Promise<GraphBody> {
const res = await fetch(buildUrl(path, accessToken), { method: "DELETE" });
return parse(res);
}
/**
* Follows `paging.next` until exhausted (or maxPages). `paging.next` is an
* absolute URL that already carries token + cursor, so it is fetched as-is.
*/
export async function graphGetAll<T>(path: string, accessToken: string, params: Params = {}, maxPages = 20): Promise<T[]> {
const items: T[] = [];
let body = await graphGet(path, accessToken, params);
for (let page = 0; page < maxPages; page++) {
items.push(...((body.data ?? []) as T[]));
const next: string | undefined = body.paging?.next;
if (!next) break;
body = await parse(await fetch(next, { cache: "no-store" }));
}
return items;
}
/** Common Graph error codes → what the user should do next. */
const GRAPH_ERROR_HINT: Record<number, string> = {
4: "เรียก Facebook ถี่เกินไป รอสักครู่แล้วลองใหม่",
17: "เรียก Facebook ถี่เกินไป รอสักครู่แล้วลองใหม่",
32: "เพจนี้เรียก Facebook ถี่เกินไป รอสักครู่แล้วลองใหม่",
190: "สิทธิ์เข้าถึงเพจหมดอายุหรือถูกยกเลิก — ไปที่เพจที่เชื่อม แล้วเชื่อมบัญชี Facebook ใหม่",
200: "บัญชีที่เชื่อมไม่มีสิทธิ์ทำสิ่งนี้ — เชื่อมบัญชี Facebook ใหม่และอนุญาตสิทธิ์ให้ครบ",
10: "บัญชีที่เชื่อมไม่มีสิทธิ์ทำสิ่งนี้ — เชื่อมบัญชี Facebook ใหม่และอนุญาตสิทธิ์ให้ครบ",
368: "Facebook บล็อกการกระทำนี้ชั่วคราว (อาจถูกมองว่าเป็นสแปม) ลองใหม่ภายหลัง",
506: "โพสต์ซ้ำกับโพสต์ล่าสุด — แก้ข้อความก่อนเผยแพร่",
1366046: "รูปไม่ผ่านเงื่อนไขของ Facebook — ลองรูป JPG/PNG ขนาดเล็กลง",
};
/**
* Logs the full Graph error server-side and returns a safe Thai message for
* the client — raw responses can carry account/asset ids.
*/
export function safeFacebookErrorMessage(e: unknown, context: string): string {
if (e instanceof FacebookApiError) {
console.error(`[${context}] Graph API error`, { message: e.message, code: e.code, subcode: e.subcode, type: e.type, raw: e.raw });
const hint = e.code !== undefined ? GRAPH_ERROR_HINT[e.code] : undefined;
if (hint) return `${hint} (code ${e.code})`;
return e.code
? `เชื่อมต่อ Facebook ไม่สำเร็จ (code ${e.code}) ลองใหม่หรือติดต่อผู้ดูแล`
: "เชื่อมต่อ Facebook ไม่สำเร็จ ลองใหม่หรือติดต่อผู้ดูแล";
}
if (e instanceof UserFacingError) return e.message;
console.error(`[${context}] Unexpected error`, e);
return "เกิดข้อผิดพลาดที่ไม่คาดคิด ลองใหม่หรือติดต่อผู้ดูแล";
}
/** An error whose message is already safe Thai text for the UI. */
export class UserFacingError extends Error {
constructor(message: string) {
super(message);
this.name = "UserFacingError";
}
}
/** Graph ids come back bare ("123") or page-prefixed ("pageId_123"); compare on the suffix. */
export function bareId(id: string): string {
const parts = id.split("_");
return parts[parts.length - 1];
}
+160
View File
@@ -0,0 +1,160 @@
import { graphGet, graphPostJson } from "./client";
import type { PageCredentials } from "./tokens";
/**
* Page inbox (Messenger + Instagram DM), read live from Graph. Message text
* is never written to the database — conversations are other people's private
* messages; the DB keeps only Conversation metadata for the bot.
*/
export type InboxPlatform = "messenger" | "instagram";
export interface Participant {
id: string;
name: string;
}
export interface InboxConversation {
id: string;
snippet: string;
updatedTime: string;
unreadCount: number;
contacts: Participant[];
}
export interface InboxMessage {
id: string;
createdTime: string;
fromId: string;
fromName: string;
fromPage: boolean;
text: string;
imageUrls: string[];
}
interface RawParticipant {
id: string;
name?: string;
username?: string;
}
function contactsOf(raw: RawParticipant[] | undefined, page: PageCredentials): Participant[] {
return (raw ?? [])
.filter((p) => p.id !== page.fbPageId && p.id !== page.igUserId)
.map((p) => ({ id: p.id, name: p.name || p.username || "ไม่ทราบชื่อ" }));
}
export async function listConversations(
page: PageCredentials,
platform: InboxPlatform,
{ limit = 25, after }: { limit?: number; after?: string } = {}
): Promise<{ conversations: InboxConversation[]; nextCursor: string | null }> {
const res = await graphGet(`/${page.fbPageId}/conversations`, page.token, {
platform,
limit,
after,
fields: "id,snippet,updated_time,unread_count,participants",
});
const conversations: InboxConversation[] = (res.data ?? []).map(
(c: { id: string; snippet?: string; updated_time: string; unread_count?: number; participants?: { data?: RawParticipant[] } }) => ({
id: c.id,
snippet: c.snippet ?? "",
updatedTime: c.updated_time,
unreadCount: c.unread_count ?? 0,
contacts: contactsOf(c.participants?.data, page),
})
);
return { conversations, nextCursor: res.paging?.cursors?.after ?? null };
}
/** Oldest first, like every chat UI. */
export async function listMessages(page: PageCredentials, conversationId: string, limit = 40): Promise<InboxMessage[]> {
const res = await graphGet(`/${conversationId}/messages`, page.token, {
limit,
fields: "id,created_time,from,message,attachments{image_data}",
});
return (res.data ?? [])
.map(
(m: {
id: string;
created_time: string;
from?: RawParticipant;
message?: string;
attachments?: { data?: Array<{ image_data?: { url?: string; preview_url?: string } }> };
}) => ({
id: m.id,
createdTime: m.created_time,
fromId: m.from?.id ?? "",
fromName: m.from?.name || m.from?.username || "ไม่ทราบชื่อ",
fromPage: m.from?.id === page.fbPageId || m.from?.id === page.igUserId,
text: m.message ?? "",
imageUrls: (m.attachments?.data ?? [])
.map((a) => a.image_data?.preview_url ?? a.image_data?.url)
.filter((u): u is string => Boolean(u)),
})
)
.reverse();
}
/**
* The person on the other end, resolved from Graph — never trust a PSID from
* the client, or the page could be used to message someone who never wrote in.
*/
export async function resolveRecipient(page: PageCredentials, conversationId: string): Promise<Participant | null> {
const res = await graphGet(`/${conversationId}`, page.token, { fields: "participants" });
return contactsOf(res.participants?.data, page)[0] ?? null;
}
export function lastInboundAt(messages: InboxMessage[]): string | null {
const inbound = messages.filter((m) => !m.fromPage);
return inbound.length ? inbound[inbound.length - 1].createdTime : null;
}
/** RESPONSE = reply inside the 24h window. No message tags: misuse risks the page's messaging permission. */
export async function sendTextMessage(page: PageCredentials, recipientId: string, text: string): Promise<string> {
const res = await graphPostJson(`/${page.fbPageId}/messages`, page.token, {
recipient: { id: recipientId },
message: { text },
messaging_type: "RESPONSE",
});
return res.message_id ?? "";
}
export async function sendImageMessage(page: PageCredentials, recipientId: string, imageUrl: string): Promise<string> {
const res = await graphPostJson(`/${page.fbPageId}/messages`, page.token, {
recipient: { id: recipientId },
message: { attachment: { type: "image", payload: { url: imageUrl, is_reusable: true } } },
messaging_type: "RESPONSE",
});
return res.message_id ?? "";
}
export async function sendSenderAction(
page: PageCredentials,
recipientId: string,
action: "mark_seen" | "typing_on" | "typing_off"
): Promise<void> {
await graphPostJson(`/${page.fbPageId}/messages`, page.token, { recipient: { id: recipientId }, sender_action: action });
}
/**
* Messenger private reply to a comment. Only works for comments on the page's
* own posts, once per comment, within 7 days. Comments in Groups fail with
* (#100) subcode 33 every time.
*/
export async function sendPrivateReply(page: PageCredentials, commentId: string, text: string): Promise<string> {
const res = await graphPostJson(`/${commentId}/private_replies`, page.token, { message: text });
return res.id ?? res.message_id ?? "";
}
/** Public reply under the comment (FB: /comments, IG: /replies). */
export async function replyToComment(
page: PageCredentials,
commentId: string,
text: string,
platform: "facebook" | "instagram"
): Promise<string> {
const edge = platform === "instagram" ? "replies" : "comments";
const res = await graphPostJson(`/${commentId}/${edge}`, page.token, { message: text });
return res.id ?? "";
}
+54
View File
@@ -0,0 +1,54 @@
import { graphGet } from "./client";
import type { PageCredentials } from "./tokens";
interface InsightMetric {
name: string;
values: Array<{ value: number | Record<string, number>; end_time?: string }>;
}
function latest(metrics: InsightMetric[], name: string): number {
const m = metrics.find((x) => x.name === name);
const v = m?.values?.[m.values.length - 1]?.value;
return typeof v === "number" ? v : 0;
}
/**
* page_impressions / page_engaged_users / page_fans / page_fan_adds are
* deprecated ("(#100) The value must be a valid insights metric"). These are
* the closest supported ones; the daily follower delta is derived by the cron
* from yesterday's snapshot since page_fan_adds has no replacement.
*/
export async function getPageDailyInsights(page: PageCredentials) {
const res = await graphGet(`/${page.fbPageId}/insights`, page.token, {
metric: "page_views_total,page_post_engagements,page_follows",
period: "day",
});
const data: InsightMetric[] = res.data ?? [];
return {
views: latest(data, "page_views_total"),
engagements: latest(data, "page_post_engagements"),
follows: latest(data, "page_follows"),
raw: res,
};
}
/**
* Metric names here are unverified against the current Graph version — if
* Meta rejects one, swap it and keep `raw` so history can be re-derived.
*/
export async function getPostInsights(page: PageCredentials, fbPostId: string) {
const id = fbPostId.includes("_") ? fbPostId : `${page.fbPageId}_${fbPostId}`;
const res = await graphGet(`/${id}/insights`, page.token, {
metric: "post_impressions,post_engaged_users,post_reactions_by_type_total",
});
const data: InsightMetric[] = res.data ?? [];
const reactionsRaw = data.find((d) => d.name === "post_reactions_by_type_total")?.values?.[0]?.value;
const reactions =
reactionsRaw && typeof reactionsRaw === "object" ? Object.values(reactionsRaw).reduce((a, b) => a + b, 0) : 0;
return {
impressions: latest(data, "post_impressions"),
engaged: latest(data, "post_engaged_users"),
reactions,
raw: res,
};
}
+21
View File
@@ -0,0 +1,21 @@
// Pure policy constants shared by API routes and the browser composer.
// Kept free of Graph/env imports so the client bundle never pulls server code.
/** Meta rejects longer text on the send API. */
export const MAX_MESSAGE_LENGTH = 2000;
/**
* A page may reply freely for 24h after the person's last message; after that
* the send API needs a message tag, so the UI blocks the send instead.
*/
export const MESSAGING_WINDOW_MS = 24 * 60 * 60 * 1000;
export function isWithinMessagingWindow(lastInboundIso: string | null): boolean {
if (!lastInboundIso) return false;
return Date.now() - new Date(lastInboundIso).getTime() < MESSAGING_WINDOW_MS;
}
export function windowRemainingMs(lastInboundIso: string | null): number {
if (!lastInboundIso) return 0;
return Math.max(0, MESSAGING_WINDOW_MS - (Date.now() - new Date(lastInboundIso).getTime()));
}
+125
View File
@@ -0,0 +1,125 @@
import { SignJWT, jwtVerify } from "jose";
import { GRAPH_API_VERSION, graphGet, UserFacingError } from "./client";
// "Login with Facebook" for connecting pages. The person granting access must
// be an admin of the pages; while the Meta app is in Development mode they
// must also have a role on the app (admin/developer/tester).
export const OAUTH_STATE_COOKIE = "pm_fb_oauth";
const STATE_TTL_SECONDS = 10 * 60;
/** Overridable with META_OAUTH_SCOPES (comma separated) when the app lacks a product, e.g. Instagram. */
export const DEFAULT_SCOPES = [
"pages_show_list",
"pages_read_engagement",
"pages_manage_metadata",
"pages_manage_posts",
"pages_read_user_content",
"pages_manage_engagement",
"pages_messaging",
"read_insights",
"business_management",
"instagram_basic",
"instagram_content_publish",
"instagram_manage_comments",
"instagram_manage_messages",
];
function appCredentials() {
const id = process.env.META_APP_ID;
const secret = process.env.META_APP_SECRET;
if (!id || !secret) throw new UserFacingError("ยังไม่ได้ตั้ง META_APP_ID / META_APP_SECRET");
return { id, secret };
}
/** App access token — used as the inspector for /debug_token. */
export function appAccessToken(): string | null {
const id = process.env.META_APP_ID;
const secret = process.env.META_APP_SECRET;
return id && secret ? `${id}|${secret}` : null;
}
export function oauthRedirectUri(origin: string): string {
return `${process.env.NEXT_PUBLIC_APP_URL || origin}/api/facebook/oauth/callback`;
}
export function oauthScopes(): string[] {
const raw = process.env.META_OAUTH_SCOPES;
return raw ? raw.split(",").map((s) => s.trim()).filter(Boolean) : DEFAULT_SCOPES;
}
function stateSecret() {
const s = process.env.SESSION_SECRET;
if (!s) throw new Error("SESSION_SECRET env var is not set");
return new TextEncoder().encode(s);
}
/**
* Signed state bound to the user who started the flow. The callback can't
* rely on the session cookie (SameSite=Strict is not sent on the cross-site
* redirect back from facebook.com), so this Lax cookie carries the identity.
*/
export async function createOAuthState(userId: string): Promise<{ nonce: string; cookie: string }> {
const nonce = crypto.randomUUID();
const cookie = await new SignJWT({ nonce })
.setProtectedHeader({ alg: "HS256" })
.setSubject(userId)
.setIssuedAt()
.setExpirationTime(`${STATE_TTL_SECONDS}s`)
.sign(stateSecret());
return { nonce, cookie };
}
export async function verifyOAuthState(cookie: string | undefined, nonce: string | null): Promise<string | null> {
if (!cookie || !nonce) return null;
try {
const { payload } = await jwtVerify(cookie, stateSecret());
return payload.nonce === nonce && payload.sub ? payload.sub : null;
} catch {
return null;
}
}
export function authorizeUrl(origin: string, nonce: string): string {
const { id } = appCredentials();
const url = new URL(`https://www.facebook.com/${GRAPH_API_VERSION}/dialog/oauth`);
url.searchParams.set("client_id", id);
url.searchParams.set("redirect_uri", oauthRedirectUri(origin));
url.searchParams.set("state", nonce);
url.searchParams.set("response_type", "code");
url.searchParams.set("scope", oauthScopes().join(","));
// Re-show declined permissions instead of silently keeping the old grant.
url.searchParams.set("auth_type", "rerequest");
return url.toString();
}
async function tokenRequest(params: Record<string, string>) {
const url = new URL(`https://graph.facebook.com/${GRAPH_API_VERSION}/oauth/access_token`);
for (const [k, v] of Object.entries(params)) url.searchParams.set(k, v);
const res = await fetch(url, { cache: "no-store" });
const body = await res.json().catch(() => ({}));
if (!res.ok || body.error || !body.access_token) {
console.error("[fb:oauth] token exchange failed", body.error ?? res.status);
throw new UserFacingError("แลก token กับ Facebook ไม่สำเร็จ ลองเชื่อมใหม่อีกครั้ง");
}
return body as { access_token: string; expires_in?: number };
}
/** code → short-lived user token → long-lived user token (~60 days). */
export async function exchangeCode(origin: string, code: string) {
const { id, secret } = appCredentials();
const short = await tokenRequest({ client_id: id, client_secret: secret, redirect_uri: oauthRedirectUri(origin), code });
const long = await tokenRequest({ grant_type: "fb_exchange_token", client_id: id, client_secret: secret, fb_exchange_token: short.access_token });
const me = await graphGet("/me", long.access_token, { fields: "id,name" });
const perms = await graphGet("/me/permissions", long.access_token);
const scopes: string[] = (perms.data ?? [])
.filter((p: { status: string }) => p.status === "granted")
.map((p: { permission: string }) => p.permission);
return {
token: long.access_token,
expiresAt: long.expires_in ? new Date(Date.now() + long.expires_in * 1000) : null,
fbUserId: me.id as string,
name: me.name as string,
scopes,
};
}
+148
View File
@@ -0,0 +1,148 @@
import { graphGet, graphGetAll, graphPostJson, graphDelete, FacebookApiError } from "./client";
import { appAccessToken } from "./oauth";
export interface AvailablePage {
fbPageId: string;
name: string;
pictureUrl: string | null;
accessToken: string;
igUserId: string | null;
igUsername: string | null;
tasks: string[];
connectionId: string | null;
}
interface RawAccount {
id: string;
name: string;
access_token?: string;
tasks?: string[];
picture?: { data?: { url?: string } };
instagram_business_account?: { id: string; username?: string };
}
/** Pages a single user/system-user token can manage, each with its own page token. */
export async function listPagesForToken(token: string): Promise<AvailablePage[]> {
const rows = await graphGetAll<RawAccount>("/me/accounts", token, {
fields: "id,name,access_token,tasks,picture{url},instagram_business_account{id,username}",
limit: 100,
});
return rows
.filter((r) => r.access_token)
.map((r) => ({
fbPageId: r.id,
name: r.name,
pictureUrl: r.picture?.data?.url ?? null,
accessToken: r.access_token!,
igUserId: r.instagram_business_account?.id ?? null,
igUsername: r.instagram_business_account?.username ?? null,
tasks: r.tasks ?? [],
connectionId: null,
}));
}
export interface PageSource {
/** MetaConnection.id, or null for the system user token */
connectionId: string | null;
label: string;
token: string;
}
/**
* Every page reachable from any token source: the optional system user token
* (env) and each "Login with Facebook" connection. Page tokens minted from a
* system user or a long-lived user token do not expire, but die when the
* person loses page access or permissions change — token-health catches that.
* A failing source is reported, not fatal.
*/
export async function listAvailablePages(sources: PageSource[]): Promise<{ pages: AvailablePage[]; errors: string[] }> {
const seen = new Map<string, AvailablePage>();
const errors: string[] = [];
for (const s of sources) {
try {
for (const p of await listPagesForToken(s.token)) {
if (!seen.has(p.fbPageId)) seen.set(p.fbPageId, { ...p, connectionId: s.connectionId });
}
} catch (e) {
console.error(`[pages:available] source ${s.label} failed`, e);
errors.push(`${s.label}: ${e instanceof FacebookApiError ? `${e.message} (code ${e.code})` : (e as Error).message}`);
}
}
return { pages: [...seen.values()], errors };
}
export function systemUserSource(): PageSource | null {
const token = process.env.META_SYSTEM_USER_TOKEN;
return token ? { connectionId: null, label: "System user", token } : null;
}
export const WEBHOOK_FIELDS = ["messages", "messaging_postbacks", "feed"] as const;
/** Subscribes our app to this page's webhook events. */
export async function subscribePageWebhook(fbPageId: string, pageToken: string): Promise<void> {
await graphPostJson(`/${fbPageId}/subscribed_apps`, pageToken, {
subscribed_fields: WEBHOOK_FIELDS.join(","),
});
}
export async function unsubscribePageWebhook(fbPageId: string, pageToken: string): Promise<void> {
await graphDelete(`/${fbPageId}/subscribed_apps`, pageToken);
}
export interface TokenHealth {
valid: boolean;
scopes: string[];
missingScopes: string[];
detail: string | null;
}
export const REQUIRED_SCOPES = [
"pages_show_list",
"pages_read_engagement",
"pages_manage_metadata",
"pages_manage_posts",
"pages_read_user_content",
"pages_manage_engagement",
"pages_messaging",
"read_insights",
] as const;
export const INSTAGRAM_SCOPES = [
"instagram_basic",
"instagram_content_publish",
"instagram_manage_comments",
"instagram_manage_messages",
] as const;
/** debug_token on a page token. Inspector = app access token (falls back to the token itself). */
export async function checkTokenHealth(pageToken: string, needsInstagram: boolean): Promise<TokenHealth> {
try {
const res = await graphGet("/debug_token", appAccessToken() ?? pageToken, { input_token: pageToken });
const data = res.data ?? {};
const scopes: string[] = data.scopes ?? [];
const required: readonly string[] = needsInstagram ? [...REQUIRED_SCOPES, ...INSTAGRAM_SCOPES] : REQUIRED_SCOPES;
const missingScopes = required.filter((s) => !scopes.includes(s));
const valid = data.is_valid === true;
return {
valid,
scopes,
missingScopes,
detail: valid ? null : data.error?.message ?? "token ใช้งานไม่ได้",
};
} catch (e) {
return {
valid: false,
scopes: [],
missingScopes: [],
detail: e instanceof FacebookApiError ? `${e.message} (code ${e.code})` : (e as Error).message,
};
}
}
export async function listSubscribedFields(fbPageId: string, pageToken: string): Promise<string[]> {
const res = await graphGet(`/${fbPageId}/subscribed_apps`, pageToken);
const appId = process.env.META_APP_ID;
const apps: Array<{ id: string; subscribed_fields?: string[] }> = res.data ?? [];
const ours = appId ? apps.find((a) => a.id === appId) : apps[0];
return ours?.subscribed_fields ?? [];
}
+80
View File
@@ -0,0 +1,80 @@
import { bareId, graphDelete, graphGet, graphGetAll, graphPostJson } from "./client";
import type { PageCredentials } from "./tokens";
/**
* Facebook rejects a scheduled_publish_time under 10 minutes or more than ~30
* days out with a bare "(#100) The specified scheduled publish time was
* invalid." 28 days is what pages accept in practice.
*/
export const MIN_SCHEDULE_MINUTES = 10;
export const MAX_SCHEDULE_DAYS = 28;
export function scheduleTimeProblem(when: Date, now: Date = new Date()): string | null {
const minutesOut = (when.getTime() - now.getTime()) / 60000;
if (Number.isNaN(minutesOut)) return "เวลาที่ตั้งไม่ถูกต้อง";
if (minutesOut < MIN_SCHEDULE_MINUTES) return `ต้องตั้งเวลาล่วงหน้าอย่างน้อย ${MIN_SCHEDULE_MINUTES} นาที`;
if (minutesOut > MAX_SCHEDULE_DAYS * 24 * 60) return `ตั้งเวลาล่วงหน้าได้ไม่เกิน ${MAX_SCHEDULE_DAYS} วัน`;
return null;
}
export interface FbPublishResult {
fbPostId: string;
permalink: string | null;
}
/**
* Publishes now or hands Facebook a scheduled_publish_time — Facebook holds
* and fires scheduled posts itself, no cron needed.
*/
export async function publishToFacebook(
page: PageCredentials,
params: { caption: string; imageUrl: string | null; scheduledAt: Date | null }
): Promise<FbPublishResult> {
const scheduling = params.scheduledAt
? { published: false, scheduled_publish_time: Math.floor(params.scheduledAt.getTime() / 1000) }
: { published: true };
let fbPostId: string;
if (params.imageUrl) {
const res = await graphPostJson(`/${page.fbPageId}/photos`, page.token, {
url: params.imageUrl,
caption: params.caption,
...scheduling,
});
// Photos return `id` (photo id) and `post_id` (feed post id) — the post id is what the feed edges use.
fbPostId = res.post_id ?? res.id;
} else {
const res = await graphPostJson(`/${page.fbPageId}/feed`, page.token, {
message: params.caption,
...scheduling,
});
fbPostId = res.id;
}
let permalink: string | null = null;
if (!params.scheduledAt) {
permalink = await fetchPermalink(page, fbPostId).catch(() => null);
}
return { fbPostId, permalink };
}
export async function fetchPermalink(page: PageCredentials, fbPostId: string): Promise<string | null> {
const id = fbPostId.includes("_") ? fbPostId : `${page.fbPageId}_${fbPostId}`;
const res = await graphGet(`/${id}`, page.token, { fields: "permalink_url" });
return res.permalink_url ?? null;
}
export async function cancelScheduledFacebookPost(page: PageCredentials, fbPostId: string): Promise<void> {
await graphDelete(`/${fbPostId}`, page.token);
}
/** What the page itself reports as published vs still queued, as bare ids. */
export async function getPageQueueState(page: PageCredentials): Promise<{ published: Set<string>; scheduled: Set<string> }> {
const [published, scheduled] = await Promise.all(
(["published_posts", "scheduled_posts"] as const).map(async (edge) => {
const rows = await graphGetAll<{ id: string }>(`/${page.fbPageId}/${edge}`, page.token, { fields: "id", limit: 100 }, 10);
return new Set(rows.map((r) => bareId(r.id)));
})
);
return { published, scheduled };
}
+61
View File
@@ -0,0 +1,61 @@
import { prisma } from "@/lib/db";
import { decryptToken } from "@/lib/crypto/tokenBox";
import { UserFacingError } from "./client";
import { systemUserSource, type PageSource } from "./pages";
// The only module that reads Page.tokenCipher. Decrypted tokens stay in
// process memory for a short TTL so a revoked/rotated token is not held long.
const TTL_MS = 30 * 60 * 1000;
const globalForTokens = globalThis as unknown as {
pageTokens?: Map<string, { token: string; fbPageId: string; at: number }>;
};
const cache = (globalForTokens.pageTokens ??= new Map());
export interface PageCredentials {
/** Page.id in our DB */
id: string;
fbPageId: string;
igUserId: string | null;
token: string;
}
/** Resolves credentials by our Page.id. Throws a user-facing error if the page is not usable. */
export async function getPageCredentials(pageId: string): Promise<PageCredentials> {
const page = await prisma.page.findUnique({
where: { id: pageId },
select: { id: true, fbPageId: true, igUserId: true, tokenCipher: true, status: true },
});
if (!page) throw new UserFacingError("ไม่พบเพจนี้ในระบบ");
if (page.status === "DISCONNECTED") throw new UserFacingError("เพจนี้ถูกถอดการเชื่อมต่อแล้ว");
const hit = cache.get(page.id);
if (hit && Date.now() - hit.at < TTL_MS) {
return { id: page.id, fbPageId: page.fbPageId, igUserId: page.igUserId, token: hit.token };
}
const token = decryptToken(page.tokenCipher);
cache.set(page.id, { token, fbPageId: page.fbPageId, at: Date.now() });
return { id: page.id, fbPageId: page.fbPageId, igUserId: page.igUserId, token };
}
/** Webhooks identify pages by their Facebook id. Returns null for pages we don't manage. */
export async function getPageCredentialsByFbId(fbPageId: string): Promise<PageCredentials | null> {
const page = await prisma.page.findUnique({ where: { fbPageId }, select: { id: true, status: true } });
if (!page || page.status === "DISCONNECTED") return null;
return getPageCredentials(page.id);
}
export function forgetPageToken(pageId: string) {
cache.delete(pageId);
}
/** Every token source for listing pages: system user (env, optional) + each Facebook login connection. */
export async function getPageSources(): Promise<PageSource[]> {
const sources: PageSource[] = [];
const sys = systemUserSource();
if (sys) sources.push(sys);
const connections = await prisma.metaConnection.findMany({ orderBy: { createdAt: "asc" } });
for (const c of connections) {
sources.push({ connectionId: c.id, label: c.name, token: decryptToken(c.tokenCipher) });
}
return sources;
}
+35
View File
@@ -0,0 +1,35 @@
import { NextResponse } from "next/server";
import { safeFacebookErrorMessage, UserFacingError, FacebookApiError } from "@/lib/facebook/client";
export async function readJson(req: Request): Promise<Record<string, unknown>> {
const body = await req.json().catch(() => null);
return body && typeof body === "object" ? (body as Record<string, unknown>) : {};
}
export const str = (v: unknown): string => (typeof v === "string" ? v : "");
export const optStr = (v: unknown): string | null => (typeof v === "string" && v.trim() ? v.trim() : null);
/** Maps thrown errors to a safe JSON response: UserFacingError → 400, Graph → 502, other → 500. */
export function errorResponse(e: unknown, context: string): NextResponse {
const message = safeFacebookErrorMessage(e, context);
const status = e instanceof UserFacingError ? 400 : e instanceof FacebookApiError ? 502 : 500;
return NextResponse.json({ error: message }, { status });
}
/**
* 200 HTML page that meta-refreshes to `path`. OAuth callbacks arrive as a
* cross-site navigation, so a 302 onward would still be cross-site and the
* SameSite=Strict session cookie would not be sent; a navigation started by
* 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, "&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>`;
return new Response(html, { headers: { "content-type": "text/html; charset=utf-8", "cache-control": "no-store" } });
}
/** Cron routes authenticate with `Authorization: Bearer ${CRON_SECRET}` (Vercel Cron sends it). */
export function cronAuthorized(req: Request): boolean {
const secret = process.env.CRON_SECRET;
return Boolean(secret) && req.headers.get("authorization") === `Bearer ${secret}`;
}
+39
View File
@@ -0,0 +1,39 @@
import type { ReplyRule, ReplyRuleKind } from "@prisma/client";
import { prisma } from "@/lib/db";
function normalize(s: string): string {
return s.normalize("NFC").toLowerCase().replace(/\s+/g, " ").trim();
}
/** Highest-priority active rule whose any keyword appears in the text. */
export async function matchRule(pageId: string, kind: ReplyRuleKind, text: string): Promise<ReplyRule | null> {
const rules = await prisma.replyRule.findMany({
where: { pageId, kind, isActive: true },
orderBy: [{ priority: "desc" }, { createdAt: "asc" }],
});
const t = normalize(text);
return rules.find((r) => r.keywords.some((k) => k.trim() && t.includes(normalize(k)))) ?? null;
}
/**
* Claims the (rule, recipient) dedupe slot before sending. Returns false if
* this person already got this rule. Call releaseReplySlot if the send fails
* so a webhook redelivery can retry.
*/
export async function claimReplySlot(ruleId: string, recipientId: string, sourceId: string): Promise<boolean> {
try {
await prisma.replyLog.create({ data: { ruleId, recipientId, sourceId } });
return true;
} catch {
return false;
}
}
export async function releaseReplySlot(ruleId: string, recipientId: string): Promise<void> {
await prisma.replyLog.delete({ where: { ruleId_recipientId: { ruleId, recipientId } } }).catch(() => {});
}
/** "Typing speed" pause so a bot reply doesn't land instantly. */
export function typingDelayMs(text: string): number {
return Math.min(900 + text.length * 35, 3500);
}
+60
View File
@@ -0,0 +1,60 @@
import type { Prisma } from "@prisma/client";
import { prisma } from "@/lib/db";
import { getPageCredentials } from "@/lib/facebook/tokens";
import { getPageDailyInsights, getPostInsights } from "@/lib/facebook/insights";
const POST_LOOKBACK_DAYS = 14;
export function todayUtc(): Date {
const n = new Date();
return new Date(Date.UTC(n.getUTCFullYear(), n.getUTCMonth(), n.getUTCDate()));
}
/**
* Upserts today's page snapshot and recent published posts' snapshots for one
* page. Used by the daily cron and the "ดึงข้อมูลตอนนี้" button — re-running
* on the same day overwrites that day's row.
*/
export async function snapshotPage(pageId: string, date = todayUtc()): Promise<{ posts: number }> {
const creds = await getPageCredentials(pageId);
const ins = await getPageDailyInsights(creds);
// page_fan_adds is retired — derive the delta from the previous snapshot.
const prev = await prisma.pageInsightSnapshot.findFirst({
where: { pageId, date: { lt: date } },
orderBy: { date: "desc" },
});
const row = {
views: ins.views,
engagements: ins.engagements,
follows: ins.follows,
followDelta: prev ? ins.follows - prev.follows : 0,
raw: ins.raw as Prisma.InputJsonValue,
};
await prisma.pageInsightSnapshot.upsert({
where: { pageId_date: { pageId, date } },
create: { pageId, date, ...row },
update: row,
});
const since = new Date(date.getTime() - POST_LOOKBACK_DAYS * 86400000);
const posts = await prisma.post.findMany({
where: { pageId, status: "PUBLISHED", fbPostId: { not: null }, updatedAt: { gte: since } },
select: { id: true, fbPostId: true },
});
let done = 0;
for (const post of posts) {
try {
const pi = await getPostInsights(creds, post.fbPostId!);
const prow = { impressions: pi.impressions, engaged: pi.engaged, reactions: pi.reactions, raw: pi.raw as Prisma.InputJsonValue };
await prisma.postInsightSnapshot.upsert({
where: { postId_date: { postId: post.id, date } },
create: { postId: post.id, date, ...prow },
update: prow,
});
done++;
} catch (e) {
console.error(`[insights] post=${post.id}`, e);
}
}
return { posts: done };
}
+34
View File
@@ -0,0 +1,34 @@
import { graphGet, graphPostJson, UserFacingError } from "@/lib/facebook/client";
import type { PageCredentials } from "@/lib/facebook/tokens";
async function waitForContainer(page: PageCredentials, containerId: string): Promise<void> {
for (let attempt = 0; attempt < 10; attempt++) {
const res = await graphGet(`/${containerId}`, page.token, { fields: "status_code" });
if (res.status_code === "FINISHED") return;
if (res.status_code === "ERROR") throw new Error("Instagram media container failed to process");
await new Promise((r) => setTimeout(r, 1500));
}
throw new Error("Timed out waiting for Instagram media container");
}
/**
* Single-image feed post. `imageUrl` must be publicly fetchable by Meta's
* servers (Vercel Blob public URL). Instagram has no native scheduling via the
* API — scheduled IG posts are fired by /api/cron/ig-publisher.
*/
export async function publishToInstagram(
page: PageCredentials,
params: { imageUrl: string; caption: string }
): Promise<{ mediaId: string; permalink: string | null }> {
if (!page.igUserId) throw new UserFacingError("เพจนี้ยังไม่ได้ผูกบัญชี Instagram Business");
const container = await graphPostJson(`/${page.igUserId}/media`, page.token, {
image_url: params.imageUrl,
caption: params.caption,
});
await waitForContainer(page, container.id);
const publish = await graphPostJson(`/${page.igUserId}/media_publish`, page.token, { creation_id: container.id });
const media = await graphGet(`/${publish.id}`, page.token, { fields: "permalink" }).catch(() => ({}));
return { mediaId: publish.id, permalink: media.permalink ?? null };
}
+316
View File
@@ -0,0 +1,316 @@
import type { Post, PostStatus } from "@prisma/client";
import { prisma } from "@/lib/db";
import { audit, SYSTEM_ACTOR } from "@/lib/audit";
import { actorLabel, isSuperadmin, type SessionUser } from "@/lib/auth/user";
import { getPageCredentials } from "@/lib/facebook/tokens";
import { cancelScheduledFacebookPost, publishToFacebook, scheduleTimeProblem } from "@/lib/facebook/posts";
import { publishToInstagram } from "@/lib/instagram/posts";
import { safeFacebookErrorMessage, UserFacingError } from "@/lib/facebook/client";
/** Approvals needed before a post can be published. */
export const REQUIRED_APPROVALS = 1;
export const EDITABLE_STATUSES: PostStatus[] = ["DRAFT", "PENDING_APPROVAL", "APPROVED", "FAILED", "CANCELLED"];
export interface PostContent {
title: string;
caption: string;
imageBlobUrl: string | null;
targets: ("FACEBOOK" | "INSTAGRAM")[];
}
export function contentProblem(c: PostContent): string | null {
if (!c.title.trim()) return "กรอกชื่อโพสต์";
if (!c.caption.trim() && !c.imageBlobUrl) return "ต้องมี caption หรือรูปอย่างน้อยหนึ่งอย่าง";
if (c.targets.length === 0) return "เลือกอย่างน้อยหนึ่งช่องทาง";
if (c.targets.includes("INSTAGRAM") && !c.imageBlobUrl) return "โพสต์ Instagram ต้องมีรูป";
if (c.caption.length > 63206) return "caption ยาวเกินที่ Facebook รับได้";
return null;
}
/**
* Edits content. Changing content after approval voids every approval and
* returns the post to PENDING_APPROVAL. Scheduled/published posts are locked —
* cancel the schedule first.
*/
export async function editPost(post: Post, user: SessionUser, next: PostContent, opts: { aiAssisted?: boolean } = {}): Promise<Post> {
if (!EDITABLE_STATUSES.includes(post.status)) {
throw new UserFacingError("โพสต์ที่ตั้งเวลาหรือเผยแพร่แล้วแก้ไม่ได้ — ยกเลิกการตั้งเวลาก่อน");
}
const problem = contentProblem(next);
if (problem) throw new UserFacingError(problem);
const changed =
post.title !== next.title ||
post.caption !== next.caption ||
post.imageBlobUrl !== next.imageBlobUrl ||
post.targets.join() !== next.targets.join();
if (!changed) return post;
const voidsApproval = post.status === "APPROVED" || post.status === "PENDING_APPROVAL";
const backToDraft = post.status === "FAILED" || post.status === "CANCELLED";
const newlyAiAssisted = Boolean(opts.aiAssisted) && !post.aiAssisted;
const detail = {
...(voidsApproval && post.status === "APPROVED" ? { note: "การอนุมัติเดิมเป็นโมฆะ" } : {}),
...(newlyAiAssisted ? { aiAssisted: true } : {}),
};
return prisma.$transaction(async (tx) => {
if (voidsApproval) await tx.postApproval.deleteMany({ where: { postId: post.id } });
const updated = await tx.post.update({
where: { id: post.id },
data: {
...next,
status: voidsApproval ? "PENDING_APPROVAL" : backToDraft ? "DRAFT" : post.status,
...(backToDraft ? { lastError: null } : {}),
...(newlyAiAssisted ? { aiAssisted: true } : {}),
lastEditedById: user.id,
lastEditedAt: new Date(),
},
});
await audit(
{
action: "POST_EDITED",
actorId: user.id,
actorLabel: actorLabel(user),
pageId: post.pageId,
postId: post.id,
detail: Object.keys(detail).length ? detail : undefined,
},
tx
);
return updated;
});
}
export async function submitForApproval(post: Post, user: SessionUser): Promise<Post> {
if (post.status !== "DRAFT" && post.status !== "FAILED" && post.status !== "CANCELLED") {
throw new UserFacingError("ส่งขออนุมัติได้เฉพาะโพสต์ที่เป็นฉบับร่าง");
}
return prisma.$transaction(async (tx) => {
await tx.postApproval.deleteMany({ where: { postId: post.id } });
const updated = await tx.post.update({ where: { id: post.id }, data: { status: "PENDING_APPROVAL", lastError: null } });
await audit({ action: "POST_SUBMITTED", actorId: user.id, actorLabel: actorLabel(user), pageId: post.pageId, postId: post.id }, tx);
return updated;
});
}
/** Separation of duty: the last editor cannot approve their own edit (SUPERADMIN may, and the log says so). */
export function selfApprovalBlockReason(post: Post, user: SessionUser): string | null {
if (post.lastEditedById !== user.id && post.createdById !== user.id) return null;
if (isSuperadmin(user)) return null;
return "คุณเป็นคนแก้โพสต์นี้ล่าสุด ต้องให้คนอื่นอนุมัติ";
}
export async function approvePost(post: Post, user: SessionUser, note: string | null): Promise<Post> {
if (post.status !== "PENDING_APPROVAL") throw new UserFacingError("โพสต์นี้ไม่ได้อยู่ในสถานะรออนุมัติ");
const block = selfApprovalBlockReason(post, user);
if (block) throw new UserFacingError(block);
const ownWork = post.lastEditedById === user.id || post.createdById === user.id;
return prisma.$transaction(async (tx) => {
await tx.postApproval.upsert({
where: { postId_approverId: { postId: post.id, approverId: user.id } },
create: { postId: post.id, approverId: user.id, approverLabel: actorLabel(user), note },
update: { note },
});
const votes = await tx.postApproval.count({ where: { postId: post.id } });
const done = votes >= REQUIRED_APPROVALS;
const updated = done ? await tx.post.update({ where: { id: post.id }, data: { status: "APPROVED" } }) : post;
await audit(
{
action: "POST_APPROVED",
actorId: user.id,
actorLabel: actorLabel(user),
pageId: post.pageId,
postId: post.id,
detail: { note, votes, required: REQUIRED_APPROVALS, ...(ownWork ? { selfApproved: true } : {}) },
},
tx
);
return updated;
});
}
export async function rejectPost(post: Post, user: SessionUser, note: string | null): Promise<Post> {
if (post.status !== "PENDING_APPROVAL" && post.status !== "APPROVED") {
throw new UserFacingError("ตีกลับได้เฉพาะโพสต์ที่รออนุมัติหรืออนุมัติแล้ว");
}
return prisma.$transaction(async (tx) => {
await tx.postApproval.deleteMany({ where: { postId: post.id } });
const updated = await tx.post.update({ where: { id: post.id }, data: { status: "DRAFT", lastError: note ? `ตีกลับ: ${note}` : null } });
await audit({ action: "POST_REJECTED", actorId: user.id, actorLabel: actorLabel(user), pageId: post.pageId, postId: post.id, detail: { note } }, tx);
return updated;
});
}
/**
* Publishes now (scheduledAt = null) or schedules. Facebook holds scheduled
* posts itself; Instagram has no API scheduling, so a scheduled IG target is
* left for /api/cron/ig-publisher.
*/
export async function publishPost(post: Post, user: SessionUser, scheduledAt: Date | null): Promise<Post> {
if (post.status !== "APPROVED") throw new UserFacingError("ต้องอนุมัติก่อนถึงจะเผยแพร่หรือตั้งเวลาได้");
if (scheduledAt) {
const problem = scheduleTimeProblem(scheduledAt);
if (problem) throw new UserFacingError(problem);
}
// Atomic claim: blocks a double-click or a second approver racing the first
// into publishing the same post twice to Facebook/Instagram.
const claim = await prisma.post.updateMany({
where: { id: post.id, status: "APPROVED", publishingAt: null },
data: { publishingAt: new Date() },
});
if (claim.count === 0) {
throw new UserFacingError("โพสต์นี้กำลังถูกเผยแพร่อยู่ — รอสักครู่แล้วลองโหลดหน้าใหม่");
}
let settled = false;
try {
const page = await getPageCredentials(post.pageId);
const errors: string[] = [];
const data: Partial<Post> = { scheduledPublishAt: scheduledAt, lastError: null, publishingAt: null };
let anySuccess = false;
if (post.targets.includes("FACEBOOK")) {
try {
const fb = await publishToFacebook(page, { caption: post.caption, imageUrl: post.imageBlobUrl, scheduledAt });
data.fbPostId = fb.fbPostId;
data.fbPermalink = fb.permalink;
anySuccess = true;
} catch (e) {
errors.push(`Facebook: ${safeFacebookErrorMessage(e, "publish:fb")}`);
}
}
if (post.targets.includes("INSTAGRAM") && !scheduledAt) {
try {
const ig = await publishToInstagram(page, { imageUrl: post.imageBlobUrl!, caption: post.caption });
data.igMediaId = ig.mediaId;
data.igPermalink = ig.permalink;
anySuccess = true;
} catch (e) {
errors.push(`Instagram: ${safeFacebookErrorMessage(e, "publish:ig")}`);
}
} else if (post.targets.includes("INSTAGRAM")) {
anySuccess = true; // queued for the cron
}
data.status = !anySuccess ? "FAILED" : scheduledAt ? "SCHEDULED" : "PUBLISHED";
if (errors.length) data.lastError = errors.join(" · ");
const updated = await prisma.post.update({ where: { id: post.id }, data });
settled = true;
await audit({
action: data.status === "FAILED" ? "POST_FAILED" : scheduledAt ? "POST_SCHEDULED" : "POST_PUBLISHED",
actorId: user.id,
actorLabel: actorLabel(user),
pageId: post.pageId,
postId: post.id,
detail: { scheduledAt: scheduledAt?.toISOString() ?? null, errors },
});
if (data.status === "FAILED") throw new UserFacingError(data.lastError ?? "เผยแพร่ไม่สำเร็จ");
return updated;
} catch (e) {
if (settled) throw e; // DB already updated and the lock already released above
// Failed before the final update ran (e.g. getPageCredentials threw) — release the lock.
const msg = e instanceof UserFacingError ? e.message : safeFacebookErrorMessage(e, "publish:unexpected");
await prisma.post.update({ where: { id: post.id }, data: { status: "FAILED", publishingAt: null, lastError: msg } });
await audit({
action: "POST_FAILED",
actorId: user.id,
actorLabel: actorLabel(user),
pageId: post.pageId,
postId: post.id,
detail: { error: msg },
});
throw new UserFacingError(msg);
}
}
/** Cancels a schedule and returns the post to APPROVED so it can be rescheduled. */
export async function cancelSchedule(post: Post, user: SessionUser): Promise<Post> {
if (post.status !== "SCHEDULED") throw new UserFacingError("โพสต์นี้ไม่ได้ตั้งเวลาไว้");
if (post.fbPostId) {
const page = await getPageCredentials(post.pageId);
await cancelScheduledFacebookPost(page, post.fbPostId);
}
const updated = await prisma.post.update({
where: { id: post.id },
data: { status: "APPROVED", scheduledPublishAt: null, fbPostId: null, fbPermalink: null },
});
await audit({ action: "POST_CANCELLED", actorId: user.id, actorLabel: actorLabel(user), pageId: post.pageId, postId: post.id });
return updated;
}
/**
* Pins a post to a day on the board (or unpins with null). A plan only: it
* never publishes and never touches approval. Locked once Facebook holds it.
*/
export async function planPost(post: Post, user: SessionUser, plannedAt: Date | null): Promise<Post> {
if (post.status === "SCHEDULED" || post.status === "PUBLISHED") {
throw new UserFacingError("โพสต์นี้ตั้งเวลาหรือเผยแพร่แล้ว ย้ายวันไม่ได้ — ยกเลิกการตั้งเวลาก่อน");
}
if (plannedAt && Number.isNaN(plannedAt.getTime())) throw new UserFacingError("วันที่ไม่ถูกต้อง");
const updated = await prisma.post.update({ where: { id: post.id }, data: { plannedAt } });
await audit({
action: "POST_PLANNED",
actorId: user.id,
actorLabel: actorLabel(user),
pageId: post.pageId,
postId: post.id,
detail: { plannedAt: plannedAt?.toISOString() ?? null },
});
return updated;
}
// Longer than the ig-publisher route's maxDuration (300s), so a lock left behind
// by a crashed/timed-out run is reclaimable by the next one instead of stalling forever.
const PUBLISH_LOCK_STALE_MS = 10 * 60 * 1000;
/** Cron: publish Instagram targets whose scheduled time has come. */
export async function publishDueInstagramPosts(now = new Date()): Promise<{ published: number; failed: number }> {
const staleBefore = new Date(now.getTime() - PUBLISH_LOCK_STALE_MS);
const unclaimed = [{ publishingAt: null }, { publishingAt: { lt: staleBefore } }];
const due = await prisma.post.findMany({
where: {
status: "SCHEDULED",
scheduledPublishAt: { lte: now },
targets: { has: "INSTAGRAM" },
igMediaId: null,
OR: unclaimed,
},
take: 20,
});
let published = 0;
let failed = 0;
for (const post of due) {
// Atomic claim: a concurrent/overlapping cron run can't grab the same post.
const claim = await prisma.post.updateMany({
where: { id: post.id, status: "SCHEDULED", OR: unclaimed },
data: { publishingAt: now },
});
if (claim.count === 0) continue;
try {
const page = await getPageCredentials(post.pageId);
const ig = await publishToInstagram(page, { imageUrl: post.imageBlobUrl!, caption: post.caption });
await prisma.post.update({
where: { id: post.id },
data: { igMediaId: ig.mediaId, igPermalink: ig.permalink, status: "PUBLISHED", publishingAt: null },
});
await audit({ action: "POST_PUBLISHED", actorLabel: SYSTEM_ACTOR, pageId: post.pageId, postId: post.id, detail: { platform: "INSTAGRAM" } });
published++;
} catch (e) {
const msg = `Instagram: ${safeFacebookErrorMessage(e, "cron:ig-publisher")}`;
// FB may already be live via its own scheduler — only the IG part failed.
await prisma.post.update({
where: { id: post.id },
data: { lastError: msg, status: post.fbPostId ? "PUBLISHED" : "FAILED", publishingAt: null },
});
await audit({ action: "POST_FAILED", actorLabel: SYSTEM_ACTOR, pageId: post.pageId, postId: post.id, detail: { error: msg } });
failed++;
}
}
return { published, failed };
}
+33
View File
@@ -0,0 +1,33 @@
import { randomBytes } from "node:crypto";
import { mkdir, writeFile } from "node:fs/promises";
import path from "node:path";
/**
* Replaces Vercel Blob (public, unguessable URLs) for self-hosted deploys.
* Files land on disk under UPLOAD_DIR — mount that path as a persistent
* volume in Coolify or uploads vanish on the next container rebuild.
*/
const UPLOAD_DIR = process.env.UPLOAD_DIR ?? "/app/.data/uploads";
export async function putLocalBlob(
key: string,
file: File,
opts: { contentType: string },
baseUrl: string
): Promise<{ url: string }> {
const ext = path.extname(key);
const base = key.slice(0, key.length - ext.length);
const suffixed = `${base}-${randomBytes(10).toString("hex")}${ext}`;
const dest = path.join(UPLOAD_DIR, suffixed);
await mkdir(path.dirname(dest), { recursive: true });
await writeFile(dest, Buffer.from(await file.arrayBuffer()));
return { url: `${baseUrl}/api/uploads/${suffixed}` };
}
/** Resolves a public `/api/uploads/<rest>` path to its file on disk, rejecting traversal. */
export function resolveUploadPath(segments: string[]): string | null {
if (segments.some((s) => s === "" || s === "." || s === "..")) return null;
return path.join(UPLOAD_DIR, ...segments);
}