Compare commits

...
Author SHA1 Message Date
Julius Marminge 95144d8d18 Await hydrated client settings for new thread creation 2026-06-19 11:24:33 -07:00
JustMarkDevandcodex 31078cb4e0 Add configurable default access mode for new threads
- Persist client-side default runtime mode in settings
- Use it when creating draft threads and new local threads
- Surface the setting in the UI and cover it with tests

Co-authored-by: codex <[email protected]>
2026-06-19 11:21:26 -07:00
Wout Stiensandcodex 7dc182337c [codex] fix: show nightly badge from primary web server version (#3103)
Co-authored-by: codex <[email protected]>
2026-06-19 11:16:37 -07:00
13917df1fe Use idiomatic Effect options for server secret reads (#3110)
Co-authored-by: Cursor Agent <[email protected]>
Co-authored-by: Julius Marminge <[email protected]>
Co-authored-by: Julius Marminge <[email protected]>
Co-authored-by: codex <[email protected]>
2026-06-19 11:15:35 -07:00
Ulises Britosandcodex 5d4e2fae01 feat: allow disabling provider update checks (#3130)
Co-authored-by: codex <[email protected]>
2026-06-19 11:07:23 -07:00
Julius Marmingeandcodex 3e01c4bc57 Migrate desktop auth to Clerk bridge (#3092)
Co-authored-by: codex <[email protected]>
2026-06-19 10:28:28 -07:00
105 changed files with 2690 additions and 3525 deletions

No files matched your search

+7
View File
@@ -8,6 +8,13 @@
# T3CODE_CLERK_JWT_TEMPLATE=t3-relay
# T3CODE_CLERK_CLI_OAUTH_CLIENT_ID=oauthapp_...
# Optional: signed macOS passkey builds. The RP domain defaults to the Frontend API
# hostname encoded in T3CODE_CLERK_PUBLISHABLE_KEY. Set the override only when Clerk
# returns a different RP ID or when multiple domains must be entitled.
# T3CODE_APPLE_TEAM_ID=ABC1234567
# T3CODE_MACOS_PROVISIONING_PROFILE=/absolute/path/to/t3code.provisionprofile
# T3CODE_CLERK_PASSKEY_RP_DOMAINS=example.clerk.accounts.dev,clerk.example.com
# Get this from your relay deployment. `infra/relay` deploys update it automatically.
# T3CODE_RELAY_URL=https://relay.example.com
+1
View File
@@ -38,6 +38,7 @@ jobs:
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
test:
name: Test
+15
View File
@@ -425,6 +425,9 @@ jobs:
APPLE_API_KEY: ${{ secrets.APPLE_API_KEY }}
APPLE_API_KEY_ID: ${{ secrets.APPLE_API_KEY_ID }}
APPLE_API_ISSUER: ${{ secrets.APPLE_API_ISSUER }}
APPLE_TEAM_ID: ${{ vars.APPLE_TEAM_ID }}
MACOS_PROVISIONING_PROFILE: ${{ secrets.MACOS_PROVISIONING_PROFILE }}
T3CODE_CLERK_PASSKEY_RP_DOMAINS: ${{ vars.CLERK_PASSKEY_RP_DOMAINS }}
AZURE_TENANT_ID: ${{ secrets.AZURE_TENANT_ID }}
AZURE_CLIENT_ID: ${{ secrets.AZURE_CLIENT_ID }}
AZURE_CLIENT_SECRET: ${{ secrets.AZURE_CLIENT_SECRET }}
@@ -452,9 +455,21 @@ jobs:
if [[ "${{ matrix.platform }}" == "mac" ]]; then
if has_all "$CSC_LINK" "$CSC_KEY_PASSWORD" "$APPLE_API_KEY" "$APPLE_API_KEY_ID" "$APPLE_API_ISSUER"; then
if ! has_all "$APPLE_TEAM_ID" "$MACOS_PROVISIONING_PROFILE"; then
echo "macOS signing is configured, but APPLE_TEAM_ID or MACOS_PROVISIONING_PROFILE is missing." >&2
exit 1
fi
key_path="$RUNNER_TEMP/AuthKey_${APPLE_API_KEY_ID}.p8"
printf '%s' "$APPLE_API_KEY" > "$key_path"
export APPLE_API_KEY="$key_path"
profile_path="$RUNNER_TEMP/t3code.provisionprofile"
printf '%s' "$MACOS_PROVISIONING_PROFILE" | base64 -D > "$profile_path"
security cms -D -i "$profile_path" >/dev/null
export T3CODE_APPLE_TEAM_ID="$APPLE_TEAM_ID"
export T3CODE_MACOS_PROVISIONING_PROFILE="$profile_path"
echo "macOS signing enabled."
args+=(--signed)
else
+3
View File
@@ -12,6 +12,8 @@
"smoke-test": "node scripts/smoke-test.mjs"
},
"dependencies": {
"@clerk/electron": "catalog:",
"@clerk/electron-passkeys": "catalog:",
"@effect/platform-node": "catalog:",
"@t3tools/client-runtime": "workspace:*",
"@t3tools/contracts": "workspace:*",
@@ -20,6 +22,7 @@
"@t3tools/tailscale": "workspace:*",
"effect": "catalog:",
"electron": "41.5.0",
"electron-store": "^8.2.0",
"electron-updater": "^6.6.2",
"playwright-core": "1.60.0",
"react-grab": "^0.1.32"
+1 -21
View File
@@ -31,20 +31,12 @@ 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 = 11;
const LAUNCHER_VERSION = 12;
const defaultIconPath = join(desktopDir, "resources", "icon.icns");
const developmentMacIconPngPath = join(repoRoot, "assets", "dev", "blueprint-macos-1024.png");
// oxlint-disable-next-line t3code/no-global-process-runtime -- Standalone launcher script has no Effect runtime.
const hostPlatform = NodeOS.platform();
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",
@@ -100,7 +92,6 @@ function shellSingleQuote(value) {
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],
@@ -109,23 +100,12 @@ function writeDevelopmentLauncherScript(targetBinaryPath, electronBinaryPath) {
["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"),
+13 -5
View File
@@ -11,7 +11,7 @@ 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 DesktopClerk from "./DesktopClerk.ts";
import * as DesktopApplicationMenu from "../window/DesktopApplicationMenu.ts";
import * as DesktopBackendManager from "../backend/DesktopBackendManager.ts";
import * as DesktopEnvironment from "./DesktopEnvironment.ts";
@@ -163,6 +163,16 @@ const bootstrap = Effect.gen(function* () {
}
const serverExposureState = yield* serverExposure.configureFromSettings({ port: backendPort });
const backendConfig = yield* serverExposure.backendConfig;
const electronProtocol = yield* ElectronProtocol.ElectronProtocol;
const rendererTarget = environment.isDevelopment
? Option.getOrThrow(environment.devServerUrl)
: backendConfig.httpBaseUrl;
yield* electronProtocol.registerDesktopProtocol({
scheme: ElectronProtocol.getDesktopScheme(environment.isDevelopment),
targetOrigin: rendererTarget,
backendOrigin: backendConfig.httpBaseUrl,
clerkFrontendApiHostname: DesktopClerk.desktopClerkFrontendApiHostname,
});
yield* logBootstrapInfo("bootstrap resolved backend endpoint", {
baseUrl: backendConfig.httpBaseUrl.href,
});
@@ -189,9 +199,8 @@ const startup = Effect.gen(function* () {
const appIdentity = yield* DesktopAppIdentity.DesktopAppIdentity;
const applicationMenu = yield* DesktopApplicationMenu.DesktopApplicationMenu;
const electronApp = yield* ElectronApp.ElectronApp;
const electronProtocol = yield* ElectronProtocol.ElectronProtocol;
const lifecycle = yield* DesktopLifecycle.DesktopLifecycle;
const cloudAuth = yield* DesktopCloudAuth.DesktopCloudAuth;
const clerk = yield* DesktopClerk.DesktopClerk;
const shellEnvironment = yield* DesktopShellEnvironment.DesktopShellEnvironment;
const desktopSettings = yield* DesktopAppSettings.DesktopAppSettings;
const updates = yield* DesktopUpdates.DesktopUpdates;
@@ -209,7 +218,7 @@ const startup = Effect.gen(function* () {
yield* appIdentity.configure;
yield* lifecycle.register;
yield* cloudAuth.configure;
yield* clerk.configure;
yield* electronApp.whenReady.pipe(
Effect.withSpan("desktop.electron.whenReady"),
@@ -218,7 +227,6 @@ const startup = Effect.gen(function* () {
yield* logStartupInfo("app ready");
yield* appIdentity.configure;
yield* applicationMenu.configure;
yield* electronProtocol.registerDesktopFileProtocol;
yield* updates.configure;
yield* bootstrap.pipe(Effect.catchCause((cause) => fatalStartupCause("bootstrap", cause)));
}).pipe(Effect.withSpan("desktop.startup"));
+95
View File
@@ -0,0 +1,95 @@
import { assert, describe, it } from "@effect/vitest";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import { vi } from "vite-plus/test";
const { createClerkBridgeMock, storageAdapter, storageMock } = vi.hoisted(() => ({
createClerkBridgeMock: vi.fn(),
storageAdapter: {
getItem: vi.fn(),
setItem: vi.fn(),
removeItem: vi.fn(),
},
storageMock: vi.fn(),
}));
vi.mock("@clerk/electron", () => ({
createClerkBridge: createClerkBridgeMock,
}));
vi.mock("@clerk/electron/storage", () => ({
storage: storageMock,
}));
import {
createDesktopClerkBridge,
resolveDesktopClerkFrontendApiHostname,
} from "./DesktopClerk.ts";
import * as DesktopClerk from "./DesktopClerk.ts";
import * as DesktopEnvironment from "./DesktopEnvironment.ts";
describe("DesktopClerk", () => {
it("derives the Clerk Frontend API hostname used by the desktop CSP", () => {
const publishableKey = `pk_test_${btoa("clerk.t3.codes$")}`;
assert.equal(resolveDesktopClerkFrontendApiHostname(publishableKey), "clerk.t3.codes");
assert.equal(resolveDesktopClerkFrontendApiHostname(""), undefined);
assert.equal(resolveDesktopClerkFrontendApiHostname("invalid"), undefined);
});
it.effect("acquires and releases the SDK bridge with the layer", () => {
const cleanup = vi.fn();
storageMock.mockReturnValue(storageAdapter);
createClerkBridgeMock.mockReturnValue({ cleanup });
const environment = DesktopEnvironment.DesktopEnvironment.of({
stateDir: "/tmp/t3-state",
isDevelopment: true,
} as unknown as DesktopEnvironment.DesktopEnvironmentShape);
return Effect.gen(function* () {
yield* Effect.scoped(
Layer.build(
DesktopClerk.layer.pipe(
Layer.provide(Layer.succeed(DesktopEnvironment.DesktopEnvironment, environment)),
),
),
);
assert.deepEqual(createClerkBridgeMock.mock.calls, [
[
{
storage: storageAdapter,
passkeys: true,
renderer: { scheme: "t3code-dev", host: "app" },
},
],
]);
assert.equal(cleanup.mock.calls.length, 1);
storageMock.mockClear();
createClerkBridgeMock.mockClear();
});
});
it.each([
{ isDevelopment: true, scheme: "t3code-dev" },
{ isDevelopment: false, scheme: "t3code" },
])("configures the SDK with the $scheme renderer origin", ({ isDevelopment, scheme }) => {
const bridge = { cleanup: vi.fn() };
storageMock.mockReturnValue(storageAdapter);
createClerkBridgeMock.mockReturnValue(bridge);
assert.equal(createDesktopClerkBridge("/tmp/t3-state", isDevelopment), bridge);
assert.deepEqual(storageMock.mock.calls, [[{ path: "/tmp/t3-state" }]]);
assert.deepEqual(createClerkBridgeMock.mock.calls, [
[
{
storage: storageAdapter,
passkeys: true,
renderer: { scheme, host: "app" },
},
],
]);
storageMock.mockClear();
createClerkBridgeMock.mockClear();
});
});
+92
View File
@@ -0,0 +1,92 @@
import { createClerkBridge } from "@clerk/electron";
import { storage } from "@clerk/electron/storage";
import * as Context from "effect/Context";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Scope from "effect/Scope";
import { clerkFrontendApiHostnameFromPublishableKey } from "@t3tools/shared/relayAuth";
import * as ElectronApp from "../electron/ElectronApp.ts";
import * as ElectronProtocol from "../electron/ElectronProtocol.ts";
import * as ElectronWindow from "../electron/ElectronWindow.ts";
import * as DesktopEnvironment from "./DesktopEnvironment.ts";
declare const __T3CODE_BUILD_CLERK_PUBLISHABLE_KEY__: string | undefined;
export interface DesktopClerkShape {
readonly configure: Effect.Effect<
void,
never,
ElectronApp.ElectronApp | ElectronWindow.ElectronWindow | Scope.Scope
>;
}
export class DesktopClerk extends Context.Service<DesktopClerk, DesktopClerkShape>()(
"@t3tools/desktop/app/DesktopClerk",
) {}
export function resolveDesktopClerkFrontendApiHostname(
publishableKey: string | undefined,
): string | undefined {
const normalizedKey = publishableKey?.trim();
if (!normalizedKey) return undefined;
try {
return clerkFrontendApiHostnameFromPublishableKey(normalizedKey);
} catch {
return undefined;
}
}
export const desktopClerkFrontendApiHostname = resolveDesktopClerkFrontendApiHostname(
typeof __T3CODE_BUILD_CLERK_PUBLISHABLE_KEY__ === "undefined"
? undefined
: __T3CODE_BUILD_CLERK_PUBLISHABLE_KEY__,
);
export function createDesktopClerkBridge(stateDir: string, isDevelopment: boolean) {
return createClerkBridge({
storage: storage({ path: stateDir }),
passkeys: true,
renderer: {
scheme: ElectronProtocol.getDesktopScheme(isDevelopment),
host: ElectronProtocol.DESKTOP_HOST,
},
});
}
const make = Effect.gen(function* () {
const environment = yield* DesktopEnvironment.DesktopEnvironment;
yield* Effect.acquireRelease(
Effect.sync(() => createDesktopClerkBridge(environment.stateDir, environment.isDevelopment)),
(bridge) => Effect.sync(() => bridge.cleanup()),
);
return DesktopClerk.of({
configure: Effect.gen(function* () {
const electronApp = yield* ElectronApp.ElectronApp;
const electronWindow = yield* ElectronWindow.ElectronWindow;
const context = yield* Effect.context<ElectronWindow.ElectronWindow>();
const runPromise = Effect.runPromiseWith(context);
if (!(yield* electronApp.requestSingleInstanceLock)) {
yield* electronApp.quit;
return yield* Effect.interrupt;
}
yield* electronApp.on("second-instance", () => {
void runPromise(
Effect.gen(function* () {
const mainWindow = yield* electronWindow.currentMainOrFirst;
if (Option.isSome(mainWindow)) {
yield* electronWindow.reveal(mainWindow.value);
}
}),
);
});
}).pipe(Effect.withSpan("desktop.clerk.configure")),
});
});
export const layer = Layer.effect(DesktopClerk, make);
@@ -1,302 +0,0 @@
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);
},
);
});
-330
View File
@@ -1,330 +0,0 @@
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);
@@ -1,96 +0,0 @@
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 },
),
);
});
@@ -1,155 +0,0 @@
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"),
),
});
}),
);
@@ -0,0 +1,82 @@
import { assert, describe, it } from "@effect/vitest";
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 { HttpClient, HttpClientResponse } from "effect/unstable/http";
import * as DesktopBackendManager from "./DesktopBackendManager.ts";
import * as DesktopLocalEnvironmentAuth from "./DesktopLocalEnvironmentAuth.ts";
const config: DesktopBackendManager.DesktopBackendStartConfig = {
executablePath: "/electron",
entryPath: "/server/bin.mjs",
cwd: "/server",
env: {},
bootstrap: {
mode: "desktop",
noBrowser: true,
port: 3773,
t3Home: "/tmp/t3",
host: "127.0.0.1",
desktopBootstrapToken: "desktop-bootstrap-token",
tailscaleServeEnabled: false,
tailscaleServePort: 443,
},
httpBaseUrl: new URL("http://127.0.0.1:3773"),
captureOutput: true,
};
describe("DesktopLocalEnvironmentAuth", () => {
it.effect("exchanges the desktop bootstrap credential only once", () =>
Effect.gen(function* () {
const requestCount = yield* Ref.make(0);
const httpClientLayer = Layer.succeed(
HttpClient.HttpClient,
HttpClient.make((request) =>
Ref.update(requestCount, (count) => count + 1).pipe(
Effect.as(
HttpClientResponse.fromWeb(
request,
new Response(
JSON.stringify({
access_token: "desktop-bearer-token",
issued_token_type: "urn:ietf:params:oauth:token-type:access_token",
token_type: "Bearer",
expires_in: 3600,
scope: "orchestration:read",
}),
{ status: 200, headers: { "content-type": "application/json" } },
),
),
),
),
),
);
const managerLayer = Layer.succeed(DesktopBackendManager.DesktopBackendManager, {
start: Effect.void,
stop: () => Effect.void,
currentConfig: Effect.succeed(Option.some(config)),
snapshot: Effect.succeed({
desiredRunning: true,
ready: true,
activePid: Option.none(),
restartAttempt: 0,
restartScheduled: false,
}),
});
const testLayer = DesktopLocalEnvironmentAuth.layer.pipe(
Layer.provide(Layer.mergeAll(managerLayer, httpClientLayer)),
);
const [first, second] = yield* Effect.gen(function* () {
const auth = yield* DesktopLocalEnvironmentAuth.DesktopLocalEnvironmentAuth;
return yield* Effect.all([auth.getBearerToken, auth.getBearerToken]);
}).pipe(Effect.provide(testLayer));
assert.strictEqual(first, "desktop-bearer-token");
assert.strictEqual(second, "desktop-bearer-token");
assert.strictEqual(yield* Ref.get(requestCount), 1);
}),
);
});
@@ -0,0 +1,77 @@
import { bootstrapRemoteBearerSession } from "@t3tools/client-runtime/authorization";
import * as Context from "effect/Context";
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 Ref from "effect/Ref";
import * as Semaphore from "effect/Semaphore";
import { HttpClient } from "effect/unstable/http";
import * as DesktopBackendManager from "./DesktopBackendManager.ts";
export interface DesktopLocalEnvironmentAuthShape {
readonly getBearerToken: Effect.Effect<string, DesktopLocalEnvironmentAuthError>;
}
export class DesktopLocalEnvironmentAuthError extends Data.TaggedError(
"DesktopLocalEnvironmentAuthError",
)<{
readonly message: string;
readonly cause?: unknown;
}> {}
export class DesktopLocalEnvironmentAuth extends Context.Service<
DesktopLocalEnvironmentAuth,
DesktopLocalEnvironmentAuthShape
>()("@t3tools/desktop/backend/DesktopLocalEnvironmentAuth") {}
export const layer = Layer.effect(
DesktopLocalEnvironmentAuth,
Effect.gen(function* () {
const backendManager = yield* DesktopBackendManager.DesktopBackendManager;
const httpClient = yield* HttpClient.HttpClient;
const tokenRef = yield* Ref.make(Option.none<string>());
const mutex = yield* Semaphore.make(1);
const getBearerToken = mutex
.withPermits(1)(
Effect.gen(function* () {
const cached = yield* Ref.get(tokenRef);
if (Option.isSome(cached)) {
return cached.value;
}
const configOption = yield* backendManager.currentConfig;
if (Option.isNone(configOption)) {
return yield* new DesktopLocalEnvironmentAuthError({
message: "Local backend is not configured.",
});
}
const config = configOption.value;
const session = yield* bootstrapRemoteBearerSession({
httpBaseUrl: config.httpBaseUrl.href,
credential: config.bootstrap.desktopBootstrapToken,
clientMetadata: {
label: "T3 Code Desktop",
deviceType: "desktop",
},
}).pipe(
Effect.provideService(HttpClient.HttpClient, httpClient),
Effect.mapError(
(cause) =>
new DesktopLocalEnvironmentAuthError({
message: "Failed to create the local desktop bearer session.",
cause,
}),
),
);
yield* Ref.set(tokenRef, Option.some(session.access_token));
return session.access_token;
}),
)
.pipe(Effect.withSpan("desktop.localEnvironmentAuth.getBearerToken"));
return DesktopLocalEnvironmentAuth.of({ getBearerToken });
}),
);
@@ -1,105 +1,132 @@
import { assert, describe, it } from "@effect/vitest";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import type * as Electron from "electron";
import { beforeEach, vi } from "vite-plus/test";
const { registerFileProtocolMock, registerSchemesAsPrivilegedMock, unregisterProtocolMock } =
vi.hoisted(() => ({
registerFileProtocolMock: vi.fn(),
registerSchemesAsPrivilegedMock: vi.fn(),
unregisterProtocolMock: vi.fn(),
}));
const { handleMock, netFetchMock, unhandleMock } = vi.hoisted(() => ({
handleMock: vi.fn(),
netFetchMock: vi.fn(),
unhandleMock: vi.fn(),
}));
vi.mock("electron", () => ({
protocol: {
registerFileProtocol: registerFileProtocolMock,
registerSchemesAsPrivileged: registerSchemesAsPrivilegedMock,
unregisterProtocol: unregisterProtocolMock,
},
net: { fetch: netFetchMock },
protocol: { handle: handleMock, unhandle: unhandleMock },
}));
import * as ElectronProtocol from "./ElectronProtocol.ts";
describe("ElectronProtocol", () => {
beforeEach(() => {
registerFileProtocolMock.mockReset();
registerSchemesAsPrivilegedMock.mockReset();
unregisterProtocolMock.mockReset();
handleMock.mockReset();
netFetchMock.mockReset();
unhandleMock.mockReset();
});
it("normalizes safe desktop protocol pathnames", () => {
assert.equal(
Option.getOrNull(ElectronProtocol.normalizeDesktopProtocolPathname("/settings/./general")),
"settings/general",
);
assert.isTrue(Option.isNone(ElectronProtocol.normalizeDesktopProtocolPathname("/../secret")));
});
it.effect("proxies the stable renderer origin to the current app server", () =>
Effect.gen(function* () {
let handler: ((request: Request) => Promise<Response>) | undefined;
handleMock.mockImplementation((_scheme, nextHandler) => {
handler = nextHandler;
});
netFetchMock.mockResolvedValue(new Response("ok"));
it.effect("registers desktop scheme privileges through a layer", () =>
Effect.scoped(
Layer.build(ElectronProtocol.layerSchemePrivileges).pipe(
Effect.andThen(
Effect.sync(() => {
assert.deepEqual(registerSchemesAsPrivilegedMock.mock.calls, [
[
[
{
scheme: "t3",
privileges: {
standard: true,
secure: true,
supportFetchAPI: true,
corsEnabled: true,
},
},
],
],
]);
}),
),
),
),
yield* Effect.scoped(
Effect.gen(function* () {
const protocol = yield* ElectronProtocol.ElectronProtocol;
yield* protocol.registerDesktopProtocol({
scheme: "t3code-dev",
targetOrigin: new URL("http://127.0.0.1:3773/"),
backendOrigin: new URL("http://127.0.0.1:3774/"),
clerkFrontendApiHostname: "clerk.t3.codes",
});
assert.isDefined(handler);
const response = yield* Effect.promise(() =>
handler!(new Request("t3code-dev://app/api/health?verbose=1")),
);
assert.equal(yield* Effect.promise(() => response.text()), "ok");
assert.include(
response.headers.get("content-security-policy") ?? "",
"script-src 'self' 'unsafe-inline' https://clerk.t3.codes https://challenges.cloudflare.com",
);
assert.include(
response.headers.get("content-security-policy") ?? "",
"connect-src 'self' http: https: ws: wss:",
);
assert.include(
response.headers.get("content-security-policy") ?? "",
"img-src 'self' t3code-dev: blob: data: http: https:",
);
assert.include(
response.headers.get("content-security-policy") ?? "",
"font-src 'self' t3code-dev: data:",
);
}),
);
assert.deepEqual(
handleMock.mock.calls.map((call) => call[0]),
["t3code-dev"],
);
assert.equal(netFetchMock.mock.calls[0]?.[0], "http://127.0.0.1:3773/api/health?verbose=1");
assert.deepEqual(unhandleMock.mock.calls, [["t3code-dev"]]);
}).pipe(Effect.provide(ElectronProtocol.layer)),
);
it.effect("scopes registered file protocols", () =>
it.effect("rejects custom protocol requests for another host", () =>
Effect.gen(function* () {
let capturedHandler:
| ((
request: Electron.ProtocolRequest,
callback: (response: Electron.ProtocolResponse) => void,
) => void)
| undefined;
registerFileProtocolMock.mockImplementation((_scheme, handler) => {
capturedHandler = handler;
return true;
let handler: ((request: Request) => Promise<Response>) | undefined;
handleMock.mockImplementation((_scheme, nextHandler) => {
handler = nextHandler;
});
const response = yield* Effect.scoped(
Effect.gen(function* () {
const electronProtocol = yield* ElectronProtocol.ElectronProtocol;
yield* electronProtocol.registerFileProtocol({
scheme: "t3",
handler: () => Effect.succeed({ path: "/app/index.html" }),
});
assert.isDefined(capturedHandler);
return yield* Effect.callback<Electron.ProtocolResponse>((resume) => {
capturedHandler?.({ url: "t3://app/" } as Electron.ProtocolRequest, (response) =>
resume(Effect.succeed(response)),
);
const protocol = yield* ElectronProtocol.ElectronProtocol;
yield* protocol.registerDesktopProtocol({
scheme: "t3code",
targetOrigin: new URL("http://127.0.0.1:3773/"),
backendOrigin: new URL("http://127.0.0.1:3773/"),
clerkFrontendApiHostname: undefined,
});
return yield* Effect.promise(() => handler!(new Request("t3code://other/")));
}),
);
assert.deepEqual(response, { path: "/app/index.html" });
assert.deepEqual(
registerFileProtocolMock.mock.calls.map((call) => call[0]),
["t3"],
);
assert.deepEqual(unregisterProtocolMock.mock.calls, [["t3"]]);
assert.equal(response.status, 404);
assert.equal(netFetchMock.mock.calls.length, 0);
}).pipe(Effect.provide(ElectronProtocol.layer)),
);
it("keeps executable sources host-restricted while allowing runtime network resources", () => {
const policy = ElectronProtocol.makeDesktopContentSecurityPolicy({
scheme: "t3code",
targetOrigin: new URL("http://127.0.0.1:3773/"),
backendOrigin: new URL("http://127.0.0.1:3773/"),
clerkFrontendApiHostname: "clerk.t3.codes",
});
const directives = Object.fromEntries(
policy.split("; ").map((directive) => {
const [name, ...sources] = directive.split(" ");
return [name, sources];
}),
);
assert.deepEqual(directives["script-src"], [
"'self'",
"'unsafe-inline'",
"https://clerk.t3.codes",
"https://challenges.cloudflare.com",
]);
assert.deepEqual(directives["connect-src"], ["'self'", "http:", "https:", "ws:", "wss:"]);
assert.deepEqual(directives["img-src"], [
"'self'",
"t3code:",
"blob:",
"data:",
"http:",
"https:",
]);
assert.deepEqual(directives["font-src"], ["'self'", "t3code:", "data:"]);
});
});
+90 -216
View File
@@ -1,18 +1,27 @@
import * as Cause from "effect/Cause";
import * as Context from "effect/Context";
import * as Data from "effect/Data";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Ref from "effect/Ref";
import * as Scope from "effect/Scope";
import * as Electron from "electron";
import { DesktopEnvironment, type DesktopEnvironmentShape } from "../app/DesktopEnvironment.ts";
export const DESKTOP_HOST = "app";
export const DESKTOP_PRODUCTION_SCHEME = "t3code";
export const DESKTOP_DEVELOPMENT_SCHEME = "t3code-dev";
export const DESKTOP_SCHEME = "t3";
export function getDesktopScheme(isDevelopment: boolean): string {
return isDevelopment ? DESKTOP_DEVELOPMENT_SCHEME : DESKTOP_PRODUCTION_SCHEME;
}
export function getDesktopOrigin(isDevelopment: boolean): string {
return `${getDesktopScheme(isDevelopment)}://${DESKTOP_HOST}`;
}
export function getDesktopUrl(isDevelopment: boolean): string {
return `${getDesktopOrigin(isDevelopment)}/`;
}
export class ElectronProtocolRegistrationError extends Data.TaggedError(
"ElectronProtocolRegistrationError",
@@ -21,252 +30,117 @@ export class ElectronProtocolRegistrationError extends Data.TaggedError(
readonly cause: unknown;
}> {
override get message() {
return `Failed to register ${this.scheme}: file protocol.`;
return `Failed to register ${this.scheme}: protocol.`;
}
}
export class ElectronProtocolStaticBundleMissingError extends Data.TaggedError(
"ElectronProtocolStaticBundleMissingError",
)<{}> {
override get message() {
return "Desktop static bundle missing. Build apps/server (with bundled client) first.";
}
export interface DesktopProtocolRegistrationInput {
readonly scheme: string;
readonly targetOrigin: URL;
readonly backendOrigin: URL;
readonly clerkFrontendApiHostname: string | undefined;
}
export interface ElectronProtocolShape {
readonly registerFileProtocol: <E, R>(input: {
readonly scheme: string;
readonly handler: (
request: Electron.ProtocolRequest,
) => Effect.Effect<Electron.ProtocolResponse, E, R>;
readonly onFailure?: (
request: Electron.ProtocolRequest,
cause: Cause.Cause<E>,
) => Electron.ProtocolResponse;
}) => Effect.Effect<void, ElectronProtocolRegistrationError, R | Scope.Scope>;
readonly registerDesktopFileProtocol: Effect.Effect<
void,
ElectronProtocolRegistrationError | ElectronProtocolStaticBundleMissingError,
FileSystem.FileSystem | DesktopEnvironment | Scope.Scope
>;
readonly registerDesktopProtocol: (
input: DesktopProtocolRegistrationInput,
) => Effect.Effect<void, ElectronProtocolRegistrationError, Scope.Scope>;
}
export class ElectronProtocol extends Context.Service<ElectronProtocol, ElectronProtocolShape>()(
"@t3tools/desktop/electron/ElectronProtocol",
) {}
export function normalizeDesktopProtocolPathname(rawPath: string): Option.Option<string> {
const segments: string[] = [];
for (const segment of rawPath.split("/")) {
if (segment.length === 0 || segment === ".") {
continue;
}
if (segment === "..") {
return Option.none();
}
segments.push(segment);
}
return Option.some(segments.join("/"));
export function makeDesktopContentSecurityPolicy(input: DesktopProtocolRegistrationInput): string {
const clerkOrigin = input.clerkFrontendApiHostname
? `https://${input.clerkFrontendApiHostname}`
: undefined;
const scriptSources = [
"'self'",
"'unsafe-inline'",
...(clerkOrigin ? [clerkOrigin] : []),
"https://challenges.cloudflare.com",
];
// The renderer connects directly to user-configured environments in addition to
// the build-configured Clerk, relay, and OTLP endpoints. Those environment
// origins are not known when this response policy is created, so restrict
// connections by the network schemes the client supports instead of by host.
const connectSources = ["'self'", "http:", "https:", "ws:", "wss:"];
return [
"default-src 'self'",
`script-src ${scriptSources.join(" ")}`,
`connect-src ${connectSources.join(" ")}`,
`img-src 'self' ${input.scheme}: blob: data: http: https:`,
"style-src 'self' 'unsafe-inline'",
`font-src 'self' ${input.scheme}: data:`,
"worker-src 'self' blob:",
"frame-src 'self' https://challenges.cloudflare.com",
"form-action 'self'",
].join("; ");
}
const registerDesktopSchemePrivileges = Effect.sync(() => {
Electron.protocol.registerSchemesAsPrivileged([
{
scheme: DESKTOP_SCHEME,
privileges: {
standard: true,
secure: true,
supportFetchAPI: true,
corsEnabled: true,
},
},
]);
}).pipe(Effect.withSpan("desktop.electron.protocol.registerSchemePrivileges"));
function withContentSecurityPolicy(response: Response, policy: string): Response {
const headers = new Headers(response.headers);
headers.set("Content-Security-Policy", policy);
return new Response(response.body, {
status: response.status,
statusText: response.statusText,
headers,
});
}
export const layerSchemePrivileges = Layer.effectDiscard(registerDesktopSchemePrivileges);
const resolveDesktopStaticDir: Effect.Effect<
Option.Option<string>,
never,
FileSystem.FileSystem | DesktopEnvironment
> = Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const environment = yield* DesktopEnvironment;
const candidates = [
environment.path.join(environment.appRoot, "apps/server/dist/client"),
environment.path.join(environment.appRoot, "apps/web/dist"),
];
for (const candidate of candidates) {
const hasIndex = yield* fileSystem
.exists(environment.path.join(candidate, "index.html"))
.pipe(Effect.orElseSucceed(() => false));
if (hasIndex) {
return Option.some(candidate);
}
async function proxyRequest(
request: Request,
targetOrigin: URL,
contentSecurityPolicy: string,
): Promise<Response> {
const requestUrl = new URL(request.url);
if (requestUrl.host !== DESKTOP_HOST) {
return new Response(null, { status: 404 });
}
return Option.none<string>();
});
const resolveDesktopStaticPath = Effect.fn("desktop.electron.protocol.resolveDesktopStaticPath")(
function* (
staticRoot: string,
requestUrl: string,
): Effect.fn.Return<string, never, FileSystem.FileSystem | DesktopEnvironment> {
const fileSystem = yield* FileSystem.FileSystem;
const environment = yield* DesktopEnvironment;
const url = new URL(requestUrl);
const rawPath = decodeURIComponent(url.pathname);
const normalizedPath = normalizeDesktopProtocolPathname(rawPath);
if (Option.isNone(normalizedPath)) {
return environment.path.join(staticRoot, "index.html");
}
const requestedPath = normalizedPath.value.length > 0 ? normalizedPath.value : "index.html";
const resolvedPath = environment.path.join(staticRoot, requestedPath);
if (environment.path.extname(resolvedPath)) {
return resolvedPath;
}
const nestedIndex = environment.path.join(resolvedPath, "index.html");
const nestedIndexExists = yield* fileSystem
.exists(nestedIndex)
.pipe(Effect.orElseSucceed(() => false));
if (nestedIndexExists) {
return nestedIndex;
}
return environment.path.join(staticRoot, "index.html");
},
);
function isStaticAssetRequest(requestUrl: string, environment: DesktopEnvironmentShape): boolean {
try {
const url = new URL(requestUrl);
return environment.path.extname(url.pathname).length > 0;
} catch {
return false;
const targetUrl = new URL(`${requestUrl.pathname}${requestUrl.search}`, targetOrigin);
const init: RequestInit = {
method: request.method,
headers: request.headers,
};
if (request.method !== "GET" && request.method !== "HEAD") {
init.body = request.body;
(init as RequestInit & { duplex: "half" }).duplex = "half";
}
const response = await Electron.net.fetch(targetUrl.toString(), init);
return withContentSecurityPolicy(response, contentSecurityPolicy);
}
const make = Effect.gen(function* () {
const registeredProtocols = yield* Ref.make<ReadonlySet<string>>(new Set());
const registered = yield* Ref.make(false);
const registerFileProtocol = Effect.fn("desktop.electron.protocol.registerFileProtocol")(
function* <E, R>({
scheme,
handler,
onFailure,
}: {
readonly scheme: string;
readonly handler: (
request: Electron.ProtocolRequest,
) => Effect.Effect<Electron.ProtocolResponse, E, R>;
readonly onFailure?: (
request: Electron.ProtocolRequest,
cause: Cause.Cause<E>,
) => Electron.ProtocolResponse;
}): Effect.fn.Return<void, ElectronProtocolRegistrationError, R | Scope.Scope> {
yield* Effect.annotateCurrentSpan({ scheme });
const alreadyRegistered = yield* Ref.get(registeredProtocols).pipe(
Effect.map((protocols) => protocols.has(scheme)),
);
if (alreadyRegistered) {
return;
}
const registerDesktopProtocol = Effect.fn("desktop.electron.protocol.registerDesktopProtocol")(
function* (input: DesktopProtocolRegistrationInput) {
if (yield* Ref.get(registered)) return;
const context = yield* Effect.context<R>();
const runPromise = Effect.runPromiseWith(context);
const contentSecurityPolicy = makeDesktopContentSecurityPolicy(input);
yield* Effect.acquireRelease(
Effect.try({
try: () => {
const registered = Electron.protocol.registerFileProtocol(
scheme,
(request, callback) => {
const response = handler(request).pipe(
Effect.withSpan("desktop.electron.protocol.handleFileRequest"),
Effect.catchCause((cause) =>
Effect.succeed(onFailure?.(request, cause) ?? ({ error: -2 } as const)),
),
);
void runPromise(response).then(callback, () => callback({ error: -2 }));
},
Electron.protocol.handle(input.scheme, (request) =>
proxyRequest(request, input.targetOrigin, contentSecurityPolicy),
);
if (!registered) {
throw new ElectronProtocolRegistrationError({
scheme,
cause: "registerFileProtocol returned false",
});
}
},
catch: (cause) =>
cause instanceof ElectronProtocolRegistrationError
? cause
: new ElectronProtocolRegistrationError({ scheme, cause }),
}).pipe(
Effect.andThen(
Ref.update(registeredProtocols, (protocols) => new Set(protocols).add(scheme)),
),
),
catch: (cause) => new ElectronProtocolRegistrationError({ scheme: input.scheme, cause }),
}).pipe(Effect.andThen(Ref.set(registered, true))),
() =>
Effect.sync(() => {
Electron.protocol.unregisterProtocol(scheme);
}).pipe(
Effect.andThen(
Ref.update(registeredProtocols, (protocols) => {
const next = new Set(protocols);
next.delete(scheme);
return next;
}),
),
),
Electron.protocol.unhandle(input.scheme);
}).pipe(Effect.andThen(Ref.set(registered, false))),
);
},
);
const registerDesktopFileProtocol = Effect.gen(function* () {
const environment = yield* DesktopEnvironment;
if (environment.isDevelopment) return;
const staticRoot = yield* resolveDesktopStaticDir;
if (Option.isNone(staticRoot)) {
return yield* new ElectronProtocolStaticBundleMissingError();
}
const staticRootResolved = environment.path.resolve(staticRoot.value);
const staticRootPrefix = `${staticRootResolved}${environment.path.sep}`;
const fallbackIndex = environment.path.join(staticRootResolved, "index.html");
yield* registerFileProtocol({
scheme: DESKTOP_SCHEME,
handler: Effect.fn("desktop.electron.protocol.handleDesktopFileRequest")(function* (request) {
const fileSystem = yield* FileSystem.FileSystem;
const environment = yield* DesktopEnvironment;
const candidate = yield* resolveDesktopStaticPath(staticRootResolved, request.url);
const resolvedCandidate = environment.path.resolve(candidate);
const isInRoot =
resolvedCandidate === fallbackIndex || resolvedCandidate.startsWith(staticRootPrefix);
const isAssetRequest = isStaticAssetRequest(request.url, environment);
const exists = yield* fileSystem
.exists(resolvedCandidate)
.pipe(Effect.orElseSucceed(() => false));
if (!isInRoot || !exists) {
return isAssetRequest ? ({ error: -6 } as const) : ({ path: fallbackIndex } as const);
}
return { path: resolvedCandidate } as const;
}),
onFailure: () => ({ path: fallbackIndex }),
});
}).pipe(Effect.withSpan("desktop.electron.protocol.registerDesktopFileProtocol"));
return ElectronProtocol.of({
registerFileProtocol,
registerDesktopFileProtocol,
});
return ElectronProtocol.of({ registerDesktopProtocol });
});
export const layer = Layer.effect(ElectronProtocol, make);
+2 -12
View File
@@ -1,13 +1,6 @@
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 {
clearConnectionCatalog,
@@ -40,6 +33,7 @@ import {
import {
confirm,
getAppBranding,
getLocalEnvironmentBearerToken,
getLocalEnvironmentBootstrap,
openExternal,
pickFolder,
@@ -54,6 +48,7 @@ export const installDesktopIpcHandlers = Effect.fn("desktop.ipc.installHandlers"
yield* ipc.handleSync(getAppBranding);
yield* ipc.handleSync(getLocalEnvironmentBootstrap);
yield* ipc.handle(getLocalEnvironmentBearerToken);
yield* ipc.handle(getClientSettings);
yield* ipc.handle(setClientSettings);
@@ -80,11 +75,6 @@ export const installDesktopIpcHandlers = Effect.fn("desktop.ipc.installHandlers"
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);
yield* ipc.handle(downloadUpdate);
+2 -6
View File
@@ -3,12 +3,6 @@ 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";
@@ -18,6 +12,8 @@ export const UPDATE_INSTALL_CHANNEL = "desktop:update-install";
export const UPDATE_CHECK_CHANNEL = "desktop:update-check";
export const GET_APP_BRANDING_CHANNEL = "desktop:get-app-branding";
export const GET_LOCAL_ENVIRONMENT_BOOTSTRAP_CHANNEL = "desktop:get-local-environment-bootstrap";
export const GET_LOCAL_ENVIRONMENT_BEARER_TOKEN_CHANNEL =
"desktop:get-local-environment-bearer-token";
export const GET_CLIENT_SETTINGS_CHANNEL = "desktop:get-client-settings";
export const SET_CLIENT_SETTINGS_CHANNEL = "desktop:set-client-settings";
export const GET_CONNECTION_CATALOG_CHANNEL = "desktop:get-connection-catalog";
@@ -1,97 +0,0 @@
import { assert, describe, it } from "@effect/vitest";
import * as Effect from "effect/Effect";
import { afterEach } from "vite-plus/test";
import { fetchCloudAuth, validateClerkFrontendApiUrl } from "./cloudAuth.ts";
const originalClerkPublishableKey = process.env.T3CODE_CLERK_PUBLISHABLE_KEY;
const originalFetch = globalThis.fetch;
const clerkPublishableKey = (hostname: string): string =>
`pk_test_${Buffer.from(`${hostname}$`).toString("base64")}`;
type FetchCall = readonly [input: RequestInfo | URL, init: RequestInit];
const recordedFetch = (...responses: ReadonlyArray<Response>) => {
const calls: Array<FetchCall> = [];
let responseIndex = 0;
const fetchFn = ((input, init) => {
calls.push([input, init ?? {}]);
const response = responses[responseIndex++];
if (!response) {
return Promise.reject(new Error("Unexpected fetch call"));
}
return Promise.resolve(response);
}) satisfies typeof fetch;
return { fetchFn, calls };
};
describe("Desktop cloud auth IPC", () => {
afterEach(() => {
globalThis.fetch = originalFetch;
if (originalClerkPublishableKey === undefined) {
delete process.env.T3CODE_CLERK_PUBLISHABLE_KEY;
} else {
process.env.T3CODE_CLERK_PUBLISHABLE_KEY = originalClerkPublishableKey;
}
});
it.effect("preserves Clerk's URL-encoded OAuth form content type", () => {
const body = "strategy=oauth_google&redirect_url=t3code%3A%2F%2Fauth%2Fcallback";
const fetch = recordedFetch(Response.json({ response: { object: "sign_in_attempt" } }));
globalThis.fetch = fetch.fetchFn;
return Effect.gen(function* () {
yield* fetchCloudAuth.handler({
url: "https://example.clerk.accounts.dev/v1/client/sign_ins",
method: "POST",
headers: {
"Content-Type": "application/x-www-form-urlencoded;charset=UTF-8",
"x-mobile": "1",
},
body,
});
const forwardedRequest = fetch.calls[0];
assert(forwardedRequest !== undefined);
const [url, init] = forwardedRequest;
assert.equal(String(url), "https://example.clerk.accounts.dev/v1/client/sign_ins");
assert.equal(init.method, "POST");
assert.equal(
new Headers(init.headers).get("content-type"),
"application/x-www-form-urlencoded;charset=UTF-8",
);
assert.equal(new TextDecoder().decode(init.body as Uint8Array), body);
});
});
it.effect(
"allows the custom Clerk Frontend API host encoded by the configured publishable key",
() => {
process.env.T3CODE_CLERK_PUBLISHABLE_KEY = clerkPublishableKey("clerk.t3.codes");
const fetch = recordedFetch(Response.json({ response: { object: "client" } }));
globalThis.fetch = fetch.fetchFn;
return Effect.gen(function* () {
yield* fetchCloudAuth.handler({
url: "https://clerk.t3.codes/v1/client",
method: "GET",
headers: {},
});
const forwardedRequest = fetch.calls[0];
assert(forwardedRequest !== undefined);
assert.equal(String(forwardedRequest[0]), "https://clerk.t3.codes/v1/client");
});
},
);
it("rejects arbitrary HTTPS hosts that are not configured Clerk Frontend API hosts", () => {
process.env.T3CODE_CLERK_PUBLISHABLE_KEY = clerkPublishableKey("clerk.t3.codes");
assert.throws(
() => validateClerkFrontendApiUrl("https://attacker.example/v1/client"),
/restricted to Clerk Frontend API HTTPS hosts/u,
);
});
});
-177
View File
@@ -1,177 +0,0 @@
import {
DesktopCloudAuthFetchInputSchema,
DesktopCloudAuthFetchResultSchema,
} from "@t3tools/contracts";
import {
clerkFrontendApiHostnameFromPublishableKey,
isAllowedClerkFrontendApiHostname,
} from "@t3tools/shared/relayAuth";
import * as Data from "effect/Data";
import * as Effect from "effect/Effect";
import { identity } from "effect/Function";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Schema from "effect/Schema";
import { FetchHttpClient, 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";
declare const __T3CODE_BUILD_CLERK_PUBLISHABLE_KEY__: string | undefined;
export class DesktopCloudAuthFetchError extends Data.TaggedError("DesktopCloudAuthFetchError")<{
readonly reason: string;
readonly cause?: unknown;
}> {
override get message() {
return this.reason;
}
}
function configuredClerkFrontendApiHostname(): string | null {
const publishableKey =
process.env.T3CODE_CLERK_PUBLISHABLE_KEY?.trim() ||
(typeof __T3CODE_BUILD_CLERK_PUBLISHABLE_KEY__ === "undefined"
? ""
: __T3CODE_BUILD_CLERK_PUBLISHABLE_KEY__.trim());
if (!publishableKey) return null;
return clerkFrontendApiHostnameFromPublishableKey(publishableKey);
}
const allowedClerkFrontendApiHosts = (hostname: string): boolean =>
isAllowedClerkFrontendApiHostname(hostname, configuredClerkFrontendApiHostname());
export 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;
}
function executeCloudAuthFetch(url: URL, input: typeof DesktopCloudAuthFetchInputSchema.Type) {
return Effect.gen(function* () {
const method = (input.method ?? "GET") as "GET" | "POST";
const headers = new Headers(input.headers);
const response = yield* HttpClientRequest.make(method)(url).pipe(
HttpClientRequest.setHeaders(Object.fromEntries(headers.entries())),
input.body === undefined
? identity
: HttpClientRequest.bodyText(input.body, headers.get("content-type") ?? undefined),
HttpClient.execute,
Effect.mapError(
(cause) =>
new DesktopCloudAuthFetchError({
reason: "Desktop cloud auth fetch failed to execute.",
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,
};
});
}
const electronNetFetchLayer = Layer.unwrap(
Effect.gen(function* () {
const electronFetch = yield* Effect.promise(async () => {
const electron = (await import("electron")) as {
readonly net?: { readonly fetch?: typeof globalThis.fetch };
};
return typeof electron.net?.fetch === "function"
? electron.net.fetch.bind(electron.net)
: null;
}).pipe(Effect.catchCause(() => Effect.succeed(null)));
if (!electronFetch) {
yield* Effect.logWarning(
"electron.net.fetch is not available, falling back to global fetch. This may cause unexpected errors.",
);
}
return FetchHttpClient.layer.pipe(
Layer.provide(Layer.succeed(FetchHttpClient.Fetch, electronFetch ?? globalThis.fetch)),
);
}),
);
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,
}),
});
return yield* executeCloudAuthFetch(url, input).pipe(Effect.provide(electronNetFetchLayer));
}),
});
+11
View File
@@ -10,6 +10,7 @@ import * as Option from "effect/Option";
import * as Schema from "effect/Schema";
import * as DesktopBackendManager from "../../backend/DesktopBackendManager.ts";
import * as DesktopLocalEnvironmentAuth from "../../backend/DesktopLocalEnvironmentAuth.ts";
import * as DesktopEnvironment from "../../app/DesktopEnvironment.ts";
import * as ElectronDialog from "../../electron/ElectronDialog.ts";
import * as ElectronMenu from "../../electron/ElectronMenu.ts";
@@ -64,6 +65,16 @@ export const getLocalEnvironmentBootstrap = makeSyncIpcMethod({
}),
});
export const getLocalEnvironmentBearerToken = makeIpcMethod({
channel: IpcChannels.GET_LOCAL_ENVIRONMENT_BEARER_TOKEN_CHANNEL,
payload: Schema.Void,
result: Schema.String,
handler: Effect.fn("desktop.ipc.window.getLocalEnvironmentBearerToken")(function* () {
const localAuth = yield* DesktopLocalEnvironmentAuth.DesktopLocalEnvironmentAuth;
return yield* localAuth.getBearerToken;
}),
});
export const pickFolder = makeIpcMethod({
channel: IpcChannels.PICK_FOLDER_CHANNEL,
payload: Schema.UndefinedOr(PickFolderOptionsSchema),
+19 -7
View File
@@ -27,13 +27,13 @@ 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 DesktopConnectionCatalogStore from "./app/DesktopConnectionCatalogStore.ts";
import * as DesktopClerk from "./app/DesktopClerk.ts";
import * as DesktopApplicationMenu from "./window/DesktopApplicationMenu.ts";
import * as DesktopAssets from "./app/DesktopAssets.ts";
import * as DesktopBackendConfiguration from "./backend/DesktopBackendConfiguration.ts";
import * as DesktopBackendManager from "./backend/DesktopBackendManager.ts";
import * as DesktopLocalEnvironmentAuth from "./backend/DesktopLocalEnvironmentAuth.ts";
import * as DesktopEnvironment from "./app/DesktopEnvironment.ts";
import * as DesktopLifecycle from "./app/DesktopLifecycle.ts";
import * as DesktopObservability from "./app/DesktopObservability.ts";
@@ -119,7 +119,6 @@ const desktopFoundationLayer = Layer.mergeAll(
DesktopAppSettings.layer,
DesktopClientSettings.layer,
DesktopConnectionCatalogStore.layer.pipe(Layer.provideMerge(DesktopSavedEnvironments.layer)),
DesktopCloudAuthTokenStore.layer,
DesktopAssets.layer,
DesktopObservability.layer,
).pipe(Layer.provideMerge(desktopEnvironmentLayer));
@@ -149,17 +148,30 @@ const desktopBackendLayer = DesktopBackendManager.layer.pipe(
Layer.provideMerge(desktopWindowLayer),
);
const desktopLocalEnvironmentAuthLayer = DesktopLocalEnvironmentAuth.layer.pipe(
Layer.provideMerge(desktopBackendLayer),
);
const desktopApplicationLayer = Layer.mergeAll(
DesktopLifecycle.layer,
DesktopApplicationMenu.layer,
DesktopCloudAuth.layer,
DesktopShellEnvironment.layer,
desktopSshLayer,
).pipe(Layer.provideMerge(DesktopUpdates.layer), Layer.provideMerge(desktopBackendLayer));
).pipe(
Layer.provideMerge(DesktopUpdates.layer),
Layer.provideMerge(desktopLocalEnvironmentAuthLayer),
);
const desktopRuntimeLayer = ElectronProtocol.layerSchemePrivileges.pipe(
Layer.flatMap(() =>
const desktopClerkLayer = DesktopClerk.layer.pipe(
Layer.provideMerge(desktopEnvironmentLayer),
Layer.provideMerge(NodeServices.layer),
Layer.provideMerge(ElectronApp.layer),
);
const desktopRuntimeLayer = desktopClerkLayer.pipe(
Layer.flatMap((clerkContext) =>
desktopApplicationLayer.pipe(
Layer.provideMerge(Layer.succeedContext(clerkContext)),
Layer.provideMerge(NodeServices.layer),
Layer.provideMerge(NodeHttpClient.layerUndici),
Layer.provideMerge(NetService.layer),
+5 -17
View File
@@ -4,10 +4,13 @@ import type {
DesktopPreviewRecordingFrame,
DesktopPreviewTabState,
} from "@t3tools/contracts";
import { exposeClerkBridge } from "@clerk/electron/preload";
import { contextBridge, ipcRenderer } from "electron";
import * as IpcChannels from "./ipc/channels.ts";
exposeClerkBridge({ passkeys: true });
function unwrapEnsureSshEnvironmentResult(result: unknown) {
if (
typeof result === "object" &&
@@ -39,6 +42,8 @@ contextBridge.exposeInMainWorld("desktopBridge", {
}
return result as ReturnType<DesktopBridge["getLocalEnvironmentBootstrap"]>;
},
getLocalEnvironmentBearerToken: () =>
ipcRenderer.invoke(IpcChannels.GET_LOCAL_ENVIRONMENT_BEARER_TOKEN_CHANNEL),
getClientSettings: () => ipcRenderer.invoke(IpcChannels.GET_CLIENT_SETTINGS_CHANNEL),
setClientSettings: (settings) =>
ipcRenderer.invoke(IpcChannels.SET_CLIENT_SETTINGS_CHANNEL, settings),
@@ -95,23 +100,6 @@ 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;
@@ -15,6 +15,7 @@ const clientSettings: ClientSettings = {
autoOpenPlanSidebar: false,
confirmThreadArchive: true,
confirmThreadDelete: false,
defaultRuntimeMode: "full-access",
dismissedProviderUpdateNotificationKeys: [],
diffIgnoreWhitespace: true,
diffWordWrap: true,
@@ -191,19 +191,19 @@ describe("DesktopWindow", () => {
it("recognizes only same-origin renderer navigations", () => {
assert.isTrue(
DesktopWindow.isSameOriginRendererNavigation({
applicationUrl: "http://127.0.0.1:3773/",
navigationUrl: "http://127.0.0.1:3773/settings/connections",
applicationUrl: "t3code://app/",
navigationUrl: "t3code://app/settings/connections",
}),
);
assert.isFalse(
DesktopWindow.isSameOriginRendererNavigation({
applicationUrl: "http://127.0.0.1:3773/",
applicationUrl: "t3code://app/",
navigationUrl: "https://accounts.microsoft.com/oauth",
}),
);
assert.isFalse(
DesktopWindow.isSameOriginRendererNavigation({
applicationUrl: "http://127.0.0.1:3773/",
applicationUrl: "t3code://app/",
navigationUrl: "not a url",
}),
);
@@ -231,7 +231,7 @@ describe("DesktopWindow", () => {
assert.equal(yield* Ref.get(createCount), 1);
assert.isTrue(createdWindowOptions[0]?.disableAutoHideCursor);
assert.deepEqual(fakeWindow.setAutoHideCursor.mock.calls, [[false]]);
assert.deepEqual(fakeWindow.loadURL.mock.calls[0], ["http://127.0.0.1:5733/"]);
assert.deepEqual(fakeWindow.loadURL.mock.calls[0], ["t3code-dev://app/"]);
assert.equal(fakeWindow.openDevTools.mock.calls.length, 1);
}).pipe(Effect.provide(layer));
}),
+7 -30
View File
@@ -1,5 +1,4 @@
import * as Context from "effect/Context";
import * as Data from "effect/Data";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
@@ -16,8 +15,8 @@ import * as ElectronMenu from "../electron/ElectronMenu.ts";
import * as ElectronShell from "../electron/ElectronShell.ts";
import * as ElectronTheme from "../electron/ElectronTheme.ts";
import * as ElectronWindow from "../electron/ElectronWindow.ts";
import { getDesktopUrl } from "../electron/ElectronProtocol.ts";
import * as IpcChannels from "../ipc/channels.ts";
import * as DesktopServerExposure from "../backend/DesktopServerExposure.ts";
const TITLEBAR_HEIGHT = 40;
const TITLEBAR_COLOR = "#01000000"; // #00000000 does not work correctly on Linux
@@ -32,7 +31,6 @@ type WindowTitleBarOptions = Pick<
type DesktopWindowRuntimeServices =
| DesktopEnvironment.DesktopEnvironment
| DesktopAssets.DesktopAssets
| DesktopServerExposure.DesktopServerExposure
| DesktopState.DesktopState
| ElectronMenu.ElectronMenu
| ElectronShell.ElectronShell
@@ -40,16 +38,7 @@ type DesktopWindowRuntimeServices =
| ElectronWindow.ElectronWindow
| PreviewManager.PreviewManager;
export class DesktopWindowDevServerUrlMissingError extends Data.TaggedError(
"DesktopWindowDevServerUrlMissingError",
)<{}> {
override get message() {
return "VITE_DEV_SERVER_URL is required in desktop development.";
}
}
export type DesktopWindowError =
| DesktopWindowDevServerUrlMissingError
| ElectronWindow.ElectronWindowCreateError
| PreviewManager.PreviewManagerError;
@@ -71,15 +60,6 @@ export class DesktopWindow extends Context.Service<DesktopWindow, DesktopWindowS
const { logInfo: logWindowInfo, logWarning: logWindowWarning } =
DesktopObservability.makeComponentLogger("desktop-window");
function resolveDesktopDevServerUrl(
environment: DesktopEnvironment.DesktopEnvironmentShape,
): Effect.Effect<string, DesktopWindowDevServerUrlMissingError> {
return Option.match(environment.devServerUrl, {
onNone: () => Effect.fail(new DesktopWindowDevServerUrlMissingError()),
onSome: (url) => Effect.succeed(url.href),
});
}
function getIconOption(
iconPaths: DesktopAssets.DesktopIconPaths,
platform: NodeJS.Platform,
@@ -171,18 +151,16 @@ const make = Effect.gen(function* () {
const electronTheme = yield* ElectronTheme.ElectronTheme;
const electronWindow = yield* ElectronWindow.ElectronWindow;
const previewManager = yield* PreviewManager.PreviewManager;
const serverExposure = yield* DesktopServerExposure.DesktopServerExposure;
const state = yield* DesktopState.DesktopState;
const context = yield* Effect.context<DesktopWindowRuntimeServices>();
const runPromise = Effect.runPromiseWith(context);
const createWindow = Effect.fn("desktop.window.createWindow")(function* (
backendHttpUrl: URL,
): Effect.fn.Return<Electron.BrowserWindow, DesktopWindowError> {
const createWindow = Effect.fn("desktop.window.createWindow")(function* (): Effect.fn.Return<
Electron.BrowserWindow,
DesktopWindowError
> {
yield* previewManager.getBrowserSession();
const applicationUrl = environment.isDevelopment
? yield* resolveDesktopDevServerUrl(environment)
: backendHttpUrl.href;
const applicationUrl = getDesktopUrl(environment.isDevelopment);
const iconPaths = yield* assets.iconPaths;
const iconOption = getIconOption(iconPaths, environment.platform);
const shouldUseDarkColors = yield* electronTheme.shouldUseDarkColors;
@@ -350,8 +328,7 @@ const make = Effect.gen(function* () {
});
const createMain = Effect.gen(function* () {
const backendConfig = yield* serverExposure.backendConfig;
const window = yield* createWindow(backendConfig.httpBaseUrl);
const window = yield* createWindow();
yield* electronWindow.setMain(window);
yield* logWindowInfo("main window created");
return window;
+6
View File
@@ -56,6 +56,12 @@ export default defineConfig({
outExtensions: () => ({ js: ".cjs" }),
define: publicConfigDefine,
entry: ["src/preload.ts"],
deps: {
// Sandboxed Electron preloads cannot reliably resolve package imports
// from inside the packaged ASAR. Bundle Clerk's preload bridge into the
// preload artifact instead of leaving a runtime require() behind.
alwaysBundle: (id) => id === "@clerk/electron" || id.startsWith("@clerk/electron/"),
},
},
{
format: "cjs",
+1 -1
View File
@@ -40,7 +40,7 @@
},
"dependencies": {
"@callstack/liquid-glass": "^0.7.1",
"@clerk/expo": "^3.4.1",
"@clerk/expo": "catalog:",
"@effect/atom-react": "catalog:",
"@expo-google-fonts/dm-sans": "^0.4.2",
"@expo/ui": "~56.0.8",
+5
View File
@@ -3,6 +3,7 @@ import {
CloudSession,
EnvironmentOwnedDataCleanup,
PlatformConnectionSource,
PrimaryEnvironmentAuth,
RelayDeviceIdentity,
SshEnvironmentGateway,
} from "@t3tools/client-runtime/platform";
@@ -119,6 +120,10 @@ const capabilitiesLayer = Layer.succeedContext(
}),
}),
).pipe(
Context.add(
PrimaryEnvironmentAuth,
PrimaryEnvironmentAuth.of({ bearerToken: Effect.succeed(Option.none()) }),
),
Context.add(
RelayDeviceIdentity,
RelayDeviceIdentity.of({
+23 -22
View File
@@ -1,10 +1,11 @@
import * as NodeServices from "@effect/platform-node/NodeServices";
import { expect, it } from "@effect/vitest";
import { assert, it } from "@effect/vitest";
import * as Cause from "effect/Cause";
import * as Deferred from "effect/Deferred";
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 Ref from "effect/Ref";
import * as PlatformError from "effect/PlatformError";
@@ -145,13 +146,13 @@ const makeConcurrentCreateSecretStoreLayer = () =>
);
it.layer(NodeServices.layer)("ServerSecretStore.layer", (it) => {
it.effect("returns null when a secret file does not exist", () =>
it.effect("returns Option.none when a secret file does not exist", () =>
Effect.gen(function* () {
const secretStore = yield* ServerSecretStore.ServerSecretStore;
const secret = yield* secretStore.get("missing-secret");
expect(secret).toBeNull();
assert.isTrue(Option.isNone(secret));
}).pipe(Effect.provide(makeServerSecretStoreLayer())),
);
@@ -162,7 +163,7 @@ it.layer(NodeServices.layer)("ServerSecretStore.layer", (it) => {
const first = yield* secretStore.getOrCreateRandom("session-signing-key", 32);
const second = yield* secretStore.getOrCreateRandom("session-signing-key", 32);
expect(Array.from(second)).toEqual(Array.from(first));
assert.deepEqual(Array.from(second), Array.from(first));
}).pipe(Effect.provide(makeServerSecretStoreLayer())),
);
@@ -178,10 +179,10 @@ it.layer(NodeServices.layer)("ServerSecretStore.layer", (it) => {
{ concurrency: "unbounded" },
);
const persisted = yield* secretStore.get("session-signing-key");
const persistedBytes = Option.getOrThrow(persisted);
expect(persisted).not.toBeNull();
expect(Array.from(first)).toEqual(Array.from(persisted ?? new Uint8Array()));
expect(Array.from(second)).toEqual(Array.from(persisted ?? new Uint8Array()));
assert.deepEqual(Array.from(first), Array.from(persistedBytes));
assert.deepEqual(Array.from(second), Array.from(persistedBytes));
}).pipe(Effect.provide(makeConcurrentCreateSecretStoreLayer())),
);
@@ -217,10 +218,10 @@ it.layer(NodeServices.layer)("ServerSecretStore.layer", (it) => {
yield* secretStore.set("session-signing-key", Uint8Array.from([1, 2, 3]));
expect(chmodCalls.some((call) => call.mode === 0o700 && call.path.endsWith("/secrets"))).toBe(
true,
assert.isTrue(
chmodCalls.some((call) => call.mode === 0o700 && call.path.endsWith("/secrets")),
);
expect(chmodCalls.filter((call) => call.mode === 0o600).length).toBeGreaterThanOrEqual(2);
assert.isAtLeast(chmodCalls.filter((call) => call.mode === 0o600).length, 2);
}).pipe(Effect.provide(NodeServices.layer)),
);
@@ -230,10 +231,10 @@ it.layer(NodeServices.layer)("ServerSecretStore.layer", (it) => {
const error = yield* Effect.flip(secretStore.getOrCreateRandom("session-signing-key", 32));
expect(error).toBeInstanceOf(ServerSecretStore.SecretStoreError);
expect(error.message).toContain("Failed to read secret session-signing-key.");
expect(error.cause).toBeInstanceOf(PlatformError.PlatformError);
expect((error.cause as PlatformError.PlatformError).reason._tag).toBe("PermissionDenied");
assert.instanceOf(error, ServerSecretStore.SecretStoreError);
assert.include(error.message, "Failed to read secret session-signing-key.");
assert.instanceOf(error.cause, PlatformError.PlatformError);
assert.equal((error.cause as PlatformError.PlatformError).reason._tag, "PermissionDenied");
}).pipe(Effect.provide(makePermissionDeniedSecretStoreLayer())),
);
@@ -245,10 +246,10 @@ it.layer(NodeServices.layer)("ServerSecretStore.layer", (it) => {
secretStore.set("session-signing-key", Uint8Array.from([1, 2, 3])),
);
expect(error).toBeInstanceOf(ServerSecretStore.SecretStoreError);
expect(error.message).toContain("Failed to persist secret session-signing-key.");
expect(error.cause).toBeInstanceOf(PlatformError.PlatformError);
expect((error.cause as PlatformError.PlatformError).reason._tag).toBe("PermissionDenied");
assert.instanceOf(error, ServerSecretStore.SecretStoreError);
assert.include(error.message, "Failed to persist secret session-signing-key.");
assert.instanceOf(error.cause, PlatformError.PlatformError);
assert.equal((error.cause as PlatformError.PlatformError).reason._tag, "PermissionDenied");
}).pipe(Effect.provide(makeRenameFailureSecretStoreLayer())),
);
@@ -258,10 +259,10 @@ it.layer(NodeServices.layer)("ServerSecretStore.layer", (it) => {
const error = yield* Effect.flip(secretStore.remove("session-signing-key"));
expect(error).toBeInstanceOf(ServerSecretStore.SecretStoreError);
expect(error.message).toContain("Failed to remove secret session-signing-key.");
expect(error.cause).toBeInstanceOf(PlatformError.PlatformError);
expect((error.cause as PlatformError.PlatformError).reason._tag).toBe("PermissionDenied");
assert.instanceOf(error, ServerSecretStore.SecretStoreError);
assert.include(error.message, "Failed to remove secret session-signing-key.");
assert.instanceOf(error.cause, PlatformError.PlatformError);
assert.equal((error.cause as PlatformError.PlatformError).reason._tag, "PermissionDenied");
}).pipe(Effect.provide(makeRemoveFailureSecretStoreLayer())),
);
});
+47 -41
View File
@@ -1,19 +1,23 @@
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 FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Path from "effect/Path";
import * as Predicate from "effect/Predicate";
import * as PlatformError from "effect/PlatformError";
import * as Schema from "effect/Schema";
import { ServerConfig } from "../config.ts";
export class SecretStoreError extends Data.TaggedError("SecretStoreError")<{
readonly message: string;
readonly cause?: unknown;
}> {}
export class SecretStoreError extends Schema.TaggedErrorClass<SecretStoreError>()(
"SecretStoreError",
{
message: Schema.String,
cause: Schema.optional(Schema.Defect()),
},
) {}
const isPlatformError = (value: unknown): value is PlatformError.PlatformError =>
Predicate.isTagged(value, "PlatformError");
@@ -22,7 +26,7 @@ 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 get: (name: string) => Effect.Effect<Option.Option<Uint8Array>, SecretStoreError>;
readonly set: (name: string, value: Uint8Array) => Effect.Effect<void, SecretStoreError>;
readonly create: (name: string, value: Uint8Array) => Effect.Effect<void, SecretStoreError>;
readonly getOrCreateRandom: (
@@ -57,10 +61,10 @@ export const make = Effect.fn("makeServerSecretStore")(function* () {
const get: ServerSecretStoreShape["get"] = (name) =>
fileSystem.readFile(resolveSecretPath(name)).pipe(
Effect.map((bytes) => Uint8Array.from(bytes)),
Effect.map((bytes) => Option.some(Uint8Array.from(bytes))),
Effect.catch((cause) =>
cause.reason._tag === "NotFound"
? Effect.succeed(null)
? Effect.succeed(Option.none())
: Effect.fail(
new SecretStoreError({
message: `Failed to read secret ${name}.`,
@@ -133,41 +137,43 @@ export const make = Effect.fn("makeServerSecretStore")(function* () {
const getOrCreateRandom: ServerSecretStoreShape["getOrCreateRandom"] = (name, bytes) =>
get(name).pipe(
Effect.flatMap((existing) => {
if (existing) {
return Effect.succeed(existing);
}
return crypto.randomBytes(bytes).pipe(
Effect.mapError(
(cause) =>
new SecretStoreError({
message: `Failed to generate random bytes for secret ${name}.`,
cause,
}),
),
Effect.flatMap((generated) =>
create(name, generated).pipe(
Effect.as(Uint8Array.from(generated)),
Effect.catchTag("SecretStoreError", (error) =>
isSecretAlreadyExistsError(error)
? get(name).pipe(
Effect.flatMap((created) =>
created !== null
? Effect.succeed(created)
: Effect.fail(
new SecretStoreError({
message: `Failed to read secret ${name} after concurrent creation.`,
}),
),
),
)
: Effect.fail(error),
Effect.flatMap(
Option.match({
onSome: Effect.succeed,
onNone: () =>
crypto.randomBytes(bytes).pipe(
Effect.mapError(
(cause) =>
new SecretStoreError({
message: `Failed to generate random bytes for secret ${name}.`,
cause,
}),
),
Effect.flatMap((generated) =>
create(name, generated).pipe(
Effect.as(Uint8Array.from(generated)),
Effect.catchTag("SecretStoreError", (error) =>
isSecretAlreadyExistsError(error)
? get(name).pipe(
Effect.flatMap(
Option.match({
onSome: Effect.succeed,
onNone: () =>
Effect.fail(
new SecretStoreError({
message: `Failed to read secret ${name} after concurrent creation.`,
}),
),
}),
),
)
: Effect.fail(error),
),
),
),
),
),
);
}),
}),
),
Effect.withSpan("ServerSecretStore.getOrCreateRandom"),
);
+3 -3
View File
@@ -385,9 +385,9 @@ const connectStatusCommand = Command.make("status", {
const status: CloudCliStatus = {
desired,
authenticated,
linked: cloudUserId !== null,
cloudUserId: cloudUserId ? bytesToString(cloudUserId) : null,
relayUrl: relayUrl ? bytesToString(relayUrl) : null,
linked: Option.isSome(cloudUserId),
cloudUserId: Option.isSome(cloudUserId) ? bytesToString(cloudUserId.value) : null,
relayUrl: Option.isSome(relayUrl) ? bytesToString(relayUrl.value) : null,
relayClient: executable,
};
yield* Console.log(formatCloudStatus(status, { json: flags.json }));
+6 -5
View File
@@ -1,7 +1,8 @@
import * as NodeServices from "@effect/platform-node/NodeServices";
import { expect, it } from "@effect/vitest";
import { assert, it } from "@effect/vitest";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
import { ServerConfig } from "../config.ts";
@@ -40,18 +41,18 @@ it.layer(NodeServices.layer)("CliState", (it) => {
Effect.gen(function* () {
const secrets = yield* ServerSecretStore.ServerSecretStore;
expect(yield* CliState.readCliDesiredCloudLink).toBe(false);
assert.isFalse(yield* CliState.readCliDesiredCloudLink);
yield* CliState.setCliDesiredCloudLink(true);
expect(yield* CliState.readCliDesiredCloudLink).toBe(true);
assert.isTrue(yield* CliState.readCliDesiredCloudLink);
for (const name of persistedCloudLinkSecrets) {
yield* secrets.set(name, new TextEncoder().encode(name));
}
yield* CliState.clearPersistedCloudLink;
expect(yield* CliState.readCliDesiredCloudLink).toBe(false);
assert.isFalse(yield* CliState.readCliDesiredCloudLink);
for (const name of persistedCloudLinkSecrets) {
expect(yield* secrets.get(name)).toBe(null);
assert.isTrue(Option.isNone(yield* secrets.get(name)));
}
}).pipe(Effect.provide(makeTestLayer())),
);
+2 -1
View File
@@ -1,4 +1,5 @@
import * as Effect from "effect/Effect";
import * as Option from "effect/Option";
import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
import {
@@ -17,7 +18,7 @@ const TRUE_BYTES = new TextEncoder().encode("true");
export const readCliDesiredCloudLink = Effect.gen(function* () {
const secrets = yield* ServerSecretStore.ServerSecretStore;
return (yield* secrets.get(CLOUD_CLI_DESIRED_LINK_SECRET)) !== null;
return Option.isSome(yield* secrets.get(CLOUD_CLI_DESIRED_LINK_SECRET));
});
export const setCliDesiredCloudLink = Effect.fn("cloud.cli_state.set_desired")(function* (
+2 -2
View File
@@ -100,8 +100,8 @@ const make = Effect.gen(function* () {
const read = Effect.fn("cloud.cli_token.read")(function* () {
const encoded = yield* secrets.get(CLOUD_CLI_OAUTH_TOKEN_SECRET);
if (!encoded) return Option.none<PersistedToken>();
return Option.some(yield* decodePersistedToken(bytesToString(encoded)));
if (Option.isNone(encoded)) return Option.none<PersistedToken>();
return Option.some(yield* decodePersistedToken(bytesToString(encoded.value)));
});
const exchangeToken = Effect.fn("cloud.cli_token.exchange")(function* (
@@ -22,10 +22,10 @@ function bytesToString(bytes: Uint8Array): string {
const readRuntimeConfig = Effect.gen(function* () {
const secrets = yield* ServerSecretStore.ServerSecretStore;
const bytes = yield* secrets.get(CLOUD_ENDPOINT_RUNTIME_CONFIG);
if (!bytes) {
if (Option.isNone(bytes)) {
return null;
}
return Option.getOrNull(decodeRuntimeConfig(bytesToString(bytes)));
return Option.getOrNull(decodeRuntimeConfig(bytesToString(bytes.value)));
});
export interface CloudManagedEndpointRuntimeShape {
+12 -9
View File
@@ -1,7 +1,8 @@
import * as NodeServices from "@effect/platform-node/NodeServices";
import { expect, it } from "@effect/vitest";
import { assert, it } from "@effect/vitest";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as PlatformError from "effect/PlatformError";
import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
@@ -23,10 +24,10 @@ it.layer(NodeServices.layer)("getOrCreateEnvironmentKeyPairFromSecretStore", (it
const first = yield* getOrCreateEnvironmentKeyPairFromSecretStore(secretStore);
const second = yield* getOrCreateEnvironmentKeyPairFromSecretStore(secretStore);
expect(second).toEqual(first);
expect(yield* secretStore.get("cloud-link-ed25519-key-pair")).not.toBeNull();
expect(yield* secretStore.get("cloud-link-ed25519-private-key")).toBeNull();
expect(yield* secretStore.get("cloud-link-ed25519-public-key")).toBeNull();
assert.deepEqual(second, first);
assert.isTrue(Option.isSome(yield* secretStore.get("cloud-link-ed25519-key-pair")));
assert.isTrue(Option.isNone(yield* secretStore.get("cloud-link-ed25519-private-key")));
assert.isTrue(Option.isNone(yield* secretStore.get("cloud-link-ed25519-public-key")));
}).pipe(Effect.provide(makeServerSecretStoreLayer())),
);
@@ -36,11 +37,11 @@ it.layer(NodeServices.layer)("getOrCreateEnvironmentKeyPairFromSecretStore", (it
yield* secretStore.set("cloud-link-ed25519-private-key", new TextEncoder().encode("private"));
yield* secretStore.set("cloud-link-ed25519-public-key", new TextEncoder().encode("public"));
expect(yield* getOrCreateEnvironmentKeyPairFromSecretStore(secretStore)).toEqual({
assert.deepEqual(yield* getOrCreateEnvironmentKeyPairFromSecretStore(secretStore), {
privateKey: "private",
publicKey: "public",
});
expect(yield* secretStore.get("cloud-link-ed25519-key-pair")).not.toBeNull();
assert.isTrue(Option.isSome(yield* secretStore.get("cloud-link-ed25519-key-pair")));
}).pipe(Effect.provide(makeServerSecretStoreLayer())),
);
@@ -53,7 +54,9 @@ it.layer(NodeServices.layer)("getOrCreateEnvironmentKeyPairFromSecretStore", (it
const secretStore = {
get: (name) =>
Effect.sync(() =>
name === "cloud-link-ed25519-key-pair" && createAttempted ? winner : null,
name === "cloud-link-ed25519-key-pair" && createAttempted
? Option.some(winner)
: Option.none(),
),
set: unusedSecretStoreOperation,
create: () =>
@@ -78,7 +81,7 @@ it.layer(NodeServices.layer)("getOrCreateEnvironmentKeyPairFromSecretStore", (it
remove: unusedSecretStoreOperation,
} satisfies ServerSecretStore.ServerSecretStoreShape;
expect(yield* getOrCreateEnvironmentKeyPairFromSecretStore(secretStore)).toEqual({
assert.deepEqual(yield* getOrCreateEnvironmentKeyPairFromSecretStore(secretStore), {
privateKey: "winner-private",
publicKey: "winner-public",
});
+16 -12
View File
@@ -1,5 +1,6 @@
import * as NodeCrypto from "node:crypto";
import * as Effect from "effect/Effect";
import * as Option from "effect/Option";
import * as Schema from "effect/Schema";
import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
@@ -33,14 +34,15 @@ const readEnvironmentKeyPair = Effect.fn("readEnvironmentKeyPair")(function* (
secrets: ServerSecretStore.ServerSecretStoreShape,
) {
const encoded = yield* secrets.get(CLOUD_LINK_KEY_PAIR);
if (encoded === null) {
return null;
if (Option.isNone(encoded)) {
return Option.none<EnvironmentKeyPair>();
}
return yield* decodeEnvironmentKeyPair(bytesToString(encoded)).pipe(
const decoded = yield* decodeEnvironmentKeyPair(bytesToString(encoded.value)).pipe(
Effect.mapError((cause) =>
keyPairPersistenceError("Failed to decode environment signing key pair.", cause),
),
);
return Option.some(decoded);
});
const persistEnvironmentKeyPair = Effect.fn("persistEnvironmentKeyPair")(function* (
@@ -57,14 +59,16 @@ const persistEnvironmentKeyPair = Effect.fn("persistEnvironmentKeyPair")(functio
Effect.catchTag("SecretStoreError", (error) =>
ServerSecretStore.isSecretAlreadyExistsError(error)
? readEnvironmentKeyPair(secrets).pipe(
Effect.flatMap((existing) =>
existing !== null
? Effect.succeed(existing)
: Effect.fail(
Effect.flatMap(
Option.match({
onSome: Effect.succeed,
onNone: () =>
Effect.fail(
keyPairPersistenceError(
"Failed to read environment signing key pair after concurrent creation.",
),
),
}),
),
)
: Effect.fail(error),
@@ -76,16 +80,16 @@ export const getOrCreateEnvironmentKeyPairFromSecretStore = Effect.fn(function*
secrets: ServerSecretStore.ServerSecretStoreShape,
) {
const existing = yield* readEnvironmentKeyPair(secrets);
if (existing !== null) {
return existing;
if (Option.isSome(existing)) {
return existing.value;
}
const existingPrivate = yield* secrets.get(CLOUD_LINK_PRIVATE_KEY);
const existingPublic = yield* secrets.get(CLOUD_LINK_PUBLIC_KEY);
if (existingPrivate && existingPublic) {
if (Option.isSome(existingPrivate) && Option.isSome(existingPublic)) {
return yield* persistEnvironmentKeyPair(secrets, {
privateKey: bytesToString(existingPrivate),
publicKey: bytesToString(existingPublic),
privateKey: bytesToString(existingPrivate.value),
publicKey: bytesToString(existingPublic.value),
});
}
+22 -22
View File
@@ -220,10 +220,10 @@ function validateLinkedCloudUser(input: {
}),
),
Effect.flatMap((existing) => {
if (!existing) {
if (Option.isNone(existing)) {
return Effect.void;
}
const existingCloudUserId = bytesToString(existing);
const existingCloudUserId = bytesToString(existing.value);
return existingCloudUserId === input.cloudUserId
? Effect.void
: Effect.fail(
@@ -248,8 +248,8 @@ function readInstalledCloudUserId(
}),
),
Effect.flatMap((bytes) =>
bytes
? Effect.succeed(bytesToString(bytes))
Option.isSome(bytes)
? Effect.succeed(bytesToString(bytes.value))
: Effect.fail(
new EnvironmentAuth.ServerAuthInternalError({
message: "Cloud linked user is not installed for this environment.",
@@ -622,12 +622,12 @@ const readCloudLinkState = Effect.fn("environment.cloud.readLinkState")(function
{ concurrency: 4 },
);
return {
linked: cloudUserId !== null,
cloudUserId: cloudUserId ? bytesToString(cloudUserId) : null,
relayUrl: relayUrl ? bytesToString(relayUrl) : null,
relayIssuer: relayIssuer ? bytesToString(relayIssuer) : null,
publishAgentActivity: publishAgentActivity
? bytesToString(publishAgentActivity) === "true"
linked: Option.isSome(cloudUserId),
cloudUserId: Option.isSome(cloudUserId) ? bytesToString(cloudUserId.value) : null,
relayUrl: Option.isSome(relayUrl) ? bytesToString(relayUrl.value) : null,
relayIssuer: Option.isSome(relayIssuer) ? bytesToString(relayIssuer.value) : null,
publishAgentActivity: Option.isSome(publishAgentActivity)
? bytesToString(publishAgentActivity.value) === "true"
: false,
} satisfies EnvironmentCloudLinkStateResult;
});
@@ -690,8 +690,8 @@ const cloudEnvironmentHealthHandler = Effect.fn("environment.cloud.health")(
function* (dependencies: CloudHttpDependencies, request: RelayCloudEnvironmentHealthRequest) {
const cloudMintPublicKey = yield* dependencies.secrets.get(CLOUD_MINT_PUBLIC_KEY).pipe(
Effect.flatMap((bytes) =>
bytes
? Effect.succeed(bytesToString(bytes))
Option.isSome(bytes)
? Effect.succeed(bytesToString(bytes.value))
: Effect.fail(
new EnvironmentAuth.ServerAuthInternalError({
message: "Cloud mint public key is not installed for this environment.",
@@ -701,12 +701,12 @@ const cloudEnvironmentHealthHandler = Effect.fn("environment.cloud.health")(
);
const relayIssuer = yield* dependencies.secrets.get(RELAY_ISSUER_SECRET).pipe(
Effect.flatMap((bytes) =>
bytes
? Effect.succeed(bytesToString(bytes))
Option.isSome(bytes)
? Effect.succeed(bytesToString(bytes.value))
: dependencies.secrets.get(RELAY_URL_SECRET).pipe(
Effect.flatMap((fallbackBytes) =>
fallbackBytes
? Effect.succeed(bytesToString(fallbackBytes))
Option.isSome(fallbackBytes)
? Effect.succeed(bytesToString(fallbackBytes.value))
: Effect.fail(
new EnvironmentAuth.ServerAuthInternalError({
message: "Cloud relay issuer is not installed for this environment.",
@@ -807,8 +807,8 @@ const cloudMintCredentialHandler = Effect.fn("environment.cloud.mintCredential")
function* (dependencies: CloudHttpDependencies, request: RelayCloudMintCredentialRequest) {
const cloudMintPublicKey = yield* dependencies.secrets.get(CLOUD_MINT_PUBLIC_KEY).pipe(
Effect.flatMap((bytes) =>
bytes
? Effect.succeed(bytesToString(bytes))
Option.isSome(bytes)
? Effect.succeed(bytesToString(bytes.value))
: Effect.fail(
new EnvironmentAuth.ServerAuthInternalError({
message: "Cloud mint public key is not installed for this environment.",
@@ -818,12 +818,12 @@ const cloudMintCredentialHandler = Effect.fn("environment.cloud.mintCredential")
);
const relayIssuer = yield* dependencies.secrets.get(RELAY_ISSUER_SECRET).pipe(
Effect.flatMap((bytes) =>
bytes
? Effect.succeed(bytesToString(bytes))
Option.isSome(bytes)
? Effect.succeed(bytesToString(bytes.value))
: dependencies.secrets.get(RELAY_URL_SECRET).pipe(
Effect.flatMap((fallbackBytes) =>
fallbackBytes
? Effect.succeed(bytesToString(fallbackBytes))
Option.isSome(fallbackBytes)
? Effect.succeed(bytesToString(fallbackBytes.value))
: Effect.fail(
new EnvironmentAuth.ServerAuthInternalError({
message: "Cloud relay issuer is not installed for this environment.",
@@ -20,12 +20,12 @@ import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Path from "effect/Path";
import * as Schema from "effect/Schema";
import * as Stream from "effect/Stream";
import { HttpClient } from "effect/unstable/http";
import { ChildProcessSpawner } from "effect/unstable/process";
import { makeClaudeTextGeneration } from "../../textGeneration/ClaudeTextGeneration.ts";
import { ServerConfig } from "../../config.ts";
import { ServerSettingsService } from "../../serverSettings.ts";
import { ProviderDriverError } from "../Errors.ts";
import { makeClaudeAdapter } from "../Layers/ClaudeAdapter.ts";
import {
@@ -48,6 +48,11 @@ import {
normalizeCommandPath,
resolveProviderMaintenanceCapabilitiesEffect,
} from "../providerMaintenance.ts";
import {
haveProviderSnapshotSettingsChanged,
makeProviderSnapshotSettingsSource,
type ProviderSnapshotSettings,
} from "../providerUpdateSettings.ts";
import { makeClaudeCapabilitiesCacheKey, makeClaudeContinuationGroupKey } from "./ClaudeHome.ts";
const decodeClaudeSettings = Schema.decodeSync(ClaudeSettings);
@@ -83,7 +88,8 @@ export type ClaudeDriverEnv =
| HttpClient.HttpClient
| Path.Path
| ProviderEventLoggers
| ServerConfig;
| ServerConfig
| ServerSettingsService;
const withInstanceIdentity =
(input: {
@@ -114,6 +120,7 @@ export const ClaudeDriver: ProviderDriver<ClaudeSettings, ClaudeDriverEnv> = {
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
const path = yield* Path.Path;
const httpClient = yield* HttpClient.HttpClient;
const serverSettings = yield* ServerSettingsService;
const eventLoggers = yield* ProviderEventLoggers;
const processEnv = mergeProviderInstanceEnvironment(environment);
const fallbackContinuationIdentity = defaultProviderContinuationIdentity({
@@ -163,16 +170,19 @@ export const ClaudeDriver: ProviderDriver<ClaudeSettings, ClaudeDriverEnv> = {
Effect.provideService(Path.Path, path),
);
const snapshot = yield* makeManagedServerProvider<ClaudeSettings>({
const snapshotSettings = makeProviderSnapshotSettingsSource(effectiveConfig, serverSettings);
const snapshot = yield* makeManagedServerProvider<ProviderSnapshotSettings<ClaudeSettings>>({
maintenanceCapabilities,
getSettings: Effect.succeed(effectiveConfig),
streamSettings: Stream.never,
haveSettingsChanged: () => false,
getSettings: snapshotSettings.getSettings,
streamSettings: snapshotSettings.streamSettings,
haveSettingsChanged: haveProviderSnapshotSettingsChanged,
initialSnapshot: (settings) =>
makePendingClaudeProvider(settings).pipe(Effect.map(stampIdentity)),
makePendingClaudeProvider(settings.provider).pipe(Effect.map(stampIdentity)),
checkProvider,
enrichSnapshot: ({ snapshot, publishSnapshot }) =>
enrichProviderSnapshotWithVersionAdvisory(snapshot, maintenanceCapabilities).pipe(
enrichSnapshot: ({ settings, snapshot, publishSnapshot }) =>
enrichProviderSnapshotWithVersionAdvisory(snapshot, maintenanceCapabilities, {
enableProviderUpdateChecks: settings.enableProviderUpdateChecks,
}).pipe(
Effect.provideService(HttpClient.HttpClient, httpClient),
Effect.flatMap((enrichedSnapshot) => publishSnapshot(enrichedSnapshot)),
),
@@ -28,12 +28,12 @@ import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Path from "effect/Path";
import * as Schema from "effect/Schema";
import * as Stream from "effect/Stream";
import { HttpClient } from "effect/unstable/http";
import { ChildProcessSpawner } from "effect/unstable/process";
import { makeCodexTextGeneration } from "../../textGeneration/CodexTextGeneration.ts";
import { ServerConfig } from "../../config.ts";
import { ServerSettingsService } from "../../serverSettings.ts";
import { ProviderDriverError } from "../Errors.ts";
import { makeCodexAdapter } from "../Layers/CodexAdapter.ts";
import { checkCodexProviderStatus, makePendingCodexProvider } from "../Layers/CodexProvider.ts";
@@ -47,6 +47,11 @@ import {
makePackageManagedProviderMaintenanceResolver,
resolveProviderMaintenanceCapabilitiesEffect,
} from "../providerMaintenance.ts";
import {
haveProviderSnapshotSettingsChanged,
makeProviderSnapshotSettingsSource,
type ProviderSnapshotSettings,
} from "../providerUpdateSettings.ts";
import {
codexContinuationIdentity,
materializeCodexShadowHome,
@@ -75,7 +80,8 @@ export type CodexDriverEnv =
| HttpClient.HttpClient
| Path.Path
| ProviderEventLoggers
| ServerConfig;
| ServerConfig
| ServerSettingsService;
/**
* Stamp instance identity onto a `ServerProvider` snapshot produced by the
@@ -111,6 +117,7 @@ export const CodexDriver: ProviderDriver<CodexSettings, CodexDriverEnv> = {
Effect.gen(function* () {
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
const httpClient = yield* HttpClient.HttpClient;
const serverSettings = yield* ServerSettingsService;
const eventLoggers = yield* ProviderEventLoggers;
const processEnv = mergeProviderInstanceEnvironment(environment);
const homeLayout = yield* resolveCodexHomeLayout(config);
@@ -163,16 +170,19 @@ export const CodexDriver: ProviderDriver<CodexSettings, CodexDriverEnv> = {
Effect.map(stampIdentity),
Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
);
const snapshot = yield* makeManagedServerProvider<CodexSettings>({
const snapshotSettings = makeProviderSnapshotSettingsSource(effectiveConfig, serverSettings);
const snapshot = yield* makeManagedServerProvider<ProviderSnapshotSettings<CodexSettings>>({
maintenanceCapabilities,
getSettings: Effect.succeed(effectiveConfig),
streamSettings: Stream.never,
haveSettingsChanged: () => false,
getSettings: snapshotSettings.getSettings,
streamSettings: snapshotSettings.streamSettings,
haveSettingsChanged: haveProviderSnapshotSettingsChanged,
initialSnapshot: (settings) =>
makePendingCodexProvider(settings).pipe(Effect.map(stampIdentity)),
makePendingCodexProvider(settings.provider).pipe(Effect.map(stampIdentity)),
checkProvider,
enrichSnapshot: ({ snapshot, publishSnapshot }) =>
enrichProviderSnapshotWithVersionAdvisory(snapshot, maintenanceCapabilities).pipe(
enrichSnapshot: ({ settings, snapshot, publishSnapshot }) =>
enrichProviderSnapshotWithVersionAdvisory(snapshot, maintenanceCapabilities, {
enableProviderUpdateChecks: settings.enableProviderUpdateChecks,
}).pipe(
Effect.provideService(HttpClient.HttpClient, httpClient),
Effect.flatMap((enrichedSnapshot) => publishSnapshot(enrichedSnapshot)),
),
@@ -18,11 +18,11 @@ import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Path from "effect/Path";
import * as Schema from "effect/Schema";
import * as Stream from "effect/Stream";
import { HttpClient } from "effect/unstable/http";
import { ChildProcessSpawner } from "effect/unstable/process";
import { ServerConfig } from "../../config.ts";
import { ServerSettingsService } from "../../serverSettings.ts";
import { makeCursorTextGeneration } from "../../textGeneration/CursorTextGeneration.ts";
import { ProviderDriverError } from "../Errors.ts";
import { makeCursorAdapter } from "../Layers/CursorAdapter.ts";
@@ -45,6 +45,11 @@ import {
makeStaticProviderMaintenanceResolver,
resolveProviderMaintenanceCapabilitiesEffect,
} from "../providerMaintenance.ts";
import {
haveProviderSnapshotSettingsChanged,
makeProviderSnapshotSettingsSource,
type ProviderSnapshotSettings,
} from "../providerUpdateSettings.ts";
const decodeCursorSettings = Schema.decodeSync(CursorSettings);
const DRIVER_KIND = ProviderDriverKind.make("cursor");
@@ -66,7 +71,8 @@ export type CursorDriverEnv =
| HttpClient.HttpClient
| Path.Path
| ProviderEventLoggers
| ServerConfig;
| ServerConfig
| ServerSettingsService;
const withInstanceIdentity =
(input: {
@@ -98,6 +104,7 @@ export const CursorDriver: ProviderDriver<CursorSettings, CursorDriverEnv> = {
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const httpClient = yield* HttpClient.HttpClient;
const serverSettings = yield* ServerSettingsService;
const eventLoggers = yield* ProviderEventLoggers;
const processEnv = mergeProviderInstanceEnvironment(environment);
const continuationIdentity = defaultProviderContinuationIdentity({
@@ -130,21 +137,23 @@ export const CursorDriver: ProviderDriver<CursorSettings, CursorDriverEnv> = {
Effect.provideService(Path.Path, path),
);
const snapshot = yield* makeManagedServerProvider<CursorSettings>({
const snapshotSettings = makeProviderSnapshotSettingsSource(effectiveConfig, serverSettings);
const snapshot = yield* makeManagedServerProvider<ProviderSnapshotSettings<CursorSettings>>({
maintenanceCapabilities,
getSettings: Effect.succeed(effectiveConfig),
streamSettings: Stream.never,
haveSettingsChanged: () => false,
getSettings: snapshotSettings.getSettings,
streamSettings: snapshotSettings.streamSettings,
haveSettingsChanged: haveProviderSnapshotSettingsChanged,
initialSnapshot: (settings) =>
buildInitialCursorProviderSnapshot(settings).pipe(Effect.map(stampIdentity)),
buildInitialCursorProviderSnapshot(settings.provider).pipe(Effect.map(stampIdentity)),
checkProvider,
// Model catalog and capabilities come exclusively from Cursor's
// list_available_models extension method during provider checks.
enrichSnapshot: ({ settings, snapshot: currentSnapshot, publishSnapshot }) =>
enrichCursorSnapshot({
settings,
settings: settings.provider,
snapshot: currentSnapshot,
maintenanceCapabilities,
enableProviderUpdateChecks: settings.enableProviderUpdateChecks,
publishSnapshot,
stampIdentity,
httpClient,
+17 -8
View File
@@ -5,11 +5,11 @@ import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Path from "effect/Path";
import * as Schema from "effect/Schema";
import * as Stream from "effect/Stream";
import { HttpClient } from "effect/unstable/http";
import { ChildProcessSpawner } from "effect/unstable/process";
import { ServerConfig } from "../../config.ts";
import { ServerSettingsService } from "../../serverSettings.ts";
import { makeGrokTextGeneration } from "../../textGeneration/GrokTextGeneration.ts";
import { ProviderDriverError } from "../Errors.ts";
import { makeGrokAdapter } from "../Layers/GrokAdapter.ts";
@@ -32,6 +32,11 @@ import {
makeStaticProviderMaintenanceResolver,
resolveProviderMaintenanceCapabilitiesEffect,
} from "../providerMaintenance.ts";
import {
haveProviderSnapshotSettingsChanged,
makeProviderSnapshotSettingsSource,
type ProviderSnapshotSettings,
} from "../providerUpdateSettings.ts";
const decodeGrokSettings = Schema.decodeSync(GrokSettings);
const DRIVER_KIND = ProviderDriverKind.make("grok");
@@ -50,7 +55,8 @@ export type GrokDriverEnv =
| HttpClient.HttpClient
| Path.Path
| ProviderEventLoggers
| ServerConfig;
| ServerConfig
| ServerSettingsService;
const withInstanceIdentity =
(input: {
@@ -80,6 +86,7 @@ export const GrokDriver: ProviderDriver<GrokSettings, GrokDriverEnv> = {
Effect.gen(function* () {
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
const httpClient = yield* HttpClient.HttpClient;
const serverSettings = yield* ServerSettingsService;
const eventLoggers = yield* ProviderEventLoggers;
const processEnv = mergeProviderInstanceEnvironment(environment);
const continuationIdentity = defaultProviderContinuationIdentity({
@@ -110,18 +117,20 @@ export const GrokDriver: ProviderDriver<GrokSettings, GrokDriverEnv> = {
Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
);
const snapshot = yield* makeManagedServerProvider<GrokSettings>({
const snapshotSettings = makeProviderSnapshotSettingsSource(effectiveConfig, serverSettings);
const snapshot = yield* makeManagedServerProvider<ProviderSnapshotSettings<GrokSettings>>({
maintenanceCapabilities,
getSettings: Effect.succeed(effectiveConfig),
streamSettings: Stream.never,
haveSettingsChanged: () => false,
getSettings: snapshotSettings.getSettings,
streamSettings: snapshotSettings.streamSettings,
haveSettingsChanged: haveProviderSnapshotSettingsChanged,
initialSnapshot: (settings) =>
buildInitialGrokProviderSnapshot(settings).pipe(Effect.map(stampIdentity)),
buildInitialGrokProviderSnapshot(settings.provider).pipe(Effect.map(stampIdentity)),
checkProvider,
enrichSnapshot: ({ snapshot: currentSnapshot, publishSnapshot }) =>
enrichSnapshot: ({ settings, snapshot: currentSnapshot, publishSnapshot }) =>
enrichGrokSnapshot({
snapshot: currentSnapshot,
maintenanceCapabilities,
enableProviderUpdateChecks: settings.enableProviderUpdateChecks,
publishSnapshot,
httpClient,
}),
@@ -19,12 +19,12 @@ import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Path from "effect/Path";
import * as Schema from "effect/Schema";
import * as Stream from "effect/Stream";
import { HttpClient } from "effect/unstable/http";
import { ChildProcessSpawner } from "effect/unstable/process";
import { makeOpenCodeTextGeneration } from "../../textGeneration/OpenCodeTextGeneration.ts";
import { ServerConfig } from "../../config.ts";
import { ServerSettingsService } from "../../serverSettings.ts";
import { ProviderDriverError } from "../Errors.ts";
import { makeOpenCodeAdapter } from "../Layers/OpenCodeAdapter.ts";
import {
@@ -47,6 +47,11 @@ import {
normalizeCommandPath,
resolveProviderMaintenanceCapabilitiesEffect,
} from "../providerMaintenance.ts";
import {
haveProviderSnapshotSettingsChanged,
makeProviderSnapshotSettingsSource,
type ProviderSnapshotSettings,
} from "../providerUpdateSettings.ts";
const decodeOpenCodeSettings = Schema.decodeSync(OpenCodeSettings);
const DRIVER_KIND = ProviderDriverKind.make("opencode");
@@ -80,7 +85,8 @@ export type OpenCodeDriverEnv =
| OpenCodeRuntime
| Path.Path
| ProviderEventLoggers
| ServerConfig;
| ServerConfig
| ServerSettingsService;
const withInstanceIdentity =
(input: {
@@ -111,6 +117,7 @@ export const OpenCodeDriver: ProviderDriver<OpenCodeSettings, OpenCodeDriverEnv>
const openCodeRuntime = yield* OpenCodeRuntime;
const serverConfig = yield* ServerConfig;
const httpClient = yield* HttpClient.HttpClient;
const serverSettings = yield* ServerSettingsService;
const eventLoggers = yield* ProviderEventLoggers;
const processEnv = mergeProviderInstanceEnvironment(environment);
const continuationIdentity = defaultProviderContinuationIdentity({
@@ -142,21 +149,26 @@ export const OpenCodeDriver: ProviderDriver<OpenCodeSettings, OpenCodeDriverEnv>
processEnv,
).pipe(Effect.map(stampIdentity), Effect.provideService(OpenCodeRuntime, openCodeRuntime));
const snapshot = yield* makeManagedServerProvider<OpenCodeSettings>({
maintenanceCapabilities,
getSettings: Effect.succeed(effectiveConfig),
streamSettings: Stream.never,
haveSettingsChanged: () => false,
initialSnapshot: (settings) =>
makePendingOpenCodeProvider(settings).pipe(Effect.map(stampIdentity)),
checkProvider,
enrichSnapshot: ({ snapshot, publishSnapshot }) =>
enrichProviderSnapshotWithVersionAdvisory(snapshot, maintenanceCapabilities).pipe(
Effect.provideService(HttpClient.HttpClient, httpClient),
Effect.flatMap((enrichedSnapshot) => publishSnapshot(enrichedSnapshot)),
),
refreshInterval: SNAPSHOT_REFRESH_INTERVAL,
}).pipe(
const snapshotSettings = makeProviderSnapshotSettingsSource(effectiveConfig, serverSettings);
const snapshot = yield* makeManagedServerProvider<ProviderSnapshotSettings<OpenCodeSettings>>(
{
maintenanceCapabilities,
getSettings: snapshotSettings.getSettings,
streamSettings: snapshotSettings.streamSettings,
haveSettingsChanged: haveProviderSnapshotSettingsChanged,
initialSnapshot: (settings) =>
makePendingOpenCodeProvider(settings.provider).pipe(Effect.map(stampIdentity)),
checkProvider,
enrichSnapshot: ({ settings, snapshot, publishSnapshot }) =>
enrichProviderSnapshotWithVersionAdvisory(snapshot, maintenanceCapabilities, {
enableProviderUpdateChecks: settings.enableProviderUpdateChecks,
}).pipe(
Effect.provideService(HttpClient.HttpClient, httpClient),
Effect.flatMap((enrichedSnapshot) => publishSnapshot(enrichedSnapshot)),
),
refreshInterval: SNAPSHOT_REFRESH_INTERVAL,
},
).pipe(
Effect.mapError(
(cause) =>
new ProviderDriverError({
@@ -1106,6 +1106,7 @@ export const enrichCursorSnapshot = (input: {
readonly settings: CursorSettings;
readonly snapshot: ServerProvider;
readonly maintenanceCapabilities: ProviderMaintenanceCapabilities;
readonly enableProviderUpdateChecks?: boolean;
readonly publishSnapshot: (snapshot: ServerProvider) => Effect.Effect<void>;
readonly stampIdentity?: (snapshot: ServerProvider) => ServerProvider;
readonly httpClient: HttpClient.HttpClient;
@@ -1117,7 +1118,9 @@ export const enrichCursorSnapshot = (input: {
return Effect.void;
}
return enrichProviderSnapshotWithVersionAdvisory(snapshot, input.maintenanceCapabilities).pipe(
return enrichProviderSnapshotWithVersionAdvisory(snapshot, input.maintenanceCapabilities, {
enableProviderUpdateChecks: input.enableProviderUpdateChecks,
}).pipe(
Effect.provideService(HttpClient.HttpClient, input.httpClient),
Effect.flatMap((enrichedSnapshot) =>
publishSnapshot(stampIdentity(enrichedSnapshot)).pipe(Effect.as(enrichedSnapshot)),
@@ -311,12 +311,15 @@ export const checkGrokProviderStatus = Effect.fn("checkGrokProviderStatus")(func
export const enrichGrokSnapshot = (input: {
readonly snapshot: ServerProvider;
readonly maintenanceCapabilities: ProviderMaintenanceCapabilities;
readonly enableProviderUpdateChecks?: boolean;
readonly publishSnapshot: (snapshot: ServerProvider) => Effect.Effect<void>;
readonly httpClient: HttpClient.HttpClient;
}): Effect.Effect<void> => {
const { snapshot, publishSnapshot } = input;
return enrichProviderSnapshotWithVersionAdvisory(snapshot, input.maintenanceCapabilities).pipe(
return enrichProviderSnapshotWithVersionAdvisory(snapshot, input.maintenanceCapabilities, {
enableProviderUpdateChecks: input.enableProviderUpdateChecks,
}).pipe(
Effect.provideService(HttpClient.HttpClient, input.httpClient),
Effect.flatMap((enrichedSnapshot) => publishSnapshot(enrichedSnapshot)),
Effect.catchCause((cause) =>
@@ -39,6 +39,7 @@ import * as Layer from "effect/Layer";
import { HttpClient, HttpClientResponse } from "effect/unstable/http";
import { ServerConfig } from "../../config.ts";
import { ServerSettingsService } from "../../serverSettings.ts";
import { ClaudeDriver } from "../Drivers/ClaudeDriver.ts";
import { CodexDriver } from "../Drivers/CodexDriver.ts";
import { CursorDriver } from "../Drivers/CursorDriver.ts";
@@ -107,6 +108,7 @@ describe("ProviderInstanceRegistryLive — multi-instance codex slice", () => {
prefix: "provider-instance-registry-test",
}).pipe(
Layer.provideMerge(NodeServices.layer),
Layer.provideMerge(ServerSettingsService.layerTest()),
Layer.provideMerge(TestHttpClientLive),
Layer.provideMerge(Layer.succeed(ProviderEventLoggers, NoOpProviderEventLoggers)),
);
@@ -244,6 +246,7 @@ describe("ProviderInstanceRegistryLive — all drivers slice", () => {
prefix: "provider-instance-registry-all-drivers-test",
}).pipe(
Layer.provideMerge(infraLayer),
Layer.provideMerge(ServerSettingsService.layerTest()),
Layer.provideMerge(TestHttpClientLive),
Layer.provideMerge(Layer.succeed(ProviderEventLoggers, NoOpProviderEventLoggers)),
);
@@ -21,7 +21,7 @@ export const makeManagedServerProvider = Effect.fn("makeManagedServerProvider")(
Settings,
>(input: {
readonly maintenanceCapabilities: ServerProviderShape["maintenanceCapabilities"];
readonly getSettings: Effect.Effect<Settings>;
readonly getSettings: Effect.Effect<Settings, ServerSettingsError>;
readonly streamSettings: Stream.Stream<Settings>;
readonly haveSettingsChanged: (previous: Settings, next: Settings) => boolean;
readonly initialSnapshot: (settings: Settings) => Effect.Effect<ServerProvider>;
@@ -4,13 +4,14 @@ import { chmodSync, mkdirSync, symlinkSync, writeFileSync } from "node:fs";
import * as NodeServices from "@effect/platform-node/NodeServices";
import * as NodeOS from "node:os";
import path from "node:path";
import { ProviderDriverKind } from "@t3tools/contracts";
import { ProviderDriverKind, ProviderInstanceId, type ServerProvider } from "@t3tools/contracts";
import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
import * as Crypto from "effect/Crypto";
import * as Effect from "effect/Effect";
import { HttpClient } from "effect/unstable/http";
import {
createProviderVersionAdvisory,
enrichProviderSnapshotWithVersionAdvisory,
makePackageManagedProviderMaintenanceResolver,
makeProviderMaintenanceCapabilities,
makeStaticProviderMaintenanceResolver,
@@ -67,6 +68,19 @@ const staticToolUpdate = makeStaticProviderMaintenanceResolver(
updateLockKey: "static-tool",
}),
);
const installedPackageToolProvider: ServerProvider = {
instanceId: ProviderInstanceId.make("packageTool"),
driver: driver("packageTool"),
enabled: true,
installed: true,
version: "1.0.0",
status: "ready",
auth: { status: "authenticated" },
checkedAt: "2026-04-10T00:00:00.000Z",
models: [],
slashCommands: [],
skills: [],
};
it.layer(NodeServices.layer)("providerMaintenance", (it) => {
it.effect("reads cached versions through the injectable cache reference", () =>
@@ -95,6 +109,32 @@ it.layer(NodeServices.layer)("providerMaintenance", (it) => {
),
);
it.effect("does not fetch latest provider versions when update checks are disabled", () =>
enrichProviderSnapshotWithVersionAdvisory(
installedPackageToolProvider,
packageToolUpdate.resolve(),
{
enableProviderUpdateChecks: false,
},
).pipe(
Effect.provideService(ProviderVersionCache, new Map()),
Effect.provideService(
HttpClient.HttpClient,
HttpClient.make(() =>
Effect.die("disabled provider update checks should not make an HTTP request"),
),
),
Effect.map((provider) => {
expect(provider.versionAdvisory).toMatchObject({
status: "unknown",
currentVersion: "1.0.0",
latestVersion: null,
checkedAt: "2026-04-10T00:00:00.000Z",
});
}),
),
);
it("marks providers with unknown current versions as unknown", () => {
expect(
createProviderVersionAdvisory({
@@ -468,10 +468,21 @@ export const resolveLatestProviderVersion = Effect.fn("resolveLatestProviderVers
export const enrichProviderSnapshotWithVersionAdvisory = Effect.fn(
"enrichProviderSnapshotWithVersionAdvisory",
)(function* (snapshot: ServerProvider, maintenanceCapabilities?: ProviderMaintenanceCapabilities) {
)(function* (
snapshot: ServerProvider,
maintenanceCapabilities?: ProviderMaintenanceCapabilities,
options?: {
readonly enableProviderUpdateChecks: boolean | undefined;
},
) {
const capabilities =
maintenanceCapabilities ?? makeManualProviderMaintenanceCapabilities(snapshot.driver);
if (!snapshot.enabled || !snapshot.installed || !snapshot.version) {
const shouldResolveLatestVersion =
options?.enableProviderUpdateChecks !== false &&
snapshot.enabled &&
snapshot.installed &&
Boolean(snapshot.version);
if (!shouldResolveLatestVersion) {
return {
...snapshot,
versionAdvisory: createProviderVersionAdvisory({
@@ -0,0 +1,43 @@
import type { ServerSettings, ServerSettingsError } from "@t3tools/contracts";
import * as Effect from "effect/Effect";
import * as Equal from "effect/Equal";
import * as Stream from "effect/Stream";
import type { ServerSettingsShape } from "../serverSettings.ts";
export interface ProviderSnapshotSettings<Settings> {
readonly provider: Settings;
readonly enableProviderUpdateChecks: boolean;
}
export function makeProviderSnapshotSettings<Settings>(
provider: Settings,
settings: ServerSettings,
): ProviderSnapshotSettings<Settings> {
return {
provider,
enableProviderUpdateChecks: settings.enableProviderUpdateChecks,
};
}
export function haveProviderSnapshotSettingsChanged<Settings>(
previous: ProviderSnapshotSettings<Settings>,
next: ProviderSnapshotSettings<Settings>,
): boolean {
return !Equal.equals(previous, next);
}
export function makeProviderSnapshotSettingsSource<Settings>(
provider: Settings,
serverSettings: ServerSettingsShape,
): {
readonly getSettings: Effect.Effect<ProviderSnapshotSettings<Settings>, ServerSettingsError>;
readonly streamSettings: Stream.Stream<ProviderSnapshotSettings<Settings>>;
} {
const mapSettings = (settings: ServerSettings) =>
makeProviderSnapshotSettings(provider, settings);
return {
getSettings: serverSettings.getSettings.pipe(Effect.map(mapSettings)),
streamSettings: serverSettings.streamChanges.pipe(Stream.map(mapSettings)),
};
}
@@ -64,9 +64,10 @@ function makeMemorySecretStore() {
const values = new Map<string, Uint8Array>();
const store = {
get: ((name) =>
Effect.sync(
() => values.get(name) ?? null,
)) satisfies ServerSecretStore.ServerSecretStoreShape["get"],
Effect.sync(() => {
const value = values.get(name);
return value === undefined ? Option.none() : Option.some(Uint8Array.from(value));
})) satisfies ServerSecretStore.ServerSecretStoreShape["get"],
set: ((name, value) =>
Effect.sync(() => {
values.set(name, Uint8Array.from(value));
@@ -625,7 +626,11 @@ describe.sequential("signRelayAgentActivityPublishProof", () => {
} satisfies ExecutionEnvironmentDescriptor;
globalThis.fetch = ((input: Parameters<typeof fetch>[0]) => {
const url = new URL(input instanceof Request ? input.url : input.toString());
const url = new URL(
typeof input === "string" || input instanceof URL
? input
: (input as unknown as { readonly url: string }).url,
);
runFork(Deferred.succeed(fetchSeen, url));
return Promise.resolve(Response.json({ ok: true, deliveries: [] }));
}) as unknown as typeof fetch;
+7 -1
View File
@@ -276,7 +276,13 @@ const make = Effect.gen(function* () {
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)));
secrets
.get(name)
.pipe(
Effect.map((bytes) =>
Option.isSome(bytes) ? new TextDecoder().decode(bytes.value) : null,
),
);
const readRelayConfig = Effect.gen(function* () {
const [url, issuer, environmentCredential] = yield* Effect.all([
+2 -1
View File
@@ -32,6 +32,7 @@ import * as Effect from "effect/Effect";
import * as Exit from "effect/Exit";
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 Equal from "effect/Equal";
import * as PubSub from "effect/PubSub";
@@ -350,7 +351,7 @@ const makeServerSettings = Effect.gen(function* () {
);
environment.push({
...variable,
value: secret ? textDecoder.decode(secret) : "",
value: Option.isSome(secret) ? textDecoder.decode(secret.value) : "",
});
}
providerInstances[instanceId] = {
+2 -2
View File
@@ -12,8 +12,8 @@
},
"dependencies": {
"@base-ui/react": "^1.4.1",
"@clerk/clerk-js": "^6.16.0",
"@clerk/react": "^6.9.0",
"@clerk/electron": "catalog:",
"@clerk/react": "catalog:",
"@dnd-kit/core": "^6.3.1",
"@dnd-kit/modifiers": "^9.0.0",
"@dnd-kit/sortable": "^10.0.0",
+20 -17
View File
@@ -1,5 +1,4 @@
import {
AuthSessionState as AuthSessionStateSchema,
EnvironmentAuthInvalidError,
type AuthBrowserSessionResult,
type AuthCreatePairingCredentialInput,
@@ -8,10 +7,11 @@ import {
} from "@t3tools/contracts";
import * as DateTime from "effect/DateTime";
import * as Effect from "effect/Effect";
import * as Schema from "effect/Schema";
import { HttpClientError, HttpClientRequest, HttpClientResponse } from "effect/unstable/http";
import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
import { installEnvironmentHttpTest } from "../test/environmentHttpTest";
import { __setPrimaryHttpRunnerForTests, type PrimaryHttpEffectRunner } from "./lib/runtime";
type TestWindow = {
location: URL;
@@ -36,8 +36,6 @@ const DESKTOP_AUTH = {
} as const;
const SESSION_EXPIRES_AT = DateTime.makeUnsafe("2026-04-05T00:00:00.000Z");
const encodeAuthSessionState = Schema.encodeSync(AuthSessionStateSchema);
const unauthenticatedSession = (auth: AuthSessionState["auth"]): AuthSessionState => ({
authenticated: false,
auth,
@@ -117,6 +115,7 @@ describe("resolveInitialServerAuthGateState", () => {
disposeHttpTest = undefined;
const { __resetServerAuthBootstrapForTests } = await import("./environments/primary");
__resetServerAuthBootstrapForTests();
__setPrimaryHttpRunnerForTests();
vi.unstubAllEnvs();
vi.useRealTimers();
vi.restoreAllMocks();
@@ -220,18 +219,22 @@ describe("resolveInitialServerAuthGateState", () => {
it("retries transient auth session bootstrap failures after restart", async () => {
vi.useFakeTimers();
const fetchMock = vi
.fn<typeof fetch>()
.mockResolvedValueOnce(new Response("Bad Gateway", { status: 502 }))
.mockResolvedValueOnce(new Response("Bad Gateway", { status: 502 }))
.mockResolvedValueOnce(new Response("Bad Gateway", { status: 502 }))
.mockResolvedValueOnce(
new Response(
JSON.stringify(encodeAuthSessionState(unauthenticatedSession(LOOPBACK_AUTH))),
{ status: 200, headers: { "content-type": "application/json" } },
),
);
vi.stubGlobal("fetch", fetchMock);
let attempts = 0;
const request = HttpClientRequest.get("http://localhost/api/auth/session");
const response = HttpClientResponse.fromWeb(
request,
new Response("Bad Gateway", { status: 502 }),
);
const runner: PrimaryHttpEffectRunner = async <A>() => {
attempts += 1;
if (attempts < 4) {
throw new HttpClientError.HttpClientError({
reason: new HttpClientError.StatusCodeError({ request, response }),
});
}
return unauthenticatedSession(LOOPBACK_AUTH) as A;
};
__setPrimaryHttpRunnerForTests(runner);
const { resolveInitialServerAuthGateState } = await import("./environments/primary");
@@ -242,7 +245,7 @@ describe("resolveInitialServerAuthGateState", () => {
status: "requires-auth",
auth: LOOPBACK_AUTH,
});
expect(fetchMock).toHaveBeenCalledTimes(4);
expect(attempts).toBe(4);
});
it("takes a pairing token from the location hash and strips it immediately", async () => {
-59
View File
@@ -1,59 +0,0 @@
import { describe, expect, it } from "vite-plus/test";
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",
providerId: "google",
iconUrl: null,
},
]);
});
it("preserves provider display metadata when Clerk exposes the strategy list", () => {
expect(
resolveDesktopCloudAuthOAuthOptions({
environment: {
userSettings: {
authenticatableSocialStrategies: ["oauth_google"],
social: {
oauth_google: {
strategy: "oauth_google",
enabled: true,
authenticatable: true,
name: "Google",
logo_url: "https://img.clerk.com/static/google.png",
},
},
},
},
}),
).toEqual([
{
strategy: "oauth_google",
label: "Google",
providerId: "google",
iconUrl: "https://img.clerk.com/static/google.png",
},
]);
});
});
-144
View File
@@ -1,144 +0,0 @@
export type DesktopCloudAuthOAuthStrategy = `oauth_${string}`;
export interface DesktopCloudAuthOAuthOption {
readonly strategy: DesktopCloudAuthOAuthStrategy;
readonly label: string;
readonly providerId: string;
readonly iconUrl: string | null;
}
interface ClerkOAuthProviderSetting {
readonly enabled?: unknown;
readonly authenticatable?: unknown;
readonly strategy?: unknown;
readonly name?: unknown;
readonly logo_url?: 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",
};
// Mirrors Clerk UI's enabled-provider projection for the local desktop replacement:
// https://github.com/clerk/javascript/blob/52861184477bee99c71552000311a289e91d3b59/packages/ui/src/hooks/useEnabledThirdPartyProviders.tsx
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) =>
createOAuthOption(strategy, findProviderSetting(userSettings, 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 createOAuthOption(strategy, provider);
})
.filter((option): option is DesktopCloudAuthOAuthOption => option !== null),
);
}
function findProviderSetting(
userSettings: ClerkUserSettingsLike | undefined,
strategy: DesktopCloudAuthOAuthStrategy,
): ClerkOAuthProviderSetting | undefined {
const social = userSettings?.social;
if (!social || typeof social !== "object") return undefined;
return Object.values(social as Record<string, ClerkOAuthProviderSetting>)
.filter(isClerkOAuthProviderSetting)
.find((provider) => provider.strategy === strategy);
}
function createOAuthOption(
strategy: DesktopCloudAuthOAuthStrategy,
provider?: ClerkOAuthProviderSetting,
): DesktopCloudAuthOAuthOption {
return {
strategy,
label:
typeof provider?.name === "string" && provider.name.trim()
? provider.name
: getDesktopCloudAuthOAuthStrategyLabel(strategy),
providerId: strategy.replace(/^oauth_/, ""),
iconUrl:
typeof provider?.logo_url === "string" && provider.logo_url.trim() ? provider.logo_url : 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;
});
}
-322
View File
@@ -1,322 +0,0 @@
import { Clerk } from "@clerk/clerk-js";
import {
buildClerkUIScriptAttributes,
clerkUIScriptUrl,
InternalClerkProvider,
} from "@clerk/react/internal";
import type { ClerkProviderProps } from "@clerk/react";
import {
clerkFrontendApiHostnameFromPublishableKey,
isAllowedClerkFrontendApiHostname,
} from "@t3tools/shared/relayAuth";
import React, { useEffect, useState } from "react";
import {
makeDesktopClerkExternalAccountAdapter,
type DesktopClerkUser,
} from "./desktopClerkExternalAccounts";
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;
let desktopClerkFrontendApiHostname: string | null = null;
let desktopClerkExternalAccountCleanup: (() => void) | 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:" &&
isAllowedClerkFrontendApiHostname(url.hostname, desktopClerkFrontendApiHostname);
const headersToRecord = (headers: Headers): Record<string, string> => {
const record: Record<string, string> = {};
headers.forEach((value, key) => {
record[key] = value;
});
return record;
};
function installDesktopClerkFetchProxy(publishableKey: string): void {
desktopClerkFrontendApiHostname = clerkFrontendApiHostnameFromPublishableKey(publishableKey);
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 installDesktopClerkExternalAccounts(clerk: Clerk): void {
desktopClerkExternalAccountCleanup?.();
desktopClerkExternalAccountCleanup = null;
const bridge = window.desktopBridge;
if (!bridge) return;
const adapter = makeDesktopClerkExternalAccountAdapter({ bridge });
const unsubscribe = clerk.addListener(({ user }) => {
if (user) {
adapter.installUser(user as DesktopClerkUser);
}
});
desktopClerkExternalAccountCleanup = () => {
unsubscribe();
adapter.dispose();
};
}
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(publishableKey);
const hasKeyChanged = desktopClerk !== null && desktopClerk.publishableKey !== publishableKey;
if (hasKeyChanged) {
void clearStoredClientJwt();
desktopClerkExternalAccountCleanup?.();
desktopClerkExternalAccountCleanup = null;
desktopClerk = null;
}
if (desktopClerk !== null) {
return desktopClerk;
}
const nextClerk = new Clerk(publishableKey);
installDesktopClerkExternalAccounts(nextClerk);
if (!isNativeRequestClerk(nextClerk)) {
desktopClerk = nextClerk;
return nextClerk;
}
const onBeforeRequest =
nextClerk.__internal_onBeforeRequest ?? nextClerk.__unstable__onBeforeRequest;
const onAfterResponse =
nextClerk.__internal_onAfterResponse ?? nextClerk.__unstable__onAfterResponse;
// Keep this aligned with Clerk Expo's native FAPI adapter:
// https://github.com/clerk/javascript/blob/52861184477bee99c71552000311a289e91d3b59/packages/expo/src/provider/singleton/createClerkInstance.ts
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>
);
}
@@ -1,78 +0,0 @@
import { describe, expect, it, vi } from "vite-plus/test";
import {
makeDesktopClerkExternalAccountAdapter,
type DesktopClerkUser,
} from "./desktopClerkExternalAccounts";
describe("desktop Clerk external account adapter", () => {
it("replaces renderer redirects with native callbacks and reloads the user on return", async () => {
const callbacks: ((rawUrl: string) => void)[] = [];
const callbackCleanup = vi.fn();
const bridge = {
createCloudAuthRequest: vi
.fn()
.mockResolvedValueOnce("t3code://auth/callback?t3_state=add")
.mockResolvedValueOnce("t3code://auth/callback?t3_state=reconnect"),
onCloudAuthCallback: vi.fn((listener: (rawUrl: string) => void) => {
callbacks.push(listener);
return callbackCleanup;
}),
};
const reauthorize = vi.fn(async (_params: Record<string, unknown>) => account);
const account = { reauthorize };
const createExternalAccount = vi.fn(async (_params: Record<string, unknown>) => account);
const reload = vi.fn(async () => undefined);
const user = {
externalAccounts: [],
createExternalAccount,
reload,
} satisfies DesktopClerkUser;
const adapter = makeDesktopClerkExternalAccountAdapter({ bridge });
adapter.installUser(user);
await user.createExternalAccount({
redirectUrl: "http://127.0.0.1:3773/?__clerk_modal_state=state",
strategy: "oauth_microsoft",
});
expect(createExternalAccount).toHaveBeenCalledWith({
redirectUrl: "t3code://auth/callback?t3_state=add",
strategy: "oauth_microsoft",
});
callbacks[0]?.("t3code://auth/callback?t3_state=add");
await Promise.resolve();
expect(reload).toHaveBeenCalledOnce();
await account.reauthorize({
redirectUrl: "http://127.0.0.1:3773/?__clerk_modal_state=state",
});
expect(reauthorize).toHaveBeenCalledWith({
redirectUrl: "t3code://auth/callback?t3_state=reconnect",
});
});
it("cleans up the pending callback when Clerk rejects account creation", async () => {
const callbackCleanup = vi.fn();
const bridge = {
createCloudAuthRequest: vi.fn().mockResolvedValue("t3code://auth/callback?t3_state=failed"),
onCloudAuthCallback: vi.fn(() => callbackCleanup),
};
const createError = new Error("oauth provider unavailable");
const user = {
externalAccounts: [],
createExternalAccount: vi.fn(async (_params: Record<string, unknown>) => {
throw createError;
}),
reload: vi.fn(async () => undefined),
} satisfies DesktopClerkUser;
const adapter = makeDesktopClerkExternalAccountAdapter({ bridge });
adapter.installUser(user);
await expect(user.createExternalAccount({ strategy: "oauth_microsoft" })).rejects.toBe(
createError,
);
expect(callbackCleanup).toHaveBeenCalledOnce();
});
});
@@ -1,112 +0,0 @@
interface DesktopClerkExternalAccountParams {
readonly redirectUrl?: string;
readonly [key: string]: unknown;
}
interface DesktopClerkExternalAccount {
reauthorize: (params: DesktopClerkExternalAccountParams) => Promise<DesktopClerkExternalAccount>;
}
interface DesktopClerkUser {
readonly externalAccounts: readonly DesktopClerkExternalAccount[];
createExternalAccount: (
params: DesktopClerkExternalAccountParams,
) => Promise<DesktopClerkExternalAccount>;
reload: () => Promise<unknown>;
}
interface DesktopClerkExternalAccountBridge {
readonly createCloudAuthRequest: () => Promise<string>;
readonly onCloudAuthCallback: (listener: (rawUrl: string) => void) => () => void;
}
interface DesktopClerkExternalAccountAdapter {
readonly dispose: () => void;
readonly installUser: (user: DesktopClerkUser) => void;
}
interface MakeDesktopClerkExternalAccountAdapterInput {
readonly bridge: DesktopClerkExternalAccountBridge;
readonly reportError?: (message: string, error: unknown) => void;
}
// Clerk's profile component uses window.location.href as the OAuth callback and navigates the
// current window to the provider. Keep the upstream component intact while adapting its resource
// calls to the native callback bridge:
// https://github.com/clerk/javascript/blob/52861184477bee99c71552000311a289e91d3b59/packages/ui/src/components/UserProfile/ConnectedAccountsMenu.tsx
// https://github.com/clerk/javascript/blob/52861184477bee99c71552000311a289e91d3b59/packages/ui/src/components/UserProfile/ConnectedAccountsSection.tsx
export function makeDesktopClerkExternalAccountAdapter({
bridge,
reportError = console.error,
}: MakeDesktopClerkExternalAccountAdapterInput): DesktopClerkExternalAccountAdapter {
const installedAccounts = new WeakSet<object>();
const installedUsers = new WeakSet<object>();
let callbackGeneration = 0;
let callbackCleanup: (() => void) | null = null;
const clearCallback = () => {
callbackGeneration += 1;
callbackCleanup?.();
callbackCleanup = null;
};
const createRedirectUrl = async (user: DesktopClerkUser): Promise<string> => {
clearCallback();
const redirectUrl = await bridge.createCloudAuthRequest();
const generation = callbackGeneration;
callbackCleanup = bridge.onCloudAuthCallback(() => {
if (generation !== callbackGeneration) return;
clearCallback();
void user.reload().catch((error: unknown) => {
reportError("Failed to reload Clerk after desktop account linking.", error);
});
});
return redirectUrl;
};
const installAccount = (user: DesktopClerkUser, account: DesktopClerkExternalAccount): void => {
if (installedAccounts.has(account)) return;
installedAccounts.add(account);
const reauthorize = account.reauthorize.bind(account);
account.reauthorize = async (params) => {
const redirectUrl = await createRedirectUrl(user);
try {
const nextAccount = await reauthorize({ ...params, redirectUrl });
installAccount(user, nextAccount);
return nextAccount;
} catch (error) {
clearCallback();
throw error;
}
};
};
const installUser = (user: DesktopClerkUser): void => {
for (const account of user.externalAccounts) {
installAccount(user, account);
}
if (installedUsers.has(user)) return;
installedUsers.add(user);
const createExternalAccount = user.createExternalAccount.bind(user);
user.createExternalAccount = async (params) => {
const redirectUrl = await createRedirectUrl(user);
try {
const account = await createExternalAccount({ ...params, redirectUrl });
installAccount(user, account);
return account;
} catch (error) {
clearCallback();
throw error;
}
};
};
return {
dispose: clearCallback,
installUser,
};
}
export type { DesktopClerkExternalAccountAdapter, DesktopClerkUser };
@@ -1,4 +1,5 @@
import {
type DesktopBridge,
EnvironmentId,
type RelayClientInstallProgressEvent,
WS_METHODS,
@@ -28,6 +29,7 @@ import {
ManagedRelayDpopSigner,
} from "@t3tools/client-runtime/relay";
import { remoteHttpClientLayer } from "@t3tools/client-runtime/rpc";
import { __resetDesktopPrimaryAuthForTests } from "../environments/primary/desktopAuth";
import {
collectCloudLinkTargets,
@@ -146,6 +148,7 @@ beforeEach(() => {
});
afterEach(() => {
__resetDesktopPrimaryAuthForTests();
vi.unstubAllGlobals();
vi.unstubAllEnvs();
vi.restoreAllMocks();
@@ -224,6 +227,33 @@ describe("web cloud link environment client", () => {
}),
);
it.effect("uses desktop bearer auth for primary cloud link state", () =>
Effect.gen(function* () {
const fetchMock = vi.fn().mockResolvedValue(
Response.json({
linked: true,
cloudUserId: "user-1",
relayUrl: "https://relay.example.test",
relayIssuer: "https://relay.example.test",
publishAgentActivity: false,
}),
);
vi.stubGlobal("fetch", fetchMock);
vi.stubGlobal("window", {
location: { origin: "t3code://app" },
desktopBridge: {
getLocalEnvironmentBearerToken: vi.fn().mockResolvedValue("desktop-bearer-token"),
} as unknown as DesktopBridge,
});
yield* withServices(readPrimaryCloudLinkState({ target: TARGET }));
const request = new Request(fetchMock.mock.calls[0]?.[0], fetchMock.mock.calls[0]?.[1]);
expect(request.credentials).not.toBe("include");
expect(request.headers.get("authorization")).toBe("Bearer desktop-bearer-token");
}),
);
it.effect("links an available primary environment without invoking installation", () =>
Effect.gen(function* () {
const fetchMock = vi
+9 -22
View File
@@ -31,7 +31,7 @@ import {
readPrimaryEnvironmentDescriptor,
readPrimaryEnvironmentTarget,
} from "../environments/primary";
import { withPrimaryEnvironmentRequestInit } from "../environments/primary/requestInit";
import { primaryEnvironmentHttpLayer } from "../environments/primary/httpLayer";
import { resolveCloudPublicConfig } from "./publicConfig";
import {
finishRelayClientInstall,
@@ -327,11 +327,8 @@ export function readPrimaryCloudLinkState(input: {
const client = yield* makeEnvironmentHttpApiClient(input.target.httpBaseUrl);
return yield* client.connect
.linkState({ headers: {} })
.pipe(
withPrimaryEnvironmentRequestInit,
Effect.mapError(environmentApiError("Could not read environment cloud link state.")),
);
});
.pipe(Effect.mapError(environmentApiError("Could not read environment cloud link state.")));
}).pipe(Effect.provide(primaryEnvironmentHttpLayer));
}
export function updatePrimaryCloudPreferences(input: {
@@ -346,10 +343,9 @@ export function updatePrimaryCloudPreferences(input: {
payload: input,
})
.pipe(
withPrimaryEnvironmentRequestInit,
Effect.mapError(environmentApiError("Could not update environment cloud preferences.")),
);
});
}).pipe(Effect.provide(primaryEnvironmentHttpLayer));
}
export function unlinkPrimaryEnvironmentFromCloud(input: {
@@ -360,10 +356,7 @@ export function unlinkPrimaryEnvironmentFromCloud(input: {
const client = yield* makeEnvironmentHttpApiClient(input.target.httpBaseUrl);
yield* client.connect
.unlink({ headers: {} })
.pipe(
withPrimaryEnvironmentRequestInit,
Effect.mapError(environmentApiError("Could not unlink the environment from cloud.")),
);
.pipe(Effect.mapError(environmentApiError("Could not unlink the environment from cloud.")));
const configuredRelayUrl = relayUrl();
if (configuredRelayUrl && input.clerkToken) {
@@ -381,7 +374,7 @@ export function unlinkPrimaryEnvironmentFromCloud(input: {
),
);
}
});
}).pipe(Effect.provide(primaryEnvironmentHttpLayer));
}
export function linkPrimaryEnvironmentToCloud(input: {
@@ -433,10 +426,7 @@ export function linkPrimaryEnvironmentToCloud(input: {
origin: endpointOrigin(input.target.httpBaseUrl),
},
})
.pipe(
withPrimaryEnvironmentRequestInit,
Effect.mapError(environmentApiError("Could not obtain environment link proof.")),
);
.pipe(Effect.mapError(environmentApiError("Could not obtain environment link proof.")));
const link = yield* relayClient
.linkEnvironment({
clerkToken: input.clerkToken,
@@ -470,9 +460,6 @@ export function linkPrimaryEnvironmentToCloud(input: {
endpointRuntime: link.endpointRuntime,
},
})
.pipe(
withPrimaryEnvironmentRequestInit,
Effect.mapError(environmentApiError("Could not configure environment relay access.")),
);
});
.pipe(Effect.mapError(environmentApiError("Could not configure environment relay access.")));
}).pipe(Effect.provide(primaryEnvironmentHttpLayer));
}
+13 -5
View File
@@ -89,7 +89,6 @@ import {
} from "../proposedPlan";
import {
DEFAULT_INTERACTION_MODE,
DEFAULT_RUNTIME_MODE,
DEFAULT_THREAD_TERMINAL_ID,
MAX_TERMINALS_PER_GROUP,
type ChatMessage,
@@ -141,7 +140,11 @@ import { getProviderModelCapabilities, resolveSelectableProvider } from "../prov
import { useSettings } from "../hooks/useSettings";
import { resolveAppModelSelectionForInstance } from "../modelSelection";
import { getTerminalFocusOwner } from "../lib/terminalFocus";
import { resolveNewDraftStartFromOrigin } from "../lib/chatThreadActions";
import {
buildNewDraftExecutionDefaults,
resolveNewDraftStartFromOrigin,
} from "../lib/chatThreadActions";
import { loadClientSettingsForNewThread } from "../lib/clientSettingsHydration";
import {
deriveLogicalProjectKeyFromSettings,
selectProjectGroupingSettings,
@@ -1212,7 +1215,8 @@ function ChatViewContent(props: ChatViewProps) {
const threadError = isServerThread
? (localServerError ?? serverThread?.session?.lastError ?? null)
: localDraftError;
const runtimeMode = composerRuntimeMode ?? activeThread?.runtimeMode ?? DEFAULT_RUNTIME_MODE;
const runtimeMode =
composerRuntimeMode ?? activeThread?.runtimeMode ?? settings.defaultRuntimeMode;
const interactionMode =
composerInteractionMode ?? activeThread?.interactionMode ?? DEFAULT_INTERACTION_MODE;
const isLocalDraftThread = !isServerThread && localDraftThread !== undefined;
@@ -1526,13 +1530,17 @@ function ChatViewContent(props: ChatViewProps) {
return activeDraftSession.threadId;
}
const clientSettings = await loadClientSettingsForNewThread();
if (!clientSettings) {
return null;
}
const nextDraftId = newDraftId();
const nextThreadId = newThreadId();
setLogicalProjectDraftThreadId(logicalProjectKey, activeProjectRef, nextDraftId, {
threadId: nextThreadId,
createdAt: new Date().toISOString(),
runtimeMode: DEFAULT_RUNTIME_MODE,
interactionMode: DEFAULT_INTERACTION_MODE,
...buildNewDraftExecutionDefaults(clientSettings.defaultRuntimeMode),
...input,
});
await navigate({
@@ -14,6 +14,7 @@ import {
resolveProjectStatusIndicator,
resolveSidebarNewThreadSeedContext,
resolveSidebarNewThreadEnvMode,
resolveSidebarStageBadgeLabel,
resolveThreadRowClassName,
resolveThreadStatusPill,
shouldClearThreadSelectionOnMouseDown,
@@ -36,6 +37,44 @@ import {
const localEnvironmentId = EnvironmentId.make("environment-local");
describe("resolveSidebarStageBadgeLabel", () => {
it("returns Nightly for nightly primary server versions", () => {
expect(
resolveSidebarStageBadgeLabel({
primaryServerVersion: "0.0.28-nightly.20260616.12",
fallbackStageLabel: "Alpha",
}),
).toBe("Nightly");
});
it("returns the fallback label for stable primary server versions", () => {
expect(
resolveSidebarStageBadgeLabel({
primaryServerVersion: "0.0.27",
fallbackStageLabel: "Alpha",
}),
).toBe("Alpha");
});
it("returns the fallback label when the primary server version is missing", () => {
expect(
resolveSidebarStageBadgeLabel({
primaryServerVersion: null,
fallbackStageLabel: "Dev",
}),
).toBe("Dev");
});
it("returns the fallback label for malformed nightly prerelease versions", () => {
expect(
resolveSidebarStageBadgeLabel({
primaryServerVersion: "0.0.28-nightly.20260616",
fallbackStageLabel: "Alpha",
}),
).toBe("Alpha");
});
});
function makeLatestTurn(overrides?: {
completedAt?: string | null;
startedAt?: string | null;
+11
View File
@@ -12,6 +12,7 @@ import { isLatestTurnSettled } from "../session-logic";
export const THREAD_SELECTION_SAFE_SELECTOR = "[data-thread-item], [data-thread-selection-safe]";
export const THREAD_JUMP_HINT_SHOW_DELAY_MS = 100;
const NIGHTLY_SERVER_VERSION_PATTERN = /-nightly\.\d{8}\.\d+$/;
// Visible sidebar rows are prewarmed into the thread-detail cache so opening a
// nearby thread usually reuses an already-hot subscription.
export const SIDEBAR_THREAD_PREWARM_LIMIT = 10;
@@ -64,6 +65,16 @@ export interface ThreadJumpHintVisibilityController {
dispose: () => void;
}
export function resolveSidebarStageBadgeLabel(input: {
primaryServerVersion: string | null | undefined;
fallbackStageLabel: string;
}): string {
return input.primaryServerVersion &&
NIGHTLY_SERVER_VERSION_PATTERN.test(input.primaryServerVersion)
? "Nightly"
: input.fallbackStageLabel;
}
export function createThreadJumpHintVisibilityController(input: {
delayMs: number;
onVisibilityChange: (visible: boolean) => void;
+9 -2
View File
@@ -188,6 +188,7 @@ import {
orderItemsByPreferredIds,
shouldClearThreadSelectionOnMouseDown,
sortProjectsForSidebar,
resolveSidebarStageBadgeLabel,
useThreadJumpHintVisibility,
ThreadStatusPill,
} from "./Sidebar.logic";
@@ -197,7 +198,7 @@ import { useCopyToClipboard } from "~/hooks/useCopyToClipboard";
import { useIsMobile } from "~/hooks/useMediaQuery";
import { CommandDialogTrigger } from "./ui/command";
import { useSettings, useUpdateSettings } from "~/hooks/useSettings";
import { primaryServerKeybindingsAtom } from "../state/server";
import { primaryServerConfigAtom, primaryServerKeybindingsAtom } from "../state/server";
import {
derivePhysicalProjectKey,
deriveProjectGroupingOverrideKey,
@@ -2680,6 +2681,12 @@ const SidebarChromeHeader = memo(function SidebarChromeHeader({
}: {
isElectron: boolean;
}) {
const primaryServerVersion =
useAtomValue(primaryServerConfigAtom)?.environment.serverVersion ?? null;
const stageBadgeLabel = resolveSidebarStageBadgeLabel({
primaryServerVersion,
fallbackStageLabel: APP_STAGE_LABEL,
});
const wordmark = (
<div className="flex items-center gap-2">
<SidebarTrigger className="shrink-0 md:hidden" />
@@ -2696,7 +2703,7 @@ const SidebarChromeHeader = memo(function SidebarChromeHeader({
Code
</span>
<span className="rounded-full bg-muted/50 px-1.5 py-0.5 text-[8px] font-medium uppercase tracking-[0.18em] text-muted-foreground/60">
{APP_STAGE_LABEL}
{stageBadgeLabel}
</span>
</Link>
}
@@ -1,137 +0,0 @@
import type { ReactNode } from "react";
import { cn } from "../../lib/utils";
// Mirrors Clerk's raised card/footer/branding composition for the desktop-native flow:
// https://github.com/clerk/javascript/blob/52861184477bee99c71552000311a289e91d3b59/packages/ui/src/elements/Card/CardRoot.tsx
// https://github.com/clerk/javascript/blob/52861184477bee99c71552000311a289e91d3b59/packages/ui/src/elements/Card/CardFooter.tsx
// https://github.com/clerk/javascript/blob/52861184477bee99c71552000311a289e91d3b59/packages/ui/src/elements/Card/CardClerkAndPagesTag.tsx
// https://github.com/clerk/javascript/blob/52861184477bee99c71552000311a289e91d3b59/packages/ui/src/elements/DevModeNotice.tsx
export function DesktopClerkCard({
children,
footerAction,
}: {
children: ReactNode;
footerAction?: ReactNode;
}) {
return (
<div className="isolate w-full max-w-[25rem] overflow-hidden rounded-xl border border-border/80 bg-card text-card-foreground shadow-[0_12px_28px_rgba(0,0,0,0.12)]">
<div className="relative -m-px flex flex-col gap-8 rounded-lg border border-border/80 bg-card px-10 py-8 text-center">
{children}
</div>
<div className="-mt-2 flex flex-col bg-muted/45 pt-2">
{footerAction ? (
<div className="border-t border-border/70 px-8 py-4">{footerAction}</div>
) : null}
<DesktopClerkBranding />
</div>
</div>
);
}
export function DesktopClerkHeader({ title, subtitle }: { title: string; subtitle: string }) {
return (
<div className="space-y-1">
<h2 className="text-xl font-bold tracking-[-0.025em] text-foreground">{title}</h2>
<p className="text-sm leading-5 text-muted-foreground">{subtitle}</p>
</div>
);
}
export function DesktopClerkFooterAction({
children,
actionLabel,
onAction,
}: {
children: ReactNode;
actionLabel: string;
onAction: () => void;
}) {
return (
<p className="flex items-center justify-center gap-1 text-sm text-muted-foreground">
<span>{children}</span>
<button
type="button"
className="cursor-pointer font-semibold text-foreground outline-none hover:underline focus-visible:underline"
onClick={onAction}
>
{actionLabel}
</button>
</p>
);
}
export function DesktopClerkAlert({ children }: { children?: ReactNode }) {
if (!children) return null;
return (
<div
role="alert"
className="rounded-md border border-destructive/20 bg-destructive/8 px-3 py-2 text-left text-xs leading-5 text-destructive-foreground"
>
{children}
</div>
);
}
export function DesktopClerkInput({
className,
...props
}: React.ComponentPropsWithoutRef<"input">) {
return (
<input
{...props}
className={cn(
"h-10 w-full rounded-md border border-input bg-background px-3 text-sm text-foreground shadow-xs outline-none placeholder:text-muted-foreground/80 focus:border-ring focus:ring-2 focus:ring-ring/15 disabled:opacity-64",
className,
)}
/>
);
}
export function DesktopClerkPrimaryButton({
children,
disabled,
}: {
children: ReactNode;
disabled?: boolean;
}) {
return (
<button
type="submit"
disabled={disabled}
className="h-10 w-full cursor-pointer rounded-md border border-neutral-950 bg-neutral-900 px-4 text-sm font-semibold text-white shadow-sm transition-colors hover:bg-neutral-800 disabled:pointer-events-none disabled:opacity-64 dark:border-neutral-200 dark:bg-neutral-100 dark:text-neutral-900 dark:hover:bg-white"
>
{children}
</button>
);
}
function DesktopClerkBranding() {
const isDevelopmentMode = import.meta.env.VITE_CLERK_PUBLISHABLE_KEY?.startsWith("pk_test_");
return (
<div
className={cn(
"flex flex-col items-center justify-center gap-2 border-t border-border/70 px-8 py-4 text-xs text-muted-foreground",
isDevelopmentMode &&
"bg-[repeating-linear-gradient(-45deg,rgba(249,115,22,0.035),rgba(249,115,22,0.035)_8px,transparent_8px,transparent_16px)]",
)}
>
<span>
Secured by{" "}
<a
className="font-bold text-muted-foreground hover:text-foreground"
href="https://go.clerk.com/components"
rel="noreferrer"
target="_blank"
>
clerk
</a>
</span>
{isDevelopmentMode ? (
<strong className="font-semibold text-orange-500">Development mode</strong>
) : null}
</div>
);
}
@@ -1,150 +0,0 @@
import { LoaderCircleIcon } from "lucide-react";
import type {
DesktopCloudAuthOAuthOption,
DesktopCloudAuthOAuthStrategy,
} from "../../cloud/desktopAuth";
import { cn } from "../../lib/utils";
import {
DesktopClerkAlert,
DesktopClerkCard,
DesktopClerkFooterAction,
DesktopClerkHeader,
} from "./DesktopClerkCard";
import { useDesktopClerkSignIn } from "./useDesktopClerkSignIn";
// Mirrors Clerk's compact social-button layout while delegating OAuth to the desktop bridge:
// https://github.com/clerk/javascript/blob/52861184477bee99c71552000311a289e91d3b59/packages/ui/src/elements/SocialButtons.tsx
export function DesktopClerkSignIn({ onJoinWaitlist }: { onJoinWaitlist: () => void }) {
const { isStarting, oauthOptions, startingStrategy, startOAuth } = useDesktopClerkSignIn();
return (
<DesktopClerkSignInCard
isStarting={isStarting}
oauthOptions={oauthOptions}
startingStrategy={startingStrategy}
onJoinWaitlist={onJoinWaitlist}
onStartOAuth={(strategy) => void startOAuth(strategy)}
/>
);
}
export function DesktopClerkSignInCard({
isStarting,
oauthOptions,
startingStrategy,
onJoinWaitlist,
onStartOAuth,
}: {
isStarting: boolean;
oauthOptions: readonly DesktopCloudAuthOAuthOption[];
startingStrategy: DesktopCloudAuthOAuthStrategy | null;
onJoinWaitlist: () => void;
onStartOAuth: (strategy: DesktopCloudAuthOAuthStrategy) => void;
}) {
return (
<DesktopClerkCard
footerAction={
<DesktopClerkFooterAction actionLabel="Join waitlist" onAction={onJoinWaitlist}>
Want early access?
</DesktopClerkFooterAction>
}
>
<DesktopClerkHeader
title="Sign in to T3 Code"
subtitle="Welcome back! Please sign in to continue"
/>
{oauthOptions.length === 0 ? (
<DesktopClerkAlert>No OAuth providers are enabled for desktop sign-in.</DesktopClerkAlert>
) : (
<DesktopClerkSocialButtons
isStarting={isStarting}
oauthOptions={oauthOptions}
startingStrategy={startingStrategy}
onStartOAuth={onStartOAuth}
/>
)}
</DesktopClerkCard>
);
}
function DesktopClerkSocialButtons({
isStarting,
oauthOptions,
startingStrategy,
onStartOAuth,
}: {
isStarting: boolean;
oauthOptions: readonly DesktopCloudAuthOAuthOption[];
startingStrategy: DesktopCloudAuthOAuthStrategy | null;
onStartOAuth: (strategy: DesktopCloudAuthOAuthStrategy) => void;
}) {
const useBlockButtons = oauthOptions.length <= 2;
return (
<div className={cn("grid gap-2", useBlockButtons ? "grid-cols-1" : "grid-cols-3")}>
{oauthOptions.map((option) => {
const isCurrent = option.strategy === startingStrategy;
return (
<button
key={option.strategy}
type="button"
aria-label={`Continue with ${option.label}`}
className={cn(
"flex h-10 cursor-pointer items-center justify-center rounded-md border border-input bg-popover px-3 text-sm font-semibold text-foreground shadow-xs outline-none transition-colors hover:bg-accent/50 focus-visible:ring-2 focus-visible:ring-ring/20 disabled:pointer-events-none disabled:opacity-64",
useBlockButtons && "w-full",
)}
disabled={isStarting}
onClick={() => onStartOAuth(option.strategy)}
>
<span
className={cn(
"flex min-w-0 items-center justify-center gap-3",
useBlockButtons && "w-full",
)}
>
{isCurrent ? (
<LoaderCircleIcon className="size-4 animate-spin opacity-70" />
) : (
<DesktopClerkProviderIcon option={option} />
)}
{useBlockButtons ? (
<span className="truncate">
{oauthOptions.length === 1 ? `Continue with ${option.label}` : option.label}
</span>
) : null}
</span>
</button>
);
})}
</div>
);
}
function DesktopClerkProviderIcon({ option }: { option: DesktopCloudAuthOAuthOption }) {
if (!option.iconUrl) {
return (
<span
aria-hidden
className="flex size-4 shrink-0 items-center justify-center rounded bg-muted text-[9px] font-bold text-muted-foreground"
>
{option.label.slice(0, 1).toUpperCase()}
</span>
);
}
if (["apple", "github", "vercel"].includes(option.providerId)) {
return (
<span
aria-hidden
className="size-4 shrink-0 bg-foreground"
style={{
WebkitMask: `url(${option.iconUrl}) center / cover no-repeat`,
mask: `url(${option.iconUrl}) center / cover no-repeat`,
}}
/>
);
}
return <img alt="" aria-hidden className="size-4 shrink-0" src={option.iconUrl} />;
}
@@ -1,106 +0,0 @@
import { useClerk } from "@clerk/react";
import { useState } from "react";
import {
DesktopClerkAlert,
DesktopClerkCard,
DesktopClerkFooterAction,
DesktopClerkHeader,
DesktopClerkInput,
DesktopClerkPrimaryButton,
} from "./DesktopClerkCard";
import { DesktopClerkSignIn } from "./DesktopClerkSignIn";
type DesktopClerkScreen = "waitlist" | "sign-in";
// Mirrors Clerk's waitlist card and form, replacing its router transition with the desktop sign-in flow:
// https://github.com/clerk/javascript/blob/52861184477bee99c71552000311a289e91d3b59/packages/ui/src/components/Waitlist/index.tsx
// https://github.com/clerk/javascript/blob/52861184477bee99c71552000311a289e91d3b59/packages/ui/src/components/Waitlist/WaitlistForm.tsx
export function DesktopClerkWaitlist() {
const [screen, setScreen] = useState<DesktopClerkScreen>("waitlist");
if (screen === "sign-in") {
return <DesktopClerkSignIn onJoinWaitlist={() => setScreen("waitlist")} />;
}
return <DesktopClerkWaitlistForm onSignIn={() => setScreen("sign-in")} />;
}
function DesktopClerkWaitlistForm({ onSignIn }: { onSignIn: () => void }) {
const clerk = useClerk();
const [emailAddress, setEmailAddress] = useState("");
const [error, setError] = useState<string | null>(null);
const [isSubmitting, setIsSubmitting] = useState(false);
const [didJoin, setDidJoin] = useState(false);
const submitWaitlist = async (event: React.FormEvent<HTMLFormElement>) => {
event.preventDefault();
setError(null);
setIsSubmitting(true);
try {
await clerk.joinWaitlist({ emailAddress });
setDidJoin(true);
} catch (cause) {
setError(getClerkErrorMessage(cause));
} finally {
setIsSubmitting(false);
}
};
if (didJoin) {
return (
<DesktopClerkCard>
<DesktopClerkHeader
title="Thanks for joining the waitlist!"
subtitle="We’ll be in touch when your spot is ready"
/>
</DesktopClerkCard>
);
}
return (
<DesktopClerkCard
footerAction={
<DesktopClerkFooterAction actionLabel="Sign in" onAction={onSignIn}>
Already have access?
</DesktopClerkFooterAction>
}
>
<DesktopClerkHeader
title="Join the waitlist"
subtitle="Enter your email address and we’ll let you know when your spot is ready"
/>
<DesktopClerkAlert>{error}</DesktopClerkAlert>
<form className="space-y-8 text-left" onSubmit={submitWaitlist}>
<label className="block space-y-2" htmlFor="desktop-clerk-waitlist-email">
<span className="text-sm font-semibold text-foreground">Email address</span>
<DesktopClerkInput
required
autoComplete="email"
id="desktop-clerk-waitlist-email"
name="emailAddress"
placeholder="Enter your email address"
type="email"
value={emailAddress}
onChange={(event) => setEmailAddress(event.currentTarget.value)}
/>
</label>
<DesktopClerkPrimaryButton disabled={isSubmitting}>
{isSubmitting ? "Joining the waitlist…" : "Join the waitlist"}
</DesktopClerkPrimaryButton>
</form>
</DesktopClerkCard>
);
}
function getClerkErrorMessage(error: unknown): string {
if (typeof error === "object" && error !== null && "errors" in error) {
const errors = (error as { errors?: Array<{ longMessage?: unknown; message?: unknown }> })
.errors;
const firstError = errors?.[0];
if (typeof firstError?.longMessage === "string") return firstError.longMessage;
if (typeof firstError?.message === "string") return firstError.message;
}
if (error instanceof Error && error.message) return error.message;
return "Could not join the waitlist. Please try again.";
}
@@ -1,199 +0,0 @@
import { useClerk } from "@clerk/react";
import { useSignIn, useSignUp } from "@clerk/react/legacy";
import { useCallback, useEffect, useRef, useState } from "react";
import {
type DesktopCloudAuthOAuthStrategy,
resolveDesktopCloudAuthOAuthOptions,
} from "../../cloud/desktopAuth";
import { toastManager } from "../ui/toast";
// Mirrors Clerk Expo's browser-based native SSO flow, with Electron handling the external browser
// and callback transport:
// https://github.com/clerk/javascript/blob/52861184477bee99c71552000311a289e91d3b59/packages/expo/src/hooks/useSSO.ts
class DesktopClerkOperationError extends Error {
override readonly cause?: unknown;
constructor(message: string, cause?: unknown) {
super(message);
this.name = "DesktopClerkOperationError";
this.cause = cause;
}
}
async function runDesktopClerkOperation<T>(
operation: () => Promise<T>,
message: string,
): Promise<T> {
try {
return await operation();
} catch (cause) {
throw new DesktopClerkOperationError(message, cause);
}
}
function desktopClerkErrorMessage(error: unknown, fallback: string): string {
if (error instanceof DesktopClerkOperationError) {
const cause = error.cause;
if (cause instanceof Error && cause.message && cause.message !== error.message) {
return `${error.message}: ${cause.message}`;
}
return error.message;
}
return error instanceof Error ? error.message : fallback;
}
export function useDesktopClerkSignIn() {
const clerk = useClerk();
const { setActive } = clerk;
const { isLoaded: signInLoaded, signIn } = useSignIn();
const { isLoaded: signUpLoaded, signUp } = useSignUp();
const [startingStrategy, setStartingStrategy] = useState<DesktopCloudAuthOAuthStrategy | null>(
null,
);
const oauthOptions = resolveDesktopCloudAuthOAuthOptions(clerk);
const callbackCleanupRef = useRef<(() => void) | null>(null);
const clearCallbackListener = useCallback(() => {
callbackCleanupRef.current?.();
callbackCleanupRef.current = null;
}, []);
const completeOAuthCallback = useCallback(
async (rawUrl: string) => {
if (!signInLoaded || !signIn || !signUpLoaded || !signUp) {
toastManager.add({
type: "error",
title: "Cloud sign-in failed",
description: "Clerk is still loading. Try signing in again.",
});
return;
}
let rotatingTokenNonce: string | null = null;
let sessionId: string | null = null;
try {
const callbackUrl = new URL(rawUrl);
rotatingTokenNonce = callbackUrl.searchParams.get("rotating_token_nonce");
sessionId = callbackUrl.searchParams.get("created_session_id");
} catch {
// Handled by the explicit nonce check below.
}
if (!rotatingTokenNonce) {
toastManager.add({
type: "error",
title: "Cloud sign-in failed",
description:
"Clerk did not return a native session nonce. Verify this redirect URL is allowlisted for native SSO redirects.",
});
return;
}
try {
await runDesktopClerkOperation(
() => signIn.reload({ rotatingTokenNonce }),
"Could not reload the desktop sign-in session.",
);
sessionId = sessionId || signIn.createdSessionId;
if (!sessionId && signIn.firstFactorVerification.status === "transferable") {
const signUpAttempt = await runDesktopClerkOperation(
() => signUp.create({ transfer: true }),
"Could not transfer the desktop sign-up session.",
);
sessionId = signUpAttempt.createdSessionId;
}
if (!sessionId) {
throw new DesktopClerkOperationError("Clerk did not create a desktop session.");
}
await runDesktopClerkOperation(
() => setActive({ session: sessionId! }),
"Could not activate the desktop cloud session.",
);
} catch (error) {
toastManager.add({
type: "error",
title: "Cloud sign-in failed",
description: desktopClerkErrorMessage(error, "Could not complete cloud sign-in."),
});
}
},
[setActive, signIn, signInLoaded, signUp, signUpLoaded],
);
useEffect(() => {
return () => {
clearCallbackListener();
};
}, [clearCallbackListener]);
const startOAuth = useCallback(
async (strategy: DesktopCloudAuthOAuthStrategy) => {
if (!signInLoaded || !signIn) {
toastManager.add({
type: "error",
title: "Cloud sign-in failed",
description: "Clerk is still loading. Try signing in again.",
});
return;
}
setStartingStrategy(strategy);
clearCallbackListener();
try {
const redirectUrl = await runDesktopClerkOperation(
() => window.desktopBridge?.createCloudAuthRequest() ?? Promise.resolve(undefined),
"Desktop auth callback is unavailable.",
);
if (!redirectUrl) {
throw new DesktopClerkOperationError("Desktop auth callback is unavailable.");
}
callbackCleanupRef.current =
window.desktopBridge?.onCloudAuthCallback((rawUrl) => {
clearCallbackListener();
void completeOAuthCallback(rawUrl);
}) ?? null;
await runDesktopClerkOperation(
() => signIn.create({ strategy, redirectUrl } as never),
"Could not create the desktop OAuth request.",
);
const externalUrl =
signIn.firstFactorVerification.externalVerificationRedirectURL?.toString();
if (!externalUrl) {
throw new DesktopClerkOperationError(
"Clerk did not return an external OAuth redirect URL.",
);
}
const opened = await runDesktopClerkOperation(
() => window.desktopBridge?.openExternal(externalUrl) ?? Promise.resolve(false),
"Could not open the system browser.",
);
if (!opened) {
throw new DesktopClerkOperationError("Could not open the system browser.");
}
} catch (error) {
clearCallbackListener();
toastManager.add({
type: "error",
title: "Cloud sign-in failed",
description: desktopClerkErrorMessage(error, "Could not start cloud sign-in."),
});
} finally {
setStartingStrategy(null);
}
},
[clearCallbackListener, completeOAuthCallback, signIn, signInLoaded],
);
return {
isStarting: startingStrategy !== null,
oauthOptions,
startingStrategy,
startOAuth,
};
}
@@ -1,29 +1,9 @@
import { useClerk } from "@clerk/react";
import { useState } from "react";
import { isElectron } from "../../env";
import { Dialog, DialogPopup } from "../ui/dialog";
import { DesktopClerkWaitlist } from "./DesktopClerkWaitlist";
export function useT3ConnectAuthPrompt() {
const clerk = useClerk();
const [desktopAuthOpen, setDesktopAuthOpen] = useState(false);
const openAuthPrompt = () => {
if (isElectron) {
setDesktopAuthOpen(true);
return;
}
clerk.openWaitlist();
};
const authPrompt = isElectron ? (
<Dialog open={desktopAuthOpen} onOpenChange={setDesktopAuthOpen}>
<DialogPopup className="max-w-md border-0 bg-transparent shadow-none" showCloseButton={false}>
<DesktopClerkWaitlist />
</DialogPopup>
</Dialog>
) : null;
return { authPrompt, openAuthPrompt };
return { authPrompt: null, openAuthPrompt };
}
@@ -9,6 +9,7 @@ import {
ProviderDriverKind,
type ProviderInstanceConfig,
type ProviderInstanceId,
type RuntimeMode,
type ScopedThreadRef,
} from "@t3tools/contracts";
import { scopeThreadRef } from "@t3tools/client-runtime/environment";
@@ -108,6 +109,12 @@ const TIMESTAMP_FORMAT_LABELS = {
"24-hour": "24-hour",
} as const;
const RUNTIME_MODE_LABELS: Record<RuntimeMode, string> = {
"approval-required": "Supervised",
"auto-accept-edits": "Auto-accept edits",
"full-access": "Full access",
};
const DEFAULT_DRIVER_KIND = ProviderDriverKind.make("codex");
function withoutProviderInstanceKey<V>(
@@ -412,6 +419,9 @@ export function useSettingsRestore(onRestored?: () => void) {
DEFAULT_UNIFIED_SETTINGS.newWorktreesStartFromOrigin
? ["New worktrees start from origin"]
: []),
...(settings.defaultRuntimeMode !== DEFAULT_UNIFIED_SETTINGS.defaultRuntimeMode
? ["Default access mode"]
: []),
...(settings.addProjectBaseDirectory !== DEFAULT_UNIFIED_SETTINGS.addProjectBaseDirectory
? ["Add project base directory"]
: []),
@@ -429,6 +439,7 @@ export function useSettingsRestore(onRestored?: () => void) {
settings.confirmThreadArchive,
settings.confirmThreadDelete,
settings.addProjectBaseDirectory,
settings.defaultRuntimeMode,
settings.defaultThreadEnvMode,
settings.newWorktreesStartFromOrigin,
settings.diffIgnoreWhitespace,
@@ -462,6 +473,7 @@ export function useSettingsRestore(onRestored?: () => void) {
automaticGitFetchInterval: DEFAULT_UNIFIED_SETTINGS.automaticGitFetchInterval,
defaultThreadEnvMode: DEFAULT_UNIFIED_SETTINGS.defaultThreadEnvMode,
newWorktreesStartFromOrigin: DEFAULT_UNIFIED_SETTINGS.newWorktreesStartFromOrigin,
defaultRuntimeMode: DEFAULT_UNIFIED_SETTINGS.defaultRuntimeMode,
addProjectBaseDirectory: DEFAULT_UNIFIED_SETTINGS.addProjectBaseDirectory,
confirmThreadArchive: DEFAULT_UNIFIED_SETTINGS.confirmThreadArchive,
confirmThreadDelete: DEFAULT_UNIFIED_SETTINGS.confirmThreadDelete,
@@ -668,6 +680,33 @@ export function GeneralSettingsPanel() {
}
/>
<SettingsRow
title="Provider update checks"
description="Check installed provider CLIs for newer available versions."
resetAction={
settings.enableProviderUpdateChecks !==
DEFAULT_UNIFIED_SETTINGS.enableProviderUpdateChecks ? (
<SettingResetButton
label="provider update checks"
onClick={() =>
updateSettings({
enableProviderUpdateChecks: DEFAULT_UNIFIED_SETTINGS.enableProviderUpdateChecks,
})
}
/>
) : null
}
control={
<Switch
checked={settings.enableProviderUpdateChecks}
onCheckedChange={(checked) =>
updateSettings({ enableProviderUpdateChecks: Boolean(checked) })
}
aria-label="Check provider versions"
/>
}
/>
<SettingsRow
title="Auto-open task panel"
description="Open the right-side plan and task panel automatically when steps appear."
@@ -770,6 +809,52 @@ export function GeneralSettingsPanel() {
/>
) : null}
<SettingsRow
title="Default access"
description="Pick the permission mode used when newly created draft threads start."
resetAction={
settings.defaultRuntimeMode !== DEFAULT_UNIFIED_SETTINGS.defaultRuntimeMode ? (
<SettingResetButton
label="default access mode"
onClick={() =>
updateSettings({
defaultRuntimeMode: DEFAULT_UNIFIED_SETTINGS.defaultRuntimeMode,
})
}
/>
) : null
}
control={
<Select
value={settings.defaultRuntimeMode}
onValueChange={(value) => {
if (
value === "approval-required" ||
value === "auto-accept-edits" ||
value === "full-access"
) {
updateSettings({ defaultRuntimeMode: value });
}
}}
>
<SelectTrigger className="w-full sm:w-44" aria-label="Default access mode">
<SelectValue>{RUNTIME_MODE_LABELS[settings.defaultRuntimeMode]}</SelectValue>
</SelectTrigger>
<SelectPopup align="end" alignItemWithTrigger={false}>
<SelectItem hideIndicator value="approval-required">
{RUNTIME_MODE_LABELS["approval-required"]}
</SelectItem>
<SelectItem hideIndicator value="auto-accept-edits">
{RUNTIME_MODE_LABELS["auto-accept-edits"]}
</SelectItem>
<SelectItem hideIndicator value="full-access">
{RUNTIME_MODE_LABELS["full-access"]}
</SelectItem>
</SelectPopup>
</Select>
}
/>
<SettingsRow
title="Add project starts in"
description='Leave empty to use "~/" when the Add Project browser opens.'
+31 -30
View File
@@ -3,6 +3,7 @@ import {
CloudSession,
EnvironmentOwnedDataCleanup,
PlatformConnectionSource,
PrimaryEnvironmentAuth,
RelayDeviceIdentity,
SshEnvironmentGateway,
} from "@t3tools/client-runtime/platform";
@@ -30,9 +31,9 @@ import * as Option from "effect/Option";
import * as Queue from "effect/Queue";
import * as Schedule from "effect/Schedule";
import * as Stream from "effect/Stream";
import { FetchHttpClient, HttpClient } from "effect/unstable/http";
import { primaryEnvironmentRequestInit } from "../environments/primary/requestInit";
import { readDesktopPrimaryBearerToken } from "../environments/primary/desktopAuth";
import { primaryEnvironmentHttpLayer } from "../environments/primary/httpLayer";
import { readPrimaryEnvironmentTarget } from "../environments/primary/target";
import { clearComposerDraftsEnvironment } from "../composerDraftStore";
import { isHostedStaticApp } from "../hostedPairing";
@@ -193,6 +194,16 @@ const capabilitiesLayer = Layer.effectContext(
const identity = RelayDeviceIdentity.of({
deviceId: Effect.succeed(Option.none()),
});
const primaryAuth = PrimaryEnvironmentAuth.of({
bearerToken: Effect.tryPromise({
try: readDesktopPrimaryBearerToken,
catch: (cause) =>
new ConnectionTransientError({
reason: "remote-unavailable",
message: `Could not load the desktop primary credential: ${String(cause)}`,
}),
}).pipe(Effect.map(Option.fromNullishOr)),
});
const ssh = SshEnvironmentGateway.of({
provision: Effect.fn("web.connectionPlatform.ssh.provision")(function* (target) {
const bridge = window.desktopBridge;
@@ -252,6 +263,7 @@ const capabilitiesLayer = Layer.effectContext(
});
return Context.make(CloudSession, cloudSession).pipe(
Context.add(PrimaryEnvironmentAuth, primaryAuth),
Context.add(RelayDeviceIdentity, identity),
Context.add(ClientPresentation, presentation),
Context.add(SshEnvironmentGateway, ssh),
@@ -271,10 +283,7 @@ const loadPrimaryConnectionRegistration = Effect.fn(
}
const descriptor = yield* fetchRemoteEnvironmentDescriptor({
httpBaseUrl: resolved.target.httpBaseUrl,
}).pipe(
Effect.provideService(FetchHttpClient.RequestInit, primaryEnvironmentRequestInit),
Effect.mapError(mapRemoteEnvironmentError),
);
}).pipe(Effect.provide(primaryEnvironmentHttpLayer), Effect.mapError(mapRemoteEnvironmentError));
return new PrimaryConnectionRegistration({
target: new PrimaryConnectionTarget({
environmentId: descriptor.environmentId,
@@ -289,32 +298,24 @@ const primaryRegistrationRetrySchedule = Schedule.exponential("1 second").pipe(
Schedule.either(Schedule.spaced("16 seconds")),
);
const platformConnectionSourceLayer = Layer.effect(
PlatformConnectionSource,
Effect.gen(function* () {
if (isHostedStaticApp()) {
return PlatformConnectionSource.of({
registrations: Stream.empty,
});
}
const httpClient = yield* HttpClient.HttpClient;
const platformConnectionSourceLayer = Layer.sync(PlatformConnectionSource, () => {
if (isHostedStaticApp()) {
return PlatformConnectionSource.of({
registrations: Stream.fromEffect(
loadPrimaryConnectionRegistration().pipe(
Effect.provideService(HttpClient.HttpClient, httpClient),
),
).pipe(
Stream.tapError((error) =>
Effect.logWarning("Could not discover the primary environment.", {
error,
}),
),
Stream.retry(primaryRegistrationRetrySchedule),
Stream.catchCause(() => Stream.empty),
),
registrations: Stream.empty,
});
}),
);
}
return PlatformConnectionSource.of({
registrations: Stream.fromEffect(loadPrimaryConnectionRegistration()).pipe(
Stream.tapError((error) =>
Effect.logWarning("Could not discover the primary environment.", {
error,
}),
),
Stream.retry(primaryRegistrationRetrySchedule),
Stream.catchCause(() => Stream.empty),
),
});
});
const environmentOwnedDataCleanupLayer = Layer.succeed(
EnvironmentOwnedDataCleanup,
@@ -0,0 +1,33 @@
import type { DesktopBridge } from "@t3tools/contracts";
import { afterEach, beforeEach, describe, expect, it, vi } from "@effect/vitest";
import { __resetDesktopPrimaryAuthForTests, readDesktopPrimaryBearerToken } from "./desktopAuth";
describe("desktop primary auth", () => {
beforeEach(() => {
Object.defineProperty(globalThis, "window", {
configurable: true,
value: {},
});
});
afterEach(() => {
__resetDesktopPrimaryAuthForTests();
Reflect.deleteProperty(globalThis, "window");
});
it("reuses the main-process bearer token across renderer requests", async () => {
const getLocalEnvironmentBearerToken = vi.fn().mockResolvedValue("desktop-bearer-token");
window.desktopBridge = {
getLocalEnvironmentBearerToken,
} as unknown as DesktopBridge;
await expect(readDesktopPrimaryBearerToken()).resolves.toBe("desktop-bearer-token");
await expect(readDesktopPrimaryBearerToken()).resolves.toBe("desktop-bearer-token");
expect(getLocalEnvironmentBearerToken).toHaveBeenCalledTimes(1);
});
it("does not require desktop auth in a browser", async () => {
await expect(readDesktopPrimaryBearerToken()).resolves.toBeNull();
});
});
@@ -0,0 +1,21 @@
let desktopBearerTokenPromise: Promise<string> | null = null;
export function readDesktopPrimaryBearerToken(): Promise<string | null> {
if (typeof window === "undefined") {
return Promise.resolve(null);
}
const bridge = window.desktopBridge;
if (!bridge) {
return Promise.resolve(null);
}
desktopBearerTokenPromise ??= bridge.getLocalEnvironmentBearerToken().catch((error) => {
desktopBearerTokenPromise = null;
throw error;
});
return desktopBearerTokenPromise;
}
export function __resetDesktopPrimaryAuthForTests(): void {
desktopBearerTokenPromise = null;
}
@@ -0,0 +1,65 @@
import type { DesktopBridge } from "@t3tools/contracts";
import { afterEach, describe, expect, it, vi } from "@effect/vitest";
import * as Effect from "effect/Effect";
import { HttpClient } from "effect/unstable/http";
import { __resetDesktopPrimaryAuthForTests } from "./desktopAuth";
import { makePrimaryEnvironmentHttpLayer } from "./httpLayer";
describe.sequential("primary environment HTTP layer", () => {
afterEach(() => {
__resetDesktopPrimaryAuthForTests();
Reflect.deleteProperty(globalThis, "window");
vi.unstubAllGlobals();
});
it.effect("uses cookie credentials for browser primary environments", () => {
const fetchMock = vi.fn().mockResolvedValue(new Response(null, { status: 200 }));
vi.stubGlobal("fetch", fetchMock);
Object.defineProperty(globalThis, "window", {
configurable: true,
value: {
location: {
href: "http://127.0.0.1:3773/settings",
origin: "http://127.0.0.1:3773",
},
},
});
return Effect.gen(function* () {
yield* HttpClient.get("http://127.0.0.1:3773/api/auth/session");
const request = new Request(fetchMock.mock.calls[0]?.[0], fetchMock.mock.calls[0]?.[1]);
expect(request.credentials).toBe("include");
expect(request.headers.get("authorization")).toBeNull();
}).pipe(Effect.provide(makePrimaryEnvironmentHttpLayer()));
});
it.effect("uses bearer auth without cookies for desktop-managed primaries", () => {
const fetchMock = vi.fn().mockResolvedValue(new Response(null, { status: 200 }));
vi.stubGlobal("fetch", fetchMock);
Object.defineProperty(globalThis, "window", {
configurable: true,
value: {
location: { origin: "t3code://app" },
desktopBridge: {
getLocalEnvironmentBootstrap: () => ({
label: "Local environment",
httpBaseUrl: "http://127.0.0.1:3773",
wsBaseUrl: "ws://127.0.0.1:3773",
bootstrapToken: "desktop-bootstrap-token",
}),
getLocalEnvironmentBearerToken: vi.fn().mockResolvedValue("desktop-bearer-token"),
} as unknown as DesktopBridge,
},
});
return Effect.gen(function* () {
yield* HttpClient.get("http://127.0.0.1:3773/api/connect/link-state");
const request = new Request(fetchMock.mock.calls[0]?.[0], fetchMock.mock.calls[0]?.[1]);
expect(request.credentials).not.toBe("include");
expect(request.headers.get("authorization")).toBe("Bearer desktop-bearer-token");
}).pipe(Effect.provide(makePrimaryEnvironmentHttpLayer()));
});
});
@@ -0,0 +1,58 @@
import { remoteHttpClientLayer } from "@t3tools/client-runtime/rpc";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import { FetchHttpClient, HttpClient, HttpClientRequest } from "effect/unstable/http";
import { readDesktopPrimaryBearerToken } from "./desktopAuth";
import { resolvePrimaryEnvironmentHttpUrl } from "./target";
function isSameOriginBrowserPrimary(): boolean {
if (
typeof window === "undefined" ||
window.desktopBridge !== undefined ||
window.nativeApi !== undefined ||
!window.location.origin.startsWith("http")
) {
return false;
}
return new URL(resolvePrimaryEnvironmentHttpUrl("/")).origin === window.location.origin;
}
function withPrimaryBearerToken(client: HttpClient.HttpClient): HttpClient.HttpClient {
return client.pipe(
HttpClient.mapRequestEffect((request) =>
Effect.promise(readDesktopPrimaryBearerToken).pipe(
Effect.map((bearerToken) =>
bearerToken ? HttpClientRequest.bearerToken(request, bearerToken) : request,
),
),
),
);
}
export function makePrimaryEnvironmentHttpLayer() {
return Layer.unwrap(
Effect.sync(() => {
const baseLayer = remoteHttpClientLayer(globalThis.fetch);
if (isSameOriginBrowserPrimary()) {
return Layer.merge(
baseLayer,
Layer.succeed(FetchHttpClient.RequestInit, { credentials: "include" }),
);
}
const bearerClientLayer = Layer.effect(
HttpClient.HttpClient,
Effect.map(HttpClient.HttpClient, withPrimaryBearerToken),
).pipe(Layer.provide(baseLayer));
return Layer.merge(
bearerClientLayer,
Layer.succeed(FetchHttpClient.RequestInit, { credentials: "omit" }),
);
}),
);
}
export const primaryEnvironmentHttpLayer = makePrimaryEnvironmentHttpLayer();
@@ -33,6 +33,8 @@ export {
export { refreshPrimarySessionState, usePrimarySessionState } from "./sessionState";
export { PrimaryEnvironmentHttpClient } from "./httpClient";
export {
readPrimaryEnvironmentTarget,
resolvePrimaryEnvironmentHttpUrl,
@@ -1,7 +0,0 @@
import * as Effect from "effect/Effect";
import { FetchHttpClient } from "effect/unstable/http";
export const primaryEnvironmentRequestInit = { credentials: "include" } as const;
export const withPrimaryEnvironmentRequestInit = <A, E, R>(effect: Effect.Effect<A, E, R>) =>
effect.pipe(Effect.provideService(FetchHttpClient.RequestInit, primaryEnvironmentRequestInit));
+16 -7
View File
@@ -3,7 +3,7 @@ import {
scopeProjectRef,
scopeThreadRef,
} from "@t3tools/client-runtime/environment";
import { DEFAULT_RUNTIME_MODE, type ScopedProjectRef } from "@t3tools/contracts";
import { type ScopedProjectRef } from "@t3tools/contracts";
import { useParams, useRouter } from "@tanstack/react-router";
import { useCallback, useMemo } from "react";
import {
@@ -20,7 +20,11 @@ import {
selectProjectGroupingSettings,
} from "../logicalProject";
import { readThreadShell, useProjects, useThread } from "../state/entities";
import { resolveNewDraftStartFromOrigin } from "../lib/chatThreadActions";
import {
buildNewDraftExecutionDefaults,
resolveNewDraftStartFromOrigin,
} from "../lib/chatThreadActions";
import { loadClientSettingsForNewThread } from "../lib/clientSettingsHydration";
import { resolveThreadRouteTarget } from "../threadRoutes";
import { legacyProjectCwdPreferenceKey, useUiStateStore } from "../uiStateStore";
import { useSettings } from "./useSettings";
@@ -152,11 +156,16 @@ export function useNewThreadHandler() {
return Promise.resolve();
}
const draftId = newDraftId();
const threadId = newThreadId();
const createdAt = new Date().toISOString();
const initialEnvMode = options?.envMode ?? "local";
return (async () => {
const clientSettings = await loadClientSettingsForNewThread();
if (!clientSettings) {
return;
}
const draftId = newDraftId();
const threadId = newThreadId();
const createdAt = new Date().toISOString();
const initialEnvMode = options?.envMode ?? "local";
setLogicalProjectDraftThreadId(logicalProjectKey, projectRef, draftId, {
threadId,
createdAt,
@@ -169,7 +178,7 @@ export function useNewThreadHandler() {
envMode: initialEnvMode,
newWorktreesStartFromOrigin,
}),
runtimeMode: DEFAULT_RUNTIME_MODE,
...buildNewDraftExecutionDefaults(clientSettings.defaultRuntimeMode),
});
applyStickyState(draftId);
+74
View File
@@ -0,0 +1,74 @@
import { DEFAULT_CLIENT_SETTINGS, type DesktopBridge } from "@t3tools/contracts";
import { afterEach, describe, expect, it, vi } from "vite-plus/test";
function deferred<T>() {
let resolve!: (value: T) => void;
let reject!: (reason?: unknown) => void;
const promise = new Promise<T>((resolvePromise, rejectPromise) => {
resolve = resolvePromise;
reject = rejectPromise;
});
return { promise, reject, resolve };
}
function stubDesktopSettings(getClientSettings: DesktopBridge["getClientSettings"]): void {
vi.stubGlobal("window", {
desktopBridge: {
getClientSettings,
} as DesktopBridge,
});
}
afterEach(() => {
vi.resetModules();
vi.unstubAllGlobals();
vi.restoreAllMocks();
});
describe("getHydratedClientSettings", () => {
it("waits for persisted settings instead of returning the eager defaults", async () => {
const persistedSettings = {
...DEFAULT_CLIENT_SETTINGS,
defaultRuntimeMode: "approval-required" as const,
};
const settingsRequest = deferred<typeof persistedSettings | null>();
stubDesktopSettings(() => settingsRequest.promise);
const { getHydratedClientSettings } = await import("./useSettings");
let settled = false;
const hydration = getHydratedClientSettings().then((settings) => {
settled = true;
return settings;
});
await Promise.resolve();
expect(settled).toBe(false);
settingsRequest.resolve(persistedSettings);
await expect(hydration).resolves.toEqual(persistedSettings);
});
it("rejects when persisted settings cannot be loaded", async () => {
const error = new Error("settings unavailable");
stubDesktopSettings(() => Promise.reject(error));
vi.spyOn(console, "error").mockImplementation(() => undefined);
const { getHydratedClientSettings } = await import("./useSettings");
await expect(getHydratedClientSettings()).rejects.toBe(error);
});
it("blocks new-thread defaults when persisted settings cannot be loaded", async () => {
const error = new Error("settings unavailable");
stubDesktopSettings(() => Promise.reject(error));
vi.spyOn(console, "error").mockImplementation(() => undefined);
const { toastManager } = await import("../components/ui/toast");
const addToast = vi.spyOn(toastManager, "add").mockImplementation(() => "toast-1");
const { loadClientSettingsForNewThread } = await import("../lib/clientSettingsHydration");
await expect(loadClientSettingsForNewThread()).resolves.toBeNull();
expect(addToast).toHaveBeenCalledWith(
expect.objectContaining({
title: "Could not create thread",
}),
);
});
});
+16 -6
View File
@@ -64,7 +64,7 @@ function setClientSettingsHydrated(nextHydrated: boolean): void {
function subscribeClientSettings(listener: () => void): () => void {
clientSettingsListeners.add(listener);
void hydrateClientSettings();
void hydrateClientSettings().catch(() => undefined);
return () => {
clientSettingsListeners.delete(listener);
};
@@ -76,7 +76,7 @@ function getClientSettingsHydratedSnapshot(): boolean {
function subscribeClientSettingsHydration(listener: () => void): () => void {
clientSettingsHydrationListeners.add(listener);
void hydrateClientSettings();
void hydrateClientSettings().catch(() => undefined);
return () => {
clientSettingsHydrationListeners.delete(listener);
};
@@ -100,12 +100,10 @@ async function hydrateClientSettings(): Promise<void> {
if (persistedSettings) {
replaceClientSettingsSnapshot({ ...DEFAULT_CLIENT_SETTINGS, ...persistedSettings });
}
setClientSettingsHydrated(true);
} catch (error) {
console.error(`${CLIENT_SETTINGS_PERSISTENCE_ERROR_SCOPE} hydrate failed`, error);
} finally {
if (hydrationGeneration === clientSettingsHydrationGeneration) {
setClientSettingsHydrated(true);
}
throw error;
}
})();
@@ -167,6 +165,18 @@ export function getClientSettings(): ClientSettings {
return getClientSettingsSnapshot();
}
/**
* Waits for persisted client settings before returning the current snapshot.
*
* User actions whose behavior depends on a persisted setting must use this
* accessor instead of the eager default snapshot. Hydration failures reject
* so callers can stop the action instead of silently falling back.
*/
export async function getHydratedClientSettings(): Promise<ClientSettings> {
await hydrateClientSettings();
return getClientSettingsSnapshot();
}
export function useClientSettingsHydrated(): boolean {
return useSyncExternalStore(
subscribeClientSettingsHydration,
+9 -1
View File
@@ -2,8 +2,9 @@ import { scopeProjectRef } from "@t3tools/client-runtime/environment";
import { EnvironmentId, ProjectId } from "@t3tools/contracts";
import { describe, expect, it, vi } from "vite-plus/test";
import {
resolveThreadActionProjectRef,
buildNewDraftExecutionDefaults,
resolveNewDraftStartFromOrigin,
resolveThreadActionProjectRef,
startNewLocalThreadFromContext,
startNewThreadFromContext,
type ChatThreadActionContext,
@@ -25,6 +26,13 @@ function createContext(overrides: Partial<ChatThreadActionContext> = {}): ChatTh
}
describe("chatThreadActions", () => {
it("initializes new drafts with the configured default access mode", () => {
expect(buildNewDraftExecutionDefaults("approval-required")).toEqual({
runtimeMode: "approval-required",
interactionMode: "default",
});
});
it("only applies the start-from-origin default to new worktree drafts", () => {
expect(
resolveNewDraftStartFromOrigin({
+18 -1
View File
@@ -1,5 +1,12 @@
import { scopeProjectRef } from "@t3tools/client-runtime/environment";
import type { EnvironmentId, ProjectId, ScopedProjectRef } from "@t3tools/contracts";
import {
DEFAULT_PROVIDER_INTERACTION_MODE,
type EnvironmentId,
type ProjectId,
type ProviderInteractionMode,
type RuntimeMode,
type ScopedProjectRef,
} from "@t3tools/contracts";
import type { DraftThreadEnvMode } from "../composerDraftStore";
interface ThreadContextLike {
@@ -43,6 +50,16 @@ export function resolveNewDraftStartFromOrigin(input: {
return input.envMode === "worktree" && input.newWorktreesStartFromOrigin;
}
export function buildNewDraftExecutionDefaults(defaultRuntimeMode: RuntimeMode): {
runtimeMode: RuntimeMode;
interactionMode: ProviderInteractionMode;
} {
return {
runtimeMode: defaultRuntimeMode,
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
};
}
export function resolveThreadActionProjectRef(
context: ChatThreadActionContext,
): ScopedProjectRef | null {
@@ -0,0 +1,22 @@
import type { ClientSettings } from "@t3tools/contracts/settings";
import { stackedThreadToast, toastManager } from "../components/ui/toast";
import { getHydratedClientSettings } from "../hooks/useSettings";
export async function loadClientSettingsForNewThread(): Promise<ClientSettings | null> {
try {
return await getHydratedClientSettings();
} catch (error) {
toastManager.add(
stackedThreadToast({
type: "error",
title: "Could not create thread",
description:
error instanceof Error
? `Could not load your saved default access mode. ${error.message}`
: "Could not load your saved default access mode. No thread was created.",
}),
);
return null;
}
}
+2 -12
View File
@@ -1,17 +1,15 @@
import * as ManagedRuntime from "effect/ManagedRuntime";
import type * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import { FetchHttpClient } from "effect/unstable/http";
import * as Socket from "effect/unstable/socket/Socket";
import { remoteHttpClientLayer } from "@t3tools/client-runtime/rpc";
import { httpHeaderRedactionLayer } from "@t3tools/shared/httpObservability";
import { makeRelayClientTracingLayer } from "@t3tools/shared/relayTracing";
import {
PrimaryEnvironmentHttpClient,
primaryEnvironmentHttpClientLive,
} from "../environments/primary/httpClient";
import { primaryEnvironmentRequestInit } from "../environments/primary/requestInit";
import { primaryEnvironmentHttpLayer } from "../environments/primary/httpLayer";
import { browserCryptoLayer } from "../cloud/dpop";
import { managedRelayClientLayer } from "../cloud/managedRelayLayer";
@@ -32,15 +30,7 @@ const relayTracingLayer = makeRelayClientTracingLayer(resolveRelayTracingConfig(
export const remoteHttpRuntime = ManagedRuntime.make(httpClientLayer);
const primaryHttpRuntime = ManagedRuntime.make(
primaryEnvironmentHttpClientLive.pipe(
Layer.provide(
Layer.mergeAll(
remoteHttpClientLayer((input, init) => globalThis.fetch(input, init)),
Layer.succeed(FetchHttpClient.RequestInit, primaryEnvironmentRequestInit),
httpHeaderRedactionLayer,
),
),
),
primaryEnvironmentHttpClientLive.pipe(Layer.provide(primaryEnvironmentHttpLayer)),
);
export type PrimaryHttpEffectRunner = <A, E>(
+4 -3
View File
@@ -1,6 +1,8 @@
import React from "react";
import ReactDOM from "react-dom/client";
import { ClerkProvider } from "@clerk/react";
import { passkeys } from "@clerk/electron/passkeys";
import { ClerkProvider as ElectronClerkProvider } from "@clerk/electron/react";
import { createHashHistory, createBrowserHistory } from "@tanstack/react-router";
import "@fontsource-variable/dm-sans/index.css";
@@ -10,7 +12,6 @@ import "@xterm/xterm/css/xterm.css";
import "./index.css";
import { isElectron } from "./env";
import { DesktopClerkProvider } from "./cloud/desktopClerk";
import { ManagedRelayAuthProvider } from "./cloud/managedAuth";
import { hasCloudPublicConfig } from "./cloud/publicConfig";
import { getRouter } from "./router";
@@ -37,9 +38,9 @@ ReactDOM.createRoot(document.getElementById("root") as HTMLElement).render(
<React.StrictMode>
{clerkPublishableKey && hasCloudPublicConfig() ? (
isElectron ? (
<DesktopClerkProvider publishableKey={clerkPublishableKey}>
<ElectronClerkProvider publishableKey={clerkPublishableKey} passkeys={passkeys}>
<ManagedRelayAuthProvider>{app}</ManagedRelayAuthProvider>
</DesktopClerkProvider>
</ElectronClerkProvider>
) : (
<ClerkProvider publishableKey={clerkPublishableKey}>
<ManagedRelayAuthProvider>{app}</ManagedRelayAuthProvider>
+3 -2
View File
@@ -3,11 +3,12 @@ import * as Layer from "effect/Layer";
import * as ManagedRuntime from "effect/ManagedRuntime";
import * as Scope from "effect/Scope";
import * as Tracer from "effect/Tracer";
import { FetchHttpClient, HttpClient } from "effect/unstable/http";
import { HttpClient } from "effect/unstable/http";
import { OtlpSerialization, OtlpTracer } from "effect/unstable/observability";
import { settleAsyncResult, squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
import { resolvePrimaryEnvironmentHttpUrl } from "../environments/primary";
import { primaryEnvironmentHttpLayer } from "../environments/primary/httpLayer";
import { isElectron } from "../env";
import { APP_VERSION } from "~/branding";
@@ -22,7 +23,7 @@ const CLIENT_TRACING_RESOURCE = {
} as const;
const delegateRuntimeLayer = Layer.mergeAll(
FetchHttpClient.layer,
primaryEnvironmentHttpLayer,
OtlpSerialization.layerJson,
Layer.succeed(HttpClient.TracerDisabledWhen, () => true),
);
+1
View File
@@ -126,6 +126,7 @@ export default defineConfig(() => {
},
resolve: {
tsconfigPaths: true,
dedupe: ["react", "react-dom"],
},
server: {
host,
+76 -10
View File
@@ -120,20 +120,86 @@ selects the concrete relay deployment, but changing that URL does not require a
## Desktop OAuth Redirect Allowlist
The desktop app opens OAuth in the system browser and returns to the app with a custom URL scheme.
In **Clerk Dashboard > Native applications**, enable native application support and add these
entries under the mobile SSO redirect allowlist:
In **Clerk Dashboard > Native applications**, enable the Native API and add these entries under the
mobile SSO redirect allowlist:
```text
t3code-dev://auth/callback
t3code://auth/callback
t3code-dev://app/
t3code://app/
```
The first entry is for local desktop development. The second is for packaged desktop builds.
The app also adds a request-scoped `t3_state` query parameter and validates it on callback. Initial
sign-in and linked-account OAuth flows both return through this bridge. The desktop provider keeps
Clerk's stock profile component, replaces its renderer-page callback with the custom-scheme callback,
and opens the provider URL in the system browser. Do not add the local renderer URL as an OAuth
redirect: an external browser cannot use it to reopen the packaged app.
Local desktop development uses `t3code-dev://app`, while packaged builds use `t3code://app`. Add the
matching origin to each Clerk instance's Backend API `allowed_origins` array as well. The development
Clerk instance should only need `t3code-dev://app`; the production Clerk instance should only need
`t3code://app`. `@clerk/electron` owns the native request adapter, encrypted Clerk token persistence,
external-browser OAuth transport, and callback delivery for initial sign-in and linked-account flows.
There is currently no Dashboard UI for `allowed_origins`. Preserve any existing entries and update
the instance through the Backend API:
```sh
curl -X PATCH https://api.clerk.com/v1/instance \
-H "Content-Type: application/json" \
-H "Authorization: Bearer $CLERK_SECRET_KEY" \
-d '{"allowed_origins":["t3code://app"]}'
```
Never put `CLERK_SECRET_KEY` in the desktop app, a client-facing environment file, or a build
artifact.
## Desktop Passkeys
The production macOS bundle ID is `com.t3tools.t3code`. To enable native passkeys:
1. Create an explicit macOS App ID for `com.t3tools.t3code` in the Apple Developer portal and enable
**Associated Domains**.
2. Create a compatible macOS provisioning profile for that App ID and the certificate used to sign
the distributed app.
3. In Clerk's Native API settings, add an iOS app with the same Apple Team ID and bundle ID. This is
also the configuration point for Electron/macOS passkeys.
4. Confirm Clerk serves `https://<frontend-api>/.well-known/apple-app-site-association` and that
`webcredentials.apps` contains `<TEAM_ID>.com.t3tools.t3code`.
5. Set the local or CI signing configuration described below.
For a local signed build, add these values to `.env.local` or export them before invoking the
desktop artifact command:
```dotenv
T3CODE_APPLE_TEAM_ID=ABC1234567
T3CODE_MACOS_PROVISIONING_PROFILE=/absolute/path/to/t3code.provisionprofile
# Optional: comma-separated override when Clerk's RP ID differs from the Frontend API hostname.
T3CODE_CLERK_PASSKEY_RP_DOMAINS=example.clerk.accounts.dev,clerk.example.com
```
When `T3CODE_CLERK_PASSKEY_RP_DOMAINS` is absent, the build derives the RP domain from
`T3CODE_CLERK_PUBLISHABLE_KEY`. Signed macOS builds fail early if the Team ID, provisioning profile,
or RP-domain configuration is missing. The generated main-app entitlements include every configured
`webcredentials:<domain>` entry; helper apps keep Electron's minimal default entitlements.
The normal `dev:desktop` launcher is unsigned and cannot complete macOS passkey ceremonies. For
renderer HMR, build and install a signed app first, run the renderer dev server, then launch the
installed app executable with `VITE_DEV_SERVER_URL` and `T3CODE_PORT` set. Rebuild the signed app
after native dependency, main-process, preload, entitlement, provisioning, or signing changes;
renderer-only changes can reuse the installed app.
For the default development ports, run `pnpm dev:web` in one terminal and launch the installed
binary from another:
```sh
VITE_DEV_SERVER_URL=http://127.0.0.1:5733 \
T3CODE_PORT=13773 \
"/Applications/T3 Code (Alpha).app/Contents/MacOS/T3 Code (Alpha)"
```
After changing Associated Domains, bump the build version before rebuilding; macOS may otherwise
reuse stale Shared Web Credentials metadata for the same app/version pair.
Verify the installed bundle before testing:
```sh
codesign --verify --deep --strict "/Applications/T3 Code (Alpha).app"
codesign -d --entitlements :- "/Applications/T3 Code (Alpha).app"
```
The current mobile UI uses Clerk's native authentication view. If a future mobile browser OAuth
flow uses a custom redirect URI, add that exact URI to the same allowlist.
+1 -1
View File
@@ -2,5 +2,5 @@
- `.github/workflows/ci.yml` runs `bun run lint`, `bun run typecheck`, and `bun run test` on pull requests and pushes to `main`.
- `.github/workflows/release.yml` builds macOS (`arm64` and `x64`), Linux (`x64`), and Windows (`x64`) desktop artifacts from a single `v*.*.*` tag and publishes one GitHub release.
- The release workflow auto-enables signing only when secrets are present: Apple credentials for macOS and Azure Trusted Signing credentials for Windows. Without secrets, it still releases unsigned artifacts.
- The release workflow auto-enables signing only when platform credentials are present. macOS passkey builds additionally require `APPLE_TEAM_ID` and the `MACOS_PROVISIONING_PROFILE` secret; Windows uses Azure Trusted Signing. Without the core signing credentials, it still releases unsigned artifacts.
- See [Release Checklist](./release.md) for the full release/signing setup checklist.
+28 -8
View File
@@ -219,26 +219,44 @@ Required secrets used by the workflow:
- `APPLE_API_KEY`
- `APPLE_API_KEY_ID`
- `APPLE_API_ISSUER`
- `MACOS_PROVISIONING_PROFILE` (base64-encoded provisioning profile with Associated Domains)
Required repository variables:
- `APPLE_TEAM_ID`
Optional repository variables:
- `CLERK_PASSKEY_RP_DOMAINS`: comma-separated RP-domain override. By default, the build derives the
domain from the production Clerk publishable key.
Checklist:
1. Apple Developer account access:
- Team has rights to create Developer ID certificates.
2. Create `Developer ID Application` certificate.
3. Export certificate + private key as `.p12` from Keychain.
4. Base64-encode the `.p12` and store as `CSC_LINK`.
5. Store the `.p12` export password as `CSC_KEY_PASSWORD`.
6. In App Store Connect, create an API key (Team key).
7. Add API key values:
2. Create an explicit App ID for `com.t3tools.t3code` and enable Associated Domains.
3. Create a `Developer ID Application` certificate and a compatible provisioning profile for that
App ID with Associated Domains enabled.
4. Export the certificate + private key as `.p12` from Keychain.
5. Base64-encode the `.p12` and store as `CSC_LINK`.
6. Base64-encode the provisioning profile and store it as `MACOS_PROVISIONING_PROFILE`.
7. Store the `.p12` export password as `CSC_KEY_PASSWORD`, and set `APPLE_TEAM_ID` to the
10-character Apple Developer Team ID.
8. In App Store Connect, create an API key (Team key).
9. Add API key values:
- `APPLE_API_KEY`: contents of the downloaded `.p8`
- `APPLE_API_KEY_ID`: Key ID
- `APPLE_API_ISSUER`: Issuer ID
8. Re-run a tag release and confirm macOS artifacts are signed/notarized.
10. Complete the Clerk Native API and AASA setup in [T3 Connect Clerk Setup](../cloud/t3-connect-clerk.md#desktop-passkeys).
11. Re-run a tag release and confirm macOS artifacts are signed/notarized and contain the expected
`com.apple.developer.associated-domains` entitlement.
Notes:
- `APPLE_API_KEY` is stored as raw key text in secrets.
- The workflow writes it to a temporary `AuthKey_<id>.p8` file at runtime.
- The workflow decodes `MACOS_PROVISIONING_PROFILE`, validates it with `security cms`, and passes it
to the desktop packager.
## 3) Azure Trusted Signing setup (Windows)
@@ -281,7 +299,9 @@ Checklist:
## 5) Troubleshooting
- macOS build unsigned when expected signed:
- Check all Apple secrets are populated and non-empty.
- Check all Apple secrets plus `APPLE_TEAM_ID` are populated and non-empty.
- Confirm the provisioning profile belongs to `APPLE_TEAM_ID.com.t3tools.t3code` and includes
Associated Domains.
- Windows build unsigned when expected signed:
- Check all Azure ATS and auth secrets are populated and non-empty.
- Build fails with signing error:
+4 -1
View File
@@ -20,11 +20,14 @@
- Default build is unsigned/not notarized for local sharing.
- The DMG build uses `assets/macos-icon-1024.png` as the production app icon source.
- Desktop production windows load the bundled UI from `t3://app/index.html` (not a `127.0.0.1` document URL).
- Desktop production windows load the bundled UI from `t3code://app/index.html` (not a `127.0.0.1` document URL).
- Desktop packaging includes `apps/server/dist` (the `t3` backend) and starts it on loopback with an auth token for WebSocket/API traffic.
- Your tester can still open it on macOS by right-clicking the app and choosing **Open** on first launch.
- To keep staging files for debugging package contents, run: `bun run dist:desktop:dmg -- --keep-stage`
- To allow code-signing/notarization when configured in CI/secrets, add: `--signed`.
- Signed macOS builds also require `T3CODE_APPLE_TEAM_ID` and
`T3CODE_MACOS_PROVISIONING_PROFILE`. The passkey RP domain is derived from
`T3CODE_CLERK_PUBLISHABLE_KEY` unless `T3CODE_CLERK_PASSKEY_RP_DOMAINS` overrides it.
- Windows `--signed` uses Azure Trusted Signing and expects:
`AZURE_TRUSTED_SIGNING_ENDPOINT`, `AZURE_TRUSTED_SIGNING_ACCOUNT_NAME`,
`AZURE_TRUSTED_SIGNING_CERTIFICATE_PROFILE_NAME`, and `AZURE_TRUSTED_SIGNING_PUBLISHER_NAME`.
+1 -1
View File
@@ -9,7 +9,7 @@
"typecheck": "tsgo --noEmit"
},
"dependencies": {
"@clerk/backend": "3.6.1",
"@clerk/backend": "catalog:",
"@effect/sql-pg": "catalog:",
"@t3tools/client-runtime": "workspace:*",
"@t3tools/contracts": "workspace:*",
@@ -17,6 +17,7 @@ import { ConnectionResolver } from "./resolver.ts";
import { connectionResolverLayer } from "./resolver.ts";
import {
CloudSession,
PrimaryEnvironmentAuth,
RelayDeviceIdentity,
SshEnvironmentGateway,
} from "../platform/capabilities.ts";
@@ -101,6 +102,7 @@ const makeDependencies = Effect.fn("TestConnectionResolver.makeDependencies")((o
readonly connectEnvironment?: ManagedRelayClient["Service"]["connectEnvironment"];
readonly authorizeBearer?: RemoteEnvironmentAuthorization["Service"]["authorizeBearer"];
readonly authorizeDpop?: RemoteEnvironmentAuthorization["Service"]["authorizeDpop"];
readonly primaryBearerToken?: string;
readonly prepareSsh?: SshEnvironmentGateway["Service"]["prepare"];
}) => {
const profiles = new Map(
@@ -170,6 +172,12 @@ const makeDependencies = Effect.fn("TestConnectionResolver.makeDependencies")((o
Layer.succeed(ConnectionProfileStore, profileStore),
Layer.succeed(ConnectionCredentialStore, credentialStore),
Layer.succeed(CloudSession, CloudSession.of({ clerkToken: Effect.succeed("clerk-session") })),
Layer.succeed(
PrimaryEnvironmentAuth,
PrimaryEnvironmentAuth.of({
bearerToken: Effect.succeed(Option.fromNullishOr(options?.primaryBearerToken)),
}),
),
Layer.succeed(
RelayDeviceIdentity,
RelayDeviceIdentity.of({ deviceId: Effect.succeed(Option.some("device-1")) }),
@@ -217,6 +225,42 @@ 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 brokerLayer = yield* makeDependencies({
primaryBearerToken: "desktop-bearer",
authorizeBearer: (input) =>
Ref.update(bearerInputs, (values) => [...values, input.bearerToken]).pipe(
Effect.as({
environmentId: input.expectedEnvironmentId,
label: "Primary",
httpBaseUrl: input.httpBaseUrl,
socketUrl: "ws://127.0.0.1:3777/ws?wsTicket=desktop",
httpAuthorization: {
_tag: "Bearer" as const,
token: input.bearerToken,
},
}),
),
});
const broker = yield* ConnectionResolver.pipe(Effect.provide(brokerLayer));
const target = new PrimaryConnectionTarget({
environmentId: ENVIRONMENT_ID,
label: "Primary",
httpBaseUrl: "http://127.0.0.1:3777",
wsBaseUrl: "ws://127.0.0.1:3777",
});
expect(yield* broker.prepare(catalogEntry(target))).toMatchObject({
socketUrl: "ws://127.0.0.1:3777/ws?wsTicket=desktop",
httpAuthorization: { _tag: "Bearer", token: "desktop-bearer" },
target,
});
expect(yield* Ref.get(bearerInputs)).toEqual(["desktop-bearer"]);
}),
);
it.effect("uses the registered bearer profile without re-reading the profile store", () =>
Effect.gen(function* () {
const bearerInputs = yield* Ref.make<ReadonlyArray<string>>([]);
@@ -10,6 +10,7 @@ import { RemoteEnvironmentAuthorization } from "../authorization/service.ts";
import { ManagedRelayClient } from "../relay/managedRelay.ts";
import {
CloudSession,
PrimaryEnvironmentAuth,
RelayDeviceIdentity,
SshEnvironmentGateway,
} from "../platform/capabilities.ts";
@@ -58,17 +59,37 @@ function primarySocketUrl(target: PrimaryConnectionTarget): string {
return url.toString();
}
const primaryBroker = Effect.fn("clientRuntime.connection.broker.primary")(
(target: PrimaryConnectionTarget) =>
Effect.succeed({
environmentId: target.environmentId,
label: target.label,
const makePrimaryBroker = Effect.fn("clientRuntime.connection.broker.makePrimary")(function* () {
const auth = yield* PrimaryEnvironmentAuth;
const remote = yield* RemoteEnvironmentAuthorization;
return Effect.fn("clientRuntime.connection.broker.primary")(function* (
target: PrimaryConnectionTarget,
) {
const bearerToken = yield* auth.bearerToken;
if (Option.isNone(bearerToken)) {
return {
environmentId: target.environmentId,
label: target.label,
httpBaseUrl: target.httpBaseUrl,
socketUrl: primarySocketUrl(target),
httpAuthorization: null,
target,
} satisfies PreparedConnection;
}
const authorized = yield* remote.authorizeBearer({
expectedEnvironmentId: target.environmentId,
httpBaseUrl: target.httpBaseUrl,
socketUrl: primarySocketUrl(target),
httpAuthorization: null,
wsBaseUrl: target.wsBaseUrl,
bearerToken: bearerToken.value,
});
return {
...authorized,
target,
} satisfies PreparedConnection),
);
} satisfies PreparedConnection;
});
});
const makeBearerBroker = Effect.fn("clientRuntime.connection.broker.makeBearer")(function* () {
const credentials = yield* ConnectionCredentialStore;
@@ -228,6 +249,7 @@ const makeSshBroker = Effect.fn("clientRuntime.connection.broker.makeSsh")(funct
export const connectionResolverLayer = Layer.effect(
ConnectionResolver,
Effect.gen(function* () {
const primary = yield* makePrimaryBroker();
const bearer = yield* makeBearerBroker();
const relay = yield* makeRelayBroker();
const ssh = yield* makeSshBroker();
@@ -242,7 +264,7 @@ export const connectionResolverLayer = Layer.effect(
});
switch (target._tag) {
case "PrimaryConnectionTarget":
return yield* primaryBroker(target);
return yield* primary(target);
case "BearerConnectionTarget":
return yield* bearer({ ...entry, target });
case "RelayConnectionTarget":
@@ -43,6 +43,13 @@ export class ClientPresentation extends Context.Service<
}
>()("@t3tools/client-runtime/platform/capabilities/ClientPresentation") {}
export class PrimaryEnvironmentAuth extends Context.Service<
PrimaryEnvironmentAuth,
{
readonly bearerToken: Effect.Effect<Option.Option<string>, ConnectionAttemptError>;
}
>()("@t3tools/client-runtime/platform/capabilities/PrimaryEnvironmentAuth") {}
export class SshEnvironmentGateway extends Context.Service<
SshEnvironmentGateway,
{
+1 -23
View File
@@ -415,23 +415,6 @@ export const PickFolderOptionsSchema = Schema.Struct({
initialPath: Schema.optionalKey(Schema.NullOr(Schema.String)),
});
export const DesktopCloudAuthFetchInputSchema = Schema.Struct({
url: Schema.String,
method: Schema.optionalKey(Schema.String),
headers: Schema.Record(Schema.String, Schema.String),
body: Schema.optionalKey(Schema.String),
});
export type DesktopCloudAuthFetchInput = typeof DesktopCloudAuthFetchInputSchema.Type;
export const DesktopCloudAuthFetchResultSchema = Schema.Struct({
ok: Schema.Boolean,
status: Schema.Number,
statusText: Schema.String,
headers: Schema.Record(Schema.String, Schema.String),
body: Schema.String,
});
export type DesktopCloudAuthFetchResult = typeof DesktopCloudAuthFetchResultSchema.Type;
/**
* Renderer-facing snapshot of a desktop preview tab. Mirrors the main-process
* PreviewTabState shape but uses serialisable primitives only.
@@ -897,6 +880,7 @@ export const DesktopPreviewAutomationWaitForInputSchema = Schema.Struct({
export interface DesktopBridge {
getAppBranding: () => DesktopAppBranding | null;
getLocalEnvironmentBootstrap: () => DesktopEnvironmentBootstrap | null;
getLocalEnvironmentBearerToken: () => Promise<string>;
getClientSettings: () => Promise<ClientSettings | null>;
setClientSettings: (settings: ClientSettings) => Promise<void>;
getConnectionCatalog?: () => Promise<string | null>;
@@ -935,12 +919,6 @@ export interface DesktopBridge {
position?: { x: number; y: number },
) => Promise<T | null>;
openExternal: (url: string) => Promise<boolean>;
createCloudAuthRequest: () => Promise<string>;
getCloudAuthToken: () => Promise<string | null>;
setCloudAuthToken: (token: string) => Promise<boolean>;
clearCloudAuthToken: () => Promise<void>;
fetchCloudAuth: (input: DesktopCloudAuthFetchInput) => Promise<DesktopCloudAuthFetchResult>;
onCloudAuthCallback: (listener: (rawUrl: string) => void) => () => void;
onMenuAction: (listener: (action: string) => void) => () => void;
getUpdateState: () => Promise<DesktopUpdateState>;
setUpdateChannel: (channel: DesktopUpdateChannel) => Promise<DesktopUpdateState>;
+24 -1
View File
@@ -1,13 +1,36 @@
import { describe, expect, it } from "vite-plus/test";
import * as Schema from "effect/Schema";
import { DEFAULT_RUNTIME_MODE } from "./orchestration.ts";
import { ProviderInstanceId } from "./providerInstance.ts";
import { DEFAULT_SERVER_SETTINGS, ServerSettings, ServerSettingsPatch } from "./settings.ts";
import {
ClientSettingsPatch,
ClientSettingsSchema,
DEFAULT_CLIENT_SETTINGS,
DEFAULT_SERVER_SETTINGS,
ServerSettings,
ServerSettingsPatch,
} from "./settings.ts";
const decodeClientSettings = Schema.decodeUnknownSync(ClientSettingsSchema);
const decodeClientSettingsPatch = Schema.decodeUnknownSync(ClientSettingsPatch);
const decodeServerSettings = Schema.decodeUnknownSync(ServerSettings);
const decodeServerSettingsPatch = Schema.decodeUnknownSync(ServerSettingsPatch);
const encodeServerSettings = Schema.encodeSync(ServerSettings);
describe("ClientSettings default runtime mode", () => {
it("defaults new thread access mode to the existing runtime default", () => {
expect(DEFAULT_CLIENT_SETTINGS.defaultRuntimeMode).toBe(DEFAULT_RUNTIME_MODE);
expect(decodeClientSettings({}).defaultRuntimeMode).toBe(DEFAULT_RUNTIME_MODE);
});
it("accepts runtime mode patches", () => {
const patch = decodeClientSettingsPatch({ defaultRuntimeMode: "approval-required" });
expect(patch.defaultRuntimeMode).toBe("approval-required");
});
});
describe("ServerSettings.providerInstances (slice-2 invariant)", () => {
it("defaults to an empty record so legacy configs without the key still decode", () => {
expect(DEFAULT_SERVER_SETTINGS.providerInstances).toEqual({});
Loaded 100 of 105 files, more files were not shown because too many files have changed in this diff. Show more