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
4 changes: 3 additions & 1 deletion apps/frontend/AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ Import direction is one-way and must stay that way: `api.ts` ← `authClient.ts`

**No Cognito SDK on the client.** The browser only ever talks to the backend's `/auth/*` routes; the auth lambda does the Cognito work.

**Session.** Tokens (`branch_access_token` / `branch_id_token` / `branch_refresh_token`) live in localStorage, owned exclusively by `src/lib/authTokens.ts`. `grep -rn "branch_access_token" src/` must only ever match that file.
**Session.** Tokens (`branch_access_token` / `branch_id_token` / `branch_refresh_token`) live in localStorage, and the staff impersonation session id (`branch_impersonation_session`) in sessionStorage, all owned exclusively by `src/lib/authTokens.ts`. `grep -rn "branch_access_token" src/` must only ever match that file.

**Identity comes from `GET /auth/me`, never from decoding a token.** `is_admin` lives only in Postgres and there is no pre-token-generation trigger, so it is not a JWT claim; a Cognito *access* token carries neither `email` nor `name` either. `AuthProvider` calls `/auth/me` on mount (skipping the call entirely when no tokens are stored) and exposes `user`, `isAuthenticated`, `isAdmin`, `isLoading`. Do not add a "fall back to decoding the ID token" path.

Expand All @@ -83,6 +83,8 @@ Both live in `src/app/components/Permission.tsx`. Record-scoped actions take a `

Tests: `test/rbac.ts` has `adminSubject` / `directorSubject` / `memberSubject` and a `session()` builder. The shared `render` from `test/utils.tsx` signs in as an admin by default — pass `{ subject }` to render as someone else, or `renderWithLiveAuth` for the handful of tests that exercise `AuthProvider` itself.

**Staff impersonation.** A staff account (`rbac.isStaff`) lands on `/staff`, the staff console, which is the only page it can open as itself. `startImpersonation(userId, 'read_only' | 'full')` stores the server's session id in **sessionStorage** (`authTokens.ts`, so the switch-in is per tab) and `authedFetch` sends it as `X-Impersonate-Session` on every call. `/auth/me` then reports the *target*, so every page, permission and nav item is the target's with no further code. `ImpersonationBanner` (mounted in `providers.tsx`) shows who you are viewing as and exits via `stopImpersonation()`. Both calls clear the whole query cache, because every entry was fetched as the other identity; `logout()` now does too. When the server ends a session (`IMPERSONATION_EXPIRED`), `authedFetch` drops the id and retries a GET as the staff account, never a write. Console calls that must go out as staff pass `asSelf: true`. See `shared/rbac/README.md`.

**Challenges.** `login()` returns `{ status: 'authenticated' }` or `{ status: 'challenge', ... }`. `NEW_PASSWORD_REQUIRED` is handled by the login page; the other challenge names are plumbed through `respondToChallenge` and become reachable if MFA is switched on in `infrastructure/aws/cognito.tf`, needing only a UI step.

**No self-serve signup.** The backend still serves `/auth/register`, `/auth/verify-email` and `/auth/resend-code`, but the frontend deliberately does not expose them — see the comment in `AuthContext.tsx`. Onboarding is admin-invite.
Expand Down
57 changes: 57 additions & 0 deletions apps/frontend/src/app/components/ImpersonationBanner.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
'use client';

import { useState } from 'react';
import { useRouter } from 'next/navigation';
import { useAuth } from '@/context/AuthContext';
import { STAFF_CONSOLE_PATH } from '@/lib/routes';

function timeOf(iso: string): string {
return new Date(iso).toLocaleTimeString([], {
hour: 'numeric',
minute: '2-digit',
});
}

export default function ImpersonationBanner() {
const { user, stopImpersonation } = useAuth();
const router = useRouter();
const [leaving, setLeaving] = useState(false);
const impersonation = user?.impersonation;
if (!user || !impersonation) return null;

const full = impersonation.mode === 'full';

const exit = async () => {
setLeaving(true);
try {
await stopImpersonation();
router.replace(STAFF_CONSOLE_PATH);
} finally {
setLeaving(false);
}
};

// `!` on padding and colours: Chakra's reset outranks unprefixed utilities.
return (
<div
role="status"
className={`sticky top-0 z-50 flex flex-wrap items-center justify-between gap-2 !px-4 !py-2 text-sm !text-core-white ${
full ? '!bg-error-red' : '!bg-accent-dark-green'
}`}
>
<span className="min-w-0">
Viewing as <strong>{user.name}</strong> ({user.email}) ·{' '}
{full ? 'Full access: changes are real' : 'Read-only'} · ends{' '}
{timeOf(impersonation.expiresAt)}
</span>
<button
type="button"
onClick={exit}
disabled={leaving}
className="shrink-0 rounded !border-[1px] !border-solid !border-core-white !bg-transparent !px-3 !py-1 font-semibold !text-core-white hover:!opacity-80 disabled:!opacity-60"
>
{leaving ? 'Exiting…' : 'Exit'}
</button>
</div>
);
}
2 changes: 2 additions & 0 deletions apps/frontend/src/app/providers.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import { QueryClientProvider } from '@tanstack/react-query';
import { AuthProvider } from '@/context/AuthContext';
import { makeQueryClient } from '@/lib/queryClient';
import AuthGate from './components/AuthGate';
import ImpersonationBanner from './components/ImpersonationBanner';
import RoutePrefetcher from './components/RoutePrefetcher';

// AuthGate lives here so every route is guarded by construction. Note that
Expand All @@ -32,6 +33,7 @@ export function Providers({ children }: { children: React.ReactNode }) {
<RoutePrefetcher />
<ChakraProvider value={defaultSystem}>
<AuthProvider>
<ImpersonationBanner />
<AuthGate>{children}</AuthGate>
</AuthProvider>
</ChakraProvider>
Expand Down
186 changes: 186 additions & 0 deletions apps/frontend/src/app/staff/page.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,186 @@
'use client';

import React, { useEffect, useState } from 'react';
import { useRouter } from 'next/navigation';
import Header from '../components/Header';
import Button from '../components/Button';
import DataTable, { type DataTableColumn } from '../components/DataTable';
import ConfirmDeleteDialog from '../components/ConfirmDeleteDialog';
import TextInputField from '../components/TextInputField';
import { useApi } from '@/hooks/useApi';
import { useAuth, type ImpersonationMode } from '@/context/AuthContext';
import { LOGIN_PATH, landingPathFor } from '@/lib/routes';

interface Target {
userId: number;
name: string;
email: string;
isAdmin: boolean;
pending: boolean;
directorProjectCount: number;
memberProjectCount: number;
}

const SEARCH_DEBOUNCE_MS = 250;

function roleOf(t: Target): string {
if (t.isAdmin) return 'Admin';
if (t.directorProjectCount > 0) return 'Director';
return t.memberProjectCount > 0 ? 'Member' : 'No projects';
}

export default function StaffConsolePage() {
const api = useApi();
const router = useRouter();
const { startImpersonation, logout } = useAuth();
const [search, setSearch] = useState('');
const [targets, setTargets] = useState<Target[]>([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const [switching, setSwitching] = useState<number | null>(null);
const [confirmFull, setConfirmFull] = useState<Target | null>(null);

useEffect(() => {
let cancelled = false;
const timer = setTimeout(async () => {
setError(null);
try {
const query = search.trim()
? `?search=${encodeURIComponent(search.trim())}`
: '';
const json = await api.get<{ users: Target[] }>(
`/auth/impersonation/targets${query}`,
);
if (!cancelled) setTargets(json.users ?? []);
} catch (err) {
if (!cancelled)
setError(err instanceof Error ? err.message : 'Failed to load users');
} finally {
if (!cancelled) setLoading(false);
}
}, SEARCH_DEBOUNCE_MS);
return () => {
cancelled = true;
clearTimeout(timer);
};
}, [api, search]);

const switchInto = async (target: Target, mode: ImpersonationMode) => {
setSwitching(target.userId);
setError(null);
try {
const me = await startImpersonation(target.userId, mode);
router.replace(landingPathFor(me.rbac));
} catch (err) {
setSwitching(null);
setError(
err instanceof Error ? err.message : 'Could not switch into this user',
);
throw err;
}
};

const columns: DataTableColumn<Target>[] = [
{
key: 'name',
header: 'Name',
cell: (t) => (
<span>
{t.name}
{t.pending && (
<span className="!pl-2 text-xs text-gray-500">
(never signed in)
</span>
)}
</span>
),
},
{ key: 'email', header: 'Email', cell: (t) => t.email },
{ key: 'role', header: 'Role', width: '120px', cell: roleOf },
{
key: 'actions',
header: '',
width: '220px',
align: 'right',
cell: (t) => (
<div className="flex justify-end gap-2">
<Button
variant="secondary"
isLoading={switching === t.userId}
disabled={switching !== null}
onClick={() => switchInto(t, 'read_only').catch(() => undefined)}
>
View as
</Button>
<Button
variant="danger"
disabled={switching !== null}
onClick={() => setConfirmFull(t)}
>
Act as
</Button>
</div>
),
},
];

return (
<div className="min-h-screen bg-core-white">
<Header text="Staff console" />
<main className="!p-6">
<div className="flex flex-wrap items-end justify-between gap-4 !pb-4">
<div className="w-full max-w-sm">
<TextInputField
label="Search by name or email"
value={search}
onChange={setSearch}
/>
</div>
<Button
variant="ghost"
onClick={async () => {
await logout();
router.replace(LOGIN_PATH);
}}
>
Sign out
</Button>
</div>
<p className="!pb-4 text-sm text-gray-600">
<strong>View as</strong> is read-only. <strong>Act as</strong> makes
real changes in that user&apos;s name. Every change is recorded
against your account. A switch-in lasts one hour.
</p>
{error && (
<p role="alert" className="!pb-4 text-sm !text-error-red">
{error}
</p>
)}
<DataTable
columns={columns}
rows={targets}
rowKey={(t) => t.userId}
isLoading={loading}
loadingLabel="Loading users"
emptyMessage={
search ? 'No users match that search.' : 'No users yet.'
}
/>
</main>

<ConfirmDeleteDialog
open={confirmFull !== null}
onClose={() => setConfirmFull(null)}
onConfirm={() =>
confirmFull ? switchInto(confirmFull, 'full') : undefined
}
title="Act as this user with full access?"
itemName={
confirmFull ? `${confirmFull.name} (${confirmFull.email})` : undefined
}
consequences="Anything you create, edit, approve or delete is real and is saved as this user. Each change is also recorded against your staff account."
confirmLabel="Act as"
/>
</div>
);
}
Loading
Loading