Repository navigation
feat: migrate auth to Better Auth + ship device-flow login (helpbase 0.5.0) - #3
Conversation
Replace the Supabase Auth chain with Better Auth (bearer + magic-link + deviceAuthorization plugins) end-to-end across apps/web and packages/cli. Device flow is now the default `helpbase login`: the CLI opens the browser at helpbase.dev/device?user_code=..., the user clicks Authorize, and the CLI picks up the bearer via /api/auth/device/token. Under 10 seconds on the warm path. Progressive hints at T+30s / T+90s / T+4min keep the YC-founder first-run oriented. Magic-link paste flow preserved behind `helpbase login --email` for CI and sandboxed envs. Tenant CRUD moves to a dedicated server-side API. `helpbase deploy`, `link`, `open`, and `whoami` now call `/api/v1/tenants/*` endpoints instead of speaking Supabase directly. Ownership checks live in the route handlers (auth.api.getSession + service-role DB writes), since the Better Auth migration dropped the RLS `*_own` policies that `auth.uid()` used to enforce. Security fixes folded in via /review: - mcp_public_token leak closed (tenants_public view + anon grants revoked on the base tenants table). - Resend API key now required in production; dev-mode console fallback is gated on NODE_ENV != production so a misconfigured prod deploy fails boot rather than printing live magic-link URLs to Vercel logs. - ~/.helpbase/auth.json force-narrowed to 0600 on every write. - Error response bodies redacted before splicing into CLI stderr. The DB migration (scripts/migrate-auth-to-better-auth.sql) copies auth.users -> public.user preserving UUIDs as text IDs, re-points the tenants.owner_id and llm_usage_events.user_id FKs, and drops the auth.uid()-based RLS policies that became inert under Better Auth. Applied to prod Supabase via MCP as part of this work. 41 new tests across 4 suites cover extractVerificationToken, deviceLogin, pollDeviceAuth, consumeMagicLink, verifyLoginFromMagicLink, getCurrentSession, withAuthAndQuota, and the CLI toAuthSession factory. auth.ts split into auth.ts + auth-device.ts for cohesion (387 -> 265 LOC on the main file). Known follow-ups: - OAuth providers (Google/GitHub) still pending — requires OAuth apps in the respective consoles. - Resend domain verification (SPF/DKIM on helpbase.dev) needed before prod can send magic-link email. - AuthorizeDeviceClient React component lacks unit tests (needs jsdom + @testing-library setup in apps/web/vitest.config). Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
|
The latest updates on your projects. Learn more about Vercel for GitHub.
|
|
Warning Rate limit exceeded
Your organization is not enrolled in usage-based pricing. Contact your admin to enable usage-based pricing to continue reviews beyond the rate limit, or try again in 3 minutes and 4 seconds. ⌛ How to resolve this issue?After the wait time has elapsed, a review can be triggered using the We recommend that you space out your commits to avoid hitting the rate limit. 🚦 How do rate limits work?CodeRabbit enforces hourly rate limits for each developer per organization. Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout. Please see our FAQ for further information. ℹ️ Review info⚙️ Run configurationConfiguration used: defaults Review profile: CHILL Plan: Pro Run ID: ⛔ Files ignored due to path filters (1)
📒 Files selected for processing (23)
📝 WalkthroughWalkthroughThis pull request migrates authentication from Supabase Auth to Better Auth across the helpbase platform. The web app now uses Better Auth for session management with RFC 8628 device authorization flow support. The CLI switches from direct Supabase access to calling hosted Changes
Sequence Diagram(s)sequenceDiagram
actor User as User / CLI
participant CLI as CLI
participant Web as Web App<br/>(/device)
participant Auth as Better Auth<br/>(/api/auth/*)
participant Session as Session Store<br/>(Database)
participant Email as Resend<br/>Email Service
User->>CLI: helpbase login
CLI->>Auth: POST /device/code
Auth->>Session: Create device code record
Auth-->>CLI: {deviceCode, userCode, verificationUri, ...}
CLI->>CLI: Open browser to /device?user_code=...
CLI->>CLI: Begin polling /device/token
User->>Web: Visit /device?user_code=...
Web->>Auth: GET /get-session (no bearer)
Auth-->>Web: {user: null} (unsigned-in)
Web->>User: Show email input form
User->>Web: Enter email & submit
Web->>Auth: POST /sign-in/magic-link {email, callbackURL: /}
Auth->>Email: Send magic-link URL
Email-->>User: Email with link
Web->>User: Show "Check your email"
User->>User: Click link in email
User->>Auth: GET /magic-link/verify?token=...
Auth->>Session: Mark token verified, create bearer
Auth-->>User: 302 redirect with Set-Auth-Token: <bearer>
User->>Web: Auto-redirect to /device
Web->>Auth: GET /get-session (with bearer)
Auth->>Session: Retrieve session
Auth-->>Web: {user, session}
Web->>User: Show approval screen
User->>Web: Click "Approve"
Web->>Auth: POST /device/approve {userCode}
Auth->>Session: Link device code to user
Auth-->>Web: {success: true}
Web->>User: Show "Approved!"
CLI->>Auth: (polling) POST /device/token {deviceCode}
Auth->>Session: Check if device linked to user
Auth-->>CLI: {accessToken}
CLI->>Auth: GET /get-session {Authorization: Bearer ...}
Auth-->>CLI: {user, session}
CLI->>CLI: Store session to ~/.helpbase/auth.json
CLI->>User: "Successfully logged in!"
sequenceDiagram
participant CLI as CLI
participant Web as Web App<br/>Tenant API
participant Supabase as Supabase<br/>(admin role)
participant Cache as ISR Cache
User->>CLI: helpbase deploy --slug myhelp
CLI->>Web: GET /api/v1/tenants/mine {Bearer token}
Web->>Web: Validate session
Supabase->>Supabase: Query tenants {owner_id: userId, active: true}
Web-->>CLI: [{id, slug, name}, ...]
CLI->>Web: POST /api/v1/tenants/{id}/deploy {categories, articles, chunks}
Web->>Web: requireOwnedTenant(id) — verify session user owns tenant
Supabase->>Supabase: RPC deploy_tenant(id, categories, articles, chunks)
Supabase-->>Web: {deploy_id, ...}
Web->>Supabase: Query article/chunk counts
Supabase-->>Web: counts
Web->>Cache: Trigger ISR revalidatePath(/t/{slug})
Web-->>CLI: {deploy_id, article_count, chunk_count, slug}
CLI->>User: Deployment complete!
Estimated code review effort🎯 5 (Critical) | ⏱️ ~95 minutes Poem
🚥 Pre-merge checks | ✅ 2 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (2 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
The DATABASE_URL + RESEND_API_KEY guards in apps/web/lib/auth.ts threw at module load whenever NODE_ENV=production. That fires during `next build`'s static page-data collection step, not just at runtime — so CI without prod secrets failed to build, and any local `pnpm build` without a .env.local with those vars blew up before ever serving. Check NEXT_PHASE=phase-production-build to detect the build phase and skip the throw there. Missing DATABASE_URL at build time just logs a warning; the throw still fires on the first real request if the var wasn't set, which is the correct failure mode (runtime 500 on /api/auth/* routes while the rest of the site still serves). Fixes PR #3 CI break. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
There was a problem hiding this comment.
Actionable comments posted: 7
Note
Due to the large number of review comments, Critical, Major severity comments were prioritized as inline comments.
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (2)
apps/web/lib/tenant-content.ts (1)
5-23:⚠️ Potential issue | 🟡 MinorType cast obscures nullability of
tenants_publicfields; add explicit type to clarify.The
tenants_publicview columns are all nullable (id: string | null,slug: string | null, etc. per supabase.ts), yet the current castas Tenant | nullclaims fields are non-null. This type dishonesty invites future unsafe field access. All current callers properly guard with null-checks before dereferencing, but the type system doesn't reflect the actual schema.Add an explicit
PublicTenant = Tables<"tenants_public">type and return it fromgetTenantto make nullability explicit for downstream callers.🛠️ Proposed fix
export type Tenant = Tables<"tenants"> +export type PublicTenant = Tables<"tenants_public"> export type TenantArticle = Tables<"tenant_articles"> export type TenantCategory = Tables<"tenant_categories"> export const getTenant = cache(async (slug: string): Promise<PublicTenant | null> => { const { data } = await supabase .from("tenants_public") .select("*") .eq("slug", slug) .maybeSingle() - return data as Tenant | null + return data })🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@apps/web/lib/tenant-content.ts` around lines 5 - 23, The current getTenant function incorrectly casts the result to Tenant | null which hides nullable columns from the tenants_public view; define a new type alias PublicTenant = Tables<"tenants_public"> and change the getTenant signature and return to Promise<PublicTenant | null>, and replace the cast (as Tenant | null) with the explicit PublicTenant | null return so callers see the true nullable fields; update any imports/uses that referenced Tenant for this function to use PublicTenant where appropriate.packages/cli/src/commands/deploy.ts (1)
541-594:⚠️ Potential issue | 🔴 CriticalBroken auth fallback —
verifyLoginCodealways throws in the new auth module.This
ensureAuthenticatedpath still collects a 6-digit code and callsverifyLoginCode(email, code), butpackages/cli/src/lib/auth.tsnow makesverifyLoginCodeunconditionally throwE_AUTH_VERIFY_OTP("6-digit code login is no longer supported"). A user who runshelpbase deploywithout first runninghelpbase loginwill:
- Receive the magic-link URL email from Resend
- Be prompted for a non-existent 6-digit code
- Hit the always-throw stub, see a confusing "not supported" error, and be unable to deploy
Either delegate to the new flow (run
deviceLogin()fromauth-device.ts, or fall back toverifyLoginFromMagicLinkwith a URL-paste prompt), or remove this inline login entirely and printRun \helpbase login` first. Same concern applies to any other commands (link,open,whoami) that call an equivalentensureAuthenticated`.🐛 Minimal fix: delegate to device-flow
- note("First time? Let's get you set up.", "Authentication") - - const email = await text({ - message: "Enter your email:", - placeholder: "you@company.com", - validate: (v) => { - if (!v.includes("@")) return "Please enter a valid email" - return undefined - }, - }) - if (isCancel(email)) { - cancel("Cancelled.") - process.exit(0) - } - - const s = spinner() - s.start("Sending magic link...") - try { - await sendLoginCode(email as string) - s.stop("Magic link sent!") - } catch (err) { - s.stop("Failed to send magic link") - if (err instanceof HelpbaseError) { - cancel(formatError(err).trimEnd()) - } else { - cancel(`Authentication error: ${String(err)}`) - } - process.exit(1) - } - - const code = await text({ - message: "Enter the 6-digit code from your email:", - placeholder: "123456", - validate: (v) => { - if (!/^\d{6}$/.test(v)) return "Enter the 6-digit code" - return undefined - }, - }) - if (isCancel(code)) { - cancel("Cancelled.") - process.exit(0) - } - - try { - const session = await verifyLoginCode(email as string, code as string) - note(`Authenticated as ${pc.cyan(session.email)}`, "Success") - return session - } catch (err) { - if (err instanceof HelpbaseError) { - cancel(formatError(err).trimEnd()) - } else { - cancel(`Verification failed: ${String(err)}`) - } - process.exit(1) - } + cancel(`You're not signed in. Run ${pc.cyan("helpbase login")} first, then re-run this command.`) + process.exit(1)🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/cli/src/commands/deploy.ts` around lines 541 - 594, The current ensureAuthenticated flow collects a 6-digit code and calls verifyLoginCode(email, code) but verifyLoginCode now always throws; replace that broken OTP path by delegating to the device flow: after sendLoginCode(email) succeeds, call deviceLogin() (from auth-device.ts) and return its session (or alternatively prompt for a pasted magic-link URL and call verifyLoginFromMagicLink(url)); remove the code prompt and the verifyLoginCode call and preserve the same error handling pattern (HelpbaseError branch and process.exit) using the deviceLogin/verifyLoginFromMagicLink call sites so other commands (link, open, whoami) using ensureAuthenticated will use the supported auth flow.
🟡 Minor comments (14)
scripts/migrate-auth-to-better-auth.sql-39-47 (1)
39-47:⚠️ Potential issue | 🟡 MinorAll current reads of tenant_chunks/tenant_deploys/tenant_mcp_queries use service role via server endpoints.
The policies were dropped without recreation (confirmed), leaving RLS logically enabled but without any policies. A grep for direct client-side reads found none—the codebase routes all reads through API routes using the admin client. The migration comment explicitly notes this is intentional ("writes flow through server-side code using the service role").
However, the risk remains valid: if future code adds a direct client query, it would silently return empty results. Consider documenting this constraint or adding table-level security comments to prevent accidental client-side usage.
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@scripts/migrate-auth-to-better-auth.sql` around lines 39 - 47, Add explicit database-level comments explaining that RLS was intentionally left with no policies for tenant_chunks, tenant_deploys, and tenant_mcp_queries and that all reads must go through server endpoints using the service role; update the migration (and/or add a follow-up migration) to create table comments on tenant_chunks, tenant_deploys, and tenant_mcp_queries stating this constraint and warning that direct client-side queries will return empty results, so future contributors should route reads via the admin/service role endpoints or restore RLS policies if needed.packages/cli/src/commands/whoami.ts-54-57 (1)
54-57:⚠️ Potential issue | 🟡 Minor
listMyTenants()[0]is non-deterministic when the user owns multiple tenants.Per
packages/cli/src/lib/tenants-client.ts:70-78, the endpoint returnsTenantSummary[]with no documented ordering guarantee, sowhoamimay display a different tenant than the one linked locally. Consider preferringreadProjectConfig()first (likeopen.tsdoes) and only falling back totenants[0], and/or guaranteeing a stable server-side ordering (e.g., bycreated_at). Same issue also applies topackages/cli/src/commands/open.tsLines 54-55 as a resolver fallback, which is more user-visible.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/cli/src/commands/whoami.ts` around lines 54 - 57, The current whoami.ts (and similarly open.ts) uses the first element of listMyTenants(session) which is non-deterministic; change the resolver to prefer the local project config first by calling readProjectConfig() and using its linked tenant slug to select the matching entry from listMyTenants(session), and only if no local config or no match exists fall back to a deterministic choice (e.g., sort tenants by a stable field such as created_at or explicitly pick by slug) before using tenants[0]; update the logic in functions handling tenant resolution (referencing listMyTenants, readProjectConfig, and the tenant selection code in whoami.ts and open.ts) to implement this fallback and deterministic selection.apps/web/.env.example-32-32 (1)
32-32:⚠️ Potential issue | 🟡 MinorQuote
RESEND_FROM_EMAIL— angle brackets break most dotenv parsers.
helpbase <login@helpbase.dev>contains<and>which are shell redirection metacharacters and are interpreted inconsistently across dotenv parsers (Next.js/dotenv typically treats them literally, but shells sourcing this file will choke, and some tools strip whitespace around them). Quote the value to match the relevant_code_snippets default inapps/web/lib/auth.ts:10and to appeasedotenv-linter.🔧 Proposed fix
-RESEND_FROM_EMAIL=helpbase <login@helpbase.dev> +RESEND_FROM_EMAIL="helpbase <login@helpbase.dev>"🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@apps/web/.env.example` at line 32, The RESEND_FROM_EMAIL value in apps/web/.env.example contains angle brackets which break dotenv parsers; update that entry to quote the entire value (e.g., wrap helpbase <login@helpbase.dev> in double quotes) so parsers and dotenv-linter accept it, and ensure it matches the default format expected by apps/web/lib/auth.ts (the default at line referenced).apps/web/app/api/v1/tenants/[id]/rotate-mcp-token/route.ts-30-37 (1)
30-37:⚠️ Potential issue | 🟡 MinorConfirm the UPDATE actually hit a row before returning the new token.
If the tenant row disappears between
requireOwnedTenantand the update (soft-delete, admin action, race withDELETE), Supabase returns{ error: null }with zero rows affected — the handler then responds200 { mcp_public_token: newToken }. The CLI (packages/cli/src/lib/tenants-client.ts:156-171) will happily hand that token to the MCP client, which will then 401 forever because the DB has a different (or no) token.Return the updated row via
.select("id").maybeSingle()and 404 when nothing matched.🔧 Proposed fix
- const { error } = await admin + const { data: updated, error } = await admin .from("tenants") .update({ mcp_public_token: newToken }) .eq("id", tenant.id) + .select("id") + .maybeSingle() if (error) { return jsonError(503, "rotate_failed", error.message) } + if (!updated) { + return jsonError(404, "tenant_not_found", "Tenant disappeared before rotation completed.") + } return NextResponse.json({ mcp_public_token: newToken })🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@apps/web/app/api/v1/tenants/`[id]/rotate-mcp-token/route.ts around lines 30 - 37, The update currently ignores whether any row was affected; change the admin.from("tenants").update({ mcp_public_token: newToken }) call to include .select("id").maybeSingle() and check the returned row (or data) rather than only error; if the result is null/undefined (no row matched) return jsonError(404, "not_found", "tenant not found") (or similar) instead of returning NextResponse.json({ mcp_public_token: newToken }); keep the existing error handling for non-null error objects and only return the new token when the updated row is actually returned.apps/web/app/api/v1/tenants/by-slug/[slug]/route.ts-22-34 (1)
22-34:⚠️ Potential issue | 🟡 MinorAvailability probe may lie when an inactive tenant holds the slug.
The
.eq("active", true)filter means a soft-deleted/deactivated tenant holdingslugcauses this endpoint to return{ available: true }, but the subsequentPOST /api/v1/tenantswill fail with aUNIQUE (slug)constraint violation because the unique index ontenants.slugdoes not have aWHERE activeclause. The CLI atpackages/cli/src/commands/deploy.ts:166-169trustsavailableand proceeds with creation, so the user will hit a confusing 409 downstream.Remove
.eq("active", true)so availability matches the uniqueness contract.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@apps/web/app/api/v1/tenants/by-slug/`[slug]/route.ts around lines 22 - 34, The availability check currently filters out inactive tenants by using .eq("active", true"), which can lie compared to the DB unique index; update the query in the getServiceRoleClient admin call that selects from the tenants table (the block using .from("tenants").select(...).eq("slug", slug)) to remove the .eq("active", true) clause so the lookup includes inactive/soft-deleted rows and returns available: false when any tenant row exists for that slug.apps/web/app/api/v1/tenants/route.ts-59-67 (1)
59-67:⚠️ Potential issue | 🟡 MinorPrefer the Postgres error code over regex-matching the message; avoid leaking raw DB errors.
/duplicate|unique/ionerror.messageis locale/driver-dependent and will silently stop working if PostgREST changes wording. Useerror.code === '23505'(unique_violation). Also,msgflowing straight into the 503 response reintroduces the error-body leak the CHANGELOG lists as fixed.🛡️ Proposed fix
if (error) { - const msg = error.message ?? "" - if (/duplicate|unique/i.test(msg)) { + // 23505 = unique_violation + if ((error as { code?: string }).code === "23505") { return jsonError(409, "slug_taken", `"${slug}" is already taken.`) } - return jsonError(503, "internal_error", msg) + console.error("[tenants.create] supabase error", { slug, error }) + return jsonError(503, "internal_error", "Could not create tenant.") }🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@apps/web/app/api/v1/tenants/route.ts` around lines 59 - 67, Replace the fragile regex and raw DB error leak: in the error handling branch around the insert (the `error` variable and `msg` usage), check Postgres unique-violation by testing `error.code === '23505'` and return the 409 via `jsonError(409, "slug_taken", \`"${slug}" is already taken.\`) for that case; for all other errors do NOT return `msg` (the raw DB error) but return a generic 503 `jsonError(503, "internal_error", "Internal server error")` (or another non-sensitive message) instead—update the logic where `msg` is computed and where `jsonError` is called so no database error text is sent to clients.apps/web/app/api/v1/tenants/[id]/route.ts-48-49 (1)
48-49:⚠️ Potential issue | 🟡 MinorAvoid echoing raw DB error messages to the client.
error.messagefrom PostgREST can leak constraint names, column names, or internal hints (the CHANGELOG explicitly calls out "redaction of error bodies" as a security fix — this path regresses that). Log server-side; return a generic message.🛡️ Proposed fix
const { error } = await admin.from("tenants").delete().eq("id", tenant.id) - if (error) return jsonError(503, "delete_failed", error.message) + if (error) { + console.error("[tenants.delete] supabase error", { tenantId: tenant.id, error }) + return jsonError(503, "delete_failed", "Could not delete tenant.") + } return NextResponse.json({ deleted: true, slug: tenant.slug })🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@apps/web/app/api/v1/tenants/`[id]/route.ts around lines 48 - 49, The handler currently returns raw DB error.message to the client after calling admin.from("tenants").delete().eq("id", tenant.id"); instead, log the full error server-side (use your logger or console.error) and call jsonError with a generic message (e.g., jsonError(503, "delete_failed") or include minimal non-sensitive detail), removing error.message from the response; update the code around the admin.from(...).delete() call and jsonError invocation to perform server-side logging and return the redacted/generic error to the client.apps/web/app/api/v1/tenants/route.ts-15-15 (1)
15-15:⚠️ Potential issue | 🟡 MinorSlug regex permits leading/trailing hyphens — invalid as a subdomain.
^[a-z0-9-]+$accepts-foo,foo-,---,-. The CLI (packages/cli/src/commands/link.ts:18) uses^[a-z0-9][a-z0-9-]*[a-z0-9]$, which is the correct DNS label shape. A request going directly to the API (bypassing the CLI validator) can create a tenant with a slug that downstream DNS/routing won't serve cleanly.🔧 Proposed fix — align with CLI + add min-length safety for the 2-char edge
-const SLUG_REGEX = /^[a-z0-9-]+$/ +// DNS-label shape: no leading/trailing hyphen, matches packages/cli/src/commands/link.ts. +const SLUG_REGEX = /^[a-z0-9]([a-z0-9-]*[a-z0-9])?$/🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@apps/web/app/api/v1/tenants/route.ts` at line 15, Replace the permissive SLUG_REGEX constant (currently /^[a-z0-9-]+$/) with a DNS-label-safe pattern used by the CLI: require alphanumeric start and end and enforce a minimum length of 2; e.g. update SLUG_REGEX to something like /(?=.{2,}$)^[a-z0-9][a-z0-9-]*[a-z0-9]$/ and ensure any validation that uses SLUG_REGEX (the SLUG_REGEX constant in route.ts and the tenant creation/validation flow) uses this new pattern so leading/trailing hyphens are rejected and very short edge-case slugs are prevented.packages/cli/src/commands/login.ts-68-79 (1)
68-79:⚠️ Potential issue | 🟡 MinorHardcoded 240s threshold assumes a 5-minute device-code lifetime.
The "1 minute until this code expires" message at line 71 is based on a hardcoded 240s threshold, which assumes the server-provided
expires_inis always 300s (Better Auth's default). If the server changes this value, the message becomes incorrect.While
info.expires_inis available in theonStartcallback, theonProgresscallback (line 68) only receiveselapsedMsand has no access to the actual expiry duration. To fix this, either captureexpires_ininonStartand reference it in theonProgressclosure, or suppress the timing claim if it isn't derived from the actual server value.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/cli/src/commands/login.ts` around lines 68 - 79, The onProgress callback uses a hardcoded 240_000ms threshold to claim "1 minute until this code expires", which assumes a 300s expires_in; capture the real expiry from the onStart callback (info.expires_in) into the surrounding scope and use that value to compute remaining time inside onProgress (compare elapsedMs against (expires_in * 1000) - 60_000) or otherwise avoid emitting a specific "1 minute" message when expires_in is unavailable; update the closure that contains onStart/onProgress so onProgress can reference the stored expires_in and use s.message only when the computed remaining time is accurate.packages/cli/src/commands/link.ts-149-164 (1)
149-164:⚠️ Potential issue | 🟡 Minor
link --slugdoesn't verify ownership — links happily to another user's tenant.
checkSlugAvailabilityhits the public/by-slug/:slugendpoint with no authentication, soavailable === falseonly proves the slug is taken — not that this user owns it. The CLI writes.helpbase/project.jsonanyway, and the user only discovers the mistake whenhelpbase deploy/open/whoami403s later.Confirm ownership by calling
GET /api/v1/tenants/:idwith the session bearer before persisting.getTenantreturnsnullon 403 (access denied), so check for that instead of catching an exception.🔧 Proposed fix
-async function linkBySlug(slug: string): Promise<void> { +async function linkBySlug(slug: string, session: AuthSession): Promise<void> { const availability = await checkSlugAvailability(slug) if (availability.available) { cancel( `Tenant "${slug}" not found.\n` + ` Run ${pc.cyan("helpbase link")} without --slug to see your tenants, ` + `or ${pc.cyan(`helpbase deploy --slug ${slug}`)} to create one.`, ) process.exit(1) } if (!availability.id) { cancel("Availability check did not return an id.") process.exit(1) } + // Confirm ownership before persisting the binding — by-slug is public + // and only proves the slug is taken, not that the caller owns it. + const tenant = await getTenant(session, availability.id) + if (!tenant) { + cancel(`You don't own "${slug}.helpbase.dev". Pick another subdomain.`) + process.exit(1) + } writeProjectConfig({ tenantId: availability.id, slug: availability.slug ?? slug }) }Caller update at line 63:
- await linkBySlug(opts.slug) + await linkBySlug(opts.slug, session)🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/cli/src/commands/link.ts` around lines 149 - 164, linkBySlug currently trusts checkSlugAvailability (public /by-slug) and writes project config without verifying the current user owns that tenant; instead, after obtaining availability.id call getTenant(id) using the authenticated session (the GET /api/v1/tenants/:id path) and validate the result is non-null (getTenant returns null on 403) before calling writeProjectConfig; if getTenant returns null, call cancel with a helpful message and exit rather than persisting the tenant id/slug.apps/web/app/device/AuthorizeDeviceClient.tsx-240-253 (1)
240-253:⚠️ Potential issue | 🟡 Minor"Try again" strands signed-in users in the email form.
Setting
phasetosigned-outdirectly doesn't re-run the derivation effect (its deps[sessionPending, session, userCode]haven't changed). A user who was already signed in, hit an error duringdevice.approve, and clicked "Try again" will see the email-entry form even thoughsession.useris still valid — refreshing is their only way out.Route the retry back through the same derivation logic the effect uses by checking if the user is still signed in:
🐛 Proposed fix
- <button - type="button" - onClick={() => setPhase({ kind: "signed-out" })} - className="text-sm text-neutral-600 underline dark:text-neutral-400" - > - Try again - </button> + <button + type="button" + onClick={() => { + if (session?.user && userCode) { + setPhase({ kind: "signed-in", email: session.user.email, userCode }) + } else { + setPhase({ kind: "signed-out" }) + } + }} + className="text-sm text-neutral-600 underline dark:text-neutral-400" + > + Try again + </button>🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@apps/web/app/device/AuthorizeDeviceClient.tsx` around lines 240 - 253, The "Try again" button currently forces phase to { kind: "signed-out" } which won't retrigger the derivation effect (deps: [sessionPending, session, userCode]) and leaves already-signed-in users stuck; change the onClick handler to set phase based on the current session state (e.g. call setPhase(session?.user ? { kind: "signed-in" } : { kind: "signed-out" })) so the retry follows the same derivation logic used in the effect (referencing setPhase, phase kinds "signed-in"/"signed-out", and the effect deps [sessionPending, session, userCode]).packages/cli/src/commands/deploy.ts-111-114 (1)
111-114:⚠️ Potential issue | 🟡 MinorNon-deterministic tenant selection when user owns >1 tenant.
tenants[0]depends on whatever ordering the/api/v1/tenants/mineendpoint returns. If a user owns multiple tenants and hasn'thelpbase linked the project, the "default" deploy target silently changes. Worse, once picked, the codewriteProjectConfig({ tenantId, slug: tenantSlug })at line 131 persists that arbitrary choice.Consider either:
- Prompting when
tenants.length > 1(interactive) and requiring--slug(non-interactive), or- Making
listMyTenantsreturn a server-guaranteed sort order (e.g.created_at ASC) and documenting it.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/cli/src/commands/deploy.ts` around lines 111 - 114, The code currently picks tenants[0] from listMyTenants() which is non-deterministic when a user has multiple tenants and then persists that choice via writeProjectConfig({ tenantId, slug: tenantSlug }). Change this by: when listMyTenants(session) returns length > 1, prompt the user interactively to choose a tenant (use the same CLI flow where deploy command detects interactive mode) and, for non-interactive runs, require the caller to pass --slug (fail with a clear error if not supplied); update the logic around existingTenant, tenantId and tenantSlug to use the selected/validated slug and only call writeProjectConfig after explicit selection/validation. Ensure listMyTenants remains unchanged unless you opt for the alternate server-sort approach described in the review.apps/web/app/api/v1/tenants/[id]/deploy/route.ts-1-85 (1)
1-85:⚠️ Potential issue | 🟡 MinorRoute signature and RPC parameters are correct —
as nevercasts are unnecessary.The route handler signature
ctx: { params: Promise<{ id: string }> }matches the Next.js 16.1.6 standard and is used consistently across the codebase. The RPC call parameters (p_tenant_id,p_categories,p_articles,p_chunks,p_validation_report) match the generated Supabase types exactly. TherevalidatePathusage is also correct.However, the
as nevercasts on lines 50–53 are inconsistent with other RPC calls in the codebase (e.g.,get_user_tokens_today,increment_global_tokens) which don't require them. Remove the casts to align with the pattern used elsewhere.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@apps/web/app/api/v1/tenants/`[id]/deploy/route.ts around lines 1 - 85, Remove the unnecessary `as never` casts on the RPC call arguments in the admin.rpc("deploy_tenant", ...) invocation — specifically remove `as never` on p_categories, p_articles, p_chunks and p_validation_report so the call matches other RPC usages (e.g., get_user_tokens_today) and relies on the generated Supabase types; keep the same parameter names (p_tenant_id, p_categories, p_articles, p_chunks, p_validation_report) and return handling intact.packages/cli/src/lib/tenants-client.ts-80-91 (1)
80-91:⚠️ Potential issue | 🟡 Minor403 collapsed into
nullhides authorization failures.
getTenanttreats 403 and 404 identically, so callers can't distinguish "tenant doesn't exist" from "you don't own this tenant." That will surface as confusing UX inlink/open/whoami(e.g. "tenant not found" when the user actually lacks access). Consider returningnullonly on 404 and letting 403 throw viathrowHttp, or returning a discriminated result.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/cli/src/lib/tenants-client.ts` around lines 80 - 91, The getTenant function currently collapses 403 and 404 into null; change it so only 404 returns null and 403 (and other non-OK statuses) are handled by throwHttp. Concretely, modify getTenant to: call fetch as before, if res.status === 404 return null, otherwise await parseBody(res) and if (!res.ok) call throwHttp("get tenant", res, body); finally return body as TenantDetail. This preserves existing parseBody/throwHttp usage and allows callers of getTenant to observe authorization failures (403).
🧹 Nitpick comments (19)
scripts/migrate-auth-to-better-auth.sql (2)
74-77: Re-run hazard on production is correctly called out, but consider gating in-script.The header comment (lines 14-19) acknowledges
ALTER COLUMN ... TYPE text USING ::textrewrites the table and takes anACCESS EXCLUSIVElock even when alreadytext. Forllm_usage_events(typically growth-heavy), a re-run on prod is pretty painful. Consider wrapping the twoALTER COLUMN ... TYPE textstatements in aDO $$ ... IF (SELECT data_type ...) <> 'text' THEN ... END IF; $$;so accidental re-runs are no-ops. Otherwise this script is effectively "dev only" after first apply.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@scripts/migrate-auth-to-better-auth.sql` around lines 74 - 77, The two ALTERs on llm_usage_events.user_id and tenants.owner_id should be made idempotent by checking the current column data_type before executing to avoid an unnecessary table rewrite and ACCESS EXCLUSIVE lock on re-runs; wrap each ALTER COLUMN statement in an anonymous PL/pgSQL block (DO $$ ... $$) that queries information_schema.columns (filtering on table_name and column_name) and only executes the ALTER TABLE ... ALTER COLUMN ... TYPE text USING ... if the data_type is not already 'text'.
52-66: ConsiderTRIM+loweron email, and verifyname NOT NULLcompatibility.Two small things:
- Better Auth's
user.emailis conventionally stored lowercase; Supabase'sauth.users.emailis already normalized but mixed-case historical rows exist. If any downstream join is case-sensitive,lower(u.email)here future-proofs it.- The
nameCOALESCE falls back tosplit_part(u.email, '@', 1), which is never null given theWHERE u.email IS NOT NULLfilter — good. But if the live"user"table schema hasnameasNULL-allowed, the PR's later writes may passnull; worth confirming the schema matches the type definition inapps/web/types/supabase.ts(name: string, not nullable).🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@scripts/migrate-auth-to-better-auth.sql` around lines 52 - 66, Update the INSERT to normalize emails and guarantee a non-null name: replace occurrences of u.email with lower(trim(u.email)) in the SELECT and in the name fallback, i.e. use split_part(lower(trim(u.email)), '@', 1) as the final COALESCE fallback for name so it always produces a non-null string; also verify the target "user".name column matches the non-null string expectation used in apps/web/types/supabase.ts (`name: string`) and adjust the COALESCE default (e.g., empty string) if the schema allows NULLs.apps/web/lib/auth.ts (2)
99-99: Confusing comment — clarify intent.
"10m", // longer than default 30m would be gratuitousreads as if the default is 30m (so 10m is shorter, not longer). If you meant "shorter than the 30m default is fine", reword; if the default is actually 10m and you're documenting an upper bound, say so explicitly. Minor nit.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@apps/web/lib/auth.ts` at line 99, The inline comment next to expiresIn: "10m" in apps/web/lib/auth.ts is misleading; update it to clearly state the intended relation to the default timeout (e.g., "10m — intentionally shorter than the default 30m" or "10m — set as a short expiry; default is 30m") or correct it to reflect the actual default if different, leaving the expiresIn: "10m" value unchanged unless you intend to alter it.
82-108: Pool is created unconditionally — dev runs withDATABASE_URL=undefinedwill 500, as documented, but consider a named instance.Not a blocker, just a hygiene thought:
new Pool({ connectionString: DATABASE_URL })in a Next.js server module gets re-instantiated on HMR and (in some dev conditions) leaks handles. Pattern used elsewhere in the repo for Supabase clients is usually aglobalThis-cached singleton. If you hit dev-server handle exhaustion later, that's the knob.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@apps/web/lib/auth.ts` around lines 82 - 108, The Pool is created unconditionally which can leak connections on HMR; change to create and reuse a single global-scope Pool instance (e.g., store it on globalThis as pgPool or authDbPool) and pass that instance into betterAuth instead of calling new Pool({ connectionString: DATABASE_URL }) inline; update the auth initialization to reference the cached pool variable and ensure the cache key is unique to avoid re-creation across module reloads.packages/cli/src/lib/auth-client.ts (1)
58-60: Nit:slice(0, 200)before redaction can leave a token prefix.If a token happens to straddle index 200, the tail is sliced off, so the remaining prefix in
body[0..200]may be <24 chars and miss the redactor. In practice token-bearing bodies are tiny JSON and this doesn't hit, but swapping the order (redact → slice) avoids the edge case entirely:♻️ Proposed nit
function safeSnippet(body: string): string { - return body.slice(0, 200).replace(/[A-Za-z0-9_+/=-]{24,}/g, "[redacted]") + return body.replace(/[A-Za-z0-9_+/=-]{24,}/g, "[redacted]").slice(0, 200) }🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/cli/src/lib/auth-client.ts` around lines 58 - 60, The function safeSnippet can leave a token prefix when slice(0, 200) runs before the redaction; update safeSnippet so it first apply the redaction regex (/[A-Za-z0-9_+/=-]{24,}/g) to the full body and then return the first 200 chars of the redacted string (i.e., perform replace(...) before slice(...)) to avoid leaking partial tokens while keeping the same redaction pattern and length limit.packages/cli/test/auth-device.test.ts (1)
14-15: Top-levelprocess.env.HOMEmutation can leak across test files.
process.env.HOME = TMP_HOMEruns at module-import time and is never restored. If Vitest is ever run withpoolOptions.threads.isolate: falseor with a shared worker pool (common for speed), any other test file loaded in the same worker after this one will inherit the fakeHOMEand may write stray.helpbase/files into a tmpdir — or worse, a later test that re-importsauth-devicewill see a staleAUTH_DIR. SnapshotoriginalHome, swap it inbeforeAll, restore inafterAll.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/cli/test/auth-device.test.ts` around lines 14 - 15, The test currently sets process.env.HOME at module-import time by creating TMP_HOME and assigning process.env.HOME = TMP_HOME (TMP_HOME and process.env.HOME), which can leak into other tests; change this to capture the originalHome (e.g. const originalHome = process.env.HOME) and move the assignment into a beforeAll hook to set process.env.HOME = TMP_HOME, and restore process.env.HOME = originalHome in an afterAll hook so AUTH_DIR and any other modules that read HOME during test runtime are isolated and restored after the suite.apps/web/app/api/v1/tenants/by-slug/[slug]/route.ts (1)
17-28: Validate slug shape before querying / add rate limit.
slugis taken unvalidated from the URL and fed into an unauthenticated DB query. Supabase parameterizes.eq, so no injection, but:
- No length cap → a 10 KB
slugis still a DB round-trip.- No charset check → wasted queries on values that can never be tenant slugs.
- Unauthenticated + no rate limit (Vercel KV is configured elsewhere in the PR) → trivial enumeration/bulk probing of the tenants table.
Gate with the slug regex you use at create-time and hook into the existing KV rate-limiter.
+const SLUG_RE = /^[a-z0-9](?:[a-z0-9-]{0,30}[a-z0-9])?$/ + export async function GET( _req: NextRequest, ctx: { params: Promise<{ slug: string }> }, ): Promise<NextResponse> { const { slug } = await ctx.params + if (!SLUG_RE.test(slug)) { + return NextResponse.json({ available: false }, { status: 400 }) + } const admin = getServiceRoleClient()🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@apps/web/app/api/v1/tenants/by-slug/`[slug]/route.ts around lines 17 - 28, The GET handler currently pulls slug from ctx.params and queries the DB without validation or rate-limiting; before calling getServiceRoleClient().from("tenants").select(...).eq("slug", slug)...maybeSingle(), validate slug against the same creation regex and a reasonable max length (reject with 400 if it fails), and then run the existing KV rate-limiter used elsewhere in the repo to throttle requests per client/slug (return 429 when limit exceeded); only after passing validation and rate checks proceed to query in the GET function.apps/web/app/device/page.tsx (1)
12-36: LGTM — minor: unusederrorsearch param.The route types
error?: stringinsearchParamsbut never surfaces it. If Better Auth ever redirects back to/device?error=…, the user will see only the generic prompt. Either drop it from the type or pass it through toAuthorizeDeviceClientso the client can render a message. Non-blocking; the client component likely handles its own error states.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@apps/web/app/device/page.tsx` around lines 12 - 36, The DevicePage component extracts user_code but ignores the declared error search param; update DevicePage to also read and trim params.error (e.g., const error = params.error?.trim() ?? "") and pass it to the client component (pass an initialError or error prop to AuthorizeDeviceClient alongside initialUserCode) so the client can render any redirect/authorization error instead of silently dropping it.apps/web/app/api/v1/tenants/[id]/rotate-mcp-token/route.ts (1)
26-28: Nit:crypto.randomBytes(32).toString("hex")is a one-liner.Both produce the same 64-char hex string and both are CSPRNG-backed on
runtime = "nodejs". The Node API is a bit less code and doesn't build an intermediate typed array.- const bytes = new Uint8Array(32) - crypto.getRandomValues(bytes) - const newToken = Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join("") + const { randomBytes } = await import("node:crypto") + const newToken = randomBytes(32).toString("hex")🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@apps/web/app/api/v1/tenants/`[id]/rotate-mcp-token/route.ts around lines 26 - 28, Replace the current CSPRNG construction (the Uint8Array named bytes and crypto.getRandomValues usage that produces newToken) with the simpler Node API call: use crypto.randomBytes(32).toString("hex") to produce the 64-char hex token and assign it to newToken; remove the intermediate bytes/Uint8Array and getRandomValues usage and ensure newToken is produced directly from crypto.randomBytes.apps/web/app/api/v1/tenants/_shared.ts (2)
60-62: Return type inference — consider explicitNextResponsereturn type.
jsonErrorhas no explicit return annotation; TypeScript infersNextResponse<{error: string; message?: string}>which is fine, but an explicit: NextResponse(or: NextResponse<ErrorBody>) makes the helper's contract documentable and prevents accidental shape drift.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@apps/web/app/api/v1/tenants/_shared.ts` around lines 60 - 62, The helper jsonError currently relies on inferred return type; add an explicit return annotation to document and lock its contract: update the jsonError function signature to return NextResponse or NextResponse<ErrorBody> (declare a small ErrorBody type/interface with error: string and optional message?: string) and keep the existing body construction and status options inside the function so the return shape cannot drift accidentally; reference the function name jsonError and the ErrorBody type when making the change.
46-53: 404 masks internal DB errors and leaks no observability signal.
if (error || !tenant)collapses "tenant-not-found" and "DB error" into the same 404. A connectivity blip, permission misconfig, or schema-drift error returnstenant_not_foundindistinguishable from a legitimate miss — no alert, no log line, just a silent 404 to the client. Consider loggingerrorserver-side (at warn/error level) and returning 503 on non-nullerrorto distinguish infra issues from legitimate misses.🛡️ Proposed fix
- if (error || !tenant) { - return NextResponse.json({ error: "tenant_not_found" }, { status: 404 }) - } + if (error) { + console.error("requireOwnedTenant: DB lookup failed", { tenantId, error: error.message }) + return NextResponse.json({ error: "tenant_lookup_failed" }, { status: 503 }) + } + if (!tenant) { + return NextResponse.json({ error: "tenant_not_found" }, { status: 404 }) + }🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@apps/web/app/api/v1/tenants/_shared.ts` around lines 46 - 53, The current check conflates DB errors and missing rows; change the logic in the block that calls admin.from("tenants").select("*").eq("id", tenantId).maybeSingle() so that if the returned error variable is non-null you log the error server-side (using your app logger) at warn/error level and return NextResponse.json({ error: "service_unavailable" }, { status: 503 }), but if error is null and tenant is null return NextResponse.json({ error: "tenant_not_found" }, { status: 404 }); keep the successful path unchanged; use the existing symbols (admin, tenant, error, NextResponse.json) to locate and update the code.packages/cli/src/lib/auth.ts (2)
61-76:refreshed.accessToken === stored.accessTokenalways — mirror comparison is tautologically partial.
toAuthSession(resp, stored.accessToken)usesstored.accessTokenas the bearer, so the three compared fields (userId,expiresAt) are the only ones that can ever differ. That is in fact the intent (Better Auth'sget-sessiondoesn't return a rotated bearer), so the behavior is right, but consider a one-line comment making that explicit to prevent a future contributor from "fixing" the apparent missingaccessTokencheck.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/cli/src/lib/auth.ts` around lines 61 - 76, The comparison block currently omits accessToken because toAuthSession(resp, stored.accessToken) uses the stored bearer and getSessionWithBearer/Better Auth's get-session never returns a rotated accessToken; add a one-line comment above the "refreshed" assignment or above the comparison (near getSessionWithBearer, toAuthSession, storeSession and clearStoredSession) explaining that accessToken is intentionally not compared because the server doesn't return a new bearer so this is not a bug and prevents future contributors from re-introducing an accessToken check.
151-161: Stub throws unconditionally — callers still wire it.This function always throws, but
packages/cli/src/commands/deploy.ts:583(and any sibling commands that inlined the same auth flow) still invoke it as if it could succeed. I've flagged the root-cause fix indeploy.ts. Separately, since this is a stub with no viable code path, consider whether keeping it exported is worth the API-surface debt, or if it should be deleted alongside its call sites in the same PR to avoid the stale API lingering.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/cli/src/lib/auth.ts` around lines 151 - 161, The exported function verifyLoginCode currently always throws and callers (e.g., the auth flow in deploy.ts) still call it; remove the stale API usage or the API itself. Fix by either (A) deleting verifyLoginCode and updating every caller (such as the logic in deploy.ts around line ~583 and any sibling commands) to use the new browser device-flow / magic-link URL handling, or (B) if you must keep the symbol, implement it to surface a clear migration error at the call site (return a typed failure or helper that instructs callers to open the magic-link URL) and update callers to handle that return instead of expecting a successful AuthSession. Locate verifyLoginCode and the calls in deploy.ts / other command files and either remove/replace the calls with the new auth flow helpers or remove the exported stub to avoid stale API surface.apps/web/app/api/v1/tenants/[id]/deploy/route.ts (1)
44-46: Consider validating array element shape, not justArray.isArray.The handler accepts any array for
categories/articles/chunksand forwards it to the Supabase RPC asas never. Malformed element shapes only surface as opaquedeploy_failed503s from the DB. Since the shared schemas (categoryMetaSchema,frontmatterSchema,TenantChunk) already exist in@workspace/shared/schemasand are used client-side indeploy.ts, applying the same Zod parse server-side would convert a class of obscure 503s into precise 400s and defend against a malicious/misconfigured CLI caller.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@apps/web/app/api/v1/tenants/`[id]/deploy/route.ts around lines 44 - 46, The current handler only checks Array.isArray for body.categories/articles/chunks but not element shapes, causing malformed payloads to reach the Supabase RPC and produce opaque 503 deploy_failed errors; update the route handler to import and use the existing Zod schemas (categoryMetaSchema, frontmatterSchema, TenantChunk) from `@workspace/shared/schemas` and run Zod parsing/validation on each array (e.g., parse or safeParse for body.categories with categoryMetaSchema.array(), body.articles with frontmatterSchema.array(), and body.chunks with TenantChunk.array()), return a 400 jsonError with the Zod error details on validation failure, and pass the validated arrays (not casted as never) into the Supabase RPC call so only well-shaped data is forwarded.packages/cli/test/auth-client.test.ts (1)
218-231: Consider tightening the "non-JSON body" test label.The test at lines 223–226 names itself "throws on non-JSON body" but the raised error message
device/token: bad JSONcovers the same code path as thenon-2xx without RFC error bodycase at 228–231 when the response body is non-JSON. Behavior is correct; just noting the distinction between the two tests is subtle — consider renaming to e.g."throws with 'bad JSON' when body is not parseable"for clarity.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/cli/test/auth-client.test.ts` around lines 218 - 231, The test name "throws on non-JSON body" is ambiguous; rename the spec for clarity to indicate it expects a parse error: update the test case that calls pollDeviceAuth("dc") with a non-HTML JSON response to use a clearer title such as "throws with 'bad JSON' when body is not parseable" (reference: the test that stubs fetch and expects pollDeviceAuth to reject with /bad JSON/); leave the assertion and stub untouched.packages/cli/src/commands/deploy.ts (1)
172-183: Error-code string match is brittle.Classifying
slug_taken/slug_reservedvia/regex/.test(msg)on anError.messagecouples the CLI to the server's error formatting. If the server ever wraps the body (e.g."create tenant failed (409): {\"error\":\"slug_taken\"}"vs"slug_taken") or localizes the message, the user gets the generic"Failed to create tenant"branch instead of the targeted copy.Consider surfacing the structured
errorfield fromthrowHttpas a typed property on the thrown error so callers canif (err.code === "slug_taken")instead of regexing the message.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/cli/src/commands/deploy.ts` around lines 172 - 183, The catch block that handles apiCreateTenant should stop relying on regexing err.message and instead detect a structured error code exposed by the HTTP layer; update the catch to narrow the error (e.g. const httpErr = err as { code?: string; message?: string }) and check httpErr.code === "slug_taken" || httpErr.code === "slug_reserved" to call cancel with the specific subdomain-unavailable text, falling back to the existing message-based check only if no code exists; reference apiCreateTenant and the cancel(...) call when making this change so callers can rely on a typed code property from the throwHttp error.packages/cli/src/lib/auth-device.ts (1)
29-41: Pre-startsignal.abortedcheck is missing.The
opts.signal?.abortedcheck sits inside the loop but runs afterstartDeviceAuth(clientId)resolves. A caller that passes an already-aborted signal will still issue a device-code allocation to the server before the loop's first iteration checks and throws. Add an earlyif (opts.signal?.aborted) throw ...above thestartDeviceAuthcall (and ideally forward the signal tofetchviaAbortController).🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/cli/src/lib/auth-device.ts` around lines 29 - 41, Add an early abort check in deviceLogin before calling startDeviceAuth: if opts.signal?.aborted, throw an abort error immediately to avoid allocating a device code for an already-aborted caller; then propagate the caller signal into the network request by passing it to startDeviceAuth (or creating an AbortController and wiring opts.signal to its signal) so underlying fetch calls can be aborted. Update deviceLogin to perform the pre-start check and to forward opts.signal (or the created AbortController.signal) into startDeviceAuth/fetch.packages/cli/test/auth.unit.test.ts (1)
6-10: SetUSERPROFILEin addition toHOMEto isolateos.homedir()on Windows.
os.homedir()reads$HOMEon POSIX but%USERPROFILE%(or%HOMEDRIVE%%HOMEPATH%) on Windows. This test sets onlyprocess.env.HOMEbefore importing the auth module, which determinesAUTH_DIRfromos.homedir(). On Windows,AUTH_DIRwill still resolve to the real user's~/.helpbasedirectory, causing tests to potentially fail or write to a developer's actual auth file.Set USERPROFILE as well
const TMP_HOME = fs.mkdtempSync(path.join(os.tmpdir(), "helpbase-auth-unit-")) process.env.HOME = TMP_HOME +process.env.USERPROFILE = TMP_HOME const AUTH_FILE = path.join(TMP_HOME, ".helpbase", "auth.json")🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/cli/test/auth.unit.test.ts` around lines 6 - 10, The test only sets process.env.HOME (TMP_HOME) so os.homedir() can still resolve to the real Windows profile; update the setup to also set process.env.USERPROFILE (and optionally process.env.HOMEDRIVE and process.env.HOMEPATH) to TMP_HOME before importing the module that captures AUTH_DIR so AUTH_FILE (and any use of os.homedir()) is isolated to the temporary directory; reference TMP_HOME, AUTH_FILE, and process.env.HOME in the change and ensure these env vars are restored/isolated per test run.packages/cli/src/lib/tenants-client.ts (1)
18-44: Add runtime validation for API response bodies using zod schemas.All response bodies are cast directly with zero runtime validation (
body as TenantDetail,body as DeployResult, etc.). This silently producesundefinedwhen fields are missing or renamed server-side. Sincezod@4.3.6is already a CLI dependency, define schemas forTenantSummary,TenantDetail,DeployResult,SlugAvailability, andTenantCreated, then usesafeParse()to validate before returning. The explicit check inrotateMcpToken(lines 166–170) is a good partial precedent—zod would generalize and strengthen this pattern across all API functions.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/cli/src/lib/tenants-client.ts` around lines 18 - 44, Add runtime zod schemas for TenantSummary, TenantDetail, TenantCreated, DeployResult, and SlugAvailability that mirror the TypeScript interfaces, then replace all direct casts of response bodies (e.g., places returning body as TenantDetail, DeployResult, SlugAvailability, TenantCreated) with zodSchema.safeParse(body) checks; on failure throw or return a clear validation error (follow the rotateMcpToken pattern used already) and on success return the parsed.data. Ensure you import zod, export the schemas next to the interface definitions, and use the schema variables (e.g., TenantDetailSchema, DeployResultSchema) in each API function that consumes response bodies.
ℹ️ Review info
⚙️ Run configuration
Configuration used: defaults
Review profile: CHILL
Plan: Pro
Run ID: 2668ecbf-19c4-43e4-80fe-1c8cd0fe2d21
⛔ Files ignored due to path filters (1)
pnpm-lock.yamlis excluded by!**/pnpm-lock.yaml
📒 Files selected for processing (43)
.gitignoreCHANGELOG.mdDEVICE_FLOW_PLAN.mdREADME.mdapps/web/.env.exampleapps/web/app/(main)/errors/[code]/page.tsxapps/web/app/api/auth/[...all]/route.tsapps/web/app/api/revalidate/route.tsapps/web/app/api/v1/llm/_shared.tsapps/web/app/api/v1/tenants/[id]/deploy/route.tsapps/web/app/api/v1/tenants/[id]/rotate-mcp-token/route.tsapps/web/app/api/v1/tenants/[id]/route.tsapps/web/app/api/v1/tenants/_shared.tsapps/web/app/api/v1/tenants/by-slug/[slug]/route.tsapps/web/app/api/v1/tenants/mine/route.tsapps/web/app/api/v1/tenants/route.tsapps/web/app/api/v1/usage/today/route.tsapps/web/app/device/AuthorizeDeviceClient.tsxapps/web/app/device/page.tsxapps/web/lib/auth.tsapps/web/lib/supabase-admin.tsapps/web/lib/tenant-content.tsapps/web/next-env.d.tsapps/web/package.jsonapps/web/proxy.tsapps/web/test/llm-auth-swap.test.tsapps/web/types/supabase.tspackages/cli/package.jsonpackages/cli/src/commands/deploy.tspackages/cli/src/commands/link.tspackages/cli/src/commands/login.tspackages/cli/src/commands/open.tspackages/cli/src/commands/whoami.tspackages/cli/src/lib/auth-client.tspackages/cli/src/lib/auth-device.tspackages/cli/src/lib/auth.tspackages/cli/src/lib/errors.tspackages/cli/src/lib/supabase-client.tspackages/cli/src/lib/tenants-client.tspackages/cli/test/auth-client.test.tspackages/cli/test/auth-device.test.tspackages/cli/test/auth.unit.test.tsscripts/migrate-auth-to-better-auth.sql
💤 Files with no reviewable changes (1)
- packages/cli/src/lib/supabase-client.ts
Scaffolded projects don't run auth. The /device/ route imports better-auth/react which isn't in the template's dependencies, so every scaffolded project's next build fails with "Can't resolve 'better-auth/react'". Add app/device/ and lib/auth.ts to HOSTED_TIER_EXCLUDES so sync:templates keeps them in apps/web only. The hosted tier (auth, tenant routing, error pages) stays with helpbase.dev; the template remains a clean content-only Next.js project. Verified with pnpm smoke:install locally — 70 files scaffolded, 5 routes, build succeeds. Fixes PR #3 smoke-install CI failure. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Critical + Major: - device: coalesce `session.user.email` (better-auth types it `string|null`) - web: move `better-auth` to runtime dependencies; untrack next-env.d.ts - cli: bounded transient-error retry in device-flow polling + new `E_DEVICE_NETWORK` code so a DNS blip doesn't abort a 5-min wait - cli: fix Windows openBrowser (`cmd /c start "" <url>`) + async-error listener - cli: shared `v1Fetch` with `AbortSignal.timeout` on every tenants-client call - cli: drop broken 6-digit OTP fallback in `deploy.ts`/`inline-auth.ts`; use the device-flow inline so commands don't bounce users to `login` - sql: explicit `REVOKE SELECT ON public.tenants FROM anon` in migration Security-relevant Minor: - api: redact raw Supabase error bodies on create/delete/deploy/rotate routes; detect unique violations via code 23505 instead of regex - api: DNS-safe slug regex; by-slug no longer filters by `active=true` (matches UNIQUE(slug) contract) - api: `rotate-mcp-token` returns 404 when no row was actually updated - api: `_shared.requireOwnedTenant` separates infra 503 from missing 404 - api: deploy route validates payload with shared `deployPayloadSchema` (turns malformed input into precise 400s instead of opaque 503s) - cli: `link --slug` confirms ownership via authed `getTenant` before writing project.json; `getTenant` no longer collapses 403 to null - cli: deterministic tenant selection in `deploy` — prompt on >1 tenants, require `--slug` in non-interactive mode - device: "Try again" routes back through signed-in state when session is still valid instead of stranding the user in the email form Polish: - sql: idempotent `ALTER COLUMN TYPE text` (no full-table rewrite on re-run) - sql: lowercase+trim email on auth.users -> public.user copy - cli: login spinner uses actual server `expires_in` for expiry hint - cli tests: save/restore HOME + USERPROFILE to prevent cross-worker leaks - env: quote `RESEND_FROM_EMAIL` + point at `auth.helpbase.dev` Tests: 369 CLI / 51 web, all green. Typecheck clean on both. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
|
@coderabbitai review |
✅ Actions performedReview triggered.
|
The DATABASE_URL + RESEND_API_KEY guards in apps/web/lib/auth.ts threw at module load whenever NODE_ENV=production. That fires during `next build`'s static page-data collection step, not just at runtime — so CI without prod secrets failed to build, and any local `pnpm build` without a .env.local with those vars blew up before ever serving. Check NEXT_PHASE=phase-production-build to detect the build phase and skip the throw there. Missing DATABASE_URL at build time just logs a warning; the throw still fires on the first real request if the var wasn't set, which is the correct failure mode (runtime 500 on /api/auth/* routes while the rest of the site still serves). Fixes PR #3 CI break. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Scaffolded projects don't run auth. The /device/ route imports better-auth/react which isn't in the template's dependencies, so every scaffolded project's next build fails with "Can't resolve 'better-auth/react'". Add app/device/ and lib/auth.ts to HOSTED_TIER_EXCLUDES so sync:templates keeps them in apps/web only. The hosted tier (auth, tenant routing, error pages) stays with helpbase.dev; the template remains a clean content-only Next.js project. Verified with pnpm smoke:install locally — 70 files scaffolded, 5 routes, build succeeds. Fixes PR #3 smoke-install CI failure. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Pulls the Phase union and transition logic out of AuthorizeDeviceClient into a pure `phaseReducer(state, action)` so the state machine can be tested without React, the DOM, or better-auth mocks. Component now calls `useReducer(phaseReducer, initialPhase)` and dispatches actions from handlers + the derivation effect. - apps/web/app/device/phase-reducer.ts — new pure module with the Phase union, PhaseAction union, `phaseReducer`, and state machine ASCII diagram as the file header - apps/web/app/device/phase-reducer.test.ts — 20 unit tests, 100% branch coverage of transitions including the `email ?? ""` regression from PR #3 review - apps/web/app/device/AuthorizeDeviceClient.tsx — switches to useReducer; "Try again" button collapses to a single SESSION_RESOLVED dispatch (no duplicated derivation logic) - apps/web/app/device/AuthorizeDeviceClient.test.tsx — 15 thin integration tests via @testing-library/react + jsdom covering the effect wiring, providers-prop conditional render, and async handler dispatch sites - apps/web/vitest.config.ts — new config wiring @vitejs/plugin-react for JSX transform + `@/*` alias. Default env stays node; integration test opts into jsdom via `/* @vitest-environment jsdom */` - apps/web/package.json — jsdom, @testing-library/{react, user-event, jest-dom}, @vitejs/plugin-react (dev deps) Result: 86 web tests pass (was 51). +35 new tests in <1s, typecheck clean. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Pulls the Phase union and transition logic out of AuthorizeDeviceClient into a pure `phaseReducer(state, action)` so the state machine can be tested without React, the DOM, or better-auth mocks. Component now calls `useReducer(phaseReducer, initialPhase)` and dispatches actions from handlers + the derivation effect. - apps/web/app/device/phase-reducer.ts — new pure module with the Phase union, PhaseAction union, `phaseReducer`, and state machine ASCII diagram as the file header - apps/web/app/device/phase-reducer.test.ts — 20 unit tests, 100% branch coverage of transitions including the `email ?? ""` regression from PR #3 review - apps/web/app/device/AuthorizeDeviceClient.tsx — switches to useReducer; "Try again" button collapses to a single SESSION_RESOLVED dispatch (no duplicated derivation logic) - apps/web/app/device/AuthorizeDeviceClient.test.tsx — 15 thin integration tests via @testing-library/react + jsdom covering the effect wiring, providers-prop conditional render, and async handler dispatch sites - apps/web/vitest.config.ts — new config wiring @vitejs/plugin-react for JSX transform + `@/*` alias. Default env stays node; integration test opts into jsdom via `/* @vitest-environment jsdom */` - apps/web/package.json — jsdom, @testing-library/{react, user-event, jest-dom}, @vitejs/plugin-react (dev deps) Result: 86 web tests pass (was 51). +35 new tests in <1s, typecheck clean. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
**TODO-018 shipped**: `helpbase context` (and any other LLM call) now accepts `ANTHROPIC_API_KEY` or `OPENAI_API_KEY` directly, not just `AI_GATEWAY_API_KEY`. Precedence: Gateway > Anthropic > OpenAI > hosted. - packages/shared/src/llm.ts: `resolveByokModel(modelString)` routes to the right Vercel AI SDK provider. When ANTHROPIC_API_KEY is set the model must be `anthropic/...`; mismatches throw with the exact command to try instead (no silent Gateway fallback). - isByokMode() now returns true for any of the three keys. - byokGenerateObject + byokGenerateText pass the resolved factory into `generateObject` / `generateText` instead of a bare string. - context-errors.ts E_CONTEXT_MISSING_KEY rewritten: if the user already has an Anthropic or OpenAI key, skip the Gateway signup entirely. - whoami + doctor surfaces now name whichever key is set. - Pinned @ai-sdk/anthropic@^2.0.77 + @ai-sdk/openai@^2.0.103 so provider versions track ai@5's `@ai-sdk/provider@2.x` peer (not the 3.x line destined for ai@6). Lockfile updated. Tests: +9 routing tests in packages/shared covering every precedence path + every provider mismatch error. 141/141 shared tests green. **TODOS.md cleanup**: 5 open items → 0 open items. - TODO-020 (device-flow login): ALREADY SHIPPED in PR #3 (726a0fd). `packages/cli/src/lib/auth-device.ts` runs full RFC 8628 as the default; `--email` is the magic-link fallback. TODO pre-dated the better-auth migration — moved to Completed with commit ref. - TODO-018: completed by this commit. - TODO-017 (helpbase agent): dropped. Its own body blocked it on user feedback from sync, which hasn't arrived. Keeping a stale P3 is noise; re-file when feedback actually shows up. - TODO-019 (external-repo eval + nightly CI): dropped. The local `pnpm eval` gate already covers pre-prompt-change work. A nightly 90-call GitHub Action is ongoing spend against speculative regressions we've never observed. Add the specific fixture IF a real regression surfaces; don't run perpetual guardrails on hypotheticals. - TODO-004 (hero screenshot): dropped. README placeholder comment removed — drop in apps/web/public/og.png whenever ready, no tracker needed. helpbase.dev is the primary marketing surface. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Summary
Two flagship changes plus a cluster of security/quality fixes surfaced by
/review:1. Auth backend: Supabase Auth → Better Auth
The CLI and the hosted API now run on Better Auth (bearer + magic-link + deviceAuthorization plugins).
~/.helpbase/auth.jsonshape andHELPBASE_TOKENcontract preserved; zero action required for existing installs. Emails route through Resend.@supabase/supabase-jsdropped frompackages/clidependencies — the CLI talks to helpbase.dev over plainfetch.2. Device-flow login is the new default
helpbase loginopens the browser athelpbase.dev/device?user_code=…, user clicks Authorize, CLI picks up the bearer via/api/auth/device/token. Under 10s on the warm path. Progressive hints at T+30s / T+90s / T+4min keep the YC-founder first-run oriented. Magic-link paste flow preserved behindhelpbase login --email.3. Server-side tenant API (
/api/v1/tenants/*)deploy,link,open,whoaminow call typed HTTP endpoints instead of speaking Supabase directly. Ownership enforced in route handlers viaauth.api.getSession+ service-role DB writes, since the migration dropped theauth.uid()-based RLS*_ownpolicies.Security fixes folded in via /review:
mcp_public_tokenleak closed — newtenants_publicview, anon grants revoked on the basetenantstable. Pre-existing issue where the CLI's embedded anon key could enumerate every active tenant's MCP bearer./api/revalidateswapped to Better Auth (was 401ing on every deploy post-migration).RESEND_API_KEYrequired in production; dev console fallback gated onNODE_ENV.~/.helpbase/auth.jsonforce-narrowed to 0600 on every write.Test Coverage
41 new tests across 4 suites cover the new auth surface:
auth-client.test.ts—extractVerificationToken(URL/fragment parsing, boundary cases),sendMagicLink,consumeMagicLink(5 failure branches),startDeviceAuth,pollDeviceAuth(8 RFC error branches),getSessionWithBearer.auth-device.test.ts—deviceLoginstate machine (happy path +authorization_pending+access_denied+expired_token+ abort-signal +onStartcallback).auth.unit.test.ts—toAuthSession,getCurrentSession(stale/valid/backcompat paths),verifyLoginFromMagicLink(happy + malformed + null-session).llm-auth-swap.test.ts—withAuthAndQuota(401, 429 quota, 503 RPC failure, text-userId RPC arg).Tests: 379 → 420 (+41 new). All pass against the feature branch.
Gap:
AuthorizeDeviceClientReact component phase reducer lacks unit tests (needs jsdom +@testing-librarysetup inapps/web/vitest.config— filed as follow-up). Manual browser smoke covered it end-to-end.Pre-Landing Review
Four-specialist dispatch (security, testing, maintainability, data-migration) + Claude adversarial + /review ran before this PR was opened. 20 findings (5 critical, 15 informational). All addressed:
0600chmod,toAuthSessiondedup, error-body redaction, migration comment./api/revalidateauth swap,mcp_public_tokenview, Resend prod guard, unused error codes removed.deploy/link/openrefactor).Database Migrations
Two migrations applied to prod Supabase via MCP during this work:
better_auth_core_tables— createsuser/session/account/verification+deviceCodetables with RLS locked down.migrate_auth_users_to_better_auth— copiesauth.users→public.userpreserving UUIDs as text IDs; re-pointstenants.owner_id+llm_usage_events.user_idFKs; drops inert RLS*_ownpolicies.tenants_public_view_hide_mcp_token— security fix.deploy_tenant_rpc_no_authuid— dropsauth.uid()ownership check (now enforced in route handlers).scripts/migrate-auth-to-better-auth.sqlcommitted for reproducibility against fresh DBs.Known Follow-ups (post-merge)
helpbase.devbefore prod can send real magic-link email.@testing-librarytoapps/weband coverAuthorizeDeviceClient's 8-phase reducer.auth.users— planned 30 days after this PR as read-only backup window.Test plan
pnpm -F helpbase testgreen (369 pass, 3 skipped)pnpm -F web testgreen (51 pass)pnpm -F helpbase typecheckgreenpnpm -F web typecheckgreenhelpbase login(device flow) →helpbase whoamireturns migrated user's historical quota (153k / 500k tokens)/api/v1/tenants/mine401 unauthed, 200 authed;/api/v1/tenants/:id403 cross-usercurl -H "Authorization: Bearer $(jq -r .access_token ~/.helpbase/auth.json)" https://helpbase.dev/api/v1/usage/todayBETTER_AUTH_SECRET,DATABASE_URL,RESEND_API_KEY,BETTER_AUTH_URLin Vercel production env before mergehelpbase.devdomain in Resend (SPF + DKIM DNS records) before first prod magic-link send🤖 Generated with Claude Code
Summary by CodeRabbit
New Features
--emailflag for headless environments.Bug Fixes
Documentation
Chores