Skip to content
Open
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
2 changes: 2 additions & 0 deletions apps/web/src/app/route-pages.messages.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,10 @@ import { defineMessages } from "@/i18n/messages";

/** Pages a route falls back to: the unknown address and the loading error. */
export const routePagesMessages = defineMessages("routePages", {
loadingLinger: "Loading Linger…",
notFoundTitle: "Page not found",
openMessages: "Open Messages",
goToLogin: "Go to Log in",
loadingError: "TeamHub loading error",
rooms: "Rooms",
roomNavigation: "Room navigation",
Expand Down
42 changes: 38 additions & 4 deletions apps/web/src/app/router.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ describe("Web app route contract", () => {
"rooms/:roomId",
"chat",
"profile",
"dashboard/:workItemId",
"dashboard/:workItemId?",
"documents/:documentId",
"settings",
"account",
Expand All @@ -87,23 +87,57 @@ describe("Web app route contract", () => {
);
});

it("keeps Work Item links and Room chat reachable", () => {
it("keeps Work Item links, bare Dashboard, and Room chat reachable", () => {
const routes = createAppRoutes(
new QueryClient(),
createTestTeamHubRuntime(),
);
expect(
matchRoutes(routes, "/t/tenant-a/dashboard")?.at(-1)?.route.path,
).toBe("*");
).toBe("dashboard/:workItemId?");
expect(
matchRoutes(routes, "/t/tenant-a/dashboard/work-item-a")?.at(-1)?.route
.path,
).toBe("dashboard/:workItemId");
).toBe("dashboard/:workItemId?");
expect(
matchRoutes(routes, "/t/tenant-a/rooms/room-a/chat")?.at(-1)?.route.path,
).toBe("chat");
});

it("redirects /t/:tenantId 401 failures to /login with reason=session-expired and return_to", async () => {
const runtime = createTestTeamHubRuntime();
runtime.server.on("GET", "/v0/session", () =>
teamHubErrorResponse(401, "UNAUTHENTICATED", "Sign in required"),
);
const queryClient = new QueryClient({
defaultOptions: { queries: { retry: false } },
});
const tenantLoader = createAppRoutes(queryClient, runtime).find(
(route) => route.path === "/t/:tenantId",
)!.loader as LoaderFunction;
let thrown: unknown;
try {
await tenantLoader({
context: new RouterContextProvider(),
params: { tenantId: "tenant-northstar" },
pattern: "/t/:tenantId",
request: new Request(
"http://localhost/t/tenant-northstar/dashboard?room=room-all",
),
url: new URL(
"http://localhost/t/tenant-northstar/dashboard?room=room-all",
),
});
} catch (error) {
thrown = error;
}
expect(thrown).toBeInstanceOf(Response);
expect((thrown as Response).headers.get("Location")).toBe(
`/login?reason=session-expired&return_to=${encodeURIComponent("/t/tenant-northstar/dashboard?room=room-all")}`,
);
queryClient.clear();
});

it("mounts My Documents, Shared with me, and Wiki below Library", () => {
const tenantRoute = createAppRoutes(
new QueryClient({ defaultOptions: { queries: { retry: false } } }),
Expand Down
35 changes: 26 additions & 9 deletions apps/web/src/app/router.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,6 @@ import {
type TeamHubClient,
} from "@/features/teamhub/teamhub-client";
import type { TeamHubRuntime } from "@/features/teamhub/teamhub-runtime";
import { commonMessages } from "@/i18n/common.messages";
import { translate } from "@/i18n/language";
import { useT } from "@/i18n/use-translation";
import {
Expand Down Expand Up @@ -150,8 +149,13 @@ export function createAppRoutes(
}),
path: "/login",
},
{ lazy: loadSharedDocumentPage, path: "/shared-documents" },
{
HydrateFallback: InitialAppLoading,
lazy: loadSharedDocumentPage,
path: "/shared-documents",
},
{
HydrateFallback: InitialAppLoading,
path: "/shared-room-history",
lazy: async () => {
const { SharedRoomHistoryPage } =
Expand All @@ -165,6 +169,7 @@ export function createAppRoutes(
},
{
ErrorBoundary: FullPageRouteErrorSurface,
HydrateFallback: InitialAppLoading,
lazy: () =>
authenticationOperation(
new AbortController().signal,
Expand Down Expand Up @@ -294,7 +299,7 @@ export function createAppRoutes(
createWorkItemDashboardRoute(
queryClient,
client,
"dashboard/:workItemId",
"dashboard/:workItemId?",
),
createWorkspaceRoute(),
{
Expand Down Expand Up @@ -337,7 +342,13 @@ export function createAppRoutes(
]);
} catch (error) {
request.signal.throwIfAborted();
redirectAuthenticationError(error, queryClient);
const current = new URL(request.url);
const returnTo = `${current.pathname}${current.search}`;
redirectAuthenticationError(
error,
queryClient,
`/login?reason=session-expired&return_to=${encodeURIComponent(returnTo)}`,
);
throw error;
}

Expand All @@ -355,7 +366,7 @@ export function createAppRoutes(
function createWorkItemDashboardRoute(
queryClient: QueryClient,
client: TeamHubClient,
path: "dashboard/:workItemId",
path: "dashboard/:workItemId?",
): RouteObject {
return {
ErrorBoundary: PanelRouteErrorSurface,
Expand Down Expand Up @@ -788,11 +799,11 @@ export function InitialAppLoading() {
return (
<main
aria-busy="true"
aria-label={t(commonMessages.loadingApp)}
aria-label={t(routePagesMessages.loadingLinger)}
className="flex min-h-dvh items-center justify-center gap-2 bg-app-canvas text-sm text-app-muted"
>
<Spinner />
{t(commonMessages.loadingRoom)}
{t(routePagesMessages.loadingLinger)}
</main>
);
}
Expand Down Expand Up @@ -820,10 +831,16 @@ function NotFoundRoute({ inShell = false }: { inShell?: boolean }) {
<h1 className="text-lg">{t(routePagesMessages.notFoundTitle)}</h1>
<Button
onClick={() => {
void navigate(tenantId ? `/t/${tenantId}/rooms` : "/");
void navigate(
inShell && tenantId ? `/t/${tenantId}/rooms` : "/login",
);
}}
>
{t(routePagesMessages.openMessages)}
{t(
inShell && tenantId
? routePagesMessages.openMessages
: routePagesMessages.goToLogin,
)}
</Button>
</main>
);
Expand Down
43 changes: 43 additions & 0 deletions apps/web/src/app/teamhub-authentication-runtime.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -226,4 +226,47 @@ describe("TeamHub authentication runtime", () => {
expect(navigate).toHaveBeenCalledWith("/", { replace: true });
stop();
});

it("redirects an unauthenticated root entry to /login without session-expired", () => {
const navigate = vi.fn();
const signals = createTeamHubAuthenticationSignals({
channelFactory: () => null,
});
const stop = startTeamHubAuthenticationRuntime({
currentLocation: () => ({ pathname: "/", search: "" }),
navigate,
queryClient: new QueryClient(),
signals,
});

signals.publish("authentication-required", "session-expired");

expect(navigate).toHaveBeenCalledWith("/login", { replace: true });
stop();
});

it("preserves a Tenant deep link when an authenticated session expires", () => {
const navigate = vi.fn();
const signals = createTeamHubAuthenticationSignals({
channelFactory: () => null,
});
const deepLink = "/t/tenant-northstar/dashboard?room=room-all";
const stop = startTeamHubAuthenticationRuntime({
currentLocation: () => ({
pathname: "/t/tenant-northstar/dashboard",
search: "?room=room-all",
}),
navigate,
queryClient: new QueryClient(),
signals,
});

signals.publish("authentication-required", "session-expired");

expect(navigate).toHaveBeenCalledWith(
`/login?reason=session-expired&return_to=${encodeURIComponent(deepLink)}`,
{ replace: true },
);
stop();
});
});
4 changes: 4 additions & 0 deletions apps/web/src/app/teamhub-authentication-runtime.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,10 @@ export function startTeamHubAuthenticationRuntime({
const invalidate = (reason: TeamHubAuthenticationReason) => {
clearLocalAuthenticatedState(queryClient);
const location = currentLocation?.();
if (location?.pathname === "/") {
void navigate("/login", { replace: true });
return;
}
const returnTo = location
? safeAuthenticationReturnTo(
location.pathname === "/login"
Expand Down
21 changes: 19 additions & 2 deletions apps/web/src/app/teamhub-router.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -613,7 +613,7 @@ describe("TeamHub routes", () => {
expect(screen.getByRole("button", { name: "Open Messages" })).toBeVisible();
});

it("renders the in-shell not-found page for bare /t/:tenantId/dashboard", async () => {
it("renders the Dashboard page for bare /t/:tenantId/dashboard", async () => {
const runtime = createTestTeamHubRuntime();
const queryClient = testQueryClient();
const router = createMemoryRouter(createAppRoutes(queryClient, runtime), {
Expand All @@ -622,10 +622,27 @@ describe("TeamHub routes", () => {

renderApp(queryClient, runtime, router);

expect(
await screen.findByRole("heading", { name: "Fixture Dashboard" }),
).toBeVisible();
});

it("offers Go to Log in on signed-out unknown paths", async () => {
const runtime = createTestTeamHubRuntime();
const queryClient = testQueryClient();
const router = createMemoryRouter(createAppRoutes(queryClient, runtime), {
initialEntries: ["/no-such-page"],
});

renderApp(queryClient, runtime, router);

expect(
await screen.findByRole("heading", { name: "Page not found" }),
).toBeVisible();
expect(screen.getByRole("button", { name: "Open Messages" })).toBeVisible();
expect(screen.getByRole("button", { name: "Go to Log in" })).toBeVisible();
expect(
screen.queryByRole("button", { name: "Open Messages" }),
).not.toBeInTheDocument();
});

it("preloads the Room chat chunk from /, /t/:tenantId/rooms, and /t/:tenantId/rooms/:roomId loaders", async () => {
Expand Down
5 changes: 3 additions & 2 deletions apps/web/src/features/auth/auth.messages.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,9 @@ export const authMessages = defineMessages("auth", {
showPassword: "Show password",
hidePassword: "Hide password",
signIn: "Sign in",
logIn: "Log in",
working: "Working...",
invalidCredentials:
"Incorrect email or password. Check your credentials and try again.",
accessHelp: "Need access or a password reset? Contact your workspace admin.",
artTitleFirst: "Your personal AI.",
artTitleSecond: "A step ahead.",
artLede:
Expand Down
10 changes: 10 additions & 0 deletions apps/web/src/features/auth/authentication-return-to.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,20 @@ const setup = "/connect-computer?code_challenge=challenge&state=state";
it("preserves a same-origin Local Computer setup path after authentication", () => {
expect(safeAuthenticationReturnTo(setup)).toBe(setup);
});
it("preserves a same-origin Tenant Space path with query parameters", () => {
expect(
safeAuthenticationReturnTo("/t/tenant-northstar/dashboard?room=room-all"),
).toBe("/t/tenant-northstar/dashboard?room=room-all");
expect(
safeAuthenticationReturnTo("/t/tenant-northstar/rooms/room-all/chat"),
).toBe("/t/tenant-northstar/rooms/room-all/chat");
});
it.each([
`https://evil.example${setup}`,
`//evil.example${setup}`,
"//evil.example/t/tenant-northstar/rooms",
`${setup}#token`,
"/t/tenant-northstar/rooms#fragment",
"/connect-computer",
"/rooms/room_private",
])("rejects unsafe or unsupported return paths: %s", (value) => {
Expand Down
9 changes: 7 additions & 2 deletions apps/web/src/features/auth/authentication-return-to.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
// Destination for signed-in users leaving the login page: only allowlisted local setup paths are accepted; anything else goes to the home page.
// Destination for signed-in users leaving the login page: only allowlisted
// local setup and Space paths are accepted; anything else goes to the home page.
export function authenticatedLoginDestination(
searchParams: URLSearchParams,
): string {
Expand All @@ -9,6 +10,7 @@ export function safeAuthenticationReturnTo(
value: string | null,
): string | null {
if (!value || value.length > 2_048) return null;
if (!value.startsWith("/") || value.startsWith("//")) return null;
let target: URL;
try {
target = new URL(value, "http://localhost");
Expand All @@ -18,5 +20,8 @@ export function safeAuthenticationReturnTo(
if (target.origin !== "http://localhost" || target.hash !== "") return null;
const computerSetup =
target.pathname === "/connect-computer" && target.search.length > 1;
return computerSetup ? `${target.pathname}${target.search}` : null;
const tenantSpace = /^\/t\/[^/]+(?:\/.*)?$/u.test(target.pathname);
return computerSetup || tenantSpace
? `${target.pathname}${target.search}`
: null;
}
7 changes: 6 additions & 1 deletion apps/web/src/features/auth/teamhub-authentication.ts
Original file line number Diff line number Diff line change
Expand Up @@ -188,6 +188,11 @@ export function useTeamHubAuthentication(input: {
}

function readAuthenticationError(error: unknown) {
if (error instanceof TeamHubError) return error.message;
if (error instanceof TeamHubError) {
if (error.code === "INVALID_CREDENTIALS") {
return translate(m.invalidCredentials);
}
return error.message;
}
return translate(m.teamHubUnreachable);
}
Loading