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 43223def..1a682514 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/requests/authorize-copilot-handoff/index.test.ts b/hub/client/application/hub/requests/authorize-copilot-handoff/index.test.ts index 0e07c7f7..abe7a78f 100644 --- a/hub/client/application/hub/requests/authorize-copilot-handoff/index.test.ts +++ b/hub/client/application/hub/requests/authorize-copilot-handoff/index.test.ts @@ -11,13 +11,28 @@ describe("authorizeCopilotHandoff()", () => { ) vi.stubGlobal("fetch", fetch) - await expect(authorizeCopilotHandoff("2001", { allowCopyFallback: true })).resolves.toBe(false) + await expect(authorizeCopilotHandoff("2001", { allowCopyFallback: true })).resolves.toBe("copy") await expect(authorizeCopilotHandoff("2001")).rejects.toMatchObject({ status: 503 }) }) + it.each([undefined, true])( + "denies a hidden repository even when copy fallback is %s", + async (allowCopyFallback) => { + vi.stubGlobal( + "fetch", + vi + .fn() + .mockResolvedValue( + Response.json({ error: "Repository not found", canCopy: true }, { status: 404 }), + ), + ) + + await expect(authorizeCopilotHandoff("2001", { allowCopyFallback })).resolves.toBe(false) + }, + ) + it.each([ { status: 401, canCopy: true }, - { status: 404, canCopy: true }, { status: 503, canCopy: undefined }, { status: 503, canCopy: false }, ])("rejects a $status with no applicable copy authorization", async ({ status, canCopy }) => { 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 b69afb68..79bd2fde 100644 --- a/hub/client/application/hub/requests/authorize-copilot-handoff/index.ts +++ b/hub/client/application/hub/requests/authorize-copilot-handoff/index.ts @@ -8,7 +8,7 @@ const copyFallback = z.object({ canCopy: z.literal(true) }) export async function authorizeCopilotHandoff( repositoryId: string, { allowCopyFallback = false } = {}, -) { +): Promise { try { const permission = await requestJson( new URL(`/api/repositories/${repositoryId}/create/permission`, window.location.origin), @@ -16,13 +16,15 @@ export async function authorizeCopilotHandoff( ) 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 if ( allowCopyFallback && error instanceof ApiRequestError && error.status === 503 && copyFallback.safeParse(error.body).success ) { - return false + return "copy" } 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 0413ee6e..304f575f 100644 --- a/hub/client/application/hub/routes/expanded-flows.test.tsx +++ b/hub/client/application/hub/routes/expanded-flows.test.tsx @@ -237,21 +237,34 @@ 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")) + await router.settle(() => fireEvent.click(screen.getByRole("link", { name: "Create" }))) + expect(router.state.location.pathname).toBe("/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 bc89233c..cf7aa471 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,150 @@ 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) + server.use( + http.get( + `${window.location.origin}/api/repositories/${repositoryId}/create/permission`, + () => HttpResponse.json({ error: "Repository not found." }, { status: 404 }), + ), + ) + writeText.mockClear() + + fireEvent.click(screen.getByRole("button", { name: "Create prototype" })) + + expect(await screen.findByRole("alert")).toBeVisible() + expect(screen.getByRole("textbox", { name: "What should we create?" })).toHaveValue(brief) + expect(screen.queryByRole("button", { name: "Copy prompt" })).not.toBeInTheDocument() + expect(screen.queryByRole("link", { name: "Open Copilot App" })).not.toBeInTheDocument() + expect(writeText).not.toHaveBeenCalled() + 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/application/hub/routes/session-flow.test.tsx b/hub/client/application/hub/routes/session-flow.test.tsx index 87138bc1..651035ac 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 133e0ac3..d3bf98a0 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 e2166325..5a5f639e 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 44528e52..e83991b9 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: 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 a9d3a2b1..f56225e5 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/client/hooks/use-copilot-handoff/index.test.ts b/hub/client/hooks/use-copilot-handoff/index.test.ts new file mode 100644 index 00000000..dee66e97 --- /dev/null +++ b/hub/client/hooks/use-copilot-handoff/index.test.ts @@ -0,0 +1,17 @@ +import { act, renderHook } from "@testing-library/react" +import { describe, expect, it, vi } from "vitest" + +import { useCopilotHandoff } from "." + +describe("useCopilotHandoff()", () => { + it("reports a denial when copy fallback has no available copy action", async () => { + const authorize = vi.fn<() => Promise>().mockResolvedValue("copy") + const openDialog = vi.fn() + const { result } = renderHook(() => useCopilotHandoff(authorize)) + + await act(() => result.current.prepare(openDialog)) + + expect(result.current.error).not.toBeNull() + expect(openDialog).not.toHaveBeenCalled() + }) +}) diff --git a/hub/client/hooks/use-copilot-handoff/index.ts b/hub/client/hooks/use-copilot-handoff/index.ts index 563881f7..8dfe4392 100644 --- a/hub/client/hooks/use-copilot-handoff/index.ts +++ b/hub/client/hooks/use-copilot-handoff/index.ts @@ -1,6 +1,6 @@ import { useRef, useState } from "react" -export function useCopilotHandoff(authorize: (() => Promise) | undefined) { +export function useCopilotHandoff(authorize: (() => Promise) | undefined) { const checking = useRef(false) const [pending, setPending] = useState(false) const [error, setError] = useState(null) @@ -15,11 +15,12 @@ export function useCopilotHandoff(authorize: (() => Promise) | undefine setPending(true) setError(null) try { - if (await authorize()) openDialog() - else if (offerCopy) offerCopy() + const permission = await authorize() + if (permission === true) openDialog() + else if (permission === "copy" && offerCopy) offerCopy() 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/index.test.tsx b/hub/client/pages/new-prototype-page/index.test.tsx index 90671e45..f170b950 100644 --- a/hub/client/pages/new-prototype-page/index.test.tsx +++ b/hub/client/pages/new-prototype-page/index.test.tsx @@ -75,10 +75,10 @@ function submitBrief(brief: string) { } describe("NewPrototypePage()", () => { - it("offers a deliberate copy when fresh authorization denies Copilot but still allows viewing", async () => { + it("offers a deliberate copy when fresh authorization explicitly permits copy fallback", async () => { const writeText = vi.fn().mockResolvedValue(undefined) vi.stubGlobal("navigator", { ...navigator, clipboard: { writeText } }) - const authorizeHandoff = vi.fn().mockResolvedValue(false) + const authorizeHandoff = vi.fn().mockResolvedValue("copy") const onOpenApp = vi.fn() const { copy } = PAGE_DATA const brief = "Improve the settings flow" @@ -112,23 +112,40 @@ describe("NewPrototypePage()", () => { expect(onOpenApp).not.toHaveBeenCalled() }) - it("does not offer copying when the handoff check cannot verify repository visibility", async () => { - const authorizeHandoff = vi.fn().mockRejectedValue(new Error("Repository no longer visible")) - render() + it.each(["denied", "unavailable"])( + "preserves the brief without copying when repository access is %s", + async (outcome) => { + const writeText = vi.fn() + vi.stubGlobal("navigator", { ...navigator, clipboard: { writeText } }) + const authorizeHandoff = + outcome === "denied" + ? vi.fn().mockResolvedValue(false) + : vi.fn().mockRejectedValue(new Error("Repository access unavailable")) + const onOpenApp = vi.fn() + render( + , + ) - submitBrief("Preserve this draft") + submitBrief("Preserve this draft") - expect(await screen.findByRole("alert")).toBeVisible() - expect(screen.getByRole("textbox", { name: PAGE_DATA.copy.heading })).toHaveValue( - "Preserve this draft", - ) - expect( - screen.queryByRole("button", { name: PAGE_DATA.copy.copyPromptLabel }), - ).not.toBeInTheDocument() - expect( - screen.queryByRole("link", { name: PAGE_DATA.copy.openAppLabel }), - ).not.toBeInTheDocument() - }) + expect(await screen.findByRole("alert")).toBeVisible() + expect(screen.getByRole("textbox", { name: PAGE_DATA.copy.heading })).toHaveValue( + "Preserve this draft", + ) + expect( + screen.queryByRole("button", { name: PAGE_DATA.copy.copyPromptLabel }), + ).not.toBeInTheDocument() + expect( + screen.queryByRole("link", { name: PAGE_DATA.copy.openAppLabel }), + ).not.toBeInTheDocument() + expect(writeText).not.toHaveBeenCalled() + expect(onOpenApp).not.toHaveBeenCalled() + }, + ) it("copies a local brief and saved details without launching Copilot", async () => { const writeText = vi.fn().mockResolvedValue(undefined) diff --git a/hub/client/pages/new-prototype-page/index.tsx b/hub/client/pages/new-prototype-page/index.tsx index bcb857b3..e5e8081e 100644 --- a/hub/client/pages/new-prototype-page/index.tsx +++ b/hub/client/pages/new-prototype-page/index.tsx @@ -30,7 +30,7 @@ export function NewPrototypePage({ }: { data: NewPrototypePageData onOpenApp?: (url: string) => void - authorizeHandoff?: () => Promise + authorizeHandoff?: () => Promise submissionDisabled?: boolean }) { const headingId = useId() diff --git a/hub/client/pages/new-prototype-page/stories.tsx b/hub/client/pages/new-prototype-page/stories.tsx index 6af9c12d..74c2babc 100644 --- a/hub/client/pages/new-prototype-page/stories.tsx +++ b/hub/client/pages/new-prototype-page/stories.tsx @@ -138,7 +138,7 @@ export const CopyPromptAsViewer: Story = { } export const CopyAfterHandoffDenied: Story = { - args: { authorizeHandoff: () => Promise.resolve(false) }, + args: { authorizeHandoff: () => Promise.resolve("copy") }, play: async ({ canvas, userEvent }) => { await userEvent.type( canvas.getByRole("textbox", { name: data.copy.heading }), @@ -228,14 +228,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/client/pages/prototypes-show-page/types.ts b/hub/client/pages/prototypes-show-page/types.ts index 69b8e7bf..18d8ba88 100644 --- a/hub/client/pages/prototypes-show-page/types.ts +++ b/hub/client/pages/prototypes-show-page/types.ts @@ -96,7 +96,7 @@ export interface PrototypesShowPageProps extends PrototypeDetailsControls { initialComposerExpanded?: boolean onNotificationMessageOpened?: (commentId: number) => void onOpenApp?: (url: string) => void - authorizeHandoff?: () => Promise + authorizeHandoff?: () => Promise viewerUrl?: string minimized?: boolean initialMinimized?: boolean diff --git a/hub/client/pages/replica-browse-page/index.test.tsx b/hub/client/pages/replica-browse-page/index.test.tsx index 9a0e9e71..f867f1d4 100644 --- a/hub/client/pages/replica-browse-page/index.test.tsx +++ b/hub/client/pages/replica-browse-page/index.test.tsx @@ -512,10 +512,10 @@ describe("ReplicaBrowsePage()", () => { ).not.toBeInTheDocument() }) - it("offers deliberate copying from a saved template after Copilot permission is withdrawn", async () => { + it("offers deliberate copying from a saved template when explicitly authorized as a fallback", async () => { const writeText = vi.fn().mockResolvedValue(undefined) vi.stubGlobal("navigator", { ...navigator, clipboard: { writeText } }) - const authorizeHandoff = vi.fn().mockResolvedValue(false) + const authorizeHandoff = vi.fn().mockResolvedValue("copy") const onOpenApp = vi.fn() const data = { ...replicaBrowseData, @@ -555,6 +555,32 @@ describe("ReplicaBrowsePage()", () => { expect(onOpenApp).not.toHaveBeenCalled() }) + it("preserves the brief without offering copy when repository access is denied", async () => { + const writeText = vi.fn() + vi.stubGlobal("navigator", { ...navigator, clipboard: { writeText } }) + const authorizeHandoff = vi.fn().mockResolvedValue(false) + const onOpenApp = vi.fn() + renderPage({ authorizeHandoff, onOpenApp }) + fireEvent.click(screen.getByRole("button", { name: replicaBrowseData.forkLabel })) + const brief = screen.getByRole("textbox", { name: replicaBrowseData.branchPlaceholder }) + fireEvent.change(brief, { target: { value: "Preserve this draft" } }) + + fireEvent.click(screen.getByRole("button", { name: replicaBrowseData.branchSubmitLabel })) + + expect(await screen.findByRole("alert")).toBeVisible() + expect(brief).toHaveValue("Preserve this draft") + expect( + screen.queryByRole("button", { + name: replicaBrowseData.branchContinuation.copyPromptLabel, + }), + ).not.toBeInTheDocument() + expect( + screen.queryByRole("link", { name: replicaBrowseData.branchContinuation.openAppLabel }), + ).not.toBeInTheDocument() + expect(writeText).not.toHaveBeenCalled() + expect(onOpenApp).not.toHaveBeenCalled() + }) + it("copies the local brief and branch instructions without an app handoff", async () => { const writeText = vi.fn().mockResolvedValue(undefined) const onOpenApp = vi.fn() diff --git a/hub/client/pages/replica-browse-page/stories.tsx b/hub/client/pages/replica-browse-page/stories.tsx index 03192877..8a208408 100644 --- a/hub/client/pages/replica-browse-page/stories.tsx +++ b/hub/client/pages/replica-browse-page/stories.tsx @@ -92,7 +92,7 @@ export const CopyTemplatePromptAsViewer: Story = { } export const CopyTemplateAfterHandoffDenied: Story = { - args: { ...Template.args, authorizeHandoff: () => Promise.resolve(false) }, + args: { ...Template.args, authorizeHandoff: () => Promise.resolve("copy") }, play: async ({ canvas, userEvent }) => { await userEvent.click(canvas.getByRole("button", { name: data.forkLabel })) await userEvent.type( diff --git a/hub/client/pages/replica-browse-page/types.ts b/hub/client/pages/replica-browse-page/types.ts index 387352ca..baaed266 100644 --- a/hub/client/pages/replica-browse-page/types.ts +++ b/hub/client/pages/replica-browse-page/types.ts @@ -46,5 +46,5 @@ export interface ReplicaBrowsePageProps { onMinimizedChange?: (minimized: boolean) => void onFrameLoad?: () => void onOpenApp?: (url: string) => void - authorizeHandoff?: () => Promise + authorizeHandoff?: () => Promise } diff --git a/hub/docs/frontend.md b/hub/docs/frontend.md index f8681068..7038bcdb 100644 --- a/hub/docs/frontend.md +++ b/hub/docs/frontend.md @@ -162,8 +162,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 cannot submit a creation handoff. -- **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. @@ -281,7 +281,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. -Signed-in members who can view a repository can compose a kickoff prompt in Create or from a saved template. Local, Entra, and GitHub read-only viewers use **Copy prompt**. Hosted Copilot handoffs require current GitHub write access to the selected repository. `GET /api/repositories/:repositoryId/create/permission` rechecks access before opening the continuation dialog. If that check denies write access or GitHub is unavailable, Hub keeps the brief and offers **Copy prompt** only when the viewer still has repository access. 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 00000000..a026b1b2 --- /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 4de2ba4d..4482e635 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 c2194244..99d93844 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 9fc8e91f..942e9152 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 e61e6c50..fc33b25c 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" @@ -201,7 +200,7 @@ it("keeps the catalog, screenshot, and routed preview on one successful default- const catalog = (await list.json()) as { templates: { id: string; screenshotUrl: string }[] } - expect(catalog).toMatchObject({ canCreate: true, submissionMode: "copy" }) + expect(catalog).toMatchObject({ canCreate: true, submissionMode: "copilot" }) const { templates } = catalog expect(templates.map(({ id }) => id)).toEqual(["default", "settings"]) expect(templates[1]).toMatchObject({ buildNumber: 2, category: "Administration", route }) @@ -213,7 +212,7 @@ it("keeps the catalog, screenshot, and routed preview on one successful default- template: { previewUrl: string } initialRoute: string } - expect(saved).toMatchObject({ canCreate: true, submissionMode: "copy" }) + expect(saved).toMatchObject({ canCreate: true, submissionMode: "copilot" }) const { template, initialRoute } = saved const preview = new URL(template.previewUrl) expect(preview.pathname).toBe(screenshot.pathname) @@ -253,62 +252,59 @@ it("keeps the catalog, screenshot, and routed preview on one successful default- }) }) -it("rechecks GitHub write permission when starting a Copilot handoff", async () => { +it("offers a visible reader a hosted handoff without granting listing management", async () => { await withRepository(async ({ read, permission }) => { - permission.mockResolvedValue("write") - expect(await (await read("/create/permission")).json()).toMatchObject({ canCreate: true }) expect(await (await read("/templates/default")).json()).toMatchObject({ canCreate: true, submissionMode: "copilot", template: { id: "default" }, }) - permission.mockResolvedValue("read") - expect(await (await read("/create/permission")).json()).toMatchObject({ canCreate: false }) - expect(await (await read("/templates/default")).json()).toMatchObject({ + 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: "copy", - template: { id: "default" }, + submissionMode: "copilot", }) - permission.mockRejectedValue(new GitHubProviderRequestError()) - const unavailable = await read("/create/permission") - expect(unavailable.status).toBe(503) - const copyPermission = (await unavailable.json()) as { error?: unknown; canCopy?: unknown } - expect(typeof copyPermission.error).toBe("string") - expect(copyPermission.canCopy).toBe(true) - const fallback = await read() - expect(fallback.status).toBe(200) - expect(await fallback.json()).toMatchObject({ canCreate: true, submissionMode: "copy" }) + expect(await (await read("/create/permission")).json()).toEqual({ canCreate: true }) }) }) -it.each(["read", "outage"] as const)( - "does not allow copy when repository access is revoked during a provider check ending in %s", - async (outcome) => { - await withRepository(async ({ repositoryId, read, permission }) => { - permission.mockImplementation(async () => { - await prisma.repositoryAccessGrant.deleteMany({ where: { repositoryId } }) - if (outcome === "outage") throw new GitHubProviderRequestError() - return "read" - }) +it("allows a visible viewer to start a handoff without checking GitHub permission", async () => { + await withRepository(async ({ read, permission }) => { + permission.mockRejectedValue(new Error("GitHub unavailable")) - const denied = await read("/create/permission") - expect(denied.status).toBe(404) - expect(await denied.json()).not.toHaveProperty("canCopy") - }) - }, -) + for (const path of ["/templates", "/templates/default"]) { + const response = await read(path) + expect(response.status).toBe(200) + expect(await response.json()).toMatchObject({ + canCreate: true, + submissionMode: "copilot", + }) + } + const handoff = await read("/create/permission") + expect(handoff.status).toBe(200) + expect(await handoff.json()).toEqual({ canCreate: true }) + expect(permission).not.toHaveBeenCalled() + }) +}) -it("lets an Entra viewer compose from the blank template but not hand off to Copilot", async () => { - await withRepository(async ({ read, permission }) => { - permission.mockResolvedValue("write") - const blank = await read("/templates/default") - expect(blank.status).toBe(200) - expect(await blank.json()).toMatchObject({ - canCreate: true, - submissionMode: "copy", +it("lets an Entra viewer start a Copilot handoff from the blank template", async () => { + await withRepository(async ({ read }) => { + for (const path of ["/templates", "/templates/default"]) { + const response = await read(path) + expect(response.status).toBe(200) + expect(await response.json()).toMatchObject({ + canCreate: true, + submissionMode: "copilot", + }) + } + expect(await (await read("/templates/default")).json()).toMatchObject({ template: { id: "default" }, }) - expect(await (await read("/create/permission")).json()).toMatchObject({ canCreate: false }) + expect(await (await read("/create/permission")).json()).toEqual({ canCreate: true }) }, "entra") }) @@ -318,6 +314,8 @@ it("conceals the composer and Copilot handoff from a viewer outside repository s permission.mockResolvedValue("write") expect((await read()).status).toBe(404) expect((await read("/templates/default")).status).toBe(404) - expect((await read("/create/permission")).status).toBe(404) + const denied = await read("/create/permission") + expect(denied.status).toBe(404) + expect(await denied.json()).not.toHaveProperty("canCopy") }) }) 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 00000000..8e28fe5d --- /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 88a3650a..af349d0b 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,16 +164,10 @@ export function templateRoutes( const snapshot = await load(viewer, repositoryId) if (!snapshot) return null const { repository, templates, build, local } = snapshot - const canHandOff = - !local && - (await canHandOffToCopilot(product, viewer, repositoryId).catch((error: unknown) => { - if (!(error instanceof GitHubProviderRequestError)) throw error - request.log?.warn("GitHub is unavailable for Copilot handoff. Offering prompt copy.") - return false - })) - if (!(await product.isRepositoryVisible(viewer, repositoryId))) return null - const submissionMode = canHandOff ? "copilot" : "copy" - const context = { repository, canCreate: true, submissionMode } + const canCreate = await canStartPrototypeSession(product, viewer, repositoryId) + if (!canCreate) return null + const submissionMode = local ? "copy" : "copilot" + const context = { repository, canCreate, submissionMode } if (!id) { return { ...context, @@ -212,26 +204,11 @@ export function templateRoutes( detail: read(true), permission: authorized( async (_request, viewer, repositoryId) => { - if (!(await product.isRepositoryVisible(viewer, repositoryId))) return null - try { - const canCreate = await canHandOffToCopilot(product, viewer, repositoryId) - return (await product.isRepositoryVisible(viewer, repositoryId)) ? { canCreate } : null - } catch (error) { - if (!(error instanceof GitHubProviderRequestError)) throw error - return (await product.isRepositoryVisible(viewer, repositoryId)) - ? { unavailable: true } - : null - } + if (!(await canStartPrototypeSession(product, viewer, repositoryId))) return null + return { canCreate: true } }, (response, result) => { - if ("unavailable" in result) { - response.status(503).json({ - error: "Hub could not check GitHub repository permissions.", - canCopy: true, - }) - } else { - response.json(result) - } + response.json(result) }, ), access: authorized(