Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ export const canvasApprovalSchema = z

export const canvasConnectionsSchema = z
.object({
viewerId: z.uuid(),
connections: z.array(
z
.object({
Expand Down
36 changes: 27 additions & 9 deletions hub/client/application/hub/routes/canvas-connections/index.tsx
Original file line number Diff line number Diff line change
@@ -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"
Expand All @@ -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"

Expand All @@ -23,20 +24,22 @@ export const handle = {
signedOutEntry: "canvas",
} satisfies WorkspaceRouteHandle

type ConnectionsData = {
viewerId: string
page: Extract<CanvasPairingsPageData, { kind: "connections" }>
}

export async function clientLoader({
request,
}: Route.ClientLoaderArgs): Promise<Extract<
CanvasPairingsPageData,
{ kind: "connections" }
> | null> {
}: Route.ClientLoaderArgs): Promise<ConnectionsData | null> {
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",
Expand All @@ -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
Expand Down Expand Up @@ -94,12 +98,26 @@ export function meta() {
export default function CanvasConnections({ loaderData }: Route.ComponentProps) {
const workspace = useOutletContext<WorkspaceResponse | null>()
const { search } = useLocation()
const revalidator = useRevalidator()
if (loaderData && workspace && loaderData.viewerId !== workspace.viewer.id) {
return (
<RouteFeedback
kind="error"
heading="Canvas connections unavailable"
description="Your Hub account changed while loading connections. Try again to see your connections."
embedded
Comment on lines +104 to +108
onRetry={() => 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 (
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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<never> }) => unknown
Expand Down Expand Up @@ -66,10 +68,17 @@ function applicationRoute(entry: RouteConfigEntry): RouteObject {
: { ...common, children: entry.children?.map(applicationRoute) }
}

async function renderApplication(path: string, handlers: Parameters<typeof setupServer>) {
async function renderApplication(
path: string,
handlers: Parameters<typeof setupServer>,
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)
Expand Down Expand Up @@ -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,
Expand All @@ -126,7 +134,7 @@ function workspaceApi(
json("/api/auth/session", {
authenticated: true,
membershipId: "bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb",
userId,
userId: workspaceViewerId,
...user,
role,
reviewInboxAvailable,
Expand Down Expand Up @@ -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 }),
),
Expand Down Expand Up @@ -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, [
Expand Down
2 changes: 1 addition & 1 deletion hub/docs/prototype-canvas.md
Original file line number Diff line number Diff line change
Expand Up @@ -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/<directory-name>`. 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.

Expand Down
6 changes: 5 additions & 1 deletion hub/server/domains/canvas/connections/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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),
}
})
},

Expand Down
1 change: 1 addition & 0 deletions hub/server/repositories/canvas/authority/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
10 changes: 9 additions & 1 deletion hub/server/routes/api/canvas/extension.db.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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({
Expand All @@ -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 } })
Expand All @@ -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", {
Expand Down
7 changes: 4 additions & 3 deletions hub/server/routes/api/canvas/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
Loading