Skip to content

Open-source Grok Bot alternative for named AI teammates. Local-first desktop, web, and mobile clients with per-bot tools, instructions, and memory. Independent fork of T3 Code.

Migrate desktop auth to Clerk bridge (#3092)

Julius Marminge3e01c4bc572e
diff --git a/.env.example b/.env.example
index 067aad9cc..79b2adaf0 100644
--- a/.env.example
+++ b/.env.example
@@ -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
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index eaf8fc367..21fbce026 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -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
diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml
index 2348417ab..168c000c3 100644
--- a/.github/workflows/release.yml
+++ b/.github/workflows/release.yml
@@ -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
diff --git a/apps/desktop/package.json b/apps/desktop/package.json
index bba35c8de..bb52416cc 100644
--- a/apps/desktop/package.json
+++ b/apps/desktop/package.json
@@ -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"
diff --git a/apps/desktop/scripts/electron-launcher.mjs b/apps/desktop/scripts/electron-launcher.mjs
index 52b6dd5cc..73d778fb4 100644
--- a/apps/desktop/scripts/electron-launcher.mjs
+++ b/apps/desktop/scripts/electron-launcher.mjs
@@ -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"),
diff --git a/apps/desktop/src/app/DesktopApp.ts b/apps/desktop/src/app/DesktopApp.ts
index 4da1ce63b..136a9dfd0 100644
--- a/apps/desktop/src/app/DesktopApp.ts
+++ b/apps/desktop/src/app/DesktopApp.ts
@@ -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"));
diff --git a/apps/desktop/src/app/DesktopClerk.test.ts b/apps/desktop/src/app/DesktopClerk.test.ts
new file mode 100644
index 000000000..84eab6598
--- /dev/null
+++ b/apps/desktop/src/app/DesktopClerk.test.ts
@@ -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();
+ });
+});
diff --git a/apps/desktop/src/app/DesktopClerk.ts b/apps/desktop/src/app/DesktopClerk.ts
new file mode 100644
index 000000000..5fa8e0ffb
--- /dev/null
+++ b/apps/desktop/src/app/DesktopClerk.ts
@@ -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);
diff --git a/apps/desktop/src/app/DesktopCloudAuth.test.ts b/apps/desktop/src/app/DesktopCloudAuth.test.ts
deleted file mode 100644
index 002fd86b0..000000000
--- a/apps/desktop/src/app/DesktopCloudAuth.test.ts
+++ /dev/null
@@ -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);
- },
- );
-});
diff --git a/apps/desktop/src/app/DesktopCloudAuth.ts b/apps/desktop/src/app/DesktopCloudAuth.ts
deleted file mode 100644
index 732de27b9..000000000
--- a/apps/desktop/src/app/DesktopCloudAuth.ts
+++ /dev/null
@@ -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);
diff --git a/apps/desktop/src/app/DesktopCloudAuthTokenStore.test.ts b/apps/desktop/src/app/DesktopCloudAuthTokenStore.test.ts
deleted file mode 100644
index 3257edca8..000000000
--- a/apps/desktop/src/app/DesktopCloudAuthTokenStore.test.ts
+++ /dev/null
@@ -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 },
- ),
- );
-});
diff --git a/apps/desktop/src/app/DesktopCloudAuthTokenStore.ts b/apps/desktop/src/app/DesktopCloudAuthTokenStore.ts
deleted file mode 100644
index 652072c1f..000000000
--- a/apps/desktop/src/app/DesktopCloudAuthTokenStore.ts
+++ /dev/null
@@ -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"),
- ),
- });
- }),
-);
diff --git a/apps/desktop/src/backend/DesktopLocalEnvironmentAuth.test.ts b/apps/desktop/src/backend/DesktopLocalEnvironmentAuth.test.ts
new file mode 100644
index 000000000..914b6ada0
--- /dev/null
+++ b/apps/desktop/src/backend/DesktopLocalEnvironmentAuth.test.ts
@@ -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);
+ }),
+ );
+});
diff --git a/apps/desktop/src/backend/DesktopLocalEnvironmentAuth.ts b/apps/desktop/src/backend/DesktopLocalEnvironmentAuth.ts
new file mode 100644
index 000000000..e70057ee1
--- /dev/null
+++ b/apps/desktop/src/backend/DesktopLocalEnvironmentAuth.ts
@@ -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 });
+ }),
+);
diff --git a/apps/desktop/src/electron/ElectronProtocol.test.ts b/apps/desktop/src/electron/ElectronProtocol.test.ts
index 2306c101c..619b7e871 100644
--- a/apps/desktop/src/electron/ElectronProtocol.test.ts
+++ b/apps/desktop/src/electron/ElectronProtocol.test.ts
@@ -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"));
+
+ 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:",
+ );
+ }),
+ );
- 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,
- },
- },
- ],
- ],
- ]);
- }),
- ),
- ),
- ),
+ 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:"]);
+ });
});
diff --git a/apps/desktop/src/electron/ElectronProtocol.ts b/apps/desktop/src/electron/ElectronProtocol.ts
index a56e442dd..3a3e9f180 100644
--- a/apps/desktop/src/electron/ElectronProtocol.ts
+++ b/apps/desktop/src/electron/ElectronProtocol.ts
@@ -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("/"));
-}
-
-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"));
-
-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"),
+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",
];
- 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);
- }
- }
- 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;
- }
+ // 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 nestedIndex = environment.path.join(resolvedPath, "index.html");
- const nestedIndexExists = yield* fileSystem
- .exists(nestedIndex)
- .pipe(Effect.orElseSucceed(() => false));
- if (nestedIndexExists) {
- return nestedIndex;
- }
+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,
+ });
+}
- return environment.path.join(staticRoot, "index.html");
- },
-);
+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 });
+ }
-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);
diff --git a/apps/desktop/src/ipc/DesktopIpcHandlers.ts b/apps/desktop/src/ipc/DesktopIpcHandlers.ts
index 1a9d16380..180e44e52 100644
--- a/apps/desktop/src/ipc/DesktopIpcHandlers.ts
+++ b/apps/desktop/src/ipc/DesktopIpcHandlers.ts
@@ -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);
diff --git a/apps/desktop/src/ipc/channels.ts b/apps/desktop/src/ipc/channels.ts
index e270ef404..cc2a92ca8 100644
--- a/apps/desktop/src/ipc/channels.ts
+++ b/apps/desktop/src/ipc/channels.ts
@@ -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";
diff --git a/apps/desktop/src/ipc/methods/cloudAuth.test.ts b/apps/desktop/src/ipc/methods/cloudAuth.test.ts
deleted file mode 100644
index c5f1e2b2c..000000000
--- a/apps/desktop/src/ipc/methods/cloudAuth.test.ts
+++ /dev/null
@@ -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,
- );
- });
-});
diff --git a/apps/desktop/src/ipc/methods/cloudAuth.ts b/apps/desktop/src/ipc/methods/cloudAuth.ts
deleted file mode 100644
index 9f6a964ac..000000000
--- a/apps/desktop/src/ipc/methods/cloudAuth.ts
+++ /dev/null
@@ -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));
- }),
-});
diff --git a/apps/desktop/src/ipc/methods/window.ts b/apps/desktop/src/ipc/methods/window.ts
index 1cb4d7265..708bb299c 100644
--- a/apps/desktop/src/ipc/methods/window.ts
+++ b/apps/desktop/src/ipc/methods/window.ts
@@ -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),
diff --git a/apps/desktop/src/main.ts b/apps/desktop/src/main.ts
index 33eac8ea6..326fc1af0 100644
--- a/apps/desktop/src/main.ts
+++ b/apps/desktop/src/main.ts
@@ -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 desktopClerkLayer = DesktopClerk.layer.pipe(
+ Layer.provideMerge(desktopEnvironmentLayer),
+ Layer.provideMerge(NodeServices.layer),
+ Layer.provideMerge(ElectronApp.layer),
+);
-const desktopRuntimeLayer = ElectronProtocol.layerSchemePrivileges.pipe(
- Layer.flatMap(() =>
+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),
diff --git a/apps/desktop/src/preload.ts b/apps/desktop/src/preload.ts
index 35c34d39c..6f126f413 100644
--- a/apps/desktop/src/preload.ts
+++ b/apps/desktop/src/preload.ts
@@ -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;
diff --git a/apps/desktop/src/window/DesktopWindow.test.ts b/apps/desktop/src/window/DesktopWindow.test.ts
index e22db07c0..679fa8744 100644
--- a/apps/desktop/src/window/DesktopWindow.test.ts
+++ b/apps/desktop/src/window/DesktopWindow.test.ts
@@ -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));
}),
diff --git a/apps/desktop/src/window/DesktopWindow.ts b/apps/desktop/src/window/DesktopWindow.ts
index 642abd535..e911d4ff7 100644
--- a/apps/desktop/src/window/DesktopWindow.ts
+++ b/apps/desktop/src/window/DesktopWindow.ts
@@ -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;
diff --git a/apps/desktop/vite.config.ts b/apps/desktop/vite.config.ts
index dceefc14e..96e089b91 100644
--- a/apps/desktop/vite.config.ts
+++ b/apps/desktop/vite.config.ts
@@ -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",
diff --git a/apps/mobile/package.json b/apps/mobile/package.json
index f47fb9d24..ddf5b2a02 100644
--- a/apps/mobile/package.json
+++ b/apps/mobile/package.json
@@ -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",
diff --git a/apps/mobile/src/connection/platform.ts b/apps/mobile/src/connection/platform.ts
index 580341941..8b959b40b 100644
--- a/apps/mobile/src/connection/platform.ts
+++ b/apps/mobile/src/connection/platform.ts
@@ -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({
diff --git a/apps/server/src/relay/AgentAwarenessRelay.test.ts b/apps/server/src/relay/AgentAwarenessRelay.test.ts
index 6bdf62b10..b81eb8088 100644
--- a/apps/server/src/relay/AgentAwarenessRelay.test.ts
+++ b/apps/server/src/relay/AgentAwarenessRelay.test.ts
@@ -625,7 +625,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;
diff --git a/apps/web/package.json b/apps/web/package.json
index 13973b188..632e2d143 100644
--- a/apps/web/package.json
+++ b/apps/web/package.json
@@ -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",
diff --git a/apps/web/src/authBootstrap.test.ts b/apps/web/src/authBootstrap.test.ts
index 6815cd70f..53c17c064 100644
--- a/apps/web/src/authBootstrap.test.ts
+++ b/apps/web/src/authBootstrap.test.ts
@@ -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 () => {
diff --git a/apps/web/src/cloud/desktopAuth.test.ts b/apps/web/src/cloud/desktopAuth.test.ts
deleted file mode 100644
index 520130518..000000000
--- a/apps/web/src/cloud/desktopAuth.test.ts
+++ /dev/null
@@ -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",
- },
- ]);
- });
-});
diff --git a/apps/web/src/cloud/desktopAuth.ts b/apps/web/src/cloud/desktopAuth.ts
deleted file mode 100644
index 0e2a328c3..000000000
--- a/apps/web/src/cloud/desktopAuth.ts
+++ /dev/null
@@ -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;
- });
-}
diff --git a/apps/web/src/cloud/desktopClerk.tsx b/apps/web/src/cloud/desktopClerk.tsx
deleted file mode 100644
index 68179f5cf..000000000
--- a/apps/web/src/cloud/desktopClerk.tsx
+++ /dev/null
@@ -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>
- );
-}
diff --git a/apps/web/src/cloud/desktopClerkExternalAccounts.test.ts b/apps/web/src/cloud/desktopClerkExternalAccounts.test.ts
deleted file mode 100644
index 031094b7a..000000000
--- a/apps/web/src/cloud/desktopClerkExternalAccounts.test.ts
+++ /dev/null
@@ -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();
- });
-});
diff --git a/apps/web/src/cloud/desktopClerkExternalAccounts.ts b/apps/web/src/cloud/desktopClerkExternalAccounts.ts
deleted file mode 100644
index 01ff8603e..000000000
--- a/apps/web/src/cloud/desktopClerkExternalAccounts.ts
+++ /dev/null
@@ -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 };
diff --git a/apps/web/src/cloud/linkEnvironment.test.ts b/apps/web/src/cloud/linkEnvironment.test.ts
index b4a347fca..fe639d9c5 100644
--- a/apps/web/src/cloud/linkEnvironment.test.ts
+++ b/apps/web/src/cloud/linkEnvironment.test.ts
@@ -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
diff --git a/apps/web/src/cloud/linkEnvironment.ts b/apps/web/src/cloud/linkEnvironment.ts
index 360ef6d36..a8f410acd 100644
--- a/apps/web/src/cloud/linkEnvironment.ts
+++ b/apps/web/src/cloud/linkEnvironment.ts
@@ -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));
}
diff --git a/apps/web/src/components/clerk/DesktopClerkCard.tsx b/apps/web/src/components/clerk/DesktopClerkCard.tsx
deleted file mode 100644
index e2e0c4f9a..000000000
--- a/apps/web/src/components/clerk/DesktopClerkCard.tsx
+++ /dev/null
@@ -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>
- );
-}
diff --git a/apps/web/src/components/clerk/DesktopClerkSignIn.tsx b/apps/web/src/components/clerk/DesktopClerkSignIn.tsx
deleted file mode 100644
index dc8b432e1..000000000
--- a/apps/web/src/components/clerk/DesktopClerkSignIn.tsx
+++ /dev/null
@@ -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} />;
-}
diff --git a/apps/web/src/components/clerk/DesktopClerkWaitlist.tsx b/apps/web/src/components/clerk/DesktopClerkWaitlist.tsx
deleted file mode 100644
index ec9198498..000000000
--- a/apps/web/src/components/clerk/DesktopClerkWaitlist.tsx
+++ /dev/null
@@ -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.";
-}
diff --git a/apps/web/src/components/clerk/useDesktopClerkSignIn.ts b/apps/web/src/components/clerk/useDesktopClerkSignIn.ts
deleted file mode 100644
index 7b58c4f1e..000000000
--- a/apps/web/src/components/clerk/useDesktopClerkSignIn.ts
+++ /dev/null
@@ -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,
- };
-}
diff --git a/apps/web/src/components/clerk/useT3ConnectAuthPrompt.tsx b/apps/web/src/components/clerk/useT3ConnectAuthPrompt.tsx
index b38d630df..05fa8250b 100644
--- a/apps/web/src/components/clerk/useT3ConnectAuthPrompt.tsx
+++ b/apps/web/src/components/clerk/useT3ConnectAuthPrompt.tsx
@@ -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 };
}
diff --git a/apps/web/src/connection/platform.ts b/apps/web/src/connection/platform.ts
index 5fe503ec3..c8426d551 100644
--- a/apps/web/src/connection/platform.ts
+++ b/apps/web/src/connection/platform.ts
@@ -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,
diff --git a/apps/web/src/environments/primary/desktopAuth.test.ts b/apps/web/src/environments/primary/desktopAuth.test.ts
new file mode 100644
index 000000000..d87a6a0c7
--- /dev/null
+++ b/apps/web/src/environments/primary/desktopAuth.test.ts
@@ -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();
+ });
+});
diff --git a/apps/web/src/environments/primary/desktopAuth.ts b/apps/web/src/environments/primary/desktopAuth.ts
new file mode 100644
index 000000000..325773d91
--- /dev/null
+++ b/apps/web/src/environments/primary/desktopAuth.ts
@@ -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;
+}
diff --git a/apps/web/src/environments/primary/httpLayer.test.ts b/apps/web/src/environments/primary/httpLayer.test.ts
new file mode 100644
index 000000000..5bc1ef01d
--- /dev/null
+++ b/apps/web/src/environments/primary/httpLayer.test.ts
@@ -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()));
+ });
+});
diff --git a/apps/web/src/environments/primary/httpLayer.ts b/apps/web/src/environments/primary/httpLayer.ts
new file mode 100644
index 000000000..bedb4954d
--- /dev/null
+++ b/apps/web/src/environments/primary/httpLayer.ts
@@ -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();
diff --git a/apps/web/src/environments/primary/index.ts b/apps/web/src/environments/primary/index.ts
index 3728cb024..305ced9c9 100644
--- a/apps/web/src/environments/primary/index.ts
+++ b/apps/web/src/environments/primary/index.ts
@@ -33,6 +33,8 @@ export {
export { refreshPrimarySessionState, usePrimarySessionState } from "./sessionState";
+export { PrimaryEnvironmentHttpClient } from "./httpClient";
+
export {
readPrimaryEnvironmentTarget,
resolvePrimaryEnvironmentHttpUrl,
diff --git a/apps/web/src/environments/primary/requestInit.ts b/apps/web/src/environments/primary/requestInit.ts
deleted file mode 100644
index cf7023738..000000000
--- a/apps/web/src/environments/primary/requestInit.ts
+++ /dev/null
@@ -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));
diff --git a/apps/web/src/lib/runtime.ts b/apps/web/src/lib/runtime.ts
index 728163b24..cf4ffb084 100644
--- a/apps/web/src/lib/runtime.ts
+++ b/apps/web/src/lib/runtime.ts
@@ -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>(
diff --git a/apps/web/src/main.tsx b/apps/web/src/main.tsx
index 7d56d572f..838a990d6 100644
--- a/apps/web/src/main.tsx
+++ b/apps/web/src/main.tsx
@@ -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>
diff --git a/apps/web/src/observability/clientTracing.ts b/apps/web/src/observability/clientTracing.ts
index 61c6006a8..11045392b 100644
--- a/apps/web/src/observability/clientTracing.ts
+++ b/apps/web/src/observability/clientTracing.ts
@@ -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),
);
diff --git a/apps/web/vite.config.ts b/apps/web/vite.config.ts
index 43c79eba3..8f984c850 100644
--- a/apps/web/vite.config.ts
+++ b/apps/web/vite.config.ts
@@ -126,6 +126,7 @@ export default defineConfig(() => {
},
resolve: {
tsconfigPaths: true,
+ dedupe: ["react", "react-dom"],
},
server: {
host,
diff --git a/docs/cloud/t3-connect-clerk.md b/docs/cloud/t3-connect-clerk.md
index d768c3874..3fd1943f7 100644
--- a/docs/cloud/t3-connect-clerk.md
+++ b/docs/cloud/t3-connect-clerk.md
@@ -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.
diff --git a/docs/operations/ci.md b/docs/operations/ci.md
index 244446ba9..d030b446b 100644
--- a/docs/operations/ci.md
+++ b/docs/operations/ci.md
@@ -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.
diff --git a/docs/operations/release.md b/docs/operations/release.md
index 8f149446b..76f787dc0 100644
--- a/docs/operations/release.md
+++ b/docs/operations/release.md
@@ -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:
diff --git a/docs/reference/scripts.md b/docs/reference/scripts.md
index b3fcd4b30..d4d2b9686 100644
--- a/docs/reference/scripts.md
+++ b/docs/reference/scripts.md
@@ -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`.
diff --git a/infra/relay/package.json b/infra/relay/package.json
index 213c1fe5c..eebd9f472 100644
--- a/infra/relay/package.json
+++ b/infra/relay/package.json
@@ -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:*",
diff --git a/packages/client-runtime/src/connection/resolver.test.ts b/packages/client-runtime/src/connection/resolver.test.ts
index 31f75bf4b..5c1ed83ec 100644
--- a/packages/client-runtime/src/connection/resolver.test.ts
+++ b/packages/client-runtime/src/connection/resolver.test.ts
@@ -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>>([]);
diff --git a/packages/client-runtime/src/connection/resolver.ts b/packages/client-runtime/src/connection/resolver.ts
index 6eb0027e3..ae18535e4 100644
--- a/packages/client-runtime/src/connection/resolver.ts
+++ b/packages/client-runtime/src/connection/resolver.ts
@@ -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":
diff --git a/packages/client-runtime/src/platform/capabilities.ts b/packages/client-runtime/src/platform/capabilities.ts
index ddc93046b..a20b7d404 100644
--- a/packages/client-runtime/src/platform/capabilities.ts
+++ b/packages/client-runtime/src/platform/capabilities.ts
@@ -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,
{
diff --git a/packages/contracts/src/ipc.ts b/packages/contracts/src/ipc.ts
index 03c06d2f8..f9377d6bf 100644
--- a/packages/contracts/src/ipc.ts
+++ b/packages/contracts/src/ipc.ts
@@ -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>;
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 9b9312da6..1bd9272b6 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -35,6 +35,13 @@ catalogs:
version: 0.1.24
overrides:
+ '@clerk/backend': 3.8.2-snapshot.v20260619001138
+ '@clerk/clerk-js': 6.18.2-snapshot.v20260619001138
+ '@clerk/electron': 0.0.1-snapshot.v20260619001138
+ '@clerk/electron-passkeys': 0.0.1-snapshot.v20260619001138
+ '@clerk/expo': 3.4.8-snapshot.v20260619001138
+ '@clerk/react': 6.10.4-snapshot.v20260619001138
+ '@clerk/shared': 4.19.2-snapshot.v20260619001138
'@clerk/clerk-js>@base-org/account': '-'
'@clerk/clerk-js>@coinbase/wallet-sdk': '-'
'@clerk/clerk-js>@solana/wallet-adapter-base': '-'
@@ -105,6 +112,12 @@ importers:
apps/desktop:
dependencies:
+ '@clerk/electron':
+ specifier: 0.0.1-snapshot.v20260619001138
+ '@clerk/electron-passkeys':
+ specifier: 0.0.1-snapshot.v20260619001138
+ version: 0.0.1-snapshot.v20260619001138
'@effect/platform-node':
specifier: 4.0.0-beta.78
version: 4.0.0-beta.78([email protected])([email protected](patch_hash=c502bc684210b707dfceb87d8fe6ad6843395af6e19cfc02cd65854898bde2c5))([email protected])([email protected])
@@ -129,6 +142,9 @@ importers:
electron:
specifier: 41.5.0
version: 41.5.0
+ electron-store:
+ specifier: ^8.2.0
+ version: 8.2.0
electron-updater:
specifier: ^6.6.2
version: 6.8.3
@@ -178,10 +194,10 @@ importers:
dependencies:
'@callstack/liquid-glass':
specifier: ^0.7.1
'@clerk/expo':
- specifier: ^3.4.1
+ specifier: 3.4.8-snapshot.v20260619001138
'@effect/atom-react':
specifier: 4.0.0-beta.78
version: 4.0.0-beta.78([email protected](patch_hash=c502bc684210b707dfceb87d8fe6ad6843395af6e19cfc02cd65854898bde2c5))([email protected])([email protected])
@@ -190,10 +206,10 @@ importers:
version: 0.4.2
'@expo/ui':
specifier: ~56.0.8
- version: 56.0.15(ab3f255d102c60ba0fd2bbe4e47ba584)
+ version: 56.0.15(961c4aa6f32829b318e3c87ef20ad401)
'@legendapp/list':
specifier: 3.0.0-beta.44
'@noble/curves':
specifier: 'catalog:'
version: 1.9.1
@@ -205,7 +221,7 @@ importers:
version: 1.3.0-beta.5(patch_hash=7cb6da88544119adda056b2f46f43956f99326227732da0b345081e285a6c53a)(@shikijs/[email protected])([email protected]([email protected]))([email protected])
'@react-native-menu/menu':
specifier: ^2.0.0
'@shikijs/core':
specifier: 4.2.0
version: 4.2.0
@@ -226,7 +242,7 @@ importers:
version: link:../../packages/contracts
'@t3tools/mobile-markdown-text':
specifier: file:./modules/t3-markdown-text
- version: file:apps/mobile/modules/t3-markdown-text(e909ee9a8f7fbe234da80c739fca4984)
+ version: file:apps/mobile/modules/t3-markdown-text(f0ff241d48c23db461fff5d47e450578)
'@t3tools/mobile-review-diff-native':
specifier: file:./modules/t3-review-diff
version: file:apps/mobile/modules/t3-review-diff
@@ -247,40 +263,40 @@ importers:
version: 4.0.0-beta.78(patch_hash=c502bc684210b707dfceb87d8fe6ad6843395af6e19cfc02cd65854898bde2c5)
expo:
specifier: ^56.0.0
+ version: 56.0.8(63f7aade424ad9e7b1154b679fa2a14d)
expo-asset:
specifier: ~56.0.15
expo-auth-session:
specifier: ~56.0.12
expo-build-properties:
specifier: ~56.0.15
version: 56.0.16([email protected])
expo-camera:
specifier: ~56.0.7
expo-clipboard:
specifier: ~56.0.3
expo-constants:
specifier: ~56.0.16
expo-crypto:
specifier: ~56.0.4
version: 56.0.4([email protected])
expo-dev-client:
specifier: ~56.0.16
expo-file-system:
specifier: ~56.0.7
expo-font:
specifier: ~56.0.5
expo-glass-effect:
specifier: ~56.0.4
expo-haptics:
specifier: ~56.0.3
version: 56.0.3([email protected])
@@ -289,19 +305,19 @@ importers:
version: 56.0.15([email protected])
expo-linking:
specifier: ~56.0.12
expo-network:
specifier: ~56.0.5
expo-notifications:
specifier: ~56.0.14
expo-paste-input:
specifier: ^0.1.15
expo-router:
specifier: ~56.2.7
- version: 56.2.8(c021de11d02907bd585610408f5252e8)
+ version: 56.2.8(5bfdf39b8f760e4dc2d5c3acffc97310)
expo-secure-store:
specifier: ~56.0.4
version: 56.0.4([email protected])
@@ -310,16 +326,16 @@ importers:
expo-symbols:
specifier: ~56.0.5
expo-updates:
specifier: ~56.0.17
expo-web-browser:
specifier: ~56.0.5
expo-widgets:
specifier: ~56.0.15
- version: 56.0.16(ab3f255d102c60ba0fd2bbe4e47ba584)
+ version: 56.0.16(961c4aa6f32829b318e3c87ef20ad401)
punycode:
specifier: ^2.3.1
version: 2.3.1
@@ -331,43 +347,43 @@ importers:
version: 19.2.3([email protected])
react-native:
specifier: 0.85.3
react-native-gesture-handler:
specifier: ~2.31.1
react-native-image-viewing:
specifier: ^0.2.2
react-native-keyboard-controller:
specifier: 1.21.6
react-native-nitro-markdown:
specifier: ^0.5.0
react-native-nitro-modules:
specifier: ^0.35.4
- version: 0.35.9(patch_hash=825622aae63a8fb5b904f3c77908a0e216261d727ea171709f2c0b6088422675)([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected])([email protected])([email protected]))([email protected])
+ version: 0.35.9(patch_hash=825622aae63a8fb5b904f3c77908a0e216261d727ea171709f2c0b6088422675)([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected])([email protected])([email protected]))(@types/[email protected])([email protected])([email protected])([email protected]))([email protected])
react-native-reanimated:
specifier: 4.3.1
react-native-safe-area-context:
specifier: ~5.7.0
react-native-screens:
specifier: 4.25.2
react-native-shiki-engine:
specifier: ^0.3.12
react-native-svg:
specifier: 15.15.4
react-native-webview:
specifier: ^13.16.1
react-native-worklets:
specifier: 0.8.3
shiki:
specifier: 4.2.0
version: 4.2.0
@@ -376,7 +392,7 @@ importers:
version: 3.6.0
uniwind:
specifier: ^1.6.2
devDependencies:
'@effect/vitest':
specifier: 4.0.0-beta.78
@@ -466,12 +482,12 @@ importers:
'@base-ui/react':
specifier: ^1.4.1
- '@clerk/clerk-js':
- specifier: ^6.16.0
+ '@clerk/electron':
+ specifier: 0.0.1-snapshot.v20260619001138
'@clerk/react':
- specifier: ^6.9.0
+ specifier: 6.10.4-snapshot.v20260619001138
+ version: 6.10.4-snapshot.v20260619001138([email protected]([email protected]))([email protected])
'@dnd-kit/core':
specifier: ^6.3.1
@@ -621,8 +637,8 @@ importers:
infra/relay:
dependencies:
'@clerk/backend':
- specifier: 3.6.1
+ specifier: 3.8.2-snapshot.v20260619001138
+ version: 3.8.2-snapshot.v20260619001138([email protected]([email protected]))([email protected])
'@effect/sql-pg':
specifier: 4.0.0-beta.78
version: 4.0.0-beta.78([email protected](patch_hash=c502bc684210b707dfceb87d8fe6ad6843395af6e19cfc02cd65854898bde2c5))
@@ -1516,19 +1532,60 @@ packages:
resolution: {integrity: sha512-wKh+wTjmrUoUdkZg8KpJO5X+p9PWV+KE9mePseq9UYWkukgTKsGS47RRL2HstwVcvDQH+PenrPJWII8+MfiiyA==}
engines: {node: '>= 20.12.0'}
- '@clerk/[email protected]':
- resolution: {integrity: sha512-LkfekzF/0UMXacX+17xy3ExRraO0mm+thXejC8Q32gWHd1wLdxK3YXDsLDF00E1r1InWBKIt2ZOxs6hTwZPJjA==}
+ '@clerk/[email protected]':
+ resolution: {integrity: sha512-nT6M7rKTuvoDnSZwO3Th2NMjcWZy/0ZfXYyqd/o/lFpUFcQO0J4fM2e2wF9kNCl99EPvDQQUAR8APNNy/j40rg==}
engines: {node: '>=20.9.0'}
- '@clerk/[email protected]':
- resolution: {integrity: sha512-8xv/XDsxhOZd1n4DNIRJ2EehIRUg6UiqKAnfd0L88R2t1g6sVnLi1FInJ5i8Qyx5oY/creXx6X1AZ1V5PobRkA==}
+ '@clerk/[email protected]':
+ resolution: {integrity: sha512-BpRSi2QXdfR5nnzC7/YCCqK40m1M4A/rN5unau7QKHj6V7xChl2fOvxYjekpH+DEyw6NAe/2jdqQv35iv3T5oA==}
engines: {node: '>=20.9.0'}
- '@clerk/[email protected]':
- resolution: {integrity: sha512-gpAXsuUnsUdUD0/2XjyxaC9quF5rT+2umkmV74nBLVAFurGMMMMHvnHqrQEtZ7tH5GHNXYw5+pgmnzd1HiMQbQ==}
+ '@clerk/[email protected]':
+ resolution: {integrity: sha512-dbQ/0ZtfDQgYKCSzu3AMxTnGSrdZxulurZMT4Jpvin48Etc27PdcT7VvwOGIa7R+Ab8yMeaoLJbfwHTZv35F+Q==}
+ cpu: [arm64]
+ os: [darwin]
+
+ '@clerk/[email protected]':
+ resolution: {integrity: sha512-g9tbni7yKIJ/Xpollm25Gf7YLyFP24VyqRHcGDnEsHC1tIffG41spjLr10NgsBoRvFLMlaQJMSrfpjVOpBhAjw==}
+ cpu: [x64]
+ os: [darwin]
+
+ '@clerk/electron-passkeys-win32-arm64-msvc@0.0.1-snapshot.v20260619001138':
+ resolution: {integrity: sha512-mFDQ1vQ9dLIUrnjNGhIGxqyK0iiym919gYDPO3orYEcICdEiE8xZyEbCtKSVaeX6RWGJAcqFzCxbLVG6V+1k4Q==}
+ cpu: [arm64]
+ os: [win32]
+
+ '@clerk/[email protected]':
+ resolution: {integrity: sha512-IwkLw+d73bd7YJPRR8LAkqP42VIIpbJXCCbs5eVKbmam9M0vSUyeLWEtSiWUEypmLK13xv+7316K4GIA2tmDGQ==}
+ cpu: [x64]
+ os: [win32]
+
+ '@clerk/[email protected]':
+ resolution: {integrity: sha512-diU5Q9Nx+30mesrLFOmr0OCnmxE0ogUHXktZBTQx2nQvZb/n2UGOpGNLbY1p9edKMcSc5LfJEsQ8NogfLBBvPg==}
+ engines: {node: '>=20.9.0'}
+
+ '@clerk/[email protected]':
+ resolution: {integrity: sha512-wrBEdMMRqhMF4a7aQpZaBXKJfONIpaYLcgBl0m1b2r+Xg4yuZ47YUoDxhI2Ksvbx2KQPd4i9HP0enL6gEcoqfA==}
engines: {node: '>=20.9.0'}
peerDependencies:
- '@clerk/expo-passkeys': '>=0.0.6'
+ '@clerk/electron-passkeys': 0.0.1-snapshot.v20260619001138
+ electron: '>=28'
+ electron-store: ^8.2.0
+ react: ^18.0.0 || ~19.0.3 || ~19.1.4 || ~19.2.3 || ~19.3.0-0
+ react-dom: ^18.0.0 || ~19.0.3 || ~19.1.4 || ~19.2.3 || ~19.3.0-0
+ peerDependenciesMeta:
+ '@clerk/electron-passkeys':
+ optional: true
+ electron-store:
+ optional: true
+ react-dom:
+ optional: true
+
+ '@clerk/[email protected]':
+ resolution: {integrity: sha512-E6q4p5ded45aO3y/+f7APfy5pFj2Y/BEpe/1gzdr6UGxj9kJxkiZQV29hcpjYEFMEJK60f7XbOHZTQEZRB5OwQ==}
+ engines: {node: '>=20.9.0'}
+ peerDependencies:
+ '@clerk/expo-passkeys': 1.1.8-snapshot.v20260619001138
expo: '>=53 <57'
expo-apple-authentication: '>=7.0.0'
expo-auth-session: '>=5'
@@ -1560,15 +1617,15 @@ packages:
react-dom:
optional: true
- '@clerk/[email protected]':
- resolution: {integrity: sha512-M0QGyGS732tYBXeG+28UgElXM2TfoSZ+4mWGisC8yxJX8NjH4hEPJTAQuZmYRLNaCyGQCuzjYVQiQRC+GbDtmA==}
+ '@clerk/[email protected]':
+ resolution: {integrity: sha512-Z7Otjly14SoxadMmk8d9ZdbaXU0me9B1zGdCtnNIcQ7X2GCbeyKm/lOM27IzWYXZKO6o+sXlqsq9A9tcxet5nA==}
engines: {node: '>=20.9.0'}
peerDependencies:
react: ^18.0.0 || ~19.0.3 || ~19.1.4 || ~19.2.3 || ~19.3.0-0
react-dom: ^18.0.0 || ~19.0.3 || ~19.1.4 || ~19.2.3 || ~19.3.0-0
- '@clerk/[email protected]':
- resolution: {integrity: sha512-YeQ+6zDmqyor1mPHjZx18j+LssL6Pobvid8hb7HQMioSo8sGDBEVi/Z12bs+gUhe9KbdP+ygHsKOqqeGAPuPZA==}
+ '@clerk/[email protected]':
+ resolution: {integrity: sha512-NAIz0L6+CaRrYn0DoXclUP1R0g6C2ljOzHogQ3rx9/SWUVpfaYX2lxPhURU89xvPoOGBZQb2xwk6xFh/7cjJfQ==}
engines: {node: '>=20.9.0'}
peerDependencies:
react: ^18.0.0 || ~19.0.3 || ~19.1.4 || ~19.2.3 || ~19.3.0-0
@@ -4962,6 +5019,14 @@ packages:
ajv:
optional: true
+ resolution: {integrity: sha512-Wx0Kx52hxE7C18hkMEggYlEifqWZtYaRgouJor+WMdPnQyEK13vgEWyVNup7SoeeoLMsr4kf5h6dOW11I15MUA==}
+ peerDependencies:
+ ajv: ^8.0.0
+ peerDependenciesMeta:
+ ajv:
+ optional: true
+
resolution: {integrity: sha512-8iUql50EUR+uUcdRQ3HDqa6EVyo3docL8g5WJ3FNcWmu62IbkGUue/pEyLBW8VGKKucTPgqeks4fIU1DA4yowQ==}
peerDependencies:
@@ -5127,6 +5192,10 @@ packages:
resolution: {integrity: sha512-+q/t7Ekv1EDY2l6Gda6LLiX14rU9TV20Wa3ofeQmwPFZbOMo9DXrLbOjFaaclkXKWidIaopwAObQDqwWtGUjqg==}
engines: {node: '>= 4.0.0'}
+ resolution: {integrity: sha512-Xcz9l0z7y9yQ9rdDaxlmaI4uJHf/T8g9hOEzJcsEqX2SjCj4J20uK7+ldkDHMbpJDK76wF7xEIgxc/vSlsfw5w==}
+ engines: {node: '>=10.12.0'}
+
resolution: {integrity: sha512-ooviqdwwgfIfNmDwo94wlshcdzfO64XV0Cg6oDsDYBJfITDz1EngD2z7DkbvCWn+XIMsIqW27sEVF6qcpJrRcg==}
engines: {node: ^12.20.0 || ^14.13.1 || >=16.0.0}
@@ -5535,6 +5604,10 @@ packages:
resolution: {integrity: sha512-/Srv4dswyQNBfohGpz9o6Yb3Gz3SrUDqBH5rTuhGR7ahtlbYKnVxw2bCFMRljaA7EXHaXZ8wsHdodFvbkhKmqg==}
+ resolution: {integrity: sha512-8fLl9F04EJqjSqH+QjITQfJF8BrOVaYr1jewVgSRAEWePfxT0sku4w2hrGQ60BC/TNLGQ2pgxNlTbWQmMPFvXg==}
+ engines: {node: '>=12'}
+
resolution: {integrity: sha512-ZqRXc+tZukToSNmh5C2iWMSoV3X1YUcPbqEM4DkEG5tNQXrQUZCNVGGv3IuicnkMtPfGf3Xtp8WCXs295iQ1pQ==}
engines: {node: '>= 0.10.0'}
@@ -5643,6 +5716,10 @@ packages:
resolution: {integrity: sha512-1+BhOB8ahCn4O0cep0Sh2l9KCOfOdY+BXJnKMHFFzDEouSr/el18QwXEMRlOj9UY5nCeA8UN3a/82rUWRBeyBw==}
engines: {node: ^12.20.0 || ^14.13.1 || >=16.0.0}
+ resolution: {integrity: sha512-8pYCQiL9Xdcg0UPSD3d+0KMlOjp+KGU5EPwYddgzQ7DATsg4fuUDjQtsYLmWjnk2obnNHgV3vE2Y4jejSOJVBQ==}
+ engines: {node: '>=10'}
+
resolution: {integrity: sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==}
peerDependencies:
@@ -5782,6 +5859,10 @@ packages:
resolution: {integrity: sha512-6kZKyUajlDuqlHKVX1w7gyslj9MPIXzIFiz/rGu35uC1wMi+kMhQwGhl4lt9unC9Vb9INnY9Z3/ZA3+FhASLaw==}
+ resolution: {integrity: sha512-tE7ztYzXHIeyvc7N+hR3oi7FIbf/NIjVP9hmAt3yMXzrQ072/fpjGLx2GxNxGxUl5V73MEqYzioOMoVhGMJ5cA==}
+ engines: {node: '>=10'}
+
resolution: {integrity: sha512-zIHwmZPRshsCdpMDyVsqGmgyP0yT8GAgXUnkdAoJisxvf33k7yO6OuoKmcTGuXPWSsm8Oh88nZicRLA9Y0rUeA==}
engines: {node: '>=12'}
@@ -5940,6 +6021,9 @@ packages:
resolution: {integrity: sha512-q+jrSTIh/Cv4eGZa7oVR+grEJo/FoLMYBAnSL5GCtqwUpr1T+VgKB/dn1pnzxIxqD8S/jP1yilT9VrwCqINR4w==}
+ resolution: {integrity: sha512-ukLL5Bevdil6oieAOXz3CMy+OgaItMiVBg701MNlG6W5RaC0AHN7rvlqTCmeb6O7jP0Qa1KKYTE0xV0xbhF4Hw==}
+
resolution: {integrity: sha512-G/dYE3+AYhyHwzTwg8UbnXf7zqMERYh7l2jJ3QujhFsH8agSYwtnGAR2aZ7f0AakIKJXd5En/Hre4igIUrdlYw==}
@@ -6488,6 +6572,10 @@ packages:
resolution: {integrity: sha512-a85L9ZoXtNAey3Y6Z+eBWW658kO/MwR7zIafkIUPUMf3isZG0NCs2pjW2wtjxAKuJPxMAsHUIP4ZPGv0o5gyTA==}
+ resolution: {integrity: sha512-1yD6RmLI1XBfxugvORwlck6f75tYL+iR0jqwsOrOxMZyGYqUuDhJ0l4AXdO1iX/FTs9cBAMEk1gWSEx1kSbylg==}
+ engines: {node: '>=6'}
+
resolution: {integrity: sha512-9UbaD6XdAL97+k/n+N7JwX46K/M6Zc6KcFYskrYL8wbBV/Uyk0CTAMY0VT+qiK5PM7AIc9aTWYtq65U7T+aCNQ==}
engines: {node: '>=8'}
@@ -6917,6 +7005,10 @@ packages:
resolution: {integrity: sha512-41Cifkg6e8TylSpdtTpeLVMqvSBEVzTttHvERD741+pnZ8ANv0004MRL43QKPDlK9cGvNp6NZWZUBlbGXYxxng==}
engines: {node: '>=0.12.0'}
+ resolution: {integrity: sha512-drqDG3cbczxxEJRoOXcOjtdp1J/lyp1mNn0xaznRs8+muBhgQcrnbspox5X5fOw0HnMnbfDzvnEMEtqDEJEo8w==}
+ engines: {node: '>=8'}
+
resolution: {integrity: sha512-+Pgi+vMuUNkJyExiMBt5IlFoMyKnr5zhJ4Uspz58WOhBF5QoIZkFyNHIbBAtHwzVAgk5RtndVNsDRN61/mmDqg==}
engines: {node: '>=12'}
@@ -7040,6 +7132,9 @@ packages:
resolution: {integrity: sha512-NM8/P9n3XjXhIZn1lLhkFaACTOURQXjWhV4BA/RnOv8xvgqtqpAX9IO4mRQxSx1Rlo4tqzeqb0sOlruaOy3dug==}
+ resolution: {integrity: sha512-7DE8mpG+/fVw+dTpjbxnx47TaMnDfOI1jwft9g1VybltZCduyRQPJPvc+zzKY9WPHxhPWczyFuYa6I8Mw4iU5A==}
+
resolution: {integrity: sha512-fQhoXdcvc3V28x7C7BMs4P5+kNlgUURe2jmUT1T//oBRMDrqy1QPelJimwZGo7Hg9VPV3EQV5Bnq4hbFy2vetA==}
@@ -7323,6 +7418,10 @@ packages:
resolution: {integrity: sha512-NXYBzinNrblfraPGyrbPoD19C1h9lfI/1mzgWYvXUTe414Gz/X1FD2XBZSZM7rRTrMA8JL3OtAaGifrIKhQ5yQ==}
engines: {node: '>= 12.0.0'}
+ resolution: {integrity: sha512-7AO748wWnIhNqAuaty2ZWHkQHRSNfPVIsPIfwEOWO22AmaoVrWavlOcMR5nzTLNYvp36X220/maaRsrec1G65A==}
+ engines: {node: '>=6'}
+
resolution: {integrity: sha512-FT1yDzDYEoYWhnSGnpE/4Kj1fLZkDFyqRb7fNt6FdYOSxlUWAtp42Eh6Wb0rGIv/m9Bgo7x4GhQbm5Ys4SG5ow==}
@@ -7677,6 +7776,10 @@ packages:
resolution: {integrity: sha512-OqbOk5oEQeAZ8WXWydlu9HJjz9WVdEIvamMCcXmuqUYjTknH/sqsWvhQ3vgwKFRR1HpjvNBKQ37nbJgYzGqGcg==}
engines: {node: '>=6'}
+ resolution: {integrity: sha512-Ysbi9uYW9hFyfrThdDEQuykN4Ey6BuwPD2kpI5ES/nFTDn/98yxYNLZJcgUAKPT/mcrLLKaGzJR9YVxJrIdASQ==}
+ engines: {node: '>=8'}
+
resolution: {integrity: sha512-VP79XUPxV2CigYP3jWwAUFSku2aKqBH7uTAapFWCBqutsbmDo96KY5o8uh6U+/YSIn5OxJnXp73beVkpqMIGhA==}
engines: {node: '>=18'}
@@ -7985,6 +8088,10 @@ packages:
resolution: {integrity: sha512-BZOr3nRQHOntUjTrH8+Lh54smKHoHyur8We1V8DSMVrl5A2malOOwuJRnKRDjSnkoeBh4at6BwEnb5I7Jl31wg==}
engines: {node: '>=8'}
+ resolution: {integrity: sha512-//88mFWSJx8lxCzwdAABTJL2MyWB12+eIY7MDL2SqLmAkeKU9qxRvWuSyTjm3FUmpBEMuFfckAIqEaVGUDxb6w==}
+ engines: {node: '>=6'}
+
resolution: {integrity: sha512-TYOanM3wGwNGsZN2cVTYPArw454xnXj5qmWF1bEoAc4+cU/ol7GVh7odevjp1FNHduHc3KZMcFduxU5Xc6uJRQ==}
engines: {node: '>=10'}
@@ -7993,6 +8100,10 @@ packages:
resolution: {integrity: sha512-7cIXg/Z0M5WZRblrsOla88S4wAK+zOQQWeBYfV3qJuJXMr+LnbYjaadrFaS0JILfEDPVqHyKnZ1Z/1d6J9VVUw==}
engines: {node: '>=20'}
+ resolution: {integrity: sha512-x+12w/To+4GFfgJhBEpiDcLozRJGegY+Ei7/z0tSLkMmxGZNybVMSfWj9aJn8Z5Fc7dBUNJOOVgPv2H7IwulSQ==}
+ engines: {node: '>=6'}
+
resolution: {integrity: sha512-7NED7xhQ74Ngp4JP/2e0VZHp7vSWfJfqeiR92jPgxsz6m0Se4P03YoTKa9dDXyZ3r6P616gUXttrB6nnHYKang==}
engines: {node: '>=20'}
@@ -8001,6 +8112,10 @@ packages:
resolution: {integrity: sha512-AxTM2wDGORHGEkPCt8yqxOTMgpfbEHqF51f/5fJCmwFC3C/zNcGT63SymH2ttOAaiIws2zVg4+izQCjrakcwHg==}
engines: {node: '>=20'}
+ resolution: {integrity: sha512-R4nPAVTAU0B9D35/Gk3uJf/7XYbQcyohSKdvAxIRSNghFl4e71hVoGnBNQz9cWaXxO2I10KTC+3jMdvvoKw6dQ==}
+ engines: {node: '>=6'}
+
resolution: {integrity: sha512-61A5ThoTiDG/C8s8UMZwSorAGwMJ0ERVGj2OjoW5pAalsNOg15+iQiPzrLJ4jhZ1HJzmC2PIHT2oEiH3R5fzNA==}
@@ -8031,6 +8146,10 @@ packages:
resolution: {integrity: sha512-b7uo2UCUOYZcnF/3ID0lulOJi/bafxa1xPe7ZPsammBSpjSWQkjNxlt635YGS2MiR9GjvuXCtz2emr3jbsz98g==}
+ resolution: {integrity: sha512-bpC7GYwiDYQ4wYLe+FA8lhRjhQCMcQGuSgGGqDkg/QerRWw9CmGRT0iSOVRSZJ29NMLZgIzqaljJ63oaL4NIJQ==}
+ engines: {node: '>=4'}
+
resolution: {integrity: sha512-cbrerZV+6rvdQrrD+iGMcZFEiiSrbv9Tfdkvnusy6y0x0GKBXREFg/Y65GhIfm0tnLntThhzCnfKwp1WRjeCyQ==}
engines: {node: '>=14.0.0'}
@@ -8141,6 +8260,10 @@ packages:
resolution: {integrity: sha512-wQ0b/W4Fr01qtpHlqSqspcj3EhBvimsdh0KlHhH8HRZnMsEa0ea2fTULOXOS9ccQr3om+GcGRk4e+isrZWV8qQ==}
engines: {node: '>=16.20.0'}
+ resolution: {integrity: sha512-nDywThFk1i4BQK4twPQ6TA4RT8bDY96yeuCVBWL3ePARCiEKDRSrNGbFIgUJpLp+XeIR65v8ra7WuJOFUBtkMA==}
+ engines: {node: '>=8'}
+
resolution: {integrity: sha512-9bW6zvX/m0lEbgTKJ6YppOKx8H3VOPBMOCFh2irXFOT4BbHgrx5hPjwJYLT40Lu+4qtD36qKc/Hn56StUW57IA==}
engines: {node: '>=18'}
@@ -9211,6 +9334,10 @@ packages:
resolution: {integrity: sha512-Ne2YiiGN8bmrmJJEuTWTLJR32nh/JdL1+PSicowtNb0WFpn59GK8/lfD61bVtzguz7b3PBt74nxpv/Pw5po5Rg==}
engines: {node: '>=8'}
+ resolution: {integrity: sha512-RAH822pAdBgcNMAfWnCBU3CFZcfZ/i1eZjwFU/dsLKumyuuP3niueg2UAukXYF0E2AAoc82ZSSf9J0WQBinzHA==}
+ engines: {node: '>=12.20'}
+
resolution: {integrity: sha512-1URUxUqfHFM1c+zfSPsa3gnkO7Aq21qyH75SIduNYz4SzY964rn1X2vCMQaHSHhktiw+0kPa2iyb6PUpXqB6Vg==}
engines: {node: '>=20'}
@@ -10712,10 +10839,10 @@ snapshots:
optionalDependencies:
'@types/react': 19.2.16
dependencies:
react: 19.2.3
'@capsizecss/[email protected]':
dependencies:
@@ -10744,18 +10871,18 @@ snapshots:
fast-wrap-ansi: 0.2.2
sisteransi: 1.0.5
dependencies:
+ '@clerk/shared': 4.19.2-snapshot.v20260619001138([email protected]([email protected]))([email protected])
standardwebhooks: 1.0.0
tslib: 2.8.1
transitivePeerDependencies:
- react
- react-dom
dependencies:
+ '@clerk/shared': 4.19.2-snapshot.v20260619001138([email protected]([email protected]))([email protected])
'@stripe/stripe-js': 5.6.0
'@swc/helpers': 0.5.21
'@tanstack/query-core': 5.100.14
@@ -10770,9 +10897,9 @@ snapshots:
- react
- react-dom
dependencies:
+ '@clerk/shared': 4.19.2-snapshot.v20260619001138([email protected]([email protected]))([email protected])
'@stripe/stripe-js': 5.6.0
'@swc/helpers': 0.5.21
'@tanstack/query-core': 5.100.14
@@ -10787,40 +10914,72 @@ snapshots:
- react
- react-dom
+ '@clerk/[email protected]':
+ optional: true
+
+ '@clerk/[email protected]':
+ optional: true
+
+ '@clerk/electron-passkeys-win32-arm64-msvc@0.0.1-snapshot.v20260619001138':
+ optional: true
+
+ '@clerk/[email protected]':
+ optional: true
+
+ '@clerk/[email protected]':
+ optionalDependencies:
+ '@clerk/electron-passkeys-darwin-arm64': 0.0.1-snapshot.v20260619001138
+ '@clerk/electron-passkeys-darwin-x64': 0.0.1-snapshot.v20260619001138
+ '@clerk/electron-passkeys-win32-arm64-msvc': 0.0.1-snapshot.v20260619001138
+ '@clerk/electron-passkeys-win32-x64-msvc': 0.0.1-snapshot.v20260619001138
+
+ dependencies:
+ '@clerk/clerk-js': 6.18.2-snapshot.v20260619001138([email protected]([email protected]))([email protected])
+ '@clerk/react': 6.10.4-snapshot.v20260619001138([email protected]([email protected]))([email protected])
+ '@clerk/shared': 4.19.2-snapshot.v20260619001138([email protected]([email protected]))([email protected])
+ electron: 41.5.0
+ react: 19.2.6
+ tslib: 2.8.1
+ optionalDependencies:
+ '@clerk/electron-passkeys': 0.0.1-snapshot.v20260619001138
+ electron-store: 8.2.0
+ react-dom: 19.2.6([email protected])
+
dependencies:
+ '@clerk/clerk-js': 6.18.2-snapshot.v20260619001138([email protected]([email protected]))([email protected])
+ '@clerk/react': 6.10.4-snapshot.v20260619001138([email protected]([email protected]))([email protected])
+ '@clerk/shared': 4.19.2-snapshot.v20260619001138([email protected]([email protected]))([email protected])
base-64: 1.0.0
+ expo: 56.0.8(63f7aade424ad9e7b1154b679fa2a14d)
react: 19.2.3
tslib: 2.8.1
optionalDependencies:
expo-crypto: 56.0.4([email protected])
expo-secure-store: 56.0.4([email protected])
react-dom: 19.2.3([email protected])
dependencies:
+ '@clerk/shared': 4.19.2-snapshot.v20260619001138([email protected]([email protected]))([email protected])
react: 19.2.3
react-dom: 19.2.3([email protected])
tslib: 2.8.1
dependencies:
+ '@clerk/shared': 4.19.2-snapshot.v20260619001138([email protected]([email protected]))([email protected])
react: 19.2.6
react-dom: 19.2.6([email protected])
tslib: 2.8.1
dependencies:
'@tanstack/query-core': 5.100.14
dequal: 2.0.3
@@ -10830,7 +10989,7 @@ snapshots:
react: 19.2.3
react-dom: 19.2.3([email protected])
dependencies:
'@tanstack/query-core': 5.100.14
dequal: 2.0.3
@@ -11370,7 +11529,7 @@ snapshots:
'@expo-google-fonts/[email protected]': {}
dependencies:
'@expo/code-signing-certificates': 0.0.6
'@expo/config': 56.0.9([email protected])
@@ -11380,7 +11539,7 @@ snapshots:
'@expo/image-utils': 0.10.1([email protected])
'@expo/inline-modules': 0.0.10([email protected])
'@expo/json-file': 10.2.0
'@expo/metro': 56.0.0([email protected])([email protected])
'@expo/metro-config': 56.0.13(patch_hash=8cb08b5bb7051ed9d2dbe46a2c293c5a1e17f1bd6ddf30de27909e18c921ff46)([email protected])([email protected])([email protected])([email protected])
'@expo/metro-file-map': 56.0.3
@@ -11405,7 +11564,7 @@ snapshots:
connect: 3.7.0
debug: 4.4.3
dnssd-advertise: 1.1.4
+ expo: 56.0.8(63f7aade424ad9e7b1154b679fa2a14d)
expo-server: 56.0.4
fetch-nodeshim: 0.4.10
getenv: 2.0.0
@@ -11431,8 +11590,8 @@ snapshots:
zod: 3.25.76
optionalDependencies:
- expo-router: 56.2.8(c021de11d02907bd585610408f5252e8)
+ expo-router: 56.2.8(5bfdf39b8f760e4dc2d5c3acffc97310)
transitivePeerDependencies:
- '@expo/dom-webview'
- '@expo/metro-runtime'
@@ -11494,18 +11653,18 @@ snapshots:
transitivePeerDependencies:
- supports-color
dependencies:
chalk: 4.1.2
optionalDependencies:
react: 19.2.3
dependencies:
+ expo: 56.0.8(63f7aade424ad9e7b1154b679fa2a14d)
react: 19.2.3
dependencies:
@@ -11566,13 +11725,13 @@ snapshots:
- supports-color
- typescript
dependencies:
anser: 1.4.10
+ expo: 56.0.8(63f7aade424ad9e7b1154b679fa2a14d)
react: 19.2.3
stacktrace-parser: 0.1.11
'@expo/[email protected](patch_hash=8cb08b5bb7051ed9d2dbe46a2c293c5a1e17f1bd6ddf30de27909e18c921ff46)([email protected])([email protected])([email protected])([email protected])':
@@ -11602,7 +11761,7 @@ snapshots:
postcss: 8.5.15
resolve-from: 5.0.0
optionalDependencies:
+ expo: 56.0.8(63f7aade424ad9e7b1154b679fa2a14d)
transitivePeerDependencies:
- bufferutil
- supports-color
@@ -11620,14 +11779,14 @@ snapshots:
transitivePeerDependencies:
- supports-color
dependencies:
anser: 1.4.10
+ expo: 56.0.8(63f7aade424ad9e7b1154b679fa2a14d)
pretty-format: 29.7.0
react: 19.2.3
stacktrace-parser: 0.1.11
whatwg-fetch: 3.6.20
optionalDependencies:
@@ -11702,14 +11861,14 @@ snapshots:
dependencies:
debug: 4.4.3
+ expo: 56.0.8(63f7aade424ad9e7b1154b679fa2a14d)
expo-server: 56.0.4
react: 19.2.3
optionalDependencies:
- expo-router: 56.2.8(c021de11d02907bd585610408f5252e8)
+ expo-router: 56.2.8(5bfdf39b8f760e4dc2d5c3acffc97310)
react-dom: 19.2.3([email protected])
transitivePeerDependencies:
- supports-color
@@ -11724,18 +11883,18 @@ snapshots:
'@expo/[email protected]': {}
- '@expo/[email protected](ab3f255d102c60ba0fd2bbe4e47ba584)':
+ '@expo/[email protected](961c4aa6f32829b318e3c87ef20ad401)':
dependencies:
+ expo: 56.0.8(63f7aade424ad9e7b1154b679fa2a14d)
react: 19.2.3
sf-symbols-typescript: 2.2.0
optionalDependencies:
'@babel/core': 7.29.7
react-dom: 19.2.3([email protected])
transitivePeerDependencies:
- '@types/react'
- '@types/react-dom'
@@ -11996,13 +12155,13 @@ snapshots:
dependencies:
jsbi: 4.3.2
dependencies:
react: 19.2.3
use-sync-external-store: 1.6.0([email protected])
optionalDependencies:
react-dom: 19.2.3([email protected])
dependencies:
@@ -12825,15 +12984,15 @@ snapshots:
prompts: 2.4.2
tinyexec: 1.2.4
dependencies:
react: 19.2.3
dependencies:
react: 19.2.3
'@react-native/[email protected]': {}
@@ -12893,7 +13052,7 @@ snapshots:
tinyglobby: 0.2.17
yargs: 17.7.2
dependencies:
'@react-native/dev-middleware': 0.85.3([email protected])([email protected])
debug: 4.4.3
@@ -12903,7 +13062,7 @@ snapshots:
metro-core: 0.84.4
semver: 7.8.1
optionalDependencies:
- '@react-native/metro-config': 0.85.3(@babel/[email protected])
+ '@react-native/metro-config': 0.85.3(@babel/[email protected])([email protected])([email protected])
transitivePeerDependencies:
- bufferutil
- supports-color
@@ -12951,7 +13110,7 @@ snapshots:
transitivePeerDependencies:
- supports-color
- '@react-native/[email protected](@babel/[email protected])':
dependencies:
'@react-native/js-polyfills': 0.85.3
'@react-native/metro-babel-transformer': 0.85.3(@babel/[email protected])
@@ -12959,16 +13118,18 @@ snapshots:
metro-runtime: 0.84.4
transitivePeerDependencies:
- '@babel/core'
+ - bufferutil
- supports-color
+ - utf-8-validate
'@react-native/[email protected]': {}
dependencies:
invariant: 2.2.4
nullthrows: 1.1.1
react: 19.2.3
optionalDependencies:
'@types/react': 19.2.16
@@ -13381,15 +13542,15 @@ snapshots:
dependencies:
defer-to-connect: 2.0.1
- '@t3tools/mobile-markdown-text@file:apps/mobile/modules/t3-markdown-text(e909ee9a8f7fbe234da80c739fca4984)':
+ '@t3tools/mobile-markdown-text@file:apps/mobile/modules/t3-markdown-text(f0ff241d48c23db461fff5d47e450578)':
dependencies:
expo-haptics: 56.0.3([email protected])
react: 19.2.3
'@t3tools/mobile-review-diff-native@file:apps/mobile/modules/t3-review-diff': {}
@@ -14060,6 +14221,10 @@ snapshots:
optionalDependencies:
ajv: 8.20.0
+ optionalDependencies:
+ ajv: 8.20.0
+
optionalDependencies:
ajv: 8.20.0
@@ -14355,6 +14520,8 @@ snapshots:
+
@@ -14459,8 +14626,8 @@ snapshots:
react-refresh: 0.14.2
optionalDependencies:
'@babel/runtime': 7.29.7
- expo-widgets: 56.0.16(ab3f255d102c60ba0fd2bbe4e47ba584)
+ expo: 56.0.8(63f7aade424ad9e7b1154b679fa2a14d)
+ expo-widgets: 56.0.16(961c4aa6f32829b318e3c87ef20ad401)
transitivePeerDependencies:
- '@babel/core'
- supports-color
@@ -14821,6 +14988,19 @@ snapshots:
+ dependencies:
+ ajv: 8.20.0
+ ajv-formats: 2.1.1([email protected])
+ atomically: 1.7.0
+ debounce-fn: 4.0.0
+ dot-prop: 6.0.1
+ env-paths: 2.2.1
+ json-schema-typed: 7.0.3
+ onetime: 5.1.2
+ pkg-up: 3.1.0
+ semver: 7.8.1
+
dependencies:
debug: 2.6.9
@@ -14923,6 +15103,10 @@ snapshots:
+ dependencies:
+ mimic-fn: 3.1.0
+
dependencies:
ms: 2.0.0
@@ -15052,6 +15236,10 @@ snapshots:
domelementtype: 2.3.0
domhandler: 5.0.3
+ dependencies:
+ is-obj: 2.0.0
+
dependencies:
dotenv: 16.6.1
@@ -15142,6 +15330,11 @@ snapshots:
transitivePeerDependencies:
- supports-color
+ dependencies:
+ conf: 10.2.0
+ type-fest: 2.19.0
+
@@ -15325,29 +15518,29 @@ snapshots:
dependencies:
+ expo: 56.0.8(63f7aade424ad9e7b1154b679fa2a14d)
dependencies:
'@expo/image-utils': 0.10.1([email protected])
+ expo: 56.0.8(63f7aade424ad9e7b1154b679fa2a14d)
react: 19.2.3
transitivePeerDependencies:
- supports-color
- typescript
dependencies:
expo-application: 56.0.3([email protected])
expo-crypto: 56.0.4([email protected])
invariant: 2.2.4
react: 19.2.3
transitivePeerDependencies:
- expo
- supports-color
@@ -15355,119 +15548,119 @@ snapshots:
dependencies:
'@expo/schema-utils': 56.0.1
+ expo: 56.0.8(63f7aade424ad9e7b1154b679fa2a14d)
resolve-from: 5.0.0
semver: 7.8.1
dependencies:
barcode-detector: 3.2.0(@types/[email protected])
+ expo: 56.0.8(63f7aade424ad9e7b1154b679fa2a14d)
react: 19.2.3
transitivePeerDependencies:
- '@types/emscripten'
dependencies:
+ expo: 56.0.8(63f7aade424ad9e7b1154b679fa2a14d)
react: 19.2.3
dependencies:
'@expo/env': 2.3.0
+ expo: 56.0.8(63f7aade424ad9e7b1154b679fa2a14d)
transitivePeerDependencies:
- supports-color
dependencies:
+ expo: 56.0.8(63f7aade424ad9e7b1154b679fa2a14d)
dependencies:
+ expo: 56.0.8(63f7aade424ad9e7b1154b679fa2a14d)
expo-dev-menu-interface: 56.0.1([email protected])
expo-manifests: 56.0.4([email protected])
expo-updates-interface: 56.0.2([email protected])
transitivePeerDependencies:
- react-native
dependencies:
'@expo/schema-utils': 56.0.1
+ expo: 56.0.8(63f7aade424ad9e7b1154b679fa2a14d)
expo-manifests: 56.0.4([email protected])
dependencies:
+ expo: 56.0.8(63f7aade424ad9e7b1154b679fa2a14d)
dependencies:
+ expo: 56.0.8(63f7aade424ad9e7b1154b679fa2a14d)
expo-dev-menu-interface: 56.0.1([email protected])
dependencies:
+ expo: 56.0.8(63f7aade424ad9e7b1154b679fa2a14d)
dependencies:
+ expo: 56.0.8(63f7aade424ad9e7b1154b679fa2a14d)
fontfaceobserver: 2.3.0
react: 19.2.3
dependencies:
+ expo: 56.0.8(63f7aade424ad9e7b1154b679fa2a14d)
react: 19.2.3
dependencies:
+ expo: 56.0.8(63f7aade424ad9e7b1154b679fa2a14d)
dependencies:
+ expo: 56.0.8(63f7aade424ad9e7b1154b679fa2a14d)
dependencies:
+ expo: 56.0.8(63f7aade424ad9e7b1154b679fa2a14d)
expo-image-loader: 56.0.3([email protected])
dependencies:
+ expo: 56.0.8(63f7aade424ad9e7b1154b679fa2a14d)
react: 19.2.3
dependencies:
invariant: 2.2.4
react: 19.2.3
transitivePeerDependencies:
- expo
- supports-color
dependencies:
+ expo: 56.0.8(63f7aade424ad9e7b1154b679fa2a14d)
expo-json-utils: 56.0.0
@@ -15480,66 +15673,66 @@ snapshots:
- supports-color
- typescript
dependencies:
'@expo/expo-modules-macros-plugin': 0.0.9
invariant: 2.2.4
react: 19.2.3
optionalDependencies:
dependencies:
dependencies:
+ expo: 56.0.8(63f7aade424ad9e7b1154b679fa2a14d)
react: 19.2.3
dependencies:
'@expo/image-utils': 0.10.1([email protected])
abort-controller: 3.0.0
badgin: 1.2.3
+ expo: 56.0.8(63f7aade424ad9e7b1154b679fa2a14d)
expo-application: 56.0.3([email protected])
react: 19.2.3
transitivePeerDependencies:
- supports-color
- typescript
dependencies:
+ expo: 56.0.8(63f7aade424ad9e7b1154b679fa2a14d)
react: 19.2.3
- [email protected](c021de11d02907bd585610408f5252e8):
+ [email protected](5bfdf39b8f760e4dc2d5c3acffc97310):
dependencies:
'@expo/schema-utils': 56.0.1
- '@expo/ui': 56.0.15(ab3f255d102c60ba0fd2bbe4e47ba584)
+ '@expo/ui': 56.0.15(961c4aa6f32829b318e3c87ef20ad401)
'@radix-ui/react-slot': 1.2.4(@types/[email protected])([email protected])
'@testing-library/jest-dom': 6.9.1
'@testing-library/user-event': 14.6.1(@testing-library/[email protected])
client-only: 0.0.1
color: 4.2.3
debug: 4.4.3
escape-string-regexp: 4.0.0
+ expo: 56.0.8(63f7aade424ad9e7b1154b679fa2a14d)
expo-server: 56.0.4
fast-deep-equal: 3.1.3
invariant: 2.2.4
nanoid: 3.3.12
@@ -15547,18 +15740,18 @@ snapshots:
react: 19.2.3
react-fast-compare: 3.2.2
react-is: 19.2.7
+ react-native-drawer-layout: 4.2.4(0e9729601f58a7a7ae26c76fe6017455)
server-only: 0.0.1
sf-symbols-typescript: 2.2.0
shallowequal: 1.1.0
optionalDependencies:
react-dom: 19.2.3([email protected])
transitivePeerDependencies:
- '@babel/core'
- '@testing-library/dom'
@@ -15570,7 +15763,7 @@ snapshots:
dependencies:
+ expo: 56.0.8(63f7aade424ad9e7b1154b679fa2a14d)
@@ -15578,7 +15771,7 @@ snapshots:
dependencies:
'@expo/config-plugins': 56.0.8([email protected])
'@expo/image-utils': 0.10.1([email protected])
+ expo: 56.0.8(63f7aade424ad9e7b1154b679fa2a14d)
xml2js: 0.6.0
transitivePeerDependencies:
- supports-color
@@ -15586,20 +15779,20 @@ snapshots:
dependencies:
'@expo-google-fonts/material-symbols': 0.4.38
+ expo: 56.0.8(63f7aade424ad9e7b1154b679fa2a14d)
react: 19.2.3
sf-symbols-typescript: 2.2.0
dependencies:
+ expo: 56.0.8(63f7aade424ad9e7b1154b679fa2a14d)
dependencies:
'@expo/code-signing-certificates': 0.0.6
'@expo/plist': 0.7.0
@@ -15607,7 +15800,7 @@ snapshots:
arg: 4.1.3
chalk: 4.1.2
debug: 4.4.3
+ expo: 56.0.8(63f7aade424ad9e7b1154b679fa2a14d)
expo-eas-client: 56.0.1
expo-manifests: 56.0.4([email protected])
expo-structured-headers: 56.0.0
@@ -15617,25 +15810,25 @@ snapshots:
ignore: 5.3.2
nullthrows: 1.1.1
react: 19.2.3
resolve-from: 5.0.0
optionalDependencies:
transitivePeerDependencies:
- supports-color
dependencies:
+ expo: 56.0.8(63f7aade424ad9e7b1154b679fa2a14d)
- [email protected](ab3f255d102c60ba0fd2bbe4e47ba584):
+ [email protected](961c4aa6f32829b318e3c87ef20ad401):
dependencies:
'@expo/plist': 0.7.0
- '@expo/ui': 56.0.15(ab3f255d102c60ba0fd2bbe4e47ba584)
+ '@expo/ui': 56.0.15(961c4aa6f32829b318e3c87ef20ad401)
+ expo: 56.0.8(63f7aade424ad9e7b1154b679fa2a14d)
react: 19.2.3
transitivePeerDependencies:
- '@babel/core'
- '@types/react'
@@ -15644,37 +15837,37 @@ snapshots:
- react-native-reanimated
- react-native-worklets
+ [email protected](63f7aade424ad9e7b1154b679fa2a14d):
dependencies:
'@babel/runtime': 7.29.7
'@expo/config': 56.0.9([email protected])
'@expo/config-plugins': 56.0.8([email protected])
'@expo/fingerprint': 0.19.3
'@expo/local-build-cache-provider': 56.0.8([email protected])
'@expo/metro': 56.0.0([email protected])([email protected])
'@expo/metro-config': 56.0.13(patch_hash=8cb08b5bb7051ed9d2dbe46a2c293c5a1e17f1bd6ddf30de27909e18c921ff46)([email protected])([email protected])([email protected])([email protected])
'@ungap/structured-clone': 1.3.1
expo-keep-awake: 56.0.3([email protected])([email protected])
expo-modules-autolinking: 56.0.14([email protected])
pretty-format: 29.7.0
react: 19.2.3
react-refresh: 0.14.2
whatwg-url-minimum: 0.1.2
optionalDependencies:
react-dom: 19.2.3([email protected])
transitivePeerDependencies:
- '@babel/core'
- bufferutil
@@ -15862,6 +16055,10 @@ snapshots:
+ dependencies:
+ locate-path: 3.0.0
+
@@ -16388,6 +16585,8 @@ snapshots:
+
@@ -16488,6 +16687,8 @@ snapshots:
+
@@ -16715,6 +16916,11 @@ snapshots:
lightningcss-win32-arm64-msvc: 1.32.0
lightningcss-win32-x64-msvc: 1.32.0
+ dependencies:
+ p-locate: 3.0.0
+ path-exists: 3.0.0
+
@@ -17363,6 +17569,8 @@ snapshots:
+
@@ -17703,6 +17911,10 @@ snapshots:
+ dependencies:
+ p-try: 2.2.0
+
dependencies:
yocto-queue: 0.1.0
@@ -17711,6 +17923,10 @@ snapshots:
dependencies:
yocto-queue: 1.2.2
+ dependencies:
+ p-limit: 2.3.0
+
dependencies:
eventemitter3: 5.0.4
@@ -17718,6 +17934,8 @@ snapshots:
+
@@ -17755,6 +17973,8 @@ snapshots:
+
@@ -17847,6 +18067,10 @@ snapshots:
+ dependencies:
+ find-up: 3.0.0
+
@@ -18061,102 +18285,102 @@ snapshots:
transitivePeerDependencies:
- supports-color
+ [email protected](0e9729601f58a7a7ae26c76fe6017455):
dependencies:
color: 4.2.3
react: 19.2.3
use-latest-callback: 0.2.6([email protected])
dependencies:
'@egjs/hammerjs': 2.0.17
'@types/react-test-renderer': 19.1.0
hoist-non-react-statics: 3.3.2
invariant: 2.2.4
react: 19.2.3
dependencies:
react: 19.2.3
dependencies:
react: 19.2.3
dependencies:
react: 19.2.3
dependencies:
react: 19.2.3
- react-native-nitro-modules: 0.35.9(patch_hash=825622aae63a8fb5b904f3c77908a0e216261d727ea171709f2c0b6088422675)([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected])([email protected])([email protected]))([email protected])
+ react-native-nitro-modules: 0.35.9(patch_hash=825622aae63a8fb5b904f3c77908a0e216261d727ea171709f2c0b6088422675)([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected])([email protected])([email protected]))(@types/[email protected])([email protected])([email protected])([email protected]))([email protected])
optionalDependencies:
- [email protected](patch_hash=825622aae63a8fb5b904f3c77908a0e216261d727ea171709f2c0b6088422675)([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected])([email protected])([email protected]))([email protected]):
dependencies:
react: 19.2.3
dependencies:
react: 19.2.3
semver: 7.8.1
dependencies:
react: 19.2.3
dependencies:
react: 19.2.3
react-freeze: 1.0.4([email protected])
warn-once: 0.1.1
dependencies:
'@shikijs/types': 4.2.0
'@shikijs/vscode-textmate': 10.0.2
react: 19.2.3
dependencies:
css-select: 5.2.2
css-tree: 1.1.3
react: 19.2.3
warn-once: 0.1.1
dependencies:
whatwg-url-without-unicode: 8.0.0-3
dependencies:
escape-string-regexp: 4.0.0
invariant: 2.2.4
react: 19.2.3
dependencies:
'@babel/core': 7.29.7
'@babel/plugin-transform-arrow-functions': 7.29.7(@babel/[email protected])
@@ -18168,23 +18392,23 @@ snapshots:
'@babel/plugin-transform-template-literals': 7.29.7(@babel/[email protected])
'@babel/plugin-transform-unicode-regex': 7.29.7(@babel/[email protected])
'@babel/preset-typescript': 7.29.7(@babel/[email protected])
- '@react-native/metro-config': 0.85.3(@babel/[email protected])
+ '@react-native/metro-config': 0.85.3(@babel/[email protected])([email protected])([email protected])
convert-source-map: 2.0.0
react: 19.2.3
semver: 7.8.1
transitivePeerDependencies:
- supports-color
dependencies:
'@react-native/assets-registry': 0.85.3
'@react-native/codegen': 0.85.3(@babel/[email protected])
- '@react-native/community-cli-plugin': 0.85.3(@react-native/[email protected](@babel/[email protected]))([email protected])([email protected])
+ '@react-native/community-cli-plugin': 0.85.3(@react-native/[email protected](@babel/[email protected])([email protected])([email protected]))([email protected])([email protected])
'@react-native/gradle-plugin': 0.85.3
'@react-native/js-polyfills': 0.85.3
'@react-native/normalize-colors': 0.85.3
abort-controller: 3.0.0
anser: 1.4.10
ansi-regex: 5.0.1
@@ -19100,6 +19324,8 @@ snapshots:
+
dependencies:
tagged-tag: 1.0.0
@@ -19211,14 +19437,14 @@ snapshots:
dependencies:
'@tailwindcss/node': 4.2.1
'@tailwindcss/oxide': 4.2.1
culori: 4.0.2
lightningcss: 1.30.1
react: 19.2.3
tailwindcss: 4.3.0
diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yaml
index 233680b72..03960dfbb 100644
--- a/pnpm-workspace.yaml
+++ b/pnpm-workspace.yaml
@@ -6,6 +6,13 @@ packages:
- scripts
catalog:
+ "@clerk/backend": 3.8.2-snapshot.v20260619001138
+ "@clerk/clerk-js": 6.18.2-snapshot.v20260619001138
+ "@clerk/electron": 0.0.1-snapshot.v20260619001138
+ "@clerk/electron-passkeys": 0.0.1-snapshot.v20260619001138
+ "@clerk/expo": 3.4.8-snapshot.v20260619001138
+ "@clerk/react": 6.10.4-snapshot.v20260619001138
+ "@clerk/shared": 4.19.2-snapshot.v20260619001138
"@effect/atom-react": 4.0.0-beta.78
"@effect/openapi-generator": 4.0.0-beta.78
"@effect/platform-bun": 4.0.0-beta.78
@@ -40,6 +47,16 @@ onlyBuiltDependencies:
- sharp
overrides:
+ # Keep every Clerk consumer on the same snapshot train. Clerk publishes wallet
+ # auth integrations as required dependencies, but T3 Code does not support
+ # wallet auth, so keep that unused dependency tree out of installs.
+ "@clerk/backend": "catalog:"
+ "@clerk/clerk-js": "catalog:"
+ "@clerk/electron": "catalog:"
+ "@clerk/electron-passkeys": "catalog:"
+ "@clerk/expo": "catalog:"
+ "@clerk/react": "catalog:"
+ "@clerk/shared": "catalog:"
"@clerk/clerk-js>@base-org/account": "-"
"@clerk/clerk-js>@coinbase/wallet-sdk": "-"
"@clerk/clerk-js>@solana/wallet-adapter-base": "-"
diff --git a/scripts/build-desktop-artifact.test.ts b/scripts/build-desktop-artifact.test.ts
index 8135f7e25..b0d84bb12 100644
--- a/scripts/build-desktop-artifact.test.ts
+++ b/scripts/build-desktop-artifact.test.ts
@@ -8,7 +8,11 @@ import * as Option from "effect/Option";
import {
createStageWorkspaceConfig,
createStagePnpmConfig,
+ createBuildConfig,
DESKTOP_ASAR_UNPACK,
+ renderMacPasskeyEntitlements,
+ resolveClerkPasskeyNativeArtifacts,
+ resolveMacPasskeySigningConfiguration,
resolveDesktopRuntimeDependencies,
resolveFffNativeDependencies,
resolveBuildOptions,
@@ -175,6 +179,86 @@ it.layer(NodeServices.layer)("build-desktop-artifact", (it) => {
assert.deepStrictEqual(DESKTOP_ASAR_UNPACK, ["node_modules/@ff-labs/fff-bin-*/**/*"]);
});
+ it("derives macOS passkey signing configuration from the Clerk publishable key", () => {
+ const configuration = resolveMacPasskeySigningConfiguration({
+ T3CODE_APPLE_TEAM_ID: "abc1234567",
+ T3CODE_MACOS_PROVISIONING_PROFILE: "/tmp/t3code.provisionprofile",
+ T3CODE_CLERK_PUBLISHABLE_KEY: `pk_test_${btoa("example.clerk.accounts.dev$")}`,
+ });
+
+ assert.deepStrictEqual(configuration, {
+ appId: "com.t3tools.t3code",
+ teamId: "ABC1234567",
+ rpDomains: ["example.clerk.accounts.dev"],
+ provisioningProfilePath: "/tmp/t3code.provisionprofile",
+ });
+ });
+
+ it("normalizes explicit macOS passkey RP domains and renders required entitlements", () => {
+ const configuration = resolveMacPasskeySigningConfiguration({
+ T3CODE_APPLE_TEAM_ID: "ABC1234567",
+ T3CODE_MACOS_PROVISIONING_PROFILE: "/tmp/t3code.provisionprofile",
+ T3CODE_CLERK_PASSKEY_RP_DOMAINS:
+ " Clerk.Example.com,example.clerk.accounts.dev,clerk.example.com ",
+ });
+ const entitlements = renderMacPasskeyEntitlements(configuration);
+
+ assert.deepStrictEqual(configuration.rpDomains, [
+ "clerk.example.com",
+ "example.clerk.accounts.dev",
+ ]);
+ assert.include(entitlements, "<string>ABC1234567.com.t3tools.t3code</string>");
+ assert.include(entitlements, "<string>webcredentials:clerk.example.com</string>");
+ assert.include(entitlements, "<string>webcredentials:example.clerk.accounts.dev</string>");
+ assert.include(entitlements, "<key>com.apple.security.cs.allow-jit</key>");
+ });
+
+ it("rejects incomplete macOS passkey signing configuration", () => {
+ assert.throws(
+ () =>
+ resolveMacPasskeySigningConfiguration({
+ T3CODE_APPLE_TEAM_ID: "ABC1234567",
+ T3CODE_CLERK_PASSKEY_RP_DOMAINS: "example.clerk.accounts.dev",
+ }),
+ /T3CODE_MACOS_PROVISIONING_PROFILE/u,
+ );
+ assert.throws(
+ () =>
+ resolveMacPasskeySigningConfiguration({
+ T3CODE_APPLE_TEAM_ID: "ABC1234567",
+ T3CODE_MACOS_PROVISIONING_PROFILE: "/tmp/t3code.provisionprofile",
+ T3CODE_CLERK_PASSKEY_RP_DOMAINS: "https://example.clerk.accounts.dev/path",
+ }),
+ /Invalid passkey RP domain/u,
+ );
+ assert.throws(
+ () =>
+ resolveMacPasskeySigningConfiguration({
+ T3CODE_APPLE_TEAM_ID: "ABC1234567",
+ T3CODE_MACOS_PROVISIONING_PROFILE: "/tmp/t3code.provisionprofile",
+ T3CODE_CLERK_PASSKEY_RP_DOMAINS: "example.clerk.accounts.dev:8443",
+ }),
+ /Invalid passkey RP domain/u,
+ );
+ });
+
+ it.effect("adds passkey entitlements and both renderer protocols to signed macOS builds", () =>
+ Effect.gen(function* () {
+ const config = yield* createBuildConfig("mac", "dmg", "1.2.3", true, false, undefined, {
+ entitlementsPath: "/tmp/entitlements.mac.plist",
+ provisioningProfilePath: "/tmp/t3code.provisionprofile",
+ });
+
+ const mac = config.mac as Record<string, unknown>;
+ assert.equal(config.appId, "com.t3tools.t3code");
+ assert.equal(mac.entitlements, "/tmp/entitlements.mac.plist");
+ assert.equal(mac.provisioningProfile, "/tmp/t3code.provisionprofile");
+ assert.deepStrictEqual(mac.protocols, [
+ { name: "T3 Code", schemes: ["t3code", "t3code-dev"] },
+ ]);
+ }).pipe(Effect.provide(ConfigProvider.layer(ConfigProvider.fromEnv({ env: {} })))),
+ );
+
it("promotes target fff binaries to direct staged dependencies", () => {
assert.deepStrictEqual(resolveFffNativeDependencies("mac", "arm64", "0.9.4"), {
"@ff-labs/fff-bin-darwin-arm64": "0.9.4",
@@ -192,6 +276,26 @@ it.layer(NodeServices.layer)("build-desktop-artifact", (it) => {
});
});
+ it("resolves target Clerk passkey native artifacts", () => {
+ assert.deepStrictEqual(resolveClerkPasskeyNativeArtifacts("mac", "universal"), [
+ {
+ packageName: "@clerk/electron-passkeys-darwin-arm64",
+ binaryFileName: "electron-passkeys.darwin-arm64.node",
+ },
+ {
+ packageName: "@clerk/electron-passkeys-darwin-x64",
+ binaryFileName: "electron-passkeys.darwin-x64.node",
+ },
+ ]);
+ assert.deepStrictEqual(resolveClerkPasskeyNativeArtifacts("win", "x64"), [
+ {
+ packageName: "@clerk/electron-passkeys-win32-x64-msvc",
+ binaryFileName: "electron-passkeys.win32-x64-msvc.node",
+ },
+ ]);
+ assert.deepStrictEqual(resolveClerkPasskeyNativeArtifacts("linux", "x64"), []);
+ });
+
it("falls back to the default mock update port when the configured port is blank", () => {
assert.equal(resolveMockUpdateServerUrl(undefined), "http://localhost:3000");
assert.equal(resolveMockUpdateServerUrl(4123), "http://localhost:4123");
diff --git a/scripts/build-desktop-artifact.ts b/scripts/build-desktop-artifact.ts
index 6b519b1d4..8aa95c3e6 100644
--- a/scripts/build-desktop-artifact.ts
+++ b/scripts/build-desktop-artifact.ts
@@ -1,7 +1,10 @@
#!/usr/bin/env node
+import { createRequire } from "node:module";
+
import { fromYaml } from "@t3tools/shared/schemaYaml";
import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
+import { clerkFrontendApiHostnameFromPublishableKey } from "@t3tools/shared/relayAuth";
import { resolveSpawnCommand } from "@t3tools/shared/shell";
import rootPackageJson from "../package.json" with { type: "json" };
import desktopPackageJson from "../apps/desktop/package.json" with { type: "json" };
@@ -9,6 +12,7 @@ import serverPackageJson from "../apps/server/package.json" with { type: "json"
import { BRAND_ASSET_PATHS } from "./lib/brand-assets.ts";
import { getDefaultBuildArch } from "./lib/build-target-arch.ts";
+import { loadRepoEnv } from "./lib/public-config.ts";
import { resolveCatalogDependencies } from "./lib/resolve-catalog.ts";
import * as NodeRuntime from "@effect/platform-node/NodeRuntime";
@@ -27,6 +31,8 @@ import { Command, Flag } from "effect/unstable/cli";
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
const LINUX_ICON_SIZES = [16, 22, 24, 32, 48, 64, 128, 256, 512] as const;
+const DESKTOP_APP_ID = "com.t3tools.t3code";
+const APPLE_TEAM_ID_PATTERN = /^[A-Z0-9]{10}$/u;
const BuildPlatform = Schema.Literals(["mac", "linux", "win"]);
const BuildArch = Schema.Literals(["arm64", "x64", "universal"]);
@@ -293,6 +299,121 @@ interface StagePackageJson {
export const STAGE_INSTALL_ARGS = ["install", "--prod"] as const;
export const DESKTOP_ASAR_UNPACK = ["node_modules/@ff-labs/fff-bin-*/**/*"] as const;
+export interface MacPasskeySigningConfiguration {
+ readonly appId: string;
+ readonly teamId: string;
+ readonly rpDomains: readonly string[];
+ readonly provisioningProfilePath: string;
+}
+
+function normalizePasskeyRpDomain(value: string): string {
+ const normalized = value.trim().toLowerCase();
+ let parsed: URL;
+ try {
+ parsed = new URL(`https://${normalized}`);
+ } catch {
+ throw new Error(`Invalid passkey RP domain: ${value}`);
+ }
+
+ if (
+ normalized.length === 0 ||
+ parsed.host !== normalized ||
+ parsed.username.length > 0 ||
+ parsed.password.length > 0 ||
+ parsed.port.length > 0 ||
+ parsed.pathname !== "/" ||
+ parsed.search.length > 0 ||
+ parsed.hash.length > 0
+ ) {
+ throw new Error(`Invalid passkey RP domain: ${value}`);
+ }
+
+ return parsed.hostname;
+}
+
+export function resolveMacPasskeySigningConfiguration(
+ env: Readonly<Record<string, string | undefined>>,
+): MacPasskeySigningConfiguration {
+ const teamId = env.T3CODE_APPLE_TEAM_ID?.trim().toUpperCase() ?? "";
+ if (!APPLE_TEAM_ID_PATTERN.test(teamId)) {
+ throw new Error("T3CODE_APPLE_TEAM_ID must be a 10-character Apple Developer Team ID.");
+ }
+
+ const provisioningProfilePath = env.T3CODE_MACOS_PROVISIONING_PROFILE?.trim() ?? "";
+ if (provisioningProfilePath.length === 0) {
+ throw new Error(
+ "T3CODE_MACOS_PROVISIONING_PROFILE must point to an Associated Domains provisioning profile.",
+ );
+ }
+
+ const configuredRpDomains = env.T3CODE_CLERK_PASSKEY_RP_DOMAINS?.trim();
+ let rpDomains: readonly string[];
+ if (configuredRpDomains) {
+ rpDomains = configuredRpDomains.split(",").map(normalizePasskeyRpDomain);
+ } else {
+ const publishableKey = env.T3CODE_CLERK_PUBLISHABLE_KEY?.trim();
+ if (!publishableKey) {
+ throw new Error(
+ "T3CODE_CLERK_PUBLISHABLE_KEY or T3CODE_CLERK_PASSKEY_RP_DOMAINS is required for signed macOS passkey builds.",
+ );
+ }
+ rpDomains = [
+ normalizePasskeyRpDomain(clerkFrontendApiHostnameFromPublishableKey(publishableKey)),
+ ];
+ }
+
+ const uniqueRpDomains = [...new Set(rpDomains)];
+ if (uniqueRpDomains.length === 0) {
+ throw new Error("At least one Clerk passkey RP domain is required.");
+ }
+
+ return {
+ appId: DESKTOP_APP_ID,
+ teamId,
+ rpDomains: uniqueRpDomains,
+ provisioningProfilePath,
+ };
+}
+
+function escapeXml(value: string): string {
+ return value
+ .replaceAll("&", "&amp;")
+ .replaceAll("<", "&lt;")
+ .replaceAll(">", "&gt;")
+ .replaceAll('"', "&quot;")
+ .replaceAll("'", "&apos;");
+}
+
+export function renderMacPasskeyEntitlements(
+ configuration: MacPasskeySigningConfiguration,
+): string {
+ const associatedDomains = configuration.rpDomains
+ .map((domain) => ` <string>webcredentials:${escapeXml(domain)}</string>`)
+ .join("\n");
+
+ return `<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
+<plist version="1.0">
+ <dict>
+ <key>com.apple.application-identifier</key>
+ <string>${escapeXml(`${configuration.teamId}.${configuration.appId}`)}</string>
+ <key>com.apple.developer.team-identifier</key>
+ <string>${escapeXml(configuration.teamId)}</string>
+ <key>com.apple.developer.associated-domains</key>
+ <array>
+${associatedDomains}
+ </array>
+ <key>com.apple.security.cs.allow-jit</key>
+ <true/>
+ <key>com.apple.security.cs.allow-unsigned-executable-memory</key>
+ <true/>
+ <key>com.apple.security.cs.disable-library-validation</key>
+ <true/>
+ </dict>
+</plist>
+`;
+}
+
export function resolveFffNativeDependencies(
platform: typeof BuildPlatform.Type,
arch: typeof BuildArch.Type,
@@ -319,6 +440,63 @@ export function resolveFffNativeDependencies(
);
}
+export interface ClerkPasskeyNativeArtifact {
+ readonly packageName: string;
+ readonly binaryFileName: string;
+}
+
+export function resolveClerkPasskeyNativeArtifacts(
+ platform: typeof BuildPlatform.Type,
+ arch: typeof BuildArch.Type,
+): readonly ClerkPasskeyNativeArtifact[] {
+ const architectures = arch === "universal" ? (["arm64", "x64"] as const) : [arch];
+
+ if (platform === "mac") {
+ return architectures.map((architecture) => ({
+ packageName: `@clerk/electron-passkeys-darwin-${architecture}`,
+ binaryFileName: `electron-passkeys.darwin-${architecture}.node`,
+ }));
+ }
+
+ if (platform === "win") {
+ return architectures.map((architecture) => ({
+ packageName: `@clerk/electron-passkeys-win32-${architecture}-msvc`,
+ binaryFileName: `electron-passkeys.win32-${architecture}-msvc.node`,
+ }));
+ }
+
+ return [];
+}
+
+// pnpm nests the architecture package under @clerk/electron-passkeys, while electron-builder only
+// retains collected top-level dependencies. The SDK loader checks beside index.js first, so stage
+// the binary there and let electron-builder's native-addon handling unpack it from the ASAR.
+const stageClerkPasskeyNativeBinaries = Effect.fn("stageClerkPasskeyNativeBinaries")(function* (
+ stageAppDir: string,
+ platform: typeof BuildPlatform.Type,
+ arch: typeof BuildArch.Type,
+) {
+ const fs = yield* FileSystem.FileSystem;
+ const path = yield* Path.Path;
+ const packageEntryPath = yield* fs.realPath(
+ path.join(stageAppDir, "node_modules", "@clerk", "electron-passkeys", "index.js"),
+ );
+ const packageDir = path.dirname(packageEntryPath);
+ const packageRequire = createRequire(packageEntryPath);
+
+ for (const artifact of resolveClerkPasskeyNativeArtifacts(platform, arch)) {
+ const sourcePath = yield* Effect.try({
+ try: () => packageRequire.resolve(artifact.packageName),
+ catch: (cause) =>
+ new BuildScriptError({
+ message: `Clerk passkey native package is missing: ${artifact.packageName}`,
+ cause,
+ }),
+ });
+ yield* fs.copyFile(sourcePath, path.join(packageDir, artifact.binaryFileName));
+ }
+});
+
export function createStageWorkspaceConfig(
platform: typeof BuildPlatform.Type,
arch: typeof BuildArch.Type,
@@ -739,16 +917,22 @@ export function resolveDesktopProductName(version: string): string {
: (desktopPackageJson.productName ?? "T3 Code");
}
-const createBuildConfig = Effect.fn("createBuildConfig")(function* (
+export const createBuildConfig = Effect.fn("createBuildConfig")(function* (
platform: typeof BuildPlatform.Type,
target: string,
version: string,
signed: boolean,
mockUpdates: boolean,
mockUpdateServerPort: number | undefined,
+ macPasskeySigning:
+ | {
+ readonly entitlementsPath: string;
+ readonly provisioningProfilePath: string;
+ }
+ | undefined,
) {
const buildConfig: Record<string, unknown> = {
- appId: "com.t3tools.t3code",
+ appId: DESKTOP_APP_ID,
productName: resolveDesktopProductName(version),
artifactName: "T3-Code-${version}-${arch}.${ext}",
asarUnpack: [...DESKTOP_ASAR_UNPACK],
@@ -777,9 +961,15 @@ const createBuildConfig = Effect.fn("createBuildConfig")(function* (
protocols: [
{
name: "T3 Code",
- schemes: ["t3code"],
+ schemes: ["t3code", "t3code-dev"],
},
],
+ ...(macPasskeySigning
+ ? {
+ entitlements: macPasskeySigning.entitlementsPath,
+ provisioningProfile: macPasskeySigning.provisioningProfilePath,
+ }
+ : {}),
};
}
@@ -956,6 +1146,38 @@ const buildDesktopArtifact = Effect.fn("buildDesktopArtifact")(function* (
// electron-builder is filtering out stageResourcesDir directory in the AppImage for production
yield* fs.copy(stageResourcesDir, path.join(stageAppDir, "apps/desktop/prod-resources"));
+ const configuredMacPasskeySigning =
+ options.platform === "mac" && options.signed
+ ? yield* Effect.try({
+ try: () => resolveMacPasskeySigningConfiguration(loadRepoEnv({ repoRoot })),
+ catch: (cause) =>
+ new BuildScriptError({
+ message: cause instanceof Error ? cause.message : String(cause),
+ cause,
+ }),
+ })
+ : undefined;
+ const macPasskeySigning = configuredMacPasskeySigning
+ ? {
+ ...configuredMacPasskeySigning,
+ provisioningProfilePath: path.resolve(
+ repoRoot,
+ configuredMacPasskeySigning.provisioningProfilePath,
+ ),
+ }
+ : undefined;
+ const macEntitlementsPath = macPasskeySigning
+ ? path.join(stageAppDir, "entitlements.mac.plist")
+ : undefined;
+ if (macPasskeySigning && macEntitlementsPath) {
+ if (!(yield* fs.exists(macPasskeySigning.provisioningProfilePath))) {
+ return yield* new BuildScriptError({
+ message: `macOS provisioning profile not found: ${macPasskeySigning.provisioningProfilePath}`,
+ });
+ }
+ yield* fs.writeFileString(macEntitlementsPath, renderMacPasskeyEntitlements(macPasskeySigning));
+ }
+
const stageDependencies = {
...resolvedServerDependencies,
...resolvedDesktopRuntimeDependencies,
@@ -983,6 +1205,12 @@ const buildDesktopArtifact = Effect.fn("buildDesktopArtifact")(function* (
options.signed,
options.mockUpdates,
options.mockUpdateServerPort,
+ macPasskeySigning && macEntitlementsPath
+ ? {
+ entitlementsPath: macEntitlementsPath,
+ provisioningProfilePath: macPasskeySigning.provisioningProfilePath,
+ }
+ : undefined,
),
dependencies: stageDependencies,
devDependencies: {
@@ -1014,6 +1242,7 @@ const buildDesktopArtifact = Effect.fn("buildDesktopArtifact")(function* (
}),
{ label: "vp install --prod", verbose: options.verbose },
);
+ yield* stageClerkPasskeyNativeBinaries(stageAppDir, options.platform, options.arch);
// electron-builder treats several set-but-empty variables (e.g. CSC_LINK="")
// as enabled, so copy the host env and scrub empty values instead of relying