Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,9 @@ out/
build
dist

# Auto-generated by Next.js — should not be tracked
apps/web/next-env.d.ts


# Debug
npm-debug.log*
Expand All @@ -48,3 +51,10 @@ apps/web/public/_helpbase-assets/
# Eval harness output — per-run artifact, not committed
packages/cli/eval/eval-report.json
packages/cli/eval/hosted-parity-report.json

# Local agent tooling (not shared)
.agents/
.claude/
skills-lock.json
DEVICE_FLOW_PROMPT.md
NEXT_SESSION_PROMPT.md
58 changes: 58 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,64 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

## [Unreleased]

## [helpbase 0.5.0] — 2026-04-17

### Added
- **`helpbase login` now uses a browser device-flow by default.** Run
`helpbase login` and the CLI opens your browser at
`helpbase.dev/device?user_code=ABCD-EFGH`, where you click Authorize
and the terminal picks up your bearer token. Under 10 seconds on the
fast path. No more email round-trip, no more paste-back dance. Built
on Better Auth's `deviceAuthorization` plugin (RFC 8628 device grant).
The old magic-link email flow is preserved behind
`helpbase login --email` as the fallback for CI and sandboxed envs.
- **Server-side tenant API** under `/api/v1/tenants/*`. `helpbase deploy`,
`helpbase link`, and `helpbase open` now call typed HTTP endpoints
instead of talking to Supabase directly. Ownership checks happen in
the server routes using Better Auth session verification.
- **Progressive polling hints** during device-flow wait: the spinner
surfaces targeted help at T+30s / T+90s / T+4min so the YC-founder
first-run doesn't hit a silent 3-minute staring contest.

### Changed
- **Auth backend migrated from Supabase Auth to Better Auth.** The CLI
and the hosted API now authenticate via Better Auth (bearer + magic-link
+ device-authorization plugins). The `~/.helpbase/auth.json` shape and
`HELPBASE_TOKEN` env contract are preserved — no action required for
existing installs. Emails now deliver via Resend.
- `helpbase login` auto-detects headless environments (Codespaces,
SSH sessions) and skips the browser spawn; prints the URL for manual
copy-paste instead. Override with `HELPBASE_LOGIN_NO_BROWSER=1` in
any environment.

### Fixed
- `~/.helpbase/auth.json` is now force-narrowed to mode `0600` on every
write (previously only on file creation, which left stale-permissioned
files loose on shared dev machines).

### Security
- `mcp_public_token` is no longer readable by the anon Supabase key.
The `tenants` table lost its anon SELECT grant; anon-facing reads go
through a new `tenants_public` view that projects only id/slug/name/
active/theme_config. Closes a pre-existing leak where the embedded
CLI anon key could enumerate every active tenant's MCP bearer.
- Resend API key is now required in production. Without it, the auth
config fails boot rather than silently printing magic-link URLs to
Vercel Runtime Logs (dev-mode console fallback is gated on
`NODE_ENV !== "production"`).

### Internal
- `packages/cli/src/lib/auth.ts` split into `auth.ts` (session core) +
`auth-device.ts` (device-flow state machine). 387 → 265 LOC on the
main file.
- 41 new tests across 4 new suites covering the auth surface:
`extractVerificationToken`, `deviceLogin`, `pollDeviceAuth`,
`consumeMagicLink`, `verifyLoginFromMagicLink`, `getCurrentSession`,
`withAuthAndQuota`, and the CLI `toAuthSession` factory.
- Removed the CLI's dependency on `@supabase/supabase-js`. The CLI now
talks to helpbase.dev over plain `fetch`. Lean install, one less
auth chain to maintain.

## [helpbase 0.4.1] — 2026-04-17

### Fixed
Expand Down
489 changes: 489 additions & 0 deletions DEVICE_FLOW_PLAN.md

Large diffs are not rendered by default.

33 changes: 33 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -432,6 +432,39 @@ Every package has its own `pnpm test`. Run the CLI locally with
`pnpm --filter helpbase dev`, then use `node packages/cli/dist/index.js`
from any directory to test against a scaffolded project.

### Local auth development

helpbase auth runs on [Better Auth](https://better-auth.com) against the
same Supabase Postgres that backs tenant content. To run auth locally:

1. **Copy the env template.** `cp apps/web/.env.example apps/web/.env.local`
and fill in the four auth values:
- `BETTER_AUTH_SECRET` — `openssl rand -base64 32`
- `BETTER_AUTH_URL` — `http://localhost:3000` (or whatever port Next picks)
- `DATABASE_URL` — Supabase dashboard → Project Settings → Database →
Connection string (Session / direct pooler). The migrations in
`scripts/migrate-auth-to-better-auth.sql` must already be applied
against this DB.
- `RESEND_API_KEY` — **leave blank**. Without it, magic-link URLs print
to the Next dev-server stderr so you can click them from your
terminal without signing up for a mail provider.

2. **Start the web app.** `pnpm -F web dev`.
3. **Verify auth is live.** `curl localhost:3000/api/auth/ok` → `{"ok":true}`.
4. **Point the CLI at your local server.** Prefix any CLI invocation with
both env overrides:
```bash
HELPBASE_BASE_URL=http://localhost:3000 \
HELPBASE_PROXY_URL=http://localhost:3000 \
node packages/cli/dist/index.js login
```
`HELPBASE_BASE_URL` is the auth endpoint root; `HELPBASE_PROXY_URL` is
the LLM/usage proxy root. In prod they're the same host; in dev you
set both to the local dev port.
5. **The magic link.** When you paste your email, watch the `pnpm -F web
dev` terminal — the verification URL shows up between `─── DEV MAGIC
LINK ───` fences. Paste the URL back into the CLI prompt to finish.

## Testing the CLI against a real project

```bash
Expand Down
44 changes: 44 additions & 0 deletions apps/web/.env.example
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
# -----------------------------------------------------------------------------
# helpbase.dev (apps/web) environment variables
# Copy to .env.local for local development. Real values go in Vercel env.
# -----------------------------------------------------------------------------

# ── Better Auth ──────────────────────────────────────────────────────────────
# Encryption secret for session cookies. Min 32 chars.
# generate: openssl rand -base64 32
BETTER_AUTH_SECRET=

# Base URL of the running web app. In dev, http://localhost:3000.
BETTER_AUTH_URL=http://localhost:3000

# ── Database ─────────────────────────────────────────────────────────────────
# Postgres connection string for the Better Auth tables (user/session/account/
# verification). Uses the same Supabase project as NEXT_PUBLIC_SUPABASE_URL.
# Supabase dashboard → Project Settings → Database → Connection string
# Use the "direct" (session) connection, not the pooler — Better Auth's
# built-in migrations need session-level features that PgBouncer transaction
# mode doesn't support. For runtime, the pooler is fine; for migrations, use
# direct.
DATABASE_URL=

# ── Email (Resend) ───────────────────────────────────────────────────────────
# Resend API key for transactional emails (magic-link sign-in).
# get at resend.com/api-keys
# If unset in local dev, magic links are printed to the server console (stderr)
# so you can click them from your terminal without signing up for Resend.
RESEND_API_KEY=

# From-address for sign-in emails. Requires the domain to be verified in Resend.
RESEND_FROM_EMAIL="helpbase <login@auth.helpbase.dev>"

# ── Supabase (existing — used for tenant content, NOT auth) ──────────────────
NEXT_PUBLIC_SUPABASE_URL=
NEXT_PUBLIC_SUPABASE_ANON_KEY=
SUPABASE_SERVICE_ROLE_KEY=

# ── Tenant routing ───────────────────────────────────────────────────────────
NEXT_PUBLIC_ROOT_DOMAIN=helpbase.dev

# ── Vercel KV (rate limiting) ────────────────────────────────────────────────
KV_REST_API_URL=
KV_REST_API_TOKEN=
52 changes: 52 additions & 0 deletions apps/web/app/(main)/errors/[code]/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -362,6 +362,58 @@ const ERRORS: Record<string, ErrorDoc> = {
"Check status.anthropic.com / openai.com if the problem persists.",
],
},

// ── Device-authorization flow (RFC 8628) ──────────────────────────────
"e-auth-cancelled": {
code: "E_AUTH_CANCELLED",
title: "Login cancelled",
summary: "You aborted `helpbase login` before the browser finished authorizing.",
causes: [
"You pressed Ctrl-C during the spinner.",
"A programmatic signal interrupted the CLI's polling loop.",
],
fixes: [
"Run `helpbase login` again when you're ready to sign in.",
"If you meant to use the email fallback, run `helpbase login --email`.",
],
},
"e-device-denied": {
code: "E_DEVICE_DENIED",
title: "Authorization was cancelled in the browser",
summary:
"You clicked Cancel (or closed the tab) on the /device approval page before finishing sign-in.",
causes: [
"The browser tab was closed before Authorize.",
"You clicked Cancel on purpose.",
"A different browser session received the URL — possible phishing — and rejected it.",
],
fixes: [
"Run `helpbase login` again if that wasn't you.",
"If you didn't start this login, no action is needed; the code is now void.",
],
},
"e-device-expired": {
code: "E_DEVICE_EXPIRED",
title: "Device code expired",
summary:
"The browser didn't approve the CLI within the 10-minute window, so the one-time code is now void.",
causes: [
"You walked away or got distracted mid-flow.",
"Network delays pushed polling past the expiry.",
"The auth server rejected the code early (rare).",
],
fixes: [
"Run `helpbase login` again to get a fresh code.",
"If you're on a slow network, `helpbase login --email` is more forgiving — the email link lives for 10 minutes after you click it.",
],
},
// E_DEVICE_NETWORK, E_DEVICE_NO_BROWSER, E_LOGIN_RESEND_DOWN,
// E_LOGIN_STALE_TOKEN were drafted during the 2026-04-17 device-flow
// plan but the CLI never throws them — network errors surface as the
// generic login-failed cancel, headless envs are a behavior (URL
// printed, polling continues) rather than an error, and stale tokens
// are cleared silently with a fresh login prompt. Entries removed to
// keep /errors/<code> pages in sync with what the CLI actually emits.
}

export function generateStaticParams() {
Expand Down
15 changes: 15 additions & 0 deletions apps/web/app/api/auth/[...all]/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import { toNextJsHandler } from "better-auth/next-js"
import { auth } from "@/lib/auth"

// Better Auth's Next.js adapter. Handles every /api/auth/* route:
// GET /api/auth/ok → health check
// POST /api/auth/sign-in/magic-link → triggers sendMagicLink
// GET /api/auth/verify-magic-link → consumes the magic token, sets session cookie
// GET /api/auth/session → reads current session (cookie or Bearer)
// POST /api/auth/sign-out → clears session
// ... plus every plugin-mounted route (bearer, magicLink, later deviceAuthorization)
//
// All auth state lives in the database (public.user / public.session / public.account
// / public.verification). No cookies-in-proxy or token-in-proxy logic — plugins own it.

export const { GET, POST } = toNextJsHandler(auth.handler)
57 changes: 21 additions & 36 deletions apps/web/app/api/revalidate/route.ts
Original file line number Diff line number Diff line change
@@ -1,39 +1,33 @@
import { NextResponse, type NextRequest } from "next/server"
import { revalidatePath } from "next/cache"
import { createClient } from "@supabase/supabase-js"
import type { Database } from "@/types/supabase"
import { auth } from "@/lib/auth"
import { getServiceRoleClient } from "@/lib/supabase-admin"

/**
* POST /api/revalidate
* body: { tenant_id: string }
* auth: Bearer <supabase-session-access-token> (from the CLI's authed session)
* auth: Bearer <Better Auth session token> (from the CLI's authed session)
*
* Called by `helpbase deploy` after a successful RPC to flush the ISR cache
* for the tenant's pages. Without this, pages served under
* `{slug}.helpbase.dev/...` (ISR, 1h TTL) keep serving stale content for up
* to an hour after the deploy — which breaks trust on the first deploy.
*
* Security: the caller's access-token must belong to the tenant owner.
* We use the anon Supabase client with the user's JWT to read `tenants`
* under RLS — the `tenants_select_public` policy + the owner_id check in
* the query form a belt-and-suspenders filter. Service role is NOT used
* here; only the rightful owner should be able to revalidate their tenant.
* Security: the caller's bearer must resolve to a Better Auth session whose
* userId matches tenants.owner_id. Tenant lookup goes through the service-
* role client because the 2026-04-17 migration dropped RLS owner-policies;
* the owner match is enforced in application code. Mirrors the pattern in
* /api/v1/llm/_shared.ts.
*/

const SUPABASE_URL = process.env.NEXT_PUBLIC_SUPABASE_URL ?? ""
const SUPABASE_ANON_KEY = process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY ?? ""

export async function POST(req: NextRequest) {
if (!SUPABASE_URL || !SUPABASE_ANON_KEY) {
return NextResponse.json({ error: "Supabase not configured" }, { status: 500 })
}

// Extract bearer token (Supabase session access token from the CLI).
const authHeader = req.headers.get("authorization") ?? ""
const match = /^Bearer\s+(.+)$/i.exec(authHeader.trim())
const accessToken = match?.[1]
if (!accessToken) {
return NextResponse.json({ error: "missing bearer token" }, { status: 401 })
// Better Auth bearer → session. Rejects cookie-only or missing headers.
const session = await auth.api.getSession({ headers: req.headers })
if (!session?.user?.id) {
return NextResponse.json(
{ error: "missing, malformed, or expired session token" },
{ status: 401 },
)
}

// Parse body.
Expand All @@ -48,28 +42,19 @@ export async function POST(req: NextRequest) {
return NextResponse.json({ error: "tenant_id is required" }, { status: 400 })
}

// Resolve tenant + verify ownership via the caller's JWT.
// createClient + Authorization header = queries run as that user under RLS.
const client = createClient<Database>(SUPABASE_URL, SUPABASE_ANON_KEY, {
global: { headers: { Authorization: `Bearer ${accessToken}` } },
})

const { data: userData } = await client.auth.getUser(accessToken)
const userId = userData.user?.id
if (!userId) {
return NextResponse.json({ error: "invalid session" }, { status: 401 })
}

const { data: tenant, error } = await client
// Service-role lookup — RLS owner-policies were dropped in the Better Auth
// migration, so ownership is enforced in code below.
const admin = getServiceRoleClient()
const { data: tenant, error } = await admin
.from("tenants")
.select("slug, owner_id")
.eq("id", tenantId)
.single()
.maybeSingle()

if (error || !tenant) {
return NextResponse.json({ error: "tenant not found" }, { status: 404 })
}
if (tenant.owner_id !== userId) {
if (tenant.owner_id !== session.user.id) {
return NextResponse.json({ error: "not tenant owner" }, { status: 403 })
}

Expand Down
23 changes: 10 additions & 13 deletions apps/web/app/api/v1/llm/_shared.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
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"
import { getServiceRoleClient } from "@/lib/supabase-admin"
import { auth } from "@/lib/auth"

/**
* Shared helpers for /api/v1/llm/generate-object and /generate-text.
Expand Down Expand Up @@ -36,22 +37,18 @@ export interface AuthedContext {
export async function withAuthAndQuota(
req: Request,
): Promise<AuthedContext | NextResponse> {
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.")
// Better Auth's bearer plugin reads Authorization: Bearer <token> and
// resolves it to a session via public.session.token. Same bearer shape
// as pre-migration (Supabase JWTs); callers see no API change.
const session = await auth.api.getSession({ headers: req.headers })
if (!session?.user?.id) {
return wireError(401, "auth_required", "Missing, malformed, 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_user_tokens_today", { p_user_id: session.user.id }),
client.rpc("get_global_tokens_today"),
])

Expand Down Expand Up @@ -90,7 +87,7 @@ export async function withAuthAndQuota(
const maxOutputTokens = Math.min(PER_CALL_CEILING, remaining)

return {
userId: user.userId,
userId: session.user.id,
usedToday,
resetAtIso,
maxOutputTokens,
Expand Down
Loading
Loading