Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions .agents/skills/test-t3-app/references/feature-map.md
Original file line number Diff line number Diff line change
Expand Up @@ -208,7 +208,7 @@ Code:

Connections:

- **settings.connections** — `/settings/connections`, "Environments": "This machine", "Linked environments", "Network access", "Tailscale HTTPS", "T3 Connect", "Load balancing".
- **settings.connections** — `/settings/connections`, "Environments": "This machine", "Linked environments", "Network access", "Tailscale HTTPS", "T3 Connect", "Load balancing", "Google sign-in" (when configured).
- **settings.access** — `/settings/access`, "Sharing & access": paired devices, "Guest links", "Require approval for new devices".
- **settings.secrets** — `/settings/secrets`, "Secrets" (only when secrets are enabled).

Expand All @@ -230,7 +230,7 @@ Old links that redirect:
## Onboarding, pairing and connect pages

- **onboard.welcome** — `/welcome`, "Welcome": "Set up an agent" (Codex, Claude Code), "Import projects and their threads", "Set up T3 Connect", mobile app pointer.
- **onboard.pair** — `/pair`, "Pair with this environment": "Paste a one-time token or pairing secret".
- **onboard.pair** — `/pair`, "Pair with this environment": "Paste a one-time token or pairing secret", "Sign in with Google" (when configured).
- **onboard.connect** — `/connect`, "Authorization request", "Connecting your terminal": approves a `t3` CLI sign-in through T3 Connect.
- **onboard.connect-agent** — `/connect-agent`, "Agent sign-in", "Connect <client>": lets an outside agent connect. Reached from the code made by "Use T3 Code in another app (MCP)".
- **onboard.approve-agent** — `/approve-agent`, "Agent sign-in": "Choose what it may do", "Read only", "Continue", "Deny".
Expand Down
36 changes: 36 additions & 0 deletions apps/desktop/src/backend/DesktopLocalEnvironmentAuth.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -193,6 +193,42 @@ describe("DesktopLocalEnvironmentAuth", () => {
},
]),
} as unknown as DesktopBackendPool.DesktopBackendPool["Service"]);

it.effect("uses the WorkOS session only after the browser handoff completes", () =>
Effect.gen(function* () {
const authorizationUrl = "https://t3.example.test/api/auth/workos/start?desktop=handoff";
const opened = yield* Ref.make<unknown>(null);
const layerHttpClient = Layer.succeed(
HttpClient.HttpClient,
HttpClient.make((request) => {
const path = new URL(request.url).pathname;
if (path === "/oauth/token") return Effect.succeed(tokenResponse(request));
const response = path.endsWith("/start")
? Response.json({ id: "handoff", authorizationUrl })
: path.endsWith("/finish")
? Response.json({ token: "verified-session", expiresAt: 120_000 })
: new Response(null, { status: 204 });
return Effect.succeed(HttpClientResponse.fromWeb(request, response));
}),
);
const auth = yield* DesktopLocalEnvironmentAuth.DesktopLocalEnvironmentAuth.pipe(
Effect.provide(
DesktopLocalEnvironmentAuth.layer.pipe(
Layer.provide(Layer.mergeAll(layerPool, layerHttpClient, NodeCrypto.layerMac)),
),
),
);
const open = (url: unknown) => Ref.set(opened, url).pipe(Effect.as(true));
yield* auth.workOsAction("start", open);
assert.strictEqual(yield* Ref.get(opened), authorizationUrl);
assert.strictEqual(yield* auth.getRendererBearerToken, "desktop-bearer-token");
yield* auth.workOsAction("finish", open);
assert.strictEqual(yield* auth.getRendererBearerToken, "verified-session");
yield* auth.workOsAction("logout", open);
assert.strictEqual(yield* auth.getRendererBearerToken, "desktop-bearer-token");
}),
);

const makeExchange = (failures: number, failure: () => Response) =>
Effect.gen(function* () {
const requestCount = yield* Ref.make(0);
Expand Down
141 changes: 129 additions & 12 deletions apps/desktop/src/backend/DesktopLocalEnvironmentAuth.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
// @effect-diagnostics nodeBuiltinImport:off - PKCE is generated in the Electron main process.
import * as NodeCrypto from "node:crypto";
import { bootstrapRemoteBearerSession } from "@t3tools/client-runtime/authorization";
import type { RemoteEnvironmentRequestError } from "@t3tools/client-runtime/rpc";
import { PRIMARY_LOCAL_ENVIRONMENT_ID } from "@t3tools/contracts";
Expand All @@ -13,8 +15,9 @@ import * as Ref from "effect/Ref";
import * as Schedule from "effect/Schedule";
import * as Schema from "effect/Schema";
import * as Semaphore from "effect/Semaphore";
import * as HttpClient from "effect/http/HttpClient";
import { HttpClient, HttpClientRequest } from "effect/http";

import * as ElectronShell from "../electron/ElectronShell.ts";
import * as DesktopBackendPool from "./DesktopBackendPool.ts";

// Each /oauth/token attempt may take 10 s, so a backend busy after ready needs several attempts.
Expand Down Expand Up @@ -58,10 +61,25 @@ export const DesktopLocalEnvironmentAuthError = Schema.Union([
]);
export type DesktopLocalEnvironmentAuthError = typeof DesktopLocalEnvironmentAuthError.Type;

const DesktopStart = Schema.Struct({ id: Schema.String, authorizationUrl: Schema.String });
const DesktopFinish = Schema.Struct({ token: Schema.String, expiresAt: Schema.Number });
const decodeWorkOsStart = Schema.decodeUnknownEffect(DesktopStart);
const decodeWorkOsFinish = Schema.decodeUnknownEffect(DesktopFinish);

export class DesktopWorkOsRequestError extends Schema.TaggedError<DesktopWorkOsRequestError>()(
"DesktopWorkOsRequestError",
{ message: Schema.String },
) {}

export class DesktopLocalEnvironmentAuth extends Context.Service<
DesktopLocalEnvironmentAuth,
{
readonly getBearerToken: Effect.Effect<string, DesktopLocalEnvironmentAuthError>;
readonly getRendererBearerToken: Effect.Effect<string, DesktopLocalEnvironmentAuthError>;
readonly workOsAction: (
action: "start" | "finish" | "logout",
openExternal: ElectronShell.ElectronShell["Service"]["openExternal"],
) => Effect.Effect<void, DesktopLocalEnvironmentAuthError | DesktopWorkOsRequestError>;
}
>()("@t3tools/desktop/backend/DesktopLocalEnvironmentAuth") {}

Expand All @@ -72,6 +90,25 @@ export const make = Effect.gen(function* () {
const mac = yield* Mac.Mac;
const tokenRef = yield* Ref.make(Option.none<string>());
const mutex = yield* Semaphore.make(1);
const workOsMutex = yield* Semaphore.make(1);
let pending:
| { readonly base: string; readonly id: string; readonly verifier: string }
| undefined;
let verified:
| { readonly base: string; readonly token: string; readonly expiresAt: number }
| undefined;

const primaryConfig = Effect.fn("DesktopLocalEnvironmentAuth.primaryConfig")(function* () {
const instances = yield* pool.list;
const primary = instances.find((instance) => instance.id === PRIMARY_LOCAL_ENVIRONMENT_ID);
if (primary === undefined || !(yield* primary.waitForReady(Duration.infinity))) {
return yield* new DesktopLocalEnvironmentAuthBackendNotConfiguredError();
}
const config = yield* primary.currentConfig;
if (Option.isNone(config))
return yield* new DesktopLocalEnvironmentAuthBackendNotConfiguredError();
return config.value;
});

const getBearerToken = mutex
.withPermits(1)(
Expand All @@ -81,16 +118,7 @@ export const make = Effect.gen(function* () {
return cached.value;
}

const instances = yield* pool.list;
const primary = instances.find((instance) => instance.id === PRIMARY_LOCAL_ENVIRONMENT_ID);
if (primary === undefined || !(yield* primary.waitForReady(Duration.infinity))) {
return yield* new DesktopLocalEnvironmentAuthBackendNotConfiguredError();
}
const configOption = yield* primary.currentConfig;
if (Option.isNone(configOption)) {
return yield* new DesktopLocalEnvironmentAuthBackendNotConfiguredError();
}
const config = configOption.value;
const config = yield* primaryConfig();
// Secret-authenticated backends accept the current window token; the launch token may be stale.
const secret = config.bootstrap.desktopBootstrapSecret;
const credential =
Expand Down Expand Up @@ -129,7 +157,96 @@ export const make = Effect.gen(function* () {
)
.pipe(Effect.withSpan("desktop.localEnvironmentAuth.getBearerToken"));

return DesktopLocalEnvironmentAuth.of({ getBearerToken });
const getRendererBearerToken = Effect.gen(function* () {
if (verified && verified.expiresAt > (yield* Clock.currentTimeMillis)) {
const current = yield* primaryConfig();
if (current.httpBaseUrl.href === verified.base) return verified.token;
}
return yield* getBearerToken;
});

const requestWorkOs = Effect.fn("DesktopLocalEnvironmentAuth.requestWorkOs")(function* (
base: string,
path: "desktop/start" | "desktop/finish" | "logout",
token: string,
body?: object,
) {
const unavailable = () =>
new DesktopWorkOsRequestError({ message: "Could not reach the local T3 Code server." });
const request = HttpClientRequest.post(new URL(`/api/auth/workos/${path}`, base)).pipe(
HttpClientRequest.bearerToken(token),
);
const prepared = body
? yield* HttpClientRequest.bodyJson(request, body).pipe(Effect.mapError(unavailable))
: request;
const response = yield* httpClient
.execute(prepared)
.pipe(Effect.timeout("10 seconds"), Effect.mapError(unavailable));
if (response.status < 200 || response.status >= 300) {
return yield* new DesktopWorkOsRequestError({
message:
response.status === 409
? "Finish Google sign-in in your browser first."
: "Google sign-in could not be completed. Start again.",
});
}
if (response.status === 204) return undefined;
return yield* response.json.pipe(Effect.mapError(unavailable));
});

const workOsAction: DesktopLocalEnvironmentAuth["Service"]["workOsAction"] = Effect.fn(
"DesktopLocalEnvironmentAuth.workOsAction",
)(function* (action, openExternal) {
const base = (yield* primaryConfig()).httpBaseUrl.href;
const invalidResponse = () =>
new DesktopWorkOsRequestError({
message: "The local server returned an invalid sign-in response.",
});
if (action === "logout") {
if (verified?.base === base && verified.expiresAt > (yield* Clock.currentTimeMillis)) {
yield* requestWorkOs(base, "logout", verified.token);
}
verified = undefined;
pending = undefined;
return;
}
const token = yield* getBearerToken;
if (action === "start") {
const verifier = NodeCrypto.randomBytes(32).toString("base64url");
const challenge = NodeCrypto.createHash("sha256").update(verifier).digest("base64url");
const result = yield* requestWorkOs(base, "desktop/start", token, { challenge });
const { id, authorizationUrl } = yield* decodeWorkOsStart(result).pipe(
Effect.mapError(invalidResponse),
);
const url = URL.parse(authorizationUrl);
if (
url?.protocol !== "https:" ||
url.username ||
url.password ||
url.pathname !== "/api/auth/workos/start" ||
url.searchParams.get("desktop") !== id
) {
return yield* invalidResponse();
}
if (!(yield* openExternal(url.href))) {
return yield* new DesktopWorkOsRequestError({
message: "Could not open your system browser.",
});
}
pending = { base, id, verifier };
return;
}
if (!pending || pending.base !== base) {
return yield* new DesktopWorkOsRequestError({ message: "Start Google sign-in again." });
}
const { id, verifier } = pending;
const result = yield* requestWorkOs(base, "desktop/finish", token, { id, verifier });
const session = yield* decodeWorkOsFinish(result).pipe(Effect.mapError(invalidResponse));
verified = { base, ...session };
pending = undefined;
}, workOsMutex.withPermits(1));

return DesktopLocalEnvironmentAuth.of({ getBearerToken, getRendererBearerToken, workOsAction });
});

export const layer = Layer.effect(DesktopLocalEnvironmentAuth, make);
2 changes: 2 additions & 0 deletions apps/desktop/src/ipc/DesktopIpcHandlers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ import {
getAppBranding,
getLocalEnvironmentBootstraps,
getLocalEnvironmentBearerToken,
workOsSignIn,
installRelayTelemetryEnabled,
getSystemLocale,
getPreferredSystemLanguages,
Expand Down Expand Up @@ -109,6 +110,7 @@ export const installDesktopIpcHandlers = Effect.fn("desktop.ipc.installHandlers"
yield* ipc.handle(setLocalEnvironmentEnabled);
yield* ipc.handle(getHostEnvironmentId);
yield* ipc.handle(getLocalEnvironmentBearerToken);
yield* ipc.handle(workOsSignIn);

yield* ipc.handle(restartAudioService);
yield* ipc.handle(getClientSettings);
Expand Down
1 change: 1 addition & 0 deletions apps/desktop/src/ipc/channels.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@ export const SET_LOCAL_ENVIRONMENT_ENABLED_CHANNEL = "desktop:set-local-environm
export const GET_HOST_ENVIRONMENT_ID_CHANNEL = "desktop:get-host-environment-id";
export const GET_LOCAL_ENVIRONMENT_BEARER_TOKEN_CHANNEL =
"desktop:get-local-environment-bearer-token";
export const WORKOS_SIGN_IN_CHANNEL = "desktop:workos-sign-in";
export const GET_CLIENT_SETTINGS_CHANNEL = "desktop:get-client-settings";
export const SET_CLIENT_SETTINGS_CHANNEL = "desktop:set-client-settings";
export const SETUP_SNAP_SHOT_CHANNEL = "desktop:setup-snap-shot";
Expand Down
13 changes: 12 additions & 1 deletion apps/desktop/src/ipc/methods/window.ts
Original file line number Diff line number Diff line change
Expand Up @@ -205,7 +205,18 @@ export const getLocalEnvironmentBearerToken = DesktopIpc.makeIpcMethod({
result: Schema.String,
handler: Effect.fn("desktop.ipc.window.getLocalEnvironmentBearerToken")(function* () {
const localAuth = yield* DesktopLocalEnvironmentAuth.DesktopLocalEnvironmentAuth;
return yield* localAuth.getBearerToken;
return yield* localAuth.getRendererBearerToken;
}),
});

export const workOsSignIn = DesktopIpc.makeIpcMethod({
channel: IpcChannels.WORKOS_SIGN_IN_CHANNEL,
payload: Schema.Literals(["start", "finish", "logout"]),
result: Schema.Void,
handler: Effect.fn("desktop.ipc.window.workOsSignIn")(function* (action) {
const localAuth = yield* DesktopLocalEnvironmentAuth.DesktopLocalEnvironmentAuth;
const shell = yield* ElectronShell.ElectronShell;
yield* localAuth.workOsAction(action, shell.openExternal);
}),
});

Expand Down
1 change: 1 addition & 0 deletions apps/desktop/src/preload.ts
Original file line number Diff line number Diff line change
Expand Up @@ -154,6 +154,7 @@ contextBridge.exposeInMainWorld("desktopBridge", {
},
getLocalEnvironmentBearerToken: () =>
ipcRenderer.invoke(IpcChannels.GET_LOCAL_ENVIRONMENT_BEARER_TOKEN_CHANNEL),
workOsSignIn: (action) => ipcRenderer.invoke(IpcChannels.WORKOS_SIGN_IN_CHANNEL, action),
getLocalEnvironmentEnabled: () =>
ipcRenderer.sendSync(IpcChannels.GET_LOCAL_ENVIRONMENT_ENABLED_CHANNEL) !== false,
setLocalEnvironmentEnabled: (enabled) =>
Expand Down
1 change: 1 addition & 0 deletions apps/server/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,7 @@
"diff": "8.0.3",
"effect": "catalog:",
"ffi-rs": "1.3.2",
"jose": "6.2.17",
"jsonc-parser": "3.3.1",
"node-pty": "^1.2.0-beta.15",
"playwright-core": "1.64.1",
Expand Down
Loading
Loading