feat(analytics): report connected client platforms (#8481)

This commit is contained in:
Theo Browne authored and GitHub committed 2026-08-28 01:43:20 -07:00
1 parent 49f6241dde
commit 88be5631ff
29 files changed
+1005 -60

No files matched your search

+4 -4
View File
@@ -6,6 +6,9 @@ on:
branches:
- main
permissions:
contents: read
concurrency:
group: ci-${{ github.event.pull_request.number || github.sha }}
cancel-in-progress: ${{ github.event_name == 'pull_request' }}
@@ -52,10 +55,7 @@ jobs:
run: vp run build:desktop
- name: Verify preload bundle output
run: |
test -f apps/desktop/dist-electron/preload.cjs
grep -nE "desktopBridge|getLocalEnvironmentBootstrap|PICK_FOLDER_CHANNEL|wsUrl" apps/desktop/dist-electron/preload.cjs
grep -n "__clerk_internal_electron_passkeys" apps/desktop/dist-electron/preload.cjs
run: node apps/desktop/scripts/verify-preload-bundle.mjs
# Everything except `t3` (apps/server). `--parallel` drops the package
# dependency ordering that `vp run` applies by default: these `test` tasks
+1
View File
@@ -30,6 +30,7 @@
"devDependencies": {
"@effect/vitest": "catalog:",
"@types/node": "catalog:",
"acorn": "8.16.0",
"cross-env": "^10.1.0",
"electron-builder": "26.15.6",
"tailwindcss": "^4.0.0",
@@ -0,0 +1,147 @@
import * as NodeEvents from "node:events";
import * as NodeFS from "node:fs";
import * as NodeFSP from "node:fs/promises";
import * as NodeTimers from "node:timers";
import * as NodeURL from "node:url";
import * as NodeVM from "node:vm";
import { parse } from "acorn";
const expectedDesktopBridgeApis = [
"getClientPlatform",
"getLocalEnvironmentBootstraps",
"pickFolder",
];
const clerkPasskeysGlobal = "__clerk_internal_electron_passkeys";
const preloadExecutionTimeoutMs = 1_000;
const desktopPackage = JSON.parse(
NodeFS.readFileSync(new URL("../package.json", import.meta.url), "utf8"),
);
const electronVersion = desktopPackage.dependencies.electron;
const isSyntaxNode = (value) =>
typeof value === "object" && value !== null && "type" in value && typeof value.type === "string";
const inspectBundle = (source) => {
const runtimeImports = [];
const visit = (node) => {
if (node.type === "ImportExpression") {
throw new Error("Desktop preload bundle contains a dynamic import() call");
}
if (node.type === "CallExpression" && node.callee.type === "Identifier") {
if (node.callee.name === "require") {
const [argument] = node.arguments;
if (node.arguments.length !== 1 || argument?.type !== "Literal") {
throw new Error("Desktop preload bundle contains a dynamic require() call");
}
if (typeof argument.value !== "string") {
throw new Error("Desktop preload bundle contains a dynamic require() call");
}
runtimeImports.push(argument.value);
}
}
for (const child of Object.values(node)) {
if (Array.isArray(child)) {
for (const item of child) {
if (isSyntaxNode(item)) visit(item);
}
} else if (isSyntaxNode(child)) {
visit(child);
}
}
};
visit(parse(source, { ecmaVersion: "latest", sourceType: "script" }));
return runtimeImports;
};
const createSandboxModules = (exposedGlobals) => {
const ipcRenderer = {
invoke: () => Promise.resolve(undefined),
on: () => undefined,
removeListener: () => undefined,
sendSync: () => undefined,
};
const electron = {
contextBridge: {
exposeInMainWorld: (name, api) => exposedGlobals.set(name, api),
},
ipcRenderer,
};
return new Map([
["electron", electron],
["electron/common", electron],
["electron/renderer", electron],
["events", NodeEvents.default],
["node:events", NodeEvents.default],
["timers", NodeTimers.default],
["node:timers", NodeTimers.default],
["url", NodeURL.default],
["node:url", NodeURL.default],
]);
};
const executeBundle = (source, sandboxModules) => {
const sandboxProcess = {
contextIsolated: true,
// oxlint-disable-next-line t3code/no-global-process-runtime -- This standalone CI verifier supplies the preload's host platform without loading Effect.
platform: process.platform,
versions: { electron: electronVersion },
};
const requireSandboxModule = (moduleName) => {
if (!sandboxModules.has(moduleName)) {
throw new Error(
`Unsupported sandbox module requested during preload execution: ${moduleName}`,
);
}
return sandboxModules.get(moduleName);
};
NodeVM.runInNewContext(
source,
{
process: sandboxProcess,
require: requireSandboxModule,
},
{
filename: "desktop-preload.cjs",
timeout: preloadExecutionTimeoutMs,
},
);
};
export const verifyPreloadBundle = (source) => {
const runtimeImports = inspectBundle(source);
const exposedGlobals = new Map();
const sandboxModules = createSandboxModules(exposedGlobals);
const unsupportedImports = [...new Set(runtimeImports)]
.filter((moduleName) => !sandboxModules.has(moduleName))
.toSorted();
if (unsupportedImports.length > 0) {
throw new Error(
`Desktop preload bundle contains unsupported sandbox imports: ${unsupportedImports.join(", ")}`,
);
}
executeBundle(source, sandboxModules);
const desktopBridge = exposedGlobals.get("desktopBridge");
const missingApis = expectedDesktopBridgeApis.filter(
(api) => typeof desktopBridge?.[api] !== "function",
);
if (!exposedGlobals.has("desktopBridge")) missingApis.unshift("desktopBridge exposure");
if (!exposedGlobals.has(clerkPasskeysGlobal)) missingApis.push(`${clerkPasskeysGlobal} exposure`);
if (missingApis.length > 0) {
throw new Error(`Desktop preload bundle is missing executable APIs: ${missingApis.join(", ")}`);
}
};
if (process.argv[1] && NodeURL.pathToFileURL(process.argv[1]).href === import.meta.url) {
const preloadUrl = new URL("../dist-electron/preload.cjs", import.meta.url);
const source = await NodeFSP.readFile(preloadUrl, "utf8");
verifyPreloadBundle(source);
}
@@ -0,0 +1,104 @@
import { assert, describe, it } from "vite-plus/test";
import { verifyPreloadBundle } from "./verify-preload-bundle.mjs";
const validPreload = `
const electron = require("electron");
const PICK_FOLDER_CHANNEL = "desktop:pick-folder";
electron.contextBridge.exposeInMainWorld("__clerk_internal_electron_passkeys", {});
electron.contextBridge.exposeInMainWorld("desktopBridge", {
getClientPlatform: () => process.platform,
getLocalEnvironmentBootstraps: () => [],
pickFolder: (options) => electron.ipcRenderer.invoke(PICK_FOLDER_CHANNEL, options),
});
`;
describe("desktop preload bundle verifier", () => {
it("rejects required API names that only appear in strings", () => {
assert.throws(
() =>
verifyPreloadBundle(`
"desktopBridge getClientPlatform getLocalEnvironmentBootstraps pickFolder";
"__clerk_internal_electron_passkeys";
require("electron");
`),
/missing executable APIs/,
);
});
it("rejects a required API whose exposed value is not callable", () => {
assert.throws(
() =>
verifyPreloadBundle(
validPreload.replace(
"getClientPlatform: () => process.platform,",
"getClientPlatform: undefined,",
),
),
/missing executable APIs: getClientPlatform/,
);
});
it("accepts a required API exposed through a function alias", () => {
assert.doesNotThrow(() =>
verifyPreloadBundle(`
const readClientPlatform = () => process.platform;
${validPreload.replace(
"getClientPlatform: () => process.platform,",
"getClientPlatform: readClientPlatform,",
)}
`),
);
});
it("rejects dynamic imports with comments before the opening parenthesis", () => {
assert.throws(
() =>
verifyPreloadBundle(`${validPreload}\nimport /* @vite-ignore */("unsupported-module");`),
/dynamic import\(\)/,
);
});
it("ignores import-like text in strings", () => {
assert.doesNotThrow(() =>
verifyPreloadBundle(`${validPreload}\nconst message = 'import /* comment */("module")';`),
);
});
it("rejects unsupported require calls with comments before the opening parenthesis", () => {
assert.throws(
() => verifyPreloadBundle(`${validPreload}\nrequire /* @__PURE__ */ ("node:fs");`),
/unsupported sandbox imports: node:fs/,
);
});
it("rejects unsupported optional require calls", () => {
assert.throws(
() => verifyPreloadBundle(`${validPreload}\nrequire?.("node:fs");`),
/unsupported sandbox imports: node:fs/,
);
});
it("accepts Electron sandbox module aliases", () => {
assert.doesNotThrow(() =>
verifyPreloadBundle(`
${validPreload}
require("electron/common");
require("electron/renderer");
require("node:events");
require("node:timers");
require("node:url");
`),
);
});
it("ignores require-like text in strings and comments", () => {
assert.doesNotThrow(() =>
verifyPreloadBundle(`
${validPreload}
const message = 'require("node:fs")';
// require("node:path")
`),
);
});
});
+4
View File
@@ -11,6 +11,9 @@ import * as IpcChannels from "./ipc/channels.ts";
exposeClerkBridge({ passkeys: true });
// oxlint-disable-next-line t3code/no-global-process-runtime -- Electron exposes the client platform in its sandboxed preload process.
const clientPlatform = process.platform;
function unwrapEnsureSshEnvironmentResult(result: unknown) {
if (
typeof result === "object" &&
@@ -35,6 +38,7 @@ contextBridge.exposeInMainWorld("desktopBridge", {
}
return result as ReturnType<DesktopBridge["getAppBranding"]>;
},
getClientPlatform: () => clientPlatform,
getSystemLocale: () => {
const result = ipcRenderer.sendSync(IpcChannels.GET_SYSTEM_LOCALE_CHANNEL);
return typeof result === "string" ? result : null;
@@ -34,6 +34,14 @@ vi.mock("expo-constants", () => ({
}));
vi.mock("expo-device", () => ({
deviceType: 1,
DeviceType: {
UNKNOWN: 0,
PHONE: 1,
TABLET: 2,
DESKTOP: 3,
TV: 4,
},
osVersion: "18.4.1",
modelName: "iPhone 15 Pro",
}));
+6 -1
View File
@@ -8,7 +8,12 @@ export function authClientMetadata(appVersion?: string): AuthClientPresentationM
return {
label: "T3 Code Mobile",
deviceType: "mobile",
deviceType:
Device.deviceType === Device.DeviceType.TABLET
? "tablet"
: Device.deviceType === Device.DeviceType.PHONE
? "mobile"
: "unknown",
...(Platform.OS === "ios" ? { os: "iOS" } : Platform.OS === "android" ? { os: "Android" } : {}),
...(Number.isFinite(osMajorVersion) && osMajorVersion > 0 ? { osMajorVersion } : {}),
...(deviceModel ? { deviceModel } : {}),
+20
View File
@@ -10,6 +10,14 @@ import { authClientMetadata } from "./authClientMetadata";
const mobilePlatform = vi.hoisted(() => ({ OS: "ios" as "ios" | "android" }));
const mobileDevice = vi.hoisted(() => ({
deviceType: 1,
DeviceType: {
UNKNOWN: 0,
PHONE: 1,
TABLET: 2,
DESKTOP: 3,
TV: 4,
},
osVersion: "18.4.1",
modelName: "iPhone 15 Pro",
}));
@@ -29,6 +37,7 @@ vi.mock("expo-device", () => mobileDevice);
describe("mobile remote connection records", () => {
afterEach(() => {
mobilePlatform.OS = "ios";
mobileDevice.deviceType = mobileDevice.DeviceType.PHONE;
mobileDevice.osVersion = "18.4.1";
mobileDevice.modelName = "iPhone 15 Pro";
});
@@ -56,6 +65,17 @@ describe("mobile remote connection records", () => {
});
});
it("identifies native tablets separately from phones", () => {
mobileDevice.deviceType = mobileDevice.DeviceType.TABLET;
mobileDevice.modelName = "iPad Pro 13-inch";
expect(authClientMetadata()).toMatchObject({
deviceType: "tablet",
os: "iOS",
deviceModel: "iPad Pro 13-inch",
});
});
it("includes the mobile app version when the client provides it", () => {
expect(authClientMetadata("1.2.3")).toMatchObject({
surface: "mobile",
+131 -2
View File
@@ -5261,7 +5261,7 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
}) as const;
const wsUrl = yield* getWsServerUrl(
"/ws?clientSurface=mobile&clientAppVersion=1.2.3&clientOs=iOS&clientOsMajorVersion=18&clientDeviceModel=iPhone+15+Pro",
"/ws?clientSurface=mobile&clientAppVersion=1.2.3&clientDeviceType=phone&clientOs=iOS&clientOsMajorVersion=18&clientDeviceModel=iPhone+15+Pro&connectionMethod=relay",
);
yield* Effect.scoped(
withWsRpcClient(wsUrl, (client) =>
@@ -5298,15 +5298,144 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
{
surface: "mobile",
appVersion: "1.2.3",
clientAppVersion: "1.2.3",
clientOs: "iOS",
os: "iOS",
clientDeviceType: "phone",
osMajorVersion: 18,
clientOsMajorVersion: 18,
deviceModel: "iPhone 15 Pro",
clientDeviceModel: "iPhone 15 Pro",
connectionMethod: "relay",
},
{
surface: "mobile",
appVersion: "1.2.3",
clientAppVersion: "1.2.3",
clientOs: "iOS",
os: "iOS",
clientDeviceType: "phone",
osMajorVersion: 18,
clientOsMajorVersion: 18,
deviceModel: "iPhone 15 Pro",
clientDeviceModel: "iPhone 15 Pro",
connectionMethod: "relay",
},
{ surface: "mobile", appVersion: "1.2.3" },
]);
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
);
it.effect("keeps telemetry separate for simultaneous clients", () =>
Effect.gen(function* () {
const analyticsEvents: Array<{
event: string;
properties: Readonly<Record<string, unknown>> | undefined;
}> = [];
yield* buildAppUnderTest({
layers: {
analyticsService: {
record: (event, properties) =>
Effect.sync(() => analyticsEvents.push({ event, properties })),
},
orchestrationEngine: {
dispatch: () => Effect.succeed({ sequence: 1 }),
},
},
});
const webUrl = yield* getWsServerUrl(
"/ws?clientSurface=web&clientAppVersion=2.0.0&clientDeviceType=desktop&clientOs=Windows&clientWebDeployment=hosted&clientBrowser=Chrome&connectionMethod=direct",
);
const mobileUrl = yield* getWsServerUrl(
"/ws?clientSurface=mobile&clientAppVersion=3.0.0&clientDeviceType=tablet&clientOs=Android&clientOsMajorVersion=15&clientDeviceModel=Pixel+Tablet&connectionMethod=relay",
);
const turnCommand = (client: string) => ({
type: "thread.turn.start" as const,
commandId: CommandId.make(`cmd-${client}-turn`),
threadId: ThreadId.make(`thread-${client}`),
message: {
messageId: MessageId.make(`message-${client}`),
role: "user" as const,
text: "hello",
attachments: [],
},
modelSelection: defaultModelSelection,
runtimeMode: "full-access" as const,
interactionMode: "default" as const,
createdAt: "2026-01-01T00:00:00.000Z",
});
yield* Effect.scoped(
withWsRpcClient(webUrl, (webClient) =>
withWsRpcClient(mobileUrl, (mobileClient) =>
Effect.gen(function* () {
yield* mobileClient[ORCHESTRATION_WS_METHODS.dispatchCommand](turnCommand("mobile"));
yield* webClient[ORCHESTRATION_WS_METHODS.dispatchCommand](turnCommand("web"));
}),
),
),
);
assert.deepEqual(
analyticsEvents
.filter(({ event }) => event === "client.turn.requested")
.map(({ properties }) => properties),
[
{
surface: "mobile",
appVersion: "3.0.0",
clientAppVersion: "3.0.0",
clientOs: "Android",
os: "Android",
clientDeviceType: "tablet",
osMajorVersion: 15,
clientOsMajorVersion: 15,
deviceModel: "Pixel Tablet",
clientDeviceModel: "Pixel Tablet",
connectionMethod: "relay",
},
{
surface: "web",
appVersion: "2.0.0",
clientAppVersion: "2.0.0",
clientOs: "Windows",
clientDeviceType: "desktop",
webDeployment: "hosted",
clientBrowser: "Chrome",
connectionMethod: "direct",
},
],
);
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
);
it.effect("ignores invalid client telemetry without rejecting the connection", () =>
Effect.gen(function* () {
const connectedProperties: Array<Readonly<Record<string, unknown>> | undefined> = [];
yield* buildAppUnderTest({
layers: {
analyticsService: {
record: (event, properties) =>
event === "client.connected"
? Effect.sync(() => connectedProperties.push(properties))
: Effect.void,
},
},
});
const invalidUrl = yield* getWsServerUrl(
"/ws?clientSurface=watch&clientDeviceType=television&clientOs=Plan9&clientWebDeployment=cdn&clientBrowser=&clientOsMajorVersion=-1&connectionMethod=teleport",
);
yield* Effect.scoped(
withWsRpcClient(invalidUrl, (client) => client[WS_METHODS.serverGetSettings]({})),
);
assert.deepEqual(connectedProperties, [{}]);
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
);
it.effect("routes websocket rpc projects.writeFile errors", () =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
@@ -7,6 +7,7 @@ import * as Layer from "effect/Layer";
import * as HttpServer from "effect/unstable/http/HttpServer";
import * as HttpServerRequest from "effect/unstable/http/HttpServerRequest";
import * as HttpServerResponse from "effect/unstable/http/HttpServerResponse";
import { HostProcessArchitecture, HostProcessPlatform } from "@t3tools/shared/hostProcess";
import * as ServerConfig from "../config.ts";
import { getTelemetryIdentifier } from "./Identify.ts";
@@ -20,6 +21,11 @@ interface RecordedBatchRequest {
readonly properties?: {
readonly index?: number;
readonly clientType?: string;
readonly serverOs?: string;
readonly serverArch?: string;
readonly serverAppVersion?: string;
readonly serverMode?: string;
readonly t3CodeVersion?: string;
};
}>;
} | null;
@@ -31,6 +37,11 @@ interface RecordedBatchBody {
readonly properties?: {
readonly index?: number;
readonly clientType?: string;
readonly serverOs?: string;
readonly serverArch?: string;
readonly serverAppVersion?: string;
readonly serverMode?: string;
readonly t3CodeVersion?: string;
};
}>;
}
@@ -71,6 +82,12 @@ it.layer(NodeServices.layer)("AnalyticsService test", (it) => {
);
const runtimeLayer = telemetryLayer.pipe(
Layer.provide(configLayer),
Layer.provide(
Layer.mergeAll(
Layer.succeed(HostProcessPlatform, "linux"),
Layer.succeed(HostProcessArchitecture, "arm64"),
),
),
Layer.provideMerge(NodeHttpServer.layerTest),
);
@@ -117,6 +134,18 @@ it.layer(NodeServices.layer)("AnalyticsService test", (it) => {
),
true,
);
assert.equal(
batchRequests.every((request) =>
request.body.batch.every(
(event) =>
event.properties?.serverOs === "Linux" &&
event.properties.serverArch === "arm64" &&
event.properties.serverAppVersion === event.properties.t3CodeVersion &&
event.properties.serverMode === "web",
),
),
true,
);
}),
);
});
@@ -7,6 +7,7 @@
* @module AnalyticsService
*/
import { HostProcessArchitecture, HostProcessPlatform } from "@t3tools/shared/hostProcess";
import type { ClientOs } from "@t3tools/contracts";
import * as Config from "effect/Config";
import * as Context from "effect/Context";
import * as DateTime from "effect/DateTime";
@@ -66,6 +67,21 @@ export class AnalyticsService extends Context.Service<
);
}
export function serverOsFromNodePlatform(platform: string): ClientOs {
switch (platform) {
case "darwin":
return "macOS";
case "win32":
return "Windows";
case "linux":
return "Linux";
case "android":
return "Android";
default:
return "other";
}
}
export const make = Effect.gen(function* () {
const telemetryConfig = yield* TelemetryEnvConfig;
const httpClient = yield* HttpClient.HttpClient;
@@ -121,6 +137,11 @@ export const make = Effect.gen(function* () {
arch: hostArchitecture,
t3CodeVersion: packageJson.version,
clientType,
serverOs: serverOsFromNodePlatform(hostPlatform),
serverArch: hostArchitecture,
serverWslDistro: Option.getOrUndefined(telemetryConfig.wslDistroName),
serverAppVersion: packageJson.version,
serverMode: serverConfig.mode,
},
timestamp: event.capturedAt,
})),
+53 -22
View File
@@ -15,7 +15,11 @@ import {
type AuthAccessStreamEvent,
type AuthEnvironmentScope,
AuthSessionId,
ClientConnectionMethod,
ClientDeviceType,
ClientOs,
ClientSurface,
ClientWebDeployment,
CommandId,
type DiscoveredLocalServerList,
EventId,
@@ -370,7 +374,12 @@ function toAuthAccessStreamEvent(
}
const isClientSurface = Schema.is(ClientSurface);
const isClientConnectionMethod = Schema.is(ClientConnectionMethod);
const isClientDeviceType = Schema.is(ClientDeviceType);
const isClientOs = Schema.is(ClientOs);
const isClientWebDeployment = Schema.is(ClientWebDeployment);
const MAX_CLIENT_APP_VERSION_LENGTH = 64;
const MAX_CLIENT_BROWSER_LENGTH = 64;
const MAX_CLIENT_DEVICE_MODEL_LENGTH = 80;
// Optional client identity announced on the /ws upgrade URL next to wsTicket.
@@ -393,36 +402,56 @@ function readClientConnectionOrigin(
};
}
const clientOriginAnalyticsProps = (origin: OrchestrationClientOrigin) => ({
...(origin.surface !== undefined ? { surface: origin.surface } : {}),
...(origin.appVersion !== undefined ? { appVersion: origin.appVersion } : {}),
});
function readMobileDeviceAnalyticsProps(request: HttpServerRequest.HttpServerRequest) {
// Client telemetry stays in this socket's RPC layer. It must not become a
// server-global "current client" because several client types can connect at once.
function readClientAnalyticsProps(request: HttpServerRequest.HttpServerRequest) {
const url = HttpServerRequest.toURL(request);
if (Option.isNone(url) || url.value.searchParams.get("clientSurface") !== "mobile") {
if (Option.isNone(url)) {
return {};
}
const surface = url.value.searchParams.get("clientSurface");
const appVersion = url.value.searchParams.get("clientAppVersion")?.trim() ?? "";
const deviceType = url.value.searchParams.get("clientDeviceType");
const os = url.value.searchParams.get("clientOs");
const webDeployment = url.value.searchParams.get("clientWebDeployment");
const browser = url.value.searchParams.get("clientBrowser")?.trim() ?? "";
const connectionMethod = url.value.searchParams.get("connectionMethod");
const rawOsMajorVersion = url.value.searchParams.get("clientOsMajorVersion") ?? "";
const osMajorVersion = Number(rawOsMajorVersion);
const deviceModel = url.value.searchParams.get("clientDeviceModel")?.trim() ?? "";
const isMobile = surface === "mobile";
const hasOsMajorVersion =
isMobile && rawOsMajorVersion !== "" && Number.isInteger(osMajorVersion) && osMajorVersion > 0;
const hasDeviceModel =
isMobile && deviceModel !== "" && deviceModel.length <= MAX_CLIENT_DEVICE_MODEL_LENGTH;
return {
...(os === "iOS" || os === "Android" ? { os } : {}),
...(rawOsMajorVersion !== "" && Number.isInteger(osMajorVersion) && osMajorVersion > 0
? { osMajorVersion }
...(isClientSurface(surface) ? { surface } : {}),
...(appVersion !== "" && appVersion.length <= MAX_CLIENT_APP_VERSION_LENGTH
? { appVersion, clientAppVersion: appVersion }
: {}),
...(deviceModel !== "" && deviceModel.length <= MAX_CLIENT_DEVICE_MODEL_LENGTH
? { deviceModel }
...(isClientOs(os)
? {
clientOs: os,
...(isMobile && (os === "iOS" || os === "Android") ? { os } : {}),
}
: {}),
...(isClientDeviceType(deviceType) ? { clientDeviceType: deviceType } : {}),
...(surface === "web" && isClientWebDeployment(webDeployment) ? { webDeployment } : {}),
...(surface === "web" && browser !== "" && browser.length <= MAX_CLIENT_BROWSER_LENGTH
? { clientBrowser: browser }
: {}),
...(hasOsMajorVersion ? { osMajorVersion, clientOsMajorVersion: osMajorVersion } : {}),
...(hasDeviceModel ? { deviceModel, clientDeviceModel: deviceModel } : {}),
...(isClientConnectionMethod(connectionMethod) ? { connectionMethod } : {}),
};
}
const makeWsRpcLayer = (
currentSession: EnvironmentAuth.AuthenticatedSession,
clientOrigin: OrchestrationClientOrigin,
clientAnalyticsProps: Readonly<Record<string, unknown>>,
previewAutomationBroker: PreviewAutomationBroker.PreviewAutomationBroker["Service"],
) =>
WsRpcGroup.toLayer(
@@ -444,18 +473,17 @@ const makeWsRpcLayer = (
command,
hasClientOrigin ? { origin: clientOrigin } : undefined,
);
const originProps = clientOriginAnalyticsProps(clientOrigin);
const recordClientCommandAnalytics = (command: OrchestrationCommand) => {
switch (command.type) {
case "thread.create":
return analytics.record("client.thread.started", originProps);
return analytics.record("client.thread.started", clientAnalyticsProps);
case "thread.turn.start":
return command.bootstrap?.createThread
? Effect.andThen(
analytics.record("client.thread.started", originProps),
analytics.record("client.turn.requested", originProps),
analytics.record("client.thread.started", clientAnalyticsProps),
analytics.record("client.turn.requested", clientAnalyticsProps),
)
: analytics.record("client.turn.requested", originProps);
: analytics.record("client.turn.requested", clientAnalyticsProps);
default:
return Effect.void;
}
@@ -2479,16 +2507,19 @@ export const websocketRpcRouteLayer = Layer.unwrap(
),
);
const clientOrigin = readClientConnectionOrigin(request);
const clientAnalyticsProps = readClientAnalyticsProps(request);
yield* sessions.recordClientConnection(session.sessionId, clientOrigin);
yield* analytics.record("client.connected", {
...clientOriginAnalyticsProps(clientOrigin),
...readMobileDeviceAnalyticsProps(request),
});
yield* analytics.record("client.connected", clientAnalyticsProps);
const rpcWebSocketHttpEffect = yield* RpcServer.toHttpEffectWebsocket(WsRpcGroup, {
disableTracing: true,
}).pipe(
Effect.provide(
makeWsRpcLayer(session, clientOrigin, previewAutomationBroker).pipe(
makeWsRpcLayer(
session,
clientOrigin,
clientAnalyticsProps,
previewAutomationBroker,
).pipe(
Layer.provideMerge(RpcSerialization.layerJson),
Layer.provide(ProviderMaintenanceRunner.layer),
Layer.provide(Layer.succeed(ServerSelfUpdate.ServerSelfUpdate, serverSelfUpdate)),
@@ -0,0 +1,90 @@
import { describe, expect, it } from "vite-plus/test";
import {
browserClientOs,
browserDeviceType,
browserFamily,
clientPresentationMetadata,
} from "./clientMetadata";
const desktopChrome = {
userAgent:
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 Chrome/140.0.0.0 Safari/537.36",
platform: "Win32",
maxTouchPoints: 0,
};
describe("client telemetry metadata", () => {
it("distinguishes hosted web from server-served web", () => {
expect(
clientPresentationMetadata({
appVersion: "1.2.3",
hosted: true,
identity: desktopChrome,
desktopBridge: undefined,
}),
).toMatchObject({
surface: "web",
webDeployment: "hosted",
deviceType: "desktop",
os: "Windows",
browser: "Chrome",
appVersion: "1.2.3",
});
expect(
clientPresentationMetadata({
appVersion: "0.0.0",
hosted: false,
identity: desktopChrome,
desktopBridge: undefined,
}),
).toMatchObject({ surface: "web", webDeployment: "server" });
});
it("identifies phone and tablet browsers", () => {
const iphone = {
userAgent:
"Mozilla/5.0 (iPhone; CPU iPhone OS 18_6 like Mac OS X) AppleWebKit/605.1.15 Version/18.6 Mobile/15E148 Safari/604.1",
platform: "iPhone",
maxTouchPoints: 5,
};
const androidTablet = {
userAgent:
"Mozilla/5.0 (Linux; Android 15; Pixel Tablet) AppleWebKit/537.36 Chrome/140.0.0.0 Safari/537.36",
platform: "Linux armv8l",
maxTouchPoints: 5,
};
const ipadosDesktopUa = {
userAgent:
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15) AppleWebKit/605.1.15 Version/18.0 Safari/605.1.15",
platform: "MacIntel",
maxTouchPoints: 5,
};
expect(browserDeviceType(iphone)).toBe("mobile");
expect(browserClientOs(iphone)).toBe("iOS");
expect(browserFamily(iphone.userAgent)).toBe("Safari");
expect(browserDeviceType(androidTablet)).toBe("tablet");
expect(browserClientOs(androidTablet)).toBe("Android");
expect(browserDeviceType(ipadosDesktopUa)).toBe("tablet");
expect(browserClientOs(ipadosDesktopUa)).toBe("iOS");
});
it("uses Electron's client platform for desktop", () => {
expect(
clientPresentationMetadata({
appVersion: "1.2.3",
hosted: false,
identity: desktopChrome,
desktopBridge: { getClientPlatform: () => "darwin" },
}),
).toEqual({
label: "T3 Code Desktop",
deviceType: "desktop",
os: "macOS",
surface: "desktop",
appVersion: "1.2.3",
});
});
});
+97
View File
@@ -0,0 +1,97 @@
import type {
AuthClientMetadataDeviceType,
AuthClientPresentationMetadata,
ClientOs,
DesktopBridge,
} from "@t3tools/contracts";
interface BrowserIdentity {
readonly userAgent: string;
readonly platform: string;
readonly maxTouchPoints: number;
}
function clientOsFromElectronPlatform(platform: string | undefined): ClientOs {
switch (platform) {
case "darwin":
return "macOS";
case "win32":
return "Windows";
case "linux":
return "Linux";
default:
return platform ? "other" : "unknown";
}
}
function isIpadosDesktopUserAgent(identity: BrowserIdentity): boolean {
return (
/macintosh/i.test(identity.userAgent) &&
/mac/i.test(identity.platform) &&
identity.maxTouchPoints > 1
);
}
export function browserClientOs(identity: BrowserIdentity): ClientOs {
const userAgent = identity.userAgent;
if (userAgent.trim() === "") return "unknown";
if (/iphone|ipad|ipod/i.test(userAgent) || isIpadosDesktopUserAgent(identity)) return "iOS";
if (/android/i.test(userAgent)) return "Android";
if (/cros/i.test(userAgent)) return "ChromeOS";
if (/windows/i.test(userAgent)) return "Windows";
if (/macintosh|mac os x/i.test(userAgent)) return "macOS";
if (/linux|x11/i.test(userAgent)) return "Linux";
return "other";
}
export function browserFamily(userAgent: string): string {
if (userAgent.trim() === "") return "unknown";
if (/edg(?:e|a|ios)?\//i.test(userAgent)) return "Edge";
if (/opr\/|opios\//i.test(userAgent)) return "Opera";
if (/samsungbrowser\//i.test(userAgent)) return "Samsung Internet";
if (/firefox\/|fxios\//i.test(userAgent)) return "Firefox";
if (/chrome\/|crios\//i.test(userAgent)) return "Chrome";
if (/safari\//i.test(userAgent)) return "Safari";
return "other";
}
export function browserDeviceType(identity: BrowserIdentity): AuthClientMetadataDeviceType {
const userAgent = identity.userAgent;
if (userAgent.trim() === "") return "unknown";
if (
/ipad|tablet|kindle|silk/i.test(userAgent) ||
(/android/i.test(userAgent) && !/mobile/i.test(userAgent)) ||
isIpadosDesktopUserAgent(identity)
) {
return "tablet";
}
if (/iphone|ipod|android.+mobile|mobile/i.test(userAgent)) return "mobile";
return "desktop";
}
export function clientPresentationMetadata(input: {
readonly appVersion: string;
readonly hosted: boolean;
readonly identity: BrowserIdentity;
readonly desktopBridge: Pick<DesktopBridge, "getClientPlatform"> | undefined;
}): AuthClientPresentationMetadata {
if (input.desktopBridge !== undefined) {
return {
label: "T3 Code Desktop",
deviceType: "desktop",
os: clientOsFromElectronPlatform(input.desktopBridge.getClientPlatform?.()),
surface: "desktop",
...(input.appVersion === "0.0.0" ? {} : { appVersion: input.appVersion }),
};
}
return {
label: "T3 Code Web",
deviceType: browserDeviceType(input.identity),
os: browserClientOs(input.identity),
surface: "web",
webDeployment: input.hosted ? "hosted" : "server",
browser: browserFamily(input.identity.userAgent),
...(input.appVersion === "0.0.0" ? {} : { appVersion: input.appVersion }),
};
}
+11 -9
View File
@@ -59,6 +59,7 @@ import {
type DesktopSecondaryBootstrapsRead,
} from "./desktopLocal";
import { connectionStorageLayer } from "./storage";
import { clientPresentationMetadata } from "./clientMetadata";
let nextObservedRpcRequestId = 0;
@@ -115,15 +116,16 @@ const wakeupsLayer = Wakeups.layer({
});
function clientMetadata() {
const desktop = window.desktopBridge !== undefined;
const platform = navigator.platform.trim();
return {
label: desktop ? "T3 Code Desktop" : "T3 Code Web",
deviceType: "desktop" as const,
...(platform === "" ? {} : { os: platform }),
surface: desktop ? ("desktop" as const) : ("web" as const),
...(APP_VERSION === "0.0.0" ? {} : { appVersion: APP_VERSION }),
};
return clientPresentationMetadata({
appVersion: APP_VERSION,
hosted: isHostedStaticApp(),
identity: {
userAgent: navigator.userAgent,
platform: navigator.platform,
maxTouchPoints: navigator.maxTouchPoints,
},
desktopBridge: window.desktopBridge,
});
}
function sshPreparationError(cause: unknown) {
+1
View File
@@ -33,6 +33,7 @@ policy in [CONTRIBUTING.md](../CONTRIBUTING.md); agent rules in [AGENTS.md](../A
- [Remote environments](./internals/remote.md)
- [Server updates](./internals/server-updates.md)
- [Resource telemetry](./internals/resource-telemetry.md)
- [Product analytics](./internals/product-analytics.md)
- [Environment auth](./internals/environment-auth.md)
- [T3 Connect](./internals/t3-connect.md)
- [CI gates](./internals/ci.md)
+2 -1
View File
@@ -8,7 +8,8 @@ and pushes to `main`:
- **Check**: `vp check` (format and lint; this repo sets `typeCheck: false` in its lint options),
then `vpr typecheck` for the workspace type check. The same job
builds the desktop pipeline (`vp run build:desktop`) and verifies the preload bundle exists and
still exports its expected symbols.
uses only imports that Electron's sandbox can load. The verifier parses imports, then executes the
trusted artifact with controlled bridge stubs to confirm that its required APIs are callable.
- **Test**: `vp run test` across the workspace.
- **Mobile Native Static Analysis**: `vp run lint:mobile` on macOS, wrapping
`scripts/mobile-native-static-check.ts`. A cheap Linux **Mobile Native Changes** job gates it:
+1
View File
@@ -134,6 +134,7 @@ already dispatch.
- [Workspace layout](./workspace-layout.md), [Glossary](./glossary.md)
- [Remote environments](./remote.md), [Server updates](./server-updates.md)
- [Resource telemetry](./resource-telemetry.md)
- [Product analytics](./product-analytics.md)
- [Scripts](./scripts.md), [CI gates](./ci.md)
[rpc]: ../../packages/contracts/src/rpc.ts
+112
View File
@@ -0,0 +1,112 @@
# Product analytics
T3 Code sends anonymous product events from the server to PostHog. The server
uses the first available hashed Codex account ID, hashed Claude user ID, or
installation-scoped anonymous ID as the distinct ID. It also keeps the
telemetry opt-out, event buffer, and batch delivery. Clients do not load the
PostHog browser SDK.
## Client events
These events use the metadata from the WebSocket connection that caused them.
The metadata is not a person property or server-global current-client value.
Two clients connected to one server can report different values at the same
time.
| Event | Description |
| ----------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------- |
| `client.connected` | The server accepted an authenticated WebSocket connection. Reconnects count again. Use this event for connection diagnostics, not active-use counts. |
| `client.thread.started` | The server accepted a command that created a thread. |
| `client.turn.requested` | The server accepted a turn request. This is the standard active-use event. |
`provider.turn.sent` stays a provider execution event. It does not receive
client metadata because a provider turn can continue after the requesting
client disconnects.
## Recommended properties
Client properties appear on the three client events when the connected client
reports them. Older clients can omit every client property.
| Property | Values and meaning |
| ---------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `surface` | Product client: `web`, `desktop`, or `mobile`. |
| `webDeployment` | Web delivery: `hosted` for the hosted app or `server` for web files served by a T3 server. Web only. This does not describe connection distance. |
| `clientOs` | `macOS`, `Windows`, `Linux`, `iOS`, `Android`, `ChromeOS`, `other`, or `unknown`. |
| `clientDeviceType` | `desktop`, `phone`, `tablet`, or `unknown`. This is separate from `surface`. |
| `clientBrowser` | Normalized browser family. Web only. Browser detection is best effort. |
| `clientAppVersion` | Version of the connected client. |
| `clientOsMajorVersion` | Client OS major version when the native client reports it. Initially mobile only. |
| `clientDeviceModel` | Hardware model when the native client reports it. Initially mobile only. This is not a user-assigned device name. |
| `connectionMethod` | `direct`, `ssh`, `relay`, or `unknown`. `direct` means that the client connected to the server endpoint without an SSH or relay connection. It does not mean both processes run on one machine. |
Server properties appear on all events, including server boot and background
events.
| Property | Values and meaning |
| ------------------ | -------------------------------------------------------------- |
| `serverOs` | Server process OS, normalized to the same names as `clientOs`. |
| `serverArch` | Server process architecture. |
| `serverWslDistro` | WSL distribution from `WSL_DISTRO_NAME`, when present. |
| `serverAppVersion` | T3 server version. |
| `serverMode` | Server runtime mode: `desktop` or `web`. |
## Legacy properties
Existing property meanings do not change:
- `clientType` describes how the server runs. It is `desktop-app` for a desktop
server and `cli-web-client` for a CLI web server. It does not describe the
connected client. Use `surface` and `webDeployment` for new reports.
- `platform`, `arch`, `wsl`, and `t3CodeVersion` describe the server. Use the
new `server*` names for new reports.
- `appVersion` describes the connected client. Use `clientAppVersion` for new
reports.
- Mobile connection events keep `os`, `osMajorVersion`, and `deviceModel`.
Use the new `client*` names for new reports.
## PostHog dashboard
Create one saved dashboard named `Client and platform usage`. Set
`client.turn.requested` as the event for active-use reports. A user can appear
in several client groups during one period, so do not add breakdown values to
calculate a total.
Save these insights:
| Insight | Configuration |
| ------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Active users, daily | Trends, `client.turn.requested`, unique users, daily interval. |
| Active users, weekly | Trends, `client.turn.requested`, unique users, weekly interval. |
| Active users, monthly | Trends, `client.turn.requested`, unique users, monthly interval. |
| Client usage | Trends, `client.turn.requested`, unique users. Save four filtered series: `surface = desktop`, `surface = mobile`, `surface = web` and `webDeployment = hosted`, and `surface = web` and `webDeployment = server`. Name them Desktop, Native mobile, Hosted web, and Server-served web. |
| Client OS, active users | Trends, `client.turn.requested`, unique users, breakdown by `clientOs`. |
| Client OS, turns | Trends, `client.turn.requested`, total events, breakdown by `clientOs`. |
| Client versus server OS | Table, `client.turn.requested`, breakdown by `clientOs` and `serverOs`. |
| Connection method, active users | Trends, `client.turn.requested`, unique users, breakdown by `connectionMethod`. |
| Connection method, turns | Trends, `client.turn.requested`, total events, breakdown by `connectionMethod`. |
| Mobile devices | Table, `client.turn.requested`, filter `surface = mobile`, breakdown by `clientOs`, `clientOsMajorVersion`, and `clientDeviceType`. |
| Client version adoption | Trends, `client.turn.requested`, unique users, breakdown by `clientAppVersion`. |
| Server version adoption | Trends, `client.turn.requested`, unique users, breakdown by `serverAppVersion`. |
| Missing metadata | Table or SQL insight that shows the percentage of `client.turn.requested` events where each of `surface`, `clientOs`, `clientDeviceType`, `clientAppVersion`, and `connectionMethod` is absent. Track `webDeployment` and `clientBrowser` only within `surface = web`. |
In PostHog Data management, use the event and property descriptions from this
document. Mark the recommended properties as verified. Keep `clientType`
visible with its legacy description so old reports remain understandable.
## Collection and release boundary
Client values are best effort. Invalid values are ignored and never reject a
connection. Browser clients use user-agent data for broad OS, browser, phone,
and tablet groups. They do not infer CPU architecture or an exact OS version
from `navigator.platform`.
This change does not collect URLs, tokens, prompts, IP addresses, or
user-assigned device names. It measures authenticated product use. It does not
measure a person who visits the hosted app without connecting to a server.
The new fields start with the first client and server release that contains
this metadata path. Historical events cannot reliably identify the client OS,
hosted web use, device type, or connection method when the old client did not
send those fields. Reports must treat missing values as pre-release or older
client data instead of backfilling them from server fields.
@@ -174,6 +174,7 @@ describe("RemoteEnvironmentAuthorization", () => {
httpBaseUrl: ENDPOINT.httpBaseUrl,
wsBaseUrl: ENDPOINT.wsBaseUrl,
bearerToken: "bearer-token",
connectionMethod: "direct",
});
return [yield* authorize(), yield* authorize()] as const;
}).pipe(Effect.provide(harness.layer));
@@ -211,6 +212,7 @@ describe("RemoteEnvironmentAuthorization", () => {
httpBaseUrl: ENDPOINT.httpBaseUrl,
wsBaseUrl: ENDPOINT.wsBaseUrl,
bearerToken: "bearer-token",
connectionMethod: "direct",
});
yield* authorize();
@@ -255,6 +257,7 @@ describe("RemoteEnvironmentAuthorization", () => {
}).pipe(Effect.provide(harness.layer));
expect(authorized.socketUrl).toContain("wsTicket=cached-ticket");
expect(authorized.socketUrl).toContain("connectionMethod=relay");
expect(yield* Ref.get(harness.bootstrapCalls)).toBe(0);
expect(harness.fetch.calls).toHaveLength(1);
expect(String(harness.fetch.calls[0]?.[0])).toBe(
@@ -7,6 +7,7 @@ import * as TestClock from "effect/testing/TestClock";
import { EnvironmentAuthInvalidError } from "@t3tools/contracts";
import {
appendClientConnectionParams,
bootstrapRemoteBearerSession,
exchangeRemoteDpopAccessToken,
fetchRemoteDpopSessionState,
@@ -209,6 +210,47 @@ describe("remote environment authorization", () => {
}),
);
it.effect("keeps OS sentinels in telemetry but out of display metadata", () =>
Effect.gen(function* () {
const tokenResponse = () =>
Response.json(
{
access_token: "bearer-token",
issued_token_type: "urn:ietf:params:oauth:token-type:access_token",
token_type: "Bearer",
expires_in: 3600,
scope: "orchestration:read",
},
{ status: 200 },
);
const fetch = recordedFetch(tokenResponse(), tokenResponse());
for (const os of ["unknown", "other"] as const) {
yield* bootstrapRemoteBearerSession({
httpBaseUrl: "https://remote.example.com/",
credential: "pairing-token",
clientMetadata: {
label: "T3 Code Web",
deviceType: "desktop",
os,
},
}).pipe(provideRemoteHttp(fetch.fetchFn));
}
for (const [, init] of fetch.calls) {
expect(String(init.body)).not.toContain("client_os=");
}
const websocketUrl = new URL("wss://remote.example.com/ws");
appendClientConnectionParams(websocketUrl, {
surface: "web",
deviceType: "desktop",
os: "unknown",
});
expect(websocketUrl.searchParams.get("clientOs")).toBe("unknown");
}),
);
it.effect("allows a client to explicitly narrow a pairing grant", () =>
Effect.gen(function* () {
const fetch = recordedFetch(
@@ -470,14 +512,16 @@ describe("remote environment authorization", () => {
clientMetadata: {
surface: "mobile",
appVersion: "1.2.3",
deviceType: "mobile",
os: "Android",
osMajorVersion: 15,
deviceModel: "Pixel 9",
},
connectionMethod: "relay",
}).pipe(provideRemoteHttp(fetch.fetchFn));
expect(url).toBe(
"wss://remote.example.com/ws?wsTicket=ws-ticket&clientSurface=mobile&clientAppVersion=1.2.3&clientOs=Android&clientOsMajorVersion=15&clientDeviceModel=Pixel+9",
"wss://remote.example.com/ws?wsTicket=ws-ticket&clientSurface=mobile&clientAppVersion=1.2.3&clientDeviceType=phone&clientOs=Android&clientOsMajorVersion=15&clientDeviceModel=Pixel+9&connectionMethod=relay",
);
}),
);
@@ -3,6 +3,7 @@ import {
type AuthClientPresentationMetadata,
AuthEnvironmentBootstrapTokenType,
AuthTokenExchangeGrantType,
type ClientConnectionMethod,
type AuthEnvironmentScope,
} from "@t3tools/contracts";
import { encodeOAuthScope } from "@t3tools/shared/oauthScope";
@@ -26,17 +27,23 @@ const DEFAULT_REMOTE_REQUEST_TIMEOUT_MS = 10_000;
const clientMetadataTokenExchangeFields = (
clientMetadata: AuthClientPresentationMetadata | undefined,
) => ({
...(clientMetadata?.label ? { client_label: clientMetadata.label } : {}),
...(clientMetadata?.deviceType ? { client_device_type: clientMetadata.deviceType } : {}),
...(clientMetadata?.os ? { client_os: clientMetadata.os } : {}),
});
) => {
const displayOs = clientMetadata?.os;
return {
...(clientMetadata?.label ? { client_label: clientMetadata.label } : {}),
...(clientMetadata?.deviceType ? { client_device_type: clientMetadata.deviceType } : {}),
...(displayOs && displayOs !== "unknown" && displayOs !== "other"
? { client_os: displayOs }
: {}),
};
};
// The server reads these off the /ws upgrade URL next to wsTicket. Optional on
// both ends: old servers ignore unknown params, old clients never send them.
export const appendClientConnectionParams = (
url: URL,
clientMetadata: AuthClientPresentationMetadata | undefined,
connectionMethod?: ClientConnectionMethod,
): void => {
if (clientMetadata?.surface) {
url.searchParams.set("clientSurface", clientMetadata.surface);
@@ -44,10 +51,27 @@ export const appendClientConnectionParams = (
if (clientMetadata?.appVersion) {
url.searchParams.set("clientAppVersion", clientMetadata.appVersion);
}
if (clientMetadata?.surface === "mobile") {
if (clientMetadata.os) {
url.searchParams.set("clientOs", clientMetadata.os);
if (clientMetadata?.deviceType) {
const deviceType =
clientMetadata.deviceType === "mobile"
? "phone"
: clientMetadata.deviceType === "desktop" || clientMetadata.deviceType === "tablet"
? clientMetadata.deviceType
: "unknown";
url.searchParams.set("clientDeviceType", deviceType);
}
if (clientMetadata?.os) {
url.searchParams.set("clientOs", clientMetadata.os);
}
if (clientMetadata?.surface === "web") {
if (clientMetadata.webDeployment) {
url.searchParams.set("clientWebDeployment", clientMetadata.webDeployment);
}
if (clientMetadata.browser) {
url.searchParams.set("clientBrowser", clientMetadata.browser);
}
}
if (clientMetadata?.surface === "mobile") {
if (clientMetadata.osMajorVersion !== undefined) {
url.searchParams.set("clientOsMajorVersion", String(clientMetadata.osMajorVersion));
}
@@ -55,6 +79,9 @@ export const appendClientConnectionParams = (
url.searchParams.set("clientDeviceModel", clientMetadata.deviceModel);
}
}
if (connectionMethod) {
url.searchParams.set("connectionMethod", connectionMethod);
}
};
export const exchangeRemoteDpopAccessToken = Effect.fn(
@@ -200,6 +227,7 @@ export const resolveRemoteWebSocketConnectionUrl = Effect.fn(
readonly httpBaseUrl: string;
readonly bearerToken: string;
readonly clientMetadata?: AuthClientPresentationMetadata;
readonly connectionMethod?: ClientConnectionMethod;
readonly timeoutMs?: number;
}) {
const issued = yield* issueRemoteWebSocketTicket({
@@ -213,7 +241,7 @@ export const resolveRemoteWebSocketConnectionUrl = Effect.fn(
url.pathname = "/ws";
}
url.searchParams.set("wsTicket", issued.ticket);
appendClientConnectionParams(url, input.clientMetadata);
appendClientConnectionParams(url, input.clientMetadata, input.connectionMethod);
return url.toString();
});
@@ -225,6 +253,7 @@ export const resolveRemoteDpopWebSocketConnectionUrl = Effect.fn(
readonly accessToken: string;
readonly dpopProof: string;
readonly clientMetadata?: AuthClientPresentationMetadata;
readonly connectionMethod?: ClientConnectionMethod;
readonly timeoutMs?: number;
}) {
const issued = yield* issueRemoteDpopWebSocketTicket({
@@ -238,6 +267,6 @@ export const resolveRemoteDpopWebSocketConnectionUrl = Effect.fn(
url.pathname = "/ws";
}
url.searchParams.set("wsTicket", issued.ticket);
appendClientConnectionParams(url, input.clientMetadata);
appendClientConnectionParams(url, input.clientMetadata, input.connectionMethod);
return url.toString();
});
@@ -1,4 +1,8 @@
import { EnvironmentId, type ExecutionEnvironmentDescriptor } from "@t3tools/contracts";
import {
type ClientConnectionMethod,
EnvironmentId,
type ExecutionEnvironmentDescriptor,
} from "@t3tools/contracts";
import type { RelayManagedEndpoint } from "@t3tools/contracts/relay";
import {
exchangeRemoteDpopAccessToken,
@@ -46,6 +50,7 @@ export class RemoteEnvironmentAuthorization extends Context.Service<
readonly httpBaseUrl: string;
readonly wsBaseUrl: string;
readonly bearerToken: string;
readonly connectionMethod: ClientConnectionMethod;
}) => Effect.Effect<AuthorizedRemoteEnvironment, ConnectionAttemptError>;
readonly authorizeDpop: (input: {
readonly expectedEnvironmentId: EnvironmentId;
@@ -99,6 +104,7 @@ export const make = Effect.gen(function* () {
readonly httpBaseUrl: string;
readonly wsBaseUrl: string;
readonly bearerToken: string;
readonly connectionMethod: ClientConnectionMethod;
}) {
const now = yield* Clock.currentTimeMillis;
const cachedDescriptor = (yield* Ref.get(bearerDescriptors)).get(input.expectedEnvironmentId);
@@ -132,6 +138,7 @@ export const make = Effect.gen(function* () {
httpBaseUrl: input.httpBaseUrl,
bearerToken: input.bearerToken,
clientMetadata: presentation.metadata,
connectionMethod: input.connectionMethod,
}).pipe(
Effect.mapError(mapRemoteEnvironmentError),
Effect.provideService(HttpClient.HttpClient, httpClient),
@@ -172,6 +179,7 @@ export const make = Effect.gen(function* () {
accessToken: token.accessToken,
dpopProof: ticketProof,
clientMetadata: presentation.metadata,
connectionMethod: "relay",
...(timeoutMs === undefined ? {} : { timeoutMs }),
}).pipe(Effect.provideService(HttpClient.HttpClient, httpClient));
},
@@ -223,7 +223,8 @@ describe("ConnectionResolver", () => {
environmentId: ENVIRONMENT_ID,
label: "Primary",
httpBaseUrl: "http://127.0.0.1:3777",
socketUrl: "ws://127.0.0.1:3777/ws?clientSurface=web",
socketUrl:
"ws://127.0.0.1:3777/ws?clientSurface=web&clientDeviceType=desktop&connectionMethod=direct",
httpAuthorization: null,
target,
});
@@ -232,11 +233,14 @@ describe("ConnectionResolver", () => {
it.effect("authorizes a desktop primary environment with its platform bearer token", () =>
Effect.gen(function* () {
const bearerInputs = yield* Ref.make<ReadonlyArray<string>>([]);
const bearerInputs = yield* Ref.make<ReadonlyArray<{ token: string; method: string }>>([]);
const brokerLayer = yield* makeDependencies({
primaryBearerToken: "desktop-bearer",
authorizeBearer: (input) =>
Ref.update(bearerInputs, (values) => [...values, input.bearerToken]).pipe(
Ref.update(bearerInputs, (values) => [
...values,
{ token: input.bearerToken, method: input.connectionMethod },
]).pipe(
Effect.as({
environmentId: input.expectedEnvironmentId,
label: "Primary",
@@ -262,13 +266,13 @@ describe("ConnectionResolver", () => {
httpAuthorization: { _tag: "Bearer", token: "desktop-bearer" },
target,
});
expect(yield* Ref.get(bearerInputs)).toEqual(["desktop-bearer"]);
expect(yield* Ref.get(bearerInputs)).toEqual([{ token: "desktop-bearer", method: "direct" }]);
}),
);
it.effect("uses the registered bearer profile without re-reading the profile store", () =>
Effect.gen(function* () {
const bearerInputs = yield* Ref.make<ReadonlyArray<string>>([]);
const bearerInputs = yield* Ref.make<ReadonlyArray<{ token: string; method: string }>>([]);
const target = new BearerConnectionTarget({
environmentId: ENVIRONMENT_ID,
label: "Saved",
@@ -284,7 +288,10 @@ describe("ConnectionResolver", () => {
const brokerLayer = yield* makeDependencies({
credentials: [["saved-1", new BearerConnectionCredential({ token: "secret-bearer" })]],
authorizeBearer: (input) =>
Ref.update(bearerInputs, (values) => [...values, input.bearerToken]).pipe(
Ref.update(bearerInputs, (values) => [
...values,
{ token: input.bearerToken, method: input.connectionMethod },
]).pipe(
Effect.as({
environmentId: input.expectedEnvironmentId,
label: "Saved",
@@ -302,7 +309,7 @@ describe("ConnectionResolver", () => {
expect(
(yield* broker.prepare(catalogEntry(target, Option.some(profile)))).socketUrl,
).toContain("wsTicket=ticket");
expect(yield* Ref.get(bearerInputs)).toEqual(["secret-bearer"]);
expect(yield* Ref.get(bearerInputs)).toEqual([{ token: "secret-bearer", method: "direct" }]);
}),
);
@@ -411,6 +418,7 @@ describe("ConnectionResolver", () => {
it.effect("delegates SSH launch to the platform gateway before remote authorization", () =>
Effect.gen(function* () {
const preparedTargets = yield* Ref.make<ReadonlyArray<DesktopSshEnvironmentTarget>>([]);
const connectionMethods = yield* Ref.make<ReadonlyArray<string>>([]);
const target = new SshConnectionTarget({
environmentId: ENVIRONMENT_ID,
label: "SSH",
@@ -435,6 +443,19 @@ describe("ConnectionResolver", () => {
bearerToken: "ssh-bearer",
}),
),
authorizeBearer: (input) =>
Ref.update(connectionMethods, (methods) => [...methods, input.connectionMethod]).pipe(
Effect.as({
environmentId: input.expectedEnvironmentId,
label: "SSH",
httpBaseUrl: input.httpBaseUrl,
socketUrl: "wss://environment.example.test/ws?wsTicket=bearer",
httpAuthorization: {
_tag: "Bearer" as const,
token: input.bearerToken,
},
}),
),
});
const broker = yield* ConnectionResolver.ConnectionResolver.pipe(Effect.provide(brokerLayer));
@@ -442,6 +463,7 @@ describe("ConnectionResolver", () => {
(yield* broker.prepare(catalogEntry(target, Option.some(profile)))).socketUrl,
).toContain("wsTicket=bearer");
expect(yield* Ref.get(preparedTargets)).toEqual([SSH_TARGET]);
expect(yield* Ref.get(connectionMethods)).toEqual(["ssh"]);
}),
);
@@ -56,7 +56,7 @@ function primarySocketUrl(
if (url.pathname === "" || url.pathname === "/") {
url.pathname = "/ws";
}
appendClientConnectionParams(url, clientMetadata);
appendClientConnectionParams(url, clientMetadata, "direct");
return url.toString();
}
@@ -85,6 +85,7 @@ const makePrimaryBroker = Effect.fn("clientRuntime.connection.broker.makePrimary
httpBaseUrl: target.httpBaseUrl,
wsBaseUrl: target.wsBaseUrl,
bearerToken: bearerToken.value,
connectionMethod: "direct",
});
return {
...authorized,
@@ -133,6 +134,7 @@ const makeBearerBroker = Effect.fn("clientRuntime.connection.broker.makeBearer")
httpBaseUrl: profile.httpBaseUrl,
wsBaseUrl: profile.wsBaseUrl,
bearerToken: credential.token,
connectionMethod: "direct",
});
return {
environmentId: authorized.environmentId,
@@ -236,6 +238,7 @@ const makeSshBroker = Effect.fn("clientRuntime.connection.broker.makeSsh")(funct
httpBaseUrl: prepared.bootstrap.httpBaseUrl,
wsBaseUrl: prepared.bootstrap.wsBaseUrl,
bearerToken: prepared.bearerToken,
connectionMethod: "ssh",
});
return {
environmentId: authorized.environmentId,
+8 -1
View File
@@ -1,7 +1,12 @@
import * as Schema from "effect/Schema";
import * as HttpApiSchema from "effect/unstable/httpapi/HttpApiSchema";
import { AuthSessionId, ClientSurface, TrimmedNonEmptyString } from "./baseSchemas.ts";
import {
AuthSessionId,
ClientSurface,
ClientWebDeployment,
TrimmedNonEmptyString,
} from "./baseSchemas.ts";
/**
* Declares the server's overall authentication posture.
@@ -172,6 +177,8 @@ export const AuthClientPresentationMetadata = Schema.Struct({
osMajorVersion: Schema.optionalKey(Schema.Int),
deviceModel: Schema.optionalKey(TrimmedNonEmptyString),
surface: Schema.optionalKey(ClientSurface),
webDeployment: Schema.optionalKey(ClientWebDeployment),
browser: Schema.optionalKey(TrimmedNonEmptyString),
appVersion: Schema.optionalKey(TrimmedNonEmptyString),
});
export type AuthClientPresentationMetadata = typeof AuthClientPresentationMetadata.Type;
+21
View File
@@ -80,6 +80,27 @@ export type RpcClientId = typeof RpcClientId.Type;
export const ClientSurface = Schema.Literals(["web", "desktop", "mobile"]);
export type ClientSurface = typeof ClientSurface.Type;
export const ClientOs = Schema.Literals([
"macOS",
"Windows",
"Linux",
"iOS",
"Android",
"ChromeOS",
"other",
"unknown",
]);
export type ClientOs = typeof ClientOs.Type;
export const ClientDeviceType = Schema.Literals(["desktop", "phone", "tablet", "unknown"]);
export type ClientDeviceType = typeof ClientDeviceType.Type;
export const ClientWebDeployment = Schema.Literals(["hosted", "server"]);
export type ClientWebDeployment = typeof ClientWebDeployment.Type;
export const ClientConnectionMethod = Schema.Literals(["direct", "ssh", "relay", "unknown"]);
export type ClientConnectionMethod = typeof ClientConnectionMethod.Type;
export const ProviderItemId = makeEntityId("ProviderItemId");
export type ProviderItemId = typeof ProviderItemId.Type;
export const RuntimeSessionId = makeEntityId("RuntimeSessionId");
+2
View File
@@ -1069,6 +1069,8 @@ export const DesktopPreviewAutomationWaitForInputSchema = Schema.Struct({
export interface DesktopBridge {
getAppBranding: () => DesktopAppBranding | null;
/** The desktop client's OS platform, read from Electron's preload process. */
getClientPlatform?: () => string;
/**
* The OS locale as a BCP-47 tag, which the renderer cannot read for itself:
* the packaged app ships only the `en-US` Chromium locale pak, so
+3
View File
@@ -170,6 +170,9 @@ importers:
'@types/node':
specifier: 24.12.4
version: 24.12.4
acorn:
specifier: 8.16.0
version: 8.16.0
cross-env:
specifier: ^10.1.0
version: 10.1.0