Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
17 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions apps/auth-ui/eslint.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -24,5 +24,12 @@ export default tseslint.config(
'@typescript-eslint/no-explicit-any': 'off',
'react-refresh/only-export-components': ['warn', { allowConstantExport: true }],
},
},
{
// Test doubles and render helpers are not hot-reloaded.
files: ['tests/**/*.{ts,tsx}'],
rules: {
'react-refresh/only-export-components': 'off',
},
}
);
18 changes: 13 additions & 5 deletions apps/auth-ui/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@
"build:docker": "docker buildx build --build-arg APP_NAME=$npm_package_name -f ../../docker/frontend.Dockerfile -t ${DOCKER_REGISTRY:-}${npm_package_name}:${DOCKER_TAG:-latest} ${DOCKER_FLAGS:-} ../..",
"build:docker-no-cache": "cross-env DOCKER_FLAGS=--no-cache pnpm run build:docker",
"lint": "eslint . --ext ts,tsx --report-unused-disable-directives --max-warnings 0",
"test": "vitest run",
"test:watch": "vitest",
"preview": "vite preview",
"knip": "knip --directory ../.. --workspace apps/auth-ui"
},
Expand All @@ -18,6 +20,7 @@
},
"dependencies": {
"@hookform/resolvers": "^5.0.1",
"@monaco-editor/loader": "^1.7.0",
"@monaco-editor/react": "^4.7.0",
"@radix-ui/react-checkbox": "^1.1.5",
"@radix-ui/react-dialog": "^1.1.11",
Expand All @@ -34,8 +37,8 @@
"clsx": "^2.1.1",
"cmdk": "^1.1.1",
"date-fns": "^3.6.0",
"lodash": "catalog:",
"lucide-react": "^0.488.0",
"@monaco-editor/loader": "^1.7.0",
"monaco-editor": "^0.54.0",
"next-themes": "^0.4.6",
"openapi-fetch": "^0.13.5",
Expand All @@ -49,24 +52,29 @@
"sonner": "^2.0.3",
"tailwind-merge": "^3.2.0",
"tailwindcss": "^4.1.3",
"tailwindcss-animate": "^1.0.7",
"tw-animate-css": "^1.2.5",
"zod": "^3.24.4",
"lodash": "catalog:",
"tailwindcss-animate": "^1.0.7"
"zod": "^3.24.4"
},
"devDependencies": {
"@eslint/js": "^9.21.0",
"@testing-library/dom": "^10.4.1",
"@testing-library/jest-dom": "^7.0.1",
"@testing-library/react": "^16.3.3",
"@testing-library/user-event": "^14.6.7",
"@types/node": "^22.14.1",
"@types/react": "^19.0.10",
"@types/react-dom": "^19.0.4",
"@vitejs/plugin-react": "^4.3.4",
"auth-openapi": "workspace:*",
"eslint": "^9.21.0",
"eslint-plugin-react-hooks": "^5.1.0",
"eslint-plugin-react-refresh": "^0.4.19",
"globals": "^15.15.0",
"jsdom": "^29.1.1",
"typescript": "^5.8.3",
"typescript-eslint": "^8.24.1",
"vite": "^6.2.6",
"auth-openapi": "workspace:*"
"vitest": "catalog:"
}
}
30 changes: 7 additions & 23 deletions apps/auth-ui/src/App.tsx
Original file line number Diff line number Diff line change
@@ -1,40 +1,24 @@
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { BrowserRouter, Routes, Route, Navigate } from 'react-router-dom';
import { Layout } from './components/layout';
import { ClientsPage } from './pages/clients';
import { ConnectionsPage } from './pages/connections';
import { DomainsPage } from './pages/domains';
import { JWTInspectorPage } from './pages/jwt-inspector';
import { NotFoundPage } from './pages/not-found';
import { ErrorPage } from './pages/error';
import { OPAValidatorPage } from './pages/opa-validator';
import { RouterProvider, createBrowserRouter } from 'react-router-dom';
import { Toaster } from './components/ui/sonner';
import { ConfigProvider } from './contexts/ConfigProvider';
import { ErrorBoundary } from './hooks/useErrorBoundary';
import { ThemeProvider } from './components/theme-provider';
import { appRoutes } from './routes';

const queryClient = new QueryClient();

// A data router rather than <BrowserRouter>: the asset editor's unsaved-work guard
// needs useBlocker, which only a data router provides.
const router = createBrowserRouter(appRoutes);

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The move to a data router changes the meaning of what three existing pages already do to the URL. ClientsPage.tsx:63, ConnectionsPage.tsx:60 and DomainsPage.tsx:46 each call window.history.replaceState({}, '', url.toString()) on every filter change. Under <BrowserRouter> that was harmless. createBrowserRouter keeps {usr, key, idx} in history state and reads idx on every push — index = getIndex() + 1 — so after the wipe every entry pushed thereafter carries idx: NaN. I confirmed that in this repo with a throwaway spec: filter the clients list, click a sidebar link, history.state.idx is NaN.

useBlocker is the only consumer of that number, and it is this PR's unsaved-work guard. On a POP it computes delta = NaN, which passes its own delta != null check, and calls history.go(NaN); react-router's warning string names this exact scenario ("navigating outside the router via window.history.pushState"). I could not reproduce the browser-side symptom under jsdom — its history.go is not a faithful oracle — so please check it in a browser: filter the clients list, open an asset, edit it, press Back. Story 47 asks for no regression on the existing pages, and the guard is the one thing between an edit and losing it.

The change is one token in each of the three pages:

window.history.replaceState(window.history.state, '', url.toString());

or switch them to setSearchParams(..., { replace: true }) the way AssetsPage already does.


function App() {
return (
<ErrorBoundary>
<ThemeProvider attribute="class" defaultTheme="system" enableSystem>
<ConfigProvider>
<QueryClientProvider client={queryClient}>
<BrowserRouter>
<Routes>
<Route path="/" element={<Layout />}>
<Route index element={<Navigate to="/clients" replace />} />
<Route path="clients" element={<ClientsPage />} />
<Route path="connections" element={<ConnectionsPage />} />
<Route path="domains" element={<DomainsPage />} />
<Route path="jwt-inspector" element={<JWTInspectorPage />} />
<Route path="opa-validator" element={<OPAValidatorPage />} />
<Route path="*" element={<NotFoundPage />} />
</Route>
<Route path="/error" element={<ErrorPage />} />
</Routes>
</BrowserRouter>
<RouterProvider router={router} />
<Toaster />
</QueryClientProvider>
</ConfigProvider>
Expand Down
96 changes: 96 additions & 0 deletions apps/auth-ui/src/components/asset-editor.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
import { DiffEditor, Editor } from '@monaco-editor/react';
import { useTheme } from 'next-themes';
import { useRef } from 'react';
import { REGO_LANGUAGE_ID, REGO_TEMPLATE_LANGUAGE_ID } from '../lib/monaco/language-ids';

/**
* The asset editor. Unlike the json editor the opa validator uses, this one is a fixed
* height filling its container with its own scrollbar, so a page's save action stays on
* screen however long the policy is.
*
* The existing json editor is deliberately left alone: the validator page depends on it.
*/
interface AssetEditorProps {
value: string;
language: string;
/** A template asset's interpolation points are highlighted apart from the rego around them. */
isTemplate?: boolean;
readOnly?: boolean;
onChange?: (value: string) => void;
/** Fires on the editor's save shortcut, which also swallows the browser default. */
onSave?: () => void;
}

interface AssetDiffEditorProps {
original: string;
modified: string;
language: string;
isTemplate?: boolean;
}

const EDITOR_OPTIONS = {
minimap: { enabled: false },
scrollBeyondLastLine: false,
automaticLayout: true,
tabSize: 2,
wordWrap: 'on',
fixedOverflowWidgets: true,
} as const;

/** The editor follows the application theme by prop, so a theme change does not remount it. */
const useEditorTheme = (): string => (useTheme().resolvedTheme === 'dark' ? 'vs-dark' : 'light');

const templateVariant = (language: string, isTemplate: boolean): string =>
isTemplate && language === REGO_LANGUAGE_ID ? REGO_TEMPLATE_LANGUAGE_ID : language;

export const AssetEditor = ({ value, language, isTemplate = false, readOnly = false, onChange, onSave }: AssetEditorProps) => {
const theme = useEditorTheme();

// The command is registered once, on mount, so it has to read the current handler.
const onSaveRef = useRef(onSave);
onSaveRef.current = onSave;

return (
<div
className="h-full overflow-hidden rounded-md border"
// Belt and braces. The command below is the one the editor itself dispatches; this
// catches the keystroke if it ever reaches the wrapper instead, and either way the
// browser's own save dialog is what must not open.
onKeyDown={(event) => {
if (!onSave || event.key !== 's' || !(event.ctrlKey || event.metaKey)) return;
event.preventDefault();
onSave();
}}
>
<Editor
height="100%"
language={templateVariant(language, isTemplate)}
theme={theme}
value={value}
onChange={(next) => onChange?.(next ?? '')}
options={{ ...EDITOR_OPTIONS, readOnly }}
onMount={(editor, monaco) => {
if (monaco.KeyMod === undefined || monaco.KeyCode === undefined) return;
editor.addCommand(monaco.KeyMod.CtrlCmd | monaco.KeyCode.KeyS, () => onSaveRef.current?.());
}}
/>
</div>
);
};

export const AssetDiffEditor = ({ original, modified, language, isTemplate = false }: AssetDiffEditorProps) => {
const theme = useEditorTheme();

return (
<div className="h-full overflow-hidden rounded-md border">
<DiffEditor
height="100%"
language={templateVariant(language, isTemplate)}
theme={theme}
original={original}
modified={modified}
options={{ ...EDITOR_OPTIONS, readOnly: true }}
/>
</div>
);
};
9 changes: 7 additions & 2 deletions apps/auth-ui/src/components/layout/Sidebar.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { Link, useLocation } from 'react-router-dom';
import { cn } from '../../lib/utils';
import { Users, Link as LinkIcon, Globe, Menu, X, Key, Shield } from 'lucide-react';
import { Users, Link as LinkIcon, Globe, Menu, X, Key, Shield, FileCode } from 'lucide-react';
import { Button } from '../ui/button';
import { SiteSwitcher } from './SiteSwitcher';
import { ThemeToggle } from '../theme-toggle';
Expand Down Expand Up @@ -30,6 +30,11 @@ export const Sidebar = ({ className, isCollapsed, onCollapse }: SidebarProps) =>
href: '/domains',
icon: Globe,
},
{
title: 'Assets',
href: '/assets',
icon: FileCode,
},
{
title: 'JWT Inspector',
href: '/jwt-inspector',
Expand Down Expand Up @@ -57,7 +62,7 @@ export const Sidebar = ({ className, isCollapsed, onCollapse }: SidebarProps) =>
)}
<nav className="flex-1 p-2 space-y-1">
{navItems.map((item) => {
const isActive = location.pathname === item.href;
const isActive = location.pathname === item.href || location.pathname.startsWith(`${item.href}/`);
return (
<Link
key={item.href}
Expand Down
6 changes: 6 additions & 0 deletions apps/auth-ui/src/fetch/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,12 @@ const createApiClientsFromConfig = (config: NetworkConfig) => {
return siteApis;
};

/**
* The raw fetch client behind `$api`, for the few calls that need the response status
* rather than just its body — telling a stale-version conflict from any other failure.
*/
export const getFetchClient = () => defaultFetchClient;

export const updateApiBaseUrl = (baseUrl: string) => {
localStorage.setItem('currentBaseUrl', baseUrl);
window.location.reload();
Expand Down
108 changes: 108 additions & 0 deletions apps/auth-ui/src/lib/asset-content.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,108 @@
/**
* Conversion between the api's base64 representation of an asset's content and the text an editor shows.
*
* Pure by design: no react, no app imports, so the rules live in one place instead of being hand-rolled by each page.
*/

/** The api rejects json bodies larger than this, so an encoded payload above it can never be saved. */
export const MAX_ENCODED_BYTES = 1024 * 1024;

/**
* The raw byte ceiling that base64 inflation implies: every 3 raw bytes become 4 encoded ones, so only three quarters
* of the body limit is available to the content itself. Derived rather than written out, so the two stay in step.
*/
export const MAX_RAW_BYTES = Math.floor(MAX_ENCODED_BYTES / 4) * 3;

/** `String.fromCharCode` takes its bytes as arguments, and engines cap how many a call may receive. */
const BINARY_STRING_CHUNK_SIZE = 8192;

/** UTF-8 encodes a code point in one to four bytes, split at these boundaries. */
const TWO_BYTE_BOUNDARY = 0x80;
const THREE_BYTE_BOUNDARY = 0x800;
const FOUR_BYTE_BOUNDARY = 0x10000;

export interface DecodedAssetContent {
/** The content as text. Lossy — with replacement characters in place of the offending bytes — when `isValidText` is false. */
text: string;
/**
* False when the bytes are not valid UTF-8. Callers open such content read-only: re-encoding the lossy text would
* write the replacement characters back over the original bytes and corrupt the asset.
*/
isValidText: boolean;
}

/** Decodes an asset's base64 content into the text an editor shows, reporting whether the bytes were valid text. */
export function decodeAssetContent(base64: string): DecodedAssetContent {
const bytes = base64ToBytes(base64);

// Not even base64. Nothing can be shown, and re-encoding an empty buffer over it would
// be the same corruption the flag exists to prevent.
if (bytes === null) return { text: '', isValidText: false };

try {
return { text: new TextDecoder('utf-8', { fatal: true }).decode(bytes), isValidText: true };
} catch {
// Not text. Decode again leniently so the caller still has something to display.
return { text: new TextDecoder('utf-8').decode(bytes), isValidText: false };
}
}

/** Encodes an editor's text back into the base64 content the api expects. */
export function encodeAssetContent(text: string): string {
return bytesToBase64(new TextEncoder().encode(text));
}

/**
* The number of bytes the encoded payload would occupy, without performing the encode. Lets a page warn about the body
* limit on every keystroke without allocating a base64 copy of the content each time.
*/
export function estimateEncodedSize(text: string): number {
return Math.ceil(utf8ByteLength(text) / 3) * 4;
}

/** Whether encoding this text would produce a payload the api's body limit rejects. */
export function isOverSizeLimit(text: string): boolean {
return estimateEncodedSize(text) > MAX_ENCODED_BYTES;
}

/** Null when the string is not base64 at all, which `atob` reports by throwing. */
function base64ToBytes(base64: string): Uint8Array | null {
try {
return Uint8Array.from(atob(base64), (character) => character.charCodeAt(0));
} catch {
return null;
}
}

function bytesToBase64(bytes: Uint8Array): string {
let binary = '';

// Chunked because the whole array spread into one `String.fromCharCode` call blows the argument limit, which large
// assets reach long before the api's body limit does.
for (let offset = 0; offset < bytes.length; offset += BINARY_STRING_CHUNK_SIZE) {
binary += String.fromCharCode(...bytes.subarray(offset, offset + BINARY_STRING_CHUNK_SIZE));
}

return btoa(binary);
}

function utf8ByteLength(text: string): number {
let bytes = 0;

for (const character of text) {
const codePoint = character.codePointAt(0) ?? 0;

if (codePoint < TWO_BYTE_BOUNDARY) {
bytes += 1;
} else if (codePoint < THREE_BYTE_BOUNDARY) {
bytes += 2;
} else if (codePoint < FOUR_BYTE_BOUNDARY) {
// Lone surrogates land here, and the encoder replaces each with U+FFFD — also three bytes.
bytes += 3;
} else {
bytes += 4;
}
}

return bytes;
}
8 changes: 8 additions & 0 deletions apps/auth-ui/src/lib/monaco/language-ids.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
/**
* The language ids, apart from the registration module, so a page can name a language
* without importing the editor library and everything it drags in.
*/
export const REGO_LANGUAGE_ID = 'rego';

/** Rego with template interpolations highlighted; used for a template asset. */
export const REGO_TEMPLATE_LANGUAGE_ID = 'rego-template';
Loading
Loading