diff --git a/CHANGELOG.md b/CHANGELOG.md index 5e29f30..3d517cf 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,19 +7,50 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] -### Changed -- **`helpbase context` renamed to `helpbase ingest`.** `context` described - a domain concept, not an action — `ingest` names what the command does - (walk your code + markdown, synthesize cited how-tos, wire MCP). The - old name continues to work as a deprecation shim: same flags, same - behavior, one-line stderr warning, suppressed under `--json`/`--quiet`. - Help text + README Quick Start + scaffolder next-steps output now lead - with `ingest`. CI scripts pinned to `helpbase context` keep working - until v0.7, which is when the shim is removed. Flag surface is shared - via `applyIngestOptions()` so the two commands can't drift. First PR - of the CLI DX v2 plan. - ### Added +- **`helpbase login` reserves a subdomain instantly.** After successful + authentication, the CLI calls `POST /api/v1/tenants/auto-provision` + which mints a product-neutral `docs-<6hex>.helpbase.dev` reservation + for the caller. The reserved URL prints in the login outro so users + see a concrete destination before they've written a single article. + TTHW for the first-deploy happy path drops from ~3-4 min (slug + prompt + confirmation) to ~90s (login + deploy, zero prompts). If + the auto-provision call 503s, login still succeeds — the reservation + is best-effort, and `helpbase whoami` / `helpbase deploy` both lazy- + provision as a fallback for users who were logged in before this + feature existed or who Ctrl-C'd between session save and the first + auto-provision call. +- **New command: `helpbase rename `.** Pre-deploy slug rename + for the auto-provisioned reservation. Server gates on `deployed_at + IS NULL`, so post-deploy renames are cleanly rejected with + `E_RESERVATION_LOCKED`. Update + local cache write is atomic from + the user's perspective; subsequent `whoami` reflects the new slug + without an extra round-trip. +- **Branded "coming soon" landing page** at reserved-tenant subdomains. + Reserved tenants now render a helpbase-branded placeholder at `/` + explaining that the help center hasn't been published yet, and + return 404 for every other path so article deep-links don't leak + the empty category grid. Every reserved-tenant response carries + `X-Robots-Tag: noindex, nofollow` so Google doesn't index `docs-*. + helpbase.dev` placeholders. +- **`helpbase whoami` surfaces the reservation.** Users with no + deployed tenants but an active reservation see a `reserved: + .helpbase.dev` line and a hint to run `helpbase deploy` or + `helpbase rename`. `helpbase open` falls back to the reservation + URL when no deployed tenant exists. +- **`deploy_tenant` RPC flips `deployed_at` atomically.** First publish + transitions a reservation to "live" inside the same transaction as + the content INSERT, so the reservation-vs-deployed boundary is + never racy. `COALESCE` preserves the ORIGINAL `deployed_at` on + re-deploys — per-deploy history continues to live in + `tenant_deploys.created_at`. +- **Vercel Cron: `/api/cron/cleanup-reservations`.** Nightly (03:00 + UTC) job that prunes reservations older than 30 days that never + deployed. Guarded by a `NOT EXISTS (SELECT 1 FROM tenant_deploys + WHERE tenant_id = tenants.id)` predicate so a row with ghost + deploy history can never be deleted even if `deployed_at` somehow + failed to update. Supports `?dry=true` for a no-op count. Bearer + auth via `CRON_SECRET` env var. - **Unit tests for the device-authorize state machine.** Extracted the 8-phase `Phase` union from `AuthorizeDeviceClient` into a pure `phaseReducer` function so every transition can be verified without @@ -41,6 +72,41 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 magic-link path always remains available as a fallback. Cold-path TTHW drops from ~60s (email round-trip) to ~20s (one-click OAuth). +### Changed +- **`helpbase context` renamed to `helpbase ingest`.** `context` described + a domain concept, not an action — `ingest` names what the command does + (walk your code + markdown, synthesize cited how-tos, wire MCP). The + old name continues to work as a deprecation shim: same flags, same + behavior, one-line stderr warning, suppressed under `--json`/`--quiet`. + Help text + README Quick Start + scaffolder next-steps output now lead + with `ingest`. CI scripts pinned to `helpbase context` keep working + until v0.7, which is when the shim is removed. Flag surface is shared + via `applyIngestOptions()` so the two commands can't drift. First PR + of the CLI DX v2 plan. +- **`/api/v1/tenants/mine` hides reservations.** Reservations are + pre-first-deploy placeholders and shouldn't pollute the tenant + picker for multi-tenant users. The new filter is + `.not("deployed_at", "is", null)`. Callers that specifically want + the reservation (login, whoami, open) hit + `GET /api/v1/tenants/reservation` instead. +- **`tenants_public` view now exposes `deployed_at`.** The subdomain + middleware needs this to distinguish reserved tenants from live + ones without granting anon read access to the full tenants table. + `mcp_public_token` still never appears in the view. + +### Schema +- New columns on `public.tenants`: `deployed_at timestamptz` + + `auto_provisioned_at timestamptz` (both nullable). Backfilled + existing rows with `deployed_at = created_at`. +- New UNIQUE partial index `idx_tenants_owner_one_reservation` + on `owner_id WHERE auto_provisioned_at IS NOT NULL AND + deployed_at IS NULL` — race-safe idempotency for the + auto-provision endpoint. +- New lookup index `idx_tenants_owner_auto_provisioned` on the same + partial predicate minus the `deployed_at` clause — small and + sargable for the reservation lookup path. +- Migration: `slug_reservation_columns_and_first_deploy_timestamp`. + ## [helpbase 0.5.0] — 2026-04-17 ### Added diff --git a/apps/web/app/(tenant)/t/[tenant]/mcp/route.ts b/apps/web/app/(tenant)/t/[tenant]/mcp/route.ts index e361ed4..d95679c 100644 --- a/apps/web/app/(tenant)/t/[tenant]/mcp/route.ts +++ b/apps/web/app/(tenant)/t/[tenant]/mcp/route.ts @@ -47,6 +47,7 @@ type TenantForMcp = { slug: string mcp_public_token: string active: boolean + deployed_at: string | null } async function loadTenant( @@ -55,7 +56,7 @@ async function loadTenant( ): Promise { const { data } = await client .from("tenants") - .select("id, slug, mcp_public_token, active") + .select("id, slug, mcp_public_token, active, deployed_at") .eq("slug", slug) .eq("active", true) .maybeSingle() @@ -237,7 +238,12 @@ async function handle(request: NextRequest, tenantSlug: string): Promise -

- Help center not found -

-

- This subdomain hasn't been set up yet. -

- - Create your help center - - - ) +/** + * Tenant "not found" page. Rendered by the subdomain middleware for: + * - unknown subdomains (never-existed tenants) + * - reserved tenants at deep-link paths (articles/search/etc. — root + * `/` still routes to the branded "coming soon" landing) + * + * Calling `notFound()` is the load-bearing bit: Next.js converts it into + * a true HTTP 404 response (not a 200 with "not found" copy). That + * matters because middleware-level rewrites preserve the destination's + * status, and we want crawlers + MCP clients + monitoring tools hitting + * unknown or reserved subdomain paths to see "nope, nothing here" at + * the protocol level, not "here's a page that claims nothing is here." + * The previous implementation rendered a 200 HTML page with a "Create + * your help center" CTA; that CTA can come back as a proper + * `not-found.tsx` route later. Ship correctness first. + * Caught by /review codex on 2026-04-18. + */ +export default function TenantNotFound(): never { + notFound() } diff --git a/apps/web/app/(tenant)/t/_reserved/[slug]/page.tsx b/apps/web/app/(tenant)/t/_reserved/[slug]/page.tsx new file mode 100644 index 0000000..bb27c0a --- /dev/null +++ b/apps/web/app/(tenant)/t/_reserved/[slug]/page.tsx @@ -0,0 +1,82 @@ +import type { Metadata } from "next" + +/** + * Reserved-tenant landing page. + * + * Rendered by the subdomain middleware (proxy.ts) when a subdomain + * matches a tenant row whose `deployed_at` is still null — meaning the + * owner logged in and got an auto-provisioned reservation but hasn't + * published content yet. Anyone visiting the URL sees this page instead + * of an empty category grid, and the response carries X-Robots-Tag: + * noindex so Google doesn't index placeholder subdomains. + * + * Intentionally minimal: no Supabase lookup (the middleware already + * confirmed the slug exists), no owner email leakage, no admin info. + * The slug in the URL is the only identifier shown. + */ + +export const metadata: Metadata = { + robots: { index: false, follow: false }, + title: "Coming soon", +} + +// Static — no per-slug data is fetched, everything the page needs lives +// in the URL segment. `revalidate` can be any value since nothing varies. +export const revalidate = 3600 + +export default async function ReservedTenantPage({ + params, +}: { + params: Promise<{ slug: string }> +}) { + const { slug } = await params + // Keep in sync with proxy.ts. The apex stays configurable so staging + // (e.g. helpbase-dev.vercel.app) and self-hosted setups don't render + // a page advertising the wrong hostname. CodeRabbit flagged the hard + // coded "helpbase.dev" string on PR #10. + const rootDomain = (process.env.NEXT_PUBLIC_ROOT_DOMAIN ?? "helpbase.dev").trim() + const displayHost = `${slug}.${rootDomain}` + + return ( +
+
+

+ helpbase +

+

+ This help center isn't live yet +

+

+ {displayHost}{" "} + has been reserved. The owner needs to publish content before visitors + see anything here. +

+ +
+

If this is your help center

+

+ Run the helpbase CLI from your project root to publish: +

+
+            {`helpbase deploy`}
+          
+

+ Prefer a different subdomain? Run{" "} + helpbase rename <new-slug>{" "} + before your first deploy. +

+
+ +

+ Learn more at{" "} + + helpbase.dev + +

+
+
+ ) +} diff --git a/apps/web/app/api/cron/cleanup-reservations/route.ts b/apps/web/app/api/cron/cleanup-reservations/route.ts new file mode 100644 index 0000000..730f26a --- /dev/null +++ b/apps/web/app/api/cron/cleanup-reservations/route.ts @@ -0,0 +1,183 @@ +import { NextResponse, type NextRequest } from "next/server" +import { getServiceRoleClient } from "@/lib/supabase-admin" +import { + RESERVATION_TTL_DAYS, + filterDeletable, + reservationCutoff, +} from "@/lib/reservation-cleanup" + +/** + * GET/POST /api/cron/cleanup-reservations + * auth: Authorization: Bearer $CRON_SECRET (Vercel Cron passes this automatically) + * query: ?dry=true — return candidate count + slugs without deleting + * returns: { deleted: number, slugs: string[] } on success + * + * Prunes abandoned reservations: rows that were auto-provisioned more than + * 30 days ago, never deployed, and have no deploy history. + * + * Scheduled via vercel.json cron entry (daily 03:00 UTC). Vercel Cron + * invokes paths as an HTTP GET with Authorization: Bearer $CRON_SECRET, + * so GET is the primary export. POST is aliased so curl runbooks that + * default to `-X POST` also work. A POST-only handler (earlier iteration + * of this file) gets a 405 from Vercel Cron and the job silently never + * runs — caught by /review codex on 2026-04-18. + * + * Running it manually locally: + * curl -H "Authorization: Bearer $CRON_SECRET" \ + * https://helpbase.dev/api/cron/cleanup-reservations?dry=true + */ + +export const runtime = "nodejs" +export const dynamic = "force-dynamic" + +// Hard cap on candidates per run. Protects the Node runtime from OOM on +// a runaway backlog and protects PostgREST from URL-length blowouts on +// the follow-up IN (id, ...) filters. If the real backlog grows past +// this, the cron catches up day-by-day (30-day TTL means anything truly +// abandoned sits longer than one run). +const MAX_CANDIDATES_PER_RUN = 500 + +// TTL constant + cutoff/filter helpers moved to lib/reservation-cleanup.ts +// so unit tests can exercise the exact same functions the route runs. +// Re-export so downstream consumers (docs, tests) keep the old import +// path working. +export { RESERVATION_TTL_DAYS } + +export async function GET(req: NextRequest): Promise { + return handle(req) +} + +export async function POST(req: NextRequest): Promise { + return handle(req) +} + +async function handle(req: NextRequest): Promise { + // Vercel Cron sends Authorization: Bearer . Unauthenticated + // hits get 401 so the endpoint isn't a public /admin/prune button. + const secret = process.env.CRON_SECRET + if (!secret) { + console.error("[cron.cleanup-reservations] CRON_SECRET not configured") + return NextResponse.json({ error: "cron_not_configured" }, { status: 500 }) + } + const authHeader = req.headers.get("authorization") ?? "" + if (authHeader !== `Bearer ${secret}`) { + return NextResponse.json({ error: "unauthorized" }, { status: 401 }) + } + + // Accept common truthy values for the dry-run flag so a stressed operator + // typing `?dry=1` in a runbook doesn't accidentally delete. + const dryParam = (req.nextUrl.searchParams.get("dry") ?? "").toLowerCase() + const dryRun = dryParam === "true" || dryParam === "1" || dryParam === "yes" + + const admin = getServiceRoleClient() + + // Find abandoned reservation candidates. Guards on SELECT: + // - auto_provisioned_at IS NOT NULL — provisioned via /auto-provision + // - deployed_at IS NULL — never went live + // - auto_provisioned_at < NOW() - 30d — old enough to be considered stale + // `.limit(MAX_CANDIDATES_PER_RUN)` caps memory + URL-length risk on the + // follow-up .in() filters. Day-over-day runs drain the backlog. + const cutoff = reservationCutoff(new Date()) + + const { data: candidates, error: selectError } = await admin + .from("tenants") + .select("id, slug") + .not("auto_provisioned_at", "is", null) + .is("deployed_at", null) + .lt("auto_provisioned_at", cutoff) + .limit(MAX_CANDIDATES_PER_RUN) + + if (selectError) { + console.error("[cron.cleanup-reservations] select error", { selectError }) + return NextResponse.json({ error: "select_failed" }, { status: 503 }) + } + + const candidateIds = (candidates ?? []).map((c) => c.id) + if (candidateIds.length === 0) { + return NextResponse.json({ deleted: 0, slugs: [], dry: dryRun }) + } + + // Belt-and-suspenders: if any candidate has tenant_deploys rows despite + // deployed_at being null, something's off (deployed_at update failed, + // data-repair script ran, etc.) — preserve them and log for audit. + const { data: deployedShadows, error: shadowError } = await admin + .from("tenant_deploys") + .select("tenant_id") + .in("tenant_id", candidateIds) + + if (shadowError) { + console.error("[cron.cleanup-reservations] shadow lookup error", { shadowError }) + return NextResponse.json({ error: "shadow_check_failed" }, { status: 503 }) + } + + const shadowList = deployedShadows ?? [] + const toDelete = filterDeletable(candidates!, shadowList) + const shadows = candidates!.length - toDelete.length + if (shadows > 0) { + const shadowIds = new Set(shadowList.map((r) => r.tenant_id)) + const shadowSlugs = candidates! + .filter((c) => shadowIds.has(c.id)) + .map((c) => c.slug) + console.warn( + "[cron.cleanup-reservations] skipping tenants with deploy history despite deployed_at IS NULL", + { count: shadows, slugs: shadowSlugs }, + ) + } + + if (dryRun) { + return NextResponse.json({ + deleted: 0, + slugs: toDelete.map((c) => c.slug), + dry: true, + candidate_count: toDelete.length, + }) + } + + if (toDelete.length === 0) { + return NextResponse.json({ deleted: 0, slugs: [] }) + } + + // Race-safe delete: the WHERE clause repeats every predicate so a + // tenant that deployed AFTER the candidate select but BEFORE this + // DELETE is NOT dropped by this statement — PostgreSQL evaluates the + // filters at DELETE time, not at the earlier SELECT. Without these + // extra filters, the cron could race a concurrent first deploy and + // destroy a tenant that just went live. Codex caught this in the PR + // #10 /review pass 2026-04-18. + const { data: deleted, error: deleteError } = await admin + .from("tenants") + .delete() + .in( + "id", + toDelete.map((c) => c.id), + ) + .not("auto_provisioned_at", "is", null) + .is("deployed_at", null) + .lt("auto_provisioned_at", cutoff) + .select("id, slug") + + if (deleteError) { + console.error("[cron.cleanup-reservations] delete error", { deleteError }) + return NextResponse.json({ error: "delete_failed" }, { status: 503 }) + } + + const actuallyDeleted = deleted ?? [] + const raced = toDelete.length - actuallyDeleted.length + if (raced > 0) { + console.info( + "[cron.cleanup-reservations] skipped tenants that raced a deploy between select and delete", + { raced }, + ) + } + + console.info("[cron.cleanup-reservations] deleted", { + count: actuallyDeleted.length, + slugs: actuallyDeleted.map((c) => c.slug), + }) + + return NextResponse.json({ + deleted: actuallyDeleted.length, + slugs: actuallyDeleted.map((c) => c.slug), + raced, + }) +} diff --git a/apps/web/app/api/v1/tenants/auto-provision/route.ts b/apps/web/app/api/v1/tenants/auto-provision/route.ts new file mode 100644 index 0000000..b3a1d1e --- /dev/null +++ b/apps/web/app/api/v1/tenants/auto-provision/route.ts @@ -0,0 +1,176 @@ +import { NextResponse, type NextRequest } from "next/server" +import { randomBytes } from "node:crypto" +import { getServiceRoleClient } from "@/lib/supabase-admin" +import { jsonError, requireSession } from "../_shared" + +/** + * POST /api/v1/tenants/auto-provision + * auth: Bearer + * body: (none) + * returns: { id, slug, name, live_url, mcp_public_token, is_new } + * + * Reserves a `docs-<6hex>` subdomain for the caller at login time. Idempotent: + * a second call from the same user (or a retry after a flaky network) returns + * the existing reservation with `is_new: false` — the UNIQUE partial index + * `idx_tenants_owner_one_reservation` guarantees a concurrent race can't + * create two reservations. + * + * Product rationale (from /plan-devex-review 2026-04-18): users deploy PRODUCT + * docs, not personal ones, so the default slug is deliberately product-neutral + * (`docs-<6hex>`) rather than email-derived. Users rename via + * `helpbase rename ` (pre-deploy only) or abandon the reservation and + * pick a real slug on their first deploy. Abandoned reservations clean up + * after 30 days via /api/cron/cleanup-reservations. + * + * Collision strategy: the slug uses 24 bits of entropy (6 hex chars ≈ 16M + * values), so a first-try collision is vanishingly rare even at launch-day + * signup volume. If 23505 hits on the slug UNIQUE we retry once with a + * fresh suffix; a second collision returns 503 (signals either an under- + * provisioned PRNG or something pathological). + */ + +export const runtime = "nodejs" +export const dynamic = "force-dynamic" + +const ROOT_DOMAIN = (process.env.NEXT_PUBLIC_ROOT_DOMAIN ?? "helpbase.dev").trim() + +/** + * Generate a new reservation slug. `docs-` prefix is product-neutral and + * signals "placeholder" at a glance. 6 hex chars = 16M possibilities; + * collision probability on a fresh insert is effectively zero. + */ +function generateReservationSlug(): string { + return `docs-${randomBytes(3).toString("hex")}` +} + +/** + * Build the live URL for a tenant. The subdomain middleware in proxy.ts + * reads this same ROOT_DOMAIN env var; keep both in sync. + */ +function liveUrlFor(slug: string): string { + return `https://${slug}.${ROOT_DOMAIN}` +} + +interface ReservationRow { + id: string + slug: string + name: string + mcp_public_token: string +} + +export async function POST(req: NextRequest): Promise { + const sessionOrResp = await requireSession(req) + if (sessionOrResp instanceof NextResponse) return sessionOrResp + const { userId } = sessionOrResp + + const admin = getServiceRoleClient() + + // 1. Idempotency check: does the caller already have an active reservation? + // The UNIQUE partial index enforces at most one, so .maybeSingle() is + // the right shape. If they have a DEPLOYED tenant but no reservation, + // that's not our concern — login calls this; the reservation is only + // the pre-first-deploy placeholder. + const { data: existing, error: lookupError } = await admin + .from("tenants") + .select("id, slug, name, mcp_public_token") + .eq("owner_id", userId) + .not("auto_provisioned_at", "is", null) + .is("deployed_at", null) + .maybeSingle() + + if (lookupError) { + console.error("[tenants.auto-provision] lookup error", { userId, lookupError }) + return jsonError(503, "internal_error", "Could not check for existing reservation.") + } + + if (existing) { + return NextResponse.json({ + id: existing.id, + slug: existing.slug, + name: existing.name, + live_url: liveUrlFor(existing.slug), + mcp_public_token: existing.mcp_public_token, + is_new: false, + }) + } + + // 2. Insert a fresh reservation. Retry once on slug collision; the + // UNIQUE partial index on owner_id catches a concurrent second + // auto-provision call and we re-read the existing row in that case. + for (let attempt = 0; attempt < 2; attempt++) { + const slug = generateReservationSlug() + const { data: created, error: insertError } = await admin + .from("tenants") + .insert({ + slug, + owner_id: userId, + name: slug, + auto_provisioned_at: new Date().toISOString(), + // deployed_at stays null; deploy_tenant RPC flips it on first publish. + }) + .select("id, slug, name, mcp_public_token") + .maybeSingle() + + if (!insertError && created) { + return NextResponse.json( + { + id: created.id, + slug: created.slug, + name: created.name, + live_url: liveUrlFor(created.slug), + mcp_public_token: created.mcp_public_token, + is_new: true, + }, + { status: 201 }, + ) + } + + // Postgres 23505 = unique_violation. Two constraints can fire on this + // INSERT: the slug UNIQUE (collision on the random docs-<6hex>) and the + // owner-reservation UNIQUE partial index (concurrent login won the race). + // + // We used to discriminate via substring-match on `details`/`message` + // looking for the partial-index name, but that's fragile to driver + // version and Postgres error-message format changes. Safer: re-read + // the caller's reservation unconditionally. If one exists, a concurrent + // call won — return it as the idempotent path (is_new: false). If + // nothing exists, the collision was on the slug — retry with a fresh + // suffix. Worst case: two round-trips per collision instead of one; + // collisions are vanishingly rare anyway (24 bits of entropy). + const code = (insertError as { code?: string } | null)?.code + if (code === "23505") { + const { data: raced } = await admin + .from("tenants") + .select("id, slug, name, mcp_public_token") + .eq("owner_id", userId) + .not("auto_provisioned_at", "is", null) + .is("deployed_at", null) + .maybeSingle() + if (raced) { + return NextResponse.json({ + id: raced.id, + slug: raced.slug, + name: raced.name, + live_url: liveUrlFor(raced.slug), + mcp_public_token: raced.mcp_public_token, + is_new: false, + }) + } + // No reservation found → the 23505 was the slug UNIQUE. Retry with + // a fresh suffix on the next loop iteration. + continue + } + + console.error("[tenants.auto-provision] insert error", { userId, insertError }) + return jsonError(503, "internal_error", "Could not create reservation.") + } + + // Exhausted retries. Two consecutive slug collisions with 24 bits of entropy + // is astronomical; log loudly so we notice if the PRNG is degraded. + console.error("[tenants.auto-provision] exhausted slug-collision retries", { userId }) + return jsonError( + 503, + "slug_exhausted", + "Could not mint a unique reservation slug after 2 attempts — retry shortly.", + ) +} diff --git a/apps/web/app/api/v1/tenants/mine/route.ts b/apps/web/app/api/v1/tenants/mine/route.ts index 7460699..ef08d03 100644 --- a/apps/web/app/api/v1/tenants/mine/route.ts +++ b/apps/web/app/api/v1/tenants/mine/route.ts @@ -10,6 +10,12 @@ import { requireSession } from "../_shared" * Replaces the old CLI-side anon-Supabase query that filtered by * owner_id = auth.uid(). All current owner-lookups in deploy/link/open * route through here. + * + * Hides reservations: rows with deployed_at IS NULL are slug-reserved + * but never published. They'd pollute the `helpbase deploy` tenant + * picker and the `helpbase open` default-URL resolution. Callers that + * WANT the reservation (login auto-provision, whoami) hit + * GET /api/v1/tenants/reservation instead. */ export const runtime = "nodejs" @@ -25,6 +31,7 @@ export async function GET(req: NextRequest): Promise { .select("id, slug, name") .eq("owner_id", sessionOrResp.userId) .eq("active", true) + .not("deployed_at", "is", null) .order("created_at", { ascending: false }) if (error) { diff --git a/apps/web/app/api/v1/tenants/reservation/route.ts b/apps/web/app/api/v1/tenants/reservation/route.ts new file mode 100644 index 0000000..adc7547 --- /dev/null +++ b/apps/web/app/api/v1/tenants/reservation/route.ts @@ -0,0 +1,68 @@ +import { NextResponse, type NextRequest } from "next/server" +import { getServiceRoleClient } from "@/lib/supabase-admin" +import { jsonError, requireSession } from "../_shared" + +/** + * GET /api/v1/tenants/reservation + * auth: Bearer + * returns (200): { id, slug, name, live_url, mcp_public_token } + * returns (404): { error: "no_reservation" } + * + * Read-side counterpart to POST /api/v1/tenants/auto-provision. The /mine + * endpoint hides reservations so they don't pollute the tenant picker; + * callers that need the reservation specifically (login re-hydration, + * whoami's "reserved: ..." line, open's default URL fallback) hit this. + * + * Idempotent + cheap: single indexed lookup by the UNIQUE partial index + * on owner_id WHERE auto_provisioned_at IS NOT NULL AND deployed_at IS NULL. + */ + +export const runtime = "nodejs" +export const dynamic = "force-dynamic" + +const ROOT_DOMAIN = (process.env.NEXT_PUBLIC_ROOT_DOMAIN ?? "helpbase.dev").trim() + +function liveUrlFor(slug: string): string { + return `https://${slug}.${ROOT_DOMAIN}` +} + +interface ReservationRow { + id: string + slug: string + name: string + mcp_public_token: string +} + +export async function GET(req: NextRequest): Promise { + const sessionOrResp = await requireSession(req) + if (sessionOrResp instanceof NextResponse) return sessionOrResp + + const admin = getServiceRoleClient() + const { data, error } = await admin + .from("tenants") + .select("id, slug, name, mcp_public_token") + .eq("owner_id", sessionOrResp.userId) + .not("auto_provisioned_at", "is", null) + .is("deployed_at", null) + .maybeSingle() + + if (error) { + console.error("[tenants.reservation] lookup error", { + userId: sessionOrResp.userId, + error, + }) + return jsonError(503, "internal_error", "Could not fetch reservation.") + } + + if (!data) { + return jsonError(404, "no_reservation") + } + + return NextResponse.json({ + id: data.id, + slug: data.slug, + name: data.name, + live_url: liveUrlFor(data.slug), + mcp_public_token: data.mcp_public_token, + }) +} diff --git a/apps/web/app/api/v1/tenants/reservation/slug/route.ts b/apps/web/app/api/v1/tenants/reservation/slug/route.ts new file mode 100644 index 0000000..fe90de6 --- /dev/null +++ b/apps/web/app/api/v1/tenants/reservation/slug/route.ts @@ -0,0 +1,142 @@ +import { NextResponse, type NextRequest } from "next/server" +import { getServiceRoleClient } from "@/lib/supabase-admin" +import { jsonError, requireSession } from "../../_shared" + +/** + * PATCH /api/v1/tenants/reservation/slug + * auth: Bearer + * body: { slug: string } + * returns (200): { id, slug, name, live_url, mcp_public_token } + * returns (400): invalid_body | slug_required | slug_invalid + * returns (404): no_reservation + * returns (409): slug_reserved | slug_taken + * + * Pre-deploy rename for the caller's active reservation. Post-deploy + * renames are out of scope (would need a slug redirect layer the proxy + * doesn't have yet) — the `.is("deployed_at", null)` filter is the gate. + * + * Slug validation rules MUST match POST /api/v1/tenants (the real-create + * path): same regex, same length, same reserved list. A drift would mean + * a user could `rename` into a shape that the subsequent `deploy --slug` + * flow would reject. This file intentionally duplicates the two constants + * until we have a single source-of-truth shared module (pre-existing + * TODO in proxy.ts:8 — drift guard is a v1.5 CI check). + */ + +export const runtime = "nodejs" +export const dynamic = "force-dynamic" + +const ROOT_DOMAIN = (process.env.NEXT_PUBLIC_ROOT_DOMAIN ?? "helpbase.dev").trim() + +// DNS-label shape, matches POST /api/v1/tenants and the CLI. +const SLUG_REGEX = /^[a-z0-9]([a-z0-9-]*[a-z0-9])?$/ +const RESERVED = new Set([ + "www", "app", "api", "admin", "dashboard", "docs", "help", "blog", "status", + "mail", "mcp", "deploy", "login", "signup", "signin", "auth", "billing", + "support", "cdn", "static", "assets", "files", "media", "images", "img", +]) + +function liveUrlFor(slug: string): string { + return `https://${slug}.${ROOT_DOMAIN}` +} + +interface ReservationRow { + id: string + slug: string + name: string + mcp_public_token: string + deployed_at: string | null +} + +export async function PATCH(req: NextRequest): Promise { + const sessionOrResp = await requireSession(req) + if (sessionOrResp instanceof NextResponse) return sessionOrResp + const { userId } = sessionOrResp + + let body: { slug?: string } + try { + body = await req.json() + } catch { + return jsonError(400, "invalid_body", "Expected JSON {slug}.") + } + + const slug = body.slug?.trim() + if (!slug) return jsonError(400, "slug_required") + if (!SLUG_REGEX.test(slug)) { + return jsonError(400, "slug_invalid", "Use lowercase letters, numbers, and hyphens.") + } + if (slug.length < 3 || slug.length > 40) { + return jsonError(400, "slug_invalid", "Slug must be 3-40 characters.") + } + if (RESERVED.has(slug)) { + return jsonError(409, "slug_reserved", `"${slug}" is reserved.`) + } + + const admin = getServiceRoleClient() + + // Fetch the caller's reservation first so we can distinguish "no + // reservation" (404) from "tenant already deployed" (409 — the CLI + // surfaces this as E_RESERVATION_LOCKED). + const { data: current, error: lookupError } = await admin + .from("tenants") + .select("id, slug, name, mcp_public_token, deployed_at") + .eq("owner_id", userId) + .not("auto_provisioned_at", "is", null) + .is("deployed_at", null) + .maybeSingle() + + if (lookupError) { + console.error("[tenants.reservation.slug] lookup error", { userId, lookupError }) + return jsonError(503, "internal_error", "Could not fetch reservation.") + } + if (!current) { + return jsonError(404, "no_reservation") + } + // No-op rename: user sent the same slug they already have. Return 200 + // with the unchanged row so the CLI's rename command can idempotently + // re-run (matches the auto-provision idempotency contract). + if (current.slug === slug) { + return NextResponse.json({ + id: current.id, + slug: current.slug, + name: current.name, + live_url: liveUrlFor(current.slug), + mcp_public_token: current.mcp_public_token, + }) + } + + // Update the slug in place. The UNIQUE constraint on tenants.slug fires + // if the new slug is taken; we catch 23505 and return 409. + const { data: updated, error: updateError } = await admin + .from("tenants") + .update({ slug, name: slug }) + .eq("id", current.id) + // Belt-and-suspenders: refuse to update if the row was deployed + // between our lookup and this write. Shouldn't happen (deploys only + // fire via the owner's own CLI, no race in practice), but the filter + // costs nothing. + .is("deployed_at", null) + .select("id, slug, name, mcp_public_token") + .maybeSingle>() + + if (updateError) { + if ((updateError as { code?: string }).code === "23505") { + return jsonError(409, "slug_taken", `"${slug}" is already taken.`) + } + console.error("[tenants.reservation.slug] update error", { userId, updateError }) + return jsonError(503, "internal_error", "Could not rename reservation.") + } + if (!updated) { + // Row vanished between lookup and update — likely deploy raced. + // Callers should re-query reservation state and surface appropriately. + return jsonError(409, "reservation_locked", "Reservation was deployed before rename completed.") + } + + return NextResponse.json({ + id: updated.id, + slug: updated.slug, + name: updated.name, + live_url: liveUrlFor(updated.slug), + mcp_public_token: updated.mcp_public_token, + }) +} diff --git a/apps/web/lib/reservation-cleanup.ts b/apps/web/lib/reservation-cleanup.ts new file mode 100644 index 0000000..446b8b4 --- /dev/null +++ b/apps/web/lib/reservation-cleanup.ts @@ -0,0 +1,35 @@ +/** + * Pure helpers for the cleanup-reservations cron. Extracted so unit tests + * exercise the same predicate the route handler runs, not a shadow copy. + * CodeRabbit flagged the duplication on PR #10. + * + * The route still performs the actual SELECT + DELETE against Supabase + * (that part is not unit-testable without a live DB); what we pin here + * is the 30-day TTL math and the shadow-safety filter. + */ + +export const RESERVATION_TTL_DAYS = 30 + +/** ISO timestamp of the cutoff: anything auto_provisioned before this is TTL-expired. */ +export function reservationCutoff(now: Date): string { + return new Date(now.getTime() - RESERVATION_TTL_DAYS * 24 * 60 * 60 * 1000).toISOString() +} + +export interface Candidate { + id: string + slug: string +} + +/** + * Given candidate reservation rows (TTL-expired) and the set of tenant_ids + * that have deploy history, returns only the rows that are safe to delete. + * Belt-and-suspenders: any candidate with a tenant_deploys row is preserved + * even if `deployed_at` is null (data-repair state, failed RPC, etc.). + */ +export function filterDeletable( + candidates: Candidate[], + deployedShadows: Array<{ tenant_id: string }>, +): Candidate[] { + const shadowSet = new Set(deployedShadows.map((r) => r.tenant_id)) + return candidates.filter((c) => !shadowSet.has(c.id)) +} diff --git a/apps/web/proxy.ts b/apps/web/proxy.ts index 330f532..2360070 100644 --- a/apps/web/proxy.ts +++ b/apps/web/proxy.ts @@ -126,10 +126,11 @@ export async function proxy(request: NextRequest) { // Read from the public-safe view (tenants_public hides mcp_public_token // and owner_id from anon). Base tenants table has no anon read grant - // post-2026-04-17 migration. + // post-2026-04-17 migration. `deployed_at` is the reservation flag — + // null means "auto-provisioned placeholder, never published." const { data: tenant } = await supabase .from("tenants_public") - .select("slug") + .select("slug, deployed_at") .eq("slug", subdomain) .maybeSingle() @@ -140,6 +141,39 @@ export async function proxy(request: NextRequest) { return NextResponse.rewrite(url) } + // Reserved tenant: auto-provisioned placeholder without published + // content. Routing rules: + // - `/` → branded "coming soon" landing + // (/t/_reserved/) + // - `/mcp` + `/mcp/*` → fall through to the tenant route so the MCP + // handler's own 403 `tenant_not_deployed` response fires. If + // middleware short-circuits /mcp to _not-found, MCP clients polling + // a reservation URL during the first-deploy window get a 404 HTML + // page instead of the structured 403 JSON they expect (their retry + // logic then misclassifies "reserved, come back later" as "this + // tenant doesn't exist"). Caught by /review codex on 2026-04-18. + // - everything else → rewrite to _not-found (which calls notFound() + // and returns HTTP 404) + // Every reserved-tenant response carries X-Robots-Tag: noindex,nofollow. + if (tenant.deployed_at === null) { + if (pathname === "/mcp" || pathname.startsWith("/mcp/")) { + const url = request.nextUrl.clone() + url.pathname = `/t/${subdomain}${pathname}` + const res = NextResponse.rewrite(url) + res.headers.set("X-Robots-Tag", "noindex, nofollow") + return res + } + const url = request.nextUrl.clone() + if (pathname === "/" || pathname === "") { + url.pathname = `/t/_reserved/${subdomain}` + } else { + url.pathname = "/t/_not-found" + } + const res = NextResponse.rewrite(url) + res.headers.set("X-Robots-Tag", "noindex, nofollow") + return res + } + // Rewrite to tenant route: company.helpbase.dev/path → /t/company/path const url = request.nextUrl.clone() url.pathname = `/t/${subdomain}${pathname}` diff --git a/apps/web/test/reservation-cron.test.ts b/apps/web/test/reservation-cron.test.ts new file mode 100644 index 0000000..46cad70 --- /dev/null +++ b/apps/web/test/reservation-cron.test.ts @@ -0,0 +1,86 @@ +import { describe, it, expect } from "vitest" +import { + RESERVATION_TTL_DAYS, + filterDeletable, + reservationCutoff, +} from "@/lib/reservation-cleanup" + +/** + * Unit tests for the cleanup-reservations cron predicate. + * + * The route handler is thin by design — Supabase does the heavy lifting, + * and the middleware + auth gate are covered elsewhere. What's worth + * testing in isolation is the 30-day cutoff math (easy to get wrong on + * a date-refactor) and the defensive filter that excludes any tenant + * with deploy history. + * + * Both functions are imported from `@/lib/reservation-cleanup` — the + * SAME module the route handler imports. No shadow copies; test drift + * can't silently pass against a stale duplicate. CodeRabbit flagged the + * earlier shadow-copy pattern on PR #10. + */ + +describe("cleanup-reservations TTL math", () => { + it("TTL constant is 30 days (guard against an accidental refactor)", () => { + expect(RESERVATION_TTL_DAYS).toBe(30) + }) + + it("cutoff is exactly 30 days before now (ISO)", () => { + const now = new Date("2026-05-01T00:00:00.000Z") + expect(reservationCutoff(now)).toBe("2026-04-01T00:00:00.000Z") + }) + + it("reservations younger than TTL are NOT candidates", () => { + const now = new Date("2026-05-01T00:00:00.000Z") + const cutoff = reservationCutoff(now) + expect(now.toISOString() < cutoff).toBe(false) + const ago29 = new Date(now.getTime() - 29 * 24 * 60 * 60 * 1000).toISOString() + expect(ago29 < cutoff).toBe(false) + }) + + it("reservations older than TTL ARE candidates", () => { + const now = new Date("2026-05-01T00:00:00.000Z") + const cutoff = reservationCutoff(now) + const ago31 = new Date(now.getTime() - 31 * 24 * 60 * 60 * 1000).toISOString() + expect(ago31 < cutoff).toBe(true) + const ago90 = new Date(now.getTime() - 90 * 24 * 60 * 60 * 1000).toISOString() + expect(ago90 < cutoff).toBe(true) + }) +}) + +describe("cleanup-reservations shadow filter", () => { + it("empty candidate list returns empty", () => { + expect(filterDeletable([], [])).toEqual([]) + }) + + it("candidates with no deploy history are all kept for deletion", () => { + const candidates = [ + { id: "t-1", slug: "docs-aaa" }, + { id: "t-2", slug: "docs-bbb" }, + ] + expect(filterDeletable(candidates, [])).toEqual(candidates) + }) + + it("candidates with deploy history are filtered out (safety net)", () => { + const candidates = [ + { id: "t-1", slug: "docs-aaa" }, + { id: "t-2", slug: "docs-bbb" }, + { id: "t-3", slug: "docs-ccc" }, + ] + const deployedShadows = [{ tenant_id: "t-2" }] + const result = filterDeletable(candidates, deployedShadows) + expect(result).toEqual([ + { id: "t-1", slug: "docs-aaa" }, + { id: "t-3", slug: "docs-ccc" }, + ]) + }) + + it("every candidate has deploy history → nothing deleted", () => { + const candidates = [ + { id: "t-1", slug: "docs-aaa" }, + { id: "t-2", slug: "docs-bbb" }, + ] + const deployedShadows = [{ tenant_id: "t-1" }, { tenant_id: "t-2" }] + expect(filterDeletable(candidates, deployedShadows)).toEqual([]) + }) +}) diff --git a/apps/web/types/supabase.ts b/apps/web/types/supabase.ts index c700037..50dc4ea 100644 --- a/apps/web/types/supabase.ts +++ b/apps/web/types/supabase.ts @@ -518,7 +518,9 @@ export type Database = { tenants: { Row: { active: boolean + auto_provisioned_at: string | null created_at: string + deployed_at: string | null id: string mcp_calls_today: number mcp_public_token: string @@ -530,7 +532,9 @@ export type Database = { } Insert: { active?: boolean + auto_provisioned_at?: string | null created_at?: string + deployed_at?: string | null id?: string mcp_calls_today?: number mcp_public_token?: string @@ -542,7 +546,9 @@ export type Database = { } Update: { active?: boolean + auto_provisioned_at?: string | null created_at?: string + deployed_at?: string | null id?: string mcp_calls_today?: number mcp_public_token?: string @@ -645,6 +651,7 @@ export type Database = { tenants_public: { Row: { active: boolean | null + deployed_at: string | null id: string | null name: string | null slug: string | null @@ -652,6 +659,7 @@ export type Database = { } Insert: { active?: boolean | null + deployed_at?: string | null id?: string | null name?: string | null slug?: string | null @@ -659,6 +667,7 @@ export type Database = { } Update: { active?: boolean | null + deployed_at?: string | null id?: string | null name?: string | null slug?: string | null diff --git a/apps/web/vercel.json b/apps/web/vercel.json new file mode 100644 index 0000000..ebee386 --- /dev/null +++ b/apps/web/vercel.json @@ -0,0 +1,9 @@ +{ + "$schema": "https://openapi.vercel.sh/vercel.json", + "crons": [ + { + "path": "/api/cron/cleanup-reservations", + "schedule": "0 3 * * *" + } + ] +} diff --git a/docs/cli.md b/docs/cli.md index ad775ed..2a2ec3d 100644 --- a/docs/cli.md +++ b/docs/cli.md @@ -14,6 +14,7 @@ - [`helpbase deploy`](#helpbase-deploy) - [`helpbase link`](#helpbase-link) - [`helpbase open`](#helpbase-open) +- [`helpbase rename`](#helpbase-rename) - [`helpbase generate`](#helpbase-generate) - [`helpbase sync`](#helpbase-sync) - [`helpbase mcp`](#helpbase-mcp) @@ -199,6 +200,31 @@ Options: -h, --help display help for command ``` +## `helpbase rename` + +```text +Usage: helpbase rename [options] + +Rename your auto-provisioned reservation before first deploy (changes your +`.helpbase.dev` subdomain). + +Arguments: + new-slug The new subdomain (lowercase letters, numbers, hyphens; 3-40 + chars) + +Options: + -h, --help display help for command + +Examples: + $ helpbase rename acme # reserve acme.helpbase.dev + $ helpbase rename acme-docs + +Rename rules: + - Only works BEFORE your first deploy. After deploy, the slug is fixed. + - New slug follows the same validation as helpbase deploy --slug. + - If the new slug is taken, you'll get a slug_taken error — try another. +``` + ## `helpbase generate` ```text diff --git a/packages/cli/src/commands/deploy.ts b/packages/cli/src/commands/deploy.ts index d34b672..790f1f8 100644 --- a/packages/cli/src/commands/deploy.ts +++ b/packages/cli/src/commands/deploy.ts @@ -25,6 +25,8 @@ import { removeProjectConfig, writeProjectConfig, } from "../lib/project-config.js" +import { ensureReservation, loadReservation } from "../lib/reservation.js" +import { clearCachedReservation } from "../lib/reservation-cache.js" const SLUG_REGEX = /^[a-z0-9][a-z0-9-]*[a-z0-9]$/ // Kept in sync with RESERVED_SLUGS in link.ts and the subdomain-middleware allowlist. @@ -83,6 +85,143 @@ Examples: // 2. Authenticate const session = await ensureAuthenticated() + // 2.5. Read + validate content BEFORE resolving / creating a tenant. + // Content failures must never leave an orphan tenant row — if + // `deploy --slug foo` hit apiCreateTenant first and then failed + // on frontmatter validation, the row would sit forever with + // auto_provisioned_at=NULL + deployed_at=NULL, hidden from + // /mine, invisible to /reservation, untouched by cleanup cron, + // slug permanently burned. Validating first means content + // problems fail with zero server-side state change. Skipped + // for --rotate-mcp-token (it doesn't touch content). + // Caught by /review codex on 2026-04-18. + const categories: Array<{ + slug: string + title: string + description: string + icon: string + order: number + }> = [] + const articles: Array<{ + slug: string + category: string + title: string + description: string + content: string + frontmatter: Record + order: number + tags: string[] + heroImage: string | null + videoEmbed: string | null + featured: boolean + filePath: string + }> = [] + if (!opts.rotateMcpToken) { + const s = spinner() + s.start("Reading content...") + const errors: string[] = [] + const categoryDirs = fs + .readdirSync(contentDir, { withFileTypes: true }) + .filter((d) => d.isDirectory()) + + for (const dir of categoryDirs) { + const categorySlug = dir.name + const categoryPath = path.join(contentDir, categorySlug) + + const metaPath = path.join(categoryPath, "_category.json") + let meta = { title: categorySlug, description: "", icon: "file-text", order: 999 } + if (fs.existsSync(metaPath)) { + try { + const raw = JSON.parse(fs.readFileSync(metaPath, "utf-8")) + const parsed = categoryMetaSchema.safeParse(raw) + if (parsed.success) { + meta = parsed.data + } else { + // Previously we silently fell back to defaults when the + // schema didn't match, which let malformed _category.json + // ship as "categorySlug / no description / file-text icon" + // without any signal to the user. Surface the issue so it + // gets fixed before the deploy atomic write. CodeRabbit + // caught this on PR #10. + errors.push( + `${categorySlug}/_category.json: ${parsed.error.issues.map((i) => i.message).join(", ")}`, + ) + } + } catch { + errors.push(`${categorySlug}/_category.json: Invalid JSON`) + } + } + + categories.push({ slug: categorySlug, ...meta }) + + const files = fs + .readdirSync(categoryPath) + .filter((f) => f.endsWith(".mdx") || f.endsWith(".md")) + + for (const file of files) { + const filePath = path.join(categoryPath, file) + const raw = fs.readFileSync(filePath, "utf-8") + const { data, content } = matter(raw) + + const parsed = frontmatterSchema.safeParse(data) + if (!parsed.success) { + errors.push( + `${categorySlug}/${file}: ${parsed.error.issues.map((i) => i.message).join(", ")}`, + ) + continue + } + + const articleSlug = file.replace(/\.mdx?$/, "") + + // Reject articles whose body is empty (or only whitespace). A + // frontmatter-only MDX file deploys as a ghost article with a + // title but no content — visible in search, clickable, then + // renders a blank page. Catch it at deploy time instead. + // CodeRabbit caught this on PR #10. + if (content.trim().length === 0) { + errors.push( + `${categorySlug}/${file}: article body is empty (add content below the frontmatter)`, + ) + continue + } + + articles.push({ + slug: articleSlug, + category: categorySlug, + title: parsed.data.title, + description: parsed.data.description, + content, + frontmatter: data as Record, + order: parsed.data.order, + tags: parsed.data.tags, + heroImage: parsed.data.heroImage ?? null, + videoEmbed: parsed.data.videoEmbed ?? null, + featured: parsed.data.featured ?? false, + filePath: `content/${categorySlug}/${file}`, + }) + } + } + + s.stop(`Found ${categories.length} categories, ${articles.length} articles`) + + if (errors.length > 0) { + cancel( + `${errors.length} article(s) have invalid frontmatter:\n` + + errors.map((e) => ` ${pc.red("•")} ${e}`).join("\n") + + "\n\nFix these and run helpbase deploy again.", + ) + process.exit(1) + } + + if (articles.length === 0) { + cancel( + "No articles found in content/.\n" + + `Generate some: ${pc.cyan("helpbase generate --url ")}`, + ) + process.exit(1) + } + } + // 3. Get or create tenant // Priority: .helpbase/project.json → owner lookup → create new. // All tenant CRUD now goes through /api/v1/tenants/* — the CLI @@ -92,6 +231,10 @@ Examples: // is enforced server-side. const linked = readProjectConfig() let existingTenant: { id: string; slug: string } | null = null + // Flag so the post-deploy cleanup knows to invalidate the reservation + // cache — once deploy_tenant flips deployed_at, the cached reservation + // is stale and next whoami would still read the old row as "reserved". + let usedReservation = false if (linked) { // apiGetTenant now throws on 403 (caller isn't the owner). Treat @@ -110,7 +253,44 @@ Examples: } } else { const tenants = await listMyTenants(session) - if (tenants.length === 0) { + // Reservation-first path: if the user has no deployed tenants and + // didn't pass an explicit --slug, use the auto-provisioned reservation + // (minted at login). Skips the interactive slug prompt entirely for + // the common first-deploy happy path — matches the DX review's + // "TTHW drops from 3-4 min to 90s" target. --slug override still + // creates a new tenant (user intentionally chose a custom slug). + // + // Lazy-provision: if no cached/remote reservation exists, call + // ensureReservation (idempotent POST /auto-provision). Covers users + // who Ctrl-C'd login mid-auto-provision, or who logged in before + // reservations existed. Soft-fails on 503 → falls through to the + // interactive slug prompt. + if (tenants.length === 0 && !opts.slug) { + // Write path: force-refresh from the server so a stale cache + // (e.g. reservation was renamed in another shell, or deleted by + // the cleanup cron) doesn't send us to a tenantId that no longer + // exists. The read-only whoami/open stay cache-first for speed; + // deploy pays the one round-trip. CodeRabbit flagged this on PR #10. + let reservation = await loadReservation(session, { forceRefresh: true }).catch( + () => null, + ) + if (!reservation) { + const ensured = await ensureReservation(session) + if (ensured) { + reservation = await loadReservation(session, { forceRefresh: true }).catch( + () => null, + ) + } + } + if (reservation) { + existingTenant = { id: reservation.tenantId, slug: reservation.slug } + usedReservation = true + } + } + if (existingTenant) { + // Already resolved via reservation — skip the picker/disambiguator + // logic below. + } else if (tenants.length === 0) { existingTenant = null } else if (tenants.length === 1) { const only = tenants[0]! @@ -159,9 +339,14 @@ Examples: if (existingTenant) { tenantId = existingTenant.id tenantSlug = existingTenant.slug + const tag = linked + ? "(linked)" + : usedReservation + ? "(reserved at login)" + : "" note( - linked - ? `Deploying to ${pc.cyan(`${tenantSlug}.helpbase.dev`)} ${pc.dim("(linked)")}` + tag + ? `Deploying to ${pc.cyan(`${tenantSlug}.helpbase.dev`)} ${pc.dim(tag)}` : `Deploying to ${pc.cyan(`${tenantSlug}.helpbase.dev`)}`, "Tenant", ) @@ -268,113 +453,11 @@ Examples: return } - // 4. Read and validate content + // 5. Compute chunks (CLI-side chunking for MCP search_docs). Content + // was already read + validated at step 2.5 (pre-tenant-resolution) + // so by the time we reach this point `articles` + `categories` are + // populated and known-valid. const s = spinner() - s.start("Reading content...") - - const categories: Array<{ - slug: string - title: string - description: string - icon: string - order: number - }> = [] - const articles: Array<{ - slug: string - category: string - title: string - description: string - content: string - frontmatter: Record - order: number - tags: string[] - heroImage: string | null - videoEmbed: string | null - featured: boolean - filePath: string - }> = [] - const errors: string[] = [] - - const categoryDirs = fs - .readdirSync(contentDir, { withFileTypes: true }) - .filter((d) => d.isDirectory()) - - for (const dir of categoryDirs) { - const categorySlug = dir.name - const categoryPath = path.join(contentDir, categorySlug) - - // Read _category.json if it exists - const metaPath = path.join(categoryPath, "_category.json") - let meta = { title: categorySlug, description: "", icon: "file-text", order: 999 } - if (fs.existsSync(metaPath)) { - try { - const raw = JSON.parse(fs.readFileSync(metaPath, "utf-8")) - const parsed = categoryMetaSchema.safeParse(raw) - if (parsed.success) meta = parsed.data - } catch { - errors.push(`${categorySlug}/_category.json: Invalid JSON`) - } - } - - categories.push({ slug: categorySlug, ...meta }) - - // Read MDX files - const files = fs - .readdirSync(categoryPath) - .filter((f) => f.endsWith(".mdx") || f.endsWith(".md")) - - for (const file of files) { - const filePath = path.join(categoryPath, file) - const raw = fs.readFileSync(filePath, "utf-8") - const { data, content } = matter(raw) - - const parsed = frontmatterSchema.safeParse(data) - if (!parsed.success) { - errors.push( - `${categorySlug}/${file}: ${parsed.error.issues.map((i) => i.message).join(", ")}` - ) - continue - } - - const articleSlug = file.replace(/\.mdx?$/, "") - - articles.push({ - slug: articleSlug, - category: categorySlug, - title: parsed.data.title, - description: parsed.data.description, - content, - frontmatter: data as Record, - order: parsed.data.order, - tags: parsed.data.tags, - heroImage: parsed.data.heroImage ?? null, - videoEmbed: parsed.data.videoEmbed ?? null, - featured: parsed.data.featured ?? false, - filePath: `content/${categorySlug}/${file}`, - }) - } - } - - s.stop(`Found ${categories.length} categories, ${articles.length} articles`) - - if (errors.length > 0) { - cancel( - `${errors.length} article(s) have invalid frontmatter:\n` + - errors.map((e) => ` ${pc.red("•")} ${e}`).join("\n") + - "\n\nFix these and run helpbase deploy again." - ) - process.exit(1) - } - - if (articles.length === 0) { - cancel( - "No articles found in content/.\n" + - `Generate some: ${pc.cyan("helpbase generate --url ")}` - ) - process.exit(1) - } - - // 5. Compute chunks (CLI-side chunking for MCP search_docs). s.start("Chunking content for search...") const chunks: TenantChunk[] = [] for (const a of articles) { @@ -444,12 +527,25 @@ Examples: const tenantAfter = await apiGetTenant(session, tenantId).catch(() => null) const mcpToken = tenantAfter?.mcp_public_token ?? "" - // 9. Done. - const liveUrl = `https://${tenantSlug}.helpbase.dev` - const mcpUrl = `https://${tenantSlug}.helpbase.dev/mcp` + // 9. Done. If we consumed a reservation to get here, the server just + // flipped deployed_at in deploy_tenant — invalidate the cache so + // `helpbase whoami` stops showing the tenant as "reserved". + if (usedReservation) { + clearCachedReservation() + } + // Use the slug the SERVER echoes from deploy_tenant, not the local + // `tenantSlug` captured before the RPC. The local value can be stale: + // a concurrent `helpbase rename` in another terminal (or an admin + // rename in the dashboard) might have changed the slug between our + // loadReservation cache hit and this print. The deploy RPC resolves + // by tenantId and returns the canonical slug; trust that for the + // URL summary. Caught by /review codex on 2026-04-18. + const finalSlug = deployResult.slug || tenantSlug + const liveUrl = `https://${finalSlug}.helpbase.dev` + const mcpUrl = `https://${finalSlug}.helpbase.dev/mcp` outro(`${pc.green("✓")} Deployed! Your help center is live.`) summaryTable([ - ["Tenant", `${tenantSlug}.helpbase.dev`], + ["Tenant", `${finalSlug}.helpbase.dev`], ["Articles", String(articles.length)], ["Chunks", String(chunks.length)], ["Categories", String(categories.length)], @@ -462,7 +558,7 @@ Examples: const mcpConfig = JSON.stringify( { mcpServers: { - [tenantSlug]: { + [finalSlug]: { url: mcpUrl, headers: { Authorization: `Bearer ${mcpToken}` }, }, diff --git a/packages/cli/src/commands/login.ts b/packages/cli/src/commands/login.ts index e5fd703..c44bd8c 100644 --- a/packages/cli/src/commands/login.ts +++ b/packages/cli/src/commands/login.ts @@ -8,12 +8,14 @@ import { isNonInteractive, sendLoginCode, verifyLoginFromMagicLink, + type AuthSession, } from "../lib/auth.js" import { HelpbaseError, formatError } from "../lib/errors.js" import { hasAskedForConsent, setTelemetryConsent, } from "../lib/telemetry.js" +import { ensureReservation } from "../lib/reservation.js" export const loginCommand = new Command("login") .description("Log in to helpbase cloud") @@ -84,9 +86,13 @@ async function runDeviceFlow(): Promise { }, }) s.stop(`Logged in as ${pc.cyan(session.email)}`) + // Auto-provision a docs-<6hex> reservation so the user sees a URL + // right after login — the "magical moment" /plan-devex-review + // mandated. Best-effort: a 503 prints a soft warning via + // ensureReservation and returns null; login still succeeds. + const reservation = await ensureReservation(session) await maybeAskTelemetryConsent() - outro(`Logged in as ${pc.cyan(session.email)}`) - nextSteps({ commands: ["helpbase whoami", "helpbase new"] }) + printLoginOutro(session, reservation) } catch (err) { s.stop("Login failed.") if (err instanceof HelpbaseError) { @@ -148,9 +154,11 @@ async function runMagicLinkFlow(preset?: string): Promise { try { const session = await verifyLoginFromMagicLink((input as string).trim()) + // Same auto-provision path as the device flow — the magic-link fallback + // should produce an identical "welcome + reserved URL" experience. + const reservation = await ensureReservation(session) await maybeAskTelemetryConsent() - outro(`Logged in as ${pc.cyan(session.email)}`) - nextSteps({ commands: ["helpbase whoami", "helpbase new"] }) + printLoginOutro(session, reservation) } catch (err) { if (err instanceof HelpbaseError) { cancel(formatError(err).trimEnd()) @@ -161,6 +169,44 @@ async function runMagicLinkFlow(preset?: string): Promise { } } +/** + * Terminal footer for a successful login. Shows the reserved URL when + * one was minted so the user sees a concrete destination before the + * telemetry prompt finishes fading from their scrollback, and falls + * back gracefully when auto-provisioning soft-failed (ensureReservation + * already logged the reason to stderr in that case). + */ +function printLoginOutro( + session: AuthSession, + reservation: Awaited>, +): void { + if (reservation) { + const label = reservation.isNew ? "Reserved" : "Your help center" + note( + `${pc.dim(label + ":")} ${pc.cyan(reservation.liveUrl)}\n` + + `${pc.dim( + reservation.isNew + ? "Deploy content to publish, or rename before first deploy." + : "Deploy content to publish.", + )}`, + "helpbase", + ) + outro(`Logged in as ${pc.cyan(session.email)}`) + nextSteps({ + commands: [ + "helpbase deploy", + "helpbase rename ", + "helpbase whoami", + ], + }) + return + } + // No reservation (auto-provision soft-failed): fall back to the + // pre-reservation-era next-steps block. + outro(`Logged in as ${pc.cyan(session.email)}`) + nextSteps({ commands: ["helpbase whoami", "helpbase new"] }) +} + /** * Ask once, after the user's first successful login, whether they want to * share anonymous usage telemetry. Silent on every subsequent login. diff --git a/packages/cli/src/commands/open.ts b/packages/cli/src/commands/open.ts index a1e983e..7e7d8a8 100644 --- a/packages/cli/src/commands/open.ts +++ b/packages/cli/src/commands/open.ts @@ -4,6 +4,7 @@ import pc from "picocolors" import { readProjectConfig } from "../lib/project-config.js" import { getCurrentSession } from "../lib/auth.js" import { listMyTenants } from "../lib/tenants-client.js" +import { loadReservation } from "../lib/reservation.js" export const openCommand = new Command("open") .description("Open this project's help center in the default browser") @@ -52,7 +53,16 @@ async function resolveSlug(): Promise { if (!session) return null try { const tenants = await listMyTenants(session) - return tenants[0]?.slug ?? null + if (tenants[0]) return tenants[0].slug + } catch { + // fall through to reservation check + } + // Last fallback: the auto-provisioned reservation. Opens the branded + // "coming soon" page at the reserved URL, which is useful for a freshly + // logged-in user running `helpbase open` before they've deployed. + try { + const reservation = await loadReservation(session) + return reservation?.slug ?? null } catch { return null } diff --git a/packages/cli/src/commands/rename.ts b/packages/cli/src/commands/rename.ts new file mode 100644 index 0000000..2d04787 --- /dev/null +++ b/packages/cli/src/commands/rename.ts @@ -0,0 +1,191 @@ +import { Command } from "commander" +import { intro, outro, cancel, note } from "@clack/prompts" +import pc from "picocolors" +import { getCurrentSession } from "../lib/auth.js" +import { renameReservation } from "../lib/tenants-client.js" +import { loadReservation } from "../lib/reservation.js" +import { + writeCachedReservation, + clearCachedReservation, +} from "../lib/reservation-cache.js" +import { HelpbaseError, formatError } from "../lib/errors.js" + +/** + * `helpbase rename ` + * + * Pre-deploy slug rename for an auto-provisioned reservation. The server + * enforces the deploy gate (`deployed_at IS NULL`); this command is a thin + * wrapper that: + * 1. Loads the current reservation (cache-first, falls back to server). + * 2. Calls PATCH /api/v1/tenants/reservation/slug with the new slug. + * 3. Updates the local cache so `helpbase whoami` reflects the new URL + * immediately — without, the user would see the old slug until the + * next `helpbase login` refreshed it. + * + * Post-deploy rename is intentionally out of scope. Slug changes after a + * tenant has been published would need a redirect layer in proxy.ts that + * we haven't built yet, and the existing published URL might already be + * linked-to (blog posts, MCP client configs). Ship path for post-deploy + * slug changes: delete and recreate. + */ + +export const renameCommand = new Command("rename") + .description( + "Rename your auto-provisioned reservation before first deploy (changes your `.helpbase.dev` subdomain).", + ) + .argument("", "The new subdomain (lowercase letters, numbers, hyphens; 3-40 chars)") + .addHelpText( + "after", + ` +Examples: + $ helpbase rename acme # reserve acme.helpbase.dev + $ helpbase rename acme-docs + +Rename rules: + - Only works BEFORE your first deploy. After deploy, the slug is fixed. + - New slug follows the same validation as ${pc.cyan("helpbase deploy --slug")}. + - If the new slug is taken, you'll get a ${pc.cyan("slug_taken")} error — try another. +`, + ) + .action(async (newSlug: string) => { + intro(pc.bgCyan(pc.black(" helpbase rename "))) + + const session = await getCurrentSession() + if (!session) { + cancel( + `Not signed in. Run ${pc.cyan("helpbase login")} first.`, + ) + process.exit(1) + } + + // Force a server round-trip instead of trusting the cache. Rename is + // a write path — if another shell already renamed or deployed this + // reservation, the cache's slug is stale and the same-slug + // short-circuit below would lie to the user ("nothing to rename") + // when in fact the server knows a different slug. CodeRabbit caught + // this on PR #10. + const current = await loadReservation(session, { forceRefresh: true }) + if (!current) { + throw new HelpbaseError({ + code: "E_RESERVATION_MISSING", + problem: "You don't have an active reservation to rename.", + cause: + "Renames only apply to the pre-deploy placeholder `docs-` slug that login auto-provisions. " + + "After your first deploy (or if you logged in before reservations existed), the tenant's slug is fixed.", + fix: [ + `To claim a specific slug on first deploy, use ${pc.cyan("helpbase deploy --slug ")}.`, + `To see your current state, run ${pc.cyan("helpbase whoami")}.`, + ], + }) + } + + if (current.slug === newSlug) { + outro( + `Already reserved ${pc.cyan(current.liveUrl)} — nothing to rename.`, + ) + return + } + + try { + const updated = await renameReservation(session, newSlug) + // Overwrite the local cache so the next `whoami` / `open` reflects + // the new slug without a second round-trip. + writeCachedReservation({ + tenantId: updated.id, + slug: updated.slug, + liveUrl: updated.live_url, + mcpPublicToken: updated.mcp_public_token, + userId: session.userId, + }) + note( + `${pc.dim("Before:")} ${pc.dim(current.liveUrl)}\n` + + `${pc.dim("After:")} ${pc.cyan(updated.live_url)}`, + "Reservation renamed", + ) + outro( + `Reserved ${pc.cyan(updated.live_url)} — run ${pc.cyan("helpbase deploy")} to publish.`, + ) + } catch (err) { + const msg = err instanceof Error ? err.message : String(err) + // Translate the server's error codes into HelpbaseError instances + // so the user gets the structured fix/docs output and the rest of + // the CLI's error formatting layer kicks in. + if (/slug_taken/.test(msg)) { + throw new HelpbaseError({ + code: "E_SLUG_TAKEN", + problem: `The slug "${newSlug}" is already taken by another helpbase user.`, + cause: "Each helpbase.dev subdomain must be globally unique.", + fix: [ + "Pick a different slug and retry.", + "If you think this is your own tenant, run `helpbase whoami` to confirm.", + ], + }) + } + if (/slug_reserved/.test(msg)) { + throw new HelpbaseError({ + code: "E_SLUG_RESERVED", + problem: `The slug "${newSlug}" is reserved by helpbase.`, + cause: + "A short list of slugs (www, api, admin, docs, mcp, ...) is reserved so they can't collide with helpbase.dev marketing/auth/infra URLs.", + fix: ["Pick a different slug and retry."], + }) + } + // Server-side slug validation failures. The CLI doesn't pre-validate + // so these fall through from the PATCH body check in + // /api/v1/tenants/reservation/slug/route.ts. Without these branches + // the user gets a raw `Rename failed: slug_invalid` cancel line + // instead of structured fix copy. + if (/slug_invalid/.test(msg)) { + throw new HelpbaseError({ + code: "E_SLUG_INVALID", + problem: `The slug "${newSlug}" is not a valid subdomain.`, + cause: + "Slugs must be lowercase letters, numbers, and hyphens only — 3 to 40 characters, starting and ending with an alphanumeric character.", + fix: [ + "Examples of valid slugs: acme, acme-docs, my-product-42.", + "Examples that fail: ACME (uppercase), -acme (leading hyphen), a (too short).", + ], + }) + } + if (/slug_required/.test(msg)) { + throw new HelpbaseError({ + code: "E_MISSING_FLAG", + problem: "Rename needs a new slug.", + cause: "The PATCH call reached the server with an empty slug body.", + fix: [ + `Pass the slug as an argument: ${pc.cyan("helpbase rename ")}.`, + ], + }) + } + if (/reservation_locked/.test(msg)) { + clearCachedReservation() + throw new HelpbaseError({ + code: "E_RESERVATION_LOCKED", + problem: + "Your reservation was deployed before the rename could complete.", + cause: + "A concurrent `helpbase deploy` flipped the tenant from reservation to live while this rename was in flight. Post-deploy slug changes aren't supported.", + fix: [ + `Run ${pc.cyan("helpbase whoami")} to see the deployed slug.`, + `To move content to a different subdomain, delete the tenant and re-create: ${pc.cyan("helpbase deploy --delete --yes")} then ${pc.cyan("helpbase deploy --slug ")}.`, + ], + }) + } + if (/no_reservation/.test(msg)) { + // Server says no reservation even though the cache claimed one — + // likely the tenant was deleted or deployed from a different + // shell. Refresh the cache to prevent future confusion. + clearCachedReservation() + throw new HelpbaseError({ + code: "E_RESERVATION_MISSING", + problem: "You don't have an active reservation to rename.", + cause: + "The server reports no active reservation for your account. The local cache was stale.", + fix: [`Run ${pc.cyan("helpbase whoami")} to see your current tenant state.`], + }) + } + // Unknown — let it bubble as a plain error. + cancel(`Rename failed: ${msg}`) + process.exit(1) + } + }) diff --git a/packages/cli/src/commands/whoami.ts b/packages/cli/src/commands/whoami.ts index 0f7efbe..fa5e4a0 100644 --- a/packages/cli/src/commands/whoami.ts +++ b/packages/cli/src/commands/whoami.ts @@ -2,6 +2,7 @@ import { Command } from "commander" import pc from "picocolors" import { getCurrentSession } from "../lib/auth.js" import { listMyTenants } from "../lib/tenants-client.js" +import { ensureReservation, loadReservation } from "../lib/reservation.js" import { fetchUsageToday, getActiveByokKey, isByokMode } from "@workspace/shared/llm" import { humanTokens, humanUntil } from "@workspace/shared/llm-errors" import { BYOK_DOCS_URL } from "@workspace/shared/llm-wire" @@ -50,16 +51,55 @@ export const whoamiCommand = new Command("whoami") // Best-effort tenant lookup — we don't fail whoami if this errors. // Goes through /api/v1/tenants/mine (owner filter + active check are - // enforced server-side with the user's Better Auth bearer). + // enforced server-side with the user's Better Auth bearer). /mine + // hides reservations, so the reservation is fetched separately via + // loadReservation (cache-first, server on miss). let tenant: { slug: string; name: string } | null = null + // Track whether the tenant lookup actually succeeded vs threw. Without + // this flag we'd conflate "/mine returned zero rows" with "/mine hit a + // network error", and the mutating ensureReservation fallback below + // could mint a reservation for an account that already owns deployed + // tenants we just couldn't reach. CodeRabbit caught this on PR #10. + let tenantLookupSucceeded = false try { const tenants = await listMyTenants(session) + tenantLookupSucceeded = true const first = tenants[0] if (first) tenant = { slug: first.slug, name: first.name } } catch { // ignore — tenant lookup is informational } + let reservation: Awaited> = null + // Only show a reservation when the user has NO deployed tenants. + // A power user with 5 deployed tenants doesn't care about the + // pre-first-deploy placeholder anymore. + if (!tenant) { + try { + reservation = await loadReservation(session) + // Lazy-provision fallback: if the user has no deployed tenants + // AND no cached/remote reservation, they likely Ctrl-C'd login + // between session persist and auto-provision, or logged in + // before the feature existed. ensureReservation hits the + // idempotent POST /auto-provision — either returns their + // existing row or mints a fresh one. Soft-fails on 503 + // (ensureReservation writes a stderr warning + returns null). + // + // GATE: only run this mutating path if the tenant lookup + // actually succeeded and came back empty. If /mine threw, we + // don't know whether the user has deployed tenants and + // provisioning a fresh reservation could create unwanted state. + if (!reservation && tenantLookupSucceeded) { + const ensured = await ensureReservation(session) + if (ensured) { + reservation = await loadReservation(session) + } + } + } catch { + // ignore — reservation display is informational + } + } + // Best-effort usage lookup. Fails closed silently: if the hosted API is // unreachable, we don't want whoami to error — just omit the usage line. let usage: UsageTodayResponse | null = null @@ -80,6 +120,9 @@ export const whoamiCommand = new Command("whoami") userId: session.userId, source, tenant, + reservation: reservation + ? { slug: reservation.slug, liveUrl: reservation.liveUrl } + : null, byok, usage: usage?.quota ?? null, }, @@ -115,6 +158,15 @@ export const whoamiCommand = new Command("whoami") console.log(` source: ${pc.dim(source)}`) if (tenant) { console.log(` tenant: ${pc.cyan(`${tenant.slug}.helpbase.dev`)} ${pc.dim(`(${tenant.name})`)}`) + } else if (reservation) { + // liveUrl is the server's source of truth for the reservation's + // hostname — respects NEXT_PUBLIC_ROOT_DOMAIN in staging/dev, where + // `${slug}.helpbase.dev` would mislead the user. CodeRabbit caught + // the hard-coded root domain on PR #10. + const host = reservation.liveUrl.replace(/^https?:\/\//, "") + console.log( + ` reserved: ${pc.cyan(host)} ${pc.dim("(not yet deployed — run `helpbase deploy` to publish, or `helpbase rename ` to change)")}`, + ) } else { console.log(` tenant: ${pc.dim("none — run `helpbase deploy` to create one")}`) } diff --git a/packages/cli/src/index.ts b/packages/cli/src/index.ts index 22dff77..44499dc 100644 --- a/packages/cli/src/index.ts +++ b/packages/cli/src/index.ts @@ -20,6 +20,7 @@ import { logoutCommand } from "./commands/logout.js" import { whoamiCommand } from "./commands/whoami.js" import { linkCommand } from "./commands/link.js" import { openCommand } from "./commands/open.js" +import { renameCommand } from "./commands/rename.js" import { feedbackCommand } from "./commands/feedback.js" import { configCommand } from "./commands/config.js" import { doctorCommand } from "./commands/doctor.js" @@ -92,6 +93,7 @@ program.addCommand(logoutCommand) program.addCommand(whoamiCommand) program.addCommand(linkCommand) program.addCommand(openCommand) +program.addCommand(renameCommand) program.addCommand(feedbackCommand) program.addCommand(configCommand) program.addCommand(doctorCommand) diff --git a/packages/cli/src/lib/errors.ts b/packages/cli/src/lib/errors.ts index de049db..d968a5b 100644 --- a/packages/cli/src/lib/errors.ts +++ b/packages/cli/src/lib/errors.ts @@ -23,6 +23,7 @@ export type ErrorCode = | "E_AUTH_EXPIRED" | "E_SLUG_TAKEN" | "E_SLUG_RESERVED" + | "E_SLUG_INVALID" | "E_TENANT_NOT_FOUND" | "E_MISSING_API_KEY" | "E_NOT_A_PROJECT" @@ -60,6 +61,9 @@ export type ErrorCode = | "E_DEVICE_DENIED" | "E_DEVICE_EXPIRED" | "E_DEVICE_NETWORK" + | "E_RESERVATION_MISSING" + | "E_RESERVATION_LOCKED" + | "E_RESERVATION_PROVISION_FAILED" export interface HelpbaseErrorInit { code: ErrorCode diff --git a/packages/cli/src/lib/help.ts b/packages/cli/src/lib/help.ts index bb4a697..6e4e5fb 100644 --- a/packages/cli/src/lib/help.ts +++ b/packages/cli/src/lib/help.ts @@ -29,7 +29,7 @@ interface GroupDef { const GROUPS: GroupDef[] = [ { label: "Get started", commands: ["ingest", "preview", "new", "dev"] }, - { label: "Ship", commands: ["deploy", "link", "open"] }, + { label: "Ship", commands: ["deploy", "link", "open", "rename"] }, { label: "Author", commands: ["generate", "sync", "mcp", "audit"] }, { label: "Account", commands: ["login", "logout", "whoami", "config"] }, { label: "Diagnose", commands: ["doctor", "feedback", "completion", "upgrade"] }, diff --git a/packages/cli/src/lib/reservation-cache.ts b/packages/cli/src/lib/reservation-cache.ts new file mode 100644 index 0000000..177c5e3 --- /dev/null +++ b/packages/cli/src/lib/reservation-cache.ts @@ -0,0 +1,122 @@ +import fs from "node:fs" +import path from "node:path" +import os from "node:os" + +/** + * Local cache for the user's slug reservation. + * + * The server (POST /api/v1/tenants/auto-provision) is the source of + * truth; this file exists so `helpbase whoami` / `open` / `deploy` + * don't have to hit the network every time to show or consume the + * reserved URL. On cache miss (no file, corrupt JSON, or stale tenant + * id) callers fall back to `getReservation()` against the server and + * overwrite the cache with the fresh row. + * + * Intentionally a SEPARATE file from `~/.helpbase/auth.json`. Reasons: + * - `storeSession` writes a fixed StoredAuth shape; extending it to + * also carry a reservation would mean every session write has to + * preserve the reservation, creating a subtle "lost on re-auth" + * footgun. + * - Two concerns, two files: the session is a credential; the + * reservation is just cached state. `logout` clears auth.json but + * leaves reservation.json alone (the reservation survives on the + * server across logins). + * + * File location: `~/.helpbase/reservation.json`, mode 0o600 to match + * auth.json. The 0o700 parent-dir mode is created by storeSession on + * first login; we reuse it if it exists and fall through if not. + */ + +const HOME = os.homedir() +// Mirrors the AUTH_DIR constant in auth.ts — keep in lockstep. +const BASE_DIR = process.env.HELPBASE_CONFIG_DIR ?? path.join(HOME, ".helpbase") +const FILE = path.join(BASE_DIR, "reservation.json") + +export interface CachedReservation { + /** The reserved tenant's UUID — used as the idempotency key for deploy. */ + tenantId: string + slug: string + /** e.g. `https://docs-a3f9c1.helpbase.dev`. Precomputed by the server. */ + liveUrl: string + /** Raw MCP bearer — mirrored here so `helpbase whoami` can surface it without a second roundtrip. */ + mcpPublicToken: string + /** The user this reservation belongs to. If the CLI logs in as a different user, the cache is stale. */ + userId: string + /** ISO timestamp of when this cache entry was written. Purely informational. */ + cachedAt: string +} + +/** + * Read the cached reservation, or return null if the file is missing, + * unreadable, or shaped wrong. Callers treat null as "no cache — hit + * the server." + */ +export function readCachedReservation(): CachedReservation | null { + if (!fs.existsSync(FILE)) return null + try { + const raw = fs.readFileSync(FILE, "utf-8") + const parsed = JSON.parse(raw) as Partial + if ( + typeof parsed.tenantId !== "string" || + typeof parsed.slug !== "string" || + typeof parsed.liveUrl !== "string" || + typeof parsed.mcpPublicToken !== "string" || + typeof parsed.userId !== "string" + ) { + return null + } + return { + tenantId: parsed.tenantId, + slug: parsed.slug, + liveUrl: parsed.liveUrl, + mcpPublicToken: parsed.mcpPublicToken, + userId: parsed.userId, + cachedAt: parsed.cachedAt ?? "", + } + } catch { + return null + } +} + +/** + * Write the reservation to disk. Creates `~/.helpbase/` if it doesn't + * exist with 0o700, and force-narrows the file to 0o600 on every write + * (matches auth.ts — writeFileSync's mode is only honored on create, so + * a pre-existing loose-perms file needs an explicit chmod). + */ +export function writeCachedReservation(reservation: Omit): void { + if (!fs.existsSync(BASE_DIR)) { + fs.mkdirSync(BASE_DIR, { recursive: true, mode: 0o700 }) + } + const payload: CachedReservation = { + ...reservation, + cachedAt: new Date().toISOString(), + } + fs.writeFileSync(FILE, JSON.stringify(payload, null, 2), { mode: 0o600 }) + try { + fs.chmodSync(FILE, 0o600) + } catch { + // best-effort — FAT/SMB don't support chmod + } +} + +/** + * Remove the cache file. Called by `deploy` after first-deploy succeeds + * (the reservation is no longer a reservation — it's a live tenant, and + * `.helpbase/project.json` is now the canonical local pointer) and by + * `rename` before re-fetching so a stale slug can't leak into the next + * whoami render. + */ +export function clearCachedReservation(): boolean { + if (!fs.existsSync(FILE)) return false + try { + fs.unlinkSync(FILE) + return true + } catch { + return false + } +} + +export function getCachedReservationPath(): string { + return FILE +} diff --git a/packages/cli/src/lib/reservation.ts b/packages/cli/src/lib/reservation.ts new file mode 100644 index 0000000..0331644 --- /dev/null +++ b/packages/cli/src/lib/reservation.ts @@ -0,0 +1,126 @@ +import pc from "picocolors" +import type { AuthSession } from "./auth.js" +import { + autoProvisionTenant, + getReservation, + type ReservationCreated, + type ReservationRow, +} from "./tenants-client.js" +import { + readCachedReservation, + writeCachedReservation, + type CachedReservation, +} from "./reservation-cache.js" + +/** + * Reservation resolution helpers. + * + * Two shapes the CLI needs on a regular basis: + * + * - `ensureReservation(session)` — called by `login`, `whoami`, and + * `deploy` when the user is authed but has no deployed tenants + + * no cached reservation. Calls POST /auto-provision (idempotent + * on the server) and writes the result to the local cache. If the + * server is unreachable or 503s, returns null so the caller can + * print a soft warning without failing the surrounding flow. + * + * - `loadReservation(session)` — read-only path for commands like + * `whoami` / `open`. Checks the cache first; falls back to + * GET /reservation on miss; refreshes the cache on hit. Returns + * null when the user has no active reservation. + * + * The cache can go stale (the user might `rename` from a different + * shell, for example). Cache-first callers that tolerate staleness + * use `loadReservation`; auth-critical paths (first-login bootstrap) + * bypass the cache and call autoProvisionTenant directly. + */ + +/** Returned by `ensureReservation` so callers can differentiate fresh vs existing. */ +export interface EnsuredReservation { + tenantId: string + slug: string + liveUrl: string + mcpPublicToken: string + isNew: boolean +} + +export async function ensureReservation( + session: AuthSession, +): Promise { + try { + const provisioned = await autoProvisionTenant(session) + cacheFromServer(session, provisioned) + return toEnsured(provisioned) + } catch (err) { + const msg = err instanceof Error ? err.message : String(err) + // Best-effort: login flows swallow this; the caller prints a soft + // warning. We surface a structured diagnostic to stderr so the user + // can still see what went wrong without the error aborting login. + process.stderr.write( + `${pc.yellow("!")} ${pc.dim("Could not reserve a subdomain right now:")} ${msg}\n` + + ` ${pc.dim("Login succeeded. Run")} ${pc.cyan("helpbase whoami")} ${pc.dim("later to retry.")}\n`, + ) + return null + } +} + +/** + * Cache-first reservation lookup. Returns whatever we know about the + * user's reservation (from the local file, then from the server on miss) + * or null if they have no active reservation. + * + * Callers can pass `forceRefresh: true` to skip the cache — useful for + * `helpbase rename` / `helpbase whoami --refresh` where the user explicitly + * wants a round-trip. + */ +export async function loadReservation( + session: AuthSession, + opts: { forceRefresh?: boolean } = {}, +): Promise { + if (!opts.forceRefresh) { + const cached = readCachedReservation() + if (cached && cached.userId === session.userId) { + return cached + } + } + let remote: ReservationRow | null = null + try { + remote = await getReservation(session) + } catch { + // Network / 503 — fall back to whatever's cached, but ONLY if the + // cache belongs to the current user. Without this check, a user on + // a shared laptop logs in over a previous user's cache, hits a + // transient network blip on first whoami, and the UI leaks the + // previous user's reservation (including MCP token). Caught by + // /review codex + Claude adversarial on 2026-04-18. + const fallback = readCachedReservation() + if (fallback && fallback.userId === session.userId) return fallback + return null + } + if (!remote) return null + cacheFromServer(session, remote) + return readCachedReservation() +} + +function cacheFromServer( + session: AuthSession, + row: ReservationCreated | ReservationRow, +): void { + writeCachedReservation({ + tenantId: row.id, + slug: row.slug, + liveUrl: row.live_url, + mcpPublicToken: row.mcp_public_token, + userId: session.userId, + }) +} + +function toEnsured(row: ReservationCreated): EnsuredReservation { + return { + tenantId: row.id, + slug: row.slug, + liveUrl: row.live_url, + mcpPublicToken: row.mcp_public_token, + isNew: row.is_new, + } +} diff --git a/packages/cli/src/lib/tenants-client.ts b/packages/cli/src/lib/tenants-client.ts index 8170950..40e2849 100644 --- a/packages/cli/src/lib/tenants-client.ts +++ b/packages/cli/src/lib/tenants-client.ts @@ -191,3 +191,87 @@ export async function rotateMcpToken( } return obj.mcp_public_token } + +// ── Reservation flow (PR-B of CLI DX v2) ──────────────────────────────── +// +// Login calls `autoProvisionTenant` to reserve a `docs-<6hex>.helpbase.dev` +// slug so the user sees a URL immediately. `getReservation` is the read-side +// used by `helpbase whoami` / `open` / lazy-provision fallbacks. +// `renameReservation` backs the `helpbase rename ` command — pre-deploy +// slug change only. + +export interface ReservationRow { + id: string + slug: string + name: string + live_url: string + mcp_public_token: string +} + +export interface ReservationCreated extends ReservationRow { + /** True when this call minted a fresh row, false when it returned an existing reservation. */ + is_new: boolean +} + +/** + * Call POST /api/v1/tenants/auto-provision. Idempotent server-side — + * repeat calls return the caller's existing reservation with `is_new: false`. + * Login invokes this once after successful device flow; `whoami` / `deploy` + * use it as a lazy-provision fallback for users who logged in before this + * feature existed or who Ctrl-C'd between session save and the first + * auto-provision call. + */ +export async function autoProvisionTenant( + session: AuthSession, +): Promise { + const res = await v1Fetch("/auto-provision", { + method: "POST", + headers: { authorization: `Bearer ${session.accessToken}` }, + }) + const body = await parseBody(res) + if (!res.ok) throwHttp("auto-provision tenant", res, body) + return body as ReservationCreated +} + +/** + * Call GET /api/v1/tenants/reservation. Returns null on 404 so callers + * can treat "no reservation" and "has reservation" as branching states + * without catching an error object. Any other non-200 throws. + */ +export async function getReservation( + session: AuthSession, +): Promise { + const res = await v1Fetch("/reservation", { + headers: { authorization: `Bearer ${session.accessToken}` }, + }) + if (res.status === 404) return null + const body = await parseBody(res) + if (!res.ok) throwHttp("get reservation", res, body) + return body as ReservationRow +} + +/** + * Call PATCH /api/v1/tenants/reservation/slug. Server enforces the + * pre-deploy gate (deployed_at IS NULL) and the slug validation rules. + * Common failure codes the CLI handler translates to errors: + * - 404 `no_reservation` → user has no reservation to rename + * - 409 `slug_taken` → someone else owns the slug + * - 409 `slug_reserved` → matches the RESERVED list + * - 409 `reservation_locked` → raced with a deploy that flipped deployed_at + */ +export async function renameReservation( + session: AuthSession, + slug: string, +): Promise { + const res = await v1Fetch("/reservation/slug", { + method: "PATCH", + headers: { + authorization: `Bearer ${session.accessToken}`, + "content-type": "application/json", + }, + body: JSON.stringify({ slug }), + }) + const body = await parseBody(res) + if (!res.ok) throwHttp("rename reservation", res, body) + return body as ReservationRow +} diff --git a/packages/cli/test/reservation-cache.test.ts b/packages/cli/test/reservation-cache.test.ts new file mode 100644 index 0000000..a0b5248 --- /dev/null +++ b/packages/cli/test/reservation-cache.test.ts @@ -0,0 +1,123 @@ +import { describe, it, expect, beforeEach, afterEach } from "vitest" +import fs from "node:fs" +import os from "node:os" +import path from "node:path" + +/** + * Pure-IO tests for the reservation cache. The module reads + * `HELPBASE_CONFIG_DIR` at import time per-read, so tests can swap the + * home directory per-test by setting the env var before importing. + * Dynamic import inside each test so module-scoped state doesn't leak. + */ + +let TMP_HOME: string + +beforeEach(() => { + TMP_HOME = fs.mkdtempSync(path.join(os.tmpdir(), "helpbase-reservation-cache-")) + process.env.HELPBASE_CONFIG_DIR = TMP_HOME +}) + +afterEach(() => { + delete process.env.HELPBASE_CONFIG_DIR + fs.rmSync(TMP_HOME, { recursive: true, force: true }) +}) + +describe("reservation-cache", () => { + it("returns null when no cache file exists", async () => { + const mod = await import("../src/lib/reservation-cache.js?no-cache-1") + expect(mod.readCachedReservation()).toBe(null) + }) + + it("write then read round-trips the reservation", async () => { + const mod = await import("../src/lib/reservation-cache.js?no-cache-2") + mod.writeCachedReservation({ + tenantId: "t-123", + slug: "docs-abc123", + liveUrl: "https://docs-abc123.helpbase.dev", + mcpPublicToken: "mcp-token-xyz", + userId: "u-456", + }) + const read = mod.readCachedReservation() + expect(read).not.toBe(null) + expect(read?.tenantId).toBe("t-123") + expect(read?.slug).toBe("docs-abc123") + expect(read?.liveUrl).toBe("https://docs-abc123.helpbase.dev") + expect(read?.userId).toBe("u-456") + // cachedAt is stamped at write time; just verify it's an ISO string. + expect(read?.cachedAt).toMatch(/^\d{4}-\d{2}-\d{2}T/) + }) + + it("returns null on corrupt JSON (never throws)", async () => { + const mod = await import("../src/lib/reservation-cache.js?no-cache-3") + const filePath = path.join(TMP_HOME, "reservation.json") + fs.mkdirSync(TMP_HOME, { recursive: true }) + fs.writeFileSync(filePath, "{ not valid json") + expect(mod.readCachedReservation()).toBe(null) + }) + + it("returns null on JSON that's missing required fields", async () => { + const mod = await import("../src/lib/reservation-cache.js?no-cache-4") + const filePath = path.join(TMP_HOME, "reservation.json") + fs.mkdirSync(TMP_HOME, { recursive: true }) + // Missing tenantId / userId — the shape guard in readCachedReservation + // treats this as a corrupt cache and returns null so callers hit the + // server on the next read. + fs.writeFileSync(filePath, JSON.stringify({ slug: "docs-abc" })) + expect(mod.readCachedReservation()).toBe(null) + }) + + it("clearCachedReservation removes the file and returns true only when it existed", async () => { + const mod = await import("../src/lib/reservation-cache.js?no-cache-5") + // No file yet: returns false. + expect(mod.clearCachedReservation()).toBe(false) + mod.writeCachedReservation({ + tenantId: "t-1", + slug: "docs-1", + liveUrl: "https://docs-1.helpbase.dev", + mcpPublicToken: "x", + userId: "u-1", + }) + expect(mod.clearCachedReservation()).toBe(true) + expect(mod.readCachedReservation()).toBe(null) + }) + + it("write overrides an existing file (user can re-login as a different account)", async () => { + const mod = await import("../src/lib/reservation-cache.js?no-cache-6") + mod.writeCachedReservation({ + tenantId: "t-1", + slug: "docs-first", + liveUrl: "https://docs-first.helpbase.dev", + mcpPublicToken: "x", + userId: "u-1", + }) + mod.writeCachedReservation({ + tenantId: "t-2", + slug: "docs-second", + liveUrl: "https://docs-second.helpbase.dev", + mcpPublicToken: "y", + userId: "u-2", + }) + const read = mod.readCachedReservation() + expect(read?.tenantId).toBe("t-2") + expect(read?.userId).toBe("u-2") + }) + + it("sets file mode to 0o600 so the bearer stays per-user readable", async () => { + // chmod isn't supported on all filesystems (FAT/SMB) so this test only + // runs on real POSIX platforms. Most developer machines + CI runners + // qualify. + if (process.platform === "win32") return + const mod = await import("../src/lib/reservation-cache.js?no-cache-7") + mod.writeCachedReservation({ + tenantId: "t-1", + slug: "docs-perm", + liveUrl: "https://docs-perm.helpbase.dev", + mcpPublicToken: "x", + userId: "u-1", + }) + const filePath = path.join(TMP_HOME, "reservation.json") + const stat = fs.statSync(filePath) + // Lower 9 bits are the file permissions. 0o600 = owner rw, nobody else. + expect(stat.mode & 0o777).toBe(0o600) + }) +})