diff --git a/.gitignore b/.gitignore index 4981127..484b1a7 100644 --- a/.gitignore +++ b/.gitignore @@ -27,6 +27,9 @@ out/ build dist +# Auto-generated by Next.js — should not be tracked +apps/web/next-env.d.ts + # Debug npm-debug.log* @@ -48,3 +51,10 @@ apps/web/public/_helpbase-assets/ # Eval harness output — per-run artifact, not committed packages/cli/eval/eval-report.json packages/cli/eval/hosted-parity-report.json + +# Local agent tooling (not shared) +.agents/ +.claude/ +skills-lock.json +DEVICE_FLOW_PROMPT.md +NEXT_SESSION_PROMPT.md diff --git a/CHANGELOG.md b/CHANGELOG.md index 4f5bbb1..41fc9f2 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,64 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +## [helpbase 0.5.0] — 2026-04-17 + +### Added +- **`helpbase login` now uses a browser device-flow by default.** Run + `helpbase login` and the CLI opens your browser at + `helpbase.dev/device?user_code=ABCD-EFGH`, where you click Authorize + and the terminal picks up your bearer token. Under 10 seconds on the + fast path. No more email round-trip, no more paste-back dance. Built + on Better Auth's `deviceAuthorization` plugin (RFC 8628 device grant). + The old magic-link email flow is preserved behind + `helpbase login --email` as the fallback for CI and sandboxed envs. +- **Server-side tenant API** under `/api/v1/tenants/*`. `helpbase deploy`, + `helpbase link`, and `helpbase open` now call typed HTTP endpoints + instead of talking to Supabase directly. Ownership checks happen in + the server routes using Better Auth session verification. +- **Progressive polling hints** during device-flow wait: the spinner + surfaces targeted help at T+30s / T+90s / T+4min so the YC-founder + first-run doesn't hit a silent 3-minute staring contest. + +### Changed +- **Auth backend migrated from Supabase Auth to Better Auth.** The CLI + and the hosted API now authenticate via Better Auth (bearer + magic-link + + device-authorization plugins). The `~/.helpbase/auth.json` shape and + `HELPBASE_TOKEN` env contract are preserved — no action required for + existing installs. Emails now deliver via Resend. +- `helpbase login` auto-detects headless environments (Codespaces, + SSH sessions) and skips the browser spawn; prints the URL for manual + copy-paste instead. Override with `HELPBASE_LOGIN_NO_BROWSER=1` in + any environment. + +### Fixed +- `~/.helpbase/auth.json` is now force-narrowed to mode `0600` on every + write (previously only on file creation, which left stale-permissioned + files loose on shared dev machines). + +### Security +- `mcp_public_token` is no longer readable by the anon Supabase key. + The `tenants` table lost its anon SELECT grant; anon-facing reads go + through a new `tenants_public` view that projects only id/slug/name/ + active/theme_config. Closes a pre-existing leak where the embedded + CLI anon key could enumerate every active tenant's MCP bearer. +- Resend API key is now required in production. Without it, the auth + config fails boot rather than silently printing magic-link URLs to + Vercel Runtime Logs (dev-mode console fallback is gated on + `NODE_ENV !== "production"`). + +### Internal +- `packages/cli/src/lib/auth.ts` split into `auth.ts` (session core) + + `auth-device.ts` (device-flow state machine). 387 → 265 LOC on the + main file. +- 41 new tests across 4 new suites covering the auth surface: + `extractVerificationToken`, `deviceLogin`, `pollDeviceAuth`, + `consumeMagicLink`, `verifyLoginFromMagicLink`, `getCurrentSession`, + `withAuthAndQuota`, and the CLI `toAuthSession` factory. +- Removed the CLI's dependency on `@supabase/supabase-js`. The CLI now + talks to helpbase.dev over plain `fetch`. Lean install, one less + auth chain to maintain. + ## [helpbase 0.4.1] — 2026-04-17 ### Fixed diff --git a/DEVICE_FLOW_PLAN.md b/DEVICE_FLOW_PLAN.md new file mode 100644 index 0000000..8a09c06 --- /dev/null +++ b/DEVICE_FLOW_PLAN.md @@ -0,0 +1,489 @@ +# Device-flow login — migrate auth to Better Auth, then wire `helpbase login` to the device-authorization plugin + +Source: 2026-04-17 dogfood of `helpbase@0.4.1` (URL-paste fallback) revealed three context switches on every login. Captured as **TODO-020**. Initial plan drafted a custom device-flow on top of Supabase. `/plan-eng-review` + context7 research (`/websites/better-auth`) found that Better Auth ships first-class `deviceAuthorization` and `bearer` plugins that implement RFC 8628 natively, and ships an official Supabase migration script. The auth-provider seam at `packages/cli/src/lib/auth.ts:11–16` already anticipates this migration with the comment *"When helpbase migrates to Better Auth, only this file needs to change."* + +Decision (2026-04-17): migrate first, ship device flow second. Two PRs. **Email transport switches to Resend** as part of PR 1 (eliminates the Supabase-email-template fragility that started this thread). User base is n=1 (the founder), so migration cost is at its lifetime minimum. + +--- + +## Problem + +`helpbase login` today: +1. CLI prompts for email. +2. Supabase sends a magic-link email (URL only — Supabase's default template has no 6-digit code). +3. User leaves the terminal, opens email, copies URL. +4. Pastes URL back in terminal. +5. CLI parses `access_token` / `refresh_token` out of the URL fragment, writes `~/.helpbase/auth.json`. + +Three context switches. Fragile on email clients that rewrite `#fragment`. New users' first-touch surface is this friction. The scaffolder (`create-helpbase@0.3.1`) now runs `helpbase login` inline, so the friction is in `create-helpbase`'s TTHW path too. + +The proper fix is a `gh auth login --web` / `claude login` / `supabase login` style browser-bounce flow. Which is exactly what Better Auth's `deviceAuthorization` plugin implements. + +## Strategy — two PRs + +**PR 1: Migrate auth from Supabase to Better Auth.** No new features. The existing magic-link-URL-paste CLI login UX is preserved — just powered by Better Auth's `magicLink` plugin (with Resend as the email transport) instead of Supabase's `signInWithOtp`. Validate end-to-end, then merge + deploy. + +**PR 2: Add the `deviceAuthorization` server plugin + swap the CLI to `deviceAuthorizationClient`.** Strictly additive on top of PR 1. ~60 lines of CLI code, plugin owns the device-code / user-code / expiry / atomic-consume state machine. + +Staging is the deliberate risk control. A broken migration doesn't block the device-flow feature. A broken device-flow doesn't require rolling back the migration. Each PR is reviewable in <1 hour. + +## Goal + +End state after both PRs: + +- `helpbase login` default: opens the browser, user signs in (or is already signed in on helpbase.dev), clicks Authorize (with user-code shown for phishing defense), terminal picks up the bearer token, writes `~/.helpbase/auth.json`. Under 10 seconds on the fast path. +- `helpbase login --email` still works as the CI / sandboxed-env fallback, now powered by Better Auth magic-link. +- `apps/web` runs on Better Auth. Supabase's `auth.users` table is no longer authoritative; Better Auth's `user` / `session` / `account` tables are. Supabase-as-database stays (for tenant content, `llm_usage_events`, `global_daily_tokens`, etc.) — only the auth layer moves. +- Email transport is Resend. Zero dependency on Supabase email template config. +- Existing `HELPBASE_TOKEN` env shape preserved (opaque bearer token). + +--- + +## What already exists (reconciled with current code) + +- `packages/cli/src/lib/auth.ts` — `AuthSession`, `getCurrentSession`, `storeSession`, `loadStoredSession`, `clearStoredSession`, `isNonInteractive`. Provider-agnostic surface by design. The `client.auth.setSession` calls get replaced with `authClient.getSession({ headers: { Authorization: ... } })`. +- `packages/cli/src/lib/supabase-client.ts` — deleted in PR 1. Replaced by a thin `better-auth/client` factory in a new `packages/cli/src/lib/auth-client.ts`. +- `apps/web/lib/supabase-admin.ts:36` — `verifyBearerToken(token)`. Replaced by `auth.api.getSession({ headers })` (Better Auth bearer plugin pattern). One-line swap in every call site. +- `apps/web/lib/supabase.ts` — stays. Still used for tenant content + LLM usage counters. Not auth. +- `apps/web/app/api/v1/llm/_shared.ts:36` — `withAuthAndQuota`. Swap the token verification line. Rest of the function (quota, limits, wire error envelope) is unchanged. +- `apps/web/lib/rate-limit.ts:43` — unchanged. Still the per-IP / per-tenant pattern. Prior learning `rate-limit-fire-and-forget-write` still applies. +- `packages/create-helpbase/src/index.ts:794` — `openBrowser` helper. In PR 2 we reuse `open` from npm (Better Auth's docs use it) and delete the inline platform-branch helper. Or keep ours and skip the `open` dep. TBD in PR 2. +- Existing Supabase DB tables: `llm_usage_events`, `global_daily_tokens`, `tenants`, `tenant_articles`. These reference `auth.users.id`. We preserve user IDs during migration, so FKs keep working. + +--- + +## PR 1 — Supabase auth → Better Auth + Resend + +### 1.1 Install + configure Better Auth on `apps/web` + +**Files:** +- New: `apps/web/lib/auth.ts` — `betterAuth()` config. Postgres pool pointing at the same Supabase DB (standard Better Auth + Supabase-as-database pattern). Plugins: `magicLink`, `bearer`. +- New: `apps/web/lib/auth-client.ts` — server-side `authClient` for route handlers if needed. +- New: `apps/web/app/api/auth/[...all]/route.ts` — Better Auth's catch-all route handler (per Better Auth Next.js docs). +- Modify: `apps/web/package.json` — add `better-auth`, `resend`, `@auth/better-auth-cli` (for schema generation). + +```ts +// apps/web/lib/auth.ts +import { betterAuth } from "better-auth" +import { magicLink, bearer } from "better-auth/plugins" +import { Pool } from "pg" +import { Resend } from "resend" + +const resend = new Resend(process.env.RESEND_API_KEY!) + +export const auth = betterAuth({ + database: new Pool({ connectionString: process.env.DATABASE_URL! }), + plugins: [ + bearer(), + magicLink({ + sendMagicLink: async ({ email, url }) => { + await resend.emails.send({ + from: "helpbase ", + to: email, + subject: "Sign in to helpbase", + text: `Click to sign in: ${url}\n\nThis link expires in 10 minutes.`, + }) + }, + }), + ], + trustedOrigins: ["https://helpbase.dev", "http://localhost:3000"], +}) +``` + +**Env additions (Vercel + local):** +- `DATABASE_URL` — Postgres connection string for the Supabase DB. Pooler URL from Supabase project settings. Already available, just needs to be added to Vercel env. +- `RESEND_API_KEY` — new. +- `BETTER_AUTH_SECRET` — random 32-byte base64, for session signing. +- `BETTER_AUTH_URL` — `https://helpbase.dev` in prod, `http://localhost:3000` in dev. + +`NEXT_PUBLIC_SUPABASE_URL` / `NEXT_PUBLIC_SUPABASE_ANON_KEY` stay — still used for tenant content + LLM usage tables. `SUPABASE_SERVICE_ROLE_KEY` stays for the same reason. + +### 1.2 Schema — Better Auth tables alongside Supabase tables + +Better Auth owns its own `user`, `session`, `account`, `verification` tables in the public schema. These live **alongside** Supabase's `auth.users`. During migration we copy `auth.users` → `public.user` preserving IDs. Post-migration, Supabase's `auth.users` is no longer written to; `public.user` is authoritative. + +**Files:** +- New: `apps/web/drizzle/schema.ts` — Better Auth-generated schema (via `npx @better-auth/cli generate`). +- New: `apps/web/drizzle/migrations/0001_init_better_auth.sql` — generated migration. +- Modify: `apps/web/package.json` — add `drizzle-orm` + `drizzle-kit` (Better Auth's recommended schema tool). Or use plain SQL migrations if we prefer to keep the dep list lean. + +**FK reconciliation:** +- `llm_usage_events.user_id` references `auth.users(id)` today. After migration, point the FK at `public.user(id)` via `ALTER TABLE llm_usage_events DROP CONSTRAINT ... ADD CONSTRAINT ... REFERENCES public.user(id);`. IDs are preserved so no row breaks. +- `tenants.user_id` (if any) — same treatment. +- Run as part of the migration SQL; keep idempotent with `IF EXISTS` guards. + +### 1.3 Migration script + +Adapt Better Auth's official Supabase migration guide (`https://better-auth.com/docs/guides/supabase-migration-guide`): + +**Files:** +- New: `scripts/migrate-to-better-auth.mjs` — batch reader over `auth.users`, maps each row to Better Auth's `user` + `account` shape, inserts via the Better Auth internal adapter (or raw INSERTs — both are documented paths). Batch size 5000, cursor-based resume via `lastProcessedId`. +- Preserves: `id` (critical for FK), `email`, `emailVerified` (from `email_confirmed_at`), `name` (from `raw_user_meta_data.full_name` or email prefix), `createdAt`, `updatedAt`. +- One-shot run against prod — user base is n=1 so this is a single-row migration in practice. Test data preserved in case we get test users between now and ship. +- Idempotent via `ON CONFLICT (id) DO NOTHING`. + +**Acceptance:** +- `SELECT count(*) FROM auth.users` = `SELECT count(*) FROM public."user"` after migration. +- `select email from public.user where email = 'christer.hagen@gmail.com'` returns one row. +- Post-migration, `SELECT id FROM llm_usage_events` + `SELECT id FROM public.user` join cleanly (FK works). + +### 1.4 Rewire `/api/v1/llm/*` auth + +**Files:** +- Modify: `apps/web/app/api/v1/llm/_shared.ts` — replace `verifyBearerToken(token)` call with `auth.api.getSession({ headers: req.headers })`. The function already expects a session-shaped return; adapt the return type. +- Delete: `apps/web/lib/supabase-admin.ts:36` — `verifyBearerToken`. Replaced. +- Keep: `apps/web/lib/supabase-admin.ts:15` — `getServiceRoleClient`. Still needed for `llm_usage_events` insert + `global_daily_tokens` RPC. + +**Contract preserved:** +- CLI sends `Authorization: Bearer `. That still works — `bearer()` plugin intercepts it. +- `userId` / `email` returned from session verification stays the same shape. The rest of `withAuthAndQuota` (quota math, limits, wire error envelope) doesn't change. + +### 1.5 CLI rewire (preserves 0.4.1 UX) + +**Files:** +- New: `packages/cli/src/lib/auth-client.ts` — creates `authClient` via `createAuthClient({ baseURL: "https://helpbase.dev", plugins: [bearerClient()] })`. Replaces `getAnonSupabase`. +- Modify: `packages/cli/src/lib/auth.ts` — replace the five Supabase calls: + - `sendLoginCode(email)` → `authClient.signIn.magicLink({ email, callbackURL: "/login/cli/success" })`. + - `verifyLoginFromMagicLink(url)` → parse the same token params out of the URL fragment (Better Auth's magic-link callback writes compatible params) OR call `authClient.magicLink.verify({ token })` if the URL carries a `token` query param (check Better Auth's magic-link output format during implementation). + - `verifyLoginCode(email, code)` → Better Auth's magic-link is URL-only by default; if we want a 6-digit code, there's `otp()` plugin. PR 1 just mirrors today's URL-paste path; `verifyLoginCode` becomes a stub that throws "unsupported — paste the URL from the email". + - `resolveTokenSession(token)` → `authClient.getSession({ fetchOptions: { headers: { Authorization: \`Bearer ${token}\` } } })`. + - `getCurrentSession` refresh path → Better Auth handles refresh server-side; CLI just re-calls `getSession` and persists the response. +- Delete: `packages/cli/src/lib/supabase-client.ts`. No longer needed. +- Modify: `packages/cli/package.json` — remove `@supabase/supabase-js`, add `better-auth`. + +**What the user sees on PR 1:** +- `helpbase login` — same as today. Email prompt → email arrives from `login@helpbase.dev` (Resend, not Supabase) → user pastes URL → "Logged in as christer.hagen@gmail.com". Zero UX delta. Email template is now our own HTML (one `sendMagicLink` function to edit). + +### 1.6 Dev + CI + +**Files:** +- Modify: `apps/web/.env.example` — document new env vars. +- Modify: `README.md` — document Better Auth env setup in the "Local development" section. +- Modify: `scripts/smoke-install.sh` — add an auth smoke that hits `/api/auth/session` on the scaffolded app. +- Modify: `.github/workflows/ci.yml` — add `BETTER_AUTH_SECRET` + `RESEND_API_KEY` (mocked in CI) to the test matrix. + +### 1.7 Ship + +- Merge to `main` → Vercel auto-deploys (`vercel_auto_deploy` memory). +- Dogfood: `rm -f ~/.helpbase/auth.json && helpbase login` end-to-end. Email from Resend lands, URL pastes, CLI writes token, `/api/v1/llm` accepts it. +- **Do not delete** Supabase's `auth.users` table post-migration — leave it as a read-only backup for 30 days. Cleanup is a follow-up TODO. + +### 1.8 PR 1 success criteria + +- `helpbase login` works end-to-end via Better Auth + Resend. UX identical to 0.4.1. +- `curl -H "Authorization: Bearer $(jq -r .access_token ~/.helpbase/auth.json)" https://helpbase.dev/api/v1/usage/today` returns the quota snapshot. +- Fresh user: `helpbase login` with a new email → Better Auth creates a `public.user` row, `auth.users` stays untouched. +- Existing code path: `pnpm dlx create-helpbase@latest foo` → pick "A code repository" → pick "Log in" → same user-visible flow as before. +- `pnpm -F web test && pnpm -F helpbase test` green. + +--- + +## PR 2 — Device authorization plugin + OAuth providers + CLI `authClient.device.*` + +Strictly additive. Requires PR 1 to be merged + deployed. + +**DX review (2026-04-17) raised the bar on PR 2.** Three additions folded in: +1. **OAuth providers (Google + GitHub)** to drop cold-path TTHW from ~60s (magic-link round-trip) to ~15s (one-click sign-in). Eliminates the email round-trip entirely for the 100% of first-time scaffolder users who aren't yet cookied on helpbase.dev. +2. **Tier-3 error catalog** — 6 structured error codes with matching `/errors/[code]` pages and telemetry drop-off logging. Mirrors the pattern shipped for `helpbase sync` + `helpbase context`. +3. **Progressive polling hints** — CLI surfaces contextual help at T+30s, T+90s, T+4min while waiting on browser approval, so the YC-founder persona never hits the 3-minute silent-spinner abandonment zone. + +### 2.1 Add `deviceAuthorization` server plugin + +**Files:** +- Modify: `apps/web/lib/auth.ts` — append `deviceAuthorization()` to the plugins array. +- Generated: `apps/web/drizzle/migrations/0002_device_authorization.sql` — Better Auth writes the `deviceCode` table migration automatically via `npx @better-auth/cli generate`. + +Plugin config: +```ts +deviceAuthorization({ + expiresIn: "5m", + interval: "2s", + // The browser-facing page path that the user visits. + // Better Auth mounts its own /device endpoint; we customize the UI via our route. + verificationUri: "/device", +}) +``` + +### 2.1b OAuth providers (Google + GitHub) + +**Files:** +- Modify: `apps/web/lib/auth.ts` — add `socialProviders: { google: {...}, github: {...} }` to the `betterAuth()` config. +- Modify: `apps/web/.env.example` — document `GOOGLE_CLIENT_ID`, `GOOGLE_CLIENT_SECRET`, `GITHUB_CLIENT_ID`, `GITHUB_CLIENT_SECRET`. +- Modify: `apps/web/app/device/AuthorizeDeviceClient.tsx` — when user is signed-out, show three buttons: "Continue with Google", "Continue with GitHub", "Sign in with email" (collapses the magic-link form to secondary). + +**Pre-merge operator work (documented in plan, not in code):** +- Create a Google OAuth 2.0 Client in the Google Cloud console. Authorized redirect URI: `https://helpbase.dev/api/auth/callback/google` + local dev. Verified domain requirements noted in Better Auth docs. +- Create a GitHub OAuth App at github.com/settings/developers. Callback URL: `https://helpbase.dev/api/auth/callback/github` + local dev. +- Add the four env vars to Vercel prod + the local `.env.local`. + +**trustedOrigins dynamic construction:** +```ts +trustedOrigins: [ + "https://helpbase.dev", + "http://localhost:3000", + process.env.VERCEL_URL ? `https://${process.env.VERCEL_URL}` : null, +].filter(Boolean), +``` +So preview deploys can authenticate. + +**What the cold-path user sees:** +1. `helpbase login` → browser opens at `/device?user_code=ABCD-EFGH`. +2. Not signed in → three buttons. +3. Click "Continue with Google" → Google consent screen (if not already consented) → redirect back to `/device?user_code=ABCD-EFGH` signed-in → Authorize card → click → done. +4. Cold-path TTHW: ~15s. Matches `gh auth login --web`. + +**Email fallback preserved.** If the user prefers magic-link (corporate SSO restriction, privacy preference), the third button works unchanged. + +### 2.2 Browser-facing page + +**Files:** +- New: `apps/web/app/device/page.tsx` — server component. If the user is not signed in (no Better Auth session cookie), show inline magic-link sign-in (same `` component PR 1 built for the standalone `/login` page). If signed in, show ``. +- New: `apps/web/app/device/AuthorizeDeviceClient.tsx` — client component. Reads `user_code` from `?user_code=` (pattern from the plugin). Displays: + - "You're signing the helpbase CLI in. Code: **ABCD-EFGH**" + - "Signed in as ``." + - Buttons: "Authorize" / "Cancel". + - On Authorize: `authClient.device.approve({ userCode })`. On Cancel: `authClient.device.deny({ userCode })`. + - On success: "Done. Return to your terminal." Auto-close tab after 2s. + +**Phishing defense comes for free:** the user-code shown on the page matches what the CLI printed in the terminal. User compares; if they don't match, this is a phishing URL. + +### 2.3 CLI device-flow + +**Files:** +- Modify: `packages/cli/src/commands/login.ts` — port the device-flow state machine from Better Auth's docs, but **do NOT copy the `console.log` + emoji output verbatim**. Reshape through our existing UI helpers (`intro`, `note`, `spinner`, `pc.cyan`) so the output matches the voice of `helpbase new` / `helpbase context`. +- Modify: `packages/cli/src/lib/auth-client.ts` — add `deviceAuthorizationClient()` to the plugin list. +- Add `--email` option on `login` command that preserves the PR 1 magic-link-URL-paste flow (escape hatch for CI / sandboxed envs). +- New util: `packages/cli/src/lib/open-browser.ts` — extract the existing platform-branched helper from `create-helpbase/src/index.ts:794–809` (DRY). Avoid adding the `open` npm dep (~150KB) — we already have a working 15-line helper that handles `darwin`/`win32`/`linux`. +- Respect `HELPBASE_LOGIN_NO_BROWSER=1` env: skip auto-open, print URL + user-code for manual entry. +- **Auto-detect browser-less environments** and set the same behavior. Check `process.env.CODESPACES === "true"`, `process.env.SSH_TTY`, `process.env.SSH_CONNECTION`. When detected, print a one-line "Detected remote session — skipping auto-open" and fall through to the URL-print path. + +**Terminal output shape (post-voice-adjustment):** +``` +┌ helpbase login +│ +◆ Opening your browser to authorize… +│ URL: https://helpbase.dev/device?user_code=ABCD-EFGH +│ Code: ABCD-EFGH +│ +│ (compare this code to what the browser shows — if they differ, cancel +│ and run `helpbase login` again in a fresh terminal) +│ +◇ Waiting for browser approval… +│ +└ Logged in as me@company.com +``` + +**Progressive polling hints.** The spinner text updates on a timer regardless of polling activity: +- **T+0s:** "Waiting for browser approval…" +- **T+30s:** "Still waiting… check that a browser tab opened. URL: https://helpbase.dev/device?user_code=ABCD-EFGH" +- **T+90s:** "Taking longer than usual? Cancel with Ctrl-C, then run `helpbase login --email` for the fallback." +- **T+4min:** "1 minute until this code expires." +- **T+5min:** exits with `E_DEVICE_EXPIRED` (see error catalog below). + +Implemented as a `setInterval` inside `pollForToken` that rewrites the clack spinner message at each threshold. No extra polling load on the server — these are purely client-side. + +### 2.3b Error catalog (Tier 3) + +Six error codes, each with inline CLI copy (problem + cause + fix + docs link), a `helpbase.dev/errors/[code]` page (reuse `apps/web/app/(main)/errors/[code]/page.tsx`), and a telemetry event (opt-in via existing consent, logs the code + duration_ms_before_error). Prior learning `error-messages-need-working-links` — each docs page must ship in the same PR as the error, not later. + +| Code | When | CLI message (abbreviated) | Docs page | +|---|---|---|---| +| `E_DEVICE_DENIED` | User clicks Cancel in browser | "Cancelled. Run `helpbase login` again when you're ready." | `/errors/e-device-denied` | +| `E_DEVICE_EXPIRED` | 5-min code TTL hit | "Device code expired. Run `helpbase login` again." | `/errors/e-device-expired` | +| `E_DEVICE_NETWORK` | /device/token fetch fails after 3 retries | "Couldn't reach helpbase.dev. Check your network, then retry. `helpbase login --email` also works offline-to-email." | `/errors/e-device-network` | +| `E_DEVICE_NO_BROWSER` | Auto-detect browser-less OR `openBrowser` throws | "No browser detected. Open this URL manually: . Code: ." | `/errors/e-device-no-browser` | +| `E_LOGIN_RESEND_DOWN` | `sendMagicLink` returns Resend error (PR 1 surface) | "Couldn't send sign-in email. Resend error: . Try again in a minute." | `/errors/e-login-resend-down` | +| `E_LOGIN_STALE_TOKEN` | `~/.helpbase/auth.json` present but `getSession` returns null | "Your previous session expired. Starting a fresh login…" (non-fatal — flow continues into login) | `/errors/e-login-stale-token` | + +**Telemetry field:** each error captures `{ code, duration_ms_before_error, stage: "pre-browser" | "polling" | "post-approve" }` into the existing telemetry pipeline. Lets us measure drop-off by stage and iterate error copy. + +**Files:** +- New: `apps/web/app/(main)/errors/e-device-denied/page.tsx` + 5 others (one per code). Each page: "What happened / Why / What to do / What to try instead" four-section layout matching the existing `/errors/e-no-citations` pattern. +- Modify: `packages/cli/src/lib/errors.ts` — register the 6 codes. +- Modify: `packages/cli/src/lib/telemetry.ts` — add `logLoginError(code, fields)` helper. + +### 2.3c Stale-session UX (PR 1 + PR 2 shared) + +If the CLI detects a token on disk but `authClient.getSession` returns null (stale post-migration, expired, or revoked), do NOT silently re-prompt. Print one line first: + +``` +◇ Your previous session expired. Starting a fresh login… +``` + +Then proceed into the device-flow. Friction-point-free. + +### 2.4 Scaffolder inherits the new flow + +`packages/create-helpbase/src/index.ts:749–770` (`runHelpbaseLogin`) just spawns `helpbase login`. Zero changes needed. The moment `helpbase@0.5.0` ships, the scaffolder's "Log in" branch bounces through the browser automatically. + +### 2.5 Tests + +**Files:** +- New: `packages/cli/src/lib/__tests__/device-auth.test.ts` — mocks `authClient.device.*`, covers happy-path polling, `authorization_pending`, `slow_down`, `access_denied`, `expired_token`, `HELPBASE_LOGIN_NO_BROWSER`, Codespaces/SSH auto-detect, each of the 6 error codes, progressive-hint thresholds (fake timers). +- New: `apps/web/app/device/__tests__/page.test.tsx` — renders the server component for signed-in / signed-out / unknown-code cases, plus the OAuth-provider button render paths. +- New: `apps/web/app/(main)/errors/__tests__/device-errors.test.tsx` — smoke-renders each of the 6 error pages (catches the error-link-must-work-pre-ship regression). +- Modify: `scripts/smoke-install.sh` — add a `--device-login` mode with a mocked-auth server. + +### 2.6 Ship + +- Publish `helpbase@0.5.0`. +- CHANGELOG: "`helpbase login` now uses a browser device-flow. Legacy magic-link path preserved behind `--email`." +- Dogfood the full `pnpm dlx create-helpbase` flow → pick repo → pick Log in → browser bounces, Authorize click, cited docs at localhost:3000. No email involvement on the happy path. +- Save findings to memory. +- Rewrite `project_vegard_walkthrough.md` to drop the "check your email" step. + +### 2.7 PR 2 success criteria + +**TTHW (measurable):** +- Warm path (cookied on helpbase.dev): ≤10s end-to-end, ≤15s p95. +- Cold path via Google/GitHub OAuth: ≤20s end-to-end (first-time-only consent screen adds ~5s). +- Cold path via email fallback: ≤75s including email delivery round-trip. +- `pnpm dlx create-helpbase` → repo → Log in → OAuth → cited docs at localhost:3000: ≤2min total (Champion tier). + +**Behavior:** +- User-code shown in both CLI and browser; docs/error messages tell users to compare them. +- `HELPBASE_LOGIN_NO_BROWSER=1 helpbase login` prints URL + user-code and polls. Auto-detects `CODESPACES=true`, `SSH_TTY`, `SSH_CONNECTION` and behaves the same without the env var. +- `helpbase login --email` still runs the PR 1 magic-link-paste flow unchanged. +- All 6 error codes render a matching `/errors/[code]` page on helpbase.dev (no 404 links). +- Progressive polling hints fire at the documented T+30/90/240s thresholds. +- First-run post-migration: stale-token users see the "previous session expired" message, not a silent re-prompt. + +**Instrumentation:** +- `login_duration_ms` telemetry event (opt-in, respects existing consent). Fields: `{ path: "warm" | "oauth-google" | "oauth-github" | "email", duration_ms, outcome: "success" | "" }`. +- After 20 real login events, we have a measured distribution to compare against the claims above. Feeds the post-ship `/devex-review` boomerang. + +### 2.8 Docs updates (PR 2) + +**Files:** +- Modify: `README.md` — quickstart now mentions "the CLI opens a browser and shows a short code; compare it to the browser." One sentence, sets expectation. +- Modify: `packages/cli/README.md` — add a "Logging in" section covering the three paths (default device flow, `--email` fallback, `HELPBASE_TOKEN` for CI). +- Modify: `apps/web/content/getting-started/installation.mdx` — mirror the README update. +- Modify: `project_vegard_walkthrough.md` — strip the "check your email" step; walkthrough now reads "click Authorize in the browser tab that just opened." + +--- + +## Failure modes (both PRs combined) + +| Codepath | Failure | Caught? | User sees | +|---|---|---|---| +| Resend API down | Magic-link email never sends | Yes (Resend returns error) | `sendMagicLink` surfaces the error, CLI prints "Couldn't send sign-in email. Try again or paste a URL." | +| `/api/auth/*` 500 | Better Auth bug | Yes | CLI sees fetch error, prints "Couldn't reach helpbase.dev — check your network or run `helpbase login --email`." | +| Migration script — duplicate email conflict | `ON CONFLICT (id) DO NOTHING` skips rows | Partial — logged | Script prints per-row outcome; Christer's row is the only real one | +| FK repoint fails mid-migration | Transactional BEGIN/COMMIT | Yes | Migration aborts, Supabase auth still primary, rollback trivial | +| `authClient.device.code` errors | Plugin returns standard `error.error_description` | Yes | CLI prints a human-readable message and exits 1 | +| Polling: `slow_down` | Plugin's standard response | Yes | CLI increases interval (per Better Auth's docs) | +| Polling: `expired_token` | Row TTL hit | Yes | CLI prints "Login timed out — run `helpbase login` again" | +| Browser `open` fails (no xdg-open / missing util) | — | Yes | URL + user-code always printed to stdout first; user copies manually | +| User denies authorization in browser | `access_denied` from plugin | Yes | CLI prints "Cancelled." and exits 0 | +| User closes browser tab mid-flow | Row expires after 5min | Yes | Same as `expired_token` | +| Phishing: attacker sends victim a `/device?user_code=...` URL | User-code display is the whole defense | Yes | Victim compares user-code to their own terminal; mismatch = don't click | +| `RESEND_API_KEY` missing in prod | Better Auth boot fails | Yes | Vercel build / runtime error surfaces; operator gets clear log | +| `DATABASE_URL` not set | Better Auth can't boot | Yes | Vercel env check fails at deploy time | +| Stale `~/.helpbase/auth.json` with Supabase-format token post-migration | `auth.api.getSession` returns null | Yes | CLI falls back to unauthed state, prompts re-login | + +--- + +## Risks / open questions (eng) + +1. **Migration atomicity.** Copying `auth.users` → `public.user` + re-pointing FKs is a multi-statement operation. Wrap in a transaction. Back up `auth.users` before running (`pg_dump` of the `auth` schema). Test on a Supabase branch DB first (Supabase branches are cheap). + +2. **Better Auth + Supabase Postgres pooler compatibility.** Supabase's pooler is PgBouncer in transaction mode, which doesn't support session-level features like `LISTEN`. Better Auth uses the standard `pg` Pool — no `LISTEN` — so should be fine. Confirm by running migration script against a Supabase branch before prod. + +3. **`bearer()` plugin semantics.** The token Better Auth issues is a long random string (not a JWT). `~/.helpbase/auth.json` schema stays compatible because the CLI treats tokens opaquely — but `expiresAt` handling may shift. Check Better Auth's session expiry defaults and update the CLI's refresh logic if needed. + +4. **Refresh tokens.** Better Auth uses rolling session cookies server-side; the bearer token surface may or may not expose a separate refresh token. Need to verify during PR 1 implementation. If no refresh token, CLI just re-runs `login` when the bearer expires (default 7 days) — acceptable. + +5. **Resend sender domain.** `login@helpbase.dev` requires the `helpbase.dev` domain to be verified in Resend (SPF + DKIM). Takes ~10 min + a DNS change. Add as pre-merge prerequisite for PR 1. + +6. **`@better-auth/cli generate` output format.** Better Auth recommends Drizzle but also supports raw SQL. If we add `drizzle-kit`, that's a new framework in the stack (innovation token?). Cheap alternative: use Better Auth's `generate --sql` flag and land a plain `.sql` migration, skip Drizzle entirely. Prefer plain SQL unless we hit friction. + +7. **`trustedOrigins` list.** Must include every Vercel preview URL pattern, or preview deploys can't authenticate. Use `VERCEL_URL` env in the `trustedOrigins` array construction (dynamic). + +8. **`deviceAuthorization` plugin's `client_id` semantics.** The docs use `"demo-cli"`. We need a stable one like `"helpbase-cli"`. Per the plugin, `client_id` is not a secret — it identifies the CLI to the user-facing page for display purposes. + +9. **Session cookie vs bearer on the browser page.** Better Auth uses cookies by default on the browser. The device-flow approve endpoint reads the cookie session server-side. No token-in-body carriage needed. + +10. **Rollback plan.** PR 1 rollback: revert the `_shared.ts` + `auth.ts` + CLI commits, keep the DB tables (they're additive — no data lost). PR 2 rollback: revert the `login.ts` commit; `helpbase login --email` still works. Both PRs are trivially revertable. + +--- + +## NOT in scope (deferred) + +- **2FA / passkeys.** Better Auth has `twoFactor()` and `passkey()` plugins. Skip for v1. +- **Delete Supabase `auth.users`.** Leave as a read-only backup for 30 days. Cleanup is a separate TODO. +- **Session introspection UI on helpbase.dev** (list devices / revoke). Needs a signed-in dashboard, which we don't have. Post-Vegard. +- **Phone-number / SMS magic link.** Supabase supports it; Better Auth has a `phoneNumber()` plugin; current users don't need it. +- **Migration of `llm_usage_events` user_id semantics.** They reference user IDs we're preserving — no migration needed. Flag if FK breaks during implementation. + +--- + +## Success criteria (both PRs shipped) + +**PR 1 alone (magic-link UX unchanged):** +- `helpbase login` with a fresh email creates a row in `public.user` (not `auth.users`). +- Resend delivers the sign-in email from `login@helpbase.dev`. +- `/api/v1/llm/generate-object` + `/generate-text` accept the Better Auth bearer token with no API shape change. +- Supabase `auth.users` row count is ≥ `public.user` row count (never fewer — migration is copy, not move). +- FK: `select llm_usage_events.user_id from llm_usage_events join public.user on public.user.id = llm_usage_events.user_id` works for all existing rows. +- `pnpm dlx create-helpbase@latest foo` with "Log in" branch picks up the new auth transparently. + +**PR 2 additionally:** +- `helpbase login` fast path (cookied on helpbase.dev): under 10s end-to-end. +- User-code shown in both terminal + browser; docs/error messages tell user to compare them. +- `HELPBASE_LOGIN_NO_BROWSER=1` prints URL + user-code, polling still works. +- `helpbase login --email` runs the PR 1 magic-link-paste flow unchanged. +- `project_vegard_walkthrough.md` rewritten: "check your email" step deleted. + +--- + +## DX SCORECARD + +``` ++====================================================================+ +| DX PLAN REVIEW — SCORECARD | ++====================================================================+ +| Dimension | Pre | Post | Δ | +|----------------------|--------|--------|--------| +| Getting Started | 8/10 | 9/10 | +1 ↑ | +| API/CLI/SDK | 9/10 | 9/10 | — | +| Error Messages | 6/10 | 9/10 | +3 ↑ | +| Documentation | 7/10 | 8/10 | +1 ↑ | +| Upgrade Path | 8/10 | 9/10 | +1 ↑ | +| Dev Environment | 8/10 | 9/10 | +1 ↑ | +| Community | 6/10 | 6/10 | — | +| DX Measurement | 7/10 | 9/10 | +2 ↑ | ++--------------------------------------------------------------------+ +| TTHW warm | n/a | ≤10s | Champion | +| TTHW cold (OAuth) | ~60s | ≤20s | Champion | +| TTHW cold (email) | ~60s | ≤75s | Competitive | +| Competitive Rank | Champion on warm + OAuth, Competitive on email | +| Magical Moment | designed via copy-paste (create-helpbase) | +| Product Type | CLI Tool (primary) + Service (secondary) | +| Mode | POLISH | +| Overall DX | 7.4/10 | 8.5/10 | +1.1 ↑ | ++====================================================================+ +| DX PRINCIPLE COVERAGE | +| Zero Friction | covered (OAuth one-click cold path) | +| Learn by Doing | covered (scaffolder is the demo) | +| Fight Uncertainty | covered (6 error codes + /errors pages + hints)| +| Opinionated + Escape Hatches | covered (--email, NO_BROWSER env) | +| Code in Context | covered (scaffolder integration, not abstract) | +| Magical Moments | covered (cited docs from user's repo) | ++====================================================================+ +``` + +**Prior DX trend on main:** 8/10 (2026-04-17 autoplan). This plan moves the auth surface from "acceptable friction" to "first-class" — it's the product's first-touch surface, so the +1.1 lift is high-leverage. + +## GSTACK REVIEW REPORT + +| Review | Trigger | Why | Runs | Status | Findings | +|--------|---------|-----|------|--------|----------| +| CEO Review | `/plan-ceo-review` | Scope & strategy | 0 | — | Scope decided by user + context7: library adoption over custom roll | +| Codex Review | `/codex review` | Independent 2nd opinion | 0 | — | Skipped — revisit if PR 1 implementation surfaces unknowns | +| Eng Review | `/plan-eng-review` | Architecture & tests (required) | 1 | CLEAR (PLAN) | Pivoted from custom-device-flow to Better Auth; staged 2 PRs to de-risk migration + feature | +| Design Review | `/plan-design-review` | UI/UX gaps | 0 | — | One page + reused sign-in form; skipped | +| DX Review | `/plan-devex-review` | Developer experience gaps | 1 | CLEAR | 7.4 → 8.5, 3 gaps fixed: OAuth added (cold TTHW 60s→20s), Tier-3 error catalog (6 codes + docs + telemetry), progressive polling hints | + +**UNRESOLVED:** — +**CRITICAL GAPS:** — +**VERDICT:** ENG + DX CLEARED — ready to implement after user approval. Awaiting the STOP gate. diff --git a/README.md b/README.md index 201649c..e4363c6 100644 --- a/README.md +++ b/README.md @@ -432,6 +432,39 @@ Every package has its own `pnpm test`. Run the CLI locally with `pnpm --filter helpbase dev`, then use `node packages/cli/dist/index.js` from any directory to test against a scaffolded project. +### Local auth development + +helpbase auth runs on [Better Auth](https://better-auth.com) against the +same Supabase Postgres that backs tenant content. To run auth locally: + +1. **Copy the env template.** `cp apps/web/.env.example apps/web/.env.local` + and fill in the four auth values: + - `BETTER_AUTH_SECRET` — `openssl rand -base64 32` + - `BETTER_AUTH_URL` — `http://localhost:3000` (or whatever port Next picks) + - `DATABASE_URL` — Supabase dashboard → Project Settings → Database → + Connection string (Session / direct pooler). The migrations in + `scripts/migrate-auth-to-better-auth.sql` must already be applied + against this DB. + - `RESEND_API_KEY` — **leave blank**. Without it, magic-link URLs print + to the Next dev-server stderr so you can click them from your + terminal without signing up for a mail provider. + +2. **Start the web app.** `pnpm -F web dev`. +3. **Verify auth is live.** `curl localhost:3000/api/auth/ok` → `{"ok":true}`. +4. **Point the CLI at your local server.** Prefix any CLI invocation with + both env overrides: + ```bash + HELPBASE_BASE_URL=http://localhost:3000 \ + HELPBASE_PROXY_URL=http://localhost:3000 \ + node packages/cli/dist/index.js login + ``` + `HELPBASE_BASE_URL` is the auth endpoint root; `HELPBASE_PROXY_URL` is + the LLM/usage proxy root. In prod they're the same host; in dev you + set both to the local dev port. +5. **The magic link.** When you paste your email, watch the `pnpm -F web + dev` terminal — the verification URL shows up between `─── DEV MAGIC + LINK ───` fences. Paste the URL back into the CLI prompt to finish. + ## Testing the CLI against a real project ```bash diff --git a/apps/web/.env.example b/apps/web/.env.example new file mode 100644 index 0000000..86b1d85 --- /dev/null +++ b/apps/web/.env.example @@ -0,0 +1,44 @@ +# ----------------------------------------------------------------------------- +# helpbase.dev (apps/web) environment variables +# Copy to .env.local for local development. Real values go in Vercel env. +# ----------------------------------------------------------------------------- + +# ── Better Auth ────────────────────────────────────────────────────────────── +# Encryption secret for session cookies. Min 32 chars. +# generate: openssl rand -base64 32 +BETTER_AUTH_SECRET= + +# Base URL of the running web app. In dev, http://localhost:3000. +BETTER_AUTH_URL=http://localhost:3000 + +# ── Database ───────────────────────────────────────────────────────────────── +# Postgres connection string for the Better Auth tables (user/session/account/ +# verification). Uses the same Supabase project as NEXT_PUBLIC_SUPABASE_URL. +# Supabase dashboard → Project Settings → Database → Connection string +# Use the "direct" (session) connection, not the pooler — Better Auth's +# built-in migrations need session-level features that PgBouncer transaction +# mode doesn't support. For runtime, the pooler is fine; for migrations, use +# direct. +DATABASE_URL= + +# ── Email (Resend) ─────────────────────────────────────────────────────────── +# Resend API key for transactional emails (magic-link sign-in). +# get at resend.com/api-keys +# If unset in local dev, magic links are printed to the server console (stderr) +# so you can click them from your terminal without signing up for Resend. +RESEND_API_KEY= + +# From-address for sign-in emails. Requires the domain to be verified in Resend. +RESEND_FROM_EMAIL="helpbase " + +# ── Supabase (existing — used for tenant content, NOT auth) ────────────────── +NEXT_PUBLIC_SUPABASE_URL= +NEXT_PUBLIC_SUPABASE_ANON_KEY= +SUPABASE_SERVICE_ROLE_KEY= + +# ── Tenant routing ─────────────────────────────────────────────────────────── +NEXT_PUBLIC_ROOT_DOMAIN=helpbase.dev + +# ── Vercel KV (rate limiting) ──────────────────────────────────────────────── +KV_REST_API_URL= +KV_REST_API_TOKEN= diff --git a/apps/web/app/(main)/errors/[code]/page.tsx b/apps/web/app/(main)/errors/[code]/page.tsx index 0c80d7b..97e942f 100644 --- a/apps/web/app/(main)/errors/[code]/page.tsx +++ b/apps/web/app/(main)/errors/[code]/page.tsx @@ -362,6 +362,58 @@ const ERRORS: Record = { "Check status.anthropic.com / openai.com if the problem persists.", ], }, + + // ── Device-authorization flow (RFC 8628) ────────────────────────────── + "e-auth-cancelled": { + code: "E_AUTH_CANCELLED", + title: "Login cancelled", + summary: "You aborted `helpbase login` before the browser finished authorizing.", + causes: [ + "You pressed Ctrl-C during the spinner.", + "A programmatic signal interrupted the CLI's polling loop.", + ], + fixes: [ + "Run `helpbase login` again when you're ready to sign in.", + "If you meant to use the email fallback, run `helpbase login --email`.", + ], + }, + "e-device-denied": { + code: "E_DEVICE_DENIED", + title: "Authorization was cancelled in the browser", + summary: + "You clicked Cancel (or closed the tab) on the /device approval page before finishing sign-in.", + causes: [ + "The browser tab was closed before Authorize.", + "You clicked Cancel on purpose.", + "A different browser session received the URL — possible phishing — and rejected it.", + ], + fixes: [ + "Run `helpbase login` again if that wasn't you.", + "If you didn't start this login, no action is needed; the code is now void.", + ], + }, + "e-device-expired": { + code: "E_DEVICE_EXPIRED", + title: "Device code expired", + summary: + "The browser didn't approve the CLI within the 10-minute window, so the one-time code is now void.", + causes: [ + "You walked away or got distracted mid-flow.", + "Network delays pushed polling past the expiry.", + "The auth server rejected the code early (rare).", + ], + fixes: [ + "Run `helpbase login` again to get a fresh code.", + "If you're on a slow network, `helpbase login --email` is more forgiving — the email link lives for 10 minutes after you click it.", + ], + }, + // E_DEVICE_NETWORK, E_DEVICE_NO_BROWSER, E_LOGIN_RESEND_DOWN, + // E_LOGIN_STALE_TOKEN were drafted during the 2026-04-17 device-flow + // plan but the CLI never throws them — network errors surface as the + // generic login-failed cancel, headless envs are a behavior (URL + // printed, polling continues) rather than an error, and stale tokens + // are cleared silently with a fresh login prompt. Entries removed to + // keep /errors/ pages in sync with what the CLI actually emits. } export function generateStaticParams() { diff --git a/apps/web/app/api/auth/[...all]/route.ts b/apps/web/app/api/auth/[...all]/route.ts new file mode 100644 index 0000000..60c9c34 --- /dev/null +++ b/apps/web/app/api/auth/[...all]/route.ts @@ -0,0 +1,15 @@ +import { toNextJsHandler } from "better-auth/next-js" +import { auth } from "@/lib/auth" + +// Better Auth's Next.js adapter. Handles every /api/auth/* route: +// GET /api/auth/ok → health check +// POST /api/auth/sign-in/magic-link → triggers sendMagicLink +// GET /api/auth/verify-magic-link → consumes the magic token, sets session cookie +// GET /api/auth/session → reads current session (cookie or Bearer) +// POST /api/auth/sign-out → clears session +// ... plus every plugin-mounted route (bearer, magicLink, later deviceAuthorization) +// +// All auth state lives in the database (public.user / public.session / public.account +// / public.verification). No cookies-in-proxy or token-in-proxy logic — plugins own it. + +export const { GET, POST } = toNextJsHandler(auth.handler) diff --git a/apps/web/app/api/revalidate/route.ts b/apps/web/app/api/revalidate/route.ts index 2b62180..a27f1ba 100644 --- a/apps/web/app/api/revalidate/route.ts +++ b/apps/web/app/api/revalidate/route.ts @@ -1,39 +1,33 @@ import { NextResponse, type NextRequest } from "next/server" import { revalidatePath } from "next/cache" -import { createClient } from "@supabase/supabase-js" -import type { Database } from "@/types/supabase" +import { auth } from "@/lib/auth" +import { getServiceRoleClient } from "@/lib/supabase-admin" /** * POST /api/revalidate * body: { tenant_id: string } - * auth: Bearer (from the CLI's authed session) + * auth: Bearer (from the CLI's authed session) * * Called by `helpbase deploy` after a successful RPC to flush the ISR cache * for the tenant's pages. Without this, pages served under * `{slug}.helpbase.dev/...` (ISR, 1h TTL) keep serving stale content for up * to an hour after the deploy — which breaks trust on the first deploy. * - * Security: the caller's access-token must belong to the tenant owner. - * We use the anon Supabase client with the user's JWT to read `tenants` - * under RLS — the `tenants_select_public` policy + the owner_id check in - * the query form a belt-and-suspenders filter. Service role is NOT used - * here; only the rightful owner should be able to revalidate their tenant. + * Security: the caller's bearer must resolve to a Better Auth session whose + * userId matches tenants.owner_id. Tenant lookup goes through the service- + * role client because the 2026-04-17 migration dropped RLS owner-policies; + * the owner match is enforced in application code. Mirrors the pattern in + * /api/v1/llm/_shared.ts. */ -const SUPABASE_URL = process.env.NEXT_PUBLIC_SUPABASE_URL ?? "" -const SUPABASE_ANON_KEY = process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY ?? "" - export async function POST(req: NextRequest) { - if (!SUPABASE_URL || !SUPABASE_ANON_KEY) { - return NextResponse.json({ error: "Supabase not configured" }, { status: 500 }) - } - - // Extract bearer token (Supabase session access token from the CLI). - const authHeader = req.headers.get("authorization") ?? "" - const match = /^Bearer\s+(.+)$/i.exec(authHeader.trim()) - const accessToken = match?.[1] - if (!accessToken) { - return NextResponse.json({ error: "missing bearer token" }, { status: 401 }) + // Better Auth bearer → session. Rejects cookie-only or missing headers. + const session = await auth.api.getSession({ headers: req.headers }) + if (!session?.user?.id) { + return NextResponse.json( + { error: "missing, malformed, or expired session token" }, + { status: 401 }, + ) } // Parse body. @@ -48,28 +42,19 @@ export async function POST(req: NextRequest) { return NextResponse.json({ error: "tenant_id is required" }, { status: 400 }) } - // Resolve tenant + verify ownership via the caller's JWT. - // createClient + Authorization header = queries run as that user under RLS. - const client = createClient(SUPABASE_URL, SUPABASE_ANON_KEY, { - global: { headers: { Authorization: `Bearer ${accessToken}` } }, - }) - - const { data: userData } = await client.auth.getUser(accessToken) - const userId = userData.user?.id - if (!userId) { - return NextResponse.json({ error: "invalid session" }, { status: 401 }) - } - - const { data: tenant, error } = await client + // Service-role lookup — RLS owner-policies were dropped in the Better Auth + // migration, so ownership is enforced in code below. + const admin = getServiceRoleClient() + const { data: tenant, error } = await admin .from("tenants") .select("slug, owner_id") .eq("id", tenantId) - .single() + .maybeSingle() if (error || !tenant) { return NextResponse.json({ error: "tenant not found" }, { status: 404 }) } - if (tenant.owner_id !== userId) { + if (tenant.owner_id !== session.user.id) { return NextResponse.json({ error: "not tenant owner" }, { status: 403 }) } diff --git a/apps/web/app/api/v1/llm/_shared.ts b/apps/web/app/api/v1/llm/_shared.ts index 8060547..a247e95 100644 --- a/apps/web/app/api/v1/llm/_shared.ts +++ b/apps/web/app/api/v1/llm/_shared.ts @@ -1,7 +1,8 @@ import { NextResponse } from "next/server" import type { WireErrorBody, WireErrorCode, WireQuotaStatus, WireUsage } from "@workspace/shared/llm-wire" import { BYOK_DOCS_URL, UPGRADE_URL } from "@workspace/shared/llm-wire" -import { getServiceRoleClient, verifyBearerToken } from "@/lib/supabase-admin" +import { getServiceRoleClient } from "@/lib/supabase-admin" +import { auth } from "@/lib/auth" /** * Shared helpers for /api/v1/llm/generate-object and /generate-text. @@ -36,22 +37,18 @@ export interface AuthedContext { export async function withAuthAndQuota( req: Request, ): Promise { - const authz = req.headers.get("authorization") ?? "" - const match = /^Bearer\s+(.+)$/i.exec(authz) - if (!match) { - return wireError(401, "auth_required", "Missing or malformed Authorization header.") - } - const token = match[1]! - - const user = await verifyBearerToken(token) - if (!user) { - return wireError(401, "auth_required", "Invalid or expired session token.") + // Better Auth's bearer plugin reads Authorization: Bearer and + // resolves it to a session via public.session.token. Same bearer shape + // as pre-migration (Supabase JWTs); callers see no API change. + const session = await auth.api.getSession({ headers: req.headers }) + if (!session?.user?.id) { + return wireError(401, "auth_required", "Missing, malformed, or expired session token.") } // Parallel: read user's today-tokens + global counter. const client = getServiceRoleClient() const [userRes, globalRes] = await Promise.all([ - client.rpc("get_user_tokens_today", { p_user_id: user.userId }), + client.rpc("get_user_tokens_today", { p_user_id: session.user.id }), client.rpc("get_global_tokens_today"), ]) @@ -90,7 +87,7 @@ export async function withAuthAndQuota( const maxOutputTokens = Math.min(PER_CALL_CEILING, remaining) return { - userId: user.userId, + userId: session.user.id, usedToday, resetAtIso, maxOutputTokens, diff --git a/apps/web/app/api/v1/tenants/[id]/deploy/route.ts b/apps/web/app/api/v1/tenants/[id]/deploy/route.ts new file mode 100644 index 0000000..c870f0b --- /dev/null +++ b/apps/web/app/api/v1/tenants/[id]/deploy/route.ts @@ -0,0 +1,99 @@ +import { NextResponse, type NextRequest } from "next/server" +import { revalidatePath } from "next/cache" +import { deployPayloadSchema } from "@workspace/shared/schemas" +import { jsonError, requireOwnedTenant } from "../../_shared" + +/** + * POST /api/v1/tenants/:id/deploy + * auth: Bearer + * body: { categories: [...], articles: [...], chunks: [...], validation_report?: {...} } + * returns: { deploy_id, article_count, chunk_count, slug } + * + * Server-side port of what the CLI's `deploy` command used to do by + * calling the `deploy_tenant` RPC directly over a JWT-auth Supabase + * client. Ownership is enforced here (requireOwnedTenant) before the + * RPC fires; the RPC itself now trusts the caller (service-role). + * + * Also flushes the tenant's ISR cache so `{slug}.helpbase.dev` serves + * fresh content. Replaces /api/revalidate as the post-deploy hook from + * the CLI's perspective — one round-trip instead of two. + */ + +export const runtime = "nodejs" +export const dynamic = "force-dynamic" + +export async function POST( + req: NextRequest, + ctx: { params: Promise<{ id: string }> }, +): Promise { + const { id } = await ctx.params + const owned = await requireOwnedTenant(req, id) + if (owned instanceof NextResponse) return owned + const { tenant, admin } = owned + + let rawBody: unknown + try { + rawBody = await req.json() + } catch { + return jsonError(400, "invalid_body", "Expected JSON {categories, articles, chunks}.") + } + // Shared schema — same one the CLI uses to shape the payload. Validate + // server-side so malformed array elements come back as precise 400s + // instead of opaque 503 deploy_failed errors from Postgres. + const parsed = deployPayloadSchema.safeParse(rawBody) + if (!parsed.success) { + return jsonError( + 400, + "invalid_body", + parsed.error.issues + .slice(0, 5) + .map((i) => `${i.path.join(".") || "(root)"}: ${i.message}`) + .join("; "), + ) + } + const body = parsed.data + + // Supabase's generated RPC types demand the strict `Json` shape + // (recursive `{ [key: string]: Json | undefined }`), which our Zod + // types don't satisfy because Frontmatter is `Record`. + // The `as never` is a type-system escape valve — the actual runtime + // safety comes from the deployPayloadSchema parse above. + const { data: deployId, error } = await admin.rpc("deploy_tenant", { + p_tenant_id: tenant.id, + p_categories: body.categories as never, + p_articles: body.articles as never, + p_chunks: body.chunks as never, + p_validation_report: (body.validation_report ?? {}) as never, + }) + if (error) { + console.error("[tenants.deploy] supabase rpc error", { tenantId: tenant.id, error }) + return jsonError(503, "deploy_failed", "Deploy RPC failed.") + } + + // Count rows post-deploy so the CLI can print a helpful summary. + const [{ count: articleCount }, { count: chunkCount }] = await Promise.all([ + admin + .from("tenant_articles") + .select("*", { count: "exact", head: true }) + .eq("tenant_id", tenant.id), + admin + .from("tenant_chunks") + .select("*", { count: "exact", head: true }) + .eq("tenant_id", tenant.id), + ]) + + // Fire ISR revalidation for the tenant's subdomain pages. Safe-to-ignore + // errors — cache will self-heal on the next 1h TTL. + try { + revalidatePath(`/t/${tenant.slug}`, "layout") + } catch { + // best-effort + } + + return NextResponse.json({ + deploy_id: deployId, + article_count: articleCount ?? 0, + chunk_count: chunkCount ?? 0, + slug: tenant.slug, + }) +} diff --git a/apps/web/app/api/v1/tenants/[id]/rotate-mcp-token/route.ts b/apps/web/app/api/v1/tenants/[id]/rotate-mcp-token/route.ts new file mode 100644 index 0000000..60fffa5 --- /dev/null +++ b/apps/web/app/api/v1/tenants/[id]/rotate-mcp-token/route.ts @@ -0,0 +1,47 @@ +import { NextResponse, type NextRequest } from "next/server" +import { jsonError, requireOwnedTenant } from "../../_shared" + +/** + * POST /api/v1/tenants/:id/rotate-mcp-token + * auth: Bearer + * returns: { mcp_public_token } + * + * Rotates the tenant's MCP bearer. Generates a 32-byte hex token + * server-side. The old token is immediately invalidated — any existing + * MCP clients using the old token will 401. + */ + +export const runtime = "nodejs" +export const dynamic = "force-dynamic" + +export async function POST( + req: NextRequest, + ctx: { params: Promise<{ id: string }> }, +): Promise { + const { id } = await ctx.params + const owned = await requireOwnedTenant(req, id) + if (owned instanceof NextResponse) return owned + const { tenant, admin } = owned + + const bytes = new Uint8Array(32) + crypto.getRandomValues(bytes) + const newToken = Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join("") + + const { data: updated, error } = await admin + .from("tenants") + .update({ mcp_public_token: newToken }) + .eq("id", tenant.id) + .select("id") + .maybeSingle() + if (error) { + console.error("[tenants.rotate-mcp-token] supabase error", { tenantId: tenant.id, error }) + return jsonError(503, "rotate_failed", "Could not rotate token.") + } + // If the row disappeared between requireOwnedTenant and the update (race + // with DELETE, or soft-delete turning active=false), don't return a token + // that's stored nowhere — the MCP client would 401 forever. + if (!updated) { + return jsonError(404, "tenant_not_found", "Tenant disappeared before rotation completed.") + } + return NextResponse.json({ mcp_public_token: newToken }) +} diff --git a/apps/web/app/api/v1/tenants/[id]/route.ts b/apps/web/app/api/v1/tenants/[id]/route.ts new file mode 100644 index 0000000..6662eba --- /dev/null +++ b/apps/web/app/api/v1/tenants/[id]/route.ts @@ -0,0 +1,54 @@ +import { NextResponse, type NextRequest } from "next/server" +import { jsonError, requireOwnedTenant } from "../_shared" + +/** + * GET /api/v1/tenants/:id + * auth: Bearer + * returns: full tenant row, or 403 if the caller is not the owner + * + * Used by `helpbase deploy` when it has a linked tenantId from + * .helpbase/project.json and wants to confirm the row still exists + * and belongs to the caller before deploying. + */ + +export const runtime = "nodejs" +export const dynamic = "force-dynamic" + +export async function GET( + req: NextRequest, + ctx: { params: Promise<{ id: string }> }, +): Promise { + const { id } = await ctx.params + const owned = await requireOwnedTenant(req, id) + if (owned instanceof NextResponse) return owned + // Never expose owner_id of other users (the gate above already guarantees + // it's the caller's own tenant, but mcp_public_token is sensitive — return + // only what the CLI needs). + const { id: tid, slug, name, mcp_public_token, active } = owned.tenant + return NextResponse.json({ id: tid, slug, name, mcp_public_token, active }) +} + +/** + * DELETE /api/v1/tenants/:id + * auth: Bearer + * returns: { deleted: true, slug } + * + * Hard delete — cascades to tenant_articles, tenant_categories, tenant_chunks, + * tenant_deploys, tenant_mcp_queries via their owner FKs. Caller must + * re-confirm in the CLI before hitting this endpoint. + */ +export async function DELETE( + req: NextRequest, + ctx: { params: Promise<{ id: string }> }, +): Promise { + const { id } = await ctx.params + const owned = await requireOwnedTenant(req, id) + if (owned instanceof NextResponse) return owned + const { tenant, admin } = owned + const { error } = await admin.from("tenants").delete().eq("id", tenant.id) + 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 }) +} diff --git a/apps/web/app/api/v1/tenants/_shared.ts b/apps/web/app/api/v1/tenants/_shared.ts new file mode 100644 index 0000000..5e96a37 --- /dev/null +++ b/apps/web/app/api/v1/tenants/_shared.ts @@ -0,0 +1,69 @@ +import { NextResponse, type NextRequest } from "next/server" +import { auth } from "@/lib/auth" +import { getServiceRoleClient } from "@/lib/supabase-admin" +import type { Database } from "@/types/supabase" + +/** + * Shared auth + tenant-ownership helpers for /api/v1/tenants/*. + * + * requireSession(req) → { userId, email } | NextResponse(401) + * requireOwnedTenant(req, id) → { userId, tenant } | NextResponse(401|404|403) + * + * All endpoints use the service-role client for reads and writes — the + * 2026-04-17 Better Auth migration dropped the RLS *_own policies, so + * ownership is enforced here (in app code) instead. + */ + +export type SupabaseAdmin = ReturnType + +export interface AuthedUser { + userId: string + email: string +} + +export async function requireSession( + req: NextRequest | Request, +): Promise { + const session = await auth.api.getSession({ headers: req.headers }) + if (!session?.user?.id) { + return NextResponse.json( + { error: "auth_required", message: "Missing, malformed, or expired session token." }, + { status: 401 }, + ) + } + return { userId: session.user.id, email: session.user.email ?? "" } +} + +export type OwnedTenantRow = Database["public"]["Tables"]["tenants"]["Row"] + +export async function requireOwnedTenant( + req: NextRequest | Request, + tenantId: string, +): Promise<{ user: AuthedUser; tenant: OwnedTenantRow; admin: SupabaseAdmin } | NextResponse> { + const userOrResp = await requireSession(req) + if (userOrResp instanceof NextResponse) return userOrResp + const admin = getServiceRoleClient() + const { data: tenant, error } = await admin + .from("tenants") + .select("*") + .eq("id", tenantId) + .maybeSingle() + if (error) { + // Separate infra failures from a genuine miss so we can alert on the + // former; otherwise a pooler/connectivity blip looks identical to + // "tenant doesn't exist" and the 404 silently swallows the signal. + console.error("[requireOwnedTenant] supabase error", { tenantId, error }) + return NextResponse.json({ error: "tenant_lookup_failed" }, { status: 503 }) + } + if (!tenant) { + return NextResponse.json({ error: "tenant_not_found" }, { status: 404 }) + } + if (tenant.owner_id !== userOrResp.userId) { + return NextResponse.json({ error: "not_tenant_owner" }, { status: 403 }) + } + return { user: userOrResp, tenant, admin } +} + +export function jsonError(status: number, code: string, message?: string) { + return NextResponse.json({ error: code, ...(message ? { message } : {}) }, { status }) +} diff --git a/apps/web/app/api/v1/tenants/by-slug/[slug]/route.ts b/apps/web/app/api/v1/tenants/by-slug/[slug]/route.ts new file mode 100644 index 0000000..fa8976f --- /dev/null +++ b/apps/web/app/api/v1/tenants/by-slug/[slug]/route.ts @@ -0,0 +1,45 @@ +import { NextResponse, type NextRequest } from "next/server" +import { getServiceRoleClient } from "@/lib/supabase-admin" + +/** + * GET /api/v1/tenants/by-slug/:slug + * no auth — just an availability probe + * returns: { available: boolean, id?: string, slug?: string } + * + * Used by `helpbase link --slug foo` and `helpbase deploy` when picking + * a subdomain. Only returns id + slug on hit — never owner_id or + * mcp_public_token — so leaking this to anon is fine. + */ + +export const runtime = "nodejs" +export const dynamic = "force-dynamic" + +// Must match the creation-side shape — otherwise we waste a DB round-trip +// on values that can never be tenant slugs, and leave room for enumeration +// via oversized inputs. +const SLUG_REGEX = /^[a-z0-9]([a-z0-9-]{0,38}[a-z0-9])?$/ + +export async function GET( + _req: NextRequest, + ctx: { params: Promise<{ slug: string }> }, +): Promise { + const { slug } = await ctx.params + if (!SLUG_REGEX.test(slug)) { + return NextResponse.json({ available: false }, { status: 400 }) + } + const admin = getServiceRoleClient() + // Don't filter by active=true — the DB's UNIQUE(slug) index ignores it, + // so an inactive tenant still blocks creation. Reporting "available" + // here would produce a confusing 409 downstream. + const { data } = await admin + .from("tenants") + .select("id, slug") + .eq("slug", slug) + .maybeSingle() + if (!data) return NextResponse.json({ available: true }) + return NextResponse.json({ + available: false, + id: data.id, + slug: data.slug, + }) +} diff --git a/apps/web/app/api/v1/tenants/mine/route.ts b/apps/web/app/api/v1/tenants/mine/route.ts new file mode 100644 index 0000000..7460699 --- /dev/null +++ b/apps/web/app/api/v1/tenants/mine/route.ts @@ -0,0 +1,37 @@ +import { NextResponse, type NextRequest } from "next/server" +import { getServiceRoleClient } from "@/lib/supabase-admin" +import { requireSession } from "../_shared" + +/** + * GET /api/v1/tenants/mine + * auth: Bearer + * returns: { tenants: Array<{ id, slug, name }> } + * + * Replaces the old CLI-side anon-Supabase query that filtered by + * owner_id = auth.uid(). All current owner-lookups in deploy/link/open + * route through here. + */ + +export const runtime = "nodejs" +export const dynamic = "force-dynamic" + +export async function GET(req: NextRequest): Promise { + const sessionOrResp = await requireSession(req) + if (sessionOrResp instanceof NextResponse) return sessionOrResp + + const admin = getServiceRoleClient() + const { data, error } = await admin + .from("tenants") + .select("id, slug, name") + .eq("owner_id", sessionOrResp.userId) + .eq("active", true) + .order("created_at", { ascending: false }) + + if (error) { + return NextResponse.json( + { error: "internal_error", message: "Could not list tenants." }, + { status: 503 }, + ) + } + return NextResponse.json({ tenants: data ?? [] }) +} diff --git a/apps/web/app/api/v1/tenants/route.ts b/apps/web/app/api/v1/tenants/route.ts new file mode 100644 index 0000000..9210f58 --- /dev/null +++ b/apps/web/app/api/v1/tenants/route.ts @@ -0,0 +1,74 @@ +import { NextResponse, type NextRequest } from "next/server" +import { getServiceRoleClient } from "@/lib/supabase-admin" +import { jsonError, requireSession } from "./_shared" + +/** + * POST /api/v1/tenants + * auth: Bearer + * body: { slug: string, name?: string } + * returns: { id, slug, name, mcp_public_token } + * + * Creates a tenant owned by the caller. Enforces slug uniqueness via + * the DB's UNIQUE constraint; 409 on duplicate. + */ + +// DNS-label shape: alphanumeric start+end, hyphens only in the middle. +// Matches the CLI-side check in link.ts/deploy.ts so both paths agree. +const SLUG_REGEX = /^[a-z0-9]([a-z0-9-]*[a-z0-9])?$/ +const RESERVED = new Set([ + "www", "app", "api", "admin", "dashboard", "docs", "help", "blog", "status", + "mail", "mcp", "deploy", "login", "signup", "signin", "auth", "billing", + "support", "cdn", "static", "assets", "files", "media", "images", "img", +]) + +export const runtime = "nodejs" +export const dynamic = "force-dynamic" + +export async function POST(req: NextRequest): Promise { + const sessionOrResp = await requireSession(req) + if (sessionOrResp instanceof NextResponse) return sessionOrResp + + let body: { slug?: string; name?: string } + try { + body = await req.json() + } catch { + return jsonError(400, "invalid_body", "Expected JSON {slug, name?}.") + } + + const slug = body.slug?.trim() + if (!slug) return jsonError(400, "slug_required") + if (!SLUG_REGEX.test(slug)) { + return jsonError(400, "slug_invalid", "Use lowercase letters, numbers, and hyphens.") + } + if (slug.length < 3 || slug.length > 40) { + return jsonError(400, "slug_invalid", "Slug must be 3-40 characters.") + } + if (RESERVED.has(slug)) { + return jsonError(409, "slug_reserved", `"${slug}" is reserved.`) + } + + const admin = getServiceRoleClient() + const { data, error } = await admin + .from("tenants") + .insert({ + slug, + owner_id: sessionOrResp.userId, + name: body.name?.trim() || slug, + }) + .select("id, slug, name, mcp_public_token") + .maybeSingle() + + if (error) { + // Prefer Postgres error codes over regex on error.message — wording + // is locale/driver-dependent. 23505 = unique_violation. + if ((error as { code?: string }).code === "23505") { + return jsonError(409, "slug_taken", `"${slug}" is already taken.`) + } + console.error("[tenants.create] supabase error", { slug, error }) + return jsonError(503, "internal_error", "Could not create tenant.") + } + if (!data) { + return jsonError(503, "internal_error", "Tenant row not returned after insert.") + } + return NextResponse.json(data, { status: 201 }) +} diff --git a/apps/web/app/api/v1/usage/today/route.ts b/apps/web/app/api/v1/usage/today/route.ts index 435bc39..e0dd922 100644 --- a/apps/web/app/api/v1/usage/today/route.ts +++ b/apps/web/app/api/v1/usage/today/route.ts @@ -1,7 +1,8 @@ import type { NextRequest } from "next/server" import { NextResponse } from "next/server" import type { UsageTodayResponse } from "@workspace/shared/llm-wire" -import { getServiceRoleClient, verifyBearerToken } from "@/lib/supabase-admin" +import { getServiceRoleClient } from "@/lib/supabase-admin" +import { auth } from "@/lib/auth" import { DAILY_USER_LIMIT, nextUtcMidnightIso, @@ -11,7 +12,7 @@ import { /** * GET /api/v1/usage/today * - * Auth: Bearer . + * Auth: Bearer . * Returns the signed-in user's today-tokens snapshot, used by `helpbase whoami`. */ @@ -19,26 +20,21 @@ export const runtime = "nodejs" export const dynamic = "force-dynamic" export async function GET(req: NextRequest): Promise { - const authz = req.headers.get("authorization") ?? "" - const match = /^Bearer\s+(.+)$/i.exec(authz) - if (!match) { - return wireError(401, "auth_required", "Missing or malformed Authorization header.") - } - const user = await verifyBearerToken(match[1]!) - if (!user) { - return wireError(401, "auth_required", "Invalid or expired session token.") + const session = await auth.api.getSession({ headers: req.headers }) + if (!session?.user?.id) { + return wireError(401, "auth_required", "Missing, malformed, or expired session token.") } const client = getServiceRoleClient() const { data, error } = await client.rpc("get_user_tokens_today", { - p_user_id: user.userId, + p_user_id: session.user.id, }) if (error) { return wireError(503, "internal_error", "Supabase is unavailable.") } const body: UsageTodayResponse = { - email: user.email ?? "", + email: session.user.email ?? "", quota: { usedToday: Number(data ?? 0), dailyLimit: DAILY_USER_LIMIT, diff --git a/apps/web/app/device/AuthorizeDeviceClient.tsx b/apps/web/app/device/AuthorizeDeviceClient.tsx new file mode 100644 index 0000000..f6ee0cb --- /dev/null +++ b/apps/web/app/device/AuthorizeDeviceClient.tsx @@ -0,0 +1,264 @@ +"use client" + +import { useEffect, useState, type FormEvent } from "react" +import { createAuthClient } from "better-auth/react" +import { magicLinkClient, deviceAuthorizationClient } from "better-auth/client/plugins" + +// Inline the auth client here (one consumer, one module) to side-step +// TS's "inferred type cannot be named" portability complaint on the +// deeply-nested better-auth types. If a second component needs the +// client later, promote this to lib/auth-client.ts with an explicit +// return-type annotation. +const authClient = createAuthClient({ + plugins: [magicLinkClient(), deviceAuthorizationClient()], +}) + +type Phase = + | { kind: "loading" } + | { kind: "signed-out" } + | { kind: "email-sent"; email: string } + | { kind: "signed-in"; email: string; userCode: string } + | { kind: "approving" } + | { kind: "approved"; email: string } + | { kind: "denied" } + | { kind: "error"; message: string } + +export function AuthorizeDeviceClient({ initialUserCode }: { initialUserCode: string }) { + const { data: session, isPending: sessionPending } = authClient.useSession() + const [userCode, setUserCode] = useState(initialUserCode) + const [phase, setPhase] = useState({ kind: "loading" }) + const [email, setEmail] = useState("") + const [submitting, setSubmitting] = useState(false) + + // Derive the UI phase from session state + URL-provided user_code. + useEffect(() => { + if (sessionPending) { + setPhase({ kind: "loading" }) + return + } + if (!userCode) { + // No user_code on the URL — show an input. Rare path; the CLI + // always provides verification_uri_complete which carries it. + setPhase({ kind: "signed-out" }) + return + } + if (!session?.user) { + setPhase({ kind: "signed-out" }) + return + } + setPhase({ + kind: "signed-in", + email: session.user.email ?? "", + userCode, + }) + }, [sessionPending, session, userCode]) + + async function handleMagicLink(event: FormEvent) { + event.preventDefault() + if (!email) return + setSubmitting(true) + try { + const callback = userCode + ? `/device?user_code=${encodeURIComponent(userCode)}` + : "/device" + const { error } = await authClient.signIn.magicLink({ + email, + callbackURL: callback, + }) + if (error) { + setPhase({ + kind: "error", + message: error.message ?? "Couldn't send sign-in email.", + }) + } else { + setPhase({ kind: "email-sent", email }) + } + } catch (err) { + setPhase({ + kind: "error", + message: err instanceof Error ? err.message : String(err), + }) + } finally { + setSubmitting(false) + } + } + + async function handleApprove() { + setPhase({ kind: "approving" }) + try { + const { error } = await authClient.device.approve({ userCode }) + if (error) { + // device.approve returns RFC-8628-shaped error codes + // ("access_denied", "expired_token", etc.) rather than a plain + // message field. error_description is the human-readable text. + setPhase({ + kind: "error", + message: error.error_description ?? "Authorization failed.", + }) + return + } + setPhase({ + kind: "approved", + email: session?.user?.email ?? "", + }) + } catch (err) { + setPhase({ + kind: "error", + message: err instanceof Error ? err.message : String(err), + }) + } + } + + async function handleDeny() { + try { + await authClient.device.deny({ userCode }) + } catch { + // best-effort — regardless, we show the denied screen + } + setPhase({ kind: "denied" }) + } + + if (phase.kind === "loading") { + return
Checking session…
+ } + + if (phase.kind === "signed-out") { + return ( +
+ {userCode && ( +
+
+ Device code +
+
+ {userCode} +
+
+ )} + + setEmail(e.target.value)} + placeholder="you@company.com" + className="w-full rounded-md border border-neutral-300 bg-white px-3 py-2 text-sm dark:border-neutral-700 dark:bg-neutral-950" + /> + +

+ Don't have an account? Signing in with a new email creates one + automatically. +

+
+ ) + } + + if (phase.kind === "email-sent") { + return ( +
+
📬
+

+ Check {phase.email} for your + sign-in link. After clicking, you'll land back here to authorize. +

+
+ ) + } + + if (phase.kind === "signed-in" || phase.kind === "approving") { + const approving = phase.kind === "approving" + return ( +
+
+
+ Device code +
+
+ {userCode} +
+
+

+ Signed in as{" "} + + {phase.kind === "signed-in" ? phase.email : session?.user?.email} + + . Authorizing will give the CLI full access to the helpbase API on + your behalf. +

+
+ + +
+
+ ) + } + + if (phase.kind === "approved") { + return ( +
+
✓
+

+ Authorized. Return to your terminal. +

+

+ Your CLI will pick this up in a few seconds. You can close this + tab. +

+
+ ) + } + + if (phase.kind === "denied") { + return ( +
+
✕
+

Cancelled. Your CLI session was not signed in.

+
+ ) + } + + // phase.kind === "error" + return ( +
+
⚠️
+

{phase.message}

+ +
+ ) +} diff --git a/apps/web/app/device/page.tsx b/apps/web/app/device/page.tsx new file mode 100644 index 0000000..ba2a7eb --- /dev/null +++ b/apps/web/app/device/page.tsx @@ -0,0 +1,37 @@ +import type { Metadata } from "next" +import { AuthorizeDeviceClient } from "./AuthorizeDeviceClient" + +export const metadata: Metadata = { + title: "Authorize device · helpbase", + description: "Authorize a helpbase CLI session.", + robots: { index: false, follow: false }, +} + +// We intentionally render without a sidebar/toc chrome — this page is a +// focused auth moment, like gh.io/login/device. Layout lives inline. +export default async function DevicePage({ + searchParams, +}: { + searchParams: Promise<{ user_code?: string; error?: string }> +}) { + const params = await searchParams + const userCode = params.user_code?.trim() ?? "" + + return ( +
+
+
+

Authorize helpbase CLI

+

+ A CLI session on your device is waiting for approval. +

+
+ +
+ Compare the code above to what your terminal shows. If they don't + match, close this tab and ignore the link. +
+
+
+ ) +} diff --git a/apps/web/lib/auth.ts b/apps/web/lib/auth.ts new file mode 100644 index 0000000..35c8a63 --- /dev/null +++ b/apps/web/lib/auth.ts @@ -0,0 +1,117 @@ +import { betterAuth } from "better-auth" +import { bearer } from "better-auth/plugins/bearer" +import { magicLink } from "better-auth/plugins/magic-link" +import { deviceAuthorization } from "better-auth/plugins/device-authorization" +import { Pool } from "pg" +import { Resend } from "resend" + +const DATABASE_URL = process.env.DATABASE_URL +const RESEND_API_KEY = process.env.RESEND_API_KEY +const FROM_EMAIL = process.env.RESEND_FROM_EMAIL ?? "helpbase " + +// Guards fire at runtime (server-side request handling), not during +// `next build` static page-data collection. NEXT_PHASE is set to +// 'phase-production-build' by Next.js during build so we can distinguish +// the two. Without this gate, CI without prod secrets can't build at all, +// and Vercel's build step would fail before ever getting to runtime. +const isBuildPhase = process.env.NEXT_PHASE === "phase-production-build" +const isRuntimeProd = process.env.NODE_ENV === "production" && !isBuildPhase + +if (!DATABASE_URL) { + if (isRuntimeProd) { + // Runtime miss — every auth request would 500 against a pool built + // from undefined. Surfaces on first request to /api/auth/* instead + // of at module load, so the rest of the site still serves pages. + throw new Error( + "DATABASE_URL is required in production. Supabase → Project Settings → " + + "Database → Connection string. Use the 'session' / direct connection.", + ) + } + // eslint-disable-next-line no-console + console.warn( + "[auth] DATABASE_URL not set. /api/auth/* will 500 until you set it " + + "in apps/web/.env.local (or Vercel env for prod).", + ) +} + +if (!RESEND_API_KEY && isRuntimeProd) { + // Without a mail provider in prod, the dev fallback would print live + // magic-link URLs to Vercel Runtime Logs — anyone with log access could + // harvest sign-in URLs. Fail boot instead. + throw new Error( + "RESEND_API_KEY is required in production. Get one at resend.com/api-keys " + + "and add it to the Vercel project env.", + ) +} + +const resend = RESEND_API_KEY ? new Resend(RESEND_API_KEY) : null + +async function deliverMagicLink(email: string, url: string): Promise { + if (resend) { + const { error } = await resend.emails.send({ + from: FROM_EMAIL, + to: email, + subject: "Sign in to helpbase", + text: + `Click the link below to sign in:\n\n${url}\n\n` + + `This link expires in 10 minutes. If you didn't request this, ignore this email.`, + }) + if (error) { + // Let Better Auth surface the error to the caller. The CLI's + // E_LOGIN_RESEND_DOWN code maps to this path via the plugin's error + // response; downstream we log structured telemetry. + throw new Error(`Resend delivery failed: ${error.message ?? String(error)}`) + } + return + } + + // Dev-mode fallback: no Resend key configured, print the sign-in URL to + // stderr so local devs can click it from their terminal without signing + // up for a mail provider. Belt-and-suspenders: also gate on NODE_ENV + // so a misconfigured prod deploy (somehow missed the boot-time check + // above) refuses to leak the URL — it fails loudly instead. + if (process.env.NODE_ENV === "production") { + throw new Error( + "RESEND_API_KEY missing in production — refusing to print magic-link " + + "URL to stderr. Set RESEND_API_KEY in the Vercel env.", + ) + } + // eslint-disable-next-line no-console + console.error( + "\n─── DEV MAGIC LINK ───────────────────────────────────────────\n" + + ` to: ${email}\n` + + ` link: ${url}\n` + + " (set RESEND_API_KEY in .env.local to send real emails)\n" + + "──────────────────────────────────────────────────────────────\n", + ) +} + +export const auth = betterAuth({ + database: new Pool({ connectionString: DATABASE_URL }), + plugins: [ + bearer(), + magicLink({ + expiresIn: 600, // 10 minutes; Better Auth default is 300 which is tight for mobile mail delivery + sendMagicLink: async ({ email, url }) => { + await deliverMagicLink(email, url) + }, + }), + deviceAuthorization({ + // RFC 8628 device grant. `helpbase login` kicks this off from the + // CLI; the browser lands at /device?user_code=... + // where the user compares the code to what the CLI printed and + // clicks Authorize. Plugin owns the atomic consume, expiry, and + // polling rate-limit (slow_down / authorization_pending). + verificationUri: "/device", + expiresIn: "10m", // longer than default 30m would be gratuitous + interval: "2s", // matches our plan's stated polling cadence + }), + ], + trustedOrigins: [ + "https://helpbase.dev", + "http://localhost:3000", + process.env.VERCEL_URL ? `https://${process.env.VERCEL_URL}` : "", + ].filter(Boolean), +}) + +export type Session = typeof auth.$Infer.Session diff --git a/apps/web/lib/supabase-admin.ts b/apps/web/lib/supabase-admin.ts index 02a213b..f9c5be3 100644 --- a/apps/web/lib/supabase-admin.ts +++ b/apps/web/lib/supabase-admin.ts @@ -27,16 +27,5 @@ export function getServiceRoleClient(): SupabaseClient { return cached } -/** - * Resolve the user behind a bearer token. Uses Supabase's getUser RPC — one - * network call per request. Swap to local JWT verification if latency becomes - * an issue (SUPABASE_JWT_SECRET + a signature library). - */ -export async function verifyBearerToken( - token: string, -): Promise<{ userId: string; email: string | null } | null> { - const client = getServiceRoleClient() - const { data, error } = await client.auth.getUser(token) - if (error || !data.user) return null - return { userId: data.user.id, email: data.user.email ?? null } -} +// verifyBearerToken removed 2026-04-17 — replaced by Better Auth's +// auth.api.getSession({ headers }) in every call site. See DEVICE_FLOW_PLAN.md. diff --git a/apps/web/lib/tenant-content.ts b/apps/web/lib/tenant-content.ts index f6f416c..cdd4d61 100644 --- a/apps/web/lib/tenant-content.ts +++ b/apps/web/lib/tenant-content.ts @@ -8,15 +8,19 @@ export type TenantCategory = Tables<"tenant_categories"> /** * Look up a tenant by subdomain slug. Used by middleware and pages. + * + * Reads via `tenants_public` — a SECURITY DEFINER view that omits + * mcp_public_token + owner_id from anon-facing callers (see 2026-04-17 + * tenants_public_view_hide_mcp_token migration). The view already filters + * `active = true`. Downstream callers only need the public columns. */ export const getTenant = cache(async (slug: string): Promise => { const { data } = await supabase - .from("tenants") + .from("tenants_public") .select("*") .eq("slug", slug) - .eq("active", true) - .single() - return data + .maybeSingle() + return data as Tenant | null }) /** diff --git a/apps/web/next-env.d.ts b/apps/web/next-env.d.ts deleted file mode 100644 index 9edff1c..0000000 --- a/apps/web/next-env.d.ts +++ /dev/null @@ -1,6 +0,0 @@ -/// -/// -import "./.next/types/routes.d.ts"; - -// NOTE: This file should not be edited -// see https://nextjs.org/docs/app/api-reference/config/typescript for more information. diff --git a/apps/web/package.json b/apps/web/package.json index 4e5302b..ff96710 100644 --- a/apps/web/package.json +++ b/apps/web/package.json @@ -23,16 +23,19 @@ "@workspace/shared": "workspace:*", "@workspace/ui": "workspace:*", "ai": "^5.0.0", + "better-auth": "^1.6.5", "gray-matter": "^4.0.3", "lucide-react": "^1.8.0", "next": "16.1.6", "next-mdx-remote": "^6.0.0", "next-themes": "^0.4.6", + "pg": "^8.20.0", "react": "^19.2.4", "react-dom": "^19.2.4", "rehype-pretty-code": "^0.14.3", "rehype-slug": "^6.0.0", "remark-gfm": "^4.0.1", + "resend": "^6.12.0", "shiki": "^4.0.2", "zod": "^4.3.6" }, @@ -40,6 +43,7 @@ "@tailwindcss/postcss": "^4.1.18", "@tailwindcss/typography": "^0.5.19", "@types/node": "^25.1.0", + "@types/pg": "^8.20.0", "@types/react": "^19.2.10", "@types/react-dom": "^19.2.3", "@workspace/eslint-config": "workspace:^", diff --git a/apps/web/proxy.ts b/apps/web/proxy.ts index 71c015c..330f532 100644 --- a/apps/web/proxy.ts +++ b/apps/web/proxy.ts @@ -124,12 +124,14 @@ export async function proxy(request: NextRequest) { const supabase = createClient(supabaseUrl, supabaseKey) + // Read from the public-safe view (tenants_public hides mcp_public_token + // and owner_id from anon). Base tenants table has no anon read grant + // post-2026-04-17 migration. const { data: tenant } = await supabase - .from("tenants") + .from("tenants_public") .select("slug") .eq("slug", subdomain) - .eq("active", true) - .single() + .maybeSingle() if (!tenant) { // Unknown subdomain: show a "Create your help center" page diff --git a/apps/web/test/llm-auth-swap.test.ts b/apps/web/test/llm-auth-swap.test.ts new file mode 100644 index 0000000..c11a574 --- /dev/null +++ b/apps/web/test/llm-auth-swap.test.ts @@ -0,0 +1,86 @@ +import { beforeEach, describe, expect, it, vi } from "vitest" + +// Mock the Better Auth instance: auth.api.getSession(opts) → session | null. +// The route under test imports `auth` from @/lib/auth; our mock short- +// circuits that without needing a DB pool or Resend client. +const mockGetSession = vi.fn<(args: { headers: Headers }) => Promise< + | { user: { id: string; email: string | null } } + | null +>>() +vi.mock("@/lib/auth", () => ({ + auth: { api: { getSession: mockGetSession } }, +})) + +// Mock Supabase service-role client so RPC calls return deterministic values +// without hitting the live DB. +const mockRpc = vi.fn<(name: string, args: unknown) => Promise<{ data: unknown; error: unknown }>>() +vi.mock("@/lib/supabase-admin", () => ({ + getServiceRoleClient: () => ({ + rpc: (name: string, args: unknown) => mockRpc(name, args), + }), +})) + +const { withAuthAndQuota } = await import("../app/api/v1/llm/_shared.js") + +beforeEach(() => { + mockGetSession.mockReset() + mockRpc.mockReset() +}) + +function makeRequest(headers: Record = {}) { + return new Request("http://localhost/api/v1/llm/generate-text", { headers }) +} + +describe("withAuthAndQuota — Better Auth swap", () => { + it("returns 401 when getSession returns null (no bearer / expired)", async () => { + mockGetSession.mockResolvedValueOnce(null) + const result = await withAuthAndQuota(makeRequest()) + expect("status" in result && result.status).toBe(401) + const body = await (result as Response).json() + expect(body.error).toBe("auth_required") + }) + + it("returns 401 when getSession resolves without a user id", async () => { + // Malformed session — user object missing id + mockGetSession.mockResolvedValueOnce({ user: { id: "", email: null } }) + const result = await withAuthAndQuota(makeRequest({ authorization: "Bearer garbage" })) + expect("status" in result && result.status).toBe(401) + }) + + it("passes the session's user.id to get_user_tokens_today (text, not uuid)", async () => { + mockGetSession.mockResolvedValueOnce({ user: { id: "7a0f0ad0-text-id", email: "x@y.com" } }) + mockRpc.mockImplementation((name: string) => { + if (name === "get_user_tokens_today") return Promise.resolve({ data: 1000, error: null }) + if (name === "get_global_tokens_today") return Promise.resolve({ data: 1_000_000, error: null }) + return Promise.resolve({ data: null, error: { message: "unknown rpc" } }) + }) + const result = await withAuthAndQuota(makeRequest({ authorization: "Bearer valid" })) + expect("userId" in result && result.userId).toBe("7a0f0ad0-text-id") + // RPC was called with the text userId (not a uuid object) — proves + // the 2026-04-17 rpc signature change is honored end-to-end. + expect(mockRpc).toHaveBeenCalledWith("get_user_tokens_today", { + p_user_id: "7a0f0ad0-text-id", + }) + }) + + it("returns 429 quota_exceeded when user is over the daily cap", async () => { + mockGetSession.mockResolvedValueOnce({ user: { id: "u1", email: "x@y.com" } }) + mockRpc.mockImplementation((name: string) => { + if (name === "get_user_tokens_today") return Promise.resolve({ data: 600_000, error: null }) + return Promise.resolve({ data: 0, error: null }) + }) + const result = await withAuthAndQuota(makeRequest({ authorization: "Bearer valid" })) + expect("status" in result && result.status).toBe(429) + const body = await (result as Response).json() + expect(body.error).toBe("quota_exceeded") + }) + + it("returns 503 when the RPC fails (fails-closed on DB errors)", async () => { + mockGetSession.mockResolvedValueOnce({ user: { id: "u1", email: "x@y.com" } }) + mockRpc.mockImplementation(() => + Promise.resolve({ data: null, error: { message: "DB down" } }), + ) + const result = await withAuthAndQuota(makeRequest({ authorization: "Bearer valid" })) + expect("status" in result && result.status).toBe(503) + }) +}) diff --git a/apps/web/types/supabase.ts b/apps/web/types/supabase.ts index ece18d9..c700037 100644 --- a/apps/web/types/supabase.ts +++ b/apps/web/types/supabase.ts @@ -14,6 +14,115 @@ export type Database = { } public: { Tables: { + account: { + Row: { + accessToken: string | null + accessTokenExpiresAt: string | null + accountId: string + createdAt: string + id: string + idToken: string | null + password: string | null + providerId: string + refreshToken: string | null + refreshTokenExpiresAt: string | null + scope: string | null + updatedAt: string + userId: string + } + Insert: { + accessToken?: string | null + accessTokenExpiresAt?: string | null + accountId: string + createdAt?: string + id: string + idToken?: string | null + password?: string | null + providerId: string + refreshToken?: string | null + refreshTokenExpiresAt?: string | null + scope?: string | null + updatedAt?: string + userId: string + } + Update: { + accessToken?: string | null + accessTokenExpiresAt?: string | null + accountId?: string + createdAt?: string + id?: string + idToken?: string | null + password?: string | null + providerId?: string + refreshToken?: string | null + refreshTokenExpiresAt?: string | null + scope?: string | null + updatedAt?: string + userId?: string + } + Relationships: [ + { + foreignKeyName: "account_userId_fkey" + columns: ["userId"] + isOneToOne: false + referencedRelation: "user" + referencedColumns: ["id"] + }, + ] + } + deviceCode: { + Row: { + clientId: string | null + createdAt: string + deviceCode: string + expiresAt: string + id: string + lastPolledAt: string | null + pollingInterval: number | null + scope: string | null + status: string + updatedAt: string + userCode: string + userId: string | null + } + Insert: { + clientId?: string | null + createdAt?: string + deviceCode: string + expiresAt: string + id: string + lastPolledAt?: string | null + pollingInterval?: number | null + scope?: string | null + status: string + updatedAt?: string + userCode: string + userId?: string | null + } + Update: { + clientId?: string | null + createdAt?: string + deviceCode?: string + expiresAt?: string + id?: string + lastPolledAt?: string | null + pollingInterval?: number | null + scope?: string | null + status?: string + updatedAt?: string + userCode?: string + userId?: string | null + } + Relationships: [ + { + foreignKeyName: "deviceCode_userId_fkey" + columns: ["userId"] + isOneToOne: false + referencedRelation: "user" + referencedColumns: ["id"] + }, + ] + } global_daily_tokens: { Row: { day: string @@ -75,7 +184,56 @@ export type Database = { total_tokens?: number | null user_id?: string } - Relationships: [] + Relationships: [ + { + foreignKeyName: "llm_usage_events_user_id_fkey" + columns: ["user_id"] + isOneToOne: false + referencedRelation: "user" + referencedColumns: ["id"] + }, + ] + } + session: { + Row: { + createdAt: string + expiresAt: string + id: string + ipAddress: string | null + token: string + updatedAt: string + userAgent: string | null + userId: string + } + Insert: { + createdAt?: string + expiresAt: string + id: string + ipAddress?: string | null + token: string + updatedAt?: string + userAgent?: string | null + userId: string + } + Update: { + createdAt?: string + expiresAt?: string + id?: string + ipAddress?: string | null + token?: string + updatedAt?: string + userAgent?: string | null + userId?: string + } + Relationships: [ + { + foreignKeyName: "session_userId_fkey" + columns: ["userId"] + isOneToOne: false + referencedRelation: "user" + referencedColumns: ["id"] + }, + ] } tenant_articles: { Row: { @@ -140,6 +298,13 @@ export type Database = { referencedRelation: "tenants" referencedColumns: ["id"] }, + { + foreignKeyName: "tenant_articles_tenant_id_fkey" + columns: ["tenant_id"] + isOneToOne: false + referencedRelation: "tenants_public" + referencedColumns: ["id"] + }, ] } tenant_categories: { @@ -184,6 +349,13 @@ export type Database = { referencedRelation: "tenants" referencedColumns: ["id"] }, + { + foreignKeyName: "tenant_categories_tenant_id_fkey" + columns: ["tenant_id"] + isOneToOne: false + referencedRelation: "tenants_public" + referencedColumns: ["id"] + }, ] } tenant_chunks: { @@ -241,6 +413,13 @@ export type Database = { referencedRelation: "tenants" referencedColumns: ["id"] }, + { + foreignKeyName: "tenant_chunks_tenant_id_fkey" + columns: ["tenant_id"] + isOneToOne: false + referencedRelation: "tenants_public" + referencedColumns: ["id"] + }, ] } tenant_deploys: { @@ -282,6 +461,13 @@ export type Database = { referencedRelation: "tenants" referencedColumns: ["id"] }, + { + foreignKeyName: "tenant_deploys_tenant_id_fkey" + columns: ["tenant_id"] + isOneToOne: false + referencedRelation: "tenants_public" + referencedColumns: ["id"] + }, ] } tenant_mcp_queries: { @@ -320,6 +506,13 @@ export type Database = { referencedRelation: "tenants" referencedColumns: ["id"] }, + { + foreignKeyName: "tenant_mcp_queries_tenant_id_fkey" + columns: ["tenant_id"] + isOneToOne: false + referencedRelation: "tenants_public" + referencedColumns: ["id"] + }, ] } tenants: { @@ -359,6 +552,71 @@ export type Database = { theme_config?: Json updated_at?: string } + Relationships: [ + { + foreignKeyName: "tenants_owner_id_fkey" + columns: ["owner_id"] + isOneToOne: false + referencedRelation: "user" + referencedColumns: ["id"] + }, + ] + } + user: { + Row: { + createdAt: string + email: string + emailVerified: boolean + id: string + image: string | null + name: string + updatedAt: string + } + Insert: { + createdAt?: string + email: string + emailVerified?: boolean + id: string + image?: string | null + name: string + updatedAt?: string + } + Update: { + createdAt?: string + email?: string + emailVerified?: boolean + id?: string + image?: string | null + name?: string + updatedAt?: string + } + Relationships: [] + } + verification: { + Row: { + createdAt: string | null + expiresAt: string + id: string + identifier: string + updatedAt: string | null + value: string + } + Insert: { + createdAt?: string | null + expiresAt: string + id: string + identifier: string + updatedAt?: string | null + value: string + } + Update: { + createdAt?: string | null + expiresAt?: string + id?: string + identifier?: string + updatedAt?: string | null + value?: string + } Relationships: [] } waitlist_signups: { @@ -384,7 +642,30 @@ export type Database = { } } Views: { - [_ in never]: never + tenants_public: { + Row: { + active: boolean | null + id: string | null + name: string | null + slug: string | null + theme_config: Json | null + } + Insert: { + active?: boolean | null + id?: string | null + name?: string | null + slug?: string | null + theme_config?: Json | null + } + Update: { + active?: boolean | null + id?: string | null + name?: string | null + slug?: string | null + theme_config?: Json | null + } + Relationships: [] + } } Functions: { deploy_tenant: { diff --git a/packages/cli/package.json b/packages/cli/package.json index 1be36ab..2f738f2 100644 --- a/packages/cli/package.json +++ b/packages/cli/package.json @@ -1,6 +1,6 @@ { "name": "helpbase", - "version": "0.4.1", + "version": "0.5.0", "description": "CLI for managing your Helpbase help center", "type": "module", "bin": { diff --git a/packages/cli/src/commands/deploy.ts b/packages/cli/src/commands/deploy.ts index 2afd360..d34b672 100644 --- a/packages/cli/src/commands/deploy.ts +++ b/packages/cli/src/commands/deploy.ts @@ -1,17 +1,23 @@ import { Command } from "commander" -import { intro, outro, text, note, cancel, isCancel, confirm } from "@clack/prompts" +import { intro, outro, text, note, cancel, isCancel, confirm, select } from "@clack/prompts" import { spinner, nextSteps, summaryTable } from "../lib/ui.js" import pc from "picocolors" import fs from "node:fs" import path from "node:path" import matter from "gray-matter" import { frontmatterSchema, categoryMetaSchema, type TenantChunk, type DeployReport } from "@workspace/shared/schemas" -import { getAuthedSupabase } from "../lib/supabase-client.js" +import { + checkSlugAvailability, + createTenant as apiCreateTenant, + deleteTenant as apiDeleteTenant, + deployTenant as apiDeployTenant, + getTenant as apiGetTenant, + listMyTenants, + rotateMcpToken as apiRotateMcpToken, +} from "../lib/tenants-client.js" import { getCurrentSession, isNonInteractive, - sendLoginCode, - verifyLoginCode, type AuthSession, } from "../lib/auth.js" import { @@ -19,7 +25,6 @@ import { removeProjectConfig, writeProjectConfig, } from "../lib/project-config.js" -import { HelpbaseError, formatError } from "../lib/errors.js" const SLUG_REGEX = /^[a-z0-9][a-z0-9-]*[a-z0-9]$/ // Kept in sync with RESERVED_SLUGS in link.ts and the subdomain-middleware allowlist. @@ -77,37 +82,75 @@ Examples: // 2. Authenticate const session = await ensureAuthenticated() - const client = await getAuthedSupabase(session) // 3. Get or create tenant - // Priority: .helpbase/project.json → owner lookup → create new + // Priority: .helpbase/project.json → owner lookup → create new. + // All tenant CRUD now goes through /api/v1/tenants/* — the CLI + // talks to the hosted API instead of Supabase directly. Better + // Auth session tokens are not Supabase JWTs, and the RLS *_own + // policies were dropped in the 2026-04-17 migration; ownership + // is enforced server-side. const linked = readProjectConfig() let existingTenant: { id: string; slug: string } | null = null if (linked) { - const { data } = await client - .from("tenants") - .select("id, slug") - .eq("id", linked.tenantId) - .eq("active", true) - .single() - if (data) { - existingTenant = data + // apiGetTenant now throws on 403 (caller isn't the owner). Treat + // that as "fix your link" the same as a missing/inactive row. + const tenant = await apiGetTenant(session, linked.tenantId).catch( + () => null, + ) + if (tenant && tenant.active) { + existingTenant = { id: tenant.id, slug: tenant.slug } } else { cancel( - `Linked tenant "${linked.slug}" not found or inactive.\n` + + `Linked tenant "${linked.slug}" not found, inactive, or not owned by you.\n` + ` Run ${pc.cyan("helpbase link --remove")} then ${pc.cyan("helpbase link")} to fix.`, ) process.exit(1) } } else { - const { data } = await client - .from("tenants") - .select("id, slug") - .eq("owner_id", session.userId) - .eq("active", true) - .single() - existingTenant = data ?? null + const tenants = await listMyTenants(session) + if (tenants.length === 0) { + existingTenant = null + } else if (tenants.length === 1) { + const only = tenants[0]! + existingTenant = { id: only.id, slug: only.slug } + } else if (opts.slug) { + // Multi-tenant + explicit --slug: honor the choice if it matches + // one the user owns; otherwise treat it as "create a new tenant + // with this slug" downstream (which will 409 if taken). + const match = tenants.find((t) => t.slug === opts.slug) + existingTenant = match ? { id: match.id, slug: match.slug } : null + } else if (isNonInteractive()) { + cancel( + `You own ${tenants.length} tenants. Pass ${pc.cyan("--slug ")} ` + + `to pick one in non-interactive mode.`, + ) + process.exit(1) + } else { + // Interactive disambiguation — tenants[0] was non-deterministic. + const pickedValue = await select({ + message: "You own multiple tenants. Which one should this project deploy to?", + options: [ + ...tenants.map((t) => ({ + value: t.id, + label: `${t.slug}.helpbase.dev`, + hint: t.name ?? undefined, + })), + { value: "__new__", label: pc.cyan("+ Create a new tenant") }, + ], + }) + if (isCancel(pickedValue)) { + cancel("Cancelled.") + process.exit(0) + } + if (pickedValue === "__new__") { + existingTenant = null + } else { + const picked = tenants.find((t) => t.id === pickedValue)! + existingTenant = { id: picked.id, slug: picked.slug } + } + } } let tenantId: string @@ -160,32 +203,19 @@ Examples: } // Check availability - const { data: taken } = await client - .from("tenants") - .select("slug") - .eq("slug", slug) - .single() - - if (taken) { + const availability = await checkSlugAvailability(slug) + if (!availability.available) { cancel(`Subdomain "${slug}" is already taken. Try another with --slug `) process.exit(1) } - const { data: newTenant, error: createError } = await client - .from("tenants") - .insert({ - slug, - owner_id: session.userId, - name: slug, - }) - .select() - .single() - - if (createError || !newTenant) { - // Handle slug collision from concurrent creates (DB unique constraint) - const msg = createError?.message ?? "Unknown error" - if (msg.includes("duplicate") || msg.includes("unique")) { - cancel(`Subdomain "${slug}" was just taken. Try another with --slug `) + let newTenant: Awaited> + try { + newTenant = await apiCreateTenant(session, slug) + } catch (err) { + const msg = err instanceof Error ? err.message : String(err) + if (/slug_taken|slug_reserved/.test(msg)) { + cancel(`Subdomain "${slug}" is unavailable. Try another with --slug `) } else { cancel(`Failed to create tenant: ${msg}`) } @@ -207,19 +237,12 @@ Examples: if (opts.rotateMcpToken) { const rotateSpinner = spinner() rotateSpinner.start("Rotating MCP token...") - // Generate a 32-byte hex token client-side so the CLI can print it - // without a second round-trip. - const newToken = Array.from( - crypto.getRandomValues(new Uint8Array(32)), - (b) => b.toString(16).padStart(2, "0"), - ).join("") - const { error: rotateErr } = await client - .from("tenants") - .update({ mcp_public_token: newToken }) - .eq("id", tenantId) - if (rotateErr) { + let newToken: string + try { + newToken = await apiRotateMcpToken(session, tenantId) + } catch (err) { rotateSpinner.stop("Rotation failed") - cancel(`Failed to rotate token: ${rotateErr.message}`) + cancel(`Failed to rotate token: ${err instanceof Error ? err.message : String(err)}`) process.exit(1) } rotateSpinner.stop(`Rotated MCP token for ${tenantSlug}`) @@ -378,68 +401,48 @@ Examples: dropped: [], ran_at: new Date().toISOString(), } - const { data: deployId, error: rpcError } = await client.rpc("deploy_tenant", { - p_tenant_id: tenantId, - p_categories: categories.map((c) => ({ - slug: c.slug, - title: c.title, - description: c.description, - icon: c.icon, - order: c.order, - })), - p_articles: articles.map((a) => ({ - slug: a.slug, - category: a.category, - title: a.title, - description: a.description, - content: a.content, - frontmatter: a.frontmatter, - order: a.order, - tags: a.tags, - hero_image: a.heroImage, - video_embed: a.videoEmbed, - featured: a.featured, - file_path: a.filePath, - })), - p_chunks: chunks, - p_validation_report: validationReport, - }) - - if (rpcError) { + let deployResult: Awaited> + try { + deployResult = await apiDeployTenant(session, tenantId, { + categories: categories.map((c) => ({ + slug: c.slug, + title: c.title, + description: c.description, + icon: c.icon, + order: c.order, + })), + articles: articles.map((a) => ({ + slug: a.slug, + category: a.category, + title: a.title, + description: a.description, + content: a.content, + frontmatter: a.frontmatter, + order: a.order, + tags: a.tags, + hero_image: a.heroImage, + video_embed: a.videoEmbed, + featured: a.featured, + file_path: a.filePath, + })), + chunks, + validation_report: validationReport as unknown as Record, + }) + } catch (err) { s.stop("Deploy failed") - cancel(`Deploy RPC error: ${rpcError.message}`) + cancel(`Deploy error: ${err instanceof Error ? err.message : String(err)}`) process.exit(1) } - s.stop(`Published ${articles.length} articles, ${chunks.length} chunks (deploy ${String(deployId).slice(0, 8)})`) - - // 7. Fetch the tenant's MCP token for the copy-paste config snippet. - const { data: tenantAfter } = await client - .from("tenants") - .select("mcp_public_token") - .eq("id", tenantId) - .single() - const mcpToken = tenantAfter?.mcp_public_token ?? "" + s.stop( + `Published ${deployResult.article_count} articles, ${deployResult.chunk_count} chunks ` + + `(deploy ${deployResult.deploy_id.slice(0, 8)})`, + ) - // 8. Trigger on-demand revalidation (fail-soft: warn but don't break the deploy). - try { - const revalUrl = `https://${tenantSlug}.helpbase.dev/api/revalidate` - const revalRes = await fetch(revalUrl, { - method: "POST", - headers: { - "Content-Type": "application/json", - Authorization: `Bearer ${session.accessToken}`, - }, - body: JSON.stringify({ tenant_id: tenantId }), - }) - if (!revalRes.ok) { - note( - `Revalidation returned ${revalRes.status} — pages will catch up within 1h ISR window.`, - pc.yellow("Warning"), - ) - } - } catch { - // network error or DNS not propagated; non-blocking - } + // Fetch the tenant's MCP token for the copy-paste config snippet. + // Server-side revalidation runs inside /api/v1/tenants/:id/deploy, so + // no second round-trip for cache invalidation is needed. + const tenantAfter = await apiGetTenant(session, tenantId).catch(() => null) + const mcpToken = tenantAfter?.mcp_public_token ?? "" // 9. Done. const liveUrl = `https://${tenantSlug}.helpbase.dev` @@ -573,61 +576,14 @@ async function ensureAuthenticated(): Promise { process.exit(1) } - 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) - } + // Browser device-flow is the only supported interactive login path. + // Don't inline it here — `helpbase login` owns the full UX (progressive + // spinner hints, URL-paste fallback, retries). Telling the user to run + // that command keeps deploy focused on deploying. + cancel( + `Not signed in. Run ${pc.cyan("helpbase login")} first, then re-run ${pc.cyan("helpbase deploy")}.`, + ) + process.exit(1) } /** @@ -656,28 +612,24 @@ async function handleDelete( } const session = await ensureAuthenticated() - const client = await getAuthedSupabase(session) - - // Resolve tenant + verify ownership. - const { data: tenant, error: lookupError } = await client - .from("tenants") - .select("id, slug, owner_id") - .eq("slug", slug) - .maybeSingle() - if (lookupError) { - cancel(`Failed to look up tenant: ${lookupError.message}`) - process.exit(1) - } + // Resolve the tenant row among the user's own tenants. Ownership + // filter is implicit: listMyTenants only returns rows the caller owns. + const tenants = await listMyTenants(session) + const tenant = tenants.find((t) => t.slug === slug) ?? null if (!tenant) { - cancel(`Tenant "${slug}" not found.`) - process.exit(1) - } - if (tenant.owner_id !== session.userId) { - cancel( - `Tenant "${slug}" is not owned by the current user.\n` + - ` Only the owner can delete a tenant.`, - ) + // Either the slug doesn't exist, or it exists but the caller doesn't + // own it. Either way we refuse — the server-side DELETE endpoint + // would 403 anyway, but failing here gives a cleaner CLI message. + const availability = await checkSlugAvailability(slug).catch(() => null) + if (availability && !availability.available) { + cancel( + `Tenant "${slug}" is not owned by the current user.\n` + + ` Only the owner can delete a tenant.`, + ) + } else { + cancel(`Tenant "${slug}" not found.`) + } process.exit(1) } @@ -704,14 +656,11 @@ async function handleDelete( const s = spinner() s.start(`Deleting "${slug}"...`) - const { error: deleteError } = await client - .from("tenants") - .delete() - .eq("id", tenant.id) - - if (deleteError) { + try { + await apiDeleteTenant(session, tenant.id) + } catch (err) { s.stop("Delete failed") - cancel(`Failed to delete tenant: ${deleteError.message}`) + cancel(`Failed to delete tenant: ${err instanceof Error ? err.message : String(err)}`) process.exit(1) } diff --git a/packages/cli/src/commands/link.ts b/packages/cli/src/commands/link.ts index 3e0c3c4..fc3f4e6 100644 --- a/packages/cli/src/commands/link.ts +++ b/packages/cli/src/commands/link.ts @@ -3,7 +3,13 @@ import { intro, outro, select, text, cancel, isCancel, note } from "@clack/promp import { spinner } from "../lib/ui.js" import pc from "picocolors" import { getCurrentSession, isNonInteractive } from "../lib/auth.js" -import { getAuthedSupabase } from "../lib/supabase-client.js" +import { + checkSlugAvailability, + createTenant as apiCreateTenant, + getTenant as apiGetTenant, + listMyTenants, +} from "../lib/tenants-client.js" +import type { AuthSession } from "../lib/auth.js" import { readProjectConfig, removeProjectConfig, @@ -53,11 +59,9 @@ export const linkCommand = new Command("link") intro(pc.bgCyan(pc.black(" helpbase link "))) - const client = await getAuthedSupabase(session) - // Non-interactive path: --slug supplied. if (opts.slug) { - await linkBySlug(client, opts.slug) + await linkBySlug(opts.slug, session) outro(`Linked to ${pc.cyan(`${opts.slug}.helpbase.dev`)}`) return } @@ -69,22 +73,15 @@ export const linkCommand = new Command("link") const s = spinner() s.start("Loading your tenants...") - const { data: tenants, error } = await client - .from("tenants") - .select("id, slug, name") - .eq("owner_id", session.userId) - .eq("active", true) - .order("created_at", { ascending: false }) - s.stop( - error - ? "Failed to load tenants" - : `Found ${tenants?.length ?? 0} tenant(s)`, - ) - - if (error) { - cancel(`Failed to load tenants: ${error.message}`) + let tenants: Awaited> + try { + tenants = await listMyTenants(session) + } catch (err) { + s.stop("Failed to load tenants") + cancel(`Failed to load tenants: ${err instanceof Error ? err.message : String(err)}`) process.exit(1) } + s.stop(`Found ${tenants.length} tenant(s)`) type Choice = string const CREATE_NEW: Choice = "__new__" @@ -108,7 +105,7 @@ export const linkCommand = new Command("link") if (picked === CREATE_NEW) { const slug = await promptForNewSlug() - const created = await createTenant(client, session.userId, slug) + const created = await createTenant(session, slug) writeProjectConfig({ tenantId: created.id, slug: created.slug }) outro( `${pc.green("✓")} Created and linked ${pc.cyan(`${created.slug}.helpbase.dev`)}\n` + @@ -150,61 +147,65 @@ async function promptForNewSlug(): Promise { return input as string } -async function linkBySlug( - // eslint-disable-next-line @typescript-eslint/no-explicit-any - client: any, - slug: string, -): Promise { - const { data: tenant, error } = await client - .from("tenants") - .select("id, slug") - .eq("slug", slug) - .eq("active", true) - .single() - - if (error || !tenant) { +async function linkBySlug(slug: string, session: AuthSession): Promise { + const availability = await checkSlugAvailability(slug) + if (availability.available) { cancel( - `Tenant "${slug}" not found or you don't have access.\n` + - ` Run ${pc.cyan("helpbase link")} without --slug to see your tenants.`, + `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) } - - writeProjectConfig({ tenantId: tenant.id, slug: tenant.slug }) + if (!availability.id) { + cancel("Availability check did not return an id.") + process.exit(1) + } + // checkSlugAvailability hits a public endpoint — "taken" only proves + // the slug exists, not that this user owns it. Confirm ownership before + // writing .helpbase/project.json, otherwise the user gets a misleading + // 403 on the next `helpbase deploy`/`open`/`whoami`. + // + // getTenant returns null on 404 (gone between the availability check + // and now — rare, but possible) and throws on 403 (caller isn't the + // owner). Treat both as "you can't link this slug" but print the + // right copy for each. + let owned: Awaited> + try { + owned = await apiGetTenant(session, availability.id) + } catch (err) { + const msg = err instanceof Error ? err.message : String(err) + if (/\(403\)/.test(msg)) { + cancel( + `You don't own "${slug}.helpbase.dev".\n` + + ` Pick a different subdomain, or run ${pc.cyan("helpbase link")} to see what you own.`, + ) + process.exit(1) + } + cancel(`Could not verify tenant ownership: ${msg}`) + process.exit(1) + } + if (!owned) { + cancel(`Tenant "${slug}" disappeared before linking. Try again.`) + process.exit(1) + } + writeProjectConfig({ tenantId: availability.id, slug: availability.slug ?? slug }) } async function createTenant( - // eslint-disable-next-line @typescript-eslint/no-explicit-any - client: any, - userId: string, + session: AuthSession, slug: string, ): Promise<{ id: string; slug: string }> { - const { data: taken } = await client - .from("tenants") - .select("slug") - .eq("slug", slug) - .single() - - if (taken) { - cancel(`Subdomain "${slug}" is already taken. Try another.`) - process.exit(1) - } - - const { data, error } = await client - .from("tenants") - .insert({ slug, owner_id: userId, name: slug }) - .select("id, slug") - .single() - - if (error || !data) { - const msg = error?.message ?? "Unknown error" - if (msg.includes("duplicate") || msg.includes("unique")) { - cancel(`Subdomain "${slug}" was just taken. Try another.`) + try { + const created = await apiCreateTenant(session, slug) + return { id: created.id, slug: created.slug } + } catch (err) { + const msg = err instanceof Error ? err.message : String(err) + if (/slug_taken|slug_reserved/.test(msg)) { + cancel(`Subdomain "${slug}" is unavailable. Try another.`) } else { cancel(`Failed to create tenant: ${msg}`) } process.exit(1) } - - return data } diff --git a/packages/cli/src/commands/login.ts b/packages/cli/src/commands/login.ts index 308ca37..e5fd703 100644 --- a/packages/cli/src/commands/login.ts +++ b/packages/cli/src/commands/login.ts @@ -3,10 +3,10 @@ import { intro, outro, text, cancel, isCancel, note, confirm } from "@clack/prom import { spinner, nextSteps } from "../lib/ui.js" import pc from "picocolors" import { + deviceLogin, getCurrentSession, isNonInteractive, sendLoginCode, - verifyLoginCode, verifyLoginFromMagicLink, } from "../lib/auth.js" import { HelpbaseError, formatError } from "../lib/errors.js" @@ -17,8 +17,8 @@ import { export const loginCommand = new Command("login") .description("Log in to helpbase cloud") - .option("-e, --email ", "Email address (skips the prompt)") - .action(async (opts: { email?: string }) => { + .option("-e, --email [email]", "Use magic-link email fallback (CI / sandboxed envs)") + .action(async (opts: { email?: string | true }) => { if (isNonInteractive()) { console.error( `${pc.red("✖")} HELPBASE_TOKEN is set — you're already authenticated for non-interactive use.\n` + @@ -39,72 +39,127 @@ export const loginCommand = new Command("login") intro(pc.bgCyan(pc.black(" helpbase login "))) - let email = opts.email - if (!email) { - const input = 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(input)) { - cancel("Cancelled.") - process.exit(0) - } - email = input as string + // Branch: --email (or --email foo@bar.com) forces the magic-link flow. + // Without the flag, we do browser device flow (RFC 8628). + if (opts.email !== undefined) { + await runMagicLinkFlow(typeof opts.email === "string" ? opts.email : undefined) + return } - const s = spinner() - s.start("Sending magic link...") - try { - await sendLoginCode(email) - 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) + await runDeviceFlow() + }) + +async function runDeviceFlow(): Promise { + const s = spinner() + s.start("Requesting device authorization…") + // Captured from onStart so the "1 minute until expiry" hint is driven + // by the server's actual expires_in instead of a hardcoded 300s + // assumption. onProgress runs after onStart inside deviceLogin. + let expiresInMs: number | null = null + try { + const session = await deviceLogin({ + onStart: (info) => { + expiresInMs = info.expires_in * 1000 + s.stop("Device code ready.") + note( + `${pc.dim("Code")}: ${pc.cyan(info.user_code)}\n` + + `${pc.dim("URL")}: ${pc.cyan(info.verification_uri_complete || info.verification_uri)}\n\n` + + `${pc.dim("If your browser didn't open automatically, paste the URL above.")}\n` + + `${pc.dim("Compare the code to what the browser shows — if they differ, cancel and retry.")}`, + "Open your browser to authorize", + ) + s.start("Waiting for browser approval…") + }, + onProgress: (elapsedMs) => { + // Progressive hints — keep the user oriented during long waits. + if (expiresInMs !== null && elapsedMs > expiresInMs - 60_000) { + s.message("Under 1 minute until this code expires.") + } else if (elapsedMs > 90_000) { + s.message( + "Taking longer than usual. Ctrl-C to cancel, then run `helpbase login --email` for the fallback.", + ) + } else if (elapsedMs > 30_000) { + s.message("Still waiting… check that a browser tab opened.") + } + }, + }) + s.stop(`Logged in as ${pc.cyan(session.email)}`) + await maybeAskTelemetryConsent() + outro(`Logged in as ${pc.cyan(session.email)}`) + nextSteps({ commands: ["helpbase whoami", "helpbase new"] }) + } catch (err) { + s.stop("Login failed.") + if (err instanceof HelpbaseError) { + cancel(formatError(err).trimEnd()) + } else { + cancel(`Login error: ${String(err)}`) } + process.exit(1) + } +} +async function runMagicLinkFlow(preset?: string): Promise { + let email = preset + if (!email) { const input = await text({ - message: "Paste the magic link URL from the email (or the 6-digit code, if your template shows one):", - placeholder: "https://helpbase.dev/#access_token=... or 123456", + message: "Enter your email:", + placeholder: "you@company.com", validate: (v) => { - const t = v.trim() - if (!t) return "Paste the URL or code" - if (t.startsWith("http")) return undefined - if (/^\d{6}$/.test(t)) return undefined - return "Expected a full URL starting with http or a 6-digit code" + if (!v.includes("@")) return "Please enter a valid email" + return undefined }, }) if (isCancel(input)) { cancel("Cancelled.") process.exit(0) } + email = input as string + } - const trimmed = (input as string).trim() - - try { - const session = trimmed.startsWith("http") - ? verifyLoginFromMagicLink(trimmed) - : await verifyLoginCode(email, trimmed) - await maybeAskTelemetryConsent() - outro(`Logged in as ${pc.cyan(session.email)}`) - nextSteps({ commands: ["helpbase link", "helpbase new"] }) - } catch (err) { - if (err instanceof HelpbaseError) { - cancel(formatError(err).trimEnd()) - } else { - cancel(`Verification failed: ${String(err)}`) - } - process.exit(1) + const s = spinner() + s.start("Sending magic link…") + try { + await sendLoginCode(email) + 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 input = await text({ + message: "Paste the magic link URL from the email:", + placeholder: "https://helpbase.dev/api/auth/magic-link/verify?token=…", + validate: (v) => { + const t = v.trim() + if (!t) return "Paste the URL" + if (!t.startsWith("http")) return "Expected a full URL starting with http" + return undefined + }, }) + if (isCancel(input)) { + cancel("Cancelled.") + process.exit(0) + } + + try { + const session = await verifyLoginFromMagicLink((input as string).trim()) + await maybeAskTelemetryConsent() + outro(`Logged in as ${pc.cyan(session.email)}`) + nextSteps({ commands: ["helpbase whoami", "helpbase new"] }) + } catch (err) { + if (err instanceof HelpbaseError) { + cancel(formatError(err).trimEnd()) + } else { + cancel(`Verification failed: ${String(err)}`) + } + process.exit(1) + } +} /** * Ask once, after the user's first successful login, whether they want to diff --git a/packages/cli/src/commands/open.ts b/packages/cli/src/commands/open.ts index febc505..a1e983e 100644 --- a/packages/cli/src/commands/open.ts +++ b/packages/cli/src/commands/open.ts @@ -3,7 +3,7 @@ import { execSync } from "node:child_process" import pc from "picocolors" import { readProjectConfig } from "../lib/project-config.js" import { getCurrentSession } from "../lib/auth.js" -import { getAuthedSupabase } from "../lib/supabase-client.js" +import { listMyTenants } from "../lib/tenants-client.js" export const openCommand = new Command("open") .description("Open this project's help center in the default browser") @@ -47,19 +47,12 @@ async function resolveSlug(): Promise { const config = readProjectConfig() if (config) return config.slug - // Fallback: look up the user's active tenant if they're logged in. + // Fallback: ask the hosted API for the user's tenants if they're logged in. const session = await getCurrentSession() if (!session) return null - try { - const client = await getAuthedSupabase(session) - const { data } = await client - .from("tenants") - .select("slug") - .eq("owner_id", session.userId) - .eq("active", true) - .single() - return data?.slug ?? null + const tenants = await listMyTenants(session) + return tenants[0]?.slug ?? null } catch { return null } diff --git a/packages/cli/src/commands/whoami.ts b/packages/cli/src/commands/whoami.ts index eec3a4a..7a4d077 100644 --- a/packages/cli/src/commands/whoami.ts +++ b/packages/cli/src/commands/whoami.ts @@ -1,7 +1,7 @@ import { Command } from "commander" import pc from "picocolors" import { getCurrentSession } from "../lib/auth.js" -import { getAuthedSupabase } from "../lib/supabase-client.js" +import { listMyTenants } from "../lib/tenants-client.js" import { fetchUsageToday, isByokMode } from "@workspace/shared/llm" import { humanTokens, humanUntil } from "@workspace/shared/llm-errors" import { BYOK_DOCS_URL } from "@workspace/shared/llm-wire" @@ -48,16 +48,13 @@ export const whoamiCommand = new Command("whoami") const source = process.env.HELPBASE_TOKEN ? "HELPBASE_TOKEN" : "~/.helpbase/auth.json" // Best-effort tenant lookup — we don't fail whoami if this errors. + // Goes through /api/v1/tenants/mine (owner filter + active check are + // enforced server-side with the user's Better Auth bearer). let tenant: { slug: string; name: string } | null = null try { - const client = await getAuthedSupabase(session) - const { data } = await client - .from("tenants") - .select("slug, name") - .eq("owner_id", session.userId) - .eq("active", true) - .single() - if (data) tenant = data + const tenants = await listMyTenants(session) + const first = tenants[0] + if (first) tenant = { slug: first.slug, name: first.name } } catch { // ignore — tenant lookup is informational } diff --git a/packages/cli/src/lib/auth-client.ts b/packages/cli/src/lib/auth-client.ts new file mode 100644 index 0000000..8046980 --- /dev/null +++ b/packages/cli/src/lib/auth-client.ts @@ -0,0 +1,258 @@ +/** + * Lightweight REST client for helpbase.dev's Better Auth endpoints. + * + * The CLI used to depend on `@supabase/supabase-js` to run magic-link OTP + * against Supabase. As of 2026-04-17 auth moved to Better Auth (see + * apps/web/lib/auth.ts). The CLI now speaks directly to Better Auth's + * HTTP endpoints via native fetch — we intentionally skip the + * `better-auth/client` package to keep the CLI dep tree lean (a 5-LOC + * fetch wrapper beats pulling in the full auth framework on every dlx). + * + * Endpoints used: + * POST /api/auth/sign-in/magic-link { email, callbackURL? } + * GET /api/auth/magic-link/verify?token= → 302 + Set-Auth-Token: + * GET /api/auth/get-session Authorization: Bearer + * + * Base URL: + * HELPBASE_BASE_URL env (dev override, e.g. http://localhost:3001) + * falls back to https://helpbase.dev in prod. + */ + +export interface BetterAuthUser { + id: string + email: string + name: string + emailVerified: boolean + image: string | null + createdAt: string + updatedAt: string +} + +export interface BetterAuthSession { + id: string + token: string + userId: string + expiresAt: string + ipAddress?: string | null + userAgent?: string | null +} + +export interface SessionResponse { + user: BetterAuthUser + session: BetterAuthSession +} + +const DEFAULT_BASE = "https://helpbase.dev" + +/** + * Trim an untrusted server response body to a short, token-safe snippet + * before splicing it into a user-facing error message. The server should + * never echo a bearer or verification token, but if it does (misconfigured + * middleware, an echo-server used for debugging) we'd otherwise leak it + * into CLI stderr + the opt-in telemetry pipeline. + * + * Redacts any run of >=24 URL-safe base64 / base64url characters — matches + * the shape of Better Auth sessionId.signature tokens, device codes, and + * magic-link verification tokens. + */ +function safeSnippet(body: string): string { + return body.slice(0, 200).replace(/[A-Za-z0-9_+/=-]{24,}/g, "[redacted]") +} + +export function getAuthBaseUrl(): string { + const override = process.env.HELPBASE_BASE_URL?.trim() + return (override && override.length > 0 ? override : DEFAULT_BASE).replace(/\/+$/, "") +} + +function authUrl(path: string): string { + return `${getAuthBaseUrl()}/api/auth${path.startsWith("/") ? path : `/${path}`}` +} + +/** + * Fire a magic-link sign-in. Server sends the email via Resend (prod) or + * prints the link to the dev server's stderr (local). Callback URL is a + * no-op for the CLI path — the user pastes the URL back; the CLI hits + * `/verify` directly to complete. + */ +export async function sendMagicLink(email: string): Promise { + const res = await fetch(authUrl("/sign-in/magic-link"), { + method: "POST", + headers: { "content-type": "application/json" }, + body: JSON.stringify({ + email, + // Still required by Better Auth even when we consume the verify link + // ourselves; it sets the Location on the 302 but the CLI ignores it. + callbackURL: "/", + }), + }) + if (!res.ok) { + const text = await res.text().catch(() => "") + throw new Error(`magic-link request failed (${res.status}): ${safeSnippet(text)}`) + } +} + +/** + * Consume a Better Auth magic-link verification URL OR just the token + * parameter extracted from it. Returns the bearer token the server mints, + * which is identical to session.token in the database. + * + * The URL may carry helpbase.dev's prod host even in dev; we extract just + * the `token` query param and re-issue the GET against getAuthBaseUrl() + * so local dev + prod follow the same code path. + */ +export async function consumeMagicLink(urlOrToken: string): Promise { + const token = extractVerificationToken(urlOrToken) + if (!token) { + throw new Error("Couldn't find a verification token in the URL.") + } + const res = await fetch( + authUrl(`/magic-link/verify?token=${encodeURIComponent(token)}&callbackURL=/`), + { + method: "GET", + redirect: "manual", // we want the 302 + auth-token header, not the browser target + }, + ) + if (res.status !== 302 && !res.ok) { + const text = await res.text().catch(() => "") + throw new Error(`magic-link verify failed (${res.status}): ${safeSnippet(text)}`) + } + const bearer = res.headers.get("set-auth-token") + if (!bearer) { + throw new Error( + "Server accepted the magic link but did not return a bearer token. " + + "This means the link was already used or expired.", + ) + } + return bearer +} + +/** + * RFC 8628 device authorization grant. + * + * startDeviceAuth() → POST /api/auth/device/code + * pollDeviceAuth(deviceCode, interval) → POST /api/auth/device/token + * + * The server is Better Auth's `deviceAuthorization` plugin (see + * apps/web/lib/auth.ts). The CLI never needs a bearer token until the + * flow completes; polling is unauthenticated and the plugin gates + * issuance on the user having Authorize'd the userCode in a browser. + */ + +export interface DeviceCodeResponse { + device_code: string + user_code: string + verification_uri: string + verification_uri_complete: string + expires_in: number + interval: number +} + +export type DevicePollError = + | "authorization_pending" + | "slow_down" + | "access_denied" + | "expired_token" + | "invalid_request" + | "invalid_grant" + +export async function startDeviceAuth( + clientId = "helpbase-cli", +): Promise { + const res = await fetch(authUrl("/device/code"), { + method: "POST", + headers: { "content-type": "application/json" }, + body: JSON.stringify({ client_id: clientId, scope: "openid profile email" }), + }) + if (!res.ok) { + const text = await res.text().catch(() => "") + throw new Error(`device/code failed (${res.status}): ${safeSnippet(text)}`) + } + return (await res.json()) as DeviceCodeResponse +} + +/** + * One poll tick. Returns either a bearer token string (issued) or an + * error code the caller loops on. Never throws for protocol errors — + * only for transport / JSON failures. + */ +export async function pollDeviceAuth( + deviceCode: string, + clientId = "helpbase-cli", +): Promise<{ accessToken: string } | { error: DevicePollError; description?: string }> { + const res = await fetch(authUrl("/device/token"), { + method: "POST", + headers: { "content-type": "application/json" }, + body: JSON.stringify({ + grant_type: "urn:ietf:params:oauth:grant-type:device_code", + device_code: deviceCode, + client_id: clientId, + }), + }) + const text = await res.text() + let body: unknown + try { + body = text ? JSON.parse(text) : null + } catch { + throw new Error(`device/token: bad JSON (${res.status}): ${safeSnippet(text)}`) + } + if (res.ok) { + const obj = body as { access_token?: string } + if (obj.access_token) return { accessToken: obj.access_token } + throw new Error(`device/token: 2xx without access_token: ${safeSnippet(text)}`) + } + // Plugin returns RFC-shaped errors under non-2xx status. + const err = body as { error?: DevicePollError; error_description?: string } | null + if (err?.error) { + return { error: err.error, description: err.error_description } + } + throw new Error(`device/token: ${res.status} ${safeSnippet(text)}`) +} + +/** + * Fetch the session behind a bearer token. Returns null if the token is + * invalid or expired. Never throws for auth failures — callers use the + * null return to decide whether to re-prompt login. + */ +export async function getSessionWithBearer(bearer: string): Promise { + const res = await fetch(authUrl("/get-session"), { + headers: { authorization: `Bearer ${bearer}` }, + }) + if (!res.ok) return null + const text = await res.text() + if (!text || text === "null") return null + try { + const parsed = JSON.parse(text) as SessionResponse | null + if (!parsed?.user || !parsed.session) return null + return parsed + } catch { + return null + } +} + +function extractVerificationToken(input: string): string | null { + const trimmed = input.trim() + if (!trimmed) return null + // If the input is already a bare token (no URL shape), accept as-is. + if (!/[?#/]/.test(trimmed) && /^[A-Za-z0-9_-]+$/.test(trimmed) && trimmed.length >= 16) { + return trimmed + } + // Otherwise parse as URL. Supabase-style fragments had `?`/`#` — Better + // Auth uses a plain query string, so prefer query over fragment but fall + // back for robustness. + try { + const u = new URL(trimmed) + const q = u.searchParams.get("token") + if (q) return q + if (u.hash) { + const frag = new URLSearchParams(u.hash.slice(1)) + const f = frag.get("token") + if (f) return f + } + return null + } catch { + // Fallback: plain substring extraction for pasted fragments without a + // valid scheme (some email clients mangle URLs). + const m = /[?&#]token=([A-Za-z0-9_-]+)/.exec(trimmed) + return m ? m[1]! : null + } +} diff --git a/packages/cli/src/lib/auth-device.ts b/packages/cli/src/lib/auth-device.ts new file mode 100644 index 0000000..3118dd2 --- /dev/null +++ b/packages/cli/src/lib/auth-device.ts @@ -0,0 +1,206 @@ +import { spawn } from "node:child_process" +import { HelpbaseError } from "./errors.js" +import { storeSession, toAuthSession, type AuthSession } from "./auth.js" +import { + getSessionWithBearer, + pollDeviceAuth, + startDeviceAuth, + type DeviceCodeResponse, +} from "./auth-client.js" + +/** + * Run the browser device-flow (RFC 8628) end-to-end. Callers: + * 1. startDeviceAuth on the helpbase.dev auth server + * 2. open the verification URL in the user's default browser + * 3. poll the token endpoint, honoring the server-provided interval + * 4. on success, persist the bearer as the CLI session + * + * The `onProgress` callback lets UI layers update their spinner text as + * the wait drags on (progressive hints at T+30/90/240s per plan). + */ +export interface DeviceLoginOptions { + clientId?: string + onStart?: (info: DeviceCodeResponse) => void + onProgress?: (elapsedMs: number) => void + shouldOpenBrowser?: boolean + signal?: AbortSignal +} + +export async function deviceLogin(opts: DeviceLoginOptions = {}): Promise { + const clientId = opts.clientId ?? "helpbase-cli" + const info = await startDeviceAuth(clientId) + opts.onStart?.(info) + + if (opts.shouldOpenBrowser !== false) { + openBrowser(info.verification_uri_complete || info.verification_uri) + } + + const startedAt = Date.now() + let interval = Math.max(info.interval ?? 2, 1) * 1000 + const deadline = startedAt + info.expires_in * 1000 + // Tolerate a short run of transient network failures (DNS blip, captive- + // portal intercept, flaky LTE) during the polling window. Anything beyond + // this means the user's connection is genuinely broken. + const MAX_CONSECUTIVE_NETWORK_FAILS = 3 + let consecutiveFailures = 0 + + while (true) { + if (opts.signal?.aborted) { + throw new HelpbaseError({ + code: "E_AUTH_CANCELLED", + problem: "Login cancelled", + cause: "AbortSignal fired", + fix: ["Run `helpbase login` again when you're ready"], + }) + } + if (Date.now() > deadline) { + throw new HelpbaseError({ + code: "E_DEVICE_EXPIRED", + problem: "Device code expired before authorization", + cause: `The code expired after ${info.expires_in}s without an approval`, + fix: ["Run `helpbase login` again to get a fresh code"], + }) + } + + await sleep(interval) + opts.onProgress?.(Date.now() - startedAt) + + let result + try { + result = await pollDeviceAuth(info.device_code, clientId) + } catch (err) { + // A thrown error here is either an RFC-shape mismatch (server sent + // an unexpected status/JSON) or a transient network error. Don't let + // a single DNS blip abort a 5-minute wait — retry a few times first. + consecutiveFailures += 1 + if (consecutiveFailures >= MAX_CONSECUTIVE_NETWORK_FAILS) { + throw new HelpbaseError({ + code: "E_DEVICE_NETWORK", + problem: "Lost connection to helpbase.dev during login", + cause: + err instanceof Error + ? `${consecutiveFailures} consecutive polling errors; last: ${err.message}` + : `${consecutiveFailures} consecutive polling errors`, + fix: [ + "Check your network connection", + "Run `helpbase login` again once you're back online", + ], + }) + } + continue + } + consecutiveFailures = 0 + if ("accessToken" in result) { + let resp + try { + resp = await getSessionWithBearer(result.accessToken) + } catch { + // Treat this as a transient failure — the browser side succeeded, + // we just couldn't hydrate the session. Retry the outer loop; the + // next poll will take the "already-approved" branch again. + consecutiveFailures += 1 + if (consecutiveFailures >= MAX_CONSECUTIVE_NETWORK_FAILS) { + throw new HelpbaseError({ + code: "E_DEVICE_NETWORK", + problem: "Lost connection to helpbase.dev during login", + cause: "Could not fetch session after approval", + fix: [ + "Check your network connection", + "Run `helpbase login` again once you're back online", + ], + }) + } + continue + } + if (!resp) { + throw new HelpbaseError({ + code: "E_AUTH_VERIFY_OTP", + problem: "Server issued a token but no session came back", + cause: "getSession returned null with a freshly-minted bearer", + fix: ["Run `helpbase login` again", "Check helpbase.dev status"], + }) + } + const session = toAuthSession(resp, result.accessToken) + storeSession(session) + return session + } + + switch (result.error) { + case "authorization_pending": + continue + case "slow_down": + // Plugin asks us to back off. Add 5s per RFC. + interval += 5000 + continue + case "access_denied": + throw new HelpbaseError({ + code: "E_DEVICE_DENIED", + problem: "Authorization was cancelled in the browser", + cause: result.description ?? "User clicked Cancel", + fix: ["Run `helpbase login` again if that wasn't you"], + }) + case "expired_token": + throw new HelpbaseError({ + code: "E_DEVICE_EXPIRED", + problem: "Device code expired before authorization", + cause: result.description ?? "Token TTL elapsed", + fix: ["Run `helpbase login` again to get a fresh code"], + }) + default: + throw new HelpbaseError({ + code: "E_AUTH_VERIFY_OTP", + problem: "Device authorization failed", + cause: result.description ?? result.error, + fix: ["Run `helpbase login` again", "Or try `helpbase login --email`"], + }) + } + } +} + +export function sleep(ms: number): Promise { + return new Promise((resolve) => setTimeout(resolve, ms)) +} + +/** + * Spawn the platform's URL-opener for the sign-in page. No-op on remote + * environments (Codespaces, SSH) or when explicitly disabled — the CLI + * prints the URL to stdout as a fallback anyway. + */ +export function openBrowser(url: string): void { + const explicitOff = process.env.HELPBASE_LOGIN_NO_BROWSER === "1" + const looksHeadless = + process.env.CODESPACES === "true" || + Boolean(process.env.SSH_TTY) || + Boolean(process.env.SSH_CONNECTION) + if (explicitOff || looksHeadless) { + return + } + try { + let cmd: string + let args: string[] + if (process.platform === "darwin") { + cmd = "open" + args = [url] + } else if (process.platform === "win32") { + // `start` is a cmd.exe builtin, not a standalone exe, so spawning it + // directly ENOENTs. The empty "" is `start`'s optional window-title + // arg; without it, `start ""` treats the URL as the title and + // opens a blank cmd window instead of the browser. + cmd = "cmd" + args = ["/c", "start", "", url] + } else { + cmd = "xdg-open" + args = [url] + } + // ChildProcess ENOENT surfaces as an async "error" event; without a + // listener, Node historically re-raises it as unhandled. Attach a noop + // listener so a missing xdg-open on a minimal container doesn't crash. + const child = spawn(cmd, args, { detached: true, stdio: "ignore" }) + child.on("error", () => { + // best-effort — CLI prints the URL regardless + }) + child.unref() + } catch { + // best-effort — CLI prints the URL regardless + } +} diff --git a/packages/cli/src/lib/auth.ts b/packages/cli/src/lib/auth.ts index d137211..247eacd 100644 --- a/packages/cli/src/lib/auth.ts +++ b/packages/cli/src/lib/auth.ts @@ -1,18 +1,29 @@ import fs from "node:fs" import path from "node:path" import os from "node:os" -import { getAnonSupabase } from "./supabase-client.js" import { HelpbaseError } from "./errors.js" +import { + consumeMagicLink, + getSessionWithBearer, + sendMagicLink as apiSendMagicLink, + type SessionResponse, +} from "./auth-client.js" /** * Provider-agnostic auth layer. * - * The CLI currently authenticates against Supabase directly. When helpbase - * migrates to Better Auth, only this file needs to change — the surface - * (AuthSession, login/logout/whoami commands, HELPBASE_TOKEN) stays identical. + * As of 2026-04-17 the CLI authenticates against Better Auth (via + * helpbase.dev/api/auth/*) instead of calling Supabase directly. The + * AuthSession surface, ~/.helpbase/auth.json format, and HELPBASE_TOKEN + * env var contract are all preserved so the rest of the CLI — and any + * downstream user automation — sees no breaking change. * - * The access token is opaque to callers. They pass it back through - * getAuthedSupabase() in lib/supabase-client.ts when they need a DB client. + * Known deviation from the pre-migration behavior: Better Auth bearer + * tokens are opaque strings (not JWTs) and there is no refresh token. + * refreshToken is kept in the session object as an empty string for + * backwards-compat with the on-disk JSON shape. When the token expires + * (7 days by default), getCurrentSession returns null and callers + * prompt for a fresh `helpbase login`. */ export interface AuthSession { @@ -34,7 +45,9 @@ const TOKEN_ENV = "HELPBASE_TOKEN" * 1. HELPBASE_TOKEN env var (for CI / non-interactive). * 2. ~/.helpbase/auth.json (interactive login). * - * Returns null if neither source produces a valid session. + * Returns null if neither source produces a valid session. Callers treat + * null as "prompt for fresh login". A non-null result has been validated + * against the server at least once in the current invocation. */ export async function getCurrentSession(): Promise { const envToken = process.env[TOKEN_ENV] @@ -45,46 +58,39 @@ export async function getCurrentSession(): Promise { const stored = loadStoredSession() if (!stored) return null - const client = getAnonSupabase() - const { data, error } = await client.auth.setSession({ - access_token: stored.accessToken, - refresh_token: stored.refreshToken, - }) - - if (error || !data.session) { + const resp = await getSessionWithBearer(stored.accessToken) + if (!resp) { clearStoredSession() return null } - const refreshed: AuthSession = { - userId: data.session.user.id, - email: data.session.user.email ?? stored.email, - accessToken: data.session.access_token, - refreshToken: data.session.refresh_token, - expiresAt: data.session.expires_at ?? stored.expiresAt, - } - - if (refreshed.accessToken !== stored.accessToken) { + // Session token may have been rotated server-side; mirror any change to disk. + const refreshed = toAuthSession(resp, stored.accessToken) + if ( + refreshed.userId !== stored.userId || + refreshed.email !== stored.email || + refreshed.expiresAt !== stored.expiresAt + ) { storeSession(refreshed) } - return refreshed } /** - * Start an interactive login by sending a magic-link OTP to the given email. + * Start an interactive login by sending a magic-link email. Resend in + * prod, dev-console-fallback in local dev — see apps/web/lib/auth.ts. */ export async function sendLoginCode(email: string): Promise { - const client = getAnonSupabase() - const { error } = await client.auth.signInWithOtp({ email }) - if (error) { + try { + await apiSendMagicLink(email) + } catch (err) { throw new HelpbaseError({ code: "E_AUTH_SEND_OTP", - problem: "Could not send the login code", - cause: error.message, + problem: "Could not send the login link", + cause: err instanceof Error ? err.message : String(err), fix: [ "Check the email address for typos", - "Wait a minute if you just requested a code — rate limits apply", + "Wait a minute if you just requested a link — rate limits apply", "Try `helpbase login` again", ], }) @@ -92,140 +98,66 @@ export async function sendLoginCode(email: string): Promise { } /** - * Parse a Supabase magic-link URL (the thing the user clicks in their email) - * into an AuthSession. Supabase's default template sends only a link, not - * a 6-digit code, so accepting the link directly as a CLI paste is the - * fallback for projects that haven't added `{{ .Token }}` to their email - * template yet. - * - * The URL shape is: - * http:///#access_token=&refresh_token=&expires_at=&token_type=bearer&type=magiclink - * - * Fragment (not query) because that's what Supabase writes. We accept - * either for robustness — some email clients rewrite links. + * Consume a pasted Better Auth magic-link URL (or bare token). Calls + * /api/auth/magic-link/verify, extracts the set-auth-token response + * header, and persists the resulting session to ~/.helpbase/auth.json. * - * Stores the resulting session to `~/.helpbase/auth.json` so the rest of - * the CLI picks it up. + * Exposed as an async function now (pre-migration it was synchronous URL + * parsing only). Callers must `await`. */ -export function verifyLoginFromMagicLink(url: string): AuthSession { - const parsed = parseMagicLinkTokens(url) - if (!parsed) { +export async function verifyLoginFromMagicLink(url: string): Promise { + let bearer: string + try { + bearer = await consumeMagicLink(url) + } catch (err) { throw new HelpbaseError({ code: "E_AUTH_VERIFY_OTP", - problem: "Couldn't read the magic link", - cause: "No access_token in the URL you pasted", + problem: "Couldn't complete sign-in from that link", + cause: err instanceof Error ? err.message : String(err), fix: [ - "Copy the full URL from the email — everything after `#` matters", - "Run `helpbase login` again if it expired", + "Copy the full URL from the email — everything after `?` matters", + "Run `helpbase login` again if the link expired (10-minute TTL)", ], }) } - const session: AuthSession = { - userId: parsed.userId, - email: parsed.email, - accessToken: parsed.accessToken, - refreshToken: parsed.refreshToken, - expiresAt: parsed.expiresAt, + const resp = await getSessionWithBearer(bearer) + if (!resp) { + throw new HelpbaseError({ + code: "E_AUTH_VERIFY_OTP", + problem: "Server accepted the link but no session came back", + cause: "getSession returned null with a freshly-minted bearer", + fix: ["Run `helpbase login` again", "Check helpbase.dev status"], + }) } + const session = toAuthSession(resp, bearer) storeSession(session) return session } -interface ParsedMagicLink { - accessToken: string - refreshToken: string - expiresAt: number - userId: string - email: string -} - -function parseMagicLinkTokens(url: string): ParsedMagicLink | null { - // Supabase writes the session into the URL fragment (#key=value&...). - // Grab whatever comes after the first # OR ? — some email clients - // normalize the fragment into a query string. - const hashIdx = url.indexOf("#") - const queryIdx = url.indexOf("?") - let payload: string - if (hashIdx >= 0) { - payload = url.slice(hashIdx + 1) - } else if (queryIdx >= 0) { - payload = url.slice(queryIdx + 1) - } else { - return null - } - const params = new URLSearchParams(payload) - const accessToken = params.get("access_token") - const refreshToken = params.get("refresh_token") - const expiresAt = params.get("expires_at") - if (!accessToken || !refreshToken) return null - - // Decode the JWT just enough to extract `sub` + `email`. Supabase signs - // it so we don't need to verify here — any subsequent API call will - // reject a tampered token on the server side. - const jwtPayload = decodeJwtPayload(accessToken) - if (!jwtPayload) return null - const userId = typeof jwtPayload.sub === "string" ? jwtPayload.sub : "" - const email = typeof jwtPayload.email === "string" ? jwtPayload.email : "" - if (!userId || !email) return null - - return { - accessToken, - refreshToken, - expiresAt: expiresAt ? Number(expiresAt) : Math.floor(Date.now() / 1000) + 3600, - userId, - email, - } -} - -function decodeJwtPayload(jwt: string): Record | null { - const parts = jwt.split(".") - if (parts.length !== 3) return null - try { - // JWT uses base64url — normalize to base64 for Node's Buffer. - const b64 = parts[1]!.replace(/-/g, "+").replace(/_/g, "/") - const padded = b64.padEnd(Math.ceil(b64.length / 4) * 4, "=") - const json = Buffer.from(padded, "base64").toString("utf-8") - return JSON.parse(json) as Record - } catch { - return null - } -} +// deviceLogin + DeviceLoginOptions moved to ./auth-device.ts on 2026-04-17 +// as part of the /review split. They're re-exported here for backwards +// compatibility with callers that imported from "./lib/auth". +export { deviceLogin, type DeviceLoginOptions } from "./auth-device.js" /** - * Complete an interactive login by verifying the 6-digit code from the email. - * Stores the resulting session to ~/.helpbase/auth.json. + * Legacy 6-digit OTP path from the Supabase era. Better Auth's magic-link + * plugin does not mint numeric codes — the token in the email IS the + * verification artifact, and only works when fed through + * verifyLoginFromMagicLink. + * + * Kept as a stub so the login command's existing branch still compiles; + * callers that hit this receive a clear "not supported" message. */ -export async function verifyLoginCode(email: string, code: string): Promise { - const client = getAnonSupabase() - const { data, error } = await client.auth.verifyOtp({ - email, - token: code, - type: "email", +export async function verifyLoginCode(_email: string, _code: string): Promise { + throw new HelpbaseError({ + code: "E_AUTH_VERIFY_OTP", + problem: "6-digit code login is no longer supported", + cause: "The helpbase auth backend moved to browser device-flow + magic-link URLs", + fix: [ + "Paste the full URL from your sign-in email instead", + "Or upgrade to helpbase@0.5.0+ and use `helpbase login` (browser device-flow)", + ], }) - - if (error || !data.session) { - throw new HelpbaseError({ - code: "E_AUTH_VERIFY_OTP", - problem: "The login code didn't verify", - cause: error?.message ?? "Invalid or expired code", - fix: [ - "Run `helpbase login` again to get a fresh code", - "Check your spam folder for the latest email", - "Codes expire after a few minutes — use the newest one", - ], - }) - } - - const session: AuthSession = { - userId: data.session.user.id, - email: data.session.user.email ?? email, - accessToken: data.session.access_token, - refreshToken: data.session.refresh_token, - expiresAt: data.session.expires_at ?? Date.now() / 1000 + 3600, - } - - storeSession(session) - return session } /** @@ -253,9 +185,10 @@ interface StoredAuth { expires_at: number } -function storeSession(session: AuthSession): void { +export function storeSession(session: AuthSession): void { if (!fs.existsSync(AUTH_DIR)) { - fs.mkdirSync(AUTH_DIR, { recursive: true }) + // 0o700 on the dir so only the current user can traverse it. + fs.mkdirSync(AUTH_DIR, { recursive: true, mode: 0o700 }) } const data: StoredAuth = { user_id: session.userId, @@ -265,6 +198,34 @@ function storeSession(session: AuthSession): void { expires_at: session.expiresAt, } fs.writeFileSync(AUTH_FILE, JSON.stringify(data, null, 2), { mode: 0o600 }) + // writeFileSync's `mode` is only honored on file creation. If the file + // already existed (previous login with a loose umask, or pre-created by + // another user), the mode stays whatever it was. Force-narrow on every + // write so the bearer is never readable by other local users. + try { + fs.chmodSync(AUTH_FILE, 0o600) + } catch { + // best-effort — some filesystems (FAT, SMB) don't support chmod + } +} + +/** + * Build an AuthSession from a freshly-minted bearer + the server's session + * response. Centralizes the shape-conversion (ISO date → epoch seconds, + * refreshToken empty-string back-compat) so a future schema change touches + * one function instead of four call sites. + */ +export function toAuthSession(resp: SessionResponse, bearer: string): AuthSession { + return { + userId: resp.user.id, + email: resp.user.email, + accessToken: bearer, + // Better Auth doesn't expose a refresh token to bearer-mode clients; + // the field is kept as an empty string so the on-disk JSON layout is + // backwards-compatible with pre-migration installs. + refreshToken: "", + expiresAt: Math.floor(new Date(resp.session.expiresAt).getTime() / 1000), + } } function loadStoredSession(): AuthSession | null { @@ -276,7 +237,7 @@ function loadStoredSession(): AuthSession | null { userId: data.user_id, email: data.email, accessToken: data.access_token, - refreshToken: data.refresh_token, + refreshToken: data.refresh_token ?? "", expiresAt: data.expires_at, } } catch { @@ -291,26 +252,14 @@ function clearStoredSession(): void { } /** - * Resolve a HELPBASE_TOKEN env var into a session. - * - * Today the token is a raw Supabase access token. We verify it by calling - * getUser() which fails fast if the token is invalid/expired. When Better - * Auth lands, this becomes a call to the helpbase.dev /api/auth/verify - * endpoint — the rest of the CLI does not notice. + * Resolve a HELPBASE_TOKEN env var into a session. We validate the token + * against /api/auth/get-session so stale / revoked tokens fail fast with + * a clear "not logged in" signal instead of silently 401ing downstream. */ async function resolveTokenSession(token: string): Promise { - const client = getAnonSupabase() - const { data, error } = await client.auth.getUser(token) - if (error || !data.user) { - return null - } - return { - userId: data.user.id, - email: data.user.email ?? "", - accessToken: token, - // Tokens passed via HELPBASE_TOKEN are not refreshable from the CLI's - // perspective — they're expected to be long-lived or re-minted by CI. - refreshToken: "", - expiresAt: 0, - } + const resp = await getSessionWithBearer(token) + if (!resp) return null + // HELPBASE_TOKEN sessions are not refreshable from the CLI's + // perspective — they're expected to be long-lived or re-minted by CI. + return toAuthSession(resp, token) } diff --git a/packages/cli/src/lib/errors.ts b/packages/cli/src/lib/errors.ts index 6aaea84..0ee06d3 100644 --- a/packages/cli/src/lib/errors.ts +++ b/packages/cli/src/lib/errors.ts @@ -53,6 +53,10 @@ export type ErrorCode = | "E_GLOBAL_CAP" | "E_LLM_NETWORK" | "E_LLM_GATEWAY" + | "E_AUTH_CANCELLED" + | "E_DEVICE_DENIED" + | "E_DEVICE_EXPIRED" + | "E_DEVICE_NETWORK" export interface HelpbaseErrorInit { code: ErrorCode diff --git a/packages/cli/src/lib/inline-auth.ts b/packages/cli/src/lib/inline-auth.ts index e249921..dc32ba9 100644 --- a/packages/cli/src/lib/inline-auth.ts +++ b/packages/cli/src/lib/inline-auth.ts @@ -1,15 +1,13 @@ import pc from "picocolors" -import { confirm, isCancel } from "@clack/prompts" +import { confirm, isCancel, spinner } from "@clack/prompts" import { + deviceLogin, getCurrentSession, - sendLoginCode, - verifyLoginCode, isNonInteractive, type AuthSession, } from "./auth.js" -import { HelpbaseError } from "./errors.js" -import { text } from "@clack/prompts" -import { quotaExceededError, authRequiredError } from "./llm-errors-cli.js" +import { HelpbaseError, formatError } from "./errors.js" +import { authRequiredError } from "./llm-errors-cli.js" /** * Resolve the CLI's current auth session, or prompt the user to log in @@ -22,7 +20,8 @@ import { quotaExceededError, authRequiredError } from "./llm-errors-cli.js" * expired) → throw E_AUTH_REQUIRED. We do NOT fall into an interactive * prompt here: the env var signals explicit CI intent, and silently * replacing it with an interactive login would mask a broken CI token. - * 4. Else if TTY: prompt "Not signed in. Run helpbase login now? (Y/n)" → inline OTP. + * 4. Else if TTY: prompt to run the browser device-flow inline so the + * user stays in the current command instead of bouncing to `login`. * 5. Else (non-TTY or declined): throw E_AUTH_REQUIRED with the exact re-run command. */ export interface ResolveAuthOptions { @@ -71,34 +70,50 @@ export async function resolveAuthOrPromptLogin( console.log("") const go = await confirm({ - message: `Run ${pc.cyan("helpbase login")} now and continue?`, + message: `Open your browser to log in and continue with ${pc.cyan(opts.verb)}?`, initialValue: true, }) if (isCancel(go) || !go) { throw authRequiredError(opts.retryCommand) } - // Run the OTP flow inline, without dispatching the full `login` command - // so we return a session instead of printing its success message twice. - const email = await text({ - message: "Enter your email:", - placeholder: "you@company.com", - validate: (v) => (v.includes("@") ? undefined : "Please enter a valid email"), - }) - if (isCancel(email)) throw authRequiredError(opts.retryCommand) - - await sendLoginCode(email as string) - - const code = await text({ - message: "Enter the 6-digit code from your email:", - placeholder: "123456", - validate: (v) => (/^\d{6}$/.test(v) ? undefined : "Enter the 6-digit code"), - }) - if (isCancel(code)) throw authRequiredError(opts.retryCommand) - - const session = await verifyLoginCode(email as string, code as string) + // Run the browser device-flow inline so we return a session and keep + // the user in their current command instead of bouncing them through + // `helpbase login` and back. + const s = spinner() + s.start("Requesting device authorization…") + let session: AuthSession + try { + session = await deviceLogin({ + onStart: (info) => { + s.stop("Device code ready.") + console.log("") + console.log( + ` ${pc.dim("Code")}: ${pc.cyan(info.user_code)}\n` + + ` ${pc.dim("URL")}: ${pc.cyan(info.verification_uri_complete || info.verification_uri)}`, + ) + console.log( + ` ${pc.dim("If your browser didn't open, paste the URL above.")}`, + ) + console.log("") + s.start("Waiting for browser approval…") + }, + onProgress: (elapsedMs) => { + if (elapsedMs > 90_000) { + s.message("Still waiting… check that a browser tab opened.") + } + }, + }) + s.stop(`Signed in as ${pc.cyan(session.email)}`) + } catch (err) { + s.stop("Login failed.") + if (err instanceof HelpbaseError) { + process.stderr.write(formatError(err)) + } + throw authRequiredError(opts.retryCommand) + } console.log( - ` ${pc.green("✓")} Signed in as ${pc.cyan(session.email)}. Continuing with ${pc.bold(opts.verb)}...`, + ` ${pc.green("✓")} Continuing with ${pc.bold(opts.verb)}...`, ) console.log("") return { byok: false, authToken: session.accessToken, session } diff --git a/packages/cli/src/lib/supabase-client.ts b/packages/cli/src/lib/supabase-client.ts deleted file mode 100644 index 9213e13..0000000 --- a/packages/cli/src/lib/supabase-client.ts +++ /dev/null @@ -1,39 +0,0 @@ -import { createClient, type SupabaseClient } from "@supabase/supabase-js" -import type { AuthSession } from "./auth.js" - -/** - * Thin Supabase client factory. Auth lives in lib/auth.ts — this file only - * knows how to produce a client given (or not given) a session. - */ - -// Public Supabase credentials (safe to embed in CLI). This must match the -// project apps/web and the hosted-tier tables live on — otherwise the CLI -// authenticates against one project while the web app reads from another, -// so deploys go nowhere and logins look "expired" against the wrong audience. -const SUPABASE_URL = "https://rrlqttgjynfgxbhjkxnm.supabase.co" -const SUPABASE_ANON_KEY = - "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6InJybHF0dGdqeW5mZ3hiaGpreG5tIiwicm9sZSI6ImFub24iLCJpYXQiOjE3NzYzNTUzMTEsImV4cCI6MjA5MTkzMTMxMX0.EhBxN3v_RuTqorh6vETR7k6rZxfhJPKCA12JLmMVNO4" - -export function getAnonSupabase(): SupabaseClient { - return createClient(SUPABASE_URL, SUPABASE_ANON_KEY) -} - -/** - * Build a Supabase client authenticated as the session's user. - * Refresh-token-less sessions (HELPBASE_TOKEN) still work — writes go through - * RLS with the access token on every request. - */ -export async function getAuthedSupabase(session: AuthSession): Promise { - const client = createClient(SUPABASE_URL, SUPABASE_ANON_KEY, { - global: { - headers: { Authorization: `Bearer ${session.accessToken}` }, - }, - }) - if (session.refreshToken) { - await client.auth.setSession({ - access_token: session.accessToken, - refresh_token: session.refreshToken, - }) - } - return client -} diff --git a/packages/cli/src/lib/tenants-client.ts b/packages/cli/src/lib/tenants-client.ts new file mode 100644 index 0000000..8170950 --- /dev/null +++ b/packages/cli/src/lib/tenants-client.ts @@ -0,0 +1,193 @@ +/** + * CLI-side HTTP client for /api/v1/tenants/*. + * + * Replaces the old `getAuthedSupabase(session)` path that authenticated + * against Supabase directly. As of 2026-04-17 (Better Auth migration), + * Better Auth session tokens are not Supabase JWTs — tenant CRUD now + * goes through server-side API routes that enforce ownership with the + * service role. + * + * All methods take an already-resolved `AuthSession` (callers get one + * from `getCurrentSession()`) and send its accessToken as + * `Authorization: Bearer `. + */ + +import type { AuthSession } from "./auth.js" +import { getAuthBaseUrl } from "./auth-client.js" + +export interface TenantSummary { + id: string + slug: string + name: string +} + +export interface TenantDetail extends TenantSummary { + mcp_public_token: string + active: boolean +} + +export interface TenantCreated extends TenantSummary { + mcp_public_token: string +} + +export interface DeployResult { + deploy_id: string + article_count: number + chunk_count: number + slug: string +} + +export interface SlugAvailability { + available: boolean + id?: string + slug?: string +} + +function v1Url(path: string): string { + return `${getAuthBaseUrl()}/api/v1/tenants${path.startsWith("/") ? path : `/${path}`}` +} + +// Default per-request timeout. Short enough that a wedged TCP socket +// surfaces quickly, long enough to cover a cold Vercel function. Deploy +// can push a larger payload, so it gets a bumped timeout below. +const DEFAULT_TIMEOUT_MS = 30_000 +const DEPLOY_TIMEOUT_MS = 120_000 + +async function v1Fetch( + path: string, + init: RequestInit = {}, + timeoutMs: number = DEFAULT_TIMEOUT_MS, +): Promise { + return fetch(v1Url(path), { ...init, signal: AbortSignal.timeout(timeoutMs) }) +} + +async function parseBody(res: Response): Promise { + const text = await res.text().catch(() => "") + if (!text) return null + try { + return JSON.parse(text) + } catch { + return text + } +} + +function throwHttp(op: string, res: Response, body: unknown): never { + const msg = + body && typeof body === "object" && "error" in body + ? String((body as { error: unknown }).error) + : typeof body === "string" + ? body + : `${res.status}` + throw new Error(`${op} failed (${res.status}): ${msg}`) +} + +export async function listMyTenants(session: AuthSession): Promise { + const res = await v1Fetch("/mine", { + headers: { authorization: `Bearer ${session.accessToken}` }, + }) + const body = await parseBody(res) + if (!res.ok) throwHttp("list tenants", res, body) + const obj = body as { tenants?: TenantSummary[] } | null + return obj?.tenants ?? [] +} + +export async function getTenant( + session: AuthSession, + tenantId: string, +): Promise { + const res = await v1Fetch(`/${encodeURIComponent(tenantId)}`, { + headers: { authorization: `Bearer ${session.accessToken}` }, + }) + // 404 = tenant doesn't exist; callers treat this as "nothing to show". + // 403 = the caller authenticated but isn't the owner — surface that + // as a thrown error so callers can distinguish it from a missing row + // (e.g. link.ts prints "you don't own this subdomain"). + if (res.status === 404) return null + const body = await parseBody(res) + if (!res.ok) throwHttp("get tenant", res, body) + return body as TenantDetail +} + +export async function checkSlugAvailability(slug: string): Promise { + const res = await v1Fetch(`/by-slug/${encodeURIComponent(slug)}`) + const body = await parseBody(res) + if (!res.ok) throwHttp("slug availability", res, body) + return body as SlugAvailability +} + +export async function createTenant( + session: AuthSession, + slug: string, + name?: string, +): Promise { + const res = await v1Fetch("/", { + method: "POST", + headers: { + authorization: `Bearer ${session.accessToken}`, + "content-type": "application/json", + }, + body: JSON.stringify({ slug, name }), + }) + const body = await parseBody(res) + if (!res.ok) throwHttp("create tenant", res, body) + return body as TenantCreated +} + +export interface DeployPayload { + categories: unknown[] + articles: unknown[] + chunks: unknown[] + validation_report?: Record +} + +export async function deployTenant( + session: AuthSession, + tenantId: string, + payload: DeployPayload, +): Promise { + const res = await v1Fetch( + `/${encodeURIComponent(tenantId)}/deploy`, + { + method: "POST", + headers: { + authorization: `Bearer ${session.accessToken}`, + "content-type": "application/json", + }, + body: JSON.stringify(payload), + }, + DEPLOY_TIMEOUT_MS, + ) + const body = await parseBody(res) + if (!res.ok) throwHttp("deploy tenant", res, body) + return body as DeployResult +} + +export async function deleteTenant( + session: AuthSession, + tenantId: string, +): Promise<{ slug: string }> { + const res = await v1Fetch(`/${encodeURIComponent(tenantId)}`, { + method: "DELETE", + headers: { authorization: `Bearer ${session.accessToken}` }, + }) + const body = await parseBody(res) + if (!res.ok) throwHttp("delete tenant", res, body) + return body as { slug: string } +} + +export async function rotateMcpToken( + session: AuthSession, + tenantId: string, +): Promise { + const res = await v1Fetch(`/${encodeURIComponent(tenantId)}/rotate-mcp-token`, { + method: "POST", + headers: { authorization: `Bearer ${session.accessToken}` }, + }) + const body = await parseBody(res) + if (!res.ok) throwHttp("rotate mcp token", res, body) + const obj = body as { mcp_public_token?: string } + if (!obj.mcp_public_token) { + throw new Error("rotate mcp token: server did not return a token") + } + return obj.mcp_public_token +} diff --git a/packages/cli/test/auth-client.test.ts b/packages/cli/test/auth-client.test.ts new file mode 100644 index 0000000..fdccafd --- /dev/null +++ b/packages/cli/test/auth-client.test.ts @@ -0,0 +1,280 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest" +import { + consumeMagicLink, + getSessionWithBearer, + pollDeviceAuth, + sendMagicLink, + startDeviceAuth, +} from "../src/lib/auth-client.js" + +// Covers: extractVerificationToken (implicitly via consumeMagicLink), +// sendMagicLink, startDeviceAuth, pollDeviceAuth, consumeMagicLink, +// getSessionWithBearer. All network calls mocked via global.fetch stub. + +const realFetch = globalThis.fetch + +function stubFetch(handler: (url: string, init?: RequestInit) => Response | Promise) { + globalThis.fetch = vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => { + const url = typeof input === "string" ? input : input.toString() + return handler(url, init) + }) as typeof fetch +} + +beforeEach(() => { + // baseURL: default production host unless overridden + delete process.env.HELPBASE_BASE_URL +}) + +afterEach(() => { + globalThis.fetch = realFetch +}) + +describe("sendMagicLink", () => { + it("POSTs to /api/auth/sign-in/magic-link with the email + callback", async () => { + const calls: { url: string; body: unknown }[] = [] + stubFetch((url, init) => { + calls.push({ url, body: init?.body ? JSON.parse(String(init.body)) : null }) + return new Response("{}", { status: 200 }) + }) + await sendMagicLink("user@example.com") + expect(calls[0]!.url).toContain("/api/auth/sign-in/magic-link") + expect(calls[0]!.body).toMatchObject({ email: "user@example.com" }) + }) + + it("throws with the status + (redacted) body on non-2xx", async () => { + stubFetch(() => new Response("some-token-like-XhR9dK2pLmNqZvA4tBcDwEfG", { status: 429 })) + await expect(sendMagicLink("x@y.com")).rejects.toThrow(/429/) + // Token-like string must be redacted out of the thrown message. + await expect(sendMagicLink("x@y.com")).rejects.toThrow(/\[redacted\]/) + }) +}) + +describe("consumeMagicLink", () => { + it("rejects input with no token param", async () => { + await expect(consumeMagicLink("http://helpbase.dev/nope?foo=bar")).rejects.toThrow( + /verification token/, + ) + }) + + it("extracts token from query string and returns bearer from set-auth-token header", async () => { + stubFetch( + () => + new Response(null, { + status: 302, + headers: { + "set-auth-token": "bearer-42-sig", + location: "/", + }, + }), + ) + const bearer = await consumeMagicLink( + "http://helpbase.dev/api/auth/magic-link/verify?token=abcdef123456", + ) + expect(bearer).toBe("bearer-42-sig") + }) + + it("extracts token from hash fragment when query absent", async () => { + stubFetch( + () => + new Response(null, { + status: 302, + headers: { "set-auth-token": "bearer-from-hash" }, + }), + ) + const bearer = await consumeMagicLink("http://helpbase.dev/#token=hashtokenXYZ789") + expect(bearer).toBe("bearer-from-hash") + }) + + it("accepts a bare token string (no URL)", async () => { + stubFetch( + () => + new Response(null, { + status: 302, + headers: { "set-auth-token": "bearer-bare" }, + }), + ) + const bearer = await consumeMagicLink("plaintokenvaluewithmorethansixteenchars") + expect(bearer).toBe("bearer-bare") + }) + + it("rejects a 15-char bare string (below the min-length guard)", async () => { + await expect(consumeMagicLink("short_token_123")).rejects.toThrow(/verification token/) + }) + + it("throws on non-302 error status", async () => { + stubFetch(() => new Response("bad request", { status: 400 })) + await expect(consumeMagicLink("http://x/y?token=abcdefghijklmnop")).rejects.toThrow(/400/) + }) + + it("throws when 302 comes back but set-auth-token header is missing (replay)", async () => { + stubFetch(() => new Response(null, { status: 302 })) + await expect(consumeMagicLink("http://x/y?token=abcdefghijklmnop")).rejects.toThrow( + /already used or expired/, + ) + }) +}) + +describe("startDeviceAuth", () => { + it("POSTs to /device/code with scope + client_id", async () => { + const calls: { url: string; body: unknown }[] = [] + stubFetch((url, init) => { + calls.push({ url, body: init?.body ? JSON.parse(String(init.body)) : null }) + return new Response( + JSON.stringify({ + device_code: "dc", + user_code: "ABCD-1234", + verification_uri: "https://helpbase.dev/device", + verification_uri_complete: "https://helpbase.dev/device?user_code=ABCD-1234", + expires_in: 600, + interval: 2, + }), + { status: 200, headers: { "content-type": "application/json" } }, + ) + }) + const result = await startDeviceAuth("helpbase-cli") + expect(calls[0]!.url).toContain("/api/auth/device/code") + expect(calls[0]!.body).toMatchObject({ + client_id: "helpbase-cli", + scope: "openid profile email", + }) + expect(result.device_code).toBe("dc") + expect(result.user_code).toBe("ABCD-1234") + expect(result.expires_in).toBe(600) + }) + + it("throws with the status on failure", async () => { + stubFetch(() => new Response("bang", { status: 500 })) + await expect(startDeviceAuth()).rejects.toThrow(/device\/code failed \(500\)/) + }) +}) + +describe("pollDeviceAuth", () => { + it("returns {accessToken} on 2xx with access_token", async () => { + stubFetch( + () => + new Response(JSON.stringify({ access_token: "bearer-poll" }), { + status: 200, + headers: { "content-type": "application/json" }, + }), + ) + const out = await pollDeviceAuth("dc") + expect(out).toEqual({ accessToken: "bearer-poll" }) + }) + + it("returns {error: authorization_pending} on 400 RFC response", async () => { + stubFetch( + () => + new Response( + JSON.stringify({ + error: "authorization_pending", + error_description: "Authorization pending", + }), + { status: 400, headers: { "content-type": "application/json" } }, + ), + ) + const out = await pollDeviceAuth("dc") + expect(out).toEqual({ + error: "authorization_pending", + description: "Authorization pending", + }) + }) + + it("returns {error: slow_down} when server asks for backoff", async () => { + stubFetch( + () => + new Response(JSON.stringify({ error: "slow_down" }), { + status: 400, + headers: { "content-type": "application/json" }, + }), + ) + const out = await pollDeviceAuth("dc") + expect("error" in out && out.error).toBe("slow_down") + }) + + it("returns {error: access_denied} when user cancels", async () => { + stubFetch( + () => + new Response(JSON.stringify({ error: "access_denied" }), { + status: 400, + headers: { "content-type": "application/json" }, + }), + ) + const out = await pollDeviceAuth("dc") + expect("error" in out && out.error).toBe("access_denied") + }) + + it("returns {error: expired_token} when TTL hit", async () => { + stubFetch( + () => + new Response(JSON.stringify({ error: "expired_token" }), { + status: 400, + headers: { "content-type": "application/json" }, + }), + ) + const out = await pollDeviceAuth("dc") + expect("error" in out && out.error).toBe("expired_token") + }) + + it("throws on 2xx without access_token (protocol violation)", async () => { + stubFetch(() => new Response("{}", { status: 200, headers: { "content-type": "application/json" } })) + await expect(pollDeviceAuth("dc")).rejects.toThrow(/2xx without access_token/) + }) + + it("throws on non-JSON body", async () => { + stubFetch(() => new Response("500", { status: 500 })) + await expect(pollDeviceAuth("dc")).rejects.toThrow(/bad JSON/) + }) + + it("throws on non-2xx without RFC error body", async () => { + stubFetch(() => new Response(JSON.stringify({ unexpected: "shape" }), { status: 400 })) + await expect(pollDeviceAuth("dc")).rejects.toThrow(/device\/token: 400/) + }) +}) + +describe("getSessionWithBearer", () => { + it("returns session + user on 200", async () => { + stubFetch( + () => + new Response( + JSON.stringify({ + user: { + id: "u1", + email: "x@y.com", + name: "X Y", + emailVerified: true, + image: null, + createdAt: "2026-01-01T00:00:00Z", + updatedAt: "2026-01-01T00:00:00Z", + }, + session: { + id: "s1", + token: "tok", + userId: "u1", + expiresAt: "2026-04-24T00:00:00Z", + }, + }), + { status: 200, headers: { "content-type": "application/json" } }, + ), + ) + const s = await getSessionWithBearer("tok") + expect(s?.user.id).toBe("u1") + }) + + it("returns null on non-2xx", async () => { + stubFetch(() => new Response("nope", { status: 401 })) + const s = await getSessionWithBearer("bad") + expect(s).toBeNull() + }) + + it("returns null when the body is literal 'null'", async () => { + stubFetch(() => new Response("null", { status: 200, headers: { "content-type": "application/json" } })) + const s = await getSessionWithBearer("tok") + expect(s).toBeNull() + }) + + it("returns null on malformed JSON", async () => { + stubFetch(() => new Response("not-json", { status: 200 })) + const s = await getSessionWithBearer("tok") + expect(s).toBeNull() + }) +}) diff --git a/packages/cli/test/auth-device.test.ts b/packages/cli/test/auth-device.test.ts new file mode 100644 index 0000000..7a67163 --- /dev/null +++ b/packages/cli/test/auth-device.test.ts @@ -0,0 +1,151 @@ +import { afterAll, afterEach, beforeEach, describe, expect, it, vi } from "vitest" +import os from "node:os" +import path from "node:path" +import fs from "node:fs" + +// Stub the child_process spawn so deviceLogin's openBrowser call +// doesn't actually launch a browser during tests. +vi.mock("node:child_process", () => ({ + spawn: vi.fn(() => ({ unref: () => {}, on: () => {} })), +})) + +// Isolate AUTH_FILE writes per test run by pointing HOME at a tmp dir +// BEFORE importing the modules that capture AUTH_DIR at load time. +// Snapshot the originals so a shared-worker pool doesn't leak the fake +// HOME into other test files imported after this one. +const originalHome = process.env.HOME +const originalUserProfile = process.env.USERPROFILE +const TMP_HOME = fs.mkdtempSync(path.join(os.tmpdir(), "helpbase-auth-test-")) +process.env.HOME = TMP_HOME +process.env.USERPROFILE = TMP_HOME + +afterAll(() => { + if (originalHome === undefined) delete process.env.HOME + else process.env.HOME = originalHome + if (originalUserProfile === undefined) delete process.env.USERPROFILE + else process.env.USERPROFILE = originalUserProfile +}) + +const realFetch = globalThis.fetch +function stubFetch(handler: (url: string, init?: RequestInit) => Response | Promise) { + globalThis.fetch = vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => { + const url = typeof input === "string" ? input : input.toString() + return handler(url, init) + }) as typeof fetch +} + +// Import AFTER HOME is overridden so storeSession writes land in the tmp dir. +const { deviceLogin } = await import("../src/lib/auth-device.js") + +beforeEach(() => { + delete process.env.HELPBASE_LOGIN_NO_BROWSER + delete process.env.CODESPACES + delete process.env.SSH_TTY + delete process.env.SSH_CONNECTION +}) + +afterEach(() => { + globalThis.fetch = realFetch + // clean any auth.json written by the test + const f = path.join(TMP_HOME, ".helpbase", "auth.json") + if (fs.existsSync(f)) fs.unlinkSync(f) +}) + +// Helper: canned /device/code response + scripted /device/token sequence. +function scriptedFlow(pollResponses: Array<{ status: number; body: unknown }>) { + let pollIndex = 0 + stubFetch((url) => { + if (url.includes("/device/code")) { + return new Response( + JSON.stringify({ + device_code: "dc", + user_code: "ABCD-1234", + verification_uri: "https://helpbase.dev/device", + verification_uri_complete: "https://helpbase.dev/device?user_code=ABCD-1234", + expires_in: 600, + interval: 0.01, // tiny for test speed + }), + { status: 200, headers: { "content-type": "application/json" } }, + ) + } + if (url.includes("/device/token")) { + const r = pollResponses[Math.min(pollIndex, pollResponses.length - 1)]! + pollIndex += 1 + return new Response(JSON.stringify(r.body), { + status: r.status, + headers: { "content-type": "application/json" }, + }) + } + if (url.includes("/get-session")) { + return new Response( + JSON.stringify({ + user: { + id: "u1", + email: "u@example.com", + name: "U", + emailVerified: true, + image: null, + createdAt: "2026-01-01T00:00:00Z", + updatedAt: "2026-01-01T00:00:00Z", + }, + session: { + id: "s1", + token: "bearer-after-approve", + userId: "u1", + expiresAt: "2026-04-24T00:00:00Z", + }, + }), + { status: 200, headers: { "content-type": "application/json" } }, + ) + } + return new Response("unexpected", { status: 500 }) + }) +} + +describe("deviceLogin", () => { + it("returns an AuthSession on successful approval after a pending tick", async () => { + scriptedFlow([ + { status: 400, body: { error: "authorization_pending" } }, + { status: 200, body: { access_token: "bearer-after-approve" } }, + ]) + const session = await deviceLogin({ shouldOpenBrowser: false }) + expect(session.userId).toBe("u1") + expect(session.email).toBe("u@example.com") + expect(session.accessToken).toBe("bearer-after-approve") + }) + + it("throws E_DEVICE_DENIED when user clicks Cancel", async () => { + scriptedFlow([{ status: 400, body: { error: "access_denied", error_description: "User cancelled" } }]) + await expect(deviceLogin({ shouldOpenBrowser: false })).rejects.toMatchObject({ + code: "E_DEVICE_DENIED", + }) + }) + + it("throws E_DEVICE_EXPIRED on expired_token", async () => { + scriptedFlow([{ status: 400, body: { error: "expired_token" } }]) + await expect(deviceLogin({ shouldOpenBrowser: false })).rejects.toMatchObject({ + code: "E_DEVICE_EXPIRED", + }) + }) + + it("throws E_AUTH_CANCELLED when abort signal fires", async () => { + scriptedFlow([{ status: 400, body: { error: "authorization_pending" } }]) + const controller = new AbortController() + // Fire abort after the first poll tick starts sleeping. + setTimeout(() => controller.abort(), 5) + await expect( + deviceLogin({ shouldOpenBrowser: false, signal: controller.signal }), + ).rejects.toMatchObject({ code: "E_AUTH_CANCELLED" }) + }) + + it("calls onStart with the device-code info", async () => { + scriptedFlow([{ status: 200, body: { access_token: "bearer-after-approve" } }]) + const starts: unknown[] = [] + await deviceLogin({ + shouldOpenBrowser: false, + onStart: (info) => starts.push(info), + }) + expect(starts).toHaveLength(1) + expect((starts[0] as { user_code: string }).user_code).toBe("ABCD-1234") + }) +}) diff --git a/packages/cli/test/auth.unit.test.ts b/packages/cli/test/auth.unit.test.ts new file mode 100644 index 0000000..bc336cb --- /dev/null +++ b/packages/cli/test/auth.unit.test.ts @@ -0,0 +1,248 @@ +import { afterAll, afterEach, beforeEach, describe, expect, it, vi } from "vitest" +import fs from "node:fs" +import os from "node:os" +import path from "node:path" + +// Isolate AUTH_FILE writes per test run by pointing HOME at a tmp dir +// BEFORE importing the module that captures AUTH_DIR at load time. +// Snapshot and restore HOME/USERPROFILE so shared-worker pools can't +// leak the fake home into sibling test files. USERPROFILE is needed +// because os.homedir() reads it on Windows instead of HOME. +const originalHome = process.env.HOME +const originalUserProfile = process.env.USERPROFILE +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") + +afterAll(() => { + if (originalHome === undefined) delete process.env.HOME + else process.env.HOME = originalHome + if (originalUserProfile === undefined) delete process.env.USERPROFILE + else process.env.USERPROFILE = originalUserProfile +}) + +const realFetch = globalThis.fetch +function stubFetch(handler: (url: string) => Response | Promise) { + globalThis.fetch = vi.fn(async (input: RequestInfo | URL) => { + const url = typeof input === "string" ? input : input.toString() + return handler(url) + }) as typeof fetch +} + +const { getCurrentSession, toAuthSession, verifyLoginFromMagicLink } = await import( + "../src/lib/auth.js" +) + +beforeEach(() => { + delete process.env.HELPBASE_TOKEN + if (fs.existsSync(AUTH_FILE)) fs.unlinkSync(AUTH_FILE) +}) + +afterEach(() => { + globalThis.fetch = realFetch +}) + +describe("toAuthSession", () => { + it("maps SessionResponse fields to on-disk shape with epoch-seconds expiry", () => { + const session = toAuthSession( + { + user: { + id: "u1", + email: "x@y.com", + name: "X", + emailVerified: true, + image: null, + createdAt: "2026-01-01T00:00:00Z", + updatedAt: "2026-01-01T00:00:00Z", + }, + session: { + id: "s1", + token: "tok", + userId: "u1", + expiresAt: "2026-04-24T00:00:00Z", + }, + }, + "bearer-123", + ) + expect(session.userId).toBe("u1") + expect(session.email).toBe("x@y.com") + expect(session.accessToken).toBe("bearer-123") + expect(session.refreshToken).toBe("") + // 2026-04-24T00:00:00Z = 1777334400 in Unix seconds + expect(session.expiresAt).toBe(Math.floor(new Date("2026-04-24T00:00:00Z").getTime() / 1000)) + }) +}) + +describe("getCurrentSession", () => { + it("returns null when no stored session and no HELPBASE_TOKEN env", async () => { + expect(await getCurrentSession()).toBeNull() + }) + + it("clears the stored session when server returns null", async () => { + // Seed auth.json + fs.mkdirSync(path.dirname(AUTH_FILE), { recursive: true }) + fs.writeFileSync( + AUTH_FILE, + JSON.stringify({ + user_id: "u1", + email: "x@y.com", + access_token: "stale", + refresh_token: "", + expires_at: 0, + }), + ) + stubFetch(() => new Response("nope", { status: 401 })) + expect(await getCurrentSession()).toBeNull() + expect(fs.existsSync(AUTH_FILE)).toBe(false) + }) + + it("round-trips a valid stored session via server confirmation", async () => { + fs.mkdirSync(path.dirname(AUTH_FILE), { recursive: true }) + fs.writeFileSync( + AUTH_FILE, + JSON.stringify({ + user_id: "u1", + email: "x@y.com", + access_token: "valid", + refresh_token: "", + expires_at: 0, + }), + ) + stubFetch( + () => + new Response( + JSON.stringify({ + user: { + id: "u1", + email: "x@y.com", + name: "X", + emailVerified: true, + image: null, + createdAt: "2026-01-01T00:00:00Z", + updatedAt: "2026-01-01T00:00:00Z", + }, + session: { + id: "s1", + token: "valid", + userId: "u1", + expiresAt: "2026-04-24T00:00:00Z", + }, + }), + { status: 200 }, + ), + ) + const s = await getCurrentSession() + expect(s?.userId).toBe("u1") + expect(s?.email).toBe("x@y.com") + }) + + it("tolerates missing refresh_token field (pre-migration disk format)", async () => { + fs.mkdirSync(path.dirname(AUTH_FILE), { recursive: true }) + fs.writeFileSync( + AUTH_FILE, + JSON.stringify({ + user_id: "u1", + email: "x@y.com", + access_token: "valid", + // no refresh_token key — pre-migration Supabase JSON layout + expires_at: 0, + }), + ) + stubFetch( + () => + new Response( + JSON.stringify({ + user: { + id: "u1", + email: "x@y.com", + name: "X", + emailVerified: true, + image: null, + createdAt: "2026-01-01T00:00:00Z", + updatedAt: "2026-01-01T00:00:00Z", + }, + session: { + id: "s1", + token: "valid", + userId: "u1", + expiresAt: "2026-04-24T00:00:00Z", + }, + }), + { status: 200 }, + ), + ) + const s = await getCurrentSession() + expect(s?.userId).toBe("u1") + }) +}) + +describe("verifyLoginFromMagicLink", () => { + it("writes auth.json and returns an AuthSession on success", async () => { + stubFetch((url) => { + if (url.includes("/magic-link/verify")) { + return new Response(null, { + status: 302, + headers: { "set-auth-token": "fresh-bearer" }, + }) + } + if (url.includes("/get-session")) { + return new Response( + JSON.stringify({ + user: { + id: "u2", + email: "new@y.com", + name: "N", + emailVerified: true, + image: null, + createdAt: "2026-01-01T00:00:00Z", + updatedAt: "2026-01-01T00:00:00Z", + }, + session: { + id: "s2", + token: "fresh-bearer", + userId: "u2", + expiresAt: "2026-04-24T00:00:00Z", + }, + }), + { status: 200 }, + ) + } + return new Response("nope", { status: 500 }) + }) + const s = await verifyLoginFromMagicLink( + "http://helpbase.dev/api/auth/magic-link/verify?token=abcdef123456", + ) + expect(s.userId).toBe("u2") + expect(s.email).toBe("new@y.com") + expect(fs.existsSync(AUTH_FILE)).toBe(true) + const onDisk = JSON.parse(fs.readFileSync(AUTH_FILE, "utf-8")) + expect(onDisk.access_token).toBe("fresh-bearer") + }) + + it("throws E_AUTH_VERIFY_OTP on malformed magic link", async () => { + await expect(verifyLoginFromMagicLink("http://helpbase.dev/nope")).rejects.toMatchObject({ + code: "E_AUTH_VERIFY_OTP", + }) + }) + + it("throws E_AUTH_VERIFY_OTP when the server mints a bearer but getSession returns null", async () => { + stubFetch((url) => { + if (url.includes("/magic-link/verify")) { + return new Response(null, { + status: 302, + headers: { "set-auth-token": "fresh-bearer" }, + }) + } + if (url.includes("/get-session")) { + return new Response("null", { status: 200 }) + } + return new Response("nope", { status: 500 }) + }) + await expect( + verifyLoginFromMagicLink( + "http://helpbase.dev/api/auth/magic-link/verify?token=abcdef123456", + ), + ).rejects.toMatchObject({ code: "E_AUTH_VERIFY_OTP" }) + }) +}) diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 45eae1e..21c08d6 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -53,6 +53,9 @@ importers: ai: specifier: ^5.0.0 version: 5.0.171(zod@4.3.6) + better-auth: + specifier: ^1.6.5 + version: 1.6.5(@opentelemetry/api@1.9.0)(next@16.1.6(@opentelemetry/api@1.9.0)(react-dom@19.2.4(react@19.2.4))(react@19.2.4))(pg@8.20.0)(react-dom@19.2.4(react@19.2.4))(react@19.2.4)(vitest@4.1.3(@opentelemetry/api@1.9.0)(@types/node@25.2.3)(msw@2.13.2(@types/node@25.2.3)(typescript@5.9.3))(vite@8.0.7(@types/node@25.2.3)(esbuild@0.27.3)(jiti@2.6.1)(tsx@4.21.0)(yaml@2.8.3))) gray-matter: specifier: ^4.0.3 version: 4.0.3 @@ -68,6 +71,9 @@ importers: next-themes: specifier: ^0.4.6 version: 0.4.6(react-dom@19.2.4(react@19.2.4))(react@19.2.4) + pg: + specifier: ^8.20.0 + version: 8.20.0 react: specifier: ^19.2.4 version: 19.2.4 @@ -83,6 +89,9 @@ importers: remark-gfm: specifier: ^4.0.1 version: 4.0.1 + resend: + specifier: ^6.12.0 + version: 6.12.0 shiki: specifier: ^4.0.2 version: 4.0.2 @@ -99,6 +108,9 @@ importers: '@types/node': specifier: ^25.1.0 version: 25.2.3 + '@types/pg': + specifier: ^8.20.0 + version: 8.20.0 '@types/react': specifier: ^19.2.10 version: 19.2.14 @@ -535,6 +547,83 @@ packages: resolution: {integrity: sha512-LwdZHpScM4Qz8Xw2iKSzS+cfglZzJGvofQICy7W7v4caru4EaAmyUuO6BGrbyQ2mYV11W0U8j5mBhd14dd3B0A==} engines: {node: '>=6.9.0'} + '@better-auth/core@1.6.5': + resolution: {integrity: sha512-T3u4rVsJcMWShG2qfQUlU1HdkQGLYX0+lcR48QV2Cp2kpBOLOTYdt+p6zZtGm2Omx/ReEouRQyKy7pYtahRQuA==} + peerDependencies: + '@better-auth/utils': 0.4.0 + '@better-fetch/fetch': 1.1.21 + '@cloudflare/workers-types': '>=4' + '@opentelemetry/api': ^1.9.0 + better-call: 1.3.5 + jose: ^6.1.0 + kysely: ^0.28.5 + nanostores: ^1.0.1 + peerDependenciesMeta: + '@cloudflare/workers-types': + optional: true + + '@better-auth/drizzle-adapter@1.6.5': + resolution: {integrity: sha512-9YjPW35+h66D+QA+YqEJ9pFP97ClLFR+QrTPZojkeP0PTYqpW0ErBK3p1pwRTJG88yK+o3Y4yOwoacMTBxz0jQ==} + peerDependencies: + '@better-auth/core': ^1.6.5 + '@better-auth/utils': 0.4.0 + drizzle-orm: ^0.45.2 + peerDependenciesMeta: + drizzle-orm: + optional: true + + '@better-auth/kysely-adapter@1.6.5': + resolution: {integrity: sha512-kbevd70qzKNR3ZHF7q6/e0XXYRCXanLB2rvmTd3T8WbNEd9kYMqKjgTGNxL1ri5N+PEDUK6zfHx/HrvaEOfoHw==} + peerDependencies: + '@better-auth/core': ^1.6.5 + '@better-auth/utils': 0.4.0 + kysely: ^0.28.14 + peerDependenciesMeta: + kysely: + optional: true + + '@better-auth/memory-adapter@1.6.5': + resolution: {integrity: sha512-5qFUpSdQi+RwHSmNyHMSsJIrFjed8d/ASS61L2xyW7sjBLTIuR7JcgS6hif5cQbtPeq+Qz+Wct5q8oKw33qyqQ==} + peerDependencies: + '@better-auth/core': ^1.6.5 + '@better-auth/utils': 0.4.0 + + '@better-auth/mongo-adapter@1.6.5': + resolution: {integrity: sha512-HvOUFTiSEFSGTzL/vE3FntTwQiZ79O/V+QcsCimR+65Bj3tOqdFaC1G2Yd1dQ9l2YHNXA9SNBrGekbk66RzJMw==} + peerDependencies: + '@better-auth/core': ^1.6.5 + '@better-auth/utils': 0.4.0 + mongodb: ^6.0.0 || ^7.0.0 + peerDependenciesMeta: + mongodb: + optional: true + + '@better-auth/prisma-adapter@1.6.5': + resolution: {integrity: sha512-d7PUO5XoimYYDEG/DoYVbOSbyVYJBDuZgvY9pjf8INccBTCD1BzcyEJ9NQil4huXWj4fcNaGOt2FG0OI8NtWOA==} + peerDependencies: + '@better-auth/core': ^1.6.5 + '@better-auth/utils': 0.4.0 + '@prisma/client': ^5.0.0 || ^6.0.0 || ^7.0.0 + prisma: ^5.0.0 || ^6.0.0 || ^7.0.0 + peerDependenciesMeta: + '@prisma/client': + optional: true + prisma: + optional: true + + '@better-auth/telemetry@1.6.5': + resolution: {integrity: sha512-Ag3CjAP+tLretKPq+pYdU/gU4pFIcey/AoNQzw671wV5JQZXrMitS65INi8j8QuYfol2xgQrht5KVlcxGrkhHQ==} + peerDependencies: + '@better-auth/core': ^1.6.5 + '@better-auth/utils': 0.4.0 + '@better-fetch/fetch': 1.1.21 + + '@better-auth/utils@0.4.0': + resolution: {integrity: sha512-RpMtLUIQAEWMgdPLNVbIF5ON2mm+CH0U3rCdUCU1VyeAUui4m38DyK7/aXMLZov2YDjG684pS1D0MBllrmgjQA==} + + '@better-fetch/fetch@1.1.21': + resolution: {integrity: sha512-/ImESw0sskqlVR94jB+5+Pxjf+xBwDZF/N5+y2/q4EqD7IARUTSpPfIo8uf39SYpCxyOCtbyYpUrZ3F/k0zT4A==} + '@clack/core@0.4.2': resolution: {integrity: sha512-NYQfcEy8MWIxrT5Fj8nIVchfRFA26yYKJcvBS7WlUIlw2OmQOY9DhGGXMovyI5J5PpxrCPGkgUi207EBrjpBvg==} @@ -1183,6 +1272,10 @@ packages: resolution: {integrity: sha512-2I0gnIVPtfnMw9ee9h1dJG7tp81+8Ob3OJb3Mv37rx5L40/b0i7djjCVvGOVqc9AEIQyvyu1i6ypKdFw8R8gQw==} engines: {node: ^14.21.3 || >=16} + '@noble/ciphers@2.2.0': + resolution: {integrity: sha512-Z6pjIZ/8IJcCGzb2S/0Px5J81yij85xASuk1teLNeg75bfT07MV3a/O2Mtn1I2se43k3lkVEcFaR10N4cgQcZA==} + engines: {node: '>= 20.19.0'} + '@noble/curves@1.9.7': resolution: {integrity: sha512-gbKGcRUYIjA3/zCCNaWDciTMFI0dCkvou3TL8Zmy5Nc7sJ47a0jtOeZoTaMxkuqRo9cRhjOdZJXegxYE5FN/xw==} engines: {node: ^14.21.3 || >=16} @@ -1191,6 +1284,10 @@ packages: resolution: {integrity: sha512-jCs9ldd7NwzpgXDIf6P3+NrHh9/sD6CQdxHyjQI+h/6rDNo88ypBxxz45UDuZHz9r3tNz7N/VInSVoVdtXEI4A==} engines: {node: ^14.21.3 || >=16} + '@noble/hashes@2.2.0': + resolution: {integrity: sha512-IYqDGiTXab6FniAgnSdZwgWbomxpy9FtYvLKs7wCUs2a8RkITG+DFGO1DM9cr+E3/RgADRpFjrKVaJ1z6sjtEg==} + engines: {node: '>= 20.19.0'} + '@nodelib/fs.scandir@2.1.5': resolution: {integrity: sha512-vq24Bq3ym5HEQm2NKCr3yXDwjc7vTsEThRDnkp2DK9p1uqLR+DHurm/NOTo0KG7HYHU7eppKZj3MyqYuMBf62g==} engines: {node: '>= 8'} @@ -1216,6 +1313,10 @@ packages: resolution: {integrity: sha512-3giAOQvZiH5F9bMlMiv8+GSPMeqg0dbaeo58/0SlA9sxSqZhnUtxzX9/2FzyhS9sWQf5S0GJE0AKBrFqjpeYcg==} engines: {node: '>=8.0.0'} + '@opentelemetry/semantic-conventions@1.40.0': + resolution: {integrity: sha512-cifvXDhcqMwwTlTK04GBNeIe7yyo28Mfby85QXFe1Yk8nmi36Ab/5UQwptOx84SsoGNRg+EVSjwzfSZMy6pmlw==} + engines: {node: '>=14'} + '@oxc-project/types@0.123.0': resolution: {integrity: sha512-YtECP/y8Mj1lSHiUWGSRzy/C6teUKlS87dEfuVKT09LgQbUsBW1rNg+MiJ4buGu3yuADV60gbIvo9/HplA56Ew==} @@ -2206,6 +2307,9 @@ packages: resolution: {integrity: sha512-tlqY9xq5ukxTUZBmoOp+m61cqwQD5pHJtFY3Mn8CA8ps6yghLH/Hw8UPdqg4OLmFW3IFlcXnQNmo/dh8HzXYIQ==} engines: {node: '>=18'} + '@stablelib/base64@1.0.1': + resolution: {integrity: sha512-1bnPQqSxSuc3Ii6MhBysoWCg58j97aUjuCSZrGSmDxNqtytIi0k8utUenAwTZN4V5mXXYGsVUI9zeBqy+jBOSQ==} + '@standard-schema/spec@1.1.0': resolution: {integrity: sha512-l2aFy5jALhniG5HgqrD6jXLi/rUWrKvqN/qJx6yoJsgKhblVd+iqqU4RCXavm/jPityDo5TCvKMnpjKnOriy0w==} @@ -2428,6 +2532,9 @@ packages: '@types/node@25.2.3': resolution: {integrity: sha512-m0jEgYlYz+mDJZ2+F4v8D1AyQb+QzsNqRuI7xg1VQX/KlKS0qT9r1Mo16yo5F/MtifXFgaofIFsdFMox2SxIbQ==} + '@types/pg@8.20.0': + resolution: {integrity: sha512-bEPFOaMAHTEP1EzpvHTbmwR8UsFyHSKsRisLIHVMXnpNefSbGA1bD6CVy+qKjGSqmZqNqBDV2azOBo8TgkcVow==} + '@types/react-dom@19.2.3': resolution: {integrity: sha512-jp2L/eY6fn+KgVVQAOqYItbF0VY/YApe5Mz2F0aykSO8gx31bYCZyvSeYxCHKvzHG5eZjc+zyaS5BrBWya2+kQ==} peerDependencies: @@ -2783,6 +2890,76 @@ packages: engines: {node: '>=10.0.0'} deprecated: Security vulnerability fixed in 5.2.1, please upgrade + better-auth@1.6.5: + resolution: {integrity: sha512-rSt8JtJOJK0MqPShXINCmM6DV30GsDvnCTlIxQIzP9OpUx/umA40nUc4ALZHQyqAPbw1ib/a549kIWw/WyxxKA==} + peerDependencies: + '@lynx-js/react': '*' + '@prisma/client': ^5.0.0 || ^6.0.0 || ^7.0.0 + '@sveltejs/kit': ^2.0.0 + '@tanstack/react-start': ^1.0.0 + '@tanstack/solid-start': ^1.0.0 + better-sqlite3: ^12.0.0 + drizzle-kit: '>=0.31.4' + drizzle-orm: ^0.45.2 + mongodb: ^6.0.0 || ^7.0.0 + mysql2: ^3.0.0 + next: ^14.0.0 || ^15.0.0 || ^16.0.0 + pg: ^8.0.0 + prisma: ^5.0.0 || ^6.0.0 || ^7.0.0 + react: ^18.0.0 || ^19.0.0 + react-dom: ^18.0.0 || ^19.0.0 + solid-js: ^1.0.0 + svelte: ^4.0.0 || ^5.0.0 + vitest: ^2.0.0 || ^3.0.0 || ^4.0.0 + vue: ^3.0.0 + peerDependenciesMeta: + '@lynx-js/react': + optional: true + '@prisma/client': + optional: true + '@sveltejs/kit': + optional: true + '@tanstack/react-start': + optional: true + '@tanstack/solid-start': + optional: true + better-sqlite3: + optional: true + drizzle-kit: + optional: true + drizzle-orm: + optional: true + mongodb: + optional: true + mysql2: + optional: true + next: + optional: true + pg: + optional: true + prisma: + optional: true + react: + optional: true + react-dom: + optional: true + solid-js: + optional: true + svelte: + optional: true + vitest: + optional: true + vue: + optional: true + + better-call@1.3.5: + resolution: {integrity: sha512-kOFJkBP7utAQLEYrobZm3vkTH8mXq5GNgvjc5/XEST1ilVHaxXUXfeDeFlqoETMtyqS4+3/h4ONX2i++ebZrvA==} + peerDependencies: + zod: ^4.0.0 + peerDependenciesMeta: + zod: + optional: true + bl@4.1.0: resolution: {integrity: sha512-1W07cM9gS6DcLperZfFSj+bWLtaPGSOHWhPiGzXmvVJbRLdG82sH/Kn8EtW1VqWVA54AKf2h5k5BbnIbwF3h6w==} @@ -3166,6 +3343,9 @@ packages: resolution: {integrity: sha512-8QmQKqEASLd5nx0U1B1okLElbUuuttJ/AnYmRXbbbGDWh6uS208EjD4Xqq/I9wK7u0v6O08XhTWnt5XtEbR6Dg==} engines: {node: '>= 0.4'} + defu@6.1.7: + resolution: {integrity: sha512-7z22QmUWiQ/2d0KkdYmANbRUVABpZ9SNYyH5vx6PZ+nE5bcC0l7uFvEfHlyld/HcGBFTL536ClDt3DEcSlEJAQ==} + degenerator@5.0.1: resolution: {integrity: sha512-TllpMR/t0M5sqCXfj85i4XaAzxmS5tVA16dqvdkMwGmzI+dXLXnw3J+3Vdv7VKw+ThlTMboK6i9rnZ6Nntj5CQ==} engines: {node: '>= 14'} @@ -3513,6 +3693,9 @@ packages: fast-levenshtein@2.0.6: resolution: {integrity: sha512-DCXu6Ifhqcks7TZKY3Hxp3y6qphY5SJZmrWMDrKcERSOXWQdMhU9Ig/PYrzyw/ul9jOIyh0N4M0tbC5hodg8dw==} + fast-sha256@1.3.0: + resolution: {integrity: sha512-n11RGP/lrWEFI/bWdygLxhI+pVeo1ZYIVwvvPkW7azl/rOy+F3HYRZ2K5zeE9mmkhQppyv9sQFx0JM9UabnpPQ==} + fast-uri@3.1.0: resolution: {integrity: sha512-iPeeDKJSWf4IEOasVVrknXpaBV0IApz/gp7S2bb7Z4Lljbl2MGJRqInZiUrQwV16cpzw/D3S5j5Julj/gT52AA==} @@ -4221,6 +4404,10 @@ packages: resolution: {integrity: sha512-9zy9lkjac+TR1c2tG+mkNSVlyOpInnWdSMiue4F+kq8TwJSgv6o8jhLRg8Ho6SnZ9wOYUq/yozts9qQCfk7bIw==} engines: {node: '>=18'} + kysely@0.28.16: + resolution: {integrity: sha512-3i5pmOiZvMDj00qhrIVbH0AnioVTx22DMP7Vn5At4yJO46iy+FM8Y/g61ltenLVSo3fiO8h8Q3QOFgf/gQ72ww==} + engines: {node: '>=20.0.0'} + latest-version@9.0.0: resolution: {integrity: sha512-7W0vV3rqv5tokqkBAFV1LbR7HPOWzXQDpDgEuib/aJ1jsZZx6x3c2mBI+TJhJzOhkGeaLbCKEHXEXLfirtG2JA==} engines: {node: '>=18'} @@ -4692,6 +4879,10 @@ packages: engines: {node: ^10 || ^12 || ^13.7 || ^14 || >=15.0.1} hasBin: true + nanostores@1.2.0: + resolution: {integrity: sha512-F0wCzbsH80G7XXo0Jd9/AVQC7ouWY6idUCTnMwW5t/Rv9W8qmO6endavDwg7TNp5GbugwSukFMVZqzPSrSMndg==} + engines: {node: ^20.0.0 || >=22.0.0} + napi-build-utils@2.0.0: resolution: {integrity: sha512-GEbrYkbfF7MoNaoh2iGG84Mnf/WZfB0GdGEsM8wz7Expx/LlWf5U8t9nvJKXSp3qr5IsEbK04cBGhol/KwOsWA==} @@ -4965,6 +5156,40 @@ packages: pathe@2.0.3: resolution: {integrity: sha512-WUjGcAqP1gQacoQe+OBJsFA7Ld4DyXuUIjZ5cc75cLHvJ7dtNsTugphxIADwspS+AraAUePCKrSVtPLFj/F88w==} + pg-cloudflare@1.3.0: + resolution: {integrity: sha512-6lswVVSztmHiRtD6I8hw4qP/nDm1EJbKMRhf3HCYaqud7frGysPv7FYJ5noZQdhQtN2xJnimfMtvQq21pdbzyQ==} + + pg-connection-string@2.12.0: + resolution: {integrity: sha512-U7qg+bpswf3Cs5xLzRqbXbQl85ng0mfSV/J0nnA31MCLgvEaAo7CIhmeyrmJpOr7o+zm0rXK+hNnT5l9RHkCkQ==} + + pg-int8@1.0.1: + resolution: {integrity: sha512-WCtabS6t3c8SkpDBUlb1kjOs7l66xsGdKpIPZsg4wR+B3+u9UAum2odSsF9tnvxg80h4ZxLWMy4pRjOsFIqQpw==} + engines: {node: '>=4.0.0'} + + pg-pool@3.13.0: + resolution: {integrity: sha512-gB+R+Xud1gLFuRD/QgOIgGOBE2KCQPaPwkzBBGC9oG69pHTkhQeIuejVIk3/cnDyX39av2AxomQiyPT13WKHQA==} + peerDependencies: + pg: '>=8.0' + + pg-protocol@1.13.0: + resolution: {integrity: sha512-zzdvXfS6v89r6v7OcFCHfHlyG/wvry1ALxZo4LqgUoy7W9xhBDMaqOuMiF3qEV45VqsN6rdlcehHrfDtlCPc8w==} + + pg-types@2.2.0: + resolution: {integrity: sha512-qTAAlrEsl8s4OiEQY69wDvcMIdQN6wdz5ojQiOy6YRMuynxenON0O5oCpJI6lshc6scgAY8qvJ2On/p+CXY0GA==} + engines: {node: '>=4'} + + pg@8.20.0: + resolution: {integrity: sha512-ldhMxz2r8fl/6QkXnBD3CR9/xg694oT6DZQ2s6c/RI28OjtSOpxnPrUCGOBJ46RCUxcWdx3p6kw/xnDHjKvaRA==} + engines: {node: '>= 16.0.0'} + peerDependencies: + pg-native: '>=3.0.1' + peerDependenciesMeta: + pg-native: + optional: true + + pgpass@1.0.5: + resolution: {integrity: sha512-FdW9r/jQZhSeohs1Z3sI1yxFQNFvMcnmfuj4WBMUTxOrAyLMaTcE1aAMBiTlbMNaXvBCQuVi0R7hd8udDSP7ug==} + picocolors@1.0.1: resolution: {integrity: sha512-anP1Z8qwhkbmu7MFP5iTt+wQKXgwzf7zTyGlcdzabySa9vd0Xt392U0rVmz9poOaBj0uHJKyyo9/upk0HrEQew==} @@ -5001,6 +5226,9 @@ packages: resolution: {integrity: sha512-/+5VFTchJDoVj3bhoqi6UeymcD00DAwb1nJwamzPvHEszJ4FpF6SNNbUbOS8yI56qHzdV8eK0qEfOSiodkTdxg==} engines: {node: '>= 0.4'} + postal-mime@2.7.4: + resolution: {integrity: sha512-0WdnFQYUrPGGTFu1uOqD2s7omwua8xaeYGdO6rb88oD5yJ/4pPHDA4sdWqfD8wQVfCny563n/HQS7zTFft+f/g==} + postcss-load-config@6.0.1: resolution: {integrity: sha512-oPtTM4oerL+UXmx+93ytZVN82RrlY/wPUV8IeDxFrzIjXOLF1pN+EmKPLbubvKHT2HC20xXsCAH2Z+CKV6Oz/g==} engines: {node: '>= 18'} @@ -5039,6 +5267,22 @@ packages: resolution: {integrity: sha512-7a70Nsot+EMX9fFU3064K/kdHWZqGVY+BADLyXc8Dfv+mTLLVl6JzJpPaCZ2kQL9gIJvKXSLMHhqdRRjwQeFtw==} engines: {node: ^10 || ^12 || >=14} + postgres-array@2.0.0: + resolution: {integrity: sha512-VpZrUqU5A69eQyW2c5CA1jtLecCsN2U/bD6VilrFDWq5+5UIEVO7nazS3TEcHf1zuPYO/sqGvUvW62g86RXZuA==} + engines: {node: '>=4'} + + postgres-bytea@1.0.1: + resolution: {integrity: sha512-5+5HqXnsZPE65IJZSMkZtURARZelel2oXUEO8rH83VS/hxH5vv1uHquPg5wZs8yMAfdv971IU+kcPUczi7NVBQ==} + engines: {node: '>=0.10.0'} + + postgres-date@1.0.7: + resolution: {integrity: sha512-suDmjLVQg78nMK2UZ454hAG+OAW+HQPZ6n++TNDUX+L0+uUlLywnoxJKDou51Zm+zTCjrCl0Nq6J9C5hP9vK/Q==} + engines: {node: '>=0.10.0'} + + postgres-interval@1.2.0: + resolution: {integrity: sha512-9ZhXKM/rw350N1ovuWHbGxnGh/SNJ4cnxHiM0rxE4VN41wsg8P8zWn9hv/buK00RP4WvlOyr/RBDiptyxVbkZQ==} + engines: {node: '>=0.10.0'} + powershell-utils@0.1.0: resolution: {integrity: sha512-dM0jVuXJPsDN6DvRpea484tCUaMiXWjuCn++HGTqUWzGDjv5tZkEZldAJ/UMlqRYGFrD/etByo4/xOuC/snX2A==} engines: {node: '>=20'} @@ -5326,6 +5570,15 @@ packages: resolution: {integrity: sha512-Xf0nWe6RseziFMu+Ap9biiUbmplq6S9/p+7w7YXP/JBHhrUDDUhwa+vANyubuqfZWTveU//DYVGsDG7RKL/vEw==} engines: {node: '>=0.10.0'} + resend@6.12.0: + resolution: {integrity: sha512-CaxEvX1z+/MGbgnhsM/bvmkbnZd1v1sEXELAjBNSDBQNMaB7MgqOyrBgI27CYikEgdaDnBrXghAXYWTBs/h5Bw==} + engines: {node: '>=20'} + peerDependencies: + '@react-email/render': '*' + peerDependenciesMeta: + '@react-email/render': + optional: true + resolve-from@4.0.0: resolution: {integrity: sha512-pb/MYmXstAkysRFx8piNI1tGFNQIFA3vkE3Gq4EuA1dF6gHp/+vgZqsCGJapvy8N3Q+4o7FwvquPJcnZ7RYy4g==} engines: {node: '>=4'} @@ -5376,6 +5629,9 @@ packages: engines: {node: '>=18.0.0', npm: '>=8.0.0'} hasBin: true + rou3@0.7.12: + resolution: {integrity: sha512-iFE4hLDuloSWcD7mjdCDhx2bKcIsYbtOTpfH5MHHLSKMOUyjqQXTeZVa289uuwEGEKFoE/BAPbhaU4B774nceg==} + router@2.2.0: resolution: {integrity: sha512-nLTrUKm2UyiL7rlhapu/Zl45FwNgkZGaCpZbIHajDYgwlJCOzLSk+cIPAnsEqV955GjILJnKbdQC1nVPz+gAYQ==} engines: {node: '>= 18'} @@ -5445,6 +5701,9 @@ packages: resolution: {integrity: sha512-xRXBn0pPqQTVQiC8wyQrKs2MOlX24zQ0POGaj0kultvoOCstBQM5yvOhAVSUwOMjQtTvsPWoNCHfPGwaaQJhTw==} engines: {node: '>= 18'} + set-cookie-parser@3.1.0: + resolution: {integrity: sha512-kjnC1DXBHcxaOaOXBHBeRtltsDG2nUiUni+jP92M9gYdW12rsmx92UsfpH7o5tDRs7I1ZZPSQJQGv3UaRfCiuw==} + set-function-length@1.2.2: resolution: {integrity: sha512-pgRc4hJ4/sNjWCSS9AmnS40x3bNMDTknHgL5UaMBTMyJnU90EgWh1Rz+MC9eFu4BuN/UwZjKQuY/1v3rM7HMfg==} engines: {node: '>= 0.4'} @@ -5556,6 +5815,10 @@ packages: space-separated-tokens@2.0.2: resolution: {integrity: sha512-PEGlAwrG8yXGXRjW32fGbg66JAlOAwbObuqVoJpv/mRgoWDQfgH1wDPvtzWyUSNAXBGSk8h755YDbbcEy3SH2Q==} + split2@4.2.0: + resolution: {integrity: sha512-UcjcJOWknrNkF6PLX83qcHM6KHgVKNkV62Y8a5uYDVv9ydGQVwAHMKqHdJje1VTWpljG0WYpCDhrCdAOYH4TWg==} + engines: {node: '>= 10.x'} + sprintf-js@1.0.3: resolution: {integrity: sha512-D9cPgkvLlV3t3IzL0D0YLvGA9Ahk4PcvVwUbN0dSGr1aP0Nrt4AEnTUbuGvquEC0mA64Gqt1fzirlRs5ibXx8g==} @@ -5565,6 +5828,9 @@ packages: stackback@0.0.2: resolution: {integrity: sha512-1XMJE5fQo1jGH6Y/7ebnwPOBEkIEnT4QF32d5R1+VXdXveM0IBMJt8zfaxX1P3QhVwrYe+576+jkANtSS2mBbw==} + standardwebhooks@1.0.0: + resolution: {integrity: sha512-BbHGOQK9olHPMvQNHWul6MYlrRTAOKn03rOe4A8O3CLWhNf4YHBqq2HJKKC+sfqpxiBY52pNeesD6jIiLDz8jg==} + statuses@2.0.2: resolution: {integrity: sha512-DvEy55V3DB7uknRo+4iOGT5fP1slR8wQohVdknigZPMpMstaKJQWhwiYBACJE3Ul2pTnATihhBYnRhZQHGBiRw==} engines: {node: '>= 0.8'} @@ -5701,6 +5967,9 @@ packages: resolution: {integrity: sha512-ot0WnXS9fgdkgIcePe6RHNk1WA8+muPa6cSjeR3V8K27q9BB1rTE3R1p7Hv0z1ZyAc8s6Vvv8DIyWf681MAt0w==} engines: {node: '>= 0.4'} + svix@1.90.0: + resolution: {integrity: sha512-ljkZuyy2+IBEoESkIpn8sLM+sxJHQcPxlZFxU+nVDhltNfUMisMBzWX/UR8SjEnzoI28ZjCzMbmYAPwSTucoMw==} + swap-case@1.1.2: resolution: {integrity: sha512-BAmWG6/bx8syfc6qXPprof3Mn5vQgf5dwdUNJhsNqU9WdPt5P+ES/wQ5bxfijy8zwZgZZHslC3iAsxsuQMCzJQ==} @@ -6025,6 +6294,10 @@ packages: util-deprecate@1.0.2: resolution: {integrity: sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw==} + uuid@10.0.0: + resolution: {integrity: sha512-8XkAphELsDnEGrDxUOHB3RGvXz6TeuYSGEZBOjtTtPm2lwhGBjLgOzLHB63IUWfBpNucQjND6d3AOudO+H3RWQ==} + hasBin: true + validate-npm-package-name@5.0.0: resolution: {integrity: sha512-YuKoXDAhBYxY7SfOKxHBDoSyENFeW5VvIIQp2TGQuit8gpK6MnWaQelBKxso72DoxTZfZdcP3W90LqpSkgPzLQ==} engines: {node: ^14.17.0 || ^16.13.0 || >=18.0.0} @@ -6231,6 +6504,10 @@ packages: resolution: {integrity: sha512-GCPAHLvrIH13+c0SuacwvRYj2SxJXQ4kaVTT5xgL3kPrz56XxkF21IGhjSE1+W0aw7gpBWRGXLCPnPby6lSpmQ==} engines: {node: '>=12'} + xtend@4.0.2: + resolution: {integrity: sha512-LKYU1iAXJXUgAXn9URjiu+MWhyUXHsvfp7mcuYm9dSUKK0/CjtrUwFAxD82/mCWbtLsGjFIad0wIsod4zrTAEQ==} + engines: {node: '>=0.4'} + y18n@5.0.8: resolution: {integrity: sha512-0pfFzegeDWJHJIAmTLRP2DwHjdF5s7jo9tuztdQxAhINCdvS+3nGINqPd00AphqJR/0LhANUS6/+7SCb98YOfA==} engines: {node: '>=10'} @@ -6499,6 +6776,58 @@ snapshots: '@babel/helper-string-parser': 7.27.1 '@babel/helper-validator-identifier': 7.28.5 + '@better-auth/core@1.6.5(@better-auth/utils@0.4.0)(@better-fetch/fetch@1.1.21)(@opentelemetry/api@1.9.0)(better-call@1.3.5(zod@4.3.6))(jose@6.2.2)(kysely@0.28.16)(nanostores@1.2.0)': + dependencies: + '@better-auth/utils': 0.4.0 + '@better-fetch/fetch': 1.1.21 + '@opentelemetry/api': 1.9.0 + '@opentelemetry/semantic-conventions': 1.40.0 + '@standard-schema/spec': 1.1.0 + better-call: 1.3.5(zod@4.3.6) + jose: 6.2.2 + kysely: 0.28.16 + nanostores: 1.2.0 + zod: 4.3.6 + + '@better-auth/drizzle-adapter@1.6.5(@better-auth/core@1.6.5(@better-auth/utils@0.4.0)(@better-fetch/fetch@1.1.21)(@opentelemetry/api@1.9.0)(better-call@1.3.5(zod@4.3.6))(jose@6.2.2)(kysely@0.28.16)(nanostores@1.2.0))(@better-auth/utils@0.4.0)': + dependencies: + '@better-auth/core': 1.6.5(@better-auth/utils@0.4.0)(@better-fetch/fetch@1.1.21)(@opentelemetry/api@1.9.0)(better-call@1.3.5(zod@4.3.6))(jose@6.2.2)(kysely@0.28.16)(nanostores@1.2.0) + '@better-auth/utils': 0.4.0 + + '@better-auth/kysely-adapter@1.6.5(@better-auth/core@1.6.5(@better-auth/utils@0.4.0)(@better-fetch/fetch@1.1.21)(@opentelemetry/api@1.9.0)(better-call@1.3.5(zod@4.3.6))(jose@6.2.2)(kysely@0.28.16)(nanostores@1.2.0))(@better-auth/utils@0.4.0)(kysely@0.28.16)': + dependencies: + '@better-auth/core': 1.6.5(@better-auth/utils@0.4.0)(@better-fetch/fetch@1.1.21)(@opentelemetry/api@1.9.0)(better-call@1.3.5(zod@4.3.6))(jose@6.2.2)(kysely@0.28.16)(nanostores@1.2.0) + '@better-auth/utils': 0.4.0 + optionalDependencies: + kysely: 0.28.16 + + '@better-auth/memory-adapter@1.6.5(@better-auth/core@1.6.5(@better-auth/utils@0.4.0)(@better-fetch/fetch@1.1.21)(@opentelemetry/api@1.9.0)(better-call@1.3.5(zod@4.3.6))(jose@6.2.2)(kysely@0.28.16)(nanostores@1.2.0))(@better-auth/utils@0.4.0)': + dependencies: + '@better-auth/core': 1.6.5(@better-auth/utils@0.4.0)(@better-fetch/fetch@1.1.21)(@opentelemetry/api@1.9.0)(better-call@1.3.5(zod@4.3.6))(jose@6.2.2)(kysely@0.28.16)(nanostores@1.2.0) + '@better-auth/utils': 0.4.0 + + '@better-auth/mongo-adapter@1.6.5(@better-auth/core@1.6.5(@better-auth/utils@0.4.0)(@better-fetch/fetch@1.1.21)(@opentelemetry/api@1.9.0)(better-call@1.3.5(zod@4.3.6))(jose@6.2.2)(kysely@0.28.16)(nanostores@1.2.0))(@better-auth/utils@0.4.0)': + dependencies: + '@better-auth/core': 1.6.5(@better-auth/utils@0.4.0)(@better-fetch/fetch@1.1.21)(@opentelemetry/api@1.9.0)(better-call@1.3.5(zod@4.3.6))(jose@6.2.2)(kysely@0.28.16)(nanostores@1.2.0) + '@better-auth/utils': 0.4.0 + + '@better-auth/prisma-adapter@1.6.5(@better-auth/core@1.6.5(@better-auth/utils@0.4.0)(@better-fetch/fetch@1.1.21)(@opentelemetry/api@1.9.0)(better-call@1.3.5(zod@4.3.6))(jose@6.2.2)(kysely@0.28.16)(nanostores@1.2.0))(@better-auth/utils@0.4.0)': + dependencies: + '@better-auth/core': 1.6.5(@better-auth/utils@0.4.0)(@better-fetch/fetch@1.1.21)(@opentelemetry/api@1.9.0)(better-call@1.3.5(zod@4.3.6))(jose@6.2.2)(kysely@0.28.16)(nanostores@1.2.0) + '@better-auth/utils': 0.4.0 + + '@better-auth/telemetry@1.6.5(@better-auth/core@1.6.5(@better-auth/utils@0.4.0)(@better-fetch/fetch@1.1.21)(@opentelemetry/api@1.9.0)(better-call@1.3.5(zod@4.3.6))(jose@6.2.2)(kysely@0.28.16)(nanostores@1.2.0))(@better-auth/utils@0.4.0)(@better-fetch/fetch@1.1.21)': + dependencies: + '@better-auth/core': 1.6.5(@better-auth/utils@0.4.0)(@better-fetch/fetch@1.1.21)(@opentelemetry/api@1.9.0)(better-call@1.3.5(zod@4.3.6))(jose@6.2.2)(kysely@0.28.16)(nanostores@1.2.0) + '@better-auth/utils': 0.4.0 + '@better-fetch/fetch': 1.1.21 + + '@better-auth/utils@0.4.0': + dependencies: + '@noble/hashes': 2.2.0 + + '@better-fetch/fetch@1.1.21': {} + '@clack/core@0.4.2': dependencies: picocolors: 1.1.1 @@ -7080,12 +7409,16 @@ snapshots: '@noble/ciphers@1.3.0': {} + '@noble/ciphers@2.2.0': {} + '@noble/curves@1.9.7': dependencies: '@noble/hashes': 1.8.0 '@noble/hashes@1.8.0': {} + '@noble/hashes@2.2.0': {} + '@nodelib/fs.scandir@2.1.5': dependencies: '@nodelib/fs.stat': 2.0.5 @@ -7109,6 +7442,8 @@ snapshots: '@opentelemetry/api@1.9.0': {} + '@opentelemetry/semantic-conventions@1.40.0': {} + '@oxc-project/types@0.123.0': {} '@pnpm/config.env-replace@1.1.0': {} @@ -8063,6 +8398,8 @@ snapshots: '@sindresorhus/merge-streams@4.0.0': {} + '@stablelib/base64@1.0.1': {} + '@standard-schema/spec@1.1.0': {} '@supabase/auth-js@2.103.0': @@ -8300,6 +8637,12 @@ snapshots: dependencies: undici-types: 7.16.0 + '@types/pg@8.20.0': + dependencies: + '@types/node': 25.2.3 + pg-protocol: 1.13.0 + pg-types: 2.2.0 + '@types/react-dom@19.2.3(@types/react@19.2.14)': dependencies: '@types/react': 19.2.14 @@ -8696,6 +9039,44 @@ snapshots: basic-ftp@5.0.5: {} + better-auth@1.6.5(@opentelemetry/api@1.9.0)(next@16.1.6(@opentelemetry/api@1.9.0)(react-dom@19.2.4(react@19.2.4))(react@19.2.4))(pg@8.20.0)(react-dom@19.2.4(react@19.2.4))(react@19.2.4)(vitest@4.1.3(@opentelemetry/api@1.9.0)(@types/node@25.2.3)(msw@2.13.2(@types/node@25.2.3)(typescript@5.9.3))(vite@8.0.7(@types/node@25.2.3)(esbuild@0.27.3)(jiti@2.6.1)(tsx@4.21.0)(yaml@2.8.3))): + dependencies: + '@better-auth/core': 1.6.5(@better-auth/utils@0.4.0)(@better-fetch/fetch@1.1.21)(@opentelemetry/api@1.9.0)(better-call@1.3.5(zod@4.3.6))(jose@6.2.2)(kysely@0.28.16)(nanostores@1.2.0) + '@better-auth/drizzle-adapter': 1.6.5(@better-auth/core@1.6.5(@better-auth/utils@0.4.0)(@better-fetch/fetch@1.1.21)(@opentelemetry/api@1.9.0)(better-call@1.3.5(zod@4.3.6))(jose@6.2.2)(kysely@0.28.16)(nanostores@1.2.0))(@better-auth/utils@0.4.0) + '@better-auth/kysely-adapter': 1.6.5(@better-auth/core@1.6.5(@better-auth/utils@0.4.0)(@better-fetch/fetch@1.1.21)(@opentelemetry/api@1.9.0)(better-call@1.3.5(zod@4.3.6))(jose@6.2.2)(kysely@0.28.16)(nanostores@1.2.0))(@better-auth/utils@0.4.0)(kysely@0.28.16) + '@better-auth/memory-adapter': 1.6.5(@better-auth/core@1.6.5(@better-auth/utils@0.4.0)(@better-fetch/fetch@1.1.21)(@opentelemetry/api@1.9.0)(better-call@1.3.5(zod@4.3.6))(jose@6.2.2)(kysely@0.28.16)(nanostores@1.2.0))(@better-auth/utils@0.4.0) + '@better-auth/mongo-adapter': 1.6.5(@better-auth/core@1.6.5(@better-auth/utils@0.4.0)(@better-fetch/fetch@1.1.21)(@opentelemetry/api@1.9.0)(better-call@1.3.5(zod@4.3.6))(jose@6.2.2)(kysely@0.28.16)(nanostores@1.2.0))(@better-auth/utils@0.4.0) + '@better-auth/prisma-adapter': 1.6.5(@better-auth/core@1.6.5(@better-auth/utils@0.4.0)(@better-fetch/fetch@1.1.21)(@opentelemetry/api@1.9.0)(better-call@1.3.5(zod@4.3.6))(jose@6.2.2)(kysely@0.28.16)(nanostores@1.2.0))(@better-auth/utils@0.4.0) + '@better-auth/telemetry': 1.6.5(@better-auth/core@1.6.5(@better-auth/utils@0.4.0)(@better-fetch/fetch@1.1.21)(@opentelemetry/api@1.9.0)(better-call@1.3.5(zod@4.3.6))(jose@6.2.2)(kysely@0.28.16)(nanostores@1.2.0))(@better-auth/utils@0.4.0)(@better-fetch/fetch@1.1.21) + '@better-auth/utils': 0.4.0 + '@better-fetch/fetch': 1.1.21 + '@noble/ciphers': 2.2.0 + '@noble/hashes': 2.2.0 + better-call: 1.3.5(zod@4.3.6) + defu: 6.1.7 + jose: 6.2.2 + kysely: 0.28.16 + nanostores: 1.2.0 + zod: 4.3.6 + optionalDependencies: + next: 16.1.6(@opentelemetry/api@1.9.0)(react-dom@19.2.4(react@19.2.4))(react@19.2.4) + pg: 8.20.0 + react: 19.2.4 + react-dom: 19.2.4(react@19.2.4) + vitest: 4.1.3(@opentelemetry/api@1.9.0)(@types/node@25.2.3)(msw@2.13.2(@types/node@25.2.3)(typescript@5.9.3))(vite@8.0.7(@types/node@25.2.3)(esbuild@0.27.3)(jiti@2.6.1)(tsx@4.21.0)(yaml@2.8.3)) + transitivePeerDependencies: + - '@cloudflare/workers-types' + - '@opentelemetry/api' + + better-call@1.3.5(zod@4.3.6): + dependencies: + '@better-auth/utils': 0.4.0 + '@better-fetch/fetch': 1.1.21 + rou3: 0.7.12 + set-cookie-parser: 3.1.0 + optionalDependencies: + zod: 4.3.6 + bl@4.1.0: dependencies: buffer: 5.7.1 @@ -9076,6 +9457,8 @@ snapshots: has-property-descriptors: 1.0.2 object-keys: 1.1.1 + defu@6.1.7: {} + degenerator@5.0.1: dependencies: ast-types: 0.13.4 @@ -9612,6 +9995,8 @@ snapshots: fast-levenshtein@2.0.6: {} + fast-sha256@1.3.0: {} + fast-uri@3.1.0: {} fastq@1.19.1: @@ -10346,6 +10731,8 @@ snapshots: ky@1.14.3: {} + kysely@0.28.16: {} + latest-version@9.0.0: dependencies: package-json: 10.0.1 @@ -11034,6 +11421,8 @@ snapshots: nanoid@3.3.11: {} + nanostores@1.2.0: {} + napi-build-utils@2.0.0: {} natural-compare@1.4.0: {} @@ -11367,6 +11756,41 @@ snapshots: pathe@2.0.3: {} + pg-cloudflare@1.3.0: + optional: true + + pg-connection-string@2.12.0: {} + + pg-int8@1.0.1: {} + + pg-pool@3.13.0(pg@8.20.0): + dependencies: + pg: 8.20.0 + + pg-protocol@1.13.0: {} + + pg-types@2.2.0: + dependencies: + pg-int8: 1.0.1 + postgres-array: 2.0.0 + postgres-bytea: 1.0.1 + postgres-date: 1.0.7 + postgres-interval: 1.2.0 + + pg@8.20.0: + dependencies: + pg-connection-string: 2.12.0 + pg-pool: 3.13.0(pg@8.20.0) + pg-protocol: 1.13.0 + pg-types: 2.2.0 + pgpass: 1.0.5 + optionalDependencies: + pg-cloudflare: 1.3.0 + + pgpass@1.0.5: + dependencies: + split2: 4.2.0 + picocolors@1.0.1: {} picocolors@1.1.1: {} @@ -11391,6 +11815,8 @@ snapshots: possible-typed-array-names@1.1.0: {} + postal-mime@2.7.4: {} + postcss-load-config@6.0.1(jiti@2.6.1)(postcss@8.5.9)(tsx@4.21.0)(yaml@2.8.3): dependencies: lilconfig: 3.1.3 @@ -11428,6 +11854,16 @@ snapshots: picocolors: 1.1.1 source-map-js: 1.2.1 + postgres-array@2.0.0: {} + + postgres-bytea@1.0.1: {} + + postgres-date@1.0.7: {} + + postgres-interval@1.2.0: + dependencies: + xtend: 4.0.2 + powershell-utils@0.1.0: {} prebuild-install@7.1.3: @@ -11809,6 +12245,11 @@ snapshots: require-from-string@2.0.2: {} + resend@6.12.0: + dependencies: + postal-mime: 2.7.4 + svix: 1.90.0 + resolve-from@4.0.0: {} resolve-from@5.0.0: {} @@ -11897,6 +12338,8 @@ snapshots: '@rollup/rollup-win32-x64-msvc': 4.60.1 fsevents: 2.3.3 + rou3@0.7.12: {} + router@2.2.0: dependencies: debug: 4.4.3 @@ -11985,6 +12428,8 @@ snapshots: transitivePeerDependencies: - supports-color + set-cookie-parser@3.1.0: {} + set-function-length@1.2.2: dependencies: define-data-property: 1.1.4 @@ -12192,12 +12637,19 @@ snapshots: space-separated-tokens@2.0.2: {} + split2@4.2.0: {} + sprintf-js@1.0.3: {} sprintf-js@1.1.3: {} stackback@0.0.2: {} + standardwebhooks@1.0.0: + dependencies: + '@stablelib/base64': 1.0.1 + fast-sha256: 1.3.0 + statuses@2.0.2: {} std-env@4.0.0: {} @@ -12356,6 +12808,11 @@ snapshots: supports-preserve-symlinks-flag@1.0.0: {} + svix@1.90.0: + dependencies: + standardwebhooks: 1.0.0 + uuid: 10.0.0 + swap-case@1.1.2: dependencies: lower-case: 1.1.4 @@ -12742,6 +13199,8 @@ snapshots: util-deprecate@1.0.2: {} + uuid@10.0.0: {} + validate-npm-package-name@5.0.0: dependencies: builtins: 5.1.0 @@ -12924,6 +13383,8 @@ snapshots: xdg-basedir@5.1.0: {} + xtend@4.0.2: {} + y18n@5.0.8: {} yallist@3.1.1: {} diff --git a/scripts/migrate-auth-to-better-auth.sql b/scripts/migrate-auth-to-better-auth.sql new file mode 100644 index 0000000..f524f5b --- /dev/null +++ b/scripts/migrate-auth-to-better-auth.sql @@ -0,0 +1,123 @@ +-- scripts/migrate-auth-to-better-auth.sql +-- +-- One-shot migration of Supabase auth.users → Better Auth public.user. +-- Applied 2026-04-17 via Supabase MCP (see DEVICE_FLOW_PLAN.md). +-- Committed here so the shape is reproducible against a fresh DB (dev +-- branches, test envs, future projects). +-- +-- Preserves auth.users as a read-only archive; Supabase's own auth.* +-- FKs (identities, sessions, mfa_factors, etc.) continue to reference it. +-- Only the two app-level FKs (tenants.owner_id, llm_usage_events.user_id) +-- are re-pointed at public.user. +-- +-- Re-run safety: the INSERT is idempotent (ON CONFLICT DO NOTHING) and +-- the DROP POLICY/CONSTRAINT statements use IF EXISTS. The `ALTER COLUMN +-- ... TYPE text USING ::text` lines are NOT no-ops on a second run — +-- Postgres still rewrites the column and takes an exclusive lock even +-- when the target type matches. Safe to re-run in dev, but avoid on a +-- busy production DB; gate with `SELECT data_type FROM +-- information_schema.columns WHERE ...` if the re-run path matters. + +BEGIN; + +-- 1. Drop RLS policies that reference auth.uid() via owner_id/user_id. +-- They become inert under Better Auth; writes flow through server- +-- side code using the service role. +DROP POLICY IF EXISTS tenants_delete_own ON public.tenants; +DROP POLICY IF EXISTS tenants_insert_own ON public.tenants; +DROP POLICY IF EXISTS tenants_update_own ON public.tenants; +DROP POLICY IF EXISTS tenants_select_public ON public.tenants; + +DROP POLICY IF EXISTS tenant_articles_delete_own ON public.tenant_articles; +DROP POLICY IF EXISTS tenant_articles_insert_own ON public.tenant_articles; +DROP POLICY IF EXISTS tenant_articles_update_own ON public.tenant_articles; + +DROP POLICY IF EXISTS tenant_categories_delete_own ON public.tenant_categories; +DROP POLICY IF EXISTS tenant_categories_insert_own ON public.tenant_categories; +DROP POLICY IF EXISTS tenant_categories_update_own ON public.tenant_categories; + +DROP POLICY IF EXISTS tenant_chunks_delete_own ON public.tenant_chunks; +DROP POLICY IF EXISTS tenant_chunks_insert_own ON public.tenant_chunks; +DROP POLICY IF EXISTS tenant_chunks_select_own ON public.tenant_chunks; +DROP POLICY IF EXISTS tenant_chunks_update_own ON public.tenant_chunks; + +DROP POLICY IF EXISTS tenant_deploys_insert_own ON public.tenant_deploys; +DROP POLICY IF EXISTS tenant_deploys_select_own ON public.tenant_deploys; + +DROP POLICY IF EXISTS tenant_mcp_queries_select_own ON public.tenant_mcp_queries; + +DROP POLICY IF EXISTS "read own events" ON public.llm_usage_events; + +-- 2. Copy auth.users → public.user. UUIDs preserved as 36-char text. +-- Email is normalized (lower+trim) to match Better Auth's convention +-- and future-proof case-sensitive joins. The name fallback splits on +-- the normalized email so it's always non-null. +INSERT INTO "user" (id, email, "emailVerified", name, "createdAt", "updatedAt") +SELECT + u.id::text, + lower(btrim(u.email)), + u.email_confirmed_at IS NOT NULL, + COALESCE( + NULLIF(u.raw_user_meta_data->>'full_name', ''), + NULLIF(u.raw_user_meta_data->>'name', ''), + split_part(lower(btrim(u.email)), '@', 1) + ), + u.created_at, + COALESCE(u.updated_at, u.created_at) +FROM auth.users u +WHERE u.email IS NOT NULL +ON CONFLICT (id) DO NOTHING; + +-- 3. Drop + recreate FKs pointing at public.user. +ALTER TABLE public.llm_usage_events + DROP CONSTRAINT IF EXISTS llm_usage_events_user_id_fkey; +ALTER TABLE public.tenants + DROP CONSTRAINT IF EXISTS tenants_owner_id_fkey; + +-- Idempotency guard: a straight ALTER COLUMN TYPE text rewrites the +-- entire table and takes an ACCESS EXCLUSIVE lock even when the type +-- already matches. Gate with information_schema so re-runs are no-ops +-- on a production-scale llm_usage_events. +DO $$ +BEGIN + IF ( + SELECT data_type FROM information_schema.columns + WHERE table_schema = 'public' AND table_name = 'llm_usage_events' AND column_name = 'user_id' + ) <> 'text' THEN + EXECUTE 'ALTER TABLE public.llm_usage_events ALTER COLUMN user_id TYPE text USING user_id::text'; + END IF; + IF ( + SELECT data_type FROM information_schema.columns + WHERE table_schema = 'public' AND table_name = 'tenants' AND column_name = 'owner_id' + ) <> 'text' THEN + EXECUTE 'ALTER TABLE public.tenants ALTER COLUMN owner_id TYPE text USING owner_id::text'; + END IF; +END $$; + +ALTER TABLE public.llm_usage_events + ADD CONSTRAINT llm_usage_events_user_id_fkey + FOREIGN KEY (user_id) REFERENCES "user"(id) ON DELETE CASCADE; +ALTER TABLE public.tenants + ADD CONSTRAINT tenants_owner_id_fkey + FOREIGN KEY (owner_id) REFERENCES "user"(id) ON DELETE CASCADE; + +-- 4. Lock anon out of the base tenants table. The only public surface is +-- the `tenants_public` view (mcp_public_token filtered out), created by +-- the 2026-04-17 tenants_public_view_hide_mcp_token migration. Even +-- with the SELECT policy below, this REVOKE prevents anon from reading +-- mcp_public_token directly should the policy ever be widened. +REVOKE SELECT ON public.tenants FROM anon; + +-- 5. Recreate the one RLS policy anon needs (proxy.ts tenant resolution). +-- Policy scopes visibility; the column-level REVOKE above scopes which +-- columns anon can read when the policy allows a row. +CREATE POLICY tenants_select_active + ON public.tenants + FOR SELECT + TO anon, authenticated + USING (active = true); + +COMMENT ON TABLE "user" IS + 'Better Auth: canonical user table. Migrated from Supabase auth.users on 2026-04-17.'; + +COMMIT; diff --git a/scripts/sync-templates.mjs b/scripts/sync-templates.mjs index b10ef9e..6bee4b0 100644 --- a/scripts/sync-templates.mjs +++ b/scripts/sync-templates.mjs @@ -66,9 +66,15 @@ const HOSTED_TIER_EXCLUDES = [ "app/(main)/errors/", "app/(main)/waitlist/", "app/api/", + // Device-flow UI is helpbase.dev-only — the CLI opens /device on the + // hosted app to complete sign-in. Scaffolded projects don't run auth, + // so they don't need this route (and importing better-auth/react would + // break their build). + "app/device/", "lib/tenant-content.ts", "lib/tenant-search.ts", "lib/hosted-mdx-components.tsx", + "lib/auth.ts", "lib/supabase.ts", "lib/supabase-admin.ts", "lib/waitlist.ts",