From f568847e0ef2d44d3c9de80d6d5e61ce75b0adb7 Mon Sep 17 00:00:00 2001 From: Will Eastler <32074613+weastler@users.noreply.github.com> Date: Thu, 19 Nov 2026 19:05:13 -0800 Subject: [PATCH 1/3] fix(hub): allow visible members to start prototypes Keep repository writes separately authorized while allowing signed-in repository viewers to compose and copy kickoff prompts. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- .../hub/mocks/create-product-store/index.ts | 4 +- .../hub/routes/expanded-flows.test.tsx | 26 +++- .../hub/routes/real-prototype-index.test.tsx | 129 +++++++++++++++++ hub/client/hooks/use-copilot-handoff/index.ts | 2 +- .../pages/new-prototype-page/stories.tsx | 18 +-- hub/docs/frontend.md | 4 +- .../can-start-prototype-session/index.ts | 12 ++ .../template-repository-access/index.ts | 12 +- .../prototypes/show/get/index.test.ts | 33 ++++- .../repositories/prototypes/show/get/index.ts | 16 +-- .../repositories/templates/index.db.test.ts | 14 +- .../api/repositories/templates/index.test.ts | 136 ++++++++++++++++++ .../api/repositories/templates/index.ts | 14 +- 13 files changed, 363 insertions(+), 57 deletions(-) create mode 100644 hub/server/routes/api/product/can-start-prototype-session/index.ts create mode 100644 hub/server/routes/api/repositories/templates/index.test.ts diff --git a/hub/client/application/hub/mocks/create-product-store/index.ts b/hub/client/application/hub/mocks/create-product-store/index.ts index 43223def4..1a6825143 100644 --- a/hub/client/application/hub/mocks/create-product-store/index.ts +++ b/hub/client/application/hub/mocks/create-product-store/index.ts @@ -168,7 +168,7 @@ export function createProductStore(context: MockFlowContext) { return { repository: context.repositoryRecord(repositoryId), templates: templates(repositoryId), - canCreate: session.read().capabilities.createPrototypes, + canCreate: true, } }, @@ -179,7 +179,7 @@ export function createProductStore(context: MockFlowContext) { return { repository: context.repositoryRecord(repositoryId), template, - canCreate: session.read().capabilities.createPrototypes, + canCreate: true, controlsIdentity: context.controlsIdentity([ "template", repositoryId, diff --git a/hub/client/application/hub/routes/expanded-flows.test.tsx b/hub/client/application/hub/routes/expanded-flows.test.tsx index 0413ee6ee..856189c1c 100644 --- a/hub/client/application/hub/routes/expanded-flows.test.tsx +++ b/hub/client/application/hub/routes/expanded-flows.test.tsx @@ -237,21 +237,33 @@ describe("Hub expanded frontend flows", () => { expect(router.state.location.pathname).toBe("/repositories/2001/new") }) - it("keeps prototype creation and management unavailable to a reader", async () => { + it("allows a reader to start a prompt handoff while denying listing writes", async () => { const store = createMockStore({ origin: window.location.origin }) store.session.select("reader") const server = setupServer(...createMockHandlers(store)) const router = await renderHubFlow(server, "/repositories/2001", { workspaceRoutes }) expect(screen.queryByRole("link", { name: "Edit prototype listings" })).not.toBeInTheDocument() - expect(screen.queryByRole("link", { name: "Create" })).not.toBeInTheDocument() await router.settle(() => router.navigate("/repositories/2001/new")) - expect(screen.getByRole("button", { name: "Create prototype" })).toBeDisabled() - expect(screen.getByRole("main")).toHaveTextContent(/do not have permission to create/i) - expect( - screen.queryByRole("dialog", { name: "Continue in Copilot app" }), - ).not.toBeInTheDocument() + fireEvent.change(screen.getByRole("textbox", { name: "What should we create?" }), { + target: { value: "Simplify the settings flow" }, + }) + await router.settle(() => + fireEvent.click(screen.getByRole("button", { name: "Create prototype" })), + ) + expect(screen.getByRole("dialog", { name: "Continue in Copilot app" })).toBeVisible() + const previousName = store.getPrototype("2001", "1").prototype.name + const write = await fetch( + `${window.location.origin}/api/repositories/2001/prototype-management/1`, + { + method: "PATCH", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ name: "Unauthorized edit", description: null, startPage: "/" }), + }, + ) + expect(write.status).toBe(403) + expect(store.getPrototype("2001", "1").prototype.name).toBe(previousName) }) it("shares management edits with the existing preview and repository", async () => { diff --git a/hub/client/application/hub/routes/real-prototype-index.test.tsx b/hub/client/application/hub/routes/real-prototype-index.test.tsx index bc89233cb..363c1297d 100644 --- a/hub/client/application/hub/routes/real-prototype-index.test.tsx +++ b/hub/client/application/hub/routes/real-prototype-index.test.tsx @@ -88,6 +88,135 @@ async function renderApplication(path: string) { } describe("real prototype index", () => { + it.each(["github", "entra"])( + "starts and copies Default and selected-template sessions for a visible %s member without write capabilities", + async (provider) => { + vi.stubEnv("MODE", "development") + vi.stubEnv("DEV", true) + const repositoryId = "11111111-1111-4111-8111-111111111111" + const repository = { + id: repositoryId, + nameWithOwner: "team/design", + defaultBranch: "main", + capabilities: { + browseTemplates: true, + reviewPrototypes: false, + manageSharing: false, + managePrototypeListings: false, + }, + } + const userId = "44444444-4444-4444-8444-444444444444" + const writeText = vi.fn().mockResolvedValue(undefined) + Object.defineProperty(navigator, "clipboard", { configurable: true, value: { writeText } }) + const permissionChecks = vi.fn() + const writes = vi.fn() + const templateRoute = "/settings?tab=profile#details" + const server = setupServer( + http.get(`${window.location.origin}/api/auth/session`, () => + HttpResponse.json({ + authenticated: true, + membershipId: "55555555-5555-4555-8555-555555555555", + userId, + provider, + login: "member", + name: "Member", + role: "MEMBER", + }), + ), + http.get(`${window.location.origin}/api/workspace`, () => + HttpResponse.json({ + viewer: { id: userId, provider, login: "member", name: "Member", avatarUrl: null }, + capabilities: { + createPrototypes: false, + reviewPrototypes: false, + manageSharing: false, + administerHub: false, + }, + repositories: [repository], + }), + ), + http.get(`${window.location.origin}/api/repositories/${repositoryId}/templates`, () => + HttpResponse.json({ + repository, + canCreate: true, + submissionMode: "copilot", + templates: [ + { + id: "default", + name: "Default", + description: "Start at home.", + route: "/", + previewUrl: null, + screenshotUrl: null, + buildNumber: null, + }, + { + id: "settings", + name: "Settings", + description: "Manage settings.", + route: templateRoute, + previewUrl: null, + screenshotUrl: null, + buildNumber: 1, + }, + ], + }), + ), + http.get( + `${window.location.origin}/api/repositories/${repositoryId}/create/permission`, + () => { + permissionChecks() + return HttpResponse.json({ canCreate: true }) + }, + ), + ) + server.events.on("request:start", ({ request }) => { + if (request.method !== "GET" && new URL(request.url).pathname.startsWith("/api/")) writes() + }) + server.listen({ onUnhandledRequest: "error" }) + onTestFinished(() => server.close()) + const router = await renderApplication(`/repositories/${repositoryId}/new`) + const brief = "Make settings easier to use" + fireEvent.change(await screen.findByRole("textbox", { name: "What should we create?" }), { + target: { value: brief }, + }) + + for (const selected of [false, true]) { + if (selected) { + fireEvent.click(screen.getByRole("button", { name: "Template: Default" })) + fireEvent.click(screen.getByRole("option", { name: `Settings ${templateRoute}` })) + } + fireEvent.click(screen.getByRole("button", { name: "Create prototype" })) + const dialog = await screen.findByRole("dialog", { name: "Continue in Copilot app" }) + const openApp = within(dialog).getByRole("link", { + name: "Open Copilot App", + }) + const launch = new URL(openApp.href) + expect(launch.origin + launch.pathname).toBe("https://github.com/copilot/app/launch") + const session = new URL(launch.searchParams.get("open")!) + expect(session.searchParams.get("repo")).toBe(repository.nameWithOwner) + const prompt = session.searchParams.get("prompt")! + expect(prompt).toContain(brief) + if (selected) { + expect(prompt).toContain(encodeURIComponent(templateRoute)) + expect(prompt).toContain("startPage") + } else { + expect(prompt).not.toContain("TEMPLATE_ROUTE_DATA") + } + const open = vi.fn((event: MouseEvent) => event.preventDefault()) + openApp.addEventListener("click", open, { once: true }) + fireEvent.click(openApp) + expect(open).toHaveBeenCalledOnce() + fireEvent.click(within(dialog).getByRole("button", { name: "Copy prompt" })) + await waitFor(() => expect(writeText).toHaveBeenLastCalledWith(prompt)) + fireEvent.click(within(dialog).getByRole("button", { name: "Close Copilot app dialog" })) + } + expect(permissionChecks).toHaveBeenCalledTimes(2) + expect(writes).not.toHaveBeenCalled() + expect(router.state.location.pathname).toBe(`/repositories/${repositoryId}/new`) + }, + ) + it("opens prototype details from the real index after sign-in", async () => { vi.stubEnv("MODE", "development") vi.stubEnv("DEV", true) diff --git a/hub/client/hooks/use-copilot-handoff/index.ts b/hub/client/hooks/use-copilot-handoff/index.ts index e46a40deb..870bbb1d5 100644 --- a/hub/client/hooks/use-copilot-handoff/index.ts +++ b/hub/client/hooks/use-copilot-handoff/index.ts @@ -18,7 +18,7 @@ export function useCopilotHandoff(authorize: (() => Promise) | undefine if (await authorize()) openDialog() else setError("You do not have permission to create a prototype in this repository.") } catch { - setError("Hub could not check GitHub repository permissions. Try again.") + setError("Hub could not check repository access. Try again.") } finally { checking.current = false setPending(false) diff --git a/hub/client/pages/new-prototype-page/stories.tsx b/hub/client/pages/new-prototype-page/stories.tsx index 3816c6cad..15bf4242e 100644 --- a/hub/client/pages/new-prototype-page/stories.tsx +++ b/hub/client/pages/new-prototype-page/stories.tsx @@ -202,14 +202,16 @@ export const ClearedDetails: Story = { }, } -export const ReadOnly: Story = { +export const AccessChanged: Story = { args: { - submissionDisabled: true, - data: { - ...data, - newPrototypePath: null, - submissionDisabledReason: - "You do not have permission to create prototypes in this repository.", - }, + authorizeHandoff: () => Promise.resolve(false), + }, + play: Submitted.play, +} + +export const AccessUnavailable: Story = { + args: { + authorizeHandoff: () => Promise.reject(new Error("Repository access unavailable")), }, + play: Submitted.play, } diff --git a/hub/docs/frontend.md b/hub/docs/frontend.md index 2307bf0ae..8b6a7a87f 100644 --- a/hub/docs/frontend.md +++ b/hub/docs/frontend.md @@ -160,7 +160,7 @@ These redirects retain other query parameters. The repository-settings redirects ## Connected mock flows -- **Create:** write a brief or start from a template, then open the original continuation dialog. Only its explicit **Open Copilot App** link launches the app; submitting the brief does not create a mock prototype or Build or send a creation request to Hub. Closing the dialog retains the brief. Readers cannot submit a creation handoff. +- **Create:** write a brief or start from a template, then open the original continuation dialog. Only its explicit **Open Copilot App** link launches the app; submitting the brief does not create a mock prototype or Build or send a creation request to Hub. Closing the dialog retains the brief. Readers may submit a creation handoff; repository mutations remain permission-gated. - **Preview and branch:** the first visit opens the prototype information dialog; dismissing it is retained during the mock session. Minimized preview URLs remain valid when reloaded or reopened; their view state is separate from gallery/list filters. **Branch from here** opens the retained composer for users who can create prototypes. Its Copilot prompt names the source branch and includes the live preview route when available. It does not change the pinned Build or create a local record. Prototypes without a Build can still be branching starting points. - **Controls:** a successful preview exposes the original Controls button and in-preview toolbar, including for readers. Failed, running and absent previews do not show Controls. The mock preview supplies an isolated Controls fixture so changes such as **Show description** and **Card spacing** affect the rendered preview without implementing hosted Builds. - **Manage:** the gear beside the Prototypes heading opens the existing management route for users who can create prototypes. Gallery metadata, start-page metadata and fixture-branch registration change canonical local records, not GitHub, source code, workflows, or immutable Build contents. @@ -279,7 +279,7 @@ The `/` and `/repositories` entry points send signed-out viewers to sign-in and `GET /api/repositories/:repositoryId/templates` returns the catalog. `GET /api/repositories/:repositoryId/templates/:templateId` returns a template and its initial route. The template detail page uses the [isolated Build preview](build-previews.md). It supports Controls and minimization, but not prototype review or Build selection. Its copied Hub link records the viewed path, query, and fragment as `return_path` and reopens them on the latest successful Build. Branch from here uses the viewed route as prompt context and makes it the landing page for a non-Default template. -Local Create and template details use **Copy prompt** without contacting GitHub. Hosted handoffs require write access to the selected repository. `GET /api/repositories/:repositoryId/create/permission` rechecks access before opening the continuation dialog. Only **Open Copilot App** opens the GitHub launcher. A handoff from a template starts from the default branch; one from a prototype starts from its branch. Hub never creates a branch or Build in these flows. +Local Create and template details use **Copy prompt** without contacting GitHub. Any signed-in member who can see the repository may start a prototype session or copy its prompt, including GitHub readers and Entra members. Hub administrators still need legitimate repository visibility. `GET /api/repositories/:repositoryId/create/permission` rechecks visibility before opening the continuation dialog. Only **Open Copilot App** opens the GitHub launcher. A handoff from a template starts from the default branch; one from a prototype starts from its branch. Hub never creates a branch or Build in these flows. Pushing or publishing requires the user's separate repository write permission; listing management and other repository mutations retain their own access checks. **Hide welcome** removes the sidebar link for the signed-in user and leaves `/welcome` available in every session. Express returns the preference as `welcomeHidden` in `GET /api/workspace`; `PATCH /api/workspace/welcome` hides the link for the current user without accepting a user ID. The **Create prototype** card opens the selected repository's Create page when template browsing is available, including in local mode. Welcome embeds the same [introduction video](https://www.youtube.com/watch?v=J2Z28CwIfsA) as Rails through YouTube's privacy-enhanced host. To use a different video file, set `VITE_WELCOME_VIDEO_URL` and optionally `VITE_WELCOME_VIDEO_POSTER_URL` when building the client. diff --git a/hub/server/routes/api/product/can-start-prototype-session/index.ts b/hub/server/routes/api/product/can-start-prototype-session/index.ts new file mode 100644 index 000000000..a026b1b24 --- /dev/null +++ b/hub/server/routes/api/product/can-start-prototype-session/index.ts @@ -0,0 +1,12 @@ +import type { ProductViewer, WorkspaceProductRouteDependencies } from "../types.ts" + +export function canStartPrototypeSession( + product: Pick, + viewer: ProductViewer, + repositoryId: string, +) { + // Preparing a prompt does not write to the repository. + return viewer.sessionProvider + ? product.isRepositoryVisible(viewer, repositoryId) + : Promise.resolve(false) +} diff --git a/hub/server/routes/api/product/template-repository-access/index.ts b/hub/server/routes/api/product/template-repository-access/index.ts index 4de2ba4d8..4482e635f 100644 --- a/hub/server/routes/api/product/template-repository-access/index.ts +++ b/hub/server/routes/api/product/template-repository-access/index.ts @@ -1,17 +1,7 @@ -import type { ProductViewer, WorkspaceProductRouteDependencies } from "../types.ts" +import type { ProductViewer } from "../types.ts" export function canBrowseTemplates(viewer: ProductViewer, local: boolean) { return local ? viewer.sessionProvider === "local" && viewer.role === "ADMINISTRATOR" : viewer.sessionProvider !== "local" && viewer.sessionProvider !== null } - -export async function canHandOffToCopilot( - product: Pick, - viewer: ProductViewer, - repositoryId: string, -) { - if (viewer.sessionProvider !== "github") return false - const permission = await product.getRepositoryPermission?.(viewer, repositoryId) - return permission === "write" || permission === "maintain" || permission === "admin" -} diff --git a/hub/server/routes/api/repositories/prototypes/show/get/index.test.ts b/hub/server/routes/api/repositories/prototypes/show/get/index.test.ts index c2194244c..99d938447 100644 --- a/hub/server/routes/api/repositories/prototypes/show/get/index.test.ts +++ b/hub/server/routes/api/repositories/prototypes/show/get/index.test.ts @@ -6,6 +6,7 @@ import express from "express" import { describe, expect, it, vi, type Mock } from "vitest" import type { ProductRouteDependencies } from "../../../../product/types" +import { GitHubProviderRequestError } from "../../../../../../integrations/github/errors" import { get } from "." /** Exercises response preparation without replacing it with a prebuilt JSON body. */ @@ -13,7 +14,9 @@ async function withDetailRoute( operation: ( url: string, readIntroduction: Mock, + visibility: Mock, ) => Promise, + provider = "github", ) { const repositoryId = randomUUID() const prototypeId = randomUUID() @@ -38,8 +41,12 @@ async function withDetailRoute( const readIntroduction = vi.fn( (_input, prepare) => Promise.resolve(prepare(detail, true)), ) + const visibility = vi + .fn() + .mockResolvedValue(true) const product: ProductRouteDependencies = { - isRepositoryVisible: vi.fn(), + isRepositoryVisible: visibility, + getRepositoryPermission: vi.fn().mockResolvedValue("read"), listRepositories: vi.fn(), findRepositoryIndex: vi.fn(), findRepositoryAuthors: vi.fn(), @@ -56,7 +63,8 @@ async function withDetailRoute( restore: vi.fn().mockResolvedValue({ membershipId: randomUUID(), userId: randomUUID(), - provider: "github", + provider, + sessionProvider: provider, login: "viewer", name: null, role: "MEMBER", @@ -73,6 +81,7 @@ async function withDetailRoute( await operation( `http://127.0.0.1:${port}/repositories/${repositoryId}/prototypes/${prototypeId}`, readIntroduction, + visibility, ) } finally { await new Promise((resolve, reject) => { @@ -82,6 +91,26 @@ async function withDetailRoute( } describe("get()", () => { + it.each(["github", "entra"])( + "allows a visible %s reader to start a session from a prototype", + async (provider) => { + await withDetailRoute(async (url) => { + const response = await fetch(url, { headers: { cookie: "hub_session=member-session" } }) + expect(response.status).toBe(200) + expect(await response.json()).toMatchObject({ canBranch: true }) + }, provider) + }, + ) + + it("reports a visibility failure rather than returning a prototype with kickoff silently disabled", async () => { + await withDetailRoute(async (url, _readIntroduction, visibility) => { + visibility.mockRejectedValue(new GitHubProviderRequestError()) + const response = await fetch(url, { headers: { cookie: "hub_session=member-session" } }) + expect(response.status).toBe(503) + expect((await response.json()) as unknown).toHaveProperty("error") + }) + }) + it("keeps editing available when preparing the first introduction response", async () => { await withDetailRoute(async (url) => { const response = await fetch(url, { diff --git a/hub/server/routes/api/repositories/prototypes/show/get/index.ts b/hub/server/routes/api/repositories/prototypes/show/get/index.ts index 9fc8e91f1..942e91520 100644 --- a/hub/server/routes/api/repositories/prototypes/show/get/index.ts +++ b/hub/server/routes/api/repositories/prototypes/show/get/index.ts @@ -9,7 +9,7 @@ import { GitHubProviderRequestError } from "../../../../../../integrations/githu import type { CurrentSessionDependencies } from "../../../../auth/types.ts" import { readProductSession } from "../../../../product/read-product-session/index.ts" import { readProductWithCurrentAuthority } from "../../../../product/read-product-with-current-authority/index.ts" -import { canHandOffToCopilot } from "../../../../product/template-repository-access/index.ts" +import { canStartPrototypeSession } from "../../../../product/can-start-prototype-session/index.ts" import type { WorkspaceProductRouteDependencies } from "../../../../product/types.ts" import { readHostedSharingCapability } from "../../../../public-sharing/read-hosted-sharing-capability/index.ts" import type { PublicSharingRouteDependencies } from "../../../../public-sharing/types.ts" @@ -72,16 +72,10 @@ export function get( }) const eligibility = - product.getRepositoryPermission && initial.sessionProvider === "github" - ? await readProductWithCurrentAuthority(initial, cookie, session, async (viewer) => { - if (!(await product.isRepositoryVisible(viewer, repositoryId.data))) return false - try { - return await canHandOffToCopilot(product, viewer, repositoryId.data) - } catch (error) { - if (error instanceof GitHubProviderRequestError) return false - throw error - } - }) + initial.sessionProvider !== "local" + ? await readProductWithCurrentAuthority(initial, cookie, session, (viewer) => + canStartPrototypeSession(product, viewer, repositoryId.data), + ) : { result: false } if (!eligibility) { response.status(401).json({ error: "Sign in to continue." }) diff --git a/hub/server/routes/api/repositories/templates/index.db.test.ts b/hub/server/routes/api/repositories/templates/index.db.test.ts index fae26a20c..3af18869a 100644 --- a/hub/server/routes/api/repositories/templates/index.db.test.ts +++ b/hub/server/routes/api/repositories/templates/index.db.test.ts @@ -8,7 +8,6 @@ import { expect, it, vi } from "vitest" import { createApp } from "../../../../create-app" import { hubSessionCookieName } from "../../../../integrations/express/hub-session-cookie-name" import { prisma } from "../../../../integrations/prisma" -import { GitHubProviderRequestError } from "../../../../integrations/github/errors" import { findBuildArtifact } from "../../../../repositories/build-artifacts/find-build-artifact" import { findBuildPreviewTarget } from "../../../../repositories/build-artifacts/find-build-preview-target" import { createProductRouteDependencies } from "../../product/create-product-route-dependencies" @@ -247,15 +246,20 @@ it("keeps the catalog, screenshot, and routed preview on one successful default- }) }) -it("offers hosted handoffs only while the host permission resolver confirms write access", async () => { +it("offers a visible reader a hosted handoff without granting listing management", async () => { await withRepository(async ({ read, permission }) => { - expect(await (await read()).json()).toMatchObject({ canCreate: false }) + expect(await (await read()).json()).toMatchObject({ + canCreate: true, + submissionMode: "copilot", + }) + expect(await (await read("/create/permission")).json()).toEqual({ canCreate: true }) + const management = await read("/prototype-management") + expect(management.status).toBe(404) permission.mockResolvedValue("write") + expect((await read("/prototype-management")).status).toBe(200) expect(await (await read()).json()).toMatchObject({ canCreate: true, submissionMode: "copilot", }) - permission.mockRejectedValue(new GitHubProviderRequestError()) - expect((await read("/create/permission")).status).toBe(503) }) }) diff --git a/hub/server/routes/api/repositories/templates/index.test.ts b/hub/server/routes/api/repositories/templates/index.test.ts new file mode 100644 index 000000000..8e28fe5d2 --- /dev/null +++ b/hub/server/routes/api/repositories/templates/index.test.ts @@ -0,0 +1,136 @@ +import { randomUUID } from "node:crypto" +import { once } from "node:events" +import { createServer } from "node:http" +import type { AddressInfo } from "node:net" +import express from "express" +import { describe, expect, it, vi } from "vitest" + +import type { CurrentSessionDependencies } from "../../auth/types" +import { GitHubProviderRequestError } from "../../../../integrations/github/errors" +import type { WorkspaceProductRouteDependencies } from "../../product/types" +import { templateRoutes } from "." + +type Viewer = NonNullable>> + +async function withTemplates( + options: { provider: string; administrator?: boolean; permission?: "read" | "write" }, + run: (fixture: { + read: (path: string, cookie?: string) => Promise + visibility: ReturnType> + restore: ReturnType> + }) => Promise, +) { + const repositoryId = randomUUID() + const viewer: Viewer = { + userId: randomUUID(), + membershipId: randomUUID(), + provider: options.provider, + sessionProvider: options.provider, + login: "member", + name: null, + role: options.administrator ? "ADMINISTRATOR" : "MEMBER", + } + const restore = vi.fn().mockResolvedValue(viewer) + const visibility = vi + .fn() + .mockResolvedValue(true) + const product: WorkspaceProductRouteDependencies & { + templates: NonNullable + } = { + isRepositoryVisible: visibility, + getRepositoryPermission: vi.fn().mockResolvedValue(options.permission ?? "read"), + templates: { + findBuild: vi.fn().mockResolvedValue({ + repository: { + id: repositoryId, + nameWithOwner: "team/design", + defaultBranch: "main", + localPath: null, + }, + build: null, + }), + }, + listRepositories: vi.fn(), + findRepositoryIndex: vi.fn(), + findRepositoryAuthors: vi.fn(), + findPrototypeDetail: vi.fn(), + readPrototypeWithIntroduction: vi.fn(), + editPrototypeMetadata: vi.fn(), + findBuildPreviewTarget: vi.fn(), + } + const routes = templateRoutes({ restore }, product, undefined) + const app = express() + app.get("/repositories/:repositoryId/templates", routes.catalog) + app.get("/repositories/:repositoryId/templates/:templateId", routes.detail) + app.get("/repositories/:repositoryId/create/permission", routes.permission) + const server = createServer(app) + server.listen(0, "127.0.0.1") + await once(server, "listening") + try { + const { port } = server.address() as AddressInfo + await run({ + visibility, + restore, + read: (path, cookie = "hub_session=member-session") => + fetch(`http://127.0.0.1:${port}/repositories/${repositoryId}${path}`, { + headers: { cookie }, + }), + }) + } finally { + await new Promise((resolve, reject) => + server.close((error) => (error ? reject(error) : resolve())), + ) + } +} + +describe("templateRoutes()", () => { + it.each([ + { access: "GitHub read-only", provider: "github", permission: "read" as const }, + { access: "Entra member", provider: "entra" }, + { access: "Hub administrator", provider: "github", administrator: true }, + { access: "GitHub writer", provider: "github", permission: "write" as const }, + ])("allows a visible $access to compose and start without repository writes", async (viewer) => { + await withTemplates(viewer, async ({ read }) => { + for (const path of ["/templates", "/templates/default", "/create/permission"]) { + const response = await read(path) + expect(response.status).toBe(200) + expect(await response.json()).toMatchObject({ canCreate: true }) + } + }) + }) + + it("denies an anonymous caller and a hidden repository even for an administrator", async () => { + await withTemplates( + { provider: "github", administrator: true }, + async ({ read, visibility }) => { + visibility.mockResolvedValue(false) + for (const path of ["/templates", "/templates/default", "/create/permission"]) { + expect((await read(path, "")).status).toBe(401) + expect((await read(path)).status).toBe(404) + } + }, + ) + }) + + it("reports visibility provider failures instead of granting an administrator access", async () => { + await withTemplates( + { provider: "github", administrator: true }, + async ({ read, visibility }) => { + visibility.mockRejectedValue(new GitHubProviderRequestError()) + for (const path of ["/templates", "/templates/default", "/create/permission"]) { + const response = await read(path) + expect(response.status).toBe(503) + expect((await response.json()) as unknown).toHaveProperty("error") + } + }, + ) + }) + + it("does not return kickoff permission after the session is revoked during the read", async () => { + await withTemplates({ provider: "entra" }, async ({ read, restore }) => { + const viewer = await restore("test-session") + restore.mockReset().mockResolvedValueOnce(viewer).mockResolvedValueOnce(null) + expect((await read("/create/permission")).status).toBe(401) + }) + }) +}) diff --git a/hub/server/routes/api/repositories/templates/index.ts b/hub/server/routes/api/repositories/templates/index.ts index d5fff9bcb..af349d0b3 100644 --- a/hub/server/routes/api/repositories/templates/index.ts +++ b/hub/server/routes/api/repositories/templates/index.ts @@ -18,10 +18,8 @@ import type { BuildPreviewRouteDependencies } from "../../../build-preview/types import type { CurrentSessionDependencies } from "../../auth/types.ts" import { readProductSession } from "../../product/read-product-session/index.ts" import { readProductWithCurrentAuthority } from "../../product/read-product-with-current-authority/index.ts" -import { - canBrowseTemplates, - canHandOffToCopilot, -} from "../../product/template-repository-access/index.ts" +import { canBrowseTemplates } from "../../product/template-repository-access/index.ts" +import { canStartPrototypeSession } from "../../product/can-start-prototype-session/index.ts" import type { ProductViewer, WorkspaceProductRouteDependencies } from "../../product/types.ts" const defaultTemplate = { @@ -166,8 +164,8 @@ export function templateRoutes( const snapshot = await load(viewer, repositoryId) if (!snapshot) return null const { repository, templates, build, local } = snapshot - const canCreate = local || (await canHandOffToCopilot(product, viewer, repositoryId)) - if (!(await product.isRepositoryVisible(viewer, repositoryId))) return null + const canCreate = await canStartPrototypeSession(product, viewer, repositoryId) + if (!canCreate) return null const submissionMode = local ? "copy" : "copilot" const context = { repository, canCreate, submissionMode } if (!id) { @@ -206,8 +204,8 @@ export function templateRoutes( detail: read(true), permission: authorized( async (_request, viewer, repositoryId) => { - if (!(await product.isRepositoryVisible(viewer, repositoryId))) return null - return { canCreate: await canHandOffToCopilot(product, viewer, repositoryId) } + if (!(await canStartPrototypeSession(product, viewer, repositoryId))) return null + return { canCreate: true } }, (response, result) => { response.json(result) From 53de4a724ff24d5459eb91d74a9e97f9e3af9d60 Mon Sep 17 00:00:00 2001 From: Will Eastler <32074613+weastler@users.noreply.github.com> Date: Thu, 19 Nov 2026 19:50:46 -0800 Subject: [PATCH 2/3] fix(hub): show lost repository access as a denial Treat a hidden repository during the Copilot handoff check as a denial, show Create to mock readers, and align the mock flow documentation. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- .../authorize-copilot-handoff/index.test.ts | 36 +++++++++++++++++++ .../authorize-copilot-handoff/index.ts | 17 ++++++--- .../hub/routes/expanded-flows.test.tsx | 3 +- .../view-models/repository-workspace/index.ts | 2 +- hub/docs/frontend.md | 4 +-- 5 files changed, 53 insertions(+), 9 deletions(-) create mode 100644 hub/client/application/hub/requests/authorize-copilot-handoff/index.test.ts diff --git a/hub/client/application/hub/requests/authorize-copilot-handoff/index.test.ts b/hub/client/application/hub/requests/authorize-copilot-handoff/index.test.ts new file mode 100644 index 000000000..58a002898 --- /dev/null +++ b/hub/client/application/hub/requests/authorize-copilot-handoff/index.test.ts @@ -0,0 +1,36 @@ +import { http, HttpResponse } from "msw" +import { setupServer } from "msw/node" +import { describe, expect, it, onTestFinished, vi } from "vitest" + +import { ApiRequestError } from "../api-request-error" +import { authorizeCopilotHandoff } from "." + +const repositoryId = "11111111-1111-4111-8111-111111111111" + +function respondWith(status: number) { + vi.stubEnv("MODE", "development") + const server = setupServer( + http.get(`${window.location.origin}/api/repositories/${repositoryId}/create/permission`, () => + HttpResponse.json({ error: "Unavailable." }, { status }), + ), + ) + server.listen({ onUnhandledRequest: "error" }) + onTestFinished(() => server.close()) +} + +describe("authorizeCopilotHandoff()", () => { + it("denies the handoff when the repository is no longer visible", async () => { + respondWith(404) + + await expect(authorizeCopilotHandoff(repositoryId)).resolves.toBe(false) + }) + + it("reports an unavailable access check instead of a denial", async () => { + respondWith(503) + + await expect(authorizeCopilotHandoff(repositoryId)).rejects.toMatchObject({ + constructor: ApiRequestError, + status: 503, + }) + }) +}) diff --git a/hub/client/application/hub/requests/authorize-copilot-handoff/index.ts b/hub/client/application/hub/requests/authorize-copilot-handoff/index.ts index 03c937b2b..435d92635 100644 --- a/hub/client/application/hub/requests/authorize-copilot-handoff/index.ts +++ b/hub/client/application/hub/requests/authorize-copilot-handoff/index.ts @@ -1,11 +1,18 @@ import { z } from "zod" +import { ApiRequestError } from "../api-request-error" import { requestJson } from "../request-json" export async function authorizeCopilotHandoff(repositoryId: string) { - const permission = await requestJson( - new URL(`/api/repositories/${repositoryId}/create/permission`, window.location.origin), - z.object({ canCreate: z.boolean() }), - ) - return permission.canCreate + try { + const permission = await requestJson( + new URL(`/api/repositories/${repositoryId}/create/permission`, window.location.origin), + z.object({ canCreate: z.boolean() }), + ) + return permission.canCreate + } catch (error) { + // Hub hides repositories the viewer can no longer see behind a 404. + if (error instanceof ApiRequestError && error.status === 404) return false + throw error + } } diff --git a/hub/client/application/hub/routes/expanded-flows.test.tsx b/hub/client/application/hub/routes/expanded-flows.test.tsx index 856189c1c..304f575f2 100644 --- a/hub/client/application/hub/routes/expanded-flows.test.tsx +++ b/hub/client/application/hub/routes/expanded-flows.test.tsx @@ -244,7 +244,8 @@ describe("Hub expanded frontend flows", () => { const router = await renderHubFlow(server, "/repositories/2001", { workspaceRoutes }) expect(screen.queryByRole("link", { name: "Edit prototype listings" })).not.toBeInTheDocument() - await router.settle(() => router.navigate("/repositories/2001/new")) + await router.settle(() => fireEvent.click(screen.getByRole("link", { name: "Create" }))) + expect(router.state.location.pathname).toBe("/repositories/2001/new") fireEvent.change(screen.getByRole("textbox", { name: "What should we create?" }), { target: { value: "Simplify the settings flow" }, diff --git a/hub/client/application/hub/view-models/repository-workspace/index.ts b/hub/client/application/hub/view-models/repository-workspace/index.ts index a9d3a2b11..f56225e50 100644 --- a/hub/client/application/hub/view-models/repository-workspace/index.ts +++ b/hub/client/application/hub/view-models/repository-workspace/index.ts @@ -12,7 +12,7 @@ export function repositoryWorkspace( ) { const browseTemplates = real ? workspace.repositories.find(({ id }) => id === repository.id)?.capabilities?.browseTemplates - : workspace.capabilities?.createPrototypes + : true const canManageAnalytics = repository.capabilities?.manageAnalytics || workspace.repositories.find((entry) => entry.id === repository.id)?.capabilities diff --git a/hub/docs/frontend.md b/hub/docs/frontend.md index 8b6a7a87f..9dc44b9a2 100644 --- a/hub/docs/frontend.md +++ b/hub/docs/frontend.md @@ -160,8 +160,8 @@ These redirects retain other query parameters. The repository-settings redirects ## Connected mock flows -- **Create:** write a brief or start from a template, then open the original continuation dialog. Only its explicit **Open Copilot App** link launches the app; submitting the brief does not create a mock prototype or Build or send a creation request to Hub. Closing the dialog retains the brief. Readers may submit a creation handoff; repository mutations remain permission-gated. -- **Preview and branch:** the first visit opens the prototype information dialog; dismissing it is retained during the mock session. Minimized preview URLs remain valid when reloaded or reopened; their view state is separate from gallery/list filters. **Branch from here** opens the retained composer for users who can create prototypes. Its Copilot prompt names the source branch and includes the live preview route when available. It does not change the pinned Build or create a local record. Prototypes without a Build can still be branching starting points. +- **Create:** write a brief or start from a template, then open the original continuation dialog. Only its explicit **Open Copilot App** link launches the app; submitting the brief does not create a mock prototype or Build or send a creation request to Hub. Closing the dialog retains the brief. Readers see **Create** and may submit a creation handoff; repository mutations remain permission-gated. +- **Preview and branch:** the first visit opens the prototype information dialog; dismissing it is retained during the mock session. Minimized preview URLs remain valid when reloaded or reopened; their view state is separate from gallery/list filters. **Branch from here** opens the retained composer for anyone who can see the repository, including readers. Its Copilot prompt names the source branch and includes the live preview route when available. It does not change the pinned Build or create a local record. Prototypes without a Build can still be branching starting points. - **Controls:** a successful preview exposes the original Controls button and in-preview toolbar, including for readers. Failed, running and absent previews do not show Controls. The mock preview supplies an isolated Controls fixture so changes such as **Show description** and **Card spacing** affect the rendered preview without implementing hosted Builds. - **Manage:** the gear beside the Prototypes heading opens the existing management route for users who can create prototypes. Gallery metadata, start-page metadata and fixture-branch registration change canonical local records, not GitHub, source code, workflows, or immutable Build contents. - **Review:** the existing preview bridge supports element and area selection. All conversation changes share one mock review store. Ordinary failed saves retain the draft for retry. Denied or unavailable review writes refresh access; loaded comments are removed if the refresh reports access loss. The read-only profile can inspect conversations but cannot change them. This is not a live multi-user review service. From 694d0e6ef4ee81223ddd1cf7521406832391d254 Mon Sep 17 00:00:00 2001 From: Will Eastler <32074613+weastler@users.noreply.github.com> Date: Thu, 19 Nov 2026 19:58:17 -0800 Subject: [PATCH 3/3] fix(hub): let visible readers branch in mock flows Align mock Create and Branch from here with the visibility-based kickoff policy and update navigation tests that still expected readers to lack Create. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- .../application/hub/routes/session-flow.test.tsx | 4 ++-- .../hub/routes/sharing-navigation.test.tsx | 8 ++++---- .../hub/routes/sidebar-consistency.test.tsx | 16 +++++----------- .../hub/view-models/prototype-show-data/index.ts | 4 +--- 4 files changed, 12 insertions(+), 20 deletions(-) diff --git a/hub/client/application/hub/routes/session-flow.test.tsx b/hub/client/application/hub/routes/session-flow.test.tsx index 87138bc1c..651035ac6 100644 --- a/hub/client/application/hub/routes/session-flow.test.tsx +++ b/hub/client/application/hub/routes/session-flow.test.tsx @@ -100,7 +100,7 @@ describe("Hub mock session flow", () => { ) }) - it("lets Mona save details without granting creation, sharing or management", async () => { + it("lets Mona branch and save details without granting sharing or management", async () => { const store = createMockStore({ origin: window.location.origin }) store.session.select("reader") const server = setupServer(...createMockHandlers(store)) @@ -109,7 +109,7 @@ describe("Hub mock session flow", () => { expect(await screen.findByRole("button", { name: "Account menu for @mona" })).toBeVisible() fireEvent.click(screen.getByRole("button", { name: "View prototype" })) - expect(screen.queryByRole("button", { name: "Branch from here" })).not.toBeInTheDocument() + expect(screen.getByRole("button", { name: "Branch from here" })).toBeVisible() fireEvent.click(screen.getByRole("button", { name: "Edit details" })) const editor = screen.getByRole("dialog", { name: "Edit prototype details" }) fireEvent.change(within(editor).getByRole("textbox", { name: "Name" }), { diff --git a/hub/client/application/hub/routes/sharing-navigation.test.tsx b/hub/client/application/hub/routes/sharing-navigation.test.tsx index 133e0ac3f..d3bf98a0c 100644 --- a/hub/client/application/hub/routes/sharing-navigation.test.tsx +++ b/hub/client/application/hub/routes/sharing-navigation.test.tsx @@ -179,11 +179,11 @@ describe("Public sharing navigation", () => { }) it.each([ - { profile: "owner", login: "octocat", canCreate: true }, - { profile: "reader", login: "mona", canCreate: false }, + { profile: "owner", login: "octocat" }, + { profile: "reader", login: "mona" }, ] as const)( "keeps $profile repository permissions but hides Hub administrator entries and sharing controls when access is denied", - async ({ profile, login, canCreate }) => { + async ({ profile, login }) => { const store = createMockStore({ origin: window.location.origin }) store.session.select(profile) const server = setupServer(...createMockHandlers(store)) @@ -197,7 +197,7 @@ describe("Public sharing navigation", () => { expect(new URL(navigationLink("/notifications").href).searchParams.get("repositoryId")).toBe( "2002", ) - expect(screen.queryByRole("link", { name: "Create" }) !== null).toBe(canCreate) + expect(screen.getByRole("link", { name: "Create" })).toBeVisible() expectNoSharingAdministration() }, ) diff --git a/hub/client/application/hub/routes/sidebar-consistency.test.tsx b/hub/client/application/hub/routes/sidebar-consistency.test.tsx index e2166325d..5a5f639e8 100644 --- a/hub/client/application/hub/routes/sidebar-consistency.test.tsx +++ b/hub/client/application/hub/routes/sidebar-consistency.test.tsx @@ -130,12 +130,10 @@ function administrationLinks() { function expectRepositoryNavigation({ admin, - canCreate = true, welcomeHidden = false, unreadCount, }: { admin: boolean - canCreate?: boolean welcomeHidden?: boolean unreadCount: number }) { @@ -146,7 +144,7 @@ function expectRepositoryNavigation({ const links = navigationLinks() expect(links.map(linkTarget)).toEqual([ ...(welcomeHidden ? [] : ["/welcome?repositoryId=2002"]), - ...(canCreate ? ["/repositories/2002/new"] : []), + "/repositories/2002/new", "/repositories/2002", "/notifications?repositoryId=2002", "/repositories/2002/analytics", @@ -191,19 +189,16 @@ describe("Hub sidebar consistency", () => { } }, 15_000) - it.each([ - { profile: "owner", canCreate: true }, - { profile: "reader", canCreate: false }, - ] as const)( + it.each([{ profile: "owner" }, { profile: "reader" }] as const)( "keeps $profile permissions, hidden Welcome and unread counts when moving between repository and settings pages", - async ({ profile, canCreate }) => { + async ({ profile }) => { const store = createMockStore({ origin: window.location.origin }) store.session.select(profile) store.settings.mutate({ operation: "welcome-hide" }) const unreadCount = store.getWorkspace().navigation!.notificationsUnreadCount const server = setupServer(...createMockHandlers(store)) const router = await renderHubFlow(server, "/repositories/2002", { workspaceRoutes }) - expectRepositoryNavigation({ admin: false, canCreate, welcomeHidden: true, unreadCount }) + expectRepositoryNavigation({ admin: false, welcomeHidden: true, unreadCount }) for (const pathname of [ "/repositories/2002/analytics", @@ -214,7 +209,7 @@ describe("Hub sidebar consistency", () => { const link = navigationLinks().find((item) => new URL(item.href).pathname === pathname)! await router.settle(() => fireEvent.click(link)) expect(router.state.location.pathname).toBe(pathname) - expectRepositoryNavigation({ admin: false, canCreate, welcomeHidden: true, unreadCount }) + expectRepositoryNavigation({ admin: false, welcomeHidden: true, unreadCount }) } }, ) @@ -277,7 +272,6 @@ describe("Hub sidebar consistency", () => { expectRepositoryNavigation({ admin: true, - canCreate: false, unreadCount: store.getWorkspace().navigation!.notificationsUnreadCount, }) }) diff --git a/hub/client/application/hub/view-models/prototype-show-data/index.ts b/hub/client/application/hub/view-models/prototype-show-data/index.ts index 44528e526..e83991b9b 100644 --- a/hub/client/application/hub/view-models/prototype-show-data/index.ts +++ b/hub/client/application/hub/view-models/prototype-show-data/index.ts @@ -58,9 +58,7 @@ export function prototypeShowData( branchFromLabel: `Branch from: ${data.prototype.name}`, branchPlaceholder: "What changes would you like to make?", branchSubmitLabel: "Start from this prototype", - branchSubmissionMode: (options.real ? data.canBranch : workspace.capabilities?.createPrototypes) - ? "copilot" - : "disabled", + branchSubmissionMode: !options.real || data.canBranch ? "copilot" : "disabled", branchInitialRoute: options.real ? (data.prototype.startPage ?? "/") : undefined, branchInstructions: `BRIEF-END\nStart from the existing \`${data.prototype.branchName}\` prototype branch in this repository. Create a new branch from that branch for the changes above, keeping the existing prototype as the starting point.\nBuild an interactive working UI prototype. Use the repository's \`create-prototype\` skill if it is installed; otherwise follow its own instructions and conventions.\nDo not publish, commit, or push without explicit approval.`, branchPageInstructions: