diff --git a/frontend/src/buttons/ServiceConnectButton.tsx b/frontend/src/buttons/ServiceConnectButton.tsx index e7571112b..5206cc7c0 100644 --- a/frontend/src/buttons/ServiceConnectButton.tsx +++ b/frontend/src/buttons/ServiceConnectButton.tsx @@ -11,11 +11,12 @@ import { ErrorButton } from '../buttons/ErrorButton' import { DesktopUI } from '../components/DesktopUI' import { Gutters } from '../components/Gutters' import { LocalSubnetConnect } from '../components/LocalSubnetConnect' -import { isConsoleService } from '../helpers/sshHelper' +import { opensTerminal } from '../helpers/sshHelper' import { useLocalSignIn, useSubnetReach } from '../hooks/useLocalSubnetName' import { LocalSignInNotice } from '../components/LocalSignInNotice' import { BrowserGatewayConnect } from '../components/BrowserGatewayConnect' -import { ConsoleTerminalOption } from '../components/ConsoleTerminal' +import { AppTerminalOption } from '../components/AppTerminal' +import { useServiceApp } from '../hooks/useDeviceApps' import { useApplication } from '../hooks/useApplication' import { Link } from '../components/Link' import { LocalPortConnect } from '../components/LocalPortConnect' @@ -35,6 +36,10 @@ export const ServiceConnectButton: React.FC = () => { // (services/browserGateway), the proxy one step away as for a local name. const web = useApplication(service, connection).urlForm const ssh = service?.typeID === 28 + // The app the service belongs to, where it does: one whose service is ssh and that signs people in by certificate + // opens in our web SSH as well, with the person's own account (components/AppTerminal). + const serving = useServiceApp(device, service) + const byCertificate = opensTerminal(serving.app, serving.appService) const gateway = !local && reach.checked && !!reach.name && (!!web || ssh) && !proxy // A local port of this machine (services/localPorts), where it runs our daemon: asked for here, or open already — // then it is what the panel shows, until it is disconnected. @@ -125,7 +130,12 @@ export const ServiceConnectButton: React.FC = () => { ) : named ? ( {local ? ( - + ) : ( { port: service.port || 22, title: service.name, service: service.id, - console: isConsoleService(service), + byCertificate, } : undefined } @@ -167,10 +177,10 @@ export const ServiceConnectButton: React.FC = () => { {portLink} )} - {/* The console: our web SSH, an option beside the ways above. */} - {isConsoleService(service) && ( + {/* An app's ssh service that signs people in by certificate: our web SSH, an option beside the ways above. */} + {byCertificate && ( - + )} {/* The service's other ports here that this machine's daemon lists: the machine's, opened by someone else. */} diff --git a/frontend/src/components/AppCatalogRow.tsx b/frontend/src/components/AppCatalogRow.tsx index 17b10f298..533fdaae3 100644 --- a/frontend/src/components/AppCatalogRow.tsx +++ b/frontend/src/components/AppCatalogRow.tsx @@ -1,11 +1,12 @@ import React from 'react' import { useTranslation } from 'react-i18next' import { Box, ListItem, ListItemButton, ListItemIcon, ListItemText, Typography } from '@mui/material' -import { firstPartyApp } from './firstPartyApps' +import { appIcon, capabilitiesLine } from '../helpers/appsHelper' import { Icon } from './Icon' /* One app in the catalogue (presence-server docs/device-apps-design.md, "The Apps pages"): its name, its publisher with - Verified: and Yours for the account's own, Runs as root or Restricted, its description, its platforms and + Verified: and Yours for the account's own, Runs as root or Restricted and what else it asks of remote.it + (its capabilities, in words), its icon from how its service opens, its description, its platforms and what is said beside them (how many devices have it, or why this device cannot take it). The row opens the app; its action (Add…) sits at its end. */ export type AppCatalogRowProps = { @@ -15,6 +16,8 @@ export type AppCatalogRowProps = { verifiedDomain?: string | null own?: boolean // the account's own publisher root: boolean + capabilities?: string[] + protocol?: string | null // how its service opens: its icon description?: string | null platforms?: string | null // as families aside?: React.ReactNode // beside the platforms: how many devices have it @@ -30,6 +33,8 @@ export const AppCatalogRow: React.FC = ({ verifiedDomain, own, root, + capabilities, + protocol, description, platforms, aside, @@ -41,7 +46,7 @@ export const AppCatalogRow: React.FC = ({ const body = ( <> - + = ({ ? t('apps.runsAsRootFull', 'Runs as root: full control of the device') : t('apps.restricted', 'Restricted')} + {!!capabilities?.length && ( + + {capabilitiesLine(t, capabilities)} + + )} } secondaryTypographyProps={{ component: 'div' }} diff --git a/frontend/src/components/AppRootConsent.tsx b/frontend/src/components/AppRootConsent.tsx index 5933671b9..344761124 100644 --- a/frontend/src/components/AppRootConsent.tsx +++ b/frontend/src/components/AppRootConsent.tsx @@ -1,66 +1,131 @@ -import React, { useState } from 'react' +import React, { useEffect, useState } from 'react' import { useTranslation } from 'react-i18next' -import { Typography } from '@mui/material' +import { Box, Typography } from '@mui/material' import type { DeviceApp } from '../services/graphQLDeviceApps' import { AppChange, refused } from '../services/deviceAppsShared' import type { DeviceApps } from '../hooks/useDeviceApps' +import { asksConsent, capabilityWords, ConsentAsking } from '../helpers/appsHelper' +import { graphQLCatalogApp } from '../services/graphQLAppCatalog' import { Confirm } from './Confirm' -/* Asking for the person's yes to a root app's full control, in words naming the app, its publisher and that it gets - full control of the device (presence-server docs/device-apps-design.md, "Root, shown and consented to"). For a - product it says the yes covers every device in the product, now and later, as graphql keeps it on the product. */ +/* Asking for the person's yes to what a release asks (helpers/appsHelper asksConsent, graphql's rule): to run as root — + full control of the device (presence-server docs/device-apps-design.md, "Root, shown and consented to") — and the + capabilities it declares (presence-contract docs/self-contained-apps.md, "Manifest"), in words naming the app and its + publisher. A root release is asked as root, its capabilities beside; a restricted one that declares capabilities is + asked for those. For a product it says the yes covers every device in the product, now and later, as graphql keeps + it on the product. + + What is asked is the release's the yes is given to (release), not the version the device runs: a release may ask + more than the one before it, and graphql takes the yes as covering what that release asks. Where the change may give + one of several (a channel's candidate or current, by the device's bucket), all they ask together. It is read from its + catalogue entry, under the account the device or product was read for (useReleaseAsks); until it is, the yes waits. + action: the confirm button's words, where they are not turning it on, for a release that runs as root or not. */ export const RootConsent: React.FC<{ - app?: { name: string; publisher: string } // open while there is one + // open while there is one; root and capabilities: the app's own, where the catalogue does not name the release + app?: { id?: string; name: string; publisher: string; root: boolean; capabilities?: string[] } product?: boolean // a product's consent, for every device in it - action?: string // the confirm button's words, where they are not turning it on - // A release of an app already on that newly runs as root: the consent moves it there (a re-consent). + action?: (root: boolean) => string + // A release of an app already on that newly asks for consent: the consent moves it there (a re-consent). version?: string | null + // The release the yes is given to, where it is not version: a pin, the release enabling gives — or the releases a + // change may give. None: the app's own. + release?: string | string[] | null + accountId: string | undefined // whose catalogue names the release: the device's or the product's account onConfirm: () => void onDeny: () => void -}> = ({ app, product, action, version, onConfirm, onDeny }) => { +}> = ({ app, product, action, version, release, accountId, onConfirm, onDeny }) => { const { t } = useTranslation() const words = { app: app?.name, publisher: app?.publisher, version } + const asks = useReleaseAsks(app, release ?? version, accountId) + // Not known (null): asked as the most it could be, and not given until it is. + const root = asks ? asks.root : true return ( {version && ( - {product + {root + ? product + ? t( + 'productApps.rootUpdate', + '{{app}} {{version}} needs to run as root. Its devices stay on the version they run until you consent.', + words + ) + : t( + 'deviceApps.rootUpdate', + '{{app}} {{version}} needs to run as root. This device stays on the version it runs until you consent.', + words + ) + : product ? t( - 'productApps.rootUpdate', - '{{app}} {{version}} needs to run as root. Its devices stay on the version they run until you consent.', + 'productApps.asksUpdate', + '{{app}} {{version}} asks more of remote.it. Its devices stay on the version they run until you consent.', words ) : t( - 'deviceApps.rootUpdate', - '{{app}} {{version}} needs to run as root. This device stays on the version it runs until you consent.', + 'deviceApps.asksUpdate', + '{{app}} {{version}} asks more of remote.it. This device stays on the version it runs until you consent.', words )} )} - - {product + + {root + ? product + ? t( + 'productApps.rootBody', + '{{app}}, published by {{publisher}}, runs as root: it gets full control of this device — every file, account and program on it — on every device in this product, now and later.', + words + ) + : t( + 'deviceApps.rootBody', + '{{app}}, published by {{publisher}}, runs as root: it gets full control of this device — every file, account and program on it.', + words + ) + : product ? t( - 'productApps.rootBody', - '{{app}}, published by {{publisher}}, runs as root: it gets full control of this device — every file, account and program on it — on every device in this product, now and later.', + 'productApps.asksBody', + '{{app}}, published by {{publisher}}, runs restricted, with an account of its own on every device in this product, now and later.', words ) : t( - 'deviceApps.rootBody', - '{{app}}, published by {{publisher}}, runs as root: it gets full control of this device — every file, account and program on it.', + 'deviceApps.asksBody', + '{{app}}, published by {{publisher}}, runs restricted, with an account of its own on this device.', words )} + {asks === null && ( + + {t( + 'apps.asksUnknown', + 'What this version asks could not be read, so it cannot be consented to here. Try again later.' + )} + + )} + {product ? t( @@ -74,16 +139,80 @@ export const RootConsent: React.FC<{ ) } +/* What the releases a consent is for ask (whether one runs as root, and their capabilities, together): each its + catalogue entry's, read under the account the device or product was read for. The app's own where no release is + named (an app offered to the device: its fields are the release the device would be given). null where a release + named is not one the catalogue answers for (an API without one, an error, one it does not list): what it asks is + not known, and a yes to it is not taken. undefined while they are read. */ +export function useReleaseAsks( + app: { id?: string; root: boolean; capabilities?: string[] } | undefined, + release: string | string[] | null | undefined, + accountId: string | undefined +): ConsentAsking | null | undefined { + const [read, setRead] = useState<{ key: string; asks: ConsentAsking | null }>() + const releases = (Array.isArray(release) ? release : [release]).filter((r): r is string => !!r) + const key = app?.id && releases.length ? `${accountId ?? ''}/${app.id}/${releases.join(',')}` : '' + useEffect(() => { + if (!key || !app?.id) return + let current = true + graphQLCatalogApp(app.id, { accountId, releases: 100 }).then(answer => { + if (!current) return + const listed = typeof answer === 'object' && answer ? answer.releases : [] + const entries = releases.map(version => listed.find(r => r.version === version)) + const known = entries.every(entry => !!entry) + setRead({ + key, + asks: known + ? { + root: entries.some(entry => entry!.root), + capabilities: [...new Set(entries.flatMap(entry => entry!.capabilities))], + } + : null, + }) + }) + return () => { + current = false + } + }, [key]) + if (!app) return undefined + if (!key) return { root: app.root, capabilities: app.capabilities ?? [] } + if (read?.key !== key) return undefined + return read.asks +} + +// What an app asks of remote.it beyond running, a line each: in its consent, and where it is offered. +export const AppCapabilities: React.FC<{ capabilities?: string[]; title?: string }> = ({ capabilities, title }) => { + const { t } = useTranslation() + if (!capabilities?.length) return null + return ( + + {title ?? t('apps.capabilitiesAlso', 'It also asks of remote.it:')} + {capabilities.map(capability => ( + + · {capabilityWords(t, capability)} + + ))} + + ) +} + /* Enabling or disabling an app, from wherever it is offered (the device's Apps section, the app's page on the device, - the console's connect panel). A root app is enabled only once the person says yes (RootConsent); that yes is - consentRoot, which graphql refuses a root app without. Disabling, or a restricted app, at once. A release that newly - runs as root while the app is enabled (awaitingRoot) is asked for the same way (reconsent): the yes is - setDeviceAppRelease's consentRoot alone — Update now —, which moves the device to that release. graphql's refusal, - in its words, goes to onRefused; a change made, to onChanged. */ + an app's service's connect panel, the device's catalogue). An app is enabled only once the person says yes + (RootConsent) where graphql asks for one (needsConsent); that yes is consentRoot. Disabling, or an app that asks for + nothing a consent does not already cover, at once. A release that newly asks while the app is enabled (awaitingRoot) + is asked for the same way (reconsent): the yes is setDeviceAppRelease's consentRoot alone — Update now —, which moves + the device to that release. graphql's refusal, in its words, goes to onRefused; a change made, to onChanged. */ export function useAppSwitch( { turn, setRelease }: Pick & Partial>, - onRefused?: (reason: string) => void, - onChanged?: (app: DeviceApp) => void + onRefused: ((reason: string) => void) | undefined, + onChanged: ((app: DeviceApp) => void) | undefined, + accountId: string | undefined // the device's account, whose catalogue names the release consented to ) { const { t } = useTranslation() const [asking, setAsking] = useState() @@ -94,7 +223,7 @@ export function useAppSwitch( } const flip = (app: DeviceApp, enabled: boolean) => { - if (enabled && app.root) setAsking(app) + if (enabled && needsConsent(app)) setAsking(app) else turn(app, enabled).then(done(app)) } @@ -102,12 +231,17 @@ export function useAppSwitch( // An enabled app held back for a release that runs as root: the yes moves it there. const waiting = (app?: DeviceApp) => !!app?.enabled && (!!app.awaitingRoot || app.heldBack?.reason === 'consent') const updating = waiting(asking) ? asking?.awaitingRoot || asking?.latest || '' : null + // The release the yes goes to: the one waiting for it (graphql's awaitingRoot, enabled or not). None for an app + // offered to the device: its own fields are what its release asks there. + const target = updating || asking?.awaitingRoot || null const consent = ( t('deviceApps.rootUpdateAction', 'Consent and update') : undefined} onConfirm={() => { const app = asking setAsking(undefined) @@ -121,3 +255,9 @@ export function useAppSwitch( return { flip, reconsent, consent } } + +/* Whether turning an app on asks the person's yes, as graphql decides it: a release waiting for one (awaitingRoot — + graphql names it, enabled or not, where what its release asks is not covered by the consent kept with it), or, for + one the device does not have yet (offered: no consent kept), a release that asks for one (asksConsent). */ +export const needsConsent = (app: Pick) => + !!app.awaitingRoot || (asksConsent(app) && !app.rootConsent) diff --git a/frontend/src/components/AppTerminal.test.tsx b/frontend/src/components/AppTerminal.test.tsx new file mode 100644 index 000000000..796ad46f9 --- /dev/null +++ b/frontend/src/components/AppTerminal.test.tsx @@ -0,0 +1,254 @@ +import React, { act } from 'react' +import { createRoot, Root } from 'react-dom/client' +import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest' + +const { apps, name, openTerminal, env } = vi.hoisted(() => ({ + apps: { value: {} as any }, + name: { value: 'pi-evan.on.remote.it' as string | undefined }, + openTerminal: vi.fn(), + env: { isNative: false }, +})) +// The device's apps as the API says them; which one a service belongs to is the portal's own rule (appsHelper). +// The release a consent names is read from its catalogue entry; none here: the app's own capabilities. +vi.mock('../services/graphQLAppCatalog', () => ({ graphQLCatalogApp: () => Promise.resolve('UNSERVED') })) +vi.mock('../hooks/useDeviceApps', async () => { + const { appServiceOf, isAppService, serviceApp } = await import('../helpers/appsHelper') + return { + useServiceApp: (device?: IDevice, service?: IService) => { + const read = device && isAppService(service) ? apps.value : {} + const app = serviceApp(read.apps, service) + return { ...read, app, appService: appServiceOf(app, service) } + }, + } +}) +vi.mock('../hooks/useLocalSubnetName', () => ({ + useSubnetName: (deviceId?: string) => (deviceId ? name.value : undefined), +})) +vi.mock('../helpers/terminalHelper', () => ({ openTerminal })) +vi.mock('../services/browser', () => ({ default: env, windowOpen: vi.fn() })) +vi.mock('./Confirm', () => ({ + Confirm: ({ open, title, children, onConfirm, onDeny }: any) => + open ? ( + + {title} {children} + + ) +} + +/** A service's row in its device's services: a terminal button while its app runs. */ +export const AppTerminalButton: React.FC<{ device: IDevice; service: IService }> = ({ device, service }) => { + const { t } = useTranslation() + const { app, appService } = useServiceApp(device, service) + const terminal = opensTerminal(app, appService) + const name = useSubnetName(terminal ? device.id : undefined) + const port = service.port + if (!app || !terminal || app.state !== 'running' || appService?.serviceId !== service.id || !name || !port) return null + return ( + { + // The row opens the service's page: the button is not the row. + event.stopPropagation() + open(app, service.id, name, port) + }} + /> + ) +} + +/** A service's connect panel, where its app opens a terminal (serving: useServiceApp, read by the panel): Open in web + * SSH while the app runs, whichever way the panel connects it — its name on this machine, the browser's client (where + * the panel's own terminal button is this too) or the proxy; otherwise what the app is doing — and, for those who may + * run code on the device (Manage and Scripting), turning it on, with their yes to its running as root + * (components/AppRootConsent). */ +export const AppTerminalOption: React.FC<{ device?: IDevice; service?: IService; serving: ServiceApp }> = ({ + device, + service, + serving: { app, appService, switching, turn, setRelease }, +}) => { + const { t } = useTranslation() + const terminal = opensTerminal(app, appService) + const name = useSubnetName(terminal ? device?.id : undefined) + const { flip, consent } = useAppSwitch({ turn, setRelease }, undefined, undefined, device?.accountId) + if (!app || !terminal || !name) return null + // Not where its product holds it off: graphql refuses that, naming the product. + const canTurnOn = + !app.locked && !!device?.permissions?.includes('MANAGE') && !!device?.permissions?.includes('SCRIPTING') + + const port = service?.port + if (app.state === 'running' && !switching) { + const serviceId = appService?.serviceId + if (!serviceId || !port) return null + return ( + + open(app, serviceId, name, port)}> + + {label(t)} + + + ) + } + + const status = switching + ? t('deviceApps.switching', 'Waiting for the device…') + : app.state === 'starting' + ? t('appTerminal.starting', '{{app}} is starting: web SSH opens it once it runs', { app: app.name }) + : app.state === 'unavailable' + ? t('deviceApps.unavailable', 'Not available here: {{detail}}', { detail: app.detail }) + : t('appTerminal.disabled', '{{app}} is disabled: enable it to open it in web SSH', { app: app.name }) + + return ( + + {status} + {app.state === 'disabled' && !switching && canTurnOn && ( + <> + {' '} + flip(app, true)}>{t('appTerminal.enable', 'Enable it')} + + )} + {consent} + + ) +} diff --git a/frontend/src/components/BrowserGatewayConnect.tsx b/frontend/src/components/BrowserGatewayConnect.tsx index a30525f8f..0a1e706ea 100644 --- a/frontend/src/components/BrowserGatewayConnect.tsx +++ b/frontend/src/components/BrowserGatewayConnect.tsx @@ -12,9 +12,10 @@ import { Icon } from './Icon' browser's remote.it client — nothing to install, and no connection to start. An SSH service opens a terminal in this app instead (pages/TerminalPage), its session through the same client — from the desktop app, in the web portal (helpers/terminalHelper). The counterpart of LocalSubnetConnect, - which is shown instead when an agent here does reach it. The console's plain ssh command is offered to copy as well: - it works from a machine signed in on its remote.it device app. */ -type Props = { name: string; terminal?: { port: number; title?: string; service?: string; console?: boolean } } + which is shown instead when an agent here does reach it. The plain ssh command of an app's service that signs people + in by certificate (byCertificate) is offered to copy as well: it works from a machine signed in on its remote.it + device app. */ +type Props = { name: string; terminal?: { port: number; title?: string; service?: string; byCertificate?: boolean } } export const BrowserGatewayConnect: React.FC = ({ name, terminal }) => { const { t } = useTranslation() @@ -57,14 +58,14 @@ export const BrowserGatewayConnect: React.FC = ({ name, terminal }) => { {t('browserGatewayConnect.failed', 'Could not open it: try again')} )} - {terminal?.console && ( + {terminal?.byCertificate && ( {sshCommand(name, terminal.port)} —{' '} {t('localSubnetConnect.sshHint', 'Works from a machine signed in on its remote.it device app')} )} - {terminal?.console && } + {terminal?.byCertificate && } - device?.services?.find(service => service.id === app.serviceId)?.port - -const ConsoleHostKey: React.FC = ({ app }) => { - const { t } = useTranslation() - const [hostKey, setHostKey] = useState(null) - const running = app.state === 'running' && app.serviceId - - useEffect(() => { - setHostKey(null) - if (!running || !app.serviceId) return - let current = true - graphQLSshHostKey(app.serviceId).then(key => current && setHostKey(key)) - return () => { - current = false - } - }, [running, app.serviceId]) - - if (!running || !hostKey) return null - return ( - - {t('deviceApps.hostKey', 'Host key {{key}}', { key: hostKey })} - - ) -} - -const ConsoleOpenTerminal: React.FC = ({ device, app }) => { - const { t } = useTranslation() - const name = useSubnetName(device.id) - const port = consolePort(device, app) - if (app.state !== 'running' || !name || !port || !app.serviceId) return null - return ( - - ) -} - -export const CONSOLE_APP: FirstPartyApp = { - icon: 'terminal', - state: (t, app) => - app.state === 'running' - ? t('deviceApps.consoleRunning', 'Running — logins by certificate, nothing listening on the device') - : app.state === 'disabled' - ? t('deviceApps.consoleDisabled', 'Disabled — a terminal on this device, from this app, by certificate') - : undefined, - settings: t => ({ - ai_commands: { - label: t('deviceApps.consoleAiCommands', 'Allow AI commands'), - help: t( - 'deviceApps.consoleAiCommandsHelp', - "AI assistants you authorize may run commands on this device's console through remote.it's MCP server. The device's administrator can turn this off on the machine." - ), - }, - }), - Lines: ConsoleHostKey, - Actions: ConsoleOpenTerminal, -} diff --git a/frontend/src/components/ConsoleTerminal.test.tsx b/frontend/src/components/ConsoleTerminal.test.tsx deleted file mode 100644 index 6708a01b6..000000000 --- a/frontend/src/components/ConsoleTerminal.test.tsx +++ /dev/null @@ -1,186 +0,0 @@ -import React, { act } from 'react' -import { createRoot, Root } from 'react-dom/client' -import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest' - -const { apps, name, openTerminal, env } = vi.hoisted(() => ({ - apps: { value: {} as any }, - name: { value: 'pi-evan.on.remote.it' as string | undefined }, - openTerminal: vi.fn(), - env: { isNative: false }, -})) -vi.mock('../hooks/useDeviceApps', () => ({ useDeviceApps: (deviceId?: string) => (deviceId ? apps.value : {}) })) -vi.mock('../hooks/useLocalSubnetName', () => ({ - useSubnetName: (deviceId?: string) => (deviceId ? name.value : undefined), -})) -vi.mock('../helpers/terminalHelper', () => ({ openTerminal })) -vi.mock('../services/browser', () => ({ default: env, windowOpen: vi.fn() })) -vi.mock('./Confirm', () => ({ - Confirm: ({ open, title, children, onConfirm, onDeny }: any) => - open ? ( - - {title} {children} - + ), +})) +vi.mock('./SelectSetting', () => ({ + SelectSetting: ({ value, values, disabled, helperText, onChange }: any) => ( +
+ {values.map((v: any) => ( +
+ ), +})) +vi.mock('react-i18next', () => ({ + useTranslation: () => ({ + t: (_key: string, text: string, values?: any) => text.replace(/{{(\w+)}}/g, (_, k) => values?.[k] ?? ''), + }), +})) + +import { DeviceAppSetting } from './DeviceAppSetting' +import type { DeviceAppSetting as Setting } from '../services/graphQLDeviceApps' +;(globalThis as any).IS_REACT_ACT_ENVIRONMENT = true + +// The console's "Allow AI commands" (forcible: its administrator may hold it on as well as off). +const aiCommands = (control: string, more: Partial = {}): Setting => ({ + name: 'ai_commands', + type: 'bool', + label: 'Allow AI commands', + help: 'Commands an AI runs on this device through MCP, as the people you allow', + default: true, + value: true, + at: null, + by: null, + onDevice: false, + control: control as any, + locked: null, + choices: null, + deprecated: null, + ...more, +}) + +async function render(setting: Setting, onChange = vi.fn()) { + const container = document.createElement('div') + await act(async () => + createRoot(container).render( + + ) + ) + return container +} +const row = (page: HTMLElement) => page.querySelector('[data-row]') as HTMLButtonElement + +describe('an app setting its device’s administrator holds', () => { + it('ai_commands held off: off, greyed, "Set by this device’s administrator" — no change offered', async () => { + const onChange = vi.fn() + const page = await render(aiCommands('off', { value: false }), onChange) + expect(row(page).dataset.on).toBe('false') + expect(row(page).disabled).toBe(true) + expect(row(page).textContent).toBe('Allow AI commands — Set by this device’s administrator') + await act(async () => row(page).click()) + expect(onChange).not.toHaveBeenCalled() + }) + + it('ai_commands held on: on, greyed, said the same', async () => { + const page = await render(aiCommands('on', { value: true })) + expect(row(page).dataset.on).toBe('true') + expect(row(page).disabled).toBe(true) + expect(row(page).textContent).toBe('Allow AI commands — Set by this device’s administrator') + }) + + it('held by its administrator and its product: both said', async () => { + const page = await render( + aiCommands('off', { value: false, locked: { product: 'Kiosks', level: 'enforced' } as any }) + ) + expect(row(page).textContent).toBe( + 'Allow AI commands — Set by this device’s administrator · Managed by product Kiosks (enforced)' + ) + }) + + it('not held: switched here, its help said; local is set on the device only; its product’s lock alone as before', async () => { + for (const control of ['cloud+local', 'cloud']) { + const onChange = vi.fn() + const page = await render(aiCommands(control), onChange) + expect(row(page).disabled).toBe(false) + expect(row(page).textContent).toBe( + 'Allow AI commands — Commands an AI runs on this device through MCP, as the people you allow' + ) + await act(async () => row(page).click()) + expect(onChange).toHaveBeenCalledWith(false) + } + const local = await render(aiCommands('local')) + expect(row(local).disabled).toBe(true) + expect(row(local).textContent).toBe('Allow AI commands — Set only on the device') + const product = await render(aiCommands('cloud+local', { locked: { product: 'Kiosks', level: 'synced' } as any })) + expect(row(product).disabled).toBe(true) + expect(row(product).textContent).toBe('Allow AI commands — Set by its product Kiosks') + }) + + it('a choice it fixes: that choice, greyed, said the same', async () => { + const mode: Setting = { + ...aiCommands('nightly'), + name: 'mode', + type: 'choice', + label: 'Back up', + help: null, + value: 'nightly', + default: 'hourly', + choices: [ + { value: 'hourly', label: 'Every hour' }, + { value: 'nightly', label: 'Every night' }, + ], + } + const page = await render(mode) + const select = page.querySelector('[data-select]') as HTMLElement + expect(select.dataset.value).toBe('nightly') + expect(select.dataset.disabled).toBe('true') + expect(select.textContent).toBe('Set by this device’s administrator') + const free = await render({ ...mode, control: 'cloud+local' as any }) + expect((free.querySelector('[data-select]') as HTMLElement).dataset.disabled).toBe('false') + }) +}) diff --git a/frontend/src/components/DeviceAppSetting.tsx b/frontend/src/components/DeviceAppSetting.tsx index 5db43c379..811ef1a7c 100644 --- a/frontend/src/components/DeviceAppSetting.tsx +++ b/frontend/src/components/DeviceAppSetting.tsx @@ -4,6 +4,7 @@ import { Button, ListItem, TextField } from '@mui/material' import type { TFunction } from 'i18next' import { AppStringRules, DeviceAppSetting as Setting } from '../services/graphQLDeviceApps' import { settingLocked } from '../services/graphQLDeviceSettings' +import { productLockNote } from '../helpers/productPolicyHelper' import { DeviceSettingChoice, DeviceSettingRow, deprecatedLine, settingNote } from './DeviceSettingRow' import { spacing } from '../styling' @@ -43,9 +44,25 @@ export const DeviceAppSetting: React.FC = props => { ) } +// Whether the device's administrator holds the setting (graphql's DeviceAppSetting.control, the device's +// `._control`): off, on (where its release says forcible, as the console's ai_commands) or a choice it fixes. +// The device applies the held value, and graphql refuses a change to it. +export const adminHolds = (setting: Setting) => + !!setting.control && !['cloud+local', 'cloud', 'local'].includes(setting.control) + +/* Why an app's setting is as it is, where that is not the portal's doing: held by the device's administrator — and by + its product too, where its product locks it — else what a device setting's row says (set only on the device, its + product's lock, a change made on the device). None for one set here. */ +export function appSettingNote(t: TFunction, setting: Setting): string | undefined { + if (!adminHolds(setting)) return settingNote(t, setting) + const held = t('deviceApps.settingAdminHeld', 'Set by this device’s administrator') + return setting.locked ? `${held} · ${productLockNote(t, setting.locked)}` : held +} + const AppSettingControl: React.FC = ({ setting, label, help, disabled, onChange }) => { const { t } = useTranslation() const deprecated = deprecatedLine(t, setting.deprecated) + const note = appSettingNote(t, setting) switch (setting.type) { case 'bool': @@ -55,7 +72,8 @@ const AppSettingControl: React.FC = ({ setting, label, help, disabled, on hideIcon disableGutters label={label} - subLabel={help} + subLabel={note || help} + quiet deprecated={setting.deprecated} disabled={disabled} onChange={onChange} @@ -71,6 +89,7 @@ const AppSettingControl: React.FC = ({ setting, label, help, disabled, on label={label} value={fixed ? setting.control : String(setting.value ?? '')} choices={choices} + why={note} note={deprecated || help || undefined} disabled={disabled} onChange={onChange} @@ -148,7 +167,7 @@ const AppSettingField: React.FC = ({ setting, label, help, disabled, onCh onChange(list ? listItems(text) : text) } - const note = [deprecatedLine(t, setting.deprecated), settingNote(t, setting) || help].filter(Boolean).join(' · ') + const note = [deprecatedLine(t, setting.deprecated), appSettingNote(t, setting) || help].filter(Boolean).join(' · ') const max = setting.type === 'string' ? setting.declaration?.string?.max : undefined return ( diff --git a/frontend/src/components/DeviceApps.test.tsx b/frontend/src/components/DeviceApps.test.tsx index 6349264c6..9c536a169 100644 --- a/frontend/src/components/DeviceApps.test.tsx +++ b/frontend/src/components/DeviceApps.test.tsx @@ -2,24 +2,22 @@ import React, { act } from 'react' import { createRoot, Root } from 'react-dom/client' import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest' -const { apps, hostKey, name, openTerminal, push } = vi.hoisted(() => ({ +const { apps, name, openTerminal, push } = vi.hoisted(() => ({ push: vi.fn(), apps: { value: {} as any }, - hostKey: vi.fn(), name: { value: 'pi-evan.on.remote.it' as string | undefined }, openTerminal: vi.fn(), })) +// The release a consent names is read from its catalogue entry; none here: the app's own capabilities. +vi.mock('../services/graphQLAppCatalog', () => ({ graphQLCatalogApp: () => Promise.resolve('UNSERVED') })) vi.mock('../services/post', () => ({ post: vi.fn() })) vi.mock('react-router-dom', () => ({ useHistory: () => ({ push }) })) vi.mock('../services/graphQL', () => ({ graphQLBasicRequest: vi.fn(), graphQLGetErrors: vi.fn() })) -vi.mock('../services/graphQLDeviceApps', async importOriginal => ({ - ...(await importOriginal()), - graphQLSshHostKey: hostKey, -})) vi.mock('../hooks/useDeviceApps', () => ({ useDeviceApps: () => apps.value })) vi.mock('../hooks/useDeviceSettings', () => ({ useDeviceSettings: () => ({ setting: () => undefined }) })) vi.mock('../hooks/useLocalSubnetName', () => ({ useSubnetName: () => name.value })) vi.mock('../helpers/terminalHelper', () => ({ openTerminal })) +vi.mock('../services/browser', () => ({ default: { isNative: false }, windowOpen: vi.fn() })) vi.mock('./Icon', () => ({ Icon: ({ name }: any) => (name ? : null) })) vi.mock('./Confirm', () => ({ Confirm: ({ open, title, action, children, onConfirm, onDeny }: any) => @@ -42,6 +40,7 @@ vi.mock('react-i18next', () => ({ import { DeviceApps } from './DeviceApps' import type { DeviceApp, DeviceAppSetting } from '../services/graphQLDeviceApps' +import { withServices } from '../test/deviceApps' ;(globalThis as any).IS_REACT_ACT_ENVIRONMENT = true const setting = (more: Partial = {}): DeviceAppSetting => ({ @@ -61,7 +60,8 @@ const setting = (more: Partial = {}): DeviceAppSetting => ({ ...more, }) -const consoleApp = (more: Partial = {}): DeviceApp => ({ +const consoleApp = (more: Partial = {}): DeviceApp => + withServices({ id: 'remoteit.console', name: 'Console', publisher: 'remote.it', @@ -72,11 +72,17 @@ const consoleApp = (more: Partial = {}): DeviceApp => ({ state: 'running', detail: null, serviceId: 'S1', + protocol: 'ssh', + capabilities: ['person-accounts', 'person-certificates', 'ssh-exec'], + hostKey: 'SHA256:abc', + sessions: [], + sessionsOpen: 0, settings: [setting()], ...more, -}) + }) -const backup = (more: Partial = {}): DeviceApp => ({ +const backup = (more: Partial = {}): DeviceApp => + withServices({ id: 'acme.backup', name: 'Backup', publisher: 'Acme', @@ -87,6 +93,11 @@ const backup = (more: Partial = {}): DeviceApp => ({ state: 'disabled', detail: null, serviceId: null, + protocol: null, + capabilities: [], + hostKey: null, + sessions: [], + sessionsOpen: 0, settings: [ setting({ name: 'mode', @@ -103,10 +114,18 @@ const backup = (more: Partial = {}): DeviceApp => ({ setting({ name: 'keep', type: 'int', label: 'Keep this many', help: null, default: 7, value: 7 }), ], ...more, -}) + }) const device = (permissions = ['VIEW', 'CONNECT', 'MANAGE', 'SCRIPTING']) => - ({ id: 'D1', name: 'Pi', permissions, services: [{ id: 'S1', port: 2222 }] } as unknown as IDevice) + ({ + id: 'D1', + name: 'Pi', + permissions, + services: [ + { id: 'S1', port: 2222 }, + { id: 'S3', port: 30022 }, + ], + } as unknown as IDevice) const turn = vi.fn() const setRelease = vi.fn() @@ -129,7 +148,6 @@ afterEach(() => { beforeEach(() => { turn.mockReset().mockResolvedValue(true) setSetting.mockReset().mockResolvedValue(true) - hostKey.mockReset().mockResolvedValue('SHA256:abc') openTerminal.mockReset() push.mockReset() name.value = 'pi-evan.on.remote.it' @@ -270,6 +288,38 @@ describe('the switch enables and disables', () => { expect(turn).toHaveBeenCalledWith(expect.objectContaining({ id: 'remoteit.console' }), true, true) }) + it('a restricted app that declares capabilities asks the yes to them first, in their words', async () => { + apps.value = { ...apps.value, apps: [backup({ capabilities: ['ssh-exec'] })] } + const page = await render() + await click(switchOf(appRow(page, 'acme.backup'))) + expect(turn).not.toHaveBeenCalled() + expect(page.querySelector('[data-confirm-title]')?.textContent).toBe('Allow Backup what it asks?') + expect(page.querySelector('[data-root-consent]')?.getAttribute('data-root-consent')).toBe('capabilities') + expect(page.querySelector('[data-confirm] [data-app-capability]')?.getAttribute('data-app-capability')).toBe('ssh-exec') + expect(page.querySelector('[data-confirm-ok]')?.textContent).toBe('Allow and turn on') + await click(page.querySelector('[data-confirm-ok]')) + expect(turn).toHaveBeenCalledWith(expect.objectContaining({ id: 'acme.backup' }), true, true) + }) + + it('a consent kept that covers its release (none awaited): turned on at once; one awaited asks again', async () => { + const consent = { by: 'U1', email: null, at: '2026-11-10T00:00:00Z', version: '1.4.0', via: 'person' } + apps.value = { ...apps.value, apps: [consoleApp({ enabled: false, state: 'disabled', rootConsent: consent })] } + let page = await render() + await click(switchOf(appRow(page, 'remoteit.console'))) + expect(page.querySelector('[data-confirm]')).toBeNull() + expect(turn).toHaveBeenCalledWith(expect.objectContaining({ id: 'remoteit.console' }), true) + act(() => root.unmount()) + turn.mockClear() + apps.value = { + ...apps.value, + apps: [consoleApp({ enabled: false, state: 'disabled', rootConsent: consent, awaitingRoot: '1.5.0' })], + } + page = await render() + await click(switchOf(appRow(page, 'remoteit.console'))) + expect(turn).not.toHaveBeenCalled() + expect(page.querySelector('[data-confirm-title]')?.textContent).toBe('Run Console as root?') + }) + it('a restricted app at once; any app disabled at once', async () => { const page = await render() await click(switchOf(appRow(page, 'acme.backup'))) @@ -292,13 +342,64 @@ describe('the switch enables and disables', () => { }) }) -describe('the console’s Open terminal stays in its row', () => { - it('while it runs, through its service’s port; no other app has it', async () => { +describe('drawn from what the API says, none by its id', () => { + // Anyone's app whose service is ssh and that signs people in by certificate. + const shell = consoleApp({ + id: 'acme.shell', + name: 'Shell', + publisher: 'Acme', + root: false, + serviceId: 'S3', + capabilities: ['person-certificates'], + }) + + it('Open terminal in the row of any app whose service is ssh and that declares person-certificates, while it runs', async () => { + apps.value.apps = [ + shell, + backup(), + consoleApp({ id: 'acme.web', serviceId: 'S1', protocol: 'https', capabilities: [] }), + ] + const page = await render() + await click(appRow(page, 'acme.shell').querySelector('[data-app-terminal]')) + expect(openTerminal).toHaveBeenCalledWith({ + name: 'pi-evan.on.remote.it', + port: 30022, + title: 'Shell', + service: 'S3', + }) + expect(appRow(page, 'acme.backup').querySelector('[data-app-terminal]')).toBeNull() + expect(appRow(page, 'acme.web').querySelector('[data-app-terminal]')).toBeNull() + }) + + it('the console as any such app: Open terminal through its service’s port', async () => { + const page = await render() + await click(appRow(page, 'remoteit.console').querySelector('[data-app-terminal]')) + expect(openTerminal).toHaveBeenCalledWith({ + name: 'pi-evan.on.remote.it', + port: 2222, + title: 'Console', + service: 'S1', + }) + }) + + it('no Open terminal while it does not run, or without a name in device subnets', async () => { + apps.value.apps = [{ ...shell, state: 'starting' }] + let page = await render() + expect(page.querySelector('[data-app-terminal]')).toBeNull() + act(() => root.unmount()) + container.remove() + apps.value.apps = [shell] + name.value = undefined + page = await render() + expect(page.querySelector('[data-app-terminal]')).toBeNull() + }) + + it('its icon from how its service opens', async () => { + apps.value.apps = [shell, backup(), consoleApp({ id: 'acme.web', protocol: 'https' })] const page = await render() - const button = [...appRow(page, 'remoteit.console').querySelectorAll('button')].find(b => b.textContent === 'Open terminal') - await click(button!) - expect(openTerminal).toHaveBeenCalledWith(expect.objectContaining({ name: 'pi-evan.on.remote.it', port: 2222, service: 'S1' })) - expect(appRow(page, 'acme.backup').textContent).not.toContain('Open terminal') + expect(appRow(page, 'acme.shell').querySelector('[data-icon="terminal"]')).not.toBeNull() + expect(appRow(page, 'acme.web').querySelector('[data-icon="globe"]')).not.toBeNull() + expect(appRow(page, 'acme.backup').querySelector('[data-icon="cube"]')).not.toBeNull() }) }) diff --git a/frontend/src/components/DeviceApps.tsx b/frontend/src/components/DeviceApps.tsx index c2728cc52..c969a276b 100644 --- a/frontend/src/components/DeviceApps.tsx +++ b/frontend/src/components/DeviceApps.tsx @@ -14,19 +14,30 @@ import { Typography, } from '@mui/material' import { useHistory } from 'react-router-dom' -import { DeviceApp, SCREENVIEW } from '../services/graphQLDeviceApps' +import { DeviceApp, DeviceAppService, SCREENVIEW } from '../services/graphQLDeviceApps' import { useDeviceApps } from '../hooks/useDeviceApps' import { useAppSwitch } from './AppRootConsent' -import { firstPartyApp } from './firstPartyApps' -import { adminLine, adminRefuses, heldBackLine, managedLine, offered, runsAsWord, stateWord } from '../helpers/appsHelper' +import { AppTerminalAction } from './AppTerminal' +import { + adminLine, + adminRefuses, + appIcon, + heldBackLine, + managedLine, + offered, + openWord, + runsAsWord, + stateWord, +} from '../helpers/appsHelper' import { Notice } from './Notice' import { Icon } from './Icon' /* A device's apps on its Configure page (presence-server docs/device-apps-design.md, "The Apps pages", the device's Apps section): the device's own apps, a row each — its publisher, Runs as root or Restricted, the version it runs, its state in a word, held back where it is —, its Enabled switch, and the row opening the app on this device - (/devices/:deviceID/apps/:appID), where its settings, channel, pin and Remove are. The console's Open terminal stays - in its row. Add opens the catalogue for this device (/devices/:deviceID/apps/add), offered only where there is + (/devices/:deviceID/apps/:appID), where its settings, channel, pin and Remove are. Every app is drawn from what the + API says of it, none by its id: its icon from how its service opens, and Open terminal in its row for one whose + service is ssh and that signs people in by certificate (components/AppTerminal). Add opens the catalogue for this device (/devices/:deviceID/apps/add), offered only where there is something it can add. Enabling runs code on the device, so it needs Scripting as well as Manage, and a root release no consent covers asks @@ -40,11 +51,14 @@ import { Icon } from './Icon' export const DeviceApps: React.FC<{ device: IDevice }> = ({ device }) => { const { t } = useTranslation() const history = useHistory() - const deviceApps = useDeviceApps(device.id) + const deviceApps = useDeviceApps(device.id, { accountId: device.accountId }) const { apps, available, switching } = deviceApps const [refusal, setRefusal] = useState() - const { flip, consent } = useAppSwitch(deviceApps, reason => - setRefusal(reason || t('apps.notChanged', 'The app was not changed.')) + const { flip, consent } = useAppSwitch( + deviceApps, + reason => setRefusal(reason || t('apps.notChanged', 'The app was not changed.')), + undefined, + device.accountId ) const canManage = !!device.permissions?.includes('MANAGE') const canRun = canManage && !!device.permissions?.includes('SCRIPTING') @@ -118,13 +132,12 @@ export const DeviceApps: React.FC<{ device: IDevice }> = ({ device }) => { )} {apps.map(app => { - const own = firstPartyApp(app.id) const removing = app.state === 'removing' const enabled = switching === app.id ? !app.enabled : app.enabled const row = ( <> - + = ({ device }) => { /> ) - // The switch and the console's Open terminal act alone: a click on them is not the row's. + // The switch and Open terminal act alone: a click on them is not the row's. const actions = removing ? null : ( event.stopPropagation()}> - {own?.Actions && } + {app.services.map(service => ( + + ))} = ({ device }) => { ) } -/* Open, for any app reached as a service (serviceId) while it runs: its service's connection, started and launched as - its application type launches — HTTP opens in the browser —, as any service's Connect page does. remote.it's own apps - with a part of their own (components/firstPartyApps: the console's Open terminal) have theirs instead. */ -export const AppOpen: React.FC<{ device: IDevice; app: DeviceApp }> = ({ device, app }) => { +/* Open, for one of an app's services while the app runs and the service is served (serviceId): its connection, + started and launched as its application type launches (graphql makes the type from the manifest's protocol: http and + https open in the browser, vnc and rdp in a viewer, udp nothing: a port for the person's own UDP client), as any + service's Connect page does — a multi-port service's on its first port, its launch port; said by its protocol (Open + page, Open screen, Connect). One that opens as a terminal (helpers/sshHelper opensTerminal) has Open terminal + instead (components/AppTerminal). */ +export const AppOpen: React.FC<{ device: IDevice; app: DeviceApp; service: DeviceAppService }> = ({ + device, + app, + service, +}) => { const { t } = useTranslation() const history = useHistory() - if (!app.enabled || app.state !== 'running' || !app.serviceId) return null + if (!app.enabled || app.state !== 'running' || !service.serviceId) return null return ( ) } diff --git a/frontend/src/components/DeviceSettingRow.tsx b/frontend/src/components/DeviceSettingRow.tsx index 04ebb47da..43b27bb5f 100644 --- a/frontend/src/components/DeviceSettingRow.tsx +++ b/frontend/src/components/DeviceSettingRow.tsx @@ -88,14 +88,17 @@ export const DeviceSettingChoice: React.FC<{ value: string // the value standing, as the setting's control fixes it choices: ISelect[] note?: React.ReactNode // the setting's state, below who set it + why?: string // who set it, or why it is fixed, in the caller's words (an app's setting); else a device setting's disabled?: boolean onChange: (value: string) => void -}> = ({ setting, icon, hideIcon, label, value, choices, note, disabled, onChange }) => { +}> = ({ setting, icon, hideIcon, label, value, choices, note, why: said, disabled, onChange }) => { const { t } = useTranslation() const fixed = choices.find(choice => choice.key === setting.control) - const why = fixed - ? t('deviceSetting.controlFixedTo', "Set to {{value}} by the device's administrator", { value: fixed.name }) - : settingNote(t, setting) + const why = + said ?? + (fixed + ? t('deviceSetting.controlFixedTo', "Set to {{value}} by the device's administrator", { value: fixed.name }) + : settingNote(t, setting)) return ( : port 443 on a name is the host's web service, under the stage's certificate, whatever port it is on (presence-server docs/subnet-https.md) — and that URL is what is shown and copied, since : is the service's own port, plain http. An SSH service is shown and copied as - the command that reaches it, plain `ssh`: the console's works as it is from a machine signed in on its remote.it - device app, which gets a certificate for its own ssh (connectd remoteit-device ssh-config). A multi-port + the command that reaches it, plain `ssh`: that of an app signing people in by certificate (byCertificate) works as it + is from a machine signed in on its remote.it device app, which gets a certificate for its own ssh (connectd + remoteit-device ssh-config), and says so. A multi-port service is reached here on every port it lists, each by its own number (graphql-api docs/MULTI-PORT-SERVICES.md), so they are all shown; what is copied and launched is the first, as for a connection. A web service whose device passed its redirect to https:// on the same host back to the browser (services/graphQLDetectedScheme redirectLoops) would only loop on its name: Launch says so first, and the way out is its type, HTTPS on the port it redirects to. */ -type Props = { local: LocalSubnetName; service?: IService; connection?: IConnection } +type Props = { local: LocalSubnetName; service?: IService; connection?: IConnection; byCertificate?: boolean } -export const LocalSubnetConnect: React.FC = ({ local, service, connection }) => { +export const LocalSubnetConnect: React.FC = ({ local, service, connection, byCertificate }) => { const { t } = useTranslation() const port = service?.port const ssh = service?.typeID === 28 @@ -118,7 +119,7 @@ export const LocalSubnetConnect: React.FC = ({ local, service, connection {t('localSubnetConnect.address', 'resolves here to {{address}}', { address: local.address })}
)} - {isConsoleService(service) && ( + {byCertificate && ( {t('localSubnetConnect.sshHint', 'Works from a machine signed in on its remote.it device app')} diff --git a/frontend/src/components/ProductPolicyApps.test.tsx b/frontend/src/components/ProductPolicyApps.test.tsx index 1a12c1bf0..7ff05beb0 100644 --- a/frontend/src/components/ProductPolicyApps.test.tsx +++ b/frontend/src/components/ProductPolicyApps.test.tsx @@ -2,7 +2,9 @@ import React, { act } from 'react' import { createRoot, Root } from 'react-dom/client' import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest' -const { setApp, setAppSetting } = vi.hoisted(() => ({ setApp: vi.fn(), setAppSetting: vi.fn() })) +const { setApp, setAppSetting, catalog } = vi.hoisted(() => ({ setApp: vi.fn(), setAppSetting: vi.fn(), catalog: vi.fn() })) +// The release a consent names is read from its catalogue entry; unserved by default: the app's own. +vi.mock('../services/graphQLAppCatalog', () => ({ graphQLCatalogApp: catalog })) vi.mock('../services/post', () => ({ post: vi.fn() })) vi.mock('../services/graphQL', () => ({ graphQLGetErrors: vi.fn(), @@ -39,12 +41,12 @@ vi.mock('./SelectSetting', () => ({ vi.mock('./Icon', () => ({ Icon: ({ name }: any) => (name ? : null) })) vi.mock('./Notice', () => ({ Notice: ({ children }: any) =>
{children}
})) vi.mock('./Confirm', () => ({ - Confirm: ({ open, title, action, children, onConfirm, onDeny }: any) => + Confirm: ({ open, title, action, children, disabled, onConfirm, onDeny }: any) => open ? (
{title} {children} - {!done && ( - )} {app.enabled && app.heldBack?.reason === 'pinned' && !held && ( - )} @@ -256,7 +303,7 @@ export const DeviceAppPage: React.FC = () => { variant="standard" value={app.channel ?? ''} disabled={runLocked || !!saving} - onChange={e => e.target.value !== (app.channel ?? '') && release('channel', { channel: e.target.value })} + onChange={e => e.target.value !== (app.channel ?? '') && move('channel', { channel: e.target.value })} SelectProps={{ native: true }} inputProps={{ 'data-app-channel': true, 'aria-label': t('apps.channel', 'Channel') }} > @@ -275,7 +322,7 @@ export const DeviceAppPage: React.FC = () => { variant="standard" value={app.pinned ?? ''} disabled={runLocked || !!saving} - onChange={e => e.target.value !== (app.pinned ?? '') && pin(e.target.value)} + onChange={e => e.target.value !== (app.pinned ?? '') && move('pin', { version: e.target.value })} SelectProps={{ native: true }} inputProps={{ 'data-app-pin': true, 'aria-label': t('apps.pin', 'Pin') }} > @@ -288,20 +335,108 @@ export const DeviceAppPage: React.FC = () => { )} - {app.serviceId && !gone && ( - - - - {service - ? t('apps.serviceLine', '{{name}} · port {{port}}', { name: service.name, port: service.port }) - : app.name} + {shown.map((served, index) => { + const service = device.services?.find(s => s.id === served.serviceId) + // Its ports as the device's service has them, as every connection to it reads them (a port setting's change + // reads the device again: hooks/useDeviceApps). + const list = service?.ports ?? (service ? [String(service.port)] : []) + const several = served.multiPort || list.length > 1 || !!list[0]?.includes('-') + const own = [...ports].filter(([, port]) => port.service === served) + return ( + + + + {several + ? t('apps.serviceLinePorts', '{{name}} · ports {{ports}}', { + name: service?.name ?? served.name, + ports: formatPorts(list), + }) + : !list.length + ? served.name + : served.protocol === 'udp' + ? t('apps.serviceLineUdp', '{{name}} · UDP port {{port}}', { + name: service?.name ?? served.name, + port: list[0], + }) + : t('apps.serviceLine', '{{name}} · port {{port}}', { name: service?.name ?? served.name, port: list[0] })} + + {/* A connection reaches its first port, the launch port; the rest by name on the device subnet + (graphql-api docs/MULTI-PORT-SERVICES.md, "Clients: address mode only"). */} + {several && list.length > 0 && ( + + {t('multiPort.firstPortOnly', 'This connection reaches port {{port}} only.', { + port: firstPortOf(list[0]), + })}{' '} + {t('multiPort.subnetReachesAll', 'All its ports, {{ports}}, are reached by name on the device subnet.', { + ports: formatPorts(list), + })} + + )} + {index === 0 && app.hostKey && ( + + {t('deviceApps.hostKey', 'Host key {{key}}', { key: app.hostKey })} + + )} + {own.map(([name, port]) => { + const setting = app.settings.find(s => s.name === name) + if (!setting) return null + return ( + + change(name, () => setSetting(app, name, value))} + /> + + ) + })} + + {app.enabled && + (opensTerminal(app, served) ? ( + + ) : ( + + ))} + + ) + })} + {app.enabled && !gone && app.sessionsOpen > 0 && ( + + + + {t('apps.sessionsOpen', '{{number}} open now', { number: app.sessionsOpen })} - {own?.Lines && } + {canManage && + app.sessions.map(session => ( + + {sessionLine(t, session)} + + ))} + {canManage && app.sessions.length > 0 && app.sessionsOpen > app.sessions.length && ( + + {t('apps.sessionsMore', '{{number}} more not listed', { + number: app.sessionsOpen - app.sessions.length, + })} + + )} - {app.enabled && (own?.Actions ? : )} )} - {!app.serviceId && !app.enabled && !gone && catalog && catalog.serves !== 'none' && ( + {!app.serviceId && !app.enabled && !gone && catalog?.protocol && ( {t('apps.serviceStopped', 'Stopped while the app is disabled: enable it to open it')} @@ -320,8 +455,8 @@ export const DeviceAppPage: React.FC = () => { change(setting.name, () => setSetting(app, setting.name, value))} onClear={ @@ -399,14 +534,22 @@ export const DeviceAppPage: React.FC = () => { )} {consent} + moving?.values.version + ? root + ? t('apps.pinRootAction', 'Pin with full control') + : t('apps.pinAsksAction', 'Allow and pin') + : t('deviceApps.rootUpdateAction', 'Consent and update') + } onConfirm={() => { - const version = pinning - setPinning(undefined) - if (version) release('pin', { version, consentRoot: true }) + const move = moving + setMoving(undefined) + if (move) release(move.key, { ...move.values, consentRoot: true }) }} - onDeny={() => setPinning(undefined)} + onDeny={() => setMoving(undefined)} /> { } // One line of the page: its label, then what it says and its controls. +/* The settings that are a service's ports, each with the words it is edited under there: a service of one port's + (portSetting), the port people connect to; a listener's, where it listens — a multi-port service's ports are its + listeners' own, so each is named by its listener. */ +function portSettingsOf(t: TFunction, service: DeviceAppService): [string, { service: DeviceAppService; label: string }][] { + const out: [string, { service: DeviceAppService; label: string }][] = [] + if (service.portSetting) out.push([service.portSetting, { service, label: t('apps.servicePort', 'Port people connect to') }]) + for (const listener of service.listeners) { + if (!listener.portSetting || out.some(([name]) => name === listener.portSetting)) continue + const label = listener.name + ? t('apps.listenerPort', 'Port of {{listener}}', { listener: listener.name }) + : t('apps.listenPort', 'Port it listens on') + out.push([listener.portSetting, { service, label }]) + } + return out +} + const Row: React.FC<{ label: string; data: string; top?: boolean; children: React.ReactNode }> = ({ label, data, @@ -453,6 +612,19 @@ const Row: React.FC<{ label: string; data: string; top?: boolean; children: Reac ) +// A session it serves, as the app reports it: the session (its id's first characters), as whom on the device, by an AI +// where one opened it, and since when. Never who: an app knows a session, not a person. +function sessionLine(t: TFunction, session: DeviceApp['sessions'][number]): string { + return [ + t('apps.sessionId', 'Session {{id}}', { id: session.session.slice(0, 8) }), + session.login && t('apps.sessionAs', 'as {{login}}', { login: session.login }), + session.via === 'ai' && t('apps.sessionByAi', 'by an AI'), + session.since && t('apps.sessionSince', 'since {{when}}', { when: when(session.since) }), + ] + .filter(Boolean) + .join(' · ') +} + // What it runs against what it is offered: "1.4.0 running · 1.4.0 offered on stable · up to date". function versionLine(t: TFunction, app: DeviceApp, channel: string): string { // Running only where the device says it runs: one it holds but does not run (turned off or kept disabled by its diff --git a/frontend/src/pages/DevicePage.tsx b/frontend/src/pages/DevicePage.tsx index 7f60ef797..f9f7f1c8d 100644 --- a/frontend/src/pages/DevicePage.tsx +++ b/frontend/src/pages/DevicePage.tsx @@ -8,8 +8,7 @@ import { DeviceTagEditor } from '../components/DeviceTagEditor' import { AddServiceButton } from '../buttons/AddServiceButton' import { ListItemLocation } from '../components/ListItemLocation' import { ServiceMiniState } from '../components/ServiceMiniState' -import { ConsoleTerminalButton } from '../components/ConsoleTerminal' -import { isConsoleService } from '../helpers/sshHelper' +import { AppTerminalButton } from '../components/AppTerminal' import { useLocation, useHistory } from 'react-router-dom' import { useDispatch, useSelector } from 'react-redux' import { selectDeviceModelAttributes } from '../selectors/devices' @@ -246,7 +245,7 @@ export const DevicePage: React.FC = () => { {hold.product && hold.services.includes(s.id) && } - {isConsoleService(s) && } + ) diff --git a/frontend/src/pages/ProductsPage/ProductPolicyPage.tsx b/frontend/src/pages/ProductsPage/ProductPolicyPage.tsx index ab10b4039..7bf31c2b9 100644 --- a/frontend/src/pages/ProductsPage/ProductPolicyPage.tsx +++ b/frontend/src/pages/ProductsPage/ProductPolicyPage.tsx @@ -29,7 +29,7 @@ export const ProductPolicyPage: React.FC = () => { const product = products.find(p => p.id === productId) const accountId = useSelector(selectActiveAccountId) const manage = useSelector(selectPermissions).includes('ADMIN') - const { served, policy, reload } = useProductPolicy(productId) + const { served, policy, reload, accountId: readUnder } = useProductPolicy(productId) if (!product) return @@ -76,6 +76,7 @@ export const ProductPolicyPage: React.FC = () => { {policy.apps && ( { ) : 'ERROR' const account = own === 'ERROR' ? null : own?.data?.data?.sshAccount - // The host key the device reports for its console: one that matches is let through, another refused. + // The host key the device reports for the app serving it (graphql sshHostKey): one that matches is let through, + // another refused. const expectedHostKey: string = (own === 'ERROR' ? null : own?.data?.data?.sshHostKey) || '' if (account) term.write(`login as: ${account}\r\n`) const user = account || (await readLine('login as: ', true)).trim() diff --git a/frontend/src/pages/ThisDevicePage.test.tsx b/frontend/src/pages/ThisDevicePage.test.tsx index a5343b771..c5adad2a3 100644 --- a/frontend/src/pages/ThisDevicePage.test.tsx +++ b/frontend/src/pages/ThisDevicePage.test.tsx @@ -12,7 +12,11 @@ vi.mock('react-i18next', () => ({ vi.mock('../components/Container', () => ({ Container: ({ children }: any) =>
{children}
})) vi.mock('../hooks/useThisDevice', () => ({ useThisDevice: () => null })) vi.mock('../components/ThisDeviceSignIn', () => ({ ThisDeviceSignIn: () => null })) -const { usage } = vi.hoisted(() => ({ usage: vi.fn() })) +const { usage, deviceApps } = vi.hoisted(() => ({ usage: vi.fn(), deviceApps: vi.fn() })) +// The device's apps as the API says them, the device read by its UID: their words and whether each serves a service. +vi.mock('../hooks/useDeviceApps', () => ({ + useDeviceApps: (uid?: string) => ({ apps: uid ? deviceApps(uid) : undefined }), +})) vi.mock('../services/transferUsage', () => ({ fetchTransferUsage: usage, UNSUPPORTED: 'UNSUPPORTED' })) vi.mock('../helpers/dateHelper', async importOriginal => ({ ...(await importOriginal()), @@ -592,8 +596,18 @@ describe('This device has what Settings has', () => { expect(container.querySelector('[data-section="settings"] [data-setting="printers"]')).toBeNull() }) + // The console as the API gives it: named, its setting labelled by its release, its service ssh. + const consoleApp = { + id: 'remoteit.console', + name: 'Console', + protocol: 'ssh', + settings: [{ name: 'ai_commands', label: 'Allow AI commands' }], + } + it('what the device offers: reasons, a change replaced, the relay in use, and what is not served', async () => { + deviceApps.mockReturnValue([consoleApp]) const { container } = await render({ capabilities: caps, status, settings }, { part: 'advanced' }) + expect(deviceApps).toHaveBeenCalledWith('80:00:00:00:01:0A:BC:DE') const row = (name: string) => container.querySelector(`[data-section="settings"] [data-setting="${name}"]`)! expect(row('exit_node').textContent).toContain('Turned off by this machine’s administrator') expect((row('exit_node').querySelector('input') as HTMLInputElement).disabled).toBe(true) @@ -642,7 +656,8 @@ describe('This device has what Settings has', () => { expect(row('acme.files').textContent).toContain('Running — Kept by this device’s administrator, though its release was withdrawn 1.2.0') }) - it('the console’s AI commands: an option of the console’s row, set by the console’s key', async () => { + it('an app’s settings — the console’s AI commands — options of its row, in the API’s words, set by their keys', async () => { + deviceApps.mockReturnValue([consoleApp]) const { container, bridge } = await render({ capabilities: caps, status, settings }, { part: 'advanced' }) const rows = [...container.querySelectorAll('[data-section="settings"] [data-setting]')] const at = rows.findIndex(r => r.getAttribute('data-setting') === 'remoteit.console') @@ -657,6 +672,22 @@ describe('This device has what Settings has', () => { ]) }) + it('an app the API does not name: said by its names, its options still under it, and not said to need the services', async () => { + deviceApps.mockReturnValue(null) + const apps = [ + ...settings.filter(s => !s.name.startsWith('remoteit.console')), + { name: 'acme.shell', value: true, source: 'cloud' as const, app: { state: 'running', version: '1.0.0' } }, + { name: 'acme.shell.colour', value: true, source: 'default' as const }, + ] + const { container } = await render({ capabilities: caps, status, settings: apps }, { part: 'advanced' }) + const rows = [...container.querySelectorAll('[data-section="settings"] [data-setting]')] + const at = rows.findIndex(r => r.getAttribute('data-setting') === 'acme.shell') + expect(rows[at].textContent).toContain('acme.shell') + expect(rows[at].textContent).not.toContain('Not served') + expect(rows[at + 1].getAttribute('data-setting')).toBe('acme.shell.colour') + expect(getComputedStyle(rows[at + 1] as HTMLElement).paddingLeft).toBe('32px') + }) + it('the detailed connection logging, and the app’s own Open at login', async () => { const { container, bridge } = await render( { capabilities: caps, status, settings, app: { openAtLogin: { on: true } } }, diff --git a/frontend/src/services/__fixtures__/appCatalogMock.ts b/frontend/src/services/__fixtures__/appCatalogMock.ts index c1a4870e4..530511e4d 100644 --- a/frontend/src/services/__fixtures__/appCatalogMock.ts +++ b/frontend/src/services/__fixtures__/appCatalogMock.ts @@ -73,8 +73,9 @@ export type MockCatalogApp = { publisher: typeof PUBLISHER_REMOTEIT runsAs: string root: boolean - kind: string - serves: string + capabilities: string[] + protocol: string | null + contract: number | null platforms: string[] version: string | null accountChannel: string | null @@ -84,6 +85,8 @@ export type MockCatalogApp = { created: string notes: string | null root: boolean + capabilities: string[] + protocol: string | null platforms: string[] withdrawn: string | null channels: string[] @@ -125,8 +128,9 @@ export const MOCK_CATALOG: MockCatalogApp[] = [ publisher: PUBLISHER_REMOTEIT, runsAs: 'root', root: true, - kind: 'binary', - serves: 'inetd', + capabilities: ['person-accounts', 'person-certificates', 'ssh-exec'], + protocol: 'ssh', + contract: 1, platforms: ['linux-amd64', 'linux-arm64', 'darwin-arm64', 'windows-amd64'], version: '1.4.0', accountChannel: null, @@ -140,6 +144,8 @@ export const MOCK_CATALOG: MockCatalogApp[] = [ created: '2026-11-10T18:00:00.000Z', notes: 'Detached commands keep running when the browser closes.', root: true, + capabilities: ['person-accounts', 'person-certificates', 'ssh-exec'], + protocol: 'ssh', platforms: ['linux-amd64', 'linux-arm64', 'darwin-arm64', 'windows-amd64'], withdrawn: null, channels: ['beta'], @@ -149,6 +155,8 @@ export const MOCK_CATALOG: MockCatalogApp[] = [ created: '2026-11-01T18:00:00.000Z', notes: 'AI commands are a setting of their own.', root: true, + capabilities: ['person-accounts', 'person-certificates', 'ssh-exec'], + protocol: 'ssh', platforms: ['linux-amd64', 'linux-arm64', 'darwin-arm64', 'windows-amd64'], withdrawn: null, channels: ['stable'], @@ -164,8 +172,9 @@ export const MOCK_CATALOG: MockCatalogApp[] = [ publisher: PUBLISHER_REMOTEIT, runsAs: 'restricted', root: false, - kind: 'binary', - serves: 'socket', + capabilities: [], + protocol: 'https', + contract: 1, platforms: ['linux-amd64', 'linux-arm64'], version: '1.2.0', accountChannel: null, @@ -176,6 +185,8 @@ export const MOCK_CATALOG: MockCatalogApp[] = [ created: '2026-10-28T18:00:00.000Z', notes: null, root: false, + capabilities: [], + protocol: 'https', platforms: ['linux-amd64', 'linux-arm64'], withdrawn: null, channels: ['stable'], @@ -191,8 +202,9 @@ export const MOCK_CATALOG: MockCatalogApp[] = [ publisher: PUBLISHER_ACME, runsAs: 'restricted', root: false, - kind: 'binary', - serves: 'none', + capabilities: [], + protocol: null, + contract: 1, platforms: ['linux-amd64', 'linux-arm64', 'linux-arm64-musl'], version: '1.4.0', accountChannel: 'stable', @@ -206,6 +218,8 @@ export const MOCK_CATALOG: MockCatalogApp[] = [ created: '2026-11-12T18:00:00.000Z', notes: 'Adds S3-compatible targets.\nA bucket on any S3-compatible service can be the target.', root: false, + capabilities: [], + protocol: null, platforms: ['linux-amd64', 'linux-arm64', 'linux-arm64-musl'], withdrawn: null, channels: ['beta'], @@ -215,6 +229,8 @@ export const MOCK_CATALOG: MockCatalogApp[] = [ created: '2026-11-01T18:00:00.000Z', notes: 'Fixes the retry after a lost connection.', root: false, + capabilities: [], + protocol: null, platforms: ['linux-amd64', 'linux-arm64', 'linux-arm64-musl'], withdrawn: null, channels: ['stable'], @@ -224,6 +240,8 @@ export const MOCK_CATALOG: MockCatalogApp[] = [ created: '2026-10-20T18:00:00.000Z', notes: null, root: false, + capabilities: [], + protocol: null, platforms: ['linux-amd64', 'linux-arm64'], withdrawn: '2026-10-25T18:00:00.000Z', channels: [], diff --git a/frontend/src/services/deviceAppsShared.ts b/frontend/src/services/deviceAppsShared.ts index 3054777ff..ace0a5f47 100644 --- a/frontend/src/services/deviceAppsShared.ts +++ b/frontend/src/services/deviceAppsShared.ts @@ -8,6 +8,12 @@ export type AppChange = T | Refused export const refused = (result: unknown): result is Refused => !!result && typeof result === 'object' && 'reason' in result && typeof (result as Refused).reason === 'string' +// A choice as its owner sees it (label) and as the app gets it (value). The manifest's string shorthand is both, so a +// choice graphql gives as a string, or without a label, is labelled by its value. +export type AppSettingChoice = { value: string; label: string } +export const choiceOf = (choice: any): AppSettingChoice => + typeof choice === 'string' ? { value: choice, label: choice } : { value: choice.value, label: choice.label || choice.value } + // What graphql says of a release a device's remote.it is too old to run — restricted, a script or bundle, one served on // a socket — where it is enabled: its state unavailable, this its detail. export const NEEDS_NEWER = 'Needs a newer remote.it on this device' diff --git a/frontend/src/services/graphQLAppCatalog.test.ts b/frontend/src/services/graphQLAppCatalog.test.ts index 11be4a4d4..a14cc2815 100644 --- a/frontend/src/services/graphQLAppCatalog.test.ts +++ b/frontend/src/services/graphQLAppCatalog.test.ts @@ -80,14 +80,22 @@ describe('the catalogue, where graphql serves it', () => { ) const app = await graphQLCatalogApp('acme.backup', { heldBack: true, heldBackReason: 'daemon' }) const { query, variables } = post.mock.calls[1][0] - expect(query).toContain('releases(first: $releases) { version created notes root platforms withdrawn channels }') + expect(query).toContain( + 'releases(first: $releases) { version created notes root capabilities protocol contract platforms withdrawn channels }' + ) + // Contract 1: how its service opens and the contract it is written to; no kind or serves (run and listen are the + // daemon's to read). + expect(query).toMatch(/runsAs root capabilities protocol contract platforms/) + expect(query).not.toMatch(/\bkind\b|\bserves\b/) expect(query).toContain('devices(first: 100, after: $after, heldBack: $heldBack, heldBackReason: $heldBackReason, version: $version)') expect(query).toContain('heldBackBy { reason count }') expect(query).toContain('heldBack { reason detail }') expect(variables).toMatchObject({ id: 'acme.backup', heldBack: true, heldBackReason: 'daemon', releases: 20 }) expect(app).toMatchObject({ channels: [{ channel: 'beta', current: '1.5.0', candidate: '1.5.1', share: 10 }], - releases: [{ version: '1.5.0', notes: 'Adds S3' }], + releases: [{ version: '1.5.0', notes: 'Adds S3', capabilities: [], protocol: null }], + capabilities: [], + protocol: null, fleet: { total: 1, heldBack: 1, heldBackBy: [{ reason: 'daemon', count: 1 }] }, devices: { total: 1, items: [{ deviceId: 'D1', heldBack: { reason: 'daemon', detail: 'x' }, pinned: null }] }, }) diff --git a/frontend/src/services/graphQLAppCatalog.ts b/frontend/src/services/graphQLAppCatalog.ts index 8c9901b3b..fcb325c3f 100644 --- a/frontend/src/services/graphQLAppCatalog.ts +++ b/frontend/src/services/graphQLAppCatalog.ts @@ -1,6 +1,7 @@ import { post } from './post' import { graphQLGetErrors, graphQLRequestWithReason } from './graphQL' import type { AppHeldBack, AppChange } from './deviceAppsShared' +import type { AppCapability, AppProtocol } from './graphQLDeviceApps' /* The account's app catalogue (presence-server docs/device-apps-design.md, "Lifecycle: add, disable, remove", API, and "The Apps pages"): every app the account may take — remote.it's, its own publisher's —, each with its publisher, how @@ -26,6 +27,9 @@ export type CatalogAppRelease = { created: string notes: string | null // its manifest's notes, as its publisher signed them root: boolean + capabilities: (AppCapability | string)[] // what it asks of the platform beyond an ordinary app's + protocol: AppProtocol | string | null // how its service opens; none for one that serves nothing + contract: number | null // the app contract its manifest is written to (1); none for one from before contracts platforms: string[] withdrawn: string | null channels: string[] // where this stage points at it: "stable", "beta", "beta candidate" @@ -67,8 +71,9 @@ export type CatalogApp = { publisher: CatalogAppPublisher runsAs: string // restricted | root, of version root: boolean - kind: string // binary | script | bundle - serves: string // inetd | socket | none + capabilities: (AppCapability | string)[] // of version, as root is + protocol: AppProtocol | string | null // of version: how its service opens, none for one that serves nothing + contract: number | null // of version platforms: string[] // version's archive keys version: string | null // the release the account's channel gives here; none: none here yet accountChannel: string | null // none: stable @@ -110,10 +115,11 @@ export function resetAppCatalog() { const PUBLISHER = 'publisher { id name verifiedDomain remoteit own }' const FLEET_COUNTS = 'total enabled disabled upToDate heldBack versions { version count }' -const BASE = `id name description ${PUBLISHER} runsAs root kind serves platforms version accountChannel` +const BASE = `id name description ${PUBLISHER} runsAs root capabilities protocol contract platforms version accountChannel` const LIST = `${BASE} fleet { ${FLEET_COUNTS} }` const ONE = `${BASE} fleet { ${FLEET_COUNTS} heldBackBy { reason count } }` -const RELEASES = 'releases(first: $releases) { version created notes root platforms withdrawn channels }' +const RELEASES = + 'releases(first: $releases) { version created notes root capabilities protocol contract platforms withdrawn channels }' const CHANNELS = 'channels { channel current candidate share }' const DEVICE = 'deviceId name enabled state detail version release latest channel pinned upToDate heldBack { reason detail }' const DEVICES = `devices(first: 100, after: $after, heldBack: $heldBack, heldBackReason: $heldBackReason, version: $version) { items { ${DEVICE} } total next }` @@ -160,8 +166,9 @@ export const catalogAppOf = (app: any): CatalogApp => ({ publisher: publisherOf(app.publisher), runsAs: app.runsAs ?? (app.root ? 'root' : 'restricted'), root: !!app.root, - kind: app.kind ?? 'binary', - serves: app.serves ?? 'none', + capabilities: app.capabilities ?? [], + protocol: app.protocol ?? null, + contract: app.contract ?? null, platforms: app.platforms ?? [], version: app.version ?? null, accountChannel: app.accountChannel ?? null, @@ -176,6 +183,9 @@ export const catalogAppOf = (app: any): CatalogApp => ({ created: r.created, notes: r.notes ?? null, root: !!r.root, + capabilities: r.capabilities ?? [], + protocol: r.protocol ?? null, + contract: r.contract ?? null, platforms: r.platforms ?? [], withdrawn: r.withdrawn ?? null, channels: r.channels ?? [], diff --git a/frontend/src/services/graphQLDeviceApps.test.ts b/frontend/src/services/graphQLDeviceApps.test.ts index 2f775660f..3bb8924ba 100644 --- a/frontend/src/services/graphQLDeviceApps.test.ts +++ b/frontend/src/services/graphQLDeviceApps.test.ts @@ -79,13 +79,87 @@ describe('Device.apps', () => { expect(query).toContain( 'settings { name type label help default value at by onDevice control locked { product level } deprecated choices { value label } declaration }' ) - // The console's host key and port are not the app's: its own extras ask them (components/ConsoleApp). - expect(query).not.toMatch(/hostKey|port|\bon\b/) + // What draws any app, none by its id: the contract it is written to, how its service opens, what it asks of + // remote.it, the key its service presents, the sessions it serves, what it serves at runtime, and the setting + // that is its service's port. + for (const field of ['contract', 'protocol', 'capabilities', 'hostKey', 'sessionsOpen', 'features', 'portSetting']) + expect(query).toMatch(new RegExp(`\\b${field}\\b`)) + // A session as the app reports it: never a person. + expect(query).toContain('sessions { session login via since }') + expect(query).not.toMatch(/\bperson\b/) + // Its services, the primary first, each with its listeners and its service on the device; where its named listeners + // listen. An app's own port is never asked: a service's is. + const services = + 'services { key name protocol multiPort port portSetting listeners { name type port portSetting ports } serviceId }' + expect(query).toContain(`${services} listeners { name listen }`) + expect(query.replace(services, '')).not.toMatch(/\bport\b|\bon\b/) expect(query).toContain('heldBack { reason detail }') expect(apps?.[0].settings[0].value).toBe(true) expect(apps?.[0].adminControl).toBe('cloud+local') // none said: the default }) + it('how its service opens, what it asks of remote.it, its host key and sessions, as graphql says them', async () => { + const session = { + session: '9f2c1e', + login: 'r3-evan', + via: 'ai', + since: '2026-11-15T10:00:00.000Z', + } + const shell = { + ...consoleApp, + id: 'acme.shell', + protocol: 'ssh', + capabilities: ['person-certificates'], + hostKey: 'SHA256:abc', + sessions: [session, { session: 'k2' }], + sessionsOpen: 40, + contract: 1, + features: ['remoteit-commands@remote.it'], + portSetting: 'port', + } + post.mockResolvedValue( + answer({ login: { device: [{ id: 'D1', apps: [shell, { ...consoleApp, id: 'acme.files' }] }] } }) + ) + const [app, files] = (await graphQLDeviceApps('D1'))! + expect(app).toMatchObject({ + protocol: 'ssh', + capabilities: ['person-certificates'], + hostKey: 'SHA256:abc', + sessionsOpen: 40, + contract: 1, + features: ['remoteit-commands@remote.it'], + portSetting: 'port', + }) + expect(app.sessions).toEqual([session, { session: 'k2', login: null, via: null, since: null }]) + // None said: none, and an app that serves nothing. + expect(files).toMatchObject({ + contract: null, + protocol: null, + capabilities: [], + hostKey: null, + sessions: [], + sessionsOpen: 0, + features: [], + portSetting: null, + }) + }) + + it('a choice as its owner sees it and the app gets it: its label, its value; the shorthand labelled by its value', async () => { + const mode = { + ...aiCommands, + name: 'root_login', + type: 'choice', + choices: [{ value: 'prohibit-password', label: 'Keys only' }, { value: ':0', label: null }, ':1'], + } + post.mockResolvedValue(answer({ login: { device: [{ id: 'D1', apps: [{ ...consoleApp, settings: [mode] }] }] } })) + const [app] = (await graphQLDeviceApps('D1'))! + expect(app.settings[0].choices).toEqual([ + { value: 'prohibit-password', label: 'Keys only' }, + { value: ':0', label: ':0' }, + { value: ':1', label: ':1' }, + ]) + }) + it('its administrator’s control as graphql says it', async () => { post.mockResolvedValue(answer({ login: { device: [{ id: 'D1', apps: [{ ...consoleApp, adminControl: 'local' }] }] } })) expect((await graphQLDeviceApps('D1'))?.[0].adminControl).toBe('local') @@ -135,7 +209,7 @@ describe('Device.apps', () => { ) const apps = (await graphQLDeviceApps('D1'))! expect(post.mock.calls[0][0].query).toMatch( - /serviceId problems \{ name error detail } settings \{[^}]*\{[^}]*}[^}]*\{[^}]*} declaration } locked \{ product level }/ + /sessionsOpen features portSetting services \{[^}]*\{[^}]*}[^}]*} listeners \{ name listen } problems \{ name error detail } settings \{[^}]*\{[^}]*}[^}]*\{[^}]*} declaration } locked \{ product level }/ ) expect(apps[0].locked).toEqual({ product: 'Acme', level: 'enforced' }) expect(apps[1].locked).toBeNull() @@ -283,9 +357,12 @@ describe('build step 5: what a device may add, and a remote.it too old', () => { ) expect(await graphQLAvailableApps('D1')).toEqual([ { id: 'remoteit.files', name: 'Files', publisher: 'remote.it', publisherVerifiedDomain: null, description: null, root: false, version: '1.0.0', refused: null, adminControl: 'cloud+local', needsNewer: true, oldInstall: false, - conversion: null, conversionDetail: null }, + conversion: null, conversionDetail: null, protocol: null, capabilities: [], contract: null, services: [] }, ]) - expect(post.mock.calls[0][0].query).toContain('availableApps { id name publisher publisherVerifiedDomain description root version refused adminControl needsNewer oldInstall conversion conversionDetail }') + expect(post.mock.calls[0][0].query).toContain('availableApps { id name publisher publisherVerifiedDomain description root version refused adminControl needsNewer oldInstall conversion conversionDetail protocol capabilities contract services { key name protocol multiPort port portSetting listeners { name type port portSetting ports } } }') + // How its service opens and what it asks of remote.it, of the release its stage gives. + post.mockResolvedValue(answer({ login: { device: [{ availableApps: [{ id: 'acme.shell', name: 'Shell', publisher: 'Acme', protocol: 'ssh', capabilities: ['person-certificates'], contract: 1 }] }] } })) + expect((await graphQLAvailableApps('D1'))[0]).toMatchObject({ protocol: 'ssh', capabilities: ['person-certificates'], contract: 1 }) // Its administrator's control, where it says one (none said: the default). post.mockResolvedValue(answer({ login: { device: [{ availableApps: [{ id: 'remoteit.files', name: 'Files', publisher: 'remote.it', adminControl: 'local' }] }] } })) expect((await graphQLAvailableApps('D1'))[0].adminControl).toBe('local') @@ -293,6 +370,28 @@ describe('build step 5: what a device may add, and a remote.it too old', () => { expect(await graphQLAvailableApps('D1')).toEqual([]) }) + it('its services, the primary first: each its listeners and, while served, its service on the device', async () => { + const services = [ + { key: null, name: 'Camera', protocol: 'http', multiPort: false, port: null, portSetting: 'web_port', + listeners: [{ name: 'web', type: 'tcp', port: null, portSetting: 'web_port', ports: null }], serviceId: 'S1' }, + { key: 'rtsp', name: 'Stream', protocol: 'tcp', multiPort: true, + listeners: [{ name: 'rtsp', type: 'tcp', port: 8554 }, { name: 'rtp', type: 'udp', ports: '5004-5005' }], serviceId: 'S2' }, + ] + post.mockResolvedValue(answer({ login: { device: [{ apps: [{ ...consoleApp, services, listeners: [{ name: 'web', listen: 'tcp:8080' }] }] }] } })) + const [app] = (await graphQLDeviceApps('D1'))! + expect(app.services).toEqual([ + services[0], + { ...services[1], port: null, portSetting: null, listeners: [ + { name: 'rtsp', type: 'tcp', port: 8554, portSetting: null, ports: null }, + { name: 'rtp', type: 'udp', port: null, portSetting: null, ports: '5004-5005' }, + ] }, + ]) + expect(app.listeners).toEqual([{ name: 'web', listen: 'tcp:8080' }]) + // An app that serves nothing: none. + post.mockResolvedValue(answer({ login: { device: [{ apps: [consoleApp] }] } })) + expect((await graphQLDeviceApps('D1'))![0].services).toEqual([]) + }) + it('a setting\'s declaration is read, for a string\'s max and pattern', async () => { post.mockResolvedValue(answer({ login: { device: [{ apps: [{ ...consoleApp, settings: [{ ...aiCommands, declaration: { string: { max: 8, pattern: null } } }] }] }] } })) const [app] = (await graphQLDeviceApps('D1'))! diff --git a/frontend/src/services/graphQLDeviceApps.ts b/frontend/src/services/graphQLDeviceApps.ts index 1e3e3eaeb..d7d51a1e1 100644 --- a/frontend/src/services/graphQLDeviceApps.ts +++ b/frontend/src/services/graphQLDeviceApps.ts @@ -2,21 +2,26 @@ import { post } from './post' import { graphQLBasicRequest, graphQLGetErrors, graphQLRequestWithReason } from './graphQL' import type { SettingState } from './graphQLDeviceSettings' import { appPolicyFields, settingLockOf, SettingLock } from './productPolicy' -import { AppChange, AppHeldBack, refused } from './deviceAppsShared' +import { AppChange, AppHeldBack, AppSettingChoice, choiceOf, refused } from './deviceAppsShared' export { NEEDS_NEWER, needsNewer, refused } from './deviceAppsShared' export type { AppChange, AppHeldBack, AppHeldBackReason, Refused } from './deviceAppsShared' /* A device's apps (presence-server docs/device-apps-design.md, "The portal's Apps section"): each a catalogue entry - (`.`, the console `remoteit.console`) the device has a row for — enabled or disabled, its channel, the version - installed there, whether it runs as root, and its state as the device says: disabled, starting, running, unavailable - with why, or removing. Its settings are declared by the app's release and set with the same version rule as a device setting: + (`.`) the device has a row for — enabled or disabled, its channel, the version installed there, + whether it runs as root, and its state as the device says: disabled, starting, running, unavailable with why, or + removing. Its settings are declared by the app's release and set with the same version rule as a device setting: who set each from which side, its administrator's control (`._control`) and its product's lock. Whether it is on may be its product's too (locked), where the API says: graphql refuses a change to either, naming the - product. graphql's Device.apps, the lifecycle's mutations and setDeviceAppSetting. */ + product. graphql's Device.apps, the lifecycle's mutations and setDeviceAppSetting. -export const CONSOLE = 'remoteit.console' -// ScreenView as an app (build step 9): root, served on its socket as a type-48 service. + Every app is drawn from what the API says of it, none by its id (remoteit/apps docs/contract.md, contract 1): how its + service opens (protocol), what it asks of the platform beyond an ordinary app (capabilities), the key its service + presents (hostKey), the sessions it serves and what it serves at runtime (features), all from its manifest and its + own status.json as its device reports them. */ + +// ScreenView's old install (build step 9), and only that: what becomes of a type-48 service installed before ScreenView +// was an app (oldInstall, conversion). The app itself is drawn as any other. export const SCREENVIEW = 'remoteit.screenview' /* An app's state on its device (presence-server docs/device-apps-design.md, "Lifecycle: add, disable, remove"): disabled @@ -31,11 +36,63 @@ export type DeviceAppState = 'disabled' | 'starting' | 'running' | 'unavailable' or remove. */ export type AppAdminControl = 'cloud+local' | 'cloud' | 'local' | 'off' +/* How the portal opens an app's service (its manifest's service.protocol): ssh a terminal, http and https a page, vnc + and rdp a viewer, tcp as its service's type launches, udp as a connection alone — a port for the person's own UDP + client, never a terminal or a page. None for an app that serves nothing (no listen, or no service). */ +export type AppProtocol = 'ssh' | 'http' | 'https' | 'vnc' | 'rdp' | 'tcp' | 'udp' + +/* What an app asks of the platform beyond an ordinary app's (its manifest's capabilities; self-contained-apps.md, + "Capabilities, as the platform keeps them"): people's own accounts kept on the device while it is enabled + (person-accounts), people signed in to its service by remote.it certificate (person-certificates), and AI commands + run through it (ssh-exec). The list is open: one this portal does not know is shown by its name. */ +export type AppCapability = 'person-accounts' | 'person-certificates' | 'ssh-exec' + +/* One of an app's listeners, as its release declares it (remoteit/apps docs/contract.md, listen as a map of named + listeners): where the app listens on the device. Its port pinned, the owner's (portSetting: the setting whose value + it is), a range it binds (ports, "low-high"), or none where remote.it picks it or it has none (unix, stdio). */ +export type AppListener = { + name: string | null // none for an app with one listener + type: string // tcp, udp, unix or stdio + port: number | null + portSetting: string | null + ports: string | null +} + +/* One of an app's services (graphql's DeviceAppService), the primary first — the app's single-service fields + (serviceId, protocol, portSetting) are the primary's. key: none for the primary, else its first listener's name. A + multi-port service's ports are its listeners' own, in their order, the first its launch port; one of one port has a + port (or portSetting, the owner's). serviceId: the service on the device, while the app is enabled and the service + served — where it listens is that service's (IDevice.services: its port and ports), as every connection to it reads + it. */ +export type DeviceAppService = { + key: string | null + name: string + protocol: AppProtocol | string | null + multiPort: boolean + port: number | null + portSetting: string | null + listeners: AppListener[] + serviceId: string | null +} + +// Where one of an app's named listeners listens, as the device reports it while the app runs: tcp:, +// udp:, a range (tcp:-, udp:-), unix or stdio. +export type DeviceAppListener = { name: string; listen: string } + +// A session the app serves, as it reports it in its status.json: the session id (remote.it's, from the identity line +// or ${remoteit.session}), the account on the device where it knows one, "ai" where an AI opened it, and since when. +// Never a person: who is behind a session is remote.it's to know, not an app's. +export type DeviceAppSession = { + session: string + login: string | null + via: string | null + since: string | null +} // The declaration's types; the list is open, so one this portal does not know is shown and left alone. export type AppSettingType = 'bool' | 'choice' | 'int' | 'string' | 'list' -export type AppSettingChoice = { value: string; label: string } +export type { AppSettingChoice } from './deviceAppsShared' // A string's rules, and a list item's: at most max characters, and the whole value matching pattern where there is one. export type AppStringRules = { max: number; pattern: string | null } @@ -93,6 +150,18 @@ export type DeviceApp = { state: DeviceAppState detail: string | null serviceId: string | null // the service it is reached as + contract?: number | null // the app contract its release is written to (1) + protocol: AppProtocol | string | null // how its service opens; none for one that serves nothing + capabilities: (AppCapability | string)[] + hostKey: string | null // the key its service presents, as the app reports it (an OpenSSH or TLS SHA-256 fingerprint) + sessions: DeviceAppSession[] // the open ones the app lists, for those who manage it + sessionsOpen: number // how many are open + features?: string[] // what it says it serves at runtime (remoteit-commands@remote.it) + // The setting whose value is its service's port (service.port "${setting.X}"): the owner chooses the port there, and + // graphql keeps the service in step — edited in one place, the setting. + portSetting?: string | null + services: DeviceAppService[] // its services, the primary first; none for an app that serves nothing + listeners?: DeviceAppListener[] // where its named listeners listen, as the device reports it while it runs locked?: SettingLock | null // enabled or disabled as its product holds it: a synced or enforced product that sets it rootConsent?: DeviceAppRootConsent | null // the consent to root it runs under, where the API says // A newer release that newly runs as root, waiting for a consent: the device stays on the version it runs until @@ -136,7 +205,13 @@ export const rootConsentOf = (consent: any): DeviceAppRootConsent | null => const SETTING_FIELDS = 'name type label help default value at by onDevice control locked { product level } deprecated choices { value label } declaration' // The lifecycle's fields (enabled, added, latest, upToDate, heldBack, grantUntil) as the design pins them. -const FIELDS = `id name publisher publisherVerifiedDomain oldInstall conversion conversionDetail root enabled added channel pinned version release latest upToDate heldBack { reason detail } grantUntil adminControl state detail serviceId problems { name error detail } settings { ${SETTING_FIELDS} }` +const SESSION_FIELDS = 'session login via since' +// An app's services as its release declares them (AppService), and which of the device's services each is +// (DeviceAppService). +const DECLARED_SERVICE_FIELDS = + 'key name protocol multiPort port portSetting listeners { name type port portSetting ports }' +const SERVICE_FIELDS = `${DECLARED_SERVICE_FIELDS} serviceId` +const FIELDS = `id name publisher publisherVerifiedDomain oldInstall conversion conversionDetail root enabled added channel pinned version release latest upToDate heldBack { reason detail } grantUntil adminControl state detail serviceId contract protocol capabilities hostKey sessions { ${SESSION_FIELDS} } sessionsOpen features portSetting services { ${SERVICE_FIELDS} } listeners { name listen } problems { name error detail } settings { ${SETTING_FIELDS} }` // A setting as read: its value the declared default where none was set, and its lock only where it names a product. function parsedSetting(setting: any): DeviceAppSetting { @@ -144,32 +219,64 @@ function parsedSetting(setting: any): DeviceAppSetting { ...setting, value: setting.value ?? setting.default ?? null, locked: setting.locked?.product || setting.locked?.level ? setting.locked : null, - choices: setting.choices ?? null, + choices: setting.choices ? setting.choices.map(choiceOf) : null, deprecated: setting.deprecated ?? null, declaration: setting.declaration ?? null, } } -export const parsedDeviceApp = (app: any): DeviceApp => ({ - ...app, - enabled: !!app.enabled, - added: app.added ?? null, - pinned: app.pinned ?? null, - release: app.release ?? null, - latest: app.latest ?? null, - upToDate: !!app.upToDate, - heldBack: app.heldBack?.reason ? { reason: app.heldBack.reason, detail: app.heldBack.detail ?? '' } : null, - grantUntil: app.grantUntil ?? null, - adminControl: app.adminControl ?? 'cloud+local', - locked: app.locked?.product || app.locked?.level ? settingLockOf(app.locked) : null, - rootConsent: rootConsentOf(app.rootConsent), - awaitingRoot: app.awaitingRoot ?? null, - problems: app.problems ?? [], - conversion: conversionOf(app.conversion), - conversionDetail: app.conversionDetail ?? null, - settings: (app.settings ?? []).map(parsedSetting), +const parsedService = (service: any): DeviceAppService => ({ + key: service.key ?? null, + name: service.name, + protocol: service.protocol ?? null, + multiPort: !!service.multiPort, + port: service.port ?? null, + portSetting: service.portSetting ?? null, + listeners: (service.listeners ?? []).map((listener: any) => ({ + name: listener.name ?? null, + type: listener.type, + port: listener.port ?? null, + portSetting: listener.portSetting ?? null, + ports: listener.ports ?? null, + })), + serviceId: service.serviceId ?? null, }) +export const parsedDeviceApp = (app: any): DeviceApp => ({ + ...app, + enabled: !!app.enabled, + added: app.added ?? null, + pinned: app.pinned ?? null, + release: app.release ?? null, + latest: app.latest ?? null, + upToDate: !!app.upToDate, + heldBack: app.heldBack?.reason ? { reason: app.heldBack.reason, detail: app.heldBack.detail ?? '' } : null, + grantUntil: app.grantUntil ?? null, + adminControl: app.adminControl ?? 'cloud+local', + locked: app.locked?.product || app.locked?.level ? settingLockOf(app.locked) : null, + rootConsent: rootConsentOf(app.rootConsent), + awaitingRoot: app.awaitingRoot ?? null, + problems: app.problems ?? [], + conversion: conversionOf(app.conversion), + conversionDetail: app.conversionDetail ?? null, + contract: app.contract ?? null, + protocol: app.protocol ?? null, + capabilities: app.capabilities ?? [], + hostKey: app.hostKey ?? null, + sessions: (app.sessions ?? []).map((session: any) => ({ + session: session.session, + login: session.login ?? null, + via: session.via ?? null, + since: session.since ?? null, + })), + sessionsOpen: app.sessionsOpen ?? app.sessions?.length ?? 0, + features: app.features ?? [], + portSetting: app.portSetting ?? null, + services: (app.services ?? []).map(parsedService), + listeners: app.listeners ?? [], + settings: (app.settings ?? []).map(parsedSetting), + }) + // An app's fields, with its product's lock and its root consent where the API has them. const appFields = async () => [FIELDS, await appPolicyFields()].filter(Boolean).join(' ') @@ -187,7 +294,8 @@ export async function graphQLDeviceApps(deviceId: string): Promise { - const query = `query AvailableApps($id: [String!]!) { login { device(id: $id) { id availableApps { id name publisher publisherVerifiedDomain description root version refused adminControl needsNewer oldInstall conversion conversionDetail } } } }` + const query = `query AvailableApps($id: [String!]!) { login { device(id: $id) { id availableApps { id name publisher publisherVerifiedDomain description root version refused adminControl needsNewer oldInstall conversion conversionDetail protocol capabilities contract services { ${DECLARED_SERVICE_FIELDS} } } } } }` const variables = { id: [deviceId] } const response = await post({ query, variables }) if (response === 'ERROR') return [] @@ -222,6 +335,10 @@ export async function graphQLAvailableApps(deviceId: string): Promise { - const response = await graphQLBasicRequest( - ` query SshHostKey($serviceId: String!) { - sshHostKey(serviceId: $serviceId) - }`, - { serviceId }, - true - ) - return response === 'ERROR' ? null : response?.data?.data?.sshHostKey ?? null -} diff --git a/frontend/src/services/productPolicy.test.ts b/frontend/src/services/productPolicy.test.ts index c6d402f01..bb2ffcc68 100644 --- a/frontend/src/services/productPolicy.test.ts +++ b/frontend/src/services/productPolicy.test.ts @@ -684,17 +684,50 @@ describe('product apps', () => { 'apps { id name publisher description root version state channel pinned rootConsent { by at version } needsConsent locked at by settings { name type label help default value at by forcible locked deprecated choices { value label } } }' ) expect(call.query).not.toContain('declaration') - // An API from before consents named their person, releases waiting for root, or removed settings: none of them. + // An API from before consents named their person, releases waiting for root, removed settings, or what an app asks + // of remote.it and how its service opens: none of them. + expect(call.query).not.toMatch(/capabilities|protocol/) expect(policy.apps).toEqual([ { ...consoleApp, rootConsent: { ...consoleApp.rootConsent, email: null }, awaitingRoot: null, removedSettings: [], + capabilities: [], + protocol: null, }, ]) }) + it('where the API has them: what an app asks of remote.it and how its service opens', async () => { + const schema = { + ...APPS, + DeviceProductApp: { + ...APPS.DeviceProductApp, + capabilities: { type: nonNull(list(nonNull(scalar()))) }, + protocol: { type: scalar() }, + }, + } + serve(schema, () => ({ + login: { + account: { + deviceProducts: { + items: [ + { + id: 'P1', + sync: 'synced', + apps: [{ ...consoleApp, capabilities: ['person-certificates'], protocol: 'ssh' }], + }, + ], + }, + }, + }, + })) + const [app] = ((await graphQLProductPolicy('P1')) as any).apps + expect(asked(request.mock.calls.length - 1).query).toContain('root capabilities protocol version') + expect(app).toMatchObject({ capabilities: ['person-certificates'], protocol: 'ssh' }) + }) + it('where the API has them: the consent’s person, a release waiting for root, and removed settings with the release that removed them', async () => { const schema = { ...APPS, diff --git a/frontend/src/services/productPolicy.ts b/frontend/src/services/productPolicy.ts index 08f2cd04e..24b20fdca 100644 --- a/frontend/src/services/productPolicy.ts +++ b/frontend/src/services/productPolicy.ts @@ -1,6 +1,7 @@ import { post } from './post' import { graphQLGetErrors, graphQLRequestWithReason } from './graphQL' import type { NetworkDeviceRole } from './graphQLDeviceNetworks' +import { choiceOf } from './deviceAppsShared' /* Product policy for Control Link devices (graphql-api docs/PROXY-GROUPS.md §11, "Wave 4: product policy"). A product holds settings and grants — networks, proxies, tags — and a sync level that says what its devices get of them: @@ -104,6 +105,8 @@ export type ProductApp = { publisher: string description: string | null root: boolean // the release its devices are given runs as root + capabilities: string[] // what that release asks of remote.it beyond running, where the API says + protocol: string | null // how its service opens, where the API says version: string | null // the release this stage gives on its channel, or its pin; null none here yet state: ProductAppState | null // null unset: each device's own channel: string | null @@ -429,6 +432,8 @@ const APP: Want = { publisher: true, description: true, root: true, + capabilities: true, + protocol: true, version: true, state: true, channel: true, @@ -449,6 +454,8 @@ export const productAppOf = (app: any): ProductApp => ({ publisher: app.publisher ?? '', description: app.description ?? null, root: !!app.root, + capabilities: app.capabilities ?? [], + protocol: app.protocol ?? null, version: app.version ?? null, state: PRODUCT_APP_STATES.includes(app.state) ? app.state : null, channel: app.channel ?? null, @@ -479,7 +486,7 @@ export const productAppOf = (app: any): ProductApp => ({ forcible: !!setting.forcible, locked: !!setting.locked, deprecated: setting.deprecated ?? null, - choices: setting.choices ?? null, + choices: setting.choices ? setting.choices.map(choiceOf) : null, }) ), removedSettings: (app.removedSettings || []).map( diff --git a/frontend/src/test/deviceApps.ts b/frontend/src/test/deviceApps.ts new file mode 100644 index 000000000..291d73810 --- /dev/null +++ b/frontend/src/test/deviceApps.ts @@ -0,0 +1,19 @@ +import type { DeviceApp, DeviceAppService } from '../services/graphQLDeviceApps' + +/* A test app's services as graphql gives them where its fixture names none: its one service, the primary, from its + single-service fields (serviceId, protocol, portSetting) — none for an app that serves nothing. */ +export function withServices(app: Omit & { services?: DeviceAppService[] }): DeviceApp { + if (app.services) return app as DeviceApp + const serves = !!app.serviceId || !!app.protocol + const primary: DeviceAppService = { + key: null, + name: app.name, + protocol: app.protocol, + multiPort: false, + port: null, + portSetting: app.portSetting ?? null, + listeners: [], + serviceId: app.serviceId, + } + return { ...app, services: serves ? [primary] : [] } +}