Skip to content

feat: migrate auth to Better Auth + ship device-flow login (helpbase 0.5.0) - #3

Merged
Codehagen merged 5 commits into
mainfrom
feat/better-auth-device-flow
Apr 17, 2026
Merged

Codehagen merged 5 commits into
mainfrom
feat/better-auth-device-flow

Conversation

@Codehagen

@Codehagen Codehagen commented Apr 17, 2026 •

Copy link
Copy Markdown
Owner

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.json shape and HELPBASE_TOKEN contract preserved; zero action required for existing installs. Emails route through Resend. @supabase/supabase-js dropped from packages/cli dependencies — the CLI talks to helpbase.dev over plain fetch.

2. Device-flow login is the new default
helpbase login opens the browser at helpbase.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 behind helpbase login --email.

3. Server-side tenant API (/api/v1/tenants/*)
deploy, link, open, whoami now call typed HTTP endpoints instead of speaking Supabase directly. Ownership enforced in route handlers via auth.api.getSession + service-role DB writes, since the migration dropped the auth.uid()-based RLS *_own policies.

Security fixes folded in via /review:

  • mcp_public_token leak closed — new tenants_public view, anon grants revoked on the base tenants table. Pre-existing issue where the CLI's embedded anon key could enumerate every active tenant's MCP bearer.
  • /api/revalidate swapped to Better Auth (was 401ing on every deploy post-migration).
  • RESEND_API_KEY required in production; dev console fallback gated on NODE_ENV.
  • ~/.helpbase/auth.json force-narrowed to 0600 on every write.
  • Error response bodies redacted before splicing into CLI stderr.

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 — deviceLogin state machine (happy path + authorization_pending + access_denied + expired_token + abort-signal + onStart callback).
  • 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: AuthorizeDeviceClient React component phase reducer lacks unit tests (needs jsdom + @testing-library setup in apps/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:

  • Auto-fixed: 0600 chmod, toAuthSession dedup, error-body redaction, migration comment.
  • Fixed via ASK: /api/revalidate auth swap, mcp_public_token view, Resend prod guard, unused error codes removed.
  • Folded in: server-side tenant API rewrite (Phase D — deploy/link/open refactor).

Database Migrations

Two migrations applied to prod Supabase via MCP during this work:

  1. better_auth_core_tables — creates user / session / account / verification + deviceCode tables with RLS locked down.
  2. migrate_auth_users_to_better_auth — copies auth.users → public.user preserving UUIDs as text IDs; re-points tenants.owner_id + llm_usage_events.user_id FKs; drops inert RLS *_own policies.
  3. tenants_public_view_hide_mcp_token — security fix.
  4. deploy_tenant_rpc_no_authuid — drops auth.uid() ownership check (now enforced in route handlers).

scripts/migrate-auth-to-better-auth.sql committed for reproducibility against fresh DBs.

Known Follow-ups (post-merge)

  • OAuth providers (Google/GitHub) — drops cold-path TTHW from ~60s to ~20s. Needs OAuth apps in the respective consoles.
  • Resend domain verification — SPF/DKIM on helpbase.dev before prod can send real magic-link email.
  • React component tests — add jsdom + @testing-library to apps/web and cover AuthorizeDeviceClient's 8-phase reducer.
  • Delete Supabase auth.users — planned 30 days after this PR as read-only backup window.

Test plan

  • pnpm -F helpbase test green (369 pass, 3 skipped)
  • pnpm -F web test green (51 pass)
  • pnpm -F helpbase typecheck green
  • pnpm -F web typecheck green
  • CLI + web build green
  • End-to-end smoke: helpbase login (device flow) → helpbase whoami returns migrated user's historical quota (153k / 500k tokens)
  • Direct API probes: /api/v1/tenants/mine 401 unauthed, 200 authed; /api/v1/tenants/:id 403 cross-user
  • Production smoke after Vercel deploys: curl -H "Authorization: Bearer $(jq -r .access_token ~/.helpbase/auth.json)" https://helpbase.dev/api/v1/usage/today
  • Set BETTER_AUTH_SECRET, DATABASE_URL, RESEND_API_KEY, BETTER_AUTH_URL in Vercel production env before merge
  • Verify helpbase.dev domain in Resend (SPF + DKIM DNS records) before first prod magic-link send

🤖 Generated with Claude Code

Summary by CodeRabbit

  • New Features

    • Introduced RFC 8628 device flow for CLI authentication with browser-based authorization and progressive polling messages.
    • Added magic-link email login fallback via --email flag for headless environments.
    • New tenant management API endpoints for listing, creating, retrieving, deleting tenants and rotating MCP tokens.
  • Bug Fixes

    • Enforced secure file permissions (mode 0600) on authentication configuration files.
  • Documentation

    • Added local authentication development guide with Better Auth configuration instructions.
    • Added environment variable reference file for the web application.
  • Chores

    • Migrated authentication backend from Supabase to Better Auth.
    • Updated CLI version from 0.4.1 to 0.5.0.
    • Expanded test coverage for authentication and session-related functionality.

Codehagen and others added 2 commits April 17, 2026 19:18
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>
@vercel

vercel Bot commented Apr 17, 2026 •

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated (UTC)
helpbase Ready Ready Preview, Comment Apr 17, 2026 6:12pm

Request Review

@coderabbitai

coderabbitai Bot commented Apr 17, 2026 •

Copy link
Copy Markdown

Warning

Rate limit exceeded

@Codehagen has exceeded the limit for the number of commits that can be reviewed per hour. Please wait 3 minutes and 4 seconds before requesting another review.

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 @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

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 configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 74aa4853-005f-4ee7-aa5a-3ddedba1d3aa

📥 Commits

Reviewing files that changed from the base of the PR and between 65b48d0 and 951fbd1.

⛔ Files ignored due to path filters (1)
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
📒 Files selected for processing (23)
  • .gitignore
  • apps/web/.env.example
  • apps/web/app/api/v1/tenants/[id]/deploy/route.ts
  • apps/web/app/api/v1/tenants/[id]/rotate-mcp-token/route.ts
  • apps/web/app/api/v1/tenants/[id]/route.ts
  • apps/web/app/api/v1/tenants/_shared.ts
  • apps/web/app/api/v1/tenants/by-slug/[slug]/route.ts
  • apps/web/app/api/v1/tenants/route.ts
  • apps/web/app/device/AuthorizeDeviceClient.tsx
  • apps/web/lib/auth.ts
  • apps/web/next-env.d.ts
  • apps/web/package.json
  • packages/cli/src/commands/deploy.ts
  • packages/cli/src/commands/link.ts
  • packages/cli/src/commands/login.ts
  • packages/cli/src/lib/auth-device.ts
  • packages/cli/src/lib/errors.ts
  • packages/cli/src/lib/inline-auth.ts
  • packages/cli/src/lib/tenants-client.ts
  • packages/cli/test/auth-device.test.ts
  • packages/cli/test/auth.unit.test.ts
  • scripts/migrate-auth-to-better-auth.sql
  • scripts/sync-templates.mjs
📝 Walkthrough

Walkthrough

This 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 /api/v1/tenants/* endpoints, eliminating its direct database dependency while retaining magic-link email login as a fallback.

Changes

Cohort / File(s) Summary
Configuration & Environment
.gitignore, apps/web/.env.example, apps/web/next-env.d.ts, packages/cli/package.json
Added local agent tooling ignores, new .env.example with Better Auth/Resend/database vars, updated generated type references, and bumped CLI version to 0.5.0.
Documentation
CHANGELOG.md, DEVICE_FLOW_PLAN.md, README.md
Documented auth migration to Better Auth, device authorization flow introduction, and local auth development setup; added comprehensive device flow implementation plan (489 lines).
Better Auth Web Configuration
apps/web/lib/auth.ts, apps/web/app/api/auth/[...all]/route.ts, apps/web/package.json
Introduced Better Auth instance with PostgreSQL backend, bearer/magic-link/device authorization plugins, and Next.js route handler for /api/auth/* subroutes; added pg, resend, better-auth dependencies.
Auth-Dependent Web API Routes
apps/web/app/api/revalidate/route.ts, apps/web/app/api/v1/llm/_shared.ts, apps/web/app/api/v1/usage/today/route.ts
Replaced Supabase JWT verification with Better Auth session resolution via auth.api.getSession({ headers }); updated quota RPC calls to use authenticated user ID.
Tenant Management Web API Routes
apps/web/app/api/v1/tenants/route.ts, apps/web/app/api/v1/tenants/[id]/route.ts, apps/web/app/api/v1/tenants/[id]/deploy/route.ts, apps/web/app/api/v1/tenants/[id]/rotate-mcp-token/route.ts, apps/web/app/api/v1/tenants/by-slug/[slug]/route.ts, apps/web/app/api/v1/tenants/mine/route.ts, apps/web/app/api/v1/tenants/_shared.ts
Implemented comprehensive v1 tenant REST API with ownership validation, slug availability checks, deployments, MCP token rotation, and centralized auth/error helpers.
Web Device Authorization UI
apps/web/app/device/page.tsx, apps/web/app/device/AuthorizeDeviceClient.tsx, apps/web/app/(main)/errors/[code]/page.tsx
Added device authorization page, multi-phase React component managing device-flow state machine (loading/signed-out/email-sent/signed-in/approving/approved/denied/error), and error pages for device auth codes.
Web Database & Auth Removal
apps/web/lib/supabase-admin.ts, apps/web/lib/tenant-content.ts, apps/web/proxy.ts, apps/web/types/supabase.ts
Removed verifyBearerToken function; updated tenant lookups to query tenants_public view; added Better Auth table typings (user, account, session, deviceCode, verification) and foreign-key relationships; dropped RLS policies pending migration.
CLI Auth Client & Device Flow
packages/cli/src/lib/auth-client.ts, packages/cli/src/lib/auth-device.ts, packages/cli/src/lib/auth.ts, packages/cli/src/lib/tenants-client.ts, packages/cli/src/lib/supabase-client.ts (removed)
Introduced Better Auth HTTP client for magic-link/device auth, RFC 8628 device-flow state machine with progressive polling, and hosted tenant API client; replaced Supabase auth with Better Auth session resolution and removed direct Supabase client dependency.
CLI Commands
packages/cli/src/commands/login.ts, packages/cli/src/commands/deploy.ts, packages/cli/src/commands/link.ts, packages/cli/src/commands/open.ts, packages/cli/src/commands/whoami.ts
Updated login to support new --email flag for magic-link fallback and default device-flow; migrated deploy/link/open/whoami commands from direct Supabase queries to hosted tenant API calls with authentication.
Error Definitions & Migration
packages/cli/src/lib/errors.ts, scripts/migrate-auth-to-better-auth.sql
Added three device-auth error codes (E_AUTH_CANCELLED, E_DEVICE_DENIED, E_DEVICE_EXPIRED); created SQL migration to copy Supabase auth.users to Better Auth "user" table, remove RLS policies, and reconcile foreign keys with ON DELETE CASCADE.
Web App Tests
apps/web/test/llm-auth-swap.test.ts
Added test suite validating withAuthAndQuota behavior with Better Auth session resolution and mocked quota RPC calls.
CLI Tests
packages/cli/test/auth-client.test.ts, packages/cli/test/auth-device.test.ts, packages/cli/test/auth.unit.test.ts
Introduced comprehensive test coverage for Better Auth HTTP client (magic-link, device code endpoints), RFC 8628 device flow (approval/denial/expiry/cancellation), and auth session helpers (toAuthSession, getCurrentSession, verifyLoginFromMagicLink).

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!"
Loading
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!
Loading

Estimated code review effort

🎯 5 (Critical) | ⏱️ ~95 minutes

Poem

🐰 Hark, the auth hath changed its coat!
From Supabase to Better Auth we float,
Device flows dance with RFC glory,
Magic links tell the signin story,
No more direct DB calls in sight—
The CLI talks API, clean and right! ✨

🚥 Pre-merge checks | ✅ 2 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 26.15% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (2 passed)
Check name Status Explanation
Title check ✅ Passed The title directly and clearly summarizes the main changes: migration from Supabase Auth to Better Auth and introduction of device-flow login as the new default, with the version bump indicated.
Description check ✅ Passed The pull request description is comprehensive and well-structured, covering all major changes, security fixes, testing, migrations, and follow-ups.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feat/better-auth-device-flow

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.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

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>

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 | 🟡 Minor

Type cast obscures nullability of tenants_public fields; add explicit type to clarify.

The tenants_public view columns are all nullable (id: string | null, slug: string | null, etc. per supabase.ts), yet the current cast as Tenant | null claims 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 from getTenant to 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 | 🔴 Critical

Broken auth fallback — verifyLoginCode always throws in the new auth module.

This ensureAuthenticated path still collects a 6-digit code and calls verifyLoginCode(email, code), but packages/cli/src/lib/auth.ts now makes verifyLoginCode unconditionally throw E_AUTH_VERIFY_OTP ("6-digit code login is no longer supported"). A user who runs helpbase deploy without first running helpbase login will:

  1. Receive the magic-link URL email from Resend
  2. Be prompted for a non-existent 6-digit code
  3. Hit the always-throw stub, see a confusing "not supported" error, and be unable to deploy

Either delegate to the new flow (run deviceLogin() from auth-device.ts, or fall back to verifyLoginFromMagicLink with a URL-paste prompt), or remove this inline login entirely and print Run \helpbase login` first. Same concern applies to any other commands (link, open, whoami) that call an equivalent ensureAuthenticated`.

🐛 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 | 🟡 Minor

All 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 returns TenantSummary[] with no documented ordering guarantee, so whoami may display a different tenant than the one linked locally. Consider preferring readProjectConfig() first (like open.ts does) and only falling back to tenants[0], and/or guaranteeing a stable server-side ordering (e.g., by created_at). Same issue also applies to packages/cli/src/commands/open.ts Lines 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 | 🟡 Minor

Quote 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 in apps/web/lib/auth.ts:10 and to appease dotenv-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 | 🟡 Minor

Confirm the UPDATE actually hit a row before returning the new token.

If the tenant row disappears between requireOwnedTenant and the update (soft-delete, admin action, race with DELETE), Supabase returns { error: null } with zero rows affected — the handler then responds 200 { 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 | 🟡 Minor

Availability probe may lie when an inactive tenant holds the slug.

The .eq("active", true) filter means a soft-deleted/deactivated tenant holding slug causes this endpoint to return { available: true }, but the subsequent POST /api/v1/tenants will fail with a UNIQUE (slug) constraint violation because the unique index on tenants.slug does not have a WHERE active clause. The CLI at packages/cli/src/commands/deploy.ts:166-169 trusts available and 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 | 🟡 Minor

Prefer the Postgres error code over regex-matching the message; avoid leaking raw DB errors.

/duplicate|unique/i on error.message is locale/driver-dependent and will silently stop working if PostgREST changes wording. Use error.code === '23505' (unique_violation). Also, msg flowing 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 | 🟡 Minor

Avoid echoing raw DB error messages to the client.

error.message from 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 | 🟡 Minor

Slug 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 | 🟡 Minor

Hardcoded 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_in is always 300s (Better Auth's default). If the server changes this value, the message becomes incorrect.

While info.expires_in is available in the onStart callback, the onProgress callback (line 68) only receives elapsedMs and has no access to the actual expiry duration. To fix this, either capture expires_in in onStart and reference it in the onProgress closure, 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 --slug doesn't verify ownership — links happily to another user's tenant.

checkSlugAvailability hits the public /by-slug/:slug endpoint with no authentication, so available === false only proves the slug is taken — not that this user owns it. The CLI writes .helpbase/project.json anyway, and the user only discovers the mistake when helpbase deploy / open / whoami 403s later.

Confirm ownership by calling GET /api/v1/tenants/:id with the session bearer before persisting. getTenant returns null on 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 phase to signed-out directly 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 during device.approve, and clicked "Try again" will see the email-entry form even though session.user is 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 | 🟡 Minor

Non-deterministic tenant selection when user owns >1 tenant.

tenants[0] depends on whatever ordering the /api/v1/tenants/mine endpoint returns. If a user owns multiple tenants and hasn't helpbase linked the project, the "default" deploy target silently changes. Worse, once picked, the code writeProjectConfig({ 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 listMyTenants return 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 | 🟡 Minor

Route signature and RPC parameters are correct — as never casts 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. The revalidatePath usage is also correct.

However, the as never casts 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 | 🟡 Minor

403 collapsed into null hides authorization failures.

getTenant treats 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 in link/open/whoami (e.g. "tenant not found" when the user actually lacks access). Consider returning null only on 404 and letting 403 throw via throwHttp, 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 ::text rewrites the table and takes an ACCESS EXCLUSIVE lock even when already text. For llm_usage_events (typically growth-heavy), a re-run on prod is pretty painful. Consider wrapping the two ALTER COLUMN ... TYPE text statements in a DO $$ ... 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: Consider TRIM + lower on email, and verify name NOT NULL compatibility.

Two small things:

  • Better Auth's user.email is conventionally stored lowercase; Supabase's auth.users.email is already normalized but mixed-case historical rows exist. If any downstream join is case-sensitive, lower(u.email) here future-proofs it.
  • The name COALESCE falls back to split_part(u.email, '@', 1), which is never null given the WHERE u.email IS NOT NULL filter — good. But if the live "user" table schema has name as NULL-allowed, the PR's later writes may pass null; worth confirming the schema matches the type definition in apps/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 gratuitous reads 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 with DATABASE_URL=undefined will 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 a globalThis-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-level process.env.HOME mutation can leak across test files.

process.env.HOME = TMP_HOME runs at module-import time and is never restored. If Vitest is ever run with poolOptions.threads.isolate: false or with a shared worker pool (common for speed), any other test file loaded in the same worker after this one will inherit the fake HOME and may write stray .helpbase/ files into a tmpdir — or worse, a later test that re-imports auth-device will see a stale AUTH_DIR. Snapshot originalHome, swap it in beforeAll, restore in afterAll.

🤖 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.

slug is 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 slug is 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: unused error search param.

The route types error?: string in searchParams but 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 to AuthorizeDeviceClient so 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 explicit NextResponse return type.

jsonError has no explicit return annotation; TypeScript infers NextResponse<{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 returns tenant_not_found indistinguishable from a legitimate miss — no alert, no log line, just a silent 404 to the client. Consider logging error server-side (at warn/error level) and returning 503 on non-null error to 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.accessToken always — mirror comparison is tautologically partial.

toAuthSession(resp, stored.accessToken) uses stored.accessToken as the bearer, so the three compared fields (userId, email, expiresAt) are the only ones that can ever differ. That is in fact the intent (Better Auth's get-session doesn'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 missing accessToken check.

🤖 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 in deploy.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 just Array.isArray.

The handler accepts any array for categories/articles/chunks and forwards it to the Supabase RPC as as never. Malformed element shapes only surface as opaque deploy_failed 503s from the DB. Since the shared schemas (categoryMetaSchema, frontmatterSchema, TenantChunk) already exist in @workspace/shared/schemas and are used client-side in deploy.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 JSON covers the same code path as the non-2xx without RFC error body case 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_reserved via /regex/.test(msg) on an Error.message couples 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 error field from throwHttp as a typed property on the thrown error so callers can if (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-start signal.aborted check is missing.

The opts.signal?.aborted check sits inside the loop but runs after startDeviceAuth(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 early if (opts.signal?.aborted) throw ... above the startDeviceAuth call (and ideally forward the signal to fetch via AbortController).

🤖 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: Set USERPROFILE in addition to HOME to isolate os.homedir() on Windows.

os.homedir() reads $HOME on POSIX but %USERPROFILE% (or %HOMEDRIVE%%HOMEPATH%) on Windows. This test sets only process.env.HOME before importing the auth module, which determines AUTH_DIR from os.homedir(). On Windows, AUTH_DIR will still resolve to the real user's ~/.helpbase directory, 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 produces undefined when fields are missing or renamed server-side. Since zod@4.3.6 is already a CLI dependency, define schemas for TenantSummary, TenantDetail, DeployResult, SlugAvailability, and TenantCreated, then use safeParse() to validate before returning. The explicit check in rotateMcpToken (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

📥 Commits

Reviewing files that changed from the base of the PR and between ac862e0 and 65b48d0.

⛔ Files ignored due to path filters (1)
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
📒 Files selected for processing (43)
  • .gitignore
  • CHANGELOG.md
  • DEVICE_FLOW_PLAN.md
  • README.md
  • apps/web/.env.example
  • apps/web/app/(main)/errors/[code]/page.tsx
  • apps/web/app/api/auth/[...all]/route.ts
  • apps/web/app/api/revalidate/route.ts
  • apps/web/app/api/v1/llm/_shared.ts
  • apps/web/app/api/v1/tenants/[id]/deploy/route.ts
  • apps/web/app/api/v1/tenants/[id]/rotate-mcp-token/route.ts
  • apps/web/app/api/v1/tenants/[id]/route.ts
  • apps/web/app/api/v1/tenants/_shared.ts
  • apps/web/app/api/v1/tenants/by-slug/[slug]/route.ts
  • apps/web/app/api/v1/tenants/mine/route.ts
  • apps/web/app/api/v1/tenants/route.ts
  • apps/web/app/api/v1/usage/today/route.ts
  • apps/web/app/device/AuthorizeDeviceClient.tsx
  • apps/web/app/device/page.tsx
  • apps/web/lib/auth.ts
  • apps/web/lib/supabase-admin.ts
  • apps/web/lib/tenant-content.ts
  • apps/web/next-env.d.ts
  • apps/web/package.json
  • apps/web/proxy.ts
  • apps/web/test/llm-auth-swap.test.ts
  • apps/web/types/supabase.ts
  • packages/cli/package.json
  • packages/cli/src/commands/deploy.ts
  • packages/cli/src/commands/link.ts
  • packages/cli/src/commands/login.ts
  • packages/cli/src/commands/open.ts
  • packages/cli/src/commands/whoami.ts
  • packages/cli/src/lib/auth-client.ts
  • packages/cli/src/lib/auth-device.ts
  • packages/cli/src/lib/auth.ts
  • packages/cli/src/lib/errors.ts
  • packages/cli/src/lib/supabase-client.ts
  • packages/cli/src/lib/tenants-client.ts
  • packages/cli/test/auth-client.test.ts
  • packages/cli/test/auth-device.test.ts
  • packages/cli/test/auth.unit.test.ts
  • scripts/migrate-auth-to-better-auth.sql
💤 Files with no reviewable changes (1)
  • packages/cli/src/lib/supabase-client.ts

Comment thread apps/web/next-env.d.ts Resolved
Comment thread apps/web/package.json Resolved
Comment thread packages/cli/src/lib/auth-device.ts Resolved
Comment thread packages/cli/src/lib/auth-device.ts Resolved
Comment thread packages/cli/src/lib/tenants-client.ts Resolved
Comment thread scripts/migrate-auth-to-better-auth.sql Resolved
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>
@Codehagen

Copy link
Copy Markdown
Owner Author

@coderabbitai review

@coderabbitai

coderabbitai Bot commented Apr 17, 2026

Copy link
Copy Markdown
✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@Codehagen
Codehagen merged commit 726a0fd into main Apr 17, 2026
5 checks passed
Codehagen added a commit that referenced this pull request Apr 17, 2026
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>
Codehagen added a commit that referenced this pull request Apr 17, 2026
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>
@Codehagen
Codehagen deleted the feat/better-auth-device-flow branch April 17, 2026 18:18
Codehagen added a commit that referenced this pull request Apr 17, 2026
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>
Codehagen added a commit that referenced this pull request Apr 17, 2026
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>
Codehagen added a commit that referenced this pull request Apr 17, 2026
**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>

This branch was successfully deployed

1 active deployment
Preview — 951fbd16 Deployed Apr 17, 2026 by vercel[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant