diff --git a/.gitignore b/.gitignore index 5e941c7b9f..ef6067824f 100644 --- a/.gitignore +++ b/.gitignore @@ -5,6 +5,7 @@ node_modules *.log *.tsbuildinfo apps/*/dist +infra/*/dist .astro packages/*/dist .env @@ -26,3 +27,8 @@ squashfs-root/ .gstack/ dist-electron/ .electron-runtime/ +node_modules/ +.alchemy/ +*.log +.env* +!.env.example diff --git a/AGENTS.md b/AGENTS.md index 7a8075e29b..380a920268 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -29,22 +29,8 @@ Long term maintainability is a core priority. If you add new functionality, firs - `apps/server`: Node.js WebSocket server. Wraps Codex app-server (JSON-RPC over stdio), serves the React web app, and manages provider sessions. - `apps/web`: React/Vite UI. Owns session UX, conversation/event rendering, and client-side state. Connects to the server via WebSocket. - `packages/contracts`: Shared effect/Schema schemas and TypeScript contracts for provider events, WebSocket protocol, and model/session types. Keep this package schema-only — no runtime logic. -- `packages/shared`: Shared runtime utilities consumed by both server and web. Uses explicit subpath exports (e.g. `@t3tools/shared/git`) — no barrel index. - -## Codex App Server (Important) - -T3 Code is currently Codex-first. The server starts `codex app-server` (JSON-RPC over stdio) per provider session, then streams structured events to the browser through WebSocket push messages. - -How we use it in this codebase: - -- Session startup/resume and turn lifecycle are brokered in `apps/server/src/codexAppServerManager.ts`. -- Provider dispatch and thread event logging are coordinated in `apps/server/src/providerManager.ts`. -- WebSocket server routes NativeApi methods in `apps/server/src/wsServer.ts`. -- Web app consumes orchestration domain events via WebSocket push on channel `orchestration.domainEvent` (provider runtime activity is projected into orchestration events server-side). - -Docs: - -- Codex App Server docs: https://developers.openai.com/codex/sdk/#app-server +- `packages/shared`: Shared runtime utilities consumed by both server and client applications. Uses explicit subpath exports (e.g. `@t3tools/shared/git`) — no barrel index. +- `packages/client-runtime`: Shared runtime package for sharing client code across web and mobile. ## Reference Repos diff --git a/README.md b/README.md index e9b6da70ea..4398753c06 100644 --- a/README.md +++ b/README.md @@ -48,6 +48,10 @@ We are not accepting contributions yet. Observability guide: [docs/observability.md](./docs/observability.md) +Relay observability: [docs/relay-observability.md](./docs/relay-observability.md) + +T3 Cloud Clerk setup: [docs/t3-cloud-clerk.md](./docs/t3-cloud-clerk.md) + ## If you REALLY want to contribute still.... read this first Before local development, prepare the environment and install dependencies: diff --git a/apps/desktop/scripts/dev-electron.mjs b/apps/desktop/scripts/dev-electron.mjs index 9a7e68dfbb..2a2e52449b 100644 --- a/apps/desktop/scripts/dev-electron.mjs +++ b/apps/desktop/scripts/dev-electron.mjs @@ -2,7 +2,7 @@ import { spawn, spawnSync } from "node:child_process"; import { watch } from "node:fs"; import { join } from "node:path"; -import { desktopDir, resolveElectronPath } from "./electron-launcher.mjs"; +import { desktopDir, resolveDevProtocolClient, resolveElectronPath } from "./electron-launcher.mjs"; import { waitForResources } from "./wait-for-resources.mjs"; const devServerUrl = process.env.VITE_DEV_SERVER_URL?.trim(); @@ -28,6 +28,7 @@ const watchedDirectories = [ const forcedShutdownTimeoutMs = 1_500; const restartDebounceMs = 120; const childTreeGracePeriodMs = 1_200; +const remoteDebuggingPort = process.env.T3CODE_DESKTOP_REMOTE_DEBUGGING_PORT?.trim(); await waitForResources({ baseDir: desktopDir, @@ -38,6 +39,11 @@ await waitForResources({ const childEnv = { ...process.env }; delete childEnv.ELECTRON_RUN_AS_NODE; +const devProtocolClient = resolveDevProtocolClient(); +if (devProtocolClient) { + childEnv.T3CODE_DESKTOP_APP_USER_MODEL_ID = devProtocolClient.appBundleId; + childEnv.T3CODE_DESKTOP_PROTOCOL_REGISTRATION_MANAGED = "1"; +} let shuttingDown = false; let restartTimer = null; @@ -67,15 +73,17 @@ function startApp() { return; } - const app = spawn( - resolveElectronPath(), - [`--t3code-dev-root=${desktopDir}`, "dist-electron/main.cjs"], - { - cwd: desktopDir, - env: childEnv, - stdio: "inherit", - }, - ); + const electronArgs = remoteDebuggingPort + ? [`--remote-debugging-port=${remoteDebuggingPort}`] + : []; + const launchArgs = devProtocolClient + ? electronArgs + : [...electronArgs, `--t3code-dev-root=${desktopDir}`, "dist-electron/main.cjs"]; + const app = spawn(resolveElectronPath(), launchArgs, { + cwd: desktopDir, + env: childEnv, + stdio: "inherit", + }); currentApp = app; @@ -125,6 +133,7 @@ async function stopApp() { app.once("exit", finish); app.kill("SIGTERM"); killChildTreeByPid(app.pid, "TERM"); + cleanupStaleDevApps(); setTimeout(() => { if (settled) { @@ -133,6 +142,7 @@ async function stopApp() { app.kill("SIGKILL"); killChildTreeByPid(app.pid, "KILL"); + cleanupStaleDevApps(); finish(); }, forcedShutdownTimeoutMs).unref(); }); diff --git a/apps/desktop/scripts/electron-launcher.mjs b/apps/desktop/scripts/electron-launcher.mjs index 113dd82f58..8f20001bbb 100644 --- a/apps/desktop/scripts/electron-launcher.mjs +++ b/apps/desktop/scripts/electron-launcher.mjs @@ -3,6 +3,7 @@ import { spawnSync } from "node:child_process"; import { copyFileSync, + chmodSync, cpSync, existsSync, mkdirSync, @@ -13,21 +14,34 @@ import { writeFileSync, } from "node:fs"; import { createRequire } from "node:module"; -import { dirname, join, resolve } from "node:path"; +import { basename, dirname, join, resolve } from "node:path"; import { fileURLToPath } from "node:url"; import { ensureElectronRuntime } from "./ensure-electron-runtime.mjs"; const isDevelopment = Boolean(process.env.VITE_DEV_SERVER_URL); -const APP_DISPLAY_NAME = isDevelopment ? "T3 Code (Dev)" : "T3 Code (Alpha)"; -const APP_BUNDLE_ID = isDevelopment ? "com.t3tools.t3code.dev" : "com.t3tools.t3code"; -const LAUNCHER_VERSION = 2; - const __dirname = dirname(fileURLToPath(import.meta.url)); export const desktopDir = resolve(__dirname, ".."); const repoRoot = resolve(desktopDir, "..", ".."); +const devBundleIdSuffix = basename(repoRoot) + .toLowerCase() + .replaceAll(/[^a-z0-9]+/g, ""); +export const APP_DISPLAY_NAME = isDevelopment ? "T3 Code (Dev)" : "T3 Code (Alpha)"; +export const APP_BUNDLE_ID = isDevelopment + ? `com.t3tools.t3code.dev.${devBundleIdSuffix || "local"}` + : "com.t3tools.t3code"; +const APP_PROTOCOL_SCHEMES = isDevelopment ? ["t3code-dev"] : ["t3code"]; +const LAUNCHER_VERSION = 10; const defaultIconPath = join(desktopDir, "resources", "icon.icns"); const developmentMacIconPngPath = join(repoRoot, "assets", "dev", "blueprint-macos-1024.png"); +function resolveDevelopmentProtocolCallbackPort() { + const configuredPort = Number.parseInt(process.env.T3CODE_PORT ?? "", 10); + if (Number.isInteger(configuredPort) && configuredPort > 0 && configuredPort < 65535) { + return configuredPort + 1; + } + return 13774; +} + function setPlistString(plistPath, key, value) { const replaceResult = spawnSync("plutil", ["-replace", key, "-string", value, plistPath], { encoding: "utf8", @@ -47,6 +61,26 @@ function setPlistString(plistPath, key, value) { throw new Error(`Failed to update plist key "${key}" at ${plistPath}: ${details}`.trim()); } +function setPlistJson(plistPath, key, value) { + const serialized = JSON.stringify(value); + const replaceResult = spawnSync("plutil", ["-replace", key, "-json", serialized, plistPath], { + encoding: "utf8", + }); + if (replaceResult.status === 0) { + return; + } + + const insertResult = spawnSync("plutil", ["-insert", key, "-json", serialized, plistPath], { + encoding: "utf8", + }); + if (insertResult.status === 0) { + return; + } + + const details = [replaceResult.stderr, insertResult.stderr].filter(Boolean).join("\n"); + throw new Error(`Failed to update plist key "${key}" at ${plistPath}: ${details}`.trim()); +} + function runChecked(command, args) { const result = spawnSync(command, args, { encoding: "utf8" }); if (result.status === 0) { @@ -57,6 +91,71 @@ function runChecked(command, args) { throw new Error(`Failed to run ${command} ${args.join(" ")}: ${details}`.trim()); } +function shellSingleQuote(value) { + return `'${value.replaceAll("'", "'\\''")}'`; +} + +function writeDevelopmentLauncherScript(targetBinaryPath, electronBinaryPath) { + const mainEntryPath = join(desktopDir, "dist-electron", "main.cjs"); + const protocolCallbackUrl = `http://127.0.0.1:${resolveDevelopmentProtocolCallbackPort()}/auth/callback`; + const envEntries = [ + ["VITE_DEV_SERVER_URL", process.env.VITE_DEV_SERVER_URL], + ["T3CODE_PORT", process.env.T3CODE_PORT], + ["T3CODE_HOME", process.env.T3CODE_HOME], + ["T3CODE_COMMIT_HASH", process.env.T3CODE_COMMIT_HASH], + ["T3CODE_OTLP_TRACES_URL", process.env.T3CODE_OTLP_TRACES_URL], + ["T3CODE_OTLP_EXPORT_INTERVAL_MS", process.env.T3CODE_OTLP_EXPORT_INTERVAL_MS], + ["T3CODE_DESKTOP_APP_USER_MODEL_ID", APP_BUNDLE_ID], + ["T3CODE_DESKTOP_PROTOCOL_REGISTRATION_MANAGED", "1"], + ["T3CODE_DESKTOP_PROTOCOL_CALLBACK_URL", protocolCallbackUrl], + ].filter((entry) => typeof entry[1] === "string" && entry[1].trim().length > 0); + writeFileSync( + targetBinaryPath, + [ + "#!/bin/sh", + ...envEntries.map(([name, value]) => `export ${name}=${shellSingleQuote(value)}`), + 'for arg in "$@"; do', + ' case "$arg" in', + " t3code-dev://auth/callback*)", + ' if [ -n "$T3CODE_DESKTOP_PROTOCOL_CALLBACK_URL" ]; then', + ' /usr/bin/curl -fsS --max-time 2 -X POST --data-binary "$arg" "$T3CODE_DESKTOP_PROTOCOL_CALLBACK_URL" >/dev/null 2>&1 && exit 0', + " fi", + " ;;", + " esac", + "done", + `exec ${shellSingleQuote(electronBinaryPath)} --t3code-dev-root=${shellSingleQuote(desktopDir)} ${shellSingleQuote(mainEntryPath)} "$@"`, + "", + ].join("\n"), + ); + chmodSync(targetBinaryPath, 0o755); +} + +function registerMacLauncherBundle(appBundlePath) { + runChecked( + "/System/Library/Frameworks/CoreServices.framework/Frameworks/LaunchServices.framework/Support/lsregister", + ["-f", appBundlePath], + ); + + if (!isDevelopment) { + return; + } + + for (const scheme of APP_PROTOCOL_SCHEMES) { + runChecked("osascript", [ + "-l", + "JavaScript", + "-e", + [ + 'ObjC.import("CoreServices");', + `const scheme = $.NSString.alloc.initWithUTF8String(${JSON.stringify(scheme)});`, + `const bundle = $.NSString.alloc.initWithUTF8String(${JSON.stringify(APP_BUNDLE_ID)});`, + "const status = $.LSSetDefaultHandlerForURLScheme(scheme, bundle);", + "if (status !== 0) throw new Error(`LSSetDefaultHandlerForURLScheme failed: ${status}`);", + ].join(" "), + ]); + } +} + function ensureDevelopmentIconIcns(runtimeDir) { const generatedIconPath = join(runtimeDir, "icon-dev.icns"); mkdirSync(runtimeDir, { recursive: true }); @@ -115,12 +214,49 @@ function patchMainBundleInfoPlist(appBundlePath, iconPath) { setPlistString(infoPlistPath, "CFBundleName", APP_DISPLAY_NAME); setPlistString(infoPlistPath, "CFBundleIdentifier", APP_BUNDLE_ID); setPlistString(infoPlistPath, "CFBundleIconFile", "icon.icns"); + setPlistJson(infoPlistPath, "CFBundleURLTypes", [ + { + CFBundleURLName: APP_BUNDLE_ID, + CFBundleURLSchemes: APP_PROTOCOL_SCHEMES, + }, + ]); const resourcesDir = join(appBundlePath, "Contents", "Resources"); copyFileSync(iconPath, join(resourcesDir, "icon.icns")); copyFileSync(iconPath, join(resourcesDir, "electron.icns")); } +function patchHelperBundleInfoPlists(appBundlePath) { + const helperBundleNames = [ + ["Electron Helper.app", "helper", `${APP_DISPLAY_NAME} Helper`], + ["Electron Helper (GPU).app", "helper.gpu", `${APP_DISPLAY_NAME} Helper (GPU)`], + ["Electron Helper (Plugin).app", "helper.plugin", `${APP_DISPLAY_NAME} Helper (Plugin)`], + ["Electron Helper (Renderer).app", "helper.renderer", `${APP_DISPLAY_NAME} Helper (Renderer)`], + ]; + + for (const [bundleName, bundleIdentifierSuffix, bundleDisplayName] of helperBundleNames) { + const infoPlistPath = join( + appBundlePath, + "Contents", + "Frameworks", + bundleName, + "Contents", + "Info.plist", + ); + if (!existsSync(infoPlistPath)) { + continue; + } + + setPlistString(infoPlistPath, "CFBundleDisplayName", bundleDisplayName); + setPlistString(infoPlistPath, "CFBundleName", bundleDisplayName); + setPlistString( + infoPlistPath, + "CFBundleIdentifier", + `${APP_BUNDLE_ID}.${bundleIdentifierSuffix}`, + ); + } +} + function readJson(path) { try { return JSON.parse(readFileSync(path, "utf8")); @@ -144,6 +280,8 @@ function buildMacLauncher(electronBinaryPath) { sourceAppBundlePath, sourceAppMtimeMs: statSync(sourceAppBundlePath).mtimeMs, iconMtimeMs: statSync(iconPath).mtimeMs, + appBundleId: APP_BUNDLE_ID, + appProtocolSchemes: APP_PROTOCOL_SCHEMES, }; const currentMetadata = readJson(metadataPath); @@ -152,13 +290,19 @@ function buildMacLauncher(electronBinaryPath) { currentMetadata && JSON.stringify(currentMetadata) === JSON.stringify(expectedMetadata) ) { + registerMacLauncherBundle(targetAppBundlePath); return targetBinaryPath; } rmSync(targetAppBundlePath, { recursive: true, force: true }); cpSync(sourceAppBundlePath, targetAppBundlePath, { recursive: true }); patchMainBundleInfoPlist(targetAppBundlePath, iconPath); + patchHelperBundleInfoPlists(targetAppBundlePath); + if (isDevelopment) { + writeDevelopmentLauncherScript(targetBinaryPath, electronBinaryPath); + } writeFileSync(metadataPath, `${JSON.stringify(expectedMetadata, null, 2)}\n`); + registerMacLauncherBundle(targetAppBundlePath); return targetBinaryPath; } @@ -173,11 +317,19 @@ export function resolveElectronPath() { return electronBinaryPath; } - // Dev launches do not need a renamed app bundle badly enough to risk breaking - // Electron helper resource lookup on macOS. - if (isDevelopment) { - return electronBinaryPath; - } - return buildMacLauncher(electronBinaryPath); } + +export function resolveDevProtocolClient() { + if (process.platform !== "darwin" || !isDevelopment) { + return null; + } + + const require = createRequire(import.meta.url); + const electronBinaryPath = require("electron"); + const launcherBinaryPath = buildMacLauncher(electronBinaryPath); + return { + appBundlePath: resolve(launcherBinaryPath, "..", "..", ".."), + appBundleId: APP_BUNDLE_ID, + }; +} diff --git a/apps/desktop/src/app/DesktopApp.ts b/apps/desktop/src/app/DesktopApp.ts index 85b8aed4a4..052a25e4b9 100644 --- a/apps/desktop/src/app/DesktopApp.ts +++ b/apps/desktop/src/app/DesktopApp.ts @@ -1,16 +1,17 @@ import * as Cause from "effect/Cause"; -import * as Crypto from "effect/Crypto"; import * as Data from "effect/Data"; import * as Effect from "effect/Effect"; import * as Option from "effect/Option"; import * as Ref from "effect/Ref"; import * as NetService from "@t3tools/shared/Net"; +import * as Crypto from "effect/Crypto"; import * as ElectronApp from "../electron/ElectronApp.ts"; import * as ElectronDialog from "../electron/ElectronDialog.ts"; import * as ElectronProtocol from "../electron/ElectronProtocol.ts"; import { installDesktopIpcHandlers } from "../ipc/DesktopIpcHandlers.ts"; import * as DesktopAppIdentity from "./DesktopAppIdentity.ts"; +import * as DesktopCloudAuth from "./DesktopCloudAuth.ts"; import * as DesktopApplicationMenu from "../window/DesktopApplicationMenu.ts"; import * as DesktopBackendManager from "../backend/DesktopBackendManager.ts"; import * as DesktopEnvironment from "./DesktopEnvironment.ts"; @@ -190,6 +191,7 @@ const startup = Effect.gen(function* () { const electronApp = yield* ElectronApp.ElectronApp; const electronProtocol = yield* ElectronProtocol.ElectronProtocol; const lifecycle = yield* DesktopLifecycle.DesktopLifecycle; + const cloudAuth = yield* DesktopCloudAuth.DesktopCloudAuth; const shellEnvironment = yield* DesktopShellEnvironment.DesktopShellEnvironment; const desktopSettings = yield* DesktopAppSettings.DesktopAppSettings; const updates = yield* DesktopUpdates.DesktopUpdates; @@ -207,6 +209,7 @@ const startup = Effect.gen(function* () { yield* appIdentity.configure; yield* lifecycle.register; + yield* cloudAuth.configure; yield* electronApp.whenReady.pipe( Effect.withSpan("desktop.electron.whenReady"), diff --git a/apps/desktop/src/app/DesktopAppIdentity.test.ts b/apps/desktop/src/app/DesktopAppIdentity.test.ts index f95fd1bef7..eafdbf056d 100644 --- a/apps/desktop/src/app/DesktopAppIdentity.test.ts +++ b/apps/desktop/src/app/DesktopAppIdentity.test.ts @@ -53,6 +53,9 @@ const makeElectronAppLayer = (calls: ElectronAppCalls) => calls.setAboutPanelOptions.push(options); }), setAppUserModelId: () => Effect.void, + requestSingleInstanceLock: Effect.succeed(true), + isDefaultProtocolClient: () => Effect.succeed(false), + setAsDefaultProtocolClient: () => Effect.succeed(true), setDesktopName: () => Effect.void, setDockIcon: (iconPath) => Effect.sync(() => { diff --git a/apps/desktop/src/app/DesktopCloudAuth.test.ts b/apps/desktop/src/app/DesktopCloudAuth.test.ts new file mode 100644 index 0000000000..002fd86b0a --- /dev/null +++ b/apps/desktop/src/app/DesktopCloudAuth.test.ts @@ -0,0 +1,302 @@ +import { assert, describe, it } from "@effect/vitest"; +import * as NodeServices from "@effect/platform-node/NodeServices"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import * as Option from "effect/Option"; + +import * as ElectronApp from "../electron/ElectronApp.ts"; +import * as ElectronWindow from "../electron/ElectronWindow.ts"; +import * as IpcChannels from "../ipc/channels.ts"; +import * as DesktopCloudAuth from "./DesktopCloudAuth.ts"; +import * as DesktopEnvironment from "./DesktopEnvironment.ts"; + +interface CloudAuthHarness { + readonly app: ElectronApp.ElectronAppShape; + readonly window: ElectronWindow.ElectronWindowShape; + readonly listeners: Map void)[]>; + readonly protocolRegistrations: { + readonly protocol: string; + readonly path?: string; + readonly args?: readonly string[]; + }[]; + readonly sends: { readonly channel: string; readonly args: readonly unknown[] }[]; + readonly reveals: unknown[]; + readonly layer: Layer.Layer< + | DesktopCloudAuth.DesktopCloudAuth + | DesktopEnvironment.DesktopEnvironment + | ElectronApp.ElectronApp + | ElectronWindow.ElectronWindow + >; +} + +function makeHarness(input: { readonly isDevelopment: boolean }): CloudAuthHarness { + const listeners = new Map void)[]>(); + const protocolRegistrations: CloudAuthHarness["protocolRegistrations"] = []; + const sends: CloudAuthHarness["sends"] = []; + const reveals: unknown[] = []; + const mainWindow = { id: "main-window" }; + + const app = ElectronApp.ElectronApp.of({ + metadata: Effect.succeed({ + appVersion: "0.0.0-test", + appPath: "/tmp/t3-code-test", + isPackaged: !input.isDevelopment, + resourcesPath: "/tmp/t3-code-test/resources", + runningUnderArm64Translation: false, + }), + name: Effect.succeed("T3 Code"), + whenReady: Effect.void, + quit: Effect.void, + exit: () => Effect.void, + relaunch: () => Effect.void, + setPath: () => Effect.void, + setName: () => Effect.void, + setAboutPanelOptions: () => Effect.void, + setAppUserModelId: () => Effect.void, + requestSingleInstanceLock: Effect.succeed(true), + isDefaultProtocolClient: () => Effect.succeed(false), + setAsDefaultProtocolClient: (protocol, path, args) => + Effect.sync(() => { + protocolRegistrations.push({ + protocol, + ...(path === undefined ? {} : { path }), + ...(args === undefined ? {} : { args }), + }); + return true; + }), + setDesktopName: () => Effect.void, + setDockIcon: () => Effect.void, + appendCommandLineSwitch: () => Effect.void, + on: (eventName, listener) => + Effect.sync(() => { + const erasedListener = listener as (...args: readonly unknown[]) => void; + listeners.set(eventName, [...(listeners.get(eventName) ?? []), erasedListener]); + }), + }); + + const window = ElectronWindow.ElectronWindow.of({ + create: () => Effect.die("not used"), + main: Effect.succeed(Option.some(mainWindow as never)), + currentMainOrFirst: Effect.succeed(Option.some(mainWindow as never)), + focusedMainOrFirst: Effect.succeed(Option.some(mainWindow as never)), + setMain: () => Effect.void, + clearMain: () => Effect.void, + reveal: (target) => + Effect.sync(() => { + reveals.push(target); + }), + sendAll: (channel, ...args) => + Effect.sync(() => { + sends.push({ channel, args }); + }), + destroyAll: Effect.void, + syncAllAppearance: () => Effect.void, + }); + + const environment = DesktopEnvironment.DesktopEnvironment.of({ + isDevelopment: input.isDevelopment, + } as DesktopEnvironment.DesktopEnvironmentShape); + const environmentLayer = Layer.succeed(DesktopEnvironment.DesktopEnvironment, environment); + + return { + app, + window, + listeners, + protocolRegistrations, + sends, + reveals, + layer: Layer.mergeAll( + DesktopCloudAuth.layer.pipe( + Layer.provideMerge(environmentLayer), + Layer.provide(NodeServices.layer), + ), + Layer.succeed(ElectronApp.ElectronApp, app), + Layer.succeed(ElectronWindow.ElectronWindow, window), + ), + }; +} + +function emitAppEvent( + harness: CloudAuthHarness, + eventName: string, + ...args: readonly unknown[] +): void { + for (const listener of harness.listeners.get(eventName) ?? []) { + listener(...args); + } +} + +const flushCloudAuthDispatch = Effect.promise(() => Promise.resolve()); + +describe("DesktopCloudAuth", () => { + it("uses separate callback schemes for packaged and development builds", () => { + assert.equal( + DesktopCloudAuth.resolveCloudAuthCallbackScheme({ isDevelopment: false }), + "t3code", + ); + assert.equal( + DesktopCloudAuth.resolveCloudAuthCallbackScheme({ isDevelopment: true }), + "t3code-dev", + ); + }); + + it("builds a native callback URL with request state", () => { + assert.equal( + DesktopCloudAuth.buildCloudAuthCallbackUrl({ + scheme: "t3code", + state: "state-1", + }), + "t3code://auth/callback?t3_state=state-1", + ); + }); + + it("accepts only the expected scheme, host, path, and state", () => { + assert.isNotNull( + DesktopCloudAuth.parseCloudAuthCallbackUrl({ + rawUrl: "t3code://auth/callback?rotating_token_nonce=nonce&t3_state=state-1", + scheme: "t3code", + state: "state-1", + }), + ); + assert.isNull( + DesktopCloudAuth.parseCloudAuthCallbackUrl({ + rawUrl: "t3code://auth/callback?rotating_token_nonce=nonce&t3_state=wrong", + scheme: "t3code", + state: "state-1", + }), + ); + assert.isNull( + DesktopCloudAuth.parseCloudAuthCallbackUrl({ + rawUrl: "https://example.com/callback?rotating_token_nonce=nonce&t3_state=state-1", + scheme: "t3code", + state: "state-1", + }), + ); + }); + + it("builds a native development callback URL with request state", () => { + assert.equal( + DesktopCloudAuth.buildCloudAuthCallbackUrl({ + scheme: "t3code-dev", + state: "state-1", + }), + "t3code-dev://auth/callback?t3_state=state-1", + ); + }); + + it.effect("registers the development protocol client and dispatches matching callbacks", () => { + const harness = makeHarness({ isDevelopment: true }); + + return Effect.gen(function* () { + const cloudAuth = yield* DesktopCloudAuth.DesktopCloudAuth; + yield* cloudAuth.configure; + const redirectUrl = yield* cloudAuth.createRequest; + const callbackUrl = new URL(redirectUrl); + callbackUrl.searchParams.set("rotating_token_nonce", "nonce-1"); + + let prevented = false; + emitAppEvent( + harness, + "open-url", + { preventDefault: () => (prevented = true) }, + callbackUrl.toString(), + ); + yield* flushCloudAuthDispatch; + + assert.isTrue(prevented); + assert.deepEqual( + harness.protocolRegistrations.map((registration) => registration.protocol), + ["t3code-dev"], + ); + assert.isString(harness.protocolRegistrations[0]?.path); + assert.isArray(harness.protocolRegistrations[0]?.args); + assert.deepEqual(harness.sends, [ + { + channel: IpcChannels.CLOUD_AUTH_CALLBACK_CHANNEL, + args: [callbackUrl.toString()], + }, + ]); + assert.lengthOf(harness.reveals, 1); + }).pipe(Effect.provide(harness.layer), Effect.scoped); + }); + + it.effect("rejects mismatched callback state and only consumes the pending request once", () => { + const harness = makeHarness({ isDevelopment: false }); + + return Effect.gen(function* () { + const cloudAuth = yield* DesktopCloudAuth.DesktopCloudAuth; + yield* cloudAuth.configure; + const redirectUrl = yield* cloudAuth.createRequest; + const validCallback = new URL(redirectUrl); + validCallback.searchParams.set("rotating_token_nonce", "nonce-1"); + const invalidCallback = new URL(validCallback); + invalidCallback.searchParams.set(DesktopCloudAuth.CLOUD_AUTH_CALLBACK_STATE_PARAM, "wrong"); + + emitAppEvent( + harness, + "open-url", + { preventDefault: () => undefined }, + invalidCallback.toString(), + ); + yield* flushCloudAuthDispatch; + assert.deepEqual(harness.sends, []); + + emitAppEvent( + harness, + "open-url", + { preventDefault: () => undefined }, + validCallback.toString(), + ); + yield* flushCloudAuthDispatch; + emitAppEvent( + harness, + "open-url", + { preventDefault: () => undefined }, + validCallback.toString(), + ); + yield* flushCloudAuthDispatch; + + assert.deepEqual( + harness.protocolRegistrations.map((registration) => registration.protocol), + ["t3code"], + ); + assert.deepEqual(harness.sends, [ + { + channel: IpcChannels.CLOUD_AUTH_CALLBACK_CHANNEL, + args: [validCallback.toString()], + }, + ]); + }).pipe(Effect.provide(harness.layer), Effect.scoped); + }); + + it.effect( + "routes second-instance callbacks and reveals the window for non-callback launches", + () => { + const harness = makeHarness({ isDevelopment: true }); + + return Effect.gen(function* () { + const cloudAuth = yield* DesktopCloudAuth.DesktopCloudAuth; + yield* cloudAuth.configure; + const redirectUrl = yield* cloudAuth.createRequest; + const callbackUrl = new URL(redirectUrl); + callbackUrl.searchParams.set("rotating_token_nonce", "nonce-1"); + + emitAppEvent(harness, "second-instance", {}, ["electron", callbackUrl.toString()]); + yield* flushCloudAuthDispatch; + + const revealCountAfterCallback = harness.reveals.length; + emitAppEvent(harness, "second-instance", {}, ["electron", "--opened-from-dock"]); + yield* flushCloudAuthDispatch; + + assert.deepEqual(harness.sends, [ + { + channel: IpcChannels.CLOUD_AUTH_CALLBACK_CHANNEL, + args: [callbackUrl.toString()], + }, + ]); + assert.equal(revealCountAfterCallback, 1); + assert.equal(harness.reveals.length, 2); + }).pipe(Effect.provide(harness.layer), Effect.scoped); + }, + ); +}); diff --git a/apps/desktop/src/app/DesktopCloudAuth.ts b/apps/desktop/src/app/DesktopCloudAuth.ts new file mode 100644 index 0000000000..732de27b9a --- /dev/null +++ b/apps/desktop/src/app/DesktopCloudAuth.ts @@ -0,0 +1,330 @@ +import * as Context from "effect/Context"; +import * as Crypto from "effect/Crypto"; +import * as Data from "effect/Data"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import * as Option from "effect/Option"; +import * as Scope from "effect/Scope"; +import { HttpRouter, HttpServerRequest, HttpServerResponse } from "effect/unstable/http"; + +import * as NodeHttpServer from "@effect/platform-node/NodeHttpServer"; +import * as ElectronApp from "../electron/ElectronApp.ts"; +import * as ElectronWindow from "../electron/ElectronWindow.ts"; +import * as IpcChannels from "../ipc/channels.ts"; +import * as DesktopEnvironment from "./DesktopEnvironment.ts"; +import type * as Electron from "electron"; + +export const CLOUD_AUTH_CALLBACK_HOST = "auth"; +export const CLOUD_AUTH_CALLBACK_PATHNAME = "/callback"; +export const CLOUD_AUTH_CALLBACK_STATE_PARAM = "t3_state"; +export const CLOUD_AUTH_CALLBACK_SCHEME = "t3code"; +export const DEVELOPMENT_CLOUD_AUTH_CALLBACK_SCHEME = "t3code-dev"; + +const CLOUD_AUTH_REQUEST_TIMEOUT_MS = 5 * 60 * 1000; + +export class DesktopCloudAuthCallbackServerError extends Data.TaggedError( + "DesktopCloudAuthCallbackServerError", +)<{ + readonly cause: unknown; +}> { + override get message() { + return "Failed to start the desktop cloud auth callback server."; + } +} + +interface PendingCloudAuthRequest { + readonly state: string; + readonly redirectUrl: string; + readonly close: () => void; +} + +export interface DesktopCloudAuthShape { + readonly createRequest: Effect.Effect; + readonly configure: Effect.Effect< + void, + never, + ElectronApp.ElectronApp | ElectronWindow.ElectronWindow | Scope.Scope + >; +} + +export class DesktopCloudAuth extends Context.Service()( + "@t3tools/desktop/app/DesktopCloudAuth", +) {} + +export function resolveCloudAuthCallbackScheme(input: { readonly isDevelopment: boolean }): string { + return input.isDevelopment ? DEVELOPMENT_CLOUD_AUTH_CALLBACK_SCHEME : CLOUD_AUTH_CALLBACK_SCHEME; +} + +export function buildCloudAuthCallbackUrl(input: { + readonly scheme: string; + readonly state: string; +}): string { + const url = new URL( + `${input.scheme}://${CLOUD_AUTH_CALLBACK_HOST}${CLOUD_AUTH_CALLBACK_PATHNAME}`, + ); + url.searchParams.set(CLOUD_AUTH_CALLBACK_STATE_PARAM, input.state); + return url.toString(); +} + +export function parseCloudAuthCallbackUrl(input: { + readonly rawUrl: unknown; + readonly scheme: string; + readonly state: string; +}): URL | null { + if (typeof input.rawUrl !== "string") { + return null; + } + + try { + const url = new URL(input.rawUrl); + if (url.protocol !== `${input.scheme}:`) return null; + if (url.hostname !== CLOUD_AUTH_CALLBACK_HOST) return null; + if (url.pathname !== CLOUD_AUTH_CALLBACK_PATHNAME) return null; + if (url.searchParams.get(CLOUD_AUTH_CALLBACK_STATE_PARAM) !== input.state) return null; + return url; + } catch { + return null; + } +} + +export function findCloudAuthCallbackUrl(input: { + readonly values: readonly unknown[]; + readonly scheme: string; + readonly state: string; +}): URL | null { + for (const value of input.values) { + const url = parseCloudAuthCallbackUrl({ + rawUrl: value, + scheme: input.scheme, + state: input.state, + }); + if (url) return url; + } + return null; +} + +export function resolveProtocolClientLaunchArgs(input: { + readonly argv: readonly string[]; +}): readonly string[] { + return input.argv.slice(1); +} + +function resolveConfiguredProtocolClient(): { + readonly path: string; + readonly args: readonly string[]; +} | null { + const path = process.env.T3CODE_DESKTOP_PROTOCOL_CLIENT_PATH?.trim(); + if (!path) return null; + + return { + path, + args: (process.env.T3CODE_DESKTOP_PROTOCOL_CLIENT_ARGS ?? "") + .split("\n") + .map((arg) => arg.trim()) + .filter((arg) => arg.length > 0), + }; +} + +function isProtocolRegistrationManagedExternally(): boolean { + return process.env.T3CODE_DESKTOP_PROTOCOL_REGISTRATION_MANAGED?.trim() === "1"; +} + +function resolveProtocolCallbackForwardUrl(): URL | null { + const rawUrl = process.env.T3CODE_DESKTOP_PROTOCOL_CALLBACK_URL?.trim(); + if (!rawUrl) return null; + + try { + const url = new URL(rawUrl); + if (url.protocol !== "http:") return null; + if (url.hostname !== "127.0.0.1") return null; + if (url.pathname !== "/auth/callback") return null; + if (!url.port) return null; + return url; + } catch { + return null; + } +} + +const closeCloudAuthRequest = (request: PendingCloudAuthRequest | null): null => { + request?.close(); + return null; +}; + +function createCloudAuthRequestTimeout(onExpire: () => void): ReturnType { + // @effect-diagnostics-next-line globalTimers:off - Auth request expiry is tied to an Electron callback server, not fiber scheduling. + return setTimeout(onExpire, CLOUD_AUTH_REQUEST_TIMEOUT_MS); +} + +function ignoreCloudAuthCallback(_rawUrl: string) {} + +function startProtocolCallbackForwardServer( + callbackUrl: URL, + dispatch: (rawUrl: string) => void, +): Effect.Effect { + const port = Number.parseInt(callbackUrl.port, 10); + const routesLayer = HttpRouter.add( + "POST", + "/auth/callback", + Effect.gen(function* () { + const request = yield* HttpServerRequest.HttpServerRequest; + const rawUrl = yield* request.text; + yield* Effect.sync(() => { + dispatch(rawUrl); + }); + return HttpServerResponse.empty({ status: 204 }); + }), + ); + + return Effect.gen(function* () { + const NodeHttp = yield* Effect.promise(() => import("node:http")); + const serverLayer = NodeHttpServer.layer(NodeHttp.createServer, { + host: callbackUrl.hostname, + port, + }); + yield* Layer.launch(HttpRouter.serve(routesLayer).pipe(Layer.provideMerge(serverLayer))).pipe( + Effect.forkScoped, + ); + }); +} + +const make = Effect.gen(function* () { + const crypto = yield* Crypto.Crypto; + const environment = yield* DesktopEnvironment.DesktopEnvironment; + let pendingAuthRequest: PendingCloudAuthRequest | null = null; + let dispatchCloudAuthCallback: (rawUrl: string) => void = ignoreCloudAuthCallback; + const makeCloudAuthRequestState = Effect.gen(function* () { + const [left, right] = yield* Effect.all([crypto.randomUUIDv4, crypto.randomUUIDv4]); + return `${left}${right}`.replaceAll("-", ""); + }); + + return DesktopCloudAuth.of({ + createRequest: Effect.gen(function* () { + const scheme = resolveCloudAuthCallbackScheme({ + isDevelopment: environment.isDevelopment, + }); + const state = yield* makeCloudAuthRequestState.pipe( + Effect.mapError((cause) => new DesktopCloudAuthCallbackServerError({ cause })), + ); + + pendingAuthRequest = closeCloudAuthRequest(pendingAuthRequest); + + const redirectUrl = buildCloudAuthCallbackUrl({ scheme, state }); + const timeout = createCloudAuthRequestTimeout(() => { + pendingAuthRequest = closeCloudAuthRequest(pendingAuthRequest); + }); + pendingAuthRequest = { + state, + redirectUrl, + close: () => clearTimeout(timeout), + }; + return redirectUrl; + }), + configure: Effect.gen(function* () { + const electronApp = yield* ElectronApp.ElectronApp; + const electronWindow = yield* ElectronWindow.ElectronWindow; + const scope = yield* Scope.Scope; + const context = yield* Effect.context(); + const runPromise = Effect.runPromiseWith(context); + const scheme = resolveCloudAuthCallbackScheme({ + isDevelopment: environment.isDevelopment, + }); + + yield* Scope.addFinalizer( + scope, + Effect.sync(() => { + pendingAuthRequest = closeCloudAuthRequest(pendingAuthRequest); + }), + ); + + if (isProtocolRegistrationManagedExternally()) { + // Development macOS launchers set the default URL handler before the stock Electron + // process starts so LaunchServices binds the scheme to the worktree-specific app bundle. + } else if (environment.isDevelopment) { + const configuredClient = resolveConfiguredProtocolClient(); + if (configuredClient) { + yield* electronApp.setAsDefaultProtocolClient( + scheme, + configuredClient.path, + configuredClient.args, + ); + } else { + yield* electronApp.setAsDefaultProtocolClient( + scheme, + process.execPath, + resolveProtocolClientLaunchArgs({ argv: process.argv }), + ); + } + } else { + yield* electronApp.setAsDefaultProtocolClient(scheme); + } + + dispatchCloudAuthCallback = (rawUrl: string) => { + const pending = pendingAuthRequest; + const callbackUrl = pending + ? parseCloudAuthCallbackUrl({ rawUrl, scheme, state: pending.state }) + : null; + if (!callbackUrl) { + return; + } + + pendingAuthRequest = closeCloudAuthRequest(pendingAuthRequest); + void runPromise( + Effect.gen(function* () { + yield* electronWindow.sendAll( + IpcChannels.CLOUD_AUTH_CALLBACK_CHANNEL, + callbackUrl.toString(), + ); + const mainWindow = yield* electronWindow.currentMainOrFirst; + if (Option.isSome(mainWindow)) { + yield* electronWindow.reveal(mainWindow.value); + } + }), + ); + }; + + const protocolCallbackForwardUrl = resolveProtocolCallbackForwardUrl(); + if (environment.isDevelopment && protocolCallbackForwardUrl) { + yield* startProtocolCallbackForwardServer( + protocolCallbackForwardUrl, + dispatchCloudAuthCallback, + ); + } + + const hasInstanceLock = yield* electronApp.requestSingleInstanceLock; + if (!hasInstanceLock) { + return yield* electronApp.quit; + } + + yield* electronApp.on<[Electron.Event, string]>("open-url", (event, rawUrl) => { + event.preventDefault?.(); + dispatchCloudAuthCallback(rawUrl); + }); + + yield* electronApp.on<[Electron.Event, readonly string[]]>( + "second-instance", + (_event, argv) => { + const values = resolveProtocolClientLaunchArgs({ argv }); + const pending = pendingAuthRequest; + const callbackUrl = pending + ? findCloudAuthCallbackUrl({ values, scheme, state: pending.state }) + : null; + if (callbackUrl) { + dispatchCloudAuthCallback(callbackUrl.toString()); + return; + } + + void runPromise( + Effect.gen(function* () { + const mainWindow = yield* electronWindow.currentMainOrFirst; + if (Option.isSome(mainWindow)) { + yield* electronWindow.reveal(mainWindow.value); + } + }), + ); + }, + ); + }).pipe(Effect.withSpan("desktop.cloudAuth.configure")), + }); +}); + +export const layer = Layer.effect(DesktopCloudAuth, make); diff --git a/apps/desktop/src/app/DesktopCloudAuthTokenStore.test.ts b/apps/desktop/src/app/DesktopCloudAuthTokenStore.test.ts new file mode 100644 index 0000000000..3257edca88 --- /dev/null +++ b/apps/desktop/src/app/DesktopCloudAuthTokenStore.test.ts @@ -0,0 +1,96 @@ +import * as NodeServices from "@effect/platform-node/NodeServices"; +import { assert, describe, it } from "@effect/vitest"; +import * as Effect from "effect/Effect"; +import * as FileSystem from "effect/FileSystem"; +import * as Layer from "effect/Layer"; +import * as Option from "effect/Option"; + +import * as ElectronSafeStorage from "../electron/ElectronSafeStorage.ts"; +import * as DesktopConfig from "./DesktopConfig.ts"; +import * as DesktopEnvironment from "./DesktopEnvironment.ts"; +import * as DesktopCloudAuthTokenStore from "./DesktopCloudAuthTokenStore.ts"; + +const textDecoder = new TextDecoder(); +const textEncoder = new TextEncoder(); + +function makeSafeStorageLayer(input: { readonly available: boolean }) { + return Layer.succeed(ElectronSafeStorage.ElectronSafeStorage, { + isEncryptionAvailable: Effect.succeed(input.available), + encryptString: (value) => Effect.succeed(textEncoder.encode(`enc:${value}`)), + decryptString: (value) => { + const decoded = textDecoder.decode(value); + if (!decoded.startsWith("enc:")) { + return Effect.fail( + new ElectronSafeStorage.ElectronSafeStorageDecryptError({ + cause: new Error("invalid encrypted token"), + }), + ); + } + return Effect.succeed(decoded.slice("enc:".length)); + }, + } satisfies ElectronSafeStorage.ElectronSafeStorageShape); +} + +function makeLayer(baseDir: string, input?: { readonly encryptionAvailable?: boolean }) { + const environmentLayer = DesktopEnvironment.layer({ + dirname: "/repo/apps/desktop/src", + homeDirectory: baseDir, + platform: "darwin", + processArch: "x64", + appVersion: "1.2.3", + appPath: "/repo", + isPackaged: true, + resourcesPath: "/missing/resources", + runningUnderArm64Translation: false, + }).pipe( + Layer.provide( + Layer.mergeAll(NodeServices.layer, DesktopConfig.layerTest({ T3CODE_HOME: baseDir })), + ), + ); + + return DesktopCloudAuthTokenStore.layer.pipe( + Layer.provideMerge(environmentLayer), + Layer.provideMerge(makeSafeStorageLayer({ available: input?.encryptionAvailable ?? true })), + Layer.provideMerge(NodeServices.layer), + ); +} + +const withTokenStore = ( + effect: Effect.Effect, + input?: { readonly encryptionAvailable?: boolean }, +) => + Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const baseDir = yield* fileSystem.makeTempDirectoryScoped({ + prefix: "t3-desktop-cloud-auth-token-test-", + }); + return yield* effect.pipe(Effect.provide(makeLayer(baseDir, input))); + }).pipe(Effect.provide(NodeServices.layer), Effect.scoped); + +describe("DesktopCloudAuthTokenStore", () => { + it.effect("persists, reads, and clears the encrypted Clerk client JWT", () => + withTokenStore( + Effect.gen(function* () { + const tokenStore = yield* DesktopCloudAuthTokenStore.DesktopCloudAuthTokenStore; + + assert.isTrue(yield* tokenStore.set("__client=test.jwt")); + assert.deepStrictEqual(yield* tokenStore.get, Option.some("__client=test.jwt")); + + yield* tokenStore.clear; + assert.deepStrictEqual(yield* tokenStore.get, Option.none()); + }), + ), + ); + + it.effect("does not persist a token when Electron safe storage is unavailable", () => + withTokenStore( + Effect.gen(function* () { + const tokenStore = yield* DesktopCloudAuthTokenStore.DesktopCloudAuthTokenStore; + + assert.isFalse(yield* tokenStore.set("__client=test.jwt")); + assert.deepStrictEqual(yield* tokenStore.get, Option.none()); + }), + { encryptionAvailable: false }, + ), + ); +}); diff --git a/apps/desktop/src/app/DesktopCloudAuthTokenStore.ts b/apps/desktop/src/app/DesktopCloudAuthTokenStore.ts new file mode 100644 index 0000000000..652072c1f5 --- /dev/null +++ b/apps/desktop/src/app/DesktopCloudAuthTokenStore.ts @@ -0,0 +1,155 @@ +import { fromLenientJson } from "@t3tools/shared/schemaJson"; +import * as Context from "effect/Context"; +import * as Crypto from "effect/Crypto"; +import * as Data from "effect/Data"; +import * as Effect from "effect/Effect"; +import * as Encoding from "effect/Encoding"; +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 PlatformError from "effect/PlatformError"; +import * as Schema from "effect/Schema"; + +import * as ElectronSafeStorage from "../electron/ElectronSafeStorage.ts"; +import * as DesktopEnvironment from "./DesktopEnvironment.ts"; + +interface CloudAuthTokenDocument { + readonly version: number; + readonly encryptedClientJwt: string; +} + +const CloudAuthTokenDocumentSchema = Schema.Struct({ + version: Schema.Number, + encryptedClientJwt: Schema.String, +}); + +const CloudAuthTokenDocumentJson = fromLenientJson(CloudAuthTokenDocumentSchema); +const decodeCloudAuthTokenDocumentJson = Schema.decodeEffect(CloudAuthTokenDocumentJson); +const encodeCloudAuthTokenDocumentJson = Schema.encodeEffect(CloudAuthTokenDocumentJson); + +export class DesktopCloudAuthTokenStoreWriteError extends Data.TaggedError( + "DesktopCloudAuthTokenStoreWriteError", +)<{ + readonly cause: PlatformError.PlatformError | Schema.SchemaError; +}> { + override get message() { + return `Failed to write desktop cloud auth token: ${this.cause.message}`; + } +} + +export class DesktopCloudAuthTokenStoreDecodeError extends Data.TaggedError( + "DesktopCloudAuthTokenStoreDecodeError", +)<{ + readonly cause: Encoding.EncodingError; +}> { + override get message() { + return "Failed to decode desktop cloud auth token."; + } +} + +export interface DesktopCloudAuthTokenStoreShape { + readonly get: Effect.Effect< + Option.Option, + | DesktopCloudAuthTokenStoreDecodeError + | ElectronSafeStorage.ElectronSafeStorageAvailabilityError + | ElectronSafeStorage.ElectronSafeStorageDecryptError + >; + readonly set: ( + token: string, + ) => Effect.Effect< + boolean, + | DesktopCloudAuthTokenStoreWriteError + | ElectronSafeStorage.ElectronSafeStorageAvailabilityError + | ElectronSafeStorage.ElectronSafeStorageEncryptError + >; + readonly clear: Effect.Effect; +} + +export class DesktopCloudAuthTokenStore extends Context.Service< + DesktopCloudAuthTokenStore, + DesktopCloudAuthTokenStoreShape +>()("@t3tools/desktop/app/DesktopCloudAuthTokenStore") {} + +function decodeSecretBytes( + encoded: string, +): Effect.Effect { + return Effect.fromResult(Encoding.decodeBase64(encoded)).pipe( + Effect.mapError((cause) => new DesktopCloudAuthTokenStoreDecodeError({ cause })), + ); +} + +const readDocument = ( + fileSystem: FileSystem.FileSystem, + tokenPath: string, +): Effect.Effect> => + fileSystem.readFileString(tokenPath).pipe( + Effect.option, + Effect.flatMap( + Option.match({ + onNone: () => Effect.succeed(Option.none()), + onSome: (raw) => decodeCloudAuthTokenDocumentJson(raw).pipe(Effect.option), + }), + ), + ); + +const writeDocument = Effect.fn("desktop.cloudAuthTokenStore.writeDocument")(function* (input: { + readonly fileSystem: FileSystem.FileSystem; + readonly path: Path.Path; + readonly tokenPath: string; + readonly document: CloudAuthTokenDocument; + readonly suffix: string; +}): Effect.fn.Return { + const directory = input.path.dirname(input.tokenPath); + const tempPath = `${input.tokenPath}.${process.pid}.${input.suffix}.tmp`; + const encoded = yield* encodeCloudAuthTokenDocumentJson(input.document); + yield* input.fileSystem.makeDirectory(directory, { recursive: true }); + yield* input.fileSystem.writeFileString(tempPath, `${encoded}\n`); + yield* input.fileSystem.rename(tempPath, input.tokenPath); +}); + +export const layer = Layer.effect( + DesktopCloudAuthTokenStore, + Effect.gen(function* () { + const environment = yield* DesktopEnvironment.DesktopEnvironment; + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const safeStorage = yield* ElectronSafeStorage.ElectronSafeStorage; + const crypto = yield* Crypto.Crypto; + const tokenPath = path.join(environment.stateDir, "cloud-auth-token.json"); + + return DesktopCloudAuthTokenStore.of({ + get: Effect.gen(function* () { + const document = yield* readDocument(fileSystem, tokenPath); + if (Option.isNone(document) || !(yield* safeStorage.isEncryptionAvailable)) { + return Option.none(); + } + + const secretBytes = yield* decodeSecretBytes(document.value.encryptedClientJwt); + return Option.some(yield* safeStorage.decryptString(secretBytes)); + }).pipe(Effect.withSpan("desktop.cloudAuthTokenStore.get")), + set: Effect.fn("desktop.cloudAuthTokenStore.set")(function* (token) { + if (!(yield* safeStorage.isEncryptionAvailable)) { + return false; + } + + const encryptedClientJwt = Encoding.encodeBase64(yield* safeStorage.encryptString(token)); + const suffix = (yield* crypto.randomUUIDv4.pipe( + Effect.mapError((cause) => new DesktopCloudAuthTokenStoreWriteError({ cause })), + )).replace(/-/g, ""); + yield* writeDocument({ + fileSystem, + path, + tokenPath, + document: { version: 1, encryptedClientJwt }, + suffix, + }).pipe(Effect.mapError((cause) => new DesktopCloudAuthTokenStoreWriteError({ cause }))); + return true; + }), + clear: fileSystem.remove(tokenPath, { force: true }).pipe( + Effect.catch(() => Effect.void), + Effect.withSpan("desktop.cloudAuthTokenStore.clear"), + ), + }); + }), +); diff --git a/apps/desktop/src/app/DesktopConfig.ts b/apps/desktop/src/app/DesktopConfig.ts index a921831401..4bf6b51330 100644 --- a/apps/desktop/src/app/DesktopConfig.ts +++ b/apps/desktop/src/app/DesktopConfig.ts @@ -37,6 +37,7 @@ export const DesktopConfig = Config.all({ xdgConfigHome: trimmedString("XDG_CONFIG_HOME"), t3Home: trimmedString("T3CODE_HOME"), devServerUrl: Config.url("VITE_DEV_SERVER_URL").pipe(Config.option), + appUserModelIdOverride: trimmedString("T3CODE_DESKTOP_APP_USER_MODEL_ID"), devRemoteT3ServerEntryPath: trimmedString("T3CODE_DEV_REMOTE_T3_SERVER_ENTRY_PATH"), configuredBackendPort: Config.port("T3CODE_PORT").pipe(Config.option), commitHashOverride: trimmedString("T3CODE_COMMIT_HASH"), diff --git a/apps/desktop/src/app/DesktopEnvironment.test.ts b/apps/desktop/src/app/DesktopEnvironment.test.ts index 11ea03f681..ee732bf830 100644 --- a/apps/desktop/src/app/DesktopEnvironment.test.ts +++ b/apps/desktop/src/app/DesktopEnvironment.test.ts @@ -93,6 +93,20 @@ describe("DesktopEnvironment", () => { }), ); + it.effect("uses a configured app user model id override", () => + Effect.gen(function* () { + const environment = yield* makeEnvironment( + {}, + { + T3CODE_DESKTOP_APP_USER_MODEL_ID: " com.t3tools.t3code.dev.local ", + VITE_DEV_SERVER_URL: "http://localhost:5173", + }, + ); + + assert.equal(environment.appUserModelId, "com.t3tools.t3code.dev.local"); + }), + ); + it.effect("resolves picker defaults without nullish sentinels", () => Effect.gen(function* () { const environment = yield* makeEnvironment(); diff --git a/apps/desktop/src/app/DesktopEnvironment.ts b/apps/desktop/src/app/DesktopEnvironment.ts index 2c5db8a16d..431e0d34d8 100644 --- a/apps/desktop/src/app/DesktopEnvironment.ts +++ b/apps/desktop/src/app/DesktopEnvironment.ts @@ -199,7 +199,9 @@ const makeDesktopEnvironment = Effect.fn("desktop.environment.make")(function* ( otlpExportIntervalMs: config.otlpExportIntervalMs, branding, displayName, - appUserModelId: isDevelopment ? "com.t3tools.t3code.dev" : "com.t3tools.t3code", + appUserModelId: Option.getOrElse(config.appUserModelIdOverride, () => + isDevelopment ? "com.t3tools.t3code.dev" : "com.t3tools.t3code", + ), linuxDesktopEntryName: isDevelopment ? "t3code-dev.desktop" : "t3code.desktop", linuxWmClass: isDevelopment ? "t3code-dev" : "t3code", userDataDirName, diff --git a/apps/desktop/src/electron/ElectronApp.test.ts b/apps/desktop/src/electron/ElectronApp.test.ts index 9eab65ade9..f6ed5cb1df 100644 --- a/apps/desktop/src/electron/ElectronApp.test.ts +++ b/apps/desktop/src/electron/ElectronApp.test.ts @@ -7,12 +7,15 @@ const { exitMock, getAppPathMock, getVersionMock, + isDefaultProtocolClientMock, onMock, quitMock, relaunchMock, removeListenerMock, + requestSingleInstanceLockMock, setAboutPanelOptionsMock, setAppUserModelIdMock, + setAsDefaultProtocolClientMock, setDesktopNameMock, setDockIconMock, setNameMock, @@ -23,12 +26,15 @@ const { exitMock: vi.fn(), getAppPathMock: vi.fn(() => "/app"), getVersionMock: vi.fn(() => "1.2.3"), + isDefaultProtocolClientMock: vi.fn(() => false), onMock: vi.fn(), quitMock: vi.fn(), relaunchMock: vi.fn(), removeListenerMock: vi.fn(), + requestSingleInstanceLockMock: vi.fn(() => true), setAboutPanelOptionsMock: vi.fn(), setAppUserModelIdMock: vi.fn(), + setAsDefaultProtocolClientMock: vi.fn(() => true), setDesktopNameMock: vi.fn(), setDockIconMock: vi.fn(), setNameMock: vi.fn(), @@ -46,14 +52,17 @@ vi.mock("electron", () => ({ }, getAppPath: getAppPathMock, getVersion: getVersionMock, + isDefaultProtocolClient: isDefaultProtocolClientMock, isPackaged: true, name: "T3 Code", on: onMock, quit: quitMock, relaunch: relaunchMock, removeListener: removeListenerMock, + requestSingleInstanceLock: requestSingleInstanceLockMock, runningUnderARM64Translation: false, setAboutPanelOptions: setAboutPanelOptionsMock, + setAsDefaultProtocolClient: setAsDefaultProtocolClientMock, setAppUserModelId: setAppUserModelIdMock, setDesktopName: setDesktopNameMock, setName: setNameMock, diff --git a/apps/desktop/src/electron/ElectronApp.ts b/apps/desktop/src/electron/ElectronApp.ts index bd7a5ec847..49b432fd5d 100644 --- a/apps/desktop/src/electron/ElectronApp.ts +++ b/apps/desktop/src/electron/ElectronApp.ts @@ -29,6 +29,13 @@ export interface ElectronAppShape { options: Electron.AboutPanelOptionsOptions, ) => Effect.Effect; readonly setAppUserModelId: (id: string) => Effect.Effect; + readonly requestSingleInstanceLock: Effect.Effect; + readonly isDefaultProtocolClient: (protocol: string) => Effect.Effect; + readonly setAsDefaultProtocolClient: ( + protocol: string, + path?: string, + args?: readonly string[], + ) => Effect.Effect; readonly setDesktopName: (desktopName: string) => Effect.Effect; readonly setDockIcon: (iconPath: string) => Effect.Effect; readonly appendCommandLineSwitch: (switchName: string, value?: string) => Effect.Effect; @@ -93,6 +100,16 @@ const make = ElectronApp.of({ Effect.sync(() => { Electron.app.setAppUserModelId(id); }), + requestSingleInstanceLock: Effect.sync(() => Electron.app.requestSingleInstanceLock()), + isDefaultProtocolClient: (protocol) => + Effect.sync(() => Electron.app.isDefaultProtocolClient(protocol)), + setAsDefaultProtocolClient: (protocol, path, args) => + Effect.sync(() => { + if (path === undefined) { + return Electron.app.setAsDefaultProtocolClient(protocol); + } + return Electron.app.setAsDefaultProtocolClient(protocol, path, [...(args ?? [])]); + }), setDesktopName: (desktopName) => Effect.sync(() => { const linuxApp = Electron.app as Electron.App & { diff --git a/apps/desktop/src/ipc/DesktopIpcHandlers.ts b/apps/desktop/src/ipc/DesktopIpcHandlers.ts index d0b08c8dac..d26aa599a6 100644 --- a/apps/desktop/src/ipc/DesktopIpcHandlers.ts +++ b/apps/desktop/src/ipc/DesktopIpcHandlers.ts @@ -1,6 +1,13 @@ import * as Effect from "effect/Effect"; import * as DesktopIpc from "./DesktopIpc.ts"; +import { + clearCloudAuthToken, + createCloudAuthRequest, + fetchCloudAuth, + getCloudAuthToken, + setCloudAuthToken, +} from "./methods/cloudAuth.ts"; import { getClientSettings, setClientSettings } from "./methods/clientSettings.ts"; import { getSavedEnvironmentRegistry, @@ -75,6 +82,11 @@ export const installDesktopIpcHandlers = Effect.gen(function* () { yield* ipc.handle(setTheme); yield* ipc.handle(showContextMenu); yield* ipc.handle(openExternal); + yield* ipc.handle(createCloudAuthRequest); + yield* ipc.handle(getCloudAuthToken); + yield* ipc.handle(setCloudAuthToken); + yield* ipc.handle(clearCloudAuthToken); + yield* ipc.handle(fetchCloudAuth); yield* ipc.handle(getUpdateState); yield* ipc.handle(setUpdateChannel); diff --git a/apps/desktop/src/ipc/channels.ts b/apps/desktop/src/ipc/channels.ts index 2715b20cb3..1ded238c66 100644 --- a/apps/desktop/src/ipc/channels.ts +++ b/apps/desktop/src/ipc/channels.ts @@ -3,6 +3,12 @@ export const CONFIRM_CHANNEL = "desktop:confirm"; export const SET_THEME_CHANNEL = "desktop:set-theme"; export const CONTEXT_MENU_CHANNEL = "desktop:context-menu"; export const OPEN_EXTERNAL_CHANNEL = "desktop:open-external"; +export const CREATE_CLOUD_AUTH_REQUEST_CHANNEL = "desktop:create-cloud-auth-request"; +export const GET_CLOUD_AUTH_TOKEN_CHANNEL = "desktop:get-cloud-auth-token"; +export const SET_CLOUD_AUTH_TOKEN_CHANNEL = "desktop:set-cloud-auth-token"; +export const CLEAR_CLOUD_AUTH_TOKEN_CHANNEL = "desktop:clear-cloud-auth-token"; +export const FETCH_CLOUD_AUTH_CHANNEL = "desktop:fetch-cloud-auth"; +export const CLOUD_AUTH_CALLBACK_CHANNEL = "desktop:cloud-auth-callback"; export const MENU_ACTION_CHANNEL = "desktop:menu-action"; export const UPDATE_STATE_CHANNEL = "desktop:update-state"; export const UPDATE_GET_STATE_CHANNEL = "desktop:update-get-state"; diff --git a/apps/desktop/src/ipc/methods/cloudAuth.ts b/apps/desktop/src/ipc/methods/cloudAuth.ts new file mode 100644 index 0000000000..2870732f7e --- /dev/null +++ b/apps/desktop/src/ipc/methods/cloudAuth.ts @@ -0,0 +1,128 @@ +import { + DesktopCloudAuthFetchInputSchema, + DesktopCloudAuthFetchResultSchema, +} from "@t3tools/contracts"; +import * as Data from "effect/Data"; +import * as Effect from "effect/Effect"; +import * as Option from "effect/Option"; +import * as Schema from "effect/Schema"; +import { HttpClient, HttpClientRequest } from "effect/unstable/http"; + +import * as DesktopCloudAuth from "../../app/DesktopCloudAuth.ts"; +import * as DesktopCloudAuthTokenStore from "../../app/DesktopCloudAuthTokenStore.ts"; +import * as IpcChannels from "../channels.ts"; +import { makeIpcMethod } from "../DesktopIpc.ts"; + +export class DesktopCloudAuthFetchError extends Data.TaggedError("DesktopCloudAuthFetchError")<{ + readonly reason: string; + readonly cause?: unknown; +}> { + override get message() { + return this.reason; + } +} + +const allowedClerkFrontendApiHosts = (hostname: string): boolean => + hostname.endsWith(".clerk.accounts.dev") || hostname.endsWith(".clerk.accounts.com"); + +function validateClerkFrontendApiUrl(rawUrl: string): URL { + const url = new URL(rawUrl); + if (url.protocol !== "https:" || !allowedClerkFrontendApiHosts(url.hostname)) { + throw new DesktopCloudAuthFetchError({ + reason: "Desktop cloud auth fetch is restricted to Clerk Frontend API HTTPS hosts.", + }); + } + return url; +} + +export const createCloudAuthRequest = makeIpcMethod({ + channel: IpcChannels.CREATE_CLOUD_AUTH_REQUEST_CHANNEL, + payload: Schema.Void, + result: Schema.String, + handler: Effect.fn("desktop.ipc.cloudAuth.createRequest")(function* () { + const cloudAuth = yield* DesktopCloudAuth.DesktopCloudAuth; + return yield* cloudAuth.createRequest; + }), +}); + +export const getCloudAuthToken = makeIpcMethod({ + channel: IpcChannels.GET_CLOUD_AUTH_TOKEN_CHANNEL, + payload: Schema.Void, + result: Schema.NullOr(Schema.String), + handler: Effect.fn("desktop.ipc.cloudAuth.getToken")(function* () { + const tokenStore = yield* DesktopCloudAuthTokenStore.DesktopCloudAuthTokenStore; + return Option.getOrNull(yield* tokenStore.get); + }), +}); + +export const setCloudAuthToken = makeIpcMethod({ + channel: IpcChannels.SET_CLOUD_AUTH_TOKEN_CHANNEL, + payload: Schema.String, + result: Schema.Boolean, + handler: Effect.fn("desktop.ipc.cloudAuth.setToken")(function* (token) { + const tokenStore = yield* DesktopCloudAuthTokenStore.DesktopCloudAuthTokenStore; + return yield* tokenStore.set(token); + }), +}); + +export const clearCloudAuthToken = makeIpcMethod({ + channel: IpcChannels.CLEAR_CLOUD_AUTH_TOKEN_CHANNEL, + payload: Schema.Void, + result: Schema.Void, + handler: Effect.fn("desktop.ipc.cloudAuth.clearToken")(function* () { + const tokenStore = yield* DesktopCloudAuthTokenStore.DesktopCloudAuthTokenStore; + yield* tokenStore.clear; + }), +}); + +export const fetchCloudAuth = makeIpcMethod({ + channel: IpcChannels.FETCH_CLOUD_AUTH_CHANNEL, + payload: DesktopCloudAuthFetchInputSchema, + result: DesktopCloudAuthFetchResultSchema, + handler: Effect.fn("desktop.ipc.cloudAuth.fetch")(function* (input) { + const url = yield* Effect.try({ + try: () => validateClerkFrontendApiUrl(input.url), + catch: (cause) => + cause instanceof DesktopCloudAuthFetchError + ? cause + : new DesktopCloudAuthFetchError({ + reason: "Desktop cloud auth fetch received an invalid URL.", + cause, + }), + }); + + const request = HttpClientRequest.make((input.method ?? "GET") as "GET" | "POST")(url, { + headers: input.headers, + }).pipe( + input.body === undefined ? (request) => request : HttpClientRequest.bodyText(input.body), + ); + + const response = yield* HttpClient.execute(request).pipe( + Effect.mapError( + (cause) => + new DesktopCloudAuthFetchError({ + reason: "Desktop cloud auth fetch failed.", + cause, + }), + ), + ); + + const body = yield* response.text.pipe( + Effect.mapError( + (cause) => + new DesktopCloudAuthFetchError({ + reason: "Desktop cloud auth fetch response could not be read.", + cause, + }), + ), + ); + + return { + ok: response.status >= 200 && response.status < 300, + status: response.status, + statusText: "", + headers: response.headers, + body, + }; + }), +}); diff --git a/apps/desktop/src/main.ts b/apps/desktop/src/main.ts index 8c458db012..9356eef441 100644 --- a/apps/desktop/src/main.ts +++ b/apps/desktop/src/main.ts @@ -26,6 +26,8 @@ import * as ElectronUpdater from "./electron/ElectronUpdater.ts"; import * as ElectronWindow from "./electron/ElectronWindow.ts"; import * as DesktopApp from "./app/DesktopApp.ts"; import * as DesktopAppIdentity from "./app/DesktopAppIdentity.ts"; +import * as DesktopCloudAuth from "./app/DesktopCloudAuth.ts"; +import * as DesktopCloudAuthTokenStore from "./app/DesktopCloudAuthTokenStore.ts"; import * as DesktopApplicationMenu from "./window/DesktopApplicationMenu.ts"; import * as DesktopAssets from "./app/DesktopAssets.ts"; import * as DesktopBackendConfiguration from "./backend/DesktopBackendConfiguration.ts"; @@ -111,6 +113,7 @@ const desktopFoundationLayer = Layer.mergeAll( DesktopAppSettings.layer, DesktopClientSettings.layer, DesktopSavedEnvironments.layer, + DesktopCloudAuthTokenStore.layer, DesktopAssets.layer, DesktopObservability.layer, ).pipe(Layer.provideMerge(desktopEnvironmentLayer)); @@ -135,6 +138,7 @@ const desktopBackendLayer = DesktopBackendManager.layer.pipe( const desktopApplicationLayer = Layer.mergeAll( DesktopLifecycle.layer, DesktopApplicationMenu.layer, + DesktopCloudAuth.layer, DesktopShellEnvironment.layer, desktopSshLayer, ).pipe(Layer.provideMerge(DesktopUpdates.layer), Layer.provideMerge(desktopBackendLayer)); diff --git a/apps/desktop/src/preload.ts b/apps/desktop/src/preload.ts index 737567990d..84f7580cb0 100644 --- a/apps/desktop/src/preload.ts +++ b/apps/desktop/src/preload.ts @@ -96,6 +96,23 @@ contextBridge.exposeInMainWorld("desktopBridge", { ...(position === undefined ? {} : { position }), }), openExternal: (url: string) => ipcRenderer.invoke(IpcChannels.OPEN_EXTERNAL_CHANNEL, url), + createCloudAuthRequest: () => ipcRenderer.invoke(IpcChannels.CREATE_CLOUD_AUTH_REQUEST_CHANNEL), + getCloudAuthToken: () => ipcRenderer.invoke(IpcChannels.GET_CLOUD_AUTH_TOKEN_CHANNEL), + setCloudAuthToken: (token: string) => + ipcRenderer.invoke(IpcChannels.SET_CLOUD_AUTH_TOKEN_CHANNEL, token), + clearCloudAuthToken: () => ipcRenderer.invoke(IpcChannels.CLEAR_CLOUD_AUTH_TOKEN_CHANNEL), + fetchCloudAuth: (input) => ipcRenderer.invoke(IpcChannels.FETCH_CLOUD_AUTH_CHANNEL, input), + onCloudAuthCallback: (listener) => { + const wrappedListener = (_event: Electron.IpcRendererEvent, rawUrl: unknown) => { + if (typeof rawUrl !== "string") return; + listener(rawUrl); + }; + + ipcRenderer.on(IpcChannels.CLOUD_AUTH_CALLBACK_CHANNEL, wrappedListener); + return () => { + ipcRenderer.removeListener(IpcChannels.CLOUD_AUTH_CALLBACK_CHANNEL, wrappedListener); + }; + }, onMenuAction: (listener) => { const wrappedListener = (_event: Electron.IpcRendererEvent, action: unknown) => { if (typeof action !== "string") return; diff --git a/apps/desktop/src/settings/DesktopSavedEnvironments.ts b/apps/desktop/src/settings/DesktopSavedEnvironments.ts index 494e5c3253..bb571a9ad3 100644 --- a/apps/desktop/src/settings/DesktopSavedEnvironments.ts +++ b/apps/desktop/src/settings/DesktopSavedEnvironments.ts @@ -53,6 +53,7 @@ const PersistedSavedEnvironmentStorageRecordSchema = Schema.Struct({ createdAt: Schema.String, lastConnectedAt: Schema.NullOr(Schema.String), desktopSsh: Schema.optionalKey(DesktopSshTargetSchema), + relayManaged: Schema.optionalKey(Schema.Struct({ relayUrl: Schema.String })), encryptedBearerToken: Schema.optionalKey(Schema.String), }); @@ -134,7 +135,11 @@ function toPersistedSavedEnvironmentRecord( createdAt: record.createdAt, lastConnectedAt: record.lastConnectedAt, }; - return record.desktopSsh ? { ...nextRecord, desktopSsh: record.desktopSsh } : nextRecord; + return { + ...nextRecord, + ...(record.desktopSsh ? { desktopSsh: record.desktopSsh } : {}), + ...(record.relayManaged ? { relayManaged: record.relayManaged } : {}), + }; } function toSavedEnvironmentStorageRecord( @@ -149,20 +154,13 @@ function toSavedEnvironmentStorageRecord( createdAt: record.createdAt, lastConnectedAt: record.lastConnectedAt, }; - const desktopSsh = record.desktopSsh; - if (desktopSsh) { - return Option.match(encryptedBearerToken, { - onNone: () => ({ ...nextRecord, desktopSsh }), - onSome: (value) => ({ - ...nextRecord, - desktopSsh, - encryptedBearerToken: value, - }), - }); - } + const metadata = { + ...(record.desktopSsh ? { desktopSsh: record.desktopSsh } : {}), + ...(record.relayManaged ? { relayManaged: record.relayManaged } : {}), + }; return Option.match(encryptedBearerToken, { - onNone: () => nextRecord, - onSome: (value) => ({ ...nextRecord, encryptedBearerToken: value }), + onNone: () => ({ ...nextRecord, ...metadata }), + onSome: (value) => ({ ...nextRecord, ...metadata, encryptedBearerToken: value }), }); } diff --git a/apps/desktop/src/window/DesktopApplicationMenu.test.ts b/apps/desktop/src/window/DesktopApplicationMenu.test.ts index fc589b3e39..62d619fe18 100644 --- a/apps/desktop/src/window/DesktopApplicationMenu.test.ts +++ b/apps/desktop/src/window/DesktopApplicationMenu.test.ts @@ -39,6 +39,9 @@ const electronAppLayer = Layer.succeed(ElectronApp.ElectronApp, { setName: () => Effect.void, setAboutPanelOptions: () => Effect.void, setAppUserModelId: () => Effect.void, + requestSingleInstanceLock: Effect.succeed(true), + isDefaultProtocolClient: () => Effect.succeed(false), + setAsDefaultProtocolClient: () => Effect.succeed(true), setDesktopName: () => Effect.void, setDockIcon: () => Effect.void, appendCommandLineSwitch: () => Effect.void, diff --git a/apps/mobile/app.config.ts b/apps/mobile/app.config.ts index 378ca1964a..d9288d9474 100644 --- a/apps/mobile/app.config.ts +++ b/apps/mobile/app.config.ts @@ -96,6 +96,11 @@ const config: ExpoConfig = { favicon: "./assets/favicon.png", }, plugins: [ + "expo-router", + "expo-font", + "expo-secure-store", + ["@clerk/expo", { theme: "./clerk-theme.json" }], + "expo-web-browser", [ "expo-camera", { @@ -120,17 +125,36 @@ const config: ExpoConfig = { "expo-build-properties", { ios: { - deploymentTarget: "16.4", + deploymentTarget: "18.0", }, }, ], - "expo-secure-store", - "expo-router", - "expo-font", + [ + "expo-widgets", + { + bundleIdentifier: `${variant.iosBundleIdentifier}.widgets`, + groupIdentifier: `group.${variant.iosBundleIdentifier}`, + enablePushNotifications: true, + widgets: [ + { + name: "AgentActivity", + displayName: "Agent Activity", + description: "Shows the current state of active T3 Code agents.", + supportedFamilies: ["systemSmall", "systemMedium", "accessoryRectangular"], + }, + ], + }, + ], "./plugins/withAndroidCleartextTraffic.cjs", ], extra: { appVariant: APP_VARIANT, + relay: { + url: process.env.T3_RELAY_URL ?? null, + }, + clerk: { + publishableKey: process.env.EXPO_PUBLIC_CLERK_PUBLISHABLE_KEY ?? null, + }, eas: { projectId: "d763fcb8-d37c-41ea-a773-b54a0ab4a454", }, diff --git a/apps/mobile/clerk-theme.json b/apps/mobile/clerk-theme.json new file mode 100644 index 0000000000..52941785f3 --- /dev/null +++ b/apps/mobile/clerk-theme.json @@ -0,0 +1,39 @@ +{ + "colors": { + "primary": "#262626", + "background": "#F2F2F7", + "input": "#FFFFFF", + "danger": "#DC2626", + "success": "#059669", + "warning": "#D97706", + "foreground": "#262626", + "mutedForeground": "#737373", + "primaryForeground": "#FFFFFF", + "inputForeground": "#262626", + "neutral": "#F5F5F5", + "border": "#E5E5EA", + "ring": "#A3A3A3", + "muted": "#F5F5F5", + "shadow": "#000000" + }, + "darkColors": { + "primary": "#F5F5F5", + "background": "#0E0E0E", + "input": "#171717", + "danger": "#FCA5A5", + "success": "#34D399", + "warning": "#FBBF24", + "foreground": "#F5F5F5", + "mutedForeground": "#A3A3A3", + "primaryForeground": "#0A0A0A", + "inputForeground": "#F5F5F5", + "neutral": "#1C1C1C", + "border": "#2A2A2A", + "ring": "#525252", + "muted": "#1C1C1C", + "shadow": "#000000" + }, + "design": { + "borderRadius": 18 + } +} diff --git a/apps/mobile/global.css b/apps/mobile/global.css index bbd1cb0be0..4642879451 100644 --- a/apps/mobile/global.css +++ b/apps/mobile/global.css @@ -38,6 +38,7 @@ --color-secondary: #ffffff; --color-secondary-foreground: #262626; --color-secondary-border: rgba(0, 0, 0, 0.08); + --color-switch-active: #34c759; /* Danger */ --color-danger: #fef2f2; @@ -125,6 +126,7 @@ --color-secondary: rgba(255, 255, 255, 0.04); --color-secondary-foreground: #f5f5f5; --color-secondary-border: rgba(255, 255, 255, 0.06); + --color-switch-active: #30d158; /* Danger */ --color-danger: rgba(239, 68, 68, 0.14); diff --git a/apps/mobile/package.json b/apps/mobile/package.json index 6f48f529c8..4b08a338e1 100644 --- a/apps/mobile/package.json +++ b/apps/mobile/package.json @@ -39,10 +39,13 @@ }, "dependencies": { "@callstack/liquid-glass": "^0.7.1", + "@clerk/expo": "^3.3.0", "@effect/atom-react": "catalog:", "@expo-google-fonts/dm-sans": "^0.4.2", "@expo/ui": "~56.0.8", "@legendapp/list": "3.0.0-beta.44", + "@noble/curves": "catalog:", + "@noble/hashes": "catalog:", "@pierre/diffs": "catalog:", "@react-native-menu/menu": "^2.0.0", "@shikijs/core": "3.23.0", @@ -58,6 +61,7 @@ "diff": "8.0.3", "effect": "catalog:", "expo": "^56.0.0", + "expo-auth-session": "~56.0.12", "expo-build-properties": "~56.0.15", "expo-camera": "~56.0.7", "expo-clipboard": "~56.0.3", @@ -70,12 +74,15 @@ "expo-haptics": "~56.0.3", "expo-image-picker": "~56.0.14", "expo-linking": "~56.0.12", + "expo-notifications": "~56.0.14", "expo-paste-input": "^0.1.15", "expo-router": "~56.2.7", "expo-secure-store": "~56.0.4", "expo-splash-screen": "~56.0.10", "expo-symbols": "~56.0.5", "expo-updates": "~56.0.17", + "expo-web-browser": "~56.0.5", + "expo-widgets": "~56.0.15", "punycode": "^2.3.1", "react": "19.2.3", "react-dom": "19.2.3", @@ -96,6 +103,7 @@ "uniwind": "^1.6.2" }, "devDependencies": { + "@effect/vitest": "catalog:", "@types/react": "~19.2.0", "babel-preset-expo": "~56.0.0", "tailwindcss": "^4.0.0", diff --git a/apps/mobile/src/app/_layout.tsx b/apps/mobile/src/app/_layout.tsx index 15ff31339f..70fd861aaa 100644 --- a/apps/mobile/src/app/_layout.tsx +++ b/apps/mobile/src/app/_layout.tsx @@ -20,12 +20,15 @@ import { } from "../state/use-remote-environment-registry"; import { RegistryContext } from "@effect/atom-react"; import { appAtomRegistry } from "../state/atom-registry"; +import { CloudAuthProvider } from "../features/cloud/CloudAuthProvider"; +import { useAgentNotificationNavigation } from "../features/agent-awareness/notificationNavigation"; function AppNavigator() { const { isLoadingSavedConnection } = useRemoteEnvironmentState(); const colorScheme = useColorScheme(); const statusBarBg = useCSSVariable("--color-status-bar"); const sheetStyle = useResolveClassNames("bg-sheet"); + useAgentNotificationNavigation(); const newTaskScreenOptions = { contentStyle: sheetStyle, @@ -45,6 +48,11 @@ function AppNavigator() { sheetGrabberVisible: true, }; + const settingsSheetScreenOptions = { + ...connectionSheetScreenOptions, + sheetAllowedDetents: [0.7], + }; + if (isLoadingSavedConnection) { return ; } @@ -66,6 +74,7 @@ function AppNavigator() { headerShadowVisible: false, }} /> + - - - - {fontsLoaded ? : } - - - - + + + + + + {fontsLoaded ? ( + + ) : ( + + )} + + + + + ); } diff --git a/apps/mobile/src/app/connections/index.tsx b/apps/mobile/src/app/connections/index.tsx index 6b5717094b..1f9a94a2b9 100644 --- a/apps/mobile/src/app/connections/index.tsx +++ b/apps/mobile/src/app/connections/index.tsx @@ -22,8 +22,8 @@ export default function ConnectionsRouteScreen() { const hasEnvironments = connectedEnvironments.length > 0; const [expandedId, setExpandedId] = useState(null); - const primaryFg = useThemeColor("--color-primary-foreground"); const accentColor = useThemeColor("--color-icon-muted"); + const iconColor = useThemeColor("--color-icon"); const handleToggle = useCallback((environmentId: EnvironmentId) => { setExpandedId((prev) => (prev === environmentId ? null : environmentId)); @@ -36,11 +36,15 @@ export default function ConnectionsRouteScreen() { title: "Environments", headerRight: () => ( - + diff --git a/apps/mobile/src/app/connections/new.tsx b/apps/mobile/src/app/connections/new.tsx index 6601090059..b817b446ec 100644 --- a/apps/mobile/src/app/connections/new.tsx +++ b/apps/mobile/src/app/connections/new.tsx @@ -130,7 +130,9 @@ export default function ConnectionsNewRouteScreen() { title: showScanner ? "Scan QR Code" : "Add Environment", headerRight: () => ( { if (showScanner) { closeScanner(); diff --git a/apps/mobile/src/app/index.tsx b/apps/mobile/src/app/index.tsx index 666a796736..1ae0ea36b2 100644 --- a/apps/mobile/src/app/index.tsx +++ b/apps/mobile/src/app/index.tsx @@ -78,16 +78,11 @@ export default function HomeRouteScreen() { - - More - router.push("/connections")} - subtitle="Manage connected hosts" - > - Environments - - + router.push("/settings")} + separateBackground + /> {/* Bottom toolbar: search + compose, visually split like iMessage */} diff --git a/apps/mobile/src/app/settings/_layout.tsx b/apps/mobile/src/app/settings/_layout.tsx new file mode 100644 index 0000000000..0110d765a6 --- /dev/null +++ b/apps/mobile/src/app/settings/_layout.tsx @@ -0,0 +1,41 @@ +import Stack from "expo-router/stack"; +import { useResolveClassNames } from "uniwind"; + +import { useThemeColor } from "../../lib/useThemeColor"; + +export const unstable_settings = { + anchor: "index", +}; + +export default function SettingsLayout() { + const contentStyle = useResolveClassNames("bg-sheet"); + const sheetBg = String(useThemeColor("--color-sheet")); + const headerTint = String(useThemeColor("--color-icon")); + + return ( + + + + + + + ); +} diff --git a/apps/mobile/src/app/settings/environment-new.tsx b/apps/mobile/src/app/settings/environment-new.tsx new file mode 100644 index 0000000000..3fb3e8d3a0 --- /dev/null +++ b/apps/mobile/src/app/settings/environment-new.tsx @@ -0,0 +1 @@ +export { default } from "../connections/new"; diff --git a/apps/mobile/src/app/settings/environments.tsx b/apps/mobile/src/app/settings/environments.tsx new file mode 100644 index 0000000000..ba6ddeea98 --- /dev/null +++ b/apps/mobile/src/app/settings/environments.tsx @@ -0,0 +1,335 @@ +import { useAuth } from "@clerk/expo"; +import { Link, Stack } from "expo-router"; +import { SymbolView } from "expo-symbols"; +import type { EnvironmentId } from "@t3tools/contracts"; +import { RELAY_CLERK_TOKEN_OPTIONS } from "@t3tools/shared/relayAuth"; +import * as Effect from "effect/Effect"; +import { useCallback, useEffect, useMemo, useRef, useState } from "react"; +import { ActivityIndicator, Alert, Pressable, ScrollView, View } from "react-native"; +import { useSafeAreaInsets } from "react-native-safe-area-context"; + +import { AppText as Text } from "../../components/AppText"; +import { + cloudEnvironmentsPendingStatus, + type CloudEnvironmentRecordWithStatus, + connectCloudEnvironment, + listCloudEnvironments, + loadCloudEnvironmentStatuses, +} from "../../features/cloud/linkEnvironment"; +import { ConnectionEnvironmentRow } from "../../features/connection/ConnectionEnvironmentRow"; +import { cn } from "../../lib/cn"; +import { mobileRuntime } from "../../lib/runtime"; +import { useThemeColor } from "../../lib/useThemeColor"; +import { + connectSavedEnvironment, + useRemoteConnections, + useRemoteEnvironmentState, +} from "../../state/use-remote-environment-registry"; + +export default function SettingsEnvironmentsRouteScreen() { + const { getToken, isLoaded, isSignedIn } = useAuth({ treatPendingAsSignedOut: false }); + const getTokenRef = useRef(getToken); + getTokenRef.current = getToken; + const { + connectedEnvironments, + onReconnectEnvironment, + onRemoveEnvironmentPress, + onUpdateEnvironment, + } = useRemoteConnections(); + const { savedConnectionsById } = useRemoteEnvironmentState(); + const insets = useSafeAreaInsets(); + const hasEnvironments = connectedEnvironments.length > 0; + const [expandedId, setExpandedId] = useState(null); + const [cloudEnvironments, setCloudEnvironments] = useState< + ReadonlyArray + >([]); + const [cloudStatus, setCloudStatus] = useState<"idle" | "loading" | "error">("idle"); + const [cloudError, setCloudError] = useState(null); + const [connectingCloudEnvironmentId, setConnectingCloudEnvironmentId] = useState( + null, + ); + + const accentColor = useThemeColor("--color-icon-muted"); + const iconColor = useThemeColor("--color-icon"); + + const handleToggle = useCallback((environmentId: EnvironmentId) => { + setExpandedId((prev) => (prev === environmentId ? null : environmentId)); + }, []); + + const availableCloudEnvironments = useMemo( + () => + cloudEnvironments.filter( + (record) => savedConnectionsById[record.environment.environmentId] === undefined, + ), + [cloudEnvironments, savedConnectionsById], + ); + + const refreshCloudEnvironments = useCallback(async () => { + if (!isLoaded || !isSignedIn) { + setCloudEnvironments([]); + setCloudStatus("idle"); + setCloudError(null); + return; + } + + setCloudStatus("loading"); + setCloudError(null); + try { + const token = await getTokenRef.current(RELAY_CLERK_TOKEN_OPTIONS); + if (!token) { + setCloudEnvironments([]); + setCloudStatus("idle"); + return; + } + const environments = await mobileRuntime.runPromise( + listCloudEnvironments({ clerkToken: token }), + ); + setCloudEnvironments(cloudEnvironmentsPendingStatus(environments)); + const records = await mobileRuntime.runPromise( + loadCloudEnvironmentStatuses({ clerkToken: token, environments }), + ); + setCloudEnvironments(records); + setCloudStatus("idle"); + } catch (error) { + setCloudStatus("error"); + setCloudError( + error instanceof Error ? error.message : "Could not load T3 Cloud environments.", + ); + } + }, [isLoaded, isSignedIn]); + + useEffect(() => { + void refreshCloudEnvironments(); + }, [refreshCloudEnvironments]); + + const handleConnectCloudEnvironment = useCallback( + async (record: CloudEnvironmentRecordWithStatus) => { + setConnectingCloudEnvironmentId(record.environment.environmentId); + try { + const token = await getToken(RELAY_CLERK_TOKEN_OPTIONS); + if (!token) { + throw new Error("Sign in to T3 Cloud before connecting."); + } + await mobileRuntime.runPromise( + connectCloudEnvironment({ + clerkToken: token, + environment: record.environment, + }).pipe(Effect.flatMap(connectSavedEnvironment)), + ); + setCloudEnvironments((records) => + records.filter( + (candidate) => candidate.environment.environmentId !== record.environment.environmentId, + ), + ); + } catch (error) { + Alert.alert( + "Connect failed", + error instanceof Error ? error.message : "Could not connect to this environment.", + ); + } finally { + setConnectingCloudEnvironmentId(null); + } + }, + [getToken], + ); + + return ( + + ( + + + + + + ), + }} + /> + + {hasEnvironments ? ( + + {connectedEnvironments.map((environment, index) => ( + + handleToggle(environment.environmentId)} + onReconnect={onReconnectEnvironment} + onRemove={onRemoveEnvironmentPress} + onUpdate={onUpdateEnvironment} + /> + + ))} + + ) : ( + + + + + + No environments connected yet.{"\n"}Tap{" "} + + to add one. + + + )} + + {isSignedIn ? ( + + + + T3 Cloud + + + {cloudStatus === "loading" ? ( + + ) : ( + + )} + + + + {availableCloudEnvironments.length > 0 ? ( + + {availableCloudEnvironments.map((record, index) => ( + handleConnectCloudEnvironment(record)} + /> + ))} + + ) : cloudStatus === "loading" ? ( + + + + Loading linked cloud environments. + + + ) : cloudStatus === "error" ? ( + + + Could not load T3 Cloud environments + + + {cloudError} + + + ) : ( + + + No additional linked cloud environments. + + + )} + + ) : null} + + + ); +} + +function CloudEnvironmentRow(props: { + readonly record: CloudEnvironmentRecordWithStatus; + readonly borderTop: boolean; + readonly isConnecting: boolean; + readonly onConnect: () => void; +}) { + const mutedColor = useThemeColor("--color-icon-muted"); + const { environment, status, statusError } = props.record; + const disabled = props.isConnecting; + const statusText = + status === null + ? (statusError ?? "Status unavailable") + : status.status === "online" + ? "Online" + : (status.error ?? "Offline"); + + return ( + + + + + + + {environment.label} + + + {environment.endpoint.httpBaseUrl} + + + {statusText} + + + + + {props.isConnecting ? "Connecting" : "Connect"} + + + + ); +} diff --git a/apps/mobile/src/app/settings/index.tsx b/apps/mobile/src/app/settings/index.tsx new file mode 100644 index 0000000000..917c8db8a2 --- /dev/null +++ b/apps/mobile/src/app/settings/index.tsx @@ -0,0 +1,400 @@ +import { useAuth, useUser, useUserProfileModal } from "@clerk/expo"; +import * as Notifications from "expo-notifications"; +import { RELAY_CLERK_TOKEN_OPTIONS } from "@t3tools/shared/relayAuth"; +import { Link, Stack, useRouter } from "expo-router"; +import { SymbolView } from "expo-symbols"; +import * as Effect from "effect/Effect"; +import { useCallback, useEffect, useMemo, useState } from "react"; +import type { ComponentProps, ReactNode } from "react"; +import { Alert, Linking, Pressable, ScrollView, Switch, View } from "react-native"; +import { useSafeAreaInsets } from "react-native-safe-area-context"; + +import { AppText as Text } from "../../components/AppText"; +import { setLiveActivityUpdatesEnabled } from "../../features/agent-awareness/liveActivityPreferences"; +import { requestAgentNotificationPermission } from "../../features/agent-awareness/notificationPermissions"; +import { refreshAgentAwarenessRegistration } from "../../features/agent-awareness/remoteRegistration"; +import { mobileRuntime } from "../../lib/runtime"; +import { loadPreferences } from "../../lib/storage"; +import { useThemeColor } from "../../lib/useThemeColor"; +import { useRemoteEnvironmentState } from "../../state/use-remote-environment-registry"; + +type NotificationStatus = "checking" | "enabled" | "disabled" | "unsupported"; +type LiveActivityStatus = "checking" | "enabled" | "disabled" | "signed-out" | "linking"; + +export default function SettingsRouteScreen() { + const insets = useSafeAreaInsets(); + const { push } = useRouter(); + const { getToken, isLoaded, isSignedIn } = useAuth({ treatPendingAsSignedOut: false }); + const { user } = useUser(); + const { isAvailable: isUserProfileModalAvailable, presentUserProfile } = useUserProfileModal(); + const { savedConnectionsById } = useRemoteEnvironmentState(); + const [notificationStatus, setNotificationStatus] = useState("checking"); + const [liveActivityStatus, setLiveActivityStatus] = useState("checking"); + + const icon = useThemeColor("--color-icon"); + const connections = useMemo(() => Object.values(savedConnectionsById), [savedConnectionsById]); + const environmentCount = connections.length; + const accountLabel = useMemo(() => { + if (!isLoaded) return "Checking"; + if (!isSignedIn) return "Request access"; + return user?.primaryEmailAddress?.emailAddress ?? "Signed in"; + }, [isLoaded, isSignedIn, user?.primaryEmailAddress?.emailAddress]); + + const refreshNotifications = useCallback(async () => { + if (process.env.EXPO_OS !== "ios") { + setNotificationStatus("unsupported"); + return; + } + const permission = await Notifications.getPermissionsAsync(); + setNotificationStatus(permission.granted ? "enabled" : "disabled"); + }, []); + + useEffect(() => { + void refreshNotifications(); + }, [refreshNotifications]); + + useEffect(() => { + if (!isLoaded) { + setLiveActivityStatus("checking"); + return; + } + if (!isSignedIn) { + setLiveActivityStatus("signed-out"); + return; + } + void loadPreferences().then( + (preferences) => { + setLiveActivityStatus(preferences.liveActivitiesEnabled === false ? "disabled" : "enabled"); + }, + () => { + setLiveActivityStatus("enabled"); + }, + ); + }, [isLoaded, isSignedIn]); + + const requestNotifications = useCallback(async () => { + try { + const result = await mobileRuntime.runPromise( + requestAgentNotificationPermission.pipe( + Effect.tap((permission) => + permission.type === "granted" ? refreshAgentAwarenessRegistration() : Effect.void, + ), + ), + ); + if (result.type === "granted") { + setNotificationStatus("enabled"); + Alert.alert( + "Notifications enabled", + "Live Activity notifications are enabled for this device.", + ); + return; + } + if (result.type === "unsupported") { + setNotificationStatus("unsupported"); + Alert.alert( + "Notifications unavailable", + "Live Activity notifications are only available on iOS.", + ); + return; + } + setNotificationStatus("disabled"); + if (result.canAskAgain) { + Alert.alert("Notifications disabled", "Notifications were not enabled."); + return; + } + Alert.alert( + "Notifications disabled", + "Notifications were denied for this app. Open Settings to enable them.", + [ + { text: "Cancel", style: "cancel" }, + { text: "Open Settings", onPress: () => void Linking.openSettings() }, + ], + ); + } catch (error) { + Alert.alert( + "Notifications unavailable", + error instanceof Error ? error.message : "Could not request notification permission.", + ); + } + }, []); + + const promptSignIn = useCallback(() => { + Alert.alert( + "Request T3 Cloud access", + "Live Activity updates require approved T3 Cloud access so relay can deliver updates to this device.", + [ + { text: "Cancel", style: "cancel" }, + { text: "Continue", onPress: () => push("/settings/waitlist") }, + ], + ); + }, [push]); + + const linkEnvironments = useCallback(async () => { + if (!isSignedIn) { + promptSignIn(); + return; + } + + setLiveActivityStatus("linking"); + try { + const token = await getToken(RELAY_CLERK_TOKEN_OPTIONS); + if (!token) { + promptSignIn(); + setLiveActivityStatus("signed-out"); + return; + } + + await mobileRuntime.runPromise( + setLiveActivityUpdatesEnabled({ + enabled: true, + clerkToken: token, + connections, + }), + ); + setLiveActivityStatus("enabled"); + Alert.alert( + "Live Activities enabled", + environmentCount > 0 + ? `${environmentCount} environment${environmentCount === 1 ? "" : "s"} linked for Live Activity updates.` + : "Live Activity updates are enabled. Add an environment to start receiving updates.", + ); + } catch (error) { + setLiveActivityStatus("disabled"); + Alert.alert( + "Live Activities unavailable", + error instanceof Error ? error.message : "Could not enable Live Activity updates.", + ); + } + }, [connections, environmentCount, getToken, isSignedIn, promptSignIn]); + + const handleDeviceNotificationsChange = useCallback( + (enabled: boolean) => { + if (enabled) { + void requestNotifications(); + return; + } + + Alert.alert( + "Disable notifications", + "Notification permission is controlled by iOS. Open Settings to disable notifications for T3 Code.", + [ + { text: "Cancel", style: "cancel" }, + { text: "Open Settings", onPress: () => void Linking.openSettings() }, + ], + ); + }, + [requestNotifications], + ); + + const handleLiveActivitiesChange = useCallback( + (enabled: boolean) => { + if (!enabled) { + setLiveActivityStatus("disabled"); + void (async () => { + try { + const token = isSignedIn ? await getToken(RELAY_CLERK_TOKEN_OPTIONS) : null; + await mobileRuntime.runPromise( + setLiveActivityUpdatesEnabled({ + enabled: false, + clerkToken: token, + connections, + }), + ); + } catch { + // The switch is optimistic; a future refresh reconciles relay state. + } + })(); + return; + } + + if (!isSignedIn) { + promptSignIn(); + return; + } + + void linkEnvironments(); + }, + [connections, getToken, isSignedIn, linkEnvironments, promptSignIn], + ); + + const openAccount = useCallback(() => { + if (!isLoaded) return; + if (!isSignedIn) { + push("/settings/waitlist"); + return; + } + if (isUserProfileModalAvailable) { + void presentUserProfile(); + return; + } + Alert.alert( + "T3 Cloud unavailable", + "Native T3 Cloud account management is not available in this build.", + ); + }, [isLoaded, isSignedIn, isUserProfileModalAvailable, presentUserProfile, push]); + + return ( + + + + + + + + + T3 Code works locally without signing in. Cloud features are optional. + + + + + + + + + + + + + Version + Alpha + + + + + ); +} + +type SymbolName = ComponentProps["name"]; + +function SettingsSection(props: { readonly title: string; readonly children: ReactNode }) { + return ( + + {props.title} + + {props.children} + + + ); +} + +function SettingsRow(props: { + readonly disabled?: boolean; + readonly icon: SymbolName; + readonly label: string; + readonly value?: string; + readonly href?: "/settings/environments"; + readonly onPress?: () => void; +}) { + const icon = useThemeColor("--color-icon"); + const chevron = useThemeColor("--color-chevron"); + const content = ( + + + {props.label} + {props.value ? ( + + {props.value} + + ) : null} + + + ); + + if (props.href) { + return ( + + {content} + + ); + } + + return ( + + {content} + + ); +} + +function SettingsSwitchRow(props: { + readonly disabled?: boolean; + readonly icon: SymbolName; + readonly label: string; + readonly value: boolean; + readonly onValueChange: (value: boolean) => void; +}) { + const icon = useThemeColor("--color-icon"); + const activeTrack = String(useThemeColor("--color-switch-active")); + const track = String(useThemeColor("--color-secondary-border")); + + return ( + + + {props.label} + + + ); +} diff --git a/apps/mobile/src/app/settings/waitlist.tsx b/apps/mobile/src/app/settings/waitlist.tsx new file mode 100644 index 0000000000..348197bfdf --- /dev/null +++ b/apps/mobile/src/app/settings/waitlist.tsx @@ -0,0 +1,67 @@ +import Constants from "expo-constants"; +import { Stack } from "expo-router"; +import { ScrollView, Text, View } from "react-native"; + +import { CloudWaitlistEnrollment } from "../../features/cloud/CloudWaitlistEnrollment"; +import { useNativeClerkAuthModal } from "../../features/cloud/useNativeClerkAuthModal"; +import { useThemeColor } from "../../lib/useThemeColor"; + +function hasClerkConfig(): boolean { + const clerkConfig = Constants.expoConfig?.extra?.clerk as + | { readonly publishableKey?: string | null } + | undefined; + return Boolean(clerkConfig?.publishableKey); +} + +export default function SettingsWaitlistRouteScreen() { + const { presentAuth } = useNativeClerkAuthModal(); + const foreground = String(useThemeColor("--color-foreground")); + const secondaryForeground = String(useThemeColor("--color-foreground-secondary")); + + return ( + <> + + + {hasClerkConfig() ? ( + void presentAuth()} /> + ) : ( + + + T3 Cloud is not configured + + + Add EXPO_PUBLIC_CLERK_PUBLISHABLE_KEY to this build to enable waitlist enrollment. + + + )} + + + ); +} diff --git a/apps/mobile/src/features/agent-awareness/liveActivityController.test.ts b/apps/mobile/src/features/agent-awareness/liveActivityController.test.ts new file mode 100644 index 0000000000..69d002577e --- /dev/null +++ b/apps/mobile/src/features/agent-awareness/liveActivityController.test.ts @@ -0,0 +1,256 @@ +import { afterEach, beforeEach, vi } from "vitest"; +import { describe, expect, it } from "@effect/vitest"; +import * as Effect from "effect/Effect"; +import { ManagedRelayClient } from "@t3tools/client-runtime"; + +import type { EnvironmentId, OrchestrationShellSnapshot, ThreadId } from "@t3tools/contracts"; +import { + __resetAgentLiveActivitiesForTest, + refreshActiveLiveActivityRemoteRegistration, + syncAgentLiveActivitiesForSnapshot, +} from "./liveActivityController"; +import { registerLiveActivityPushToken } from "./remoteRegistration"; + +const mocks = vi.hoisted(() => { + const existingActivity = { + update: vi.fn(() => Promise.resolve()), + end: vi.fn((_dismissal: unknown, _props?: unknown, _endedAt?: unknown) => Promise.resolve()), + getPushToken: vi.fn(() => Promise.resolve("activity-token")), + addPushTokenListener: vi.fn(), + }; + return { + existingActivity, + getInstances: vi.fn(() => [existingActivity]), + start: vi.fn(() => existingActivity), + registerLiveActivityPushToken: vi.fn( + (): Effect.Effect => Effect.succeed(true), + ), + }; +}); + +vi.mock("react-native", () => ({ + Platform: { + OS: "ios", + }, +})); + +vi.mock("expo-linking", () => ({ + default: { + createURL: vi.fn((path: string) => `t3code://${path}`), + }, + createURL: vi.fn((path: string) => `t3code://${path}`), +})); + +vi.mock("expo-widgets", () => ({ + after: (date: Date) => ({ after: date }), +})); + +vi.mock("../../lib/runtime", () => ({ + mobileRuntime: { + runPromise: (operation: Effect.Effect) => Effect.runPromise(operation), + }, +})); + +vi.mock("../../widgets/AgentActivity", () => ({ + default: { + getInstances: mocks.getInstances, + start: mocks.start, + }, +})); + +vi.mock("./remoteRegistration", () => ({ + registerLiveActivityPushToken: mocks.registerLiveActivityPushToken, +})); + +const runManagedRelayEffect = (effect: Effect.Effect): Promise => + Effect.runPromise(effect.pipe(Effect.provideService(ManagedRelayClient, null as never))); + +function runningSnapshot(): OrchestrationShellSnapshot { + return { + projects: [ + { + id: "project-1", + title: "Project", + }, + ], + threads: [ + { + id: "thread-1" as ThreadId, + projectId: "project-1", + title: "Thread", + modelSelection: { + model: "gpt-5", + }, + session: { + status: "running", + providerName: "Codex", + }, + latestTurn: { + state: "running", + }, + updatedAt: "2026-05-25T00:00:00.000Z", + hasPendingApprovals: false, + hasPendingUserInput: false, + }, + ], + } as unknown as OrchestrationShellSnapshot; +} + +function completedSnapshot(): OrchestrationShellSnapshot { + return { + projects: [ + { + id: "project-1", + title: "Project", + }, + ], + threads: [ + { + id: "thread-1" as ThreadId, + projectId: "project-1", + title: "Thread", + modelSelection: { + model: "gpt-5", + }, + session: null, + latestTurn: { + state: "completed", + }, + updatedAt: "2026-05-25T00:01:00.000Z", + hasPendingApprovals: false, + hasPendingUserInput: false, + }, + ], + } as unknown as OrchestrationShellSnapshot; +} + +describe("liveActivityController", () => { + beforeEach(() => { + vi.stubGlobal("__DEV__", false); + __resetAgentLiveActivitiesForTest(); + mocks.existingActivity.update.mockClear(); + mocks.existingActivity.end.mockClear(); + mocks.existingActivity.getPushToken.mockClear(); + mocks.existingActivity.addPushTokenListener.mockClear(); + mocks.getInstances.mockClear(); + mocks.getInstances.mockReturnValue([mocks.existingActivity]); + mocks.start.mockClear(); + mocks.registerLiveActivityPushToken.mockClear(); + mocks.registerLiveActivityPushToken.mockReturnValue(Effect.succeed(true)); + }); + + afterEach(() => { + vi.useRealTimers(); + }); + + it("adopts an existing remote-started Live Activity instead of creating a duplicate", async () => { + await Effect.runPromise( + syncAgentLiveActivitiesForSnapshot({ + environmentId: "env-1" as EnvironmentId, + snapshot: runningSnapshot(), + }), + ); + + expect(mocks.getInstances).toHaveBeenCalledTimes(1); + expect(mocks.existingActivity.update).toHaveBeenCalledTimes(1); + expect(mocks.start).not.toHaveBeenCalled(); + expect(registerLiveActivityPushToken).toHaveBeenCalledWith({ + activity: mocks.existingActivity, + }); + }); + + it("keeps skipped remote token registrations retryable after cloud sign-in", async () => { + mocks.registerLiveActivityPushToken + .mockReturnValueOnce(Effect.succeed(false)) + .mockReturnValueOnce(Effect.succeed(true)); + + await Effect.runPromise( + syncAgentLiveActivitiesForSnapshot({ + environmentId: "env-1" as EnvironmentId, + snapshot: runningSnapshot(), + }), + ); + await runManagedRelayEffect(refreshActiveLiveActivityRemoteRegistration()); + + expect(registerLiveActivityPushToken).toHaveBeenCalledTimes(2); + expect(registerLiveActivityPushToken).toHaveBeenNthCalledWith(2, { + activity: mocks.existingActivity, + }); + }); + + it("retries cloud sign-in Live Activity token refresh failures", async () => { + vi.useFakeTimers(); + mocks.registerLiveActivityPushToken + .mockReturnValueOnce(Effect.succeed(true)) + .mockReturnValueOnce(Effect.fail(new Error("relay unavailable"))) + .mockReturnValueOnce(Effect.succeed(true)); + + await Effect.runPromise( + syncAgentLiveActivitiesForSnapshot({ + environmentId: "env-1" as EnvironmentId, + snapshot: runningSnapshot(), + }), + ); + await runManagedRelayEffect(refreshActiveLiveActivityRemoteRegistration()); + + expect(registerLiveActivityPushToken).toHaveBeenCalledTimes(2); + + await vi.advanceTimersByTimeAsync(15_000); + + expect(registerLiveActivityPushToken).toHaveBeenCalledTimes(3); + expect(registerLiveActivityPushToken).toHaveBeenNthCalledWith(3, { + activity: mocks.existingActivity, + }); + }); + + it("retries adopted remote-start Live Activity token registration when the token is initially unavailable", async () => { + vi.useFakeTimers(); + mocks.registerLiveActivityPushToken + .mockReturnValueOnce(Effect.succeed(false)) + .mockReturnValueOnce(Effect.succeed(true)); + + await Effect.runPromise( + syncAgentLiveActivitiesForSnapshot({ + environmentId: "env-1" as EnvironmentId, + snapshot: runningSnapshot(), + }), + ); + + expect(registerLiveActivityPushToken).toHaveBeenCalledTimes(1); + + await vi.advanceTimersByTimeAsync(15_000); + + expect(registerLiveActivityPushToken).toHaveBeenCalledTimes(2); + expect(registerLiveActivityPushToken).toHaveBeenNthCalledWith(2, { + activity: mocks.existingActivity, + }); + }); + + it("ends active Live Activities with the terminal thread content state", async () => { + await Effect.runPromise( + syncAgentLiveActivitiesForSnapshot({ + environmentId: "env-1" as EnvironmentId, + snapshot: runningSnapshot(), + }), + ); + await Effect.runPromise( + syncAgentLiveActivitiesForSnapshot({ + environmentId: "env-1" as EnvironmentId, + snapshot: completedSnapshot(), + }), + ); + + expect(mocks.existingActivity.end).toHaveBeenCalledTimes(1); + expect(mocks.existingActivity.end.mock.calls[0]?.[1]).toMatchObject({ + activeCount: 1, + activities: [ + { + environmentId: "env-1", + threadId: "thread-1", + phase: "completed", + status: "Done", + }, + ], + }); + }); +}); diff --git a/apps/mobile/src/features/agent-awareness/liveActivityController.ts b/apps/mobile/src/features/agent-awareness/liveActivityController.ts new file mode 100644 index 0000000000..ed10e1e4ec --- /dev/null +++ b/apps/mobile/src/features/agent-awareness/liveActivityController.ts @@ -0,0 +1,605 @@ +import { + isTerminalAgentAwarenessPhase, + projectThreadAwareness, + type AgentAwarenessState, +} from "@t3tools/shared/agentAwareness"; +import type { + EnvironmentId, + OrchestrationProjectShell, + OrchestrationShellSnapshot, +} from "@t3tools/contracts"; +import * as DateTime from "effect/DateTime"; +import * as Duration from "effect/Duration"; +import * as Effect from "effect/Effect"; +import * as Option from "effect/Option"; +import * as Semaphore from "effect/Semaphore"; +import { after, type LiveActivity } from "expo-widgets"; +import * as Linking from "expo-linking"; +import { Platform } from "react-native"; +import { ManagedRelayClient } from "@t3tools/client-runtime"; + +import { mobileRuntime } from "../../lib/runtime"; +import AgentActivity, { type AgentActivityProps } from "../../widgets/AgentActivity"; +import { registerLiveActivityPushToken } from "./remoteRegistration"; + +const MAX_LOCAL_LIVE_ACTIVITIES = 3; +const FINAL_ACTIVITY_DISMISSAL_MS = 5 * 60 * 1_000; +const REMOTE_TOKEN_REGISTRATION_RETRY_MS = 15_000; +const MISSING_STATE_GRACE_MS = 30_000; + +interface ActiveDeviceActivity { + readonly instance: LiveActivity; + readonly props: AgentActivityProps; + readonly lastRemoteTokenRegistrationAttemptAt: number | null; + readonly remoteTokenRegistered: boolean; + readonly remoteTokenRetryScheduled: boolean; + readonly missingSince: number | null; +} + +let activeActivity: ActiveDeviceActivity | null = null; +const environmentStates = new Map>(); +let localLiveActivitiesEnabled = true; +const liveActivitySyncSemaphore = Effect.runSync(Semaphore.make(1)); + +function canUseLocalLiveActivities(): boolean { + return localLiveActivitiesEnabled && Platform.OS === "ios"; +} + +function logLiveActivityDebug(context: string, details?: unknown): void { + if (!__DEV__) { + return; + } + console.log(`[agent-awareness] ${context}`, details ?? ""); +} + +function logLiveActivityWarning(context: string, error: unknown): void { + if (!__DEV__) { + return; + } + console.warn( + `[agent-awareness] ${context}`, + error instanceof Error ? error.message : String(error), + ); +} + +function statusForPhase(phase: AgentAwarenessState["phase"]): string { + switch (phase) { + case "waiting_for_approval": + return "Approval"; + case "waiting_for_input": + return "Input"; + case "completed": + return "Done"; + case "failed": + return "Failed"; + case "starting": + return "Starting"; + case "running": + return "Working"; + case "stale": + return "Waiting"; + } +} + +function epochMillis(iso: string): number { + return Option.match(DateTime.make(iso), { + onNone: () => Number.NaN, + onSome: (dt) => dt.epochMilliseconds, + }); +} + +function currentTimeMillis(): number { + return Date.now(); +} + +function currentDateTime(): DateTime.Utc { + return DateTime.nowUnsafe(); +} + +function toActivityProps(states: ReadonlyArray): AgentActivityProps { + const updatedAt = states.reduce((latest, state) => { + if (latest === null) { + return state.updatedAt; + } + return epochMillis(state.updatedAt) > epochMillis(latest) ? state.updatedAt : latest; + }, null); + + return { + title: "T3 Code", + subtitle: "Agent work in progress", + activeCount: states.length, + updatedAt: updatedAt ?? DateTime.formatIso(currentDateTime()), + activities: states.slice(0, MAX_LOCAL_LIVE_ACTIVITIES).map((state) => ({ + environmentId: state.environmentId, + threadId: state.threadId, + projectTitle: state.projectTitle, + threadTitle: state.threadTitle, + modelTitle: state.modelTitle, + phase: state.phase, + status: statusForPhase(state.phase), + updatedAt: state.updatedAt, + deepLink: state.deepLink, + })), + }; +} + +function hasSameActivityContent(left: AgentActivityProps, right: AgentActivityProps): boolean { + return JSON.stringify(left) === JSON.stringify(right); +} + +function sortByUpdatedAtDesc(left: AgentAwarenessState, right: AgentAwarenessState): number { + return epochMillis(right.updatedAt) - epochMillis(left.updatedAt); +} + +function projectSnapshotAwareness(input: { + readonly environmentId: EnvironmentId; + readonly snapshot: OrchestrationShellSnapshot; +}): ReadonlyArray { + const projectsById = new Map( + input.snapshot.projects.map((project) => [project.id, project]), + ); + const states: AgentAwarenessState[] = []; + + for (const thread of input.snapshot.threads) { + const project = projectsById.get(thread.projectId); + if (!project) { + continue; + } + const state = projectThreadAwareness({ + environmentId: input.environmentId, + project, + thread, + }); + if (state) { + states.push(state); + } + } + + return states; +} + +export function syncAgentLiveActivitiesForSnapshot(input: { + readonly environmentId: EnvironmentId; + readonly snapshot: OrchestrationShellSnapshot | null; +}): Effect.Effect { + return enqueueLiveActivitySync( + Effect.gen(function* () { + if (!canUseLocalLiveActivities()) { + return; + } + + if (input.snapshot === null) { + return yield* endEnvironmentLiveActivitiesNow(input.environmentId); + } + + const states = projectSnapshotAwareness({ + environmentId: input.environmentId, + snapshot: input.snapshot, + }); + environmentStates.set(input.environmentId, states); + return yield* syncAgentLiveActivities(); + }), + ); +} + +export function endEnvironmentLiveActivities( + environmentId: EnvironmentId, +): Effect.Effect { + return enqueueLiveActivitySync(endEnvironmentLiveActivitiesNow(environmentId)); +} + +function endEnvironmentLiveActivitiesNow( + environmentId: EnvironmentId, +): Effect.Effect { + return Effect.gen(function* () { + environmentStates.delete(environmentId); + return yield* syncAgentLiveActivities(); + }); +} + +export function endAllAgentLiveActivities(): Effect.Effect { + return enqueueLiveActivitySync(endAllAgentLiveActivitiesNow()); +} + +function endAllAgentLiveActivitiesNow(): Effect.Effect { + return Effect.gen(function* () { + environmentStates.clear(); + return yield* endActiveActivity(null, "all-ended"); + }); +} + +function enqueueLiveActivitySync( + operation: Effect.Effect, +): Effect.Effect { + return liveActivitySyncSemaphore.withPermits(1)(operation); +} + +function syncAgentLiveActivities(): Effect.Effect { + const states = [...environmentStates.values()].flat().sort(sortByUpdatedAtDesc); + const activeNonTerminalStates = states.filter( + (state) => !isTerminalAgentAwarenessPhase(state.phase), + ); + const terminalState = states.find((state) => isTerminalAgentAwarenessPhase(state.phase)) ?? null; + + if (activeNonTerminalStates.length === 0) { + if (!activeActivity) { + return Effect.void; + } + if (terminalState) { + return endActiveActivity(terminalState, "terminal-state"); + } + const now = currentTimeMillis(); + if (activeActivity.missingSince === null) { + activeActivity = { ...activeActivity, missingSince: now }; + logLiveActivityDebug("live activity missing state; waiting before ending", { + graceMs: MISSING_STATE_GRACE_MS, + }); + return Effect.void; + } + if (now - activeActivity.missingSince >= MISSING_STATE_GRACE_MS) { + return endActiveActivity(null, "missing-state"); + } + return Effect.void; + } + + return startOrUpdateActivity(activeNonTerminalStates); +} + +function startOrUpdateActivity( + states: ReadonlyArray, +): Effect.Effect { + const props = toActivityProps(states); + const primaryState = states[0]; + if (activeActivity) { + const active = activeActivity; + if (!hasSameActivityContent(active.props, props)) { + logLiveActivityDebug("updating live activity", { + activeCount: props.activeCount, + primaryThreadId: primaryState?.threadId ?? null, + }); + return runLiveActivityOperation( + "update", + Effect.tryPromise({ + try: () => active.instance.update(props), + catch: (error) => error, + }), + ).pipe( + Effect.flatMap((updated) => + Effect.sync(() => { + if (!updated.ok) { + activeActivity = null; + return; + } + activeActivity = { ...active, props, missingSince: null }; + retryRemoteTokenRegistration(activeActivity.instance); + }), + ), + ); + } else if (activeActivity.missingSince !== null) { + activeActivity = { ...activeActivity, missingSince: null }; + } + retryRemoteTokenRegistration(activeActivity.instance); + return Effect.void; + } + + return adoptExistingActivity(props, primaryState).pipe( + Effect.flatMap((adopted) => { + if (adopted) { + return Effect.void; + } + + logLiveActivityDebug("starting live activity", { + activeCount: props.activeCount, + primaryThreadId: primaryState?.threadId ?? null, + }); + return runLiveActivityOperation( + "start", + Effect.try({ + try: () => AgentActivity.start(props, Linking.createURL(primaryState?.deepLink ?? "/")), + catch: (error) => error, + }), + ).pipe( + Effect.flatMap((started) => + Effect.sync(() => { + const instance = started.ok ? started.value : undefined; + if (instance) { + logLiveActivityDebug("live activity started", { + primaryThreadId: primaryState?.threadId ?? null, + localActivityCount: AgentActivity.getInstances().length, + rowCount: props.activeCount, + }); + activeActivity = { + instance, + props, + lastRemoteTokenRegistrationAttemptAt: null, + remoteTokenRegistered: false, + remoteTokenRetryScheduled: false, + missingSince: null, + }; + retryRemoteTokenRegistration(instance); + } + }), + ), + ); + }), + ); +} + +function adoptExistingActivity( + props: AgentActivityProps, + primaryState: AgentAwarenessState | undefined, +): Effect.Effect { + const existingActivity = AgentActivity.getInstances()[0]; + if (!existingActivity) { + return Effect.succeed(false); + } + + logLiveActivityDebug("adopting existing live activity", { + activeCount: props.activeCount, + primaryThreadId: primaryState?.threadId ?? null, + }); + return runLiveActivityOperation( + "update", + Effect.tryPromise({ + try: () => existingActivity.update(props), + catch: (error) => error, + }), + ).pipe( + Effect.flatMap((updated) => + Effect.sync(() => { + if (!updated.ok) { + return false; + } + + activeActivity = { + instance: existingActivity, + props, + lastRemoteTokenRegistrationAttemptAt: null, + remoteTokenRegistered: false, + remoteTokenRetryScheduled: false, + missingSince: null, + }; + retryRemoteTokenRegistration(existingActivity); + return true; + }), + ), + ); +} + +function retryRemoteTokenRegistration(activity: LiveActivity): void { + if (!activeActivity) { + return; + } + + if (activeActivity.remoteTokenRegistered) { + return; + } + const now = currentTimeMillis(); + if ( + activeActivity.lastRemoteTokenRegistrationAttemptAt !== null && + now - activeActivity.lastRemoteTokenRegistrationAttemptAt < REMOTE_TOKEN_REGISTRATION_RETRY_MS + ) { + return; + } + + activeActivity = { + ...activeActivity, + lastRemoteTokenRegistrationAttemptAt: now, + }; + void mobileRuntime + .runPromise( + registerRemoteActivityToken(activity).pipe( + Effect.flatMap((registered) => + Effect.sync(() => { + if (!registered) { + scheduleRemoteTokenRegistrationRetry(activity); + } + }), + ), + Effect.catch((error) => + Effect.sync(() => { + logLiveActivityWarning( + "live activity token registration failed; retry scheduled", + error, + ); + scheduleRemoteTokenRegistrationRetry(activity); + }), + ), + ), + ) + .catch((error: unknown) => { + logLiveActivityWarning("unexpected live activity token registration failure", error); + }); +} + +function registerRemoteActivityToken( + activity: LiveActivity, +): Effect.Effect { + return registerLiveActivityPushToken({ activity }).pipe( + Effect.flatMap((registered) => + Effect.sync(() => { + if (registered && activeActivity?.instance === activity) { + activeActivity = { + ...activeActivity, + remoteTokenRegistered: true, + remoteTokenRetryScheduled: false, + }; + } + return registered; + }), + ), + ); +} + +function scheduleRemoteTokenRegistrationRetry(activity: LiveActivity): void { + if ( + !activeActivity || + activeActivity.instance !== activity || + activeActivity.remoteTokenRegistered || + activeActivity.remoteTokenRetryScheduled + ) { + return; + } + + activeActivity = { + ...activeActivity, + remoteTokenRetryScheduled: true, + }; + + void mobileRuntime + .runPromise( + Effect.sleep(Duration.millis(REMOTE_TOKEN_REGISTRATION_RETRY_MS)).pipe( + Effect.flatMap(() => + enqueueLiveActivitySync( + Effect.sync(() => { + if (!activeActivity || activeActivity.instance !== activity) { + return; + } + activeActivity = { + ...activeActivity, + remoteTokenRetryScheduled: false, + lastRemoteTokenRegistrationAttemptAt: null, + }; + retryRemoteTokenRegistration(activity); + }), + ), + ), + Effect.catch((error) => + Effect.sync(() => { + logLiveActivityWarning("live activity token retry failed", error); + }), + ), + ), + ) + .catch((error: unknown) => { + logLiveActivityWarning("unexpected live activity token retry failure", error); + }); +} + +export function refreshActiveLiveActivityRemoteRegistration(): Effect.Effect< + void, + unknown, + ManagedRelayClient +> { + return enqueueLiveActivitySync( + Effect.gen(function* () { + if (!activeActivity || !canUseLocalLiveActivities()) { + return; + } + const activity = activeActivity.instance; + activeActivity = { + ...activeActivity, + remoteTokenRegistered: false, + remoteTokenRetryScheduled: false, + lastRemoteTokenRegistrationAttemptAt: currentTimeMillis(), + }; + yield* registerRemoteActivityToken(activity).pipe( + Effect.flatMap((registered) => + Effect.sync(() => { + if (!registered) { + scheduleRemoteTokenRegistrationRetry(activity); + } + }), + ), + Effect.catch((error) => + Effect.sync(() => { + logLiveActivityWarning("live activity token refresh failed; retry scheduled", error); + scheduleRemoteTokenRegistrationRetry(activity); + }), + ), + ); + }), + ); +} + +function endActiveActivity( + finalState: AgentAwarenessState | null, + reason: string, +): Effect.Effect { + const active = activeActivity; + if (!active) { + return Effect.void; + } + + activeActivity = null; + logLiveActivityDebug("ending live activity", { + reason, + finalPhase: finalState?.phase ?? null, + }); + if (finalState) { + const now = currentDateTime(); + return runLiveActivityOperation( + "end", + Effect.tryPromise({ + try: () => + active.instance.end( + after( + DateTime.toDateUtc(DateTime.add(now, { milliseconds: FINAL_ACTIVITY_DISMISSAL_MS })), + ), + toActivityProps([finalState]), + DateTime.toDateUtc(now), + ), + catch: (error) => error, + }), + ).pipe(Effect.asVoid); + } + + return runLiveActivityOperation( + "end", + Effect.tryPromise({ + try: () => active.instance.end("immediate"), + catch: (error) => error, + }), + ).pipe(Effect.asVoid); +} + +type LiveActivityOperationResult = + | { + readonly ok: true; + readonly value: T; + } + | { + readonly ok: false; + }; + +function runLiveActivityOperation( + operationName: "start" | "update" | "end", + operation: Effect.Effect, +): Effect.Effect> { + return operation.pipe( + Effect.match({ + onSuccess: (value) => ({ ok: true, value }) as const, + onFailure: (error): LiveActivityOperationResult => { + if ( + (operationName === "end" || operationName === "update") && + isMissingNativeLiveActivityError(error) + ) { + logLiveActivityWarning( + `live activity ${operationName} skipped; native activity was already gone`, + error, + ); + return { ok: false }; + } + + logLiveActivityWarning( + "live activity operation failed; disabling local live activities", + error, + ); + localLiveActivitiesEnabled = false; + activeActivity = null; + environmentStates.clear(); + return { ok: false }; + }, + }), + ); +} + +function isMissingNativeLiveActivityError(error: unknown): boolean { + return error instanceof Error && error.message.includes("Can't find live activity with id:"); +} + +export function __resetAgentLiveActivitiesForTest(): void { + localLiveActivitiesEnabled = true; + activeActivity = null; + environmentStates.clear(); +} diff --git a/apps/mobile/src/features/agent-awareness/liveActivityPreferences.test.ts b/apps/mobile/src/features/agent-awareness/liveActivityPreferences.test.ts new file mode 100644 index 0000000000..da5ce59107 --- /dev/null +++ b/apps/mobile/src/features/agent-awareness/liveActivityPreferences.test.ts @@ -0,0 +1,129 @@ +import { beforeEach, vi } from "vitest"; +import { describe, expect, it } from "@effect/vitest"; +import * as Effect from "effect/Effect"; +import type { EnvironmentId } from "@t3tools/contracts"; +import { ManagedRelayClient } from "@t3tools/client-runtime"; +import { HttpClient } from "effect/unstable/http"; + +import type { SavedRemoteConnection } from "../../lib/connection"; +import { savePreferencesPatch } from "../../lib/storage"; +import { linkEnvironmentToCloud } from "../cloud/linkEnvironment"; +import { endAllAgentLiveActivities } from "./liveActivityController"; +import { setLiveActivityUpdatesEnabled } from "./liveActivityPreferences"; +import { refreshAgentAwarenessRegistration } from "./remoteRegistration"; + +vi.mock("../../lib/storage", () => ({ + savePreferencesPatch: vi.fn(() => Promise.resolve()), +})); + +vi.mock("../cloud/linkEnvironment", () => ({ + linkEnvironmentToCloud: vi.fn(() => Effect.void), +})); + +vi.mock("./liveActivityController", () => ({ + endAllAgentLiveActivities: vi.fn(() => Effect.void), +})); + +vi.mock("./remoteRegistration", () => ({ + refreshAgentAwarenessRegistration: vi.fn(() => Effect.void), +})); + +const connection: SavedRemoteConnection = { + environmentId: "env-1" as EnvironmentId, + environmentLabel: "Desktop", + pairingUrl: "https://desktop.example.test/", + displayUrl: "https://desktop.example.test/", + httpBaseUrl: "https://desktop.example.test/", + wsBaseUrl: "wss://desktop.example.test/ws", + bearerToken: "local-bearer", +}; + +const runWithHttpClient = ( + effect: Effect.Effect, +): Promise => + Effect.runPromise( + effect.pipe( + Effect.provideService(ManagedRelayClient, null as never), + Effect.provideService( + HttpClient.HttpClient, + HttpClient.make(() => Effect.die("unexpected HTTP request")), + ), + ), + ); + +describe("liveActivityPreferences", () => { + beforeEach(() => { + vi.clearAllMocks(); + }); + + it("pushes disabled Live Activity preferences to local and relay registrations", async () => { + await runWithHttpClient( + setLiveActivityUpdatesEnabled({ + enabled: false, + clerkToken: "clerk-token", + connections: [connection], + }), + ); + + expect(savePreferencesPatch).toHaveBeenCalledWith({ liveActivitiesEnabled: false }); + expect(endAllAgentLiveActivities).toHaveBeenCalledTimes(1); + expect(refreshAgentAwarenessRegistration).toHaveBeenCalledTimes(1); + expect(linkEnvironmentToCloud).toHaveBeenCalledWith({ + clerkToken: "clerk-token", + connection, + }); + }); + + it("pushes enabled Live Activity preferences without ending active local activities", async () => { + await runWithHttpClient( + setLiveActivityUpdatesEnabled({ + enabled: true, + clerkToken: "clerk-token", + connections: [connection], + }), + ); + + expect(savePreferencesPatch).toHaveBeenCalledWith({ liveActivitiesEnabled: true }); + expect(endAllAgentLiveActivities).not.toHaveBeenCalled(); + expect(refreshAgentAwarenessRegistration).toHaveBeenCalledTimes(1); + expect(linkEnvironmentToCloud).toHaveBeenCalledWith({ + clerkToken: "clerk-token", + connection, + }); + }); + + it("keeps local preferences refreshable when signed out", async () => { + await runWithHttpClient( + setLiveActivityUpdatesEnabled({ + enabled: false, + clerkToken: null, + connections: [connection], + }), + ); + + expect(savePreferencesPatch).toHaveBeenCalledWith({ liveActivitiesEnabled: false }); + expect(refreshAgentAwarenessRegistration).toHaveBeenCalledTimes(1); + expect(linkEnvironmentToCloud).not.toHaveBeenCalled(); + }); + + it("does not try to re-link managed relay connections without bearer credentials", async () => { + const managedConnection: SavedRemoteConnection = { + ...connection, + bearerToken: null, + }; + + await runWithHttpClient( + setLiveActivityUpdatesEnabled({ + enabled: true, + clerkToken: "clerk-token", + connections: [connection, managedConnection], + }), + ); + + expect(linkEnvironmentToCloud).toHaveBeenCalledTimes(1); + expect(linkEnvironmentToCloud).toHaveBeenCalledWith({ + clerkToken: "clerk-token", + connection, + }); + }); +}); diff --git a/apps/mobile/src/features/agent-awareness/liveActivityPreferences.ts b/apps/mobile/src/features/agent-awareness/liveActivityPreferences.ts new file mode 100644 index 0000000000..fe2a9117be --- /dev/null +++ b/apps/mobile/src/features/agent-awareness/liveActivityPreferences.ts @@ -0,0 +1,39 @@ +import * as Effect from "effect/Effect"; +import { HttpClient } from "effect/unstable/http"; +import { ManagedRelayClient } from "@t3tools/client-runtime"; + +import type { SavedRemoteConnection } from "../../lib/connection"; +import { savePreferencesPatch } from "../../lib/storage"; +import { linkEnvironmentToCloud } from "../cloud/linkEnvironment"; +import { endAllAgentLiveActivities } from "./liveActivityController"; +import { refreshAgentAwarenessRegistration } from "./remoteRegistration"; + +export function setLiveActivityUpdatesEnabled(input: { + readonly enabled: boolean; + readonly clerkToken: string | null; + readonly connections: ReadonlyArray; +}): Effect.Effect { + return Effect.gen(function* () { + yield* Effect.tryPromise({ + try: () => savePreferencesPatch({ liveActivitiesEnabled: input.enabled }), + catch: (error) => error, + }); + + if (!input.enabled) { + yield* endAllAgentLiveActivities(); + } + + yield* refreshAgentAwarenessRegistration(); + + const clerkToken = input.clerkToken; + if (!clerkToken) { + return; + } + + yield* Effect.forEach( + input.connections.filter((connection) => connection.bearerToken !== null), + (connection) => linkEnvironmentToCloud({ clerkToken, connection }), + { concurrency: "unbounded" }, + ); + }); +} diff --git a/apps/mobile/src/features/agent-awareness/notificationNavigation.test.ts b/apps/mobile/src/features/agent-awareness/notificationNavigation.test.ts new file mode 100644 index 0000000000..361641557a --- /dev/null +++ b/apps/mobile/src/features/agent-awareness/notificationNavigation.test.ts @@ -0,0 +1,106 @@ +import { describe, expect, it } from "vitest"; + +import { + extractAgentNotificationDeepLink, + routeAgentNotificationResponseOnce, +} from "./notificationPayload"; + +function responseWithData(data: Record, identifier = "notification-1") { + return { + notification: { + request: { + identifier, + content: { + data, + }, + }, + }, + }; +} + +describe("extractAgentNotificationDeepLink", () => { + it("uses explicit deep links from APNs payload data", () => { + expect( + extractAgentNotificationDeepLink( + responseWithData({ + deepLink: "/threads/env/thread", + environmentId: "ignored", + threadId: "ignored", + }), + ), + ).toBe("/threads/env/thread"); + }); + + it("normalizes explicit thread deep links from APNs payload data", () => { + expect( + extractAgentNotificationDeepLink( + responseWithData({ + deepLink: "/threads/env%201/thread%2F2", + }), + ), + ).toBe("/threads/env%201/thread%2F2"); + }); + + it("falls back to the thread route from environment and thread ids", () => { + expect( + extractAgentNotificationDeepLink( + responseWithData({ + environmentId: "env 1", + threadId: "thread/2", + }), + ), + ).toBe("/threads/env%201/thread%2F2"); + }); + + it("falls back to ids when explicit deep link is not an agent thread route", () => { + expect( + extractAgentNotificationDeepLink( + responseWithData({ + deepLink: "/", + environmentId: "env", + threadId: "thread", + }), + ), + ).toBe("/threads/env/thread"); + }); + + it("ignores malformed or external links", () => { + expect( + extractAgentNotificationDeepLink(responseWithData({ deepLink: "https://example.com" })), + ).toBeNull(); + expect( + extractAgentNotificationDeepLink(responseWithData({ deepLink: "/settings" })), + ).toBeNull(); + expect( + extractAgentNotificationDeepLink(responseWithData({ deepLink: "//example.com" })), + ).toBeNull(); + expect( + extractAgentNotificationDeepLink(responseWithData({ deepLink: "/threads/env/thread?x=1" })), + ).toBeNull(); + expect(extractAgentNotificationDeepLink({})).toBeNull(); + }); +}); + +describe("routeAgentNotificationResponseOnce", () => { + it("does not navigate twice when the initial and listener responses refer to one notification", () => { + const handledResponseIds = new Set(); + const navigations: Array = []; + const response = responseWithData({ + environmentId: "env", + threadId: "thread", + }); + + routeAgentNotificationResponseOnce({ + handledResponseIds, + response, + navigate: (deepLink) => navigations.push(deepLink), + }); + routeAgentNotificationResponseOnce({ + handledResponseIds, + response, + navigate: (deepLink) => navigations.push(deepLink), + }); + + expect(navigations).toEqual(["/threads/env/thread"]); + }); +}); diff --git a/apps/mobile/src/features/agent-awareness/notificationNavigation.ts b/apps/mobile/src/features/agent-awareness/notificationNavigation.ts new file mode 100644 index 0000000000..a702762365 --- /dev/null +++ b/apps/mobile/src/features/agent-awareness/notificationNavigation.ts @@ -0,0 +1,35 @@ +import { useEffect, useRef } from "react"; +import * as Notifications from "expo-notifications"; +import { useRouter } from "expo-router"; + +import { routeAgentNotificationResponseOnce } from "./notificationPayload"; + +export function useAgentNotificationNavigation(): void { + const router = useRouter(); + const handledResponseIds = useRef(new Set()); + + useEffect(() => { + const handleResponse = (response: Notifications.NotificationResponse): void => { + routeAgentNotificationResponseOnce({ + handledResponseIds: handledResponseIds.current, + response, + navigate: (deepLink) => router.push(deepLink as never), + }); + }; + + const subscription = Notifications.addNotificationResponseReceivedListener(handleResponse); + void Notifications.getLastNotificationResponseAsync() + .then((response) => { + if (response) { + handleResponse(response); + return Notifications.clearLastNotificationResponseAsync(); + } + return undefined; + }) + .catch(() => undefined); + + return () => { + subscription.remove(); + }; + }, [router]); +} diff --git a/apps/mobile/src/features/agent-awareness/notificationPayload.ts b/apps/mobile/src/features/agent-awareness/notificationPayload.ts new file mode 100644 index 0000000000..dc72e3d1bd --- /dev/null +++ b/apps/mobile/src/features/agent-awareness/notificationPayload.ts @@ -0,0 +1,106 @@ +function dataFromNotificationResponse(response: unknown): Record | null { + if (typeof response !== "object" || response === null) { + return null; + } + const notification = (response as { readonly notification?: unknown }).notification; + if (typeof notification !== "object" || notification === null) { + return null; + } + const request = (notification as { readonly request?: unknown }).request; + if (typeof request !== "object" || request === null) { + return null; + } + const content = (request as { readonly content?: unknown }).content; + if (typeof content !== "object" || content === null) { + return null; + } + const data = (content as { readonly data?: unknown }).data; + return typeof data === "object" && data !== null ? (data as Record) : null; +} + +function identifierFromNotificationResponse(response: unknown): string | null { + if (typeof response !== "object" || response === null) { + return null; + } + const notification = (response as { readonly notification?: unknown }).notification; + if (typeof notification !== "object" || notification === null) { + return null; + } + const request = (notification as { readonly request?: unknown }).request; + if (typeof request !== "object" || request === null) { + return null; + } + const identifier = (request as { readonly identifier?: unknown }).identifier; + return typeof identifier === "string" ? identifier : null; +} + +function encodeThreadDeepLink(input: { + readonly environmentId: string; + readonly threadId: string; +}): string | null { + if (input.environmentId.length === 0 || input.threadId.length === 0) { + return null; + } + return `/threads/${encodeURIComponent(input.environmentId)}/${encodeURIComponent(input.threadId)}`; +} + +function normalizeThreadDeepLink(value: string): string | null { + if ( + value.trim() !== value || + value.startsWith("//") || + value.includes("?") || + value.includes("#") + ) { + return null; + } + + const parts = value.split("/"); + if (parts.length !== 4 || parts[0] !== "" || parts[1] !== "threads") { + return null; + } + + try { + return encodeThreadDeepLink({ + environmentId: decodeURIComponent(parts[2] ?? ""), + threadId: decodeURIComponent(parts[3] ?? ""), + }); + } catch { + return null; + } +} + +export function extractAgentNotificationDeepLink(response: unknown): string | null { + const data = dataFromNotificationResponse(response); + const deepLink = data?.deepLink; + if (typeof deepLink === "string") { + const normalizedDeepLink = normalizeThreadDeepLink(deepLink); + if (normalizedDeepLink) { + return normalizedDeepLink; + } + } + + const environmentId = data?.environmentId; + const threadId = data?.threadId; + if (typeof environmentId === "string" && typeof threadId === "string") { + return encodeThreadDeepLink({ environmentId, threadId }); + } + return null; +} + +export function routeAgentNotificationResponseOnce(input: { + readonly handledResponseIds: Set; + readonly response: unknown; + readonly navigate: (deepLink: string) => void; +}): void { + const responseId = identifierFromNotificationResponse(input.response); + if (responseId && input.handledResponseIds.has(responseId)) { + return; + } + if (responseId) { + input.handledResponseIds.add(responseId); + } + const deepLink = extractAgentNotificationDeepLink(input.response); + if (deepLink) { + input.navigate(deepLink); + } +} diff --git a/apps/mobile/src/features/agent-awareness/notificationPermissions.ts b/apps/mobile/src/features/agent-awareness/notificationPermissions.ts new file mode 100644 index 0000000000..ce8dfddf3d --- /dev/null +++ b/apps/mobile/src/features/agent-awareness/notificationPermissions.ts @@ -0,0 +1,44 @@ +import * as Notifications from "expo-notifications"; +import * as Effect from "effect/Effect"; +import { Platform } from "react-native"; + +export type NotificationPermissionResult = + | { readonly type: "unsupported" } + | { readonly type: "granted" } + | { readonly type: "denied"; readonly canAskAgain: boolean }; + +export const requestAgentNotificationPermission: Effect.Effect< + NotificationPermissionResult, + unknown +> = Effect.gen(function* () { + if (Platform.OS !== "ios") { + return { type: "unsupported" }; + } + + const existing = yield* Effect.tryPromise({ + try: () => Notifications.getPermissionsAsync(), + catch: (error) => error, + }); + if (existing.granted) { + return { type: "granted" }; + } + + if (!existing.canAskAgain) { + return { type: "denied", canAskAgain: false }; + } + + const requested = yield* Effect.tryPromise({ + try: () => + Notifications.requestPermissionsAsync({ + ios: { + allowAlert: true, + allowBadge: true, + allowSound: true, + }, + }), + catch: (error) => error, + }); + return requested.granted + ? { type: "granted" } + : { type: "denied", canAskAgain: requested.canAskAgain }; +}); diff --git a/apps/mobile/src/features/agent-awareness/registrationPayload.ts b/apps/mobile/src/features/agent-awareness/registrationPayload.ts new file mode 100644 index 0000000000..b0d29b877e --- /dev/null +++ b/apps/mobile/src/features/agent-awareness/registrationPayload.ts @@ -0,0 +1,31 @@ +import type { RelayDeviceRegistrationRequest } from "@t3tools/contracts/relay"; + +import type { MobilePreferences } from "../../lib/storage"; + +export function makeRelayDeviceRegistrationRequest(input: { + readonly deviceId: string; + readonly iosMajorVersion: number; + readonly appVersion?: string; + readonly pushToken?: string; + readonly pushToStartToken?: string; + readonly notificationsEnabled: boolean; + readonly preferences: MobilePreferences; +}): RelayDeviceRegistrationRequest { + const liveActivitiesEnabled = input.preferences.liveActivitiesEnabled !== false; + return { + deviceId: input.deviceId, + platform: "ios", + iosMajorVersion: input.iosMajorVersion, + appVersion: input.appVersion, + ...(input.pushToken ? { pushToken: input.pushToken } : {}), + ...(input.pushToStartToken ? { pushToStartToken: input.pushToStartToken } : {}), + preferences: { + liveActivitiesEnabled, + notificationsEnabled: input.notificationsEnabled, + notifyOnApproval: true, + notifyOnInput: true, + notifyOnCompletion: true, + notifyOnFailure: true, + }, + }; +} diff --git a/apps/mobile/src/features/agent-awareness/remoteRegistration.test.ts b/apps/mobile/src/features/agent-awareness/remoteRegistration.test.ts new file mode 100644 index 0000000000..b3c04bd616 --- /dev/null +++ b/apps/mobile/src/features/agent-awareness/remoteRegistration.test.ts @@ -0,0 +1,409 @@ +/// + +import * as NodeCrypto from "node:crypto"; + +import { beforeEach, vi } from "vitest"; +import { describe, expect, it } from "@effect/vitest"; +import Constants from "expo-constants"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import { FetchHttpClient } from "effect/unstable/http"; +import type { ManagedRelayClient } from "@t3tools/client-runtime"; + +import type { EnvironmentId } from "@t3tools/contracts"; +import { verifyDpopProof } from "@t3tools/shared/dpop"; +import type { SavedRemoteConnection } from "../../lib/connection"; +import { mobileCryptoLayer } from "../cloud/dpop"; +import { mobileManagedRelayClientLayer } from "../cloud/managedRelayLayer"; +import { makeRelayDeviceRegistrationRequest } from "./registrationPayload"; +import { + __resetAgentAwarenessRemoteRegistrationForTest, + refreshAgentAwarenessRegistration, + normalizeAgentAwarenessRelayBaseUrl, + registerAgentAwarenessConnection, + registerLiveActivityPushToken, + setAgentAwarenessRelayTokenProvider, + shouldRegisterAgentAwarenessDeviceForProvider, + unregisterAgentAwarenessConnection, +} from "./remoteRegistration"; +import * as Notifications from "expo-notifications"; + +const secureStore = vi.hoisted(() => new Map()); + +vi.mock("expo-constants", () => ({ + default: { + expoConfig: { + version: "1.0.0", + extra: {}, + }, + }, +})); + +vi.mock("expo-widgets", () => ({ + addPushToStartTokenListener: vi.fn(() => ({ remove: vi.fn() })), +})); + +vi.mock("expo-notifications", () => ({ + addPushTokenListener: vi.fn(() => ({ remove: vi.fn() })), + getDevicePushTokenAsync: vi.fn(() => Promise.resolve({ type: "ios", data: "apns-token" })), + getPermissionsAsync: vi.fn(() => Promise.resolve({ granted: true })), +})); + +vi.mock("expo-crypto", () => ({ + CryptoDigestAlgorithm: { + SHA1: "SHA-1", + SHA256: "SHA-256", + SHA384: "SHA-384", + SHA512: "SHA-512", + }, + getRandomBytes: (byteCount: number) => new Uint8Array(NodeCrypto.randomBytes(byteCount)), + getRandomBytesAsync: (byteCount: number) => + Promise.resolve(new Uint8Array(NodeCrypto.randomBytes(byteCount))), + digest: (algorithm: string, data: unknown) => { + if (!(data instanceof Uint8Array)) { + return Promise.reject(new TypeError("expo-crypto digest data must be a typed array.")); + } + return Promise.resolve( + new Uint8Array(NodeCrypto.createHash(algorithm).update(data).digest()).buffer, + ); + }, +})); + +vi.mock("expo-secure-store", () => ({ + getItemAsync: (key: string) => Promise.resolve(secureStore.get(key) ?? null), + setItemAsync: (key: string, value: string) => { + secureStore.set(key, value); + return Promise.resolve(); + }, +})); + +vi.mock("react-native", () => ({ + Platform: { + OS: "ios", + Version: "18.0", + }, +})); + +vi.mock("../../lib/runtime", () => ({ + mobileRuntime: { + runPromise: (operation: Effect.Effect) => + Effect.runPromise( + operation.pipe( + Effect.provide( + mobileManagedRelayClientLayer("https://relay.example.test").pipe( + Layer.provide(Layer.mergeAll(FetchHttpClient.layer, mobileCryptoLayer)), + ), + ), + ), + ), + }, +})); + +vi.mock("../../lib/storage", () => ({ + loadAgentAwarenessDeviceId: vi.fn(() => Promise.resolve("device-1")), + loadOrCreateAgentAwarenessDeviceId: vi.fn(() => Promise.resolve("device-1")), + loadPreferences: vi.fn(() => Promise.resolve({})), +})); + +function proofIat(proof: string): number { + const payload = proof.split(".")[1]; + if (!payload) { + throw new Error("Missing DPoP payload."); + } + const decoded = JSON.parse(Buffer.from(payload, "base64url").toString("utf8")) as { + readonly iat: number; + }; + return decoded.iat; +} + +function savedConnection(): SavedRemoteConnection { + return { + environmentId: "env-1" as EnvironmentId, + environmentLabel: "Desktop", + pairingUrl: "https://desktop.example/pair", + displayUrl: "https://desktop.example", + httpBaseUrl: "https://desktop.example", + wsBaseUrl: "wss://desktop.example/ws", + bearerToken: "bearer-token", + }; +} + +const runRegistrationEffect = (effect: Effect.Effect): Promise => + Effect.runPromise( + effect.pipe( + Effect.provide( + mobileManagedRelayClientLayer("https://relay.example.test").pipe( + Layer.provide(Layer.mergeAll(FetchHttpClient.layer, mobileCryptoLayer)), + ), + ), + ), + ); + +async function waitForFetchCalls( + fetchMock: ReturnType, + count: number, +): Promise { + for (let attempt = 0; attempt < 20; attempt += 1) { + if (fetchMock.mock.calls.length >= count) { + return; + } + await new Promise((resolve) => setTimeout(resolve, 0)); + } +} + +describe("makeRelayDeviceRegistrationRequest", () => { + beforeEach(() => { + vi.unstubAllGlobals(); + vi.stubGlobal("__DEV__", false); + secureStore.clear(); + Constants.expoConfig!.extra = {}; + __resetAgentAwarenessRemoteRegistrationForTest(); + }); + + it("preserves disabled Live Activity preferences in relay registrations", () => { + expect( + makeRelayDeviceRegistrationRequest({ + deviceId: "device-1", + iosMajorVersion: 18, + appVersion: "1.0.0", + pushToken: "apns-token", + pushToStartToken: "push-to-start-token", + notificationsEnabled: true, + preferences: { + liveActivitiesEnabled: false, + }, + }), + ).toEqual({ + deviceId: "device-1", + platform: "ios", + iosMajorVersion: 18, + appVersion: "1.0.0", + pushToken: "apns-token", + pushToStartToken: "push-to-start-token", + preferences: { + liveActivitiesEnabled: false, + notificationsEnabled: true, + notifyOnApproval: true, + notifyOnInput: true, + notifyOnCompletion: true, + notifyOnFailure: true, + }, + }); + }); + + it("marks notification delivery disabled when APNs permission is unavailable", () => { + expect( + makeRelayDeviceRegistrationRequest({ + deviceId: "device-1", + iosMajorVersion: 18, + appVersion: "1.0.0", + pushToStartToken: "push-to-start-token", + notificationsEnabled: false, + preferences: { + liveActivitiesEnabled: true, + }, + }), + ).toEqual({ + deviceId: "device-1", + platform: "ios", + iosMajorVersion: 18, + appVersion: "1.0.0", + pushToStartToken: "push-to-start-token", + preferences: { + liveActivitiesEnabled: true, + notificationsEnabled: false, + notifyOnApproval: true, + notifyOnInput: true, + notifyOnCompletion: true, + notifyOnFailure: true, + }, + }); + }); + + it("normalizes relay base URLs for APNs registration requests", () => { + expect(normalizeAgentAwarenessRelayBaseUrl(" https://relay.example.test/// ")).toBe( + "https://relay.example.test", + ); + expect(normalizeAgentAwarenessRelayBaseUrl(" ")).toBeNull(); + }); + + it("registers at most one listener while a Live Activity push token is pending", async () => { + registerAgentAwarenessConnection(savedConnection()); + const addPushTokenListener = vi.fn(); + const activity = { + getPushToken: vi.fn(() => Promise.resolve(null)), + addPushTokenListener, + }; + + await expect( + runRegistrationEffect(registerLiveActivityPushToken({ activity: activity as never })), + ).resolves.toBe(false); + await expect( + runRegistrationEffect(registerLiveActivityPushToken({ activity: activity as never })), + ).resolves.toBe(false); + + expect(activity.getPushToken).toHaveBeenCalledTimes(2); + expect(addPushTokenListener).toHaveBeenCalledTimes(1); + }); + + it("reports Live Activity token registration as skipped when relay auth is unavailable", async () => { + registerAgentAwarenessConnection(savedConnection()); + const activity = { + getPushToken: vi.fn(() => Promise.resolve("activity-token")), + addPushTokenListener: vi.fn(), + }; + + await expect( + runRegistrationEffect(registerLiveActivityPushToken({ activity: activity as never })), + ).resolves.toBe(false); + }); + + it("refreshes APNs registration for connected environments after settings changes", async () => { + registerAgentAwarenessConnection(savedConnection()); + await new Promise((resolve) => setTimeout(resolve, 0)); + vi.mocked(Notifications.getDevicePushTokenAsync).mockClear(); + + await runRegistrationEffect(refreshAgentAwarenessRegistration()); + + expect(Notifications.getDevicePushTokenAsync).toHaveBeenCalledTimes(1); + }); + + it.effect("registers the APNs device when cloud auth becomes available", () => { + const fetchMock = vi.fn((request: RequestInfo | URL) => { + const url = request instanceof Request ? request.url : String(request); + return Promise.resolve( + Response.json( + url.endsWith("/v1/client/dpop-token") + ? { + access_token: "relay-dpop-token", + issued_token_type: "urn:ietf:params:oauth:token-type:access_token", + token_type: "DPoP", + expires_in: 300, + scope: "mobile:registration", + } + : { ok: true }, + ), + ); + }); + vi.stubGlobal("fetch", fetchMock); + Constants.expoConfig!.extra = { + relay: { + url: "https://relay.example.test/", + }, + }; + + setAgentAwarenessRelayTokenProvider(() => Promise.resolve("clerk-token-user-a")); + + return Effect.gen(function* () { + yield* Effect.promise(() => waitForFetchCalls(fetchMock, 2)); + + expect(fetchMock).toHaveBeenCalledTimes(2); + const [request, init] = fetchMock.mock.calls[1] as unknown as [ + unknown, + RequestInit | undefined, + ]; + const url = request instanceof Request ? request.url : String(request); + const method = request instanceof Request ? request.method : init?.method; + const headers = request instanceof Request ? request.headers : new Headers(init?.headers); + const dpop = headers.get("dpop"); + expect(url).toBe("https://relay.example.test/v1/mobile/devices"); + expect(method).toBe("POST"); + expect(headers.get("authorization")).toBe("DPoP relay-dpop-token"); + expect(dpop).toEqual(expect.any(String)); + if (!dpop) { + throw new Error("Missing DPoP header."); + } + expect( + verifyDpopProof({ + proof: dpop, + method: "POST", + url: "https://relay.example.test/v1/mobile/devices", + expectedAccessToken: "relay-dpop-token", + nowEpochSeconds: proofIat(dpop), + }), + ).toMatchObject({ ok: true }); + }); + }); + + it("only registers again when the authenticated identity changes", () => { + expect(shouldRegisterAgentAwarenessDeviceForProvider(null, "user-a")).toBe(true); + expect(shouldRegisterAgentAwarenessDeviceForProvider("user-a", "user-a")).toBe(false); + expect(shouldRegisterAgentAwarenessDeviceForProvider("user-a", "user-b")).toBe(true); + expect(shouldRegisterAgentAwarenessDeviceForProvider("user-a", undefined)).toBe(true); + }); + + it("registers rotated APNs tokens without rereading the native token", async () => { + const fetchMock = vi.fn((request: RequestInfo | URL) => { + const url = request instanceof Request ? request.url : String(request); + return Promise.resolve( + Response.json( + url.endsWith("/v1/client/dpop-token") + ? { + access_token: "relay-dpop-token", + issued_token_type: "urn:ietf:params:oauth:token-type:access_token", + token_type: "DPoP", + expires_in: 300, + scope: "mobile:registration", + } + : { ok: true }, + ), + ); + }); + vi.stubGlobal("fetch", fetchMock); + Constants.expoConfig!.extra = { + relay: { + url: "https://relay.example.test/", + }, + }; + + vi.mocked(Notifications.getDevicePushTokenAsync).mockClear(); + setAgentAwarenessRelayTokenProvider(() => Promise.resolve("clerk-token-user-a")); + + const tokenListener = vi.mocked(Notifications.addPushTokenListener).mock.calls.at(-1)?.[0]; + expect(tokenListener).toBeDefined(); + tokenListener?.({ type: "ios", data: "rotated-apns-token" } as never); + + await new Promise((resolve) => setTimeout(resolve, 0)); + + expect(Notifications.getDevicePushTokenAsync).toHaveBeenCalledTimes(1); + }); + + it.effect( + "keeps the user-scoped relay APNs device when an environment connection is removed", + () => { + const fetchMock = vi.fn((request: RequestInfo | URL) => { + const url = request instanceof Request ? request.url : String(request); + return Promise.resolve( + Response.json( + url.endsWith("/v1/client/dpop-token") + ? { + access_token: "relay-dpop-token", + issued_token_type: "urn:ietf:params:oauth:token-type:access_token", + token_type: "DPoP", + expires_in: 300, + scope: "mobile:registration", + } + : { ok: true }, + ), + ); + }); + vi.stubGlobal("fetch", fetchMock); + Constants.expoConfig!.extra = { + relay: { + url: "https://relay.example.test/", + }, + }; + + registerAgentAwarenessConnection(savedConnection()); + setAgentAwarenessRelayTokenProvider(() => Promise.resolve("clerk-token-user-a")); + return Effect.gen(function* () { + yield* Effect.promise(() => waitForFetchCalls(fetchMock, 2)); + fetchMock.mockClear(); + + unregisterAgentAwarenessConnection(savedConnection().environmentId); + + expect(fetchMock).not.toHaveBeenCalled(); + }); + }, + ); +}); diff --git a/apps/mobile/src/features/agent-awareness/remoteRegistration.ts b/apps/mobile/src/features/agent-awareness/remoteRegistration.ts new file mode 100644 index 0000000000..14bf87af66 --- /dev/null +++ b/apps/mobile/src/features/agent-awareness/remoteRegistration.ts @@ -0,0 +1,448 @@ +import { addPushToStartTokenListener, type LiveActivity } from "expo-widgets"; +import Constants from "expo-constants"; +import * as Notifications from "expo-notifications"; +import * as Effect from "effect/Effect"; +import { Platform } from "react-native"; +import type { EnvironmentId } from "@t3tools/contracts"; +import { + type RelayDeviceRegistrationRequest, + type RelayLiveActivityRegistrationRequest, +} from "@t3tools/contracts/relay"; +import { ManagedRelayClient } from "@t3tools/client-runtime"; + +import type { SavedRemoteConnection } from "../../lib/connection"; +import { mobileRuntime } from "../../lib/runtime"; +import { + loadAgentAwarenessDeviceId, + loadOrCreateAgentAwarenessDeviceId, + loadPreferences, +} from "../../lib/storage"; +import type { AgentActivityProps } from "../../widgets/AgentActivity"; +import { makeRelayDeviceRegistrationRequest } from "./registrationPayload"; + +const environmentConnections = new Map(); +const activityPushTokenListeners = new WeakSet>(); +let pushToStartSubscription: { remove: () => void } | null = null; +let pushTokenSubscription: { remove: () => void } | null = null; +let relayTokenProvider: (() => Promise) | null = null; +let relayTokenProviderIdentity: string | null = null; + +export function normalizeAgentAwarenessRelayBaseUrl( + value: string | null | undefined, +): string | null { + const trimmed = value?.trim(); + if (!trimmed) { + return null; + } + return trimmed.replace(/\/+$/g, ""); +} + +function readRelayConfig(): { readonly url: string } | null { + const relayConfig = Constants.expoConfig?.extra?.relay as + | { readonly url?: string | null } + | undefined; + const relayUrl = normalizeAgentAwarenessRelayBaseUrl(relayConfig?.url); + if (!relayUrl) { + logRegistrationDebug("relay registration skipped; relay config missing"); + return null; + } + + return { url: relayUrl }; +} + +function canRegisterRemoteLiveActivities(): boolean { + return Platform.OS === "ios"; +} + +export function shouldRegisterAgentAwarenessDeviceForProvider( + previousIdentity: string | null, + identity: string | undefined, +): boolean { + return identity === undefined || identity !== previousIdentity; +} + +export function setAgentAwarenessRelayTokenProvider( + provider: (() => Promise) | null, + identity?: string, +): void { + const isExistingIdentity = + provider !== null && + !shouldRegisterAgentAwarenessDeviceForProvider(relayTokenProviderIdentity, identity); + relayTokenProvider = provider; + relayTokenProviderIdentity = provider ? (identity ?? null) : null; + if (!provider) { + pushToStartSubscription?.remove(); + pushToStartSubscription = null; + pushTokenSubscription?.remove(); + pushTokenSubscription = null; + return; + } + ensurePushToStartListener(); + ensurePushTokenListener(); + if (isExistingIdentity) { + return; + } + runRegistrationInBackground(registerDevice(), "device registration after cloud sign-in failed"); +} + +function iosMajorVersion(): number { + const version = Platform.Version; + if (typeof version === "number") { + return Math.floor(version); + } + const major = Number.parseInt(version.split(".")[0] ?? "", 10); + return Number.isFinite(major) ? major : 18; +} + +function nativePushTokenRegistration(observedPushToken?: string) { + return Effect.gen(function* () { + if (!canRegisterRemoteLiveActivities()) { + return { notificationsEnabled: false, pushToken: null }; + } + if (observedPushToken) { + return { notificationsEnabled: true, pushToken: observedPushToken }; + } + const permissions = yield* Effect.tryPromise({ + try: () => Notifications.getPermissionsAsync(), + catch: (error) => error, + }); + if (!permissions.granted) { + return { notificationsEnabled: false, pushToken: null }; + } + const token = yield* Effect.tryPromise({ + try: () => Notifications.getDevicePushTokenAsync(), + catch: (error) => error, + }).pipe( + Effect.tapError((error) => + Effect.sync(() => { + logRegistrationError("native APNs token lookup failed", error); + }), + ), + Effect.orElseSucceed(() => null), + ); + const pushToken = + token?.type === "ios" && typeof token.data === "string" && token.data.trim().length > 0 + ? token.data.trim() + : null; + return { notificationsEnabled: pushToken !== null, pushToken }; + }); +} + +const relayToken = Effect.gen(function* () { + const provider = relayTokenProvider; + if (!provider) { + return null; + } + return yield* Effect.tryPromise({ + try: provider, + catch: (error) => error, + }); +}); + +function registerDeviceWithRelay( + body: RelayDeviceRegistrationRequest, +): Effect.Effect { + return Effect.gen(function* () { + if (!readRelayConfig()) return; + const token = yield* relayToken; + if (!token) { + logRegistrationDebug("relay device registration skipped; user is not signed in"); + return; + } + + const client = yield* ManagedRelayClient; + yield* client.registerDevice({ + clerkToken: token, + payload: body, + }); + }); +} + +function unregisterDeviceWithRelay(input: { + readonly deviceId: string; + readonly tokenProvider: () => Promise; +}): Effect.Effect { + return Effect.gen(function* () { + if (!readRelayConfig()) return; + const token = yield* Effect.tryPromise({ + try: input.tokenProvider, + catch: (error) => error, + }); + if (!token) { + logRegistrationDebug("relay device unregistration skipped; user is not signed in"); + return; + } + + const client = yield* ManagedRelayClient; + yield* client.unregisterDevice({ + clerkToken: token, + deviceId: input.deviceId, + }); + }); +} + +function registerLiveActivityWithRelay( + body: RelayLiveActivityRegistrationRequest, +): Effect.Effect { + return Effect.gen(function* () { + if (!readRelayConfig()) return false; + const token = yield* relayToken; + if (!token) { + logRegistrationDebug("relay live activity registration skipped; user is not signed in"); + return false; + } + + const client = yield* ManagedRelayClient; + yield* client.registerLiveActivity({ + clerkToken: token, + payload: body, + }); + return true; + }); +} + +function logRegistrationError(context: string, error: unknown): void { + if (!__DEV__) { + return; + } + console.warn( + `[agent-awareness] ${context}`, + error instanceof Error ? error.message : String(error), + ); +} + +function logRegistrationDebug(context: string, details?: unknown): void { + if (!__DEV__) { + return; + } + console.log(`[agent-awareness] ${context}`, details ?? ""); +} + +function runRegistrationInBackground( + operation: Effect.Effect, + context: string, +): void { + void mobileRuntime.runPromise(operation).catch((error: unknown) => { + logRegistrationError(context, error); + }); +} + +function registerDevice(input?: { + readonly pushToStartToken?: string; + readonly observedPushToken?: string; +}): Effect.Effect { + return Effect.gen(function* () { + if (!canRegisterRemoteLiveActivities()) { + return; + } + + const [deviceId, preferences] = yield* Effect.all([ + Effect.tryPromise({ + try: () => loadOrCreateAgentAwarenessDeviceId(), + catch: (error) => error, + }), + Effect.tryPromise({ + try: () => loadPreferences(), + catch: (error) => error, + }), + ]); + const pushTokenRegistration = yield* nativePushTokenRegistration(input?.observedPushToken); + yield* registerDeviceWithRelay( + makeRelayDeviceRegistrationRequest({ + deviceId, + iosMajorVersion: iosMajorVersion(), + appVersion: Constants.expoConfig?.version, + ...(pushTokenRegistration.pushToken ? { pushToken: pushTokenRegistration.pushToken } : {}), + ...(input?.pushToStartToken ? { pushToStartToken: input.pushToStartToken } : {}), + notificationsEnabled: pushTokenRegistration.notificationsEnabled, + preferences, + }), + ); + }); +} + +function registerDeviceForCurrentUser( + pushToStartToken?: string, +): Effect.Effect { + return registerDevice(pushToStartToken ? { pushToStartToken } : undefined); +} + +function registerPushToStartTokenForCurrentUser(pushToStartToken: string): void { + runRegistrationInBackground( + registerDeviceForCurrentUser(pushToStartToken), + "push-to-start token registration failed", + ); +} + +function ensurePushToStartListener(): void { + if (pushToStartSubscription || !canRegisterRemoteLiveActivities()) { + return; + } + + pushToStartSubscription = addPushToStartTokenListener((event) => { + const token = event.activityPushToStartToken; + if (token) { + registerPushToStartTokenForCurrentUser(token); + } + }); +} + +function ensurePushTokenListener(): void { + if (pushTokenSubscription || !canRegisterRemoteLiveActivities()) { + return; + } + + pushTokenSubscription = Notifications.addPushTokenListener((token) => { + if (token.type === "ios" && typeof token.data === "string" && token.data.trim().length > 0) { + runRegistrationInBackground( + registerDevice({ observedPushToken: token.data.trim() }), + "native APNs token rotation registration failed", + ); + } + }); +} + +export function registerAgentAwarenessConnection(connection: SavedRemoteConnection): void { + if (!canRegisterRemoteLiveActivities()) { + return; + } + + environmentConnections.set(connection.environmentId, connection); + ensurePushToStartListener(); + ensurePushTokenListener(); + runRegistrationInBackground(registerDevice(), "device registration failed"); +} + +function removeAgentAwarenessConnection(environmentId: EnvironmentId): void { + environmentConnections.delete(environmentId); +} + +export function unregisterAgentAwarenessConnection(environmentId: EnvironmentId): void { + removeAgentAwarenessConnection(environmentId); +} + +export function unregisterAllAgentAwarenessConnections(): void { + environmentConnections.clear(); + pushToStartSubscription?.remove(); + pushToStartSubscription = null; + pushTokenSubscription?.remove(); + pushTokenSubscription = null; +} + +export function refreshAgentAwarenessRegistration(): Effect.Effect< + void, + never, + ManagedRelayClient +> { + return registerDeviceForCurrentUser().pipe( + Effect.catch((error) => + Effect.sync(() => { + logRegistrationError("device registration refresh failed", error); + }), + ), + ); +} + +export function __resetAgentAwarenessRemoteRegistrationForTest(): void { + environmentConnections.clear(); + pushToStartSubscription?.remove(); + pushToStartSubscription = null; + pushTokenSubscription?.remove(); + pushTokenSubscription = null; + relayTokenProvider = null; + relayTokenProviderIdentity = null; +} + +export function unregisterAgentAwarenessDeviceForCurrentUser( + tokenProvider: () => Promise, +): Effect.Effect { + return Effect.gen(function* () { + const deviceId = yield* Effect.tryPromise({ + try: () => loadAgentAwarenessDeviceId(), + catch: (error) => error, + }); + if (!deviceId) { + return; + } + yield* unregisterDeviceWithRelay({ deviceId, tokenProvider }); + }).pipe( + Effect.catch((error) => + Effect.sync(() => { + logRegistrationError("device unregistration failed", error); + }), + ), + ); +} + +export function registerLiveActivityPushToken(input: { + readonly activity: LiveActivity; +}): Effect.Effect { + return Effect.gen(function* () { + if (!canRegisterRemoteLiveActivities()) { + return false; + } + + const activityPushToken = yield* Effect.tryPromise({ + try: () => input.activity.getPushToken(), + catch: (error) => error, + }); + if (!activityPushToken) { + if (activityPushTokenListeners.has(input.activity)) { + logRegistrationDebug( + "live activity push token not available yet; token listener already registered", + { + connectionCount: environmentConnections.size, + }, + ); + return false; + } + + logRegistrationDebug( + "live activity push token not available yet; listening for token event", + { + connectionCount: environmentConnections.size, + }, + ); + activityPushTokenListeners.add(input.activity); + input.activity.addPushTokenListener((event) => { + if (event.pushToken) { + logRegistrationDebug("live activity push token event received", { + tokenSuffix: event.pushToken.slice(-8), + }); + runRegistrationInBackground( + registerLiveActivityPushTokenValue({ + activityPushToken: event.pushToken, + }), + "live activity token listener registration failed", + ); + } + }); + return false; + } + + return yield* registerLiveActivityPushTokenValue({ + activityPushToken, + }); + }); +} + +function registerLiveActivityPushTokenValue(input: { + readonly activityPushToken: string; +}): Effect.Effect { + return Effect.gen(function* () { + const deviceId = yield* Effect.tryPromise({ + try: () => loadOrCreateAgentAwarenessDeviceId(), + catch: (error) => error, + }); + const registered = yield* registerLiveActivityWithRelay({ + deviceId, + activityPushToken: input.activityPushToken, + }); + if (registered) { + logRegistrationDebug("live activity push token registered", { + tokenSuffix: input.activityPushToken.slice(-8), + }); + } + return registered; + }); +} diff --git a/apps/mobile/src/features/agent-awareness/shellLiveActivitySync.ts b/apps/mobile/src/features/agent-awareness/shellLiveActivitySync.ts new file mode 100644 index 0000000000..44c720d0e7 --- /dev/null +++ b/apps/mobile/src/features/agent-awareness/shellLiveActivitySync.ts @@ -0,0 +1,59 @@ +import { shellSnapshotStateAtom } from "@t3tools/client-runtime"; +import type { EnvironmentId } from "@t3tools/contracts"; + +import type { SavedRemoteConnection } from "../../lib/connection"; +import { mobileRuntime } from "../../lib/runtime"; +import { appAtomRegistry } from "../../state/atom-registry"; +import { + endAllAgentLiveActivities, + endEnvironmentLiveActivities, + syncAgentLiveActivitiesForSnapshot, +} from "./liveActivityController"; +import { + registerAgentAwarenessConnection, + unregisterAgentAwarenessConnection, + unregisterAllAgentAwarenessConnections, +} from "./remoteRegistration"; + +const environmentUnsubscribers = new Map void>(); + +export function startAgentAwarenessForEnvironment(connection: SavedRemoteConnection): void { + const { environmentId } = connection; + if (environmentUnsubscribers.has(environmentId)) { + return; + } + + registerAgentAwarenessConnection(connection); + + const sync = () => { + const state = appAtomRegistry.get(shellSnapshotStateAtom(environmentId)); + void mobileRuntime + .runPromise( + syncAgentLiveActivitiesForSnapshot({ + environmentId, + snapshot: state.data, + }), + ) + .catch(() => undefined); + }; + + const unsubscribe = appAtomRegistry.subscribe(shellSnapshotStateAtom(environmentId), sync); + environmentUnsubscribers.set(environmentId, unsubscribe); + sync(); +} + +export function stopAgentAwarenessForEnvironment(environmentId: EnvironmentId): void { + environmentUnsubscribers.get(environmentId)?.(); + environmentUnsubscribers.delete(environmentId); + unregisterAgentAwarenessConnection(environmentId); + void mobileRuntime.runPromise(endEnvironmentLiveActivities(environmentId)).catch(() => undefined); +} + +export function stopAllAgentAwareness(): void { + for (const unsubscribe of environmentUnsubscribers.values()) { + unsubscribe(); + } + environmentUnsubscribers.clear(); + unregisterAllAgentAwarenessConnections(); + void mobileRuntime.runPromise(endAllAgentLiveActivities()).catch(() => undefined); +} diff --git a/apps/mobile/src/features/agent-awareness/updatedAtLabel.test.ts b/apps/mobile/src/features/agent-awareness/updatedAtLabel.test.ts new file mode 100644 index 0000000000..25d234e451 --- /dev/null +++ b/apps/mobile/src/features/agent-awareness/updatedAtLabel.test.ts @@ -0,0 +1,16 @@ +import { describe, expect, it } from "@effect/vitest"; + +import { formatAgentActivityUpdatedAtLabel } from "./updatedAtLabel"; + +describe("formatAgentActivityUpdatedAtLabel", () => { + it("formats ISO timestamps without using ambient time APIs", () => { + expect(formatAgentActivityUpdatedAtLabel("2026-05-25T00:03:00.000Z")).toBe("12:03"); + expect(formatAgentActivityUpdatedAtLabel("2026-05-25T09:45:00.000Z")).toBe("9:45"); + expect(formatAgentActivityUpdatedAtLabel("2026-05-25T13:07:00.000Z")).toBe("1:07"); + }); + + it("uses now for malformed timestamps", () => { + expect(formatAgentActivityUpdatedAtLabel("not-a-date")).toBe("now"); + expect(formatAgentActivityUpdatedAtLabel("2026-05-25T24:00:00.000Z")).toBe("now"); + }); +}); diff --git a/apps/mobile/src/features/agent-awareness/updatedAtLabel.ts b/apps/mobile/src/features/agent-awareness/updatedAtLabel.ts new file mode 100644 index 0000000000..c721c98f4f --- /dev/null +++ b/apps/mobile/src/features/agent-awareness/updatedAtLabel.ts @@ -0,0 +1,12 @@ +const ISO_TIME_PATTERN = /^\d{4}-\d{2}-\d{2}T(?\d{2}):(?\d{2}):/; + +export function formatAgentActivityUpdatedAtLabel(updatedAt: string): string { + const match = ISO_TIME_PATTERN.exec(updatedAt); + const hours24 = Number(match?.groups?.hours); + const minutes = match?.groups?.minutes; + if (!Number.isInteger(hours24) || hours24 < 0 || hours24 > 23 || !minutes) { + return "now"; + } + + return `${hours24 % 12 || 12}:${minutes}`; +} diff --git a/apps/mobile/src/features/cloud/CloudAuthProvider.tsx b/apps/mobile/src/features/cloud/CloudAuthProvider.tsx new file mode 100644 index 0000000000..8748117a3a --- /dev/null +++ b/apps/mobile/src/features/cloud/CloudAuthProvider.tsx @@ -0,0 +1,89 @@ +import { ClerkProvider, useAuth } from "@clerk/expo"; +import { tokenCache } from "@clerk/expo/token-cache"; +import Constants from "expo-constants"; +import { type ReactNode, useEffect, useRef } from "react"; +import { RELAY_CLERK_TOKEN_OPTIONS } from "@t3tools/shared/relayAuth"; + +import { mobileRuntime } from "../../lib/runtime"; +import { + setAgentAwarenessRelayTokenProvider, + unregisterAgentAwarenessDeviceForCurrentUser, +} from "../agent-awareness/remoteRegistration"; +import { refreshActiveLiveActivityRemoteRegistration } from "../agent-awareness/liveActivityController"; + +function readClerkPublishableKey(): string | null { + const clerkConfig = Constants.expoConfig?.extra?.clerk as + | { readonly publishableKey?: string | null } + | undefined; + return clerkConfig?.publishableKey ?? null; +} + +function CloudAuthBridge(props: { readonly children: ReactNode }) { + const { getToken, isLoaded, isSignedIn, userId } = useAuth({ treatPendingAsSignedOut: false }); + const previousTokenProviderRef = useRef<{ + readonly userId: string; + readonly provider: () => Promise; + } | null>(null); + + useEffect(() => { + if (!isLoaded) { + return; + } + if (!isSignedIn || !userId) { + const previous = previousTokenProviderRef.current; + previousTokenProviderRef.current = null; + if (previous) { + void mobileRuntime + .runPromise(unregisterAgentAwarenessDeviceForCurrentUser(previous.provider)) + .catch(() => undefined); + } + setAgentAwarenessRelayTokenProvider(null); + return; + } + + const previous = previousTokenProviderRef.current; + if (previous && previous.userId !== userId) { + void mobileRuntime + .runPromise(unregisterAgentAwarenessDeviceForCurrentUser(previous.provider)) + .catch(() => undefined); + } + const tokenProvider = () => getToken(RELAY_CLERK_TOKEN_OPTIONS); + previousTokenProviderRef.current = { userId, provider: tokenProvider }; + setAgentAwarenessRelayTokenProvider(tokenProvider, userId); + if (!previous || previous.userId !== userId) { + void mobileRuntime + .runPromise(refreshActiveLiveActivityRemoteRegistration()) + .catch(() => undefined); + } + }, [getToken, isLoaded, isSignedIn, userId]); + + useEffect( + () => () => { + previousTokenProviderRef.current = null; + setAgentAwarenessRelayTokenProvider(null); + }, + [], + ); + + return props.children; +} + +export function CloudAuthProvider(props: { readonly children: ReactNode }) { + const publishableKey = readClerkPublishableKey(); + + useEffect(() => { + if (!publishableKey) { + setAgentAwarenessRelayTokenProvider(null); + } + }, [publishableKey]); + + if (!publishableKey) { + return props.children; + } + + return ( + + {props.children} + + ); +} diff --git a/apps/mobile/src/features/cloud/CloudWaitlistEnrollment.tsx b/apps/mobile/src/features/cloud/CloudWaitlistEnrollment.tsx new file mode 100644 index 0000000000..1528a8fb97 --- /dev/null +++ b/apps/mobile/src/features/cloud/CloudWaitlistEnrollment.tsx @@ -0,0 +1,208 @@ +import { useWaitlist } from "@clerk/expo"; +import { ActivityIndicator, Pressable, StyleSheet, Text, TextInput, View } from "react-native"; +import { useState } from "react"; + +import { useThemeColor } from "../../lib/useThemeColor"; + +export function CloudWaitlistEnrollment(props: { readonly onSignIn: () => void }) { + const { errors, fetchStatus, waitlist } = useWaitlist(); + const colors = useCloudWaitlistColors(); + const [emailAddress, setEmailAddress] = useState(""); + const [requestError, setRequestError] = useState(null); + const isSubmitting = fetchStatus === "fetching"; + const fieldError = errors.fields.emailAddress?.longMessage; + + const joinWaitlist = async () => { + const normalizedEmailAddress = emailAddress.trim(); + if (!normalizedEmailAddress || isSubmitting) { + return; + } + + setRequestError(null); + try { + const { error } = await waitlist.join({ emailAddress: normalizedEmailAddress }); + if (error) { + setRequestError("Could not join the waitlist. Check your email address and try again."); + } + } catch { + setRequestError("Could not join the waitlist. Check your connection and try again."); + } + }; + + if (waitlist.id) { + return ( + + You are on the waitlist + + We will email you when your T3 Cloud access is ready. + + + + ); + } + + return ( + + + Enter your email and we will let you know when access is ready. + + + + Email address + { + setEmailAddress(value); + setRequestError(null); + }} + onSubmitEditing={() => void joinWaitlist()} + placeholder="Enter your email address" + placeholderTextColor={colors.placeholder} + returnKeyType="join" + style={[ + styles.input, + { + backgroundColor: colors.input, + borderColor: + fieldError || requestError ? colors.dangerForeground : colors.inputBorder, + color: colors.foreground, + }, + ]} + textContentType="emailAddress" + value={emailAddress} + /> + {fieldError || requestError ? ( + + {fieldError ?? requestError} + + ) : null} + + + void joinWaitlist()} + style={[ + styles.primaryButton, + { + backgroundColor: colors.primary, + opacity: isSubmitting || emailAddress.trim().length === 0 ? 0.45 : 1, + }, + ]} + > + {isSubmitting ? : null} + + {isSubmitting ? "Joining" : "Join the waitlist"} + + + + + + ); +} + +function SignInAction(props: { readonly onPress: () => void }) { + const colors = useCloudWaitlistColors(); + return ( + + Already have access? + + Sign in + + + ); +} + +function useCloudWaitlistColors() { + return { + dangerForeground: String(useThemeColor("--color-danger-foreground")), + foreground: String(useThemeColor("--color-foreground")), + input: String(useThemeColor("--color-input")), + inputBorder: String(useThemeColor("--color-input-border")), + placeholder: String(useThemeColor("--color-placeholder")), + primary: String(useThemeColor("--color-primary")), + primaryForeground: String(useThemeColor("--color-primary-foreground")), + secondaryForeground: String(useThemeColor("--color-foreground-secondary")), + }; +} + +const styles = StyleSheet.create({ + body: { + fontFamily: "DMSans_400Regular", + fontSize: 15, + lineHeight: 21, + }, + buttonText: { + fontFamily: "DMSans_700Bold", + fontSize: 16, + }, + content: { + gap: 18, + }, + confirmationBody: { + textAlign: "center", + }, + error: { + fontFamily: "DMSans_400Regular", + fontSize: 13, + lineHeight: 18, + }, + field: { + gap: 8, + }, + input: { + borderCurve: "continuous", + borderRadius: 16, + borderWidth: 1, + fontFamily: "DMSans_400Regular", + fontSize: 17, + minHeight: 54, + paddingHorizontal: 16, + paddingVertical: 14, + }, + label: { + fontFamily: "DMSans_700Bold", + fontSize: 13, + lineHeight: 18, + }, + primaryButton: { + alignItems: "center", + borderRadius: 999, + flexDirection: "row", + gap: 8, + justifyContent: "center", + minHeight: 54, + paddingHorizontal: 20, + paddingVertical: 12, + }, + signInRow: { + alignItems: "center", + flexDirection: "row", + gap: 4, + justifyContent: "center", + paddingTop: 4, + }, + signInText: { + fontFamily: "DMSans_700Bold", + fontSize: 15, + lineHeight: 21, + }, + title: { + fontFamily: "DMSans_700Bold", + fontSize: 20, + lineHeight: 26, + textAlign: "center", + }, +}); diff --git a/apps/mobile/src/features/cloud/dpop.test.ts b/apps/mobile/src/features/cloud/dpop.test.ts new file mode 100644 index 0000000000..ccab9ac047 --- /dev/null +++ b/apps/mobile/src/features/cloud/dpop.test.ts @@ -0,0 +1,166 @@ +/// + +import * as NodeCrypto from "node:crypto"; + +import { vi } from "vitest"; +import { describe, expect, it } from "@effect/vitest"; +import * as Crypto from "effect/Crypto"; +import * as Effect from "effect/Effect"; +import { verifyDpopProof } from "@t3tools/shared/dpop"; + +import { + createDpopProof, + generateDpopProofKeyPair, + loadOrCreateDpopProofKeyPair, + mobileCryptoLayer, +} from "./dpop"; + +vi.mock("expo-crypto", () => ({ + CryptoDigestAlgorithm: { + SHA1: "SHA-1", + SHA256: "SHA-256", + SHA384: "SHA-384", + SHA512: "SHA-512", + }, + getRandomBytes: (byteCount: number) => new Uint8Array(NodeCrypto.randomBytes(byteCount)), + getRandomBytesAsync: (byteCount: number) => + Promise.resolve(new Uint8Array(NodeCrypto.randomBytes(byteCount))), + digest: (algorithm: string, data: unknown) => { + if (!(data instanceof Uint8Array)) { + return Promise.reject(new TypeError("expo-crypto digest data must be a typed array.")); + } + return Promise.resolve( + new Uint8Array(NodeCrypto.createHash(algorithm).update(data).digest()).buffer, + ); + }, +})); + +const secureStore = new Map(); +vi.mock("expo-secure-store", () => ({ + getItemAsync: (key: string) => Promise.resolve(secureStore.get(key) ?? null), + setItemAsync: (key: string, value: string) => { + secureStore.set(key, value); + return Promise.resolve(); + }, +})); + +function proofIat(proof: string): number { + const payload = proof.split(".")[1]; + if (!payload) { + throw new Error("Missing DPoP payload."); + } + const decoded = JSON.parse(Buffer.from(payload, "base64url").toString("utf8")) as { + readonly iat: number; + }; + return decoded.iat; +} + +function proofHtu(proof: string): string { + const payload = proof.split(".")[1]; + if (!payload) { + throw new Error("Missing DPoP payload."); + } + const decoded = JSON.parse(Buffer.from(payload, "base64url").toString("utf8")) as { + readonly htu: string; + }; + return decoded.htu; +} + +describe("mobile DPoP", () => { + it.effect("passes typed-array digest input through the Expo Crypto adapter", () => + Effect.gen(function* () { + const crypto = yield* Crypto.Crypto; + const digest = yield* crypto.digest("SHA-256", new TextEncoder().encode("typed-array")); + + expect(Buffer.from(digest).toString("hex")).toBe( + NodeCrypto.createHash("sha256").update("typed-array").digest("hex"), + ); + }).pipe(Effect.provide(mobileCryptoLayer)), + ); + + it.effect("persists and reuses the installation proof key", () => + Effect.gen(function* () { + secureStore.clear(); + const first = yield* loadOrCreateDpopProofKeyPair(); + const second = yield* loadOrCreateDpopProofKeyPair(); + + expect(second.thumbprint).toBe(first.thumbprint); + expect(second.privateJwk).toEqual(first.privateJwk); + }).pipe(Effect.provide(mobileCryptoLayer)), + ); + + it.effect("rejects malformed persisted proof keys", () => + Effect.gen(function* () { + secureStore.set("t3code.cloud.dpop-proof-key", `{"kty":"EC","crv":"P-256","d":42}`); + + const error = yield* loadOrCreateDpopProofKeyPair().pipe(Effect.flip); + + expect(error.message).toBe("Stored DPoP proof key is invalid."); + }).pipe(Effect.provide(mobileCryptoLayer)), + ); + + it.effect("signs connect and bootstrap proofs with the same ephemeral proof key", () => + Effect.gen(function* () { + const proofKey = yield* generateDpopProofKeyPair(); + const connect = yield* createDpopProof({ + method: "POST", + url: "https://relay.example.test/v1/environments/env-1/connect", + accessToken: "clerk-token", + proofKey, + }); + const bootstrap = yield* createDpopProof({ + method: "POST", + url: "https://desktop.example.test/oauth/token", + proofKey, + }); + + expect(connect.thumbprint).toBe(proofKey.thumbprint); + expect(bootstrap.thumbprint).toBe(proofKey.thumbprint); + expect( + verifyDpopProof({ + proof: connect.proof, + method: "POST", + url: "https://relay.example.test/v1/environments/env-1/connect", + expectedThumbprint: proofKey.thumbprint, + expectedAccessToken: "clerk-token", + nowEpochSeconds: proofIat(connect.proof), + }), + ).toMatchObject({ ok: true, thumbprint: proofKey.thumbprint }); + expect( + verifyDpopProof({ + proof: bootstrap.proof, + method: "POST", + url: "https://desktop.example.test/oauth/token", + expectedThumbprint: proofKey.thumbprint, + nowEpochSeconds: proofIat(bootstrap.proof), + }), + ).toMatchObject({ ok: true, thumbprint: proofKey.thumbprint }); + }).pipe(Effect.provide(mobileCryptoLayer)), + ); + + it.effect("signs DPoP proofs with RFC 9449 htu normalization", () => + Effect.gen(function* () { + const proofKey = yield* generateDpopProofKeyPair(); + const proof = yield* createDpopProof({ + method: "POST", + url: "https://relay.example.test/v1/environments/env-1/connect?debug=1#ignored", + accessToken: "clerk-token", + proofKey, + }); + + expect(proofHtu(proof.proof)).toBe( + "https://relay.example.test/v1/environments/env-1/connect", + ); + expect( + verifyDpopProof({ + proof: proof.proof, + method: "POST", + url: "https://relay.example.test/v1/environments/env-1/connect?debug=1#ignored", + expectedThumbprint: proofKey.thumbprint, + expectedAccessToken: "clerk-token", + nowEpochSeconds: proofIat(proof.proof), + }), + ).toMatchObject({ ok: true }); + }).pipe(Effect.provide(mobileCryptoLayer)), + ); +}); diff --git a/apps/mobile/src/features/cloud/dpop.ts b/apps/mobile/src/features/cloud/dpop.ts new file mode 100644 index 0000000000..0a3d7c2a5a --- /dev/null +++ b/apps/mobile/src/features/cloud/dpop.ts @@ -0,0 +1,270 @@ +import * as Clock from "effect/Clock"; +import * as Crypto from "effect/Crypto"; +import * as Data from "effect/Data"; +import * as Effect from "effect/Effect"; +import * as Encoding from "effect/Encoding"; +import * as Result from "effect/Result"; +import * as Schema from "effect/Schema"; +import * as ExpoCrypto from "expo-crypto"; +import * as SecureStore from "expo-secure-store"; +import { p256 } from "@noble/curves/nist"; +import { + computeDpopAccessTokenHash, + computeDpopJwkThumbprint, + DpopPublicJwk, + normalizeDpopHtu, +} from "@t3tools/shared/dpop"; +import * as Layer from "effect/Layer"; + +export class CloudDpopError extends Data.TaggedError("CloudDpopError")<{ + readonly message: string; + readonly cause?: unknown; +}> {} + +function cloudDpopError(message: string) { + return (cause: unknown) => new CloudDpopError({ message, cause }); +} + +const DpopPrivateJwkSchema = Schema.Struct({ + ...DpopPublicJwk.fields, + d: Schema.String, +}); + +const DpopPrivateJwkJson = Schema.fromJsonString(DpopPrivateJwkSchema); +const decodeDpopPrivateJwkJson = Schema.decodeUnknownEffect(DpopPrivateJwkJson); +const encodeDpopPrivateJwkJson = Schema.encodeEffect(DpopPrivateJwkJson); + +const DpopJwtHeaderJson = Schema.fromJsonString( + Schema.Struct({ + typ: Schema.Literal("dpop+jwt"), + alg: Schema.Literal("ES256"), + jwk: DpopPublicJwk, + }), +); + +const DpopJwtPayloadJson = Schema.fromJsonString( + Schema.Struct({ + htm: Schema.String, + htu: Schema.String, + jti: Schema.String, + iat: Schema.Int, + ath: Schema.optionalKey(Schema.String), + }), +); + +const encodeDpopJwtHeaderJson = Schema.encodeEffect(DpopJwtHeaderJson); +const encodeDpopJwtPayloadJson = Schema.encodeEffect(DpopJwtPayloadJson); + +function toExpoDigestAlgorithm( + algorithm: Crypto.DigestAlgorithm, +): ExpoCrypto.CryptoDigestAlgorithm { + switch (algorithm) { + case "SHA-1": + return ExpoCrypto.CryptoDigestAlgorithm.SHA1; + case "SHA-256": + return ExpoCrypto.CryptoDigestAlgorithm.SHA256; + case "SHA-384": + return ExpoCrypto.CryptoDigestAlgorithm.SHA384; + case "SHA-512": + return ExpoCrypto.CryptoDigestAlgorithm.SHA512; + } +} + +export const mobileCryptoLayer = Layer.succeed( + Crypto.Crypto, + Crypto.make({ + randomBytes: ExpoCrypto.getRandomBytes, + digest: (algorithm, data) => + Effect.promise(async () => { + const input = new Uint8Array(data.length); + input.set(data); + return new Uint8Array(await ExpoCrypto.digest(toExpoDigestAlgorithm(algorithm), input)); + }), + }), +); + +type DpopPrivateJwk = typeof DpopPrivateJwkSchema.Type; + +export interface DpopProofKeyPair { + readonly privateJwk: DpopPrivateJwk; + readonly publicJwk: DpopPublicJwk; + readonly thumbprint: string; +} + +const DPOP_PROOF_KEY_STORAGE_KEY = "t3code.cloud.dpop-proof-key"; + +function base64UrlToBytes(value: string): Uint8Array { + return Result.getOrThrow(Encoding.decodeBase64Url(value)); +} + +function sha256Digest( + data: Uint8Array, + message: string, +): Effect.Effect { + return Crypto.Crypto.pipe( + Effect.flatMap((crypto) => crypto.digest("SHA-256", data)), + Effect.mapError(cloudDpopError(message)), + ); +} + +function secureRandomBytes( + byteCount: number, + message: string, +): Effect.Effect { + return Crypto.Crypto.pipe( + Effect.flatMap((crypto) => crypto.randomBytes(byteCount)), + Effect.mapError(cloudDpopError(message)), + ); +} + +function publicJwkFromUncompressedPublicKey(publicKey: Uint8Array): DpopPublicJwk { + if (publicKey.length !== 65 || publicKey[0] !== 0x04) { + throw new Error("Generated DPoP public key is not an uncompressed P-256 point."); + } + return { + kty: "EC", + crv: "P-256", + x: Encoding.encodeBase64Url(publicKey.slice(1, 33)), + y: Encoding.encodeBase64Url(publicKey.slice(33, 65)), + }; +} + +function privateJwkFromPrivateKey( + privateKey: Uint8Array, + publicJwk: DpopPublicJwk, +): DpopPrivateJwk { + return { ...publicJwk, d: Encoding.encodeBase64Url(privateKey) }; +} + +export function generateDpopProofKeyPair(): Effect.Effect< + DpopProofKeyPair, + CloudDpopError, + Crypto.Crypto +> { + return Effect.gen(function* () { + let privateKey: Uint8Array; + do { + privateKey = yield* secureRandomBytes( + p256.CURVE.nByteLength, + "Could not generate DPoP key pair randomness.", + ); + } while (!p256.utils.isValidPrivateKey(privateKey)); + const publicJwk = yield* Effect.try({ + try: () => publicJwkFromUncompressedPublicKey(p256.getPublicKey(privateKey, false)), + catch: cloudDpopError("Generated DPoP public key is invalid."), + }); + const thumbprint = computeDpopJwkThumbprint(publicJwk); + return { + privateJwk: privateJwkFromPrivateKey(privateKey, publicJwk), + publicJwk, + thumbprint, + }; + }); +} + +export function loadOrCreateDpopProofKeyPair(): Effect.Effect< + DpopProofKeyPair, + CloudDpopError, + Crypto.Crypto +> { + return Effect.gen(function* () { + const stored = yield* Effect.tryPromise({ + try: () => SecureStore.getItemAsync(DPOP_PROOF_KEY_STORAGE_KEY), + catch: cloudDpopError("Could not read the DPoP proof key."), + }); + if (stored) { + const storedPrivateJwk = yield* decodeDpopPrivateJwkJson(stored).pipe( + Effect.mapError(cloudDpopError("Stored DPoP proof key is invalid.")), + ); + const restored = yield* Effect.try({ + try: () => { + const privateKey = base64UrlToBytes(storedPrivateJwk.d); + const publicJwk = publicJwkFromUncompressedPublicKey( + p256.getPublicKey(privateKey, false), + ); + if (publicJwk.x !== storedPrivateJwk.x || publicJwk.y !== storedPrivateJwk.y) { + throw new Error("Stored DPoP key does not match its public key."); + } + return { privateJwk: storedPrivateJwk, publicJwk }; + }, + catch: cloudDpopError("Stored DPoP proof key is invalid."), + }); + return { + ...restored, + thumbprint: computeDpopJwkThumbprint(restored.publicJwk), + }; + } + const generated = yield* generateDpopProofKeyPair(); + const encodedPrivateJwk = yield* encodeDpopPrivateJwkJson(generated.privateJwk).pipe( + Effect.mapError(cloudDpopError("Could not encode the DPoP proof key.")), + ); + yield* Effect.tryPromise({ + try: () => SecureStore.setItemAsync(DPOP_PROOF_KEY_STORAGE_KEY, encodedPrivateJwk), + catch: cloudDpopError("Could not store the DPoP proof key."), + }); + return generated; + }); +} + +function normalizeHtu(url: string): Effect.Effect { + const normalized = normalizeDpopHtu(url); + return normalized + ? Effect.succeed(normalized) + : Effect.fail(new CloudDpopError({ message: "DPoP URL is invalid." })); +} + +export function createDpopProof(input: { + readonly method: string; + readonly url: string; + readonly accessToken?: string; + readonly proofKey?: DpopProofKeyPair; +}): Effect.Effect< + { readonly proof: string; readonly thumbprint: string }, + CloudDpopError, + Crypto.Crypto +> { + return Effect.gen(function* () { + const keyPair = input.proofKey ?? (yield* generateDpopProofKeyPair()); + const privateKey = yield* Effect.try({ + try: () => base64UrlToBytes(keyPair.privateJwk.d), + catch: cloudDpopError("Could not import DPoP private key."), + }); + const nowMs = yield* Clock.currentTimeMillis; + const jti = yield* Crypto.Crypto.pipe( + Effect.flatMap((crypto) => crypto.randomUUIDv4), + Effect.mapError(cloudDpopError("Could not generate DPoP proof identifier.")), + ); + const htu = yield* normalizeHtu(input.url); + const header = yield* encodeDpopJwtHeaderJson({ + typ: "dpop+jwt", + alg: "ES256", + jwk: keyPair.publicJwk, + }).pipe( + Effect.map(Encoding.encodeBase64Url), + Effect.mapError(cloudDpopError("Could not encode DPoP proof header.")), + ); + const ath = input.accessToken ? computeDpopAccessTokenHash(input.accessToken) : null; + const payload = yield* encodeDpopJwtPayloadJson({ + htm: input.method.toUpperCase(), + htu, + jti, + iat: Math.floor(nowMs / 1_000), + ...(ath ? { ath } : {}), + }).pipe( + Effect.map(Encoding.encodeBase64Url), + Effect.mapError(cloudDpopError("Could not encode DPoP proof payload.")), + ); + const signatureInputHash = yield* sha256Digest( + new TextEncoder().encode(`${header}.${payload}`), + "Could not hash DPoP signing input.", + ); + const signature = yield* Effect.try({ + try: () => p256.sign(signatureInputHash, privateKey, { prehash: false }).toCompactRawBytes(), + catch: cloudDpopError("Could not sign DPoP proof."), + }); + return { + proof: `${header}.${payload}.${Encoding.encodeBase64Url(signature)}`, + thumbprint: keyPair.thumbprint, + }; + }); +} diff --git a/apps/mobile/src/features/cloud/linkEnvironment.test.ts b/apps/mobile/src/features/cloud/linkEnvironment.test.ts new file mode 100644 index 0000000000..e2e3df4eb6 --- /dev/null +++ b/apps/mobile/src/features/cloud/linkEnvironment.test.ts @@ -0,0 +1,1030 @@ +import { beforeEach, vi } from "vitest"; +import { describe, expect, it } from "@effect/vitest"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import { EnvironmentId } from "@t3tools/contracts"; +import { RelayMobileClientId } from "@t3tools/contracts/relay"; +import { + managedRelayClientLayer, + ManagedRelayClient, + ManagedRelayDpopSigner, + remoteHttpClientLayer, +} from "@t3tools/client-runtime"; +import { HttpClient } from "effect/unstable/http"; + +import { + cloudEnvironmentsPendingStatus, + linkEnvironmentToCloud, + connectCloudEnvironment, + listCloudEnvironments, + listCloudEnvironmentsWithStatus, + normalizeRelayBaseUrl, +} from "./linkEnvironment"; + +vi.mock("expo-constants", () => ({ + default: { + expoConfig: { + extra: { + relay: { + url: "https://relay.example.test", + }, + }, + }, + }, +})); + +vi.mock("react-native", () => ({ + Platform: { + OS: "ios", + }, +})); + +vi.mock("../../lib/storage", () => ({ + loadOrCreateAgentAwarenessDeviceId: vi.fn(() => Promise.resolve("device-1")), + loadPreferences: vi.fn(() => Promise.resolve({})), +})); + +const savedConnection = { + environmentId: EnvironmentId.make("env-1"), + environmentLabel: "Desktop", + pairingUrl: "https://desktop.example.test/", + displayUrl: "https://desktop.example.test/", + httpBaseUrl: "https://desktop.example.test/", + wsBaseUrl: "wss://desktop.example.test/ws", + bearerToken: "local-bearer", +}; + +const createProofMock = vi.fn( + (input: { readonly method: string; readonly url: string; readonly accessToken?: string }) => + Effect.succeed(`dpop:${input.method}:${input.url}`), +); +const testDpopSignerLayer = Layer.succeed( + ManagedRelayDpopSigner, + ManagedRelayDpopSigner.of({ + thumbprint: Effect.succeed("client-proof-key-thumbprint"), + createProof: (input) => createProofMock(input), + }), +); + +function cloudClientLayer() { + const httpClientLayer = remoteHttpClientLayer((input, init) => globalThis.fetch(input, init)); + return Layer.mergeAll( + httpClientLayer, + managedRelayClientLayer({ + relayUrl: "https://relay.example.test", + clientId: RelayMobileClientId, + }).pipe(Layer.provideMerge(testDpopSignerLayer), Layer.provide(httpClientLayer)), + ); +} + +const withCloudServices = ( + effect: Effect.Effect, +) => effect.pipe(Effect.provide(cloudClientLayer())); + +function validLinkProof() { + return "signed-environment-link-jwt"; +} + +function validLinkResponse(environmentId = "env-1") { + return { + ok: true, + environmentId, + endpoint: { + httpBaseUrl: "https://managed.example.test/", + wsBaseUrl: "wss://managed.example.test/ws", + providerKind: "cloudflare_tunnel", + }, + endpointRuntime: { + providerKind: "cloudflare_tunnel", + connectorToken: "connector-token", + }, + relayIssuer: "https://relay.example.test", + cloudUserId: "user_123", + environmentCredential: "environment-credential", + cloudMintPublicKey: "cloud-mint-public-key", + }; +} + +function validLinkChallengeResponse() { + return { + challenge: "link-challenge", + expiresAt: "2026-05-25T00:05:00.000Z", + }; +} + +function requestBodyText(body: BodyInit | null | undefined): string { + return body instanceof Uint8Array ? new TextDecoder().decode(body) : String(body ?? ""); +} + +function validDpopAccessTokenResponse(scope = "environment:status environment:connect") { + return { + access_token: "relay-dpop-token", + issued_token_type: "urn:ietf:params:oauth:token-type:access_token", + token_type: "DPoP", + expires_in: 300, + scope, + }; +} + +function listedEnvironment(environmentId: string) { + return { + environmentId: EnvironmentId.make(environmentId), + label: "Desktop", + endpoint: { + httpBaseUrl: `https://${environmentId}.example.test/`, + wsBaseUrl: `wss://${environmentId}.example.test/ws`, + providerKind: "cloudflare_tunnel" as const, + }, + linkedAt: "2026-05-25T00:00:00.000Z", + }; +} + +describe("mobile cloud link environment client", () => { + beforeEach(() => { + vi.restoreAllMocks(); + createProofMock.mockClear(); + }); + + it("normalizes configured relay base URLs before building DPoP-bound requests", () => { + expect(normalizeRelayBaseUrl(" https://relay.example.test/// ")).toBe( + "https://relay.example.test", + ); + expect(normalizeRelayBaseUrl(" ")).toBeNull(); + }); + + it("makes linked environments visible while their status is still loading", () => { + expect(cloudEnvironmentsPendingStatus([listedEnvironment("env-1")])).toMatchObject([ + { + environment: { environmentId: "env-1", label: "Desktop" }, + status: null, + statusError: "Checking status...", + }, + ]); + }); + + it.effect("decodes relay environment list responses before returning records", () => + Effect.gen(function* () { + vi.stubGlobal( + "fetch", + vi.fn(() => + Promise.resolve( + Response.json({ + environments: [ + { + environmentId: "env-1", + label: "Desktop", + endpoint: { + httpBaseUrl: "https://desktop.example.test/", + wsBaseUrl: "wss://desktop.example.test/ws", + providerKind: "cloudflare_tunnel", + }, + linkedAt: "2026-05-25T00:00:00.000Z", + }, + ], + }), + ), + ), + ); + + const records = yield* withCloudServices( + listCloudEnvironments({ clerkToken: "clerk-token" }), + ); + expect(records).toEqual([ + { + environmentId: "env-1", + label: "Desktop", + endpoint: { + httpBaseUrl: "https://desktop.example.test/", + wsBaseUrl: "wss://desktop.example.test/ws", + providerKind: "cloudflare_tunnel", + }, + linkedAt: "2026-05-25T00:00:00.000Z", + }, + ]); + }), + ); + + it.effect("rejects malformed relay environment list responses", () => + Effect.gen(function* () { + vi.stubGlobal( + "fetch", + vi.fn(() => + Promise.resolve( + Response.json({ + environments: [ + { + environmentId: "env-1", + label: "Desktop", + endpoint: { + httpBaseUrl: "", + wsBaseUrl: "wss://desktop.example.test/ws", + providerKind: "cloudflare_tunnel", + }, + linkedAt: "2026-05-25T00:00:00.000Z", + }, + ], + }), + ), + ), + ); + + const error = yield* withCloudServices( + listCloudEnvironments({ clerkToken: "clerk-token" }), + ).pipe(Effect.flip); + expect(error).toMatchObject({ + _tag: "CloudEnvironmentLinkError", + message: "https://relay.example.test/v1/environments failed", + }); + }), + ); + + it.effect("loads signed status for each advertised cloud environment", () => + Effect.gen(function* () { + const fetchMock = vi.fn((url: string | URL, _init?: RequestInit) => { + if (String(url) === "https://relay.example.test/v1/environments") { + return Promise.resolve( + Response.json({ + environments: [ + { + environmentId: "env-1", + label: "Desktop", + endpoint: { + httpBaseUrl: "https://desktop.example.test/", + wsBaseUrl: "wss://desktop.example.test/ws", + providerKind: "cloudflare_tunnel", + }, + linkedAt: "2026-05-25T00:00:00.000Z", + }, + ], + }), + ); + } + if (String(url) === "https://relay.example.test/v1/client/dpop-token") { + return Promise.resolve(Response.json(validDpopAccessTokenResponse())); + } + expect(String(url)).toBe("https://relay.example.test/v1/environments/env-1/status"); + return Promise.resolve( + Response.json({ + environmentId: "env-1", + endpoint: { + httpBaseUrl: "https://desktop.example.test/", + wsBaseUrl: "wss://desktop.example.test/ws", + providerKind: "cloudflare_tunnel", + }, + status: "online", + checkedAt: "2026-05-25T00:01:00.000Z", + descriptor: { + environmentId: "env-1", + label: "Desktop", + platform: { os: "darwin", arch: "arm64" }, + serverVersion: "0.0.0-test", + capabilities: { repositoryIdentity: true }, + }, + }), + ); + }); + vi.stubGlobal("fetch", fetchMock); + + const records = yield* withCloudServices( + listCloudEnvironmentsWithStatus({ clerkToken: "clerk-token" }), + ); + expect(records).toMatchObject([ + { + environment: { + environmentId: "env-1", + label: "Desktop", + }, + status: { + environmentId: "env-1", + status: "online", + checkedAt: "2026-05-25T00:01:00.000Z", + }, + statusError: null, + }, + ]); + expect(String(fetchMock.mock.calls[2]?.[0])).toBe( + "https://relay.example.test/v1/environments/env-1/status", + ); + expect(fetchMock.mock.calls[2]?.[1]?.method).toBe("POST"); + const statusHeaders = new Headers(fetchMock.mock.calls[2]?.[1]?.headers); + expect(statusHeaders.get("authorization")).toBe("DPoP relay-dpop-token"); + expect(statusHeaders.get("dpop")).toBe( + "dpop:POST:https://relay.example.test/v1/environments/env-1/status", + ); + expect(createProofMock).toHaveBeenCalledWith({ + method: "POST", + url: "https://relay.example.test/v1/environments/env-1/status", + accessToken: "relay-dpop-token", + }); + }), + ); + + it.effect("reuses one valid DPoP access token while probing multiple environment statuses", () => + Effect.gen(function* () { + const fetchMock = vi.fn((url: string | URL, _init?: RequestInit) => { + if (String(url).endsWith("/v1/environments")) { + return Promise.resolve( + Response.json({ + environments: [listedEnvironment("env-1"), listedEnvironment("env-2")], + }), + ); + } + if (String(url).endsWith("/v1/client/dpop-token")) { + return Promise.resolve(Response.json(validDpopAccessTokenResponse())); + } + const environmentId = String(url).includes("/env-1/") ? "env-1" : "env-2"; + return Promise.resolve( + Response.json({ + environmentId, + endpoint: listedEnvironment(environmentId).endpoint, + status: "online", + checkedAt: "2026-05-25T00:01:00.000Z", + descriptor: { + environmentId, + label: "Desktop", + platform: { os: "darwin", arch: "arm64" }, + serverVersion: "0.0.0-test", + capabilities: { repositoryIdentity: true }, + }, + }), + ); + }); + vi.stubGlobal("fetch", fetchMock); + + yield* withCloudServices(listCloudEnvironmentsWithStatus({ clerkToken: "clerk-token" })); + + expect( + fetchMock.mock.calls.filter(([url]) => String(url).endsWith("/v1/client/dpop-token")), + ).toHaveLength(1); + }), + ); + + it.effect("reuses the status-and-connect token when connecting from the cloud list", () => + Effect.gen(function* () { + const fetchMock = vi.fn((url: string | URL, _init?: RequestInit) => { + if (String(url).endsWith("/v1/environments")) { + return Promise.resolve( + Response.json({ + environments: [listedEnvironment("env-1")], + }), + ); + } + if (String(url).endsWith("/v1/client/dpop-token")) { + return Promise.resolve(Response.json(validDpopAccessTokenResponse())); + } + if (String(url).endsWith("/status")) { + return Promise.resolve( + Response.json({ + environmentId: "env-1", + endpoint: listedEnvironment("env-1").endpoint, + status: "online", + checkedAt: "2026-05-25T00:01:00.000Z", + descriptor: { + environmentId: "env-1", + label: "Desktop", + platform: { os: "darwin", arch: "arm64" }, + serverVersion: "0.0.0-test", + capabilities: { repositoryIdentity: true }, + }, + }), + ); + } + if (String(url).endsWith("/connect")) { + return Promise.resolve( + Response.json({ + environmentId: "env-1", + endpoint: listedEnvironment("env-1").endpoint, + credential: "one-time-cloud-credential", + expiresAt: "2026-05-25T00:05:00.000Z", + }), + ); + } + if (String(url).endsWith("/.well-known/t3/environment")) { + return Promise.resolve( + Response.json({ + environmentId: "env-1", + label: "Desktop", + platform: { os: "darwin", arch: "arm64" }, + serverVersion: "0.0.0-test", + capabilities: { repositoryIdentity: true }, + }), + ); + } + return Promise.resolve( + Response.json({ + access_token: "environment-dpop-token", + issued_token_type: "urn:ietf:params:oauth:token-type:access_token", + token_type: "DPoP", + expires_in: 3600, + scope: "orchestration:read orchestration:operate terminal:operate review:write", + }), + ); + }); + vi.stubGlobal("fetch", fetchMock); + + yield* withCloudServices( + Effect.gen(function* () { + const records = yield* listCloudEnvironmentsWithStatus({ clerkToken: "clerk-token" }); + yield* connectCloudEnvironment({ + clerkToken: "clerk-token", + environment: records[0]!.environment, + }); + }), + ); + + expect( + fetchMock.mock.calls.filter(([url]) => String(url).endsWith("/v1/client/dpop-token")), + ).toHaveLength(1); + const exchangeRequest = fetchMock.mock.calls.find(([url]) => + String(url).endsWith("/v1/client/dpop-token"), + )?.[1]; + expect(new URLSearchParams(requestBodyText(exchangeRequest?.body)).get("scope")).toBe( + "environment:status environment:connect", + ); + const environmentTokenRequest = fetchMock.mock.calls.find(([url]) => + String(url).endsWith("/oauth/token"), + )?.[1]; + const environmentTokenBody = new URLSearchParams( + requestBodyText(environmentTokenRequest?.body), + ); + expect(environmentTokenBody.get("client_label")).toBe("T3 Code Mobile"); + expect(environmentTokenBody.get("client_device_type")).toBe("mobile"); + expect(environmentTokenBody.get("client_os")).toBe("iOS"); + }), + ); + + it.effect("keeps advertised environments visible when status probing fails", () => + Effect.gen(function* () { + vi.stubGlobal( + "fetch", + vi.fn((url: string | URL) => { + if (String(url) === "https://relay.example.test/v1/environments") { + return Promise.resolve( + Response.json({ + environments: [ + { + environmentId: "env-1", + label: "Desktop", + endpoint: { + httpBaseUrl: "https://desktop.example.test/", + wsBaseUrl: "wss://desktop.example.test/ws", + providerKind: "cloudflare_tunnel", + }, + linkedAt: "2026-05-25T00:00:00.000Z", + }, + ], + }), + ); + } + if (String(url) === "https://relay.example.test/v1/client/dpop-token") { + return Promise.resolve(Response.json(validDpopAccessTokenResponse())); + } + return Promise.resolve(Response.json({ error: "offline" }, { status: 503 })); + }), + ); + + const records = yield* withCloudServices( + listCloudEnvironmentsWithStatus({ clerkToken: "clerk-token" }), + ); + expect(records).toMatchObject([ + { + environment: { + environmentId: "env-1", + label: "Desktop", + }, + status: null, + statusError: "https://relay.example.test/v1/environments/env-1/status failed", + }, + ]); + }), + ); + + it.effect("rejects status responses for a different advertised environment", () => + Effect.gen(function* () { + vi.stubGlobal( + "fetch", + vi.fn((url: string | URL) => { + if (String(url) === "https://relay.example.test/v1/environments") { + return Promise.resolve( + Response.json({ + environments: [ + { + environmentId: "env-1", + label: "Desktop", + endpoint: { + httpBaseUrl: "https://desktop.example.test/", + wsBaseUrl: "wss://desktop.example.test/ws", + providerKind: "cloudflare_tunnel", + }, + linkedAt: "2026-05-25T00:00:00.000Z", + }, + ], + }), + ); + } + if (String(url) === "https://relay.example.test/v1/client/dpop-token") { + return Promise.resolve(Response.json(validDpopAccessTokenResponse())); + } + return Promise.resolve( + Response.json({ + environmentId: "env-other", + endpoint: { + httpBaseUrl: "https://desktop.example.test/", + wsBaseUrl: "wss://desktop.example.test/ws", + providerKind: "cloudflare_tunnel", + }, + status: "online", + checkedAt: "2026-05-25T00:01:00.000Z", + descriptor: { + environmentId: "env-other", + label: "Other Desktop", + platform: { os: "darwin", arch: "arm64" }, + serverVersion: "0.0.0-test", + capabilities: { repositoryIdentity: true }, + }, + }), + ); + }), + ); + + const records = yield* withCloudServices( + listCloudEnvironmentsWithStatus({ clerkToken: "clerk-token" }), + ); + expect(records).toMatchObject([ + { + environment: { + environmentId: "env-1", + label: "Desktop", + }, + status: null, + statusError: "Relay returned status for a different environment.", + }, + ]); + }), + ); + + it.effect( + "rejects relay link credentials for a different environment before persisting relay config", + () => + Effect.gen(function* () { + const fetchMock = vi.fn((url: string | URL) => { + if (String(url).endsWith("/v1/client/environment-link-challenges")) { + return Promise.resolve(Response.json(validLinkChallengeResponse())); + } + if (String(url).endsWith("/api/cloud/link-proof")) { + return Promise.resolve(Response.json(validLinkProof())); + } + return Promise.resolve(Response.json(validLinkResponse("env-other"))); + }); + vi.stubGlobal("fetch", fetchMock); + + const error = yield* withCloudServices( + linkEnvironmentToCloud({ + clerkToken: "clerk-token", + connection: savedConnection, + }), + ).pipe(Effect.flip); + expect(error).toMatchObject({ + _tag: "CloudEnvironmentLinkError", + message: "Relay returned credentials for a different environment.", + }); + expect(fetchMock).toHaveBeenCalledTimes(3); + }), + ); + + it.effect("preserves typed local environment failures while obtaining a link proof", () => + Effect.gen(function* () { + const fetchMock = vi.fn((url: string | URL) => { + if (String(url).endsWith("/v1/client/environment-link-challenges")) { + return Promise.resolve(Response.json(validLinkChallengeResponse())); + } + return Promise.resolve( + Response.json( + { + _tag: "EnvironmentHttpUnauthorizedError", + message: "Invalid environment bearer session.", + }, + { status: 401 }, + ), + ); + }); + vi.stubGlobal("fetch", fetchMock); + + const error = yield* withCloudServices( + linkEnvironmentToCloud({ + clerkToken: "clerk-token", + connection: savedConnection, + }), + ).pipe(Effect.flip); + expect(error._tag).toBe("CloudEnvironmentLinkError"); + expect(error.message).toBe( + "Could not obtain environment link proof: Invalid environment bearer session.", + ); + expect(fetchMock).toHaveBeenCalledTimes(2); + }), + ); + + it.effect("preserves typed relay error bodies while linking environments", () => + Effect.gen(function* () { + const fetchMock = vi.fn((url: string | URL) => { + if (String(url).endsWith("/v1/client/environment-link-challenges")) { + return Promise.resolve(Response.json(validLinkChallengeResponse())); + } + if (String(url).endsWith("/api/cloud/link-proof")) { + return Promise.resolve(Response.json(validLinkProof())); + } + return Promise.resolve( + Response.json( + { + _tag: "RelayEnvironmentLinkProofInvalidError", + code: "environment_link_proof_invalid", + reason: "origin_not_allowed", + traceId: "trace-test", + }, + { status: 400 }, + ), + ); + }); + vi.stubGlobal("fetch", fetchMock); + + const error = yield* withCloudServices( + linkEnvironmentToCloud({ + clerkToken: "clerk-token", + connection: savedConnection, + }), + ).pipe(Effect.flip); + expect(error).toMatchObject({ + _tag: "CloudEnvironmentLinkError", + message: + "https://relay.example.test/v1/client/environment-links failed: Relay rejected the environment link proof (origin_not_allowed).", + }); + expect(fetchMock).toHaveBeenCalledTimes(3); + }), + ); + + it.effect("rejects relay link credentials for a different managed endpoint provider", () => + Effect.gen(function* () { + const fetchMock = vi.fn((url: string | URL) => { + if (String(url).endsWith("/v1/client/environment-link-challenges")) { + return Promise.resolve(Response.json(validLinkChallengeResponse())); + } + if (String(url).endsWith("/api/cloud/link-proof")) { + return Promise.resolve(Response.json(validLinkProof())); + } + return Promise.resolve( + Response.json({ + ...validLinkResponse(), + endpoint: { + ...validLinkResponse().endpoint, + providerKind: "manual", + }, + }), + ); + }); + vi.stubGlobal("fetch", fetchMock); + + const error = yield* withCloudServices( + linkEnvironmentToCloud({ + clerkToken: "clerk-token", + connection: savedConnection, + }), + ).pipe(Effect.flip); + expect(error).toMatchObject({ + _tag: "CloudEnvironmentLinkError", + message: "Relay returned credentials for a different endpoint provider.", + }); + expect(fetchMock).toHaveBeenCalledTimes(3); + }), + ); + + it.effect("preserves disabled Live Activity preferences when linking an environment", () => + Effect.gen(function* () { + const storage = yield* Effect.promise(() => import("../../lib/storage")); + vi.mocked(storage.loadPreferences).mockResolvedValueOnce({ + liveActivitiesEnabled: false, + }); + const bodies: Array = []; + const fetchMock = vi.fn((url: string | URL, init?: RequestInit) => { + if (init?.body) { + // @effect-diagnostics-next-line preferSchemaOverJson:off + bodies.push(JSON.parse(requestBodyText(init.body))); + } + if (String(url).endsWith("/v1/client/environment-link-challenges")) { + return Promise.resolve(Response.json(validLinkChallengeResponse())); + } + if (String(url).endsWith("/api/cloud/link-proof")) { + return Promise.resolve(Response.json(validLinkProof())); + } + if (String(url).endsWith("/v1/client/environment-links")) { + return Promise.resolve(Response.json(validLinkResponse())); + } + return Promise.resolve( + Response.json({ ok: true, endpointRuntimeStatus: { status: "configured" } }), + ); + }); + vi.stubGlobal("fetch", fetchMock); + + yield* withCloudServices( + linkEnvironmentToCloud({ + clerkToken: "clerk-token", + connection: savedConnection, + }), + ); + + expect(bodies[1]).toMatchObject({ + endpoint: { + httpBaseUrl: "https://desktop.example.test/", + wsBaseUrl: "wss://desktop.example.test/ws", + providerKind: "cloudflare_tunnel", + }, + origin: { + localHttpHost: "127.0.0.1", + localHttpPort: 443, + }, + }); + expect(bodies[2]).toMatchObject({ + deviceId: "device-1", + notificationsEnabled: true, + liveActivitiesEnabled: false, + managedTunnelsEnabled: true, + }); + expect(bodies[3]).toMatchObject({ + cloudUserId: "user_123", + environmentCredential: "environment-credential", + }); + }), + ); + + it.effect( + "does not persist cloud connect bootstrap credentials in saved connection records", + () => + Effect.gen(function* () { + let connectRequestBody = ""; + const fetchMock = vi.fn((url: string | URL, init?: RequestInit) => { + if (String(url).endsWith("/v1/client/dpop-token")) { + return Promise.resolve( + Response.json(validDpopAccessTokenResponse("environment:connect")), + ); + } + if (String(url).endsWith("/.well-known/t3/environment")) { + return Promise.resolve( + Response.json({ + environmentId: "env-1", + label: "Desktop", + platform: { os: "darwin", arch: "arm64" }, + serverVersion: "0.0.0-test", + capabilities: { repositoryIdentity: true }, + }), + ); + } + if (String(url).endsWith("/oauth/token")) { + return Promise.resolve( + Response.json({ + access_token: "environment-dpop-token", + issued_token_type: "urn:ietf:params:oauth:token-type:access_token", + token_type: "DPoP", + expires_in: 3600, + scope: "orchestration:read orchestration:operate terminal:operate review:write", + }), + ); + } + connectRequestBody = requestBodyText(init?.body); + return Promise.resolve( + Response.json({ + environmentId: "env-1", + endpoint: { + httpBaseUrl: "https://desktop.example.test/", + wsBaseUrl: "wss://desktop.example.test/ws", + providerKind: "cloudflare_tunnel", + }, + credential: "one-time-cloud-credential", + expiresAt: "2026-05-25T00:05:00.000Z", + }), + ); + }); + vi.stubGlobal("fetch", fetchMock); + + const connection = yield* withCloudServices( + connectCloudEnvironment({ + clerkToken: "clerk-token", + environment: { + environmentId: EnvironmentId.make("env-1"), + label: "Desktop", + endpoint: { + httpBaseUrl: "https://desktop.example.test/", + wsBaseUrl: "wss://desktop.example.test/ws", + providerKind: "cloudflare_tunnel", + }, + linkedAt: "2026-05-25T00:00:00.000Z", + }, + }), + ); + + expect(connection.pairingUrl).toBe("https://desktop.example.test/"); + expect(connection.pairingUrl).not.toContain("one-time-cloud-credential"); + expect(connection.bearerToken).toBeNull(); + expect(connection.authenticationMethod).toBe("dpop"); + expect(connection.dpopAccessToken).toBe("environment-dpop-token"); + // @effect-diagnostics-next-line preferSchemaOverJson:off + expect(JSON.parse(connectRequestBody)).toMatchObject({ + deviceId: "device-1", + clientKeyThumbprint: "client-proof-key-thumbprint", + }); + expect(createProofMock).toHaveBeenCalledWith({ + method: "POST", + url: "https://relay.example.test/v1/environments/env-1/connect", + accessToken: "relay-dpop-token", + }); + expect(createProofMock).toHaveBeenCalledWith({ + method: "POST", + url: "https://desktop.example.test/oauth/token", + }); + }), + ); + + it.effect("rejects relay connect responses for a different environment", () => + Effect.gen(function* () { + vi.stubGlobal( + "fetch", + vi.fn((url: string | URL) => + Promise.resolve( + String(url).endsWith("/v1/client/dpop-token") + ? Response.json(validDpopAccessTokenResponse("environment:connect")) + : Response.json({ + environmentId: "env-other", + endpoint: { + httpBaseUrl: "https://desktop.example.test/", + wsBaseUrl: "wss://desktop.example.test/ws", + providerKind: "cloudflare_tunnel", + }, + credential: "one-time-cloud-credential", + expiresAt: "2026-05-25T00:05:00.000Z", + }), + ), + ), + ); + + const error = yield* withCloudServices( + connectCloudEnvironment({ + clerkToken: "clerk-token", + environment: { + environmentId: EnvironmentId.make("env-1"), + label: "Desktop", + endpoint: { + httpBaseUrl: "https://desktop.example.test/", + wsBaseUrl: "wss://desktop.example.test/ws", + providerKind: "cloudflare_tunnel", + }, + linkedAt: "2026-05-25T00:00:00.000Z", + }, + }), + ).pipe(Effect.flip); + expect(error).toMatchObject({ + _tag: "CloudEnvironmentLinkError", + message: "Relay returned credentials for a different environment.", + }); + }), + ); + + it.effect("preserves relay DPoP auth failures while connecting environments", () => + Effect.gen(function* () { + vi.stubGlobal( + "fetch", + vi.fn((url: string | URL) => + Promise.resolve( + String(url).endsWith("/v1/client/dpop-token") + ? Response.json(validDpopAccessTokenResponse("environment:connect")) + : Response.json( + { + _tag: "RelayAuthInvalidError", + code: "auth_invalid", + reason: "invalid_dpop", + traceId: "trace-connect", + }, + { status: 401 }, + ), + ), + ), + ); + + const error = yield* withCloudServices( + connectCloudEnvironment({ + clerkToken: "clerk-token", + environment: { + environmentId: EnvironmentId.make("env-1"), + label: "Desktop", + endpoint: { + httpBaseUrl: "https://desktop.example.test/", + wsBaseUrl: "wss://desktop.example.test/ws", + providerKind: "cloudflare_tunnel", + }, + linkedAt: "2026-05-25T00:00:00.000Z", + }, + }), + ).pipe(Effect.flip); + expect(error).toMatchObject({ + _tag: "CloudEnvironmentLinkError", + message: + "https://relay.example.test/v1/environments/env-1/connect failed: Relay rejected the DPoP proof.", + }); + }), + ); + + it.effect("rejects relay connect responses for a different endpoint", () => + Effect.gen(function* () { + vi.stubGlobal( + "fetch", + vi.fn((url: string | URL) => + Promise.resolve( + String(url).endsWith("/v1/client/dpop-token") + ? Response.json(validDpopAccessTokenResponse("environment:connect")) + : Response.json({ + environmentId: "env-1", + endpoint: { + httpBaseUrl: "https://other-desktop.example.test/", + wsBaseUrl: "wss://other-desktop.example.test/ws", + providerKind: "cloudflare_tunnel", + }, + credential: "one-time-cloud-credential", + expiresAt: "2026-05-25T00:05:00.000Z", + }), + ), + ), + ); + + const error = yield* withCloudServices( + connectCloudEnvironment({ + clerkToken: "clerk-token", + environment: { + environmentId: EnvironmentId.make("env-1"), + label: "Desktop", + endpoint: { + httpBaseUrl: "https://desktop.example.test/", + wsBaseUrl: "wss://desktop.example.test/ws", + providerKind: "cloudflare_tunnel", + }, + linkedAt: "2026-05-25T00:00:00.000Z", + }, + }), + ).pipe(Effect.flip); + expect(error).toMatchObject({ + _tag: "CloudEnvironmentLinkError", + message: "Relay returned credentials for a different endpoint.", + }); + }), + ); + + it.effect( + "rejects managed endpoints whose descriptor does not match the selected environment", + () => + Effect.gen(function* () { + vi.stubGlobal( + "fetch", + vi.fn((url: string | URL) => + Promise.resolve( + String(url).endsWith("/v1/client/dpop-token") + ? Response.json(validDpopAccessTokenResponse("environment:connect")) + : String(url).endsWith("/.well-known/t3/environment") + ? Response.json({ + environmentId: "env-other", + label: "Other Desktop", + platform: { os: "darwin", arch: "arm64" }, + serverVersion: "0.0.0-test", + capabilities: { repositoryIdentity: true }, + }) + : Response.json({ + environmentId: "env-1", + endpoint: { + httpBaseUrl: "https://desktop.example.test/", + wsBaseUrl: "wss://desktop.example.test/ws", + providerKind: "cloudflare_tunnel", + }, + credential: "one-time-cloud-credential", + expiresAt: "2026-05-25T00:05:00.000Z", + }), + ), + ), + ); + + const error = yield* withCloudServices( + connectCloudEnvironment({ + clerkToken: "clerk-token", + environment: { + environmentId: EnvironmentId.make("env-1"), + label: "Desktop", + endpoint: { + httpBaseUrl: "https://desktop.example.test/", + wsBaseUrl: "wss://desktop.example.test/ws", + providerKind: "cloudflare_tunnel", + }, + linkedAt: "2026-05-25T00:00:00.000Z", + }, + }), + ).pipe(Effect.flip); + expect(error).toMatchObject({ + _tag: "CloudEnvironmentLinkError", + message: "Connected endpoint descriptor does not match the selected environment.", + }); + }), + ); +}); diff --git a/apps/mobile/src/features/cloud/linkEnvironment.ts b/apps/mobile/src/features/cloud/linkEnvironment.ts new file mode 100644 index 0000000000..e13e31bf19 --- /dev/null +++ b/apps/mobile/src/features/cloud/linkEnvironment.ts @@ -0,0 +1,552 @@ +import Constants from "expo-constants"; +import * as Data from "effect/Data"; +import * as Effect from "effect/Effect"; +import * as Schema from "effect/Schema"; +import { HttpClient } from "effect/unstable/http"; +import { + EnvironmentCloudEndpointUnavailableError, + EnvironmentHttpBadRequestError, + EnvironmentHttpConflictError, + EnvironmentHttpForbiddenError, + EnvironmentHttpInternalServerError, + EnvironmentHttpUnauthorizedError, +} from "@t3tools/contracts"; +import { stripPairingTokenFromUrl } from "@t3tools/shared/remote"; +import { + type RelayEnvironmentConnectResponse as RelayEnvironmentConnectResponseType, + type RelayEnvironmentLinkResponse as RelayEnvironmentLinkResponseType, + RelayEnvironmentConnectScope, + RelayEnvironmentStatusScope, + RelayProtectedError, + type RelayDpopAccessTokenScope, + type RelayProtectedError as RelayProtectedErrorType, + type RelayClientEnvironmentRecord, + type RelayEnvironmentStatusResponse as RelayEnvironmentStatusResponseType, + type RelayManagedEndpointProviderKind, +} from "@t3tools/contracts/relay"; +import { + exchangeRemoteDpopAccessToken, + fetchRemoteEnvironmentDescriptor, + makeEnvironmentHttpApiClient, + ManagedRelayClient, + ManagedRelayDpopSigner, +} from "@t3tools/client-runtime"; + +import { mobileAuthClientMetadata } from "../../lib/authClientMetadata"; +import type { SavedRemoteConnection } from "../../lib/connection"; +import { loadOrCreateAgentAwarenessDeviceId, loadPreferences } from "../../lib/storage"; + +const RELAY_STATUS_AND_CONNECT_SCOPES = [ + RelayEnvironmentStatusScope, + RelayEnvironmentConnectScope, +] satisfies ReadonlyArray; + +export function normalizeRelayBaseUrl(value: string | null | undefined): string | null { + const trimmed = value?.trim(); + if (!trimmed) { + return null; + } + return trimmed.replace(/\/+$/g, ""); +} + +function readRelayUrl(): string | null { + const relayConfig = Constants.expoConfig?.extra?.relay as + | { readonly url?: string | null } + | undefined; + return normalizeRelayBaseUrl(relayConfig?.url); +} + +export class CloudEnvironmentLinkError extends Data.TaggedError("CloudEnvironmentLinkError")<{ + readonly message: string; + readonly cause?: unknown; +}> {} + +export interface CloudEnvironmentRecordWithStatus { + readonly environment: RelayClientEnvironmentRecord; + readonly status: RelayEnvironmentStatusResponseType | null; + readonly statusError: string | null; +} + +const isRelayProtectedError = Schema.is(RelayProtectedError); +const isEnvironmentCloudApiError = Schema.is( + Schema.Union([ + EnvironmentHttpBadRequestError, + EnvironmentHttpUnauthorizedError, + EnvironmentHttpForbiddenError, + EnvironmentHttpConflictError, + EnvironmentHttpInternalServerError, + EnvironmentCloudEndpointUnavailableError, + ]), +); + +const MANAGED_ENDPOINT_PROVIDER_KIND = + "cloudflare_tunnel" satisfies RelayManagedEndpointProviderKind; + +function cloudEnvironmentLinkError(message: string) { + return (cause: unknown) => { + const environmentError = findEnvironmentCloudApiError(cause); + return new CloudEnvironmentLinkError({ + message: environmentError + ? `${message.replace(/[.:]$/, "")}: ${environmentError.message}` + : withDevCause(message, cause), + cause, + }); + }; +} + +function isDevRuntime(): boolean { + return typeof __DEV__ !== "undefined" && __DEV__; +} + +function causeMessage(cause: unknown): string | null { + if (cause instanceof Error && cause.message) { + return cause.message; + } + if (typeof cause === "object" && cause !== null) { + const record = cause as { readonly message?: unknown; readonly cause?: unknown }; + if (typeof record.message === "string" && record.message.length > 0) { + const nested = causeMessage(record.cause); + return nested ? `${record.message}: ${nested}` : record.message; + } + } + return null; +} + +function withDevCause(message: string, cause: unknown): string { + if (!isDevRuntime()) { + return message; + } + const detail = causeMessage(cause); + return detail ? `${message} (${detail})` : message; +} + +function relayProtectedErrorMessage(error: RelayProtectedErrorType): string { + switch (error._tag) { + case "RelayAuthInvalidError": + switch (error.reason) { + case "missing_bearer": + case "invalid_bearer": + return "Relay rejected the cloud session token."; + case "invalid_dpop": + return "Relay rejected the DPoP proof."; + case "not_authorized": + return "Relay rejected the authenticated request."; + } + case "RelayEnvironmentLinkProofExpiredError": + return "Relay rejected an expired environment link proof."; + case "RelayEnvironmentLinkProofInvalidError": + return `Relay rejected the environment link proof (${error.reason}).`; + case "RelayEnvironmentConnectNotAuthorizedError": + return "Relay rejected the environment connection request."; + case "RelayEnvironmentEndpointUnavailableError": + return `Relay could not reach the environment endpoint (${error.reason}).`; + case "RelayEnvironmentEndpointTimedOutError": + return "Relay timed out while contacting the environment endpoint."; + case "RelayEnvironmentLinkFailedError": + return `Relay could not link the environment (${error.reason}).`; + case "RelayEnvironmentLinkUnavailableError": + return `Relay cannot provision the managed endpoint (${error.reason}).`; + case "RelayAgentActivityPublishProofExpiredError": + return "Relay rejected an expired agent activity publish proof."; + case "RelayAgentActivityPublishProofInvalidError": + return `Relay rejected the agent activity publish proof (${error.reason}).`; + case "RelayInternalError": + return `Relay encountered an internal error (${error.reason}, trace ${error.traceId}).`; + } +} + +function decodedRelayClientError(message: string) { + return (cause: unknown) => { + const relayError = findRelayProtectedError(cause); + const detail = relayError ? relayProtectedErrorMessage(relayError) : null; + return new CloudEnvironmentLinkError({ + message: detail ? `${message}: ${detail}` : message, + cause, + }); + }; +} + +function findRelayProtectedError(cause: unknown): RelayProtectedErrorType | null { + if (isRelayProtectedError(cause)) { + return cause; + } + if (typeof cause !== "object" || cause === null) { + return null; + } + return "cause" in cause ? findRelayProtectedError(cause.cause) : null; +} + +function findEnvironmentCloudApiError(cause: unknown): { readonly message: string } | null { + if (isEnvironmentCloudApiError(cause)) { + return cause; + } + if (typeof cause !== "object" || cause === null) { + return null; + } + return "cause" in cause ? findEnvironmentCloudApiError(cause.cause) : null; +} + +function requireRelayUrl(): Effect.Effect { + const relayUrl = readRelayUrl(); + return relayUrl + ? Effect.succeed(relayUrl) + : Effect.fail(new CloudEnvironmentLinkError({ message: "Relay URL is not configured." })); +} + +function endpointOrigin(httpBaseUrl: string) { + const url = new URL(httpBaseUrl); + return { + localHttpHost: "127.0.0.1", + localHttpPort: Number(url.port || (url.protocol === "https:" ? 443 : 80)), + }; +} + +function ensureLinkedEnvironmentMatches(input: { + readonly expectedEnvironmentId: string; + readonly expectedProviderKind: RelayManagedEndpointProviderKind; + readonly link: RelayEnvironmentLinkResponseType; +}): Effect.Effect { + if (input.link.environmentId !== input.expectedEnvironmentId) { + return new CloudEnvironmentLinkError({ + message: "Relay returned credentials for a different environment.", + }); + } + if (input.link.endpoint.providerKind !== input.expectedProviderKind) { + return new CloudEnvironmentLinkError({ + message: "Relay returned credentials for a different endpoint provider.", + }); + } + return Effect.void; +} + +function endpointMatches( + left: RelayClientEnvironmentRecord["endpoint"], + right: RelayClientEnvironmentRecord["endpoint"], +): boolean { + return ( + left.httpBaseUrl === right.httpBaseUrl && + left.wsBaseUrl === right.wsBaseUrl && + left.providerKind === right.providerKind + ); +} + +function ensureStatusMatchesEnvironment(input: { + readonly environment: RelayClientEnvironmentRecord; + readonly status: RelayEnvironmentStatusResponseType; +}): Effect.Effect { + if (input.status.environmentId !== input.environment.environmentId) { + return new CloudEnvironmentLinkError({ + message: "Relay returned status for a different environment.", + }); + } + if (!endpointMatches(input.status.endpoint, input.environment.endpoint)) { + return new CloudEnvironmentLinkError({ + message: "Relay returned status for a different endpoint.", + }); + } + if ( + input.status.descriptor && + input.status.descriptor.environmentId !== input.environment.environmentId + ) { + return new CloudEnvironmentLinkError({ + message: "Relay returned status descriptor for a different environment.", + }); + } + return Effect.void; +} + +function ensureConnectEndpointMatchesEnvironment(input: { + readonly environment: RelayClientEnvironmentRecord; + readonly connect: RelayEnvironmentConnectResponseType; +}): Effect.Effect { + if (!endpointMatches(input.connect.endpoint, input.environment.endpoint)) { + return new CloudEnvironmentLinkError({ + message: "Relay returned credentials for a different endpoint.", + }); + } + return Effect.void; +} + +export function linkEnvironmentToCloud(input: { + readonly connection: SavedRemoteConnection; + readonly clerkToken: string; +}): Effect.Effect { + return Effect.gen(function* () { + if (!input.connection.bearerToken) { + return yield* new CloudEnvironmentLinkError({ + message: "Only a locally paired bearer connection can be linked to the cloud.", + }); + } + const localBearerToken = input.connection.bearerToken; + const relayUrl = yield* requireRelayUrl(); + const relayClient = yield* ManagedRelayClient; + const deviceId = yield* Effect.tryPromise({ + try: () => loadOrCreateAgentAwarenessDeviceId(), + catch: cloudEnvironmentLinkError("Could not load the mobile device id."), + }); + const preferences = yield* Effect.tryPromise({ + try: () => loadPreferences(), + catch: cloudEnvironmentLinkError("Could not load mobile notification preferences."), + }); + const liveActivitiesEnabled = preferences.liveActivitiesEnabled !== false; + const challenge = yield* relayClient + .createEnvironmentLinkChallenge({ + clerkToken: input.clerkToken, + payload: { + notificationsEnabled: true, + liveActivitiesEnabled, + managedTunnelsEnabled: true, + }, + }) + .pipe( + Effect.mapError( + decodedRelayClientError(`${relayUrl}/v1/client/environment-link-challenges failed`), + ), + ); + const environmentClient = yield* makeEnvironmentHttpApiClient(input.connection.httpBaseUrl); + const proof = yield* environmentClient.cloud + .linkProof({ + headers: { authorization: `Bearer ${localBearerToken}` }, + payload: { + challenge: challenge.challenge, + relayIssuer: relayUrl, + endpoint: { + httpBaseUrl: input.connection.httpBaseUrl, + wsBaseUrl: input.connection.wsBaseUrl, + providerKind: MANAGED_ENDPOINT_PROVIDER_KIND, + }, + origin: endpointOrigin(input.connection.httpBaseUrl), + }, + }) + .pipe(Effect.mapError(cloudEnvironmentLinkError("Could not obtain environment link proof."))); + const link = yield* relayClient + .linkEnvironment({ + clerkToken: input.clerkToken, + payload: { + deviceId, + proof, + notificationsEnabled: true, + liveActivitiesEnabled, + managedTunnelsEnabled: true, + }, + }) + .pipe( + Effect.mapError(decodedRelayClientError(`${relayUrl}/v1/client/environment-links failed`)), + ); + yield* ensureLinkedEnvironmentMatches({ + expectedEnvironmentId: input.connection.environmentId, + expectedProviderKind: MANAGED_ENDPOINT_PROVIDER_KIND, + link, + }); + + yield* environmentClient.cloud + .relayConfig({ + headers: { authorization: `Bearer ${localBearerToken}` }, + payload: { + relayUrl, + relayIssuer: link.relayIssuer, + cloudUserId: link.cloudUserId, + environmentCredential: link.environmentCredential, + cloudMintPublicKey: link.cloudMintPublicKey, + endpointRuntime: link.endpointRuntime, + }, + }) + .pipe( + Effect.mapError(cloudEnvironmentLinkError("Could not configure environment relay access.")), + ); + }); +} + +export function listCloudEnvironments(input: { + readonly clerkToken: string; +}): Effect.Effect< + ReadonlyArray, + CloudEnvironmentLinkError, + ManagedRelayClient +> { + return Effect.gen(function* () { + const relayUrl = yield* requireRelayUrl(); + const relayClient = yield* ManagedRelayClient; + + return yield* relayClient + .listEnvironments({ + clerkToken: input.clerkToken, + }) + .pipe(Effect.mapError(decodedRelayClientError(`${relayUrl}/v1/environments failed`))); + }); +} + +export function getCloudEnvironmentStatus(input: { + readonly clerkToken: string; + readonly environment: RelayClientEnvironmentRecord; + readonly relayScopes?: ReadonlyArray; +}): Effect.Effect< + RelayEnvironmentStatusResponseType, + CloudEnvironmentLinkError, + ManagedRelayClient +> { + return Effect.gen(function* () { + const relayUrl = yield* requireRelayUrl(); + const relayClient = yield* ManagedRelayClient; + const status = yield* relayClient + .getEnvironmentStatus({ + clerkToken: input.clerkToken, + scopes: input.relayScopes ?? [RelayEnvironmentStatusScope], + environmentId: input.environment.environmentId, + }) + .pipe( + Effect.mapError( + decodedRelayClientError( + `${relayUrl}/v1/environments/${encodeURIComponent(input.environment.environmentId)}/status failed`, + ), + ), + ); + yield* ensureStatusMatchesEnvironment({ environment: input.environment, status }); + return status; + }); +} + +export function cloudEnvironmentsPendingStatus( + environments: ReadonlyArray, +): ReadonlyArray { + return environments.map((environment) => ({ + environment, + status: null, + statusError: "Checking status...", + })); +} + +export function loadCloudEnvironmentStatuses(input: { + readonly clerkToken: string; + readonly environments: ReadonlyArray; +}): Effect.Effect< + ReadonlyArray, + CloudEnvironmentLinkError, + ManagedRelayClient +> { + return Effect.forEach( + input.environments, + (environment) => + getCloudEnvironmentStatus({ + clerkToken: input.clerkToken, + environment, + relayScopes: RELAY_STATUS_AND_CONNECT_SCOPES, + }).pipe( + Effect.match({ + onFailure: (error) => ({ + environment, + status: null, + statusError: error.message, + }), + onSuccess: (status) => ({ + environment, + status, + statusError: null, + }), + }), + ), + { concurrency: "unbounded" }, + ); +} + +export function listCloudEnvironmentsWithStatus(input: { + readonly clerkToken: string; +}): Effect.Effect< + ReadonlyArray, + CloudEnvironmentLinkError, + ManagedRelayClient +> { + return Effect.gen(function* () { + const environments = yield* listCloudEnvironments(input); + return yield* loadCloudEnvironmentStatuses({ + clerkToken: input.clerkToken, + environments, + }); + }); +} + +export function connectCloudEnvironment(input: { + readonly clerkToken: string; + readonly environment: RelayClientEnvironmentRecord; +}): Effect.Effect< + SavedRemoteConnection, + CloudEnvironmentLinkError, + HttpClient.HttpClient | ManagedRelayClient | ManagedRelayDpopSigner +> { + return Effect.gen(function* () { + const relayUrl = yield* requireRelayUrl(); + const relayClient = yield* ManagedRelayClient; + + const deviceId = yield* Effect.tryPromise({ + try: () => loadOrCreateAgentAwarenessDeviceId(), + catch: cloudEnvironmentLinkError("Could not load the mobile device id."), + }); + const connect = yield* relayClient + .connectEnvironment({ + clerkToken: input.clerkToken, + scopes: [RelayEnvironmentConnectScope], + environmentId: input.environment.environmentId, + deviceId, + }) + .pipe( + Effect.mapError( + decodedRelayClientError( + `${relayUrl}/v1/environments/${encodeURIComponent(input.environment.environmentId)}/connect failed`, + ), + ), + ); + if (connect.environmentId !== input.environment.environmentId) { + return yield* new CloudEnvironmentLinkError({ + message: "Relay returned credentials for a different environment.", + }); + } + yield* ensureConnectEndpointMatchesEnvironment({ + environment: input.environment, + connect, + }); + + const descriptor = yield* fetchRemoteEnvironmentDescriptor({ + httpBaseUrl: connect.endpoint.httpBaseUrl, + }).pipe( + Effect.mapError( + cloudEnvironmentLinkError("Could not fetch the connected environment descriptor."), + ), + ); + if (descriptor.environmentId !== connect.environmentId) { + return yield* new CloudEnvironmentLinkError({ + message: "Connected endpoint descriptor does not match the selected environment.", + }); + } + const signer = yield* ManagedRelayDpopSigner; + const bootstrapDpop = yield* signer + .createProof({ + method: "POST", + url: new URL("/oauth/token", connect.endpoint.httpBaseUrl).toString(), + }) + .pipe(Effect.mapError(cloudEnvironmentLinkError("Could not create bootstrap DPoP proof."))); + const bootstrap = yield* exchangeRemoteDpopAccessToken({ + httpBaseUrl: connect.endpoint.httpBaseUrl, + credential: connect.credential, + dpopProof: bootstrapDpop, + clientMetadata: mobileAuthClientMetadata(), + }).pipe( + Effect.mapError( + cloudEnvironmentLinkError("Could not exchange a managed endpoint DPoP access token."), + ), + ); + const pairingUrl = new URL(connect.endpoint.httpBaseUrl); + pairingUrl.hash = new URLSearchParams([["token", connect.credential]]).toString(); + + return { + environmentId: descriptor.environmentId, + environmentLabel: descriptor.label, + pairingUrl: stripPairingTokenFromUrl(pairingUrl).toString(), + displayUrl: connect.endpoint.httpBaseUrl, + httpBaseUrl: connect.endpoint.httpBaseUrl, + wsBaseUrl: connect.endpoint.wsBaseUrl, + bearerToken: null, + authenticationMethod: "dpop", + dpopAccessToken: bootstrap.access_token, + }; + }); +} diff --git a/apps/mobile/src/features/cloud/managedRelayLayer.ts b/apps/mobile/src/features/cloud/managedRelayLayer.ts new file mode 100644 index 0000000000..0de43d049c --- /dev/null +++ b/apps/mobile/src/features/cloud/managedRelayLayer.ts @@ -0,0 +1,42 @@ +import { + managedRelayClientLayer, + ManagedRelayDpopSigner, + ManagedRelayDpopSignerError, +} from "@t3tools/client-runtime"; +import { RelayMobileClientId } from "@t3tools/contracts/relay"; +import * as Crypto from "effect/Crypto"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; + +import { createDpopProof, loadOrCreateDpopProofKeyPair } from "./dpop"; + +const mobileRelayDpopSignerLayer = Layer.effect( + ManagedRelayDpopSigner, + Effect.gen(function* () { + const crypto = yield* Crypto.Crypto; + return ManagedRelayDpopSigner.of({ + thumbprint: Effect.suspend(() => + loadOrCreateDpopProofKeyPair().pipe( + Effect.provideService(Crypto.Crypto, crypto), + Effect.map((proofKey) => proofKey.thumbprint), + Effect.mapError((cause) => new ManagedRelayDpopSignerError({ cause })), + ), + ), + createProof: (input) => + Effect.gen(function* () { + const proofKey = yield* loadOrCreateDpopProofKeyPair().pipe( + Effect.provideService(Crypto.Crypto, crypto), + ); + return yield* createDpopProof({ ...input, proofKey }).pipe( + Effect.provideService(Crypto.Crypto, crypto), + Effect.map((proof) => proof.proof), + ); + }).pipe(Effect.mapError((cause) => new ManagedRelayDpopSignerError({ cause }))), + }); + }), +); + +export const mobileManagedRelayClientLayer = (relayUrl: string) => + managedRelayClientLayer({ relayUrl, clientId: RelayMobileClientId }).pipe( + Layer.provideMerge(mobileRelayDpopSignerLayer), + ); diff --git a/apps/mobile/src/features/cloud/useNativeClerkAuthModal.ts b/apps/mobile/src/features/cloud/useNativeClerkAuthModal.ts new file mode 100644 index 0000000000..3356642776 --- /dev/null +++ b/apps/mobile/src/features/cloud/useNativeClerkAuthModal.ts @@ -0,0 +1,134 @@ +import { getClerkInstance } from "@clerk/expo"; +import { tokenCache } from "@clerk/expo/token-cache"; +import * as Data from "effect/Data"; +import { useCallback, useRef } from "react"; +import type { TurboModule } from "react-native"; +import { TurboModuleRegistry } from "react-native"; + +const CLERK_CLIENT_JWT_KEY = "__clerk_client_jwt"; + +interface NativeClerkModule extends TurboModule { + readonly getClientToken?: () => Promise; + readonly presentAuth?: (options: { + readonly dismissable: boolean; + readonly mode: "signInOrUp"; + }) => Promise; +} + +interface NativeAuthResult { + readonly cancelled?: boolean; + readonly session?: { + readonly id?: string; + }; + readonly sessionId?: string; +} + +interface ClerkWithNativeSync { + readonly __internal_reloadInitialResources?: () => Promise; + readonly setActive?: (params: { readonly session: string }) => Promise; +} + +const NativeClerk = TurboModuleRegistry.get("ClerkExpo"); + +class NativeClerkAuthError extends Data.TaggedError("NativeClerkAuthError")<{ + readonly message: string; + readonly cause?: unknown; +}> {} + +async function syncNativeSession(sessionId: string): Promise { + const getClientToken = NativeClerk?.getClientToken; + let nativeClientToken: string | null = null; + if (getClientToken) { + try { + nativeClientToken = await getClientToken(); + } catch (cause) { + throw new NativeClerkAuthError({ + message: "Could not read native Clerk client token.", + cause, + }); + } + } + if (nativeClientToken) { + const saveToken = tokenCache?.saveToken; + if (saveToken) { + try { + await saveToken(CLERK_CLIENT_JWT_KEY, nativeClientToken); + } catch (cause) { + throw new NativeClerkAuthError({ + message: "Could not save native Clerk client token.", + cause, + }); + } + } + } + + const clerk = getClerkInstance(); + const clerkWithNativeSync = clerk as ClerkWithNativeSync; + const reloadInitialResources = clerkWithNativeSync.__internal_reloadInitialResources; + if (reloadInitialResources) { + try { + await reloadInitialResources(); + } catch (cause) { + throw new NativeClerkAuthError({ + message: "Could not reload Clerk resources after native auth.", + cause, + }); + } + } + const setActive = clerkWithNativeSync.setActive; + if (setActive) { + try { + await setActive({ session: sessionId }); + } catch (cause) { + throw new NativeClerkAuthError({ + message: "Could not activate native Clerk session.", + cause, + }); + } + } +} + +export function useNativeClerkAuthModal() { + const presentingRef = useRef(false); + + const presentAuth = useCallback(async (): Promise => { + if (presentingRef.current || !NativeClerk?.presentAuth) { + return; + } + + presentingRef.current = true; + const presentNativeAuth = NativeClerk.presentAuth; + try { + // Clerk's iOS AuthView is not inline. It presents this same native modal + // internally; call the presenter directly so Expo Router does not render + // an empty formSheet behind it. + let result: NativeAuthResult | null; + try { + result = await presentNativeAuth({ + dismissable: true, + mode: "signInOrUp", + }); + } catch (cause) { + throw new NativeClerkAuthError({ + message: "Native Clerk auth presentation failed.", + cause, + }); + } + const sessionId = result?.sessionId ?? result?.session?.id ?? null; + if (sessionId && !result?.cancelled) { + await syncNativeSession(sessionId); + } + } catch (error) { + if (__DEV__) { + console.error("[useNativeClerkAuthModal] presentAuth failed:", error); + } + } finally { + presentingRef.current = false; + } + }, []); + + return { + isAvailable: !!NativeClerk?.presentAuth, + presentAuth, + }; +} diff --git a/apps/mobile/src/lib/authClientMetadata.ts b/apps/mobile/src/lib/authClientMetadata.ts new file mode 100644 index 0000000000..b341c7b6bd --- /dev/null +++ b/apps/mobile/src/lib/authClientMetadata.ts @@ -0,0 +1,10 @@ +import type { AuthClientPresentationMetadata } from "@t3tools/contracts"; +import { Platform } from "react-native"; + +export function mobileAuthClientMetadata(): AuthClientPresentationMetadata { + return { + label: "T3 Code Mobile", + deviceType: "mobile", + ...(Platform.OS === "ios" ? { os: "iOS" } : Platform.OS === "android" ? { os: "Android" } : {}), + }; +} diff --git a/apps/mobile/src/lib/connection.test.ts b/apps/mobile/src/lib/connection.test.ts index ddd3a40eab..a11b7269a6 100644 --- a/apps/mobile/src/lib/connection.test.ts +++ b/apps/mobile/src/lib/connection.test.ts @@ -3,7 +3,7 @@ import { describe, expect, it, vi } from "vite-plus/test"; import { mobileAuthClientMetadata, redactPairingCredential } from "./connection"; vi.mock("./runtime", () => ({ - mobileRemoteHttpRuntime: { + mobileRuntime: { runPromise: vi.fn(), }, })); diff --git a/apps/mobile/src/lib/connection.ts b/apps/mobile/src/lib/connection.ts index 8d87fda09c..8500a80873 100644 --- a/apps/mobile/src/lib/connection.ts +++ b/apps/mobile/src/lib/connection.ts @@ -1,11 +1,14 @@ -import { type AuthClientPresentationMetadata, EnvironmentId } from "@t3tools/contracts"; +import { EnvironmentId } from "@t3tools/contracts"; import { bootstrapRemoteBearerSession, fetchRemoteEnvironmentDescriptor, } from "@t3tools/client-runtime"; import { resolveRemotePairingTarget, stripPairingTokenFromUrl } from "@t3tools/shared/remote"; -import { Platform } from "react-native"; -import { mobileRemoteHttpRuntime } from "./runtime"; +import * as Effect from "effect/Effect"; +import { mobileAuthClientMetadata } from "./authClientMetadata"; +import { mobileRuntime } from "./runtime"; + +export { mobileAuthClientMetadata } from "./authClientMetadata"; export interface RemoteConnectionInput { readonly pairingUrl: string; @@ -18,7 +21,9 @@ export interface SavedRemoteConnection { readonly displayUrl: string; readonly httpBaseUrl: string; readonly wsBaseUrl: string; - readonly bearerToken: string; + readonly bearerToken: string | null; + readonly authenticationMethod?: "bearer" | "dpop"; + readonly dpopAccessToken?: string; } export type RemoteClientConnectionState = @@ -37,14 +42,6 @@ export function redactPairingCredential(pairingUrl: string): string { } } -export function mobileAuthClientMetadata(): AuthClientPresentationMetadata { - return { - label: "T3 Code Mobile", - deviceType: "mobile", - ...(Platform.OS === "ios" ? { os: "iOS" } : Platform.OS === "android" ? { os: "Android" } : {}), - }; -} - export async function bootstrapRemoteConnection( input: RemoteConnectionInput, ): Promise { @@ -52,18 +49,20 @@ export async function bootstrapRemoteConnection( pairingUrl: input.pairingUrl, }); - const descriptor = await mobileRemoteHttpRuntime.runPromise( - fetchRemoteEnvironmentDescriptor({ - httpBaseUrl: target.httpBaseUrl, - }), - ); - - const bootstrap = await mobileRemoteHttpRuntime.runPromise( - bootstrapRemoteBearerSession({ - httpBaseUrl: target.httpBaseUrl, - credential: target.credential, - clientMetadata: mobileAuthClientMetadata(), - }), + const { descriptor, bootstrap } = await mobileRuntime.runPromise( + Effect.all( + { + descriptor: fetchRemoteEnvironmentDescriptor({ + httpBaseUrl: target.httpBaseUrl, + }), + bootstrap: bootstrapRemoteBearerSession({ + httpBaseUrl: target.httpBaseUrl, + credential: target.credential, + clientMetadata: mobileAuthClientMetadata(), + }), + }, + { concurrency: "unbounded" }, + ), ); return { @@ -74,5 +73,6 @@ export async function bootstrapRemoteConnection( httpBaseUrl: target.httpBaseUrl, wsBaseUrl: target.wsBaseUrl, bearerToken: bootstrap.access_token, + authenticationMethod: "bearer", }; } diff --git a/apps/mobile/src/lib/runtime.ts b/apps/mobile/src/lib/runtime.ts index f50ddf6df8..22b8b4fa55 100644 --- a/apps/mobile/src/lib/runtime.ts +++ b/apps/mobile/src/lib/runtime.ts @@ -1,5 +1,26 @@ +import Constants from "expo-constants"; +import * as Layer from "effect/Layer"; import * as ManagedRuntime from "effect/ManagedRuntime"; import { remoteHttpClientLayer } from "@t3tools/client-runtime"; -export const mobileRemoteHttpRuntime = ManagedRuntime.make(remoteHttpClientLayer(fetch)); +import { mobileCryptoLayer } from "../features/cloud/dpop"; +import { mobileManagedRelayClientLayer } from "../features/cloud/managedRelayLayer"; + +function configuredRelayUrl(): string { + const relay = Constants.expoConfig?.extra?.relay as { readonly url?: string | null } | undefined; + const value = relay?.url?.trim(); + return value ? value.replace(/\/+$/g, "") : "http://relay.invalid"; +} + +const mobileHttpClientLayer = remoteHttpClientLayer(fetch); + +export const mobileRuntime = ManagedRuntime.make( + Layer.mergeAll( + mobileHttpClientLayer, + mobileCryptoLayer, + mobileManagedRelayClientLayer(configuredRelayUrl()).pipe( + Layer.provide(Layer.mergeAll(mobileHttpClientLayer, mobileCryptoLayer)), + ), + ), +); diff --git a/apps/mobile/src/lib/storage.ts b/apps/mobile/src/lib/storage.ts index e2eb173fac..41702b02ff 100644 --- a/apps/mobile/src/lib/storage.ts +++ b/apps/mobile/src/lib/storage.ts @@ -9,6 +9,7 @@ import type { SavedRemoteConnection } from "./connection"; const CONNECTIONS_KEY = "t3code.connections"; const PREFERENCES_KEY = "t3code.preferences"; +const AGENT_AWARENESS_DEVICE_ID_KEY = "t3code.agent-awareness.device-id"; const SHELL_SNAPSHOT_CACHE_SCHEMA_VERSION = 1; const SHELL_SNAPSHOT_CACHE_DIRECTORY = "shell-snapshots"; @@ -20,6 +21,7 @@ export interface CachedShellSnapshot { } export interface MobilePreferences { + readonly liveActivitiesEnabled?: boolean; readonly terminalFontSize?: number; } @@ -133,7 +135,12 @@ export async function loadSavedConnections(): Promise !!c.environmentId && !!c.bearerToken?.trim()), + Arr.filter( + (c) => + !!c.environmentId && + (!!c.bearerToken?.trim() || + (c.authenticationMethod === "dpop" && !!c.dpopAccessToken?.trim())), + ), ); } @@ -164,11 +171,19 @@ export async function loadPreferences(): Promise { return {}; } + const preferences: { + liveActivitiesEnabled?: boolean; + terminalFontSize?: number; + } = {}; + + if (typeof parsed.liveActivitiesEnabled === "boolean") { + preferences.liveActivitiesEnabled = parsed.liveActivitiesEnabled; + } if (typeof parsed.terminalFontSize === "number") { - return { terminalFontSize: parsed.terminalFontSize }; + preferences.terminalFontSize = parsed.terminalFontSize; } - return {}; + return preferences; } export async function savePreferencesPatch( @@ -182,3 +197,20 @@ export async function savePreferencesPatch( await writeStorageItem(PREFERENCES_KEY, JSON.stringify(next)); return next; } + +export async function loadOrCreateAgentAwarenessDeviceId(): Promise { + const existing = await readStorageItem(AGENT_AWARENESS_DEVICE_ID_KEY); + if (existing?.trim()) { + return existing; + } + + const { uuidv4 } = await import("./uuid"); + const deviceId = uuidv4(); + await writeStorageItem(AGENT_AWARENESS_DEVICE_ID_KEY, deviceId); + return deviceId; +} + +export async function loadAgentAwarenessDeviceId(): Promise { + const existing = await readStorageItem(AGENT_AWARENESS_DEVICE_ID_KEY); + return existing?.trim() ? existing : null; +} diff --git a/apps/mobile/src/state/use-remote-environment-registry.test.ts b/apps/mobile/src/state/use-remote-environment-registry.test.ts new file mode 100644 index 0000000000..bb2ab1c9d3 --- /dev/null +++ b/apps/mobile/src/state/use-remote-environment-registry.test.ts @@ -0,0 +1,301 @@ +import { describe, expect, it } from "@effect/vitest"; +import { EnvironmentId } from "@t3tools/contracts"; +import { ManagedRelayDpopSigner } from "@t3tools/client-runtime"; +import * as Effect from "effect/Effect"; +import { beforeEach, vi } from "vitest"; + +const mocks = vi.hoisted(() => { + const environmentConnection = { + ensureBootstrapped: vi.fn(() => Promise.resolve()), + dispose: vi.fn(() => Promise.resolve()), + }; + const sessionConnection = { + dispose: vi.fn(() => Promise.resolve()), + }; + return { + environmentConnection, + sessionConnection, + createEnvironmentConnection: vi.fn(() => environmentConnection), + createKnownEnvironment: vi.fn((input: unknown) => input), + createWsRpcClient: vi.fn(() => ({ rpc: true })), + wsTransportConstructor: vi.fn(), + resolveRemoteWebSocketConnectionUrl: vi.fn(() => ({ _tag: "remote-ws-url-effect" })), + resolveRemoteDpopWebSocketConnectionUrl: vi.fn(), + remoteEndpointUrl: vi.fn((baseUrl: string, path: string) => new URL(path, baseUrl).toString()), + createDpopProof: vi.fn(), + bootstrapRemoteConnection: vi.fn(), + clearCachedShellSnapshot: vi.fn(() => Promise.resolve()), + clearSavedConnection: vi.fn(() => Promise.resolve()), + saveConnection: vi.fn(() => Promise.resolve()), + saveCachedShellSnapshot: vi.fn(() => Promise.resolve()), + mobileRunPromise: vi.fn((_effect?: unknown) => + Promise.resolve("wss://desktop.example/ws?wsTicket=token"), + ), + removeEnvironmentSession: vi.fn(() => null), + setEnvironmentSession: vi.fn(), + notifyEnvironmentConnectionListeners: vi.fn(), + stopAgentAwarenessForEnvironment: vi.fn(), + startAgentAwarenessForEnvironment: vi.fn(), + shellSnapshotInvalidate: vi.fn(), + shellSnapshotMarkPending: vi.fn(), + environmentRuntimeInvalidate: vi.fn(), + environmentRuntimePatch: vi.fn(), + clearCachedShellSnapshotMetadata: vi.fn(), + invalidateSourceControlDiscoveryForEnvironment: vi.fn(), + terminalSessionInvalidateEnvironment: vi.fn(), + subscribeTerminalMetadata: vi.fn(() => vi.fn()), + terminalDebugLog: vi.fn(), + WsTransport: function WsTransport(...args: ReadonlyArray) { + mocks.wsTransportConstructor(...args); + }, + }; +}); + +vi.mock("react-native", () => ({ + Alert: { + alert: vi.fn(), + }, +})); + +vi.mock("@t3tools/client-runtime", async (importOriginal) => { + const actual = await importOriginal(); + return { + ...actual, + WsTransport: mocks.WsTransport, + createEnvironmentConnection: mocks.createEnvironmentConnection, + createKnownEnvironment: mocks.createKnownEnvironment, + createWsRpcClient: mocks.createWsRpcClient, + remoteEndpointUrl: mocks.remoteEndpointUrl, + resolveRemoteDpopWebSocketConnectionUrl: mocks.resolveRemoteDpopWebSocketConnectionUrl, + resolveRemoteWebSocketConnectionUrl: mocks.resolveRemoteWebSocketConnectionUrl, + }; +}); + +vi.mock("../lib/connection", () => ({ + bootstrapRemoteConnection: mocks.bootstrapRemoteConnection, +})); + +vi.mock("../lib/storage", () => ({ + clearCachedShellSnapshot: mocks.clearCachedShellSnapshot, + clearSavedConnection: mocks.clearSavedConnection, + loadCachedShellSnapshot: vi.fn(() => Promise.resolve(null)), + loadSavedConnections: vi.fn(() => Promise.resolve([])), + saveCachedShellSnapshot: mocks.saveCachedShellSnapshot, + saveConnection: mocks.saveConnection, +})); + +vi.mock("../lib/runtime", () => ({ + mobileRuntime: { + runPromise: mocks.mobileRunPromise, + }, +})); + +vi.mock("./environment-session-registry", () => ({ + drainEnvironmentSessions: vi.fn(() => []), + notifyEnvironmentConnectionListeners: mocks.notifyEnvironmentConnectionListeners, + removeEnvironmentSession: mocks.removeEnvironmentSession, + setEnvironmentSession: mocks.setEnvironmentSession, +})); + +vi.mock("../features/agent-awareness/shellLiveActivitySync", () => ({ + startAgentAwarenessForEnvironment: mocks.startAgentAwarenessForEnvironment, + stopAgentAwarenessForEnvironment: mocks.stopAgentAwarenessForEnvironment, + stopAllAgentAwareness: vi.fn(), +})); + +vi.mock("../features/terminal/terminalDebugLog", () => ({ + terminalDebugLog: mocks.terminalDebugLog, +})); + +vi.mock("./use-environment-runtime", () => ({ + environmentRuntimeManager: { + invalidate: mocks.environmentRuntimeInvalidate, + patch: mocks.environmentRuntimePatch, + }, + useEnvironmentRuntimeStates: vi.fn(() => ({})), +})); + +vi.mock("./use-shell-snapshot", () => ({ + clearCachedShellSnapshotMetadata: mocks.clearCachedShellSnapshotMetadata, + hydrateCachedShellSnapshot: vi.fn(), + markShellSnapshotLive: vi.fn(), + shellSnapshotManager: { + applyEvent: vi.fn(), + invalidate: mocks.shellSnapshotInvalidate, + markPending: mocks.shellSnapshotMarkPending, + syncSnapshot: vi.fn(), + }, +})); + +vi.mock("./use-source-control-discovery", () => ({ + invalidateSourceControlDiscoveryForEnvironment: + mocks.invalidateSourceControlDiscoveryForEnvironment, + resetSourceControlDiscoveryState: vi.fn(), +})); + +vi.mock("./use-terminal-session", () => ({ + subscribeTerminalMetadata: mocks.subscribeTerminalMetadata, + terminalSessionManager: { + invalidate: vi.fn(), + invalidateEnvironment: mocks.terminalSessionInvalidateEnvironment, + }, +})); + +import { connectSavedEnvironment, disconnectEnvironment } from "./use-remote-environment-registry"; + +const environmentId = EnvironmentId.make("env-mobile-test"); + +const connection = { + environmentId, + environmentLabel: "Mobile Test Desktop", + pairingUrl: "https://desktop.example/", + displayUrl: "https://desktop.example/", + httpBaseUrl: "https://desktop.example/", + wsBaseUrl: "wss://desktop.example/", + bearerToken: "remote-access-token", +} as const; + +describe("mobile remote environment registry effects", () => { + beforeEach(() => { + vi.clearAllMocks(); + mocks.createEnvironmentConnection.mockReturnValue(mocks.environmentConnection); + mocks.environmentConnection.ensureBootstrapped.mockResolvedValue(undefined); + mocks.environmentConnection.dispose.mockResolvedValue(undefined); + mocks.sessionConnection.dispose.mockResolvedValue(undefined); + mocks.removeEnvironmentSession.mockReturnValue(null); + mocks.mobileRunPromise.mockResolvedValue("wss://desktop.example/ws?wsTicket=token"); + mocks.createDpopProof.mockReturnValue(Effect.succeed("dpop-proof")); + mocks.resolveRemoteDpopWebSocketConnectionUrl.mockReturnValue( + Effect.succeed("wss://desktop.example/ws?wsTicket=dpop-token"), + ); + }); + + it.effect("connects a saved managed endpoint environment through Effect-wrapped APIs", () => + Effect.gen(function* () { + yield* connectSavedEnvironment(connection); + + expect(mocks.saveConnection).toHaveBeenCalledWith(connection); + expect(mocks.wsTransportConstructor).toHaveBeenCalledTimes(1); + expect(mocks.createEnvironmentConnection).toHaveBeenCalledTimes(1); + expect(mocks.setEnvironmentSession).toHaveBeenCalledWith( + connection.environmentId, + expect.objectContaining({ + connection: mocks.environmentConnection, + }), + ); + expect(mocks.subscribeTerminalMetadata).toHaveBeenCalledWith( + expect.objectContaining({ environmentId: connection.environmentId }), + ); + expect(mocks.startAgentAwarenessForEnvironment).toHaveBeenCalledWith(connection); + expect(mocks.environmentConnection.ensureBootstrapped).toHaveBeenCalledTimes(1); + }), + ); + + it.effect("uses DPoP-bound admission for a managed DPoP connection", () => + Effect.gen(function* () { + const dpopConnection = { + ...connection, + bearerToken: null, + authenticationMethod: "dpop", + dpopAccessToken: "environment-dpop-token", + } as const; + mocks.mobileRunPromise.mockImplementationOnce((effect?: unknown) => + Effect.runPromise( + (effect as Effect.Effect).pipe( + Effect.provideService( + ManagedRelayDpopSigner, + ManagedRelayDpopSigner.of({ + thumbprint: Effect.succeed("mobile-key-thumbprint"), + createProof: mocks.createDpopProof, + }), + ), + ), + ), + ); + + yield* connectSavedEnvironment(dpopConnection); + const openSocket = mocks.wsTransportConstructor.mock.calls[0]?.[0] as + | (() => Promise) + | undefined; + expect(openSocket).toBeDefined(); + yield* Effect.promise(() => openSocket!()); + + expect(mocks.createDpopProof).toHaveBeenCalledWith({ + method: "POST", + url: "https://desktop.example/api/auth/websocket-ticket", + accessToken: "environment-dpop-token", + }); + expect(mocks.resolveRemoteDpopWebSocketConnectionUrl).toHaveBeenCalledWith({ + wsBaseUrl: dpopConnection.wsBaseUrl, + httpBaseUrl: dpopConnection.httpBaseUrl, + accessToken: "environment-dpop-token", + dpopProof: "dpop-proof", + }); + expect(mocks.resolveRemoteWebSocketConnectionUrl).not.toHaveBeenCalled(); + }), + ); + + it.effect("fails interactive connects when the managed endpoint bootstrap fails", () => + Effect.gen(function* () { + mocks.environmentConnection.ensureBootstrapped.mockRejectedValueOnce( + new Error("bootstrap failed"), + ); + mocks.removeEnvironmentSession.mockReturnValueOnce(null).mockReturnValueOnce({ + connection: mocks.sessionConnection, + } as never); + + const result = yield* Effect.exit(connectSavedEnvironment(connection)); + + expect(result._tag).toBe("Failure"); + expect(mocks.environmentRuntimePatch).toHaveBeenCalledWith( + { environmentId: connection.environmentId }, + expect.any(Function), + ); + expect(mocks.sessionConnection.dispose).toHaveBeenCalledTimes(1); + expect(mocks.subscribeTerminalMetadata).not.toHaveBeenCalled(); + expect(mocks.startAgentAwarenessForEnvironment).not.toHaveBeenCalled(); + }), + ); + + it.effect("can suppress bootstrap failures during best-effort startup reconnect", () => + Effect.gen(function* () { + mocks.environmentConnection.ensureBootstrapped.mockRejectedValueOnce( + new Error("bootstrap failed"), + ); + mocks.removeEnvironmentSession.mockReturnValueOnce(null).mockReturnValueOnce({ + connection: mocks.sessionConnection, + } as never); + + yield* connectSavedEnvironment(connection, { + persist: false, + suppressBootstrapError: true, + }); + + expect(mocks.saveConnection).not.toHaveBeenCalled(); + expect(mocks.environmentConnection.ensureBootstrapped).toHaveBeenCalledTimes(1); + expect(mocks.sessionConnection.dispose).toHaveBeenCalledTimes(1); + expect(mocks.subscribeTerminalMetadata).not.toHaveBeenCalled(); + expect(mocks.startAgentAwarenessForEnvironment).not.toHaveBeenCalled(); + expect(mocks.environmentRuntimePatch).toHaveBeenCalledWith( + { environmentId: connection.environmentId }, + expect.any(Function), + ); + }), + ); + + it.effect("disconnects and removes persisted managed endpoint state when requested", () => + Effect.gen(function* () { + mocks.removeEnvironmentSession.mockReturnValue({ + connection: mocks.sessionConnection, + } as never); + + yield* disconnectEnvironment(connection.environmentId, { removeSaved: true }); + + expect(mocks.sessionConnection.dispose).toHaveBeenCalledTimes(1); + expect(mocks.stopAgentAwarenessForEnvironment).toHaveBeenCalledWith(connection.environmentId); + expect(mocks.clearSavedConnection).toHaveBeenCalledWith(connection.environmentId); + expect(mocks.clearCachedShellSnapshot).toHaveBeenCalledWith(connection.environmentId); + expect(mocks.clearCachedShellSnapshotMetadata).toHaveBeenCalledWith(connection.environmentId); + }), + ); +}); diff --git a/apps/mobile/src/state/use-remote-environment-registry.ts b/apps/mobile/src/state/use-remote-environment-registry.ts index 4e27cb27f8..97d95609a6 100644 --- a/apps/mobile/src/state/use-remote-environment-registry.ts +++ b/apps/mobile/src/state/use-remote-environment-registry.ts @@ -9,11 +9,16 @@ import { createKnownEnvironment, createWsRpcClient, EnvironmentConnectionState, + ManagedRelayDpopSigner, WsTransport, + remoteEndpointUrl, + resolveRemoteDpopWebSocketConnectionUrl, resolveRemoteWebSocketConnectionUrl, } from "@t3tools/client-runtime"; import type { EnvironmentId } from "@t3tools/contracts"; import * as Arr from "effect/Array"; +import * as Duration from "effect/Duration"; +import * as Effect from "effect/Effect"; import * as Order from "effect/Order"; import * as Option from "effect/Option"; import { pipe } from "effect/Function"; @@ -29,7 +34,7 @@ import { saveConnection, } from "../lib/storage"; import { appAtomRegistry } from "./atom-registry"; -import { mobileRemoteHttpRuntime } from "../lib/runtime"; +import { mobileRuntime } from "../lib/runtime"; import { drainEnvironmentSessions, notifyEnvironmentConnectionListeners, @@ -41,6 +46,11 @@ import { invalidateSourceControlDiscoveryForEnvironment, resetSourceControlDiscoveryState, } from "./use-source-control-discovery"; +import { + startAgentAwarenessForEnvironment, + stopAgentAwarenessForEnvironment, + stopAllAgentAwareness, +} from "../features/agent-awareness/shellLiveActivitySync"; import { environmentRuntimeManager, useEnvironmentRuntimeStates } from "./use-environment-runtime"; import { clearCachedShellSnapshotMetadata, @@ -153,223 +163,265 @@ function setEnvironmentConnectionStatus( })); } -function withTimeout( - promise: Promise, - timeoutMs: number, - timeoutMessage: string, -): Promise { - return new Promise((resolve, reject) => { - const timeoutId = setTimeout(() => { - reject(new Error(timeoutMessage)); - }, timeoutMs); - - promise.then( - (value) => { - clearTimeout(timeoutId); - resolve(value); - }, - (error: unknown) => { - clearTimeout(timeoutId); - reject(error); - }, - ); +function fromPromise(tryPromise: () => Promise): Effect.Effect { + return Effect.tryPromise({ + try: tryPromise, + catch: (cause) => cause, }); } -export async function disconnectEnvironment( +export function disconnectEnvironment( environmentId: EnvironmentId, options?: { readonly preserveShellSnapshot?: boolean; readonly removeSaved?: boolean; readonly preserveConnectionAttempt?: boolean; }, -) { - if (!options?.preserveConnectionAttempt) { - environmentConnectionAttempts.cancel(environmentId); - } +): Effect.Effect { + return Effect.gen(function* () { + if (!options?.preserveConnectionAttempt) { + environmentConnectionAttempts.cancel(environmentId); + } - const session = removeEnvironmentSession(environmentId); - notifyEnvironmentConnectionListeners(); - await session?.connection.dispose(); - terminalMetadataUnsubscribers.get(environmentId)?.(); - terminalMetadataUnsubscribers.delete(environmentId); - if (!options?.preserveShellSnapshot) { - shellSnapshotManager.invalidate({ environmentId }); - } - invalidateSourceControlDiscoveryForEnvironment(environmentId); - terminalSessionManager.invalidateEnvironment(environmentId); - environmentRuntimeManager.invalidate({ environmentId }); + const session = removeEnvironmentSession(environmentId); + notifyEnvironmentConnectionListeners(); + if (session) { + yield* fromPromise(() => session.connection.dispose()); + } + terminalMetadataUnsubscribers.get(environmentId)?.(); + terminalMetadataUnsubscribers.delete(environmentId); + stopAgentAwarenessForEnvironment(environmentId); + if (!options?.preserveShellSnapshot) { + shellSnapshotManager.invalidate({ environmentId }); + } + invalidateSourceControlDiscoveryForEnvironment(environmentId); + terminalSessionManager.invalidateEnvironment(environmentId); + environmentRuntimeManager.invalidate({ environmentId }); - if (options?.removeSaved) { - await clearSavedConnection(environmentId); - await clearCachedShellSnapshot(environmentId); - clearCachedShellSnapshotMetadata(environmentId); - removeSavedConnection(environmentId); - } + if (options?.removeSaved) { + yield* Effect.all( + [ + fromPromise(() => clearSavedConnection(environmentId)), + fromPromise(() => clearCachedShellSnapshot(environmentId)), + ], + { concurrency: 2 }, + ); + clearCachedShellSnapshotMetadata(environmentId); + removeSavedConnection(environmentId); + } + }); } -export async function connectSavedEnvironment( +export function connectSavedEnvironment( connection: SavedRemoteConnection, - options?: { readonly persist?: boolean }, -) { - const connectionAttempt = environmentConnectionAttempts.begin(connection.environmentId); - const isCurrentAttempt = connectionAttempt.isCurrent; + options?: { readonly persist?: boolean; readonly suppressBootstrapError?: boolean }, +): Effect.Effect { + return Effect.gen(function* () { + const connectionAttempt = environmentConnectionAttempts.begin(connection.environmentId); + const isCurrentAttempt = connectionAttempt.isCurrent; - await disconnectEnvironment(connection.environmentId, { - preserveShellSnapshot: true, - preserveConnectionAttempt: true, - }); - if (!isCurrentAttempt()) { - return; - } - - if (options?.persist !== false) { - await saveConnection(connection); + yield* disconnectEnvironment(connection.environmentId, { + preserveShellSnapshot: true, + preserveConnectionAttempt: true, + }); if (!isCurrentAttempt()) { return; } - } - upsertSavedConnection(connection); - setEnvironmentConnectionStatus(connection.environmentId, "connecting", null); - shellSnapshotManager.markPending({ environmentId: connection.environmentId }); - - const transport = new WsTransport( - () => - mobileRemoteHttpRuntime.runPromise( - resolveRemoteWebSocketConnectionUrl({ - wsBaseUrl: connection.wsBaseUrl, - httpBaseUrl: connection.httpBaseUrl, - bearerToken: connection.bearerToken, - }), - ), - { - onAttempt: () => { - if (!isCurrentAttempt()) { - return; - } - - environmentRuntimeManager.patch({ environmentId: connection.environmentId }, (previous) => { - const nextState = - previous.connectionState === "ready" || previous.connectionState === "reconnecting" - ? "reconnecting" - : "connecting"; - const keepSettledFailure = - previous.connectionState === "disconnected" && previous.connectionError !== null; - return { - ...previous, - connectionState: keepSettledFailure ? "disconnected" : nextState, - connectionError: keepSettledFailure ? previous.connectionError : null, - }; - }); - }, - onError: (message) => { - if (isCurrentAttempt()) { - setEnvironmentConnectionStatus(connection.environmentId, "disconnected", message); - } - }, - onClose: (details) => { - if (!isCurrentAttempt()) { - return; - } - - const reason = - details.reason.trim().length > 0 - ? details.reason - : details.code === 1000 - ? null - : `Remote connection closed (${details.code}).`; - setEnvironmentConnectionStatus(connection.environmentId, "disconnected", reason); - }, - }, - ); - - const client = createWsRpcClient(transport); - const environmentConnection = createEnvironmentConnection({ - kind: "saved", - knownEnvironment: { - ...createKnownEnvironment({ - id: connection.environmentId, - label: connection.environmentLabel, - source: "manual", - target: { - httpBaseUrl: connection.httpBaseUrl, - wsBaseUrl: connection.wsBaseUrl, - }, - }), - environmentId: connection.environmentId, - }, - client, - applyShellEvent: (event, environmentId) => { - if (isCurrentAttempt()) { - shellSnapshotManager.applyEvent({ environmentId }, event); - } - }, - syncShellSnapshot: (snapshot, environmentId) => { + if (options?.persist !== false) { + yield* fromPromise(() => saveConnection(connection)); if (!isCurrentAttempt()) { return; } - - shellSnapshotManager.syncSnapshot({ environmentId }, snapshot); - markShellSnapshotLive(environmentId); - void saveCachedShellSnapshot(environmentId, snapshot); - environmentRuntimeManager.patch({ environmentId }, (runtime) => ({ - ...runtime, - connectionState: "ready", - connectionError: null, - })); - }, - onShellResubscribe: (environmentId) => { - if (isCurrentAttempt()) { - shellSnapshotManager.markPending({ environmentId }); - } - }, - onConfigSnapshot: (serverConfig) => { - if (isCurrentAttempt()) { - environmentRuntimeManager.patch({ environmentId: connection.environmentId }, (runtime) => ({ - ...runtime, - serverConfig, - })); - } - }, - }); - - if (!isCurrentAttempt()) { - await environmentConnection.dispose(); - return; - } - - setEnvironmentSession(connection.environmentId, { - client, - connection: environmentConnection, - }); - terminalMetadataUnsubscribers.set( - connection.environmentId, - subscribeTerminalMetadata({ - environmentId: connection.environmentId, - client, - }), - ); - terminalDebugLog("registry:terminal-metadata-subscribed", { - environmentId: connection.environmentId, - }); - notifyEnvironmentConnectionListeners(); - - try { - await withTimeout( - environmentConnection.ensureBootstrapped(), - SAVED_CONNECTION_BOOTSTRAP_TIMEOUT_MS, - "Environment did not respond before the connection timeout.", - ); - } catch (error) { - if (isCurrentAttempt()) { - setEnvironmentConnectionStatus( - connection.environmentId, - "disconnected", - error instanceof Error ? error.message : "Failed to bootstrap remote connection.", - ); } - } + + upsertSavedConnection(connection); + setEnvironmentConnectionStatus(connection.environmentId, "connecting", null); + shellSnapshotManager.markPending({ environmentId: connection.environmentId }); + + const dpopAccessToken = + connection.authenticationMethod === "dpop" ? connection.dpopAccessToken : undefined; + const transport = new WsTransport( + () => + mobileRuntime.runPromise( + dpopAccessToken + ? Effect.gen(function* () { + const signer = yield* ManagedRelayDpopSigner; + const dpop = yield* signer.createProof({ + method: "POST", + url: remoteEndpointUrl(connection.httpBaseUrl, "/api/auth/websocket-ticket"), + accessToken: dpopAccessToken, + }); + return yield* resolveRemoteDpopWebSocketConnectionUrl({ + wsBaseUrl: connection.wsBaseUrl, + httpBaseUrl: connection.httpBaseUrl, + accessToken: dpopAccessToken, + dpopProof: dpop, + }); + }) + : resolveRemoteWebSocketConnectionUrl({ + wsBaseUrl: connection.wsBaseUrl, + httpBaseUrl: connection.httpBaseUrl, + bearerToken: connection.bearerToken ?? "", + }), + ), + { + onAttempt: () => { + if (!isCurrentAttempt()) { + return; + } + + environmentRuntimeManager.patch( + { environmentId: connection.environmentId }, + (previous) => { + const nextState = + previous.connectionState === "ready" || previous.connectionState === "reconnecting" + ? "reconnecting" + : "connecting"; + const keepSettledFailure = + previous.connectionState === "disconnected" && previous.connectionError !== null; + return { + ...previous, + connectionState: keepSettledFailure ? "disconnected" : nextState, + connectionError: keepSettledFailure ? previous.connectionError : null, + }; + }, + ); + }, + onError: (message) => { + if (isCurrentAttempt()) { + setEnvironmentConnectionStatus(connection.environmentId, "disconnected", message); + } + }, + onClose: (details) => { + if (!isCurrentAttempt()) { + return; + } + + const reason = + details.reason.trim().length > 0 + ? details.reason + : details.code === 1000 + ? null + : `Remote connection closed (${details.code}).`; + setEnvironmentConnectionStatus(connection.environmentId, "disconnected", reason); + }, + }, + ); + + const client = createWsRpcClient(transport); + const environmentConnection = createEnvironmentConnection({ + kind: "saved", + knownEnvironment: { + ...createKnownEnvironment({ + id: connection.environmentId, + label: connection.environmentLabel, + source: "manual", + target: { + httpBaseUrl: connection.httpBaseUrl, + wsBaseUrl: connection.wsBaseUrl, + }, + }), + environmentId: connection.environmentId, + }, + client, + applyShellEvent: (event, environmentId) => { + if (isCurrentAttempt()) { + shellSnapshotManager.applyEvent({ environmentId }, event); + } + }, + syncShellSnapshot: (snapshot, environmentId) => { + if (!isCurrentAttempt()) { + return; + } + + shellSnapshotManager.syncSnapshot({ environmentId }, snapshot); + markShellSnapshotLive(environmentId); + void saveCachedShellSnapshot(environmentId, snapshot).catch(() => undefined); + environmentRuntimeManager.patch({ environmentId }, (runtime) => ({ + ...runtime, + connectionState: "ready", + connectionError: null, + })); + }, + onShellResubscribe: (environmentId) => { + if (isCurrentAttempt()) { + shellSnapshotManager.markPending({ environmentId }); + } + }, + onConfigSnapshot: (serverConfig) => { + if (isCurrentAttempt()) { + environmentRuntimeManager.patch( + { environmentId: connection.environmentId }, + (runtime) => ({ + ...runtime, + serverConfig, + }), + ); + } + }, + }); + + if (!isCurrentAttempt()) { + yield* fromPromise(() => environmentConnection.dispose()); + return; + } + + setEnvironmentSession(connection.environmentId, { + client, + connection: environmentConnection, + }); + + const bootstrap = fromPromise(() => environmentConnection.ensureBootstrapped()).pipe( + Effect.timeoutOption(Duration.millis(SAVED_CONNECTION_BOOTSTRAP_TIMEOUT_MS)), + Effect.flatMap((result) => + Option.match(result, { + onNone: () => + Effect.fail(new Error("Environment did not respond before the connection timeout.")), + onSome: Effect.succeed, + }), + ), + Effect.tapError((error: unknown) => + isCurrentAttempt() + ? Effect.gen(function* () { + setEnvironmentConnectionStatus( + connection.environmentId, + "disconnected", + error instanceof Error ? error.message : "Failed to bootstrap remote connection.", + ); + const pendingSession = removeEnvironmentSession(connection.environmentId); + notifyEnvironmentConnectionListeners(); + if (pendingSession) { + yield* fromPromise(() => pendingSession.connection.dispose()); + } + }) + : Effect.void, + ), + ); + const bootstrapped = yield* options?.suppressBootstrapError + ? bootstrap.pipe( + Effect.as(true), + Effect.catch(() => Effect.succeed(false)), + ) + : bootstrap.pipe(Effect.as(true)); + + if (!bootstrapped || !isCurrentAttempt()) { + return; + } + + terminalMetadataUnsubscribers.set( + connection.environmentId, + subscribeTerminalMetadata({ + environmentId: connection.environmentId, + client, + }), + ); + terminalDebugLog("registry:terminal-metadata-subscribed", { + environmentId: connection.environmentId, + }); + startAgentAwarenessForEnvironment(connection); + notifyEnvironmentConnectionListeners(); + }); } const environmentsSortOrder = Order.mapInput( @@ -404,8 +456,9 @@ export function useRemoteEnvironmentBootstrap() { useEffect(() => { let cancelled = false; - void loadSavedConnections() - .then((connections) => { + void (async () => { + try { + const connections = await loadSavedConnections(); if (cancelled) { return; } @@ -418,34 +471,36 @@ export function useRemoteEnvironmentBootstrap() { setIsLoadingSavedConnection(false); - void (async () => { - await Promise.all( - connections.map(async (connection) => { - const cached = await loadCachedShellSnapshot(connection.environmentId); - if (!cancelled && cached) { - hydrateCachedShellSnapshot(cached); - } - }), - ); + await Promise.all( + connections.map(async (connection) => { + const cached = await loadCachedShellSnapshot(connection.environmentId); + if (!cancelled && cached) { + hydrateCachedShellSnapshot(cached); + } + }), + ); - if (cancelled) { - return; - } + if (cancelled) { + return; + } - await Promise.all( + await mobileRuntime.runPromise( + Effect.all( connections.map((connection) => connectSavedEnvironment(connection, { persist: false, + suppressBootstrapError: true, }), ), - ); - })(); - }) - .catch(() => { + { concurrency: "unbounded" }, + ), + ); + } catch { if (!cancelled) { setIsLoadingSavedConnection(false); } - }); + } + })(); return () => { cancelled = true; @@ -457,6 +512,7 @@ export function useRemoteEnvironmentBootstrap() { } terminalMetadataUnsubscribers.clear(); environmentConnectionAttempts.clear(); + stopAllAgentAwareness(); environmentRuntimeManager.invalidate(); shellSnapshotManager.invalidate(); resetSourceControlDiscoveryState(); @@ -538,7 +594,7 @@ export function useRemoteConnections() { const nextPairingUrl = pairingUrl ?? connectionPairingUrl; const connection = await bootstrapRemoteConnection({ pairingUrl: nextPairingUrl }); clearPendingConnectionError(); - await connectSavedEnvironment(connection); + await mobileRuntime.runPromise(connectSavedEnvironment(connection)); clearConnectionPairingUrl(); } catch (error) { setPendingConnectionError( @@ -577,7 +633,14 @@ export function useRemoteConnections() { if (!connection) { return; } - void connectSavedEnvironment(connection, { persist: false }); + void mobileRuntime + .runPromise( + connectSavedEnvironment(connection, { + persist: false, + suppressBootstrapError: true, + }), + ) + .catch(() => undefined); }, []); const onRemoveEnvironmentPress = useCallback((environmentId: EnvironmentId) => { @@ -595,7 +658,9 @@ export function useRemoteConnections() { text: "Remove", style: "destructive", onPress: () => { - void disconnectEnvironment(environmentId, { removeSaved: true }); + void mobileRuntime + .runPromise(disconnectEnvironment(environmentId, { removeSaved: true })) + .catch(() => undefined); }, }, ], diff --git a/apps/mobile/src/widgets/AgentActivity.tsx b/apps/mobile/src/widgets/AgentActivity.tsx new file mode 100644 index 0000000000..58c65bef2b --- /dev/null +++ b/apps/mobile/src/widgets/AgentActivity.tsx @@ -0,0 +1,313 @@ +import { HStack, Spacer, Text, VStack } from "@expo/ui/swift-ui"; +import { font, foregroundStyle, lineLimit, padding } from "@expo/ui/swift-ui/modifiers"; +import { + createLiveActivity, + type LiveActivityComponent, + type LiveActivityLayout, +} from "expo-widgets"; +import { formatAgentActivityUpdatedAtLabel } from "../features/agent-awareness/updatedAtLabel"; + +type LiveActivityEnvironment = Parameters>[1]; + +export type AgentActivityPhase = + | "starting" + | "running" + | "waiting_for_approval" + | "waiting_for_input" + | "completed" + | "failed" + | "stale"; + +export interface AgentActivityRowProps { + readonly environmentId: string; + readonly threadId: string; + readonly projectTitle: string; + readonly threadTitle: string; + readonly modelTitle: string; + readonly phase: AgentActivityPhase; + readonly status: string; + readonly updatedAt: string; + readonly deepLink: string; +} + +export interface AgentActivityProps { + readonly title: string; + readonly subtitle: string; + readonly activeCount: number; + readonly updatedAt: string; + readonly activities: ReadonlyArray; +} + +function AgentActivity( + props: AgentActivityProps, + environment: LiveActivityEnvironment, +): LiveActivityLayout { + "widget"; + + const row0 = props.activities[0]; + const row1 = props.activities[1]; + const row2 = props.activities[2]; + const updatedAt = formatAgentActivityUpdatedAtLabel(props.updatedAt); + const activeLabel = `${props.activeCount} active`; + const isLight = environment.colorScheme === "light"; + const primaryForeground = isLight ? "#0f172a" : "#ffffff"; + const secondaryForeground = isLight ? "#475569" : "#cbd5e1"; + const mutedForeground = isLight ? "#64748b" : "#94a3b8"; + const tint = environment.isLuminanceReduced + ? secondaryForeground + : row0?.phase === "waiting_for_approval" || row0?.phase === "waiting_for_input" + ? "#f97316" + : row0?.phase === "failed" + ? "#ef4444" + : "#14b8a6"; + + return { + banner: ( + + + + + {props.title} + + + {props.subtitle} + + + + + {activeLabel} + + + {row0 ? ( + + + + {row0.threadTitle} + + + {row0.projectTitle} - {row0.modelTitle} + + + + + {row0.status} + + + ) : null} + {row1 ? ( + + + + {row1.threadTitle} + + + {row1.projectTitle} - {row1.modelTitle} + + + + + {row1.status} + + + ) : null} + {row2 ? ( + + + + {row2.threadTitle} + + + {row2.projectTitle} - {row2.modelTitle} + + + + + {row2.status} + + + ) : null} + + Updated {updatedAt} + + + ), + bannerSmall: ( + + + + {props.title} + + + + {activeLabel} + + + {row0 ? ( + + + {row0.threadTitle} + + + {row0.projectTitle} - {row0.status} + + + ) : null} + + ), + compactLeading: ( + T3 + ), + compactTrailing: ( + + {activeLabel} + + ), + minimal: ( + T3 + ), + expandedLeading: ( + + + {activeLabel} + + + ), + expandedCenter: row0 ? ( + + + {row0.threadTitle} + + + {row0.projectTitle} - {row0.status} + + + ) : null, + expandedTrailing: ( + + Updated {updatedAt} + + ), + expandedBottom: ( + + {row0 ? ( + + + + {row0.threadTitle} + + + {row0.projectTitle} - {row0.modelTitle} + + + + + {row0.status} + + + ) : null} + {row1 ? ( + + + + {row1.threadTitle} + + + {row1.projectTitle} - {row1.modelTitle} + + + + + {row1.status} + + + ) : null} + {row2 ? ( + + + + {row2.threadTitle} + + + {row2.projectTitle} - {row2.modelTitle} + + + + + {row2.status} + + + ) : null} + + ), + }; +} + +export default createLiveActivity("AgentActivity", AgentActivity); diff --git a/apps/server/integration/OrchestrationEngineHarness.integration.ts b/apps/server/integration/OrchestrationEngineHarness.integration.ts index 837c32fc4f..4e3d483a9f 100644 --- a/apps/server/integration/OrchestrationEngineHarness.integration.ts +++ b/apps/server/integration/OrchestrationEngineHarness.integration.ts @@ -77,6 +77,7 @@ import * as VcsDriverRegistry from "../src/vcs/VcsDriverRegistry.ts"; import { VcsStatusBroadcaster } from "../src/vcs/VcsStatusBroadcaster.ts"; import { GitWorkflowService } from "../src/git/GitWorkflowService.ts"; import * as VcsProcess from "../src/vcs/VcsProcess.ts"; +import * as AgentAwarenessRelay from "../src/relay/AgentAwarenessRelay.ts"; const decodeCodexSettings = Schema.decodeEffect(CodexSettings); @@ -364,6 +365,12 @@ export const makeOrchestrationIntegrationHarness = ( drain: Effect.void, }), ), + Layer.provideMerge( + Layer.succeed(AgentAwarenessRelay.AgentAwarenessRelay, { + publishThread: () => Effect.void, + start: () => Effect.void, + }), + ), ); const layer = Layer.empty.pipe( Layer.provideMerge(runtimeServicesLayer), diff --git a/apps/server/src/auth/EnvironmentAuth.ts b/apps/server/src/auth/EnvironmentAuth.ts index abb1f7b792..d8c0079089 100644 --- a/apps/server/src/auth/EnvironmentAuth.ts +++ b/apps/server/src/auth/EnvironmentAuth.ts @@ -19,6 +19,7 @@ import { } from "@t3tools/contracts"; import { encodeOAuthScope } from "@t3tools/shared/oauthScope"; import * as Context from "effect/Context"; +import * as Crypto from "effect/Crypto"; import * as Data from "effect/Data"; import * as DateTime from "effect/DateTime"; import * as Duration from "effect/Duration"; @@ -31,6 +32,7 @@ import * as EnvironmentAuthPolicy from "./EnvironmentAuthPolicy.ts"; import * as PairingGrantStore from "./PairingGrantStore.ts"; import * as ServerSecretStore from "./ServerSecretStore.ts"; import * as SessionStore from "./SessionStore.ts"; +import { verifyRequestDpopProof } from "./dpop.ts"; import { layerConfig as SqlitePersistenceLayer } from "../persistence/Layers/Sqlite.ts"; export const DEFAULT_SESSION_SUBJECT = "cli-issued-session"; @@ -61,6 +63,7 @@ export interface AuthenticatedSession { readonly subject: string; readonly method: ServerAuthSessionMethod; readonly scopes: ReadonlyArray; + readonly proofKeyThumbprint?: string; readonly expiresAt?: DateTime.DateTime; } @@ -107,6 +110,9 @@ export interface EnvironmentAuthShape { credential: string, requestedScopes: ReadonlyArray | undefined, requestMetadata: AuthClientMetadata, + input?: { + readonly proofKeyThumbprint?: string; + }, ) => Effect.Effect< AuthAccessTokenResult, ServerAuthInvalidCredentialError | ServerAuthInvalidRequestError | ServerAuthInternalError @@ -116,6 +122,7 @@ export interface EnvironmentAuthShape { readonly label?: string; readonly scopes?: ReadonlyArray; readonly subject?: string; + readonly proofKeyThumbprint?: string; }) => Effect.Effect; readonly issuePairingCredential: ( input?: AuthCreatePairingCredentialInput, @@ -184,6 +191,7 @@ type BootstrapExchangeResult = { }; const AUTHORIZATION_PREFIX = "Bearer "; +const DPOP_AUTHORIZATION_PREFIX = "DPoP "; const WEBSOCKET_TICKET_QUERY_PARAM = "wsTicket"; const bySessionPriority = (left: AuthClientSession, right: AuthClientSession) => { @@ -245,10 +253,21 @@ function parseBearerToken(request: HttpServerRequest.HttpServerRequest): string return token.length > 0 ? token : null; } +function parseDpopToken(request: HttpServerRequest.HttpServerRequest): string | null { + const header = request.headers["authorization"]; + if (typeof header !== "string" || !header.startsWith(DPOP_AUTHORIZATION_PREFIX)) { + return null; + } + const token = header.slice(DPOP_AUTHORIZATION_PREFIX.length).trim(); + return token.length > 0 ? token : null; +} + export const make = Effect.fn("makeEnvironmentAuth")(function* () { const policy = yield* EnvironmentAuthPolicy.EnvironmentAuthPolicy; const bootstrapCredentials = yield* PairingGrantStore.PairingGrantStore; const sessions = yield* SessionStore.SessionStore; + const secretStore = yield* ServerSecretStore.ServerSecretStore; + const crypto = yield* Crypto.Crypto; const descriptor = yield* policy.getDescriptor(); const authenticateToken = ( @@ -270,6 +289,7 @@ export const make = Effect.fn("makeEnvironmentAuth")(function* () { subject: session.subject, method: session.method, scopes: session.scopes, + ...(session.proofKeyThumbprint ? { proofKeyThumbprint: session.proofKeyThumbprint } : {}), ...(session.expiresAt ? { expiresAt: session.expiresAt } : {}), })), mapSessionVerificationErrors, @@ -278,11 +298,43 @@ export const make = Effect.fn("makeEnvironmentAuth")(function* () { const authenticateRequest = (request: HttpServerRequest.HttpServerRequest) => { const cookieToken = request.cookies[sessions.cookieName]; const bearerToken = parseBearerToken(request); - const credential = cookieToken ?? bearerToken; + const dpopToken = parseDpopToken(request); + const credential = cookieToken ?? bearerToken ?? dpopToken; if (!credential) { return Effect.fail(new ServerAuthInvalidCredentialError({ reason: "missing_credential" })); } - return authenticateToken(credential); + return authenticateToken(credential).pipe( + Effect.flatMap((session) => { + if (session.proofKeyThumbprint) { + if (!dpopToken || dpopToken !== credential) { + return Effect.fail( + new ServerAuthInvalidCredentialError({ + reason: "invalid_credential", + cause: "DPoP-bound access token requires DPoP authorization.", + }), + ); + } + return verifyRequestDpopProof({ + request, + expectedThumbprint: session.proofKeyThumbprint, + expectedAccessToken: dpopToken, + }).pipe( + Effect.provideService(ServerSecretStore.ServerSecretStore, secretStore), + Effect.provideService(Crypto.Crypto, crypto), + Effect.as(session), + ); + } + if (dpopToken) { + return Effect.fail( + new ServerAuthInvalidCredentialError({ + reason: "invalid_credential", + cause: "DPoP authorization requires a proof-bound access token.", + }), + ); + } + return Effect.succeed(session); + }), + ); }; const getSessionState: EnvironmentAuthShape["getSessionState"] = (request) => @@ -349,8 +401,8 @@ export const make = Effect.fn("makeEnvironmentAuth")(function* () { ); const exchangeBootstrapCredentialForAccessToken: EnvironmentAuthShape["exchangeBootstrapCredentialForAccessToken"] = - (credential, requestedScopes, requestMetadata) => - bootstrapCredentials.consume(credential).pipe( + (credential, requestedScopes, requestMetadata, input) => + bootstrapCredentials.consume(credential, input).pipe( Effect.mapError(toBootstrapExchangeError), Effect.flatMap((grant) => Effect.gen(function* () { @@ -362,9 +414,15 @@ export const make = Effect.fn("makeEnvironmentAuth")(function* () { } return yield* sessions .issue({ - method: "bearer-access-token", + method: input?.proofKeyThumbprint ? "dpop-access-token" : "bearer-access-token", subject: grant.subject, scopes: grantedScopes, + ...(input?.proofKeyThumbprint + ? { + proofKeyThumbprint: input.proofKeyThumbprint, + ttl: Duration.hours(1), + } + : {}), client: { ...requestMetadata, ...(grant.label ? { label: grant.label } : {}), @@ -388,7 +446,7 @@ export const make = Effect.fn("makeEnvironmentAuth")(function* () { ({ access_token: session.token, issued_token_type: AuthAccessTokenType, - token_type: "Bearer", + token_type: input?.proofKeyThumbprint ? "DPoP" : "Bearer", expires_in: Math.max( 0, Math.floor( @@ -434,6 +492,7 @@ export const make = Effect.fn("makeEnvironmentAuth")(function* () { subject: input?.subject ?? "one-time-token", ...(input?.ttl ? { ttl: input.ttl } : {}), ...(input?.label ? { label: input.label } : {}), + ...(input?.proofKeyThumbprint ? { proofKeyThumbprint: input.proofKeyThumbprint } : {}), }); return { id: issued.id, diff --git a/apps/server/src/auth/EnvironmentAuthPolicy.ts b/apps/server/src/auth/EnvironmentAuthPolicy.ts index 3968ddb253..205c85b023 100644 --- a/apps/server/src/auth/EnvironmentAuthPolicy.ts +++ b/apps/server/src/auth/EnvironmentAuthPolicy.ts @@ -39,7 +39,7 @@ export const make = Effect.fn("makeEnvironmentAuthPolicy")(function* () { const descriptor: ServerAuthDescriptor = { policy, bootstrapMethods, - sessionMethods: ["browser-session-cookie", "bearer-access-token"], + sessionMethods: ["browser-session-cookie", "bearer-access-token", "dpop-access-token"], sessionCookieName: resolveSessionCookieName({ mode: config.mode, port: config.port, diff --git a/apps/server/src/auth/PairingGrantStore.test.ts b/apps/server/src/auth/PairingGrantStore.test.ts index 0c33a753f7..3861b4fc78 100644 --- a/apps/server/src/auth/PairingGrantStore.test.ts +++ b/apps/server/src/auth/PairingGrantStore.test.ts @@ -92,6 +92,29 @@ it.layer(NodeServices.layer)("PairingGrantStore.layer", (it) => { }).pipe(Effect.provide(makePairingGrantStoreLayer())), ); + it.effect("requires the bound proof key thumbprint when present", () => + Effect.gen(function* () { + const bootstrapCredentials = yield* PairingGrantStore.PairingGrantStore; + const token = yield* bootstrapCredentials.issueOneTimeToken({ + proofKeyThumbprint: "client-proof-key-thumbprint", + }); + + const missing = yield* Effect.flip(bootstrapCredentials.consume(token.credential)); + const wrong = yield* Effect.flip( + bootstrapCredentials.consume(token.credential, { + proofKeyThumbprint: "other-proof-key-thumbprint", + }), + ); + const consumed = yield* bootstrapCredentials.consume(token.credential, { + proofKeyThumbprint: "client-proof-key-thumbprint", + }); + + expect(missing.message).toContain("proof key mismatch"); + expect(wrong.message).toContain("proof key mismatch"); + expect(consumed.proofKeyThumbprint).toBe("client-proof-key-thumbprint"); + }).pipe(Effect.provide(makePairingGrantStoreLayer())), + ); + it.effect("seeds the desktop bootstrap credential as a one-time grant", () => Effect.gen(function* () { const bootstrapCredentials = yield* PairingGrantStore.PairingGrantStore; diff --git a/apps/server/src/auth/PairingGrantStore.ts b/apps/server/src/auth/PairingGrantStore.ts index 4fcc133ebb..e97696fbad 100644 --- a/apps/server/src/auth/PairingGrantStore.ts +++ b/apps/server/src/auth/PairingGrantStore.ts @@ -26,6 +26,7 @@ export interface BootstrapGrant { readonly scopes: ReadonlyArray; readonly subject: string; readonly label?: string; + readonly proofKeyThumbprint?: string; readonly expiresAt: DateTime.DateTime; } @@ -50,6 +51,7 @@ export interface IssuedBootstrapCredential { readonly id: string; readonly credential: string; readonly label?: string; + readonly proofKeyThumbprint?: string; readonly expiresAt: DateTime.Utc; } @@ -69,6 +71,7 @@ export interface PairingGrantStoreShape { readonly scopes?: ReadonlyArray; readonly subject?: string; readonly label?: string; + readonly proofKeyThumbprint?: string; }) => Effect.Effect; readonly listActive: () => Effect.Effect< ReadonlyArray, @@ -76,7 +79,12 @@ export interface PairingGrantStoreShape { >; readonly streamChanges: Stream.Stream; readonly revoke: (id: string) => Effect.Effect; - readonly consume: (credential: string) => Effect.Effect; + readonly consume: ( + credential: string, + input?: { + readonly proofKeyThumbprint?: string; + }, + ) => Effect.Effect; } export class PairingGrantStore extends Context.Service()( @@ -232,6 +240,7 @@ export const make = Effect.fn("makePairingGrantStore")(function* () { id, credential, ...(input?.label ? { label: input.label } : {}), + ...(input?.proofKeyThumbprint ? { proofKeyThumbprint: input.proofKeyThumbprint } : {}), expiresAt, }; yield* pairingLinks.create({ @@ -241,6 +250,7 @@ export const make = Effect.fn("makePairingGrantStore")(function* () { scopes: input?.scopes ?? AuthStandardClientScopes, subject: input?.subject ?? "one-time-token", label: input?.label ?? null, + proofKeyThumbprint: input?.proofKeyThumbprint ?? null, createdAt: now, expiresAt: expiresAt, }); @@ -259,7 +269,7 @@ export const make = Effect.fn("makePairingGrantStore")(function* () { ); const consume: PairingGrantStoreShape["consume"] = Effect.fn("PairingGrantStore.consume")( - function* (credential) { + function* (credential, input) { const now = yield* DateTime.now; const seededResult: ConsumeResult = yield* Ref.modify( seededGrantsRef, @@ -289,6 +299,17 @@ export const make = Effect.fn("makePairingGrantStore")(function* () { ]; } + if (grant.proofKeyThumbprint && grant.proofKeyThumbprint !== input?.proofKeyThumbprint) { + return [ + { + _tag: "error", + reason: "not-found", + error: invalidBootstrapCredentialError("Bootstrap credential proof key mismatch."), + }, + next, + ]; + } + const remainingUses = grant.remainingUses; if (typeof remainingUses === "number") { if (remainingUses <= 1) { @@ -309,6 +330,9 @@ export const make = Effect.fn("makePairingGrantStore")(function* () { scopes: grant.scopes, subject: grant.subject, ...(grant.label ? { label: grant.label } : {}), + ...(grant.proofKeyThumbprint + ? { proofKeyThumbprint: grant.proofKeyThumbprint } + : {}), expiresAt: grant.expiresAt, } satisfies BootstrapGrant, }, @@ -326,6 +350,7 @@ export const make = Effect.fn("makePairingGrantStore")(function* () { const consumed = yield* pairingLinks.consumeAvailable({ credential, + proofKeyThumbprint: input?.proofKeyThumbprint ?? null, consumedAt: now, now, }); @@ -337,6 +362,9 @@ export const make = Effect.fn("makePairingGrantStore")(function* () { scopes: consumed.value.scopes, subject: consumed.value.subject, ...(consumed.value.label ? { label: consumed.value.label } : {}), + ...(consumed.value.proofKeyThumbprint + ? { proofKeyThumbprint: consumed.value.proofKeyThumbprint } + : {}), expiresAt: consumed.value.expiresAt, } satisfies BootstrapGrant; } @@ -360,6 +388,13 @@ export const make = Effect.fn("makePairingGrantStore")(function* () { return yield* invalidBootstrapCredentialError("Bootstrap credential expired."); } + if ( + matching.value.proofKeyThumbprint !== null && + matching.value.proofKeyThumbprint !== input?.proofKeyThumbprint + ) { + return yield* invalidBootstrapCredentialError("Bootstrap credential proof key mismatch."); + } + return yield* invalidBootstrapCredentialError("Bootstrap credential is no longer available."); }, Effect.mapError((cause) => diff --git a/apps/server/src/auth/ServerSecretStore.ts b/apps/server/src/auth/ServerSecretStore.ts index 93dcc95aa5..3b84ba5837 100644 --- a/apps/server/src/auth/ServerSecretStore.ts +++ b/apps/server/src/auth/ServerSecretStore.ts @@ -15,9 +15,16 @@ export class SecretStoreError extends Data.TaggedError("SecretStoreError")<{ readonly cause?: unknown; }> {} +const isPlatformError = (value: unknown): value is PlatformError.PlatformError => + Predicate.isTagged(value, "PlatformError"); + +export const isSecretAlreadyExistsError = (error: SecretStoreError): boolean => + isPlatformError(error.cause) && error.cause.reason._tag === "AlreadyExists"; + export interface ServerSecretStoreShape { readonly get: (name: string) => Effect.Effect; readonly set: (name: string, value: Uint8Array) => Effect.Effect; + readonly create: (name: string, value: Uint8Array) => Effect.Effect; readonly getOrCreateRandom: ( name: string, bytes: number, @@ -48,9 +55,6 @@ export const make = Effect.fn("makeServerSecretStore")(function* () { const resolveSecretPath = (name: string) => path.join(serverConfig.secretsDir, `${name}.bin`); - const isPlatformError = (u: unknown): u is PlatformError.PlatformError => - Predicate.isTagged(u, "PlatformError"); - const get: ServerSecretStoreShape["get"] = (name) => fileSystem.readFile(resolveSecretPath(name)).pipe( Effect.map((bytes) => Uint8Array.from(bytes)), @@ -104,7 +108,7 @@ export const make = Effect.fn("makeServerSecretStore")(function* () { ); }; - const create: ServerSecretStoreShape["set"] = (name, value) => { + const create: ServerSecretStoreShape["create"] = (name, value) => { const secretPath = resolveSecretPath(name); return Effect.scoped( Effect.gen(function* () { @@ -146,7 +150,7 @@ export const make = Effect.fn("makeServerSecretStore")(function* () { create(name, generated).pipe( Effect.as(Uint8Array.from(generated)), Effect.catchTag("SecretStoreError", (error) => - isPlatformError(error.cause) && error.cause.reason._tag === "AlreadyExists" + isSecretAlreadyExistsError(error) ? get(name).pipe( Effect.flatMap((created) => created !== null @@ -185,6 +189,7 @@ export const make = Effect.fn("makeServerSecretStore")(function* () { return { get, set, + create, getOrCreateRandom, remove, } satisfies ServerSecretStoreShape; diff --git a/apps/server/src/auth/SessionStore.ts b/apps/server/src/auth/SessionStore.ts index 83f38c6b6d..8de145ca33 100644 --- a/apps/server/src/auth/SessionStore.ts +++ b/apps/server/src/auth/SessionStore.ts @@ -40,6 +40,7 @@ export interface IssuedSession { readonly client: AuthClientMetadata; readonly expiresAt: DateTime.DateTime; readonly scopes: ReadonlyArray; + readonly proofKeyThumbprint?: string; } export interface VerifiedSession { @@ -50,6 +51,7 @@ export interface VerifiedSession { readonly expiresAt?: DateTime.DateTime; readonly subject: string; readonly scopes: ReadonlyArray; + readonly proofKeyThumbprint?: string; } export type SessionCredentialChange = @@ -86,6 +88,7 @@ export interface SessionStoreShape { readonly method?: ServerAuthSessionMethod; readonly scopes?: ReadonlyArray; readonly client?: AuthClientMetadata; + readonly proofKeyThumbprint?: string; }) => Effect.Effect; readonly verify: (token: string) => Effect.Effect; readonly issueWebSocketToken: ( @@ -132,7 +135,8 @@ const SessionClaims = Schema.Struct({ sid: AuthSessionId, sub: Schema.String, scopes: AuthEnvironmentScopes, - method: Schema.Literals(["browser-session-cookie", "bearer-access-token"]), + method: Schema.Literals(["browser-session-cookie", "bearer-access-token", "dpop-access-token"]), + jkt: Schema.optionalKey(Schema.String), iat: Schema.Number, exp: Schema.Number, }); @@ -310,6 +314,7 @@ export const make = Effect.fn("makeSessionStore")(function* () { sub: input?.subject ?? "browser", scopes: input?.scopes ?? AuthStandardClientScopes, method: input?.method ?? "browser-session-cookie", + ...(input?.proofKeyThumbprint ? { jkt: input.proofKeyThumbprint } : {}), iat: issuedAt.epochMilliseconds, exp: expiresAt.epochMilliseconds, }; @@ -360,6 +365,7 @@ export const make = Effect.fn("makeSessionStore")(function* () { client, expiresAt: expiresAt, scopes: claims.scopes, + ...(claims.jkt ? { proofKeyThumbprint: claims.jkt } : {}), } satisfies IssuedSession; }, Effect.mapError(toSessionCredentialInternalError("Failed to issue session credential.")), @@ -425,6 +431,7 @@ export const make = Effect.fn("makeSessionStore")(function* () { expiresAt: expiresAt.value, subject: claims.sub, scopes: claims.scopes, + ...(claims.jkt ? { proofKeyThumbprint: claims.jkt } : {}), } satisfies VerifiedSession; }, Effect.mapError((cause) => diff --git a/apps/server/src/auth/dpop.test.ts b/apps/server/src/auth/dpop.test.ts new file mode 100644 index 0000000000..379e77844e --- /dev/null +++ b/apps/server/src/auth/dpop.test.ts @@ -0,0 +1,33 @@ +import { describe, expect, it } from "vitest"; +import * as PlatformError from "effect/PlatformError"; + +import * as ServerSecretStore from "./ServerSecretStore.ts"; +import { mapDpopReplayStoreError } from "./dpop.ts"; + +const storeFailure = (tag: "AlreadyExists" | "PermissionDenied") => + new ServerSecretStore.SecretStoreError({ + message: "Failed to persist DPoP proof.", + cause: PlatformError.systemError({ + _tag: tag, + module: "FileSystem", + method: "open", + pathOrDescriptor: "dpop-proof.bin", + }), + }); + +describe("mapDpopReplayStoreError", () => { + it("reports replay conflicts as invalid credentials", () => { + const error = mapDpopReplayStoreError(storeFailure("AlreadyExists")); + + expect(error._tag).toBe("ServerAuthInvalidCredentialError"); + }); + + it("reports replay-store availability failures as internal errors", () => { + const error = mapDpopReplayStoreError(storeFailure("PermissionDenied")); + + expect(error._tag).toBe("ServerAuthInternalError"); + if (error._tag === "ServerAuthInternalError") { + expect(error.message).toBe("Failed to record DPoP proof replay state."); + } + }); +}); diff --git a/apps/server/src/auth/dpop.ts b/apps/server/src/auth/dpop.ts new file mode 100644 index 0000000000..66cd07f9e2 --- /dev/null +++ b/apps/server/src/auth/dpop.ts @@ -0,0 +1,92 @@ +import { verifyDpopProof } from "@t3tools/shared/dpop"; +import * as Crypto from "effect/Crypto"; +import * as DateTime from "effect/DateTime"; +import * as Effect from "effect/Effect"; +import * as Encoding from "effect/Encoding"; +import type * as HttpServerRequest from "effect/unstable/http/HttpServerRequest"; + +import * as EnvironmentAuth from "./EnvironmentAuth.ts"; +import * as ServerSecretStore from "./ServerSecretStore.ts"; + +function firstHeaderValue(value: string | undefined): string | undefined { + const first = value?.split(",")[0]?.trim(); + return first && first.length > 0 ? first : undefined; +} + +export function requestAbsoluteUrl(request: HttpServerRequest.HttpServerRequest): string { + try { + return new URL(request.originalUrl).href; + } catch { + const host = firstHeaderValue(request.headers.host) ?? "127.0.0.1"; + const forwardedProto = firstHeaderValue(request.headers["x-forwarded-proto"]); + const proto = forwardedProto === "https" || forwardedProto === "http" ? forwardedProto : "http"; + return new URL(request.originalUrl, `${proto}://${host}`).href; + } +} + +export const mapDpopReplayStoreError = ( + error: ServerSecretStore.SecretStoreError, +): EnvironmentAuth.ServerAuthInvalidCredentialError | EnvironmentAuth.ServerAuthInternalError => + ServerSecretStore.isSecretAlreadyExistsError(error) + ? new EnvironmentAuth.ServerAuthInvalidCredentialError({ + reason: "invalid_credential", + cause: "DPoP proof replayed.", + }) + : new EnvironmentAuth.ServerAuthInternalError({ + message: "Failed to record DPoP proof replay state.", + cause: error, + }); + +export const verifyRequestDpopProof = (input: { + readonly request: HttpServerRequest.HttpServerRequest; + readonly expectedThumbprint?: string; + readonly expectedAccessToken?: string; +}) => + Effect.gen(function* () { + const proof = input.request.headers.dpop; + const now = yield* DateTime.now; + const result = verifyDpopProof({ + proof, + method: input.request.method, + url: requestAbsoluteUrl(input.request), + nowEpochSeconds: Math.floor(now.epochMilliseconds / 1_000), + ...(input.expectedThumbprint ? { expectedThumbprint: input.expectedThumbprint } : {}), + ...(input.expectedAccessToken ? { expectedAccessToken: input.expectedAccessToken } : {}), + }); + if (!result.ok) { + return yield* new EnvironmentAuth.ServerAuthInvalidCredentialError({ + reason: "invalid_credential", + cause: result.reason, + }); + } + const secretStore = yield* ServerSecretStore.ServerSecretStore; + const replayKey = yield* Crypto.Crypto.pipe( + Effect.flatMap((crypto) => + crypto.digest("SHA-256", new TextEncoder().encode(`${result.thumbprint}:${result.jti}`)), + ), + Effect.map(Encoding.encodeBase64Url), + Effect.mapError( + (cause) => + new EnvironmentAuth.ServerAuthInternalError({ + message: "Failed to calculate DPoP replay key.", + cause, + }), + ), + ); + yield* secretStore + .create( + `dpop-proof-${replayKey}`, + new TextEncoder().encode( + [ + `thumbprint=${result.thumbprint}`, + `jti=${result.jti}`, + `iat=${result.iat}`, + `consumedAt=${DateTime.formatIso(now)}`, + ].join("\n"), + ), + ) + .pipe( + Effect.catchTag("SecretStoreError", (error) => Effect.fail(mapDpopReplayStoreError(error))), + ); + return result.thumbprint; + }); diff --git a/apps/server/src/auth/http.ts b/apps/server/src/auth/http.ts index b36c8dd647..ed640863d2 100644 --- a/apps/server/src/auth/http.ts +++ b/apps/server/src/auth/http.ts @@ -34,6 +34,32 @@ import * as HttpApiBuilder from "effect/unstable/httpapi/HttpApiBuilder"; import * as EnvironmentAuth from "./EnvironmentAuth.ts"; import * as SessionStore from "./SessionStore.ts"; import { deriveAuthClientMetadata } from "./utils.ts"; +import { verifyRequestDpopProof } from "./dpop.ts"; + +const CREDENTIAL_RESPONSE_HEADERS = { + "cache-control": "no-store", + pragma: "no-cache", +} as const; + +const appendCredentialResponseHeaders = HttpEffect.appendPreResponseHandler((_request, response) => + Effect.succeed(HttpServerResponse.setHeaders(response, CREDENTIAL_RESPONSE_HEADERS)), +); + +const appendDpopChallengeHeader = HttpEffect.appendPreResponseHandler((_request, response) => + Effect.succeed(HttpServerResponse.setHeader(response, "www-authenticate", "DPoP")), +); + +const appendDpopChallengeOnUnauthorized = (error: EnvironmentAuthInvalidError) => + Effect.gen(function* () { + const request = yield* HttpServerRequest.HttpServerRequest; + const usesDpop = + (request.originalUrl.startsWith("/oauth/token") && request.headers.dpop !== undefined) || + request.headers.authorization?.startsWith("DPoP ") === true; + if (usesDpop) { + yield* appendDpopChallengeHeader; + } + return yield* error; + }); export const currentEnvironmentTraceId = Effect.currentParentSpan.pipe( Effect.map((span) => span.traceId), @@ -152,7 +178,7 @@ export const environmentAuthenticatedAuthLayer = Layer.effect( scopes: new Set(session.scopes), }), ); - }); + }).pipe(Effect.catchTag("EnvironmentAuthInvalidError", appendDpopChallengeOnUnauthorized)); }), ); @@ -199,6 +225,7 @@ export const authHttpApiLayer = HttpApiBuilder.group( yield* HttpEffect.appendPreResponseHandler((_request, response) => Effect.succeed(HttpServerResponse.mergeCookies(response, sessionCookies)), ); + yield* appendCredentialResponseHeaders; return result.response; }, Effect.catchTags({ @@ -230,8 +257,22 @@ export const authHttpApiLayer = HttpApiBuilder.group( AuthRelayWriteScope, ]), }); - if (requestedScopes === null) + if (requestedScopes === null) { return yield* failEnvironmentInvalidRequest("invalid_scope"); + } + const proofKeyThumbprint = args.headers.dpop + ? yield* verifyRequestDpopProof({ request }).pipe( + Effect.catchTags({ + ServerAuthInvalidCredentialError: () => + appendDpopChallengeHeader.pipe( + Effect.andThen(failEnvironmentAuthInvalid("invalid_credential")), + ), + ServerAuthInternalError: (error) => + failEnvironmentInternal("access_token_issuance_failed", error), + }), + ) + : undefined; + yield* appendCredentialResponseHeaders; return yield* serverAuth.exchangeBootstrapCredentialForAccessToken( args.payload.subject_token, requestedScopes, @@ -245,6 +286,7 @@ export const authHttpApiLayer = HttpApiBuilder.group( ...(args.payload.client_os ? { os: args.payload.client_os } : {}), }, }), + proofKeyThumbprint ? { proofKeyThumbprint } : undefined, ); }, Effect.catchTags({ @@ -261,6 +303,7 @@ export const authHttpApiLayer = HttpApiBuilder.group( function* (args) { yield* annotateEnvironmentRequest(args.endpoint.name); const session = yield* EnvironmentAuthenticatedPrincipal; + yield* appendCredentialResponseHeaders; return yield* serverAuth.issueWebSocketTicket(session); }, Effect.catchTag("ServerAuthInternalError", (error) => diff --git a/apps/server/src/auth/utils.ts b/apps/server/src/auth/utils.ts index 26b4ae4c4b..7260ac7c54 100644 --- a/apps/server/src/auth/utils.ts +++ b/apps/server/src/auth/utils.ts @@ -5,6 +5,8 @@ import type { } from "@t3tools/contracts"; import type * as HttpServerRequest from "effect/unstable/http/HttpServerRequest"; import * as Crypto from "node:crypto"; +import * as Encoding from "effect/Encoding"; +import * as Result from "effect/Result"; const SESSION_COOKIE_NAME = "t3_session"; @@ -20,12 +22,13 @@ export function resolveSessionCookieName(input: { } export function base64UrlEncode(input: string | Uint8Array): string { - const buffer = typeof input === "string" ? Buffer.from(input, "utf8") : Buffer.from(input); - return buffer.toString("base64url"); + return typeof input === "string" + ? Encoding.encodeBase64Url(new TextEncoder().encode(input)) + : Encoding.encodeBase64Url(input); } export function base64UrlDecodeUtf8(input: string): string { - return Buffer.from(input, "base64url").toString("utf8"); + return Result.getOrThrow(Encoding.decodeBase64UrlString(input)); } export function signPayload(payload: string, secret: Uint8Array): string { diff --git a/apps/server/src/cloud/ManagedEndpointRuntime.test.ts b/apps/server/src/cloud/ManagedEndpointRuntime.test.ts new file mode 100644 index 0000000000..d3baceee73 --- /dev/null +++ b/apps/server/src/cloud/ManagedEndpointRuntime.test.ts @@ -0,0 +1,244 @@ +import { describe, expect, it } from "@effect/vitest"; +import * as Deferred from "effect/Deferred"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import * as PlatformError from "effect/PlatformError"; +import * as Sink from "effect/Sink"; +import * as Stream from "effect/Stream"; +import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process"; + +import { makeCloudManagedEndpointRuntime } from "./ManagedEndpointRuntime.ts"; + +function makeHandle(input: { + readonly pid: number; + readonly onKill: () => void; + readonly isRunning?: () => boolean; + readonly exitCode?: Effect.Effect; +}) { + return ChildProcessSpawner.makeHandle({ + pid: ChildProcessSpawner.ProcessId(input.pid), + exitCode: input.exitCode ?? Effect.never, + isRunning: Effect.sync(() => input.isRunning?.() ?? true), + kill: () => + Effect.sync(() => { + input.onKill(); + }), + unref: Effect.succeed(Effect.void), + stdin: Sink.drain, + stdout: Stream.empty, + stderr: Stream.empty, + all: Stream.empty, + getInputFd: () => Sink.drain, + getOutputFd: () => Stream.empty, + }); +} + +describe("CloudManagedEndpointRuntime", () => { + it.effect("starts, deduplicates, rotates, and stops the Cloudflare connector", () => + Effect.gen(function* () { + const spawned: Array = []; + const killed: Array = []; + let nextPid = 100; + const spawner = ChildProcessSpawner.make((command) => + Effect.gen(function* () { + if (!ChildProcess.isStandardCommand(command)) { + throw new Error("Expected standard command."); + } + spawned.push(command); + const pid = nextPid; + nextPid += 1; + const handle = makeHandle({ + pid, + onKill: () => { + killed.push(pid); + }, + }); + yield* Effect.addFinalizer(() => handle.kill().pipe(Effect.ignore)); + return handle; + }), + ); + const runtime = yield* makeCloudManagedEndpointRuntime.pipe( + Effect.provide(Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, spawner)), + ); + + yield* runtime.applyConfig({ + providerKind: "cloudflare_tunnel", + connectorToken: "token-1", + tunnelId: "tunnel-1", + tunnelName: "t3-code-env-1", + }); + yield* runtime.applyConfig({ + providerKind: "cloudflare_tunnel", + connectorToken: "token-1", + tunnelId: "tunnel-1", + tunnelName: "t3-code-env-1", + }); + yield* runtime.applyConfig({ + providerKind: "cloudflare_tunnel", + connectorToken: "token-2", + tunnelId: "tunnel-1", + tunnelName: "t3-code-env-1", + }); + const stopped = yield* runtime.applyConfig(null); + + expect(spawned.map((command) => command.command)).toEqual(["cloudflared", "cloudflared"]); + expect(spawned.map((command) => command.args)).toEqual([ + ["tunnel", "run", "--token", "token-1"], + ["tunnel", "run", "--token", "token-2"], + ]); + expect(spawned.map((command) => command.options.stdout)).toEqual(["ignore", "ignore"]); + expect(spawned.map((command) => command.options.stderr)).toEqual(["ignore", "ignore"]); + expect(killed).toEqual([100, 101]); + expect(stopped).toEqual({ status: "disabled" }); + }), + ); + + it.effect("stops an active connector when a non-Cloudflare runtime config is applied", () => + Effect.gen(function* () { + const killed: Array = []; + const spawner = ChildProcessSpawner.make(() => + Effect.gen(function* () { + const handle = makeHandle({ + pid: 200, + onKill: () => { + killed.push(200); + }, + }); + yield* Effect.addFinalizer(() => handle.kill().pipe(Effect.ignore)); + return handle; + }), + ); + const runtime = yield* makeCloudManagedEndpointRuntime.pipe( + Effect.provide(Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, spawner)), + ); + + const started = yield* runtime.applyConfig({ + providerKind: "cloudflare_tunnel", + connectorToken: "token", + }); + const unsupported = yield* runtime.applyConfig({ + providerKind: "manual", + connectorToken: "manual-token", + }); + + expect(started.status).toBe("running"); + expect(unsupported).toEqual({ status: "unsupported", providerKind: "manual" }); + expect(killed).toEqual([200]); + }), + ); + + it.effect("restarts the connector when the active process has exited", () => + Effect.gen(function* () { + const spawned: Array = []; + const killed: Array = []; + let firstRunning = true; + const spawner = ChildProcessSpawner.make(() => + Effect.gen(function* () { + const pid = spawned.length === 0 ? 300 : 301; + spawned.push(pid); + const handle = makeHandle({ + pid, + isRunning: () => (pid === 300 ? firstRunning : true), + onKill: () => { + killed.push(pid); + }, + }); + yield* Effect.addFinalizer(() => handle.kill().pipe(Effect.ignore)); + return handle; + }), + ); + const runtime = yield* makeCloudManagedEndpointRuntime.pipe( + Effect.provide(Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, spawner)), + ); + const config = { + providerKind: "cloudflare_tunnel" as const, + connectorToken: "token", + tunnelId: "tunnel-1", + }; + + const first = yield* runtime.applyConfig(config); + firstRunning = false; + const second = yield* runtime.applyConfig(config); + + expect(first).toMatchObject({ status: "running", pid: 300 }); + expect(second).toMatchObject({ status: "running", pid: 301 }); + expect(spawned).toEqual([300, 301]); + expect(killed).toEqual([300]); + }), + ); + + it.effect("supervises the active connector and restarts it after process exit", () => + Effect.gen(function* () { + const spawned: Array = []; + const killed: Array = []; + const firstExit = yield* Deferred.make(); + const secondSpawned = yield* Deferred.make(); + const spawner = ChildProcessSpawner.make(() => + Effect.gen(function* () { + const pid = spawned.length === 0 ? 400 : 401; + spawned.push(pid); + if (pid === 401) { + yield* Deferred.succeed(secondSpawned, undefined); + } + const handle = makeHandle({ + pid, + exitCode: + pid === 400 + ? Deferred.await(firstExit) + : (Effect.never as Effect.Effect), + onKill: () => { + killed.push(pid); + }, + }); + yield* Effect.addFinalizer(() => handle.kill().pipe(Effect.ignore)); + return handle; + }), + ); + const runtime = yield* makeCloudManagedEndpointRuntime.pipe( + Effect.provide(Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, spawner)), + ); + + const started = yield* runtime.applyConfig({ + providerKind: "cloudflare_tunnel", + connectorToken: "token", + tunnelId: "tunnel-1", + }); + yield* Deferred.succeed(firstExit, ChildProcessSpawner.ExitCode(1)); + yield* Deferred.await(secondSpawned); + + expect(started).toMatchObject({ status: "running", pid: 400 }); + expect(spawned).toEqual([400, 401]); + expect(killed).toEqual([]); + }), + ); + + it.effect("reports connector spawn failures", () => + Effect.gen(function* () { + const spawner = ChildProcessSpawner.make(() => + Effect.fail( + PlatformError.systemError({ + _tag: "NotFound", + module: "ChildProcess", + method: "spawn", + description: "cloudflared missing", + }), + ), + ); + const runtime = yield* makeCloudManagedEndpointRuntime.pipe( + Effect.provide(Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, spawner)), + ); + + const status = yield* runtime.applyConfig({ + providerKind: "cloudflare_tunnel", + connectorToken: "token", + tunnelId: "tunnel-1", + }); + + expect(status).toMatchObject({ + status: "failed", + providerKind: "cloudflare_tunnel", + tunnelId: "tunnel-1", + }); + }), + ); +}); diff --git a/apps/server/src/cloud/ManagedEndpointRuntime.ts b/apps/server/src/cloud/ManagedEndpointRuntime.ts new file mode 100644 index 0000000000..25906ef8ed --- /dev/null +++ b/apps/server/src/cloud/ManagedEndpointRuntime.ts @@ -0,0 +1,233 @@ +import type { RelayManagedEndpointRuntimeConfig } from "@t3tools/contracts/relay"; +import * as Context from "effect/Context"; +import * as Effect from "effect/Effect"; +import * as Exit from "effect/Exit"; +import * as Layer from "effect/Layer"; +import * as Option from "effect/Option"; +import * as Ref from "effect/Ref"; +import * as Scope from "effect/Scope"; +import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process"; + +import * as ServerSecretStore from "../auth/ServerSecretStore.ts"; +import { CLOUD_ENDPOINT_RUNTIME_CONFIG, decodeRuntimeConfig } from "./config.ts"; + +function bytesToString(bytes: Uint8Array): string { + return new TextDecoder().decode(bytes); +} + +const readRuntimeConfig = Effect.gen(function* () { + const secrets = yield* ServerSecretStore.ServerSecretStore; + const bytes = yield* secrets.get(CLOUD_ENDPOINT_RUNTIME_CONFIG); + if (!bytes) { + return null; + } + return Option.getOrNull(decodeRuntimeConfig(bytesToString(bytes))); +}); + +export interface CloudManagedEndpointRuntimeShape { + readonly applyConfig: ( + config: RelayManagedEndpointRuntimeConfig | null, + ) => Effect.Effect; +} + +export class CloudManagedEndpointRuntime extends Context.Service< + CloudManagedEndpointRuntime, + CloudManagedEndpointRuntimeShape +>()("t3/cloud/ManagedEndpointRuntime/CloudManagedEndpointRuntime") {} + +export type CloudManagedEndpointRuntimeStatus = + | { + readonly status: "disabled"; + } + | { + readonly status: "failed"; + readonly providerKind: RelayManagedEndpointRuntimeConfig["providerKind"]; + readonly reason: string; + readonly tunnelId?: string; + readonly tunnelName?: string; + } + | { + readonly status: "running"; + readonly providerKind: "cloudflare_tunnel"; + readonly pid: number; + readonly tunnelId?: string; + readonly tunnelName?: string; + } + | { + readonly status: "unsupported"; + readonly providerKind: RelayManagedEndpointRuntimeConfig["providerKind"]; + }; + +interface ActiveConnector { + readonly child: ChildProcessSpawner.ChildProcessHandle; + readonly scope: Scope.Closeable; + readonly configKey: string; + readonly config: RelayManagedEndpointRuntimeConfig; +} + +function runtimeConfigKey(config: RelayManagedEndpointRuntimeConfig): string { + return JSON.stringify({ + providerKind: config.providerKind, + connectorToken: config.connectorToken, + tunnelId: config.tunnelId ?? null, + tunnelName: config.tunnelName ?? null, + }); +} + +const stopConnector = (connector: ActiveConnector | null) => + connector + ? Scope.close(connector.scope, Exit.void).pipe( + Effect.tap(() => + Effect.logInfo("Cloudflare managed endpoint connector stopped", { + pid: Number(connector.child.pid), + }), + ), + Effect.ignore, + ) + : Effect.void; + +export const makeCloudManagedEndpointRuntime = Effect.gen(function* () { + const spawner = yield* ChildProcessSpawner.ChildProcessSpawner; + const activeRef = yield* Ref.make(null); + let applyConfig: CloudManagedEndpointRuntimeShape["applyConfig"]; + + const stopActive = Effect.gen(function* () { + const active = yield* Ref.getAndSet(activeRef, null); + yield* stopConnector(active); + }); + + const superviseConnector = (connector: ActiveConnector) => + Effect.gen(function* () { + const exitCode = yield* connector.child.exitCode; + const active = yield* Ref.get(activeRef); + if (active?.child.pid !== connector.child.pid || active.configKey !== connector.configKey) { + return; + } + yield* Ref.set(activeRef, null); + yield* Effect.logWarning("Cloudflare managed endpoint connector exited; restarting", { + pid: Number(connector.child.pid), + exitCode: Number(exitCode), + tunnelId: connector.config.tunnelId, + tunnelName: connector.config.tunnelName, + }); + yield* applyConfig(connector.config); + }).pipe( + Effect.catch((cause) => + Effect.logWarning("Cloudflare managed endpoint connector supervisor failed", { cause }), + ), + ); + + applyConfig = Effect.fn("CloudManagedEndpointRuntime.applyConfig")(function* (config) { + if (!config || config.providerKind !== "cloudflare_tunnel") { + yield* stopActive; + return config + ? { status: "unsupported", providerKind: config.providerKind } + : { status: "disabled" }; + } + + const nextConfigKey = runtimeConfigKey(config); + const active = yield* Ref.get(activeRef); + if (active?.configKey === nextConfigKey) { + const isRunning = yield* active.child.isRunning.pipe( + Effect.catch(() => Effect.succeed(false)), + ); + if (isRunning) { + return { + status: "running", + providerKind: "cloudflare_tunnel", + pid: Number(active.child.pid), + ...(active.config.tunnelId ? { tunnelId: active.config.tunnelId } : {}), + ...(active.config.tunnelName ? { tunnelName: active.config.tunnelName } : {}), + } satisfies CloudManagedEndpointRuntimeStatus; + } + } + + yield* stopActive; + + const connectorScope = yield* Scope.make("sequential"); + const child = yield* spawner + .spawn( + ChildProcess.make("cloudflared", ["tunnel", "run", "--token", config.connectorToken], { + shell: process.platform === "win32", + stderr: "ignore", + stdout: "ignore", + }), + ) + .pipe( + Effect.provideService(Scope.Scope, connectorScope), + Effect.tap(() => + Effect.logInfo("Cloudflare managed endpoint connector started", { + tunnelId: config.tunnelId, + tunnelName: config.tunnelName, + }), + ), + Effect.catch((cause) => + Effect.logWarning("Failed to start Cloudflare managed endpoint connector", { + cause, + tunnelId: config.tunnelId, + tunnelName: config.tunnelName, + }).pipe( + Effect.andThen(Scope.close(connectorScope, Exit.void).pipe(Effect.ignore)), + Effect.as({ + status: "failed", + providerKind: "cloudflare_tunnel", + reason: String(cause), + ...(config.tunnelId ? { tunnelId: config.tunnelId } : {}), + ...(config.tunnelName ? { tunnelName: config.tunnelName } : {}), + } satisfies CloudManagedEndpointRuntimeStatus), + ), + ), + ); + + if ("status" in child && child.status === "failed") { + return child; + } + + if (!("status" in child)) { + const connector = { + child, + scope: connectorScope, + configKey: nextConfigKey, + config, + } satisfies ActiveConnector; + yield* Ref.set(activeRef, connector); + yield* Effect.forkIn(superviseConnector(connector), connectorScope); + return { + status: "running", + providerKind: "cloudflare_tunnel", + pid: Number(child.pid), + ...(config.tunnelId ? { tunnelId: config.tunnelId } : {}), + ...(config.tunnelName ? { tunnelName: config.tunnelName } : {}), + } satisfies CloudManagedEndpointRuntimeStatus; + } + + return { + status: "failed", + providerKind: "cloudflare_tunnel", + reason: "Cloudflare connector did not start.", + ...(config.tunnelId ? { tunnelId: config.tunnelId } : {}), + ...(config.tunnelName ? { tunnelName: config.tunnelName } : {}), + } satisfies CloudManagedEndpointRuntimeStatus; + }); + + return CloudManagedEndpointRuntime.of({ + applyConfig, + }); +}); + +export const layer = Layer.effect( + CloudManagedEndpointRuntime, + Effect.gen(function* () { + const runtime = yield* makeCloudManagedEndpointRuntime; + const initialConfig = yield* readRuntimeConfig.pipe( + Effect.catch((cause) => + Effect.logWarning("Failed to read managed endpoint runtime config", { cause }).pipe( + Effect.as(null), + ), + ), + ); + yield* runtime.applyConfig(initialConfig); + yield* Effect.addFinalizer(() => runtime.applyConfig(null)); + return runtime; + }), +); diff --git a/apps/server/src/cloud/config.ts b/apps/server/src/cloud/config.ts new file mode 100644 index 0000000000..51b05e64a5 --- /dev/null +++ b/apps/server/src/cloud/config.ts @@ -0,0 +1,17 @@ +import { RelayManagedEndpointRuntimeConfig } from "@t3tools/contracts/relay"; +import * as Schema from "effect/Schema"; + +export const CLOUD_MINT_PUBLIC_KEY = "cloud-mint-ed25519-public-key"; +export const CLOUD_ENDPOINT_RUNTIME_CONFIG = "cloud-endpoint-runtime-config"; +export const CLOUD_LINKED_USER_ID = "cloud-linked-user-id"; +export const RELAY_URL_SECRET = "cloud-relay-url"; +export const RELAY_ISSUER_SECRET = "cloud-relay-issuer"; +export const RELAY_ENVIRONMENT_CREDENTIAL_SECRET = "cloud-relay-environment-credential"; + +export const encodeEndpointRuntimeConfigJson = Schema.encodeEffect( + Schema.fromJsonString(RelayManagedEndpointRuntimeConfig), +); + +export const decodeRuntimeConfig = Schema.decodeUnknownOption( + Schema.fromJsonString(RelayManagedEndpointRuntimeConfig), +); diff --git a/apps/server/src/cloud/http.test.ts b/apps/server/src/cloud/http.test.ts new file mode 100644 index 0000000000..c4e52f4967 --- /dev/null +++ b/apps/server/src/cloud/http.test.ts @@ -0,0 +1,60 @@ +import { describe, expect, it } from "@effect/vitest"; +import * as Effect from "effect/Effect"; +import * as PlatformError from "effect/PlatformError"; + +import * as ServerSecretStore from "../auth/ServerSecretStore.ts"; +import { consumeCloudReplayGuards } from "./http.ts"; + +const storeFailure = (tag: "AlreadyExists" | "PermissionDenied") => + new ServerSecretStore.SecretStoreError({ + message: "Failed to persist cloud replay guard.", + cause: PlatformError.systemError({ + _tag: tag, + module: "FileSystem", + method: "open", + pathOrDescriptor: "cloud-replay-guard.bin", + }), + }); + +const unusedSecretStoreOperation = () => Effect.die("unused secret-store operation"); + +function makeSecretStore( + create: ServerSecretStore.ServerSecretStoreShape["create"], +): ServerSecretStore.ServerSecretStoreShape { + return { + get: unusedSecretStoreOperation, + set: unusedSecretStoreOperation, + create, + getOrCreateRandom: unusedSecretStoreOperation, + remove: unusedSecretStoreOperation, + }; +} + +describe("consumeCloudReplayGuards", () => { + it.effect("reports already-created guards as replay conflicts", () => + Effect.gen(function* () { + const consumed = yield* consumeCloudReplayGuards({ + secrets: makeSecretStore(() => Effect.fail(storeFailure("AlreadyExists"))), + names: ["cloud-jti", "cloud-nonce"], + value: new Uint8Array(), + }); + + expect(consumed).toBe(false); + }), + ); + + it.effect("preserves replay-store availability failures", () => + Effect.gen(function* () { + const failure = storeFailure("PermissionDenied"); + const error = yield* Effect.flip( + consumeCloudReplayGuards({ + secrets: makeSecretStore(() => Effect.fail(failure)), + names: ["cloud-jti", "cloud-nonce"], + value: new Uint8Array(), + }), + ); + + expect(error).toBe(failure); + }), + ); +}); diff --git a/apps/server/src/cloud/http.ts b/apps/server/src/cloud/http.ts new file mode 100644 index 0000000000..c50deebc26 --- /dev/null +++ b/apps/server/src/cloud/http.ts @@ -0,0 +1,797 @@ +import * as NodeCrypto from "node:crypto"; +import { + AuthRelayManageScope, + AuthStandardClientScopes, + EnvironmentCloudEndpointUnavailableError, + EnvironmentCloudLinkStateResult, + EnvironmentCloudRelayConfigResult, + EnvironmentHttpApi, + EnvironmentHttpBadRequestError, + EnvironmentHttpConflictError, + EnvironmentHttpInternalServerError, + EnvironmentHttpUnauthorizedError, +} from "@t3tools/contracts"; +import { + RelayCloudEnvironmentHealthProofPayload, + RelayCloudEnvironmentHealthRequest, + RelayCloudMintCredentialProofPayload, + RelayCloudMintCredentialRequest, + RelayEnvironmentHealthResponseProofPayload, + type RelayEnvironmentHealthResponse as RelayEnvironmentHealthResponseShape, + RelayEnvironmentConfigRequest, + RelayEnvironmentMintResponseProofPayload, + type RelayEnvironmentMintResponse as RelayEnvironmentMintResponseShape, + RelayEnvironmentLinkProof, + RelayEnvironmentLinkProofPayload, + RelayLinkProofRequest, + RelayManagedEndpointOrigin, +} from "@t3tools/contracts/relay"; +import { + normalizeRelayIssuer, + RELAY_HEALTH_REQUEST_TYP, + RELAY_HEALTH_RESPONSE_TYP, + RELAY_LINK_PROOF_TYP, + RELAY_MINT_REQUEST_TYP, + RELAY_MINT_RESPONSE_TYP, + signRelayJwt, + verifyRelayJwt, +} from "@t3tools/shared/relayJwt"; +import * as DateTime from "effect/DateTime"; +import * as Crypto from "effect/Crypto"; +import * as Duration from "effect/Duration"; +import * as Effect from "effect/Effect"; +import * as Option from "effect/Option"; +import * as Schema from "effect/Schema"; +import * as HttpEffect from "effect/unstable/http/HttpEffect"; +import { HttpServerRequest, HttpServerResponse } from "effect/unstable/http"; +import * as HttpApiBuilder from "effect/unstable/httpapi/HttpApiBuilder"; + +import * as EnvironmentAuth from "../auth/EnvironmentAuth.ts"; +import * as ServerSecretStore from "../auth/ServerSecretStore.ts"; +import { requireEnvironmentScope } from "../auth/http.ts"; +import { + ServerEnvironment, + type ServerEnvironmentShape, +} from "../environment/Services/ServerEnvironment.ts"; +import { + CloudManagedEndpointRuntime, + type CloudManagedEndpointRuntimeShape, +} from "./ManagedEndpointRuntime.ts"; +import { + CLOUD_ENDPOINT_RUNTIME_CONFIG, + CLOUD_LINKED_USER_ID, + CLOUD_MINT_PUBLIC_KEY, + encodeEndpointRuntimeConfigJson, + RELAY_ENVIRONMENT_CREDENTIAL_SECRET, + RELAY_ISSUER_SECRET, + RELAY_URL_SECRET, +} from "./config.ts"; + +const CLOUD_LINK_PRIVATE_KEY = "cloud-link-ed25519-private-key"; +const CLOUD_LINK_PUBLIC_KEY = "cloud-link-ed25519-public-key"; +const CLOUD_MINT_NONCE_PREFIX = "cloud-mint-nonce-"; +const CLOUD_MINT_JTI_PREFIX = "cloud-mint-jti-"; +const CLOUD_HEALTH_NONCE_PREFIX = "cloud-health-nonce-"; +const CLOUD_HEALTH_JTI_PREFIX = "cloud-health-jti-"; +const CLOUD_PROOF_MAX_LIFETIME_SECONDS = 5 * 60; +const CLOUD_PROOF_CLOCK_SKEW_SECONDS = 60; +const LOOPBACK_HOSTNAMES = new Set(["127.0.0.1", "::1", "localhost"]); +const CLOUD_CREDENTIAL_RESPONSE_HEADERS = { + "cache-control": "no-store", + pragma: "no-cache", +} as const; + +const appendCloudCredentialResponseHeaders = HttpEffect.appendPreResponseHandler( + (_request, response) => + Effect.succeed(HttpServerResponse.setHeaders(response, CLOUD_CREDENTIAL_RESPONSE_HEADERS)), +); + +const failEnvironmentCloudInternalError = + (message: string) => + (cause: unknown): Effect.Effect => + Effect.logError(message, { cause }).pipe( + Effect.flatMap(() => Effect.fail(new EnvironmentHttpInternalServerError({ message }))), + ); + +function bytesToString(bytes: Uint8Array): string { + return new TextDecoder().decode(bytes); +} + +function stringToBytes(value: string): Uint8Array { + return new TextEncoder().encode(value); +} + +export function consumeCloudReplayGuards(input: { + readonly secrets: ServerSecretStore.ServerSecretStoreShape; + readonly names: ReadonlyArray; + readonly value: Uint8Array; +}) { + return Effect.all( + input.names.map((name) => + input.secrets.create(name, input.value).pipe( + Effect.as(true), + Effect.catchTag("SecretStoreError", (error) => + ServerSecretStore.isSecretAlreadyExistsError(error) + ? Effect.succeed(false) + : Effect.fail(error), + ), + ), + ), + { concurrency: input.names.length }, + ).pipe(Effect.map((created) => created.every(Boolean))); +} + +function normalizePemForSignedPayload(value: string): string { + return value.trim(); +} + +function normalizeHostname(hostname: string): string { + return hostname + .trim() + .toLowerCase() + .replace(/^\[(.*)\]$/, "$1"); +} + +function validateCloudMintPublicKey( + publicKey: string, +): Effect.Effect { + return Effect.try({ + try: () => NodeCrypto.createPublicKey(publicKey.replace(/\\n/g, "\n")), + catch: () => + new EnvironmentHttpBadRequestError({ + message: "Cloud mint public key must be a valid Ed25519 public key.", + }), + }).pipe( + Effect.flatMap((key) => + key.asymmetricKeyType === "ed25519" + ? Effect.void + : Effect.fail( + new EnvironmentHttpBadRequestError({ + message: "Cloud mint public key must be a valid Ed25519 public key.", + }), + ), + ), + ); +} + +function isSecureRelayUrl(value: string): boolean { + try { + const url = new URL(value); + return ( + url.protocol === "https:" && + url.username.length === 0 && + url.password.length === 0 && + url.hash.length === 0 + ); + } catch { + return false; + } +} + +function validateRelayConfigPayload( + payload: RelayEnvironmentConfigRequest, +): Effect.Effect { + if (!isSecureRelayUrl(payload.relayUrl)) { + return Effect.fail( + new EnvironmentHttpBadRequestError({ + message: "Relay URL must be a secure absolute HTTPS URL.", + }), + ); + } + if (payload.relayIssuer !== undefined && !isSecureRelayUrl(payload.relayIssuer)) { + return Effect.fail( + new EnvironmentHttpBadRequestError({ + message: "Relay issuer must be a secure absolute HTTPS URL.", + }), + ); + } + if (payload.environmentCredential.trim().length === 0) { + return Effect.fail( + new EnvironmentHttpBadRequestError({ + message: "Relay environment credential is required.", + }), + ); + } + if (payload.cloudUserId.trim().length === 0) { + return Effect.fail( + new EnvironmentHttpBadRequestError({ + message: "Cloud user id is required.", + }), + ); + } + return Effect.void; +} + +function validateLinkedCloudUser(input: { + readonly secrets: ServerSecretStore.ServerSecretStoreShape; + readonly cloudUserId: string; +}): Effect.Effect { + return input.secrets.get(CLOUD_LINKED_USER_ID).pipe( + Effect.mapError( + (cause) => + new EnvironmentAuth.ServerAuthInternalError({ + message: "Could not verify the linked cloud account.", + cause, + }), + ), + Effect.flatMap((existing) => { + if (!existing) { + return Effect.void; + } + const existingCloudUserId = bytesToString(existing); + return existingCloudUserId === input.cloudUserId + ? Effect.void + : Effect.fail( + new EnvironmentHttpConflictError({ + message: + "This environment is already linked to a different cloud account. Unlink it before switching accounts.", + }), + ); + }), + ); +} + +function readInstalledCloudUserId( + secrets: ServerSecretStore.ServerSecretStoreShape, +): Effect.Effect { + return secrets.get(CLOUD_LINKED_USER_ID).pipe( + Effect.mapError( + (cause) => + new EnvironmentAuth.ServerAuthInternalError({ + message: "Could not read the linked cloud account.", + cause, + }), + ), + Effect.flatMap((bytes) => + bytes + ? Effect.succeed(bytesToString(bytes)) + : Effect.fail( + new EnvironmentAuth.ServerAuthInternalError({ + message: "Cloud linked user is not installed for this environment.", + }), + ), + ), + ); +} + +function isLoopbackHostname(hostname: string): boolean { + return LOOPBACK_HOSTNAMES.has(normalizeHostname(hostname)); +} + +function firstForwardedHeaderValue(value: string | undefined): string | undefined { + const first = value?.split(",")[0]?.trim(); + return first && first.length > 0 ? first : undefined; +} + +function requestAbsoluteUrl(request: HttpServerRequest.HttpServerRequest): string | null { + try { + return new URL(request.originalUrl).href; + } catch { + const host = firstForwardedHeaderValue(request.headers.host) ?? "127.0.0.1"; + try { + return new URL(request.originalUrl, `http://${host}`).href; + } catch { + return null; + } + } +} + +function hasForwardedAuthorityHeaders(request: HttpServerRequest.HttpServerRequest): boolean { + return ( + firstForwardedHeaderValue(request.headers["x-forwarded-host"]) !== undefined || + firstForwardedHeaderValue(request.headers["x-forwarded-proto"]) !== undefined + ); +} + +function endpointRequestPort(url: URL): number { + return Number(url.port || (url.protocol === "https:" ? 443 : 80)); +} + +function isAllowedEndpointOrigin(input: { + readonly origin: RelayManagedEndpointOrigin; + readonly requestUrl: string; +}): boolean { + if (!isLoopbackHostname(input.origin.localHttpHost)) { + return false; + } + + const url = new URL(input.requestUrl); + if (!isLoopbackHostname(url.hostname)) { + return false; + } + + return input.origin.localHttpPort === endpointRequestPort(url); +} + +function providerKindMatchesRequestedLinkScopes(request: RelayLinkProofRequest): boolean { + return request.endpoint.providerKind === "cloudflare_tunnel"; +} + +function hasExactScope(input: { + readonly scopes: ReadonlyArray; + readonly expected: string; +}): boolean { + return input.scopes.length === 1 && input.scopes[0] === input.expected; +} + +function hasBoundedCloudProofLifetime(input: { + readonly iat: number; + readonly exp: number; + readonly nowSeconds: number; +}): boolean { + return ( + input.exp > input.iat && + input.exp - input.iat <= CLOUD_PROOF_MAX_LIFETIME_SECONDS && + input.iat <= input.nowSeconds + CLOUD_PROOF_CLOCK_SKEW_SECONDS + ); +} + +const decodeCloudHealthProof = Schema.decodeUnknownEffect(RelayCloudEnvironmentHealthProofPayload); +const decodeCloudMintProof = Schema.decodeUnknownEffect(RelayCloudMintCredentialProofPayload); + +export const getOrCreateEnvironmentKeyPairFromSecretStore = Effect.fn(function* ( + secrets: ServerSecretStore.ServerSecretStoreShape, +) { + const existingPrivate = yield* secrets.get(CLOUD_LINK_PRIVATE_KEY); + const existingPublic = yield* secrets.get(CLOUD_LINK_PUBLIC_KEY); + if (existingPrivate && existingPublic) { + return { + privateKey: bytesToString(existingPrivate), + publicKey: bytesToString(existingPublic), + }; + } + + const keyPair = NodeCrypto.generateKeyPairSync("ed25519", { + privateKeyEncoding: { format: "pem", type: "pkcs8" }, + publicKeyEncoding: { format: "pem", type: "spki" }, + }); + yield* secrets.set(CLOUD_LINK_PRIVATE_KEY, stringToBytes(keyPair.privateKey)); + yield* secrets.set(CLOUD_LINK_PUBLIC_KEY, stringToBytes(keyPair.publicKey)); + return { + privateKey: keyPair.privateKey, + publicKey: keyPair.publicKey, + }; +}); + +interface CloudHttpDependencies { + readonly secrets: ServerSecretStore.ServerSecretStoreShape; + readonly environment: ServerEnvironmentShape; + readonly endpointRuntime: CloudManagedEndpointRuntimeShape; + readonly environmentAuth: EnvironmentAuth.EnvironmentAuthShape; +} + +const cloudLinkProofHandler = Effect.fn("environment.cloud.linkProof")( + function* (dependencies: CloudHttpDependencies, request: RelayLinkProofRequest) { + yield* requireEnvironmentScope(AuthRelayManageScope); + const httpRequest = yield* HttpServerRequest.HttpServerRequest; + const keyPair = yield* getOrCreateEnvironmentKeyPairFromSecretStore(dependencies.secrets); + const requestUrl = requestAbsoluteUrl(httpRequest); + if ( + requestUrl === null || + hasForwardedAuthorityHeaders(httpRequest) || + !providerKindMatchesRequestedLinkScopes(request) || + !isAllowedEndpointOrigin({ + origin: request.origin, + requestUrl, + }) + ) { + return yield* new EnvironmentHttpBadRequestError({ + message: "Invalid managed endpoint origin.", + }); + } + const now = yield* DateTime.now; + const expiresAt = DateTime.add(now, { minutes: 5 }); + const nowSeconds = Math.floor(now.epochMilliseconds / 1_000); + const descriptor = yield* dependencies.environment.getDescriptor; + const payload = { + iss: `t3-env:${descriptor.environmentId}`, + aud: normalizeRelayIssuer(request.relayIssuer), + sub: descriptor.environmentId, + jti: yield* Crypto.Crypto.pipe(Effect.flatMap((crypto) => crypto.randomUUIDv4)), + iat: nowSeconds, + exp: Math.floor(expiresAt.epochMilliseconds / 1_000), + challenge: request.challenge, + descriptor, + environmentId: descriptor.environmentId, + environmentPublicKey: normalizePemForSignedPayload(keyPair.publicKey), + endpoint: request.endpoint, + origin: request.origin, + scopes: ["agent_activity_notifications", "managed_tunnels"], + } satisfies RelayEnvironmentLinkProofPayload; + const proof = yield* signRelayJwt({ + privateKey: keyPair.privateKey, + typ: RELAY_LINK_PROOF_TYP, + payload, + }).pipe( + Effect.mapError( + (cause) => + new EnvironmentAuth.ServerAuthInternalError({ + message: "Failed to sign cloud link JWT.", + cause, + }), + ), + ); + yield* appendCloudCredentialResponseHeaders; + return proof satisfies RelayEnvironmentLinkProof; + }, + Effect.catchTag("ServerAuthInternalError", (error) => + failEnvironmentCloudInternalError(error.message)(error.cause), + ), + Effect.catchTags({ + PlatformError: failEnvironmentCloudInternalError("Could not generate environment link proof."), + SecretStoreError: failEnvironmentCloudInternalError( + "Could not generate environment link proof.", + ), + }), +); + +const cloudRelayConfigHandler = Effect.fn("environment.cloud.relayConfig")( + function* (dependencies: CloudHttpDependencies, payload: RelayEnvironmentConfigRequest) { + yield* requireEnvironmentScope(AuthRelayManageScope); + yield* validateRelayConfigPayload(payload); + yield* validateLinkedCloudUser({ + secrets: dependencies.secrets, + cloudUserId: payload.cloudUserId, + }); + yield* validateCloudMintPublicKey(payload.cloudMintPublicKey); + const endpointRuntimeStatus = yield* dependencies.endpointRuntime.applyConfig( + payload.endpointRuntime, + ); + const ok = + endpointRuntimeStatus.status === "disabled" || endpointRuntimeStatus.status === "running"; + if (!ok) { + return yield* new EnvironmentCloudEndpointUnavailableError({ + message: "Managed endpoint runtime could not be started.", + endpointRuntimeStatus, + }); + } + + yield* dependencies.secrets.set(RELAY_URL_SECRET, stringToBytes(payload.relayUrl)); + yield* dependencies.secrets.set( + RELAY_ISSUER_SECRET, + stringToBytes(payload.relayIssuer ?? payload.relayUrl), + ); + yield* dependencies.secrets.set(CLOUD_LINKED_USER_ID, stringToBytes(payload.cloudUserId)); + yield* dependencies.secrets.set( + RELAY_ENVIRONMENT_CREDENTIAL_SECRET, + stringToBytes(payload.environmentCredential), + ); + yield* dependencies.secrets.set( + CLOUD_MINT_PUBLIC_KEY, + stringToBytes(payload.cloudMintPublicKey), + ); + if (payload.endpointRuntime) { + const endpointRuntimeJson = yield* encodeEndpointRuntimeConfigJson(payload.endpointRuntime); + yield* dependencies.secrets.set( + CLOUD_ENDPOINT_RUNTIME_CONFIG, + stringToBytes(endpointRuntimeJson), + ); + } else { + yield* dependencies.secrets.remove(CLOUD_ENDPOINT_RUNTIME_CONFIG); + } + return { ok, endpointRuntimeStatus } satisfies EnvironmentCloudRelayConfigResult; + }, + Effect.catchTag("ServerAuthInternalError", (error) => + failEnvironmentCloudInternalError(error.message)(error.cause), + ), + Effect.catchTags({ + SchemaError: failEnvironmentCloudInternalError( + "Could not persist environment relay configuration.", + ), + SecretStoreError: failEnvironmentCloudInternalError( + "Could not persist environment relay configuration.", + ), + }), +); + +const cloudLinkStateHandler = Effect.fn("environment.cloud.linkState")( + function* (dependencies: CloudHttpDependencies) { + yield* requireEnvironmentScope(AuthRelayManageScope); + const [cloudUserId, relayUrl, relayIssuer] = yield* Effect.all( + [ + dependencies.secrets.get(CLOUD_LINKED_USER_ID), + dependencies.secrets.get(RELAY_URL_SECRET), + dependencies.secrets.get(RELAY_ISSUER_SECRET), + ], + { concurrency: 3 }, + ); + const response = { + linked: cloudUserId !== null, + cloudUserId: cloudUserId ? bytesToString(cloudUserId) : null, + relayUrl: relayUrl ? bytesToString(relayUrl) : null, + relayIssuer: relayIssuer ? bytesToString(relayIssuer) : null, + } satisfies EnvironmentCloudLinkStateResult; + return response; + }, + Effect.catchTag( + "SecretStoreError", + failEnvironmentCloudInternalError("Could not read environment relay configuration."), + ), +); + +const cloudUnlinkHandler = Effect.fn("environment.cloud.unlink")( + function* (dependencies: CloudHttpDependencies) { + yield* requireEnvironmentScope(AuthRelayManageScope); + const endpointRuntimeStatus = yield* dependencies.endpointRuntime.applyConfig(null); + yield* Effect.all( + [ + dependencies.secrets.remove(CLOUD_LINKED_USER_ID), + dependencies.secrets.remove(RELAY_URL_SECRET), + dependencies.secrets.remove(RELAY_ISSUER_SECRET), + dependencies.secrets.remove(RELAY_ENVIRONMENT_CREDENTIAL_SECRET), + dependencies.secrets.remove(CLOUD_MINT_PUBLIC_KEY), + dependencies.secrets.remove(CLOUD_ENDPOINT_RUNTIME_CONFIG), + ], + { concurrency: 6 }, + ); + return { ok: true, endpointRuntimeStatus } satisfies EnvironmentCloudRelayConfigResult; + }, + Effect.catchTag( + "SecretStoreError", + failEnvironmentCloudInternalError("Could not remove environment relay configuration."), + ), +); + +const cloudEnvironmentHealthHandler = Effect.fn("environment.cloud.health")( + function* (dependencies: CloudHttpDependencies, request: RelayCloudEnvironmentHealthRequest) { + const keyPair = yield* getOrCreateEnvironmentKeyPairFromSecretStore(dependencies.secrets); + const cloudMintPublicKey = yield* dependencies.secrets.get(CLOUD_MINT_PUBLIC_KEY).pipe( + Effect.flatMap((bytes) => + bytes + ? Effect.succeed(bytesToString(bytes)) + : Effect.fail( + new EnvironmentAuth.ServerAuthInternalError({ + message: "Cloud mint public key is not installed for this environment.", + }), + ), + ), + ); + const relayIssuer = yield* dependencies.secrets.get(RELAY_ISSUER_SECRET).pipe( + Effect.flatMap((bytes) => + bytes + ? Effect.succeed(bytesToString(bytes)) + : dependencies.secrets.get(RELAY_URL_SECRET).pipe( + Effect.flatMap((fallbackBytes) => + fallbackBytes + ? Effect.succeed(bytesToString(fallbackBytes)) + : Effect.fail( + new EnvironmentAuth.ServerAuthInternalError({ + message: "Cloud relay issuer is not installed for this environment.", + }), + ), + ), + ), + ), + ); + const environmentId = yield* dependencies.environment.getEnvironmentId; + const linkedCloudUserId = yield* readInstalledCloudUserId(dependencies.secrets); + const now = yield* DateTime.now; + const nowSeconds = Math.floor(now.epochMilliseconds / 1_000); + const proofOption = yield* verifyRelayJwt({ + publicKey: cloudMintPublicKey, + token: request.proof, + typ: RELAY_HEALTH_REQUEST_TYP, + issuer: normalizeRelayIssuer(relayIssuer), + audience: `t3-env:${environmentId}`, + nowEpochSeconds: nowSeconds, + }).pipe(Effect.flatMap(decodeCloudHealthProof), Effect.option); + if ( + Option.isNone(proofOption) || + proofOption.value.environmentId !== environmentId || + proofOption.value.sub !== linkedCloudUserId || + !hasBoundedCloudProofLifetime({ ...proofOption.value, nowSeconds }) || + !hasExactScope({ scopes: proofOption.value.scope, expected: "environment:status" }) + ) { + return yield* new EnvironmentHttpUnauthorizedError({ + message: "Invalid cloud health request.", + }); + } + const proof = proofOption.value; + + const jtiSecretName = `${CLOUD_HEALTH_JTI_PREFIX}${proof.jti}`; + const nonceSecretName = `${CLOUD_HEALTH_NONCE_PREFIX}${proof.nonce}`; + const consumedReplayGuards = yield* consumeCloudReplayGuards({ + secrets: dependencies.secrets, + names: [jtiSecretName, nonceSecretName], + value: stringToBytes(DateTime.formatIso(now)), + }); + if (!consumedReplayGuards) { + return yield* new EnvironmentHttpConflictError({ + message: "Cloud health request was already consumed.", + }); + } + + const descriptor = yield* dependencies.environment.getDescriptor; + const responseExpiresAt = DateTime.add(now, { minutes: 5 }); + const responsePayload = { + iss: `t3-env:${environmentId}`, + aud: normalizeRelayIssuer(relayIssuer), + sub: environmentId, + jti: yield* Crypto.Crypto.pipe(Effect.flatMap((crypto) => crypto.randomUUIDv4)), + iat: nowSeconds, + exp: Math.floor(responseExpiresAt.epochMilliseconds / 1_000), + environmentId, + requestNonce: proof.nonce, + status: "online", + descriptor, + checkedAt: DateTime.formatIso(now), + } satisfies RelayEnvironmentHealthResponseProofPayload; + const responseProof = yield* signRelayJwt({ + privateKey: keyPair.privateKey, + typ: RELAY_HEALTH_RESPONSE_TYP, + payload: responsePayload, + }).pipe( + Effect.mapError( + (cause) => + new EnvironmentAuth.ServerAuthInternalError({ + message: "Failed to sign cloud health JWT.", + cause, + }), + ), + ); + const response = { + environmentId, + status: "online", + descriptor, + checkedAt: responsePayload.checkedAt, + proof: responseProof, + } satisfies RelayEnvironmentHealthResponseShape; + + yield* appendCloudCredentialResponseHeaders; + return response; + }, + Effect.catchTag("ServerAuthInternalError", (error) => + failEnvironmentCloudInternalError(error.message)(error.cause), + ), + Effect.catchTags({ + PlatformError: failEnvironmentCloudInternalError("Could not answer cloud health request."), + SecretStoreError: failEnvironmentCloudInternalError("Could not answer cloud health request."), + }), +); + +const cloudMintCredentialHandler = Effect.fn("environment.cloud.mintCredential")( + function* (dependencies: CloudHttpDependencies, request: RelayCloudMintCredentialRequest) { + const keyPair = yield* getOrCreateEnvironmentKeyPairFromSecretStore(dependencies.secrets); + const cloudMintPublicKey = yield* dependencies.secrets.get(CLOUD_MINT_PUBLIC_KEY).pipe( + Effect.flatMap((bytes) => + bytes + ? Effect.succeed(bytesToString(bytes)) + : Effect.fail( + new EnvironmentAuth.ServerAuthInternalError({ + message: "Cloud mint public key is not installed for this environment.", + }), + ), + ), + ); + const relayIssuer = yield* dependencies.secrets.get(RELAY_ISSUER_SECRET).pipe( + Effect.flatMap((bytes) => + bytes + ? Effect.succeed(bytesToString(bytes)) + : dependencies.secrets.get(RELAY_URL_SECRET).pipe( + Effect.flatMap((fallbackBytes) => + fallbackBytes + ? Effect.succeed(bytesToString(fallbackBytes)) + : Effect.fail( + new EnvironmentAuth.ServerAuthInternalError({ + message: "Cloud relay issuer is not installed for this environment.", + }), + ), + ), + ), + ), + ); + const environmentId = yield* dependencies.environment.getEnvironmentId; + const linkedCloudUserId = yield* readInstalledCloudUserId(dependencies.secrets); + const now = yield* DateTime.now; + const nowSeconds = Math.floor(now.epochMilliseconds / 1_000); + const proofOption = yield* verifyRelayJwt({ + publicKey: cloudMintPublicKey, + token: request.proof, + typ: RELAY_MINT_REQUEST_TYP, + issuer: normalizeRelayIssuer(relayIssuer), + audience: `t3-env:${environmentId}`, + nowEpochSeconds: nowSeconds, + }).pipe(Effect.flatMap(decodeCloudMintProof), Effect.option); + if ( + Option.isNone(proofOption) || + proofOption.value.environmentId !== environmentId || + proofOption.value.sub !== linkedCloudUserId || + proofOption.value.cnf.jkt !== proofOption.value.clientProofKeyThumbprint || + !hasBoundedCloudProofLifetime({ ...proofOption.value, nowSeconds }) || + !hasExactScope({ scopes: proofOption.value.scope, expected: "environment:connect" }) + ) { + return yield* new EnvironmentHttpUnauthorizedError({ + message: "Invalid cloud mint request.", + }); + } + const proof = proofOption.value; + + const jtiSecretName = `${CLOUD_MINT_JTI_PREFIX}${proof.jti}`; + const nonceSecretName = `${CLOUD_MINT_NONCE_PREFIX}${proof.nonce}`; + const consumedReplayGuards = yield* consumeCloudReplayGuards({ + secrets: dependencies.secrets, + names: [jtiSecretName, nonceSecretName], + value: stringToBytes(DateTime.formatIso(now)), + }); + if (!consumedReplayGuards) { + return yield* new EnvironmentHttpConflictError({ + message: "Cloud mint request was already consumed.", + }); + } + + const issued = yield* dependencies.environmentAuth.createPairingLink({ + scopes: AuthStandardClientScopes, + subject: "cloud-connect", + ttl: Duration.minutes(2), + label: "T3 Cloud connect", + proofKeyThumbprint: proof.clientProofKeyThumbprint, + }); + const responsePayload = { + iss: `t3-env:${environmentId}`, + aud: normalizeRelayIssuer(relayIssuer), + sub: environmentId, + jti: yield* Crypto.Crypto.pipe(Effect.flatMap((crypto) => crypto.randomUUIDv4)), + iat: nowSeconds, + exp: Math.floor(issued.expiresAt.epochMilliseconds / 1_000), + environmentId, + clientProofKeyThumbprint: proof.clientProofKeyThumbprint, + requestNonce: proof.nonce, + credential: issued.credential, + } satisfies RelayEnvironmentMintResponseProofPayload; + const responseProof = yield* signRelayJwt({ + privateKey: keyPair.privateKey, + typ: RELAY_MINT_RESPONSE_TYP, + payload: responsePayload, + }).pipe( + Effect.mapError( + (cause) => + new EnvironmentAuth.ServerAuthInternalError({ + message: "Failed to sign cloud mint JWT.", + cause, + }), + ), + ); + const response = { + credential: issued.credential, + expiresAt: DateTime.formatIso(issued.expiresAt), + proof: responseProof, + } satisfies RelayEnvironmentMintResponseShape; + + yield* appendCloudCredentialResponseHeaders; + return response; + }, + Effect.catchTag("ServerAuthInternalError", (error) => + failEnvironmentCloudInternalError(error.message)(error.cause), + ), + Effect.catchTags({ + PlatformError: failEnvironmentCloudInternalError( + "Could not issue cloud connection credential.", + ), + SecretStoreError: failEnvironmentCloudInternalError( + "Could not issue cloud connection credential.", + ), + }), +); + +export const cloudHttpApiLayer = HttpApiBuilder.group( + EnvironmentHttpApi, + "cloud", + Effect.fnUntraced(function* (handlers) { + const dependencies: CloudHttpDependencies = { + secrets: yield* ServerSecretStore.ServerSecretStore, + environment: yield* ServerEnvironment, + endpointRuntime: yield* CloudManagedEndpointRuntime, + environmentAuth: yield* EnvironmentAuth.EnvironmentAuth, + }; + return handlers + .handle("linkProof", ({ payload }) => cloudLinkProofHandler(dependencies, payload)) + .handle("relayConfig", ({ payload }) => cloudRelayConfigHandler(dependencies, payload)) + .handle("linkState", () => cloudLinkStateHandler(dependencies)) + .handle("unlink", () => cloudUnlinkHandler(dependencies)) + .handle("health", ({ payload }) => cloudEnvironmentHealthHandler(dependencies, payload)) + .handle("mintCredential", ({ payload }) => cloudMintCredentialHandler(dependencies, payload)) + .handle("t3MintCredential", ({ payload }) => + cloudMintCredentialHandler(dependencies, payload), + ); + }), +); diff --git a/apps/server/src/httpCors.ts b/apps/server/src/httpCors.ts index e44486d3c4..aeb8dbce5a 100644 --- a/apps/server/src/httpCors.ts +++ b/apps/server/src/httpCors.ts @@ -4,6 +4,7 @@ export const browserApiCorsAllowedHeaders = [ "b3", "traceparent", "content-type", + "dpop", ] as const; export const browserApiCorsHeaders = { diff --git a/apps/server/src/orchestration/Layers/OrchestrationReactor.test.ts b/apps/server/src/orchestration/Layers/OrchestrationReactor.test.ts index 13524ae85d..300d1526bb 100644 --- a/apps/server/src/orchestration/Layers/OrchestrationReactor.test.ts +++ b/apps/server/src/orchestration/Layers/OrchestrationReactor.test.ts @@ -11,6 +11,7 @@ import { ProviderRuntimeIngestionService } from "../Services/ProviderRuntimeInge import { ThreadDeletionReactor } from "../Services/ThreadDeletionReactor.ts"; import { OrchestrationReactor } from "../Services/OrchestrationReactor.ts"; import { makeOrchestrationReactor } from "./OrchestrationReactor.ts"; +import * as AgentAwarenessRelay from "../../relay/AgentAwarenessRelay.ts"; describe("OrchestrationReactor", () => { let runtime: ManagedRuntime.ManagedRuntime | null = null; @@ -63,6 +64,15 @@ describe("OrchestrationReactor", () => { drain: Effect.void, }), ), + Layer.provideMerge( + Layer.succeed(AgentAwarenessRelay.AgentAwarenessRelay, { + publishThread: () => Effect.void, + start: () => { + started.push("agent-awareness-relay"); + return Effect.void; + }, + }), + ), ), ); @@ -75,6 +85,7 @@ describe("OrchestrationReactor", () => { "provider-command-reactor", "checkpoint-reactor", "thread-deletion-reactor", + "agent-awareness-relay", ]); await Effect.runPromise(Scope.close(scope, Exit.void)); diff --git a/apps/server/src/orchestration/Layers/OrchestrationReactor.ts b/apps/server/src/orchestration/Layers/OrchestrationReactor.ts index 5e432d9884..fb7543e31a 100644 --- a/apps/server/src/orchestration/Layers/OrchestrationReactor.ts +++ b/apps/server/src/orchestration/Layers/OrchestrationReactor.ts @@ -9,18 +9,21 @@ import { CheckpointReactor } from "../Services/CheckpointReactor.ts"; import { ProviderCommandReactor } from "../Services/ProviderCommandReactor.ts"; import { ProviderRuntimeIngestionService } from "../Services/ProviderRuntimeIngestion.ts"; import { ThreadDeletionReactor } from "../Services/ThreadDeletionReactor.ts"; +import * as AgentAwarenessRelay from "../../relay/AgentAwarenessRelay.ts"; export const makeOrchestrationReactor = Effect.gen(function* () { const providerRuntimeIngestion = yield* ProviderRuntimeIngestionService; const providerCommandReactor = yield* ProviderCommandReactor; const checkpointReactor = yield* CheckpointReactor; const threadDeletionReactor = yield* ThreadDeletionReactor; + const agentAwarenessRelay = yield* AgentAwarenessRelay.AgentAwarenessRelay; const start: OrchestrationReactorShape["start"] = Effect.fn("start")(function* () { yield* providerRuntimeIngestion.start(); yield* providerCommandReactor.start(); yield* checkpointReactor.start(); yield* threadDeletionReactor.start(); + yield* agentAwarenessRelay.start(); }); return { diff --git a/apps/server/src/persistence/Layers/AuthPairingLinks.ts b/apps/server/src/persistence/Layers/AuthPairingLinks.ts index 7519c65c12..9d2760d144 100644 --- a/apps/server/src/persistence/Layers/AuthPairingLinks.ts +++ b/apps/server/src/persistence/Layers/AuthPairingLinks.ts @@ -41,6 +41,7 @@ const makeAuthPairingLinkRepository = Effect.gen(function* () { scopes, subject, label, + proof_key_thumbprint, created_at, expires_at, consumed_at, @@ -53,6 +54,7 @@ const makeAuthPairingLinkRepository = Effect.gen(function* () { ${JSON.stringify(input.scopes)}, ${input.subject}, ${input.label}, + ${input.proofKeyThumbprint}, ${input.createdAt}, ${input.expiresAt}, NULL, @@ -64,7 +66,7 @@ const makeAuthPairingLinkRepository = Effect.gen(function* () { const consumeAvailablePairingLinkRow = SqlSchema.findOneOption({ Request: ConsumeAuthPairingLinkInput, Result: AuthPairingLinkRecord, - execute: ({ credential, consumedAt, now }) => + execute: ({ credential, proofKeyThumbprint, consumedAt, now }) => sql` UPDATE auth_pairing_links SET consumed_at = ${consumedAt} @@ -72,6 +74,10 @@ const makeAuthPairingLinkRepository = Effect.gen(function* () { AND revoked_at IS NULL AND consumed_at IS NULL AND expires_at > ${now} + AND ( + proof_key_thumbprint IS NULL + OR proof_key_thumbprint = ${proofKeyThumbprint} + ) RETURNING id AS "id", credential AS "credential", @@ -79,6 +85,7 @@ const makeAuthPairingLinkRepository = Effect.gen(function* () { scopes AS "scopes", subject AS "subject", label AS "label", + proof_key_thumbprint AS "proofKeyThumbprint", created_at AS "createdAt", expires_at AS "expiresAt", consumed_at AS "consumedAt", @@ -98,6 +105,7 @@ const makeAuthPairingLinkRepository = Effect.gen(function* () { scopes AS "scopes", subject AS "subject", label AS "label", + proof_key_thumbprint AS "proofKeyThumbprint", created_at AS "createdAt", expires_at AS "expiresAt", consumed_at AS "consumedAt", @@ -136,6 +144,7 @@ const makeAuthPairingLinkRepository = Effect.gen(function* () { scopes AS "scopes", subject AS "subject", label AS "label", + proof_key_thumbprint AS "proofKeyThumbprint", created_at AS "createdAt", expires_at AS "expiresAt", consumed_at AS "consumedAt", diff --git a/apps/server/src/persistence/Migrations.ts b/apps/server/src/persistence/Migrations.ts index 9524deae8d..ba1131ee25 100644 --- a/apps/server/src/persistence/Migrations.ts +++ b/apps/server/src/persistence/Migrations.ts @@ -44,6 +44,7 @@ import Migration0028 from "./Migrations/028_ProjectionThreadSessionInstanceId.ts import Migration0029 from "./Migrations/029_ProjectionThreadDetailOrderingIndexes.ts"; import Migration0030 from "./Migrations/030_ProjectionThreadShellArchiveIndexes.ts"; import Migration0031 from "./Migrations/031_AuthAuthorizationScopes.ts"; +import Migration0032 from "./Migrations/032_AuthPairingProofKeyThumbprint.ts"; /** * Migration loader with all migrations defined inline. @@ -87,6 +88,7 @@ export const migrationEntries = [ [29, "ProjectionThreadDetailOrderingIndexes", Migration0029], [30, "ProjectionThreadShellArchiveIndexes", Migration0030], [31, "AuthAuthorizationScopes", Migration0031], + [32, "AuthPairingProofKeyThumbprint", Migration0032], ] as const; export const makeMigrationLoader = (throughId?: number) => diff --git a/apps/server/src/persistence/Migrations/032_AuthPairingProofKeyThumbprint.ts b/apps/server/src/persistence/Migrations/032_AuthPairingProofKeyThumbprint.ts new file mode 100644 index 0000000000..db414213a1 --- /dev/null +++ b/apps/server/src/persistence/Migrations/032_AuthPairingProofKeyThumbprint.ts @@ -0,0 +1,16 @@ +import * as Effect from "effect/Effect"; +import * as SqlClient from "effect/unstable/sql/SqlClient"; + +export default Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + + const pairingLinkColumns = yield* sql<{ readonly name: string }>` + PRAGMA table_info(auth_pairing_links) + `; + if (!pairingLinkColumns.some((column) => column.name === "proof_key_thumbprint")) { + yield* sql` + ALTER TABLE auth_pairing_links + ADD COLUMN proof_key_thumbprint TEXT + `; + } +}); diff --git a/apps/server/src/persistence/Services/AuthPairingLinks.ts b/apps/server/src/persistence/Services/AuthPairingLinks.ts index 16a9c4035a..c8745982d2 100644 --- a/apps/server/src/persistence/Services/AuthPairingLinks.ts +++ b/apps/server/src/persistence/Services/AuthPairingLinks.ts @@ -13,6 +13,7 @@ export const AuthPairingLinkRecord = Schema.Struct({ scopes: Schema.fromJsonString(AuthEnvironmentScopes), subject: Schema.String, label: Schema.NullOr(Schema.String), + proofKeyThumbprint: Schema.NullOr(Schema.String), createdAt: Schema.DateTimeUtcFromString, expiresAt: Schema.DateTimeUtcFromString, consumedAt: Schema.NullOr(Schema.DateTimeUtcFromString), @@ -27,6 +28,7 @@ export const CreateAuthPairingLinkInput = Schema.Struct({ scopes: AuthEnvironmentScopes, subject: Schema.String, label: Schema.NullOr(Schema.String), + proofKeyThumbprint: Schema.NullOr(Schema.String), createdAt: Schema.DateTimeUtcFromString, expiresAt: Schema.DateTimeUtcFromString, }); @@ -34,6 +36,7 @@ export type CreateAuthPairingLinkInput = typeof CreateAuthPairingLinkInput.Type; export const ConsumeAuthPairingLinkInput = Schema.Struct({ credential: Schema.String, + proofKeyThumbprint: Schema.NullOr(Schema.String), consumedAt: Schema.DateTimeUtcFromString, now: Schema.DateTimeUtcFromString, }); diff --git a/apps/server/src/relay/AgentAwarenessRelay.test.ts b/apps/server/src/relay/AgentAwarenessRelay.test.ts new file mode 100644 index 0000000000..abb54057b1 --- /dev/null +++ b/apps/server/src/relay/AgentAwarenessRelay.test.ts @@ -0,0 +1,634 @@ +import * as NodeCrypto from "node:crypto"; +import * as NodeServices from "@effect/platform-node/NodeServices"; + +import type { + EnvironmentId, + ExecutionEnvironmentDescriptor, + OrchestrationEvent, + OrchestrationProjectShell, + OrchestrationShellSnapshot, + OrchestrationThreadShell, + ProjectId, + ThreadId, + TurnId, +} from "@t3tools/contracts"; +import type { + RelayAgentActivityPublishProofPayload, + RelayAgentActivityState, +} from "@t3tools/contracts/relay"; +import { CommandId, ProviderInstanceId } from "@t3tools/contracts"; +import { RELAY_ACTIVITY_PUBLISH_TYP, verifyRelayJwt } from "@t3tools/shared/relayJwt"; +import { describe, expect, it } from "@effect/vitest"; +import * as Deferred from "effect/Deferred"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import * as Option from "effect/Option"; +import * as Queue from "effect/Queue"; +import * as Stream from "effect/Stream"; + +import * as ServerSecretStore from "../auth/ServerSecretStore.ts"; +import { ServerEnvironment } from "../environment/Services/ServerEnvironment.ts"; +import { + OrchestrationEngineService, + type OrchestrationEngineShape, +} from "../orchestration/Services/OrchestrationEngine.ts"; +import { + ProjectionSnapshotQuery, + type ProjectionSnapshotQueryShape, +} from "../orchestration/Services/ProjectionSnapshotQuery.ts"; +import { + RELAY_ENVIRONMENT_CREDENTIAL_SECRET, + RELAY_ISSUER_SECRET, + RELAY_URL_SECRET, +} from "../cloud/config.ts"; +import * as AgentAwarenessRelay from "./AgentAwarenessRelay.ts"; + +const state: RelayAgentActivityState = { + environmentId: "env" as RelayAgentActivityState["environmentId"], + threadId: "thread" as RelayAgentActivityState["threadId"], + projectTitle: "Project", + threadTitle: "Thread", + modelTitle: "gpt-5.4", + phase: "running", + headline: "Running", + updatedAt: "2026-05-25T00:00:00.000Z", + deepLink: "/threads/env/thread", +}; + +const encodeSecret = (value: string): Uint8Array => new TextEncoder().encode(value); + +function makeMemorySecretStore() { + const values = new Map(); + const store = { + get: ((name) => + Effect.sync( + () => values.get(name) ?? null, + )) satisfies ServerSecretStore.ServerSecretStoreShape["get"], + set: ((name, value) => + Effect.sync(() => { + values.set(name, Uint8Array.from(value)); + })) satisfies ServerSecretStore.ServerSecretStoreShape["set"], + create: ((name, value) => + Effect.sync(() => { + values.set(name, Uint8Array.from(value)); + })) satisfies ServerSecretStore.ServerSecretStoreShape["create"], + getOrCreateRandom: ((name, bytes) => + Effect.sync(() => { + const existing = values.get(name); + if (existing) { + return existing; + } + const generated = new Uint8Array(bytes); + values.set(name, generated); + return generated; + })) satisfies ServerSecretStore.ServerSecretStoreShape["getOrCreateRandom"], + remove: ((name) => + Effect.sync(() => { + values.delete(name); + })) satisfies ServerSecretStore.ServerSecretStoreShape["remove"], + } satisfies ServerSecretStore.ServerSecretStoreShape; + return { + store, + setString: (name: string, value: string) => store.set(name, encodeSecret(value)), + }; +} + +describe.sequential("signRelayAgentActivityPublishProof", () => { + it("derives the thread id from the aggregate id for thread events without payload thread ids", () => { + const threadId = "thread-aggregate-1" as ThreadId; + const now = "2026-05-25T00:00:00.000Z"; + const event = { + type: "thread.activity-appended", + sequence: 1, + eventId: "evt-aggregate-1", + commandId: CommandId.make("cmd-1"), + aggregateKind: "thread", + aggregateId: threadId, + actor: { kind: "server" }, + payload: {}, + occurredAt: now, + } as unknown as OrchestrationEvent; + + expect(AgentAwarenessRelay.eventThreadId(event)).toBe(threadId); + }); + + it("does not publish streaming content or non-awareness activity events", () => { + const now = "2026-05-25T00:00:00.000Z"; + const base = { + sequence: 1, + eventId: "evt-1", + commandId: CommandId.make("cmd-1"), + aggregateKind: "thread", + aggregateId: "thread-1" as ThreadId, + occurredAt: now, + }; + + expect( + AgentAwarenessRelay.shouldPublishAgentAwarenessEvent({ + ...base, + type: "thread.message-sent", + payload: { + threadId: "thread-1" as ThreadId, + streaming: true, + }, + } as unknown as OrchestrationEvent), + ).toBe(false); + expect( + AgentAwarenessRelay.shouldPublishAgentAwarenessEvent({ + ...base, + type: "thread.activity-appended", + payload: { + threadId: "thread-1" as ThreadId, + activity: { + kind: "task.progress", + }, + }, + } as unknown as OrchestrationEvent), + ).toBe(false); + expect( + AgentAwarenessRelay.shouldPublishAgentAwarenessEvent({ + ...base, + type: "thread.activity-appended", + payload: { + threadId: "thread-1" as ThreadId, + activity: { + kind: "approval.requested", + }, + }, + } as unknown as OrchestrationEvent), + ).toBe(true); + expect( + AgentAwarenessRelay.shouldPublishAgentAwarenessEvent({ + ...base, + type: "thread.message-sent", + payload: { + threadId: "thread-1" as ThreadId, + streaming: false, + }, + } as unknown as OrchestrationEvent), + ).toBe(true); + }); + + it("deduplicates awareness state updates whose only change is their event timestamp", () => { + expect(AgentAwarenessRelay.agentAwarenessPublishIdentity(state)).toBe( + AgentAwarenessRelay.agentAwarenessPublishIdentity({ + ...state, + updatedAt: "2026-05-25T00:10:00.000Z", + }), + ); + expect(AgentAwarenessRelay.agentAwarenessPublishIdentity(state)).not.toBe( + AgentAwarenessRelay.agentAwarenessPublishIdentity({ + ...state, + phase: "completed", + headline: "Agent finished", + }), + ); + }); + + it("resolves a null publish state when a thread or project snapshot disappeared", () => { + const environmentId = "env-1" as EnvironmentId; + const threadId = "thread-1" as ThreadId; + const thread = { + id: threadId, + projectId: "project-1" as ProjectId, + title: "Deleted thread", + modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" }, + session: null, + latestTurn: null, + updatedAt: "2026-05-25T00:00:00.000Z", + hasPendingApprovals: false, + hasPendingUserInput: false, + } as OrchestrationThreadShell; + + expect( + AgentAwarenessRelay.resolveAgentAwarenessRelayPublishSnapshot({ + environmentId, + threadId, + thread: Option.none(), + project: Option.none(), + }), + ).toEqual({ + projectId: null, + state: null, + reason: "thread-not-found", + }); + + expect( + AgentAwarenessRelay.resolveAgentAwarenessRelayPublishSnapshot({ + environmentId, + threadId, + thread: Option.some(thread), + project: Option.none(), + }), + ).toEqual({ + projectId: "project-1", + state: null, + reason: "project-not-found", + }); + }); + + it("selects only active shell snapshot threads for startup catch-up", () => { + const now = "2026-05-25T00:00:00.000Z"; + const environmentId = "env-1" as EnvironmentId; + const projectId = "project-1" as ProjectId; + const activeThreadId = "thread-active" as ThreadId; + const idleThreadId = "thread-idle" as ThreadId; + + const baseThread = { + projectId, + title: "Run remote agent", + modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" }, + runtimeMode: "full-access", + interactionMode: "default", + branch: null, + worktreePath: null, + latestTurn: null, + createdAt: now, + updatedAt: now, + archivedAt: null, + session: null, + latestUserMessageAt: null, + hasPendingApprovals: false, + hasPendingUserInput: false, + hasActionableProposedPlan: false, + } satisfies Omit; + + expect( + AgentAwarenessRelay.resolveAgentAwarenessRelayActiveThreadIds({ + environmentId, + projects: [ + { + id: projectId, + title: "T3 Code", + }, + ], + threads: [ + { + ...baseThread, + id: activeThreadId, + latestTurn: { + turnId: "turn-1" as TurnId, + state: "running", + requestedAt: now, + startedAt: now, + completedAt: null, + assistantMessageId: null, + }, + }, + { + ...baseThread, + id: idleThreadId, + }, + { + ...baseThread, + id: "thread-missing-project" as ThreadId, + projectId: "missing-project" as ProjectId, + latestTurn: { + turnId: "turn-2" as TurnId, + state: "running", + requestedAt: now, + startedAt: now, + completedAt: null, + assistantMessageId: null, + }, + }, + ], + }), + ).toEqual([activeThreadId]); + }); + + it("signs the activity publish JWT and rejects tampering", async () => { + const keyPair = NodeCrypto.generateKeyPairSync("ed25519", { + privateKeyEncoding: { format: "pem", type: "pkcs8" }, + publicKeyEncoding: { format: "pem", type: "spki" }, + }); + const payload = { + iss: "t3-env:env", + aud: "https://relay.example.test", + sub: "env", + jti: "nonce-1", + iat: 100, + exp: 200, + environmentId: state.environmentId, + threadId: state.threadId, + state, + } satisfies RelayAgentActivityPublishProofPayload; + const proof = await Effect.runPromise( + AgentAwarenessRelay.signRelayAgentActivityPublishProof({ + privateKey: keyPair.privateKey, + payload, + }), + ); + + await expect( + Effect.runPromise( + verifyRelayJwt({ + publicKey: keyPair.publicKey, + token: proof, + typ: RELAY_ACTIVITY_PUBLISH_TYP, + issuer: "t3-env:env", + audience: "https://relay.example.test", + nowEpochSeconds: 150, + }), + ), + ).resolves.toMatchObject({ jti: "nonce-1", state }); + await expect( + Effect.runPromise( + verifyRelayJwt({ + publicKey: keyPair.publicKey, + token: (() => { + const [header, body, signature = ""] = proof.split("."); + const corruptedSignature = `${signature.startsWith("a") ? "b" : "a"}${signature.slice(1)}`; + return `${header}.${body}.${corruptedSignature}`; + })(), + typ: RELAY_ACTIVITY_PUBLISH_TYP, + issuer: "t3-env:env", + audience: "https://relay.example.test", + nowEpochSeconds: 150, + }), + ), + ).rejects.toBeDefined(); + }); + + it.effect("keeps the orchestration listener armed until relay config is installed", () => + Effect.scoped( + Effect.gen(function* () { + const events = yield* Queue.unbounded(); + const threadShellRequested = yield* Deferred.make(); + const secrets = makeMemorySecretStore(); + const now = "2026-05-25T00:00:00.000Z"; + const projectId = "project-1" as ProjectId; + const threadId = "thread-1" as ThreadId; + const environmentId = "env-1" as EnvironmentId; + + const project = { + id: projectId, + title: "T3 Code", + workspaceRoot: "/workspace", + repositoryIdentity: null, + defaultModelSelection: null, + scripts: [], + createdAt: now, + updatedAt: now, + } satisfies OrchestrationProjectShell; + + const thread = { + id: threadId, + projectId, + title: "Run remote agent", + modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" }, + runtimeMode: "full-access", + interactionMode: "default", + branch: null, + worktreePath: null, + latestTurn: { + turnId: "turn-1" as TurnId, + state: "running", + requestedAt: now, + startedAt: now, + completedAt: null, + assistantMessageId: null, + }, + createdAt: now, + updatedAt: now, + archivedAt: null, + session: { + threadId, + status: "running", + providerName: "Codex", + runtimeMode: "full-access", + activeTurnId: "turn-1" as TurnId, + lastError: null, + updatedAt: now, + }, + latestUserMessageAt: now, + hasPendingApprovals: false, + hasPendingUserInput: false, + hasActionableProposedPlan: false, + } satisfies OrchestrationThreadShell; + + const orchestrationEngine = { + readEvents: () => Stream.empty, + dispatch: () => Effect.succeed({ sequence: 1 }), + streamDomainEvents: Stream.fromQueue(events), + } satisfies OrchestrationEngineShape; + + const snapshotQuery = { + getShellSnapshot: () => + Effect.succeed({ + snapshotSequence: 1, + projects: [project], + threads: [thread], + updatedAt: now, + } satisfies OrchestrationShellSnapshot), + getThreadShellById: () => + Deferred.succeed(threadShellRequested, undefined).pipe( + Effect.ignore, + Effect.as(Option.some(thread)), + ), + getProjectShellById: () => Effect.succeed(Option.some(project)), + } as unknown as ProjectionSnapshotQueryShape; + + const descriptor = { + environmentId, + label: "Test Desktop", + platform: { + os: "darwin", + arch: "arm64", + }, + serverVersion: "0.0.0-test", + capabilities: { + repositoryIdentity: true, + }, + } satisfies ExecutionEnvironmentDescriptor; + + const layer = Layer.mergeAll( + Layer.succeed(ServerSecretStore.ServerSecretStore, secrets.store), + Layer.succeed(ServerEnvironment, { + getEnvironmentId: Effect.succeed(environmentId), + getDescriptor: Effect.succeed(descriptor), + }), + Layer.succeed(OrchestrationEngineService, orchestrationEngine), + Layer.succeed(ProjectionSnapshotQuery, snapshotQuery), + ); + + yield* Effect.gen(function* () { + const relay = yield* AgentAwarenessRelay.AgentAwarenessRelay; + yield* relay.start(); + yield* secrets.setString(RELAY_URL_SECRET, "http://127.0.0.1:1"); + yield* secrets.setString(RELAY_ENVIRONMENT_CREDENTIAL_SECRET, "relay-credential"); + yield* Queue.offer(events, { + type: "thread.activity-appended", + sequence: 1, + eventId: "evt-1", + commandId: CommandId.make("cmd-1"), + aggregateKind: "thread", + aggregateId: threadId, + actor: { kind: "server" }, + payload: { + threadId, + activity: { + kind: "approval.requested", + }, + }, + occurredAt: now, + } as unknown as OrchestrationEvent); + + yield* Deferred.await(threadShellRequested).pipe(Effect.timeout("2 seconds")); + }).pipe( + Effect.provide( + AgentAwarenessRelay.layer.pipe( + Layer.provide(layer), + Layer.provideMerge(NodeServices.layer), + ), + ), + ); + }), + ), + ); + + it.effect("publishes agent activity to the relay transport URL, not the relay issuer", () => + Effect.scoped( + Effect.gen(function* () { + const originalFetch = globalThis.fetch; + const context = yield* Effect.context(); + const runFork = Effect.runForkWith(context); + const events = yield* Queue.unbounded(); + const fetchSeen = yield* Deferred.make(); + const secrets = makeMemorySecretStore(); + const now = "2026-05-25T00:00:00.000Z"; + const projectId = "project-1" as ProjectId; + const threadId = "thread-1" as ThreadId; + const environmentId = "env-1" as EnvironmentId; + + const project = { + id: projectId, + title: "T3 Code", + workspaceRoot: "/workspace", + repositoryIdentity: null, + defaultModelSelection: null, + scripts: [], + createdAt: now, + updatedAt: now, + } satisfies OrchestrationProjectShell; + + const thread = { + id: threadId, + projectId, + title: "Run remote agent", + modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" }, + runtimeMode: "full-access", + interactionMode: "default", + branch: null, + worktreePath: null, + latestTurn: { + turnId: "turn-1" as TurnId, + state: "running", + requestedAt: now, + startedAt: now, + completedAt: null, + assistantMessageId: null, + }, + createdAt: now, + updatedAt: now, + archivedAt: null, + session: { + threadId, + status: "running", + providerName: "Codex", + runtimeMode: "full-access", + activeTurnId: "turn-1" as TurnId, + lastError: null, + updatedAt: now, + }, + latestUserMessageAt: now, + hasPendingApprovals: false, + hasPendingUserInput: false, + hasActionableProposedPlan: false, + } satisfies OrchestrationThreadShell; + + const descriptor = { + environmentId, + label: "Test Desktop", + platform: { + os: "darwin", + arch: "arm64", + }, + serverVersion: "0.0.0-test", + capabilities: { + repositoryIdentity: true, + }, + } satisfies ExecutionEnvironmentDescriptor; + + globalThis.fetch = ((input: Parameters[0]) => { + const url = new URL(input instanceof Request ? input.url : input.toString()); + runFork(Deferred.succeed(fetchSeen, url)); + return Promise.resolve(Response.json({ ok: true, deliveries: [] })); + }) as unknown as typeof fetch; + yield* Effect.addFinalizer(() => + Effect.sync(() => { + globalThis.fetch = originalFetch; + }), + ); + + const layer = Layer.mergeAll( + Layer.succeed(ServerSecretStore.ServerSecretStore, secrets.store), + Layer.succeed(ServerEnvironment, { + getEnvironmentId: Effect.succeed(environmentId), + getDescriptor: Effect.succeed(descriptor), + }), + Layer.succeed(OrchestrationEngineService, { + readEvents: () => Stream.empty, + dispatch: () => Effect.succeed({ sequence: 1 }), + streamDomainEvents: Stream.fromQueue(events), + } satisfies OrchestrationEngineShape), + Layer.succeed(ProjectionSnapshotQuery, { + getShellSnapshot: () => + Effect.succeed({ + snapshotSequence: 1, + projects: [project], + threads: [thread], + updatedAt: now, + } satisfies OrchestrationShellSnapshot), + getThreadShellById: () => Effect.succeed(Option.some(thread)), + getProjectShellById: () => Effect.succeed(Option.some(project)), + } as unknown as ProjectionSnapshotQueryShape), + ); + + yield* Effect.gen(function* () { + const relay = yield* AgentAwarenessRelay.AgentAwarenessRelay; + yield* secrets.setString(RELAY_URL_SECRET, "https://transport.example.test"); + yield* secrets.setString(RELAY_ISSUER_SECRET, "https://issuer.example.test"); + yield* secrets.setString(RELAY_ENVIRONMENT_CREDENTIAL_SECRET, "relay-credential"); + yield* relay.start(); + yield* Queue.offer(events, { + type: "thread.activity-appended", + sequence: 1, + eventId: "evt-1", + commandId: CommandId.make("cmd-1"), + aggregateKind: "thread", + aggregateId: threadId, + actor: { kind: "server" }, + payload: { + threadId, + activity: { + kind: "approval.requested", + }, + }, + occurredAt: now, + } as unknown as OrchestrationEvent); + + const url = yield* Deferred.await(fetchSeen).pipe(Effect.timeout("2 seconds")); + expect(url.origin).toBe("https://transport.example.test"); + }).pipe( + Effect.provide( + AgentAwarenessRelay.layer.pipe( + Layer.provide(layer), + Layer.provideMerge(NodeServices.layer), + ), + ), + ); + }), + ), + ); +}); diff --git a/apps/server/src/relay/AgentAwarenessRelay.ts b/apps/server/src/relay/AgentAwarenessRelay.ts new file mode 100644 index 0000000000..1c778c2799 --- /dev/null +++ b/apps/server/src/relay/AgentAwarenessRelay.ts @@ -0,0 +1,459 @@ +import { + RelayApi, + type RelayAgentActivityPublishProofPayload, + type RelayAgentActivityState, +} from "@t3tools/contracts/relay"; +import type { + EnvironmentId, + OrchestrationEvent, + OrchestrationProjectShell, + OrchestrationThreadShell, + ThreadId, +} from "@t3tools/contracts"; +import { projectThreadAwareness } from "@t3tools/shared/agentAwareness"; +import { makeDrainableWorker } from "@t3tools/shared/DrainableWorker"; +import { + RELAY_ACTIVITY_PUBLISH_TYP, + signRelayJwt, + normalizeRelayIssuer, +} from "@t3tools/shared/relayJwt"; +import * as Cause from "effect/Cause"; +import * as Context from "effect/Context"; +import * as Crypto from "effect/Crypto"; +import * as DateTime from "effect/DateTime"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import * as Option from "effect/Option"; +import * as Ref from "effect/Ref"; +import type * as Scope from "effect/Scope"; +import * as Stream from "effect/Stream"; +import { FetchHttpClient } from "effect/unstable/http"; +import * as HttpClient from "effect/unstable/http/HttpClient"; +import * as HttpClientRequest from "effect/unstable/http/HttpClientRequest"; +import * as HttpApiClient from "effect/unstable/httpapi/HttpApiClient"; + +import * as ServerSecretStore from "../auth/ServerSecretStore.ts"; +import { getOrCreateEnvironmentKeyPairFromSecretStore } from "../cloud/http.ts"; +import { + RELAY_ENVIRONMENT_CREDENTIAL_SECRET, + RELAY_ISSUER_SECRET, + RELAY_URL_SECRET, +} from "../cloud/config.ts"; +import { ServerEnvironment } from "../environment/Services/ServerEnvironment.ts"; +import { OrchestrationEngineService } from "../orchestration/Services/OrchestrationEngine.ts"; +import { ProjectionSnapshotQuery } from "../orchestration/Services/ProjectionSnapshotQuery.ts"; + +export interface AgentAwarenessRelayShape { + readonly publishThread: (threadId: ThreadId) => Effect.Effect; + readonly start: () => Effect.Effect; +} + +export class AgentAwarenessRelay extends Context.Service< + AgentAwarenessRelay, + AgentAwarenessRelayShape +>()("t3/relay/AgentAwarenessRelay") {} + +export function eventThreadId(event: OrchestrationEvent): ThreadId | null { + const payload = event.payload as { readonly threadId?: unknown }; + if (typeof payload.threadId === "string") { + return payload.threadId as ThreadId; + } + if (event.aggregateKind === "thread" && typeof event.aggregateId === "string") { + return event.aggregateId as ThreadId; + } + return null; +} + +export function shouldPublishAgentAwarenessEvent(event: OrchestrationEvent): boolean { + switch (event.type) { + case "thread.message-sent": + return !event.payload.streaming; + case "thread.proposed-plan-upserted": + case "thread.runtime-mode-set": + case "thread.interaction-mode-set": + return false; + case "thread.activity-appended": + return ( + event.payload.activity.kind === "approval.requested" || + event.payload.activity.kind === "approval.resolved" || + event.payload.activity.kind === "provider.approval.respond.failed" || + event.payload.activity.kind === "user-input.requested" || + event.payload.activity.kind === "user-input.resolved" || + event.payload.activity.kind === "runtime.error" + ); + default: + return true; + } +} + +export function agentAwarenessPublishIdentity(state: RelayAgentActivityState | null): string { + if (state === null) { + return "null"; + } + const { updatedAt: _updatedAt, ...meaningfulState } = state; + return JSON.stringify(meaningfulState); +} + +function relayEnvironmentClient(token: string) { + return HttpClient.mapRequest(HttpClientRequest.setHeader("authorization", `Bearer ${token}`)); +} + +function deliveryStats( + deliveries: ReadonlyArray<{ + readonly ok: boolean; + readonly queued?: boolean | undefined; + readonly kind: string; + readonly apnsStatus?: number | null; + readonly apnsReason?: string | null; + }>, +) { + let queued = 0; + let successful = 0; + let failed = 0; + const failedReasons: string[] = []; + const kinds = new Set(); + + for (const delivery of deliveries) { + kinds.add(delivery.kind); + if (delivery.queued) { + queued += 1; + continue; + } + if (delivery.ok) { + successful += 1; + continue; + } + failed += 1; + failedReasons.push(`${delivery.apnsStatus ?? "transport"}:${delivery.apnsReason ?? "unknown"}`); + } + + return { + total: deliveries.length, + queued, + successful, + failed, + kinds: [...kinds], + failedReasons, + }; +} + +export function signRelayAgentActivityPublishProof(input: { + readonly privateKey: string; + readonly payload: RelayAgentActivityPublishProofPayload; +}) { + return signRelayJwt({ + privateKey: input.privateKey, + typ: RELAY_ACTIVITY_PUBLISH_TYP, + payload: input.payload, + }); +} + +const makePublishProof = Effect.fn("makePublishProof")(function* (input: { + readonly privateKey: string; + readonly relayIssuer: string; + readonly environmentId: string; + readonly threadId: ThreadId; + readonly state: RelayAgentActivityState | null; + readonly jti: string; +}) { + const now = yield* DateTime.now; + const expiresAt = DateTime.add(now, { minutes: 5 }); + const payload = { + iss: `t3-env:${input.environmentId}`, + aud: normalizeRelayIssuer(input.relayIssuer), + sub: input.environmentId, + jti: input.jti, + iat: Math.floor(now.epochMilliseconds / 1_000), + exp: Math.floor(expiresAt.epochMilliseconds / 1_000), + environmentId: input.environmentId as RelayAgentActivityPublishProofPayload["environmentId"], + threadId: input.threadId, + state: input.state, + } satisfies RelayAgentActivityPublishProofPayload; + return yield* signRelayAgentActivityPublishProof({ privateKey: input.privateKey, payload }); +}); + +export function resolveAgentAwarenessRelayPublishSnapshot(input: { + readonly environmentId: EnvironmentId; + readonly threadId: ThreadId; + readonly thread: Option.Option; + readonly project: Option.Option; +}): { + readonly projectId: string | null; + readonly state: RelayAgentActivityState | null; + readonly reason: "snapshot" | "thread-not-found" | "project-not-found"; +} { + if (Option.isNone(input.thread)) { + return { + projectId: null, + state: null, + reason: "thread-not-found", + }; + } + if (Option.isNone(input.project)) { + return { + projectId: input.thread.value.projectId, + state: null, + reason: "project-not-found", + }; + } + return { + projectId: input.thread.value.projectId, + state: projectThreadAwareness({ + environmentId: input.environmentId, + project: input.project.value, + thread: input.thread.value, + }), + reason: "snapshot", + }; +} + +export function resolveAgentAwarenessRelayActiveThreadIds(input: { + readonly environmentId: EnvironmentId; + readonly projects: ReadonlyArray>; + readonly threads: ReadonlyArray; +}): ReadonlyArray { + const projectById = new Map(input.projects.map((project) => [project.id, project])); + return input.threads + .filter((thread) => { + const project = projectById.get(thread.projectId); + if (!project) { + return false; + } + return ( + projectThreadAwareness({ + environmentId: input.environmentId, + project, + thread, + }) !== null + ); + }) + .map((thread) => thread.id); +} + +const make = Effect.gen(function* () { + const secrets = yield* ServerSecretStore.ServerSecretStore; + const serverEnvironment = yield* ServerEnvironment; + const snapshotQuery = yield* ProjectionSnapshotQuery; + const orchestrationEngine = yield* OrchestrationEngineService; + const crypto = yield* Crypto.Crypto; + const cloudLinkKeyPair = yield* getOrCreateEnvironmentKeyPairFromSecretStore(secrets); + const activeSnapshotPublishedRef = yield* Ref.make(false); + const publishedStateByThreadRef = yield* Ref.make(new Map()); + + const readSecretString = (name: string) => + secrets.get(name).pipe(Effect.map((bytes) => (bytes ? new TextDecoder().decode(bytes) : null))); + + const readRelayConfig = Effect.gen(function* () { + const [url, issuer, environmentCredential] = yield* Effect.all([ + readSecretString(RELAY_URL_SECRET), + readSecretString(RELAY_ISSUER_SECRET), + readSecretString(RELAY_ENVIRONMENT_CREDENTIAL_SECRET), + ]); + return url && environmentCredential + ? { url, issuer: issuer ?? url, environmentCredential } + : null; + }); + + const makeRelayClient = (relayConfig: { + readonly url: string; + readonly environmentCredential: string; + }) => + HttpApiClient.make(RelayApi, { + baseUrl: relayConfig.url, + transformClient: relayEnvironmentClient(relayConfig.environmentCredential), + }).pipe(Effect.provide(FetchHttpClient.layer)); + + const publishThreadUnsafe = Effect.fn("publishThreadUnsafe")(function* (threadId: ThreadId) { + const relayConfig = yield* readRelayConfig.pipe(Effect.orElseSucceed(() => null)); + if (!relayConfig) { + yield* Effect.logDebug("agent awareness relay publish skipped; relay config missing", { + threadId, + }); + return; + } + const relayClient = yield* makeRelayClient(relayConfig); + const environmentId = yield* serverEnvironment.getEnvironmentId; + + const publishState = (input: { + readonly projectId: string | null; + readonly state: RelayAgentActivityState | null; + readonly reason: string; + }) => + Effect.gen(function* () { + const proof = yield* makePublishProof({ + privateKey: cloudLinkKeyPair.privateKey, + relayIssuer: relayConfig.issuer, + environmentId, + threadId, + state: input.state, + jti: yield* crypto.randomUUIDv4, + }); + + yield* Effect.logInfo("agent awareness relay publishing thread", { + environmentId, + threadId, + projectId: input.projectId, + statePhase: input.state?.phase ?? null, + hasState: input.state !== null, + reason: input.reason, + }); + + const response = yield* relayClient.server.publishAgentActivity({ + params: { + environmentId, + threadId, + }, + payload: { + state: input.state, + proof, + }, + }); + + yield* Effect.logInfo("agent awareness relay publish completed", { + environmentId, + threadId, + ok: response.ok, + deliveries: deliveryStats(response.deliveries), + }); + }); + + const thread = yield* snapshotQuery.getThreadShellById(threadId); + const project = Option.isSome(thread) + ? yield* snapshotQuery.getProjectShellById(thread.value.projectId) + : Option.none(); + const snapshot = resolveAgentAwarenessRelayPublishSnapshot({ + environmentId, + threadId, + thread, + project, + }); + const publishIdentity = agentAwarenessPublishIdentity(snapshot.state); + const publishedStateByThread = yield* Ref.get(publishedStateByThreadRef); + if (publishedStateByThread.get(threadId) === publishIdentity) { + yield* Effect.logDebug("agent awareness relay publish skipped; projected state unchanged", { + environmentId, + threadId, + reason: snapshot.reason, + }); + return; + } + + if (snapshot.reason === "thread-not-found") { + yield* Effect.logDebug("agent awareness relay publishing tombstone; thread not found", { + environmentId, + threadId, + }); + } else if (snapshot.reason === "project-not-found") { + yield* Effect.logDebug("agent awareness relay publishing tombstone; project not found", { + environmentId, + threadId, + projectId: snapshot.projectId, + }); + } + + yield* publishState({ + projectId: snapshot.projectId, + state: snapshot.state, + reason: snapshot.reason, + }); + yield* Ref.update(publishedStateByThreadRef, (publishedStates) => { + const nextPublishedStates = new Map(publishedStates); + nextPublishedStates.set(threadId, publishIdentity); + return nextPublishedStates; + }); + }); + + const publishThread: AgentAwarenessRelayShape["publishThread"] = (threadId) => + publishThreadUnsafe(threadId).pipe( + Effect.catchCause((cause) => { + return Effect.logWarning("agent awareness relay publish failed", { + threadId, + cause: Cause.pretty(cause), + }); + }), + Effect.withSpan("AgentAwarenessRelay.publishThread"), + ); + + const publishActiveThreadsUnsafe = Effect.gen(function* () { + const relayConfig = yield* readRelayConfig.pipe(Effect.orElseSucceed(() => null)); + if (!relayConfig) { + yield* Effect.logDebug("agent awareness relay active snapshot skipped; relay config missing"); + return false; + } + const environmentId = yield* serverEnvironment.getEnvironmentId; + const snapshot = yield* snapshotQuery.getShellSnapshot(); + const activeThreadIds = resolveAgentAwarenessRelayActiveThreadIds({ + environmentId, + projects: snapshot.projects, + threads: snapshot.threads, + }); + if (activeThreadIds.length === 0) { + yield* Effect.logDebug("agent awareness relay active snapshot has no publishable threads"); + return true; + } + yield* Effect.logInfo("agent awareness relay publishing active snapshot", { + count: activeThreadIds.length, + }); + yield* Effect.forEach(activeThreadIds, publishThread, { concurrency: 4, discard: true }); + return true; + }); + + const publishActiveThreadsOnceWhenConfigured = Effect.gen(function* () { + while (!(yield* Ref.get(activeSnapshotPublishedRef))) { + const published = yield* publishActiveThreadsUnsafe.pipe(Effect.orElseSucceed(() => false)); + if (published) { + yield* Ref.set(activeSnapshotPublishedRef, true); + return; + } + yield* Effect.sleep("5 seconds"); + } + }); + + const worker = yield* makeDrainableWorker(publishThread); + + const start: AgentAwarenessRelayShape["start"] = Effect.fn("AgentAwarenessRelay.start")( + function* () { + const relayConfig = yield* readRelayConfig.pipe(Effect.orElseSucceed(() => null)); + if (!relayConfig) { + yield* Effect.logInfo("agent awareness relay standby; relay config missing"); + } else { + yield* Effect.logInfo("agent awareness relay enabled", { + relayUrl: relayConfig.url, + }); + } + yield* Effect.forkScoped( + Effect.sleep("1 second").pipe(Effect.andThen(publishActiveThreadsOnceWhenConfigured)), + ); + yield* Effect.forkScoped( + Stream.runForEach(orchestrationEngine.streamDomainEvents, (event) => { + const threadId = eventThreadId(event); + if (threadId === null) { + return Effect.logDebug("agent awareness relay ignored event without thread id", { + eventType: event.type, + }); + } + if (!shouldPublishAgentAwarenessEvent(event)) { + return Effect.logDebug( + "agent awareness relay ignored event without awareness changes", + { + eventType: event.type, + threadId, + }, + ); + } + return Effect.logDebug("agent awareness relay queued thread publish", { + eventType: event.type, + threadId, + }).pipe(Effect.andThen(worker.enqueue(threadId))); + }), + ); + }, + ); + + return { + publishThread, + start, + } satisfies AgentAwarenessRelayShape; +}); + +export const layer = Layer.effect(AgentAwarenessRelay, make); diff --git a/apps/server/src/server.test.ts b/apps/server/src/server.test.ts index 495a1264b1..bd7ae885ff 100644 --- a/apps/server/src/server.test.ts +++ b/apps/server/src/server.test.ts @@ -1,6 +1,7 @@ import * as NodeHttpServer from "@effect/platform-node/NodeHttpServer"; import * as NodeSocket from "@effect/platform-node/NodeSocket"; import * as NodeServices from "@effect/platform-node/NodeServices"; +import * as NodeCrypto from "node:crypto"; import { AuthAccessTokenType, @@ -28,6 +29,12 @@ import { WsRpcGroup, EditorId, } from "@t3tools/contracts"; +import { + computeDpopAccessTokenHash, + computeDpopJwkThumbprint, + type DpopPublicJwk, +} from "@t3tools/shared/dpop"; +import { RELAY_HEALTH_REQUEST_TYP, RELAY_MINT_REQUEST_TYP } from "@t3tools/shared/relayJwt"; import { assert, it } from "@effect/vitest"; import { assertFailure, assertInclude, assertTrue } from "@effect/vitest/utils"; import * as Clock from "effect/Clock"; @@ -43,13 +50,13 @@ import * as Path from "effect/Path"; import * as Stream from "effect/Stream"; import { ChildProcessSpawner } from "effect/unstable/process"; import { - Cookies, FetchHttpClient, HttpBody, HttpClient, + HttpClientRequest, + HttpClientResponse, HttpRouter, HttpServer, - UrlParams, } from "effect/unstable/http"; import { OtlpSerialization, OtlpTracer } from "effect/unstable/observability"; import { RpcClient, RpcSerialization } from "effect/unstable/rpc"; @@ -120,6 +127,10 @@ import * as ReviewService from "./review/ReviewService.ts"; import * as SourceControlRepositoryService from "./sourceControl/SourceControlRepositoryService.ts"; import * as ServerSecretStore from "./auth/ServerSecretStore.ts"; import * as EnvironmentAuth from "./auth/EnvironmentAuth.ts"; +import { + CloudManagedEndpointRuntime, + type CloudManagedEndpointRuntimeShape, +} from "./cloud/ManagedEndpointRuntime.ts"; import * as ProcessDiagnostics from "./diagnostics/ProcessDiagnostics.ts"; import * as ProcessResourceMonitor from "./diagnostics/ProcessResourceMonitor.ts"; import * as TraceDiagnostics from "./diagnostics/TraceDiagnostics.ts"; @@ -347,6 +358,7 @@ const buildAppUnderTest = (options?: { serverRuntimeStartup?: Partial; serverEnvironment?: Partial; repositoryIdentityResolver?: Partial; + cloudManagedEndpointRuntime?: Partial; }; }) => Effect.gen(function* () { @@ -741,7 +753,17 @@ const buildAppUnderTest = (options?: { ...options?.layers?.repositoryIdentityResolver, }), ), + Layer.provide( + Layer.succeed( + CloudManagedEndpointRuntime, + CloudManagedEndpointRuntime.of({ + applyConfig: () => Effect.succeed({ status: "disabled" }), + ...options?.layers?.cloudManagedEndpointRuntime, + }), + ), + ), Layer.provideMerge(makeAuthTestLayer()), + Layer.provideMerge(ServerSecretStore.layer), Layer.provide(workspaceAndProjectServicesLayer), Layer.provideMerge(FetchHttpClient.layer), Layer.provide(layerConfig), @@ -799,6 +821,13 @@ const appendSessionCookieToWsUrl = (url: string, sessionCookieHeader: string) => return isAbsoluteUrl ? next.toString() : `${next.pathname}${next.search}${next.hash}`; }; +const getHttpServerUrl = (pathname = "") => + Effect.gen(function* () { + const server = yield* HttpServer.HttpServer; + const address = server.address as HttpServer.TcpAddress; + return `http://127.0.0.1:${address.port}${pathname}`; + }); + const bootstrapBrowserSession = ( credential = defaultDesktopBootstrapToken, options?: { @@ -806,19 +835,26 @@ const bootstrapBrowserSession = ( }, ) => Effect.gen(function* () { - const response = yield* HttpClient.post("/api/auth/browser-session", { - headers: options?.headers, - body: yield* HttpBody.json({ credential }), + const bootstrapUrl = yield* getHttpServerUrl("/api/auth/browser-session"); + const response = yield* fetchEffect(bootstrapUrl, { + method: "POST", + headers: { + "content-type": "application/json", + ...options?.headers, + }, + body: jsonRequestBody({ + credential, + }), }); - const body = (yield* response.json) as { + const body = yield* responseJsonEffect<{ readonly authenticated: boolean; readonly sessionMethod: string; readonly expiresAt: string; - }; + }>(response); return { response, body, - cookie: Cookies.toSetCookieHeaders(response.cookies)[0] ?? null, + cookie: response.headers["set-cookie"], }; }); @@ -835,48 +871,227 @@ const exchangeAccessToken = ( }, ) => Effect.gen(function* () { - const response = yield* HttpClient.post("/oauth/token", { - headers: options?.headers, - body: HttpBody.urlParams( - UrlParams.fromInput({ - grant_type: AuthTokenExchangeGrantType, - subject_token: credential, - subject_token_type: AuthEnvironmentBootstrapTokenType, - requested_token_type: AuthAccessTokenType, - scope: - options?.scope ?? - "orchestration:read orchestration:operate terminal:operate review:write relay:read access:read access:write relay:write", - ...(options?.clientMetadata?.label ? { client_label: options.clientMetadata.label } : {}), - ...(options?.clientMetadata?.deviceType - ? { client_device_type: options.clientMetadata.deviceType } - : {}), - ...(options?.clientMetadata?.os ? { client_os: options.clientMetadata.os } : {}), - }), - ), + const tokenUrl = yield* getHttpServerUrl("/oauth/token"); + const response = yield* fetchEffect(tokenUrl, { + method: "POST", + headers: { + "content-type": "application/x-www-form-urlencoded", + ...options?.headers, + }, + body: new URLSearchParams({ + grant_type: AuthTokenExchangeGrantType, + subject_token: credential, + subject_token_type: AuthEnvironmentBootstrapTokenType, + requested_token_type: AuthAccessTokenType, + scope: + options?.scope ?? + "orchestration:read orchestration:operate terminal:operate review:write relay:read access:read access:write relay:write", + ...(options?.clientMetadata?.label ? { client_label: options.clientMetadata.label } : {}), + ...(options?.clientMetadata?.deviceType + ? { client_device_type: options.clientMetadata.deviceType } + : {}), + ...(options?.clientMetadata?.os ? { client_os: options.clientMetadata.os } : {}), + }).toString(), }); - const body = (yield* response.json) as { + const body = yield* responseJsonEffect<{ readonly access_token?: string; readonly issued_token_type?: string; readonly token_type?: string; readonly expires_in?: number; readonly scope?: string; readonly _tag?: string; - readonly message?: string; - }; + readonly code?: string; + readonly reason?: string; + readonly traceId?: string; + }>(response); return { response, body, }; }); +const makeDpopProof = (input: { + readonly method: string; + readonly url: string; + readonly iat: number; + readonly accessToken?: string; + readonly jti?: string; + readonly privateKey?: NodeCrypto.KeyObject; + readonly publicJwk?: DpopPublicJwk; +}) => { + const keyPair = + input.privateKey && input.publicJwk + ? { privateKey: input.privateKey, publicJwk: input.publicJwk } + : (() => { + const { privateKey, publicKey } = NodeCrypto.generateKeyPairSync("ec", { + namedCurve: "P-256", + }); + return { privateKey, publicJwk: publicKey.export({ format: "jwk" }) as DpopPublicJwk }; + })(); + const header = Buffer.from( + JSON.stringify({ + typ: "dpop+jwt", + alg: "ES256", + jwk: keyPair.publicJwk, + }), + ).toString("base64url"); + const payload = Buffer.from( + JSON.stringify({ + htm: input.method, + htu: input.url, + jti: input.jti ?? "proof-1", + iat: input.iat, + ...(input.accessToken ? { ath: computeDpopAccessTokenHash(input.accessToken) } : {}), + }), + ).toString("base64url"); + const signature = NodeCrypto.sign("sha256", Buffer.from(`${header}.${payload}`), { + key: keyPair.privateKey, + dsaEncoding: "ieee-p1363", + }).toString("base64url"); + return { + proof: `${header}.${payload}.${signature}`, + thumbprint: computeDpopJwkThumbprint(keyPair.publicJwk), + privateKey: keyPair.privateKey, + publicJwk: keyPair.publicJwk, + }; +}; + +const makeCloudMintCredentialRequest = (input: { + readonly privateKey: string; + readonly environmentId: EnvironmentId; + readonly clientProofKeyThumbprint: string; + readonly issuer?: string; + readonly audience?: string; + readonly subject?: string; + readonly jti?: string; + readonly nonce: string; + readonly issuedAt: string; + readonly expiresAt: string; + readonly scope?: ReadonlyArray<"environment:connect">; +}) => { + const payload = { + iss: input.issuer ?? "https://relay.example.test", + aud: input.audience ?? `t3-env:${input.environmentId}`, + sub: input.subject ?? "user_123", + jti: input.jti ?? "cloud-mint-jti-1", + environmentId: input.environmentId, + clientProofKeyThumbprint: input.clientProofKeyThumbprint, + cnf: { + jkt: input.clientProofKeyThumbprint, + }, + nonce: input.nonce, + iat: Math.floor(DateTime.makeUnsafe(input.issuedAt).epochMilliseconds / 1_000), + exp: Math.floor(DateTime.makeUnsafe(input.expiresAt).epochMilliseconds / 1_000), + scope: input.scope ?? ["environment:connect"], + } as const; + const header = Buffer.from( + JSON.stringify({ alg: "EdDSA", typ: RELAY_MINT_REQUEST_TYP }), + ).toString("base64url"); + const encodedPayload = Buffer.from(JSON.stringify(payload)).toString("base64url"); + const signingInput = `${header}.${encodedPayload}`; + return { + proof: `${signingInput}.${NodeCrypto.sign(null, Buffer.from(signingInput), input.privateKey).toString("base64url")}`, + }; +}; + +const makeCloudEnvironmentHealthRequest = (input: { + readonly privateKey: string; + readonly environmentId: EnvironmentId; + readonly issuer?: string; + readonly audience?: string; + readonly subject?: string; + readonly jti?: string; + readonly nonce: string; + readonly issuedAt: string; + readonly expiresAt: string; + readonly scope?: ReadonlyArray<"environment:status">; +}) => { + const payload = { + iss: input.issuer ?? "https://relay.example.test", + aud: input.audience ?? `t3-env:${input.environmentId}`, + sub: input.subject ?? "user_123", + jti: input.jti ?? "cloud-health-jti-1", + environmentId: input.environmentId, + nonce: input.nonce, + iat: Math.floor(DateTime.makeUnsafe(input.issuedAt).epochMilliseconds / 1_000), + exp: Math.floor(DateTime.makeUnsafe(input.expiresAt).epochMilliseconds / 1_000), + scope: input.scope ?? ["environment:status"], + } as const; + const header = Buffer.from( + JSON.stringify({ alg: "EdDSA", typ: RELAY_HEALTH_REQUEST_TYP }), + ).toString("base64url"); + const encodedPayload = Buffer.from(JSON.stringify(payload)).toString("base64url"); + const signingInput = `${header}.${encodedPayload}`; + return { + proof: `${signingInput}.${NodeCrypto.sign(null, Buffer.from(signingInput), input.privateKey).toString("base64url")}`, + }; +}; + +const decodeCompactJwtPayload = (token: string): A => { + const encodedPayload = token.split(".")[1]; + if (!encodedPayload) { + throw new Error("JWT does not contain a payload."); + } + return JSON.parse(Buffer.from(encodedPayload, "base64url").toString("utf8")) as A; +}; + class AuthenticationGetterError extends Data.TaggedError("AuthenticationGetterError")<{ readonly message: string; }> {} +class TestHttpRequestError extends Data.TaggedError("TestHttpRequestError")<{ + readonly cause: unknown; +}> {} + +const testRequestUrl = (input: Parameters[0]): string => { + const value = input.toString(); + if (!/^https?:\/\//i.test(value)) { + return value; + } + const url = new URL(value); + return `${url.pathname}${url.search}`; +}; + +const fetchEffect = (input: Parameters[0], init?: RequestInit) => { + const request = HttpClientRequest.make((init?.method ?? "GET") as "GET" | "POST")( + testRequestUrl(input), + { + headers: init?.headers as Record | undefined, + }, + ).pipe( + typeof init?.body === "string" + ? HttpClientRequest.bodyText( + init.body, + (init.headers as Record | undefined)?.["content-type"] ?? + "application/json", + ) + : (request) => request, + ); + const effect = HttpClient.execute(request); + return ( + init?.redirect === "manual" + ? effect.pipe(Effect.provideService(FetchHttpClient.RequestInit, { redirect: "manual" })) + : effect + ).pipe(Effect.mapError((cause) => new TestHttpRequestError({ cause }))); +}; + +const jsonRequestBody = (value: unknown): string => { + return JSON.stringify(value); +}; + +const responseJsonEffect = (response: HttpClientResponse.HttpClientResponse) => + response.json.pipe( + Effect.map((json) => json as A), + Effect.mapError((cause) => new TestHttpRequestError({ cause })), + ); + +const responseOk = (response: HttpClientResponse.HttpClientResponse) => + response.status >= 200 && response.status < 300; + const getAuthenticatedSessionCookieHeader = (credential = defaultDesktopBootstrapToken) => Effect.gen(function* () { const { response, cookie } = yield* bootstrapBrowserSession(credential); - if (response.status !== 200) { + if (!responseOk(response)) { return yield* new AuthenticationGetterError({ message: `Expected bootstrap session response to succeed, got ${response.status}`, }); @@ -894,7 +1109,7 @@ const getAuthenticatedSessionCookieHeader = (credential = defaultDesktopBootstra const getAuthenticatedBearerSessionToken = (credential = defaultDesktopBootstrapToken) => Effect.gen(function* () { const { response, body } = yield* exchangeAccessToken(credential); - if (response.status !== 200) { + if (!responseOk(response)) { return yield* new AuthenticationGetterError({ message: `Expected bearer bootstrap response to succeed, got ${response.status}`, }); @@ -918,7 +1133,7 @@ const extractSessionTokenFromSetCookie = (cookieHeader: string): string => { return token; }; -const splitHeaderTokens = (value: string | null) => +const splitHeaderTokens = (value: string | null | undefined) => (value ?? "") .split(",") .map((token) => token.trim()) @@ -940,10 +1155,11 @@ const assertBrowserApiCorsPreflightHeaders = ( "OPTIONS", "POST", ]); - assert.deepEqual(splitHeaderTokens(headers["access-control-allow-headers"] ?? null), [ + assert.deepEqual(splitHeaderTokens(headers["access-control-allow-headers"]), [ "authorization", "b3", "content-type", + "dpop", "traceparent", ]); }; @@ -989,9 +1205,8 @@ it.layer(NodeServices.layer)("server router seam", (it) => { config: { devUrl: new URL("http://127.0.0.1:5173") }, }); - const response = yield* HttpClient.get("/foo/bar?token=test-token").pipe( - Effect.provideService(FetchHttpClient.RequestInit, { redirect: "manual" }), - ); + const url = yield* getHttpServerUrl("/foo/bar?token=test-token"); + const response = yield* fetchEffect(url, { redirect: "manual" }); assert.equal(response.status, 302); assert.equal(response.headers.location, "http://127.0.0.1:5173/foo/bar?token=test-token"); @@ -1057,8 +1272,9 @@ it.layer(NodeServices.layer)("server router seam", (it) => { Effect.gen(function* () { yield* buildAppUnderTest(); - const response = yield* HttpClient.get("/.well-known/t3/environment"); - const body = (yield* response.json) as typeof testEnvironmentDescriptor; + const url = yield* getHttpServerUrl("/.well-known/t3/environment"); + const response = yield* fetchEffect(url); + const body = yield* responseJsonEffect(response); assert.equal(response.status, 200); assert.deepEqual(body, testEnvironmentDescriptor); @@ -1069,12 +1285,13 @@ it.layer(NodeServices.layer)("server router seam", (it) => { Effect.gen(function* () { yield* buildAppUnderTest(); - const response = yield* HttpClient.get("/.well-known/t3/environment", { + const url = yield* getHttpServerUrl("/.well-known/t3/environment"); + const response = yield* fetchEffect(url, { headers: { origin: crossOriginClientOrigin, }, }); - const body = (yield* response.json) as typeof testEnvironmentDescriptor; + const body = yield* responseJsonEffect(response); assert.equal(response.status, 200); assertBrowserApiCorsResponseHeaders(response.headers); @@ -1086,8 +1303,9 @@ it.layer(NodeServices.layer)("server router seam", (it) => { Effect.gen(function* () { yield* buildAppUnderTest(); - const response = yield* HttpClient.get("/api/auth/session"); - const body = (yield* response.json) as { + const url = yield* getHttpServerUrl("/api/auth/session"); + const response = yield* fetchEffect(url); + const body = yield* responseJsonEffect<{ readonly authenticated: boolean; readonly auth: { readonly policy: string; @@ -1095,13 +1313,17 @@ it.layer(NodeServices.layer)("server router seam", (it) => { readonly sessionMethods: ReadonlyArray; readonly sessionCookieName: string; }; - }; + }>(response); assert.equal(response.status, 200); assert.equal(body.authenticated, false); assert.equal(body.auth.policy, "desktop-managed-local"); assert.deepEqual(body.auth.bootstrapMethods, ["desktop-bootstrap"]); - assert.deepEqual(body.auth.sessionMethods, ["browser-session-cookie", "bearer-access-token"]); + assert.deepEqual(body.auth.sessionMethods, [ + "browser-session-cookie", + "bearer-access-token", + "dpop-access-token", + ]); assert.isTrue(body.auth.sessionCookieName.startsWith("t3_session_")); }).pipe(Effect.provide(NodeHttpServer.layerTest)), ); @@ -1122,15 +1344,16 @@ it.layer(NodeServices.layer)("server router seam", (it) => { assert.isUndefined((bootstrapBody as { readonly sessionToken?: string }).sessionToken); assert.isDefined(setCookie); - const sessionResponse = yield* HttpClient.get("/api/auth/session", { + const sessionUrl = yield* getHttpServerUrl("/api/auth/session"); + const sessionResponse = yield* fetchEffect(sessionUrl, { headers: { cookie: setCookie?.split(";")[0] ?? "", }, }); - const sessionBody = (yield* sessionResponse.json) as { + const sessionBody = yield* responseJsonEffect<{ readonly authenticated: boolean; readonly sessionMethod?: string; - }; + }>(sessionResponse); assert.equal(sessionResponse.status, 200); assert.equal(sessionBody.authenticated, true); @@ -1142,9 +1365,9 @@ it.layer(NodeServices.layer)("server router seam", (it) => { Effect.gen(function* () { yield* buildAppUnderTest(); - const { response: bootstrapResponse, body: tokenBody } = yield* exchangeAccessToken(); + const { response: tokenResponse, body: tokenBody } = yield* exchangeAccessToken(); - assert.equal(bootstrapResponse.status, 200); + assert.equal(tokenResponse.status, 200); assert.equal(tokenBody.issued_token_type, AuthAccessTokenType); assert.equal(tokenBody.token_type, "Bearer"); assert.equal( @@ -1152,18 +1375,18 @@ it.layer(NodeServices.layer)("server router seam", (it) => { "orchestration:read orchestration:operate terminal:operate review:write relay:read access:read access:write relay:write", ); assert.equal(typeof tokenBody.access_token, "string"); - assert.isTrue((tokenBody.access_token?.length ?? 0) > 0); - const sessionResponse = yield* HttpClient.get("/api/auth/session", { + const sessionUrl = yield* getHttpServerUrl("/api/auth/session"); + const sessionResponse = yield* fetchEffect(sessionUrl, { headers: { authorization: `Bearer ${tokenBody.access_token ?? ""}`, }, }); - const sessionBody = (yield* sessionResponse.json) as { + const sessionBody = yield* responseJsonEffect<{ readonly authenticated: boolean; readonly sessionMethod?: string; readonly scopes?: ReadonlyArray; - }; + }>(sessionResponse); assert.equal(sessionResponse.status, 200); assert.equal(sessionBody.authenticated, true); @@ -1181,20 +1404,1581 @@ it.layer(NodeServices.layer)("server router seam", (it) => { }).pipe(Effect.provide(NodeHttpServer.layerTest)), ); + it.effect("persists token exchange client display metadata for authorized-client listings", () => + Effect.gen(function* () { + yield* buildAppUnderTest({ + config: { + host: "0.0.0.0", + }, + }); + + const ownerCookie = yield* getAuthenticatedSessionCookieHeader(); + const pairingResponse = yield* HttpClient.post("/api/auth/pairing-token", { + headers: { + cookie: ownerCookie, + }, + body: yield* HttpBody.json({}), + }); + const pairingBody = (yield* pairingResponse.json) as { + readonly credential: string; + }; + + const { response } = yield* exchangeAccessToken(pairingBody.credential, { + headers: { + "user-agent": "undici", + }, + scope: "orchestration:read orchestration:operate terminal:operate review:write", + clientMetadata: { + label: "T3 Code Mobile", + deviceType: "mobile", + os: "iOS", + }, + }); + + const clientsResponse = yield* HttpClient.get("/api/auth/clients", { + headers: { + cookie: ownerCookie, + }, + }); + const clients = (yield* clientsResponse.json) as ReadonlyArray<{ + readonly current: boolean; + readonly client: { + readonly label?: string; + readonly deviceType: string; + readonly ipAddress?: string; + readonly os?: string; + readonly userAgent?: string; + }; + }>; + const mobileClient = clients.find((client) => !client.current); + + assert.equal(pairingResponse.status, 200); + assert.equal(response.status, 200); + assert.equal(clientsResponse.status, 200); + assert.deepInclude(mobileClient?.client, { + label: "T3 Code Mobile", + deviceType: "mobile", + os: "iOS", + ipAddress: "127.0.0.1", + userAgent: "undici", + }); + }).pipe(Effect.provide(NodeHttpServer.layerTest)), + ); + + it.effect( + "exchanges a bootstrap credential for a DPoP-bound access token without bearer downgrade", + () => + Effect.gen(function* () { + yield* buildAppUnderTest(); + + const ownerCookie = yield* getAuthenticatedSessionCookieHeader(); + const credentialResponse = yield* HttpClient.post("/api/auth/pairing-token", { + headers: { cookie: ownerCookie }, + body: yield* HttpBody.json({}), + }); + const credential = (yield* credentialResponse.json) as { readonly credential: string }; + const tokenUrl = yield* getHttpServerUrl("/oauth/token"); + const now = yield* DateTime.now; + const tokenProof = makeDpopProof({ + method: "POST", + url: tokenUrl, + iat: Math.floor(now.epochMilliseconds / 1_000), + jti: "token-exchange-proof", + }); + const tokenResponse = yield* fetchEffect(tokenUrl, { + method: "POST", + headers: { + "content-type": "application/x-www-form-urlencoded", + dpop: tokenProof.proof, + }, + body: new URLSearchParams({ + grant_type: "urn:ietf:params:oauth:grant-type:token-exchange", + subject_token: credential.credential, + subject_token_type: "urn:t3:params:oauth:token-type:environment-bootstrap", + requested_token_type: "urn:ietf:params:oauth:token-type:access_token", + scope: "orchestration:read orchestration:operate terminal:operate review:write", + }).toString(), + }); + const token = yield* responseJsonEffect<{ + readonly access_token: string; + readonly token_type: string; + }>(tokenResponse); + + assert.equal(tokenResponse.status, 200); + assert.equal(tokenResponse.headers["cache-control"], "no-store"); + assert.equal(token.token_type, "DPoP"); + + const sessionUrl = yield* getHttpServerUrl("/api/auth/session"); + const bearerResponse = yield* fetchEffect(sessionUrl, { + headers: { authorization: `Bearer ${token.access_token}` }, + }); + const bearerState = yield* responseJsonEffect<{ readonly authenticated: boolean }>( + bearerResponse, + ); + assert.equal(bearerState.authenticated, false); + + const sessionProof = makeDpopProof({ + method: "GET", + url: sessionUrl, + iat: Math.floor(now.epochMilliseconds / 1_000), + jti: "session-proof", + accessToken: token.access_token, + privateKey: tokenProof.privateKey, + publicJwk: tokenProof.publicJwk, + }); + const dpopResponse = yield* fetchEffect(sessionUrl, { + headers: { + authorization: `DPoP ${token.access_token}`, + dpop: sessionProof.proof, + }, + }); + const dpopState = yield* responseJsonEffect<{ + readonly authenticated: boolean; + readonly sessionMethod?: string; + }>(dpopResponse); + assert.equal(dpopState.authenticated, true); + assert.equal(dpopState.sessionMethod, "dpop-access-token"); + }).pipe(Effect.provide(NodeHttpServer.layerTest)), + ); + + it.effect("rejects replayed DPoP proofs across token exchanges", () => + Effect.gen(function* () { + yield* buildAppUnderTest(); + + const ownerCookie = yield* getAuthenticatedSessionCookieHeader(); + const firstCredentialResponse = yield* HttpClient.post("/api/auth/pairing-token", { + headers: { + cookie: ownerCookie, + }, + body: yield* HttpBody.json({}), + }); + const firstCredential = (yield* firstCredentialResponse.json) as { + readonly credential: string; + }; + const secondCredentialResponse = yield* HttpClient.post("/api/auth/pairing-token", { + headers: { + cookie: ownerCookie, + }, + body: yield* HttpBody.json({}), + }); + const secondCredential = (yield* secondCredentialResponse.json) as { + readonly credential: string; + }; + const tokenUrl = yield* getHttpServerUrl("/oauth/token"); + const now = yield* DateTime.now; + const dpop = makeDpopProof({ + method: "POST", + url: tokenUrl, + iat: Math.floor(now.epochMilliseconds / 1_000), + }); + + const firstBootstrap = yield* exchangeAccessToken(firstCredential.credential, { + headers: { + dpop: dpop.proof, + }, + scope: "orchestration:read orchestration:operate terminal:operate review:write", + }); + const replayBootstrap = yield* exchangeAccessToken(secondCredential.credential, { + headers: { + dpop: dpop.proof, + }, + scope: "orchestration:read orchestration:operate terminal:operate review:write", + }); + + assert.equal(firstBootstrap.response.status, 200); + assert.equal(replayBootstrap.response.status, 401); + assert.equal(replayBootstrap.body._tag, "EnvironmentAuthInvalidError"); + assert.equal(replayBootstrap.body.code, "auth_invalid"); + assert.equal(replayBootstrap.body.reason, "invalid_credential"); + assert.equal(typeof replayBootstrap.body.traceId, "string"); + }).pipe(Effect.provide(NodeHttpServer.layerTest)), + ); + + it.effect("ignores forwarded host headers when validating token exchange DPoP URLs", () => + Effect.gen(function* () { + yield* buildAppUnderTest(); + + const ownerCookie = yield* getAuthenticatedSessionCookieHeader(); + const credentialResponse = yield* HttpClient.post("/api/auth/pairing-token", { + headers: { + cookie: ownerCookie, + }, + body: yield* HttpBody.json({}), + }); + const credential = (yield* credentialResponse.json) as { + readonly credential: string; + }; + const tokenUrl = yield* getHttpServerUrl("/oauth/token"); + const now = yield* DateTime.now; + const dpop = makeDpopProof({ + method: "POST", + url: tokenUrl, + iat: Math.floor(now.epochMilliseconds / 1_000), + }); + + const bootstrap = yield* exchangeAccessToken(credential.credential, { + headers: { + dpop: dpop.proof, + "x-forwarded-host": "environment.example.test", + }, + scope: "orchestration:read orchestration:operate terminal:operate review:write", + }); + + assert.equal(bootstrap.response.status, 200); + assert.equal(bootstrap.body.token_type, "DPoP"); + }).pipe(Effect.provide(NodeHttpServer.layerTest)), + ); + + it.effect("rejects token exchange DPoP proofs bound to spoofed forwarded hosts", () => + Effect.gen(function* () { + yield* buildAppUnderTest(); + + const ownerCookie = yield* getAuthenticatedSessionCookieHeader(); + const credentialResponse = yield* HttpClient.post("/api/auth/pairing-token", { + headers: { + cookie: ownerCookie, + }, + body: yield* HttpBody.json({}), + }); + const credential = (yield* credentialResponse.json) as { + readonly credential: string; + }; + const tokenUrl = yield* getHttpServerUrl("/oauth/token"); + const spoofedUrl = new URL(tokenUrl); + spoofedUrl.hostname = "environment.example.test"; + const now = yield* DateTime.now; + const dpop = makeDpopProof({ + method: "POST", + url: spoofedUrl.href, + iat: Math.floor(now.epochMilliseconds / 1_000), + }); + + const bootstrap = yield* exchangeAccessToken(credential.credential, { + headers: { + dpop: dpop.proof, + "x-forwarded-host": spoofedUrl.host, + }, + scope: "orchestration:read orchestration:operate terminal:operate review:write", + }); + + assert.equal(bootstrap.response.status, 401); + assert.equal(bootstrap.body._tag, "EnvironmentAuthInvalidError"); + assert.equal(bootstrap.body.code, "auth_invalid"); + assert.equal(bootstrap.body.reason, "invalid_credential"); + assert.equal(typeof bootstrap.body.traceId, "string"); + }).pipe(Effect.provide(NodeHttpServer.layerTest)), + ); + + it.effect("rejects cloud link proofs for non-loopback managed endpoint origins", () => + Effect.gen(function* () { + yield* buildAppUnderTest(); + + const ownerCookie = yield* getAuthenticatedSessionCookieHeader(); + const linkProofUrl = yield* getHttpServerUrl("/api/cloud/link-proof"); + const linkProofResponse = yield* fetchEffect(linkProofUrl, { + method: "POST", + headers: { + cookie: ownerCookie, + "content-type": "application/json", + }, + body: jsonRequestBody({ + challenge: "relay-link-challenge", + relayIssuer: "https://relay.example.test", + endpoint: { + httpBaseUrl: "https://environment.example.test/", + wsBaseUrl: "wss://environment.example.test/ws", + providerKind: "manual", + }, + origin: { + localHttpHost: "192.168.1.42", + localHttpPort: 3773, + }, + }), + }); + const body = yield* responseJsonEffect<{ + readonly _tag?: string; + readonly message?: string; + }>(linkProofResponse); + + assert.equal(linkProofResponse.status, 400); + assert.equal(body._tag, "EnvironmentHttpBadRequestError"); + assert.equal(body.message, "Invalid managed endpoint origin."); + }).pipe(Effect.provide(NodeHttpServer.layerTest)), + ); + + it.effect("rejects managed cloud link proofs for manual endpoint providers", () => + Effect.gen(function* () { + yield* buildAppUnderTest(); + + const ownerCookie = yield* getAuthenticatedSessionCookieHeader(); + const linkProofUrl = yield* getHttpServerUrl("/api/cloud/link-proof"); + const serverPort = Number(new URL(linkProofUrl).port); + const linkProofResponse = yield* fetchEffect(linkProofUrl, { + method: "POST", + headers: { + cookie: ownerCookie, + "content-type": "application/json", + }, + body: jsonRequestBody({ + challenge: "relay-link-challenge", + relayIssuer: "https://relay.example.test", + endpoint: { + httpBaseUrl: linkProofUrl.replace("/api/cloud/link-proof", ""), + wsBaseUrl: linkProofUrl + .replace("http://", "ws://") + .replace("/api/cloud/link-proof", "/ws"), + providerKind: "manual", + }, + origin: { + localHttpHost: "127.0.0.1", + localHttpPort: serverPort, + }, + }), + }); + const body = yield* responseJsonEffect<{ + readonly _tag?: string; + readonly message?: string; + }>(linkProofResponse); + + assert.equal(linkProofResponse.status, 400); + assert.equal(body._tag, "EnvironmentHttpBadRequestError"); + assert.equal(body.message, "Invalid managed endpoint origin."); + }).pipe(Effect.provide(NodeHttpServer.layerTest)), + ); + + it.effect("rejects cloud link proofs requested through a public managed endpoint", () => + Effect.gen(function* () { + yield* buildAppUnderTest(); + + const linkProofUrl = yield* getHttpServerUrl("/api/cloud/link-proof"); + const serverPort = Number(new URL(linkProofUrl).port); + const linkProofResponse = yield* HttpClient.post("/api/cloud/link-proof", { + headers: { + cookie: yield* getAuthenticatedSessionCookieHeader(), + "content-type": "application/json", + host: "environment.example.test", + "x-forwarded-host": "environment.example.test", + "x-forwarded-proto": "https", + }, + body: HttpBody.text( + jsonRequestBody({ + challenge: "relay-link-challenge", + relayIssuer: "https://relay.example.test", + endpoint: { + httpBaseUrl: "https://environment.example.test/", + wsBaseUrl: "wss://environment.example.test/ws", + providerKind: "manual", + }, + origin: { + localHttpHost: "127.0.0.1", + localHttpPort: serverPort, + }, + }), + "application/json", + ), + }); + const body = (yield* linkProofResponse.json) as { + readonly _tag?: string; + readonly message?: string; + }; + + assert.equal(linkProofResponse.status, 400); + assert.equal(body._tag, "EnvironmentHttpBadRequestError"); + assert.equal(body.message, "Invalid managed endpoint origin."); + }).pipe(Effect.provide(NodeHttpServer.layerTest)), + ); + + it.effect( + "rejects cloud link proofs when a public request spoofs loopback forwarded headers", + () => + Effect.gen(function* () { + yield* buildAppUnderTest(); + + const linkProofUrl = yield* getHttpServerUrl("/api/cloud/link-proof"); + const serverPort = Number(new URL(linkProofUrl).port); + const linkProofResponse = yield* HttpClient.post("/api/cloud/link-proof", { + headers: { + cookie: yield* getAuthenticatedSessionCookieHeader(), + "content-type": "application/json", + host: "environment.example.test", + "x-forwarded-host": `127.0.0.1:${serverPort}`, + "x-forwarded-proto": "http", + }, + body: HttpBody.text( + jsonRequestBody({ + challenge: "relay-link-challenge", + relayIssuer: "https://relay.example.test", + endpoint: { + httpBaseUrl: "https://environment.example.test/", + wsBaseUrl: "wss://environment.example.test/ws", + providerKind: "manual", + }, + origin: { + localHttpHost: "127.0.0.1", + localHttpPort: serverPort, + }, + }), + "application/json", + ), + }); + const body = (yield* linkProofResponse.json) as { + readonly _tag?: string; + readonly message?: string; + }; + + assert.equal(linkProofResponse.status, 400); + assert.equal(body._tag, "EnvironmentHttpBadRequestError"); + assert.equal(body.message, "Invalid managed endpoint origin."); + }).pipe(Effect.provide(NodeHttpServer.layerTest)), + ); + + it.effect("rejects cloud link proofs with malformed forwarded request hosts", () => + Effect.gen(function* () { + yield* buildAppUnderTest(); + + const linkProofUrl = yield* getHttpServerUrl("/api/cloud/link-proof"); + const serverPort = Number(new URL(linkProofUrl).port); + const linkProofResponse = yield* HttpClient.post("/api/cloud/link-proof", { + headers: { + cookie: yield* getAuthenticatedSessionCookieHeader(), + "content-type": "application/json", + host: "bad host", + "x-forwarded-host": "bad host", + "x-forwarded-proto": "https", + }, + body: HttpBody.text( + jsonRequestBody({ + challenge: "relay-link-challenge", + relayIssuer: "https://relay.example.test", + endpoint: { + httpBaseUrl: "https://environment.example.test/", + wsBaseUrl: "wss://environment.example.test/ws", + providerKind: "manual", + }, + origin: { + localHttpHost: "127.0.0.1", + localHttpPort: serverPort, + }, + }), + "application/json", + ), + }); + const body = (yield* linkProofResponse.json) as { + readonly _tag?: string; + readonly message?: string; + }; + + assert.equal(linkProofResponse.status, 400); + assert.equal(body._tag, "EnvironmentHttpBadRequestError"); + assert.equal(body.message, "Invalid managed endpoint origin."); + }).pipe(Effect.provide(NodeHttpServer.layerTest)), + ); + + it.effect("rejects local cloud link proofs for a different loopback port", () => + Effect.gen(function* () { + yield* buildAppUnderTest(); + + const ownerCookie = yield* getAuthenticatedSessionCookieHeader(); + const linkProofUrl = yield* getHttpServerUrl("/api/cloud/link-proof"); + const serverPort = Number(new URL(linkProofUrl).port); + const linkProofResponse = yield* fetchEffect(linkProofUrl, { + method: "POST", + headers: { + cookie: ownerCookie, + "content-type": "application/json", + }, + body: jsonRequestBody({ + challenge: "relay-link-challenge", + relayIssuer: "https://relay.example.test", + endpoint: { + httpBaseUrl: "https://environment.example.test/", + wsBaseUrl: "wss://environment.example.test/ws", + providerKind: "manual", + }, + origin: { + localHttpHost: "127.0.0.1", + localHttpPort: serverPort === 65_535 ? serverPort - 1 : serverPort + 1, + }, + }), + }); + const body = yield* responseJsonEffect<{ + readonly _tag?: string; + readonly message?: string; + }>(linkProofResponse); + + assert.equal(linkProofResponse.status, 400); + assert.equal(body._tag, "EnvironmentHttpBadRequestError"); + assert.equal(body.message, "Invalid managed endpoint origin."); + }).pipe(Effect.provide(NodeHttpServer.layerTest)), + ); + + it.effect("rejects managed relay configuration reads without relay management scope", () => + Effect.gen(function* () { + yield* buildAppUnderTest(); + + const ownerCookie = yield* getAuthenticatedSessionCookieHeader(); + const credentialResponse = yield* HttpClient.post("/api/auth/pairing-token", { + headers: { cookie: ownerCookie }, + body: yield* HttpBody.json({}), + }); + const credential = (yield* credentialResponse.json) as { readonly credential: string }; + const pairedCookie = yield* getAuthenticatedSessionCookieHeader(credential.credential); + const linkStateUrl = yield* getHttpServerUrl("/api/cloud/link-state"); + const response = yield* fetchEffect(linkStateUrl, { + headers: { cookie: pairedCookie }, + }); + const body = yield* responseJsonEffect<{ + readonly _tag?: string; + readonly code?: string; + readonly requiredScope?: string; + readonly traceId?: string; + }>(response); + + assert.equal(response.status, 403); + assert.equal(body._tag, "EnvironmentScopeRequiredError"); + assert.equal(body.code, "insufficient_scope"); + assert.equal(body.requiredScope, "relay:manage"); + assert.equal(typeof body.traceId, "string"); + }).pipe(Effect.provide(NodeHttpServer.layerTest)), + ); + + it.effect("rejects relay config with an invalid cloud mint public key", () => + Effect.gen(function* () { + yield* buildAppUnderTest(); + + const ownerCookie = yield* getAuthenticatedSessionCookieHeader(); + const relayConfigUrl = yield* getHttpServerUrl("/api/cloud/relay-config"); + const relayConfigResponse = yield* fetchEffect(relayConfigUrl, { + method: "POST", + headers: { + cookie: ownerCookie, + "content-type": "application/json", + }, + body: jsonRequestBody({ + relayUrl: "https://relay.example.test", + cloudUserId: "user_123", + environmentCredential: "t3env_test_credential", + cloudMintPublicKey: "not-a-public-key", + endpointRuntime: null, + }), + }); + const body = yield* responseJsonEffect<{ + readonly _tag?: string; + readonly message?: string; + }>(relayConfigResponse); + + assert.equal(relayConfigResponse.status, 400); + assert.equal(body._tag, "EnvironmentHttpBadRequestError"); + assert.equal(body.message, "Cloud mint public key must be a valid Ed25519 public key."); + }).pipe(Effect.provide(NodeHttpServer.layerTest)), + ); + + it.effect("rejects relay config with insecure relay metadata or empty credentials", () => + Effect.gen(function* () { + yield* buildAppUnderTest(); + + const cloudKeyPair = NodeCrypto.generateKeyPairSync("ed25519", { + privateKeyEncoding: { format: "pem", type: "pkcs8" }, + publicKeyEncoding: { format: "pem", type: "spki" }, + }); + const ownerCookie = yield* getAuthenticatedSessionCookieHeader(); + const relayConfigUrl = yield* getHttpServerUrl("/api/cloud/relay-config"); + const postRelayConfig = (body: { + readonly relayUrl: string; + readonly relayIssuer?: string; + readonly cloudUserId: string; + readonly environmentCredential: string; + }) => + fetchEffect(relayConfigUrl, { + method: "POST", + headers: { + cookie: ownerCookie, + "content-type": "application/json", + }, + body: jsonRequestBody({ + ...body, + cloudMintPublicKey: cloudKeyPair.publicKey, + endpointRuntime: null, + }), + }); + + const insecureRelayUrl = yield* postRelayConfig({ + relayUrl: "http://relay.example.test", + cloudUserId: "user_123", + environmentCredential: "t3env_test_credential", + }); + const insecureRelayIssuer = yield* postRelayConfig({ + relayUrl: "https://relay.example.test", + cloudUserId: "user_123", + relayIssuer: "http://relay.example.test", + environmentCredential: "t3env_test_credential", + }); + const emptyCredential = yield* postRelayConfig({ + relayUrl: "https://relay.example.test", + cloudUserId: "user_123", + environmentCredential: " ", + }); + const insecureRelayUrlBody = yield* responseJsonEffect<{ readonly message?: string }>( + insecureRelayUrl, + ); + const insecureRelayIssuerBody = yield* responseJsonEffect<{ readonly message?: string }>( + insecureRelayIssuer, + ); + const emptyCredentialBody = yield* responseJsonEffect<{ readonly message?: string }>( + emptyCredential, + ); + + assert.equal(insecureRelayUrl.status, 400); + assert.equal(insecureRelayUrlBody.message, "Relay URL must be a secure absolute HTTPS URL."); + assert.equal(insecureRelayIssuer.status, 400); + assert.equal( + insecureRelayIssuerBody.message, + "Relay issuer must be a secure absolute HTTPS URL.", + ); + assert.equal(emptyCredential.status, 400); + assert.equal(emptyCredentialBody.message, "Relay environment credential is required."); + }).pipe(Effect.provide(NodeHttpServer.layerTest)), + ); + + it.effect("rejects relay config replacement from a different cloud account", () => + Effect.gen(function* () { + yield* buildAppUnderTest(); + + const cloudKeyPair = NodeCrypto.generateKeyPairSync("ed25519", { + privateKeyEncoding: { format: "pem", type: "pkcs8" }, + publicKeyEncoding: { format: "pem", type: "spki" }, + }); + const ownerCookie = yield* getAuthenticatedSessionCookieHeader(); + const relayConfigUrl = yield* getHttpServerUrl("/api/cloud/relay-config"); + const postRelayConfig = (cloudUserId: string, environmentCredential: string) => + fetchEffect(relayConfigUrl, { + method: "POST", + headers: { + cookie: ownerCookie, + "content-type": "application/json", + }, + body: jsonRequestBody({ + relayUrl: "https://relay.example.test", + cloudUserId, + environmentCredential, + cloudMintPublicKey: cloudKeyPair.publicKey, + endpointRuntime: null, + }), + }); + + const firstResponse = yield* postRelayConfig("user_123", "t3env_first_credential"); + const replacementResponse = yield* postRelayConfig("user_456", "t3env_second_credential"); + const replacementBody = yield* responseJsonEffect<{ + readonly _tag?: string; + readonly message?: string; + }>(replacementResponse); + + assert.equal(firstResponse.status, 200); + assert.equal(replacementResponse.status, 409); + assert.equal(replacementBody._tag, "EnvironmentHttpConflictError"); + assert.equal( + replacementBody.message, + "This environment is already linked to a different cloud account. Unlink it before switching accounts.", + ); + }).pipe(Effect.provide(NodeHttpServer.layerTest)), + ); + + it.effect("reports local cloud link state from persisted relay config", () => + Effect.gen(function* () { + yield* buildAppUnderTest(); + + const cloudKeyPair = NodeCrypto.generateKeyPairSync("ed25519", { + privateKeyEncoding: { format: "pem", type: "pkcs8" }, + publicKeyEncoding: { format: "pem", type: "spki" }, + }); + const ownerCookie = yield* getAuthenticatedSessionCookieHeader(); + const linkStateUrl = yield* getHttpServerUrl("/api/cloud/link-state"); + const relayConfigUrl = yield* getHttpServerUrl("/api/cloud/relay-config"); + + const initialResponse = yield* fetchEffect(linkStateUrl, { + headers: { + cookie: ownerCookie, + }, + }); + const initialBody = yield* responseJsonEffect<{ + readonly linked?: boolean; + readonly cloudUserId?: string | null; + }>(initialResponse); + assert.equal(initialResponse.status, 200); + assert.equal(initialBody.linked, false); + assert.equal(initialBody.cloudUserId, null); + + const relayConfigResponse = yield* fetchEffect(relayConfigUrl, { + method: "POST", + headers: { + cookie: ownerCookie, + "content-type": "application/json", + }, + body: jsonRequestBody({ + relayUrl: "https://transport.example.test", + relayIssuer: "https://relay.example.test", + cloudUserId: "user_123", + environmentCredential: "t3env_test_credential", + cloudMintPublicKey: cloudKeyPair.publicKey, + endpointRuntime: null, + }), + }); + assert.equal(relayConfigResponse.status, 200); + + const linkedResponse = yield* fetchEffect(linkStateUrl, { + headers: { + cookie: ownerCookie, + }, + }); + const linkedBody = yield* responseJsonEffect<{ + readonly linked?: boolean; + readonly cloudUserId?: string | null; + readonly relayUrl?: string | null; + readonly relayIssuer?: string | null; + }>(linkedResponse); + + assert.equal(linkedResponse.status, 200); + assert.equal(linkedBody.linked, true); + assert.equal(linkedBody.cloudUserId, "user_123"); + assert.equal(linkedBody.relayUrl, "https://transport.example.test"); + assert.equal(linkedBody.relayIssuer, "https://relay.example.test"); + }).pipe(Effect.provide(NodeHttpServer.layerTest)), + ); + + it.effect("unlinks local cloud state and disables the managed endpoint runtime", () => + Effect.gen(function* () { + const appliedRuntimeConfigs: Array = []; + yield* buildAppUnderTest({ + layers: { + cloudManagedEndpointRuntime: { + applyConfig: (config) => { + appliedRuntimeConfigs.push(config); + if (!config) { + return Effect.succeed({ status: "disabled" }); + } + return Effect.succeed({ + status: "running", + providerKind: "cloudflare_tunnel", + pid: 123, + ...(config.tunnelId ? { tunnelId: config.tunnelId } : {}), + ...(config.tunnelName ? { tunnelName: config.tunnelName } : {}), + }); + }, + }, + }, + }); + + const cloudKeyPair = NodeCrypto.generateKeyPairSync("ed25519", { + privateKeyEncoding: { format: "pem", type: "pkcs8" }, + publicKeyEncoding: { format: "pem", type: "spki" }, + }); + const ownerCookie = yield* getAuthenticatedSessionCookieHeader(); + const relayConfigUrl = yield* getHttpServerUrl("/api/cloud/relay-config"); + const unlinkUrl = yield* getHttpServerUrl("/api/cloud/unlink"); + const linkStateUrl = yield* getHttpServerUrl("/api/cloud/link-state"); + + const relayConfigResponse = yield* fetchEffect(relayConfigUrl, { + method: "POST", + headers: { + cookie: ownerCookie, + "content-type": "application/json", + }, + body: jsonRequestBody({ + relayUrl: "https://transport.example.test", + relayIssuer: "https://relay.example.test", + cloudUserId: "user_123", + environmentCredential: "t3env_test_credential", + cloudMintPublicKey: cloudKeyPair.publicKey, + endpointRuntime: { + providerKind: "cloudflare_tunnel", + connectorToken: "connector-token", + tunnelId: "tunnel-id", + tunnelName: "tunnel-name", + }, + }), + }); + assert.equal(relayConfigResponse.status, 200); + + const unlinkResponse = yield* fetchEffect(unlinkUrl, { + method: "POST", + headers: { + cookie: ownerCookie, + }, + }); + const unlinkBody = yield* responseJsonEffect<{ + readonly ok?: boolean; + readonly endpointRuntimeStatus?: { readonly status?: string }; + }>(unlinkResponse); + assert.equal(unlinkResponse.status, 200); + assert.equal(unlinkBody.ok, true); + assert.equal(unlinkBody.endpointRuntimeStatus?.status, "disabled"); + + const linkStateResponse = yield* fetchEffect(linkStateUrl, { + headers: { + cookie: ownerCookie, + }, + }); + const linkStateBody = yield* responseJsonEffect<{ + readonly linked?: boolean; + readonly cloudUserId?: string | null; + readonly relayUrl?: string | null; + readonly relayIssuer?: string | null; + }>(linkStateResponse); + assert.equal(linkStateResponse.status, 200); + assert.equal(linkStateBody.linked, false); + assert.equal(linkStateBody.cloudUserId, null); + assert.equal(linkStateBody.relayUrl, null); + assert.equal(linkStateBody.relayIssuer, null); + assert.deepEqual(appliedRuntimeConfigs, [ + { + providerKind: "cloudflare_tunnel", + connectorToken: "connector-token", + tunnelId: "tunnel-id", + tunnelName: "tunnel-name", + }, + null, + ]); + }).pipe(Effect.provide(NodeHttpServer.layerTest)), + ); + + it.effect("rejects replayed cloud mint requests atomically", () => + Effect.gen(function* () { + yield* buildAppUnderTest(); + + const cloudKeyPair = NodeCrypto.generateKeyPairSync("ed25519", { + privateKeyEncoding: { format: "pem", type: "pkcs8" }, + publicKeyEncoding: { format: "pem", type: "spki" }, + }); + const ownerCookie = yield* getAuthenticatedSessionCookieHeader(); + const relayConfigUrl = yield* getHttpServerUrl("/api/cloud/relay-config"); + const relayConfigResponse = yield* fetchEffect(relayConfigUrl, { + method: "POST", + headers: { + cookie: ownerCookie, + "content-type": "application/json", + }, + body: jsonRequestBody({ + relayUrl: "https://relay.example.test", + cloudUserId: "user_123", + environmentCredential: "t3env_test_credential", + cloudMintPublicKey: cloudKeyPair.publicKey, + endpointRuntime: null, + }), + }); + assert.equal(relayConfigResponse.status, 200); + + const now = yield* DateTime.now; + const request = makeCloudMintCredentialRequest({ + privateKey: cloudKeyPair.privateKey, + environmentId: testEnvironmentDescriptor.environmentId, + clientProofKeyThumbprint: "client-proof-key-thumbprint", + nonce: "cloud-mint-nonce-1", + issuedAt: DateTime.formatIso(now), + expiresAt: DateTime.formatIso(DateTime.add(now, { minutes: 5 })), + }); + const mintUrl = yield* getHttpServerUrl("/api/cloud/mint-credential"); + const postMint = () => + fetchEffect(mintUrl, { + method: "POST", + headers: { + "content-type": "application/json", + }, + body: jsonRequestBody(request), + }); + + const firstResponse = yield* postMint(); + const replayResponse = yield* postMint(); + const replayBody = yield* responseJsonEffect<{ + readonly _tag?: string; + readonly message?: string; + }>(replayResponse); + + assert.equal(firstResponse.status, 200); + assert.equal(replayResponse.status, 409); + assert.equal(replayBody._tag, "EnvironmentHttpConflictError"); + assert.equal(replayBody.message, "Cloud mint request was already consumed."); + }).pipe(Effect.provide(NodeHttpServer.layerTest)), + ); + + it.effect("serves the documented T3 Cloud mint credential endpoint", () => + Effect.gen(function* () { + yield* buildAppUnderTest(); + + const cloudKeyPair = NodeCrypto.generateKeyPairSync("ed25519", { + privateKeyEncoding: { format: "pem", type: "pkcs8" }, + publicKeyEncoding: { format: "pem", type: "spki" }, + }); + const ownerCookie = yield* getAuthenticatedSessionCookieHeader(); + const relayConfigUrl = yield* getHttpServerUrl("/api/cloud/relay-config"); + const relayConfigResponse = yield* fetchEffect(relayConfigUrl, { + method: "POST", + headers: { + cookie: ownerCookie, + "content-type": "application/json", + }, + body: jsonRequestBody({ + relayUrl: "https://relay.example.test", + cloudUserId: "user_123", + environmentCredential: "t3env_test_credential", + cloudMintPublicKey: cloudKeyPair.publicKey, + endpointRuntime: null, + }), + }); + assert.equal(relayConfigResponse.status, 200); + + const now = yield* DateTime.now; + const request = makeCloudMintCredentialRequest({ + privateKey: cloudKeyPair.privateKey, + environmentId: testEnvironmentDescriptor.environmentId, + clientProofKeyThumbprint: "client-proof-key-thumbprint", + jti: "cloud-mint-jti-documented-endpoint", + nonce: "cloud-mint-nonce-documented-endpoint", + issuedAt: DateTime.formatIso(now), + expiresAt: DateTime.formatIso(DateTime.add(now, { minutes: 5 })), + }); + const mintUrl = yield* getHttpServerUrl("/api/t3-cloud/mint-credential"); + const response = yield* fetchEffect(mintUrl, { + method: "POST", + headers: { + "content-type": "application/json", + }, + body: jsonRequestBody(request), + }); + + assert.equal(response.status, 200); + const body = yield* responseJsonEffect<{ + readonly credential?: string; + readonly proof?: string; + }>(response); + assert.equal(typeof body.credential, "string"); + assert.equal(typeof body.proof, "string"); + assert.equal( + decodeCompactJwtPayload<{ readonly requestNonce?: string }>(body.proof!).requestNonce, + "cloud-mint-nonce-documented-endpoint", + ); + }).pipe(Effect.provide(NodeHttpServer.layerTest)), + ); + + it.effect("serves signed T3 Cloud environment health checks", () => + Effect.gen(function* () { + yield* buildAppUnderTest(); + + const cloudKeyPair = NodeCrypto.generateKeyPairSync("ed25519", { + privateKeyEncoding: { format: "pem", type: "pkcs8" }, + publicKeyEncoding: { format: "pem", type: "spki" }, + }); + const ownerCookie = yield* getAuthenticatedSessionCookieHeader(); + const relayConfigUrl = yield* getHttpServerUrl("/api/cloud/relay-config"); + const relayConfigResponse = yield* fetchEffect(relayConfigUrl, { + method: "POST", + headers: { + cookie: ownerCookie, + "content-type": "application/json", + }, + body: jsonRequestBody({ + relayUrl: "https://relay.example.test", + cloudUserId: "user_123", + environmentCredential: "t3env_test_credential", + cloudMintPublicKey: cloudKeyPair.publicKey, + endpointRuntime: null, + }), + }); + assert.equal(relayConfigResponse.status, 200); + + const now = yield* DateTime.now; + const request = makeCloudEnvironmentHealthRequest({ + privateKey: cloudKeyPair.privateKey, + environmentId: testEnvironmentDescriptor.environmentId, + jti: "cloud-health-jti-documented-endpoint", + nonce: "cloud-health-nonce-documented-endpoint", + issuedAt: DateTime.formatIso(now), + expiresAt: DateTime.formatIso(DateTime.add(now, { minutes: 5 })), + }); + const healthUrl = yield* getHttpServerUrl("/api/t3-cloud/health"); + const response = yield* fetchEffect(healthUrl, { + method: "POST", + headers: { + "content-type": "application/json", + }, + body: jsonRequestBody(request), + }); + + assert.equal(response.status, 200); + const body = yield* responseJsonEffect<{ + readonly status?: string; + readonly descriptor?: { readonly environmentId?: string }; + readonly proof?: string; + }>(response); + assert.equal(body.status, "online"); + assert.equal(body.descriptor?.environmentId, testEnvironmentDescriptor.environmentId); + assert.equal(typeof body.proof, "string"); + assert.equal( + decodeCompactJwtPayload<{ readonly requestNonce?: string }>(body.proof!).requestNonce, + "cloud-health-nonce-documented-endpoint", + ); + }).pipe(Effect.provide(NodeHttpServer.layerTest)), + ); + + it.effect("rejects replayed cloud health requests atomically", () => + Effect.gen(function* () { + yield* buildAppUnderTest(); + + const cloudKeyPair = NodeCrypto.generateKeyPairSync("ed25519", { + privateKeyEncoding: { format: "pem", type: "pkcs8" }, + publicKeyEncoding: { format: "pem", type: "spki" }, + }); + const ownerCookie = yield* getAuthenticatedSessionCookieHeader(); + const relayConfigUrl = yield* getHttpServerUrl("/api/cloud/relay-config"); + const relayConfigResponse = yield* fetchEffect(relayConfigUrl, { + method: "POST", + headers: { + cookie: ownerCookie, + "content-type": "application/json", + }, + body: jsonRequestBody({ + relayUrl: "https://relay.example.test", + cloudUserId: "user_123", + environmentCredential: "t3env_test_credential", + cloudMintPublicKey: cloudKeyPair.publicKey, + endpointRuntime: null, + }), + }); + assert.equal(relayConfigResponse.status, 200); + + const now = yield* DateTime.now; + const request = makeCloudEnvironmentHealthRequest({ + privateKey: cloudKeyPair.privateKey, + environmentId: testEnvironmentDescriptor.environmentId, + jti: "cloud-health-jti-replay", + nonce: "cloud-health-nonce-replay", + issuedAt: DateTime.formatIso(now), + expiresAt: DateTime.formatIso(DateTime.add(now, { minutes: 5 })), + }); + const healthUrl = yield* getHttpServerUrl("/api/t3-cloud/health"); + const postHealth = () => + fetchEffect(healthUrl, { + method: "POST", + headers: { + "content-type": "application/json", + }, + body: jsonRequestBody(request), + }); + + const firstResponse = yield* postHealth(); + const replayResponse = yield* postHealth(); + const replayBody = yield* responseJsonEffect<{ + readonly _tag?: string; + readonly message?: string; + }>(replayResponse); + + assert.equal(firstResponse.status, 200); + assert.equal(replayResponse.status, 409); + assert.equal(replayBody._tag, "EnvironmentHttpConflictError"); + assert.equal(replayBody.message, "Cloud health request was already consumed."); + }).pipe(Effect.provide(NodeHttpServer.layerTest)), + ); + + it.effect( + "validates cloud proofs against the configured relay issuer, not the transport URL", + () => + Effect.gen(function* () { + yield* buildAppUnderTest(); + + const cloudKeyPair = NodeCrypto.generateKeyPairSync("ed25519", { + privateKeyEncoding: { format: "pem", type: "pkcs8" }, + publicKeyEncoding: { format: "pem", type: "spki" }, + }); + const ownerCookie = yield* getAuthenticatedSessionCookieHeader(); + const relayConfigUrl = yield* getHttpServerUrl("/api/cloud/relay-config"); + const relayConfigResponse = yield* fetchEffect(relayConfigUrl, { + method: "POST", + headers: { + cookie: ownerCookie, + "content-type": "application/json", + }, + body: jsonRequestBody({ + relayUrl: "https://transport.example.test", + cloudUserId: "user_123", + relayIssuer: "https://relay.example.test", + environmentCredential: "t3env_test_credential", + cloudMintPublicKey: cloudKeyPair.publicKey, + endpointRuntime: null, + }), + }); + assert.equal(relayConfigResponse.status, 200); + + const now = yield* DateTime.now; + const mintUrl = yield* getHttpServerUrl("/api/t3-cloud/mint-credential"); + const postMint = (request: ReturnType) => + fetchEffect(mintUrl, { + method: "POST", + headers: { + "content-type": "application/json", + }, + body: jsonRequestBody(request), + }); + + const acceptedResponse = yield* postMint( + makeCloudMintCredentialRequest({ + privateKey: cloudKeyPair.privateKey, + environmentId: testEnvironmentDescriptor.environmentId, + clientProofKeyThumbprint: "client-proof-key-thumbprint", + issuer: "https://relay.example.test", + jti: "cloud-mint-jti-explicit-relay-issuer", + nonce: "cloud-mint-nonce-explicit-relay-issuer", + issuedAt: DateTime.formatIso(now), + expiresAt: DateTime.formatIso(DateTime.add(now, { minutes: 5 })), + }), + ); + const rejectedResponse = yield* postMint( + makeCloudMintCredentialRequest({ + privateKey: cloudKeyPair.privateKey, + environmentId: testEnvironmentDescriptor.environmentId, + clientProofKeyThumbprint: "client-proof-key-thumbprint", + issuer: "https://transport.example.test", + jti: "cloud-mint-jti-transport-url", + nonce: "cloud-mint-nonce-transport-url", + issuedAt: DateTime.formatIso(now), + expiresAt: DateTime.formatIso(DateTime.add(now, { minutes: 5 })), + }), + ); + + assert.equal(acceptedResponse.status, 200); + assert.equal(rejectedResponse.status, 401); + }).pipe(Effect.provide(NodeHttpServer.layerTest)), + ); + + it.effect("fails relay config when the managed endpoint connector cannot start", () => + Effect.gen(function* () { + yield* buildAppUnderTest({ + layers: { + cloudManagedEndpointRuntime: { + applyConfig: () => + Effect.succeed({ + status: "failed", + providerKind: "cloudflare_tunnel", + reason: "cloudflared missing", + tunnelId: "tunnel-1", + }), + }, + }, + }); + + const cloudKeyPair = NodeCrypto.generateKeyPairSync("ed25519", { + privateKeyEncoding: { format: "pem", type: "pkcs8" }, + publicKeyEncoding: { format: "pem", type: "spki" }, + }); + const ownerCookie = yield* getAuthenticatedSessionCookieHeader(); + const relayConfigUrl = yield* getHttpServerUrl("/api/cloud/relay-config"); + const relayConfigResponse = yield* fetchEffect(relayConfigUrl, { + method: "POST", + headers: { + cookie: ownerCookie, + "content-type": "application/json", + }, + body: jsonRequestBody({ + relayUrl: "https://relay.example.test", + cloudUserId: "user_123", + environmentCredential: "t3env_test_credential", + cloudMintPublicKey: cloudKeyPair.publicKey, + endpointRuntime: { + providerKind: "cloudflare_tunnel", + connectorToken: "connector-token", + tunnelId: "tunnel-1", + }, + }), + }); + + assert.equal(relayConfigResponse.status, 503); + const relayConfigBody = yield* responseJsonEffect<{ + _tag?: string; + message?: string; + endpointRuntimeStatus?: { status?: string; reason?: string }; + }>(relayConfigResponse); + assert.equal(relayConfigBody._tag, "EnvironmentCloudEndpointUnavailableError"); + assert.equal(relayConfigBody.message, "Managed endpoint runtime could not be started."); + assert.equal(relayConfigBody.endpointRuntimeStatus?.status, "failed"); + assert.equal(relayConfigBody.endpointRuntimeStatus?.reason, "cloudflared missing"); + + const now = yield* DateTime.now; + const healthRequest = makeCloudEnvironmentHealthRequest({ + privateKey: cloudKeyPair.privateKey, + environmentId: testEnvironmentDescriptor.environmentId, + nonce: "cloud-health-after-failed-runtime", + issuedAt: DateTime.formatIso(now), + expiresAt: DateTime.formatIso(DateTime.add(now, { minutes: 5 })), + }); + const healthUrl = yield* getHttpServerUrl("/api/t3-cloud/health"); + const healthResponse = yield* fetchEffect(healthUrl, { + method: "POST", + headers: { + "content-type": "application/json", + }, + body: jsonRequestBody(healthRequest), + }); + const healthBody = yield* responseJsonEffect<{ + _tag?: string; + message?: string; + }>(healthResponse); + assert.equal(healthResponse.status, 500); + assert.equal(healthBody._tag, "EnvironmentHttpInternalServerError"); + assert.equal( + healthBody.message, + "Cloud mint public key is not installed for this environment.", + ); + }).pipe(Effect.provide(NodeHttpServer.layerTest)), + ); + + it.effect("rejects cloud mint requests with the wrong issuer or audience", () => + Effect.gen(function* () { + yield* buildAppUnderTest(); + + const cloudKeyPair = NodeCrypto.generateKeyPairSync("ed25519", { + privateKeyEncoding: { format: "pem", type: "pkcs8" }, + publicKeyEncoding: { format: "pem", type: "spki" }, + }); + const ownerCookie = yield* getAuthenticatedSessionCookieHeader(); + const relayConfigUrl = yield* getHttpServerUrl("/api/cloud/relay-config"); + const relayConfigResponse = yield* fetchEffect(relayConfigUrl, { + method: "POST", + headers: { + cookie: ownerCookie, + "content-type": "application/json", + }, + body: jsonRequestBody({ + relayUrl: "https://relay.example.test/", + cloudUserId: "user_123", + environmentCredential: "t3env_test_credential", + cloudMintPublicKey: cloudKeyPair.publicKey, + endpointRuntime: null, + }), + }); + assert.equal(relayConfigResponse.status, 200); + + const now = yield* DateTime.now; + const mintUrl = yield* getHttpServerUrl("/api/cloud/mint-credential"); + const postMint = (request: ReturnType) => + fetchEffect(mintUrl, { + method: "POST", + headers: { + "content-type": "application/json", + }, + body: jsonRequestBody(request), + }); + + const wrongIssuer = yield* postMint( + makeCloudMintCredentialRequest({ + privateKey: cloudKeyPair.privateKey, + environmentId: testEnvironmentDescriptor.environmentId, + clientProofKeyThumbprint: "client-proof-key-thumbprint", + issuer: "https://attacker.example.test", + jti: "cloud-mint-jti-wrong-issuer", + nonce: "cloud-mint-nonce-wrong-issuer", + issuedAt: DateTime.formatIso(now), + expiresAt: DateTime.formatIso(DateTime.add(now, { minutes: 5 })), + }), + ); + const wrongAudience = yield* postMint( + makeCloudMintCredentialRequest({ + privateKey: cloudKeyPair.privateKey, + environmentId: testEnvironmentDescriptor.environmentId, + clientProofKeyThumbprint: "client-proof-key-thumbprint", + audience: "t3-env:other-environment", + jti: "cloud-mint-jti-wrong-audience", + nonce: "cloud-mint-nonce-wrong-audience", + issuedAt: DateTime.formatIso(now), + expiresAt: DateTime.formatIso(DateTime.add(now, { minutes: 5 })), + }), + ); + + assert.equal(wrongIssuer.status, 401); + assert.equal(wrongAudience.status, 401); + }).pipe(Effect.provide(NodeHttpServer.layerTest)), + ); + + it.effect("rejects cloud mint requests for a cloud subject other than the linked user", () => + Effect.gen(function* () { + yield* buildAppUnderTest(); + + const cloudKeyPair = NodeCrypto.generateKeyPairSync("ed25519", { + privateKeyEncoding: { format: "pem", type: "pkcs8" }, + publicKeyEncoding: { format: "pem", type: "spki" }, + }); + const ownerCookie = yield* getAuthenticatedSessionCookieHeader(); + const relayConfigUrl = yield* getHttpServerUrl("/api/cloud/relay-config"); + const relayConfigResponse = yield* fetchEffect(relayConfigUrl, { + method: "POST", + headers: { + cookie: ownerCookie, + "content-type": "application/json", + }, + body: jsonRequestBody({ + relayUrl: "https://relay.example.test/", + cloudUserId: "user_123", + environmentCredential: "t3env_test_credential", + cloudMintPublicKey: cloudKeyPair.publicKey, + endpointRuntime: null, + }), + }); + assert.equal(relayConfigResponse.status, 200); + + const now = yield* DateTime.now; + const mintUrl = yield* getHttpServerUrl("/api/t3-cloud/mint-credential"); + const response = yield* fetchEffect(mintUrl, { + method: "POST", + headers: { + "content-type": "application/json", + }, + body: jsonRequestBody( + makeCloudMintCredentialRequest({ + privateKey: cloudKeyPair.privateKey, + environmentId: testEnvironmentDescriptor.environmentId, + clientProofKeyThumbprint: "client-proof-key-thumbprint", + subject: "user_other", + jti: "cloud-mint-jti-wrong-subject", + nonce: "cloud-mint-nonce-wrong-subject", + issuedAt: DateTime.formatIso(now), + expiresAt: DateTime.formatIso(DateTime.add(now, { minutes: 5 })), + }), + ), + }); + + assert.equal(response.status, 401); + }).pipe(Effect.provide(NodeHttpServer.layerTest)), + ); + + it.effect("rejects cloud mint requests without the exact connect scope", () => + Effect.gen(function* () { + yield* buildAppUnderTest(); + + const cloudKeyPair = NodeCrypto.generateKeyPairSync("ed25519", { + privateKeyEncoding: { format: "pem", type: "pkcs8" }, + publicKeyEncoding: { format: "pem", type: "spki" }, + }); + const ownerCookie = yield* getAuthenticatedSessionCookieHeader(); + const relayConfigUrl = yield* getHttpServerUrl("/api/cloud/relay-config"); + const relayConfigResponse = yield* fetchEffect(relayConfigUrl, { + method: "POST", + headers: { + cookie: ownerCookie, + "content-type": "application/json", + }, + body: jsonRequestBody({ + relayUrl: "https://relay.example.test/", + cloudUserId: "user_123", + environmentCredential: "t3env_test_credential", + cloudMintPublicKey: cloudKeyPair.publicKey, + endpointRuntime: null, + }), + }); + assert.equal(relayConfigResponse.status, 200); + + const now = yield* DateTime.now; + const mintUrl = yield* getHttpServerUrl("/api/t3-cloud/mint-credential"); + const response = yield* fetchEffect(mintUrl, { + method: "POST", + headers: { + "content-type": "application/json", + }, + body: jsonRequestBody( + makeCloudMintCredentialRequest({ + privateKey: cloudKeyPair.privateKey, + environmentId: testEnvironmentDescriptor.environmentId, + clientProofKeyThumbprint: "client-proof-key-thumbprint", + jti: "cloud-mint-jti-duplicate-scope", + nonce: "cloud-mint-nonce-duplicate-scope", + issuedAt: DateTime.formatIso(now), + expiresAt: DateTime.formatIso(DateTime.add(now, { minutes: 5 })), + scope: ["environment:connect", "environment:connect"], + }), + ), + }); + + assert.equal(response.status, 401); + }).pipe(Effect.provide(NodeHttpServer.layerTest)), + ); + + it.effect("rejects cloud health requests with the wrong issuer or audience", () => + Effect.gen(function* () { + yield* buildAppUnderTest(); + + const cloudKeyPair = NodeCrypto.generateKeyPairSync("ed25519", { + privateKeyEncoding: { format: "pem", type: "pkcs8" }, + publicKeyEncoding: { format: "pem", type: "spki" }, + }); + const ownerCookie = yield* getAuthenticatedSessionCookieHeader(); + const relayConfigUrl = yield* getHttpServerUrl("/api/cloud/relay-config"); + const relayConfigResponse = yield* fetchEffect(relayConfigUrl, { + method: "POST", + headers: { + cookie: ownerCookie, + "content-type": "application/json", + }, + body: jsonRequestBody({ + relayUrl: "https://relay.example.test/", + cloudUserId: "user_123", + environmentCredential: "t3env_test_credential", + cloudMintPublicKey: cloudKeyPair.publicKey, + endpointRuntime: null, + }), + }); + assert.equal(relayConfigResponse.status, 200); + + const now = yield* DateTime.now; + const healthUrl = yield* getHttpServerUrl("/api/t3-cloud/health"); + const postHealth = (request: ReturnType) => + fetchEffect(healthUrl, { + method: "POST", + headers: { + "content-type": "application/json", + }, + body: jsonRequestBody(request), + }); + + const wrongIssuer = yield* postHealth( + makeCloudEnvironmentHealthRequest({ + privateKey: cloudKeyPair.privateKey, + environmentId: testEnvironmentDescriptor.environmentId, + issuer: "https://attacker.example.test", + jti: "cloud-health-jti-wrong-issuer", + nonce: "cloud-health-nonce-wrong-issuer", + issuedAt: DateTime.formatIso(now), + expiresAt: DateTime.formatIso(DateTime.add(now, { minutes: 5 })), + }), + ); + const wrongAudience = yield* postHealth( + makeCloudEnvironmentHealthRequest({ + privateKey: cloudKeyPair.privateKey, + environmentId: testEnvironmentDescriptor.environmentId, + audience: "t3-env:other-environment", + jti: "cloud-health-jti-wrong-audience", + nonce: "cloud-health-nonce-wrong-audience", + issuedAt: DateTime.formatIso(now), + expiresAt: DateTime.formatIso(DateTime.add(now, { minutes: 5 })), + }), + ); + + assert.equal(wrongIssuer.status, 401); + assert.equal(wrongAudience.status, 401); + }).pipe(Effect.provide(NodeHttpServer.layerTest)), + ); + + it.effect("rejects cloud health requests for a cloud subject other than the linked user", () => + Effect.gen(function* () { + yield* buildAppUnderTest(); + + const cloudKeyPair = NodeCrypto.generateKeyPairSync("ed25519", { + privateKeyEncoding: { format: "pem", type: "pkcs8" }, + publicKeyEncoding: { format: "pem", type: "spki" }, + }); + const ownerCookie = yield* getAuthenticatedSessionCookieHeader(); + const relayConfigUrl = yield* getHttpServerUrl("/api/cloud/relay-config"); + const relayConfigResponse = yield* fetchEffect(relayConfigUrl, { + method: "POST", + headers: { + cookie: ownerCookie, + "content-type": "application/json", + }, + body: jsonRequestBody({ + relayUrl: "https://relay.example.test/", + cloudUserId: "user_123", + environmentCredential: "t3env_test_credential", + cloudMintPublicKey: cloudKeyPair.publicKey, + endpointRuntime: null, + }), + }); + assert.equal(relayConfigResponse.status, 200); + + const now = yield* DateTime.now; + const healthUrl = yield* getHttpServerUrl("/api/t3-cloud/health"); + const response = yield* fetchEffect(healthUrl, { + method: "POST", + headers: { + "content-type": "application/json", + }, + body: jsonRequestBody( + makeCloudEnvironmentHealthRequest({ + privateKey: cloudKeyPair.privateKey, + environmentId: testEnvironmentDescriptor.environmentId, + subject: "user_other", + jti: "cloud-health-jti-wrong-subject", + nonce: "cloud-health-nonce-wrong-subject", + issuedAt: DateTime.formatIso(now), + expiresAt: DateTime.formatIso(DateTime.add(now, { minutes: 5 })), + }), + ), + }); + + assert.equal(response.status, 401); + }).pipe(Effect.provide(NodeHttpServer.layerTest)), + ); + + it.effect("rejects cloud health requests without the exact status scope", () => + Effect.gen(function* () { + yield* buildAppUnderTest(); + + const cloudKeyPair = NodeCrypto.generateKeyPairSync("ed25519", { + privateKeyEncoding: { format: "pem", type: "pkcs8" }, + publicKeyEncoding: { format: "pem", type: "spki" }, + }); + const ownerCookie = yield* getAuthenticatedSessionCookieHeader(); + const relayConfigUrl = yield* getHttpServerUrl("/api/cloud/relay-config"); + const relayConfigResponse = yield* fetchEffect(relayConfigUrl, { + method: "POST", + headers: { + cookie: ownerCookie, + "content-type": "application/json", + }, + body: jsonRequestBody({ + relayUrl: "https://relay.example.test/", + cloudUserId: "user_123", + environmentCredential: "t3env_test_credential", + cloudMintPublicKey: cloudKeyPair.publicKey, + endpointRuntime: null, + }), + }); + assert.equal(relayConfigResponse.status, 200); + + const now = yield* DateTime.now; + const healthUrl = yield* getHttpServerUrl("/api/t3-cloud/health"); + const response = yield* fetchEffect(healthUrl, { + method: "POST", + headers: { + "content-type": "application/json", + }, + body: jsonRequestBody( + makeCloudEnvironmentHealthRequest({ + privateKey: cloudKeyPair.privateKey, + environmentId: testEnvironmentDescriptor.environmentId, + jti: "cloud-health-jti-duplicate-scope", + nonce: "cloud-health-nonce-duplicate-scope", + issuedAt: DateTime.formatIso(now), + expiresAt: DateTime.formatIso(DateTime.add(now, { minutes: 5 })), + scope: ["environment:status", "environment:status"], + }), + ), + }); + + assert.equal(response.status, 401); + }).pipe(Effect.provide(NodeHttpServer.layerTest)), + ); + it.effect("issues short-lived websocket tickets for authenticated bearer sessions", () => Effect.gen(function* () { yield* buildAppUnderTest(); const bearerToken = yield* getAuthenticatedBearerSessionToken(); - const wsTicketResponse = yield* HttpClient.post("/api/auth/websocket-ticket", { + const wsTicketUrl = yield* getHttpServerUrl("/api/auth/websocket-ticket"); + const wsTicketResponse = yield* fetchEffect(wsTicketUrl, { + method: "POST", headers: { authorization: `Bearer ${bearerToken}`, }, }); - const wsTicketBody = (yield* wsTicketResponse.json) as { + const wsTicketBody = yield* responseJsonEffect<{ readonly ticket: string; readonly expiresAt: string; - }; + }>(wsTicketResponse); assert.equal(wsTicketResponse.status, 200); assert.equal(typeof wsTicketBody.ticket, "string"); @@ -1274,43 +3058,46 @@ it.layer(NodeServices.layer)("server router seam", (it) => { yield* buildAppUnderTest(); const origin = crossOriginClientOrigin; - const { response: bootstrapResponse, body: tokenBody } = yield* exchangeAccessToken( + const { response: tokenResponse, body: tokenBody } = yield* exchangeAccessToken( defaultDesktopBootstrapToken, { headers: { origin }, }, ); - assert.equal(bootstrapResponse.status, 200); - assertBrowserApiCorsResponseHeaders(bootstrapResponse.headers); + assert.equal(tokenResponse.status, 200); + assertBrowserApiCorsResponseHeaders(tokenResponse.headers); assert.equal(tokenBody.token_type, "Bearer"); assert.equal(typeof tokenBody.access_token, "string"); - const sessionResponse = yield* HttpClient.get("/api/auth/session", { + const sessionUrl = yield* getHttpServerUrl("/api/auth/session"); + const sessionResponse = yield* fetchEffect(sessionUrl, { headers: { authorization: `Bearer ${tokenBody.access_token ?? ""}`, origin, }, }); - const sessionBody = (yield* sessionResponse.json) as { + const sessionBody = yield* responseJsonEffect<{ readonly authenticated: boolean; readonly sessionMethod?: string; - }; + }>(sessionResponse); assert.equal(sessionResponse.status, 200); assertBrowserApiCorsResponseHeaders(sessionResponse.headers); assert.equal(sessionBody.authenticated, true); assert.equal(sessionBody.sessionMethod, "bearer-access-token"); - const wsTicketResponse = yield* HttpClient.post("/api/auth/websocket-ticket", { + const wsTicketUrl = yield* getHttpServerUrl("/api/auth/websocket-ticket"); + const wsTicketResponse = yield* fetchEffect(wsTicketUrl, { + method: "POST", headers: { authorization: `Bearer ${tokenBody.access_token ?? ""}`, origin, }, }); - const wsTicketBody = (yield* wsTicketResponse.json) as { + const wsTicketBody = yield* responseJsonEffect<{ readonly ticket: string; - }; + }>(wsTicketResponse); assert.equal(wsTicketResponse.status, 200); assertBrowserApiCorsResponseHeaders(wsTicketResponse.headers); @@ -1324,7 +3111,9 @@ it.layer(NodeServices.layer)("server router seam", (it) => { Effect.gen(function* () { yield* buildAppUnderTest(); - const response = yield* HttpClient.options("/api/auth/websocket-ticket", { + const wsTicketUrl = yield* getHttpServerUrl("/api/auth/websocket-ticket"); + const response = yield* fetchEffect(wsTicketUrl, { + method: "OPTIONS", headers: { origin: crossOriginClientOrigin, "access-control-request-method": "POST", @@ -1341,17 +3130,19 @@ it.layer(NodeServices.layer)("server router seam", (it) => { Effect.gen(function* () { yield* buildAppUnderTest(); - const response = yield* HttpClient.post("/api/auth/websocket-ticket", { + const wsTicketUrl = yield* getHttpServerUrl("/api/auth/websocket-ticket"); + const response = yield* fetchEffect(wsTicketUrl, { + method: "POST", headers: { origin: crossOriginClientOrigin, }, }); - const body = (yield* response.json) as { + const body = yield* responseJsonEffect<{ readonly _tag?: string; readonly code?: string; readonly reason?: string; readonly traceId?: string; - }; + }>(response); assert.equal(response.status, 401); assertBrowserApiCorsResponseHeaders(response.headers); @@ -1362,67 +3153,6 @@ it.layer(NodeServices.layer)("server router seam", (it) => { }).pipe(Effect.provide(NodeHttpServer.layerTest)), ); - it.effect("persists token exchange client display metadata for authorized-client listings", () => - Effect.gen(function* () { - yield* buildAppUnderTest({ - config: { - host: "0.0.0.0", - }, - }); - - const ownerCookie = yield* getAuthenticatedSessionCookieHeader(); - const pairingResponse = yield* HttpClient.post("/api/auth/pairing-token", { - headers: { - cookie: ownerCookie, - }, - body: yield* HttpBody.json({}), - }); - const pairingBody = (yield* pairingResponse.json) as { - readonly credential: string; - }; - - const { response } = yield* exchangeAccessToken(pairingBody.credential, { - headers: { - "user-agent": "undici", - }, - scope: "orchestration:read orchestration:operate terminal:operate review:write relay:read", - clientMetadata: { - label: "T3 Code Mobile", - deviceType: "mobile", - os: "iOS", - }, - }); - - const clientsResponse = yield* HttpClient.get("/api/auth/clients", { - headers: { - cookie: ownerCookie, - }, - }); - const clients = (yield* clientsResponse.json) as ReadonlyArray<{ - readonly current: boolean; - readonly client: { - readonly label?: string; - readonly deviceType: string; - readonly ipAddress?: string; - readonly os?: string; - readonly userAgent?: string; - }; - }>; - const mobileClient = clients.find((client) => !client.current); - - assert.equal(pairingResponse.status, 200); - assert.equal(response.status, 200); - assert.equal(clientsResponse.status, 200); - assert.deepInclude(mobileClient?.client, { - label: "T3 Code Mobile", - deviceType: "mobile", - os: "iOS", - ipAddress: "127.0.0.1", - userAgent: "undici", - }); - }).pipe(Effect.provide(NodeHttpServer.layerTest)), - ); - it.effect("issues authenticated one-time pairing credentials for additional clients", () => Effect.gen(function* () { yield* buildAppUnderTest(); @@ -1538,8 +3268,9 @@ it.layer(NodeServices.layer)("server router seam", (it) => { const revokeResponse = yield* HttpClient.post("/api/auth/pairing-links/revoke", { headers: { cookie: ownerCookie, + "content-type": "application/json", }, - body: yield* HttpBody.json({ id: createdBody.id }), + body: HttpBody.text(jsonRequestBody({ id: createdBody.id }), "application/json"), }); const revokedBootstrap = yield* bootstrapBrowserSession(createdBody.credential); @@ -1601,16 +3332,21 @@ it.layer(NodeServices.layer)("server router seam", (it) => { }); const ownerCookie = yield* getAuthenticatedSessionCookieHeader(); - const ownerPairingResponse = yield* HttpClient.post("/api/auth/pairing-token", { + const pairingTokenUrl = yield* getHttpServerUrl("/api/auth/pairing-token"); + const ownerPairingResponse = yield* fetchEffect(pairingTokenUrl, { + method: "POST", headers: { cookie: ownerCookie, + "content-type": "application/json", }, - body: yield* HttpBody.json({ label: "Julius iPhone" }), + body: jsonRequestBody({ + label: "Julius iPhone", + }), }); - const ownerPairingBody = (yield* ownerPairingResponse.json) as { + const ownerPairingBody = yield* responseJsonEffect<{ readonly credential: string; readonly label?: string; - }; + }>(ownerPairingResponse); assert.equal(ownerPairingResponse.status, 200); const pairedSessionBootstrap = yield* bootstrapBrowserSession(ownerPairingBody.credential, { headers: { @@ -1794,8 +3530,9 @@ it.layer(NodeServices.layer)("server router seam", (it) => { const revokeResponse = yield* HttpClient.post("/api/auth/clients/revoke", { headers: { cookie: ownerCookie, + "content-type": "application/json", }, - body: yield* HttpBody.json({ sessionId: pairedSessionId }), + body: HttpBody.text(jsonRequestBody({ sessionId: pairedSessionId }), "application/json"), }); const pairedClientPairingResponse = yield* HttpClient.post("/api/auth/pairing-token", { headers: { @@ -1890,20 +3627,22 @@ it.layer(NodeServices.layer)("server router seam", (it) => { ); it.effect( - "accepts websocket rpc handshake with a dedicated websocket token in the query string", + "accepts websocket rpc handshake with a dedicated websocket ticket in the query string", () => Effect.gen(function* () { yield* buildAppUnderTest(); const bearerToken = yield* getAuthenticatedBearerSessionToken(); - const wsTicketResponse = yield* HttpClient.post("/api/auth/websocket-ticket", { + const wsTicketUrl = yield* getHttpServerUrl("/api/auth/websocket-ticket"); + const wsTicketResponse = yield* fetchEffect(wsTicketUrl, { + method: "POST", headers: { authorization: `Bearer ${bearerToken}`, }, }); - const wsTicketBody = (yield* wsTicketResponse.json) as { + const wsTicketBody = yield* responseJsonEffect<{ readonly ticket: string; - }; + }>(wsTicketResponse); const wsUrl = `${yield* getWsServerUrl("/ws", { authenticated: false })}?wsTicket=${encodeURIComponent(wsTicketBody.ticket)}`; const response = yield* Effect.scoped( @@ -2103,7 +3842,8 @@ it.layer(NodeServices.layer)("server router seam", (it) => { "content-type": "application/json", origin: "http://localhost:5733", }, - body: yield* HttpBody.json(payload), + // @effect-diagnostics-next-line preferSchemaOverJson:off + body: HttpBody.text(JSON.stringify(payload), "application/json"), }); assert.equal(response.status, 204); @@ -2148,8 +3888,7 @@ it.layer(NodeServices.layer)("server router seam", (it) => { ]); assert.deepEqual(upstreamRequests, [ { - // @effect-diagnostics-next-line preferSchemaOverJson:off - body: JSON.stringify(payload), + body: jsonRequestBody(payload), contentType: "application/json", }, ]); @@ -2170,14 +3909,18 @@ it.layer(NodeServices.layer)("server router seam", (it) => { assert.equal(response.status, 204); assert.equal(response.headers["access-control-allow-origin"], "*"); - assert.deepEqual( - splitHeaderTokens(response.headers["access-control-allow-methods"] ?? null), - ["GET", "OPTIONS", "POST"], - ); - assert.deepEqual( - splitHeaderTokens(response.headers["access-control-allow-headers"] ?? null), - ["authorization", "b3", "content-type", "traceparent"], - ); + assert.deepEqual(splitHeaderTokens(response.headers["access-control-allow-methods"]), [ + "GET", + "OPTIONS", + "POST", + ]); + assert.deepEqual(splitHeaderTokens(response.headers["access-control-allow-headers"]), [ + "authorization", + "b3", + "content-type", + "dpop", + "traceparent", + ]); }).pipe(Effect.provide(NodeHttpServer.layerTest)), ); @@ -2214,7 +3957,8 @@ it.layer(NodeServices.layer)("server router seam", (it) => { cookie: yield* getAuthenticatedSessionCookieHeader(), "content-type": "application/json", }, - body: yield* HttpBody.json(payload), + // @effect-diagnostics-next-line preferSchemaOverJson:off + body: HttpBody.text(JSON.stringify(payload), "application/json"), }); assert.equal(response.status, 204); diff --git a/apps/server/src/server.ts b/apps/server/src/server.ts index 5c0bbb8425..06251ef343 100644 --- a/apps/server/src/server.ts +++ b/apps/server/src/server.ts @@ -44,6 +44,7 @@ import { ProviderRuntimeIngestionLive } from "./orchestration/Layers/ProviderRun import { ProviderCommandReactorLive } from "./orchestration/Layers/ProviderCommandReactor.ts"; import { CheckpointReactorLive } from "./orchestration/Layers/CheckpointReactor.ts"; import { ThreadDeletionReactorLive } from "./orchestration/Layers/ThreadDeletionReactor.ts"; +import * as AgentAwarenessRelay from "./relay/AgentAwarenessRelay.ts"; import { ProviderRegistryLive } from "./provider/Layers/ProviderRegistry.ts"; import { ServerSettingsLive } from "./serverSettings.ts"; import { ProjectFaviconResolverLive } from "./project/Layers/ProjectFaviconResolver.ts"; @@ -67,6 +68,8 @@ import { ServerEnvironmentLive } from "./environment/Layers/ServerEnvironment.ts import { authHttpApiLayer, environmentAuthenticatedAuthLayer } from "./auth/http.ts"; import * as ServerSecretStore from "./auth/ServerSecretStore.ts"; import * as EnvironmentAuth from "./auth/EnvironmentAuth.ts"; +import { cloudHttpApiLayer } from "./cloud/http.ts"; +import * as CloudManagedEndpointRuntime from "./cloud/ManagedEndpointRuntime.ts"; import * as ProcessDiagnostics from "./diagnostics/ProcessDiagnostics.ts"; import * as ProcessResourceMonitor from "./diagnostics/ProcessResourceMonitor.ts"; import * as TraceDiagnostics from "./diagnostics/TraceDiagnostics.ts"; @@ -134,6 +137,7 @@ const ReactorLayerLive = Layer.empty.pipe( Layer.provideMerge(ProviderCommandReactorLive), Layer.provideMerge(CheckpointReactorLive), Layer.provideMerge(ThreadDeletionReactorLive), + Layer.provideMerge(AgentAwarenessRelay.layer.pipe(Layer.provide(ServerSecretStore.layer))), Layer.provideMerge(RuntimeReceiptBusLive), ); @@ -271,6 +275,10 @@ const RuntimeCoreDependenciesLive = ReactorLayerLive.pipe( Layer.provideMerge(RepositoryIdentityResolverLive), Layer.provideMerge(ServerEnvironmentLive), Layer.provideMerge(AuthLayerLive), + Layer.provideMerge(ServerSecretStore.layer), + Layer.provideMerge( + CloudManagedEndpointRuntime.layer.pipe(Layer.provide(ServerSecretStore.layer)), + ), ); const RuntimeDependenciesLive = RuntimeCoreDependenciesLive.pipe( @@ -291,6 +299,7 @@ const RuntimeServicesLive = ServerRuntimeStartupLive.pipe( export const makeRoutesLayer = Layer.mergeAll( HttpApiBuilder.layer(EnvironmentHttpApi).pipe( Layer.provide(authHttpApiLayer), + Layer.provide(cloudHttpApiLayer), Layer.provide(orchestrationHttpApiLayer), Layer.provide(serverEnvironmentHttpApiLayer), Layer.provide(environmentAuthenticatedAuthLayer), diff --git a/apps/server/src/serverRuntimeStartup.ts b/apps/server/src/serverRuntimeStartup.ts index 8c41e28b7b..cde308ffe4 100644 --- a/apps/server/src/serverRuntimeStartup.ts +++ b/apps/server/src/serverRuntimeStartup.ts @@ -8,6 +8,7 @@ import { ThreadId, } from "@t3tools/contracts"; import * as Data from "effect/Data"; +import * as Crypto from "effect/Crypto"; import * as Deferred from "effect/Deferred"; import * as Effect from "effect/Effect"; import * as Exit from "effect/Exit"; @@ -19,7 +20,6 @@ import * as Ref from "effect/Ref"; import * as Scope from "effect/Scope"; import * as Context from "effect/Context"; import * as Console from "effect/Console"; -import * as Crypto from "effect/Crypto"; import * as DateTime from "effect/DateTime"; import { ServerConfig } from "./config.ts"; @@ -289,6 +289,7 @@ export const makeServerRuntimeStartup = Effect.gen(function* () { const lifecycleEvents = yield* ServerLifecycleEvents; const serverSettings = yield* ServerSettingsService; const serverEnvironment = yield* ServerEnvironment; + const crypto = yield* Crypto.Crypto; const commandGate = yield* makeCommandGate; const httpListening = yield* Deferred.make(); @@ -361,7 +362,9 @@ export const makeServerRuntimeStartup = Effect.gen(function* () { runStartupPhase( "welcome.autobootstrap", Effect.gen(function* () { - const bootstrapTargets = yield* resolveAutoBootstrapWelcomeTargets; + const bootstrapTargets = yield* resolveAutoBootstrapWelcomeTargets.pipe( + Effect.provideService(Crypto.Crypto, crypto), + ); if (!bootstrapTargets.bootstrapProjectId && !bootstrapTargets.bootstrapThreadId) { return; } diff --git a/apps/web/package.json b/apps/web/package.json index b464a3a0a5..2d09705313 100644 --- a/apps/web/package.json +++ b/apps/web/package.json @@ -14,6 +14,8 @@ }, "dependencies": { "@base-ui/react": "^1.4.1", + "@clerk/clerk-js": "^6.13.0", + "@clerk/react": "^6.7.2", "@dnd-kit/core": "^6.3.1", "@dnd-kit/modifiers": "^9.0.0", "@dnd-kit/sortable": "^10.0.0", @@ -33,6 +35,7 @@ "@xterm/xterm": "^6.0.0", "class-variance-authority": "^0.7.1", "effect": "catalog:", + "jose": "catalog:", "lexical": "^0.41.0", "lucide-react": "^0.564.0", "react": "19.2.6", @@ -44,6 +47,7 @@ }, "devDependencies": { "@effect/platform-node": "catalog:", + "@effect/vitest": "catalog:", "@rolldown/plugin-babel": "^0.2.0", "@tailwindcss/vite": "^4.0.0", "@tanstack/router-plugin": "^1.161.0", diff --git a/apps/web/src/clientPersistenceStorage.ts b/apps/web/src/clientPersistenceStorage.ts index 30c949b37a..2da74ae6c4 100644 --- a/apps/web/src/clientPersistenceStorage.ts +++ b/apps/web/src/clientPersistenceStorage.ts @@ -27,6 +27,7 @@ const BrowserSavedEnvironmentRecordSchema = Schema.Struct({ port: Schema.NullOr(Schema.Number), }), ), + relayManaged: Schema.optionalKey(Schema.Struct({ relayUrl: Schema.String })), bearerToken: Schema.optionalKey(Schema.String), }); type BrowserSavedEnvironmentRecord = typeof BrowserSavedEnvironmentRecordSchema.Type; @@ -53,7 +54,11 @@ function toPersistedSavedEnvironmentRecord( createdAt: record.createdAt, lastConnectedAt: record.lastConnectedAt, }; - return record.desktopSsh ? { ...nextRecord, desktopSsh: record.desktopSsh } : nextRecord; + return { + ...nextRecord, + ...(record.desktopSsh ? { desktopSsh: record.desktopSsh } : {}), + ...(record.relayManaged ? { relayManaged: record.relayManaged } : {}), + }; } export function readBrowserClientSettings(): ClientSettings | null { @@ -145,6 +150,7 @@ export function writeBrowserSavedEnvironmentRegistry( createdAt: record.createdAt, lastConnectedAt: record.lastConnectedAt, ...(record.desktopSsh ? { desktopSsh: record.desktopSsh } : {}), + ...(record.relayManaged ? { relayManaged: record.relayManaged } : {}), bearerToken, } : toPersistedSavedEnvironmentRecord(record); @@ -171,6 +177,8 @@ export function writeBrowserSavedEnvironmentSecret( let found = false; writeBrowserSavedEnvironmentRegistryDocument({ version: document.version ?? 1, + // The persistence update is copy-on-write so storage subscribers observe a new document. + // oxlint-disable-next-line oxc/no-map-spread records: records.map((record) => { if (record.environmentId !== environmentId) { return record; @@ -185,7 +193,11 @@ export function writeBrowserSavedEnvironmentSecret( lastConnectedAt: record.lastConnectedAt, bearerToken: secret, }; - return record.desktopSsh ? { ...nextRecord, desktopSsh: record.desktopSsh } : nextRecord; + return { + ...nextRecord, + ...(record.desktopSsh ? { desktopSsh: record.desktopSsh } : {}), + ...(record.relayManaged ? { relayManaged: record.relayManaged } : {}), + }; }), }); return found; diff --git a/apps/web/src/cloud/desktopAuth.test.ts b/apps/web/src/cloud/desktopAuth.test.ts new file mode 100644 index 0000000000..171e5cb4f8 --- /dev/null +++ b/apps/web/src/cloud/desktopAuth.test.ts @@ -0,0 +1,24 @@ +import { describe, expect, it } from "vitest"; + +import { resolveDesktopCloudAuthOAuthOptions } from "./desktopAuth"; + +describe("resolveDesktopCloudAuthOAuthOptions", () => { + it("ignores absent social provider settings", () => { + expect( + resolveDesktopCloudAuthOAuthOptions({ + environment: { + userSettings: { + social: { + github: null, + google: { + strategy: "oauth_google", + enabled: true, + authenticatable: true, + }, + }, + }, + }, + }), + ).toEqual([{ strategy: "oauth_google", label: "Google" }]); + }); +}); diff --git a/apps/web/src/cloud/desktopAuth.ts b/apps/web/src/cloud/desktopAuth.ts new file mode 100644 index 0000000000..be7377be15 --- /dev/null +++ b/apps/web/src/cloud/desktopAuth.ts @@ -0,0 +1,116 @@ +export type DesktopCloudAuthOAuthStrategy = `oauth_${string}`; + +export interface DesktopCloudAuthOAuthOption { + readonly strategy: DesktopCloudAuthOAuthStrategy; + readonly label: string; +} + +interface ClerkOAuthProviderSetting { + readonly enabled?: unknown; + readonly authenticatable?: unknown; + readonly strategy?: unknown; + readonly name?: unknown; +} + +interface ClerkUserSettingsLike { + readonly authenticatableSocialStrategies?: unknown; + readonly social?: unknown; +} + +interface ClerkEnvironmentLike { + readonly userSettings?: ClerkUserSettingsLike; +} + +interface ClerkLike { + readonly __internal_environment?: ClerkEnvironmentLike; + readonly environment?: ClerkEnvironmentLike; +} + +const isClerkOAuthProviderSetting = (value: unknown): value is ClerkOAuthProviderSetting => + typeof value === "object" && value !== null; + +const OAUTH_LABELS: Readonly> = { + oauth_apple: "Apple", + oauth_discord: "Discord", + oauth_github: "GitHub", + oauth_gitlab: "GitLab", + oauth_google: "Google", + oauth_linear: "Linear", + oauth_microsoft: "Microsoft", + oauth_slack: "Slack", + oauth_x: "X", +}; + +export function isDesktopCloudAuthOAuthStrategy( + value: unknown, +): value is DesktopCloudAuthOAuthStrategy { + return typeof value === "string" && value.startsWith("oauth_"); +} + +export function getDesktopCloudAuthOAuthStrategyLabel( + strategy: DesktopCloudAuthOAuthStrategy, +): string { + const mapped = OAUTH_LABELS[strategy]; + if (mapped) return mapped; + return strategy + .replace(/^oauth_custom_/, "") + .replace(/^oauth_/, "") + .split("_") + .filter(Boolean) + .map((part) => part.charAt(0).toUpperCase() + part.slice(1)) + .join(" "); +} + +export function resolveDesktopCloudAuthOAuthOptions( + clerk: unknown, +): readonly DesktopCloudAuthOAuthOption[] { + const environment = + (clerk as ClerkLike | null | undefined)?.__internal_environment ?? + (clerk as ClerkLike | null | undefined)?.environment; + const userSettings = environment?.userSettings; + const strategies = userSettings?.authenticatableSocialStrategies; + if (Array.isArray(strategies)) { + return uniqueOptions( + strategies.filter(isDesktopCloudAuthOAuthStrategy).map((strategy) => ({ + strategy, + label: getDesktopCloudAuthOAuthStrategyLabel(strategy), + })), + ); + } + + const social = userSettings?.social; + if (!social || typeof social !== "object") { + return []; + } + + return uniqueOptions( + Object.values(social as Record) + .filter(isClerkOAuthProviderSetting) + .filter((provider) => provider.enabled !== false && provider.authenticatable !== false) + .map((provider) => { + const strategy = isDesktopCloudAuthOAuthStrategy(provider.strategy) + ? provider.strategy + : null; + if (!strategy) return null; + return { + strategy, + label: + typeof provider.name === "string" && provider.name.trim() + ? provider.name + : getDesktopCloudAuthOAuthStrategyLabel(strategy), + }; + }) + .filter((option): option is DesktopCloudAuthOAuthOption => option !== null), + ); +} + +function uniqueOptions( + options: readonly DesktopCloudAuthOAuthOption[], +): readonly DesktopCloudAuthOAuthOption[] { + const seen = new Set(); + return options.filter((option) => { + if (seen.has(option.strategy)) return false; + seen.add(option.strategy); + return true; + }); +} diff --git a/apps/web/src/cloud/desktopClerk.tsx b/apps/web/src/cloud/desktopClerk.tsx new file mode 100644 index 0000000000..25ed936a18 --- /dev/null +++ b/apps/web/src/cloud/desktopClerk.tsx @@ -0,0 +1,286 @@ +import { Clerk } from "@clerk/clerk-js"; +import { + buildClerkUIScriptAttributes, + clerkUIScriptUrl, + InternalClerkProvider, +} from "@clerk/react/internal"; +import type { ClerkProviderProps } from "@clerk/react"; +import React, { useEffect, useState } from "react"; + +type DesktopClerkUiCtor = NonNullable; + +interface ClerkFrontendApiRequest { + credentials?: RequestCredentials; + headers?: Headers; + url?: URL; +} + +interface ClerkFrontendApiResponse { + headers: Headers; + payload?: { + errors?: readonly { + code?: string; + }[]; + }; +} + +interface NativeRequestClerk { + readonly publishableKey?: string; + __internal_onBeforeRequest?: ( + listener: (request: ClerkFrontendApiRequest) => void | Promise, + ) => void; + __internal_onAfterResponse?: ( + listener: ( + request: ClerkFrontendApiRequest, + response?: ClerkFrontendApiResponse, + ) => void | Promise, + ) => void; + __unstable__onBeforeRequest?: ( + listener: (request: ClerkFrontendApiRequest) => void | Promise, + ) => void; + __unstable__onAfterResponse?: ( + listener: ( + request: ClerkFrontendApiRequest, + response?: ClerkFrontendApiResponse, + ) => void | Promise, + ) => void; +} + +interface DesktopClerkProviderProps { + readonly children: React.ReactNode; + readonly publishableKey: string; +} + +let desktopClerk: Clerk | null = null; +let desktopClerkFetchInstalled = false; +let desktopClerkUiLoad: Promise | null = null; + +const isNativeRequestClerk = (value: unknown): value is NativeRequestClerk => { + if (typeof value !== "object" || value === null) return false; + const candidate = value as { + __internal_onBeforeRequest?: unknown; + __internal_onAfterResponse?: unknown; + __unstable__onBeforeRequest?: unknown; + __unstable__onAfterResponse?: unknown; + }; + return ( + (typeof candidate.__internal_onBeforeRequest === "function" || + typeof candidate.__unstable__onBeforeRequest === "function") && + (typeof candidate.__internal_onAfterResponse === "function" || + typeof candidate.__unstable__onAfterResponse === "function") + ); +}; + +const getStoredClientJwt = (): Promise => + window.desktopBridge?.getCloudAuthToken() ?? Promise.resolve(null); + +const setStoredClientJwt = (token: string): Promise => + window.desktopBridge?.setCloudAuthToken(token) ?? Promise.resolve(false); + +const clearStoredClientJwt = (): Promise => + window.desktopBridge?.clearCloudAuthToken() ?? Promise.resolve(); + +const isClerkFrontendApiUrl = (url: URL): boolean => + url.protocol === "https:" && + (url.hostname.endsWith(".clerk.accounts.dev") || url.hostname.endsWith(".clerk.accounts.com")); + +const headersToRecord = (headers: Headers): Record => { + const record: Record = {}; + headers.forEach((value, key) => { + record[key] = value; + }); + return record; +}; + +function installDesktopClerkFetchProxy(): void { + if (desktopClerkFetchInstalled) return; + const bridge = window.desktopBridge; + if (!bridge) return; + + const browserFetch = window.fetch.bind(window); + window.fetch = async (input, init) => { + const request = new Request(input, init); + const url = new URL(request.url); + if (!isClerkFrontendApiUrl(url)) { + return browserFetch(input, init); + } + + const body = + request.method === "GET" || request.method === "HEAD" + ? undefined + : await request.clone().text(); + const result = await bridge.fetchCloudAuth({ + url: request.url, + method: request.method, + headers: headersToRecord(request.headers), + ...(body === undefined ? {} : { body }), + }); + + return new Response(result.body, { + status: result.status, + statusText: result.statusText, + headers: result.headers, + }); + }; + desktopClerkFetchInstalled = true; +} + +function loadDesktopClerkUi(publishableKey: string): Promise { + if (window.__internal_ClerkUICtor) { + return Promise.resolve(window.__internal_ClerkUICtor); + } + if (desktopClerkUiLoad) { + return desktopClerkUiLoad; + } + + const load = new Promise((resolve, reject) => { + const scriptUrl = clerkUIScriptUrl({ publishableKey }); + const existingScript = document.querySelector( + "script[data-clerk-ui-script]", + ); + + const resolveLoadedUi = () => { + const ClerkUI = window.__internal_ClerkUICtor; + if (ClerkUI) { + resolve(ClerkUI); + return true; + } + return false; + }; + if (resolveLoadedUi()) { + return; + } + + const script = existingScript ?? document.createElement("script"); + script.async = true; + script.crossOrigin = "anonymous"; + script.src = scriptUrl; + script.dataset.clerkUiScript = "true"; + const attributes = buildClerkUIScriptAttributes({ publishableKey }); + for (const [name, value] of Object.entries(attributes)) { + script.setAttribute(name, value); + } + + const timeoutId = window.setTimeout(() => { + reject(new Error("Timed out loading Clerk UI for desktop auth.")); + }, 15_000); + script.addEventListener("load", () => { + window.clearTimeout(timeoutId); + if (!resolveLoadedUi()) { + reject(new Error("Clerk UI loaded without exposing the UI constructor.")); + } + }); + script.addEventListener("error", () => { + window.clearTimeout(timeoutId); + reject(new Error("Failed to load Clerk UI for desktop auth.")); + }); + if (!existingScript) { + document.head.append(script); + } + }).catch((error: unknown) => { + desktopClerkUiLoad = null; + throw error; + }); + + desktopClerkUiLoad = load; + return load; +} + +function getDesktopClerkInstance(publishableKey: string): Clerk { + installDesktopClerkFetchProxy(); + + const hasKeyChanged = desktopClerk !== null && desktopClerk.publishableKey !== publishableKey; + if (hasKeyChanged) { + void clearStoredClientJwt(); + desktopClerk = null; + } + + if (desktopClerk !== null) { + return desktopClerk; + } + + const nextClerk = new Clerk(publishableKey); + if (!isNativeRequestClerk(nextClerk)) { + desktopClerk = nextClerk; + return nextClerk; + } + + const onBeforeRequest = + nextClerk.__internal_onBeforeRequest ?? nextClerk.__unstable__onBeforeRequest; + const onAfterResponse = + nextClerk.__internal_onAfterResponse ?? nextClerk.__unstable__onAfterResponse; + + onBeforeRequest(async (request) => { + request.credentials = "omit"; + request.url?.searchParams.append("_is_native", "1"); + const headers = new Headers(request.headers); + + const clientJwt = await getStoredClientJwt(); + headers.set("authorization", clientJwt ?? ""); + headers.set("x-mobile", "1"); + request.headers = headers; + }); + + onAfterResponse(async (_request, response) => { + const clientJwt = response?.headers.get("authorization"); + if (clientJwt) { + await setStoredClientJwt(clientJwt); + } + + const errorCode = response?.payload?.errors?.[0]?.code; + if (errorCode === "native_api_disabled") { + console.error( + "Clerk Native API is disabled. Enable Native applications in the Clerk dashboard for desktop sign-in.", + ); + } + }); + + desktopClerk = nextClerk; + return nextClerk; +} + +export function DesktopClerkProvider({ children, publishableKey }: DesktopClerkProviderProps) { + const [clerkUiCtor, setClerkUiCtor] = useState( + () => window.__internal_ClerkUICtor, + ); + const [clerkUiError, setClerkUiError] = useState(null); + + useEffect(() => { + let isCurrent = true; + void loadDesktopClerkUi(publishableKey).then( + (ClerkUI) => { + if (isCurrent) { + setClerkUiCtor(() => ClerkUI); + } + }, + (error: unknown) => { + if (isCurrent) { + setClerkUiError(error); + } + }, + ); + return () => { + isCurrent = false; + }; + }, [publishableKey]); + + if (!clerkUiCtor) { + if (clerkUiError) { + console.error("Failed to load Clerk UI for desktop auth.", clerkUiError); + } + return null; + } + + const clerk = getDesktopClerkInstance(publishableKey); + return ( + + {children} + + ); +} diff --git a/apps/web/src/cloud/dpop.test.ts b/apps/web/src/cloud/dpop.test.ts new file mode 100644 index 0000000000..bea52c9664 --- /dev/null +++ b/apps/web/src/cloud/dpop.test.ts @@ -0,0 +1,32 @@ +import { verifyDpopProof } from "@t3tools/shared/dpop"; +import * as Effect from "effect/Effect"; +import { describe, expect, it, vi } from "vitest"; + +import { browserCryptoLayer, createBrowserDpopProof, generateBrowserDpopKey } from "./dpop"; + +describe("browser DPoP proofs", () => { + it("signs relay resource proofs with an access-token hash", async () => { + vi.stubGlobal("indexedDB", undefined); + const issuedAt = Math.floor(Date.now() / 1_000); + const proofKey = await Effect.runPromise(generateBrowserDpopKey); + const proof = await Effect.runPromise( + createBrowserDpopProof({ + method: "POST", + url: "https://relay.example.test/v1/environments/env-1/connect?ignored=true", + accessToken: "relay-access-token", + proofKey, + }).pipe(Effect.provide(browserCryptoLayer)), + ); + + expect( + verifyDpopProof({ + proof: proof.proof, + method: "POST", + url: "https://relay.example.test/v1/environments/env-1/connect", + expectedThumbprint: proof.thumbprint, + expectedAccessToken: "relay-access-token", + nowEpochSeconds: issuedAt, + }), + ).toMatchObject({ ok: true }); + }); +}); diff --git a/apps/web/src/cloud/dpop.ts b/apps/web/src/cloud/dpop.ts new file mode 100644 index 0000000000..79b439f610 --- /dev/null +++ b/apps/web/src/cloud/dpop.ts @@ -0,0 +1,188 @@ +import { + computeDpopAccessTokenHash, + computeDpopJwkThumbprint, + DpopPublicJwk, +} from "@t3tools/shared/dpop"; +import * as Crypto from "effect/Crypto"; +import * as Data from "effect/Data"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import * as Schema from "effect/Schema"; +import { importJWK, SignJWT, type JWK } from "jose"; + +export interface BrowserDpopKey { + readonly privateKey: CryptoKey; + readonly publicJwk: DpopPublicJwk; + readonly thumbprint: string; +} + +export class BrowserDpopError extends Data.TaggedError("BrowserDpopError")<{ + readonly message: string; + readonly cause?: unknown; +}> {} + +const DPOP_DATABASE_NAME = "t3code:cloud-auth"; +const DPOP_DATABASE_VERSION = 1; +const DPOP_KEY_STORE_NAME = "keys"; +const DPOP_KEY_ID = "relay-dpop-proof-key"; +const decodeDpopPublicJwk = Schema.decodeUnknownEffect(DpopPublicJwk); + +export const browserCryptoLayer = Layer.succeed( + Crypto.Crypto, + Crypto.make({ + randomBytes: (size) => globalThis.crypto.getRandomValues(new Uint8Array(size)), + digest: (algorithm, data) => + Effect.promise(async () => { + const input = new Uint8Array(data.length); + input.set(data); + return new Uint8Array(await globalThis.crypto.subtle.digest(algorithm, input.buffer)); + }), + }), +); + +function dpopError(message: string, cause?: unknown) { + return new BrowserDpopError({ message, ...(cause === undefined ? {} : { cause }) }); +} + +function openDpopDatabase(): Effect.Effect { + return Effect.callback((resume) => { + const request = indexedDB.open(DPOP_DATABASE_NAME, DPOP_DATABASE_VERSION); + request.addEventListener("error", () => + resume( + Effect.fail(dpopError("Could not open DPoP key storage.", request.error ?? undefined)), + ), + ); + request.addEventListener("upgradeneeded", () => { + if (!request.result.objectStoreNames.contains(DPOP_KEY_STORE_NAME)) { + request.result.createObjectStore(DPOP_KEY_STORE_NAME); + } + }); + request.addEventListener("success", () => resume(Effect.succeed(request.result))); + }); +} + +export function readStoredBrowserDpopKey(): Effect.Effect { + if (typeof indexedDB === "undefined") { + return Effect.succeed(null); + } + return Effect.acquireUseRelease( + openDpopDatabase(), + (database) => + Effect.callback((resume) => { + const request = database + .transaction(DPOP_KEY_STORE_NAME, "readonly") + .objectStore(DPOP_KEY_STORE_NAME) + .get(DPOP_KEY_ID); + request.addEventListener("error", () => + resume(Effect.fail(dpopError("Could not read DPoP key.", request.error ?? undefined))), + ); + request.addEventListener("success", () => + resume(Effect.succeed((request.result as BrowserDpopKey | undefined) ?? null)), + ); + }), + (database) => Effect.sync(() => database.close()), + ); +} + +export function writeStoredBrowserDpopKey( + key: BrowserDpopKey, +): Effect.Effect { + if (typeof indexedDB === "undefined") { + return Effect.void; + } + return Effect.acquireUseRelease( + openDpopDatabase(), + (database) => + Effect.callback((resume) => { + const transaction = database.transaction(DPOP_KEY_STORE_NAME, "readwrite"); + transaction.addEventListener("error", () => + resume( + Effect.fail(dpopError("Could not write DPoP key.", transaction.error ?? undefined)), + ), + ); + transaction.addEventListener("complete", () => resume(Effect.void)); + transaction.objectStore(DPOP_KEY_STORE_NAME).put(key, DPOP_KEY_ID); + }), + (database) => Effect.sync(() => database.close()), + ); +} + +export const generateBrowserDpopKey: Effect.Effect = Effect.gen( + function* () { + const generated = yield* Effect.tryPromise({ + try: () => + crypto.subtle.generateKey({ name: "ECDSA", namedCurve: "P-256" }, true, [ + "sign", + "verify", + ]) as Promise, + catch: (cause) => dpopError("Could not generate DPoP proof key.", cause), + }); + const privateJwk = yield* Effect.tryPromise({ + try: () => crypto.subtle.exportKey("jwk", generated.privateKey), + catch: (cause) => dpopError("Could not export DPoP private key.", cause), + }); + const publicJwk = yield* Effect.tryPromise({ + try: () => crypto.subtle.exportKey("jwk", generated.publicKey), + catch: (cause) => dpopError("Could not export DPoP public key.", cause), + }).pipe( + Effect.flatMap((jwk) => decodeDpopPublicJwk(jwk)), + Effect.mapError((cause) => + cause instanceof BrowserDpopError + ? cause + : dpopError("Generated DPoP public key is invalid.", cause), + ), + ); + const privateKey = yield* Effect.tryPromise({ + try: () => + importJWK(privateJwk as JWK, "ES256", { extractable: false }) as Promise, + catch: (cause) => dpopError("Could not import DPoP private key.", cause), + }); + return { + privateKey, + publicJwk, + thumbprint: computeDpopJwkThumbprint(publicJwk), + }; + }, +); + +export function createBrowserDpopProof(input: { + readonly method: string; + readonly url: string; + readonly accessToken?: string; + readonly proofKey: BrowserDpopKey; +}): Effect.Effect< + { readonly proof: string; readonly thumbprint: string }, + BrowserDpopError, + Crypto.Crypto +> { + return Effect.gen(function* () { + const normalizedUrl = yield* Effect.try({ + try: () => new URL(input.url), + catch: (cause) => dpopError("Could not normalize DPoP proof URL.", cause), + }); + normalizedUrl.search = ""; + normalizedUrl.hash = ""; + const jti = yield* Crypto.Crypto.pipe( + Effect.flatMap((crypto) => crypto.randomUUIDv4), + Effect.mapError((cause) => dpopError("Could not generate DPoP proof identifier.", cause)), + ); + const proof = yield* Effect.tryPromise({ + try: () => + new SignJWT({ + htm: input.method.toUpperCase(), + htu: normalizedUrl.toString(), + jti, + ...(input.accessToken ? { ath: computeDpopAccessTokenHash(input.accessToken) } : {}), + }) + .setProtectedHeader({ + typ: "dpop+jwt", + alg: "ES256", + jwk: input.proofKey.publicJwk, + }) + .setIssuedAt() + .sign(input.proofKey.privateKey), + catch: (cause) => dpopError("Could not sign DPoP proof.", cause), + }); + return { proof, thumbprint: input.proofKey.thumbprint }; + }); +} diff --git a/apps/web/src/cloud/linkEnvironment.test.ts b/apps/web/src/cloud/linkEnvironment.test.ts new file mode 100644 index 0000000000..d6b2d98eba --- /dev/null +++ b/apps/web/src/cloud/linkEnvironment.test.ts @@ -0,0 +1,797 @@ +import { EnvironmentId } from "@t3tools/contracts"; +import { RelayWebClientId } from "@t3tools/contracts/relay"; +import { beforeEach, vi } from "vitest"; +import { describe, expect, it } from "@effect/vitest"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import { HttpClient } from "effect/unstable/http"; +import { + managedRelayClientLayer, + ManagedRelayClient, + ManagedRelayDpopSigner, + remoteHttpClientLayer, +} from "@t3tools/client-runtime"; + +import type { SavedEnvironmentRecord } from "../environments/runtime"; +import { + connectManagedCloudEnvironment, + linkEnvironmentToCloud, + linkPrimaryEnvironmentToCloud, + listManagedCloudEnvironments, + normalizeRelayBaseUrl, + readPrimaryCloudLinkState, + unlinkPrimaryEnvironmentFromCloud, +} from "./linkEnvironment"; +import { + readPrimaryEnvironmentDescriptor, + readPrimaryEnvironmentTarget, + resolvePrimaryEnvironmentHttpUrl, +} from "../environments/primary"; + +const getSavedEnvironmentSecretMock = vi.fn(); + +const createProofMock = vi.fn( + (_input: { readonly method: string; readonly url: string; readonly accessToken?: string }) => + Effect.succeed("web-dpop-proof"), +); +const testDpopSignerLayer = Layer.succeed( + ManagedRelayDpopSigner, + ManagedRelayDpopSigner.of({ + thumbprint: Effect.succeed("web-thumbprint"), + createProof: (input) => createProofMock(input), + }), +); + +function cloudClientLayer() { + const httpClientLayer = remoteHttpClientLayer(globalThis.fetch); + return Layer.mergeAll( + httpClientLayer, + managedRelayClientLayer({ + relayUrl: "https://relay.example.test", + clientId: RelayWebClientId, + }).pipe(Layer.provideMerge(testDpopSignerLayer), Layer.provide(httpClientLayer)), + ); +} + +const withCloudServices = ( + effect: Effect.Effect, +) => effect.pipe(Effect.provide(cloudClientLayer())); + +vi.mock("../localApi", () => ({ + ensureLocalApi: () => ({ + persistence: { + getSavedEnvironmentSecret: getSavedEnvironmentSecretMock, + }, + }), +})); + +vi.mock("../environments/primary", () => ({ + readPrimaryEnvironmentDescriptor: vi.fn(() => null), + readPrimaryEnvironmentTarget: vi.fn(() => null), + resolvePrimaryEnvironmentHttpUrl: vi.fn((path: string) => `http://127.0.0.1:3000${path}`), +})); + +const savedEnvironment: SavedEnvironmentRecord = { + environmentId: EnvironmentId.make("env-1"), + label: "Desktop", + httpBaseUrl: "http://127.0.0.1:3000", + wsBaseUrl: "ws://127.0.0.1:3000", + createdAt: "2026-05-25T00:00:00.000Z", + lastConnectedAt: null, +}; + +function validProof() { + return "signed-environment-link-jwt"; +} + +function validChallenge() { + return { + challenge: "link-challenge", + expiresAt: "2026-05-25T00:05:00.000Z", + }; +} + +function requestBodyText(body: BodyInit | null | undefined): string { + return body instanceof Uint8Array ? new TextDecoder().decode(body) : String(body ?? ""); +} + +describe("web cloud link environment client", () => { + beforeEach(() => { + vi.restoreAllMocks(); + createProofMock.mockClear(); + vi.stubEnv("VITE_T3_RELAY_URL", "https://relay.example.test"); + getSavedEnvironmentSecretMock.mockResolvedValue("local-bearer"); + vi.mocked(readPrimaryEnvironmentDescriptor).mockReturnValue(null); + vi.mocked(readPrimaryEnvironmentTarget).mockReturnValue(null); + vi.mocked(resolvePrimaryEnvironmentHttpUrl).mockImplementation( + (path: string) => `http://127.0.0.1:3000${path}`, + ); + }); + + it("normalizes configured relay base URLs before building relay requests", () => { + expect(normalizeRelayBaseUrl(" https://relay.example.test/// ")).toBe( + "https://relay.example.test", + ); + expect(normalizeRelayBaseUrl(" ")).toBeNull(); + }); + + it.effect("lists relay-managed environments for hosted and served web clients", () => + Effect.gen(function* () { + const fetchMock = vi.fn().mockResolvedValueOnce( + Response.json({ + environments: [ + { + environmentId: "env-1", + label: "Managed desktop", + endpoint: { + httpBaseUrl: "https://managed.example.test", + wsBaseUrl: "wss://managed.example.test", + providerKind: "cloudflare_tunnel", + }, + linkedAt: "2026-05-25T00:00:00.000Z", + }, + ], + }), + ); + vi.stubGlobal("fetch", fetchMock); + + const environments = yield* withCloudServices( + listManagedCloudEnvironments({ clerkToken: "clerk-token" }), + ); + expect(environments).toHaveLength(1); + expect(String(fetchMock.mock.calls[0]?.[0])).toBe( + "https://relay.example.test/v1/environments", + ); + expect(fetchMock.mock.calls[0]?.[1]?.headers.authorization).toBe("Bearer clerk-token"); + expect(fetchMock.mock.calls[0]?.[1]?.credentials).not.toBe("include"); + }), + ); + + it.effect("connects web clients to managed environments with a tunnel-only DPoP token", () => + Effect.gen(function* () { + const environment = { + environmentId: EnvironmentId.make("env-1"), + label: "Managed desktop", + endpoint: { + httpBaseUrl: "https://managed.example.test", + wsBaseUrl: "wss://managed.example.test", + providerKind: "cloudflare_tunnel" as const, + }, + linkedAt: "2026-05-25T00:00:00.000Z", + }; + const fetchMock = vi + .fn() + .mockResolvedValueOnce( + Response.json({ + access_token: "relay-access-token", + issued_token_type: "urn:ietf:params:oauth:token-type:access_token", + token_type: "DPoP", + expires_in: 300, + scope: "environment:connect", + }), + ) + .mockResolvedValueOnce( + Response.json({ + environmentId: "env-1", + endpoint: environment.endpoint, + credential: "environment-bootstrap", + expiresAt: "2026-05-25T00:05:00.000Z", + }), + ) + .mockResolvedValueOnce( + Response.json({ + environmentId: "env-1", + label: "Managed desktop", + platform: { os: "darwin", arch: "arm64" }, + serverVersion: "0.0.0-test", + capabilities: { repositoryIdentity: true }, + }), + ) + .mockResolvedValueOnce( + Response.json({ + access_token: "environment-access-token", + issued_token_type: "urn:ietf:params:oauth:token-type:access_token", + token_type: "DPoP", + expires_in: 3600, + scope: "orchestration:read orchestration:operate terminal:operate review:write", + }), + ); + vi.stubGlobal("fetch", fetchMock); + + const connection = yield* withCloudServices( + connectManagedCloudEnvironment({ clerkToken: "clerk-token", environment }), + ); + expect(connection).toMatchObject({ + environmentId: "env-1", + accessToken: "environment-access-token", + }); + + const tokenBody = requestBodyText(fetchMock.mock.calls[0]?.[1]?.body); + expect(new URLSearchParams(tokenBody).get("client_id")).toBe("t3-web"); + expect(new URLSearchParams(tokenBody).get("scope")).toBe("environment:connect"); + expect(fetchMock.mock.calls[1]?.[1]?.headers.authorization).toBe("DPoP relay-access-token"); + expect(fetchMock.mock.calls[1]?.[1]?.headers.dpop).toBe("web-dpop-proof"); + expect(createProofMock).toHaveBeenCalledWith({ + method: "POST", + url: "https://managed.example.test/oauth/token", + }); + }), + ); + + it.effect("rejects a stored managed connection for another relay origin", () => + Effect.gen(function* () { + const environment = { + environmentId: EnvironmentId.make("env-1"), + label: "Managed desktop", + endpoint: { + httpBaseUrl: "https://managed.example.test", + wsBaseUrl: "wss://managed.example.test", + providerKind: "cloudflare_tunnel" as const, + }, + linkedAt: "2026-05-25T00:00:00.000Z", + }; + + const error = yield* withCloudServices( + connectManagedCloudEnvironment({ + clerkToken: "clerk-token", + environment, + relayUrl: "https://old-relay.example.test", + }), + ).pipe(Effect.flip); + expect(error).toMatchObject({ + message: "The saved environment is linked through a different configured relay.", + }); + }), + ); + + it.effect("rejects malformed local environment link proofs", () => + Effect.gen(function* () { + vi.stubGlobal( + "fetch", + vi + .fn() + .mockResolvedValueOnce(Response.json(validChallenge())) + .mockResolvedValueOnce( + Response.json({ + payload: { + environmentId: "env-1", + }, + signature: "signature-1", + }), + ), + ); + + const error = yield* withCloudServices( + linkEnvironmentToCloud({ + environment: savedEnvironment, + clerkToken: "clerk-token", + }), + ).pipe(Effect.flip); + expect(error).toMatchObject({ + _tag: "CloudEnvironmentLinkError", + message: "Could not obtain environment link proof.", + }); + }), + ); + + it.effect("preserves typed local environment failures while obtaining a link proof", () => + Effect.gen(function* () { + vi.stubGlobal( + "fetch", + vi + .fn() + .mockResolvedValueOnce(Response.json(validChallenge())) + .mockResolvedValueOnce( + Response.json( + { + _tag: "EnvironmentHttpUnauthorizedError", + message: "Invalid environment bearer session.", + }, + { status: 401 }, + ), + ), + ); + + const error = yield* withCloudServices( + linkEnvironmentToCloud({ + environment: savedEnvironment, + clerkToken: "clerk-token", + }), + ).pipe(Effect.flip); + expect(error._tag).toBe("CloudEnvironmentLinkError"); + expect(error.message).toBe( + "Could not obtain environment link proof: Invalid environment bearer session.", + ); + }), + ); + + it.effect("rejects malformed relay environment link responses", () => + Effect.gen(function* () { + vi.stubGlobal( + "fetch", + vi + .fn() + .mockResolvedValueOnce(Response.json(validChallenge())) + .mockResolvedValueOnce(Response.json(validProof())) + .mockResolvedValueOnce( + Response.json({ + ok: true, + environmentId: "env-1", + endpoint: { + httpBaseUrl: "https://desktop.example.test", + wsBaseUrl: "wss://desktop.example.test", + providerKind: "cloudflare_tunnel", + }, + endpointRuntime: null, + relayIssuer: "https://issuer.example.test", + cloudUserId: "user_123", + environmentCredential: "", + cloudMintPublicKey: "cloud-mint-public-key", + }), + ), + ); + + const error = yield* withCloudServices( + linkEnvironmentToCloud({ + environment: savedEnvironment, + clerkToken: "clerk-token", + }), + ).pipe(Effect.flip); + expect(error).toMatchObject({ + _tag: "CloudEnvironmentLinkError", + message: "https://relay.example.test/v1/client/environment-links failed", + }); + }), + ); + + it.effect( + "links the primary local environment through the relay using the owner cookie session", + () => + Effect.gen(function* () { + vi.mocked(readPrimaryEnvironmentDescriptor).mockReturnValue({ + environmentId: EnvironmentId.make("env-1"), + label: "Desktop", + platform: { os: "darwin", arch: "arm64" }, + serverVersion: "0.0.0-test", + capabilities: { repositoryIdentity: true }, + }); + vi.mocked(readPrimaryEnvironmentTarget).mockReturnValue({ + source: "desktop-managed", + target: { + httpBaseUrl: "http://127.0.0.1:3000", + wsBaseUrl: "ws://127.0.0.1:3000", + }, + }); + vi.mocked(resolvePrimaryEnvironmentHttpUrl).mockImplementation( + (path: string) => `http://127.0.0.1:3000${path}`, + ); + + const fetchMock = vi + .fn() + .mockResolvedValueOnce(Response.json(validChallenge())) + .mockResolvedValueOnce(Response.json(validProof())) + .mockResolvedValueOnce( + Response.json({ + ok: true, + environmentId: "env-1", + endpoint: { + httpBaseUrl: "https://desktop.example.test", + wsBaseUrl: "wss://desktop.example.test", + providerKind: "cloudflare_tunnel", + }, + endpointRuntime: { + providerKind: "cloudflare_tunnel", + connectorToken: "connector-token", + tunnelId: "tunnel-id", + tunnelName: "tunnel-name", + }, + relayIssuer: "https://issuer.example.test", + cloudUserId: "user_123", + environmentCredential: "t3env_test_credential", + cloudMintPublicKey: "cloud-mint-public-key", + }), + ) + .mockResolvedValueOnce( + Response.json({ ok: true, endpointRuntimeStatus: { status: "configured" } }), + ); + vi.stubGlobal("fetch", fetchMock); + + yield* withCloudServices( + linkPrimaryEnvironmentToCloud({ + clerkToken: "clerk-token", + }), + ); + + expect(String(fetchMock.mock.calls[0]?.[0])).toBe( + "https://relay.example.test/v1/client/environment-link-challenges", + ); + expect(fetchMock.mock.calls[0]?.[1]?.method).toBe("POST"); + expect(fetchMock.mock.calls[0]?.[1]?.headers.authorization).toBe("Bearer clerk-token"); + expect(fetchMock.mock.calls[0]?.[1]?.credentials).not.toBe("include"); + + expect(String(fetchMock.mock.calls[1]?.[0])).toBe( + "http://127.0.0.1:3000/api/cloud/link-proof", + ); + expect(fetchMock.mock.calls[1]?.[1]).toMatchObject({ + method: "POST", + credentials: "include", + headers: expect.objectContaining({ + "content-type": "application/json", + }), + }); + // @effect-diagnostics-next-line preferSchemaOverJson:off + expect(JSON.parse(requestBodyText(fetchMock.mock.calls[1]?.[1]?.body))).toMatchObject({ + challenge: "link-challenge", + endpoint: { + httpBaseUrl: "http://127.0.0.1:3000", + wsBaseUrl: "ws://127.0.0.1:3000", + providerKind: "cloudflare_tunnel", + }, + origin: { + localHttpHost: "127.0.0.1", + localHttpPort: 3000, + }, + }); + + expect(String(fetchMock.mock.calls[2]?.[0])).toBe( + "https://relay.example.test/v1/client/environment-links", + ); + expect(fetchMock.mock.calls[2]?.[1]?.method).toBe("POST"); + expect(fetchMock.mock.calls[2]?.[1]?.headers.authorization).toBe("Bearer clerk-token"); + expect(fetchMock.mock.calls[2]?.[1]?.credentials).not.toBe("include"); + expect(fetchMock.mock.calls[2]?.[1]?.headers["content-type"]).toBe("application/json"); + // @effect-diagnostics-next-line preferSchemaOverJson:off + expect(JSON.parse(requestBodyText(fetchMock.mock.calls[2]?.[1]?.body))).toMatchObject({ + proof: validProof(), + notificationsEnabled: true, + liveActivitiesEnabled: true, + managedTunnelsEnabled: true, + }); + + expect(String(fetchMock.mock.calls[3]?.[0])).toBe( + "http://127.0.0.1:3000/api/cloud/relay-config", + ); + expect(fetchMock.mock.calls[3]?.[1]).toMatchObject({ + method: "POST", + credentials: "include", + headers: expect.objectContaining({ + "content-type": "application/json", + }), + }); + // @effect-diagnostics-next-line preferSchemaOverJson:off + expect(JSON.parse(requestBodyText(fetchMock.mock.calls[3]?.[1]?.body))).toMatchObject({ + relayUrl: "https://relay.example.test", + relayIssuer: "https://issuer.example.test", + cloudUserId: "user_123", + environmentCredential: "t3env_test_credential", + cloudMintPublicKey: "cloud-mint-public-key", + endpointRuntime: { + providerKind: "cloudflare_tunnel", + connectorToken: "connector-token", + tunnelId: "tunnel-id", + tunnelName: "tunnel-name", + }, + }); + }), + ); + + it.effect("reads the primary local cloud link state with the owner cookie session", () => + Effect.gen(function* () { + vi.mocked(readPrimaryEnvironmentDescriptor).mockReturnValue({ + environmentId: EnvironmentId.make("env-1"), + label: "Desktop", + platform: { os: "darwin", arch: "arm64" }, + serverVersion: "0.0.0-test", + capabilities: { repositoryIdentity: true }, + }); + vi.mocked(readPrimaryEnvironmentTarget).mockReturnValue({ + source: "desktop-managed", + target: { + httpBaseUrl: "http://127.0.0.1:3000", + wsBaseUrl: "ws://127.0.0.1:3000", + }, + }); + const fetchMock = vi.fn().mockResolvedValueOnce( + Response.json({ + linked: true, + cloudUserId: "user_123", + relayUrl: "https://relay.example.test", + relayIssuer: "https://issuer.example.test", + }), + ); + vi.stubGlobal("fetch", fetchMock); + + const state = yield* withCloudServices(readPrimaryCloudLinkState()); + expect(state).toEqual({ + linked: true, + cloudUserId: "user_123", + relayUrl: "https://relay.example.test", + relayIssuer: "https://issuer.example.test", + }); + expect(String(fetchMock.mock.calls[0]?.[0])).toBe( + "http://127.0.0.1:3000/api/cloud/link-state", + ); + expect(fetchMock.mock.calls[0]?.[1]).toMatchObject({ + method: "GET", + credentials: "include", + }); + }), + ); + + it.effect("revokes the primary cloud link before clearing local relay credentials", () => + Effect.gen(function* () { + vi.mocked(readPrimaryEnvironmentDescriptor).mockReturnValue({ + environmentId: EnvironmentId.make("env-1"), + label: "Desktop", + platform: { os: "darwin", arch: "arm64" }, + serverVersion: "0.0.0-test", + capabilities: { repositoryIdentity: true }, + }); + vi.mocked(readPrimaryEnvironmentTarget).mockReturnValue({ + source: "desktop-managed", + target: { + httpBaseUrl: "http://127.0.0.1:3000", + wsBaseUrl: "ws://127.0.0.1:3000", + }, + }); + const fetchMock = vi + .fn() + .mockResolvedValueOnce(Response.json({ ok: true })) + .mockResolvedValueOnce( + Response.json({ ok: true, endpointRuntimeStatus: { status: "disabled" } }), + ); + vi.stubGlobal("fetch", fetchMock); + + yield* withCloudServices( + unlinkPrimaryEnvironmentFromCloud({ + clerkToken: "clerk-token", + }), + ); + + expect(String(fetchMock.mock.calls[0]?.[0])).toBe( + "https://relay.example.test/v1/client/environment-links/env-1", + ); + expect(fetchMock.mock.calls[0]?.[1]?.method).toBe("DELETE"); + expect(fetchMock.mock.calls[0]?.[1]?.headers.authorization).toBe("Bearer clerk-token"); + expect(String(fetchMock.mock.calls[1]?.[0])).toBe("http://127.0.0.1:3000/api/cloud/unlink"); + expect(fetchMock.mock.calls[1]?.[1]).toMatchObject({ + method: "POST", + credentials: "include", + }); + }), + ); + + it.effect("still clears local relay credentials when relay revocation fails", () => + Effect.gen(function* () { + vi.mocked(readPrimaryEnvironmentDescriptor).mockReturnValue({ + environmentId: EnvironmentId.make("env-1"), + label: "Desktop", + platform: { os: "darwin", arch: "arm64" }, + serverVersion: "0.0.0-test", + capabilities: { repositoryIdentity: true }, + }); + vi.mocked(readPrimaryEnvironmentTarget).mockReturnValue({ + source: "desktop-managed", + target: { + httpBaseUrl: "http://127.0.0.1:3000", + wsBaseUrl: "ws://127.0.0.1:3000", + }, + }); + const fetchMock = vi + .fn() + .mockResolvedValueOnce(Response.json({ error: "unavailable" }, { status: 503 })) + .mockResolvedValueOnce( + Response.json({ ok: true, endpointRuntimeStatus: { status: "disabled" } }), + ); + vi.stubGlobal("fetch", fetchMock); + + yield* withCloudServices( + unlinkPrimaryEnvironmentFromCloud({ + clerkToken: "clerk-token", + }), + ); + + expect(fetchMock).toHaveBeenCalledTimes(2); + expect(String(fetchMock.mock.calls[1]?.[0])).toBe("http://127.0.0.1:3000/api/cloud/unlink"); + expect(fetchMock.mock.calls[1]?.[1]).toMatchObject({ + method: "POST", + credentials: "include", + }); + }), + ); + + it.effect("rejects primary environment linking when the local environment is not ready", () => + Effect.gen(function* () { + vi.stubGlobal("fetch", vi.fn()); + + const error = yield* withCloudServices( + linkPrimaryEnvironmentToCloud({ + clerkToken: "clerk-token", + }), + ).pipe(Effect.flip); + expect(error).toMatchObject({ + _tag: "CloudEnvironmentLinkError", + message: "Local environment is not ready yet.", + }); + expect(fetch).not.toHaveBeenCalled(); + }), + ); + + it.effect("preserves relay transport failures while linking environments", () => + Effect.gen(function* () { + vi.stubGlobal( + "fetch", + vi + .fn() + .mockResolvedValueOnce(Response.json(validChallenge())) + .mockResolvedValueOnce(Response.json(validProof())) + .mockResolvedValueOnce(Response.json({ error: "unavailable" }, { status: 503 })), + ); + + const error = yield* withCloudServices( + linkEnvironmentToCloud({ + environment: savedEnvironment, + clerkToken: "clerk-token", + }), + ).pipe(Effect.flip); + expect(error).toMatchObject({ + _tag: "CloudEnvironmentLinkError", + message: "https://relay.example.test/v1/client/environment-links failed", + }); + }), + ); + + it.effect("preserves typed relay error bodies while linking environments", () => + Effect.gen(function* () { + vi.stubGlobal( + "fetch", + vi + .fn() + .mockResolvedValueOnce(Response.json(validChallenge())) + .mockResolvedValueOnce(Response.json(validProof())) + .mockResolvedValueOnce( + Response.json( + { + _tag: "RelayEnvironmentLinkProofInvalidError", + code: "environment_link_proof_invalid", + reason: "origin_not_allowed", + traceId: "trace-test", + }, + { status: 400 }, + ), + ), + ); + + const error = yield* withCloudServices( + linkEnvironmentToCloud({ + environment: savedEnvironment, + clerkToken: "clerk-token", + }), + ).pipe(Effect.flip); + expect(error).toMatchObject({ + _tag: "CloudEnvironmentLinkError", + message: + "https://relay.example.test/v1/client/environment-links failed: Relay rejected the environment link proof (origin_not_allowed).", + }); + }), + ); + + it.effect("rejects relay credentials for a different environment", () => + Effect.gen(function* () { + const fetchMock = vi + .fn() + .mockResolvedValueOnce(Response.json(validChallenge())) + .mockResolvedValueOnce(Response.json(validProof())) + .mockResolvedValueOnce( + Response.json({ + ok: true, + environmentId: "env-2", + endpoint: { + httpBaseUrl: "https://desktop.example.test", + wsBaseUrl: "wss://desktop.example.test", + providerKind: "cloudflare_tunnel", + }, + endpointRuntime: null, + relayIssuer: "https://issuer.example.test", + cloudUserId: "user_123", + environmentCredential: "t3env_test_credential", + cloudMintPublicKey: "cloud-mint-public-key", + }), + ); + vi.stubGlobal("fetch", fetchMock); + + const error = yield* withCloudServices( + linkEnvironmentToCloud({ + environment: savedEnvironment, + clerkToken: "clerk-token", + }), + ).pipe(Effect.flip); + expect(error).toMatchObject({ + _tag: "CloudEnvironmentLinkError", + message: "Relay returned credentials for a different environment.", + }); + expect(fetchMock).toHaveBeenCalledTimes(3); + }), + ); + + it.effect("rejects relay credentials for a different managed endpoint provider", () => + Effect.gen(function* () { + const fetchMock = vi + .fn() + .mockResolvedValueOnce(Response.json(validChallenge())) + .mockResolvedValueOnce(Response.json(validProof())) + .mockResolvedValueOnce( + Response.json({ + ok: true, + environmentId: "env-1", + endpoint: { + httpBaseUrl: "https://desktop.example.test", + wsBaseUrl: "wss://desktop.example.test", + providerKind: "manual", + }, + endpointRuntime: null, + relayIssuer: "https://issuer.example.test", + cloudUserId: "user_123", + environmentCredential: "t3env_test_credential", + cloudMintPublicKey: "cloud-mint-public-key", + }), + ); + vi.stubGlobal("fetch", fetchMock); + + const error = yield* withCloudServices( + linkEnvironmentToCloud({ + environment: savedEnvironment, + clerkToken: "clerk-token", + }), + ).pipe(Effect.flip); + expect(error).toMatchObject({ + _tag: "CloudEnvironmentLinkError", + message: "Relay returned credentials for a different endpoint provider.", + }); + expect(fetchMock).toHaveBeenCalledTimes(3); + }), + ); + + it.effect("passes the relay issuer from the link response into local relay config", () => + Effect.gen(function* () { + const fetchMock = vi + .fn() + .mockResolvedValueOnce(Response.json(validChallenge())) + .mockResolvedValueOnce(Response.json(validProof())) + .mockResolvedValueOnce( + Response.json({ + ok: true, + environmentId: "env-1", + endpoint: { + httpBaseUrl: "https://desktop.example.test", + wsBaseUrl: "wss://desktop.example.test", + providerKind: "cloudflare_tunnel", + }, + endpointRuntime: null, + relayIssuer: "https://issuer.example.test", + cloudUserId: "user_123", + environmentCredential: "t3env_test_credential", + cloudMintPublicKey: "cloud-mint-public-key", + }), + ) + .mockResolvedValueOnce( + Response.json({ ok: true, endpointRuntimeStatus: { status: "disabled" } }), + ); + vi.stubGlobal("fetch", fetchMock); + + yield* withCloudServices( + linkEnvironmentToCloud({ + environment: savedEnvironment, + clerkToken: "clerk-token", + }), + ); + + // @effect-diagnostics-next-line preferSchemaOverJson:off + expect(JSON.parse(requestBodyText(fetchMock.mock.calls[3]?.[1]?.body))).toMatchObject({ + relayUrl: "https://relay.example.test", + relayIssuer: "https://issuer.example.test", + cloudUserId: "user_123", + }); + }), + ); +}); diff --git a/apps/web/src/cloud/linkEnvironment.ts b/apps/web/src/cloud/linkEnvironment.ts new file mode 100644 index 0000000000..d4ab09c691 --- /dev/null +++ b/apps/web/src/cloud/linkEnvironment.ts @@ -0,0 +1,605 @@ +import * as Data from "effect/Data"; +import * as Effect from "effect/Effect"; +import * as Schema from "effect/Schema"; +import { FetchHttpClient, HttpClient } from "effect/unstable/http"; +import { + EnvironmentCloudEndpointUnavailableError, + type EnvironmentCloudLinkStateResult, + EnvironmentHttpBadRequestError, + EnvironmentHttpConflictError, + EnvironmentHttpForbiddenError, + EnvironmentHttpInternalServerError, + EnvironmentHttpUnauthorizedError, + EnvironmentId, +} from "@t3tools/contracts"; +import { + RelayEnvironmentConnectScope, + type RelayEnvironmentLinkResponse, + RelayProtectedError, + type RelayClientEnvironmentRecord, + type RelayProtectedError as RelayProtectedErrorType, + type RelayManagedEndpointProviderKind, +} from "@t3tools/contracts/relay"; +import { + exchangeRemoteDpopAccessToken, + fetchRemoteEnvironmentDescriptor, + makeEnvironmentHttpApiClient, + ManagedRelayClient, + ManagedRelayDpopSigner, +} from "@t3tools/client-runtime"; + +import { ensureLocalApi } from "../localApi"; +import type { SavedEnvironmentRecord } from "../environments/runtime"; +import { + readPrimaryEnvironmentDescriptor, + readPrimaryEnvironmentTarget, + resolvePrimaryEnvironmentHttpUrl, +} from "../environments/primary"; + +export function normalizeRelayBaseUrl(value: string | null | undefined): string | null { + const trimmed = value?.trim(); + if (!trimmed) { + return null; + } + return trimmed.replace(/\/+$/g, ""); +} + +function relayUrl(): string | null { + return normalizeRelayBaseUrl(import.meta.env.VITE_T3_RELAY_URL as string | undefined); +} + +export class CloudEnvironmentLinkError extends Data.TaggedError("CloudEnvironmentLinkError")<{ + readonly message: string; + readonly cause?: unknown; +}> {} + +const isRelayProtectedError = Schema.is(RelayProtectedError); +const isEnvironmentCloudApiError = Schema.is( + Schema.Union([ + EnvironmentHttpBadRequestError, + EnvironmentHttpUnauthorizedError, + EnvironmentHttpForbiddenError, + EnvironmentHttpConflictError, + EnvironmentHttpInternalServerError, + EnvironmentCloudEndpointUnavailableError, + ]), +); + +function relayProtectedErrorMessage(error: RelayProtectedErrorType): string { + switch (error._tag) { + case "RelayAuthInvalidError": + switch (error.reason) { + case "missing_bearer": + case "invalid_bearer": + return "Relay rejected the cloud session token."; + case "invalid_dpop": + return "Relay rejected the DPoP proof."; + case "not_authorized": + return "Relay rejected the authenticated request."; + } + case "RelayEnvironmentLinkProofExpiredError": + return "Relay rejected an expired environment link proof."; + case "RelayEnvironmentLinkProofInvalidError": + return `Relay rejected the environment link proof (${error.reason}).`; + case "RelayEnvironmentConnectNotAuthorizedError": + return "Relay rejected the environment connection request."; + case "RelayEnvironmentEndpointUnavailableError": + return `Relay could not reach the environment endpoint (${error.reason}).`; + case "RelayEnvironmentEndpointTimedOutError": + return "Relay timed out while contacting the environment endpoint."; + case "RelayEnvironmentLinkFailedError": + return `Relay could not link the environment (${error.reason}).`; + case "RelayEnvironmentLinkUnavailableError": + return `Relay cannot provision the managed endpoint (${error.reason}).`; + case "RelayAgentActivityPublishProofExpiredError": + return "Relay rejected an expired agent activity publish proof."; + case "RelayAgentActivityPublishProofInvalidError": + return `Relay rejected the agent activity publish proof (${error.reason}).`; + case "RelayInternalError": + return `Relay encountered an internal error (${error.reason}, trace ${error.traceId}).`; + } +} + +function decodedRelayClientError(message: string) { + return (cause: unknown) => { + const relayError = findRelayProtectedError(cause); + const detail = relayError ? relayProtectedErrorMessage(relayError) : null; + return new CloudEnvironmentLinkError({ + message: detail ? `${message}: ${detail}` : message, + cause, + }); + }; +} + +function findRelayProtectedError(cause: unknown): RelayProtectedErrorType | null { + if (isRelayProtectedError(cause)) { + return cause; + } + if (typeof cause !== "object" || cause === null) { + return null; + } + return "cause" in cause ? findRelayProtectedError(cause.cause) : null; +} + +function findEnvironmentCloudApiError(cause: unknown): { readonly message: string } | null { + if (isEnvironmentCloudApiError(cause)) { + return cause; + } + if (typeof cause !== "object" || cause === null) { + return null; + } + return "cause" in cause ? findEnvironmentCloudApiError(cause.cause) : null; +} + +const environmentApiError = (message: string) => (cause: unknown) => { + const environmentError = findEnvironmentCloudApiError(cause); + return new CloudEnvironmentLinkError({ + message: environmentError + ? `${message.replace(/[.:]$/, "")}: ${environmentError.message}` + : message, + cause, + }); +}; + +const withPrimaryEnvironmentCookies = (effect: Effect.Effect) => + effect.pipe(Effect.provideService(FetchHttpClient.RequestInit, { credentials: "include" })); + +function endpointOrigin(httpBaseUrl: string) { + const url = new URL(httpBaseUrl); + return { + localHttpHost: "127.0.0.1", + localHttpPort: Number(url.port || (url.protocol === "https:" ? 443 : 80)), + }; +} + +const MANAGED_ENDPOINT_PROVIDER_KIND = + "cloudflare_tunnel" satisfies RelayManagedEndpointProviderKind; + +function ensureLinkedEnvironmentMatches(input: { + readonly expectedEnvironmentId: string; + readonly expectedProviderKind: RelayManagedEndpointProviderKind; + readonly link: RelayEnvironmentLinkResponse; +}): Effect.Effect { + if (input.link.environmentId !== input.expectedEnvironmentId) { + return new CloudEnvironmentLinkError({ + message: "Relay returned credentials for a different environment.", + }); + } + if (input.link.endpoint.providerKind !== input.expectedProviderKind) { + return new CloudEnvironmentLinkError({ + message: "Relay returned credentials for a different endpoint provider.", + }); + } + return Effect.void; +} + +export interface CloudLinkTarget { + readonly environmentId: string; + readonly label: string; + readonly httpBaseUrl: string; + readonly wsBaseUrl: string; +} + +export type CloudLinkState = EnvironmentCloudLinkStateResult; + +export interface CloudManagedConnection { + readonly environmentId: RelayClientEnvironmentRecord["environmentId"]; + readonly label: string; + readonly httpBaseUrl: string; + readonly wsBaseUrl: string; + readonly relayUrl: string; + readonly accessToken: string; +} + +export function collectCloudLinkTargets(input: { + readonly primary: CloudLinkTarget | null; + readonly saved: ReadonlyArray; +}): ReadonlyArray { + const byId = new Map(); + if (input.primary) { + byId.set(input.primary.environmentId, input.primary); + } + for (const environment of input.saved) { + if (!byId.has(environment.environmentId)) { + byId.set(environment.environmentId, environment); + } + } + return [...byId.values()]; +} + +export function readPrimaryCloudLinkTarget(): CloudLinkTarget | null { + const descriptor = readPrimaryEnvironmentDescriptor(); + const target = readPrimaryEnvironmentTarget(); + if (!descriptor || !target) { + return null; + } + return { + environmentId: descriptor.environmentId, + label: descriptor.label, + httpBaseUrl: target.target.httpBaseUrl, + wsBaseUrl: target.target.wsBaseUrl, + }; +} + +export function listManagedCloudEnvironments(input: { + readonly clerkToken: string; +}): Effect.Effect< + ReadonlyArray, + CloudEnvironmentLinkError, + ManagedRelayClient +> { + return Effect.gen(function* () { + const configuredRelayUrl = relayUrl(); + if (!configuredRelayUrl) { + return yield* new CloudEnvironmentLinkError({ + message: "VITE_T3_RELAY_URL is not configured.", + }); + } + const relayClient = yield* ManagedRelayClient; + return yield* relayClient + .listEnvironments({ + clerkToken: input.clerkToken, + }) + .pipe( + Effect.mapError( + (cause) => + new CloudEnvironmentLinkError({ + message: "Could not list relay-managed environments.", + cause, + }), + ), + ); + }); +} + +export function connectManagedCloudEnvironment(input: { + readonly clerkToken: string; + readonly environment: RelayClientEnvironmentRecord; + readonly relayUrl?: string; +}): Effect.Effect< + CloudManagedConnection, + CloudEnvironmentLinkError, + HttpClient.HttpClient | ManagedRelayClient | ManagedRelayDpopSigner +> { + return Effect.gen(function* () { + const configuredRelayUrl = relayUrl(); + if (!configuredRelayUrl) { + return yield* new CloudEnvironmentLinkError({ + message: "VITE_T3_RELAY_URL is not configured.", + }); + } + const persistedRelayUrl = normalizeRelayBaseUrl(input.relayUrl); + if (persistedRelayUrl && persistedRelayUrl !== configuredRelayUrl) { + return yield* new CloudEnvironmentLinkError({ + message: "The saved environment is linked through a different configured relay.", + }); + } + const relayClient = yield* ManagedRelayClient; + const connected = yield* relayClient + .connectEnvironment({ + clerkToken: input.clerkToken, + scopes: [RelayEnvironmentConnectScope], + environmentId: input.environment.environmentId, + }) + .pipe( + Effect.mapError( + (cause) => + new CloudEnvironmentLinkError({ + message: "Could not connect to relay-managed environment.", + cause, + }), + ), + ); + if (connected.environmentId !== input.environment.environmentId) { + return yield* new CloudEnvironmentLinkError({ + message: "Relay returned credentials for a different environment.", + }); + } + if ( + connected.endpoint.httpBaseUrl !== input.environment.endpoint.httpBaseUrl || + connected.endpoint.wsBaseUrl !== input.environment.endpoint.wsBaseUrl || + connected.endpoint.providerKind !== input.environment.endpoint.providerKind + ) { + return yield* new CloudEnvironmentLinkError({ + message: "Relay returned credentials for a different endpoint.", + }); + } + const descriptor = yield* fetchRemoteEnvironmentDescriptor({ + httpBaseUrl: connected.endpoint.httpBaseUrl, + }).pipe( + Effect.mapError( + (cause) => + new CloudEnvironmentLinkError({ + message: "Could not read connected environment descriptor.", + cause, + }), + ), + ); + if (descriptor.environmentId !== connected.environmentId) { + return yield* new CloudEnvironmentLinkError({ + message: "Connected endpoint does not match the selected environment.", + }); + } + const signer = yield* ManagedRelayDpopSigner; + const bootstrapProof = yield* signer + .createProof({ + method: "POST", + url: new URL("/oauth/token", connected.endpoint.httpBaseUrl).toString(), + }) + .pipe( + Effect.mapError( + (cause) => + new CloudEnvironmentLinkError({ + message: "Could not create environment DPoP proof.", + cause, + }), + ), + ); + const session = yield* exchangeRemoteDpopAccessToken({ + httpBaseUrl: connected.endpoint.httpBaseUrl, + credential: connected.credential, + dpopProof: bootstrapProof, + }).pipe( + Effect.mapError( + (cause) => + new CloudEnvironmentLinkError({ + message: "Could not authorize managed environment.", + cause, + }), + ), + ); + return { + environmentId: descriptor.environmentId, + label: descriptor.label, + httpBaseUrl: connected.endpoint.httpBaseUrl, + wsBaseUrl: connected.endpoint.wsBaseUrl, + relayUrl: configuredRelayUrl, + accessToken: session.access_token, + }; + }); +} + +export function readPrimaryCloudLinkState(): Effect.Effect< + CloudLinkState | null, + CloudEnvironmentLinkError, + HttpClient.HttpClient +> { + return Effect.gen(function* () { + if (!readPrimaryCloudLinkTarget()) { + return null; + } + const client = yield* makeEnvironmentHttpApiClient(resolvePrimaryEnvironmentHttpUrl("/")); + return yield* client.cloud + .linkState({ headers: {} }) + .pipe( + withPrimaryEnvironmentCookies, + Effect.mapError(environmentApiError("Could not read environment cloud link state.")), + ); + }); +} + +export function unlinkPrimaryEnvironmentFromCloud(input: { + readonly clerkToken: string | null; +}): Effect.Effect { + return Effect.gen(function* () { + const target = readPrimaryCloudLinkTarget(); + if (!target) { + return yield* new CloudEnvironmentLinkError({ + message: "Local environment is not ready yet.", + }); + } + const configuredRelayUrl = relayUrl(); + if (configuredRelayUrl && input.clerkToken) { + const relayClient = yield* ManagedRelayClient; + yield* relayClient + .unlinkEnvironment({ + clerkToken: input.clerkToken, + environmentId: EnvironmentId.make(target.environmentId), + }) + .pipe( + Effect.catch((cause) => + Effect.logWarning("Could not revoke cloud environment link before local unlink.", { + cause, + }), + ), + ); + } + + const client = yield* makeEnvironmentHttpApiClient(resolvePrimaryEnvironmentHttpUrl("/")); + yield* client.cloud + .unlink({ headers: {} }) + .pipe( + withPrimaryEnvironmentCookies, + Effect.mapError(environmentApiError("Could not unlink the environment from cloud.")), + ); + }); +} + +export function linkEnvironmentToCloud(input: { + readonly environment: SavedEnvironmentRecord; + readonly clerkToken: string; +}): Effect.Effect { + return Effect.gen(function* () { + const configuredRelayUrl = relayUrl(); + if (!configuredRelayUrl) { + return yield* new CloudEnvironmentLinkError({ + message: "VITE_T3_RELAY_URL is not configured.", + }); + } + const relayClient = yield* ManagedRelayClient; + const bearerToken = yield* Effect.tryPromise({ + try: () => + ensureLocalApi().persistence.getSavedEnvironmentSecret(input.environment.environmentId), + catch: (cause) => + new CloudEnvironmentLinkError({ + message: `Could not read saved bearer token for ${input.environment.label}.`, + cause, + }), + }); + if (!bearerToken) { + return yield* new CloudEnvironmentLinkError({ + message: `No saved bearer token for ${input.environment.label}.`, + }); + } + + const challenge = yield* relayClient + .createEnvironmentLinkChallenge({ + clerkToken: input.clerkToken, + payload: { + notificationsEnabled: true, + liveActivitiesEnabled: true, + managedTunnelsEnabled: true, + }, + }) + .pipe( + Effect.mapError( + decodedRelayClientError( + `${configuredRelayUrl}/v1/client/environment-link-challenges failed`, + ), + ), + ); + const environmentClient = yield* makeEnvironmentHttpApiClient(input.environment.httpBaseUrl); + const proof = yield* environmentClient.cloud + .linkProof({ + headers: { authorization: `Bearer ${bearerToken}` }, + payload: { + challenge: challenge.challenge, + relayIssuer: configuredRelayUrl, + endpoint: { + httpBaseUrl: input.environment.httpBaseUrl, + wsBaseUrl: input.environment.wsBaseUrl, + providerKind: MANAGED_ENDPOINT_PROVIDER_KIND, + }, + origin: endpointOrigin(input.environment.httpBaseUrl), + }, + }) + .pipe(Effect.mapError(environmentApiError("Could not obtain environment link proof."))); + const link = yield* relayClient + .linkEnvironment({ + clerkToken: input.clerkToken, + payload: { + proof, + notificationsEnabled: true, + liveActivitiesEnabled: true, + managedTunnelsEnabled: true, + }, + }) + .pipe( + Effect.mapError( + decodedRelayClientError(`${configuredRelayUrl}/v1/client/environment-links failed`), + ), + ); + yield* ensureLinkedEnvironmentMatches({ + expectedEnvironmentId: input.environment.environmentId, + expectedProviderKind: MANAGED_ENDPOINT_PROVIDER_KIND, + link, + }); + + yield* environmentClient.cloud + .relayConfig({ + headers: { authorization: `Bearer ${bearerToken}` }, + payload: { + relayUrl: configuredRelayUrl, + relayIssuer: link.relayIssuer, + cloudUserId: link.cloudUserId, + environmentCredential: link.environmentCredential, + cloudMintPublicKey: link.cloudMintPublicKey, + endpointRuntime: link.endpointRuntime, + }, + }) + .pipe(Effect.mapError(environmentApiError("Could not configure environment relay access."))); + }); +} + +export function linkPrimaryEnvironmentToCloud(input: { + readonly clerkToken: string; +}): Effect.Effect { + return Effect.gen(function* () { + const configuredRelayUrl = relayUrl(); + if (!configuredRelayUrl) { + return yield* new CloudEnvironmentLinkError({ + message: "VITE_T3_RELAY_URL is not configured.", + }); + } + const relayClient = yield* ManagedRelayClient; + const target = readPrimaryCloudLinkTarget(); + if (!target) { + return yield* new CloudEnvironmentLinkError({ + message: "Local environment is not ready yet.", + }); + } + + const challenge = yield* relayClient + .createEnvironmentLinkChallenge({ + clerkToken: input.clerkToken, + payload: { + notificationsEnabled: true, + liveActivitiesEnabled: true, + managedTunnelsEnabled: true, + }, + }) + .pipe( + Effect.mapError( + decodedRelayClientError( + `${configuredRelayUrl}/v1/client/environment-link-challenges failed`, + ), + ), + ); + const environmentClient = yield* makeEnvironmentHttpApiClient(target.httpBaseUrl); + const proof = yield* environmentClient.cloud + .linkProof({ + headers: {}, + payload: { + challenge: challenge.challenge, + relayIssuer: configuredRelayUrl, + endpoint: { + httpBaseUrl: target.httpBaseUrl, + wsBaseUrl: target.wsBaseUrl, + providerKind: MANAGED_ENDPOINT_PROVIDER_KIND, + }, + origin: endpointOrigin(target.httpBaseUrl), + }, + }) + .pipe( + withPrimaryEnvironmentCookies, + Effect.mapError(environmentApiError("Could not obtain environment link proof.")), + ); + const link = yield* relayClient + .linkEnvironment({ + clerkToken: input.clerkToken, + payload: { + proof, + notificationsEnabled: true, + liveActivitiesEnabled: true, + managedTunnelsEnabled: true, + }, + }) + .pipe( + Effect.mapError( + decodedRelayClientError(`${configuredRelayUrl}/v1/client/environment-links failed`), + ), + ); + yield* ensureLinkedEnvironmentMatches({ + expectedEnvironmentId: target.environmentId, + expectedProviderKind: MANAGED_ENDPOINT_PROVIDER_KIND, + link, + }); + + yield* environmentClient.cloud + .relayConfig({ + headers: {}, + payload: { + relayUrl: configuredRelayUrl, + relayIssuer: link.relayIssuer, + cloudUserId: link.cloudUserId, + environmentCredential: link.environmentCredential, + cloudMintPublicKey: link.cloudMintPublicKey, + endpointRuntime: link.endpointRuntime, + }, + }) + .pipe( + withPrimaryEnvironmentCookies, + Effect.mapError(environmentApiError("Could not configure environment relay access.")), + ); + }); +} diff --git a/apps/web/src/cloud/managedAuth.tsx b/apps/web/src/cloud/managedAuth.tsx new file mode 100644 index 0000000000..9bc3a69a3a --- /dev/null +++ b/apps/web/src/cloud/managedAuth.tsx @@ -0,0 +1,22 @@ +import { useAuth } from "@clerk/react"; +import { RELAY_CLERK_TOKEN_OPTIONS } from "@t3tools/shared/relayAuth"; +import { useEffect, type ReactNode } from "react"; + +let relayTokenProvider: (() => Promise) | null = null; + +export async function readManagedRelayClerkToken(): Promise { + return relayTokenProvider?.() ?? null; +} + +export function ManagedRelayAuthProvider({ children }: { readonly children: ReactNode }) { + const { getToken, isSignedIn } = useAuth(); + + useEffect(() => { + relayTokenProvider = isSignedIn ? () => getToken(RELAY_CLERK_TOKEN_OPTIONS) : null; + return () => { + relayTokenProvider = null; + }; + }, [getToken, isSignedIn]); + + return children; +} diff --git a/apps/web/src/cloud/managedRelayLayer.ts b/apps/web/src/cloud/managedRelayLayer.ts new file mode 100644 index 0000000000..f34ad2f9c9 --- /dev/null +++ b/apps/web/src/cloud/managedRelayLayer.ts @@ -0,0 +1,62 @@ +import { + managedRelayClientLayer, + ManagedRelayDpopSigner, + ManagedRelayDpopSignerError, +} from "@t3tools/client-runtime"; +import { RelayWebClientId } from "@t3tools/contracts/relay"; +import * as Crypto from "effect/Crypto"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import * as Semaphore from "effect/Semaphore"; + +import { + createBrowserDpopProof, + generateBrowserDpopKey, + readStoredBrowserDpopKey, + writeStoredBrowserDpopKey, + type BrowserDpopKey, +} from "./dpop"; + +export const webRelayDpopSignerLayer = Layer.effect( + ManagedRelayDpopSigner, + Effect.gen(function* () { + const crypto = yield* Crypto.Crypto; + const keyLoadSemaphore = yield* Semaphore.make(1); + let loadedKey: BrowserDpopKey | null = null; + const loadOrCreateBrowserDpopKey = keyLoadSemaphore.withPermit( + Effect.gen(function* () { + if (loadedKey) { + return loadedKey; + } + const stored = yield* readStoredBrowserDpopKey(); + if (stored) { + loadedKey = stored; + return stored; + } + const generated = yield* generateBrowserDpopKey; + yield* writeStoredBrowserDpopKey(generated); + loadedKey = generated; + return generated; + }), + ); + const signerError = (cause: unknown) => new ManagedRelayDpopSignerError({ cause }); + return ManagedRelayDpopSigner.of({ + thumbprint: loadOrCreateBrowserDpopKey.pipe( + Effect.map((proofKey) => proofKey.thumbprint), + Effect.mapError(signerError), + ), + createProof: (input) => + loadOrCreateBrowserDpopKey.pipe( + Effect.flatMap((proofKey) => createBrowserDpopProof({ ...input, proofKey })), + Effect.provideService(Crypto.Crypto, crypto), + Effect.map((proof) => proof.proof), + Effect.mapError(signerError), + ), + }); + }), +); + +export const webManagedRelayClientLayer = (relayUrl: string) => + managedRelayClientLayer({ relayUrl, clientId: RelayWebClientId }).pipe( + Layer.provideMerge(webRelayDpopSignerLayer), + ); diff --git a/apps/web/src/components/settings/CloudSettings.tsx b/apps/web/src/components/settings/CloudSettings.tsx new file mode 100644 index 0000000000..e5974319c1 --- /dev/null +++ b/apps/web/src/components/settings/CloudSettings.tsx @@ -0,0 +1,556 @@ +import { UserButton, Waitlist, useAuth, useClerk } from "@clerk/react"; +import { useSignIn, useSignUp } from "@clerk/react/legacy"; +import { RELAY_CLERK_TOKEN_OPTIONS } from "@t3tools/shared/relayAuth"; +import type { RelayClientEnvironmentRecord } from "@t3tools/contracts/relay"; +import * as Effect from "effect/Effect"; +import { CloudIcon } from "lucide-react"; +import { useCallback, useEffect, useRef, useState } from "react"; + +import { + type DesktopCloudAuthOAuthStrategy, + resolveDesktopCloudAuthOAuthOptions, +} from "../../cloud/desktopAuth"; +import { + collectCloudLinkTargets, + connectManagedCloudEnvironment, + linkEnvironmentToCloud, + linkPrimaryEnvironmentToCloud, + listManagedCloudEnvironments, + readPrimaryCloudLinkState, + readPrimaryCloudLinkTarget, + type CloudLinkState, + unlinkPrimaryEnvironmentFromCloud, +} from "../../cloud/linkEnvironment"; +import { isElectron } from "../../env"; +import { usePrimaryEnvironmentId } from "../../environments/primary"; +import { + addManagedRelayEnvironment, + listSavedEnvironmentRecords, + useSavedEnvironmentRegistryStore, +} from "../../environments/runtime"; +import { webRuntime } from "../../lib/runtime"; +import { Button } from "../ui/button"; +import { toastManager } from "../ui/toast"; +import { SettingsPageContainer, SettingsRow, SettingsSection } from "./settingsLayout"; + +function hasClerkConfig(): boolean { + return Boolean(import.meta.env.VITE_CLERK_PUBLISHABLE_KEY); +} + +class CloudSettingsOperationError extends Error { + override readonly cause?: unknown; + + constructor(message: string, cause?: unknown) { + super(message); + this.name = "CloudSettingsOperationError"; + this.cause = cause; + } +} + +async function runCloudOperation(operation: () => Promise, message: string): Promise { + try { + return await operation(); + } catch (cause) { + throw new CloudSettingsOperationError(message, cause); + } +} + +function cloudErrorMessage(error: unknown, fallback: string): string { + if (error instanceof CloudSettingsOperationError) { + const cause = error.cause; + if (cause instanceof Error && cause.message && cause.message !== error.message) { + return `${error.message}: ${cause.message}`; + } + return error.message; + } + return error instanceof Error ? error.message : fallback; +} + +export function CloudSettingsPanel() { + if (!hasClerkConfig()) { + return ( + + }> + + + + ); + } + + return ; +} + +function ConfiguredCloudSettingsPanel() { + const { isLoaded, isSignedIn } = useAuth(); + + if (!isLoaded) { + return null; + } + + return isSignedIn ? : ; +} + +function CloudWaitlistPanel() { + return ( + + + {isElectron ? ( +
+

Already approved? Sign in through the desktop app.

+ +
+ ) : null} +
+ ); +} + +function CloudSettingsPanelInner() { + const { getToken, userId } = useAuth(); + const primaryEnvironmentId = usePrimaryEnvironmentId(); + const savedEnvironmentCount = useSavedEnvironmentRegistryStore( + (state) => Object.keys(state.byId).length, + ); + const [isLinking, setIsLinking] = useState(false); + const [isUnlinking, setIsUnlinking] = useState(false); + const [primaryLinkState, setPrimaryLinkState] = useState(null); + const [linkStateError, setLinkStateError] = useState(null); + const [managedEnvironments, setManagedEnvironments] = useState< + ReadonlyArray + >([]); + const [isLoadingManaged, setIsLoadingManaged] = useState(false); + const [connectingEnvironmentId, setConnectingEnvironmentId] = useState(null); + const linkableEnvironmentCount = collectCloudLinkTargets({ + primary: primaryEnvironmentId ? readPrimaryCloudLinkTarget() : null, + saved: listSavedEnvironmentRecords().filter((environment) => !environment.relayManaged), + }).length; + const linkedCloudUserId = primaryLinkState?.cloudUserId ?? null; + const hasCloudAccountMismatch = Boolean( + userId && linkedCloudUserId && linkedCloudUserId !== userId, + ); + + const refreshPrimaryLinkState = useCallback(() => { + if (!primaryEnvironmentId) { + setPrimaryLinkState(null); + setLinkStateError(null); + return; + } + void webRuntime.runPromise(readPrimaryCloudLinkState()).then( + (state) => { + setPrimaryLinkState(state); + setLinkStateError(null); + }, + (error: unknown) => { + setPrimaryLinkState(null); + setLinkStateError(cloudErrorMessage(error, "Could not read local cloud link state.")); + }, + ); + }, [primaryEnvironmentId]); + + useEffect(() => { + refreshPrimaryLinkState(); + }, [refreshPrimaryLinkState]); + + const refreshManagedEnvironments = useCallback(async () => { + setIsLoadingManaged(true); + try { + const token = await getToken(RELAY_CLERK_TOKEN_OPTIONS); + if (!token) { + setManagedEnvironments([]); + return; + } + setManagedEnvironments( + await webRuntime.runPromise(listManagedCloudEnvironments({ clerkToken: token })), + ); + } catch (error) { + toastManager.add({ + type: "error", + title: "Cloud environments unavailable", + description: cloudErrorMessage(error, "Could not load linked environments."), + }); + } finally { + setIsLoadingManaged(false); + } + }, [getToken]); + + useEffect(() => { + void refreshManagedEnvironments(); + }, [refreshManagedEnvironments]); + + const linkEnvironments = async () => { + if (hasCloudAccountMismatch) { + toastManager.add({ + type: "error", + title: "Cloud account mismatch", + description: "This environment is linked to a different cloud account.", + }); + return; + } + setIsLinking(true); + try { + const token = await runCloudOperation( + () => getToken(RELAY_CLERK_TOKEN_OPTIONS), + "Could not get the current cloud session.", + ); + if (!token) { + return; + } + const primaryTarget = readPrimaryCloudLinkTarget(); + const savedEnvironments = listSavedEnvironmentRecords().filter( + (environment) => !environment.relayManaged, + ); + const savedEnvironmentIds = new Set(primaryTarget ? [primaryTarget.environmentId] : []); + if (primaryTarget) { + await runCloudOperation( + () => webRuntime.runPromise(linkPrimaryEnvironmentToCloud({ clerkToken: token })), + "Could not link the local environment.", + ); + } + await runCloudOperation( + () => + webRuntime.runPromise( + Effect.all( + savedEnvironments + .filter((environment) => { + if (savedEnvironmentIds.has(environment.environmentId)) { + return false; + } + savedEnvironmentIds.add(environment.environmentId); + return true; + }) + .map((environment) => linkEnvironmentToCloud({ environment, clerkToken: token })), + { concurrency: "unbounded" }, + ), + ), + "Could not link environments.", + ); + toastManager.add({ + type: "success", + title: "Environments linked", + description: "Relay notifications are enabled for linked environments.", + }); + refreshPrimaryLinkState(); + } catch (error) { + toastManager.add({ + type: "error", + title: "Cloud link failed", + description: cloudErrorMessage(error, "Could not link environments."), + }); + } finally { + setIsLinking(false); + } + }; + + const unlinkPrimaryEnvironment = async () => { + setIsUnlinking(true); + try { + const token = await getToken(RELAY_CLERK_TOKEN_OPTIONS).catch(() => null); + await runCloudOperation( + () => webRuntime.runPromise(unlinkPrimaryEnvironmentFromCloud({ clerkToken: token })), + "Could not unlink the local environment.", + ); + refreshPrimaryLinkState(); + toastManager.add({ + type: "success", + title: "Environment unlinked", + description: "Local relay credentials and managed endpoint runtime config were removed.", + }); + } catch (error) { + toastManager.add({ + type: "error", + title: "Cloud unlink failed", + description: cloudErrorMessage(error, "Could not unlink the local environment."), + }); + } finally { + setIsUnlinking(false); + } + }; + + const connectManagedEnvironment = async (environment: RelayClientEnvironmentRecord) => { + setConnectingEnvironmentId(environment.environmentId); + try { + const token = await getToken(RELAY_CLERK_TOKEN_OPTIONS); + if (!token) { + throw new CloudSettingsOperationError("Could not get the current cloud session."); + } + const connection = await webRuntime.runPromise( + connectManagedCloudEnvironment({ clerkToken: token, environment }), + ); + await addManagedRelayEnvironment(connection); + toastManager.add({ + type: "success", + title: "Environment connected", + description: `${connection.label} is available through its managed tunnel.`, + }); + } catch (error) { + toastManager.add({ + type: "error", + title: "Managed connection failed", + description: cloudErrorMessage(error, "Could not connect to the cloud environment."), + }); + } finally { + setConnectingEnvironmentId(null); + } + }; + + return ( + + }> + } + /> + + {linkedCloudUserId ? ( + + ) : null} + + + } + /> + void refreshManagedEnvironments()} + > + Refresh + + } + /> + {managedEnvironments.map((environment) => ( + void connectManagedEnvironment(environment)} + > + {connectingEnvironmentId === environment.environmentId + ? "Connecting..." + : "Connect"} + + } + /> + ))} + + + ); +} + +function DesktopCloudSignInButton() { + const clerk = useClerk(); + const { setActive } = clerk; + const { isLoaded: signInLoaded, signIn } = useSignIn(); + const { isLoaded: signUpLoaded, signUp } = useSignUp(); + const [startingStrategy, setStartingStrategy] = useState( + null, + ); + const oauthOptions = resolveDesktopCloudAuthOAuthOptions(clerk); + const callbackCleanupRef = useRef<(() => void) | null>(null); + + const clearCallbackListener = useCallback(() => { + callbackCleanupRef.current?.(); + callbackCleanupRef.current = null; + }, []); + + const completeOAuthCallback = useCallback( + async (rawUrl: string) => { + if (!signInLoaded || !signIn || !signUpLoaded || !signUp) { + toastManager.add({ + type: "error", + title: "Cloud sign-in failed", + description: "Clerk is still loading. Try signing in again.", + }); + return; + } + + let rotatingTokenNonce: string | null = null; + let sessionId: string | null = null; + try { + const callbackUrl = new URL(rawUrl); + rotatingTokenNonce = callbackUrl.searchParams.get("rotating_token_nonce"); + sessionId = callbackUrl.searchParams.get("created_session_id"); + } catch { + // Handled by the explicit nonce check below. + } + if (!rotatingTokenNonce) { + toastManager.add({ + type: "error", + title: "Cloud sign-in failed", + description: + "Clerk did not return a native session nonce. Verify this redirect URL is allowlisted for native SSO redirects.", + }); + return; + } + + try { + await runCloudOperation( + () => signIn.reload({ rotatingTokenNonce }), + "Could not reload the desktop sign-in session.", + ); + sessionId = sessionId || signIn.createdSessionId; + + if (!sessionId && signIn.firstFactorVerification.status === "transferable") { + const signUpAttempt = await runCloudOperation( + () => signUp.create({ transfer: true }), + "Could not transfer the desktop sign-up session.", + ); + sessionId = signUpAttempt.createdSessionId; + } + + if (!sessionId) { + throw new CloudSettingsOperationError("Clerk did not create a desktop session."); + } + + await runCloudOperation( + () => setActive({ session: sessionId! }), + "Could not activate the desktop cloud session.", + ); + } catch (error) { + toastManager.add({ + type: "error", + title: "Cloud sign-in failed", + description: cloudErrorMessage(error, "Could not complete cloud sign-in."), + }); + } + }, + [setActive, signIn, signInLoaded, signUp, signUpLoaded], + ); + + useEffect(() => { + return () => { + clearCallbackListener(); + }; + }, [clearCallbackListener]); + + const startOAuth = async (strategy: DesktopCloudAuthOAuthStrategy) => { + if (!signInLoaded || !signIn) { + toastManager.add({ + type: "error", + title: "Cloud sign-in failed", + description: "Clerk is still loading. Try signing in again.", + }); + return; + } + + setStartingStrategy(strategy); + clearCallbackListener(); + try { + const redirectUrl = await runCloudOperation( + () => window.desktopBridge?.createCloudAuthRequest() ?? Promise.resolve(undefined), + "Desktop auth callback is unavailable.", + ); + if (!redirectUrl) { + throw new CloudSettingsOperationError("Desktop auth callback is unavailable."); + } + + callbackCleanupRef.current = + window.desktopBridge?.onCloudAuthCallback((rawUrl) => { + clearCallbackListener(); + void completeOAuthCallback(rawUrl); + }) ?? null; + + const signInAttempt = await runCloudOperation( + () => signIn.create({ strategy, redirectUrl } as never), + "Could not create the desktop OAuth request.", + ); + const externalUrl = + signInAttempt.firstFactorVerification.externalVerificationRedirectURL?.toString(); + if (!externalUrl) { + throw new CloudSettingsOperationError( + "Clerk did not return an external OAuth redirect URL.", + ); + } + + const opened = await runCloudOperation( + () => window.desktopBridge?.openExternal(externalUrl) ?? Promise.resolve(false), + "Could not open the system browser.", + ); + if (!opened) { + throw new CloudSettingsOperationError("Could not open the system browser."); + } + } catch (error) { + clearCallbackListener(); + toastManager.add({ + type: "error", + title: "Cloud sign-in failed", + description: cloudErrorMessage(error, "Could not start cloud sign-in."), + }); + } finally { + setStartingStrategy(null); + } + }; + + const isStarting = startingStrategy !== null; + + if (oauthOptions.length === 0) { + return ( + + ); + } + + return ( +
+ {oauthOptions.map((option) => ( + + ))} +
+ ); +} diff --git a/apps/web/src/components/settings/SettingsPanels.browser.tsx b/apps/web/src/components/settings/SettingsPanels.browser.tsx index f059354661..0ccdf58512 100644 --- a/apps/web/src/components/settings/SettingsPanels.browser.tsx +++ b/apps/web/src/components/settings/SettingsPanels.browser.tsx @@ -450,6 +450,18 @@ const createDesktopBridgeStub = (overrides?: { setTheme: vi.fn().mockResolvedValue(undefined), showContextMenu: vi.fn().mockResolvedValue(null), openExternal: vi.fn().mockResolvedValue(true), + createCloudAuthRequest: vi.fn().mockResolvedValue("t3code-dev://auth/callback?t3_state=test"), + getCloudAuthToken: vi.fn().mockResolvedValue(null), + setCloudAuthToken: vi.fn().mockResolvedValue(true), + clearCloudAuthToken: vi.fn().mockResolvedValue(undefined), + fetchCloudAuth: vi.fn().mockResolvedValue({ + ok: true, + status: 200, + statusText: "OK", + headers: {}, + body: "", + }), + onCloudAuthCallback: () => () => {}, onMenuAction: () => () => {}, getUpdateState: vi.fn().mockResolvedValue(idleUpdateState), setUpdateChannel: diff --git a/apps/web/src/components/settings/SettingsSidebarNav.tsx b/apps/web/src/components/settings/SettingsSidebarNav.tsx index bec9606386..08afc9d8f6 100644 --- a/apps/web/src/components/settings/SettingsSidebarNav.tsx +++ b/apps/web/src/components/settings/SettingsSidebarNav.tsx @@ -3,6 +3,7 @@ import { ArchiveIcon, ArrowLeftIcon, BotIcon, + CloudIcon, GitBranchIcon, KeyboardIcon, Link2Icon, @@ -26,6 +27,7 @@ export type SettingsSectionPath = | "/settings/keybindings" | "/settings/providers" | "/settings/source-control" + | "/settings/cloud" | "/settings/connections" | "/settings/archived"; @@ -38,6 +40,7 @@ export const SETTINGS_NAV_ITEMS: ReadonlyArray<{ { label: "Keybindings", to: "/settings/keybindings", icon: KeyboardIcon }, { label: "Providers", to: "/settings/providers", icon: BotIcon }, { label: "Source Control", to: "/settings/source-control", icon: GitBranchIcon }, + { label: "T3 Cloud", to: "/settings/cloud", icon: CloudIcon }, { label: "Connections", to: "/settings/connections", icon: Link2Icon }, { label: "Archive", to: "/settings/archived", icon: ArchiveIcon }, ]; diff --git a/apps/web/src/environments/primary/auth.ts b/apps/web/src/environments/primary/auth.ts index 40bd277fc0..f6f07dbb30 100644 --- a/apps/web/src/environments/primary/auth.ts +++ b/apps/web/src/environments/primary/auth.ts @@ -3,6 +3,7 @@ import type { AuthClientMetadata, AuthEnvironmentScope, AuthPairingCredentialResult, + ServerAuthSessionMethod, AuthSessionId, AuthSessionState, } from "@t3tools/contracts"; @@ -45,7 +46,7 @@ export interface ServerClientSessionRecord { readonly sessionId: AuthSessionId; readonly subject: string; readonly scopes: ReadonlyArray; - readonly method: "browser-session-cookie" | "bearer-access-token"; + readonly method: ServerAuthSessionMethod; readonly client: AuthClientMetadata; readonly issuedAt: string; readonly expiresAt: string; diff --git a/apps/web/src/environments/primary/index.ts b/apps/web/src/environments/primary/index.ts index 6856b9ac5f..09576c34e4 100644 --- a/apps/web/src/environments/primary/index.ts +++ b/apps/web/src/environments/primary/index.ts @@ -34,4 +34,8 @@ export { export { refreshPrimarySessionState, usePrimarySessionState } from "./sessionState"; -export { resolvePrimaryEnvironmentHttpUrl, isLoopbackHostname } from "./target"; +export { + readPrimaryEnvironmentTarget, + resolvePrimaryEnvironmentHttpUrl, + isLoopbackHostname, +} from "./target"; diff --git a/apps/web/src/environments/runtime/catalog.test.ts b/apps/web/src/environments/runtime/catalog.test.ts index d530c8173b..1002ab08dd 100644 --- a/apps/web/src/environments/runtime/catalog.test.ts +++ b/apps/web/src/environments/runtime/catalog.test.ts @@ -6,11 +6,13 @@ import { import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test"; import { + readSavedEnvironmentCredential, resetSavedEnvironmentRegistryStoreForTests, resetSavedEnvironmentRuntimeStoreForTests, useSavedEnvironmentRegistryStore, useSavedEnvironmentRuntimeStore, waitForSavedEnvironmentRegistryHydration, + writeSavedEnvironmentCredential, } from "./catalog"; describe("environment runtime catalog stores", () => { @@ -74,6 +76,47 @@ describe("environment runtime catalog stores", () => { expect(useSavedEnvironmentRuntimeStore.getState().byId).toEqual({}); }); + it("decodes legacy bearer secrets and writes versioned DPoP credentials", async () => { + let storedSecret: string | null = "legacy-bearer-token"; + vi.stubGlobal("window", { + nativeApi: { + persistence: { + getClientSettings: async () => null, + setClientSettings: async () => undefined, + getSavedEnvironmentRegistry: async () => [], + setSavedEnvironmentRegistry: async () => undefined, + getSavedEnvironmentSecret: async () => storedSecret, + setSavedEnvironmentSecret: async (_environmentId, secret) => { + storedSecret = secret; + return true; + }, + removeSavedEnvironmentSecret: async () => undefined, + }, + } satisfies Pick, + }); + const { __resetLocalApiForTests } = await import("../../localApi"); + await __resetLocalApiForTests(); + const environmentId = EnvironmentId.make("environment-1"); + + await expect(readSavedEnvironmentCredential(environmentId)).resolves.toEqual({ + version: 1, + method: "bearer", + token: "legacy-bearer-token", + }); + await expect( + writeSavedEnvironmentCredential(environmentId, { + version: 1, + method: "dpop", + accessToken: "managed-dpop-access-token", + }), + ).resolves.toBe(true); + await expect(readSavedEnvironmentCredential(environmentId)).resolves.toEqual({ + version: 1, + method: "dpop", + accessToken: "managed-dpop-access-token", + }); + }); + it("does not throw when local api lookup fails during registry persistence", async () => { vi.unstubAllGlobals(); const errorSpy = vi.spyOn(console, "error").mockImplementation(() => {}); diff --git a/apps/web/src/environments/runtime/catalog.ts b/apps/web/src/environments/runtime/catalog.ts index 5d1c956051..570d9753c1 100644 --- a/apps/web/src/environments/runtime/catalog.ts +++ b/apps/web/src/environments/runtime/catalog.ts @@ -6,6 +6,8 @@ import type { PersistedSavedEnvironmentRecord, ServerConfig, } from "@t3tools/contracts"; +import * as Option from "effect/Option"; +import * as Schema from "effect/Schema"; import { create } from "zustand"; import { ensureLocalApi } from "../../localApi"; @@ -19,8 +21,29 @@ export interface SavedEnvironmentRecord { readonly createdAt: string; readonly lastConnectedAt: string | null; readonly desktopSsh?: PersistedSavedEnvironmentRecord["desktopSsh"]; + readonly relayManaged?: PersistedSavedEnvironmentRecord["relayManaged"]; } +export const SavedEnvironmentCredential = Schema.Union([ + Schema.Struct({ + version: Schema.Literal(1), + method: Schema.Literal("bearer"), + token: Schema.String, + }), + Schema.Struct({ + version: Schema.Literal(1), + method: Schema.Literal("dpop"), + accessToken: Schema.String, + }), +]); +export type SavedEnvironmentCredential = typeof SavedEnvironmentCredential.Type; + +const SavedEnvironmentCredentialJson = Schema.fromJsonString(SavedEnvironmentCredential); +const decodeSavedEnvironmentCredentialJson = Schema.decodeUnknownOption( + SavedEnvironmentCredentialJson, +); +const encodeSavedEnvironmentCredentialJson = Schema.encodeSync(SavedEnvironmentCredentialJson); + interface SavedEnvironmentRegistryState { readonly byId: Record; } @@ -47,6 +70,7 @@ export function toPersistedSavedEnvironmentRecord( createdAt: record.createdAt, lastConnectedAt: record.lastConnectedAt, ...(record.desktopSsh ? { desktopSsh: record.desktopSsh } : {}), + ...(record.relayManaged ? { relayManaged: record.relayManaged } : {}), }; } @@ -250,6 +274,31 @@ export async function readSavedEnvironmentBearerToken( return ensureLocalApi().persistence.getSavedEnvironmentSecret(environmentId); } +export async function readSavedEnvironmentCredential( + environmentId: EnvironmentId, +): Promise { + const secret = await ensureLocalApi().persistence.getSavedEnvironmentSecret(environmentId); + if (!secret) { + return null; + } + const decoded = decodeSavedEnvironmentCredentialJson(secret); + if (Option.isSome(decoded)) { + return decoded.value; + } + // Legacy bearer secrets were stored directly as strings. + return { version: 1, method: "bearer", token: secret }; +} + +export async function writeSavedEnvironmentCredential( + environmentId: EnvironmentId, + credential: SavedEnvironmentCredential, +): Promise { + return ensureLocalApi().persistence.setSavedEnvironmentSecret( + environmentId, + encodeSavedEnvironmentCredentialJson(credential), + ); +} + export async function writeSavedEnvironmentBearerToken( environmentId: EnvironmentId, bearerToken: string, diff --git a/apps/web/src/environments/runtime/index.ts b/apps/web/src/environments/runtime/index.ts index d6acb67e86..7333e03a42 100644 --- a/apps/web/src/environments/runtime/index.ts +++ b/apps/web/src/environments/runtime/index.ts @@ -16,6 +16,7 @@ export { export { addSavedEnvironment, + addManagedRelayEnvironment, connectDesktopSshEnvironment, disconnectSavedEnvironment, ensureEnvironmentConnectionBootstrapped, diff --git a/apps/web/src/environments/runtime/service.addSavedEnvironment.test.ts b/apps/web/src/environments/runtime/service.addSavedEnvironment.test.ts index a6924c476f..e7f2e60b58 100644 --- a/apps/web/src/environments/runtime/service.addSavedEnvironment.test.ts +++ b/apps/web/src/environments/runtime/service.addSavedEnvironment.test.ts @@ -1,4 +1,5 @@ import { EnvironmentAuthInvalidError, EnvironmentId } from "@t3tools/contracts"; +import * as Effect from "effect/Effect"; import * as Schema from "effect/Schema"; import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test"; @@ -10,17 +11,33 @@ const mockResolveRemotePairingTarget = vi.fn(); const mockFetchRemoteEnvironmentDescriptor = vi.fn(); const mockBootstrapRemoteBearerSession = vi.fn(); const mockFetchRemoteSessionState = vi.fn(); +const mockFetchRemoteDpopSessionState = vi.fn(); const mockResolveRemoteWebSocketConnectionUrl = vi.fn(); -const mockRemoteHttpRunPromise = vi.fn((effect: Promise) => effect); +let managedRelayDpopSigner: typeof import("@t3tools/client-runtime").ManagedRelayDpopSigner; +const mockRemoteHttpRunPromise = vi.fn((effect: Effect.Effect) => + Effect.runPromise( + effect.pipe( + Effect.provideService( + managedRelayDpopSigner, + managedRelayDpopSigner.of({ + thumbprint: Effect.succeed("thumbprint"), + createProof: () => Effect.succeed("dpop-proof"), + }), + ), + ), + ), +); const mockBootstrapSshBearerSession = vi.fn(); const mockFetchSshSessionState = vi.fn(); const mockPersistSavedEnvironmentRecord = vi.fn(); const mockWriteSavedEnvironmentBearerToken = vi.fn(); +const mockWriteSavedEnvironmentCredential = vi.fn(); const mockSetSavedEnvironmentRegistry = vi.fn(); const mockGetSavedEnvironmentRecord = vi.fn((environmentId: EnvironmentId) => { return mockSavedRecords.find((record) => record.environmentId === environmentId) ?? null; }); const mockReadSavedEnvironmentBearerToken = vi.fn(); +const mockReadSavedEnvironmentCredential = vi.fn(); const mockRemoveSavedEnvironmentBearerToken = vi.fn(); const mockPatchRuntime = vi.fn(); const mockClearRuntime = vi.fn(); @@ -58,6 +75,8 @@ const mockClientGetConfig = vi.fn(async () => ({ label: "Remote environment", }, })); +const mockConnectManagedCloudEnvironment = vi.fn(); +const mockReadManagedRelayClerkToken = vi.fn(); vi.mock("@t3tools/shared/remote", async (importOriginal) => ({ ...(await importOriginal()), @@ -65,11 +84,19 @@ vi.mock("@t3tools/shared/remote", async (importOriginal) => ({ })); vi.mock("../../lib/runtime", () => ({ - remoteHttpRuntime: { + webRuntime: { runPromise: mockRemoteHttpRunPromise, }, })); +vi.mock("../../cloud/linkEnvironment", () => ({ + connectManagedCloudEnvironment: mockConnectManagedCloudEnvironment, +})); + +vi.mock("../../cloud/managedAuth", () => ({ + readManagedRelayClerkToken: mockReadManagedRelayClerkToken, +})); + vi.mock("~/localApi", () => ({ ensureLocalApi: () => ({ persistence: { @@ -84,6 +111,7 @@ vi.mock("./catalog", () => ({ listSavedEnvironmentRecords: mockListSavedEnvironmentRecords, persistSavedEnvironmentRecord: mockPersistSavedEnvironmentRecord, readSavedEnvironmentBearerToken: mockReadSavedEnvironmentBearerToken, + readSavedEnvironmentCredential: mockReadSavedEnvironmentCredential, removeSavedEnvironmentBearerToken: mockRemoveSavedEnvironmentBearerToken, toPersistedSavedEnvironmentRecord: mockToPersistedSavedEnvironmentRecord, useSavedEnvironmentRegistryStore: { @@ -105,6 +133,7 @@ vi.mock("./catalog", () => ({ }, waitForSavedEnvironmentRegistryHydration: vi.fn(), writeSavedEnvironmentBearerToken: mockWriteSavedEnvironmentBearerToken, + writeSavedEnvironmentCredential: mockWriteSavedEnvironmentCredential, })); vi.mock("./connection", async (importOriginal) => ({ @@ -114,6 +143,7 @@ vi.mock("./connection", async (importOriginal) => ({ vi.mock("@t3tools/client-runtime", async (importOriginal) => { const actual = await importOriginal(); + managedRelayDpopSigner = actual.ManagedRelayDpopSigner; return { ...actual, bootstrapRemoteBearerSession: mockBootstrapRemoteBearerSession, @@ -130,6 +160,7 @@ vi.mock("@t3tools/client-runtime", async (importOriginal) => { })), fetchRemoteEnvironmentDescriptor: mockFetchRemoteEnvironmentDescriptor, fetchRemoteSessionState: mockFetchRemoteSessionState, + fetchRemoteDpopSessionState: mockFetchRemoteDpopSessionState, resolveRemoteWebSocketConnectionUrl: mockResolveRemoteWebSocketConnectionUrl, }; }); @@ -172,20 +203,36 @@ describe("addSavedEnvironment", () => { credential: input.pairingCode ?? "pairing-code", }), ); - mockFetchRemoteEnvironmentDescriptor.mockResolvedValue({ - environmentId: EnvironmentId.make("environment-1"), - label: "Remote environment", + mockReadSavedEnvironmentCredential.mockImplementation(async () => { + const token = await mockReadSavedEnvironmentBearerToken(); + return token ? { version: 1, method: "bearer", token } : null; }); - mockBootstrapRemoteBearerSession.mockResolvedValue({ - access_token: "bearer-token", - scope: "orchestration:read orchestration:operate terminal:operate review:write relay:read", - }); - mockFetchRemoteSessionState.mockResolvedValue({ - authenticated: true, - scopes: ["orchestration:read", "access:write"], - }); - mockResolveRemoteWebSocketConnectionUrl.mockResolvedValue( - "wss://remote.example.com/?wsTicket=remote-token", + mockFetchRemoteEnvironmentDescriptor.mockReturnValue( + Effect.succeed({ + environmentId: EnvironmentId.make("environment-1"), + label: "Remote environment", + }), + ); + mockBootstrapRemoteBearerSession.mockReturnValue( + Effect.succeed({ + access_token: "bearer-token", + scope: "orchestration:read orchestration:operate terminal:operate review:write relay:read", + }), + ); + mockFetchRemoteSessionState.mockReturnValue( + Effect.succeed({ + authenticated: true, + scopes: ["orchestration:read", "access:write"], + }), + ); + mockFetchRemoteDpopSessionState.mockReturnValue( + Effect.succeed({ + authenticated: true, + scopes: ["orchestration:read", "access:write"], + }), + ); + mockResolveRemoteWebSocketConnectionUrl.mockReturnValue( + Effect.succeed("wss://remote.example.com/?wsTicket=remote-token"), ); mockFetchSshEnvironmentDescriptor.mockResolvedValue({ environmentId: EnvironmentId.make("environment-1"), @@ -197,6 +244,8 @@ describe("addSavedEnvironment", () => { }); mockPersistSavedEnvironmentRecord.mockResolvedValue(undefined); mockWriteSavedEnvironmentBearerToken.mockResolvedValue(false); + mockWriteSavedEnvironmentCredential.mockResolvedValue(true); + mockReadManagedRelayClerkToken.mockResolvedValue(null); mockSetSavedEnvironmentRegistry.mockResolvedValue(undefined); mockReadSavedEnvironmentBearerToken.mockResolvedValue(null); mockRemoveSavedEnvironmentBearerToken.mockResolvedValue(undefined); @@ -323,6 +372,94 @@ describe("addSavedEnvironment", () => { await resetEnvironmentServiceForTests(); }); + it("installs relay-managed environments with versioned DPoP credentials", async () => { + const { addManagedRelayEnvironment, resetEnvironmentServiceForTests } = + await import("./service"); + + await addManagedRelayEnvironment({ + environmentId: EnvironmentId.make("environment-1"), + label: "Managed remote", + httpBaseUrl: "https://managed.example.com/", + wsBaseUrl: "wss://managed.example.com/", + relayUrl: "https://relay.example.com", + accessToken: "managed-access-token", + }); + + expect(mockWriteSavedEnvironmentCredential).toHaveBeenCalledWith( + EnvironmentId.make("environment-1"), + { + version: 1, + method: "dpop", + accessToken: "managed-access-token", + }, + ); + expect(mockFetchRemoteDpopSessionState).toHaveBeenCalledWith({ + httpBaseUrl: "https://managed.example.com/", + accessToken: "managed-access-token", + dpopProof: "dpop-proof", + }); + await resetEnvironmentServiceForTests(); + }); + + it("renews expired managed DPoP credentials through the relay", async () => { + const environmentId = EnvironmentId.make("environment-1"); + mockSavedRecords = [ + { + environmentId, + label: "Managed remote", + httpBaseUrl: "https://managed.example.com/", + wsBaseUrl: "wss://managed.example.com/", + createdAt: "2026-05-25T00:00:00.000Z", + lastConnectedAt: null, + relayManaged: { relayUrl: "https://relay.example.com" }, + }, + ]; + mockReadSavedEnvironmentCredential.mockResolvedValue({ + version: 1, + method: "dpop", + accessToken: "expired-access-token", + }); + mockFetchRemoteDpopSessionState + .mockReturnValueOnce( + Effect.fail( + decodeEnvironmentAuthInvalidError({ + _tag: "EnvironmentAuthInvalidError", + code: "auth_invalid", + reason: "invalid_credential", + traceId: "trace-auth-expired", + }), + ), + ) + .mockReturnValue(Effect.succeed({ authenticated: true, scopes: ["orchestration:read"] })); + mockReadManagedRelayClerkToken.mockResolvedValue("clerk-token"); + mockConnectManagedCloudEnvironment.mockReturnValue( + Effect.succeed({ + environmentId, + label: "Managed remote", + httpBaseUrl: "https://managed.example.com/", + wsBaseUrl: "wss://managed.example.com/", + relayUrl: "https://relay.example.com", + accessToken: "renewed-access-token", + }), + ); + + const { reconnectSavedEnvironment, resetEnvironmentServiceForTests } = + await import("./service"); + await reconnectSavedEnvironment(environmentId); + + expect(mockConnectManagedCloudEnvironment).toHaveBeenCalledWith({ + clerkToken: "clerk-token", + relayUrl: "https://relay.example.com", + environment: expect.objectContaining({ environmentId }), + }); + expect(mockWriteSavedEnvironmentCredential).toHaveBeenCalledWith(environmentId, { + version: 1, + method: "dpop", + accessToken: "renewed-access-token", + }); + await resetEnvironmentServiceForTests(); + }); + it("removes an older ssh record when the same target returns a new environment id", async () => { mockWriteSavedEnvironmentBearerToken.mockResolvedValue(true); mockFetchSshEnvironmentDescriptor.mockResolvedValue({ @@ -424,7 +561,7 @@ describe("addSavedEnvironment", () => { reason: "invalid_credential", traceId: "trace-auth-test", }); - mockFetchRemoteSessionState.mockRejectedValueOnce(authError); + mockFetchRemoteSessionState.mockReturnValueOnce(Effect.fail(authError)); const { addSavedEnvironment, resetEnvironmentServiceForTests } = await import("./service"); @@ -747,9 +884,12 @@ describe("addSavedEnvironment", () => { readonly scopes: ReadonlyArray<"orchestration:read" | "access:write">; }) => void; mockFetchRemoteSessionState.mockReturnValue( - new Promise((resolve) => { - resolveSessionState = resolve; - }), + Effect.promise( + () => + new Promise((resolve) => { + resolveSessionState = resolve; + }), + ), ); const { diff --git a/apps/web/src/environments/runtime/service.savedEnvironments.test.ts b/apps/web/src/environments/runtime/service.savedEnvironments.test.ts index 7aca514962..e7c15ec6b3 100644 --- a/apps/web/src/environments/runtime/service.savedEnvironments.test.ts +++ b/apps/web/src/environments/runtime/service.savedEnvironments.test.ts @@ -11,6 +11,7 @@ const mockWaitForSavedEnvironmentRegistryHydration = vi.fn(); const mockListSavedEnvironmentRecords = vi.fn(); const mockSavedEnvironmentRegistrySubscribe = vi.fn(); const mockReadSavedEnvironmentBearerToken = vi.fn(); +const mockReadSavedEnvironmentCredential = vi.fn(); const mockGetSavedEnvironmentRecord = vi.fn(); function MockWsTransport() { @@ -31,7 +32,7 @@ vi.mock("../primary", () => ({ })); vi.mock("../../lib/runtime", () => ({ - remoteHttpRuntime: { + webRuntime: { runPromise: mockRemoteHttpRunPromise, }, })); @@ -42,6 +43,7 @@ vi.mock("./catalog", () => ({ listSavedEnvironmentRecords: mockListSavedEnvironmentRecords, persistSavedEnvironmentRecord: vi.fn(), readSavedEnvironmentBearerToken: mockReadSavedEnvironmentBearerToken, + readSavedEnvironmentCredential: mockReadSavedEnvironmentCredential, removeSavedEnvironmentBearerToken: vi.fn(), useSavedEnvironmentRegistryStore: { subscribe: mockSavedEnvironmentRegistrySubscribe, @@ -61,6 +63,7 @@ vi.mock("./catalog", () => ({ }, waitForSavedEnvironmentRegistryHydration: mockWaitForSavedEnvironmentRegistryHydration, writeSavedEnvironmentBearerToken: vi.fn(), + writeSavedEnvironmentCredential: vi.fn(), })); vi.mock("./connection", async (importOriginal) => ({ @@ -231,6 +234,10 @@ describe("saved environment startup", () => { mockSavedEnvironmentRegistrySubscribe.mockReturnValue(() => undefined); mockWaitForSavedEnvironmentRegistryHydration.mockResolvedValue(undefined); mockReadSavedEnvironmentBearerToken.mockResolvedValue("saved-bearer-token"); + mockReadSavedEnvironmentCredential.mockImplementation(async () => { + const token = await mockReadSavedEnvironmentBearerToken(); + return token ? { version: 1, method: "bearer", token } : null; + }); mockCreateWsRpcClient.mockImplementation(() => createClient()); mockCreateEnvironmentConnection.mockImplementation((input) => { if (input.kind === "saved") { diff --git a/apps/web/src/environments/runtime/service.threadSubscriptions.test.ts b/apps/web/src/environments/runtime/service.threadSubscriptions.test.ts index ec2bcc4110..33e2b0aa8c 100644 --- a/apps/web/src/environments/runtime/service.threadSubscriptions.test.ts +++ b/apps/web/src/environments/runtime/service.threadSubscriptions.test.ts @@ -18,6 +18,7 @@ const mockWaitForSavedEnvironmentRegistryHydration = vi.fn(); const mockListSavedEnvironmentRecords = vi.fn(); const mockGetSavedEnvironmentRecord = vi.fn(); const mockReadSavedEnvironmentBearerToken = vi.fn(); +const mockReadSavedEnvironmentCredential = vi.fn(); const mockSavedEnvironmentRegistrySubscribe = vi.fn(); const mockGetPrimaryKnownEnvironment = vi.hoisted(() => vi.fn()); const mockFetchRemoteSessionState = vi.fn(); @@ -35,7 +36,7 @@ vi.mock("../primary", () => ({ })); vi.mock("../../lib/runtime", () => ({ - remoteHttpRuntime: { + webRuntime: { runPromise: mockRemoteHttpRunPromise, }, })); @@ -46,6 +47,7 @@ vi.mock("./catalog", () => ({ listSavedEnvironmentRecords: mockListSavedEnvironmentRecords, persistSavedEnvironmentRecord: vi.fn(), readSavedEnvironmentBearerToken: mockReadSavedEnvironmentBearerToken, + readSavedEnvironmentCredential: mockReadSavedEnvironmentCredential, removeSavedEnvironmentBearerToken: vi.fn(), useSavedEnvironmentRegistryStore: { subscribe: mockSavedEnvironmentRegistrySubscribe, @@ -65,6 +67,7 @@ vi.mock("./catalog", () => ({ }, waitForSavedEnvironmentRegistryHydration: mockWaitForSavedEnvironmentRegistryHydration, writeSavedEnvironmentBearerToken: vi.fn(), + writeSavedEnvironmentCredential: vi.fn(), })); vi.mock("./connection", async (importOriginal) => ({ @@ -301,6 +304,10 @@ describe("retainThreadDetailSubscription", () => { mockListSavedEnvironmentRecords.mockReturnValue([]); mockGetSavedEnvironmentRecord.mockReturnValue(null); mockReadSavedEnvironmentBearerToken.mockResolvedValue(null); + mockReadSavedEnvironmentCredential.mockImplementation(async () => { + const token = await mockReadSavedEnvironmentBearerToken(); + return token ? { version: 1, method: "bearer", token } : null; + }); mockFetchRemoteSessionState.mockResolvedValue({ authenticated: true, scopes: ["orchestration:read"], diff --git a/apps/web/src/environments/runtime/service.ts b/apps/web/src/environments/runtime/service.ts index 406a855d3c..38c62f55ac 100644 --- a/apps/web/src/environments/runtime/service.ts +++ b/apps/web/src/environments/runtime/service.ts @@ -1,6 +1,5 @@ import { AuthEnvironmentScope, - AuthStandardClientScopes, type DesktopSshEnvironmentBootstrap, type DesktopSshEnvironmentTarget, type EnvironmentId, @@ -16,12 +15,17 @@ import { type WsRpcClient, bootstrapRemoteBearerSession, fetchRemoteEnvironmentDescriptor, + fetchRemoteDpopSessionState, fetchRemoteSessionState, + type ManagedRelayDpopProofInput, + ManagedRelayDpopSigner, + resolveRemoteDpopWebSocketConnectionUrl, resolveRemoteWebSocketConnectionUrl, } from "@t3tools/client-runtime"; import { type QueryClient } from "@tanstack/react-query"; import { Throttler } from "@tanstack/react-pacer"; +import * as Effect from "effect/Effect"; import * as Schema from "effect/Schema"; import { createKnownEnvironment, @@ -40,21 +44,25 @@ import { ensureLocalApi } from "~/localApi"; import { collectActiveTerminalUiThreadKeys } from "~/lib/terminalUiStateCleanup"; import { deriveOrchestrationBatchEffects } from "~/orchestrationEventEffects"; import { getPrimaryKnownEnvironment } from "../primary"; -import { remoteHttpRuntime } from "../../lib/runtime"; +import { webRuntime } from "../../lib/runtime"; +import { connectManagedCloudEnvironment } from "../../cloud/linkEnvironment"; +import { readManagedRelayClerkToken } from "../../cloud/managedAuth"; import { getSavedEnvironmentRecord, hasSavedEnvironmentRegistryHydrated, listSavedEnvironmentRecords, persistSavedEnvironmentRecord, - readSavedEnvironmentBearerToken, + readSavedEnvironmentCredential, removeSavedEnvironmentBearerToken, type SavedEnvironmentRecord, + type SavedEnvironmentCredential, toPersistedSavedEnvironmentRecord, useSavedEnvironmentRegistryStore, useSavedEnvironmentRuntimeStore, waitForSavedEnvironmentRegistryHydration, writeSavedEnvironmentBearerToken, + writeSavedEnvironmentCredential, } from "./catalog"; import { createEnvironmentConnection, @@ -159,6 +167,12 @@ const INITIAL_SERVER_CONFIG_SNAPSHOT_WAIT_MS = 150; const NOOP = () => undefined; const SSH_HTTP_STATUS_RE = /^\[ssh_http:(\d+)\]\s/u; +const createManagedRelayDpopProof = (input: ManagedRelayDpopProofInput) => + Effect.gen(function* () { + const signer = yield* ManagedRelayDpopSigner; + return yield* signer.createProof(input); + }); + function createDeferredPromise() { let resolve: ((value: T) => void) | null = null; const promise = new Promise((nextResolve) => { @@ -1156,7 +1170,7 @@ function createPrimaryEnvironmentClient( function createSavedEnvironmentClient( environmentId: EnvironmentId, - bearerToken: string, + credentialRef: { current: SavedEnvironmentCredential }, ): WsRpcClient { useSavedEnvironmentRuntimeStore.getState().ensure(environmentId); @@ -1167,19 +1181,70 @@ function createSavedEnvironmentClient( if (!record) { throw new Error(`Saved environment ${environmentId} not found.`); } - return record.desktopSsh - ? await resolveDesktopSshWebSocketConnectionUrl( - record.wsBaseUrl, - record.httpBaseUrl, - bearerToken, - ) - : await remoteHttpRuntime.runPromise( - resolveRemoteWebSocketConnectionUrl({ - wsBaseUrl: record.wsBaseUrl, - httpBaseUrl: record.httpBaseUrl, - bearerToken, - }), + const credential = credentialRef.current; + if (record.desktopSsh) { + if (credential.method !== "bearer") { + throw new Error("SSH environments require bearer credentials."); + } + return await resolveDesktopSshWebSocketConnectionUrl( + record.wsBaseUrl, + record.httpBaseUrl, + credential.token, + ); + } + if (credential.method === "dpop") { + try { + return await webRuntime.runPromise( + createManagedRelayDpopProof({ + method: "POST", + url: new URL("/api/auth/websocket-ticket", record.httpBaseUrl).toString(), + accessToken: credential.accessToken, + }).pipe( + Effect.flatMap((proof) => + resolveRemoteDpopWebSocketConnectionUrl({ + wsBaseUrl: record.wsBaseUrl, + httpBaseUrl: record.httpBaseUrl, + accessToken: credential.accessToken, + dpopProof: proof, + }), + ), + ), ); + } catch (error) { + if (!isEnvironmentAuthInvalidError(error)) { + throw error; + } + const renewed = await renewManagedRelayCredential(record); + if (!renewed || renewed.credential.method !== "dpop") { + throw error; + } + const renewedCredential = renewed.credential; + credentialRef.current = renewedCredential; + return await webRuntime.runPromise( + createManagedRelayDpopProof({ + method: "POST", + url: new URL("/api/auth/websocket-ticket", renewed.record.httpBaseUrl).toString(), + accessToken: renewedCredential.accessToken, + }).pipe( + Effect.flatMap((proof) => + resolveRemoteDpopWebSocketConnectionUrl({ + wsBaseUrl: renewed.record.wsBaseUrl, + httpBaseUrl: renewed.record.httpBaseUrl, + accessToken: renewedCredential.accessToken, + dpopProof: proof, + }), + ), + ), + ); + } + } + return await webRuntime.runPromise( + resolveRemoteWebSocketConnectionUrl({ + wsBaseUrl: record.wsBaseUrl, + httpBaseUrl: record.httpBaseUrl, + bearerToken: credential.token, + }), + ); }, { getConnectionLabel: () => getSavedEnvironmentRecord(environmentId)?.label ?? null, @@ -1221,7 +1286,7 @@ function createSavedEnvironmentClient( async function refreshSavedEnvironmentMetadata( environmentId: EnvironmentId, - bearerToken: string, + credential: SavedEnvironmentCredential, client: WsRpcClient, scopeHint?: ReadonlyArray | null, configHint?: ServerConfig | null, @@ -1234,13 +1299,31 @@ async function refreshSavedEnvironmentMetadata( const [serverConfig, sessionState] = await Promise.all([ configHint ? Promise.resolve(configHint) : client.server.getConfig(), record.desktopSsh - ? fetchDesktopSshSessionState(record.httpBaseUrl, bearerToken) - : remoteHttpRuntime.runPromise( - fetchRemoteSessionState({ - httpBaseUrl: record.httpBaseUrl, - bearerToken, - }), - ), + ? credential.method === "bearer" + ? fetchDesktopSshSessionState(record.httpBaseUrl, credential.token) + : Promise.reject(new Error("SSH environments require bearer credentials.")) + : credential.method === "dpop" + ? webRuntime.runPromise( + createManagedRelayDpopProof({ + method: "GET", + url: new URL("/api/auth/session", record.httpBaseUrl).toString(), + accessToken: credential.accessToken, + }).pipe( + Effect.flatMap((proof) => + fetchRemoteDpopSessionState({ + httpBaseUrl: record.httpBaseUrl, + accessToken: credential.accessToken, + dpopProof: proof, + }), + ), + ), + ) + : webRuntime.runPromise( + fetchRemoteSessionState({ + httpBaseUrl: record.httpBaseUrl, + bearerToken: credential.token, + }), + ), ]); useSavedEnvironmentRuntimeStore.getState().patch(record.environmentId, { @@ -1254,6 +1337,52 @@ async function refreshSavedEnvironmentMetadata( .rename(record.environmentId, serverConfig.environment.label); } +async function renewManagedRelayCredential(record: SavedEnvironmentRecord): Promise<{ + readonly record: SavedEnvironmentRecord; + readonly credential: SavedEnvironmentCredential; +} | null> { + if (!record.relayManaged) { + return null; + } + const clerkToken = await readManagedRelayClerkToken(); + if (!clerkToken) { + return null; + } + const connected = await webRuntime.runPromise( + connectManagedCloudEnvironment({ + clerkToken, + relayUrl: record.relayManaged.relayUrl, + environment: { + environmentId: record.environmentId, + label: record.label, + linkedAt: record.createdAt, + endpoint: { + httpBaseUrl: record.httpBaseUrl, + wsBaseUrl: record.wsBaseUrl, + providerKind: "cloudflare_tunnel", + }, + }, + }), + ); + const nextRecord: SavedEnvironmentRecord = { + ...record, + label: connected.label, + httpBaseUrl: connected.httpBaseUrl, + wsBaseUrl: connected.wsBaseUrl, + }; + const credential: SavedEnvironmentCredential = { + version: 1, + method: "dpop", + accessToken: connected.accessToken, + }; + await persistSavedEnvironmentRecord(nextRecord); + if (!(await writeSavedEnvironmentCredential(nextRecord.environmentId, credential))) { + throw new Error("Unable to persist refreshed managed environment credentials."); + } + useSavedEnvironmentRegistryStore.getState().upsert(nextRecord); + return { record: nextRecord, credential }; +} + function registerConnection(connection: EnvironmentConnection): EnvironmentConnection { const existing = environmentConnections.get(connection.environmentId); if (existing && existing !== connection) { @@ -1320,8 +1449,10 @@ async function ensureSavedEnvironmentConnection( options?: { readonly client?: WsRpcClient; readonly bearerToken?: string; + readonly credential?: SavedEnvironmentCredential; readonly scopes?: ReadonlyArray | null; readonly serverConfig?: ServerConfig | null; + readonly allowManagedRenewal?: boolean; }, ): Promise { const existing = environmentConnections.get(record.environmentId); @@ -1340,14 +1471,17 @@ async function ensureSavedEnvironmentConnection( promise: Promise.resolve().then(async () => { let activeRecord = record; let scopeHint = options?.scopes ?? null; - let bearerToken = - options?.bearerToken ?? (await readSavedEnvironmentBearerToken(record.environmentId)); - if (!bearerToken) { + let credential = + options?.credential ?? + (options?.bearerToken + ? ({ version: 1, method: "bearer", token: options.bearerToken } as const) + : await readSavedEnvironmentCredential(record.environmentId)); + if (!credential) { if (record.desktopSsh) { const issued = await issueDesktopSshBearerSession(record); activeRecord = issued.record; - bearerToken = issued.bearerToken; - scopeHint = [...AuthStandardClientScopes]; + credential = { version: 1, method: "bearer", token: issued.bearerToken }; + scopeHint = issued.scopes; } else { useSavedEnvironmentRuntimeStore.getState().patch(record.environmentId, { authState: "requires-auth", @@ -1363,10 +1497,10 @@ async function ensureSavedEnvironmentConnection( activeRecord = prepared.record; } - const activeBearerToken = bearerToken; + const activeCredential = { current: credential }; const client = options?.client ?? - createSavedEnvironmentClient(activeRecord.environmentId, activeBearerToken); + createSavedEnvironmentClient(activeRecord.environmentId, activeCredential); const initialConfigSnapshot = createDeferredPromise(); const knownEnvironment = createKnownEnvironment({ id: activeRecord.environmentId, @@ -1387,7 +1521,7 @@ async function ensureSavedEnvironmentConnection( refreshMetadata: async () => { await refreshSavedEnvironmentMetadata( activeRecord.environmentId, - activeBearerToken, + activeCredential.current, client, ); }, @@ -1416,7 +1550,7 @@ async function ensureSavedEnvironmentConnection( )); await refreshSavedEnvironmentMetadata( activeRecord.environmentId, - activeBearerToken, + activeCredential.current, client, scopeHint, initialServerConfig, @@ -1429,20 +1563,41 @@ async function ensureSavedEnvironmentConnection( throw error; } if (!activeRecord.desktopSsh) { + if ( + activeCredential.current.method === "dpop" && + options?.allowManagedRenewal !== false + ) { + const renewed = await renewManagedRelayCredential(activeRecord); + if (renewed) { + await connection.dispose().catch(() => undefined); + pendingSavedEnvironmentConnections.delete(activeRecord.environmentId); + return await ensureSavedEnvironmentConnection(renewed.record, { + credential: renewed.credential, + scopes: scopeHint, + serverConfig: options?.serverConfig ?? null, + allowManagedRenewal: false, + }); + } + } await removeSavedEnvironmentBearerToken(activeRecord.environmentId); - throw new Error("Saved environment credential expired. Pair it again.", { - cause: error, - }); + throw new Error( + activeCredential.current.method === "dpop" + ? "Managed tunnel credential expired. Connect it again from T3 Cloud." + : "Saved environment credential expired. Pair it again.", + { + cause: error, + }, + ); } const issued = await issueDesktopSshBearerSession(activeRecord); activeRecord = issued.record; - bearerToken = issued.bearerToken; - scopeHint = [...AuthStandardClientScopes]; + credential = { version: 1, method: "bearer", token: issued.bearerToken }; + scopeHint = issued.scopes; await connection.dispose().catch(() => undefined); pendingSavedEnvironmentConnections.delete(activeRecord.environmentId); return await ensureSavedEnvironmentConnection(activeRecord, { - bearerToken, + credential, scopes: scopeHint, serverConfig: options?.serverConfig ?? null, }); @@ -1647,7 +1802,7 @@ export async function reconnectSavedEnvironment(environmentId: EnvironmentId): P await removeConnection(environmentId).catch(() => false); await ensureSavedEnvironmentConnection(issued.record, { bearerToken: issued.bearerToken, - scopes: [...AuthStandardClientScopes], + scopes: issued.scopes, }); return; } catch (recoveryError) { @@ -1686,7 +1841,7 @@ export async function addSavedEnvironment(input: { }); const descriptor = input.desktopSsh ? await fetchDesktopSshEnvironmentDescriptor(resolvedTarget.httpBaseUrl) - : await remoteHttpRuntime.runPromise( + : await webRuntime.runPromise( fetchRemoteEnvironmentDescriptor({ httpBaseUrl: resolvedTarget.httpBaseUrl, }), @@ -1701,7 +1856,7 @@ export async function addSavedEnvironment(input: { const bearerSession = input.desktopSsh ? await bootstrapDesktopSshBearerSession(resolvedTarget.httpBaseUrl, resolvedTarget.credential) - : await remoteHttpRuntime.runPromise( + : await webRuntime.runPromise( bootstrapRemoteBearerSession({ httpBaseUrl: resolvedTarget.httpBaseUrl, credential: resolvedTarget.credential, @@ -1741,6 +1896,40 @@ export async function addSavedEnvironment(input: { return record; } +export async function addManagedRelayEnvironment(input: { + readonly environmentId: EnvironmentId; + readonly label: string; + readonly httpBaseUrl: string; + readonly wsBaseUrl: string; + readonly relayUrl: string; + readonly accessToken: string; +}): Promise { + const existingRecord = getSavedEnvironmentRecord(input.environmentId); + const record: SavedEnvironmentRecord = { + environmentId: input.environmentId, + label: input.label.trim() || existingRecord?.label || "Managed environment", + httpBaseUrl: input.httpBaseUrl, + wsBaseUrl: input.wsBaseUrl, + createdAt: existingRecord?.createdAt ?? isoNow(), + lastConnectedAt: isoNow(), + relayManaged: { relayUrl: input.relayUrl }, + }; + const credential: SavedEnvironmentCredential = { + version: 1, + method: "dpop", + accessToken: input.accessToken, + }; + + await persistSavedEnvironmentRecord(record); + if (!(await writeSavedEnvironmentCredential(record.environmentId, credential))) { + throw new Error("Unable to persist managed environment credentials."); + } + useSavedEnvironmentRegistryStore.getState().upsert(record); + await removeConnection(record.environmentId).catch(() => false); + await ensureSavedEnvironmentConnection(record, { credential }); + return record; +} + export async function connectDesktopSshEnvironment( target: DesktopSshEnvironmentTarget, options?: { label?: string }, diff --git a/apps/web/src/hooks/useTheme.ts b/apps/web/src/hooks/useTheme.ts index cd254c9754..78d063a960 100644 --- a/apps/web/src/hooks/useTheme.ts +++ b/apps/web/src/hooks/useTheme.ts @@ -109,7 +109,7 @@ function applyTheme(theme: Theme, suppressTransitions = false) { function syncDesktopTheme(theme: Theme) { if (typeof window === "undefined") return; const bridge = window.desktopBridge; - if (!bridge || lastDesktopTheme === theme) { + if (!bridge || typeof bridge.setTheme !== "function" || lastDesktopTheme === theme) { return; } diff --git a/apps/web/src/hostedPairing.ts b/apps/web/src/hostedPairing.ts index cc547323f8..2caf844af9 100644 --- a/apps/web/src/hostedPairing.ts +++ b/apps/web/src/hostedPairing.ts @@ -10,7 +10,7 @@ export interface HostedPairingRequest { export type HostedAppChannel = "latest" | "nightly"; -function configuredHostedAppUrl(): string { +export function configuredHostedAppUrl(): string { return import.meta.env.VITE_HOSTED_APP_URL?.trim() || DEFAULT_HOSTED_APP_URL; } diff --git a/apps/web/src/lib/runtime.ts b/apps/web/src/lib/runtime.ts index 8c1f0f0a5b..abb885e3bb 100644 --- a/apps/web/src/lib/runtime.ts +++ b/apps/web/src/lib/runtime.ts @@ -9,7 +9,17 @@ import { primaryEnvironmentHttpClientLive, } from "../environments/primary/httpClient"; -export const remoteHttpRuntime = ManagedRuntime.make(remoteHttpClientLayer(globalThis.fetch)); +import { browserCryptoLayer } from "../cloud/dpop"; +import { webManagedRelayClientLayer } from "../cloud/managedRelayLayer"; + +function configuredRelayUrl(): string { + const value = (import.meta.env.VITE_T3_RELAY_URL as string | undefined)?.trim(); + return value ? value.replace(/\/+$/g, "") : "http://relay.invalid"; +} + +const webHttpClientLayer = remoteHttpClientLayer(globalThis.fetch); + +export const remoteHttpRuntime = ManagedRuntime.make(webHttpClientLayer); const primaryHttpRuntime = ManagedRuntime.make( primaryEnvironmentHttpClientLive.pipe( @@ -37,3 +47,13 @@ export const runPrimaryHttp = (effect: Effect.Effect = {}): DesktopBridg setTheme: async () => undefined, showContextMenu: async () => null, openExternal: async () => true, + createCloudAuthRequest: async () => "t3code-dev://auth/callback?t3_state=test", + getCloudAuthToken: async () => null, + setCloudAuthToken: async () => true, + clearCloudAuthToken: async () => undefined, + fetchCloudAuth: async () => ({ + ok: true, + status: 200, + statusText: "OK", + headers: {}, + body: "", + }), + onCloudAuthCallback: () => () => undefined, onMenuAction: () => () => undefined, getUpdateState: async () => { throw new Error("getUpdateState not implemented in test"); diff --git a/apps/web/src/main.tsx b/apps/web/src/main.tsx index 68a7dfaa93..a665bc4d43 100644 --- a/apps/web/src/main.tsx +++ b/apps/web/src/main.tsx @@ -1,5 +1,6 @@ import React from "react"; import ReactDOM from "react-dom/client"; +import { ClerkProvider } from "@clerk/react"; import { RouterProvider } from "@tanstack/react-router"; import { createHashHistory, createBrowserHistory } from "@tanstack/react-router"; @@ -7,6 +8,8 @@ import "@xterm/xterm/css/xterm.css"; import "./index.css"; import { isElectron } from "./env"; +import { DesktopClerkProvider } from "./cloud/desktopClerk"; +import { ManagedRelayAuthProvider } from "./cloud/managedAuth"; import { getRouter } from "./router"; import { APP_DISPLAY_NAME } from "./branding"; import { syncDocumentWindowControlsOverlayClass } from "./lib/windowControlsOverlay"; @@ -22,8 +25,25 @@ if (isElectron) { document.title = APP_DISPLAY_NAME; +const clerkPublishableKey = import.meta.env.VITE_CLERK_PUBLISHABLE_KEY as string | undefined; +const cloudWaitlistUrl = "/settings/cloud"; + +const app = ; + ReactDOM.createRoot(document.getElementById("root") as HTMLElement).render( - + {clerkPublishableKey ? ( + isElectron ? ( + + {app} + + ) : ( + + {app} + + ) + ) : ( + app + )} , ); diff --git a/apps/web/src/routeTree.gen.ts b/apps/web/src/routeTree.gen.ts index 3a9140e278..cafba0f829 100644 --- a/apps/web/src/routeTree.gen.ts +++ b/apps/web/src/routeTree.gen.ts @@ -19,6 +19,7 @@ import { Route as SettingsKeybindingsRouteImport } from './routes/settings.keybi import { Route as SettingsGeneralRouteImport } from './routes/settings.general' import { Route as SettingsDiagnosticsRouteImport } from './routes/settings.diagnostics' import { Route as SettingsConnectionsRouteImport } from './routes/settings.connections' +import { Route as SettingsCloudRouteImport } from './routes/settings.cloud' import { Route as SettingsArchivedRouteImport } from './routes/settings.archived' import { Route as ChatDraftDraftIdRouteImport } from './routes/_chat.draft.$draftId' import { Route as ChatEnvironmentIdThreadIdRouteImport } from './routes/_chat.$environmentId.$threadId' @@ -72,6 +73,11 @@ const SettingsConnectionsRoute = SettingsConnectionsRouteImport.update({ path: '/connections', getParentRoute: () => SettingsRoute, } as any) +const SettingsCloudRoute = SettingsCloudRouteImport.update({ + id: '/cloud', + path: '/cloud', + getParentRoute: () => SettingsRoute, +} as any) const SettingsArchivedRoute = SettingsArchivedRouteImport.update({ id: '/archived', path: '/archived', @@ -94,6 +100,7 @@ export interface FileRoutesByFullPath { '/pair': typeof PairRoute '/settings': typeof SettingsRouteWithChildren '/settings/archived': typeof SettingsArchivedRoute + '/settings/cloud': typeof SettingsCloudRoute '/settings/connections': typeof SettingsConnectionsRoute '/settings/diagnostics': typeof SettingsDiagnosticsRoute '/settings/general': typeof SettingsGeneralRoute @@ -107,6 +114,7 @@ export interface FileRoutesByTo { '/pair': typeof PairRoute '/settings': typeof SettingsRouteWithChildren '/settings/archived': typeof SettingsArchivedRoute + '/settings/cloud': typeof SettingsCloudRoute '/settings/connections': typeof SettingsConnectionsRoute '/settings/diagnostics': typeof SettingsDiagnosticsRoute '/settings/general': typeof SettingsGeneralRoute @@ -123,6 +131,7 @@ export interface FileRoutesById { '/pair': typeof PairRoute '/settings': typeof SettingsRouteWithChildren '/settings/archived': typeof SettingsArchivedRoute + '/settings/cloud': typeof SettingsCloudRoute '/settings/connections': typeof SettingsConnectionsRoute '/settings/diagnostics': typeof SettingsDiagnosticsRoute '/settings/general': typeof SettingsGeneralRoute @@ -140,6 +149,7 @@ export interface FileRouteTypes { | '/pair' | '/settings' | '/settings/archived' + | '/settings/cloud' | '/settings/connections' | '/settings/diagnostics' | '/settings/general' @@ -153,6 +163,7 @@ export interface FileRouteTypes { | '/pair' | '/settings' | '/settings/archived' + | '/settings/cloud' | '/settings/connections' | '/settings/diagnostics' | '/settings/general' @@ -168,6 +179,7 @@ export interface FileRouteTypes { | '/pair' | '/settings' | '/settings/archived' + | '/settings/cloud' | '/settings/connections' | '/settings/diagnostics' | '/settings/general' @@ -257,6 +269,13 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof SettingsConnectionsRouteImport parentRoute: typeof SettingsRoute } + '/settings/cloud': { + id: '/settings/cloud' + path: '/cloud' + fullPath: '/settings/cloud' + preLoaderRoute: typeof SettingsCloudRouteImport + parentRoute: typeof SettingsRoute + } '/settings/archived': { id: '/settings/archived' path: '/archived' @@ -297,6 +316,7 @@ const ChatRouteWithChildren = ChatRoute._addFileChildren(ChatRouteChildren) interface SettingsRouteChildren { SettingsArchivedRoute: typeof SettingsArchivedRoute + SettingsCloudRoute: typeof SettingsCloudRoute SettingsConnectionsRoute: typeof SettingsConnectionsRoute SettingsDiagnosticsRoute: typeof SettingsDiagnosticsRoute SettingsGeneralRoute: typeof SettingsGeneralRoute @@ -307,6 +327,7 @@ interface SettingsRouteChildren { const SettingsRouteChildren: SettingsRouteChildren = { SettingsArchivedRoute: SettingsArchivedRoute, + SettingsCloudRoute: SettingsCloudRoute, SettingsConnectionsRoute: SettingsConnectionsRoute, SettingsDiagnosticsRoute: SettingsDiagnosticsRoute, SettingsGeneralRoute: SettingsGeneralRoute, diff --git a/apps/web/src/routes/_chat.index.tsx b/apps/web/src/routes/_chat.index.tsx index 98a125bdfe..32587c0f18 100644 --- a/apps/web/src/routes/_chat.index.tsx +++ b/apps/web/src/routes/_chat.index.tsx @@ -48,13 +48,13 @@ function HostedStaticOnboardingState() { Connect an environment to get started - Open a pairing link from your T3 Code desktop app or add a reachable backend - manually. Your saved environments stay in this browser. + Sign in to T3 Cloud to connect a linked environment through its managed tunnel, or + add a reachable backend manually.
-
diff --git a/apps/web/src/routes/settings.cloud.tsx b/apps/web/src/routes/settings.cloud.tsx new file mode 100644 index 0000000000..e91eb70e81 --- /dev/null +++ b/apps/web/src/routes/settings.cloud.tsx @@ -0,0 +1,7 @@ +import { createFileRoute } from "@tanstack/react-router"; + +import { CloudSettingsPanel } from "../components/settings/CloudSettings"; + +export const Route = createFileRoute("/settings/cloud")({ + component: CloudSettingsPanel, +}); diff --git a/apps/web/src/vite-env.d.ts b/apps/web/src/vite-env.d.ts index 59704466ac..c00ade5912 100644 --- a/apps/web/src/vite-env.d.ts +++ b/apps/web/src/vite-env.d.ts @@ -7,6 +7,7 @@ interface ImportMetaEnv { readonly VITE_WS_URL: string; readonly VITE_HOSTED_APP_URL: string; readonly VITE_HOSTED_APP_CHANNEL: string; + readonly VITE_CLERK_PUBLISHABLE_KEY: string; readonly APP_VERSION: string; } diff --git a/docs/relay-observability.md b/docs/relay-observability.md new file mode 100644 index 0000000000..d6db81ba60 --- /dev/null +++ b/docs/relay-observability.md @@ -0,0 +1,40 @@ +# Relay observability + +The relay Alchemy stack owns a focused Axiom trace setup: + +- `t3-code-relay-traces`, an OpenTelemetry trace dataset for Worker requests +- `t3-code-relay-otel-ingest`, a dataset-scoped ingest token bound to the Worker +- `t3-code-relay-readonly-query`, a dataset-scoped token for scripted diagnostics +- `t3-code-relay-recent-spans`, a view of recent request and endpoint spans + +Deploy from `infra/relay` with the normal Alchemy workflow: + +```sh +bun run deploy +``` + +Alchemy resolves Axiom deployment credentials through its provider. At runtime, the Worker +receives only the scoped ingest token; it does not receive the diagnostics query token. + +The Worker emits Effect's built-in HTTP server spans plus endpoint and database child spans. +Effect's OpenTelemetry exporter stores semantic HTTP attributes below the `attributes.` prefix. +For example: + +```apl +['t3-code-relay-traces'] +| where name startswith 'http.server' +| project _time, name, trace_id, duration, + ['attributes.http.request.method'], + ['attributes.url.path'], + ['attributes.http.response.status_code'] +| order by _time desc +| limit 200 +``` + +Endpoint failure annotations and other relay-specific attributes are also emitted in the +`attributes.custom` map when present on a span, for example +`['attributes.custom']['relay.endpoint']`. + +Agents should prefer the provisioned view or APL queries for completed incidents instead of +tailing the Cloudflare Worker. Use the read-only query token when scripted access is needed; +keep the ingest token reserved for the Worker. diff --git a/docs/t3-cloud-clerk.md b/docs/t3-cloud-clerk.md new file mode 100644 index 0000000000..376688cf75 --- /dev/null +++ b/docs/t3-cloud-clerk.md @@ -0,0 +1,81 @@ +# T3 Cloud Clerk Setup + +T3 Cloud uses one Clerk application for web, desktop, and mobile authentication. The relay accepts +Clerk JWTs only when they are generated from the `t3-relay` template with the relay URL as the +audience. + +## Application Keys + +Use keys from the same Clerk instance in each location: + +| Consumer | Configuration | Value | +| ------------------------ | --------------------------------------- | ----------------------------------------------------- | +| Web and desktop renderer | `apps/web/.env` | `VITE_CLERK_PUBLISHABLE_KEY=` | +| Mobile build | `apps/mobile/.env` or build environment | `EXPO_PUBLIC_CLERK_PUBLISHABLE_KEY=` | +| Relay deployment | Alchemy secret | `CLERK_SECRET_KEY=` | + +Never put `CLERK_SECRET_KEY` in a client application environment. + +## JWT Template + +In **Clerk Dashboard > JWT templates**, create a template with: + +| Setting | Value | +| ------- | ------------------------------------------------------ | +| Name | `t3-relay` | +| Claims | `{ "aud": "https://t3code-relay.ineededadomain.com" }` | + +The `aud` value must be the deployed relay public URL, with no trailing slash, and must match +`VITE_T3_RELAY_URL` and `T3_RELAY_URL`. If the relay domain changes, update all three values. + +## Desktop OAuth Redirect Allowlist + +The desktop app opens OAuth in the system browser and returns to the app with a custom URL scheme. +In **Clerk Dashboard > Native applications**, enable native application support and add these +entries under the mobile SSO redirect allowlist: + +```text +t3code-dev://auth/callback +t3code://auth/callback +``` + +The first entry is for local desktop development. The second is for packaged desktop builds. +The app also adds a request-scoped `t3_state` query parameter and validates it on callback. + +The current mobile UI uses Clerk's native authentication view. If a future mobile browser OAuth +flow uses a custom redirect URI, add that exact URI to the same allowlist. + +## Enable Waitlist Access + +For a private beta where people should request access, use **Clerk Dashboard > Waitlist**: + +1. Toggle on **Enable waitlist** and save. +2. Review requests on the same page and select **Invite** or **Deny**. + +Signed-out web and desktop users see Clerk's waitlist enrollment as the T3 Cloud page content, +while approved signed-in users see cloud settings. The browser app also uses `/settings/cloud` as +its Clerk waitlist URL. + +On mobile, signed-out users open **Settings > T3 Account** to reach `/settings/waitlist` within the +Settings form sheet. It submits enrollment through Clerk's `useWaitlist()` flow because the prebuilt +`` component is web-only in the Expo SDK. Approved users can use **Sign in** from that +screen. + +## Alternative: Known-User Allowlist + +For a closed beta where all permitted users are known in advance, use an allowlist instead of a +request-and-approval waitlist: + +To restrict the beta to permitted email addresses or domains: + +1. In **Clerk Dashboard > Restrictions > Allowlist**, add each permitted email address or email + domain. +2. Enable the allowlist and save. +3. Alternatively, enable **Restricted mode** when all new users must be explicitly invited or + manually created without a waitlist request flow. + +Do not enable an empty allowlist: it blocks all new sign-ups. + +Clerk allowlists control who can sign up. They do not revoke an existing user's active cloud +access. To remove an already-created user's access, ban that user in Clerk so their active +sessions are ended and future sign-ins are rejected. diff --git a/docs/t3-code-cloud-auth-flow.html b/docs/t3-code-cloud-auth-flow.html new file mode 100644 index 0000000000..67d01f2a75 --- /dev/null +++ b/docs/t3-code-cloud-auth-flow.html @@ -0,0 +1,1820 @@ + + + + + + T3 Code Cloud Control Plane and Managed Endpoint Flow + + + +
+
+
Draft architecture
+

T3 Code Cloud Control Plane and Managed Endpoint Flow

+

+ A concrete topology for one user with a MacBook Pro desktop environment, a headless Mac + mini environment, the T3 Code mobile app, and the hosted web UI. The control plane owns + identity, grants, provisioning, endpoint records, and connection tickets. The managed + endpoint carries both normal environment HTTP/WebSocket traffic and short signed + control-over-data-plane requests such as credential minting. +

+
+ Client -> Cloud: HTTPS + IdP JWT + Cloud -> Env: HTTPS + cloud-signed request + Env -> Cloud: env-signed response + Client -> Env: HTTPS/WSS + local T3 auth +
+
+ +
+
+

Security Invariant

+

+ A cloud user session is not environment authority. Remote access requires an authorized + IdP user, a linked environment authenticated by its registered cloud-link key, and a + one-time local bootstrap credential minted by the target T3 server. +

+
+ T3 Cloud must not proxy normal app traffic. It brokers identity, provisioning, grants, + endpoint records, and connect tickets. To connect a client, T3 Cloud sends a short-lived + signed mint request through the managed endpoint to the target local T3 server. After + token exchange, clients talk directly to + https://env_abc.tunnels.t3code.com and + wss://env_abc.tunnels.t3code.com/ws. +
+
+ +
+

Minimal Credential Set

+

1. User session
Hosted IdP session/JWT on clients.

+

+ 2. Cloud signing key
Private key controlled by T3 Cloud; public + issuer metadata installed into linked environments. +

+

+ 3. Environment cloud-link keypair
Private key stored in + Keychain/state dir; public key registered with T3 Cloud. +

+

+ 4. Local server authority
Local tokens carrying + relay:manage mint single-use bootstrap credentials. +

+

+ 5. Managed endpoint runtime credential
Endpoint runtime credential + used only to expose the environment's managed endpoint. +

+
+
+ +
+

Implementation Auth and Transport Matrix

+

+ This table is the contract to implement and validate against. The managed endpoint + transport forwards bytes; it does not authorize T3 sessions. +

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
PathTransportAuth MaterialVerifierPurpose
Client -> T3 CloudHTTPSHosted IdP session/JWTT3 CloudList environments, manage grants, request connect.
T3 Cloud -> local T3 serverHTTPS through managed endpointCloud-signed mint or health request with nonce, audience, expiry, and scope.Local T3 serverAsk the linked environment to mint a one-time bootstrap credential.
Local T3 server -> T3 Cloud + HTTPS response through managed endpoint, or direct HTTPS cloud API for status. + Environment cloud-link signature.T3 CloudProve the real linked environment responded or reported status.
Client -> local T3 token exchangeHTTPS through managed endpointSingle-use bootstrap credential minted by the local T3 server.Local T3 serverMint a scoped proof-bound environment access token.
Client -> local T3 WebSocket ticket APIHTTPS through managed endpointScoped environment access token plus DPoP proof.Local T3 serverMint a short-lived ticket for one WebSocket connection.
Client -> local T3 WebSocketWSS through managed endpointwsTicket query parameter.Local T3 serverRun the existing app RPC protocol.
Endpoint runtime -> endpoint providerProvider-specific outbound tunnel connectionCloudflare tunnel token today; T3 relay connector token later.Cloudflare Tunnel or T3 RelayExpose the loopback T3 server as a stable public HTTPS/WSS endpoint.
APNs -> mobile appAPNs push transportApple push token and APNs provider auth.Apple APNs and mobile app.Wake or update mobile UI with minimal status, not full agent traffic.
+
+ Do not add an app-session authorization dependency to Cloudflare Tunnel or T3 Relay. The + endpoint provider may authenticate the connector, but local T3 auth remains the only + verifier for bootstrap credentials, scoped access tokens, WebSocket tickets, and commands. + The endpoint runtime credential authenticates the connector to the endpoint provider; it + is not a client-facing access gate for the public hostname. +
+
+ +
+
+

Overall Actor Diagram

+ Service-level auth/control/data lanes +
+
+ +
+ +
+
+ User path + The hosted IdP authenticates the human. Desktop, mobile, and hosted web present IdP + sessions to T3 Cloud for account-scoped API calls. +
+
+ Control plane + T3 Cloud stores links, grants, endpoint records, audit events, and short-lived connect + tickets. It reaches environments through signed requests over their managed endpoints, + not through a persistent per-environment control channel. +
+
+ Data plane + Cloudflare Tunnel is the first managed endpoint transport. Later T3 Relay keeps the same + httpBaseUrl/wsBaseUrl client contract. +
+
+ Local authority + The loopback T3 server remains the execution boundary and mints the one-time credential + required before remote clients can open a normal session. +
+
+
+ +
+

Credential Ownership

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
CredentialStored ByPresented ToWhat It ProvesImplementation Rule
Hosted IdP session/JWTDesktop renderer, mobile app, hosted web browser.T3 Cloud control plane.The human user and account identity.Never treat this as local environment authority.
Cloud signing keyT3 Cloud secret storage or signing service.Linked local T3 servers.The request came from T3 Cloud and was authorized by cloud policy.Use short expiries, nonce/jti replay protection, audience, and scoped claims.
Environment cloud-link private keyLocal T3 server on MacBook or Mac mini.T3 Cloud.The response/status came from the linked environment. + Private key never leaves the environment; public key is registered in T3 Cloud. +
Managed endpoint runtime credentialLocal environment sidecar/runtime.Cloudflare Tunnel today; T3 Relay later.The connector may expose this loopback origin through the endpoint provider. + Do not use this as T3 app authorization; rotate on unlink or suspected compromise. +
Single-use bootstrap credentialMinted by local T3 server; returned to the requesting client via T3 Cloud.Local T3 server over managed endpoint.The client completed cloud authorization and environment minting.Single use, short TTL, bound to environment and cloud request nonce.
Environment access tokenRemote client after token exchange.Local T3 server over managed endpoint.The client has the granted environment scopes and proof key.Issued and revoked only by the local T3 server.
WebSocket ticketRemote client, briefly.Local T3 WebSocket endpoint.The WebSocket was opened by a client with a valid scoped access token.Short-lived, one connection, verified by existing T3 WebSocket auth.
APNs tokenMobile app and T3 Cloud.Apple APNs.User/device notification and Live Activity delivery target. + Account-scoped token. Environment links and preferences decide which environment + updates fan out to that user's devices. Never include full agent traffic or secrets + in push payloads. +
+
+ +
+

How To Read The Sequence Diagrams

+

+ Each participant name includes where it runs. Arrows are concrete service boundaries: + hosted IdP auth, local app-to-environment calls, T3 Cloud API calls, signed + control-over-data-plane requests, managed endpoint traffic, or APNs delivery. +

+
+ The hosted IdP never calls into a MacBook or Mac mini. An IdP arrow back to a client means + the client-side auth SDK or hosted auth page finished sign-in and the client now has an + IdP session/JWT. +
+
+ +
+

Endpoint Contracts

+

+ Names are draft, but these contracts are the behavioral boundary. All timestamps are ISO + strings. All nonces and token ids must be replay-protected until their expiry window has + passed. +

+

Cloud API: Request Remote Connect

+
POST /v1/environments/:environmentId/connect
+Authorization: Bearer <idp-jwt>
+DPoP: <client-proof-jwt>
+
+Request body
+{
+  "clientKeyThumbprint": "jkt_..."
+}
+
+Response 200
+{
+  "environmentId": "env_mbp",
+  "httpBaseUrl": "https://env_mbp.tunnels.t3code.com/",
+  "wsBaseUrl": "wss://env_mbp.tunnels.t3code.com/ws",
+  "credential": "one_time_bootstrap_...",
+  "expiresAt": "2026-05-25T12:00:30.000Z"
+}
+ +

Cloud -> Environment: Mint Credential

+
POST https://env_mbp.tunnels.t3code.com/api/t3-cloud/mint-credential
+Authorization: T3Cloud <cloud-signed-jwt>
+Content-Type: application/json
+
+Cloud-signed claims
+{
+  "iss": "https://cloud.t3code.com",
+  "aud": "t3-env:env_mbp",
+  "sub": "user_123",
+  "deviceId": "device_456",
+  "cnf": { "jkt": "jkt_..." },
+  "scope": ["environment:connect"],
+  "nonce": "nonce_...",
+  "jti": "mint_request_...",
+  "exp": 1780000030
+}
+
+Environment-signed response 200
+{
+  "environmentId": "env_mbp",
+  "nonce": "nonce_...",
+  "credential": "one_time_bootstrap_...",
+  "expiresAt": "2026-05-25T12:00:30.000Z",
+  "signature": "env_signature_..."
+}
+ +

Client -> Environment: Exchange Proof-Bound Bootstrap Grant

+
POST https://env_mbp.tunnels.t3code.com/oauth/token
+DPoP: <client-proof-jwt-for-token-url>
+Content-Type: application/x-www-form-urlencoded
+
+grant_type=urn:ietf:params:oauth:grant-type:token-exchange
+&subject_token=one_time_bootstrap_...
+&subject_token_type=urn:t3:params:oauth:token-type:environment-bootstrap
+&requested_token_type=urn:ietf:params:oauth:token-type:access_token
+&scope=orchestration:read%20orchestration:operate%20terminal:operate%20review:write
+
+Response 200
+{
+  "access_token": "env_access_...",
+  "issued_token_type": "urn:ietf:params:oauth:token-type:access_token",
+  "token_type": "DPoP",
+  "expires_in": 3600,
+  "scope": "orchestration:read orchestration:operate terminal:operate review:write"
+}
+
+ The client generates an ephemeral proof key before requesting connect. T3 Cloud includes + the key thumbprint in the signed mint request, and the local T3 server binds the one-time + bootstrap credential to that thumbprint. A cloud service that can see the minted + credential still cannot redeem it without the client's private proof key. +
+ +

Client -> Environment: Existing WebSocket Flow

+
POST https://env_mbp.tunnels.t3code.com/api/auth/websocket-ticket
+Authorization: DPoP <env_access_token>
+DPoP: <client-proof-jwt-for-ticket-url>
+
+Response 200
+{ "ticket": "ws_ticket_...", "expiresAt": "2026-05-25T12:01:00.000Z" }
+
+GET wss://env_mbp.tunnels.t3code.com/ws?wsTicket=ws_ticket_...
+ +

Environment -> Cloud: Status For Notifications

+
POST /v1/environments/:environmentId/status
+Authorization: T3Environment <env-signed-jwt-or-dpop-proof>
+
+{
+  "environmentId": "env_mbp",
+  "status": "online",
+  "summary": {
+    "activeThreadId": "thread_123",
+    "state": "agent_running"
+  },
+  "issuedAt": "2026-05-25T12:00:00.000Z",
+  "nonce": "nonce_..."
+}
+
+ These contracts preserve the current app protocol. Only the cloud connect flow and the + local /api/t3-cloud/mint-credential endpoint are new. Bootstrap grants, + scoped access tokens, and WebSocket tickets stay owned by the local T3 server. +
+
+ +
+
+

Flow 1: Link MacBook Desktop Environment

+
+sequenceDiagram
+  actor User as User on MacBook
+  participant Desktop as Desktop app on MacBook
+  participant IdP as Hosted IdP
+  participant Env as T3 server env_mbp on MacBook
+  participant Cloud as T3 Cloud control plane
+  participant Endpoint as Managed endpoint platform
+
+  Note over Desktop,Env: Both run on the MacBook. The IdP never calls into the MacBook directly.
+  User->>Desktop: Click Link cloud account
+  Desktop->>IdP: Official hosted IdP sign-in flow
+  IdP-->>Desktop: IdP session and JWT
+  Desktop->>Env: Local owner-authorized link request with IdP JWT
+  Env->>Env: Get or create cloud-link keypair
+  Note right of Env: Private key stays local.
+  Env->>Cloud: Link env_mbp with IdP JWT + descriptor + public key
+  Cloud->>Cloud: Verify IdP user and store env grant/link record
+  Cloud->>Endpoint: Create managed endpoint for env_mbp
+  Endpoint-->>Cloud: Endpoint URLs and local runtime config
+  Cloud-->>Env: Link accepted with endpoint config
+  Env->>Env: Persist cloud link, cloud issuer metadata, and endpoint runtime config
+  Env->>Endpoint: Maintain managed endpoint to loopback origin
+  Cloud->>Endpoint: Optional signed health check through managed endpoint
+  Endpoint->>Env: Forward health check to loopback origin
+  Env-->>Endpoint: Signed environment health response
+  Endpoint-->>Cloud: Environment health response
+  Env-->>Desktop: Linked account and endpoint status
+          
+
+ Flow 1 has three service boundaries: the hosted IdP proves the human user, the local T3 + environment proves local machine authority, and T3 Cloud creates the cloud link plus + managed endpoint. Health and credential-mint requests use the endpoint instead of a + persistent environment control channel. +
+
+ +
+

Flow 2: Link Headless Mac Mini

+
+sequenceDiagram
+  actor Admin as User in browser
+  participant IdP as Hosted IdP
+  participant CLI as t3 cloud login on Mac mini
+  participant Env as T3 server env_mini on Mac mini
+  participant Cloud as T3 Cloud control plane
+  participant Endpoint as Managed endpoint platform
+
+  CLI->>Env: Local owner-authorized headless link request
+  Env->>Env: Get or create cloud-link keypair
+  Env-->>CLI: Environment descriptor and public cloud-link key
+  Note right of Env: Private key stays local.
+  CLI->>Cloud: Start device-link request with descriptor and public key
+  Cloud-->>CLI: Browser URL and short code
+  CLI-->>Admin: Print URL and code
+  Admin->>IdP: Open URL and sign in
+  IdP-->>Admin: IdP session and JWT
+  Admin->>Cloud: Approve device-link request with IdP JWT and code
+  Cloud->>Cloud: Verify IdP user and store env grant/link record
+  CLI->>Cloud: Poll until device-link request is approved
+  Cloud->>Endpoint: Create managed endpoint for env_mini
+  Endpoint-->>Cloud: Endpoint URLs and local runtime config
+  Cloud-->>CLI: Link accepted with endpoint config
+  CLI->>Env: Install endpoint config, cloud issuer metadata, and enable cloud link
+  Env->>Env: Persist cloud link and endpoint runtime config
+  Env->>Endpoint: Maintain managed endpoint to loopback origin
+  Cloud->>Endpoint: Optional signed health check through managed endpoint
+  Endpoint->>Env: Forward health check to loopback origin
+  Env-->>Endpoint: Signed environment health response
+  Endpoint-->>Cloud: Environment health response
+          
+
+ This is the headless equivalent of desktop setup. The end state is identical: + env_mini has a local cloud-link key, a managed endpoint connection, and a + local endpoint that can verify signed cloud requests. The browser only approves the + login; it never talks to the Mac mini directly. +
+
+ +
+

Flow 3: Remote Connect Bootstrap

+
+sequenceDiagram
+  participant Client as Mobile or hosted web client
+  participant Cloud as T3 Cloud control plane
+  participant Endpoint as Managed endpoint data plane
+  participant Env as Target T3 server on loopback
+
+  Client->>Client: Generate ephemeral proof key
+  Client->>Cloud: POST /v1/environments/:id/connect with IdP JWT + DPoP proof
+  Cloud->>Cloud: Verify IdP user, grant, endpoint record, and connect policy
+  Cloud->>Cloud: Create short-lived signed mint request bound to client key thumbprint
+  Cloud->>Endpoint: POST /api/t3-cloud/mint-credential with signed request
+  Endpoint->>Env: Forward signed mint request to loopback origin
+  Env->>Env: Verify cloud signature, audience, expiry, nonce, link state, and key binding
+  Env-->>Endpoint: Single-use proof-bound bootstrap credential and signed response
+  Endpoint-->>Cloud: Single-use bootstrap credential and signed response
+  Cloud->>Cloud: Verify environment signature and consume connect ticket
+  Cloud-->>Client: httpBaseUrl, wsBaseUrl, one-time credential
+  Client->>Endpoint: POST /oauth/token with credential, scopes, and DPoP proof
+  Endpoint->>Env: Forward request to loopback origin
+  Env->>Env: Verify proof matches credential key binding
+  Env-->>Endpoint: Scoped DPoP access token response
+  Endpoint-->>Client: Scoped DPoP access token response
+  Client->>Endpoint: POST /api/auth/websocket-ticket using DPoP access token
+  Endpoint-->>Client: Short-lived wsTicket
+  Client->>Endpoint: Open WebSocket with wsTicket
+          
+
+ T3 Cloud authorizes the account, but the environment still decides whether to mint the + credential. The request reaches the local server through the managed endpoint, so the + first implementation can infer reachability at connect time instead of maintaining a + separate cloud-side presence service. +
+
+ +
+

Flow 4: Mobile and Hosted Web Discover Environments

+
+sequenceDiagram
+  participant Client as Mobile app or hosted web UI
+  participant IdP as Hosted IdP
+  participant Cloud as T3 Cloud control plane
+  participant Endpoint as Managed endpoint data plane
+  participant Env as Target T3 server
+
+  Client->>IdP: Official hosted IdP sign-in flow
+  IdP-->>Client: IdP session and JWT
+  Client->>Cloud: GET /v1/environments with IdP JWT
+  Cloud->>Cloud: Verify user and lookup grants and endpoint records
+  Cloud-->>Client: Environment list and endpoint records
+  Client->>Cloud: POST /v1/environments/:id/connect with DPoP proof
+  Cloud->>Endpoint: Signed proof-bound mint request over managed endpoint
+  Endpoint->>Env: Forward signed mint request to loopback server
+  Env-->>Endpoint: Single-use proof-bound bootstrap credential
+  Endpoint-->>Cloud: Single-use bootstrap credential
+  Cloud-->>Client: Endpoint URLs and one-time credential
+  Client->>Endpoint: Exchange grant for scoped DPoP token and open WebSocket with ticket
+  Endpoint->>Env: Forward app protocol to loopback server
+          
+
+ Discovery stays cloud-mediated. Normal session traffic is direct to the managed endpoint + after connect, not streamed through T3 Cloud. +
+
+
+ +
+
+

Agent Traffic Over Managed Endpoint

+ App protocol stays HTTP + WebSocket +
+
+sequenceDiagram
+  participant Client as Mobile or hosted web client
+  participant Cloud as T3 Cloud control plane
+  participant Endpoint as Cloudflare Tunnel or T3 Relay edge
+  participant Env as T3 server loopback origin
+
+  Client->>Cloud: Connect request with IdP JWT + DPoP proof
+  Cloud->>Endpoint: Signed proof-bound mint request over managed endpoint
+  Endpoint->>Env: Forward signed mint request to loopback origin
+  Env-->>Endpoint: One-time proof-bound bootstrap credential
+  Endpoint-->>Cloud: One-time bootstrap credential
+  Cloud-->>Client: Endpoint URLs and one-time bootstrap credential
+  Client->>Endpoint: HTTPS token exchange with requested scopes and DPoP proof
+  Endpoint->>Env: Forward request over managed endpoint to loopback origin
+  Env-->>Endpoint: Scoped DPoP access token response
+  Endpoint-->>Client: Scoped DPoP access token established
+  Client->>Endpoint: WebSocket RPC stream
+  Endpoint->>Env: Forward WebSocket frames to existing T3 protocol
+  Env-->>Endpoint: Agent chunks, status, command results
+  Endpoint-->>Client: Agent chunks, status, command results
+        
+
+
+ Cloud before traffic + The control plane authorizes the user, checks grants, creates a short-lived signed mint + request, and sends it through the managed endpoint to the target environment. +
+
+ Data plane during traffic + Normal agent chunks and command RPC use the existing environment HTTP/WebSocket protocol + through the managed endpoint. T3 Cloud is not in this hot path. +
+
+ Environment remains the boundary + The local T3 server authenticates the bootstrap credential, mints WebSocket tickets, and + can reject commands based on local policy or approval state. +
+
+
+ +
+
+

Push Notifications and Live Activities

+ Minimal payloads, control-plane state +
+
+sequenceDiagram
+  participant Mobile as T3 mobile app
+  participant IdP as Hosted IdP
+  participant Cloud as T3 Cloud control plane
+  participant APNs as Apple APNs
+  participant Env as Local T3 server
+
+  Mobile->>IdP: Sign in with hosted IdP
+  IdP-->>Mobile: IdP session and JWT
+  Mobile->>Cloud: Register APNs and Live Activity tokens with IdP JWT
+  Cloud->>Cloud: Store token per user/device with agent-awareness preferences
+  Env->>Cloud: Publish minimal status via cloud API or webhook with cloud-link signature
+  Cloud->>Cloud: Select linked users for the publishing environment
+  Cloud->>Cloud: Store latest summary and notification state
+  Cloud->>APNs: Send minimal notification or Live Activity payload
+  APNs-->>Mobile: Deliver push or Live Activity update
+  Mobile->>Cloud: App foregrounds and requests connect
+  Cloud-->>Mobile: Endpoint URLs and bootstrap credential
+        
+
+ Push payloads should be summaries: environment id, thread id, status, counters, and a + short title if product policy allows. Full agent chunks are fetched from the environment + over the managed endpoint after authentication. +
+
+ +
+
+

Hosted Web UI Monitoring

+
+sequenceDiagram
+  participant Browser as Browser on other device
+  participant IdP as Hosted IdP
+  participant Cloud as T3 Cloud control plane
+  participant Endpoint as Managed endpoint data plane
+  participant Env as env_mbp or env_mini
+
+  Browser->>IdP: Open app.t3.codes and sign in
+  IdP-->>Browser: IdP session and JWT
+  Browser->>Cloud: GET linked environments with IdP JWT
+  Cloud-->>Browser: env_mbp and env_mini metadata
+  Browser->>Cloud: Connect to selected environment
+  Cloud->>Endpoint: Signed mint request over managed endpoint
+  Endpoint->>Env: Forward signed mint request to loopback local server
+  Env-->>Endpoint: One-time bootstrap credential
+  Endpoint-->>Cloud: One-time bootstrap credential
+  Cloud-->>Browser: Endpoint URLs and one-time credential
+  Browser->>Endpoint: Exchange bootstrap grant for scoped DPoP access token
+  Endpoint->>Env: Forward to loopback local server
+  Browser->>Endpoint: Open WebSocket RPC stream
+  Env-->>Endpoint: Live chunks and status
+  Endpoint-->>Browser: Live chunks and status
+  opt User starts an agent remotely
+    Browser->>Endpoint: Command request over existing WebSocket
+    Env->>Env: Local policy check
+    Env-->>Endpoint: Accept or reject
+    Endpoint-->>Browser: Accept or reject
+  end
+          
+
+ +
+

Account Mismatch Rule

+
+
+ Compare two identities + The environment link state says env_mbp is linked to User A. The renderer + IdP browser session may currently be User B. +
+
+ Match + If the renderer user and environment link match, show normal cloud management: refresh + endpoint, unlink, rotate, and configure. +
+
+ Mismatch + If they differ, show linked-as User A and signed-in-as User B. Allow sign out, sign in + as the linked user, or an explicit unlink/switch flow. +
+
+ Never allowed + Do not silently replace the linked account, treat the renderer cookie as environment + authority, or issue connect credentials unless that cloud user is explicitly granted. +
+
+
+ The displayed cloud account for an environment comes from the environment link state, + not from whatever IdP session currently exists in the renderer. +
+
+
+ +
+

End-to-End Setup Checklist For This Use Case

+
+
+ 1. MacBook Pro desktop + Start desktop app. User signs in with the hosted IdP. env_mbp registers its + descriptor and cloud-link public key, receives a managed endpoint, enables the managed + endpoint runtime, and accepts signed cloud mint requests through that endpoint. +
+
+ 2. Mac mini headless server + Run t3 cloud login. Complete device/browser login as the same T3 user or + org. env_mini registers its own cloud-link key, receives its own managed + endpoint, enables the managed endpoint runtime, and accepts signed cloud mint requests + through that endpoint. +
+
+ 3. MacBook remote environment entry + Add Mac mini as a remote environment using existing direct auth such as SSH, pairing, or + private network. This is for direct local/private management; the cloud link is a + separate managed endpoint record. +
+
+ 4. Mobile app + Sign into the T3 Code mobile app with the hosted IdP. Register APNs and Live Activity + tokens. The app lists env_mbp and env_mini, asks T3 Cloud to + connect, then opens HTTP/WebSocket traffic directly against the selected endpoint. +
+
+ 5. Hosted web + Sign into app.t3.codes. It lists the same linked environments and exchanges + for a direct managed-endpoint access token the same way mobile does. +
+
+
+ +
+
+

Managed Endpoint Boundary

+ Cloudflare Tunnel is a transport choice, not the product architecture +
+
+
+ Stable client contract + T3 Cloud returns httpBaseUrl, wsBaseUrl, and a one-time + credential. Clients do not know whether the endpoint is backed by Cloudflare Tunnel or a + future T3 relay. +
+
+ Cloudflare Tunnel today + Provision one tunnel per environment, configure ingress to + http://127.0.0.1:<serverPort>, create the public hostname, and give + the linked environment only the endpoint credential it needs to expose that endpoint. T3 + Cloud reaches the environment through signed HTTPS requests to that endpoint. +
+
+ Request-time reachability + V1 does not maintain authoritative online presence for each environment. The control + plane infers reachability when it attempts a signed health or credential-mint request + over the managed endpoint, then returns a concrete connect result or a timeout/failure. +
+
+ T3 Relay later + Replace the endpoint runtime with t3-relayd connect ... and keep the same + managed endpoint, control-plane, and local credential semantics. The relay can add + purpose-built stateful behavior later without changing client bootstrap semantics. +
+
+
+ +
+

Implementation Validation Checklist

+
+
+ Cloud user auth is isolated + A valid IdP JWT can list cloud environments and request connect, but cannot call local + T3 app APIs directly without a local bootstrap credential. +
+
+ Cloud-signed mint requests are strict + The local T3 server rejects mint requests with the wrong issuer, audience, environment + id, scope, expiry, nonce, replayed jti, or client key binding. +
+
+ Environment responses are authenticated + T3 Cloud rejects credential and health responses that are missing the environment + cloud-link signature or are signed by a key other than the registered environment key. +
+
+ Endpoint runtime auth is not app auth + Stealing or rotating the Cloudflare tunnel token or future relay connector token does + not create a valid T3 access token, WebSocket ticket, or environment-signed response. +
+
+ Bootstrap credentials are one-shot + The local T3 server rejects expired, replayed, wrong-environment, or wrong-nonce + bootstrap credentials, and rejects proof-bound credentials unless the bootstrap request + proves possession of the bound client key. +
+
+ Existing WebSocket protocol stays unchanged + After token exchange, remote clients use scoped access tokens and the + wsTicket flow used for remote environments. +
+
+ T3 Cloud is not in the hot path + Agent chunks, command RPC, terminal traffic, and session WebSocket frames flow from + client to managed endpoint to local T3 server, not through T3 Cloud. +
+
+ Provider swap is observable only in endpoint metadata + Replacing Cloudflare Tunnel with T3 Relay changes endpoint runtime provisioning and + provider refs, but not client token exchange, scoped authorization, or WebSocket + behavior. +
+
+
+ +
+
+

V1 Infrastructure Primitives

+ Concrete stack for the first managed endpoint implementation +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ConcernV1 PrimitiveSource Of Truth?Implementation Notes
Control plane runtimeCloudflare WorkersNo, stateless runtime. + Hosts T3 Cloud APIs, verifies IdP JWTs, provisions endpoint records, signs mint + requests, receives status updates, and enqueues async work. +
Hosted user identityHosted IdP, v1 implementation: ClerkNo, external identity authority. + T3 Cloud verifies IdP JWTs and consumes IdP webhooks. Local T3 servers do not trust + hosted IdP sessions directly. +
Relational databasePlanetScale Postgres via Cloudflare HyperdriveYes. + Stores accounts, users, devices, environments, grants, cloud links, endpoint + records, public environment keys, connect requests, notification targets, status + snapshots, and audit events. +
Database connection layerCloudflare HyperdriveNo, connection/pooling layer. + Workers connect to PlanetScale Postgres through Hyperdrive. Hyperdrive is never used + as application state. +
Cloud secretsCloudflare Worker secret bindingsNo, secret source for Worker runtime. + Use for IdP secrets, IdP webhook secret, Cloudflare API token, cloud mint signing + private key, APNs provider credentials, and optional app encryption key. Do not use + Secrets Store for v1 unless multiple independently deployed Workers need shared + account-level secrets. +
Environment private keysLocal Keychain or local state directoryYes, for environment identity. + Environment cloud-link private keys remain local only. T3 Cloud stores only the + public key in PlanetScale. +
Managed endpoint data planeCloudflare TunnelNo, transport provider. + First ManagedEndpointProvider. T3 Cloud provisions tunnels, DNS + records, endpoint metadata, and one-time runtime config for the local environment. +
Future data planeT3 RelayNo, transport provider. + Implements the same provider interface and client contract: + httpBaseUrl, wsBaseUrl, and local T3 auth. +
Async jobsCloudflare Queues with dead-letter queuesNo, delivery mechanism. + Use for endpoint provisioning, endpoint reconciliation, IdP webhook processing, + unlink/rotate workflows, audit event fanout, and APNs delivery. +
Push deliveryCloudflare Queues consumer -> Apple APNsNo, delivery mechanism. + Queue APNs jobs after status updates. Payloads are minimal and must not include full + agent chunks, access tokens, bootstrap credentials, or WebSocket tickets. +
Scheduled reconciliationCloudflare Cron TriggersNo, scheduler. + Expire connect requests, reconcile pending tunnel provisioning, expire stale health + observations, audit dangling tunnel/DNS records, and clean old link codes. +
Blob/object storageCloudflare R2, optionalNo for core auth/control state. + Use only for diagnostics, exports, large redacted logs, or archived webhook + payloads. PlanetScale remains the source of truth. +
CoordinationDatabase constraints, idempotency keys, queuesPlanetScale is authoritative. + Use explicit idempotency keys for link, provisioning, connect, notification, and + rotation workflows. Keep the database as the durable coordination point for v1. +
ObservabilityWorkers Observability, Analytics Engine, PlanetScale audit rowsPlanetScale for durable audit events. + Use Analytics Engine for high-cardinality operational/product metrics. Keep durable + audit history in PlanetScale, with optional R2 exports. +
+
+ Worker secret bindings are enough for the initial cloud secrets, and + control-over-data-plane requests avoid persistent environment control sockets. +
+
+ +
+

Design Anchors

+

+ These references are the standards this shape should align with. They are not product + requirements by themselves, but they describe the secure patterns we should avoid + reinventing badly. +

+
    +
  • + RFC 8252: OAuth 2.0 for native + apps. Use browser-based user auth instead of collecting credentials inside the app. +
  • +
  • + RFC 8628: Device authorization + grant. Good fit for headless t3 cloud login. +
  • +
  • + RFC 9449: DPoP / + proof-of-possession. Useful model for making stolen bearer tokens insufficient without + the environment key. +
  • +
+
+
+ + + diff --git a/infra/relay/alchemy.run.ts b/infra/relay/alchemy.run.ts new file mode 100644 index 0000000000..d80e3483bb --- /dev/null +++ b/infra/relay/alchemy.run.ts @@ -0,0 +1,38 @@ +import * as Alchemy from "alchemy"; +import * as Axiom from "alchemy/Axiom"; +import * as Cloudflare from "alchemy/Cloudflare"; +import * as Drizzle from "alchemy/Drizzle"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import * as Planetscale from "alchemy/Planetscale"; +import * as FetchHttpClient from "effect/unstable/http/FetchHttpClient"; + +import { PlanetscaleDatabase, RelayHyperdrive } from "./src/db.ts"; +import Api from "./src/worker.ts"; + +export default Alchemy.Stack( + "T3CodeRelay", + { + // @effect-diagnostics-next-line anyUnknownInErrorContext:off layerMergeAllWithDependencies:off - Alchemy provider helpers expose framework-owned any requirements. + providers: Layer.mergeAll( + Axiom.providers(), + Cloudflare.providers(), + Drizzle.providers(), + Planetscale.providers(), + FetchHttpClient.layer, + ), + state: Cloudflare.state(), + }, + Effect.gen(function* () { + const db = yield* PlanetscaleDatabase; + const hyperdrive = yield* RelayHyperdrive; + const api = yield* Api; + + return { + databaseName: db.database.name, + hyperdriveName: hyperdrive.name, + workerName: api.workerName, + url: api.url, + }; + }), +); diff --git a/infra/relay/migrations/postgres/20260527044716_baseline/migration.sql b/infra/relay/migrations/postgres/20260527044716_baseline/migration.sql new file mode 100644 index 0000000000..694885f380 --- /dev/null +++ b/infra/relay/migrations/postgres/20260527044716_baseline/migration.sql @@ -0,0 +1,104 @@ +CREATE TABLE "relay_agent_activity_rows" ( + "environment_id" varchar(191), + "environment_public_key" text, + "thread_id" varchar(191), + "state_json" jsonb NOT NULL, + "updated_at" varchar(64) NOT NULL, + "created_at" varchar(64) NOT NULL, + CONSTRAINT "relay_agent_activity_rows_pkey" PRIMARY KEY("environment_id","environment_public_key","thread_id") +); +--> statement-breakpoint +CREATE TABLE "relay_delivery_attempts" ( + "id" varchar(36) PRIMARY KEY, + "created_at" varchar(64) NOT NULL, + "user_id" varchar(255), + "environment_id" varchar(191), + "thread_id" varchar(191), + "device_id" varchar(255), + "kind" varchar(64) NOT NULL, + "source_job_id" varchar(64), + "token_suffix" varchar(16), + "apns_status" integer, + "apns_reason" text, + "apns_id" varchar(128), + "transport_error" text +); +--> statement-breakpoint +CREATE TABLE "relay_dpop_proofs" ( + "thumbprint" varchar(128), + "jti" varchar(255), + "iat" integer NOT NULL, + "expires_at" varchar(64) NOT NULL, + "created_at" varchar(64) NOT NULL, + CONSTRAINT "relay_dpop_proofs_pkey" PRIMARY KEY("thumbprint","jti") +); +--> statement-breakpoint +CREATE TABLE "relay_environment_credentials" ( + "credential_id" varchar(64) PRIMARY KEY, + "environment_id" varchar(191) NOT NULL, + "environment_public_key" text NOT NULL, + "credential_hash" varchar(191) NOT NULL, + "revoked_at" varchar(64), + "created_at" varchar(64) NOT NULL, + "updated_at" varchar(64) NOT NULL +); +--> statement-breakpoint +CREATE TABLE "relay_environment_links" ( + "user_id" varchar(191), + "environment_id" varchar(191), + "environment_label" text DEFAULT 'T3 Environment' NOT NULL, + "environment_public_key" text NOT NULL, + "endpoint_http_base_url" text NOT NULL, + "endpoint_ws_base_url" text NOT NULL, + "endpoint_provider_kind" varchar(32) NOT NULL, + "notifications_enabled" boolean DEFAULT true NOT NULL, + "live_activities_enabled" boolean DEFAULT true NOT NULL, + "managed_tunnels_enabled" boolean DEFAULT false NOT NULL, + "created_by_device_id" varchar(191), + "revoked_at" varchar(64), + "created_at" varchar(64) NOT NULL, + "updated_at" varchar(64) NOT NULL, + CONSTRAINT "relay_environment_links_pkey" PRIMARY KEY("user_id","environment_id") +); +--> statement-breakpoint +CREATE TABLE "relay_live_activities" ( + "user_id" varchar(255), + "device_id" varchar(255), + "activity_push_token" text, + "remote_start_queued_at" varchar(64), + "remote_started_at" varchar(64), + "ended_at" varchar(64), + "last_aggregate_json" jsonb, + "last_live_activity_delivery_at" varchar(64), + "created_at" varchar(64) NOT NULL, + "updated_at" varchar(64) NOT NULL, + CONSTRAINT "relay_live_activities_pkey" PRIMARY KEY("user_id","device_id") +); +--> statement-breakpoint +CREATE TABLE "relay_mobile_devices" ( + "user_id" varchar(255), + "device_id" varchar(255), + "platform" varchar(16) NOT NULL, + "ios_major_version" integer NOT NULL, + "app_version" varchar(64), + "push_token" text, + "push_to_start_token" text, + "preferences_json" jsonb NOT NULL, + "created_at" varchar(64) NOT NULL, + "updated_at" varchar(64) NOT NULL, + CONSTRAINT "relay_mobile_devices_pkey" PRIMARY KEY("user_id","device_id") +); +--> statement-breakpoint +CREATE INDEX "idx_relay_agent_activity_rows_updated" ON "relay_agent_activity_rows" ("updated_at");--> statement-breakpoint +CREATE INDEX "idx_relay_delivery_attempts_environment" ON "relay_delivery_attempts" ("environment_id","thread_id","created_at");--> statement-breakpoint +CREATE UNIQUE INDEX "idx_relay_delivery_attempts_source_job" ON "relay_delivery_attempts" ("source_job_id");--> statement-breakpoint +CREATE INDEX "idx_relay_dpop_proofs_expires_at" ON "relay_dpop_proofs" ("expires_at");--> statement-breakpoint +CREATE UNIQUE INDEX "idx_relay_environment_credentials_hash" ON "relay_environment_credentials" ("credential_hash");--> statement-breakpoint +CREATE INDEX "idx_relay_environment_credentials_environment" ON "relay_environment_credentials" ("environment_id","revoked_at");--> statement-breakpoint +CREATE INDEX "idx_relay_environment_credentials_environment_key" ON "relay_environment_credentials" ("environment_id","environment_public_key","revoked_at");--> statement-breakpoint +CREATE INDEX "idx_relay_environment_links_environment" ON "relay_environment_links" ("environment_id","revoked_at");--> statement-breakpoint +CREATE INDEX "idx_relay_live_activities_user" ON "relay_live_activities" ("user_id");--> statement-breakpoint +CREATE UNIQUE INDEX "idx_relay_live_activities_activity_push_token" ON "relay_live_activities" ("activity_push_token");--> statement-breakpoint +CREATE INDEX "idx_relay_mobile_devices_user" ON "relay_mobile_devices" ("user_id");--> statement-breakpoint +CREATE UNIQUE INDEX "idx_relay_mobile_devices_push_token" ON "relay_mobile_devices" ("push_token");--> statement-breakpoint +CREATE UNIQUE INDEX "idx_relay_mobile_devices_push_to_start_token" ON "relay_mobile_devices" ("push_to_start_token"); \ No newline at end of file diff --git a/infra/relay/migrations/postgres/20260527044716_baseline/snapshot.json b/infra/relay/migrations/postgres/20260527044716_baseline/snapshot.json new file mode 100644 index 0000000000..aa35a4f8ee --- /dev/null +++ b/infra/relay/migrations/postgres/20260527044716_baseline/snapshot.json @@ -0,0 +1,1267 @@ +{ + "version": "8", + "dialect": "postgres", + "id": "ad620f05-3fd1-43b8-a3ca-d4c02543d892", + "prevIds": ["00000000-0000-0000-0000-000000000000"], + "ddl": [ + { + "isRlsEnabled": false, + "name": "relay_agent_activity_rows", + "entityType": "tables", + "schema": "public" + }, + { + "isRlsEnabled": false, + "name": "relay_delivery_attempts", + "entityType": "tables", + "schema": "public" + }, + { + "isRlsEnabled": false, + "name": "relay_dpop_proofs", + "entityType": "tables", + "schema": "public" + }, + { + "isRlsEnabled": false, + "name": "relay_environment_credentials", + "entityType": "tables", + "schema": "public" + }, + { + "isRlsEnabled": false, + "name": "relay_environment_links", + "entityType": "tables", + "schema": "public" + }, + { + "isRlsEnabled": false, + "name": "relay_live_activities", + "entityType": "tables", + "schema": "public" + }, + { + "isRlsEnabled": false, + "name": "relay_mobile_devices", + "entityType": "tables", + "schema": "public" + }, + { + "type": "varchar(191)", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "environment_id", + "entityType": "columns", + "schema": "public", + "table": "relay_agent_activity_rows" + }, + { + "type": "text", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "environment_public_key", + "entityType": "columns", + "schema": "public", + "table": "relay_agent_activity_rows" + }, + { + "type": "varchar(191)", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "thread_id", + "entityType": "columns", + "schema": "public", + "table": "relay_agent_activity_rows" + }, + { + "type": "jsonb", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "state_json", + "entityType": "columns", + "schema": "public", + "table": "relay_agent_activity_rows" + }, + { + "type": "varchar(64)", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "updated_at", + "entityType": "columns", + "schema": "public", + "table": "relay_agent_activity_rows" + }, + { + "type": "varchar(64)", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "created_at", + "entityType": "columns", + "schema": "public", + "table": "relay_agent_activity_rows" + }, + { + "type": "varchar(36)", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "id", + "entityType": "columns", + "schema": "public", + "table": "relay_delivery_attempts" + }, + { + "type": "varchar(64)", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "created_at", + "entityType": "columns", + "schema": "public", + "table": "relay_delivery_attempts" + }, + { + "type": "varchar(255)", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "user_id", + "entityType": "columns", + "schema": "public", + "table": "relay_delivery_attempts" + }, + { + "type": "varchar(191)", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "environment_id", + "entityType": "columns", + "schema": "public", + "table": "relay_delivery_attempts" + }, + { + "type": "varchar(191)", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "thread_id", + "entityType": "columns", + "schema": "public", + "table": "relay_delivery_attempts" + }, + { + "type": "varchar(255)", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "device_id", + "entityType": "columns", + "schema": "public", + "table": "relay_delivery_attempts" + }, + { + "type": "varchar(64)", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "kind", + "entityType": "columns", + "schema": "public", + "table": "relay_delivery_attempts" + }, + { + "type": "varchar(64)", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "source_job_id", + "entityType": "columns", + "schema": "public", + "table": "relay_delivery_attempts" + }, + { + "type": "varchar(16)", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "token_suffix", + "entityType": "columns", + "schema": "public", + "table": "relay_delivery_attempts" + }, + { + "type": "integer", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "apns_status", + "entityType": "columns", + "schema": "public", + "table": "relay_delivery_attempts" + }, + { + "type": "text", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "apns_reason", + "entityType": "columns", + "schema": "public", + "table": "relay_delivery_attempts" + }, + { + "type": "varchar(128)", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "apns_id", + "entityType": "columns", + "schema": "public", + "table": "relay_delivery_attempts" + }, + { + "type": "text", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "transport_error", + "entityType": "columns", + "schema": "public", + "table": "relay_delivery_attempts" + }, + { + "type": "varchar(128)", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "thumbprint", + "entityType": "columns", + "schema": "public", + "table": "relay_dpop_proofs" + }, + { + "type": "varchar(255)", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "jti", + "entityType": "columns", + "schema": "public", + "table": "relay_dpop_proofs" + }, + { + "type": "integer", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "iat", + "entityType": "columns", + "schema": "public", + "table": "relay_dpop_proofs" + }, + { + "type": "varchar(64)", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "expires_at", + "entityType": "columns", + "schema": "public", + "table": "relay_dpop_proofs" + }, + { + "type": "varchar(64)", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "created_at", + "entityType": "columns", + "schema": "public", + "table": "relay_dpop_proofs" + }, + { + "type": "varchar(64)", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "credential_id", + "entityType": "columns", + "schema": "public", + "table": "relay_environment_credentials" + }, + { + "type": "varchar(191)", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "environment_id", + "entityType": "columns", + "schema": "public", + "table": "relay_environment_credentials" + }, + { + "type": "text", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "environment_public_key", + "entityType": "columns", + "schema": "public", + "table": "relay_environment_credentials" + }, + { + "type": "varchar(191)", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "credential_hash", + "entityType": "columns", + "schema": "public", + "table": "relay_environment_credentials" + }, + { + "type": "varchar(64)", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "revoked_at", + "entityType": "columns", + "schema": "public", + "table": "relay_environment_credentials" + }, + { + "type": "varchar(64)", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "created_at", + "entityType": "columns", + "schema": "public", + "table": "relay_environment_credentials" + }, + { + "type": "varchar(64)", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "updated_at", + "entityType": "columns", + "schema": "public", + "table": "relay_environment_credentials" + }, + { + "type": "varchar(191)", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "user_id", + "entityType": "columns", + "schema": "public", + "table": "relay_environment_links" + }, + { + "type": "varchar(191)", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "environment_id", + "entityType": "columns", + "schema": "public", + "table": "relay_environment_links" + }, + { + "type": "text", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": "'T3 Environment'", + "generated": null, + "identity": null, + "name": "environment_label", + "entityType": "columns", + "schema": "public", + "table": "relay_environment_links" + }, + { + "type": "text", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "environment_public_key", + "entityType": "columns", + "schema": "public", + "table": "relay_environment_links" + }, + { + "type": "text", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "endpoint_http_base_url", + "entityType": "columns", + "schema": "public", + "table": "relay_environment_links" + }, + { + "type": "text", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "endpoint_ws_base_url", + "entityType": "columns", + "schema": "public", + "table": "relay_environment_links" + }, + { + "type": "varchar(32)", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "endpoint_provider_kind", + "entityType": "columns", + "schema": "public", + "table": "relay_environment_links" + }, + { + "type": "boolean", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": "true", + "generated": null, + "identity": null, + "name": "notifications_enabled", + "entityType": "columns", + "schema": "public", + "table": "relay_environment_links" + }, + { + "type": "boolean", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": "true", + "generated": null, + "identity": null, + "name": "live_activities_enabled", + "entityType": "columns", + "schema": "public", + "table": "relay_environment_links" + }, + { + "type": "boolean", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": "false", + "generated": null, + "identity": null, + "name": "managed_tunnels_enabled", + "entityType": "columns", + "schema": "public", + "table": "relay_environment_links" + }, + { + "type": "varchar(191)", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "created_by_device_id", + "entityType": "columns", + "schema": "public", + "table": "relay_environment_links" + }, + { + "type": "varchar(64)", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "revoked_at", + "entityType": "columns", + "schema": "public", + "table": "relay_environment_links" + }, + { + "type": "varchar(64)", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "created_at", + "entityType": "columns", + "schema": "public", + "table": "relay_environment_links" + }, + { + "type": "varchar(64)", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "updated_at", + "entityType": "columns", + "schema": "public", + "table": "relay_environment_links" + }, + { + "type": "varchar(255)", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "user_id", + "entityType": "columns", + "schema": "public", + "table": "relay_live_activities" + }, + { + "type": "varchar(255)", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "device_id", + "entityType": "columns", + "schema": "public", + "table": "relay_live_activities" + }, + { + "type": "text", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "activity_push_token", + "entityType": "columns", + "schema": "public", + "table": "relay_live_activities" + }, + { + "type": "varchar(64)", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "remote_start_queued_at", + "entityType": "columns", + "schema": "public", + "table": "relay_live_activities" + }, + { + "type": "varchar(64)", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "remote_started_at", + "entityType": "columns", + "schema": "public", + "table": "relay_live_activities" + }, + { + "type": "varchar(64)", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "ended_at", + "entityType": "columns", + "schema": "public", + "table": "relay_live_activities" + }, + { + "type": "jsonb", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "last_aggregate_json", + "entityType": "columns", + "schema": "public", + "table": "relay_live_activities" + }, + { + "type": "varchar(64)", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "last_live_activity_delivery_at", + "entityType": "columns", + "schema": "public", + "table": "relay_live_activities" + }, + { + "type": "varchar(64)", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "created_at", + "entityType": "columns", + "schema": "public", + "table": "relay_live_activities" + }, + { + "type": "varchar(64)", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "updated_at", + "entityType": "columns", + "schema": "public", + "table": "relay_live_activities" + }, + { + "type": "varchar(255)", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "user_id", + "entityType": "columns", + "schema": "public", + "table": "relay_mobile_devices" + }, + { + "type": "varchar(255)", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "device_id", + "entityType": "columns", + "schema": "public", + "table": "relay_mobile_devices" + }, + { + "type": "varchar(16)", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "platform", + "entityType": "columns", + "schema": "public", + "table": "relay_mobile_devices" + }, + { + "type": "integer", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "ios_major_version", + "entityType": "columns", + "schema": "public", + "table": "relay_mobile_devices" + }, + { + "type": "varchar(64)", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "app_version", + "entityType": "columns", + "schema": "public", + "table": "relay_mobile_devices" + }, + { + "type": "text", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "push_token", + "entityType": "columns", + "schema": "public", + "table": "relay_mobile_devices" + }, + { + "type": "text", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "push_to_start_token", + "entityType": "columns", + "schema": "public", + "table": "relay_mobile_devices" + }, + { + "type": "jsonb", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "preferences_json", + "entityType": "columns", + "schema": "public", + "table": "relay_mobile_devices" + }, + { + "type": "varchar(64)", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "created_at", + "entityType": "columns", + "schema": "public", + "table": "relay_mobile_devices" + }, + { + "type": "varchar(64)", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "updated_at", + "entityType": "columns", + "schema": "public", + "table": "relay_mobile_devices" + }, + { + "nameExplicit": true, + "columns": [ + { + "value": "updated_at", + "isExpression": false, + "asc": true, + "nullsFirst": false, + "opclass": null + } + ], + "isUnique": false, + "where": null, + "with": "", + "method": "btree", + "concurrently": false, + "name": "idx_relay_agent_activity_rows_updated", + "entityType": "indexes", + "schema": "public", + "table": "relay_agent_activity_rows" + }, + { + "nameExplicit": true, + "columns": [ + { + "value": "environment_id", + "isExpression": false, + "asc": true, + "nullsFirst": false, + "opclass": null + }, + { + "value": "thread_id", + "isExpression": false, + "asc": true, + "nullsFirst": false, + "opclass": null + }, + { + "value": "created_at", + "isExpression": false, + "asc": true, + "nullsFirst": false, + "opclass": null + } + ], + "isUnique": false, + "where": null, + "with": "", + "method": "btree", + "concurrently": false, + "name": "idx_relay_delivery_attempts_environment", + "entityType": "indexes", + "schema": "public", + "table": "relay_delivery_attempts" + }, + { + "nameExplicit": true, + "columns": [ + { + "value": "source_job_id", + "isExpression": false, + "asc": true, + "nullsFirst": false, + "opclass": null + } + ], + "isUnique": true, + "where": null, + "with": "", + "method": "btree", + "concurrently": false, + "name": "idx_relay_delivery_attempts_source_job", + "entityType": "indexes", + "schema": "public", + "table": "relay_delivery_attempts" + }, + { + "nameExplicit": true, + "columns": [ + { + "value": "expires_at", + "isExpression": false, + "asc": true, + "nullsFirst": false, + "opclass": null + } + ], + "isUnique": false, + "where": null, + "with": "", + "method": "btree", + "concurrently": false, + "name": "idx_relay_dpop_proofs_expires_at", + "entityType": "indexes", + "schema": "public", + "table": "relay_dpop_proofs" + }, + { + "nameExplicit": true, + "columns": [ + { + "value": "credential_hash", + "isExpression": false, + "asc": true, + "nullsFirst": false, + "opclass": null + } + ], + "isUnique": true, + "where": null, + "with": "", + "method": "btree", + "concurrently": false, + "name": "idx_relay_environment_credentials_hash", + "entityType": "indexes", + "schema": "public", + "table": "relay_environment_credentials" + }, + { + "nameExplicit": true, + "columns": [ + { + "value": "environment_id", + "isExpression": false, + "asc": true, + "nullsFirst": false, + "opclass": null + }, + { + "value": "revoked_at", + "isExpression": false, + "asc": true, + "nullsFirst": false, + "opclass": null + } + ], + "isUnique": false, + "where": null, + "with": "", + "method": "btree", + "concurrently": false, + "name": "idx_relay_environment_credentials_environment", + "entityType": "indexes", + "schema": "public", + "table": "relay_environment_credentials" + }, + { + "nameExplicit": true, + "columns": [ + { + "value": "environment_id", + "isExpression": false, + "asc": true, + "nullsFirst": false, + "opclass": null + }, + { + "value": "environment_public_key", + "isExpression": false, + "asc": true, + "nullsFirst": false, + "opclass": null + }, + { + "value": "revoked_at", + "isExpression": false, + "asc": true, + "nullsFirst": false, + "opclass": null + } + ], + "isUnique": false, + "where": null, + "with": "", + "method": "btree", + "concurrently": false, + "name": "idx_relay_environment_credentials_environment_key", + "entityType": "indexes", + "schema": "public", + "table": "relay_environment_credentials" + }, + { + "nameExplicit": true, + "columns": [ + { + "value": "environment_id", + "isExpression": false, + "asc": true, + "nullsFirst": false, + "opclass": null + }, + { + "value": "revoked_at", + "isExpression": false, + "asc": true, + "nullsFirst": false, + "opclass": null + } + ], + "isUnique": false, + "where": null, + "with": "", + "method": "btree", + "concurrently": false, + "name": "idx_relay_environment_links_environment", + "entityType": "indexes", + "schema": "public", + "table": "relay_environment_links" + }, + { + "nameExplicit": true, + "columns": [ + { + "value": "user_id", + "isExpression": false, + "asc": true, + "nullsFirst": false, + "opclass": null + } + ], + "isUnique": false, + "where": null, + "with": "", + "method": "btree", + "concurrently": false, + "name": "idx_relay_live_activities_user", + "entityType": "indexes", + "schema": "public", + "table": "relay_live_activities" + }, + { + "nameExplicit": true, + "columns": [ + { + "value": "activity_push_token", + "isExpression": false, + "asc": true, + "nullsFirst": false, + "opclass": null + } + ], + "isUnique": true, + "where": null, + "with": "", + "method": "btree", + "concurrently": false, + "name": "idx_relay_live_activities_activity_push_token", + "entityType": "indexes", + "schema": "public", + "table": "relay_live_activities" + }, + { + "nameExplicit": true, + "columns": [ + { + "value": "user_id", + "isExpression": false, + "asc": true, + "nullsFirst": false, + "opclass": null + } + ], + "isUnique": false, + "where": null, + "with": "", + "method": "btree", + "concurrently": false, + "name": "idx_relay_mobile_devices_user", + "entityType": "indexes", + "schema": "public", + "table": "relay_mobile_devices" + }, + { + "nameExplicit": true, + "columns": [ + { + "value": "push_token", + "isExpression": false, + "asc": true, + "nullsFirst": false, + "opclass": null + } + ], + "isUnique": true, + "where": null, + "with": "", + "method": "btree", + "concurrently": false, + "name": "idx_relay_mobile_devices_push_token", + "entityType": "indexes", + "schema": "public", + "table": "relay_mobile_devices" + }, + { + "nameExplicit": true, + "columns": [ + { + "value": "push_to_start_token", + "isExpression": false, + "asc": true, + "nullsFirst": false, + "opclass": null + } + ], + "isUnique": true, + "where": null, + "with": "", + "method": "btree", + "concurrently": false, + "name": "idx_relay_mobile_devices_push_to_start_token", + "entityType": "indexes", + "schema": "public", + "table": "relay_mobile_devices" + }, + { + "columns": ["environment_id", "environment_public_key", "thread_id"], + "nameExplicit": false, + "name": "relay_agent_activity_rows_pkey", + "entityType": "pks", + "schema": "public", + "table": "relay_agent_activity_rows" + }, + { + "columns": ["thumbprint", "jti"], + "nameExplicit": false, + "name": "relay_dpop_proofs_pkey", + "entityType": "pks", + "schema": "public", + "table": "relay_dpop_proofs" + }, + { + "columns": ["user_id", "environment_id"], + "nameExplicit": false, + "name": "relay_environment_links_pkey", + "entityType": "pks", + "schema": "public", + "table": "relay_environment_links" + }, + { + "columns": ["user_id", "device_id"], + "nameExplicit": false, + "name": "relay_live_activities_pkey", + "entityType": "pks", + "schema": "public", + "table": "relay_live_activities" + }, + { + "columns": ["user_id", "device_id"], + "nameExplicit": false, + "name": "relay_mobile_devices_pkey", + "entityType": "pks", + "schema": "public", + "table": "relay_mobile_devices" + }, + { + "columns": ["id"], + "nameExplicit": false, + "name": "relay_delivery_attempts_pkey", + "schema": "public", + "table": "relay_delivery_attempts", + "entityType": "pks" + }, + { + "columns": ["credential_id"], + "nameExplicit": false, + "name": "relay_environment_credentials_pkey", + "schema": "public", + "table": "relay_environment_credentials", + "entityType": "pks" + } + ], + "renames": [] +} diff --git a/infra/relay/package.json b/infra/relay/package.json new file mode 100644 index 0000000000..15ff6a5c92 --- /dev/null +++ b/infra/relay/package.json @@ -0,0 +1,32 @@ +{ + "name": "t3code-relay", + "private": true, + "type": "module", + "scripts": { + "deploy": "alchemy deploy", + "destroy": "alchemy destroy", + "test": "vitest run", + "typecheck": "tsc --noEmit" + }, + "dependencies": { + "@clerk/backend": "^3.4.14", + "@distilled.cloud/cloudflare": "^0.21.5", + "@effect/sql-pg": "catalog:", + "@t3tools/client-runtime": "workspace:*", + "@t3tools/contracts": "workspace:*", + "@t3tools/shared": "workspace:*", + "alchemy": "2.0.0-beta.45", + "drizzle-orm": "^1.0.0-rc.1", + "effect": "catalog:" + }, + "devDependencies": { + "@cloudflare/workers-types": "^4.20260520.0", + "@effect/platform-node": "catalog:", + "@effect/vitest": "catalog:", + "@types/node": "catalog:", + "@types/pg": "^8.15.6", + "drizzle-kit": "^1.0.0-rc.1", + "typescript": "catalog:", + "vitest": "catalog:" + } +} diff --git a/infra/relay/src/Config.ts b/infra/relay/src/Config.ts new file mode 100644 index 0000000000..4cd54e86d8 --- /dev/null +++ b/infra/relay/src/Config.ts @@ -0,0 +1,32 @@ +import * as Context from "effect/Context"; +import * as Redacted from "effect/Redacted"; +import * as Schema from "effect/Schema"; + +export const ApnsEnvironment = Schema.Literals(["sandbox", "production"]); +export type ApnsEnvironment = typeof ApnsEnvironment.Type; + +export interface ApnsCredentials { + readonly teamId: string; + readonly keyId: string; + readonly privateKey: Redacted.Redacted; + readonly bundleId: string; + readonly environment: ApnsEnvironment; +} + +export interface RelayConfigurationShape { + readonly relayIssuer: string; + readonly apns: ApnsCredentials; + readonly clerkSecretKey: Redacted.Redacted; + readonly apnsDeliveryJobSigningSecret: Redacted.Redacted; + readonly cloudMintPrivateKey: Redacted.Redacted; + readonly cloudMintPublicKey: string; + readonly managedEndpointBaseDomain: string | undefined; + readonly cloudflareAccountId: string | undefined; + readonly cloudflareZoneId: string | undefined; + readonly cloudflareApiToken: Redacted.Redacted | undefined; +} + +export class RelayConfiguration extends Context.Service< + RelayConfiguration, + RelayConfigurationShape +>()("RelayConfiguration") {} diff --git a/infra/relay/src/RelayCrypto.ts b/infra/relay/src/RelayCrypto.ts new file mode 100644 index 0000000000..a0c2673597 --- /dev/null +++ b/infra/relay/src/RelayCrypto.ts @@ -0,0 +1,16 @@ +import * as Crypto from "effect/Crypto"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; + +export const layer = Layer.succeed( + Crypto.Crypto, + Crypto.make({ + randomBytes: (size) => globalThis.crypto.getRandomValues(new Uint8Array(size)), + digest: (algorithm, data) => + Effect.promise(async () => { + const input = new Uint8Array(data.length); + input.set(data); + return new Uint8Array(await globalThis.crypto.subtle.digest(algorithm, input.buffer)); + }), + }), +); diff --git a/infra/relay/src/agentActivityPayloads.ts b/infra/relay/src/agentActivityPayloads.ts new file mode 100644 index 0000000000..ed3fc3f011 --- /dev/null +++ b/infra/relay/src/agentActivityPayloads.ts @@ -0,0 +1,63 @@ +import type { + RelayAgentActivityAggregateRow, + RelayAgentActivityAggregateState, +} from "@t3tools/contracts/relay"; +import type { ApnsNotificationPayload } from "./apnsDeliveryJobs.ts"; + +const MAX_SUMMARY_TEXT_LENGTH = 120; +const MAX_STATUS_TEXT_LENGTH = 40; +const MAX_DEEP_LINK_LENGTH = 512; +const MAX_ACTIVITY_ROWS = 3; + +function truncateText(value: string, maxLength: number): string { + const trimmed = value.trim(); + if (trimmed.length <= maxLength) { + return trimmed; + } + return trimmed.slice(0, maxLength - 3).trimEnd() + "..."; +} + +function sanitizeDeepLink(value: string): string { + const trimmed = value.trim(); + if (!trimmed.startsWith("/") || trimmed.startsWith("//")) { + return "/"; + } + return truncateText(trimmed, MAX_DEEP_LINK_LENGTH); +} + +export function sanitizeAgentActivityAggregateRow( + row: RelayAgentActivityAggregateRow, +): RelayAgentActivityAggregateRow { + return { + ...row, + projectTitle: truncateText(row.projectTitle, MAX_SUMMARY_TEXT_LENGTH), + threadTitle: truncateText(row.threadTitle, MAX_SUMMARY_TEXT_LENGTH), + modelTitle: truncateText(row.modelTitle, MAX_SUMMARY_TEXT_LENGTH), + status: truncateText(row.status, MAX_STATUS_TEXT_LENGTH), + deepLink: sanitizeDeepLink(row.deepLink), + }; +} + +export function sanitizeAgentActivityAggregateState( + aggregate: RelayAgentActivityAggregateState, +): RelayAgentActivityAggregateState { + return { + ...aggregate, + title: truncateText(aggregate.title, MAX_SUMMARY_TEXT_LENGTH), + subtitle: truncateText(aggregate.subtitle, MAX_SUMMARY_TEXT_LENGTH), + activities: aggregate.activities + .slice(0, MAX_ACTIVITY_ROWS) + .map(sanitizeAgentActivityAggregateRow), + }; +} + +export function sanitizeApnsNotificationPayload( + notification: ApnsNotificationPayload, +): ApnsNotificationPayload { + return { + ...notification, + title: truncateText(notification.title, MAX_SUMMARY_TEXT_LENGTH), + body: truncateText(notification.body, MAX_SUMMARY_TEXT_LENGTH), + deepLink: sanitizeDeepLink(notification.deepLink), + }; +} diff --git a/infra/relay/src/api.test.ts b/infra/relay/src/api.test.ts new file mode 100644 index 0000000000..626f5ade9b --- /dev/null +++ b/infra/relay/src/api.test.ts @@ -0,0 +1,157 @@ +import { describe, expect, it } from "@effect/vitest"; +import * as Context from "effect/Context"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import * as Option from "effect/Option"; +import * as Predicate from "effect/Predicate"; +import * as Redacted from "effect/Redacted"; +import * as Tracer from "effect/Tracer"; +import * as HttpRouter from "effect/unstable/http/HttpRouter"; +import * as HttpServerRequest from "effect/unstable/http/HttpServerRequest"; +import * as HttpServerResponse from "effect/unstable/http/HttpServerResponse"; +import { RelayEnvironmentAuth } from "@t3tools/contracts/relay"; + +import { + isDpopAuthorizationHeader, + relayCors, + relayCorsPreflightHeaders, + relayEnvironmentAuthLayer, + relayNotFoundRoute, + traceRelayHttpRequestWith, + withoutCapturedParentSpan, +} from "./api.ts"; +import * as EnvironmentCredentials from "./persistence/EnvironmentCredentials.ts"; + +function splitHeaderTokens(value: string): ReadonlyArray { + return value.split(",").map((token) => token.trim()); +} + +describe("relay CORS", () => { + it("allows Effect trace propagation headers from browser clients", () => { + expect(splitHeaderTokens(relayCorsPreflightHeaders["access-control-allow-headers"])).toEqual([ + "authorization", + "b3", + "traceparent", + "content-type", + "dpop", + ]); + }); +}); + +describe("relay DPoP authentication", () => { + it("requires the HTTP DPoP authorization scheme", () => { + expect(isDpopAuthorizationHeader("DPoP access-token")).toBe(true); + expect(isDpopAuthorizationHeader("dpop access-token")).toBe(true); + expect(isDpopAuthorizationHeader("Bearer access-token")).toBe(false); + expect(isDpopAuthorizationHeader("access-token")).toBe(false); + }); +}); + +describe("relay environment authentication", () => { + it.effect("preserves credential lookup persistence failures as internal errors", () => { + const failure = new EnvironmentCredentials.EnvironmentCredentialAuthenticatePersistenceError({ + cause: "database unavailable", + }); + const credentials: EnvironmentCredentials.EnvironmentCredentialsShape = { + create: () => Effect.die("unused create"), + authenticate: () => Effect.fail(failure), + revokeForEnvironmentPublicKey: () => Effect.die("unused revoke"), + }; + + return Effect.gen(function* () { + const auth = yield* RelayEnvironmentAuth; + const error = yield* Effect.flip( + auth.bearer(Effect.succeed(HttpServerResponse.empty()), { + credential: Redacted.make("environment-credential"), + endpoint: {} as never, + group: {} as never, + }), + ); + + expect(Predicate.isTagged(error, "RelayInternalError")).toBe(true); + if (Predicate.isTagged(error, "RelayInternalError")) { + expect(error.reason).toBe("persistence_failed"); + } + }).pipe( + Effect.provideService( + HttpServerRequest.HttpServerRequest, + HttpServerRequest.fromWeb(new Request("https://relay.test/v1/server/link")), + ), + Effect.provideService(HttpServerRequest.ParsedSearchParams, {}), + Effect.provideService(HttpRouter.RouteContext, { + params: {}, + route: {} as never, + }), + Effect.provide( + relayEnvironmentAuthLayer.pipe( + Layer.provide(Layer.succeed(EnvironmentCredentials.EnvironmentCredentials, credentials)), + ), + ), + Effect.scoped, + ); + }); +}); + +describe("relay request tracing", () => { + it.effect( + "does not parent endpoint spans to an ambient parent captured while building handlers", + () => + Effect.gen(function* () { + const spans: Array = []; + const tracer = Tracer.make({ + span: (options) => { + const span = new Tracer.NativeSpan(options); + spans.push(span); + return span; + }, + }); + const ambientParent = Tracer.externalSpan({ + traceId: "00000000000000000000000000000001", + spanId: "0000000000000001", + sampled: true, + }); + const endpoint = yield* withoutCapturedParentSpan( + Effect.context().pipe( + Effect.map((capturedContext: Context.Context) => + Effect.fn("relay.test.endpoint")(() => + Effect.succeed(HttpServerResponse.empty({ status: 204 })), + )().pipe(Effect.provideContext(capturedContext)), + ), + ), + ).pipe(Effect.provideService(Tracer.ParentSpan, ambientParent)); + const request = HttpServerRequest.fromWeb( + new Request("https://relay.test/v1/mobile/devices?client=mobile", { + method: "POST", + }), + ); + + yield* traceRelayHttpRequestWith(endpoint, Layer.succeed(Tracer.Tracer, tracer)).pipe( + Effect.provideService(HttpServerRequest.HttpServerRequest, request), + ); + + expect(spans.map((span) => span.name)).toEqual(["http.server POST", "relay.test.endpoint"]); + expect(spans[0]?.kind).toBe("server"); + expect(spans[0]?.attributes.get("url.path")).toBe("/v1/mobile/devices"); + expect(spans[0]?.attributes.get("http.response.status_code")).toBe(204); + expect(Option.isNone(spans[0]!.parent)).toBe(true); + expect(Option.getOrUndefined(spans[1]!.parent)?.spanId).toBe(spans[0]?.spanId); + }), + ); +}); + +describe("relay routing fallback", () => { + it.effect("returns a CORS-compatible 404 response for unmatched paths", () => + Effect.gen(function* () { + const request = HttpServerRequest.fromWeb( + new Request("https://relay.test/v1/environmentsd", { method: "GET" }), + ); + const httpEffect = yield* HttpRouter.toHttpEffect(Layer.merge(relayNotFoundRoute, relayCors)); + const response = yield* httpEffect.pipe( + Effect.provideService(HttpServerRequest.HttpServerRequest, request), + ); + + expect(response.status).toBe(404); + expect(response.headers["access-control-allow-origin"]).toBe("*"); + }).pipe(Effect.scoped), + ); +}); diff --git a/infra/relay/src/api.ts b/infra/relay/src/api.ts new file mode 100644 index 0000000000..08d4d331da --- /dev/null +++ b/infra/relay/src/api.ts @@ -0,0 +1,1016 @@ +import { verifyToken } from "@clerk/backend"; +import { sql as drizzleSql } from "drizzle-orm"; +import * as Data from "effect/Data"; +import * as Crypto from "effect/Crypto"; +import * as Context from "effect/Context"; +import * as DateTime from "effect/DateTime"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import * as Record from "effect/Record"; +import * as Redacted from "effect/Redacted"; +import * as Schema from "effect/Schema"; +import * as Tracer from "effect/Tracer"; +import * as HttpEffect from "effect/unstable/http/HttpEffect"; +import * as HttpMiddleware from "effect/unstable/http/HttpMiddleware"; +import * as HttpPlatform from "effect/unstable/http/HttpPlatform"; +import * as HttpRouter from "effect/unstable/http/HttpRouter"; +import * as HttpServerRequest from "effect/unstable/http/HttpServerRequest"; +import * as HttpServerResponse from "effect/unstable/http/HttpServerResponse"; +import * as HttpApiBuilder from "effect/unstable/httpapi/HttpApiBuilder"; +import * as HttpApiError from "effect/unstable/httpapi/HttpApiError"; +import { encodeOAuthScope } from "@t3tools/shared/oauthScope"; + +import { + RelayApi, + RelayAgentActivityPublishProofExpiredError, + RelayAgentActivityPublishProofInvalidError, + RelayClientAuth, + RelayClientPrincipal, + RelayAccessTokenType, + RelayDpopClientAuth, + RelayEnvironmentConnectScope, + RelayEnvironmentStatusScope, + RelayMobileRegistrationScope, + RelayAuthInvalidError, + type RelayAuthInvalidReason, + RelayEnvironmentAuth, + RelayEnvironmentConnectNotAuthorizedError, + RelayEnvironmentEndpointTimedOutError, + RelayEnvironmentEndpointUnavailableError, + RelayEnvironmentLinkFailedError, + RelayEnvironmentLinkProofExpiredError, + RelayEnvironmentLinkProofInvalidError, + RelayEnvironmentLinkUnavailableError, + RelayEnvironmentPrincipal, + type RelayEnvironmentConnectRequest, + type RelayDpopAccessTokenScope, + RelayInternalError, +} from "@t3tools/contracts/relay"; +import { normalizeRelayIssuer } from "@t3tools/shared/relayJwt"; + +import { verifyAndConsumeDpopProof } from "./dpop.ts"; +import * as DeliveryAttempts from "./persistence/DeliveryAttempts.ts"; +import * as AgentActivityRows from "./persistence/AgentActivityRows.ts"; +import * as Devices from "./persistence/Devices.ts"; +import * as DpopProofs from "./persistence/DpopProofs.ts"; +import * as EnvironmentCredentials from "./persistence/EnvironmentCredentials.ts"; +import * as EnvironmentLinks from "./persistence/EnvironmentLinks.ts"; +import * as LiveActivities from "./persistence/LiveActivities.ts"; +import * as RelayConfiguration from "./Config.ts"; +import * as AgentActivityPublisher from "./services/AgentActivityPublisher.ts"; +import * as EnvironmentConnector from "./services/EnvironmentConnector.ts"; +import * as EnvironmentLinker from "./services/EnvironmentLinker.ts"; +import * as EnvironmentPublishSignatures from "./services/EnvironmentPublishSignatures.ts"; +import * as MobileRegistrations from "./services/MobileRegistrations.ts"; +import { withSpanAttributes, withUserId } from "./telemetry.ts"; +import { RelayDb } from "./db.ts"; +import { + issueDpopAccessToken, + issueLinkChallengeToken, + resolveDpopAccessTokenScopes, + verifyDpopAccessToken, +} from "./relayTokens.ts"; + +export const RelayHttpPlatformLayer = Layer.succeed(HttpPlatform.HttpPlatform, { + fileResponse: () => Effect.die("Relay API does not serve filesystem responses"), + fileWebResponse: () => Effect.die("Relay API does not serve file responses"), +}); + +const relayCorsAllowedMethods = ["GET", "POST", "DELETE", "OPTIONS"] as const; +const relayCorsAllowedHeaders = [ + "authorization", + "b3", + "traceparent", + "content-type", + "dpop", +] as const; +const relayCorsExposedHeaders = ["x-t3-relay-auth-failure", "www-authenticate"] as const; + +const relayCorsHeaders = { + "access-control-allow-origin": "*", + "access-control-expose-headers": relayCorsExposedHeaders.join(","), +} as const; + +export const relayCorsPreflightHeaders = { + ...relayCorsHeaders, + "access-control-allow-methods": relayCorsAllowedMethods.join(","), + "access-control-allow-headers": relayCorsAllowedHeaders.join(","), + "access-control-max-age": "86400", +} as const; + +const appendRelayCredentialResponseHeaders = HttpEffect.appendPreResponseHandler( + (_request, response) => + Effect.succeed( + HttpServerResponse.setHeaders(response, { + "cache-control": "no-store", + pragma: "no-cache", + }), + ), +); + +const appendRelayDpopChallengeHeader = HttpEffect.appendPreResponseHandler((_request, response) => + Effect.succeed( + response.status === 401 + ? HttpServerResponse.setHeader(response, "www-authenticate", "DPoP") + : response, + ), +); + +export const relayCors = HttpRouter.middleware( + Effect.fnUntraced(function* ( + httpEffect: Effect.Effect< + HttpServerResponse.HttpServerResponse, + E, + HttpServerRequest.HttpServerRequest | R + >, + ) { + const request = yield* HttpServerRequest.HttpServerRequest; + if (request.method === "OPTIONS") { + return HttpServerResponse.empty({ + status: 204, + headers: relayCorsPreflightHeaders, + }); + } + const response = yield* httpEffect; + return HttpServerResponse.setHeaders(response, relayCorsHeaders); + }), + { global: true }, +); + +export const relayNotFoundRoute = HttpRouter.add( + "*", + "/*", + HttpServerResponse.empty({ status: 404 }), +); + +export const traceRelayHttpRequest = ( + httpEffect: Effect.Effect< + HttpServerResponse.HttpServerResponse, + E, + HttpServerRequest.HttpServerRequest | R + >, +) => + // HttpMiddleware finalizes its span on the dispatcher; do not close a request-scoped exporter first. + HttpMiddleware.tracer(httpEffect).pipe(Effect.ensuring(Effect.yieldNow)); + +export const traceRelayHttpRequestWith = ( + httpEffect: Effect.Effect< + HttpServerResponse.HttpServerResponse, + E, + HttpServerRequest.HttpServerRequest | R + >, + tracerLayer: Layer.Layer, +) => traceRelayHttpRequest(httpEffect).pipe(Effect.provide(tracerLayer)); + +export const withoutCapturedParentSpan = ( + effect: Effect.Effect, +): Effect.Effect => + Effect.withFiber((fiber) => { + const context = fiber.context; + // HttpApiBuilder captures its build context for route handlers; an event parent would outlive export. + fiber.setContext(Context.omit(Tracer.ParentSpan)(context)); + return effect.pipe(Effect.ensuring(Effect.sync(() => fiber.setContext(context)))); + }); + +export const relayClientAuthLayer = Layer.effect( + RelayClientAuth, + Effect.gen(function* () { + const config = yield* RelayConfiguration.RelayConfiguration; + return { + bearer: Effect.fn("relay.auth.client.bearer")(function* (httpEffect, { credential }) { + const token = Redacted.value(credential); + const verified = yield* verifyClerkBearerToken(config, token).pipe( + Effect.tapError((error) => + Effect.logWarning("relay clerk token verification failed", { + reason: clerkVerificationFailureReason(error.cause), + }), + ), + Effect.catch(() => relayAuthInvalidError("invalid_bearer")), + ); + if (!verified.sub) { + return yield* relayAuthInvalidError("invalid_bearer"); + } + yield* Effect.annotateCurrentSpan({ + "relay.auth.mode": "clerk_bearer", + "relay.auth.subject": verified.sub, + }); + return yield* httpEffect.pipe( + withUserId(verified.sub), + Effect.provideService(RelayClientPrincipal, { + userId: verified.sub, + token, + }), + ); + }), + }; + }), +); + +export const relayEnvironmentAuthLayer = Layer.effect( + RelayEnvironmentAuth, + Effect.gen(function* () { + const credentials = yield* EnvironmentCredentials.EnvironmentCredentials; + return { + bearer: Effect.fn("relay.auth.environment.bearer")(function* (httpEffect, { credential }) { + const token = Redacted.value(credential); + const principal = yield* credentials + .authenticate(token) + .pipe( + Effect.catchTag("EnvironmentCredentialAuthenticatePersistenceError", () => + relayInternalErrorResponse("persistence_failed"), + ), + ); + if (principal._tag === "None") { + return yield* relayAuthInvalidError("not_authorized"); + } + yield* Effect.annotateCurrentSpan({ + "relay.auth.mode": "environment_credential", + }); + return yield* httpEffect.pipe( + withSpanAttributes({ + "relay.environment_id": principal.value.environmentId, + }), + Effect.provideService(RelayEnvironmentPrincipal, principal.value), + ); + }), + }; + }), +); + +export const relayDpopClientAuthLayer = Layer.effect( + RelayDpopClientAuth, + Effect.gen(function* () { + const config = yield* RelayConfiguration.RelayConfiguration; + return { + relayDpop: Effect.fn("relay.auth.dpop_client")(function* (httpEffect, { credential }) { + yield* appendRelayDpopChallengeHeader; + const request = yield* HttpServerRequest.HttpServerRequest; + if (!isDpopAuthorizationHeader(request.headers.authorization)) { + return yield* relayAuthInvalidError("invalid_bearer"); + } + // Effect beta.73 exposes arbitrary HTTP schemes but currently leaves + // the separating spaces in the decoded credential. + const token = Redacted.value(credential).trimStart(); + const now = yield* DateTime.now; + const verified = yield* verifyDpopAccessToken({ + config, + token, + nowEpochSeconds: Math.floor(now.epochMilliseconds / 1_000), + }); + if (!verified) { + return yield* relayAuthInvalidError("invalid_bearer"); + } + yield* Effect.annotateCurrentSpan({ + "relay.auth.mode": "dpop", + "relay.auth.subject": verified.sub, + }); + return yield* httpEffect.pipe( + withUserId(verified.sub), + Effect.provideService(RelayClientPrincipal, { + userId: verified.sub, + token, + proofKeyThumbprint: verified.cnf.jkt, + dpopScopes: verified.scope, + }), + ); + }), + }; + }), +); + +export function isDpopAuthorizationHeader(value: string | undefined): boolean { + return /^DPoP +/iu.test(value ?? ""); +} + +export const metadataApi = HttpApiBuilder.group( + RelayApi, + "metadata", + Effect.fnUntraced(function* (handlers) { + const settings = yield* RelayConfiguration.RelayConfiguration; + const issuer = normalizeRelayIssuer(settings.relayIssuer); + const scopes = [ + RelayEnvironmentConnectScope, + RelayEnvironmentStatusScope, + RelayMobileRegistrationScope, + ] as const; + return handlers + .handle("authorizationServer", () => + Effect.succeed({ + issuer, + token_endpoint: `${issuer}/v1/client/dpop-token`, + grant_types_supported: ["urn:ietf:params:oauth:grant-type:token-exchange"] as const, + token_endpoint_auth_methods_supported: ["none"] as const, + dpop_signing_alg_values_supported: ["ES256"] as const, + scopes_supported: scopes, + }), + ) + .handle("protectedResource", () => + Effect.succeed({ + resource: issuer, + authorization_servers: [issuer], + scopes_supported: scopes, + dpop_bound_access_tokens_required: true, + dpop_signing_alg_values_supported: ["ES256"] as const, + }), + ); + }), +); + +export const healthApi = HttpApiBuilder.group( + RelayApi, + "health", + Effect.fnUntraced(function* (handlers) { + const db = yield* RelayDb; + return handlers.handle( + "health", + Effect.fn("relay.api.health")( + function* () { + const startedAt = yield* Effect.clockWith((clock) => clock.currentTimeMillis); + yield* db + .execute(drizzleSql`SELECT 1`) + .pipe(Effect.withSpan("relay.api.health.db_probe")); + const completedAt = yield* Effect.clockWith((clock) => clock.currentTimeMillis); + yield* Effect.logInfo("relay health db probe completed", { + durationMs: completedAt - startedAt, + }); + return { ok: true, service: "relay" as const }; + }, + Effect.catch(() => relayInternalErrorResponse("database_unavailable")), + ), + ); + }), +); + +export const mobileApi = HttpApiBuilder.group( + RelayApi, + "mobile", + Effect.fnUntraced(function* (handlers) { + const registrations = yield* MobileRegistrations.MobileRegistrations; + const dpopProofs = yield* DpopProofs.DpopProofReplay; + return handlers + .handle( + "registerDevice", + Effect.fn("relay.api.mobile.registerDevice")(function* (args) { + const { payload } = args; + const { userId, token } = yield* RelayClientPrincipal; + const proofKeyThumbprint = yield* requireDpopPrincipalScope("mobile:registration"); + yield* requireDpopThumbprint(proofKeyThumbprint, { + expectedAccessToken: token, + }).pipe(Effect.provideService(DpopProofs.DpopProofReplay, dpopProofs)); + return yield* registrations.registerDevice({ userId, payload }); + }, mapRelayCommonApiErrors("invalid_dpop")), + ) + .handle( + "registerLiveActivity", + Effect.fn("relay.api.mobile.registerLiveActivity")(function* (args) { + const { payload } = args; + const { userId, token } = yield* RelayClientPrincipal; + const proofKeyThumbprint = yield* requireDpopPrincipalScope("mobile:registration"); + yield* requireDpopThumbprint(proofKeyThumbprint, { + expectedAccessToken: token, + }).pipe(Effect.provideService(DpopProofs.DpopProofReplay, dpopProofs)); + return yield* registrations.registerLiveActivity({ userId, payload }); + }, mapRelayCommonApiErrors("invalid_dpop")), + ) + .handle( + "unregisterDevice", + Effect.fn("relay.api.mobile.unregisterDevice")(function* (args) { + const { params } = args; + const { userId, token } = yield* RelayClientPrincipal; + const proofKeyThumbprint = yield* requireDpopPrincipalScope("mobile:registration"); + yield* requireDpopThumbprint(proofKeyThumbprint, { + expectedAccessToken: token, + }).pipe(Effect.provideService(DpopProofs.DpopProofReplay, dpopProofs)); + return yield* registrations.unregisterDevice({ userId, deviceId: params.deviceId }); + }, mapRelayCommonApiErrors("invalid_dpop")), + ); + }), +); + +export const clientApi = HttpApiBuilder.group( + RelayApi, + "client", + Effect.fnUntraced(function* (handlers) { + const config = yield* RelayConfiguration.RelayConfiguration; + const crypto = yield* Crypto.Crypto; + const linker = yield* EnvironmentLinker.EnvironmentLinker; + const links = yield* EnvironmentLinks.EnvironmentLinks; + const credentials = yield* EnvironmentCredentials.EnvironmentCredentials; + return handlers + .handle( + "listEnvironments", + Effect.fn("relay.api.client.listEnvironments")(function* () { + const { userId } = yield* RelayClientPrincipal; + const environments = yield* links.listForUser({ userId }); + return { environments }; + }, mapRelayCommonApiErrors("not_authorized")), + ) + .handle( + "linkEnvironment", + Effect.fn("relay.api.client.linkEnvironment")( + function* (args) { + const { payload } = args; + yield* appendRelayCredentialResponseHeaders; + const { userId } = yield* RelayClientPrincipal; + const result = yield* linker.link({ userId, request: payload }); + return { + ok: true, + cloudUserId: userId, + environmentId: result.environmentId, + endpoint: result.endpoint, + endpointRuntime: result.endpointRuntime, + relayIssuer: config.relayIssuer, + environmentCredential: result.environmentCredential, + cloudMintPublicKey: config.cloudMintPublicKey, + }; + }, + mapErrorTags({ + EnvironmentLinkProofExpired: (_error, traceId) => + new RelayEnvironmentLinkProofExpiredError({ + code: "environment_link_proof_expired", + traceId, + }), + EnvironmentLinkProofInvalid: (linkError, traceId) => + new RelayEnvironmentLinkProofInvalidError({ + code: "environment_link_proof_invalid", + reason: linkError.reason, + traceId, + }), + ManagedEndpointProvisioningNotConfigured: (_error, traceId) => + new RelayEnvironmentLinkUnavailableError({ + code: "environment_link_unavailable", + reason: "managed_endpoint_not_configured", + traceId, + }), + ManagedEndpointProvisioningFailed: (_error, traceId) => + new RelayEnvironmentLinkUnavailableError({ + code: "environment_link_unavailable", + reason: "managed_endpoint_provisioning_failed", + traceId, + }), + ManagedEndpointOriginNotAllowed: (_error, traceId) => + new RelayEnvironmentLinkProofInvalidError({ + code: "environment_link_proof_invalid", + reason: "origin_not_allowed", + traceId, + }), + EnvironmentLinkUpsertPersistenceError: (_error, traceId) => + new RelayEnvironmentLinkFailedError({ + code: "environment_link_failed", + reason: "link_persistence_failed", + traceId, + }), + EnvironmentCredentialCreatePersistenceError: (_error, traceId) => + new RelayEnvironmentLinkFailedError({ + code: "environment_link_failed", + reason: "credential_persistence_failed", + traceId, + }), + DpopProofReplayPersistenceError: (_error, traceId) => + new RelayEnvironmentLinkFailedError({ + code: "environment_link_failed", + reason: "replay_persistence_failed", + traceId, + }), + }), + mapRelayCommonApiErrors("not_authorized"), + ), + ) + .handle( + "createEnvironmentLinkChallenge", + Effect.fn("relay.api.client.createEnvironmentLinkChallenge")(function* (args) { + yield* appendRelayCredentialResponseHeaders; + const { userId } = yield* RelayClientPrincipal; + const now = yield* DateTime.now; + const expiresAt = DateTime.add(now, { minutes: 5 }); + const jti = yield* crypto.randomUUIDv4.pipe( + Effect.catch(() => relayInternalErrorResponse("internal_error")), + ); + const challenge = yield* issueLinkChallengeToken({ + config, + userId, + request: args.payload, + jti, + issuedAtEpochSeconds: Math.floor(now.epochMilliseconds / 1_000), + expiresAtEpochSeconds: Math.floor(expiresAt.epochMilliseconds / 1_000), + }).pipe(Effect.catch(() => relayInternalErrorResponse("internal_error"))); + return { challenge, expiresAt: DateTime.formatIso(expiresAt) }; + }, mapRelayCommonApiErrors("not_authorized")), + ) + .handle( + "unlinkEnvironment", + Effect.fn("relay.api.client.unlinkEnvironment")(function* (args) { + const { params } = args; + const { userId } = yield* RelayClientPrincipal; + const link = yield* links.getForUser({ + userId, + environmentId: params.environmentId, + }); + if (link === null) { + return { ok: false }; + } + const unlinked = yield* links.revokeForUser({ + userId, + environmentId: params.environmentId, + }); + if (unlinked) { + yield* credentials.revokeForEnvironmentPublicKey({ + environmentId: link.environmentId, + environmentPublicKey: link.environmentPublicKey, + }); + } + return { ok: unlinked }; + }, mapRelayCommonApiErrors("not_authorized")), + ); + }), +); + +export const tokenApi = HttpApiBuilder.group( + RelayApi, + "token", + Effect.fnUntraced(function* (handlers) { + const config = yield* RelayConfiguration.RelayConfiguration; + const crypto = yield* Crypto.Crypto; + const dpopProofs = yield* DpopProofs.DpopProofReplay; + return handlers.handle( + "exchangeDpopAccessToken", + Effect.fn("relay.api.token.exchangeDpopAccessToken")(function* (args) { + yield* appendRelayCredentialResponseHeaders; + const issuer = normalizeRelayIssuer(config.relayIssuer); + const requestedScopes = resolveDpopAccessTokenScopes({ + clientId: args.payload.client_id, + scope: args.payload.scope, + }); + yield* Effect.annotateCurrentSpan({ + "relay.auth.mode": "clerk_bearer_token_exchange", + "relay.oauth.client_id": args.payload.client_id, + "relay.oauth.scopes": args.payload.scope, + }); + if (args.payload.resource !== issuer || requestedScopes === null) { + return yield* new HttpApiError.Unauthorized({}); + } + + const verified = yield* verifyClerkBearerToken(config, args.payload.subject_token).pipe( + Effect.catch(() => relayAuthInvalidError("invalid_bearer")), + ); + if (!verified.sub) { + return yield* relayAuthInvalidError("invalid_bearer"); + } + return yield* Effect.gen(function* () { + const proofKeyThumbprint = yield* requireDpopProof().pipe( + Effect.provideService(DpopProofs.DpopProofReplay, dpopProofs), + ); + const now = yield* DateTime.now; + const expiresAt = DateTime.add(now, { minutes: 5 }); + const jti = yield* crypto.randomUUIDv4.pipe( + Effect.catch(() => relayInternalErrorResponse("internal_error")), + ); + return { + access_token: yield* issueDpopAccessToken({ + config, + userId: verified.sub, + proofKeyThumbprint, + jti, + issuedAtEpochSeconds: Math.floor(now.epochMilliseconds / 1_000), + expiresAtEpochSeconds: Math.floor(expiresAt.epochMilliseconds / 1_000), + clientId: args.payload.client_id, + scopes: requestedScopes, + }).pipe(Effect.catch(() => relayInternalErrorResponse("internal_error"))), + issued_token_type: RelayAccessTokenType, + token_type: "DPoP" as const, + expires_in: 300, + scope: encodeOAuthScope(requestedScopes), + }; + }).pipe(withUserId(verified.sub)); + }, mapRelayCommonApiErrors("invalid_dpop")), + ); + }), +); + +export const dpopClientApi = HttpApiBuilder.group( + RelayApi, + "dpopClient", + Effect.fnUntraced(function* (handlers) { + const connector = yield* EnvironmentConnector.EnvironmentConnector; + const dpopProofs = yield* DpopProofs.DpopProofReplay; + return handlers + .handle( + "connectEnvironment", + Effect.fn("relay.api.dpopClient.connectEnvironment")( + function* (args) { + const { params, payload } = args; + yield* appendRelayCredentialResponseHeaders; + const { userId, token } = yield* RelayClientPrincipal; + const proofKeyThumbprint = yield* requireDpopPrincipalScope("environment:connect"); + const requestedThumbprint = resolveConnectClientKeyThumbprint(payload); + if (!requestedThumbprint || requestedThumbprint !== proofKeyThumbprint) { + return yield* new HttpApiError.Unauthorized({}); + } + const clientProofKeyThumbprint = yield* requireDpopThumbprint(proofKeyThumbprint, { + expectedAccessToken: token, + }).pipe(Effect.provideService(DpopProofs.DpopProofReplay, dpopProofs)); + return yield* connector.connect({ + userId, + environmentId: params.environmentId, + clientProofKeyThumbprint, + ...(payload.deviceId ? { deviceId: payload.deviceId } : {}), + }); + }, + mapRelayCommonApiErrors("invalid_dpop"), + mapErrorTags({ + EnvironmentConnectNotAuthorized: (_error, traceId) => + new RelayEnvironmentConnectNotAuthorizedError({ + code: "environment_connect_not_authorized", + traceId, + }), + EnvironmentMintRequestFailed: (_error, traceId) => + new RelayEnvironmentEndpointUnavailableError({ + code: "environment_endpoint_unavailable", + reason: "endpoint_request_failed", + traceId, + }), + EnvironmentMintRequestTimedOut: (_error, traceId) => + new RelayEnvironmentEndpointTimedOutError({ + code: "environment_endpoint_timed_out", + traceId, + }), + EnvironmentMintResponseInvalid: (_error, traceId) => + new RelayEnvironmentEndpointUnavailableError({ + code: "environment_endpoint_unavailable", + reason: "endpoint_response_invalid", + traceId, + }), + }), + ), + ) + .handle( + "getEnvironmentStatus", + Effect.fn("relay.api.dpopClient.getEnvironmentStatus")( + function* (args) { + const { params } = args; + const { userId, token } = yield* RelayClientPrincipal; + const proofKeyThumbprint = yield* requireDpopPrincipalScope("environment:status"); + yield* requireDpopThumbprint(proofKeyThumbprint, { + expectedAccessToken: token, + }).pipe(Effect.provideService(DpopProofs.DpopProofReplay, dpopProofs)); + return yield* connector.status({ + userId, + environmentId: params.environmentId, + }); + }, + mapRelayCommonApiErrors("invalid_dpop"), + mapErrorTags({ + EnvironmentConnectNotAuthorized: (_error, traceId) => + new RelayEnvironmentConnectNotAuthorizedError({ + code: "environment_connect_not_authorized", + traceId, + }), + EnvironmentMintRequestFailed: (_error, traceId) => + new RelayEnvironmentEndpointUnavailableError({ + code: "environment_endpoint_unavailable", + reason: "endpoint_request_failed", + traceId, + }), + EnvironmentMintRequestTimedOut: (_error, traceId) => + new RelayEnvironmentEndpointTimedOutError({ + code: "environment_endpoint_timed_out", + traceId, + }), + EnvironmentMintResponseInvalid: (_error, traceId) => + new RelayEnvironmentEndpointUnavailableError({ + code: "environment_endpoint_unavailable", + reason: "endpoint_response_invalid", + traceId, + }), + }), + ), + ); + }), +); + +export const serverApi = HttpApiBuilder.group( + RelayApi, + "server", + Effect.fnUntraced(function* (handlers) { + const publisher = yield* AgentActivityPublisher.AgentActivityPublisher; + const publishSignatures = yield* EnvironmentPublishSignatures.EnvironmentPublishSignatures; + return handlers.handle( + "publishAgentActivity", + Effect.fn("relay.api.server.publishAgentActivity")( + function* (args) { + const { params, payload } = args; + const principal = yield* RelayEnvironmentPrincipal; + if (principal.environmentId !== params.environmentId) { + return yield* new HttpApiError.Unauthorized({}); + } + yield* publishSignatures.verify({ + environmentId: params.environmentId, + environmentPublicKey: principal.environmentPublicKey, + threadId: params.threadId, + request: payload, + }); + return yield* publisher.publish({ + environmentId: params.environmentId, + environmentPublicKey: principal.environmentPublicKey, + threadId: params.threadId, + state: payload.state, + }); + }, + mapErrorTags({ + EnvironmentPublishPublicKeyMissing: (_error, traceId) => + new RelayAuthInvalidError({ + code: "auth_invalid", + reason: "not_authorized", + traceId, + }), + EnvironmentPublishSignatureExpired: (_error, traceId) => + new RelayAgentActivityPublishProofExpiredError({ + code: "agent_activity_publish_proof_expired", + traceId, + }), + EnvironmentPublishSignatureInvalid: (_error, traceId) => + new RelayAgentActivityPublishProofInvalidError({ + code: "agent_activity_publish_proof_invalid", + reason: "invalid_signature_or_payload", + traceId, + }), + DpopProofReplayPersistenceError: (_error, traceId) => + new RelayInternalError({ + code: "internal_error", + reason: "persistence_failed", + traceId, + }), + ApnsDeliveryJobInvalid: (_error, traceId) => + new RelayInternalError({ + code: "internal_error", + reason: "internal_error", + traceId, + }), + ApnsDeliveryJobExpired: (_error, traceId) => + new RelayInternalError({ + code: "internal_error", + reason: "internal_error", + traceId, + }), + ApnsDeliveryJobClaimInFlight: (_error, traceId) => + new RelayInternalError({ + code: "internal_error", + reason: "internal_error", + traceId, + }), + ApnsDeliveryQueueSendError: (_error, traceId) => + new RelayInternalError({ + code: "internal_error", + reason: "upstream_unavailable", + traceId, + }), + }), + mapRelayCommonApiErrors("not_authorized"), + ), + ); + }), +); + +class ClerkTokenVerificationFailed extends Data.TaggedError("ClerkTokenVerificationFailed")<{ + readonly cause: unknown; +}> {} + +const isHttpUnauthorized = Schema.is(HttpApiError.Unauthorized); + +const currentTraceId = Effect.currentParentSpan.pipe( + Effect.map((span) => span.traceId), + Effect.orElseSucceed(() => "unavailable"), +); + +type RelayCommonPersistenceError = + | Devices.DeviceRegistrationPersistenceError + | Devices.DeviceUnregistrationPersistenceError + | LiveActivities.LiveActivityRegistrationPersistenceError + | EnvironmentLinks.EnvironmentLinkUserListPersistenceError + | EnvironmentLinks.EnvironmentPublicKeyListPersistenceError + | EnvironmentLinks.EnvironmentLinkListPersistenceError + | EnvironmentLinks.EnvironmentLinkLookupPersistenceError + | EnvironmentLinks.EnvironmentLinkRevokePersistenceError + | EnvironmentCredentials.EnvironmentCredentialAuthenticatePersistenceError + | EnvironmentCredentials.EnvironmentCredentialRevokePersistenceError + | DpopProofs.DpopProofReplayPersistenceError + | LiveActivities.LiveActivityTargetListPersistenceError + | AgentActivityRows.AgentActivityRowUpsertPersistenceError + | AgentActivityRows.AgentActivityRowDeletePersistenceError + | AgentActivityRows.AgentActivityRowListPersistenceError + | LiveActivities.LiveActivityDeliveryMarkPersistenceError + | DeliveryAttempts.DeliveryAttemptRecordPersistenceError; + +type MapRelayCommonApiError = + | Exclude + | (Extract extends never ? never : RelayAuthInvalidError) + | (Extract extends never ? never : RelayInternalError); + +function isRelayCommonPersistenceError(error: unknown): error is RelayCommonPersistenceError { + return ( + error instanceof Devices.DeviceRegistrationPersistenceError || + error instanceof Devices.DeviceUnregistrationPersistenceError || + error instanceof LiveActivities.LiveActivityRegistrationPersistenceError || + error instanceof EnvironmentLinks.EnvironmentLinkUserListPersistenceError || + error instanceof EnvironmentLinks.EnvironmentPublicKeyListPersistenceError || + error instanceof EnvironmentLinks.EnvironmentLinkListPersistenceError || + error instanceof EnvironmentLinks.EnvironmentLinkLookupPersistenceError || + error instanceof EnvironmentLinks.EnvironmentLinkRevokePersistenceError || + error instanceof EnvironmentCredentials.EnvironmentCredentialAuthenticatePersistenceError || + error instanceof EnvironmentCredentials.EnvironmentCredentialRevokePersistenceError || + error instanceof DpopProofs.DpopProofReplayPersistenceError || + error instanceof LiveActivities.LiveActivityTargetListPersistenceError || + error instanceof AgentActivityRows.AgentActivityRowUpsertPersistenceError || + error instanceof AgentActivityRows.AgentActivityRowDeletePersistenceError || + error instanceof AgentActivityRows.AgentActivityRowListPersistenceError || + error instanceof LiveActivities.LiveActivityDeliveryMarkPersistenceError || + error instanceof DeliveryAttempts.DeliveryAttemptRecordPersistenceError + ); +} + +function relayInternalErrorResponse(reason: RelayInternalError["reason"]) { + return currentTraceId.pipe( + Effect.flatMap((traceId) => + Effect.fail(new RelayInternalError({ code: "internal_error", reason, traceId })), + ), + ); +} + +function mapRelayCommonApiErrors(authReason: RelayAuthInvalidReason) { + const mapError = Effect.fnUntraced(function* (error: E) { + const traceId = yield* currentTraceId; + if (isHttpUnauthorized(error)) { + return yield* Effect.fail( + new RelayAuthInvalidError({ + code: "auth_invalid", + reason: authReason, + traceId, + }) as MapRelayCommonApiError, + ); + } + if (isRelayCommonPersistenceError(error)) { + return yield* Effect.fail( + new RelayInternalError({ + code: "internal_error", + reason: "persistence_failed", + traceId, + }) as MapRelayCommonApiError, + ); + } + + return yield* Effect.fail(error as MapRelayCommonApiError); + }); + + return ( + effect: Effect.Effect, + ): Effect.Effect, R> => effect.pipe(Effect.catch(mapError)); +} + +type TaggedErrorTag = Extract["_tag"]; + +type MapErrorTagCases = { + readonly [K in TaggedErrorTag]+?: ( + error: Extract, + traceId: string, + ) => unknown; +}; + +type MappedTagError = Cases[keyof Cases] extends ( + ...args: ReadonlyArray +) => infer Error + ? Error + : never; + +type CatchTagCases = { + readonly [K in TaggedErrorTag]+?: ( + error: Extract, + ) => Effect.Effect>; +} & (unknown extends E ? {} : { readonly [K in Exclude>]: never }); + +function mapErrorTags< + E, + Cases extends MapErrorTagCases & + (unknown extends E ? {} : { readonly [K in Exclude>]: never }), +>(cases: Cases) { + const catchCases = Record.map( + cases as Record.ReadonlyRecord< + string, + (error: never, traceId: string) => MappedTagError + >, + (makeError) => (error: never) => + currentTraceId.pipe(Effect.flatMap((traceId) => Effect.fail(makeError(error, traceId)))), + ) as CatchTagCases; + + return ( + self: Effect.Effect, + ): Effect.Effect | MappedTagError, R> => + Effect.catchTags(self, catchCases) as Effect.Effect< + A, + Exclude | MappedTagError, + R + >; +} + +function resolveConnectClientKeyThumbprint(payload: RelayEnvironmentConnectRequest): string | null { + const requestedThumbprint = payload.clientKeyThumbprint ?? payload.clientProofKeyThumbprint; + if (!requestedThumbprint) { + return null; + } + if ( + payload.clientKeyThumbprint && + payload.clientProofKeyThumbprint && + payload.clientKeyThumbprint !== payload.clientProofKeyThumbprint + ) { + return null; + } + return requestedThumbprint; +} + +function safeAuthFailureReason(value: string): string { + return /^[a-z0-9._-]+$/i.test(value) ? value : "unknown"; +} + +function clerkVerificationFailureReason(cause: unknown): string { + if (typeof cause === "object" && cause !== null && "reason" in cause) { + const reason = (cause as { readonly reason?: unknown }).reason; + if (typeof reason === "string" && reason.length > 0) { + return safeAuthFailureReason(reason); + } + } + if (cause instanceof Error && cause.name) { + return safeAuthFailureReason(cause.name); + } + return "unknown"; +} + +function verifyClerkBearerToken(config: RelayConfiguration.RelayConfigurationShape, token: string) { + return Effect.tryPromise({ + try: () => + verifyToken(token, { + secretKey: Redacted.value(config.clerkSecretKey), + audience: normalizeRelayIssuer(config.relayIssuer), + }), + catch: (cause) => new ClerkTokenVerificationFailed({ cause }), + }); +} + +const requireDpopPrincipalScope = Effect.fn("relay.api.require_dpop_principal_scope")(function* ( + scope: RelayDpopAccessTokenScope, +) { + yield* Effect.annotateCurrentSpan({ "relay.dpop.required_scope": scope }); + const principal = yield* RelayClientPrincipal; + if (!principal.proofKeyThumbprint || !principal.dpopScopes?.includes(scope)) { + return yield* new HttpApiError.Unauthorized({}); + } + return principal.proofKeyThumbprint; +}); + +const requireDpopThumbprint = Effect.fn("relay.api.require_dpop_thumbprint")(function* ( + expectedThumbprint: string, + options?: { + readonly expectedAccessToken?: string; + }, +) { + const request = yield* HttpServerRequest.HttpServerRequest; + const now = yield* DateTime.now; + const url = HttpServerRequest.toURL(request); + if (url._tag === "None") { + return yield* new HttpApiError.Unauthorized({}); + } + return yield* verifyAndConsumeDpopProof({ + proof: request.headers.dpop, + method: request.method, + url: url.value.href, + now, + expectedThumbprint, + ...(options?.expectedAccessToken ? { expectedAccessToken: options.expectedAccessToken } : {}), + }); +}); + +const requireDpopProof = Effect.fn("relay.api.require_dpop_proof")(function* (options?: { + readonly expectedAccessToken?: string; +}) { + const request = yield* HttpServerRequest.HttpServerRequest; + const now = yield* DateTime.now; + const url = HttpServerRequest.toURL(request); + if (url._tag === "None") { + return yield* new HttpApiError.Unauthorized({}); + } + return yield* verifyAndConsumeDpopProof({ + proof: request.headers.dpop, + method: request.method, + url: url.value.href, + now, + ...(options?.expectedAccessToken ? { expectedAccessToken: options.expectedAccessToken } : {}), + }); +}); + +const relayAuthInvalidError = Effect.fnUntraced(function* (reason: RelayAuthInvalidReason) { + const traceId = yield* currentTraceId; + yield* Effect.annotateCurrentSpan({ + "relay.trace_id": traceId, + "relay.error.outbound_tag": "RelayAuthInvalidError", + "relay.error.outbound_reason": reason, + }); + return yield* new RelayAuthInvalidError({ code: "auth_invalid", reason, traceId }); +}); diff --git a/infra/relay/src/apns.test.ts b/infra/relay/src/apns.test.ts new file mode 100644 index 0000000000..cb885cebe1 --- /dev/null +++ b/infra/relay/src/apns.test.ts @@ -0,0 +1,116 @@ +import { describe, expect, it } from "@effect/vitest"; +import * as DateTime from "effect/DateTime"; + +import type { RelayAgentActivityAggregateState } from "@t3tools/contracts/relay"; +import { makeLiveActivityRequest, makePushNotificationRequest } from "./apns.ts"; +import { EnvironmentId, ThreadId } from "@t3tools/contracts"; + +describe("makeLiveActivityRequest", () => { + const now = DateTime.makeUnsafe(0); + const state: RelayAgentActivityAggregateState = { + title: "T3 Code", + subtitle: "Agent work in progress", + activeCount: 1, + updatedAt: DateTime.formatIso(now), + activities: [ + { + environmentId: EnvironmentId.make("env"), + threadId: ThreadId.make("thread"), + projectTitle: "Project", + threadTitle: "Thread", + modelTitle: "gpt-5.4", + phase: "running" as const, + status: "Working", + updatedAt: DateTime.formatIso(now), + deepLink: "/", + }, + ], + }; + + it("requests an update push token when remotely starting a Live Activity", () => { + const request = makeLiveActivityRequest({ + event: "start", + token: "token", + state, + nowEpochSeconds: Math.floor(now.epochMilliseconds / 1_000), + nowIso: DateTime.formatIso(now), + }); + + expect(request.priority).toBe("10"); + expect(request.payload).toMatchObject({ + aps: { + event: "start", + "attributes-type": "LiveActivityAttributes", + "input-push-token": 1, + "content-state": { + name: "AgentActivity", + }, + }, + }); + }); + + it("builds a low-priority update payload", () => { + const request = makeLiveActivityRequest({ + event: "update", + token: "token", + state, + nowEpochSeconds: Math.floor(now.epochMilliseconds / 1_000), + nowIso: DateTime.formatIso(now), + }); + + expect(request.priority).toBe("5"); + expect(request.payload).toMatchObject({ + aps: { + event: "update", + "content-state": { + name: "AgentActivity", + }, + }, + }); + }); + + it("builds an end payload with a dismissal date", () => { + const request = makeLiveActivityRequest({ + event: "end", + token: "token", + state, + nowEpochSeconds: Math.floor(now.epochMilliseconds / 1_000), + nowIso: DateTime.formatIso(now), + }); + + expect(request.priority).toBe("10"); + expect(request.payload).toMatchObject({ + aps: { + event: "end", + "dismissal-date": 300, + }, + }); + }); + + it("builds a standard APNs alert payload with routing metadata", () => { + const request = makePushNotificationRequest({ + token: "push-token", + notification: { + title: "Thread", + body: "Input: Project", + environmentId: "env", + threadId: "thread", + deepLink: "/threads/env/thread", + }, + }); + + expect(request.priority).toBe("10"); + expect(request.payload).toMatchObject({ + aps: { + alert: { + title: "Thread", + body: "Input: Project", + }, + sound: "default", + }, + environmentId: "env", + threadId: "thread", + deepLink: "/threads/env/thread", + }); + }); +}); diff --git a/infra/relay/src/apns.ts b/infra/relay/src/apns.ts new file mode 100644 index 0000000000..3d1063e623 --- /dev/null +++ b/infra/relay/src/apns.ts @@ -0,0 +1,274 @@ +import * as NodeCrypto from "node:crypto"; + +import type { RelayAgentActivityAggregateState } from "@t3tools/contracts/relay"; +import * as Data from "effect/Data"; +import * as Effect from "effect/Effect"; +import * as Encoding from "effect/Encoding"; +import * as Option from "effect/Option"; +import * as Redacted from "effect/Redacted"; +import * as Schema from "effect/Schema"; +import { + Headers, + HttpClient, + HttpClientRequest, + type HttpBody, + type HttpClientError, +} from "effect/unstable/http"; +import type { ApnsCredentials } from "./Config.ts"; +import type { ApnsNotificationPayload } from "./apnsDeliveryJobs.ts"; + +const LIVE_ACTIVITY_NAME = "AgentActivity"; +const STALE_AFTER_SECONDS = 2 * 60; +const DISMISS_AFTER_SECONDS = 5 * 60; + +export type ApnsLiveActivityEvent = "start" | "update" | "end"; + +export interface ApnsLiveActivityRequest { + readonly token: string; + readonly event: ApnsLiveActivityEvent; + readonly priority: "5" | "10"; + readonly payload: unknown; +} + +export interface ApnsPushNotificationRequest { + readonly token: string; + readonly priority: "10"; + readonly payload: unknown; +} + +export interface ApnsDeliveryResult { + readonly ok: boolean; + readonly status: number; + readonly reason?: string; + readonly apnsId: string | null; +} + +export class ApnsSigningError extends Data.TaggedError("ApnsSigningError")<{ + readonly cause: unknown; +}> {} + +export class ApnsHttpRequestError extends Data.TaggedError("ApnsHttpRequestError")<{ + readonly cause: HttpClientError.HttpClientError | HttpBody.HttpBodyError; +}> {} + +export class ApnsInvalidResponseError extends Data.TaggedError("ApnsInvalidResponseError")<{ + readonly cause: unknown; +}> {} + +export type ApnsError = ApnsSigningError | ApnsHttpRequestError | ApnsInvalidResponseError; + +const decodeApnsErrorResponseJson = Schema.decodeUnknownOption( + Schema.fromJsonString( + Schema.Struct({ + reason: Schema.optional(Schema.String), + }), + ), +); + +function makeApnsJwt(input: { + readonly teamId: ApnsCredentials["teamId"]; + readonly keyId: ApnsCredentials["keyId"]; + readonly privateKey: ApnsCredentials["privateKey"]; + readonly issuedAtUnixSeconds: number; +}): Effect.Effect { + return Effect.try({ + try: () => { + const privateKey = Redacted.value(input.privateKey); + const header = Encoding.encodeBase64Url(JSON.stringify({ alg: "ES256", kid: input.keyId })); + const payload = Encoding.encodeBase64Url( + JSON.stringify({ iss: input.teamId, iat: input.issuedAtUnixSeconds }), + ); + const signingInput = `${header}.${payload}`; + const signature = NodeCrypto.createSign("sha256") + .update(signingInput) + .sign({ + key: privateKey.replace(/\\n/g, "\n"), + dsaEncoding: "ieee-p1363", + }); + return `${signingInput}.${Encoding.encodeBase64Url(signature)}`; + }, + catch: (cause) => new ApnsSigningError({ cause }), + }); +} + +function contentState(state: RelayAgentActivityAggregateState) { + return { + name: LIVE_ACTIVITY_NAME, + props: JSON.stringify(state), + }; +} + +interface LiveActivityRequestBase { + readonly token: string; + readonly nowEpochSeconds: number; + readonly nowIso: string; +} + +export type MakeLiveActivityRequestInput = + | (LiveActivityRequestBase & { + readonly event: "end"; + readonly state: RelayAgentActivityAggregateState | null; + }) + | (LiveActivityRequestBase & { + readonly event: "start" | "update"; + readonly state: RelayAgentActivityAggregateState; + }); + +export function makeLiveActivityRequest( + input: MakeLiveActivityRequestInput, +): ApnsLiveActivityRequest { + const timestamp = input.nowEpochSeconds; + if (input.event === "end") { + return { + token: input.token, + event: input.event, + priority: "10", + payload: { + aps: { + timestamp, + event: "end", + ...(input.state ? { "content-state": contentState(input.state) } : {}), + "dismissal-date": timestamp + DISMISS_AFTER_SECONDS, + }, + }, + }; + } + + const state = input.state; + return { + token: input.token, + event: input.event, + priority: input.event === "update" ? "5" : "10", + payload: { + aps: { + timestamp, + event: input.event, + ...(input.event === "start" + ? { + "attributes-type": "LiveActivityAttributes", + attributes: {}, + "input-push-token": 1, + alert: { + title: state.title, + body: state.subtitle, + }, + } + : {}), + "content-state": contentState(state), + "stale-date": timestamp + STALE_AFTER_SECONDS, + }, + }, + }; +} + +export function makePushNotificationRequest(input: { + readonly token: string; + readonly notification: ApnsNotificationPayload; +}): ApnsPushNotificationRequest { + return { + token: input.token, + priority: "10", + payload: { + aps: { + alert: { + title: input.notification.title, + body: input.notification.body, + }, + sound: "default", + }, + environmentId: input.notification.environmentId, + threadId: input.notification.threadId, + deepLink: input.notification.deepLink, + }, + }; +} + +function apnsReasonFromBody(body: string): string | undefined { + if (body.trim().length === 0) { + return undefined; + } + return Option.match(decodeApnsErrorResponseJson(body), { + onNone: () => body, + onSome: (parsed) => parsed.reason ?? body, + }); +} + +export const sendLiveActivityRequest = Effect.fn("relay.apns.send_live_activity_request")( + function* (input: { + readonly credentials: ApnsCredentials; + readonly request: ApnsLiveActivityRequest; + readonly issuedAtUnixSeconds: number; + }) { + yield* Effect.annotateCurrentSpan({ "relay.apns.event": input.request.event }); + const jwt = yield* makeApnsJwt({ + ...input.credentials, + issuedAtUnixSeconds: input.issuedAtUnixSeconds, + }); + const host = + input.credentials.environment === "production" + ? "https://api.push.apple.com" + : "https://api.sandbox.push.apple.com"; + const httpClient = yield* HttpClient.HttpClient; + const response = yield* HttpClientRequest.post(`${host}/3/device/${input.request.token}`).pipe( + HttpClientRequest.setHeaders({ + authorization: `bearer ${jwt}`, + "apns-priority": input.request.priority, + "apns-push-type": "liveactivity", + "apns-topic": `${input.credentials.bundleId}.push-type.liveactivity`, + }), + HttpClientRequest.bodyJson(input.request.payload), + Effect.flatMap(httpClient.execute), + Effect.mapError((cause) => new ApnsHttpRequestError({ cause })), + ); + const responseText = yield* response.text.pipe( + Effect.mapError((cause) => new ApnsHttpRequestError({ cause })), + ); + const reason = apnsReasonFromBody(responseText); + return { + ok: response.status >= 200 && response.status < 300, + status: response.status, + ...(reason === undefined ? {} : { reason }), + apnsId: Option.getOrNull(Headers.get(response.headers, "apns-id")), + }; + }, +); + +export const sendPushNotificationRequest = Effect.fn("relay.apns.send_push_notification_request")( + function* (input: { + readonly credentials: ApnsCredentials; + readonly request: ApnsPushNotificationRequest; + readonly issuedAtUnixSeconds: number; + }) { + yield* Effect.annotateCurrentSpan({ "relay.apns.event": "push_notification" }); + const jwt = yield* makeApnsJwt({ + ...input.credentials, + issuedAtUnixSeconds: input.issuedAtUnixSeconds, + }); + const host = + input.credentials.environment === "production" + ? "https://api.push.apple.com" + : "https://api.sandbox.push.apple.com"; + const httpClient = yield* HttpClient.HttpClient; + const response = yield* HttpClientRequest.post(`${host}/3/device/${input.request.token}`).pipe( + HttpClientRequest.setHeaders({ + authorization: `bearer ${jwt}`, + "apns-priority": input.request.priority, + "apns-push-type": "alert", + "apns-topic": input.credentials.bundleId, + }), + HttpClientRequest.bodyJson(input.request.payload), + Effect.flatMap(httpClient.execute), + Effect.mapError((cause) => new ApnsHttpRequestError({ cause })), + ); + const responseText = yield* response.text.pipe( + Effect.mapError((cause) => new ApnsHttpRequestError({ cause })), + ); + const reason = apnsReasonFromBody(responseText); + return { + ok: response.status >= 200 && response.status < 300, + status: response.status, + ...(reason === undefined ? {} : { reason }), + apnsId: Option.getOrNull(Headers.get(response.headers, "apns-id")), + }; + }, +); diff --git a/infra/relay/src/apnsDeliveryJobs.test.ts b/infra/relay/src/apnsDeliveryJobs.test.ts new file mode 100644 index 0000000000..428dc3a82b --- /dev/null +++ b/infra/relay/src/apnsDeliveryJobs.test.ts @@ -0,0 +1,221 @@ +import { describe, expect, it } from "@effect/vitest"; +import { EnvironmentId, ThreadId } from "@t3tools/contracts"; +import type { RelayAgentActivityAggregateState } from "@t3tools/contracts/relay"; +import * as Redacted from "effect/Redacted"; + +import { + makeApnsDeliveryJobPayload, + signApnsDeliveryJob, + verifySignedApnsDeliveryJob, +} from "./apnsDeliveryJobs.ts"; + +const secret = Redacted.make("queue-signing-secret"); +const aggregate: RelayAgentActivityAggregateState = { + title: "T3 Code", + subtitle: "Agent work in progress", + activeCount: 1, + updatedAt: "2026-05-25T00:00:00.000Z", + activities: [ + { + environmentId: EnvironmentId.make("env"), + threadId: ThreadId.make("thread"), + projectTitle: "Project", + threadTitle: "Thread", + modelTitle: "gpt-5.4", + phase: "running", + status: "Working", + updatedAt: "2026-05-25T00:00:00.000Z", + deepLink: "/threads/env/thread", + }, + ], +}; + +const notification = { + title: "Thread", + body: "Input: Project", + environmentId: "env", + threadId: "thread", + deepLink: "/threads/env/thread", +}; + +describe("apnsDeliveryJobs", () => { + it("rejects tampered signed queue jobs", () => { + const payload = makeApnsDeliveryJobPayload({ + kind: "live_activity_end", + userId: "user-1", + deviceId: "device-1", + token: "token-1", + aggregate: null, + createdAt: "2026-05-25T00:00:00.000Z", + expiresAt: "2026-05-25T00:05:00.000Z", + jobId: "job-1", + }); + const signed = signApnsDeliveryJob({ secret, payload }); + const tampered = { + ...signed, + payload: { + ...signed.payload, + target: { + ...signed.payload.target, + token: "attacker-token", + }, + }, + }; + + const result = verifySignedApnsDeliveryJob({ + secret, + job: tampered, + nowMs: 0, + }); + + expect(result).toMatchObject({ + _tag: "ApnsDeliveryJobInvalid", + }); + }); + + it("rejects Live Activity start jobs without aggregate state", () => { + const payload = makeApnsDeliveryJobPayload({ + kind: "live_activity_start", + userId: "user-1", + deviceId: "device-1", + token: "token-1", + aggregate: null, + createdAt: "2026-05-25T00:00:00.000Z", + expiresAt: "2026-05-25T00:05:00.000Z", + jobId: "job-start-invalid", + }); + const signed = signApnsDeliveryJob({ secret, payload }); + + const result = verifySignedApnsDeliveryJob({ + secret, + job: signed, + nowMs: 0, + }); + + expect(result).toMatchObject({ + _tag: "ApnsDeliveryJobInvalid", + message: "Live Activity start/update jobs require an aggregate.", + }); + }); + + it("rejects push notification jobs carrying aggregate state", () => { + const payload = makeApnsDeliveryJobPayload({ + kind: "push_notification", + userId: "user-1", + deviceId: "device-1", + token: "token-1", + aggregate, + notification, + createdAt: "2026-05-25T00:00:00.000Z", + expiresAt: "2026-05-25T00:05:00.000Z", + jobId: "job-push-invalid", + }); + const signed = signApnsDeliveryJob({ secret, payload }); + + const result = verifySignedApnsDeliveryJob({ + secret, + job: signed, + nowMs: 0, + }); + + expect(result).toMatchObject({ + _tag: "ApnsDeliveryJobInvalid", + message: "Push notification jobs must not carry aggregate state.", + }); + }); + + it("accepts minimal kind-specific signed queue jobs", () => { + const pushPayload = makeApnsDeliveryJobPayload({ + kind: "push_notification", + userId: "user-1", + deviceId: "device-1", + token: "token-1", + aggregate: null, + notification, + createdAt: "2026-05-25T00:00:00.000Z", + expiresAt: "2026-05-25T00:05:00.000Z", + jobId: "job-push-valid", + }); + const liveActivityPayload = makeApnsDeliveryJobPayload({ + kind: "live_activity_update", + userId: "user-1", + deviceId: "device-1", + token: "token-1", + aggregate, + createdAt: "2026-05-25T00:00:00.000Z", + expiresAt: "2026-05-25T00:05:00.000Z", + jobId: "job-live-valid", + }); + + expect( + verifySignedApnsDeliveryJob({ + secret, + job: signApnsDeliveryJob({ secret, payload: pushPayload }), + nowMs: 0, + }), + ).toEqual(pushPayload); + expect( + verifySignedApnsDeliveryJob({ + secret, + job: signApnsDeliveryJob({ secret, payload: liveActivityPayload }), + nowMs: 0, + }), + ).toEqual(liveActivityPayload); + }); + + it("rejects jobs with invalid or overlong time windows", () => { + const basePayload = makeApnsDeliveryJobPayload({ + kind: "live_activity_end", + userId: "user-1", + deviceId: "device-1", + token: "token-1", + aggregate: null, + createdAt: "2026-05-25T00:00:00.000Z", + expiresAt: "2026-05-25T00:10:00.000Z", + jobId: "job-window", + }); + const invalidCreatedAt = { + ...basePayload, + createdAt: "not-a-date", + }; + const invertedWindow = { + ...basePayload, + expiresAt: "2026-05-24T23:59:59.000Z", + }; + const overlongWindow = { + ...basePayload, + expiresAt: "2026-05-25T00:10:01.000Z", + }; + + expect( + verifySignedApnsDeliveryJob({ + secret, + job: signApnsDeliveryJob({ secret, payload: invalidCreatedAt }), + nowMs: 0, + }), + ).toMatchObject({ + _tag: "ApnsDeliveryJobInvalid", + message: "Invalid APNs delivery job creation time.", + }); + expect( + verifySignedApnsDeliveryJob({ + secret, + job: signApnsDeliveryJob({ secret, payload: invertedWindow }), + nowMs: 0, + }), + ).toMatchObject({ + _tag: "ApnsDeliveryJobInvalid", + message: "Invalid APNs delivery job time window.", + }); + expect( + verifySignedApnsDeliveryJob({ + secret, + job: signApnsDeliveryJob({ secret, payload: overlongWindow }), + nowMs: 0, + }), + ).toMatchObject({ + _tag: "ApnsDeliveryJobInvalid", + message: "APNs delivery job time window is too long.", + }); + }); +}); diff --git a/infra/relay/src/apnsDeliveryJobs.ts b/infra/relay/src/apnsDeliveryJobs.ts new file mode 100644 index 0000000000..0de28197e0 --- /dev/null +++ b/infra/relay/src/apnsDeliveryJobs.ts @@ -0,0 +1,196 @@ +import * as NodeCrypto from "node:crypto"; + +import { RelayAgentActivityAggregateState, type RelayDeliveryKind } from "@t3tools/contracts/relay"; +import { stableStringify } from "@t3tools/shared/relaySigning"; +import * as Data from "effect/Data"; +import * as DateTime from "effect/DateTime"; +import * as Option from "effect/Option"; +import * as Redacted from "effect/Redacted"; +import * as Schema from "effect/Schema"; + +const MAX_JOB_AGE_MS = 10 * 60 * 1_000; +export const APNS_DELIVERY_JOB_SIGNING_ALGORITHM = "hmac-sha256"; + +const ApnsDeliveryKind = Schema.Literals([ + "live_activity_start", + "live_activity_update", + "live_activity_end", + "push_notification", +]); + +export const ApnsNotificationPayload = Schema.Struct({ + title: Schema.String, + body: Schema.String, + environmentId: Schema.String, + threadId: Schema.String, + deepLink: Schema.String, +}); +export type ApnsNotificationPayload = typeof ApnsNotificationPayload.Type; + +export const ApnsDeliveryJobPayload = Schema.Struct({ + version: Schema.Literal(1), + jobId: Schema.String, + kind: ApnsDeliveryKind, + target: Schema.Struct({ + userId: Schema.String, + deviceId: Schema.String, + token: Schema.String, + }), + aggregate: Schema.NullOr(RelayAgentActivityAggregateState), + notification: Schema.NullOr(ApnsNotificationPayload), + createdAt: Schema.String, + expiresAt: Schema.String, +}); +export type ApnsDeliveryJobPayload = typeof ApnsDeliveryJobPayload.Type; + +export const SignedApnsDeliveryJob = Schema.Struct({ + algorithm: Schema.Literal(APNS_DELIVERY_JOB_SIGNING_ALGORITHM), + payload: ApnsDeliveryJobPayload, + signature: Schema.String, +}); +export type SignedApnsDeliveryJob = typeof SignedApnsDeliveryJob.Type; + +export class ApnsDeliveryJobInvalid extends Data.TaggedError("ApnsDeliveryJobInvalid")<{ + readonly message: string; +}> {} + +export class ApnsDeliveryJobExpired extends Data.TaggedError("ApnsDeliveryJobExpired")<{ + readonly expiresAt: string; +}> {} + +export type ApnsDeliveryJobVerificationError = ApnsDeliveryJobInvalid | ApnsDeliveryJobExpired; + +export function makeApnsDeliveryJobPayload(input: { + readonly kind: RelayDeliveryKind; + readonly userId: string; + readonly deviceId: string; + readonly token: string; + readonly aggregate: ApnsDeliveryJobPayload["aggregate"]; + readonly notification?: ApnsNotificationPayload | null; + readonly createdAt: string; + readonly expiresAt: string; + readonly jobId: string; +}): ApnsDeliveryJobPayload { + return { + version: 1, + jobId: input.jobId, + kind: input.kind, + target: { + userId: input.userId, + deviceId: input.deviceId, + token: input.token, + }, + aggregate: input.aggregate, + notification: input.notification ?? null, + createdAt: input.createdAt, + expiresAt: input.expiresAt, + }; +} + +export function expiresAtForJob(createdAtMs: number): string { + return DateTime.formatIso(Option.getOrThrow(DateTime.make(createdAtMs + MAX_JOB_AGE_MS))); +} + +function validatePayloadShape(payload: ApnsDeliveryJobPayload): ApnsDeliveryJobInvalid | null { + switch (payload.kind) { + case "live_activity_start": + case "live_activity_update": + if (payload.aggregate === null) { + return new ApnsDeliveryJobInvalid({ + message: "Live Activity start/update jobs require an aggregate.", + }); + } + if (payload.notification !== null) { + return new ApnsDeliveryJobInvalid({ + message: "Live Activity jobs must not carry push notification payloads.", + }); + } + return null; + case "live_activity_end": + if (payload.notification !== null) { + return new ApnsDeliveryJobInvalid({ + message: "Live Activity jobs must not carry push notification payloads.", + }); + } + return null; + case "push_notification": + if (payload.notification === null) { + return new ApnsDeliveryJobInvalid({ + message: "Push notification jobs require a notification payload.", + }); + } + if (payload.aggregate !== null) { + return new ApnsDeliveryJobInvalid({ + message: "Push notification jobs must not carry aggregate state.", + }); + } + return null; + } +} + +function signatureForPayload(input: { + readonly secret: Redacted.Redacted; + readonly payload: ApnsDeliveryJobPayload; +}): string { + return NodeCrypto.createHmac("sha256", Redacted.value(input.secret)) + .update(stableStringify(input.payload)) + .digest("base64url"); +} + +function timingSafeEqualBase64Url(left: string, right: string): boolean { + const leftBuffer = Buffer.from(left, "base64url"); + const rightBuffer = Buffer.from(right, "base64url"); + if (leftBuffer.length !== rightBuffer.length) { + return false; + } + return NodeCrypto.timingSafeEqual(leftBuffer, rightBuffer); +} + +export function signApnsDeliveryJob(input: { + readonly secret: Redacted.Redacted; + readonly payload: ApnsDeliveryJobPayload; +}): SignedApnsDeliveryJob { + return { + algorithm: APNS_DELIVERY_JOB_SIGNING_ALGORITHM, + payload: input.payload, + signature: signatureForPayload(input), + }; +} + +export function verifySignedApnsDeliveryJob(input: { + readonly secret: Redacted.Redacted; + readonly job: SignedApnsDeliveryJob; + readonly nowMs: number; +}): ApnsDeliveryJobPayload | ApnsDeliveryJobVerificationError { + const invalidPayload = validatePayloadShape(input.job.payload); + if (invalidPayload !== null) { + return invalidPayload; + } + const createdAt = DateTime.make(input.job.payload.createdAt); + if (Option.isNone(createdAt)) { + return new ApnsDeliveryJobInvalid({ message: "Invalid APNs delivery job creation time." }); + } + const expiresAt = DateTime.make(input.job.payload.expiresAt); + if (Option.isNone(expiresAt)) { + return new ApnsDeliveryJobInvalid({ message: "Invalid APNs delivery job expiry." }); + } + const createdAtMs = createdAt.value.epochMilliseconds; + const expiresAtMs = expiresAt.value.epochMilliseconds; + if (expiresAtMs <= createdAtMs) { + return new ApnsDeliveryJobInvalid({ message: "Invalid APNs delivery job time window." }); + } + if (expiresAtMs - createdAtMs > MAX_JOB_AGE_MS) { + return new ApnsDeliveryJobInvalid({ message: "APNs delivery job time window is too long." }); + } + if (expiresAtMs <= input.nowMs) { + return new ApnsDeliveryJobExpired({ expiresAt: input.job.payload.expiresAt }); + } + const expected = signatureForPayload({ + secret: input.secret, + payload: input.job.payload, + }); + if (!timingSafeEqualBase64Url(input.job.signature, expected)) { + return new ApnsDeliveryJobInvalid({ message: "Invalid APNs delivery job signature." }); + } + return input.job.payload; +} diff --git a/infra/relay/src/db.test.ts b/infra/relay/src/db.test.ts new file mode 100644 index 0000000000..5a708d5479 --- /dev/null +++ b/infra/relay/src/db.test.ts @@ -0,0 +1,182 @@ +import * as NodeFileSystem from "@effect/platform-node/NodeFileSystem"; +import * as NodePath from "@effect/platform-node/NodePath"; +import { describe, expect, it } from "@effect/vitest"; +import * as Data from "effect/Data"; +import * as Effect from "effect/Effect"; +import * as FileSystem from "effect/FileSystem"; +import * as Layer from "effect/Layer"; +import * as Path from "effect/Path"; + +import { relayPostgresDatabaseRegion } from "./db.ts"; +import { parseJsonString } from "./persistence/json.ts"; + +const migrationsDir = "migrations/postgres"; +const schemaFile = "src/schema.ts"; +const NodeTestServices = Layer.mergeAll(NodeFileSystem.layer, NodePath.layer); + +class DbMigrationTestError extends Data.TaggedError("DbMigrationTestError")<{ + readonly message: string; + readonly cause: unknown; +}> {} + +interface DrizzleKitPostgresApi { + readonly generateDrizzleJson: ( + imports: Record, + prevId?: string, + schemaFilters?: ReadonlyArray, + ) => Promise; + readonly generateMigration: (prev: unknown, cur: unknown) => Promise>; +} + +const readMigrationDirectories = Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const entries = yield* fs.readDirectory(migrationsDir); + const directories = yield* Effect.all( + entries.map((entry) => + fs + .stat(path.join(migrationsDir, entry)) + .pipe(Effect.map((stat) => (stat.type === "Directory" ? entry : null))), + ), + ); + return directories.filter((entry): entry is string => entry !== null).sort(); +}); + +const readMigrationSqlFiles = Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const directories = yield* readMigrationDirectories; + const files = yield* Effect.all( + directories.map((directory) => + Effect.gen(function* () { + const migrationPath = path.join(migrationsDir, directory, "migration.sql"); + const exists = yield* fs.exists(migrationPath); + if (!exists) return null; + const sql = yield* fs.readFileString(migrationPath); + return { directory, sql }; + }), + ), + ); + return files.filter( + (file): file is { readonly directory: string; readonly sql: string } => file !== null, + ); +}); + +const readLatestMigrationSnapshot = Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const directories = yield* readMigrationDirectories; + const directoriesWithSnapshots = yield* Effect.all( + directories.map((directory) => + fs + .exists(path.join(migrationsDir, directory, "snapshot.json")) + .pipe(Effect.map((exists) => (exists ? directory : null))), + ), + ); + const latestDirectory = directoriesWithSnapshots.findLast( + (directory): directory is string => directory !== null, + ); + if (!latestDirectory) { + return null; + } + const snapshotPath = path.join(migrationsDir, latestDirectory, "snapshot.json"); + const exists = yield* fs.exists(snapshotPath); + if (!exists) { + return { + directory: latestDirectory, + snapshot: null, + }; + } + const snapshot = yield* parseJsonString(yield* fs.readFileString(snapshotPath)); + return { + directory: latestDirectory, + snapshot, + }; +}); + +const loadDrizzleKit = Effect.tryPromise({ + try: () => import("drizzle-kit/api-postgres") as Promise, + catch: (cause) => + new DbMigrationTestError({ + message: "failed to load drizzle-kit postgres api", + cause, + }), +}); + +const loadRelaySchema = Effect.gen(function* () { + const path = yield* Path.Path; + return yield* Effect.tryPromise({ + try: () => import(path.resolve(schemaFile)) as Promise>, + catch: (cause) => + new DbMigrationTestError({ + message: "failed to load relay schema", + cause, + }), + }); +}); + +describe("relay database migrations", () => { + it("pins the PlanetScale database near west coast Worker traffic", () => { + expect(relayPostgresDatabaseRegion).toEqual({ slug: "us-west" }); + }); + + it.effect("does not leave empty generated migration directories behind", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const directories = yield* readMigrationDirectories; + const emptyDirectories = yield* Effect.all( + directories.map((directory) => + fs + .readDirectory(path.join(migrationsDir, directory)) + .pipe(Effect.map((entries) => (entries.length === 0 ? directory : null))), + ), + ).pipe(Effect.map((entries) => entries.filter((entry): entry is string => entry !== null))); + + expect(emptyDirectories).toEqual([]); + }).pipe(Effect.provide(NodeTestServices)), + ); + + it.effect("starts from a single baseline migration", () => + Effect.gen(function* () { + const migrations = yield* readMigrationSqlFiles; + + expect(migrations).toHaveLength(1); + expect(migrations[0]?.directory).toContain("baseline"); + expect(migrations[0]?.sql).toContain('CREATE TABLE "relay_environment_credentials"'); + expect(migrations[0]?.sql).toContain('"environment_public_key" text NOT NULL'); + }).pipe(Effect.provide(NodeTestServices)), + ); + + it.effect( + "keeps the latest migration snapshot aligned with the relay schema", + () => + Effect.gen(function* () { + const latest = yield* readLatestMigrationSnapshot; + expect(latest).not.toBeNull(); + expect(latest?.snapshot, `${latest?.directory} is missing snapshot.json`).not.toBeNull(); + + const kit = yield* loadDrizzleKit; + const relaySchema = yield* loadRelaySchema; + const currentSnapshot = yield* Effect.tryPromise({ + try: () => kit.generateDrizzleJson(relaySchema), + catch: (cause) => + new DbMigrationTestError({ + message: "failed to generate current drizzle snapshot", + cause, + }), + }); + const statements = yield* Effect.tryPromise({ + try: () => kit.generateMigration(latest?.snapshot, currentSnapshot), + catch: (cause) => + new DbMigrationTestError({ + message: "failed to diff relay schema", + cause, + }), + }); + + expect(statements).toEqual([]); + }).pipe(Effect.provide(NodeTestServices)), + 20_000, + ); +}); diff --git a/infra/relay/src/db.ts b/infra/relay/src/db.ts new file mode 100644 index 0000000000..d1a2bc912e --- /dev/null +++ b/infra/relay/src/db.ts @@ -0,0 +1,50 @@ +import type { PgClient } from "@effect/sql-pg/PgClient"; +import * as Cloudflare from "alchemy/Cloudflare"; +import * as Drizzle from "alchemy/Drizzle"; +import * as Planetscale from "alchemy/Planetscale"; +import type { EffectPgDatabase } from "drizzle-orm/effect-postgres"; +import * as Context from "effect/Context"; +import * as Effect from "effect/Effect"; + +export interface RelayDatabase extends EffectPgDatabase { + readonly $client: PgClient; +} + +export class RelayDb extends Context.Service()("RelayDb") {} + +export const relayPostgresDatabaseRegion = { slug: "us-west" } as const; + +export const RelaySchema = Drizzle.Schema("RelaySchema", { + schema: "./src/schema.ts", + out: "./migrations/postgres", + dialect: "postgres", +}); + +export const PlanetscaleDatabase = Effect.gen(function* () { + const schema = yield* RelaySchema; + const database = yield* Planetscale.PostgresDatabase("RelayPostgresDatabase", { + region: relayPostgresDatabaseRegion, + clusterSize: "PS_5", + migrationsDir: schema.out, + migrationsTable: "relay_migrations", + replicas: 0, // BUMP BEFORE GOING TO PROD + }); + + const runtimeRole = yield* Planetscale.PostgresRole("RelayPostgresRuntimeRole", { + database, + inheritedRoles: ["pg_read_all_data", "pg_write_all_data"], + }); + + return { database, runtimeRole, schema }; +}); + +export const RelayHyperdrive = Effect.gen(function* () { + const { runtimeRole } = yield* PlanetscaleDatabase; + return yield* Cloudflare.Hyperdrive("RelayHyperdrive", { + origin: runtimeRole.origin, + caching: { + disabled: true, + }, + originConnectionLimit: 5, + }); +}); diff --git a/infra/relay/src/dpop.test.ts b/infra/relay/src/dpop.test.ts new file mode 100644 index 0000000000..81b4cc8cbf --- /dev/null +++ b/infra/relay/src/dpop.test.ts @@ -0,0 +1,203 @@ +import * as NodeCrypto from "node:crypto"; + +import { describe, expect, it } from "@effect/vitest"; +import { + computeDpopAccessTokenHash, + computeDpopJwkThumbprint, + type DpopPublicJwk, +} from "@t3tools/shared/dpop"; +import * as DateTime from "effect/DateTime"; +import * as Effect from "effect/Effect"; + +import { verifyAndConsumeDpopProof } from "./dpop.ts"; +import * as DpopProofs from "./persistence/DpopProofs.ts"; + +function makeDpopProof(input: { + readonly method: string; + readonly url: string; + readonly iat: number; + readonly jti: string; + readonly accessToken?: string; +}) { + const { privateKey, publicKey } = NodeCrypto.generateKeyPairSync("ec", { + namedCurve: "P-256", + }); + const publicJwk = publicKey.export({ format: "jwk" }) as DpopPublicJwk; + const header = Buffer.from( + JSON.stringify({ + typ: "dpop+jwt", + alg: "ES256", + jwk: publicJwk, + }), + ).toString("base64url"); + const payload = Buffer.from( + JSON.stringify({ + htm: input.method, + htu: input.url, + jti: input.jti, + iat: input.iat, + ...(input.accessToken ? { ath: computeDpopAccessTokenHash(input.accessToken) } : {}), + }), + ).toString("base64url"); + const signature = NodeCrypto.sign("sha256", Buffer.from(`${header}.${payload}`), { + key: privateKey, + dsaEncoding: "ieee-p1363", + }).toString("base64url"); + return { + proof: `${header}.${payload}.${signature}`, + thumbprint: computeDpopJwkThumbprint(publicJwk), + }; +} + +describe("verifyAndConsumeDpopProof", () => { + it.effect("rejects replayed proofs after persistence consumes the jti once", () => { + const now = DateTime.makeUnsafe("2026-05-25T12:00:00.000Z"); + const proof = makeDpopProof({ + method: "POST", + url: "https://relay.example.com/v1/environments/env/connect", + iat: Math.floor(now.epochMilliseconds / 1_000), + jti: "proof-1", + }); + const consumed = new Set(); + const dpopProofs: DpopProofs.DpopProofReplayShape = { + consume: (input) => + Effect.sync(() => { + const key = `${input.thumbprint}:${input.jti}`; + if (consumed.has(key)) { + return false; + } + consumed.add(key); + return true; + }), + pruneExpired: Effect.void, + }; + + return Effect.gen(function* () { + const first = yield* verifyAndConsumeDpopProof({ + proof: proof.proof, + method: "POST", + url: "https://relay.example.com/v1/environments/env/connect", + expectedThumbprint: proof.thumbprint, + now, + }); + const replay = yield* Effect.exit( + verifyAndConsumeDpopProof({ + proof: proof.proof, + method: "POST", + url: "https://relay.example.com/v1/environments/env/connect", + expectedThumbprint: proof.thumbprint, + now, + }), + ); + + expect(first).toBe(proof.thumbprint); + expect(replay._tag).toBe("Failure"); + }).pipe(Effect.provideService(DpopProofs.DpopProofReplay, dpopProofs)); + }); + + it.effect("rejects proofs missing the expected access token hash", () => { + const now = DateTime.makeUnsafe("2026-05-25T12:00:00.000Z"); + const proof = makeDpopProof({ + method: "POST", + url: "https://relay.example.com/v1/environments/env/connect", + iat: Math.floor(now.epochMilliseconds / 1_000), + jti: "proof-1", + }); + const dpopProofs: DpopProofs.DpopProofReplayShape = { + consume: () => Effect.succeed(true), + pruneExpired: Effect.void, + }; + + return Effect.gen(function* () { + const result = yield* Effect.exit( + verifyAndConsumeDpopProof({ + proof: proof.proof, + method: "POST", + url: "https://relay.example.com/v1/environments/env/connect", + expectedThumbprint: proof.thumbprint, + expectedAccessToken: "clerk-access-token", + now, + }), + ); + + expect(result._tag).toBe("Failure"); + }).pipe(Effect.provideService(DpopProofs.DpopProofReplay, dpopProofs)); + }); + + it.effect("preserves replay persistence failures", () => { + const now = DateTime.makeUnsafe("2026-05-25T12:00:00.000Z"); + const proof = makeDpopProof({ + method: "POST", + url: "https://relay.example.com/v1/environments/env/connect", + iat: Math.floor(now.epochMilliseconds / 1_000), + jti: "proof-persistence-failure", + }); + const failure = new DpopProofs.DpopProofReplayPersistenceError({ + cause: "database unavailable", + }); + const dpopProofs: DpopProofs.DpopProofReplayShape = { + consume: () => Effect.fail(failure), + pruneExpired: Effect.void, + }; + + return Effect.gen(function* () { + const error = yield* Effect.flip( + verifyAndConsumeDpopProof({ + proof: proof.proof, + method: "POST", + url: "https://relay.example.com/v1/environments/env/connect", + expectedThumbprint: proof.thumbprint, + now, + }), + ); + + expect(error).toBe(failure); + }).pipe(Effect.provideService(DpopProofs.DpopProofReplay, dpopProofs)); + }); + + it.effect("accepts unbound DPoP proofs when they are bound to the access token hash", () => { + const now = DateTime.makeUnsafe("2026-05-25T12:00:00.000Z"); + const proof = makeDpopProof({ + method: "POST", + url: "https://relay.example.com/v1/environments/env/status", + iat: Math.floor(now.epochMilliseconds / 1_000), + jti: "proof-status-1", + accessToken: "clerk-access-token", + }); + const consumed = new Set(); + const dpopProofs: DpopProofs.DpopProofReplayShape = { + consume: (input) => + Effect.sync(() => { + const key = `${input.thumbprint}:${input.jti}`; + if (consumed.has(key)) { + return false; + } + consumed.add(key); + return true; + }), + pruneExpired: Effect.void, + }; + + return Effect.gen(function* () { + const thumbprint = yield* verifyAndConsumeDpopProof({ + proof: proof.proof, + method: "POST", + url: "https://relay.example.com/v1/environments/env/status", + expectedAccessToken: "clerk-access-token", + now, + }); + const replay = yield* Effect.exit( + verifyAndConsumeDpopProof({ + proof: proof.proof, + method: "POST", + url: "https://relay.example.com/v1/environments/env/status", + expectedAccessToken: "clerk-access-token", + now, + }), + ); + + expect(thumbprint).toBe(proof.thumbprint); + expect(replay._tag).toBe("Failure"); + }).pipe(Effect.provideService(DpopProofs.DpopProofReplay, dpopProofs)); + }); +}); diff --git a/infra/relay/src/dpop.ts b/infra/relay/src/dpop.ts new file mode 100644 index 0000000000..e34f51740b --- /dev/null +++ b/infra/relay/src/dpop.ts @@ -0,0 +1,61 @@ +import { verifyDpopProof } from "@t3tools/shared/dpop"; +import * as DateTime from "effect/DateTime"; +import * as Effect from "effect/Effect"; +import * as HttpApiError from "effect/unstable/httpapi/HttpApiError"; + +import * as DpopProofs from "./persistence/DpopProofs.ts"; + +export const verifyAndConsumeDpopProof = Effect.fn("relay.dpop.verify_and_consume")( + function* (input: { + readonly proof: string | undefined; + readonly method: string; + readonly url: string; + readonly expectedThumbprint?: string; + readonly expectedAccessToken?: string; + readonly now: DateTime.DateTime; + }) { + const dpopProofs = yield* DpopProofs.DpopProofReplay; + yield* Effect.annotateCurrentSpan({ + "relay.dpop.method": input.method, + "relay.dpop.expected_thumbprint_present": input.expectedThumbprint !== undefined, + "relay.dpop.expected_access_token_present": input.expectedAccessToken !== undefined, + }); + const result = verifyDpopProof({ + proof: input.proof, + method: input.method, + url: input.url, + nowEpochSeconds: Math.floor(input.now.epochMilliseconds / 1_000), + ...(input.expectedThumbprint ? { expectedThumbprint: input.expectedThumbprint } : {}), + ...(input.expectedAccessToken ? { expectedAccessToken: input.expectedAccessToken } : {}), + }); + if (!result.ok) { + yield* Effect.logWarning("relay dpop proof rejected", { + reason: result.reason, + method: input.method, + url: input.url, + expectedThumbprintPresent: input.expectedThumbprint !== undefined, + expectedAccessTokenPresent: input.expectedAccessToken !== undefined, + }); + return yield* new HttpApiError.Unauthorized({}); + } + const consumed = yield* dpopProofs.consume({ + thumbprint: result.thumbprint, + jti: result.jti, + iat: result.iat, + expiresAt: DateTime.add(input.now, { minutes: 5 }), + }); + if (!consumed) { + yield* Effect.logWarning("relay dpop proof replay rejected", { + thumbprint: result.thumbprint, + jti: result.jti, + iat: result.iat, + }); + return yield* new HttpApiError.Unauthorized({}); + } + yield* Effect.annotateCurrentSpan({ + "relay.dpop.thumbprint": result.thumbprint, + "relay.dpop.iat": result.iat, + }); + return result.thumbprint; + }, +); diff --git a/infra/relay/src/infra/ManagedEndpointStackConfig.test.ts b/infra/relay/src/infra/ManagedEndpointStackConfig.test.ts new file mode 100644 index 0000000000..675b82216a --- /dev/null +++ b/infra/relay/src/infra/ManagedEndpointStackConfig.test.ts @@ -0,0 +1,27 @@ +import { describe, expect, it } from "vitest"; + +import { + MANAGED_ENDPOINT_PROVISIONER_TOKEN_POLICIES, + MANAGED_ENDPOINT_ZONE, +} from "./ManagedEndpointStackConfig.ts"; + +describe("ManagedEndpointStackConfig", () => { + it("restricts endpoint provisioning to the relay account and DNS zone", () => { + expect(MANAGED_ENDPOINT_PROVISIONER_TOKEN_POLICIES).toEqual([ + { + effect: "allow", + permissionGroups: ["Cloudflare Tunnel Read", "Cloudflare Tunnel Write"], + resources: { + [`com.cloudflare.api.account.${MANAGED_ENDPOINT_ZONE.accountId}`]: "*", + }, + }, + { + effect: "allow", + permissionGroups: ["DNS Read", "DNS Write"], + resources: { + [`com.cloudflare.api.account.zone.${MANAGED_ENDPOINT_ZONE.zoneId}`]: "*", + }, + }, + ]); + }); +}); diff --git a/infra/relay/src/infra/ManagedEndpointStackConfig.ts b/infra/relay/src/infra/ManagedEndpointStackConfig.ts new file mode 100644 index 0000000000..28fb23ced5 --- /dev/null +++ b/infra/relay/src/infra/ManagedEndpointStackConfig.ts @@ -0,0 +1,26 @@ +export const MANAGED_ENDPOINT_ZONE = { + name: "ineededadomain.com", + zoneId: "fcea40a6915723b0f5c4a9480eb3507b", + accountId: "1468bbd99811cdaccfbb707dc725421a", +} as const; + +export const RELAY_PUBLIC_DOMAIN = `t3code-relay.${MANAGED_ENDPOINT_ZONE.name}`; +export const RELAY_PUBLIC_ORIGIN = `https://${RELAY_PUBLIC_DOMAIN}`; +export const MANAGED_ENDPOINT_BASE_DOMAIN = MANAGED_ENDPOINT_ZONE.name; + +export const MANAGED_ENDPOINT_PROVISIONER_TOKEN_POLICIES = [ + { + effect: "allow" as const, + permissionGroups: ["Cloudflare Tunnel Read" as const, "Cloudflare Tunnel Write" as const], + resources: { + [`com.cloudflare.api.account.${MANAGED_ENDPOINT_ZONE.accountId}`]: "*", + }, + }, + { + effect: "allow" as const, + permissionGroups: ["DNS Read" as const, "DNS Write" as const], + resources: { + [`com.cloudflare.api.account.zone.${MANAGED_ENDPOINT_ZONE.zoneId}`]: "*", + }, + }, +]; diff --git a/infra/relay/src/infra/RelayObservability.test.ts b/infra/relay/src/infra/RelayObservability.test.ts new file mode 100644 index 0000000000..7a7b6a6809 --- /dev/null +++ b/infra/relay/src/infra/RelayObservability.test.ts @@ -0,0 +1,82 @@ +import * as Alchemy from "alchemy"; +import * as Axiom from "alchemy/Axiom"; +import * as Output from "alchemy/Output"; +import * as Effect from "effect/Effect"; +import { describe, expect, it } from "vitest"; + +import { + RELAY_AXIOM_TRACE_DATASET, + provisionRelayObservability, + relayAxiomIngestDatasetCapabilities, + relayAxiomQueryDatasetCapabilities, + relayRecentSpansQuery, + relayTraceQuery, +} from "./RelayObservability.ts"; + +describe("RelayObservability", () => { + it("scopes the ingest token only to HTTP span ingestion", () => { + expect(relayAxiomIngestDatasetCapabilities()).toEqual({ + [RELAY_AXIOM_TRACE_DATASET]: { ingest: ["create"] }, + }); + }); + + it("scopes the diagnostics query token only to HTTP spans", () => { + expect(relayAxiomQueryDatasetCapabilities()).toEqual({ + [RELAY_AXIOM_TRACE_DATASET]: { query: ["read"] }, + }); + }); + + it("builds APL queries for the trace dataset", () => { + expect(relayTraceQuery("| where name == 'GET /health'", "relay-traces-test")).toBe( + "['relay-traces-test']\n| where name == 'GET /health'", + ); + }); + + it("projects Effect HTTP span attributes through their OTLP field names", () => { + const query = relayRecentSpansQuery("relay-traces-test"); + + expect(query).toContain("['relay-traces-test']"); + expect(query).toContain("attributes.http.request.method"); + expect(query).toContain("attributes.http.response.status_code"); + expect(query).toContain("attributes.url.path"); + expect(query).toContain("attributes.http.route"); + expect(query).toContain("customAttributes = column_ifexists('attributes.custom', dynamic({}))"); + expect(query).toContain("customAttributes['user.id']"); + expect(query).not.toContain("['http.request.method']"); + }); + + it("orders token and view resources behind the trace dataset", async () => { + const stack = { + name: "RelayObservabilityTest", + stage: "test", + resources: {}, + bindings: {}, + actions: {}, + }; + + await Effect.runPromise( + provisionRelayObservability.pipe( + Effect.provideService(Alchemy.Stack, stack), + Effect.provideService(Axiom.Providers, { + kind: "ProviderCollection", + get: () => undefined, + }), + ), + ); + + const resources = stack.resources as Record; + const traces = resources.RelayTracesDataset; + + expect(traces).toBeDefined(); + for (const logicalId of [ + "RelayAxiomIngestToken", + "RelayAxiomQueryToken", + "RelayRecentSpansView", + ]) { + expect(resources[logicalId]).toBeDefined(); + expect(Object.keys(Output.resolveUpstream(resources[logicalId]!.Props))).toContain( + traces!.FQN, + ); + } + }); +}); diff --git a/infra/relay/src/infra/RelayObservability.ts b/infra/relay/src/infra/RelayObservability.ts new file mode 100644 index 0000000000..7cf943ee07 --- /dev/null +++ b/infra/relay/src/infra/RelayObservability.ts @@ -0,0 +1,58 @@ +import * as Axiom from "alchemy/Axiom"; +import * as Output from "alchemy/Output"; +import * as Effect from "effect/Effect"; + +export const RELAY_OBSERVABILITY_SERVICE_NAME = "t3-code-relay-worker"; +export const RELAY_OBSERVABILITY_EXPORT_INTERVAL = "1 second"; +export const RELAY_AXIOM_TRACE_DATASET = "t3-code-relay-traces"; + +export const relayTraceQuery = (query: string, dataset: string = RELAY_AXIOM_TRACE_DATASET) => + `['${dataset}']\n${query}`; + +export const relayRecentSpansQuery = (dataset: string = RELAY_AXIOM_TRACE_DATASET) => + relayTraceQuery( + "| where isnotnull(span_id) or isnotnull(trace_id)\n| extend requestMethod = column_ifexists('attributes.http.request.method', ''), path = column_ifexists('attributes.url.path', ''), endpoint = column_ifexists('attributes.http.route', ''), statusCode = column_ifexists('attributes.http.response.status_code', 0), customAttributes = column_ifexists('attributes.custom', dynamic({}))\n| extend userId = customAttributes['user.id']\n| project _time, name, trace_id, span_id, duration, requestMethod, path, statusCode, endpoint, userId\n| order by _time desc\n| limit 200", + dataset, + ); + +export const relayAxiomIngestDatasetCapabilities = ( + dataset: string = RELAY_AXIOM_TRACE_DATASET, +) => ({ + [dataset]: { ingest: ["create" as const] }, +}); + +export const relayAxiomQueryDatasetCapabilities = ( + dataset: string = RELAY_AXIOM_TRACE_DATASET, +) => ({ + [dataset]: { query: ["read" as const] }, +}); + +export const provisionRelayObservability = Effect.gen(function* () { + const traces = yield* Axiom.Dataset("RelayTracesDataset", { + name: RELAY_AXIOM_TRACE_DATASET, + kind: "otel:traces:v1", + description: "T3 Code relay Worker HTTP request spans.", + retentionDays: 30, + useRetentionPeriod: true, + }); + + const ingestToken = yield* Axiom.ApiToken("RelayAxiomIngestToken", { + name: "t3-code-relay-otel-ingest", + description: "Owned by Alchemy. Scoped OTLP ingest token for relay HTTP spans.", + datasetCapabilities: Output.map(traces.name, relayAxiomIngestDatasetCapabilities), + }); + const queryToken = yield* Axiom.ApiToken("RelayAxiomQueryToken", { + name: "t3-code-relay-readonly-query", + description: "Owned by Alchemy. Read-only query token for relay HTTP span diagnostics.", + datasetCapabilities: Output.map(traces.name, relayAxiomQueryDatasetCapabilities), + }); + + yield* Axiom.View("RelayRecentSpansView", { + name: "t3-code-relay-recent-spans", + description: "Recent relay HTTP request spans.", + datasets: [traces.name], + aplQuery: Output.map(traces.name, relayRecentSpansQuery), + }); + + return { traces, ingestToken, queryToken } as const; +}); diff --git a/infra/relay/src/persistence/AgentActivityRows.ts b/infra/relay/src/persistence/AgentActivityRows.ts new file mode 100644 index 0000000000..1f59c21e8b --- /dev/null +++ b/infra/relay/src/persistence/AgentActivityRows.ts @@ -0,0 +1,155 @@ +import type { RelayAgentActivityState } from "@t3tools/contracts/relay"; +import { RelayAgentActivityState as RelayAgentActivityStateSchema } from "@t3tools/contracts/relay"; +import * as Context from "effect/Context"; +import * as Data from "effect/Data"; +import * as DateTime from "effect/DateTime"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import * as Option from "effect/Option"; +import * as Schema from "effect/Schema"; +import { and, desc, eq, isNull } from "drizzle-orm"; + +import { RelayDb } from "../db.ts"; +import { relayAgentActivityRows, relayEnvironmentLinks } from "../schema.ts"; +import { parseJsonString, stringifyJsonValue } from "./json.ts"; + +export class AgentActivityRowUpsertPersistenceError extends Data.TaggedError( + "AgentActivityRowUpsertPersistenceError", +)<{ + readonly cause: unknown; +}> {} + +export class AgentActivityRowDeletePersistenceError extends Data.TaggedError( + "AgentActivityRowDeletePersistenceError", +)<{ + readonly cause: unknown; +}> {} + +export class AgentActivityRowListPersistenceError extends Data.TaggedError( + "AgentActivityRowListPersistenceError", +)<{ + readonly cause: unknown; +}> {} + +export interface AgentActivityRowsShape { + readonly upsert: (input: { + readonly environmentPublicKey: string; + readonly state: RelayAgentActivityState; + }) => Effect.Effect; + readonly remove: (input: { + readonly environmentId: string; + readonly environmentPublicKey: string; + readonly threadId: string; + }) => Effect.Effect; + readonly listForUser: (input: { + readonly userId: string; + }) => Effect.Effect, AgentActivityRowListPersistenceError>; +} + +export class AgentActivityRows extends Context.Service()( + "AgentActivityRows", +) {} + +const encodeRelayAgentActivityStateJson = Schema.encodeEffect( + Schema.fromJsonString(RelayAgentActivityStateSchema), +); + +const decodeRelayAgentActivityStateJson = Schema.decodeUnknownOption( + Schema.fromJsonString(RelayAgentActivityStateSchema), +); + +const make = Effect.gen(function* () { + const db = yield* RelayDb; + + return AgentActivityRows.of({ + upsert: Effect.fn("relay.agent_activity_rows.upsert")( + function* (input) { + yield* Effect.annotateCurrentSpan({ + "relay.environment_id": input.state.environmentId, + "relay.thread_id": input.state.threadId, + }); + const now = yield* DateTime.now; + const stateJson = yield* parseJsonString( + yield* encodeRelayAgentActivityStateJson(input.state), + ); + yield* db + .insert(relayAgentActivityRows) + .values({ + environmentId: input.state.environmentId, + environmentPublicKey: input.environmentPublicKey, + threadId: input.state.threadId, + stateJson, + updatedAt: input.state.updatedAt, + createdAt: DateTime.formatIso(now), + }) + .onConflictDoUpdate({ + target: [ + relayAgentActivityRows.environmentId, + relayAgentActivityRows.environmentPublicKey, + relayAgentActivityRows.threadId, + ], + set: { + stateJson, + updatedAt: input.state.updatedAt, + }, + }); + }, + Effect.mapError((cause) => new AgentActivityRowUpsertPersistenceError({ cause })), + ), + + remove: Effect.fn("relay.agent_activity_rows.remove")(function* (input) { + yield* Effect.annotateCurrentSpan({ + "relay.environment_id": input.environmentId, + "relay.thread_id": input.threadId, + }); + yield* db + .delete(relayAgentActivityRows) + .where( + and( + eq(relayAgentActivityRows.environmentId, input.environmentId), + eq(relayAgentActivityRows.environmentPublicKey, input.environmentPublicKey), + eq(relayAgentActivityRows.threadId, input.threadId), + ), + ) + .pipe(Effect.mapError((cause) => new AgentActivityRowDeletePersistenceError({ cause }))); + }), + + listForUser: Effect.fn("relay.agent_activity_rows.list_for_user")(function* (input) { + yield* Effect.annotateCurrentSpan({ "user.id": input.userId }); + return yield* db + .select({ stateJson: relayAgentActivityRows.stateJson }) + .from(relayAgentActivityRows) + .innerJoin( + relayEnvironmentLinks, + and( + eq(relayEnvironmentLinks.environmentId, relayAgentActivityRows.environmentId), + eq( + relayEnvironmentLinks.environmentPublicKey, + relayAgentActivityRows.environmentPublicKey, + ), + ), + ) + .where( + and( + eq(relayEnvironmentLinks.userId, input.userId), + isNull(relayEnvironmentLinks.revokedAt), + eq(relayEnvironmentLinks.liveActivitiesEnabled, true), + ), + ) + .orderBy(desc(relayAgentActivityRows.updatedAt)) + .pipe( + Effect.flatMap((rows) => + Effect.forEach(rows, (row) => stringifyJsonValue(row.stateJson), { + concurrency: "unbounded", + }), + ), + Effect.map((rows) => + rows.flatMap((row) => Option.toArray(decodeRelayAgentActivityStateJson(row))), + ), + Effect.mapError((cause) => new AgentActivityRowListPersistenceError({ cause })), + ); + }), + }); +}); + +export const layer = Layer.effect(AgentActivityRows, make); diff --git a/infra/relay/src/persistence/DeliveryAttempts.test.ts b/infra/relay/src/persistence/DeliveryAttempts.test.ts new file mode 100644 index 0000000000..baeb974cf8 --- /dev/null +++ b/infra/relay/src/persistence/DeliveryAttempts.test.ts @@ -0,0 +1,323 @@ +import * as NodeCryptoLayer from "@effect/platform-node/NodeCrypto"; +import { describe, expect, it } from "@effect/vitest"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; + +import { RelayDb, type RelayDatabase } from "../db.ts"; +import { relayDeliveryAttempts } from "../schema.ts"; +import * as DeliveryAttempts from "./DeliveryAttempts.ts"; + +describe("DeliveryAttempts", () => { + it.effect("records the signed queue source job id for APNs delivery auditability", () => { + const insertedValues: Array> = []; + const fakeDb = { + insert: (table: unknown) => { + expect(table).toBe(relayDeliveryAttempts); + return { + values: (values: Record) => { + insertedValues.push(values); + return Effect.void; + }, + }; + }, + } as unknown as RelayDatabase; + + return Effect.gen(function* () { + const attempts = yield* DeliveryAttempts.DeliveryAttempts; + yield* attempts.record({ + userId: "user-1", + environmentId: "env-1", + threadId: "thread-1", + deviceId: "device-1", + kind: "live_activity_update", + sourceJobId: "job-1", + token: "apns-token", + apnsStatus: 200, + apnsId: "apns-id", + }); + + expect(insertedValues).toHaveLength(1); + expect(insertedValues[0]).toMatchObject({ + userId: "user-1", + environmentId: "env-1", + threadId: "thread-1", + deviceId: "device-1", + kind: "live_activity_update", + sourceJobId: "job-1", + tokenSuffix: "ns-token", + apnsStatus: 200, + apnsId: "apns-id", + }); + }).pipe( + Effect.provide( + DeliveryAttempts.layer.pipe( + Layer.provide(NodeCryptoLayer.layer), + Layer.provide(Layer.succeed(RelayDb, fakeDb)), + ), + ), + ); + }); + + it.effect("claims signed queue source jobs before APNs delivery", () => { + const insertedValues: Array> = []; + const conflictTargets: Array = []; + const fakeDb = { + insert: (table: unknown) => { + expect(table).toBe(relayDeliveryAttempts); + return { + values: (values: Record) => { + insertedValues.push(values); + return { + onConflictDoNothing: (config: { readonly target: unknown }) => { + conflictTargets.push(config.target); + return { + returning: () => Effect.succeed([{ id: values.id }]), + }; + }, + }; + }, + }; + }, + } as unknown as RelayDatabase; + + return Effect.gen(function* () { + const attempts = yield* DeliveryAttempts.DeliveryAttempts; + const claimed = yield* attempts.claimSourceJob({ + userId: "user-1", + environmentId: "env-1", + threadId: "thread-1", + deviceId: "device-1", + kind: "push_notification", + sourceJobId: "job-1", + token: "apns-token", + }); + + expect(claimed).toBe("claimed"); + expect(conflictTargets).toEqual([relayDeliveryAttempts.sourceJobId]); + expect(insertedValues[0]).toMatchObject({ + kind: "push_notification", + sourceJobId: "job-1", + tokenSuffix: "ns-token", + apnsStatus: null, + }); + }).pipe( + Effect.provide( + DeliveryAttempts.layer.pipe( + Layer.provide(NodeCryptoLayer.layer), + Layer.provide(Layer.succeed(RelayDb, fakeDb)), + ), + ), + ); + }); + + it.effect("reports completed source jobs when the durable claim already exists", () => { + const fakeDb = { + insert: () => ({ + values: () => ({ + onConflictDoNothing: () => ({ + returning: () => Effect.succeed([]), + }), + }), + }), + select: () => ({ + from: () => ({ + where: () => ({ + limit: () => + Effect.succeed([ + { + createdAt: "2026-05-26T00:00:00.000Z", + apnsStatus: 200, + apnsReason: null, + apnsId: null, + transportError: null, + }, + ]), + }), + }), + }), + } as unknown as RelayDatabase; + + return Effect.gen(function* () { + const attempts = yield* DeliveryAttempts.DeliveryAttempts; + const claimed = yield* attempts.claimSourceJob({ + userId: "user-1", + environmentId: null, + threadId: null, + deviceId: "device-1", + kind: "live_activity_update", + sourceJobId: "job-1", + token: "apns-token", + }); + + expect(claimed).toBe("completed"); + }).pipe( + Effect.provide( + DeliveryAttempts.layer.pipe( + Layer.provide(NodeCryptoLayer.layer), + Layer.provide(Layer.succeed(RelayDb, fakeDb)), + ), + ), + ); + }); + + it.effect("reports in-flight source jobs while an active claim lease exists", () => { + const fakeDb = { + insert: () => ({ + values: () => ({ + onConflictDoNothing: () => ({ + returning: () => Effect.succeed([]), + }), + }), + }), + select: () => ({ + from: () => ({ + where: () => ({ + limit: () => + Effect.succeed([ + { + createdAt: "2999-01-01T00:00:00.000Z", + apnsStatus: null, + apnsReason: null, + apnsId: null, + transportError: null, + }, + ]), + }), + }), + }), + } as unknown as RelayDatabase; + + return Effect.gen(function* () { + const attempts = yield* DeliveryAttempts.DeliveryAttempts; + const claimed = yield* attempts.claimSourceJob({ + userId: "user-1", + environmentId: null, + threadId: null, + deviceId: "device-1", + kind: "live_activity_update", + sourceJobId: "job-1", + token: "apns-token", + }); + + expect(claimed).toBe("in_flight"); + }).pipe( + Effect.provide( + DeliveryAttempts.layer.pipe( + Layer.provide(NodeCryptoLayer.layer), + Layer.provide(Layer.succeed(RelayDb, fakeDb)), + ), + ), + ); + }); + + it.effect("reclaims source jobs after the claim lease expires", () => { + const updatedValues: Array> = []; + const fakeDb = { + insert: () => ({ + values: () => ({ + onConflictDoNothing: () => ({ + returning: () => Effect.succeed([]), + }), + }), + }), + select: () => ({ + from: () => ({ + where: () => ({ + limit: () => + Effect.succeed([ + { + createdAt: "1969-12-31T23:00:00.000Z", + apnsStatus: null, + apnsReason: null, + apnsId: null, + transportError: null, + }, + ]), + }), + }), + }), + update: () => ({ + set: (values: Record) => { + updatedValues.push(values); + return { + where: () => ({ + returning: () => Effect.succeed([{ id: "attempt-1" }]), + }), + }; + }, + }), + } as unknown as RelayDatabase; + + return Effect.gen(function* () { + const attempts = yield* DeliveryAttempts.DeliveryAttempts; + const claimed = yield* attempts.claimSourceJob({ + userId: "user-1", + environmentId: null, + threadId: null, + deviceId: "device-1", + kind: "live_activity_update", + sourceJobId: "job-1", + token: "apns-token", + }); + + expect(claimed).toBe("claimed"); + expect(updatedValues[0]?.createdAt).toEqual(expect.any(String)); + }).pipe( + Effect.provide( + DeliveryAttempts.layer.pipe( + Layer.provide(NodeCryptoLayer.layer), + Layer.provide(Layer.succeed(RelayDb, fakeDb)), + ), + ), + ); + }); + + it.effect("completes a claimed source job with the APNs outcome", () => { + const updatedValues: Array> = []; + const whereClauses: Array = []; + const fakeDb = { + update: (table: unknown) => { + expect(table).toBe(relayDeliveryAttempts); + return { + set: (values: Record) => { + updatedValues.push(values); + return { + where: (clause: unknown) => { + whereClauses.push(clause); + return Effect.void; + }, + }; + }, + }; + }, + } as unknown as RelayDatabase; + + return Effect.gen(function* () { + const attempts = yield* DeliveryAttempts.DeliveryAttempts; + yield* attempts.completeSourceJob({ + sourceJobId: "job-1", + apnsStatus: 410, + apnsReason: "Unregistered", + apnsId: "apns-id", + }); + + expect(whereClauses).toHaveLength(1); + expect(updatedValues).toEqual([ + { + createdAt: expect.any(String), + apnsStatus: 410, + apnsReason: "Unregistered", + apnsId: "apns-id", + transportError: null, + }, + ]); + }).pipe( + Effect.provide( + DeliveryAttempts.layer.pipe( + Layer.provide(NodeCryptoLayer.layer), + Layer.provide(Layer.succeed(RelayDb, fakeDb)), + ), + ), + ); + }); +}); diff --git a/infra/relay/src/persistence/DeliveryAttempts.ts b/infra/relay/src/persistence/DeliveryAttempts.ts new file mode 100644 index 0000000000..4ab4e3d21f --- /dev/null +++ b/infra/relay/src/persistence/DeliveryAttempts.ts @@ -0,0 +1,205 @@ +import * as Context from "effect/Context"; +import * as Data from "effect/Data"; +import * as DateTime from "effect/DateTime"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import * as Option from "effect/Option"; +import { and, eq, isNull } from "drizzle-orm"; +import * as Crypto from "effect/Crypto"; + +import { RelayDb } from "../db.ts"; +import { relayDeliveryAttempts } from "../schema.ts"; + +export class DeliveryAttemptRecordPersistenceError extends Data.TaggedError( + "DeliveryAttemptRecordPersistenceError", +)<{ + readonly cause: unknown; +}> {} + +export interface DeliveryAttemptInput { + readonly userId: string | null; + readonly environmentId: string | null; + readonly threadId: string | null; + readonly deviceId: string | null; + readonly kind: string; + readonly sourceJobId?: string | null; + readonly token: string | null; + readonly apnsStatus?: number; + readonly apnsReason?: string; + readonly apnsId?: string | null; + readonly transportError?: string; +} + +export interface DeliveryAttemptCompletionInput { + readonly sourceJobId: string; + readonly apnsStatus?: number; + readonly apnsReason?: string; + readonly apnsId?: string | null; + readonly transportError?: string; +} + +export type DeliverySourceJobClaimResult = "claimed" | "completed" | "in_flight"; + +export interface DeliveryAttemptsShape { + readonly record: ( + input: DeliveryAttemptInput, + ) => Effect.Effect; + readonly claimSourceJob: ( + input: DeliveryAttemptInput & { readonly sourceJobId: string }, + ) => Effect.Effect; + readonly completeSourceJob: ( + input: DeliveryAttemptCompletionInput, + ) => Effect.Effect; +} + +export class DeliveryAttempts extends Context.Service()( + "DeliveryAttempts", +) {} + +const SOURCE_JOB_CLAIM_LEASE_MINUTES = 10; + +function insertValues( + input: DeliveryAttemptInput, + id: string, + createdAt: string, +): typeof relayDeliveryAttempts.$inferInsert { + return { + id, + createdAt, + userId: input.userId, + environmentId: input.environmentId, + threadId: input.threadId, + deviceId: input.deviceId, + kind: input.kind, + sourceJobId: input.sourceJobId ?? null, + tokenSuffix: input.token?.slice(-8) ?? null, + apnsStatus: input.apnsStatus ?? null, + apnsReason: input.apnsReason ?? null, + apnsId: input.apnsId ?? null, + transportError: input.transportError ?? null, + }; +} + +const make = Effect.gen(function* () { + const db = yield* RelayDb; + const crypto = yield* Crypto.Crypto; + + const isExpiredClaim = (claimedAt: string | null, now: DateTime.DateTime) => { + if (claimedAt === null) { + return true; + } + return Option.match(DateTime.make(claimedAt), { + onNone: () => true, + onSome: (dateTime) => + now.epochMilliseconds - dateTime.epochMilliseconds >= + SOURCE_JOB_CLAIM_LEASE_MINUTES * 60 * 1_000, + }); + }; + + return DeliveryAttempts.of({ + record: Effect.fn("relay.delivery_attempts.record")( + function* (input) { + yield* Effect.annotateCurrentSpan({ + "relay.delivery.kind": input.kind, + ...(input.sourceJobId ? { "relay.delivery.job_id": input.sourceJobId } : {}), + ...(input.deviceId ? { "relay.mobile.device_id": input.deviceId } : {}), + ...(input.environmentId ? { "relay.environment_id": input.environmentId } : {}), + ...(input.threadId ? { "relay.thread_id": input.threadId } : {}), + ...(input.userId ? { "user.id": input.userId } : {}), + }); + const id = yield* crypto.randomUUIDv4; + const createdAt = DateTime.formatIso(yield* DateTime.now); + yield* db.insert(relayDeliveryAttempts).values(insertValues(input, id, createdAt)); + }, + Effect.mapError((cause) => new DeliveryAttemptRecordPersistenceError({ cause })), + ), + claimSourceJob: Effect.fn("relay.delivery_attempts.claim_source_job")( + function* (input) { + yield* Effect.annotateCurrentSpan({ + "relay.delivery.kind": input.kind, + "relay.delivery.job_id": input.sourceJobId, + ...(input.deviceId ? { "relay.mobile.device_id": input.deviceId } : {}), + ...(input.environmentId ? { "relay.environment_id": input.environmentId } : {}), + ...(input.threadId ? { "relay.thread_id": input.threadId } : {}), + ...(input.userId ? { "user.id": input.userId } : {}), + }); + const id = yield* crypto.randomUUIDv4; + const now = yield* DateTime.now; + const createdAt = DateTime.formatIso(now); + const inserted = yield* db + .insert(relayDeliveryAttempts) + .values(insertValues(input, id, createdAt)) + .onConflictDoNothing({ target: relayDeliveryAttempts.sourceJobId }) + .returning({ id: relayDeliveryAttempts.id }); + if (inserted.length > 0) { + return "claimed"; + } + + const existing = yield* db + .select({ + createdAt: relayDeliveryAttempts.createdAt, + apnsStatus: relayDeliveryAttempts.apnsStatus, + apnsReason: relayDeliveryAttempts.apnsReason, + apnsId: relayDeliveryAttempts.apnsId, + transportError: relayDeliveryAttempts.transportError, + }) + .from(relayDeliveryAttempts) + .where(eq(relayDeliveryAttempts.sourceJobId, input.sourceJobId)) + .limit(1); + const row = existing[0]; + if (!row) { + return "in_flight"; + } + if ( + row.apnsStatus !== null || + row.apnsReason !== null || + row.apnsId !== null || + row.transportError !== null + ) { + return "completed"; + } + if (!isExpiredClaim(row.createdAt, now)) { + return "in_flight"; + } + + const reclaimed = yield* db + .update(relayDeliveryAttempts) + .set({ + createdAt, + }) + .where( + and( + eq(relayDeliveryAttempts.sourceJobId, input.sourceJobId), + eq(relayDeliveryAttempts.createdAt, row.createdAt), + isNull(relayDeliveryAttempts.apnsStatus), + isNull(relayDeliveryAttempts.apnsReason), + isNull(relayDeliveryAttempts.apnsId), + isNull(relayDeliveryAttempts.transportError), + ), + ) + .returning({ id: relayDeliveryAttempts.id }); + return reclaimed.length > 0 ? "claimed" : "in_flight"; + }, + Effect.mapError((cause) => new DeliveryAttemptRecordPersistenceError({ cause })), + ), + completeSourceJob: Effect.fn("relay.delivery_attempts.complete_source_job")( + function* (input) { + yield* Effect.annotateCurrentSpan({ "relay.delivery.job_id": input.sourceJobId }); + const completedAt = DateTime.formatIso(yield* DateTime.now); + yield* db + .update(relayDeliveryAttempts) + .set({ + createdAt: completedAt, + apnsStatus: input.apnsStatus ?? null, + apnsReason: input.apnsReason ?? null, + apnsId: input.apnsId ?? null, + transportError: input.transportError ?? null, + }) + .where(eq(relayDeliveryAttempts.sourceJobId, input.sourceJobId)); + }, + Effect.mapError((cause) => new DeliveryAttemptRecordPersistenceError({ cause })), + ), + }); +}); + +export const layer = Layer.effect(DeliveryAttempts, make); diff --git a/infra/relay/src/persistence/Devices.test.ts b/infra/relay/src/persistence/Devices.test.ts new file mode 100644 index 0000000000..55aed59730 --- /dev/null +++ b/infra/relay/src/persistence/Devices.test.ts @@ -0,0 +1,160 @@ +import type { RelayDeviceRegistrationRequest } from "@t3tools/contracts/relay"; +import { describe, expect, it } from "@effect/vitest"; +import type { SQL } from "drizzle-orm"; +import { PgDialect } from "drizzle-orm/pg-core"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; + +import { RelayDb, type RelayDatabase } from "../db.ts"; +import { relayLiveActivities, relayMobileDevices } from "../schema.ts"; +import * as Devices from "./Devices.ts"; + +const registration: RelayDeviceRegistrationRequest = { + deviceId: "device-1" as RelayDeviceRegistrationRequest["deviceId"], + platform: "ios", + iosMajorVersion: 18, + appVersion: "1.0.0" as RelayDeviceRegistrationRequest["appVersion"], + pushToken: "apns-device-token" as RelayDeviceRegistrationRequest["pushToken"], + pushToStartToken: "push-to-start-token" as RelayDeviceRegistrationRequest["pushToStartToken"], + preferences: { + notificationsEnabled: true, + liveActivitiesEnabled: true, + notifyOnApproval: true, + notifyOnInput: true, + notifyOnCompletion: true, + notifyOnFailure: true, + }, +}; + +describe("Devices", () => { + it.effect("claims APNs tokens globally before upserting the current user device", () => { + const calls: Array = []; + const updateSets: Array> = []; + const updateConditions: Array = []; + const insertedValues: Array> = []; + const dialect = new PgDialect(); + + const fakeDb = { + update: (table: unknown) => { + expect(table).toBe(relayMobileDevices); + calls.push("update"); + return { + set: (values: Record) => { + updateSets.push(values); + calls.push("update.set"); + return { + where: (condition: SQL) => { + expect(condition).toBeDefined(); + updateConditions.push(condition); + calls.push("update.where"); + return Effect.void; + }, + }; + }, + }; + }, + insert: (table: unknown) => { + expect(table).toBe(relayMobileDevices); + calls.push("insert"); + return { + values: (values: Record) => { + insertedValues.push(values); + calls.push("insert.values"); + return { + onConflictDoUpdate: (config: unknown) => { + expect(config).toBeDefined(); + calls.push("insert.onConflictDoUpdate"); + return Effect.void; + }, + }; + }, + }; + }, + } as unknown as RelayDatabase; + + return Effect.gen(function* () { + const devices = yield* Devices.Devices; + yield* devices.register({ userId: "user-2", registration }); + + expect(calls).toEqual([ + "update", + "update.set", + "update.where", + "update", + "update.set", + "update.where", + "insert", + "insert.values", + "insert.onConflictDoUpdate", + ]); + expect(updateSets).toEqual([ + expect.objectContaining({ pushToken: null }), + expect.objectContaining({ pushToStartToken: null }), + ]); + expect(updateConditions.map((condition) => dialect.sqlToQuery(condition))).toEqual([ + { + sql: '"relay_mobile_devices"."push_token" = $1', + params: ["apns-device-token"], + }, + { + sql: '"relay_mobile_devices"."push_to_start_token" = $1', + params: ["push-to-start-token"], + }, + ]); + expect(insertedValues).toEqual([ + expect.objectContaining({ + userId: "user-2", + deviceId: "device-1", + pushToken: "apns-device-token", + pushToStartToken: "push-to-start-token", + }), + ]); + }).pipe(Effect.provide(Devices.layer.pipe(Layer.provide(Layer.succeed(RelayDb, fakeDb))))); + }); + + it.effect("unregisters APNs state only for the current user device", () => { + const calls: Array = []; + const deleteConditions: Array = []; + const dialect = new PgDialect(); + + const fakeDb = { + delete: (table: unknown) => { + calls.push(table === relayLiveActivities ? "delete.liveActivities" : "delete.devices"); + return { + where: (condition: SQL) => { + expect(condition).toBeDefined(); + deleteConditions.push(condition); + calls.push("delete.where"); + return Effect.void; + }, + }; + }, + } as unknown as RelayDatabase; + + return Effect.gen(function* () { + const devices = yield* Devices.Devices; + yield* devices.unregister({ userId: "user-2", deviceId: "device-1" }); + + expect(calls).toEqual([ + "delete.liveActivities", + "delete.where", + "delete.devices", + "delete.where", + ]); + expect(deleteConditions.map((condition) => dialect.sqlToQuery(condition))).toEqual([ + { + sql: + '(("relay_live_activities"."user_id" = $1) and ' + + '("relay_live_activities"."device_id" = $2))', + params: ["user-2", "device-1"], + }, + { + sql: + '(("relay_mobile_devices"."user_id" = $1) and ' + + '("relay_mobile_devices"."device_id" = $2))', + params: ["user-2", "device-1"], + }, + ]); + }).pipe(Effect.provide(Devices.layer.pipe(Layer.provide(Layer.succeed(RelayDb, fakeDb))))); + }); +}); diff --git a/infra/relay/src/persistence/Devices.ts b/infra/relay/src/persistence/Devices.ts new file mode 100644 index 0000000000..a012fa60df --- /dev/null +++ b/infra/relay/src/persistence/Devices.ts @@ -0,0 +1,134 @@ +import type { RelayDeviceRegistrationRequest } from "@t3tools/contracts/relay"; +import * as Context from "effect/Context"; +import * as Data from "effect/Data"; +import * as DateTime from "effect/DateTime"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import { and, eq } from "drizzle-orm"; +import { sql } from "drizzle-orm"; + +import { RelayDb } from "../db.ts"; +import { relayLiveActivities, relayMobileDevices } from "../schema.ts"; + +export class DeviceRegistrationPersistenceError extends Data.TaggedError( + "DeviceRegistrationPersistenceError", +)<{ + readonly cause: unknown; +}> {} + +export class DeviceUnregistrationPersistenceError extends Data.TaggedError( + "DeviceUnregistrationPersistenceError", +)<{ + readonly cause: unknown; +}> {} + +export interface DevicesShape { + readonly register: (input: { + readonly userId: string; + readonly registration: RelayDeviceRegistrationRequest; + }) => Effect.Effect; + readonly unregister: (input: { + readonly userId: string; + readonly deviceId: string; + }) => Effect.Effect; +} + +export class Devices extends Context.Service()("Devices") {} + +const make = Effect.gen(function* () { + const db = yield* RelayDb; + + return Devices.of({ + register: Effect.fn("relay.devices.register")( + function* (input) { + yield* Effect.annotateCurrentSpan({ + "user.id": input.userId, + "relay.mobile.device_id": input.registration.deviceId, + }); + const updatedAt = DateTime.formatIso(yield* DateTime.now); + const registration = input.registration; + + yield* Effect.all( + [ + registration.pushToken + ? db + .update(relayMobileDevices) + .set({ pushToken: null, updatedAt }) + .where(eq(relayMobileDevices.pushToken, registration.pushToken)) + : Effect.void, + registration.pushToStartToken + ? db + .update(relayMobileDevices) + .set({ pushToStartToken: null, updatedAt }) + .where(eq(relayMobileDevices.pushToStartToken, registration.pushToStartToken)) + : Effect.void, + ], + { concurrency: 2, discard: true }, + ); + + yield* db + .insert(relayMobileDevices) + .values({ + userId: input.userId, + deviceId: registration.deviceId, + platform: registration.platform, + iosMajorVersion: registration.iosMajorVersion, + appVersion: registration.appVersion ?? null, + pushToken: registration.pushToken ?? null, + pushToStartToken: registration.pushToStartToken ?? null, + preferencesJson: registration.preferences, + createdAt: updatedAt, + updatedAt, + }) + .onConflictDoUpdate({ + target: [relayMobileDevices.userId, relayMobileDevices.deviceId], + set: { + platform: registration.platform, + iosMajorVersion: registration.iosMajorVersion, + appVersion: registration.appVersion ?? null, + pushToken: sql`coalesce(excluded.push_token, ${relayMobileDevices.pushToken})`, + pushToStartToken: sql`coalesce( + excluded.push_to_start_token, + ${relayMobileDevices.pushToStartToken} + )`, + preferencesJson: registration.preferences, + updatedAt, + }, + }); + }, + Effect.mapError((cause) => new DeviceRegistrationPersistenceError({ cause })), + ), + unregister: Effect.fn("relay.devices.unregister")( + function* (input) { + yield* Effect.annotateCurrentSpan({ + "user.id": input.userId, + "relay.mobile.device_id": input.deviceId, + }); + yield* Effect.all( + [ + db + .delete(relayLiveActivities) + .where( + and( + eq(relayLiveActivities.userId, input.userId), + eq(relayLiveActivities.deviceId, input.deviceId), + ), + ), + db + .delete(relayMobileDevices) + .where( + and( + eq(relayMobileDevices.userId, input.userId), + eq(relayMobileDevices.deviceId, input.deviceId), + ), + ), + ], + { concurrency: 2, discard: true }, + ); + }, + Effect.mapError((cause) => new DeviceUnregistrationPersistenceError({ cause })), + ), + }); +}); + +export const layer = Layer.effect(Devices, make); diff --git a/infra/relay/src/persistence/DpopProofs.test.ts b/infra/relay/src/persistence/DpopProofs.test.ts new file mode 100644 index 0000000000..33aa67b3fe --- /dev/null +++ b/infra/relay/src/persistence/DpopProofs.test.ts @@ -0,0 +1,95 @@ +import { describe, expect, it } from "@effect/vitest"; +import * as DateTime from "effect/DateTime"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import * as Option from "effect/Option"; + +import { RelayDb, type RelayDatabase } from "../db.ts"; +import { relayDpopProofs } from "../schema.ts"; +import * as DpopProofs from "./DpopProofs.ts"; + +describe("DpopProofReplay", () => { + it.effect("consumes proof ids without pruning expired rows on the request path", () => { + const calls: Array = []; + const insertedValues: Array<{ + readonly thumbprint: string; + readonly jti: string; + readonly iat: number; + readonly expiresAt: string; + readonly createdAt: string; + }> = []; + const fakeDb = { + insert: (table: unknown) => { + expect(table).toBe(relayDpopProofs); + calls.push("insert"); + return { + values: (values: (typeof insertedValues)[number]) => { + insertedValues.push(values); + calls.push("insert.values"); + return { + onConflictDoNothing: () => { + calls.push("insert.onConflictDoNothing"); + return { + returning: (selection: unknown) => { + expect(selection).toBeDefined(); + calls.push("insert.returning"); + return Effect.succeed([{ jti: values.jti }]); + }, + }; + }, + }; + }, + }; + }, + } as unknown as RelayDatabase; + + return Effect.gen(function* () { + const replay = yield* DpopProofs.DpopProofReplay; + const consumed = yield* replay.consume({ + thumbprint: "thumbprint", + jti: "jti", + iat: 1_771_000_000, + expiresAt: Option.getOrThrow(DateTime.make("2026-05-25T12:00:00.000Z")), + }); + + expect(consumed).toBe(true); + expect(calls).toEqual([ + "insert", + "insert.values", + "insert.onConflictDoNothing", + "insert.returning", + ]); + expect(insertedValues).toMatchObject([ + { + thumbprint: "thumbprint", + jti: "jti", + iat: 1_771_000_000, + expiresAt: "2026-05-25T12:00:00.000Z", + }, + ]); + }).pipe(Effect.provide(DpopProofs.layer.pipe(Layer.provide(Layer.succeed(RelayDb, fakeDb))))); + }); + + it.effect("prunes expired proof rows from the maintenance path", () => { + const calls: Array = []; + const fakeDb = { + delete: (table: unknown) => { + expect(table).toBe(relayDpopProofs); + calls.push("delete"); + return { + where: (condition: unknown) => { + expect(condition).toBeDefined(); + calls.push("delete.where"); + return Effect.void; + }, + }; + }, + } as unknown as RelayDatabase; + + return Effect.gen(function* () { + const replay = yield* DpopProofs.DpopProofReplay; + yield* replay.pruneExpired; + expect(calls).toEqual(["delete", "delete.where"]); + }).pipe(Effect.provide(DpopProofs.layer.pipe(Layer.provide(Layer.succeed(RelayDb, fakeDb))))); + }); +}); diff --git a/infra/relay/src/persistence/DpopProofs.ts b/infra/relay/src/persistence/DpopProofs.ts new file mode 100644 index 0000000000..a0e296c570 --- /dev/null +++ b/infra/relay/src/persistence/DpopProofs.ts @@ -0,0 +1,68 @@ +import * as Context from "effect/Context"; +import * as Data from "effect/Data"; +import * as DateTime from "effect/DateTime"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import { lt } from "drizzle-orm"; + +import { RelayDb } from "../db.ts"; +import { relayDpopProofs } from "../schema.ts"; + +export class DpopProofReplayPersistenceError extends Data.TaggedError( + "DpopProofReplayPersistenceError", +)<{ + readonly cause: unknown; +}> {} + +export interface DpopProofReplayShape { + readonly consume: (input: { + readonly thumbprint: string; + readonly jti: string; + readonly iat: number; + readonly expiresAt: DateTime.DateTime; + }) => Effect.Effect; + + readonly pruneExpired: Effect.Effect; +} + +export class DpopProofReplay extends Context.Service()( + "DpopProofReplay", +) {} + +const make = Effect.gen(function* () { + const db = yield* RelayDb; + + const consume: DpopProofReplayShape["consume"] = Effect.fn("relay.dpop_proofs.consume")( + function* (input) { + const createdAt = DateTime.formatIso(yield* DateTime.now); + const inserted = yield* db + .insert(relayDpopProofs) + .values({ + thumbprint: input.thumbprint, + jti: input.jti, + iat: input.iat, + expiresAt: DateTime.formatIso(input.expiresAt), + createdAt, + }) + .onConflictDoNothing() + .returning({ jti: relayDpopProofs.jti }); + return inserted.length > 0; + }, + Effect.mapError((cause) => new DpopProofReplayPersistenceError({ cause })), + ); + + const pruneExpired: DpopProofReplayShape["pruneExpired"] = Effect.fn( + "relay.dpop_proofs.prune_expired", + )(function* () { + const now = DateTime.formatIso(yield* DateTime.now); + yield* Effect.annotateCurrentSpan({ "relay.dpop_prune.before": now }); + yield* db.delete(relayDpopProofs).where(lt(relayDpopProofs.expiresAt, now)); + })().pipe(Effect.mapError((cause) => new DpopProofReplayPersistenceError({ cause }))); + + return DpopProofReplay.of({ + consume, + pruneExpired, + }); +}); + +export const layer = Layer.effect(DpopProofReplay, make); diff --git a/infra/relay/src/persistence/EnvironmentCredentials.test.ts b/infra/relay/src/persistence/EnvironmentCredentials.test.ts new file mode 100644 index 0000000000..315815606e --- /dev/null +++ b/infra/relay/src/persistence/EnvironmentCredentials.test.ts @@ -0,0 +1,148 @@ +import * as NodeCryptoLayer from "@effect/platform-node/NodeCrypto"; +import { describe, expect, it } from "@effect/vitest"; +import { PgDialect } from "drizzle-orm/pg-core"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; + +import { RelayDb, type RelayDatabase } from "../db.ts"; +import { relayEnvironmentCredentials } from "../schema.ts"; +import * as EnvironmentCredentials from "./EnvironmentCredentials.ts"; + +describe("EnvironmentCredentials", () => { + it.effect( + "creates opaque credentials and revokes only older credentials for the same key", + () => { + const insertedValues: Array<{ + readonly credentialId: string; + readonly environmentId: string; + readonly environmentPublicKey: string; + readonly credentialHash: string; + readonly revokedAt: null; + readonly createdAt: string; + readonly updatedAt: string; + }> = []; + const staleCredentialRevocations: Array<{ + readonly values: Record; + readonly condition: unknown; + }> = []; + + const fakeDb = { + insert: (table: unknown) => { + expect(table).toBe(relayEnvironmentCredentials); + return { + values: (values: (typeof insertedValues)[number]) => { + insertedValues.push(values); + return Effect.void; + }, + }; + }, + update: (table: unknown) => { + expect(table).toBe(relayEnvironmentCredentials); + return { + set: (values: Record) => ({ + where: (condition: unknown) => { + staleCredentialRevocations.push({ values, condition }); + return Effect.void; + }, + }), + }; + }, + } as unknown as RelayDatabase; + + return Effect.gen(function* () { + const credentials = yield* EnvironmentCredentials.EnvironmentCredentials; + const token = yield* credentials.create({ + environmentId: "env_test", + environmentPublicKey: "environment-public-key", + }); + const [, credentialId, secret] = token.split("_"); + + expect(token).toMatch(/^t3env_[0-9a-f]{64}_[0-9a-f]{96}$/); + expect(credentialId).toHaveLength(64); + expect(secret).toHaveLength(96); + expect(insertedValues).toHaveLength(1); + expect(insertedValues[0]).toMatchObject({ + credentialId, + environmentId: "env_test", + environmentPublicKey: "environment-public-key", + revokedAt: null, + }); + expect(insertedValues[0]?.credentialHash).toMatch(/^[A-Za-z0-9_-]{43}$/); + expect(insertedValues[0]?.credentialHash).not.toContain(token); + expect(insertedValues[0]?.createdAt).toBe(insertedValues[0]?.updatedAt); + expect(staleCredentialRevocations).toHaveLength(1); + expect(staleCredentialRevocations[0]?.values.revokedAt).toEqual( + staleCredentialRevocations[0]?.values.updatedAt, + ); + + const query = new PgDialect().sqlToQuery(staleCredentialRevocations[0]?.condition as never); + expect(query.sql).toContain('"relay_environment_credentials"."environment_id" = $1'); + expect(query.sql).toContain( + '"relay_environment_credentials"."environment_public_key" = $2', + ); + expect(query.sql).toContain('"relay_environment_credentials"."credential_id" <> $3'); + expect(query.sql).toContain('"relay_environment_credentials"."revoked_at" is null'); + expect(query.params).toEqual(["env_test", "environment-public-key", credentialId]); + }).pipe( + Effect.provide( + EnvironmentCredentials.layer.pipe( + Layer.provide(NodeCryptoLayer.layer), + Layer.provide(Layer.succeed(RelayDb, fakeDb)), + ), + ), + ); + }, + ); + + it.effect("revokes active credentials for an environment public key", () => { + const updateValues: Array> = []; + const whereConditions: Array = []; + const fakeDb = { + update: (table: unknown) => { + expect(table).toBe(relayEnvironmentCredentials); + return { + set: (values: Record) => { + updateValues.push(values); + return { + where: (condition: unknown) => { + whereConditions.push(condition); + return { + returning: (selection: unknown) => { + expect(selection).toBeDefined(); + return Effect.succeed([{ credentialId: "credential-1" }]); + }, + }; + }, + }; + }, + }; + }, + } as unknown as RelayDatabase; + + return Effect.gen(function* () { + const credentials = yield* EnvironmentCredentials.EnvironmentCredentials; + const revoked = yield* credentials.revokeForEnvironmentPublicKey({ + environmentId: "env_test", + environmentPublicKey: "environment-public-key", + }); + + expect(revoked).toBe(true); + expect(updateValues).toHaveLength(1); + expect(updateValues[0]?.revokedAt).toEqual(updateValues[0]?.updatedAt); + expect(whereConditions).toHaveLength(1); + + const query = new PgDialect().sqlToQuery(whereConditions[0] as never); + expect(query.sql).toContain('"relay_environment_credentials"."environment_id" = $1'); + expect(query.sql).toContain('"relay_environment_credentials"."environment_public_key" = $2'); + expect(query.sql).toContain('"relay_environment_credentials"."revoked_at" is null'); + expect(query.params).toEqual(["env_test", "environment-public-key"]); + }).pipe( + Effect.provide( + EnvironmentCredentials.layer.pipe( + Layer.provide(NodeCryptoLayer.layer), + Layer.provide(Layer.succeed(RelayDb, fakeDb)), + ), + ), + ); + }); +}); diff --git a/infra/relay/src/persistence/EnvironmentCredentials.ts b/infra/relay/src/persistence/EnvironmentCredentials.ts new file mode 100644 index 0000000000..4036123607 --- /dev/null +++ b/infra/relay/src/persistence/EnvironmentCredentials.ts @@ -0,0 +1,176 @@ +import * as Context from "effect/Context"; +import * as Crypto from "effect/Crypto"; +import * as Data from "effect/Data"; +import * as DateTime from "effect/DateTime"; +import * as Effect from "effect/Effect"; +import * as Encoding from "effect/Encoding"; +import * as Layer from "effect/Layer"; +import * as Option from "effect/Option"; +import { and, eq, isNull, ne } from "drizzle-orm"; + +import { RelayDb } from "../db.ts"; +import { relayEnvironmentCredentials } from "../schema.ts"; + +export class EnvironmentCredentialCreatePersistenceError extends Data.TaggedError( + "EnvironmentCredentialCreatePersistenceError", +)<{ + readonly cause: unknown; +}> {} + +export class EnvironmentCredentialAuthenticatePersistenceError extends Data.TaggedError( + "EnvironmentCredentialAuthenticatePersistenceError", +)<{ + readonly cause: unknown; +}> {} + +export class EnvironmentCredentialRevokePersistenceError extends Data.TaggedError( + "EnvironmentCredentialRevokePersistenceError", +)<{ + readonly cause: unknown; +}> {} + +export interface EnvironmentCredentialPrincipal { + readonly credentialId: string; + readonly environmentId: string; + readonly environmentPublicKey: string; +} + +export interface EnvironmentCredentialsShape { + readonly create: (input: { + readonly environmentId: string; + readonly environmentPublicKey: string; + }) => Effect.Effect; + readonly authenticate: ( + token: string, + ) => Effect.Effect< + Option.Option, + EnvironmentCredentialAuthenticatePersistenceError + >; + readonly revokeForEnvironmentPublicKey: (input: { + readonly environmentId: string; + readonly environmentPublicKey: string; + }) => Effect.Effect; +} + +export class EnvironmentCredentials extends Context.Service< + EnvironmentCredentials, + EnvironmentCredentialsShape +>()("EnvironmentCredentials") {} + +const make = Effect.gen(function* () { + const db = yield* RelayDb; + const crypto = yield* Crypto.Crypto; + const hashToken = (token: string) => + crypto + .digest("SHA-256", new TextEncoder().encode(token)) + .pipe(Effect.map(Encoding.encodeBase64Url)); + const randomTokenPart = (segments: number) => + Effect.map(Effect.all(Array.from({ length: segments }, () => crypto.randomUUIDv4)), (values) => + values.join("").replaceAll("-", ""), + ); + const makeCredential = Effect.fnUntraced(function* () { + const credentialId = yield* randomTokenPart(2); + const secret = yield* randomTokenPart(3); + return { + credentialId, + token: `t3env_${credentialId}_${secret}`, + }; + }); + + return EnvironmentCredentials.of({ + create: Effect.fn("relay.environment_credentials.create")( + function* (input) { + yield* Effect.annotateCurrentSpan({ "relay.environment_id": input.environmentId }); + const credential = yield* makeCredential(); + const credentialHash = yield* hashToken(credential.token); + const now = DateTime.formatIso(yield* DateTime.now); + yield* db.insert(relayEnvironmentCredentials).values({ + credentialId: credential.credentialId, + environmentId: input.environmentId, + environmentPublicKey: input.environmentPublicKey, + credentialHash, + revokedAt: null, + createdAt: now, + updatedAt: now, + }); + yield* db + .update(relayEnvironmentCredentials) + .set({ + revokedAt: now, + updatedAt: now, + }) + .where( + and( + eq(relayEnvironmentCredentials.environmentId, input.environmentId), + eq(relayEnvironmentCredentials.environmentPublicKey, input.environmentPublicKey), + ne(relayEnvironmentCredentials.credentialId, credential.credentialId), + isNull(relayEnvironmentCredentials.revokedAt), + ), + ); + return credential.token; + }, + Effect.mapError((cause) => new EnvironmentCredentialCreatePersistenceError({ cause })), + ), + + authenticate: Effect.fn("relay.environment_credentials.authenticate")( + function* (token) { + const credentialHash = yield* hashToken(token); + const rows = yield* db + .select({ + credentialId: relayEnvironmentCredentials.credentialId, + environmentId: relayEnvironmentCredentials.environmentId, + environmentPublicKey: relayEnvironmentCredentials.environmentPublicKey, + }) + .from(relayEnvironmentCredentials) + .where( + and( + eq(relayEnvironmentCredentials.credentialHash, credentialHash), + isNull(relayEnvironmentCredentials.revokedAt), + ), + ) + .limit(1); + const row = rows[0]; + if (row) { + yield* Effect.annotateCurrentSpan({ "relay.environment_id": row.environmentId }); + } + return row + ? Option.some({ + credentialId: row.credentialId, + environmentId: row.environmentId, + environmentPublicKey: row.environmentPublicKey, + }) + : Option.none(); + }, + Effect.mapError((cause) => new EnvironmentCredentialAuthenticatePersistenceError({ cause })), + ), + + revokeForEnvironmentPublicKey: Effect.fn( + "relay.environment_credentials.revoke_for_environment_public_key", + )( + function* (input) { + yield* Effect.annotateCurrentSpan({ "relay.environment_id": input.environmentId }); + const revokedAt = DateTime.formatIso(yield* DateTime.now); + const rows = yield* db + .update(relayEnvironmentCredentials) + .set({ + revokedAt, + updatedAt: revokedAt, + }) + .where( + and( + eq(relayEnvironmentCredentials.environmentId, input.environmentId), + eq(relayEnvironmentCredentials.environmentPublicKey, input.environmentPublicKey), + isNull(relayEnvironmentCredentials.revokedAt), + ), + ) + .returning({ + credentialId: relayEnvironmentCredentials.credentialId, + }); + return rows.length > 0; + }, + Effect.mapError((cause) => new EnvironmentCredentialRevokePersistenceError({ cause })), + ), + }); +}); + +export const layer = Layer.effect(EnvironmentCredentials, make); diff --git a/infra/relay/src/persistence/EnvironmentLinks.test.ts b/infra/relay/src/persistence/EnvironmentLinks.test.ts new file mode 100644 index 0000000000..500ffadb71 --- /dev/null +++ b/infra/relay/src/persistence/EnvironmentLinks.test.ts @@ -0,0 +1,78 @@ +import { describe, expect, it } from "@effect/vitest"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import { PgDialect } from "drizzle-orm/pg-core"; + +import { RelayDb, type RelayDatabase } from "../db.ts"; +import { relayEnvironmentLinks } from "../schema.ts"; +import { + agentAwarenessDeliveryUserCondition, + EnvironmentLinks, + layer, +} from "./EnvironmentLinks.ts"; + +describe("EnvironmentLinks", () => { + it("selects users when either notifications or Live Activities are enabled", () => { + const dialect = new PgDialect(); + const condition = agentAwarenessDeliveryUserCondition("env-1"); + expect(condition).toBeDefined(); + if (!condition) { + throw new Error("Expected agent awareness delivery condition."); + } + const query = dialect.sqlToQuery(condition); + + expect(query.sql).toContain('"relay_environment_links"."environment_id" = $1'); + expect(query.sql).toContain('"relay_environment_links"."revoked_at" is null'); + expect(query.sql).toContain('"relay_environment_links"."notifications_enabled" = $2'); + expect(query.sql).toContain('"relay_environment_links"."live_activities_enabled" = $3'); + expect(query.sql).toContain(" or "); + expect(query.params).toEqual(["env-1", true, true]); + }); + + it.effect("revokes only the active link owned by the requesting user", () => { + const updateValues: Array> = []; + const whereConditions: Array = []; + const fakeDb = { + update: (table: unknown) => { + expect(table).toBe(relayEnvironmentLinks); + return { + set: (values: Record) => { + updateValues.push(values); + return { + where: (condition: unknown) => { + whereConditions.push(condition); + return { + returning: (selection: unknown) => { + expect(selection).toBeDefined(); + return Effect.succeed([{ environmentId: "env-1" }]); + }, + }; + }, + }; + }, + }; + }, + } as unknown as RelayDatabase; + + return Effect.gen(function* () { + const links = yield* EnvironmentLinks; + const revoked = yield* links.revokeForUser({ + userId: "user-1", + environmentId: "env-1", + }); + + expect(revoked).toBe(true); + expect(updateValues).toHaveLength(1); + expect(updateValues[0]?.revokedAt).toEqual(updateValues[0]?.updatedAt); + expect(typeof updateValues[0]?.revokedAt).toBe("string"); + expect(whereConditions).toHaveLength(1); + + const dialect = new PgDialect(); + const query = dialect.sqlToQuery(whereConditions[0] as never); + expect(query.sql).toContain('"relay_environment_links"."user_id" = $1'); + expect(query.sql).toContain('"relay_environment_links"."environment_id" = $2'); + expect(query.sql).toContain('"relay_environment_links"."revoked_at" is null'); + expect(query.params).toEqual(["user-1", "env-1"]); + }).pipe(Effect.provide(layer.pipe(Layer.provide(Layer.succeed(RelayDb, fakeDb))))); + }); +}); diff --git a/infra/relay/src/persistence/EnvironmentLinks.ts b/infra/relay/src/persistence/EnvironmentLinks.ts new file mode 100644 index 0000000000..1d70d88d8c --- /dev/null +++ b/infra/relay/src/persistence/EnvironmentLinks.ts @@ -0,0 +1,349 @@ +import type { + RelayClientEnvironmentRecord, + RelayEnvironmentLinkProofPayload, + RelayEnvironmentLinkRequest, + RelayManagedEndpoint, +} from "@t3tools/contracts/relay"; +import * as Context from "effect/Context"; +import * as Data from "effect/Data"; +import * as DateTime from "effect/DateTime"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import { and, eq, isNull, or } from "drizzle-orm"; + +import { RelayDb } from "../db.ts"; +import { relayEnvironmentLinks } from "../schema.ts"; + +export interface RelayLinkedEnvironmentRecord extends RelayClientEnvironmentRecord { + readonly environmentPublicKey: string; +} + +export interface AgentAwarenessDeliveryUserRecord { + readonly userId: string; + readonly notificationsEnabled: boolean; + readonly liveActivitiesEnabled: boolean; +} + +export class EnvironmentLinkUpsertPersistenceError extends Data.TaggedError( + "EnvironmentLinkUpsertPersistenceError", +)<{ + readonly cause: unknown; +}> {} + +export class EnvironmentLinkUserListPersistenceError extends Data.TaggedError( + "EnvironmentLinkUserListPersistenceError", +)<{ + readonly cause: unknown; +}> {} + +export class EnvironmentPublicKeyListPersistenceError extends Data.TaggedError( + "EnvironmentPublicKeyListPersistenceError", +)<{ + readonly cause: unknown; +}> {} + +export class EnvironmentLinkListPersistenceError extends Data.TaggedError( + "EnvironmentLinkListPersistenceError", +)<{ + readonly cause: unknown; +}> {} + +export class EnvironmentLinkLookupPersistenceError extends Data.TaggedError( + "EnvironmentLinkLookupPersistenceError", +)<{ + readonly cause: unknown; +}> {} + +export class EnvironmentLinkRevokePersistenceError extends Data.TaggedError( + "EnvironmentLinkRevokePersistenceError", +)<{ + readonly cause: unknown; +}> {} + +export interface EnvironmentLinksShape { + readonly upsert: (input: { + readonly userId: string; + readonly request: RelayEnvironmentLinkRequest; + readonly proof: RelayEnvironmentLinkProofPayload; + readonly endpoint: RelayManagedEndpoint; + }) => Effect.Effect; + readonly listUsersForEnvironment: (input: { + readonly environmentId: string; + }) => Effect.Effect, EnvironmentLinkUserListPersistenceError>; + readonly listDeliveryUsersForEnvironment: (input: { + readonly environmentId: string; + readonly environmentPublicKey: string; + }) => Effect.Effect< + ReadonlyArray, + EnvironmentLinkUserListPersistenceError + >; + readonly listPublicKeysForEnvironment: (input: { + readonly environmentId: string; + }) => Effect.Effect, EnvironmentPublicKeyListPersistenceError>; + readonly listForUser: (input: { + readonly userId: string; + }) => Effect.Effect< + ReadonlyArray, + EnvironmentLinkListPersistenceError + >; + readonly getForUser: (input: { + readonly userId: string; + readonly environmentId: string; + }) => Effect.Effect; + readonly revokeForUser: (input: { + readonly userId: string; + readonly environmentId: string; + }) => Effect.Effect; +} + +export class EnvironmentLinks extends Context.Service()( + "EnvironmentLinks", +) {} + +export function agentAwarenessDeliveryUserCondition(environmentId: string) { + return and( + eq(relayEnvironmentLinks.environmentId, environmentId), + isNull(relayEnvironmentLinks.revokedAt), + or( + eq(relayEnvironmentLinks.notificationsEnabled, true), + eq(relayEnvironmentLinks.liveActivitiesEnabled, true), + ), + ); +} + +export function agentAwarenessDeliveryUserKeyCondition(input: { + readonly environmentId: string; + readonly environmentPublicKey: string; +}) { + return and( + agentAwarenessDeliveryUserCondition(input.environmentId), + eq(relayEnvironmentLinks.environmentPublicKey, input.environmentPublicKey), + ); +} + +const make = Effect.gen(function* () { + const db = yield* RelayDb; + + return EnvironmentLinks.of({ + upsert: Effect.fn("relay.environment_links.upsert")( + function* (input) { + yield* Effect.annotateCurrentSpan({ + "user.id": input.userId, + "relay.environment_id": input.proof.environmentId, + }); + const now = DateTime.formatIso(yield* DateTime.now); + const { request, proof } = input; + const environmentId = proof.environmentId; + const { endpoint } = input; + yield* db + .insert(relayEnvironmentLinks) + .values({ + userId: input.userId, + environmentId, + environmentLabel: proof.descriptor.label, + environmentPublicKey: proof.environmentPublicKey, + endpointHttpBaseUrl: endpoint.httpBaseUrl, + endpointWsBaseUrl: endpoint.wsBaseUrl, + endpointProviderKind: endpoint.providerKind, + notificationsEnabled: request.notificationsEnabled, + liveActivitiesEnabled: request.liveActivitiesEnabled, + managedTunnelsEnabled: request.managedTunnelsEnabled, + createdByDeviceId: request.deviceId ?? null, + revokedAt: null, + createdAt: now, + updatedAt: now, + }) + .onConflictDoUpdate({ + target: [relayEnvironmentLinks.userId, relayEnvironmentLinks.environmentId], + set: { + environmentPublicKey: proof.environmentPublicKey, + environmentLabel: proof.descriptor.label, + endpointHttpBaseUrl: endpoint.httpBaseUrl, + endpointWsBaseUrl: endpoint.wsBaseUrl, + endpointProviderKind: endpoint.providerKind, + notificationsEnabled: request.notificationsEnabled, + liveActivitiesEnabled: request.liveActivitiesEnabled, + managedTunnelsEnabled: request.managedTunnelsEnabled, + createdByDeviceId: request.deviceId ?? null, + revokedAt: null, + updatedAt: now, + }, + }); + }, + Effect.mapError((cause) => new EnvironmentLinkUpsertPersistenceError({ cause })), + ), + + listUsersForEnvironment: Effect.fn("relay.environment_links.list_users_for_environment")( + function* (input) { + yield* Effect.annotateCurrentSpan({ "relay.environment_id": input.environmentId }); + return yield* db + .select({ userId: relayEnvironmentLinks.userId }) + .from(relayEnvironmentLinks) + .where(agentAwarenessDeliveryUserCondition(input.environmentId)) + .pipe( + Effect.map((rows) => rows.map((row) => row.userId)), + Effect.mapError((cause) => new EnvironmentLinkUserListPersistenceError({ cause })), + ); + }, + ), + + listDeliveryUsersForEnvironment: Effect.fn( + "relay.environment_links.list_delivery_users_for_environment", + )(function* (input) { + yield* Effect.annotateCurrentSpan({ "relay.environment_id": input.environmentId }); + return yield* db + .select({ + userId: relayEnvironmentLinks.userId, + notificationsEnabled: relayEnvironmentLinks.notificationsEnabled, + liveActivitiesEnabled: relayEnvironmentLinks.liveActivitiesEnabled, + }) + .from(relayEnvironmentLinks) + .where(agentAwarenessDeliveryUserKeyCondition(input)) + .pipe( + Effect.map((rows) => + rows.map((row) => ({ + userId: row.userId, + notificationsEnabled: row.notificationsEnabled, + liveActivitiesEnabled: row.liveActivitiesEnabled, + })), + ), + Effect.mapError((cause) => new EnvironmentLinkUserListPersistenceError({ cause })), + ); + }), + + listPublicKeysForEnvironment: Effect.fn( + "relay.environment_links.list_public_keys_for_environment", + )(function* (input) { + yield* Effect.annotateCurrentSpan({ "relay.environment_id": input.environmentId }); + return yield* db + .select({ environmentPublicKey: relayEnvironmentLinks.environmentPublicKey }) + .from(relayEnvironmentLinks) + .where( + and( + eq(relayEnvironmentLinks.environmentId, input.environmentId), + isNull(relayEnvironmentLinks.revokedAt), + ), + ) + .pipe( + Effect.map((rows) => [ + ...new Set(rows.map((row) => row.environmentPublicKey).filter((key) => key.length > 0)), + ]), + Effect.mapError((cause) => new EnvironmentPublicKeyListPersistenceError({ cause })), + ); + }), + + listForUser: Effect.fn("relay.environment_links.list_for_user")(function* (input) { + yield* Effect.annotateCurrentSpan({ "user.id": input.userId }); + return yield* db + .select({ + environmentId: relayEnvironmentLinks.environmentId, + environmentLabel: relayEnvironmentLinks.environmentLabel, + endpointHttpBaseUrl: relayEnvironmentLinks.endpointHttpBaseUrl, + endpointWsBaseUrl: relayEnvironmentLinks.endpointWsBaseUrl, + endpointProviderKind: relayEnvironmentLinks.endpointProviderKind, + createdAt: relayEnvironmentLinks.createdAt, + }) + .from(relayEnvironmentLinks) + .where( + and( + eq(relayEnvironmentLinks.userId, input.userId), + isNull(relayEnvironmentLinks.revokedAt), + ), + ) + .pipe( + Effect.map((rows) => + rows.map((row) => ({ + environmentId: row.environmentId as RelayClientEnvironmentRecord["environmentId"], + label: + row.environmentLabel.trim().length > 0 ? row.environmentLabel : row.environmentId, + endpoint: { + httpBaseUrl: row.endpointHttpBaseUrl, + wsBaseUrl: row.endpointWsBaseUrl, + providerKind: + row.endpointProviderKind as RelayClientEnvironmentRecord["endpoint"]["providerKind"], + }, + linkedAt: row.createdAt, + })), + ), + Effect.mapError((cause) => new EnvironmentLinkListPersistenceError({ cause })), + ); + }), + + getForUser: Effect.fn("relay.environment_links.get_for_user")(function* (input) { + yield* Effect.annotateCurrentSpan({ + "user.id": input.userId, + "relay.environment_id": input.environmentId, + }); + return yield* db + .select({ + environmentId: relayEnvironmentLinks.environmentId, + environmentLabel: relayEnvironmentLinks.environmentLabel, + environmentPublicKey: relayEnvironmentLinks.environmentPublicKey, + endpointHttpBaseUrl: relayEnvironmentLinks.endpointHttpBaseUrl, + endpointWsBaseUrl: relayEnvironmentLinks.endpointWsBaseUrl, + endpointProviderKind: relayEnvironmentLinks.endpointProviderKind, + createdAt: relayEnvironmentLinks.createdAt, + }) + .from(relayEnvironmentLinks) + .where( + and( + eq(relayEnvironmentLinks.userId, input.userId), + eq(relayEnvironmentLinks.environmentId, input.environmentId), + isNull(relayEnvironmentLinks.revokedAt), + ), + ) + .limit(1) + .pipe( + Effect.map((rows) => { + const row = rows[0]; + return row + ? { + environmentId: row.environmentId as RelayClientEnvironmentRecord["environmentId"], + label: + row.environmentLabel.trim().length > 0 + ? row.environmentLabel + : row.environmentId, + endpoint: { + httpBaseUrl: row.endpointHttpBaseUrl, + wsBaseUrl: row.endpointWsBaseUrl, + providerKind: + row.endpointProviderKind as RelayClientEnvironmentRecord["endpoint"]["providerKind"], + }, + environmentPublicKey: row.environmentPublicKey, + linkedAt: row.createdAt, + } + : null; + }), + Effect.mapError((cause) => new EnvironmentLinkLookupPersistenceError({ cause })), + ); + }), + + revokeForUser: Effect.fn("relay.environment_links.revoke_for_user")( + function* (input) { + yield* Effect.annotateCurrentSpan({ + "user.id": input.userId, + "relay.environment_id": input.environmentId, + }); + const revokedAt = DateTime.formatIso(yield* DateTime.now); + const rows = yield* db + .update(relayEnvironmentLinks) + .set({ + revokedAt, + updatedAt: revokedAt, + }) + .where( + and( + eq(relayEnvironmentLinks.userId, input.userId), + eq(relayEnvironmentLinks.environmentId, input.environmentId), + isNull(relayEnvironmentLinks.revokedAt), + ), + ) + .returning({ environmentId: relayEnvironmentLinks.environmentId }); + return rows.length > 0; + }, + Effect.mapError((cause) => new EnvironmentLinkRevokePersistenceError({ cause })), + ), + }); +}); + +export const layer = Layer.effect(EnvironmentLinks, make); diff --git a/infra/relay/src/persistence/LiveActivities.test.ts b/infra/relay/src/persistence/LiveActivities.test.ts new file mode 100644 index 0000000000..3f909fb7ba --- /dev/null +++ b/infra/relay/src/persistence/LiveActivities.test.ts @@ -0,0 +1,196 @@ +import type { + RelayAgentActivityAggregateState, + RelayLiveActivityRegistrationRequest, +} from "@t3tools/contracts/relay"; +import { describe, expect, it } from "@effect/vitest"; +import type { SQL } from "drizzle-orm"; +import { PgDialect } from "drizzle-orm/pg-core"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; + +import { RelayDb, type RelayDatabase } from "../db.ts"; +import { relayLiveActivities } from "../schema.ts"; +import * as LiveActivities from "./LiveActivities.ts"; + +const aggregate: RelayAgentActivityAggregateState = { + title: "T3 Code", + subtitle: "Agent work in progress", + activeCount: 1, + updatedAt: "2026-05-25T00:00:00.000Z", + activities: [ + { + environmentId: + "env" as RelayAgentActivityAggregateState["activities"][number]["environmentId"], + threadId: "thread" as RelayAgentActivityAggregateState["activities"][number]["threadId"], + projectTitle: "Project", + threadTitle: "Thread", + modelTitle: "gpt-5.4", + phase: "running", + status: "Working", + updatedAt: "2026-05-25T00:00:00.000Z", + deepLink: "/threads/env/thread", + }, + ], +}; + +describe("LiveActivities", () => { + it.effect( + "claims Live Activity push tokens globally before upserting the current user device", + () => { + const registration: RelayLiveActivityRegistrationRequest = { + deviceId: "device-1" as RelayLiveActivityRegistrationRequest["deviceId"], + activityPushToken: + "activity-push-token" as RelayLiveActivityRegistrationRequest["activityPushToken"], + }; + const calls: Array = []; + const updateSets: Array> = []; + const updateConditions: Array = []; + const insertedValues: Array> = []; + const conflictConfigs: Array<{ + readonly set?: Record; + }> = []; + const dialect = new PgDialect(); + + const fakeDb = { + update: (table: unknown) => { + expect(table).toBe(relayLiveActivities); + calls.push("update"); + return { + set: (values: Record) => { + updateSets.push(values); + calls.push("update.set"); + return { + where: (condition: SQL) => { + expect(condition).toBeDefined(); + updateConditions.push(condition); + calls.push("update.where"); + return Effect.void; + }, + }; + }, + }; + }, + insert: (table: unknown) => { + expect(table).toBe(relayLiveActivities); + calls.push("insert"); + return { + values: (values: Record) => { + insertedValues.push(values); + calls.push("insert.values"); + return { + onConflictDoUpdate: (config: { readonly set?: Record }) => { + expect(config).toBeDefined(); + conflictConfigs.push(config); + calls.push("insert.onConflictDoUpdate"); + return Effect.void; + }, + }; + }, + }; + }, + } as unknown as RelayDatabase; + + return Effect.gen(function* () { + const liveActivities = yield* LiveActivities.LiveActivities; + yield* liveActivities.register({ userId: "user-2", registration }); + + expect(calls).toEqual([ + "update", + "update.set", + "update.where", + "insert", + "insert.values", + "insert.onConflictDoUpdate", + ]); + expect(updateSets).toEqual([ + expect.objectContaining({ + activityPushToken: null, + remoteStartQueuedAt: null, + remoteStartedAt: null, + }), + ]); + expect(updateConditions.map((condition) => dialect.sqlToQuery(condition))).toEqual([ + { + sql: '"relay_live_activities"."activity_push_token" = $1', + params: ["activity-push-token"], + }, + ]); + expect(insertedValues).toEqual([ + expect.objectContaining({ + userId: "user-2", + deviceId: "device-1", + activityPushToken: "activity-push-token", + remoteStartQueuedAt: null, + remoteStartedAt: expect.any(String), + endedAt: null, + lastAggregateJson: null, + lastLiveActivityDeliveryAt: null, + }), + ]); + expect(conflictConfigs[0]?.set).toEqual( + expect.objectContaining({ + activityPushToken: "activity-push-token", + remoteStartQueuedAt: null, + remoteStartedAt: expect.any(String), + endedAt: null, + lastAggregateJson: null, + lastLiveActivityDeliveryAt: null, + }), + ); + }).pipe( + Effect.provide(LiveActivities.layer.pipe(Layer.provide(Layer.succeed(RelayDb, fakeDb)))), + ); + }, + ); + + it.effect("preserves ended state when a delayed update delivery is marked", () => { + const insertedValues: Array> = []; + const conflictConfigs: Array<{ + readonly set?: Record; + }> = []; + + const fakeDb = { + insert: (table: unknown) => { + expect(table).toBe(relayLiveActivities); + return { + values: (values: Record) => { + insertedValues.push(values); + return { + onConflictDoUpdate: (config: { readonly set?: Record }) => { + conflictConfigs.push(config); + return Effect.void; + }, + }; + }, + }; + }, + } as unknown as RelayDatabase; + + return Effect.gen(function* () { + const liveActivities = yield* LiveActivities.LiveActivities; + yield* liveActivities.markDelivery({ + userId: "user-2", + deviceId: "device-1", + kind: "live_activity_update", + aggregate, + deliveredAt: "2026-05-25T00:00:10.000Z", + }); + + expect(insertedValues).toEqual([ + expect.objectContaining({ + userId: "user-2", + deviceId: "device-1", + endedAt: null, + }), + ]); + expect(conflictConfigs[0]?.set).toEqual( + expect.objectContaining({ + endedAt: relayLiveActivities.endedAt, + lastLiveActivityDeliveryAt: "2026-05-25T00:00:10.000Z", + }), + ); + }).pipe( + Effect.provide(LiveActivities.layer.pipe(Layer.provide(Layer.succeed(RelayDb, fakeDb)))), + ); + }); +}); diff --git a/infra/relay/src/persistence/LiveActivities.ts b/infra/relay/src/persistence/LiveActivities.ts new file mode 100644 index 0000000000..a9bbd82f8f --- /dev/null +++ b/infra/relay/src/persistence/LiveActivities.ts @@ -0,0 +1,375 @@ +import type { + RelayAgentActivityAggregateState, + RelayDeliveryKind, + RelayLiveActivityRegistrationRequest, +} from "@t3tools/contracts/relay"; +import { RelayAgentActivityAggregateState as RelayAgentActivityAggregateStateSchema } from "@t3tools/contracts/relay"; +import * as Context from "effect/Context"; +import * as Data from "effect/Data"; +import * as DateTime from "effect/DateTime"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import * as Schema from "effect/Schema"; +import { and, eq, sql } from "drizzle-orm"; + +import { RelayDb } from "../db.ts"; +import { relayLiveActivities, relayMobileDevices } from "../schema.ts"; +import { parseJsonString, stringifyJsonValue } from "./json.ts"; + +export class LiveActivityRegistrationPersistenceError extends Data.TaggedError( + "LiveActivityRegistrationPersistenceError", +)<{ + readonly cause: unknown; +}> {} + +export class LiveActivityTargetListPersistenceError extends Data.TaggedError( + "LiveActivityTargetListPersistenceError", +)<{ + readonly cause: unknown; +}> {} + +export class LiveActivityDeliveryMarkPersistenceError extends Data.TaggedError( + "LiveActivityDeliveryMarkPersistenceError", +)<{ + readonly cause: unknown; +}> {} + +export interface DeviceRow { + readonly user_id: string; + readonly device_id: string; + readonly platform: "ios"; + readonly ios_major_version: number; + readonly app_version: string | null; + readonly push_token: string | null; + readonly push_to_start_token: string | null; + readonly preferences_json: string; +} + +export interface LiveActivityRow { + readonly activity_push_token: string | null; + readonly remote_start_queued_at: string | null; + readonly remote_started_at: string | null; + readonly ended_at: string | null; + readonly last_aggregate_json: string | null; + readonly last_live_activity_delivery_at: string | null; +} + +export type TargetRow = DeviceRow & LiveActivityRow; + +export interface LiveActivitiesShape { + readonly register: (input: { + readonly userId: string; + readonly registration: RelayLiveActivityRegistrationRequest; + }) => Effect.Effect; + readonly listTargets: (input: { + readonly userId: string; + }) => Effect.Effect, LiveActivityTargetListPersistenceError>; + readonly markDelivery: (input: { + readonly userId: string; + readonly deviceId: string; + readonly kind: RelayDeliveryKind; + readonly aggregate: RelayAgentActivityAggregateState | null; + readonly deliveredAt: string; + }) => Effect.Effect; + readonly markStartQueued: (input: { + readonly userId: string; + readonly deviceId: string; + readonly queuedAt: string; + }) => Effect.Effect; + readonly clearStartQueued: (input: { + readonly userId: string; + readonly deviceId: string; + }) => Effect.Effect; + readonly invalidateDeliveryToken: (input: { + readonly userId: string; + readonly deviceId: string; + readonly kind: RelayDeliveryKind; + readonly invalidatedAt: string; + }) => Effect.Effect; +} + +export class LiveActivities extends Context.Service()( + "LiveActivities", +) {} + +const encodeRelayAgentActivityAggregateStateJson = Schema.encodeEffect( + Schema.fromJsonString(RelayAgentActivityAggregateStateSchema), +); + +const make = Effect.gen(function* () { + const db = yield* RelayDb; + + return LiveActivities.of({ + register: Effect.fn("relay.live_activities.register")( + function* (input) { + yield* Effect.annotateCurrentSpan({ + "user.id": input.userId, + "relay.mobile.device_id": input.registration.deviceId, + }); + const updatedAt = DateTime.formatIso(yield* DateTime.now); + const registration = input.registration; + + yield* db + .update(relayLiveActivities) + .set({ + activityPushToken: null, + remoteStartQueuedAt: null, + remoteStartedAt: null, + endedAt: updatedAt, + updatedAt, + }) + .where(eq(relayLiveActivities.activityPushToken, registration.activityPushToken)); + + yield* db + .insert(relayLiveActivities) + .values({ + userId: input.userId, + deviceId: registration.deviceId, + activityPushToken: registration.activityPushToken, + remoteStartQueuedAt: null, + remoteStartedAt: updatedAt, + endedAt: null, + lastAggregateJson: null, + lastLiveActivityDeliveryAt: null, + createdAt: updatedAt, + updatedAt, + }) + .onConflictDoUpdate({ + target: [relayLiveActivities.userId, relayLiveActivities.deviceId], + set: { + activityPushToken: registration.activityPushToken, + remoteStartQueuedAt: null, + remoteStartedAt: updatedAt, + endedAt: null, + lastAggregateJson: null, + lastLiveActivityDeliveryAt: null, + updatedAt, + }, + }); + }, + Effect.mapError((cause) => new LiveActivityRegistrationPersistenceError({ cause })), + ), + + listTargets: Effect.fn("relay.live_activities.list_targets")(function* (input) { + yield* Effect.annotateCurrentSpan({ "user.id": input.userId }); + return yield* db + .select({ + device_id: relayMobileDevices.deviceId, + user_id: relayMobileDevices.userId, + platform: relayMobileDevices.platform, + ios_major_version: relayMobileDevices.iosMajorVersion, + app_version: relayMobileDevices.appVersion, + push_token: relayMobileDevices.pushToken, + push_to_start_token: relayMobileDevices.pushToStartToken, + preferences_json: relayMobileDevices.preferencesJson, + activity_push_token: relayLiveActivities.activityPushToken, + remote_start_queued_at: relayLiveActivities.remoteStartQueuedAt, + remote_started_at: relayLiveActivities.remoteStartedAt, + ended_at: relayLiveActivities.endedAt, + last_aggregate_json: relayLiveActivities.lastAggregateJson, + last_live_activity_delivery_at: relayLiveActivities.lastLiveActivityDeliveryAt, + }) + .from(relayMobileDevices) + .leftJoin( + relayLiveActivities, + and( + eq(relayLiveActivities.userId, relayMobileDevices.userId), + eq(relayLiveActivities.deviceId, relayMobileDevices.deviceId), + ), + ) + .where(eq(relayMobileDevices.userId, input.userId)) + .pipe( + Effect.flatMap((rows) => + Effect.forEach( + rows, + (row) => + Effect.all({ + preferences_json: stringifyJsonValue(row.preferences_json), + last_aggregate_json: + row.last_aggregate_json === null + ? Effect.succeed(null) + : stringifyJsonValue(row.last_aggregate_json), + }).pipe( + Effect.map((json) => ({ + ...row, + ...json, + })), + ), + { concurrency: "unbounded" }, + ), + ), + Effect.map((rows): ReadonlyArray => rows), + Effect.mapError((cause) => new LiveActivityTargetListPersistenceError({ cause })), + ); + }), + + markDelivery: Effect.fn("relay.live_activities.mark_delivery")( + function* (input) { + yield* Effect.annotateCurrentSpan({ + "user.id": input.userId, + "relay.mobile.device_id": input.deviceId, + "relay.delivery.kind": input.kind, + }); + const aggregateJson = + input.aggregate === null + ? null + : yield* parseJsonString( + yield* encodeRelayAgentActivityAggregateStateJson(input.aggregate), + ); + + yield* db + .insert(relayLiveActivities) + .values({ + userId: input.userId, + deviceId: input.deviceId, + remoteStartedAt: input.kind === "live_activity_start" ? input.deliveredAt : null, + remoteStartQueuedAt: null, + endedAt: input.kind === "live_activity_end" ? input.deliveredAt : null, + lastAggregateJson: aggregateJson, + lastLiveActivityDeliveryAt: input.deliveredAt, + createdAt: input.deliveredAt, + updatedAt: input.deliveredAt, + }) + .onConflictDoUpdate({ + target: [relayLiveActivities.userId, relayLiveActivities.deviceId], + set: { + remoteStartedAt: sql`coalesce( + ${relayLiveActivities.remoteStartedAt}, + excluded.remote_started_at + )`, + remoteStartQueuedAt: null, + endedAt: + input.kind === "live_activity_start" + ? null + : input.kind === "live_activity_end" + ? input.deliveredAt + : relayLiveActivities.endedAt, + lastAggregateJson: aggregateJson, + lastLiveActivityDeliveryAt: input.deliveredAt, + updatedAt: input.deliveredAt, + }, + }); + }, + Effect.mapError((cause) => new LiveActivityDeliveryMarkPersistenceError({ cause })), + ), + + markStartQueued: Effect.fn("relay.live_activities.mark_start_queued")(function* (input) { + yield* Effect.annotateCurrentSpan({ + "user.id": input.userId, + "relay.mobile.device_id": input.deviceId, + }); + yield* db + .insert(relayLiveActivities) + .values({ + userId: input.userId, + deviceId: input.deviceId, + remoteStartQueuedAt: input.queuedAt, + remoteStartedAt: null, + endedAt: null, + createdAt: input.queuedAt, + updatedAt: input.queuedAt, + }) + .onConflictDoUpdate({ + target: [relayLiveActivities.userId, relayLiveActivities.deviceId], + set: { + remoteStartQueuedAt: sql`coalesce( + ${relayLiveActivities.remoteStartQueuedAt}, + excluded.remote_start_queued_at + )`, + endedAt: null, + updatedAt: input.queuedAt, + }, + }) + .pipe(Effect.mapError((cause) => new LiveActivityDeliveryMarkPersistenceError({ cause }))); + }), + + clearStartQueued: Effect.fn("relay.live_activities.clear_start_queued")(function* (input) { + yield* Effect.annotateCurrentSpan({ + "user.id": input.userId, + "relay.mobile.device_id": input.deviceId, + }); + yield* db + .update(relayLiveActivities) + .set({ remoteStartQueuedAt: null }) + .where( + and( + eq(relayLiveActivities.userId, input.userId), + eq(relayLiveActivities.deviceId, input.deviceId), + ), + ) + .pipe(Effect.mapError((cause) => new LiveActivityDeliveryMarkPersistenceError({ cause }))); + }), + + invalidateDeliveryToken: Effect.fn("relay.live_activities.invalidate_delivery_token")( + function* (input) { + yield* Effect.annotateCurrentSpan({ + "user.id": input.userId, + "relay.mobile.device_id": input.deviceId, + "relay.delivery.kind": input.kind, + }); + if (input.kind === "push_notification") { + yield* db + .update(relayMobileDevices) + .set({ + pushToken: null, + updatedAt: input.invalidatedAt, + }) + .where( + and( + eq(relayMobileDevices.userId, input.userId), + eq(relayMobileDevices.deviceId, input.deviceId), + ), + ); + return; + } + + if (input.kind === "live_activity_start") { + yield* db + .update(relayMobileDevices) + .set({ + pushToStartToken: null, + updatedAt: input.invalidatedAt, + }) + .where( + and( + eq(relayMobileDevices.userId, input.userId), + eq(relayMobileDevices.deviceId, input.deviceId), + ), + ); + yield* db + .update(relayLiveActivities) + .set({ + remoteStartQueuedAt: null, + updatedAt: input.invalidatedAt, + }) + .where( + and( + eq(relayLiveActivities.userId, input.userId), + eq(relayLiveActivities.deviceId, input.deviceId), + ), + ); + return; + } + + yield* db + .update(relayLiveActivities) + .set({ + activityPushToken: null, + remoteStartQueuedAt: null, + remoteStartedAt: null, + endedAt: input.invalidatedAt, + updatedAt: input.invalidatedAt, + }) + .where( + and( + eq(relayLiveActivities.userId, input.userId), + eq(relayLiveActivities.deviceId, input.deviceId), + ), + ); + }, + Effect.mapError((cause) => new LiveActivityDeliveryMarkPersistenceError({ cause })), + ), + }); +}); + +export const layer = Layer.effect(LiveActivities, make); diff --git a/infra/relay/src/persistence/json.ts b/infra/relay/src/persistence/json.ts new file mode 100644 index 0000000000..9adaf36130 --- /dev/null +++ b/infra/relay/src/persistence/json.ts @@ -0,0 +1,10 @@ +import * as Effect from "effect/Effect"; +import * as Schema from "effect/Schema"; + +const decodeJsonString = Schema.decodeEffect(Schema.UnknownFromJsonString); +const encodeJsonValue = Schema.encodeEffect(Schema.UnknownFromJsonString); + +export const parseJsonString = (value: string) => + decodeJsonString(value).pipe(Effect.map((decoded) => decoded as A)); + +export const stringifyJsonValue = (value: unknown) => encodeJsonValue(value); diff --git a/infra/relay/src/queues.ts b/infra/relay/src/queues.ts new file mode 100644 index 0000000000..7275a8d9db --- /dev/null +++ b/infra/relay/src/queues.ts @@ -0,0 +1,7 @@ +import * as Cloudflare from "alchemy/Cloudflare"; + +export const RelayApnsDeliveryDeadLetterQueue = Cloudflare.Queue( + "RelayApnsDeliveryDeadLetterQueue", +); + +export const RelayApnsDeliveryQueue = Cloudflare.Queue("RelayApnsDeliveryQueue"); diff --git a/infra/relay/src/relayTokens.test.ts b/infra/relay/src/relayTokens.test.ts new file mode 100644 index 0000000000..c2f61e47ff --- /dev/null +++ b/infra/relay/src/relayTokens.test.ts @@ -0,0 +1,196 @@ +import * as NodeCrypto from "node:crypto"; + +import { describe, expect, it } from "vitest"; +import { signRelayJwt } from "@t3tools/shared/relayJwt"; +import * as Effect from "effect/Effect"; +import * as Redacted from "effect/Redacted"; + +import * as RelayConfiguration from "./Config.ts"; +import { + issueDpopAccessToken, + issueLinkChallengeToken, + resolveDpopAccessTokenScopes, + verifyDpopAccessToken, + verifyLinkChallengeToken, +} from "./relayTokens.ts"; + +const keyPair = NodeCrypto.generateKeyPairSync("ed25519", { + privateKeyEncoding: { format: "pem", type: "pkcs8" }, + publicKeyEncoding: { format: "pem", type: "spki" }, +}); + +const config = RelayConfiguration.RelayConfiguration.of({ + relayIssuer: "https://relay.example.test/", + apns: { + environment: "sandbox", + teamId: "team-id", + keyId: "key-id", + privateKey: Redacted.make("private-key"), + bundleId: "com.t3tools.t3code.dev", + }, + apnsDeliveryJobSigningSecret: Redacted.make("job-secret"), + clerkSecretKey: Redacted.make("clerk-secret"), + cloudMintPrivateKey: Redacted.make(keyPair.privateKey), + cloudMintPublicKey: keyPair.publicKey, + managedEndpointBaseDomain: undefined, + cloudflareAccountId: undefined, + cloudflareZoneId: undefined, + cloudflareApiToken: undefined, +}); + +describe("relay tokens", () => { + it("issues a user-bound environment link challenge", async () => { + const token = await Effect.runPromise( + issueLinkChallengeToken({ + config, + userId: "user_123", + request: { + notificationsEnabled: true, + liveActivitiesEnabled: true, + managedTunnelsEnabled: true, + }, + jti: "challenge-1", + issuedAtEpochSeconds: 100, + expiresAtEpochSeconds: 200, + }), + ); + + expect( + await Effect.runPromise( + verifyLinkChallengeToken({ + config, + token, + userId: "user_123", + request: { + notificationsEnabled: true, + liveActivitiesEnabled: true, + managedTunnelsEnabled: true, + }, + nowEpochSeconds: 150, + }), + ), + ).toMatchObject({ sub: "user_123", jti: "challenge-1" }); + expect( + await Effect.runPromise( + verifyLinkChallengeToken({ + config, + token, + userId: "attacker", + request: { + notificationsEnabled: true, + liveActivitiesEnabled: true, + managedTunnelsEnabled: true, + }, + nowEpochSeconds: 150, + }), + ), + ).toBeNull(); + }); + + it("issues and verifies DPoP access tokens bound to one proof-key thumbprint", async () => { + const token = await Effect.runPromise( + issueDpopAccessToken({ + config, + userId: "user_123", + proofKeyThumbprint: "proof-key-thumbprint", + jti: "access-token-1", + issuedAtEpochSeconds: 100, + expiresAtEpochSeconds: 200, + clientId: "t3-mobile", + scopes: ["environment:connect", "environment:status", "mobile:registration"], + }), + ); + + expect( + await Effect.runPromise(verifyDpopAccessToken({ config, token, nowEpochSeconds: 150 })), + ).toMatchObject({ + sub: "user_123", + cnf: { jkt: "proof-key-thumbprint" }, + client_id: "t3-mobile", + scope: ["environment:connect", "environment:status", "mobile:registration"], + }); + expect( + await Effect.runPromise(verifyDpopAccessToken({ config, token, nowEpochSeconds: 261 })), + ).toBeNull(); + }); + + it("issues tunnel-only DPoP access tokens to web public clients", async () => { + const token = await Effect.runPromise( + issueDpopAccessToken({ + config, + userId: "user_123", + proofKeyThumbprint: "web-proof-key-thumbprint", + jti: "web-access-token-1", + issuedAtEpochSeconds: 100, + expiresAtEpochSeconds: 200, + clientId: "t3-web", + scopes: ["environment:connect", "environment:status"], + }), + ); + + expect( + await Effect.runPromise(verifyDpopAccessToken({ config, token, nowEpochSeconds: 150 })), + ).toMatchObject({ + client_id: "t3-web", + scope: ["environment:connect", "environment:status"], + cnf: { jkt: "web-proof-key-thumbprint" }, + }); + }); + + it("treats requested scope as an order-independent set", () => { + expect( + resolveDpopAccessTokenScopes({ + clientId: "t3-mobile", + scope: "environment:status environment:connect environment:status", + }), + ).toEqual(["environment:status", "environment:connect"]); + }); + + it("rejects signed DPoP tokens whose scope is outside the relay policy", async () => { + const token = await Effect.runPromise( + signRelayJwt({ + privateKey: keyPair.privateKey, + typ: "t3-relay-dpop-access+jwt", + payload: { + iss: "https://relay.example.test", + aud: "https://relay.example.test", + sub: "user_123", + jti: "access-token-invalid-scope", + iat: 100, + exp: 200, + client_id: "t3-mobile", + scope: "environment:admin", + cnf: { jkt: "proof-key-thumbprint" }, + }, + }), + ); + + expect( + await Effect.runPromise(verifyDpopAccessToken({ config, token, nowEpochSeconds: 150 })), + ).toBeNull(); + }); + + it("rejects mobile registration scope on a web public client token", async () => { + const token = await Effect.runPromise( + signRelayJwt({ + privateKey: keyPair.privateKey, + typ: "t3-relay-dpop-access+jwt", + payload: { + iss: "https://relay.example.test", + aud: "https://relay.example.test", + sub: "user_123", + jti: "web-token-invalid-mobile-scope", + iat: 100, + exp: 200, + client_id: "t3-web", + scope: "environment:connect mobile:registration", + cnf: { jkt: "proof-key-thumbprint" }, + }, + }), + ); + + expect( + await Effect.runPromise(verifyDpopAccessToken({ config, token, nowEpochSeconds: 150 })), + ).toBeNull(); + }); +}); diff --git a/infra/relay/src/relayTokens.ts b/infra/relay/src/relayTokens.ts new file mode 100644 index 0000000000..6cef727257 --- /dev/null +++ b/infra/relay/src/relayTokens.ts @@ -0,0 +1,186 @@ +import { + RelayDpopAccessTokenScope, + RelayEnvironmentConnectScope, + RelayEnvironmentStatusScope, + RelayMobileClientId, + RelayMobileRegistrationScope, + RelayWebClientId, + type RelayPublicClientId, + type RelayEnvironmentLinkChallengeRequest, +} from "@t3tools/contracts/relay"; +import { encodeOAuthScope, parseAllowedOAuthScope } from "@t3tools/shared/oauthScope"; +import { normalizeRelayIssuer, signRelayJwt, verifyRelayJwt } from "@t3tools/shared/relayJwt"; +import * as Effect from "effect/Effect"; +import * as Redacted from "effect/Redacted"; +import * as Schema from "effect/Schema"; + +import * as RelayConfiguration from "./Config.ts"; + +const LINK_CHALLENGE_TYP = "t3-link-challenge+jwt"; +const ACCESS_TOKEN_TYP = "t3-relay-dpop-access+jwt"; +const LINK_CHALLENGE_KIND = "environment_link_challenge"; + +const LinkChallengeClaims = Schema.Struct({ + kind: Schema.Literal(LINK_CHALLENGE_KIND), + iss: Schema.String, + aud: Schema.String, + sub: Schema.String, + jti: Schema.String, + iat: Schema.Int, + exp: Schema.Int, + notificationsEnabled: Schema.Boolean, + liveActivitiesEnabled: Schema.Boolean, + managedTunnelsEnabled: Schema.Boolean, +}); +export type LinkChallengeClaims = typeof LinkChallengeClaims.Type; + +const RelayDpopAccessTokenClaims = Schema.Struct({ + iss: Schema.String, + aud: Schema.String, + sub: Schema.String, + jti: Schema.String, + iat: Schema.Int, + exp: Schema.Int, + client_id: Schema.Literals([RelayMobileClientId, RelayWebClientId]), + scope: Schema.String, + cnf: Schema.Struct({ jkt: Schema.String }), +}); +export type RelayDpopAccessTokenClaims = Omit & { + readonly scope: ReadonlyArray; +}; + +const decodeLinkChallengeClaims = Schema.decodeUnknownEffect(LinkChallengeClaims); +const decodeDpopAccessTokenClaims = Schema.decodeUnknownEffect(RelayDpopAccessTokenClaims); + +const allowedScopesByClientId: Record< + RelayPublicClientId, + ReadonlySet +> = { + [RelayMobileClientId]: new Set([ + RelayEnvironmentConnectScope, + RelayEnvironmentStatusScope, + RelayMobileRegistrationScope, + ]), + [RelayWebClientId]: new Set([RelayEnvironmentConnectScope, RelayEnvironmentStatusScope]), +}; + +export function resolveDpopAccessTokenScopes(input: { + readonly clientId: RelayPublicClientId; + readonly scope: string; +}): ReadonlyArray | null { + return parseAllowedOAuthScope({ + value: input.scope, + allowedScopes: allowedScopesByClientId[input.clientId], + }); +} + +export function issueLinkChallengeToken(input: { + readonly config: RelayConfiguration.RelayConfigurationShape; + readonly userId: string; + readonly request: RelayEnvironmentLinkChallengeRequest; + readonly jti: string; + readonly issuedAtEpochSeconds: number; + readonly expiresAtEpochSeconds: number; +}) { + const issuer = normalizeRelayIssuer(input.config.relayIssuer); + return signRelayJwt({ + privateKey: Redacted.value(input.config.cloudMintPrivateKey), + typ: LINK_CHALLENGE_TYP, + payload: { + kind: LINK_CHALLENGE_KIND, + iss: issuer, + aud: issuer, + sub: input.userId, + jti: input.jti, + iat: input.issuedAtEpochSeconds, + exp: input.expiresAtEpochSeconds, + ...input.request, + }, + }); +} + +export function verifyLinkChallengeToken(input: { + readonly config: RelayConfiguration.RelayConfigurationShape; + readonly token: string; + readonly userId: string; + readonly request: RelayEnvironmentLinkChallengeRequest; + readonly nowEpochSeconds: number; +}) { + const issuer = normalizeRelayIssuer(input.config.relayIssuer); + return verifyRelayJwt({ + publicKey: input.config.cloudMintPublicKey, + token: input.token, + typ: LINK_CHALLENGE_TYP, + issuer, + audience: issuer, + nowEpochSeconds: input.nowEpochSeconds, + }).pipe( + Effect.flatMap(decodeLinkChallengeClaims), + Effect.map((claims) => { + if ( + claims.sub !== input.userId || + (input.request.notificationsEnabled && claims.notificationsEnabled !== true) || + (input.request.liveActivitiesEnabled && claims.liveActivitiesEnabled !== true) || + (input.request.managedTunnelsEnabled && claims.managedTunnelsEnabled !== true) + ) { + return null; + } + return claims; + }), + Effect.catch(() => Effect.succeed(null)), + ); +} + +export function issueDpopAccessToken(input: { + readonly config: RelayConfiguration.RelayConfigurationShape; + readonly userId: string; + readonly proofKeyThumbprint: string; + readonly jti: string; + readonly issuedAtEpochSeconds: number; + readonly expiresAtEpochSeconds: number; + readonly clientId: RelayPublicClientId; + readonly scopes: ReadonlyArray; +}) { + const issuer = normalizeRelayIssuer(input.config.relayIssuer); + return signRelayJwt({ + privateKey: Redacted.value(input.config.cloudMintPrivateKey), + typ: ACCESS_TOKEN_TYP, + payload: { + iss: issuer, + aud: issuer, + sub: input.userId, + jti: input.jti, + iat: input.issuedAtEpochSeconds, + exp: input.expiresAtEpochSeconds, + client_id: input.clientId, + scope: encodeOAuthScope(input.scopes), + cnf: { jkt: input.proofKeyThumbprint }, + }, + }); +} + +export function verifyDpopAccessToken(input: { + readonly config: RelayConfiguration.RelayConfigurationShape; + readonly token: string; + readonly nowEpochSeconds: number; +}) { + const issuer = normalizeRelayIssuer(input.config.relayIssuer); + return verifyRelayJwt({ + publicKey: input.config.cloudMintPublicKey, + token: input.token, + typ: ACCESS_TOKEN_TYP, + issuer, + audience: issuer, + nowEpochSeconds: input.nowEpochSeconds, + }).pipe( + Effect.flatMap(decodeDpopAccessTokenClaims), + Effect.map((claims): RelayDpopAccessTokenClaims | null => { + const scopes = resolveDpopAccessTokenScopes({ + clientId: claims.client_id, + scope: claims.scope, + }); + return scopes === null ? null : { ...claims, scope: scopes }; + }), + Effect.orElseSucceed(() => null), + ); +} diff --git a/infra/relay/src/schema.ts b/infra/relay/src/schema.ts new file mode 100644 index 0000000000..eb46586957 --- /dev/null +++ b/infra/relay/src/schema.ts @@ -0,0 +1,163 @@ +import type { + RelayAgentActivityAggregateState, + RelayAgentActivityState, + RelayAgentAwarenessPreferences, +} from "@t3tools/contracts/relay"; +import { + boolean, + index, + integer, + jsonb, + pgTable, + primaryKey, + text, + uniqueIndex, + varchar, +} from "drizzle-orm/pg-core"; + +export const relayMobileDevices = pgTable( + "relay_mobile_devices", + { + userId: varchar("user_id", { length: 255 }).notNull(), + deviceId: varchar("device_id", { length: 255 }).notNull(), + platform: varchar("platform", { length: 16 }).notNull().$type<"ios">(), + iosMajorVersion: integer("ios_major_version").notNull(), + appVersion: varchar("app_version", { length: 64 }), + pushToken: text("push_token"), + pushToStartToken: text("push_to_start_token"), + preferencesJson: jsonb("preferences_json").notNull().$type(), + createdAt: varchar("created_at", { length: 64 }).notNull(), + updatedAt: varchar("updated_at", { length: 64 }).notNull(), + }, + (table) => [ + primaryKey({ columns: [table.userId, table.deviceId] }), + index("idx_relay_mobile_devices_user").on(table.userId), + uniqueIndex("idx_relay_mobile_devices_push_token").on(table.pushToken), + uniqueIndex("idx_relay_mobile_devices_push_to_start_token").on(table.pushToStartToken), + ], +); + +export const relayLiveActivities = pgTable( + "relay_live_activities", + { + userId: varchar("user_id", { length: 255 }).notNull(), + deviceId: varchar("device_id", { length: 255 }).notNull(), + activityPushToken: text("activity_push_token"), + remoteStartQueuedAt: varchar("remote_start_queued_at", { length: 64 }), + remoteStartedAt: varchar("remote_started_at", { length: 64 }), + endedAt: varchar("ended_at", { length: 64 }), + lastAggregateJson: jsonb("last_aggregate_json").$type(), + lastLiveActivityDeliveryAt: varchar("last_live_activity_delivery_at", { length: 64 }), + createdAt: varchar("created_at", { length: 64 }).notNull(), + updatedAt: varchar("updated_at", { length: 64 }).notNull(), + }, + (table) => [ + primaryKey({ columns: [table.userId, table.deviceId] }), + index("idx_relay_live_activities_user").on(table.userId), + uniqueIndex("idx_relay_live_activities_activity_push_token").on(table.activityPushToken), + ], +); + +export const relayEnvironmentLinks = pgTable( + "relay_environment_links", + { + userId: varchar("user_id", { length: 191 }).notNull(), + environmentId: varchar("environment_id", { length: 191 }).notNull(), + environmentLabel: text("environment_label").notNull().default("T3 Environment"), + environmentPublicKey: text("environment_public_key").notNull(), + endpointHttpBaseUrl: text("endpoint_http_base_url").notNull(), + endpointWsBaseUrl: text("endpoint_ws_base_url").notNull(), + endpointProviderKind: varchar("endpoint_provider_kind", { length: 32 }).notNull(), + notificationsEnabled: boolean("notifications_enabled").notNull().default(true), + liveActivitiesEnabled: boolean("live_activities_enabled").notNull().default(true), + managedTunnelsEnabled: boolean("managed_tunnels_enabled").notNull().default(false), + createdByDeviceId: varchar("created_by_device_id", { length: 191 }), + revokedAt: varchar("revoked_at", { length: 64 }), + createdAt: varchar("created_at", { length: 64 }).notNull(), + updatedAt: varchar("updated_at", { length: 64 }).notNull(), + }, + (table) => [ + primaryKey({ columns: [table.userId, table.environmentId] }), + index("idx_relay_environment_links_environment").on(table.environmentId, table.revokedAt), + ], +); + +export const relayEnvironmentCredentials = pgTable( + "relay_environment_credentials", + { + credentialId: varchar("credential_id", { length: 64 }).primaryKey(), + environmentId: varchar("environment_id", { length: 191 }).notNull(), + environmentPublicKey: text("environment_public_key").notNull(), + credentialHash: varchar("credential_hash", { length: 191 }).notNull(), + revokedAt: varchar("revoked_at", { length: 64 }), + createdAt: varchar("created_at", { length: 64 }).notNull(), + updatedAt: varchar("updated_at", { length: 64 }).notNull(), + }, + (table) => [ + uniqueIndex("idx_relay_environment_credentials_hash").on(table.credentialHash), + index("idx_relay_environment_credentials_environment").on(table.environmentId, table.revokedAt), + index("idx_relay_environment_credentials_environment_key").on( + table.environmentId, + table.environmentPublicKey, + table.revokedAt, + ), + ], +); + +export const relayAgentActivityRows = pgTable( + "relay_agent_activity_rows", + { + environmentId: varchar("environment_id", { length: 191 }).notNull(), + environmentPublicKey: text("environment_public_key").notNull(), + threadId: varchar("thread_id", { length: 191 }).notNull(), + stateJson: jsonb("state_json").notNull().$type(), + updatedAt: varchar("updated_at", { length: 64 }).notNull(), + createdAt: varchar("created_at", { length: 64 }).notNull(), + }, + (table) => [ + primaryKey({ columns: [table.environmentId, table.environmentPublicKey, table.threadId] }), + index("idx_relay_agent_activity_rows_updated").on(table.updatedAt), + ], +); + +export const relayDeliveryAttempts = pgTable( + "relay_delivery_attempts", + { + id: varchar("id", { length: 36 }).primaryKey(), + createdAt: varchar("created_at", { length: 64 }).notNull(), + userId: varchar("user_id", { length: 255 }), + environmentId: varchar("environment_id", { length: 191 }), + threadId: varchar("thread_id", { length: 191 }), + deviceId: varchar("device_id", { length: 255 }), + kind: varchar("kind", { length: 64 }).notNull(), + sourceJobId: varchar("source_job_id", { length: 64 }), + tokenSuffix: varchar("token_suffix", { length: 16 }), + apnsStatus: integer("apns_status"), + apnsReason: text("apns_reason"), + apnsId: varchar("apns_id", { length: 128 }), + transportError: text("transport_error"), + }, + (table) => [ + index("idx_relay_delivery_attempts_environment").on( + table.environmentId, + table.threadId, + table.createdAt, + ), + uniqueIndex("idx_relay_delivery_attempts_source_job").on(table.sourceJobId), + ], +); + +export const relayDpopProofs = pgTable( + "relay_dpop_proofs", + { + thumbprint: varchar("thumbprint", { length: 128 }).notNull(), + jti: varchar("jti", { length: 255 }).notNull(), + iat: integer("iat").notNull(), + expiresAt: varchar("expires_at", { length: 64 }).notNull(), + createdAt: varchar("created_at", { length: 64 }).notNull(), + }, + (table) => [ + primaryKey({ columns: [table.thumbprint, table.jti] }), + index("idx_relay_dpop_proofs_expires_at").on(table.expiresAt), + ], +); diff --git a/infra/relay/src/services/AgentActivityPublisher.test.ts b/infra/relay/src/services/AgentActivityPublisher.test.ts new file mode 100644 index 0000000000..b63b125b0b --- /dev/null +++ b/infra/relay/src/services/AgentActivityPublisher.test.ts @@ -0,0 +1,627 @@ +import type { RelayAgentActivityState, RelayDeliveryResult } from "@t3tools/contracts/relay"; +import { describe, expect, it } from "@effect/vitest"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; + +import * as AgentActivityRows from "../persistence/AgentActivityRows.ts"; +import * as EnvironmentLinks from "../persistence/EnvironmentLinks.ts"; +import * as LiveActivities from "../persistence/LiveActivities.ts"; +import * as AgentActivityPublisher from "./AgentActivityPublisher.ts"; +import * as ApnsDeliveries from "./ApnsDeliveries.ts"; + +const state: RelayAgentActivityState = { + environmentId: "env" as RelayAgentActivityState["environmentId"], + threadId: "thread" as RelayAgentActivityState["threadId"], + projectTitle: "Project", + threadTitle: "Thread", + modelTitle: "gpt-5.4", + phase: "running", + headline: "Running", + updatedAt: "1970-01-01T00:00:00.000Z", + deepLink: "/threads/env/thread", +}; + +function target(deviceId: string): LiveActivities.TargetRow { + return { + user_id: "dev:julius", + device_id: deviceId, + platform: "ios", + ios_major_version: 18, + app_version: "1.0.0", + push_token: null, + push_to_start_token: "start-token", + preferences_json: "{}", + activity_push_token: null, + remote_start_queued_at: null, + remote_started_at: null, + ended_at: null, + last_aggregate_json: null, + last_live_activity_delivery_at: null, + }; +} + +function makeLiveActivities( + overrides: Partial = {}, +): LiveActivities.LiveActivitiesShape { + return { + register: () => Effect.void, + listTargets: () => Effect.succeed([]), + markDelivery: () => Effect.void, + markStartQueued: () => Effect.void, + clearStartQueued: () => Effect.void, + invalidateDeliveryToken: () => Effect.void, + ...overrides, + }; +} + +function makeAgentActivityRows( + overrides: Partial = {}, +): AgentActivityRows.AgentActivityRowsShape { + return { + upsert: () => Effect.void, + remove: () => Effect.void, + listForUser: () => Effect.succeed([state]), + ...overrides, + }; +} + +function makeEnvironmentLinks( + overrides: Partial = {}, +): EnvironmentLinks.EnvironmentLinksShape { + return { + upsert: () => Effect.void, + listUsersForEnvironment: () => Effect.succeed(["dev:julius"]), + listDeliveryUsersForEnvironment: () => + Effect.succeed([ + { + userId: "dev:julius", + notificationsEnabled: true, + liveActivitiesEnabled: true, + }, + ]), + listPublicKeysForEnvironment: () => Effect.succeed([]), + listForUser: () => Effect.succeed([]), + getForUser: () => Effect.succeed(null), + revokeForUser: () => Effect.succeed(false), + ...overrides, + }; +} + +function makeApnsDeliveries( + overrides: Partial = {}, +): ApnsDeliveries.ApnsDeliveriesShape { + return { + sendForTarget: () => Effect.succeed(null), + sendPushNotificationForTarget: () => Effect.succeed(null), + sendLiveActivity: () => + Effect.succeed({ + deviceId: "device", + kind: "live_activity_start", + ok: true, + apnsStatus: 200, + apnsReason: null, + apnsId: "apns-id", + }), + sendPushNotification: () => + Effect.succeed({ + deviceId: "device", + kind: "push_notification", + ok: true, + apnsStatus: 200, + apnsReason: null, + apnsId: "apns-id", + }), + processSignedJob: () => + Effect.succeed({ + deviceId: "device", + kind: "live_activity_start", + ok: true, + apnsStatus: 200, + apnsReason: null, + apnsId: "apns-id", + }), + ...overrides, + }; +} + +describe("AgentActivityPublisher", () => { + it.effect("replays the latest aggregate when a Live Activity token registers", () => { + const registeredTarget: LiveActivities.TargetRow = { + ...target("device-1"), + push_to_start_token: null, + activity_push_token: "activity-token", + remote_start_queued_at: null, + remote_started_at: "1970-01-01T00:00:01.000Z", + }; + const sent: Array[0]> = []; + const deliveryResult: RelayDeliveryResult = { + deviceId: "device-1", + kind: "live_activity_update", + ok: true, + apnsStatus: null, + apnsReason: null, + apnsId: "queued", + }; + + return Effect.gen(function* () { + const result = yield* Effect.gen(function* () { + const publisher = yield* AgentActivityPublisher.AgentActivityPublisher; + return yield* publisher.replayForLiveActivityRegistration({ + userId: "dev:julius", + deviceId: "device-1", + }); + }).pipe( + Effect.provide( + AgentActivityPublisher.layer.pipe( + Layer.provide( + Layer.mergeAll( + Layer.succeed(AgentActivityRows.AgentActivityRows, makeAgentActivityRows()), + Layer.succeed(EnvironmentLinks.EnvironmentLinks, makeEnvironmentLinks()), + Layer.succeed( + LiveActivities.LiveActivities, + makeLiveActivities({ + listTargets: () => Effect.succeed([registeredTarget, target("device-2")]), + }), + ), + Layer.succeed( + ApnsDeliveries.ApnsDeliveries, + makeApnsDeliveries({ + sendForTarget: (input) => + Effect.sync(() => { + sent.push(input); + return deliveryResult; + }), + }), + ), + ), + ), + ), + ), + ); + + expect(result).toEqual(deliveryResult); + expect(sent).toHaveLength(1); + expect(sent[0]?.target.device_id).toBe("device-1"); + expect(sent[0]?.aggregate).toMatchObject({ + activeCount: 1, + activities: [ + { + environmentId: state.environmentId, + threadId: state.threadId, + status: "Working", + }, + ], + }); + }); + }); + + it.effect("publishes listed targets through the APNs delivery service", () => { + const firstTarget = target("device-1"); + const secondTarget = target("device-2"); + const deliveryResult: RelayDeliveryResult = { + deviceId: "device-1", + kind: "live_activity_start", + ok: true, + apnsStatus: 200, + apnsReason: null, + apnsId: "apns-id", + }; + const sentTargets: Array = []; + const deliveryLookups: Array<{ + readonly environmentId: string; + readonly environmentPublicKey: string; + }> = []; + const upserts: Array[0]> = []; + + return Effect.gen(function* () { + const result = yield* Effect.gen(function* () { + const publisher = yield* AgentActivityPublisher.AgentActivityPublisher; + return yield* publisher.publish({ + environmentId: "env", + environmentPublicKey: "environment-public-key", + threadId: "thread", + state, + }); + }).pipe( + Effect.provide( + AgentActivityPublisher.layer.pipe( + Layer.provide( + Layer.mergeAll( + Layer.succeed( + AgentActivityRows.AgentActivityRows, + makeAgentActivityRows({ + upsert: (input) => + Effect.sync(() => { + upserts.push(input); + }), + }), + ), + Layer.succeed( + EnvironmentLinks.EnvironmentLinks, + makeEnvironmentLinks({ + listDeliveryUsersForEnvironment: (input) => + Effect.sync(() => { + deliveryLookups.push(input); + return [ + { + userId: "dev:julius", + notificationsEnabled: true, + liveActivitiesEnabled: true, + }, + ]; + }), + }), + ), + Layer.succeed( + LiveActivities.LiveActivities, + makeLiveActivities({ + listTargets: () => Effect.succeed([firstTarget, secondTarget]), + }), + ), + Layer.succeed( + ApnsDeliveries.ApnsDeliveries, + makeApnsDeliveries({ + sendForTarget: (input) => + Effect.sync(() => { + sentTargets.push(input.target.device_id); + return input.target.device_id === "device-1" ? deliveryResult : null; + }), + }), + ), + ), + ), + ), + ), + ); + + expect(sentTargets).toEqual(["device-1", "device-2"]); + expect(deliveryLookups).toEqual([ + { + environmentId: "env", + environmentPublicKey: "environment-public-key", + }, + ]); + expect(upserts).toMatchObject([ + { + environmentPublicKey: "environment-public-key", + state: { + environmentId: "env", + threadId: "thread", + }, + }, + ]); + expect(result).toEqual({ ok: true, deliveries: [deliveryResult] }); + }); + }); + + it.effect("ends the last remote Live Activity with a terminal content state", () => { + const completedState: RelayAgentActivityState = { + ...state, + phase: "completed", + headline: "Done", + updatedAt: "1970-01-01T00:00:10.000Z", + }; + const sentAggregates: Array< + Parameters[0] + > = []; + const removals: Array[0]> = []; + + return Effect.gen(function* () { + const result = yield* Effect.gen(function* () { + const publisher = yield* AgentActivityPublisher.AgentActivityPublisher; + return yield* publisher.publish({ + environmentId: "env", + environmentPublicKey: "environment-public-key", + threadId: "thread", + state: completedState, + }); + }).pipe( + Effect.provide( + AgentActivityPublisher.layer.pipe( + Layer.provide( + Layer.mergeAll( + Layer.succeed( + AgentActivityRows.AgentActivityRows, + makeAgentActivityRows({ + remove: (input) => + Effect.sync(() => { + removals.push(input); + }), + listForUser: () => Effect.succeed([]), + }), + ), + Layer.succeed(EnvironmentLinks.EnvironmentLinks, makeEnvironmentLinks()), + Layer.succeed( + LiveActivities.LiveActivities, + makeLiveActivities({ + listTargets: () => + Effect.succeed([ + { + ...target("device-1"), + push_to_start_token: null, + activity_push_token: "activity-token", + remote_started_at: "1970-01-01T00:00:00.000Z", + }, + ]), + }), + ), + Layer.succeed( + ApnsDeliveries.ApnsDeliveries, + makeApnsDeliveries({ + sendForTarget: (input) => + Effect.sync(() => { + sentAggregates.push(input); + return { + deviceId: input.target.device_id, + kind: "live_activity_end", + ok: true, + apnsStatus: null, + apnsReason: null, + apnsId: "queued", + }; + }), + }), + ), + ), + ), + ), + ), + ); + + expect(result.deliveries).toMatchObject([ + { + deviceId: "device-1", + kind: "live_activity_end", + ok: true, + }, + ]); + expect(removals).toEqual([ + { + environmentId: "env", + environmentPublicKey: "environment-public-key", + threadId: "thread", + }, + ]); + expect(sentAggregates).toHaveLength(1); + expect(sentAggregates[0]?.aggregate).toMatchObject({ + activeCount: 0, + subtitle: "Agent work completed", + activities: [ + { + environmentId: completedState.environmentId, + threadId: completedState.threadId, + phase: "completed", + status: "Done", + }, + ], + }); + }); + }); + + it.effect("queues push notifications for notification-only environment links", () => { + const notificationState: RelayAgentActivityState = { + ...state, + phase: "waiting_for_input", + headline: "Needs input", + }; + const liveAggregates: Array< + Parameters[0] + > = []; + const pushAggregates: Array< + Parameters[0] + > = []; + + return Effect.gen(function* () { + const result = yield* Effect.gen(function* () { + const publisher = yield* AgentActivityPublisher.AgentActivityPublisher; + return yield* publisher.publish({ + environmentId: "env", + environmentPublicKey: "environment-public-key", + threadId: "thread", + state: notificationState, + }); + }).pipe( + Effect.provide( + AgentActivityPublisher.layer.pipe( + Layer.provide( + Layer.mergeAll( + Layer.succeed( + AgentActivityRows.AgentActivityRows, + makeAgentActivityRows({ + listForUser: () => Effect.succeed([]), + }), + ), + Layer.succeed( + EnvironmentLinks.EnvironmentLinks, + makeEnvironmentLinks({ + listDeliveryUsersForEnvironment: () => + Effect.succeed([ + { + userId: "dev:julius", + notificationsEnabled: true, + liveActivitiesEnabled: false, + }, + ]), + }), + ), + Layer.succeed( + LiveActivities.LiveActivities, + makeLiveActivities({ + listTargets: () => + Effect.succeed([ + { + ...target("device-1"), + push_token: "apns-device-token", + push_to_start_token: null, + }, + ]), + }), + ), + Layer.succeed( + ApnsDeliveries.ApnsDeliveries, + makeApnsDeliveries({ + sendForTarget: (input) => + Effect.sync(() => { + liveAggregates.push(input); + return null; + }), + sendPushNotificationForTarget: (input) => + Effect.sync(() => { + pushAggregates.push(input); + return { + deviceId: input.target.device_id, + kind: "push_notification", + ok: true, + queued: true, + apnsStatus: null, + apnsReason: null, + apnsId: null, + }; + }), + }), + ), + ), + ), + ), + ), + ); + + expect(liveAggregates).toMatchObject([{ aggregate: null }]); + expect(pushAggregates).toHaveLength(1); + expect(pushAggregates[0]?.aggregate).toMatchObject({ + activeCount: 1, + activities: [ + { + phase: "waiting_for_input", + status: "Input", + threadId: notificationState.threadId, + }, + ], + }); + expect(result.deliveries).toMatchObject([ + { + deviceId: "device-1", + kind: "push_notification", + queued: true, + }, + ]); + }); + }); + + it.effect( + "does not build Live Activity aggregates for links with Live Activities disabled", + () => { + const notificationState: RelayAgentActivityState = { + ...state, + phase: "waiting_for_approval", + headline: "Needs approval", + }; + const liveAggregates: Array< + Parameters[0] + > = []; + const pushAggregates: Array< + Parameters[0] + > = []; + + return Effect.gen(function* () { + const result = yield* Effect.gen(function* () { + const publisher = yield* AgentActivityPublisher.AgentActivityPublisher; + return yield* publisher.publish({ + environmentId: "env", + environmentPublicKey: "environment-public-key", + threadId: "thread", + state: notificationState, + }); + }).pipe( + Effect.provide( + AgentActivityPublisher.layer.pipe( + Layer.provide( + Layer.mergeAll( + Layer.succeed( + AgentActivityRows.AgentActivityRows, + makeAgentActivityRows({ + listForUser: () => + Effect.succeed([ + { + ...state, + environmentId: "other-env" as RelayAgentActivityState["environmentId"], + threadId: "other-thread" as RelayAgentActivityState["threadId"], + }, + ]), + }), + ), + Layer.succeed( + EnvironmentLinks.EnvironmentLinks, + makeEnvironmentLinks({ + listDeliveryUsersForEnvironment: () => + Effect.succeed([ + { + userId: "dev:julius", + notificationsEnabled: true, + liveActivitiesEnabled: false, + }, + ]), + }), + ), + Layer.succeed( + LiveActivities.LiveActivities, + makeLiveActivities({ + listTargets: () => + Effect.succeed([ + { + ...target("device-1"), + push_token: "apns-device-token", + push_to_start_token: "push-to-start-token", + }, + ]), + }), + ), + Layer.succeed( + ApnsDeliveries.ApnsDeliveries, + makeApnsDeliveries({ + sendForTarget: (input) => + Effect.sync(() => { + liveAggregates.push(input); + return null; + }), + sendPushNotificationForTarget: (input) => + Effect.sync(() => { + pushAggregates.push(input); + return { + deviceId: input.target.device_id, + kind: "push_notification", + ok: true, + queued: true, + apnsStatus: null, + apnsReason: null, + apnsId: null, + }; + }), + }), + ), + ), + ), + ), + ), + ); + + expect(liveAggregates).toMatchObject([{ aggregate: null }]); + expect(pushAggregates).toHaveLength(1); + expect(pushAggregates[0]?.aggregate?.activities).toMatchObject([ + { + environmentId: notificationState.environmentId, + threadId: notificationState.threadId, + phase: "waiting_for_approval", + }, + ]); + expect(result.deliveries).toMatchObject([ + { + deviceId: "device-1", + kind: "push_notification", + queued: true, + }, + ]); + }); + }, + ); +}); diff --git a/infra/relay/src/services/AgentActivityPublisher.ts b/infra/relay/src/services/AgentActivityPublisher.ts new file mode 100644 index 0000000000..e2e53f2cdd --- /dev/null +++ b/infra/relay/src/services/AgentActivityPublisher.ts @@ -0,0 +1,234 @@ +import type { + RelayAgentActivityAggregateState, + RelayAgentActivityState, + RelayDeliveryResult, + RelayPublishResponse, +} from "@t3tools/contracts/relay"; +import * as Context from "effect/Context"; +import * as DateTime from "effect/DateTime"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; + +import { sanitizeAgentActivityAggregateState } from "../agentActivityPayloads.ts"; +import * as AgentActivityRows from "../persistence/AgentActivityRows.ts"; +import * as EnvironmentLinks from "../persistence/EnvironmentLinks.ts"; +import * as LiveActivities from "../persistence/LiveActivities.ts"; +import { withUserId } from "../telemetry.ts"; +import * as ApnsDeliveries from "./ApnsDeliveries.ts"; + +export type AgentActivityPublishError = + | AgentActivityRows.AgentActivityRowUpsertPersistenceError + | AgentActivityRows.AgentActivityRowDeletePersistenceError + | AgentActivityRows.AgentActivityRowListPersistenceError + | EnvironmentLinks.EnvironmentLinkUserListPersistenceError + | LiveActivities.LiveActivityTargetListPersistenceError + | ApnsDeliveries.ApnsDeliveryError; + +export interface AgentActivityPublisherShape { + readonly publish: (input: { + readonly environmentId: string; + readonly environmentPublicKey: string; + readonly threadId: string; + readonly state: RelayAgentActivityState | null; + }) => Effect.Effect; + readonly replayForLiveActivityRegistration: (input: { + readonly userId: string; + readonly deviceId: string; + }) => Effect.Effect; +} + +export class AgentActivityPublisher extends Context.Service< + AgentActivityPublisher, + AgentActivityPublisherShape +>()("AgentActivityPublisher") {} + +const make = Effect.gen(function* () { + const rows = yield* AgentActivityRows.AgentActivityRows; + const links = yield* EnvironmentLinks.EnvironmentLinks; + const liveActivities = yield* LiveActivities.LiveActivities; + const apnsDeliveries = yield* ApnsDeliveries.ApnsDeliveries; + + const publishForDeliveryUser = Effect.fnUntraced(function* (input: { + readonly deliveryUser: EnvironmentLinks.AgentAwarenessDeliveryUserRecord; + readonly state: RelayAgentActivityState | null; + readonly nowMs: number; + }) { + const activeStates = yield* rows.listForUser({ userId: input.deliveryUser.userId }); + const liveActivityAggregate = input.deliveryUser.liveActivitiesEnabled + ? makeAggregateState({ + activeStates, + terminalState: input.state && isTerminalPhase(input.state) ? input.state : null, + }) + : null; + const notificationOnlyAggregate = + input.deliveryUser.notificationsEnabled && + !input.deliveryUser.liveActivitiesEnabled && + input.state !== null + ? makeAggregateState({ + activeStates: isTerminalPhase(input.state) ? [] : [input.state], + terminalState: isTerminalPhase(input.state) ? input.state : null, + }) + : null; + const targets = yield* liveActivities.listTargets({ userId: input.deliveryUser.userId }); + const deliveriesByTarget = yield* Effect.forEach( + targets, + (target) => + Effect.all( + [ + apnsDeliveries.sendForTarget({ + target, + aggregate: liveActivityAggregate, + nowMs: input.nowMs, + }), + notificationOnlyAggregate === null + ? Effect.succeed(null) + : apnsDeliveries.sendPushNotificationForTarget({ + target, + aggregate: notificationOnlyAggregate, + }), + ], + { concurrency: 2 }, + ), + { concurrency: 4 }, + ); + return deliveriesByTarget.flat(); + }); + + return AgentActivityPublisher.of({ + replayForLiveActivityRegistration: Effect.fn( + "relay.agent_activity_publisher.replay_for_live_activity_registration", + )( + function* (input) { + yield* Effect.annotateCurrentSpan({ + "relay.mobile.device_id": input.deviceId, + "relay.operation": "replayForLiveActivityRegistration", + }); + const activeStates = yield* rows.listForUser({ userId: input.userId }); + const targets = yield* liveActivities.listTargets({ userId: input.userId }); + const target = targets.find((row) => row.device_id === input.deviceId) ?? null; + if (target === null) { + return null; + } + const aggregate = makeAggregateState({ activeStates, terminalState: null }); + const now = yield* DateTime.now; + return yield* apnsDeliveries.sendForTarget({ + target, + aggregate, + nowMs: now.epochMilliseconds, + }); + }, + (effect, input) => effect.pipe(withUserId(input.userId)), + ), + publish: Effect.fn("relay.agent_activity_publisher.publish")(function* (input) { + yield* Effect.annotateCurrentSpan({ + "relay.environment_id": input.environmentId, + "relay.thread_id": input.threadId, + "relay.agent_activity.phase": input.state?.phase ?? "deleted", + }); + if (input.state && !isTerminalPhase(input.state)) { + yield* rows.upsert({ + environmentPublicKey: input.environmentPublicKey, + state: input.state, + }); + } else { + yield* rows.remove({ + environmentId: input.environmentId, + environmentPublicKey: input.environmentPublicKey, + threadId: input.threadId, + }); + } + + const deliveryUsers = yield* links.listDeliveryUsersForEnvironment({ + environmentId: input.environmentId, + environmentPublicKey: input.environmentPublicKey, + }); + const now = yield* DateTime.now; + const deliveriesByUser = yield* Effect.forEach( + deliveryUsers, + (deliveryUser) => + publishForDeliveryUser({ + deliveryUser, + state: input.state, + nowMs: now.epochMilliseconds, + }).pipe(withUserId(deliveryUser.userId)), + { concurrency: 4 }, + ); + const deliveries = deliveriesByUser.flat(); + return { + ok: true, + deliveries: deliveries.filter( + (delivery): delivery is RelayDeliveryResult => delivery !== null, + ), + }; + }), + }); +}); + +function statusForPhase(phase: RelayAgentActivityState["phase"]): string { + switch (phase) { + case "waiting_for_approval": + return "Approval"; + case "waiting_for_input": + return "Input"; + case "completed": + return "Done"; + case "failed": + return "Failed"; + case "starting": + return "Starting"; + case "running": + return "Working"; + case "stale": + return "Waiting"; + } +} + +function isTerminalPhase(state: RelayAgentActivityState): boolean { + return state.phase === "completed" || state.phase === "failed"; +} + +function aggregateRowForState(state: RelayAgentActivityState) { + return { + environmentId: state.environmentId, + threadId: state.threadId, + projectTitle: state.projectTitle, + threadTitle: state.threadTitle, + modelTitle: state.modelTitle, + phase: state.phase, + status: statusForPhase(state.phase), + updatedAt: state.updatedAt, + deepLink: state.deepLink, + }; +} + +function terminalAggregateState(state: RelayAgentActivityState): RelayAgentActivityAggregateState { + return sanitizeAgentActivityAggregateState({ + title: "T3 Code", + subtitle: state.phase === "failed" ? "Agent work failed" : "Agent work completed", + activeCount: 0, + updatedAt: state.updatedAt, + activities: [aggregateRowForState(state)], + }); +} + +function makeAggregateState(input: { + readonly activeStates: ReadonlyArray; + readonly terminalState: RelayAgentActivityState | null; +}): RelayAgentActivityAggregateState | null { + const activeStates = input.activeStates.filter((state) => !isTerminalPhase(state)); + if (activeStates.length === 0) { + return input.terminalState === null ? null : terminalAggregateState(input.terminalState); + } + const updatedAt = activeStates.reduce((latest, state) => + state.updatedAt.localeCompare(latest.updatedAt) > 0 ? state : latest, + ).updatedAt; + return sanitizeAgentActivityAggregateState({ + title: "T3 Code", + subtitle: "Agent work in progress", + activeCount: activeStates.length, + updatedAt, + activities: activeStates.slice(0, 3).map(aggregateRowForState), + }); +} + +export const layer = Layer.effect(AgentActivityPublisher, make); diff --git a/infra/relay/src/services/ApnsDeliveries.test.ts b/infra/relay/src/services/ApnsDeliveries.test.ts new file mode 100644 index 0000000000..e099557089 --- /dev/null +++ b/infra/relay/src/services/ApnsDeliveries.test.ts @@ -0,0 +1,1126 @@ +import type { + RelayAgentActivityAggregateState, + RelayAgentActivityState, +} from "@t3tools/contracts/relay"; +import * as NodeCryptoLayer from "@effect/platform-node/NodeCrypto"; +import { describe, expect, it } from "@effect/vitest"; +import * as NodeCrypto from "node:crypto"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import * as Redacted from "effect/Redacted"; +import { + FetchHttpClient, + HttpClient, + HttpClientRequest, + HttpClientResponse, +} from "effect/unstable/http"; + +import { + makeApnsDeliveryJobPayload, + signApnsDeliveryJob, + type SignedApnsDeliveryJob, +} from "../apnsDeliveryJobs.ts"; +import * as DeliveryAttempts from "../persistence/DeliveryAttempts.ts"; +import * as LiveActivities from "../persistence/LiveActivities.ts"; +import * as RelayConfiguration from "../Config.ts"; +import * as ApnsDeliveryQueue from "./ApnsDeliveryQueue.ts"; +import * as ApnsDeliveries from "./ApnsDeliveries.ts"; + +const config = RelayConfiguration.RelayConfiguration.of({ + relayIssuer: "https://relay.example.test", + apns: { + environment: "sandbox", + teamId: "team-id", + keyId: "key-id", + privateKey: Redacted.make("not-a-private-key"), + bundleId: "com.t3tools.t3code.dev", + }, + apnsDeliveryJobSigningSecret: Redacted.make("job-signing-secret"), + clerkSecretKey: Redacted.make("clerk-secret"), + cloudMintPrivateKey: Redacted.make("cloud-private-key"), + cloudMintPublicKey: "cloud-public-key", + managedEndpointBaseDomain: undefined, + cloudflareAccountId: undefined, + cloudflareZoneId: undefined, + cloudflareApiToken: undefined, +}); + +const apnsSigningKeyPair = NodeCrypto.generateKeyPairSync("ec", { + namedCurve: "P-256", + privateKeyEncoding: { format: "pem", type: "pkcs8" }, + publicKeyEncoding: { format: "pem", type: "spki" }, +}); + +const signingConfig = RelayConfiguration.RelayConfiguration.of({ + ...config, + apns: { + ...config.apns, + privateKey: Redacted.make(apnsSigningKeyPair.privateKey), + }, +}); + +const state: RelayAgentActivityState = { + environmentId: "env" as RelayAgentActivityState["environmentId"], + threadId: "thread" as RelayAgentActivityState["threadId"], + projectTitle: "Project", + threadTitle: "Thread", + modelTitle: "gpt-5.4", + phase: "running", + headline: "Running", + updatedAt: "1970-01-01T00:00:00.000Z", + deepLink: "/", +}; + +const aggregate: RelayAgentActivityAggregateState = { + title: "T3 Code", + subtitle: "Agent work in progress", + activeCount: 1, + updatedAt: state.updatedAt, + activities: [ + { + environmentId: state.environmentId, + threadId: state.threadId, + projectTitle: state.projectTitle, + threadTitle: state.threadTitle, + modelTitle: state.modelTitle, + phase: state.phase, + status: "Working", + updatedAt: state.updatedAt, + deepLink: state.deepLink, + }, + ], +}; + +const enabledPreferences = JSON.stringify({ + liveActivitiesEnabled: true, + notificationsEnabled: true, + notifyOnApproval: true, + notifyOnInput: true, + notifyOnCompletion: true, + notifyOnFailure: true, +}); + +const disabledPreferences = JSON.stringify({ + liveActivitiesEnabled: false, + notificationsEnabled: true, + notifyOnApproval: true, + notifyOnInput: true, + notifyOnCompletion: true, + notifyOnFailure: true, +}); + +const notificationsDisabledPreferences = JSON.stringify({ + liveActivitiesEnabled: false, + notificationsEnabled: false, + notifyOnApproval: true, + notifyOnInput: true, + notifyOnCompletion: true, + notifyOnFailure: true, +}); + +const target: LiveActivities.TargetRow = { + user_id: "dev:julius", + device_id: "device-1", + platform: "ios", + ios_major_version: 18, + app_version: "1.0.0", + push_token: null, + push_to_start_token: "start-token", + preferences_json: enabledPreferences, + activity_push_token: "activity-token", + remote_start_queued_at: null, + remote_started_at: "1970-01-01T00:00:00.000Z", + ended_at: null, + last_aggregate_json: null, + last_live_activity_delivery_at: null, +}; + +function makeLayer(input: { + readonly attempts: Array; + readonly sourceJobClaims?: ReadonlyMap; + readonly queuedJobs?: Array; + readonly queuedStarts?: Array< + Parameters[0] + >; + readonly clearedStarts?: Array< + Parameters[0] + >; + readonly markedDeliveries?: Array< + Parameters[0] + >; + readonly invalidatedTokens?: Array< + Parameters[0] + >; + readonly currentTargets?: ReadonlyArray; + readonly config?: RelayConfiguration.RelayConfigurationShape; + readonly execute?: ( + request: HttpClientRequest.HttpClientRequest, + ) => Effect.Effect; +}) { + return ApnsDeliveries.layer.pipe( + Layer.provide(ApnsDeliveryQueue.layer.pipe(Layer.provide(NodeCryptoLayer.layer))), + Layer.provide( + Layer.mergeAll( + Layer.succeed(ApnsDeliveryQueue.ApnsDeliveryQueueSender, { + send: (body) => + Effect.sync(() => { + input.queuedJobs?.push(body); + }), + }), + Layer.succeed(DeliveryAttempts.DeliveryAttempts, { + record: (attempt) => + Effect.sync(() => { + input.attempts.push(attempt); + }), + claimSourceJob: (attempt) => + Effect.sync(() => { + const claim = input.sourceJobClaims?.get(attempt.sourceJobId); + if (claim) { + return claim; + } + input.attempts.push(attempt); + return "claimed"; + }), + completeSourceJob: (completion) => + Effect.sync(() => { + const attempt = input.attempts.find( + (row) => row.sourceJobId === completion.sourceJobId, + ); + if (attempt) { + Object.assign(attempt, completion); + } + }), + }), + Layer.succeed(LiveActivities.LiveActivities, { + register: () => Effect.void, + listTargets: () => Effect.succeed(input.currentTargets ?? [target]), + markStartQueued: (queued) => + Effect.sync(() => { + input.queuedStarts?.push(queued); + }), + clearStartQueued: (cleared) => + Effect.sync(() => { + input.clearedStarts?.push(cleared); + }), + markDelivery: (delivery) => + Effect.sync(() => { + input.markedDeliveries?.push(delivery); + }), + invalidateDeliveryToken: (invalidated) => + Effect.sync(() => { + input.invalidatedTokens?.push(invalidated); + }), + }), + Layer.succeed(RelayConfiguration.RelayConfiguration, input.config ?? config), + input.execute + ? Layer.succeed(HttpClient.HttpClient, HttpClient.make(input.execute)) + : FetchHttpClient.layer, + ), + ), + ); +} + +describe("ApnsDeliveries", () => { + it.effect("queues a restart using the push-to-start token", () => { + const attempts: Array = []; + const queuedJobs: Array = []; + const queuedStarts: Array< + Parameters[0] + > = []; + const markedDeliveries: Array< + Parameters[0] + > = []; + + return Effect.gen(function* () { + const deliveries = yield* ApnsDeliveries.ApnsDeliveries; + const result = yield* deliveries.sendForTarget({ + target: { + ...target, + ended_at: "1970-01-01T00:00:05.000Z", + }, + aggregate, + nowMs: 10_000, + }); + + expect(result?.kind).toBe("live_activity_start"); + expect(result?.ok).toBe(true); + expect(queuedJobs).toMatchObject([ + { + payload: { + kind: "live_activity_start", + target: { + token: "start-token", + }, + }, + }, + ]); + expect(attempts).toEqual([]); + expect(queuedStarts).toMatchObject([ + { + userId: target.user_id, + deviceId: target.device_id, + }, + ]); + expect(markedDeliveries).toEqual([]); + }).pipe(Effect.provide(makeLayer({ attempts, queuedJobs, queuedStarts, markedDeliveries }))); + }); + + it.effect("queues an end using the activity token", () => { + const attempts: Array = []; + const queuedJobs: Array = []; + + return Effect.gen(function* () { + const deliveries = yield* ApnsDeliveries.ApnsDeliveries; + const result = yield* deliveries.sendForTarget({ + target, + aggregate: null, + nowMs: 5_000, + }); + + expect(result?.kind).toBe("live_activity_end"); + expect(result?.ok).toBe(true); + expect(queuedJobs).toMatchObject([ + { + payload: { + kind: "live_activity_end", + target: { + token: "activity-token", + }, + }, + }, + ]); + expect(attempts).toEqual([]); + }).pipe(Effect.provide(makeLayer({ attempts, queuedJobs }))); + }); + + it.effect("does not queue a remote start when Live Activities are disabled", () => { + const attempts: Array = []; + const queuedJobs: Array = []; + + return Effect.gen(function* () { + const deliveries = yield* ApnsDeliveries.ApnsDeliveries; + const result = yield* deliveries.sendForTarget({ + target: { + ...target, + activity_push_token: null, + remote_started_at: null, + ended_at: null, + preferences_json: disabledPreferences, + }, + aggregate, + nowMs: 5_000, + }); + + expect(result).toBeNull(); + expect(queuedJobs).toEqual([]); + expect(attempts).toEqual([]); + }).pipe(Effect.provide(makeLayer({ attempts, queuedJobs }))); + }); + + it.effect("does not queue a duplicate remote start while a start is already queued", () => { + const attempts: Array = []; + const queuedJobs: Array = []; + + return Effect.gen(function* () { + const deliveries = yield* ApnsDeliveries.ApnsDeliveries; + const result = yield* deliveries.sendForTarget({ + target: { + ...target, + activity_push_token: null, + remote_start_queued_at: "1970-01-01T00:00:03.000Z", + remote_started_at: null, + ended_at: null, + }, + aggregate, + nowMs: 5_000, + }); + + expect(result).toBeNull(); + expect(queuedJobs).toEqual([]); + expect(attempts).toEqual([]); + }).pipe(Effect.provide(makeLayer({ attempts, queuedJobs }))); + }); + + it.effect("queues bounded Live Activity aggregate payloads", () => { + const attempts: Array = []; + const queuedJobs: Array = []; + const longTitle = "x".repeat(300); + const inputAggregate: RelayAgentActivityAggregateState = { + ...aggregate, + title: longTitle, + subtitle: longTitle, + activities: [0, 1, 2, 3].map((index) => + Object.assign({}, aggregate.activities[0]!, { + projectTitle: longTitle, + threadTitle: longTitle, + modelTitle: longTitle, + status: longTitle, + threadId: `thread-${index}` as RelayAgentActivityState["threadId"], + deepLink: "https://example.test/not-an-app-link", + }), + ), + }; + + return Effect.gen(function* () { + const deliveries = yield* ApnsDeliveries.ApnsDeliveries; + yield* deliveries.sendForTarget({ + target: { + ...target, + activity_push_token: null, + remote_started_at: null, + ended_at: "1970-01-01T00:00:05.000Z", + }, + aggregate: inputAggregate, + nowMs: 10_000, + }); + + const payloadAggregate = queuedJobs[0]?.payload.aggregate; + expect(payloadAggregate?.title.length).toBeLessThanOrEqual(120); + expect(payloadAggregate?.subtitle.length).toBeLessThanOrEqual(120); + expect(payloadAggregate?.activities).toHaveLength(3); + expect(payloadAggregate?.activities[0]?.projectTitle.length).toBeLessThanOrEqual(120); + expect(payloadAggregate?.activities[0]?.status.length).toBeLessThanOrEqual(40); + expect(payloadAggregate?.activities[0]?.deepLink).toBe("/"); + expect(attempts).toEqual([]); + }).pipe(Effect.provide(makeLayer({ attempts, queuedJobs }))); + }); + + it.effect("queues an end for an active Live Activity when Live Activities are disabled", () => { + const attempts: Array = []; + const queuedJobs: Array = []; + + return Effect.gen(function* () { + const deliveries = yield* ApnsDeliveries.ApnsDeliveries; + const result = yield* deliveries.sendForTarget({ + target: { + ...target, + preferences_json: disabledPreferences, + }, + aggregate, + nowMs: 5_000, + }); + + expect(result?.kind).toBe("live_activity_end"); + expect(queuedJobs).toMatchObject([ + { + payload: { + kind: "live_activity_end", + target: { + token: "activity-token", + }, + }, + }, + ]); + expect(attempts).toEqual([]); + }).pipe(Effect.provide(makeLayer({ attempts, queuedJobs }))); + }); + + it.effect( + "queues an alert while ending an active Live Activity when only Live Activities are disabled", + () => { + const attempts: Array = []; + const queuedJobs: Array = []; + const inputAggregate: RelayAgentActivityAggregateState = { + ...aggregate, + activities: [ + { + ...aggregate.activities[0]!, + phase: "waiting_for_input", + status: "Input", + }, + ], + }; + + return Effect.gen(function* () { + const deliveries = yield* ApnsDeliveries.ApnsDeliveries; + const result = yield* deliveries.sendForTarget({ + target: { + ...target, + push_token: "apns-device-token", + preferences_json: disabledPreferences, + }, + aggregate: inputAggregate, + nowMs: 5_000, + }); + + expect(result?.kind).toBe("live_activity_end"); + expect(queuedJobs).toMatchObject([ + { + payload: { + kind: "live_activity_end", + target: { + token: "activity-token", + }, + }, + }, + { + payload: { + kind: "push_notification", + target: { + token: "apns-device-token", + }, + notification: { + title: "Thread", + body: "Input: Project", + environmentId: "env", + threadId: "thread", + deepLink: "/", + }, + }, + }, + ]); + expect(attempts).toEqual([]); + }).pipe(Effect.provide(makeLayer({ attempts, queuedJobs }))); + }, + ); + + it.effect("does not queue alert pushes when notification permission is disabled", () => { + const attempts: Array = []; + const queuedJobs: Array = []; + const inputAggregate: RelayAgentActivityAggregateState = { + ...aggregate, + activities: [ + { + ...aggregate.activities[0]!, + phase: "waiting_for_input", + status: "Input", + }, + ], + }; + + return Effect.gen(function* () { + const deliveries = yield* ApnsDeliveries.ApnsDeliveries; + const result = yield* deliveries.sendForTarget({ + target: { + ...target, + push_token: "apns-device-token", + preferences_json: notificationsDisabledPreferences, + }, + aggregate: inputAggregate, + nowMs: 5_000, + }); + + expect(result?.kind).toBe("live_activity_end"); + expect(queuedJobs).toMatchObject([ + { + payload: { + kind: "live_activity_end", + target: { + token: "activity-token", + }, + }, + }, + ]); + expect(attempts).toEqual([]); + }).pipe(Effect.provide(makeLayer({ attempts, queuedJobs }))); + }); + + it.effect( + "queues a push notification for approval and input states when no Live Activity delivery is available", + () => { + const attempts: Array = []; + const queuedJobs: Array = []; + const inputAggregate: RelayAgentActivityAggregateState = { + ...aggregate, + activities: [ + { + ...aggregate.activities[0]!, + phase: "waiting_for_input", + status: "Input", + }, + ], + }; + + return Effect.gen(function* () { + const deliveries = yield* ApnsDeliveries.ApnsDeliveries; + const result = yield* deliveries.sendForTarget({ + target: { + ...target, + push_token: "apns-device-token", + push_to_start_token: null, + activity_push_token: null, + remote_started_at: null, + }, + aggregate: inputAggregate, + nowMs: 5_000, + }); + + expect(result?.kind).toBe("push_notification"); + expect(result?.ok).toBe(true); + expect(queuedJobs).toMatchObject([ + { + payload: { + kind: "push_notification", + target: { + token: "apns-device-token", + }, + notification: { + title: "Thread", + body: "Input: Project", + environmentId: "env", + threadId: "thread", + deepLink: "/", + }, + }, + }, + ]); + expect(attempts).toEqual([]); + }).pipe(Effect.provide(makeLayer({ attempts, queuedJobs }))); + }, + ); + + it.effect("queues bounded alert notification payloads", () => { + const attempts: Array = []; + const queuedJobs: Array = []; + const longTitle = "x".repeat(300); + const inputAggregate: RelayAgentActivityAggregateState = { + ...aggregate, + activities: [ + { + ...aggregate.activities[0]!, + projectTitle: longTitle, + threadTitle: longTitle, + phase: "waiting_for_input", + status: "Input", + deepLink: "https://example.test/not-an-app-link", + }, + ], + }; + + return Effect.gen(function* () { + const deliveries = yield* ApnsDeliveries.ApnsDeliveries; + yield* deliveries.sendForTarget({ + target: { + ...target, + push_token: "apns-device-token", + push_to_start_token: null, + activity_push_token: null, + remote_started_at: null, + }, + aggregate: inputAggregate, + nowMs: 5_000, + }); + + const notification = queuedJobs[0]?.payload.notification; + expect(notification?.title.length).toBeLessThanOrEqual(120); + expect(notification?.body.length).toBeLessThanOrEqual(120); + expect(notification?.deepLink).toBe("/"); + expect(attempts).toEqual([]); + }).pipe(Effect.provide(makeLayer({ attempts, queuedJobs }))); + }); + + it.effect("processes signed jobs through APNs and records attempts", () => { + const attempts: Array = []; + const payload = makeApnsDeliveryJobPayload({ + kind: "live_activity_update", + userId: target.user_id, + deviceId: target.device_id, + token: target.activity_push_token ?? "activity-token", + aggregate, + createdAt: "1970-01-01T00:00:00.000Z", + expiresAt: "1970-01-01T00:10:00.000Z", + jobId: "job-1", + }); + const signed = signApnsDeliveryJob({ + secret: config.apnsDeliveryJobSigningSecret, + payload, + }); + + return Effect.gen(function* () { + const deliveries = yield* ApnsDeliveries.ApnsDeliveries; + const result = yield* deliveries.processSignedJob(signed); + + expect(result.kind).toBe("live_activity_update"); + expect(result.ok).toBe(false); + expect(attempts).toMatchObject([ + { + kind: "live_activity_update", + sourceJobId: "job-1", + token: "activity-token", + }, + ]); + }).pipe(Effect.provide(makeLayer({ attempts }))); + }); + + it.effect("processes signed push notification jobs through APNs and records attempts", () => { + const attempts: Array = []; + const payload = makeApnsDeliveryJobPayload({ + kind: "push_notification", + userId: target.user_id, + deviceId: target.device_id, + token: "apns-device-token", + aggregate: null, + notification: { + title: "Thread", + body: "Input: Project", + environmentId: "env", + threadId: "thread", + deepLink: "/", + }, + createdAt: "1970-01-01T00:00:00.000Z", + expiresAt: "1970-01-01T00:10:00.000Z", + jobId: "job-push-1", + }); + const signed = signApnsDeliveryJob({ + secret: config.apnsDeliveryJobSigningSecret, + payload, + }); + const execute = (request: HttpClientRequest.HttpClientRequest) => + Effect.succeed(HttpClientResponse.fromWeb(request, new Response("", { status: 200 }))); + + return Effect.gen(function* () { + const deliveries = yield* ApnsDeliveries.ApnsDeliveries; + const result = yield* deliveries.processSignedJob(signed); + + expect(result.kind).toBe("push_notification"); + expect(result.ok).toBe(true); + expect(result.apnsStatus).toBe(200); + expect(attempts).toMatchObject([ + { + kind: "push_notification", + sourceJobId: "job-push-1", + token: "apns-device-token", + environmentId: "env", + threadId: "thread", + deviceId: target.device_id, + apnsStatus: 200, + }, + ]); + }).pipe( + Effect.provide( + makeLayer({ + attempts, + currentTargets: [ + { + ...target, + push_token: "apns-device-token", + }, + ], + config: signingConfig, + execute, + }), + ), + ); + }); + + it.effect("skips duplicate signed queue jobs before calling APNs", () => { + const attempts: Array = []; + let executeCount = 0; + const payload = makeApnsDeliveryJobPayload({ + kind: "push_notification", + userId: target.user_id, + deviceId: target.device_id, + token: "apns-device-token", + aggregate: null, + notification: { + title: "Thread", + body: "Input: Project", + environmentId: "env", + threadId: "thread", + deepLink: "/", + }, + createdAt: "1970-01-01T00:00:00.000Z", + expiresAt: "1970-01-01T00:10:00.000Z", + jobId: "job-push-duplicate", + }); + const signed = signApnsDeliveryJob({ + secret: config.apnsDeliveryJobSigningSecret, + payload, + }); + const execute = (request: HttpClientRequest.HttpClientRequest) => + Effect.sync(() => { + executeCount += 1; + return HttpClientResponse.fromWeb(request, new Response("", { status: 200 })); + }); + + return Effect.gen(function* () { + const deliveries = yield* ApnsDeliveries.ApnsDeliveries; + const result = yield* deliveries.processSignedJob(signed); + + expect(result).toMatchObject({ + kind: "push_notification", + ok: true, + apnsStatus: null, + apnsReason: "Duplicate APNs delivery job skipped.", + }); + expect(executeCount).toBe(0); + expect(attempts).toEqual([]); + }).pipe( + Effect.provide( + makeLayer({ + attempts, + sourceJobClaims: new Map([["job-push-duplicate", "completed"]]), + config: signingConfig, + execute, + }), + ), + ); + }); + + it.effect("skips stale signed Live Activity jobs when the registered token changed", () => { + const attempts: Array = []; + let executeCount = 0; + const payload = makeApnsDeliveryJobPayload({ + kind: "live_activity_update", + userId: target.user_id, + deviceId: target.device_id, + token: "stale-activity-token", + aggregate, + createdAt: "1970-01-01T00:00:00.000Z", + expiresAt: "1970-01-01T00:10:00.000Z", + jobId: "job-update-stale-token", + }); + const signed = signApnsDeliveryJob({ + secret: config.apnsDeliveryJobSigningSecret, + payload, + }); + const execute = (request: HttpClientRequest.HttpClientRequest) => + Effect.sync(() => { + executeCount += 1; + return HttpClientResponse.fromWeb(request, new Response("", { status: 200 })); + }); + + return Effect.gen(function* () { + const deliveries = yield* ApnsDeliveries.ApnsDeliveries; + const result = yield* deliveries.processSignedJob(signed); + + expect(result).toMatchObject({ + kind: "live_activity_update", + ok: true, + apnsStatus: null, + apnsReason: "Stale APNs delivery job skipped.", + }); + expect(executeCount).toBe(0); + expect(attempts).toMatchObject([ + { + kind: "live_activity_update", + sourceJobId: "job-update-stale-token", + token: "stale-activity-token", + apnsReason: "Stale APNs delivery job skipped.", + }, + ]); + }).pipe( + Effect.provide( + makeLayer({ + attempts, + config: signingConfig, + execute, + }), + ), + ); + }); + + it.effect("skips stale signed push notification jobs when the device token changed", () => { + const attempts: Array = []; + let executeCount = 0; + const payload = makeApnsDeliveryJobPayload({ + kind: "push_notification", + userId: target.user_id, + deviceId: target.device_id, + token: "stale-device-token", + aggregate: null, + notification: { + title: "Thread", + body: "Input: Project", + environmentId: "env", + threadId: "thread", + deepLink: "/", + }, + createdAt: "1970-01-01T00:00:00.000Z", + expiresAt: "1970-01-01T00:10:00.000Z", + jobId: "job-push-stale-token", + }); + const signed = signApnsDeliveryJob({ + secret: config.apnsDeliveryJobSigningSecret, + payload, + }); + const execute = (request: HttpClientRequest.HttpClientRequest) => + Effect.sync(() => { + executeCount += 1; + return HttpClientResponse.fromWeb(request, new Response("", { status: 200 })); + }); + + return Effect.gen(function* () { + const deliveries = yield* ApnsDeliveries.ApnsDeliveries; + const result = yield* deliveries.processSignedJob(signed); + + expect(result).toMatchObject({ + kind: "push_notification", + ok: true, + apnsStatus: null, + apnsReason: "Stale APNs delivery job skipped.", + }); + expect(executeCount).toBe(0); + expect(attempts).toMatchObject([ + { + kind: "push_notification", + sourceJobId: "job-push-stale-token", + token: "stale-device-token", + apnsReason: "Stale APNs delivery job skipped.", + }, + ]); + }).pipe( + Effect.provide( + makeLayer({ + attempts, + currentTargets: [ + { + ...target, + push_token: "current-device-token", + }, + ], + config: signingConfig, + execute, + }), + ), + ); + }); + + it.effect("retries signed queue jobs that are already claimed but not completed", () => { + const attempts: Array = []; + let executeCount = 0; + const payload = makeApnsDeliveryJobPayload({ + kind: "push_notification", + userId: target.user_id, + deviceId: target.device_id, + token: "apns-device-token", + aggregate: null, + notification: { + title: "Thread", + body: "Input: Project", + environmentId: "env", + threadId: "thread", + deepLink: "/", + }, + createdAt: "1970-01-01T00:00:00.000Z", + expiresAt: "1970-01-01T00:10:00.000Z", + jobId: "job-push-in-flight", + }); + const signed = signApnsDeliveryJob({ + secret: config.apnsDeliveryJobSigningSecret, + payload, + }); + const execute = (request: HttpClientRequest.HttpClientRequest) => + Effect.sync(() => { + executeCount += 1; + return HttpClientResponse.fromWeb(request, new Response("", { status: 200 })); + }); + + return Effect.gen(function* () { + const deliveries = yield* ApnsDeliveries.ApnsDeliveries; + const result = yield* Effect.exit(deliveries.processSignedJob(signed)); + + expect(result._tag).toBe("Failure"); + if (result._tag === "Failure") { + expect(result.cause.toString()).toContain("ApnsDeliveryJobClaimInFlight"); + } + expect(executeCount).toBe(0); + expect(attempts).toEqual([]); + }).pipe( + Effect.provide( + makeLayer({ + attempts, + sourceJobClaims: new Map([["job-push-in-flight", "in_flight"]]), + config: signingConfig, + execute, + }), + ), + ); + }); + + it.effect("invalidates dead device push tokens after permanent APNs alert failures", () => { + const attempts: Array = []; + const invalidatedTokens: Array< + Parameters[0] + > = []; + const payload = makeApnsDeliveryJobPayload({ + kind: "push_notification", + userId: target.user_id, + deviceId: target.device_id, + token: "apns-device-token", + aggregate: null, + notification: { + title: "Thread", + body: "Failed: Project", + environmentId: "env", + threadId: "thread", + deepLink: "/", + }, + createdAt: "1970-01-01T00:00:00.000Z", + expiresAt: "1970-01-01T00:10:00.000Z", + jobId: "job-push-bad-token", + }); + const signed = signApnsDeliveryJob({ + secret: config.apnsDeliveryJobSigningSecret, + payload, + }); + const execute = (request: HttpClientRequest.HttpClientRequest) => + Effect.succeed( + HttpClientResponse.fromWeb( + request, + Response.json({ reason: "BadDeviceToken" }, { status: 400 }), + ), + ); + + return Effect.gen(function* () { + const deliveries = yield* ApnsDeliveries.ApnsDeliveries; + const result = yield* deliveries.processSignedJob(signed); + + expect(result.kind).toBe("push_notification"); + expect(result.ok).toBe(false); + expect(result.apnsStatus).toBe(400); + expect(result.apnsReason).toBe("BadDeviceToken"); + expect(invalidatedTokens).toMatchObject([ + { + userId: target.user_id, + deviceId: target.device_id, + kind: "push_notification", + }, + ]); + }).pipe( + Effect.provide( + makeLayer({ + attempts, + invalidatedTokens, + currentTargets: [ + { + ...target, + push_token: "apns-device-token", + }, + ], + config: signingConfig, + execute, + }), + ), + ); + }); + + it.effect("clears queued start state when a start job fails in APNs", () => { + const attempts: Array = []; + const clearedStarts: Array< + Parameters[0] + > = []; + const payload = makeApnsDeliveryJobPayload({ + kind: "live_activity_start", + userId: target.user_id, + deviceId: target.device_id, + token: target.push_to_start_token ?? "start-token", + aggregate, + createdAt: "1970-01-01T00:00:00.000Z", + expiresAt: "1970-01-01T00:10:00.000Z", + jobId: "job-start-1", + }); + const signed = signApnsDeliveryJob({ + secret: config.apnsDeliveryJobSigningSecret, + payload, + }); + + return Effect.gen(function* () { + const deliveries = yield* ApnsDeliveries.ApnsDeliveries; + const result = yield* deliveries.processSignedJob(signed); + + expect(result.kind).toBe("live_activity_start"); + expect(result.ok).toBe(false); + expect(clearedStarts).toEqual([ + { + userId: target.user_id, + deviceId: target.device_id, + }, + ]); + }).pipe(Effect.provide(makeLayer({ attempts, clearedStarts }))); + }); + + it.effect("invalidates dead push-to-start tokens after permanent APNs start failures", () => { + const attempts: Array = []; + const invalidatedTokens: Array< + Parameters[0] + > = []; + const payload = makeApnsDeliveryJobPayload({ + kind: "live_activity_start", + userId: target.user_id, + deviceId: target.device_id, + token: target.push_to_start_token ?? "start-token", + aggregate, + createdAt: "1970-01-01T00:00:00.000Z", + expiresAt: "1970-01-01T00:10:00.000Z", + jobId: "job-start-bad-token", + }); + const signed = signApnsDeliveryJob({ + secret: config.apnsDeliveryJobSigningSecret, + payload, + }); + const execute = (request: HttpClientRequest.HttpClientRequest) => + Effect.succeed( + HttpClientResponse.fromWeb( + request, + Response.json({ reason: "BadDeviceToken" }, { status: 400 }), + ), + ); + + return Effect.gen(function* () { + const deliveries = yield* ApnsDeliveries.ApnsDeliveries; + const result = yield* deliveries.processSignedJob(signed); + + expect(result.kind).toBe("live_activity_start"); + expect(result.ok).toBe(false); + expect(result.apnsStatus).toBe(400); + expect(result.apnsReason).toBe("BadDeviceToken"); + expect(invalidatedTokens).toMatchObject([ + { + userId: target.user_id, + deviceId: target.device_id, + kind: "live_activity_start", + }, + ]); + }).pipe( + Effect.provide(makeLayer({ attempts, invalidatedTokens, config: signingConfig, execute })), + ); + }); + + it.effect("invalidates dead Live Activity tokens after APNs unregisters them", () => { + const attempts: Array = []; + const invalidatedTokens: Array< + Parameters[0] + > = []; + const payload = makeApnsDeliveryJobPayload({ + kind: "live_activity_update", + userId: target.user_id, + deviceId: target.device_id, + token: target.activity_push_token ?? "activity-token", + aggregate, + createdAt: "1970-01-01T00:00:00.000Z", + expiresAt: "1970-01-01T00:10:00.000Z", + jobId: "job-update-unregistered", + }); + const signed = signApnsDeliveryJob({ + secret: config.apnsDeliveryJobSigningSecret, + payload, + }); + const execute = (request: HttpClientRequest.HttpClientRequest) => + Effect.succeed( + HttpClientResponse.fromWeb( + request, + Response.json({ reason: "Unregistered" }, { status: 410 }), + ), + ); + + return Effect.gen(function* () { + const deliveries = yield* ApnsDeliveries.ApnsDeliveries; + const result = yield* deliveries.processSignedJob(signed); + + expect(result.kind).toBe("live_activity_update"); + expect(result.ok).toBe(false); + expect(result.apnsStatus).toBe(410); + expect(result.apnsReason).toBe("Unregistered"); + expect(invalidatedTokens).toMatchObject([ + { + userId: target.user_id, + deviceId: target.device_id, + kind: "live_activity_update", + }, + ]); + }).pipe( + Effect.provide(makeLayer({ attempts, invalidatedTokens, config: signingConfig, execute })), + ); + }); +}); diff --git a/infra/relay/src/services/ApnsDeliveries.ts b/infra/relay/src/services/ApnsDeliveries.ts new file mode 100644 index 0000000000..db399fa24b --- /dev/null +++ b/infra/relay/src/services/ApnsDeliveries.ts @@ -0,0 +1,793 @@ +import type { + RelayAgentActivityAggregateState, + RelayAgentAwarenessPreferences, + RelayDeliveryKind, + RelayDeliveryResult, +} from "@t3tools/contracts/relay"; +import { + RelayAgentActivityAggregateState as RelayAgentActivityAggregateStateSchema, + RelayAgentAwarenessPreferences as RelayAgentAwarenessPreferencesSchema, +} from "@t3tools/contracts/relay"; +import * as Context from "effect/Context"; +import * as Data from "effect/Data"; +import * as DateTime from "effect/DateTime"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import * as Option from "effect/Option"; +import * as Schema from "effect/Schema"; +import { HttpClient } from "effect/unstable/http"; + +import { + sanitizeAgentActivityAggregateState, + sanitizeApnsNotificationPayload, +} from "../agentActivityPayloads.ts"; +import * as Apns from "../apns.ts"; +import { + ApnsDeliveryJobInvalid, + type ApnsNotificationPayload, + SignedApnsDeliveryJob, + verifySignedApnsDeliveryJob, + type ApnsDeliveryJobVerificationError, +} from "../apnsDeliveryJobs.ts"; +import * as DeliveryAttempts from "../persistence/DeliveryAttempts.ts"; +import * as LiveActivities from "../persistence/LiveActivities.ts"; +import * as RelayConfiguration from "../Config.ts"; +import { withUserId } from "../telemetry.ts"; +import * as ApnsDeliveryQueue from "./ApnsDeliveryQueue.ts"; + +const MIN_LIVE_ACTIVITY_UPDATE_INTERVAL_MS = 15_000; +const PERMANENT_APNS_TOKEN_REASONS = new Set([ + "BadDeviceToken", + "DeviceTokenNotForTopic", + "Unregistered", +]); + +type LiveActivityDeliveryKind = Extract< + RelayDeliveryKind, + "live_activity_start" | "live_activity_update" | "live_activity_end" +>; + +type ChosenLiveActivityDelivery = + | { + readonly kind: "live_activity_start" | "live_activity_update"; + readonly token: string; + readonly aggregate: RelayAgentActivityAggregateState; + } + | { + readonly kind: "live_activity_end"; + readonly token: string; + readonly aggregate: RelayAgentActivityAggregateState | null; + }; + +type ChosenPushNotificationDelivery = { + readonly kind: "push_notification"; + readonly token: string; + readonly notification: ApnsNotificationPayload; +}; + +type ChosenDelivery = ChosenLiveActivityDelivery | ChosenPushNotificationDelivery; + +export type ApnsDeliveryError = + | ApnsDeliveryQueue.ApnsDeliveryQueueError + | ApnsDeliveryJobVerificationError + | ApnsDeliveryJobClaimInFlight + | DeliveryAttempts.DeliveryAttemptRecordPersistenceError + | LiveActivities.LiveActivityTargetListPersistenceError + | LiveActivities.LiveActivityDeliveryMarkPersistenceError; + +export class ApnsDeliveryJobClaimInFlight extends Data.TaggedError("ApnsDeliveryJobClaimInFlight")<{ + readonly sourceJobId: string; +}> {} + +const decodeRelayAgentActivityAggregateStateJson = Schema.decodeUnknownOption( + Schema.fromJsonString(RelayAgentActivityAggregateStateSchema), +); +const decodeRelayAgentAwarenessPreferencesJson = Schema.decodeUnknownOption( + Schema.fromJsonString(RelayAgentAwarenessPreferencesSchema), +); +const decodeSignedApnsDeliveryJob = Schema.decodeUnknownEffect(SignedApnsDeliveryJob); + +function apnsErrorMessage(error: Apns.ApnsError): string { + switch (error._tag) { + case "ApnsSigningError": + return "Failed to sign APNs request."; + case "ApnsHttpRequestError": + return "Failed to send APNs request."; + case "ApnsInvalidResponseError": + return "APNs returned an invalid response."; + } +} + +function parseAggregate(value: string | null): RelayAgentActivityAggregateState | null { + if (!value) { + return null; + } + return Option.getOrNull(decodeRelayAgentActivityAggregateStateJson(value)); +} + +function parsePreferences(value: string): RelayAgentAwarenessPreferences | null { + return Option.getOrNull(decodeRelayAgentAwarenessPreferencesJson(value)); +} + +function shouldUpdateLiveActivity(input: { + readonly previousAggregate: RelayAgentActivityAggregateState | null; + readonly nextAggregate: RelayAgentActivityAggregateState; + readonly lastDeliveryAt: string | null; + readonly nowMs: number; +}): boolean { + if (!input.previousAggregate) { + return true; + } + if (input.previousAggregate.activeCount !== input.nextAggregate.activeCount) { + return true; + } + if (JSON.stringify(input.previousAggregate) === JSON.stringify(input.nextAggregate)) { + return false; + } + const lastDeliveryAtMs = + input.lastDeliveryAt === null + ? null + : Option.match(DateTime.make(input.lastDeliveryAt), { + onNone: () => Number.NaN, + onSome: (dt) => dt.epochMilliseconds, + }); + return ( + lastDeliveryAtMs === null || + Number.isNaN(lastDeliveryAtMs) || + input.nowMs - lastDeliveryAtMs >= MIN_LIVE_ACTIVITY_UPDATE_INTERVAL_MS + ); +} + +function notificationForAggregate(input: { + readonly target: LiveActivities.TargetRow; + readonly aggregate: RelayAgentActivityAggregateState | null; +}): ApnsNotificationPayload | null { + if (!input.target.push_token || input.aggregate === null) { + return null; + } + const preferences = parsePreferences(input.target.preferences_json); + if (!preferences?.notificationsEnabled) { + return null; + } + const activity = input.aggregate.activities[0]; + if (!activity) { + return null; + } + const enabled = + (activity.phase === "waiting_for_approval" && preferences.notifyOnApproval) || + (activity.phase === "waiting_for_input" && preferences.notifyOnInput) || + (activity.phase === "completed" && preferences.notifyOnCompletion) || + (activity.phase === "failed" && preferences.notifyOnFailure); + if (!enabled) { + return null; + } + return { + title: activity.threadTitle, + body: `${activity.status}: ${activity.projectTitle}`, + environmentId: activity.environmentId, + threadId: activity.threadId, + deepLink: activity.deepLink, + }; +} + +function chooseLiveActivityDelivery(input: { + readonly target: LiveActivities.TargetRow; + readonly aggregate: RelayAgentActivityAggregateState | null; + readonly nowMs: number; +}): ChosenLiveActivityDelivery | null { + const hasActiveActivity = + input.target.ended_at === null && + (input.target.remote_start_queued_at !== null || + input.target.remote_started_at !== null || + input.target.activity_push_token !== null); + const preferences = parsePreferences(input.target.preferences_json); + if (preferences?.liveActivitiesEnabled === false) { + return hasActiveActivity && input.target.activity_push_token + ? { + kind: "live_activity_end", + token: input.target.activity_push_token, + aggregate: null, + } + : null; + } + if (input.aggregate === null || input.aggregate.activeCount === 0) { + return hasActiveActivity && input.target.activity_push_token + ? { + kind: "live_activity_end", + token: input.target.activity_push_token, + aggregate: input.aggregate, + } + : null; + } + if (!hasActiveActivity) { + return input.target.push_to_start_token + ? { + kind: "live_activity_start", + token: input.target.push_to_start_token, + aggregate: input.aggregate, + } + : null; + } + if (!input.target.activity_push_token) { + return null; + } + return shouldUpdateLiveActivity({ + previousAggregate: parseAggregate(input.target.last_aggregate_json), + nextAggregate: input.aggregate, + lastDeliveryAt: input.target.last_live_activity_delivery_at, + nowMs: input.nowMs, + }) || + input.aggregate.activities.some( + (row) => row.phase === "waiting_for_approval" || row.phase === "waiting_for_input", + ) + ? { + kind: "live_activity_update", + token: input.target.activity_push_token, + aggregate: input.aggregate, + } + : null; +} + +function chooseDelivery(input: { + readonly target: LiveActivities.TargetRow; + readonly aggregate: RelayAgentActivityAggregateState | null; + readonly nowMs: number; +}): ChosenDelivery | null { + const liveActivityDelivery = chooseLiveActivityDelivery(input); + if (liveActivityDelivery) { + return liveActivityDelivery; + } + const notification = notificationForAggregate(input); + return notification && input.target.push_token + ? { + kind: "push_notification", + token: input.target.push_token, + notification, + } + : null; +} + +function deliveryEvent(kind: LiveActivityDeliveryKind): Apns.ApnsLiveActivityEvent { + switch (kind) { + case "live_activity_start": + return "start"; + case "live_activity_update": + return "update"; + case "live_activity_end": + return "end"; + } +} + +function isPermanentApnsTokenFailure(result: Apns.ApnsDeliveryResult): boolean { + return ( + !result.ok && + (result.status === 410 || + (result.status === 400 && + result.reason !== undefined && + PERMANENT_APNS_TOKEN_REASONS.has(result.reason))) + ); +} + +function isDeliveryJobVerificationError(value: unknown): value is ApnsDeliveryJobVerificationError { + return ( + typeof value === "object" && + value !== null && + "_tag" in value && + (value._tag === "ApnsDeliveryJobInvalid" || value._tag === "ApnsDeliveryJobExpired") + ); +} + +function duplicateJobResult(input: { + readonly deviceId: string; + readonly kind: RelayDeliveryKind; +}): RelayDeliveryResult { + return { + deviceId: input.deviceId, + kind: input.kind, + ok: true, + apnsStatus: null, + apnsReason: "Duplicate APNs delivery job skipped.", + apnsId: null, + }; +} + +function staleJobResult(input: { + readonly deviceId: string; + readonly kind: RelayDeliveryKind; +}): RelayDeliveryResult { + return { + deviceId: input.deviceId, + kind: input.kind, + ok: true, + apnsStatus: null, + apnsReason: "Stale APNs delivery job skipped.", + apnsId: null, + }; +} + +function deliveryAttemptOutcome(result: Apns.ApnsDeliveryResult) { + return { + ...(result.status === 0 ? {} : { apnsStatus: result.status }), + ...(result.reason === undefined ? {} : { apnsReason: result.reason }), + apnsId: result.apnsId, + ...(result.status === 0 ? { transportError: result.reason ?? "APNs request failed." } : {}), + }; +} + +interface LiveActivityDeliveryTarget { + readonly user_id: string; + readonly device_id: string; +} + +function expectedCurrentToken(input: { + readonly target: LiveActivities.TargetRow; + readonly kind: RelayDeliveryKind; +}): string | null { + switch (input.kind) { + case "live_activity_start": + return input.target.push_to_start_token; + case "live_activity_update": + case "live_activity_end": + return input.target.activity_push_token; + case "push_notification": + return input.target.push_token; + } +} + +interface SendLiveActivityDeliveryInputBase { + readonly target: LiveActivityDeliveryTarget; + readonly token: string; + readonly sourceJobId?: string | null; +} + +export type SendLiveActivityDeliveryInput = + | (SendLiveActivityDeliveryInputBase & { + readonly kind: "live_activity_start" | "live_activity_update"; + readonly aggregate: RelayAgentActivityAggregateState; + }) + | (SendLiveActivityDeliveryInputBase & { + readonly kind: "live_activity_end"; + readonly aggregate: RelayAgentActivityAggregateState | null; + }); + +function makeLiveActivityDeliveryRequest( + input: SendLiveActivityDeliveryInput, + now: DateTime.DateTime, +) { + const epochSeconds = Math.floor(now.epochMilliseconds / 1_000); + const base = { + token: input.token, + nowEpochSeconds: epochSeconds, + nowIso: DateTime.formatIso(now), + }; + switch (input.kind) { + case "live_activity_start": + case "live_activity_update": + return { + epochSeconds, + iso: base.nowIso, + request: Apns.makeLiveActivityRequest({ + ...base, + event: deliveryEvent(input.kind), + state: input.aggregate, + }), + }; + case "live_activity_end": + return { + epochSeconds, + iso: base.nowIso, + request: Apns.makeLiveActivityRequest({ + ...base, + event: "end", + state: input.aggregate, + }), + }; + } +} + +export interface ApnsDeliveriesShape { + readonly sendForTarget: (input: { + readonly target: LiveActivities.TargetRow; + readonly aggregate: RelayAgentActivityAggregateState | null; + readonly nowMs: number; + }) => Effect.Effect; + readonly sendPushNotificationForTarget: (input: { + readonly target: LiveActivities.TargetRow; + readonly aggregate: RelayAgentActivityAggregateState | null; + }) => Effect.Effect; + readonly sendLiveActivity: ( + input: SendLiveActivityDeliveryInput, + ) => Effect.Effect; + readonly processSignedJob: ( + body: unknown, + ) => Effect.Effect; + readonly sendPushNotification: (input: { + readonly target: LiveActivityDeliveryTarget; + readonly token: string; + readonly sourceJobId?: string | null; + readonly notification: ApnsNotificationPayload; + }) => Effect.Effect; +} + +export class ApnsDeliveries extends Context.Service()( + "ApnsDeliveries", +) {} + +const make = Effect.gen(function* () { + const attempts = yield* DeliveryAttempts.DeliveryAttempts; + const liveActivities = yield* LiveActivities.LiveActivities; + const deliveryQueue = yield* ApnsDeliveryQueue.ApnsDeliveryQueue; + const config = yield* RelayConfiguration.RelayConfiguration; + const httpClient = yield* HttpClient.HttpClient; + + const isCurrentSignedJobToken = Effect.fnUntraced(function* (input: { + readonly target: LiveActivityDeliveryTarget; + readonly kind: RelayDeliveryKind; + readonly token: string; + }) { + return yield* liveActivities.listTargets({ userId: input.target.user_id }).pipe( + Effect.map((targets) => { + const currentTarget = targets.find((row) => row.device_id === input.target.device_id); + return ( + currentTarget !== undefined && + expectedCurrentToken({ target: currentTarget, kind: input.kind }) === input.token + ); + }), + ); + }); + + const sendLiveActivity: ApnsDeliveriesShape["sendLiveActivity"] = Effect.fn( + "relay.apns_deliveries.send_live_activity", + )( + function* (input) { + yield* Effect.annotateCurrentSpan({ + "relay.mobile.device_id": input.target.device_id, + "relay.delivery.kind": input.kind, + ...(input.sourceJobId ? { "relay.delivery.job_id": input.sourceJobId } : {}), + }); + const now = yield* DateTime.now; + const aggregate = + input.aggregate === null ? null : sanitizeAgentActivityAggregateState(input.aggregate); + const { epochSeconds, iso, request } = makeLiveActivityDeliveryRequest( + { ...input, aggregate } as SendLiveActivityDeliveryInput, + now, + ); + if (input.sourceJobId) { + const claim = yield* attempts.claimSourceJob({ + userId: input.target.user_id, + environmentId: null, + threadId: null, + deviceId: input.target.device_id, + kind: input.kind, + sourceJobId: input.sourceJobId, + token: input.token, + }); + if (claim === "completed") { + return duplicateJobResult({ deviceId: input.target.device_id, kind: input.kind }); + } + if (claim === "in_flight") { + return yield* new ApnsDeliveryJobClaimInFlight({ sourceJobId: input.sourceJobId }); + } + const tokenIsCurrent = yield* isCurrentSignedJobToken({ + target: input.target, + kind: input.kind, + token: input.token, + }); + if (!tokenIsCurrent) { + yield* attempts.completeSourceJob({ + sourceJobId: input.sourceJobId, + apnsReason: "Stale APNs delivery job skipped.", + }); + return staleJobResult({ deviceId: input.target.device_id, kind: input.kind }); + } + } + const result = yield* Apns.sendLiveActivityRequest({ + credentials: config.apns, + request, + issuedAtUnixSeconds: epochSeconds, + }).pipe( + Effect.provideService(HttpClient.HttpClient, httpClient), + Effect.catch((error) => + Effect.succeed({ + ok: false, + status: 0, + reason: apnsErrorMessage(error), + apnsId: null, + }), + ), + ); + if (result.ok) { + yield* liveActivities.markDelivery({ + userId: input.target.user_id, + deviceId: input.target.device_id, + kind: input.kind, + aggregate, + deliveredAt: iso, + }); + } else if (isPermanentApnsTokenFailure(result)) { + yield* liveActivities.invalidateDeliveryToken({ + userId: input.target.user_id, + deviceId: input.target.device_id, + kind: input.kind, + invalidatedAt: iso, + }); + } else if (input.kind === "live_activity_start") { + yield* liveActivities.clearStartQueued({ + userId: input.target.user_id, + deviceId: input.target.device_id, + }); + } + if (input.sourceJobId) { + yield* attempts.completeSourceJob({ + sourceJobId: input.sourceJobId, + ...deliveryAttemptOutcome(result), + }); + } else { + yield* attempts.record({ + userId: input.target.user_id, + environmentId: null, + threadId: null, + deviceId: input.target.device_id, + kind: input.kind, + token: input.token, + ...deliveryAttemptOutcome(result), + }); + } + return { + deviceId: input.target.device_id, + kind: input.kind, + ok: result.ok, + apnsStatus: result.status === 0 ? null : result.status, + apnsReason: result.reason ?? null, + apnsId: result.apnsId, + }; + }, + (effect, input) => effect.pipe(withUserId(input.target.user_id)), + ); + + const sendPushNotification: ApnsDeliveriesShape["sendPushNotification"] = Effect.fn( + "relay.apns_deliveries.send_push_notification", + )( + function* (input) { + yield* Effect.annotateCurrentSpan({ + "relay.mobile.device_id": input.target.device_id, + "relay.delivery.kind": "push_notification", + ...(input.sourceJobId ? { "relay.delivery.job_id": input.sourceJobId } : {}), + }); + const now = yield* DateTime.now; + const epochSeconds = Math.floor(now.epochMilliseconds / 1_000); + const notification = sanitizeApnsNotificationPayload(input.notification); + yield* Effect.annotateCurrentSpan({ + "relay.environment_id": notification.environmentId, + "relay.thread_id": notification.threadId, + }); + const request = Apns.makePushNotificationRequest({ + token: input.token, + notification, + }); + if (input.sourceJobId) { + const claim = yield* attempts.claimSourceJob({ + userId: input.target.user_id, + environmentId: notification.environmentId, + threadId: notification.threadId, + deviceId: input.target.device_id, + kind: "push_notification", + sourceJobId: input.sourceJobId, + token: input.token, + }); + if (claim === "completed") { + return duplicateJobResult({ + deviceId: input.target.device_id, + kind: "push_notification", + }); + } + if (claim === "in_flight") { + return yield* new ApnsDeliveryJobClaimInFlight({ sourceJobId: input.sourceJobId }); + } + const tokenIsCurrent = yield* isCurrentSignedJobToken({ + target: input.target, + kind: "push_notification", + token: input.token, + }); + if (!tokenIsCurrent) { + yield* attempts.completeSourceJob({ + sourceJobId: input.sourceJobId, + apnsReason: "Stale APNs delivery job skipped.", + }); + return staleJobResult({ + deviceId: input.target.device_id, + kind: "push_notification", + }); + } + } + const result = yield* Apns.sendPushNotificationRequest({ + credentials: config.apns, + request, + issuedAtUnixSeconds: epochSeconds, + }).pipe( + Effect.provideService(HttpClient.HttpClient, httpClient), + Effect.catch((error) => + Effect.succeed({ + ok: false, + status: 0, + reason: apnsErrorMessage(error), + apnsId: null, + }), + ), + ); + if (isPermanentApnsTokenFailure(result)) { + yield* liveActivities.invalidateDeliveryToken({ + userId: input.target.user_id, + deviceId: input.target.device_id, + kind: "push_notification", + invalidatedAt: DateTime.formatIso(now), + }); + } + if (input.sourceJobId) { + yield* attempts.completeSourceJob({ + sourceJobId: input.sourceJobId, + ...deliveryAttemptOutcome(result), + }); + } else { + yield* attempts.record({ + userId: input.target.user_id, + environmentId: notification.environmentId, + threadId: notification.threadId, + deviceId: input.target.device_id, + kind: "push_notification", + token: input.token, + ...deliveryAttemptOutcome(result), + }); + } + return { + deviceId: input.target.device_id, + kind: "push_notification" as const, + ok: result.ok, + apnsStatus: result.status === 0 ? null : result.status, + apnsReason: result.reason ?? null, + apnsId: result.apnsId, + }; + }, + (effect, input) => effect.pipe(withUserId(input.target.user_id)), + ); + + const processSignedJob: ApnsDeliveriesShape["processSignedJob"] = Effect.fn( + "relay.apns_deliveries.process_signed_job", + )(function* (body) { + const signedJob = yield* decodeSignedApnsDeliveryJob(body).pipe( + Effect.mapError( + () => + new ApnsDeliveryJobInvalid({ + message: "Invalid APNs delivery queue job.", + }), + ), + ); + const now = yield* DateTime.now; + const payload = verifySignedApnsDeliveryJob({ + secret: config.apnsDeliveryJobSigningSecret, + job: signedJob, + nowMs: now.epochMilliseconds, + }); + if (isDeliveryJobVerificationError(payload)) { + return yield* payload; + } + yield* Effect.annotateCurrentSpan({ + "user.id": payload.target.userId, + "relay.mobile.device_id": payload.target.deviceId, + "relay.delivery.kind": payload.kind, + "relay.delivery.job_id": payload.jobId, + }); + switch (payload.kind) { + case "live_activity_start": + case "live_activity_update": + if (payload.aggregate === null) { + return yield* new ApnsDeliveryJobInvalid({ + message: "Live Activity start/update jobs require an aggregate.", + }); + } + return yield* sendLiveActivity({ + target: { + user_id: payload.target.userId, + device_id: payload.target.deviceId, + }, + token: payload.target.token, + sourceJobId: payload.jobId, + kind: payload.kind, + aggregate: payload.aggregate, + }); + case "live_activity_end": + return yield* sendLiveActivity({ + target: { + user_id: payload.target.userId, + device_id: payload.target.deviceId, + }, + token: payload.target.token, + sourceJobId: payload.jobId, + kind: payload.kind, + aggregate: payload.aggregate, + }); + case "push_notification": + if (payload.notification === null) { + return yield* new ApnsDeliveryJobInvalid({ + message: "Push notification jobs require a notification payload.", + }); + } + return yield* sendPushNotification({ + target: { + user_id: payload.target.userId, + device_id: payload.target.deviceId, + }, + token: payload.target.token, + sourceJobId: payload.jobId, + notification: payload.notification, + }); + } + }); + + return ApnsDeliveries.of({ + sendLiveActivity, + sendPushNotification, + processSignedJob, + sendPushNotificationForTarget: Effect.fnUntraced(function* (input) { + const notification = notificationForAggregate(input); + const token = input.target.push_token; + return yield* notification && token + ? deliveryQueue.enqueuePushNotification({ + userId: input.target.user_id, + deviceId: input.target.device_id, + token, + notification, + }) + : Effect.succeed(null); + }), + sendForTarget: Effect.fnUntraced(function* (input) { + const delivery = chooseDelivery({ + target: input.target, + aggregate: input.aggregate, + nowMs: input.nowMs, + }); + if (!delivery) { + return null; + } + if (delivery.kind === "push_notification") { + const result = yield* deliveryQueue.enqueuePushNotification({ + userId: input.target.user_id, + deviceId: input.target.device_id, + token: delivery.token, + notification: delivery.notification, + }); + return result; + } + const result = yield* deliveryQueue.enqueueLiveActivity({ + userId: input.target.user_id, + deviceId: input.target.device_id, + kind: delivery.kind, + token: delivery.token, + aggregate: delivery.aggregate, + }); + const notification = notificationForAggregate({ + target: input.target, + aggregate: input.aggregate, + }); + if (delivery.kind === "live_activity_end" && notification && input.target.push_token) { + yield* deliveryQueue.enqueuePushNotification({ + userId: input.target.user_id, + deviceId: input.target.device_id, + token: input.target.push_token, + notification, + }); + } + if (delivery.kind === "live_activity_start") { + const now = yield* DateTime.now; + yield* liveActivities.markStartQueued({ + userId: input.target.user_id, + deviceId: input.target.device_id, + queuedAt: DateTime.formatIso(now), + }); + } + return result; + }), + }); +}); + +export const layer = Layer.effect(ApnsDeliveries, make); diff --git a/infra/relay/src/services/ApnsDeliveryQueue.ts b/infra/relay/src/services/ApnsDeliveryQueue.ts new file mode 100644 index 0000000000..be7bafb9e9 --- /dev/null +++ b/infra/relay/src/services/ApnsDeliveryQueue.ts @@ -0,0 +1,144 @@ +import type { RelayDeliveryResult } from "@t3tools/contracts/relay"; +import * as Crypto from "effect/Crypto"; +import * as Context from "effect/Context"; +import * as Data from "effect/Data"; +import * as DateTime from "effect/DateTime"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; + +import { + sanitizeAgentActivityAggregateState, + sanitizeApnsNotificationPayload, +} from "../agentActivityPayloads.ts"; +import { + expiresAtForJob, + makeApnsDeliveryJobPayload, + signApnsDeliveryJob, + type ApnsDeliveryJobPayload, + type SignedApnsDeliveryJob, +} from "../apnsDeliveryJobs.ts"; +import * as RelayConfiguration from "../Config.ts"; +import { withUserId } from "../telemetry.ts"; + +export class ApnsDeliveryQueueSendError extends Data.TaggedError("ApnsDeliveryQueueSendError")<{ + readonly cause: unknown; +}> {} + +export type ApnsDeliveryQueueError = ApnsDeliveryQueueSendError; + +export interface ApnsDeliveryQueueSenderShape { + readonly send: (body: SignedApnsDeliveryJob) => Effect.Effect; +} + +export class ApnsDeliveryQueueSender extends Context.Service< + ApnsDeliveryQueueSender, + ApnsDeliveryQueueSenderShape +>()("ApnsDeliveryQueueSender") {} + +export interface ApnsDeliveryQueueShape { + readonly enqueueLiveActivity: (input: { + readonly kind: ApnsDeliveryJobPayload["kind"]; + readonly userId: string; + readonly deviceId: string; + readonly token: string; + readonly aggregate: ApnsDeliveryJobPayload["aggregate"]; + }) => Effect.Effect; + readonly enqueuePushNotification: (input: { + readonly userId: string; + readonly deviceId: string; + readonly token: string; + readonly notification: NonNullable; + }) => Effect.Effect; +} + +export class ApnsDeliveryQueue extends Context.Service()( + "ApnsDeliveryQueue", +) {} + +const make = Effect.gen(function* () { + const sender = yield* ApnsDeliveryQueueSender; + const crypto = yield* Crypto.Crypto; + const config = yield* RelayConfiguration.RelayConfiguration; + + return ApnsDeliveryQueue.of({ + enqueueLiveActivity: Effect.fn("relay.apns_delivery_queue.enqueue_live_activity")( + function* (input) { + yield* Effect.annotateCurrentSpan({ + "relay.mobile.device_id": input.deviceId, + "relay.delivery.kind": input.kind, + }); + const now = yield* DateTime.now; + const jobId = yield* crypto.randomUUIDv4.pipe( + Effect.mapError((cause) => new ApnsDeliveryQueueSendError({ cause })), + ); + yield* Effect.annotateCurrentSpan({ "relay.delivery.job_id": jobId }); + const payload = makeApnsDeliveryJobPayload({ + ...input, + aggregate: + input.aggregate === null ? null : sanitizeAgentActivityAggregateState(input.aggregate), + jobId, + createdAt: DateTime.formatIso(now), + expiresAt: expiresAtForJob(now.epochMilliseconds), + }); + const signed = signApnsDeliveryJob({ + secret: config.apnsDeliveryJobSigningSecret, + payload, + }); + yield* sender.send(signed); + return { + deviceId: input.deviceId, + kind: input.kind, + ok: true, + queued: true, + apnsStatus: null, + apnsReason: null, + apnsId: null, + }; + }, + (effect, input) => effect.pipe(withUserId(input.userId)), + ), + enqueuePushNotification: Effect.fn("relay.apns_delivery_queue.enqueue_push_notification")( + function* (input) { + yield* Effect.annotateCurrentSpan({ + "relay.mobile.device_id": input.deviceId, + "relay.delivery.kind": "push_notification", + "relay.environment_id": input.notification.environmentId, + "relay.thread_id": input.notification.threadId, + }); + const now = yield* DateTime.now; + const jobId = yield* crypto.randomUUIDv4.pipe( + Effect.mapError((cause) => new ApnsDeliveryQueueSendError({ cause })), + ); + yield* Effect.annotateCurrentSpan({ "relay.delivery.job_id": jobId }); + const payload = makeApnsDeliveryJobPayload({ + kind: "push_notification", + userId: input.userId, + deviceId: input.deviceId, + token: input.token, + aggregate: null, + notification: sanitizeApnsNotificationPayload(input.notification), + jobId, + createdAt: DateTime.formatIso(now), + expiresAt: expiresAtForJob(now.epochMilliseconds), + }); + const signed = signApnsDeliveryJob({ + secret: config.apnsDeliveryJobSigningSecret, + payload, + }); + yield* sender.send(signed); + return { + deviceId: input.deviceId, + kind: "push_notification" as const, + ok: true, + queued: true, + apnsStatus: null, + apnsReason: null, + apnsId: null, + }; + }, + (effect, input) => effect.pipe(withUserId(input.userId)), + ), + }); +}); + +export const layer = Layer.effect(ApnsDeliveryQueue, make); diff --git a/infra/relay/src/services/Auth.ts b/infra/relay/src/services/Auth.ts new file mode 100644 index 0000000000..a7f92b566b --- /dev/null +++ b/infra/relay/src/services/Auth.ts @@ -0,0 +1,19 @@ +import * as Context from "effect/Context"; + +export interface ClientPrincipalShape { + readonly userId: string; +} + +export class ClientPrincipal extends Context.Service()( + "ClientPrincipal", +) {} + +export interface EnvironmentPrincipalShape { + readonly environmentId: string; + readonly credentialId: string; +} + +export class EnvironmentPrincipal extends Context.Service< + EnvironmentPrincipal, + EnvironmentPrincipalShape +>()("EnvironmentPrincipal") {} diff --git a/infra/relay/src/services/EnvironmentConnector.test.ts b/infra/relay/src/services/EnvironmentConnector.test.ts new file mode 100644 index 0000000000..9acb89402a --- /dev/null +++ b/infra/relay/src/services/EnvironmentConnector.test.ts @@ -0,0 +1,583 @@ +import * as NodeCrypto from "node:crypto"; +import * as NodeCryptoLayer from "@effect/platform-node/NodeCrypto"; + +import type { + RelayCloudEnvironmentHealthProofPayload, + RelayCloudEnvironmentHealthRequest, + RelayCloudMintCredentialProofPayload, + RelayCloudMintCredentialRequest, + RelayEnvironmentHealthResponse, + RelayEnvironmentHealthResponseProofPayload, + RelayEnvironmentMintResponse, + RelayEnvironmentMintResponseProofPayload, +} from "@t3tools/contracts/relay"; +import { describe, expect, it } from "@effect/vitest"; +import * as DateTime from "effect/DateTime"; +import { RELAY_HEALTH_RESPONSE_TYP, RELAY_MINT_RESPONSE_TYP } from "@t3tools/shared/relayJwt"; +import * as Duration from "effect/Duration"; +import * as Effect from "effect/Effect"; +import * as Fiber from "effect/Fiber"; +import * as Layer from "effect/Layer"; +import * as Redacted from "effect/Redacted"; +import * as Result from "effect/Result"; +import * as TestClock from "effect/testing/TestClock"; +import { HttpClient, HttpClientRequest, HttpClientResponse } from "effect/unstable/http"; + +import * as EnvironmentLinks from "../persistence/EnvironmentLinks.ts"; +import * as RelayConfiguration from "../Config.ts"; +import * as EnvironmentConnector from "./EnvironmentConnector.ts"; + +const cloudKeyPair = NodeCrypto.generateKeyPairSync("ed25519", { + privateKeyEncoding: { format: "pem", type: "pkcs8" }, + publicKeyEncoding: { format: "pem", type: "spki" }, +}); + +const environmentKeyPair = NodeCrypto.generateKeyPairSync("ed25519", { + privateKeyEncoding: { format: "pem", type: "pkcs8" }, + publicKeyEncoding: { format: "pem", type: "spki" }, +}); + +const otherEnvironmentKeyPair = NodeCrypto.generateKeyPairSync("ed25519", { + privateKeyEncoding: { format: "pem", type: "pkcs8" }, + publicKeyEncoding: { format: "pem", type: "spki" }, +}); + +const settings = RelayConfiguration.RelayConfiguration.of({ + relayIssuer: "https://relay.example.test", + apns: { + environment: "sandbox", + teamId: "team-id", + keyId: "key-id", + privateKey: Redacted.make("private-key"), + bundleId: "com.t3tools.t3code.dev", + }, + apnsDeliveryJobSigningSecret: Redacted.make("job-secret"), + clerkSecretKey: Redacted.make("clerk-secret"), + cloudMintPrivateKey: Redacted.make(cloudKeyPair.privateKey), + cloudMintPublicKey: cloudKeyPair.publicKey, + managedEndpointBaseDomain: undefined, + cloudflareAccountId: undefined, + cloudflareZoneId: undefined, + cloudflareApiToken: undefined, +}); + +function signTestJwt(payload: object, typ: string, privateKey: string): string { + const header = Buffer.from(JSON.stringify({ alg: "EdDSA", typ })).toString("base64url"); + const encodedPayload = Buffer.from(JSON.stringify(payload)).toString("base64url"); + const input = `${header}.${encodedPayload}`; + return `${input}.${NodeCrypto.sign(null, Buffer.from(input), privateKey).toString("base64url")}`; +} + +function decodeRequestProof(proof: string): T { + const payload = proof.split(".")[1]; + if (!payload) throw new Error("Missing JWT payload."); + return JSON.parse(Buffer.from(payload, "base64url").toString("utf8")) as T; +} + +function signMintResponse( + request: RelayCloudMintCredentialRequest, + overrides: Partial = {}, + privateKey = environmentKeyPair.privateKey, +): RelayEnvironmentMintResponse { + const requestProof = decodeRequestProof(request.proof); + const payload = { + iss: `t3-env:${requestProof.environmentId}`, + aud: "https://relay.example.test", + sub: requestProof.environmentId, + jti: "mint-response-jti", + iat: requestProof.iat, + exp: requestProof.exp, + environmentId: requestProof.environmentId, + clientProofKeyThumbprint: requestProof.clientProofKeyThumbprint, + requestNonce: requestProof.nonce, + credential: "pairing_credential", + ...overrides, + } satisfies RelayEnvironmentMintResponseProofPayload; + return { + credential: payload.credential, + expiresAt: DateTime.formatIso(DateTime.makeUnsafe(payload.exp * 1_000)), + proof: signTestJwt(payload, RELAY_MINT_RESPONSE_TYP, privateKey), + }; +} + +function signHealthResponse( + request: RelayCloudEnvironmentHealthRequest, + privateKey = environmentKeyPair.privateKey, + overrides: Partial = {}, + payloadOverrides: Partial = {}, +): RelayEnvironmentHealthResponse { + const requestProof = decodeRequestProof(request.proof); + const payload = { + iss: `t3-env:${requestProof.environmentId}`, + aud: "https://relay.example.test", + sub: requestProof.environmentId, + jti: "health-response-jti", + iat: requestProof.iat, + exp: requestProof.exp, + environmentId: requestProof.environmentId, + requestNonce: requestProof.nonce, + status: "online", + descriptor: { + environmentId: requestProof.environmentId, + label: "Connector Test Environment", + platform: { os: "darwin", arch: "arm64" }, + serverVersion: "0.0.0-test", + capabilities: { repositoryIdentity: true }, + }, + checkedAt: DateTime.formatIso(DateTime.makeUnsafe(requestProof.iat * 1_000)), + ...payloadOverrides, + } satisfies RelayEnvironmentHealthResponseProofPayload; + return { + environmentId: payload.environmentId, + status: "online", + descriptor: payload.descriptor, + checkedAt: payload.checkedAt, + proof: signTestJwt(payload, RELAY_HEALTH_RESPONSE_TYP, privateKey), + ...overrides, + }; +} + +function connectorTestLayer( + execute: ( + request: HttpClientRequest.HttpClientRequest, + ) => Effect.Effect, + options?: { + readonly links?: EnvironmentLinks.EnvironmentLinksShape; + }, +) { + return EnvironmentConnector.layer.pipe( + Layer.provide(NodeCryptoLayer.layer), + Layer.provide(Layer.succeed(EnvironmentLinks.EnvironmentLinks, options?.links ?? makeLinks())), + Layer.provide(Layer.succeed(RelayConfiguration.RelayConfiguration, settings)), + Layer.provide(Layer.succeed(HttpClient.HttpClient, HttpClient.make(execute))), + ); +} + +function makeLinks( + overrides: Partial = {}, +): EnvironmentLinks.EnvironmentLinksShape { + return { + upsert: () => Effect.void, + listUsersForEnvironment: () => Effect.succeed([]), + listDeliveryUsersForEnvironment: () => Effect.succeed([]), + listPublicKeysForEnvironment: () => Effect.succeed([environmentKeyPair.publicKey]), + listForUser: () => Effect.succeed([]), + getForUser: () => + Effect.succeed({ + environmentId: "env-connector-test" as never, + label: "Connector Test Environment", + endpoint: { + httpBaseUrl: "https://env.example.test/", + wsBaseUrl: "wss://env.example.test/", + providerKind: "manual", + }, + linkedAt: "2026-05-25T00:00:00.000Z", + environmentPublicKey: environmentKeyPair.publicKey, + ...overrides, + }), + revokeForUser: () => Effect.succeed(false), + }; +} + +describe("EnvironmentConnector", () => { + it.effect("checks linked environment health through the managed endpoint", () => { + const seenUrls: Array = []; + const seenProofs: Array = []; + const execute = (request: HttpClientRequest.HttpClientRequest) => + Effect.sync(() => { + const healthRequest = JSON.parse( + request.body._tag === "Uint8Array" ? new TextDecoder().decode(request.body.body) : "{}", + ) as RelayCloudEnvironmentHealthRequest; + seenUrls.push(request.url); + seenProofs.push(decodeRequestProof(healthRequest.proof)); + return HttpClientResponse.fromWeb( + request, + Response.json(signHealthResponse(healthRequest), { status: 200 }), + ); + }); + + return Effect.gen(function* () { + const connector = yield* EnvironmentConnector.EnvironmentConnector; + const result = yield* connector.status({ + userId: "user_123", + environmentId: "env-connector-test", + }); + + expect(seenUrls).toEqual(["https://env.example.test/api/t3-cloud/health"]); + expect(seenProofs[0]).toMatchObject({ + iss: "https://relay.example.test", + aud: "t3-env:env-connector-test", + sub: "user_123", + environmentId: "env-connector-test", + scope: ["environment:status"], + }); + expect(result).toMatchObject({ + environmentId: "env-connector-test", + status: "online", + descriptor: { + environmentId: "env-connector-test", + label: "Connector Test Environment", + }, + }); + }).pipe(Effect.provide(connectorTestLayer(execute))); + }); + + it.effect("rejects signed health responses with stale checkedAt timestamps", () => { + const execute = (request: HttpClientRequest.HttpClientRequest) => + Effect.sync(() => { + const healthRequest = JSON.parse( + request.body._tag === "Uint8Array" ? new TextDecoder().decode(request.body.body) : "{}", + ) as RelayCloudEnvironmentHealthRequest; + return HttpClientResponse.fromWeb( + request, + Response.json( + signHealthResponse( + healthRequest, + environmentKeyPair.privateKey, + {}, + { + checkedAt: "2026-05-24T00:00:00.000Z", + }, + ), + { status: 200 }, + ), + ); + }); + + return Effect.gen(function* () { + const connector = yield* EnvironmentConnector.EnvironmentConnector; + const result = yield* Effect.exit( + connector.status({ + userId: "user_123", + environmentId: "env-connector-test", + }), + ); + + expect(result._tag).toBe("Failure"); + if (result._tag === "Failure") { + expect(result.cause.toString()).toContain("EnvironmentMintResponseInvalid"); + } + }).pipe(Effect.provide(connectorTestLayer(execute))); + }); + + it.effect("reports offline status when the managed endpoint health request fails", () => { + const execute = (request: HttpClientRequest.HttpClientRequest) => + Effect.succeed( + HttpClientResponse.fromWeb( + request, + Response.json( + { + _tag: "EnvironmentHttpInternalServerError", + message: "Environment is unavailable.", + }, + { status: 500 }, + ), + ), + ); + + return Effect.gen(function* () { + const connector = yield* EnvironmentConnector.EnvironmentConnector; + const result = yield* connector.status({ + userId: "user_123", + environmentId: "env-connector-test", + }); + + expect(result).toMatchObject({ + environmentId: "env-connector-test", + status: "offline", + error: "Managed endpoint health request failed: Environment is unavailable.", + }); + }).pipe(Effect.provide(connectorTestLayer(execute))); + }); + + it.effect("rejects health responses with a mismatched top-level environment id", () => { + const execute = (request: HttpClientRequest.HttpClientRequest) => + Effect.sync(() => { + const healthRequest = JSON.parse( + request.body._tag === "Uint8Array" ? new TextDecoder().decode(request.body.body) : "{}", + ) as RelayCloudEnvironmentHealthRequest; + return HttpClientResponse.fromWeb( + request, + Response.json( + signHealthResponse(healthRequest, environmentKeyPair.privateKey, { + environmentId: "other-env" as RelayEnvironmentHealthResponse["environmentId"], + }), + { status: 200 }, + ), + ); + }); + + return Effect.gen(function* () { + const connector = yield* EnvironmentConnector.EnvironmentConnector; + const result = yield* Effect.exit( + connector.status({ + userId: "user_123", + environmentId: "env-connector-test", + }), + ); + + expect(result._tag).toBe("Failure"); + if (result._tag === "Failure") { + expect(result.cause.toString()).toContain("EnvironmentMintResponseInvalid"); + } + }).pipe(Effect.provide(connectorTestLayer(execute))); + }); + + it.effect("rejects health responses with an unsigned top-level descriptor mutation", () => { + const execute = (request: HttpClientRequest.HttpClientRequest) => + Effect.sync(() => { + const healthRequest = JSON.parse( + request.body._tag === "Uint8Array" ? new TextDecoder().decode(request.body.body) : "{}", + ) as RelayCloudEnvironmentHealthRequest; + const response = signHealthResponse(healthRequest); + return HttpClientResponse.fromWeb( + request, + Response.json( + { + ...response, + descriptor: { + ...response.descriptor, + label: "Tampered Environment Label", + }, + } satisfies RelayEnvironmentHealthResponse, + { status: 200 }, + ), + ); + }); + + return Effect.gen(function* () { + const connector = yield* EnvironmentConnector.EnvironmentConnector; + const result = yield* Effect.exit( + connector.status({ + userId: "user_123", + environmentId: "env-connector-test", + }), + ); + + expect(result._tag).toBe("Failure"); + if (result._tag === "Failure") { + expect(result.cause.toString()).toContain("EnvironmentMintResponseInvalid"); + } + }).pipe(Effect.provide(connectorTestLayer(execute))); + }); + + it.effect("rejects health responses when the linked environment public key is malformed", () => { + const execute = (request: HttpClientRequest.HttpClientRequest) => + Effect.sync(() => { + const healthRequest = JSON.parse( + request.body._tag === "Uint8Array" ? new TextDecoder().decode(request.body.body) : "{}", + ) as RelayCloudEnvironmentHealthRequest; + return HttpClientResponse.fromWeb( + request, + Response.json(signHealthResponse(healthRequest), { status: 200 }), + ); + }); + + return Effect.gen(function* () { + const connector = yield* EnvironmentConnector.EnvironmentConnector; + const result = yield* Effect.exit( + connector.status({ + userId: "user_123", + environmentId: "env-connector-test", + }), + ); + + expect(result._tag).toBe("Failure"); + if (result._tag === "Failure") { + expect(result.cause.toString()).toContain("EnvironmentMintResponseInvalid"); + } + }).pipe( + Effect.provide( + connectorTestLayer(execute, { + links: makeLinks({ + environmentPublicKey: "not a pem public key", + }), + }), + ), + ); + }); + + it.effect("mints a one-time environment credential through the linked endpoint", () => { + const seenUrls: Array = []; + const seenProofs: Array = []; + const execute = (request: HttpClientRequest.HttpClientRequest) => + Effect.sync(() => { + const mintRequest = JSON.parse( + request.body._tag === "Uint8Array" ? new TextDecoder().decode(request.body.body) : "{}", + ) as RelayCloudMintCredentialRequest; + seenUrls.push(request.url); + seenProofs.push(decodeRequestProof(mintRequest.proof)); + return HttpClientResponse.fromWeb( + request, + Response.json(signMintResponse(mintRequest), { status: 200 }), + ); + }); + + return Effect.gen(function* () { + const connector = yield* EnvironmentConnector.EnvironmentConnector; + const result = yield* connector.connect({ + userId: "user_123", + environmentId: "env-connector-test", + clientProofKeyThumbprint: "client-proof-key-thumbprint", + deviceId: "device-123", + }); + + expect(seenUrls).toEqual(["https://env.example.test/api/t3-cloud/mint-credential"]); + expect(seenProofs[0]).toMatchObject({ + iss: "https://relay.example.test", + aud: "t3-env:env-connector-test", + sub: "user_123", + environmentId: "env-connector-test", + clientProofKeyThumbprint: "client-proof-key-thumbprint", + cnf: { jkt: "client-proof-key-thumbprint" }, + deviceId: "device-123", + scope: ["environment:connect"], + }); + expect(result).toMatchObject({ + environmentId: "env-connector-test", + credential: "pairing_credential", + endpoint: { + httpBaseUrl: "https://env.example.test/", + wsBaseUrl: "wss://env.example.test/", + }, + }); + }).pipe(Effect.provide(connectorTestLayer(execute))); + }); + + it.effect("only accepts mint responses signed by the user's linked environment key", () => { + const execute = (request: HttpClientRequest.HttpClientRequest) => + Effect.sync(() => { + const mintRequest = JSON.parse( + request.body._tag === "Uint8Array" ? new TextDecoder().decode(request.body.body) : "{}", + ) as RelayCloudMintCredentialRequest; + return HttpClientResponse.fromWeb( + request, + Response.json(signMintResponse(mintRequest, {}, otherEnvironmentKeyPair.privateKey), { + status: 200, + }), + ); + }); + + return Effect.gen(function* () { + const connector = yield* EnvironmentConnector.EnvironmentConnector; + const result = yield* Effect.exit( + connector.connect({ + userId: "user_123", + environmentId: "env-connector-test", + clientProofKeyThumbprint: "client-proof-key-thumbprint", + }), + ); + + expect(result._tag).toBe("Failure"); + if (result._tag === "Failure") { + expect(result.cause.toString()).toContain("EnvironmentMintResponseInvalid"); + } + }).pipe(Effect.provide(connectorTestLayer(execute))); + }); + + it.effect("rejects mint responses when the linked environment public key is malformed", () => { + const execute = (request: HttpClientRequest.HttpClientRequest) => + Effect.sync(() => { + const mintRequest = JSON.parse( + request.body._tag === "Uint8Array" ? new TextDecoder().decode(request.body.body) : "{}", + ) as RelayCloudMintCredentialRequest; + return HttpClientResponse.fromWeb( + request, + Response.json(signMintResponse(mintRequest), { status: 200 }), + ); + }); + + return Effect.gen(function* () { + const connector = yield* EnvironmentConnector.EnvironmentConnector; + const result = yield* Effect.exit( + connector.connect({ + userId: "user_123", + environmentId: "env-connector-test", + clientProofKeyThumbprint: "client-proof-key-thumbprint", + }), + ); + + expect(result._tag).toBe("Failure"); + if (result._tag === "Failure") { + expect(result.cause.toString()).toContain("EnvironmentMintResponseInvalid"); + } + }).pipe( + Effect.provide( + connectorTestLayer(execute, { + links: makeLinks({ + environmentPublicKey: "not a pem public key", + }), + }), + ), + ); + }); + + it.effect("rejects environment mint responses with an overlong credential window", () => { + const execute = (request: HttpClientRequest.HttpClientRequest) => + Effect.sync(() => { + const mintRequest = JSON.parse( + request.body._tag === "Uint8Array" ? new TextDecoder().decode(request.body.body) : "{}", + ) as RelayCloudMintCredentialRequest; + return HttpClientResponse.fromWeb( + request, + Response.json( + { ...signMintResponse(mintRequest), expiresAt: "2999-01-01T00:00:00.000Z" }, + { status: 200 }, + ), + ); + }); + + return Effect.gen(function* () { + const connector = yield* EnvironmentConnector.EnvironmentConnector; + const result = yield* Effect.exit( + connector.connect({ + userId: "user_123", + environmentId: "env-connector-test", + clientProofKeyThumbprint: "client-proof-key-thumbprint", + }), + ); + + expect(result._tag).toBe("Failure"); + if (result._tag === "Failure") { + expect(result.cause.toString()).toContain("EnvironmentMintResponseInvalid"); + } + }).pipe(Effect.provide(connectorTestLayer(execute))); + }); + + it.effect("times out hung managed endpoint mint requests", () => { + let resolveRequestStarted: (() => void) | undefined; + const requestStarted = new Promise((resolve) => { + resolveRequestStarted = () => resolve(); + }); + const execute = () => + Effect.sync(() => { + resolveRequestStarted?.(); + }).pipe(Effect.andThen(Effect.never as Effect.Effect)); + + return Effect.gen(function* () { + const connector = yield* EnvironmentConnector.EnvironmentConnector; + const resultFiber = yield* connector + .connect({ + userId: "user_123", + environmentId: "env-connector-test", + clientProofKeyThumbprint: "client-proof-key-thumbprint", + }) + .pipe(Effect.result, Effect.forkScoped); + + yield* Effect.promise(() => requestStarted); + yield* TestClock.adjust( + Duration.millis(EnvironmentConnector.ENVIRONMENT_MINT_REQUEST_TIMEOUT_MS), + ); + const result = yield* Fiber.join(resultFiber); + + expect(Result.isFailure(result)).toBe(true); + if (Result.isFailure(result)) { + expect(result.failure._tag).toBe("EnvironmentMintRequestTimedOut"); + expect(result.failure).toMatchObject({ + environmentId: "env-connector-test", + timeoutMs: EnvironmentConnector.ENVIRONMENT_MINT_REQUEST_TIMEOUT_MS, + }); + } + }).pipe(Effect.provide(Layer.merge(TestClock.layer(), connectorTestLayer(execute)))); + }); +}); diff --git a/infra/relay/src/services/EnvironmentConnector.ts b/infra/relay/src/services/EnvironmentConnector.ts new file mode 100644 index 0000000000..623b5099bb --- /dev/null +++ b/infra/relay/src/services/EnvironmentConnector.ts @@ -0,0 +1,397 @@ +import { + EnvironmentHttpBadRequestError, + EnvironmentHttpConflictError, + EnvironmentHttpForbiddenError, + EnvironmentHttpInternalServerError, + EnvironmentHttpUnauthorizedError, +} from "@t3tools/contracts"; +import { makeEnvironmentHttpApiClient } from "@t3tools/client-runtime"; +import { + RelayCloudEnvironmentHealthProofPayload, + RelayEnvironmentHealthResponse, + RelayEnvironmentHealthResponseProofPayload, + RelayEnvironmentMintResponse, + RelayEnvironmentMintResponseProofPayload, + RelayCloudMintCredentialProofPayload, + type RelayEnvironmentConnectResponse, + type RelayEnvironmentStatusResponse, +} from "@t3tools/contracts/relay"; +import { + normalizeRelayIssuer, + RELAY_HEALTH_REQUEST_TYP, + RELAY_HEALTH_RESPONSE_TYP, + RELAY_MINT_REQUEST_TYP, + RELAY_MINT_RESPONSE_TYP, + signRelayJwt, + verifyRelayJwt, +} from "@t3tools/shared/relayJwt"; +import { stableStringify } from "@t3tools/shared/relaySigning"; +import * as Context from "effect/Context"; +import * as Crypto from "effect/Crypto"; +import * as Data from "effect/Data"; +import * as DateTime from "effect/DateTime"; +import * as Duration from "effect/Duration"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import * as Option from "effect/Option"; +import * as Redacted from "effect/Redacted"; +import * as Schema from "effect/Schema"; +import { HttpClient } from "effect/unstable/http"; + +import * as EnvironmentLinks from "../persistence/EnvironmentLinks.ts"; +import * as RelayConfiguration from "../Config.ts"; +import { withUserId } from "../telemetry.ts"; + +export class EnvironmentConnectNotAuthorized extends Data.TaggedError( + "EnvironmentConnectNotAuthorized", +)<{ + readonly environmentId: string; +}> {} + +export class EnvironmentMintRequestFailed extends Data.TaggedError("EnvironmentMintRequestFailed")<{ + readonly cause: unknown; +}> {} + +export class EnvironmentMintRequestTimedOut extends Data.TaggedError( + "EnvironmentMintRequestTimedOut", +)<{ + readonly environmentId: string; + readonly timeoutMs: number; +}> {} + +export class EnvironmentMintResponseInvalid extends Data.TaggedError( + "EnvironmentMintResponseInvalid", +)<{ + readonly environmentId: string; +}> {} + +export type EnvironmentConnectorError = + | EnvironmentConnectNotAuthorized + | EnvironmentMintRequestFailed + | EnvironmentMintRequestTimedOut + | EnvironmentMintResponseInvalid + | EnvironmentLinks.EnvironmentLinkLookupPersistenceError; + +export const ENVIRONMENT_MINT_REQUEST_TIMEOUT_MS = 10_000; +const ENVIRONMENT_HEALTH_CLOCK_SKEW_MILLIS = 60 * 1_000; + +export interface EnvironmentConnectorShape { + readonly connect: (input: { + readonly userId: string; + readonly environmentId: string; + readonly clientProofKeyThumbprint: string; + readonly deviceId?: string; + }) => Effect.Effect; + readonly status: (input: { + readonly userId: string; + readonly environmentId: string; + }) => Effect.Effect; +} + +export class EnvironmentConnector extends Context.Service< + EnvironmentConnector, + EnvironmentConnectorShape +>()("EnvironmentConnector") {} + +const decodeMintResponseProof = Schema.decodeUnknownEffect( + RelayEnvironmentMintResponseProofPayload, +); +const decodeHealthResponseProof = Schema.decodeUnknownEffect( + RelayEnvironmentHealthResponseProofPayload, +); +const isEnvironmentHealthError = Schema.is( + Schema.Union([ + EnvironmentHttpBadRequestError, + EnvironmentHttpUnauthorizedError, + EnvironmentHttpForbiddenError, + EnvironmentHttpConflictError, + EnvironmentHttpInternalServerError, + ]), +); + +function environmentHealthRequestFailureMessage(cause: unknown): string { + return isEnvironmentHealthError(cause) + ? `Managed endpoint health request failed: ${cause.message}` + : "Managed endpoint health request failed."; +} + +const verifyWithEnvironmentKeys = Effect.fnUntraced(function* (input: { + readonly token: string; + readonly typ: string; + readonly issuer: string; + readonly audience: string; + readonly nowEpochSeconds: number; + readonly environmentPublicKeys: ReadonlyArray; + readonly decodePayload: (input: unknown) => Effect.Effect; +}) { + const { decodePayload, ...rest } = input; + for (const publicKey of input.environmentPublicKeys) { + const proof = yield* verifyRelayJwt({ ...rest, publicKey }).pipe( + Effect.flatMap(decodePayload), + Effect.option, + ); + if (Option.isSome(proof)) { + return proof.value; + } + // A linked environment can have rotated keys; try the remaining active keys. + } + return null; +}); + +function verifyEnvironmentResponse(input: { + readonly response: typeof RelayEnvironmentMintResponse.Type; + readonly environmentId: string; + readonly requestNonce: string; + readonly clientProofKeyThumbprint: string; + readonly environmentPublicKeys: ReadonlyArray; + readonly relayIssuer: string; + readonly nowEpochSeconds: number; +}) { + return verifyWithEnvironmentKeys({ + token: input.response.proof, + typ: RELAY_MINT_RESPONSE_TYP, + issuer: `t3-env:${input.environmentId}`, + audience: normalizeRelayIssuer(input.relayIssuer), + nowEpochSeconds: input.nowEpochSeconds, + environmentPublicKeys: input.environmentPublicKeys, + decodePayload: decodeMintResponseProof, + }).pipe( + Effect.map( + (proof) => + proof !== null && + proof.environmentId === input.environmentId && + proof.requestNonce === input.requestNonce && + proof.clientProofKeyThumbprint === input.clientProofKeyThumbprint && + proof.credential === input.response.credential && + Option.match(DateTime.make(input.response.expiresAt), { + onNone: () => false, + onSome: (expiresAt) => Math.floor(expiresAt.epochMilliseconds / 1_000) === proof.exp, + }), + ), + ); +} + +function verifyEnvironmentHealthResponse(input: { + readonly response: typeof RelayEnvironmentHealthResponse.Type; + readonly environmentId: string; + readonly requestNonce: string; + readonly requestIssuedAt: DateTime.DateTime; + readonly environmentPublicKeys: ReadonlyArray; + readonly relayIssuer: string; + readonly now: DateTime.DateTime; +}) { + return verifyWithEnvironmentKeys({ + token: input.response.proof, + typ: RELAY_HEALTH_RESPONSE_TYP, + issuer: `t3-env:${input.environmentId}`, + audience: normalizeRelayIssuer(input.relayIssuer), + nowEpochSeconds: Math.floor(input.now.epochMilliseconds / 1_000), + environmentPublicKeys: input.environmentPublicKeys, + decodePayload: decodeHealthResponseProof, + }).pipe( + Effect.map((proof) => { + if ( + proof === null || + input.response.environmentId !== input.environmentId || + proof.environmentId !== input.environmentId || + proof.requestNonce !== input.requestNonce || + proof.status !== input.response.status || + proof.checkedAt !== input.response.checkedAt || + stableStringify(proof.descriptor) !== stableStringify(input.response.descriptor) + ) { + return false; + } + const checkedAt = DateTime.make(input.response.checkedAt); + if (Option.isNone(checkedAt)) { + return false; + } + return ( + checkedAt.value.epochMilliseconds >= + input.requestIssuedAt.epochMilliseconds - ENVIRONMENT_HEALTH_CLOCK_SKEW_MILLIS && + checkedAt.value.epochMilliseconds <= + input.now.epochMilliseconds + ENVIRONMENT_HEALTH_CLOCK_SKEW_MILLIS + ); + }), + ); +} + +const make = Effect.gen(function* () { + const links = yield* EnvironmentLinks.EnvironmentLinks; + const settings = yield* RelayConfiguration.RelayConfiguration; + const httpClient = yield* HttpClient.HttpClient; + const crypto = yield* Crypto.Crypto; + const relayIssuer = normalizeRelayIssuer(settings.relayIssuer); + const makeEnvironmentClient = (httpBaseUrl: string) => + makeEnvironmentHttpApiClient(httpBaseUrl).pipe( + Effect.provideService(HttpClient.HttpClient, httpClient), + ); + + return EnvironmentConnector.of({ + status: Effect.fn("relay.environment_connector.status")( + function* (input) { + yield* Effect.annotateCurrentSpan({ + "relay.environment_id": input.environmentId, + "relay.operation": "status", + }); + const link = yield* links.getForUser(input); + if (!link) { + return yield* new EnvironmentConnectNotAuthorized({ environmentId: input.environmentId }); + } + const now = yield* DateTime.now; + const expiresAt = DateTime.add(now, { minutes: 2 }); + const nonce = yield* crypto.randomUUIDv4.pipe( + Effect.mapError((cause) => new EnvironmentMintRequestFailed({ cause })), + ); + const payload = { + iss: relayIssuer, + aud: `t3-env:${link.environmentId}`, + sub: input.userId, + jti: yield* crypto.randomUUIDv4.pipe( + Effect.mapError((cause) => new EnvironmentMintRequestFailed({ cause })), + ), + iat: Math.floor(now.epochMilliseconds / 1_000), + exp: Math.floor(expiresAt.epochMilliseconds / 1_000), + environmentId: link.environmentId, + nonce, + scope: ["environment:status"], + } satisfies typeof RelayCloudEnvironmentHealthProofPayload.Type; + const proof = yield* signRelayJwt({ + privateKey: Redacted.value(settings.cloudMintPrivateKey), + typ: RELAY_HEALTH_REQUEST_TYP, + payload, + }).pipe(Effect.mapError((cause) => new EnvironmentMintRequestFailed({ cause }))); + const checkedAt = DateTime.formatIso(now); + const environmentClient = yield* makeEnvironmentClient(link.endpoint.httpBaseUrl); + const responseOption = yield* environmentClient.cloud.health({ payload: { proof } }).pipe( + Effect.match({ + onFailure: (cause) => ({ _tag: "Failure" as const, cause }), + onSuccess: (response) => ({ _tag: "Success" as const, response }), + }), + Effect.timeoutOption(Duration.millis(ENVIRONMENT_MINT_REQUEST_TIMEOUT_MS)), + ); + if (Option.isNone(responseOption)) { + return { + environmentId: link.environmentId, + endpoint: link.endpoint, + status: "offline" as const, + checkedAt, + error: "Managed endpoint health request timed out.", + }; + } + if (responseOption.value._tag === "Failure") { + return { + environmentId: link.environmentId, + endpoint: link.endpoint, + status: "offline" as const, + checkedAt, + error: environmentHealthRequestFailureMessage(responseOption.value.cause), + }; + } + const decoded = responseOption.value.response; + const verified = yield* verifyEnvironmentHealthResponse({ + response: decoded, + environmentId: input.environmentId, + requestNonce: nonce, + requestIssuedAt: now, + environmentPublicKeys: [link.environmentPublicKey], + relayIssuer, + now: yield* DateTime.now, + }); + if (!verified) { + return yield* new EnvironmentMintResponseInvalid({ environmentId: input.environmentId }); + } + return { + environmentId: link.environmentId, + endpoint: link.endpoint, + status: "online" as const, + checkedAt: decoded.checkedAt, + descriptor: decoded.descriptor, + }; + }, + (effect, input) => effect.pipe(withUserId(input.userId)), + ), + connect: Effect.fn("relay.environment_connector.connect")( + function* (input) { + yield* Effect.annotateCurrentSpan({ + "relay.environment_id": input.environmentId, + "relay.operation": "connect", + "relay.connect.has_device_id": input.deviceId !== undefined, + ...(input.deviceId ? { "relay.mobile.device_id": input.deviceId } : {}), + }); + if (input.clientProofKeyThumbprint.trim().length === 0) { + return yield* new EnvironmentConnectNotAuthorized({ environmentId: input.environmentId }); + } + const link = yield* links.getForUser(input); + if (!link) { + return yield* new EnvironmentConnectNotAuthorized({ environmentId: input.environmentId }); + } + const now = yield* DateTime.now; + const expiresAt = DateTime.add(now, { minutes: 2 }); + const nonce = yield* crypto.randomUUIDv4.pipe( + Effect.mapError((cause) => new EnvironmentMintRequestFailed({ cause })), + ); + const payload = { + iss: relayIssuer, + aud: `t3-env:${link.environmentId}`, + sub: input.userId, + jti: yield* crypto.randomUUIDv4.pipe( + Effect.mapError((cause) => new EnvironmentMintRequestFailed({ cause })), + ), + iat: Math.floor(now.epochMilliseconds / 1_000), + exp: Math.floor(expiresAt.epochMilliseconds / 1_000), + environmentId: link.environmentId, + clientProofKeyThumbprint: input.clientProofKeyThumbprint, + cnf: { jkt: input.clientProofKeyThumbprint }, + ...(input.deviceId ? { deviceId: input.deviceId } : {}), + nonce, + scope: ["environment:connect"], + } satisfies typeof RelayCloudMintCredentialProofPayload.Type; + const proof = yield* signRelayJwt({ + privateKey: Redacted.value(settings.cloudMintPrivateKey), + typ: RELAY_MINT_REQUEST_TYP, + payload, + }).pipe(Effect.mapError((cause) => new EnvironmentMintRequestFailed({ cause }))); + const environmentClient = yield* makeEnvironmentClient(link.endpoint.httpBaseUrl); + const decoded = yield* environmentClient.cloud + .t3MintCredential({ payload: { proof } }) + .pipe( + Effect.mapError((cause) => new EnvironmentMintRequestFailed({ cause })), + Effect.timeoutOption(Duration.millis(ENVIRONMENT_MINT_REQUEST_TIMEOUT_MS)), + Effect.flatMap( + Option.match({ + onNone: () => + Effect.fail( + new EnvironmentMintRequestTimedOut({ + environmentId: input.environmentId, + timeoutMs: ENVIRONMENT_MINT_REQUEST_TIMEOUT_MS, + }), + ), + onSome: Effect.succeed, + }), + ), + ); + const verified = yield* verifyEnvironmentResponse({ + response: decoded, + environmentId: input.environmentId, + requestNonce: nonce, + clientProofKeyThumbprint: input.clientProofKeyThumbprint, + environmentPublicKeys: [link.environmentPublicKey], + relayIssuer, + nowEpochSeconds: Math.floor(now.epochMilliseconds / 1_000), + }); + if (!verified) { + return yield* new EnvironmentMintResponseInvalid({ environmentId: input.environmentId }); + } + return { + environmentId: link.environmentId, + endpoint: link.endpoint, + credential: decoded.credential, + expiresAt: decoded.expiresAt, + }; + }, + (effect, input) => effect.pipe(withUserId(input.userId)), + ), + }); +}); + +export const layer = Layer.effect(EnvironmentConnector, make); diff --git a/infra/relay/src/services/EnvironmentLinker.test.ts b/infra/relay/src/services/EnvironmentLinker.test.ts new file mode 100644 index 0000000000..2b3dbfee45 --- /dev/null +++ b/infra/relay/src/services/EnvironmentLinker.test.ts @@ -0,0 +1,203 @@ +import * as NodeCrypto from "node:crypto"; +import type { + RelayEnvironmentLinkProofPayload, + RelayEnvironmentLinkRequest, +} from "@t3tools/contracts/relay"; +import { RELAY_LINK_PROOF_TYP } from "@t3tools/shared/relayJwt"; +import { describe, expect, it } from "@effect/vitest"; +import * as DateTime from "effect/DateTime"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import * as Redacted from "effect/Redacted"; +import * as Result from "effect/Result"; + +import * as DpopProofs from "../persistence/DpopProofs.ts"; +import * as EnvironmentCredentials from "../persistence/EnvironmentCredentials.ts"; +import * as EnvironmentLinks from "../persistence/EnvironmentLinks.ts"; +import * as RelayConfiguration from "../Config.ts"; +import * as EnvironmentLinker from "./EnvironmentLinker.ts"; +import * as ManagedEndpointProvider from "./ManagedEndpointProvider.ts"; +import { issueLinkChallengeToken } from "../relayTokens.ts"; + +const relayKeyPair = NodeCrypto.generateKeyPairSync("ed25519", { + privateKeyEncoding: { format: "pem", type: "pkcs8" }, + publicKeyEncoding: { format: "pem", type: "spki" }, +}); +const environmentKeyPair = NodeCrypto.generateKeyPairSync("ed25519", { + privateKeyEncoding: { format: "pem", type: "pkcs8" }, + publicKeyEncoding: { format: "pem", type: "spki" }, +}); +const config = RelayConfiguration.RelayConfiguration.of({ + relayIssuer: "https://relay.example.test", + apns: { + environment: "sandbox", + teamId: "team-id", + keyId: "key-id", + privateKey: Redacted.make("private-key"), + bundleId: "com.t3tools.t3code.dev", + }, + apnsDeliveryJobSigningSecret: Redacted.make("job-secret"), + clerkSecretKey: Redacted.make("clerk-secret"), + cloudMintPrivateKey: Redacted.make(relayKeyPair.privateKey), + cloudMintPublicKey: relayKeyPair.publicKey, + managedEndpointBaseDomain: undefined, + cloudflareAccountId: undefined, + cloudflareZoneId: undefined, + cloudflareApiToken: undefined, +}); + +function signTestJwt(payload: object, typ: string, privateKey: string): string { + const header = Buffer.from(JSON.stringify({ alg: "EdDSA", typ })).toString("base64url"); + const encodedPayload = Buffer.from(JSON.stringify(payload)).toString("base64url"); + const signingInput = `${header}.${encodedPayload}`; + return `${signingInput}.${NodeCrypto.sign(null, Buffer.from(signingInput), privateKey).toString("base64url")}`; +} + +const makeRequest = Effect.gen(function* () { + const now = yield* DateTime.now; + const expiresAt = DateTime.add(now, { minutes: 5 }); + const challenge = yield* issueLinkChallengeToken({ + config, + userId: "user_123", + request: { + notificationsEnabled: true, + liveActivitiesEnabled: true, + managedTunnelsEnabled: true, + }, + jti: "challenge-jti", + issuedAtEpochSeconds: Math.floor(now.epochMilliseconds / 1_000), + expiresAtEpochSeconds: Math.floor(expiresAt.epochMilliseconds / 1_000), + }); + const payload = { + iss: "t3-env:env-link-test", + aud: "https://relay.example.test", + sub: "env-link-test", + jti: "link-proof-jti", + iat: Math.floor(now.epochMilliseconds / 1_000), + exp: Math.floor(expiresAt.epochMilliseconds / 1_000), + challenge, + environmentId: "env-link-test" as RelayEnvironmentLinkProofPayload["environmentId"], + descriptor: { + environmentId: "env-link-test" as RelayEnvironmentLinkProofPayload["environmentId"], + label: "Link Test Environment", + platform: { os: "darwin", arch: "arm64" }, + serverVersion: "0.0.0-test", + capabilities: { repositoryIdentity: true }, + }, + environmentPublicKey: environmentKeyPair.publicKey.trim(), + endpoint: { + httpBaseUrl: "https://env.example.test/", + wsBaseUrl: "wss://env.example.test/", + providerKind: "manual", + }, + origin: { localHttpHost: "127.0.0.1", localHttpPort: 3773 }, + scopes: ["agent_activity_notifications", "managed_tunnels"], + } satisfies RelayEnvironmentLinkProofPayload; + return { + request: { + proof: signTestJwt(payload, RELAY_LINK_PROOF_TYP, environmentKeyPair.privateKey), + notificationsEnabled: true, + liveActivitiesEnabled: true, + managedTunnelsEnabled: false, + } satisfies RelayEnvironmentLinkRequest, + payload, + }; +}); + +function testLayer(input?: { + readonly upsert?: EnvironmentLinks.EnvironmentLinksShape["upsert"]; + readonly consume?: DpopProofs.DpopProofReplayShape["consume"]; +}) { + return EnvironmentLinker.layer.pipe( + Layer.provide( + Layer.mergeAll( + Layer.succeed(RelayConfiguration.RelayConfiguration, config), + Layer.succeed(DpopProofs.DpopProofReplay, { + consume: input?.consume ?? (() => Effect.succeed(true)), + pruneExpired: Effect.void, + }), + Layer.succeed(EnvironmentLinks.EnvironmentLinks, { + upsert: input?.upsert ?? (() => Effect.void), + listUsersForEnvironment: () => Effect.succeed([]), + listDeliveryUsersForEnvironment: () => Effect.succeed([]), + listPublicKeysForEnvironment: () => Effect.succeed([]), + listForUser: () => Effect.succeed([]), + getForUser: () => Effect.succeed(null), + revokeForUser: () => Effect.succeed(false), + }), + Layer.succeed(EnvironmentCredentials.EnvironmentCredentials, { + create: () => Effect.succeed("t3env_credential_secret"), + authenticate: () => Effect.succeedNone, + revokeForEnvironmentPublicKey: () => Effect.succeed(false), + }), + Layer.succeed(ManagedEndpointProvider.ManagedEndpointProvider, { + provision: () => + Effect.succeed({ + endpoint: { + httpBaseUrl: "https://managed.example.test/", + wsBaseUrl: "wss://managed.example.test/ws", + providerKind: "cloudflare_tunnel", + }, + runtime: { providerKind: "cloudflare_tunnel", connectorToken: "connector-token" }, + }), + }), + ), + ), + ); +} + +describe("EnvironmentLinker", () => { + it.effect("uses verified JWT claims when linking an environment", () => { + let persistedEnvironmentId: string | null = null; + return Effect.gen(function* () { + const { request, payload } = yield* makeRequest; + const linker = yield* EnvironmentLinker.EnvironmentLinker; + const result = yield* linker.link({ userId: "user_123", request }); + expect(result.environmentId).toBe(payload.environmentId); + expect(result.environmentCredential).toBe("t3env_credential_secret"); + expect(persistedEnvironmentId).toBe(payload.environmentId); + }).pipe( + Effect.provide( + testLayer({ + upsert: (input) => + Effect.sync(() => { + persistedEnvironmentId = input.proof.environmentId; + }), + }), + ), + ); + }); + + it.effect("rejects a tampered compact proof before persistence", () => { + let persisted = false; + return Effect.gen(function* () { + const { request } = yield* makeRequest; + const segments = request.proof.split("."); + const signature = segments[2]!; + segments[2] = `${signature.startsWith("A") ? "B" : "A"}${signature.slice(1)}`; + const tampered = { ...request, proof: segments.join(".") }; + const linker = yield* EnvironmentLinker.EnvironmentLinker; + const result = yield* Effect.result(linker.link({ userId: "user_123", request: tampered })); + expect(Result.isFailure(result)).toBe(true); + expect(persisted).toBe(false); + }).pipe( + Effect.provide( + testLayer({ + upsert: () => + Effect.sync(() => { + persisted = true; + }), + }), + ), + ); + }); + + it.effect("rejects replayed JWT ids", () => + Effect.gen(function* () { + const { request } = yield* makeRequest; + const linker = yield* EnvironmentLinker.EnvironmentLinker; + const result = yield* Effect.result(linker.link({ userId: "user_123", request })); + expect(Result.isFailure(result)).toBe(true); + }).pipe(Effect.provide(testLayer({ consume: () => Effect.succeed(false) }))), + ); +}); diff --git a/infra/relay/src/services/EnvironmentLinker.ts b/infra/relay/src/services/EnvironmentLinker.ts new file mode 100644 index 0000000000..ff12bc688c --- /dev/null +++ b/infra/relay/src/services/EnvironmentLinker.ts @@ -0,0 +1,270 @@ +import { + RelayEnvironmentLinkProofPayload, + type RelayEnvironmentLinkProofInvalidReason, + type RelayEnvironmentLinkRequest, +} from "@t3tools/contracts/relay"; +import { + decodeRelayJwt, + normalizeRelayIssuer, + RELAY_LINK_PROOF_TYP, + verifyRelayJwt, +} from "@t3tools/shared/relayJwt"; +import * as Context from "effect/Context"; +import * as Data from "effect/Data"; +import * as DateTime from "effect/DateTime"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import * as Schema from "effect/Schema"; + +import * as DpopProofs from "../persistence/DpopProofs.ts"; +import * as EnvironmentCredentials from "../persistence/EnvironmentCredentials.ts"; +import * as EnvironmentLinks from "../persistence/EnvironmentLinks.ts"; +import * as ManagedEndpointProvider from "./ManagedEndpointProvider.ts"; +import * as RelayConfiguration from "../Config.ts"; +import { verifyLinkChallengeToken } from "../relayTokens.ts"; +import { withUserId } from "../telemetry.ts"; + +export class EnvironmentLinkProofExpired extends Data.TaggedError("EnvironmentLinkProofExpired")<{ + readonly expiresAt: string; +}> {} + +export class EnvironmentLinkProofInvalid extends Data.TaggedError("EnvironmentLinkProofInvalid")<{ + readonly environmentId: string; + readonly reason: RelayEnvironmentLinkProofInvalidReason; +}> {} + +export type EnvironmentLinkError = + | EnvironmentLinkProofExpired + | EnvironmentLinkProofInvalid + | DpopProofs.DpopProofReplayPersistenceError + | EnvironmentLinks.EnvironmentLinkUpsertPersistenceError + | EnvironmentCredentials.EnvironmentCredentialCreatePersistenceError + | ManagedEndpointProvider.ManagedEndpointProviderError; + +export interface EnvironmentLinkerShape { + readonly link: (input: { + readonly userId: string; + readonly request: RelayEnvironmentLinkRequest; + }) => Effect.Effect< + { + readonly environmentId: RelayEnvironmentLinkProofPayload["environmentId"]; + readonly endpoint: RelayEnvironmentLinkProofPayload["endpoint"]; + readonly endpointRuntime: + | ManagedEndpointProvider.ManagedEndpointProvisioningResult["runtime"] + | null; + readonly environmentCredential: string; + }, + EnvironmentLinkError + >; +} + +export class EnvironmentLinker extends Context.Service()( + "EnvironmentLinker", +) {} + +const decodeProof = Schema.decodeUnknownEffect(RelayEnvironmentLinkProofPayload); + +function proofAuthorizesRequestedCapabilities( + proof: RelayEnvironmentLinkProofPayload, + request: RelayEnvironmentLinkRequest, +): boolean { + const scopes = new Set(proof.scopes); + if (request.managedTunnelsEnabled && !scopes.has("managed_tunnels")) { + return false; + } + return !( + (request.notificationsEnabled || request.liveActivitiesEnabled) && + !scopes.has("agent_activity_notifications") + ); +} + +function isSecureManagedEndpoint(endpoint: RelayEnvironmentLinkProofPayload["endpoint"]): boolean { + try { + const httpUrl = new URL(endpoint.httpBaseUrl); + const wsUrl = new URL(endpoint.wsBaseUrl); + return httpUrl.protocol === "https:" && wsUrl.protocol === "wss:"; + } catch { + return false; + } +} + +function normalizeHostname(hostname: string): string { + return hostname + .trim() + .toLowerCase() + .replace(/^\[(.*)\]$/u, "$1"); +} + +function isLoopbackManagedTunnelOrigin( + origin: RelayEnvironmentLinkProofPayload["origin"], +): boolean { + const hostname = normalizeHostname(origin.localHttpHost); + return ( + (hostname === "127.0.0.1" || hostname === "::1" || hostname === "localhost") && + Number.isInteger(origin.localHttpPort) && + origin.localHttpPort > 0 && + origin.localHttpPort <= 65_535 + ); +} + +const make = Effect.gen(function* () { + const links = yield* EnvironmentLinks.EnvironmentLinks; + const credentials = yield* EnvironmentCredentials.EnvironmentCredentials; + const managedEndpointProvider = yield* ManagedEndpointProvider.ManagedEndpointProvider; + const proofReplay = yield* DpopProofs.DpopProofReplay; + const config = yield* RelayConfiguration.RelayConfiguration; + + return EnvironmentLinker.of({ + link: Effect.fn("relay.environment_linker.link")( + function* (input) { + const now = yield* DateTime.now; + const nowSeconds = Math.floor(now.epochMilliseconds / 1_000); + const unverified = yield* Effect.try({ + try: () => decodeRelayJwt(input.request.proof), + catch: () => + new EnvironmentLinkProofInvalid({ + environmentId: "unknown", + reason: "invalid_signature_or_scope", + }), + }); + const decoded = yield* decodeProof(unverified).pipe(Effect.option); + if (decoded._tag === "None") { + return yield* new EnvironmentLinkProofInvalid({ + environmentId: "unknown", + reason: "invalid_signature_or_scope", + }); + } + const candidate = decoded.value; + yield* Effect.annotateCurrentSpan({ + "relay.environment_id": candidate.environmentId, + "relay.link.notifications_enabled": input.request.notificationsEnabled, + "relay.link.live_activities_enabled": input.request.liveActivitiesEnabled, + "relay.link.managed_tunnels_enabled": input.request.managedTunnelsEnabled, + }); + if (candidate.exp <= nowSeconds) { + return yield* new EnvironmentLinkProofExpired({ + expiresAt: DateTime.formatIso(DateTime.makeUnsafe(candidate.exp * 1_000)), + }); + } + const issuer = `t3-env:${candidate.environmentId}`; + const relayIssuer = normalizeRelayIssuer(config.relayIssuer); + const verified = yield* verifyRelayJwt({ + publicKey: candidate.environmentPublicKey, + token: input.request.proof, + typ: RELAY_LINK_PROOF_TYP, + issuer, + audience: relayIssuer, + nowEpochSeconds: nowSeconds, + }).pipe( + Effect.flatMap(decodeProof), + Effect.mapError( + () => + new EnvironmentLinkProofInvalid({ + environmentId: candidate.environmentId, + reason: "invalid_signature_or_scope", + }), + ), + ); + if ( + verified.sub !== verified.environmentId || + !proofAuthorizesRequestedCapabilities(verified, input.request) + ) { + return yield* new EnvironmentLinkProofInvalid({ + environmentId: candidate.environmentId, + reason: "invalid_signature_or_scope", + }); + } + if (verified.descriptor.environmentId !== verified.environmentId) { + return yield* new EnvironmentLinkProofInvalid({ + environmentId: verified.environmentId, + reason: "descriptor_mismatch", + }); + } + const challenge = yield* verifyLinkChallengeToken({ + config, + token: verified.challenge, + userId: input.userId, + request: { + notificationsEnabled: input.request.notificationsEnabled, + liveActivitiesEnabled: input.request.liveActivitiesEnabled, + managedTunnelsEnabled: input.request.managedTunnelsEnabled, + }, + nowEpochSeconds: nowSeconds, + }); + if (challenge === null) { + return yield* new EnvironmentLinkProofInvalid({ + environmentId: verified.environmentId, + reason: "challenge_invalid", + }); + } + const expiresAt = DateTime.make(verified.exp * 1_000); + if (expiresAt._tag === "None") { + return yield* new EnvironmentLinkProofInvalid({ + environmentId: verified.environmentId, + reason: "invalid_signature_or_scope", + }); + } + const consumedNonce = yield* proofReplay.consume({ + thumbprint: verified.environmentPublicKey, + jti: verified.jti, + iat: verified.iat, + expiresAt: expiresAt.value, + }); + if (!consumedNonce) { + return yield* new EnvironmentLinkProofInvalid({ + environmentId: verified.environmentId, + reason: "replayed_nonce", + }); + } + const consumedChallenge = yield* proofReplay.consume({ + thumbprint: "relay-environment-link-challenge", + jti: challenge.jti, + iat: challenge.iat, + expiresAt: expiresAt.value, + }); + if (!consumedChallenge) { + return yield* new EnvironmentLinkProofInvalid({ + environmentId: verified.environmentId, + reason: "challenge_invalid", + }); + } + if ( + input.request.managedTunnelsEnabled && + !isLoopbackManagedTunnelOrigin(verified.origin) + ) { + return yield* new EnvironmentLinkProofInvalid({ + environmentId: verified.environmentId, + reason: "origin_not_allowed", + }); + } + const provisioned = input.request.managedTunnelsEnabled + ? yield* managedEndpointProvider.provision({ + environmentId: verified.environmentId, + origin: verified.origin, + }) + : null; + const endpoint = provisioned?.endpoint ?? verified.endpoint; + if (!isSecureManagedEndpoint(endpoint)) { + return yield* new EnvironmentLinkProofInvalid({ + environmentId: verified.environmentId, + reason: "endpoint_not_secure", + }); + } + yield* links.upsert({ ...input, proof: verified, endpoint }); + const environmentCredential = yield* credentials.create({ + environmentId: verified.environmentId, + environmentPublicKey: verified.environmentPublicKey, + }); + return { + environmentId: verified.environmentId, + endpoint, + endpointRuntime: provisioned?.runtime ?? null, + environmentCredential, + }; + }, + (effect, input) => effect.pipe(withUserId(input.userId)), + ), + }); +}); + +export const layer = Layer.effect(EnvironmentLinker, make); diff --git a/infra/relay/src/services/EnvironmentPublishSignatures.test.ts b/infra/relay/src/services/EnvironmentPublishSignatures.test.ts new file mode 100644 index 0000000000..9826137074 --- /dev/null +++ b/infra/relay/src/services/EnvironmentPublishSignatures.test.ts @@ -0,0 +1,160 @@ +import * as NodeCrypto from "node:crypto"; +import * as NodeServices from "@effect/platform-node/NodeServices"; +import type { + RelayAgentActivityPublishProofPayload, + RelayAgentActivityPublishRequest, + RelayAgentActivityState, +} from "@t3tools/contracts/relay"; +import { RELAY_ACTIVITY_PUBLISH_TYP } from "@t3tools/shared/relayJwt"; +import { describe, expect, it } from "@effect/vitest"; +import * as DateTime from "effect/DateTime"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import * as Redacted from "effect/Redacted"; +import * as Result from "effect/Result"; + +import * as DpopProofs from "../persistence/DpopProofs.ts"; +import * as RelayConfiguration from "../Config.ts"; +import * as EnvironmentPublishSignatures from "./EnvironmentPublishSignatures.ts"; +import { environmentPublishReplayThumbprint } from "./EnvironmentPublishSignatures.ts"; + +const keyPair = NodeCrypto.generateKeyPairSync("ed25519", { + privateKeyEncoding: { format: "pem", type: "pkcs8" }, + publicKeyEncoding: { format: "pem", type: "spki" }, +}); +const config = RelayConfiguration.RelayConfiguration.of({ + relayIssuer: "https://relay.example.test", + apns: { + environment: "sandbox", + teamId: "team-id", + keyId: "key-id", + privateKey: Redacted.make("private-key"), + bundleId: "com.t3tools.t3code.dev", + }, + apnsDeliveryJobSigningSecret: Redacted.make("job-secret"), + clerkSecretKey: Redacted.make("clerk-secret"), + cloudMintPrivateKey: Redacted.make(keyPair.privateKey), + cloudMintPublicKey: keyPair.publicKey, + managedEndpointBaseDomain: undefined, + cloudflareAccountId: undefined, + cloudflareZoneId: undefined, + cloudflareApiToken: undefined, +}); +const state: RelayAgentActivityState = { + environmentId: "env" as RelayAgentActivityState["environmentId"], + threadId: "thread" as RelayAgentActivityState["threadId"], + projectTitle: "Project", + threadTitle: "Thread", + modelTitle: "gpt-5.4", + phase: "running", + headline: "Running", + updatedAt: "2026-05-25T00:00:00.000Z", + deepLink: "/threads/env/thread", +}; + +function signTestJwt(payload: object, privateKey: string): string { + const header = Buffer.from( + JSON.stringify({ alg: "EdDSA", typ: RELAY_ACTIVITY_PUBLISH_TYP }), + ).toString("base64url"); + const encodedPayload = Buffer.from(JSON.stringify(payload)).toString("base64url"); + const signingInput = `${header}.${encodedPayload}`; + return `${signingInput}.${NodeCrypto.sign(null, Buffer.from(signingInput), privateKey).toString("base64url")}`; +} + +const freshRequest = Effect.gen(function* () { + const now = yield* DateTime.now; + const payload = { + iss: "t3-env:env", + aud: "https://relay.example.test", + sub: "env", + jti: "publish-jti", + iat: Math.floor(now.epochMilliseconds / 1_000), + exp: Math.floor(DateTime.add(now, { minutes: 5 }).epochMilliseconds / 1_000), + environmentId: state.environmentId, + threadId: state.threadId, + state, + } satisfies RelayAgentActivityPublishProofPayload; + return { + state, + proof: signTestJwt(payload, keyPair.privateKey), + } satisfies RelayAgentActivityPublishRequest; +}); + +function layer(replay?: Partial) { + return EnvironmentPublishSignatures.layer.pipe( + Layer.provide( + Layer.merge( + Layer.succeed(RelayConfiguration.RelayConfiguration, config), + Layer.succeed(DpopProofs.DpopProofReplay, { + consume: replay?.consume ?? (() => Effect.succeed(true)), + pruneExpired: replay?.pruneExpired ?? Effect.void, + }), + ), + ), + Layer.provideMerge(NodeServices.layer), + ); +} + +describe("EnvironmentPublishSignatures", () => { + it.effect("verifies activity JWTs and scopes replay storage to the environment key", () => { + let replayThumbprint: string | null = null; + return Effect.gen(function* () { + const request = yield* freshRequest; + const signatures = yield* EnvironmentPublishSignatures.EnvironmentPublishSignatures; + yield* signatures.verify({ + environmentId: state.environmentId, + environmentPublicKey: keyPair.publicKey, + threadId: state.threadId, + request, + }); + expect(replayThumbprint).toBe( + yield* environmentPublishReplayThumbprint({ + environmentId: state.environmentId, + environmentPublicKey: keyPair.publicKey, + }), + ); + }).pipe( + Effect.provide( + layer({ + consume: (input) => + Effect.sync(() => { + replayThumbprint = input.thumbprint; + return true; + }), + }), + ), + ); + }); + + it.effect("rejects top-level state tampering", () => + Effect.gen(function* () { + const request = yield* freshRequest; + const signatures = yield* EnvironmentPublishSignatures.EnvironmentPublishSignatures; + const result = yield* Effect.result( + signatures.verify({ + environmentId: state.environmentId, + environmentPublicKey: keyPair.publicKey, + threadId: state.threadId, + request: { ...request, state: { ...state, headline: "Tampered" } }, + }), + ); + expect(Result.isFailure(result)).toBe(true); + }).pipe(Effect.provide(layer())), + ); + + it.effect("rejects replayed activity JWT ids", () => + Effect.gen(function* () { + const request = yield* freshRequest; + const signatures = yield* EnvironmentPublishSignatures.EnvironmentPublishSignatures; + const result = yield* Effect.result( + signatures.verify({ + environmentId: state.environmentId, + environmentPublicKey: keyPair.publicKey, + threadId: state.threadId, + request, + }), + ); + expect(Result.isFailure(result)).toBe(true); + }).pipe(Effect.provide(layer({ consume: () => Effect.succeed(false) }))), + ); +}); diff --git a/infra/relay/src/services/EnvironmentPublishSignatures.ts b/infra/relay/src/services/EnvironmentPublishSignatures.ts new file mode 100644 index 0000000000..6c92b02b99 --- /dev/null +++ b/infra/relay/src/services/EnvironmentPublishSignatures.ts @@ -0,0 +1,176 @@ +import { + RelayAgentActivityPublishProofPayload, + type RelayAgentActivityPublishRequest, +} from "@t3tools/contracts/relay"; +import { + decodeRelayJwt, + normalizeRelayIssuer, + RELAY_ACTIVITY_PUBLISH_TYP, + verifyRelayJwt, +} from "@t3tools/shared/relayJwt"; +import { stableStringify } from "@t3tools/shared/relaySigning"; +import * as Context from "effect/Context"; +import * as Crypto from "effect/Crypto"; +import * as Data from "effect/Data"; +import * as DateTime from "effect/DateTime"; +import * as Effect from "effect/Effect"; +import * as Encoding from "effect/Encoding"; +import * as Layer from "effect/Layer"; +import * as Schema from "effect/Schema"; + +import * as DpopProofs from "../persistence/DpopProofs.ts"; +import * as RelayConfiguration from "../Config.ts"; + +export class EnvironmentPublishSignatureExpired extends Data.TaggedError( + "EnvironmentPublishSignatureExpired", +)<{ + readonly expiresAt: string; +}> {} + +export class EnvironmentPublishSignatureInvalid extends Data.TaggedError( + "EnvironmentPublishSignatureInvalid", +)<{ + readonly environmentId: string; +}> {} + +export class EnvironmentPublishPublicKeyMissing extends Data.TaggedError( + "EnvironmentPublishPublicKeyMissing", +)<{ + readonly environmentId: string; +}> {} + +export type EnvironmentPublishSignatureError = + | EnvironmentPublishSignatureExpired + | EnvironmentPublishSignatureInvalid + | EnvironmentPublishPublicKeyMissing + | DpopProofs.DpopProofReplayPersistenceError; + +export interface EnvironmentPublishSignaturesShape { + readonly verify: (input: { + readonly environmentId: string; + readonly environmentPublicKey: string; + readonly threadId: string; + readonly request: RelayAgentActivityPublishRequest; + }) => Effect.Effect; +} + +export class EnvironmentPublishSignatures extends Context.Service< + EnvironmentPublishSignatures, + EnvironmentPublishSignaturesShape +>()("EnvironmentPublishSignatures") {} + +const decodeProof = Schema.decodeUnknownEffect(RelayAgentActivityPublishProofPayload); + +function environmentPublishReplayThumbprintData(input: { + readonly environmentId: string; + readonly environmentPublicKey: string; +}) { + return new TextEncoder().encode( + stableStringify({ + environmentId: input.environmentId, + environmentPublicKey: input.environmentPublicKey, + }), + ); +} + +const formatEnvironmentPublishReplayThumbprint = (digest: Uint8Array) => + `env-publish:${Encoding.encodeBase64Url(digest)}`; + +export function environmentPublishReplayThumbprint(input: { + readonly environmentId: string; + readonly environmentPublicKey: string; +}) { + return Crypto.Crypto.pipe( + Effect.flatMap((crypto) => + crypto.digest("SHA-256", environmentPublishReplayThumbprintData(input)), + ), + Effect.map(formatEnvironmentPublishReplayThumbprint), + ); +} + +const make = Effect.gen(function* () { + const proofReplay = yield* DpopProofs.DpopProofReplay; + const config = yield* RelayConfiguration.RelayConfiguration; + const crypto = yield* Crypto.Crypto; + + return EnvironmentPublishSignatures.of({ + verify: Effect.fn("relay.environment_publish_signatures.verify")(function* (input) { + yield* Effect.annotateCurrentSpan({ + "relay.environment_id": input.environmentId, + "relay.thread_id": input.threadId, + }); + const now = yield* DateTime.now; + const decoded = yield* Effect.try({ + try: () => decodeRelayJwt(input.request.proof), + catch: () => new EnvironmentPublishSignatureInvalid({ environmentId: input.environmentId }), + }); + if ( + typeof decoded.exp === "number" && + decoded.exp <= Math.floor(now.epochMilliseconds / 1_000) + ) { + return yield* new EnvironmentPublishSignatureExpired({ + expiresAt: DateTime.formatIso(DateTime.makeUnsafe(decoded.exp * 1_000)), + }); + } + const proof = yield* verifyRelayJwt({ + publicKey: input.environmentPublicKey, + token: input.request.proof, + typ: RELAY_ACTIVITY_PUBLISH_TYP, + issuer: `t3-env:${input.environmentId}`, + audience: normalizeRelayIssuer(config.relayIssuer), + nowEpochSeconds: Math.floor(now.epochMilliseconds / 1_000), + }).pipe( + Effect.flatMap(decodeProof), + Effect.mapError( + () => new EnvironmentPublishSignatureInvalid({ environmentId: input.environmentId }), + ), + ); + if ( + proof.environmentId !== input.environmentId || + proof.threadId !== input.threadId || + proof.sub !== input.environmentId || + stableStringify(proof.state) !== stableStringify(input.request.state) || + (input.request.state !== null && + (input.request.state.environmentId !== input.environmentId || + input.request.state.threadId !== input.threadId)) + ) { + return yield* new EnvironmentPublishSignatureInvalid({ + environmentId: input.environmentId, + }); + } + const expiresAt = DateTime.make(proof.exp * 1_000); + if (expiresAt._tag === "None") { + return yield* new EnvironmentPublishSignatureInvalid({ + environmentId: input.environmentId, + }); + } + const thumbprint = yield* crypto + .digest( + "SHA-256", + environmentPublishReplayThumbprintData({ + environmentId: input.environmentId, + environmentPublicKey: input.environmentPublicKey, + }), + ) + .pipe( + Effect.map(formatEnvironmentPublishReplayThumbprint), + Effect.mapError( + () => new EnvironmentPublishSignatureInvalid({ environmentId: input.environmentId }), + ), + ); + const consumedNonce = yield* proofReplay.consume({ + thumbprint, + jti: proof.jti, + iat: proof.iat, + expiresAt: expiresAt.value, + }); + if (!consumedNonce) { + return yield* new EnvironmentPublishSignatureInvalid({ + environmentId: input.environmentId, + }); + } + }), + }); +}); + +export const layer = Layer.effect(EnvironmentPublishSignatures, make); diff --git a/infra/relay/src/services/ManagedEndpointProvider.test.ts b/infra/relay/src/services/ManagedEndpointProvider.test.ts new file mode 100644 index 0000000000..bd1bbb4765 --- /dev/null +++ b/infra/relay/src/services/ManagedEndpointProvider.test.ts @@ -0,0 +1,446 @@ +import * as NodeCrypto from "node:crypto"; +import * as NodeServices from "@effect/platform-node/NodeServices"; + +import { describe, expect, it } from "@effect/vitest"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import * as Redacted from "effect/Redacted"; +import { HttpClient, HttpClientRequest, HttpClientResponse } from "effect/unstable/http"; + +import * as RelayConfiguration from "../Config.ts"; +import * as ManagedEndpointProvider from "./ManagedEndpointProvider.ts"; + +const config = RelayConfiguration.RelayConfiguration.of({ + relayIssuer: "https://relay.example.test", + apns: { + environment: "sandbox", + teamId: "team-id", + keyId: "key-id", + privateKey: Redacted.make("private-key"), + bundleId: "com.t3tools.t3code.dev", + }, + apnsDeliveryJobSigningSecret: Redacted.make("job-secret"), + clerkSecretKey: Redacted.make("clerk-secret"), + cloudMintPrivateKey: Redacted.make("cloud-private-key"), + cloudMintPublicKey: "cloud-public-key", + managedEndpointBaseDomain: "t3code.test", + cloudflareAccountId: "account-id", + cloudflareZoneId: "zone-id", + cloudflareApiToken: Redacted.make("api-token"), +}); + +function decodeBody(request: HttpClientRequest.HttpClientRequest): unknown { + return request.body._tag === "Uint8Array" + ? JSON.parse(new TextDecoder().decode(request.body.body)) + : null; +} + +function expectedManagedHostname(environmentId: string): string { + const hash = NodeCrypto.createHash("sha256").update(environmentId).digest("hex").slice(0, 16); + return `tunnels-env-abc-${hash}.t3code.test`; +} + +function expectedManagedTunnelName(environmentId: string): string { + const hash = NodeCrypto.createHash("sha256").update(environmentId).digest("hex").slice(0, 16); + return `t3-code-env-abc-${hash}`; +} + +describe("ManagedEndpointProvider", () => { + it.effect("provisions a Cloudflare tunnel endpoint and connector token", () => { + const calls: Array<{ + readonly method: string; + readonly url: string; + readonly body: unknown; + readonly authorization: string | undefined; + }> = []; + const execute = (request: HttpClientRequest.HttpClientRequest) => + Effect.sync(() => { + calls.push({ + method: request.method, + url: request.url, + body: decodeBody(request), + authorization: request.headers.authorization, + }); + if (request.url.includes("/cfd_tunnel?")) { + return HttpClientResponse.fromWeb( + request, + Response.json({ success: true, result: [] }, { status: 200 }), + ); + } + if (request.url.endsWith("/token")) { + return HttpClientResponse.fromWeb( + request, + Response.json({ success: true, result: "connector-token" }, { status: 200 }), + ); + } + if (request.url.includes("/dns_records?")) { + return HttpClientResponse.fromWeb( + request, + Response.json({ success: true, result: [] }, { status: 200 }), + ); + } + if (request.url.endsWith("/dns_records")) { + return HttpClientResponse.fromWeb( + request, + Response.json({ success: true }, { status: 200 }), + ); + } + if (request.url.endsWith("/configurations")) { + return HttpClientResponse.fromWeb( + request, + Response.json({ success: true }, { status: 200 }), + ); + } + return HttpClientResponse.fromWeb( + request, + Response.json( + { success: true, result: { id: "tunnel-id", name: "tunnel-name" } }, + { status: 200 }, + ), + ); + }); + + return Effect.gen(function* () { + const hostname = expectedManagedHostname("env_ABC"); + const provider = yield* ManagedEndpointProvider.ManagedEndpointProvider; + const result = yield* provider.provision({ + environmentId: "env_ABC", + origin: { localHttpHost: "127.0.0.1", localHttpPort: 3773 }, + }); + + expect(result).toEqual({ + endpoint: { + httpBaseUrl: `https://${hostname}/`, + wsBaseUrl: `wss://${hostname}/ws`, + providerKind: "cloudflare_tunnel", + }, + runtime: { + providerKind: "cloudflare_tunnel", + connectorToken: "connector-token", + tunnelId: "tunnel-id", + tunnelName: "tunnel-name", + }, + }); + expect(calls.map((call) => call.method)).toEqual([ + "GET", + "POST", + "PUT", + "GET", + "POST", + "GET", + ]); + expect(calls.every((call) => call.authorization === "Bearer api-token")).toBe(true); + expect(calls[2]?.body).toMatchObject({ + config: { + ingress: [ + { + hostname, + service: "http://127.0.0.1:3773", + }, + { service: "http_status:404" }, + ], + }, + }); + expect(calls[0]?.url).toContain( + `name=${expectedManagedTunnelName("env_ABC")}&is_deleted=false`, + ); + }).pipe( + Effect.provide( + ManagedEndpointProvider.layer.pipe( + Layer.provideMerge(NodeServices.layer), + Layer.provide(Layer.succeed(RelayConfiguration.RelayConfiguration, config)), + Layer.provide(Layer.succeed(HttpClient.HttpClient, HttpClient.make(execute))), + ), + ), + ); + }); + + it.effect( + "normalizes unusual environment ids before using them in Cloudflare tunnel names", + () => { + const calls: Array<{ + readonly method: string; + readonly url: string; + readonly body: unknown; + }> = []; + const execute = (request: HttpClientRequest.HttpClientRequest) => + Effect.sync(() => { + calls.push({ + method: request.method, + url: request.url, + body: decodeBody(request), + }); + if (request.url.includes("/cfd_tunnel?")) { + return HttpClientResponse.fromWeb( + request, + Response.json({ success: true, result: [] }, { status: 200 }), + ); + } + if (request.url.endsWith("/token")) { + return HttpClientResponse.fromWeb( + request, + Response.json({ success: true, result: "connector-token" }, { status: 200 }), + ); + } + if (request.url.includes("/dns_records?")) { + return HttpClientResponse.fromWeb( + request, + Response.json({ success: true, result: [] }, { status: 200 }), + ); + } + if (request.url.endsWith("/dns_records") || request.url.endsWith("/configurations")) { + return HttpClientResponse.fromWeb( + request, + Response.json({ success: true }, { status: 200 }), + ); + } + return HttpClientResponse.fromWeb( + request, + Response.json( + { success: true, result: { id: "tunnel-id", name: "normalized-name" } }, + { status: 200 }, + ), + ); + }); + + return Effect.gen(function* () { + const environmentId = "ENV With Spaces/../Symbols!" + "x".repeat(80); + const provider = yield* ManagedEndpointProvider.ManagedEndpointProvider; + yield* provider.provision({ + environmentId, + origin: { localHttpHost: "127.0.0.1", localHttpPort: 3773 }, + }); + + const listUrl = calls[0]?.url ?? ""; + const createBody = calls[1]?.body; + const requestedName = new URL(listUrl).searchParams.get("name"); + expect(requestedName).toMatch(/^t3-code-env-with-spaces-symbols-x+-[a-f0-9]{16}$/); + expect(requestedName?.length).toBeLessThanOrEqual(89); + const configBody = calls.find((call) => call.url.endsWith("/configurations"))?.body; + expect(configBody).toMatchObject({ + config: { + ingress: [ + { + hostname: expect.stringMatching( + /^tunnels-env-with-spaces-symbols-x+-[a-f0-9]{16}\.t3code\.test$/, + ), + }, + { service: "http_status:404" }, + ], + }, + }); + const hostname = ( + configBody as + | { + readonly config?: { + readonly ingress?: readonly [{ readonly hostname?: unknown }, unknown]; + }; + } + | undefined + )?.config?.ingress?.[0]?.hostname; + expect( + typeof hostname === "string" ? hostname.split(".")[0]?.length : 0, + ).toBeLessThanOrEqual(63); + expect(createBody).toMatchObject({ + name: requestedName, + config_src: "cloudflare", + }); + }).pipe( + Effect.provide( + ManagedEndpointProvider.layer.pipe( + Layer.provideMerge(NodeServices.layer), + Layer.provide(Layer.succeed(RelayConfiguration.RelayConfiguration, config)), + Layer.provide(Layer.succeed(HttpClient.HttpClient, HttpClient.make(execute))), + ), + ), + ); + }, + ); + + it.effect("formats IPv6 loopback origins as valid Cloudflare ingress service URLs", () => { + const calls: Array<{ + readonly method: string; + readonly url: string; + readonly body: unknown; + }> = []; + const execute = (request: HttpClientRequest.HttpClientRequest) => + Effect.sync(() => { + calls.push({ + method: request.method, + url: request.url, + body: decodeBody(request), + }); + if (request.url.includes("/cfd_tunnel?")) { + return HttpClientResponse.fromWeb( + request, + Response.json({ success: true, result: [] }, { status: 200 }), + ); + } + if (request.url.endsWith("/token")) { + return HttpClientResponse.fromWeb( + request, + Response.json({ success: true, result: "connector-token" }, { status: 200 }), + ); + } + if (request.url.includes("/dns_records?")) { + return HttpClientResponse.fromWeb( + request, + Response.json({ success: true, result: [] }, { status: 200 }), + ); + } + if (request.url.endsWith("/dns_records") || request.url.endsWith("/configurations")) { + return HttpClientResponse.fromWeb( + request, + Response.json({ success: true }, { status: 200 }), + ); + } + return HttpClientResponse.fromWeb( + request, + Response.json( + { success: true, result: { id: "tunnel-id", name: "normalized-name" } }, + { status: 200 }, + ), + ); + }); + + return Effect.gen(function* () { + const provider = yield* ManagedEndpointProvider.ManagedEndpointProvider; + yield* provider.provision({ + environmentId: "env-ipv6", + origin: { localHttpHost: "::1", localHttpPort: 3773 }, + }); + + expect(calls[2]?.body).toMatchObject({ + config: { + ingress: [ + { + service: "http://[::1]:3773", + }, + { service: "http_status:404" }, + ], + }, + }); + }).pipe( + Effect.provide( + ManagedEndpointProvider.layer.pipe( + Layer.provideMerge(NodeServices.layer), + Layer.provide(Layer.succeed(RelayConfiguration.RelayConfiguration, config)), + Layer.provide(Layer.succeed(HttpClient.HttpClient, HttpClient.make(execute))), + ), + ), + ); + }); + + it.effect("rejects non-loopback managed endpoint origins before calling Cloudflare", () => { + const calls: Array = []; + const execute = (request: HttpClientRequest.HttpClientRequest) => + Effect.sync(() => { + calls.push(request); + return HttpClientResponse.fromWeb( + request, + Response.json({ success: true, result: [] }, { status: 200 }), + ); + }); + + return Effect.gen(function* () { + const provider = yield* ManagedEndpointProvider.ManagedEndpointProvider; + const result = yield* Effect.result( + provider.provision({ + environmentId: "env_ABC", + origin: { localHttpHost: "192.168.1.10", localHttpPort: 3773 }, + }), + ); + + expect(calls).toHaveLength(0); + expect(result._tag).toBe("Failure"); + if (result._tag === "Failure") { + expect(result.failure._tag).toBe("ManagedEndpointOriginNotAllowed"); + } + }).pipe( + Effect.provide( + ManagedEndpointProvider.layer.pipe( + Layer.provideMerge(NodeServices.layer), + Layer.provide(Layer.succeed(RelayConfiguration.RelayConfiguration, config)), + Layer.provide(Layer.succeed(HttpClient.HttpClient, HttpClient.make(execute))), + ), + ), + ); + }); + + it.effect("rejects invalid managed endpoint origin ports before calling Cloudflare", () => { + const calls: Array = []; + const execute = (request: HttpClientRequest.HttpClientRequest) => + Effect.sync(() => { + calls.push(request); + return HttpClientResponse.fromWeb( + request, + Response.json({ success: true, result: [] }, { status: 200 }), + ); + }); + + return Effect.gen(function* () { + const provider = yield* ManagedEndpointProvider.ManagedEndpointProvider; + const result = yield* Effect.result( + provider.provision({ + environmentId: "env_ABC", + origin: { localHttpHost: "127.0.0.1", localHttpPort: 65_536 }, + }), + ); + + expect(calls).toHaveLength(0); + expect(result._tag).toBe("Failure"); + if (result._tag === "Failure") { + expect(result.failure._tag).toBe("ManagedEndpointOriginNotAllowed"); + } + }).pipe( + Effect.provide( + ManagedEndpointProvider.layer.pipe( + Layer.provideMerge(NodeServices.layer), + Layer.provide(Layer.succeed(RelayConfiguration.RelayConfiguration, config)), + Layer.provide(Layer.succeed(HttpClient.HttpClient, HttpClient.make(execute))), + ), + ), + ); + }); + + it.effect("fails provisioning when Cloudflare returns a 2xx application error", () => { + const execute = (request: HttpClientRequest.HttpClientRequest) => + Effect.sync(() => + HttpClientResponse.fromWeb( + request, + Response.json( + { + success: false, + result: [], + errors: [{ code: 10_000, message: "Cloudflare application failure" }], + }, + { status: 200 }, + ), + ), + ); + + return Effect.gen(function* () { + const provider = yield* ManagedEndpointProvider.ManagedEndpointProvider; + const error = yield* Effect.flip( + provider.provision({ + environmentId: "env_ABC", + origin: { localHttpHost: "127.0.0.1", localHttpPort: 3773 }, + }), + ); + + expect(error._tag).toBe("ManagedEndpointProvisioningFailed"); + expect(error.cause).toMatchObject({ + success: false, + errors: [{ message: "Cloudflare application failure" }], + }); + }).pipe( + Effect.provide( + ManagedEndpointProvider.layer.pipe( + Layer.provideMerge(NodeServices.layer), + Layer.provide(Layer.succeed(RelayConfiguration.RelayConfiguration, config)), + Layer.provide(Layer.succeed(HttpClient.HttpClient, HttpClient.make(execute))), + ), + ), + ); + }); +}); diff --git a/infra/relay/src/services/ManagedEndpointProvider.ts b/infra/relay/src/services/ManagedEndpointProvider.ts new file mode 100644 index 0000000000..c16413e5da --- /dev/null +++ b/infra/relay/src/services/ManagedEndpointProvider.ts @@ -0,0 +1,343 @@ +// @effect-diagnostics nodeBuiltinImport:off + +import type { + RelayManagedEndpoint, + RelayManagedEndpointOrigin, + RelayManagedEndpointRuntimeConfig, +} from "@t3tools/contracts/relay"; +import * as Context from "effect/Context"; +import * as Crypto from "effect/Crypto"; +import * as Data from "effect/Data"; +import * as Effect from "effect/Effect"; +import * as Encoding from "effect/Encoding"; +import * as Layer from "effect/Layer"; +import * as Redacted from "effect/Redacted"; +import * as Schema from "effect/Schema"; +import { HttpClient, HttpClientRequest } from "effect/unstable/http"; + +import * as RelayConfiguration from "../Config.ts"; + +export class ManagedEndpointProvisioningNotConfigured extends Data.TaggedError( + "ManagedEndpointProvisioningNotConfigured", +)<{}> {} + +export class ManagedEndpointProvisioningFailed extends Data.TaggedError( + "ManagedEndpointProvisioningFailed", +)<{ + readonly cause: unknown; +}> {} + +export class ManagedEndpointOriginNotAllowed extends Data.TaggedError( + "ManagedEndpointOriginNotAllowed", +)<{ + readonly host: string; + readonly port: number; +}> {} + +export type ManagedEndpointProviderError = + | ManagedEndpointProvisioningNotConfigured + | ManagedEndpointProvisioningFailed + | ManagedEndpointOriginNotAllowed; + +export interface ManagedEndpointProvisioningResult { + readonly endpoint: RelayManagedEndpoint; + readonly runtime: RelayManagedEndpointRuntimeConfig; +} + +export interface ManagedEndpointProviderShape { + readonly provision: (input: { + readonly environmentId: string; + readonly origin: RelayManagedEndpointOrigin; + }) => Effect.Effect; +} + +export class ManagedEndpointProvider extends Context.Service< + ManagedEndpointProvider, + ManagedEndpointProviderShape +>()("ManagedEndpointProvider") {} + +const CloudflareTunnelCreateResponse = Schema.Struct({ + success: Schema.Boolean, + result: Schema.Struct({ + id: Schema.String, + name: Schema.String, + }), +}); + +const CloudflareTunnelListResponse = Schema.Struct({ + success: Schema.Boolean, + result: Schema.Array( + Schema.Struct({ + id: Schema.String, + name: Schema.String, + }), + ), +}); + +const CloudflareTunnelTokenResponse = Schema.Struct({ + success: Schema.Boolean, + result: Schema.String, +}); + +const CloudflareDnsRecordResponse = Schema.Struct({ + success: Schema.Boolean, +}); + +const CloudflareDnsRecordListResponse = Schema.Struct({ + success: Schema.Boolean, + result: Schema.Array( + Schema.Struct({ + id: Schema.String, + }), + ), +}); + +const requireCloudflareSettings = Effect.fnUntraced(function* ( + settings: RelayConfiguration.RelayConfigurationShape, +) { + if ( + !settings.managedEndpointBaseDomain || + !settings.cloudflareAccountId || + !settings.cloudflareZoneId || + !settings.cloudflareApiToken + ) { + return yield* new ManagedEndpointProvisioningNotConfigured(); + } + return { + accountId: settings.cloudflareAccountId, + zoneId: settings.cloudflareZoneId, + apiToken: Redacted.value(settings.cloudflareApiToken), + baseDomain: settings.managedEndpointBaseDomain, + }; +}); + +function cloudflareRequest(input: { + readonly method: "GET" | "POST" | "PUT"; + readonly url: string; + readonly apiToken: string; + readonly body?: unknown; +}): Effect.Effect { + const base = + input.method === "GET" + ? HttpClientRequest.get(input.url) + : input.method === "POST" + ? HttpClientRequest.post(input.url) + : HttpClientRequest.put(input.url); + + const request = base.pipe( + HttpClientRequest.setHeader("authorization", `Bearer ${input.apiToken}`), + HttpClientRequest.setHeader("content-type", "application/json"), + ); + return input.body === undefined + ? Effect.succeed(request) + : request.pipe( + HttpClientRequest.bodyJson(input.body), + Effect.mapError((cause) => new ManagedEndpointProvisioningFailed({ cause })), + ); +} + +const MANAGED_ENDPOINT_HOST_PREFIX = "tunnels"; +const DNS_LABEL_MAX_LENGTH = 63; +const MANAGED_ENDPOINT_HASH_LENGTH = 16; +const MANAGED_ENDPOINT_SAFE_ID_LENGTH = + DNS_LABEL_MAX_LENGTH - MANAGED_ENDPOINT_HOST_PREFIX.length - 2 - MANAGED_ENDPOINT_HASH_LENGTH; + +function managedHostname(environmentId: string, baseDomain: string, hash: string): string { + const safeId = environmentId + .toLowerCase() + .replaceAll(/[^a-z0-9-]/g, "-") + .replaceAll(/-+/g, "-") + .replaceAll(/^-+|-+$/g, "") + .slice(0, MANAGED_ENDPOINT_SAFE_ID_LENGTH); + const prefix = safeId.length > 0 ? safeId : "env"; + return `${MANAGED_ENDPOINT_HOST_PREFIX}-${prefix}-${hash.slice(0, MANAGED_ENDPOINT_HASH_LENGTH)}.${baseDomain.replace(/^\.+|\.+$/g, "")}`; +} + +function managedTunnelName(environmentId: string, hash: string): string { + const safeId = environmentId + .toLowerCase() + .replaceAll(/[^a-z0-9-]/g, "-") + .replaceAll(/-+/g, "-") + .replaceAll(/^-+|-+$/g, "") + .slice(0, 64); + return `t3-code-${safeId.length > 0 ? safeId : "env"}-${hash.slice(0, 16)}`; +} + +function formatOriginService(origin: RelayManagedEndpointOrigin): string { + const host = origin.localHttpHost.includes(":") + ? `[${origin.localHttpHost.replace(/^\[(.*)\]$/u, "$1")}]` + : origin.localHttpHost; + return `http://${host}:${origin.localHttpPort}`; +} + +function normalizeHostname(hostname: string): string { + return hostname + .trim() + .toLowerCase() + .replace(/^\[(.*)\]$/u, "$1"); +} + +function isLoopbackOrigin(origin: RelayManagedEndpointOrigin): boolean { + const hostname = normalizeHostname(origin.localHttpHost); + return ( + (hostname === "127.0.0.1" || hostname === "::1" || hostname === "localhost") && + Number.isInteger(origin.localHttpPort) && + origin.localHttpPort > 0 && + origin.localHttpPort <= 65_535 + ); +} + +const make = Effect.gen(function* () { + const config = yield* RelayConfiguration.RelayConfiguration; + const httpClient = yield* HttpClient.HttpClient; + const crypto = yield* Crypto.Crypto; + + const requireCloudflareSuccess = ( + json: unknown, + ): Effect.Effect => + typeof json === "object" && + json !== null && + "success" in json && + (json as { readonly success: unknown }).success === false + ? Effect.fail(new ManagedEndpointProvisioningFailed({ cause: json })) + : Effect.void; + + const executeJson = Effect.fnUntraced(function* ( + request: HttpClientRequest.HttpClientRequest, + schema: Schema.Schema, + ) { + const response = yield* httpClient + .execute(request) + .pipe(Effect.mapError((cause) => new ManagedEndpointProvisioningFailed({ cause }))); + if (response.status < 200 || response.status >= 300) { + return yield* new ManagedEndpointProvisioningFailed({ cause: response.status }); + } + const json = yield* response.json.pipe( + Effect.mapError((cause) => new ManagedEndpointProvisioningFailed({ cause })), + ); + const isSchema = Schema.is(schema); + if (!isSchema(json)) { + return yield* new ManagedEndpointProvisioningFailed({ cause: json }); + } + yield* requireCloudflareSuccess(json); + return json; + }); + + return ManagedEndpointProvider.of({ + provision: Effect.fn("relay.managed_endpoint_provider.provision")(function* (input) { + yield* Effect.annotateCurrentSpan({ + "relay.environment_id": input.environmentId, + "relay.managed_endpoint.origin_host": input.origin.localHttpHost, + "relay.managed_endpoint.origin_port": input.origin.localHttpPort, + }); + if (!isLoopbackOrigin(input.origin)) { + return yield* new ManagedEndpointOriginNotAllowed({ + host: input.origin.localHttpHost, + port: input.origin.localHttpPort, + }); + } + const cf = yield* requireCloudflareSettings(config); + const environmentHash = yield* crypto + .digest("SHA-256", new TextEncoder().encode(input.environmentId)) + .pipe( + Effect.map(Encoding.encodeHex), + Effect.mapError((cause) => new ManagedEndpointProvisioningFailed({ cause })), + ); + const hostname = managedHostname(input.environmentId, cf.baseDomain, environmentHash); + const tunnelName = managedTunnelName(input.environmentId, environmentHash); + const existingTunnels = yield* cloudflareRequest({ + method: "GET", + url: `https://api.cloudflare.com/client/v4/accounts/${cf.accountId}/cfd_tunnel?${new URLSearchParams( + [ + ["name", tunnelName], + ["is_deleted", "false"], + ], + ).toString()}`, + apiToken: cf.apiToken, + }).pipe(Effect.flatMap((request) => executeJson(request, CloudflareTunnelListResponse))); + const existingTunnel = existingTunnels.result.find((tunnel) => tunnel.name === tunnelName); + const tunnel = + existingTunnel ?? + (yield* cloudflareRequest({ + method: "POST", + url: `https://api.cloudflare.com/client/v4/accounts/${cf.accountId}/cfd_tunnel`, + apiToken: cf.apiToken, + body: { + name: tunnelName, + config_src: "cloudflare", + }, + }).pipe( + Effect.flatMap((request) => executeJson(request, CloudflareTunnelCreateResponse)), + Effect.map((response) => response.result), + )); + + yield* cloudflareRequest({ + method: "PUT", + url: `https://api.cloudflare.com/client/v4/accounts/${cf.accountId}/cfd_tunnel/${tunnel.id}/configurations`, + apiToken: cf.apiToken, + body: { + config: { + ingress: [ + { + hostname, + service: formatOriginService(input.origin), + }, + { service: "http_status:404" }, + ], + }, + }, + }).pipe( + Effect.flatMap((request) => + executeJson(request, Schema.Struct({ success: Schema.Boolean })), + ), + ); + + const dnsRecords = yield* cloudflareRequest({ + method: "GET", + url: `https://api.cloudflare.com/client/v4/zones/${cf.zoneId}/dns_records?${new URLSearchParams( + [ + ["type", "CNAME"], + ["name", hostname], + ], + ).toString()}`, + apiToken: cf.apiToken, + }).pipe(Effect.flatMap((request) => executeJson(request, CloudflareDnsRecordListResponse))); + const existingDnsRecordId = dnsRecords.result[0]?.id; + yield* cloudflareRequest({ + method: existingDnsRecordId ? "PUT" : "POST", + url: existingDnsRecordId + ? `https://api.cloudflare.com/client/v4/zones/${cf.zoneId}/dns_records/${existingDnsRecordId}` + : `https://api.cloudflare.com/client/v4/zones/${cf.zoneId}/dns_records`, + apiToken: cf.apiToken, + body: { + type: "CNAME", + name: hostname, + content: `${tunnel.id}.cfargotunnel.com`, + proxied: true, + }, + }).pipe(Effect.flatMap((request) => executeJson(request, CloudflareDnsRecordResponse))); + + const token = yield* cloudflareRequest({ + method: "GET", + url: `https://api.cloudflare.com/client/v4/accounts/${cf.accountId}/cfd_tunnel/${tunnel.id}/token`, + apiToken: cf.apiToken, + }).pipe(Effect.flatMap((request) => executeJson(request, CloudflareTunnelTokenResponse))); + + return { + endpoint: { + httpBaseUrl: `https://${hostname}/`, + wsBaseUrl: `wss://${hostname}/ws`, + providerKind: "cloudflare_tunnel", + }, + runtime: { + providerKind: "cloudflare_tunnel", + connectorToken: token.result, + tunnelId: tunnel.id, + tunnelName: tunnel.name, + }, + } satisfies ManagedEndpointProvisioningResult; + }), + }); +}); + +export const layer = Layer.effect(ManagedEndpointProvider, make); diff --git a/infra/relay/src/services/MobileRegistrations.test.ts b/infra/relay/src/services/MobileRegistrations.test.ts new file mode 100644 index 0000000000..4750939405 --- /dev/null +++ b/infra/relay/src/services/MobileRegistrations.test.ts @@ -0,0 +1,461 @@ +import type { + RelayAgentActivityState, + RelayDeviceRegistrationRequest, +} from "@t3tools/contracts/relay"; +import type { SignedApnsDeliveryJob } from "../apnsDeliveryJobs.ts"; +import * as NodeCryptoLayer from "@effect/platform-node/NodeCrypto"; +import { describe, expect, it } from "@effect/vitest"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import * as Redacted from "effect/Redacted"; +import { FetchHttpClient } from "effect/unstable/http"; + +import * as Devices from "../persistence/Devices.ts"; +import * as AgentActivityRows from "../persistence/AgentActivityRows.ts"; +import * as DeliveryAttempts from "../persistence/DeliveryAttempts.ts"; +import * as EnvironmentLinks from "../persistence/EnvironmentLinks.ts"; +import * as LiveActivities from "../persistence/LiveActivities.ts"; +import * as RelayConfiguration from "../Config.ts"; +import * as AgentActivityPublisher from "./AgentActivityPublisher.ts"; +import * as ApnsDeliveries from "./ApnsDeliveries.ts"; +import * as ApnsDeliveryQueue from "./ApnsDeliveryQueue.ts"; +import * as MobileRegistrations from "./MobileRegistrations.ts"; + +const device: RelayDeviceRegistrationRequest = { + deviceId: "device-1" as RelayDeviceRegistrationRequest["deviceId"], + platform: "ios", + iosMajorVersion: 18, + appVersion: "1.0.0" as RelayDeviceRegistrationRequest["appVersion"], + preferences: { + liveActivitiesEnabled: true, + notificationsEnabled: true, + notifyOnApproval: true, + notifyOnInput: true, + notifyOnCompletion: true, + notifyOnFailure: true, + }, +}; + +function makeDevices(overrides: Partial = {}): Devices.DevicesShape { + return { + register: () => Effect.void, + unregister: () => Effect.void, + ...overrides, + }; +} + +function makeLiveActivities( + overrides: Partial = {}, +): LiveActivities.LiveActivitiesShape { + return { + register: () => Effect.void, + listTargets: () => Effect.succeed([]), + markDelivery: () => Effect.void, + markStartQueued: () => Effect.void, + clearStartQueued: () => Effect.void, + invalidateDeliveryToken: () => Effect.void, + ...overrides, + }; +} + +function makeAgentActivityRows( + overrides: Partial = {}, +): AgentActivityRows.AgentActivityRowsShape { + return { + upsert: () => Effect.void, + remove: () => Effect.void, + listForUser: () => { + const activeState: RelayAgentActivityState = { + environmentId: "env-1" as RelayAgentActivityState["environmentId"], + threadId: "thread-1" as RelayAgentActivityState["threadId"], + projectTitle: "Project", + threadTitle: "Implement APNs", + modelTitle: "gpt-5.4", + phase: "running", + headline: "Working", + updatedAt: "1970-01-01T00:00:10.000Z", + deepLink: "/env-1/thread-1", + }; + return Effect.succeed([activeState]); + }, + ...overrides, + }; +} + +function makeEnvironmentLinks( + overrides: Partial = {}, +): EnvironmentLinks.EnvironmentLinksShape { + return { + upsert: () => Effect.void, + listUsersForEnvironment: () => Effect.succeed(["dev:julius"]), + listDeliveryUsersForEnvironment: () => + Effect.succeed([ + { + userId: "dev:julius", + notificationsEnabled: true, + liveActivitiesEnabled: true, + }, + ]), + listPublicKeysForEnvironment: () => Effect.succeed([]), + listForUser: () => Effect.succeed([]), + getForUser: () => Effect.succeed(null), + revokeForUser: () => Effect.succeed(false), + ...overrides, + }; +} + +function makeDeliveryAttempts( + overrides: Partial = {}, +): DeliveryAttempts.DeliveryAttemptsShape { + return { + record: () => Effect.void, + claimSourceJob: () => Effect.succeed("claimed"), + completeSourceJob: () => Effect.void, + ...overrides, + }; +} + +const config = RelayConfiguration.RelayConfiguration.of({ + relayIssuer: "https://relay.example.test", + apns: { + environment: "sandbox", + teamId: "team-id", + keyId: "key-id", + bundleId: "codes.t3.mobile", + privateKey: Redacted.make("apns-private-key"), + }, + clerkSecretKey: Redacted.make("clerk-secret"), + apnsDeliveryJobSigningSecret: Redacted.make("apns-job-secret"), + cloudMintPrivateKey: Redacted.make("cloud-private-key"), + cloudMintPublicKey: "cloud-public-key", + managedEndpointBaseDomain: undefined, + cloudflareAccountId: undefined, + cloudflareZoneId: undefined, + cloudflareApiToken: undefined, +}); + +function makeRegistrationReplayLayer(input: { + readonly devices: Devices.DevicesShape; + readonly liveActivities: LiveActivities.LiveActivitiesShape; + readonly queuedJobs: Array; +}) { + return MobileRegistrations.layer.pipe( + Layer.provide(AgentActivityPublisher.layer), + Layer.provide(ApnsDeliveries.layer), + Layer.provide(ApnsDeliveryQueue.layer.pipe(Layer.provide(NodeCryptoLayer.layer))), + Layer.provide( + Layer.mergeAll( + Layer.succeed(Devices.Devices, input.devices), + Layer.succeed(AgentActivityRows.AgentActivityRows, makeAgentActivityRows()), + Layer.succeed(EnvironmentLinks.EnvironmentLinks, makeEnvironmentLinks()), + Layer.succeed(LiveActivities.LiveActivities, input.liveActivities), + Layer.succeed(DeliveryAttempts.DeliveryAttempts, makeDeliveryAttempts()), + Layer.succeed(RelayConfiguration.RelayConfiguration, config), + Layer.succeed(ApnsDeliveryQueue.ApnsDeliveryQueueSender, { + send: (body) => + Effect.sync(() => { + input.queuedJobs.push(body); + }), + }), + ), + ), + Layer.provide(FetchHttpClient.layer), + ); +} + +function makeAgentActivityPublisher( + overrides: Partial = {}, +): AgentActivityPublisher.AgentActivityPublisherShape { + return { + publish: () => Effect.succeed({ ok: true, deliveries: [] }), + replayForLiveActivityRegistration: () => Effect.succeed(null), + ...overrides, + }; +} + +describe("MobileRegistrations", () => { + it.effect("registers devices through the device persistence service", () => { + let registered: Parameters[0] | null = null; + let replayed: + | Parameters< + AgentActivityPublisher.AgentActivityPublisherShape["replayForLiveActivityRegistration"] + >[0] + | null = null; + + return Effect.gen(function* () { + const result = yield* Effect.gen(function* () { + const registrations = yield* MobileRegistrations.MobileRegistrations; + return yield* registrations.registerDevice({ userId: "dev:julius", payload: device }); + }).pipe( + Effect.provide( + MobileRegistrations.layer.pipe( + Layer.provide( + Layer.mergeAll( + Layer.succeed( + Devices.Devices, + makeDevices({ + register: (input) => + Effect.sync(() => { + registered = input; + }), + }), + ), + Layer.succeed(LiveActivities.LiveActivities, makeLiveActivities()), + Layer.succeed( + AgentActivityPublisher.AgentActivityPublisher, + makeAgentActivityPublisher({ + replayForLiveActivityRegistration: (input) => + Effect.sync(() => { + replayed = input; + return null; + }), + }), + ), + ), + ), + ), + ), + ); + + expect(result).toEqual({ ok: true }); + expect(registered).toEqual({ userId: "dev:julius", registration: device }); + expect(replayed).toEqual({ + userId: "dev:julius", + deviceId: "device-1", + }); + }); + }); + + it.effect("keeps device registration successful when activity replay fails", () => { + return Effect.gen(function* () { + const result = yield* Effect.gen(function* () { + const registrations = yield* MobileRegistrations.MobileRegistrations; + return yield* registrations.registerDevice({ userId: "dev:julius", payload: device }); + }).pipe( + Effect.provide( + MobileRegistrations.layer.pipe( + Layer.provide( + Layer.mergeAll( + Layer.succeed(Devices.Devices, makeDevices()), + Layer.succeed(LiveActivities.LiveActivities, makeLiveActivities()), + Layer.succeed( + AgentActivityPublisher.AgentActivityPublisher, + makeAgentActivityPublisher({ + replayForLiveActivityRegistration: () => + Effect.fail( + new AgentActivityRows.AgentActivityRowListPersistenceError({ + cause: "replay failed", + }), + ), + }), + ), + ), + ), + ), + ), + ); + + expect(result).toEqual({ ok: true }); + }); + }); + + it.effect("unregisters the current user's device", () => { + let unregistered: Parameters[0] | null = null; + + return Effect.gen(function* () { + const result = yield* Effect.gen(function* () { + const registrations = yield* MobileRegistrations.MobileRegistrations; + return yield* registrations.unregisterDevice({ + userId: "dev:julius", + deviceId: "device-1", + }); + }).pipe( + Effect.provide( + MobileRegistrations.layer.pipe( + Layer.provide( + Layer.mergeAll( + Layer.succeed( + Devices.Devices, + makeDevices({ + unregister: (input) => + Effect.sync(() => { + unregistered = input; + }), + }), + ), + Layer.succeed(LiveActivities.LiveActivities, makeLiveActivities()), + Layer.succeed( + AgentActivityPublisher.AgentActivityPublisher, + makeAgentActivityPublisher(), + ), + ), + ), + ), + ), + ); + + expect(result).toEqual({ ok: true }); + expect(unregistered).toEqual({ + userId: "dev:julius", + deviceId: "device-1", + }); + }); + }); + + it.effect("replays the latest activity state after registering a Live Activity token", () => { + const liveActivity = { + deviceId: "device-1" as const, + activityPushToken: "activity-token" as const, + }; + let registered: Parameters[0] | null = null; + let replayed: + | Parameters< + AgentActivityPublisher.AgentActivityPublisherShape["replayForLiveActivityRegistration"] + >[0] + | null = null; + + return Effect.gen(function* () { + const result = yield* Effect.gen(function* () { + const registrations = yield* MobileRegistrations.MobileRegistrations; + return yield* registrations.registerLiveActivity({ + userId: "dev:julius", + payload: liveActivity, + }); + }).pipe( + Effect.provide( + MobileRegistrations.layer.pipe( + Layer.provide( + Layer.mergeAll( + Layer.succeed(Devices.Devices, makeDevices()), + Layer.succeed( + LiveActivities.LiveActivities, + makeLiveActivities({ + register: (input) => + Effect.sync(() => { + registered = input; + }), + }), + ), + Layer.succeed( + AgentActivityPublisher.AgentActivityPublisher, + makeAgentActivityPublisher({ + replayForLiveActivityRegistration: (input) => + Effect.sync(() => { + replayed = input; + return null; + }), + }), + ), + ), + ), + ), + ), + ); + + expect(result).toEqual({ ok: true }); + expect(registered).toEqual({ + userId: "dev:julius", + registration: liveActivity, + }); + expect(replayed).toEqual({ + userId: "dev:julius", + deviceId: "device-1", + }); + }); + }); + + it.effect( + "starts a remote Live Activity through the real publisher and APNs queue when a device registers after work is already active", + () => { + const queuedJobs: Array = []; + const queuedStarts: Array< + Parameters[0] + > = []; + const registeredDevices: Array[0]> = []; + const devices = makeDevices({ + register: (input) => + Effect.sync(() => { + registeredDevices.push(input); + }), + }); + const liveActivities = makeLiveActivities({ + listTargets: () => + Effect.succeed([ + { + user_id: "dev:julius", + device_id: "device-1", + platform: "ios", + ios_major_version: 18, + app_version: "1.0.0", + push_token: "apns-device-token", + push_to_start_token: "push-to-start-token", + preferences_json: JSON.stringify(device.preferences), + activity_push_token: null, + remote_start_queued_at: null, + remote_started_at: null, + ended_at: null, + last_aggregate_json: null, + last_live_activity_delivery_at: null, + }, + ]), + markStartQueued: (input) => + Effect.sync(() => { + queuedStarts.push(input); + }), + }); + + return Effect.gen(function* () { + const registrations = yield* MobileRegistrations.MobileRegistrations; + const result = yield* registrations.registerDevice({ + userId: "dev:julius", + payload: { + ...device, + pushToken: "apns-device-token", + pushToStartToken: "push-to-start-token", + }, + }); + + expect(result).toEqual({ ok: true }); + expect(registeredDevices).toEqual([ + { + userId: "dev:julius", + registration: { + ...device, + pushToken: "apns-device-token", + pushToStartToken: "push-to-start-token", + }, + }, + ]); + expect(queuedStarts).toMatchObject([ + { + userId: "dev:julius", + deviceId: "device-1", + }, + ]); + expect(queuedJobs).toHaveLength(1); + expect(queuedJobs[0]?.payload).toMatchObject({ + kind: "live_activity_start", + target: { + userId: "dev:julius", + deviceId: "device-1", + token: "push-to-start-token", + }, + aggregate: { + title: "T3 Code", + subtitle: "Agent work in progress", + activeCount: 1, + activities: [ + { + environmentId: "env-1", + threadId: "thread-1", + threadTitle: "Implement APNs", + status: "Working", + }, + ], + }, + notification: null, + }); + }).pipe(Effect.provide(makeRegistrationReplayLayer({ devices, liveActivities, queuedJobs }))); + }, + ); +}); diff --git a/infra/relay/src/services/MobileRegistrations.ts b/infra/relay/src/services/MobileRegistrations.ts new file mode 100644 index 0000000000..8bc0395d2a --- /dev/null +++ b/infra/relay/src/services/MobileRegistrations.ts @@ -0,0 +1,101 @@ +import type { + RelayDeviceRegistrationRequest, + RelayLiveActivityRegistrationRequest, +} from "@t3tools/contracts/relay"; +import * as Context from "effect/Context"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; + +import * as Devices from "../persistence/Devices.ts"; +import * as LiveActivities from "../persistence/LiveActivities.ts"; +import { withUserId } from "../telemetry.ts"; +import * as AgentActivityPublisher from "./AgentActivityPublisher.ts"; + +export type MobileRegistrationError = + | Devices.DeviceRegistrationPersistenceError + | Devices.DeviceUnregistrationPersistenceError + | LiveActivities.LiveActivityRegistrationPersistenceError; + +export interface MobileRegistrationsShape { + readonly registerDevice: (input: { + readonly userId: string; + readonly payload: RelayDeviceRegistrationRequest; + }) => Effect.Effect<{ readonly ok: true }, MobileRegistrationError>; + readonly registerLiveActivity: (input: { + readonly userId: string; + readonly payload: RelayLiveActivityRegistrationRequest; + }) => Effect.Effect<{ readonly ok: true }, MobileRegistrationError>; + readonly unregisterDevice: (input: { + readonly userId: string; + readonly deviceId: string; + }) => Effect.Effect<{ readonly ok: true }, MobileRegistrationError>; +} + +export class MobileRegistrations extends Context.Service< + MobileRegistrations, + MobileRegistrationsShape +>()("MobileRegistrations") {} + +const make = Effect.gen(function* () { + const devices = yield* Devices.Devices; + const liveActivities = yield* LiveActivities.LiveActivities; + const publisher = yield* AgentActivityPublisher.AgentActivityPublisher; + + return MobileRegistrations.of({ + registerDevice: Effect.fn("relay.mobile_registrations.register_device")( + function* (input) { + yield* Effect.annotateCurrentSpan({ + "relay.mobile.device_id": input.payload.deviceId, + "relay.mobile.platform": input.payload.platform, + }); + yield* devices.register({ userId: input.userId, registration: input.payload }); + yield* publisher + .replayForLiveActivityRegistration({ + userId: input.userId, + deviceId: input.payload.deviceId, + }) + .pipe( + Effect.tapError((cause) => + Effect.logWarning("device registration activity replay failed", { cause }), + ), + Effect.ignore, + ); + return { ok: true as const }; + }, + (effect, input) => effect.pipe(withUserId(input.userId)), + ), + registerLiveActivity: Effect.fn("relay.mobile_registrations.register_live_activity")( + function* (input) { + yield* Effect.annotateCurrentSpan({ + "relay.mobile.device_id": input.payload.deviceId, + }); + yield* liveActivities.register({ userId: input.userId, registration: input.payload }); + yield* publisher + .replayForLiveActivityRegistration({ + userId: input.userId, + deviceId: input.payload.deviceId, + }) + .pipe( + Effect.tapError((cause) => + Effect.logWarning("live activity registration replay failed", { cause }), + ), + Effect.ignore, + ); + return { ok: true as const }; + }, + (effect, input) => effect.pipe(withUserId(input.userId)), + ), + unregisterDevice: Effect.fn("relay.mobile_registrations.unregister_device")( + function* (input) { + yield* Effect.annotateCurrentSpan({ + "relay.mobile.device_id": input.deviceId, + }); + yield* devices.unregister(input); + return { ok: true as const }; + }, + (effect, input) => effect.pipe(withUserId(input.userId)), + ), + }); +}); + +export const layer = Layer.effect(MobileRegistrations, make); diff --git a/infra/relay/src/telemetry.test.ts b/infra/relay/src/telemetry.test.ts new file mode 100644 index 0000000000..51cd36d838 --- /dev/null +++ b/infra/relay/src/telemetry.test.ts @@ -0,0 +1,31 @@ +import { describe, expect, it } from "@effect/vitest"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import * as Tracer from "effect/Tracer"; + +import { withUserId } from "./telemetry.ts"; + +describe("relay telemetry", () => { + it.effect("annotates the active span and descendant spans with the user id", () => + Effect.gen(function* () { + const spans: Array = []; + const tracer = Tracer.make({ + span: (options) => { + const span = new Tracer.NativeSpan(options); + spans.push(span); + return span; + }, + }); + + yield* Effect.succeed("ok").pipe( + Effect.withSpan("relay.test.child"), + withUserId("user-123"), + Effect.withSpan("relay.test.parent"), + Effect.provide(Layer.succeed(Tracer.Tracer, tracer)), + ); + + expect(spans.map((span) => span.name)).toEqual(["relay.test.parent", "relay.test.child"]); + expect(spans.map((span) => span.attributes.get("user.id"))).toEqual(["user-123", "user-123"]); + }), + ); +}); diff --git a/infra/relay/src/telemetry.ts b/infra/relay/src/telemetry.ts new file mode 100644 index 0000000000..c82454e5b9 --- /dev/null +++ b/infra/relay/src/telemetry.ts @@ -0,0 +1,10 @@ +import * as Effect from "effect/Effect"; + +export const withSpanAttributes = + (attributes: Record) => + (effect: Effect.Effect): Effect.Effect => + Effect.annotateCurrentSpan(attributes).pipe( + Effect.andThen(effect.pipe(Effect.annotateSpans(attributes))), + ); + +export const withUserId = (userId: string) => withSpanAttributes({ "user.id": userId }); diff --git a/infra/relay/src/worker.ts b/infra/relay/src/worker.ts new file mode 100644 index 0000000000..4543050917 --- /dev/null +++ b/infra/relay/src/worker.ts @@ -0,0 +1,295 @@ +import * as Alchemy from "alchemy"; +import * as Cloudflare from "alchemy/Cloudflare"; +import * as Drizzle from "alchemy/Drizzle"; +import * as Config from "effect/Config"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import * as Redacted from "effect/Redacted"; +import * as Stream from "effect/Stream"; +import * as Etag from "effect/unstable/http/Etag"; +import * as HttpRouter from "effect/unstable/http/HttpRouter"; +import * as HttpApiBuilder from "effect/unstable/httpapi/HttpApiBuilder"; +import * as OtlpSerialization from "effect/unstable/observability/OtlpSerialization"; +import * as OtlpTracer from "effect/unstable/observability/OtlpTracer"; + +import { RelayApi } from "@t3tools/contracts/relay"; + +import { + RelayHttpPlatformLayer, + clientApi, + dpopClientApi, + healthApi, + metadataApi, + mobileApi, + relayClientAuthLayer, + relayDpopClientAuthLayer, + relayCors, + relayEnvironmentAuthLayer, + relayNotFoundRoute, + serverApi, + traceRelayHttpRequestWith, + tokenApi, + withoutCapturedParentSpan, +} from "./api.ts"; +import { + MANAGED_ENDPOINT_BASE_DOMAIN, + MANAGED_ENDPOINT_PROVISIONER_TOKEN_POLICIES, + MANAGED_ENDPOINT_ZONE, + RELAY_PUBLIC_DOMAIN, + RELAY_PUBLIC_ORIGIN, +} from "./infra/ManagedEndpointStackConfig.ts"; +import { + RELAY_AXIOM_TRACE_DATASET, + RELAY_OBSERVABILITY_EXPORT_INTERVAL, + RELAY_OBSERVABILITY_SERVICE_NAME, + provisionRelayObservability, +} from "./infra/RelayObservability.ts"; +import * as DeliveryAttempts from "./persistence/DeliveryAttempts.ts"; +import * as AgentActivityRows from "./persistence/AgentActivityRows.ts"; +import * as Devices from "./persistence/Devices.ts"; +import * as DpopProofs from "./persistence/DpopProofs.ts"; +import * as EnvironmentCredentials from "./persistence/EnvironmentCredentials.ts"; +import * as EnvironmentLinks from "./persistence/EnvironmentLinks.ts"; +import * as LiveActivities from "./persistence/LiveActivities.ts"; +import { RelayDb, RelayHyperdrive } from "./db.ts"; +import { RelayApnsDeliveryDeadLetterQueue, RelayApnsDeliveryQueue } from "./queues.ts"; +import * as RelayConfiguration from "./Config.ts"; +import * as AgentActivityPublisher from "./services/AgentActivityPublisher.ts"; +import * as ApnsDeliveryQueue from "./services/ApnsDeliveryQueue.ts"; +import * as ApnsDeliveries from "./services/ApnsDeliveries.ts"; +import * as EnvironmentConnector from "./services/EnvironmentConnector.ts"; +import * as EnvironmentLinker from "./services/EnvironmentLinker.ts"; +import * as EnvironmentPublishSignatures from "./services/EnvironmentPublishSignatures.ts"; +import * as ManagedEndpointProvider from "./services/ManagedEndpointProvider.ts"; +import * as MobileRegistrations from "./services/MobileRegistrations.ts"; +import * as RelayCrypto from "./RelayCrypto.ts"; + +const relayApiLayer = Layer.mergeAll( + healthApi, + metadataApi, + mobileApi, + clientApi, + tokenApi, + dpopClientApi, + serverApi, +); + +const makeRelayTraceLayer = (input: { + readonly tracesEndpoint: string; + readonly tracesDatasetName: string; + readonly ingestToken: Redacted.Redacted; +}) => + OtlpTracer.layer({ + url: input.tracesEndpoint, + resource: { + serviceName: RELAY_OBSERVABILITY_SERVICE_NAME, + attributes: { + "service.runtime": "cloudflare-worker", + "service.component": "relay", + }, + }, + headers: { + Authorization: `Bearer ${Redacted.value(input.ingestToken)}`, + "X-Axiom-Dataset": input.tracesDatasetName, + }, + exportInterval: RELAY_OBSERVABILITY_EXPORT_INTERVAL, + }).pipe(Layer.provide(OtlpSerialization.layerJson)); + +// Bind secrets explicitly and only read them through the runtime worker +// environment. Reading them through Config during Worker init currently +// registers a competing plaintext binding. +const apnsPrivateKeyConfig = Config.redacted("APNS_PRIVATE_KEY"); +const clerkSecretKeyConfig = Config.redacted("CLERK_SECRET_KEY"); + +export default class Api extends Cloudflare.Worker()( + "Api", + { + main: import.meta.filename, + compatibility: { + date: "2026-05-22", + flags: ["nodejs_compat"], + }, + domain: RELAY_PUBLIC_DOMAIN, + env: { + APNS_PRIVATE_KEY: apnsPrivateKeyConfig, + CLERK_SECRET_KEY: clerkSecretKeyConfig, + }, + }, + Effect.gen(function* () { + const managedEndpointProvisionerToken = yield* Cloudflare.AccountApiToken( + "ManagedEndpointProvisionerToken", + { + name: "t3-code-relay-managed-endpoint-provisioner", + policies: MANAGED_ENDPOINT_PROVISIONER_TOKEN_POLICIES, + }, + ); + const managedEndpointCloudflareApiToken = yield* managedEndpointProvisionerToken.value; + const relayHyperdrive = yield* RelayHyperdrive; + const apnsDeliveryQueue = yield* RelayApnsDeliveryQueue; + const apnsDeliveryDeadLetterQueue = yield* RelayApnsDeliveryDeadLetterQueue; + const hyperdrive = yield* Cloudflare.Hyperdrive.bind(relayHyperdrive); + const apnsDeliveryQueueSender = yield* Cloudflare.QueueBinding.bind(apnsDeliveryQueue); + const cloudMintKeyPair = yield* Alchemy.KeyPair("CloudMintKeyPair"); + const environment = yield* Config.schema( + RelayConfiguration.ApnsEnvironment, + "APNS_ENVIRONMENT", + ).pipe(Config.withDefault("sandbox")); + const apnsTeamId = yield* Config.string("APNS_TEAM_ID"); + const apnsKeyId = yield* Config.string("APNS_KEY_ID"); + const apnsBundleId = yield* Config.string("APNS_BUNDLE_ID"); + const relayObservability = yield* provisionRelayObservability; + const axiomIngestToken = yield* relayObservability.ingestToken.token; + const axiomTracesEndpoint = yield* relayObservability.traces.otelTracesEndpoint; + const relayTraceLayer = Effect.all({ + tracesEndpoint: axiomTracesEndpoint, + ingestToken: axiomIngestToken, + }).pipe( + Effect.map((input) => + makeRelayTraceLayer({ ...input, tracesDatasetName: RELAY_AXIOM_TRACE_DATASET }), + ), + Layer.unwrap, + ); + const randomApnsDeliveryJobSigningSecret = yield* Alchemy.Random( + "ApnsDeliveryJobSigningSecret", + { bytes: 32 }, + ); + const apnsDeliveryJobSigningSecret = yield* randomApnsDeliveryJobSigningSecret.text; + const cloudMintPrivateKey = yield* cloudMintKeyPair.privateKey; + const cloudMintPublicKey = yield* cloudMintKeyPair.publicKey; + const db = yield* Drizzle.postgres(hyperdrive.connectionString); + + const loadSettings = Effect.gen(function* () { + const workerEnvironment = yield* Cloudflare.WorkerEnvironment; + const apnsPrivateKey = Redacted.make(workerEnvironment.APNS_PRIVATE_KEY); + const clerkSecretKey = Redacted.make(workerEnvironment.CLERK_SECRET_KEY); + return RelayConfiguration.RelayConfiguration.of({ + relayIssuer: RELAY_PUBLIC_ORIGIN, + apns: { + environment, + teamId: apnsTeamId, + keyId: apnsKeyId, + bundleId: apnsBundleId, + privateKey: apnsPrivateKey, + }, + apnsDeliveryJobSigningSecret: yield* apnsDeliveryJobSigningSecret, + clerkSecretKey, + cloudMintPrivateKey: yield* cloudMintPrivateKey, + cloudMintPublicKey: yield* cloudMintPublicKey, + managedEndpointBaseDomain: MANAGED_ENDPOINT_BASE_DOMAIN, + cloudflareAccountId: MANAGED_ENDPOINT_ZONE.accountId, + cloudflareZoneId: MANAGED_ENDPOINT_ZONE.zoneId, + cloudflareApiToken: yield* managedEndpointCloudflareApiToken, + }); + }); + + const runtimeLayer = Layer.unwrap( + Effect.gen(function* () { + const settings = yield* loadSettings; + return Layer.mergeAll( + MobileRegistrations.layer.pipe(Layer.provideMerge(AgentActivityPublisher.layer)), + EnvironmentConnector.layer, + EnvironmentLinker.layer.pipe( + Layer.provideMerge(ManagedEndpointProvider.layer), + Layer.provideMerge(DpopProofs.layer), + ), + EnvironmentPublishSignatures.layer.pipe(Layer.provideMerge(DpopProofs.layer)), + DpopProofs.layer, + ).pipe( + Layer.provide(ApnsDeliveries.layer), + Layer.provide(ApnsDeliveryQueue.layer), + Layer.provide(AgentActivityRows.layer), + Layer.provide(Devices.layer), + Layer.provide(EnvironmentCredentials.layer), + Layer.provide(EnvironmentLinks.layer), + Layer.provide(LiveActivities.layer), + Layer.provide(DeliveryAttempts.layer), + Layer.provide(Layer.succeed(RelayDb, db)), + Layer.provide( + Layer.succeed(ApnsDeliveryQueue.ApnsDeliveryQueueSender, { + send: (body) => + apnsDeliveryQueueSender + .send(body) + .pipe( + Effect.mapError( + (cause) => new ApnsDeliveryQueue.ApnsDeliveryQueueSendError({ cause }), + ), + ) as Effect.Effect, + }), + ), + Layer.provide(Layer.succeed(RelayConfiguration.RelayConfiguration, settings)), + Layer.provide(RelayCrypto.layer), + ); + }), + ); + + const appLayer = Layer.unwrap( + Effect.gen(function* () { + const settings = yield* loadSettings; + return relayApiLayer.pipe( + Layer.provide(runtimeLayer), + Layer.provide(relayClientAuthLayer), + Layer.provide(relayDpopClientAuthLayer), + Layer.provide(relayEnvironmentAuthLayer), + Layer.provide(EnvironmentCredentials.layer), + Layer.provide(EnvironmentLinks.layer), + Layer.provide(Layer.succeed(RelayDb, db)), + Layer.provideMerge(Layer.succeed(RelayConfiguration.RelayConfiguration, settings)), + Layer.provide(RelayCrypto.layer), + ); + }), + ); + + yield* Cloudflare.messages(apnsDeliveryQueue, { + batchSize: 10, + maxRetries: 5, + maxWaitTime: "5 seconds", + retryDelay: "30 seconds", + // Alchemy beta.45 expects a resolved string here although Queue names are Outputs. + deadLetterQueue: apnsDeliveryDeadLetterQueue.queueName as unknown as string, + }).subscribe((stream) => + stream.pipe( + Stream.withSpan("relay.apn_delivery_queue.process_batch"), + Stream.runForEach( + Effect.fn("relay.apn_delivery_queue.process_message")((message) => + ApnsDeliveries.ApnsDeliveries.pipe( + Effect.flatMap((deliveries) => deliveries.processSignedJob(message.body)), + ), + ), + ), + Effect.provide(runtimeLayer), + ), + ); + + yield* Cloudflare.cron("*/5 * * * *").subscribe(() => + DpopProofs.DpopProofReplay.pipe( + Effect.flatMap((dpopProofs) => dpopProofs.pruneExpired), + Effect.withSpan("relay.cron.prune_expired_dpop_proofs"), + Effect.provide(runtimeLayer), + ), + ); + + const fetch = Layer.merge( + HttpApiBuilder.layer(RelayApi).pipe( + Layer.provide(appLayer), + Layer.provide([Etag.layerWeak, RelayHttpPlatformLayer, relayCors]), + ), + relayNotFoundRoute, + ).pipe( + HttpRouter.toHttpEffect, + withoutCapturedParentSpan, + Effect.map((httpEffect) => traceRelayHttpRequestWith(httpEffect, relayTraceLayer)), + Effect.flatten, + ); + + return { fetch }; + }).pipe( + Effect.provide( + Layer.mergeAll( + Cloudflare.HyperdriveBindingLive, + Cloudflare.CronEventSourceLive, + Cloudflare.QueueBindingLive, + Cloudflare.QueueEventSourceLive, + ), + ), + ), +) {} diff --git a/infra/relay/tsconfig.json b/infra/relay/tsconfig.json new file mode 100644 index 0000000000..67e2a2c773 --- /dev/null +++ b/infra/relay/tsconfig.json @@ -0,0 +1,9 @@ +{ + "extends": "../../tsconfig.base.json", + "compilerOptions": { + "target": "ES2023", + "lib": ["ES2023", "WebWorker"], + "types": ["@cloudflare/workers-types", "node"] + }, + "include": ["alchemy.run.ts", "src/**/*.ts"] +} diff --git a/packages/client-runtime/src/index.ts b/packages/client-runtime/src/index.ts index 51efb313ee..7aa36d29fb 100644 --- a/packages/client-runtime/src/index.ts +++ b/packages/client-runtime/src/index.ts @@ -26,3 +26,4 @@ export * from "./composerPathSearchState.ts"; export * from "./archivedThreadsState.ts"; export * from "./checkpointDiffState.ts"; export * from "./remote.ts"; +export * from "./managedRelay.ts"; diff --git a/packages/client-runtime/src/managedRelay.test.ts b/packages/client-runtime/src/managedRelay.test.ts new file mode 100644 index 0000000000..4eefdb29d0 --- /dev/null +++ b/packages/client-runtime/src/managedRelay.test.ts @@ -0,0 +1,114 @@ +import { EnvironmentId } from "@t3tools/contracts"; +import { RelayEnvironmentStatusScope } from "@t3tools/contracts/relay"; +import { describe, expect, it } from "@effect/vitest"; +import * as Duration from "effect/Duration"; +import * as Effect from "effect/Effect"; +import * as Fiber from "effect/Fiber"; +import * as Layer from "effect/Layer"; +import * as TestClock from "effect/testing/TestClock"; + +import { + MANAGED_RELAY_REQUEST_TIMEOUT_MS, + ManagedRelayClient, + ManagedRelayDpopSigner, + managedRelayClientLayer, + type ManagedRelayDpopProofInput, +} from "./managedRelay.ts"; +import { remoteHttpClientLayer } from "./remote.ts"; + +function managedRelayTestLayer(fetchFn: typeof globalThis.fetch) { + const httpClientLayer = remoteHttpClientLayer(fetchFn); + const signerLayer = Layer.succeed( + ManagedRelayDpopSigner, + ManagedRelayDpopSigner.of({ + thumbprint: Effect.succeed("client-thumbprint"), + createProof: (input: ManagedRelayDpopProofInput) => Effect.succeed(`proof:${input.url}`), + }), + ); + return managedRelayClientLayer({ + relayUrl: "https://relay.example.test", + clientId: "t3-mobile", + }).pipe(Layer.provide(signerLayer), Layer.provide(httpClientLayer)); +} + +describe("ManagedRelayClient", () => { + it.effect("reuses usable DPoP tokens and refreshes cleared or expiring cache entries", () => { + let tokenExchangeCount = 0; + const fetchFn = ((input) => { + const url = String(input); + if (url.endsWith("/v1/client/dpop-token")) { + tokenExchangeCount += 1; + return Promise.resolve( + Response.json({ + access_token: `relay-token-${tokenExchangeCount}`, + issued_token_type: "urn:ietf:params:oauth:token-type:access_token", + token_type: "DPoP", + expires_in: 10, + scope: RelayEnvironmentStatusScope, + }), + ); + } + return Promise.resolve( + Response.json({ + environmentId: "env-1", + endpoint: { + httpBaseUrl: "https://desktop.example.test/", + wsBaseUrl: "wss://desktop.example.test/ws", + providerKind: "cloudflare_tunnel", + }, + status: "online", + checkedAt: "2026-05-25T00:01:00.000Z", + descriptor: { + environmentId: "env-1", + label: "Desktop", + platform: { os: "darwin", arch: "arm64" }, + serverVersion: "0.0.0-test", + capabilities: { repositoryIdentity: true }, + }, + }), + ); + }) satisfies typeof globalThis.fetch; + + return Effect.gen(function* () { + const relayClient = yield* ManagedRelayClient; + const statusInput = { + clerkToken: "clerk-token", + scopes: [RelayEnvironmentStatusScope], + environmentId: EnvironmentId.make("env-1"), + } as const; + + yield* relayClient.getEnvironmentStatus(statusInput); + yield* relayClient.getEnvironmentStatus(statusInput); + expect(tokenExchangeCount).toBe(1); + + yield* TestClock.adjust(Duration.seconds(6)); + yield* relayClient.getEnvironmentStatus(statusInput); + expect(tokenExchangeCount).toBe(2); + + yield* relayClient.resetTokenCache; + yield* relayClient.getEnvironmentStatus(statusInput); + expect(tokenExchangeCount).toBe(3); + }).pipe(Effect.provide(managedRelayTestLayer(fetchFn))); + }); + + it.effect("times out stalled relay environment listing requests", () => { + const fetchFn = (() => + new Promise(() => undefined)) satisfies typeof globalThis.fetch; + + return Effect.gen(function* () { + const relayClient = yield* ManagedRelayClient; + const errorFiber = yield* relayClient + .listEnvironments({ clerkToken: "clerk-token" }) + .pipe(Effect.flip, Effect.forkScoped); + + yield* Effect.yieldNow; + yield* TestClock.adjust(Duration.millis(MANAGED_RELAY_REQUEST_TIMEOUT_MS)); + const error = yield* Fiber.join(errorFiber); + + expect(error).toMatchObject({ + _tag: "ManagedRelayClientError", + message: "Relay environment listing timed out.", + }); + }).pipe(Effect.provide(Layer.merge(TestClock.layer(), managedRelayTestLayer(fetchFn)))); + }); +}); diff --git a/packages/client-runtime/src/managedRelay.ts b/packages/client-runtime/src/managedRelay.ts new file mode 100644 index 0000000000..90d41a7ede --- /dev/null +++ b/packages/client-runtime/src/managedRelay.ts @@ -0,0 +1,470 @@ +import { + RelayAccessTokenType, + RelayApi, + type RelayClientEnvironmentRecord, + RelayConnectEnvironmentEndpoint, + type RelayDeviceRegistrationRequest, + type RelayDpopAccessTokenScope, + RelayDpopTokenExchangeGrantType, + type RelayEnvironmentConnectRequest, + type RelayEnvironmentConnectResponse, + type RelayEnvironmentLinkChallengeRequest, + type RelayEnvironmentLinkChallengeResponse, + type RelayEnvironmentLinkRequest, + type RelayEnvironmentLinkResponse, + type RelayEnvironmentStatusResponse, + RelayExchangeDpopAccessTokenEndpoint, + RelayGetEnvironmentStatusEndpoint, + RelayJwtSubjectTokenType, + type RelayLiveActivityRegistrationRequest, + RelayMobileRegistrationScope, + type RelayOkResponse, + type RelayPublicClientId, + RelayRegisterDeviceEndpoint, + RelayRegisterLiveActivityEndpoint, + RelayUnregisterDeviceEndpoint, +} from "@t3tools/contracts/relay"; +import { encodeOAuthScope, oauthScopeSetEquals } from "@t3tools/shared/oauthScope"; +import * as Clock from "effect/Clock"; +import * as Context from "effect/Context"; +import * as Data from "effect/Data"; +import * as Duration from "effect/Duration"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import * as Option from "effect/Option"; +import * as SynchronizedRef from "effect/SynchronizedRef"; +import type { HttpMethod } from "effect/unstable/http/HttpMethod"; +import * as HttpApiClient from "effect/unstable/httpapi/HttpApiClient"; + +export interface ManagedRelayDpopProofInput { + readonly method: HttpMethod; + readonly url: string; + readonly accessToken?: string; +} + +export class ManagedRelayDpopSignerError extends Data.TaggedError("ManagedRelayDpopSignerError")<{ + readonly cause: unknown; +}> {} + +export interface ManagedRelayDpopSignerShape { + readonly thumbprint: Effect.Effect; + readonly createProof: ( + input: ManagedRelayDpopProofInput, + ) => Effect.Effect; +} + +export class ManagedRelayDpopSigner extends Context.Service< + ManagedRelayDpopSigner, + ManagedRelayDpopSignerShape +>()("@t3tools/client-runtime/managedRelay/ManagedRelayDpopSigner") {} + +export class ManagedRelayClientError extends Data.TaggedError("ManagedRelayClientError")<{ + readonly message: string; + readonly cause?: unknown; +}> {} + +export const MANAGED_RELAY_REQUEST_TIMEOUT_MS = 10_000; + +interface CachedRelayAccessToken { + readonly clerkToken: string; + readonly thumbprint: string; + readonly scopes: ReadonlyArray; + readonly accessToken: string; + readonly expiresAtMillis: number; +} + +export interface ManagedRelayAuthorization { + readonly accessToken: string; + readonly proof: string; + readonly thumbprint: string; +} + +export interface ManagedRelayClientLayerOptions { + readonly relayUrl: string; + readonly clientId: RelayPublicClientId; +} + +export interface ManagedRelayClientShape { + readonly relayUrl: string; + readonly listEnvironments: (input: { + readonly clerkToken: string; + }) => Effect.Effect, ManagedRelayClientError>; + readonly createEnvironmentLinkChallenge: (input: { + readonly clerkToken: string; + readonly payload: RelayEnvironmentLinkChallengeRequest; + }) => Effect.Effect; + readonly linkEnvironment: (input: { + readonly clerkToken: string; + readonly payload: RelayEnvironmentLinkRequest; + }) => Effect.Effect; + readonly unlinkEnvironment: (input: { + readonly clerkToken: string; + readonly environmentId: RelayClientEnvironmentRecord["environmentId"]; + }) => Effect.Effect; + readonly getEnvironmentStatus: (input: { + readonly clerkToken: string; + readonly scopes: ReadonlyArray; + readonly environmentId: RelayClientEnvironmentRecord["environmentId"]; + }) => Effect.Effect; + readonly connectEnvironment: (input: { + readonly clerkToken: string; + readonly scopes: ReadonlyArray; + readonly environmentId: RelayClientEnvironmentRecord["environmentId"]; + readonly deviceId?: string; + }) => Effect.Effect; + readonly registerDevice: (input: { + readonly clerkToken: string; + readonly payload: RelayDeviceRegistrationRequest; + }) => Effect.Effect; + readonly unregisterDevice: (input: { + readonly clerkToken: string; + readonly deviceId: string; + }) => Effect.Effect; + readonly registerLiveActivity: (input: { + readonly clerkToken: string; + readonly payload: RelayLiveActivityRegistrationRequest; + }) => Effect.Effect; + readonly resetTokenCache: Effect.Effect; +} + +export class ManagedRelayClient extends Context.Service< + ManagedRelayClient, + ManagedRelayClientShape +>()("@t3tools/client-runtime/managedRelay/ManagedRelayClient") {} + +function relayClientError(message: string, cause?: unknown): ManagedRelayClientError { + return new ManagedRelayClientError({ message, ...(cause === undefined ? {} : { cause }) }); +} + +function timeoutRelayRequest(message: string) { + return ( + request: Effect.Effect, + ): Effect.Effect => + request.pipe( + Effect.timeoutOption(Duration.millis(MANAGED_RELAY_REQUEST_TIMEOUT_MS)), + Effect.flatMap( + Option.match({ + onNone: () => Effect.fail(relayClientError(message)), + onSome: Effect.succeed, + }), + ), + ); +} + +function tokenMatches( + token: CachedRelayAccessToken, + input: { + readonly clerkToken: string; + readonly thumbprint: string; + readonly scopes: ReadonlyArray; + readonly nowMillis: number; + }, +): boolean { + return ( + token.clerkToken === input.clerkToken && + token.thumbprint === input.thumbprint && + token.expiresAtMillis > input.nowMillis + 5_000 && + input.scopes.every((scope) => token.scopes.includes(scope)) + ); +} + +function bearerHeaders(clerkToken: string) { + return { authorization: `Bearer ${clerkToken}` }; +} + +function dpopHeaders(authorization: ManagedRelayAuthorization) { + return { + authorization: `DPoP ${authorization.accessToken}`, + dpop: authorization.proof, + }; +} + +export function managedRelayClientLayer(options: ManagedRelayClientLayerOptions) { + return Layer.effect( + ManagedRelayClient, + Effect.gen(function* () { + const signer = yield* ManagedRelayDpopSigner; + const client = yield* HttpApiClient.make(RelayApi, { baseUrl: options.relayUrl }); + const cachedTokens = yield* SynchronizedRef.make>([]); + const urlBuilder = HttpApiClient.urlBuilder(RelayApi, { baseUrl: options.relayUrl }); + + type DpopProofTarget = Pick; + const dpopProofTargets = { + exchangeAccessToken: (): DpopProofTarget => ({ + method: RelayExchangeDpopAccessTokenEndpoint.method, + url: urlBuilder.token.exchangeDpopAccessToken(), + }), + getEnvironmentStatus: ( + environmentId: RelayClientEnvironmentRecord["environmentId"], + ): DpopProofTarget => ({ + method: RelayGetEnvironmentStatusEndpoint.method, + url: urlBuilder.dpopClient.getEnvironmentStatus({ params: { environmentId } }), + }), + connectEnvironment: ( + environmentId: RelayClientEnvironmentRecord["environmentId"], + ): DpopProofTarget => ({ + method: RelayConnectEnvironmentEndpoint.method, + url: urlBuilder.dpopClient.connectEnvironment({ params: { environmentId } }), + }), + registerDevice: (): DpopProofTarget => ({ + method: RelayRegisterDeviceEndpoint.method, + url: urlBuilder.mobile.registerDevice(), + }), + unregisterDevice: (deviceId: string): DpopProofTarget => ({ + method: RelayUnregisterDeviceEndpoint.method, + url: urlBuilder.mobile.unregisterDevice({ params: { deviceId } }), + }), + registerLiveActivity: (): DpopProofTarget => ({ + method: RelayRegisterLiveActivityEndpoint.method, + url: urlBuilder.mobile.registerLiveActivity(), + }), + }; + + const obtainAccessToken = Effect.fn("clientRuntime.managedRelay.obtainAccessToken")( + function* (input: { + readonly clerkToken: string; + readonly scopes: ReadonlyArray; + readonly thumbprint: string; + }) { + const nowMillis = yield* Clock.currentTimeMillis; + return yield* SynchronizedRef.modifyEffect(cachedTokens, (tokens) => { + const activeTokens = tokens.filter( + (token) => token.expiresAtMillis > nowMillis + 5_000, + ); + const cached = activeTokens.find((token) => + tokenMatches(token, { ...input, nowMillis }), + ); + if (cached) { + return Effect.succeed([cached, activeTokens] as const); + } + return Effect.gen(function* () { + const proof = yield* signer + .createProof(dpopProofTargets.exchangeAccessToken()) + .pipe( + Effect.mapError((cause) => + relayClientError("Could not create relay token DPoP proof.", cause), + ), + ); + const response = yield* client.token + .exchangeDpopAccessToken({ + headers: { dpop: proof }, + payload: { + grant_type: RelayDpopTokenExchangeGrantType, + subject_token: input.clerkToken, + subject_token_type: RelayJwtSubjectTokenType, + requested_token_type: RelayAccessTokenType, + resource: options.relayUrl, + scope: encodeOAuthScope(input.scopes), + client_id: options.clientId, + }, + }) + .pipe( + Effect.mapError((cause) => + relayClientError("Could not exchange relay DPoP access token.", cause), + ), + timeoutRelayRequest("Relay DPoP access token exchange timed out."), + ); + if (!oauthScopeSetEquals(response.scope, input.scopes)) { + return yield* relayClientError( + "Relay granted unexpected DPoP access token scopes.", + ); + } + const next: CachedRelayAccessToken = { + clerkToken: input.clerkToken, + thumbprint: input.thumbprint, + scopes: input.scopes, + accessToken: response.access_token, + expiresAtMillis: nowMillis + response.expires_in * 1_000, + }; + return [next, [...activeTokens, next]] as const; + }); + }); + }, + ); + + const authorize = (input: { + readonly clerkToken: string; + readonly scopes: ReadonlyArray; + readonly target: DpopProofTarget; + }) => + Effect.gen(function* () { + const thumbprint = yield* signer.thumbprint.pipe( + Effect.mapError((cause) => + relayClientError("Could not load relay DPoP proof key.", cause), + ), + ); + const token = yield* obtainAccessToken({ + clerkToken: input.clerkToken, + scopes: input.scopes, + thumbprint, + }); + const proof = yield* signer + .createProof({ + ...input.target, + accessToken: token.accessToken, + }) + .pipe( + Effect.mapError((cause) => + relayClientError("Could not create relay request DPoP proof.", cause), + ), + ); + return { accessToken: token.accessToken, proof, thumbprint }; + }); + + const authorizeMobileRegistration = (input: { + readonly clerkToken: string; + readonly target: DpopProofTarget; + }) => + authorize({ + ...input, + scopes: [RelayMobileRegistrationScope], + }); + + return ManagedRelayClient.of({ + relayUrl: options.relayUrl, + listEnvironments: (input) => + client.client.listEnvironments({ headers: bearerHeaders(input.clerkToken) }).pipe( + Effect.map((response) => response.environments), + Effect.mapError((cause) => + relayClientError("Could not list relay-managed environments.", cause), + ), + timeoutRelayRequest("Relay environment listing timed out."), + ), + createEnvironmentLinkChallenge: (input) => + client.client + .createEnvironmentLinkChallenge({ + headers: bearerHeaders(input.clerkToken), + payload: input.payload, + }) + .pipe( + Effect.mapError((cause) => + relayClientError("Could not create relay environment link challenge.", cause), + ), + timeoutRelayRequest("Relay environment link challenge timed out."), + ), + linkEnvironment: (input) => + client.client + .linkEnvironment({ + headers: bearerHeaders(input.clerkToken), + payload: input.payload, + }) + .pipe( + Effect.mapError((cause) => + relayClientError("Could not link relay environment.", cause), + ), + timeoutRelayRequest("Relay environment linking timed out."), + ), + unlinkEnvironment: (input) => + client.client + .unlinkEnvironment({ + headers: bearerHeaders(input.clerkToken), + params: { environmentId: input.environmentId }, + }) + .pipe( + Effect.mapError((cause) => + relayClientError("Could not unlink relay environment.", cause), + ), + timeoutRelayRequest("Relay environment unlinking timed out."), + ), + getEnvironmentStatus: (input) => + Effect.gen(function* () { + const authorization = yield* authorize({ + clerkToken: input.clerkToken, + scopes: input.scopes, + target: dpopProofTargets.getEnvironmentStatus(input.environmentId), + }); + return yield* client.dpopClient + .getEnvironmentStatus({ + headers: dpopHeaders(authorization), + params: { environmentId: input.environmentId }, + }) + .pipe( + Effect.mapError((cause) => + relayClientError("Could not get relay environment status.", cause), + ), + timeoutRelayRequest("Relay environment status request timed out."), + ); + }), + connectEnvironment: (input) => + Effect.gen(function* () { + const authorization = yield* authorize({ + clerkToken: input.clerkToken, + scopes: input.scopes, + target: dpopProofTargets.connectEnvironment(input.environmentId), + }); + const payload: RelayEnvironmentConnectRequest = { + ...(input.deviceId ? { deviceId: input.deviceId } : {}), + clientKeyThumbprint: authorization.thumbprint, + }; + return yield* client.dpopClient + .connectEnvironment({ + headers: dpopHeaders(authorization), + params: { environmentId: input.environmentId }, + payload, + }) + .pipe( + Effect.mapError((cause) => + relayClientError("Could not connect relay environment.", cause), + ), + timeoutRelayRequest("Relay environment connection timed out."), + ); + }), + registerDevice: (input) => + Effect.gen(function* () { + const authorization = yield* authorizeMobileRegistration({ + clerkToken: input.clerkToken, + target: dpopProofTargets.registerDevice(), + }); + return yield* client.mobile + .registerDevice({ + headers: dpopHeaders(authorization), + payload: input.payload, + }) + .pipe( + Effect.mapError((cause) => + relayClientError("Could not register relay mobile device.", cause), + ), + timeoutRelayRequest("Relay mobile device registration timed out."), + ); + }), + unregisterDevice: (input) => + Effect.gen(function* () { + const authorization = yield* authorizeMobileRegistration({ + clerkToken: input.clerkToken, + target: dpopProofTargets.unregisterDevice(input.deviceId), + }); + return yield* client.mobile + .unregisterDevice({ + headers: dpopHeaders(authorization), + params: { deviceId: input.deviceId }, + }) + .pipe( + Effect.mapError((cause) => + relayClientError("Could not unregister relay mobile device.", cause), + ), + timeoutRelayRequest("Relay mobile device unregistration timed out."), + ); + }), + registerLiveActivity: (input) => + Effect.gen(function* () { + const authorization = yield* authorizeMobileRegistration({ + clerkToken: input.clerkToken, + target: dpopProofTargets.registerLiveActivity(), + }); + return yield* client.mobile + .registerLiveActivity({ + headers: dpopHeaders(authorization), + payload: input.payload, + }) + .pipe( + Effect.mapError((cause) => + relayClientError("Could not register relay live activity.", cause), + ), + timeoutRelayRequest("Relay Live Activity registration timed out."), + ); + }), + resetTokenCache: SynchronizedRef.set(cachedTokens, []), + }); + }), + ); +} diff --git a/packages/client-runtime/src/remote.test.ts b/packages/client-runtime/src/remote.test.ts index 27c0ce9271..c20832bd37 100644 --- a/packages/client-runtime/src/remote.test.ts +++ b/packages/client-runtime/src/remote.test.ts @@ -8,8 +8,11 @@ import * as TestClock from "effect/testing/TestClock"; import { EnvironmentAuthInvalidError } from "@t3tools/contracts"; import { bootstrapRemoteBearerSession, + exchangeRemoteDpopAccessToken, + fetchRemoteDpopSessionState, fetchRemoteEnvironmentDescriptor, fetchRemoteSessionState, + issueRemoteDpopWebSocketTicket, issueRemoteWebSocketTicket, remoteHttpClientLayer, RemoteEnvironmentAuthInvalidJsonError, @@ -123,6 +126,55 @@ describe("remote", () => { }), ); + it.effect("exchanges managed credentials and admits websocket requests with DPoP", () => + Effect.gen(function* () { + const fetch = recordedFetch( + Response.json({ + access_token: "dpop-access-token", + issued_token_type: "urn:ietf:params:oauth:token-type:access_token", + token_type: "DPoP", + expires_in: 3600, + scope: "orchestration:read orchestration:operate terminal:operate review:write", + }), + Response.json({ + ticket: "ws-ticket", + expiresAt: "2026-05-01T12:05:00.000Z", + }), + ); + + const token = yield* exchangeRemoteDpopAccessToken({ + httpBaseUrl: "https://remote.example.com/", + credential: "one-time-credential", + dpopProof: "token-proof", + clientMetadata: { + label: "T3 Code Mobile", + deviceType: "mobile", + os: "iOS", + }, + }).pipe(provideRemoteHttp(fetch.fetchFn)); + yield* issueRemoteDpopWebSocketTicket({ + httpBaseUrl: "https://remote.example.com/", + accessToken: token.access_token, + dpopProof: "resource-proof", + }).pipe(provideRemoteHttp(fetch.fetchFn)); + + expectFetchCall(fetch.calls, 1, { + url: "https://remote.example.com/oauth/token", + method: "POST", + headers: { dpop: "token-proof", "content-type": "application/x-www-form-urlencoded" }, + body: "grant_type=urn%3Aietf%3Aparams%3Aoauth%3Agrant-type%3Atoken-exchange&subject_token=one-time-credential&subject_token_type=urn%3At3%3Aparams%3Aoauth%3Atoken-type%3Aenvironment-bootstrap&requested_token_type=urn%3Aietf%3Aparams%3Aoauth%3Atoken-type%3Aaccess_token&client_label=T3+Code+Mobile&client_device_type=mobile&client_os=iOS", + }); + expectFetchCall(fetch.calls, 2, { + url: "https://remote.example.com/api/auth/websocket-ticket", + method: "POST", + headers: { + authorization: "DPoP dpop-access-token", + dpop: "resource-proof", + }, + }); + }), + ); + it.effect("submits optional client display metadata during bearer token exchange", () => Effect.gen(function* () { const fetch = recordedFetch( @@ -186,7 +238,7 @@ describe("remote", () => { }), ); - it.effect("loads remote session state and websocket tokens over bearer auth", () => + it.effect("loads remote session state and websocket tickets over bearer auth", () => Effect.gen(function* () { const fetch = recordedFetch( Response.json( @@ -257,11 +309,11 @@ describe("remote", () => { ], }); - const token = yield* issueRemoteWebSocketTicket({ + const ticket = yield* issueRemoteWebSocketTicket({ httpBaseUrl: "https://remote.example.com/", bearerToken: "bearer-token", }).pipe(provideRemoteHttp(fetch.fetchFn)); - expect(token).toMatchObject({ + expect(ticket).toMatchObject({ ticket: "ws-ticket", }); @@ -286,6 +338,45 @@ describe("remote", () => { }), ); + it.effect("loads remote session state with a DPoP-bound access token", () => + Effect.gen(function* () { + const fetch = recordedFetch( + Response.json({ + authenticated: true, + auth: { + policy: "remote-reachable", + bootstrapMethods: ["one-time-token"], + sessionMethods: ["dpop-access-token"], + sessionCookieName: "t3_session", + }, + sessionMethod: "dpop-access-token", + scopes: [ + "orchestration:read", + "orchestration:operate", + "terminal:operate", + "review:write", + ], + expiresAt: "2026-05-01T12:00:00.000Z", + }), + ); + + yield* fetchRemoteDpopSessionState({ + httpBaseUrl: "https://remote.example.com/", + accessToken: "dpop-access-token", + dpopProof: "dpop-proof", + }).pipe(provideRemoteHttp(fetch.fetchFn)); + + expectFetchCall(fetch.calls, 1, { + url: "https://remote.example.com/api/auth/session", + method: "GET", + headers: { + authorization: "DPoP dpop-access-token", + dpop: "dpop-proof", + }, + }); + }), + ); + it.effect("fails hung fetch requests on the configured timeout", () => Effect.gen(function* () { const fetch = hangingFetch(); @@ -360,27 +451,25 @@ describe("remote", () => { }), ); - it.effect( - "mints a websocket url that targets the rpc route with a short-lived websocket ticket", - () => - Effect.gen(function* () { - const fetch = recordedFetch( - Response.json( - { - ticket: "ws-ticket", - expiresAt: "2026-05-01T12:05:00.000Z", - }, - { status: 200 }, - ), - ); + it.effect("mints a websocket url that targets the rpc route with a short-lived ticket", () => + Effect.gen(function* () { + const fetch = recordedFetch( + Response.json( + { + ticket: "ws-ticket", + expiresAt: "2026-05-01T12:05:00.000Z", + }, + { status: 200 }, + ), + ); - const url = yield* resolveRemoteWebSocketConnectionUrl({ - wsBaseUrl: "wss://remote.example.com/", - httpBaseUrl: "https://remote.example.com/", - bearerToken: "bearer-token", - }).pipe(provideRemoteHttp(fetch.fetchFn)); + const url = yield* resolveRemoteWebSocketConnectionUrl({ + wsBaseUrl: "wss://remote.example.com/", + httpBaseUrl: "https://remote.example.com/", + bearerToken: "bearer-token", + }).pipe(provideRemoteHttp(fetch.fetchFn)); - expect(url).toBe("wss://remote.example.com/ws?wsTicket=ws-ticket"); - }), + expect(url).toBe("wss://remote.example.com/ws?wsTicket=ws-ticket"); + }), ); }); diff --git a/packages/client-runtime/src/remote.ts b/packages/client-runtime/src/remote.ts index cc8ef361b7..896a218ade 100644 --- a/packages/client-runtime/src/remote.ts +++ b/packages/client-runtime/src/remote.ts @@ -7,7 +7,6 @@ import { EnvironmentHttpApi, EnvironmentHttpCommonError, } from "@t3tools/contracts"; -import { encodeOAuthScope } from "@t3tools/shared/oauthScope"; import type { EnvironmentAuthInvalidError, EnvironmentInternalError, @@ -15,6 +14,7 @@ import type { EnvironmentRequestInvalidError, EnvironmentScopeRequiredError, } from "@t3tools/contracts"; +import { encodeOAuthScope } from "@t3tools/shared/oauthScope"; import * as Data from "effect/Data"; import * as Duration from "effect/Duration"; import * as Effect from "effect/Effect"; @@ -27,7 +27,7 @@ import * as HttpApiClient from "effect/unstable/httpapi/HttpApiClient"; const DEFAULT_REMOTE_REQUEST_TIMEOUT_MS = 10_000; const isEnvironmentHttpCommonError = Schema.is(EnvironmentHttpCommonError); -const remoteEndpointUrl = (httpBaseUrl: string, pathname: string): string => { +export const remoteEndpointUrl = (httpBaseUrl: string, pathname: string): string => { const url = new URL(httpBaseUrl); url.pathname = pathname; url.search = ""; @@ -43,6 +43,14 @@ const remoteApiBaseUrl = (httpBaseUrl: string): string => { return url.toString(); }; +const clientMetadataTokenExchangeFields = ( + clientMetadata: AuthClientPresentationMetadata | undefined, +) => ({ + ...(clientMetadata?.label ? { client_label: clientMetadata.label } : {}), + ...(clientMetadata?.deviceType ? { client_device_type: clientMetadata.deviceType } : {}), + ...(clientMetadata?.os ? { client_os: clientMetadata.os } : {}), +}); + export class RemoteEnvironmentAuthFetchError extends Data.TaggedError( "RemoteEnvironmentAuthFetchError", )<{ @@ -170,6 +178,35 @@ export const makeEnvironmentHttpApiClient = (httpBaseUrl: string) => }); }); +export const exchangeRemoteDpopAccessToken = Effect.fn( + "clientRuntime.remote.exchangeRemoteDpopAccessToken", +)(function* (input: { + readonly httpBaseUrl: string; + readonly credential: string; + readonly scopes?: ReadonlyArray; + readonly clientMetadata?: AuthClientPresentationMetadata; + readonly dpopProof: string; + readonly timeoutMs?: number; +}) { + const client = yield* makeEnvironmentHttpApiClient(input.httpBaseUrl); + const response = yield* executeRemoteRequest( + remoteEndpointUrl(input.httpBaseUrl, "/oauth/token"), + input.timeoutMs ?? DEFAULT_REMOTE_REQUEST_TIMEOUT_MS, + client.auth.token({ + headers: { dpop: input.dpopProof }, + payload: { + grant_type: AuthTokenExchangeGrantType, + subject_token: input.credential, + subject_token_type: AuthEnvironmentBootstrapTokenType, + requested_token_type: AuthAccessTokenType, + ...(input.scopes ? { scope: encodeOAuthScope(input.scopes) } : {}), + ...clientMetadataTokenExchangeFields(input.clientMetadata), + }, + }), + ); + return response; +}); + export const bootstrapRemoteBearerSession = Effect.fn( "clientRuntime.remote.bootstrapRemoteBearerSession", )(function* (input: { @@ -184,17 +221,14 @@ export const bootstrapRemoteBearerSession = Effect.fn( remoteEndpointUrl(input.httpBaseUrl, "/oauth/token"), input.timeoutMs ?? DEFAULT_REMOTE_REQUEST_TIMEOUT_MS, client.auth.token({ + headers: {}, payload: { grant_type: AuthTokenExchangeGrantType, subject_token: input.credential, subject_token_type: AuthEnvironmentBootstrapTokenType, requested_token_type: AuthAccessTokenType, ...(input.scopes ? { scope: encodeOAuthScope(input.scopes) } : {}), - ...(input.clientMetadata?.label ? { client_label: input.clientMetadata.label } : {}), - ...(input.clientMetadata?.deviceType - ? { client_device_type: input.clientMetadata.deviceType } - : {}), - ...(input.clientMetadata?.os ? { client_os: input.clientMetadata.os } : {}), + ...clientMetadataTokenExchangeFields(input.clientMetadata), }, }), ); @@ -219,6 +253,27 @@ export const fetchRemoteSessionState = Effect.fn("clientRuntime.remote.fetchRemo }, ); +export const fetchRemoteDpopSessionState = Effect.fn( + "clientRuntime.remote.fetchRemoteDpopSessionState", +)(function* (input: { + readonly httpBaseUrl: string; + readonly accessToken: string; + readonly dpopProof: string; + readonly timeoutMs?: number; +}) { + const client = yield* makeEnvironmentHttpApiClient(input.httpBaseUrl); + return yield* executeRemoteRequest( + remoteEndpointUrl(input.httpBaseUrl, "/api/auth/session"), + input.timeoutMs ?? DEFAULT_REMOTE_REQUEST_TIMEOUT_MS, + client.auth.session({ + headers: { + authorization: `DPoP ${input.accessToken}`, + dpop: input.dpopProof, + }, + }), + ); +}); + export const fetchRemoteEnvironmentDescriptor = Effect.fn( "clientRuntime.remote.fetchRemoteEnvironmentDescriptor", )(function* (input: { readonly httpBaseUrl: string; readonly timeoutMs?: number }) { @@ -249,6 +304,27 @@ export const issueRemoteWebSocketTicket = Effect.fn( ); }); +export const issueRemoteDpopWebSocketTicket = Effect.fn( + "clientRuntime.remote.issueRemoteDpopWebSocketTicket", +)(function* (input: { + readonly httpBaseUrl: string; + readonly accessToken: string; + readonly dpopProof: string; + readonly timeoutMs?: number; +}) { + const client = yield* makeEnvironmentHttpApiClient(input.httpBaseUrl); + return yield* executeRemoteRequest( + remoteEndpointUrl(input.httpBaseUrl, "/api/auth/websocket-ticket"), + input.timeoutMs ?? DEFAULT_REMOTE_REQUEST_TIMEOUT_MS, + client.auth.webSocketTicket({ + headers: { + authorization: `DPoP ${input.accessToken}`, + dpop: input.dpopProof, + }, + }), + ); +}); + export const resolveRemoteWebSocketConnectionUrl = Effect.fn( "clientRuntime.remote.resolveRemoteWebSocketConnectionUrl", )(function* (input: { @@ -270,3 +346,26 @@ export const resolveRemoteWebSocketConnectionUrl = Effect.fn( url.searchParams.set("wsTicket", issued.ticket); return url.toString(); }); + +export const resolveRemoteDpopWebSocketConnectionUrl = Effect.fn( + "clientRuntime.remote.resolveRemoteDpopWebSocketConnectionUrl", +)(function* (input: { + readonly wsBaseUrl: string; + readonly httpBaseUrl: string; + readonly accessToken: string; + readonly dpopProof: string; + readonly timeoutMs?: number; +}) { + const issued = yield* issueRemoteDpopWebSocketTicket({ + httpBaseUrl: input.httpBaseUrl, + accessToken: input.accessToken, + dpopProof: input.dpopProof, + ...(input.timeoutMs ? { timeoutMs: input.timeoutMs } : {}), + }); + const url = new URL(input.wsBaseUrl); + if (url.pathname === "" || url.pathname === "/") { + url.pathname = "/ws"; + } + url.searchParams.set("wsTicket", issued.ticket); + return url.toString(); +}); diff --git a/packages/contracts/package.json b/packages/contracts/package.json index 7b945f91b3..5f2cb0909d 100644 --- a/packages/contracts/package.json +++ b/packages/contracts/package.json @@ -14,6 +14,10 @@ "./settings": { "types": "./src/settings.ts", "import": "./src/settings.ts" + }, + "./relay": { + "types": "./src/relay.ts", + "import": "./src/relay.ts" } }, "scripts": { diff --git a/packages/contracts/src/auth.ts b/packages/contracts/src/auth.ts index 2b062fc2d6..70b2899757 100644 --- a/packages/contracts/src/auth.ts +++ b/packages/contracts/src/auth.ts @@ -63,10 +63,13 @@ export type ServerAuthBootstrapMethod = typeof ServerAuthBootstrapMethod.Type; * app after bootstrap/pairing * - `bearer-access-token`: scoped token suitable for non-cookie or * non-browser clients + * - `dpop-access-token`: scoped proof-of-possession token used by managed + * relay connections */ export const ServerAuthSessionMethod = Schema.Literals([ "browser-session-cookie", "bearer-access-token", + "dpop-access-token", ]); export type ServerAuthSessionMethod = typeof ServerAuthSessionMethod.Type; @@ -184,7 +187,7 @@ export type AuthTokenExchangeRequest = typeof AuthTokenExchangeRequest.Type; export const AuthAccessTokenResult = Schema.Struct({ access_token: TrimmedNonEmptyString, issued_token_type: Schema.Literal(AuthAccessTokenType), - token_type: Schema.Literal("Bearer"), + token_type: Schema.Literals(["Bearer", "DPoP"]), expires_in: Schema.Number, scope: TrimmedNonEmptyString, }); diff --git a/packages/contracts/src/environmentHttp.ts b/packages/contracts/src/environmentHttp.ts index 93189f62a9..064d38499b 100644 --- a/packages/contracts/src/environmentHttp.ts +++ b/packages/contracts/src/environmentHttp.ts @@ -31,9 +31,23 @@ import { DispatchResult, OrchestrationReadModel, } from "./orchestration.ts"; +import { + RelayCloudEnvironmentHealthRequest, + RelayCloudMintCredentialRequest, + RelayEnvironmentConfigRequest, + RelayEnvironmentHealthResponse, + RelayEnvironmentLinkProof, + RelayEnvironmentMintResponse, + RelayLinkProofRequest, +} from "./relay.ts"; const OptionalBearerHeaders = Schema.Struct({ authorization: Schema.optionalKey(Schema.String), + dpop: Schema.optionalKey(Schema.String), +}); + +const OptionalDpopProofHeaders = Schema.Struct({ + dpop: Schema.optionalKey(Schema.String), }); export const EnvironmentRequestInvalidReason = Schema.Literals([ @@ -154,6 +168,81 @@ const EnvironmentAuthenticationErrors = [ EnvironmentAuthInvalidError, EnvironmentInternalError, ] as const; + +export class EnvironmentHttpBadRequestError extends Schema.TaggedErrorClass()( + "EnvironmentHttpBadRequestError", + { + message: Schema.String, + }, + { httpApiStatus: 400 }, +) { + [HttpServerRespondable.symbol]() { + return HttpServerResponse.schemaJson(EnvironmentHttpBadRequestError)(this, { status: 400 }); + } +} + +export class EnvironmentHttpUnauthorizedError extends Schema.TaggedErrorClass()( + "EnvironmentHttpUnauthorizedError", + { + message: Schema.String, + }, + { httpApiStatus: 401 }, +) { + [HttpServerRespondable.symbol]() { + return HttpServerResponse.schemaJson(EnvironmentHttpUnauthorizedError)(this, { status: 401 }); + } +} + +export class EnvironmentHttpForbiddenError extends Schema.TaggedErrorClass()( + "EnvironmentHttpForbiddenError", + { + message: Schema.String, + }, + { httpApiStatus: 403 }, +) { + [HttpServerRespondable.symbol]() { + return HttpServerResponse.schemaJson(EnvironmentHttpForbiddenError)(this, { status: 403 }); + } +} + +export class EnvironmentHttpInternalServerError extends Schema.TaggedErrorClass()( + "EnvironmentHttpInternalServerError", + { + message: Schema.String, + }, + { httpApiStatus: 500 }, +) { + [HttpServerRespondable.symbol]() { + return HttpServerResponse.schemaJson(EnvironmentHttpInternalServerError)(this, { status: 500 }); + } +} + +export class EnvironmentHttpConflictError extends Schema.TaggedErrorClass()( + "EnvironmentHttpConflictError", + { + message: Schema.String, + }, + { httpApiStatus: 409 }, +) { + [HttpServerRespondable.symbol]() { + return HttpServerResponse.schemaJson(EnvironmentHttpConflictError)(this, { status: 409 }); + } +} + +export class EnvironmentCloudEndpointUnavailableError extends Schema.TaggedErrorClass()( + "EnvironmentCloudEndpointUnavailableError", + { + message: Schema.String, + endpointRuntimeStatus: Schema.Unknown, + }, + { httpApiStatus: 503 }, +) { + [HttpServerRespondable.symbol]() { + return HttpServerResponse.schemaJson(EnvironmentCloudEndpointUnavailableError)(this, { + status: 503, + }); + } +} const EnvironmentSessionCreationErrors = [ EnvironmentAuthInvalidError, EnvironmentInternalError, @@ -191,6 +280,7 @@ export interface EnvironmentSessionPrincipalShape { readonly subject: string; readonly method: ServerAuthSessionMethod; readonly scopes: ReadonlySet; + readonly proofKeyThumbprint?: string; readonly expiresAt?: DateTime.DateTime; } @@ -206,6 +296,29 @@ export class EnvironmentAuthenticatedAuth extends HttpApiMiddleware.Service< error: EnvironmentAuthenticationErrors, }) {} +const EnvironmentHttpCloudErrors = [ + EnvironmentHttpBadRequestError, + EnvironmentHttpUnauthorizedError, + EnvironmentHttpForbiddenError, + EnvironmentHttpConflictError, + EnvironmentHttpInternalServerError, + EnvironmentScopeRequiredError, +] as const; + +export const EnvironmentCloudRelayConfigResult = Schema.Struct({ + ok: Schema.Boolean, + endpointRuntimeStatus: Schema.Unknown, +}); +export type EnvironmentCloudRelayConfigResult = typeof EnvironmentCloudRelayConfigResult.Type; + +export const EnvironmentCloudLinkStateResult = Schema.Struct({ + linked: Schema.Boolean, + cloudUserId: Schema.NullOr(Schema.String), + relayUrl: Schema.NullOr(Schema.String), + relayIssuer: Schema.NullOr(Schema.String), +}); +export type EnvironmentCloudLinkStateResult = typeof EnvironmentCloudLinkStateResult.Type; + export const AuthPairingLinkRevokeResult = Schema.Struct({ revoked: Schema.Boolean, }); @@ -244,6 +357,7 @@ export class EnvironmentAuthHttpApi extends HttpApiGroup.make("auth") ) .add( HttpApiEndpoint.post("token", "/oauth/token", { + headers: OptionalDpopProofHeaders, payload: AuthTokenExchangeRequest, success: AuthAccessTokenResult, error: EnvironmentTokenExchangeErrors, @@ -319,7 +433,61 @@ export class EnvironmentOrchestrationHttpApi extends HttpApiGroup.make("orchestr }).middleware(EnvironmentAuthenticatedAuth), ) {} +export class EnvironmentCloudHttpApi extends HttpApiGroup.make("cloud") + .add( + HttpApiEndpoint.post("linkProof", "/api/cloud/link-proof", { + headers: OptionalBearerHeaders, + payload: RelayLinkProofRequest, + success: RelayEnvironmentLinkProof, + error: EnvironmentHttpCloudErrors, + }).middleware(EnvironmentAuthenticatedAuth), + ) + .add( + HttpApiEndpoint.post("relayConfig", "/api/cloud/relay-config", { + headers: OptionalBearerHeaders, + payload: RelayEnvironmentConfigRequest, + success: EnvironmentCloudRelayConfigResult, + error: [...EnvironmentHttpCloudErrors, EnvironmentCloudEndpointUnavailableError], + }).middleware(EnvironmentAuthenticatedAuth), + ) + .add( + HttpApiEndpoint.get("linkState", "/api/cloud/link-state", { + headers: OptionalBearerHeaders, + success: EnvironmentCloudLinkStateResult, + error: EnvironmentHttpCloudErrors, + }).middleware(EnvironmentAuthenticatedAuth), + ) + .add( + HttpApiEndpoint.post("unlink", "/api/cloud/unlink", { + headers: OptionalBearerHeaders, + success: EnvironmentCloudRelayConfigResult, + error: EnvironmentHttpCloudErrors, + }).middleware(EnvironmentAuthenticatedAuth), + ) + .add( + HttpApiEndpoint.post("health", "/api/t3-cloud/health", { + payload: RelayCloudEnvironmentHealthRequest, + success: RelayEnvironmentHealthResponse, + error: EnvironmentHttpCloudErrors, + }), + ) + .add( + HttpApiEndpoint.post("mintCredential", "/api/cloud/mint-credential", { + payload: RelayCloudMintCredentialRequest, + success: RelayEnvironmentMintResponse, + error: EnvironmentHttpCloudErrors, + }), + ) + .add( + HttpApiEndpoint.post("t3MintCredential", "/api/t3-cloud/mint-credential", { + payload: RelayCloudMintCredentialRequest, + success: RelayEnvironmentMintResponse, + error: EnvironmentHttpCloudErrors, + }), + ) {} + export class EnvironmentHttpApi extends HttpApi.make("environment") .add(EnvironmentMetadataHttpApi) .add(EnvironmentAuthHttpApi) - .add(EnvironmentOrchestrationHttpApi) {} + .add(EnvironmentOrchestrationHttpApi) + .add(EnvironmentCloudHttpApi) {} diff --git a/packages/contracts/src/ipc.ts b/packages/contracts/src/ipc.ts index 684974fcac..56f929f7de 100644 --- a/packages/contracts/src/ipc.ts +++ b/packages/contracts/src/ipc.ts @@ -338,6 +338,11 @@ export const PersistedSavedEnvironmentRecordSchema = Schema.Struct({ createdAt: Schema.String, lastConnectedAt: Schema.NullOr(Schema.String), desktopSsh: Schema.optionalKey(DesktopSshEnvironmentTargetSchema), + relayManaged: Schema.optionalKey( + Schema.Struct({ + relayUrl: Schema.String, + }), + ), }); export type PersistedSavedEnvironmentRecord = typeof PersistedSavedEnvironmentRecordSchema.Type; @@ -372,6 +377,23 @@ export const PickFolderOptionsSchema = Schema.Struct({ initialPath: Schema.optionalKey(Schema.NullOr(Schema.String)), }); +export const DesktopCloudAuthFetchInputSchema = Schema.Struct({ + url: Schema.String, + method: Schema.optionalKey(Schema.String), + headers: Schema.Record(Schema.String, Schema.String), + body: Schema.optionalKey(Schema.String), +}); +export type DesktopCloudAuthFetchInput = typeof DesktopCloudAuthFetchInputSchema.Type; + +export const DesktopCloudAuthFetchResultSchema = Schema.Struct({ + ok: Schema.Boolean, + status: Schema.Number, + statusText: Schema.String, + headers: Schema.Record(Schema.String, Schema.String), + body: Schema.String, +}); +export type DesktopCloudAuthFetchResult = typeof DesktopCloudAuthFetchResultSchema.Type; + export interface DesktopBridge { getAppBranding: () => DesktopAppBranding | null; getLocalEnvironmentBootstrap: () => DesktopEnvironmentBootstrap | null; @@ -417,6 +439,12 @@ export interface DesktopBridge { position?: { x: number; y: number }, ) => Promise; openExternal: (url: string) => Promise; + createCloudAuthRequest: () => Promise; + getCloudAuthToken: () => Promise; + setCloudAuthToken: (token: string) => Promise; + clearCloudAuthToken: () => Promise; + fetchCloudAuth: (input: DesktopCloudAuthFetchInput) => Promise; + onCloudAuthCallback: (listener: (rawUrl: string) => void) => () => void; onMenuAction: (listener: (action: string) => void) => () => void; getUpdateState: () => Promise; setUpdateChannel: (channel: DesktopUpdateChannel) => Promise; diff --git a/packages/contracts/src/relay.test.ts b/packages/contracts/src/relay.test.ts new file mode 100644 index 0000000000..42ce2e196a --- /dev/null +++ b/packages/contracts/src/relay.test.ts @@ -0,0 +1,16 @@ +import { describe, expect, it } from "vitest"; +import * as OpenApi from "effect/unstable/httpapi/OpenApi"; + +import { RelayApi } from "./relay.ts"; + +describe("RelayApi security", () => { + it("describes DPoP access tokens using the HTTP DPoP authorization scheme", () => { + const document = OpenApi.fromApi(RelayApi); + + expect(document.components.securitySchemes?.relayDpop).toEqual({ + type: "http", + scheme: "DPoP", + description: "DPoP-bound access token. Requests must also include the DPoP proof JWT header.", + }); + }); +}); diff --git a/packages/contracts/src/relay.ts b/packages/contracts/src/relay.ts new file mode 100644 index 0000000000..f0397c1596 --- /dev/null +++ b/packages/contracts/src/relay.ts @@ -0,0 +1,868 @@ +import * as Schema from "effect/Schema"; +import * as Context from "effect/Context"; +import * as HttpApi from "effect/unstable/httpapi/HttpApi"; +import * as HttpApiEndpoint from "effect/unstable/httpapi/HttpApiEndpoint"; +import * as HttpApiGroup from "effect/unstable/httpapi/HttpApiGroup"; +import * as HttpApiMiddleware from "effect/unstable/httpapi/HttpApiMiddleware"; +import * as HttpApiSchema from "effect/unstable/httpapi/HttpApiSchema"; +import * as HttpApiSecurity from "effect/unstable/httpapi/HttpApiSecurity"; +import * as OpenApi from "effect/unstable/httpapi/OpenApi"; + +import { EnvironmentId, ThreadId, TrimmedNonEmptyString } from "./baseSchemas.ts"; +import { ExecutionEnvironmentDescriptor } from "./environment.ts"; + +export const RelayAgentAwarenessPlatform = Schema.Literal("ios"); +export type RelayAgentAwarenessPlatform = typeof RelayAgentAwarenessPlatform.Type; + +export const RelayAgentAwarenessPhase = Schema.Literals([ + "starting", + "running", + "waiting_for_approval", + "waiting_for_input", + "completed", + "failed", + "stale", +]); +export type RelayAgentAwarenessPhase = typeof RelayAgentAwarenessPhase.Type; + +export const RelayAgentAwarenessPreferences = Schema.Struct({ + liveActivitiesEnabled: Schema.Boolean, + notificationsEnabled: Schema.Boolean, + notifyOnApproval: Schema.Boolean, + notifyOnInput: Schema.Boolean, + notifyOnCompletion: Schema.Boolean, + notifyOnFailure: Schema.Boolean, +}); +export type RelayAgentAwarenessPreferences = typeof RelayAgentAwarenessPreferences.Type; + +export const RelayDeviceRegistrationRequest = Schema.Struct({ + deviceId: TrimmedNonEmptyString, + platform: RelayAgentAwarenessPlatform, + iosMajorVersion: Schema.Int.check(Schema.isGreaterThanOrEqualTo(18)), + appVersion: Schema.optional(TrimmedNonEmptyString), + pushToken: Schema.optional(TrimmedNonEmptyString), + pushToStartToken: Schema.optional(TrimmedNonEmptyString), + preferences: RelayAgentAwarenessPreferences, +}); +export type RelayDeviceRegistrationRequest = typeof RelayDeviceRegistrationRequest.Type; + +export const RelayLiveActivityRegistrationRequest = Schema.Struct({ + deviceId: TrimmedNonEmptyString, + activityPushToken: TrimmedNonEmptyString, +}); +export type RelayLiveActivityRegistrationRequest = typeof RelayLiveActivityRegistrationRequest.Type; + +export const RelayDeviceUnregistrationParams = Schema.Struct({ + deviceId: TrimmedNonEmptyString, +}); +export type RelayDeviceUnregistrationParams = typeof RelayDeviceUnregistrationParams.Type; + +export const RelayAgentActivityState = Schema.Struct({ + environmentId: EnvironmentId, + threadId: ThreadId, + projectTitle: TrimmedNonEmptyString, + threadTitle: TrimmedNonEmptyString, + phase: RelayAgentAwarenessPhase, + headline: TrimmedNonEmptyString, + detail: Schema.optional(TrimmedNonEmptyString), + modelTitle: TrimmedNonEmptyString, + updatedAt: TrimmedNonEmptyString, + deepLink: TrimmedNonEmptyString, +}); +export type RelayAgentActivityState = typeof RelayAgentActivityState.Type; + +export const RelayAgentActivityAggregateRow = Schema.Struct({ + environmentId: EnvironmentId, + threadId: ThreadId, + projectTitle: TrimmedNonEmptyString, + threadTitle: TrimmedNonEmptyString, + modelTitle: TrimmedNonEmptyString, + phase: RelayAgentAwarenessPhase, + status: TrimmedNonEmptyString, + updatedAt: TrimmedNonEmptyString, + deepLink: TrimmedNonEmptyString, +}); +export type RelayAgentActivityAggregateRow = typeof RelayAgentActivityAggregateRow.Type; + +export const RelayAgentActivityAggregateState = Schema.Struct({ + title: TrimmedNonEmptyString, + subtitle: TrimmedNonEmptyString, + activeCount: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)), + updatedAt: TrimmedNonEmptyString, + activities: Schema.Array(RelayAgentActivityAggregateRow), +}); +export type RelayAgentActivityAggregateState = typeof RelayAgentActivityAggregateState.Type; + +export const RelayManagedEndpointProviderKind = Schema.Literals([ + "manual", + "cloudflare_tunnel", + "t3_relay", +]); +export type RelayManagedEndpointProviderKind = typeof RelayManagedEndpointProviderKind.Type; + +export const RelayManagedEndpoint = Schema.Struct({ + httpBaseUrl: TrimmedNonEmptyString, + wsBaseUrl: TrimmedNonEmptyString, + providerKind: RelayManagedEndpointProviderKind, +}); +export type RelayManagedEndpoint = typeof RelayManagedEndpoint.Type; + +export const RelayManagedEndpointOrigin = Schema.Struct({ + localHttpHost: TrimmedNonEmptyString, + localHttpPort: Schema.Int.check( + Schema.isGreaterThanOrEqualTo(1), + Schema.isLessThanOrEqualTo(65_535), + ), +}); +export type RelayManagedEndpointOrigin = typeof RelayManagedEndpointOrigin.Type; + +export const RelayManagedEndpointRuntimeConfig = Schema.Struct({ + providerKind: RelayManagedEndpointProviderKind, + connectorToken: TrimmedNonEmptyString, + tunnelId: Schema.optional(TrimmedNonEmptyString), + tunnelName: Schema.optional(TrimmedNonEmptyString), +}); +export type RelayManagedEndpointRuntimeConfig = typeof RelayManagedEndpointRuntimeConfig.Type; + +export const RelayLinkProofRequest = Schema.Struct({ + challenge: Schema.String, + relayIssuer: Schema.String, + endpoint: RelayManagedEndpoint, + origin: RelayManagedEndpointOrigin, +}); +export type RelayLinkProofRequest = typeof RelayLinkProofRequest.Type; + +export const RelayEnvironmentConfigRequest = Schema.Struct({ + relayUrl: Schema.String, + relayIssuer: Schema.optional(Schema.String), + cloudUserId: Schema.String, + environmentCredential: Schema.String, + cloudMintPublicKey: Schema.String, + endpointRuntime: Schema.NullOr(RelayManagedEndpointRuntimeConfig), +}); +export type RelayEnvironmentConfigRequest = typeof RelayEnvironmentConfigRequest.Type; + +const RelaySignedJwtRegisteredClaims = { + iss: TrimmedNonEmptyString, + aud: TrimmedNonEmptyString, + sub: TrimmedNonEmptyString, + jti: TrimmedNonEmptyString, + iat: Schema.Int, + exp: Schema.Int, +} as const; + +export const RelayAgentActivityPublishProofPayload = Schema.Struct({ + ...RelaySignedJwtRegisteredClaims, + environmentId: EnvironmentId, + threadId: ThreadId, + state: Schema.NullOr(RelayAgentActivityState), +}); +export type RelayAgentActivityPublishProofPayload = + typeof RelayAgentActivityPublishProofPayload.Type; +export type RelayAgentActivityPublishProof = string; + +export const RelayAgentActivityPublishRequest = Schema.Struct({ + state: Schema.NullOr(RelayAgentActivityState), + proof: TrimmedNonEmptyString, +}); +export type RelayAgentActivityPublishRequest = typeof RelayAgentActivityPublishRequest.Type; + +export const RelayEnvironmentLinkScope = Schema.Literals([ + "agent_activity_notifications", + "managed_tunnels", +]); +export type RelayEnvironmentLinkScope = typeof RelayEnvironmentLinkScope.Type; + +export const RelayEnvironmentLinkProofPayload = Schema.Struct({ + ...RelaySignedJwtRegisteredClaims, + challenge: TrimmedNonEmptyString, + descriptor: ExecutionEnvironmentDescriptor, + environmentId: EnvironmentId, + environmentPublicKey: TrimmedNonEmptyString, + endpoint: RelayManagedEndpoint, + origin: RelayManagedEndpointOrigin, + scopes: Schema.Array(RelayEnvironmentLinkScope), +}); +export type RelayEnvironmentLinkProofPayload = typeof RelayEnvironmentLinkProofPayload.Type; + +export const RelayEnvironmentLinkProof = TrimmedNonEmptyString; +export type RelayEnvironmentLinkProof = typeof RelayEnvironmentLinkProof.Type; + +export const RelayEnvironmentLinkChallengeRequest = Schema.Struct({ + notificationsEnabled: Schema.Boolean, + liveActivitiesEnabled: Schema.Boolean, + managedTunnelsEnabled: Schema.Boolean, +}); +export type RelayEnvironmentLinkChallengeRequest = typeof RelayEnvironmentLinkChallengeRequest.Type; + +export const RelayEnvironmentLinkChallengeResponse = Schema.Struct({ + challenge: TrimmedNonEmptyString, + expiresAt: TrimmedNonEmptyString, +}); +export type RelayEnvironmentLinkChallengeResponse = + typeof RelayEnvironmentLinkChallengeResponse.Type; + +export const RelayEnvironmentLinkRequest = Schema.Struct({ + deviceId: Schema.optional(TrimmedNonEmptyString), + proof: RelayEnvironmentLinkProof, + notificationsEnabled: Schema.Boolean, + liveActivitiesEnabled: Schema.Boolean, + managedTunnelsEnabled: Schema.Boolean, +}); +export type RelayEnvironmentLinkRequest = typeof RelayEnvironmentLinkRequest.Type; + +export const RelayEnvironmentLinkResponse = Schema.Struct({ + ok: Schema.Boolean, + cloudUserId: TrimmedNonEmptyString, + environmentId: EnvironmentId, + endpoint: RelayManagedEndpoint, + endpointRuntime: Schema.NullOr(RelayManagedEndpointRuntimeConfig), + relayIssuer: TrimmedNonEmptyString, + environmentCredential: TrimmedNonEmptyString, + cloudMintPublicKey: TrimmedNonEmptyString, +}); +export type RelayEnvironmentLinkResponse = typeof RelayEnvironmentLinkResponse.Type; + +export const RelayEnvironmentLinkProofInvalidReason = Schema.Literals([ + "invalid_signature_or_scope", + "descriptor_mismatch", + "replayed_nonce", + "challenge_invalid", + "origin_not_allowed", + "endpoint_not_secure", +]); +export type RelayEnvironmentLinkProofInvalidReason = + typeof RelayEnvironmentLinkProofInvalidReason.Type; + +export const RelayEnvironmentLinkFailedReason = Schema.Literals([ + "link_persistence_failed", + "credential_persistence_failed", + "replay_persistence_failed", + "internal_error", +]); +export type RelayEnvironmentLinkFailedReason = typeof RelayEnvironmentLinkFailedReason.Type; + +export const RelayEnvironmentLinkUnavailableReason = Schema.Literals([ + "managed_endpoint_not_configured", + "managed_endpoint_provisioning_failed", +]); +export type RelayEnvironmentLinkUnavailableReason = + typeof RelayEnvironmentLinkUnavailableReason.Type; + +export const RelayEnvironmentEndpointUnavailableReason = Schema.Literals([ + "endpoint_request_failed", + "endpoint_response_invalid", +]); +export type RelayEnvironmentEndpointUnavailableReason = + typeof RelayEnvironmentEndpointUnavailableReason.Type; + +export const RelayAgentActivityPublishProofInvalidReason = Schema.Literals([ + "invalid_signature_or_payload", + "replayed_nonce", +]); +export type RelayAgentActivityPublishProofInvalidReason = + typeof RelayAgentActivityPublishProofInvalidReason.Type; + +export const RelayAuthInvalidReason = Schema.Literals([ + "missing_bearer", + "invalid_bearer", + "invalid_dpop", + "not_authorized", +]); +export type RelayAuthInvalidReason = typeof RelayAuthInvalidReason.Type; + +export const RelayInternalErrorReason = Schema.Literals([ + "database_unavailable", + "persistence_failed", + "upstream_unavailable", + "internal_error", +]); +export type RelayInternalErrorReason = typeof RelayInternalErrorReason.Type; + +export class RelayAuthInvalidError extends Schema.TaggedErrorClass()( + "RelayAuthInvalidError", + { + code: Schema.Literal("auth_invalid"), + reason: RelayAuthInvalidReason, + traceId: TrimmedNonEmptyString, + }, + { httpApiStatus: 401 }, +) {} + +export class RelayEnvironmentLinkProofExpiredError extends Schema.TaggedErrorClass()( + "RelayEnvironmentLinkProofExpiredError", + { + code: Schema.Literal("environment_link_proof_expired"), + traceId: TrimmedNonEmptyString, + }, + { httpApiStatus: 401 }, +) {} + +export class RelayEnvironmentLinkProofInvalidError extends Schema.TaggedErrorClass()( + "RelayEnvironmentLinkProofInvalidError", + { + code: Schema.Literal("environment_link_proof_invalid"), + reason: RelayEnvironmentLinkProofInvalidReason, + traceId: TrimmedNonEmptyString, + }, + { httpApiStatus: 400 }, +) {} + +export class RelayEnvironmentConnectNotAuthorizedError extends Schema.TaggedErrorClass()( + "RelayEnvironmentConnectNotAuthorizedError", + { + code: Schema.Literal("environment_connect_not_authorized"), + traceId: TrimmedNonEmptyString, + }, + { httpApiStatus: 403 }, +) {} + +export class RelayEnvironmentEndpointUnavailableError extends Schema.TaggedErrorClass()( + "RelayEnvironmentEndpointUnavailableError", + { + code: Schema.Literal("environment_endpoint_unavailable"), + reason: RelayEnvironmentEndpointUnavailableReason, + traceId: TrimmedNonEmptyString, + }, + { httpApiStatus: 502 }, +) {} + +export class RelayEnvironmentEndpointTimedOutError extends Schema.TaggedErrorClass()( + "RelayEnvironmentEndpointTimedOutError", + { + code: Schema.Literal("environment_endpoint_timed_out"), + traceId: TrimmedNonEmptyString, + }, + { httpApiStatus: 504 }, +) {} + +export class RelayEnvironmentLinkFailedError extends Schema.TaggedErrorClass()( + "RelayEnvironmentLinkFailedError", + { + code: Schema.Literal("environment_link_failed"), + reason: RelayEnvironmentLinkFailedReason, + traceId: TrimmedNonEmptyString, + }, + { httpApiStatus: 500 }, +) {} + +export class RelayEnvironmentLinkUnavailableError extends Schema.TaggedErrorClass()( + "RelayEnvironmentLinkUnavailableError", + { + code: Schema.Literal("environment_link_unavailable"), + reason: RelayEnvironmentLinkUnavailableReason, + traceId: TrimmedNonEmptyString, + }, + { httpApiStatus: 503 }, +) {} + +export class RelayAgentActivityPublishProofExpiredError extends Schema.TaggedErrorClass()( + "RelayAgentActivityPublishProofExpiredError", + { + code: Schema.Literal("agent_activity_publish_proof_expired"), + traceId: TrimmedNonEmptyString, + }, + { httpApiStatus: 401 }, +) {} + +export class RelayAgentActivityPublishProofInvalidError extends Schema.TaggedErrorClass()( + "RelayAgentActivityPublishProofInvalidError", + { + code: Schema.Literal("agent_activity_publish_proof_invalid"), + reason: RelayAgentActivityPublishProofInvalidReason, + traceId: TrimmedNonEmptyString, + }, + { httpApiStatus: 401 }, +) {} + +export class RelayInternalError extends Schema.TaggedErrorClass()( + "RelayInternalError", + { + code: Schema.Literal("internal_error"), + reason: RelayInternalErrorReason, + traceId: TrimmedNonEmptyString, + }, + { httpApiStatus: 500 }, +) {} + +export const RelayProtectedError = Schema.Union([ + RelayAuthInvalidError, + RelayEnvironmentLinkProofExpiredError, + RelayEnvironmentLinkProofInvalidError, + RelayEnvironmentConnectNotAuthorizedError, + RelayEnvironmentEndpointUnavailableError, + RelayEnvironmentEndpointTimedOutError, + RelayEnvironmentLinkFailedError, + RelayEnvironmentLinkUnavailableError, + RelayAgentActivityPublishProofExpiredError, + RelayAgentActivityPublishProofInvalidError, + RelayInternalError, +]); +export type RelayProtectedError = typeof RelayProtectedError.Type; + +const RelayAuthAndInternalErrors = [RelayAuthInvalidError, RelayInternalError] as const; + +const RelayEnvironmentLinkErrors = [ + RelayAuthInvalidError, + RelayEnvironmentLinkProofExpiredError, + RelayEnvironmentLinkProofInvalidError, + RelayEnvironmentLinkUnavailableError, + RelayEnvironmentLinkFailedError, + RelayInternalError, +] as const; + +const RelayEnvironmentConnectErrors = [ + RelayAuthInvalidError, + RelayEnvironmentConnectNotAuthorizedError, + RelayEnvironmentEndpointUnavailableError, + RelayEnvironmentEndpointTimedOutError, + RelayInternalError, +] as const; + +const RelayAgentActivityPublishErrors = [ + RelayAuthInvalidError, + RelayAgentActivityPublishProofExpiredError, + RelayAgentActivityPublishProofInvalidError, + RelayInternalError, +] as const; + +export interface RelayClientPrincipalShape { + readonly userId: string; + readonly token: string; + readonly proofKeyThumbprint?: string; + readonly dpopScopes?: ReadonlyArray; +} + +export class RelayClientPrincipal extends Context.Service< + RelayClientPrincipal, + RelayClientPrincipalShape +>()("@t3tools/contracts/relay/RelayClientPrincipal") {} + +export interface RelayEnvironmentPrincipalShape { + readonly environmentId: string; + readonly environmentPublicKey: string; +} + +export class RelayEnvironmentPrincipal extends Context.Service< + RelayEnvironmentPrincipal, + RelayEnvironmentPrincipalShape +>()("@t3tools/contracts/relay/RelayEnvironmentPrincipal") {} + +export class RelayClientAuth extends HttpApiMiddleware.Service< + RelayClientAuth, + { provides: RelayClientPrincipal } +>()("RelayClientAuth", { + error: RelayAuthInvalidError, + security: { bearer: HttpApiSecurity.bearer }, +}) {} + +export class RelayEnvironmentAuth extends HttpApiMiddleware.Service< + RelayEnvironmentAuth, + { provides: RelayEnvironmentPrincipal } +>()("RelayEnvironmentAuth", { + error: [RelayAuthInvalidError, RelayInternalError], + security: { bearer: HttpApiSecurity.bearer }, +}) {} + +const RelayDpopAuthorization = HttpApiSecurity.http({ scheme: "DPoP" }).pipe( + HttpApiSecurity.annotate( + OpenApi.Description, + "DPoP-bound access token. Requests must also include the DPoP proof JWT header.", + ), +); + +export class RelayDpopClientAuth extends HttpApiMiddleware.Service< + RelayDpopClientAuth, + { provides: RelayClientPrincipal } +>()("RelayDpopClientAuth", { + error: RelayAuthInvalidError, + security: { relayDpop: RelayDpopAuthorization }, +}) {} + +export const RelayClientEnvironmentRecord = Schema.Struct({ + environmentId: EnvironmentId, + label: TrimmedNonEmptyString, + endpoint: RelayManagedEndpoint, + linkedAt: TrimmedNonEmptyString, +}); +export type RelayClientEnvironmentRecord = typeof RelayClientEnvironmentRecord.Type; + +export const RelayListEnvironmentsResponse = Schema.Struct({ + environments: Schema.Array(RelayClientEnvironmentRecord), +}); +export type RelayListEnvironmentsResponse = typeof RelayListEnvironmentsResponse.Type; + +export const RelayEnvironmentConnectRequest = Schema.Struct({ + deviceId: Schema.optional(TrimmedNonEmptyString), + clientKeyThumbprint: Schema.optional(TrimmedNonEmptyString), + clientProofKeyThumbprint: Schema.optional(TrimmedNonEmptyString), +}); +export type RelayEnvironmentConnectRequest = typeof RelayEnvironmentConnectRequest.Type; + +export const RelayEnvironmentConnectScope = "environment:connect" as const; +export const RelayEnvironmentStatusScope = "environment:status" as const; +export const RelayMobileRegistrationScope = "mobile:registration" as const; +export const RelayDpopAccessTokenScope = Schema.Literals([ + RelayEnvironmentConnectScope, + RelayEnvironmentStatusScope, + RelayMobileRegistrationScope, +]); +export type RelayDpopAccessTokenScope = typeof RelayDpopAccessTokenScope.Type; + +export const RelayDpopTokenExchangeGrantType = + "urn:ietf:params:oauth:grant-type:token-exchange" as const; +export const RelayJwtSubjectTokenType = "urn:ietf:params:oauth:token-type:jwt" as const; +export const RelayAccessTokenType = "urn:ietf:params:oauth:token-type:access_token" as const; +export const RelayPublicClientId = Schema.Literals(["t3-mobile", "t3-web"]); +export type RelayPublicClientId = typeof RelayPublicClientId.Type; +export const RelayMobileClientId = "t3-mobile" as const; +export const RelayWebClientId = "t3-web" as const; + +export const RelayDpopAccessTokenRequest = Schema.Struct({ + grant_type: Schema.Literal(RelayDpopTokenExchangeGrantType), + subject_token: TrimmedNonEmptyString, + subject_token_type: Schema.Literal(RelayJwtSubjectTokenType), + requested_token_type: Schema.Literal(RelayAccessTokenType), + resource: TrimmedNonEmptyString, + scope: TrimmedNonEmptyString, + client_id: RelayPublicClientId, +}).pipe(HttpApiSchema.asFormUrlEncoded()); +export type RelayDpopAccessTokenRequest = typeof RelayDpopAccessTokenRequest.Type; + +export const RelayDpopAccessTokenResponse = Schema.Struct({ + access_token: TrimmedNonEmptyString, + issued_token_type: Schema.Literal(RelayAccessTokenType), + token_type: Schema.Literal("DPoP"), + expires_in: Schema.Int.check(Schema.isGreaterThan(0)), + scope: TrimmedNonEmptyString, +}); +export type RelayDpopAccessTokenResponse = typeof RelayDpopAccessTokenResponse.Type; + +export const RelayBearerRequestHeaders = Schema.Struct({ + authorization: TrimmedNonEmptyString, +}); + +export const RelayDpopProofRequestHeaders = Schema.Struct({ + dpop: TrimmedNonEmptyString, +}); + +export const RelayDpopRequestHeaders = Schema.Struct({ + authorization: TrimmedNonEmptyString, + dpop: TrimmedNonEmptyString, +}); + +export const RelayAuthorizationServerMetadata = Schema.Struct({ + issuer: TrimmedNonEmptyString, + token_endpoint: TrimmedNonEmptyString, + grant_types_supported: Schema.Array(Schema.Literal(RelayDpopTokenExchangeGrantType)), + token_endpoint_auth_methods_supported: Schema.Array(Schema.Literal("none")), + dpop_signing_alg_values_supported: Schema.Array(Schema.Literal("ES256")), + scopes_supported: Schema.Array(RelayDpopAccessTokenScope), +}); + +export const RelayProtectedResourceMetadata = Schema.Struct({ + resource: TrimmedNonEmptyString, + authorization_servers: Schema.Array(TrimmedNonEmptyString), + scopes_supported: Schema.Array(RelayDpopAccessTokenScope), + dpop_bound_access_tokens_required: Schema.Boolean, + dpop_signing_alg_values_supported: Schema.Array(Schema.Literal("ES256")), +}); + +export const RelayEnvironmentUnlinkParams = Schema.Struct({ + environmentId: EnvironmentId, +}); +export type RelayEnvironmentUnlinkParams = typeof RelayEnvironmentUnlinkParams.Type; + +export const RelayEnvironmentConnectResponse = Schema.Struct({ + environmentId: EnvironmentId, + endpoint: RelayManagedEndpoint, + credential: TrimmedNonEmptyString, + expiresAt: TrimmedNonEmptyString, +}); +export type RelayEnvironmentConnectResponse = typeof RelayEnvironmentConnectResponse.Type; + +export const RelayEnvironmentStatusValue = Schema.Literals(["online", "offline"]); +export type RelayEnvironmentStatusValue = typeof RelayEnvironmentStatusValue.Type; + +export const RelayEnvironmentStatusResponse = Schema.Struct({ + environmentId: EnvironmentId, + endpoint: RelayManagedEndpoint, + status: RelayEnvironmentStatusValue, + checkedAt: TrimmedNonEmptyString, + descriptor: Schema.optional(ExecutionEnvironmentDescriptor), + error: Schema.optional(TrimmedNonEmptyString), +}); +export type RelayEnvironmentStatusResponse = typeof RelayEnvironmentStatusResponse.Type; + +export const RelayCloudMintCredentialProofPayload = Schema.Struct({ + ...RelaySignedJwtRegisteredClaims, + environmentId: EnvironmentId, + clientProofKeyThumbprint: TrimmedNonEmptyString, + cnf: Schema.Struct({ + jkt: TrimmedNonEmptyString, + }), + deviceId: Schema.optional(TrimmedNonEmptyString), + nonce: TrimmedNonEmptyString, + scope: Schema.Array(Schema.Literal("environment:connect")), +}); +export type RelayCloudMintCredentialProofPayload = typeof RelayCloudMintCredentialProofPayload.Type; + +export const RelayCloudMintCredentialProof = TrimmedNonEmptyString; +export type RelayCloudMintCredentialProof = typeof RelayCloudMintCredentialProof.Type; + +export const RelayCloudMintCredentialRequest = Schema.Struct({ + proof: RelayCloudMintCredentialProof, +}); +export type RelayCloudMintCredentialRequest = typeof RelayCloudMintCredentialRequest.Type; + +export const RelayCloudEnvironmentHealthProofPayload = Schema.Struct({ + ...RelaySignedJwtRegisteredClaims, + environmentId: EnvironmentId, + nonce: TrimmedNonEmptyString, + scope: Schema.Array(Schema.Literal("environment:status")), +}); +export type RelayCloudEnvironmentHealthProofPayload = + typeof RelayCloudEnvironmentHealthProofPayload.Type; + +export const RelayCloudEnvironmentHealthProof = TrimmedNonEmptyString; +export type RelayCloudEnvironmentHealthProof = typeof RelayCloudEnvironmentHealthProof.Type; + +export const RelayCloudEnvironmentHealthRequest = Schema.Struct({ + proof: RelayCloudEnvironmentHealthProof, +}); +export type RelayCloudEnvironmentHealthRequest = typeof RelayCloudEnvironmentHealthRequest.Type; + +export const RelayEnvironmentHealthResponseProofPayload = Schema.Struct({ + ...RelaySignedJwtRegisteredClaims, + environmentId: EnvironmentId, + requestNonce: TrimmedNonEmptyString, + status: Schema.Literal("online"), + descriptor: ExecutionEnvironmentDescriptor, + checkedAt: TrimmedNonEmptyString, +}); +export type RelayEnvironmentHealthResponseProofPayload = + typeof RelayEnvironmentHealthResponseProofPayload.Type; + +export const RelayEnvironmentHealthResponse = Schema.Struct({ + environmentId: EnvironmentId, + status: Schema.Literal("online"), + descriptor: ExecutionEnvironmentDescriptor, + checkedAt: TrimmedNonEmptyString, + proof: TrimmedNonEmptyString, +}); +export type RelayEnvironmentHealthResponse = typeof RelayEnvironmentHealthResponse.Type; + +export const RelayEnvironmentMintResponseProofPayload = Schema.Struct({ + ...RelaySignedJwtRegisteredClaims, + environmentId: EnvironmentId, + clientProofKeyThumbprint: TrimmedNonEmptyString, + requestNonce: TrimmedNonEmptyString, + credential: TrimmedNonEmptyString, +}); +export type RelayEnvironmentMintResponseProofPayload = + typeof RelayEnvironmentMintResponseProofPayload.Type; + +export const RelayEnvironmentMintResponse = Schema.Struct({ + credential: TrimmedNonEmptyString, + expiresAt: TrimmedNonEmptyString, + proof: TrimmedNonEmptyString, +}); +export type RelayEnvironmentMintResponse = typeof RelayEnvironmentMintResponse.Type; + +export const RelayDeliveryKind = Schema.Literals([ + "live_activity_start", + "live_activity_update", + "live_activity_end", + "push_notification", +]); +export type RelayDeliveryKind = typeof RelayDeliveryKind.Type; + +export const RelayDeliveryResult = Schema.Struct({ + deviceId: TrimmedNonEmptyString, + kind: RelayDeliveryKind, + ok: Schema.Boolean, + queued: Schema.optional(Schema.Boolean), + apnsStatus: Schema.NullOr(Schema.Number), + apnsReason: Schema.NullOr(Schema.String), + apnsId: Schema.NullOr(Schema.String), +}); +export type RelayDeliveryResult = typeof RelayDeliveryResult.Type; + +export const RelayOkResponse = Schema.Struct({ + ok: Schema.Boolean, +}); +export type RelayOkResponse = typeof RelayOkResponse.Type; + +export const RelayPublishResponse = Schema.Struct({ + ok: Schema.Boolean, + deliveries: Schema.Array(RelayDeliveryResult), +}); +export type RelayPublishResponse = typeof RelayPublishResponse.Type; + +export const RelayHealthResponse = Schema.Struct({ + ok: Schema.Boolean, + service: Schema.Literal("relay"), +}); +export type RelayHealthResponse = typeof RelayHealthResponse.Type; + +export const RelayHealthGroup = HttpApiGroup.make("health").add( + HttpApiEndpoint.get("health", "/health", { + success: RelayHealthResponse, + error: RelayInternalError, + }), +); + +export const RelayMetadataGroup = HttpApiGroup.make("metadata").add( + HttpApiEndpoint.get("authorizationServer", "/.well-known/oauth-authorization-server", { + success: RelayAuthorizationServerMetadata, + }), + HttpApiEndpoint.get("protectedResource", "/.well-known/oauth-protected-resource", { + success: RelayProtectedResourceMetadata, + }), +); + +export const RelayRegisterDeviceEndpoint = HttpApiEndpoint.post( + "registerDevice", + "/v1/mobile/devices", + { + headers: RelayDpopRequestHeaders, + payload: RelayDeviceRegistrationRequest, + success: RelayOkResponse, + error: RelayAuthAndInternalErrors, + }, +); + +export const RelayRegisterLiveActivityEndpoint = HttpApiEndpoint.post( + "registerLiveActivity", + "/v1/mobile/live-activities", + { + headers: RelayDpopRequestHeaders, + payload: RelayLiveActivityRegistrationRequest, + success: RelayOkResponse, + error: RelayAuthAndInternalErrors, + }, +); + +export const RelayUnregisterDeviceEndpoint = HttpApiEndpoint.delete( + "unregisterDevice", + "/v1/mobile/devices/:deviceId", + { + headers: RelayDpopRequestHeaders, + params: RelayDeviceUnregistrationParams, + success: RelayOkResponse, + error: RelayAuthAndInternalErrors, + }, +); + +export const RelayMobileGroup = HttpApiGroup.make("mobile") + .add( + RelayRegisterDeviceEndpoint, + RelayRegisterLiveActivityEndpoint, + RelayUnregisterDeviceEndpoint, + ) + .middleware(RelayDpopClientAuth); + +export const RelayClientGroup = HttpApiGroup.make("client") + .add( + HttpApiEndpoint.get("listEnvironments", "/v1/environments", { + headers: RelayBearerRequestHeaders, + success: RelayListEnvironmentsResponse, + error: RelayAuthAndInternalErrors, + }), + HttpApiEndpoint.post("linkEnvironment", "/v1/client/environment-links", { + headers: RelayBearerRequestHeaders, + payload: RelayEnvironmentLinkRequest, + success: RelayEnvironmentLinkResponse, + error: RelayEnvironmentLinkErrors, + }), + HttpApiEndpoint.post( + "createEnvironmentLinkChallenge", + "/v1/client/environment-link-challenges", + { + headers: RelayBearerRequestHeaders, + payload: RelayEnvironmentLinkChallengeRequest, + success: RelayEnvironmentLinkChallengeResponse, + error: RelayAuthAndInternalErrors, + }, + ), + HttpApiEndpoint.delete("unlinkEnvironment", "/v1/client/environment-links/:environmentId", { + headers: RelayBearerRequestHeaders, + params: RelayEnvironmentUnlinkParams, + success: RelayOkResponse, + error: RelayAuthAndInternalErrors, + }), + ) + .middleware(RelayClientAuth); + +export const RelayExchangeDpopAccessTokenEndpoint = HttpApiEndpoint.post( + "exchangeDpopAccessToken", + "/v1/client/dpop-token", + { + headers: RelayDpopProofRequestHeaders, + payload: RelayDpopAccessTokenRequest, + success: RelayDpopAccessTokenResponse, + error: RelayAuthAndInternalErrors, + }, +); + +export const RelayTokenGroup = HttpApiGroup.make("token").add(RelayExchangeDpopAccessTokenEndpoint); + +export const RelayConnectEnvironmentEndpoint = HttpApiEndpoint.post( + "connectEnvironment", + "/v1/environments/:environmentId/connect", + { + headers: RelayDpopRequestHeaders, + params: Schema.Struct({ + environmentId: EnvironmentId, + }), + payload: RelayEnvironmentConnectRequest, + success: RelayEnvironmentConnectResponse, + error: RelayEnvironmentConnectErrors, + }, +); + +export const RelayGetEnvironmentStatusEndpoint = HttpApiEndpoint.post( + "getEnvironmentStatus", + "/v1/environments/:environmentId/status", + { + headers: RelayDpopRequestHeaders, + params: Schema.Struct({ + environmentId: EnvironmentId, + }), + success: RelayEnvironmentStatusResponse, + error: RelayEnvironmentConnectErrors, + }, +); + +export const RelayDpopClientGroup = HttpApiGroup.make("dpopClient") + .add(RelayConnectEnvironmentEndpoint, RelayGetEnvironmentStatusEndpoint) + .middleware(RelayDpopClientAuth); + +export const RelayServerGroup = HttpApiGroup.make("server") + .add( + HttpApiEndpoint.post( + "publishAgentActivity", + "/v1/environments/:environmentId/threads/:threadId/agent-activity", + { + params: Schema.Struct({ + environmentId: EnvironmentId, + threadId: ThreadId, + }), + payload: RelayAgentActivityPublishRequest, + success: RelayPublishResponse, + error: RelayAgentActivityPublishErrors, + }, + ), + ) + .middleware(RelayEnvironmentAuth); + +export const RelayApi = HttpApi.make("RelayApi").add( + RelayHealthGroup, + RelayMetadataGroup, + RelayMobileGroup, + RelayClientGroup, + RelayTokenGroup, + RelayDpopClientGroup, + RelayServerGroup, +); +export type RelayApi = typeof RelayApi; diff --git a/packages/shared/package.json b/packages/shared/package.json index ea4233a9d9..a447c40407 100644 --- a/packages/shared/package.json +++ b/packages/shared/package.json @@ -11,6 +11,10 @@ "types": "./src/advertisedEndpoint.ts", "import": "./src/advertisedEndpoint.ts" }, + "./agentAwareness": { + "types": "./src/agentAwareness.ts", + "import": "./src/agentAwareness.ts" + }, "./git": { "types": "./src/git.ts", "import": "./src/git.ts" @@ -83,6 +87,26 @@ "types": "./src/remote.ts", "import": "./src/remote.ts" }, + "./relaySigning": { + "types": "./src/relaySigning.ts", + "import": "./src/relaySigning.ts" + }, + "./dpop": { + "types": "./src/dpop.ts", + "import": "./src/dpop.ts" + }, + "./dpopCommon": { + "types": "./src/dpopCommon.ts", + "import": "./src/dpopCommon.ts" + }, + "./relayAuth": { + "types": "./src/relayAuth.ts", + "import": "./src/relayAuth.ts" + }, + "./relayJwt": { + "types": "./src/relayJwt.ts", + "import": "./src/relayJwt.ts" + }, "./oauthScope": { "types": "./src/oauthScope.ts", "import": "./src/oauthScope.ts" @@ -121,8 +145,11 @@ "test": "vp test run" }, "dependencies": { + "@noble/curves": "catalog:", + "@noble/hashes": "catalog:", "@t3tools/contracts": "workspace:*", "effect": "catalog:", + "jose": "catalog:", "yaml": "catalog:" }, "devDependencies": { diff --git a/packages/shared/src/agentAwareness.test.ts b/packages/shared/src/agentAwareness.test.ts new file mode 100644 index 0000000000..217e001635 --- /dev/null +++ b/packages/shared/src/agentAwareness.test.ts @@ -0,0 +1,128 @@ +import { describe, expect, it } from "@effect/vitest"; + +import type { + EnvironmentId, + OrchestrationProjectShell, + OrchestrationThreadShell, + ThreadId, + TurnId, +} from "@t3tools/contracts"; +import { ProviderInstanceId } from "@t3tools/contracts"; + +import { projectThreadAwareness } from "./agentAwareness.ts"; + +const NOW = "2026-05-22T12:00:00.000Z"; + +const project = { + title: "t3code", +} satisfies Pick; + +function thread( + overrides: Partial = {}, +): Pick< + OrchestrationThreadShell, + | "id" + | "title" + | "modelSelection" + | "session" + | "latestTurn" + | "updatedAt" + | "hasPendingApprovals" + | "hasPendingUserInput" +> { + return { + id: "thread-1" as ThreadId, + title: "Fix failing CI", + modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" }, + session: null, + latestTurn: null, + updatedAt: NOW, + hasPendingApprovals: false, + hasPendingUserInput: false, + ...overrides, + }; +} + +describe("projectThreadAwareness", () => { + it("returns null for idle threads without an active awareness state", () => { + expect( + projectThreadAwareness({ + environmentId: "env-1" as EnvironmentId, + project, + thread: thread(), + }), + ).toBeNull(); + }); + + it("prioritizes approval requests over running state", () => { + const state = projectThreadAwareness({ + environmentId: "env-1" as EnvironmentId, + project, + thread: thread({ + hasPendingApprovals: true, + session: { + threadId: "thread-1" as ThreadId, + status: "running", + providerName: "Codex", + runtimeMode: "full-access", + activeTurnId: "turn-1" as TurnId, + lastError: null, + updatedAt: NOW, + }, + }), + }); + + expect(state?.phase).toBe("waiting_for_approval"); + expect(state?.headline).toBe("Approval needed"); + }); + + it("projects running provider sessions", () => { + const state = projectThreadAwareness({ + environmentId: "env-1" as EnvironmentId, + project, + thread: thread({ + session: { + threadId: "thread-1" as ThreadId, + status: "running", + providerName: "Codex", + runtimeMode: "full-access", + activeTurnId: "turn-1" as TurnId, + lastError: null, + updatedAt: NOW, + }, + }), + }); + + expect(state).toMatchObject({ + phase: "running", + headline: "Agent is working", + detail: "Codex is active.", + modelTitle: "gpt-5.4", + deepLink: "/threads/env-1/thread-1", + }); + }); + + it("projects failures with the session error detail", () => { + const state = projectThreadAwareness({ + environmentId: "env-1" as EnvironmentId, + project, + thread: thread({ + session: { + threadId: "thread-1" as ThreadId, + status: "error", + providerName: "Codex", + runtimeMode: "full-access", + activeTurnId: null, + lastError: "Provider process exited.", + updatedAt: NOW, + }, + }), + }); + + expect(state).toMatchObject({ + phase: "failed", + headline: "Agent failed", + detail: "Provider process exited.", + }); + }); +}); diff --git a/packages/shared/src/agentAwareness.ts b/packages/shared/src/agentAwareness.ts new file mode 100644 index 0000000000..6831e8ba30 --- /dev/null +++ b/packages/shared/src/agentAwareness.ts @@ -0,0 +1,142 @@ +import type { + EnvironmentId, + OrchestrationProjectShell, + OrchestrationThreadShell, + ThreadId, +} from "@t3tools/contracts"; + +export type AgentAwarenessPhase = + | "starting" + | "running" + | "waiting_for_approval" + | "waiting_for_input" + | "completed" + | "failed" + | "stale"; + +export interface AgentAwarenessState { + readonly environmentId: EnvironmentId; + readonly threadId: ThreadId; + readonly projectTitle: string; + readonly threadTitle: string; + readonly phase: AgentAwarenessPhase; + readonly headline: string; + readonly detail?: string; + readonly modelTitle: string; + readonly updatedAt: string; + readonly deepLink: string; +} + +export interface ProjectThreadAwarenessInput { + readonly environmentId: EnvironmentId; + readonly project: Pick; + readonly thread: Pick< + OrchestrationThreadShell, + | "id" + | "title" + | "modelSelection" + | "session" + | "latestTurn" + | "updatedAt" + | "hasPendingApprovals" + | "hasPendingUserInput" + >; +} + +export function buildAgentAwarenessDeepLink(input: { + readonly environmentId: EnvironmentId; + readonly threadId: ThreadId; +}): string { + return `/threads/${encodeURIComponent(input.environmentId)}/${encodeURIComponent(input.threadId)}`; +} + +export function isTerminalAgentAwarenessPhase(phase: AgentAwarenessPhase): boolean { + return phase === "completed" || phase === "failed"; +} + +export function isInterruptiveAgentAwarenessPhase(phase: AgentAwarenessPhase): boolean { + return phase === "waiting_for_approval" || phase === "waiting_for_input" || phase === "failed"; +} + +export function projectThreadAwareness( + input: ProjectThreadAwarenessInput, +): AgentAwarenessState | null { + const { environmentId, project, thread } = input; + const phase = resolveThreadAwarenessPhase(thread); + if (!phase) { + return null; + } + + const detail = detailForPhase(phase, thread); + return { + environmentId, + threadId: thread.id, + projectTitle: project.title, + threadTitle: thread.title, + phase, + headline: headlineForPhase(phase), + ...(detail === undefined ? {} : { detail }), + modelTitle: thread.modelSelection.model, + updatedAt: thread.updatedAt, + deepLink: buildAgentAwarenessDeepLink({ environmentId, threadId: thread.id }), + }; +} + +function resolveThreadAwarenessPhase( + thread: ProjectThreadAwarenessInput["thread"], +): AgentAwarenessPhase | null { + if (thread.hasPendingApprovals) { + return "waiting_for_approval"; + } + if (thread.hasPendingUserInput) { + return "waiting_for_input"; + } + if (thread.session?.status === "error" || thread.latestTurn?.state === "error") { + return "failed"; + } + if (thread.session?.status === "starting") { + return "starting"; + } + if (thread.session?.status === "running" || thread.latestTurn?.state === "running") { + return "running"; + } + if (thread.latestTurn?.state === "completed") { + return "completed"; + } + return null; +} + +function headlineForPhase(phase: AgentAwarenessPhase): string { + switch (phase) { + case "starting": + return "Starting agent"; + case "running": + return "Agent is working"; + case "waiting_for_approval": + return "Approval needed"; + case "waiting_for_input": + return "Waiting for input"; + case "completed": + return "Agent finished"; + case "failed": + return "Agent failed"; + case "stale": + return "Update delayed"; + } +} + +function detailForPhase( + phase: AgentAwarenessPhase, + thread: ProjectThreadAwarenessInput["thread"], +): string | undefined { + if (phase === "failed") { + return thread.session?.lastError ?? undefined; + } + if (phase === "completed") { + return "Review the completed task."; + } + if (phase === "running" && thread.session?.providerName) { + return `${thread.session.providerName} is active.`; + } + return undefined; +} diff --git a/packages/shared/src/dpop.test.ts b/packages/shared/src/dpop.test.ts new file mode 100644 index 0000000000..58bd161e2a --- /dev/null +++ b/packages/shared/src/dpop.test.ts @@ -0,0 +1,205 @@ +import * as NodeCrypto from "node:crypto"; + +import { describe, expect, it } from "@effect/vitest"; + +import { + computeDpopAccessTokenHash, + computeDpopJwkThumbprint, + normalizeDpopHtu, + type DpopPublicJwk, + verifyDpopProof, +} from "./dpop.ts"; + +function signDpopProof(input: { + readonly method: string; + readonly url: string; + readonly iat: number; + readonly privateKey: NodeCrypto.KeyObject; + readonly publicJwk: DpopPublicJwk | (DpopPublicJwk & { readonly d: string }); + readonly accessToken?: string; +}) { + const header = Buffer.from( + JSON.stringify({ + typ: "dpop+jwt", + alg: "ES256", + jwk: input.publicJwk, + }), + ).toString("base64url"); + const payload = Buffer.from( + JSON.stringify({ + htm: input.method, + htu: input.url, + jti: "proof-1", + iat: input.iat, + ...(input.accessToken ? { ath: computeDpopAccessTokenHash(input.accessToken) } : {}), + }), + ).toString("base64url"); + const signature = NodeCrypto.sign("sha256", Buffer.from(`${header}.${payload}`), { + key: input.privateKey, + dsaEncoding: "ieee-p1363", + }).toString("base64url"); + return `${header}.${payload}.${signature}`; +} + +describe("verifyDpopProof", () => { + const { privateKey, publicKey } = NodeCrypto.generateKeyPairSync("ec", { + namedCurve: "P-256", + }); + const publicJwk = publicKey.export({ format: "jwk" }) as DpopPublicJwk; + const proof = signDpopProof({ + method: "POST", + url: "https://example.com/oauth/token", + iat: 100, + privateKey, + publicJwk, + }); + + it("verifies an ES256 DPoP proof and returns the RFC 7638 thumbprint", () => { + const thumbprint = computeDpopJwkThumbprint(publicJwk); + expect( + verifyDpopProof({ + proof, + method: "POST", + url: "https://example.com/oauth/token", + nowEpochSeconds: 101, + expectedThumbprint: thumbprint, + }), + ).toMatchObject({ + ok: true, + thumbprint, + jti: "proof-1", + }); + }); + + it("rejects method, URL, thumbprint, and time-window mismatches", () => { + const thumbprint = computeDpopJwkThumbprint(publicJwk); + expect( + verifyDpopProof({ + proof, + method: "GET", + url: "https://example.com/oauth/token", + nowEpochSeconds: 101, + expectedThumbprint: thumbprint, + }), + ).toMatchObject({ ok: false }); + expect( + verifyDpopProof({ + proof, + method: "POST", + url: "https://example.com/other", + nowEpochSeconds: 101, + expectedThumbprint: thumbprint, + }), + ).toMatchObject({ ok: false }); + expect( + verifyDpopProof({ + proof, + method: "POST", + url: "https://example.com/oauth/token", + nowEpochSeconds: 101, + expectedThumbprint: "other-thumbprint", + }), + ).toMatchObject({ ok: false }); + expect( + verifyDpopProof({ + proof, + method: "POST", + url: "https://example.com/oauth/token", + nowEpochSeconds: 1_000, + expectedThumbprint: thumbprint, + }), + ).toMatchObject({ ok: false }); + }); + + it("requires the RFC 9449 access token hash when an access token is expected", () => { + const thumbprint = computeDpopJwkThumbprint(publicJwk); + const accessTokenProof = signDpopProof({ + method: "POST", + url: "https://example.com/v1/environments/env/connect", + iat: 100, + privateKey, + publicJwk, + accessToken: "clerk-access-token", + }); + + expect( + verifyDpopProof({ + proof: accessTokenProof, + method: "POST", + url: "https://example.com/v1/environments/env/connect", + nowEpochSeconds: 101, + expectedThumbprint: thumbprint, + expectedAccessToken: "clerk-access-token", + }), + ).toMatchObject({ ok: true }); + expect( + verifyDpopProof({ + proof, + method: "POST", + url: "https://example.com/oauth/token", + nowEpochSeconds: 101, + expectedThumbprint: thumbprint, + expectedAccessToken: "clerk-access-token", + }), + ).toMatchObject({ ok: false, reason: "DPoP access token hash mismatch." }); + expect( + verifyDpopProof({ + proof: accessTokenProof, + method: "POST", + url: "https://example.com/v1/environments/env/connect", + nowEpochSeconds: 101, + expectedThumbprint: thumbprint, + expectedAccessToken: "other-access-token", + }), + ).toMatchObject({ ok: false, reason: "DPoP access token hash mismatch." }); + }); + + it("normalizes htu by excluding query and fragment components per RFC 9449", () => { + expect(normalizeDpopHtu("https://example.com/v1/environments/env/connect?foo=bar#frag")).toBe( + "https://example.com/v1/environments/env/connect", + ); + + const thumbprint = computeDpopJwkThumbprint(publicJwk); + const queryProof = signDpopProof({ + method: "POST", + url: "https://example.com/v1/environments/env/connect", + iat: 100, + privateKey, + publicJwk, + }); + + expect( + verifyDpopProof({ + proof: queryProof, + method: "POST", + url: "https://example.com/v1/environments/env/connect?foo=bar#frag", + nowEpochSeconds: 101, + expectedThumbprint: thumbprint, + }), + ).toMatchObject({ ok: true }); + }); + + it("rejects DPoP public JWK headers that expose private key material", () => { + const thumbprint = computeDpopJwkThumbprint(publicJwk); + const privateJwk = privateKey.export({ format: "jwk" }) as DpopPublicJwk & { + readonly d: string; + }; + const proofWithPrivateJwk = signDpopProof({ + method: "POST", + url: "https://example.com/oauth/token", + iat: 100, + privateKey, + publicJwk: privateJwk, + }); + + expect( + verifyDpopProof({ + proof: proofWithPrivateJwk, + method: "POST", + url: "https://example.com/oauth/token", + nowEpochSeconds: 101, + expectedThumbprint: thumbprint, + }), + ).toMatchObject({ ok: false, reason: "Invalid DPoP JWT header." }); + }); +}); diff --git a/packages/shared/src/dpop.ts b/packages/shared/src/dpop.ts new file mode 100644 index 0000000000..3421067900 --- /dev/null +++ b/packages/shared/src/dpop.ts @@ -0,0 +1,200 @@ +import { p256 } from "@noble/curves/nist"; +import { sha256 } from "@noble/hashes/sha2"; +import * as Encoding from "effect/Encoding"; +import * as Result from "effect/Result"; +import * as Schema from "effect/Schema"; + +import { stableStringify } from "./relaySigning.ts"; + +const DPOP_TYP = "dpop+jwt"; +const DPOP_ALG = "ES256"; +const DEFAULT_MAX_AGE_SECONDS = 300; + +export const DpopPublicJwk = Schema.Struct({ + kty: Schema.Literal("EC"), + crv: Schema.Literal("P-256"), + x: Schema.String.check(Schema.isNonEmpty()), + y: Schema.String.check(Schema.isNonEmpty()), +}); +export type DpopPublicJwk = typeof DpopPublicJwk.Type; +const isDpopPublicJwk = Schema.is(DpopPublicJwk); + +interface DpopJwtHeader { + readonly typ: string; + readonly alg: string; + readonly jwk: DpopPublicJwk; +} + +interface DpopJwtPayload { + readonly htm: string; + readonly htu: string; + readonly jti: string; + readonly iat: number; + readonly ath?: string; +} + +export type DpopVerificationResult = + | { + readonly ok: true; + readonly thumbprint: string; + readonly jti: string; + readonly iat: number; + } + | { + readonly ok: false; + readonly reason: string; + }; + +function base64UrlToBytes(value: string): Uint8Array { + return Result.getOrThrow(Encoding.decodeBase64Url(value)); +} + +function decodeBase64UrlJson(value: string): unknown { + return JSON.parse(Result.getOrThrow(Encoding.decodeBase64UrlString(value))) as unknown; +} + +function isDpopJwtHeader(value: unknown): value is DpopJwtHeader { + if (typeof value !== "object" || value === null) { + return false; + } + const record = value as Record; + return ( + record.typ === DPOP_TYP && + record.alg === DPOP_ALG && + typeof record.jwk === "object" && + record.jwk !== null && + !("d" in record.jwk) && + isDpopPublicJwk(record.jwk) + ); +} + +function isDpopJwtPayload(value: unknown): value is DpopJwtPayload { + if (typeof value !== "object" || value === null) { + return false; + } + const record = value as Record; + return ( + typeof record.htm === "string" && + record.htm.length > 0 && + typeof record.htu === "string" && + record.htu.length > 0 && + typeof record.jti === "string" && + record.jti.length > 0 && + typeof record.iat === "number" && + Number.isInteger(record.iat) + ); +} + +function dpopThumbprintInput(jwk: DpopPublicJwk): string { + return stableStringify({ + crv: jwk.crv, + kty: jwk.kty, + x: jwk.x, + y: jwk.y, + }); +} + +export function normalizeDpopHtu(url: string): string | null { + try { + const parsed = new URL(url); + parsed.hash = ""; + parsed.search = ""; + return parsed.toString(); + } catch { + return null; + } +} + +export function computeDpopJwkThumbprint(jwk: DpopPublicJwk): string { + return Encoding.encodeBase64Url(sha256(new TextEncoder().encode(dpopThumbprintInput(jwk)))); +} + +export function computeDpopAccessTokenHash(accessToken: string): string { + return Encoding.encodeBase64Url(sha256(new TextEncoder().encode(accessToken))); +} + +function publicKeyBytesFromJwk(jwk: DpopPublicJwk): Uint8Array { + const x = base64UrlToBytes(jwk.x); + const y = base64UrlToBytes(jwk.y); + if (x.length !== 32 || y.length !== 32) { + throw new Error("Invalid P-256 public key coordinate length."); + } + const publicKey = new Uint8Array(65); + publicKey[0] = 0x04; + publicKey.set(x, 1); + publicKey.set(y, 33); + return publicKey; +} + +export function verifyDpopProof(input: { + readonly proof: string | null | undefined; + readonly method: string; + readonly url: string; + readonly nowEpochSeconds: number; + readonly expectedThumbprint?: string; + readonly expectedAccessToken?: string; + readonly maxAgeSeconds?: number; +}): DpopVerificationResult { + if (!input.proof?.trim()) { + return { ok: false, reason: "Missing DPoP proof." }; + } + + const parts = input.proof.split("."); + if (parts.length !== 3 || !parts[0] || !parts[1] || !parts[2]) { + return { ok: false, reason: "Invalid DPoP compact JWT." }; + } + + try { + const header = decodeBase64UrlJson(parts[0]); + const payload = decodeBase64UrlJson(parts[1]); + if (!isDpopJwtHeader(header)) { + return { ok: false, reason: "Invalid DPoP JWT header." }; + } + if (!isDpopJwtPayload(payload)) { + return { ok: false, reason: "Invalid DPoP JWT payload." }; + } + + const thumbprint = computeDpopJwkThumbprint(header.jwk); + if (input.expectedThumbprint && thumbprint !== input.expectedThumbprint) { + return { ok: false, reason: "DPoP key thumbprint mismatch." }; + } + if (payload.htm.toUpperCase() !== input.method.toUpperCase()) { + return { ok: false, reason: "DPoP method mismatch." }; + } + const normalizedHtu = normalizeDpopHtu(input.url); + if (normalizedHtu === null || payload.htu !== normalizedHtu) { + return { ok: false, reason: "DPoP URL mismatch." }; + } + if (input.expectedAccessToken) { + const expectedAth = computeDpopAccessTokenHash(input.expectedAccessToken); + if (payload.ath !== expectedAth) { + return { ok: false, reason: "DPoP access token hash mismatch." }; + } + } + + const maxAgeSeconds = input.maxAgeSeconds ?? DEFAULT_MAX_AGE_SECONDS; + if ( + payload.iat > input.nowEpochSeconds + 5 || + input.nowEpochSeconds - payload.iat > maxAgeSeconds + ) { + return { ok: false, reason: "DPoP proof is outside the allowed time window." }; + } + + const signature = base64UrlToBytes(parts[2]); + const signatureInputHash = sha256(new TextEncoder().encode(`${parts[0]}.${parts[1]}`)); + const verified = p256.verify(signature, signatureInputHash, publicKeyBytesFromJwk(header.jwk), { + prehash: false, + format: "compact", + }); + return verified + ? { + ok: true, + thumbprint, + jti: payload.jti, + iat: payload.iat, + } + : { ok: false, reason: "Invalid DPoP signature." }; + } catch { + return { ok: false, reason: "Invalid DPoP proof." }; + } +} diff --git a/packages/shared/src/dpopCommon.ts b/packages/shared/src/dpopCommon.ts new file mode 100644 index 0000000000..ba57b016c3 --- /dev/null +++ b/packages/shared/src/dpopCommon.ts @@ -0,0 +1,20 @@ +import * as Schema from "effect/Schema"; + +export const DpopPublicJwk = Schema.Struct({ + kty: Schema.Literal("EC"), + crv: Schema.Literal("P-256"), + x: Schema.String.check(Schema.isNonEmpty()), + y: Schema.String.check(Schema.isNonEmpty()), +}); +export type DpopPublicJwk = typeof DpopPublicJwk.Type; + +export function normalizeDpopHtu(url: string): string | null { + try { + const parsed = new URL(url); + parsed.hash = ""; + parsed.search = ""; + return parsed.toString(); + } catch { + return null; + } +} diff --git a/packages/shared/src/oauthScope.ts b/packages/shared/src/oauthScope.ts index 7016e49280..47c6dd7051 100644 --- a/packages/shared/src/oauthScope.ts +++ b/packages/shared/src/oauthScope.ts @@ -1,7 +1,8 @@ const OAUTH_SCOPE_TOKEN = /^[\u0021\u0023-\u005b\u005d-\u007e]+$/u; /** - * Decodes an RFC 6749 `scope` value as a set while preserving first-seen order. + * Decodes an RFC 6749 `scope` value as a set while preserving its first-seen + * order for canonical responses and logs. */ export function parseOAuthScope(value: string): ReadonlyArray | null { if (value.length === 0) { @@ -25,6 +26,15 @@ export function encodeOAuthScope(scopes: ReadonlyArray): string { return encoded; } +export function oauthScopeSetEquals(value: string, expectedScopes: ReadonlyArray): boolean { + const scopes = parseOAuthScope(value); + return ( + scopes !== null && + scopes.length === new Set(expectedScopes).size && + scopes.every((scope) => expectedScopes.includes(scope)) + ); +} + export function parseAllowedOAuthScope(input: { readonly value: string; readonly allowedScopes: ReadonlySet; diff --git a/packages/shared/src/relayAuth.ts b/packages/shared/src/relayAuth.ts new file mode 100644 index 0000000000..0f8c139d41 --- /dev/null +++ b/packages/shared/src/relayAuth.ts @@ -0,0 +1,6 @@ +export const RELAY_CLERK_JWT_TEMPLATE = "t3-relay"; + +export const RELAY_CLERK_TOKEN_OPTIONS = { + template: RELAY_CLERK_JWT_TEMPLATE, + skipCache: true, +} as const; diff --git a/packages/shared/src/relayJwt.ts b/packages/shared/src/relayJwt.ts new file mode 100644 index 0000000000..bd00023e8f --- /dev/null +++ b/packages/shared/src/relayJwt.ts @@ -0,0 +1,69 @@ +import { decodeJwt, importPKCS8, importSPKI, jwtVerify, SignJWT, type JWTPayload } from "jose"; +import * as Data from "effect/Data"; +import * as DateTime from "effect/DateTime"; +import * as Effect from "effect/Effect"; + +export const RELAY_LINK_PROOF_TYP = "t3-env-link+jwt"; +export const RELAY_MINT_REQUEST_TYP = "t3-cloud-mint+jwt"; +export const RELAY_HEALTH_REQUEST_TYP = "t3-cloud-health+jwt"; +export const RELAY_MINT_RESPONSE_TYP = "t3-env-mint+jwt"; +export const RELAY_HEALTH_RESPONSE_TYP = "t3-env-health+jwt"; +export const RELAY_ACTIVITY_PUBLISH_TYP = "t3-env-activity+jwt"; + +export class RelayJwtError extends Data.TaggedError("RelayJwtError")<{ + readonly cause: unknown; +}> {} + +export function normalizeRelayIssuer(value: string): string { + return value.trim().replace(/\/+$/gu, ""); +} + +export function decodeRelayJwt(token: string): JWTPayload { + return decodeJwt(token); +} + +function normalizePem(value: string): string { + return value.replace(/\\n/gu, "\n").trim(); +} + +export function signRelayJwt(input: { + readonly privateKey: string; + readonly typ: string; + readonly payload: JWTPayload; +}): Effect.Effect { + return Effect.tryPromise({ + try: async () => { + const key = await importPKCS8(normalizePem(input.privateKey), "EdDSA"); + return new SignJWT(input.payload) + .setProtectedHeader({ alg: "EdDSA", typ: input.typ }) + .sign(key); + }, + catch: (cause) => new RelayJwtError({ cause }), + }); +} + +export function verifyRelayJwt(input: { + readonly publicKey: string; + readonly token: string; + readonly typ: string; + readonly issuer: string; + readonly audience: string; + readonly nowEpochSeconds: number; +}): Effect.Effect { + return Effect.tryPromise({ + try: async () => { + const key = await importSPKI(normalizePem(input.publicKey), "EdDSA"); + const verified = await jwtVerify(input.token, key, { + algorithms: ["EdDSA"], + typ: input.typ, + issuer: input.issuer, + audience: input.audience, + maxTokenAge: "5 minutes", + clockTolerance: 60, + currentDate: DateTime.toDate(DateTime.makeUnsafe(input.nowEpochSeconds * 1_000)), + }); + return verified.payload; + }, + catch: (cause) => new RelayJwtError({ cause }), + }); +} diff --git a/packages/shared/src/relaySigning.test.ts b/packages/shared/src/relaySigning.test.ts new file mode 100644 index 0000000000..f847d9457d --- /dev/null +++ b/packages/shared/src/relaySigning.test.ts @@ -0,0 +1,18 @@ +import { describe, expect, it } from "@effect/vitest"; + +import { stableStringify } from "./relaySigning.ts"; + +describe("relaySigning", () => { + it("canonicalizes object keys recursively", () => { + expect( + stableStringify({ + z: 1, + a: { + y: true, + b: null, + }, + list: [{ c: "three", a: "one" }], + }), + ).toBe('{"a":{"b":null,"y":true},"list":[{"a":"one","c":"three"}],"z":1}'); + }); +}); diff --git a/packages/shared/src/relaySigning.ts b/packages/shared/src/relaySigning.ts new file mode 100644 index 0000000000..6b8b8cb2c7 --- /dev/null +++ b/packages/shared/src/relaySigning.ts @@ -0,0 +1,17 @@ +function isRecord(value: unknown): value is Record { + return typeof value === "object" && value !== null && !Array.isArray(value); +} + +export function stableStringify(value: unknown): string { + if (Array.isArray(value)) { + return `[${value.map(stableStringify).join(",")}]`; + } + if (isRecord(value)) { + return `{${Object.entries(value) + .filter(([, entryValue]) => entryValue !== undefined) + .sort(([left], [right]) => left.localeCompare(right)) + .map(([key, entryValue]) => `${JSON.stringify(key)}:${stableStringify(entryValue)}`) + .join(",")}}`; + } + return JSON.stringify(value) ?? "null"; +} diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yaml index 4897eb1427..644bb663de 100644 --- a/pnpm-workspace.yaml +++ b/pnpm-workspace.yaml @@ -1,5 +1,6 @@ packages: - "apps/*" + - "infra/*" - "oxlint-plugin-t3code" - "packages/*" - "scripts" @@ -21,14 +22,19 @@ catalog: "@effect/platform-bun": 4.0.0-beta.73 "@effect/platform-node": 4.0.0-beta.73 "@effect/platform-node-shared": 4.0.0-beta.73 + "@effect/sql-pg": 4.0.0-beta.73 "@effect/sql-sqlite-bun": 4.0.0-beta.73 "@effect/vitest": 4.0.0-beta.73 "@effect/tsgo": 0.11.4 + "@noble/curves": 1.9.1 + "@noble/hashes": 1.8.0 "@pierre/diffs": 1.1.20 "@vitest/runner": ^4.1.8 "@types/bun": ^1.3.11 "@types/node": 24.12.4 "@typescript/native-preview": 7.0.0-dev.20260527.2 + jose: 6.2.2 + tsdown: ^0.20.3 typescript: ~6.0.3 vitest: npm:@voidzero-dev/vite-plus-test@latest vite: npm:@voidzero-dev/vite-plus-core@latest @@ -39,6 +45,7 @@ overrides: "@effect/platform-bun": "catalog:" "@effect/platform-node": "catalog:" "@effect/platform-node-shared": "catalog:" + "@effect/sql-pg": "catalog:" "@effect/sql-sqlite-bun": "catalog:" "@effect/vitest": "catalog:" "@types/node": "catalog:" diff --git a/scripts/build-desktop-artifact.ts b/scripts/build-desktop-artifact.ts index f86c94e5d9..0ee2e38880 100644 --- a/scripts/build-desktop-artifact.ts +++ b/scripts/build-desktop-artifact.ts @@ -717,6 +717,12 @@ const createBuildConfig = Effect.fn("createBuildConfig")(function* ( target: target === "dmg" ? [target, "zip"] : [target], icon: "icon.icns", category: "public.app-category.developer-tools", + protocols: [ + { + name: "T3 Code", + schemes: ["t3code"], + }, + ], }; }