diff --git a/frontend/src/buttons/ServiceConnectButton.tsx b/frontend/src/buttons/ServiceConnectButton.tsx index 8f96f9be3..5206cc7c0 100644 --- a/frontend/src/buttons/ServiceConnectButton.tsx +++ b/frontend/src/buttons/ServiceConnectButton.tsx @@ -39,7 +39,7 @@ export const ServiceConnectButton: React.FC = () => { // 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) + 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. diff --git a/frontend/src/components/AppTerminal.test.tsx b/frontend/src/components/AppTerminal.test.tsx index 768d88f9a..796ad46f9 100644 --- a/frontend/src/components/AppTerminal.test.tsx +++ b/frontend/src/components/AppTerminal.test.tsx @@ -12,11 +12,12 @@ const { apps, name, openTerminal, env } = vi.hoisted(() => ({ // 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 { isAppService, serviceApp } = await import('../helpers/appsHelper') + const { appServiceOf, isAppService, serviceApp } = await import('../helpers/appsHelper') return { useServiceApp: (device?: IDevice, service?: IService) => { const read = device && isAppService(service) ? apps.value : {} - return { ...read, app: serviceApp(read.apps, service) } + const app = serviceApp(read.apps, service) + return { ...read, app, appService: appServiceOf(app, service) } }, } }) @@ -48,6 +49,7 @@ vi.mock('react-i18next', () => ({ import { AppTerminalAction, AppTerminalButton, AppTerminalOption } from './AppTerminal' import { useServiceApp } from '../hooks/useDeviceApps' import type { DeviceApp } from '../services/graphQLDeviceApps' +import { withServices } from '../test/deviceApps' ;(globalThis as any).IS_REACT_ACT_ENVIRONMENT = true // Any app whose service is ssh and that signs people in by certificate: not the console, nor named anywhere. @@ -55,7 +57,8 @@ const shellService = { id: 'S1', name: 'Shell', typeID: 28, host: 'remoteit-app- const sshService = { id: 'S2', name: 'SSH', typeID: 28, host: 'localhost', port: 22 } as IService const device = (permissions = ['CONNECT', 'MANAGE', 'SCRIPTING']) => ({ id: 'D1', name: 'Pi', permissions, services: [shellService, sshService] } as unknown as IDevice) -const app = (state: string, extra: Partial = {}): DeviceApp => ({ +const app = (state: string, extra: Partial = {}): DeviceApp => + withServices({ id: 'acme.shell', name: 'Shell', publisher: 'Acme', @@ -74,7 +77,7 @@ const app = (state: string, extra: Partial = {}): DeviceApp => ({ version: null, settings: [], ...extra, -}) + }) const turn = vi.fn() let root: Root @@ -232,7 +235,8 @@ describe('AppTerminalButton — the service’s row in the device’s services', describe('AppTerminalAction — Open terminal in the device’s Apps', () => { it('while it runs, through its service’s port; nothing for an app that opens no terminal', async () => { - let container = await render() + const action = (shell: DeviceApp) => + let container = await render(action(app('running'))) await click(container.querySelector('[data-app-terminal]')) expect(openTerminal).toHaveBeenCalledWith({ name: 'pi-evan.on.remote.it', @@ -241,10 +245,10 @@ describe('AppTerminalAction — Open terminal in the device’s Apps', () => { service: 'S1', }) act(() => root.unmount()) - container = await render() + container = await render(action(app('starting'))) expect(container.innerHTML).toBe('') act(() => root.unmount()) - container = await render() + container = await render(action(app('running', { capabilities: [] }))) expect(container.innerHTML).toBe('') }) }) diff --git a/frontend/src/components/AppTerminal.tsx b/frontend/src/components/AppTerminal.tsx index 739d50065..ef2779825 100644 --- a/frontend/src/components/AppTerminal.tsx +++ b/frontend/src/components/AppTerminal.tsx @@ -3,7 +3,7 @@ import { useTranslation } from 'react-i18next' import type { TFunction } from 'i18next' import { Button, Typography } from '@mui/material' import browser from '../services/browser' -import { DeviceApp } from '../services/graphQLDeviceApps' +import { DeviceApp, DeviceAppService } from '../services/graphQLDeviceApps' import { ServiceApp, useServiceApp } from '../hooks/useDeviceApps' import { useAppSwitch } from './AppRootConsent' import { useSubnetName } from '../hooks/useLocalSubnetName' @@ -13,17 +13,16 @@ import { IconButton } from '../buttons/IconButton' import { Link } from './Link' import { Icon } from './Icon' -/* An app's service opened in our web SSH (pages/TerminalPage), for any app whose service is ssh and that signs people - in by remote.it certificate (helpers/sshHelper opensTerminal) — from wherever it is picked: the device's Apps +/* An app's service opened in our web SSH (pages/TerminalPage), for any app's service that is ssh where the app signs + people in by remote.it certificate (helpers/sshHelper opensTerminal) — from wherever it is picked: the device's Apps section and the app's page there, its service's row in the device's services and its connect panel. Always the same: the device's name in device subnets, the service's port, the person's own account and a certificate for it, and the host key the device reports for the app, which the terminal checks. An option beside the service's own ways to connect, which stay as they are. Nothing where the device has no name in device subnets or the API has no apps. From the desktop and mobile apps it opens in the web portal, in the system browser (helpers/terminalHelper). */ -function open(app: DeviceApp, name: string, port: number) { - if (!app.serviceId) return - openTerminal({ name, port, title: app.name, service: app.serviceId }) +function open(app: DeviceApp, serviceId: string, name: string, port: number) { + openTerminal({ name, port, title: app.name, service: serviceId }) } const label = (t: TFunction) => @@ -31,18 +30,23 @@ const label = (t: TFunction) => ? t('appTerminal.openInBrowser', 'Open in web SSH, in your browser') : t('appTerminal.open', 'Open in web SSH') -const servicePort = (device: IDevice | undefined, app: DeviceApp) => - device?.services?.find(service => service.id === app.serviceId)?.port +const servicePort = (device: IDevice | undefined, serviceId: string | null) => + device?.services?.find(service => service.id === serviceId)?.port -/** Open terminal, in the device's Apps section and on the app's page there: while it runs. */ -export const AppTerminalAction: React.FC<{ device: IDevice; app: DeviceApp }> = ({ device, app }) => { +/** Open terminal, in the device's Apps section and on the app's page there, for one of its services: while it runs. */ +export const AppTerminalAction: React.FC<{ device: IDevice; app: DeviceApp; service: DeviceAppService }> = ({ + device, + app, + service, +}) => { const { t } = useTranslation() - const terminal = opensTerminal(app) + const terminal = opensTerminal(app, service) const name = useSubnetName(terminal ? device.id : undefined) - const port = servicePort(device, app) - if (!terminal || app.state !== 'running' || !name || !port || !app.serviceId) return null + const port = servicePort(device, service.serviceId) + if (!terminal || app.state !== 'running' || !name || !port || !service.serviceId) return null + const serviceId = service.serviceId return ( - ) @@ -51,11 +55,11 @@ export const AppTerminalAction: React.FC<{ device: IDevice; app: DeviceApp }> = /** 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 } = useServiceApp(device, service) - const terminal = opensTerminal(app) + 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' || !app.serviceId || !name || !port) return null + if (!app || !terminal || app.state !== 'running' || appService?.serviceId !== service.id || !name || !port) return null return ( onClick={event => { // The row opens the service's page: the button is not the row. event.stopPropagation() - open(app, name, port) + open(app, service.id, name, port) }} /> ) @@ -79,10 +83,10 @@ export const AppTerminalButton: React.FC<{ device: IDevice; service: IService }> export const AppTerminalOption: React.FC<{ device?: IDevice; service?: IService; serving: ServiceApp }> = ({ device, service, - serving: { app, switching, turn, setRelease }, + serving: { app, appService, switching, turn, setRelease }, }) => { const { t } = useTranslation() - const terminal = opensTerminal(app) + 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 @@ -92,10 +96,11 @@ export const AppTerminalOption: React.FC<{ device?: IDevice; service?: IService; const port = service?.port if (app.state === 'running' && !switching) { - if (!app.serviceId || !port) return null + const serviceId = appService?.serviceId + if (!serviceId || !port) return null return ( - open(app, name, port)}> + open(app, serviceId, name, port)}> {label(t)} diff --git a/frontend/src/components/DeviceApps.test.tsx b/frontend/src/components/DeviceApps.test.tsx index 94b66d9f5..23640191b 100644 --- a/frontend/src/components/DeviceApps.test.tsx +++ b/frontend/src/components/DeviceApps.test.tsx @@ -40,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 => ({ @@ -59,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', @@ -77,9 +79,10 @@ const consoleApp = (more: Partial = {}): DeviceApp => ({ sessionsOpen: 0, settings: [setting()], ...more, -}) + }) -const backup = (more: Partial = {}): DeviceApp => ({ +const backup = (more: Partial = {}): DeviceApp => + withServices({ id: 'acme.backup', name: 'Backup', publisher: 'Acme', @@ -111,7 +114,7 @@ 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']) => ({ diff --git a/frontend/src/components/DeviceApps.tsx b/frontend/src/components/DeviceApps.tsx index 51426d31b..a39b651a6 100644 --- a/frontend/src/components/DeviceApps.tsx +++ b/frontend/src/components/DeviceApps.tsx @@ -14,7 +14,7 @@ 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 { AppTerminalAction } from './AppTerminal' @@ -175,7 +175,9 @@ export const DeviceApps: React.FC<{ device: IDevice }> = ({ device }) => { // The switch and Open terminal act alone: a click on them is not the row's. const actions = removing ? null : ( event.stopPropagation()}> - + {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 (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; said by its protocol (Open page, Open screen, Connect). One whose service - opens as a terminal (helpers/sshHelper opensTerminal) has Open terminal instead (components/AppTerminal). */ -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/helpers/appsHelper.test.ts b/frontend/src/helpers/appsHelper.test.ts index bb51aa06e..1b8d7ab47 100644 --- a/frontend/src/helpers/appsHelper.test.ts +++ b/frontend/src/helpers/appsHelper.test.ts @@ -12,8 +12,10 @@ import { stateLine, stateWord, withdrawal, + appServiceOf, } from './appsHelper' -import type { DeviceApp } from '../services/graphQLDeviceApps' +import type { DeviceApp, DeviceAppService } from '../services/graphQLDeviceApps' +import { withServices } from '../test/deviceApps' const t = ((_key: string, text: string, values?: any) => text.replace(/{{(\w+)}}/g, (_, k) => values?.[k] ?? '')) as unknown as TFunction @@ -109,7 +111,7 @@ describe('an app’s icon and service, from what the API says — never its id', expect(appIcon(null)).toBe('cube') }) - const app = (id: string, serviceId: string | null) => ({ id, serviceId } as DeviceApp) + const app = (id: string, serviceId: string | null) => withServices({ id, name: id, serviceId, protocol: null } as DeviceApp) it('a service at an app’s host is looked for among its device’s apps; any other is no app’s', () => { expect(appHost('acme.shell')).toBe('remoteit-app-acme-shell') @@ -128,4 +130,20 @@ describe('an app’s icon and service, from what the API says — never its id', expect(serviceApp([app('acme.shell', 'S5')], { id: 'S5', host: 'localhost' })).toBeUndefined() expect(serviceApp(null, service)).toBeUndefined() }) + + it('an app of several services: any of them is the app’s, and which of its services it is', () => { + const stream: DeviceAppService = { + key: 'rtsp', name: 'Stream', protocol: 'tcp', multiPort: true, port: null, portSetting: null, listeners: [], serviceId: 'S6', ports: ['8554', '5004-5005'], + } + const camera = withServices(app('acme.camera', 'S5')) + const both = { ...camera, services: [...camera.services, stream] } + const other = { id: 'S6', host: 'remoteit-app-acme-camera' } + expect(serviceApp([both], other)?.id).toBe('acme.camera') + expect(appServiceOf(both, other)?.key).toBe('rtsp') + expect(appServiceOf(both, { id: 'S5', host: 'remoteit-app-acme-camera' })?.key).toBeNull() + // Disabled, naming none: the primary, at the app's host. + const disabled = withServices({ ...app('acme.camera', null), services: undefined, protocol: 'http' }) + expect(appServiceOf(disabled, { id: 'S5', host: 'remoteit-app-acme-camera' })?.key).toBeNull() + expect(appServiceOf(disabled, { id: 'S5', host: 'remoteit-app-acme-other' })).toBeUndefined() + }) }) diff --git a/frontend/src/helpers/appsHelper.ts b/frontend/src/helpers/appsHelper.ts index 9deae5365..8fd8e5159 100644 --- a/frontend/src/helpers/appsHelper.ts +++ b/frontend/src/helpers/appsHelper.ts @@ -1,5 +1,11 @@ import type { TFunction } from 'i18next' -import type { AppHeldBack, AvailableApp, DeviceApp, DeviceAppRootConsent } from '../services/graphQLDeviceApps' +import type { + AppHeldBack, + AvailableApp, + DeviceApp, + DeviceAppRootConsent, + DeviceAppService, +} from '../services/graphQLDeviceApps' import { needsNewer } from '../services/deviceAppsShared' import type { SettingLock } from '../services/productPolicy' import { timeOptions } from '../components/Timestamp' @@ -81,16 +87,29 @@ export const appHost = (id: string) => `${APP_HOST_PREFIX}${id.toLowerCase().rep const hostOf = (service?: Pick) => (service?.host ?? '').trim().toLowerCase() export const isAppService = (service?: Pick) => hostOf(service).startsWith(APP_HOST_PREFIX) -/* The app a service belongs to: the one that names it (DeviceApp.serviceId); while an app is disabled graphql names no - service (it is kept, stopped), so the one whose host it is. An app that names another service is not this one's. */ +/* The app a service belongs to: the one that names it among its services (DeviceApp.services' serviceId — an app may + have several); while an app is disabled graphql names no service (it is kept, stopped), so the one whose host it is. + An app that names another service is not this one's. */ export function serviceApp(apps: DeviceApp[] | null | undefined, service?: Pick) { if (!apps || !service || !isAppService(service)) return undefined return ( - apps.find(app => app.serviceId === service.id) ?? + apps.find(app => app.services.some(served => served.serviceId === service.id)) ?? apps.find(app => !app.serviceId && appHost(app.id) === hostOf(service)) ) } +// Which of its app's services a device's service is: the one naming it, or — the app disabled, found by its host — +// its primary. +export function appServiceOf( + app: DeviceApp | undefined, + service?: Pick +): DeviceAppService | undefined { + if (!app || !service) return undefined + const named = app.services.find(served => served.serviceId === service.id) + if (named) return named + return !app.serviceId && appHost(app.id) === hostOf(service) ? app.services[0] : undefined +} + // A channel by name: stable or beta, or the account's where none is set. export const channelName = (t: TFunction, channel: string | null | undefined) => channel === 'beta' @@ -337,6 +356,7 @@ export const offered = (app: AvailableApp): DeviceApp => ({ hostKey: null, sessions: [], sessionsOpen: 0, + services: app.services ?? [], settings: [], }) diff --git a/frontend/src/helpers/sshHelper.test.ts b/frontend/src/helpers/sshHelper.test.ts index b9eada2e8..232fb1955 100644 --- a/frontend/src/helpers/sshHelper.test.ts +++ b/frontend/src/helpers/sshHelper.test.ts @@ -8,15 +8,15 @@ describe('sshHelper', () => { expect(sshCommand('pi-evan.on.remote.it')).toBe('ssh pi-evan.on.remote.it') }) - it('opens a terminal for any app whose service is ssh and that declares person-certificates — none by its id', () => { - expect(opensTerminal({ protocol: 'ssh', capabilities: ['person-certificates'] })).toBe(true) + it('opens a terminal for an app’s service that is ssh, where the app declares person-certificates — none by its id', () => { + expect(opensTerminal({ capabilities: ['person-certificates'] }, { protocol: 'ssh' })).toBe(true) expect( - opensTerminal({ protocol: 'ssh', capabilities: ['person-accounts', 'person-certificates', 'ssh-exec'] }) + opensTerminal({ capabilities: ['person-accounts', 'person-certificates', 'ssh-exec'] }, { protocol: 'ssh' }) ).toBe(true) - expect(opensTerminal({ protocol: 'ssh', capabilities: ['ssh-exec'] })).toBe(false) - expect(opensTerminal({ protocol: 'https', capabilities: ['person-certificates'] })).toBe(false) - expect(opensTerminal({ protocol: 'udp', capabilities: ['person-certificates'] })).toBe(false) - expect(opensTerminal({ protocol: null, capabilities: [] })).toBe(false) + expect(opensTerminal({ capabilities: ['ssh-exec'] }, { protocol: 'ssh' })).toBe(false) + expect(opensTerminal({ capabilities: ['person-certificates'] }, { protocol: 'https' })).toBe(false) + expect(opensTerminal({ capabilities: ['person-certificates'] }, { protocol: 'udp' })).toBe(false) + expect(opensTerminal({ capabilities: [] }, { protocol: null })).toBe(false) expect(opensTerminal(undefined)).toBe(false) }) }) diff --git a/frontend/src/helpers/sshHelper.ts b/frontend/src/helpers/sshHelper.ts index 25f22cdf2..1f10cccd2 100644 --- a/frontend/src/helpers/sshHelper.ts +++ b/frontend/src/helpers/sshHelper.ts @@ -1,14 +1,17 @@ -import type { DeviceApp } from '../services/graphQLDeviceApps' +import type { DeviceApp, DeviceAppService } from '../services/graphQLDeviceApps' /* Plain ssh to a remote.it name: a machine signed in on its remote.it device app gets a certificate for its own ssh (connectd remoteit-device ssh-config), which an app that signs people in by certificate takes — so its command works there as it is. */ -/** An app whose service opens as a terminal (pages/TerminalPage) with the person's own account and a certificate: its - * service is ssh and it declares person-certificates (presence-contract docs/self-contained-apps.md, "Capabilities, - * as the platform keeps them"). graphql's sshAccount, sshCertificate and sshHostKey answer for its service. */ -export const opensTerminal = (app?: Pick) => - app?.protocol === 'ssh' && !!app.capabilities?.includes('person-certificates') +/** An app's service that opens as a terminal (pages/TerminalPage) with the person's own account and a certificate: the + * service is ssh and its app declares person-certificates (presence-contract docs/self-contained-apps.md, + * "Capabilities, as the platform keeps them"). graphql's sshAccount, sshCertificate and sshHostKey answer for its ssh + * service. */ +export const opensTerminal = ( + app?: Pick, + service?: Pick | null +) => service?.protocol === 'ssh' && !!app?.capabilities?.includes('person-certificates') /** The plain ssh command for a name and port: the port named only when it is not 22. */ export const sshCommand = (name: string, port?: number) => diff --git a/frontend/src/hooks/useDeviceApps.test.tsx b/frontend/src/hooks/useDeviceApps.test.tsx index c6b0326ec..5916b69d2 100644 --- a/frontend/src/hooks/useDeviceApps.test.tsx +++ b/frontend/src/hooks/useDeviceApps.test.tsx @@ -23,6 +23,7 @@ vi.mock('../services/graphQLDeviceApps', () => ({ })) import { DeviceApps, ServiceApp, useDeviceApps, useServiceApp } from './useDeviceApps' +import { withServices } from '../test/deviceApps' ;(globalThis as any).IS_REACT_ACT_ENVIRONMENT = true const aiCommands = (value: boolean) => ({ @@ -41,7 +42,7 @@ const aiCommands = (value: boolean) => ({ deprecated: null, }) -const app = (state: string, enabled = state !== 'disabled') => ({ +const rawApp = (state: string, enabled = state !== 'disabled') => ({ id: 'remoteit.console', name: 'Console', publisher: 'remote.it', @@ -51,9 +52,11 @@ const app = (state: string, enabled = state !== 'disabled') => ({ state, detail: null, serviceId: enabled ? 'S1' : null, + protocol: 'ssh', version: null, settings: [aiCommands(true)], }) +const app = (state: string, enabled?: boolean) => withServices(rawApp(state, enabled) as any) let root: Root const seen: Record = {} @@ -228,16 +231,33 @@ describe('useDeviceApps', () => { expect(setSetting).toHaveBeenCalledWith('D1', 'remoteit.console', 'ai_commands', false) expect(seen.a.apps?.[0].settings[0].value).toBe(false) expect(seen.b.apps?.[0].settings[0].value).toBe(false) + // Not a port: the apps are not read again. + expect(read).toHaveBeenCalledTimes(1) + }) + + it('a port setting — a service’s or a listener’s — reads the apps again: their services’ ports moved with it', async () => { + const stream = { key: 'rtsp', name: 'Stream', protocol: 'udp', multiPort: true, port: null, portSetting: null, serviceId: 'S8', + listeners: [{ name: 'rtsp', type: 'udp', port: null, portSetting: 'rtsp_port', ports: null }], ports: ['8554'] } + const camera = withServices({ ...rawApp('running'), services: undefined } as any) + read.mockResolvedValue([{ ...camera, services: [...camera.services, stream] }]) + await render() + read.mockResolvedValue([{ ...camera, services: [...camera.services, { ...stream, ports: ['9554'] }] }]) + await act(async () => { + await seen.a.setSetting(seen.a.apps![0], 'rtsp_port', 9554) + }) + expect(read).toHaveBeenCalledTimes(2) + expect(seen.a.apps?.[0].services[1].ports).toEqual(['9554']) }) }) describe('useServiceApp: the app a service belongs to', () => { - const shell = (state: string, more: any = {}) => ({ - ...app(state), - id: 'acme.shell', - serviceId: state === 'disabled' ? null : 'S5', - ...more, - }) + const shell = (state: string, more: any = {}) => + withServices({ + ...rawApp(state), + id: 'acme.shell', + serviceId: state === 'disabled' ? null : 'S5', + ...more, + } as any) it('the app naming the service; while disabled, the app whose host the service is at', async () => { read.mockResolvedValue([app('running'), shell('running')]) diff --git a/frontend/src/hooks/useDeviceApps.ts b/frontend/src/hooks/useDeviceApps.ts index e04ed1675..f16a7ac50 100644 --- a/frontend/src/hooks/useDeviceApps.ts +++ b/frontend/src/hooks/useDeviceApps.ts @@ -4,6 +4,7 @@ import { AppRelease, AvailableApp, DeviceApp, + DeviceAppService, graphQLAddDeviceApp, graphQLAvailableApps, graphQLDeviceApps, @@ -13,7 +14,7 @@ import { graphQLSetDeviceAppSetting, refused, } from '../services/graphQLDeviceApps' -import { isAppService, serviceApp } from '../helpers/appsHelper' +import { appServiceOf, isAppService, serviceApp } from '../helpers/appsHelper' type Read = ReturnType @@ -135,6 +136,11 @@ export function useDeviceApps(deviceId?: string, { offers = true }: { offers?: b a.id === app.id ? { ...a, settings: a.settings.map(s => (s.name === name ? setting : s)) } : a ) tell(deviceId, now) + // A port setting moves its service's ports, which graphql keeps in step: read them as it now has them. + if (isPortSetting(app, name)) { + const read = await graphQLDeviceApps(deviceId) + if (read) tell(deviceId, read) + } return true }, [deviceId, apps] @@ -151,10 +157,17 @@ export function useDeviceApps(deviceId?: string, { offers = true }: { offers?: b } } -/* The app a service of a device belongs to (helpers/appsHelper serviceApp), with its device's apps to turn it on: read - only for a service at an app's host, so a device's other services ask nothing. */ -export type ServiceApp = DeviceApps & { app?: DeviceApp } +// Whether a setting is one of an app's ports: a service's (portSetting), or a listener's. +const isPortSetting = (app: DeviceApp, name: string) => + app.portSetting === name || + app.services.some(service => service.portSetting === name || service.listeners.some(l => l.portSetting === name)) + +/* The app a service of a device belongs to (helpers/appsHelper serviceApp) and which of its services it is + (appServiceOf), with its device's apps to turn it on: read only for a service at an app's host, so a device's other + services ask nothing. */ +export type ServiceApp = DeviceApps & { app?: DeviceApp; appService?: DeviceAppService } export function useServiceApp(device?: IDevice, service?: IService): ServiceApp { const deviceApps = useDeviceApps(isAppService(service) ? device?.id : undefined, { offers: false }) - return { ...deviceApps, app: serviceApp(deviceApps.apps, service) } + const app = serviceApp(deviceApps.apps, service) + return { ...deviceApps, app, appService: appServiceOf(app, service) } } diff --git a/frontend/src/i18n/locales/de/app.json b/frontend/src/i18n/locales/de/app.json index 1651c0f7a..acd82325d 100644 --- a/frontend/src/i18n/locales/de/app.json +++ b/frontend/src/i18n/locales/de/app.json @@ -277,6 +277,8 @@ "heldUngranted": "", "heldUntrusted": "", "keptWithdrawn": "", + "listenerPort": "", + "listenPort": "", "managed": "", "managedBy": "", "manageReleases": "", @@ -335,6 +337,7 @@ "searchDevices": "", "service": "", "serviceLine": "", + "serviceLinePorts": "", "serviceLineUdp": "", "servicePort": "", "serviceStopped": "", diff --git a/frontend/src/i18n/locales/en/app.json b/frontend/src/i18n/locales/en/app.json index e9ec0ea19..16eb7ecf5 100644 --- a/frontend/src/i18n/locales/en/app.json +++ b/frontend/src/i18n/locales/en/app.json @@ -277,6 +277,8 @@ "heldUngranted": "The device refused its delivery grant", "heldUntrusted": "The device refused its publisher’s signature", "keptWithdrawn": "Kept by this device’s administrator, though its release was withdrawn", + "listenerPort": "Port of {{listener}}", + "listenPort": "Port it listens on", "managed": "Managed by its product", "managedBy": "Managed by its product {{product}}", "manageReleases": "Manage releases", @@ -335,6 +337,7 @@ "searchDevices": "Search devices…", "service": "Service", "serviceLine": "{{name}} · port {{port}}", + "serviceLinePorts": "{{name}} · ports {{ports}}", "serviceLineUdp": "{{name}} · UDP port {{port}}", "servicePort": "Port people connect to", "serviceStopped": "Stopped while the app is disabled: enable it to open it", diff --git a/frontend/src/i18n/locales/es/app.json b/frontend/src/i18n/locales/es/app.json index 05e6998cb..24eb14c2d 100644 --- a/frontend/src/i18n/locales/es/app.json +++ b/frontend/src/i18n/locales/es/app.json @@ -284,6 +284,8 @@ "heldUngranted": "", "heldUntrusted": "", "keptWithdrawn": "", + "listenerPort": "", + "listenPort": "", "managed": "", "managedBy": "", "manageReleases": "", @@ -342,6 +344,7 @@ "searchDevices": "", "service": "", "serviceLine": "", + "serviceLinePorts": "", "serviceLineUdp": "", "servicePort": "", "serviceStopped": "", diff --git a/frontend/src/i18n/locales/ja/app.json b/frontend/src/i18n/locales/ja/app.json index bae183e93..19181d0b6 100644 --- a/frontend/src/i18n/locales/ja/app.json +++ b/frontend/src/i18n/locales/ja/app.json @@ -270,6 +270,8 @@ "heldUngranted": "", "heldUntrusted": "", "keptWithdrawn": "", + "listenerPort": "", + "listenPort": "", "managed": "", "managedBy": "", "manageReleases": "", @@ -328,6 +330,7 @@ "searchDevices": "", "service": "", "serviceLine": "", + "serviceLinePorts": "", "serviceLineUdp": "", "servicePort": "", "serviceStopped": "", diff --git a/frontend/src/pages/DeviceAppPage.test.tsx b/frontend/src/pages/DeviceAppPage.test.tsx index 712b6ff1c..9c398d815 100644 --- a/frontend/src/pages/DeviceAppPage.test.tsx +++ b/frontend/src/pages/DeviceAppPage.test.tsx @@ -9,6 +9,8 @@ const { apps, catalog, push, params, openTerminal } = vi.hoisted(() => ({ params: { appID: 'acme.backup' }, openTerminal: vi.fn(), })) +// The page reads its services' ports with multiPortServices' formatting; nothing here asks the API. +vi.mock('../services/post', () => ({ post: vi.fn() })) vi.mock('react-router-dom', () => ({ useHistory: () => ({ push }), useParams: () => params })) vi.mock('../services/Context', async () => ({ DeviceContext: (await import('react')).createContext({}) })) vi.mock('../services/graphQLAppCatalog', () => ({ graphQLCatalogApp: catalog })) @@ -56,9 +58,11 @@ vi.mock('react-i18next', () => ({ import { DeviceAppPage } from './DeviceAppPage' import { DeviceContext } from '../services/Context' import type { DeviceApp } from '../services/graphQLDeviceApps' +import { withServices } from '../test/deviceApps' ;(globalThis as any).IS_REACT_ACT_ENVIRONMENT = true -const backup = (more: Partial = {}): DeviceApp => ({ +const backup = (more: Partial = {}): DeviceApp => + withServices({ id: 'acme.backup', name: 'Backup', publisher: 'Acme', @@ -99,7 +103,7 @@ const backup = (more: Partial = {}): DeviceApp => ({ }, ], ...more, -}) + }) const CATALOG = { id: 'acme.backup', @@ -442,6 +446,55 @@ describe('its service, settings, root, delivery and problems', () => { expect(row(page, 'settings')?.textContent).toContain('Port') }) + it('each of its services, the primary first: its ports — several as a list, the first the launch port — its listeners’ port settings, and its own Open', async () => { + params.appID = 'acme.camera' + const setting = (name: string, label: string) => ({ ...backup().settings[0], name, type: 'int', label, default: 8080, value: 8080, choices: null }) + const camera = backup({ + id: 'acme.camera', + name: 'Camera', + protocol: 'http', + serviceId: 'S7', + portSetting: 'web_port', + settings: [...backup().settings, setting('web_port', 'Web port'), setting('rtsp_port', 'RTSP port')], + services: [ + { key: null, name: 'Camera', protocol: 'http', multiPort: false, port: null, portSetting: 'web_port', + listeners: [{ name: 'web', type: 'tcp', port: null, portSetting: null, ports: null }], serviceId: 'S7', ports: ['30001'] }, + { key: 'rtsp', name: 'Stream', protocol: 'udp', multiPort: true, port: null, portSetting: null, + listeners: [ + { name: 'rtsp', type: 'udp', port: null, portSetting: 'rtsp_port', ports: null }, + { name: 'rtp', type: 'udp', port: null, portSetting: null, ports: '5004-5005' }, + ], serviceId: 'S8', ports: ['8554', '5004-5005'] }, + ], + }) + apps.value.apps = [camera] + const page = await render() + const services = page.querySelectorAll('[data-app-service]') + expect(services.length).toBe(2) + expect(services[0].textContent).toContain('Backup · port 30001') + expect(services[0].querySelector('[data-app-port-setting="web_port"]')?.textContent).toBe('Port people connect to') + expect(services[1].textContent).toContain('Stream · ports 8554, 5004-5005') + expect(services[1].querySelector('[data-app-service-ports]')?.textContent).toBe( + 'This connection reaches port 8554 only. All its ports, 8554, 5004-5005, are reached by name on the device subnet.' + ) + expect(services[1].querySelector('[data-app-port-setting="rtsp_port"]')?.textContent).toBe('Port of rtsp') + // Each port setting edited once: under its service, not again under Settings. + expect(row(page, 'settings')?.querySelector('[data-setting="web_port"], [data-setting="rtsp_port"]')).toBeNull() + expect(row(page, 'settings')?.textContent).toContain('Back up') + // Each its own Open: the udp one connects, launching nothing. + const opens = page.querySelectorAll('[data-app-open]') + expect([...opens].map(open => open.textContent)).toEqual(['Open page', 'Connect']) + await click(opens[1]) + expect(push).toHaveBeenCalledWith({ pathname: '/devices/D1/S8/connect', state: { autoConnect: true } }) + act(() => root.unmount()) + container.remove() + // Disabled, its services stopped: its port settings are under Settings, by their own labels. + apps.value.apps = [{ ...camera, enabled: false, state: 'disabled', serviceId: null, services: camera.services.map(s => ({ ...s, serviceId: null, ports: [] })) }] + const stopped = await render() + expect(stopped.querySelectorAll('[data-app-service]').length).toBe(0) + expect(row(stopped, 'settings')?.textContent).toContain('Web port') + expect(row(stopped, 'settings')?.textContent).toContain('RTSP port') + }) + it('Open terminal in Open’s place, for any app whose service is ssh and that declares person-certificates', async () => { params.appID = 'acme.shell' const shell = { id: 'acme.shell', name: 'Shell', protocol: 'ssh', capabilities: ['person-certificates'] } diff --git a/frontend/src/pages/DeviceAppPage.tsx b/frontend/src/pages/DeviceAppPage.tsx index 6abbcbda0..43cce8641 100644 --- a/frontend/src/pages/DeviceAppPage.tsx +++ b/frontend/src/pages/DeviceAppPage.tsx @@ -4,7 +4,8 @@ import type { TFunction } from 'i18next' import { useHistory, useParams } from 'react-router-dom' import { Box, Button, Divider, List, Switch, TextField, Typography } from '@mui/material' import { DeviceContext } from '../services/Context' -import { DeviceApp } from '../services/graphQLDeviceApps' +import { DeviceApp, DeviceAppService } from '../services/graphQLDeviceApps' +import { firstPortOf, formatPorts } from '../services/multiPortServices' import { CatalogApp, graphQLCatalogApp } from '../services/graphQLAppCatalog' import { useDeviceApps } from '../hooks/useDeviceApps' import { useAppSwitch, RootConsent } from '../components/AppRootConsent' @@ -44,11 +45,13 @@ import { LIST_ITEM_ICON_WIDTH, spacing } from '../styling' Version the version it runs against the one offered on its channel: up to date, or held back with why and what would release it (Update now… for a release waiting for root consent, Unpin for a pin, none for the rest) Channel its channel (the account's, stable, beta) and its pin (none, or a release of it) - Service its service, opened by its protocol — Open terminal for one that is ssh and signs people in by - certificate (components/AppTerminal), a page for http and https, a viewer for vnc and rdp, a connection - alone for udp (its port, said UDP, is for the person's own UDP client) —, the key it - presents where it reports one, and the port people connect to where its owner chooses it (portSetting: - that setting is edited here, not under Settings). A disabled app has no service to open (graphql gives + Service each of its services, the primary first, opened by its protocol — Open terminal for one that is ssh + where the app signs people in by certificate (components/AppTerminal), a page for http and https, a + viewer for vnc and rdp, a connection alone for udp (its port, said UDP, is for the person's own UDP + client) —; a multi-port service's ports as a list, a connection reaching the first, its launch port, + and the rest by name on the device subnet; the key the app presents (under the primary); and the + ports its owner chooses (a service's portSetting, a listener's), each edited there, labelled with its + service or listener, not again under Settings. A disabled app has no service to open (graphql gives none: kept, stopped): said stopped, where its app serves one (its release names a protocol) Sessions how many it serves now, where it reports them; each session, as whom and since when, for those who manage it @@ -135,16 +138,14 @@ export const DeviceAppPage: React.FC = () => { // The machine's administrator refuses the switch either way (local), or enabling it (off); and its removal (local). const adminHeld = adminRefuses(app, app.enabled ? 'disable' : 'enable') const admin = adminLine(t, app) - // The setting that is its service's port (portSetting) is edited in one place: under Service, where its service is - // shown; in Settings otherwise (disabled, its service stopped). - const serviceShown = !!app.serviceId && !gone - const portSetting = serviceShown ? app.settings.find(setting => setting.name === app.portSetting) : undefined - const settings = app.settings.filter( - setting => (!setting.deprecated || setting.at) && setting !== portSetting - ) + // Its services, the primary first, each shown while it is served. A setting that is a shown service's port, or one + // of its listeners', is edited in one place: under that service, labelled so; in Settings otherwise (disabled, its + // services stopped). + const shown = gone ? [] : app.services.filter(served => !!served.serviceId) + const ports = new Map(shown.flatMap(served => portSettingsOf(t, served))) + const settings = app.settings.filter(setting => (!setting.deprecated || setting.at) && !ports.has(setting.name)) const accountChannel = catalog?.accountChannel ?? 'stable' const channel = app.channel || accountChannel - const service = device.services?.find(s => s.id === app.serviceId) const waitingRoot = app.heldBack?.reason === 'consent' || (!app.heldBack && !!app.awaitingRoot) // Held back for what its state already says (graphql gives both the same words: a withdrawal, one kept though // withdrawn, the device's refusal): said once, in State. @@ -308,47 +309,78 @@ export const DeviceAppPage: React.FC = () => { )} - {serviceShown && ( - - - - {!service - ? app.name - : app.protocol === 'udp' - ? t('apps.serviceLineUdp', '{{name}} · UDP port {{port}}', { name: service.name, port: service.port }) - : t('apps.serviceLine', '{{name}} · port {{port}}', { name: service.name, port: service.port })} - - {app.hostKey && ( - - {t('deviceApps.hostKey', 'Host key {{key}}', { key: app.hostKey })} + {shown.map((served, index) => { + const service = device.services?.find(s => s.id === served.serviceId) + // Its ports as graphql has them (a port setting's change re-reads them), else as the device's service says. + const list = served.ports.length ? served.ports : 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] })} - )} - {portSetting && ( - - change(portSetting.name, () => setSetting(app, portSetting.name, value))} - /> - - )} - - {app.enabled && - (opensTerminal(app) ? ( - - ) : ( - - ))} - - )} + {/* 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 && ( @@ -510,6 +542,22 @@ export const DeviceAppPage: React.FC = () => { } // 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, diff --git a/frontend/src/services/graphQLDeviceApps.test.ts b/frontend/src/services/graphQLDeviceApps.test.ts index 20cc45029..b1fe8debc 100644 --- a/frontend/src/services/graphQLDeviceApps.test.ts +++ b/frontend/src/services/graphQLDeviceApps.test.ts @@ -87,7 +87,12 @@ describe('Device.apps', () => { // A session as the app reports it: never a person. expect(query).toContain('sessions { session login via since }') expect(query).not.toMatch(/\bperson\b/) - expect(query).not.toMatch(/\bport\b|\bon\b/) + // Its services, the primary first, each with its listeners and its ports 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 ports }' + 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 @@ -204,7 +209,7 @@ describe('Device.apps', () => { ) const apps = (await graphQLDeviceApps('D1'))! expect(post.mock.calls[0][0].query).toMatch( - /sessionsOpen features portSetting 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() @@ -352,9 +357,9 @@ 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, protocol: null, capabilities: [], contract: 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 protocol capabilities contract }') + 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 }) @@ -365,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 and its ports', 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', ports: ['8080'] }, + { key: 'rtsp', name: 'Stream', protocol: 'tcp', multiPort: true, + listeners: [{ name: 'rtsp', type: 'tcp', port: 8554 }, { name: 'rtp', type: 'udp', ports: '5004-5005' }], serviceId: 'S2', ports: ['8554', '5004-5005'] }, + ] + 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 5aaec82ac..7bf420a3e 100644 --- a/frontend/src/services/graphQLDeviceApps.ts +++ b/frontend/src/services/graphQLDeviceApps.ts @@ -47,6 +47,38 @@ export type AppProtocol = 'ssh' | 'http' | 'https' | 'vnc' | 'rdp' | 'tcp' | 'ud 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 and ports: the service on the device and its ports and ranges there, + while the app is enabled and the service served. */ +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 + ports: string[] +} + +// 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. @@ -128,6 +160,8 @@ export type DeviceApp = { // 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 @@ -172,7 +206,11 @@ 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 SESSION_FIELDS = 'session login via since' -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 problems { name error detail } settings { ${SETTING_FIELDS} }` +// An app's services as its release declares them (AppService), and as each is on the device (DeviceAppService). +const DECLARED_SERVICE_FIELDS = + 'key name protocol multiPort port portSetting listeners { name type port portSetting ports }' +const SERVICE_FIELDS = `${DECLARED_SERVICE_FIELDS} serviceId ports` +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 { @@ -186,6 +224,24 @@ function parsedSetting(setting: any): DeviceAppSetting { } } +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, + ports: service.ports ?? [], +}) + export const parsedDeviceApp = (app: any): DeviceApp => ({ ...app, enabled: !!app.enabled, @@ -216,6 +272,8 @@ export const parsedDeviceApp = (app: any): DeviceApp => ({ 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), }) @@ -256,11 +314,12 @@ export type AvailableApp = { protocol?: AppProtocol | string | null capabilities?: (AppCapability | string)[] contract?: number | null + services?: DeviceAppService[] // as the release declares them, the primary first; none on the device yet } // [] where the API has none, or the device is not this person's to manage. export async function graphQLAvailableApps(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 protocol capabilities contract } } } }` + 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 [] @@ -279,6 +338,7 @@ export async function graphQLAvailableApps(deviceId: string): Promise & { 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, + ports: [], + } + return { ...app, services: serves ? [primary] : [] } +}