19 lines
1.3 KiB
TypeScript
19 lines
1.3 KiB
TypeScript
import { NextResponse } from "next/server";
|
|
import { requireUser } from "@/lib/auth";
|
|
import { db } from "@/lib/db";
|
|
import { createWebhookSecret, webhookSecretHash } from "@/lib/webhook";
|
|
import { requireSameOrigin } from "@/lib/security";
|
|
|
|
export async function POST(request: Request, { params }: { params: Promise<{ id: string }> }) {
|
|
try {
|
|
requireSameOrigin(request); const user = await requireUser(); const { id: rawId } = await params; const id = Number(rawId);
|
|
const source = db.prepare("SELECT id,webhook_mode FROM sources WHERE id=? AND user_id=?").get(id, user.id) as { id: number; webhook_mode: string } | undefined;
|
|
if (!source) return NextResponse.json({ error: "Not found" }, { status: 404 });
|
|
if (source.webhook_mode === "signed") return NextResponse.json({ error: "這個 Webhook 已由 Memos 自動管理;請重新連接來源以重新建立。" }, { status: 409 });
|
|
const secret = createWebhookSecret();
|
|
db.prepare("UPDATE sources SET webhook_secret_hash=? WHERE id=?").run(webhookSecretHash(secret), id);
|
|
const publicOrigin = (process.env.NEXT_PUBLIC_APP_URL || new URL(request.url).origin).replace(/\/$/, "");
|
|
return NextResponse.json({ url: `${publicOrigin}/api/sync/webhook/${id}/${secret}` });
|
|
} catch { return NextResponse.json({ error: "Unauthorized" }, { status: 401 }); }
|
|
}
|