diff --git a/frontend/src/buttons/ServiceConnectButton.tsx b/frontend/src/buttons/ServiceConnectButton.tsx index e7571112b..8f96f9be3 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) 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..b18df87db 100644 --- a/frontend/src/components/AppRootConsent.tsx +++ b/frontend/src/components/AppRootConsent.tsx @@ -1,28 +1,41 @@ -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 { capabilityWords } 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. */ + full control of the device (presence-server docs/device-apps-design.md, "Root, shown and consented to"), and what + else it asks of remote.it — its capabilities, part of the consent (presence-contract docs/self-contained-apps.md, + "Manifest"). For a product it says the yes covers every device in the product, now and later, as graphql keeps it + on the product. + + The capabilities named are 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. They are read + from its catalogue entry (useReleaseAsks); until they are, the yes waits. */ export const RootConsent: React.FC<{ - app?: { name: string; publisher: string } // open while there is one + app?: { id?: string; name: string; publisher: string; capabilities?: string[] } // open while there is one 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). version?: string | null + // The release the yes is given to, where it is not version: a pin, the release enabling gives. None: the app's own. + release?: string | null + accountId?: string // whose catalogue names the release: the device'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) return ( + {product ? t( @@ -74,8 +88,59 @@ export const RootConsent: React.FC<{ ) } +/* What the release a consent is for asks of remote.it (its capabilities): its catalogue entry's for that release; the + app's own where no release is named, or where the catalogue does not answer for it (an API without one, an error, a + release it does not list — graphql still refuses a yes that does not cover what the release asks). undefined while + it is read. */ +export function useReleaseAsks( + app: { id?: string; capabilities?: string[] } | undefined, + release: string | null | undefined, + accountId?: string +): string[] | undefined { + const [read, setRead] = useState<{ key: string; asks: string[] | null }>() + const key = app?.id && release ? `${accountId ?? ''}/${app.id}/${release}` : '' + useEffect(() => { + if (!key || !app?.id || !release) return + let current = true + graphQLCatalogApp(app.id, { accountId, releases: 100 }).then(answer => { + if (!current) return + const entry = typeof answer === 'object' && answer ? answer.releases.find(r => r.version === release) : undefined + setRead({ key, asks: entry ? entry.capabilities : null }) + }) + return () => { + current = false + } + }, [key]) + if (!app) return undefined + if (!key) return app.capabilities ?? [] + if (read?.key !== key) return undefined + return read.asks ?? app.capabilities ?? [] +} + +// 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 + an app's service'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, @@ -83,7 +148,8 @@ export const RootConsent: React.FC<{ export function useAppSwitch( { turn, setRelease }: Pick & Partial>, onRefused?: (reason: string) => void, - onChanged?: (app: DeviceApp) => void + onChanged?: (app: DeviceApp) => void, + accountId?: string // the device's account, whose catalogue names the release consented to ) { const { t } = useTranslation() const [asking, setAsking] = useState() @@ -102,11 +168,15 @@ 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, else the one enabling gives — its pin, else its channel's. + const target = updating || asking?.pinned || asking?.latest || asking?.release || asking?.version || null const consent = ( { const app = asking diff --git a/frontend/src/components/AppTerminal.test.tsx b/frontend/src/components/AppTerminal.test.tsx new file mode 100644 index 000000000..768d88f9a --- /dev/null +++ b/frontend/src/components/AppTerminal.test.tsx @@ -0,0 +1,250 @@ +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 { 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) } + }, + } +}) +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 } = useServiceApp(device, service) + const terminal = opensTerminal(app) + const name = useSubnetName(terminal ? device.id : undefined) + const port = service.port + if (!app || !terminal || app.state !== 'running' || !app.serviceId || !name || !port) return null + return ( + { + // The row opens the service's page: the button is not the row. + event.stopPropagation() + open(app, 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, switching, turn, setRelease }, +}) => { + const { t } = useTranslation() + const terminal = opensTerminal(app) + 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) { + if (!app.serviceId || !port) return null + return ( + + open(app, 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} - ) } diff --git a/frontend/src/components/LocalSubnetConnect.tsx b/frontend/src/components/LocalSubnetConnect.tsx index 4415cefb6..292c21933 100644 --- a/frontend/src/components/LocalSubnetConnect.tsx +++ b/frontend/src/components/LocalSubnetConnect.tsx @@ -12,7 +12,7 @@ import { PromptModal } from './PromptModal' import { Confirm } from './Confirm' import { useDeviceSessions } from '../hooks/useDeviceSessions' import { graphQLDetectedSchemes, redirectLoops } from '../services/graphQLDetectedScheme' -import { isConsoleService, sshCommand } from '../helpers/sshHelper' +import { sshCommand } from '../helpers/sshHelper' import { formatPorts, isMultiPort } from '../services/multiPortServices' import { Icon } from './Icon' @@ -22,15 +22,16 @@ import { Icon } from './Icon' service's own port. A web service launches as https://: 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..d766ea9df 100644 --- a/frontend/src/components/ProductPolicyApps.test.tsx +++ b/frontend/src/components/ProductPolicyApps.test.tsx @@ -3,6 +3,8 @@ 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() })) +// 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('../services/graphQL', () => ({ graphQLGetErrors: vi.fn(), @@ -82,6 +84,8 @@ const consoleApp = (more: Partial = {}): ProductApp => ({ publisher: 'remote.it', description: null, root: true, + capabilities: ['person-accounts', 'person-certificates', 'ssh-exec'], + protocol: 'ssh', version: '1.4.0', state: null, channel: 'stable', @@ -91,7 +95,13 @@ const consoleApp = (more: Partial = {}): ProductApp => ({ locked: false, at: null, by: null, - settings: [aiCommands()], + // Its words are its release's, as the API gives them. + settings: [ + aiCommands({ + label: 'Allow AI commands', + help: 'AI assistants you authorize may run commands on this device through remote.it’s MCP server.', + }), + ], ...more, }) @@ -101,6 +111,8 @@ const logs = (more: Partial = {}): ProductApp => ({ publisher: 'Acme', description: 'Reads the device’s logs', root: false, + capabilities: [], + protocol: null, version: null, state: null, channel: null, @@ -169,6 +181,11 @@ describe('a product’s Apps block', () => { expect(line(page, 'remoteit.console', 'about')).toBe('By remote.it · 1.4.0 · Stable') expect(line(page, 'remoteit.console', 'root')).toBe('Runs as root: full control of this device') expect(row(page, 'remoteit.console').querySelector('[data-icon="terminal"]')).not.toBeNull() + expect(line(page, 'remoteit.console', 'capabilities')).toBe( + 'Keeps accounts for the people you share with · Signs in people by remote.it certificate · AI commands go through this app' + ) + expect(row(page, 'acme.logs').querySelector('[data-icon="cube"]')).not.toBeNull() + expect(line(page, 'acme.logs', 'capabilities')).toBeUndefined() expect(line(page, 'acme.logs', 'about')).toBe('By Acme · No release here yet') expect(line(page, 'acme.logs', 'description')).toBe('Reads the device’s logs') expect(line(page, 'acme.logs', 'root')).toBeUndefined() @@ -229,6 +246,12 @@ describe('a product’s Apps block', () => { expect(body).toContain('full control of this device') expect(body).toContain('every device in this product, now and later') expect(confirm.textContent).toContain('Turn it on only if you trust remote.it with every device in this product.') + // What else it asks of remote.it is part of the consent. + expect([...confirm.querySelectorAll('[data-app-capability]')].map(c => c.textContent)).toEqual([ + '· Keeps accounts for the people you share with', + '· Signs in people by remote.it certificate', + '· AI commands go through this app', + ]) await click(confirm.querySelector('[data-confirm-ok]')) expect(setApp).toHaveBeenCalledWith('P1', 'remoteit.console', 'enabled', { channel: 'stable', diff --git a/frontend/src/components/ProductPolicyApps.tsx b/frontend/src/components/ProductPolicyApps.tsx index c69074065..1071b4a8a 100644 --- a/frontend/src/components/ProductPolicyApps.tsx +++ b/frontend/src/components/ProductPolicyApps.tsx @@ -11,13 +11,13 @@ import { graphQLSetDeviceProductApp, graphQLSetDeviceProductAppSetting, } from '../services/productPolicy' -import { firstPartyApp } from './firstPartyApps' import { RootConsent } from './AppRootConsent' import { deprecatedLine } from './DeviceSettingRow' import { SelectSetting } from './SelectSetting' import { timeOptions } from './Timestamp' import { Notice } from './Notice' import { Icon } from './Icon' +import { appIcon, capabilitiesLine } from '../helpers/appsHelper' import { LIST_ITEM_ICON_WIDTH, spacing } from '../styling' type Props = { @@ -33,14 +33,15 @@ const UNSET = '' /* The apps a product sets on its devices (presence-server docs/device-apps-design.md, "Product policy" under "Lifecycle: add, disable, remove", and "The Apps pages"): every catalogue app its account may take, a row each — its - publisher, its version and channel or pin, Runs as root where it does — with a select: Unset (each device's own), + publisher, its version and channel or pin, Runs as root where it does and what else it asks of remote.it (its + capabilities, where the API says them) — with a select: Unset (each device's own), Enabled (added and enabled), Disabled (added, nothing installed) or Removed (taken off its devices, and kept off); under enforced, Unset reads "Removed (not listed)", as an app the product does not list is removed. Its settings are its options, inside its row and lined up under its name. One the product sets is locked on its devices while it is synced or enforced; a setting the release says may not be forced is given to them but not locked, and is said so. A root app is enabled for the product only once the person says yes to its full control of every device in the - product, now and later (components/AppRootConsent); graphql keeps that consent on the product, and asks for it again + product, now and later, and to what else it asks of remote.it (components/AppRootConsent); graphql keeps that consent on the product, and asks for it again when a new release newly runs as root, its devices staying on its last restricted release meanwhile (or not turned on, where there is none). Turning an app on needs Scripting in the product's account as well as managing the product; graphql says so where it refuses, and its words are shown. @@ -111,15 +112,13 @@ export const ProductPolicyApps: React.FC = ({ productId, apps, sync, mana {apps.map(app => { - const own = firstPartyApp(app.id) - const words = own?.settings?.(t) ?? {} const settings = app.settings.filter(setting => !setting.deprecated || setting.value !== null) const value = app.state ?? UNSET return ( - + = ({ productId, apps, sync, mana {t('deviceApps.runsAsRoot', 'Runs as root: full control of this device')} )} + {!!app.capabilities.length && ( + {capabilitiesLine(t, app.capabilities)} + )} {app.locked && {lockedLine(t, sync)}} {app.rootConsent && !app.needsConsent && ( @@ -210,8 +212,8 @@ export const ProductPolicyApps: React.FC = ({ productId, apps, sync, mana key={setting.name} setting={setting} sync={sync} - label={words[setting.name]?.label ?? setting.label} - help={words[setting.name]?.help ?? setting.help} + label={setting.label} + help={setting.help} disabled={!manage || saving === `${app.id}.${setting.name}`} onChange={next => setSetting(app, setting.name, next)} /> @@ -230,6 +232,7 @@ export const ProductPolicyApps: React.FC = ({ productId, apps, sync, mana product app={asking} version={asking?.state === 'enabled' && asking.needsConsent ? asking.awaitingRoot : undefined} + release={asking?.awaitingRoot || asking?.version} action={asking?.state === 'enabled' ? t('productApps.consentAction', 'Consent to full control') : undefined} onConfirm={() => { const app = asking diff --git a/frontend/src/components/firstPartyApps.ts b/frontend/src/components/firstPartyApps.ts deleted file mode 100644 index e2ef6be2c..000000000 --- a/frontend/src/components/firstPartyApps.ts +++ /dev/null @@ -1,20 +0,0 @@ -import type React from 'react' -import type { TFunction } from 'i18next' -import { CONSOLE, DeviceApp } from '../services/graphQLDeviceApps' -import { CONSOLE_APP } from './ConsoleApp' - -/* remote.it's own apps' parts of the Apps section, keyed by app id: the portal's counterpart of graphql's APP_HOOKS - (presence-server docs/device-apps-design.md, "Hooks: what only code can do"). Only remote.it's apps (`remoteit.*`) - have one; any other app is drawn from what the API says of it alone. */ -export type FirstPartyApp = { - icon: string - state?: (t: TFunction, app: DeviceApp) => string | undefined // its own words for a state, where it has them - settings?: (t: TFunction) => Record // its settings' words, translated - Lines?: React.FC<{ device: IDevice; app: DeviceApp }> // under its state - Actions?: React.FC<{ device: IDevice; app: DeviceApp }> // beside its switch -} - -export const FIRST_PARTY_APPS: Record = { [CONSOLE]: CONSOLE_APP } - -export const firstPartyApp = (id: string): FirstPartyApp | undefined => - id.startsWith('remoteit.') ? FIRST_PARTY_APPS[id] : undefined diff --git a/frontend/src/components/thisDevice/ThisDeviceAdvanced.tsx b/frontend/src/components/thisDevice/ThisDeviceAdvanced.tsx index 1b22220f4..9b96c110b 100644 --- a/frontend/src/components/thisDevice/ThisDeviceAdvanced.tsx +++ b/frontend/src/components/thisDevice/ThisDeviceAdvanced.tsx @@ -1,19 +1,23 @@ import React from 'react' import { Box, Button, Divider, List, ListItem, ListItemText, Switch, Typography } from '@mui/material' import { PermissionName, ThisDevice } from '../../services/thisDevice' +import { useDeviceApps } from '../../hooks/useDeviceApps' import { ThisDeviceModel } from './model' -import { OPTIONS, SettingRow, SWITCH_TEXT, UNDER_SERVICES } from './shared' +import { appSettings, SettingRow, SWITCH_TEXT } from './shared' /* This device's Advanced (pages/ThisDevicePage.tsx, /this-device/advanced): what is changed seldom — what the device - offers beyond the three switches (exit node, the console and its AI commands, any port, proxy, the relay), a phone's permissions, + offers beyond the three switches (exit node, its apps and their settings, any port, proxy, the relay), a phone's permissions, the app's own Open at login, the detailed logging and the diagnostics, and last its removal. */ export const ThisDeviceAdvanced: React.FC<{ device: ThisDevice; m: ThisDeviceModel }> = ({ device, m }) => { const { t, has, status, kind, permissions, logging, app } = m const d = status?.device - // An option is listed under the setting it belongs to; one whose setting is not listed stands on its own. - const options = (name: string) => m.listed.filter(s => OPTIONS[s.name]?.of === name) - const standing = m.listed.filter(s => !m.listed.some(p => p.name === OPTIONS[s.name]?.of)) + // Its apps' words, as the API says them (the device by its UID): its settings name none (shared appSettings). + const { apps } = useDeviceApps(d?.uid, { offers: false }) + const words = appSettings(m.listed, apps) + // An option is listed under the app it belongs to; one whose app is not listed stands on its own. + const options = (name: string) => m.listed.filter(s => words.of(s) === name) + const standing = m.listed.filter(s => !words.of(s)) const heading = (text: string) => ( {text} @@ -29,9 +33,9 @@ export const ThisDeviceAdvanced: React.FC<{ device: ThisDevice; m: ThisDeviceMod m.setSetting(s.name, value)} /> @@ -39,7 +43,7 @@ export const ThisDeviceAdvanced: React.FC<{ device: ThisDevice; m: ThisDeviceMod m.setSetting(o.name, value)} diff --git a/frontend/src/components/thisDevice/shared.tsx b/frontend/src/components/thisDevice/shared.tsx index ce95092d8..e6f34f638 100644 --- a/frontend/src/components/thisDevice/shared.tsx +++ b/frontend/src/components/thisDevice/shared.tsx @@ -3,19 +3,20 @@ import { useTranslation } from 'react-i18next' import { Box, ListItem, ListItemIcon, ListItemText, MenuItem, Switch, TextField } from '@mui/material' import { Icon } from '../Icon' import { stateLine } from '../../helpers/appsHelper' +import type { DeviceApp } from '../../services/graphQLDeviceApps' import { DeviceSetting, DeviceStatus, ExitRef, SettingValue } from '../../services/thisDevice' // What This device's parts share (pages/ThisDevicePage.tsx): the rows, the notes, and the words for each state. export type T = (k: string, d: string, v?: any) => string +// The device's own settings' titles. An app's are its own (appSettings). export const SETTING_TITLES: { [name: string]: string } = { subnet: 'Access remote devices', exit_node: 'Exit node', printers: 'Show remote printers', services: 'Allow remote access to services', websocket: 'Relay', - 'remoteit.console': 'Console', any_port: 'Connections to any port', proxy: 'Proxy', scripts: 'Scripts', @@ -43,15 +44,30 @@ export const relayChoices = (t: T): { value: string; title: string; line: string }, ] -// Settings served only while the services are: not served while they are off, whatever their own value says. -export const UNDER_SERVICES = ['remoteit.console', 'any_port'] -// An app's settings are options of its row, as on the device page's Apps: set in under it, labelled by what they allow. -// Each option is named here with the setting whose row it sits under, and its words (the device page's). -export const OPTIONS: { [name: string]: { of: string; title: (t: T) => string } } = { - 'remoteit.console.ai_commands': { - of: 'remoteit.console', - title: t => t('deviceApps.consoleAiCommands', 'Allow AI commands'), - }, +// The device's own settings served only while the services are: not served while they are off, whatever their own +// value says. An app's is too where it serves a service (appSettings). +export const UNDER_SERVICES = ['any_port'] + +/* An app's settings on this device, as on the device page's Apps: its on or off, named by its id — the daemon says it + is an app's (setting.app), or the API names an app by it —, and its own settings (.) options of its row, + set in under it. Their words are the API's (the device's apps, read by its UID): the app's name, and its release's + labels; where the API does not say, their names. Its on or off is not served while the services are off where the + app serves a service (its protocol). Nothing here names an app. */ +export function appSettings(listed: DeviceSetting[], apps?: DeviceApp[] | null) { + const app = (name: string) => apps?.find(a => a.id === name) + const isApp = (setting: DeviceSetting) => !!setting.app || !!app(setting.name) + // The app row an option sits under. + const of = (setting: DeviceSetting) => + listed.find(parent => isApp(parent) && setting.name.startsWith(`${parent.name}.`))?.name + const title = (setting: DeviceSetting): string | undefined => { + const own = app(setting.name) + if (own) return own.name + const parent = of(setting) + return parent ? app(parent)?.settings.find(s => `${parent}.${s.name}` === setting.name)?.label : undefined + } + const underServices = (setting: DeviceSetting) => + UNDER_SERVICES.includes(setting.name) || !!app(setting.name)?.protocol + return { of, title, underServices } } // A switch's words keep clear of the switch at the row's end, at a phone's width too. export const SWITCH_TEXT = { paddingRight: '72px' } @@ -170,7 +186,7 @@ export const SettingRow: React.FC<{ title?: string // websocket's: whether the relay carries the device's traffic now. relayUsing?: boolean - // Not served while the services are off (the console, any port), whatever its own value says. + // Not served while the services are off (any port, an app that serves a service), whatever its own value says. notServed?: boolean // An option of the switch above it (the printers, Access's): set in under it. indent?: boolean diff --git a/frontend/src/helpers/appsHelper.test.ts b/frontend/src/helpers/appsHelper.test.ts index f1d322a99..b8d51a4da 100644 --- a/frontend/src/helpers/appsHelper.test.ts +++ b/frontend/src/helpers/appsHelper.test.ts @@ -1,6 +1,19 @@ import { describe, it, expect } from 'vitest' import type { TFunction } from 'i18next' -import { outcomeLine, stateLine, stateWord, withdrawal } from './appsHelper' +import { + appHost, + appIcon, + capabilitiesLine, + capabilityWords, + isAppService, + offered, + outcomeLine, + serviceApp, + stateLine, + stateWord, + withdrawal, +} from './appsHelper' +import type { DeviceApp } from '../services/graphQLDeviceApps' const t = ((_key: string, text: string, values?: any) => text.replace(/{{(\w+)}}/g, (_, k) => values?.[k] ?? '')) as unknown as TFunction @@ -56,3 +69,62 @@ describe('a many-device call’s outcome a device (DeviceAppChange.outcome)', () expect(line('refused')).toBe('Refused') }) }) + +describe('what an app asks of remote.it, in words', () => { + it('each capability as the catalogue and the consent say it; one unknown by its name', () => { + expect(capabilityWords(t, 'person-accounts')).toBe('Keeps accounts for the people you share with') + expect(capabilityWords(t, 'person-certificates')).toBe('Signs in people by remote.it certificate') + expect(capabilityWords(t, 'ssh-exec')).toBe('AI commands go through this app') + expect(capabilityWords(t, 'gpu')).toBe('gpu') + expect(capabilitiesLine(t, ['person-certificates', 'ssh-exec'])).toBe( + 'Signs in people by remote.it certificate · AI commands go through this app' + ) + expect(capabilitiesLine(t, [])).toBe('') + }) + + it('an offered app keeps what its catalogue entry says of it', () => { + const app = offered({ + id: 'acme.shell', + name: 'Shell', + publisher: 'Acme', + description: null, + root: true, + version: '1.0.0', + refused: null, + needsNewer: false, + protocol: 'ssh', + capabilities: ['person-certificates'], + }) + expect(app).toMatchObject({ protocol: 'ssh', capabilities: ['person-certificates'], sessions: [], sessionsOpen: 0 }) + }) +}) + +describe('an app’s icon and service, from what the API says — never its id', () => { + it('its icon from how its service opens', () => { + expect(appIcon('ssh')).toBe('terminal') + expect(appIcon('https')).toBe('globe') + expect(appIcon('http')).toBe('globe') + expect(appIcon('tcp')).toBe('cube') + expect(appIcon(null)).toBe('cube') + }) + + const app = (id: string, serviceId: string | null) => ({ id, serviceId } 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') + expect(isAppService({ host: 'remoteit-app-acme-shell' })).toBe(true) + expect(isAppService({ host: 'localhost' })).toBe(false) + expect(isAppService(undefined)).toBe(false) + // No app is known by a host of its own: the console's service is at its app host like any app's. + expect(isAppService({ host: 'remoteit-console' })).toBe(false) + }) + + it('the app naming the service, or — disabled, naming none — the one at whose host it is', () => { + const service = { id: 'S5', host: 'remoteit-app-acme-shell' } + expect(serviceApp([app('acme.files', 'S4'), app('acme.shell', 'S5')], service)?.id).toBe('acme.shell') + expect(serviceApp([app('acme.shell', null)], service)?.id).toBe('acme.shell') + expect(serviceApp([app('acme.shell', 'S9')], service)).toBeUndefined() + expect(serviceApp([app('acme.shell', 'S5')], { id: 'S5', host: 'localhost' })).toBeUndefined() + expect(serviceApp(null, service)).toBeUndefined() + }) +}) diff --git a/frontend/src/helpers/appsHelper.ts b/frontend/src/helpers/appsHelper.ts index 3ac5a83cf..29c06fc50 100644 --- a/frontend/src/helpers/appsHelper.ts +++ b/frontend/src/helpers/appsHelper.ts @@ -27,6 +27,67 @@ export const runsAsLine = (t: TFunction, root: boolean) => export const runsAsWord = (t: TFunction, root: boolean) => root ? t('apps.runsAsRoot', 'Runs as root') : t('apps.restricted', 'Restricted') +/* What an app asks of the platform beyond an ordinary app's (its capabilities), each in words: shown beside Runs as + root wherever it is offered, and part of the consent to it (presence-contract docs/self-contained-apps.md, + "Manifest"). One this portal does not know is said by its name. */ +export function capabilityWords(t: TFunction, capability: string): string { + switch (capability) { + case 'person-accounts': + return t('apps.capabilityPersonAccounts', 'Keeps accounts for the people you share with') + case 'person-certificates': + return t('apps.capabilityPersonCertificates', 'Signs in people by remote.it certificate') + case 'ssh-exec': + return t('apps.capabilitySshExec', 'AI commands go through this app') + default: + return capability + } +} + +export const capabilitiesLine = (t: TFunction, capabilities: string[] = []) => + capabilities.map(capability => capabilityWords(t, capability)).join(' · ') + +// An app's icon, from how its service opens: a terminal, a page, a screen, else a box. No app has one of its own. +export const appIcon = (protocol?: string | null) => + protocol === 'ssh' + ? 'terminal' + : protocol === 'http' || protocol === 'https' + ? 'globe' + : protocol === 'vnc' || protocol === 'rdp' + ? 'desktop' + : 'cube' + +// Open, in the words of how its service opens (its protocol): a page, a screen, else its service's connection. +export function openWord(t: TFunction, protocol?: string | null): string { + switch (protocol) { + case 'http': + case 'https': + return t('deviceApps.openPage', 'Open page') + case 'vnc': + case 'rdp': + return t('deviceApps.openScreen', 'Open screen') + default: + return t('deviceApps.open', 'Open') + } +} + +/* An app's service's host (graphql src/lib/service-host.ts appHost): remoteit-app--, the id's dot a + dash — the device itself, which its daemon serves. Every app's service is at its app's host, so only such a + service is looked for among its device's apps. */ +const APP_HOST_PREFIX = 'remoteit-app-' +export const appHost = (id: string) => `${APP_HOST_PREFIX}${id.toLowerCase().replace('.', '-')}` +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. */ +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.serviceId && appHost(app.id) === hostOf(service)) + ) +} + // 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' @@ -268,6 +329,11 @@ export const offered = (app: AvailableApp): DeviceApp => ({ state: 'disabled', detail: null, serviceId: null, + protocol: app.protocol ?? null, + capabilities: app.capabilities ?? [], + hostKey: null, + sessions: [], + sessionsOpen: 0, settings: [], }) diff --git a/frontend/src/helpers/sshHelper.test.ts b/frontend/src/helpers/sshHelper.test.ts index a58159e58..94b68c7e4 100644 --- a/frontend/src/helpers/sshHelper.test.ts +++ b/frontend/src/helpers/sshHelper.test.ts @@ -1,5 +1,5 @@ import { describe, it, expect } from 'vitest' -import { isConsoleService, sshCommand } from './sshHelper' +import { opensTerminal, sshCommand } from './sshHelper' describe('sshHelper', () => { it('is the plain ssh command, the port named only when it is not 22', () => { @@ -8,10 +8,14 @@ describe('sshHelper', () => { expect(sshCommand('pi-evan.on.remote.it')).toBe('ssh pi-evan.on.remote.it') }) - it('knows the console by its host, an SSH service', () => { - expect(isConsoleService({ typeID: 28, host: 'remoteit-console' })).toBe(true) - expect(isConsoleService({ typeID: 28, host: 'localhost' })).toBe(false) - expect(isConsoleService({ typeID: 8, host: 'remoteit-console' })).toBe(false) - expect(isConsoleService(undefined)).toBe(false) + 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) + expect( + opensTerminal({ protocol: 'ssh', capabilities: ['person-accounts', 'person-certificates', 'ssh-exec'] }) + ).toBe(true) + expect(opensTerminal({ protocol: 'ssh', capabilities: ['ssh-exec'] })).toBe(false) + expect(opensTerminal({ protocol: 'https', capabilities: ['person-certificates'] })).toBe(false) + expect(opensTerminal({ protocol: null, capabilities: [] })).toBe(false) + expect(opensTerminal(undefined)).toBe(false) }) }) diff --git a/frontend/src/helpers/sshHelper.ts b/frontend/src/helpers/sshHelper.ts index 725856cc5..25f22cdf2 100644 --- a/frontend/src/helpers/sshHelper.ts +++ b/frontend/src/helpers/sshHelper.ts @@ -1,9 +1,14 @@ +import type { DeviceApp } 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 the console takes — so its command works there as it is. */ + (connectd remoteit-device ssh-config), which an app that signs people in by certificate takes — so its command works + there as it is. */ -/** The console's service: SSH, its host the device's console (graphql CONSOLE_HOST). */ -export const isConsoleService = (service?: Pick) => - service?.typeID === 28 && service?.host === 'remoteit-console' +/** 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') /** 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 26ef8d190..c6b0326ec 100644 --- a/frontend/src/hooks/useDeviceApps.test.tsx +++ b/frontend/src/hooks/useDeviceApps.test.tsx @@ -12,7 +12,6 @@ const { read, setApp, addApp, setRelease, removeApp, setSetting, available } = v setSetting: vi.fn(), })) vi.mock('../services/graphQLDeviceApps', () => ({ - CONSOLE: 'remoteit.console', graphQLDeviceApps: read, graphQLAvailableApps: available, graphQLSetDeviceAppEnabled: setApp, @@ -23,7 +22,7 @@ vi.mock('../services/graphQLDeviceApps', () => ({ refused: (r: any) => !!r && typeof r === 'object' && 'reason' in r, })) -import { DeviceApps, useDeviceApps } from './useDeviceApps' +import { DeviceApps, ServiceApp, useDeviceApps, useServiceApp } from './useDeviceApps' ;(globalThis as any).IS_REACT_ACT_ENVIRONMENT = true const aiCommands = (value: boolean) => ({ @@ -58,8 +57,13 @@ const app = (state: string, enabled = state !== 'disabled') => ({ let root: Root const seen: Record = {} -const Apps = ({ deviceId, name }: { deviceId?: string; name: string }) => { - seen[name] = useDeviceApps(deviceId) +const Apps = ({ deviceId, name, offers }: { deviceId?: string; name: string; offers?: boolean }) => { + seen[name] = useDeviceApps(deviceId, offers === undefined ? undefined : { offers }) + return null +} +const served: Record = {} +const Serving = ({ service, name }: { service: Partial; name: string }) => { + served[name] = useServiceApp({ id: 'D1' } as IDevice, service as IService) return null } @@ -88,7 +92,7 @@ describe('useDeviceApps', () => { read.mockResolvedValue([app('disabled'), { ...app('running'), id: 'remoteit.files' }]) available.mockResolvedValue([]) await act(async () => { - await seen.a.turn(seen.a.console!, true) + await seen.a.turn(seen.a.apps![0], true) }) expect(available).toHaveBeenCalledTimes(2) expect(seen.a.available).toEqual([]) @@ -108,8 +112,8 @@ describe('useDeviceApps', () => { ) expect(read).toHaveBeenCalledTimes(1) - expect(seen.a.console?.state).toBe('disabled') - expect(seen.b.console?.state).toBe('disabled') + expect(seen.a.apps?.[0].state).toBe('disabled') + expect(seen.b.apps?.[0].state).toBe('disabled') expect(seen.none.apps).toBeUndefined() }) @@ -123,12 +127,12 @@ describe('useDeviceApps', () => { read.mockResolvedValue([app('running')]) let done: unknown await act(async () => { - done = await seen.a.turn(seen.a.console!, true) + done = await seen.a.turn(seen.a.apps![0], true) }) expect(done).toBe(true) expect(setApp).toHaveBeenCalledWith('D1', 'remoteit.console', true, undefined) - expect(seen.a.console?.state).toBe('running') - expect(seen.b.console?.state).toBe('running') + expect(seen.a.apps?.[0].state).toBe('running') + expect(seen.b.apps?.[0].state).toBe('running') expect(seen.a.switching).toBeUndefined() }) @@ -136,7 +140,7 @@ describe('useDeviceApps', () => { await render() read.mockResolvedValue([app('running')]) await act(async () => { - await seen.a.turn(seen.a.console!, true, true) + await seen.a.turn(seen.a.apps![0], true, true) }) expect(setApp).toHaveBeenCalledWith('D1', 'remoteit.console', true, true) }) @@ -148,7 +152,7 @@ describe('useDeviceApps', () => { read.mockResolvedValueOnce([app('starting')]).mockResolvedValue([app('running')]) let turning: Promise | undefined act(() => { - turning = seen.a.turn(seen.a.console!, true) + turning = seen.a.turn(seen.a.apps![0], true) }) await act(async () => { await vi.advanceTimersByTimeAsync(2_000) @@ -157,7 +161,7 @@ describe('useDeviceApps', () => { await turning }) expect(read).toHaveBeenCalledTimes(3) // the first read, then starting, then running - expect(seen.a.console?.state).toBe('running') + expect(seen.a.apps?.[0].state).toBe('running') } finally { vi.useRealTimers() } @@ -168,7 +172,7 @@ describe('useDeviceApps', () => { setApp.mockResolvedValue({ reason: 'Managed by its product Kiosks' }) let done: unknown await act(async () => { - done = await seen.a.turn(seen.a.console!, true) + done = await seen.a.turn(seen.a.apps![0], true) }) expect(done).toEqual({ reason: 'Managed by its product Kiosks' }) expect(read).toHaveBeenCalledTimes(1) @@ -190,13 +194,13 @@ describe('useDeviceApps', () => { try { await render() await act(async () => { - await seen.a.setRelease(seen.a.console!, { version: '' }) + await seen.a.setRelease(seen.a.apps![0], { version: '' }) }) expect(setRelease).toHaveBeenCalledWith('D1', 'remoteit.console', { version: '' }) read.mockResolvedValueOnce([app('removing', false)]).mockResolvedValue([]) let removing: Promise | undefined act(() => { - removing = seen.a.remove(seen.a.console!) + removing = seen.a.remove(seen.a.apps![0]) }) await act(async () => { await vi.advanceTimersByTimeAsync(2_000) @@ -219,10 +223,51 @@ describe('useDeviceApps', () => { ) await act(async () => { - await seen.a.setSetting(seen.a.console!, 'ai_commands', false) + await seen.a.setSetting(seen.a.apps![0], 'ai_commands', false) }) expect(setSetting).toHaveBeenCalledWith('D1', 'remoteit.console', 'ai_commands', false) - expect(seen.a.console?.settings[0].value).toBe(false) - expect(seen.b.console?.settings[0].value).toBe(false) + expect(seen.a.apps?.[0].settings[0].value).toBe(false) + expect(seen.b.apps?.[0].settings[0].value).toBe(false) + }) +}) + +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, + }) + + it('the app naming the service; while disabled, the app whose host the service is at', async () => { + read.mockResolvedValue([app('running'), shell('running')]) + await render() + expect(served.a.app?.id).toBe('acme.shell') + act(() => root.unmount()) + read.mockResolvedValue([app('running'), shell('disabled')]) + await render() + expect(served.b.app?.id).toBe('acme.shell') + act(() => root.unmount()) + // One naming another service is not this one's: an earlier service of it, stopped. + read.mockResolvedValue([shell('running', { serviceId: 'S9' })]) + await render() + expect(served.c.app).toBeUndefined() + }) + + it('reads nothing for a service at no app’s host, and never what the device may add', async () => { + await render() + expect(read).not.toHaveBeenCalled() + expect(served.a.app).toBeUndefined() + act(() => root.unmount()) + await render() + expect(read).toHaveBeenCalledWith('D1') + expect(available).not.toHaveBeenCalled() + }) + + it('reads nothing of what the device may add where the part asking offers none', async () => { + await render() + expect(read).toHaveBeenCalledWith('D1') + expect(available).not.toHaveBeenCalled() + expect(seen.a.available).toBeUndefined() }) }) diff --git a/frontend/src/hooks/useDeviceApps.ts b/frontend/src/hooks/useDeviceApps.ts index 9273e33fc..e04ed1675 100644 --- a/frontend/src/hooks/useDeviceApps.ts +++ b/frontend/src/hooks/useDeviceApps.ts @@ -3,7 +3,6 @@ import { AppChange, AppRelease, AvailableApp, - CONSOLE, DeviceApp, graphQLAddDeviceApp, graphQLAvailableApps, @@ -14,11 +13,12 @@ import { graphQLSetDeviceAppSetting, refused, } from '../services/graphQLDeviceApps' +import { isAppService, serviceApp } from '../helpers/appsHelper' type Read = ReturnType -// One read per device for every part of a page that asks in the same moment: its Apps section, the console's row in -// its services and the console's connect panel. +// One read per device for every part of a page that asks in the same moment: its Apps section, and an app's service's +// row in its services and connect panel. const reading = new Map() function read(deviceId: string): Read { let answer = reading.get(deviceId) @@ -35,7 +35,6 @@ const tell = (deviceId: string, apps: DeviceApp[] | null) => watchers.forEach(wa export type DeviceApps = { apps: DeviceApp[] | null | undefined // undefined while read; null where the API has no apps - console?: DeviceApp // What it may add (the device's catalogue): read once its apps are, and again after one is added or removed. available?: AvailableApp[] switching?: string // the app being changed, waited for @@ -54,8 +53,9 @@ const waiting = (app?: DeviceApp) => app?.state === 'starting' || app?.state === /* A device's apps (services/graphQLDeviceApps): added, enabled or disabled, its channel and pin, removed, and its settings. The device acts within seconds: what it says is waited for, up to half a minute — while it starts the app, - or until it says the app is gone. */ -export function useDeviceApps(deviceId?: string): DeviceApps { + or until it says the app is gone. What it may add is read too, unless the part asking does not offer any (offers + false). */ +export function useDeviceApps(deviceId?: string, { offers = true }: { offers?: boolean } = {}): DeviceApps { const [apps, setApps] = useState() const [switching, setSwitching] = useState() const [available, setAvailable] = useState() @@ -63,13 +63,13 @@ export function useDeviceApps(deviceId?: string): DeviceApps { useEffect(() => { setAvailable(undefined) - if (!deviceId || apps === undefined || apps === null) return + if (!offers || !deviceId || apps === undefined || apps === null) return let current = true graphQLAvailableApps(deviceId).then(result => current && setAvailable(result)) return () => { current = false } - }, [deviceId, ids, apps === null]) + }, [offers, deviceId, ids, apps === null]) useEffect(() => { setApps(undefined) @@ -142,7 +142,6 @@ export function useDeviceApps(deviceId?: string): DeviceApps { return { apps, - console: apps?.find(app => app.id === CONSOLE), available, switching, turn, @@ -151,3 +150,11 @@ export function useDeviceApps(deviceId?: string): DeviceApps { setSetting, } } + +/* 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 } +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) } +} diff --git a/frontend/src/i18n/locales/de/app.json b/frontend/src/i18n/locales/de/app.json index 313d463b3..c9a736d97 100644 --- a/frontend/src/i18n/locales/de/app.json +++ b/frontend/src/i18n/locales/de/app.json @@ -223,6 +223,11 @@ "anyVersion": "", "cancel": "", "candidate": "", + "capabilitiesAlso": "Außerdem verlangt sie von remote.it:", + "capabilitiesAsks": "Sie verlangt von remote.it:", + "capabilityPersonAccounts": "Führt Konten für die Personen, mit denen Sie teilen", + "capabilityPersonCertificates": "Meldet Personen per remote.it-Zertifikat an", + "capabilitySshExec": "KI-Befehle laufen über diese App", "catalogFailed": "", "catalogUnserved": "", "channel": "", @@ -330,7 +335,15 @@ "searchDevices": "", "service": "", "serviceLine": "", + "servicePort": "", "serviceStopped": "", + "sessionAs": "als {{login}}", + "sessionByAi": "von einer KI", + "sessionId": "", + "sessions": "Sitzungen", + "sessionSince": "seit {{when}}", + "sessionsMore": "{{number}} weitere nicht aufgeführt", + "sessionsOpen": "{{number}} jetzt offen", "settings": "", "showMore": "", "state": "", @@ -365,6 +378,13 @@ "yourDevices": "", "yours": "" }, + "appTerminal": { + "disabled": "{{app}} ist deaktiviert: Aktivieren Sie die App, um sie in Web-SSH zu öffnen", + "enable": "Aktivieren", + "open": "In Web-SSH öffnen", + "openInBrowser": "In Web-SSH öffnen, in Ihrem Browser", + "starting": "{{app}} startet: Web-SSH öffnet sie, sobald sie läuft" + }, "appType": { "adminPanel": { "title": "Admin-Panel", @@ -886,13 +906,6 @@ "permissionSubLabel": "Erfordert die Geräteberechtigung „Verwalten“", "webAuthenticationLabel": "Web-Authentifizierung" }, - "consoleTerminal": { - "disabled": "", - "enable": "", - "open": "", - "openInBrowser": "", - "starting": "" - }, "copyCodeBlock": { "copy": "Kopieren", "copyCode": "Code kopieren", @@ -1167,11 +1180,6 @@ "consentedDevice": "Auf dem Gerät von {{by}} als root eingeschaltet, {{when}}", "consentedProduct": "Läuft als root mit der Zustimmung seines Produkts: {{by}}, {{when}}", "consentedRegistration": "Läuft als root, seit sich dieses Gerät registriert hat, {{when}}", - "console": "", - "consoleAiCommands": "", - "consoleAiCommandsHelp": "", - "consoleDisabled": "", - "consoleRunning": "", "converting": "", "hostKey": "", "needsNewer": "Benötigt ein neueres remote.it auf diesem Gerät", @@ -1179,6 +1187,8 @@ "noMatch": "Muss {{pattern}} entsprechen", "noRelease": "Hier noch keine Version verfügbar", "open": "Öffnen", + "openPage": "", + "openScreen": "", "openTerminal": "", "publisher": "", "rootAction": "", diff --git a/frontend/src/i18n/locales/en/app.json b/frontend/src/i18n/locales/en/app.json index d561a5ab1..73676d20f 100644 --- a/frontend/src/i18n/locales/en/app.json +++ b/frontend/src/i18n/locales/en/app.json @@ -223,6 +223,11 @@ "anyVersion": "Any version", "cancel": "Cancel", "candidate": "Candidate {{version}} to {{share}}% of devices", + "capabilitiesAlso": "It also asks of remote.it:", + "capabilitiesAsks": "It asks of remote.it:", + "capabilityPersonAccounts": "Keeps accounts for the people you share with", + "capabilityPersonCertificates": "Signs in people by remote.it certificate", + "capabilitySshExec": "AI commands go through this app", "catalogFailed": "The apps could not be read.", "catalogUnserved": "This server does not have the app catalogue yet.", "channel": "Channel", @@ -330,7 +335,15 @@ "searchDevices": "Search devices…", "service": "Service", "serviceLine": "{{name}} · port {{port}}", + "servicePort": "Port people connect to", "serviceStopped": "Stopped while the app is disabled: enable it to open it", + "sessionAs": "as {{login}}", + "sessionByAi": "by an AI", + "sessionId": "Session {{id}}", + "sessions": "Sessions", + "sessionSince": "since {{when}}", + "sessionsMore": "{{number}} more not listed", + "sessionsOpen": "{{number}} open now", "settings": "Settings", "showMore": "Show more", "state": "State", @@ -365,6 +378,13 @@ "yourDevices": "Your devices", "yours": "Yours" }, + "appTerminal": { + "disabled": "{{app}} is disabled: enable it to open it in web SSH", + "enable": "Enable it", + "open": "Open in web SSH", + "openInBrowser": "Open in web SSH, in your browser", + "starting": "{{app}} is starting: web SSH opens it once it runs" + }, "appType": { "adminPanel": { "title": "Admin Panel", @@ -886,13 +906,6 @@ "permissionSubLabel": "Requires device 'Manage' permission", "webAuthenticationLabel": "Web Authentication" }, - "consoleTerminal": { - "disabled": "The console is disabled: enable it to open it in web SSH", - "enable": "Enable it", - "open": "Open in web SSH", - "openInBrowser": "Open in web SSH, in your browser", - "starting": "The console is starting: web SSH opens it once it runs" - }, "copyCodeBlock": { "copy": "Copy", "copyCode": "Copy code", @@ -1167,11 +1180,6 @@ "consentedDevice": "Turned on as root on the device by {{by}}, {{when}}", "consentedProduct": "Runs as root by its product’s consent: {{by}}, {{when}}", "consentedRegistration": "Runs as root since this device registered, {{when}}", - "console": "Console", - "consoleAiCommands": "Allow AI commands", - "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.", - "consoleDisabled": "Disabled — a terminal on this device, from this app, by certificate", - "consoleRunning": "Running — logins by certificate, nothing listening on the device", "converting": "Converting from the old install", "hostKey": "Host key {{key}}", "needsNewer": "Needs a newer remote.it on this device", @@ -1179,6 +1187,8 @@ "noMatch": "Must match {{pattern}}", "noRelease": "No release of it here yet", "open": "Open", + "openPage": "Open page", + "openScreen": "Open screen", "openTerminal": "Open terminal", "publisher": "By {{publisher}}", "rootAction": "Turn on with full control", diff --git a/frontend/src/i18n/locales/es/app.json b/frontend/src/i18n/locales/es/app.json index a853b27d4..b58d51084 100644 --- a/frontend/src/i18n/locales/es/app.json +++ b/frontend/src/i18n/locales/es/app.json @@ -226,6 +226,11 @@ "anyVersion": "", "cancel": "", "candidate": "", + "capabilitiesAlso": "Además, le pide a remote.it:", + "capabilitiesAsks": "Le pide a remote.it:", + "capabilityPersonAccounts": "Mantiene cuentas para las personas con las que comparte", + "capabilityPersonCertificates": "Inicia la sesión de las personas con un certificado de remote.it", + "capabilitySshExec": "Los comandos de IA pasan por esta app", "catalogFailed": "", "catalogUnserved": "", "channel": "", @@ -337,7 +342,15 @@ "searchDevices": "", "service": "", "serviceLine": "", + "servicePort": "", "serviceStopped": "", + "sessionAs": "como {{login}}", + "sessionByAi": "por una IA", + "sessionId": "", + "sessions": "Sesiones", + "sessionSince": "desde {{when}}", + "sessionsMore": "{{number}} más sin listar", + "sessionsOpen": "{{number}} abiertas ahora", "settings": "", "showMore": "", "state": "", @@ -372,6 +385,13 @@ "yourDevices": "", "yours": "" }, + "appTerminal": { + "disabled": "{{app}} está desactivada: actívela para abrirla en SSH web", + "enable": "Activarla", + "open": "Abrir en SSH web", + "openInBrowser": "Abrir en SSH web, en su navegador", + "starting": "{{app}} se está iniciando: SSH web la abre en cuanto se ejecute" + }, "appType": { "adminPanel": { "title": "Panel de administración", @@ -895,13 +915,6 @@ "permissionSubLabel": "Requiere el permiso de dispositivo \"Administrar\"", "webAuthenticationLabel": "Autenticación web" }, - "consoleTerminal": { - "disabled": "", - "enable": "", - "open": "", - "openInBrowser": "", - "starting": "" - }, "copyCodeBlock": { "copy": "Copiar", "copyCode": "Copiar código", @@ -1181,11 +1194,6 @@ "consentedDevice": "Activada como root en el dispositivo por {{by}}, {{when}}", "consentedProduct": "Se ejecuta como root con el consentimiento de su producto: {{by}}, {{when}}", "consentedRegistration": "Se ejecuta como root desde que este dispositivo se registró, {{when}}", - "console": "", - "consoleAiCommands": "", - "consoleAiCommandsHelp": "", - "consoleDisabled": "", - "consoleRunning": "", "converting": "", "hostKey": "", "needsNewer": "Necesita un remote.it más reciente en este dispositivo", @@ -1193,6 +1201,8 @@ "noMatch": "Debe coincidir con {{pattern}}", "noRelease": "Todavía no hay una versión aquí", "open": "Abrir", + "openPage": "", + "openScreen": "", "openTerminal": "", "publisher": "", "rootAction": "", diff --git a/frontend/src/i18n/locales/ja/app.json b/frontend/src/i18n/locales/ja/app.json index 9bfbf3528..48a387d7a 100644 --- a/frontend/src/i18n/locales/ja/app.json +++ b/frontend/src/i18n/locales/ja/app.json @@ -220,6 +220,11 @@ "anyVersion": "", "cancel": "", "candidate": "", + "capabilitiesAlso": "さらに remote.it に求めるもの:", + "capabilitiesAsks": "remote.it に求めるもの:", + "capabilityPersonAccounts": "共有相手のアカウントを保持します", + "capabilityPersonCertificates": "remote.it の証明書でユーザーをサインインさせます", + "capabilitySshExec": "AI コマンドはこのアプリを経由します", "catalogFailed": "", "catalogUnserved": "", "channel": "", @@ -323,7 +328,15 @@ "searchDevices": "", "service": "", "serviceLine": "", + "servicePort": "", "serviceStopped": "", + "sessionAs": "{{login}} として", + "sessionByAi": "AI による", + "sessionId": "", + "sessions": "セッション", + "sessionSince": "{{when}} から", + "sessionsMore": "ほか {{number}} 件は一覧にありません", + "sessionsOpen": "現在 {{number}} 件が開いています", "settings": "", "showMore": "", "state": "", @@ -358,6 +371,13 @@ "yourDevices": "", "yours": "" }, + "appTerminal": { + "disabled": "{{app}} は無効です: Web SSH で開くには有効にしてください", + "enable": "有効にする", + "open": "Web SSH で開く", + "openInBrowser": "Web SSH で開く (ブラウザー)", + "starting": "{{app}} は起動中です: 実行されると Web SSH で開きます" + }, "appType": { "adminPanel": { "title": "管理パネル", @@ -877,13 +897,6 @@ "permissionSubLabel": "デバイスの「管理」権限が必要です", "webAuthenticationLabel": "Web認証" }, - "consoleTerminal": { - "disabled": "", - "enable": "", - "open": "", - "openInBrowser": "", - "starting": "" - }, "copyCodeBlock": { "copy": "コピー", "copyCode": "コードをコピー", @@ -1153,11 +1166,6 @@ "consentedDevice": "デバイス上で {{by}} が root として有効化 ({{when}})", "consentedProduct": "プロダクトの同意により root で実行: {{by}} ({{when}})", "consentedRegistration": "このデバイスの登録時から root で実行 ({{when}})", - "console": "", - "consoleAiCommands": "", - "consoleAiCommandsHelp": "", - "consoleDisabled": "", - "consoleRunning": "", "converting": "", "hostKey": "", "needsNewer": "このデバイスにはより新しい remote.it が必要です", @@ -1165,6 +1173,8 @@ "noMatch": "{{pattern}} に一致する必要があります", "noRelease": "ここではまだリリースがありません", "open": "開く", + "openPage": "", + "openScreen": "", "openTerminal": "", "publisher": "", "rootAction": "", diff --git a/frontend/src/pages/AppAddDialog.test.tsx b/frontend/src/pages/AppAddDialog.test.tsx index b72ac67e8..94f2504d0 100644 --- a/frontend/src/pages/AppAddDialog.test.tsx +++ b/frontend/src/pages/AppAddDialog.test.tsx @@ -210,6 +210,36 @@ describe('the root consent', () => { await select($('[data-app-add-version]'), '1.5.0-beta.2') expect($('[data-app-add-root]')).not.toBeNull() }) + + it('what it asks of remote.it is part of the consent — the release pinned’s, where one is', async () => { + const asks = ['person-accounts', 'person-certificates'] + const app = mockCatalogApp('acme.backup')! + catalog.mockResolvedValue({ + ...app, + root: true, + capabilities: asks, + releases: [{ ...app.releases[0], root: true, capabilities: ['ssh-exec'] }, ...app.releases.slice(1)], + }) + await render() + const said = () => + [...document.querySelectorAll('[data-app-add-root] [data-app-capability]')].map(c => c.textContent) + expect(said()).toEqual([ + '· Keeps accounts for the people you share with', + '· Signs in people by remote.it certificate', + ]) + await click($('[data-app-add-pin]')) + await select($('[data-app-add-version]'), '1.5.0-beta.2') + expect(said()).toEqual(['· AI commands go through this app']) + }) + + it('a restricted app says what it asks of remote.it above Add, with no consent asked', async () => { + catalog.mockResolvedValue({ ...mockCatalogApp('acme.backup'), capabilities: ['person-certificates'] }) + await render() + expect($('[data-app-add-root]')).toBeNull() + expect($('[data-app-add-capabilities]').textContent).toBe( + 'It asks of remote.it:· Signs in people by remote.it certificate' + ) + }) }) describe('Add, to a tag or a product', () => { diff --git a/frontend/src/pages/AppAddDialog.tsx b/frontend/src/pages/AppAddDialog.tsx index d25b58c98..a4d29d144 100644 --- a/frontend/src/pages/AppAddDialog.tsx +++ b/frontend/src/pages/AppAddDialog.tsx @@ -32,6 +32,7 @@ import { graphQLFetchDeviceCount } from '../services/graphQLDevice' import { AppChangeResults } from '../components/AppChangeResults' import { LoadingMessage } from '../components/LoadingMessage' import { Notice } from '../components/Notice' +import { AppCapabilities } from '../components/AppRootConsent' import { adminControlLine, channelName } from '../helpers/appsHelper' type Target = 'devices' | 'tag' | 'product' @@ -48,7 +49,8 @@ type Target = 'devices' | 'tag' | 'product' the product's root consent. Channel the account's, stable or beta; and a version to pin, where wanted. A root app (or a root release pinned) asks the person's yes in words before Add is offered: full control of each - device — of every device in the product, now and later, for a product. + device — of every device in the product, now and later, for a product —, and what else it asks of remote.it (its + capabilities, the release's), said in the same place; a restricted app says them above Add. Devices and a tag call addDeviceApps (at most 500 devices a call: more, and it says to add it to a product); each device's result is listed after — Added · Enabled · Already there · Refused: . */ @@ -124,6 +126,7 @@ export const AppAddDialog: React.FC = () => { const standing = ready?.releases.filter(r => !r.withdrawn) ?? [] const pinned = pinning && version ? standing.find(r => r.version === version) : undefined const root = pinned ? pinned.root : !!ready?.root + const capabilities = pinned ? pinned.capabilities : ready?.capabilities const product = products.find(p => p.id === productId) const count = target === 'devices' ? ticked.length : target === 'tag' ? tagCount ?? 0 : 0 const tooMany = target !== 'product' && count > MANY_DEVICES_MAX @@ -365,6 +368,14 @@ export const AppAddDialog: React.FC = () => { )} + {!root && !!capabilities?.length && ( + + + + )} {root && ( @@ -373,6 +384,7 @@ export const AppAddDialog: React.FC = () => { ? t('apps.rootProduct', '{{app}} runs as root: full control of every device in this product, now and later.', { app: ready.name }) : t('apps.rootDevices', '{{app}} runs as root: full control of each device.', { app: ready.name })} + ({ Notice: ({ children }: any) =>
({ LoadingMessage: () =>
})) vi.mock('../components/Link', () => ({ Link: ({ to, children, ...rest }: any) => {children} })) vi.mock('../components/Icon', () => ({ Icon: () => null })) -vi.mock('../components/firstPartyApps', () => ({ firstPartyApp: () => undefined })) vi.mock('../components/Confirm', () => ({ Confirm: ({ open, title, action, disabled, children, onConfirm, onDeny }: any) => open ? ( @@ -106,6 +105,7 @@ describe('the app in the catalogue', () => { expect(page.querySelector('[data-title]')?.textContent).toBe('Backup') expect(page.querySelector('[data-app-about]')?.textContent).toBe('1.4.0 · Acme · Verified: acme.com · Yours') expect(page.querySelector('[data-app-runs]')?.textContent).toBe('Restricted') + expect(page.querySelector('[data-app-asks]')).toBeNull() expect(page.querySelector('[data-app-platforms]')?.textContent).toBe('linux-amd64 · linux-arm64 · linux-arm64-musl') await click(page.querySelector('[data-app-add]')) expect(push).toHaveBeenCalledWith('/apps/acme.backup/add') @@ -122,6 +122,19 @@ describe('the app in the catalogue', () => { expect(page.querySelector('[data-app-runs]')?.textContent).toBe('Runs as root: full control of the device') }) + it('what it asks of remote.it beside how it runs — the app’s, and each release’s with its root', async () => { + params.appID = 'remoteit.console' + catalog.mockResolvedValue(mockCatalogApp('remoteit.console')) + const page = await render() + const asks = + 'Keeps accounts for the people you share with · Signs in people by remote.it certificate · AI commands go through this app' + expect(page.querySelector('[data-app-asks]')?.textContent).toBe(asks) + await click(page.querySelector('[data-app-release="1.4.0"]')) + expect(page.querySelector('[data-app-release-notes="1.4.0"]')?.textContent).toContain( + `Runs as root: full control of the device · ${asks}` + ) + }) + it('channels on this stage, a candidate’s share; the account’s channel set by setAccountAppChannel', async () => { const page = await render() expect(page.querySelector('[data-app-channel="beta"]')?.textContent).toContain('Candidate 1.5.0-rc.1 to 10% of devices') diff --git a/frontend/src/pages/AppPage.tsx b/frontend/src/pages/AppPage.tsx index 086b108c9..005c6afad 100644 --- a/frontend/src/pages/AppPage.tsx +++ b/frontend/src/pages/AppPage.tsx @@ -33,7 +33,6 @@ import { } from '../services/graphQLAppCatalog' import { DeviceAppChange, graphQLSetDeviceAppsRelease, refused } from '../services/graphQLDeviceApps' import { AppChangeResults } from '../components/AppChangeResults' -import { firstPartyApp } from '../components/firstPartyApps' import { LoadingMessage } from '../components/LoadingMessage' import { Container } from '../components/Container' import { Confirm } from '../components/Confirm' @@ -42,7 +41,16 @@ import { Notice } from '../components/Notice' import { Title } from '../components/Title' import { Link } from '../components/Link' import { Icon } from '../components/Icon' -import { channelName, day, heldBackLine, heldBackReason, releaseChannelName, stateWord } from '../helpers/appsHelper' +import { + appIcon, + capabilitiesLine, + channelName, + day, + heldBackLine, + heldBackReason, + releaseChannelName, + stateWord, +} from '../helpers/appsHelper' const RELEASES_PAGE = 20 // The version filter's choices besides a version: any (no filter), and none reported — catalogApp's devices(version: ""), @@ -55,12 +63,14 @@ const NO_VERSION = '-' /* The app in the catalogue (presence-server docs/device-apps-design.md, "The Apps pages", /apps/:appID), from catalogApp: - its name and version, its publisher (Verified, Yours), Runs as root or Restricted, its description and platforms; + its name and version, its publisher (Verified, Yours), Runs as root or Restricted and what else it asks of + remote.it (its capabilities, in words), its description and platforms; Add… (/apps/:appID/add), and Manage releases for the account's own publisher (the Publisher page, where releases are published); Channels on this stage — each channel's release, its candidate and to how many of the devices — and the channel this account follows (setAccountAppChannel); - Releases, newest first: each version, its date, where this stage's channels point at it, root, its platforms, + Releases, newest first: each version, its date, where this stage's channels point at it, root and its + capabilities, its platforms, withdrawn, and its notes opened in place; Show more; Your devices: how many in all, enabled, disabled, up to date and held back, and the held back by why (fleet.total, fleet.heldBackBy); each device's version running, channel, state, and up to date or held back with the reason in @@ -176,7 +186,7 @@ export const AppPage: React.FC = () => { - + {[ @@ -194,6 +204,11 @@ export const AppPage: React.FC = () => { ? t('apps.runsAsRootFull', 'Runs as root: full control of the device') : t('apps.restricted', 'Restricted')} + {!!app.capabilities.length && ( + + {capabilitiesLine(t, app.capabilities)} + + )} {app.description && ( {app.description} @@ -512,7 +527,7 @@ export const AppPage: React.FC = () => { } /* A release: its version, date, where this stage's channels point at it or that it was withdrawn, the first line of - its notes — opened in place to all of them, with root and its platforms. */ + its notes — opened in place to all of them, with root, what else it asks of remote.it and its platforms. */ const ReleaseRow: React.FC<{ release: CatalogAppRelease channels: CatalogAppChannel[] @@ -543,6 +558,7 @@ const ReleaseRow: React.FC<{ release.root ? t('apps.runsAsRootFull', 'Runs as root: full control of the device') : t('apps.restricted', 'Restricted'), + capabilitiesLine(t, release.capabilities), release.platforms.join(' · '), ] .filter(Boolean) diff --git a/frontend/src/pages/AppsPage.test.tsx b/frontend/src/pages/AppsPage.test.tsx index e20af7400..dd24807d9 100644 --- a/frontend/src/pages/AppsPage.test.tsx +++ b/frontend/src/pages/AppsPage.test.tsx @@ -17,7 +17,6 @@ vi.mock('../components/Gutters', () => ({ Gutters: ({ children }: any) =>
{ vi.mock('../components/Notice', () => ({ Notice: ({ children }: any) =>
{children}
})) vi.mock('../components/LoadingMessage', () => ({ LoadingMessage: () =>
})) vi.mock('../components/Icon', () => ({ Icon: () => null })) -vi.mock('../components/firstPartyApps', () => ({ firstPartyApp: () => undefined })) vi.mock('react-i18next', () => { const fill = (text: string, values?: any) => text.replace(/{{(\w+)}}/g, (_, k) => values?.[k] ?? '') return { @@ -69,6 +68,11 @@ describe('Apps, the account’s catalogue', () => { expect(backup.querySelector('[data-catalog-aside]')?.textContent).toBe('4 devices') const console = row(page, 'remoteit.console') expect(console.querySelector('[data-catalog-runs]')?.textContent).toBe('Runs as root: full control of the device') + // What it asks of remote.it, beside Runs as root; an ordinary app asks nothing. + expect(console.querySelector('[data-catalog-capabilities]')?.textContent).toBe( + 'Keeps accounts for the people you share with · Signs in people by remote.it certificate · AI commands go through this app' + ) + expect(backup.querySelector('[data-catalog-capabilities]')).toBeNull() expect(console.querySelector('[data-catalog-platforms]')?.textContent).toBe('linux · darwin · windows') expect(row(page, 'remoteit.files').querySelector('[data-catalog-aside]')?.textContent).toBe('—') }) diff --git a/frontend/src/pages/AppsPage.tsx b/frontend/src/pages/AppsPage.tsx index d3f052eca..a084332b9 100644 --- a/frontend/src/pages/AppsPage.tsx +++ b/frontend/src/pages/AppsPage.tsx @@ -104,6 +104,8 @@ export const AppsPage: React.FC = () => { verifiedDomain={app.publisher.verifiedDomain} own={app.publisher.own} root={app.root} + capabilities={app.capabilities} + protocol={app.protocol} description={app.description} platforms={app.version ? platformsLine(t, app.platforms) : t('apps.noRelease', 'No release here yet')} aside={ diff --git a/frontend/src/pages/DeviceAppCatalogPage.test.tsx b/frontend/src/pages/DeviceAppCatalogPage.test.tsx index 56fdf00ea..05e599889 100644 --- a/frontend/src/pages/DeviceAppCatalogPage.test.tsx +++ b/frontend/src/pages/DeviceAppCatalogPage.test.tsx @@ -3,6 +3,8 @@ import { createRoot, Root } from 'react-dom/client' import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest' const { apps, push } = vi.hoisted(() => ({ apps: { value: {} as any }, push: 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('react-router-dom', () => ({ useHistory: () => ({ push }) })) vi.mock('../services/Context', async () => ({ DeviceContext: (await import('react')).createContext({}) })) vi.mock('../hooks/useDeviceApps', () => ({ useDeviceApps: () => apps.value })) @@ -17,7 +19,6 @@ vi.mock('../components/Notice', () => ({ Notice: ({ children }: any) =>
({ LoadingMessage: () =>
})) vi.mock('../components/Link', () => ({ Link: ({ to, children }: any) => {children} })) vi.mock('../components/Icon', () => ({ Icon: () => null })) -vi.mock('../components/firstPartyApps', () => ({ firstPartyApp: () => undefined })) vi.mock('../components/Confirm', () => ({ Confirm: ({ open, title, children, onConfirm }: any) => open ? ( @@ -58,7 +59,7 @@ async function render(permissions = ['VIEW', 'CONNECT', 'MANAGE', 'SCRIPTING']) container = document.createElement('div') document.body.appendChild(container) root = createRoot(container) - const device = { id: 'D1', name: 'pi-kitchen', permissions } as unknown as IDevice + const device = { id: 'D1', name: 'pi-kitchen', accountId: 'A1', permissions } as unknown as IDevice await act(async () => root.render( @@ -155,4 +156,34 @@ describe('the catalogue for this device', () => { page = await render() expect(page.querySelector('[data-catalog-empty]')?.textContent).toBe('There is no app this device does not have already.') }) + + it('what each asks of remote.it, as graphql gives it for the release offered, beside Runs as root — and named in the consent', async () => { + apps.value.available = [ + available({ capabilities: [], protocol: 'https' }), + available({ + id: 'acme.shell', + name: 'Shell', + publisher: 'Acme', + root: true, + capabilities: ['person-accounts', 'person-certificates'], + protocol: 'ssh', + }), + ] + const page = await render() + expect(offer(page, 'acme.shell').querySelector('[data-catalog-capabilities]')?.textContent).toBe( + 'Keeps accounts for the people you share with · Signs in people by remote.it certificate' + ) + expect(offer(page, 'remoteit.files').querySelector('[data-catalog-capabilities]')).toBeNull() + await click(offer(page, 'acme.shell').querySelector('[data-available-add]')) + expect([...page.querySelectorAll('[data-confirm] [data-app-capability]')].map(c => c.textContent)).toEqual([ + '· Keeps accounts for the people you share with', + '· Signs in people by remote.it certificate', + ]) + await click(page.querySelector('[data-confirm-ok]')) + expect(turn).toHaveBeenCalledWith( + expect.objectContaining({ id: 'acme.shell', capabilities: ['person-accounts', 'person-certificates'] }), + true, + true + ) + }) }) diff --git a/frontend/src/pages/DeviceAppCatalogPage.tsx b/frontend/src/pages/DeviceAppCatalogPage.tsx index 222d72730..4b2f79af9 100644 --- a/frontend/src/pages/DeviceAppCatalogPage.tsx +++ b/frontend/src/pages/DeviceAppCatalogPage.tsx @@ -19,11 +19,12 @@ import { adminControlLine, offered } from '../helpers/appsHelper' /* The catalogue for this device (presence-server docs/device-apps-design.md, "The Apps pages", /devices/:deviceID/apps/add): the apps it may take and does not have (graphql's Device.availableApps) — remote.it's - and its own account's —, each with its publisher, Runs as root or Restricted, its description, and why it cannot be - added here where it cannot: its administrator refuses it, or its stage has no release of it yet; and where its - remote.it is too old to run it yet. A row opens the app in the catalogue; Add adds it here and enabled — a root app - only with the person's yes (components/AppRootConsent) —, then opens it on this device. Adding runs code on the - device: Scripting as well as Manage. */ + and its own account's —, each with its publisher, Runs as root or Restricted and what else it asks of remote.it (its + capabilities, as graphql gives them for the release its stage gives), its description, and why it + cannot be added here where it cannot: its administrator refuses it, or its stage has no release of it yet; and where + its remote.it is too old to run it yet. A row opens the app in the catalogue; Add adds it here and enabled — a root + app only with the person's yes (components/AppRootConsent), which names its capabilities too —, then opens it on + this device. Adding runs code on the device: Scripting as well as Manage. */ export const DeviceAppCatalogPage: React.FC = () => { const { t } = useTranslation() const history = useHistory() @@ -34,7 +35,8 @@ export const DeviceAppCatalogPage: React.FC = () => { const { flip, consent } = useAppSwitch( deviceApps, reason => setRefusal(reason || t('apps.notAdded', 'The app was not added.')), - app => device && history.push(`/devices/${device.id}/apps/${app.id}`) + app => device && history.push(`/devices/${device.id}/apps/${app.id}`), + device?.accountId ) if (!device) return @@ -91,6 +93,8 @@ export const DeviceAppCatalogPage: React.FC = () => { publisher={app.publisher} verifiedDomain={app.publisherVerifiedDomain} root={app.root} + capabilities={app.capabilities} + protocol={app.protocol} description={app.description} aside={app.version} onOpen={() => history.push(`/apps/${app.id}`)} diff --git a/frontend/src/pages/DeviceAppPage.test.tsx b/frontend/src/pages/DeviceAppPage.test.tsx index 11ce79509..89e676d67 100644 --- a/frontend/src/pages/DeviceAppPage.test.tsx +++ b/frontend/src/pages/DeviceAppPage.test.tsx @@ -2,23 +2,23 @@ import React, { act } from 'react' import { createRoot, Root } from 'react-dom/client' import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest' -const { apps, catalog, push, params } = vi.hoisted(() => ({ +const { apps, catalog, push, params, openTerminal } = vi.hoisted(() => ({ apps: { value: {} as any }, catalog: vi.fn(), push: vi.fn(), params: { appID: 'acme.backup' }, + openTerminal: 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 })) vi.mock('../hooks/useDeviceApps', () => ({ useDeviceApps: () => apps.value })) vi.mock('../hooks/useLocalSubnetName', () => ({ useSubnetName: () => 'pi.on.remote.it' })) -vi.mock('../helpers/terminalHelper', () => ({ openTerminal: vi.fn() })) +vi.mock('../helpers/terminalHelper', () => ({ openTerminal })) +vi.mock('../services/browser', () => ({ default: { isNative: false }, windowOpen: vi.fn() })) vi.mock('../services/graphQLDeviceApps', async () => ({ ...(await import('../services/deviceAppsShared')), - CONSOLE: 'remoteit.console', SCREENVIEW: 'remoteit.screenview', - graphQLSshHostKey: vi.fn(async () => 'SHA256:abc'), })) vi.mock('../components/DeviceAppSetting', () => ({ DeviceAppSetting: ({ setting, label, disabled, onChange }: any) => ( @@ -35,12 +35,12 @@ vi.mock('../components/LoadingMessage', () => ({ LoadingMessage: () =>
({ Link: ({ to, children, ...rest }: any) => {children} })) vi.mock('../components/Icon', () => ({ Icon: () => null })) vi.mock('../components/Confirm', () => ({ - Confirm: ({ open, title, action, children, onConfirm, onDeny }: any) => + Confirm: ({ open, title, action, children, disabled, onConfirm, onDeny }: any) => open ? (
{title} {children} -