The Open Framework for Building Agents
feat(eve): add Sign in with Vercel Web Chat scaffold (#1954)
Allen Zhoub1ce580196b1
diff --git a/.changeset/calm-web-chats-sign-in.md b/.changeset/calm-web-chats-sign-in.mdnew file mode 100644index 000000000..4856cdaf4--- /dev/null+++ b/.changeset/calm-web-chats-sign-in.md@@ -0,0 +1,5 @@+---+"eve": patch+---++Add an opt-in Sign in with Vercel authentication variant for programmatically scaffolded Web Chat apps.diff --git a/apps/docs/registry/channel/web-sign-in-with-vercel/agent/channels/eve.ts b/apps/docs/registry/channel/web-sign-in-with-vercel/agent/channels/eve.tsnew file mode 100644index 000000000..c67bfd712--- /dev/null+++ b/apps/docs/registry/channel/web-sign-in-with-vercel/agent/channels/eve.ts@@ -0,0 +1,28 @@+import { eveChannel } from "eve/channels/eve";+import { localDev, type AuthFn, vercelOidc } from "eve/channels/auth";+import { auth } from "@/lib/auth";++const betterAuthSession: AuthFn<Request> = async (request) => {+ const session = await auth.api.getSession({ headers: request.headers });+ if (!session) return null;++ const attributes: Record<string, string> = {+ email: session.user.email,+ name: session.user.name,+ };+ if (session.user.image) {+ attributes.picture = session.user.image;+ }++ return {+ attributes,+ authenticator: "better-auth:vercel",+ issuer: "https://vercel.com",+ principalId: session.user.id,+ principalType: "user",+ };+};++export default eveChannel({+ auth: [betterAuthSession, vercelOidc(), localDev()],+});diff --git a/apps/docs/registry/channel/web-sign-in-with-vercel/app/_components/web-chat-auth.tsx b/apps/docs/registry/channel/web-sign-in-with-vercel/app/_components/web-chat-auth.tsxnew file mode 100644index 000000000..3b1217e7f--- /dev/null+++ b/apps/docs/registry/channel/web-sign-in-with-vercel/app/_components/web-chat-auth.tsx@@ -0,0 +1,141 @@+"use client";++import { LogOutIcon } from "lucide-react";+import { useState } from "react";+import { Button } from "@/components/ui/button";+import {+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuItem,+ DropdownMenuSeparator,+ DropdownMenuTrigger,+} from "@/components/ui/dropdown-menu";+import { authClient } from "@/lib/auth-client";++const AGENT_NAME = "__EVE_INIT_APP_NAME__";++export function SignIn() {+ const [pending, setPending] = useState(false);+ const [error, setError] = useState<string>();++ async function signIn() {+ setPending(true);+ setError(undefined);+ try {+ const result = await authClient.signIn.social({+ callbackURL: "/",+ provider: "vercel",+ });+ if (!result.error) return;+ setPending(false);+ setError("Sign-in failed. Try again.");+ } catch {+ setPending(false);+ setError("Sign-in failed. Try again.");+ }+ }++ return (+ <main className="flex h-dvh items-center justify-center bg-background px-6 text-foreground">+ <div className="flex w-full max-w-sm flex-col items-center gap-6 text-center">+ <div className="space-y-2">+ <h1 className="break-words font-medium text-4xl tracking-tighter">{AGENT_NAME}</h1>+ <p className="text-muted-foreground text-sm">+ Team members can sign in with Vercel to chat.+ </p>+ </div>+ <Button disabled={pending} onClick={signIn}>+ Sign in with Vercel+ </Button>+ {error ? (+ <p className="text-destructive text-sm" role="alert">+ {error}+ </p>+ ) : null}+ </div>+ </main>+ );+}++export function AccountControl({+ email,+ image,+ name,+}: {+ readonly email: string;+ readonly image?: string | null;+ readonly name: string;+}) {+ const [imageFailed, setImageFailed] = useState(false);+ const [pending, setPending] = useState(false);+ const initials = getInitials(name, email);++ async function signOut() {+ setPending(true);+ try {+ await authClient.signOut({+ fetchOptions: {+ onError: () => setPending(false),+ onSuccess: () => window.location.assign("/"),+ },+ });+ } catch {+ setPending(false);+ }+ }++ return (+ <div className="fixed top-3 right-3 z-10">+ <DropdownMenu>+ <DropdownMenuTrigger asChild>+ <Button+ aria-label={`Open account menu for ${name}`}+ className="size-9 cursor-pointer overflow-hidden rounded-full p-0"+ size="icon"+ variant="outline"+ >+ {image && !imageFailed ? (+ <img+ alt=""+ className="size-full object-cover"+ onError={() => setImageFailed(true)}+ src={image}+ />+ ) : (+ <span aria-hidden="true" className="font-medium text-xs">+ {initials}+ </span>+ )}+ </Button>+ </DropdownMenuTrigger>+ <DropdownMenuContent align="end" className="w-64">+ <div className="min-w-0 px-2 py-1.5 text-sm">+ <span className="block truncate font-medium leading-5" title={name}>+ {name}+ </span>+ <span className="block truncate text-muted-foreground leading-5" title={email}>+ {email}+ </span>+ </div>+ <DropdownMenuSeparator />+ <DropdownMenuItem+ className="cursor-pointer justify-between"+ disabled={pending}+ onSelect={signOut}+ >+ {pending ? "Logging out…" : "Log out"}+ <LogOutIcon aria-hidden="true" />+ </DropdownMenuItem>+ </DropdownMenuContent>+ </DropdownMenu>+ </div>+ );+}++function getInitials(name: string, email: string): string {+ const parts = name.trim().split(/\s+/).filter(Boolean);+ if (parts.length >= 2) {+ return `${parts[0]?.[0] ?? ""}${parts.at(-1)?.[0] ?? ""}`.toUpperCase();+ }+ return (parts[0]?.[0] ?? email[0] ?? "?").toUpperCase();+}diff --git a/apps/docs/registry/channel/web-sign-in-with-vercel/app/api/auth/[...all]/route.ts b/apps/docs/registry/channel/web-sign-in-with-vercel/app/api/auth/[...all]/route.tsnew file mode 100644index 000000000..83ab371a7--- /dev/null+++ b/apps/docs/registry/channel/web-sign-in-with-vercel/app/api/auth/[...all]/route.ts@@ -0,0 +1,4 @@+import { toNextJsHandler } from "better-auth/next-js";+import { auth } from "@/lib/auth";++export const { GET, POST } = toNextJsHandler(auth);diff --git a/apps/docs/registry/channel/web-sign-in-with-vercel/app/layout.tsx b/apps/docs/registry/channel/web-sign-in-with-vercel/app/layout.tsxnew file mode 100644index 000000000..a9eecb090--- /dev/null+++ b/apps/docs/registry/channel/web-sign-in-with-vercel/app/layout.tsx@@ -0,0 +1,36 @@+import type { Metadata } from "next";+import { Geist, Geist_Mono } from "next/font/google";+import type { ReactNode } from "react";+import { TooltipProvider } from "@/components/ui/tooltip";+import { cn } from "@/lib/utils";+import "./globals.css";++const sans = Geist({+ variable: "--font-sans",+ subsets: ["latin"],+ weight: "variable",+ display: "swap",+});++const mono = Geist_Mono({+ variable: "--font-mono",+ subsets: ["latin"],+ weight: "variable",+ display: "swap",+});++export const metadata: Metadata = {+ title: "__EVE_INIT_APP_NAME__",+ description: "A Next.js starter for eve agents with AI Elements.",+};++// The page and Eve routes validate the generated app's Better Auth session.+export default function RootLayout({ children }: { readonly children: ReactNode }) {+ return (+ <html className={cn(sans.variable, mono.variable)} lang="en">+ <body>+ <TooltipProvider>{children}</TooltipProvider>+ </body>+ </html>+ );+}diff --git a/apps/docs/registry/channel/web-sign-in-with-vercel/app/page.tsx b/apps/docs/registry/channel/web-sign-in-with-vercel/app/page.tsxnew file mode 100644index 000000000..3d9a175e9--- /dev/null+++ b/apps/docs/registry/channel/web-sign-in-with-vercel/app/page.tsx@@ -0,0 +1,26 @@+import { headers } from "next/headers";+import { AgentChat } from "./_components/agent-chat";+import { AccountControl, SignIn } from "./_components/web-chat-auth";+import { auth } from "@/lib/auth";++export default async function Page() {+ if (process.env.NODE_ENV === "development") {+ return <AgentChat />;+ }++ const session = await auth.api.getSession({ headers: await headers() });+ if (!session) {+ return <SignIn />;+ }++ return (+ <>+ <AgentChat />+ <AccountControl+ email={session.user.email}+ image={session.user.image}+ name={session.user.name}+ />+ </>+ );+}diff --git a/apps/docs/registry/channel/web-sign-in-with-vercel/lib/auth-client.ts b/apps/docs/registry/channel/web-sign-in-with-vercel/lib/auth-client.tsnew file mode 100644index 000000000..2f75fd48b--- /dev/null+++ b/apps/docs/registry/channel/web-sign-in-with-vercel/lib/auth-client.ts@@ -0,0 +1,5 @@+"use client";++import { createAuthClient } from "better-auth/react";++export const authClient = createAuthClient();diff --git a/apps/docs/registry/channel/web-sign-in-with-vercel/lib/auth.ts b/apps/docs/registry/channel/web-sign-in-with-vercel/lib/auth.tsnew file mode 100644index 000000000..aacd9b5dd--- /dev/null+++ b/apps/docs/registry/channel/web-sign-in-with-vercel/lib/auth.ts@@ -0,0 +1,50 @@+import { betterAuth } from "better-auth";++const SESSION_MAX_AGE_SECONDS = 8 * 60 * 60;+const DEVELOPMENT_ALLOWED_HOSTS = ["localhost:*", "127.0.0.1:*"];++function getAllowedHosts(): string[] {+ if (process.env.NODE_ENV === "development") {+ return DEVELOPMENT_ALLOWED_HOSTS;+ }+ const deploymentHosts = [+ process.env.VERCEL_URL,+ process.env.VERCEL_BRANCH_URL,+ process.env.VERCEL_PROJECT_PRODUCTION_URL,+ ].filter((host): host is string => Boolean(host));+ if (deploymentHosts.length === 0) {+ throw new Error("No trusted deployment hosts are configured");+ }+ return Array.from(new Set(deploymentHosts));+}++function requireEnvironmentVariable(name: string): string {+ const value = process.env[name];+ if (value) return value;+ if (process.env.NODE_ENV === "development") return `development-${name}`;+ throw new Error(`Missing required environment variable: ${name}`);+}++export const auth = betterAuth({+ baseURL: {+ allowedHosts: getAllowedHosts(),+ protocol: process.env.NODE_ENV === "development" ? "auto" : "https",+ },+ secret: requireEnvironmentVariable("BETTER_AUTH_SECRET"),+ session: {+ expiresIn: SESSION_MAX_AGE_SECONDS,+ disableSessionRefresh: true,+ cookieCache: {+ enabled: true,+ maxAge: SESSION_MAX_AGE_SECONDS,+ refreshCache: false,+ strategy: "jwe",+ },+ },+ socialProviders: {+ vercel: {+ clientId: requireEnvironmentVariable("VERCEL_APP_CLIENT_ID"),+ clientSecret: requireEnvironmentVariable("VERCEL_APP_CLIENT_SECRET"),+ },+ },+});diff --git a/packages/eve/scripts/stamp-version-tokens.mjs b/packages/eve/scripts/stamp-version-tokens.mjsindex db8be4b6a..36d7aa09d 100644--- a/packages/eve/scripts/stamp-version-tokens.mjs+++ b/packages/eve/scripts/stamp-version-tokens.mjs@@ -43,6 +43,7 @@ const replacements = {__EVE_PACKAGE_VERSION__: packageJson.version,__NODE_ENGINE__: nodeEngine,__AI_SDK_VERSION__: await resolveCatalogVersion("ai"),+ __BETTER_AUTH_VERSION__: await resolveCatalogVersion("better-auth"),__VERCEL_CONNECT_VERSION__: await resolveCatalogVersion("@vercel/connect"),__NEXT_VERSION__: await resolveCatalogVersion("next"),__REACT_VERSION__: await resolveCatalogVersion("react"),diff --git a/packages/eve/src/setup/build.ts b/packages/eve/src/setup/build.tsindex c2614033d..a343ee350 100644--- a/packages/eve/src/setup/build.ts+++ b/packages/eve/src/setup/build.ts@@ -13,6 +13,10 @@ import { fileURLToPath } from "node:url";const SETUP_ROOT = dirname(fileURLToPath(import.meta.url));const REPO_ROOT = resolve(SETUP_ROOT, "../../../..");const SOURCE_ROOT = join(REPO_ROOT, "apps/docs/registry/channel/web");+const SIGN_IN_WITH_VERCEL_SOURCE_ROOT = join(+ REPO_ROOT,+ "apps/docs/registry/channel/web-sign-in-with-vercel",+);const REGISTRY_PATH = join(REPO_ROOT, "apps/docs/registry.json");const OUTPUT_PATH = join(SETUP_ROOT, "scaffold/create/web-template.ts");@@ -73,8 +77,8 @@ function shouldCopySourcePath(relativePath: string): boolean {);}-async function discoverSourceFiles(relativeDirectory = ""): Promise<string[]> {- const entries = await readdir(join(SOURCE_ROOT, relativeDirectory), { withFileTypes: true });+async function discoverSourceFiles(sourceRoot: string, relativeDirectory = ""): Promise<string[]> {+ const entries = await readdir(join(sourceRoot, relativeDirectory), { withFileTypes: true });const discoveredFiles: string[] = [];for (const entry of entries.sort((left, right) => left.name.localeCompare(right.name))) {@@ -82,7 +86,7 @@ async function discoverSourceFiles(relativeDirectory = ""): Promise<string[]> {if (!shouldCopySourcePath(relativePath)) continue;if (entry.isDirectory()) {- discoveredFiles.push(...(await discoverSourceFiles(relativePath)));+ discoveredFiles.push(...(await discoverSourceFiles(sourceRoot, relativePath)));} else if (entry.isFile()) {discoveredFiles.push(relativePath);}@@ -157,13 +161,20 @@ function parsePackageTemplate(source: string): PackageTemplate {}async function renderGeneratedModule(): Promise<string> {- const sourceFiles = await discoverSourceFiles();+ const sourceFiles = await discoverSourceFiles(SOURCE_ROOT);const entries = await Promise.all(sourceFiles.map(async (relativePath) => {const source = await readFile(join(SOURCE_ROOT, relativePath), "utf8");return renderFileEntry(relativePath, applyDeclaredTransforms(relativePath, source));}),);+ const signInWithVercelSourceFiles = await discoverSourceFiles(SIGN_IN_WITH_VERCEL_SOURCE_ROOT);+ const signInWithVercelEntries = await Promise.all(+ signInWithVercelSourceFiles.map(async (relativePath) => {+ const source = await readFile(join(SIGN_IN_WITH_VERCEL_SOURCE_ROOT, relativePath), "utf8");+ return renderFileEntry(relativePath, source);+ }),+ );const packageTemplate = parsePackageTemplate(await readFile(REGISTRY_PATH, "utf8"));return [@@ -174,6 +185,10 @@ async function renderGeneratedModule(): Promise<string> {...entries,"} as const;","",+ "export const WEB_APP_SIGN_IN_WITH_VERCEL_TEMPLATE_FILES = {",+ ...signInWithVercelEntries,+ "} as const;",+ "","export const WEB_APP_TEMPLATE_PACKAGE_JSON = {",renderStringRecord("scripts", packageTemplate.scripts),renderStringRecord("dependencies", packageTemplate.dependencies),diff --git a/packages/eve/src/setup/scaffold/create/web-template.ts b/packages/eve/src/setup/scaffold/create/web-template.tsindex 7835c7e22..3fc45d7d9 100644--- a/packages/eve/src/setup/scaffold/create/web-template.ts+++ b/packages/eve/src/setup/scaffold/create/web-template.ts@@ -75,6 +75,23 @@ export const WEB_APP_TEMPLATE_FILES = {'{\n "$schema": "https://json.schemastore.org/tsconfig",\n "compilerOptions": {\n "target": "ES2017",\n "lib": ["dom", "dom.iterable", "esnext"],\n "allowJs": true,\n "skipLibCheck": true,\n "strict": true,\n "noEmit": true,\n "esModuleInterop": true,\n "module": "esnext",\n "moduleResolution": "Bundler",\n "resolveJsonModule": true,\n "isolatedModules": true,\n "jsx": "react-jsx",\n "incremental": true,\n "plugins": [\n {\n "name": "next"\n }\n ],\n "paths": {\n "@/*": ["./*"]\n }\n },\n "include": [\n "next-env.d.ts",\n "**/*.ts",\n "**/*.tsx",\n ".next/types/**/*.ts",\n ".next/dev/types/**/*.ts"\n ],\n "exclude": ["node_modules"]\n}\n',} as const;+export const WEB_APP_SIGN_IN_WITH_VERCEL_TEMPLATE_FILES = {+ "agent/channels/eve.ts":+ 'import { eveChannel } from "eve/channels/eve";\nimport { localDev, type AuthFn, vercelOidc } from "eve/channels/auth";\nimport { auth } from "@/lib/auth";\n\nconst betterAuthSession: AuthFn<Request> = async (request) => {\n const session = await auth.api.getSession({ headers: request.headers });\n if (!session) return null;\n\n const attributes: Record<string, string> = {\n email: session.user.email,\n name: session.user.name,\n };\n if (session.user.image) {\n attributes.picture = session.user.image;\n }\n\n return {\n attributes,\n authenticator: "better-auth:vercel",\n issuer: "https://vercel.com",\n principalId: session.user.id,\n principalType: "user",\n };\n};\n\nexport default eveChannel({\n auth: [betterAuthSession, vercelOidc(), localDev()],\n});\n',+ "app/_components/web-chat-auth.tsx":+ '"use client";\n\nimport { LogOutIcon } from "lucide-react";\nimport { useState } from "react";\nimport { Button } from "@/components/ui/button";\nimport {\n DropdownMenu,\n DropdownMenuContent,\n DropdownMenuItem,\n DropdownMenuSeparator,\n DropdownMenuTrigger,\n} from "@/components/ui/dropdown-menu";\nimport { authClient } from "@/lib/auth-client";\n\nconst AGENT_NAME = "__EVE_INIT_APP_NAME__";\n\nexport function SignIn() {\n const [pending, setPending] = useState(false);\n const [error, setError] = useState<string>();\n\n async function signIn() {\n setPending(true);\n setError(undefined);\n try {\n const result = await authClient.signIn.social({\n callbackURL: "/",\n provider: "vercel",\n });\n if (!result.error) return;\n setPending(false);\n setError("Sign-in failed. Try again.");\n } catch {\n setPending(false);\n setError("Sign-in failed. Try again.");\n }\n }\n\n return (\n <main className="flex h-dvh items-center justify-center bg-background px-6 text-foreground">\n <div className="flex w-full max-w-sm flex-col items-center gap-6 text-center">\n <div className="space-y-2">\n <h1 className="break-words font-medium text-4xl tracking-tighter">{AGENT_NAME}</h1>\n <p className="text-muted-foreground text-sm">\n Team members can sign in with Vercel to chat.\n </p>\n </div>\n <Button disabled={pending} onClick={signIn}>\n Sign in with Vercel\n </Button>\n {error ? (\n <p className="text-destructive text-sm" role="alert">\n {error}\n </p>\n ) : null}\n </div>\n </main>\n );\n}\n\nexport function AccountControl({\n email,\n image,\n name,\n}: {\n readonly email: string;\n readonly image?: string | null;\n readonly name: string;\n}) {\n const [imageFailed, setImageFailed] = useState(false);\n const [pending, setPending] = useState(false);\n const initials = getInitials(name, email);\n\n async function signOut() {\n setPending(true);\n try {\n await authClient.signOut({\n fetchOptions: {\n onError: () => setPending(false),\n onSuccess: () => window.location.assign("/"),\n },\n });\n } catch {\n setPending(false);\n }\n }\n\n return (\n <div className="fixed top-3 right-3 z-10">\n <DropdownMenu>\n <DropdownMenuTrigger asChild>\n <Button\n aria-label={`Open account menu for ${name}`}\n className="size-9 cursor-pointer overflow-hidden rounded-full p-0"\n size="icon"\n variant="outline"\n >\n {image && !imageFailed ? (\n <img\n alt=""\n className="size-full object-cover"\n onError={() => setImageFailed(true)}\n src={image}\n />\n ) : (\n <span aria-hidden="true" className="font-medium text-xs">\n {initials}\n </span>\n )}\n </Button>\n </DropdownMenuTrigger>\n <DropdownMenuContent align="end" className="w-64">\n <div className="min-w-0 px-2 py-1.5 text-sm">\n <span className="block truncate font-medium leading-5" title={name}>\n {name}\n </span>\n <span className="block truncate text-muted-foreground leading-5" title={email}>\n {email}\n </span>\n </div>\n <DropdownMenuSeparator />\n <DropdownMenuItem\n className="cursor-pointer justify-between"\n disabled={pending}\n onSelect={signOut}\n >\n {pending ? "Logging out…" : "Log out"}\n <LogOutIcon aria-hidden="true" />\n </DropdownMenuItem>\n </DropdownMenuContent>\n </DropdownMenu>\n </div>\n );\n}\n\nfunction getInitials(name: string, email: string): string {\n const parts = name.trim().split(/\\s+/).filter(Boolean);\n if (parts.length >= 2) {\n return `${parts[0]?.[0] ?? ""}${parts.at(-1)?.[0] ?? ""}`.toUpperCase();\n }\n return (parts[0]?.[0] ?? email[0] ?? "?").toUpperCase();\n}\n',+ "app/api/auth/[...all]/route.ts":+ 'import { toNextJsHandler } from "better-auth/next-js";\nimport { auth } from "@/lib/auth";\n\nexport const { GET, POST } = toNextJsHandler(auth);\n',+ "app/layout.tsx":+ 'import type { Metadata } from "next";\nimport { Geist, Geist_Mono } from "next/font/google";\nimport type { ReactNode } from "react";\nimport { TooltipProvider } from "@/components/ui/tooltip";\nimport { cn } from "@/lib/utils";\nimport "./globals.css";\n\nconst sans = Geist({\n variable: "--font-sans",\n subsets: ["latin"],\n weight: "variable",\n display: "swap",\n});\n\nconst mono = Geist_Mono({\n variable: "--font-mono",\n subsets: ["latin"],\n weight: "variable",\n display: "swap",\n});\n\nexport const metadata: Metadata = {\n title: "__EVE_INIT_APP_NAME__",\n description: "A Next.js starter for eve agents with AI Elements.",\n};\n\n// The page and Eve routes validate the generated app\'s Better Auth session.\nexport default function RootLayout({ children }: { readonly children: ReactNode }) {\n return (\n <html className={cn(sans.variable, mono.variable)} lang="en">\n <body>\n <TooltipProvider>{children}</TooltipProvider>\n </body>\n </html>\n );\n}\n',+ "app/page.tsx":+ 'import { headers } from "next/headers";\nimport { AgentChat } from "./_components/agent-chat";\nimport { AccountControl, SignIn } from "./_components/web-chat-auth";\nimport { auth } from "@/lib/auth";\n\nexport default async function Page() {\n if (process.env.NODE_ENV === "development") {\n return <AgentChat />;\n }\n\n const session = await auth.api.getSession({ headers: await headers() });\n if (!session) {\n return <SignIn />;\n }\n\n return (\n <>\n <AgentChat />\n <AccountControl\n email={session.user.email}\n image={session.user.image}\n name={session.user.name}\n />\n </>\n );\n}\n',+ "lib/auth-client.ts":+ '"use client";\n\nimport { createAuthClient } from "better-auth/react";\n\nexport const authClient = createAuthClient();\n',+ "lib/auth.ts":+ 'import { betterAuth } from "better-auth";\n\nconst SESSION_MAX_AGE_SECONDS = 8 * 60 * 60;\nconst DEVELOPMENT_ALLOWED_HOSTS = ["localhost:*", "127.0.0.1:*"];\n\nfunction getAllowedHosts(): string[] {\n if (process.env.NODE_ENV === "development") {\n return DEVELOPMENT_ALLOWED_HOSTS;\n }\n const deploymentHosts = [\n process.env.VERCEL_URL,\n process.env.VERCEL_BRANCH_URL,\n process.env.VERCEL_PROJECT_PRODUCTION_URL,\n ].filter((host): host is string => Boolean(host));\n if (deploymentHosts.length === 0) {\n throw new Error("No trusted deployment hosts are configured");\n }\n return Array.from(new Set(deploymentHosts));\n}\n\nfunction requireEnvironmentVariable(name: string): string {\n const value = process.env[name];\n if (value) return value;\n if (process.env.NODE_ENV === "development") return `development-${name}`;\n throw new Error(`Missing required environment variable: ${name}`);\n}\n\nexport const auth = betterAuth({\n baseURL: {\n allowedHosts: getAllowedHosts(),\n protocol: process.env.NODE_ENV === "development" ? "auto" : "https",\n },\n secret: requireEnvironmentVariable("BETTER_AUTH_SECRET"),\n session: {\n expiresIn: SESSION_MAX_AGE_SECONDS,\n disableSessionRefresh: true,\n cookieCache: {\n enabled: true,\n maxAge: SESSION_MAX_AGE_SECONDS,\n refreshCache: false,\n strategy: "jwe",\n },\n },\n socialProviders: {\n vercel: {\n clientId: requireEnvironmentVariable("VERCEL_APP_CLIENT_ID"),\n clientSecret: requireEnvironmentVariable("VERCEL_APP_CLIENT_SECRET"),\n },\n },\n});\n',+} as const;+export const WEB_APP_TEMPLATE_PACKAGE_JSON = {scripts: {build: "next build",diff --git a/packages/eve/src/setup/scaffold/index.integration.test.ts b/packages/eve/src/setup/scaffold/index.integration.test.tsindex 611d46e4d..15de46633 100644--- a/packages/eve/src/setup/scaffold/index.integration.test.ts+++ b/packages/eve/src/setup/scaffold/index.integration.test.ts@@ -31,6 +31,7 @@ const RELEASE_AGE_POLICY =const TEST_WEB_PACKAGE_VERSIONS = {evePackage: TEST_EVE_PACKAGE,aiPackageVersion: "7.0.0",+ betterAuthPackageVersion: "1.6.26-test",nextPackageVersion: "16.2.6",reactPackageVersion: "19.2.6",reactDomPackageVersion: "19.2.6",@@ -247,6 +248,7 @@ describe("ensureChannel", () => {"withEve",);const packageJson = await readFile(join(projectRoot, "package.json"), "utf8");+ expect(packageJson).not.toContain('"better-auth"');expect(packageJson).toContain('"next": "16.2.6"');expect(packageJson).toContain('"build:eve": "eve build"');expect(packageJson).toContain('"dev": "next dev"');@@ -274,6 +276,68 @@ describe("ensureChannel", () => {);});+ test("writes a Sign in with Vercel authenticated Web Chat app", async () => {+ const projectRoot = await createTempDir();+ await writeFile(+ join(projectRoot, "package.json"),+ `${JSON.stringify({ name: "private-agent", type: "module" }, null, 2)}\n`,+ "utf8",+ );++ const result = await ensureChannel({+ projectRoot,+ kind: "web",+ webAuthentication: "sign-in-with-vercel",+ webPackageVersions: {+ ...TEST_WEB_PACKAGE_VERSIONS,+ nextPackageVersion: undefined,+ },+ });++ expect(result).toMatchObject({ kind: "web", action: "created" });+ expect(result.filesWritten).toEqual(+ expect.arrayContaining([+ join(projectRoot, "app/_components/web-chat-auth.tsx"),+ join(projectRoot, "app/api/auth/[...all]/route.ts"),+ join(projectRoot, "lib/auth-client.ts"),+ join(projectRoot, "lib/auth.ts"),+ ]),+ );++ const packageJson = JSON.parse(await readFile(join(projectRoot, "package.json"), "utf8")) as {+ dependencies: Record<string, string>;+ };+ expect(packageJson.dependencies["better-auth"]).toBe("1.6.26-test");+ expect(packageJson.dependencies.next).toBe("16.3.0");++ const pageSource = await readFile(join(projectRoot, "app/page.tsx"), "utf8");+ expect(pageSource).toContain("auth.api.getSession");+ expect(pageSource).toContain("<SignIn />");+ expect(pageSource).toContain("<AccountControl");++ const authSource = await readFile(join(projectRoot, "lib/auth.ts"), "utf8");+ expect(authSource).toContain('requireEnvironmentVariable("BETTER_AUTH_SECRET")');+ expect(authSource).toContain("process.env.VERCEL_PROJECT_PRODUCTION_URL");+ expect(authSource).toContain('clientId: requireEnvironmentVariable("VERCEL_APP_CLIENT_ID")');+ expect(authSource).toContain('throw new Error("No trusted deployment hosts are configured")');+ expect(authSource).not.toContain("*.vercel.app");++ const channelSource = await readFile(join(projectRoot, "agent/channels/eve.ts"), "utf8");+ expect(channelSource).toContain("auth.api.getSession");+ expect(channelSource).toContain('authenticator: "better-auth:vercel"');+ expect(channelSource).toContain("vercelOidc()");+ expect(channelSource).toContain("localDev()");+ expect(channelSource).not.toContain("placeholderAuth");++ const accountSource = await readFile(+ join(projectRoot, "app/_components/web-chat-auth.tsx"),+ "utf8",+ );+ expect(accountSource).toContain('className="size-9 cursor-pointer');+ expect(accountSource).toContain("Log out");+ expect(accountSource).not.toContain("__EVE_INIT_APP_NAME__");+ });+test("overrides an incompatible node engine when adding Web Chat", async () => {const projectRoot = await createTempDir();await mkdir(join(projectRoot, "agent"), { recursive: true });diff --git a/packages/eve/src/setup/scaffold/index.ts b/packages/eve/src/setup/scaffold/index.tsindex d25c5fdad..1837f7957 100644--- a/packages/eve/src/setup/scaffold/index.ts+++ b/packages/eve/src/setup/scaffold/index.ts@@ -26,6 +26,7 @@ export {type ChannelMutationResult,type EnsureChannelOptions,type SlackConnectorSlug,+ type WebAuthentication,type WebPackageVersions,} from "./update/channels.js";diff --git a/packages/eve/src/setup/scaffold/update/channels.ts b/packages/eve/src/setup/scaffold/update/channels.tsindex c91509a60..0480610d0 100644--- a/packages/eve/src/setup/scaffold/update/channels.ts+++ b/packages/eve/src/setup/scaffold/update/channels.ts@@ -15,27 +15,25 @@ import {} from "../workspace-root.js";import { getSupportedModuleBaseName, matchesSupportedModuleBaseName } from "./module-files.js";import { patchPackageJson, type PackageJsonPatch } from "./package-json.js";+import { CURRENT_DIRECTORY_PROJECT_NAME, resolveEvePackageContract } from "../create/project.js";import {- CURRENT_DIRECTORY_PROJECT_NAME,- DEFAULT_EVE_PACKAGE_CONTRACT,- resolveEvePackageContract,- type EvePackageContract,-} from "../create/project.js";-import { WEB_APP_TEMPLATE_FILES, WEB_APP_TEMPLATE_PACKAGE_JSON } from "../create/web-template.js";+ WEB_APP_SIGN_IN_WITH_VERCEL_TEMPLATE_FILES,+ WEB_APP_TEMPLATE_FILES,+ WEB_APP_TEMPLATE_PACKAGE_JSON,+} from "../create/web-template.js";+import {+ resolveWebPackageVersions,+ type WebAuthentication,+ type WebPackageVersions,+} from "./web-options.js";++export type { WebAuthentication, WebPackageVersions } from "./web-options.js";export const SLACK_CHANNEL_DEFAULT_ROUTE = "/eve/v1/slack";export const DEFAULT_SLACK_CONNECTOR_SLUG = "my-agent";const DEFAULT_CONNECT_PACKAGE_VERSION = "__VERCEL_CONNECT_VERSION__";-const DEFAULT_AI_PACKAGE_VERSION = "__AI_SDK_VERSION__";-const DEFAULT_NEXT_PACKAGE_VERSION = "__NEXT_VERSION__";-const DEFAULT_REACT_PACKAGE_VERSION = "__REACT_VERSION__";-const DEFAULT_REACT_DOM_PACKAGE_VERSION = "__REACT_DOM_VERSION__";-const DEFAULT_STREAMDOWN_PACKAGE_VERSION = "__STREAMDOWN_VERSION__";-const DEFAULT_ZOD_PACKAGE_VERSION = "__ZOD_VERSION__";const NEXT_TYPESCRIPT_PACKAGE_VERSION = "6.0.3";-const DEFAULT_TYPES_REACT_PACKAGE_VERSION = "__TYPES_REACT_VERSION__";-const DEFAULT_TYPES_REACT_DOM_PACKAGE_VERSION = "__TYPES_REACT_DOM_VERSION__";const CONNECT_PACKAGE_NAME = "@vercel/connect";const NEXT_PACKAGE_NAME = "next";const PACKAGE_DEPENDENCY_FIELDS = ["dependencies", "devDependencies"] as const;@@ -242,24 +240,6 @@ async function ensurePackageDependency(];}-function resolveWebPackageVersions(- input: WebPackageVersions | undefined,-): Required<WebPackageVersions> {- return {- evePackage: input?.evePackage ?? DEFAULT_EVE_PACKAGE_CONTRACT,- aiPackageVersion: input?.aiPackageVersion ?? DEFAULT_AI_PACKAGE_VERSION,- nextPackageVersion: input?.nextPackageVersion ?? DEFAULT_NEXT_PACKAGE_VERSION,- reactPackageVersion: input?.reactPackageVersion ?? DEFAULT_REACT_PACKAGE_VERSION,- reactDomPackageVersion: input?.reactDomPackageVersion ?? DEFAULT_REACT_DOM_PACKAGE_VERSION,- streamdownPackageVersion: input?.streamdownPackageVersion ?? DEFAULT_STREAMDOWN_PACKAGE_VERSION,- zodPackageVersion: input?.zodPackageVersion ?? DEFAULT_ZOD_PACKAGE_VERSION,- typesReactPackageVersion:- input?.typesReactPackageVersion ?? DEFAULT_TYPES_REACT_PACKAGE_VERSION,- typesReactDomPackageVersion:- input?.typesReactDomPackageVersion ?? DEFAULT_TYPES_REACT_DOM_PACKAGE_VERSION,- };-}-function formatEveDependencySpecifier(versionOrSpecifier: string): string {return /^\d+\.\d+\.\d+(?:[-+][0-9A-Za-z-.]+)?$/.test(versionOrSpecifier)? `^${versionOrSpecifier}`@@ -273,6 +253,7 @@ async function patchWebPackageJson(options: Required<WebPackageVersions>,onWorkspaceRootMutation?: (mutation: WorkspaceRootMutation) => void | Promise<void>,includeDependencies = true,+ authentication?: WebAuthentication,): Promise<{mutations: PackageJsonMutation[];nodeEngineOverride?: NodeEngineOverride;@@ -294,6 +275,14 @@ async function patchWebPackageJson("react-dom": resolveVersionToken("reactDomPackageVersion", options.reactDomPackageVersion),streamdown: resolveVersionToken("streamdownPackageVersion", options.streamdownPackageVersion),zod: resolveVersionToken("zodPackageVersion", options.zodPackageVersion),+ ...(authentication === "sign-in-with-vercel"+ ? {+ "better-auth": resolveVersionToken(+ "betterAuthPackageVersion",+ options.betterAuthPackageVersion,+ ),+ }+ : {}),} satisfies Record<string, string>;const devDependencies = {...WEB_APP_TEMPLATE_PACKAGE_JSON.devDependencies,@@ -467,6 +456,8 @@ export interface EnsureChannelOptions {slackCredentials?: "vercel-connect" | "environment";connectPackageVersion?: string;webPackageVersions?: WebPackageVersions;+ /** Authentication integration generated for Web Chat. Omit to keep the fail-closed placeholder. */+ webAuthentication?: WebAuthentication;/** When false, Web Chat leaves Vercel Services config unwritten for preview-only scaffolds. */configureVercelServices?: boolean;onWorkspaceRootMutation?: (mutation: WorkspaceRootMutation) => void | Promise<void>;@@ -474,18 +465,6 @@ export interface EnsureChannelOptions {skipDependencyMutation?: boolean;}-export interface WebPackageVersions {- evePackage?: EvePackageContract;- aiPackageVersion?: string;- nextPackageVersion?: string;- reactPackageVersion?: string;- reactDomPackageVersion?: string;- streamdownPackageVersion?: string;- zodPackageVersion?: string;- typesReactPackageVersion?: string;- typesReactDomPackageVersion?: string;-}-export async function ensureChannel(options: EnsureChannelOptions): Promise<ChannelMutationResult> {switch (options.kind) {case "slack":@@ -512,7 +491,10 @@ async function ensureWebChannel(};}- const webPackageVersions = resolveWebPackageVersions(options.webPackageVersions);+ const webPackageVersions = resolveWebPackageVersions(+ options.webPackageVersions,+ options.webAuthentication,+ );const packageManager = options.packageManager ?? "pnpm";const workspaceProbeRoot = resolve(options.workspaceProbeDirectory ?? options.projectRoot);const packageJsonPatch = await patchWebPackageJson(@@ -522,6 +504,7 @@ async function ensureWebChannel(webPackageVersions,options.onWorkspaceRootMutation,!options.skipDependencyMutation,+ options.webAuthentication,);const filesWritten: string[] = [];const filesOverwritten: string[] = [];@@ -550,7 +533,13 @@ async function ensureWebChannel(filesSkipped.push(...packageManagerConfiguration.filesSkipped);if (!options.skipDependencyMutation) {- for (const [relPath, content] of Object.entries(WEB_APP_TEMPLATE_FILES)) {+ const templateFiles = {+ ...WEB_APP_TEMPLATE_FILES,+ ...(options.webAuthentication === "sign-in-with-vercel"+ ? WEB_APP_SIGN_IN_WITH_VERCEL_TEMPLATE_FILES+ : {}),+ };+ for (const [relPath, content] of Object.entries(templateFiles)) {const filePath = join(options.projectRoot, relPath);if (relPath === WEB_CHANNEL_PATH && !options.force && (await pathExists(filePath))) {filesSkipped.push(filePath);diff --git a/packages/eve/src/setup/scaffold/update/web-options.ts b/packages/eve/src/setup/scaffold/update/web-options.tsnew file mode 100644index 000000000..46bade2d9--- /dev/null+++ b/packages/eve/src/setup/scaffold/update/web-options.ts@@ -0,0 +1,52 @@+import { DEFAULT_EVE_PACKAGE_CONTRACT, type EvePackageContract } from "../create/project.js";++const DEFAULT_AI_PACKAGE_VERSION = "__AI_SDK_VERSION__";+const DEFAULT_BETTER_AUTH_PACKAGE_VERSION = "__BETTER_AUTH_VERSION__";+const DEFAULT_NEXT_PACKAGE_VERSION = "__NEXT_VERSION__";+const DEFAULT_SIGN_IN_WITH_VERCEL_NEXT_PACKAGE_VERSION = "16.3.0";+const DEFAULT_REACT_PACKAGE_VERSION = "__REACT_VERSION__";+const DEFAULT_REACT_DOM_PACKAGE_VERSION = "__REACT_DOM_VERSION__";+const DEFAULT_STREAMDOWN_PACKAGE_VERSION = "__STREAMDOWN_VERSION__";+const DEFAULT_ZOD_PACKAGE_VERSION = "__ZOD_VERSION__";+const DEFAULT_TYPES_REACT_PACKAGE_VERSION = "__TYPES_REACT_VERSION__";+const DEFAULT_TYPES_REACT_DOM_PACKAGE_VERSION = "__TYPES_REACT_DOM_VERSION__";++export type WebAuthentication = "sign-in-with-vercel";++export interface WebPackageVersions {+ evePackage?: EvePackageContract;+ aiPackageVersion?: string;+ betterAuthPackageVersion?: string;+ nextPackageVersion?: string;+ reactPackageVersion?: string;+ reactDomPackageVersion?: string;+ streamdownPackageVersion?: string;+ zodPackageVersion?: string;+ typesReactPackageVersion?: string;+ typesReactDomPackageVersion?: string;+}++export function resolveWebPackageVersions(+ input: WebPackageVersions | undefined,+ authentication?: WebAuthentication,+): Required<WebPackageVersions> {+ return {+ evePackage: input?.evePackage ?? DEFAULT_EVE_PACKAGE_CONTRACT,+ aiPackageVersion: input?.aiPackageVersion ?? DEFAULT_AI_PACKAGE_VERSION,+ betterAuthPackageVersion:+ input?.betterAuthPackageVersion ?? DEFAULT_BETTER_AUTH_PACKAGE_VERSION,+ nextPackageVersion:+ input?.nextPackageVersion ??+ (authentication === "sign-in-with-vercel"+ ? DEFAULT_SIGN_IN_WITH_VERCEL_NEXT_PACKAGE_VERSION+ : DEFAULT_NEXT_PACKAGE_VERSION),+ reactPackageVersion: input?.reactPackageVersion ?? DEFAULT_REACT_PACKAGE_VERSION,+ reactDomPackageVersion: input?.reactDomPackageVersion ?? DEFAULT_REACT_DOM_PACKAGE_VERSION,+ streamdownPackageVersion: input?.streamdownPackageVersion ?? DEFAULT_STREAMDOWN_PACKAGE_VERSION,+ zodPackageVersion: input?.zodPackageVersion ?? DEFAULT_ZOD_PACKAGE_VERSION,+ typesReactPackageVersion:+ input?.typesReactPackageVersion ?? DEFAULT_TYPES_REACT_PACKAGE_VERSION,+ typesReactDomPackageVersion:+ input?.typesReactDomPackageVersion ?? DEFAULT_TYPES_REACT_DOM_PACKAGE_VERSION,+ };+}diff --git a/packages/eve/test/scenarios/post-build-scripts.scenario.test.ts b/packages/eve/test/scenarios/post-build-scripts.scenario.test.tsindex 961b1769a..255b617d2 100644--- a/packages/eve/test/scenarios/post-build-scripts.scenario.test.ts+++ b/packages/eve/test/scenarios/post-build-scripts.scenario.test.ts@@ -50,6 +50,7 @@ async function createPostBuildFixture(["catalog:",' ai: "2.0.0"',+ ' better-auth: "1.6.26"',' next: "16.2.6"',' react: "19.2.6"',' react-dom: "19.2.6"',@@ -113,6 +114,7 @@ describe("post-build scripts", () => {join(packageRoot, "dist", "src", "chunks", "scaffold-abc123.js"),['export const ai = "__AI_SDK_VERSION__";',+ 'export const betterAuth = "__BETTER_AUTH_VERSION__";','export const next = "__NEXT_VERSION__";','export const react = "__REACT_VERSION__";','export const reactDom = "__REACT_DOM_VERSION__";',@@ -142,6 +144,7 @@ describe("post-build scripts", () => {).resolves.toBe(['export const ai = "2.0.0";',+ 'export const betterAuth = "1.6.26";','export const next = "16.2.6";','export const react = "19.2.6";','export const reactDom = "19.2.6";',diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yamlindex c67e406f2..88958f482 100644--- a/pnpm-workspace.yaml+++ b/pnpm-workspace.yaml@@ -42,6 +42,7 @@ catalog:"@vercel/sandbox": "2.8.0""@workflow/world-postgres": "5.0.0-beta.32"ai: "^7.0.58"+ better-auth: "1.6.26"marked: "17.0.6"next: "16.3.0-preview.6"phase: "0.0.1"