The Open Framework for Building Agents
Add Sign in with Vercel to Web Chat channel setup (#4193)
Allen Zhoued98150ed68b
diff --git a/.changeset/web-chat-vercel-sign-in.md b/.changeset/web-chat-vercel-sign-in.mdnew file mode 100644index 000000000..a1261afaa--- /dev/null+++ b/.changeset/web-chat-vercel-sign-in.md@@ -0,0 +1,5 @@+---+"eve": patch+---++Add a Sign in with Vercel option to `eve add channel/web` and the terminal UI's channel picker. Setup offers eligible teams, provisions team-only authentication with production and preview credentials, and explains app limits and name conflicts.diff --git a/README.md b/README.mdindex 51b2c50d2..65268d2e5 100644--- a/README.md+++ b/README.md@@ -110,6 +110,20 @@ That's a working agent. Add human-in-the-loop prompts, subagents, and schedulesFollow the [first-agent tutorial](https://eve.dev/docs/tutorial/first-agent) for a completewalkthrough.+### Add Web Chat++From your agent's directory, link a Vercel project and add Web Chat:++```bash+npx eve link+npx eve add channel/web+```++Choose a hosting layout, then **Sign in with Vercel** to provision authentication for members of the project's team.+You can also select **Web Chat** from the terminal UI's `/add` channel picker.+Run `npx eve deploy` when ready to publish. Local development works without browser sign-in.+See the [Web Chat setup guide](https://eve.dev/docs/channels/eve#web-chat-with-sign-in-with-vercel) for permissions and recovery.+## CommunityThe eve community lives on [GitHub Discussions](https://github.com/vercel/eve/discussions),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.tsindex aacd9b5dd..b9966754e 100644--- 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.ts@@ -45,6 +45,7 @@ export const auth = betterAuth({vercel: {clientId: requireEnvironmentVariable("VERCEL_APP_CLIENT_ID"),clientSecret: requireEnvironmentVariable("VERCEL_APP_CLIENT_SECRET"),+ scope: ["openid", "email", "profile"],},},});diff --git a/docs/channels/eve.mdx b/docs/channels/eve.mdxindex 2a1988d27..c3452ab4f 100644--- a/docs/channels/eve.mdx+++ b/docs/channels/eve.mdx@@ -18,6 +18,71 @@ export default eveChannel({});```+## Web Chat with Sign in with Vercel++Run `eve add channel/web`, or select **Web Chat** from the terminal UI's channel+picker. Choose a hosting layout, then **Sign in with Vercel**. Setup uses a+linked Vercel project and creates a Vercel App that only members of that+project's team can sign in to.++For a new agent, initialize it first, then link a project and add Web Chat:++```bash+eve init my-agent --non-interactive+cd my-agent+eve link+eve add channel/web+```++`eve init --channel-web-nextjs` keeps its existing scaffolding behavior and does+not provision authentication. Sign-in setup runs through `eve add channel/web`+or the terminal UI's channel picker.++The generated Next.js app uses Better Auth sessions. The selected agent's HTTP+channel verifies the same session, while retaining Vercel OIDC and local+development access. In an agent workspace, setup configures only the selected+agent. Other agents keep their own authentication policies.++Setup registers `/api/auth/callback/vercel` as a project redirect URI, so Vercel+validates callbacks against the project's deployment domains. The app uses the+`authorization_code` grant, `client_secret_post` authentication, and the+`openid`, `email`, and `profile` scopes. Setup writes `VERCEL_APP_CLIENT_ID`,+`VERCEL_APP_CLIENT_SECRET`, and `BETTER_AUTH_SECRET` to production and preview;+secret values are marked sensitive and are never printed or written to source.+Run `eve deploy` after setup to publish the app. Local development continues+without browser sign-in.++For automation, supply the setup answers explicitly:++```bash+eve add channel/web --non-interactive \+ --answer 'web-hosting="vercel"' \+ --answer 'web-authentication="vercel"'+```++Use a linked project with permission to manage Vercel Apps and project+environment variables. A team owner can complete setup if your role cannot+create apps. The searchable team picker lists eligible teams first. Disabled+teams show `needs permission` or `couldn't verify`, with shared recovery guidance+below the list. If permissions cannot be verified, that team stays+disabled until you sign in or retry. Linked projects are checked before+interactive auth setup.+If setup reports a missing prerequisite, complete it and resume with+`eve add channel/web --skip-install`. Compatible existing apps+and credentials are reused; conflicting app settings or credentials stop setup+with an error. Authored channel or UI files are preserved unless you explicitly+pass `--overwrite`.++If the team has reached its Vercel App limit, remove an unused app in team+settings and retry. If a generated app name or slug is taken by an incompatible+app, rename the Vercel project in its settings and retry. Compatible apps from a+concurrent setup are reused. A client-secret limit requires removing an unused+secret from the app's settings; setup never removes an existing secret for you.++Choose **Configure authentication myself** (`web-authentication=custom`) to+keep the current channel policy. The default placeholder rejects production+browser requests until you configure your own authentication.+## RoutesThe default eve channel inspects the agent, creates sessions, accepts callbacks and task input, controls sessions, and streams events. Its public routes include:diff --git a/packages/eve/README.md b/packages/eve/README.mdindex 771ece399..23c72a0c8 100644--- a/packages/eve/README.md+++ b/packages/eve/README.md@@ -125,11 +125,26 @@ npx eve@latest init my-agent`eve init` writes a new agent with eve's default model. Pass `--modelopenai/gpt-5.5` to choose another AI Gateway model, `--reasoning high` to set areasoning effort, or `--channel-web-nextjs` to add the Web Chat application. It-installs dependencies, initializes Git, and starts the development server. When-it finds a supported coding-agent REPL, the handoff menu can open that REPL-instead or exit. Targeting an existing project directory (`eve init .`) adds the-agent files and missing dependencies instead. It does not create a Vercel-project or deploy the agent.+installs dependencies, initializes Git, and opens the terminal UI in an interactive+human terminal. Coding-agent invocations return setup instructions instead.+Targeting an existing project directory (`eve init .`) adds the agent files and+missing dependencies instead. Initialization does not create a Vercel project,+configure browser sign-in, or deploy the agent.++To add Web Chat with **Sign in with Vercel**, run these commands from the agent's directory:++```bash+npx eve link+npx eve add channel/web+```++Choose a hosting layout, then **Sign in with Vercel**. The terminal UI's `/add`+channel picker offers the same setup. A team owner or a custom role with App and+environment permissions can provision access for members of the project's team.+Setup configures production and preview credentials; run `npx eve deploy` to publish.+Local development works without browser sign-in. See the+[Web Chat setup guide](https://eve.dev/docs/channels/eve#web-chat-with-sign-in-with-vercel)+for recovery steps.CLI commands:@@ -139,6 +154,7 @@ CLI commands:- `eve build` — compile `.eve/` and build the host output- `eve start` — serve the built `.output/` app- `eve dev` — start the local runtime and REPL+- `eve add channel/web` — add Web Chat and configure browser authentication- `eve set [--model <model-id>] [--reasoning <effort>]` — change root model settings- `eve extension init <name>` — create a new extension package- `eve extension build` — build an extension packagediff --git a/packages/eve/src/cli/commands/integration-setup.test.ts b/packages/eve/src/cli/commands/integration-setup.test.tsindex d53c7b0de..78fa559e0 100644--- a/packages/eve/src/cli/commands/integration-setup.test.ts+++ b/packages/eve/src/cli/commands/integration-setup.test.ts@@ -81,11 +81,14 @@ describe("runIntegrationSetupCommand", () => {);const resolveVercelProject =vi.mocked(runIntegrationSetup).mock.calls[0]?.[1].resolveVercelProject;- await resolveVercelProject?.("GitHub");+ await resolveVercelProject?.("Web Chat sign-in");expect(ensureVercelProject).toHaveBeenCalledWith({appRoot: "/project",prompter: fake.prompter,signal: undefined,+ teamRequirement: expect.objectContaining({+ permissions: expect.objectContaining({ oauth2Application: ["create", "update"] }),+ }),});expect(output.errors).toEqual([]);});diff --git a/packages/eve/src/cli/commands/integration-setup.ts b/packages/eve/src/cli/commands/integration-setup.tsindex 12cab9cd4..0104e2d22 100644--- a/packages/eve/src/cli/commands/integration-setup.ts+++ b/packages/eve/src/cli/commands/integration-setup.ts@@ -6,6 +6,7 @@ import {withAnswers,withPolicy,} from "#setup/ask.js";+import { WEB_CHAT_TEAM_REQUIREMENT } from "#setup/integrations/web/auth-options.js";import { ensureVercelProject } from "#setup/flows/ensure-vercel-project.js";import { resolveEveProjectContext } from "#internal/project-context.js";import { createHeadlessPrompter } from "#setup/headless.js";@@ -72,6 +73,7 @@ export async function runIntegrationSetupCommand(: () =>ensureVercelProject({appRoot: projectRoot,+ teamRequirement: kind === "web" ? WEB_CHAT_TEAM_REQUIREMENT : undefined,prompter,signal: client?.signal ?? options.signal,}),diff --git a/packages/eve/src/cli/commands/registry.ts b/packages/eve/src/cli/commands/registry.tsindex ae04943d5..13d08e00f 100644--- a/packages/eve/src/cli/commands/registry.ts+++ b/packages/eve/src/cli/commands/registry.ts@@ -462,7 +462,9 @@ export async function runAddCommand(return runRegistryAction(logger, appRoot, async () => {const address = itemAddress(item);const projectRoot =- address === itemAddress("channel/web") ? await prepareWebChatProjectRoot(appRoot) : appRoot;+ address === itemAddress("channel/web") && options.skipInstall !== true+ ? await prepareWebChatProjectRoot(appRoot)+ : appRoot;const config = await readEveRegistryConfig(appRoot);if (options.skipInstall === true) {if (options.overwrite === true) {diff --git a/packages/eve/src/cli/dev/tui/setup-flow.ts b/packages/eve/src/cli/dev/tui/setup-flow.tsindex 6adbd3a80..02727af84 100644--- a/packages/eve/src/cli/dev/tui/setup-flow.ts+++ b/packages/eve/src/cli/dev/tui/setup-flow.ts@@ -11,6 +11,7 @@ export type SetupEditableSelectResult =interface SetupSelectRequestBase {message: string;+ helpText?: string;description?: string;metadata?: readonly SelectMetadata[];options: readonly SetupPanelOption[];diff --git a/packages/eve/src/cli/dev/tui/setup-panel.test.ts b/packages/eve/src/cli/dev/tui/setup-panel.test.tsindex da5b71df8..fcd7c2e0b 100644--- a/packages/eve/src/cli/dev/tui/setup-panel.test.ts+++ b/packages/eve/src/cli/dev/tui/setup-panel.test.ts@@ -551,6 +551,29 @@ describe("renderSelectQuestion", () => {expect(clipped?.endsWith("\x1b[0m")).toBe(true);});+ it("wraps shared help below the options without repeating it on rows", () => {+ const options = [+ { value: "owner", label: "Owner team" },+ { value: "member", label: "Member team", disabled: true, disabledReason: "needs permission" },+ ];+ const rows = renderSelectQuestion(+ {+ kind: "search",+ message: "Select your team",+ options,+ helpText: "For disabled teams, ask a team owner to run setup, or choose another team.",+ select: initialSelectState({ options }),+ },+ theme,+ 50,+ );+ const text = rows.join("\n");+ expect(text.indexOf("For disabled teams")).toBeGreaterThan(text.indexOf("Member team"));+ expect(text.match(/ask a team owner/g)).toHaveLength(1);+ expect(text).toContain("choose another team.");+ expect(rows.every((line) => line.length <= 50)).toBe(true);+ });+it("renders a warning-toned disabled row with a dim label and yellow alert annotation", () => {const colored = createTheme({ color: true, unicode: true });const options = [diff --git a/packages/eve/src/cli/dev/tui/setup-panel.ts b/packages/eve/src/cli/dev/tui/setup-panel.tsindex 6cb71ddae..57be1bc84 100644--- a/packages/eve/src/cli/dev/tui/setup-panel.ts+++ b/packages/eve/src/cli/dev/tui/setup-panel.ts@@ -42,6 +42,7 @@ interface SetupQuestionPanelBase {}interface SetupSelectPanelBase extends SetupQuestionPanelBase {+ helpText?: string;options: readonly SetupPanelOption[];searchAction?: SearchActionOption;select: SelectState;@@ -885,6 +886,15 @@ export function renderSelectQuestion(appendSelectNotices(rows, state.notices, presentation.layout, theme, width);}+ if (state.helpText) {+ rows.push("");+ for (const paragraph of state.helpText.split("\n")) {+ for (const line of wrapVisibleLine(paragraph, Math.max(1, width - 4))) {+ rows.push(` ${c.dim(line)}`);+ }+ }+ }+if (state.error !== undefined) {rows.push("", ` ${c.red(state.error)}`);}diff --git a/packages/eve/src/cli/dev/tui/tui-prompter.test.ts b/packages/eve/src/cli/dev/tui/tui-prompter.test.tsindex 90cc4ae47..b3d43999d 100644--- a/packages/eve/src/cli/dev/tui/tui-prompter.test.ts+++ b/packages/eve/src/cli/dev/tui/tui-prompter.test.ts@@ -45,6 +45,7 @@ describe("createTuiPrompter", () => {await prompter.select({message: "extension/agent-browser",+ helpText: "Press Enter to continue.",description: "Add browser automation tools to an eve agent.",metadata: [{ label: "Source", value: "Official eve registry" }],options: [{ value: "add", label: "Add to project" }],@@ -53,6 +54,7 @@ describe("createTuiPrompter", () => {expect(renderer.readSelect).toHaveBeenCalledWith(expect.objectContaining({kind: "single",+ helpText: "Press Enter to continue.",description: "Add browser automation tools to an eve agent.",metadata: [{ label: "Source", value: "Official eve registry" }],}),diff --git a/packages/eve/src/cli/dev/tui/tui-prompter.ts b/packages/eve/src/cli/dev/tui/tui-prompter.tsindex 2c4c6a31f..e8504795c 100644--- a/packages/eve/src/cli/dev/tui/tui-prompter.ts+++ b/packages/eve/src/cli/dev/tui/tui-prompter.ts@@ -32,9 +32,11 @@ function setupSelectRequest<T extends PrompterValue>(message: string;options: SetupSelectRequest["options"];description?: string;+ helpText?: string;metadata?: SetupSelectRequest["metadata"];} = { message: opts.message, options };if (opts.description !== undefined) base.description = opts.description;+ if (opts.helpText !== undefined) base.helpText = opts.helpText;if (opts.metadata !== undefined) base.metadata = opts.metadata;const withContext = <Request extends SetupSelectRequest>(request: Request): Request => {if (opts.notices !== undefined) request.notices = opts.notices;diff --git a/packages/eve/src/setup/boxes/resolve-provisioning.ts b/packages/eve/src/setup/boxes/resolve-provisioning.tsindex 4d21fcb8d..da1b25484 100644--- a/packages/eve/src/setup/boxes/resolve-provisioning.ts+++ b/packages/eve/src/setup/boxes/resolve-provisioning.ts@@ -34,6 +34,7 @@ import {validateTeam,} from "../vercel-project.js";import { withSpinner } from "../with-spinner.js";+import type { VercelTeamRequirement } from "../vercel-project-api.js";/** Injected for tests; defaults to the real Vercel project and fs helpers. */export interface ResolveProvisioningDeps {@@ -78,6 +79,7 @@ export interface ResolveProvisioningOptions {*/projectSelection?: "create-or-link" | "existing-only";teamSelectMessage?: (currentTeam: string) => string;+ teamRequirement?: VercelTeamRequirement;deps?: ResolveProvisioningDeps;}@@ -288,7 +290,11 @@ export function resolveProvisioning(if (deployVercel) {await deps.requireAuth(parent(), prompter, { signal });- const teamOptions = { signal, selectMessage: options.teamSelectMessage };+ const teamOptions = {+ signal,+ selectMessage: options.teamSelectMessage,+ teamRequirement: options.teamRequirement,+ };const team = await deps.pickTeam(prompter, parent(), undefined, teamOptions);const projectOptions = [{diff --git a/packages/eve/src/setup/cli/prompt-ui.test.ts b/packages/eve/src/setup/cli/prompt-ui.test.tsindex eabe89510..f8ef558d3 100644--- a/packages/eve/src/setup/cli/prompt-ui.test.ts+++ b/packages/eve/src/setup/cli/prompt-ui.test.ts@@ -345,6 +345,28 @@ describe("renderSearchableSelect", () => {expect(rendered).not.toContain("Submit");});+ test("shows shared guidance below search results and removes it after submission", () => {+ const input = {+ colors,+ state: "active" as const,+ message: "Select your team",+ multiple: false,+ filter: "",+ options: projectOptions,+ cursor: 0,+ selectedValues: [],+ submitDisplay: "alpha",+ helpText: "Ask a team owner to run setup.\nOr choose another team.",+ };+ const rendered = renderSearchableSelect(input);+ expect(rendered).toContain("Ask a team owner to run setup.");+ expect(rendered.indexOf("Ask a team owner")).toBeGreaterThan(rendered.indexOf("beta"));+ expect(rendered.indexOf("Or choose another team.")).toBeLessThan(+ rendered.indexOf("type to filter"),+ );+ expect(renderSearchableSelect({ ...input, state: "submit" })).not.toContain("team owner");+ });+test("multi-select: checkboxes, a pinned Submit row, and only a filter hint", () => {const rendered = renderSearchableSelect({colors: styledColors,diff --git a/packages/eve/src/setup/cli/prompt-ui.ts b/packages/eve/src/setup/cli/prompt-ui.tsindex d3a387fde..fc5e8c8d8 100644--- a/packages/eve/src/setup/cli/prompt-ui.ts+++ b/packages/eve/src/setup/cli/prompt-ui.ts@@ -215,6 +215,7 @@ export function renderMultiselectPrompt<T extends PromptValue>(input: {footerNote?: string;leadingRail?: "white" | "green";message: string;+ helpText?: string;options: readonly PromptOption<T>[];selectedValues: readonly T[];state: PromptState;@@ -251,17 +252,26 @@ export function renderMultiselectPrompt<T extends PromptValue>(input: {return `${head}${rail} ${input.colors.strikethrough(input.colors.dim("cancelled"))}\n${rail}`;case "error": {const rows = renderMultiselectRows({ ...input, rail });- return `${head.trim()}\n${rail} ${rows}${emptyNotice}\n${cornerFor(input.state, input.colors)} ${input.colors.red(input.error ?? "")}\n`;+ return `${head.trim()}\n${rail} ${rows}${emptyNotice}${selectHelpText(input.helpText, rail, input.colors)}\n${cornerFor(input.state, input.colors)} ${input.colors.red(input.error ?? "")}\n`;}case "initial":case "active": {const rows = renderMultiselectRows({ ...input, rail });const corner = cornerWithNote(cornerFor(input.state, input.colors), input.footerNote);- return `${head}${rail} ${rows}${emptyNotice}\n${corner}\n`;+ return `${head}${rail} ${rows}${emptyNotice}${selectHelpText(input.helpText, rail, input.colors)}\n${corner}\n`;}}}+/** Keeps shared guidance separate from option rows and keyboard controls. */+function selectHelpText(text: string | undefined, rail: string, colors: PromptColors): string {+ if (!text) return "";+ return `\n${rail}\n${text+ .split("\n")+ .map((line) => wrapTextWithPrefix(process.stdout, colors.dim(line), `${rail} `))+ .join("\n")}\n${rail}`;+}+/** Appends a status note to the corner glyph, mirroring how errors trail the corner. */function cornerWithNote(corner: string, note: string | undefined): string {return note ? `${corner} ${note}` : corner;@@ -275,6 +285,7 @@ export function renderSelectPrompt<T extends PromptValue>(input: {footerNote?: string;leadingRail?: "white" | "green";message: string;+ helpText?: string;options: readonly PromptOption<T>[];state: PromptState;}): string {@@ -315,7 +326,7 @@ export function renderSelectPrompt<T extends PromptValue>(input: {}).join(`\n${rail} `);const corner = cornerWithNote(cornerFor(input.state, input.colors), input.footerNote);- return `${head}${rail} ${rows}\n${corner}\n`;+ return `${head}${rail} ${rows}${selectHelpText(input.helpText, rail, input.colors)}\n${corner}\n`;}}}@@ -451,6 +462,7 @@ export function renderSearchableSelect<T extends PromptValue>(input: {leadingRail?: "white" | "green";message: string;multiple: boolean;+ helpText?: string;filter: string;placeholder?: string;options: readonly PromptOption<T>[];@@ -540,7 +552,7 @@ export function renderSearchableSelect<T extends PromptValue>(input: {: "";const help = searchableHelpLine(rail, colors, input.multiple);- const body = `${rail} ${colors.dim(" ")} ${filterInput}\n${rail} ${optionLines}${submitLine}${moreFooter}${help}`;+ const body = `${rail} ${colors.dim(" ")} ${filterInput}\n${rail} ${optionLines}${submitLine}${moreFooter}${selectHelpText(input.helpText, rail, colors)}${help}`;if (input.state === "error") {return `${head.trim()}\n${body}\n${cornerFor(input.state, colors)} ${colors.red(input.error ?? "")}\n`;diff --git a/packages/eve/src/setup/cli/select-component.ts b/packages/eve/src/setup/cli/select-component.tsindex ff1ad0dbc..4865e2dd0 100644--- a/packages/eve/src/setup/cli/select-component.ts+++ b/packages/eve/src/setup/cli/select-component.ts@@ -196,7 +196,7 @@ export class SelectComponent extends Prompt<string | string[]> {/** Renders the active component by dispatching to the renderer for its mode. */function renderSelectComponent(self: SelectComponent,- opts: { message: string; placeholder?: string },+ opts: { message: string; placeholder?: string; helpText?: string },leadingRail: "white" | "green",footerNote: string | undefined,): string {@@ -208,6 +208,7 @@ function renderSelectComponent(state,leadingRail,message: opts.message,+ helpText: opts.helpText,multiple: self.multiple,filter: self.filter,placeholder: opts.placeholder,@@ -229,6 +230,7 @@ function renderSelectComponent(footerNote,leadingRail,message: opts.message,+ helpText: opts.helpText,options: self.options,selectedValues: self.selectedValues(),state,@@ -242,6 +244,7 @@ function renderSelectComponent(footerNote,leadingRail,message: opts.message,+ helpText: opts.helpText,options: self.options,state,});@@ -260,6 +263,7 @@ function renderSelectComponent(*/export async function runSelectComponent<T extends PromptValue>(input: {message: string;+ helpText?: string;options: readonly PromptOption<T>[];multiple: boolean;search: boolean;@@ -295,7 +299,7 @@ export async function runSelectComponent<T extends PromptValue>(input: {if (!promptRef) return "";return renderSelectComponent(promptRef,- { message: input.message, placeholder: input.placeholder },+ { message: input.message, placeholder: input.placeholder, helpText: input.helpText },input.leadingRail,guard?.note(),);diff --git a/packages/eve/src/setup/flows/ensure-vercel-project.test.ts b/packages/eve/src/setup/flows/ensure-vercel-project.test.tsindex f863792a0..78dcade2c 100644--- a/packages/eve/src/setup/flows/ensure-vercel-project.test.ts+++ b/packages/eve/src/setup/flows/ensure-vercel-project.test.ts@@ -1,11 +1,40 @@import { describe, expect, it, vi } from "vitest";import { createFakePrompter } from "#internal/testing/fake-prompter.js";+import { captureVercel } from "#setup/primitives/index.js";+import { WEB_CHAT_TEAM_REQUIREMENT } from "#setup/integrations/web/auth-options.js";+import { WizardCancelledError } from "#setup/step.js";import { ensureVercelProject } from "./ensure-vercel-project.js";+vi.mock("#setup/primitives/index.js", async (importOriginal) => ({+ ...(await importOriginal<typeof import("#setup/primitives/index.js")>()),+ captureVercel: vi.fn(),+}));+describe("ensureVercelProject", () => {+ it("checks Web Chat permissions before reusing a linked project", async () => {+ vi.mocked(captureVercel).mockResolvedValueOnce({+ ok: true,+ stdout: JSON.stringify({ permissions: { oauth2Application: ["read"] } }),+ });+ await expect(+ ensureVercelProject({+ appRoot: "/project",+ prompter: createFakePrompter().prompter,+ teamRequirement: WEB_CHAT_TEAM_REQUIREMENT,+ deps: {+ readProjectLink: async () => ({ orgId: "team_member", projectId: "prj_existing" }),+ runLoginFlow: async () => ({ kind: "already" }),+ },+ }),+ ).rejects.toThrow(/linked Vercel team.*owner/);+ expect(captureVercel).toHaveBeenCalledWith(+ ["api", "/v1/user/permissions", "--method", "GET", "--scope", "team_member"],+ expect.objectContaining({ cwd: "/project" }),+ );+ });it("logs in before reusing an existing project link", async () => {const project = { orgId: "team", projectId: "project" };const runLoginFlow = vi.fn(async () => ({ kind: "logged-in" as const }));diff --git a/packages/eve/src/setup/flows/ensure-vercel-project.ts b/packages/eve/src/setup/flows/ensure-vercel-project.tsindex 365e7ed00..51bb511bb 100644--- a/packages/eve/src/setup/flows/ensure-vercel-project.ts+++ b/packages/eve/src/setup/flows/ensure-vercel-project.ts@@ -10,6 +10,7 @@ import { runInteractive, type AnySetupBox } from "../runner.js";import { snapshotSetupState, type SetupState } from "../state.js";import { WizardCancelledError } from "../step.js";import { requireAuth } from "../vercel-project.js";+import { checkTeamRequirement, type VercelTeamRequirement } from "../vercel-project-api.js";import { inProjectSetupState, prompterSink } from "./in-project.js";import { runLoginFlow } from "./login.js";@@ -27,6 +28,7 @@ export async function ensureVercelProject(input: {prompter: Prompter;signal?: AbortSignal;teamSelectMessage?: (currentTeam: string) => string;+ teamRequirement?: VercelTeamRequirement;deps?: Partial<EnsureVercelProjectDeps>;}): Promise<VercelProjectReference> {const readLink = input.deps?.readProjectLink ?? readProjectLink;@@ -44,7 +46,21 @@ export async function ensureVercelProject(input: {}const existing = await readLink(input.appRoot);- if (existing !== undefined) return existing;+ if (existing !== undefined) {+ if (input.teamRequirement) {+ const issue = await checkTeamRequirement(+ input.appRoot,+ existing.orgId,+ input.teamRequirement,+ { signal: input.signal },+ );+ if (issue)+ throw new Error(+ `Cannot configure the linked Vercel team. ${issue} Run \`eve link\` to choose another team, or ask its owner to finish setup.`,+ );+ }+ return existing;+ }const state = inProjectSetupState(input.appRoot, { kind: "unresolved" });const boxes: AnySetupBox<SetupState>[] = [@@ -56,6 +72,7 @@ export async function ensureVercelProject(input: {adoptExistingLink: false,projectSelection: "create-or-link",teamSelectMessage: input.teamSelectMessage,+ teamRequirement: input.teamRequirement,deps: input.deps?.resolveProvisioning,}),linkVercelProject({ prompter: input.prompter, deps: input.deps?.linkProject }),diff --git a/packages/eve/src/setup/integrations/web/auth-options.ts b/packages/eve/src/setup/integrations/web/auth-options.tsnew file mode 100644index 000000000..e3d49da73--- /dev/null+++ b/packages/eve/src/setup/integrations/web/auth-options.ts@@ -0,0 +1,34 @@+import { select } from "#setup/ask.js";+import type { VercelTeamRequirement } from "#setup/vercel-project-api.js";++export const WEB_CHAT_TEAM_REQUIREMENT: VercelTeamRequirement = {+ permissions: {+ oauth2Application: ["create", "update"],+ projectEnvVars: ["create"],+ projectEnvVarsProduction: ["create"],+ },+ disabledReason: "Web Chat sign-in requires app and environment permissions; ask a team owner.",+};++export type WebAuthenticationChoice = "vercel" | "custom";++export const WEB_AUTHENTICATION_QUESTION = select<WebAuthenticationChoice>({+ key: "web-authentication",+ message: "How should people sign in to Web Chat?",+ options: [+ {+ id: "vercel",+ label: "Sign in with Vercel",+ hint: "Create a Vercel App for members of the linked project's team.",+ value: "vercel",+ },+ {+ id: "custom",+ label: "Configure authentication myself",+ hint: "Keep the current channel auth; the default rejects production browser requests.",+ value: "custom",+ },+ ],+ recommended: "vercel",+ required: true,+});diff --git a/packages/eve/src/setup/integrations/web/auth-scaffold.integration.test.ts b/packages/eve/src/setup/integrations/web/auth-scaffold.integration.test.tsnew file mode 100644index 000000000..bffcd77a4--- /dev/null+++ b/packages/eve/src/setup/integrations/web/auth-scaffold.integration.test.ts@@ -0,0 +1,129 @@+import { mkdtemp, mkdir, readFile, rm, writeFile } from "node:fs/promises";+import { tmpdir } from "node:os";+import { basename, dirname, join, resolve } from "node:path";+import { afterEach, describe, expect, it } from "vitest";+import { resolveEveProjectContext } from "#internal/project-context.js";+import { createFakePrompter } from "#internal/testing/fake-prompter.js";+import { headlessAsker, withAnswers } from "#setup/ask.js";+import { detectPackageManager } from "#setup/package-manager.js";+import { pathExists, writeTextFile } from "#setup/scaffold/files.js";+import { integrationSetupEnvironment } from "../shared/environment.js";+import { createSetupContexts } from "../shared/ui.js";+import {+ WEB_APP_TEMPLATE_FILES,+ WEB_CHANNEL_TEMPLATES,+} from "#setup/scaffold/create/web-template.js";+import { prepareWebAuthScaffold } from "./auth-scaffold.js";+import { applyWebSetup, prepareWebSetup, type WebSetupDeps } from "./setup.js";++const roots: string[] = [];+afterEach(async () => {+ await Promise.all(roots.splice(0).map((root) => rm(root, { recursive: true, force: true })));+});+async function fixture(member = "", webDirectory = "apps/web") {+ const environmentRoot = await mkdtemp(join(tmpdir(), "eve-web-auth-"));+ roots.push(environmentRoot);+ const agentAppRoot = join(environmentRoot, member);+ const channelPath = join(agentAppRoot, "agent/channels/eve.ts");+ const packagePath = join(environmentRoot, "package.json");+ await mkdir(dirname(channelPath), { recursive: true });+ await writeFile(channelPath, WEB_CHANNEL_TEMPLATES.default);+ await writeFile(+ packagePath,+ JSON.stringify({+ scripts: { "dev:all": "vercel dev --local" },+ dependencies: { eve: "latest" },+ }),+ );+ for (const [path, source] of Object.entries(WEB_APP_TEMPLATE_FILES)) {+ const file = join(environmentRoot, webDirectory, path);+ await mkdir(dirname(file), { recursive: true });+ await writeFile(+ file,+ source+ .replaceAll("__EVE_INIT_APP_NAME__", "eve Next.js Starter")+ .replaceAll("__EVE_INIT_WITH_EVE_OPTIONS__", ""),+ );+ }+ return { environmentRoot, agentAppRoot, channelPath, packagePath };+}++describe("Web Chat auth scaffold", () => {+ it("adds auth to an existing root Web Chat without relocating it and can be retried", async () => {+ const { environmentRoot: appRoot, channelPath } = await fixture("", "");+ const nextConfig = await readFile(join(appRoot, "next.config.ts"), "utf8");+ const contexts = createSetupContexts({+ appRoot,+ asker: withAnswers({ "web-authentication": "vercel" })(headlessAsker()),+ environment: integrationSetupEnvironment("authenticated", { kind: "unresolved" }),+ prompter: createFakePrompter().prompter,+ resolveVercelProject: async () => ({ orgId: "team_example", projectId: "prj_example" }),+ });+ const deps: WebSetupDeps = {+ detectPackageManager,+ pathExists,+ readTextFile: (path) => readFile(path, "utf8"),+ resolveEveProjectContext,+ writeTextFile,+ prepareWebAuthScaffold,+ provisionWebChatAuth: async () => {},+ installScaffoldDependencies: async () => {},+ };+ for (let attempt = 0; attempt < 2; attempt += 1) {+ const plan = await prepareWebSetup(contexts.prepare, deps);+ const result = await applyWebSetup(plan, contexts.apply, deps);+ expect(result.deploymentRequired).toBe(true);+ }+ expect(await readFile(join(appRoot, "next.config.ts"), "utf8")).toBe(nextConfig);+ const importPath = /import \{ auth \} from "(.+)"/.exec(+ await readFile(channelPath, "utf8"),+ )?.[1];+ expect(importPath).toBeDefined();+ expect(resolve(dirname(channelPath), importPath!)).toBe(join(appRoot, "lib/auth.js"));+ expect(await pathExists(join(appRoot, "apps/web"))).toBe(false);+ });++ it.each(["", "agents/support"])(+ "wires the real channel to the shared auth module from %s and can be retried",+ async (member) => {+ const input = await fixture(member);+ const layoutPath = join(input.environmentRoot, "apps/web/app/layout.tsx");+ const layout = await readFile(layoutPath, "utf8");+ const write = await prepareWebAuthScaffold(input);+ await write();+ const signIn = await readFile(+ join(input.environmentRoot, "apps/web/app/_components/web-chat-auth.tsx"),+ "utf8",+ );+ expect(signIn).toContain(JSON.stringify(basename(input.agentAppRoot)));+ expect(signIn).not.toContain("__EVE_INIT_APP_NAME__");+ const channel = await readFile(input.channelPath, "utf8");+ const importPath = /import \{ auth \} from "(.+)"/.exec(channel)?.[1];+ expect(importPath).toBeDefined();+ expect(resolve(dirname(input.channelPath), importPath!)).toBe(+ join(input.environmentRoot, "apps/web/lib/auth.js"),+ );+ expect(await readFile(join(input.environmentRoot, "apps/web/lib/auth.ts"), "utf8")).toContain(+ 'requireEnvironmentVariable("BETTER_AUTH_SECRET")',+ );+ const document = JSON.parse(await readFile(input.packagePath, "utf8"));+ expect(document.dependencies["better-auth"]).toBeDefined();+ expect(document.scripts["dev:all"]).toBe("vercel dev --local");+ expect(await readFile(layoutPath, "utf8")).toBe(layout);+ await (+ await prepareWebAuthScaffold(input)+ )();+ expect(await readFile(input.channelPath, "utf8")).toBe(channel);+ },+ );++ it("rejects custom auth before the caller provisions resources or writes files", async () => {+ const input = await fixture();+ await writeFile(input.channelPath, "// existing application auth\n");+ await expect(prepareWebAuthScaffold(input)).rejects.toThrow("contains authored code");+ expect(await readFile(input.channelPath, "utf8")).toBe("// existing application auth\n");+ expect(+ JSON.parse(await readFile(input.packagePath, "utf8")).dependencies["better-auth"],+ ).toBeUndefined();+ });+});diff --git a/packages/eve/src/setup/integrations/web/auth-scaffold.ts b/packages/eve/src/setup/integrations/web/auth-scaffold.tsnew file mode 100644index 000000000..16b17b154--- /dev/null+++ b/packages/eve/src/setup/integrations/web/auth-scaffold.ts@@ -0,0 +1,82 @@+import { readFile } from "node:fs/promises";+import { basename, dirname, join, relative, sep } from "node:path";++import { appendEnv } from "#setup/append-env.js";+import { writeTextFile } from "#setup/scaffold/files.js";+import {+ WEB_APP_SIGN_IN_WITH_VERCEL_TEMPLATE_FILES,+ WEB_APP_TEMPLATE_FILES,+ WEB_CHANNEL_TEMPLATES,+} from "#setup/scaffold/create/web-template.js";+import { resolveWebPackageVersions } from "#setup/scaffold/update/web-options.js";++async function readOptional(path: string): Promise<string | undefined> {+ try {+ return await readFile(path, "utf8");+ } catch (error) {+ if ((error as NodeJS.ErrnoException).code === "ENOENT") return undefined;+ throw error;+ }+}++/** Checks authored files before provisioning, then returns the local scaffold operation. */+export async function prepareWebAuthScaffold(input: {+ environmentRoot: string;+ agentAppRoot: string;+ webRoot?: string;+ force?: boolean;+}): Promise<() => Promise<void>> {+ const webRoot = input.webRoot ?? join(input.environmentRoot, "apps", "web");+ const channelPath = join(input.agentAppRoot, "agent", "channels", "eve.ts");+ const authPath = relative(dirname(channelPath), join(webRoot, "lib", "auth.js"))+ .split(sep)+ .join("/");+ const channel = WEB_CHANNEL_TEMPLATES["sign-in-with-vercel"].replace(+ '"@/lib/auth"',+ JSON.stringify(authPath.startsWith(".") ? authPath : `./${authPath}`),+ );+ const writes = [+ ...Object.entries(WEB_APP_SIGN_IN_WITH_VERCEL_TEMPLATE_FILES)+ .filter(([path]) => path !== "app/layout.tsx")+ .map(([path, source]) => ({+ path: join(webRoot, path),+ source: source.replaceAll("__EVE_INIT_APP_NAME__", () =>+ JSON.stringify(basename(input.agentAppRoot)).slice(1, -1),+ ),+ previous: WEB_APP_TEMPLATE_FILES[path as keyof typeof WEB_APP_TEMPLATE_FILES],+ })),+ { path: channelPath, source: channel, previous: WEB_CHANNEL_TEMPLATES.default },+ ];+ for (const file of writes) {+ const current = await readOptional(file.path);+ if (+ !input.force &&+ current !== undefined &&+ current !== file.source &&+ current !== file.previous+ ) {+ throw new Error(+ `Could not add Sign in with Vercel because ${file.path} contains authored code. Preserve your changes and integrate auth manually, or retry setup with --overwrite.`,+ );+ }+ }+ const packagePath = join(input.environmentRoot, "package.json");+ return async () => {+ const document = JSON.parse(await readFile(packagePath, "utf8")) as {+ dependencies?: Record<string, string>;+ };+ document.dependencies = {+ ...document.dependencies,+ "better-auth":+ document.dependencies?.["better-auth"] ??+ resolveWebPackageVersions(undefined, "sign-in-with-vercel").betterAuthPackageVersion,+ };+ for (const file of writes) await writeTextFile(file.path, file.source, { force: true });+ await writeTextFile(packagePath, `${JSON.stringify(document, null, 2)}\n`, { force: true });+ await appendEnv(join(input.environmentRoot, ".env.example"), {+ VERCEL_APP_CLIENT_ID: "",+ VERCEL_APP_CLIENT_SECRET: "",+ BETTER_AUTH_SECRET: "",+ });+ };+}diff --git a/packages/eve/src/setup/integrations/web/provision-auth.integration.test.ts b/packages/eve/src/setup/integrations/web/provision-auth.integration.test.tsnew file mode 100644index 000000000..ba95e1d07--- /dev/null+++ b/packages/eve/src/setup/integrations/web/provision-auth.integration.test.ts@@ -0,0 +1,317 @@+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { readVercelCliToken } from "#internal/model-auth/vercel-cli.js";+import { provisionWebChatAuth } from "./provision-auth.js";++vi.mock("#internal/model-auth/vercel-cli.js", () => ({ readVercelCliToken: vi.fn() }));+const project = { orgId: "team_test", projectId: "prj_123" };+const app = {+ clientId: "cl_test",+ teamId: "team_test",+ signInFrom: "owning-team",+ scopes: ["openid", "email", "profile"],+ grantTypes: { authorization_code: true },+ clientAuthenticationMethods: { client_secret_post: true },+ projectRedirectUris: [{ projectId: "prj_123", path: "/api/auth/callback/vercel" }],+ clientSecrets: [],+};+const keys = ["VERCEL_APP_CLIENT_ID", "VERCEL_APP_CLIENT_SECRET", "BETTER_AUTH_SECRET"];+const completeEnvs = keys.map((key, i) => ({+ id: `env_${i}`,+ key,+ target: ["production", "preview"],+ value: i === 0 ? "cl_test" : undefined,+}));+const fetchMock = vi.fn<typeof fetch>();+function json(value: unknown, status = 200) {+ return new Response(JSON.stringify(value), { status });+}+function response(value: unknown, status = 200) {+ fetchMock.mockResolvedValueOnce(json(value, status));+}+function initial(envs: unknown[] = []) {+ response({ id: "prj_123", accountId: "team_test", name: "agent" });+ response({ envs });+}+function missingApp() {+ response({ error: { code: "invalid_client" } }, 400);+}+function writes() {+ return fetchMock.mock.calls.filter(([, options]) => options?.method !== "GET");+}+beforeEach(() => {+ vi.mocked(readVercelCliToken).mockResolvedValue("test-token");+ fetchMock.mockReset();+ vi.stubGlobal("fetch", fetchMock);+});+afterEach(() => vi.unstubAllGlobals());++describe("Web Chat auth provisioning", () => {+ it("creates a team-only app with project callbacks and sensitive credentials for both deployments", async () => {+ initial();+ missingApp();+ response(app);+ response({ clientId: "cl_test", clientSecret: "secret-value-1234" });+ response({ created: completeEnvs, failed: [] });++ await provisionWebChatAuth(project);++ const requests = writes();+ expect(JSON.parse(requests[0]![1]!.body as string)).toEqual({+ name: "agent Web Chat 123",+ slug: "agent-web-chat-123",+ signInFrom: "owning-team",+ scopes: ["openid", "email", "profile"],+ grantTypes: { authorization_code: true },+ clientAuthenticationMethods: { client_secret_post: true },+ projectRedirectUris: [{ projectId: "prj_123", path: "/api/auth/callback/vercel" }],+ });+ const variables = JSON.parse(requests[2]![1]!.body as string);+ expect(variables).toEqual([+ {+ key: keys[0],+ value: "cl_test",+ target: ["production", "preview"],+ type: "plain",+ visibility: "config",+ },+ {+ key: keys[1],+ value: "secret-value-1234",+ target: ["production", "preview"],+ type: "sensitive",+ visibility: "secret",+ },+ {+ key: keys[2],+ value: expect.any(String),+ target: ["production", "preview"],+ type: "sensitive",+ visibility: "secret",+ },+ ]);+ expect(Buffer.from(variables[2].value, "base64url")).toHaveLength(32);+ for (const [url, options] of fetchMock.mock.calls) {+ expect(new URL(String(url)).searchParams.get("teamId")).toBe("team_test");+ expect(options?.redirect).toBe("error");+ expect(options?.signal).toBeInstanceOf(AbortSignal);+ }+ });++ it("reuses builder-created apps by client ID without rotating secrets", async () => {+ initial(completeEnvs);+ response({ app: { ...app, slug: "random-builder-slug" } });+ await provisionWebChatAuth(project);+ expect(String(fetchMock.mock.calls[2]![0])).toContain("/oauth-apps/cl_test?");+ expect(writes()).toEqual([]);+ });++ it("fills missing preview credentials without changing production", async () => {+ initial(completeEnvs.map((env) => ({ ...env, target: ["production"] })));+ response({ app });+ response({ clientSecret: "preview-secret-5678" });+ response({ created: [], failed: [] });+ await provisionWebChatAuth(project);+ expect(+ JSON.parse(writes()[1]![1]!.body as string).map((env: { target: string[] }) => env.target),+ ).toEqual([["preview"], ["preview"], ["preview"]]);+ });++ it("does not mistake branch overrides for general preview credentials", async () => {+ initial(completeEnvs.map((env) => ({ ...env, gitBranch: "feature", target: ["preview"] })));+ response({ app });+ response({ clientSecret: "new-secret-5678" });+ response({ created: [], failed: [] });+ await provisionWebChatAuth(project);+ expect(writes()).toHaveLength(2);+ });++ it.each([+ { teamId: "team_other" },+ { signInFrom: "any-team" },+ { projectRedirectUris: [{ projectId: "prj_other", path: "/api/auth/callback/vercel" }] },+ { scopes: ["openid"] },+ { clientAuthenticationMethods: { client_secret_basic: true } },+ ])("refuses incompatible apps without changing their access: %j", async (mismatch) => {+ initial();+ response({ app: { ...app, ...mismatch } });+ await expect(provisionWebChatAuth(project)).rejects.toThrow("does not match");+ expect(writes()).toEqual([]);+ });++ it.each([false, true])("gives recovery specific to a configured app (%s)", async (configured) => {+ initial(configured ? completeEnvs : []);+ response({ app: { ...app, teamId: "team_other" } });+ await expect(provisionWebChatAuth(project)).rejects.toThrow(+ configured ? "Check VERCEL_APP_CLIENT_ID" : "Rename the Vercel project",+ );+ expect(writes()).toEqual([]);+ });++ it("rejects credentials for different apps across environments", async () => {+ initial([+ { ...completeEnvs[0], target: ["production"] },+ { ...completeEnvs[0], id: "env_other", value: "cl_other", target: ["preview"] },+ ]);+ await expect(provisionWebChatAuth(project)).rejects.toThrow("conflicting or incomplete");+ expect(writes()).toEqual([]);+ });++ it("does not attach an unknown existing secret to a newly created app", async () => {+ initial([completeEnvs[1]]);+ await expect(provisionWebChatAuth(project)).rejects.toThrow("conflicting or incomplete");+ expect(writes()).toEqual([]);+ });++ it("checks project ownership before creating any resource", async () => {+ response({ id: "prj_123", accountId: "team_other", name: "agent" });+ await expect(provisionWebChatAuth(project)).rejects.toThrow("selected team");+ expect(writes()).toEqual([]);+ });++ it.each([+ ["app_slug_taken", 409],+ ["app_limit_reached", 400],+ ] as const)(+ "reuses a matching app after concurrent creation returns %s",+ async (code, status) => {+ initial();+ missingApp();+ response({ error: { code } }, status);+ response({ app });+ response({ clientSecret: "new-secret-5678" });+ response({ created: completeEnvs, failed: [] });+ await expect(provisionWebChatAuth(project)).resolves.toBeUndefined();+ },+ );++ it("rolls back only acknowledged env writes and identifies the new secret by its last four characters", async () => {+ initial();+ response({ app });+ response({ clientSecret: "new-secret-5678" });+ response({ created: [completeEnvs[0]], failed: [{ error: { message: "conflict" } }] });+ response({});+ response({});+ await expect(provisionWebChatAuth(project)).rejects.toThrow("Could not save");+ const deletes = fetchMock.mock.calls.filter(([, options]) => options?.method === "DELETE");+ expect(deletes.map(([url]) => new URL(String(url)).pathname)).toEqual([+ "/v9/projects/prj_123/env/env_0",+ "/oauth-apps/cl_test/secret/5678",+ ]);+ });++ it.each([400, 403])(+ "removes the new secret after a definitive env rejection (%s)",+ async (status) => {+ initial();+ response({ app });+ response({ clientSecret: "new-secret-5678" });+ response({ error: { code: "rejected", message: "private-response-data" } }, status);+ response({});+ await expect(provisionWebChatAuth(project)).rejects.toThrow(+ status === 403 ? "Vercel denied" : "Vercel could not configure",+ );+ const deletes = fetchMock.mock.calls.filter(([, options]) => options?.method === "DELETE");+ expect(deletes.map(([url]) => new URL(String(url)).pathname)).toEqual([+ "/oauth-apps/cl_test/secret/5678",+ ]);+ },+ );++ it("attempts all acknowledged cleanup even if an env deletion fails", async () => {+ initial();+ response({ app });+ response({ clientSecret: "new-secret-5678" });+ response({ created: [completeEnvs[0], completeEnvs[2]], failed: [{}] });+ response({ error: { code: "forbidden", message: "private-response-data" } }, 403);+ response({});+ response({});+ await expect(provisionWebChatAuth(project)).rejects.toThrow("Cleanup was incomplete");+ const deletes = fetchMock.mock.calls.filter(([, options]) => options?.method === "DELETE");+ expect(deletes.map(([url]) => new URL(String(url)).pathname)).toEqual([+ "/v9/projects/prj_123/env/env_0",+ "/v9/projects/prj_123/env/env_2",+ "/oauth-apps/cl_test/secret/5678",+ ]);+ });++ it("keeps a saved secret when its environment variable cannot be rolled back", async () => {+ initial();+ response({ app });+ response({ clientSecret: "new-secret-5678" });+ response({ created: [completeEnvs[0], completeEnvs[1]], failed: [{}] });+ response({});+ response({ error: { code: "forbidden" } }, 403);+ await expect(provisionWebChatAuth(project)).rejects.toThrow("Cleanup was incomplete");+ expect(+ fetchMock.mock.calls.some(+ ([url, options]) => options?.method === "DELETE" && String(url).includes("/secret/"),+ ),+ ).toBe(false);+ });++ it("keeps the secret when an env write may have committed before the response was lost", async () => {+ initial();+ response({ app });+ response({ clientSecret: "new-secret-5678" });+ fetchMock.mockRejectedValueOnce(new Error("connection lost"));+ await expect(provisionWebChatAuth(project)).rejects.toThrow("Retry");+ expect(fetchMock.mock.calls.some(([, options]) => options?.method === "DELETE")).toBe(false);+ });++ it.each([500, 502])(+ "keeps the secret after an ambiguous env server failure (%s)",+ async (status) => {+ initial();+ response({ app });+ response({ clientSecret: "new-secret-5678" });+ response({ error: { code: "server_error" } }, status);+ await expect(provisionWebChatAuth(project)).rejects.toThrow("Retry");+ expect(fetchMock.mock.calls.some(([, options]) => options?.method === "DELETE")).toBe(false);+ },+ );++ it("reports access errors without echoing tokens or server response details", async () => {+ response({ error: { code: "forbidden", message: "secret-response-data" } }, 403);+ await expect(provisionWebChatAuth(project)).rejects.toThrow("Run `vercel login`");+ expect(writes()).toEqual([]);+ });++ it.each(["app_name_taken", "app_slug_taken"])(+ "explains recovery from %s without writing credentials",+ async (code) => {+ initial();+ missingApp();+ response({ error: { code, message: "private-server-detail" } }, 409);+ missingApp();+ await expect(provisionWebChatAuth(project)).rejects.toThrow("Rename the Vercel project");+ expect(writes()).toHaveLength(1);+ },+ );++ it("reports the team app limit without creating credentials", async () => {+ initial();+ missingApp();+ response({ error: { code: "app_limit_reached" } }, 400);+ missingApp();+ await expect(provisionWebChatAuth(project)).rejects.toThrow("Remove an unused app");+ expect(writes()).toHaveLength(1);+ });++ it("preserves the collision diagnosis when rereading the app is denied", async () => {+ initial();+ missingApp();+ response({ error: { code: "app_slug_taken" } }, 409);+ response({ error: { code: "forbidden" } }, 403);+ await expect(provisionWebChatAuth(project)).rejects.toThrow("Rename the Vercel project");+ expect(writes()).toHaveLength(1);+ });++ it("reports the app secret limit before generating another secret", async () => {+ initial();+ response({+ app: { ...app, clientSecrets: [{ lastFourChars: "1234" }, { lastFourChars: "5678" }] },+ });+ await expect(provisionWebChatAuth(project)).rejects.toThrow("client secret limit");+ expect(writes()).toEqual([]);+ });+});diff --git a/packages/eve/src/setup/integrations/web/provision-auth.ts b/packages/eve/src/setup/integrations/web/provision-auth.tsnew file mode 100644index 000000000..5813df56c--- /dev/null+++ b/packages/eve/src/setup/integrations/web/provision-auth.ts@@ -0,0 +1,262 @@+import { randomBytes } from "node:crypto";++import { z } from "#compiled/zod/index.js";+import { readVercelCliToken } from "#internal/model-auth/vercel-cli.js";+import type { VercelProjectReference } from "#setup/project-resolution.js";++const APP_CONFLICT_RECOVERY =+ "Rename the Vercel project in its settings, then retry `eve add channel/web --skip-install`.";+const CALLBACK_PATH = "/api/auth/callback/vercel";+const TARGETS = ["production", "preview"] as const;+const KEYS = ["VERCEL_APP_CLIENT_ID", "VERCEL_APP_CLIENT_SECRET", "BETTER_AUTH_SECRET"] as const;+const AppSchema = z.object({+ clientId: z.string().min(1),+ teamId: z.string(),+ signInFrom: z.string().optional(),+ scopes: z.array(z.string()),+ grantTypes: z.record(z.string(), z.boolean()).optional(),+ clientAuthenticationMethods: z.record(z.string(), z.boolean()).optional(),+ projectRedirectUris: z.array(z.object({ projectId: z.string(), path: z.string() })).optional(),+ clientSecrets: z.array(z.object({ lastFourChars: z.string() })).optional(),+});+const EnvSchema = z.object({+ id: z.string(),+ key: z.string(),+ value: z.string().optional(),+ target: z.union([z.string(), z.array(z.string())]).optional(),+ gitBranch: z.string().nullable().optional(),+ customEnvironmentIds: z.array(z.string()).optional(),+});+type App = z.infer<typeof AppSchema>;++class AppApiError extends Error {+ readonly status: number;+ readonly code?: string;++ constructor(status: number, code?: string) {+ super(+ status === 401 || status === 403+ ? "Vercel denied Web Chat auth setup. Run `vercel login` and check that you can manage apps and environment variables in this team, or ask a team owner to run setup."+ : code === "app_limit_reached"+ ? "This team has reached its Vercel App limit. Remove an unused app in team settings and retry."+ : code === "app_name_taken" || code === "app_slug_taken"+ ? `A Vercel App with this name or slug already exists. ${APP_CONFLICT_RECOVERY}`+ : "Vercel could not configure Web Chat authentication. Retry `eve add channel/web --skip-install`.",+ );+ this.status = status;+ this.code = code;+ }+}++function assertMatchingApp(app: App, project: VercelProjectReference, configured: boolean): void {+ if (+ app.teamId !== project.orgId ||+ app.signInFrom !== "owning-team" ||+ !app.grantTypes?.authorization_code ||+ !app.clientAuthenticationMethods?.client_secret_post ||+ !["openid", "email", "profile"].every((scope) => app.scopes.includes(scope)) ||+ !app.projectRedirectUris?.some(+ (uri) => uri.projectId === project.projectId && uri.path === CALLBACK_PATH,+ )+ ) {+ throw new Error(+ `The existing Vercel App does not match this project's team-only Web Chat settings. ${configured ? "Check VERCEL_APP_CLIENT_ID and the app in team settings before retrying." : APP_CONFLICT_RECOVERY}`,+ );+ }+}++/** Provisions team-only browser sign-in without rotating existing project credentials. */+export async function provisionWebChatAuth(+ project: VercelProjectReference,+ signal?: AbortSignal,+): Promise<void> {+ const token = await readVercelCliToken();+ if (!token) throw new Error("Run `vercel login` before setting up Sign in with Vercel.");+ const query = new URLSearchParams({ teamId: project.orgId });+ const request = async (path: string, method = "GET", body?: unknown): Promise<unknown> => {+ const options: RequestInit = {+ method,+ headers: { authorization: `Bearer ${token}`, "content-type": "application/json" },+ redirect: "error",+ signal: signal+ ? AbortSignal.any([signal, AbortSignal.timeout(15_000)])+ : AbortSignal.timeout(15_000),+ };+ if (body !== undefined) options.body = JSON.stringify(body);+ const response = await fetch(`https://api.vercel.com${path}?${query}`, options).catch(() => {+ signal?.throwIfAborted();+ throw new AppApiError(0);+ });+ if (!response.ok) {+ const error = z+ .object({ error: z.object({ code: z.string().optional() }) })+ .safeParse(await response.json().catch(() => undefined));+ throw new AppApiError(response.status, error.success ? error.data.error.code : undefined);+ }+ if (response.status === 204) return undefined;+ return response.json().catch(() => {+ throw new AppApiError(response.status);+ });+ };+ const getApp = async (id: string): Promise<App | undefined> => {+ try {+ return z+ .object({ app: AppSchema })+ .parse(await request(`/oauth-apps/${encodeURIComponent(id)}`)).app;+ } catch (error) {+ if (error instanceof AppApiError && error.code === "invalid_client") return undefined;+ throw error;+ }+ };+ const projectPath = `/v9/projects/${encodeURIComponent(project.projectId)}`;+ const remote = z+ .object({ id: z.string(), accountId: z.string(), name: z.string() })+ .parse(await request(projectPath));+ if (remote.id !== project.projectId || remote.accountId !== project.orgId) {+ throw new Error("The linked Vercel project is not available in the selected team.");+ }+ const allEnvs = z+ .object({ envs: z.array(EnvSchema) })+ .parse(await request(`${projectPath}/env`)).envs;+ const envs = allEnvs.filter((env) => !env.gitBranch && !env.customEnvironmentIds?.length);+ const forTarget = (key: string, target: string) =>+ envs.find(+ (env) =>+ env.key === key &&+ (typeof env.target === "string" ? [env.target] : (env.target ?? [])).includes(target),+ );+ const clientIds = new Set(+ TARGETS.map((target) => forTarget(KEYS[0], target)?.value).filter(Boolean),+ );+ if (+ clientIds.size > 1 ||+ TARGETS.some(+ (target) =>+ (forTarget(KEYS[1], target) || forTarget(KEYS[0], target)) &&+ !forTarget(KEYS[0], target)?.value,+ )+ ) {+ throw new Error(+ "Web Chat has conflicting or incomplete Vercel App credentials. Check production and preview environment variables before retrying.",+ );+ }+ const suffix = project.projectId.replace(/^prj_/, "").toLowerCase();+ const slug = `${remote.name.slice(0, 100)}-web-chat-${suffix}`+ .toLowerCase()+ .replace(/[^a-z0-9-]/g, "-");+ const configuredId = [...clientIds][0];+ let app = await getApp(configuredId ?? slug);+ if (!app && configuredId) {+ throw new Error(+ "The configured Vercel App is unavailable. Check VERCEL_APP_CLIENT_ID before retrying.",+ );+ }+ if (!app) {+ try {+ app = AppSchema.parse(+ await request("/oauth-apps", "POST", {+ name: `${remote.name.slice(0, 100)} Web Chat ${suffix}`,+ slug,+ projectRedirectUris: [{ projectId: project.projectId, path: CALLBACK_PATH }],+ scopes: ["openid", "email", "profile"],+ grantTypes: { authorization_code: true },+ clientAuthenticationMethods: { client_secret_post: true },+ signInFrom: "owning-team",+ }),+ );+ } catch (error) {+ if (!(error instanceof AppApiError)) throw error;+ signal?.throwIfAborted();+ // Another attempt may have created the app before this failure.+ app = await getApp(slug).catch(() => {+ signal?.throwIfAborted();+ throw error;+ });+ if (!app) throw error;+ }+ }+ assertMatchingApp(app, project, configuredId !== undefined);+ const missingTargets = (key: string) => TARGETS.filter((target) => !forTarget(key, target));+ if (KEYS.every((key) => missingTargets(key).length === 0)) return;+ const secretTargets = missingTargets(KEYS[1]);+ if (secretTargets.length && (app.clientSecrets?.length ?? 0) >= 2) {+ throw new Error(+ "This Vercel App has reached its client secret limit. Remove an unused secret in team settings and retry.",+ );+ }+ const clientSecret = secretTargets.length+ ? z+ .object({ clientSecret: z.string().min(4) })+ .parse(await request(`/v1/apps/${encodeURIComponent(app.clientId)}/secrets`, "POST", {}))+ .clientSecret+ : undefined;+ const values = {+ VERCEL_APP_CLIENT_ID: app.clientId,+ VERCEL_APP_CLIENT_SECRET: clientSecret,+ BETTER_AUTH_SECRET: randomBytes(32).toString("base64url"),+ };+ const rollback = async (created: z.infer<typeof EnvSchema>[]): Promise<void> => {+ const results = await Promise.allSettled(+ created.map((env) => request(`${projectPath}/env/${encodeURIComponent(env.id)}`, "DELETE")),+ );+ // Do not revoke a credential that may still be saved in the project.+ const secretStillSaved = results.some(+ (result, index) => result.status === "rejected" && created[index]?.key === KEYS[1],+ );+ if (clientSecret && !secretStillSaved) {+ results.push(+ ...(await Promise.allSettled([+ request(+ `/oauth-apps/${encodeURIComponent(app.clientId)}/secret/${encodeURIComponent(clientSecret.slice(-4))}`,+ "DELETE",+ ),+ ])),+ );+ }+ if (results.some((result) => result.status === "rejected")) {+ throw new Error(+ "Could not save Web Chat auth environment variables. Cleanup was incomplete. Check the project's environment variables and Vercel App client secrets in team settings before retrying.",+ );+ }+ };+ // No upsert: concurrent setup must never replace a working credential.+ const result = z+ .object({+ created: z.array(EnvSchema),+ failed: z.array(z.unknown()),+ })+ .parse(+ await request(+ `/v10/projects/${encodeURIComponent(project.projectId)}/env`,+ "POST",+ KEYS.filter((key) => missingTargets(key).length).map((key) => ({+ key,+ value: values[key],+ target: missingTargets(key),+ type: key === KEYS[0] ? "plain" : "sensitive",+ visibility: key === KEYS[0] ? "config" : "secret",+ })),+ ).catch(async (error: unknown) => {+ // Validation and permission rejections did not commit env writes.+ // Timeouts and server failures can happen after a write committed.+ if (+ error instanceof AppApiError &&+ error.status >= 400 &&+ error.status < 500 &&+ error.status !== 408 &&+ error.status !== 499+ ) {+ await rollback([]);+ }+ throw error;+ }),+ );+ if (result.failed.length === 0) return;++ // Only roll back writes acknowledged by this attempt. An ambiguous network+ // failure may have committed the secret, so it must remain usable on retry.+ await rollback(result.created);+ throw new Error(+ "Could not save Web Chat auth environment variables. Retry `eve add channel/web --skip-install`.",+ );+}diff --git a/packages/eve/src/setup/integrations/web/setup.test.ts b/packages/eve/src/setup/integrations/web/setup.test.tsindex 4aa8cf0b6..755da71c5 100644--- a/packages/eve/src/setup/integrations/web/setup.test.ts+++ b/packages/eve/src/setup/integrations/web/setup.test.ts@@ -20,13 +20,18 @@ function deps(): WebSetupDeps {kind: "standalone",})),writeTextFile: vi.fn(async () => {}),+ prepareWebAuthScaffold: vi.fn(async () => vi.fn(async () => {})),+ provisionWebChatAuth: vi.fn(async () => {}),+ installScaffoldDependencies: vi.fn(async () => {}),};}describe("Web setup", () => {it("presents the hosting topology with concise guidance", async () => {const effects = deps();- const fake = createFakePrompter({ single: () => "vercel" });+ const fake = createFakePrompter({+ single: (question) => (question.message.includes("sign in") ? "custom" : "vercel"),+ });const select = vi.spyOn(fake.prompter, "select");const ctx = createSetupContexts({appRoot: "/project",@@ -65,7 +70,9 @@ describe("Web setup", () => {const resolveVercelProject = vi.fn(async () => ({ orgId: "team", projectId: "project" }));const ctx = createSetupContexts({appRoot: "/project",- asker: withAnswers({ "web-hosting": "vercel" })(headlessAsker()),+ asker: withAnswers({ "web-hosting": "vercel", "web-authentication": "custom" })(+ headlessAsker(),+ ),environment: integrationSetupEnvironment("cli-missing", { kind: "unresolved" }),prompter: createFakePrompter().prompter,resolveVercelProject,@@ -85,7 +92,9 @@ describe("Web setup", () => {});const ctx = createSetupContexts({appRoot: "/project",- asker: withAnswers({ "web-hosting": "next" })(headlessAsker()),+ asker: withAnswers({ "web-hosting": "next", "web-authentication": "custom" })(+ headlessAsker(),+ ),environment: integrationSetupEnvironment("cli-missing", { kind: "unresolved" }),prompter: createFakePrompter().prompter,resolveVercelProject,@@ -258,4 +267,62 @@ describe("Web setup", () => {expect.anything(),);});+ it("resolves a project for sign-in and provisions it before installing auth", async () => {+ const effects = deps();+ const writeAuth = vi.fn(async () => {});+ vi.mocked(effects.prepareWebAuthScaffold).mockResolvedValue(writeAuth);+ const resolveVercelProject = vi.fn(async () => ({ orgId: "team", projectId: "project" }));+ const ctx = createSetupContexts({+ appRoot: "/project",+ asker: withAnswers({ "web-hosting": "vercel", "web-authentication": "vercel" })(+ headlessAsker(),+ ),+ environment: integrationSetupEnvironment("cli-missing", { kind: "unresolved" }),+ prompter: createFakePrompter().prompter,+ resolveVercelProject,+ });+ const plan = await prepareWebSetup(ctx.prepare, effects);+ expect(resolveVercelProject).toHaveBeenCalledWith("Web Chat sign-in");+ await expect(applyWebSetup(plan, ctx.apply, effects)).resolves.toMatchObject({+ deploymentRequired: true,+ });+ expect(effects.provisionWebChatAuth).toHaveBeenCalledWith(+ { orgId: "team", projectId: "project" },+ undefined,+ );+ expect(writeAuth).toHaveBeenCalledOnce();+ expect(vi.mocked(effects.provisionWebChatAuth).mock.invocationCallOrder[0]).toBeLessThan(+ writeAuth.mock.invocationCallOrder[0]!,+ );+ expect(effects.installScaffoldDependencies).toHaveBeenCalledWith(+ expect.objectContaining({ projectPath: "/project" }),+ );+ });++ it("keeps auth files unchanged when provisioning fails", async () => {+ const effects = deps();+ const writeAuth = vi.fn(async () => {});+ vi.mocked(effects.prepareWebAuthScaffold).mockResolvedValue(writeAuth);+ vi.mocked(effects.provisionWebChatAuth).mockRejectedValue(new Error("Cannot create app"));+ const ctx = createSetupContexts({+ appRoot: "/project",+ asker: headlessAsker(),+ environment: integrationSetupEnvironment("cli-missing", { kind: "unresolved" }),+ prompter: createFakePrompter().prompter,+ resolveVercelProject: async () => ({ orgId: "team", projectId: "project" }),+ });+ await expect(+ applyWebSetup(+ {+ hosting: "vercel",+ packageManager: "pnpm",+ authProject: { orgId: "team", projectId: "project" },+ },+ ctx.apply,+ effects,+ ),+ ).rejects.toThrow("Cannot create app");+ expect(writeAuth).not.toHaveBeenCalled();+ expect(effects.installScaffoldDependencies).not.toHaveBeenCalled();+ });});diff --git a/packages/eve/src/setup/integrations/web/setup.ts b/packages/eve/src/setup/integrations/web/setup.tsindex d76b96d09..baf155f52 100644--- a/packages/eve/src/setup/integrations/web/setup.ts+++ b/packages/eve/src/setup/integrations/web/setup.ts@@ -3,6 +3,12 @@ import { join } from "node:path";import { resolveEveProjectContext } from "#internal/project-context.js";import { select } from "#setup/ask.js";+import type { RegistrySetupCompletion } from "#setup/registry-setup-protocol.js";+import type { VercelProjectReference } from "#setup/project-resolution.js";+import { installScaffoldDependencies } from "../shared/scaffold.js";+import { prepareWebAuthScaffold } from "./auth-scaffold.js";+import { WEB_AUTHENTICATION_QUESTION } from "./auth-options.js";+import { provisionWebChatAuth } from "./provision-auth.js";import { detectPackageManager, type PackageManagerKind } from "#setup/package-manager.js";import { pathExists, writeTextFile } from "#setup/scaffold/files.js";import { WEB_CHANNEL_TEMPLATES } from "#setup/scaffold/create/web-template.js";@@ -50,6 +56,9 @@ export interface WebSetupDeps {readTextFile(path: string): Promise<string>;resolveEveProjectContext: typeof resolveEveProjectContext;writeTextFile: typeof writeTextFile;+ prepareWebAuthScaffold: typeof prepareWebAuthScaffold;+ provisionWebChatAuth: typeof provisionWebChatAuth;+ installScaffoldDependencies: typeof installScaffoldDependencies;}const defaultDeps: WebSetupDeps = {@@ -58,11 +67,16 @@ const defaultDeps: WebSetupDeps = {readTextFile: (path) => readFile(path, "utf8"),resolveEveProjectContext,writeTextFile,+ prepareWebAuthScaffold,+ provisionWebChatAuth,+ installScaffoldDependencies,};interface WebSetupPlan {hosting: "next" | "vercel";packageManager: PackageManagerKind;+ authProject?: VercelProjectReference;+ rootWebChat?: boolean;}export async function prepareWebSetup(@@ -73,32 +87,45 @@ export async function prepareWebSetup(if (project.kind === "workspace") {throw new Error("Web Chat setup requires a selected workspace agent.");}- const hosting = await context.asker.ask(- select({- key: "web-hosting",- message: "How should Web Chat and your agents be deployed?",- options: [- {- id: "vercel",- label: "Vercel services",- hint: "(Recommended) Web Chat and agents deploy as separate services.",- value: "vercel" as const,- },- {- id: "next",- label: "Next.js",- hint: "One Next.js app serves Web Chat and routes agent requests.",- value: "next" as const,- },- ],- recommended: "vercel" as const,- required: true,- }),- );- return {+ const rootWebChat =+ (await deps.pathExists(join(project.environmentRoot, "app", "eve-agent.ts"))) &&+ !(await deps.pathExists(join(project.environmentRoot, "apps", "web", "app", "eve-agent.ts")));+ const hosting = rootWebChat+ ? "next"+ : await context.asker.ask(+ select({+ key: "web-hosting",+ message: "How should Web Chat and your agents be deployed?",+ options: [+ {+ id: "vercel",+ label: "Vercel services",+ hint: "(Recommended) Web Chat and agents deploy as separate services.",+ value: "vercel" as const,+ },+ {+ id: "next",+ label: "Next.js",+ hint: "One Next.js app serves Web Chat and routes agent requests.",+ value: "next" as const,+ },+ ],+ recommended: "vercel" as const,+ required: true,+ }),+ );+ const authentication = await context.asker.ask(WEB_AUTHENTICATION_QUESTION);+ const authProject =+ authentication === "vercel"+ ? await context.resolveVercelProject("Web Chat sign-in")+ : undefined;+ const plan: WebSetupPlan = {hosting,packageManager: (await deps.detectPackageManager(project.environmentRoot)).kind,};+ if (authProject !== undefined) plan.authProject = authProject;+ if (rootWebChat) plan.rootWebChat = true;+ return plan;}function runScriptCommand(packageManager: PackageManagerKind, script: string): string {@@ -154,13 +181,24 @@ export async function applyWebSetup(const agentAppRoot =project.kind === "workspace-member" ? project.member.appRoot : project.appRoot;const channelPath = join(agentAppRoot, "agent", "channels", "eve.ts");- if (context.force || !(await deps.pathExists(channelPath))) {+ const webRoot = plan.rootWebChat+ ? project.environmentRoot+ : join(project.environmentRoot, "apps", "web");+ const writeAuth =+ plan.authProject === undefined+ ? undefined+ : await deps.prepareWebAuthScaffold({+ environmentRoot: project.environmentRoot,+ agentAppRoot,+ webRoot,+ force: context.force,+ });+ if (writeAuth === undefined && (context.force || !(await deps.pathExists(channelPath)))) {await deps.writeTextFile(channelPath, WEB_CHANNEL_TEMPLATES.default, {force: context.force,});}const agentName = project.kind === "workspace-member" ? project.member.name : undefined;- const webRoot = join(project.environmentRoot, "apps", "web");await deps.writeTextFile(join(webRoot, "app", "eve-agent.ts"),`/** Named workspace agent selected by the Web Chat installer. */\nexport const WEB_CHAT_AGENT: string | undefined = ${agentName === undefined ? "undefined" : JSON.stringify(agentName)};\n`,@@ -200,11 +238,31 @@ export default withEve(nextConfig);await configurePeerServiceScripts(project.environmentRoot, deps);startScript = "dev:all";} else {- await deps.writeTextFile(nextConfigPath, NEXT_HOSTED_CONFIG, { force: true });- startScript = "dev:web";+ await deps.writeTextFile(+ nextConfigPath,+ plan.rootWebChat ? registryNextConfig : NEXT_HOSTED_CONFIG,+ { force: true },+ );+ startScript = plan.rootWebChat ? "dev" : "dev:web";+ }+ if (plan.authProject !== undefined && writeAuth !== undefined) {+ await deps.provisionWebChatAuth(plan.authProject, context.signal);+ context.signal?.throwIfAborted();+ await writeAuth();+ await deps.installScaffoldDependencies({+ changed: true,+ log: context.presenter.log,+ projectPath: project.environmentRoot,+ signal: context.signal,+ });+ context.presenter.log.success("Configured Sign in with Vercel for this project's team");+ context.presenter.nextSteps([+ "Local setup is complete. Run `eve deploy` to publish these changes. Production and preview credentials are configured.",+ "Local development continues to use localDev() without signing in.",+ ]);}context.presenter.log.success("Configured channel: web");- return {+ const completion: RegistrySetupCompletion = {facts: [{label: "",@@ -212,6 +270,8 @@ export default withEve(nextConfig);},],};+ if (plan.authProject !== undefined) completion.deploymentRequired = true;+ return completion;}export const WEB_SETUP = defineSetupIntegration({diff --git a/packages/eve/src/setup/prompter.ts b/packages/eve/src/setup/prompter.tsindex 1ac448a96..09b2ca530 100644--- a/packages/eve/src/setup/prompter.ts+++ b/packages/eve/src/setup/prompter.ts@@ -124,6 +124,8 @@ export interface SelectCommonOptions<T extends PrompterValue> {message: string;/** Inert context rendered beneath the question heading and above its options. */description?: string;+ /** Shared guidance rendered below the options and above keyboard hints. */+ helpText?: string;/** Labeled facts rendered beneath the description and above the options. */metadata?: readonly SelectMetadata[];options: SelectOption<T>[];@@ -505,6 +507,7 @@ export function createPrompter(): Prompter {const result = guardCancel(await runSelectComponent<T>({message: opts.message,+ helpText: opts.helpText,options: opts.options,multiple: opts.multiple === true,search: opts.search ?? false,diff --git a/packages/eve/src/setup/scaffold/create/web-template.ts b/packages/eve/src/setup/scaffold/create/web-template.tsindex 331f688a5..dd713e298 100644--- a/packages/eve/src/setup/scaffold/create/web-template.ts+++ b/packages/eve/src/setup/scaffold/create/web-template.ts@@ -110,7 +110,7 @@ export const WEB_APP_SIGN_IN_WITH_VERCEL_TEMPLATE_FILES = {"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',+ '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 scope: ["openid", "email", "profile"],\n },\n },\n});\n',} as const;export const WEB_APP_TEMPLATE_PACKAGE_JSON = {diff --git a/packages/eve/src/setup/vercel-project-api.ts b/packages/eve/src/setup/vercel-project-api.tsindex efe842ad1..4d710bf90 100644--- a/packages/eve/src/setup/vercel-project-api.ts+++ b/packages/eve/src/setup/vercel-project-api.ts@@ -123,6 +123,101 @@ export async function listTeams(return parsed.data;}+/** Capabilities required by a setup flow, using Vercel's permission resource names. */+export interface VercelTeamRequirement {+ permissions: Readonly<Record<string, readonly string[]>>;+ disabledReason: string;+}++const TeamPermissionsSchema = z.record(z.string(), z.array(z.string()));+const UNVERIFIED_TEAM_PERMISSIONS = "Could not verify permissions; run `vercel login` or retry.";++function teamPermissionIssue(+ permissions: unknown,+ requirement: VercelTeamRequirement,+): string | undefined {+ const parsed = TeamPermissionsSchema.safeParse(permissions);+ if (!parsed.success) return UNVERIFIED_TEAM_PERMISSIONS;+ return Object.entries(requirement.permissions).every(([resource, actions]) =>+ actions.every((action) => parsed.data[resource]?.includes(action)),+ )+ ? undefined+ : requirement.disabledReason;+}++/** Checks the listed teams in one request, retaining unknown scopes as unavailable. */+export async function checkTeamRequirements(+ projectRoot: string,+ teams: readonly VercelTeamListEntry[],+ requirement: VercelTeamRequirement,+ options: VercelProjectOperationOptions = {},+): Promise<Map<string, string | undefined>> {+ const issues = new Map<string, string | undefined>(+ teams.map((team) => [team.slug, UNVERIFIED_TEAM_PERMISSIONS]),+ );+ const result = await captureVercel(+ ["api", `/v2/teams?permissions=true&limit=${VERCEL_TEAM_PAGE_LIMIT}`, "--method", "GET"],+ { cwd: projectRoot, signal: options.signal, timeoutMs: VERCEL_PROJECT_REQUEST_TIMEOUT_MS },+ );+ options.signal?.throwIfAborted();+ if (!result.ok) return issues;+ let body: unknown;+ try {+ body = JSON.parse(result.stdout);+ } catch {+ return issues;+ }+ const parsed = z+ .object({+ teams: z+ .array(+ z.object({+ slug: z.string(),+ permissions: z.unknown().optional(),+ limited: z.boolean().optional(),+ }),+ )+ .max(VERCEL_TEAM_PAGE_LIMIT),+ })+ .safeParse(body);+ if (!parsed.success) return issues;+ for (const team of parsed.data.teams) {+ if (issues.has(team.slug))+ issues.set(+ team.slug,+ team.limited+ ? UNVERIFIED_TEAM_PERMISSIONS+ : teamPermissionIssue(team.permissions, requirement),+ );+ }+ return issues;+}++/** Returns an actionable reason when a specific team cannot satisfy a setup flow. */+export async function checkTeamRequirement(+ projectRoot: string,+ team: string,+ requirement: VercelTeamRequirement,+ options: VercelProjectOperationOptions = {},+): Promise<string | undefined> {+ const result = await captureVercel(+ ["api", "/v1/user/permissions", "--method", "GET", "--scope", team],+ { cwd: projectRoot, signal: options.signal, timeoutMs: VERCEL_PROJECT_REQUEST_TIMEOUT_MS },+ );+ options.signal?.throwIfAborted();+ if (!result.ok) return UNVERIFIED_TEAM_PERMISSIONS;+ let body: unknown;+ try {+ body = JSON.parse(result.stdout);+ } catch {+ return UNVERIFIED_TEAM_PERMISSIONS;+ }+ const parsed = z.object({ permissions: z.unknown() }).safeParse(body);+ return parsed.success+ ? teamPermissionIssue(parsed.data.permissions, requirement)+ : UNVERIFIED_TEAM_PERMISSIONS;+}+async function fetchProjectPage(projectRoot: string,team: string,diff --git a/packages/eve/src/setup/vercel-project.test.ts b/packages/eve/src/setup/vercel-project.test.tsindex 9c5d56144..a1d4bebdf 100644--- a/packages/eve/src/setup/vercel-project.test.ts+++ b/packages/eve/src/setup/vercel-project.test.ts@@ -3,6 +3,8 @@ import { beforeEach, describe, expect, it, vi } from "vitest";import { createPromptCommandOutput, WHIMSY_POOLS } from "#setup/cli/index.js";import { captureVercel, runVercel, type VercelCaptureResult } from "#setup/primitives/index.js";+import { WEB_CHAT_TEAM_REQUIREMENT } from "./integrations/web/auth-options.js";+import { HumanActionRequiredError } from "#setup/human-action.js";import type { Prompter, PrompterValue, SingleSelectOptions } from "./prompter.js";import { createFakePrompter } from "#internal/testing/fake-prompter.js";@@ -101,6 +103,7 @@ describe("getVercelAuthStatus", () => {it.each(["Error: Not authenticated",+ "Vercel CLI 62.1.0\nError: Not authorized","Error: The specified token is not valid. Use `vercel login` to generate a new token.","Error: You do not have access to the specified account\nLearn More: https://err.sh/vercel/scope-not-accessible",])("reports logged-out for an authentication-recovery diagnostic: %s", async (stderr) => {@@ -1075,6 +1078,8 @@ describe("linkProject", () => {function stubVercel(responses: {whoami?: string;teams?: { name: string; slug: string; current: boolean }[];+ permissions?: Record<string, Record<string, string[]> | null>;+ limitedTeams?: string[];projects?: { name: string; id: string; updatedAt?: number }[];}): void {mockedCaptureVercel.mockImplementation(async (args): Promise<VercelCaptureResult> => {@@ -1093,6 +1098,19 @@ function stubVercel(responses: {? failed(): { ok: true, stdout: JSON.stringify({ teams: responses.teams }) };}+ if (args[0] === "api" && args[1] === "/v2/teams?permissions=true&limit=100") {+ return captured({+ teams: Object.entries(responses.permissions ?? {}).map(([slug, permissions]) => ({+ slug,+ permissions,+ limited: responses.limitedTeams?.includes(slug),+ })),+ });+ }+ if (args[0] === "api" && args[1] === "/v1/user/permissions") {+ const permissions = responses.permissions?.[String(args[args.indexOf("--scope") + 1])];+ return permissions == null ? failed() : captured({ permissions });+ }if (args[0] === "project" && args[1] === "ls") {return responses.projects === undefined? failed()@@ -1140,6 +1158,72 @@ describe("pickTeam selection", () => {expect(selectMessages).toEqual(["Select your team"]);});+ it("keeps ineligible teams visible and defaults to a team with Web Chat permissions", async () => {+ const permitted = {+ oauth2Application: ["create", "update"],+ projectEnvVars: ["create"],+ projectEnvVarsProduction: ["create"],+ };+ stubVercel({+ teams: [+ { name: "Member team", slug: "member", current: true },+ { name: "Owner team", slug: "owner", current: false },+ { name: "Unavailable team", slug: "unavailable", current: false },+ { name: "No production env access", slug: "restricted", current: false },+ { name: "SSO required", slug: "sso", current: false },+ ],+ permissions: {+ member: { ...permitted, oauth2Application: ["read", "list"] },+ owner: permitted,+ unavailable: null,+ restricted: { ...permitted, projectEnvVarsProduction: [] },+ sso: permitted,+ },+ limitedTeams: ["sso"],+ });+ const { prompter } = createFakePrompter({+ single: (opts) => {+ expect(opts.initialValue).toBe("owner");+ expect(opts.options).toMatchObject([+ { value: "owner", disabled: false },+ { value: "member", disabled: true, disabledReason: "needs permission" },+ {+ value: "unavailable",+ disabled: true,+ disabledReason: "couldn't verify",+ },+ { value: "restricted", disabled: true },+ { value: "sso", disabled: true },+ ]);+ expect(opts.search).toBe(true);+ expect(opts.helpText).toContain("ask a team owner");+ expect(opts.helpText).toContain("vercel login");+ return "owner";+ },+ });+ await expect(+ pickTeam(prompter, "/tmp/parent", undefined, {+ teamRequirement: WEB_CHAT_TEAM_REQUIREMENT,+ }),+ ).resolves.toBe("owner");+ });++ it.each([undefined, "member"])(+ "rejects an ineligible sole or preset team (%s)",+ async (preset) => {+ stubVercel({+ teams: [{ name: "Member", slug: "member", current: true }],+ permissions: { member: { oauth2Application: ["read"] } },+ });+ const { prompter } = createFakePrompter();+ await expect(+ pickTeam(prompter, "/tmp/parent", preset, {+ teamRequirement: WEB_CHAT_TEAM_REQUIREMENT,+ }),+ ).rejects.toThrow(/owner/);+ },+ );+it("uses a current-team-aware heading when the caller supplies one", async () => {stubVercel({teams: [diff --git a/packages/eve/src/setup/vercel-project.ts b/packages/eve/src/setup/vercel-project.tsindex 97d36e670..a21bbc385 100644--- a/packages/eve/src/setup/vercel-project.ts+++ b/packages/eve/src/setup/vercel-project.ts@@ -18,6 +18,9 @@ import {normalizeVercelApiResult,} from "./vercel-api-failure.js";import {+ checkTeamRequirement,+ checkTeamRequirements,+ type VercelTeamRequirement,listRecentProjects,listTeams,parseVercelJson,@@ -51,6 +54,7 @@ interface PickProjectOptions extends VercelProjectOperationOptions {}interface PickTeamOptions extends VercelProjectOperationOptions {+ teamRequirement?: VercelTeamRequirement;/** Builds the team selector heading from the current team's display name. */selectMessage?: (currentTeam: string) => string;}@@ -165,6 +169,7 @@ function isLoggedOutFailure(failure: VercelCaptureFailure): boolean {return (text.includes("credentials") ||text.includes("not authenticated") ||+ text.includes("not authorized") ||text.includes("not logged in") ||text.includes("specified token is not valid") ||text.includes("scope-not-accessible") ||@@ -309,7 +314,8 @@ export async function validateTeam(/*** Picks the Vercel team (scope). A passed slug is validated and resolved; with* zero or one team the current scope is used without prompting; otherwise the- * user filters and chooses from the list with a single-selection picker.+ * user filters and chooses from the list with a single-selection picker. Flows+ * with a team requirement always show the picker and disable ineligible teams.*/export async function pickTeam(prompter: Prompter,@@ -319,11 +325,72 @@ export async function pickTeam(): Promise<string> {if (presetTeam !== undefined) {await validateTeam(prompter, projectRoot, presetTeam, options);- return resolveTeam(projectRoot, presetTeam, options);+ const team = await resolveTeam(projectRoot, presetTeam, options);+ if (options.teamRequirement) {+ const issue = await checkTeamRequirement(projectRoot, team, options.teamRequirement, options);+ if (issue) throw new Error(`Cannot use Vercel team "${team}". ${issue}`);+ }+ return team;}const teams = await withSpinner(prompter, whimsyFor("teams"), () =>listTeams(projectRoot, options),);+ if (options.teamRequirement) {+ const requirement = options.teamRequirement;+ const issues = await withSpinner(prompter, "Checking team permissions…", () =>+ checkTeamRequirements(projectRoot, teams, requirement, options),+ );+ const choices = teams+ .map((team) => {+ const issue = issues.get(team.slug);+ return {+ value: team.slug,+ label: team.current ? `${team.name} (current)` : team.name,+ disabled: issue !== undefined,+ disabledReason:+ issue === undefined+ ? undefined+ : issue === requirement.disabledReason+ ? "needs permission"+ : "couldn't verify",+ };+ })+ .sort((a, b) => Number(a.disabled) - Number(b.disabled));+ const helpText = [+ ...(choices.some((choice) => choice.disabledReason === "needs permission")+ ? [+ "For teams that need permission, ask a team owner to run setup,\nor choose another team.",+ ]+ : []),+ ...(choices.some((choice) => choice.disabledReason === "couldn't verify")+ ? ["Couldn't verify access? Retry, or run `vercel login` and try again."]+ : []),+ ].join("\n");+ const enabled = choices.filter((choice) => !choice.disabled);+ if (enabled.length === 0) {+ if (choices.length)+ prompter.note(+ choices.map((choice) => `${choice.label}: ${choice.disabledReason}`).join("\n"),+ );+ throw new Error(+ `No Vercel teams are available for this setup. ${requirement.disabledReason} If permissions could not be verified, run \`vercel login\` and retry.`,+ );+ }+ const current = teams.find((team) => team.current);+ const selected = await prompter.select({+ message: options.selectMessage?.(current?.name ?? "your current team") ?? "Select your team",+ search: true,+ placeholder: "type to search teams",+ options: choices,+ helpText: helpText || undefined,+ initialValue:+ enabled.find((choice) => choice.value === current?.slug)?.value ?? enabled[0]!.value,+ });+ if (!enabled.some((choice) => choice.value === selected)) {+ throw new Error(`Cannot use Vercel team "${selected}". ${requirement.disabledReason}`);+ }+ return selected;+ }if (teams.length <= 1) {return teams.find((team) => team.current)?.slug ?? (await whoamiScope(projectRoot, options));}