From 678ac21ac817070eb99d3075468d740d0e5515b4 Mon Sep 17 00:00:00 2001 From: KayaanT <34585438+KayaanT@users.noreply.github.com> Date: Wed, 2 Dec 2026 05:35:39 +0000 Subject: [PATCH 1/8] feat(device): Sign in with Revyl for Revyl Macs OAuth 2.1 public client with S256 PKCE and a loopback redirect. A signed-in host opens and runs Revyl Macs on the user's token (refreshed and rotated in the server secret store); phones keep the API key. Refusals surface their reason instead of falling back to the key. Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> --- apps/server/src/auth/RpcAuthorization.ts | 3 + apps/server/src/device/DeviceService.test.ts | 11 + apps/server/src/device/DeviceService.ts | 66 ++- .../server/src/device/RevylDeviceHost.test.ts | 140 ++++- apps/server/src/device/RevylDeviceHost.ts | 263 +++++++--- apps/server/src/device/RevylOAuth.test.ts | 378 ++++++++++++++ apps/server/src/device/RevylOAuth.ts | 484 ++++++++++++++++++ .../src/observability/RpcInstrumentation.ts | 3 + apps/server/src/ws.ts | 3 + .../settings/RevylDeviceHostEditor.tsx | 136 +++++ apps/web/src/i18n/translations/de.json | 11 +- apps/web/src/i18n/translations/en.json | 11 +- apps/web/src/i18n/translations/es.json | 11 +- apps/web/src/i18n/translations/fr.json | 11 +- apps/web/src/i18n/translations/ja.json | 11 +- apps/web/src/i18n/translations/ko.json | 11 +- apps/web/src/i18n/translations/pl.json | 23 +- apps/web/src/i18n/translations/pt-BR.json | 11 +- apps/web/src/i18n/translations/ru.json | 11 +- apps/web/src/i18n/translations/sv.json | 11 +- apps/web/src/i18n/translations/zh.json | 11 +- apps/web/src/state/device.ts | 8 + docs/user/devices.md | 11 + packages/client-runtime/src/state/device.ts | 8 + packages/contracts/src/device.ts | 25 + packages/contracts/src/rpc.ts | 19 + 26 files changed, 1585 insertions(+), 106 deletions(-) create mode 100644 apps/server/src/device/RevylOAuth.test.ts create mode 100644 apps/server/src/device/RevylOAuth.ts diff --git a/apps/server/src/auth/RpcAuthorization.ts b/apps/server/src/auth/RpcAuthorization.ts index ace05fd99f40f..d033c416cc2de 100644 --- a/apps/server/src/auth/RpcAuthorization.ts +++ b/apps/server/src/auth/RpcAuthorization.ts @@ -248,6 +248,9 @@ export const RPC_REQUIRED_SCOPES = { [WS_METHODS.deviceTestHost]: AuthSettingsWriteScope, [WS_METHODS.deviceEasAccount]: AuthSettingsWriteScope, [WS_METHODS.deviceSimlockIdentity]: AuthSettingsWriteScope, + [WS_METHODS.deviceRevylAccount]: AuthSettingsWriteScope, + [WS_METHODS.deviceRevylSignIn]: AuthSettingsWriteScope, + [WS_METHODS.deviceRevylSignOut]: AuthSettingsWriteScope, [WS_METHODS.deviceList]: AuthOrchestrationReadScope, [WS_METHODS.deviceOpen]: AuthOrchestrationOperateScope, [WS_METHODS.deviceClose]: AuthOrchestrationOperateScope, diff --git a/apps/server/src/device/DeviceService.test.ts b/apps/server/src/device/DeviceService.test.ts index 5be22e0362ce4..3628ba6b08ae5 100644 --- a/apps/server/src/device/DeviceService.test.ts +++ b/apps/server/src/device/DeviceService.test.ts @@ -35,6 +35,8 @@ import * as TestClock from "effect/testing/TestClock"; import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner"; import { HttpClient, HttpClientResponse } from "effect/http"; import * as ServerConfig from "../config.ts"; +import * as ServerSecretStore from "../auth/ServerSecretStore.ts"; +import * as ExternalLauncher from "../process/externalLauncher.ts"; import * as ProcessRunner from "../processRunner.ts"; import * as ServerSettings from "../serverSettings.ts"; import * as DeviceHost from "./DeviceHost.ts"; @@ -768,6 +770,12 @@ describe("device setup consent", () => { ); }); +/** Revyl sign-in state no SSH or local test reaches. */ +const layerRevylOAuth = Layer.mergeAll( + Layer.mock(ServerSecretStore.ServerSecretStore)({}), + Layer.mock(ExternalLauncher.ExternalLauncher)({}), +); + const layerSecretResolver = Layer.succeed(SecretResolver.SecretResolver, { label: (provider) => Effect.succeed(provider), read: (references) => Effect.succeed(references.map(() => undefined)), @@ -820,6 +828,7 @@ it.effect.each([ Effect.gen(function* () { const { host } = yield* fixture(); const service = yield* DeviceService.make.pipe( + Effect.provide(layerRevylOAuth), Effect.provideService(DeviceHost.DeviceHost, host), Effect.provideService(ProcessRunner.ProcessRunner, { run: () => Effect.die("Testing SSH does not install local tools"), @@ -1902,6 +1911,7 @@ it.effect("reconciles SSH host settings without publishing no-op changes", () => stopAgent: Effect.void, }; const service = yield* DeviceService.make.pipe( + Effect.provide(layerRevylOAuth), Effect.provideService(DeviceHost.DeviceHost, localHost), Effect.provideService(ServerSettings.ServerSettingsService, { ...settings, @@ -2024,6 +2034,7 @@ it.effect.each(["exit", "missing"] as const)( stderrInvalidUtf8: false, }; const service = yield* DeviceService.make.pipe( + Effect.provide(layerRevylOAuth), Effect.provideService(DeviceHost.DeviceHost, host), Effect.provideService(ProcessRunner.ProcessRunner, { run: ({ command, args }) => diff --git a/apps/server/src/device/DeviceService.ts b/apps/server/src/device/DeviceService.ts index 6ccb38afdb7ac..2bd13ee145573 100644 --- a/apps/server/src/device/DeviceService.ts +++ b/apps/server/src/device/DeviceService.ts @@ -23,6 +23,9 @@ import { type DeviceSimlockIdentity, DeviceSimlockIdentityError, type DeviceSimlockIdentityInput, + type DeviceRevylAccount, + DeviceRevylAuthError, + type DeviceRevylAccountInput, type DeviceHostConfig, type EasDeviceHostConfig, type RevylDeviceHostConfig, @@ -81,6 +84,7 @@ import * as DeviceHost from "./DeviceHost.ts"; import * as SshDeviceHost from "./SshDeviceHost.ts"; import * as EasDeviceHost from "./EasDeviceHost.ts"; import * as RevylDeviceHost from "./RevylDeviceHost.ts"; +import * as RevylOAuth from "./RevylOAuth.ts"; import * as SimlockDeviceHost from "./SimlockDeviceHost.ts"; import * as HostProcess from "@t3tools/shared/HostProcess"; import { makeExpoApi } from "./ExpoApi.ts"; @@ -190,6 +194,16 @@ export class DeviceService extends Context.Service< readonly simlockIdentity: ( input: DeviceSimlockIdentityInput, ) => Effect.Effect; + /** A saved Revyl host's Sign in with Revyl state, and signing it in or out on this server. */ + readonly revylAccount: ( + input: DeviceRevylAccountInput, + ) => Effect.Effect; + readonly revylSignIn: ( + input: DeviceRevylAccountInput, + ) => Effect.Effect; + readonly revylSignOut: ( + input: DeviceRevylAccountInput, + ) => Effect.Effect; /** * The agent-device flags that reach the device: its config and session, * and the id agent-device selects it by, which can differ from its id here. @@ -1193,6 +1207,11 @@ export const makeWithHosts = Effect.fn("DeviceService.makeWithHosts")(function* // Sessions live in memory, so this removes every launcher a previous run left behind. yield* pruneLaunchers; + const revylUnavailable = () => + Effect.fail( + new DeviceRevylAuthError({ reason: "Revyl hosts are unavailable in this device service." }), + ); + return { ...DeviceService.of({ testHost, @@ -1226,6 +1245,9 @@ export const makeWithHosts = Effect.fn("DeviceService.makeWithHosts")(function* }), ); }), + revylAccount: revylUnavailable, + revylSignIn: revylUnavailable, + revylSignOut: revylUnavailable, agentTarget: Effect.fn("DeviceService.agentTarget")(function* (input) { const host = yield* resolveHost(input.hostId); const ready = yield* agentReadinessIfSupported(input.hostId); @@ -1541,6 +1563,7 @@ export const make = Effect.gen(function* () { yield* Effect.context>>(); const revylContext = yield* Effect.context>>(); + const revylAccounts = yield* RevylOAuth.make; const agentDeviceCli = Effect.fn("DeviceService.agentDeviceCli")( function* (hostId: string) { const nodePath = yield* resolveNodeExecutable("Device automation"); @@ -1621,10 +1644,11 @@ export const make = Effect.gen(function* () { if (host.kind === "revyl") { // Closing this scope ends the host's Revyl sessions, so a changed key or limit never // leaves a billed session behind. - const instance = yield* RevylDeviceHost.make(host, agentDeviceCli(host.id)).pipe( - Effect.provideService(Scope.Scope, hostScope), - Effect.provide(revylContext), - ); + const instance = yield* RevylDeviceHost.make( + host, + agentDeviceCli(host.id), + revylAccounts, + ).pipe(Effect.provideService(Scope.Scope, hostScope), Effect.provide(revylContext)); hosts.set(host.id, instance); configured.set(host.id, { config: host, scope: hostScope }); continue; @@ -1789,10 +1813,44 @@ export const make = Effect.gen(function* () { Effect.provide(simlockContext), ); + const revylHost = Effect.fn("DeviceService.revylHost")( + function* (hostId: string) { + const host = (yield* settings.getSettings).revylDeviceHosts.find( + (candidate) => candidate.id === hostId, + ); + if (!host) return yield* new DeviceRevylAuthError({ reason: "Save the Revyl host first." }); + const apiOrigin = RevylDeviceHost.revylApiOrigin(yield* HostProcess.Environment); + if (apiOrigin === null) + return yield* new DeviceRevylAuthError({ + reason: "REVYL_API_URL must be an https origin, such as https://backend.revyl.ai.", + }); + return { host, apiOrigin }; + }, + Effect.catchTags({ + ServerSettingsError: () => + Effect.fail( + new DeviceRevylAuthError({ reason: "Could not read the Revyl host's settings." }), + ), + }), + Effect.provide(revylContext), + ); + return { ...service, easAccount, simlockIdentity, + revylAccount: Effect.fn("DeviceService.revylAccount")(function* ({ hostId }) { + const { host, apiOrigin } = yield* revylHost(hostId); + return yield* revylAccounts.account(host, apiOrigin); + }), + revylSignIn: Effect.fn("DeviceService.revylSignIn")(function* ({ hostId }) { + const { host, apiOrigin } = yield* revylHost(hostId); + return yield* revylAccounts.signIn(host, apiOrigin); + }), + revylSignOut: Effect.fn("DeviceService.revylSignOut")(function* ({ hostId }) { + const { host } = yield* revylHost(hostId); + return yield* revylAccounts.signOut(host); + }), }; }); diff --git a/apps/server/src/device/RevylDeviceHost.test.ts b/apps/server/src/device/RevylDeviceHost.test.ts index 7f387abeaf506..ad23c10e4dddc 100644 --- a/apps/server/src/device/RevylDeviceHost.test.ts +++ b/apps/server/src/device/RevylDeviceHost.test.ts @@ -4,9 +4,11 @@ import type { RevylDeviceHostConfig } from "@t3tools/contracts"; import * as SecretResolver from "@t3tools/secret-provider-core/server/SecretResolver"; import * as HostProcess from "@t3tools/shared/HostProcess"; import * as Effect from "effect/Effect"; +import * as Base64Url from "effect/encoding/Base64Url"; import * as Exit from "effect/Exit"; import * as FileSystem from "effect/FileSystem"; import * as Layer from "effect/Layer"; +import * as Option from "effect/Option"; import * as Path from "effect/Path"; import * as Queue from "effect/Queue"; import * as Scope from "effect/Scope"; @@ -15,10 +17,13 @@ import { HttpClient, HttpClientResponse, HttpServerRequest, HttpServerResponse } import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner"; import * as Socket from "effect/socket/Socket"; +import * as ServerSecretStore from "../auth/ServerSecretStore.ts"; import * as ServerConfig from "../config.ts"; +import * as ExternalLauncher from "../process/externalLauncher.ts"; import * as ProcessRunner from "../processRunner.ts"; import { AGENT_DEVICE_VERSION } from "./DeviceToolchain.ts"; import * as RevylDeviceHost from "./RevylDeviceHost.ts"; +import * as RevylOAuth from "./RevylOAuth.ts"; const RUN_ID = "22f76fea-8249-4333-b131-9642526531fd"; const WHEP = "https://bridge.test/play/live-1"; @@ -55,6 +60,7 @@ const fakeRevyl = Effect.gen(function* () { const requests: Array<{ readonly method: string; readonly url: string; + readonly authorization: string | undefined; readonly contentType: string | undefined; readonly body: string; }> = []; @@ -74,6 +80,7 @@ const fakeRevyl = Effect.gen(function* () { requests.push({ method: request.method, url: url.origin + url.pathname, + authorization: request.headers.authorization, contentType: request.body._tag === "Uint8Array" ? request.body.contentType : undefined, body: request.body._tag === "Uint8Array" ? new TextDecoder().decode(request.body.body) : "", }); @@ -90,7 +97,39 @@ const fakeRevyl = Effect.gen(function* () { ) : json({}); } - if (request.headers.authorization !== "Bearer revyl-key") return json({}, 401); + if (url.pathname === "/.well-known/oauth-authorization-server/api/v1/oauth2") + return json({ + issuer: "https://backend.revyl.ai/api/v1/oauth2", + authorization_endpoint: "https://backend.revyl.ai/api/v1/oauth2/authorize", + token_endpoint: "https://backend.revyl.ai/api/v1/oauth2/token", + }); + if (url.pathname === "/api/v1/oauth2/token") + return json({ + access_token: "oauth-access", + refresh_token: "oauth-refresh-2", + expires_in: 3600, + }); + // Sign in with Revyl reaches Mac lifecycle but not the screen, as Revyl's computers scope does. + if ( + request.headers.authorization === "Bearer oauth-access" && + /\/(device-sessions|viewer-ice-servers|screen)\b/.test(url.pathname) + ) + return json( + { + detail: { + error: "not_available_to_oauth_apps", + message: "OAuth apps can't use this endpoint.", + required_scope: null, + }, + code: "access_denied", + }, + 403, + ); + if ( + request.headers.authorization !== "Bearer revyl-key" && + request.headers.authorization !== "Bearer oauth-access" + ) + return json({}, 401); const body = () => request.body._tag === "Uint8Array" ? JSON.parse(new TextDecoder().decode(request.body.body)) @@ -194,15 +233,50 @@ const layer = Layer.mergeAll( makeSecretResolver(), ).pipe(Layer.provideMerge(NodeServices.layer)); +/** Sign in with Revyl over the fake Revyl, signed in with `accessToken` when one is given. */ +const makeAccounts = (revyl: Effect.Success, accessToken?: string) => { + const store = new Map(); + if (accessToken) + store.set( + `revyl-device-host-${Base64Url.encode("revyl")}-oauth`, + new TextEncoder().encode( + JSON.stringify({ + apiOrigin: "https://backend.revyl.ai", + clientId: "revylapp_t3", + accessToken, + refreshToken: "oauth-refresh-1", + expiresAt: 3_600_000, + }), + ), + ); + return RevylOAuth.make.pipe( + Effect.provideService(HttpClient.HttpClient, revyl.http), + Effect.provide( + Layer.mergeAll( + Layer.mock(ServerSecretStore.ServerSecretStore)({ + get: (name) => Effect.sync(() => Option.fromNullishOr(store.get(name))), + set: (name, value) => Effect.sync(() => void store.set(name, value)), + remove: (name) => Effect.sync(() => void store.delete(name)), + }), + Layer.mock(ExternalLauncher.ExternalLauncher)({}), + ), + ), + ); +}; + const makeHost = ( revyl: Effect.Success, hostConfig: RevylDeviceHostConfig, scope: Scope.Scope, environment: NodeJS.ProcessEnv = {}, + signedInWith?: string, ) => - RevylDeviceHost.make( - hostConfig, - Effect.succeed({ nodePath: "node", entryPath: "/tools/agent-device.mjs" }), + Effect.flatMap(makeAccounts(revyl, signedInWith), (accounts) => + RevylDeviceHost.make( + hostConfig, + Effect.succeed({ nodePath: "node", entryPath: "/tools/agent-device.mjs" }), + accounts, + ), ).pipe( Effect.provideService(HttpClient.HttpClient, revyl.http), Effect.provideService(ProcessRunner.ProcessRunner, revyl.runner), @@ -679,6 +753,64 @@ describe("Revyl Macs", () => { }).pipe(Effect.scoped, Effect.provide(layer)), ); + it.effect( + "signed in with Revyl, runs a Mac's lifecycle on the sign-in, refreshing once on a 401, and says why Revyl refuses its screen", + () => + Effect.gen(function* () { + const revyl = yield* fakeRevyl; + const scope = yield* Scope.make(); + const host = yield* makeHost( + revyl, + config({ apiKey: "", macs: true, oauthClientId: "revylapp_t3" }), + scope, + {}, + "oauth-stale", + ); + expect(yield* host.platformAvailability("macos")).toEqual({ + platform: "macos", + available: true, + }); + expect(yield* host.platformAvailability("android")).toMatchObject({ + available: false, + reason: "Add a Revyl API key for Revyl in Settings, or set REVYL_API_KEY.", + }); + const ready = yield* host.ensureReady(() => Effect.void); + const catalog = (yield* ready.devices.list).devices.find( + (device) => device.id === "revyl:macos", + ); + + const refused = yield* Effect.flip(ready.devices.boot(catalog!)); + expect(refused).toMatchObject({ + _tag: "DeviceBootError", + diagnostics: + "Revyl does not let Sign in with Revyl do this yet (not_available_to_oauth_apps). Sign out of Revyl in Settings to use the API key.", + }); + const create = revyl.requests.find( + (request) => request.method === "POST" && request.url.endsWith("/api/v1/computer-runs"), + ); + const computerId = JSON.parse(create!.body).computer_session_id; + expect( + revyl.requests + .filter(({ url }) => url.startsWith("https://backend.revyl.ai/api/v1/")) + .map(({ method, url, authorization }) => [ + method, + url.slice("https://backend.revyl.ai/api/v1".length), + authorization, + ]), + ).toEqual([ + ["GET", "/computer-runs/persistent", "Bearer oauth-stale"], + ["POST", "/oauth2/token", undefined], + ["GET", "/computer-runs/persistent", "Bearer oauth-access"], + ["POST", "/computer-runs", "Bearer oauth-access"], + ["GET", `/computer-runs/${computerId}`, "Bearer oauth-access"], + ["GET", "/execution/device-sessions/run-1", "Bearer oauth-access"], + ["POST", `/computer-runs/${computerId}/stop`, "Bearer oauth-access"], + ]); + expect(revyl.computers.get(computerId)?.state).toBe("stopped"); + yield* Scope.close(scope, Exit.void); + }).pipe(Effect.scoped, Effect.provide(layer)), + ); + it.effect("starts a stopped Mac again on the stream of its new run", () => Effect.gen(function* () { const revyl = yield* fakeRevyl; diff --git a/apps/server/src/device/RevylDeviceHost.ts b/apps/server/src/device/RevylDeviceHost.ts index 66dc03ba64e79..4df96a2412d51 100644 --- a/apps/server/src/device/RevylDeviceHost.ts +++ b/apps/server/src/device/RevylDeviceHost.ts @@ -43,6 +43,7 @@ import * as ProcessRunner from "../processRunner.ts"; import { requireSettingsSecret } from "../secrets/settingsSecretValue.ts"; import * as DeviceHost from "./DeviceHost.ts"; import { AGENT_DEVICE_VERSION } from "./DeviceToolchain.ts"; +import * as RevylOAuth from "./RevylOAuth.ts"; import type { AgentDeviceCli } from "./SimlockDeviceHost.ts"; const REVYL_API = "https://backend.revyl.ai"; @@ -198,7 +199,8 @@ interface Mac { /** The computer's id, which stays the same across starts and is the device id T3 lists. */ readonly computerId: string; readonly platform: "macos"; - readonly apiKey: string; + /** The API key it opened with, or null when it opened signed in with Revyl. */ + readonly credential: string | null; readonly screen: PanelScreen; /** Read after each start: a start opens a new run session with a new stream. */ readonly whepUrl: string; @@ -387,9 +389,19 @@ const deviceKind = (platform: MobileDevicePlatform) => platform === "ios" ? "iOS simulator" : "Android emulator"; const RUN_ID = /([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})$/i; +/** REVYL_API_URL, or Revyl's API, when it is a bare https origin; otherwise null. */ +export const revylApiOrigin = (environment: Readonly>) => { + const configured = environment.REVYL_API_URL?.trim() || REVYL_API; + const parsed = URL.canParse(configured) ? new URL(configured) : null; + return parsed?.protocol === "https:" && parsed.href === `${parsed.origin}/` + ? parsed.origin + : null; +}; + export const make = Effect.fn("RevylDeviceHost.make")(function* ( config: RevylDeviceHostConfig, agentDeviceCli: AgentDeviceCli, + accounts: RevylOAuth.RevylAccounts, ) { const http = yield* HttpClient.HttpClient; const fs = yield* FileSystem.FileSystem; @@ -413,12 +425,7 @@ export const make = Effect.fn("RevylDeviceHost.make")(function* ( const maxAge = yield* FiberMap.make(); let ready: DeviceHost.DeviceHostReady | null = null; let cli: { readonly nodePath: string; readonly entryPath: string } | null = null; - const configuredApi = environment.REVYL_API_URL?.trim() || REVYL_API; - const parsedApi = URL.canParse(configuredApi) ? new URL(configuredApi) : null; - const apiOrigin = - parsedApi?.protocol === "https:" && parsedApi.href === `${parsedApi.origin}/` - ? parsedApi.origin - : null; + const apiOrigin = revylApiOrigin(environment); const appUrls: Readonly> = { ios: config.iosAppUrl, android: config.androidAppUrl, @@ -452,19 +459,78 @@ export const make = Effect.fn("RevylDeviceHost.make")(function* ( .execute(request.pipe(HttpClientRequest.bearerToken(apiKey))) .pipe(Effect.flatMap(HttpClientResponse.filterStatusOk), Effect.timeout(REQUEST_TIMEOUT)); + const apiRequest = (method: "GET" | "POST", route: string, body?: unknown) => + method === "GET" + ? HttpClientRequest.get(`${apiOrigin}${route}`) + : HttpClientRequest.post(`${apiOrigin}${route}`).pipe( + HttpClientRequest.bodyJsonUnsafe(body ?? {}), + ); + const revylJson = (apiKey: string, method: "GET" | "POST", route: string, body?: unknown) => - revyl( - apiKey, - method === "GET" - ? HttpClientRequest.get(`${apiOrigin}${route}`) - : HttpClientRequest.post(`${apiOrigin}${route}`).pipe( - HttpClientRequest.bodyJsonUnsafe(body ?? {}), - ), - ).pipe( + revyl(apiKey, apiRequest(method, route, body)).pipe( + Effect.flatMap((response) => response.json), + Effect.scoped, + ); + + const signedInToken = Effect.fnUntraced(function* (rejected?: string) { + const token = yield* accounts + .accessToken(config, apiOrigin ?? REVYL_API, rejected) + .pipe(Effect.mapError((error) => unavailable(error.reason, error))); + if (Option.isNone(token)) + return yield* unavailable( + `Signed out of Revyl. Sign in with Revyl for ${config.label} again, or close this Mac.`, + ); + return token.value; + }); + + /** + * What Mac requests authenticate with: null while signed in with Revyl, whose token each request + * reads, otherwise the API key. A Mac never falls back from the sign-in to the key. + */ + const macCredential = Effect.gen(function* () { + if (apiOrigin === null) + return yield* unavailable(`REVYL_API_URL must be an https origin, such as ${REVYL_API}.`); + const signedIn = yield* accounts + .accessToken(config, apiOrigin) + .pipe(Effect.mapError((error) => unavailable(error.reason, error))); + return Option.isSome(signedIn) ? null : yield* currentApiKey; + }); + + /** + * Sends a Mac request with its credential. Signed in, a 401 refreshes the token and retries once, + * and a 403 fails with Revyl's reason instead of trying the API key. + */ + const macSend = Effect.fn("RevylDeviceHost.macSend")(function* ( + credential: string | null, + request: HttpClientRequest.HttpClientRequest, + ) { + const send = (bearer: string) => + http + .execute(request.pipe(HttpClientRequest.bearerToken(bearer))) + .pipe(Effect.timeout(REQUEST_TIMEOUT)); + if (credential !== null) return yield* send(credential); + const token = yield* signedInToken(); + let response = yield* send(token); + if (response.status === 401) response = yield* send(yield* signedInToken(token)); + if (response.status === 403) + return yield* unavailable(RevylOAuth.refusalReason(yield* response.text)); + return response; + }); + + const macJson = ( + credential: string | null, + method: "GET" | "POST", + route: string, + body?: unknown, + ) => + macSend(credential, apiRequest(method, route, body)).pipe( + Effect.flatMap(HttpClientResponse.filterStatusOk), Effect.flatMap((response) => response.json), Effect.scoped, ); + const isUnavailable = Schema.is(DeviceHostUnavailableError); + const proxyRoute = (lease: Pick, action: string) => `/api/v1/execution/device-proxy/${encodeURIComponent(lease.runId)}/${action}`; @@ -494,26 +560,29 @@ export const make = Effect.fn("RevylDeviceHost.make")(function* ( const computerRoute = (computerId: string, action = "") => `/api/v1/computer-runs/${encodeURIComponent(computerId)}${action}`; - const readComputer = (apiKey: string, computerId: string) => - revylJson(apiKey, "GET", computerRoute(computerId)).pipe( + const readComputer = (credential: string | null, computerId: string) => + macJson(credential, "GET", computerRoute(computerId)).pipe( Effect.flatMap(decodeComputer), Effect.map(({ persistent }) => persistent ?? null), ); - /** The organization's persistent Macs, or null when Revyl did not list them. */ - const listMacs = currentApiKey.pipe( - Effect.flatMap((apiKey) => - revylJson(apiKey, "GET", "/api/v1/computer-runs/persistent?limit=50"), + /** The organization's persistent Macs, or null with why when Revyl did not list them. */ + const listMacs = macCredential.pipe( + Effect.flatMap((credential) => + macJson(credential, "GET", "/api/v1/computer-runs/persistent?limit=50"), ), Effect.flatMap(decodePersistentComputers), - Effect.map(({ computers }) => computers), - Effect.tapError((cause) => Effect.logDebug("Revyl did not list persistent Macs", { cause })), - Effect.orElseSucceed(() => null), + Effect.map(({ computers }) => ({ computers, detail: undefined })), + Effect.catch((cause) => + Effect.logDebug("Revyl did not list persistent Macs", { cause }).pipe( + Effect.as({ computers: null, detail: isUnavailable(cause) ? cause.reason : undefined }), + ), + ), ); - const createMac = Effect.fn("RevylDeviceHost.createMac")(function* (apiKey: string) { + const createMac = Effect.fn("RevylDeviceHost.createMac")(function* (credential: string | null) { const computerId = yield* Effect.sync(() => SecureRandom.uuidV4Unsafe()); - yield* revylJson(apiKey, "POST", "/api/v1/computer-runs", { + yield* macJson(credential, "POST", "/api/v1/computer-runs", { computer_session_id: computerId, os: "macos", persistent: true, @@ -529,31 +598,32 @@ export const make = Effect.fn("RevylDeviceHost.make")(function* ( * whether this call started it. */ const startMac = Effect.fn("RevylDeviceHost.startMac")(function* ( - apiKey: string, + credential: string | null, computerId: string, ) { - const before = yield* readComputer(apiKey, computerId).pipe(Effect.orElseSucceed(() => null)); + const before = yield* readComputer(credential, computerId).pipe( + Effect.catchIf( + (error) => !isUnavailable(error), + () => Effect.succeed(null), + ), + ); if (before?.state === "starting" || before?.state === "running") return false; for (let attempt = 1; ; attempt++) { - const answer = yield* http - .execute( - HttpClientRequest.post(`${apiOrigin}${computerRoute(computerId, "/start")}`).pipe( - HttpClientRequest.bearerToken(apiKey), - ), - ) - .pipe( - Effect.flatMap((response) => - response.text.pipe(Effect.map((text) => ({ status: response.status, text }))), - ), - Effect.scoped, - Effect.timeout(REQUEST_TIMEOUT), - ); + const answer = yield* macSend( + credential, + HttpClientRequest.post(`${apiOrigin}${computerRoute(computerId, "/start")}`), + ).pipe( + Effect.flatMap((response) => + response.text.pipe(Effect.map((text) => ({ status: response.status, text }))), + ), + Effect.scoped, + ); if (answer.status < 300) return true; const detail = Option.match(decodeApiError(answer.text), { onNone: () => `status ${answer.status}`, onSome: (error) => error.detail, }); - const current = yield* readComputer(apiKey, computerId).pipe( + const current = yield* readComputer(credential, computerId).pipe( Effect.orElseSucceed(() => null), ); if (current?.state === "starting" || current?.state === "running") return false; @@ -569,7 +639,7 @@ export const make = Effect.fn("RevylDeviceHost.make")(function* ( /** Waits for the Mac to run, then reads its current run's stream; the URL is never logged. */ const attachMac = Effect.fn("RevylDeviceHost.attachMac")(function* ( - apiKey: string, + credential: string | null, computerId: string, ) { const deadline = (yield* Clock.currentTimeMillis) + Duration.toMillis(OPEN_TIMEOUT); @@ -578,14 +648,19 @@ export const make = Effect.fn("RevylDeviceHost.make")(function* ( what: string, ) { while ((yield* Clock.currentTimeMillis) < deadline) { - const value = yield* read.pipe(Effect.orElseSucceed(() => null)); + const value = yield* read.pipe( + Effect.catchIf( + (error) => !isUnavailable(error), + () => Effect.succeed(null), + ), + ); if (value !== null) return value; yield* Effect.sleep(MAC_POLL); } return yield* unavailable(`The Revyl Mac did not ${what} in time.`); }); const runSessionId = yield* waitFor( - readComputer(apiKey, computerId).pipe( + readComputer(credential, computerId).pipe( Effect.map((computer) => computer?.state === "running" ? (computer.run_session_id ?? null) : null, ), @@ -593,8 +668,8 @@ export const make = Effect.fn("RevylDeviceHost.make")(function* ( "start", ); const feed = yield* waitFor( - revylJson( - apiKey, + macJson( + credential, "GET", `/api/v1/execution/device-sessions/${encodeURIComponent(runSessionId)}?include_computers=true`, ).pipe( @@ -603,21 +678,24 @@ export const make = Effect.fn("RevylDeviceHost.make")(function* ( ), "publish its screen", ); - const iceServers = yield* revylJson( - apiKey, + const iceServers = yield* macJson( + credential, "GET", "/api/v1/execution/streaming/viewer-ice-servers", ).pipe( Effect.flatMap(decodeViewerIceServers), Effect.map(({ ice_servers }) => ice_servers), - Effect.orElseSucceed(() => []), + Effect.catchIf( + (error) => !isUnavailable(error), + () => Effect.succeed([]), + ), ); const width = feed.screen_width ?? 1280; const height = feed.screen_height ?? 800; const mac: Mac = { computerId, platform: "macos", - apiKey, + credential, screen: { width, height, orientation: width > height ? "landscape_left" : "portrait" }, whepUrl: feed.whep_url, iceServers, @@ -628,8 +706,12 @@ export const make = Effect.fn("RevylDeviceHost.make")(function* ( }); /** Stops a Mac, which saves its disk; a stop that fails leaves the run to its lifetime limit. */ - const stopMac = (apiKey: string, computerId: string) => - revyl(apiKey, HttpClientRequest.post(`${apiOrigin}${computerRoute(computerId, "/stop")}`)).pipe( + const stopMac = (credential: string | null, computerId: string) => + macSend( + credential, + HttpClientRequest.post(`${apiOrigin}${computerRoute(computerId, "/stop")}`), + ).pipe( + Effect.flatMap(HttpClientResponse.filterStatusOk), Effect.scoped, Effect.andThen(Effect.logInfo("Stopped a Revyl Mac", { computerId })), Effect.tapError((cause) => @@ -642,20 +724,34 @@ export const make = Effect.fn("RevylDeviceHost.make")(function* ( Effect.suspend(() => { macs.delete(mac.computerId); return macsStartedHere.delete(mac.computerId) - ? stopMac(mac.apiKey, mac.computerId) + ? stopMac(mac.credential, mac.computerId) : Effect.void; }); const macIdleKey = (computerId: string) => `mac:${computerId}`; + yield* accounts.onSignOut( + hostId, + Effect.suspend(() => + Effect.forEach( + [...macs.values()].filter((mac) => mac.credential === null), + (mac) => + FiberMap.remove(maxAge, macIdleKey(mac.computerId)).pipe(Effect.andThen(releaseMac(mac))), + { discard: true }, + ), + ), + ); + const openMac = Effect.fn("RevylDeviceHost.openMac")( function* (device: DeviceHost.HostDevice) { - const apiKey = yield* currentApiKey; + const credential = yield* macCredential; const stopsAtOpen = stops; - const computerId = device.id === MAC_CATALOG_ID ? yield* createMac(apiKey) : device.id; - const started = device.id === MAC_CATALOG_ID || (yield* startMac(apiKey, computerId)); - const stopIfStarted = started ? stopMac(apiKey, computerId) : Effect.void; - const mac = yield* attachMac(apiKey, computerId).pipe(Effect.tapError(() => stopIfStarted)); + const computerId = device.id === MAC_CATALOG_ID ? yield* createMac(credential) : device.id; + const started = device.id === MAC_CATALOG_ID || (yield* startMac(credential, computerId)); + const stopIfStarted = started ? stopMac(credential, computerId) : Effect.void; + const mac = yield* attachMac(credential, computerId).pipe( + Effect.tapError(() => stopIfStarted), + ); if (stops !== stopsAtOpen) { yield* stopIfStarted; return yield* unavailable("Device support stopped while the Mac was opening."); @@ -685,13 +781,13 @@ export const make = Effect.fn("RevylDeviceHost.make")(function* ( ); const macScreenshot = (mac: Mac) => - revylJson(mac.apiKey, "GET", computerRoute(mac.computerId, "/screen/screenshot")).pipe( + macJson(mac.credential, "GET", computerRoute(mac.computerId, "/screen/screenshot")).pipe( Effect.flatMap(decodeScreenshot), Effect.map(({ png }) => new Uint8Array(Buffer.from(png, "base64"))), ); const macAct = (mac: Mac, action: MacScreenAction) => - revylJson(mac.apiKey, "POST", computerRoute(mac.computerId, "/screen/actions"), { + macJson(mac.credential, "POST", computerRoute(mac.computerId, "/screen/actions"), { action, screenshot: false, }); @@ -933,7 +1029,9 @@ export const make = Effect.fn("RevylDeviceHost.make")(function* ( const devices: DeviceHost.DeviceOperations = { list: Effect.gen(function* () { - const listedMacs = config.macs ? yield* listMacs : []; + const { computers: listedMacs, detail } = config.macs + ? yield* listMacs + : { computers: [], detail: undefined }; return { devices: [ ...phoneDevices(), @@ -961,7 +1059,7 @@ export const make = Effect.fn("RevylDeviceHost.make")(function* ( })), ]), ], - detail: undefined, + detail, ...(listedMacs === null ? { incompletePlatforms: ["macos" as const] } : {}), }; }), @@ -992,8 +1090,8 @@ export const make = Effect.fn("RevylDeviceHost.make")(function* ( Effect.andThen(releaseMac(mac)), ); if (device.platform === "macos") - return currentApiKey.pipe( - Effect.flatMap((apiKey) => stopMac(apiKey, device.id)), + return macCredential.pipe( + Effect.flatMap((credential) => stopMac(credential, device.id)), Effect.ignore, ); return Option.match(leaseFor(device.id), { @@ -1306,25 +1404,20 @@ export const make = Effect.fn("RevylDeviceHost.make")(function* ( { status: 409 }, ); if (mac) mac.activeAt = yield* Clock.currentTimeMillis; - const answer = - hubPath === SCREENSHOT_PATH - ? (mac ? macScreenshot(mac) : screenshotOf(lease!)).pipe( - Effect.map((png) => - HttpServerResponse.uint8Array(png, { - contentType: "image/png", - headers: { "cache-control": "no-store, no-transform" }, - }), - ), - ) - : webrtc?.[2] === "offer" - ? offer(target, request) - : webrtc?.[2] === "close" - ? closeView(target, request) - : hubPath === INPUT_PATH - ? mac - ? macInput(mac, request) - : input(lease!, request) - : Effect.succeed(notFound); + const answer = Effect.gen(function* () { + if (hubPath === SCREENSHOT_PATH) + return HttpServerResponse.uint8Array( + mac ? yield* macScreenshot(mac) : yield* screenshotOf(lease!), + { + contentType: "image/png", + headers: { "cache-control": "no-store, no-transform" }, + }, + ); + if (webrtc?.[2] === "offer") return yield* offer(target, request); + if (webrtc?.[2] === "close") return yield* closeView(target, request); + if (hubPath !== INPUT_PATH) return notFound; + return mac ? yield* macInput(mac, request) : yield* input(lease!, request); + }); return yield* answer.pipe( Effect.catchCause((cause) => Effect.logWarning("Revyl device request failed", { hubPath, cause }).pipe( @@ -1398,7 +1491,7 @@ export const make = Effect.fn("RevylDeviceHost.make")(function* ( yield* Effect.addFinalizer(() => stopAll); const platformAvailability = (platform: DevicePlatform) => - currentApiKey.pipe( + (platform === "macos" ? macCredential : currentApiKey).pipe( Effect.map((): DevicePlatformAvailability => (platform === "macos" ? config.macs : appUrls[platform]) ? { platform, available: true } diff --git a/apps/server/src/device/RevylOAuth.test.ts b/apps/server/src/device/RevylOAuth.test.ts new file mode 100644 index 0000000000000..3ae0458b760a5 --- /dev/null +++ b/apps/server/src/device/RevylOAuth.test.ts @@ -0,0 +1,378 @@ +// @effect-diagnostics globalFetch:off - The fake browser follows Revyl's redirect to the real loopback listener. +import { describe, expect, it } from "@effect/vitest"; +import type { RevylDeviceHostConfig } from "@t3tools/contracts"; +import * as Effect from "effect/Effect"; +import * as Base64Url from "effect/encoding/Base64Url"; +import * as Exit from "effect/Exit"; +import * as Layer from "effect/Layer"; +import * as Option from "effect/Option"; +import * as TestClock from "effect/testing/TestClock"; +import { HttpClient, HttpClientResponse } from "effect/http"; + +import * as ServerSecretStore from "../auth/ServerSecretStore.ts"; +import * as ExternalLauncher from "../process/externalLauncher.ts"; +import * as RevylOAuth from "./RevylOAuth.ts"; + +const API = "https://revyl.test"; +const ISSUER = `${API}/api/v1/oauth2`; +const SECRET = `revyl-device-host-${Base64Url.encode("revyl")}-oauth`; + +const host: RevylDeviceHostConfig = { + kind: "revyl", + id: "revyl", + label: "Revyl", + apiKey: "", + maxSessions: 2, + maxSessionMinutes: 30, + macs: true, + macIdleMinutes: 15, + oauthClientId: "revylapp_t3", +}; + +const session = (overrides: Record = {}) => ({ + apiOrigin: API, + clientId: "revylapp_t3", + accessToken: "access-1", + refreshToken: "refresh-1", + expiresAt: 3_600_000, + account: "ada@example.com (Example)", + ...overrides, +}); + +/** Revyl's authorization server and the server's secret store, recording what was asked of them. */ +const fakeRevyl = ( + answerToken: (params: URLSearchParams) => { readonly status: number; readonly body: unknown }, +) => { + const store = new Map(); + const tokenRequests: Array = []; + const revocations: Array = []; + const http = HttpClient.make((request) => + Effect.sync(() => { + const url = new URL(request.url); + const json = (body: unknown, status = 200) => + HttpClientResponse.fromWeb(request, Response.json(body, { status })); + const form = () => + new URLSearchParams( + request.body._tag === "Uint8Array" ? new TextDecoder().decode(request.body.body) : "", + ); + switch (url.pathname) { + case "/.well-known/oauth-authorization-server/api/v1/oauth2": + return json({ + issuer: ISSUER, + authorization_endpoint: `${ISSUER}/authorize`, + token_endpoint: `${ISSUER}/token`, + revocation_endpoint: `${ISSUER}/revoke`, + }); + case "/api/v1/oauth2/token": { + const params = form(); + tokenRequests.push(params); + const answer = answerToken(params); + return json(answer.body, answer.status); + } + case "/api/v1/oauth2/revoke": + revocations.push(form()); + return HttpClientResponse.fromWeb(request, new Response(null, { status: 200 })); + case "/api/v1/me": + return request.headers.authorization === "Bearer access-new" + ? json({ user: { email: "ada@example.com" }, organization: { name: "Example" } }) + : json({}, 401); + } + return json({}, 404); + }), + ); + const launched: Array = []; + const layer = Layer.mergeAll( + Layer.succeed(HttpClient.HttpClient, http), + Layer.mock(ServerSecretStore.ServerSecretStore)({ + get: (name) => Effect.sync(() => Option.fromNullishOr(store.get(name))), + set: (name, value) => Effect.sync(() => void store.set(name, value)), + remove: (name) => Effect.sync(() => void store.delete(name)), + }), + Layer.mock(ExternalLauncher.ExternalLauncher)({ + launchBrowser: (target) => + Effect.sync(() => { + launched.push(target); + redirect(target); + }), + }), + ); + let redirect = (_target: string) => {}; + const stored = () => { + const value = store.get(SECRET); + return value === undefined ? undefined : JSON.parse(new TextDecoder().decode(value)); + }; + const seed = (value: unknown) => + store.set(SECRET, new TextEncoder().encode(JSON.stringify(value))); + return { + layer, + tokenRequests, + revocations, + launched, + stored, + seed, + onBrowser: (open: (target: string) => void) => { + redirect = open; + }, + }; +}; + +const rotate = (params: URLSearchParams) => + params.get("grant_type") === "refresh_token" + ? { + status: 200, + body: { + access_token: `access-for-${params.get("refresh_token")}`, + refresh_token: `${params.get("refresh_token")}-next`, + expires_in: 3600, + token_type: "Bearer", + }, + } + : { status: 400, body: { error: "invalid_request" } }; + +describe("Sign in with Revyl PKCE", () => { + it.effect("derives the S256 challenge of RFC 7636's example verifier", () => + Effect.gen(function* () { + expect(yield* RevylOAuth.codeChallenge("dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk")).toBe( + "E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM", + ); + }), + ); + + it.effect("makes a fresh 43-character base64url verifier with its challenge and a state", () => + Effect.gen(function* () { + const first = yield* RevylOAuth.makePkce; + const second = yield* RevylOAuth.makePkce; + expect(first.verifier).toMatch(/^[A-Za-z0-9_-]{43}$/); + expect(first.challenge).toBe(yield* RevylOAuth.codeChallenge(first.verifier)); + expect(first.state).toMatch(/^[A-Za-z0-9_-]{22}$/); + expect(second.verifier).not.toBe(first.verifier); + expect(second.state).not.toBe(first.state); + }), + ); + + it("takes a callback's code only for this sign-in's state and Revyl's issuer", () => { + const expected = { state: "state-1", issuer: ISSUER }; + const callback = (query: string) => + RevylOAuth.readCallback(new URL(`http://127.0.0.1:5000/callback?${query}`), expected); + expect(callback(`code=c1&state=state-1&iss=${ISSUER}`)).toEqual({ _tag: "Code", code: "c1" }); + expect(callback(`code=c1&state=other&iss=${ISSUER}`)).toEqual({ _tag: "Ignored" }); + expect(callback("code=c1&state=state-1&iss=https://evil.test/api/v1/oauth2")).toEqual({ + _tag: "Refused", + error: "issuer_mismatch", + }); + expect(callback("code=c1&state=state-1")).toEqual({ + _tag: "Refused", + error: "issuer_mismatch", + }); + expect(callback(`error=access_denied&state=state-1&iss=${ISSUER}`)).toEqual({ + _tag: "Refused", + error: "access_denied", + }); + }); +}); + +describe("Sign in with Revyl refusals", () => { + it("says why Revyl refused a signed-in request", () => { + expect( + RevylOAuth.refusalReason( + JSON.stringify({ + detail: { error: "not_available_to_oauth_apps", message: "No.", required_scope: null }, + code: "access_denied", + }), + ), + ).toContain("(not_available_to_oauth_apps)"); + expect( + RevylOAuth.refusalReason( + JSON.stringify({ + detail: { + error: "insufficient_scope", + message: "This endpoint needs the computers scope.", + required_scope: "computers", + }, + }), + ), + ).toBe( + "Sign in with Revyl lacks the computers scope for this (insufficient_scope). Sign in with Revyl again.", + ); + expect(RevylOAuth.refusalReason('{"detail":"Forbidden"}')).toBe( + "Revyl refused this request for Sign in with Revyl (HTTP 403).", + ); + }); +}); + +describe("Sign in with Revyl tokens", () => { + it.effect("signs in through the loopback redirect and stores who signed in", () => { + const revyl = fakeRevyl((params) => + params.get("grant_type") === "authorization_code" + ? { + status: 200, + body: { + access_token: "access-new", + refresh_token: "refresh-new", + expires_in: 3600, + token_type: "Bearer", + scope: "account.read computers", + }, + } + : { status: 400, body: { error: "invalid_grant" } }, + ); + const statuses: Array = []; + let browser = Promise.resolve(); + revyl.onBrowser((target) => { + browser = (async () => { + const authorize = new URL(target); + const redirect = authorize.searchParams.get("redirect_uri")!; + const state = authorize.searchParams.get("state")!; + for (const query of [ + `code=stolen&state=forged&iss=${ISSUER}`, + `code=code-1&state=${state}&iss=${encodeURIComponent(ISSUER)}`, + ]) { + const response = await fetch(`${redirect}?${query}`); + statuses.push(response.status); + await response.text(); + } + })(); + }); + return Effect.gen(function* () { + const accounts = yield* RevylOAuth.make; + expect(yield* accounts.signIn(host, API)).toEqual({ + status: "signedIn", + account: "ada@example.com (Example)", + }); + yield* Effect.promise(() => browser); + + const authorize = new URL(revyl.launched[0]!); + expect(authorize.origin + authorize.pathname).toBe(`${ISSUER}/authorize`); + expect(revyl.launched[0]).toContain("scope=account.read%20computers"); + expect(Object.fromEntries(authorize.searchParams)).toMatchObject({ + response_type: "code", + client_id: "revylapp_t3", + scope: "account.read computers", + code_challenge_method: "S256", + }); + expect(authorize.searchParams.get("redirect_uri")).toMatch( + /^http:\/\/127\.0\.0\.1:\d+\/callback$/, + ); + expect(statuses).toEqual([400, 200]); + const [exchange] = revyl.tokenRequests; + expect(Object.fromEntries(exchange!)).toMatchObject({ + grant_type: "authorization_code", + code: "code-1", + client_id: "revylapp_t3", + redirect_uri: authorize.searchParams.get("redirect_uri"), + }); + expect(yield* RevylOAuth.codeChallenge(exchange!.get("code_verifier")!)).toBe( + authorize.searchParams.get("code_challenge"), + ); + expect(revyl.stored()).toMatchObject({ + accessToken: "access-new", + refreshToken: "refresh-new", + clientId: "revylapp_t3", + apiOrigin: API, + }); + }).pipe(Effect.provide(revyl.layer)); + }); + + it.effect( + "uses the stored token until it nears expiry, then stores each rotated refresh token", + () => { + const revyl = fakeRevyl(rotate); + revyl.seed(session()); + return Effect.gen(function* () { + const accounts = yield* RevylOAuth.make; + expect(yield* accounts.accessToken(host, API)).toEqual(Option.some("access-1")); + expect(revyl.tokenRequests).toHaveLength(0); + + yield* TestClock.adjust("3570 seconds"); + expect(yield* accounts.accessToken(host, API)).toEqual(Option.some("access-for-refresh-1")); + expect(Object.fromEntries(revyl.tokenRequests[0]!)).toEqual({ + grant_type: "refresh_token", + refresh_token: "refresh-1", + client_id: "revylapp_t3", + }); + expect(revyl.stored()).toMatchObject({ + accessToken: "access-for-refresh-1", + refreshToken: "refresh-1-next", + account: "ada@example.com (Example)", + }); + + expect(yield* accounts.accessToken(host, API, "access-for-refresh-1")).toEqual( + Option.some("access-for-refresh-1-next"), + ); + expect(revyl.tokenRequests[1]?.get("refresh_token")).toBe("refresh-1-next"); + expect(yield* accounts.accessToken(host, API, "access-for-refresh-1")).toEqual( + Option.some("access-for-refresh-1-next"), + ); + expect(revyl.tokenRequests).toHaveLength(2); + }).pipe(Effect.provide(revyl.layer)); + }, + ); + + it.effect("ends the sign-in when Revyl refuses a refresh, without falling back", () => { + const revyl = fakeRevyl(() => ({ status: 400, body: { error: "invalid_grant" } })); + revyl.seed(session()); + return Effect.gen(function* () { + const accounts = yield* RevylOAuth.make; + const refused = yield* Effect.exit(accounts.accessToken(host, API, "access-1")); + expect(refused).toEqual( + Exit.fail( + expect.objectContaining({ + reason: + "Revyl ended the sign-in for Revyl. Sign in with Revyl again in Settings, or sign out to use the API key.", + }), + ), + ); + expect(yield* accounts.account(host, API)).toMatchObject({ status: "ended" }); + expect(Exit.isFailure(yield* Effect.exit(accounts.accessToken(host, API)))).toBe(true); + expect(revyl.tokenRequests).toHaveLength(1); + }).pipe(Effect.provide(revyl.layer)); + }); + + it.effect("keeps the sign-in when Revyl cannot refresh for now", () => { + const revyl = fakeRevyl(() => ({ status: 503, body: { error: "temporarily_unavailable" } })); + revyl.seed(session()); + return Effect.gen(function* () { + const accounts = yield* RevylOAuth.make; + expect(Exit.isFailure(yield* Effect.exit(accounts.accessToken(host, API, "access-1")))).toBe( + true, + ); + expect(yield* accounts.account(host, API)).toMatchObject({ status: "signedIn" }); + expect(revyl.stored()).toMatchObject({ refreshToken: "refresh-1" }); + }).pipe(Effect.provide(revyl.layer)); + }); + + it.effect("ignores a sign-in made for another client id or API origin", () => { + const revyl = fakeRevyl(rotate); + revyl.seed(session()); + return Effect.gen(function* () { + const accounts = yield* RevylOAuth.make; + expect( + yield* accounts.accessToken({ ...host, oauthClientId: "revylapp_other" }, API), + ).toEqual(Option.none()); + expect(yield* accounts.account(host, "https://staging.revyl.test")).toEqual({ + status: "signedOut", + }); + }).pipe(Effect.provide(revyl.layer)); + }); + + it.effect("signing out releases what the host opened, then revokes and forgets the grant", () => { + const revyl = fakeRevyl(rotate); + revyl.seed(session()); + return Effect.gen(function* () { + const accounts = yield* RevylOAuth.make; + const order: Array = []; + yield* accounts.onSignOut( + "revyl", + Effect.sync(() => void order.push(`released with ${revyl.revocations.length} revoked`)), + ); + expect(yield* accounts.signOut(host)).toEqual({ status: "signedOut" }); + expect(order).toEqual(["released with 0 revoked"]); + expect(Object.fromEntries(revyl.revocations[0]!)).toEqual({ + token: "refresh-1", + client_id: "revylapp_t3", + }); + expect(revyl.stored()).toBeUndefined(); + expect(yield* accounts.accessToken(host, API)).toEqual(Option.none()); + }).pipe(Effect.scoped, Effect.provide(revyl.layer)); + }); +}); diff --git a/apps/server/src/device/RevylOAuth.ts b/apps/server/src/device/RevylOAuth.ts new file mode 100644 index 0000000000000..125bdf3a4210d --- /dev/null +++ b/apps/server/src/device/RevylOAuth.ts @@ -0,0 +1,484 @@ +/** + * Sign in with Revyl: an OAuth 2.1 public client with S256 PKCE and a loopback redirect, found + * through the configured Revyl API origin's RFC 8414 metadata. Each saved Revyl host keeps its + * tokens in the server's secret store. Revyl rotates the refresh token on every refresh and treats + * reuse of an old one as theft, so a refresh is stored before its access token is used. + */ +// @effect-diagnostics nodeBuiltinImport:off - The loopback OAuth callback is a Node HTTP boundary. +import * as NodeHttp from "node:http"; + +import * as NodeHttpServer from "@effect/platform-node/NodeHttpServer"; +import { + type DeviceRevylAccount, + DeviceRevylAuthError, + type RevylDeviceHostConfig, +} from "@t3tools/contracts"; +import * as Clock from "effect/Clock"; +import * as Context from "effect/Context"; +import * as Digest from "effect/crypto/Digest"; +import * as SecureRandom from "effect/crypto/SecureRandom"; +import * as Deferred from "effect/Deferred"; +import * as Duration from "effect/Duration"; +import * as Effect from "effect/Effect"; +import * as Base64Url from "effect/encoding/Base64Url"; +import * as Layer from "effect/Layer"; +import * as Option from "effect/Option"; +import * as Schema from "effect/Schema"; +import * as Semaphore from "effect/Semaphore"; +import { + HttpClient, + HttpClientRequest, + HttpClientResponse, + HttpServer, + HttpServerRequest, + HttpServerResponse, +} from "effect/http"; + +import * as ServerSecretStore from "../auth/ServerSecretStore.ts"; +import * as ExternalLauncher from "../process/externalLauncher.ts"; + +/** `computers` covers persistent Mac lifecycle; `account.read` names who signed in. */ +const REVYL_OAUTH_SCOPES = ["account.read", "computers"] as const; +const ISSUER_PATH = "/api/v1/oauth2"; +const METADATA_PATH = `/.well-known/oauth-authorization-server${ISSUER_PATH}`; +const SIGN_IN_TIMEOUT = Duration.minutes(5); +const REQUEST_TIMEOUT = Duration.seconds(15); +const REFRESH_EARLY_MS = 60_000; + +const decodeMetadata = Schema.decodeUnknownEffect( + Schema.Struct({ + issuer: Schema.String, + authorization_endpoint: Schema.String, + token_endpoint: Schema.String, + revocation_endpoint: Schema.optional(Schema.String), + }), +); +type Metadata = Effect.Success>; +const decodeTokens = Schema.decodeUnknownEffect( + Schema.Struct({ + access_token: Schema.String, + refresh_token: Schema.String, + expires_in: Schema.Number, + }), +); +const decodeTokenError = Schema.decodeUnknownOption( + Schema.fromJsonString(Schema.Struct({ error: Schema.String })), +); +const decodeMe = Schema.decodeUnknownOption( + Schema.Struct({ + user: Schema.Struct({ email: Schema.String }), + organization: Schema.Struct({ name: Schema.String }), + }), +); +const decodeRefusal = Schema.decodeUnknownOption( + Schema.fromJsonString( + Schema.Struct({ + detail: Schema.Struct({ + error: Schema.Literals(["insufficient_scope", "not_available_to_oauth_apps"]), + required_scope: Schema.optional(Schema.NullOr(Schema.String)), + }), + }), + ), +); + +const Session = Schema.Struct({ + apiOrigin: Schema.String, + clientId: Schema.String, + accessToken: Schema.String, + refreshToken: Schema.String, + expiresAt: Schema.Number, + account: Schema.optional(Schema.String), + /** Revyl refused a refresh, so only signing in again or out helps. */ + ended: Schema.optional(Schema.Boolean), +}); +type Session = typeof Session.Type; +const decodeSession = Schema.decodeUnknownEffect(Schema.fromJsonString(Session)); +const encodeSession = Schema.encodeEffect(Schema.fromJsonString(Session)); + +/** RFC 7636 S256: the unpadded base64url SHA-256 of the verifier. */ +export const codeChallenge = (verifier: string) => + Effect.service(Digest.Digest).pipe( + Effect.flatMap((digest) => digest.digest(Digest.sha256, new TextEncoder().encode(verifier))), + Effect.map(Base64Url.encode), + Effect.orDie, + Effect.provide(Digest.layerWebCrypto), + ); + +/** A verifier of 43 base64url characters, its S256 challenge, and a state, all fresh. */ +export const makePkce = Effect.gen(function* () { + const verifier = Base64Url.encode(yield* Effect.sync(() => SecureRandom.randomBytesUnsafe(32))); + const state = Base64Url.encode(yield* Effect.sync(() => SecureRandom.randomBytesUnsafe(16))); + return { verifier, challenge: yield* codeChallenge(verifier), state }; +}); + +/** + * What a loopback callback carries for the sign-in that expects `state`. Another state is not + * this sign-in's, so it is ignored; RFC 9207 requires the issuer, which Revyl always sends. + */ +export const readCallback = ( + url: URL, + expected: { readonly state: string; readonly issuer: string }, +): + | { readonly _tag: "Code"; readonly code: string } + | { readonly _tag: "Refused"; readonly error: string } + | { readonly _tag: "Ignored" } => { + if (url.searchParams.get("state") !== expected.state) return { _tag: "Ignored" }; + if (url.searchParams.get("iss") !== expected.issuer) + return { _tag: "Refused", error: "issuer_mismatch" }; + const error = url.searchParams.get("error"); + if (error) return { _tag: "Refused", error }; + const code = url.searchParams.get("code"); + return code ? { _tag: "Code", code } : { _tag: "Ignored" }; +}; + +/** Why Revyl answered a request made with a Sign in with Revyl token 403. */ +export const refusalReason = (body: string) => + Option.match(decodeRefusal(body), { + onNone: () => "Revyl refused this request for Sign in with Revyl (HTTP 403).", + onSome: ({ detail }) => + detail.error === "not_available_to_oauth_apps" + ? "Revyl does not let Sign in with Revyl do this yet (not_available_to_oauth_apps). Sign out of Revyl in Settings to use the API key." + : `Sign in with Revyl lacks the ${detail.required_scope ?? "needed"} scope for this (insufficient_scope). Sign in with Revyl again.`, + }); + +const accountOf = (session: Session | null): DeviceRevylAccount => + session === null + ? { status: "signedOut" } + : { + status: session.ended ? "ended" : "signedIn", + ...(session.account ? { account: session.account } : {}), + }; + +export const make = Effect.gen(function* () { + const http = yield* HttpClient.HttpClient; + const secrets = yield* ServerSecretStore.ServerSecretStore; + const launcher = yield* ExternalLauncher.ExternalLauncher; + const locks = new Map(); + const sessions = new Map(); + const metadataByOrigin = new Map(); + const beforeSignOut = new Map>(); + + const failed = (reason: string) => new DeviceRevylAuthError({ reason }); + const ended = (host: RevylDeviceHostConfig) => + failed( + `Revyl ended the sign-in for ${host.label}. Sign in with Revyl again in Settings, or sign out to use the API key.`, + ); + const lockFor = (hostId: string) => { + const existing = locks.get(hostId); + if (existing) return existing; + const lock = Semaphore.makeUnsafe(1); + locks.set(hostId, lock); + return lock; + }; + const secretName = (hostId: string) => `revyl-device-host-${Base64Url.encode(hostId)}-oauth`; + + const readSession = Effect.fn("RevylOAuth.readSession")( + function* (hostId: string) { + const cached = sessions.get(hostId); + if (cached !== undefined) return cached; + const stored = yield* secrets.get(secretName(hostId)); + const session = Option.isNone(stored) + ? null + : yield* decodeSession(new TextDecoder().decode(stored.value)); + sessions.set(hostId, session); + return session; + }, + Effect.mapError(() => failed("Could not read the Revyl sign-in.")), + ); + + const writeSession = (hostId: string, session: Session | null) => + (session === null + ? secrets.remove(secretName(hostId)) + : encodeSession(session).pipe( + Effect.flatMap((json) => secrets.set(secretName(hostId), new TextEncoder().encode(json))), + ) + ).pipe( + Effect.andThen(Effect.sync(() => sessions.set(hostId, session))), + Effect.mapError(() => failed("Could not save the Revyl sign-in.")), + ); + + /** The stored session, while it still belongs to the host's client id and API origin. */ + const currentSession = (host: RevylDeviceHostConfig, apiOrigin: string) => + readSession(host.id).pipe( + Effect.map((session) => + session?.apiOrigin === apiOrigin && session.clientId === host.oauthClientId + ? session + : null, + ), + ); + + const discover = (apiOrigin: string) => + Effect.suspend(() => { + const known = metadataByOrigin.get(apiOrigin); + if (known) return Effect.succeed(known); + return http.execute(HttpClientRequest.get(apiOrigin + METADATA_PATH)).pipe( + Effect.flatMap(HttpClientResponse.filterStatusOk), + Effect.flatMap((response) => response.json), + Effect.flatMap(decodeMetadata), + Effect.scoped, + Effect.timeout(REQUEST_TIMEOUT), + Effect.mapError(() => failed(`${apiOrigin} did not describe Sign in with Revyl.`)), + Effect.filterOrFail( + (metadata) => metadata.issuer === apiOrigin + ISSUER_PATH, + () => failed(`${apiOrigin} names another Sign in with Revyl issuer.`), + ), + Effect.tap((metadata) => Effect.sync(() => metadataByOrigin.set(apiOrigin, metadata))), + ); + }); + + const requestTokens = (endpoint: string, params: Record) => + http + .execute( + HttpClientRequest.post(endpoint).pipe( + HttpClientRequest.bodyUrlParams(params), + HttpClientRequest.acceptJson, + ), + ) + .pipe( + Effect.flatMap((response) => + Effect.gen(function* () { + if (response.status < 300) + return { _tag: "Tokens" as const, tokens: yield* decodeTokens(yield* response.json) }; + const refusal = decodeTokenError(yield* response.text); + return { + _tag: "Refused" as const, + status: response.status, + error: Option.getOrUndefined(Option.map(refusal, ({ error }) => error)), + }; + }), + ), + Effect.scoped, + Effect.timeout(REQUEST_TIMEOUT), + ); + + const revoke = (session: Session) => + discover(session.apiOrigin).pipe( + Effect.flatMap((metadata) => + metadata.revocation_endpoint === undefined + ? Effect.void + : http + .execute( + HttpClientRequest.post(metadata.revocation_endpoint).pipe( + HttpClientRequest.bodyUrlParams({ + token: session.refreshToken, + client_id: session.clientId, + }), + ), + ) + .pipe( + Effect.flatMap(HttpClientResponse.filterStatusOk), + Effect.scoped, + Effect.timeout(REQUEST_TIMEOUT), + ), + ), + Effect.tapError((cause) => + Effect.logWarning("Could not revoke a Sign in with Revyl grant", { cause }), + ), + Effect.ignore, + ); + + const whoSignedIn = (apiOrigin: string, accessToken: string) => + http + .execute( + HttpClientRequest.get(`${apiOrigin}/api/v1/me`).pipe( + HttpClientRequest.bearerToken(accessToken), + ), + ) + .pipe( + Effect.flatMap(HttpClientResponse.filterStatusOk), + Effect.flatMap((response) => response.json), + Effect.scoped, + Effect.timeout(REQUEST_TIMEOUT), + Effect.map((body) => + Option.getOrUndefined( + Option.map( + decodeMe(body), + ({ user, organization }) => `${user.email} (${organization.name})`, + ), + ), + ), + Effect.orElseSucceed(() => undefined), + ); + + const account = (host: RevylDeviceHostConfig, apiOrigin: string) => + currentSession(host, apiOrigin).pipe(Effect.map(accountOf)); + + /** + * The host's access token, refreshed when it is about to expire or is the `rejected` one Revyl + * just answered 401 to; none while signed out. Revyl refusing the refresh ends the sign-in, and + * the host stays signed in but ended rather than quietly falling back to the API key. + */ + const accessToken = (host: RevylDeviceHostConfig, apiOrigin: string, rejected?: string) => + lockFor(host.id).withPermits(1)( + Effect.gen(function* () { + const session = yield* currentSession(host, apiOrigin); + if (session === null) return Option.none(); + if (session.ended) return yield* ended(host); + const now = yield* Clock.currentTimeMillis; + if (session.accessToken !== rejected && session.expiresAt - REFRESH_EARLY_MS > now) + return Option.some(session.accessToken); + const metadata = yield* discover(apiOrigin); + const outcome = yield* requestTokens(metadata.token_endpoint, { + grant_type: "refresh_token", + refresh_token: session.refreshToken, + client_id: session.clientId, + }).pipe( + Effect.mapError(() => failed(`Revyl did not refresh the sign-in for ${host.label}.`)), + ); + if (outcome._tag === "Refused") { + // unauthorized_client: the app's organization lost early access, which keeps the grant. + if ( + outcome.status >= 500 || + outcome.status === 429 || + outcome.error === "unauthorized_client" || + outcome.error === "temporarily_unavailable" + ) + return yield* failed( + `Revyl did not refresh the sign-in for ${host.label} (${outcome.error ?? `HTTP ${outcome.status}`}). Try again later.`, + ); + yield* writeSession(host.id, { ...session, ended: true }); + yield* Effect.logInfo("Revyl ended a Sign in with Revyl session", { + hostId: host.id, + error: outcome.error ?? outcome.status, + }); + return yield* ended(host); + } + const refreshed: Session = { + ...session, + accessToken: outcome.tokens.access_token, + refreshToken: outcome.tokens.refresh_token, + expiresAt: now + outcome.tokens.expires_in * 1_000, + }; + yield* writeSession(host.id, refreshed); + return Option.some(refreshed.accessToken); + }).pipe(Effect.uninterruptible), + ); + + /** + * Signs the host in on the server's machine: a loopback listener on an ephemeral port takes + * Revyl's redirect, so the browser has to run on the same computer. + */ + const signIn = Effect.fn("RevylOAuth.signIn")(function* ( + host: RevylDeviceHostConfig, + apiOrigin: string, + ) { + const clientId = host.oauthClientId; + if (!clientId) + return yield* failed(`Save a Sign in with Revyl client ID for ${host.label} first.`); + const metadata = yield* discover(apiOrigin); + const { verifier, challenge, state } = yield* makePkce; + const callback = yield* Deferred.make(); + const server = Context.get( + yield* Layer.build( + NodeHttpServer.layer(NodeHttp.createServer, { + host: "127.0.0.1", + port: 0, + disablePreemptiveShutdown: true, + }), + ).pipe(Effect.mapError(() => failed("Could not listen for Revyl's answer on this machine."))), + HttpServer.HttpServer, + ); + yield* server.serve( + Effect.gen(function* () { + const request = yield* HttpServerRequest.HttpServerRequest; + const url = new URL(request.originalUrl, "http://127.0.0.1"); + if (url.pathname !== "/callback") + return HttpServerResponse.text("Not Found", { status: 404 }); + const result = readCallback(url, { state, issuer: metadata.issuer }); + if (result._tag === "Ignored") + return HttpServerResponse.text("This is not the sign-in T3 Code started.", { + status: 400, + }); + if (result._tag === "Refused") { + yield* Deferred.fail(callback, failed(`Revyl did not sign in (${result.error}).`)); + return HttpServerResponse.text("Revyl did not sign in. You can close this tab."); + } + yield* Deferred.succeed(callback, result.code); + return HttpServerResponse.text( + "Signed in with Revyl. You can close this tab and go back to T3 Code.", + ); + }), + ); + const address = server.address; + if (!("port" in address)) + return yield* failed("Could not listen for Revyl's answer on this machine."); + const redirectUri = `http://127.0.0.1:${address.port}/callback`; + const authorizeUrl = new URL(metadata.authorization_endpoint); + authorizeUrl.search = new URLSearchParams({ + response_type: "code", + client_id: clientId, + redirect_uri: redirectUri, + scope: REVYL_OAUTH_SCOPES.join(" "), + state, + code_challenge: challenge, + code_challenge_method: "S256", + }) + .toString() + .replaceAll("+", "%20"); + yield* launcher + .launchBrowser(authorizeUrl.href) + .pipe( + Effect.mapError(() => + failed( + "Could not open a browser on the server's machine. Sign in with Revyl needs T3 Code's server and your browser on the same computer.", + ), + ), + ); + const code = yield* Deferred.await(callback).pipe( + Effect.timeoutOrElse({ + duration: SIGN_IN_TIMEOUT, + orElse: () => Effect.fail(failed("Sign in with Revyl timed out. Try again.")), + }), + ); + const outcome = yield* requestTokens(metadata.token_endpoint, { + grant_type: "authorization_code", + code, + redirect_uri: redirectUri, + client_id: clientId, + code_verifier: verifier, + }).pipe(Effect.mapError(() => failed("Revyl did not finish the sign-in. Try again."))); + if (outcome._tag === "Refused") + return yield* failed( + `Revyl refused the sign-in (${outcome.error ?? `HTTP ${outcome.status}`}).`, + ); + const signedInAs = yield* whoSignedIn(apiOrigin, outcome.tokens.access_token); + const session: Session = { + apiOrigin, + clientId, + accessToken: outcome.tokens.access_token, + refreshToken: outcome.tokens.refresh_token, + expiresAt: (yield* Clock.currentTimeMillis) + outcome.tokens.expires_in * 1_000, + ...(signedInAs ? { account: signedInAs } : {}), + }; + const previous = yield* lockFor(host.id).withPermits(1)( + readSession(host.id).pipe(Effect.tap(() => writeSession(host.id, session))), + ); + if (previous && !previous.ended) yield* revoke(previous); + yield* Effect.logInfo("Signed in with Revyl", { hostId: host.id }); + return accountOf(session); + }, Effect.scoped); + + /** Lets the host stop what it opened with the sign-in while its token still works. */ + const onSignOut = (hostId: string, release: Effect.Effect) => + Effect.acquireRelease( + Effect.sync(() => beforeSignOut.set(hostId, release)), + () => + Effect.sync(() => { + if (beforeSignOut.get(hostId) === release) beforeSignOut.delete(hostId); + }), + ); + + const signOut = Effect.fn("RevylOAuth.signOut")(function* (host: RevylDeviceHostConfig) { + yield* beforeSignOut.get(host.id) ?? Effect.void; + const session = yield* lockFor(host.id).withPermits(1)( + readSession(host.id).pipe(Effect.tap(() => writeSession(host.id, null))), + ); + if (session && !session.ended) yield* revoke(session); + yield* Effect.logInfo("Signed out of Revyl", { hostId: host.id }); + return accountOf(null); + }); + + return { account, accessToken, signIn, signOut, onSignOut }; +}); + +export type RevylAccounts = Effect.Success; diff --git a/apps/server/src/observability/RpcInstrumentation.ts b/apps/server/src/observability/RpcInstrumentation.ts index 02145b9f587a3..b42bfbce5d11c 100644 --- a/apps/server/src/observability/RpcInstrumentation.ts +++ b/apps/server/src/observability/RpcInstrumentation.ts @@ -269,6 +269,9 @@ const RPC_AGGREGATES = { [WS_METHODS.deviceTestHost]: "device", [WS_METHODS.deviceEasAccount]: "device", [WS_METHODS.deviceSimlockIdentity]: "device", + [WS_METHODS.deviceRevylAccount]: "device", + [WS_METHODS.deviceRevylSignIn]: "device", + [WS_METHODS.deviceRevylSignOut]: "device", [WS_METHODS.deviceList]: "device", [WS_METHODS.deviceOpen]: "device", [WS_METHODS.deviceClose]: "device", diff --git a/apps/server/src/ws.ts b/apps/server/src/ws.ts index 08b5e88cdc130..fdbfe8f4e35ce 100644 --- a/apps/server/src/ws.ts +++ b/apps/server/src/ws.ts @@ -3631,6 +3631,9 @@ export const layerWsRpc = ( [WS_METHODS.deviceTestHost]: (input) => deviceService.testHost(input), [WS_METHODS.deviceEasAccount]: (input) => deviceService.easAccount(input), [WS_METHODS.deviceSimlockIdentity]: (input) => deviceService.simlockIdentity(input), + [WS_METHODS.deviceRevylAccount]: (input) => deviceService.revylAccount(input), + [WS_METHODS.deviceRevylSignIn]: (input) => deviceService.revylSignIn(input), + [WS_METHODS.deviceRevylSignOut]: (input) => deviceService.revylSignOut(input), [WS_METHODS.deviceList]: (input) => input.inspectOnly && !input.updateTool ? deviceService.inspect diff --git a/apps/web/src/components/settings/RevylDeviceHostEditor.tsx b/apps/web/src/components/settings/RevylDeviceHostEditor.tsx index b0c25d8065e4c..3a1fa13fe0fce 100644 --- a/apps/web/src/components/settings/RevylDeviceHostEditor.tsx +++ b/apps/web/src/components/settings/RevylDeviceHostEditor.tsx @@ -1,7 +1,12 @@ +import { thrownErrorMessage } from "@t3tools/client-runtime/errors"; +import { useAtomValue } from "@effect/atom-react"; import { useId, useState } from "react"; +import * as Cause from "effect/Cause"; import * as Option from "effect/Option"; import { isSecretReference, + type DeviceRevylAccount, + type DeviceRevylAccountInput, type EnvironmentId, type RevylDeviceHostConfig, type SettingsSecretValue, @@ -9,6 +14,9 @@ import { import { T, useGT } from "gt-react"; import { XIcon } from "lucide-react"; +import { m } from "~/i18n/messages"; +import { deviceEnvironment, deviceRevylAccountCheck } from "../../state/device"; +import { useAtomCommand } from "../../state/use-atom-command"; import { Button } from "../ui/button"; import { Dialog, @@ -36,6 +44,99 @@ function withAppUrl( return next; } +const failureMessage = (cause: Cause.Cause) => { + const error = Cause.squash(cause); + return error instanceof Error ? (thrownErrorMessage(error, m) ?? error.message) : String(error); +}; + +/** Sign in with Revyl for a saved host, on the environment's server, which opens the browser. */ +function RevylSignIn(props: { environmentId: EnvironmentId; hostId: string; busy: boolean }) { + const gt = useGT(); + const signIn = useAtomCommand(deviceEnvironment.revylSignIn, { reportFailure: false }); + const signOut = useAtomCommand(deviceEnvironment.revylSignOut, { reportFailure: false }); + const input: DeviceRevylAccountInput = { hostId: props.hostId }; + const opened = useAtomValue( + deviceRevylAccountCheck({ environmentId: props.environmentId, input }), + ); + const [pending, setPending] = useState<"signIn" | "signOut" | null>(null); + const [answer, setAnswer] = useState< + { account: DeviceRevylAccount } | { error: string; account?: DeviceRevylAccount } | null + >(null); + const checked = + opened._tag === "Success" ? opened.value : opened._tag === "Failure" ? undefined : null; + const account = answer?.account ?? checked; + const error = + answer && "error" in answer + ? answer.error + : !answer && opened._tag === "Failure" + ? failureMessage(opened.cause) + : null; + const run = async (command: typeof signIn, kind: "signIn" | "signOut") => { + setPending(kind); + const result = await command({ environmentId: props.environmentId, input }); + setPending(null); + setAnswer( + result._tag === "Success" + ? { account: result.value } + : { + error: failureMessage(result.cause), + ...(account ? { account } : {}), + }, + ); + }; + const disabled = props.busy || pending !== null || account === null; + return ( +
+
+ {account === null || pending !== null ? : null} + {pending === "signIn" ? ( + + Finish signing in to Revyl in the browser on the server's computer. + + ) : account?.status === "signedIn" ? ( + + {account.account + ? gt("Signed in as {account}", { account: account.account }) + : gt("Signed in with Revyl")} + + ) : account?.status === "ended" ? ( + + Revyl ended this sign-in. Sign in again, or sign out to use the API key. + + ) : null} + + {account?.status !== "signedIn" ? ( + + ) : null} + {account && account.status !== "signedOut" ? ( + + ) : null} +
+ {error === null ? null : ( +

+ {error} +

+ )} +
+ ); +} + export function RevylDeviceHostEditor(props: { environmentId: EnvironmentId; host: RevylDeviceHostConfig; @@ -197,6 +298,41 @@ export function RevylDeviceHostEditor(props: { ) : null} + +

+ + Signed in, Revyl Macs use the sign-in instead of the API key; phones keep using the + key. + +

+ {!props.isNew && + props.host.oauthClientId !== undefined && + draft.oauthClientId === props.host.oauthClientId ? ( + + ) : ( +

+ Save the host with a client ID to sign in. +

+ )} {appUrl("iosAppUrl", gt("iOS app URL"), "https://…/MyApp-simulator.zip")} {appUrl("androidAppUrl", gt("Android app URL"), "https://…/app-debug.apk")}

diff --git a/apps/web/src/i18n/translations/de.json b/apps/web/src/i18n/translations/de.json index 4c20f5c5f61f5..31c3931991744 100644 --- a/apps/web/src/i18n/translations/de.json +++ b/apps/web/src/i18n/translations/de.json @@ -13341,5 +13341,14 @@ "e3d1a5914cf23c08": "Mac-Snapshot", "67a5d0ad9ce29e74": "Sauberer Mac", "5f625a0892bec5cd": "Ein Mac behält seine Festplatte, wenn er stoppt. Er stoppt, wenn sein Gerät geschlossen wird oder nach den Leerlaufminuten, in denen niemand ihn öffnet oder darauf tippt, und startet beim Öffnen erneut.", - "97df44304fca8f42": "Dieses Gerät ist nicht mehr geöffnet. Öffne es erneut über die Geräteliste." + "97df44304fca8f42": "Dieses Gerät ist nicht mehr geöffnet. Öffne es erneut über die Geräteliste.", + "885a8b3714f09e46": "Angemeldet als {account}", + "ceb9fbab695b8593": "Mit Revyl angemeldet", + "7f632dbed358d1d3": "Mit Revyl anmelden", + "a656dc69a38a3639": "Abmelden", + "99b10baacd359e1e": "Client-ID für die Revyl-Anmeldung", + "06b77f3c66438d3b": "Speichere den Host mit einer Client-ID, um dich anzumelden.", + "547880c4244d6119": "Schließe die Anmeldung bei Revyl im Browser auf dem Computer des Servers ab.", + "e2fa8ab80b979b14": "Revyl hat diese Anmeldung beendet. Melde dich erneut an oder melde dich ab, um den API-Schlüssel zu verwenden.", + "fdad26fb3905aad6": "Angemeldet verwenden Revyl-Macs die Anmeldung statt des API-Schlüssels; Telefone verwenden weiterhin den Schlüssel." } diff --git a/apps/web/src/i18n/translations/en.json b/apps/web/src/i18n/translations/en.json index a813149a36309..4f90bcd2f79b0 100644 --- a/apps/web/src/i18n/translations/en.json +++ b/apps/web/src/i18n/translations/en.json @@ -13348,5 +13348,14 @@ "e3d1a5914cf23c08": "Mac snapshot", "67a5d0ad9ce29e74": "Clean Mac", "5f625a0892bec5cd": "A Mac keeps its disk when it stops. It stops when its device closes, or after the idle minutes with nobody opening or typing into it, and starts again when opened.", - "97df44304fca8f42": "This device is no longer open. Open it again from the device list." + "97df44304fca8f42": "This device is no longer open. Open it again from the device list.", + "885a8b3714f09e46": "Signed in as {account}", + "ceb9fbab695b8593": "Signed in with Revyl", + "7f632dbed358d1d3": "Sign in with Revyl", + "a656dc69a38a3639": "Sign out", + "99b10baacd359e1e": "Sign in with Revyl client ID", + "06b77f3c66438d3b": "Save the host with a client ID to sign in.", + "547880c4244d6119": "Finish signing in to Revyl in the browser on the server's computer.", + "e2fa8ab80b979b14": "Revyl ended this sign-in. Sign in again, or sign out to use the API key.", + "fdad26fb3905aad6": "Signed in, Revyl Macs use the sign-in instead of the API key; phones keep using the key." } diff --git a/apps/web/src/i18n/translations/es.json b/apps/web/src/i18n/translations/es.json index 02216e62a3751..c2b51c8008ce3 100644 --- a/apps/web/src/i18n/translations/es.json +++ b/apps/web/src/i18n/translations/es.json @@ -13335,5 +13335,14 @@ "e3d1a5914cf23c08": "Snapshot del Mac", "67a5d0ad9ce29e74": "Mac limpio", "5f625a0892bec5cd": "Un Mac conserva su disco cuando se detiene. Se detiene cuando se cierra su dispositivo, o tras los minutos de inactividad sin que nadie lo abra ni escriba en él, y vuelve a iniciarse al abrirlo.", - "97df44304fca8f42": "Este dispositivo ya no está abierto. Ábrelo de nuevo desde la lista de dispositivos." + "97df44304fca8f42": "Este dispositivo ya no está abierto. Ábrelo de nuevo desde la lista de dispositivos.", + "885a8b3714f09e46": "Sesión iniciada como {account}", + "ceb9fbab695b8593": "Sesión iniciada con Revyl", + "7f632dbed358d1d3": "Iniciar sesión con Revyl", + "a656dc69a38a3639": "Cerrar sesión", + "99b10baacd359e1e": "ID de cliente para iniciar sesión con Revyl", + "06b77f3c66438d3b": "Guarda el host con un ID de cliente para iniciar sesión.", + "547880c4244d6119": "Termina de iniciar sesión en Revyl en el navegador del equipo del servidor.", + "e2fa8ab80b979b14": "Revyl finalizó esta sesión. Vuelve a iniciar sesión o ciérrala para usar la clave de API.", + "fdad26fb3905aad6": "Con la sesión iniciada, los Macs de Revyl usan la sesión en lugar de la clave de API; los teléfonos siguen usando la clave." } diff --git a/apps/web/src/i18n/translations/fr.json b/apps/web/src/i18n/translations/fr.json index adecef5711332..81057f00bdb59 100644 --- a/apps/web/src/i18n/translations/fr.json +++ b/apps/web/src/i18n/translations/fr.json @@ -13340,5 +13340,14 @@ "e3d1a5914cf23c08": "Instantané du Mac", "67a5d0ad9ce29e74": "Mac vierge", "5f625a0892bec5cd": "Un Mac conserve son disque lorsqu'il s'arrête. Il s'arrête quand son appareil est fermé, ou après les minutes d'inactivité sans que personne ne l'ouvre ni n'y tape, et redémarre à l'ouverture.", - "97df44304fca8f42": "Cet appareil n’est plus ouvert. Rouvrez-le depuis la liste des appareils." + "97df44304fca8f42": "Cet appareil n’est plus ouvert. Rouvrez-le depuis la liste des appareils.", + "885a8b3714f09e46": "Connecté en tant que {account}", + "ceb9fbab695b8593": "Connecté avec Revyl", + "7f632dbed358d1d3": "Se connecter avec Revyl", + "a656dc69a38a3639": "Se déconnecter", + "99b10baacd359e1e": "ID client pour se connecter avec Revyl", + "06b77f3c66438d3b": "Enregistrez l’hôte avec un ID client pour vous connecter.", + "547880c4244d6119": "Terminez la connexion à Revyl dans le navigateur de l’ordinateur du serveur.", + "e2fa8ab80b979b14": "Revyl a mis fin à cette connexion. Reconnectez-vous, ou déconnectez-vous pour utiliser la clé d’API.", + "fdad26fb3905aad6": "Une fois connecté, les Mac Revyl utilisent la connexion au lieu de la clé d’API ; les téléphones continuent d’utiliser la clé." } diff --git a/apps/web/src/i18n/translations/ja.json b/apps/web/src/i18n/translations/ja.json index c801ee0c66727..580147539e1cf 100644 --- a/apps/web/src/i18n/translations/ja.json +++ b/apps/web/src/i18n/translations/ja.json @@ -13276,5 +13276,14 @@ "e3d1a5914cf23c08": "Mac スナップショット", "67a5d0ad9ce29e74": "クリーンな Mac", "5f625a0892bec5cd": "Mac は停止してもディスクを保持します。デバイスを閉じたとき、またはアイドル時間のあいだ誰も開かず入力もしなかったときに停止し、開くと再び起動します。", - "97df44304fca8f42": "このデバイスは開かれていません。デバイス一覧からもう一度開いてください。" + "97df44304fca8f42": "このデバイスは開かれていません。デバイス一覧からもう一度開いてください。", + "885a8b3714f09e46": "{account} としてサインインしています", + "ceb9fbab695b8593": "Revyl でサインインしています", + "7f632dbed358d1d3": "Revyl でサインイン", + "a656dc69a38a3639": "サインアウト", + "99b10baacd359e1e": "Revyl サインイン用のクライアント ID", + "06b77f3c66438d3b": "サインインするには、クライアント ID を入れてホストを保存してください。", + "547880c4244d6119": "サーバーのコンピューターのブラウザで Revyl へのサインインを完了してください。", + "e2fa8ab80b979b14": "Revyl がこのサインインを終了しました。もう一度サインインするか、サインアウトして API キーを使ってください。", + "fdad26fb3905aad6": "サインイン中は、Revyl Mac は API キーの代わりにサインインを使います。電話は引き続きキーを使います。" } diff --git a/apps/web/src/i18n/translations/ko.json b/apps/web/src/i18n/translations/ko.json index ad39e517d2130..a285d719450b9 100644 --- a/apps/web/src/i18n/translations/ko.json +++ b/apps/web/src/i18n/translations/ko.json @@ -13273,5 +13273,14 @@ "e3d1a5914cf23c08": "Mac 스냅샷", "67a5d0ad9ce29e74": "깨끗한 Mac", "5f625a0892bec5cd": "Mac은 중지되어도 디스크를 유지합니다. 기기를 닫거나 유휴 시간 동안 아무도 열거나 입력하지 않으면 중지되며, 열면 다시 시작됩니다.", - "97df44304fca8f42": "이 기기는 더 이상 열려 있지 않습니다. 기기 목록에서 다시 여세요." + "97df44304fca8f42": "이 기기는 더 이상 열려 있지 않습니다. 기기 목록에서 다시 여세요.", + "885a8b3714f09e46": "{account}(으)로 로그인됨", + "ceb9fbab695b8593": "Revyl로 로그인됨", + "7f632dbed358d1d3": "Revyl로 로그인", + "a656dc69a38a3639": "로그아웃", + "99b10baacd359e1e": "Revyl 로그인용 클라이언트 ID", + "06b77f3c66438d3b": "로그인하려면 클라이언트 ID와 함께 호스트를 저장하세요.", + "547880c4244d6119": "서버 컴퓨터의 브라우저에서 Revyl 로그인을 완료하세요.", + "e2fa8ab80b979b14": "Revyl이 이 로그인을 종료했습니다. 다시 로그인하거나, 로그아웃하여 API 키를 사용하세요.", + "fdad26fb3905aad6": "로그인하면 Revyl Mac은 API 키 대신 로그인을 사용합니다. 휴대폰은 계속 키를 사용합니다." } diff --git a/apps/web/src/i18n/translations/pl.json b/apps/web/src/i18n/translations/pl.json index 0d5a57289aad9..bb5df01831d8f 100644 --- a/apps/web/src/i18n/translations/pl.json +++ b/apps/web/src/i18n/translations/pl.json @@ -7,10 +7,18 @@ "67cd441c3345c6eb": [ "Pozwól panelowi Urządzenie otwierać chmurowe symulatory iOS i emulatory Androida z", " ", - { "t": "a", "i": 1, "c": "Revyl" }, + { + "t": "a", + "i": 1, + "c": "Revyl" + }, ", dodane w", " ", - { "t": "Link", "i": 2, "c": "Urządzeniach" }, + { + "t": "Link", + "i": 2, + "c": "Urządzeniach" + }, ". Sesje są rozliczane w Twojej organizacji Revyl. Wersja alfa, która może się zmienić lub przestać działać." ], "a9e2f81b0f3fd13f": "Nadaj hostowi nazwę, podaj adresy https aplikacji i limity w pokazanych zakresach.", @@ -13340,5 +13348,14 @@ "987dc6b9898eff50": "Uruchomienie przepływu pracy", "cc33fdbe7deb587e": "Najpierw wybierz uruchomienie", "e3588d60727537d6": "Nie udało się przenieść wiadomości z kolejki do schowka", - "4cc9772e657ae667": "Wiadomość nadal jest w kolejce." + "4cc9772e657ae667": "Wiadomość nadal jest w kolejce.", + "885a8b3714f09e46": "Zalogowano jako {account}", + "ceb9fbab695b8593": "Zalogowano przez Revyl", + "7f632dbed358d1d3": "Zaloguj się przez Revyl", + "a656dc69a38a3639": "Wyloguj się", + "99b10baacd359e1e": "Identyfikator klienta do logowania przez Revyl", + "06b77f3c66438d3b": "Zapisz hosta z identyfikatorem klienta, aby się zalogować.", + "547880c4244d6119": "Dokończ logowanie do Revyl w przeglądarce na komputerze serwera.", + "e2fa8ab80b979b14": "Revyl zakończył to logowanie. Zaloguj się ponownie lub wyloguj się, aby używać klucza API.", + "fdad26fb3905aad6": "Po zalogowaniu Maki Revyl używają logowania zamiast klucza API; telefony nadal używają klucza." } diff --git a/apps/web/src/i18n/translations/pt-BR.json b/apps/web/src/i18n/translations/pt-BR.json index 725adc3677ad7..e00ac33b5bc48 100644 --- a/apps/web/src/i18n/translations/pt-BR.json +++ b/apps/web/src/i18n/translations/pt-BR.json @@ -13340,5 +13340,14 @@ "e3d1a5914cf23c08": "Snapshot do Mac", "67a5d0ad9ce29e74": "Mac limpo", "5f625a0892bec5cd": "Um Mac mantém o disco quando para. Ele para quando o dispositivo é fechado, ou após os minutos ociosos sem ninguém abri-lo ou digitar nele, e inicia novamente ao ser aberto.", - "97df44304fca8f42": "Este dispositivo não está mais aberto. Abra-o novamente na lista de dispositivos." + "97df44304fca8f42": "Este dispositivo não está mais aberto. Abra-o novamente na lista de dispositivos.", + "885a8b3714f09e46": "Conectado como {account}", + "ceb9fbab695b8593": "Conectado com a Revyl", + "7f632dbed358d1d3": "Entrar com a Revyl", + "a656dc69a38a3639": "Sair", + "99b10baacd359e1e": "ID do cliente para entrar com a Revyl", + "06b77f3c66438d3b": "Salve o host com um ID do cliente para entrar.", + "547880c4244d6119": "Conclua a entrada na Revyl no navegador do computador do servidor.", + "e2fa8ab80b979b14": "A Revyl encerrou esta sessão. Entre novamente ou saia para usar a chave de API.", + "fdad26fb3905aad6": "Com a sessão iniciada, os Macs da Revyl usam a sessão em vez da chave de API; os telefones continuam usando a chave." } diff --git a/apps/web/src/i18n/translations/ru.json b/apps/web/src/i18n/translations/ru.json index eb253dd88cc84..c7161d0ba6fdb 100644 --- a/apps/web/src/i18n/translations/ru.json +++ b/apps/web/src/i18n/translations/ru.json @@ -13339,5 +13339,14 @@ "e3d1a5914cf23c08": "Снимок Mac", "67a5d0ad9ce29e74": "Чистый Mac", "5f625a0892bec5cd": "Mac сохраняет свой диск при остановке. Он останавливается, когда его устройство закрывают или когда в течение минут простоя никто его не открывает и ничего не вводит, и снова запускается при открытии.", - "97df44304fca8f42": "Это устройство больше не открыто. Откройте его снова из списка устройств." + "97df44304fca8f42": "Это устройство больше не открыто. Откройте его снова из списка устройств.", + "885a8b3714f09e46": "Вход выполнен как {account}", + "ceb9fbab695b8593": "Вход выполнен через Revyl", + "7f632dbed358d1d3": "Войти через Revyl", + "a656dc69a38a3639": "Выйти", + "99b10baacd359e1e": "ID клиента для входа через Revyl", + "06b77f3c66438d3b": "Сохраните хост с ID клиента, чтобы войти.", + "547880c4244d6119": "Завершите вход в Revyl в браузере на компьютере сервера.", + "e2fa8ab80b979b14": "Revyl завершил этот вход. Войдите снова или выйдите, чтобы использовать API-ключ.", + "fdad26fb3905aad6": "После входа Маки Revyl используют вход вместо API-ключа; телефоны продолжают использовать ключ." } diff --git a/apps/web/src/i18n/translations/sv.json b/apps/web/src/i18n/translations/sv.json index 625bbf573b2be..f2a84eb7335cc 100644 --- a/apps/web/src/i18n/translations/sv.json +++ b/apps/web/src/i18n/translations/sv.json @@ -13347,5 +13347,14 @@ "e3d1a5914cf23c08": "Mac-ögonblicksbild", "67a5d0ad9ce29e74": "Ren Mac", "5f625a0892bec5cd": "En Mac behåller sin disk när den stoppas. Den stoppas när enheten stängs, eller efter vilominuterna utan att någon öppnar eller skriver i den, och startar igen när den öppnas.", - "97df44304fca8f42": "Enheten är inte längre öppen. Öppna den igen från enhetslistan." + "97df44304fca8f42": "Enheten är inte längre öppen. Öppna den igen från enhetslistan.", + "885a8b3714f09e46": "Inloggad som {account}", + "ceb9fbab695b8593": "Inloggad med Revyl", + "7f632dbed358d1d3": "Logga in med Revyl", + "a656dc69a38a3639": "Logga ut", + "99b10baacd359e1e": "Klient-ID för inloggning med Revyl", + "06b77f3c66438d3b": "Spara värden med ett klient-ID för att logga in.", + "547880c4244d6119": "Slutför inloggningen till Revyl i webbläsaren på serverns dator.", + "e2fa8ab80b979b14": "Revyl avslutade den här inloggningen. Logga in igen, eller logga ut för att använda API-nyckeln.", + "fdad26fb3905aad6": "När du är inloggad använder Revyl-Mac-datorer inloggningen i stället för API-nyckeln; telefoner fortsätter använda nyckeln." } diff --git a/apps/web/src/i18n/translations/zh.json b/apps/web/src/i18n/translations/zh.json index 7d13aa955d51d..ccb6f392ad8fc 100644 --- a/apps/web/src/i18n/translations/zh.json +++ b/apps/web/src/i18n/translations/zh.json @@ -13356,5 +13356,14 @@ "e3d1a5914cf23c08": "Mac 快照", "67a5d0ad9ce29e74": "全新 Mac", "5f625a0892bec5cd": "Mac 停止时会保留其磁盘。关闭其设备时,或在空闲分钟内无人打开或输入时,它会停止,再次打开时会重新启动。", - "97df44304fca8f42": "此设备已不再打开。请从设备列表中重新打开。" + "97df44304fca8f42": "此设备已不再打开。请从设备列表中重新打开。", + "885a8b3714f09e46": "已以 {account} 身份登录", + "ceb9fbab695b8593": "已使用 Revyl 登录", + "7f632dbed358d1d3": "使用 Revyl 登录", + "a656dc69a38a3639": "退出登录", + "99b10baacd359e1e": "Revyl 登录的客户端 ID", + "06b77f3c66438d3b": "使用客户端 ID 保存主机后即可登录。", + "547880c4244d6119": "请在服务器所在电脑的浏览器中完成 Revyl 登录。", + "e2fa8ab80b979b14": "Revyl 已结束此登录。请重新登录,或退出登录以使用 API 密钥。", + "fdad26fb3905aad6": "登录后,Revyl Mac 使用登录而非 API 密钥;手机继续使用密钥。" } diff --git a/apps/web/src/state/device.ts b/apps/web/src/state/device.ts index a386d8b5d3650..07a6b615d4635 100644 --- a/apps/web/src/state/device.ts +++ b/apps/web/src/state/device.ts @@ -170,6 +170,14 @@ export const deviceEasAccountCheck = createEnvironmentRpcQueryAtomFamily(connect idleTtlMs: 0, }); +/** A saved Revyl host's Sign in with Revyl state, checked as its editor opens. */ +export const deviceRevylAccountCheck = createEnvironmentRpcQueryAtomFamily(connectionAtomRuntime, { + label: "environment-data:device:revyl-account-check", + tag: WS_METHODS.deviceRevylAccount, + staleTimeMs: 0, + idleTtlMs: 0, +}); + /** Who a Simlock token is, checked as the host editor's URL and token fields change. */ export const deviceSimlockIdentityCheck = createEnvironmentRpcQueryAtomFamily( connectionAtomRuntime, diff --git a/docs/user/devices.md b/docs/user/devices.md index 3403573bbf113..800e767671d89 100644 --- a/docs/user/devices.md +++ b/docs/user/devices.md @@ -108,6 +108,17 @@ a drag drags. Typing goes to the focused app, and shortcuts such as Command-C are sent as shortcuts. Agents do not drive a Mac through device tools; run T3 Code on the Mac itself for that. +#### Sign in with Revyl + +Macs can use your own Revyl sign-in instead of the host's API key. Register a +public OAuth app in Revyl with the redirect URI `http://127.0.0.1/callback`, +put its client ID in the host's **Sign in with Revyl client ID**, save the +host, and choose **Sign in with Revyl**. The browser opens on the computer +running the environment's server, so finish signing in there. While signed in, +Macs use the sign-in and phones keep using the API key. When Revyl ends the +sign-in, Macs stop working until you sign in again or sign out to return to +the key. Revyl must allow the app the `computers` scope for your organization. + ## Device tool updates The T3 server manages device hub and `agent-device` versions automatically on itself and SSH hosts. Check versions in **Settings → Devices → Check versions**; update the remote T3 server to receive newer device tools. diff --git a/packages/client-runtime/src/state/device.ts b/packages/client-runtime/src/state/device.ts index 6a4920caa251c..b896c3dfbcabf 100644 --- a/packages/client-runtime/src/state/device.ts +++ b/packages/client-runtime/src/state/device.ts @@ -56,6 +56,14 @@ export function createDeviceEnvironmentAtoms( label: "environment-data:device:eas-account", tag: WS_METHODS.deviceEasAccount, }), + revylSignIn: createEnvironmentRpcCommand(runtime, { + label: "environment-data:device:revyl-sign-in", + tag: WS_METHODS.deviceRevylSignIn, + }), + revylSignOut: createEnvironmentRpcCommand(runtime, { + label: "environment-data:device:revyl-sign-out", + tag: WS_METHODS.deviceRevylSignOut, + }), list: createEnvironmentRpcCommand(runtime, { label: "environment-data:device:list", tag: WS_METHODS.deviceList, diff --git a/packages/contracts/src/device.ts b/packages/contracts/src/device.ts index 80773f729d6f9..6a2de92943362 100644 --- a/packages/contracts/src/device.ts +++ b/packages/contracts/src/device.ts @@ -137,6 +137,11 @@ export const RevylDeviceHostConfig = Schema.Struct({ macIdleMinutes: Schema.Int.check(Schema.isBetween({ minimum: 5, maximum: 240 })).pipe( Schema.withDecodingDefaultKey(Effect.succeed(15)), ), + /** + * The registered client id of a public Revyl OAuth app. Signed in with it, Revyl Macs use the + * sign-in instead of the API key; phones always use the API key. + */ + oauthClientId: Schema.optional(TrimmedString.check(Schema.isMaxLength(128))), }); export type RevylDeviceHostConfig = typeof RevylDeviceHostConfig.Type; @@ -208,6 +213,26 @@ export class DeviceSimlockIdentityError extends Schema.TaggedError()( + "DeviceRevylAuthError", + { reason: Schema.String }, +) { + override get message(): string { + return this.reason; + } +} + /** Checking an Expo credential failed; no device host is involved yet. */ export class DeviceEasAccountError extends Schema.TaggedError()( "DeviceEasAccountError", diff --git a/packages/contracts/src/rpc.ts b/packages/contracts/src/rpc.ts index 4ae51aa9994c4..323e5bbb05ece 100644 --- a/packages/contracts/src/rpc.ts +++ b/packages/contracts/src/rpc.ts @@ -375,6 +375,9 @@ import { DeviceSimlockIdentity, DeviceSimlockIdentityError, DeviceSimlockIdentityInput, + DeviceRevylAccount, + DeviceRevylAccountInput, + DeviceRevylAuthError, DeviceHostSummary, DeviceOpenInput, DeviceServiceState, @@ -596,6 +599,9 @@ export const WS_METHODS = { deviceTestHost: "device.testHost", deviceEasAccount: "device.easAccount", deviceSimlockIdentity: "device.simlockIdentity", + deviceRevylAccount: "device.revylAccount", + deviceRevylSignIn: "device.revylSignIn", + deviceRevylSignOut: "device.revylSignOut", deviceOpen: "device.open", deviceClose: "device.close", deviceShutdown: "device.shutdown", @@ -2170,6 +2176,16 @@ const WsDeviceSimlockIdentityRpc = Rpc.make(WS_METHODS.deviceSimlockIdentity, { error: Schema.Union([DeviceSimlockIdentityError, EnvironmentAuthorizationError]), }); +const revylAccountRpc = { + payload: DeviceRevylAccountInput, + success: DeviceRevylAccount, + error: Schema.Union([DeviceRevylAuthError, EnvironmentAuthorizationError]), +}; +const WsDeviceRevylAccountRpc = Rpc.make(WS_METHODS.deviceRevylAccount, revylAccountRpc); +/** Runs the whole browser sign-in on the server's machine, so it answers when the sign-in ends. */ +const WsDeviceRevylSignInRpc = Rpc.make(WS_METHODS.deviceRevylSignIn, revylAccountRpc); +const WsDeviceRevylSignOutRpc = Rpc.make(WS_METHODS.deviceRevylSignOut, revylAccountRpc); + const WsDeviceListRpc = Rpc.make(WS_METHODS.deviceList, { payload: DeviceListInput, success: DeviceServiceState, @@ -2821,6 +2837,9 @@ export const WsRpcGroup = RpcGroup.make( WsDeviceTestHostRpc, WsDeviceEasAccountRpc, WsDeviceSimlockIdentityRpc, + WsDeviceRevylAccountRpc, + WsDeviceRevylSignInRpc, + WsDeviceRevylSignOutRpc, WsDeviceOpenRpc, WsDeviceCloseRpc, WsDeviceShutdownRpc, From 7222a018d3bafd016f5e666bbf3e98713b0eff4a Mon Sep 17 00:00:00 2001 From: KayaanT <34585438+KayaanT@users.noreply.github.com> Date: Wed, 2 Dec 2026 05:46:09 +0000 Subject: [PATCH 2/8] feat(device): request Revyl's computers.view and computers.control scopes Sign in with Revyl now asks for account.read computers computers.view computers.control. Revyl gives OAuth tokens no unauthenticated WHEP stream, so a signed-in Mac whose feed has no stream fails at once with that reason instead of waiting out the open timeout. Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> --- .../server/src/device/RevylDeviceHost.test.ts | 66 ++++++++++++------- apps/server/src/device/RevylDeviceHost.ts | 12 +++- apps/server/src/device/RevylOAuth.test.ts | 8 ++- apps/server/src/device/RevylOAuth.ts | 7 +- docs/user/devices.md | 4 +- 5 files changed, 69 insertions(+), 28 deletions(-) diff --git a/apps/server/src/device/RevylDeviceHost.test.ts b/apps/server/src/device/RevylDeviceHost.test.ts index bbbafd45e9a0a..6b16688d85e86 100644 --- a/apps/server/src/device/RevylDeviceHost.test.ts +++ b/apps/server/src/device/RevylDeviceHost.test.ts @@ -81,6 +81,7 @@ const fakeRevyl = Effect.gen(function* () { >(); let rotated = false; let sessionEnded = false; + let oauthFeed: "noStream" | "refused" = "noStream"; const http = HttpClient.make((request) => Effect.sync(() => { const url = new URL(request.url); @@ -116,22 +117,24 @@ const fakeRevyl = Effect.gen(function* () { refresh_token: "oauth-refresh-2", expires_in: 3600, }); - // Sign in with Revyl reaches Mac lifecycle but not the screen, as Revyl's computers scope does. + // Revyl gives Sign in with Revyl no unauthenticated WHEP stream: none, or a refusal. if ( request.headers.authorization === "Bearer oauth-access" && - /\/(device-sessions|viewer-ice-servers|screen)\b/.test(url.pathname) + url.pathname.includes("/device-sessions/") ) - return json( - { - detail: { - error: "not_available_to_oauth_apps", - message: "OAuth apps can't use this endpoint.", - required_scope: null, - }, - code: "access_denied", - }, - 403, - ); + return oauthFeed === "noStream" + ? json({ status: "running", whep_url: null, screen_width: 1280, screen_height: 800 }) + : json( + { + detail: { + error: "not_available_to_oauth_apps", + message: "OAuth apps can't use this endpoint.", + required_scope: null, + }, + code: "access_denied", + }, + 403, + ); if ( request.headers.authorization !== "Bearer revyl-key" && request.headers.authorization !== "Bearer oauth-access" @@ -225,7 +228,20 @@ const fakeRevyl = Effect.gen(function* () { const endSession = () => { sessionEnded = true; }; - return { http, runner, requests, ran, actions, macActions, computers, endSession }; + const answerOAuthFeed = (answer: typeof oauthFeed) => { + oauthFeed = answer; + }; + return { + http, + runner, + requests, + ran, + actions, + macActions, + computers, + endSession, + answerOAuthFeed, + }; }); const makeSecretResolver = () => @@ -788,11 +804,21 @@ describe("Revyl Macs", () => { }).pipe(Effect.scoped, Effect.provide(layer)), ); - it.effect( - "signed in with Revyl, runs a Mac's lifecycle on the sign-in, refreshing once on a 401, and says why Revyl refuses its screen", - () => + it.effect.each([ + [ + "noStream", + "Revyl does not stream a Mac's screen to Sign in with Revyl yet. Sign out of Revyl in Settings to use the API key.", + ], + [ + "refused", + "Revyl does not let Sign in with Revyl do this yet (not_available_to_oauth_apps). Sign out of Revyl in Settings to use the API key.", + ], + ] as const)( + "signed in with Revyl, runs a Mac's lifecycle on the sign-in, refreshing once on a 401, and fails at once with a reason when the feed is %s", + ([feed, reason]) => Effect.gen(function* () { const revyl = yield* fakeRevyl; + revyl.answerOAuthFeed(feed); const scope = yield* Scope.make(); const host = yield* makeHost( revyl, @@ -815,11 +841,7 @@ describe("Revyl Macs", () => { ); const refused = yield* Effect.flip(ready.devices.boot(catalog!)); - expect(refused).toMatchObject({ - _tag: "DeviceBootError", - diagnostics: - "Revyl does not let Sign in with Revyl do this yet (not_available_to_oauth_apps). Sign out of Revyl in Settings to use the API key.", - }); + expect(refused).toMatchObject({ _tag: "DeviceBootError", diagnostics: reason }); const create = revyl.requests.find( (request) => request.method === "POST" && request.url.endsWith("/api/v1/computer-runs"), ); diff --git a/apps/server/src/device/RevylDeviceHost.ts b/apps/server/src/device/RevylDeviceHost.ts index 28078b91e35d4..0528aa6a1eae4 100644 --- a/apps/server/src/device/RevylDeviceHost.ts +++ b/apps/server/src/device/RevylDeviceHost.ts @@ -698,7 +698,17 @@ export const make = Effect.fn("RevylDeviceHost.make")(function* ( `/api/v1/execution/device-sessions/${encodeURIComponent(runSessionId)}?include_computers=true`, ).pipe( Effect.flatMap(decodeScreenFeed), - Effect.map((feed) => (feed.whep_url ? { ...feed, whep_url: feed.whep_url } : null)), + Effect.flatMap((feed) => + feed.whep_url + ? Effect.succeed({ ...feed, whep_url: feed.whep_url }) + : credential === null + ? Effect.fail( + unavailable( + "Revyl does not stream a Mac's screen to Sign in with Revyl yet. Sign out of Revyl in Settings to use the API key.", + ), + ) + : Effect.succeed(null), + ), ), "publish its screen", ); diff --git a/apps/server/src/device/RevylOAuth.test.ts b/apps/server/src/device/RevylOAuth.test.ts index 3ae0458b760a5..c27b8081315e8 100644 --- a/apps/server/src/device/RevylOAuth.test.ts +++ b/apps/server/src/device/RevylOAuth.test.ts @@ -211,7 +211,7 @@ describe("Sign in with Revyl tokens", () => { refresh_token: "refresh-new", expires_in: 3600, token_type: "Bearer", - scope: "account.read computers", + scope: "account.read computers computers.view computers.control", }, } : { status: 400, body: { error: "invalid_grant" } }, @@ -243,11 +243,13 @@ describe("Sign in with Revyl tokens", () => { const authorize = new URL(revyl.launched[0]!); expect(authorize.origin + authorize.pathname).toBe(`${ISSUER}/authorize`); - expect(revyl.launched[0]).toContain("scope=account.read%20computers"); + expect(revyl.launched[0]).toContain( + "scope=account.read%20computers%20computers.view%20computers.control", + ); expect(Object.fromEntries(authorize.searchParams)).toMatchObject({ response_type: "code", client_id: "revylapp_t3", - scope: "account.read computers", + scope: "account.read computers computers.view computers.control", code_challenge_method: "S256", }); expect(authorize.searchParams.get("redirect_uri")).toMatch( diff --git a/apps/server/src/device/RevylOAuth.ts b/apps/server/src/device/RevylOAuth.ts index 125bdf3a4210d..d986b58331822 100644 --- a/apps/server/src/device/RevylOAuth.ts +++ b/apps/server/src/device/RevylOAuth.ts @@ -38,7 +38,12 @@ import * as ServerSecretStore from "../auth/ServerSecretStore.ts"; import * as ExternalLauncher from "../process/externalLauncher.ts"; /** `computers` covers persistent Mac lifecycle; `account.read` names who signed in. */ -const REVYL_OAUTH_SCOPES = ["account.read", "computers"] as const; +const REVYL_OAUTH_SCOPES = [ + "account.read", + "computers", + "computers.view", + "computers.control", +] as const; const ISSUER_PATH = "/api/v1/oauth2"; const METADATA_PATH = `/.well-known/oauth-authorization-server${ISSUER_PATH}`; const SIGN_IN_TIMEOUT = Duration.minutes(5); diff --git a/docs/user/devices.md b/docs/user/devices.md index 800e767671d89..caa0b1db529d5 100644 --- a/docs/user/devices.md +++ b/docs/user/devices.md @@ -117,7 +117,9 @@ host, and choose **Sign in with Revyl**. The browser opens on the computer running the environment's server, so finish signing in there. While signed in, Macs use the sign-in and phones keep using the API key. When Revyl ends the sign-in, Macs stop working until you sign in again or sign out to return to -the key. Revyl must allow the app the `computers` scope for your organization. +the key. T3 asks for the `account.read`, `computers`, `computers.view`, and +`computers.control` scopes. Revyl does not stream a Mac's screen to a sign-in +yet, so opening a Mac while signed in fails with that reason until it does. ## Device tool updates From 853cb5264a27a4e7ec7e290e76c6adbe57635799 Mon Sep 17 00:00:00 2001 From: KayaanT <34585438+KayaanT@users.noreply.github.com> Date: Wed, 2 Dec 2026 06:07:21 +0000 Subject: [PATCH 3/8] feat(device): request only Revyl's computers scope for Sign in with Revyl Revyl's single computers scope covers the persistent Mac surface, screen included, so drop computers.view and computers.control and poll a signed-in Mac's stream like the API key does. A refused feed still surfaces Revyl's reason and stops the Mac. Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> --- .../server/src/device/RevylDeviceHost.test.ts | 64 ++++++------------- apps/server/src/device/RevylDeviceHost.ts | 12 +--- apps/server/src/device/RevylOAuth.test.ts | 8 +-- apps/server/src/device/RevylOAuth.ts | 7 +- docs/user/devices.md | 5 +- 5 files changed, 28 insertions(+), 68 deletions(-) diff --git a/apps/server/src/device/RevylDeviceHost.test.ts b/apps/server/src/device/RevylDeviceHost.test.ts index 6b16688d85e86..31c66070528b7 100644 --- a/apps/server/src/device/RevylDeviceHost.test.ts +++ b/apps/server/src/device/RevylDeviceHost.test.ts @@ -81,7 +81,6 @@ const fakeRevyl = Effect.gen(function* () { >(); let rotated = false; let sessionEnded = false; - let oauthFeed: "noStream" | "refused" = "noStream"; const http = HttpClient.make((request) => Effect.sync(() => { const url = new URL(request.url); @@ -117,24 +116,22 @@ const fakeRevyl = Effect.gen(function* () { refresh_token: "oauth-refresh-2", expires_in: 3600, }); - // Revyl gives Sign in with Revyl no unauthenticated WHEP stream: none, or a refusal. + // An organization whose Revyl refuses Sign in with Revyl the Mac's screen feed. if ( request.headers.authorization === "Bearer oauth-access" && url.pathname.includes("/device-sessions/") ) - return oauthFeed === "noStream" - ? json({ status: "running", whep_url: null, screen_width: 1280, screen_height: 800 }) - : json( - { - detail: { - error: "not_available_to_oauth_apps", - message: "OAuth apps can't use this endpoint.", - required_scope: null, - }, - code: "access_denied", - }, - 403, - ); + return json( + { + detail: { + error: "not_available_to_oauth_apps", + message: "OAuth apps can't use this endpoint.", + required_scope: null, + }, + code: "access_denied", + }, + 403, + ); if ( request.headers.authorization !== "Bearer revyl-key" && request.headers.authorization !== "Bearer oauth-access" @@ -228,20 +225,7 @@ const fakeRevyl = Effect.gen(function* () { const endSession = () => { sessionEnded = true; }; - const answerOAuthFeed = (answer: typeof oauthFeed) => { - oauthFeed = answer; - }; - return { - http, - runner, - requests, - ran, - actions, - macActions, - computers, - endSession, - answerOAuthFeed, - }; + return { http, runner, requests, ran, actions, macActions, computers, endSession }; }); const makeSecretResolver = () => @@ -804,21 +788,11 @@ describe("Revyl Macs", () => { }).pipe(Effect.scoped, Effect.provide(layer)), ); - it.effect.each([ - [ - "noStream", - "Revyl does not stream a Mac's screen to Sign in with Revyl yet. Sign out of Revyl in Settings to use the API key.", - ], - [ - "refused", - "Revyl does not let Sign in with Revyl do this yet (not_available_to_oauth_apps). Sign out of Revyl in Settings to use the API key.", - ], - ] as const)( - "signed in with Revyl, runs a Mac's lifecycle on the sign-in, refreshing once on a 401, and fails at once with a reason when the feed is %s", - ([feed, reason]) => + it.effect( + "signed in with Revyl, runs a Mac's lifecycle on the sign-in, refreshing once on a 401, and says why Revyl refuses its screen", + () => Effect.gen(function* () { const revyl = yield* fakeRevyl; - revyl.answerOAuthFeed(feed); const scope = yield* Scope.make(); const host = yield* makeHost( revyl, @@ -841,7 +815,11 @@ describe("Revyl Macs", () => { ); const refused = yield* Effect.flip(ready.devices.boot(catalog!)); - expect(refused).toMatchObject({ _tag: "DeviceBootError", diagnostics: reason }); + expect(refused).toMatchObject({ + _tag: "DeviceBootError", + diagnostics: + "Revyl does not let Sign in with Revyl do this yet (not_available_to_oauth_apps). Sign out of Revyl in Settings to use the API key.", + }); const create = revyl.requests.find( (request) => request.method === "POST" && request.url.endsWith("/api/v1/computer-runs"), ); diff --git a/apps/server/src/device/RevylDeviceHost.ts b/apps/server/src/device/RevylDeviceHost.ts index 0528aa6a1eae4..28078b91e35d4 100644 --- a/apps/server/src/device/RevylDeviceHost.ts +++ b/apps/server/src/device/RevylDeviceHost.ts @@ -698,17 +698,7 @@ export const make = Effect.fn("RevylDeviceHost.make")(function* ( `/api/v1/execution/device-sessions/${encodeURIComponent(runSessionId)}?include_computers=true`, ).pipe( Effect.flatMap(decodeScreenFeed), - Effect.flatMap((feed) => - feed.whep_url - ? Effect.succeed({ ...feed, whep_url: feed.whep_url }) - : credential === null - ? Effect.fail( - unavailable( - "Revyl does not stream a Mac's screen to Sign in with Revyl yet. Sign out of Revyl in Settings to use the API key.", - ), - ) - : Effect.succeed(null), - ), + Effect.map((feed) => (feed.whep_url ? { ...feed, whep_url: feed.whep_url } : null)), ), "publish its screen", ); diff --git a/apps/server/src/device/RevylOAuth.test.ts b/apps/server/src/device/RevylOAuth.test.ts index c27b8081315e8..3ae0458b760a5 100644 --- a/apps/server/src/device/RevylOAuth.test.ts +++ b/apps/server/src/device/RevylOAuth.test.ts @@ -211,7 +211,7 @@ describe("Sign in with Revyl tokens", () => { refresh_token: "refresh-new", expires_in: 3600, token_type: "Bearer", - scope: "account.read computers computers.view computers.control", + scope: "account.read computers", }, } : { status: 400, body: { error: "invalid_grant" } }, @@ -243,13 +243,11 @@ describe("Sign in with Revyl tokens", () => { const authorize = new URL(revyl.launched[0]!); expect(authorize.origin + authorize.pathname).toBe(`${ISSUER}/authorize`); - expect(revyl.launched[0]).toContain( - "scope=account.read%20computers%20computers.view%20computers.control", - ); + expect(revyl.launched[0]).toContain("scope=account.read%20computers"); expect(Object.fromEntries(authorize.searchParams)).toMatchObject({ response_type: "code", client_id: "revylapp_t3", - scope: "account.read computers computers.view computers.control", + scope: "account.read computers", code_challenge_method: "S256", }); expect(authorize.searchParams.get("redirect_uri")).toMatch( diff --git a/apps/server/src/device/RevylOAuth.ts b/apps/server/src/device/RevylOAuth.ts index d986b58331822..125bdf3a4210d 100644 --- a/apps/server/src/device/RevylOAuth.ts +++ b/apps/server/src/device/RevylOAuth.ts @@ -38,12 +38,7 @@ import * as ServerSecretStore from "../auth/ServerSecretStore.ts"; import * as ExternalLauncher from "../process/externalLauncher.ts"; /** `computers` covers persistent Mac lifecycle; `account.read` names who signed in. */ -const REVYL_OAUTH_SCOPES = [ - "account.read", - "computers", - "computers.view", - "computers.control", -] as const; +const REVYL_OAUTH_SCOPES = ["account.read", "computers"] as const; const ISSUER_PATH = "/api/v1/oauth2"; const METADATA_PATH = `/.well-known/oauth-authorization-server${ISSUER_PATH}`; const SIGN_IN_TIMEOUT = Duration.minutes(5); diff --git a/docs/user/devices.md b/docs/user/devices.md index caa0b1db529d5..0452ba7232dff 100644 --- a/docs/user/devices.md +++ b/docs/user/devices.md @@ -117,9 +117,8 @@ host, and choose **Sign in with Revyl**. The browser opens on the computer running the environment's server, so finish signing in there. While signed in, Macs use the sign-in and phones keep using the API key. When Revyl ends the sign-in, Macs stop working until you sign in again or sign out to return to -the key. T3 asks for the `account.read`, `computers`, `computers.view`, and -`computers.control` scopes. Revyl does not stream a Mac's screen to a sign-in -yet, so opening a Mac while signed in fails with that reason until it does. +the key. T3 asks for the `account.read` and `computers` scopes; when Revyl +refuses a Mac request, the panel shows Revyl's reason. ## Device tool updates From de79527755f3229a7e9584d44892d4926113f1b0 Mon Sep 17 00:00:00 2001 From: KayaanT <34585438+KayaanT@users.noreply.github.com> Date: Wed, 2 Dec 2026 07:48:26 +0000 Subject: [PATCH 4/8] feat(device): ask Revyl for one configurable Sign in with Revyl scope REVYL_OAUTH_SCOPE is the single scope the authorize request carries, omitted while unset. A Revyl that lists scopes_supported without it fails the sign-in before the browser opens. Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> --- apps/server/src/device/RevylOAuth.test.ts | 12 +++++++++--- apps/server/src/device/RevylOAuth.ts | 20 +++++++++++++++++--- docs/user/devices.md | 5 +++-- 3 files changed, 29 insertions(+), 8 deletions(-) diff --git a/apps/server/src/device/RevylOAuth.test.ts b/apps/server/src/device/RevylOAuth.test.ts index 3ae0458b760a5..92c1151d86a8a 100644 --- a/apps/server/src/device/RevylOAuth.test.ts +++ b/apps/server/src/device/RevylOAuth.test.ts @@ -171,6 +171,14 @@ describe("Sign in with Revyl PKCE", () => { }); }); +describe("Sign in with Revyl scope discovery", () => { + it("asks for a scope only a Revyl that lists it, or lists none, offers", () => { + expect(RevylOAuth.offersScope({ scopes_supported: ["workspace"] }, "workspace")).toBe(true); + expect(RevylOAuth.offersScope({ scopes_supported: ["account.read"] }, "workspace")).toBe(false); + expect(RevylOAuth.offersScope({}, "workspace")).toBe(true); + }); +}); + describe("Sign in with Revyl refusals", () => { it("says why Revyl refused a signed-in request", () => { expect( @@ -211,7 +219,6 @@ describe("Sign in with Revyl tokens", () => { refresh_token: "refresh-new", expires_in: 3600, token_type: "Bearer", - scope: "account.read computers", }, } : { status: 400, body: { error: "invalid_grant" } }, @@ -243,11 +250,10 @@ describe("Sign in with Revyl tokens", () => { const authorize = new URL(revyl.launched[0]!); expect(authorize.origin + authorize.pathname).toBe(`${ISSUER}/authorize`); - expect(revyl.launched[0]).toContain("scope=account.read%20computers"); + expect(authorize.searchParams.get("scope")).toBe(RevylOAuth.REVYL_OAUTH_SCOPE ?? null); expect(Object.fromEntries(authorize.searchParams)).toMatchObject({ response_type: "code", client_id: "revylapp_t3", - scope: "account.read computers", code_challenge_method: "S256", }); expect(authorize.searchParams.get("redirect_uri")).toMatch( diff --git a/apps/server/src/device/RevylOAuth.ts b/apps/server/src/device/RevylOAuth.ts index 125bdf3a4210d..c40b4e9528609 100644 --- a/apps/server/src/device/RevylOAuth.ts +++ b/apps/server/src/device/RevylOAuth.ts @@ -37,8 +37,11 @@ import { import * as ServerSecretStore from "../auth/ServerSecretStore.ts"; import * as ExternalLauncher from "../process/externalLauncher.ts"; -/** `computers` covers persistent Mac lifecycle; `account.read` names who signed in. */ -const REVYL_OAUTH_SCOPES = ["account.read", "computers"] as const; +/** + * The one scope Sign in with Revyl asks for: a partner connection's workspace access, acting as + * the person. Unset, the authorize request carries no `scope` and Revyl grants its default. + */ +export const REVYL_OAUTH_SCOPE: string | undefined = undefined; const ISSUER_PATH = "/api/v1/oauth2"; const METADATA_PATH = `/.well-known/oauth-authorization-server${ISSUER_PATH}`; const SIGN_IN_TIMEOUT = Duration.minutes(5); @@ -51,6 +54,7 @@ const decodeMetadata = Schema.decodeUnknownEffect( authorization_endpoint: Schema.String, token_endpoint: Schema.String, revocation_endpoint: Schema.optional(Schema.String), + scopes_supported: Schema.optional(Schema.Array(Schema.String)), }), ); type Metadata = Effect.Success>; @@ -131,6 +135,12 @@ export const readCallback = ( return code ? { _tag: "Code", code } : { _tag: "Ignored" }; }; +/** Whether a Revyl that lists its scopes offers `scope`; one that lists none is asked anyway. */ +export const offersScope = ( + metadata: { readonly scopes_supported?: ReadonlyArray | undefined }, + scope: string, +) => metadata.scopes_supported?.includes(scope) ?? true; + /** Why Revyl answered a request made with a Sign in with Revyl token 403. */ export const refusalReason = (body: string) => Option.match(decodeRefusal(body), { @@ -366,6 +376,10 @@ export const make = Effect.gen(function* () { if (!clientId) return yield* failed(`Save a Sign in with Revyl client ID for ${host.label} first.`); const metadata = yield* discover(apiOrigin); + if (REVYL_OAUTH_SCOPE !== undefined && !offersScope(metadata, REVYL_OAUTH_SCOPE)) + return yield* failed( + `${apiOrigin} does not offer the ${REVYL_OAUTH_SCOPE} scope Sign in with Revyl needs yet.`, + ); const { verifier, challenge, state } = yield* makePkce; const callback = yield* Deferred.make(); const server = Context.get( @@ -408,7 +422,7 @@ export const make = Effect.gen(function* () { response_type: "code", client_id: clientId, redirect_uri: redirectUri, - scope: REVYL_OAUTH_SCOPES.join(" "), + ...(REVYL_OAUTH_SCOPE === undefined ? {} : { scope: REVYL_OAUTH_SCOPE }), state, code_challenge: challenge, code_challenge_method: "S256", diff --git a/docs/user/devices.md b/docs/user/devices.md index 0452ba7232dff..78d43e3d5501a 100644 --- a/docs/user/devices.md +++ b/docs/user/devices.md @@ -117,8 +117,9 @@ host, and choose **Sign in with Revyl**. The browser opens on the computer running the environment's server, so finish signing in there. While signed in, Macs use the sign-in and phones keep using the API key. When Revyl ends the sign-in, Macs stop working until you sign in again or sign out to return to -the key. T3 asks for the `account.read` and `computers` scopes; when Revyl -refuses a Mac request, the panel shows Revyl's reason. +the key. T3 asks for one scope, your workspace access as yourself, and stops +before opening the browser when Revyl doesn't offer it. When Revyl refuses a +Mac request, the panel shows Revyl's reason. ## Device tool updates From e9f9e4bf828c77af7984c379ba4738faa35544d1 Mon Sep 17 00:00:00 2001 From: KayaanT <34585438+KayaanT@users.noreply.github.com> Date: Wed, 2 Dec 2026 10:05:30 +0000 Subject: [PATCH 5/8] docs(device): name workspace as Revyl's one Sign in with Revyl scope Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> --- apps/server/src/device/RevylOAuth.ts | 5 +++-- docs/user/devices.md | 6 +++--- 2 files changed, 6 insertions(+), 5 deletions(-) diff --git a/apps/server/src/device/RevylOAuth.ts b/apps/server/src/device/RevylOAuth.ts index c40b4e9528609..2916486452507 100644 --- a/apps/server/src/device/RevylOAuth.ts +++ b/apps/server/src/device/RevylOAuth.ts @@ -38,8 +38,9 @@ import * as ServerSecretStore from "../auth/ServerSecretStore.ts"; import * as ExternalLauncher from "../process/externalLauncher.ts"; /** - * The one scope Sign in with Revyl asks for: a partner connection's workspace access, acting as - * the person. Unset, the authorize request carries no `scope` and Revyl grants its default. + * The one scope Sign in with Revyl asks for. Revyl's only scope is `workspace`, a partner + * connection's access acting as the person; unset, the authorize request omits `scope` and Revyl + * grants `workspace` anyway. */ export const REVYL_OAUTH_SCOPE: string | undefined = undefined; const ISSUER_PATH = "/api/v1/oauth2"; diff --git a/docs/user/devices.md b/docs/user/devices.md index 78d43e3d5501a..97e6bfe4382ff 100644 --- a/docs/user/devices.md +++ b/docs/user/devices.md @@ -117,9 +117,9 @@ host, and choose **Sign in with Revyl**. The browser opens on the computer running the environment's server, so finish signing in there. While signed in, Macs use the sign-in and phones keep using the API key. When Revyl ends the sign-in, Macs stop working until you sign in again or sign out to return to -the key. T3 asks for one scope, your workspace access as yourself, and stops -before opening the browser when Revyl doesn't offer it. When Revyl refuses a -Mac request, the panel shows Revyl's reason. +the key. The sign-in grants Revyl's `workspace` scope, the same access as a +partner connection, acting as you. When Revyl refuses a Mac request, the panel +shows Revyl's reason. ## Device tool updates From a57dc0c7089e2734155b31144c708074183e9087 Mon Sep 17 00:00:00 2001 From: KayaanT <34585438+KayaanT@users.noreply.github.com> Date: Fri, 4 Dec 2026 20:28:49 +0000 Subject: [PATCH 6/8] fix(device): send agent and panel Mac input with the sign-in after the restack Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> --- apps/server/src/device/RevylDeviceHost.ts | 5 +++-- apps/server/src/device/RevylOAuth.test.ts | 1 + 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/apps/server/src/device/RevylDeviceHost.ts b/apps/server/src/device/RevylDeviceHost.ts index 203569b690d1f..2d6fdbbe0e9e1 100644 --- a/apps/server/src/device/RevylDeviceHost.ts +++ b/apps/server/src/device/RevylDeviceHost.ts @@ -836,6 +836,7 @@ export const make = Effect.fn("RevylDeviceHost.make")(function* ( ); const isUnavailable = Schema.is(DeviceHostUnavailableError); + const isOperationError = Schema.is(DeviceOperationError); const proxyRoute = (lease: Pick, action: string) => `/api/v1/execution/device-proxy/${encodeURIComponent(lease.runId)}/${action}`; @@ -1118,7 +1119,7 @@ export const make = Effect.fn("RevylDeviceHost.make")(function* ( Effect.timeout(AGENT_ACTION_TIMEOUT), Effect.scoped, Effect.mapError((cause) => - cause instanceof DeviceOperationError + isOperationError(cause) ? cause : new DeviceOperationError({ operation: "input", @@ -1858,7 +1859,7 @@ export const make = Effect.fn("RevylDeviceHost.make")(function* ( /** The text an action types, or null for one that types nothing. */ readonly typed: (action: A) => string | null; readonly type: (text: string) => A; - readonly send: (action: A) => ReturnType; + readonly send: (action: A) => ReturnType; readonly onInput?: (at: number) => void; }, ) { diff --git a/apps/server/src/device/RevylOAuth.test.ts b/apps/server/src/device/RevylOAuth.test.ts index 92c1151d86a8a..eeacea6520da0 100644 --- a/apps/server/src/device/RevylOAuth.test.ts +++ b/apps/server/src/device/RevylOAuth.test.ts @@ -25,6 +25,7 @@ const host: RevylDeviceHostConfig = { maxSessions: 2, maxSessionMinutes: 30, macs: true, + webApps: false, macIdleMinutes: 15, oauthClientId: "revylapp_t3", }; From 910f4ca3fd4327002ce61b6863d8c27d66f34d9e Mon Sep 17 00:00:00 2001 From: KayaanT <34585438+KayaanT@users.noreply.github.com> Date: Fri, 4 Dec 2026 20:28:57 +0000 Subject: [PATCH 7/8] docs(device): mark Sign in with Revyl as a staging-only preview Revyl registers OAuth apps on staging only, so production hosts leave the client ID empty and keep using the API key. Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> --- .../settings/RevylDeviceHostEditor.tsx | 6 ++++ apps/web/src/i18n/translations/de.json | 3 +- apps/web/src/i18n/translations/en.json | 3 +- apps/web/src/i18n/translations/es.json | 3 +- apps/web/src/i18n/translations/fr.json | 3 +- apps/web/src/i18n/translations/ja.json | 3 +- apps/web/src/i18n/translations/ko.json | 3 +- apps/web/src/i18n/translations/pl.json | 3 +- apps/web/src/i18n/translations/pt-BR.json | 3 +- apps/web/src/i18n/translations/ru.json | 3 +- apps/web/src/i18n/translations/sv.json | 3 +- apps/web/src/i18n/translations/zh.json | 3 +- docs/user/devices.md | 30 +++++++++++-------- 13 files changed, 45 insertions(+), 24 deletions(-) diff --git a/apps/web/src/components/settings/RevylDeviceHostEditor.tsx b/apps/web/src/components/settings/RevylDeviceHostEditor.tsx index ab33f68d2258b..25e31f6a1ecc2 100644 --- a/apps/web/src/components/settings/RevylDeviceHostEditor.tsx +++ b/apps/web/src/components/settings/RevylDeviceHostEditor.tsx @@ -320,6 +320,12 @@ export function RevylDeviceHostEditor(props: { key.

+

+ + Preview: Revyl registers sign-in apps on staging only. On production, leave the + client ID empty and the host uses its API key. + +

{!props.isNew && props.host.oauthClientId !== undefined && draft.oauthClientId === props.host.oauthClientId ? ( diff --git a/apps/web/src/i18n/translations/de.json b/apps/web/src/i18n/translations/de.json index 0e9ff5fffe74e..4c62216eb7f07 100644 --- a/apps/web/src/i18n/translations/de.json +++ b/apps/web/src/i18n/translations/de.json @@ -13358,5 +13358,6 @@ "06b77f3c66438d3b": "Speichere den Host mit einer Client-ID, um dich anzumelden.", "547880c4244d6119": "Schließe die Anmeldung bei Revyl im Browser auf dem Computer des Servers ab.", "e2fa8ab80b979b14": "Revyl hat diese Anmeldung beendet. Melde dich erneut an oder melde dich ab, um den API-Schlüssel zu verwenden.", - "fdad26fb3905aad6": "Angemeldet verwenden Revyl-Macs die Anmeldung statt des API-Schlüssels; Telefone verwenden weiterhin den Schlüssel." + "fdad26fb3905aad6": "Angemeldet verwenden Revyl-Macs die Anmeldung statt des API-Schlüssels; Telefone verwenden weiterhin den Schlüssel.", + "396180efa14c1fe8": "Vorschau: Revyl registriert Anmelde-Apps nur auf Staging. Lass die Client-ID in der Produktion leer, dann verwendet der Host seinen API-Schlüssel." } diff --git a/apps/web/src/i18n/translations/en.json b/apps/web/src/i18n/translations/en.json index d24f9bbbc635d..0fa95c713a4a1 100644 --- a/apps/web/src/i18n/translations/en.json +++ b/apps/web/src/i18n/translations/en.json @@ -13365,5 +13365,6 @@ "06b77f3c66438d3b": "Save the host with a client ID to sign in.", "547880c4244d6119": "Finish signing in to Revyl in the browser on the server's computer.", "e2fa8ab80b979b14": "Revyl ended this sign-in. Sign in again, or sign out to use the API key.", - "fdad26fb3905aad6": "Signed in, Revyl Macs use the sign-in instead of the API key; phones keep using the key." + "fdad26fb3905aad6": "Signed in, Revyl Macs use the sign-in instead of the API key; phones keep using the key.", + "396180efa14c1fe8": "Preview: Revyl registers sign-in apps on staging only. On production, leave the client ID empty and the host uses its API key." } diff --git a/apps/web/src/i18n/translations/es.json b/apps/web/src/i18n/translations/es.json index df0e286f2bc57..37b200d6bc8fb 100644 --- a/apps/web/src/i18n/translations/es.json +++ b/apps/web/src/i18n/translations/es.json @@ -13352,5 +13352,6 @@ "06b77f3c66438d3b": "Guarda el host con un ID de cliente para iniciar sesión.", "547880c4244d6119": "Termina de iniciar sesión en Revyl en el navegador del equipo del servidor.", "e2fa8ab80b979b14": "Revyl finalizó esta sesión. Vuelve a iniciar sesión o ciérrala para usar la clave de API.", - "fdad26fb3905aad6": "Con la sesión iniciada, los Macs de Revyl usan la sesión en lugar de la clave de API; los teléfonos siguen usando la clave." + "fdad26fb3905aad6": "Con la sesión iniciada, los Macs de Revyl usan la sesión en lugar de la clave de API; los teléfonos siguen usando la clave.", + "396180efa14c1fe8": "Vista previa: Revyl registra aplicaciones de inicio de sesión solo en staging. En producción, deja vacío el ID de cliente y el host usa su clave de API." } diff --git a/apps/web/src/i18n/translations/fr.json b/apps/web/src/i18n/translations/fr.json index 05cbb4b6c24e9..7cb196d383bf5 100644 --- a/apps/web/src/i18n/translations/fr.json +++ b/apps/web/src/i18n/translations/fr.json @@ -13357,5 +13357,6 @@ "06b77f3c66438d3b": "Enregistrez l’hôte avec un ID client pour vous connecter.", "547880c4244d6119": "Terminez la connexion à Revyl dans le navigateur de l’ordinateur du serveur.", "e2fa8ab80b979b14": "Revyl a mis fin à cette connexion. Reconnectez-vous, ou déconnectez-vous pour utiliser la clé d’API.", - "fdad26fb3905aad6": "Une fois connecté, les Mac Revyl utilisent la connexion au lieu de la clé d’API ; les téléphones continuent d’utiliser la clé." + "fdad26fb3905aad6": "Une fois connecté, les Mac Revyl utilisent la connexion au lieu de la clé d’API ; les téléphones continuent d’utiliser la clé.", + "396180efa14c1fe8": "Aperçu : Revyl n'enregistre les applications de connexion que sur staging. En production, laissez l'ID client vide et l'hôte utilise sa clé API." } diff --git a/apps/web/src/i18n/translations/ja.json b/apps/web/src/i18n/translations/ja.json index 2ae449df3a594..92b47762ecbd9 100644 --- a/apps/web/src/i18n/translations/ja.json +++ b/apps/web/src/i18n/translations/ja.json @@ -13293,5 +13293,6 @@ "06b77f3c66438d3b": "サインインするには、クライアント ID を入れてホストを保存してください。", "547880c4244d6119": "サーバーのコンピューターのブラウザで Revyl へのサインインを完了してください。", "e2fa8ab80b979b14": "Revyl がこのサインインを終了しました。もう一度サインインするか、サインアウトして API キーを使ってください。", - "fdad26fb3905aad6": "サインイン中は、Revyl Mac は API キーの代わりにサインインを使います。電話は引き続きキーを使います。" + "fdad26fb3905aad6": "サインイン中は、Revyl Mac は API キーの代わりにサインインを使います。電話は引き続きキーを使います。", + "396180efa14c1fe8": "プレビュー: Revyl はサインイン用アプリをステージングでのみ登録します。本番環境ではクライアント ID を空のままにすると、ホストは API キーを使用します。" } diff --git a/apps/web/src/i18n/translations/ko.json b/apps/web/src/i18n/translations/ko.json index 9ef6c414c7868..386cc92cdf250 100644 --- a/apps/web/src/i18n/translations/ko.json +++ b/apps/web/src/i18n/translations/ko.json @@ -13290,5 +13290,6 @@ "06b77f3c66438d3b": "로그인하려면 클라이언트 ID와 함께 호스트를 저장하세요.", "547880c4244d6119": "서버 컴퓨터의 브라우저에서 Revyl 로그인을 완료하세요.", "e2fa8ab80b979b14": "Revyl이 이 로그인을 종료했습니다. 다시 로그인하거나, 로그아웃하여 API 키를 사용하세요.", - "fdad26fb3905aad6": "로그인하면 Revyl Mac은 API 키 대신 로그인을 사용합니다. 휴대폰은 계속 키를 사용합니다." + "fdad26fb3905aad6": "로그인하면 Revyl Mac은 API 키 대신 로그인을 사용합니다. 휴대폰은 계속 키를 사용합니다.", + "396180efa14c1fe8": "미리 보기: Revyl은 로그인 앱을 스테이징에서만 등록합니다. 프로덕션에서는 클라이언트 ID를 비워 두면 호스트가 API 키를 사용합니다." } diff --git a/apps/web/src/i18n/translations/pl.json b/apps/web/src/i18n/translations/pl.json index 38d2c8c57d1bc..9d56779c3bcba 100644 --- a/apps/web/src/i18n/translations/pl.json +++ b/apps/web/src/i18n/translations/pl.json @@ -13365,5 +13365,6 @@ "06b77f3c66438d3b": "Zapisz hosta z identyfikatorem klienta, aby się zalogować.", "547880c4244d6119": "Dokończ logowanie do Revyl w przeglądarce na komputerze serwera.", "e2fa8ab80b979b14": "Revyl zakończył to logowanie. Zaloguj się ponownie lub wyloguj się, aby używać klucza API.", - "fdad26fb3905aad6": "Po zalogowaniu Maki Revyl używają logowania zamiast klucza API; telefony nadal używają klucza." + "fdad26fb3905aad6": "Po zalogowaniu Maki Revyl używają logowania zamiast klucza API; telefony nadal używają klucza.", + "396180efa14c1fe8": "Wersja zapoznawcza: Revyl rejestruje aplikacje logowania tylko na środowisku staging. W środowisku produkcyjnym zostaw identyfikator klienta pusty, a host użyje swojego klucza API." } diff --git a/apps/web/src/i18n/translations/pt-BR.json b/apps/web/src/i18n/translations/pt-BR.json index a7a1d9251a404..d50c8b22fefa5 100644 --- a/apps/web/src/i18n/translations/pt-BR.json +++ b/apps/web/src/i18n/translations/pt-BR.json @@ -13357,5 +13357,6 @@ "06b77f3c66438d3b": "Salve o host com um ID do cliente para entrar.", "547880c4244d6119": "Conclua a entrada na Revyl no navegador do computador do servidor.", "e2fa8ab80b979b14": "A Revyl encerrou esta sessão. Entre novamente ou saia para usar a chave de API.", - "fdad26fb3905aad6": "Com a sessão iniciada, os Macs da Revyl usam a sessão em vez da chave de API; os telefones continuam usando a chave." + "fdad26fb3905aad6": "Com a sessão iniciada, os Macs da Revyl usam a sessão em vez da chave de API; os telefones continuam usando a chave.", + "396180efa14c1fe8": "Prévia: o Revyl registra apps de login apenas no staging. Em produção, deixe o ID do cliente vazio e o host usa a chave de API." } diff --git a/apps/web/src/i18n/translations/ru.json b/apps/web/src/i18n/translations/ru.json index bf52d2530aade..70377dadc85fb 100644 --- a/apps/web/src/i18n/translations/ru.json +++ b/apps/web/src/i18n/translations/ru.json @@ -13356,5 +13356,6 @@ "06b77f3c66438d3b": "Сохраните хост с ID клиента, чтобы войти.", "547880c4244d6119": "Завершите вход в Revyl в браузере на компьютере сервера.", "e2fa8ab80b979b14": "Revyl завершил этот вход. Войдите снова или выйдите, чтобы использовать API-ключ.", - "fdad26fb3905aad6": "После входа Маки Revyl используют вход вместо API-ключа; телефоны продолжают использовать ключ." + "fdad26fb3905aad6": "После входа Маки Revyl используют вход вместо API-ключа; телефоны продолжают использовать ключ.", + "396180efa14c1fe8": "Предварительная версия: Revyl регистрирует приложения для входа только на staging. В продакшене оставьте идентификатор клиента пустым, и хост будет использовать свой ключ API." } diff --git a/apps/web/src/i18n/translations/sv.json b/apps/web/src/i18n/translations/sv.json index bb5bba4a2ac1a..ea27bd3b19160 100644 --- a/apps/web/src/i18n/translations/sv.json +++ b/apps/web/src/i18n/translations/sv.json @@ -13364,5 +13364,6 @@ "06b77f3c66438d3b": "Spara värden med ett klient-ID för att logga in.", "547880c4244d6119": "Slutför inloggningen till Revyl i webbläsaren på serverns dator.", "e2fa8ab80b979b14": "Revyl avslutade den här inloggningen. Logga in igen, eller logga ut för att använda API-nyckeln.", - "fdad26fb3905aad6": "När du är inloggad använder Revyl-Mac-datorer inloggningen i stället för API-nyckeln; telefoner fortsätter använda nyckeln." + "fdad26fb3905aad6": "När du är inloggad använder Revyl-Mac-datorer inloggningen i stället för API-nyckeln; telefoner fortsätter använda nyckeln.", + "396180efa14c1fe8": "Förhandsversion: Revyl registrerar inloggningsappar endast i staging. I produktion lämnar du klient-ID:t tomt så använder värden sin API-nyckel." } diff --git a/apps/web/src/i18n/translations/zh.json b/apps/web/src/i18n/translations/zh.json index 5f8ff4a9fa055..b50a54c47cd24 100644 --- a/apps/web/src/i18n/translations/zh.json +++ b/apps/web/src/i18n/translations/zh.json @@ -13373,5 +13373,6 @@ "06b77f3c66438d3b": "使用客户端 ID 保存主机后即可登录。", "547880c4244d6119": "请在服务器所在电脑的浏览器中完成 Revyl 登录。", "e2fa8ab80b979b14": "Revyl 已结束此登录。请重新登录,或退出登录以使用 API 密钥。", - "fdad26fb3905aad6": "登录后,Revyl Mac 使用登录而非 API 密钥;手机继续使用密钥。" + "fdad26fb3905aad6": "登录后,Revyl Mac 使用登录而非 API 密钥;手机继续使用密钥。", + "396180efa14c1fe8": "预览:Revyl 仅在预发布环境中注册登录应用。在生产环境中,请将客户端 ID 留空,主机将使用其 API 密钥。" } diff --git a/docs/user/devices.md b/docs/user/devices.md index 6659280a77a61..abef4635036c4 100644 --- a/docs/user/devices.md +++ b/docs/user/devices.md @@ -110,6 +110,23 @@ are sent as shortcuts. Agents open a Mac with `device_open`, look at it with described target, double and right clicks, drags, scrolls, typing, and key chords. +#### Sign in with Revyl (preview) + +Revyl registers sign-in apps on staging only for now, so this works only +with `REVYL_API_URL` set to Revyl staging. On production, leave the client ID +empty and the host uses its API key. + +Macs can use your own Revyl sign-in instead of the host's API key. Register a +public OAuth app in Revyl with the redirect URI `http://127.0.0.1/callback`, +put its client ID in the host's **Sign in with Revyl client ID**, save the +host, and choose **Sign in with Revyl**. The browser opens on the computer +running the environment's server, so finish signing in there. While signed in, +Macs use the sign-in and phones keep using the API key. When Revyl ends the +sign-in, Macs stop working until you sign in again or sign out to return to +the key. The sign-in grants Revyl's `workspace` scope, the same access as a +partner connection, acting as you. When Revyl refuses a Mac request, the panel +shows Revyl's reason. + ### Revyl web apps Turn on **Offer Revyl web apps** for a host to list your organization's Revyl @@ -125,19 +142,6 @@ with A, C or V selects all, copies or pastes inside the browser. Agents drive a web app the way they drive a Mac, with `device_input`, which can also open a URL in the browser. -#### Sign in with Revyl - -Macs can use your own Revyl sign-in instead of the host's API key. Register a -public OAuth app in Revyl with the redirect URI `http://127.0.0.1/callback`, -put its client ID in the host's **Sign in with Revyl client ID**, save the -host, and choose **Sign in with Revyl**. The browser opens on the computer -running the environment's server, so finish signing in there. While signed in, -Macs use the sign-in and phones keep using the API key. When Revyl ends the -sign-in, Macs stop working until you sign in again or sign out to return to -the key. The sign-in grants Revyl's `workspace` scope, the same access as a -partner connection, acting as you. When Revyl refuses a Mac request, the panel -shows Revyl's reason. - ## Device tool updates The T3 server manages device hub and `agent-device` versions automatically on itself and SSH hosts. Check versions in **Settings → Devices → Check versions**; update the remote T3 server to receive newer device tools. From ee78ba126e6bb5d694eda573bf2e8c1b1fea4ab2 Mon Sep 17 00:00:00 2001 From: KayaanT <34585438+KayaanT@users.noreply.github.com> Date: Fri, 4 Dec 2026 21:58:14 +0000 Subject: [PATCH 8/8] fix(device): give Mac agent input a minute again Mac requests go through macSend, which times every request out after 15 s, so agent input lost the minute Revyl can take to find a described target. macSend now takes a timeout, and agent input passes the agent action one. Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> --- .../server/src/device/RevylDeviceHost.test.ts | 42 +++++++++++++++++-- apps/server/src/device/RevylDeviceHost.ts | 4 +- 2 files changed, 41 insertions(+), 5 deletions(-) diff --git a/apps/server/src/device/RevylDeviceHost.test.ts b/apps/server/src/device/RevylDeviceHost.test.ts index f189ae644e207..153a51d7d6c32 100644 --- a/apps/server/src/device/RevylDeviceHost.test.ts +++ b/apps/server/src/device/RevylDeviceHost.test.ts @@ -91,8 +91,10 @@ const fakeRevyl = Effect.gen(function* () { staleReads: 0, pending: new Map(), }; - const http = HttpClient.make((request) => - Effect.sync(() => { + /** Seconds Revyl takes to answer a Mac screen action, as when it is finding a described target. */ + const slow = { macActionSeconds: 0 }; + const http = HttpClient.make((request) => { + const answer = Effect.sync(() => { const url = new URL(request.url); requests.push({ method: request.method, @@ -250,8 +252,11 @@ const fakeRevyl = Effect.gen(function* () { return json({ success: true }); } return json({}, 404); - }), - ); + }); + return slow.macActionSeconds > 0 && request.url.endsWith("/screen/actions") + ? Effect.delay(answer, `${slow.macActionSeconds} seconds`) + : answer; + }); const runner = ProcessRunner.ProcessRunner.of({ run: (input) => Effect.gen(function* () { @@ -283,6 +288,7 @@ const fakeRevyl = Effect.gen(function* () { computers, web, restarts, + slow, endSession, }; }); @@ -1152,6 +1158,34 @@ describe("Revyl Macs", () => { }); describe("Revyl Mac agent input", () => { + it.effect("waits past the request timeout while Revyl finds an agent's described target", () => + Effect.gen(function* () { + const revyl = yield* fakeRevyl; + const scope = yield* Scope.make(); + const host = yield* makeHost(revyl, config({ macs: true }), scope); + const ready = yield* host.ensureReady(() => Effect.void); + const catalog = (yield* ready.devices.list).devices.find( + (device) => device.id === "revyl:macos", + )!; + const deviceId = yield* ready.devices.boot(catalog); + const mac = { ...catalog, id: deviceId, booted: true }; + revyl.slow.macActionSeconds = 20; + + const clicking = yield* ready.devices.act!(mac, { + action: "click", + target: "the Save button", + }).pipe(Effect.forkChild); + yield* TestClock.adjust("20 seconds"); + yield* Fiber.join(clicking); + + expect(yield* Queue.take(revyl.macActions)).toEqual({ + action: { action: "click", target: "the Save button" }, + screenshot: false, + }); + yield* Scope.close(scope, Exit.void); + }).pipe(Effect.scoped, Effect.provide(layer)), + ); + it.effect( "clicks a described target, double-clicks, scrolls, and presses chords for an agent", () => diff --git a/apps/server/src/device/RevylDeviceHost.ts b/apps/server/src/device/RevylDeviceHost.ts index 29bd0ea515bb7..47fd85678c5bd 100644 --- a/apps/server/src/device/RevylDeviceHost.ts +++ b/apps/server/src/device/RevylDeviceHost.ts @@ -809,11 +809,12 @@ export const make = Effect.fn("RevylDeviceHost.make")(function* ( const macSend = Effect.fn("RevylDeviceHost.macSend")(function* ( credential: string | null, request: HttpClientRequest.HttpClientRequest, + timeout: Duration.Input = REQUEST_TIMEOUT, ) { const send = (bearer: string) => http .execute(request.pipe(HttpClientRequest.bearerToken(bearer))) - .pipe(Effect.timeout(REQUEST_TIMEOUT)); + .pipe(Effect.timeout(timeout)); if (credential !== null) return yield* send(credential); const token = yield* signedInToken(); let response = yield* send(token); @@ -1653,6 +1654,7 @@ export const make = Effect.fn("RevylDeviceHost.make")(function* ( action: request.body, screenshot: false, }), + AGENT_ACTION_TIMEOUT, ), ); }