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
1 change: 1 addition & 0 deletions hub/.devcontainer/compose.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ services:
environment:
DATABASE_URL: postgresql://replica:replica@db:5432/replica
TEST_DATABASE_URL: postgresql://replica:replica@db:5432/postgres
REPLICA_DEVCONTAINER: "true"
depends_on:
db:
condition: service_healthy
Expand Down
4 changes: 2 additions & 2 deletions hub/AGENTS.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# Working on Replica Hub

Hub is being rebuilt in TypeScript. The app starts locally, but its product features are not built yet. Read the [root instructions](../AGENTS.md), [shared guides](../docs/README.md), and [Hub documentation](docs/README.md) before editing.
Hub is being rebuilt in TypeScript. Read the [root instructions](../AGENTS.md), [shared guides](../docs/README.md), and [Hub documentation](docs/README.md) before editing.

- [Architecture](docs/architecture.md) explains the chosen tools, what works, and what has not been built.
- [Code architecture conventions](docs/backend-architecture.md) define repositories, integrations, utilities, domains, and allowed imports.
Expand All @@ -10,7 +10,7 @@ Hub is being rebuilt in TypeScript. The app starts locally, but its product feat
- [Development](docs/development.md) and [testing](docs/testing-and-operations.md) own local and CI commands.
- [Storybook](docs/storybook.md#ui-changes-and-pull-request-evidence) owns presentation coverage, cleanup, and PR screenshots.

Run Node commands from `hub/`, locally or inside the devcontainer. PostgreSQL and Prisma support configured GitHub authentication, administrator enrollment, and Hub sessions; see [authentication](docs/authentication.md). Prototype product models and APIs are not built. Agree on the design before adding product models, permissions, deployment choices, or product API routes.
Run Node commands from `hub/`, locally or inside the devcontainer. PostgreSQL and Prisma support configured GitHub authentication, administrator enrollment, Hub sessions, and a seeded read-only prototype index; see [authentication](docs/authentication.md). Other prototype APIs and repository-specific permissions are not built. Agree on the design before adding more product models, permissions, deployment choices, or product API routes.

`npm test` does not require PostgreSQL. Use `npm run test:database` for `.db.test.ts` and `.db.test.tsx` cases in Node.js or jsdom. Follow the database isolation and reset rules in [testing](docs/testing-and-operations.md).

Expand Down
4 changes: 2 additions & 2 deletions hub/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

Hub is being rebuilt on `build/hub/new` using TypeScript, Express, React, Vite, and Vitest. This branch lets contributors start the new app locally. It is not ready to replace the existing Hub.

The API has liveness and readiness routes. React Router connects the retained frontend pages for local exploration. Product API routes are not implemented.
The API has liveness, readiness, and read-only repository index routes. React Router also connects the retained frontend pages to local mock data.

Contributors can use PostgreSQL and Prisma locally or in the devcontainer. The backend provides:

Expand All @@ -11,7 +11,7 @@ Contributors can use PostgreSQL and Prisma locally or in the devcontainer. The b
- Explicit server-side [telemetry spans](docs/telemetry.md).
- A [WebSocket foundation](docs/websockets.md) that rejects upgrades until application access checks are supplied.

Persisted prototype data and live multi-user reviews are not implemented.
The index can show seeded prototype records. Repository discovery, product editing, and live multi-user reviews are not implemented.

The [production runtime](docs/deployment.md) packages the frontend, API, and workers in one image, with a separate release setup script.

Expand Down
8 changes: 7 additions & 1 deletion hub/client/application/hub/contracts/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ export const userSchema = z.object({
login: z.string().min(1),
name: z.string().nullable(),
avatarUrl: httpUrl.nullable(),
provider: z.string().min(1).optional(),
})

export const repositorySchema = z.object({
Expand Down Expand Up @@ -83,7 +84,12 @@ export const workspaceResponseSchema = z.object({

export const repositoryResponseSchema = z.object({
repository: repositorySchema,
prototypes: z.array(prototypeSchema),
prototypes: z.array(
prototypeSchema.extend({
authorId: z.string().nullable().optional(),
authorLogin: z.string().min(1).nullable(),
}),
),
pagination: paginationSchema,
authors: z.array(userSchema),
})
Expand Down
4 changes: 2 additions & 2 deletions hub/client/application/hub/mocks/pagination.test.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { setupServer } from "msw/node"
import { describe, expect, it, onTestFinished, vi } from "vitest"

import type { PrototypeRecord } from "../contracts/types"
import type { RepositoryResponse } from "../contracts/types"
import { getAuthors } from "../requests/get-authors"
import { getBuildHistory } from "../requests/get-build-history"
import { getRepository } from "../requests/get-repository"
Expand All @@ -23,7 +23,7 @@ describe("mock collection pagination", () => {

expect(first.pagination.pageSize).toBe(24)
expect(first.pagination.totalCount).toBeGreaterThan(48)
const records: PrototypeRecord[] = [...first.prototypes]
const records: RepositoryResponse["prototypes"] = [...first.prototypes]
for (let page = 2; page <= first.pagination.pageCount; page += 1) {
const next = await getRepository(new Request(`${request.url}?page=${page}`), "2001")
expect(next.pagination).toMatchObject({
Expand Down
17 changes: 13 additions & 4 deletions hub/client/application/hub/root.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import {
Outlet,
Scripts,
ScrollRestoration,
redirect,
useRevalidator,
useFetcher,
useFetchers,
Expand All @@ -19,7 +20,6 @@ import type { Route } from "./+types/root"
import type { SessionResponse } from "./session-contracts/types"
import { DevelopmentTools } from "./development-tools"
import { isAuthenticationRoute } from "./is-authentication-route"
import { isAdministratorRoute } from "./is-administrator-route"
import { HubNavigation } from "./hub-navigation"
import { ApiContractError } from "./requests/api-contract-error"
import { ApiRequestError } from "./requests/api-request-error"
Expand All @@ -32,7 +32,7 @@ import "./styles.css"

export async function clientLoader({
request,
}: Pick<Route.ClientLoaderArgs, "request">): Promise<SessionResponse> {
}: Pick<Route.ClientLoaderArgs, "request">): Promise<SessionResponse | Response> {
if (isAuthenticationRoute(request)) {
// The public auth shell restores its own session without claiming product permissions.
return {
Expand All @@ -45,13 +45,22 @@ export async function clientLoader({
},
}
}
if (isAdministratorRoute(request) && !(import.meta.env.DEV && import.meta.env.MODE === "mock")) {
const session = await getCurrentHubSession(request)
if (!(import.meta.env.DEV && import.meta.env.MODE === "mock")) {
let session
try {
session = await getCurrentHubSession(request)
} catch (error) {
if (error instanceof ApiRequestError && (error.status === 401 || error.status === 404)) {
return redirect("/")
}
throw error
}
return {
viewer: {
id: session.userId,
login: session.login,
name: session.name,
provider: session.provider,
avatarUrl: null,
},
capabilities: {
Expand Down
30 changes: 25 additions & 5 deletions hub/client/application/hub/routes/home/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,17 +3,36 @@ import { redirect, useLocation } from "react-router"
import { RepositoriesIndexPage } from "@pages/repositories-index-page"
import { HubApplication } from "@application/hub-application"
import { isAuthenticationRoute } from "@application/hub/is-authentication-route"
import { ApiRequestError } from "@application/hub/requests/api-request-error"
import { getCurrentHubSession } from "@application/hub/requests/get-current-hub-session"
import { getSession } from "@application/hub/requests/get-session"
import { getWorkspace } from "@application/hub/requests/get-workspace"
import { workspaceNavigation } from "@application/hub/view-models/workspace-navigation"

import type { Route } from "./+types/index"

export async function clientLoader({ request }: Pick<Route.ClientLoaderArgs, "request">) {
if (isAuthenticationRoute(request)) return null
const session = await getSession(request)
if (!session.viewer) throw redirect("/sign-in")
const workspace = await getWorkspace(request)
const mock = import.meta.env.DEV && import.meta.env.MODE === "mock"
if (mock) {
const session = await getSession(request)
if (!session.viewer) throw redirect("/sign-in")
} else if (isAuthenticationRoute(request)) {
try {
await getCurrentHubSession(request)
} catch (error) {
if (error instanceof ApiRequestError && (error.status === 401 || error.status === 404)) {
return null
}
throw error
}
}
let workspace
try {
workspace = await getWorkspace(request)
} catch (error) {
if (!mock && error instanceof ApiRequestError && error.status === 401) throw redirect("/")
throw error
}
const firstRepository = workspace.repositories[0]
if (firstRepository) throw redirect(`/repositories/${firstRepository.id}`)
return workspace
Expand All @@ -22,10 +41,11 @@ export async function clientLoader({ request }: Pick<Route.ClientLoaderArgs, "re
export default function Home({ loaderData }: Pick<Route.ComponentProps, "loaderData">) {
const location = useLocation()
if (loaderData === null) return <HubApplication />
const real = !(import.meta.env.DEV && import.meta.env.MODE === "mock")
return (
<RepositoriesIndexPage
data={{
...workspaceNavigation(loaderData, null, new URLSearchParams(location.search)),
...workspaceNavigation(loaderData, null, new URLSearchParams(location.search), real),
repository: null,
}}
/>
Expand Down
71 changes: 53 additions & 18 deletions hub/client/application/hub/routes/real-auth-flow.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ describe("Real authentication route integration", () => {
action: "/api/auth/entra/start",
},
{
label: "restored home in a production build, even with mock mode selected",
label: "restored empty workspace in a production build, even with mock mode selected",
path: "/",
mode: "mock",
dev: false,
Expand Down Expand Up @@ -106,7 +106,7 @@ describe("Real authentication route integration", () => {
action: "/api/auth/entra/admin-enrollment/start",
},
])(
"connects $label to the real session shell and leaves its POST native",
"connects $label to real authentication and leaves its POST native",
async ({ path, mode, dev, authenticated, providers, button, action }) => {
vi.stubEnv("MODE", mode)
vi.stubEnv("DEV", dev)
Expand All @@ -128,6 +128,24 @@ describe("Real authentication route integration", () => {
})
: new HttpResponse(null, { status: 401 }),
),
http.get(`${window.location.origin}/api/workspace`, () =>
HttpResponse.json({
viewer: {
id: "22222222-2222-4222-8222-222222222222",
provider: "github",
login: "octocat",
name: "The Octocat",
avatarUrl: null,
},
repositories: [],
capabilities: {
createPrototypes: false,
reviewPrototypes: false,
manageSharing: false,
administerHub: true,
},
}),
),
)
server.events.on("request:start", ({ request }) => {
requests.push(`${request.method} ${new URL(request.url).pathname}`)
Expand All @@ -153,21 +171,30 @@ describe("Real authentication route integration", () => {
</HubThemeProvider>,
)

const submit = await screen.findByRole("button", { name: button })
if (authenticated) {
expect(
await screen.findByRole("heading", { name: "No repositories available" }),
).toBeInTheDocument()
fireEvent.click(screen.getByRole("button", { name: "Account menu for @octocat" }))
}
const submit = await screen.findByRole(authenticated ? "menuitem" : "button", {
name: button,
})
const allowedRequests = authenticated
? ["GET /api/auth/session", "GET /api/workspace"]
: ["GET /api/auth/providers", "GET /api/auth/session"]
await vi.waitFor(() => {
expect(requests).toEqual(
expect.arrayContaining(["GET /api/auth/providers", "GET /api/auth/session"]),
)
expect(requests).toEqual(expect.arrayContaining(allowedRequests))
expect(router.state.initialized).toBe(true)
expect(router.state.navigation.state).toBe("idle")
})
expect(
requests.every((request) =>
["GET /api/auth/providers", "GET /api/auth/session"].includes(request),
),
).toBe(true)
expect(requests.every((request) => allowedRequests.includes(request))).toBe(true)
expect(router.state.location.pathname).toBe(path)
const form = submit instanceof HTMLButtonElement ? submit.form : submit.closest("form")
const form = authenticated
? document.querySelector<HTMLFormElement>(`form[action="${action}"]`)
: submit instanceof HTMLButtonElement
? submit.form
: submit.closest("form")
if (!form) throw new Error("The authentication control must submit a native form.")
expect(form.method).toBe("post")
const submitAction =
Expand All @@ -184,17 +211,25 @@ describe("Real authentication route integration", () => {
const submitEvent = new SubmitEvent("submit", {
bubbles: true,
cancelable: true,
submitter: submit,
submitter: authenticated ? null : submit,
})
expect(form.dispatchEvent(submitEvent)).toBe(true)

expect(router.state.location.pathname).toBe(path)
expect(screen.getByRole("button", { name: button })).toBeInTheDocument()
expect(
requests.every((request) =>
["GET /api/auth/providers", "GET /api/auth/session"].includes(request),
),
).toBe(true)
screen.getByRole(authenticated ? "menuitem" : "button", { name: button }),
).toBeInTheDocument()
expect(requests.every((request) => allowedRequests.includes(request))).toBe(true)
if (authenticated) {
await act(async () => {
await router.navigate("/repositories")
})
expect(router.state.location.pathname).toBe("/repositories")
expect(
screen.getByRole("heading", { name: "No repositories available" }),
).toBeInTheDocument()
expect(requests.every((request) => allowedRequests.includes(request))).toBe(true)
}
},
15_000,
)
Expand Down
Loading
Loading