add managed relay tunnels and standards-based auth
Co-authored-by: codex <[email protected]>
This commit is contained in:
1 parent
a6edad1974
commit
02beeaa86c
212 files changed
+34451
-610
No files matched your search
@@ -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
|
||||
@@ -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
|
||||
|
||||
|
||||
@@ -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:
|
||||
|
||||
@@ -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();
|
||||
});
|
||||
|
||||
@@ -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,
|
||||
};
|
||||
}
|
||||
@@ -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"),
|
||||
|
||||
@@ -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(() => {
|
||||
|
||||
@@ -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<string, readonly ((...args: readonly unknown[]) => 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<string, ((...args: readonly unknown[]) => 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);
|
||||
},
|
||||
);
|
||||
});
|
||||
@@ -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<string, DesktopCloudAuthCallbackServerError>;
|
||||
readonly configure: Effect.Effect<
|
||||
void,
|
||||
never,
|
||||
ElectronApp.ElectronApp | ElectronWindow.ElectronWindow | Scope.Scope
|
||||
>;
|
||||
}
|
||||
|
||||
export class DesktopCloudAuth extends Context.Service<DesktopCloudAuth, DesktopCloudAuthShape>()(
|
||||
"@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<typeof setTimeout> {
|
||||
// @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<void, never, Scope.Scope> {
|
||||
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<ElectronWindow.ElectronWindow>();
|
||||
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);
|
||||
@@ -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 = <A, E, R>(
|
||||
effect: Effect.Effect<A, E, R | DesktopCloudAuthTokenStore.DesktopCloudAuthTokenStore>,
|
||||
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 },
|
||||
),
|
||||
);
|
||||
});
|
||||
@@ -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<string>,
|
||||
| DesktopCloudAuthTokenStoreDecodeError
|
||||
| ElectronSafeStorage.ElectronSafeStorageAvailabilityError
|
||||
| ElectronSafeStorage.ElectronSafeStorageDecryptError
|
||||
>;
|
||||
readonly set: (
|
||||
token: string,
|
||||
) => Effect.Effect<
|
||||
boolean,
|
||||
| DesktopCloudAuthTokenStoreWriteError
|
||||
| ElectronSafeStorage.ElectronSafeStorageAvailabilityError
|
||||
| ElectronSafeStorage.ElectronSafeStorageEncryptError
|
||||
>;
|
||||
readonly clear: Effect.Effect<void>;
|
||||
}
|
||||
|
||||
export class DesktopCloudAuthTokenStore extends Context.Service<
|
||||
DesktopCloudAuthTokenStore,
|
||||
DesktopCloudAuthTokenStoreShape
|
||||
>()("@t3tools/desktop/app/DesktopCloudAuthTokenStore") {}
|
||||
|
||||
function decodeSecretBytes(
|
||||
encoded: string,
|
||||
): Effect.Effect<Uint8Array, DesktopCloudAuthTokenStoreDecodeError> {
|
||||
return Effect.fromResult(Encoding.decodeBase64(encoded)).pipe(
|
||||
Effect.mapError((cause) => new DesktopCloudAuthTokenStoreDecodeError({ cause })),
|
||||
);
|
||||
}
|
||||
|
||||
const readDocument = (
|
||||
fileSystem: FileSystem.FileSystem,
|
||||
tokenPath: string,
|
||||
): Effect.Effect<Option.Option<CloudAuthTokenDocument>> =>
|
||||
fileSystem.readFileString(tokenPath).pipe(
|
||||
Effect.option,
|
||||
Effect.flatMap(
|
||||
Option.match({
|
||||
onNone: () => Effect.succeed(Option.none<CloudAuthTokenDocument>()),
|
||||
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<void, PlatformError.PlatformError | Schema.SchemaError> {
|
||||
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<string>();
|
||||
}
|
||||
|
||||
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"),
|
||||
),
|
||||
});
|
||||
}),
|
||||
);
|
||||
@@ -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"),
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -29,6 +29,13 @@ export interface ElectronAppShape {
|
||||
options: Electron.AboutPanelOptionsOptions,
|
||||
) => Effect.Effect<void>;
|
||||
readonly setAppUserModelId: (id: string) => Effect.Effect<void>;
|
||||
readonly requestSingleInstanceLock: Effect.Effect<boolean>;
|
||||
readonly isDefaultProtocolClient: (protocol: string) => Effect.Effect<boolean>;
|
||||
readonly setAsDefaultProtocolClient: (
|
||||
protocol: string,
|
||||
path?: string,
|
||||
args?: readonly string[],
|
||||
) => Effect.Effect<boolean>;
|
||||
readonly setDesktopName: (desktopName: string) => Effect.Effect<void>;
|
||||
readonly setDockIcon: (iconPath: string) => Effect.Effect<void>;
|
||||
readonly appendCommandLineSwitch: (switchName: string, value?: string) => Effect.Effect<void>;
|
||||
@@ -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 & {
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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";
|
||||
|
||||
@@ -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,
|
||||
};
|
||||
}),
|
||||
});
|
||||
@@ -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));
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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 }),
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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",
|
||||
},
|
||||
|
||||
@@ -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
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -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 <LoadingScreen message="Loading remote workspace…" />;
|
||||
}
|
||||
@@ -66,6 +74,7 @@ function AppNavigator() {
|
||||
headerShadowVisible: false,
|
||||
}}
|
||||
/>
|
||||
<Stack.Screen name="settings" options={settingsSheetScreenOptions} />
|
||||
<Stack.Screen name="connections" options={connectionSheetScreenOptions} />
|
||||
<Stack.Screen name="new" options={newTaskScreenOptions} />
|
||||
<Stack.Screen
|
||||
@@ -91,14 +100,20 @@ export default function RootLayout() {
|
||||
useRemoteEnvironmentBootstrap();
|
||||
|
||||
return (
|
||||
<RegistryContext value={appAtomRegistry}>
|
||||
<GestureHandlerRootView style={{ flex: 1 }}>
|
||||
<KeyboardProvider statusBarTranslucent>
|
||||
<SafeAreaProvider>
|
||||
{fontsLoaded ? <AppNavigator /> : <LoadingScreen message="Loading remote workspace…" />}
|
||||
</SafeAreaProvider>
|
||||
</KeyboardProvider>
|
||||
</GestureHandlerRootView>
|
||||
</RegistryContext>
|
||||
<RegistryContext.Provider value={appAtomRegistry}>
|
||||
<CloudAuthProvider>
|
||||
<GestureHandlerRootView style={{ flex: 1 }}>
|
||||
<KeyboardProvider statusBarTranslucent>
|
||||
<SafeAreaProvider>
|
||||
{fontsLoaded ? (
|
||||
<AppNavigator />
|
||||
) : (
|
||||
<LoadingScreen message="Loading remote workspace…" />
|
||||
)}
|
||||
</SafeAreaProvider>
|
||||
</KeyboardProvider>
|
||||
</GestureHandlerRootView>
|
||||
</CloudAuthProvider>
|
||||
</RegistryContext.Provider>
|
||||
);
|
||||
}
|
||||
@@ -22,8 +22,8 @@ export default function ConnectionsRouteScreen() {
|
||||
const hasEnvironments = connectedEnvironments.length > 0;
|
||||
const [expandedId, setExpandedId] = useState<EnvironmentId | null>(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: () => (
|
||||
<Link href="/connections/new" asChild>
|
||||
<Pressable className="h-10 w-10 items-center justify-center rounded-full bg-primary active:opacity-70">
|
||||
<Pressable
|
||||
accessibilityLabel="Add environment"
|
||||
accessibilityRole="button"
|
||||
className="h-10 w-10 items-center justify-center active:opacity-70"
|
||||
>
|
||||
<SymbolView
|
||||
name="plus"
|
||||
size={18}
|
||||
tintColor={primaryFg}
|
||||
tintColor={iconColor}
|
||||
type="monochrome"
|
||||
weight="semibold"
|
||||
/>
|
||||
|
||||
@@ -130,7 +130,9 @@ export default function ConnectionsNewRouteScreen() {
|
||||
title: showScanner ? "Scan QR Code" : "Add Environment",
|
||||
headerRight: () => (
|
||||
<Pressable
|
||||
className="h-10 w-10 items-center justify-center rounded-full border border-border bg-secondary"
|
||||
accessibilityLabel={showScanner ? "Close QR scanner" : "Scan pairing QR code"}
|
||||
accessibilityRole="button"
|
||||
className="h-10 w-10 items-center justify-center active:opacity-70"
|
||||
onPress={() => {
|
||||
if (showScanner) {
|
||||
closeScanner();
|
||||
|
||||
@@ -78,16 +78,11 @@ export default function HomeRouteScreen() {
|
||||
</Stack.Toolbar>
|
||||
|
||||
<Stack.Toolbar placement="right">
|
||||
<Stack.Toolbar.Menu icon="ellipsis.circle" separateBackground>
|
||||
<Stack.Toolbar.Label>More</Stack.Toolbar.Label>
|
||||
<Stack.Toolbar.MenuAction
|
||||
icon="desktopcomputer"
|
||||
onPress={() => router.push("/connections")}
|
||||
subtitle="Manage connected hosts"
|
||||
>
|
||||
<Stack.Toolbar.Label>Environments</Stack.Toolbar.Label>
|
||||
</Stack.Toolbar.MenuAction>
|
||||
</Stack.Toolbar.Menu>
|
||||
<Stack.Toolbar.Button
|
||||
icon="gearshape"
|
||||
onPress={() => router.push("/settings")}
|
||||
separateBackground
|
||||
/>
|
||||
</Stack.Toolbar>
|
||||
|
||||
{/* Bottom toolbar: search + compose, visually split like iMessage */}
|
||||
|
||||
@@ -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 (
|
||||
<Stack
|
||||
screenOptions={{
|
||||
contentStyle,
|
||||
headerBackButtonDisplayMode: "minimal",
|
||||
headerShadowVisible: false,
|
||||
headerStyle: { backgroundColor: sheetBg },
|
||||
headerTintColor: headerTint,
|
||||
headerTitleStyle: { fontFamily: "DMSans_700Bold" },
|
||||
}}
|
||||
>
|
||||
<Stack.Screen name="index" options={{ animation: "none", title: "Settings" }} />
|
||||
<Stack.Screen
|
||||
name="environments"
|
||||
options={{ animation: "slide_from_right", title: "Environments" }}
|
||||
/>
|
||||
<Stack.Screen
|
||||
name="environment-new"
|
||||
options={{ animation: "slide_from_right", title: "Add Environment" }}
|
||||
/>
|
||||
<Stack.Screen
|
||||
name="waitlist"
|
||||
options={{ animation: "slide_from_right", title: "Join the waitlist" }}
|
||||
/>
|
||||
</Stack>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
export { default } from "../connections/new";
|
||||
@@ -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<EnvironmentId | null>(null);
|
||||
const [cloudEnvironments, setCloudEnvironments] = useState<
|
||||
ReadonlyArray<CloudEnvironmentRecordWithStatus>
|
||||
>([]);
|
||||
const [cloudStatus, setCloudStatus] = useState<"idle" | "loading" | "error">("idle");
|
||||
const [cloudError, setCloudError] = useState<string | null>(null);
|
||||
const [connectingCloudEnvironmentId, setConnectingCloudEnvironmentId] = useState<string | null>(
|
||||
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 (
|
||||
<View collapsable={false} className="flex-1 bg-sheet">
|
||||
<Stack.Screen
|
||||
options={{
|
||||
title: "Environments",
|
||||
headerRight: () => (
|
||||
<Link href="/settings/environment-new" asChild>
|
||||
<Pressable
|
||||
accessibilityLabel="Add environment"
|
||||
accessibilityRole="button"
|
||||
className="h-10 w-10 items-center justify-center active:opacity-70"
|
||||
>
|
||||
<SymbolView
|
||||
name="plus"
|
||||
size={18}
|
||||
tintColor={iconColor}
|
||||
type="monochrome"
|
||||
weight="semibold"
|
||||
/>
|
||||
</Pressable>
|
||||
</Link>
|
||||
),
|
||||
}}
|
||||
/>
|
||||
<ScrollView
|
||||
contentInsetAdjustmentBehavior="automatic"
|
||||
showsVerticalScrollIndicator={false}
|
||||
style={{ flex: 1 }}
|
||||
contentContainerStyle={{
|
||||
paddingBottom: Math.max(insets.bottom, 18) + 18,
|
||||
paddingHorizontal: 20,
|
||||
paddingTop: 16,
|
||||
}}
|
||||
>
|
||||
{hasEnvironments ? (
|
||||
<View collapsable={false} className="overflow-hidden rounded-[24px] bg-card">
|
||||
{connectedEnvironments.map((environment, index) => (
|
||||
<View
|
||||
key={environment.environmentId}
|
||||
collapsable={false}
|
||||
style={{
|
||||
borderTopWidth: index === 0 ? 0 : 1,
|
||||
}}
|
||||
className={cn(index !== 0 && "border-border")}
|
||||
>
|
||||
<ConnectionEnvironmentRow
|
||||
environment={environment}
|
||||
expanded={expandedId === environment.environmentId}
|
||||
onToggle={() => handleToggle(environment.environmentId)}
|
||||
onReconnect={onReconnectEnvironment}
|
||||
onRemove={onRemoveEnvironmentPress}
|
||||
onUpdate={onUpdateEnvironment}
|
||||
/>
|
||||
</View>
|
||||
))}
|
||||
</View>
|
||||
) : (
|
||||
<View collapsable={false} className="items-center gap-3 rounded-[24px] bg-card px-6 py-8">
|
||||
<View className="h-12 w-12 items-center justify-center rounded-[16px] bg-subtle">
|
||||
<SymbolView
|
||||
name="point.3.connected.trianglepath.dotted"
|
||||
size={20}
|
||||
tintColor={accentColor}
|
||||
type="monochrome"
|
||||
/>
|
||||
</View>
|
||||
<Text className="text-center text-[14px] leading-[20px] text-foreground-muted">
|
||||
No environments connected yet.{"\n"}Tap{" "}
|
||||
<Text className="font-t3-bold text-foreground">+</Text> to add one.
|
||||
</Text>
|
||||
</View>
|
||||
)}
|
||||
|
||||
{isSignedIn ? (
|
||||
<View collapsable={false} className="mt-5 gap-3">
|
||||
<View className="flex-row items-center justify-between px-1">
|
||||
<Text className="text-[13px] font-t3-bold uppercase text-foreground-muted">
|
||||
T3 Cloud
|
||||
</Text>
|
||||
<Pressable
|
||||
accessibilityRole="button"
|
||||
disabled={cloudStatus === "loading"}
|
||||
onPress={refreshCloudEnvironments}
|
||||
className="h-9 w-9 items-center justify-center rounded-full bg-subtle active:opacity-70 disabled:opacity-50"
|
||||
>
|
||||
{cloudStatus === "loading" ? (
|
||||
<ActivityIndicator color={iconColor} size="small" />
|
||||
) : (
|
||||
<SymbolView
|
||||
name="arrow.clockwise"
|
||||
size={14}
|
||||
tintColor={iconColor}
|
||||
type="monochrome"
|
||||
/>
|
||||
)}
|
||||
</Pressable>
|
||||
</View>
|
||||
|
||||
{availableCloudEnvironments.length > 0 ? (
|
||||
<View collapsable={false} className="overflow-hidden rounded-[24px] bg-card">
|
||||
{availableCloudEnvironments.map((record, index) => (
|
||||
<CloudEnvironmentRow
|
||||
key={record.environment.environmentId}
|
||||
record={record}
|
||||
borderTop={index !== 0}
|
||||
isConnecting={connectingCloudEnvironmentId === record.environment.environmentId}
|
||||
onConnect={() => handleConnectCloudEnvironment(record)}
|
||||
/>
|
||||
))}
|
||||
</View>
|
||||
) : cloudStatus === "loading" ? (
|
||||
<View
|
||||
collapsable={false}
|
||||
className="items-center gap-3 rounded-[24px] bg-card px-6 py-6"
|
||||
>
|
||||
<ActivityIndicator color={iconColor} />
|
||||
<Text className="text-center text-[14px] leading-[20px] text-foreground-muted">
|
||||
Loading linked cloud environments.
|
||||
</Text>
|
||||
</View>
|
||||
) : cloudStatus === "error" ? (
|
||||
<View collapsable={false} className="gap-3 rounded-[24px] bg-card px-5 py-5">
|
||||
<Text className="text-[15px] font-t3-bold text-foreground">
|
||||
Could not load T3 Cloud environments
|
||||
</Text>
|
||||
<Text className="text-[13px] leading-[18px] text-foreground-muted">
|
||||
{cloudError}
|
||||
</Text>
|
||||
</View>
|
||||
) : (
|
||||
<View collapsable={false} className="rounded-[24px] bg-card px-5 py-5">
|
||||
<Text className="text-[14px] leading-[20px] text-foreground-muted">
|
||||
No additional linked cloud environments.
|
||||
</Text>
|
||||
</View>
|
||||
)}
|
||||
</View>
|
||||
) : null}
|
||||
</ScrollView>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
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 (
|
||||
<View
|
||||
collapsable={false}
|
||||
className={cn(
|
||||
"flex-row items-center gap-3 bg-card px-4 py-3.5",
|
||||
props.borderTop && "border-t border-border",
|
||||
)}
|
||||
>
|
||||
<View className="h-9 w-9 items-center justify-center rounded-[14px] bg-subtle">
|
||||
<SymbolView
|
||||
name="cloud"
|
||||
size={17}
|
||||
tintColor={mutedColor}
|
||||
type="monochrome"
|
||||
weight="semibold"
|
||||
/>
|
||||
</View>
|
||||
<View className="min-w-0 flex-1 gap-0.5">
|
||||
<Text className="text-[16px] font-t3-bold leading-[21px] text-foreground" numberOfLines={1}>
|
||||
{environment.label}
|
||||
</Text>
|
||||
<Text className="text-[12px] leading-[16px] text-foreground-muted" numberOfLines={1}>
|
||||
{environment.endpoint.httpBaseUrl}
|
||||
</Text>
|
||||
<Text className="text-[12px] leading-[16px] text-foreground-muted" numberOfLines={1}>
|
||||
{statusText}
|
||||
</Text>
|
||||
</View>
|
||||
<Pressable
|
||||
accessibilityRole="button"
|
||||
disabled={disabled}
|
||||
onPress={props.onConnect}
|
||||
className="min-h-[40px] min-w-[88px] items-center justify-center rounded-[14px] bg-primary px-4 active:opacity-70 disabled:opacity-50"
|
||||
>
|
||||
<Text className="text-[13px] font-t3-bold text-primary-foreground">
|
||||
{props.isConnecting ? "Connecting" : "Connect"}
|
||||
</Text>
|
||||
</Pressable>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
@@ -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<NotificationStatus>("checking");
|
||||
const [liveActivityStatus, setLiveActivityStatus] = useState<LiveActivityStatus>("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 (
|
||||
<View collapsable={false} className="flex-1 bg-sheet">
|
||||
<Stack.Screen options={{ title: "Settings" }} />
|
||||
<ScrollView
|
||||
contentInsetAdjustmentBehavior="automatic"
|
||||
showsVerticalScrollIndicator={false}
|
||||
style={{ flex: 1 }}
|
||||
contentContainerStyle={{
|
||||
gap: 24,
|
||||
paddingBottom: Math.max(insets.bottom, 18) + 18,
|
||||
paddingHorizontal: 20,
|
||||
paddingTop: 16,
|
||||
}}
|
||||
>
|
||||
<View className="gap-3">
|
||||
<SettingsSection title="Account">
|
||||
<SettingsRow
|
||||
icon="person.crop.circle"
|
||||
label="T3 Account"
|
||||
value={accountLabel}
|
||||
onPress={openAccount}
|
||||
/>
|
||||
</SettingsSection>
|
||||
<Text className="px-2 text-[13px] leading-[18px] text-foreground-muted">
|
||||
T3 Code works locally without signing in. Cloud features are optional.
|
||||
</Text>
|
||||
</View>
|
||||
|
||||
<SettingsSection title="Configuration">
|
||||
<SettingsRow
|
||||
icon="desktopcomputer"
|
||||
label="Environments"
|
||||
value={`${environmentCount}`}
|
||||
href="/settings/environments"
|
||||
/>
|
||||
<SettingsSwitchRow
|
||||
icon="bell.badge"
|
||||
label="Device Notifications"
|
||||
disabled={notificationStatus === "checking" || notificationStatus === "unsupported"}
|
||||
value={notificationStatus === "enabled"}
|
||||
onValueChange={handleDeviceNotificationsChange}
|
||||
/>
|
||||
<SettingsSwitchRow
|
||||
disabled={
|
||||
!isLoaded || liveActivityStatus === "checking" || liveActivityStatus === "linking"
|
||||
}
|
||||
icon="bolt.circle"
|
||||
label="Live Activity Updates"
|
||||
value={liveActivityStatus === "enabled" || liveActivityStatus === "linking"}
|
||||
onValueChange={handleLiveActivitiesChange}
|
||||
/>
|
||||
</SettingsSection>
|
||||
|
||||
<SettingsSection title="App">
|
||||
<View className="flex-row items-center gap-4 px-4 py-4">
|
||||
<SymbolView
|
||||
name="info.circle"
|
||||
size={22}
|
||||
tintColor={icon}
|
||||
type="monochrome"
|
||||
weight="regular"
|
||||
/>
|
||||
<Text className="flex-1 text-[17px] text-foreground">Version</Text>
|
||||
<Text className="text-[17px] text-foreground-muted">Alpha</Text>
|
||||
</View>
|
||||
</SettingsSection>
|
||||
</ScrollView>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
type SymbolName = ComponentProps<typeof SymbolView>["name"];
|
||||
|
||||
function SettingsSection(props: { readonly title: string; readonly children: ReactNode }) {
|
||||
return (
|
||||
<View className="gap-2">
|
||||
<Text className="px-2 font-t3-bold text-[17px] text-foreground-tertiary">{props.title}</Text>
|
||||
<View
|
||||
className="overflow-hidden rounded-[28px] bg-card"
|
||||
style={{ borderCurve: "continuous" }}
|
||||
>
|
||||
{props.children}
|
||||
</View>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
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 = (
|
||||
<View
|
||||
className="flex-row items-center gap-4 px-4 py-4"
|
||||
style={{ opacity: props.disabled ? 0.45 : 1 }}
|
||||
>
|
||||
<SymbolView name={props.icon} size={22} tintColor={icon} type="monochrome" weight="regular" />
|
||||
<Text className="flex-1 text-[17px] text-foreground">{props.label}</Text>
|
||||
{props.value ? (
|
||||
<Text
|
||||
className="max-w-[180px] text-right text-[16px] text-foreground-muted"
|
||||
numberOfLines={1}
|
||||
>
|
||||
{props.value}
|
||||
</Text>
|
||||
) : null}
|
||||
<SymbolView
|
||||
name="chevron.right"
|
||||
size={16}
|
||||
tintColor={chevron}
|
||||
type="monochrome"
|
||||
weight="semibold"
|
||||
/>
|
||||
</View>
|
||||
);
|
||||
|
||||
if (props.href) {
|
||||
return (
|
||||
<Link href={props.href} asChild>
|
||||
<Pressable>{content}</Pressable>
|
||||
</Link>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<Pressable accessibilityRole="button" disabled={props.disabled} onPress={props.onPress}>
|
||||
{content}
|
||||
</Pressable>
|
||||
);
|
||||
}
|
||||
|
||||
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 (
|
||||
<View
|
||||
className="flex-row items-center gap-4 px-4 py-4"
|
||||
style={{ opacity: props.disabled ? 0.45 : 1 }}
|
||||
>
|
||||
<SymbolView name={props.icon} size={22} tintColor={icon} type="monochrome" weight="regular" />
|
||||
<Text className="flex-1 text-[17px] text-foreground">{props.label}</Text>
|
||||
<Switch
|
||||
disabled={props.disabled}
|
||||
ios_backgroundColor={track}
|
||||
onValueChange={props.onValueChange}
|
||||
trackColor={{ false: track, true: activeTrack }}
|
||||
value={props.value}
|
||||
/>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
@@ -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 (
|
||||
<>
|
||||
<Stack.Screen options={{ title: "Join the waitlist" }} />
|
||||
<ScrollView
|
||||
automaticallyAdjustKeyboardInsets
|
||||
contentContainerStyle={{
|
||||
paddingBottom: 32,
|
||||
paddingHorizontal: 20,
|
||||
paddingTop: 12,
|
||||
}}
|
||||
contentInsetAdjustmentBehavior="automatic"
|
||||
keyboardDismissMode="interactive"
|
||||
keyboardShouldPersistTaps="handled"
|
||||
showsVerticalScrollIndicator={false}
|
||||
>
|
||||
{hasClerkConfig() ? (
|
||||
<CloudWaitlistEnrollment onSignIn={() => void presentAuth()} />
|
||||
) : (
|
||||
<View className="gap-3 px-4">
|
||||
<Text
|
||||
style={{
|
||||
color: foreground,
|
||||
fontFamily: "DMSans_700Bold",
|
||||
fontSize: 22,
|
||||
textAlign: "center",
|
||||
}}
|
||||
>
|
||||
T3 Cloud is not configured
|
||||
</Text>
|
||||
<Text
|
||||
selectable
|
||||
style={{
|
||||
color: secondaryForeground,
|
||||
fontFamily: "DMSans_400Regular",
|
||||
fontSize: 16,
|
||||
lineHeight: 22,
|
||||
textAlign: "center",
|
||||
}}
|
||||
>
|
||||
Add EXPO_PUBLIC_CLERK_PUBLISHABLE_KEY to this build to enable waitlist enrollment.
|
||||
</Text>
|
||||
</View>
|
||||
)}
|
||||
</ScrollView>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -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<boolean, unknown> => 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: <A, E>(operation: Effect.Effect<A, E>) => Effect.runPromise(operation),
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock("../../widgets/AgentActivity", () => ({
|
||||
default: {
|
||||
getInstances: mocks.getInstances,
|
||||
start: mocks.start,
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock("./remoteRegistration", () => ({
|
||||
registerLiveActivityPushToken: mocks.registerLiveActivityPushToken,
|
||||
}));
|
||||
|
||||
const runManagedRelayEffect = <A, E>(effect: Effect.Effect<A, E, ManagedRelayClient>): Promise<A> =>
|
||||
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",
|
||||
},
|
||||
],
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -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<AgentActivityProps>;
|
||||
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<EnvironmentId, ReadonlyArray<AgentAwarenessState>>();
|
||||
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<AgentAwarenessState>): AgentActivityProps {
|
||||
const updatedAt = states.reduce<string | null>((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<AgentAwarenessState> {
|
||||
const projectsById = new Map<string, OrchestrationProjectShell>(
|
||||
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<void, unknown> {
|
||||
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<void, unknown> {
|
||||
return enqueueLiveActivitySync(endEnvironmentLiveActivitiesNow(environmentId));
|
||||
}
|
||||
|
||||
function endEnvironmentLiveActivitiesNow(
|
||||
environmentId: EnvironmentId,
|
||||
): Effect.Effect<void, unknown> {
|
||||
return Effect.gen(function* () {
|
||||
environmentStates.delete(environmentId);
|
||||
return yield* syncAgentLiveActivities();
|
||||
});
|
||||
}
|
||||
|
||||
export function endAllAgentLiveActivities(): Effect.Effect<void, unknown> {
|
||||
return enqueueLiveActivitySync(endAllAgentLiveActivitiesNow());
|
||||
}
|
||||
|
||||
function endAllAgentLiveActivitiesNow(): Effect.Effect<void, unknown> {
|
||||
return Effect.gen(function* () {
|
||||
environmentStates.clear();
|
||||
return yield* endActiveActivity(null, "all-ended");
|
||||
});
|
||||
}
|
||||
|
||||
function enqueueLiveActivitySync<T, R>(
|
||||
operation: Effect.Effect<T, unknown, R>,
|
||||
): Effect.Effect<T, unknown, R> {
|
||||
return liveActivitySyncSemaphore.withPermits(1)(operation);
|
||||
}
|
||||
|
||||
function syncAgentLiveActivities(): Effect.Effect<void, unknown> {
|
||||
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<AgentAwarenessState>,
|
||||
): Effect.Effect<void, unknown> {
|
||||
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<boolean, unknown> {
|
||||
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<AgentActivityProps>): 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<AgentActivityProps>,
|
||||
): Effect.Effect<boolean, unknown, ManagedRelayClient> {
|
||||
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<AgentActivityProps>): 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<void, unknown> {
|
||||
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<T> =
|
||||
| {
|
||||
readonly ok: true;
|
||||
readonly value: T;
|
||||
}
|
||||
| {
|
||||
readonly ok: false;
|
||||
};
|
||||
|
||||
function runLiveActivityOperation<T>(
|
||||
operationName: "start" | "update" | "end",
|
||||
operation: Effect.Effect<T, unknown>,
|
||||
): Effect.Effect<LiveActivityOperationResult<T>> {
|
||||
return operation.pipe(
|
||||
Effect.match({
|
||||
onSuccess: (value) => ({ ok: true, value }) as const,
|
||||
onFailure: (error): LiveActivityOperationResult<T> => {
|
||||
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();
|
||||
}
|
||||
@@ -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 = <A, E>(
|
||||
effect: Effect.Effect<A, E, HttpClient.HttpClient | ManagedRelayClient>,
|
||||
): Promise<A> =>
|
||||
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,
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -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<SavedRemoteConnection>;
|
||||
}): Effect.Effect<void, unknown, HttpClient.HttpClient | ManagedRelayClient> {
|
||||
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" },
|
||||
);
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,106 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
extractAgentNotificationDeepLink,
|
||||
routeAgentNotificationResponseOnce,
|
||||
} from "./notificationPayload";
|
||||
|
||||
function responseWithData(data: Record<string, unknown>, 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<string>();
|
||||
const navigations: Array<string> = [];
|
||||
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"]);
|
||||
});
|
||||
});
|
||||
@@ -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<string>());
|
||||
|
||||
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]);
|
||||
}
|
||||
@@ -0,0 +1,106 @@
|
||||
function dataFromNotificationResponse(response: unknown): Record<string, unknown> | 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<string, unknown>) : 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<string>;
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -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 };
|
||||
});
|
||||
@@ -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,
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,409 @@
|
||||
/// <reference types="node" />
|
||||
|
||||
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<string, string>());
|
||||
|
||||
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: <A, E>(operation: Effect.Effect<A, E>) =>
|
||||
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 = <A, E>(effect: Effect.Effect<A, E, ManagedRelayClient>): Promise<A> =>
|
||||
Effect.runPromise(
|
||||
effect.pipe(
|
||||
Effect.provide(
|
||||
mobileManagedRelayClientLayer("https://relay.example.test").pipe(
|
||||
Layer.provide(Layer.mergeAll(FetchHttpClient.layer, mobileCryptoLayer)),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
async function waitForFetchCalls(
|
||||
fetchMock: ReturnType<typeof vi.fn>,
|
||||
count: number,
|
||||
): Promise<void> {
|
||||
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();
|
||||
});
|
||||
},
|
||||
);
|
||||
});
|
||||
@@ -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<EnvironmentId, SavedRemoteConnection>();
|
||||
const activityPushTokenListeners = new WeakSet<LiveActivity<AgentActivityProps>>();
|
||||
let pushToStartSubscription: { remove: () => void } | null = null;
|
||||
let pushTokenSubscription: { remove: () => void } | null = null;
|
||||
let relayTokenProvider: (() => Promise<string | null>) | 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<string | null>) | 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<void, unknown, ManagedRelayClient> {
|
||||
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<string | null>;
|
||||
}): Effect.Effect<void, unknown, ManagedRelayClient> {
|
||||
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<boolean, unknown, ManagedRelayClient> {
|
||||
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<unknown, unknown, ManagedRelayClient>,
|
||||
context: string,
|
||||
): void {
|
||||
void mobileRuntime.runPromise(operation).catch((error: unknown) => {
|
||||
logRegistrationError(context, error);
|
||||
});
|
||||
}
|
||||
|
||||
function registerDevice(input?: {
|
||||
readonly pushToStartToken?: string;
|
||||
readonly observedPushToken?: string;
|
||||
}): Effect.Effect<void, unknown, ManagedRelayClient> {
|
||||
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<void, unknown, ManagedRelayClient> {
|
||||
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<string | null>,
|
||||
): Effect.Effect<void, never, ManagedRelayClient> {
|
||||
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<AgentActivityProps>;
|
||||
}): Effect.Effect<boolean, unknown, ManagedRelayClient> {
|
||||
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<boolean, unknown, ManagedRelayClient> {
|
||||
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;
|
||||
});
|
||||
}
|
||||
@@ -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<EnvironmentId, () => 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);
|
||||
}
|
||||
@@ -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");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,12 @@
|
||||
const ISO_TIME_PATTERN = /^\d{4}-\d{2}-\d{2}T(?<hours>\d{2}):(?<minutes>\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}`;
|
||||
}
|
||||
@@ -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<string | null>;
|
||||
} | 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 (
|
||||
<ClerkProvider publishableKey={publishableKey} tokenCache={tokenCache}>
|
||||
<CloudAuthBridge>{props.children}</CloudAuthBridge>
|
||||
</ClerkProvider>
|
||||
);
|
||||
}
|
||||
@@ -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<string | null>(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 (
|
||||
<View style={styles.content}>
|
||||
<Text style={[styles.title, { color: colors.foreground }]}>You are on the waitlist</Text>
|
||||
<Text style={[styles.body, styles.confirmationBody, { color: colors.secondaryForeground }]}>
|
||||
We will email you when your T3 Cloud access is ready.
|
||||
</Text>
|
||||
<SignInAction onPress={props.onSignIn} />
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<View style={styles.content}>
|
||||
<Text style={[styles.body, { color: colors.secondaryForeground }]}>
|
||||
Enter your email and we will let you know when access is ready.
|
||||
</Text>
|
||||
|
||||
<View style={styles.field}>
|
||||
<Text style={[styles.label, { color: colors.secondaryForeground }]}>Email address</Text>
|
||||
<TextInput
|
||||
accessibilityLabel="Email address"
|
||||
autoCapitalize="none"
|
||||
autoComplete="email"
|
||||
autoCorrect={false}
|
||||
keyboardType="email-address"
|
||||
onChangeText={(value) => {
|
||||
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 ? (
|
||||
<Text
|
||||
accessibilityLiveRegion="polite"
|
||||
style={[styles.error, { color: colors.dangerForeground }]}
|
||||
selectable
|
||||
>
|
||||
{fieldError ?? requestError}
|
||||
</Text>
|
||||
) : null}
|
||||
</View>
|
||||
|
||||
<Pressable
|
||||
accessibilityRole="button"
|
||||
accessibilityState={{
|
||||
busy: isSubmitting,
|
||||
disabled: isSubmitting || emailAddress.trim().length === 0,
|
||||
}}
|
||||
disabled={isSubmitting || emailAddress.trim().length === 0}
|
||||
onPress={() => void joinWaitlist()}
|
||||
style={[
|
||||
styles.primaryButton,
|
||||
{
|
||||
backgroundColor: colors.primary,
|
||||
opacity: isSubmitting || emailAddress.trim().length === 0 ? 0.45 : 1,
|
||||
},
|
||||
]}
|
||||
>
|
||||
{isSubmitting ? <ActivityIndicator color={colors.primaryForeground} size="small" /> : null}
|
||||
<Text style={[styles.buttonText, { color: colors.primaryForeground }]}>
|
||||
{isSubmitting ? "Joining" : "Join the waitlist"}
|
||||
</Text>
|
||||
</Pressable>
|
||||
|
||||
<SignInAction onPress={props.onSignIn} />
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
function SignInAction(props: { readonly onPress: () => void }) {
|
||||
const colors = useCloudWaitlistColors();
|
||||
return (
|
||||
<View style={styles.signInRow}>
|
||||
<Text style={[styles.body, { color: colors.secondaryForeground }]}>Already have access?</Text>
|
||||
<Pressable accessibilityRole="button" hitSlop={8} onPress={props.onPress}>
|
||||
<Text style={[styles.signInText, { color: colors.foreground }]}>Sign in</Text>
|
||||
</Pressable>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
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",
|
||||
},
|
||||
});
|
||||
@@ -0,0 +1,166 @@
|
||||
/// <reference types="node" />
|
||||
|
||||
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<string, string>();
|
||||
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)),
|
||||
);
|
||||
});
|
||||
@@ -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<Uint8Array, CloudDpopError, Crypto.Crypto> {
|
||||
return Crypto.Crypto.pipe(
|
||||
Effect.flatMap((crypto) => crypto.digest("SHA-256", data)),
|
||||
Effect.mapError(cloudDpopError(message)),
|
||||
);
|
||||
}
|
||||
|
||||
function secureRandomBytes(
|
||||
byteCount: number,
|
||||
message: string,
|
||||
): Effect.Effect<Uint8Array, CloudDpopError, Crypto.Crypto> {
|
||||
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<string, CloudDpopError> {
|
||||
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,
|
||||
};
|
||||
});
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -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<RelayDpopAccessTokenScope>;
|
||||
|
||||
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<string, CloudEnvironmentLinkError> {
|
||||
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<void, CloudEnvironmentLinkError> {
|
||||
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<void, CloudEnvironmentLinkError> {
|
||||
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<void, CloudEnvironmentLinkError> {
|
||||
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<void, CloudEnvironmentLinkError, HttpClient.HttpClient | ManagedRelayClient> {
|
||||
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<RelayClientEnvironmentRecord>,
|
||||
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<RelayDpopAccessTokenScope>;
|
||||
}): 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<RelayClientEnvironmentRecord>,
|
||||
): ReadonlyArray<CloudEnvironmentRecordWithStatus> {
|
||||
return environments.map((environment) => ({
|
||||
environment,
|
||||
status: null,
|
||||
statusError: "Checking status...",
|
||||
}));
|
||||
}
|
||||
|
||||
export function loadCloudEnvironmentStatuses(input: {
|
||||
readonly clerkToken: string;
|
||||
readonly environments: ReadonlyArray<RelayClientEnvironmentRecord>;
|
||||
}): Effect.Effect<
|
||||
ReadonlyArray<CloudEnvironmentRecordWithStatus>,
|
||||
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<CloudEnvironmentRecordWithStatus>,
|
||||
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,
|
||||
};
|
||||
});
|
||||
}
|
||||
@@ -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),
|
||||
);
|
||||
@@ -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<string | null>;
|
||||
readonly presentAuth?: (options: {
|
||||
readonly dismissable: boolean;
|
||||
readonly mode: "signInOrUp";
|
||||
}) => Promise<NativeAuthResult | null>;
|
||||
}
|
||||
|
||||
interface NativeAuthResult {
|
||||
readonly cancelled?: boolean;
|
||||
readonly session?: {
|
||||
readonly id?: string;
|
||||
};
|
||||
readonly sessionId?: string;
|
||||
}
|
||||
|
||||
interface ClerkWithNativeSync {
|
||||
readonly __internal_reloadInitialResources?: () => Promise<void>;
|
||||
readonly setActive?: (params: { readonly session: string }) => Promise<void>;
|
||||
}
|
||||
|
||||
const NativeClerk = TurboModuleRegistry.get<NativeClerkModule>("ClerkExpo");
|
||||
|
||||
class NativeClerkAuthError extends Data.TaggedError("NativeClerkAuthError")<{
|
||||
readonly message: string;
|
||||
readonly cause?: unknown;
|
||||
}> {}
|
||||
|
||||
async function syncNativeSession(sessionId: string): Promise<void> {
|
||||
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<void> => {
|
||||
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,
|
||||
};
|
||||
}
|
||||
@@ -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" } : {}),
|
||||
};
|
||||
}
|
||||
@@ -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(),
|
||||
},
|
||||
}));
|
||||
|
||||
@@ -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<SavedRemoteConnection> {
|
||||
@@ -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",
|
||||
};
|
||||
}
|
||||
@@ -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)),
|
||||
),
|
||||
),
|
||||
);
|
||||
@@ -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<ReadonlyArray<SavedRemoteC
|
||||
|
||||
return pipe(
|
||||
parsed.connections ?? [],
|
||||
Arr.filter((c) => !!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<MobilePreferences> {
|
||||
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<string> {
|
||||
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<string | null> {
|
||||
const existing = await readStorageItem(AGENT_AWARENESS_DEVICE_ID_KEY);
|
||||
return existing?.trim() ? existing : null;
|
||||
}
|
||||
@@ -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<unknown>) {
|
||||
mocks.wsTransportConstructor(...args);
|
||||
},
|
||||
};
|
||||
});
|
||||
|
||||
vi.mock("react-native", () => ({
|
||||
Alert: {
|
||||
alert: vi.fn(),
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock("@t3tools/client-runtime", async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import("@t3tools/client-runtime")>();
|
||||
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<string, unknown, ManagedRelayDpopSigner>).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<string>)
|
||||
| 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);
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -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<T>(
|
||||
promise: Promise<T>,
|
||||
timeoutMs: number,
|
||||
timeoutMessage: string,
|
||||
): Promise<T> {
|
||||
return new Promise<T>((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<T>(tryPromise: () => Promise<T>): Effect.Effect<T, unknown> {
|
||||
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<void, unknown> {
|
||||
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<void, unknown> {
|
||||
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);
|
||||
},
|
||||
},
|
||||
],
|
||||
|
||||
@@ -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<LiveActivityComponent<AgentActivityProps>>[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<AgentActivityRowProps>;
|
||||
}
|
||||
|
||||
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: (
|
||||
<VStack modifiers={[padding({ all: 14 })]}>
|
||||
<HStack>
|
||||
<VStack>
|
||||
<Text
|
||||
modifiers={[font({ weight: "bold", size: 15 }), foregroundStyle(primaryForeground)]}
|
||||
>
|
||||
{props.title}
|
||||
</Text>
|
||||
<Text
|
||||
modifiers={[font({ size: 12 }), foregroundStyle(secondaryForeground), lineLimit(1)]}
|
||||
>
|
||||
{props.subtitle}
|
||||
</Text>
|
||||
</VStack>
|
||||
<Spacer minLength={8} />
|
||||
<Text modifiers={[font({ weight: "semibold", size: 12 }), foregroundStyle(tint)]}>
|
||||
{activeLabel}
|
||||
</Text>
|
||||
</HStack>
|
||||
{row0 ? (
|
||||
<HStack modifiers={[padding({ vertical: 4 })]}>
|
||||
<VStack>
|
||||
<Text
|
||||
modifiers={[
|
||||
font({ weight: "bold", size: 13 }),
|
||||
foregroundStyle(primaryForeground),
|
||||
lineLimit(1),
|
||||
]}
|
||||
>
|
||||
{row0.threadTitle}
|
||||
</Text>
|
||||
<Text
|
||||
modifiers={[font({ size: 11 }), foregroundStyle(secondaryForeground), lineLimit(1)]}
|
||||
>
|
||||
{row0.projectTitle} - {row0.modelTitle}
|
||||
</Text>
|
||||
</VStack>
|
||||
<Spacer minLength={8} />
|
||||
<Text modifiers={[font({ weight: "semibold", size: 11 }), foregroundStyle(tint)]}>
|
||||
{row0.status}
|
||||
</Text>
|
||||
</HStack>
|
||||
) : null}
|
||||
{row1 ? (
|
||||
<HStack modifiers={[padding({ vertical: 4 })]}>
|
||||
<VStack>
|
||||
<Text
|
||||
modifiers={[
|
||||
font({ weight: "bold", size: 13 }),
|
||||
foregroundStyle(primaryForeground),
|
||||
lineLimit(1),
|
||||
]}
|
||||
>
|
||||
{row1.threadTitle}
|
||||
</Text>
|
||||
<Text
|
||||
modifiers={[font({ size: 11 }), foregroundStyle(secondaryForeground), lineLimit(1)]}
|
||||
>
|
||||
{row1.projectTitle} - {row1.modelTitle}
|
||||
</Text>
|
||||
</VStack>
|
||||
<Spacer minLength={8} />
|
||||
<Text modifiers={[font({ weight: "semibold", size: 11 }), foregroundStyle(tint)]}>
|
||||
{row1.status}
|
||||
</Text>
|
||||
</HStack>
|
||||
) : null}
|
||||
{row2 ? (
|
||||
<HStack modifiers={[padding({ vertical: 4 })]}>
|
||||
<VStack>
|
||||
<Text
|
||||
modifiers={[
|
||||
font({ weight: "bold", size: 13 }),
|
||||
foregroundStyle(primaryForeground),
|
||||
lineLimit(1),
|
||||
]}
|
||||
>
|
||||
{row2.threadTitle}
|
||||
</Text>
|
||||
<Text
|
||||
modifiers={[font({ size: 11 }), foregroundStyle(secondaryForeground), lineLimit(1)]}
|
||||
>
|
||||
{row2.projectTitle} - {row2.modelTitle}
|
||||
</Text>
|
||||
</VStack>
|
||||
<Spacer minLength={8} />
|
||||
<Text modifiers={[font({ weight: "semibold", size: 11 }), foregroundStyle(tint)]}>
|
||||
{row2.status}
|
||||
</Text>
|
||||
</HStack>
|
||||
) : null}
|
||||
<Text modifiers={[font({ size: 11 }), foregroundStyle(mutedForeground)]}>
|
||||
Updated {updatedAt}
|
||||
</Text>
|
||||
</VStack>
|
||||
),
|
||||
bannerSmall: (
|
||||
<VStack modifiers={[padding({ all: 12 })]}>
|
||||
<HStack>
|
||||
<Text
|
||||
modifiers={[font({ weight: "bold", size: 13 }), foregroundStyle(primaryForeground)]}
|
||||
>
|
||||
{props.title}
|
||||
</Text>
|
||||
<Spacer minLength={6} />
|
||||
<Text modifiers={[font({ weight: "semibold", size: 12 }), foregroundStyle(tint)]}>
|
||||
{activeLabel}
|
||||
</Text>
|
||||
</HStack>
|
||||
{row0 ? (
|
||||
<VStack>
|
||||
<Text
|
||||
modifiers={[
|
||||
font({ weight: "bold", size: 12 }),
|
||||
foregroundStyle(primaryForeground),
|
||||
lineLimit(1),
|
||||
]}
|
||||
>
|
||||
{row0.threadTitle}
|
||||
</Text>
|
||||
<Text
|
||||
modifiers={[font({ size: 11 }), foregroundStyle(secondaryForeground), lineLimit(1)]}
|
||||
>
|
||||
{row0.projectTitle} - {row0.status}
|
||||
</Text>
|
||||
</VStack>
|
||||
) : null}
|
||||
</VStack>
|
||||
),
|
||||
compactLeading: (
|
||||
<Text modifiers={[font({ weight: "bold", size: 11 }), foregroundStyle(tint)]}>T3</Text>
|
||||
),
|
||||
compactTrailing: (
|
||||
<Text modifiers={[font({ weight: "semibold", size: 11 }), foregroundStyle(tint)]}>
|
||||
{activeLabel}
|
||||
</Text>
|
||||
),
|
||||
minimal: (
|
||||
<Text modifiers={[font({ weight: "bold", size: 11 }), foregroundStyle(tint)]}>T3</Text>
|
||||
),
|
||||
expandedLeading: (
|
||||
<VStack modifiers={[padding({ all: 8 })]}>
|
||||
<Text modifiers={[font({ weight: "bold", size: 12 }), foregroundStyle(tint)]}>
|
||||
{activeLabel}
|
||||
</Text>
|
||||
</VStack>
|
||||
),
|
||||
expandedCenter: row0 ? (
|
||||
<VStack>
|
||||
<Text
|
||||
modifiers={[
|
||||
font({ weight: "bold", size: 12 }),
|
||||
foregroundStyle(primaryForeground),
|
||||
lineLimit(1),
|
||||
]}
|
||||
>
|
||||
{row0.threadTitle}
|
||||
</Text>
|
||||
<Text modifiers={[font({ size: 11 }), foregroundStyle(secondaryForeground), lineLimit(1)]}>
|
||||
{row0.projectTitle} - {row0.status}
|
||||
</Text>
|
||||
</VStack>
|
||||
) : null,
|
||||
expandedTrailing: (
|
||||
<Text modifiers={[font({ size: 11 }), foregroundStyle(secondaryForeground)]}>
|
||||
Updated {updatedAt}
|
||||
</Text>
|
||||
),
|
||||
expandedBottom: (
|
||||
<VStack modifiers={[padding({ all: 8 })]}>
|
||||
{row0 ? (
|
||||
<HStack modifiers={[padding({ vertical: 4 })]}>
|
||||
<VStack>
|
||||
<Text
|
||||
modifiers={[
|
||||
font({ weight: "bold", size: 13 }),
|
||||
foregroundStyle(primaryForeground),
|
||||
lineLimit(1),
|
||||
]}
|
||||
>
|
||||
{row0.threadTitle}
|
||||
</Text>
|
||||
<Text
|
||||
modifiers={[font({ size: 11 }), foregroundStyle(secondaryForeground), lineLimit(1)]}
|
||||
>
|
||||
{row0.projectTitle} - {row0.modelTitle}
|
||||
</Text>
|
||||
</VStack>
|
||||
<Spacer minLength={8} />
|
||||
<Text modifiers={[font({ weight: "semibold", size: 11 }), foregroundStyle(tint)]}>
|
||||
{row0.status}
|
||||
</Text>
|
||||
</HStack>
|
||||
) : null}
|
||||
{row1 ? (
|
||||
<HStack modifiers={[padding({ vertical: 4 })]}>
|
||||
<VStack>
|
||||
<Text
|
||||
modifiers={[
|
||||
font({ weight: "bold", size: 13 }),
|
||||
foregroundStyle(primaryForeground),
|
||||
lineLimit(1),
|
||||
]}
|
||||
>
|
||||
{row1.threadTitle}
|
||||
</Text>
|
||||
<Text
|
||||
modifiers={[font({ size: 11 }), foregroundStyle(secondaryForeground), lineLimit(1)]}
|
||||
>
|
||||
{row1.projectTitle} - {row1.modelTitle}
|
||||
</Text>
|
||||
</VStack>
|
||||
<Spacer minLength={8} />
|
||||
<Text modifiers={[font({ weight: "semibold", size: 11 }), foregroundStyle(tint)]}>
|
||||
{row1.status}
|
||||
</Text>
|
||||
</HStack>
|
||||
) : null}
|
||||
{row2 ? (
|
||||
<HStack modifiers={[padding({ vertical: 4 })]}>
|
||||
<VStack>
|
||||
<Text
|
||||
modifiers={[
|
||||
font({ weight: "bold", size: 13 }),
|
||||
foregroundStyle(primaryForeground),
|
||||
lineLimit(1),
|
||||
]}
|
||||
>
|
||||
{row2.threadTitle}
|
||||
</Text>
|
||||
<Text
|
||||
modifiers={[font({ size: 11 }), foregroundStyle(secondaryForeground), lineLimit(1)]}
|
||||
>
|
||||
{row2.projectTitle} - {row2.modelTitle}
|
||||
</Text>
|
||||
</VStack>
|
||||
<Spacer minLength={8} />
|
||||
<Text modifiers={[font({ weight: "semibold", size: 11 }), foregroundStyle(tint)]}>
|
||||
{row2.status}
|
||||
</Text>
|
||||
</HStack>
|
||||
) : null}
|
||||
</VStack>
|
||||
),
|
||||
};
|
||||
}
|
||||
|
||||
export default createLiveActivity<AgentActivityProps>("AgentActivity", AgentActivity);
|
||||
@@ -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),
|
||||
|
||||
@@ -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<AuthEnvironmentScope>;
|
||||
readonly proofKeyThumbprint?: string;
|
||||
readonly expiresAt?: DateTime.DateTime;
|
||||
}
|
||||
|
||||
@@ -107,6 +110,9 @@ export interface EnvironmentAuthShape {
|
||||
credential: string,
|
||||
requestedScopes: ReadonlyArray<AuthEnvironmentScope> | 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<AuthEnvironmentScope>;
|
||||
readonly subject?: string;
|
||||
readonly proofKeyThumbprint?: string;
|
||||
}) => Effect.Effect<IssuedPairingLink, ServerAuthInternalError>;
|
||||
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,
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -26,6 +26,7 @@ export interface BootstrapGrant {
|
||||
readonly scopes: ReadonlyArray<AuthEnvironmentScope>;
|
||||
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<AuthEnvironmentScope>;
|
||||
readonly subject?: string;
|
||||
readonly label?: string;
|
||||
readonly proofKeyThumbprint?: string;
|
||||
}) => Effect.Effect<IssuedBootstrapCredential, BootstrapCredentialInternalError>;
|
||||
readonly listActive: () => Effect.Effect<
|
||||
ReadonlyArray<AuthPairingLink>,
|
||||
@@ -76,7 +79,12 @@ export interface PairingGrantStoreShape {
|
||||
>;
|
||||
readonly streamChanges: Stream.Stream<BootstrapCredentialChange>;
|
||||
readonly revoke: (id: string) => Effect.Effect<boolean, BootstrapCredentialInternalError>;
|
||||
readonly consume: (credential: string) => Effect.Effect<BootstrapGrant, BootstrapCredentialError>;
|
||||
readonly consume: (
|
||||
credential: string,
|
||||
input?: {
|
||||
readonly proofKeyThumbprint?: string;
|
||||
},
|
||||
) => Effect.Effect<BootstrapGrant, BootstrapCredentialError>;
|
||||
}
|
||||
|
||||
export class PairingGrantStore extends Context.Service<PairingGrantStore, PairingGrantStoreShape>()(
|
||||
@@ -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) =>
|
||||
|
||||
@@ -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<Uint8Array | null, SecretStoreError>;
|
||||
readonly set: (name: string, value: Uint8Array) => Effect.Effect<void, SecretStoreError>;
|
||||
readonly create: (name: string, value: Uint8Array) => Effect.Effect<void, SecretStoreError>;
|
||||
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;
|
||||
|
||||
@@ -40,6 +40,7 @@ export interface IssuedSession {
|
||||
readonly client: AuthClientMetadata;
|
||||
readonly expiresAt: DateTime.DateTime;
|
||||
readonly scopes: ReadonlyArray<AuthEnvironmentScope>;
|
||||
readonly proofKeyThumbprint?: string;
|
||||
}
|
||||
|
||||
export interface VerifiedSession {
|
||||
@@ -50,6 +51,7 @@ export interface VerifiedSession {
|
||||
readonly expiresAt?: DateTime.DateTime;
|
||||
readonly subject: string;
|
||||
readonly scopes: ReadonlyArray<AuthEnvironmentScope>;
|
||||
readonly proofKeyThumbprint?: string;
|
||||
}
|
||||
|
||||
export type SessionCredentialChange =
|
||||
@@ -86,6 +88,7 @@ export interface SessionStoreShape {
|
||||
readonly method?: ServerAuthSessionMethod;
|
||||
readonly scopes?: ReadonlyArray<AuthEnvironmentScope>;
|
||||
readonly client?: AuthClientMetadata;
|
||||
readonly proofKeyThumbprint?: string;
|
||||
}) => Effect.Effect<IssuedSession, SessionCredentialInternalError>;
|
||||
readonly verify: (token: string) => Effect.Effect<VerifiedSession, SessionCredentialError>;
|
||||
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) =>
|
||||
|
||||
@@ -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.");
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -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;
|
||||
});
|
||||
@@ -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) =>
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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<ChildProcessSpawner.ExitCode>;
|
||||
}) {
|
||||
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<ChildProcess.StandardCommand> = [];
|
||||
const killed: Array<number> = [];
|
||||
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<number> = [];
|
||||
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<number> = [];
|
||||
const killed: Array<number> = [];
|
||||
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<number> = [];
|
||||
const killed: Array<number> = [];
|
||||
const firstExit = yield* Deferred.make<ChildProcessSpawner.ExitCode>();
|
||||
const secondSpawned = yield* Deferred.make<void>();
|
||||
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<ChildProcessSpawner.ExitCode>),
|
||||
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",
|
||||
});
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -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<CloudManagedEndpointRuntimeStatus>;
|
||||
}
|
||||
|
||||
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<ActiveConnector | null>(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;
|
||||
}),
|
||||
);
|
||||
@@ -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),
|
||||
);
|
||||
@@ -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);
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -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<never, EnvironmentHttpInternalServerError> =>
|
||||
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<string>;
|
||||
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<void, EnvironmentHttpBadRequestError> {
|
||||
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<void, EnvironmentHttpBadRequestError> {
|
||||
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<void, EnvironmentAuth.ServerAuthInternalError | EnvironmentHttpConflictError> {
|
||||
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<string, EnvironmentAuth.ServerAuthInternalError> {
|
||||
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<string>;
|
||||
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),
|
||||
);
|
||||
}),
|
||||
);
|
||||
@@ -4,6 +4,7 @@ export const browserApiCorsAllowedHeaders = [
|
||||
"b3",
|
||||
"traceparent",
|
||||
"content-type",
|
||||
"dpop",
|
||||
] as const;
|
||||
|
||||
export const browserApiCorsHeaders = {
|
||||
|
||||
@@ -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<OrchestrationReactor, never> | 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));
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -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) =>
|
||||
|
||||
@@ -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
|
||||
`;
|
||||
}
|
||||
});
|
||||
@@ -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,
|
||||
});
|
||||
|
||||
@@ -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<string, Uint8Array>();
|
||||
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<OrchestrationThreadShell, "id">;
|
||||
|
||||
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<OrchestrationEvent>();
|
||||
const threadShellRequested = yield* Deferred.make<void>();
|
||||
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<never>();
|
||||
const runFork = Effect.runForkWith(context);
|
||||
const events = yield* Queue.unbounded<OrchestrationEvent>();
|
||||
const fetchSeen = yield* Deferred.make<URL>();
|
||||
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<typeof fetch>[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),
|
||||
),
|
||||
),
|
||||
);
|
||||
}),
|
||||
),
|
||||
);
|
||||
});
|
||||
@@ -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<void>;
|
||||
readonly start: () => Effect.Effect<void, never, Scope.Scope>;
|
||||
}
|
||||
|
||||
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<string>();
|
||||
|
||||
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<OrchestrationThreadShell>;
|
||||
readonly project: Option.Option<OrchestrationProjectShell>;
|
||||
}): {
|
||||
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<Pick<OrchestrationProjectShell, "id" | "title">>;
|
||||
readonly threads: ReadonlyArray<OrchestrationThreadShell>;
|
||||
}): ReadonlyArray<ThreadId> {
|
||||
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<ThreadId, string>());
|
||||
|
||||
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<OrchestrationProjectShell>();
|
||||
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);
|
||||
+1896
-152
File diff suppressed because it is too large.
Load diff
@@ -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),
|
||||
|
||||
@@ -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<void>();
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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" }]);
|
||||
});
|
||||
});
|
||||
@@ -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<Record<string, string>> = {
|
||||
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<string, ClerkOAuthProviderSetting>)
|
||||
.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<string>();
|
||||
return options.filter((option) => {
|
||||
if (seen.has(option.strategy)) return false;
|
||||
seen.add(option.strategy);
|
||||
return true;
|
||||
});
|
||||
}
|
||||
@@ -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<Window["__internal_ClerkUICtor"]>;
|
||||
|
||||
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>,
|
||||
) => void;
|
||||
__internal_onAfterResponse?: (
|
||||
listener: (
|
||||
request: ClerkFrontendApiRequest,
|
||||
response?: ClerkFrontendApiResponse,
|
||||
) => void | Promise<void>,
|
||||
) => void;
|
||||
__unstable__onBeforeRequest?: (
|
||||
listener: (request: ClerkFrontendApiRequest) => void | Promise<void>,
|
||||
) => void;
|
||||
__unstable__onAfterResponse?: (
|
||||
listener: (
|
||||
request: ClerkFrontendApiRequest,
|
||||
response?: ClerkFrontendApiResponse,
|
||||
) => void | Promise<void>,
|
||||
) => void;
|
||||
}
|
||||
|
||||
interface DesktopClerkProviderProps {
|
||||
readonly children: React.ReactNode;
|
||||
readonly publishableKey: string;
|
||||
}
|
||||
|
||||
let desktopClerk: Clerk | null = null;
|
||||
let desktopClerkFetchInstalled = false;
|
||||
let desktopClerkUiLoad: Promise<DesktopClerkUiCtor> | 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<string | null> =>
|
||||
window.desktopBridge?.getCloudAuthToken() ?? Promise.resolve(null);
|
||||
|
||||
const setStoredClientJwt = (token: string): Promise<boolean> =>
|
||||
window.desktopBridge?.setCloudAuthToken(token) ?? Promise.resolve(false);
|
||||
|
||||
const clearStoredClientJwt = (): Promise<void> =>
|
||||
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<string, string> => {
|
||||
const record: Record<string, string> = {};
|
||||
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<DesktopClerkUiCtor> {
|
||||
if (window.__internal_ClerkUICtor) {
|
||||
return Promise.resolve(window.__internal_ClerkUICtor);
|
||||
}
|
||||
if (desktopClerkUiLoad) {
|
||||
return desktopClerkUiLoad;
|
||||
}
|
||||
|
||||
const load = new Promise<DesktopClerkUiCtor>((resolve, reject) => {
|
||||
const scriptUrl = clerkUIScriptUrl({ publishableKey });
|
||||
const existingScript = document.querySelector<HTMLScriptElement>(
|
||||
"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<DesktopClerkUiCtor | undefined>(
|
||||
() => window.__internal_ClerkUICtor,
|
||||
);
|
||||
const [clerkUiError, setClerkUiError] = useState<unknown>(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 (
|
||||
<InternalClerkProvider
|
||||
key={publishableKey}
|
||||
publishableKey={publishableKey}
|
||||
Clerk={clerk as ClerkProviderProps["Clerk"]}
|
||||
ui={{ ClerkUI: clerkUiCtor }}
|
||||
standardBrowser={false}
|
||||
>
|
||||
{children}
|
||||
</InternalClerkProvider>
|
||||
);
|
||||
}
|
||||
@@ -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 });
|
||||
});
|
||||
});
|
||||
Loaded 100 of 212 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user