diff --git a/hub/client/application/hub/canvas-connections/contract.ts b/hub/client/application/hub/canvas-connections/contract.ts index d84a98d2f..73e49a127 100644 --- a/hub/client/application/hub/canvas-connections/contract.ts +++ b/hub/client/application/hub/canvas-connections/contract.ts @@ -19,6 +19,7 @@ export const canvasApprovalSchema = z export const canvasConnectionsSchema = z .object({ + viewerId: z.uuid(), connections: z.array( z .object({ diff --git a/hub/client/application/hub/routes/canvas-connections/index.tsx b/hub/client/application/hub/routes/canvas-connections/index.tsx index 987ea8d66..68f023a3f 100644 --- a/hub/client/application/hub/routes/canvas-connections/index.tsx +++ b/hub/client/application/hub/routes/canvas-connections/index.tsx @@ -1,4 +1,4 @@ -import { redirect, useLocation, useOutletContext } from "react-router" +import { redirect, useLocation, useOutletContext, useRevalidator } from "react-router" import { z } from "zod" import { CanvasConnectionScreen } from "@application/hub/canvas-connections" @@ -11,6 +11,7 @@ import { import type { WorkspaceResponse } from "@application/hub/contracts/types" import { ApiRequestError } from "@application/hub/requests/api-request-error" import { requestJson } from "@application/hub/requests/request-json" +import { RouteFeedback } from "@application/hub/route-feedback" import { selectWorkspaceRepository } from "@application/hub/view-models/select-workspace-repository" import type { CanvasPairingsPageData } from "@pages/canvas-pairings-page/types" @@ -23,20 +24,22 @@ export const handle = { signedOutEntry: "canvas", } satisfies WorkspaceRouteHandle +type ConnectionsData = { + viewerId: string + page: Extract +} + export async function clientLoader({ request, -}: Route.ClientLoaderArgs): Promise | null> { +}: Route.ClientLoaderArgs): Promise { const url = new URL(request.url) try { - const { connections } = await requestJson( + const { viewerId, connections } = await requestJson( new URL("/api/canvas/connections", url), canvasConnectionsSchema, { signal: request.signal }, ) - return { + const page: ConnectionsData["page"] = { kind: "connections", productName: "Replica Hub", pageTitle: "Canvas connections", @@ -59,6 +62,7 @@ export async function clientLoader({ revokePath: `${canvasConnectionsPath}/${id}`, })), } + return { viewerId, page } } catch (error) { if (error instanceof ApiRequestError && error.status === 401) return null throw error @@ -94,12 +98,26 @@ export function meta() { export default function CanvasConnections({ loaderData }: Route.ComponentProps) { const workspace = useOutletContext() const { search } = useLocation() + const revalidator = useRevalidator() + if (loaderData && workspace && loaderData.viewerId !== workspace.viewer.id) { + return ( + void revalidator.revalidate()} + retrying={revalidator.state !== "idle"} + /> + ) + } + const repository = workspace && selectWorkspaceRepository(workspace, new URLSearchParams(search)) const page = loaderData && workspace ? { - ...loaderData, - backPath: repository ? `/repositories/${repository.id}` : loaderData.backPath, + ...loaderData.page, + backPath: repository ? `/repositories/${repository.id}` : loaderData.page.backPath, } : null return ( diff --git a/hub/client/application/hub/routes/real-workspace-navigation.test.tsx b/hub/client/application/hub/routes/real-workspace-navigation.test.tsx index ae9d4409e..49f0f275f 100644 --- a/hub/client/application/hub/routes/real-workspace-navigation.test.tsx +++ b/hub/client/application/hub/routes/real-workspace-navigation.test.tsx @@ -18,6 +18,8 @@ import { HubThemeProvider } from "@hooks/use-hub-theme" import routes from "../routes" +const workspaceViewerId = "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa" + type RouteModule = { default?: ComponentType<{ loaderData: unknown }> clientLoader?: (args: LoaderFunctionArgs & { serverLoader: () => Promise }) => unknown @@ -66,10 +68,17 @@ function applicationRoute(entry: RouteConfigEntry): RouteObject { : { ...common, children: entry.children?.map(applicationRoute) } } -async function renderApplication(path: string, handlers: Parameters) { +async function renderApplication( + path: string, + handlers: Parameters, + onMockedResponse?: (request: Request) => void, +) { vi.stubEnv("MODE", "development") vi.stubEnv("DEV", true) const server = setupServer(...handlers) + if (onMockedResponse) { + server.events.on("response:mocked", ({ request }) => onMockedResponse(request)) + } server.listen({ onUnhandledRequest: "error" }) onTestFinished(() => server.close()) window.history.replaceState(null, "", path) @@ -109,9 +118,8 @@ function workspaceApi( login: provider === "local" ? "local-developer" : "octocat", name: provider === "local" ? "Local developer" : "The Octocat", } - const userId = "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa" const workspace = { - viewer: { id: userId, ...user, avatarUrl: null }, + viewer: { id: workspaceViewerId, ...user, avatarUrl: null }, capabilities: { createPrototypes: false, reviewPrototypes: false, @@ -126,7 +134,7 @@ function workspaceApi( json("/api/auth/session", { authenticated: true, membershipId: "bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb", - userId, + userId: workspaceViewerId, ...user, role, reviewInboxAvailable, @@ -847,7 +855,7 @@ describe("real workspace navigation", () => { unreadCount: countOnly ? 3 : 1, }) }), - json("/api/canvas/connections", { connections: [] }), + json("/api/canvas/connections", { viewerId: workspaceViewerId, connections: [] }), http.get(`${window.location.origin}/api${galleryPath}/analytics`, () => HttpResponse.json({ error: "Repository analytics is unavailable." }, { status: 403 }), ), @@ -1036,6 +1044,72 @@ describe("real workspace navigation", () => { expect(screen.queryByRole("link", { name: "Inbox, 5 unread" })).not.toBeInTheDocument() }) + it.each(["workspace", "connections"] as const)( + "hides mismatched Canvas connections and allows retry when the %s response arrives last", + async (lastRead) => { + const viewerId = "cccccccc-cccc-4ccc-8ccc-cccccccccccc" + const mismatchedRepository = "team/palette" + const currentRepository = "team/garden" + const firstResponse = deferResponse() + const lastResponse = deferResponse() + const firstPath = lastRead === "workspace" ? "/api/canvas/connections" : "/api/workspace" + let enteringConnections = false + let retrying = false + const router = await renderApplication( + "/repositories", + [ + ...workspaceApi([], { + async respondToWorkspace(_request, workspace) { + if (enteringConnections && lastRead === "workspace") await lastResponse.pending + return HttpResponse.json( + retrying + ? { ...workspace, viewer: { ...workspace.viewer, id: viewerId, login: "mona" } } + : workspace, + ) + }, + }), + http.get(`${window.location.origin}/api/canvas/connections`, async () => { + if (lastRead === "connections") await lastResponse.pending + return HttpResponse.json({ + viewerId, + connections: [ + { + id: retrying ? 2 : 1, + repository: retrying ? currentRepository : mismatchedRepository, + expiresAt: "2026-11-30T12:00:00Z", + inactiveAt: null, + }, + ], + }) + }), + ], + (request) => { + if (enteringConnections && new URL(request.url).pathname === firstPath) { + firstResponse.release() + } + }, + ) + + enteringConnections = true + await act(async () => { + const navigation = router.navigate("/canvas/connections") + await firstResponse.pending + lastResponse.release() + await navigation + }) + + expect(screen.queryByText(mismatchedRepository)).not.toBeInTheDocument() + expect(screen.queryByRole("button", { name: "Revoke" })).not.toBeInTheDocument() + const retry = within(screen.getByRole("alert")).getByRole("button", { name: "Try again" }) + retrying = true + fireEvent.click(retry) + + expect(await screen.findByText(currentRepository)).toBeVisible() + expect(screen.getByRole("button", { name: "Revoke" })).toBeVisible() + expect(screen.queryByText(mismatchedRepository)).not.toBeInTheDocument() + }, + ) + it("keeps the Canvas connections return destination on a signed-out deep link", async () => { const path = "/canvas/connections?repositoryId=22222222-2222-4222-8222-222222222222" const router = await renderApplication(path, [ diff --git a/hub/docs/prototype-canvas.md b/hub/docs/prototype-canvas.md index 7cf6e28e5..2f18356d8 100644 --- a/hub/docs/prototype-canvas.md +++ b/hub/docs/prototype-canvas.md @@ -12,7 +12,7 @@ Select **Connect to the hub** in the Replica canvas. Sign in if Hub asks, then c Hub checks that the approving identity can read the repository, and checks access again when the extension claims, uses, or renews the connection. In local development, sign in as the fixed local developer and start the canvas from its matching checkout under `.local/prototypes/`. Hub pairs the checkout as `local/`. A paired repository need not have a discovered branch. -Open **Canvas connections** from the Hub navigation or at `/canvas/connections`. It lists your own active connections for the current identity. **Revoke** invalidates both the access and renewal credential without signing you out of Hub. +Open **Canvas connections** from the Hub navigation or at `/canvas/connections`. It lists your own active connections for the current identity. If the connections and navigation load for different accounts, Hub hides the list. Select **Try again** to load connections for the current account. **Revoke** invalidates both the access and renewal credential without signing you out of Hub. The extension uses version `1` of `/api/canvas`. It keeps the device, access, and refresh secrets in its private Node store; Hub stores only their digests. No secret is included in the approval URL or browser responses. Access tokens last up to seven days. Renewing one rotates the access token without extending the connection's 30-day inactivity deadline. Only interactive use extends that deadline. Ending all Hub sessions also invalidates Canvas credentials. diff --git a/hub/server/domains/canvas/connections/index.ts b/hub/server/domains/canvas/connections/index.ts index e1acc9875..21528cce4 100644 --- a/hub/server/domains/canvas/connections/index.ts +++ b/hub/server/domains/canvas/connections/index.ts @@ -291,7 +291,11 @@ export function createCanvasConnections( return database.$transaction(async (transaction) => { const viewer = await authority.current(transaction, browser.viewer, browser) const owner = viewer && canvasAuthorityReference(viewer) - return owner ? listCanvasGrants(transaction, owner) : null + if (!viewer || !owner) return null + return { + viewerId: viewer.userId, + connections: await listCanvasGrants(transaction, owner), + } }) }, diff --git a/hub/server/repositories/canvas/authority/index.ts b/hub/server/repositories/canvas/authority/index.ts index d0a9cf985..4d7598065 100644 --- a/hub/server/repositories/canvas/authority/index.ts +++ b/hub/server/repositories/canvas/authority/index.ts @@ -68,6 +68,7 @@ export async function readCanvasAuthority( sessionProvider: identity.provider, issuer: identity.issuer, subject: identity.subject, + userId: identity.userId, viewerId: identity.user.canvasId, login, githubAccessRevision: accessState?.revision ?? null, diff --git a/hub/server/routes/api/canvas/extension.db.test.ts b/hub/server/routes/api/canvas/extension.db.test.ts index e0588dc0d..7ea1d512d 100644 --- a/hub/server/routes/api/canvas/extension.db.test.ts +++ b/hub/server/routes/api/canvas/extension.db.test.ts @@ -264,8 +264,12 @@ it("pairs and renews the unchanged extension using local sign-in, then stops at ).status, ).toBe(401) + const restoredSession = await browser("/api/auth/session") + expect(restoredSession.status).toBe(200) + const { userId } = z.object({ userId: z.uuid() }).parse(await restoredSession.json()) const list = z .object({ + viewerId: z.uuid(), connections: z.array( z .object({ @@ -279,6 +283,7 @@ it("pairs and renews the unchanged extension using local sign-in, then stops at }) .strict() .parse(await (await browser("/api/canvas/connections")).json()) + expect(list.viewerId).toBe(userId) expect(list.connections.map(({ repository }) => repository)).toEqual(["local/example"]) const id = list.connections[0]!.id const original = await prisma.canvasGrant.findUniqueOrThrow({ where: { id } }) @@ -289,7 +294,10 @@ it("pairs and renews the unchanged extension using local sign-in, then stops at expect(renewed.inactiveAt).toEqual(original.inactiveAt) expect((await browser(`/api/canvas/connections/${id}`, "DELETE")).status).toBe(204) - expect(await (await browser("/api/canvas/connections")).json()).toEqual({ connections: [] }) + expect(await (await browser("/api/canvas/connections")).json()).toEqual({ + viewerId: userId, + connections: [], + }) expect(await extension.status({ register: false })).toMatchObject({ state: "disconnected" }) await expect( extension.request("/api/canvas/decision-model/evaluations", { diff --git a/hub/server/routes/api/canvas/index.ts b/hub/server/routes/api/canvas/index.ts index be778d988..ace9b8458 100644 --- a/hub/server/routes/api/canvas/index.ts +++ b/hub/server/routes/api/canvas/index.ts @@ -167,10 +167,11 @@ export function canvasRoutes( "/connections", handler(async (request, response, services) => { const session = await browser(request, services) - const connections = session && (await services.connections.list(session)) - if (!connections) return browserSessionRequired(response) + const result = session && (await services.connections.list(session)) + if (!result) return browserSessionRequired(response) response.json({ - connections: connections.map(({ id, repository, expiresAt, inactiveAt }) => ({ + viewerId: result.viewerId, + connections: result.connections.map(({ id, repository, expiresAt, inactiveAt }) => ({ id, repository: repository.nameWithOwner, expiresAt,