diff --git a/.claude/launch.json b/.claude/launch.json new file mode 100644 index 000000000..5f18425dc --- /dev/null +++ b/.claude/launch.json @@ -0,0 +1,11 @@ +{ + "version": "0.0.1", + "configurations": [ + { + "name": "storybook", + "runtimeExecutable": "pnpm", + "runtimeArgs": ["--filter", "@irene/ui", "storybook", "--no-open"], + "port": 6006 + } + ] +} diff --git a/.claude/skills/irene-react-patterns/SKILL.md b/.claude/skills/irene-react-patterns/SKILL.md new file mode 100644 index 000000000..3578997cc --- /dev/null +++ b/.claude/skills/irene-react-patterns/SKILL.md @@ -0,0 +1,85 @@ +--- +name: irene-react-patterns +description: How code is written in the irene-react monorepo (Appknox dashboard, React + TanStack Router/Query + Tailwind + Zustand). Use this skill whenever adding or changing anything in apps/dashboard or packages/* — a page, route, component, form, layout, API endpoint, service, query, mutation, store, websocket/live-update handling, normalized cache, configuration (getConfigValue, feature flags, whitelabel), translation, or test — and whenever porting a screen from the Ember app (irene). Also use it when the user asks where something should go, how a feature should be structured, or "how do we do X here", even if they don't name a specific pattern. +--- + +# irene-react patterns + +A React port of Appknox's Ember dashboard (irene). New code should look like the +code around it. `CLAUDE.md` is the authority on styling, TypeScript, comments, +tests, storage and commits; read it first. This skill covers structure and +per-layer patterns. + +## Map + +``` +apps/dashboard/src/ + routes/ thin TanStack file routes: guards, search params, loader, title, component + features// real code for one domain + pages// index.tsx + components/ hooks/ used only by that page + components/ hooks/ queries/ schemas/ actions/ utils/ store.ts + index.ts public entry, only if something outside renders the feature + components/ layouts/ hooks/ queries/ actions/ utils/ app-wide equivalents +packages/ + api/ endpoints, services, types, transforms, stores, normalization, request client + websocket/ server push + ui/ Ak* components, icons, svgs, styles/theme.css + translations/ en.json + ja.json, akMT, , FORMATS + config/ constants/ enums/ +``` + +## Where does it go? + +Narrowest level that uses it; move up when a second user appears. + +| What | Where | +| ------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------- | +| URL, guard, search params, title | `routes/…/.tsx` | +| Page | `features//pages//index.tsx` | +| Component: one page / one feature / app-wide | `pages//components/` / `features//components/` / `src/components/` | +| Generic, no app data or API | `packages/ui/src/components/ak-/` | +| Endpoint paths / HTTP call / response types | `packages/api/src/services//endpoints.ts` / `service.ts` / `types.ts` | +| Query keys + `xOptions()` | `features//queries/` or `src/queries/` | +| Form schema + typed field | `features//schemas/
.ts` | +| **Action**: plain async fn taking `queryClient`; spans cache/stores/storage, or called from guards/loaders | `actions/` (`endSession`, `setupUserAndOrgContext`) | +| **Hook** (`use…`): re-renders on state, or tied to component lifetime. Hands work to actions (`useLogout` → `endSession`) | `hooks/` (`useOrganization`, `useDashboardWebsocket`) | +| Client-only shared state | Zustand: `features//store.ts` or `packages/api/src/stores/` | +| Server codes (status, platform, risk…) | `ENUMS` from `@irene/enums`, never raw numbers | +| Client-named constants (HTTP statuses, hostnames, support email) | `@irene/constants` | +| Deployment settings / release constants / backend config | `@irene/config` / `@irene/config/product` / `configurationStore` (see [configuration.md](references/configuration.md)) | +| Live updates | tag records in services, then `useWebsocketSignal` / `useWebsocketRecord` (see [websocket.md](references/websocket.md)) | + +## Building a feature (bottom-up) + +1. Endpoints, types, service in `packages/api`. Then query keys and options. + See [api-and-data.md](references/api-and-data.md). +2. A thin route. See [routing.md](references/routing.md). +3. The page and its components. See [components-and-styles.md](references/components-and-styles.md). +4. Live updates if the data changes server-side. Usually tagging the record is + enough. See [websocket.md](references/websocket.md). +5. Copy in **both** `en.json` and `ja.json`. Use `` in + JSX, and `akMT()` in props, schemas, toasts and titles. Format dates and + numbers through the named `FORMATS`. +6. Tests next to the code (MSW + factories, ≥90% coverage). See + [testing.md](references/testing.md). +7. Porting from irene: carry every condition across. Record deliberate + differences in `DESIGN-DECISIONS.md` and scenarios in `QA-SCENARIOS.md`. + +## Everywhere + +- JSDoc on every export, saying what it does and **why**. +- Import via package paths (`@irene/ui/ak-button`, `@/features/…`). Apps never + use `@ui/*`, `@api/*` or `@config/*`. +- No `any`, `!`, `@ts-ignore` or `as unknown as`. Derive types from `z.infer`, + `ReturnType`, enums or the route tree. +- Server data lives in TanStack Query. Stores hold client state only. +- Records that are pushed or shared across queries are tagged in the service + (`tagRecordForCaching`). +- Component files stay under 350 lines of code (lint). Private helpers are + `_prefixed` and not exported. Use `data-test-*` hooks for tests. + +## Before finishing + +```bash +pnpm lint:fix && pnpm lint && pnpm lint:types && pnpm --filter @irene/dashboard test +``` diff --git a/.claude/skills/irene-react-patterns/references/api-and-data.md b/.claude/skills/irene-react-patterns/references/api-and-data.md new file mode 100644 index 000000000..53f8f4436 --- /dev/null +++ b/.claude/skills/irene-react-patterns/references/api-and-data.md @@ -0,0 +1,200 @@ +# API, queries, mutations and state + +Flow: **endpoints → service → query options → component**, one file per step. + +## Endpoints, types, index (`packages/api/src/services//`) + +```ts +// endpoints.ts: path builders only; encode segments; `as const` +export const OrganizationEndpoints = { + list: () => `${API_NAMESPACES.v1}/organizations` as const, + me: (id: number | string) => + `${API_NAMESPACES.v1}/organizations/${encodeURIComponent(id)}/me` as const, +}; + +// index.ts: always this shape +export * from './endpoints'; +export type * from './types'; +export { default as OrganizationService } from './service'; +``` + +- Namespaces: `v1` `api`, `v2` `api/v2`, `v3` `api/v3`, `hudson` + `api/hudson-api`. Use the one irene used for that endpoint. Tests build MSW + URLs from the same endpoints. +- `types.ts`: `Api*` interfaces with the server's snake_case fields, plus + `ApiRequest` and `ApiResponse`. + +## Service (`service.ts`) + +A default-exported class of `public static readonly` arrow functions. Each one +calls `apiRequest.(url, …)`, which returns the **body**. + +```ts +public static readonly getOrganizations = async () => { + const page = await apiRequest.get>( + OrganizationEndpoints.list(), { signal: AbortSignal.timeout(REQUEST_ABORT_TIMEOUT_MS) }); + + return transformPaginatedResponse(page); +}; +``` + +- **Lists**: `ApiPageEnvelope` → `transformPaginatedResponse` → `ApiPage` + (`items`, `count`, `hasNext`…). Components never read `results`. +- **JSON:API responses** (`data.attributes`, kebab-case) are flattened in + `utils/transforms.ts`. +- **Timeouts** are off by default. Add `AbortSignal.timeout(REQUEST_ABORT_TIMEOUT_MS)` + to requests that hold a screen (loaders, boot). Never add it to uploads. +- **Tag** records that are pushed or shared (see Normalized cache below). +- Resolve instead of rejecting only when failure _is_ the answer + (`StatusService`). Otherwise let it reject. + +## Enums and status codes + +- Server codes come from `ENUMS` (`@irene/enums`, ported 1:1 from irene): + `submission.status === ENUMS.SUBMISSION_STATUS.ANALYZING`, never `=== 6`. +- Each group also has `UNKNOWN` (-1), `BASE_VALUES` / `BASE_CHOICES` (as + declared), and `VALUES` / `CHOICES` (with UNKNOWN). +- Type fields from the group: + `type ApiSubmissionStatus = (typeof ENUMS.SUBMISSION_STATUS)['BASE_VALUES'][number]`. +- Group values with typed `Set`s and `Record`s (`FAILED_STATUSES`, + `PROGRESS_BY_STATUS` in `upload-app/utils.ts`), not `===` chains. +- Display, in order of preference: the server's `*_humanized` field, then + `ENUMS_DISPLAY` (e.g. `'iOS'`), then reduce to an outcome and `akMT` it. + Never show the key. +- Adding an enum: copy it exactly from irene into + `packages/enums/src/categories/.ts`, and update the group and key + counts in `packages/enums/src/index.test.ts`. +- HTTP statuses: `HTTP_STATUS_CODES` from `@irene/constants`, compared against + `getApiErrorStatus(error)`. Never bare numbers. Add missing codes, with a doc + comment, to `status-codes.ts`. The type is `HttpStatusCode`. + +## Queries (`features//queries/.ts`) + +```ts +export const organizationKeys = { + all: () => ['organization'] as const, + me: (orgId: number | string) => [...organizationKeys.all(), 'me', orgId] as const, +}; + +/** Builds the query for this account's role in one organization. */ +export const organizationMeOptions = (orgId: number | string) => + queryOptions({ + queryKey: organizationKeys.me(orgId), + queryFn: () => OrganizationService.getOrganizationMe(orgId), + staleTime: Infinity, + }); +``` + +- **Every `queryFn` calls a service**, never `apiRequest` or `fetch`. It may + add logic around the call. +- Keys nest under `all()`, so `invalidateQueries({ queryKey: xKeys.all() })` + clears the whole domain. +- Defaults: 30s stale time, retries only on network errors and 5xx, no + refetch on focus. Comment any override (`staleTime: Infinity`, + `retry: false` when a 404 is an answer). + +**Reading**, always through the `xOptions()` builder: + +- In a component that renders the data: `useQuery(xOptions())`. Handle + `isPending` with a skeleton and errors in place (`getApiErrorStatus`, + `isRateLimited`). Most pages fetch this way. +- In guards, loaders and actions: `await queryClient.query(xOptions())`. If a + loader pre-fills the cache, the component still reads it with `useQuery`. + Never use `useLoaderData`. +- Conditional queries use `enabled`, never a hook inside an `if`. No + `useEffect` fetching. `getQueryData` only for rare merges. + `useSuspenseQuery` and `useInfiniteQuery` aren't used. + +## Mutations + +Put `useMutation` inline when it's short, or in a `use` hook when the +logic is long or reused (`useLogin`, which returns `{ login, failure }`). + +```ts +const recover = useMutation({ + mutationFn: ({ username }: RecoverFormSchema) => AuthService.recoverPassword(username), + onError: unlessRateLimited((error) => { + const message = getApiFieldErrors<'username'>(error).username?.[0]; + + if (message) { + form.setError('username', { message }); + } else { + akNotify.error(akMT('somethingWentWrong')); + } + }), +}); +``` + +- `mutationFn` calls a service. Trigger with `.mutate()` and handle outcomes + in callbacks; `mutateAsync` isn't used. +- `isPending` → ``. Use `onSettled` for "either way" cleanup + (`useLogout`). Mutations are never retried. +- Wrap `onError` in `unlessRateLimited` (429s are announced globally). Field + errors go onto the form; anything else becomes `akNotify.error(akMT(…))`. +- Updating the cache afterwards, in order of preference: + 1. tagged reply → `useNormalizedRecordCache().write(type, record)` + 2. new row in a visible list → `prependRecordToPage` + 3. patch one row → `setQueryData` + `patchPaginationItem` + 4. otherwise `invalidateQueries` +- Optimistic updates only for small, reversible toggles (the notification + read state): `cancelQueries`, snapshot, `setQueryData` in `onMutate`, and + restore the snapshot in `onError`. + +## Normalized cache (`@normy/react-query`) + +`NormalizationProvider` (in `App.tsx` and the test render helpers) keys records +by `":"`, so writing a record once updates **every** query holding +it. Only records carrying the client-added `__record` field take part; +everything else behaves like plain TanStack Query. + +- **Tag in the service**, after any transform: + `tagRecordForCaching('file', file)` or + `tagPaginatedRecordsForCaching('submission', page)`. The result type is + `ApiTaggedRecord`. Tag every endpoint that returns that type, or one copy + never updates. +- **New type**: add it to `API_RECORD_TYPES` (the server's name), and to + `ApiRecordShapes` if hooks need it typed. Only tag types that are pushed or + shared. +- **Writing**: `useNormalizedRecordCache()` gives `.write(type, record)` to + patch everywhere and `.readQueriesHolding(type, id)` to invalidate. + Normalization can't _add_ rows to a list, so use `prependRecordToPage` for + that. +- **Gotcha**: strip `__record` before sending a cached record as a request + body. + +## Actions + +Plain async functions taking `queryClient` first (`endSession`, +`loadConfiguration`, `setupUserAndOrgContext`), callable from routes, hooks +and tests. Use `Promise.all` for independent fetches, and `allSettled` when +one failure shouldn't block the rest. + +## Stores (Zustand) vs queries + +| | Query | Store | +| --------------------- | -------------------------------- | ------------------------------------------------------------------- | +| Holds | server data (a service's answer) | client state, or a server value that must be read synchronously | +| Filled by | its `queryFn` → service | an action, the interceptor or the UI. **Never a service directly.** | +| Stays fresh by itself | yes | no | +| Read | `useQuery` / `queryClient.query` | a `use…` hook / `xStore.getState()` | + +Today's stores: `configurationStore`, `organizationStore` and +`vulnerabilityStore` are filled from queries by actions for synchronous +reads. `rateLimitStore` is filled by the 429 interceptor, and `uploadAppStore` +holds client-only upload progress. + +```ts +export const organizationStore = createStore((set) => ({ + ...NONE_SELECTED, + select: (organization) => set({ selected: organization }), + clear: () => set(NONE_SELECTED), +})); + +export const useOrganization = () => useStore(organizationStore); // src/hooks +``` + +- Use `createStore` from `zustand/vanilla`, so guards can read it. +- Give each store a `clear()` and call it from `endSession`, or one account's + data leaks into the next sign-in. +- Persisted values go under `irene:` keys, with storage access wrapped + in try/catch. diff --git a/.claude/skills/irene-react-patterns/references/components-and-styles.md b/.claude/skills/irene-react-patterns/references/components-and-styles.md new file mode 100644 index 000000000..ac22acbfb --- /dev/null +++ b/.claude/skills/irene-react-patterns/references/components-and-styles.md @@ -0,0 +1,196 @@ +# Components, styles, forms and copy + +Read `CLAUDE.md` → Styling alongside this. + +## App components + +Named function exports, kebab-case files, the props interface right above the +component, `Readonly`, and a JSDoc saying what it's for. + +- Build from `Ak*` components (`packages/ui/src/components/` has button, + typography, input, select, checkbox, link, icon, alert, table, skeleton, + modal, drawer, popover, menu, tooltip, chip, form…). +- Blank line between sibling JSX elements (lint). Logic longer than a few + lines goes in a `use…` hook; pure helpers go in `utils.ts` with a test. +- Loading: an `AkSkeleton` shaped like the content, or `loading` on the + button. Failures: `AkAlert` or `akNotify`. +- A feature rendered from outside exports its entry in `features//index.ts`. + +## Design-system components (`packages/ui/src/components/ak-/`) + +Generic only, with no app data or API calls. Files: `index.tsx` +(`Ak…`), `variants.ts` (`cva`), `index.stories.tsx` +(`'Components/Ak'`, autodocs), `index.test.tsx`, plus +`helpers`/`context`/`styles.module.css` when needed. + +```tsx +function AkBadge({ + className, + color = 'neutral', + ...props +}: ComponentProps<'span'> & VariantProps) { + return ( + + ); +} +``` + +- Extend the native element's props and spread the rest. Expose state as + `data-*` and style from it (`data-loading:…`). Use Radix `Slot` for + `asChild`. Use `compoundVariants` for variant × colour. +- Icons: ``. SVGs: + `import X from '@irene/ui/svgs/x.svg?react'`. +- **shadcn**: `pnpm --filter @irene/ui shadcn:add `, never the bare + CLI. It writes `ak-/index.tsx`, renames exports to `Ak*`, splits `cva` + into `variants.ts` and fixes imports. Then restyle with tokens, match irene's + props, and add a story and tests. Check what already exists first. + +## Styles + +- Inline Tailwind classes with theme tokens (`bg-primary`, + `text-foreground-disabled`, `rounded-md`). No hex, rgb, or arbitrary + radius, spacing or text size (lint). +- The root font is 14px and spacing steps are 4px (`w-14` = 56px). Use at most + two decimals (`py-2.75` works; `gap-4.375` generates nothing). +- Runtime values: `style={{ '--progress': `${pct}%` }} className="w-(--progress)"`. +- CSS Modules only for keyframes and complex selectors. No dark mode + (`dark:`), and no styled-components or inline style objects. + +### `cn` (`@irene/ui/cn` = clsx + tailwind-merge; last class wins) + +- Put the component's own classes first and the caller's `className` last, so + the caller overrides: `cn(akXVariants({ color }), isCompact && 'px-1', className)`. +- Use it when combining with conditions, variables, variants or props: + `cn('rounded-full', isUnread && 'bg-secondary')`, or `{ 'opacity-50': disabled }` + for several flags. +- **Class lists declared outside the JSX as constants** are wrapped in `cn()`, + even single literals. The lint rules only read `className`, `cn()`/`cva()` + and `*Props={{ className }}`, so a bare string would escape them. + ```tsx + const SEVERITY_DOT = { critical: cn('bg-danger'), low: cn('bg-success') } satisfies Record< + Severity, + string + >; + const CELL = cn('px-3 py-2.75 text-sm'); + ``` + Keep such constants in their own file and never export them. Shared styling + belongs in a component or a `cva` variant. (`variants.ts` is exempt.) +- Don't use it for a single inline literal: `className="flex items-center"`. +- tailwind-merge already understands the theme (`text-2xs` and `text-md` vs + colours, fractional spacing, semantic colours). Numbered shadows are + registered via `SHADOW_SCALE`. **A new non-standard token name** needs + registering in `cn/index.ts` plus a test, or merges break silently. + +## Forms (react-hook-form + zod + AkForm) + +**One schema file per form** (`features//schemas/.ts`), exporting +three things: + +```ts +/** Built per render, so its messages follow the locale. */ +export const buildResetPasswordSchema = () => + z + .object({ + password: z.string().min(1, akMT('enterNewPassword')), + confirm_password: z.string().min(1, akMT('enterConfirmPassword')), + }) + .refine((v) => v.password === v.confirm_password, { + message: akMT('passwordMatchError'), + path: ['confirm_password'], + }); + +export type ResetPasswordFormSchema = z.infer>; +export const ResetPasswordFormField = createAkFormField(); // module scope +``` + +- **Builder functions, never constants** (`akMT` is read when called). They + can take parameters (`buildStoreLinkSchema(isOffsec)`). +- Field names are the API's names, so values are the request body and API + errors map back onto fields. +- **Why `XFormField` and not `AkFormField`:** a bare `AkFormField` falls back + to the generic `FieldValues` type and accepts any string as `name`. A typo + then compiles, registers a field the schema doesn't know, and **never + validates**. `createAkFormField()` fixes the schema type once, + so `name` autocompletes and a typo is a type error, without spelling out + the generics on every field. Always use the bound field, never `AkFormField` + directly. +- Create it **once, at module scope**, in the schema file. Each call returns + a new component, so calling it during a render remounts the field on every + render and loses what was typed. +- Patterns: + - required text: `z.string().trim().min(1, akMT(…))` + - must-tick checkbox: `.refine(Boolean, …)` + - cross-field checks: `.refine` with a `path` + - several messages for one field: `.superRefine` with `_validate…` helpers + - multi-step forms: `.extend()` per step (login) + +**The form**: + +```tsx +const form = useForm({ + resolver: zodResolver(buildXSchema()), + defaultValues: { username: '' }, + reValidateMode: 'onSubmit', +}); +const usernameIsEmpty = useRequiredField('username', form); + + + mutation.mutate(v))}> + + + + + + … + + +; +``` + +- Every field gets a default value. The control is the field's **child**. +- `reValidateMode: 'onSubmit'` is the default. Use `'onChange'` for long forms + and `mode: 'onChange'` only for live checks (store link). +- `useRequiredField` disables submit while required text is empty, and hides + that field's "required" message. +- API errors: `toFormFieldErrors(schema, error)` → `setFormFieldErrors(form, …)`. + If nothing matches, show a toast. For one known field, + `getApiFieldErrors` + `form.setError` is fine. + +**zod beyond forms**: route `validateSearch` (optional params, plus +`.catch(undefined)` on navigation values), and notification `context.ts` +schemas checked with `safeParse` before rendering. Fall back on failure. Types +always come from `z.infer`. + +## Copy and translations + +- Add every key to **both** `en.json` and `ja.json`. Search first: irene's keys + exist. Nested ids use dots. +- **JSX children → ``**. It's preferred + for IntelliSense: `id` autocompletes and `values` is typed per message. +- **Everywhere else → `akMT('…', values)`**: props (`label`, `placeholder`, + `aria-label`), zod messages, toasts, route titles, hooks and tests. It + returns a string, or React nodes when the message has markup. +- Messages may contain `
` (`RICH_TEXT_TAGS`). + Never use `dangerouslySetInnerHTML`. +- Never choose the id with a ternary: branch around the call, + `cond ? akMT('a') : akMT('b')`. + +### Dates, times and numbers + +- Use the named `FORMATS` (`packages/translations/src/formats.ts`: `hhmmss` + for date/time, `USD`/`EUR` for numbers). In a message: + `"Last scanned at {at, time, hhmmss}"` with `values={{ at: new Date(…) }}`. + Standalone: `useIntl().formatTime(v, { format: 'hhmmss' })` (or `getIntl()` + outside React). +- Need another format? Add it to `FORMATS`. Never use `toLocaleString`, inline + `Intl` options or pattern strings. +- Relative time: `formatRelativeTime` from `@/utils/relative-time`. dayjs is + for parsing and arithmetic. If it must format, use + `.locale(getLocale())` per call, never the global `dayjs.locale()`. (The + fixed patterns in `notifications/utils.ts` are legacy and English-only.) +- Unreadable dates render as `''`, never "Invalid Date". diff --git a/.claude/skills/irene-react-patterns/references/configuration.md b/.claude/skills/irene-react-patterns/references/configuration.md new file mode 100644 index 000000000..8babe3f5d --- /dev/null +++ b/.claude/skills/irene-react-patterns/references/configuration.md @@ -0,0 +1,57 @@ +# Configuration + +Choose by **who decides the value**: + +| Decided by | Source | Read with | +| ---------------------------- | --------------------------------------------------- | ------------------------------------------------------------------------------ | +| Deployment (CI or container) | `@irene/config`, 12 registered keys | `getConfigValue`, `getConfigFlag`, `isPluginEnabled`, `isWhitelabelEnabled` | +| Release | `@irene/config/product` | constants: `PRODUCT_VERSIONS`, `G_RECAPTCHA`, `PENDO_API_KEY` | +| Backend at runtime | `configurationStore`, filled by `loadConfiguration` | `useServerConfiguration()`, `useWhitelabel()`, `configurationStore.getState()` | + +## Deployment keys + +Each key resolves through three sources, first match wins: + +1. `window.runtimeGlobalConfig` (injected at container start) +2. `__BUILD_CONFIG__` (from CI env, via `buildConfigDefine` in `vite.config.ts`) +3. `DEFAULTS` + +The keys are `IRENE_API_HOST`, `IRENE_SHOW_LICENSE`, `IRENE_ENABLE_PENDO`, +`IRENE_ENABLE_MARKETPLACE`, `IRENE_POSTHOG_API_KEY`, `IRENE_POSTHOG_API_HOST`, +`ENTERPRISE`, and `WHITELABEL_ENABLED` / `NAME` / `LOGO` / `THEME` / `FAVICON`. + +- Strings: `getConfigValue(key)` (unset → `''`; API host `'/'` → `''`, meaning + same origin). +- Flags: `getConfigFlag(key)`. Never compare raw values, because `'false'` is + truthy. +- Pendo / Marketplace: always `isPluginEnabled(key)`. When unset they follow + the inverse of `ENTERPRISE`. +- `getConfig(key)` gives the raw value, only when "unset" matters + (`WHITELABEL_FAVICON`). +- Read inside functions, not in module constants. Unknown keys fail type-checking. +- **Never add a key** (every deployment would need it). Release-fixed public + values go in `@irene/config/product`; backend-decided values come from + `configurationStore` or org features. + +## Backend config + +`configurationStore` exposes getters (`isEnterprise()`, `socketHost()`, +`deviceFarmUrl()`) that fall back to the deployment keys. Boot doesn't wait +for it, so components reserve space until it arrives. + +## Tests + +`tests/setup.ts` resets both sources. Set the one you mean with string values, +then restore it: + +```ts +beforeEach(() => { + globalThis.__BUILD_CONFIG__ = { WHITELABEL_ENABLED: 'true' }; +}); +afterEach(() => { + globalThis.__BUILD_CONFIG__ = {}; +}); +``` + +For backend config, answer the config endpoints via MSW with +`buildFrontendConfiguration` / `buildServerConfiguration`. diff --git a/.claude/skills/irene-react-patterns/references/routing.md b/.claude/skills/irene-react-patterns/references/routing.md new file mode 100644 index 000000000..5dc792493 --- /dev/null +++ b/.claude/skills/irene-react-patterns/references/routing.md @@ -0,0 +1,62 @@ +# Routing + +TanStack Router, file-based, in `apps/dashboard/src/routes/`. `routeTree.gen.ts` +is generated on save; never edit it. + +| File | Meaning | +| --------------------------------------- | ------------------------------------------------------ | +| `__root.tsx` | restores locale, checks session, starts config load | +| `_authenticated.tsx` | guard (→ `/login?redirectTo=…`), then loads user + org | +| `_unauthenticated.tsx` | layout for login, register, reset | +| `_authenticated/dashboard/projects.tsx` | `/dashboard/projects` | +| `_unauthenticated/reset/$token.tsx` | `/reset/:token` | + +`_name` adds a layout or guard without a URL segment. New signed-in pages go +under `_authenticated/`. A page outside both guards (`/dashboard/status`) needs +a comment saying why. + +## A route file is wiring only + +```ts +export const Route = createFileRoute('/_unauthenticated/login')({ + staticData: { pageTitle: () => akMT('login') }, + validateSearch: z.object({ + sessionExpired: z.boolean().optional(), + redirectTo: returnPathSchema, + }), + beforeLoad: async ({ context }) => { + if (await context.queryClient.query(sessionCheckOptions())) { + throw redirect({ to: '/' }); + } + }, + component: LoginPage, // from features/ +}); +``` + +- **`pageTitle`**: always set it, as a function so it follows the locale. + `RouterPageTitleContext<'/path/$p'>` types params. +- **`validateSearch`**: params are optional. Validate navigation targets + (`returnPathSchema` blocks open redirects). +- **`beforeLoad`**: guards and redirects (`replace: true` when there should be + no history entry). Its return value merges into child `context`. +- **`loader`** + `pendingComponent: RoutePending` + `errorComponent: RouteError`: + for data needed before render. The component then reads the same query with + `useQuery`. +- A guard needing data a parent _loader_ fills must await that setup itself. + Loaders run after all guards; cached queries make the second call free + (`dashboard/home.tsx`). +- Moved URL: keep the old file as a redirect-only route (`routes/status.tsx`). + +## In components + +- `` and `useNavigate()` are type-checked against the tree. +- `getRouteApi('/_unauthenticated/login').useSearch()` reads another route's + search params. +- Path unions come from `FileRouteTypes['to']`, never hand-written. + +## New page + +Add the route file (title + component) and the page in +`features//pages//` (named export). Add a loader and pending/error +components if needed, a nav entry in `layouts/*/nav-items`, and a +`renderAtRoute` test. diff --git a/.claude/skills/irene-react-patterns/references/testing.md b/.claude/skills/irene-react-patterns/references/testing.md new file mode 100644 index 000000000..55c45a507 --- /dev/null +++ b/.claude/skills/irene-react-patterns/references/testing.md @@ -0,0 +1,49 @@ +# Tests + +Vitest + Testing Library + MSW. Test files sit next to the code. Coverage must +be ≥90% on every column. See also `CLAUDE.md` → Tests. + +```tsx +const RECOVER_URL = buildAPITestURL(AuthEndpoints.recover()); + +it('posts the username and shows the confirmation', async () => { + let body: unknown; + + server.use( + http.post(RECOVER_URL, async ({ request }) => { + body = await request.json(); + return HttpResponse.json({}); + }) + ); + + await renderAtRoute('/recover'); + await userEvent.type(screen.getByLabelText(akMT('usernameEmailIdTextLabel')), USERNAME); + await userEvent.click(screen.getByRole('button', { name: akMT('resetPassword') })); + + expect(body).toEqual({ username: USERNAME }); +}); +``` + +- **Render helpers** (`tests/render.tsx`): + - `renderAtRoute(path, { settle })` for pages: real guards, loaders and + layouts. `settle: false` shows the pending state. + - `renderWithRouterContext(ui)` for components containing ``. + - `renderWithProviders(ui)` for everything else. +- **MSW** runs the real axios stack. Build URLs with + `buildAPITestURL(XEndpoints.y())`. Use `HTTP_STATUS_CODES` for statuses (older + tests' raw `204`/`500` are legacy). `tests/server.ts` already answers config, + session and signed-in setup. +- Query elements by role, label or text, with `akMT` for copy; `data-test-*` + only as a fallback. Test names state the behaviour. +- **Factories** (`tests/factories/`): `build(overrides = {})` with + faker. Pin only the fields the test is about, and assert against the built + object, never literals. +- **Don't `vi.mock` modules the app imports.** With `isolate: false`, files + share modules per worker, so the mock is silently ignored whenever another + file loaded the page first, and the test becomes flaky. Fake at the + boundary instead: MSW for HTTP; for globals and third-party scripts, set the + global and fire the event the library waits for (`loadRecaptchaWidget` in + the register test); `vi.spyOn(window, …)` for browser APIs; module state is + reset in `tests/setup.ts`. +- Packages: `api` tests services against MSW, plus stores and transforms. + `ui` gets `index.test.tsx` + a story per component. diff --git a/.claude/skills/irene-react-patterns/references/websocket.md b/.claude/skills/irene-react-patterns/references/websocket.md new file mode 100644 index 000000000..1551d1011 --- /dev/null +++ b/.claude/skills/irene-react-patterns/references/websocket.md @@ -0,0 +1,69 @@ +# Websocket (`@irene/websocket`) + +Server push becomes cache updates and signals. Read the Normalized cache +section of `api-and-data.md` first: most live updates are just tagged records. + +> `packages/websocket/README.md` is out of date; follow the code. The real +> connection options are `noticeHandlers: { onMessage, onUnreadCount }` (no +> `product`). Counter signals are `'Counter'`. The cache adapter is +> `useNormalizedRecordCache`. + +## Flow + +The connection is Socket.IO, joining room = `user.socket_id`. All event policy +lives in **`cache/dispatch.ts`**: + +| Event | Effect | +| ---------------------- | ------------------------------------------------------------------------- | +| `model_updated` | `cache.write` (every query holding the record updates) + record listeners | +| `model_created` | signal `''` + record listeners (not cached: no list holds it yet) | +| `object` / `newobject` | invalidate queries holding it (300ms debounce) | +| `counter` | signal `'Counter'` | +| `message` | `akNotify` toast | +| `notification` | unread count written into its query | + +The connection opens **once**, in `AuthenticatedLayout` via +`useDashboardWebsocket`. `endSession` closes it. Pages never connect. + +## In a page (pick the first that fits) + +1. **Record changes** → tag it in the service. No page code needed. +2. **List should grow** → `useWebsocketSignal('SubmissionCounter', refetch)`, + or `useWebsocketSignal('submission', invalidate)`. Signal names are typed. +3. **Act on the pushed record** → + `useWebsocketRecord('submission', (s) => prependRecordToPage(queryClient, key, 'submission', s))`. +4. **After your own mutation** → `raiseWebsocketSignal('InvitationCounter')`. +5. **No event exists** → `...pollUntil({ intervalMs, isDone })` on the query + (not used yet). + +Device-farm streams (`holdDeviceSession` etc.) exist but aren't used yet. + +## New server event + +- **New record type**: add it to `API_RECORD_TYPES` (plus `ApiRecordShapes`) + and tag it in its services. If the server sends `object` events for it, + map the plural in `_RECORD_TYPE_BY_OBJECT_TYPE` (`dispatch.ts`). +- **New counter**: add it to `WEBSOCKET_COUNTERS` (`events/index.ts`). +- **New event name**: add it to `WEBSOCKET_EVENTS` with a payload type + (mirror the server's `notify.py`). Add a handler via `_onPayloadWith` in + `dispatch.ts`, and update the event list in `dispatch.test.ts`. UI-facing + events extend `WebsocketNoticeHandlers`. + +## Tests + +```ts +const serverSends = (event: string, payload: unknown) => + act(() => { + websocketTransport.emit(event, payload); + }); + +server.use(http.get(LIST_URL, () => HttpResponse.error())); // only the push can update the UI +serverSends(WEBSOCKET_EVENTS.modelUpdated, { + model_name: 'submission', + data: tagRecordForCaching('submission', updated), +}); +``` + +`websocketTransport` (from `@tests/setup`) is a fake installed for every test. +`.room` shows the joined room. Break the refetch path so the test proves the +push worked. diff --git a/DESIGN-DECISIONS.md b/DESIGN-DECISIONS.md index 9d716279d..daa76e439 100644 --- a/DESIGN-DECISIONS.md +++ b/DESIGN-DECISIONS.md @@ -9,30 +9,47 @@ not when someone notices it. ## Awaiting sign-off -| Change | Where | irene | React | Why | -| ----------------------------------------------------------------- | ------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------- | -| Password fields can be revealed | Every `AkInput` with `type="password"` | No reveal control | An eye button in the field switches between hidden and visible | Passwords are 10 characters minimum and typed twice, which is where typos go unnoticed | -| OIDC error screen offers a way on | `/dashboard/oidc/redirect`, `/dashboard/oidc/authorize` | Illustration and message, no controls | "Dashboard Home" and "Login again" buttons, worded for the session | The screen was a dead end; the only ways on are the client restarting or signing in | -| Return path travels in the URL | `/login` | The blocked URL is kept in `sessionStorage` as `_lastTransitionInfo` | It rides on the URL as `?redirectTo=`, validated as an internal path | A stored value outlives the sign-in it belongs to and can redirect a later session | -| Names are required before sending | `/invite/:token` | First and last name are unvalidated, and the API refuses them empty | Both are required before the request is made | The server already requires them, so the old form spent a round trip to say so | -| Not-found page says why | Any unmatched URL | Heading and a home button | A line saying the link may be broken or the page moved | "Cannot be found" alone leaves the reader unsure whether they mistyped or we broke it | -| Status re-checks on refocus | `/dashboard/status` | Each system is checked once, in the component constructor | Each check runs again when the window is focused | The tab is left open during an outage, reporting what was true when it was opened | -| Appknox mark sized as an icon | `/dashboard/home` | The mark fills the logo slot, up to 225x100px | 40x40px; a whitelabel logo keeps the full slot | On an Appknox host the slot is fed the favicon, a square mark that reads as oversized | -| Outlined buttons are opaque | Every `AkButton` with `variant="outlined"` | Transparent, except the home page's logout button | All of them carry the page background | A transparent secondary button reads as part of whatever sits behind it | -| Disabled buttons show a cursor | Every `AkButton` | `pointer-events: none`, so the cursor is whatever the page behind it has | `cursor-not-allowed`, with pointer suppression left only on anchors | A disabled button that the cursor ignores reads as unresponsive rather than unavailable | -| Failure card names the status | Any route whose guards or loaders fail | No failure card: the error reaches Ember's error route | "Error 500" under the hint, and in the support mail's subject | A user reporting a failure had nothing to quote, and support nothing to search for | -| Status table has fixed widths | `/dashboard/status` | The table lays itself out | System 45%, Status 55% | An unreachable system carries a hint under its status, so that column needs more room | -| Mandated 2FA drops the email line | `/login`, second-factor step | The mandate notice is always followed by "We've sent a OTP code to your email", whatever the factor is | The mandate notice stands alone; the email or app wording follows the factor | `forced` and `type` are separate fields, so half of mandated accounts were sent to an empty inbox | -| Setup requests time out after 30 seconds | The dashboard and account setup queries | No request carries a timeout, so a server that accepts a connection and never replies holds the loading overlay until the browser gives up | The setup queries abandon a request after 30s and land on the failure card | A hung request left the app on a spinner with no message, no status and no retry | -| Loading screen says when a wait runs long | The boot overlay and every route's pending screen | The loading screen shows an illustration and a bar, and says nothing however long it runs | After ten seconds it adds a line, changing at 25s and 40s: "Still getting everything on your dashboard ready...", "Almost there, thanks for bearing with us a moment...", "Hang tight, we are nearly finished getting you in..." | A bar that has been creeping for half a minute reads as broken. The lines reassure rather than explain, since the delay is not the reader's to fix | -| Even margins on the side bar logo | The dashboard side navigation | `3em auto 1em` expanded, `0.5em auto 1em` collapsed | 14px above and below at either width | The logo read as sitting high in its band, and the two widths pushed the items down by different amounts | -| Buttons load in every variant | Every `AkButton` with `loading` | `loading` applies to `filled` only; on `outlined` and `text` it does nothing, not even disable the button | Every variant shows the spinner, disables and sets `aria-busy` | A flag that silently does nothing is a trap; the caller has no way to know the button never became busy | -| A loading button keeps its right icon | Every `AkButton` with `rightIcon` | The spinner replaces the left icon and the right icon is hidden | The spinner replaces the left icon; the right icon stays | The row's width jumps when the trailing mark disappears mid-action | -| Chips sit closer to their icon | Every `AkChip` with `icon` | `0.5em` on the icon and on the label, so 7px between them | 2px between the icon and the label; the outer inset is unchanged | The label read as detached from the mark it belongs to | -| Reporting opens on its first page | `/dashboard/reports` | An index route renders the reporting landing page | Redirects to `/dashboard/reports/generate` | Reporting's landing page is unbuilt, and the generate page is the only screen it offers | -| Security dashboard has a side navigation | `/security/*` | A bar carrying three tabs, and no navigation beside the page | The shared side navigation with its own three items, and the product switcher in it | The product was the only one reached without the navigation every other product has, so leaving it put the switcher out of reach from inside it | -| One navigation width for every product | Every product layout | Reporting stores `reportSidebarState`; every other product shares `sidebarState`, so reporting collapses on its own | One `irene:sidebar-state` for all of them, so collapsing in any product collapses them all | The width is a reading preference, not a property of a product; irene's split means the same person sets it twice | -| Offensive security spaces its navigation like every other product | `/dashboard/offensive-security` | `@isOffsec` puts `offsec-sidenav` on the aside, which zeroes the item list's top margin | The same gap below the switcher that every other product's navigation has | The product has one item today; spacing it differently makes it read as a different navigation rather than the same one with less in it | +| Change | Where | irene | React | Why | +| ----------------------------------------------------------------- | ------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| Password fields can be revealed | Every `AkInput` with `type="password"` | No reveal control | An eye button in the field switches between hidden and visible | Passwords are 10 characters minimum and typed twice, which is where typos go unnoticed | +| OIDC error screen offers a way on | `/dashboard/oidc/redirect`, `/dashboard/oidc/authorize` | Illustration and message, no controls | "Dashboard Home" and "Login again" buttons, worded for the session | The screen was a dead end; the only ways on are the client restarting or signing in | +| Return path travels in the URL | `/login` | The blocked URL is kept in `sessionStorage` as `_lastTransitionInfo` | It rides on the URL as `?redirectTo=`, validated as an internal path | A stored value outlives the sign-in it belongs to and can redirect a later session | +| Names are required before sending | `/invite/:token` | First and last name are unvalidated, and the API refuses them empty | Both are required before the request is made | The server already requires them, so the old form spent a round trip to say so | +| Not-found page says why | Any unmatched URL | Heading and a home button | A line saying the link may be broken or the page moved | "Cannot be found" alone leaves the reader unsure whether they mistyped or we broke it | +| Status re-checks on refocus | `/dashboard/status` | Each system is checked once, in the component constructor | Each check runs again when the window is focused | The tab is left open during an outage, reporting what was true when it was opened | +| Appknox mark sized as an icon | `/dashboard/home` | The mark fills the logo slot, up to 225x100px | 40x40px; a whitelabel logo keeps the full slot | On an Appknox host the slot is fed the favicon, a square mark that reads as oversized | +| Outlined buttons are opaque | Every `AkButton` with `variant="outlined"` | Transparent, except the home page's logout button | All of them carry the page background | A transparent secondary button reads as part of whatever sits behind it | +| Disabled buttons show a cursor | Every `AkButton` | `pointer-events: none`, so the cursor is whatever the page behind it has | `cursor-not-allowed`, with pointer suppression left only on anchors | A disabled button that the cursor ignores reads as unresponsive rather than unavailable | +| Failure card names the status | Any route whose guards or loaders fail | No failure card: the error reaches Ember's error route | "Error 500" under the hint, and in the support mail's subject | A user reporting a failure had nothing to quote, and support nothing to search for | +| Status table has fixed widths | `/dashboard/status` | The table lays itself out | System 45%, Status 55% | An unreachable system carries a hint under its status, so that column needs more room | +| Mandated 2FA drops the email line | `/login`, second-factor step | The mandate notice is always followed by "We've sent a OTP code to your email", whatever the factor is | The mandate notice stands alone; the email or app wording follows the factor | `forced` and `type` are separate fields, so half of mandated accounts were sent to an empty inbox | +| Setup requests time out after 30 seconds | The dashboard and account setup queries | No request carries a timeout, so a server that accepts a connection and never replies holds the loading overlay until the browser gives up | The setup queries abandon a request after 30s and land on the failure card | A hung request left the app on a spinner with no message, no status and no retry | +| Loading screen says when a wait runs long | The boot overlay and every route's pending screen | The loading screen shows an illustration and a bar, and says nothing however long it runs | After ten seconds it adds a line, changing at 25s and 40s: "Still getting everything on your dashboard ready...", "Almost there, thanks for bearing with us a moment...", "Hang tight, we are nearly finished getting you in..." | A bar that has been creeping for half a minute reads as broken. The lines reassure rather than explain, since the delay is not the reader's to fix | +| Even margins on the side bar logo | The dashboard side navigation | `3em auto 1em` expanded, `0.5em auto 1em` collapsed | 14px above and below at either width | The logo read as sitting high in its band, and the two widths pushed the items down by different amounts | +| Buttons load in every variant | Every `AkButton` with `loading` | `loading` applies to `filled` only; on `outlined` and `text` it does nothing, not even disable the button | Every variant shows the spinner, disables and sets `aria-busy` | A flag that silently does nothing is a trap; the caller has no way to know the button never became busy | +| A loading button keeps its right icon | Every `AkButton` with `rightIcon` | The spinner replaces the left icon and the right icon is hidden | The spinner replaces the left icon; the right icon stays | The row's width jumps when the trailing mark disappears mid-action | +| Chips sit closer to their icon | Every `AkChip` with `icon` | `0.5em` on the icon and on the label, so 7px between them | 2px between the icon and the label; the outer inset is unchanged | The label read as detached from the mark it belongs to | +| Reporting opens on its first page | `/dashboard/reports` | An index route renders the reporting landing page | Redirects to `/dashboard/reports/generate` | Reporting's landing page is unbuilt, and the generate page is the only screen it offers | +| Security dashboard has a side navigation | `/security/*` | A bar carrying three tabs, and no navigation beside the page | The shared side navigation with its own three items, and the product switcher in it | The product was the only one reached without the navigation every other product has, so leaving it put the switcher out of reach from inside it | +| One navigation width for every product | Every product layout | Reporting stores `reportSidebarState`; every other product shares `sidebarState`, so reporting collapses on its own | One `irene:sidebar-state` for all of them, so collapsing in any product collapses them all | The width is a reading preference, not a property of a product; irene's split means the same person sets it twice | +| Offensive security spaces its navigation like every other product | `/dashboard/offensive-security` | `@isOffsec` puts `offsec-sidenav` on the aside, which zeroes the item list's top margin | The same gap below the switcher that every other product's navigation has | The product has one item today; spacing it differently makes it read as a different navigation rather than the same one with less in it | +| Tabs show focus as a ring | Every `AkTabsTrigger` | A focused tab takes the same grey tint as a hovered one | A focused tab takes the ring every other control has; hover keeps the tint | Keyboard focus and the pointer resting on a tab looked identical, so a keyboard user could not tell which tab the arrow keys had reached | +| A refused language change always explains itself | `/dashboard/settings/general` | The notification shows the response's `message`, which is empty when the server sends none | The server's message, or "Something went wrong, please try again" when it gives none | An empty notification tells the reader nothing failed | +| A password change signs out directly | `/dashboard/settings/security` | Moves to `/login`, which bounces a still-signed-in session back to the dashboard until the next request is refused and the session-expired notice shows | Ends the session and opens `/login` with "Your password has been changed" | The server has already revoked every token, so the detour through the dashboard and the expiry notice says nothing true | +| Security failures name themselves | `/dashboard/settings/security` | A failed password change asks for `tSomethingWentWrong`, a key irene's translations lack, so it shows a missing-translation message | "Something went wrong, please try again" | A translation key is not a message | +| The authenticator QR code is drawn at full contrast | MFA app setup, `/dashboard/settings/security` | A canvas at 80% opacity on white | An SVG in solid black on white, same size and error correction | Full contrast scans more reliably, and an SVG stays sharp at any zoom | +| The security tab follows the current design system | `/dashboard/settings/security` | Outlined Change Password and Enable buttons; the active MFA method tinted green with a bare tick; hand-drawn square notice boxes | Filled buttons for the actions that move forward (Change Password, Enable), outlined for Disable; an "Enabled" chip beside the active method; notices as `AkAlert`; rounded list and info boxes; the warning about mandated MFA sits above the methods it explains | irene's tab predates the current look, and outlined calls to action read as secondary everywhere else in the product | +| Token-name problems sit under the field | `/dashboard/settings/developersettings` | An empty or duplicate name is reported in a notification | The message appears under the name field, as on every other form | The reader is already looking at the field they need to fix | +| Token dates name the month | `/dashboard/settings/developersettings` | `toLocaleDateString()`, so 03/04/2026 reads as March or April depending on the browser | "Apr 3, 2026", in the active locale | A numeric date is ambiguous between locales | +| Token keys are set in monospace | `/dashboard/settings/developersettings` | The body font | The theme's mono font | A key is copied and compared character by character | +| A refused revoke always explains itself | `/dashboard/settings/developersettings` | The notification reads the response's `message`, which a JSON:API refusal never has, so it is empty | The refusal's first `detail`, or "Something went wrong, please try again" | An empty notification tells the reader nothing | +| Notification preference tooltips are reachable by keyboard | `/dashboard/settings/notification-settings` | The group tooltips hang on bare icons, so only a mouse can open them | Each icon is a button, so Tab reaches it and focus opens the tooltip; the groups are drawn as rounded boxes | The tooltips are the only place that explains how the two groups interact | +| The Mercer download address is fixed | `/dashboard/settings/cyod-settings` | Read from `IRENE_MERCER_DOWNLOAD_URL`, which a deployment can override, defaulting to the public S3 release folder | Always the public S3 release folder, from `MERCER_DOWNLOAD_URL` in `@irene/config/product` | No deployment overrides it, and a thirteenth configuration key means changing every deployment. Add the key if one ever needs a mirror | +| An unconfigured device farm is recognised by a 403 | CYOD device table, `/dashboard/settings/cyod-settings` | Only a 400 counts as "not configured"; mycroft now answers 403, so irene shows "No Device Registered" instead | A 400 or a 403 shows the "not configured" notice | mycroft's `OrganizationCYODConfigured` permission refuses with 403, and telling the user to register a device they cannot register is a dead end | +| Device registration dates follow the locale | CYOD device table | `D MMMM YYYY` in English whatever the language | The named `longDate` format in the active locale | Every other date in the port is formatted through `FORMATS` | +| Account settings share one type scale | `/dashboard/settings/*` | The page title is 14px, smaller than the 16px section titles under it; subsection titles, descriptions and notes vary from tab to tab (`h6`, `subtitle1`, `subtitle2`; 13px or 14px; 10px to 12px) | Page title 18px; section titles `h5`; subsection, group and empty-state titles `subtitle1`; descriptions `body1` muted; row titles `body1` medium; row descriptions `body2` muted; fine print 12px muted; 21px padding on every tab | The tabs were built years apart in irene, so moving between them changed the type at every level | +| The Mercer steps are headed as steps | Register a device drawer, `/dashboard/settings/cyod-settings` | "Your registered devices" above the five setup steps | "How to register a device" | The drawer lists no devices; the heading described a table that is not there | +| Alert body text carries the alert colour | Every `AkAlert`, inline and in a toast | The box is tinted and coloured, but the `AkTypography` inside it defaults to `textPrimary`, so the message is `--text-primary` (`#171717`) on a coloured surface | `AkAlertDescription` inherits the alert's variant colour, so an error message is `text-danger` and a success one `text-success` | A message that is only the variant colour reads as one piece. It also means the slot has no colour of its own: `color="textSecondary"` on it does nothing, and a different colour has to come from `className` | ## Accepted @@ -46,6 +63,10 @@ port carries. | Gap | Where | Note | | -------------------------------------------------------------------- | -------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `PASSWORD_CHANGE_EVENT` is not tracked | `PasswordChange` | irene sends it, and the failure, to PostHog. Analytics is Week 5 work | +| The organization settings page is a route shell | `/dashboard/organization/settings` | The MFA notice links an owner there, so the link needs a destination. The page itself is unbuilt | +| The MFA disable modal keeps one of irene's quirks | `MfaDisable` | Its code step repeats the "MFA can not be disabled" notice. irene's own tests assert it, so the port matches the screen | +| Only the newest ten API tokens are listed | `/dashboard/settings/developersettings` | irene asks for the first page of ten and offers no other, so an account with more cannot see or revoke the older ones here. Ported as is | | `LOGOUT_EVENT` is not tracked | `useLogout` | irene sends it to PostHog. Analytics is Week 5 work | | PostHog is not registered on boot | `setupUserAndOrgContext` | The last of irene's seven ordered `afterModel()` steps; the other six are built | | Pendo is built but unverified | `setupUserAndOrgContext`, `scripts/pendo.ts`, the side navigation | Written against irene, never run against a live subscription. See below | diff --git a/QA-SCENARIOS.md b/QA-SCENARIOS.md index cad33b455..820e3b722 100644 --- a/QA-SCENARIOS.md +++ b/QA-SCENARIOS.md @@ -372,3 +372,57 @@ nothing, so an unported message is visible rather than silent. | Account language | `/login`, sign in with a Japanese account | Dashboard opens in Japanese | | Whitelabel branding | `/login` on a deployment with its own configuration | Its name, logo, favicon and colours | | No branding configured | `/login` on a plain deployment | Appknox name and logo | + +## Account settings + +Every tab has content. + +| Scenario | How to get there | Expected | +| -------------------------- | --------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------- | +| Opens on general | `/dashboard/settings`, or the side navigation's settings item | Lands on `/dashboard/settings/general` with the General tab underlined | +| Switch tabs | Press any tab | The URL and the tab title follow the tab | +| Keyboard | Tab into the row, then the arrow keys, then Enter | Arrows move focus without navigating; Enter opens the focused tab | +| CYOD hidden | Organization without the `cyod` feature | Four tabs: General, Security, Developer Settings, Notification Preferences | +| CYOD shown | Organization with the `cyod` feature | CYOD Settings sits between Developer Settings and Notification Preferences | +| CYOD by URL, tab hidden | `/dashboard/settings/cyod-settings` without the feature | The page opens with no tab underlined, as in irene | +| Account language shown | General tab, signed in as a Japanese account | The language control reads 日本語 | +| Change language | General tab, pick the other language | The page switches at once, the control locks, then the page reloads in that language | +| Language follows account | Change language, then sign in on another browser | That browser opens in the chosen language too | +| Language refused | General tab with the `lang` request failing | The server's message, or "Something went wrong, please try again"; no reload | +| Password fields required | Security tab, press Change Password with the fields empty | "Enter Current Password" and "Enter New Password" under their fields; nothing sent | +| Passwords differ | Security tab, two different new passwords | "Passwords doesnt match" under Confirm Password | +| Wrong current password | Security tab, a wrong current password | The server's message under Current Password | +| Weak new password | Security tab, a new password the server rejects | The server's reasons under New Password | +| Password changed | Security tab, valid passwords | Lands on `/login` with "Your password has been changed"; the old session no longer works | +| MFA methods listed | Security tab | Authenticator App and Email, the active one marked with an "Enabled" chip | +| Enable email MFA | Security tab, no MFA, Enable on Email | Continue emails a code; entering it turns Email on | +| Enable app MFA | Security tab, no MFA, Enable on Authenticator App | QR code to scan; the app's code turns it on | +| Switch email → app | Security tab, Email active, Enable on Authenticator App | Emailed code, then QR, then the app's code | +| Switch app → email | Security tab, app active, Enable on Email | App code, then emailed code | +| Disable MFA | Security tab, Disable on the active method | A code (emailed for Email), then the method turns off | +| Wrong or empty code | Any MFA modal | "Please enter a valid OTP", or "Enter the six digit OTP" when empty | +| MFA mandated | Account in an organization that mandates MFA | No Disable button; a yellow notice says why, with an Organization Settings link for an owner | +| No tokens yet | Developer Settings tab, account with no API tokens | The name field and Generate token button; no table | +| Generate a token | Developer Settings tab, type a name, Generate token | "Personal access token generated successfully."; the token tops the table; the field clears | +| Empty token name | Generate token with the field empty or only spaces | "Please enter the token name" under the field; nothing sent | +| Duplicate token name | Generate a token with a name already used | "Duplicate token name…" under the field | +| Copy a key | Copy icon on a row | "Token Copied!"; the key is on the clipboard | +| Revoke a token | Delete icon on a row, then Delete | Asks first; "Personal access token revoked successfully"; the row goes | +| Cancel a revoke | Delete icon, then Cancel | The modal closes; the token stays | +| More than ten tokens | Account with eleven or more tokens | Only the newest ten are listed, as in irene | +| Preferences shown | Notification Preferences tab | Each toggle matches the account's preference; toggles hold with a spinner until they arrive | +| Flip a preference | Flip any toggle | It moves at once; "Notification preference updated" | +| VA notification on | Turn the VA notification on | SAST, DAST and API Scan turn off and lock; hovering one explains why | +| VA notification off | Turn the VA notification off | The three individual toggles unlock | +| Update refused | Flip a toggle with the request failing | It moves back; "Failed to update notification preference…" | +| Preferences unavailable | Tab with the preferences request failing | "Failed to fetch notification preferences."; every toggle off | +| Group tooltips | Hover or Tab to the info icon beside each group title | Explains how the two groups interact | +| CYOD off | Organization without the `cyod` feature, open `/dashboard/settings/cyod-settings` | No CYOD tab; the URL opens an empty panel | +| Registration off, member | CYOD on, registration off, as a member | "Turn on CYOD", asking them to contact the owner | +| Registration off, owner | The same, as the owner | "Turn on CYOD", pointing at Organization Settings | +| Connected devices | CYOD on, registration on, a device online | The device with its registration date and an "Online" chip; offline devices are left out | +| No device online | No device, or only offline ones | "No Device Registered", pointing at the Register a device button | +| Device farm not configured | Organization with CYOD but no device-farm token | "CYOD device farm is not configured…" | +| Refresh devices | Refresh icon beside the heading | Loading, then the list as it now stands | +| Register a device | Register a device | A drawer with five numbered steps; macOS, Windows and Linux Mercer downloads | +| Copy server URL | Copy icon in step 3 | "Copied to clipboard!"; the API host is on the clipboard | diff --git a/apps/dashboard/package.json b/apps/dashboard/package.json index a7cc3fde2..973b6d43c 100644 --- a/apps/dashboard/package.json +++ b/apps/dashboard/package.json @@ -31,6 +31,7 @@ "@tanstack/react-query": "^5.102.8", "@tanstack/react-router": "^1.170.35", "dayjs": "^1.11.23", + "qrcode.react": "^4.2.0", "react": "^19.3.0", "react-dom": "^19.3.0", "react-google-recaptcha-v3": "^1.11.0", diff --git a/apps/dashboard/src/components/side-nav/index.test.tsx b/apps/dashboard/src/components/side-nav/index.test.tsx index dbd7deb07..a7f765d18 100644 --- a/apps/dashboard/src/components/side-nav/index.test.tsx +++ b/apps/dashboard/src/components/side-nav/index.test.tsx @@ -67,6 +67,41 @@ describe('SideNav', () => { ); }); + it.each([ + '/dashboard/settings/general', + '/dashboard/settings/security', + '/dashboard/settings/developersettings', + '/dashboard/settings/notification-settings', + '/dashboard/settings/cyod-settings', + ])('marks account settings on every one of its tabs: %s', async (path) => { + await renderAtRoute(path); + + await waitFor(() => + expect(navItem(akMT('accountSettings'))).toHaveAttribute('data-status', 'active') + ); + + expect(navItem(akMT('accountSettings'))).toHaveAttribute('aria-current', 'page'); + }); + + it('marks the organization on its settings page, which its link does not lead to', async () => { + await renderAtRoute('/dashboard/organization/settings'); + + await waitFor(() => + expect(navItem(akMT('organization'))).toHaveAttribute('data-status', 'active') + ); + }); + + it('marks nothing else while on a settings tab', async () => { + await renderAtRoute('/dashboard/settings/security'); + + await waitFor(() => + expect(navItem(akMT('accountSettings'))).toHaveAttribute('data-status', 'active') + ); + + expect(navItem(akMT('allProjects'))).not.toHaveAttribute('data-status'); + expect(navItem(akMT('organization'))).not.toHaveAttribute('data-status'); + }); + it('leaves the API documentation out until the organization buys the public APIs', async () => { await openProjects(); diff --git a/apps/dashboard/src/components/side-nav/nav-item.tsx b/apps/dashboard/src/components/side-nav/nav-item.tsx index ea93d59c5..f08560326 100644 --- a/apps/dashboard/src/components/side-nav/nav-item.tsx +++ b/apps/dashboard/src/components/side-nav/nav-item.tsx @@ -1,4 +1,4 @@ -import { Link } from '@tanstack/react-router'; +import { Link, useMatchRoute } from '@tanstack/react-router'; import { Fragment } from 'react'; import { AkChip } from '@irene/ui/ak-chip'; @@ -18,6 +18,12 @@ export interface SideNavItemDefinition { to: FileRouteTypes['to']; search?: Record; badge?: string; + /** + * Other pages, and every page beneath each, that also mark the item as the + * one the account is on: irene's `currentWhen`. The tabs of a settings page + * each have a route of their own, and all of them belong to one item. + */ + activeWhen?: FileRouteTypes['to'][]; } /** @@ -32,6 +38,17 @@ export function SideNavItem({ isCollapsed, onClick, }: Readonly<{ item: SideNavItemDefinition; isCollapsed: boolean; onClick?: () => void }>) { + const matchRoute = useMatchRoute(); + + /* + The link marks itself when the page is its own `to`. On a page it only + covers through `activeWhen` it is marked here instead, with the same two + attributes the router sets, so the styling below reads one state. + */ + const isActiveElsewhere = (item.activeWhen ?? []).some((to) => + Boolean(matchRoute({ to, fuzzy: true })) + ); + return (
  • @@ -40,6 +57,8 @@ export function SideNavItem({ search={item.search} onClick={onClick} aria-label={item.label} + data-status={isActiveElsewhere ? 'active' : undefined} + aria-current={isActiveElsewhere ? 'page' : undefined} className={cn( 'flex w-full items-center gap-2 px-4 py-2.5 hover:bg-hover-light', 'group relative text-foreground', diff --git a/apps/dashboard/src/embed/components/account-settings.tsx b/apps/dashboard/src/embed/components/account-settings.tsx new file mode 100644 index 000000000..4fdb73695 --- /dev/null +++ b/apps/dashboard/src/embed/components/account-settings.tsx @@ -0,0 +1,119 @@ +import { + createMemoryHistory, + createRootRoute, + createRoute, + createRouter, + Outlet, + redirect, + RouterProvider, +} from '@tanstack/react-router'; + +import { useEffect, useState } from 'react'; + +import { getStoredSession } from '@irene/api/utils/session'; + +import { AccountSettingsLayout } from '@/features/account-settings'; +import { CyodSettingsPage } from '@/features/account-settings/pages/cyod-settings'; +import { DeveloperSettingsPage } from '@/features/account-settings/pages/developer-settings'; +import { GeneralSettingsPage } from '@/features/account-settings/pages/general'; +import { NotificationSettingsPage } from '@/features/account-settings/pages/notification-settings'; +import { SecuritySettingsPage } from '@/features/account-settings/pages/security'; + +/* + Account settings, as one component. + + Its tabs are links and it asks which one is open, so unlike a screen that + only reads data it needs a router. That router is built here, for this screen + alone: the paths are the ones the tabs name, and nothing else is in it. The + host renders `` and gives it nothing. + + The history is in memory, so moving between tabs is this screen's business + and the host's own routing never sees it. The address bar is then written to + match, which keeps a tab linkable and the URL honest. +*/ + +const SETTINGS_BASE = '/dashboard/settings'; + +/** Where the screen opens when the address names no tab of this screen. */ +const DEFAULT_TAB = `${SETTINGS_BASE}/general`; + +/** The tab the address names, or the default where it names none of them. */ +function openingTab() { + const { pathname } = window.location; + + return pathname.startsWith(SETTINGS_BASE) ? pathname : DEFAULT_TAB; +} + +const rootRoute = createRootRoute({ component: Outlet }); + +/* + The signed-in account, under the id the panes ask for it by. It matches no + path of its own; it is here so `useSignedInUser` finds the session where it + looks for it. +*/ +const authenticatedRoute = createRoute({ + getParentRoute: () => rootRoute, + id: '_authenticated', + beforeLoad: () => ({ session: getStoredSession() }), +}); + +const settingsRoute = createRoute({ + getParentRoute: () => authenticatedRoute, + path: SETTINGS_BASE, + component: AccountSettingsLayout, +}); + +const tabRoutes = [ + { path: 'general', component: GeneralSettingsPage }, + { path: 'security', component: SecuritySettingsPage }, + { path: 'developersettings', component: DeveloperSettingsPage }, + { path: 'cyod-settings', component: CyodSettingsPage }, + { path: 'notification-settings', component: NotificationSettingsPage }, +].map(({ path, component }) => + createRoute({ getParentRoute: () => settingsRoute, path, component }) +); + +/* The screen has no landing pane; asked for no tab, it opens the general one. */ +const indexRoute = createRoute({ + getParentRoute: () => settingsRoute, + path: '/', + beforeLoad: () => { + throw redirect({ to: DEFAULT_TAB, replace: true }); + }, +}); + +const routeTree = rootRoute.addChildren([ + authenticatedRoute.addChildren([settingsRoute.addChildren([indexRoute, ...tabRoutes])]), +]); + +/** The account settings screen, tabs and all. */ +export function AccountSettings() { + /* Built once per mount, so the screen opens at the address the host is at. */ + const [router] = useState(() => + createRouter({ + routeTree, + history: createMemoryHistory({ initialEntries: [openingTab()] }), + }) + ); + + /* + The address bar follows the open tab. It replaces rather than pushes, so + the tabs add no history entries and Back leaves the screen, and it carries + the existing state object over so the host's own routing keeps its record. + */ + useEffect(() => { + const mirrorTabInAddressBar = () => { + const { pathname } = router.state.location; + + if (pathname !== window.location.pathname) { + window.history.replaceState(window.history.state, '', pathname); + } + }; + + mirrorTabInAddressBar(); + + return router.subscribe('onResolved', mirrorTabInAddressBar); + }, [router]); + + return ; +} diff --git a/apps/dashboard/src/embed/mount-component.ts b/apps/dashboard/src/embed/mount-component.ts index 9ce1a9eb1..89f7ce74c 100644 --- a/apps/dashboard/src/embed/mount-component.ts +++ b/apps/dashboard/src/embed/mount-component.ts @@ -3,6 +3,7 @@ import { createRoot, type Root } from 'react-dom/client'; import { HomePage } from '@/features/dashboard/pages/home'; +import { AccountSettings } from './components/account-settings'; import { EmbedProviders } from './providers'; import { applyEmbedConfig, DEFAULT_ASSET_BASE, linkStylesheet } from './runtime'; import { ScreenContext } from './screen-context'; @@ -18,6 +19,7 @@ type EmbeddableComponent = ComponentType>; either side. */ const COMPONENTS: Record = { + AccountSettings, HomePage, }; diff --git a/apps/dashboard/src/features/account-settings/index.ts b/apps/dashboard/src/features/account-settings/index.ts new file mode 100644 index 000000000..ddb189cb9 --- /dev/null +++ b/apps/dashboard/src/features/account-settings/index.ts @@ -0,0 +1 @@ +export { AccountSettingsLayout } from './layout/account-settings'; diff --git a/apps/dashboard/src/features/account-settings/layout/account-settings.test.tsx b/apps/dashboard/src/features/account-settings/layout/account-settings.test.tsx new file mode 100644 index 000000000..f8907c8af --- /dev/null +++ b/apps/dashboard/src/features/account-settings/layout/account-settings.test.tsx @@ -0,0 +1,98 @@ +import { screen, waitFor } from '@testing-library/react'; +import userEvent from '@testing-library/user-event'; +import { beforeEach, describe, expect, it } from 'vitest'; + +import { configurationStore } from '@irene/api/stores/configuration'; +import { storeSession } from '@irene/api/utils/session'; +import { akMT } from '@irene/translations/intl'; + +import { buildServerConfiguration, buildSession } from '@tests/factories'; +import { mockOrganizationFeatures } from '@tests/organization'; +import { renderAtRoute } from '@tests/render'; + +const tab = (name: string) => screen.getByRole('tab', { name }); + +const tabNames = () => screen.getAllByRole('tab').map((element) => element.textContent); + +describe('AccountSettingsLayout', () => { + beforeEach(() => { + storeSession(buildSession()); + configurationStore.getState().setServerConfiguration(buildServerConfiguration()); + }); + + it('opens on the general tab when no tab is named in the URL', async () => { + const { router } = await renderAtRoute('/dashboard/settings'); + + expect(router.state.location.pathname).toBe('/dashboard/settings/general'); + + expect(await screen.findByRole('tab', { name: akMT('general') })).toHaveAttribute( + 'aria-selected', + 'true' + ); + }); + + it('names the page above its tabs', async () => { + await renderAtRoute('/dashboard/settings/general'); + + expect(await screen.findByText(akMT('accountSettings'))).toBeInTheDocument(); + }); + + it('leaves the CYOD tab out for an organization without the cyod feature', async () => { + await renderAtRoute('/dashboard/settings/general'); + + await screen.findByRole('tablist'); + + expect(tabNames()).toEqual([ + akMT('general'), + akMT('security'), + akMT('developerSettings'), + akMT('notificationPreferences'), + ]); + }); + + it('offers the CYOD tab before notification preferences when the cyod feature is on', async () => { + mockOrganizationFeatures({ cyod: true }); + + await renderAtRoute('/dashboard/settings/general'); + + await screen.findByRole('tablist'); + + expect(tabNames()).toEqual([ + akMT('general'), + akMT('security'), + akMT('developerSettings'), + akMT('cyod.settings.tabLabel'), + akMT('notificationPreferences'), + ]); + }); + + it('selects the tab for the page the URL names', async () => { + await renderAtRoute('/dashboard/settings/developersettings'); + + await screen.findByRole('tablist'); + + expect(tab(akMT('developerSettings'))).toHaveAttribute('aria-selected', 'true'); + expect(tab(akMT('general'))).toHaveAttribute('aria-selected', 'false'); + }); + + it('navigates to a tab’s page when the tab is pressed', async () => { + const { router } = await renderAtRoute('/dashboard/settings/general'); + + await userEvent.click(await screen.findByRole('tab', { name: akMT('security') })); + + await waitFor(() => + expect(router.state.location.pathname).toBe('/dashboard/settings/security') + ); + + expect(tab(akMT('security'))).toHaveAttribute('aria-selected', 'true'); + }); + + it('still renders the CYOD page by URL while its tab is hidden, as irene does', async () => { + await renderAtRoute('/dashboard/settings/cyod-settings'); + + await screen.findByRole('tablist'); + + expect(screen.getByRole('tabpanel')).toBeInTheDocument(); + expect(screen.queryByRole('tab', { selected: true })).not.toBeInTheDocument(); + }); +}); diff --git a/apps/dashboard/src/features/account-settings/layout/account-settings.tsx b/apps/dashboard/src/features/account-settings/layout/account-settings.tsx new file mode 100644 index 000000000..1823f4c5f --- /dev/null +++ b/apps/dashboard/src/features/account-settings/layout/account-settings.tsx @@ -0,0 +1,76 @@ +import { Link, Outlet, useMatchRoute, useRouterState } from '@tanstack/react-router'; + +import { akMT } from '@irene/translations/intl'; +import { AkTabs, AkTabsContent, AkTabsList, AkTabsTrigger } from '@irene/ui/ak-tabs'; +import { AkTypography } from '@irene/ui/ak-typography'; + +import { useOrganization } from '@/hooks/use-organization'; +import type { FileRouteTypes } from '@/routeTree.gen'; + +/* Every page beneath account settings, read from the generated tree. */ +type AccountSettingsRoute = Extract; + +/** One tab in the account settings row. */ +interface AccountSettingsTab { + label: string; + to: AccountSettingsRoute; +} + +/** + * The frame every account settings page sits in: the heading, a tab per page, + * and the active page in the panel under them. + * + * Each tab is a link, so the route decides which tab is active and the tabs + * activate manually: the arrow keys move between them without navigating. + */ +export function AccountSettingsLayout() { + const { features } = useOrganization(); + const matchRoute = useMatchRoute(); + const pathname = useRouterState({ select: (state) => state.location.pathname }); + + /* + Every role registers its own device, so the CYOD tab follows the + organization's `cyod` feature, not the owner's registration switch, which + only blocks new enrolments while the device list stays useful. + */ + const tabs = [ + { label: akMT('general'), to: '/dashboard/settings/general' }, + { label: akMT('security'), to: '/dashboard/settings/security' }, + { label: akMT('developerSettings'), to: '/dashboard/settings/developersettings' }, + features().cyod && { + label: akMT('cyod.settings.tabLabel'), + to: '/dashboard/settings/cyod-settings', + }, + { label: akMT('notificationPreferences'), to: '/dashboard/settings/notification-settings' }, + ].filter((tab): tab is AccountSettingsTab => Boolean(tab)); + + /* + irene leaves the CYOD route reachable when its tab is hidden, so the panel + falls back to the URL and still renders a page that has no tab. + */ + const activeTab = tabs.find((tab) => matchRoute({ to: tab.to }))?.to ?? pathname; + + return ( +
    + + {akMT('accountSettings')} + + + +
    + + {tabs.map((tab) => ( + + {tab.label} + + ))} + +
    + + + + +
    +
    + ); +} diff --git a/apps/dashboard/src/features/account-settings/pages/cyod-settings/components/cyod-settings-skeleton.tsx b/apps/dashboard/src/features/account-settings/pages/cyod-settings/components/cyod-settings-skeleton.tsx new file mode 100644 index 000000000..6dc7036a2 --- /dev/null +++ b/apps/dashboard/src/features/account-settings/pages/cyod-settings/components/cyod-settings-skeleton.tsx @@ -0,0 +1,59 @@ +import { akMT } from '@irene/translations/intl'; +import { AkDivider } from '@irene/ui/ak-divider'; +import { AkSkeleton } from '@irene/ui/ak-skeleton'; + +/* + Every height here is the one the real element takes, so nothing moves when the + page replaces this: the page heading is 16px type, a section heading and its + description are both 14px, the register button is h-9, and the refresh control + is a 30px square. +*/ + +/** A heading with the line under it, as both halves of this page are introduced. */ +function SectionHeadingSkeleton() { + return ( +
    + + + +
    + ); +} + +/** + * Holds the CYOD tab's shape while its code is fetched, so the tab answers the + * click instead of leaving the previous page on screen. + */ +export function CyodSettingsSkeleton() { + return ( +
    + {akMT('loading')} + + + + {/* Device registration, and the control that opens the drawer. */} +
    + + + +
    + + + + {/* The connected device table, and the control that refetches it. */} +
    +
    + + + +
    + + +
    +
    + ); +} diff --git a/apps/dashboard/src/features/account-settings/pages/cyod-settings/components/cyod-setup-step.tsx b/apps/dashboard/src/features/account-settings/pages/cyod-settings/components/cyod-setup-step.tsx new file mode 100644 index 000000000..6cfc0e53e --- /dev/null +++ b/apps/dashboard/src/features/account-settings/pages/cyod-settings/components/cyod-setup-step.tsx @@ -0,0 +1,37 @@ +import { type ReactNode } from 'react'; +import { AkTypography } from '@irene/ui/ak-typography'; + +interface StepProps { + number: number; + title: string; + children?: ReactNode; +} + +/** + * One numbered step of registering a device. + * + * @param props.number - Where it falls in the sequence. + * @param props.title - What to do. + * @param props.children - Anything the step needs beyond its title: links, notes, a value to copy. + */ +export function CYODSetupStep({ number, title, children }: Readonly) { + return ( +
  • + + +
    + {title} + + {children} +
    +
  • + ); +} diff --git a/apps/dashboard/src/features/account-settings/pages/cyod-settings/components/device-table.tsx b/apps/dashboard/src/features/account-settings/pages/cyod-settings/components/device-table.tsx new file mode 100644 index 000000000..736ca13cc --- /dev/null +++ b/apps/dashboard/src/features/account-settings/pages/cyod-settings/components/device-table.tsx @@ -0,0 +1,190 @@ +import { useQuery } from '@tanstack/react-query'; +import { type ReactNode } from 'react'; + +import { getApiErrorStatus } from '@irene/api/utils/errors'; +import { HTTP_STATUS_CODES } from '@irene/constants'; +import { formatDateTime } from '@irene/translations/date-time'; +import { akMT } from '@irene/translations/intl'; +import { AkChip } from '@irene/ui/ak-chip'; +import { AkIcon } from '@irene/ui/ak-icon'; +import { AkIconButton } from '@irene/ui/ak-icon-button'; +import { AkSpinner } from '@irene/ui/ak-spinner'; +import { AkTable } from '@irene/ui/ak-table'; +import { createAkTableColumns } from '@irene/ui/ak-table/helpers'; +import { AkTypography } from '@irene/ui/ak-typography'; +import ProjectListEmpty from '@irene/ui/svgs/project-list-empty.svg?react'; +import type { ApiCyodRegisteredDevice } from '@irene/api/services/organization'; + +import { registeredDevicesOptions } from '@/features/account-settings/queries/cyod'; +import { useOrganization } from '@/hooks/use-organization'; + +/** The statuses that mean the organization has no device farm of its own, rather than a failure. */ +const NOT_CONFIGURED_STATUSES = new Set([ + HTTP_STATUS_CODES.BAD_REQUEST, + HTTP_STATUS_CODES.FORBIDDEN, +]); + +const deviceColumn = createAkTableColumns(); + +const DEVICE_COLUMNS = deviceColumn.columns([ + deviceColumn.display({ + id: 'name', + header: () => akMT('cyod.deviceTable.name'), + meta: { width: '340px' }, + cell: ({ row }) => { + /* The device farm fills different fields for different devices, so the first one present names it. */ + const name = row.original.name || row.original.model || row.original.serial_number; + + return ( + + {name} + + ); + }, + }), + + deviceColumn.accessor('created_on', { + header: () => akMT('cyod.deviceTable.registeredOn'), + meta: { width: '130px' }, + cell: ({ getValue }) => ( + + {formatDateTime(getValue(), 'longDate') || '-'} + + ), + }), + + deviceColumn.accessor('is_connected', { + header: () => akMT('cyod.deviceTable.status'), + meta: { width: '120px', align: 'center' }, + cell: ({ getValue }) => { + const isConnected = getValue(); + + const label = isConnected + ? akMT('cyod.deviceRegistration.online') + : akMT('cyod.deviceRegistration.offline'); + + return ( + + ); + }, + }), +]); + +interface DeviceTableProps { + heading: string; + subheading: string; + emptyHint: ReactNode; +} + +/** + * The account's connected CYOD devices, with a control to ask again. + * + * Only connected devices are listed: the account view is about the device + * this account can scan on now, and an offline one is nothing to act on. + * irene shares this table with the organization's settings, which list every + * device; that page is not built yet, so this one stays here until it is. + * + * @param props.heading - What the table holds. + * @param props.subheading - The line under the heading. + * @param props.emptyHint - What to do when there is no device yet. + */ +export function DeviceTable({ heading, subheading, emptyHint }: Readonly) { + const organizationId = useOrganization().selectedId(); + const devices = useQuery(registeredDevicesOptions(organizationId)); + const isNotConfigured = NOT_CONFIGURED_STATUSES.has(getApiErrorStatus(devices.error) ?? 0); + const connectedDevices = (devices.data ?? []).filter((device) => device.is_connected); + + return ( +
    +
    +
    + {heading} + + {subheading} +
    + + devices.refetch()} + disabled={devices.isFetching} + data-test-cyod-device-refresh + > + + +
    + + {devices.isFetching && ( +
    + + + + {akMT('loading')} + +
    + )} + + {!devices.isFetching && isNotConfigured && ( +
    + + + + {akMT('cyod.deviceRegistration.notConfigured')} + +
    + )} + + {!devices.isFetching && !isNotConfigured && connectedDevices.length > 0 && ( + device.serial_number} + /> + )} + + {!devices.isFetching && !isNotConfigured && connectedDevices.length === 0 && ( +
    +
    + )} +
    + ); +} diff --git a/apps/dashboard/src/features/account-settings/pages/cyod-settings/components/register-device-drawer.tsx b/apps/dashboard/src/features/account-settings/pages/cyod-settings/components/register-device-drawer.tsx new file mode 100644 index 000000000..18b267f54 --- /dev/null +++ b/apps/dashboard/src/features/account-settings/pages/cyod-settings/components/register-device-drawer.tsx @@ -0,0 +1,141 @@ +import { useMemo } from 'react'; + +import { getConfigValue } from '@irene/config'; +import { MERCER_DOWNLOAD_URL } from '@irene/config/product'; +import { akMT } from '@irene/translations/intl'; +import { AkButton } from '@irene/ui/ak-button'; +import { AkDrawerBody, AkDrawerContent, AkDrawerHeader } from '@irene/ui/ak-drawer'; +import { AkIcon } from '@irene/ui/ak-icon'; +import { AkIconButton } from '@irene/ui/ak-icon-button'; +import { AkTypography } from '@irene/ui/ak-typography'; +import type { IconName } from '@irene/ui/icons/sets'; + +import { useCopyToClipboard } from '@/hooks/use-copy-to-clipboard'; + +import { CYODSetupStep } from './cyod-setup-step'; + +/** The Mercer build for each desktop, as irene offers them, with the note under each. */ +const MERCER_DOWNLOADS: { + id: string; + icon: IconName; + fileName: string; + label: () => string; + note: () => string; +}[] = [ + { + id: 'mac', + icon: 'mdi:apple', + fileName: 'Mercer-x86_64.dmg', + label: () => akMT('cyod.settings.downloadMercerMac'), + note: () => akMT('cyod.settings.downloadMercerMacNote'), + }, + { + id: 'windows', + icon: 'mdi:microsoft-windows', + fileName: 'Mercer-windows-x64.exe', + label: () => akMT('cyod.settings.downloadMercerWindows'), + note: () => akMT('cyod.settings.downloadMercerWindowsNote'), + }, + { + id: 'linux', + icon: 'mdi:linux', + fileName: 'mercer.deb', + label: () => akMT('cyod.settings.downloadMercerLinux'), + note: () => akMT('cyod.settings.downloadMercerLinuxNote'), + }, +]; + +/** + * Walks the user through registering a device with Mercer: install it, sign in + * with a personal token and this server's address, register, and run. + * + * It is the drawer's content only; the page holds the drawer and its trigger. + */ +export function RegisterDeviceDrawer() { + const serverUrl = useMemo(() => { + return getConfigValue('IRENE_API_HOST') || window.location.origin; + }, []); + + const { copy } = useCopyToClipboard(); + + return ( + + + + +
    + {akMT('cyod.settings.howToRegister')} + + {akMT('cyod.settings.stepsIntro')} +
    + +
      + + + {akMT('cyod.settings.stepCertificateNote')} + + + + +
      + {MERCER_DOWNLOADS.map((download) => ( +
      + + + + + {download.label()} + + + + + {download.note()} + +
      + ))} +
      + + + {akMT('cyod.settings.stepDownloadNote')} + +
      + + +
      + + {serverUrl} + + + copy(serverUrl)} + data-test-cyod-server-url-copy + > + + +
      + + + {akMT('cyod.settings.stepSignInNote')} + +
      + + + + +
    +
    +
    + ); +} diff --git a/apps/dashboard/src/features/account-settings/pages/cyod-settings/index.test.tsx b/apps/dashboard/src/features/account-settings/pages/cyod-settings/index.test.tsx new file mode 100644 index 000000000..38e92ac3a --- /dev/null +++ b/apps/dashboard/src/features/account-settings/pages/cyod-settings/index.test.tsx @@ -0,0 +1,267 @@ +import { screen, waitFor, within } from '@testing-library/react'; +import userEvent from '@testing-library/user-event'; +import { http, HttpResponse } from 'msw'; +import { beforeEach, describe, expect, it } from 'vitest'; + +import { + OrganizationEndpoints, + type ApiCyodRegisteredDevice, +} from '@irene/api/services/organization'; + +import { configurationStore } from '@irene/api/stores/configuration'; +import { storeSession } from '@irene/api/utils/session'; +import { MERCER_DOWNLOAD_URL } from '@irene/config/product'; +import { HTTP_STATUS_CODES } from '@irene/constants'; +import { akMT } from '@irene/translations/intl'; + +import { + buildCyodRegisteredDevice, + buildServerConfiguration, + buildSession, +} from '@tests/factories'; + +import { mockOrganizationFeatures, mockOrganizationMe } from '@tests/organization'; +import { renderAtRoute } from '@tests/render'; +import { server } from '@tests/server'; + +const CYOD_SETTINGS = '/dashboard/settings/cyod-settings'; + +const REGISTERED_DEVICES_URL = `*/${OrganizationEndpoints.registeredDevices('*')}`; + +/** An organization with CYOD, and with device registration on unless the test turns it off. */ +const withCyod = ({ isRegistrationEnabled = true } = {}) => + mockOrganizationFeatures( + { cyod: true }, + {}, + { cyod_registration_enabled: isRegistrationEnabled } + ); + +const mockDevices = (devices: ApiCyodRegisteredDevice[]) => { + server.use(http.get(REGISTERED_DEVICES_URL, () => HttpResponse.json({ results: devices }))); +}; + +/** The table row a device's name sits in. */ +const deviceRow = async (name: string) => { + const row = (await screen.findByText(name)).closest('tr'); + + if (!row) { + throw new Error(`No row for ${name}`); + } + + return row; +}; + +const deviceSection = () => screen.findByText(akMT('cyod.settings.connectedDevice')); + +describe('CyodSettingsPage', () => { + beforeEach(() => { + storeSession(buildSession()); + configurationStore.getState().setServerConfiguration(buildServerConfiguration()); + mockDevices([]); + }); + + it('renders nothing for an organization without CYOD, even reached by URL', async () => { + await renderAtRoute(CYOD_SETTINGS); + + await screen.findByRole('tablist'); + + expect(screen.queryByText(akMT('cyod.registration.title'))).not.toBeInTheDocument(); + }); + + describe('while registration is off', () => { + it('asks a member to contact the owner', async () => { + withCyod({ isRegistrationEnabled: false }); + + await renderAtRoute(CYOD_SETTINGS); + + expect(await screen.findByText(akMT('cyod.settings.turnOnDesc'))).toBeInTheDocument(); + + expect( + screen.queryByRole('button', { name: akMT('cyod.settings.registerADevice') }) + ).not.toBeInTheDocument(); + }); + + it('points an owner at the organization setting', async () => { + withCyod({ isRegistrationEnabled: false }); + mockOrganizationMe({ is_owner: true }); + + await renderAtRoute(CYOD_SETTINGS); + + expect(await screen.findByText(akMT('cyod.settings.turnOnDescOwner'))).toBeInTheDocument(); + }); + }); + + describe('the connected devices', () => { + it('lists only the devices that are online', async () => { + const online = buildCyodRegisteredDevice({ is_connected: true }); + const offline = buildCyodRegisteredDevice({ is_connected: false }); + + withCyod(); + mockDevices([online, offline]); + + await renderAtRoute(CYOD_SETTINGS); + + const row = await deviceRow(online.name ?? ''); + + expect(within(row).getByText(akMT('cyod.deviceRegistration.online'))).toBeInTheDocument(); + expect(screen.queryByText(offline.name ?? '')).not.toBeInTheDocument(); + }); + + it('names a device by its model, then its serial number, when the farm gives no name', async () => { + const byModel = buildCyodRegisteredDevice({ name: null }); + const bySerial = buildCyodRegisteredDevice({ name: null, model: '' }); + + withCyod(); + mockDevices([byModel, bySerial]); + + await renderAtRoute(CYOD_SETTINGS); + + expect(await screen.findByText(byModel.model)).toBeInTheDocument(); + expect(screen.getByText(bySerial.serial_number)).toBeInTheDocument(); + }); + + it('shows a dash for a device with no registration date', async () => { + const device = buildCyodRegisteredDevice({ created_on: null }); + + withCyod(); + mockDevices([device]); + + await renderAtRoute(CYOD_SETTINGS); + + const row = await deviceRow(device.name ?? ''); + + expect(within(row).getByText('-')).toBeInTheDocument(); + }); + + it('shows the empty state, pointing at the register button, when no device is online', async () => { + withCyod(); + mockDevices([buildCyodRegisteredDevice({ is_connected: false })]); + + await renderAtRoute(CYOD_SETTINGS); + + expect(await screen.findByText(akMT('cyod.deviceTable.emptyTitle'))).toBeInTheDocument(); + }); + + it('says the device farm is not configured when the organization has none of its own', async () => { + withCyod(); + + server.use( + http.get(REGISTERED_DEVICES_URL, () => + HttpResponse.json({ detail: 'not configured' }, { status: HTTP_STATUS_CODES.FORBIDDEN }) + ) + ); + + await renderAtRoute(CYOD_SETTINGS); + + expect( + await screen.findByText(akMT('cyod.deviceRegistration.notConfigured')) + ).toBeInTheDocument(); + }); + + it('asks again for the devices when refreshed', async () => { + const device = buildCyodRegisteredDevice(); + + withCyod(); + await renderAtRoute(CYOD_SETTINGS); + await deviceSection(); + + expect(await screen.findByText(akMT('cyod.deviceTable.emptyTitle'))).toBeInTheDocument(); + + mockDevices([device]); + await userEvent.click(screen.getByRole('button', { name: akMT('refresh') })); + + expect(await screen.findByText(device.name ?? '')).toBeInTheDocument(); + }); + }); + + describe('registering a device', () => { + const openDrawer = async () => { + await userEvent.click( + await screen.findByRole('button', { name: akMT('cyod.settings.registerADevice') }) + ); + + return screen.findByRole('dialog'); + }; + + it('offers Mercer for each desktop from the release folder', async () => { + withCyod(); + + await renderAtRoute(CYOD_SETTINGS); + + const drawer = await openDrawer(); + + expect( + within(drawer).getByRole('link', { name: akMT('cyod.settings.downloadMercerMac') }) + ).toHaveAttribute('href', `${MERCER_DOWNLOAD_URL}/Mercer-x86_64.dmg`); + + expect( + within(drawer).getByRole('link', { name: akMT('cyod.settings.downloadMercerWindows') }) + ).toHaveAttribute('href', `${MERCER_DOWNLOAD_URL}/Mercer-windows-x64.exe`); + + expect( + within(drawer).getByRole('link', { name: akMT('cyod.settings.downloadMercerLinux') }) + ).toHaveAttribute('href', `${MERCER_DOWNLOAD_URL}/mercer.deb`); + }); + + it('copies the server address Mercer signs in to', async () => { + const user = userEvent.setup(); + + withCyod(); + + await renderAtRoute(CYOD_SETTINGS); + + await user.click( + await screen.findByRole('button', { name: akMT('cyod.settings.registerADevice') }) + ); + + const drawer = await screen.findByRole('dialog'); + const serverUrl = drawer.querySelector('[data-test-cyod-server-url]')?.textContent ?? ''; + + await user.click(within(drawer).getByRole('button', { name: akMT('copy') })); + + expect(await screen.findByText(akMT('copiedToClipboard'))).toBeInTheDocument(); + await expect(navigator.clipboard.readText()).resolves.toBe(serverUrl); + expect(serverUrl).not.toBe(''); + }); + + it('heads the steps as instructions, not as a list of devices', async () => { + withCyod(); + + await renderAtRoute(CYOD_SETTINGS); + + const drawer = await openDrawer(); + + expect(within(drawer).getByText(akMT('cyod.settings.howToRegister'))).toBeInTheDocument(); + + expect( + within(drawer).queryByText(akMT('cyod.settings.yourRegisteredDevices')) + ).not.toBeInTheDocument(); + }); + + it('walks through the five steps in order', async () => { + withCyod(); + + await renderAtRoute(CYOD_SETTINGS); + + const drawer = await openDrawer(); + + expect( + within(drawer) + .getAllByRole('listitem') + .map((step) => step.dataset.testCyodStep) + ).toEqual(['1', '2', '3', '4', '5']); + }); + + it('closes from its header', async () => { + withCyod(); + + await renderAtRoute(CYOD_SETTINGS); + + const drawer = await openDrawer(); + + await userEvent.click(within(drawer).getByRole('button', { name: akMT('close') })); + + await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument()); + }); + }); +}); diff --git a/apps/dashboard/src/features/account-settings/pages/cyod-settings/index.tsx b/apps/dashboard/src/features/account-settings/pages/cyod-settings/index.tsx new file mode 100644 index 000000000..ba662b578 --- /dev/null +++ b/apps/dashboard/src/features/account-settings/pages/cyod-settings/index.tsx @@ -0,0 +1,88 @@ +import { akMT } from '@irene/translations/intl'; +import { AkButton } from '@irene/ui/ak-button'; +import { AkDivider } from '@irene/ui/ak-divider'; +import { AkDrawer, AkDrawerTrigger } from '@irene/ui/ak-drawer'; +import { AkTypography } from '@irene/ui/ak-typography'; +import ToggleAutomatedDast from '@irene/ui/svgs/toggle-automated-dast.svg?react'; + +import { useOrganization } from '@/hooks/use-organization'; + +import { DeviceTable } from './components/device-table'; +import { RegisterDeviceDrawer } from './components/register-device-drawer'; + +/** + * The CYOD settings tab of account settings: the device this account can scan + * on, and how to register one with Mercer. + * + * Nothing renders unless the organization has CYOD. irene gates the tab on the + * same feature but leaves this route reachable by URL, so the page checks + * again. Where CYOD is on but the owner has turned registration off, the page + * says so, and tells an owner where to turn it on. + */ +export function CyodSettingsPage() { + const { features, selected, me } = useOrganization(); + + if (!features().cyod) { + return null; + } + + return ( +
    + {akMT('cyod.registration.title')} + + {selected?.cyod_registration_enabled ? ( + <> +
    +
    + + {akMT('cyod.settings.deviceRegistration')} + + + + {akMT('cyod.settings.deviceRegistrationDesc')} + +
    + + + + {akMT('cyod.settings.registerADevice')} + + + + +
    + + + + + + ) : ( +
    +
    + )} +
    + ); +} diff --git a/apps/dashboard/src/features/account-settings/pages/developer-settings/components/copy-token.tsx b/apps/dashboard/src/features/account-settings/pages/developer-settings/components/copy-token.tsx new file mode 100644 index 000000000..5ec9b50c9 --- /dev/null +++ b/apps/dashboard/src/features/account-settings/pages/developer-settings/components/copy-token.tsx @@ -0,0 +1,29 @@ +import { akMT } from '@irene/translations/intl'; +import { AkIcon } from '@irene/ui/ak-icon'; +import { AkIconButton } from '@irene/ui/ak-icon-button'; +import { useCopyToClipboard } from '@/hooks/use-copy-to-clipboard'; + +/** + * Copies a token's key to the clipboard. + * + * @param props.tokenKey - The key to copy. + * @param props.tokenName - The token's name, which names the control for a screen reader. + */ +export function CopyToken({ + tokenKey, + tokenName, +}: Readonly<{ tokenKey: string; tokenName: string }>) { + const { copy } = useCopyToClipboard({ successMessage: akMT('tokenCopied') }); + + return ( + copy(tokenKey)} + aria-label={`${akMT('copy')} ${tokenName}`} + className="text-info" + data-test-personal-token-copy + > + + + ); +} diff --git a/apps/dashboard/src/features/account-settings/pages/developer-settings/components/create-token-form.tsx b/apps/dashboard/src/features/account-settings/pages/developer-settings/components/create-token-form.tsx new file mode 100644 index 000000000..4780b6e23 --- /dev/null +++ b/apps/dashboard/src/features/account-settings/pages/developer-settings/components/create-token-form.tsx @@ -0,0 +1,84 @@ +import { zodResolver } from '@hookform/resolvers/zod'; +import { useMutation, useQueryClient } from '@tanstack/react-query'; +import { useForm } from 'react-hook-form'; + +import { PersonalTokenService } from '@irene/api/services/personal-token'; +import { unlessRateLimited } from '@irene/api/utils/errors'; +import { akMT } from '@irene/translations/intl'; +import { AkButton } from '@irene/ui/ak-button'; +import { AkFormProvider } from '@irene/ui/ak-form'; +import { AkIcon } from '@irene/ui/ak-icon'; +import { AkInput } from '@irene/ui/ak-input'; +import { akNotify } from '@irene/ui/notify'; + +import { + buildPersonalTokenSchema, + PersonalTokenFormField, + type PersonalTokenFormSchema, +} from '@/features/account-settings/schemas/personal-token'; + +import { getFirstJsonApiError } from '@/features/account-settings/pages/developer-settings/utils'; +import { personalTokenKeys } from '@/features/account-settings/queries/personal-token'; + +/** + * Generates an API token under a name. + * + * Names are unique per account: a name already in use is refused with the + * JSON:API code `unique`, which is said under the field. Any other refusal is + * shown as the server words it. + */ +export function CreateTokenForm() { + const queryClient = useQueryClient(); + const personalTokenSchema = buildPersonalTokenSchema(); + + const tokenForm = useForm({ + resolver: zodResolver(personalTokenSchema), + defaultValues: { name: '' }, + reValidateMode: 'onSubmit', + }); + + const createToken = useMutation({ + mutationFn: ({ name }: PersonalTokenFormSchema) => + PersonalTokenService.createPersonalToken(name), + + onSuccess: async () => { + await queryClient.invalidateQueries({ queryKey: personalTokenKeys.list() }); + tokenForm.reset(); + + akNotify.success(akMT('personalTokenGenerated')); + }, + + onError: unlessRateLimited((error) => { + const complaint = getFirstJsonApiError(error); + + if (complaint?.code === 'unique') { + tokenForm.setError('name', { message: akMT('personalTokenNameDuplicate') }); + } else { + akNotify.error(complaint?.detail ?? akMT('somethingWentWrong')); + } + }), + }); + + return ( + +
    createToken.mutate(values))} + data-test-personal-token-form + > + + + + + } + > + {akMT('personalAccessTokenCreate')} + +
    +
    + ); +} diff --git a/apps/dashboard/src/features/account-settings/pages/developer-settings/components/personal-token-list.tsx b/apps/dashboard/src/features/account-settings/pages/developer-settings/components/personal-token-list.tsx new file mode 100644 index 000000000..235a73a7c --- /dev/null +++ b/apps/dashboard/src/features/account-settings/pages/developer-settings/components/personal-token-list.tsx @@ -0,0 +1,87 @@ +import { useQuery } from '@tanstack/react-query'; + +import { formatDateTime } from '@irene/translations/date-time'; +import { akMT } from '@irene/translations/intl'; +import { AkTable } from '@irene/ui/ak-table'; +import { createAkTableColumns } from '@irene/ui/ak-table/helpers'; +import { AkTypography } from '@irene/ui/ak-typography'; +import type { ApiPersonalToken } from '@irene/api/services/personal-token'; + +import { personalTokensOptions } from '@/features/account-settings/queries/personal-token'; + +import { CopyToken } from './copy-token'; +import { RevokeToken } from './revoke-token'; + +const tokenColumn = createAkTableColumns(); + +/* Widths are irene's, in pixels, so a long name or key truncates rather than widening the table. */ +const TOKEN_COLUMNS = tokenColumn.columns([ + tokenColumn.accessor('name', { + header: () => akMT('name'), + meta: { width: '150px' }, + cell: ({ getValue }) => ( + + {getValue()} + + ), + }), + + tokenColumn.accessor('created', { + header: () => akMT('created'), + meta: { width: '120px' }, + cell: ({ getValue }) => ( + + {formatDateTime(getValue(), 'mediumDate')} + + ), + }), + + tokenColumn.accessor('key', { + header: () => akMT('personalTokenKey'), + meta: { width: '350px' }, + cell: ({ getValue }) => ( + + {getValue()} + + ), + }), + + tokenColumn.display({ + id: 'copy', + header: () => akMT('copy'), + meta: { align: 'center' }, + cell: ({ row }) => , + }), + + tokenColumn.display({ + id: 'delete', + header: () => akMT('delete'), + meta: { align: 'center' }, + cell: ({ row }) => , + }), +]); + +/** + * The account's API tokens: a form to generate one, and a table of the + * newest ten with their keys. irene shows no table until there is a token. + */ +export function PersonalTokenList() { + const { data: tokens = [] } = useQuery(personalTokensOptions()); + + if (tokens.length === 0) { + return null; + } + + return ( + token.id} + wrapperClassName="max-w-212.5" + data-test-personal-token-table + /> + ); +} diff --git a/apps/dashboard/src/features/account-settings/pages/developer-settings/components/revoke-token.tsx b/apps/dashboard/src/features/account-settings/pages/developer-settings/components/revoke-token.tsx new file mode 100644 index 000000000..4230e0013 --- /dev/null +++ b/apps/dashboard/src/features/account-settings/pages/developer-settings/components/revoke-token.tsx @@ -0,0 +1,84 @@ +import { useMutation, useQueryClient } from '@tanstack/react-query'; + +import { + AkModal, + AkModalBody, + AkModalClose, + AkModalContent, + AkModalFooter, + AkModalHeader, + AkModalTrigger, +} from '@irene/ui/ak-modal'; + +import { PersonalTokenService, type ApiPersonalToken } from '@irene/api/services/personal-token'; +import { unlessRateLimited } from '@irene/api/utils/errors'; +import { akMT } from '@irene/translations/intl'; +import { AkButton } from '@irene/ui/ak-button'; +import { AkIcon } from '@irene/ui/ak-icon'; +import { AkIconButton } from '@irene/ui/ak-icon-button'; +import { AkTypography } from '@irene/ui/ak-typography'; +import { akNotify } from '@irene/ui/notify'; + +import { getFirstJsonApiError } from '@/features/account-settings/pages/developer-settings/utils'; +import { personalTokenKeys } from '@/features/account-settings/queries/personal-token'; + +/** + * Revokes a token once the user confirms, since a revoked token cannot be + * brought back and anything calling the API with it stops working. + * + * The modal stays open while the request runs and closes once the list has + * reloaded, as irene's confirm box does. + * + * @param props.token - The token to revoke. + */ +export function RevokeToken({ token }: Readonly<{ token: ApiPersonalToken }>) { + const queryClient = useQueryClient(); + + const revoke = useMutation({ + mutationFn: () => PersonalTokenService.revokePersonalToken(token.id), + + onSuccess: async () => { + await queryClient.invalidateQueries({ queryKey: personalTokenKeys.list() }); + akNotify.success(akMT('personalTokenRevoked')); + }, + + onError: unlessRateLimited((error) => { + akNotify.error(getFirstJsonApiError(error)?.detail ?? akMT('somethingWentWrong')); + }), + }); + + return ( + + + + + + + + + + + + {akMT('confirmBox.revokePersonalToken')} + + + + revoke.mutate()}> + {akMT('delete')} + + + + + {akMT('cancel')} + + + + + + ); +} diff --git a/apps/dashboard/src/features/account-settings/pages/developer-settings/index.test.tsx b/apps/dashboard/src/features/account-settings/pages/developer-settings/index.test.tsx new file mode 100644 index 000000000..d088efab0 --- /dev/null +++ b/apps/dashboard/src/features/account-settings/pages/developer-settings/index.test.tsx @@ -0,0 +1,286 @@ +import { faker } from '@faker-js/faker'; +import { screen, waitFor, within } from '@testing-library/react'; +import userEvent from '@testing-library/user-event'; +import { http, HttpResponse } from 'msw'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; + +import { PersonalTokenEndpoints, type ApiPersonalToken } from '@irene/api/services/personal-token'; +import { configurationStore } from '@irene/api/stores/configuration'; +import { storeSession } from '@irene/api/utils/session'; +import { HTTP_STATUS_CODES } from '@irene/constants'; +import { akMT } from '@irene/translations/intl'; + +import { + buildPersonalToken, + buildServerConfiguration, + buildSession, + toPersonalTokenResource, +} from '@tests/factories'; + +import { renderAtRoute } from '@tests/render'; +import { buildAPITestURL, server } from '@tests/server'; + +const DEVELOPER_SETTINGS = '/dashboard/settings/developersettings'; + +const LIST_URL = buildAPITestURL(PersonalTokenEndpoints.list()); + +/** Answers the list with these tokens, until the test answers it again. */ +const mockTokens = (tokens: ApiPersonalToken[]) => { + server.use( + http.get(LIST_URL, () => HttpResponse.json({ data: tokens.map(toPersonalTokenResource) })) + ); +}; + +/** A JSON:API refusal carrying one complaint. */ +const jsonApiRefusal = (complaint: { code?: string; detail?: string }) => + HttpResponse.json({ errors: [complaint] }, { status: HTTP_STATUS_CODES.BAD_REQUEST }); + +const nameInput = () => screen.findByRole('textbox', { name: akMT('name') }); + +const generate = async (name: string) => { + await userEvent.type(await nameInput(), name); + await userEvent.click(screen.getByRole('button', { name: akMT('personalAccessTokenCreate') })); +}; + +const tokenRow = async (token: ApiPersonalToken) => { + const cell = await screen.findByText(token.name); + const row = cell.closest('tr'); + + if (!row) { + throw new Error(`No row for ${token.name}`); + } + + return row; +}; + +describe('DeveloperSettingsPage', () => { + beforeEach(() => { + storeSession(buildSession()); + configurationStore.getState().setServerConfiguration(buildServerConfiguration()); + mockTokens([]); + }); + + afterEach(() => { + vi.restoreAllMocks(); + }); + + describe('the list of tokens', () => { + it('shows no table until the account has a token', async () => { + await renderAtRoute(DEVELOPER_SETTINGS); + + expect(await nameInput()).toBeInTheDocument(); + expect(screen.queryByRole('table')).not.toBeInTheDocument(); + }); + + it('lists each token with its name and key', async () => { + const tokens = [buildPersonalToken(), buildPersonalToken()]; + + mockTokens(tokens); + + await renderAtRoute(DEVELOPER_SETTINGS); + + for (const token of tokens) { + const row = await tokenRow(token); + + expect(within(row).getByText(token.key)).toBeInTheDocument(); + } + }); + + it('leaves the date blank rather than writing "Invalid Date" when the server sends one it cannot read', async () => { + const token = buildPersonalToken({ created: 'not-a-date' }); + + mockTokens([token]); + + await renderAtRoute(DEVELOPER_SETTINGS); + + expect(await tokenRow(token)).not.toHaveTextContent('Invalid Date'); + }); + }); + + describe('generating a token', () => { + it('sends the name, then lists the new token', async () => { + const token = buildPersonalToken(); + let body: unknown; + + server.use( + http.post(LIST_URL, async ({ request }) => { + body = await request.json(); + mockTokens([token]); + + return HttpResponse.json({ data: toPersonalTokenResource(token) }); + }) + ); + + await renderAtRoute(DEVELOPER_SETTINGS); + await generate(token.name); + + expect(await tokenRow(token)).toBeInTheDocument(); + expect(body).toEqual({ name: token.name }); + expect(await screen.findByText(akMT('personalTokenGenerated'))).toBeInTheDocument(); + expect(await nameInput()).toHaveValue(''); + }); + + it('asks for a name rather than sending one that is only spaces', async () => { + let wasSent = false; + + server.use( + http.post(LIST_URL, () => { + wasSent = true; + + return HttpResponse.json({}); + }) + ); + + await renderAtRoute(DEVELOPER_SETTINGS); + await generate(' '); + + expect(await screen.findByText(akMT('enterTokenName'))).toBeInTheDocument(); + expect(wasSent).toBe(false); + }); + + it('says so under the field when the name is already taken', async () => { + server.use(http.post(LIST_URL, () => jsonApiRefusal({ code: 'unique', detail: 'taken' }))); + + await renderAtRoute(DEVELOPER_SETTINGS); + await generate(faker.word.words(2)); + + expect(await screen.findByText(akMT('personalTokenNameDuplicate'))).toBeInTheDocument(); + }); + + it('shows any other refusal as the server words it', async () => { + const detail = faker.lorem.sentence(); + + server.use(http.post(LIST_URL, () => jsonApiRefusal({ code: 'invalid', detail }))); + + await renderAtRoute(DEVELOPER_SETTINGS); + await generate(faker.word.words(2)); + + expect(await screen.findByText(detail)).toBeInTheDocument(); + }); + + it('says something went wrong when the refusal explains nothing', async () => { + server.use( + http.post(LIST_URL, () => + HttpResponse.json({}, { status: HTTP_STATUS_CODES.INTERNAL_SERVER_ERROR }) + ) + ); + + await renderAtRoute(DEVELOPER_SETTINGS); + await generate(faker.word.words(2)); + + expect(await screen.findByText(akMT('somethingWentWrong'))).toBeInTheDocument(); + }); + }); + + describe('copying a key', () => { + it('puts the key on the clipboard and says so', async () => { + const user = userEvent.setup(); + const token = buildPersonalToken(); + + mockTokens([token]); + + await renderAtRoute(DEVELOPER_SETTINGS); + + await user.click( + within(await tokenRow(token)).getByRole('button', { name: `${akMT('copy')} ${token.name}` }) + ); + + expect(await screen.findByText(akMT('tokenCopied'))).toBeInTheDocument(); + await expect(navigator.clipboard.readText()).resolves.toBe(token.key); + }); + + it('says so when the browser refuses the clipboard', async () => { + const user = userEvent.setup(); + const token = buildPersonalToken(); + + mockTokens([token]); + vi.spyOn(navigator.clipboard, 'writeText').mockRejectedValue(new Error('denied')); + + await renderAtRoute(DEVELOPER_SETTINGS); + + await user.click( + within(await tokenRow(token)).getByRole('button', { name: `${akMT('copy')} ${token.name}` }) + ); + + expect(await screen.findByText(akMT('pleaseTryAgain'))).toBeInTheDocument(); + }); + }); + + describe('revoking a token', () => { + const openRevoke = async (token: ApiPersonalToken) => { + await userEvent.click( + within(await tokenRow(token)).getByRole('button', { + name: `${akMT('delete')} ${token.name}`, + }) + ); + + return screen.findByRole('dialog'); + }; + + it('asks first, then revokes the token and drops it from the list', async () => { + const token = buildPersonalToken(); + let wasRevoked = false; + + mockTokens([token]); + + server.use( + http.delete(buildAPITestURL(PersonalTokenEndpoints.detail(token.id)), () => { + wasRevoked = true; + mockTokens([]); + + return new HttpResponse(null, { status: HTTP_STATUS_CODES.NO_CONTENT }); + }) + ); + + await renderAtRoute(DEVELOPER_SETTINGS); + + const dialog = await openRevoke(token); + + expect(dialog).toHaveTextContent(akMT('confirmBox.revokePersonalToken')); + expect(wasRevoked).toBe(false); + + await userEvent.click(within(dialog).getByRole('button', { name: akMT('delete') })); + + expect(await screen.findByText(akMT('personalTokenRevoked'))).toBeInTheDocument(); + await waitFor(() => expect(screen.queryByText(token.name)).not.toBeInTheDocument()); + expect(screen.queryByRole('dialog')).not.toBeInTheDocument(); + }); + + it('keeps the token when the user cancels', async () => { + const token = buildPersonalToken(); + + mockTokens([token]); + + await renderAtRoute(DEVELOPER_SETTINGS); + + const dialog = await openRevoke(token); + + await userEvent.click(within(dialog).getByRole('button', { name: akMT('cancel') })); + + await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument()); + expect(screen.getByText(token.name)).toBeInTheDocument(); + }); + + it('shows the server’s refusal and keeps the modal open', async () => { + const token = buildPersonalToken(); + const detail = faker.lorem.sentence(); + + mockTokens([token]); + + server.use( + http.delete(buildAPITestURL(PersonalTokenEndpoints.detail(token.id)), () => + jsonApiRefusal({ detail }) + ) + ); + + await renderAtRoute(DEVELOPER_SETTINGS); + + const dialog = await openRevoke(token); + + await userEvent.click(within(dialog).getByRole('button', { name: akMT('delete') })); + + expect(await screen.findByText(detail)).toBeInTheDocument(); + expect(screen.getByRole('dialog')).toBeInTheDocument(); + }); + }); +}); diff --git a/apps/dashboard/src/features/account-settings/pages/developer-settings/index.tsx b/apps/dashboard/src/features/account-settings/pages/developer-settings/index.tsx new file mode 100644 index 000000000..4595c03e3 --- /dev/null +++ b/apps/dashboard/src/features/account-settings/pages/developer-settings/index.tsx @@ -0,0 +1,28 @@ +import { akMT } from '@irene/translations/intl'; +import { AkDivider } from '@irene/ui/ak-divider'; +import { AkTypography } from '@irene/ui/ak-typography'; + +import { CreateTokenForm } from './components/create-token-form'; +import { PersonalTokenList } from './components/personal-token-list'; + +/** + * The developer settings tab of account settings: the API tokens the account + * has generated, and a form to generate another. + */ +export function DeveloperSettingsPage() { + return ( +
    +
    + {akMT('personalAccessTokens')} + + {akMT('personalAccessTokenDesc')} +
    + + + + + + +
    + ); +} diff --git a/apps/dashboard/src/features/account-settings/pages/developer-settings/utils.ts b/apps/dashboard/src/features/account-settings/pages/developer-settings/utils.ts new file mode 100644 index 000000000..c62543afe --- /dev/null +++ b/apps/dashboard/src/features/account-settings/pages/developer-settings/utils.ts @@ -0,0 +1,11 @@ +import type { ApiJsonApiError, ApiJsonApiErrorResponse } from '@irene/api/services/personal-token'; +import { getApiErrorPayload } from '@irene/api/utils/errors'; + +/** + * The first complaint in a JSON:API refusal, which is the one irene reads. + * + * @param error - Whatever the request rejected with. + * @returns The complaint, or undefined when the body holds none. + */ +export const getFirstJsonApiError = (error: unknown): ApiJsonApiError | undefined => + getApiErrorPayload(error)?.errors?.[0]; diff --git a/apps/dashboard/src/features/account-settings/pages/general/components/select-language.tsx b/apps/dashboard/src/features/account-settings/pages/general/components/select-language.tsx new file mode 100644 index 000000000..98b9c5fa3 --- /dev/null +++ b/apps/dashboard/src/features/account-settings/pages/general/components/select-language.tsx @@ -0,0 +1,85 @@ +import { useIsMutating, useMutation } from '@tanstack/react-query'; + +import { + AkSelect, + AkSelectContent, + AkSelectItem, + AkSelectTrigger, + AkSelectValue, +} from '@irene/ui/ak-select'; + +import { UserService } from '@irene/api/services/user'; +import { getApiErrorMessage, unlessRateLimited } from '@irene/api/utils/errors'; +import { akMT, getLocale, setLocale } from '@irene/translations/intl'; +import { isSupportedLocale, LOCALES, storeLocale, type Locale } from '@irene/translations/locale'; +import { AkTypography } from '@irene/ui/ak-typography'; +import { akNotify } from '@irene/ui/notify'; + +import { userKeys } from '@/queries/user'; + +/** What each locale calls itself, so a reader finds their own language in the list. */ +const LOCALE_NAMES: Record string> = { + en: () => akMT('languageEnglish'), + ja: () => akMT('languageJapanese'), +}; + +/** + * Sets the language the account reads the product in. + * + * The choice is the account's, saved on the server, unlike the signed-out + * pages' switcher, which only this browser remembers. The page switches at + * once, then reloads when the server has it, as irene does, so every + * server-translated text (vulnerability descriptions among them) is fetched + * again in the new language. + * + * Switching the locale renders the app again from the translations provider + * down, so nothing here is held in component state: the value is the active + * locale, which sign-in set from the account's `lang`, and the pending save is + * read from the mutation cache, which outlives the remount. + */ +export function SelectLanguage() { + const isSaving = useIsMutating({ mutationKey: userKeys.language() }) > 0; + + const saveLanguage = useMutation({ + mutationKey: userKeys.language(), + mutationFn: UserService.setLanguage, + onError: unlessRateLimited((error) => { + akNotify.error(getApiErrorMessage(error) ?? akMT('somethingWentWrong')); + }), + }); + + const chooseLanguage = async (value: string) => { + if (!isSupportedLocale(value)) { + return; + } + + saveLanguage.mutate(value); + storeLocale(value); + + await setLocale(value); + }; + + return ( +
    +
    + {akMT('language')} + + {akMT('selectLanguage')} +
    + + + + + + + + {LOCALES.map((option) => ( + + {LOCALE_NAMES[option]()} + + ))} + + +
    + ); +} diff --git a/apps/dashboard/src/features/account-settings/pages/general/index.test.tsx b/apps/dashboard/src/features/account-settings/pages/general/index.test.tsx new file mode 100644 index 000000000..b9e471fac --- /dev/null +++ b/apps/dashboard/src/features/account-settings/pages/general/index.test.tsx @@ -0,0 +1,166 @@ +import { faker } from '@faker-js/faker'; +import { act, screen, waitFor } from '@testing-library/react'; +import userEvent from '@testing-library/user-event'; +import { http, HttpResponse } from 'msw'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; + +import { UserEndpoints, type ApiUser } from '@irene/api/services/user'; +import { configurationStore } from '@irene/api/stores/configuration'; +import { storeSession } from '@irene/api/utils/session'; +import { HTTP_STATUS_CODES } from '@irene/constants'; +import { akMT, getLocale, setLocale } from '@irene/translations/intl'; + +import { + buildServerConfiguration, + buildSession, + buildUser, + buildUserResponse, +} from '@tests/factories'; + +import { renderAtRoute } from '@tests/render'; +import { buildAPITestURL, server } from '@tests/server'; + +const GENERAL_SETTINGS = '/dashboard/settings/general'; + +const LANGUAGE_URL = buildAPITestURL(UserEndpoints.language()); + +const session = buildSession(); + +/** Answers the signed-in account with this one, so the test decides its language. */ +const mockSignedInUser = (user: ApiUser) => { + server.use( + http.get(`*/${UserEndpoints.detail(session.userId)}`, () => + HttpResponse.json(buildUserResponse(user)) + ) + ); +}; + +/** Stands in for the reload the page does once the server has the language. */ +const stubReload = () => { + const reload = vi.fn(); + + vi.spyOn(window, 'location', 'get').mockReturnValue({ ...window.location, reload }); + + return reload; +}; + +const languageSelect = () => screen.findByRole('combobox', { name: akMT('language') }); + +const pickJapanese = async () => { + await userEvent.click(await languageSelect()); + await userEvent.click(await screen.findByRole('option', { name: akMT('languageJapanese') })); +}; + +describe('GeneralSettingsPage', () => { + beforeEach(() => { + storeSession(session); + configurationStore.getState().setServerConfiguration(buildServerConfiguration()); + mockSignedInUser(buildUser({ lang: 'en' })); + }); + + afterEach(async () => { + vi.restoreAllMocks(); + + // Inside act: the provider re-renders the tree that is still mounted. + await act(async () => setLocale('en')); + }); + + it('explains the language setting above the control', async () => { + await renderAtRoute(GENERAL_SETTINGS); + + expect(await screen.findByText(akMT('selectLanguage'))).toBeInTheDocument(); + expect(await languageSelect()).toBeInTheDocument(); + }); + + it('shows the language the account is set to', async () => { + mockSignedInUser(buildUser({ lang: 'ja' })); + + await renderAtRoute(GENERAL_SETTINGS); + + expect(await languageSelect()).toHaveTextContent(akMT('languageJapanese')); + }); + + it('saves the chosen language on the account, then reloads', async () => { + const reload = stubReload(); + let savedLanguage: string | null = null; + + server.use( + http.post(LANGUAGE_URL, async ({ request }) => { + savedLanguage = new URLSearchParams(await request.text()).get('lang'); + + return HttpResponse.json({}); + }) + ); + + await renderAtRoute(GENERAL_SETTINGS); + await pickJapanese(); + + await waitFor(() => expect(reload).toHaveBeenCalledOnce()); + expect(savedLanguage).toBe('ja'); + }); + + it('switches the page to the chosen language before the server answers', async () => { + stubReload(); + server.use(http.post(LANGUAGE_URL, () => new Promise(() => undefined))); + + await renderAtRoute(GENERAL_SETTINGS); + await pickJapanese(); + + await waitFor(() => expect(getLocale()).toBe('ja')); + expect(await screen.findByText(akMT('selectLanguage'))).toBeInTheDocument(); + }); + + it('keeps the chosen language in the control once the page has switched to it', async () => { + stubReload(); + server.use(http.post(LANGUAGE_URL, () => new Promise(() => undefined))); + + await renderAtRoute(GENERAL_SETTINGS); + await pickJapanese(); + + await waitFor(async () => + expect(await languageSelect()).toHaveTextContent(akMT('languageJapanese')) + ); + }); + + it('holds the control while the language is being saved', async () => { + stubReload(); + server.use(http.post(LANGUAGE_URL, () => new Promise(() => undefined))); + + await renderAtRoute(GENERAL_SETTINGS); + await pickJapanese(); + + await waitFor(async () => expect(await languageSelect()).toBeDisabled()); + }); + + it('shows the server’s message and stays put when the language is refused', async () => { + const reload = stubReload(); + const message = faker.lorem.sentence(); + + server.use( + http.post(LANGUAGE_URL, () => + HttpResponse.json({ message }, { status: HTTP_STATUS_CODES.BAD_REQUEST }) + ) + ); + + await renderAtRoute(GENERAL_SETTINGS); + await pickJapanese(); + + expect(await screen.findByText(message)).toBeInTheDocument(); + expect(reload).not.toHaveBeenCalled(); + }); + + it('falls back to a general message when the refusal explains nothing', async () => { + stubReload(); + + server.use( + http.post(LANGUAGE_URL, () => + HttpResponse.json({}, { status: HTTP_STATUS_CODES.INTERNAL_SERVER_ERROR }) + ) + ); + + await renderAtRoute(GENERAL_SETTINGS); + await pickJapanese(); + + expect(await screen.findByText(akMT('somethingWentWrong'))).toBeInTheDocument(); + }); +}); diff --git a/apps/dashboard/src/features/account-settings/pages/general/index.tsx b/apps/dashboard/src/features/account-settings/pages/general/index.tsx new file mode 100644 index 000000000..cbe8750a0 --- /dev/null +++ b/apps/dashboard/src/features/account-settings/pages/general/index.tsx @@ -0,0 +1,13 @@ +import { SelectLanguage } from './components/select-language'; + +/** + * The general tab of account settings. It holds the language setting alone, + * as irene's does. + */ +export function GeneralSettingsPage() { + return ( +
    + +
    + ); +} diff --git a/apps/dashboard/src/features/account-settings/pages/notification-settings/components/settings-item.tsx b/apps/dashboard/src/features/account-settings/pages/notification-settings/components/settings-item.tsx new file mode 100644 index 000000000..948b4f6a8 --- /dev/null +++ b/apps/dashboard/src/features/account-settings/pages/notification-settings/components/settings-item.tsx @@ -0,0 +1,75 @@ +import { useId } from 'react'; + +import { akMT } from '@irene/translations/intl'; +import { AkSpinner } from '@irene/ui/ak-spinner'; +import { AkToggle } from '@irene/ui/ak-toggle'; +import { AkTooltip } from '@irene/ui/ak-tooltip'; +import { AkTypography } from '@irene/ui/ak-typography'; + +interface SettingsItemProps { + title: string; + description: string; + isEnabled: boolean; + isLocked: boolean; + isLoading: boolean; + onToggle: (isEnabled: boolean) => void; +} + +/** + * One email preference: what it sends, and the toggle that turns it on. + * + * A locked preference is one the VA notification overrides. Its toggle is + * disabled and explains why on hover; the tooltip hangs on a wrapper, since a + * disabled button takes no pointer events of its own. + * + * @param props.title - What it sends. + * @param props.description - When it sends it. + * @param props.isEnabled - Whether it is on. + * @param props.isLocked - Whether the VA notification overrides it. + * @param props.isLoading - Whether a request is under way, which holds the toggle. + * @param props.onToggle - Called with the new state. + */ +export function SettingsItem({ + title, + description, + isEnabled, + isLocked, + isLoading, + onToggle, +}: Readonly) { + const descriptionId = useId(); + + return ( +
    +
    + {title} + + + {description} + +
    + +
    + {isLoading && } + + + + + + +
    +
    + ); +} diff --git a/apps/dashboard/src/features/account-settings/pages/notification-settings/index.test.tsx b/apps/dashboard/src/features/account-settings/pages/notification-settings/index.test.tsx new file mode 100644 index 000000000..dd2754228 --- /dev/null +++ b/apps/dashboard/src/features/account-settings/pages/notification-settings/index.test.tsx @@ -0,0 +1,182 @@ +import { screen, waitFor } from '@testing-library/react'; +import userEvent from '@testing-library/user-event'; +import { http, HttpResponse } from 'msw'; +import { beforeEach, describe, expect, it } from 'vitest'; + +import { + NotificationPreferenceEndpoints, + type ApiVaNotificationPreference, +} from '@irene/api/services/notification-preference'; + +import { configurationStore } from '@irene/api/stores/configuration'; +import { storeSession } from '@irene/api/utils/session'; +import { HTTP_STATUS_CODES } from '@irene/constants'; +import { akMT } from '@irene/translations/intl'; + +import { + buildServerConfiguration, + buildSession, + buildVaNotificationPreference, +} from '@tests/factories'; + +import { renderAtRoute } from '@tests/render'; +import { buildAPITestURL, server } from '@tests/server'; + +const NOTIFICATION_SETTINGS = '/dashboard/settings/notification-settings'; + +const PREFERENCE_URL = buildAPITestURL(NotificationPreferenceEndpoints.email()); +const UPDATE_URL = buildAPITestURL(NotificationPreferenceEndpoints.updateVa()); + +const mockPreference = (preference: ApiVaNotificationPreference) => { + server.use(http.get(PREFERENCE_URL, () => HttpResponse.json(preference))); +}; + +const toggle = (name: string) => screen.findByRole('switch', { name }); + +/** Waits for the preferences to arrive, which is when the toggles stop holding. */ +const settled = () => + waitFor(() => + expect( + screen.getByRole('switch', { name: akMT('accountNotifSettings.vaNotificationTitle') }) + ).toBeEnabled() + ); + +describe('NotificationSettingsPage', () => { + beforeEach(() => { + storeSession(buildSession()); + configurationStore.getState().setServerConfiguration(buildServerConfiguration()); + }); + + it('shows each preference as the account has it', async () => { + const preference = buildVaNotificationPreference({ + all_va_completed: false, + static_scan_completed: true, + dynamic_scan_completed: false, + }); + + mockPreference(preference); + + await renderAtRoute(NOTIFICATION_SETTINGS); + await settled(); + + expect(await toggle(akMT('accountNotifSettings.staticScanTitle'))).toBeChecked(); + expect(await toggle(akMT('accountNotifSettings.dynamicScanTitle'))).not.toBeChecked(); + }); + + it('locks the individual scan toggles while the VA notification is on', async () => { + mockPreference(buildVaNotificationPreference({ all_va_completed: true })); + + await renderAtRoute(NOTIFICATION_SETTINGS); + await settled(); + + expect(await toggle(akMT('accountNotifSettings.staticScanTitle'))).toBeDisabled(); + expect(await toggle(akMT('accountNotifSettings.apiScanTitle'))).toBeDisabled(); + }); + + it('sends only the preference that was flipped, and shows what the server now holds', async () => { + mockPreference( + buildVaNotificationPreference({ all_va_completed: false, api_scan_completed: false }) + ); + + let body: unknown; + + server.use( + http.put(UPDATE_URL, async ({ request }) => { + body = await request.json(); + + return HttpResponse.json( + buildVaNotificationPreference({ all_va_completed: false, api_scan_completed: true }) + ); + }) + ); + + await renderAtRoute(NOTIFICATION_SETTINGS); + await settled(); + await userEvent.click(await toggle(akMT('accountNotifSettings.apiScanTitle'))); + + expect( + await screen.findByText(akMT('accountNotifSettings.notificationPreferenceUpdated')) + ).toBeInTheDocument(); + + expect(body).toEqual({ api_scan_completed: true }); + expect(await toggle(akMT('accountNotifSettings.apiScanTitle'))).toBeChecked(); + }); + + it('turns the individual scans off and locks them when the VA notification is turned on', async () => { + mockPreference( + buildVaNotificationPreference({ all_va_completed: false, static_scan_completed: true }) + ); + + server.use( + http.put(UPDATE_URL, () => + HttpResponse.json( + buildVaNotificationPreference({ + all_va_completed: true, + static_scan_completed: false, + dynamic_scan_completed: false, + api_scan_completed: false, + }) + ) + ) + ); + + await renderAtRoute(NOTIFICATION_SETTINGS); + await settled(); + await userEvent.click(await toggle(akMT('accountNotifSettings.vaNotificationTitle'))); + + const staticScan = await toggle(akMT('accountNotifSettings.staticScanTitle')); + + await waitFor(() => expect(staticScan).not.toBeChecked()); + expect(staticScan).toBeDisabled(); + }); + + it('moves the toggle back and says so when the server refuses', async () => { + mockPreference( + buildVaNotificationPreference({ all_va_completed: false, dynamic_scan_completed: false }) + ); + + server.use( + http.put(UPDATE_URL, () => + HttpResponse.json({}, { status: HTTP_STATUS_CODES.INTERNAL_SERVER_ERROR }) + ) + ); + + await renderAtRoute(NOTIFICATION_SETTINGS); + await settled(); + await userEvent.click(await toggle(akMT('accountNotifSettings.dynamicScanTitle'))); + + expect( + await screen.findByText(akMT('accountNotifSettings.notificationPreferenceUpdateFailed')) + ).toBeInTheDocument(); + + expect(await toggle(akMT('accountNotifSettings.dynamicScanTitle'))).not.toBeChecked(); + }); + + it('says so, and shows every preference off, when the preferences cannot be fetched', async () => { + server.use( + http.get(PREFERENCE_URL, () => + HttpResponse.json({}, { status: HTTP_STATUS_CODES.INTERNAL_SERVER_ERROR }) + ) + ); + + await renderAtRoute(NOTIFICATION_SETTINGS); + + expect( + await screen.findByText(akMT('accountNotifSettings.errorFetchingPreferences')) + ).toBeInTheDocument(); + + expect(await toggle(akMT('accountNotifSettings.vaNotificationTitle'))).not.toBeChecked(); + }); + + it('notes who the emails go to, with its lead-in set in bold', async () => { + mockPreference(buildVaNotificationPreference()); + + await renderAtRoute(NOTIFICATION_SETTINGS); + await settled(); + + const note = document.querySelector('[data-test-notification-note]'); + + expect(note?.querySelector('strong')).toBeInTheDocument(); + expect(note?.textContent).not.toContain(''); + }); +}); diff --git a/apps/dashboard/src/features/account-settings/pages/notification-settings/index.tsx b/apps/dashboard/src/features/account-settings/pages/notification-settings/index.tsx new file mode 100644 index 000000000..50cd7d80c --- /dev/null +++ b/apps/dashboard/src/features/account-settings/pages/notification-settings/index.tsx @@ -0,0 +1,184 @@ +import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'; +import { Fragment, useEffect } from 'react'; + +import { + NotificationPreferenceService, + type ApiVaNotificationPreference, + type ApiVaNotificationPreferenceKey, +} from '@irene/api/services/notification-preference'; + +import { akMT } from '@irene/translations/intl'; +import { AkDivider } from '@irene/ui/ak-divider'; +import { AkIcon } from '@irene/ui/ak-icon'; +import { AkTooltip } from '@irene/ui/ak-tooltip'; +import { AkTypography } from '@irene/ui/ak-typography'; +import { akNotify } from '@irene/ui/notify'; + +import { + notificationPreferenceKeys, + vaNotificationPreferenceOptions, +} from '@/features/account-settings/queries/notification-preference'; + +import { SettingsItem } from './components/settings-item'; + +/** Every preference off: what irene shows until the account's arrive, and if they never do. */ +const NO_PREFERENCES: ApiVaNotificationPreference = { + all_va_completed: false, + static_scan_completed: false, + dynamic_scan_completed: false, + api_scan_completed: false, +}; + +interface SettingDefinition { + id: ApiVaNotificationPreferenceKey; + title: () => string; + description: () => string; +} + +interface GroupDefinition { + id: string; + title: () => string; + tooltip: () => string; + /** Whether the VA notification overrides this group while it is on. */ + isOverriddenByVa: boolean; + settings: SettingDefinition[]; +} + +/* The VA notification, then the three it overrides, as irene groups them. */ +const GROUPS: GroupDefinition[] = [ + { + id: 'va_notification', + title: () => akMT('accountNotifSettings.vaNotificationTitle'), + tooltip: () => akMT('accountNotifSettings.vaNotificationTooltip'), + isOverriddenByVa: false, + settings: [ + { + id: 'all_va_completed', + title: () => akMT('accountNotifSettings.vaNotificationTitle'), + description: () => akMT('accountNotifSettings.vaNotificationDescription'), + }, + ], + }, + { + id: 'individual_scan_level_notification', + title: () => akMT('accountNotifSettings.individualScanTitle'), + tooltip: () => akMT('accountNotifSettings.individualScanTooltip'), + isOverriddenByVa: true, + settings: [ + { + id: 'static_scan_completed', + title: () => akMT('accountNotifSettings.staticScanTitle'), + description: () => akMT('accountNotifSettings.staticScanDescription'), + }, + { + id: 'dynamic_scan_completed', + title: () => akMT('accountNotifSettings.dynamicScanTitle'), + description: () => akMT('accountNotifSettings.dynamicScanDescription'), + }, + { + id: 'api_scan_completed', + title: () => akMT('accountNotifSettings.apiScanTitle'), + description: () => akMT('accountNotifSettings.apiScanDescription'), + }, + ], + }, +]; + +/** + * The notification preferences tab of account settings: which scan results + * the account is emailed a summary of. + * + * Each toggle takes effect as it is flipped. It moves at once and moves back + * if the server refuses, as irene's does, and the server's answer replaces all + * four, since turning the VA notification on turns the other three off. + */ +export function NotificationSettingsPage() { + const queryClient = useQueryClient(); + const preferences = useQuery(vaNotificationPreferenceOptions()); + const current = preferences.data ?? NO_PREFERENCES; + + useEffect(() => { + if (preferences.isError) { + akNotify.error(akMT('accountNotifSettings.errorFetchingPreferences')); + } + }, [preferences.isError]); + + const updatePreference = useMutation({ + mutationFn: ({ key, value }: { key: ApiVaNotificationPreferenceKey; value: boolean }) => + NotificationPreferenceService.updateVaPreference(key, value), + + onMutate: async ({ key, value }) => { + await queryClient.cancelQueries({ queryKey: notificationPreferenceKeys.va() }); + queryClient.setQueryData(notificationPreferenceKeys.va(), { ...current, [key]: value }); + + return { previous: current }; + }, + + onSuccess: (updated) => { + queryClient.setQueryData(notificationPreferenceKeys.va(), updated); + akNotify.success(akMT('accountNotifSettings.notificationPreferenceUpdated')); + }, + + onError: (_error, _variables, context) => { + queryClient.setQueryData(notificationPreferenceKeys.va(), context?.previous); + akNotify.error(akMT('accountNotifSettings.notificationPreferenceUpdateFailed')); + }, + }); + + /* irene holds a toggle while its own request runs; the pending key says which one. */ + const pendingKey = updatePreference.isPending ? updatePreference.variables.key : null; + + return ( +
    + {akMT('accountNotifSettings.emailSummaryTitle')} + + {GROUPS.map((group) => ( +
    +
    + {group.title()} + + + + +
    + +
    + {group.settings.map((setting, index) => ( + + {index > 0 && } + + updatePreference.mutate({ key: setting.id, value })} + /> + + ))} +
    +
    + ))} + + + {akMT('accountNotifSettings.notificationNote')} + +
    + ); +} diff --git a/apps/dashboard/src/features/account-settings/pages/security/components/mfa-app-enable.tsx b/apps/dashboard/src/features/account-settings/pages/security/components/mfa-app-enable.tsx new file mode 100644 index 000000000..4fc29d305 --- /dev/null +++ b/apps/dashboard/src/features/account-settings/pages/security/components/mfa-app-enable.tsx @@ -0,0 +1,90 @@ +import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'; +import { useEffect, useState } from 'react'; + +import { MfaService } from '@irene/api/services/mfa'; +import { ENUMS } from '@irene/enums'; +import { akMT } from '@irene/translations/intl'; +import { AkModalBody } from '@irene/ui/ak-modal'; +import { akNotify } from '@irene/ui/notify'; + +import { + notifyOtpStepFailed, + sendOtpIfTyped, +} from '@/features/account-settings/pages/security/utils'; + +import { mfaKeys } from '@/features/account-settings/queries/mfa'; + +import { MfaAppVerify, MfaAppVerifySkeleton } from './mfa-app-verify'; +import { MfaModal } from './mfa-modal'; +import { useMfaModal } from './use-mfa-modal'; + +interface MfaAppEnableProps { + email: string; + onClose: () => void; +} + +/** + * Turns authenticator-app MFA on for an account with no second factor. + * + * The secret is asked for as the modal opens, and the QR code is drawn from it. + * It is a query that is never cached, so each opening gets a secret of its own, + * as irene's request in the constructor does, and never stale while open, so + * refocusing the window mid-scan does not swap the code for a new one. A + * failure closes the modal. + * + * @param props.email - The account's address, which names the entry in the app. + * @param props.onClose - Called when the modal closes, whether or not MFA was turned on. + */ +export function MfaAppEnable({ email, onClose }: Readonly) { + const { closeModal, modalProps } = useMfaModal(onClose); + + const queryClient = useQueryClient(); + const [otp, setOtp] = useState(''); + + const setup = useQuery({ + queryKey: [...mfaKeys.all(), 'setup', ENUMS.MFA_METHOD.TOTP], + queryFn: () => MfaService.requestMfaSetup({ method: ENUMS.MFA_METHOD.TOTP }), + staleTime: Infinity, + gcTime: 0, + retry: false, + }); + + useEffect(() => { + if (setup.isError) { + closeModal(); + akNotify.error(akMT('somethingWentWrong')); + } + }, [setup.isError, closeModal]); + + const verifyCode = useMutation({ + mutationFn: (token: string) => + MfaService.confirmMfa({ method: ENUMS.MFA_METHOD.TOTP, otp, token }), + + onSuccess: async () => { + await queryClient.invalidateQueries({ queryKey: mfaKeys.methods() }); + closeModal(); + }, + + onError: notifyOtpStepFailed, + }); + + return ( + + + {setup.data ? ( + sendOtpIfTyped(otp, () => verifyCode.mutate(setup.data.token))} + onCancel={closeModal} + isVerifying={verifyCode.isPending} + /> + ) : ( + + )} + + + ); +} diff --git a/apps/dashboard/src/features/account-settings/pages/security/components/mfa-app-verify.tsx b/apps/dashboard/src/features/account-settings/pages/security/components/mfa-app-verify.tsx new file mode 100644 index 000000000..4d53dd210 --- /dev/null +++ b/apps/dashboard/src/features/account-settings/pages/security/components/mfa-app-verify.tsx @@ -0,0 +1,110 @@ +import { QRCodeSVG } from 'qrcode.react'; +import { type FormEvent } from 'react'; + +import { akMT } from '@irene/translations/intl'; +import { AkButton } from '@irene/ui/ak-button'; +import { AkSkeleton } from '@irene/ui/ak-skeleton'; +import { AkTypography } from '@irene/ui/ak-typography'; + +import { MfaOtpInput } from './mfa-otp-input'; + +interface MfaAppVerifyProps { + secret: string; + email: string; + otp: string; + onOtpChange: (otp: string) => void; + onContinue: () => void; + onCancel: () => void; + isVerifying: boolean; +} + +/** + * Sets an authenticator app up: the code to scan, then the first code it shows. + * + * The QR code carries the standard `otpauth://` URI irene builds, with the + * address unescaped as irene leaves it, so an app set up from either reads the + * same account name. + * + * @param props.secret - The TOTP secret the server generated. + * @param props.email - The account's address, which names the entry in the app. + * @param props.otp - The code typed so far. + * @param props.onOtpChange - Called with the code as it is typed. + * @param props.onContinue - Called to submit the code. + * @param props.onCancel - Called to give up. + * @param props.isVerifying - Whether the code is being checked. + */ +export function MfaAppVerify({ + secret, + email, + otp, + onOtpChange, + onContinue, + onCancel, + isVerifying, +}: Readonly) { + const submit = (event: FormEvent) => { + event.preventDefault(); + onContinue(); + }; + + return ( +
    +
    + + {akMT('modalCard.enableMFAApp.scanBarcode')} + + + +
    + +
    + + {akMT('modalCard.enableMFAApp.enterCode')} + + + + +
    + + {akMT('continue')} + + + + {akMT('cancel')} + +
    + +
    + ); +} + +/** Stands in for the code to scan while the secret is on its way, shaped as the step it becomes. */ +export function MfaAppVerifySkeleton() { + return ( +
    +
    + + + +
    + + + + + +
    + + + +
    +
    + ); +} diff --git a/apps/dashboard/src/features/account-settings/pages/security/components/mfa-disable.tsx b/apps/dashboard/src/features/account-settings/pages/security/components/mfa-disable.tsx new file mode 100644 index 000000000..8b810550c --- /dev/null +++ b/apps/dashboard/src/features/account-settings/pages/security/components/mfa-disable.tsx @@ -0,0 +1,172 @@ +import { useMutation, useQueryClient } from '@tanstack/react-query'; +import { useState, type FormEvent } from 'react'; + +import { MfaService } from '@irene/api/services/mfa'; +import { ENUMS } from '@irene/enums'; +import { akMT } from '@irene/translations/intl'; +import { AkAlert, AkAlertDescription } from '@irene/ui/ak-alert'; +import { AkButton } from '@irene/ui/ak-button'; +import { AkIcon } from '@irene/ui/ak-icon'; +import { AkModalBody } from '@irene/ui/ak-modal'; +import { AkTypography } from '@irene/ui/ak-typography'; +import { akNotify } from '@irene/ui/notify'; + +import { + isOtpRefusal, + notifyOtpStepFailed, + sendOtpIfTyped, +} from '@/features/account-settings/pages/security/utils'; + +import { mfaKeys } from '@/features/account-settings/queries/mfa'; + +import { MfaModal, MfaModalFooter } from './mfa-modal'; +import { MfaOtpInput } from './mfa-otp-input'; +import { useMfaModal } from './use-mfa-modal'; + +interface MfaDisableProps { + email: string; + isEmailMfaEnabled: boolean; + isAppMfaEnabled: boolean; + canDisableMfa: boolean; + onClose: () => void; +} + +/** + * Turns the active second factor off, once a code from it confirms the request. + * + * For email, a first step says where the code will go, and Continue asks the + * server to send it: it emails one and refuses the request with an `otp` + * error, which is the expected answer, not a failure. For the app there is + * nothing to send, so the modal opens on the code. irene opens both on the + * email notice, which tells an app user to expect an email that never comes. + * + * One of irene's quirks is kept so the screens match: the code step repeats + * the notice that MFA cannot be disabled. The notice is irene's fallback for + * an account that may not disable MFA, which never reaches this modal, and + * irene's own tests assert it on the code step. + * + * @param props.email - The account's address, which the email confirmation step names. + * @param props.isEmailMfaEnabled - Whether email is the active factor. + * @param props.isAppMfaEnabled - Whether an authenticator app is. + * @param props.canDisableMfa - Whether the organization lets this account turn MFA off. + * @param props.onClose - Called when the modal closes, whether or not MFA was turned off. + */ +export function MfaDisable({ + email, + isEmailMfaEnabled, + isAppMfaEnabled, + canDisableMfa, + onClose, +}: Readonly) { + const { closeModal, modalProps } = useMfaModal(onClose); + + const queryClient = useQueryClient(); + /* Only email has anything to send first, so the app opens on the code. */ + const [isCodeStep, setIsCodeStep] = useState(!isEmailMfaEnabled); + const [otp, setOtp] = useState(''); + + /* irene checks email first, so an account somehow on both disables email. */ + const enabledMethod = isEmailMfaEnabled + ? ENUMS.MFA_METHOD.HOTP + : isAppMfaEnabled + ? ENUMS.MFA_METHOD.TOTP + : ENUMS.MFA_METHOD.NONE; + + const sendCode = useMutation({ + mutationFn: async () => { + try { + await MfaService.disableMfa({ method: ENUMS.MFA_METHOD.HOTP }); + } catch (error) { + /* The refusal asking for the code is the server saying it sent one. */ + if (!isOtpRefusal(error)) { + throw error; + } + } + }, + + onSuccess: () => setIsCodeStep(true), + + onError: () => { + closeModal(); + akNotify.error(akMT('somethingWentWrong')); + }, + }); + + const verifyCode = useMutation({ + mutationFn: () => MfaService.disableMfa({ method: enabledMethod, otp }), + + onSuccess: async () => { + await queryClient.invalidateQueries({ queryKey: mfaKeys.methods() }); + closeModal(); + }, + + onError: notifyOtpStepFailed, + }); + + const submitCode = (event: FormEvent) => { + event.preventDefault(); + sendOtpIfTyped(otp, () => verifyCode.mutate()); + }; + + const isConfirmStep = !isCodeStep && canDisableMfa; + + return ( + +
    + + {isConfirmStep ? ( + + {akMT('modalCard.enableMFAEmail.sendMailMsg', { email })} + + ) : ( + + + + {akMT('disableMFADenied')} + + )} + + {isCodeStep && ( +
    + + {[ + akMT('modalCard.disableMFA.enterOTP'), + isEmailMfaEnabled && akMT('modalCard.disableMFA.viaEmail'), + isAppMfaEnabled && akMT('modalCard.disableMFA.viaApp'), + ] + .filter(Boolean) + .join(' ')} + + + +
    + )} +
    + + {isConfirmStep && ( + + sendCode.mutate()}> + {akMT('continue')} + + + + {akMT('cancel')} + + + )} + + {isCodeStep && ( + + + {akMT('confirm')} + + + + {akMT('cancel')} + + + )} +
    +
    + ); +} diff --git a/apps/dashboard/src/features/account-settings/pages/security/components/mfa-email-code.tsx b/apps/dashboard/src/features/account-settings/pages/security/components/mfa-email-code.tsx new file mode 100644 index 000000000..b5e7d777f --- /dev/null +++ b/apps/dashboard/src/features/account-settings/pages/security/components/mfa-email-code.tsx @@ -0,0 +1,33 @@ +import { akMT } from '@irene/translations/intl'; +import { AkTypography } from '@irene/ui/ak-typography'; + +import { MfaOtpInput } from './mfa-otp-input'; + +interface MfaEmailCodeProps { + email: string; + value: string; + onChange: (value: string) => void; +} + +/** + * Says where the emailed code went, and takes it. + * + * @param props.email - The address the code was sent to. + * @param props.value - The code typed so far. + * @param props.onChange - Called with the code as it is typed. + */ +export function MfaEmailCode({ email, value, onChange }: Readonly) { + return ( +
    +
    + {akMT('modalCard.enableMFAEmail.description', { email })} +
    + + +
    + ); +} diff --git a/apps/dashboard/src/features/account-settings/pages/security/components/mfa-email-enable.tsx b/apps/dashboard/src/features/account-settings/pages/security/components/mfa-email-enable.tsx new file mode 100644 index 000000000..660c7f2af --- /dev/null +++ b/apps/dashboard/src/features/account-settings/pages/security/components/mfa-email-enable.tsx @@ -0,0 +1,110 @@ +import { useMutation, useQueryClient } from '@tanstack/react-query'; +import { useState } from 'react'; + +import { MfaService } from '@irene/api/services/mfa'; +import { unlessRateLimited } from '@irene/api/utils/errors'; +import { ENUMS } from '@irene/enums'; +import { akMT } from '@irene/translations/intl'; +import { AkButton } from '@irene/ui/ak-button'; +import { AkModalBody } from '@irene/ui/ak-modal'; +import { AkTypography } from '@irene/ui/ak-typography'; +import { akNotify } from '@irene/ui/notify'; + +import { + notifyOtpStepFailed, + sendOtpIfTyped, +} from '@/features/account-settings/pages/security/utils'; + +import { mfaKeys } from '@/features/account-settings/queries/mfa'; + +import { MfaEmailCode } from './mfa-email-code'; +import { MfaModal, MfaModalFooter } from './mfa-modal'; +import { useMfaModal } from './use-mfa-modal'; + +interface MfaEmailEnableProps { + email: string; + onClose: () => void; +} + +/** + * Turns email MFA on for an account with no second factor. + * + * It says a code is about to be sent and sends it on Continue, then takes the + * code. The server hands back a token with the first request, which the second + * carries so the code is checked against the secret it was made from. + * + * @param props.email - The account's address, where the code goes. + * @param props.onClose - Called when the modal closes, whether or not MFA was turned on. + */ +export function MfaEmailEnable({ email, onClose }: Readonly) { + const { closeModal, modalProps } = useMfaModal(onClose); + + const queryClient = useQueryClient(); + const [setupToken, setSetupToken] = useState(null); + const [otp, setOtp] = useState(''); + + const sendCode = useMutation({ + mutationFn: () => MfaService.requestMfaSetup({ method: ENUMS.MFA_METHOD.HOTP }), + + onSuccess: (setup) => { + setSetupToken(setup.token); + akNotify.success(akMT('mfaOtpSentTo', { email })); + }, + + onError: unlessRateLimited(() => akNotify.error(akMT('mfaOtpSendFailed'))), + }); + + const verifyCode = useMutation({ + mutationFn: (token: string) => + MfaService.confirmMfa({ method: ENUMS.MFA_METHOD.HOTP, otp, token }), + + onSuccess: async () => { + await queryClient.invalidateQueries({ queryKey: mfaKeys.methods() }); + closeModal(); + }, + + onError: notifyOtpStepFailed, + }); + + return ( + + {setupToken === null ? ( + <> + + + {akMT('modalCard.enableMFAEmail.sendMailMsg', { email })} + + + + + sendCode.mutate()}> + {akMT('continue')} + + + + {akMT('cancel')} + + + + ) : ( +
    { + event.preventDefault(); + sendOtpIfTyped(otp, () => verifyCode.mutate(setupToken)); + }} + > + + + + + + + {akMT('confirm')} + + +
    + )} +
    + ); +} diff --git a/apps/dashboard/src/features/account-settings/pages/security/components/mfa-modal.test.tsx b/apps/dashboard/src/features/account-settings/pages/security/components/mfa-modal.test.tsx new file mode 100644 index 000000000..34b89a59d --- /dev/null +++ b/apps/dashboard/src/features/account-settings/pages/security/components/mfa-modal.test.tsx @@ -0,0 +1,67 @@ +import { screen, waitFor } from '@testing-library/react'; +import userEvent from '@testing-library/user-event'; +import { StrictMode } from 'react'; +import { describe, expect, it, vi } from 'vitest'; + +import { akMT } from '@irene/translations/intl'; +import { AkModalBody } from '@irene/ui/ak-modal'; + +import { renderWithProviders } from '@tests/render'; + +import { MfaModal } from './mfa-modal'; +import { useMfaModal } from './use-mfa-modal'; + +/** A step as the MFA components write one: it opens on mount and closes itself. */ +function Step({ onClose }: Readonly<{ onClose: () => void }>) { + const { closeModal, modalProps } = useMfaModal(onClose); + + return ( + + + + + + ); +} + +/* Rendered the way the app renders, since the double pass is what remounts effects. */ +const renderStep = (onClose: () => void) => + renderWithProviders( + + + + ); + +describe('MfaModal', () => { + it('stays open once the step has mounted', async () => { + const onClose = vi.fn(); + + renderStep(onClose); + + expect(await screen.findByRole('dialog')).toBeInTheDocument(); + expect(onClose).not.toHaveBeenCalled(); + }); + + it('tells the step to unmount only after the panel has gone', async () => { + const onClose = vi.fn(); + + renderStep(onClose); + + await userEvent.click(await screen.findByRole('button', { name: 'Done' })); + + await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument()); + expect(onClose).toHaveBeenCalledOnce(); + }); + + it('closes from its header', async () => { + const onClose = vi.fn(); + + renderStep(onClose); + + await userEvent.click(await screen.findByRole('button', { name: akMT('close') })); + + await waitFor(() => expect(onClose).toHaveBeenCalledOnce()); + }); +}); diff --git a/apps/dashboard/src/features/account-settings/pages/security/components/mfa-modal.tsx b/apps/dashboard/src/features/account-settings/pages/security/components/mfa-modal.tsx new file mode 100644 index 000000000..844a2f74c --- /dev/null +++ b/apps/dashboard/src/features/account-settings/pages/security/components/mfa-modal.tsx @@ -0,0 +1,90 @@ +import { useEffect, useRef, type ReactNode } from 'react'; + +import { akMT } from '@irene/translations/intl'; +import { AkModal, AkModalContent, AkModalFooter, AkModalHeader } from '@irene/ui/ak-modal'; + +interface CloseOnUnmountProps { + isOpen: boolean; + onUnmount: () => void; +} + +interface MfaModalProps { + title: string; + isOpen: boolean; + onOpenChange: (isOpen: boolean) => void; + onClose: () => void; + children: ReactNode; +} + +/** + * The modal every MFA step runs in. + * + * The caller mounts it to open it, so each opening starts from its first step. + * Its props come from `useMfaModal`, which is what the step closes it with. + * + * @param props.title - What the steps are for. + * @param props.isOpen - Whether the panel is showing or closing. + * @param props.onOpenChange - Called when the close control, Escape or the backdrop closes it. + * @param props.onClose - Called once the panel has left the DOM. + * @param props.children - The current step: its body, and its footer when it has one. + */ +export function MfaModal({ + title, + isOpen, + onOpenChange, + onClose, + children, +}: Readonly) { + return ( + + + + + {children} + + + + + ); +} + +/** + * Reports the panel's removal from the DOM, which happens after its closing + * animation has finished. + * + * @param props.isOpen - Whether the panel is still meant to be showing. + * @param props.onUnmount - Called when the panel is removed after being closed. + */ +function CloseOnUnmount({ isOpen, onUnmount }: Readonly) { + const latestProps = useRef({ isOpen, onUnmount }); + + useEffect(() => { + latestProps.current = { isOpen, onUnmount }; + }); + + useEffect( + () => () => { + // A panel still marked open is being torn down by something other than a + // close, such as the page unmounting or a development remount. + if (!latestProps.current.isOpen) { + latestProps.current.onUnmount(); + } + }, + [] + ); + + return null; +} + +/** + * The row of controls under a step, aligned to the right as irene's are. + * + * @param props.children - The step's buttons, the one that moves on first. + */ +export function MfaModalFooter({ children }: Readonly<{ children: ReactNode }>) { + return ( + + {children} + + ); +} diff --git a/apps/dashboard/src/features/account-settings/pages/security/components/mfa-otp-input.tsx b/apps/dashboard/src/features/account-settings/pages/security/components/mfa-otp-input.tsx new file mode 100644 index 000000000..18175603d --- /dev/null +++ b/apps/dashboard/src/features/account-settings/pages/security/components/mfa-otp-input.tsx @@ -0,0 +1,43 @@ +import { useId } from 'react'; + +import { akMT } from '@irene/translations/intl'; +import { AkInput } from '@irene/ui/ak-input'; +import { AkLabel } from '@irene/ui/ak-label'; + +interface MfaOtpInputProps { + value: string; + onChange: (value: string) => void; + label?: string; +} + +/** + * The field a one-time code is typed into. + * + * irene checks nothing about the code but that it is there, and says so in a + * notification rather than under the field, so this is a plain controlled + * input rather than a form field with its own validation. + * + * @param props.value - The code typed so far. + * @param props.onChange - Called with the code as it is typed. + * @param props.label - Shown above the field. Without one, the field is still named for a screen reader. + */ +export function MfaOtpInput({ value, onChange, label }: Readonly) { + const id = useId(); + + return ( +
    + {label && {label}} + + onChange(event.target.value)} + aria-label={label ? undefined : akMT('modalCard.enableMFAEmail.enterCode')} + autoComplete="one-time-code" + inputMode="numeric" + autoFocus + data-test-mfa-otp-input + /> +
    + ); +} diff --git a/apps/dashboard/src/features/account-settings/pages/security/components/mfa-switch-to-app.tsx b/apps/dashboard/src/features/account-settings/pages/security/components/mfa-switch-to-app.tsx new file mode 100644 index 000000000..b56ae389d --- /dev/null +++ b/apps/dashboard/src/features/account-settings/pages/security/components/mfa-switch-to-app.tsx @@ -0,0 +1,149 @@ +import { useMutation, useQueryClient } from '@tanstack/react-query'; +import { useState } from 'react'; + +import { MfaService, type ApiMfaSetupToken } from '@irene/api/services/mfa'; +import { unlessRateLimited } from '@irene/api/utils/errors'; +import { ENUMS } from '@irene/enums'; +import { akMT } from '@irene/translations/intl'; +import { AkButton } from '@irene/ui/ak-button'; +import { AkModalBody } from '@irene/ui/ak-modal'; +import { AkTypography } from '@irene/ui/ak-typography'; +import { akNotify } from '@irene/ui/notify'; + +import { + isOtpRefusal, + notifyOtpStepFailed, + sendOtpIfTyped, +} from '@/features/account-settings/pages/security/utils'; + +import { mfaKeys } from '@/features/account-settings/queries/mfa'; + +import { MfaAppVerify } from './mfa-app-verify'; +import { MfaEmailCode } from './mfa-email-code'; +import { MfaModal, MfaModalFooter } from './mfa-modal'; +import { useMfaModal } from './use-mfa-modal'; + +type SwitchToAppStep = 'confirm' | 'email'; + +interface MfaSwitchToAppProps { + email: string; + onClose: () => void; +} + +/** + * Moves an account from email MFA to an authenticator app. + * + * The account proves it still holds the email factor first: asking for the + * app makes the server email a code and refuse with an `otp` error, which is + * the cue to take that code. The code buys the new secret, and the first code + * the app shows completes the switch. A request that is not refused leaves the + * modal where it is, as irene's does; the server always refuses it for an + * account on email MFA. + * + * @param props.email - The account's address, where the code goes. + * @param props.onClose - Called when the modal closes, whether or not the switch completed. + */ +export function MfaSwitchToApp({ email, onClose }: Readonly) { + const { closeModal, modalProps } = useMfaModal(onClose); + + const queryClient = useQueryClient(); + const [step, setStep] = useState('confirm'); + const [emailOtp, setEmailOtp] = useState(''); + const [appOtp, setAppOtp] = useState(''); + /* Set once the emailed code is accepted, which moves the modal to the app step. */ + const [appSetup, setAppSetup] = useState(null); + + const requestEmailCode = useMutation({ + mutationFn: () => MfaService.requestMfaSetup({ method: ENUMS.MFA_METHOD.TOTP }), + + onError: unlessRateLimited((error) => { + if (isOtpRefusal(error)) { + setStep('email'); + } else { + akNotify.error(akMT('somethingWentWrong')); + } + }), + }); + + const verifyEmailCode = useMutation({ + mutationFn: () => MfaService.requestMfaSetup({ method: ENUMS.MFA_METHOD.TOTP, otp: emailOtp }), + + onSuccess: setAppSetup, + + onError: notifyOtpStepFailed, + }); + + const verifyAppCode = useMutation({ + mutationFn: (token: string) => + MfaService.confirmMfa({ method: ENUMS.MFA_METHOD.TOTP, otp: appOtp, token }), + + onSuccess: async () => { + await queryClient.invalidateQueries({ queryKey: mfaKeys.methods() }); + closeModal(); + }, + + onError: notifyOtpStepFailed, + }); + + return ( + + {!appSetup && step === 'confirm' && ( + <> + + + {akMT('mfaSwitchToAppDescription')} + + + + + requestEmailCode.mutate()} + > + {akMT('continue')} + + + + {akMT('cancel')} + + + + )} + + {!appSetup && step === 'email' && ( +
    { + event.preventDefault(); + sendOtpIfTyped(emailOtp, () => verifyEmailCode.mutate()); + }} + > + + + + + + + {akMT('confirm')} + + +
    + )} + + {appSetup && ( + + sendOtpIfTyped(appOtp, () => verifyAppCode.mutate(appSetup.token))} + onCancel={closeModal} + isVerifying={verifyAppCode.isPending} + /> + + )} +
    + ); +} diff --git a/apps/dashboard/src/features/account-settings/pages/security/components/mfa-switch-to-email.tsx b/apps/dashboard/src/features/account-settings/pages/security/components/mfa-switch-to-email.tsx new file mode 100644 index 000000000..654154a86 --- /dev/null +++ b/apps/dashboard/src/features/account-settings/pages/security/components/mfa-switch-to-email.tsx @@ -0,0 +1,141 @@ +import { useMutation, useQueryClient } from '@tanstack/react-query'; +import { useState, type FormEvent } from 'react'; + +import { MfaService } from '@irene/api/services/mfa'; +import { ENUMS } from '@irene/enums'; +import { akMT } from '@irene/translations/intl'; +import { AkButton } from '@irene/ui/ak-button'; +import { AkModalBody } from '@irene/ui/ak-modal'; +import { AkTypography } from '@irene/ui/ak-typography'; + +import { + notifyOtpStepFailed, + sendOtpIfTyped, +} from '@/features/account-settings/pages/security/utils'; + +import { mfaKeys } from '@/features/account-settings/queries/mfa'; + +import { MfaEmailCode } from './mfa-email-code'; +import { MfaModal, MfaModalFooter } from './mfa-modal'; +import { MfaOtpInput } from './mfa-otp-input'; +import { useMfaModal } from './use-mfa-modal'; + +type SwitchToEmailStep = 'confirm' | 'app'; + +interface MfaSwitchToEmailProps { + email: string; + onClose: () => void; +} + +/** + * Moves an account from an authenticator app to email MFA. + * + * The account proves it still holds the app first: a code from it makes the + * server email a code and hand back a token, and that emailed code, sent with + * the token, completes the switch. + * + * @param props.email - The account's address, where the code goes. + * @param props.onClose - Called when the modal closes, whether or not the switch completed. + */ +export function MfaSwitchToEmail({ email, onClose }: Readonly) { + const { closeModal, modalProps } = useMfaModal(onClose); + + const queryClient = useQueryClient(); + const [step, setStep] = useState('confirm'); + const [appOtp, setAppOtp] = useState(''); + const [emailOtp, setEmailOtp] = useState(''); + /* Set once the app's code is accepted, which moves the modal to the email step. */ + const [emailToken, setEmailToken] = useState(null); + + const verifyAppCode = useMutation({ + mutationFn: () => MfaService.requestMfaSetup({ method: ENUMS.MFA_METHOD.HOTP, otp: appOtp }), + + onSuccess: (setup) => setEmailToken(setup.token), + + onError: notifyOtpStepFailed, + }); + + const verifyEmailCode = useMutation({ + mutationFn: (token: string) => + MfaService.confirmMfa({ method: ENUMS.MFA_METHOD.HOTP, otp: emailOtp, token }), + + onSuccess: async () => { + await queryClient.invalidateQueries({ queryKey: mfaKeys.methods() }); + closeModal(); + }, + + onError: notifyOtpStepFailed, + }); + + /** Keeps the form from navigating, and sends the code once one is typed. */ + const submitOtp = (event: FormEvent, otp: string, send: () => void) => { + event.preventDefault(); + sendOtpIfTyped(otp, send); + }; + + return ( + + {!emailToken && step === 'confirm' && ( + <> + + + {akMT('mfaSwitchToEmailDescription')} + + + + + setStep('app')}> + {akMT('continue')} + + + + {akMT('cancel')} + + + + )} + + {!emailToken && step === 'app' && ( +
    submitOtp(event, appOtp, () => verifyAppCode.mutate())} + > + + + {`${akMT('modalCard.disableMFA.enterOTP')} ${akMT('modalCard.disableMFA.viaApp')}`} + + + + + + + + {akMT('confirm')} + + + + {akMT('cancel')} + + +
    + )} + + {emailToken && ( +
    submitOtp(event, emailOtp, () => verifyEmailCode.mutate(emailToken))} + > + + + + + + + {akMT('confirm')} + + +
    + )} +
    + ); +} diff --git a/apps/dashboard/src/features/account-settings/pages/security/components/multi-factor-auth.test.tsx b/apps/dashboard/src/features/account-settings/pages/security/components/multi-factor-auth.test.tsx new file mode 100644 index 000000000..09d7b361b --- /dev/null +++ b/apps/dashboard/src/features/account-settings/pages/security/components/multi-factor-auth.test.tsx @@ -0,0 +1,543 @@ +import { faker } from '@faker-js/faker'; +import { screen, waitFor, within } from '@testing-library/react'; +import userEvent from '@testing-library/user-event'; +import { http, HttpResponse } from 'msw'; +import { beforeEach, describe, expect, it } from 'vitest'; + +import { MfaEndpoints } from '@irene/api/services/mfa'; +import { UserEndpoints, type ApiUser } from '@irene/api/services/user'; +import { configurationStore } from '@irene/api/stores/configuration'; +import { storeSession } from '@irene/api/utils/session'; +import { HTTP_STATUS_CODES } from '@irene/constants'; +import { akMT } from '@irene/translations/intl'; + +import { + buildMfaSetupToken, + buildServerConfiguration, + buildSession, + buildUser, + buildUserResponse, +} from '@tests/factories'; + +import { mockMfaMethods } from '@tests/mfa'; +import { mockOrganizationMe } from '@tests/organization'; +import { renderAtRoute } from '@tests/render'; +import { buildAPITestURL, server } from '@tests/server'; + +const SECURITY_SETTINGS = '/dashboard/settings/security'; + +const MFA_URL = buildAPITestURL(MfaEndpoints.mfa()); + +const APP = 1; +const EMAIL = 2; + +const session = buildSession(); + +const otp = () => faker.string.numeric(6); + +/** The refusal the server answers a step with when it wants a code, or the code is wrong. */ +const otpRefusal = () => + HttpResponse.json({ otp: ['OTP is required'] }, { status: HTTP_STATUS_CODES.BAD_REQUEST }); + +const noContent = () => new HttpResponse(null, { status: HTTP_STATUS_CODES.NO_CONTENT }); + +const mockSignedInUser = (overrides: Partial = {}) => { + const user = buildUser(overrides); + + server.use( + http.get(`*/${UserEndpoints.detail(session.userId)}`, () => + HttpResponse.json(buildUserResponse(user)) + ) + ); + + return user; +}; + +/** + * Answers each POST to the MFA endpoint with the next response in line, and + * records what each one sent. + */ +const answerPosts = (...responses: (() => Response)[]) => { + const bodies: unknown[] = []; + + server.use( + http.post(MFA_URL, async ({ request }) => { + bodies.push(await request.json()); + + return (responses[bodies.length - 1] ?? noContent)(); + }) + ); + + return bodies; +}; + +/** The same, for DELETE. */ +const answerDeletes = (...responses: (() => Response)[]) => { + const bodies: unknown[] = []; + + server.use( + http.delete(MFA_URL, async ({ request }) => { + bodies.push(await request.json()); + + return (responses[bodies.length - 1] ?? noContent)(); + }) + ); + + return bodies; +}; + +const methodRow = async (method: number) => { + await screen.findByText(akMT('mfaMethodApp')); + + const row = document.querySelector(`[data-test-mfa-method="${method}"]`); + + if (!row) { + throw new Error(`No row for method ${method}`); + } + + return row; +}; + +const pressInRow = async (method: number, name: string) => + userEvent.click(within(await methodRow(method)).getByRole('button', { name })); + +const dialog = () => screen.findByRole('dialog'); + +const pressInDialog = async (name: string) => + userEvent.click(within(await dialog()).getByRole('button', { name })); + +const typeCode = async (code: string) => + userEvent.type(within(await dialog()).getByRole('textbox'), code); + +describe('MultiFactorAuth', () => { + beforeEach(() => { + storeSession(session); + configurationStore.getState().setServerConfiguration(buildServerConfiguration()); + mockMfaMethods(); + }); + + describe('the list of methods', () => { + it('offers both methods to an account with neither on', async () => { + mockSignedInUser(); + + await renderAtRoute(SECURITY_SETTINGS); + + expect( + within(await methodRow(APP)).getByRole('button', { name: akMT('enable') }) + ).toBeInTheDocument(); + + expect( + within(await methodRow(EMAIL)).getByRole('button', { name: akMT('enable') }) + ).toBeInTheDocument(); + }); + + it('marks the active method and offers to turn it off', async () => { + mockSignedInUser(); + mockMfaMethods(EMAIL); + + await renderAtRoute(SECURITY_SETTINGS); + + const emailRow = await methodRow(EMAIL); + + await waitFor(() => + expect(within(emailRow).getByRole('button', { name: akMT('disable') })).toBeInTheDocument() + ); + + expect(emailRow.querySelector('[data-test-mfa-method-enabled]')).toBeInTheDocument(); + }); + + it('withholds the disable control, and says why, where the organization mandates MFA', async () => { + mockSignedInUser({ can_disable_mfa: false }); + mockMfaMethods(APP); + + await renderAtRoute(SECURITY_SETTINGS); + + expect(await screen.findByText(akMT('disableMFADenied'))).toBeInTheDocument(); + + expect( + within(await methodRow(APP)).queryByRole('button', { name: akMT('disable') }) + ).not.toBeInTheDocument(); + + expect( + screen.queryByRole('link', { name: akMT('organizationSettings') }) + ).not.toBeInTheDocument(); + }); + + it('points an owner at the organization setting that mandates MFA', async () => { + mockSignedInUser({ can_disable_mfa: false }); + mockOrganizationMe({ is_owner: true }); + + await renderAtRoute(SECURITY_SETTINGS); + + expect( + await screen.findByRole('link', { name: akMT('organizationSettings') }) + ).toHaveAttribute('href', '/dashboard/organization/settings'); + }); + }); + + describe('turning email MFA on', () => { + it('sends a code, then turns the method on once the code is confirmed', async () => { + const user = mockSignedInUser(); + const setup = buildMfaSetupToken(); + const code = otp(); + + const bodies = answerPosts( + () => HttpResponse.json(setup), + () => { + mockMfaMethods(EMAIL); + + return noContent(); + } + ); + + await renderAtRoute(SECURITY_SETTINGS); + await pressInRow(EMAIL, akMT('enable')); + await pressInDialog(akMT('continue')); + + expect( + await screen.findByText(akMT('mfaOtpSentTo', { email: user.email ?? '' })) + ).toBeInTheDocument(); + + await typeCode(code); + await pressInDialog(akMT('confirm')); + + await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument()); + + expect(bodies).toEqual([{ method: EMAIL }, { method: EMAIL, otp: code, token: setup.token }]); + + expect( + await within(await methodRow(EMAIL)).findByRole('button', { name: akMT('disable') }) + ).toBeInTheDocument(); + }); + + it('names the address the code goes to, in bold, before sending it', async () => { + const user = mockSignedInUser(); + + await renderAtRoute(SECURITY_SETTINGS); + await pressInRow(EMAIL, akMT('enable')); + + const confirmation = (await dialog()).querySelector( + '[data-test-mfa-email-enable-send-confirm]' + ); + + expect(confirmation?.querySelector('strong')).toHaveTextContent(user.email ?? ''); + }); + + it('names the address the code was sent to, in bold, once it is sent', async () => { + const user = mockSignedInUser(); + + answerPosts(() => HttpResponse.json(buildMfaSetupToken())); + + await renderAtRoute(SECURITY_SETTINGS); + await pressInRow(EMAIL, akMT('enable')); + await pressInDialog(akMT('continue')); + + const sent = await waitFor(() => { + const box = document.querySelector('[data-test-mfa-email-sent]'); + + expect(box).toBeInTheDocument(); + + return box; + }); + + expect(sent?.querySelector('strong')).toHaveTextContent(user.email ?? ''); + }); + + it('says so when the code cannot be sent', async () => { + mockSignedInUser(); + answerPosts(() => HttpResponse.json({}, { status: HTTP_STATUS_CODES.INTERNAL_SERVER_ERROR })); + + await renderAtRoute(SECURITY_SETTINGS); + await pressInRow(EMAIL, akMT('enable')); + await pressInDialog(akMT('continue')); + + expect(await screen.findByText(akMT('mfaOtpSendFailed'))).toBeInTheDocument(); + }); + + it('asks for the code rather than sending an empty one', async () => { + mockSignedInUser(); + const bodies = answerPosts(() => HttpResponse.json(buildMfaSetupToken())); + + await renderAtRoute(SECURITY_SETTINGS); + await pressInRow(EMAIL, akMT('enable')); + await pressInDialog(akMT('continue')); + await pressInDialog(akMT('confirm')); + + expect(await screen.findByText(akMT('enterOTP'))).toBeInTheDocument(); + expect(bodies).toHaveLength(1); + }); + + it('says the code is wrong when the server refuses it', async () => { + mockSignedInUser(); + answerPosts(() => HttpResponse.json(buildMfaSetupToken()), otpRefusal); + + await renderAtRoute(SECURITY_SETTINGS); + await pressInRow(EMAIL, akMT('enable')); + await pressInDialog(akMT('continue')); + await typeCode(otp()); + await pressInDialog(akMT('confirm')); + + expect(await screen.findByText(akMT('invalidOTP'))).toBeInTheDocument(); + expect(screen.getByRole('dialog')).toBeInTheDocument(); + }); + + it('closes from its header without a request', async () => { + mockSignedInUser(); + const bodies = answerPosts(); + + await renderAtRoute(SECURITY_SETTINGS); + await pressInRow(EMAIL, akMT('enable')); + await pressInDialog(akMT('close')); + + await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument()); + expect(bodies).toHaveLength(0); + }); + + it('closes without a request when cancelled', async () => { + mockSignedInUser(); + const bodies = answerPosts(); + + await renderAtRoute(SECURITY_SETTINGS); + await pressInRow(EMAIL, akMT('enable')); + await pressInDialog(akMT('cancel')); + + await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument()); + expect(bodies).toHaveLength(0); + }); + }); + + describe('turning app MFA on', () => { + it('shows the code to scan, then turns the method on with the first code the app shows', async () => { + mockSignedInUser(); + const setup = buildMfaSetupToken(); + const code = otp(); + + const bodies = answerPosts( + () => HttpResponse.json(setup), + () => { + mockMfaMethods(APP); + + return noContent(); + } + ); + + await renderAtRoute(SECURITY_SETTINGS); + await pressInRow(APP, akMT('enable')); + + expect( + await screen.findByRole('img', { name: akMT('modalCard.enableMFAApp.scanBarcode') }) + ).toBeInTheDocument(); + + await typeCode(code); + await pressInDialog(akMT('continue')); + + await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument()); + expect(bodies).toEqual([{ method: APP }, { method: APP, otp: code, token: setup.token }]); + }); + + it('closes and says so when no secret can be had', async () => { + mockSignedInUser(); + answerPosts(() => HttpResponse.json({}, { status: HTTP_STATUS_CODES.INTERNAL_SERVER_ERROR })); + + await renderAtRoute(SECURITY_SETTINGS); + await pressInRow(APP, akMT('enable')); + + expect(await screen.findByText(akMT('somethingWentWrong'))).toBeInTheDocument(); + await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument()); + }); + }); + + describe('switching from email to the app', () => { + it('takes the emailed code, then the app’s first code', async () => { + mockSignedInUser(); + mockMfaMethods(EMAIL); + const setup = buildMfaSetupToken(); + const emailCode = otp(); + const appCode = otp(); + + const bodies = answerPosts( + otpRefusal, + () => HttpResponse.json(setup), + () => { + mockMfaMethods(APP); + + return noContent(); + } + ); + + await renderAtRoute(SECURITY_SETTINGS); + await pressInRow(APP, akMT('enable')); + + expect(await dialog()).toHaveTextContent(akMT('mfaSwitchToAppTitle')); + + await pressInDialog(akMT('continue')); + await typeCode(emailCode); + await pressInDialog(akMT('confirm')); + + expect( + await screen.findByRole('img', { name: akMT('modalCard.enableMFAApp.scanBarcode') }) + ).toBeInTheDocument(); + + await typeCode(appCode); + await pressInDialog(akMT('continue')); + + await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument()); + + expect(bodies).toEqual([ + { method: APP }, + { method: APP, otp: emailCode }, + { method: APP, otp: appCode, token: setup.token }, + ]); + }); + + it('says something went wrong when the first step is refused for another reason', async () => { + mockSignedInUser(); + mockMfaMethods(EMAIL); + answerPosts(() => HttpResponse.json({}, { status: HTTP_STATUS_CODES.INTERNAL_SERVER_ERROR })); + + await renderAtRoute(SECURITY_SETTINGS); + await pressInRow(APP, akMT('enable')); + await pressInDialog(akMT('continue')); + + expect(await screen.findByText(akMT('somethingWentWrong'))).toBeInTheDocument(); + }); + }); + + describe('switching from the app to email', () => { + it('takes the app’s code, then the emailed code', async () => { + mockSignedInUser(); + mockMfaMethods(APP); + const setup = buildMfaSetupToken(); + const appCode = otp(); + const emailCode = otp(); + + const bodies = answerPosts( + () => HttpResponse.json(setup), + () => { + mockMfaMethods(EMAIL); + + return noContent(); + } + ); + + await renderAtRoute(SECURITY_SETTINGS); + await pressInRow(EMAIL, akMT('enable')); + + expect(await dialog()).toHaveTextContent(akMT('mfaSwitchToEmailTitle')); + + await pressInDialog(akMT('continue')); + await typeCode(appCode); + await pressInDialog(akMT('confirm')); + + expect( + await within(await dialog()).findByLabelText(akMT('modalCard.enableMFAEmail.enterCode')) + ).toBeInTheDocument(); + + await typeCode(emailCode); + await pressInDialog(akMT('confirm')); + + await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument()); + + expect(bodies).toEqual([ + { method: EMAIL, otp: appCode }, + { method: EMAIL, otp: emailCode, token: setup.token }, + ]); + }); + }); + + describe('turning MFA off', () => { + it('says where the code will go for email MFA, then turns it off with the code sent there', async () => { + const user = mockSignedInUser(); + mockMfaMethods(EMAIL); + const code = otp(); + + const bodies = answerDeletes(otpRefusal, () => { + mockMfaMethods(); + + return noContent(); + }); + + await renderAtRoute(SECURITY_SETTINGS); + await pressInRow(EMAIL, akMT('disable')); + + expect( + (await dialog()).querySelector('[data-test-mfa-disable-send-confirm] strong') + ).toHaveTextContent(user.email ?? ''); + + await pressInDialog(akMT('continue')); + + expect(await dialog()).toHaveTextContent( + `${akMT('modalCard.disableMFA.enterOTP')} ${akMT('modalCard.disableMFA.viaEmail')}` + ); + + await typeCode(code); + await pressInDialog(akMT('confirm')); + + await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument()); + expect(bodies).toEqual([{ method: EMAIL }, { method: EMAIL, otp: code }]); + }); + + it('asks for the app’s code straight away for app MFA', async () => { + mockSignedInUser(); + mockMfaMethods(APP); + const code = otp(); + const bodies = answerDeletes(); + + await renderAtRoute(SECURITY_SETTINGS); + await pressInRow(APP, akMT('disable')); + + expect(await dialog()).toHaveTextContent( + `${akMT('modalCard.disableMFA.enterOTP')} ${akMT('modalCard.disableMFA.viaApp')}` + ); + + expect( + within(await dialog()).queryByRole('button', { name: akMT('continue') }) + ).not.toBeInTheDocument(); + + await typeCode(code); + await pressInDialog(akMT('confirm')); + + await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument()); + expect(bodies).toEqual([{ method: APP, otp: code }]); + }); + + it('repeats irene’s mandated-MFA notice above the code, as irene does', async () => { + mockSignedInUser(); + mockMfaMethods(APP); + + await renderAtRoute(SECURITY_SETTINGS); + await pressInRow(APP, akMT('disable')); + + expect(await dialog()).toHaveTextContent(akMT('disableMFADenied')); + }); + + it('closes and says so when the code cannot be sent', async () => { + mockSignedInUser(); + mockMfaMethods(EMAIL); + + answerDeletes(() => + HttpResponse.json({}, { status: HTTP_STATUS_CODES.INTERNAL_SERVER_ERROR }) + ); + + await renderAtRoute(SECURITY_SETTINGS); + await pressInRow(EMAIL, akMT('disable')); + await pressInDialog(akMT('continue')); + + expect(await screen.findByText(akMT('somethingWentWrong'))).toBeInTheDocument(); + await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument()); + }); + + it('says something went wrong when the code is refused for another reason', async () => { + mockSignedInUser(); + mockMfaMethods(APP); + answerDeletes(() => HttpResponse.json({}, { status: HTTP_STATUS_CODES.FORBIDDEN })); + + await renderAtRoute(SECURITY_SETTINGS); + await pressInRow(APP, akMT('disable')); + await typeCode(otp()); + await pressInDialog(akMT('confirm')); + + expect(await screen.findByText(akMT('somethingWentWrong'))).toBeInTheDocument(); + }); + }); +}); diff --git a/apps/dashboard/src/features/account-settings/pages/security/components/multi-factor-auth.tsx b/apps/dashboard/src/features/account-settings/pages/security/components/multi-factor-auth.tsx new file mode 100644 index 000000000..98c8cca6b --- /dev/null +++ b/apps/dashboard/src/features/account-settings/pages/security/components/multi-factor-auth.tsx @@ -0,0 +1,239 @@ +import { useQuery } from '@tanstack/react-query'; +import { Link } from '@tanstack/react-router'; +import { Fragment, useState } from 'react'; + +import { ENUMS } from '@irene/enums'; +import { akMT } from '@irene/translations/intl'; +import { AkAlert, AkAlertDescription } from '@irene/ui/ak-alert'; +import { AkButton } from '@irene/ui/ak-button'; +import { AkChip } from '@irene/ui/ak-chip'; +import { AkDivider } from '@irene/ui/ak-divider'; +import { AkIcon } from '@irene/ui/ak-icon'; +import { AkLink } from '@irene/ui/ak-link'; +import { AkTypography } from '@irene/ui/ak-typography'; +import type { ApiMfa } from '@irene/api/services/mfa'; + +import { mfaMethodsOptions } from '@/features/account-settings/queries/mfa'; +import { useOrganization } from '@/hooks/use-organization'; +import { useSignedInUser } from '@/hooks/use-signed-in-user'; + +import { MfaAppEnable } from './mfa-app-enable'; +import { MfaDisable } from './mfa-disable'; +import { MfaEmailEnable } from './mfa-email-enable'; +import { MfaSwitchToApp } from './mfa-switch-to-app'; +import { MfaSwitchToEmail } from './mfa-switch-to-email'; + +/** The modal open over the list, if any: one per flow irene offers. */ +type MfaModalName = 'disable' | 'email-enable' | 'app-enable' | 'switch-to-app' | 'switch-to-email'; + +/** The authenticator apps irene suggests, with the platforms each runs on. */ +const AUTHENTICATOR_APPS = [ + { + platforms: () => akMT('mfaAppAndroidIosBlackberry'), + app: 'Google Authenticator', + infoUrl: 'https://support.google.com/accounts/answer/1066447?hl=en', + }, + { + platforms: () => akMT('mfaAppAndroidIos'), + app: 'Duo Mobile', + infoUrl: 'https://guide.duo.com/third-party-accounts', + }, + { + platforms: () => akMT('mfaAppWindowsPhone'), + app: 'Authenticator', + infoUrl: 'https://www.microsoft.com/en-us/store/p/authenticator/9wzdncrfj3rj', + }, +]; + +/** + * Lists both second factors, marks the active one, and opens the flow that + * enables, switches or disables one. + * + * Enabling a method while the other is active switches to it instead. The + * disable control is offered only where the organization lets the account turn + * MFA off; otherwise a notice says why, and points an owner at the setting. + */ +export function MultiFactorAuth() { + const user = useSignedInUser(); + const { me } = useOrganization(); + const { data: methods = [] } = useQuery(mfaMethodsOptions()); + const [openModal, setOpenModal] = useState(null); + + const canDisableMfa = Boolean(user.can_disable_mfa); + const isMfaEnabled = methods.some((mfa) => mfa.enabled); + + const isEnabled = (method: ApiMfa['method']) => + methods.some((mfa) => mfa.method === method && mfa.enabled); + + const closeModal = () => setOpenModal(null); + + const enable = (method: ApiMfa['method']) => { + if (method === ENUMS.MFA_METHOD.HOTP) { + setOpenModal(isMfaEnabled ? 'switch-to-email' : 'email-enable'); + } else { + setOpenModal(isMfaEnabled ? 'switch-to-app' : 'app-enable'); + } + }; + + return ( +
    +
    + + {akMT('multiFactorAuth')} + + + {akMT('mfaDescription')} +
    + + {!canDisableMfa && ( + + + + + {akMT('disableMFADenied')} + + {me?.is_owner && ( + <> + {akMT('disableThisIn')} + + + {akMT('organizationSettings')} + + + )} + + + )} + +
    + {akMT('mfaSelect')} + + {methods.length > 0 && ( +
    + {methods.map((mfa, index) => ( + + {index > 0 && } + + enable(mfa.method)} + onDisable={() => setOpenModal('disable')} + /> + + ))} +
    + )} +
    + + {openModal === 'disable' && ( + + )} + + {openModal === 'email-enable' && } + + {openModal === 'app-enable' && } + + {openModal === 'switch-to-app' && } + + {openModal === 'switch-to-email' && ( + + )} +
    + ); +} + +interface MfaMethodRowProps { + mfa: ApiMfa; + canDisableMfa: boolean; + onEnable: () => void; + onDisable: () => void; +} + +/** + * One method: what it is, how it works, and the control that changes it. + * + * @param props.mfa - The method, and whether it is active. + * @param props.canDisableMfa - Whether the active method may be turned off. + * @param props.onEnable - Called to enable the method, or switch to it. + * @param props.onDisable - Called to turn the active method off. + */ +function MfaMethodRow({ mfa, canDisableMfa, onEnable, onDisable }: Readonly) { + const isApp = mfa.method === ENUMS.MFA_METHOD.TOTP; + const name = isApp ? akMT('mfaMethodApp') : akMT('email'); + + return ( +
    +
    +
    + + {name} + + + {mfa.enabled && ( + } + data-test-mfa-method-enabled + /> + )} +
    + + + {isApp ? akMT('mfaAppDesc') : akMT('mfaEmailDesc')} + + + {isApp && ( +
    + {AUTHENTICATOR_APPS.map(({ platforms, app, infoUrl }) => ( +
    + + {platforms()} + + + + {app} + +
    + ))} +
    + )} +
    + + {mfa.enabled && canDisableMfa && ( + + {akMT('disable')} + + )} + + {!mfa.enabled && ( + + {akMT('enable')} + + )} +
    + ); +} diff --git a/apps/dashboard/src/features/account-settings/pages/security/components/password-change.test.tsx b/apps/dashboard/src/features/account-settings/pages/security/components/password-change.test.tsx new file mode 100644 index 000000000..e26616f96 --- /dev/null +++ b/apps/dashboard/src/features/account-settings/pages/security/components/password-change.test.tsx @@ -0,0 +1,144 @@ +import { faker } from '@faker-js/faker'; +import { screen, waitFor } from '@testing-library/react'; +import userEvent from '@testing-library/user-event'; +import { http, HttpResponse } from 'msw'; +import { beforeEach, describe, expect, it } from 'vitest'; + +import { AuthEndpoints } from '@irene/api/services/auth'; +import { configurationStore } from '@irene/api/stores/configuration'; +import { getStoredSession, storeSession } from '@irene/api/utils/session'; +import { HTTP_STATUS_CODES } from '@irene/constants'; +import { akMT } from '@irene/translations/intl'; + +import { buildServerConfiguration, buildSession } from '@tests/factories'; +import { mockMfaMethods } from '@tests/mfa'; +import { renderAtRoute } from '@tests/render'; +import { buildAPITestURL, server } from '@tests/server'; + +const SECURITY_SETTINGS = '/dashboard/settings/security'; + +const CHANGE_PASSWORD_URL = buildAPITestURL(AuthEndpoints.changePassword()); + +/** The three passwords a user types, the new one twice. */ +const buildPasswords = () => { + const newPassword = faker.internet.password({ length: 12 }); + + return { + old_password: faker.internet.password({ length: 12 }), + password: newPassword, + confirm_password: newPassword, + }; +}; + +const fillIn = async (passwords: Partial>) => { + if (passwords.old_password) { + await userEvent.type( + await screen.findByLabelText(akMT('currentPassword')), + passwords.old_password + ); + } + + if (passwords.password) { + await userEvent.type(screen.getByLabelText(akMT('newPassword')), passwords.password); + } + + if (passwords.confirm_password) { + await userEvent.type( + screen.getByLabelText(akMT('confirmPassword')), + passwords.confirm_password + ); + } +}; + +const submit = async () => + userEvent.click(await screen.findByRole('button', { name: akMT('changePassword') })); + +describe('PasswordChange', () => { + beforeEach(() => { + storeSession(buildSession()); + configurationStore.getState().setServerConfiguration(buildServerConfiguration()); + mockMfaMethods(); + }); + + it('asks for the current and the new password before sending anything', async () => { + let wasSent = false; + + server.use( + http.post(CHANGE_PASSWORD_URL, () => { + wasSent = true; + + return new HttpResponse(null, { status: HTTP_STATUS_CODES.NO_CONTENT }); + }) + ); + + await renderAtRoute(SECURITY_SETTINGS); + await submit(); + + expect(await screen.findByText(akMT('enterCurrentPassword'))).toBeInTheDocument(); + expect(screen.getByText(akMT('enterNewPassword'))).toBeInTheDocument(); + expect(wasSent).toBe(false); + }); + + it('says so when the two new passwords differ', async () => { + const passwords = buildPasswords(); + + await renderAtRoute(SECURITY_SETTINGS); + await fillIn({ ...passwords, confirm_password: `${passwords.password}x` }); + await submit(); + + expect(await screen.findByText(akMT('passwordMatchError'))).toBeInTheDocument(); + }); + + it('sends the passwords, then signs out to the login page, since the server ended every session', async () => { + const passwords = buildPasswords(); + let body: unknown; + + server.use( + http.post(CHANGE_PASSWORD_URL, async ({ request }) => { + body = await request.json(); + + return new HttpResponse(null, { status: HTTP_STATUS_CODES.NO_CONTENT }); + }) + ); + + const { router } = await renderAtRoute(SECURITY_SETTINGS); + await fillIn(passwords); + await submit(); + + await waitFor(() => expect(router.state.location.pathname).toBe('/login')); + expect(body).toEqual(passwords); + expect(getStoredSession()).toBeNull(); + expect(await screen.findByText(akMT('passwordChanged'))).toBeInTheDocument(); + }); + + it('puts the server’s complaint under the field it names', async () => { + const message = faker.lorem.sentence(); + + server.use( + http.post(CHANGE_PASSWORD_URL, () => + HttpResponse.json({ old_password: [message] }, { status: HTTP_STATUS_CODES.BAD_REQUEST }) + ) + ); + + await renderAtRoute(SECURITY_SETTINGS); + await fillIn(buildPasswords()); + await submit(); + + expect(await screen.findByText(message)).toBeInTheDocument(); + expect(getStoredSession()).not.toBeNull(); + }); + + it('says something went wrong when the refusal names no field', async () => { + server.use( + http.post(CHANGE_PASSWORD_URL, () => + HttpResponse.json({}, { status: HTTP_STATUS_CODES.INTERNAL_SERVER_ERROR }) + ) + ); + + await renderAtRoute(SECURITY_SETTINGS); + await fillIn(buildPasswords()); + await submit(); + + expect(await screen.findByText(akMT('somethingWentWrong'))).toBeInTheDocument(); + }); +}); diff --git a/apps/dashboard/src/features/account-settings/pages/security/components/password-change.tsx b/apps/dashboard/src/features/account-settings/pages/security/components/password-change.tsx new file mode 100644 index 000000000..45f7c8a25 --- /dev/null +++ b/apps/dashboard/src/features/account-settings/pages/security/components/password-change.tsx @@ -0,0 +1,108 @@ +import { zodResolver } from '@hookform/resolvers/zod'; +import { useMutation, useQueryClient } from '@tanstack/react-query'; +import { useNavigate, useRouter } from '@tanstack/react-router'; +import { useForm } from 'react-hook-form'; + +import { AuthService } from '@irene/api/services/auth'; +import { unlessRateLimited } from '@irene/api/utils/errors'; +import { akMT } from '@irene/translations/intl'; +import { AkButton } from '@irene/ui/ak-button'; +import { AkFormProvider } from '@irene/ui/ak-form'; +import { AkInput } from '@irene/ui/ak-input'; +import { AkTypography } from '@irene/ui/ak-typography'; +import { akNotify } from '@irene/ui/notify'; + +import { + buildChangePasswordSchema, + ChangePasswordFormField, + type ChangePasswordFormSchema, +} from '@/features/account-settings/schemas/change-password'; + +import { endSession } from '@/features/auth/actions/session'; +import { setFormFieldErrors, toFormFieldErrors } from '@/utils/form-field-errors'; + +/** + * Changes the signed-in account's password. + * + * The server deletes every token the account holds once the password changes, + * so this session is over too: it is ended here and the user signs in again + * with the new password. irene sends them to the login page and lets the next + * refused request end the session; ending it directly lands in the same place + * without the "session expired" detour. + */ +export function PasswordChange() { + const queryClient = useQueryClient(); + const navigate = useNavigate(); + const router = useRouter(); + const changePasswordSchema = buildChangePasswordSchema(); + + const changePasswordForm = useForm({ + resolver: zodResolver(changePasswordSchema), + defaultValues: { old_password: '', password: '', confirm_password: '' }, + reValidateMode: 'onSubmit', + }); + + const changePassword = useMutation({ + mutationFn: AuthService.changePassword, + + onSuccess: async () => { + endSession(queryClient); + await navigate({ to: '/login' }); + router.clearCache(); + + akNotify.success(akMT('passwordChanged')); + }, + + /* The server names the field it refuses, so its message goes under that field. */ + onError: unlessRateLimited((error) => { + const fieldErrors = toFormFieldErrors(changePasswordSchema, error); + + if (fieldErrors.length === 0) { + akNotify.error(akMT('somethingWentWrong')); + } else { + setFormFieldErrors(changePasswordForm, fieldErrors); + } + }), + }); + + return ( + +
    changePassword.mutate(values))} + data-test-password-change + > + {akMT('changePassword')} + + + + + + + + + + + + + + + {akMT('changePassword')} + +
    +
    + ); +} diff --git a/apps/dashboard/src/features/account-settings/pages/security/components/use-mfa-modal.ts b/apps/dashboard/src/features/account-settings/pages/security/components/use-mfa-modal.ts new file mode 100644 index 000000000..b311fded6 --- /dev/null +++ b/apps/dashboard/src/features/account-settings/pages/security/components/use-mfa-modal.ts @@ -0,0 +1,18 @@ +import { useCallback, useState } from 'react'; + +/** + * Holds the modal open until a step asks it to close. + * + * `closeModal` starts the closing animation, and the caller's `onClose` runs + * once the panel has left the DOM, so the step is unmounted after the + * animation rather than during it. + * + * @param onClose - Called once the panel is gone, to unmount the step. + */ +export function useMfaModal(onClose: () => void) { + const [isOpen, setIsOpen] = useState(true); + + const closeModal = useCallback(() => setIsOpen(false), []); + + return { closeModal, modalProps: { isOpen, onClose, onOpenChange: setIsOpen } }; +} diff --git a/apps/dashboard/src/features/account-settings/pages/security/index.tsx b/apps/dashboard/src/features/account-settings/pages/security/index.tsx new file mode 100644 index 000000000..5974a6a56 --- /dev/null +++ b/apps/dashboard/src/features/account-settings/pages/security/index.tsx @@ -0,0 +1,19 @@ +import { AkDivider } from '@irene/ui/ak-divider'; + +import { MultiFactorAuth } from './components/multi-factor-auth'; +import { PasswordChange } from './components/password-change'; + +/** + * The security tab of account settings: the password, then the second factor. + */ +export function SecuritySettingsPage() { + return ( +
    + + + + + +
    + ); +} diff --git a/apps/dashboard/src/features/account-settings/pages/security/utils.test.ts b/apps/dashboard/src/features/account-settings/pages/security/utils.test.ts new file mode 100644 index 000000000..85d8ee577 --- /dev/null +++ b/apps/dashboard/src/features/account-settings/pages/security/utils.test.ts @@ -0,0 +1,26 @@ +import { AxiosError, AxiosHeaders } from 'axios'; +import { describe, expect, it } from 'vitest'; + +import { HTTP_STATUS_CODES } from '@irene/constants'; + +import { isOtpRefusal } from './utils'; + +/** A refusal shaped as the request client rejects one. */ +const refusal = (data: unknown) => + new AxiosError('Bad Request', 'ERR_BAD_REQUEST', undefined, undefined, { + status: HTTP_STATUS_CODES.BAD_REQUEST, + statusText: 'Bad Request', + headers: {}, + config: { headers: new AxiosHeaders() }, + data, + }); + +describe('isOtpRefusal', () => { + it('reads a refusal naming the otp field as one', () => { + expect(isOtpRefusal(refusal({ otp: ['Invalid OTP'] }))).toBe(true); + }); + + it('reads any other refusal as something else', () => { + expect(isOtpRefusal(refusal({ detail: 'Cannot disable' }))).toBe(false); + }); +}); diff --git a/apps/dashboard/src/features/account-settings/pages/security/utils.ts b/apps/dashboard/src/features/account-settings/pages/security/utils.ts new file mode 100644 index 000000000..e63526b70 --- /dev/null +++ b/apps/dashboard/src/features/account-settings/pages/security/utils.ts @@ -0,0 +1,36 @@ +import { getApiFieldErrors, unlessRateLimited } from '@irene/api/utils/errors'; +import { akMT } from '@irene/translations/intl'; +import { akNotify } from '@irene/ui/notify'; + +/** + * Whether the server refused a step because it needs an OTP, or because the + * OTP it was given is wrong. Both answer with a message on the `otp` field. + * + * @param error - Whatever the request rejected with. + * @returns Whether the refusal names the OTP. + */ +export const isOtpRefusal = (error: unknown) => Boolean(getApiFieldErrors(error).otp?.length); + +/** + * Tells the user why a step that carried an OTP was refused: the code was + * wrong, or something else went wrong. A throttled account is already shown + * the rate-limit notice, so it is told nothing more. + */ +export const notifyOtpStepFailed = unlessRateLimited((error: unknown) => { + akNotify.error(isOtpRefusal(error) ? akMT('invalidOTP') : akMT('somethingWentWrong')); +}); + +/** + * Sends a code once one is typed, and says a code is needed when none is, as + * irene does before every step that carries one. + * + * @param otp - The code typed so far. + * @param send - Sends it. + */ +export function sendOtpIfTyped(otp: string, send: () => void) { + if (otp) { + send(); + } else { + akNotify.error(akMT('enterOTP')); + } +} diff --git a/apps/dashboard/src/features/account-settings/queries/cyod.ts b/apps/dashboard/src/features/account-settings/queries/cyod.ts new file mode 100644 index 000000000..1d9e80325 --- /dev/null +++ b/apps/dashboard/src/features/account-settings/queries/cyod.ts @@ -0,0 +1,25 @@ +import { queryOptions } from '@tanstack/react-query'; +import { OrganizationService } from '@irene/api/services/organization'; + +/** The cache keys for an organization's CYOD devices. */ +export const cyodKeys = { + all: () => ['cyod'] as const, + registeredDevices: (organizationId: number | string) => + [...cyodKeys.all(), 'registered-devices', organizationId] as const, +}; + +/** + * Builds the query for the CYOD devices registered to an organization. + * + * A refusal is not retried: the common one is the 403 an organization without + * its own device farm gets, which asking again will not change. + * + * @param organizationId - The organization to ask about. + * @returns Query options resolving to the devices, online or not. + */ +export const registeredDevicesOptions = (organizationId: number | string) => + queryOptions({ + queryKey: cyodKeys.registeredDevices(organizationId), + queryFn: () => OrganizationService.getRegisteredDevices(organizationId), + retry: false, + }); diff --git a/apps/dashboard/src/features/account-settings/queries/mfa.ts b/apps/dashboard/src/features/account-settings/queries/mfa.ts new file mode 100644 index 000000000..c0555b016 --- /dev/null +++ b/apps/dashboard/src/features/account-settings/queries/mfa.ts @@ -0,0 +1,19 @@ +import { queryOptions } from '@tanstack/react-query'; +import { MfaService } from '@irene/api/services/mfa'; + +/** The cache keys for the signed-in account's second factor. */ +export const mfaKeys = { + all: () => ['mfa'] as const, + methods: () => [...mfaKeys.all(), 'methods'] as const, +}; + +/** + * Builds the query for both second-factor methods and which one is active. + * + * @returns Query options resolving to the methods, the authenticator app first. + */ +export const mfaMethodsOptions = () => + queryOptions({ + queryKey: mfaKeys.methods(), + queryFn: MfaService.getMfaMethods, + }); diff --git a/apps/dashboard/src/features/account-settings/queries/notification-preference.ts b/apps/dashboard/src/features/account-settings/queries/notification-preference.ts new file mode 100644 index 000000000..420df22e5 --- /dev/null +++ b/apps/dashboard/src/features/account-settings/queries/notification-preference.ts @@ -0,0 +1,19 @@ +import { queryOptions } from '@tanstack/react-query'; +import { NotificationPreferenceService } from '@irene/api/services/notification-preference'; + +/** The cache keys for which scan results the account is emailed about. */ +export const notificationPreferenceKeys = { + all: () => ['notification-preference'] as const, + va: () => [...notificationPreferenceKeys.all(), 'va'] as const, +}; + +/** + * Builds the query for the account's scan-result email preferences. + * + * @returns Query options resolving to the four preferences. + */ +export const vaNotificationPreferenceOptions = () => + queryOptions({ + queryKey: notificationPreferenceKeys.va(), + queryFn: NotificationPreferenceService.getVaPreference, + }); diff --git a/apps/dashboard/src/features/account-settings/queries/personal-token.ts b/apps/dashboard/src/features/account-settings/queries/personal-token.ts new file mode 100644 index 000000000..bb23635ad --- /dev/null +++ b/apps/dashboard/src/features/account-settings/queries/personal-token.ts @@ -0,0 +1,19 @@ +import { queryOptions } from '@tanstack/react-query'; +import { PersonalTokenService } from '@irene/api/services/personal-token'; + +/** The cache keys for the signed-in account's API tokens. */ +export const personalTokenKeys = { + all: () => ['personal-token'] as const, + list: () => [...personalTokenKeys.all(), 'list'] as const, +}; + +/** + * Builds the query for the account's API tokens. + * + * @returns Query options resolving to the newest ten tokens. + */ +export const personalTokensOptions = () => + queryOptions({ + queryKey: personalTokenKeys.list(), + queryFn: PersonalTokenService.getPersonalTokens, + }); diff --git a/apps/dashboard/src/features/account-settings/schemas/change-password.ts b/apps/dashboard/src/features/account-settings/schemas/change-password.ts new file mode 100644 index 000000000..a87c1e844 --- /dev/null +++ b/apps/dashboard/src/features/account-settings/schemas/change-password.ts @@ -0,0 +1,32 @@ +import { z } from 'zod'; + +import { akMT } from '@irene/translations/intl'; +import { createAkFormField } from '@irene/ui/ak-form/helpers'; + +/** + * The current password, then the new one twice. irene checks only that each is + * present and that the two new ones match; the server judges the rest, and its + * complaints land on the field they name. Built per render, so its messages + * follow the active locale. + * + * @returns The schema. + */ +export const buildChangePasswordSchema = () => + z + .object({ + old_password: z.string().min(1, akMT('enterCurrentPassword')), + password: z.string().min(1, akMT('enterNewPassword')), + confirm_password: z.string(), + }) + .refine((values) => values.password === values.confirm_password, { + message: akMT('passwordMatchError'), + path: ['confirm_password'], + }); + +export type ChangePasswordFormSchema = z.infer>; + +/** + * The field this form's controls are built from, bound to the schema above so + * every `name` is checked against it. + */ +export const ChangePasswordFormField = createAkFormField(); diff --git a/apps/dashboard/src/features/account-settings/schemas/personal-token.ts b/apps/dashboard/src/features/account-settings/schemas/personal-token.ts new file mode 100644 index 000000000..d7b8adf41 --- /dev/null +++ b/apps/dashboard/src/features/account-settings/schemas/personal-token.ts @@ -0,0 +1,24 @@ +import { z } from 'zod'; + +import { akMT } from '@irene/translations/intl'; +import { createAkFormField } from '@irene/ui/ak-form/helpers'; + +/** + * The name a new API token is generated under. irene refuses a name that is + * only spaces, and the server trims what it is sent, so the name is trimmed + * here. Built per render, so its message follows the active locale. + * + * @returns The schema. + */ +export const buildPersonalTokenSchema = () => + z.object({ + name: z.string().trim().min(1, akMT('enterTokenName')), + }); + +export type PersonalTokenFormSchema = z.infer>; + +/** + * The field this form's control is built from, bound to the schema above so + * its `name` is checked against it. + */ +export const PersonalTokenFormField = createAkFormField(); diff --git a/apps/dashboard/src/features/auth/pages/oidc-authorize/index.tsx b/apps/dashboard/src/features/auth/pages/oidc-authorize/index.tsx index 5abfb6ce8..c1f567146 100644 --- a/apps/dashboard/src/features/auth/pages/oidc-authorize/index.tsx +++ b/apps/dashboard/src/features/auth/pages/oidc-authorize/index.tsx @@ -89,7 +89,7 @@ export function OidcAuthorizePage() { aria-busy data-test-oidc-authorize-pending > - + {akMT('loading')} diff --git a/apps/dashboard/src/features/auth/pages/oidc-redirect/index.tsx b/apps/dashboard/src/features/auth/pages/oidc-redirect/index.tsx index c70b6f956..a46e39664 100644 --- a/apps/dashboard/src/features/auth/pages/oidc-redirect/index.tsx +++ b/apps/dashboard/src/features/auth/pages/oidc-redirect/index.tsx @@ -55,7 +55,7 @@ export function OidcRedirectPage() { return (
    - + {akMT('loading')}
    diff --git a/apps/dashboard/src/features/auth/pages/register/index.test.tsx b/apps/dashboard/src/features/auth/pages/register/index.test.tsx index 752f4fa57..3e705f956 100644 --- a/apps/dashboard/src/features/auth/pages/register/index.test.tsx +++ b/apps/dashboard/src/features/auth/pages/register/index.test.tsx @@ -1,9 +1,8 @@ import { faker } from '@faker-js/faker'; -import { screen, waitFor } from '@testing-library/react'; +import { act, screen, waitFor } from '@testing-library/react'; import userEvent from '@testing-library/user-event'; import { http, HttpResponse } from 'msw'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; -import type { ReactNode } from 'react'; import { ConfigurationEndpoints } from '@irene/api/services/configuration/endpoints'; import { RegistrationEndpoints } from '@irene/api/services/registration/endpoints'; @@ -15,18 +14,34 @@ import { renderAtRoute } from '@tests/render'; import { buildAPITestURL, server } from '@tests/server'; /* - The widget's script never loads in a test environment, so the real hook hands - back no `executeRecaptcha` and the page sends its disabled placeholder. Held - here so a test can put a score in its place. + The widget's script never loads in a test environment, so the provider hands + back no `executeRecaptcha` and the page sends its disabled placeholder. + + A test that needs a score loads the widget the way a browser would, through + the real provider, rather than mocking the module: workers share modules + across files (`isolate: false`), so a module mock here is ignored whenever + another file in the same worker loaded the page first. */ -const recaptcha: { score?: string } = {}; +const RECAPTCHA_SCRIPT_ID = 'google-recaptcha-v3'; + +/** + * Puts the widget's global in place and fires the load event the provider + * waits for on its script, so the page gets a working `executeRecaptcha`. + * + * @param token - The token the widget issues for any action. + */ +function loadRecaptchaWidget(token: string) { + Object.assign(window, { + grecaptcha: { + ready: (onReady: () => void) => onReady(), + execute: () => Promise.resolve(token), + }, + }); -vi.mock('react-google-recaptcha-v3', () => ({ - GoogleReCaptchaProvider: ({ children }: { children: ReactNode }) => children, - useGoogleReCaptcha: () => ({ - executeRecaptcha: recaptcha.score ? () => Promise.resolve(recaptcha.score) : undefined, - }), -})); + act(() => { + document.getElementById(RECAPTCHA_SCRIPT_ID)?.dispatchEvent(new Event('load')); + }); +} const registrationUrl = buildAPITestURL(RegistrationEndpoints.register()); @@ -59,12 +74,10 @@ describe('RegisterPage', () => { }); afterEach(() => { - delete recaptcha.score; + Reflect.deleteProperty(window, 'grecaptcha'); }); it('posts the token the reCAPTCHA widget issued', async () => { - recaptcha.score = 'recaptcha-score-token'; - let sent: Record | undefined; server.use( @@ -76,6 +89,7 @@ describe('RegisterPage', () => { ); await renderAtRoute('/register'); + loadRecaptchaWidget('recaptcha-score-token'); await register(); await waitFor(() => expect(sent?.recaptcha).toBe('recaptcha-score-token')); diff --git a/apps/dashboard/src/features/auth/pages/sso-redirect/index.tsx b/apps/dashboard/src/features/auth/pages/sso-redirect/index.tsx index ef3c7ff32..1f0150e0c 100644 --- a/apps/dashboard/src/features/auth/pages/sso-redirect/index.tsx +++ b/apps/dashboard/src/features/auth/pages/sso-redirect/index.tsx @@ -11,7 +11,7 @@ export function SsoRedirectPage() { return (
    - + diff --git a/apps/dashboard/src/features/dashboard/pages/system-status/status-cell.tsx b/apps/dashboard/src/features/dashboard/pages/system-status/status-cell.tsx index f71716721..66ffad76f 100644 --- a/apps/dashboard/src/features/dashboard/pages/system-status/status-cell.tsx +++ b/apps/dashboard/src/features/dashboard/pages/system-status/status-cell.tsx @@ -18,7 +18,7 @@ export function SystemStatusCell({ if (isChecking) { return ( - + diff --git a/apps/dashboard/src/hooks/use-copy-to-clipboard.test.tsx b/apps/dashboard/src/hooks/use-copy-to-clipboard.test.tsx new file mode 100644 index 000000000..6a29804fb --- /dev/null +++ b/apps/dashboard/src/hooks/use-copy-to-clipboard.test.tsx @@ -0,0 +1,145 @@ +import { act, renderHook, waitFor } from '@testing-library/react'; +import userEvent from '@testing-library/user-event'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; + +import { akMT } from '@irene/translations/intl'; +import { akNotify } from '@irene/ui/notify'; + +import { useCopyToClipboard } from '@/hooks/use-copy-to-clipboard'; + +/** Stands in for a browser that refuses the clipboard. */ +const refuseClipboard = () => + vi.spyOn(navigator.clipboard, 'writeText').mockRejectedValue(new Error('denied')); + +describe('useCopyToClipboard', () => { + beforeEach(() => { + /* Installs the clipboard jsdom does not have. */ + userEvent.setup(); + + vi.spyOn(akNotify, 'success').mockReturnValue(''); + vi.spyOn(akNotify, 'error').mockReturnValue(''); + }); + + afterEach(() => { + vi.restoreAllMocks(); + }); + + it('puts the text on the clipboard and says it copied', async () => { + const { result } = renderHook(() => useCopyToClipboard()); + + await act(() => result.current.copy('https://api.appknox.com')); + + await expect(navigator.clipboard.readText()).resolves.toBe('https://api.appknox.com'); + expect(akNotify.success).toHaveBeenCalledWith(akMT('copiedToClipboard')); + }); + + it('reports a copy as done, then forgets it', async () => { + vi.useFakeTimers({ shouldAdvanceTime: true }); + + const { result } = renderHook(() => useCopyToClipboard()); + + expect(result.current.isCopied).toBe(false); + + await act(() => result.current.copy('copied')); + + expect(result.current.isCopied).toBe(true); + + act(() => vi.advanceTimersByTime(2000)); + + expect(result.current.isCopied).toBe(false); + + vi.useRealTimers(); + }); + + it('says so when the browser refuses the clipboard', async () => { + refuseClipboard(); + + const { result } = renderHook(() => useCopyToClipboard()); + + await act(() => result.current.copy('refused')); + + expect(akNotify.error).toHaveBeenCalledWith(akMT('pleaseTryAgain')); + expect(result.current.isCopied).toBe(false); + }); + + it('answers whether the copy went through', async () => { + const { result } = renderHook(() => useCopyToClipboard()); + + const succeeded = await act(() => result.current.copy('fine')); + + expect(succeeded).toBe(true); + + refuseClipboard(); + + const failed = await act(() => result.current.copy('refused')); + + expect(failed).toBe(false); + }); + + it('takes the messages the caller gives it', async () => { + const { result } = renderHook(() => + useCopyToClipboard({ successMessage: 'Token copied', errorMessage: 'No clipboard' }) + ); + + await act(() => result.current.copy('token')); + + expect(akNotify.success).toHaveBeenCalledWith('Token copied'); + + refuseClipboard(); + + await act(() => result.current.copy('token')); + + expect(akNotify.error).toHaveBeenCalledWith('No clipboard'); + }); + + it('shows no notification when the caller drops it', async () => { + const { result } = renderHook(() => + useCopyToClipboard({ successMessage: null, errorMessage: null }) + ); + + await act(() => result.current.copy('quiet')); + + expect(akNotify.success).not.toHaveBeenCalled(); + + refuseClipboard(); + + await act(() => result.current.copy('quiet')); + + expect(akNotify.error).not.toHaveBeenCalled(); + }); + + it('runs the caller’s own work after a copy', async () => { + const onCopied = vi.fn(); + const onFailed = vi.fn(); + + const { result } = renderHook(() => useCopyToClipboard({ onCopied, onFailed })); + + await act(() => result.current.copy('shared link')); + + expect(onCopied).toHaveBeenCalledWith('shared link'); + expect(onFailed).not.toHaveBeenCalled(); + + refuseClipboard(); + + await act(() => result.current.copy('shared link')); + + await waitFor(() => expect(onFailed).toHaveBeenCalledWith(expect.any(Error))); + }); + + it('calls the callbacks the caller has now, not the ones it started with', async () => { + const first = vi.fn(); + const second = vi.fn(); + + const { result, rerender } = renderHook( + ({ onCopied }: { onCopied: () => void }) => useCopyToClipboard({ onCopied }), + { initialProps: { onCopied: first } } + ); + + rerender({ onCopied: second }); + + await act(() => result.current.copy('latest')); + + expect(first).not.toHaveBeenCalled(); + expect(second).toHaveBeenCalledWith('latest'); + }); +}); diff --git a/apps/dashboard/src/hooks/use-copy-to-clipboard.ts b/apps/dashboard/src/hooks/use-copy-to-clipboard.ts new file mode 100644 index 000000000..fdec2c437 --- /dev/null +++ b/apps/dashboard/src/hooks/use-copy-to-clipboard.ts @@ -0,0 +1,66 @@ +import { useCallback, useEffect, useRef, useState } from 'react'; + +import { akMT } from '@irene/translations/intl'; +import { akNotify } from '@irene/ui/notify'; + +/* How long `isCopied` stays true, which is how long a control can show it worked. */ +const COPIED_RESET_DELAY = 2000; + +interface CopyToClipboardOptions { + successMessage?: string | null; + errorMessage?: string | null; + onCopied?: (text: string) => void; + onFailed?: (error: unknown) => void; +} + +/** + * Puts text on the clipboard and reports whether it got there. + * + * The browser refuses the clipboard on an insecure origin or a denied + * permission, so every copy can fail and the failure is told to the user. + * + * @param options.successMessage - Replaces the default notification; `null` drops it. + * @param options.errorMessage - Replaces the default failure notification; `null` drops it. + * @param options.onCopied - Runs after a successful copy, for anything beyond the notification. + * @param options.onFailed - Runs after a failed copy, for anything beyond the notification. + * @returns `copy`, and `isCopied` which is true for two seconds after a copy. + */ +export function useCopyToClipboard(options: Readonly = {}) { + const { successMessage, errorMessage, onCopied, onFailed } = options; + + const [isCopied, setIsCopied] = useState(false); + const resetTimer = useRef>(undefined); + + useEffect(() => () => clearTimeout(resetTimer.current), []); + + const copy = useCallback( + async (text: string) => { + try { + await navigator.clipboard.writeText(text); + + if (successMessage !== null) { + akNotify.info(successMessage ?? akMT('copiedToClipboard')); + } + + setIsCopied(true); + clearTimeout(resetTimer.current); + resetTimer.current = setTimeout(() => setIsCopied(false), COPIED_RESET_DELAY); + + onCopied?.(text); + + return true; + } catch (error) { + if (errorMessage !== null) { + akNotify.error(errorMessage ?? akMT('pleaseTryAgain')); + } + + onFailed?.(error); + + return false; + } + }, + [successMessage, errorMessage, onCopied, onFailed] + ); + + return { copy, isCopied }; +} diff --git a/apps/dashboard/src/layouts/dashboard-layout/nav-items.test.ts b/apps/dashboard/src/layouts/dashboard-layout/nav-items.test.ts index ff58cd639..d63bbc4cf 100644 --- a/apps/dashboard/src/layouts/dashboard-layout/nav-items.test.ts +++ b/apps/dashboard/src/layouts/dashboard-layout/nav-items.test.ts @@ -230,7 +230,7 @@ describe('what each item carries', () => { { id: 'account-settings', label: akMT('accountSettings'), - icon: 'material-symbols:account-box', + icon: 'material-symbols:settings-account-box-outline-rounded', to: '/dashboard/settings/general', }, { diff --git a/apps/dashboard/src/layouts/dashboard-layout/nav-items.ts b/apps/dashboard/src/layouts/dashboard-layout/nav-items.ts index 30f077213..8aa94ed56 100644 --- a/apps/dashboard/src/layouts/dashboard-layout/nav-items.ts +++ b/apps/dashboard/src/layouts/dashboard-layout/nav-items.ts @@ -98,6 +98,7 @@ export function buildDashboardNavItems(access: DashboardNavAccess): DashboardNav label: akMT('organization'), icon: 'material-symbols:group', to: '/dashboard/organization/namespaces', + activeWhen: ['/dashboard/organization/settings'], }, access.hasPublicApis && { @@ -110,8 +111,9 @@ export function buildDashboardNavItems(access: DashboardNavAccess): DashboardNav { id: 'account-settings', label: akMT('accountSettings'), - icon: 'material-symbols:account-box', + icon: 'material-symbols:settings-account-box-outline-rounded', to: '/dashboard/settings/general', + activeWhen: ['/dashboard/settings'], }, hasMarketplace && { diff --git a/apps/dashboard/src/queries/user.ts b/apps/dashboard/src/queries/user.ts index 7d61637c8..053ca78d2 100644 --- a/apps/dashboard/src/queries/user.ts +++ b/apps/dashboard/src/queries/user.ts @@ -5,6 +5,7 @@ import { UserService } from '@irene/api/services/user'; export const userKeys = { all: () => ['user'] as const, detail: (userId: number | string) => [...userKeys.all(), 'detail', userId] as const, + language: () => [...userKeys.all(), 'language'] as const, }; /** diff --git a/apps/dashboard/src/routes/_authenticated/dashboard/organization/settings.tsx b/apps/dashboard/src/routes/_authenticated/dashboard/organization/settings.tsx new file mode 100644 index 000000000..d86ce8e6a --- /dev/null +++ b/apps/dashboard/src/routes/_authenticated/dashboard/organization/settings.tsx @@ -0,0 +1,10 @@ +import { createFileRoute } from '@tanstack/react-router'; + +import { akMT } from '@irene/translations/intl'; +import { RouteShell } from '@/components/route-shell'; + +/* A shell until this screen is migrated; the MFA notice in account settings links an owner here. */ +export const Route = createFileRoute('/_authenticated/dashboard/organization/settings')({ + staticData: { pageTitle: () => akMT('organizationSettings') }, + component: () => , +}); diff --git a/apps/dashboard/src/routes/_authenticated/dashboard/settings.tsx b/apps/dashboard/src/routes/_authenticated/dashboard/settings.tsx new file mode 100644 index 000000000..2c77ee257 --- /dev/null +++ b/apps/dashboard/src/routes/_authenticated/dashboard/settings.tsx @@ -0,0 +1,10 @@ +import { createFileRoute } from '@tanstack/react-router'; + +import { akMT } from '@irene/translations/intl'; +import { AccountSettingsLayout } from '@/features/account-settings'; + +/* Every account settings page sits under the same tabs, so the tabs live on this layout route. */ +export const Route = createFileRoute('/_authenticated/dashboard/settings')({ + staticData: { pageTitle: () => akMT('settings') }, + component: AccountSettingsLayout, +}); diff --git a/apps/dashboard/src/routes/_authenticated/dashboard/settings/cyod-settings.tsx b/apps/dashboard/src/routes/_authenticated/dashboard/settings/cyod-settings.tsx new file mode 100644 index 000000000..c8317c81f --- /dev/null +++ b/apps/dashboard/src/routes/_authenticated/dashboard/settings/cyod-settings.tsx @@ -0,0 +1,19 @@ +import { createFileRoute } from '@tanstack/react-router'; + +import { akMT } from '@irene/translations/intl'; +import { CyodSettingsPage } from '@/features/account-settings/pages/cyod-settings'; +import { CyodSettingsSkeleton } from '@/features/account-settings/pages/cyod-settings/components/cyod-settings-skeleton'; + +export const Route = createFileRoute('/_authenticated/dashboard/settings/cyod-settings')({ + staticData: { pageTitle: () => akMT('cyod.settings.tabLabel') }, + component: CyodSettingsPage, + + /* + The page is a chunk of its own, so a first visit waits on a request before + anything of it exists. Only the component is split out, which leaves this + placeholder in the bundle the tab is clicked from. + */ + pendingComponent: CyodSettingsSkeleton, + pendingMs: 150, + pendingMinMs: 300, +}); diff --git a/apps/dashboard/src/routes/_authenticated/dashboard/settings/developersettings.tsx b/apps/dashboard/src/routes/_authenticated/dashboard/settings/developersettings.tsx new file mode 100644 index 000000000..afbf20abb --- /dev/null +++ b/apps/dashboard/src/routes/_authenticated/dashboard/settings/developersettings.tsx @@ -0,0 +1,9 @@ +import { createFileRoute } from '@tanstack/react-router'; + +import { akMT } from '@irene/translations/intl'; +import { DeveloperSettingsPage } from '@/features/account-settings/pages/developer-settings'; + +export const Route = createFileRoute('/_authenticated/dashboard/settings/developersettings')({ + staticData: { pageTitle: () => akMT('developerSettings') }, + component: DeveloperSettingsPage, +}); diff --git a/apps/dashboard/src/routes/_authenticated/dashboard/settings/general.tsx b/apps/dashboard/src/routes/_authenticated/dashboard/settings/general.tsx index c762851f6..e7620fea6 100644 --- a/apps/dashboard/src/routes/_authenticated/dashboard/settings/general.tsx +++ b/apps/dashboard/src/routes/_authenticated/dashboard/settings/general.tsx @@ -1,10 +1,9 @@ import { createFileRoute } from '@tanstack/react-router'; import { akMT } from '@irene/translations/intl'; -import { RouteShell } from '@/components/route-shell'; +import { GeneralSettingsPage } from '@/features/account-settings/pages/general'; -/* A shell until this screen is migrated; the side navigation links here. */ export const Route = createFileRoute('/_authenticated/dashboard/settings/general')({ - staticData: { pageTitle: () => akMT('accountSettings') }, - component: () => , + staticData: { pageTitle: () => akMT('generalSettings') }, + component: GeneralSettingsPage, }); diff --git a/apps/dashboard/src/routes/_authenticated/dashboard/settings/index.tsx b/apps/dashboard/src/routes/_authenticated/dashboard/settings/index.tsx new file mode 100644 index 000000000..5776506e9 --- /dev/null +++ b/apps/dashboard/src/routes/_authenticated/dashboard/settings/index.tsx @@ -0,0 +1,8 @@ +import { createFileRoute, redirect } from '@tanstack/react-router'; + +/* Account settings has no landing page: it opens on the general tab, as irene's route does. */ +export const Route = createFileRoute('/_authenticated/dashboard/settings/')({ + beforeLoad: () => { + throw redirect({ to: '/dashboard/settings/general', replace: true }); + }, +}); diff --git a/apps/dashboard/src/routes/_authenticated/dashboard/settings/notification-settings.tsx b/apps/dashboard/src/routes/_authenticated/dashboard/settings/notification-settings.tsx new file mode 100644 index 000000000..b3c2b7b49 --- /dev/null +++ b/apps/dashboard/src/routes/_authenticated/dashboard/settings/notification-settings.tsx @@ -0,0 +1,9 @@ +import { createFileRoute } from '@tanstack/react-router'; + +import { akMT } from '@irene/translations/intl'; +import { NotificationSettingsPage } from '@/features/account-settings/pages/notification-settings'; + +export const Route = createFileRoute('/_authenticated/dashboard/settings/notification-settings')({ + staticData: { pageTitle: () => akMT('notificationPreferences') }, + component: NotificationSettingsPage, +}); diff --git a/apps/dashboard/src/routes/_authenticated/dashboard/settings/security.tsx b/apps/dashboard/src/routes/_authenticated/dashboard/settings/security.tsx new file mode 100644 index 000000000..2df58cb3c --- /dev/null +++ b/apps/dashboard/src/routes/_authenticated/dashboard/settings/security.tsx @@ -0,0 +1,9 @@ +import { createFileRoute } from '@tanstack/react-router'; + +import { akMT } from '@irene/translations/intl'; +import { SecuritySettingsPage } from '@/features/account-settings/pages/security'; + +export const Route = createFileRoute('/_authenticated/dashboard/settings/security')({ + staticData: { pageTitle: () => akMT('securitySettings') }, + component: SecuritySettingsPage, +}); diff --git a/apps/dashboard/tests/factories/index.ts b/apps/dashboard/tests/factories/index.ts index dd1bba036..64635e8e9 100644 --- a/apps/dashboard/tests/factories/index.ts +++ b/apps/dashboard/tests/factories/index.ts @@ -1,7 +1,10 @@ export * from '@tests/factories/configuration'; +export * from '@tests/factories/mfa'; export * from '@tests/factories/notification'; +export * from '@tests/factories/notification-preference'; export * from '@tests/factories/organization'; export * from '@tests/factories/partner'; +export * from '@tests/factories/personal-token'; export * from '@tests/factories/session'; export * from '@tests/factories/sso'; export * from '@tests/factories/submission'; diff --git a/apps/dashboard/tests/factories/mfa.ts b/apps/dashboard/tests/factories/mfa.ts new file mode 100644 index 000000000..62239a9ad --- /dev/null +++ b/apps/dashboard/tests/factories/mfa.ts @@ -0,0 +1,18 @@ +import { faker } from '@faker-js/faker'; +import type { ApiMfa, ApiMfaSetupToken } from '@irene/api/services/mfa'; + +/** One second-factor method, off unless the test turns it on. */ +export const buildMfa = (overrides: Partial = {}): ApiMfa => ({ + method: faker.helpers.arrayElement([1, 2] as const), + enabled: false, + ...overrides, +}); + +/** What a step starting a setup hands back. */ +export const buildMfaSetupToken = ( + overrides: Partial = {} +): ApiMfaSetupToken => ({ + secret: faker.string.alphanumeric({ length: 32, casing: 'upper' }), + token: faker.string.alphanumeric(64), + ...overrides, +}); diff --git a/apps/dashboard/tests/factories/notification-preference.ts b/apps/dashboard/tests/factories/notification-preference.ts new file mode 100644 index 000000000..b2f5ce015 --- /dev/null +++ b/apps/dashboard/tests/factories/notification-preference.ts @@ -0,0 +1,13 @@ +import { faker } from '@faker-js/faker'; +import type { ApiVaNotificationPreference } from '@irene/api/services/notification-preference'; + +/** The four scan-result preferences, each on or off at random unless pinned. */ +export const buildVaNotificationPreference = ( + overrides: Partial = {} +): ApiVaNotificationPreference => ({ + all_va_completed: faker.datatype.boolean(), + static_scan_completed: faker.datatype.boolean(), + dynamic_scan_completed: faker.datatype.boolean(), + api_scan_completed: faker.datatype.boolean(), + ...overrides, +}); diff --git a/apps/dashboard/tests/factories/organization.ts b/apps/dashboard/tests/factories/organization.ts index 0a04481a4..d956ee656 100644 --- a/apps/dashboard/tests/factories/organization.ts +++ b/apps/dashboard/tests/factories/organization.ts @@ -1,6 +1,7 @@ import { faker } from '@faker-js/faker'; import type { + ApiCyodRegisteredDevice, ApiOrganization, ApiOrganizationAiFeatures, ApiOrganizationFeatures, @@ -116,3 +117,16 @@ export const buildOrganizationNamespace = ( requested_by: faker.number.int({ min: 1, max: 9999 }), ...overrides, }); + +/** A device registered through Mercer, online unless the test says otherwise. */ +export const buildCyodRegisteredDevice = ( + overrides: Partial = {} +): ApiCyodRegisteredDevice => ({ + name: faker.commerce.productName(), + serial_number: faker.string.alphanumeric({ length: 12, casing: 'upper' }), + model: faker.commerce.product(), + platform: faker.helpers.arrayElement([0, 1]), + is_connected: true, + created_on: faker.date.past().toISOString(), + ...overrides, +}); diff --git a/apps/dashboard/tests/factories/personal-token.ts b/apps/dashboard/tests/factories/personal-token.ts new file mode 100644 index 000000000..8c58d1539 --- /dev/null +++ b/apps/dashboard/tests/factories/personal-token.ts @@ -0,0 +1,23 @@ +import { faker } from '@faker-js/faker'; + +import type { + ApiPersonalToken, + ApiPersonalTokenResource, +} from '@irene/api/services/personal-token'; + +/** A token the account generated. */ +export const buildPersonalToken = ( + overrides: Partial = {} +): ApiPersonalToken => ({ + id: String(faker.number.int({ min: 1, max: 99999 })), + name: faker.word.words(2), + key: faker.string.hexadecimal({ length: 40, prefix: '', casing: 'lower' }), + created: faker.date.past().toISOString(), + ...overrides, +}); + +/** The same token as the endpoint sends it. */ +export const toPersonalTokenResource = ({ + id, + ...attributes +}: ApiPersonalToken): ApiPersonalTokenResource => ({ id, type: 'personaltokens', attributes }); diff --git a/apps/dashboard/tests/mfa.ts b/apps/dashboard/tests/mfa.ts new file mode 100644 index 000000000..686f836d4 --- /dev/null +++ b/apps/dashboard/tests/mfa.ts @@ -0,0 +1,29 @@ +import { http, HttpResponse } from 'msw'; + +import { MfaEndpoints } from '@irene/api/services/mfa/endpoints'; +import { buildMfa } from '@tests/factories'; +import { server } from '@tests/server'; +import type { ApiMfa } from '@irene/api/services/mfa'; + +/** + * Answers the MFA list with both methods, the authenticator app first as the + * server sends them, and whichever one is named as active. + * + * The security tab reads the list on every render, so every test that opens it + * answers it. A test that changes the active method calls this again from its + * handler, so the refetch after the change reads the new state. + * + * @param active - The active method, or nothing for an account with no second factor. + */ +export function mockMfaMethods(active?: ApiMfa['method']) { + const methods = [ + buildMfa({ method: 1, enabled: active === 1 }), + buildMfa({ method: 2, enabled: active === 2 }), + ]; + + server.use( + http.get(`*/${MfaEndpoints.mfa()}`, () => + HttpResponse.json({ count: methods.length, next: null, previous: null, results: methods }) + ) + ); +} diff --git a/apps/dashboard/tests/organization.ts b/apps/dashboard/tests/organization.ts index fe72730ad..af76a181d 100644 --- a/apps/dashboard/tests/organization.ts +++ b/apps/dashboard/tests/organization.ts @@ -5,6 +5,7 @@ import { buildOrganization, buildOrganizationMe } from '@tests/factories'; import { server } from '@tests/server'; import type { + ApiOrganization, ApiOrganizationAiFeatures, ApiOrganizationFeatures, ApiOrganizationMe, @@ -21,12 +22,14 @@ import type { * * @param features - Feature flags to enable, merged over `buildOrganization`'s defaults. * @param aiFeatures - AI feature flags to enable, merged the same way. + * @param organizationOverrides - Other organization fields to pin, such as `cyod_registration_enabled`. */ export function mockOrganizationFeatures( features: Partial, - aiFeatures: Partial = {} + aiFeatures: Partial = {}, + organizationOverrides: Partial = {} ) { - const organization = buildOrganization(); + const organization = buildOrganization(organizationOverrides); server.use( http.get(`*/${OrganizationEndpoints.list()}`, () => diff --git a/apps/dashboard/vite.config.ts b/apps/dashboard/vite.config.ts index 281a3b783..df091bea2 100644 --- a/apps/dashboard/vite.config.ts +++ b/apps/dashboard/vite.config.ts @@ -31,7 +31,26 @@ export default defineConfig({ // Turns `@irene/ui/svgs/*.svg?react` imports into components. svgrPlugin(), ], - resolve: { alias: { '@': resolvePath('./src') } }, + resolve: { + alias: { '@': resolvePath('./src') }, + + // Two copies of React answer hooks from two dispatchers, which fails as an invalid hook call. + dedupe: ['react', 'react-dom'], + }, + + optimizeDeps: { + /* + Vite pre-bundles what the app's own source imports, so a dependency only a + workspace package reaches is named here. Discovering one mid-session + reloads the dependency graph under the running page. + */ + include: [ + 'dayjs', + 'dayjs/locale/ja', + 'dayjs/plugin/localizedFormat', + 'dayjs/plugin/relativeTime', + ], + }, /* One origin for both apps, so the session is shared and crossing between diff --git a/apps/irene/app/templates/authenticated/dashboard/account-settings.hbs b/apps/irene/app/templates/authenticated/dashboard/account-settings.hbs index e1ccaa15d..1c83a7dcf 100644 --- a/apps/irene/app/templates/authenticated/dashboard/account-settings.hbs +++ b/apps/irene/app/templates/authenticated/dashboard/account-settings.hbs @@ -1,9 +1,5 @@ {{page-title 'Settings'}} - - - - {{outlet}} - - \ No newline at end of file + + diff --git a/packages/api/src/request.test.ts b/packages/api/src/request.test.ts index 93c685f79..5aa5ec164 100644 --- a/packages/api/src/request.test.ts +++ b/packages/api/src/request.test.ts @@ -217,11 +217,15 @@ describe('verb helpers', () => { expect(seen.url).toContain('api/ping'); }); - it('post, put and patch carry the body; get and delete do not', async () => { + it('post, put, patch and delete carry the body; get does not', async () => { const posted = intercept('post'); await apiRequest.post('api/ping', { a: 1 }); expect(JSON.parse(posted.body)).toEqual({ a: 1 }); + const deleted = intercept('delete'); + await apiRequest.delete('api/ping', { b: 2 }); + expect(JSON.parse(deleted.body)).toEqual({ b: 2 }); + const got = intercept('get'); await apiRequest.get('api/ping'); expect(got.body).toBe(''); diff --git a/packages/api/src/request.ts b/packages/api/src/request.ts index d6e55a07a..b7a786503 100644 --- a/packages/api/src/request.ts +++ b/packages/api/src/request.ts @@ -166,6 +166,7 @@ export const apiRequest = { patch: (url: string, data?: unknown, options?: RequestOptions) => request({ ...options, url, method: 'PATCH', data }), - delete: (url: string, options?: RequestOptions) => - request({ ...options, url, method: 'DELETE' }), + /* Takes a body like the others: some endpoints (`v2/mfa`) read what to delete from it. */ + delete: (url: string, data?: unknown, options?: RequestOptions) => + request({ ...options, url, method: 'DELETE', data }), }; diff --git a/packages/api/src/services/auth/endpoints.ts b/packages/api/src/services/auth/endpoints.ts index 8a7c1fe2c..19d23918e 100644 --- a/packages/api/src/services/auth/endpoints.ts +++ b/packages/api/src/services/auth/endpoints.ts @@ -14,6 +14,9 @@ export const AuthEndpoints = { /** Recovers a user's password. */ recover: () => `${API_NAMESPACES.v2}/forgot_password` as const, + /** Changes the signed-in user's password, which signs every session of theirs out. */ + changePassword: () => `${API_NAMESPACES.v2}/change_password` as const, + /** Resets a user's password. */ resetPassword: (token: string) => `${API_NAMESPACES.v2}/forgot_password/${token}` as const, diff --git a/packages/api/src/services/auth/service.test.ts b/packages/api/src/services/auth/service.test.ts index 08378966b..b9d27d643 100644 --- a/packages/api/src/services/auth/service.test.ts +++ b/packages/api/src/services/auth/service.test.ts @@ -369,3 +369,49 @@ describe('AuthService reset password', () => { expect(body).toEqual({ password: 'correct-horse', confirm_password: 'correct-horse' }); }); }); + +describe('AuthService.changePassword', () => { + const CHANGE_PASSWORD_URL = buildAPITestURL(AuthEndpoints.changePassword()); + + it('posts the current password and the new one twice', async () => { + const newPassword = faker.internet.password(); + + const request = { + old_password: faker.internet.password(), + password: newPassword, + confirm_password: newPassword, + }; + + let body: unknown; + + server.use( + http.post(CHANGE_PASSWORD_URL, async ({ request: sent }) => { + body = await sent.json(); + + return new HttpResponse(null, { status: HTTP_STATUS_CODES.NO_CONTENT }); + }) + ); + + await AuthService.changePassword(request); + + expect(body).toEqual(request); + }); + + it('rejects with the field the server refused', async () => { + const message = faker.lorem.sentence(); + + server.use( + http.post(CHANGE_PASSWORD_URL, () => + HttpResponse.json({ old_password: [message] }, { status: HTTP_STATUS_CODES.BAD_REQUEST }) + ) + ); + + const error = await AuthService.changePassword({ + old_password: faker.internet.password(), + password: '', + confirm_password: '', + }).catch((reason: unknown) => reason); + + expect(getApiErrorPayload(error)).toEqual({ old_password: [message] }); + }); +}); diff --git a/packages/api/src/services/auth/service.ts b/packages/api/src/services/auth/service.ts index 06019105f..f6a009786 100644 --- a/packages/api/src/services/auth/service.ts +++ b/packages/api/src/services/auth/service.ts @@ -2,6 +2,7 @@ import { apiRequest } from '@irene/api/request'; import { AuthEndpoints, + type ApiChangePasswordRequest, type ApiLoginRequest, type ApiOidcCallbackRequest, type ApiOidcCallbackResponse, @@ -75,6 +76,18 @@ export default class AuthService { public static readonly resetPassword = ({ token, ...password }: ApiResetPasswordRequest) => apiRequest.put(AuthEndpoints.resetPassword(token), password); + /** + * Changes the signed-in user's password. + * + * The server deletes every token the account holds once it is changed, so + * the session making this request ends with it. + * + * @param request - The current password, and the new one twice. + * @returns Resolves once the password is changed. + */ + public static readonly changePassword = (request: ApiChangePasswordRequest) => + apiRequest.post(AuthEndpoints.changePassword(), request); + /** * Asks how a user signs in. Runs before the user has any credential. * @param username - The username or email the user typed. diff --git a/packages/api/src/services/auth/types.ts b/packages/api/src/services/auth/types.ts index 866d7c179..181b5a2ea 100644 --- a/packages/api/src/services/auth/types.ts +++ b/packages/api/src/services/auth/types.ts @@ -49,6 +49,13 @@ export interface ApiResetTokenResponse { username: string; } +/* Request shape for the change password endpoint: the current password, then the new one twice. */ +export interface ApiChangePasswordRequest { + old_password: string; + password: string; + confirm_password: string; +} + /* Request shape for the reset password endpoint.*/ export interface ApiResetPasswordRequest { token: string; diff --git a/packages/api/src/services/mfa/endpoints.ts b/packages/api/src/services/mfa/endpoints.ts new file mode 100644 index 000000000..352e9918e --- /dev/null +++ b/packages/api/src/services/mfa/endpoints.ts @@ -0,0 +1,7 @@ +import { API_NAMESPACES } from '@irene/api/namespaces'; + +/** Paths for the signed-in account's second factor. */ +export const MfaEndpoints = { + /** Lists the methods, enables or switches one (POST), and disables the active one (DELETE). */ + mfa: () => `${API_NAMESPACES.v2}/mfa` as const, +}; diff --git a/packages/api/src/services/mfa/index.ts b/packages/api/src/services/mfa/index.ts new file mode 100644 index 000000000..0298c0b98 --- /dev/null +++ b/packages/api/src/services/mfa/index.ts @@ -0,0 +1,3 @@ +export * from './endpoints'; +export type * from './types'; +export { default as MfaService } from './service'; diff --git a/packages/api/src/services/mfa/service.test.ts b/packages/api/src/services/mfa/service.test.ts new file mode 100644 index 000000000..ff1f5c708 --- /dev/null +++ b/packages/api/src/services/mfa/service.test.ts @@ -0,0 +1,94 @@ +import { http, HttpResponse } from 'msw'; +import { describe, expect, it } from 'vitest'; + +import { HTTP_STATUS_CODES } from '@irene/constants'; + +import { MfaEndpoints, MfaService } from '@irene/api/services/mfa'; +import { getApiFieldErrors } from '@irene/api/utils/errors'; +import { buildMfa, buildMfaSetupToken } from '@tests/factories'; +import { buildAPITestURL, server } from '@tests/server'; + +const MFA_URL = buildAPITestURL(MfaEndpoints.mfa()); + +describe('MfaService.getMfaMethods', () => { + it('returns the methods out of their page', async () => { + const methods = [buildMfa({ method: 1, enabled: true }), buildMfa({ method: 2 })]; + + server.use( + http.get(MFA_URL, () => + HttpResponse.json({ count: 2, next: null, previous: null, results: methods }) + ) + ); + + await expect(MfaService.getMfaMethods()).resolves.toEqual(methods); + }); +}); + +describe('MfaService.requestMfaSetup', () => { + it('posts the step and returns the setup token it starts', async () => { + const setupToken = buildMfaSetupToken(); + let body: unknown; + + server.use( + http.post(MFA_URL, async ({ request }) => { + body = await request.json(); + + return HttpResponse.json(setupToken); + }) + ); + + await expect(MfaService.requestMfaSetup({ method: 1 })).resolves.toEqual(setupToken); + expect(body).toEqual({ method: 1 }); + }); + + it('rejects with the otp field when the step needs a code', async () => { + server.use( + http.post(MFA_URL, () => + HttpResponse.json({ otp: ['OTP is required'] }, { status: HTTP_STATUS_CODES.BAD_REQUEST }) + ) + ); + + const error = await MfaService.requestMfaSetup({ method: 1 }).catch( + (reason: unknown) => reason + ); + + expect(getApiFieldErrors(error).otp).toEqual(['OTP is required']); + }); +}); + +describe('MfaService.confirmMfa', () => { + it('posts the code with the setup token', async () => { + const request = { method: 2 as const, otp: '123456', token: buildMfaSetupToken().token }; + let body: unknown; + + server.use( + http.post(MFA_URL, async ({ request: sent }) => { + body = await sent.json(); + + return new HttpResponse(null, { status: HTTP_STATUS_CODES.NO_CONTENT }); + }) + ); + + await MfaService.confirmMfa(request); + + expect(body).toEqual(request); + }); +}); + +describe('MfaService.disableMfa', () => { + it('sends the method and code in the body of a DELETE', async () => { + let body: unknown; + + server.use( + http.delete(MFA_URL, async ({ request }) => { + body = await request.json(); + + return new HttpResponse(null, { status: HTTP_STATUS_CODES.NO_CONTENT }); + }) + ); + + await MfaService.disableMfa({ method: 2, otp: '123456' }); + + expect(body).toEqual({ method: 2, otp: '123456' }); + }); +}); diff --git a/packages/api/src/services/mfa/service.ts b/packages/api/src/services/mfa/service.ts new file mode 100644 index 000000000..b0f536f10 --- /dev/null +++ b/packages/api/src/services/mfa/service.ts @@ -0,0 +1,65 @@ +import { apiRequest, REQUEST_ABORT_TIMEOUT_MS } from '@irene/api/request'; +import { transformPaginatedResponse } from '@irene/api/utils/transforms'; +import type { ApiPageEnvelope } from '@irene/api/utils/pagination'; + +import type { + ApiMfa, + ApiMfaDisableRequest, + ApiMfaEnableRequest, + ApiMfaSetupToken, +} from '@irene/api/services/mfa'; + +import { MfaEndpoints } from './endpoints'; + +/** + * Talks to the endpoint that sets up the signed-in account's second factor. + * + * Every step of enabling, switching and disabling is a request to the one + * endpoint. A step that needs an OTP the request did not carry is refused with + * a 400 whose `otp` field says so, and for email that refusal is what sends + * the code: callers read that refusal as "now ask for the code", not as a failure. + */ +export default class MfaService { + /** + * Fetches both methods and which one is active. + * + * @returns The methods, the authenticator app first. + */ + public static readonly getMfaMethods = async () => { + const page = await apiRequest.get>(MfaEndpoints.mfa(), { + signal: AbortSignal.timeout(REQUEST_ABORT_TIMEOUT_MS), + }); + + return transformPaginatedResponse(page).items; + }; + + /** + * Takes a step of enabling a method, or of switching to it, that hands back a + * setup token: the first step of a setup, or the step of a switch that proves + * the current factor. + * + * @param request - The method, plus the OTP the step needs. + * @returns The secret and the signed token the confirming step carries. + */ + public static readonly requestMfaSetup = (request: ApiMfaEnableRequest) => + apiRequest.post(MfaEndpoints.mfa(), request); + + /** + * Takes the last step of enabling a method, or of switching to it: the code + * from the new factor, with the token its setup handed back. + * + * @param request - The method, the OTP and the setup token. + * @returns Resolves once the method is active. + */ + public static readonly confirmMfa = (request: Required) => + apiRequest.post(MfaEndpoints.mfa(), request); + + /** + * Takes one step of disabling the active method. + * + * @param request - The active method, plus the OTP once there is one. + * @returns Resolves once the method is off. + */ + public static readonly disableMfa = (request: ApiMfaDisableRequest) => + apiRequest.delete(MfaEndpoints.mfa(), request); +} diff --git a/packages/api/src/services/mfa/types.ts b/packages/api/src/services/mfa/types.ts new file mode 100644 index 000000000..3ce010cfd --- /dev/null +++ b/packages/api/src/services/mfa/types.ts @@ -0,0 +1,41 @@ +import type { ApiUserMfaMethod } from '@irene/api/services/user'; + +/** A method an account can set up: TOTP (an authenticator app) or HOTP (email). */ +export type ApiMfaSetupMethod = Exclude; + +/** One second-factor method, and whether it is the account's active one. */ +export interface ApiMfa { + method: ApiMfaSetupMethod; + enabled: boolean; +} + +/** + * One step of enabling or switching a method. + * + * The first step names the method alone. Each later step adds the OTP the + * previous step asked for, and the last adds the `token` a setup handed back. + */ +export interface ApiMfaEnableRequest { + method: ApiMfaSetupMethod; + otp?: string; + token?: string; +} + +/** + * What a step that starts a setup hands back: the secret an authenticator app + * is set up from, and a signed token naming it for the step that confirms. + * For email, `secret` is a cache key rather than a TOTP secret. + */ +export interface ApiMfaSetupToken { + secret: string; + token: string; +} + +/** + * Disabling the active method. Without an OTP the server asks for one, + * emailing it first when the method is email. + */ +export interface ApiMfaDisableRequest { + method: ApiUserMfaMethod; + otp?: string; +} diff --git a/packages/api/src/services/notification-preference/endpoints.ts b/packages/api/src/services/notification-preference/endpoints.ts new file mode 100644 index 000000000..e8910bbc4 --- /dev/null +++ b/packages/api/src/services/notification-preference/endpoints.ts @@ -0,0 +1,11 @@ +import { API_NAMESPACES } from '@irene/api/namespaces'; + +/** Paths for the emails the signed-in account is sent when its scans finish. */ +export const NotificationPreferenceEndpoints = { + /** The account's email preferences (GET). */ + email: () => `${API_NAMESPACES.v2}/nf_email_notification_preference` as const, + + /** Sets one or more of the scan-result preferences (PUT). */ + updateVa: () => + `${API_NAMESPACES.v2}/nf_email_notification_preference/update_user_va_notification_pref` as const, +}; diff --git a/packages/api/src/services/notification-preference/index.ts b/packages/api/src/services/notification-preference/index.ts new file mode 100644 index 000000000..f2a66fd9d --- /dev/null +++ b/packages/api/src/services/notification-preference/index.ts @@ -0,0 +1,3 @@ +export * from './endpoints'; +export type * from './types'; +export { default as NotificationPreferenceService } from './service'; diff --git a/packages/api/src/services/notification-preference/service.test.ts b/packages/api/src/services/notification-preference/service.test.ts new file mode 100644 index 000000000..d93195a23 --- /dev/null +++ b/packages/api/src/services/notification-preference/service.test.ts @@ -0,0 +1,46 @@ +import { faker } from '@faker-js/faker'; +import { http, HttpResponse } from 'msw'; +import { describe, expect, it } from 'vitest'; + +import { + NotificationPreferenceEndpoints, + NotificationPreferenceService, +} from '@irene/api/services/notification-preference'; + +import { buildVaNotificationPreference } from '@tests/factories'; +import { buildAPITestURL, server } from '@tests/server'; + +describe('NotificationPreferenceService.getVaPreference', () => { + it('keeps the four scan-result preferences and drops the role-only ones', async () => { + const preference = buildVaNotificationPreference(); + + server.use( + http.get(buildAPITestURL(NotificationPreferenceEndpoints.email()), () => + HttpResponse.json({ ...preference, upload_failed_payment: faker.datatype.boolean() }) + ) + ); + + await expect(NotificationPreferenceService.getVaPreference()).resolves.toEqual(preference); + }); +}); + +describe('NotificationPreferenceService.updateVaPreference', () => { + it('puts only the preference being changed, and returns all four', async () => { + const preference = buildVaNotificationPreference({ dynamic_scan_completed: true }); + let body: unknown; + + server.use( + http.put(buildAPITestURL(NotificationPreferenceEndpoints.updateVa()), async ({ request }) => { + body = await request.json(); + + return HttpResponse.json(preference); + }) + ); + + await expect( + NotificationPreferenceService.updateVaPreference('dynamic_scan_completed', true) + ).resolves.toEqual(preference); + + expect(body).toEqual({ dynamic_scan_completed: true }); + }); +}); diff --git a/packages/api/src/services/notification-preference/service.ts b/packages/api/src/services/notification-preference/service.ts new file mode 100644 index 000000000..890071b9d --- /dev/null +++ b/packages/api/src/services/notification-preference/service.ts @@ -0,0 +1,61 @@ +import { apiRequest, REQUEST_ABORT_TIMEOUT_MS } from '@irene/api/request'; + +import type { + ApiVaNotificationPreference, + ApiVaNotificationPreferenceKey, +} from '@irene/api/services/notification-preference'; + +import { NotificationPreferenceEndpoints } from './endpoints'; + +/** + * Keeps the four scan-result preferences, dropping the role-only ones the + * list also carries for an owner or admin. + * + * @param preferences - The body either endpoint answers with. + * @returns The four preferences. + */ +const _toVaPreference = ( + preferences: ApiVaNotificationPreference +): ApiVaNotificationPreference => ({ + all_va_completed: preferences.all_va_completed, + static_scan_completed: preferences.static_scan_completed, + dynamic_scan_completed: preferences.dynamic_scan_completed, + api_scan_completed: preferences.api_scan_completed, +}); + +/** Talks to the endpoints holding which scan results the account is emailed about. */ +export default class NotificationPreferenceService { + /** + * Fetches the account's scan-result email preferences. + * + * @returns The four preferences. + */ + public static readonly getVaPreference = async () => { + const preferences = await apiRequest.get( + NotificationPreferenceEndpoints.email(), + { signal: AbortSignal.timeout(REQUEST_ABORT_TIMEOUT_MS) } + ); + + return _toVaPreference(preferences); + }; + + /** + * Turns one preference on or off. + * + * @param key - The preference. + * @param value - Whether it is on. + * @returns All four as the server now holds them, which turning `all_va_completed` + * on changes beyond the one that was sent. + */ + public static readonly updateVaPreference = async ( + key: ApiVaNotificationPreferenceKey, + value: boolean + ) => { + const preferences = await apiRequest.put( + NotificationPreferenceEndpoints.updateVa(), + { [key]: value } + ); + + return _toVaPreference(preferences); + }; +} diff --git a/packages/api/src/services/notification-preference/types.ts b/packages/api/src/services/notification-preference/types.ts new file mode 100644 index 000000000..820279de1 --- /dev/null +++ b/packages/api/src/services/notification-preference/types.ts @@ -0,0 +1,16 @@ +/** + * Which scan results the account is emailed a summary of. Every role has these + * four; owners and admins are sent further preferences this type leaves out. + * + * `all_va_completed` sends one email once every scan on a file is done, and + * the server turns the three per-scan preferences off when it is turned on. + */ +export interface ApiVaNotificationPreference { + all_va_completed: boolean; + static_scan_completed: boolean; + dynamic_scan_completed: boolean; + api_scan_completed: boolean; +} + +/** One of the four scan-result preferences. */ +export type ApiVaNotificationPreferenceKey = keyof ApiVaNotificationPreference; diff --git a/packages/api/src/services/organization/endpoints.ts b/packages/api/src/services/organization/endpoints.ts index b8fdb490a..99b32af85 100644 --- a/packages/api/src/services/organization/endpoints.ts +++ b/packages/api/src/services/organization/endpoints.ts @@ -16,6 +16,10 @@ export const OrganizationEndpoints = { namespace: (organizationId: number | string, namespaceId: number | string) => `${API_NAMESPACES.v1}/organizations/${encodeURIComponent(organizationId)}/namespaces/${encodeURIComponent(namespaceId)}` as const, + /** The CYOD devices registered to an organization through Mercer, online or not. */ + registeredDevices: (organizationId: number | string) => + `${API_NAMESPACES.v1}/organizations/${encodeURIComponent(organizationId)}/registered-devices` as const, + /** The StoreKnox organization, which not every deployment has. */ storeknoxOrganization: () => `${API_NAMESPACES.v2}/sk_organization` as const, }; diff --git a/packages/api/src/services/organization/service.test.ts b/packages/api/src/services/organization/service.test.ts index d737d7cae..4372a934b 100644 --- a/packages/api/src/services/organization/service.test.ts +++ b/packages/api/src/services/organization/service.test.ts @@ -4,6 +4,7 @@ import { describe, expect, it } from 'vitest'; import { HTTP_STATUS_CODES } from '@irene/constants'; import { + buildCyodRegisteredDevice, buildOrganization, buildOrganizationMe, buildOrganizationMembership, @@ -156,3 +157,36 @@ describe('the timeout on the organization setup', () => { expect(recorder.latest()?.signal?.aborted).toBe(false); }); }); + +describe('OrganizationService.getRegisteredDevices', () => { + it('returns the devices out of their results', async () => { + const devices = [ + buildCyodRegisteredDevice(), + buildCyodRegisteredDevice({ is_connected: false }), + ]; + + server.use( + http.get(buildAPITestURL(OrganizationEndpoints.registeredDevices(ORGANIZATION_ID)), () => + HttpResponse.json({ results: devices }) + ) + ); + + await expect(OrganizationService.getRegisteredDevices(ORGANIZATION_ID)).resolves.toEqual( + devices + ); + }); + + it('rejects with a 403 where the organization has no device farm of its own', async () => { + server.use( + http.get(buildAPITestURL(OrganizationEndpoints.registeredDevices(ORGANIZATION_ID)), () => + HttpResponse.json({ detail: 'not configured' }, { status: HTTP_STATUS_CODES.FORBIDDEN }) + ) + ); + + const error = await OrganizationService.getRegisteredDevices(ORGANIZATION_ID).catch( + (reason: unknown) => reason + ); + + expect(getApiErrorStatus(error)).toBe(HTTP_STATUS_CODES.FORBIDDEN); + }); +}); diff --git a/packages/api/src/services/organization/service.ts b/packages/api/src/services/organization/service.ts index 3af6bff88..4c14dced1 100644 --- a/packages/api/src/services/organization/service.ts +++ b/packages/api/src/services/organization/service.ts @@ -3,6 +3,7 @@ import { transformPaginatedResponse } from '@irene/api/utils/transforms'; import type { ApiPageEnvelope } from '@irene/api/utils/pagination'; import type { + ApiCyodRegisteredDevice, ApiOrganization, ApiOrganizationMe, ApiOrganizationMembership, @@ -96,6 +97,25 @@ export default class OrganizationService { namespaceId: number | string ) => apiRequest.delete(OrganizationEndpoints.namespace(organizationId, namespaceId)); + /** + * Fetches the CYOD devices registered to an organization. The list arrives in + * `results` with no paging around it. + * + * Refused with a 403 when the organization holds no device-farm token of its + * own, which callers read as "not configured" rather than as a failure. + * + * @param organizationId - The organization to ask about. + * @returns The devices, online or not. + */ + public static readonly getRegisteredDevices = async (organizationId: number | string) => { + const response = await apiRequest.get<{ results: ApiCyodRegisteredDevice[] }>( + OrganizationEndpoints.registeredDevices(organizationId), + { signal: AbortSignal.timeout(REQUEST_ABORT_TIMEOUT_MS) } + ); + + return response.results; + }; + /** * Fetches the StoreKnox organization an account belongs to. * diff --git a/packages/api/src/services/organization/types.ts b/packages/api/src/services/organization/types.ts index e1fdd808a..87185bdc6 100644 --- a/packages/api/src/services/organization/types.ts +++ b/packages/api/src/services/organization/types.ts @@ -119,3 +119,17 @@ export interface ApiOrganizationNamespace { approved_by: number | null; requested_by: number | null; } + +/** + * A device registered to the organization through Mercer for CYOD scans, as + * the device farm describes it. Which fields it fills varies by device, so a + * name is read from the first of `name`, `model` and `serial_number` it has. + */ +export interface ApiCyodRegisteredDevice { + name: string | null; + serial_number: string; + model: string; + platform: number; + is_connected: boolean; + created_on: string | null; +} diff --git a/packages/api/src/services/personal-token/endpoints.ts b/packages/api/src/services/personal-token/endpoints.ts new file mode 100644 index 000000000..2c4c4e32c --- /dev/null +++ b/packages/api/src/services/personal-token/endpoints.ts @@ -0,0 +1,11 @@ +import { API_NAMESPACES } from '@irene/api/namespaces'; + +/** Paths for the API tokens the signed-in account has generated for itself. */ +export const PersonalTokenEndpoints = { + /** Lists the tokens (GET), and generates one (POST). */ + list: () => `${API_NAMESPACES.v1}/personaltokens` as const, + + /** Revokes one token (DELETE). */ + detail: (id: number | string) => + `${API_NAMESPACES.v1}/personaltokens/${encodeURIComponent(id)}` as const, +}; diff --git a/packages/api/src/services/personal-token/index.ts b/packages/api/src/services/personal-token/index.ts new file mode 100644 index 000000000..569de8639 --- /dev/null +++ b/packages/api/src/services/personal-token/index.ts @@ -0,0 +1,3 @@ +export * from './endpoints'; +export type * from './types'; +export { default as PersonalTokenService } from './service'; diff --git a/packages/api/src/services/personal-token/service.test.ts b/packages/api/src/services/personal-token/service.test.ts new file mode 100644 index 000000000..f16ccae38 --- /dev/null +++ b/packages/api/src/services/personal-token/service.test.ts @@ -0,0 +1,66 @@ +import { http, HttpResponse } from 'msw'; +import { describe, expect, it } from 'vitest'; + +import { HTTP_STATUS_CODES } from '@irene/constants'; + +import { PersonalTokenEndpoints, PersonalTokenService } from '@irene/api/services/personal-token'; +import { buildPersonalToken, toPersonalTokenResource } from '@tests/factories'; +import { buildAPITestURL, server } from '@tests/server'; + +const LIST_URL = buildAPITestURL(PersonalTokenEndpoints.list()); + +describe('PersonalTokenService.getPersonalTokens', () => { + it('asks for the first ten and returns them out of their envelopes', async () => { + const tokens = [buildPersonalToken(), buildPersonalToken()]; + let query: URLSearchParams | undefined; + + server.use( + http.get(LIST_URL, ({ request }) => { + query = new URL(request.url).searchParams; + + return HttpResponse.json({ data: tokens.map(toPersonalTokenResource) }); + }) + ); + + await expect(PersonalTokenService.getPersonalTokens()).resolves.toEqual(tokens); + expect(query?.get('limit')).toBe('10'); + expect(query?.get('offset')).toBe('0'); + }); +}); + +describe('PersonalTokenService.createPersonalToken', () => { + it('posts the name and returns the new token', async () => { + const token = buildPersonalToken(); + let body: unknown; + + server.use( + http.post(LIST_URL, async ({ request }) => { + body = await request.json(); + + return HttpResponse.json({ data: toPersonalTokenResource(token) }); + }) + ); + + await expect(PersonalTokenService.createPersonalToken(token.name)).resolves.toEqual(token); + expect(body).toEqual({ name: token.name }); + }); +}); + +describe('PersonalTokenService.revokePersonalToken', () => { + it('deletes the token by its id', async () => { + const token = buildPersonalToken(); + let wasDeleted = false; + + server.use( + http.delete(buildAPITestURL(PersonalTokenEndpoints.detail(token.id)), () => { + wasDeleted = true; + + return new HttpResponse(null, { status: HTTP_STATUS_CODES.NO_CONTENT }); + }) + ); + + await PersonalTokenService.revokePersonalToken(token.id); + + expect(wasDeleted).toBe(true); + }); +}); diff --git a/packages/api/src/services/personal-token/service.ts b/packages/api/src/services/personal-token/service.ts new file mode 100644 index 000000000..418d0033a --- /dev/null +++ b/packages/api/src/services/personal-token/service.ts @@ -0,0 +1,67 @@ +import { apiRequest, REQUEST_ABORT_TIMEOUT_MS } from '@irene/api/request'; + +import type { + ApiPersonalToken, + ApiPersonalTokenListResponse, + ApiPersonalTokenResource, + ApiPersonalTokenResponse, +} from '@irene/api/services/personal-token'; + +import { PersonalTokenEndpoints } from './endpoints'; + +/** irene asks for the first page and offers no other, so the list stops at the newest ten. */ +const PERSONAL_TOKEN_PAGE = { limit: 10, offset: 0 }; + +/** + * Takes the JSON:API envelope off one token. + * + * @param resource - The token as the endpoint sends it. + * @returns The token. + */ +const _toPersonalToken = ({ id, attributes }: ApiPersonalTokenResource): ApiPersonalToken => ({ + id, + name: attributes.name, + key: attributes.key, + created: attributes.created, +}); + +/** Talks to the endpoint holding the API tokens the signed-in account has generated. */ +export default class PersonalTokenService { + /** + * Fetches the account's tokens, newest first. + * + * @returns The newest ten, which is all irene shows. + */ + public static readonly getPersonalTokens = async () => { + const response = await apiRequest.get( + PersonalTokenEndpoints.list(), + { params: PERSONAL_TOKEN_PAGE, signal: AbortSignal.timeout(REQUEST_ABORT_TIMEOUT_MS) } + ); + + return response.data.map(_toPersonalToken); + }; + + /** + * Generates a token. Names are unique per account. + * + * @param name - What the account calls the token. + * @returns The new token, key included. + */ + public static readonly createPersonalToken = async (name: string) => { + const response = await apiRequest.post( + PersonalTokenEndpoints.list(), + { name } + ); + + return _toPersonalToken(response.data); + }; + + /** + * Revokes a token, so the API refuses it from then on. + * + * @param id - The token to revoke. + * @returns Resolves once it is revoked. + */ + public static readonly revokePersonalToken = (id: string) => + apiRequest.delete(PersonalTokenEndpoints.detail(id)); +} diff --git a/packages/api/src/services/personal-token/types.ts b/packages/api/src/services/personal-token/types.ts new file mode 100644 index 000000000..dc5af6c97 --- /dev/null +++ b/packages/api/src/services/personal-token/types.ts @@ -0,0 +1,43 @@ +/** A token as the endpoint sends it: a JSON:API resource. */ +export interface ApiPersonalTokenResource { + id: string; + type: 'personaltokens'; + attributes: { + key: string; + name: string; + created: string; + }; +} + +/** The list as the endpoint sends it. */ +export interface ApiPersonalTokenListResponse { + data: ApiPersonalTokenResource[]; +} + +/** One generated token as the endpoint sends it. */ +export interface ApiPersonalTokenResponse { + data: ApiPersonalTokenResource; +} + +/** A token the account can call the API with, with the envelope taken off. */ +export interface ApiPersonalToken { + id: string; + name: string; + key: string; + /** When it was generated, as an ISO 8601 timestamp. */ + created: string; +} + +/** + * One complaint in a JSON:API error body. A name the account already uses is + * refused with `code: 'unique'`. + */ +export interface ApiJsonApiError { + code?: string; + detail?: string; +} + +/** A refusal from a JSON:API endpoint: a list of complaints rather than DRF's per-field object. */ +export interface ApiJsonApiErrorResponse { + errors?: ApiJsonApiError[]; +} diff --git a/packages/api/src/services/user/endpoints.ts b/packages/api/src/services/user/endpoints.ts index 711f78829..0d65b3ba8 100644 --- a/packages/api/src/services/user/endpoints.ts +++ b/packages/api/src/services/user/endpoints.ts @@ -3,4 +3,5 @@ import { API_NAMESPACES } from '@irene/api/namespaces'; /** Paths for the account signed in to this session. */ export const UserEndpoints = { detail: (id: number | string) => `${API_NAMESPACES.v1}/users/${encodeURIComponent(id)}` as const, + language: () => `${API_NAMESPACES.v1}/lang` as const, }; diff --git a/packages/api/src/services/user/service.test.ts b/packages/api/src/services/user/service.test.ts index e28f6ed4b..15b4fd388 100644 --- a/packages/api/src/services/user/service.test.ts +++ b/packages/api/src/services/user/service.test.ts @@ -1,3 +1,4 @@ +import { faker } from '@faker-js/faker'; import { http, HttpResponse } from 'msw'; import { describe, expect, it } from 'vitest'; @@ -69,3 +70,37 @@ describe('the timeout on the account', () => { expect(recorder.latest()?.signal?.aborted).toBe(false); }); }); + +describe('UserService.setLanguage', () => { + const languageUrl = buildAPITestURL(UserEndpoints.language()); + + it('posts the language form-encoded, as the endpoint reads it', async () => { + const lang = faker.helpers.arrayElement(['en', 'ja'] as const); + let contentType: string | null = null; + let body = ''; + + server.use( + http.post(languageUrl, async ({ request }) => { + contentType = request.headers.get('content-type'); + body = await request.text(); + + return HttpResponse.json({}); + }) + ); + + await UserService.setLanguage(lang); + + expect(contentType).toContain('application/x-www-form-urlencoded'); + expect(new URLSearchParams(body).get('lang')).toBe(lang); + }); + + it('rejects when the request is refused', async () => { + server.use( + http.post(languageUrl, () => HttpResponse.json({}, { status: HTTP_STATUS_CODES.BAD_REQUEST })) + ); + + const error = await UserService.setLanguage('en').catch((reason: unknown) => reason); + + expect(getApiErrorStatus(error)).toBe(HTTP_STATUS_CODES.BAD_REQUEST); + }); +}); diff --git a/packages/api/src/services/user/service.ts b/packages/api/src/services/user/service.ts index 182a08205..8c5ca8525 100644 --- a/packages/api/src/services/user/service.ts +++ b/packages/api/src/services/user/service.ts @@ -1,6 +1,6 @@ import { apiRequest, REQUEST_ABORT_TIMEOUT_MS } from '@irene/api/request'; import { transformUserResponse } from '@irene/api/utils/transforms'; -import type { ApiUserResponse } from '@irene/api/services/user'; +import type { ApiUserLanguage, ApiUserResponse } from '@irene/api/services/user'; import { UserEndpoints } from './endpoints'; @@ -22,4 +22,16 @@ export default class UserService { return transformUserResponse(response); }; + + /** + * Sets the language the account reads the product in. + * + * Sent form-encoded, as irene sends it: the endpoint reads `lang` from a form + * body. The server stores it on the account, so every session and device + * follows it from the next load. + * + * @param lang - The language to read in. + */ + public static readonly setLanguage = (lang: ApiUserLanguage) => + apiRequest.post(UserEndpoints.language(), new URLSearchParams({ lang })); } diff --git a/packages/api/tests/factories/index.ts b/packages/api/tests/factories/index.ts index 85814592d..3daaaedc4 100644 --- a/packages/api/tests/factories/index.ts +++ b/packages/api/tests/factories/index.ts @@ -7,13 +7,17 @@ export { } from '@tests/factories/configuration'; export { + buildCyodRegisteredDevice, buildOrganization, buildOrganizationMe, buildOrganizationMembership, buildStoreknoxOrganization, } from '@tests/factories/organization'; +export { buildMfa, buildMfaSetupToken } from '@tests/factories/mfa'; +export { buildVaNotificationPreference } from '@tests/factories/notification-preference'; export { buildPartner } from '@tests/factories/partner'; +export { buildPersonalToken, toPersonalTokenResource } from '@tests/factories/personal-token'; export { buildProject } from '@tests/factories/project'; export { buildSubmission, buildSubmissionAppData } from '@tests/factories/submission'; export { buildSsoCheck } from '@tests/factories/sso'; diff --git a/packages/api/tests/factories/mfa.ts b/packages/api/tests/factories/mfa.ts new file mode 100644 index 000000000..62239a9ad --- /dev/null +++ b/packages/api/tests/factories/mfa.ts @@ -0,0 +1,18 @@ +import { faker } from '@faker-js/faker'; +import type { ApiMfa, ApiMfaSetupToken } from '@irene/api/services/mfa'; + +/** One second-factor method, off unless the test turns it on. */ +export const buildMfa = (overrides: Partial = {}): ApiMfa => ({ + method: faker.helpers.arrayElement([1, 2] as const), + enabled: false, + ...overrides, +}); + +/** What a step starting a setup hands back. */ +export const buildMfaSetupToken = ( + overrides: Partial = {} +): ApiMfaSetupToken => ({ + secret: faker.string.alphanumeric({ length: 32, casing: 'upper' }), + token: faker.string.alphanumeric(64), + ...overrides, +}); diff --git a/packages/api/tests/factories/notification-preference.ts b/packages/api/tests/factories/notification-preference.ts new file mode 100644 index 000000000..b2f5ce015 --- /dev/null +++ b/packages/api/tests/factories/notification-preference.ts @@ -0,0 +1,13 @@ +import { faker } from '@faker-js/faker'; +import type { ApiVaNotificationPreference } from '@irene/api/services/notification-preference'; + +/** The four scan-result preferences, each on or off at random unless pinned. */ +export const buildVaNotificationPreference = ( + overrides: Partial = {} +): ApiVaNotificationPreference => ({ + all_va_completed: faker.datatype.boolean(), + static_scan_completed: faker.datatype.boolean(), + dynamic_scan_completed: faker.datatype.boolean(), + api_scan_completed: faker.datatype.boolean(), + ...overrides, +}); diff --git a/packages/api/tests/factories/organization.ts b/packages/api/tests/factories/organization.ts index 16ceb92cb..acaf41f37 100644 --- a/packages/api/tests/factories/organization.ts +++ b/packages/api/tests/factories/organization.ts @@ -1,6 +1,7 @@ import { faker } from '@faker-js/faker'; import type { + ApiCyodRegisteredDevice, ApiOrganization, ApiOrganizationAiFeatures, ApiOrganizationFeatures, @@ -101,3 +102,16 @@ export const buildStoreknoxOrganization = ( }, ...overrides, }); + +/** A device registered through Mercer, online unless the test says otherwise. */ +export const buildCyodRegisteredDevice = ( + overrides: Partial = {} +): ApiCyodRegisteredDevice => ({ + name: faker.commerce.productName(), + serial_number: faker.string.alphanumeric({ length: 12, casing: 'upper' }), + model: faker.commerce.product(), + platform: faker.helpers.arrayElement([0, 1]), + is_connected: true, + created_on: faker.date.past().toISOString(), + ...overrides, +}); diff --git a/packages/api/tests/factories/personal-token.ts b/packages/api/tests/factories/personal-token.ts new file mode 100644 index 000000000..8c58d1539 --- /dev/null +++ b/packages/api/tests/factories/personal-token.ts @@ -0,0 +1,23 @@ +import { faker } from '@faker-js/faker'; + +import type { + ApiPersonalToken, + ApiPersonalTokenResource, +} from '@irene/api/services/personal-token'; + +/** A token the account generated. */ +export const buildPersonalToken = ( + overrides: Partial = {} +): ApiPersonalToken => ({ + id: String(faker.number.int({ min: 1, max: 99999 })), + name: faker.word.words(2), + key: faker.string.hexadecimal({ length: 40, prefix: '', casing: 'lower' }), + created: faker.date.past().toISOString(), + ...overrides, +}); + +/** The same token as the endpoint sends it. */ +export const toPersonalTokenResource = ({ + id, + ...attributes +}: ApiPersonalToken): ApiPersonalTokenResource => ({ id, type: 'personaltokens', attributes }); diff --git a/packages/config/src/product.test.ts b/packages/config/src/product.test.ts new file mode 100644 index 000000000..cdf5c6182 --- /dev/null +++ b/packages/config/src/product.test.ts @@ -0,0 +1,18 @@ +import { describe, expect, it } from 'vitest'; +import { MERCER_DOWNLOAD_URL, PRODUCT_VERSIONS } from './product'; + +describe('MERCER_DOWNLOAD_URL', () => { + it('is served over HTTPS, since it hands out an executable', () => { + expect(new URL(MERCER_DOWNLOAD_URL).protocol).toBe('https:'); + }); + + it('ends without a slash, so appending / never doubles one', () => { + expect(MERCER_DOWNLOAD_URL.endsWith('/')).toBe(false); + }); +}); + +describe('PRODUCT_VERSIONS', () => { + it('names a release for each product the navigation shows a version for', () => { + expect(Object.keys(PRODUCT_VERSIONS)).toEqual(['appknox', 'storeknox']); + }); +}); diff --git a/packages/config/src/product.ts b/packages/config/src/product.ts index 116543ff3..4810220f0 100644 --- a/packages/config/src/product.ts +++ b/packages/config/src/product.ts @@ -34,3 +34,13 @@ export const G_RECAPTCHA = { siteKey: '6LffPdIaAAAAANWL4gm7J6j9EJzKSuYEDAQ0Ry2x', jsUrl: 'https://recaptcha.net/recaptcha/api.js?render=explicit', } as const; + +/** + * Where the Mercer desktop app is downloaded from: the latest release of each + * build sits under it by file name. CYOD devices are registered through Mercer. + * + * irene reads this from `IRENE_MERCER_DOWNLOAD_URL` so a deployment can point + * at a mirror. No deployment does, so it is fixed here rather than added as a + * configuration key; add the key if one ever needs to. + */ +export const MERCER_DOWNLOAD_URL = 'https://appknox-mercer.s3.amazonaws.com/mercer/releases/latest'; diff --git a/packages/translations/package.json b/packages/translations/package.json index 5cc635098..1d5fcdc30 100644 --- a/packages/translations/package.json +++ b/packages/translations/package.json @@ -5,6 +5,7 @@ "type": "module", "exports": { "./ak-message-translate": "./src/ak-message-translate.tsx", + "./date-time": "./src/date-time.ts", "./intl": "./src/intl.ts", "./locale": "./src/locale.ts", "./messages": "./src/messages.ts", @@ -23,6 +24,7 @@ "react": "^19.2.0" }, "dependencies": { + "dayjs": "^1.11.23", "react-intl": "^11.0.1" }, "devDependencies": { diff --git a/packages/translations/src/date-time.test.ts b/packages/translations/src/date-time.test.ts new file mode 100644 index 000000000..b0cedf9f5 --- /dev/null +++ b/packages/translations/src/date-time.test.ts @@ -0,0 +1,113 @@ +import { afterEach, describe, expect, it } from 'vitest'; + +import { formatDateTime, formatRelativeTime } from '@irene/translations/date-time'; +import { setLocale } from '@irene/translations/intl'; + +/* + A fixed moment, built in local time so the expectations below hold wherever + the suite runs. A UTC timestamp would read as a different hour per timezone. +*/ +const APRIL_THIRD = new Date(2026, 3, 3, 20, 2); + +afterEach(async () => { + await setLocale('en'); +}); + +describe('formatDateTime', () => { + describe('in English', () => { + it('writes the shortest date in digits', () => { + expect(formatDateTime(APRIL_THIRD)).toBe('04/03/2026'); + }); + + it('shortens the month, so the day and month are never read the wrong way round', () => { + expect(formatDateTime(APRIL_THIRD, 'mediumDate')).toBe('Apr 3, 2026'); + }); + + it('writes the month out in full', () => { + expect(formatDateTime(APRIL_THIRD, 'longDate')).toBe('April 3, 2026'); + }); + + it('writes the time on a twelve-hour clock', () => { + expect(formatDateTime(APRIL_THIRD, 'time')).toBe('8:02 PM'); + }); + + it('writes a date and a time together', () => { + expect(formatDateTime(APRIL_THIRD, 'dateTime')).toBe('04/03/2026 8:02 PM'); + }); + + it('names the month and writes the time', () => { + expect(formatDateTime(APRIL_THIRD, 'longDateTime')).toBe('April 3, 2026 8:02 PM'); + }); + }); + + describe('in Japanese', () => { + it('orders the shortest date as the language does', async () => { + await setLocale('ja'); + + expect(formatDateTime(APRIL_THIRD)).toBe('2026/04/03'); + }); + + it('names the month as the language does', async () => { + await setLocale('ja'); + + expect(formatDateTime(APRIL_THIRD, 'longDate')).toBe('2026年4月3日'); + }); + + it('shortens the month as the language does, which does not shorten it', async () => { + await setLocale('ja'); + + expect(formatDateTime(APRIL_THIRD, 'mediumDate')).toBe('2026年4月3日'); + }); + + it('writes the time on the clock the language keeps', async () => { + await setLocale('ja'); + + expect(formatDateTime(APRIL_THIRD, 'time')).toBe('20:02'); + }); + }); + + describe('what it is given', () => { + it('reads a timestamp as well as a Date', () => { + expect(formatDateTime(APRIL_THIRD.toISOString(), 'longDate')).toBe('April 3, 2026'); + }); + + it('reads milliseconds since the epoch', () => { + expect(formatDateTime(APRIL_THIRD.getTime(), 'longDate')).toBe('April 3, 2026'); + }); + + it('answers nothing for a timestamp it cannot read, rather than "Invalid Date"', () => { + expect(formatDateTime('not a date')).toBe(''); + }); + + it('answers nothing where the API sent none', () => { + expect(formatDateTime(null)).toBe(''); + expect(formatDateTime(undefined)).toBe(''); + }); + }); +}); + +describe('formatRelativeTime', () => { + const threeDaysLater = new Date(2026, 3, 6, 20, 2); + + it('states the distance in words', () => { + expect(formatRelativeTime(APRIL_THIRD, threeDaysLater)).toBe('3 days ago'); + }); + + it('states it in the account\u2019s own language', async () => { + await setLocale('ja'); + + expect(formatRelativeTime(APRIL_THIRD, threeDaysLater)).toBe('3日前'); + }); + + it('measures against now when nothing else is given', () => { + expect(formatRelativeTime(new Date())).toBe('a few seconds ago'); + }); + + it('answers nothing for a timestamp it cannot read', () => { + expect(formatRelativeTime('not a date')).toBe(''); + }); + + it('answers nothing where the API sent none', () => { + expect(formatRelativeTime(null)).toBe(''); + }); +}); diff --git a/packages/translations/src/date-time.ts b/packages/translations/src/date-time.ts new file mode 100644 index 000000000..5e2cd337e --- /dev/null +++ b/packages/translations/src/date-time.ts @@ -0,0 +1,80 @@ +import dayjs from 'dayjs'; +import localizedFormat from 'dayjs/plugin/localizedFormat'; +import relativeTime from 'dayjs/plugin/relativeTime'; + +import 'dayjs/locale/ja'; + +import { getLocale } from '@irene/translations/intl'; + +// `localizedFormat` is what makes the tokens below follow the language. +dayjs.extend(localizedFormat); +dayjs.extend(relativeTime); + +/** The shapes a date or time is written in. */ +export type DateTimeStyle = + | 'date' + | 'mediumDate' + | 'longDate' + | 'time' + | 'dateTime' + | 'longDateTime'; + +/* Tokens rather than patterns, so the order, separators and clock follow the language. */ +const STYLE_TOKENS: Record = { + /** The shortest form, in digits: "04/03/2026", "2026/04/03". */ + date: 'L', + + /** The month shortened, so 03/04 is never read the wrong way round: "Apr 3, 2026". */ + mediumDate: 'll', + + /** The month written out: "April 3, 2026". */ + longDate: 'LL', + + /** The time of day, on the clock the language keeps: "8:02 PM", "20:02". */ + time: 'LT', + + /** A date and the time of day: "04/03/2026 8:02 PM". */ + dateTime: 'L LT', + + /** The month named, with the time: "April 3, 2026 8:02 PM". */ + longDateTime: 'LLL', +}; + +/** Anything the API might send for a moment in time. */ +export type DateTimeValue = string | number | Date | null | undefined; + +/** + * Writes a moment in the account's own language. + * + * The locale is applied per call, since `dayjs.locale()` would set it globally. + * + * @param value - The moment, as the API sends it. + * @param style - The shape to write it in. Defaults to the shortest date. + * @returns The formatted text, or an empty string for a moment it cannot read. + */ +export function formatDateTime(value: DateTimeValue, style: DateTimeStyle = 'date'): string { + if (value === null || value === undefined) { + return ''; + } + + const moment = dayjs(value); + + return moment.isValid() ? moment.locale(getLocale()).format(STYLE_TOKENS[style]) : ''; +} + +/** + * States how long ago something happened, in the account's own language. + * + * @param value - When it happened, as the API sends it. + * @param now - The moment to measure against. Defaults to the current time. + * @returns The distance in words, e.g. "3 days ago", or an empty string for a moment it cannot read. + */ +export function formatRelativeTime(value: DateTimeValue, now: Date = new Date()): string { + if (value === null || value === undefined) { + return ''; + } + + const moment = dayjs(value); + + return moment.isValid() ? moment.locale(getLocale()).from(dayjs(now)) : ''; +} diff --git a/packages/translations/src/formats.ts b/packages/translations/src/formats.ts index 55815918b..428047adf 100644 --- a/packages/translations/src/formats.ts +++ b/packages/translations/src/formats.ts @@ -7,6 +7,10 @@ export const FORMATS: CustomFormats = { }, date: { hhmmss: { hour: 'numeric', minute: 'numeric', second: 'numeric' }, + /** A calendar date with the month named, so 03/04 is never read the wrong way round: "Apr 3, 2026". */ + mediumDate: { year: 'numeric', month: 'short', day: 'numeric' }, + /** A calendar date with the month written out: "April 3, 2026". */ + longDate: { year: 'numeric', month: 'long', day: 'numeric' }, }, number: { EUR: { style: 'currency', currency: 'EUR', minimumFractionDigits: 2, maximumFractionDigits: 2 }, diff --git a/packages/translations/translations/en.json b/packages/translations/translations/en.json index d5a0a819a..ec4679232 100644 --- a/packages/translations/translations/en.json +++ b/packages/translations/translations/en.json @@ -188,6 +188,13 @@ "by": "by", "cancel": "Cancel", "chooseFile": "Choose file", + "enterCurrentPassword": "Enter Current Password", + "mfaAppAndroidIos": "For Android & iOS:", + "mfaAppAndroidIosBlackberry": "For Android, iOS, and Blackberry:", + "mfaAppWindowsPhone": "For Windows Phone:", + "mfaMethodApp": "Authenticator App", + "mfaOtpSendFailed": "Failed to send OTP. Please try again.", + "mfaOtpSentTo": "OTP sent to {email}", "noFileChosen": "No file chosen", "cancelled": "Cancelled", "cancelScan": "Cancel Scan", @@ -573,6 +580,7 @@ "editTeamName": "Edit Team Name", "editTeamNameInputLabel": "Here you can edit the team name", "editAnalysis": "Edit Analysis", + "refresh": "Refresh", "requestEditAnalysis": "Request Edit Analysis", "editAnalysisForMembersDescription": "Enables members to request edits to vulnerability analysis risk levels, subject to Owner/Admin review and approval.", "editAnalyses": "Edit Analyses", @@ -1269,8 +1277,8 @@ "enterCode": "After scanning the barcode image, the app will display a six-digit code, enter that code below." }, "enableMFAEmail": { - "sendMailMsg": "An OTP code will be send to email ", - "description": "We have sent a security code to email ", + "sendMailMsg": "We will send a one-time code to {email}.", + "description": "We have sent a security code to {email}.", "enterCode": "Enter OTP" }, "disableMFA": { @@ -2221,6 +2229,7 @@ "connectedDeviceDesc": "Check out the details of the devices that have been added to the CYOD settings.", "emptyHint": "Click on the Register a device to add a new device", "yourRegisteredDevices": "Your registered devices", + "howToRegister": "How to register a device", "stepsIntro": "To add a device, follow these steps:", "stepCertificate": "If you have an iOS device to add an iOS Signing Certificate, navigate to Account Settings, then select CYOD Settings. Click on 'iOS Signing Certificate' and hit the 'Add Certificate' button to proceed.", "stepCertificateNote": "Note - View the added and existing certificates in the existing certificates tab.", @@ -2446,6 +2455,7 @@ "searchQuery": "Search By Package Name", "searchTeamByName": "Search by team name", "security": "Security", + "securitySettings": "Security Settings", "securityDashboard": "Security Dashboard", "securityDashboardDesc": "For security researchers to perform manual assessments (PT)", "selectAll": "Select All", diff --git a/packages/translations/translations/ja.json b/packages/translations/translations/ja.json index 9c0bcce03..2bb8811bc 100644 --- a/packages/translations/translations/ja.json +++ b/packages/translations/translations/ja.json @@ -188,6 +188,13 @@ "by": "by", "cancel": "キャンセル", "chooseFile": "Choose file", + "enterCurrentPassword": "Enter Current Password", + "mfaAppAndroidIos": "For Android & iOS:", + "mfaAppAndroidIosBlackberry": "For Android, iOS, and Blackberry:", + "mfaAppWindowsPhone": "For Windows Phone:", + "mfaMethodApp": "Authenticator App", + "mfaOtpSendFailed": "Failed to send OTP. Please try again.", + "mfaOtpSentTo": "OTP sent to {email}", "noFileChosen": "No file chosen", "cancelled": "Cancelled", "cancelScan": "Cancel Scan", @@ -573,6 +580,7 @@ "editTeamName": "Edit Team Name", "editTeamNameInputLabel": "Here you can edit the team name", "editAnalysis": "Edit Analysis", + "refresh": "更新", "requestEditAnalysis": "Request Edit Analysis", "editAnalysisForMembersDescription": "Enables members to request edits to vulnerability analysis risk levels, subject to Owner/Admin review and approval.", "editAnalyses": "Edit Analyses", @@ -1269,8 +1277,8 @@ "enterCode": "After scanning the barcode image, the app will display a six-digit code, enter that code below." }, "enableMFAEmail": { - "sendMailMsg": "An OTP code will be send to email ", - "description": "We have sent a security code to email ", + "sendMailMsg": "We will send a one-time code to {email}.", + "description": "We have sent a security code to {email}.", "enterCode": "Enter OTP" }, "disableMFA": { @@ -2221,6 +2229,7 @@ "connectedDeviceDesc": "Check out the details of the devices that have been added to the CYOD settings.", "emptyHint": "Click on the Register a device to add a new device", "yourRegisteredDevices": "Your registered devices", + "howToRegister": "How to register a device", "stepsIntro": "To add a device, follow these steps:", "stepCertificate": "If you have an iOS device to add an iOS Signing Certificate, navigate to Account Settings, then select CYOD Settings. Click on 'iOS Signing Certificate' and hit the 'Add Certificate' button to proceed.", "stepCertificateNote": "Note - View the added and existing certificates in the existing certificates tab.", @@ -2446,6 +2455,7 @@ "searchQuery": "パッケージ名で検索", "searchTeamByName": "Search by team name", "security": "セキュリティ", + "securitySettings": "Security Settings", "securityDashboard": "Security Dashboard", "securityDashboardDesc": "For security researchers to perform manual assessments (PT)", "selectAll": "Select All", diff --git a/packages/ui/src/components/ak-button/index.tsx b/packages/ui/src/components/ak-button/index.tsx index 43e0c8c43..03947f6ba 100644 --- a/packages/ui/src/components/ak-button/index.tsx +++ b/packages/ui/src/components/ak-button/index.tsx @@ -67,7 +67,7 @@ function AkButton({ children ) : ( - {loading && } + {loading && } {!loading && leftIcon && ( diff --git a/packages/ui/src/components/ak-input/index.test.tsx b/packages/ui/src/components/ak-input/index.test.tsx index 555c1a7aa..4c3e88a64 100644 --- a/packages/ui/src/components/ak-input/index.test.tsx +++ b/packages/ui/src/components/ak-input/index.test.tsx @@ -153,6 +153,18 @@ describe('the password reveal control', () => { ); }); + it('shows a struck-through eye while the password is hidden, and an open one once it shows', async () => { + render(); + + const icon = () => document.querySelector('[data-test-reveal-icon]'); + + expect(icon()).toHaveAttribute('data-test-reveal-icon', 'hidden'); + + await userEvent.click(revealButton()); + + expect(icon()).toHaveAttribute('data-test-reveal-icon', 'visible'); + }); + it('renders the control disabled while the field is disabled', () => { render(); diff --git a/packages/ui/src/components/ak-input/index.tsx b/packages/ui/src/components/ak-input/index.tsx index 7be451257..5758af1b3 100644 --- a/packages/ui/src/components/ak-input/index.tsx +++ b/packages/ui/src/components/ak-input/index.tsx @@ -84,9 +84,11 @@ function AkInput({ 'transition-colors hover:text-foreground disabled:pointer-events-none' )} > + {/* The icon shows the field's state: a struck-through eye while the password is hidden. */} )} diff --git a/packages/ui/src/components/ak-spinner/index.stories.tsx b/packages/ui/src/components/ak-spinner/index.stories.tsx index db93636fc..9e50f16b9 100644 --- a/packages/ui/src/components/ak-spinner/index.stories.tsx +++ b/packages/ui/src/components/ak-spinner/index.stories.tsx @@ -13,17 +13,49 @@ type Story = StoryObj; export const Default: Story = {}; -/** The sizes it is used at, and how it follows the text colour. */ +/** The sizes it is used at. */ export const Sizes: Story = { render: () => ( -
    +
    - + +
    + ), +}; + +/** Every colour it spins in. */ +export const Colors: Story = { + render: () => ( +
    + + + + + + + + + + + + + +
    + ), +}; + +/** `inherit` takes the colour of whatever surrounds it, as a button's does. */ +export const Inherited: Story = { + render: () => ( +
    + + + Uploading
    ), }; diff --git a/packages/ui/src/components/ak-spinner/index.test.tsx b/packages/ui/src/components/ak-spinner/index.test.tsx index 9bc8d1c48..ea09d552f 100644 --- a/packages/ui/src/components/ak-spinner/index.test.tsx +++ b/packages/ui/src/components/ak-spinner/index.test.tsx @@ -28,6 +28,36 @@ describe('AkSpinner', () => { expect(spinner).not.toHaveClass('size-4'); }); + it('spins in the brand colour unless another is asked for', () => { + render(); + + expect(screen.getByRole('status')).toHaveClass('text-primary'); + }); + + it('spins in the colour it is given', () => { + render(); + + const spinner = screen.getByRole('status'); + + expect(spinner).toHaveClass('text-success'); + expect(spinner).not.toHaveClass('text-primary'); + }); + + it('takes the surrounding text colour when asked to inherit', () => { + render(); + + expect(screen.getByRole('status')).toHaveClass('text-inherit'); + }); + + it('lets a className override the colour, for a one-off', () => { + render(); + + const spinner = screen.getByRole('status'); + + expect(spinner).toHaveClass('text-danger'); + expect(spinner).not.toHaveClass('text-primary'); + }); + it('passes through svg props', () => { render(); diff --git a/packages/ui/src/components/ak-spinner/index.tsx b/packages/ui/src/components/ak-spinner/index.tsx index 384ff4658..e74673030 100644 --- a/packages/ui/src/components/ak-spinner/index.tsx +++ b/packages/ui/src/components/ak-spinner/index.tsx @@ -1,21 +1,28 @@ +import { type VariantProps } from 'class-variance-authority'; import type { ComponentProps } from 'react'; import { AkIcon } from '@irene/ui/ak-icon'; import { cn } from '@irene/ui/cn'; +import { akSpinnerVariants } from './variants'; + +type AkSpinnerProps = Omit, 'name' | 'color'> & + VariantProps; + /** - * The spinner shown while something is loading. Colour follows `currentColor`. + * The spinner shown while something is loading. * + * @param props.color - Which colour it spins in. `inherit` takes the surrounding text's. * @param props.className - Sets the size, defaulting to the text size. */ -function AkSpinner({ className, ...props }: Omit, 'name'>) { +function AkSpinner({ color, className, ...props }: Readonly) { return ( ); diff --git a/packages/ui/src/components/ak-spinner/variants.ts b/packages/ui/src/components/ak-spinner/variants.ts new file mode 100644 index 000000000..204bdca54 --- /dev/null +++ b/packages/ui/src/components/ak-spinner/variants.ts @@ -0,0 +1,23 @@ +import { cva } from 'class-variance-authority'; + +/* Colour is the only thing that varies; the size comes from the caller's className. */ +export const akSpinnerVariants = cva('size-4 animate-spin', { + variants: { + color: { + inherit: 'text-inherit', + primary: 'text-primary', + secondary: 'text-secondary', + neutral: 'text-foreground-muted', + textPrimary: 'text-foreground', + textSecondary: 'text-foreground-muted', + success: 'text-success', + error: 'text-danger', + warn: 'text-warning-strong', + info: 'text-info', + }, + }, + + defaultVariants: { + color: 'primary', + }, +}); diff --git a/packages/ui/src/components/ak-table/helpers.ts b/packages/ui/src/components/ak-table/helpers.ts index 2cd7335b7..741db4550 100644 --- a/packages/ui/src/components/ak-table/helpers.ts +++ b/packages/ui/src/components/ak-table/helpers.ts @@ -10,9 +10,11 @@ import { * * @interface AkTableColumnMeta * @property {string} [width] - A CSS width for the column, e.g. `40%`. A table with any width set lays its columns out fixed, so the widths are honoured rather than treated as hints. + * @property {'left' | 'center' | 'right'} [align] - Where the header and the cells sit, so a column of icons lines up under its heading. Left when unset. */ export interface AkTableColumnMeta { width?: string; + align?: 'left' | 'center' | 'right'; } /** diff --git a/packages/ui/src/components/ak-table/index.test.tsx b/packages/ui/src/components/ak-table/index.test.tsx index 5a87a23a9..683b2d07b 100644 --- a/packages/ui/src/components/ak-table/index.test.tsx +++ b/packages/ui/src/components/ak-table/index.test.tsx @@ -170,6 +170,19 @@ describe('column widths', () => { expect(cols[1]).toHaveStyle({ width: '30%' }); }); + it('centres a column’s header and cells together when the column asks to', () => { + const aligned = column.columns([ + column.accessor('title', { header: 'Title' }), + column.accessor('severity', { header: 'Severity', meta: { align: 'center' } }), + ]); + + render(); + + expect(screen.getByRole('columnheader', { name: 'Severity' })).toHaveClass('text-center'); + expect(screen.getByRole('cell', { name: FINDINGS[0].severity })).toHaveClass('text-center'); + expect(screen.getByRole('columnheader', { name: 'Title' })).not.toHaveClass('text-center'); + }); + it('renders table-layout fixed once any column sets a width', () => { const sized = column.columns([ column.accessor('title', { header: 'Title', meta: { width: '70%' } }), diff --git a/packages/ui/src/components/ak-table/index.tsx b/packages/ui/src/components/ak-table/index.tsx index d127e06e5..1cab6e375 100644 --- a/packages/ui/src/components/ak-table/index.tsx +++ b/packages/ui/src/components/ak-table/index.tsx @@ -5,7 +5,7 @@ import { type ComponentProps, type ReactNode } from 'react'; import { cn } from '@irene/ui/cn'; import { AK_TABLE_FEATURES, type AkTableColumn } from './helpers'; -import { akTableVariants } from './variants'; +import { akTableCellVariants, akTableVariants } from './variants'; type AkTableProps = Omit, 'children'> & VariantProps & { @@ -84,7 +84,11 @@ function AkTable({ {table.getHeaderGroups().map((group) => ( {group.headers.map((header) => ( - + {header.isPlaceholder ? null : } ))} @@ -96,7 +100,10 @@ function AkTable({ {rows.map((row) => ( {row.getAllCells().map((cell) => ( - + ))} diff --git a/packages/ui/src/components/ak-table/variants.ts b/packages/ui/src/components/ak-table/variants.ts index 1c24a0b1d..8f2ee5987 100644 --- a/packages/ui/src/components/ak-table/variants.ts +++ b/packages/ui/src/components/ak-table/variants.ts @@ -89,3 +89,14 @@ export const akTableVariants = cva( }, } ); + +/* Where a column sets its header and cells, as irene's `textAlign` column option does. */ +export const akTableCellVariants = cva('', { + variants: { + align: { + left: 'text-left', + center: 'text-center', + right: 'text-right', + }, + }, +}); diff --git a/packages/ui/src/components/ak-tabs/index.stories.tsx b/packages/ui/src/components/ak-tabs/index.stories.tsx new file mode 100644 index 000000000..a5a263a9d --- /dev/null +++ b/packages/ui/src/components/ak-tabs/index.stories.tsx @@ -0,0 +1,195 @@ +import { useState } from 'react'; +import type { Meta, StoryObj } from '@storybook/react-vite'; + +import { AkIcon } from '@irene/ui/ak-icon'; +import { AkTabs, AkTabsBadge, AkTabsContent, AkTabsList, AkTabsTrigger } from '@irene/ui/ak-tabs'; +import { AkTypography } from '@irene/ui/ak-typography'; +import { StorySection } from '@irene/ui/story-layout'; + +const VARIANTS = ['line', 'shadow', 'segmented'] as const; + +const TABS = [ + { value: 'files', label: 'Files', icon: 'material-symbols:assignment', count: 9 }, + { value: 'members', label: 'Members', icon: 'material-symbols:group', count: 100 }, + { value: 'settings', label: 'Settings', icon: 'material-symbols:settings', count: 0 }, +] as const; + +const meta = { + title: 'Components/AkTabs', + component: AkTabsList, + tags: ['autodocs'], + argTypes: { + variant: { control: 'inline-radio', options: VARIANTS }, + }, + args: { variant: 'line' }, +} satisfies Meta; + +export default meta; + +type Story = StoryObj; + +/** A row with icons and counts, and a view under it for each tab. */ +export const Playground: Story = { + render: (args) => ( + + + {TABS.map((tab) => ( + + + + {tab.label} + + {tab.count} + + ))} + + + {TABS.map((tab) => ( + + The content for {tab.label}. + + ))} + + ), +}; + +/** Each variant, with a disabled tab at the end. */ +export const Variants: Story = { + render: () => ( +
    + {VARIANTS.map((variant) => ( + + + + {TABS.map((tab) => ( + + {tab.label} + + ))} + + + Archived + + + + + ))} +
    + ), +}; + +/** A count on a tint, the default, or as bare text; and any content in place of a number. */ +export const Badges: Story = { + render: (args) => ( +
    + + + + {TABS.map((tab) => ( + + {tab.label} + + {tab.count} + + ))} + + + + + + + + {TABS.map((tab) => ( + + {tab.label} + + {tab.count} + + ))} + + + + + + + + {TABS.map((tab) => ( + + {tab.label} + + + + {tab.count} + + + ))} + + + +
    + ), +}; + +/** Selection held by the caller, as a route or a search param would hold it. */ +export const Controlled: Story = { + render: function ControlledTabs(args) { + const [active, setActive] = useState('members'); + + return ( +
    + + + {TABS.map((tab) => ( + + {tab.label} + + ))} + + + + Active: {active} +
    + ); + }, +}; + +/** + * Tabs that navigate: each tab is a link, the route decides which is active, + * and `manual` activation stops the arrow keys from navigating as they move. + */ +export const AsLinks: Story = { + render: (args) => ( + + + {TABS.map((tab) => ( + + {tab.label} + + ))} + + + ), +}; + +/** A column of tabs beside its view. */ +export const Vertical: Story = { + render: (args) => ( + + + {TABS.map((tab) => ( + + + + {tab.label} + + ))} + + + {TABS.map((tab) => ( + + The content for {tab.label}. + + ))} + + ), +}; diff --git a/packages/ui/src/components/ak-tabs/index.test.tsx b/packages/ui/src/components/ak-tabs/index.test.tsx new file mode 100644 index 000000000..b77c6dbdd --- /dev/null +++ b/packages/ui/src/components/ak-tabs/index.test.tsx @@ -0,0 +1,181 @@ +import { render, screen, within } from '@testing-library/react'; +import userEvent from '@testing-library/user-event'; +import { describe, expect, it, vi } from 'vitest'; +import { type ComponentProps } from 'react'; + +import { AkTabs, AkTabsBadge, AkTabsContent, AkTabsList, AkTabsTrigger } from '@irene/ui/ak-tabs'; + +type RenderTabsOptions = ComponentProps & { + variant?: ComponentProps['variant']; +}; + +const renderTabs = ({ variant, ...props }: RenderTabsOptions = {}) => + render( + + + + Files + 9 + + + Members + + + Archived + + + + Files view + + Members view + + ); + +const tab = (name: string) => screen.getByRole('tab', { name: new RegExp(name) }); + +describe('AkTabs', () => { + it('reads as a tablist with one tab per trigger', () => { + renderTabs(); + + expect(screen.getByRole('tablist')).toBeInTheDocument(); + expect(screen.getAllByRole('tab')).toHaveLength(3); + }); + + it('shows the view for the tab active on mount, and only that one', () => { + renderTabs(); + + expect(tab('Files')).toHaveAttribute('aria-selected', 'true'); + expect(screen.getByRole('tabpanel')).toHaveTextContent('Files view'); + expect(screen.queryByText('Members view')).not.toBeInTheDocument(); + }); + + it('switches the view when another tab is pressed', async () => { + renderTabs(); + + await userEvent.click(tab('Members')); + + expect(tab('Members')).toHaveAttribute('aria-selected', 'true'); + expect(screen.getByRole('tabpanel')).toHaveTextContent('Members view'); + }); + + it('reports the chosen tab to the caller, as irene’s onTabClick did', async () => { + const onValueChange = vi.fn(); + + renderTabs({ onValueChange }); + + await userEvent.click(tab('Members')); + + expect(onValueChange).toHaveBeenCalledWith('members'); + }); + + it('follows the value it is given rather than its own selection', async () => { + renderTabs({ value: 'files', defaultValue: undefined }); + + await userEvent.click(tab('Members')); + + expect(tab('Files')).toHaveAttribute('aria-selected', 'true'); + }); + + it('moves between tabs with the arrow keys', async () => { + renderTabs(); + + await userEvent.click(tab('Files')); + await userEvent.keyboard('{ArrowRight}'); + + expect(tab('Members')).toHaveFocus(); + }); + + it('keeps a disabled tab out of reach', async () => { + const onValueChange = vi.fn(); + + renderTabs({ onValueChange }); + + await userEvent.click(tab('Archived')); + + expect(tab('Archived')).toBeDisabled(); + expect(onValueChange).not.toHaveBeenCalled(); + }); + + it('renders a link as the tab when given one, for tabs that navigate', () => { + render( + + + + Files + + + + ); + + expect(tab('Files').tagName).toBe('A'); + expect(tab('Files')).toHaveAttribute('href', '/files'); + }); +}); + +describe('the variant a row is drawn in', () => { + it('marks the active tab with a bar under it unless another variant is asked for', () => { + renderTabs(); + + expect(screen.getByRole('tablist')).toHaveAttribute('data-variant', 'line'); + expect(tab('Files')).toHaveClass('after:bg-primary'); + }); + + it('runs the row over a rule for the line and shadow variants', () => { + renderTabs({ variant: 'shadow' }); + + expect(screen.getByRole('tablist')).toHaveClass( + 'data-[orientation=horizontal]:border-b', + 'w-full' + ); + }); + + it('lays a vertical row out as a column, with the rule down its side', () => { + renderTabs({ orientation: 'vertical' }); + + expect(screen.getByRole('tablist')).toHaveAttribute('aria-orientation', 'vertical'); + expect(screen.getByRole('tablist')).toHaveClass('data-[orientation=vertical]:border-r'); + }); + + it('lifts the active tab as a card for the shadow variant', () => { + renderTabs({ variant: 'shadow' }); + + expect(tab('Files')).toHaveClass('data-[state=active]:shadow-4'); + expect(tab('Files')).not.toHaveClass('after:bg-primary'); + }); + + it('draws the row as a tinted track for the segmented variant', () => { + renderTabs({ variant: 'segmented' }); + + expect(screen.getByRole('tablist')).toHaveClass('bg-divider-strong', 'w-fit'); + expect(tab('Files')).toHaveClass('data-[state=active]:bg-background'); + }); +}); + +describe('the count beside a tab', () => { + it('sits inside the tab it counts for', () => { + renderTabs(); + + expect(within(tab('Files')).getByText('9')).toBeInTheDocument(); + }); + + it('sits on a tint that follows the tab, unless asked to be bare text', () => { + render( + + + + Files + 9 + + + + Members + 4 + + + + ); + + expect(screen.getByText('9')).toHaveClass('bg-divider-strong'); + expect(screen.getByText('4')).toHaveClass('bg-transparent'); + }); +}); diff --git a/packages/ui/src/components/ak-tabs/index.tsx b/packages/ui/src/components/ak-tabs/index.tsx new file mode 100644 index 000000000..4b221dadf --- /dev/null +++ b/packages/ui/src/components/ak-tabs/index.tsx @@ -0,0 +1,120 @@ +import { Tabs as TabsPrimitive } from 'radix-ui'; +import { createContext, useContext, type ComponentProps } from 'react'; +import { type VariantProps } from 'class-variance-authority'; + +import { cn } from '@irene/ui/cn'; + +import { akTabsBadgeVariants, akTabsListVariants, akTabsTriggerVariants } from './variants'; + +type AkTabsVariant = NonNullable['variant']>; + +/* Carries the list's variant to its tabs, so the variant is set once per row. */ +const AkTabsVariantContext = createContext('line'); + +/** + * A set of views, one shown at a time, chosen from a row of tabs. + * + * Built on Radix's tabs, so the row reads as a tablist to assistive technology + * and takes the arrow keys, Home and End. Values are strings: irene's numeric + * tab ids become their string form. + * + * @param props.value - The active tab, for a row whose selection lives elsewhere (a route, a search param). + * @param props.defaultValue - The tab active on mount, for a row that keeps its own selection. + * @param props.onValueChange - Called with the chosen tab's value; irene's `onTabClick`. + * @param props.orientation - Lays the row out horizontally (the default) or vertically. + * @param props.activationMode - `manual` waits for Enter or Space; use it for tabs that navigate. + */ +function AkTabs({ + className, + orientation = 'horizontal', + ...props +}: ComponentProps) { + return ( + + ); +} + +/** + * The row of tabs. + * + * @param props.variant - How the active tab is marked: a bar under it (`line`), a raised card + * (`shadow`), or a raised pill on a tinted track (`segmented`). + */ +function AkTabsList({ + className, + variant = 'line', + ...props +}: ComponentProps & { variant?: AkTabsVariant }) { + return ( + + + + ); +} + +/** + * One tab. Its children are the label, with an icon before it and an + * `AkTabsBadge` after it as needed. + * + * @param props.value - Which `AkTabsContent` it shows, and what `onValueChange` receives. + * @param props.disabled - Keeps it in the row but out of reach. + * @param props.asChild - Makes the child the tab; pass a router link for tabs that navigate. + */ +function AkTabsTrigger({ className, ...props }: ComponentProps) { + const variant = useContext(AkTabsVariantContext); + + return ( + + ); +} + +/** + * The count beside a tab's label, tinted to follow the tab it sits in. + * + * @param props.background - Draws it on a tint (the default), or as bare text. + */ +function AkTabsBadge({ + className, + background, + ...props +}: ComponentProps<'span'> & VariantProps) { + return ( + + ); +} + +/** + * The view for one tab, rendered while that tab is active. + * + * @param props.value - The tab it belongs to. + * @param props.forceMount - Keeps it mounted while hidden, for a view that holds state. + */ +function AkTabsContent({ className, ...props }: ComponentProps) { + return ( + + ); +} + +export { AkTabs, AkTabsList, AkTabsTrigger, AkTabsBadge, AkTabsContent }; diff --git a/packages/ui/src/components/ak-tabs/variants.ts b/packages/ui/src/components/ak-tabs/variants.ts new file mode 100644 index 000000000..5bf2fecb9 --- /dev/null +++ b/packages/ui/src/components/ak-tabs/variants.ts @@ -0,0 +1,120 @@ +import { cva } from 'class-variance-authority'; + +/* + The row of tabs. `line` and `shadow` are irene's two indicators and run the + width of their container over a rule; `segmented` is a pill-shaped switch for + a choice between a few views, sized to its tabs. +*/ +export const akTabsListVariants = cva( + ` + inline-flex items-center + data-[orientation=vertical]:h-fit data-[orientation=vertical]:w-fit + data-[orientation=vertical]:flex-col data-[orientation=vertical]:items-stretch + `, + { + variants: { + variant: { + /* The rule runs under a row, and down the side of a column. */ + line: ` + w-full border-border + data-[orientation=horizontal]:border-b + data-[orientation=vertical]:border-r + `, + shadow: ` + w-full border-border + data-[orientation=horizontal]:border-b + data-[orientation=vertical]:border-r + `, + segmented: ` + w-fit gap-0.5 rounded-md bg-divider-strong p-0.75 + data-[orientation=horizontal]:h-9 + `, + }, + }, + + defaultVariants: { variant: 'line' }, + } +); + +/* + One tab. Every variant marks the active tab by `data-state=active`, which + Radix sets on a button and on a link passed through `asChild` alike. +*/ +export const akTabsTriggerVariants = cva( + ` + group/tabs-trigger relative inline-flex shrink-0 cursor-pointer items-center justify-center + gap-2 text-base whitespace-nowrap text-foreground-muted transition-colors outline-none + focus-visible:ring-3 focus-visible:ring-ring/50 + data-disabled:pointer-events-none data-disabled:text-foreground-disabled + [&_svg]:pointer-events-none [&_svg]:shrink-0 + [&_svg:not([class*='size-'])]:size-4.5 + data-[orientation=vertical]:justify-start + `, + { + variants: { + variant: { + /* A 3px bar under the active tab, in the primary colour. */ + line: ` + h-10 px-4 + hover:bg-hover-light + data-[state=active]:font-bold data-[state=active]:text-foreground + data-[state=active]:hover:bg-transparent + after:absolute after:bg-primary after:opacity-0 after:transition-opacity + data-[state=active]:after:opacity-100 + data-[orientation=horizontal]:after:inset-x-0 data-[orientation=horizontal]:after:bottom-0 + data-[orientation=horizontal]:after:h-0.75 + data-[orientation=horizontal]:after:rounded-t-xs + data-[orientation=vertical]:after:inset-y-0 data-[orientation=vertical]:after:right-0 + data-[orientation=vertical]:after:w-0.75 data-[orientation=vertical]:after:rounded-l-xs + `, + + /* The active tab is lifted out of the row as a card, open on the side facing its view. */ + shadow: ` + h-10 border border-transparent px-4 + data-[orientation=horizontal]:rounded-t-md data-[orientation=horizontal]:border-b-0 + data-[orientation=vertical]:rounded-l-md data-[orientation=vertical]:border-r-0 + hover:bg-hover-light + data-[state=active]:border-border data-[state=active]:bg-background + data-[state=active]:font-bold data-[state=active]:text-primary + data-[state=active]:shadow-4 + data-[state=active]:hover:bg-background + data-[state=active]:[&_svg]:text-foreground + `, + + /* The active tab is a raised surface on the tinted track. */ + segmented: ` + rounded-sm px-3 font-medium + data-[orientation=horizontal]:h-full data-[orientation=horizontal]:flex-1 + data-[orientation=vertical]:h-8 + hover:text-foreground + data-[state=active]:bg-background data-[state=active]:text-foreground + data-[state=active]:shadow-15 + `, + }, + }, + + defaultVariants: { variant: 'line' }, + } +); + +/* + The count beside a tab's label. It tints with the tab it sits in, so the + active tab's count reads as part of the selection. +*/ +export const akTabsBadgeVariants = cva( + 'inline-flex h-5 min-w-6 items-center justify-center rounded-xs px-1 text-sm font-normal', + { + variants: { + background: { + true: ` + bg-divider-strong text-foreground-muted + group-data-[state=active]/tabs-trigger:bg-primary/20 + group-data-[state=active]/tabs-trigger:text-foreground + `, + false: 'bg-transparent', + }, + }, + + defaultVariants: { background: true }, + } +); diff --git a/packages/ui/src/components/ak-toggle/index.stories.tsx b/packages/ui/src/components/ak-toggle/index.stories.tsx new file mode 100644 index 000000000..2b5950220 --- /dev/null +++ b/packages/ui/src/components/ak-toggle/index.stories.tsx @@ -0,0 +1,66 @@ +import { useState } from 'react'; +import type { Meta, StoryObj } from '@storybook/react-vite'; + +import { AkToggle } from '@irene/ui/ak-toggle'; +import { AkTypography } from '@irene/ui/ak-typography'; +import { StorySection } from '@irene/ui/story-layout'; + +const SIZES = ['small', 'default', 'large'] as const; + +const meta = { + title: 'Components/AkToggle', + component: AkToggle, + tags: ['autodocs'], + argTypes: { + size: { control: 'inline-radio', options: SIZES }, + disabled: { control: 'boolean' }, + }, + args: { size: 'default', disabled: false, 'aria-label': 'Email me' }, +} satisfies Meta; + +export default meta; + +type Story = StoryObj; + +export const Playground: Story = {}; + +/** Each size, off and on. */ +export const Sizes: Story = { + render: (args) => ( +
    + {SIZES.map((size) => ( + + + + + + ))} +
    + ), +}; + +/** Disabled, off and on: it keeps its colour, faded. */ +export const Disabled: Story = { + render: (args) => ( +
    + + + +
    + ), +}; + +/** A setting row: the label names the switch, and the state lives with the caller. */ +export const WithLabel: Story = { + render: function WithLabelToggle(args) { + const [isOn, setIsOn] = useState(true); + + return ( + + ); + }, +}; diff --git a/packages/ui/src/components/ak-toggle/index.test.tsx b/packages/ui/src/components/ak-toggle/index.test.tsx new file mode 100644 index 000000000..5fa126c6c --- /dev/null +++ b/packages/ui/src/components/ak-toggle/index.test.tsx @@ -0,0 +1,65 @@ +import { render, screen } from '@testing-library/react'; +import userEvent from '@testing-library/user-event'; +import { describe, expect, it, vi } from 'vitest'; + +import { AkToggle } from '@irene/ui/ak-toggle'; + +describe('AkToggle', () => { + it('reads as a switch, off unless told otherwise', () => { + render(); + + expect(screen.getByRole('switch', { name: 'Email me' })).not.toBeChecked(); + }); + + it('reports the new state when flipped', async () => { + const onCheckedChange = vi.fn(); + + render(); + + await userEvent.click(screen.getByRole('switch')); + + expect(onCheckedChange).toHaveBeenCalledWith(true); + }); + + it('follows the state it is given rather than its own', async () => { + render(); + + await userEvent.click(screen.getByRole('switch')); + + expect(screen.getByRole('switch')).not.toBeChecked(); + }); + + it('flips on Space, as a switch does', async () => { + const onCheckedChange = vi.fn(); + + render(); + + screen.getByRole('switch').focus(); + await userEvent.keyboard(' '); + + expect(onCheckedChange).toHaveBeenCalledWith(true); + }); + + it('stays where it is while disabled', async () => { + const onCheckedChange = vi.fn(); + + render(); + + await userEvent.click(screen.getByRole('switch')); + + expect(onCheckedChange).not.toHaveBeenCalled(); + }); + + it('draws green when on and grey when off', () => { + render(); + + expect(screen.getByRole('switch')).toHaveClass('data-[state=checked]:bg-success'); + expect(screen.getByRole('switch')).toHaveAttribute('data-state', 'checked'); + }); + + it('takes the small height beside body text', () => { + render(); + + expect(screen.getByRole('switch')).toHaveClass('h-4', 'w-8'); + }); +}); diff --git a/packages/ui/src/components/ak-toggle/index.tsx b/packages/ui/src/components/ak-toggle/index.tsx new file mode 100644 index 000000000..8e6bc8aca --- /dev/null +++ b/packages/ui/src/components/ak-toggle/index.tsx @@ -0,0 +1,37 @@ +import { Switch as SwitchPrimitive } from 'radix-ui'; +import { type VariantProps } from 'class-variance-authority'; +import { type ComponentProps } from 'react'; + +import { cn } from '@irene/ui/cn'; + +import { akToggleThumbVariants, akToggleVariants } from './variants'; + +type AkToggleProps = ComponentProps & + VariantProps; + +/** + * Turns one setting on or off, taking effect as it is flipped rather than on a + * submit. + * + * Built on Radix's switch, so it reads as a switch to assistive technology and + * flips on Space. It is a button rather than a checkbox, so it takes its name + * from `aria-label` or a `