Turnstile bot protection (sign-in, sign-up, password-reset): - Register Better Auth's captcha plugin with the cloudflare-turnstile provider; endpoints listed explicitly rather than relying on defaults. /reset-password is intentionally excluded — it is reached only via a single-use emailed token. - Add an explicit-render Turnstile widget component. Tokens are single-use, so each form resets the challenge after a failed submit; submit stays disabled until a token is held. - Read the site key server-side and pass it down as a prop, so rotating it does not require a rebuild. - Fail fast in production when TURNSTILE_SECRET_KEY is missing, and when a secret is set without a site key (that combination would demand a token no form can produce, locking every user out). - Pass a throwaway secret during `next build` in the Dockerfile, mirroring the existing BETTER_AUTH_SECRET treatment, so image builds don't need it. CSP fixes in middleware (these blocked Turnstile entirely): - Add frame-src for challenges.cloudflare.com. Without it the widget's iframe fell back to default-src 'self' and was blocked outright. - Allow 'unsafe-eval' and websockets in DEVELOPMENT only. `next dev` compiles with eval(), so the strict policy threw EvalError and killed hydration — no client JS ran at all, which also meant form submit handlers never fired. Production policy is unchanged and still strict. Also included (concurrent work in the tree): - Admin organizations pages and lib/admin/orgs. - Episode moderation migration, SEO metadata (sitemap, robots, JSON-LD, OG/Twitter images, manifest), Umami analytics, not-found page. Local dev database: docker-compose.dev.yml provisions Postgres 18 on port 5443 (5432-5442 are in use by other local projects). Note: `npx tsc --noEmit` currently fails in app/(app)/team/page.tsx — an `invitations` prop the component does not accept. This predates the commit and will fail `next build` until fixed. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
104 lines
3.5 KiB
TypeScript
104 lines
3.5 KiB
TypeScript
import "dotenv/config";
|
|
import { getBoss } from "@/lib/queue/pgboss";
|
|
import {
|
|
QUEUES,
|
|
generateEpisodePayloadSchema,
|
|
echoPayloadSchema,
|
|
type GenerateEpisodePayload,
|
|
type EchoPayload,
|
|
} from "@/lib/queue/jobs";
|
|
import { runEpisodeGeneration, refundEpisodeUsage } from "@/lib/ai/pipeline/generate-episode";
|
|
import { failEpisode } from "@/lib/episodes/status";
|
|
import { recordHeartbeat } from "@/lib/queue/health";
|
|
|
|
const HEARTBEAT_NAME = "generation-worker";
|
|
|
|
const CONCURRENCY = Math.max(1, Number(process.env.WORKER_CONCURRENCY ?? "2"));
|
|
|
|
async function main() {
|
|
const boss = await getBoss({ supervise: true });
|
|
console.log(`[worker] started (concurrency=${CONCURRENCY})`);
|
|
|
|
// Liveness heartbeat so the admin health page can tell the worker is running.
|
|
await recordHeartbeat(HEARTBEAT_NAME).catch(() => {});
|
|
setInterval(() => {
|
|
recordHeartbeat(HEARTBEAT_NAME).catch((e) => console.error("[worker] heartbeat failed", e));
|
|
}, 15_000);
|
|
|
|
// Proof-of-loop queue used by health checks / verification.
|
|
await boss.work<EchoPayload>(QUEUES.echo, { batchSize: 1 }, async (jobs) => {
|
|
for (const job of jobs) {
|
|
const parsed = echoPayloadSchema.safeParse(job.data);
|
|
if (!parsed.success) {
|
|
console.error("[echo] invalid payload — skipping job", parsed.error.issues);
|
|
continue;
|
|
}
|
|
console.log("[echo]", parsed.data);
|
|
}
|
|
});
|
|
|
|
// Episode generation. batchSize 1 = independent retries per job.
|
|
await boss.work<GenerateEpisodePayload>(
|
|
QUEUES.generateEpisode,
|
|
{ batchSize: 1, includeMetadata: true },
|
|
async (jobs) => {
|
|
for (const job of jobs) {
|
|
await handleGenerate(job);
|
|
}
|
|
}
|
|
);
|
|
|
|
const shutdown = async (signal: string) => {
|
|
console.log(`[worker] ${signal} — shutting down`);
|
|
await boss.stop({ graceful: true });
|
|
process.exit(0);
|
|
};
|
|
process.on("SIGINT", () => void shutdown("SIGINT"));
|
|
process.on("SIGTERM", () => void shutdown("SIGTERM"));
|
|
}
|
|
|
|
async function handleGenerate(job: {
|
|
data: GenerateEpisodePayload;
|
|
retryCount?: number;
|
|
retryLimit?: number;
|
|
}) {
|
|
// Runtime-validate the payload at the consume boundary. An invalid payload is
|
|
// not retryable, so skip it rather than throwing into the work loop.
|
|
const parsed = generateEpisodePayloadSchema.safeParse(job.data);
|
|
if (!parsed.success) {
|
|
console.error("[generate] invalid payload — skipping job", parsed.error.issues);
|
|
return;
|
|
}
|
|
const { episodeId, type } = parsed.data;
|
|
try {
|
|
await runEpisodeGeneration(episodeId, type ?? "full");
|
|
} catch (err) {
|
|
const message = err instanceof Error ? err.message : String(err);
|
|
const retryCount = job.retryCount ?? 0;
|
|
const retryLimit = job.retryLimit ?? 0;
|
|
const exhausted = retryCount >= retryLimit;
|
|
console.error(
|
|
`[generate] ${episodeId} failed (attempt ${retryCount}/${retryLimit}): ${message}`
|
|
);
|
|
if (exhausted) {
|
|
// Terminal failure: refund the usage the enqueuing caller reserved up
|
|
// front, so a failed generation doesn't permanently consume quota.
|
|
// (The worker never increments; see lib/usage/meter.ts invariant.)
|
|
try {
|
|
await refundEpisodeUsage(episodeId, type ?? "full");
|
|
} catch (refundErr) {
|
|
console.error(`[generate] ${episodeId} usage refund failed`, refundErr);
|
|
}
|
|
// Raw `message` goes to the job row (admin-only); the user sees generic copy.
|
|
await failEpisode(episodeId, message);
|
|
} else {
|
|
throw err; // let pg-boss retry with backoff
|
|
}
|
|
}
|
|
}
|
|
|
|
main().catch((err) => {
|
|
console.error("[worker] fatal", err);
|
|
process.exit(1);
|
|
});
|