|
| 1 | +import { NextRequest, NextResponse } from "next/server"; |
| 2 | +import { requireSession, AuthError } from "@/lib/auth"; |
| 3 | + |
| 4 | +// POST /api/wiki/profile/regenerate — trigger the wiki-profile consolidation |
| 5 | +// worker (integrations/consolidation-workers/wiki-profile) to synthesize the |
| 6 | +// "user-profile" wiki page. The worker bootstraps the page itself via |
| 7 | +// wiki_upsert_page, so this one route serves both "create" and "regenerate". |
| 8 | +// |
| 9 | +// The worker is its own Edge Function, separate from the open-brain-rest |
| 10 | +// gateway that lib/api.ts talks to, so this route resolves the worker URL |
| 11 | +// itself instead of reusing apiFetch: |
| 12 | +// 1. WIKI_PROFILE_URL wins when set. It is a plain server env — route |
| 13 | +// handlers run server-side, so no NEXT_PUBLIC_ prefix is needed (and a |
| 14 | +// restart, not a rebuild, picks up changes). |
| 15 | +// 2. Otherwise derive from NEXT_PUBLIC_API_URL by swapping the Edge Function |
| 16 | +// name: …/functions/v1/open-brain-rest → …/functions/v1/wiki-profile. |
| 17 | + |
| 18 | +/** |
| 19 | + * How long to wait for the worker. A full profile run makes up to 10 LLM |
| 20 | + * calls; the platform default fetch has no timeout and would pin this route |
| 21 | + * until the host kills it. 120s covers a normal run — the Edge Function's own |
| 22 | + * 150s wall clock is the true upper bound. |
| 23 | + */ |
| 24 | +const WORKER_TIMEOUT_MS = 120_000; |
| 25 | + |
| 26 | +/** |
| 27 | + * Mirror lib/api.ts's WR-06 check: refuse to send the session's brain key to |
| 28 | + * a non-https host (localhost excepted for dev), so a misconfigured env var |
| 29 | + * cannot fan the key out to an attacker-controlled URL. |
| 30 | + */ |
| 31 | +function validateWorkerUrl(candidate: string): string | null { |
| 32 | + try { |
| 33 | + const parsed = new URL(candidate); |
| 34 | + if ( |
| 35 | + parsed.protocol !== "https:" && |
| 36 | + parsed.hostname !== "localhost" && |
| 37 | + parsed.hostname !== "127.0.0.1" |
| 38 | + ) { |
| 39 | + return null; |
| 40 | + } |
| 41 | + // fetch() rejects credentialed URLs outright (TypeError before any |
| 42 | + // network attempt), which would surface as a misleading generic 502. |
| 43 | + if (parsed.username || parsed.password) { |
| 44 | + return null; |
| 45 | + } |
| 46 | + return candidate; |
| 47 | + } catch { |
| 48 | + return null; |
| 49 | + } |
| 50 | +} |
| 51 | + |
| 52 | +function resolveWorkerUrl(): string | null { |
| 53 | + const override = process.env.WIKI_PROFILE_URL?.trim(); |
| 54 | + if (override) return validateWorkerUrl(override); |
| 55 | + |
| 56 | + const base = (process.env.NEXT_PUBLIC_API_URL ?? "").trim(); |
| 57 | + if (!base) return null; |
| 58 | + const derived = base.replace(/\/open-brain-rest\/?$/, "/wiki-profile"); |
| 59 | + // If the base doesn't end in /open-brain-rest the swap is a no-op and we |
| 60 | + // cannot guess the worker URL — the operator must set WIKI_PROFILE_URL. |
| 61 | + if (derived === base) return null; |
| 62 | + return validateWorkerUrl(derived); |
| 63 | +} |
| 64 | + |
| 65 | +export async function POST(request: NextRequest) { |
| 66 | + let apiKey: string; |
| 67 | + try { |
| 68 | + ({ apiKey } = await requireSession()); |
| 69 | + } catch (err) { |
| 70 | + if (err instanceof AuthError) |
| 71 | + return NextResponse.json({ error: "Unauthorized" }, { status: 401 }); |
| 72 | + throw err; |
| 73 | + } |
| 74 | + |
| 75 | + const workerUrl = resolveWorkerUrl(); |
| 76 | + if (!workerUrl) { |
| 77 | + console.error( |
| 78 | + "[wiki/profile:regenerate] cannot resolve worker URL — set WIKI_PROFILE_URL " + |
| 79 | + "(NEXT_PUBLIC_API_URL does not end in /open-brain-rest, or the URL is not https)" |
| 80 | + ); |
| 81 | + return NextResponse.json( |
| 82 | + { |
| 83 | + error: |
| 84 | + "wiki-profile worker URL is not configured — set WIKI_PROFILE_URL to the worker's https URL.", |
| 85 | + }, |
| 86 | + { status: 500 } |
| 87 | + ); |
| 88 | + } |
| 89 | + |
| 90 | + // Optional {dry_run: true} body flag. The worker takes dry-run as a query |
| 91 | + // param, so translate body → query here; anything else in the body is ignored. |
| 92 | + const body = (await request.json().catch(() => ({}))) as { dry_run?: unknown }; |
| 93 | + const target = body?.dry_run === true ? `${workerUrl}?dry_run=true` : workerUrl; |
| 94 | + |
| 95 | + const controller = new AbortController(); |
| 96 | + const timer = setTimeout( |
| 97 | + () => controller.abort(new Error(`wiki-profile worker timeout after ${WORKER_TIMEOUT_MS}ms`)), |
| 98 | + WORKER_TIMEOUT_MS |
| 99 | + ); |
| 100 | + let res: Response; |
| 101 | + try { |
| 102 | + res = await fetch(target, { |
| 103 | + method: "POST", |
| 104 | + headers: { "x-brain-key": apiKey, "Content-Type": "application/json" }, |
| 105 | + signal: controller.signal, |
| 106 | + }); |
| 107 | + } catch (err) { |
| 108 | + // With an abort reason, undici rejects with that Error; older runtimes |
| 109 | + // reject with a DOMException named AbortError. Catch both shapes. |
| 110 | + const isTimeout = |
| 111 | + (err instanceof Error && err.message.startsWith("wiki-profile worker timeout")) || |
| 112 | + (typeof err === "object" && |
| 113 | + err !== null && |
| 114 | + (err as { name?: string }).name === "AbortError"); |
| 115 | + if (isTimeout) { |
| 116 | + console.error(`[wiki/profile:regenerate] worker timed out after ${WORKER_TIMEOUT_MS}ms`); |
| 117 | + return NextResponse.json( |
| 118 | + { |
| 119 | + error: |
| 120 | + "Profile generation timed out. The worker may still be finishing — refresh in a minute to see the result.", |
| 121 | + }, |
| 122 | + { status: 504 } |
| 123 | + ); |
| 124 | + } |
| 125 | + console.error("[wiki/profile:regenerate] fetch failed", err); |
| 126 | + return NextResponse.json( |
| 127 | + { error: "Could not reach the wiki-profile worker." }, |
| 128 | + { status: 502 } |
| 129 | + ); |
| 130 | + } finally { |
| 131 | + clearTimeout(timer); |
| 132 | + } |
| 133 | + |
| 134 | + if (!res.ok) { |
| 135 | + // ApiError discipline: log the upstream body server-side for debugging, |
| 136 | + // return only a safe hand-written message to the browser. |
| 137 | + const upstreamBody = await res.text().catch(() => ""); |
| 138 | + console.error("[wiki/profile:regenerate] upstream", res.status, upstreamBody); |
| 139 | + if (res.status === 404) { |
| 140 | + // The Supabase functions host answers 404 when the function isn't |
| 141 | + // deployed — the single most likely failure for a fresh install. |
| 142 | + return NextResponse.json( |
| 143 | + { |
| 144 | + error: |
| 145 | + "wiki-profile worker not deployed — deploy integrations/consolidation-workers/wiki-profile " + |
| 146 | + "(supabase functions deploy wiki-profile --no-verify-jwt), then try again.", |
| 147 | + }, |
| 148 | + { status: 404 } |
| 149 | + ); |
| 150 | + } |
| 151 | + if (res.status === 401) { |
| 152 | + return NextResponse.json( |
| 153 | + { error: "The worker rejected the brain key (MCP_ACCESS_KEY mismatch between functions)." }, |
| 154 | + { status: 401 } |
| 155 | + ); |
| 156 | + } |
| 157 | + if (res.status === 503) { |
| 158 | + return NextResponse.json( |
| 159 | + { |
| 160 | + error: |
| 161 | + "The worker is missing configuration (LLM API keys or MCP_ACCESS_KEY) — check its Supabase secrets.", |
| 162 | + }, |
| 163 | + { status: 503 } |
| 164 | + ); |
| 165 | + } |
| 166 | + return NextResponse.json( |
| 167 | + { error: `Profile generation failed (upstream ${res.status}).` }, |
| 168 | + { status: res.status } |
| 169 | + ); |
| 170 | + } |
| 171 | + |
| 172 | + let payload: unknown; |
| 173 | + try { |
| 174 | + payload = await res.json(); |
| 175 | + } catch (err) { |
| 176 | + console.error("[wiki/profile:regenerate] unreadable worker response", err); |
| 177 | + return NextResponse.json( |
| 178 | + { error: "The worker returned an unreadable response." }, |
| 179 | + { status: 502 } |
| 180 | + ); |
| 181 | + } |
| 182 | + |
| 183 | + // Pass the worker's JSON through unchanged — the client renders the |
| 184 | + // per-section outcomes (created / updated / pending / skipped / error). |
| 185 | + return NextResponse.json(payload); |
| 186 | +} |
0 commit comments