diff --git a/.env.example b/.env.example index cad879f69..2debfb66b 100644 --- a/.env.example +++ b/.env.example @@ -74,3 +74,10 @@ SMTP_FROM= # Logging RUST_LOG=info + +# App UI preview (dev server only) +# Open /dev/app-ui as the owner to see a locally built app UI in the platform's frame. +# Absolute folder with the app's built UI (its index.html and assets). +# APP_UI_DEV_DIR=/home/you/my-app/dist/ui +# Optional loopback dev host of the app that answers its UI operations. +# APP_UI_DEV_API=http://127.0.0.1:8787/dev/v1/platform-call diff --git a/web/src/features/AppUi/Components/AppDialogSurfaceModal.tsx b/web/src/features/AppUi/Components/AppDialogSurfaceModal.tsx new file mode 100644 index 000000000..81d3ce5b2 --- /dev/null +++ b/web/src/features/AppUi/Components/AppDialogSurfaceModal.tsx @@ -0,0 +1,70 @@ +import { useMemo, useState, type ReactNode } from 'react' + +import { buttonClassName } from '@/shared/Buttons/buttonStyles.ts' +import useTranslationStore from '@/shared/Language/Hooks/useTranslationStore.ts' +import { Modal } from '@/shared/Modal/index.tsx' +import { AppDialogSurfaceContext } from '../appDialogSurfaceContext.ts' +import type { AppDialogChrome } from '../Types/app-dialog-surface.types.ts' + +/** + * A platform dialog an app frame is drawn in. An app drawn with the UI kit whose root is a dialog + * fills its title, navigation and footer; otherwise the dialog shows `title`, `description` and + * its own close button around the frame. + */ +export default function AppDialogSurfaceModal({ + open, + onOpenChange, + title, + description, + children, +}: { + readonly open: boolean + readonly onOpenChange: (open: boolean) => void + readonly title: string + readonly description: string + readonly children: ReactNode +}) { + const { t } = useTranslationStore() + const [chrome, setChrome] = useState(null) + const [navigation, setNavigation] = useState(null) + const [footer, setFooter] = useState(null) + const surface = useMemo( + () => ({ setChrome, navigation, footer, close: () => onOpenChange(false) }), + [footer, navigation, onOpenChange], + ) + // The user closed the dialog: the app's root dialog hears of it before the platform closes it. + const close = () => { + chrome?.onClose() + onOpenChange(false) + } + + return ( + { + if (next) onOpenChange(true) + else close() + }} + closeDisabled={chrome?.closeDisabled ?? false} + title={chrome?.heading ?? title} + description={chrome?.description ?? description} + size="xl" + fixedHeight + height="tall" + navigation={chrome?.navigation ?
: undefined} + footer={ + chrome?.footer ? ( +
+ ) : ( + + ) + } + > +
+ {children} +
+ + ) +} diff --git a/web/src/features/AppUi/Components/AppHostActionDialog.tsx b/web/src/features/AppUi/Components/AppHostActionDialog.tsx index 5c87e572b..20b760a4a 100644 --- a/web/src/features/AppUi/Components/AppHostActionDialog.tsx +++ b/web/src/features/AppUi/Components/AppHostActionDialog.tsx @@ -1,13 +1,8 @@ -import { useMemo, useState } from 'react' - -import { buttonClassName } from '@/shared/Buttons/buttonStyles.ts' import useTranslationStore from '@/shared/Language/Hooks/useTranslationStore.ts' -import { Modal } from '@/shared/Modal/index.tsx' import AppUiFrame from '../AppUiFrame.tsx' -import { AppDialogSurfaceContext } from '../appDialogSurfaceContext.ts' import useAppHostActionDialogLogic from '../Hooks/useAppHostActionDialogLogic.ts' import type { AppHostActionDialogProps } from '../Types/app-host-table.types.ts' -import type { AppDialogChrome } from '../Types/app-dialog-surface.types.ts' +import AppDialogSurfaceModal from './AppDialogSurfaceModal.tsx' /** * A host row action of an app, opened in a platform dialog for that host. An app drawn with the UI @@ -16,60 +11,26 @@ import type { AppDialogChrome } from '../Types/app-dialog-surface.types.ts' export default function AppHostActionDialog(props: AppHostActionDialogProps) { const { t } = useTranslationStore() const { state, handler } = useAppHostActionDialogLogic(props) - const { onOpenChange } = props - const [chrome, setChrome] = useState(null) - const [navigation, setNavigation] = useState(null) - const [footer, setFooter] = useState(null) - const surface = useMemo( - () => ({ setChrome, navigation, footer, close: () => onOpenChange(false) }), - [footer, navigation, onOpenChange], - ) - // The user closed the dialog: the app's root dialog hears of it before the platform closes it. - const close = () => { - chrome?.onClose() - onOpenChange(false) - } return ( - { - if (open) onOpenChange(true) - else close() - }} - closeDisabled={chrome?.closeDisabled ?? false} - title={chrome?.heading ?? state.title ?? t('appUi.unavailable')} - description={chrome?.description ?? props.hostDomains.join(', ')} - size="xl" - fixedHeight - height="tall" - navigation={chrome?.navigation ?
: undefined} - footer={ - chrome?.footer ? ( -
- ) : ( - - ) - } + onOpenChange={props.onOpenChange} + title={state.title ?? t('appUi.unavailable')} + description={props.hostDomains.join(', ')} > {state.app && state.route ? ( -
- - - -
+ ) : ( - {t('appUi.unavailable')} + {t('appUi.unavailable')} )} - + ) } diff --git a/web/src/features/AppUiDevPreview/Components/AppUiDevPreviewSettings.tsx b/web/src/features/AppUiDevPreview/Components/AppUiDevPreviewSettings.tsx new file mode 100644 index 000000000..53b0cd961 --- /dev/null +++ b/web/src/features/AppUiDevPreview/Components/AppUiDevPreviewSettings.tsx @@ -0,0 +1,99 @@ +import { TextInput } from '@rentnerkev/inputs' +import { CustomSelect } from '@rentnerkev/select' + +import { buttonClassName } from '@/shared/Buttons/buttonStyles.ts' +import useTranslationStore from '@/shared/Language/Hooks/useTranslationStore.ts' +import type { AppUiDevPreviewSettingsProps } from '../Types/app-ui-dev-preview.types.ts' +import { APP_UI_DEV_BRIDGES } from '../validation.ts' + +/** The installation the preview pretends to be; the settings take effect when applied. */ +export default function AppUiDevPreviewSettings({ + draft, + onDraftChange, + onApply, +}: AppUiDevPreviewSettingsProps) { + const { t } = useTranslationStore() + + return ( +
{ + event.preventDefault() + onApply() + }} + > +

{t('appUi.devPreview.settings')}

+ + onDraftChange({ ...draft, surface: surface === 'dialog' ? 'dialog' : 'page' }) + } + /> + ({ value: version, label: version }))} + onValueChange={(bridge: string) => + onDraftChange({ + ...draft, + bridge: APP_UI_DEV_BRIDGES.find((version) => version === bridge) ?? '1.3.0', + }) + } + /> + onDraftChange({ ...draft, name })} + /> + onDraftChange({ ...draft, routes })} + /> + onDraftChange({ ...draft, keys })} + /> + onDraftChange({ ...draft, dialogs })} + /> + {draft.surface === 'dialog' ? ( + + onDraftChange({ ...draft, host: host.trim() || undefined }) + } + /> + ) : null} + + + ) +} diff --git a/web/src/features/AppUiDevPreview/Hooks/useAppUiDevPreviewLogic.ts b/web/src/features/AppUiDevPreview/Hooks/useAppUiDevPreviewLogic.ts new file mode 100644 index 000000000..0ff886e19 --- /dev/null +++ b/web/src/features/AppUiDevPreview/Hooks/useAppUiDevPreviewLogic.ts @@ -0,0 +1,164 @@ +import { useQuery } from '@tanstack/react-query' +import { useMemo, useState } from 'react' + +import { useAppUi } from '@/features/AppUi/AppUiProvider.tsx' +import type { AppUiResult, AppUiSummary } from '@/lib/AppUi/contract.ts' +import { APP_UI_DEV_PREFIX } from '@/lib/AppUi/paths.ts' +import { readAppUiDevPreviewStatusHandler } from '../middleware.ts' +import type { + AppUiDevPreviewLogicResult, + AppUiDevPreviewPageProps, +} from '../Types/app-ui-dev-preview.types.ts' +import { appUiDevPreviewResult, appUiDevPreviewSearch, listEntries } from '../validation.ts' + +function unavailable(requestId: string): AppUiResult { + return { + ok: false, + problem: { + requestId, + status: 503, + code: 'unavailable', + title: 'The dev server did not answer the operation.', + type: 'urn:rentnerproxy:problem:unavailable', + }, + } +} + +/** + * A locally built app UI in the platform's own frame view, as if it were installed. The settings + * apply on demand, because the frame binds the app's routes, keys and bridge when it opens. + */ +export default function useAppUiDevPreviewLogic({ + search, + onSearchChange, +}: AppUiDevPreviewPageProps): AppUiDevPreviewLogicResult { + const ui = useAppUi() + const statusQuery = useQuery({ + queryKey: ['app-ui-dev-preview'], + queryFn: () => readAppUiDevPreviewStatusHandler(), + staleTime: Number.POSITIVE_INFINITY, + retry: false, + }) + const status = statusQuery.data + const [draft, setDraft] = useState(search) + const [mount, setMount] = useState(1) + const [ended, setEnded] = useState() + const [dialogOpen, setDialogOpen] = useState(false) + const dialog = search.surface === 'dialog' + // The frame binds the app's bridge, routes, dialogs and keys when it opens, so a change of the + // committed settings, by Apply or by browser history, opens a new frame and resets the draft. + // The route alone changes in place. + const { route: _route, ...settings } = search + const committed = JSON.stringify(settings) + const [seen, setSeen] = useState(committed) + if (seen !== committed) { + setSeen(committed) + setDraft(search) + setEnded(undefined) + setMount((current) => current + 1) + } + + const app = useMemo( + () => ({ + appId: 'dev.preview', + installationId: 'dev-preview', + generation: 1, + uiBridgeVersion: search.bridge, + name: search.name, + routes: listEntries(search.routes), + dialogs: listEntries(search.dialogs), + slots: [dialog ? 'proxyHostTab' : 'navigation'], + events: [], + // The summary carries the keys unique and in ASCII order, like the platform's. + permissionKeys: listEntries(search.keys).toSorted(), + hostColumns: [], + hostActions: [], + pages: [], + }), + [dialog, search.bridge, search.dialogs, search.keys, search.name, search.routes], + ) + const route = + search.route && app.routes.includes(search.route) + ? search.route + : (app.routes[0] ?? 'overview') + const nonce = `dev-${mount}` + const fragment = new URLSearchParams({ nonce, slot: dialog ? 'proxyHostTab' : 'navigation' }) + if (dialog && search.host) fragment.set('hostId', search.host) + const restart = () => { + setEnded(undefined) + setMount((current) => current + 1) + } + + return { + state: { + status, + statusError: status === undefined && statusQuery.isError, + draft, + app, + mount, + ended, + dialogOpen, + frame: { + app, + source: { nonce, url: `${APP_UI_DEV_PREFIX}index.html#${fragment.toString()}` }, + route, + theme: ui?.theme ?? 'light', + onNavigate: (next) => onSearchChange({ ...search, route: next }), + onDisconnect: setEnded, + onApiRequest: async ( + { requestId, operationId, idempotencyKey, payload }, + signal, + ) => { + const response = await fetch(`${APP_UI_DEV_PREFIX}call`, { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ + requestId, + operationId, + idempotencyKey, + payload, + permissionKeys: app.permissionKeys, + }), + signal, + }) + const result = appUiDevPreviewResult.safeParse( + await response.json().catch(() => null), + ) + return result.success ? result.data : unavailable(requestId) + }, + onDialog: (request, settle) => { + if (!ui) settle('cancelled') + else + ui.openDialog({ + appName: app.name, + dialogId: request.dialogId, + mount: nonce, + settle, + }) + }, + onEnded: () => ui?.cancelDialog(nonce), + }, + }, + setter: { setDraft }, + handler: { + // The app keeps its own route; the rest of the settings fall back where malformed. + handleApply: () => { + const next = appUiDevPreviewSearch.parse({ ...draft, route: search.route }) + setDraft(next) + onSearchChange(next) + // Unchanged settings open no new frame by themselves, so Apply reloads it. + const { route: _next, ...nextSettings } = next + if (JSON.stringify(nextSettings) === committed) restart() + }, + handleRetryStatus: () => { + // A failed read shows as the query's error again. + statusQuery.refetch().catch(() => undefined) + }, + handleReload: restart, + handleDialogOpenChange: (open) => { + if (open) restart() + setDialogOpen(open) + }, + }, + } +} diff --git a/web/src/features/AppUiDevPreview/Types/app-ui-dev-preview.types.ts b/web/src/features/AppUiDevPreview/Types/app-ui-dev-preview.types.ts new file mode 100644 index 000000000..c812d4c0d --- /dev/null +++ b/web/src/features/AppUiDevPreview/Types/app-ui-dev-preview.types.ts @@ -0,0 +1,44 @@ +import type { AppUiSummary } from '@/lib/AppUi/contract.ts' +import type { AppFrameViewProps } from '@/features/AppUi/Types/app-frame-view.types.ts' +import type { AppUiDevPreviewSearch } from '../validation.ts' + +export interface AppUiDevPreviewStatus { + /** The absolute folder of the app's built UI, or null when the preview is off. */ + readonly directory: string | null + /** The app's local dev host for operations, or null when operations are unavailable. */ + readonly api: string | null +} + +export interface AppUiDevPreviewPageProps { + readonly search: AppUiDevPreviewSearch + readonly onSearchChange: (search: AppUiDevPreviewSearch) => void +} + +export interface AppUiDevPreviewSettingsProps { + readonly draft: AppUiDevPreviewSearch + readonly onDraftChange: (draft: AppUiDevPreviewSearch) => void + readonly onApply: () => void +} + +export interface AppUiDevPreviewLogicResult { + readonly state: { + readonly status: AppUiDevPreviewStatus | undefined + /** The status could not be read; the page offers to read it again. */ + readonly statusError: boolean + readonly draft: AppUiDevPreviewSearch + readonly app: AppUiSummary + readonly mount: number + readonly ended: string | undefined + readonly dialogOpen: boolean + readonly frame: Omit + } + readonly setter: { + readonly setDraft: (draft: AppUiDevPreviewSearch) => void + } + readonly handler: { + readonly handleApply: () => void + readonly handleRetryStatus: () => void + readonly handleReload: () => void + readonly handleDialogOpenChange: (open: boolean) => void + } +} diff --git a/web/src/features/AppUiDevPreview/index.tsx b/web/src/features/AppUiDevPreview/index.tsx new file mode 100644 index 000000000..f0b636949 --- /dev/null +++ b/web/src/features/AppUiDevPreview/index.tsx @@ -0,0 +1,117 @@ +import AppDialogSurfaceModal from '@/features/AppUi/Components/AppDialogSurfaceModal.tsx' +import AppFrameView from '@/features/AppUi/Components/AppFrameView.tsx' +import { buttonClassName } from '@/shared/Buttons/buttonStyles.ts' +import useTranslationStore from '@/shared/Language/Hooks/useTranslationStore.ts' +import PageHeader from '@/shared/Management/PageHeader.tsx' +import AppUiDevPreviewSettings from './Components/AppUiDevPreviewSettings.tsx' +import useAppUiDevPreviewLogic from './Hooks/useAppUiDevPreviewLogic.ts' +import type { AppUiDevPreviewPageProps } from './Types/app-ui-dev-preview.types.ts' + +const notice = + 'rounded-xl border border-border bg-surface-subtle p-3 text-sm leading-relaxed text-muted' + +/** + * The dev server's preview of an app UI that is built locally: the platform draws it as a page or + * as a host row dialog, the same way it draws an installed app. + */ +export default function AppUiDevPreviewPage(props: AppUiDevPreviewPageProps) { + const { t } = useTranslationStore() + const { state, setter, handler } = useAppUiDevPreviewLogic(props) + const dialog = props.search.surface === 'dialog' + const frame = state.ended ? ( +
+ + {t('appUi.devPreview.ended', { reason: state.ended })} + + +
+ ) : ( + + ) + + return ( +
+ + {t('appUi.devPreview.reload')} + + ) : null + } + /> +
+ +
+ {state.statusError ? ( +
+ {t('appUi.devPreview.statusError')} + +
+ ) : state.status === undefined ? ( + {t('appUi.loading')} + ) : null} + {state.status && !state.status.directory ? ( +

{t('appUi.devPreview.missingDirectory')}

+ ) : null} + {state.status?.directory && !state.status.api ? ( +

{t('appUi.devPreview.missingApi')}

+ ) : null} + {state.status?.directory && !dialog ? ( +
+

{state.app.name}

+ {frame} +
+ ) : null} + {state.status?.directory && dialog ? ( + <> + + + {state.dialogOpen ? frame : null} + + + ) : null} +
+
+
+ ) +} diff --git a/web/src/features/AppUiDevPreview/middleware.ts b/web/src/features/AppUiDevPreview/middleware.ts new file mode 100644 index 000000000..c11396ce1 --- /dev/null +++ b/web/src/features/AppUiDevPreview/middleware.ts @@ -0,0 +1,21 @@ +import { createServerFn } from '@tanstack/react-start' +import { setResponseHeader } from '@tanstack/react-start/server' + +import { hasOwnerRole } from '@/server/Auth/Access/rbac.service.ts' +import { getCurrentSessionService } from '@/server/Auth/Access/sessions.service.ts' +import { appUiDevApi, appUiDevDirectory } from '@/server/AppRuntime/ui/dev-preview.server.ts' +import type { AppUiDevPreviewStatus } from './Types/app-ui-dev-preview.types.ts' + +/** Which parts of the app UI preview the dev server has; production always answers none. */ +export const readAppUiDevPreviewStatusHandler = createServerFn({ method: 'GET' }).handler( + async (): Promise => { + setResponseHeader('Cache-Control', 'private, no-store') + // A failed lookup fails the call, so the page offers a retry instead of a disabled preview. + const session = await getCurrentSessionService().catch(() => { + throw new Error('The session could not be read.') + }) + // The preview is owner-only; everyone else learns nothing about its configuration. + if (!session || !hasOwnerRole(session.user.roles)) return { directory: null, api: null } + return { directory: appUiDevDirectory() ?? null, api: appUiDevApi()?.href ?? null } + }, +) diff --git a/web/src/features/AppUiDevPreview/validation.ts b/web/src/features/AppUiDevPreview/validation.ts new file mode 100644 index 000000000..216ac4f08 --- /dev/null +++ b/web/src/features/AppUiDevPreview/validation.ts @@ -0,0 +1,46 @@ +import { z } from 'zod' + +import { isAppUiPayload } from '@/lib/AppUi/bridge.ts' +import type { AppUiPayload } from '@/lib/AppUi/contract.ts' + +const recordId = /^[a-z0-9][a-z0-9_-]{0,63}$/u +const recordIds = /^[a-z0-9][a-z0-9_-]{0,63}(?:,[a-z0-9][a-z0-9_-]{0,63}){0,31}$/u +const keyList = /^(?:[a-z][a-z0-9-]{0,31}(?:,[a-z][a-z0-9-]{0,31}){0,63})?$/u + +/** The UI bridge versions the platform offers, newest first. */ +export const APP_UI_DEV_BRIDGES = ['1.3.0', '1.2.0', '1.1.0', '1.0.0'] as const + +/** The preview settings in the URL; anything malformed falls back to a working default. */ +export const appUiDevPreviewSearch = z.object({ + surface: z.enum(['page', 'dialog']).catch('page'), + bridge: z.enum(APP_UI_DEV_BRIDGES).catch('1.3.0'), + routes: z.string().regex(recordIds).catch('overview'), + route: z.string().regex(recordId).optional().catch(undefined), + keys: z.string().regex(keyList).catch(''), + dialogs: z.string().regex(keyList).catch(''), + name: z.string().trim().min(1).max(80).catch('App preview'), + // A platform host ID is a UUID; the dev stubs of apps also use readable record IDs. + host: z.string().regex(recordId).optional().catch(undefined), +}) + +export type AppUiDevPreviewSearch = z.infer + +/** What the dev server's call route answers; anything else counts as unavailable. */ +export const appUiDevPreviewResult = z.union([ + z.object({ ok: z.literal(true), payload: z.custom(isAppUiPayload) }), + z.object({ + ok: z.literal(false), + problem: z.object({ + requestId: z.string(), + status: z.number().int(), + code: z.string(), + title: z.string(), + type: z.string(), + }), + }), +]) + +/** Splits a comma list from the settings into its unique entries. */ +export function listEntries(value: string) { + return [...new Set(value.split(',').filter(Boolean))] +} diff --git a/web/src/lib/AppUi/paths.ts b/web/src/lib/AppUi/paths.ts index b3d4edd6f..a3e0fa2ed 100644 --- a/web/src/lib/AppUi/paths.ts +++ b/web/src/lib/AppUi/paths.ts @@ -1 +1,8 @@ export const APP_UI_PREFIX = '/__app-ui/' + +/** + * The dev server's preview of a locally built app UI. Production never serves it: the path then + * reaches the normal asset handler, which knows no such frame token. + */ +export const APP_UI_DEV_TOKEN = 'dev-preview' +export const APP_UI_DEV_PREFIX = APP_UI_PREFIX + APP_UI_DEV_TOKEN + '/' diff --git a/web/src/lib/Language/Locales/de.json b/web/src/lib/Language/Locales/de.json index 8d8127258..045188b76 100644 --- a/web/src/lib/Language/Locales/de.json +++ b/web/src/lib/Language/Locales/de.json @@ -417,6 +417,33 @@ "form": { "conflict": "Die gespeicherten Werte haben sich inzwischen geändert. Verwirf deine Änderungen, um mit den aktuellen Werten weiterzumachen." } + }, + "devPreview": { + "eyebrow": "Entwicklung", + "title": "App-UI-Vorschau", + "description": "Öffne die App-Oberfläche, an der du arbeitest, im Rahmen der Platform, als wäre die App installiert.", + "settings": "Vorschau-Einstellungen", + "surface": "Oberfläche", + "surfacePage": "Seite", + "surfaceDialog": "Dialog einer Hostzeile", + "bridge": "UI-Bridge", + "name": "App-Name", + "routes": "Routen", + "routesHint": "Durch Kommas getrennt; die erste öffnet sich standardmäßig.", + "keys": "Berechtigungsschlüssel", + "keysHint": "Die Manifest-Schlüssel, die der Vorschau-Nutzer hat, durch Kommas getrennt.", + "dialogs": "Bestätigungsdialoge", + "dialogsHint": "Die Dialog-IDs, die die App öffnen darf, durch Kommas getrennt.", + "host": "Host-ID", + "hostHint": "Die ID des Proxy-Hosts, für den sich der Dialog öffnet.", + "noHost": "Kein Host ausgewählt", + "apply": "Übernehmen", + "reload": "Neu laden", + "openDialog": "Dialog öffnen", + "missingDirectory": "Setze APP_UI_DEV_DIR auf den absoluten Ordner der gebauten App-Oberfläche und starte den Dev-Server neu.", + "missingApi": "Setze APP_UI_DEV_API auf den Loopback-Dev-Host deiner App, damit die Vorschau Operationen beantworten kann.", + "statusError": "Der Status der Vorschau konnte nicht gelesen werden.", + "ended": "Der App-Rahmen wurde beendet ({{reason}})." } }, "quickSearch": { diff --git a/web/src/lib/Language/Locales/en.json b/web/src/lib/Language/Locales/en.json index c56ea890b..721ef0cd8 100644 --- a/web/src/lib/Language/Locales/en.json +++ b/web/src/lib/Language/Locales/en.json @@ -417,6 +417,33 @@ "form": { "conflict": "The saved values changed in the meantime. Discard your changes to continue with the current values." } + }, + "devPreview": { + "eyebrow": "Development", + "title": "App UI preview", + "description": "Open the app UI you are building in the platform's own frame, as if the app were installed.", + "settings": "Preview settings", + "surface": "Surface", + "surfacePage": "Page", + "surfaceDialog": "Host row dialog", + "bridge": "UI bridge", + "name": "App name", + "routes": "Routes", + "routesHint": "Comma separated; the first one opens by default.", + "keys": "Permission keys", + "keysHint": "The manifest keys the preview user holds, comma separated.", + "dialogs": "Confirmation dialogs", + "dialogsHint": "The dialog IDs the app may open, comma separated.", + "host": "Host ID", + "hostHint": "The proxy host ID the dialog opens for.", + "noHost": "No host selected", + "apply": "Apply", + "reload": "Reload", + "openDialog": "Open dialog", + "missingDirectory": "Set APP_UI_DEV_DIR to the absolute folder of your app's built UI and restart the dev server.", + "missingApi": "Set APP_UI_DEV_API to your app's loopback dev host so the preview can answer operations.", + "statusError": "The preview status could not be read.", + "ended": "The app frame ended ({{reason}})." } }, "quickSearch": { diff --git a/web/src/lib/Language/Locales/es.json b/web/src/lib/Language/Locales/es.json index 3535e5044..dc729b65f 100644 --- a/web/src/lib/Language/Locales/es.json +++ b/web/src/lib/Language/Locales/es.json @@ -419,6 +419,33 @@ "form": { "conflict": "Los valores guardados han cambiado mientras tanto. Descarta tus cambios para continuar con los valores actuales." } + }, + "devPreview": { + "eyebrow": "Desarrollo", + "title": "Vista previa de la UI de la app", + "description": "Abre la interfaz de la app que estás creando en el marco de la plataforma, como si la app estuviera instalada.", + "settings": "Ajustes de la vista previa", + "surface": "Superficie", + "surfacePage": "Página", + "surfaceDialog": "Diálogo de fila de host", + "bridge": "Puente de UI", + "name": "Nombre de la app", + "routes": "Rutas", + "routesHint": "Separadas por comas; la primera se abre por defecto.", + "keys": "Claves de permiso", + "keysHint": "Las claves del manifiesto que tiene el usuario de la vista previa, separadas por comas.", + "dialogs": "Diálogos de confirmación", + "dialogsHint": "Los ID de diálogo que la app puede abrir, separados por comas.", + "host": "ID del host", + "hostHint": "El ID del host proxy para el que se abre el diálogo.", + "noHost": "Ningún host seleccionado", + "apply": "Aplicar", + "reload": "Recargar", + "openDialog": "Abrir diálogo", + "missingDirectory": "Define APP_UI_DEV_DIR con la carpeta absoluta de la UI compilada de tu app y reinicia el servidor de desarrollo.", + "missingApi": "Define APP_UI_DEV_API con el host de desarrollo loopback de tu app para que la vista previa pueda responder a las operaciones.", + "statusError": "No se pudo leer el estado de la vista previa.", + "ended": "El marco de la app terminó ({{reason}})." } }, "quickSearch": { diff --git a/web/src/lib/Language/Locales/fr.json b/web/src/lib/Language/Locales/fr.json index 592c4c99d..d9a823efa 100644 --- a/web/src/lib/Language/Locales/fr.json +++ b/web/src/lib/Language/Locales/fr.json @@ -419,6 +419,33 @@ "form": { "conflict": "Les valeurs enregistrées ont changé entre-temps. Abandonne tes modifications pour continuer avec les valeurs actuelles." } + }, + "devPreview": { + "eyebrow": "Développement", + "title": "Aperçu de l'UI de l'app", + "description": "Ouvrez l'interface de l'app que vous développez dans le cadre de la plateforme, comme si l'app était installée.", + "settings": "Paramètres de l'aperçu", + "surface": "Surface", + "surfacePage": "Page", + "surfaceDialog": "Dialogue d'une ligne d'hôte", + "bridge": "Pont UI", + "name": "Nom de l'app", + "routes": "Routes", + "routesHint": "Séparées par des virgules ; la première s’ouvre par défaut.", + "keys": "Clés d'autorisation", + "keysHint": "Les clés du manifeste dont dispose l'utilisateur de l'aperçu, séparées par des virgules.", + "dialogs": "Dialogues de confirmation", + "dialogsHint": "Les identifiants de dialogue que l'app peut ouvrir, séparés par des virgules.", + "host": "ID de l'hôte", + "hostHint": "L'ID de l'hôte proxy pour lequel le dialogue s'ouvre.", + "noHost": "Aucun hôte sélectionné", + "apply": "Appliquer", + "reload": "Recharger", + "openDialog": "Ouvrir le dialogue", + "missingDirectory": "Définissez APP_UI_DEV_DIR sur le dossier absolu de l'UI compilée de votre app et redémarrez le serveur de développement.", + "missingApi": "Définissez APP_UI_DEV_API sur l'hôte de développement loopback de votre app pour que l'aperçu puisse répondre aux opérations.", + "statusError": "L'état de l'aperçu n'a pas pu être lu.", + "ended": "Le cadre de l'app s'est terminé ({{reason}})." } }, "quickSearch": { diff --git a/web/src/lib/Language/Locales/it.json b/web/src/lib/Language/Locales/it.json index f6fcb08d2..6181bbaf2 100644 --- a/web/src/lib/Language/Locales/it.json +++ b/web/src/lib/Language/Locales/it.json @@ -419,6 +419,33 @@ "form": { "conflict": "I valori salvati sono cambiati nel frattempo. Annulla le modifiche per continuare con i valori attuali." } + }, + "devPreview": { + "eyebrow": "Sviluppo", + "title": "Anteprima UI dell'app", + "description": "Apri l'interfaccia dell'app che stai sviluppando nel riquadro della piattaforma, come se l'app fosse installata.", + "settings": "Impostazioni dell'anteprima", + "surface": "Superficie", + "surfacePage": "Pagina", + "surfaceDialog": "Finestra di una riga host", + "bridge": "Bridge UI", + "name": "Nome dell'app", + "routes": "Route", + "routesHint": "Separate da virgole; la prima si apre per impostazione predefinita.", + "keys": "Chiavi di autorizzazione", + "keysHint": "Le chiavi del manifest dell'utente dell'anteprima, separate da virgole.", + "dialogs": "Finestre di conferma", + "dialogsHint": "Gli ID delle finestre che l'app può aprire, separati da virgole.", + "host": "ID host", + "hostHint": "L'ID dell'host proxy per cui si apre la finestra.", + "noHost": "Nessun host selezionato", + "apply": "Applica", + "reload": "Ricarica", + "openDialog": "Apri finestra", + "missingDirectory": "Imposta APP_UI_DEV_DIR sulla cartella assoluta della UI compilata della tua app e riavvia il server di sviluppo.", + "missingApi": "Imposta APP_UI_DEV_API sull'host di sviluppo loopback della tua app, così l'anteprima può rispondere alle operazioni.", + "statusError": "Non è stato possibile leggere lo stato dell'anteprima.", + "ended": "Il riquadro dell'app è terminato ({{reason}})." } }, "quickSearch": { diff --git a/web/src/lib/Language/Locales/nl.json b/web/src/lib/Language/Locales/nl.json index 67c22bb97..44cc66b1f 100644 --- a/web/src/lib/Language/Locales/nl.json +++ b/web/src/lib/Language/Locales/nl.json @@ -398,6 +398,33 @@ "form": { "conflict": "De opgeslagen waarden zijn intussen gewijzigd. Verwerp je wijzigingen om verder te gaan met de huidige waarden." } + }, + "devPreview": { + "eyebrow": "Ontwikkeling", + "title": "App-UI-voorbeeld", + "description": "Open de app-interface waaraan je werkt in het kader van het platform, alsof de app geïnstalleerd is.", + "settings": "Voorbeeldinstellingen", + "surface": "Weergave", + "surfacePage": "Pagina", + "surfaceDialog": "Dialoog van een hostrij", + "bridge": "UI-bridge", + "name": "App-naam", + "routes": "Routes", + "routesHint": "Gescheiden door komma’s; de eerste opent standaard.", + "keys": "Rechtensleutels", + "keysHint": "De manifestsleutels die de voorbeeldgebruiker heeft, gescheiden door komma’s.", + "dialogs": "Bevestigingsdialogen", + "dialogsHint": "De dialoog-ID’s die de app mag openen, gescheiden door komma’s.", + "host": "Host-ID", + "hostHint": "De ID van de proxyhost waarvoor de dialoog opent.", + "noHost": "Geen host geselecteerd", + "apply": "Toepassen", + "reload": "Opnieuw laden", + "openDialog": "Dialoog openen", + "missingDirectory": "Stel APP_UI_DEV_DIR in op de absolute map van de gebouwde UI van je app en herstart de dev-server.", + "missingApi": "Stel APP_UI_DEV_API in op de loopback-dev-host van je app, zodat het voorbeeld bewerkingen kan beantwoorden.", + "statusError": "De status van het voorbeeld kon niet worden gelezen.", + "ended": "Het app-kader is beëindigd ({{reason}})." } }, "quickSearch": { diff --git a/web/src/lib/Language/Locales/pl.json b/web/src/lib/Language/Locales/pl.json index 358a9c15a..3b7c2d317 100644 --- a/web/src/lib/Language/Locales/pl.json +++ b/web/src/lib/Language/Locales/pl.json @@ -421,6 +421,33 @@ "form": { "conflict": "Zapisane wartości zmieniły się w międzyczasie. Odrzuć zmiany, aby kontynuować z aktualnymi wartościami." } + }, + "devPreview": { + "eyebrow": "Programowanie", + "title": "Podgląd interfejsu aplikacji", + "description": "Otwórz interfejs aplikacji, nad którym pracujesz, w ramce platformy, tak jakby aplikacja była zainstalowana.", + "settings": "Ustawienia podglądu", + "surface": "Powierzchnia", + "surfacePage": "Strona", + "surfaceDialog": "Okno wiersza hosta", + "bridge": "Most UI", + "name": "Nazwa aplikacji", + "routes": "Trasy", + "routesHint": "Oddzielone przecinkami; pierwsza otwiera się domyślnie.", + "keys": "Klucze uprawnień", + "keysHint": "Klucze manifestu, które ma użytkownik podglądu, oddzielone przecinkami.", + "dialogs": "Okna potwierdzenia", + "dialogsHint": "Identyfikatory okien, które aplikacja może otworzyć, oddzielone przecinkami.", + "host": "ID hosta", + "hostHint": "ID hosta proxy, dla którego otwiera się okno.", + "noHost": "Nie wybrano hosta", + "apply": "Zastosuj", + "reload": "Załaduj ponownie", + "openDialog": "Otwórz okno", + "missingDirectory": "Ustaw APP_UI_DEV_DIR na bezwzględny folder zbudowanego interfejsu aplikacji i uruchom ponownie serwer deweloperski.", + "missingApi": "Ustaw APP_UI_DEV_API na lokalny (loopback) host deweloperski aplikacji, aby podgląd mógł odpowiadać na operacje.", + "statusError": "Nie udało się odczytać stanu podglądu.", + "ended": "Ramka aplikacji została zakończona ({{reason}})." } }, "quickSearch": { diff --git a/web/src/lib/Language/Locales/pt.json b/web/src/lib/Language/Locales/pt.json index c63617566..ab16f9233 100644 --- a/web/src/lib/Language/Locales/pt.json +++ b/web/src/lib/Language/Locales/pt.json @@ -419,6 +419,33 @@ "form": { "conflict": "Os valores guardados mudaram entretanto. Descarta as tuas alterações para continuar com os valores atuais." } + }, + "devPreview": { + "eyebrow": "Desenvolvimento", + "title": "Pré-visualização da UI da app", + "description": "Abra a interface da app que está a desenvolver no quadro da plataforma, como se a app estivesse instalada.", + "settings": "Definições da pré-visualização", + "surface": "Superfície", + "surfacePage": "Página", + "surfaceDialog": "Diálogo de linha de host", + "bridge": "Ponte de UI", + "name": "Nome da app", + "routes": "Rotas", + "routesHint": "Separadas por vírgulas; a primeira abre por predefinição.", + "keys": "Chaves de permissão", + "keysHint": "As chaves do manifesto que o utilizador da pré-visualização tem, separadas por vírgulas.", + "dialogs": "Diálogos de confirmação", + "dialogsHint": "Os IDs de diálogo que a app pode abrir, separados por vírgulas.", + "host": "ID do host", + "hostHint": "O ID do host proxy para o qual o diálogo abre.", + "noHost": "Nenhum host selecionado", + "apply": "Aplicar", + "reload": "Recarregar", + "openDialog": "Abrir diálogo", + "missingDirectory": "Defina APP_UI_DEV_DIR com a pasta absoluta da UI compilada da sua app e reinicie o servidor de desenvolvimento.", + "missingApi": "Defina APP_UI_DEV_API com o host de desenvolvimento loopback da sua app para que a pré-visualização possa responder às operações.", + "statusError": "Não foi possível ler o estado da pré-visualização.", + "ended": "O quadro da app terminou ({{reason}})." } }, "quickSearch": { diff --git a/web/src/routeTree.gen.ts b/web/src/routeTree.gen.ts index 7b8f8607f..ac1d51f10 100644 --- a/web/src/routeTree.gen.ts +++ b/web/src/routeTree.gen.ts @@ -43,6 +43,7 @@ import { Route as ApiMigrationRouteImport } from './routes/api/migration' import { Route as ApiNpmImportRouteImport } from './routes/api/npm-import' import { Route as HealthLiveRouteImport } from './routes/health/live' import { Route as HealthReadyRouteImport } from './routes/health/ready' +import { Route as AuthenticatedDevAppUiRouteImport } from './routes/_authenticated/dev.app-ui' import { Route as PublicLoginIndexRouteImport } from './routes/_public/login.index' import { Route as PublicLoginTwoFactorRouteImport } from './routes/_public/login.two-factor' import { Route as ApiMigrationExportRouteImport } from './routes/api/migration/export' @@ -244,6 +245,11 @@ const HealthReadyRoute = HealthReadyRouteImport.update({ path: '/health/ready', getParentRoute: () => rootRouteImport, } as any) +const AuthenticatedDevAppUiRoute = AuthenticatedDevAppUiRouteImport.update({ + id: '/dev/app-ui', + path: '/dev/app-ui', + getParentRoute: () => AuthenticatedRouteRoute, +} as any) const PublicLoginIndexRoute = PublicLoginIndexRouteImport.update({ id: '/', path: '/', @@ -412,6 +418,7 @@ export interface FileRoutesByFullPath { '/api/npm-import': typeof ApiNpmImportRoute '/health/live': typeof HealthLiveRoute '/health/ready': typeof HealthReadyRoute + '/dev/app-ui': typeof AuthenticatedDevAppUiRoute '/login/two-factor': typeof PublicLoginTwoFactorRoute '/api/migration/export': typeof ApiMigrationExportRoute '/media/avatars/$userId': typeof MediaAvatarsUserIdRoute @@ -470,6 +477,7 @@ export interface FileRoutesByTo { '/api/npm-import': typeof ApiNpmImportRoute '/health/live': typeof HealthLiveRoute '/health/ready': typeof HealthReadyRoute + '/dev/app-ui': typeof AuthenticatedDevAppUiRoute '/login/two-factor': typeof PublicLoginTwoFactorRoute '/api/migration/export': typeof ApiMigrationExportRoute '/media/avatars/$userId': typeof MediaAvatarsUserIdRoute @@ -532,6 +540,7 @@ export interface FileRoutesById { '/health/live': typeof HealthLiveRoute '/health/ready': typeof HealthReadyRoute '/_authenticated/': typeof AuthenticatedIndexRoute + '/_authenticated/dev/app-ui': typeof AuthenticatedDevAppUiRoute '/_public/login/two-factor': typeof PublicLoginTwoFactorRoute '/api/migration/export': typeof ApiMigrationExportRoute '/media/avatars/$userId': typeof MediaAvatarsUserIdRoute @@ -593,6 +602,7 @@ export interface FileRouteTypes { | '/api/npm-import' | '/health/live' | '/health/ready' + | '/dev/app-ui' | '/login/two-factor' | '/api/migration/export' | '/media/avatars/$userId' @@ -651,6 +661,7 @@ export interface FileRouteTypes { | '/api/npm-import' | '/health/live' | '/health/ready' + | '/dev/app-ui' | '/login/two-factor' | '/api/migration/export' | '/media/avatars/$userId' @@ -712,6 +723,7 @@ export interface FileRouteTypes { | '/health/live' | '/health/ready' | '/_authenticated/' + | '/_authenticated/dev/app-ui' | '/_public/login/two-factor' | '/api/migration/export' | '/media/avatars/$userId' @@ -1009,6 +1021,13 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof HealthReadyRouteImport parentRoute: typeof rootRouteImport } + '/_authenticated/dev/app-ui': { + id: '/_authenticated/dev/app-ui' + path: '/dev/app-ui' + fullPath: '/dev/app-ui' + preLoaderRoute: typeof AuthenticatedDevAppUiRouteImport + parentRoute: typeof AuthenticatedRouteRoute + } '/_public/login/': { id: '/_public/login/' path: '/' @@ -1210,6 +1229,7 @@ interface AuthenticatedRouteRouteChildren { AuthenticatedSecurityRoute: typeof AuthenticatedSecurityRoute AuthenticatedUsersRoute: typeof AuthenticatedUsersRoute AuthenticatedIndexRoute: typeof AuthenticatedIndexRoute + AuthenticatedDevAppUiRoute: typeof AuthenticatedDevAppUiRoute AuthenticatedAppsInstallationIdChar123RouteIdChar125Route: typeof AuthenticatedAppsInstallationIdChar123RouteIdChar125Route } @@ -1236,6 +1256,7 @@ const AuthenticatedRouteRouteChildren: AuthenticatedRouteRouteChildren = { AuthenticatedSecurityRoute: AuthenticatedSecurityRoute, AuthenticatedUsersRoute: AuthenticatedUsersRoute, AuthenticatedIndexRoute: AuthenticatedIndexRoute, + AuthenticatedDevAppUiRoute: AuthenticatedDevAppUiRoute, AuthenticatedAppsInstallationIdChar123RouteIdChar125Route: AuthenticatedAppsInstallationIdChar123RouteIdChar125Route, } diff --git a/web/src/routes/_authenticated/dev.app-ui.tsx b/web/src/routes/_authenticated/dev.app-ui.tsx new file mode 100644 index 000000000..1d9d8c0c4 --- /dev/null +++ b/web/src/routes/_authenticated/dev.app-ui.tsx @@ -0,0 +1,29 @@ +import { createFileRoute, notFound } from '@tanstack/react-router' + +import AppUiDevPreviewPage from '@/features/AppUiDevPreview/index.tsx' +import { appUiDevPreviewSearch } from '@/features/AppUiDevPreview/validation.ts' +import { requireOwnerRoute } from '@/features/Auth/route-guards.ts' + +export const Route = createFileRoute('/_authenticated/dev/app-ui')({ + beforeLoad: (options) => { + // The preview exists only on the dev server; a production build has no such page. + if (!import.meta.env.DEV) throw notFound() + requireOwnerRoute(options) + }, + validateSearch: (search: Record) => appUiDevPreviewSearch.parse(search), + component: AppUiDevPreviewRoute, +}) + +function AppUiDevPreviewRoute() { + const search = Route.useSearch() + const navigate = Route.useNavigate() + + return ( + { + void navigate({ search: next, resetScroll: false }).catch(() => {}) + }} + /> + ) +} diff --git a/web/src/server.ts b/web/src/server.ts index e83302cce..ad2a5db79 100644 --- a/web/src/server.ts +++ b/web/src/server.ts @@ -1,7 +1,7 @@ import { createStartHandler, defaultStreamHandler } from '@tanstack/react-start/server' import { createServerEntry } from '@tanstack/react-start/server-entry' -import { APP_UI_PREFIX } from '@/lib/AppUi/paths.ts' +import { APP_UI_DEV_PREFIX, APP_UI_PREFIX } from '@/lib/AppUi/paths.ts' import { withRequestAbortHandling } from '@/server/request-abort.server.ts' import { startRestoreMaintenanceWatcher, @@ -18,6 +18,12 @@ const fetch = withRequestAbortHandling(serverEntry.fetch) const fencedFetch: typeof fetch = (request, options) => withRestoreMaintenanceFence(request, async () => { const url = new URL(request.url) + // The preview of a locally built app UI exists only on the dev server. + if (process.env.NODE_ENV !== 'production' && url.pathname.startsWith(APP_UI_DEV_PREFIX)) { + const { serveAppUiDevPreview } = + await import('@/server/AppRuntime/ui/dev-preview.server.ts') + return serveAppUiDevPreview(request, url) + } if (url.pathname.startsWith(APP_UI_PREFIX)) { const { serveAppUiHttp } = await import('@/server/AppRuntime/ui/http.server.ts') return serveAppUiHttp(request, url) diff --git a/web/src/server/AppRuntime/ui/dev-preview.server.ts b/web/src/server/AppRuntime/ui/dev-preview.server.ts new file mode 100644 index 000000000..5169e45cb --- /dev/null +++ b/web/src/server/AppRuntime/ui/dev-preview.server.ts @@ -0,0 +1,213 @@ +import '@tanstack/react-start/server-only' + +import { realpath } from 'node:fs/promises' +import { isAbsolute, relative, resolve } from 'node:path' +import { z } from 'zod' + +import { SESSION_COOKIE_NAME } from '@/config/auth.config.ts' +import { appUiAssetPolicy, appUiAssetType } from '@/lib/AppUi/asset-policy.ts' +import { isAppUiPayload } from '@/lib/AppUi/bridge.ts' +import type { AppUiPayload, AppUiResult } from '@/lib/AppUi/contract.ts' +import { APP_UI_DEV_PREFIX, APP_UI_DEV_TOKEN } from '@/lib/AppUi/paths.ts' +import { hasOwnerRole } from '@/server/Auth/Access/rbac.service.ts' +import { getSessionByTokenService } from '@/server/Auth/Access/sessions.service.ts' +import { getPublicOrigin } from '@/server/env.server.ts' +import { uiProblems } from './transport.server.ts' + +/* + * The dev server's preview of an app UI that is not installed: it serves the app's locally built + * UI from APP_UI_DEV_DIR under the real asset policy and forwards its operations to the app's + * local dev host at APP_UI_DEV_API. Both stay off in production and without a signed-in user. + */ + +const recordId = z.string().regex(/^[a-z0-9][a-z0-9_-]{0,63}$/u) +const maxCallBytes = 1_048_576 +// A reply holds one payload of at most 1 MiB and a small envelope around it. +const maxReplyBytes = maxCallBytes + 65_536 +const callTimeoutMs = 15_000 +const assetPath = /^(?:[A-Za-z0-9_-][A-Za-z0-9._-]*\/)*[A-Za-z0-9_-][A-Za-z0-9._-]*$/u +const loopbackHosts = new Set(['localhost', '127.0.0.1', '[::1]']) + +const payload = z.custom(isAppUiPayload) +const callInput = z.strictObject({ + requestId: recordId, + operationId: recordId, + idempotencyKey: recordId, + permissionKeys: z.array(z.string().regex(/^[a-z][a-z0-9-]{0,31}$/u)).max(64), + payload, +}) +const devAnswer = z.union([ + z.strictObject({ ok: z.literal(true), payload }), + z.strictObject({ + ok: z.literal(false), + problem: z.object({ + status: z.number().int().min(400).max(599), + code: z.string().min(1).max(64), + title: z.string().min(1).max(200), + type: z.string().min(1).max(200).optional(), + }), + }), +]) + +function production() { + return process.env.NODE_ENV === 'production' +} + +/** The absolute directory of the app's built UI, or undefined when the preview is off. */ +export function appUiDevDirectory(): string | undefined { + const value = process.env.APP_UI_DEV_DIR?.trim() + return !production() && value && isAbsolute(value) ? value : undefined +} + +/** The app's local dev host that answers operations; only a loopback address is accepted. */ +export function appUiDevApi(): URL | undefined { + const value = process.env.APP_UI_DEV_API?.trim() + if (production() || !value || !URL.canParse(value)) return undefined + const url = new URL(value) + return (url.protocol === 'http:' || url.protocol === 'https:') && + loopbackHosts.has(url.hostname) + ? url + : undefined +} + +function noStore(extra: Record = {}) { + return { + 'Cache-Control': 'private, no-store', + 'X-Content-Type-Options': 'nosniff', + 'Referrer-Policy': 'no-referrer', + ...extra, + } +} + +function answer(result: AppUiResult) { + return Response.json(result, { + headers: noStore({ 'Content-Security-Policy': "default-src 'none'; sandbox" }), + }) +} + +/** The preview is the owner's: the page is owner-only, so are its document and operations. */ +async function owner(request: Request) { + const token = new Bun.CookieMap(request.headers.get('cookie') ?? '').get(SESSION_COOKIE_NAME) + const session = token ? await getSessionByTokenService(token) : null + return session !== null && hasOwnerRole(session.user.roles) +} + +/** A body as text, or undefined once it grows past `limit` bytes; nothing more is buffered. */ +async function readLimited(body: ReadableStream | null, limit: number) { + if (!body) return undefined + const reader = body.getReader() + const chunks: Uint8Array[] = [] + let size = 0 + try { + for (;;) { + // oxlint-disable-next-line no-await-in-loop -- Each chunk counts before the next one. + const { done, value } = await reader.read() + if (done) break + size += value.byteLength + if (size > limit) { + // The rest of the body is never read. + void reader.cancel().catch(() => undefined) + return undefined + } + chunks.push(value) + } + return new TextDecoder('utf-8', { fatal: true }).decode(Buffer.concat(chunks, size)) + } catch { + return undefined + } +} + +async function asset(request: Request, path: string, origin: string, directory: string) { + if (request.method !== 'GET' || !assetPath.test(path)) return undefined + const document = path === 'index.html' + const mime = appUiAssetType(request, path, document) + if (!mime) return new Response(null, { status: 403 }) + const root = await realpath(directory).catch(() => undefined) + const file = root ? await realpath(resolve(root, path)).catch(() => undefined) : undefined + // Links inside the directory may not lead out of it, also when the directory is a root. + if (!root || !file) return undefined + const inside = relative(root, file) + if (!inside || inside.startsWith('..') || isAbsolute(inside)) return undefined + return new Response(Bun.file(file), { + headers: noStore({ + 'Content-Type': mime, + 'Content-Security-Policy': appUiAssetPolicy(origin, APP_UI_DEV_TOKEN), + ...(!document && { 'Access-Control-Allow-Origin': 'null' }), + }), + }) +} + +async function call(request: Request, origin: string): Promise { + if ( + request.method !== 'POST' || + request.headers.get('origin') !== origin || + request.headers.get('sec-fetch-site') !== 'same-origin' + ) + return answer({ ok: false, problem: uiProblems.forbidden.document() }) + const body = await readLimited(request.body, maxCallBytes) + let decoded: unknown + try { + decoded = body === undefined ? undefined : JSON.parse(body) + } catch { + decoded = undefined + } + const parsed = callInput.safeParse(decoded) + if (!parsed.success) return answer({ ok: false, problem: uiProblems.invalid.document() }) + const { requestId, ...forwarded } = parsed.data + const api = appUiDevApi() + if (!api) + return answer({ + ok: false, + problem: { + ...uiProblems.unavailable.document(requestId), + title: 'Set APP_UI_DEV_API to a loopback dev host to answer app operations.', + }, + }) + try { + const response = await fetch(api, { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify(forwarded), + signal: AbortSignal.timeout(callTimeoutMs), + redirect: 'error', + }) + // The dev host's answer is read with a bound too, before it is decoded. + const text = await readLimited(response.body, maxReplyBytes) + if (text === undefined) throw new Error('The dev host answered too much') + const reply = devAnswer.safeParse(JSON.parse(text)) + if (!reply.success) throw new Error('The dev host answered no app UI result') + if (reply.data.ok) return answer(reply.data) + const { status, code, title, type } = reply.data.problem + return answer({ + ok: false, + problem: { + requestId, + status, + code, + title, + type: type ?? `urn:rentnerproxy:problem:${code}`, + }, + }) + } catch { + return answer({ ok: false, problem: uiProblems.upstream.document(requestId) }) + } +} + +/** + * Serves the preview's files and calls; anything off, unknown or unsigned answers 404. The app's + * scripts and styles load from its opaque origin without cookies, as the assets of an installed + * app do, so only the document and the operations need the signed-in user. + */ +export async function serveAppUiDevPreview(request: Request, url: URL): Promise { + const directory = appUiDevDirectory() + const origin = getPublicOrigin() + const path = url.pathname.slice(APP_UI_DEV_PREFIX.length) + const gated = path === 'call' || path === 'index.html' + if (!directory || !origin || url.search || (gated && !(await owner(request)))) + return new Response(null, { status: 404, headers: noStore() }) + if (path === 'call') return call(request, origin) + return ( + (await asset(request, path, origin, directory)) ?? + new Response(null, { status: 404, headers: noStore() }) + ) +} diff --git a/web/src/tests/features/AppUiDevPreview/app-ui-dev-preview.test.tsx b/web/src/tests/features/AppUiDevPreview/app-ui-dev-preview.test.tsx new file mode 100644 index 000000000..21eaf154f --- /dev/null +++ b/web/src/tests/features/AppUiDevPreview/app-ui-dev-preview.test.tsx @@ -0,0 +1,347 @@ +import { afterEach, beforeEach, describe, expect, mock, test } from 'bun:test' +import { GlobalRegistrator } from '@happy-dom/global-registrator' +import { QueryClient, QueryClientProvider } from '@tanstack/react-query' +import type { Root } from 'react-dom/client' +import type { AppFrameViewProps } from '@/features/AppUi/Types/app-frame-view.types.ts' +import type { AppUiDevPreviewStatus } from '@/features/AppUiDevPreview/Types/app-ui-dev-preview.types.ts' +import type { AppUiDevPreviewSearch } from '@/features/AppUiDevPreview/validation.ts' +import withTestLanguage from '@/tests/Helpers/withTestLanguage.tsx' + +if (!GlobalRegistrator.isRegistered) GlobalRegistrator.register({ url: 'https://platform.test/' }) +Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true }) + +let status: AppUiDevPreviewStatus = { directory: '/work/app/ui', api: null } +const frames: AppFrameViewProps[] = [] +const openDialog = mock((_dialog: { mount: string; dialogId: string; appName: string }) => {}) +const cancelDialog = mock((_mount: string) => {}) + +let statusFails = false +await mock.module('@/features/AppUiDevPreview/middleware.ts', () => ({ + readAppUiDevPreviewStatusHandler: async () => { + if (statusFails) throw new Error('The dev server is restarting') + return status + }, +})) +await mock.module('@/features/AppUi/AppUiProvider.tsx', () => ({ + useAppUi: () => ({ theme: 'dark', openDialog, cancelDialog }), +})) +await mock.module('@/features/AppUi/Components/AppFrameView.tsx', () => ({ + default: (props: AppFrameViewProps) => { + frames.push(props) + return + }, +})) + +const { act } = await import('react') +const { createRoot } = await import('react-dom/client') +const { default: AppUiDevPreviewPage } = await import('@/features/AppUiDevPreview/index.tsx') +const { appUiDevPreviewSearch } = await import('@/features/AppUiDevPreview/validation.ts') + +const defaults = appUiDevPreviewSearch.parse({}) +let root: Root +let container: HTMLDivElement +let search: AppUiDevPreviewSearch +const changes: AppUiDevPreviewSearch[] = [] +const originalFetch = globalThis.fetch + +async function render(next: AppUiDevPreviewSearch = search) { + search = next + const client = new QueryClient() + await act(async () => { + root.render( + withTestLanguage( + + { + changes.push(value) + search = value + }} + /> + , + ), + ) + }) + await act(async () => { + await new Promise((resolve) => setTimeout(resolve, 0)) + }) +} + +function frame() { + const last = frames.at(-1) + if (!last) throw new Error('No app frame was drawn') + return last +} + +async function click(element: Element | null | undefined) { + if (!element) throw new Error('Nothing to click') + await act(async () => { + element.dispatchEvent(new MouseEvent('click', { bubbles: true, cancelable: true })) + await Promise.resolve() + }) +} + +function button(text: string) { + return [...document.querySelectorAll('button')].find((item) => item.textContent === text) +} + +async function setInputValue(input: HTMLInputElement, value: string) { + const setter = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value')?.set + await act(async () => { + setter?.call(input, value) + input.dispatchEvent(new Event('input', { bubbles: true })) + input.dispatchEvent(new Event('change', { bubbles: true })) + await Promise.resolve() + }) +} + +beforeEach(() => { + status = { directory: '/work/app/ui', api: null } + statusFails = false + frames.length = 0 + changes.length = 0 + openDialog.mockClear() + cancelDialog.mockClear() + document.body.innerHTML = '' + container = document.createElement('div') + document.body.append(container) + root = createRoot(container) + search = { ...defaults, routes: 'overview,details', keys: 'monitor-read', dialogs: 'confirm' } +}) + +afterEach(async () => { + globalThis.fetch = originalFetch + await act(async () => root.unmount()) +}) + +describe('app UI dev preview settings', () => { + test('fall back to a working preview for anything malformed', () => { + expect(defaults).toEqual({ + surface: 'page', + bridge: '1.3.0', + routes: 'overview', + keys: '', + dialogs: '', + name: 'App preview', + }) + expect( + appUiDevPreviewSearch.parse({ + surface: 'popup', + bridge: '2.0.0', + routes: 'Bad Route', + route: '../x', + keys: 'Monitor', + dialogs: 'a,,b', + name: ' ', + host: 'Not A Host!', + }), + ).toEqual({ ...defaults, route: undefined, host: undefined }) + }) +}) + +describe('app UI dev preview page', () => { + test('draws the local build as an installed app page', async () => { + await render() + const current = frame() + expect(current.slot).toBe('navigation') + expect(current.source).toEqual({ + nonce: 'dev-1', + url: '/__app-ui/dev-preview/index.html#nonce=dev-1&slot=navigation', + }) + expect(current.theme).toBe('dark') + expect(current.route).toBe('overview') + expect(current.app).toMatchObject({ + appId: 'dev.preview', + uiBridgeVersion: '1.3.0', + name: 'App preview', + routes: ['overview', 'details'], + dialogs: ['confirm'], + permissionKeys: ['monitor-read'], + slots: ['navigation'], + }) + expect(document.body.textContent).toContain('Set APP_UI_DEV_API') + + await act(async () => current.onNavigate('details')) + expect(changes.at(-1)?.route).toBe('details') + await render() + expect(frame().route).toBe('details') + expect(frame().source.nonce).toBe('dev-1') + }) + + test('asks for the build folder before drawing anything', async () => { + status = { directory: null, api: null } + await render() + expect(frames).toEqual([]) + expect(document.body.textContent).toContain('Set APP_UI_DEV_DIR') + expect(document.body.textContent).not.toContain('Set APP_UI_DEV_API') + }) + + test('answers operations through the dev server and checks what comes back', async () => { + status = { directory: '/work/app/ui', api: 'http://127.0.0.1:8787/call' } + const requests: { url: string; body: unknown }[] = [] + let answer: unknown = { ok: true, payload: { checks: 3 } } + globalThis.fetch = Object.assign( + async (input: string | URL | Request, init?: RequestInit) => { + requests.push({ url: String(input), body: JSON.parse(String(init?.body)) }) + return Response.json(answer) + }, + { preconnect: originalFetch.preconnect }, + ) + await render() + const request = { + requestId: 'request-1', + operationId: 'checks-list', + idempotencyKey: 'key-1', + payload: { page: 1 }, + } + const message = { + ...request, + type: 'apiRequest' as const, + installId: 'dev-preview', + installationGeneration: 1, + generation: 1, + } + const signal = new AbortController().signal + expect(await frame().onApiRequest(message, signal)).toEqual({ + ok: true, + payload: { checks: 3 }, + }) + expect(requests).toEqual([ + { + url: '/__app-ui/dev-preview/call', + body: { ...request, permissionKeys: ['monitor-read'] }, + }, + ]) + answer = { ok: 'maybe' } + expect(await frame().onApiRequest(message, signal)).toMatchObject({ + ok: false, + problem: { requestId: 'request-1', code: 'unavailable', status: 503 }, + }) + expect(document.body.textContent).not.toContain('Set APP_UI_DEV_API') + }) + + test('opens confirmations in the platform and closes them with the frame', async () => { + await render() + const settle = mock(() => {}) + frame().onDialog({ dialogId: 'confirm' } as never, settle) + expect(openDialog).toHaveBeenCalledWith({ + appName: 'App preview', + dialogId: 'confirm', + mount: 'dev-1', + settle, + }) + frame().onEnded?.() + expect(cancelDialog).toHaveBeenCalledWith('dev-1') + }) + + test('shows why the frame ended and reloads it with a new session', async () => { + await render() + await act(async () => frame().onDisconnect('disconnected')) + expect(container.querySelector('[data-frame]')).toBeNull() + expect(document.body.textContent).toContain('The app frame ended (disconnected).') + const reloads = [...container.querySelectorAll('button')].filter( + (item) => item.textContent === 'Reload', + ) + await click(reloads.at(-1)) + expect(container.querySelector('[data-frame]')).not.toBeNull() + expect(frame().source.nonce).toBe('dev-2') + }) + + test('applies edited settings and opens a fresh frame for them', async () => { + await render() + const name = container.querySelector('input[name="name"]') + const keys = container.querySelector('input[name="keys"]') + if (!name || !keys) throw new Error('Settings fields are missing') + await setInputValue(name, 'Monitoring') + await setInputValue(keys, 'monitor-write,monitor-read,monitor-write') + await click(button('Apply')) + expect(changes.at(-1)).toEqual({ + ...search, + name: 'Monitoring', + keys: 'monitor-write,monitor-read,monitor-write', + }) + await render() + expect(frame().source.nonce).toBe('dev-2') + expect(frame().app).toMatchObject({ + name: 'Monitoring', + permissionKeys: ['monitor-read', 'monitor-write'], + }) + }) + + test('follows settings from browser history: a new frame and the draft, not for the route', async () => { + await render() + await render({ ...search, route: 'details' }) + expect(frame().source.nonce).toBe('dev-1') + await render({ ...search, name: 'From history' }) + expect(frame().source.nonce).toBe('dev-2') + expect(frame().app.name).toBe('From history') + expect(container.querySelector('input[name="name"]')?.value).toBe( + 'From history', + ) + }) + + test('offers to read the status again when it could not be read', async () => { + statusFails = true + await render() + expect(document.body.textContent).toContain('The preview status could not be read.') + expect(frames).toEqual([]) + statusFails = false + await click(button('Try again')) + await act(async () => { + await new Promise((resolve) => setTimeout(resolve, 0)) + }) + expect(document.body.textContent).not.toContain('could not be read') + expect(frame().source.nonce).toBe('dev-1') + }) + + test('draws a host row dialog in the platform dialog surface', async () => { + const host = '0198d98a-0000-7000-8000-000000000001' + await render({ ...search, surface: 'dialog', host }) + expect(frames).toEqual([]) + await click(button('Open dialog')) + const current = frame() + expect(current.slot).toBe('proxyHostTab') + expect(current.app.slots).toEqual(['proxyHostTab']) + expect(current.source.url).toBe( + `/__app-ui/dev-preview/index.html#nonce=dev-2&slot=proxyHostTab&hostId=${host}`, + ) + expect(document.querySelector('[role="dialog"]')?.textContent).toContain(host) + await click(button('Close')) + expect(document.querySelector('[data-frame]')).toBeNull() + }) +}) + +describe('app UI dev preview route', () => { + test('exists only on the dev server and only for owners', async () => { + const registry = new Map void }>() + await mock.module('@/features/Auth/middleware.ts', () => ({ + getAuthStateHandler: async () => null, + logoutHandler: async () => ({ success: true }), + })) + await mock.module('@tanstack/react-router', () => ({ + createFileRoute: + (path: string) => (options: { beforeLoad: (input: unknown) => void }) => { + registry.set(path, options) + return { options } + }, + notFound: () => new Error('not-found'), + redirect: (options: { to: string }) => new Error(`redirect:${options.to}`), + })) + await import('@/routes/_authenticated/dev.app-ui.tsx') + const route = registry.get('/_authenticated/dev/app-ui') + const owner = { context: { user: { roles: ['owner'] } } } + const viewer = { context: { user: { roles: ['viewer'] } } } + // Bun reads import.meta.env from the process environment; Vite replaces it at build time. + const previous = process.env.DEV + try { + delete process.env.DEV + expect(() => route?.beforeLoad(owner)).toThrow('not-found') + process.env.DEV = 'true' + expect(() => route?.beforeLoad(owner)).not.toThrow() + expect(() => route?.beforeLoad(viewer)).toThrow('redirect:/') + } finally { + if (previous === undefined) delete process.env.DEV + else process.env.DEV = previous + } + }) +}) diff --git a/web/src/tests/features/AppUiDevPreview/middleware.test.ts b/web/src/tests/features/AppUiDevPreview/middleware.test.ts new file mode 100644 index 000000000..29378a1d0 --- /dev/null +++ b/web/src/tests/features/AppUiDevPreview/middleware.test.ts @@ -0,0 +1,50 @@ +import { beforeEach, expect, mock, test } from 'bun:test' + +let session: { user: { roles: string[] } } | null = null +let lookupFails = false +const headers = new Map() + +await mock.module('@tanstack/react-start', () => ({ + createServerFn: () => ({ handler: (handle: () => unknown) => handle }), +})) +await mock.module('@tanstack/react-start/server', () => ({ + setResponseHeader: (name: string, value: string) => { + headers.set(name, value) + }, +})) +await mock.module('@/server/Auth/Access/sessions.service.ts', () => ({ + getCurrentSessionService: async () => { + if (lookupFails) throw new Error('database unavailable') + return session + }, +})) +await mock.module('@/server/AppRuntime/ui/dev-preview.server.ts', () => ({ + appUiDevDirectory: () => '/work/app/ui', + appUiDevApi: () => new URL('http://127.0.0.1:8787/call'), +})) + +const { readAppUiDevPreviewStatusHandler } = + await import('@/features/AppUiDevPreview/middleware.ts') +const read = readAppUiDevPreviewStatusHandler as unknown as () => Promise + +beforeEach(() => headers.clear()) + +test('Only the owner learns where the preview reads its UI and operations from', async () => { + session = { user: { roles: ['owner'] } } + expect(await read()).toEqual({ directory: '/work/app/ui', api: 'http://127.0.0.1:8787/call' }) + expect(headers.get('Cache-Control')).toBe('private, no-store') + for (const other of [null, { user: { roles: ['viewer'] } }]) { + session = other + // oxlint-disable-next-line no-await-in-loop -- Each caller reads its own answer. + expect(await read()).toEqual({ directory: null, api: null }) + } +}) + +test('A failed session lookup fails the call instead of reporting a disabled preview', async () => { + lookupFails = true + try { + await expect(read()).rejects.toThrow('The session could not be read.') + } finally { + lookupFails = false + } +}) diff --git a/web/src/tests/server/AppRuntime/ui-dev-preview.test.ts b/web/src/tests/server/AppRuntime/ui-dev-preview.test.ts new file mode 100644 index 000000000..daa1a2433 --- /dev/null +++ b/web/src/tests/server/AppRuntime/ui-dev-preview.test.ts @@ -0,0 +1,273 @@ +import { afterAll, afterEach, beforeEach, describe, expect, mock, test } from 'bun:test' +import { mkdir, mkdtemp, rm, symlink, writeFile } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' + +// The owner may use the preview; another signed-in user may not. +const sessions: Record = { + 'signed-in': { id: 'owner-session', user: { roles: ['owner'] } }, + viewer: { id: 'viewer-session', user: { roles: ['viewer'] } }, +} +await mock.module('@/server/Auth/Access/sessions.service.ts', () => ({ + getSessionByTokenService: async (token: string) => sessions[token] ?? null, +})) +const { getPublicOrigin } = await import('@/server/env.server.ts') +const { appUiDevApi, appUiDevDirectory, serveAppUiDevPreview } = + await import('@/server/AppRuntime/ui/dev-preview.server.ts') + +const origin = getPublicOrigin()! +const prefix = origin + '/__app-ui/dev-preview/' +const root = await mkdtemp(join(tmpdir(), 'rentnerproxy-app-ui-dev-')) +const ui = join(root, 'ui') +await mkdir(join(ui, 'assets'), { recursive: true }) +await writeFile(join(ui, 'index.html'), '