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 3b9357672fa53..ac489d10dd7b0 100644 --- a/apps/server/src/device/DeviceService.ts +++ b/apps/server/src/device/DeviceService.ts @@ -25,6 +25,9 @@ import { type DeviceSimlockIdentity, DeviceSimlockIdentityError, type DeviceSimlockIdentityInput, + type DeviceRevylAccount, + DeviceRevylAuthError, + type DeviceRevylAccountInput, type DeviceHostConfig, type EasDeviceHostConfig, type RevylDeviceHostConfig, @@ -83,6 +86,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"; @@ -192,6 +196,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. @@ -1214,6 +1228,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, @@ -1247,6 +1266,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); @@ -1563,6 +1585,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"); @@ -1643,10 +1666,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; @@ -1811,10 +1835,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 041ecd69b8be1..153a51d7d6c32 100644 --- a/apps/server/src/device/RevylDeviceHost.test.ts +++ b/apps/server/src/device/RevylDeviceHost.test.ts @@ -4,10 +4,12 @@ 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 Fiber from "effect/Fiber"; 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"; @@ -16,11 +18,14 @@ 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 type * as DeviceHost from "./DeviceHost.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"; @@ -58,6 +63,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; }> = []; @@ -85,12 +91,15 @@ 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, 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) : "", }); @@ -107,7 +116,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, + }); + // 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 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)) @@ -211,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* () { @@ -244,6 +288,7 @@ const fakeRevyl = Effect.gen(function* () { computers, web, restarts, + slow, endSession, }; }); @@ -260,15 +305,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), @@ -800,6 +880,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; @@ -1020,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 9937dcc8e48bf..47fd85678c5bd 100644 --- a/apps/server/src/device/RevylDeviceHost.ts +++ b/apps/server/src/device/RevylDeviceHost.ts @@ -46,6 +46,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"; @@ -244,7 +245,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; @@ -692,9 +694,19 @@ const decodeSegment = (segment: string) => { }; 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; @@ -719,12 +731,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, @@ -758,19 +765,80 @@ 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, + timeout: Duration.Input = REQUEST_TIMEOUT, + ) { + const send = (bearer: string) => + http + .execute(request.pipe(HttpClientRequest.bearerToken(bearer))) + .pipe(Effect.timeout(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 isOperationError = Schema.is(DeviceOperationError); + const proxyRoute = (lease: Pick, action: string) => `/api/v1/execution/device-proxy/${encodeURIComponent(lease.runId)}/${action}`; @@ -804,28 +872,31 @@ 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, + credential: string | null, computerId: string, ) { - yield* revylJson(apiKey, "POST", "/api/v1/computer-runs", { + yield* macJson(credential, "POST", "/api/v1/computer-runs", { computer_session_id: computerId, os: "macos", persistent: true, @@ -840,33 +911,34 @@ 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, onStartSent: Effect.Effect, ) { - 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++) { yield* onStartSent; - 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; @@ -882,17 +954,17 @@ 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(MAC_START_TIMEOUT); // A restarted Mac reports running while it still names its last run, whose session has ended, // so each poll reads the computer again and takes only a live session's stream. const readFeed = Effect.gen(function* () { - const computer = yield* readComputer(apiKey, computerId); + const computer = yield* readComputer(credential, computerId); if (computer?.state !== "running" || !computer.run_session_id) return null; - const feed = yield* revylJson( - apiKey, + const feed = yield* macJson( + credential, "GET", `/api/v1/execution/device-sessions/${encodeURIComponent(computer.run_session_id)}?include_computers=true`, ).pipe(Effect.flatMap(decodeScreenFeed)); @@ -901,27 +973,35 @@ export const make = Effect.fn("RevylDeviceHost.make")(function* ( }); const feed = yield* Effect.gen(function* () { while ((yield* Clock.currentTimeMillis) < deadline) { - const feed = yield* readFeed.pipe(Effect.orElseSucceed(() => null)); + const feed = yield* readFeed.pipe( + Effect.catchIf( + (error) => !isUnavailable(error), + () => Effect.succeed(null), + ), + ); if (feed !== null) return feed; yield* Effect.sleep(MAC_POLL); } return yield* unavailable("The Revyl Mac did not start in time."); }); - 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, @@ -932,8 +1012,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) => @@ -946,15 +1030,27 @@ 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 creating = device.id === MAC_CATALOG_ID; const computerId = creating @@ -969,11 +1065,11 @@ export const make = Effect.fn("RevylDeviceHost.make")(function* ( return yield* Effect.gen(function* () { if (creating) { yield* markStarted; - yield* createMac(apiKey, computerId); + yield* createMac(credential, computerId); } else { - startedHere = yield* startMac(apiKey, computerId, markStarted); + startedHere = yield* startMac(credential, computerId, markStarted); } - const mac = yield* attachMac(apiKey, computerId); + const mac = yield* attachMac(credential, computerId); if (stops !== stopsAtOpen) return yield* unavailable("Device support stopped while the Mac was opening."); macs.set(computerId, mac); @@ -998,7 +1094,7 @@ export const make = Effect.fn("RevylDeviceHost.make")(function* ( if (exit._tag === "Success" || !startedHere) return Effect.void; macs.delete(computerId); macsStartedHere.delete(computerId); - return stopMac(apiKey, computerId); + return stopMac(credential, computerId); }), ), ); @@ -1011,7 +1107,7 @@ 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"))), ); @@ -1024,42 +1120,41 @@ export const make = Effect.fn("RevylDeviceHost.make")(function* ( ); /** An agent's input, failing with what Revyl said when it refuses one. */ - const agentAct = (apiKey: string, route: string, body: unknown) => - http - .execute( - HttpClientRequest.post(`${apiOrigin}${route}`).pipe( - HttpClientRequest.bodyJsonUnsafe(body), - HttpClientRequest.bearerToken(apiKey), - ), - ) - .pipe( - Effect.flatMap((response) => - response.status >= 200 && response.status < 300 - ? Effect.void - : response.text.pipe( - Effect.orElseSucceed(() => ""), - Effect.flatMap((text) => - Effect.fail( - new DeviceOperationError({ - operation: "input", - reason: "command_failed", - cause: `Revyl answered ${response.status}${text ? `: ${truncate(text, 300)}` : ""}`, - }), - ), + const agentAct = ( + sent: Effect.Effect, + ) => + sent.pipe( + Effect.flatMap((response) => + response.status >= 200 && response.status < 300 + ? Effect.void + : response.text.pipe( + Effect.orElseSucceed(() => ""), + Effect.flatMap((text) => + Effect.fail( + new DeviceOperationError({ + operation: "input", + reason: "command_failed", + cause: `Revyl answered ${response.status}${text ? `: ${truncate(text, 300)}` : ""}`, + }), ), ), - ), - Effect.timeout(AGENT_ACTION_TIMEOUT), - Effect.scoped, - Effect.mapError((cause) => - cause._tag === "DeviceOperationError" - ? cause - : new DeviceOperationError({ operation: "input", reason: "request_failed", cause }), - ), - ); + ), + ), + Effect.timeout(AGENT_ACTION_TIMEOUT), + Effect.scoped, + Effect.mapError((cause) => + isOperationError(cause) + ? cause + : new DeviceOperationError({ + operation: "input", + reason: isUnavailable(cause) ? "command_failed" : "request_failed", + cause: isUnavailable(cause) ? cause.reason : cause, + }), + ), + ); 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, }); @@ -1429,7 +1524,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 }; const webApps = config.webApps ? yield* listWebApps : []; const incompletePlatforms = [ ...(listedMacs === null ? ["macos" as const] : []), @@ -1473,7 +1570,7 @@ export const make = Effect.fn("RevylDeviceHost.make")(function* ( }; }), ], - detail: undefined, + detail, ...(incompletePlatforms.length > 0 ? { incompletePlatforms } : {}), }; }), @@ -1514,8 +1611,8 @@ export const make = Effect.fn("RevylDeviceHost.make")(function* ( return yield* releaseMac(mac); } if (device.platform === "macos") - return yield* currentApiKey.pipe( - Effect.flatMap((apiKey) => stopMac(apiKey, device.id)), + return yield* macCredential.pipe( + Effect.flatMap((credential) => stopMac(credential, device.id)), Effect.ignore, ); const lease = leases.get(device.id); @@ -1550,12 +1647,24 @@ export const make = Effect.fn("RevylDeviceHost.make")(function* ( }); if (mac) { yield* touchMac(mac); - return yield* agentAct(mac.apiKey, computerRoute(mac.computerId, "/screen/actions"), { - action: request.body, - screenshot: false, - }); + return yield* agentAct( + macSend( + mac.credential, + apiRequest("POST", computerRoute(mac.computerId, "/screen/actions"), { + action: request.body, + screenshot: false, + }), + AGENT_ACTION_TIMEOUT, + ), + ); } - return yield* agentAct(web!.apiKey, proxyRoute(web!, request.action), request.body); + return yield* agentAct( + http.execute( + apiRequest("POST", proxyRoute(web!, request.action), request.body).pipe( + HttpClientRequest.bearerToken(web!.apiKey), + ), + ), + ); }), agentEndpoint: (deviceId) => macs.has(deviceId) || webs.has(deviceId) @@ -1775,7 +1884,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; }, ) { @@ -1896,27 +2005,28 @@ 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) : web ? proxyScreenshot(web) : 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) - : web - ? webInput(web, request) - : input(lease!, request) - : Effect.succeed(notFound); + const answer = Effect.gen(function* () { + if (hubPath === SCREENSHOT_PATH) + return HttpServerResponse.uint8Array( + mac + ? yield* macScreenshot(mac) + : web + ? yield* proxyScreenshot(web) + : 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) + : web + ? yield* webInput(web, request) + : yield* input(lease!, request); + }); return yield* answer.pipe( Effect.catchCause((cause) => Effect.logWarning("Revyl device request failed", { hubPath, cause }).pipe( @@ -1991,7 +2101,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" diff --git a/apps/server/src/device/RevylOAuth.test.ts b/apps/server/src/device/RevylOAuth.test.ts new file mode 100644 index 0000000000000..eeacea6520da0 --- /dev/null +++ b/apps/server/src/device/RevylOAuth.test.ts @@ -0,0 +1,385 @@ +// @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, + webApps: false, + 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 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( + 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", + }, + } + : { 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(authorize.searchParams.get("scope")).toBe(RevylOAuth.REVYL_OAUTH_SCOPE ?? null); + expect(Object.fromEntries(authorize.searchParams)).toMatchObject({ + response_type: "code", + client_id: "revylapp_t3", + 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..2916486452507 --- /dev/null +++ b/apps/server/src/device/RevylOAuth.ts @@ -0,0 +1,499 @@ +/** + * 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"; + +/** + * 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"; +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), + scopes_supported: Schema.optional(Schema.Array(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" }; +}; + +/** 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), { + 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); + 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( + 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, + ...(REVYL_OAUTH_SCOPE === undefined ? {} : { scope: REVYL_OAUTH_SCOPE }), + 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 08f0e9952f51e..25e31f6a1ecc2 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,47 @@ export function RevylDeviceHostEditor(props: { ) : null} + +

+ + Signed in, Revyl Macs use the sign-in instead of the API key; phones keep using the + 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 ? ( + + ) : ( +

+ 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 448c7484ffd7d..4c62216eb7f07 100644 --- a/apps/web/src/i18n/translations/de.json +++ b/apps/web/src/i18n/translations/de.json @@ -13349,5 +13349,15 @@ "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.", + "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 ffe0132258c09..0fa95c713a4a1 100644 --- a/apps/web/src/i18n/translations/en.json +++ b/apps/web/src/i18n/translations/en.json @@ -13356,5 +13356,15 @@ "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.", + "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 81673f0c2753b..37b200d6bc8fb 100644 --- a/apps/web/src/i18n/translations/es.json +++ b/apps/web/src/i18n/translations/es.json @@ -13343,5 +13343,15 @@ "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.", + "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 42e8bca81cfe1..7cb196d383bf5 100644 --- a/apps/web/src/i18n/translations/fr.json +++ b/apps/web/src/i18n/translations/fr.json @@ -13348,5 +13348,15 @@ "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é.", + "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 53429bffffd79..92b47762ecbd9 100644 --- a/apps/web/src/i18n/translations/ja.json +++ b/apps/web/src/i18n/translations/ja.json @@ -13284,5 +13284,15 @@ "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 キーの代わりにサインインを使います。電話は引き続きキーを使います。", + "396180efa14c1fe8": "プレビュー: Revyl はサインイン用アプリをステージングでのみ登録します。本番環境ではクライアント ID を空のままにすると、ホストは API キーを使用します。" } diff --git a/apps/web/src/i18n/translations/ko.json b/apps/web/src/i18n/translations/ko.json index 38fc809f3a7ce..386cc92cdf250 100644 --- a/apps/web/src/i18n/translations/ko.json +++ b/apps/web/src/i18n/translations/ko.json @@ -13281,5 +13281,15 @@ "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 키 대신 로그인을 사용합니다. 휴대폰은 계속 키를 사용합니다.", + "396180efa14c1fe8": "미리 보기: Revyl은 로그인 앱을 스테이징에서만 등록합니다. 프로덕션에서는 클라이언트 ID를 비워 두면 호스트가 API 키를 사용합니다." } diff --git a/apps/web/src/i18n/translations/pl.json b/apps/web/src/i18n/translations/pl.json index 6f2be7bd2b84f..9d56779c3bcba 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.", @@ -13348,5 +13356,15 @@ "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.", + "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 11932ee4c3701..d50c8b22fefa5 100644 --- a/apps/web/src/i18n/translations/pt-BR.json +++ b/apps/web/src/i18n/translations/pt-BR.json @@ -13348,5 +13348,15 @@ "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.", + "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 27d64c524eaf2..70377dadc85fb 100644 --- a/apps/web/src/i18n/translations/ru.json +++ b/apps/web/src/i18n/translations/ru.json @@ -13347,5 +13347,15 @@ "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-ключа; телефоны продолжают использовать ключ.", + "396180efa14c1fe8": "Предварительная версия: Revyl регистрирует приложения для входа только на staging. В продакшене оставьте идентификатор клиента пустым, и хост будет использовать свой ключ API." } diff --git a/apps/web/src/i18n/translations/sv.json b/apps/web/src/i18n/translations/sv.json index 3e427a775964b..ea27bd3b19160 100644 --- a/apps/web/src/i18n/translations/sv.json +++ b/apps/web/src/i18n/translations/sv.json @@ -13355,5 +13355,15 @@ "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.", + "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 48fff31a29b40..b50a54c47cd24 100644 --- a/apps/web/src/i18n/translations/zh.json +++ b/apps/web/src/i18n/translations/zh.json @@ -13364,5 +13364,15 @@ "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 密钥;手机继续使用密钥。", + "396180efa14c1fe8": "预览:Revyl 仅在预发布环境中注册登录应用。在生产环境中,请将客户端 ID 留空,主机将使用其 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 2ea5c244c2205..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 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 269cf1870a280..44538f631225b 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))), /** Lists the organization's Revyl web apps, each opening in a cloud browser. */ webApps: Schema.Boolean.pipe(Schema.withDecodingDefaultKey(Effect.succeed(false))), }); @@ -210,6 +215,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,