diff --git a/README.md b/README.md index b9683ba..77c0690 100644 --- a/README.md +++ b/README.md @@ -71,7 +71,7 @@ without any MCP client setup. Same content, two surfaces: humans read the MDX, agents query over MCP. ```bash -export AI_GATEWAY_API_KEY=... # free proxy; your provider key routes through it +npx helpbase login # magic-link, no card, free 500k tokens/day npx helpbase context . # synthesize cited how-tos from your repo npx helpbase context . --ask "how do I log in?" # answer in terminal, no MCP client required ``` @@ -113,20 +113,24 @@ teammates deploy to the same tenant. CI users can skip the prompt with ### Generate articles from your site with AI -Pass `--url` and helpbase scrapes the page, sends it through the Vercel AI -Gateway, and writes structured MDX articles to `content/`. Each article +Pass `--url` and helpbase scrapes the page, generates structured MDX through +the hosted helpbase proxy, and writes the articles to `content/`. Each article comes back with a title, description, tags, and a full markdown body. ```bash -export AI_GATEWAY_API_KEY=your_key_here +npx helpbase login # once, free tier (500k tokens/day) npx create-helpbase my-help-center --url https://yourproduct.com --test ``` -Get your key at [vercel.com/ai-gateway](https://vercel.com/ai-gateway). The -`--test` flag uses Gemini 3.1 Flash Lite for cheap, fast generation. Pass +The `--test` flag uses Gemini 3.1 Flash Lite for cheap, fast generation. Pass `--model anthropic/claude-sonnet-4.6` (or any Gateway-supported model) to override. +**Power users + CI:** skip the helpbase proxy entirely with your own +[Vercel AI Gateway](https://vercel.com/ai-gateway) key — `export +AI_GATEWAY_API_KEY=...` before running. See +[helpbase.dev/docs/byok](https://helpbase.dev/docs/byok). + ### Drop into an existing Next.js app If you already have a Next.js + shadcn/ui project, add helpbase as a shadcn diff --git a/apps/web/app/(main)/errors/[code]/page.tsx b/apps/web/app/(main)/errors/[code]/page.tsx index 0e838ad..0c80d7b 100644 --- a/apps/web/app/(main)/errors/[code]/page.tsx +++ b/apps/web/app/(main)/errors/[code]/page.tsx @@ -278,6 +278,90 @@ const ERRORS: Record = { "Run `npx create-helpbase my-help-center` to start a fresh one.", ], }, + "e-auth-required": { + code: "E_AUTH_REQUIRED", + title: "Not signed in to helpbase", + summary: + "A command that needs authentication (generate, sync, context) ran without a helpbase session and without a BYOK key.", + causes: [ + "You haven't run `helpbase login` on this machine yet.", + "Your session expired and could not be refreshed.", + "In CI, `HELPBASE_TOKEN` is either not set or no longer valid.", + ], + fixes: [ + "Run `helpbase login` — free tier, no card, 500k tokens/day.", + "For CI: set `HELPBASE_TOKEN` to a valid session token.", + "Or bring your own key: `export AI_GATEWAY_API_KEY=…` (see /docs/byok).", + ], + seeAlso: [{ label: "BYOK docs", href: "/docs/byok" }], + }, + "e-quota-exceeded": { + code: "E_QUOTA_EXCEEDED", + title: "Daily free-tier quota reached", + summary: + "You've used today's free allocation of tokens across helpbase LLM calls. The limit resets at UTC midnight.", + causes: [ + "You hit 500,000 tokens of generate / sync / context --ask calls today.", + "A single call would take you over the remaining budget.", + ], + fixes: [ + "Wait for the UTC-midnight reset.", + "Join the paid-tier waitlist: https://helpbase.dev/waitlist", + "Bring your own Vercel AI Gateway key: `export AI_GATEWAY_API_KEY=…` (unlimited, your own bill).", + ], + seeAlso: [ + { label: "Waitlist", href: "/waitlist" }, + { label: "BYOK docs", href: "/docs/byok" }, + ], + }, + "e-global-cap": { + code: "E_GLOBAL_CAP", + title: "helpbase is over its daily cap", + summary: + "helpbase enforces a global 10M-token-per-day circuit breaker to protect against runaway spend. That cap was hit.", + causes: [ + "A load spike (genuine or otherwise) exhausted the global daily allocation.", + "Resets at UTC midnight like the per-user cap.", + ], + fixes: [ + "Wait for the UTC-midnight reset.", + "Bring your own Vercel AI Gateway key to bypass the hosted proxy entirely: `export AI_GATEWAY_API_KEY=…`", + ], + seeAlso: [{ label: "BYOK docs", href: "/docs/byok" }], + }, + "e-llm-network": { + code: "E_LLM_NETWORK", + title: "Couldn't reach helpbase.dev", + summary: + "The CLI tried to call the hosted LLM proxy but the request never landed — likely a network problem between you and helpbase.dev.", + causes: [ + "Internet connection is down or flaky.", + "A corporate proxy or firewall is blocking helpbase.dev.", + "DNS resolution is failing.", + ], + fixes: [ + "Check your connection and retry — transient blips are common.", + "If you're behind a corporate proxy, verify helpbase.dev is reachable.", + "Fall back to BYOK so calls don't go through helpbase.dev: `export AI_GATEWAY_API_KEY=…`", + ], + seeAlso: [{ label: "BYOK docs", href: "/docs/byok" }], + }, + "e-llm-gateway": { + code: "E_LLM_GATEWAY", + title: "LLM provider returned an error", + summary: + "The underlying model provider (e.g. Anthropic, Google) returned a non-success response. No tokens were charged against your quota.", + causes: [ + "The model ID is wrong or unsupported by Vercel AI Gateway.", + "Upstream provider is degraded.", + "The prompt triggered a provider-side safety filter.", + ], + fixes: [ + "Retry in a moment — transient upstream errors are common.", + "Try a different `--model` (e.g. `anthropic/claude-sonnet-4.6`).", + "Check status.anthropic.com / openai.com if the problem persists.", + ], + }, } export function generateStaticParams() { diff --git a/apps/web/app/(main)/waitlist/page.tsx b/apps/web/app/(main)/waitlist/page.tsx new file mode 100644 index 0000000..39b7778 --- /dev/null +++ b/apps/web/app/(main)/waitlist/page.tsx @@ -0,0 +1,83 @@ +import type { Metadata } from "next" +import { joinWaitlist } from "@/lib/waitlist" + +export const metadata: Metadata = { + title: "Join the paid-tier waitlist — helpbase", + description: + "helpbase is free to use (500k tokens/day). Paid tier with higher limits is coming. Drop your email to get notified when it ships.", +} + +export default function WaitlistPage({ + searchParams, +}: { + searchParams?: Promise<{ status?: string; from?: string }> +}) { + return +} + +/** Mirrors lib/waitlist.ts — same regex, same fallback. */ +const SAFE_SOURCE_RE = /^[a-z0-9_-]{1,40}$/ + +async function WaitlistContent({ + searchParamsP, +}: { + searchParamsP?: Promise<{ status?: string; from?: string }> +}) { + const sp = (await searchParamsP) ?? {} + const status = sp.status + const rawFrom = sp.from ?? "waitlist" + const from = SAFE_SOURCE_RE.test(rawFrom) ? rawFrom : "waitlist" + + return ( +
+

+ paid tier (coming soon) +

+

Join the waitlist

+

+ helpbase is free to use — 500,000 tokens per day is enough for most teams. A paid tier + with higher limits, priority support, and team accounts is on the way. Drop your email + and we’ll let you know when it ships. +

+ +

+ Need more tokens right now?{" "} + + Bring your own Vercel AI Gateway key + {" "} + — unlimited, your own cost. +

+ + {status === "ok" ? ( +
+ Thanks — you’re on the list. We’ll email you when the paid tier ships. +
+ ) : status === "error" ? ( +
+ Something went wrong. Try again, or email hi@helpbase.dev. +
+ ) : null} + +
+ + + +
+ +

+ No spam. We’ll email once when the paid tier opens. Unsubscribe any time. +

+
+ ) +} diff --git a/apps/web/app/api/v1/llm/_shared.ts b/apps/web/app/api/v1/llm/_shared.ts new file mode 100644 index 0000000..8060547 --- /dev/null +++ b/apps/web/app/api/v1/llm/_shared.ts @@ -0,0 +1,219 @@ +import { NextResponse } from "next/server" +import type { WireErrorBody, WireErrorCode, WireQuotaStatus, WireUsage } from "@workspace/shared/llm-wire" +import { BYOK_DOCS_URL, UPGRADE_URL } from "@workspace/shared/llm-wire" +import { getServiceRoleClient, verifyBearerToken } from "@/lib/supabase-admin" + +/** + * Shared helpers for /api/v1/llm/generate-object and /generate-text. + * + * withAuthAndQuota(req) → { userId, quota, maxOutputTokens } on success + * → NextResponse on any gate failure (401/429/503) + * + * The route handler then runs the Vercel AI SDK call and calls + * logUsageEvent() on completion, successful OR failed. + * + * Quota math: + * - Per-user daily cap: 500,000 tokens (free tier) + * - Per-call ceiling: 100,000 output tokens + * - Global daily cap: 10,000,000 tokens (circuit breaker) + * + * Overrun is accepted (same fire-and-forget pattern as apps/web/lib/rate-limit.ts). + */ + +export const DAILY_USER_LIMIT = 500_000 +export const PER_CALL_CEILING = 100_000 +export const GLOBAL_DAILY_LIMIT = 10_000_000 + +// ── Auth + quota gate ────────────────────────────────────────────────── + +export interface AuthedContext { + userId: string + usedToday: number + resetAtIso: string + maxOutputTokens: number +} + +export async function withAuthAndQuota( + req: Request, +): Promise { + const authz = req.headers.get("authorization") ?? "" + const match = /^Bearer\s+(.+)$/i.exec(authz) + if (!match) { + return wireError(401, "auth_required", "Missing or malformed Authorization header.") + } + const token = match[1]! + + const user = await verifyBearerToken(token) + if (!user) { + return wireError(401, "auth_required", "Invalid or expired session token.") + } + + // Parallel: read user's today-tokens + global counter. + const client = getServiceRoleClient() + const [userRes, globalRes] = await Promise.all([ + client.rpc("get_user_tokens_today", { p_user_id: user.userId }), + client.rpc("get_global_tokens_today"), + ]) + + if (userRes.error || globalRes.error) { + // Failing closed on DB error — safer than silently gifting tokens. + return wireError( + 503, + "internal_error", + "Supabase is unavailable. Retry in a moment.", + ) + } + + const usedToday = Number(userRes.data ?? 0) + const globalToday = Number(globalRes.data ?? 0) + const resetAtIso = nextUtcMidnightIso() + + if (usedToday >= DAILY_USER_LIMIT) { + return wireError(429, "quota_exceeded", "Daily free-tier token quota reached.", { + usedToday, + dailyLimit: DAILY_USER_LIMIT, + resetAt: resetAtIso, + upgradeUrl: UPGRADE_URL, + byokDocsUrl: BYOK_DOCS_URL, + }) + } + + if (globalToday >= GLOBAL_DAILY_LIMIT) { + return wireError(503, "global_cap_hit", "helpbase is over its daily cap.", { + resetAt: resetAtIso, + byokDocsUrl: BYOK_DOCS_URL, + }) + } + + // Clamp per-call output cap to what's actually left. + const remaining = DAILY_USER_LIMIT - usedToday + const maxOutputTokens = Math.min(PER_CALL_CEILING, remaining) + + return { + userId: user.userId, + usedToday, + resetAtIso, + maxOutputTokens, + } +} + +// ── Usage logging ────────────────────────────────────────────────────── + +export interface LogUsageInput { + userId: string + route: "generate-object" | "generate-text" + model: string + promptTokens: number + completionTokens: number + costUsd: number + status: "ok" | "gateway_error" | "schema_error" + latencyMs: number + requestId?: string +} + +/** + * Insert one row into `llm_usage_events` AND upsert the global counter. + * Both are fire-and-forget relative to the happy path: we don't await + * them on the critical path of the response, but we do await here so the + * usedToday reflected in the response is fresh. + */ +export async function logUsageEvent(input: LogUsageInput): Promise { + const client = getServiceRoleClient() + const total = input.promptTokens + input.completionTokens + + const { error: insertErr } = await client.from("llm_usage_events").insert({ + user_id: input.userId, + route: input.route, + model: input.model, + prompt_tokens: input.promptTokens, + completion_tokens: input.completionTokens, + cost_usd: input.costUsd, + status: input.status, + latency_ms: input.latencyMs, + request_id: input.requestId ?? null, + }) + + if (insertErr) { + // Failure mode #2 from the plan's failure-modes table: fail-open, log + // to Vercel logs for later reconciliation (TODO-022). + console.error("[llm_usage_events insert failed]", { + userId: input.userId, + route: input.route, + total, + message: insertErr.message, + }) + } + + if (input.status === "ok" && total > 0) { + const today = new Date().toISOString().slice(0, 10) + // Atomic increment via SQL function — see migration + // `atomic_increment_global_tokens`. The previous client-side upsert + // pattern (onConflict: "day") OVERWROTE the daily counter on every + // call, silently disabling the 10M/day global circuit breaker. + // Concurrent requests also need true atomicity; a read-modify-write + // is race-prone even on a single instance. + const { error: incrErr } = await client.rpc("increment_global_tokens", { + p_day: today, + p_delta: total, + }) + if (incrErr) { + console.error("[global_daily_tokens increment failed]", { + today, + total, + message: incrErr.message, + }) + } + } +} + +// ── Quota snapshot (for response payloads) ───────────────────────────── + +export function quotaSnapshot(usedTodayAfter: number, resetAtIso: string): WireQuotaStatus { + return { + usedToday: usedTodayAfter, + dailyLimit: DAILY_USER_LIMIT, + resetAt: resetAtIso, + } +} + +export function wireUsageFromSdk(usage: unknown, costUsd = 0): WireUsage { + const u = (usage ?? {}) as { + inputTokens?: number + outputTokens?: number + promptTokens?: number + completionTokens?: number + totalTokens?: number + } + const prompt = u.inputTokens ?? u.promptTokens ?? 0 + const completion = u.outputTokens ?? u.completionTokens ?? 0 + return { + promptTokens: prompt, + completionTokens: completion, + totalTokens: u.totalTokens ?? prompt + completion, + costUsd, + } +} + +// ── Error envelope ───────────────────────────────────────────────────── + +export function wireError( + status: number, + code: WireErrorCode, + message: string, + extra: Partial = {}, +): NextResponse { + return NextResponse.json( + { error: code, message, ...extra }, + { status }, + ) +} + +// ── Time helpers ─────────────────────────────────────────────────────── + +export function nextUtcMidnightIso(): string { + const d = new Date() + const next = new Date( + Date.UTC(d.getUTCFullYear(), d.getUTCMonth(), d.getUTCDate() + 1, 0, 0, 0, 0), + ) + return next.toISOString() +} diff --git a/apps/web/app/api/v1/llm/generate-object/route.ts b/apps/web/app/api/v1/llm/generate-object/route.ts new file mode 100644 index 0000000..4d3d38b --- /dev/null +++ b/apps/web/app/api/v1/llm/generate-object/route.ts @@ -0,0 +1,143 @@ +import type { NextRequest } from "next/server" +import { NextResponse } from "next/server" +import { generateObject, jsonSchema } from "ai" +import type { + GenerateObjectRequest, + GenerateObjectResponse, +} from "@workspace/shared/llm-wire" +import { + logUsageEvent, + quotaSnapshot, + wireError, + wireUsageFromSdk, + withAuthAndQuota, + PER_CALL_CEILING, +} from "../_shared" + +/** + * POST /api/v1/llm/generate-object + * + * Auth: Bearer (from helpbase CLI). + * Body: { model, prompt?, messages?, schema (JSON Schema), images?, maxOutputTokens? } + * Return: { object, usage, quota } + * + * Applies per-user daily token cap + global circuit breaker before the call; + * logs `llm_usage_events` and bumps `global_daily_tokens` after. + */ + +export const runtime = "nodejs" +// `dynamic = "force-dynamic"` only disables static optimization — it does NOT +// raise Vercel's 4.5 MB request body cap. Multimodal requests with large +// base64 images will still 413 at the edge. If that becomes a real problem, +// move image upload to a signed-URL flow (TODO) rather than trying to extend +// the body cap here. +export const dynamic = "force-dynamic" + +export async function POST(req: NextRequest): Promise { + const gate = await withAuthAndQuota(req) + if (gate instanceof NextResponse) return gate + const { userId, resetAtIso, maxOutputTokens: remainingBudget } = gate + + let body: GenerateObjectRequest + try { + body = (await req.json()) as GenerateObjectRequest + } catch { + return wireError(400, "bad_request", "Request body is not valid JSON.") + } + + if (!body.model || typeof body.model !== "string") { + return wireError(400, "bad_request", "Missing required field: `model` (string).") + } + if (!body.schema || typeof body.schema !== "object") { + return wireError(400, "bad_request", "Missing required field: `schema` (JSON Schema object).") + } + const hasMessages = Array.isArray(body.messages) && body.messages.length > 0 + if (!body.prompt && !hasMessages) { + return wireError(400, "bad_request", "Provide either `prompt` or a non-empty `messages` array.") + } + + // Clamp requested cap to the per-call ceiling AND to the remaining budget. + const requested = body.maxOutputTokens ?? PER_CALL_CEILING + const maxOutputTokens = Math.min(requested, remainingBudget) + if (maxOutputTokens <= 0) { + return wireError(429, "quota_exceeded", "Daily free-tier token quota reached.") + } + + // Build messages from images if provided. + const messages = body.images?.length + ? [ + { + role: "user" as const, + content: [ + ...body.images.map((img) => ({ + type: "image" as const, + image: `data:${img.mimeType};base64,${img.data}`, + })), + ...(body.prompt ? [{ type: "text" as const, text: body.prompt }] : []), + ], + }, + ] + : (body.messages as Parameters[0]["messages"]) + + const t0 = Date.now() + let object: unknown + let sdkUsage: unknown + try { + const result = await generateObject({ + model: body.model, + // Pass the client's JSON Schema straight through via Vercel AI SDK's + // `jsonSchema()` helper. The CLI sends a JSON Schema (from Zod v4's + // `z.toJSONSchema`), and the model is best guided by the full schema, + // not `z.any()`. The CLI re-parses the response with its own Zod + // schema before handing objects to commands, so we get defense-in-depth + // without needing a JSON-Schema→Zod compiler on the server. + schema: jsonSchema(body.schema as Parameters[0]), + ...(messages + ? { messages } + : { prompt: body.prompt! }), + maxOutputTokens, + }) + object = result.object + sdkUsage = result.usage + } catch (err) { + const latency = Date.now() - t0 + const message = err instanceof Error ? err.message : "Unknown gateway error" + const rawPreview = typeof message === "string" ? message.slice(0, 500) : undefined + // Gateway error → log status, do NOT charge tokens. + await logUsageEvent({ + userId, + route: "generate-object", + model: body.model, + promptTokens: 0, + completionTokens: 0, + costUsd: 0, + status: "gateway_error", + latencyMs: latency, + }) + return wireError(502, "gateway_error", "The LLM provider returned an error.", { + rawPreview, + }) + } + + const latency = Date.now() - t0 + const usage = wireUsageFromSdk(sdkUsage, 0) + + await logUsageEvent({ + userId, + route: "generate-object", + model: body.model, + promptTokens: usage.promptTokens, + completionTokens: usage.completionTokens, + costUsd: usage.costUsd, + status: "ok", + latencyMs: latency, + }) + + const resp: GenerateObjectResponse = { + object, + usage, + quota: quotaSnapshot(gate.usedToday + usage.totalTokens, resetAtIso), + } + return NextResponse.json(resp) +} + diff --git a/apps/web/app/api/v1/llm/generate-text/route.ts b/apps/web/app/api/v1/llm/generate-text/route.ts new file mode 100644 index 0000000..bff4f3e --- /dev/null +++ b/apps/web/app/api/v1/llm/generate-text/route.ts @@ -0,0 +1,107 @@ +import type { NextRequest } from "next/server" +import { NextResponse } from "next/server" +import { generateText } from "ai" +import type { + GenerateTextRequest, + GenerateTextResponse, +} from "@workspace/shared/llm-wire" +import { + logUsageEvent, + quotaSnapshot, + wireError, + wireUsageFromSdk, + withAuthAndQuota, + PER_CALL_CEILING, +} from "../_shared" + +/** + * POST /api/v1/llm/generate-text + * + * Auth: Bearer . + * Body: { model, prompt?, messages?, maxOutputTokens? } + * Return: { text, usage, quota } + */ + +export const runtime = "nodejs" +export const dynamic = "force-dynamic" + +export async function POST(req: NextRequest): Promise { + const gate = await withAuthAndQuota(req) + if (gate instanceof NextResponse) return gate + const { userId, resetAtIso, maxOutputTokens: remainingBudget } = gate + + let body: GenerateTextRequest + try { + body = (await req.json()) as GenerateTextRequest + } catch { + return wireError(400, "bad_request", "Request body is not valid JSON.") + } + + if (!body.model || typeof body.model !== "string") { + return wireError(400, "bad_request", "Missing required field: `model` (string).") + } + const hasMessages = Array.isArray(body.messages) && body.messages.length > 0 + if (!body.prompt && !hasMessages) { + return wireError(400, "bad_request", "Provide either `prompt` or a non-empty `messages` array.") + } + + const requested = body.maxOutputTokens ?? PER_CALL_CEILING + const maxOutputTokens = Math.min(requested, remainingBudget) + // Defense in depth: `withAuthAndQuota` blocks at usedToday >= DAILY_USER_LIMIT, + // so remainingBudget should always be > 0 here. This guard protects against + // future refactors or edge-case drift in the quota math. + if (maxOutputTokens <= 0) { + return wireError(429, "quota_exceeded", "Daily free-tier token quota reached.") + } + + const t0 = Date.now() + let text: string + let sdkUsage: unknown + try { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + type GenTextArgs = Parameters[0] & { messages?: any; prompt?: any } + const args: GenTextArgs = body.messages + ? ({ model: body.model, messages: body.messages, maxOutputTokens } as GenTextArgs) + : ({ model: body.model, prompt: body.prompt!, maxOutputTokens } as GenTextArgs) + const result = await generateText(args) + text = result.text + sdkUsage = result.usage + } catch (err) { + const latency = Date.now() - t0 + const message = err instanceof Error ? err.message : "Unknown gateway error" + await logUsageEvent({ + userId, + route: "generate-text", + model: body.model, + promptTokens: 0, + completionTokens: 0, + costUsd: 0, + status: "gateway_error", + latencyMs: latency, + }) + return wireError(502, "gateway_error", "The LLM provider returned an error.", { + rawPreview: message.slice(0, 500), + }) + } + + const latency = Date.now() - t0 + const usage = wireUsageFromSdk(sdkUsage, 0) + + await logUsageEvent({ + userId, + route: "generate-text", + model: body.model, + promptTokens: usage.promptTokens, + completionTokens: usage.completionTokens, + costUsd: usage.costUsd, + status: "ok", + latencyMs: latency, + }) + + const resp: GenerateTextResponse = { + text, + usage, + quota: quotaSnapshot(gate.usedToday + usage.totalTokens, resetAtIso), + } + return NextResponse.json(resp) +} diff --git a/apps/web/app/api/v1/usage/today/route.ts b/apps/web/app/api/v1/usage/today/route.ts new file mode 100644 index 0000000..435bc39 --- /dev/null +++ b/apps/web/app/api/v1/usage/today/route.ts @@ -0,0 +1,49 @@ +import type { NextRequest } from "next/server" +import { NextResponse } from "next/server" +import type { UsageTodayResponse } from "@workspace/shared/llm-wire" +import { getServiceRoleClient, verifyBearerToken } from "@/lib/supabase-admin" +import { + DAILY_USER_LIMIT, + nextUtcMidnightIso, + wireError, +} from "../../llm/_shared" + +/** + * GET /api/v1/usage/today + * + * Auth: Bearer . + * Returns the signed-in user's today-tokens snapshot, used by `helpbase whoami`. + */ + +export const runtime = "nodejs" +export const dynamic = "force-dynamic" + +export async function GET(req: NextRequest): Promise { + const authz = req.headers.get("authorization") ?? "" + const match = /^Bearer\s+(.+)$/i.exec(authz) + if (!match) { + return wireError(401, "auth_required", "Missing or malformed Authorization header.") + } + const user = await verifyBearerToken(match[1]!) + if (!user) { + return wireError(401, "auth_required", "Invalid or expired session token.") + } + + const client = getServiceRoleClient() + const { data, error } = await client.rpc("get_user_tokens_today", { + p_user_id: user.userId, + }) + if (error) { + return wireError(503, "internal_error", "Supabase is unavailable.") + } + + const body: UsageTodayResponse = { + email: user.email ?? "", + quota: { + usedToday: Number(data ?? 0), + dailyLimit: DAILY_USER_LIMIT, + resetAt: nextUtcMidnightIso(), + }, + } + return NextResponse.json(body) +} diff --git a/apps/web/content/guides/byok.mdx b/apps/web/content/guides/byok.mdx new file mode 100644 index 0000000..b09b1b3 --- /dev/null +++ b/apps/web/content/guides/byok.mdx @@ -0,0 +1,113 @@ +--- +schemaVersion: 1 +title: "Bring your own Gateway key (BYOK)" +description: "When and how to bypass the helpbase hosted proxy with your own Vercel AI Gateway key. For CI, power users, and privacy-sensitive workflows." +tags: ["byok", "advanced", "ci"] +order: 99 +featured: false +--- + +helpbase is free to use with a one-command login — 500,000 tokens per day, no +credit card. That covers most people. + +You might want your own key instead when: + +- **You're running in CI.** helpbase sessions are designed for interactive use; + machines need a token. +- **You're already paying for Vercel AI Gateway.** Route everything through + the account you already meter and bill. +- **Free-tier limits are too low for your workload.** 500k/day is ~10 full + `generate` runs or ~250 `context --ask` calls. If you run more, BYOK is + unlimited (well — limited to your own Gateway spend cap). +- **You want zero helpbase.dev round-trips.** Every BYOK call goes direct + to Vercel AI Gateway. helpbase never sees your prompts. + +## How it works + +Set `AI_GATEWAY_API_KEY` in your environment. That's it. The CLI detects it +and bypasses the helpbase proxy for every LLM call: + +```bash +export AI_GATEWAY_API_KEY=vck_live_... +helpbase generate --url https://docs.example.com +``` + +``` +┌──────────────────┐ +│ helpbase CLI │─────► Vercel AI SDK direct ─────► Vercel AI Gateway +│ │ (your key, your bill) +└──────────────────┘ + (no quota check, no usage log, no helpbase.dev round-trip) +``` + +No changes to prompts, no different models — same output as the hosted +path, just routed direct. + +## Getting a key + +1. Sign in at [vercel.com/ai-gateway](https://vercel.com/ai-gateway). +2. Create an API key. +3. Fund it (first $5 is typically free credit). +4. `export AI_GATEWAY_API_KEY=vck_...` or drop it in `.env.local`. + +## CI usage + +In GitHub Actions and other CI, set `AI_GATEWAY_API_KEY` as a repo secret +and pass it through: + +```yaml +- run: helpbase generate --url https://docs.example.com + env: + AI_GATEWAY_API_KEY: ${{ secrets.AI_GATEWAY_API_KEY }} +``` + +CI users don't need `helpbase login`. If you still want to run `helpbase +deploy` from CI (which requires a helpbase account), set `HELPBASE_TOKEN` +as well — that's the helpbase session, separate from the Gateway key. + +## Switching back to hosted + +Unset the env var: + +```bash +unset AI_GATEWAY_API_KEY +``` + +The next CLI command will use the helpbase hosted proxy again. No state to +clear, no account to delete. + +## Verify which mode you're in + +```bash +helpbase whoami +``` + +If `AI_GATEWAY_API_KEY` is set, `whoami` will show "BYOK mode active — calls +bypass helpbase (no quota applied)". Otherwise it shows your usage against +the free-tier cap. + +## Costs + +BYOK costs are whatever Gateway charges for the model you pick. As of this +writing the default and `--test` are both `google/gemini-3.1-flash-lite-preview` +(cheap + fast, ~1M context). Rough costs for a 9-article `helpbase generate` +run (~50,000 tokens): + +- Gemini 3.1 Flash Lite (default / `--test`): ~$0.004 per run. +- Claude Sonnet 4.6 (`--model anthropic/claude-sonnet-4.6`): ~$0.20–0.40. +- GPT-4o-mini (`--model openai/gpt-4o-mini`): ~$0.01–0.03. + +## Troubleshooting + +**"AI_GATEWAY_API_KEY is not set" but I just exported it.** New terminal sessions +don't see variables from old sessions. Re-export in the current shell, or +persist in `.env.local`. + +**"BYOK mode active" but I want to use hosted.** Run `unset +AI_GATEWAY_API_KEY`. You can also delete the line from `.env.local`. + +**CI passes the env var but still shows "not signed in".** `helpbase login` +and `AI_GATEWAY_API_KEY` serve different purposes. Login is for hosted +quota + deploy authorization. BYOK bypasses quota only. For deploy in CI, +you also need `HELPBASE_TOKEN` (a helpbase session token) alongside the +Gateway key. diff --git a/apps/web/content/guides/sync-in-5-minutes.mdx b/apps/web/content/guides/sync-in-5-minutes.mdx index 2d43dfe..0353613 100644 --- a/apps/web/content/guides/sync-in-5-minutes.mdx +++ b/apps/web/content/guides/sync-in-5-minutes.mdx @@ -18,11 +18,10 @@ This guide gets you from zero to your first proposal in five minutes. - A helpbase project (run `npx create-helpbase` if you don't have one yet). - Node 20+. -- An `AI_GATEWAY_API_KEY` from [vercel.com/ai-gateway](https://vercel.com/ai-gateway). Free tier is enough for this walkthrough. ## Step 1 — See what a proposal looks like (30 seconds) -Before touching your real repo, run the bundled demo. No key required. +Before touching your real repo, run the bundled demo. No login required. ```bash helpbase sync --demo @@ -38,15 +37,20 @@ The demo uses a fixture bundled with the CLI. It's the fastest way to check that `sync` is wired up correctly on your machine. -## Step 2 — Set your API key +## Step 2 — Sign in ```bash -export AI_GATEWAY_API_KEY=your_key_here +helpbase login ``` -Drop it in `.env.local` next to your project if you don't want to export -every session. The helpbase CLI picks up `.env.local` and `.env` -automatically. +Magic-link flow. Free tier is 500,000 tokens per day — enough for roughly 10 +full generates or 250 `context --ask` calls. + + +Prefer your own key? Set `AI_GATEWAY_API_KEY` and helpbase will route through +your Vercel AI Gateway account instead. See +[helpbase.dev/docs/byok](https://helpbase.dev/docs/byok). + ## Step 3 — Make a code change worth documenting diff --git a/apps/web/lib/supabase-admin.ts b/apps/web/lib/supabase-admin.ts new file mode 100644 index 0000000..02a213b --- /dev/null +++ b/apps/web/lib/supabase-admin.ts @@ -0,0 +1,42 @@ +import { createClient, type SupabaseClient } from "@supabase/supabase-js" +import type { Database } from "@/types/supabase" + +/** + * Service-role Supabase client. Bypasses RLS — use only in trusted server + * code (API routes). Never send this client to the browser and never use + * with untrusted input without parameterized queries. + * + * Used by /api/v1/llm/* to write `llm_usage_events` rows and read the + * `global_daily_tokens` counter, both of which are service-role-only. + */ + +let cached: SupabaseClient | null = null + +export function getServiceRoleClient(): SupabaseClient { + if (cached) return cached + const url = process.env.NEXT_PUBLIC_SUPABASE_URL + const key = process.env.SUPABASE_SERVICE_ROLE_KEY + if (!url || !key) { + throw new Error( + "Missing NEXT_PUBLIC_SUPABASE_URL or SUPABASE_SERVICE_ROLE_KEY — set both in the Vercel project env.", + ) + } + cached = createClient(url, key, { + auth: { persistSession: false, autoRefreshToken: false }, + }) + return cached +} + +/** + * Resolve the user behind a bearer token. Uses Supabase's getUser RPC — one + * network call per request. Swap to local JWT verification if latency becomes + * an issue (SUPABASE_JWT_SECRET + a signature library). + */ +export async function verifyBearerToken( + token: string, +): Promise<{ userId: string; email: string | null } | null> { + const client = getServiceRoleClient() + const { data, error } = await client.auth.getUser(token) + if (error || !data.user) return null + return { userId: data.user.id, email: data.user.email ?? null } +} diff --git a/apps/web/lib/waitlist.ts b/apps/web/lib/waitlist.ts new file mode 100644 index 0000000..9e80829 --- /dev/null +++ b/apps/web/lib/waitlist.ts @@ -0,0 +1,46 @@ +"use server" + +import { redirect } from "next/navigation" +import { getServiceRoleClient } from "./supabase-admin" + +/** + * Server action: insert a waitlist signup. + * + * Called from the `
` on /waitlist. On success, + * redirects back with ?status=ok; on error, ?status=error. We do not + * surface distinct errors (duplicate email, DB down) to the user — this + * is lead collection, not account creation. + * + * Note: emails are PII. We never log them; errors are diagnosed by source + + * Supabase error code. `source` is validated before use so a crafted URL + * can't inject arbitrary values into the signups table. + */ + +/** Allowed `source` tags for waitlist signups. Anything else → "waitlist". */ +const SAFE_SOURCE_RE = /^[a-z0-9_-]{1,40}$/ + +export async function joinWaitlist(formData: FormData): Promise { + const email = String(formData.get("email") ?? "").trim().toLowerCase() + const rawSource = String(formData.get("source") ?? "waitlist") + const source = SAFE_SOURCE_RE.test(rawSource) ? rawSource : "waitlist" + + if (!email || !email.includes("@")) { + redirect("/waitlist?status=error") + } + + const client = getServiceRoleClient() + // Deduplicate via the lower(email) unique index — 23505 duplicate is still success. + const { error } = await client.from("waitlist_signups").insert({ email, source }) + + if (error && error.code !== "23505") { + // No raw email in the log (PII). source + Supabase error code is enough. + console.error("[waitlist insert failed]", { + source, + code: error.code, + message: error.message, + }) + redirect("/waitlist?status=error") + } + + redirect(`/waitlist?status=ok&from=${encodeURIComponent(source)}`) +} diff --git a/apps/web/package.json b/apps/web/package.json index 72482d1..4e5302b 100644 --- a/apps/web/package.json +++ b/apps/web/package.json @@ -22,6 +22,7 @@ "@vercel/kv": "^3.0.0", "@workspace/shared": "workspace:*", "@workspace/ui": "workspace:*", + "ai": "^5.0.0", "gray-matter": "^4.0.3", "lucide-react": "^1.8.0", "next": "16.1.6", diff --git a/apps/web/public/r/help-center.json b/apps/web/public/r/help-center.json index 6e891d0..fc833f1 100644 --- a/apps/web/public/r/help-center.json +++ b/apps/web/public/r/help-center.json @@ -9,6 +9,8 @@ "gray-matter", "rehype-slug", "remark-gfm", + "rehype-pretty-code", + "shiki", "zod", "lucide-react" ], @@ -92,7 +94,7 @@ }, { "path": "registry/helpbase/lib/mdx-components.tsx", - "content": "type MDXComponents = Record>\nimport { Callout } from \"@/components/mdx/callout\"\nimport { Figure } from \"@/components/mdx/figure\"\nimport { Video } from \"@/components/mdx/video\"\nimport { Steps, Step } from \"@/components/mdx/steps\"\nimport { Accordion, AccordionItem } from \"@/components/mdx/accordion\"\nimport { Tabs, Tab } from \"@/components/mdx/tabs\"\nimport { CardGroup, Card } from \"@/components/mdx/card-group\"\nimport { CtaCard } from \"@/components/mdx/cta-card\"\n\n/**\n * Creates an MDX component map bound to a specific article's context.\n *\n * The category and slug are needed by Figure, Video, and CtaCard to\n * resolve relative asset paths (e.g. \"hero.png\" → \"/_helpbase-assets/cat/slug/hero.png\").\n * Without this binding, relative paths in MDX body would 404.\n *\n * The img override routes markdown images ![](path) through Figure\n * so they get the same asset resolution as
.\n */\nexport function createArticleComponents(category: string, slug: string): MDXComponents {\n return {\n Callout,\n Figure: (props) =>
,\n Video: (props) =>