Migrate desktop auth to Clerk bridge (#3092)
Co-authored-by: codex <[email protected]>
This commit is contained in:
1 parent
20f37f367a
commit
3e01c4bc57
67 files changed
+1988
-3320
No files matched your search
@@ -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
|
||||
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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"
|
||||
|
||||
@@ -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"),
|
||||
|
||||
@@ -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"));
|
||||
|
||||
@@ -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();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,92 @@
|
||||
import { createClerkBridge } from "@clerk/electron";
|
||||
import { storage } from "@clerk/electron/storage";
|
||||
import * as Context from "effect/Context";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Scope from "effect/Scope";
|
||||
|
||||
import { clerkFrontendApiHostnameFromPublishableKey } from "@t3tools/shared/relayAuth";
|
||||
import * as ElectronApp from "../electron/ElectronApp.ts";
|
||||
import * as ElectronProtocol from "../electron/ElectronProtocol.ts";
|
||||
import * as ElectronWindow from "../electron/ElectronWindow.ts";
|
||||
import * as DesktopEnvironment from "./DesktopEnvironment.ts";
|
||||
|
||||
declare const __T3CODE_BUILD_CLERK_PUBLISHABLE_KEY__: string | undefined;
|
||||
|
||||
export interface DesktopClerkShape {
|
||||
readonly configure: Effect.Effect<
|
||||
void,
|
||||
never,
|
||||
ElectronApp.ElectronApp | ElectronWindow.ElectronWindow | Scope.Scope
|
||||
>;
|
||||
}
|
||||
|
||||
export class DesktopClerk extends Context.Service<DesktopClerk, DesktopClerkShape>()(
|
||||
"@t3tools/desktop/app/DesktopClerk",
|
||||
) {}
|
||||
|
||||
export function resolveDesktopClerkFrontendApiHostname(
|
||||
publishableKey: string | undefined,
|
||||
): string | undefined {
|
||||
const normalizedKey = publishableKey?.trim();
|
||||
if (!normalizedKey) return undefined;
|
||||
|
||||
try {
|
||||
return clerkFrontendApiHostnameFromPublishableKey(normalizedKey);
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
export const desktopClerkFrontendApiHostname = resolveDesktopClerkFrontendApiHostname(
|
||||
typeof __T3CODE_BUILD_CLERK_PUBLISHABLE_KEY__ === "undefined"
|
||||
? undefined
|
||||
: __T3CODE_BUILD_CLERK_PUBLISHABLE_KEY__,
|
||||
);
|
||||
|
||||
export function createDesktopClerkBridge(stateDir: string, isDevelopment: boolean) {
|
||||
return createClerkBridge({
|
||||
storage: storage({ path: stateDir }),
|
||||
passkeys: true,
|
||||
renderer: {
|
||||
scheme: ElectronProtocol.getDesktopScheme(isDevelopment),
|
||||
host: ElectronProtocol.DESKTOP_HOST,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
const make = Effect.gen(function* () {
|
||||
const environment = yield* DesktopEnvironment.DesktopEnvironment;
|
||||
yield* Effect.acquireRelease(
|
||||
Effect.sync(() => createDesktopClerkBridge(environment.stateDir, environment.isDevelopment)),
|
||||
(bridge) => Effect.sync(() => bridge.cleanup()),
|
||||
);
|
||||
|
||||
return DesktopClerk.of({
|
||||
configure: Effect.gen(function* () {
|
||||
const electronApp = yield* ElectronApp.ElectronApp;
|
||||
const electronWindow = yield* ElectronWindow.ElectronWindow;
|
||||
const context = yield* Effect.context<ElectronWindow.ElectronWindow>();
|
||||
const runPromise = Effect.runPromiseWith(context);
|
||||
|
||||
if (!(yield* electronApp.requestSingleInstanceLock)) {
|
||||
yield* electronApp.quit;
|
||||
return yield* Effect.interrupt;
|
||||
}
|
||||
|
||||
yield* electronApp.on("second-instance", () => {
|
||||
void runPromise(
|
||||
Effect.gen(function* () {
|
||||
const mainWindow = yield* electronWindow.currentMainOrFirst;
|
||||
if (Option.isSome(mainWindow)) {
|
||||
yield* electronWindow.reveal(mainWindow.value);
|
||||
}
|
||||
}),
|
||||
);
|
||||
});
|
||||
}).pipe(Effect.withSpan("desktop.clerk.configure")),
|
||||
});
|
||||
});
|
||||
|
||||
export const layer = Layer.effect(DesktopClerk, make);
|
||||
@@ -1,302 +0,0 @@
|
||||
import { assert, describe, it } from "@effect/vitest";
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
|
||||
import * as ElectronApp from "../electron/ElectronApp.ts";
|
||||
import * as ElectronWindow from "../electron/ElectronWindow.ts";
|
||||
import * as IpcChannels from "../ipc/channels.ts";
|
||||
import * as DesktopCloudAuth from "./DesktopCloudAuth.ts";
|
||||
import * as DesktopEnvironment from "./DesktopEnvironment.ts";
|
||||
|
||||
interface CloudAuthHarness {
|
||||
readonly app: ElectronApp.ElectronAppShape;
|
||||
readonly window: ElectronWindow.ElectronWindowShape;
|
||||
readonly listeners: Map<string, readonly ((...args: readonly unknown[]) => void)[]>;
|
||||
readonly protocolRegistrations: {
|
||||
readonly protocol: string;
|
||||
readonly path?: string;
|
||||
readonly args?: readonly string[];
|
||||
}[];
|
||||
readonly sends: { readonly channel: string; readonly args: readonly unknown[] }[];
|
||||
readonly reveals: unknown[];
|
||||
readonly layer: Layer.Layer<
|
||||
| DesktopCloudAuth.DesktopCloudAuth
|
||||
| DesktopEnvironment.DesktopEnvironment
|
||||
| ElectronApp.ElectronApp
|
||||
| ElectronWindow.ElectronWindow
|
||||
>;
|
||||
}
|
||||
|
||||
function makeHarness(input: { readonly isDevelopment: boolean }): CloudAuthHarness {
|
||||
const listeners = new Map<string, ((...args: readonly unknown[]) => void)[]>();
|
||||
const protocolRegistrations: CloudAuthHarness["protocolRegistrations"] = [];
|
||||
const sends: CloudAuthHarness["sends"] = [];
|
||||
const reveals: unknown[] = [];
|
||||
const mainWindow = { id: "main-window" };
|
||||
|
||||
const app = ElectronApp.ElectronApp.of({
|
||||
metadata: Effect.succeed({
|
||||
appVersion: "0.0.0-test",
|
||||
appPath: "/tmp/t3-code-test",
|
||||
isPackaged: !input.isDevelopment,
|
||||
resourcesPath: "/tmp/t3-code-test/resources",
|
||||
runningUnderArm64Translation: false,
|
||||
}),
|
||||
name: Effect.succeed("T3 Code"),
|
||||
whenReady: Effect.void,
|
||||
quit: Effect.void,
|
||||
exit: () => Effect.void,
|
||||
relaunch: () => Effect.void,
|
||||
setPath: () => Effect.void,
|
||||
setName: () => Effect.void,
|
||||
setAboutPanelOptions: () => Effect.void,
|
||||
setAppUserModelId: () => Effect.void,
|
||||
requestSingleInstanceLock: Effect.succeed(true),
|
||||
isDefaultProtocolClient: () => Effect.succeed(false),
|
||||
setAsDefaultProtocolClient: (protocol, path, args) =>
|
||||
Effect.sync(() => {
|
||||
protocolRegistrations.push({
|
||||
protocol,
|
||||
...(path === undefined ? {} : { path }),
|
||||
...(args === undefined ? {} : { args }),
|
||||
});
|
||||
return true;
|
||||
}),
|
||||
setDesktopName: () => Effect.void,
|
||||
setDockIcon: () => Effect.void,
|
||||
appendCommandLineSwitch: () => Effect.void,
|
||||
on: (eventName, listener) =>
|
||||
Effect.sync(() => {
|
||||
const erasedListener = listener as (...args: readonly unknown[]) => void;
|
||||
listeners.set(eventName, [...(listeners.get(eventName) ?? []), erasedListener]);
|
||||
}),
|
||||
});
|
||||
|
||||
const window = ElectronWindow.ElectronWindow.of({
|
||||
create: () => Effect.die("not used"),
|
||||
main: Effect.succeed(Option.some(mainWindow as never)),
|
||||
currentMainOrFirst: Effect.succeed(Option.some(mainWindow as never)),
|
||||
focusedMainOrFirst: Effect.succeed(Option.some(mainWindow as never)),
|
||||
setMain: () => Effect.void,
|
||||
clearMain: () => Effect.void,
|
||||
reveal: (target) =>
|
||||
Effect.sync(() => {
|
||||
reveals.push(target);
|
||||
}),
|
||||
sendAll: (channel, ...args) =>
|
||||
Effect.sync(() => {
|
||||
sends.push({ channel, args });
|
||||
}),
|
||||
destroyAll: Effect.void,
|
||||
syncAllAppearance: () => Effect.void,
|
||||
});
|
||||
|
||||
const environment = DesktopEnvironment.DesktopEnvironment.of({
|
||||
isDevelopment: input.isDevelopment,
|
||||
} as DesktopEnvironment.DesktopEnvironmentShape);
|
||||
const environmentLayer = Layer.succeed(DesktopEnvironment.DesktopEnvironment, environment);
|
||||
|
||||
return {
|
||||
app,
|
||||
window,
|
||||
listeners,
|
||||
protocolRegistrations,
|
||||
sends,
|
||||
reveals,
|
||||
layer: Layer.mergeAll(
|
||||
DesktopCloudAuth.layer.pipe(
|
||||
Layer.provideMerge(environmentLayer),
|
||||
Layer.provide(NodeServices.layer),
|
||||
),
|
||||
Layer.succeed(ElectronApp.ElectronApp, app),
|
||||
Layer.succeed(ElectronWindow.ElectronWindow, window),
|
||||
),
|
||||
};
|
||||
}
|
||||
|
||||
function emitAppEvent(
|
||||
harness: CloudAuthHarness,
|
||||
eventName: string,
|
||||
...args: readonly unknown[]
|
||||
): void {
|
||||
for (const listener of harness.listeners.get(eventName) ?? []) {
|
||||
listener(...args);
|
||||
}
|
||||
}
|
||||
|
||||
const flushCloudAuthDispatch = Effect.promise(() => Promise.resolve());
|
||||
|
||||
describe("DesktopCloudAuth", () => {
|
||||
it("uses separate callback schemes for packaged and development builds", () => {
|
||||
assert.equal(
|
||||
DesktopCloudAuth.resolveCloudAuthCallbackScheme({ isDevelopment: false }),
|
||||
"t3code",
|
||||
);
|
||||
assert.equal(
|
||||
DesktopCloudAuth.resolveCloudAuthCallbackScheme({ isDevelopment: true }),
|
||||
"t3code-dev",
|
||||
);
|
||||
});
|
||||
|
||||
it("builds a native callback URL with request state", () => {
|
||||
assert.equal(
|
||||
DesktopCloudAuth.buildCloudAuthCallbackUrl({
|
||||
scheme: "t3code",
|
||||
state: "state-1",
|
||||
}),
|
||||
"t3code://auth/callback?t3_state=state-1",
|
||||
);
|
||||
});
|
||||
|
||||
it("accepts only the expected scheme, host, path, and state", () => {
|
||||
assert.isNotNull(
|
||||
DesktopCloudAuth.parseCloudAuthCallbackUrl({
|
||||
rawUrl: "t3code://auth/callback?rotating_token_nonce=nonce&t3_state=state-1",
|
||||
scheme: "t3code",
|
||||
state: "state-1",
|
||||
}),
|
||||
);
|
||||
assert.isNull(
|
||||
DesktopCloudAuth.parseCloudAuthCallbackUrl({
|
||||
rawUrl: "t3code://auth/callback?rotating_token_nonce=nonce&t3_state=wrong",
|
||||
scheme: "t3code",
|
||||
state: "state-1",
|
||||
}),
|
||||
);
|
||||
assert.isNull(
|
||||
DesktopCloudAuth.parseCloudAuthCallbackUrl({
|
||||
rawUrl: "https://example.com/callback?rotating_token_nonce=nonce&t3_state=state-1",
|
||||
scheme: "t3code",
|
||||
state: "state-1",
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it("builds a native development callback URL with request state", () => {
|
||||
assert.equal(
|
||||
DesktopCloudAuth.buildCloudAuthCallbackUrl({
|
||||
scheme: "t3code-dev",
|
||||
state: "state-1",
|
||||
}),
|
||||
"t3code-dev://auth/callback?t3_state=state-1",
|
||||
);
|
||||
});
|
||||
|
||||
it.effect("registers the development protocol client and dispatches matching callbacks", () => {
|
||||
const harness = makeHarness({ isDevelopment: true });
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const cloudAuth = yield* DesktopCloudAuth.DesktopCloudAuth;
|
||||
yield* cloudAuth.configure;
|
||||
const redirectUrl = yield* cloudAuth.createRequest;
|
||||
const callbackUrl = new URL(redirectUrl);
|
||||
callbackUrl.searchParams.set("rotating_token_nonce", "nonce-1");
|
||||
|
||||
let prevented = false;
|
||||
emitAppEvent(
|
||||
harness,
|
||||
"open-url",
|
||||
{ preventDefault: () => (prevented = true) },
|
||||
callbackUrl.toString(),
|
||||
);
|
||||
yield* flushCloudAuthDispatch;
|
||||
|
||||
assert.isTrue(prevented);
|
||||
assert.deepEqual(
|
||||
harness.protocolRegistrations.map((registration) => registration.protocol),
|
||||
["t3code-dev"],
|
||||
);
|
||||
assert.isString(harness.protocolRegistrations[0]?.path);
|
||||
assert.isArray(harness.protocolRegistrations[0]?.args);
|
||||
assert.deepEqual(harness.sends, [
|
||||
{
|
||||
channel: IpcChannels.CLOUD_AUTH_CALLBACK_CHANNEL,
|
||||
args: [callbackUrl.toString()],
|
||||
},
|
||||
]);
|
||||
assert.lengthOf(harness.reveals, 1);
|
||||
}).pipe(Effect.provide(harness.layer), Effect.scoped);
|
||||
});
|
||||
|
||||
it.effect("rejects mismatched callback state and only consumes the pending request once", () => {
|
||||
const harness = makeHarness({ isDevelopment: false });
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const cloudAuth = yield* DesktopCloudAuth.DesktopCloudAuth;
|
||||
yield* cloudAuth.configure;
|
||||
const redirectUrl = yield* cloudAuth.createRequest;
|
||||
const validCallback = new URL(redirectUrl);
|
||||
validCallback.searchParams.set("rotating_token_nonce", "nonce-1");
|
||||
const invalidCallback = new URL(validCallback);
|
||||
invalidCallback.searchParams.set(DesktopCloudAuth.CLOUD_AUTH_CALLBACK_STATE_PARAM, "wrong");
|
||||
|
||||
emitAppEvent(
|
||||
harness,
|
||||
"open-url",
|
||||
{ preventDefault: () => undefined },
|
||||
invalidCallback.toString(),
|
||||
);
|
||||
yield* flushCloudAuthDispatch;
|
||||
assert.deepEqual(harness.sends, []);
|
||||
|
||||
emitAppEvent(
|
||||
harness,
|
||||
"open-url",
|
||||
{ preventDefault: () => undefined },
|
||||
validCallback.toString(),
|
||||
);
|
||||
yield* flushCloudAuthDispatch;
|
||||
emitAppEvent(
|
||||
harness,
|
||||
"open-url",
|
||||
{ preventDefault: () => undefined },
|
||||
validCallback.toString(),
|
||||
);
|
||||
yield* flushCloudAuthDispatch;
|
||||
|
||||
assert.deepEqual(
|
||||
harness.protocolRegistrations.map((registration) => registration.protocol),
|
||||
["t3code"],
|
||||
);
|
||||
assert.deepEqual(harness.sends, [
|
||||
{
|
||||
channel: IpcChannels.CLOUD_AUTH_CALLBACK_CHANNEL,
|
||||
args: [validCallback.toString()],
|
||||
},
|
||||
]);
|
||||
}).pipe(Effect.provide(harness.layer), Effect.scoped);
|
||||
});
|
||||
|
||||
it.effect(
|
||||
"routes second-instance callbacks and reveals the window for non-callback launches",
|
||||
() => {
|
||||
const harness = makeHarness({ isDevelopment: true });
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const cloudAuth = yield* DesktopCloudAuth.DesktopCloudAuth;
|
||||
yield* cloudAuth.configure;
|
||||
const redirectUrl = yield* cloudAuth.createRequest;
|
||||
const callbackUrl = new URL(redirectUrl);
|
||||
callbackUrl.searchParams.set("rotating_token_nonce", "nonce-1");
|
||||
|
||||
emitAppEvent(harness, "second-instance", {}, ["electron", callbackUrl.toString()]);
|
||||
yield* flushCloudAuthDispatch;
|
||||
|
||||
const revealCountAfterCallback = harness.reveals.length;
|
||||
emitAppEvent(harness, "second-instance", {}, ["electron", "--opened-from-dock"]);
|
||||
yield* flushCloudAuthDispatch;
|
||||
|
||||
assert.deepEqual(harness.sends, [
|
||||
{
|
||||
channel: IpcChannels.CLOUD_AUTH_CALLBACK_CHANNEL,
|
||||
args: [callbackUrl.toString()],
|
||||
},
|
||||
]);
|
||||
assert.equal(revealCountAfterCallback, 1);
|
||||
assert.equal(harness.reveals.length, 2);
|
||||
}).pipe(Effect.provide(harness.layer), Effect.scoped);
|
||||
},
|
||||
);
|
||||
});
|
||||
@@ -1,330 +0,0 @@
|
||||
import * as Context from "effect/Context";
|
||||
import * as Crypto from "effect/Crypto";
|
||||
import * as Data from "effect/Data";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Scope from "effect/Scope";
|
||||
import { HttpRouter, HttpServerRequest, HttpServerResponse } from "effect/unstable/http";
|
||||
|
||||
import * as NodeHttpServer from "@effect/platform-node/NodeHttpServer";
|
||||
import * as ElectronApp from "../electron/ElectronApp.ts";
|
||||
import * as ElectronWindow from "../electron/ElectronWindow.ts";
|
||||
import * as IpcChannels from "../ipc/channels.ts";
|
||||
import * as DesktopEnvironment from "./DesktopEnvironment.ts";
|
||||
import type * as Electron from "electron";
|
||||
|
||||
export const CLOUD_AUTH_CALLBACK_HOST = "auth";
|
||||
export const CLOUD_AUTH_CALLBACK_PATHNAME = "/callback";
|
||||
export const CLOUD_AUTH_CALLBACK_STATE_PARAM = "t3_state";
|
||||
export const CLOUD_AUTH_CALLBACK_SCHEME = "t3code";
|
||||
export const DEVELOPMENT_CLOUD_AUTH_CALLBACK_SCHEME = "t3code-dev";
|
||||
|
||||
const CLOUD_AUTH_REQUEST_TIMEOUT_MS = 5 * 60 * 1000;
|
||||
|
||||
export class DesktopCloudAuthCallbackServerError extends Data.TaggedError(
|
||||
"DesktopCloudAuthCallbackServerError",
|
||||
)<{
|
||||
readonly cause: unknown;
|
||||
}> {
|
||||
override get message() {
|
||||
return "Failed to start the desktop cloud auth callback server.";
|
||||
}
|
||||
}
|
||||
|
||||
interface PendingCloudAuthRequest {
|
||||
readonly state: string;
|
||||
readonly redirectUrl: string;
|
||||
readonly close: () => void;
|
||||
}
|
||||
|
||||
export interface DesktopCloudAuthShape {
|
||||
readonly createRequest: Effect.Effect<string, DesktopCloudAuthCallbackServerError>;
|
||||
readonly configure: Effect.Effect<
|
||||
void,
|
||||
never,
|
||||
ElectronApp.ElectronApp | ElectronWindow.ElectronWindow | Scope.Scope
|
||||
>;
|
||||
}
|
||||
|
||||
export class DesktopCloudAuth extends Context.Service<DesktopCloudAuth, DesktopCloudAuthShape>()(
|
||||
"@t3tools/desktop/app/DesktopCloudAuth",
|
||||
) {}
|
||||
|
||||
export function resolveCloudAuthCallbackScheme(input: { readonly isDevelopment: boolean }): string {
|
||||
return input.isDevelopment ? DEVELOPMENT_CLOUD_AUTH_CALLBACK_SCHEME : CLOUD_AUTH_CALLBACK_SCHEME;
|
||||
}
|
||||
|
||||
export function buildCloudAuthCallbackUrl(input: {
|
||||
readonly scheme: string;
|
||||
readonly state: string;
|
||||
}): string {
|
||||
const url = new URL(
|
||||
`${input.scheme}://${CLOUD_AUTH_CALLBACK_HOST}${CLOUD_AUTH_CALLBACK_PATHNAME}`,
|
||||
);
|
||||
url.searchParams.set(CLOUD_AUTH_CALLBACK_STATE_PARAM, input.state);
|
||||
return url.toString();
|
||||
}
|
||||
|
||||
export function parseCloudAuthCallbackUrl(input: {
|
||||
readonly rawUrl: unknown;
|
||||
readonly scheme: string;
|
||||
readonly state: string;
|
||||
}): URL | null {
|
||||
if (typeof input.rawUrl !== "string") {
|
||||
return null;
|
||||
}
|
||||
|
||||
try {
|
||||
const url = new URL(input.rawUrl);
|
||||
if (url.protocol !== `${input.scheme}:`) return null;
|
||||
if (url.hostname !== CLOUD_AUTH_CALLBACK_HOST) return null;
|
||||
if (url.pathname !== CLOUD_AUTH_CALLBACK_PATHNAME) return null;
|
||||
if (url.searchParams.get(CLOUD_AUTH_CALLBACK_STATE_PARAM) !== input.state) return null;
|
||||
return url;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export function findCloudAuthCallbackUrl(input: {
|
||||
readonly values: readonly unknown[];
|
||||
readonly scheme: string;
|
||||
readonly state: string;
|
||||
}): URL | null {
|
||||
for (const value of input.values) {
|
||||
const url = parseCloudAuthCallbackUrl({
|
||||
rawUrl: value,
|
||||
scheme: input.scheme,
|
||||
state: input.state,
|
||||
});
|
||||
if (url) return url;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
export function resolveProtocolClientLaunchArgs(input: {
|
||||
readonly argv: readonly string[];
|
||||
}): readonly string[] {
|
||||
return input.argv.slice(1);
|
||||
}
|
||||
|
||||
function resolveConfiguredProtocolClient(): {
|
||||
readonly path: string;
|
||||
readonly args: readonly string[];
|
||||
} | null {
|
||||
const path = process.env.T3CODE_DESKTOP_PROTOCOL_CLIENT_PATH?.trim();
|
||||
if (!path) return null;
|
||||
|
||||
return {
|
||||
path,
|
||||
args: (process.env.T3CODE_DESKTOP_PROTOCOL_CLIENT_ARGS ?? "")
|
||||
.split("\n")
|
||||
.map((arg) => arg.trim())
|
||||
.filter((arg) => arg.length > 0),
|
||||
};
|
||||
}
|
||||
|
||||
function isProtocolRegistrationManagedExternally(): boolean {
|
||||
return process.env.T3CODE_DESKTOP_PROTOCOL_REGISTRATION_MANAGED?.trim() === "1";
|
||||
}
|
||||
|
||||
function resolveProtocolCallbackForwardUrl(): URL | null {
|
||||
const rawUrl = process.env.T3CODE_DESKTOP_PROTOCOL_CALLBACK_URL?.trim();
|
||||
if (!rawUrl) return null;
|
||||
|
||||
try {
|
||||
const url = new URL(rawUrl);
|
||||
if (url.protocol !== "http:") return null;
|
||||
if (url.hostname !== "127.0.0.1") return null;
|
||||
if (url.pathname !== "/auth/callback") return null;
|
||||
if (!url.port) return null;
|
||||
return url;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
const closeCloudAuthRequest = (request: PendingCloudAuthRequest | null): null => {
|
||||
request?.close();
|
||||
return null;
|
||||
};
|
||||
|
||||
function createCloudAuthRequestTimeout(onExpire: () => void): ReturnType<typeof setTimeout> {
|
||||
// @effect-diagnostics-next-line globalTimers:off - Auth request expiry is tied to an Electron callback server, not fiber scheduling.
|
||||
return setTimeout(onExpire, CLOUD_AUTH_REQUEST_TIMEOUT_MS);
|
||||
}
|
||||
|
||||
function ignoreCloudAuthCallback(_rawUrl: string) {}
|
||||
|
||||
function startProtocolCallbackForwardServer(
|
||||
callbackUrl: URL,
|
||||
dispatch: (rawUrl: string) => void,
|
||||
): Effect.Effect<void, never, Scope.Scope> {
|
||||
const port = Number.parseInt(callbackUrl.port, 10);
|
||||
const routesLayer = HttpRouter.add(
|
||||
"POST",
|
||||
"/auth/callback",
|
||||
Effect.gen(function* () {
|
||||
const request = yield* HttpServerRequest.HttpServerRequest;
|
||||
const rawUrl = yield* request.text;
|
||||
yield* Effect.sync(() => {
|
||||
dispatch(rawUrl);
|
||||
});
|
||||
return HttpServerResponse.empty({ status: 204 });
|
||||
}),
|
||||
);
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const NodeHttp = yield* Effect.promise(() => import("node:http"));
|
||||
const serverLayer = NodeHttpServer.layer(NodeHttp.createServer, {
|
||||
host: callbackUrl.hostname,
|
||||
port,
|
||||
});
|
||||
yield* Layer.launch(HttpRouter.serve(routesLayer).pipe(Layer.provideMerge(serverLayer))).pipe(
|
||||
Effect.forkScoped,
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
const make = Effect.gen(function* () {
|
||||
const crypto = yield* Crypto.Crypto;
|
||||
const environment = yield* DesktopEnvironment.DesktopEnvironment;
|
||||
let pendingAuthRequest: PendingCloudAuthRequest | null = null;
|
||||
let dispatchCloudAuthCallback: (rawUrl: string) => void = ignoreCloudAuthCallback;
|
||||
const makeCloudAuthRequestState = Effect.gen(function* () {
|
||||
const [left, right] = yield* Effect.all([crypto.randomUUIDv4, crypto.randomUUIDv4]);
|
||||
return `${left}${right}`.replaceAll("-", "");
|
||||
});
|
||||
|
||||
return DesktopCloudAuth.of({
|
||||
createRequest: Effect.gen(function* () {
|
||||
const scheme = resolveCloudAuthCallbackScheme({
|
||||
isDevelopment: environment.isDevelopment,
|
||||
});
|
||||
const state = yield* makeCloudAuthRequestState.pipe(
|
||||
Effect.mapError((cause) => new DesktopCloudAuthCallbackServerError({ cause })),
|
||||
);
|
||||
|
||||
pendingAuthRequest = closeCloudAuthRequest(pendingAuthRequest);
|
||||
|
||||
const redirectUrl = buildCloudAuthCallbackUrl({ scheme, state });
|
||||
const timeout = createCloudAuthRequestTimeout(() => {
|
||||
pendingAuthRequest = closeCloudAuthRequest(pendingAuthRequest);
|
||||
});
|
||||
pendingAuthRequest = {
|
||||
state,
|
||||
redirectUrl,
|
||||
close: () => clearTimeout(timeout),
|
||||
};
|
||||
return redirectUrl;
|
||||
}),
|
||||
configure: Effect.gen(function* () {
|
||||
const electronApp = yield* ElectronApp.ElectronApp;
|
||||
const electronWindow = yield* ElectronWindow.ElectronWindow;
|
||||
const scope = yield* Scope.Scope;
|
||||
const context = yield* Effect.context<ElectronWindow.ElectronWindow>();
|
||||
const runPromise = Effect.runPromiseWith(context);
|
||||
const scheme = resolveCloudAuthCallbackScheme({
|
||||
isDevelopment: environment.isDevelopment,
|
||||
});
|
||||
|
||||
yield* Scope.addFinalizer(
|
||||
scope,
|
||||
Effect.sync(() => {
|
||||
pendingAuthRequest = closeCloudAuthRequest(pendingAuthRequest);
|
||||
}),
|
||||
);
|
||||
|
||||
if (isProtocolRegistrationManagedExternally()) {
|
||||
// Development macOS launchers set the default URL handler before the stock Electron
|
||||
// process starts so LaunchServices binds the scheme to the worktree-specific app bundle.
|
||||
} else if (environment.isDevelopment) {
|
||||
const configuredClient = resolveConfiguredProtocolClient();
|
||||
if (configuredClient) {
|
||||
yield* electronApp.setAsDefaultProtocolClient(
|
||||
scheme,
|
||||
configuredClient.path,
|
||||
configuredClient.args,
|
||||
);
|
||||
} else {
|
||||
yield* electronApp.setAsDefaultProtocolClient(
|
||||
scheme,
|
||||
process.execPath,
|
||||
resolveProtocolClientLaunchArgs({ argv: process.argv }),
|
||||
);
|
||||
}
|
||||
} else {
|
||||
yield* electronApp.setAsDefaultProtocolClient(scheme);
|
||||
}
|
||||
|
||||
dispatchCloudAuthCallback = (rawUrl: string) => {
|
||||
const pending = pendingAuthRequest;
|
||||
const callbackUrl = pending
|
||||
? parseCloudAuthCallbackUrl({ rawUrl, scheme, state: pending.state })
|
||||
: null;
|
||||
if (!callbackUrl) {
|
||||
return;
|
||||
}
|
||||
|
||||
pendingAuthRequest = closeCloudAuthRequest(pendingAuthRequest);
|
||||
void runPromise(
|
||||
Effect.gen(function* () {
|
||||
yield* electronWindow.sendAll(
|
||||
IpcChannels.CLOUD_AUTH_CALLBACK_CHANNEL,
|
||||
callbackUrl.toString(),
|
||||
);
|
||||
const mainWindow = yield* electronWindow.currentMainOrFirst;
|
||||
if (Option.isSome(mainWindow)) {
|
||||
yield* electronWindow.reveal(mainWindow.value);
|
||||
}
|
||||
}),
|
||||
);
|
||||
};
|
||||
|
||||
const protocolCallbackForwardUrl = resolveProtocolCallbackForwardUrl();
|
||||
if (environment.isDevelopment && protocolCallbackForwardUrl) {
|
||||
yield* startProtocolCallbackForwardServer(
|
||||
protocolCallbackForwardUrl,
|
||||
dispatchCloudAuthCallback,
|
||||
);
|
||||
}
|
||||
|
||||
const hasInstanceLock = yield* electronApp.requestSingleInstanceLock;
|
||||
if (!hasInstanceLock) {
|
||||
return yield* electronApp.quit;
|
||||
}
|
||||
|
||||
yield* electronApp.on<[Electron.Event, string]>("open-url", (event, rawUrl) => {
|
||||
event.preventDefault?.();
|
||||
dispatchCloudAuthCallback(rawUrl);
|
||||
});
|
||||
|
||||
yield* electronApp.on<[Electron.Event, readonly string[]]>(
|
||||
"second-instance",
|
||||
(_event, argv) => {
|
||||
const values = resolveProtocolClientLaunchArgs({ argv });
|
||||
const pending = pendingAuthRequest;
|
||||
const callbackUrl = pending
|
||||
? findCloudAuthCallbackUrl({ values, scheme, state: pending.state })
|
||||
: null;
|
||||
if (callbackUrl) {
|
||||
dispatchCloudAuthCallback(callbackUrl.toString());
|
||||
return;
|
||||
}
|
||||
|
||||
void runPromise(
|
||||
Effect.gen(function* () {
|
||||
const mainWindow = yield* electronWindow.currentMainOrFirst;
|
||||
if (Option.isSome(mainWindow)) {
|
||||
yield* electronWindow.reveal(mainWindow.value);
|
||||
}
|
||||
}),
|
||||
);
|
||||
},
|
||||
);
|
||||
}).pipe(Effect.withSpan("desktop.cloudAuth.configure")),
|
||||
});
|
||||
});
|
||||
|
||||
export const layer = Layer.effect(DesktopCloudAuth, make);
|
||||
@@ -1,96 +0,0 @@
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { assert, describe, it } from "@effect/vitest";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
|
||||
import * as ElectronSafeStorage from "../electron/ElectronSafeStorage.ts";
|
||||
import * as DesktopConfig from "./DesktopConfig.ts";
|
||||
import * as DesktopEnvironment from "./DesktopEnvironment.ts";
|
||||
import * as DesktopCloudAuthTokenStore from "./DesktopCloudAuthTokenStore.ts";
|
||||
|
||||
const textDecoder = new TextDecoder();
|
||||
const textEncoder = new TextEncoder();
|
||||
|
||||
function makeSafeStorageLayer(input: { readonly available: boolean }) {
|
||||
return Layer.succeed(ElectronSafeStorage.ElectronSafeStorage, {
|
||||
isEncryptionAvailable: Effect.succeed(input.available),
|
||||
encryptString: (value) => Effect.succeed(textEncoder.encode(`enc:${value}`)),
|
||||
decryptString: (value) => {
|
||||
const decoded = textDecoder.decode(value);
|
||||
if (!decoded.startsWith("enc:")) {
|
||||
return Effect.fail(
|
||||
new ElectronSafeStorage.ElectronSafeStorageDecryptError({
|
||||
cause: new Error("invalid encrypted token"),
|
||||
}),
|
||||
);
|
||||
}
|
||||
return Effect.succeed(decoded.slice("enc:".length));
|
||||
},
|
||||
} satisfies ElectronSafeStorage.ElectronSafeStorageShape);
|
||||
}
|
||||
|
||||
function makeLayer(baseDir: string, input?: { readonly encryptionAvailable?: boolean }) {
|
||||
const environmentLayer = DesktopEnvironment.layer({
|
||||
dirname: "/repo/apps/desktop/src",
|
||||
homeDirectory: baseDir,
|
||||
platform: "darwin",
|
||||
processArch: "x64",
|
||||
appVersion: "1.2.3",
|
||||
appPath: "/repo",
|
||||
isPackaged: true,
|
||||
resourcesPath: "/missing/resources",
|
||||
runningUnderArm64Translation: false,
|
||||
}).pipe(
|
||||
Layer.provide(
|
||||
Layer.mergeAll(NodeServices.layer, DesktopConfig.layerTest({ T3CODE_HOME: baseDir })),
|
||||
),
|
||||
);
|
||||
|
||||
return DesktopCloudAuthTokenStore.layer.pipe(
|
||||
Layer.provideMerge(environmentLayer),
|
||||
Layer.provideMerge(makeSafeStorageLayer({ available: input?.encryptionAvailable ?? true })),
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
);
|
||||
}
|
||||
|
||||
const withTokenStore = <A, E, R>(
|
||||
effect: Effect.Effect<A, E, R | DesktopCloudAuthTokenStore.DesktopCloudAuthTokenStore>,
|
||||
input?: { readonly encryptionAvailable?: boolean },
|
||||
) =>
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const baseDir = yield* fileSystem.makeTempDirectoryScoped({
|
||||
prefix: "t3-desktop-cloud-auth-token-test-",
|
||||
});
|
||||
return yield* effect.pipe(Effect.provide(makeLayer(baseDir, input)));
|
||||
}).pipe(Effect.provide(NodeServices.layer), Effect.scoped);
|
||||
|
||||
describe("DesktopCloudAuthTokenStore", () => {
|
||||
it.effect("persists, reads, and clears the encrypted Clerk client JWT", () =>
|
||||
withTokenStore(
|
||||
Effect.gen(function* () {
|
||||
const tokenStore = yield* DesktopCloudAuthTokenStore.DesktopCloudAuthTokenStore;
|
||||
|
||||
assert.isTrue(yield* tokenStore.set("__client=test.jwt"));
|
||||
assert.deepStrictEqual(yield* tokenStore.get, Option.some("__client=test.jwt"));
|
||||
|
||||
yield* tokenStore.clear;
|
||||
assert.deepStrictEqual(yield* tokenStore.get, Option.none());
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("does not persist a token when Electron safe storage is unavailable", () =>
|
||||
withTokenStore(
|
||||
Effect.gen(function* () {
|
||||
const tokenStore = yield* DesktopCloudAuthTokenStore.DesktopCloudAuthTokenStore;
|
||||
|
||||
assert.isFalse(yield* tokenStore.set("__client=test.jwt"));
|
||||
assert.deepStrictEqual(yield* tokenStore.get, Option.none());
|
||||
}),
|
||||
{ encryptionAvailable: false },
|
||||
),
|
||||
);
|
||||
});
|
||||
@@ -1,155 +0,0 @@
|
||||
import { fromLenientJson } from "@t3tools/shared/schemaJson";
|
||||
import * as Context from "effect/Context";
|
||||
import * as Crypto from "effect/Crypto";
|
||||
import * as Data from "effect/Data";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Encoding from "effect/Encoding";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Path from "effect/Path";
|
||||
import * as PlatformError from "effect/PlatformError";
|
||||
import * as Schema from "effect/Schema";
|
||||
|
||||
import * as ElectronSafeStorage from "../electron/ElectronSafeStorage.ts";
|
||||
import * as DesktopEnvironment from "./DesktopEnvironment.ts";
|
||||
|
||||
interface CloudAuthTokenDocument {
|
||||
readonly version: number;
|
||||
readonly encryptedClientJwt: string;
|
||||
}
|
||||
|
||||
const CloudAuthTokenDocumentSchema = Schema.Struct({
|
||||
version: Schema.Number,
|
||||
encryptedClientJwt: Schema.String,
|
||||
});
|
||||
|
||||
const CloudAuthTokenDocumentJson = fromLenientJson(CloudAuthTokenDocumentSchema);
|
||||
const decodeCloudAuthTokenDocumentJson = Schema.decodeEffect(CloudAuthTokenDocumentJson);
|
||||
const encodeCloudAuthTokenDocumentJson = Schema.encodeEffect(CloudAuthTokenDocumentJson);
|
||||
|
||||
export class DesktopCloudAuthTokenStoreWriteError extends Data.TaggedError(
|
||||
"DesktopCloudAuthTokenStoreWriteError",
|
||||
)<{
|
||||
readonly cause: PlatformError.PlatformError | Schema.SchemaError;
|
||||
}> {
|
||||
override get message() {
|
||||
return `Failed to write desktop cloud auth token: ${this.cause.message}`;
|
||||
}
|
||||
}
|
||||
|
||||
export class DesktopCloudAuthTokenStoreDecodeError extends Data.TaggedError(
|
||||
"DesktopCloudAuthTokenStoreDecodeError",
|
||||
)<{
|
||||
readonly cause: Encoding.EncodingError;
|
||||
}> {
|
||||
override get message() {
|
||||
return "Failed to decode desktop cloud auth token.";
|
||||
}
|
||||
}
|
||||
|
||||
export interface DesktopCloudAuthTokenStoreShape {
|
||||
readonly get: Effect.Effect<
|
||||
Option.Option<string>,
|
||||
| DesktopCloudAuthTokenStoreDecodeError
|
||||
| ElectronSafeStorage.ElectronSafeStorageAvailabilityError
|
||||
| ElectronSafeStorage.ElectronSafeStorageDecryptError
|
||||
>;
|
||||
readonly set: (
|
||||
token: string,
|
||||
) => Effect.Effect<
|
||||
boolean,
|
||||
| DesktopCloudAuthTokenStoreWriteError
|
||||
| ElectronSafeStorage.ElectronSafeStorageAvailabilityError
|
||||
| ElectronSafeStorage.ElectronSafeStorageEncryptError
|
||||
>;
|
||||
readonly clear: Effect.Effect<void>;
|
||||
}
|
||||
|
||||
export class DesktopCloudAuthTokenStore extends Context.Service<
|
||||
DesktopCloudAuthTokenStore,
|
||||
DesktopCloudAuthTokenStoreShape
|
||||
>()("@t3tools/desktop/app/DesktopCloudAuthTokenStore") {}
|
||||
|
||||
function decodeSecretBytes(
|
||||
encoded: string,
|
||||
): Effect.Effect<Uint8Array, DesktopCloudAuthTokenStoreDecodeError> {
|
||||
return Effect.fromResult(Encoding.decodeBase64(encoded)).pipe(
|
||||
Effect.mapError((cause) => new DesktopCloudAuthTokenStoreDecodeError({ cause })),
|
||||
);
|
||||
}
|
||||
|
||||
const readDocument = (
|
||||
fileSystem: FileSystem.FileSystem,
|
||||
tokenPath: string,
|
||||
): Effect.Effect<Option.Option<CloudAuthTokenDocument>> =>
|
||||
fileSystem.readFileString(tokenPath).pipe(
|
||||
Effect.option,
|
||||
Effect.flatMap(
|
||||
Option.match({
|
||||
onNone: () => Effect.succeed(Option.none<CloudAuthTokenDocument>()),
|
||||
onSome: (raw) => decodeCloudAuthTokenDocumentJson(raw).pipe(Effect.option),
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
const writeDocument = Effect.fn("desktop.cloudAuthTokenStore.writeDocument")(function* (input: {
|
||||
readonly fileSystem: FileSystem.FileSystem;
|
||||
readonly path: Path.Path;
|
||||
readonly tokenPath: string;
|
||||
readonly document: CloudAuthTokenDocument;
|
||||
readonly suffix: string;
|
||||
}): Effect.fn.Return<void, PlatformError.PlatformError | Schema.SchemaError> {
|
||||
const directory = input.path.dirname(input.tokenPath);
|
||||
const tempPath = `${input.tokenPath}.${process.pid}.${input.suffix}.tmp`;
|
||||
const encoded = yield* encodeCloudAuthTokenDocumentJson(input.document);
|
||||
yield* input.fileSystem.makeDirectory(directory, { recursive: true });
|
||||
yield* input.fileSystem.writeFileString(tempPath, `${encoded}\n`);
|
||||
yield* input.fileSystem.rename(tempPath, input.tokenPath);
|
||||
});
|
||||
|
||||
export const layer = Layer.effect(
|
||||
DesktopCloudAuthTokenStore,
|
||||
Effect.gen(function* () {
|
||||
const environment = yield* DesktopEnvironment.DesktopEnvironment;
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const safeStorage = yield* ElectronSafeStorage.ElectronSafeStorage;
|
||||
const crypto = yield* Crypto.Crypto;
|
||||
const tokenPath = path.join(environment.stateDir, "cloud-auth-token.json");
|
||||
|
||||
return DesktopCloudAuthTokenStore.of({
|
||||
get: Effect.gen(function* () {
|
||||
const document = yield* readDocument(fileSystem, tokenPath);
|
||||
if (Option.isNone(document) || !(yield* safeStorage.isEncryptionAvailable)) {
|
||||
return Option.none<string>();
|
||||
}
|
||||
|
||||
const secretBytes = yield* decodeSecretBytes(document.value.encryptedClientJwt);
|
||||
return Option.some(yield* safeStorage.decryptString(secretBytes));
|
||||
}).pipe(Effect.withSpan("desktop.cloudAuthTokenStore.get")),
|
||||
set: Effect.fn("desktop.cloudAuthTokenStore.set")(function* (token) {
|
||||
if (!(yield* safeStorage.isEncryptionAvailable)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const encryptedClientJwt = Encoding.encodeBase64(yield* safeStorage.encryptString(token));
|
||||
const suffix = (yield* crypto.randomUUIDv4.pipe(
|
||||
Effect.mapError((cause) => new DesktopCloudAuthTokenStoreWriteError({ cause })),
|
||||
)).replace(/-/g, "");
|
||||
yield* writeDocument({
|
||||
fileSystem,
|
||||
path,
|
||||
tokenPath,
|
||||
document: { version: 1, encryptedClientJwt },
|
||||
suffix,
|
||||
}).pipe(Effect.mapError((cause) => new DesktopCloudAuthTokenStoreWriteError({ cause })));
|
||||
return true;
|
||||
}),
|
||||
clear: fileSystem.remove(tokenPath, { force: true }).pipe(
|
||||
Effect.catch(() => Effect.void),
|
||||
Effect.withSpan("desktop.cloudAuthTokenStore.clear"),
|
||||
),
|
||||
});
|
||||
}),
|
||||
);
|
||||
@@ -0,0 +1,82 @@
|
||||
import { assert, describe, it } from "@effect/vitest";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Ref from "effect/Ref";
|
||||
import { HttpClient, HttpClientResponse } from "effect/unstable/http";
|
||||
|
||||
import * as DesktopBackendManager from "./DesktopBackendManager.ts";
|
||||
import * as DesktopLocalEnvironmentAuth from "./DesktopLocalEnvironmentAuth.ts";
|
||||
|
||||
const config: DesktopBackendManager.DesktopBackendStartConfig = {
|
||||
executablePath: "/electron",
|
||||
entryPath: "/server/bin.mjs",
|
||||
cwd: "/server",
|
||||
env: {},
|
||||
bootstrap: {
|
||||
mode: "desktop",
|
||||
noBrowser: true,
|
||||
port: 3773,
|
||||
t3Home: "/tmp/t3",
|
||||
host: "127.0.0.1",
|
||||
desktopBootstrapToken: "desktop-bootstrap-token",
|
||||
tailscaleServeEnabled: false,
|
||||
tailscaleServePort: 443,
|
||||
},
|
||||
httpBaseUrl: new URL("http://127.0.0.1:3773"),
|
||||
captureOutput: true,
|
||||
};
|
||||
|
||||
describe("DesktopLocalEnvironmentAuth", () => {
|
||||
it.effect("exchanges the desktop bootstrap credential only once", () =>
|
||||
Effect.gen(function* () {
|
||||
const requestCount = yield* Ref.make(0);
|
||||
const httpClientLayer = Layer.succeed(
|
||||
HttpClient.HttpClient,
|
||||
HttpClient.make((request) =>
|
||||
Ref.update(requestCount, (count) => count + 1).pipe(
|
||||
Effect.as(
|
||||
HttpClientResponse.fromWeb(
|
||||
request,
|
||||
new Response(
|
||||
JSON.stringify({
|
||||
access_token: "desktop-bearer-token",
|
||||
issued_token_type: "urn:ietf:params:oauth:token-type:access_token",
|
||||
token_type: "Bearer",
|
||||
expires_in: 3600,
|
||||
scope: "orchestration:read",
|
||||
}),
|
||||
{ status: 200, headers: { "content-type": "application/json" } },
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
const managerLayer = Layer.succeed(DesktopBackendManager.DesktopBackendManager, {
|
||||
start: Effect.void,
|
||||
stop: () => Effect.void,
|
||||
currentConfig: Effect.succeed(Option.some(config)),
|
||||
snapshot: Effect.succeed({
|
||||
desiredRunning: true,
|
||||
ready: true,
|
||||
activePid: Option.none(),
|
||||
restartAttempt: 0,
|
||||
restartScheduled: false,
|
||||
}),
|
||||
});
|
||||
const testLayer = DesktopLocalEnvironmentAuth.layer.pipe(
|
||||
Layer.provide(Layer.mergeAll(managerLayer, httpClientLayer)),
|
||||
);
|
||||
|
||||
const [first, second] = yield* Effect.gen(function* () {
|
||||
const auth = yield* DesktopLocalEnvironmentAuth.DesktopLocalEnvironmentAuth;
|
||||
return yield* Effect.all([auth.getBearerToken, auth.getBearerToken]);
|
||||
}).pipe(Effect.provide(testLayer));
|
||||
|
||||
assert.strictEqual(first, "desktop-bearer-token");
|
||||
assert.strictEqual(second, "desktop-bearer-token");
|
||||
assert.strictEqual(yield* Ref.get(requestCount), 1);
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,77 @@
|
||||
import { bootstrapRemoteBearerSession } from "@t3tools/client-runtime/authorization";
|
||||
import * as Context from "effect/Context";
|
||||
import * as Data from "effect/Data";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Ref from "effect/Ref";
|
||||
import * as Semaphore from "effect/Semaphore";
|
||||
import { HttpClient } from "effect/unstable/http";
|
||||
|
||||
import * as DesktopBackendManager from "./DesktopBackendManager.ts";
|
||||
|
||||
export interface DesktopLocalEnvironmentAuthShape {
|
||||
readonly getBearerToken: Effect.Effect<string, DesktopLocalEnvironmentAuthError>;
|
||||
}
|
||||
|
||||
export class DesktopLocalEnvironmentAuthError extends Data.TaggedError(
|
||||
"DesktopLocalEnvironmentAuthError",
|
||||
)<{
|
||||
readonly message: string;
|
||||
readonly cause?: unknown;
|
||||
}> {}
|
||||
|
||||
export class DesktopLocalEnvironmentAuth extends Context.Service<
|
||||
DesktopLocalEnvironmentAuth,
|
||||
DesktopLocalEnvironmentAuthShape
|
||||
>()("@t3tools/desktop/backend/DesktopLocalEnvironmentAuth") {}
|
||||
|
||||
export const layer = Layer.effect(
|
||||
DesktopLocalEnvironmentAuth,
|
||||
Effect.gen(function* () {
|
||||
const backendManager = yield* DesktopBackendManager.DesktopBackendManager;
|
||||
const httpClient = yield* HttpClient.HttpClient;
|
||||
const tokenRef = yield* Ref.make(Option.none<string>());
|
||||
const mutex = yield* Semaphore.make(1);
|
||||
|
||||
const getBearerToken = mutex
|
||||
.withPermits(1)(
|
||||
Effect.gen(function* () {
|
||||
const cached = yield* Ref.get(tokenRef);
|
||||
if (Option.isSome(cached)) {
|
||||
return cached.value;
|
||||
}
|
||||
|
||||
const configOption = yield* backendManager.currentConfig;
|
||||
if (Option.isNone(configOption)) {
|
||||
return yield* new DesktopLocalEnvironmentAuthError({
|
||||
message: "Local backend is not configured.",
|
||||
});
|
||||
}
|
||||
const config = configOption.value;
|
||||
const session = yield* bootstrapRemoteBearerSession({
|
||||
httpBaseUrl: config.httpBaseUrl.href,
|
||||
credential: config.bootstrap.desktopBootstrapToken,
|
||||
clientMetadata: {
|
||||
label: "T3 Code Desktop",
|
||||
deviceType: "desktop",
|
||||
},
|
||||
}).pipe(
|
||||
Effect.provideService(HttpClient.HttpClient, httpClient),
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new DesktopLocalEnvironmentAuthError({
|
||||
message: "Failed to create the local desktop bearer session.",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
yield* Ref.set(tokenRef, Option.some(session.access_token));
|
||||
return session.access_token;
|
||||
}),
|
||||
)
|
||||
.pipe(Effect.withSpan("desktop.localEnvironmentAuth.getBearerToken"));
|
||||
|
||||
return DesktopLocalEnvironmentAuth.of({ getBearerToken });
|
||||
}),
|
||||
);
|
||||
@@ -1,105 +1,132 @@
|
||||
import { assert, describe, it } from "@effect/vitest";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import type * as Electron from "electron";
|
||||
import { beforeEach, vi } from "vite-plus/test";
|
||||
|
||||
const { registerFileProtocolMock, registerSchemesAsPrivilegedMock, unregisterProtocolMock } =
|
||||
vi.hoisted(() => ({
|
||||
registerFileProtocolMock: vi.fn(),
|
||||
registerSchemesAsPrivilegedMock: vi.fn(),
|
||||
unregisterProtocolMock: vi.fn(),
|
||||
}));
|
||||
const { handleMock, netFetchMock, unhandleMock } = vi.hoisted(() => ({
|
||||
handleMock: vi.fn(),
|
||||
netFetchMock: vi.fn(),
|
||||
unhandleMock: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("electron", () => ({
|
||||
protocol: {
|
||||
registerFileProtocol: registerFileProtocolMock,
|
||||
registerSchemesAsPrivileged: registerSchemesAsPrivilegedMock,
|
||||
unregisterProtocol: unregisterProtocolMock,
|
||||
},
|
||||
net: { fetch: netFetchMock },
|
||||
protocol: { handle: handleMock, unhandle: unhandleMock },
|
||||
}));
|
||||
|
||||
import * as ElectronProtocol from "./ElectronProtocol.ts";
|
||||
|
||||
describe("ElectronProtocol", () => {
|
||||
beforeEach(() => {
|
||||
registerFileProtocolMock.mockReset();
|
||||
registerSchemesAsPrivilegedMock.mockReset();
|
||||
unregisterProtocolMock.mockReset();
|
||||
handleMock.mockReset();
|
||||
netFetchMock.mockReset();
|
||||
unhandleMock.mockReset();
|
||||
});
|
||||
|
||||
it("normalizes safe desktop protocol pathnames", () => {
|
||||
assert.equal(
|
||||
Option.getOrNull(ElectronProtocol.normalizeDesktopProtocolPathname("/settings/./general")),
|
||||
"settings/general",
|
||||
);
|
||||
assert.isTrue(Option.isNone(ElectronProtocol.normalizeDesktopProtocolPathname("/../secret")));
|
||||
});
|
||||
it.effect("proxies the stable renderer origin to the current app server", () =>
|
||||
Effect.gen(function* () {
|
||||
let handler: ((request: Request) => Promise<Response>) | undefined;
|
||||
handleMock.mockImplementation((_scheme, nextHandler) => {
|
||||
handler = nextHandler;
|
||||
});
|
||||
netFetchMock.mockResolvedValue(new Response("ok"));
|
||||
|
||||
it.effect("registers desktop scheme privileges through a layer", () =>
|
||||
Effect.scoped(
|
||||
Layer.build(ElectronProtocol.layerSchemePrivileges).pipe(
|
||||
Effect.andThen(
|
||||
Effect.sync(() => {
|
||||
assert.deepEqual(registerSchemesAsPrivilegedMock.mock.calls, [
|
||||
[
|
||||
[
|
||||
{
|
||||
scheme: "t3",
|
||||
privileges: {
|
||||
standard: true,
|
||||
secure: true,
|
||||
supportFetchAPI: true,
|
||||
corsEnabled: true,
|
||||
},
|
||||
},
|
||||
],
|
||||
],
|
||||
]);
|
||||
}),
|
||||
),
|
||||
),
|
||||
),
|
||||
yield* Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const protocol = yield* ElectronProtocol.ElectronProtocol;
|
||||
yield* protocol.registerDesktopProtocol({
|
||||
scheme: "t3code-dev",
|
||||
targetOrigin: new URL("http://127.0.0.1:3773/"),
|
||||
backendOrigin: new URL("http://127.0.0.1:3774/"),
|
||||
clerkFrontendApiHostname: "clerk.t3.codes",
|
||||
});
|
||||
assert.isDefined(handler);
|
||||
|
||||
const response = yield* Effect.promise(() =>
|
||||
handler!(new Request("t3code-dev://app/api/health?verbose=1")),
|
||||
);
|
||||
assert.equal(yield* Effect.promise(() => response.text()), "ok");
|
||||
assert.include(
|
||||
response.headers.get("content-security-policy") ?? "",
|
||||
"script-src 'self' 'unsafe-inline' https://clerk.t3.codes https://challenges.cloudflare.com",
|
||||
);
|
||||
assert.include(
|
||||
response.headers.get("content-security-policy") ?? "",
|
||||
"connect-src 'self' http: https: ws: wss:",
|
||||
);
|
||||
assert.include(
|
||||
response.headers.get("content-security-policy") ?? "",
|
||||
"img-src 'self' t3code-dev: blob: data: http: https:",
|
||||
);
|
||||
assert.include(
|
||||
response.headers.get("content-security-policy") ?? "",
|
||||
"font-src 'self' t3code-dev: data:",
|
||||
);
|
||||
}),
|
||||
);
|
||||
|
||||
assert.deepEqual(
|
||||
handleMock.mock.calls.map((call) => call[0]),
|
||||
["t3code-dev"],
|
||||
);
|
||||
assert.equal(netFetchMock.mock.calls[0]?.[0], "http://127.0.0.1:3773/api/health?verbose=1");
|
||||
assert.deepEqual(unhandleMock.mock.calls, [["t3code-dev"]]);
|
||||
}).pipe(Effect.provide(ElectronProtocol.layer)),
|
||||
);
|
||||
|
||||
it.effect("scopes registered file protocols", () =>
|
||||
it.effect("rejects custom protocol requests for another host", () =>
|
||||
Effect.gen(function* () {
|
||||
let capturedHandler:
|
||||
| ((
|
||||
request: Electron.ProtocolRequest,
|
||||
callback: (response: Electron.ProtocolResponse) => void,
|
||||
) => void)
|
||||
| undefined;
|
||||
|
||||
registerFileProtocolMock.mockImplementation((_scheme, handler) => {
|
||||
capturedHandler = handler;
|
||||
return true;
|
||||
let handler: ((request: Request) => Promise<Response>) | undefined;
|
||||
handleMock.mockImplementation((_scheme, nextHandler) => {
|
||||
handler = nextHandler;
|
||||
});
|
||||
|
||||
const response = yield* Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const electronProtocol = yield* ElectronProtocol.ElectronProtocol;
|
||||
yield* electronProtocol.registerFileProtocol({
|
||||
scheme: "t3",
|
||||
handler: () => Effect.succeed({ path: "/app/index.html" }),
|
||||
});
|
||||
|
||||
assert.isDefined(capturedHandler);
|
||||
return yield* Effect.callback<Electron.ProtocolResponse>((resume) => {
|
||||
capturedHandler?.({ url: "t3://app/" } as Electron.ProtocolRequest, (response) =>
|
||||
resume(Effect.succeed(response)),
|
||||
);
|
||||
const protocol = yield* ElectronProtocol.ElectronProtocol;
|
||||
yield* protocol.registerDesktopProtocol({
|
||||
scheme: "t3code",
|
||||
targetOrigin: new URL("http://127.0.0.1:3773/"),
|
||||
backendOrigin: new URL("http://127.0.0.1:3773/"),
|
||||
clerkFrontendApiHostname: undefined,
|
||||
});
|
||||
return yield* Effect.promise(() => handler!(new Request("t3code://other/")));
|
||||
}),
|
||||
);
|
||||
|
||||
assert.deepEqual(response, { path: "/app/index.html" });
|
||||
assert.deepEqual(
|
||||
registerFileProtocolMock.mock.calls.map((call) => call[0]),
|
||||
["t3"],
|
||||
);
|
||||
assert.deepEqual(unregisterProtocolMock.mock.calls, [["t3"]]);
|
||||
assert.equal(response.status, 404);
|
||||
assert.equal(netFetchMock.mock.calls.length, 0);
|
||||
}).pipe(Effect.provide(ElectronProtocol.layer)),
|
||||
);
|
||||
|
||||
it("keeps executable sources host-restricted while allowing runtime network resources", () => {
|
||||
const policy = ElectronProtocol.makeDesktopContentSecurityPolicy({
|
||||
scheme: "t3code",
|
||||
targetOrigin: new URL("http://127.0.0.1:3773/"),
|
||||
backendOrigin: new URL("http://127.0.0.1:3773/"),
|
||||
clerkFrontendApiHostname: "clerk.t3.codes",
|
||||
});
|
||||
const directives = Object.fromEntries(
|
||||
policy.split("; ").map((directive) => {
|
||||
const [name, ...sources] = directive.split(" ");
|
||||
return [name, sources];
|
||||
}),
|
||||
);
|
||||
|
||||
assert.deepEqual(directives["script-src"], [
|
||||
"'self'",
|
||||
"'unsafe-inline'",
|
||||
"https://clerk.t3.codes",
|
||||
"https://challenges.cloudflare.com",
|
||||
]);
|
||||
assert.deepEqual(directives["connect-src"], ["'self'", "http:", "https:", "ws:", "wss:"]);
|
||||
assert.deepEqual(directives["img-src"], [
|
||||
"'self'",
|
||||
"t3code:",
|
||||
"blob:",
|
||||
"data:",
|
||||
"http:",
|
||||
"https:",
|
||||
]);
|
||||
assert.deepEqual(directives["font-src"], ["'self'", "t3code:", "data:"]);
|
||||
});
|
||||
});
|
||||
@@ -1,18 +1,27 @@
|
||||
import * as Cause from "effect/Cause";
|
||||
import * as Context from "effect/Context";
|
||||
import * as Data from "effect/Data";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Ref from "effect/Ref";
|
||||
import * as Scope from "effect/Scope";
|
||||
|
||||
import * as Electron from "electron";
|
||||
|
||||
import { DesktopEnvironment, type DesktopEnvironmentShape } from "../app/DesktopEnvironment.ts";
|
||||
export const DESKTOP_HOST = "app";
|
||||
export const DESKTOP_PRODUCTION_SCHEME = "t3code";
|
||||
export const DESKTOP_DEVELOPMENT_SCHEME = "t3code-dev";
|
||||
|
||||
export const DESKTOP_SCHEME = "t3";
|
||||
export function getDesktopScheme(isDevelopment: boolean): string {
|
||||
return isDevelopment ? DESKTOP_DEVELOPMENT_SCHEME : DESKTOP_PRODUCTION_SCHEME;
|
||||
}
|
||||
|
||||
export function getDesktopOrigin(isDevelopment: boolean): string {
|
||||
return `${getDesktopScheme(isDevelopment)}://${DESKTOP_HOST}`;
|
||||
}
|
||||
|
||||
export function getDesktopUrl(isDevelopment: boolean): string {
|
||||
return `${getDesktopOrigin(isDevelopment)}/`;
|
||||
}
|
||||
|
||||
export class ElectronProtocolRegistrationError extends Data.TaggedError(
|
||||
"ElectronProtocolRegistrationError",
|
||||
@@ -21,252 +30,117 @@ export class ElectronProtocolRegistrationError extends Data.TaggedError(
|
||||
readonly cause: unknown;
|
||||
}> {
|
||||
override get message() {
|
||||
return `Failed to register ${this.scheme}: file protocol.`;
|
||||
return `Failed to register ${this.scheme}: protocol.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class ElectronProtocolStaticBundleMissingError extends Data.TaggedError(
|
||||
"ElectronProtocolStaticBundleMissingError",
|
||||
)<{}> {
|
||||
override get message() {
|
||||
return "Desktop static bundle missing. Build apps/server (with bundled client) first.";
|
||||
}
|
||||
export interface DesktopProtocolRegistrationInput {
|
||||
readonly scheme: string;
|
||||
readonly targetOrigin: URL;
|
||||
readonly backendOrigin: URL;
|
||||
readonly clerkFrontendApiHostname: string | undefined;
|
||||
}
|
||||
|
||||
export interface ElectronProtocolShape {
|
||||
readonly registerFileProtocol: <E, R>(input: {
|
||||
readonly scheme: string;
|
||||
readonly handler: (
|
||||
request: Electron.ProtocolRequest,
|
||||
) => Effect.Effect<Electron.ProtocolResponse, E, R>;
|
||||
readonly onFailure?: (
|
||||
request: Electron.ProtocolRequest,
|
||||
cause: Cause.Cause<E>,
|
||||
) => Electron.ProtocolResponse;
|
||||
}) => Effect.Effect<void, ElectronProtocolRegistrationError, R | Scope.Scope>;
|
||||
readonly registerDesktopFileProtocol: Effect.Effect<
|
||||
void,
|
||||
ElectronProtocolRegistrationError | ElectronProtocolStaticBundleMissingError,
|
||||
FileSystem.FileSystem | DesktopEnvironment | Scope.Scope
|
||||
>;
|
||||
readonly registerDesktopProtocol: (
|
||||
input: DesktopProtocolRegistrationInput,
|
||||
) => Effect.Effect<void, ElectronProtocolRegistrationError, Scope.Scope>;
|
||||
}
|
||||
|
||||
export class ElectronProtocol extends Context.Service<ElectronProtocol, ElectronProtocolShape>()(
|
||||
"@t3tools/desktop/electron/ElectronProtocol",
|
||||
) {}
|
||||
|
||||
export function normalizeDesktopProtocolPathname(rawPath: string): Option.Option<string> {
|
||||
const segments: string[] = [];
|
||||
for (const segment of rawPath.split("/")) {
|
||||
if (segment.length === 0 || segment === ".") {
|
||||
continue;
|
||||
}
|
||||
if (segment === "..") {
|
||||
return Option.none();
|
||||
}
|
||||
segments.push(segment);
|
||||
}
|
||||
return Option.some(segments.join("/"));
|
||||
export function makeDesktopContentSecurityPolicy(input: DesktopProtocolRegistrationInput): string {
|
||||
const clerkOrigin = input.clerkFrontendApiHostname
|
||||
? `https://${input.clerkFrontendApiHostname}`
|
||||
: undefined;
|
||||
const scriptSources = [
|
||||
"'self'",
|
||||
"'unsafe-inline'",
|
||||
...(clerkOrigin ? [clerkOrigin] : []),
|
||||
"https://challenges.cloudflare.com",
|
||||
];
|
||||
|
||||
// The renderer connects directly to user-configured environments in addition to
|
||||
// the build-configured Clerk, relay, and OTLP endpoints. Those environment
|
||||
// origins are not known when this response policy is created, so restrict
|
||||
// connections by the network schemes the client supports instead of by host.
|
||||
const connectSources = ["'self'", "http:", "https:", "ws:", "wss:"];
|
||||
|
||||
return [
|
||||
"default-src 'self'",
|
||||
`script-src ${scriptSources.join(" ")}`,
|
||||
`connect-src ${connectSources.join(" ")}`,
|
||||
`img-src 'self' ${input.scheme}: blob: data: http: https:`,
|
||||
"style-src 'self' 'unsafe-inline'",
|
||||
`font-src 'self' ${input.scheme}: data:`,
|
||||
"worker-src 'self' blob:",
|
||||
"frame-src 'self' https://challenges.cloudflare.com",
|
||||
"form-action 'self'",
|
||||
].join("; ");
|
||||
}
|
||||
|
||||
const registerDesktopSchemePrivileges = Effect.sync(() => {
|
||||
Electron.protocol.registerSchemesAsPrivileged([
|
||||
{
|
||||
scheme: DESKTOP_SCHEME,
|
||||
privileges: {
|
||||
standard: true,
|
||||
secure: true,
|
||||
supportFetchAPI: true,
|
||||
corsEnabled: true,
|
||||
},
|
||||
},
|
||||
]);
|
||||
}).pipe(Effect.withSpan("desktop.electron.protocol.registerSchemePrivileges"));
|
||||
function withContentSecurityPolicy(response: Response, policy: string): Response {
|
||||
const headers = new Headers(response.headers);
|
||||
headers.set("Content-Security-Policy", policy);
|
||||
return new Response(response.body, {
|
||||
status: response.status,
|
||||
statusText: response.statusText,
|
||||
headers,
|
||||
});
|
||||
}
|
||||
|
||||
export const layerSchemePrivileges = Layer.effectDiscard(registerDesktopSchemePrivileges);
|
||||
|
||||
const resolveDesktopStaticDir: Effect.Effect<
|
||||
Option.Option<string>,
|
||||
never,
|
||||
FileSystem.FileSystem | DesktopEnvironment
|
||||
> = Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const environment = yield* DesktopEnvironment;
|
||||
const candidates = [
|
||||
environment.path.join(environment.appRoot, "apps/server/dist/client"),
|
||||
environment.path.join(environment.appRoot, "apps/web/dist"),
|
||||
];
|
||||
for (const candidate of candidates) {
|
||||
const hasIndex = yield* fileSystem
|
||||
.exists(environment.path.join(candidate, "index.html"))
|
||||
.pipe(Effect.orElseSucceed(() => false));
|
||||
if (hasIndex) {
|
||||
return Option.some(candidate);
|
||||
}
|
||||
async function proxyRequest(
|
||||
request: Request,
|
||||
targetOrigin: URL,
|
||||
contentSecurityPolicy: string,
|
||||
): Promise<Response> {
|
||||
const requestUrl = new URL(request.url);
|
||||
if (requestUrl.host !== DESKTOP_HOST) {
|
||||
return new Response(null, { status: 404 });
|
||||
}
|
||||
return Option.none<string>();
|
||||
});
|
||||
|
||||
const resolveDesktopStaticPath = Effect.fn("desktop.electron.protocol.resolveDesktopStaticPath")(
|
||||
function* (
|
||||
staticRoot: string,
|
||||
requestUrl: string,
|
||||
): Effect.fn.Return<string, never, FileSystem.FileSystem | DesktopEnvironment> {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const environment = yield* DesktopEnvironment;
|
||||
const url = new URL(requestUrl);
|
||||
const rawPath = decodeURIComponent(url.pathname);
|
||||
const normalizedPath = normalizeDesktopProtocolPathname(rawPath);
|
||||
if (Option.isNone(normalizedPath)) {
|
||||
return environment.path.join(staticRoot, "index.html");
|
||||
}
|
||||
|
||||
const requestedPath = normalizedPath.value.length > 0 ? normalizedPath.value : "index.html";
|
||||
const resolvedPath = environment.path.join(staticRoot, requestedPath);
|
||||
|
||||
if (environment.path.extname(resolvedPath)) {
|
||||
return resolvedPath;
|
||||
}
|
||||
|
||||
const nestedIndex = environment.path.join(resolvedPath, "index.html");
|
||||
const nestedIndexExists = yield* fileSystem
|
||||
.exists(nestedIndex)
|
||||
.pipe(Effect.orElseSucceed(() => false));
|
||||
if (nestedIndexExists) {
|
||||
return nestedIndex;
|
||||
}
|
||||
|
||||
return environment.path.join(staticRoot, "index.html");
|
||||
},
|
||||
);
|
||||
|
||||
function isStaticAssetRequest(requestUrl: string, environment: DesktopEnvironmentShape): boolean {
|
||||
try {
|
||||
const url = new URL(requestUrl);
|
||||
return environment.path.extname(url.pathname).length > 0;
|
||||
} catch {
|
||||
return false;
|
||||
const targetUrl = new URL(`${requestUrl.pathname}${requestUrl.search}`, targetOrigin);
|
||||
const init: RequestInit = {
|
||||
method: request.method,
|
||||
headers: request.headers,
|
||||
};
|
||||
if (request.method !== "GET" && request.method !== "HEAD") {
|
||||
init.body = request.body;
|
||||
(init as RequestInit & { duplex: "half" }).duplex = "half";
|
||||
}
|
||||
const response = await Electron.net.fetch(targetUrl.toString(), init);
|
||||
return withContentSecurityPolicy(response, contentSecurityPolicy);
|
||||
}
|
||||
|
||||
const make = Effect.gen(function* () {
|
||||
const registeredProtocols = yield* Ref.make<ReadonlySet<string>>(new Set());
|
||||
const registered = yield* Ref.make(false);
|
||||
|
||||
const registerFileProtocol = Effect.fn("desktop.electron.protocol.registerFileProtocol")(
|
||||
function* <E, R>({
|
||||
scheme,
|
||||
handler,
|
||||
onFailure,
|
||||
}: {
|
||||
readonly scheme: string;
|
||||
readonly handler: (
|
||||
request: Electron.ProtocolRequest,
|
||||
) => Effect.Effect<Electron.ProtocolResponse, E, R>;
|
||||
readonly onFailure?: (
|
||||
request: Electron.ProtocolRequest,
|
||||
cause: Cause.Cause<E>,
|
||||
) => Electron.ProtocolResponse;
|
||||
}): Effect.fn.Return<void, ElectronProtocolRegistrationError, R | Scope.Scope> {
|
||||
yield* Effect.annotateCurrentSpan({ scheme });
|
||||
const alreadyRegistered = yield* Ref.get(registeredProtocols).pipe(
|
||||
Effect.map((protocols) => protocols.has(scheme)),
|
||||
);
|
||||
if (alreadyRegistered) {
|
||||
return;
|
||||
}
|
||||
const registerDesktopProtocol = Effect.fn("desktop.electron.protocol.registerDesktopProtocol")(
|
||||
function* (input: DesktopProtocolRegistrationInput) {
|
||||
if (yield* Ref.get(registered)) return;
|
||||
|
||||
const context = yield* Effect.context<R>();
|
||||
const runPromise = Effect.runPromiseWith(context);
|
||||
const contentSecurityPolicy = makeDesktopContentSecurityPolicy(input);
|
||||
|
||||
yield* Effect.acquireRelease(
|
||||
Effect.try({
|
||||
try: () => {
|
||||
const registered = Electron.protocol.registerFileProtocol(
|
||||
scheme,
|
||||
(request, callback) => {
|
||||
const response = handler(request).pipe(
|
||||
Effect.withSpan("desktop.electron.protocol.handleFileRequest"),
|
||||
Effect.catchCause((cause) =>
|
||||
Effect.succeed(onFailure?.(request, cause) ?? ({ error: -2 } as const)),
|
||||
),
|
||||
);
|
||||
|
||||
void runPromise(response).then(callback, () => callback({ error: -2 }));
|
||||
},
|
||||
Electron.protocol.handle(input.scheme, (request) =>
|
||||
proxyRequest(request, input.targetOrigin, contentSecurityPolicy),
|
||||
);
|
||||
if (!registered) {
|
||||
throw new ElectronProtocolRegistrationError({
|
||||
scheme,
|
||||
cause: "registerFileProtocol returned false",
|
||||
});
|
||||
}
|
||||
},
|
||||
catch: (cause) =>
|
||||
cause instanceof ElectronProtocolRegistrationError
|
||||
? cause
|
||||
: new ElectronProtocolRegistrationError({ scheme, cause }),
|
||||
}).pipe(
|
||||
Effect.andThen(
|
||||
Ref.update(registeredProtocols, (protocols) => new Set(protocols).add(scheme)),
|
||||
),
|
||||
),
|
||||
catch: (cause) => new ElectronProtocolRegistrationError({ scheme: input.scheme, cause }),
|
||||
}).pipe(Effect.andThen(Ref.set(registered, true))),
|
||||
() =>
|
||||
Effect.sync(() => {
|
||||
Electron.protocol.unregisterProtocol(scheme);
|
||||
}).pipe(
|
||||
Effect.andThen(
|
||||
Ref.update(registeredProtocols, (protocols) => {
|
||||
const next = new Set(protocols);
|
||||
next.delete(scheme);
|
||||
return next;
|
||||
}),
|
||||
),
|
||||
),
|
||||
Electron.protocol.unhandle(input.scheme);
|
||||
}).pipe(Effect.andThen(Ref.set(registered, false))),
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
const registerDesktopFileProtocol = Effect.gen(function* () {
|
||||
const environment = yield* DesktopEnvironment;
|
||||
if (environment.isDevelopment) return;
|
||||
|
||||
const staticRoot = yield* resolveDesktopStaticDir;
|
||||
if (Option.isNone(staticRoot)) {
|
||||
return yield* new ElectronProtocolStaticBundleMissingError();
|
||||
}
|
||||
|
||||
const staticRootResolved = environment.path.resolve(staticRoot.value);
|
||||
const staticRootPrefix = `${staticRootResolved}${environment.path.sep}`;
|
||||
const fallbackIndex = environment.path.join(staticRootResolved, "index.html");
|
||||
|
||||
yield* registerFileProtocol({
|
||||
scheme: DESKTOP_SCHEME,
|
||||
handler: Effect.fn("desktop.electron.protocol.handleDesktopFileRequest")(function* (request) {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const environment = yield* DesktopEnvironment;
|
||||
const candidate = yield* resolveDesktopStaticPath(staticRootResolved, request.url);
|
||||
const resolvedCandidate = environment.path.resolve(candidate);
|
||||
const isInRoot =
|
||||
resolvedCandidate === fallbackIndex || resolvedCandidate.startsWith(staticRootPrefix);
|
||||
const isAssetRequest = isStaticAssetRequest(request.url, environment);
|
||||
const exists = yield* fileSystem
|
||||
.exists(resolvedCandidate)
|
||||
.pipe(Effect.orElseSucceed(() => false));
|
||||
|
||||
if (!isInRoot || !exists) {
|
||||
return isAssetRequest ? ({ error: -6 } as const) : ({ path: fallbackIndex } as const);
|
||||
}
|
||||
|
||||
return { path: resolvedCandidate } as const;
|
||||
}),
|
||||
onFailure: () => ({ path: fallbackIndex }),
|
||||
});
|
||||
}).pipe(Effect.withSpan("desktop.electron.protocol.registerDesktopFileProtocol"));
|
||||
|
||||
return ElectronProtocol.of({
|
||||
registerFileProtocol,
|
||||
registerDesktopFileProtocol,
|
||||
});
|
||||
return ElectronProtocol.of({ registerDesktopProtocol });
|
||||
});
|
||||
|
||||
export const layer = Layer.effect(ElectronProtocol, make);
|
||||
@@ -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);
|
||||
|
||||
@@ -3,12 +3,6 @@ export const CONFIRM_CHANNEL = "desktop:confirm";
|
||||
export const SET_THEME_CHANNEL = "desktop:set-theme";
|
||||
export const CONTEXT_MENU_CHANNEL = "desktop:context-menu";
|
||||
export const OPEN_EXTERNAL_CHANNEL = "desktop:open-external";
|
||||
export const CREATE_CLOUD_AUTH_REQUEST_CHANNEL = "desktop:create-cloud-auth-request";
|
||||
export const GET_CLOUD_AUTH_TOKEN_CHANNEL = "desktop:get-cloud-auth-token";
|
||||
export const SET_CLOUD_AUTH_TOKEN_CHANNEL = "desktop:set-cloud-auth-token";
|
||||
export const CLEAR_CLOUD_AUTH_TOKEN_CHANNEL = "desktop:clear-cloud-auth-token";
|
||||
export const FETCH_CLOUD_AUTH_CHANNEL = "desktop:fetch-cloud-auth";
|
||||
export const CLOUD_AUTH_CALLBACK_CHANNEL = "desktop:cloud-auth-callback";
|
||||
export const MENU_ACTION_CHANNEL = "desktop:menu-action";
|
||||
export const UPDATE_STATE_CHANNEL = "desktop:update-state";
|
||||
export const UPDATE_GET_STATE_CHANNEL = "desktop:update-get-state";
|
||||
@@ -18,6 +12,8 @@ export const UPDATE_INSTALL_CHANNEL = "desktop:update-install";
|
||||
export const UPDATE_CHECK_CHANNEL = "desktop:update-check";
|
||||
export const GET_APP_BRANDING_CHANNEL = "desktop:get-app-branding";
|
||||
export const GET_LOCAL_ENVIRONMENT_BOOTSTRAP_CHANNEL = "desktop:get-local-environment-bootstrap";
|
||||
export const GET_LOCAL_ENVIRONMENT_BEARER_TOKEN_CHANNEL =
|
||||
"desktop:get-local-environment-bearer-token";
|
||||
export const GET_CLIENT_SETTINGS_CHANNEL = "desktop:get-client-settings";
|
||||
export const SET_CLIENT_SETTINGS_CHANNEL = "desktop:set-client-settings";
|
||||
export const GET_CONNECTION_CATALOG_CHANNEL = "desktop:get-connection-catalog";
|
||||
|
||||
@@ -1,97 +0,0 @@
|
||||
import { assert, describe, it } from "@effect/vitest";
|
||||
import * as Effect from "effect/Effect";
|
||||
import { afterEach } from "vite-plus/test";
|
||||
|
||||
import { fetchCloudAuth, validateClerkFrontendApiUrl } from "./cloudAuth.ts";
|
||||
|
||||
const originalClerkPublishableKey = process.env.T3CODE_CLERK_PUBLISHABLE_KEY;
|
||||
const originalFetch = globalThis.fetch;
|
||||
|
||||
const clerkPublishableKey = (hostname: string): string =>
|
||||
`pk_test_${Buffer.from(`${hostname}$`).toString("base64")}`;
|
||||
|
||||
type FetchCall = readonly [input: RequestInfo | URL, init: RequestInit];
|
||||
|
||||
const recordedFetch = (...responses: ReadonlyArray<Response>) => {
|
||||
const calls: Array<FetchCall> = [];
|
||||
let responseIndex = 0;
|
||||
const fetchFn = ((input, init) => {
|
||||
calls.push([input, init ?? {}]);
|
||||
const response = responses[responseIndex++];
|
||||
if (!response) {
|
||||
return Promise.reject(new Error("Unexpected fetch call"));
|
||||
}
|
||||
return Promise.resolve(response);
|
||||
}) satisfies typeof fetch;
|
||||
|
||||
return { fetchFn, calls };
|
||||
};
|
||||
|
||||
describe("Desktop cloud auth IPC", () => {
|
||||
afterEach(() => {
|
||||
globalThis.fetch = originalFetch;
|
||||
if (originalClerkPublishableKey === undefined) {
|
||||
delete process.env.T3CODE_CLERK_PUBLISHABLE_KEY;
|
||||
} else {
|
||||
process.env.T3CODE_CLERK_PUBLISHABLE_KEY = originalClerkPublishableKey;
|
||||
}
|
||||
});
|
||||
|
||||
it.effect("preserves Clerk's URL-encoded OAuth form content type", () => {
|
||||
const body = "strategy=oauth_google&redirect_url=t3code%3A%2F%2Fauth%2Fcallback";
|
||||
const fetch = recordedFetch(Response.json({ response: { object: "sign_in_attempt" } }));
|
||||
globalThis.fetch = fetch.fetchFn;
|
||||
|
||||
return Effect.gen(function* () {
|
||||
yield* fetchCloudAuth.handler({
|
||||
url: "https://example.clerk.accounts.dev/v1/client/sign_ins",
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/x-www-form-urlencoded;charset=UTF-8",
|
||||
"x-mobile": "1",
|
||||
},
|
||||
body,
|
||||
});
|
||||
|
||||
const forwardedRequest = fetch.calls[0];
|
||||
assert(forwardedRequest !== undefined);
|
||||
const [url, init] = forwardedRequest;
|
||||
assert.equal(String(url), "https://example.clerk.accounts.dev/v1/client/sign_ins");
|
||||
assert.equal(init.method, "POST");
|
||||
assert.equal(
|
||||
new Headers(init.headers).get("content-type"),
|
||||
"application/x-www-form-urlencoded;charset=UTF-8",
|
||||
);
|
||||
assert.equal(new TextDecoder().decode(init.body as Uint8Array), body);
|
||||
});
|
||||
});
|
||||
|
||||
it.effect(
|
||||
"allows the custom Clerk Frontend API host encoded by the configured publishable key",
|
||||
() => {
|
||||
process.env.T3CODE_CLERK_PUBLISHABLE_KEY = clerkPublishableKey("clerk.t3.codes");
|
||||
const fetch = recordedFetch(Response.json({ response: { object: "client" } }));
|
||||
globalThis.fetch = fetch.fetchFn;
|
||||
|
||||
return Effect.gen(function* () {
|
||||
yield* fetchCloudAuth.handler({
|
||||
url: "https://clerk.t3.codes/v1/client",
|
||||
method: "GET",
|
||||
headers: {},
|
||||
});
|
||||
|
||||
const forwardedRequest = fetch.calls[0];
|
||||
assert(forwardedRequest !== undefined);
|
||||
assert.equal(String(forwardedRequest[0]), "https://clerk.t3.codes/v1/client");
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
it("rejects arbitrary HTTPS hosts that are not configured Clerk Frontend API hosts", () => {
|
||||
process.env.T3CODE_CLERK_PUBLISHABLE_KEY = clerkPublishableKey("clerk.t3.codes");
|
||||
assert.throws(
|
||||
() => validateClerkFrontendApiUrl("https://attacker.example/v1/client"),
|
||||
/restricted to Clerk Frontend API HTTPS hosts/u,
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -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));
|
||||
}),
|
||||
});
|
||||
@@ -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),
|
||||
|
||||
@@ -27,13 +27,13 @@ import * as ElectronUpdater from "./electron/ElectronUpdater.ts";
|
||||
import * as ElectronWindow from "./electron/ElectronWindow.ts";
|
||||
import * as DesktopApp from "./app/DesktopApp.ts";
|
||||
import * as DesktopAppIdentity from "./app/DesktopAppIdentity.ts";
|
||||
import * as DesktopCloudAuth from "./app/DesktopCloudAuth.ts";
|
||||
import * as DesktopCloudAuthTokenStore from "./app/DesktopCloudAuthTokenStore.ts";
|
||||
import * as DesktopConnectionCatalogStore from "./app/DesktopConnectionCatalogStore.ts";
|
||||
import * as DesktopClerk from "./app/DesktopClerk.ts";
|
||||
import * as DesktopApplicationMenu from "./window/DesktopApplicationMenu.ts";
|
||||
import * as DesktopAssets from "./app/DesktopAssets.ts";
|
||||
import * as DesktopBackendConfiguration from "./backend/DesktopBackendConfiguration.ts";
|
||||
import * as DesktopBackendManager from "./backend/DesktopBackendManager.ts";
|
||||
import * as DesktopLocalEnvironmentAuth from "./backend/DesktopLocalEnvironmentAuth.ts";
|
||||
import * as DesktopEnvironment from "./app/DesktopEnvironment.ts";
|
||||
import * as DesktopLifecycle from "./app/DesktopLifecycle.ts";
|
||||
import * as DesktopObservability from "./app/DesktopObservability.ts";
|
||||
@@ -119,7 +119,6 @@ const desktopFoundationLayer = Layer.mergeAll(
|
||||
DesktopAppSettings.layer,
|
||||
DesktopClientSettings.layer,
|
||||
DesktopConnectionCatalogStore.layer.pipe(Layer.provideMerge(DesktopSavedEnvironments.layer)),
|
||||
DesktopCloudAuthTokenStore.layer,
|
||||
DesktopAssets.layer,
|
||||
DesktopObservability.layer,
|
||||
).pipe(Layer.provideMerge(desktopEnvironmentLayer));
|
||||
@@ -149,17 +148,30 @@ const desktopBackendLayer = DesktopBackendManager.layer.pipe(
|
||||
Layer.provideMerge(desktopWindowLayer),
|
||||
);
|
||||
|
||||
const desktopLocalEnvironmentAuthLayer = DesktopLocalEnvironmentAuth.layer.pipe(
|
||||
Layer.provideMerge(desktopBackendLayer),
|
||||
);
|
||||
|
||||
const desktopApplicationLayer = Layer.mergeAll(
|
||||
DesktopLifecycle.layer,
|
||||
DesktopApplicationMenu.layer,
|
||||
DesktopCloudAuth.layer,
|
||||
DesktopShellEnvironment.layer,
|
||||
desktopSshLayer,
|
||||
).pipe(Layer.provideMerge(DesktopUpdates.layer), Layer.provideMerge(desktopBackendLayer));
|
||||
).pipe(
|
||||
Layer.provideMerge(DesktopUpdates.layer),
|
||||
Layer.provideMerge(desktopLocalEnvironmentAuthLayer),
|
||||
);
|
||||
|
||||
const desktopRuntimeLayer = ElectronProtocol.layerSchemePrivileges.pipe(
|
||||
Layer.flatMap(() =>
|
||||
const desktopClerkLayer = DesktopClerk.layer.pipe(
|
||||
Layer.provideMerge(desktopEnvironmentLayer),
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
Layer.provideMerge(ElectronApp.layer),
|
||||
);
|
||||
|
||||
const desktopRuntimeLayer = desktopClerkLayer.pipe(
|
||||
Layer.flatMap((clerkContext) =>
|
||||
desktopApplicationLayer.pipe(
|
||||
Layer.provideMerge(Layer.succeedContext(clerkContext)),
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
Layer.provideMerge(NodeHttpClient.layerUndici),
|
||||
Layer.provideMerge(NetService.layer),
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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));
|
||||
}),
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -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({
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -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 () => {
|
||||
|
||||
@@ -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",
|
||||
},
|
||||
]);
|
||||
});
|
||||
});
|
||||
@@ -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;
|
||||
});
|
||||
}
|
||||
@@ -1,322 +0,0 @@
|
||||
import { Clerk } from "@clerk/clerk-js";
|
||||
import {
|
||||
buildClerkUIScriptAttributes,
|
||||
clerkUIScriptUrl,
|
||||
InternalClerkProvider,
|
||||
} from "@clerk/react/internal";
|
||||
import type { ClerkProviderProps } from "@clerk/react";
|
||||
import {
|
||||
clerkFrontendApiHostnameFromPublishableKey,
|
||||
isAllowedClerkFrontendApiHostname,
|
||||
} from "@t3tools/shared/relayAuth";
|
||||
import React, { useEffect, useState } from "react";
|
||||
|
||||
import {
|
||||
makeDesktopClerkExternalAccountAdapter,
|
||||
type DesktopClerkUser,
|
||||
} from "./desktopClerkExternalAccounts";
|
||||
|
||||
type DesktopClerkUiCtor = NonNullable<Window["__internal_ClerkUICtor"]>;
|
||||
|
||||
interface ClerkFrontendApiRequest {
|
||||
credentials?: RequestCredentials;
|
||||
headers?: Headers;
|
||||
url?: URL;
|
||||
}
|
||||
|
||||
interface ClerkFrontendApiResponse {
|
||||
headers: Headers;
|
||||
payload?: {
|
||||
errors?: readonly {
|
||||
code?: string;
|
||||
}[];
|
||||
};
|
||||
}
|
||||
|
||||
interface NativeRequestClerk {
|
||||
readonly publishableKey?: string;
|
||||
__internal_onBeforeRequest?: (
|
||||
listener: (request: ClerkFrontendApiRequest) => void | Promise<void>,
|
||||
) => void;
|
||||
__internal_onAfterResponse?: (
|
||||
listener: (
|
||||
request: ClerkFrontendApiRequest,
|
||||
response?: ClerkFrontendApiResponse,
|
||||
) => void | Promise<void>,
|
||||
) => void;
|
||||
__unstable__onBeforeRequest?: (
|
||||
listener: (request: ClerkFrontendApiRequest) => void | Promise<void>,
|
||||
) => void;
|
||||
__unstable__onAfterResponse?: (
|
||||
listener: (
|
||||
request: ClerkFrontendApiRequest,
|
||||
response?: ClerkFrontendApiResponse,
|
||||
) => void | Promise<void>,
|
||||
) => void;
|
||||
}
|
||||
|
||||
interface DesktopClerkProviderProps {
|
||||
readonly children: React.ReactNode;
|
||||
readonly publishableKey: string;
|
||||
}
|
||||
|
||||
let desktopClerk: Clerk | null = null;
|
||||
let desktopClerkFetchInstalled = false;
|
||||
let desktopClerkUiLoad: Promise<DesktopClerkUiCtor> | null = null;
|
||||
let desktopClerkFrontendApiHostname: string | null = null;
|
||||
let desktopClerkExternalAccountCleanup: (() => void) | null = null;
|
||||
|
||||
const isNativeRequestClerk = (value: unknown): value is NativeRequestClerk => {
|
||||
if (typeof value !== "object" || value === null) return false;
|
||||
const candidate = value as {
|
||||
__internal_onBeforeRequest?: unknown;
|
||||
__internal_onAfterResponse?: unknown;
|
||||
__unstable__onBeforeRequest?: unknown;
|
||||
__unstable__onAfterResponse?: unknown;
|
||||
};
|
||||
return (
|
||||
(typeof candidate.__internal_onBeforeRequest === "function" ||
|
||||
typeof candidate.__unstable__onBeforeRequest === "function") &&
|
||||
(typeof candidate.__internal_onAfterResponse === "function" ||
|
||||
typeof candidate.__unstable__onAfterResponse === "function")
|
||||
);
|
||||
};
|
||||
|
||||
const getStoredClientJwt = (): Promise<string | null> =>
|
||||
window.desktopBridge?.getCloudAuthToken() ?? Promise.resolve(null);
|
||||
|
||||
const setStoredClientJwt = (token: string): Promise<boolean> =>
|
||||
window.desktopBridge?.setCloudAuthToken(token) ?? Promise.resolve(false);
|
||||
|
||||
const clearStoredClientJwt = (): Promise<void> =>
|
||||
window.desktopBridge?.clearCloudAuthToken() ?? Promise.resolve();
|
||||
|
||||
const isClerkFrontendApiUrl = (url: URL): boolean =>
|
||||
url.protocol === "https:" &&
|
||||
isAllowedClerkFrontendApiHostname(url.hostname, desktopClerkFrontendApiHostname);
|
||||
|
||||
const headersToRecord = (headers: Headers): Record<string, string> => {
|
||||
const record: Record<string, string> = {};
|
||||
headers.forEach((value, key) => {
|
||||
record[key] = value;
|
||||
});
|
||||
return record;
|
||||
};
|
||||
|
||||
function installDesktopClerkFetchProxy(publishableKey: string): void {
|
||||
desktopClerkFrontendApiHostname = clerkFrontendApiHostnameFromPublishableKey(publishableKey);
|
||||
if (desktopClerkFetchInstalled) return;
|
||||
const bridge = window.desktopBridge;
|
||||
if (!bridge) return;
|
||||
|
||||
const browserFetch = window.fetch.bind(window);
|
||||
window.fetch = async (input, init) => {
|
||||
const request = new Request(input, init);
|
||||
const url = new URL(request.url);
|
||||
if (!isClerkFrontendApiUrl(url)) {
|
||||
return browserFetch(input, init);
|
||||
}
|
||||
|
||||
const body =
|
||||
request.method === "GET" || request.method === "HEAD"
|
||||
? undefined
|
||||
: await request.clone().text();
|
||||
const result = await bridge.fetchCloudAuth({
|
||||
url: request.url,
|
||||
method: request.method,
|
||||
headers: headersToRecord(request.headers),
|
||||
...(body === undefined ? {} : { body }),
|
||||
});
|
||||
|
||||
return new Response(result.body, {
|
||||
status: result.status,
|
||||
statusText: result.statusText,
|
||||
headers: result.headers,
|
||||
});
|
||||
};
|
||||
desktopClerkFetchInstalled = true;
|
||||
}
|
||||
|
||||
function installDesktopClerkExternalAccounts(clerk: Clerk): void {
|
||||
desktopClerkExternalAccountCleanup?.();
|
||||
desktopClerkExternalAccountCleanup = null;
|
||||
|
||||
const bridge = window.desktopBridge;
|
||||
if (!bridge) return;
|
||||
|
||||
const adapter = makeDesktopClerkExternalAccountAdapter({ bridge });
|
||||
const unsubscribe = clerk.addListener(({ user }) => {
|
||||
if (user) {
|
||||
adapter.installUser(user as DesktopClerkUser);
|
||||
}
|
||||
});
|
||||
desktopClerkExternalAccountCleanup = () => {
|
||||
unsubscribe();
|
||||
adapter.dispose();
|
||||
};
|
||||
}
|
||||
|
||||
function loadDesktopClerkUi(publishableKey: string): Promise<DesktopClerkUiCtor> {
|
||||
if (window.__internal_ClerkUICtor) {
|
||||
return Promise.resolve(window.__internal_ClerkUICtor);
|
||||
}
|
||||
if (desktopClerkUiLoad) {
|
||||
return desktopClerkUiLoad;
|
||||
}
|
||||
|
||||
const load = new Promise<DesktopClerkUiCtor>((resolve, reject) => {
|
||||
const scriptUrl = clerkUIScriptUrl({ publishableKey });
|
||||
const existingScript = document.querySelector<HTMLScriptElement>(
|
||||
"script[data-clerk-ui-script]",
|
||||
);
|
||||
|
||||
const resolveLoadedUi = () => {
|
||||
const ClerkUI = window.__internal_ClerkUICtor;
|
||||
if (ClerkUI) {
|
||||
resolve(ClerkUI);
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
};
|
||||
if (resolveLoadedUi()) {
|
||||
return;
|
||||
}
|
||||
|
||||
const script = existingScript ?? document.createElement("script");
|
||||
script.async = true;
|
||||
script.crossOrigin = "anonymous";
|
||||
script.src = scriptUrl;
|
||||
script.dataset.clerkUiScript = "true";
|
||||
const attributes = buildClerkUIScriptAttributes({ publishableKey });
|
||||
for (const [name, value] of Object.entries(attributes)) {
|
||||
script.setAttribute(name, value);
|
||||
}
|
||||
|
||||
const timeoutId = window.setTimeout(() => {
|
||||
reject(new Error("Timed out loading Clerk UI for desktop auth."));
|
||||
}, 15_000);
|
||||
script.addEventListener("load", () => {
|
||||
window.clearTimeout(timeoutId);
|
||||
if (!resolveLoadedUi()) {
|
||||
reject(new Error("Clerk UI loaded without exposing the UI constructor."));
|
||||
}
|
||||
});
|
||||
script.addEventListener("error", () => {
|
||||
window.clearTimeout(timeoutId);
|
||||
reject(new Error("Failed to load Clerk UI for desktop auth."));
|
||||
});
|
||||
if (!existingScript) {
|
||||
document.head.append(script);
|
||||
}
|
||||
}).catch((error: unknown) => {
|
||||
desktopClerkUiLoad = null;
|
||||
throw error;
|
||||
});
|
||||
|
||||
desktopClerkUiLoad = load;
|
||||
return load;
|
||||
}
|
||||
|
||||
function getDesktopClerkInstance(publishableKey: string): Clerk {
|
||||
installDesktopClerkFetchProxy(publishableKey);
|
||||
|
||||
const hasKeyChanged = desktopClerk !== null && desktopClerk.publishableKey !== publishableKey;
|
||||
if (hasKeyChanged) {
|
||||
void clearStoredClientJwt();
|
||||
desktopClerkExternalAccountCleanup?.();
|
||||
desktopClerkExternalAccountCleanup = null;
|
||||
desktopClerk = null;
|
||||
}
|
||||
|
||||
if (desktopClerk !== null) {
|
||||
return desktopClerk;
|
||||
}
|
||||
|
||||
const nextClerk = new Clerk(publishableKey);
|
||||
installDesktopClerkExternalAccounts(nextClerk);
|
||||
if (!isNativeRequestClerk(nextClerk)) {
|
||||
desktopClerk = nextClerk;
|
||||
return nextClerk;
|
||||
}
|
||||
|
||||
const onBeforeRequest =
|
||||
nextClerk.__internal_onBeforeRequest ?? nextClerk.__unstable__onBeforeRequest;
|
||||
const onAfterResponse =
|
||||
nextClerk.__internal_onAfterResponse ?? nextClerk.__unstable__onAfterResponse;
|
||||
|
||||
// Keep this aligned with Clerk Expo's native FAPI adapter:
|
||||
// https://github.com/clerk/javascript/blob/52861184477bee99c71552000311a289e91d3b59/packages/expo/src/provider/singleton/createClerkInstance.ts
|
||||
onBeforeRequest(async (request) => {
|
||||
request.credentials = "omit";
|
||||
request.url?.searchParams.append("_is_native", "1");
|
||||
const headers = new Headers(request.headers);
|
||||
|
||||
const clientJwt = await getStoredClientJwt();
|
||||
headers.set("authorization", clientJwt ?? "");
|
||||
headers.set("x-mobile", "1");
|
||||
request.headers = headers;
|
||||
});
|
||||
|
||||
onAfterResponse(async (_request, response) => {
|
||||
const clientJwt = response?.headers.get("authorization");
|
||||
if (clientJwt) {
|
||||
await setStoredClientJwt(clientJwt);
|
||||
}
|
||||
|
||||
const errorCode = response?.payload?.errors?.[0]?.code;
|
||||
if (errorCode === "native_api_disabled") {
|
||||
console.error(
|
||||
"Clerk Native API is disabled. Enable Native applications in the Clerk dashboard for desktop sign-in.",
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
desktopClerk = nextClerk;
|
||||
return nextClerk;
|
||||
}
|
||||
|
||||
export function DesktopClerkProvider({ children, publishableKey }: DesktopClerkProviderProps) {
|
||||
const [clerkUiCtor, setClerkUiCtor] = useState<DesktopClerkUiCtor | undefined>(
|
||||
() => window.__internal_ClerkUICtor,
|
||||
);
|
||||
const [clerkUiError, setClerkUiError] = useState<unknown>(null);
|
||||
|
||||
useEffect(() => {
|
||||
let isCurrent = true;
|
||||
void loadDesktopClerkUi(publishableKey).then(
|
||||
(ClerkUI) => {
|
||||
if (isCurrent) {
|
||||
setClerkUiCtor(() => ClerkUI);
|
||||
}
|
||||
},
|
||||
(error: unknown) => {
|
||||
if (isCurrent) {
|
||||
setClerkUiError(error);
|
||||
}
|
||||
},
|
||||
);
|
||||
return () => {
|
||||
isCurrent = false;
|
||||
};
|
||||
}, [publishableKey]);
|
||||
|
||||
if (!clerkUiCtor) {
|
||||
if (clerkUiError) {
|
||||
console.error("Failed to load Clerk UI for desktop auth.", clerkUiError);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
const clerk = getDesktopClerkInstance(publishableKey);
|
||||
return (
|
||||
<InternalClerkProvider
|
||||
key={publishableKey}
|
||||
publishableKey={publishableKey}
|
||||
Clerk={clerk as ClerkProviderProps["Clerk"]}
|
||||
ui={{ ClerkUI: clerkUiCtor }}
|
||||
standardBrowser={false}
|
||||
>
|
||||
{children}
|
||||
</InternalClerkProvider>
|
||||
);
|
||||
}
|
||||
@@ -1,78 +0,0 @@
|
||||
import { describe, expect, it, vi } from "vite-plus/test";
|
||||
|
||||
import {
|
||||
makeDesktopClerkExternalAccountAdapter,
|
||||
type DesktopClerkUser,
|
||||
} from "./desktopClerkExternalAccounts";
|
||||
|
||||
describe("desktop Clerk external account adapter", () => {
|
||||
it("replaces renderer redirects with native callbacks and reloads the user on return", async () => {
|
||||
const callbacks: ((rawUrl: string) => void)[] = [];
|
||||
const callbackCleanup = vi.fn();
|
||||
const bridge = {
|
||||
createCloudAuthRequest: vi
|
||||
.fn()
|
||||
.mockResolvedValueOnce("t3code://auth/callback?t3_state=add")
|
||||
.mockResolvedValueOnce("t3code://auth/callback?t3_state=reconnect"),
|
||||
onCloudAuthCallback: vi.fn((listener: (rawUrl: string) => void) => {
|
||||
callbacks.push(listener);
|
||||
return callbackCleanup;
|
||||
}),
|
||||
};
|
||||
const reauthorize = vi.fn(async (_params: Record<string, unknown>) => account);
|
||||
const account = { reauthorize };
|
||||
const createExternalAccount = vi.fn(async (_params: Record<string, unknown>) => account);
|
||||
const reload = vi.fn(async () => undefined);
|
||||
const user = {
|
||||
externalAccounts: [],
|
||||
createExternalAccount,
|
||||
reload,
|
||||
} satisfies DesktopClerkUser;
|
||||
const adapter = makeDesktopClerkExternalAccountAdapter({ bridge });
|
||||
adapter.installUser(user);
|
||||
|
||||
await user.createExternalAccount({
|
||||
redirectUrl: "http://127.0.0.1:3773/?__clerk_modal_state=state",
|
||||
strategy: "oauth_microsoft",
|
||||
});
|
||||
|
||||
expect(createExternalAccount).toHaveBeenCalledWith({
|
||||
redirectUrl: "t3code://auth/callback?t3_state=add",
|
||||
strategy: "oauth_microsoft",
|
||||
});
|
||||
|
||||
callbacks[0]?.("t3code://auth/callback?t3_state=add");
|
||||
await Promise.resolve();
|
||||
expect(reload).toHaveBeenCalledOnce();
|
||||
|
||||
await account.reauthorize({
|
||||
redirectUrl: "http://127.0.0.1:3773/?__clerk_modal_state=state",
|
||||
});
|
||||
expect(reauthorize).toHaveBeenCalledWith({
|
||||
redirectUrl: "t3code://auth/callback?t3_state=reconnect",
|
||||
});
|
||||
});
|
||||
|
||||
it("cleans up the pending callback when Clerk rejects account creation", async () => {
|
||||
const callbackCleanup = vi.fn();
|
||||
const bridge = {
|
||||
createCloudAuthRequest: vi.fn().mockResolvedValue("t3code://auth/callback?t3_state=failed"),
|
||||
onCloudAuthCallback: vi.fn(() => callbackCleanup),
|
||||
};
|
||||
const createError = new Error("oauth provider unavailable");
|
||||
const user = {
|
||||
externalAccounts: [],
|
||||
createExternalAccount: vi.fn(async (_params: Record<string, unknown>) => {
|
||||
throw createError;
|
||||
}),
|
||||
reload: vi.fn(async () => undefined),
|
||||
} satisfies DesktopClerkUser;
|
||||
const adapter = makeDesktopClerkExternalAccountAdapter({ bridge });
|
||||
adapter.installUser(user);
|
||||
|
||||
await expect(user.createExternalAccount({ strategy: "oauth_microsoft" })).rejects.toBe(
|
||||
createError,
|
||||
);
|
||||
expect(callbackCleanup).toHaveBeenCalledOnce();
|
||||
});
|
||||
});
|
||||
@@ -1,112 +0,0 @@
|
||||
interface DesktopClerkExternalAccountParams {
|
||||
readonly redirectUrl?: string;
|
||||
readonly [key: string]: unknown;
|
||||
}
|
||||
|
||||
interface DesktopClerkExternalAccount {
|
||||
reauthorize: (params: DesktopClerkExternalAccountParams) => Promise<DesktopClerkExternalAccount>;
|
||||
}
|
||||
|
||||
interface DesktopClerkUser {
|
||||
readonly externalAccounts: readonly DesktopClerkExternalAccount[];
|
||||
createExternalAccount: (
|
||||
params: DesktopClerkExternalAccountParams,
|
||||
) => Promise<DesktopClerkExternalAccount>;
|
||||
reload: () => Promise<unknown>;
|
||||
}
|
||||
|
||||
interface DesktopClerkExternalAccountBridge {
|
||||
readonly createCloudAuthRequest: () => Promise<string>;
|
||||
readonly onCloudAuthCallback: (listener: (rawUrl: string) => void) => () => void;
|
||||
}
|
||||
|
||||
interface DesktopClerkExternalAccountAdapter {
|
||||
readonly dispose: () => void;
|
||||
readonly installUser: (user: DesktopClerkUser) => void;
|
||||
}
|
||||
|
||||
interface MakeDesktopClerkExternalAccountAdapterInput {
|
||||
readonly bridge: DesktopClerkExternalAccountBridge;
|
||||
readonly reportError?: (message: string, error: unknown) => void;
|
||||
}
|
||||
|
||||
// Clerk's profile component uses window.location.href as the OAuth callback and navigates the
|
||||
// current window to the provider. Keep the upstream component intact while adapting its resource
|
||||
// calls to the native callback bridge:
|
||||
// https://github.com/clerk/javascript/blob/52861184477bee99c71552000311a289e91d3b59/packages/ui/src/components/UserProfile/ConnectedAccountsMenu.tsx
|
||||
// https://github.com/clerk/javascript/blob/52861184477bee99c71552000311a289e91d3b59/packages/ui/src/components/UserProfile/ConnectedAccountsSection.tsx
|
||||
export function makeDesktopClerkExternalAccountAdapter({
|
||||
bridge,
|
||||
reportError = console.error,
|
||||
}: MakeDesktopClerkExternalAccountAdapterInput): DesktopClerkExternalAccountAdapter {
|
||||
const installedAccounts = new WeakSet<object>();
|
||||
const installedUsers = new WeakSet<object>();
|
||||
let callbackGeneration = 0;
|
||||
let callbackCleanup: (() => void) | null = null;
|
||||
|
||||
const clearCallback = () => {
|
||||
callbackGeneration += 1;
|
||||
callbackCleanup?.();
|
||||
callbackCleanup = null;
|
||||
};
|
||||
|
||||
const createRedirectUrl = async (user: DesktopClerkUser): Promise<string> => {
|
||||
clearCallback();
|
||||
const redirectUrl = await bridge.createCloudAuthRequest();
|
||||
const generation = callbackGeneration;
|
||||
callbackCleanup = bridge.onCloudAuthCallback(() => {
|
||||
if (generation !== callbackGeneration) return;
|
||||
clearCallback();
|
||||
void user.reload().catch((error: unknown) => {
|
||||
reportError("Failed to reload Clerk after desktop account linking.", error);
|
||||
});
|
||||
});
|
||||
return redirectUrl;
|
||||
};
|
||||
|
||||
const installAccount = (user: DesktopClerkUser, account: DesktopClerkExternalAccount): void => {
|
||||
if (installedAccounts.has(account)) return;
|
||||
installedAccounts.add(account);
|
||||
|
||||
const reauthorize = account.reauthorize.bind(account);
|
||||
account.reauthorize = async (params) => {
|
||||
const redirectUrl = await createRedirectUrl(user);
|
||||
try {
|
||||
const nextAccount = await reauthorize({ ...params, redirectUrl });
|
||||
installAccount(user, nextAccount);
|
||||
return nextAccount;
|
||||
} catch (error) {
|
||||
clearCallback();
|
||||
throw error;
|
||||
}
|
||||
};
|
||||
};
|
||||
|
||||
const installUser = (user: DesktopClerkUser): void => {
|
||||
for (const account of user.externalAccounts) {
|
||||
installAccount(user, account);
|
||||
}
|
||||
if (installedUsers.has(user)) return;
|
||||
installedUsers.add(user);
|
||||
|
||||
const createExternalAccount = user.createExternalAccount.bind(user);
|
||||
user.createExternalAccount = async (params) => {
|
||||
const redirectUrl = await createRedirectUrl(user);
|
||||
try {
|
||||
const account = await createExternalAccount({ ...params, redirectUrl });
|
||||
installAccount(user, account);
|
||||
return account;
|
||||
} catch (error) {
|
||||
clearCallback();
|
||||
throw error;
|
||||
}
|
||||
};
|
||||
};
|
||||
|
||||
return {
|
||||
dispose: clearCallback,
|
||||
installUser,
|
||||
};
|
||||
}
|
||||
|
||||
export type { DesktopClerkExternalAccountAdapter, DesktopClerkUser };
|
||||
@@ -1,4 +1,5 @@
|
||||
import {
|
||||
type DesktopBridge,
|
||||
EnvironmentId,
|
||||
type RelayClientInstallProgressEvent,
|
||||
WS_METHODS,
|
||||
@@ -28,6 +29,7 @@ import {
|
||||
ManagedRelayDpopSigner,
|
||||
} from "@t3tools/client-runtime/relay";
|
||||
import { remoteHttpClientLayer } from "@t3tools/client-runtime/rpc";
|
||||
import { __resetDesktopPrimaryAuthForTests } from "../environments/primary/desktopAuth";
|
||||
|
||||
import {
|
||||
collectCloudLinkTargets,
|
||||
@@ -146,6 +148,7 @@ beforeEach(() => {
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
__resetDesktopPrimaryAuthForTests();
|
||||
vi.unstubAllGlobals();
|
||||
vi.unstubAllEnvs();
|
||||
vi.restoreAllMocks();
|
||||
@@ -224,6 +227,33 @@ describe("web cloud link environment client", () => {
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("uses desktop bearer auth for primary cloud link state", () =>
|
||||
Effect.gen(function* () {
|
||||
const fetchMock = vi.fn().mockResolvedValue(
|
||||
Response.json({
|
||||
linked: true,
|
||||
cloudUserId: "user-1",
|
||||
relayUrl: "https://relay.example.test",
|
||||
relayIssuer: "https://relay.example.test",
|
||||
publishAgentActivity: false,
|
||||
}),
|
||||
);
|
||||
vi.stubGlobal("fetch", fetchMock);
|
||||
vi.stubGlobal("window", {
|
||||
location: { origin: "t3code://app" },
|
||||
desktopBridge: {
|
||||
getLocalEnvironmentBearerToken: vi.fn().mockResolvedValue("desktop-bearer-token"),
|
||||
} as unknown as DesktopBridge,
|
||||
});
|
||||
|
||||
yield* withServices(readPrimaryCloudLinkState({ target: TARGET }));
|
||||
|
||||
const request = new Request(fetchMock.mock.calls[0]?.[0], fetchMock.mock.calls[0]?.[1]);
|
||||
expect(request.credentials).not.toBe("include");
|
||||
expect(request.headers.get("authorization")).toBe("Bearer desktop-bearer-token");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("links an available primary environment without invoking installation", () =>
|
||||
Effect.gen(function* () {
|
||||
const fetchMock = vi
|
||||
|
||||
@@ -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));
|
||||
}
|
||||
@@ -1,137 +0,0 @@
|
||||
import type { ReactNode } from "react";
|
||||
|
||||
import { cn } from "../../lib/utils";
|
||||
|
||||
// Mirrors Clerk's raised card/footer/branding composition for the desktop-native flow:
|
||||
// https://github.com/clerk/javascript/blob/52861184477bee99c71552000311a289e91d3b59/packages/ui/src/elements/Card/CardRoot.tsx
|
||||
// https://github.com/clerk/javascript/blob/52861184477bee99c71552000311a289e91d3b59/packages/ui/src/elements/Card/CardFooter.tsx
|
||||
// https://github.com/clerk/javascript/blob/52861184477bee99c71552000311a289e91d3b59/packages/ui/src/elements/Card/CardClerkAndPagesTag.tsx
|
||||
// https://github.com/clerk/javascript/blob/52861184477bee99c71552000311a289e91d3b59/packages/ui/src/elements/DevModeNotice.tsx
|
||||
export function DesktopClerkCard({
|
||||
children,
|
||||
footerAction,
|
||||
}: {
|
||||
children: ReactNode;
|
||||
footerAction?: ReactNode;
|
||||
}) {
|
||||
return (
|
||||
<div className="isolate w-full max-w-[25rem] overflow-hidden rounded-xl border border-border/80 bg-card text-card-foreground shadow-[0_12px_28px_rgba(0,0,0,0.12)]">
|
||||
<div className="relative -m-px flex flex-col gap-8 rounded-lg border border-border/80 bg-card px-10 py-8 text-center">
|
||||
{children}
|
||||
</div>
|
||||
<div className="-mt-2 flex flex-col bg-muted/45 pt-2">
|
||||
{footerAction ? (
|
||||
<div className="border-t border-border/70 px-8 py-4">{footerAction}</div>
|
||||
) : null}
|
||||
<DesktopClerkBranding />
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function DesktopClerkHeader({ title, subtitle }: { title: string; subtitle: string }) {
|
||||
return (
|
||||
<div className="space-y-1">
|
||||
<h2 className="text-xl font-bold tracking-[-0.025em] text-foreground">{title}</h2>
|
||||
<p className="text-sm leading-5 text-muted-foreground">{subtitle}</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function DesktopClerkFooterAction({
|
||||
children,
|
||||
actionLabel,
|
||||
onAction,
|
||||
}: {
|
||||
children: ReactNode;
|
||||
actionLabel: string;
|
||||
onAction: () => void;
|
||||
}) {
|
||||
return (
|
||||
<p className="flex items-center justify-center gap-1 text-sm text-muted-foreground">
|
||||
<span>{children}</span>
|
||||
<button
|
||||
type="button"
|
||||
className="cursor-pointer font-semibold text-foreground outline-none hover:underline focus-visible:underline"
|
||||
onClick={onAction}
|
||||
>
|
||||
{actionLabel}
|
||||
</button>
|
||||
</p>
|
||||
);
|
||||
}
|
||||
|
||||
export function DesktopClerkAlert({ children }: { children?: ReactNode }) {
|
||||
if (!children) return null;
|
||||
|
||||
return (
|
||||
<div
|
||||
role="alert"
|
||||
className="rounded-md border border-destructive/20 bg-destructive/8 px-3 py-2 text-left text-xs leading-5 text-destructive-foreground"
|
||||
>
|
||||
{children}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function DesktopClerkInput({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentPropsWithoutRef<"input">) {
|
||||
return (
|
||||
<input
|
||||
{...props}
|
||||
className={cn(
|
||||
"h-10 w-full rounded-md border border-input bg-background px-3 text-sm text-foreground shadow-xs outline-none placeholder:text-muted-foreground/80 focus:border-ring focus:ring-2 focus:ring-ring/15 disabled:opacity-64",
|
||||
className,
|
||||
)}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
export function DesktopClerkPrimaryButton({
|
||||
children,
|
||||
disabled,
|
||||
}: {
|
||||
children: ReactNode;
|
||||
disabled?: boolean;
|
||||
}) {
|
||||
return (
|
||||
<button
|
||||
type="submit"
|
||||
disabled={disabled}
|
||||
className="h-10 w-full cursor-pointer rounded-md border border-neutral-950 bg-neutral-900 px-4 text-sm font-semibold text-white shadow-sm transition-colors hover:bg-neutral-800 disabled:pointer-events-none disabled:opacity-64 dark:border-neutral-200 dark:bg-neutral-100 dark:text-neutral-900 dark:hover:bg-white"
|
||||
>
|
||||
{children}
|
||||
</button>
|
||||
);
|
||||
}
|
||||
|
||||
function DesktopClerkBranding() {
|
||||
const isDevelopmentMode = import.meta.env.VITE_CLERK_PUBLISHABLE_KEY?.startsWith("pk_test_");
|
||||
|
||||
return (
|
||||
<div
|
||||
className={cn(
|
||||
"flex flex-col items-center justify-center gap-2 border-t border-border/70 px-8 py-4 text-xs text-muted-foreground",
|
||||
isDevelopmentMode &&
|
||||
"bg-[repeating-linear-gradient(-45deg,rgba(249,115,22,0.035),rgba(249,115,22,0.035)_8px,transparent_8px,transparent_16px)]",
|
||||
)}
|
||||
>
|
||||
<span>
|
||||
Secured by{" "}
|
||||
<a
|
||||
className="font-bold text-muted-foreground hover:text-foreground"
|
||||
href="https://go.clerk.com/components"
|
||||
rel="noreferrer"
|
||||
target="_blank"
|
||||
>
|
||||
clerk
|
||||
</a>
|
||||
</span>
|
||||
{isDevelopmentMode ? (
|
||||
<strong className="font-semibold text-orange-500">Development mode</strong>
|
||||
) : null}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,150 +0,0 @@
|
||||
import { LoaderCircleIcon } from "lucide-react";
|
||||
|
||||
import type {
|
||||
DesktopCloudAuthOAuthOption,
|
||||
DesktopCloudAuthOAuthStrategy,
|
||||
} from "../../cloud/desktopAuth";
|
||||
import { cn } from "../../lib/utils";
|
||||
import {
|
||||
DesktopClerkAlert,
|
||||
DesktopClerkCard,
|
||||
DesktopClerkFooterAction,
|
||||
DesktopClerkHeader,
|
||||
} from "./DesktopClerkCard";
|
||||
import { useDesktopClerkSignIn } from "./useDesktopClerkSignIn";
|
||||
|
||||
// Mirrors Clerk's compact social-button layout while delegating OAuth to the desktop bridge:
|
||||
// https://github.com/clerk/javascript/blob/52861184477bee99c71552000311a289e91d3b59/packages/ui/src/elements/SocialButtons.tsx
|
||||
export function DesktopClerkSignIn({ onJoinWaitlist }: { onJoinWaitlist: () => void }) {
|
||||
const { isStarting, oauthOptions, startingStrategy, startOAuth } = useDesktopClerkSignIn();
|
||||
|
||||
return (
|
||||
<DesktopClerkSignInCard
|
||||
isStarting={isStarting}
|
||||
oauthOptions={oauthOptions}
|
||||
startingStrategy={startingStrategy}
|
||||
onJoinWaitlist={onJoinWaitlist}
|
||||
onStartOAuth={(strategy) => void startOAuth(strategy)}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
export function DesktopClerkSignInCard({
|
||||
isStarting,
|
||||
oauthOptions,
|
||||
startingStrategy,
|
||||
onJoinWaitlist,
|
||||
onStartOAuth,
|
||||
}: {
|
||||
isStarting: boolean;
|
||||
oauthOptions: readonly DesktopCloudAuthOAuthOption[];
|
||||
startingStrategy: DesktopCloudAuthOAuthStrategy | null;
|
||||
onJoinWaitlist: () => void;
|
||||
onStartOAuth: (strategy: DesktopCloudAuthOAuthStrategy) => void;
|
||||
}) {
|
||||
return (
|
||||
<DesktopClerkCard
|
||||
footerAction={
|
||||
<DesktopClerkFooterAction actionLabel="Join waitlist" onAction={onJoinWaitlist}>
|
||||
Want early access?
|
||||
</DesktopClerkFooterAction>
|
||||
}
|
||||
>
|
||||
<DesktopClerkHeader
|
||||
title="Sign in to T3 Code"
|
||||
subtitle="Welcome back! Please sign in to continue"
|
||||
/>
|
||||
{oauthOptions.length === 0 ? (
|
||||
<DesktopClerkAlert>No OAuth providers are enabled for desktop sign-in.</DesktopClerkAlert>
|
||||
) : (
|
||||
<DesktopClerkSocialButtons
|
||||
isStarting={isStarting}
|
||||
oauthOptions={oauthOptions}
|
||||
startingStrategy={startingStrategy}
|
||||
onStartOAuth={onStartOAuth}
|
||||
/>
|
||||
)}
|
||||
</DesktopClerkCard>
|
||||
);
|
||||
}
|
||||
|
||||
function DesktopClerkSocialButtons({
|
||||
isStarting,
|
||||
oauthOptions,
|
||||
startingStrategy,
|
||||
onStartOAuth,
|
||||
}: {
|
||||
isStarting: boolean;
|
||||
oauthOptions: readonly DesktopCloudAuthOAuthOption[];
|
||||
startingStrategy: DesktopCloudAuthOAuthStrategy | null;
|
||||
onStartOAuth: (strategy: DesktopCloudAuthOAuthStrategy) => void;
|
||||
}) {
|
||||
const useBlockButtons = oauthOptions.length <= 2;
|
||||
|
||||
return (
|
||||
<div className={cn("grid gap-2", useBlockButtons ? "grid-cols-1" : "grid-cols-3")}>
|
||||
{oauthOptions.map((option) => {
|
||||
const isCurrent = option.strategy === startingStrategy;
|
||||
return (
|
||||
<button
|
||||
key={option.strategy}
|
||||
type="button"
|
||||
aria-label={`Continue with ${option.label}`}
|
||||
className={cn(
|
||||
"flex h-10 cursor-pointer items-center justify-center rounded-md border border-input bg-popover px-3 text-sm font-semibold text-foreground shadow-xs outline-none transition-colors hover:bg-accent/50 focus-visible:ring-2 focus-visible:ring-ring/20 disabled:pointer-events-none disabled:opacity-64",
|
||||
useBlockButtons && "w-full",
|
||||
)}
|
||||
disabled={isStarting}
|
||||
onClick={() => onStartOAuth(option.strategy)}
|
||||
>
|
||||
<span
|
||||
className={cn(
|
||||
"flex min-w-0 items-center justify-center gap-3",
|
||||
useBlockButtons && "w-full",
|
||||
)}
|
||||
>
|
||||
{isCurrent ? (
|
||||
<LoaderCircleIcon className="size-4 animate-spin opacity-70" />
|
||||
) : (
|
||||
<DesktopClerkProviderIcon option={option} />
|
||||
)}
|
||||
{useBlockButtons ? (
|
||||
<span className="truncate">
|
||||
{oauthOptions.length === 1 ? `Continue with ${option.label}` : option.label}
|
||||
</span>
|
||||
) : null}
|
||||
</span>
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function DesktopClerkProviderIcon({ option }: { option: DesktopCloudAuthOAuthOption }) {
|
||||
if (!option.iconUrl) {
|
||||
return (
|
||||
<span
|
||||
aria-hidden
|
||||
className="flex size-4 shrink-0 items-center justify-center rounded bg-muted text-[9px] font-bold text-muted-foreground"
|
||||
>
|
||||
{option.label.slice(0, 1).toUpperCase()}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
if (["apple", "github", "vercel"].includes(option.providerId)) {
|
||||
return (
|
||||
<span
|
||||
aria-hidden
|
||||
className="size-4 shrink-0 bg-foreground"
|
||||
style={{
|
||||
WebkitMask: `url(${option.iconUrl}) center / cover no-repeat`,
|
||||
mask: `url(${option.iconUrl}) center / cover no-repeat`,
|
||||
}}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
return <img alt="" aria-hidden className="size-4 shrink-0" src={option.iconUrl} />;
|
||||
}
|
||||
@@ -1,106 +0,0 @@
|
||||
import { useClerk } from "@clerk/react";
|
||||
import { useState } from "react";
|
||||
|
||||
import {
|
||||
DesktopClerkAlert,
|
||||
DesktopClerkCard,
|
||||
DesktopClerkFooterAction,
|
||||
DesktopClerkHeader,
|
||||
DesktopClerkInput,
|
||||
DesktopClerkPrimaryButton,
|
||||
} from "./DesktopClerkCard";
|
||||
import { DesktopClerkSignIn } from "./DesktopClerkSignIn";
|
||||
|
||||
type DesktopClerkScreen = "waitlist" | "sign-in";
|
||||
|
||||
// Mirrors Clerk's waitlist card and form, replacing its router transition with the desktop sign-in flow:
|
||||
// https://github.com/clerk/javascript/blob/52861184477bee99c71552000311a289e91d3b59/packages/ui/src/components/Waitlist/index.tsx
|
||||
// https://github.com/clerk/javascript/blob/52861184477bee99c71552000311a289e91d3b59/packages/ui/src/components/Waitlist/WaitlistForm.tsx
|
||||
export function DesktopClerkWaitlist() {
|
||||
const [screen, setScreen] = useState<DesktopClerkScreen>("waitlist");
|
||||
|
||||
if (screen === "sign-in") {
|
||||
return <DesktopClerkSignIn onJoinWaitlist={() => setScreen("waitlist")} />;
|
||||
}
|
||||
|
||||
return <DesktopClerkWaitlistForm onSignIn={() => setScreen("sign-in")} />;
|
||||
}
|
||||
|
||||
function DesktopClerkWaitlistForm({ onSignIn }: { onSignIn: () => void }) {
|
||||
const clerk = useClerk();
|
||||
const [emailAddress, setEmailAddress] = useState("");
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [isSubmitting, setIsSubmitting] = useState(false);
|
||||
const [didJoin, setDidJoin] = useState(false);
|
||||
|
||||
const submitWaitlist = async (event: React.FormEvent<HTMLFormElement>) => {
|
||||
event.preventDefault();
|
||||
setError(null);
|
||||
setIsSubmitting(true);
|
||||
try {
|
||||
await clerk.joinWaitlist({ emailAddress });
|
||||
setDidJoin(true);
|
||||
} catch (cause) {
|
||||
setError(getClerkErrorMessage(cause));
|
||||
} finally {
|
||||
setIsSubmitting(false);
|
||||
}
|
||||
};
|
||||
|
||||
if (didJoin) {
|
||||
return (
|
||||
<DesktopClerkCard>
|
||||
<DesktopClerkHeader
|
||||
title="Thanks for joining the waitlist!"
|
||||
subtitle="We’ll be in touch when your spot is ready"
|
||||
/>
|
||||
</DesktopClerkCard>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<DesktopClerkCard
|
||||
footerAction={
|
||||
<DesktopClerkFooterAction actionLabel="Sign in" onAction={onSignIn}>
|
||||
Already have access?
|
||||
</DesktopClerkFooterAction>
|
||||
}
|
||||
>
|
||||
<DesktopClerkHeader
|
||||
title="Join the waitlist"
|
||||
subtitle="Enter your email address and we’ll let you know when your spot is ready"
|
||||
/>
|
||||
<DesktopClerkAlert>{error}</DesktopClerkAlert>
|
||||
<form className="space-y-8 text-left" onSubmit={submitWaitlist}>
|
||||
<label className="block space-y-2" htmlFor="desktop-clerk-waitlist-email">
|
||||
<span className="text-sm font-semibold text-foreground">Email address</span>
|
||||
<DesktopClerkInput
|
||||
required
|
||||
autoComplete="email"
|
||||
id="desktop-clerk-waitlist-email"
|
||||
name="emailAddress"
|
||||
placeholder="Enter your email address"
|
||||
type="email"
|
||||
value={emailAddress}
|
||||
onChange={(event) => setEmailAddress(event.currentTarget.value)}
|
||||
/>
|
||||
</label>
|
||||
<DesktopClerkPrimaryButton disabled={isSubmitting}>
|
||||
{isSubmitting ? "Joining the waitlist…" : "Join the waitlist"}
|
||||
</DesktopClerkPrimaryButton>
|
||||
</form>
|
||||
</DesktopClerkCard>
|
||||
);
|
||||
}
|
||||
|
||||
function getClerkErrorMessage(error: unknown): string {
|
||||
if (typeof error === "object" && error !== null && "errors" in error) {
|
||||
const errors = (error as { errors?: Array<{ longMessage?: unknown; message?: unknown }> })
|
||||
.errors;
|
||||
const firstError = errors?.[0];
|
||||
if (typeof firstError?.longMessage === "string") return firstError.longMessage;
|
||||
if (typeof firstError?.message === "string") return firstError.message;
|
||||
}
|
||||
if (error instanceof Error && error.message) return error.message;
|
||||
return "Could not join the waitlist. Please try again.";
|
||||
}
|
||||
@@ -1,199 +0,0 @@
|
||||
import { useClerk } from "@clerk/react";
|
||||
import { useSignIn, useSignUp } from "@clerk/react/legacy";
|
||||
import { useCallback, useEffect, useRef, useState } from "react";
|
||||
|
||||
import {
|
||||
type DesktopCloudAuthOAuthStrategy,
|
||||
resolveDesktopCloudAuthOAuthOptions,
|
||||
} from "../../cloud/desktopAuth";
|
||||
import { toastManager } from "../ui/toast";
|
||||
|
||||
// Mirrors Clerk Expo's browser-based native SSO flow, with Electron handling the external browser
|
||||
// and callback transport:
|
||||
// https://github.com/clerk/javascript/blob/52861184477bee99c71552000311a289e91d3b59/packages/expo/src/hooks/useSSO.ts
|
||||
class DesktopClerkOperationError extends Error {
|
||||
override readonly cause?: unknown;
|
||||
|
||||
constructor(message: string, cause?: unknown) {
|
||||
super(message);
|
||||
this.name = "DesktopClerkOperationError";
|
||||
this.cause = cause;
|
||||
}
|
||||
}
|
||||
|
||||
async function runDesktopClerkOperation<T>(
|
||||
operation: () => Promise<T>,
|
||||
message: string,
|
||||
): Promise<T> {
|
||||
try {
|
||||
return await operation();
|
||||
} catch (cause) {
|
||||
throw new DesktopClerkOperationError(message, cause);
|
||||
}
|
||||
}
|
||||
|
||||
function desktopClerkErrorMessage(error: unknown, fallback: string): string {
|
||||
if (error instanceof DesktopClerkOperationError) {
|
||||
const cause = error.cause;
|
||||
if (cause instanceof Error && cause.message && cause.message !== error.message) {
|
||||
return `${error.message}: ${cause.message}`;
|
||||
}
|
||||
return error.message;
|
||||
}
|
||||
return error instanceof Error ? error.message : fallback;
|
||||
}
|
||||
|
||||
export function useDesktopClerkSignIn() {
|
||||
const clerk = useClerk();
|
||||
const { setActive } = clerk;
|
||||
const { isLoaded: signInLoaded, signIn } = useSignIn();
|
||||
const { isLoaded: signUpLoaded, signUp } = useSignUp();
|
||||
const [startingStrategy, setStartingStrategy] = useState<DesktopCloudAuthOAuthStrategy | null>(
|
||||
null,
|
||||
);
|
||||
const oauthOptions = resolveDesktopCloudAuthOAuthOptions(clerk);
|
||||
const callbackCleanupRef = useRef<(() => void) | null>(null);
|
||||
|
||||
const clearCallbackListener = useCallback(() => {
|
||||
callbackCleanupRef.current?.();
|
||||
callbackCleanupRef.current = null;
|
||||
}, []);
|
||||
|
||||
const completeOAuthCallback = useCallback(
|
||||
async (rawUrl: string) => {
|
||||
if (!signInLoaded || !signIn || !signUpLoaded || !signUp) {
|
||||
toastManager.add({
|
||||
type: "error",
|
||||
title: "Cloud sign-in failed",
|
||||
description: "Clerk is still loading. Try signing in again.",
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
let rotatingTokenNonce: string | null = null;
|
||||
let sessionId: string | null = null;
|
||||
try {
|
||||
const callbackUrl = new URL(rawUrl);
|
||||
rotatingTokenNonce = callbackUrl.searchParams.get("rotating_token_nonce");
|
||||
sessionId = callbackUrl.searchParams.get("created_session_id");
|
||||
} catch {
|
||||
// Handled by the explicit nonce check below.
|
||||
}
|
||||
if (!rotatingTokenNonce) {
|
||||
toastManager.add({
|
||||
type: "error",
|
||||
title: "Cloud sign-in failed",
|
||||
description:
|
||||
"Clerk did not return a native session nonce. Verify this redirect URL is allowlisted for native SSO redirects.",
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
await runDesktopClerkOperation(
|
||||
() => signIn.reload({ rotatingTokenNonce }),
|
||||
"Could not reload the desktop sign-in session.",
|
||||
);
|
||||
sessionId = sessionId || signIn.createdSessionId;
|
||||
|
||||
if (!sessionId && signIn.firstFactorVerification.status === "transferable") {
|
||||
const signUpAttempt = await runDesktopClerkOperation(
|
||||
() => signUp.create({ transfer: true }),
|
||||
"Could not transfer the desktop sign-up session.",
|
||||
);
|
||||
sessionId = signUpAttempt.createdSessionId;
|
||||
}
|
||||
|
||||
if (!sessionId) {
|
||||
throw new DesktopClerkOperationError("Clerk did not create a desktop session.");
|
||||
}
|
||||
|
||||
await runDesktopClerkOperation(
|
||||
() => setActive({ session: sessionId! }),
|
||||
"Could not activate the desktop cloud session.",
|
||||
);
|
||||
} catch (error) {
|
||||
toastManager.add({
|
||||
type: "error",
|
||||
title: "Cloud sign-in failed",
|
||||
description: desktopClerkErrorMessage(error, "Could not complete cloud sign-in."),
|
||||
});
|
||||
}
|
||||
},
|
||||
[setActive, signIn, signInLoaded, signUp, signUpLoaded],
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
return () => {
|
||||
clearCallbackListener();
|
||||
};
|
||||
}, [clearCallbackListener]);
|
||||
|
||||
const startOAuth = useCallback(
|
||||
async (strategy: DesktopCloudAuthOAuthStrategy) => {
|
||||
if (!signInLoaded || !signIn) {
|
||||
toastManager.add({
|
||||
type: "error",
|
||||
title: "Cloud sign-in failed",
|
||||
description: "Clerk is still loading. Try signing in again.",
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
setStartingStrategy(strategy);
|
||||
clearCallbackListener();
|
||||
try {
|
||||
const redirectUrl = await runDesktopClerkOperation(
|
||||
() => window.desktopBridge?.createCloudAuthRequest() ?? Promise.resolve(undefined),
|
||||
"Desktop auth callback is unavailable.",
|
||||
);
|
||||
if (!redirectUrl) {
|
||||
throw new DesktopClerkOperationError("Desktop auth callback is unavailable.");
|
||||
}
|
||||
|
||||
callbackCleanupRef.current =
|
||||
window.desktopBridge?.onCloudAuthCallback((rawUrl) => {
|
||||
clearCallbackListener();
|
||||
void completeOAuthCallback(rawUrl);
|
||||
}) ?? null;
|
||||
|
||||
await runDesktopClerkOperation(
|
||||
() => signIn.create({ strategy, redirectUrl } as never),
|
||||
"Could not create the desktop OAuth request.",
|
||||
);
|
||||
const externalUrl =
|
||||
signIn.firstFactorVerification.externalVerificationRedirectURL?.toString();
|
||||
if (!externalUrl) {
|
||||
throw new DesktopClerkOperationError(
|
||||
"Clerk did not return an external OAuth redirect URL.",
|
||||
);
|
||||
}
|
||||
|
||||
const opened = await runDesktopClerkOperation(
|
||||
() => window.desktopBridge?.openExternal(externalUrl) ?? Promise.resolve(false),
|
||||
"Could not open the system browser.",
|
||||
);
|
||||
if (!opened) {
|
||||
throw new DesktopClerkOperationError("Could not open the system browser.");
|
||||
}
|
||||
} catch (error) {
|
||||
clearCallbackListener();
|
||||
toastManager.add({
|
||||
type: "error",
|
||||
title: "Cloud sign-in failed",
|
||||
description: desktopClerkErrorMessage(error, "Could not start cloud sign-in."),
|
||||
});
|
||||
} finally {
|
||||
setStartingStrategy(null);
|
||||
}
|
||||
},
|
||||
[clearCallbackListener, completeOAuthCallback, signIn, signInLoaded],
|
||||
);
|
||||
|
||||
return {
|
||||
isStarting: startingStrategy !== null,
|
||||
oauthOptions,
|
||||
startingStrategy,
|
||||
startOAuth,
|
||||
};
|
||||
}
|
||||
@@ -1,29 +1,9 @@
|
||||
import { useClerk } from "@clerk/react";
|
||||
import { useState } from "react";
|
||||
|
||||
import { isElectron } from "../../env";
|
||||
import { Dialog, DialogPopup } from "../ui/dialog";
|
||||
import { DesktopClerkWaitlist } from "./DesktopClerkWaitlist";
|
||||
|
||||
export function useT3ConnectAuthPrompt() {
|
||||
const clerk = useClerk();
|
||||
const [desktopAuthOpen, setDesktopAuthOpen] = useState(false);
|
||||
|
||||
const openAuthPrompt = () => {
|
||||
if (isElectron) {
|
||||
setDesktopAuthOpen(true);
|
||||
return;
|
||||
}
|
||||
clerk.openWaitlist();
|
||||
};
|
||||
|
||||
const authPrompt = isElectron ? (
|
||||
<Dialog open={desktopAuthOpen} onOpenChange={setDesktopAuthOpen}>
|
||||
<DialogPopup className="max-w-md border-0 bg-transparent shadow-none" showCloseButton={false}>
|
||||
<DesktopClerkWaitlist />
|
||||
</DialogPopup>
|
||||
</Dialog>
|
||||
) : null;
|
||||
|
||||
return { authPrompt, openAuthPrompt };
|
||||
return { authPrompt: null, openAuthPrompt };
|
||||
}
|
||||
@@ -3,6 +3,7 @@ import {
|
||||
CloudSession,
|
||||
EnvironmentOwnedDataCleanup,
|
||||
PlatformConnectionSource,
|
||||
PrimaryEnvironmentAuth,
|
||||
RelayDeviceIdentity,
|
||||
SshEnvironmentGateway,
|
||||
} from "@t3tools/client-runtime/platform";
|
||||
@@ -30,9 +31,9 @@ import * as Option from "effect/Option";
|
||||
import * as Queue from "effect/Queue";
|
||||
import * as Schedule from "effect/Schedule";
|
||||
import * as Stream from "effect/Stream";
|
||||
import { FetchHttpClient, HttpClient } from "effect/unstable/http";
|
||||
|
||||
import { primaryEnvironmentRequestInit } from "../environments/primary/requestInit";
|
||||
import { readDesktopPrimaryBearerToken } from "../environments/primary/desktopAuth";
|
||||
import { primaryEnvironmentHttpLayer } from "../environments/primary/httpLayer";
|
||||
import { readPrimaryEnvironmentTarget } from "../environments/primary/target";
|
||||
import { clearComposerDraftsEnvironment } from "../composerDraftStore";
|
||||
import { isHostedStaticApp } from "../hostedPairing";
|
||||
@@ -193,6 +194,16 @@ const capabilitiesLayer = Layer.effectContext(
|
||||
const identity = RelayDeviceIdentity.of({
|
||||
deviceId: Effect.succeed(Option.none()),
|
||||
});
|
||||
const primaryAuth = PrimaryEnvironmentAuth.of({
|
||||
bearerToken: Effect.tryPromise({
|
||||
try: readDesktopPrimaryBearerToken,
|
||||
catch: (cause) =>
|
||||
new ConnectionTransientError({
|
||||
reason: "remote-unavailable",
|
||||
message: `Could not load the desktop primary credential: ${String(cause)}`,
|
||||
}),
|
||||
}).pipe(Effect.map(Option.fromNullishOr)),
|
||||
});
|
||||
const ssh = SshEnvironmentGateway.of({
|
||||
provision: Effect.fn("web.connectionPlatform.ssh.provision")(function* (target) {
|
||||
const bridge = window.desktopBridge;
|
||||
@@ -252,6 +263,7 @@ const capabilitiesLayer = Layer.effectContext(
|
||||
});
|
||||
|
||||
return Context.make(CloudSession, cloudSession).pipe(
|
||||
Context.add(PrimaryEnvironmentAuth, primaryAuth),
|
||||
Context.add(RelayDeviceIdentity, identity),
|
||||
Context.add(ClientPresentation, presentation),
|
||||
Context.add(SshEnvironmentGateway, ssh),
|
||||
@@ -271,10 +283,7 @@ const loadPrimaryConnectionRegistration = Effect.fn(
|
||||
}
|
||||
const descriptor = yield* fetchRemoteEnvironmentDescriptor({
|
||||
httpBaseUrl: resolved.target.httpBaseUrl,
|
||||
}).pipe(
|
||||
Effect.provideService(FetchHttpClient.RequestInit, primaryEnvironmentRequestInit),
|
||||
Effect.mapError(mapRemoteEnvironmentError),
|
||||
);
|
||||
}).pipe(Effect.provide(primaryEnvironmentHttpLayer), Effect.mapError(mapRemoteEnvironmentError));
|
||||
return new PrimaryConnectionRegistration({
|
||||
target: new PrimaryConnectionTarget({
|
||||
environmentId: descriptor.environmentId,
|
||||
@@ -289,32 +298,24 @@ const primaryRegistrationRetrySchedule = Schedule.exponential("1 second").pipe(
|
||||
Schedule.either(Schedule.spaced("16 seconds")),
|
||||
);
|
||||
|
||||
const platformConnectionSourceLayer = Layer.effect(
|
||||
PlatformConnectionSource,
|
||||
Effect.gen(function* () {
|
||||
if (isHostedStaticApp()) {
|
||||
return PlatformConnectionSource.of({
|
||||
registrations: Stream.empty,
|
||||
});
|
||||
}
|
||||
const httpClient = yield* HttpClient.HttpClient;
|
||||
const platformConnectionSourceLayer = Layer.sync(PlatformConnectionSource, () => {
|
||||
if (isHostedStaticApp()) {
|
||||
return PlatformConnectionSource.of({
|
||||
registrations: Stream.fromEffect(
|
||||
loadPrimaryConnectionRegistration().pipe(
|
||||
Effect.provideService(HttpClient.HttpClient, httpClient),
|
||||
),
|
||||
).pipe(
|
||||
Stream.tapError((error) =>
|
||||
Effect.logWarning("Could not discover the primary environment.", {
|
||||
error,
|
||||
}),
|
||||
),
|
||||
Stream.retry(primaryRegistrationRetrySchedule),
|
||||
Stream.catchCause(() => Stream.empty),
|
||||
),
|
||||
registrations: Stream.empty,
|
||||
});
|
||||
}),
|
||||
);
|
||||
}
|
||||
return PlatformConnectionSource.of({
|
||||
registrations: Stream.fromEffect(loadPrimaryConnectionRegistration()).pipe(
|
||||
Stream.tapError((error) =>
|
||||
Effect.logWarning("Could not discover the primary environment.", {
|
||||
error,
|
||||
}),
|
||||
),
|
||||
Stream.retry(primaryRegistrationRetrySchedule),
|
||||
Stream.catchCause(() => Stream.empty),
|
||||
),
|
||||
});
|
||||
});
|
||||
|
||||
const environmentOwnedDataCleanupLayer = Layer.succeed(
|
||||
EnvironmentOwnedDataCleanup,
|
||||
|
||||
@@ -0,0 +1,33 @@
|
||||
import type { DesktopBridge } from "@t3tools/contracts";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "@effect/vitest";
|
||||
|
||||
import { __resetDesktopPrimaryAuthForTests, readDesktopPrimaryBearerToken } from "./desktopAuth";
|
||||
|
||||
describe("desktop primary auth", () => {
|
||||
beforeEach(() => {
|
||||
Object.defineProperty(globalThis, "window", {
|
||||
configurable: true,
|
||||
value: {},
|
||||
});
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
__resetDesktopPrimaryAuthForTests();
|
||||
Reflect.deleteProperty(globalThis, "window");
|
||||
});
|
||||
|
||||
it("reuses the main-process bearer token across renderer requests", async () => {
|
||||
const getLocalEnvironmentBearerToken = vi.fn().mockResolvedValue("desktop-bearer-token");
|
||||
window.desktopBridge = {
|
||||
getLocalEnvironmentBearerToken,
|
||||
} as unknown as DesktopBridge;
|
||||
|
||||
await expect(readDesktopPrimaryBearerToken()).resolves.toBe("desktop-bearer-token");
|
||||
await expect(readDesktopPrimaryBearerToken()).resolves.toBe("desktop-bearer-token");
|
||||
expect(getLocalEnvironmentBearerToken).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("does not require desktop auth in a browser", async () => {
|
||||
await expect(readDesktopPrimaryBearerToken()).resolves.toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,21 @@
|
||||
let desktopBearerTokenPromise: Promise<string> | null = null;
|
||||
|
||||
export function readDesktopPrimaryBearerToken(): Promise<string | null> {
|
||||
if (typeof window === "undefined") {
|
||||
return Promise.resolve(null);
|
||||
}
|
||||
const bridge = window.desktopBridge;
|
||||
if (!bridge) {
|
||||
return Promise.resolve(null);
|
||||
}
|
||||
|
||||
desktopBearerTokenPromise ??= bridge.getLocalEnvironmentBearerToken().catch((error) => {
|
||||
desktopBearerTokenPromise = null;
|
||||
throw error;
|
||||
});
|
||||
return desktopBearerTokenPromise;
|
||||
}
|
||||
|
||||
export function __resetDesktopPrimaryAuthForTests(): void {
|
||||
desktopBearerTokenPromise = null;
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
import type { DesktopBridge } from "@t3tools/contracts";
|
||||
import { afterEach, describe, expect, it, vi } from "@effect/vitest";
|
||||
import * as Effect from "effect/Effect";
|
||||
import { HttpClient } from "effect/unstable/http";
|
||||
|
||||
import { __resetDesktopPrimaryAuthForTests } from "./desktopAuth";
|
||||
import { makePrimaryEnvironmentHttpLayer } from "./httpLayer";
|
||||
|
||||
describe.sequential("primary environment HTTP layer", () => {
|
||||
afterEach(() => {
|
||||
__resetDesktopPrimaryAuthForTests();
|
||||
Reflect.deleteProperty(globalThis, "window");
|
||||
vi.unstubAllGlobals();
|
||||
});
|
||||
|
||||
it.effect("uses cookie credentials for browser primary environments", () => {
|
||||
const fetchMock = vi.fn().mockResolvedValue(new Response(null, { status: 200 }));
|
||||
vi.stubGlobal("fetch", fetchMock);
|
||||
Object.defineProperty(globalThis, "window", {
|
||||
configurable: true,
|
||||
value: {
|
||||
location: {
|
||||
href: "http://127.0.0.1:3773/settings",
|
||||
origin: "http://127.0.0.1:3773",
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
return Effect.gen(function* () {
|
||||
yield* HttpClient.get("http://127.0.0.1:3773/api/auth/session");
|
||||
|
||||
const request = new Request(fetchMock.mock.calls[0]?.[0], fetchMock.mock.calls[0]?.[1]);
|
||||
expect(request.credentials).toBe("include");
|
||||
expect(request.headers.get("authorization")).toBeNull();
|
||||
}).pipe(Effect.provide(makePrimaryEnvironmentHttpLayer()));
|
||||
});
|
||||
|
||||
it.effect("uses bearer auth without cookies for desktop-managed primaries", () => {
|
||||
const fetchMock = vi.fn().mockResolvedValue(new Response(null, { status: 200 }));
|
||||
vi.stubGlobal("fetch", fetchMock);
|
||||
Object.defineProperty(globalThis, "window", {
|
||||
configurable: true,
|
||||
value: {
|
||||
location: { origin: "t3code://app" },
|
||||
desktopBridge: {
|
||||
getLocalEnvironmentBootstrap: () => ({
|
||||
label: "Local environment",
|
||||
httpBaseUrl: "http://127.0.0.1:3773",
|
||||
wsBaseUrl: "ws://127.0.0.1:3773",
|
||||
bootstrapToken: "desktop-bootstrap-token",
|
||||
}),
|
||||
getLocalEnvironmentBearerToken: vi.fn().mockResolvedValue("desktop-bearer-token"),
|
||||
} as unknown as DesktopBridge,
|
||||
},
|
||||
});
|
||||
|
||||
return Effect.gen(function* () {
|
||||
yield* HttpClient.get("http://127.0.0.1:3773/api/connect/link-state");
|
||||
|
||||
const request = new Request(fetchMock.mock.calls[0]?.[0], fetchMock.mock.calls[0]?.[1]);
|
||||
expect(request.credentials).not.toBe("include");
|
||||
expect(request.headers.get("authorization")).toBe("Bearer desktop-bearer-token");
|
||||
}).pipe(Effect.provide(makePrimaryEnvironmentHttpLayer()));
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,58 @@
|
||||
import { remoteHttpClientLayer } from "@t3tools/client-runtime/rpc";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import { FetchHttpClient, HttpClient, HttpClientRequest } from "effect/unstable/http";
|
||||
|
||||
import { readDesktopPrimaryBearerToken } from "./desktopAuth";
|
||||
import { resolvePrimaryEnvironmentHttpUrl } from "./target";
|
||||
|
||||
function isSameOriginBrowserPrimary(): boolean {
|
||||
if (
|
||||
typeof window === "undefined" ||
|
||||
window.desktopBridge !== undefined ||
|
||||
window.nativeApi !== undefined ||
|
||||
!window.location.origin.startsWith("http")
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return new URL(resolvePrimaryEnvironmentHttpUrl("/")).origin === window.location.origin;
|
||||
}
|
||||
|
||||
function withPrimaryBearerToken(client: HttpClient.HttpClient): HttpClient.HttpClient {
|
||||
return client.pipe(
|
||||
HttpClient.mapRequestEffect((request) =>
|
||||
Effect.promise(readDesktopPrimaryBearerToken).pipe(
|
||||
Effect.map((bearerToken) =>
|
||||
bearerToken ? HttpClientRequest.bearerToken(request, bearerToken) : request,
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
export function makePrimaryEnvironmentHttpLayer() {
|
||||
return Layer.unwrap(
|
||||
Effect.sync(() => {
|
||||
const baseLayer = remoteHttpClientLayer(globalThis.fetch);
|
||||
if (isSameOriginBrowserPrimary()) {
|
||||
return Layer.merge(
|
||||
baseLayer,
|
||||
Layer.succeed(FetchHttpClient.RequestInit, { credentials: "include" }),
|
||||
);
|
||||
}
|
||||
|
||||
const bearerClientLayer = Layer.effect(
|
||||
HttpClient.HttpClient,
|
||||
Effect.map(HttpClient.HttpClient, withPrimaryBearerToken),
|
||||
).pipe(Layer.provide(baseLayer));
|
||||
|
||||
return Layer.merge(
|
||||
bearerClientLayer,
|
||||
Layer.succeed(FetchHttpClient.RequestInit, { credentials: "omit" }),
|
||||
);
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
export const primaryEnvironmentHttpLayer = makePrimaryEnvironmentHttpLayer();
|
||||
@@ -33,6 +33,8 @@ export {
|
||||
|
||||
export { refreshPrimarySessionState, usePrimarySessionState } from "./sessionState";
|
||||
|
||||
export { PrimaryEnvironmentHttpClient } from "./httpClient";
|
||||
|
||||
export {
|
||||
readPrimaryEnvironmentTarget,
|
||||
resolvePrimaryEnvironmentHttpUrl,
|
||||
|
||||
@@ -1,7 +0,0 @@
|
||||
import * as Effect from "effect/Effect";
|
||||
import { FetchHttpClient } from "effect/unstable/http";
|
||||
|
||||
export const primaryEnvironmentRequestInit = { credentials: "include" } as const;
|
||||
|
||||
export const withPrimaryEnvironmentRequestInit = <A, E, R>(effect: Effect.Effect<A, E, R>) =>
|
||||
effect.pipe(Effect.provideService(FetchHttpClient.RequestInit, primaryEnvironmentRequestInit));
|
||||
@@ -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>(
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
import React from "react";
|
||||
import ReactDOM from "react-dom/client";
|
||||
import { ClerkProvider } from "@clerk/react";
|
||||
import { passkeys } from "@clerk/electron/passkeys";
|
||||
import { ClerkProvider as ElectronClerkProvider } from "@clerk/electron/react";
|
||||
import { createHashHistory, createBrowserHistory } from "@tanstack/react-router";
|
||||
|
||||
import "@fontsource-variable/dm-sans/index.css";
|
||||
@@ -10,7 +12,6 @@ import "@xterm/xterm/css/xterm.css";
|
||||
import "./index.css";
|
||||
|
||||
import { isElectron } from "./env";
|
||||
import { DesktopClerkProvider } from "./cloud/desktopClerk";
|
||||
import { ManagedRelayAuthProvider } from "./cloud/managedAuth";
|
||||
import { hasCloudPublicConfig } from "./cloud/publicConfig";
|
||||
import { getRouter } from "./router";
|
||||
@@ -37,9 +38,9 @@ ReactDOM.createRoot(document.getElementById("root") as HTMLElement).render(
|
||||
<React.StrictMode>
|
||||
{clerkPublishableKey && hasCloudPublicConfig() ? (
|
||||
isElectron ? (
|
||||
<DesktopClerkProvider publishableKey={clerkPublishableKey}>
|
||||
<ElectronClerkProvider publishableKey={clerkPublishableKey} passkeys={passkeys}>
|
||||
<ManagedRelayAuthProvider>{app}</ManagedRelayAuthProvider>
|
||||
</DesktopClerkProvider>
|
||||
</ElectronClerkProvider>
|
||||
) : (
|
||||
<ClerkProvider publishableKey={clerkPublishableKey}>
|
||||
<ManagedRelayAuthProvider>{app}</ManagedRelayAuthProvider>
|
||||
|
||||
@@ -3,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),
|
||||
);
|
||||
|
||||
@@ -126,6 +126,7 @@ export default defineConfig(() => {
|
||||
},
|
||||
resolve: {
|
||||
tsconfigPaths: true,
|
||||
dedupe: ["react", "react-dom"],
|
||||
},
|
||||
server: {
|
||||
host,
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -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.
|
||||
@@ -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:
|
||||
|
||||
@@ -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`.
|
||||
|
||||
@@ -9,7 +9,7 @@
|
||||
"typecheck": "tsgo --noEmit"
|
||||
},
|
||||
"dependencies": {
|
||||
"@clerk/backend": "3.6.1",
|
||||
"@clerk/backend": "catalog:",
|
||||
"@effect/sql-pg": "catalog:",
|
||||
"@t3tools/client-runtime": "workspace:*",
|
||||
"@t3tools/contracts": "workspace:*",
|
||||
|
||||
@@ -17,6 +17,7 @@ import { ConnectionResolver } from "./resolver.ts";
|
||||
import { connectionResolverLayer } from "./resolver.ts";
|
||||
import {
|
||||
CloudSession,
|
||||
PrimaryEnvironmentAuth,
|
||||
RelayDeviceIdentity,
|
||||
SshEnvironmentGateway,
|
||||
} from "../platform/capabilities.ts";
|
||||
@@ -101,6 +102,7 @@ const makeDependencies = Effect.fn("TestConnectionResolver.makeDependencies")((o
|
||||
readonly connectEnvironment?: ManagedRelayClient["Service"]["connectEnvironment"];
|
||||
readonly authorizeBearer?: RemoteEnvironmentAuthorization["Service"]["authorizeBearer"];
|
||||
readonly authorizeDpop?: RemoteEnvironmentAuthorization["Service"]["authorizeDpop"];
|
||||
readonly primaryBearerToken?: string;
|
||||
readonly prepareSsh?: SshEnvironmentGateway["Service"]["prepare"];
|
||||
}) => {
|
||||
const profiles = new Map(
|
||||
@@ -170,6 +172,12 @@ const makeDependencies = Effect.fn("TestConnectionResolver.makeDependencies")((o
|
||||
Layer.succeed(ConnectionProfileStore, profileStore),
|
||||
Layer.succeed(ConnectionCredentialStore, credentialStore),
|
||||
Layer.succeed(CloudSession, CloudSession.of({ clerkToken: Effect.succeed("clerk-session") })),
|
||||
Layer.succeed(
|
||||
PrimaryEnvironmentAuth,
|
||||
PrimaryEnvironmentAuth.of({
|
||||
bearerToken: Effect.succeed(Option.fromNullishOr(options?.primaryBearerToken)),
|
||||
}),
|
||||
),
|
||||
Layer.succeed(
|
||||
RelayDeviceIdentity,
|
||||
RelayDeviceIdentity.of({ deviceId: Effect.succeed(Option.some("device-1")) }),
|
||||
@@ -217,6 +225,42 @@ describe("ConnectionResolver", () => {
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("authorizes a desktop primary environment with its platform bearer token", () =>
|
||||
Effect.gen(function* () {
|
||||
const bearerInputs = yield* Ref.make<ReadonlyArray<string>>([]);
|
||||
const brokerLayer = yield* makeDependencies({
|
||||
primaryBearerToken: "desktop-bearer",
|
||||
authorizeBearer: (input) =>
|
||||
Ref.update(bearerInputs, (values) => [...values, input.bearerToken]).pipe(
|
||||
Effect.as({
|
||||
environmentId: input.expectedEnvironmentId,
|
||||
label: "Primary",
|
||||
httpBaseUrl: input.httpBaseUrl,
|
||||
socketUrl: "ws://127.0.0.1:3777/ws?wsTicket=desktop",
|
||||
httpAuthorization: {
|
||||
_tag: "Bearer" as const,
|
||||
token: input.bearerToken,
|
||||
},
|
||||
}),
|
||||
),
|
||||
});
|
||||
const broker = yield* ConnectionResolver.pipe(Effect.provide(brokerLayer));
|
||||
const target = new PrimaryConnectionTarget({
|
||||
environmentId: ENVIRONMENT_ID,
|
||||
label: "Primary",
|
||||
httpBaseUrl: "http://127.0.0.1:3777",
|
||||
wsBaseUrl: "ws://127.0.0.1:3777",
|
||||
});
|
||||
|
||||
expect(yield* broker.prepare(catalogEntry(target))).toMatchObject({
|
||||
socketUrl: "ws://127.0.0.1:3777/ws?wsTicket=desktop",
|
||||
httpAuthorization: { _tag: "Bearer", token: "desktop-bearer" },
|
||||
target,
|
||||
});
|
||||
expect(yield* Ref.get(bearerInputs)).toEqual(["desktop-bearer"]);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("uses the registered bearer profile without re-reading the profile store", () =>
|
||||
Effect.gen(function* () {
|
||||
const bearerInputs = yield* Ref.make<ReadonlyArray<string>>([]);
|
||||
|
||||
@@ -10,6 +10,7 @@ import { RemoteEnvironmentAuthorization } from "../authorization/service.ts";
|
||||
import { ManagedRelayClient } from "../relay/managedRelay.ts";
|
||||
import {
|
||||
CloudSession,
|
||||
PrimaryEnvironmentAuth,
|
||||
RelayDeviceIdentity,
|
||||
SshEnvironmentGateway,
|
||||
} from "../platform/capabilities.ts";
|
||||
@@ -58,17 +59,37 @@ function primarySocketUrl(target: PrimaryConnectionTarget): string {
|
||||
return url.toString();
|
||||
}
|
||||
|
||||
const primaryBroker = Effect.fn("clientRuntime.connection.broker.primary")(
|
||||
(target: PrimaryConnectionTarget) =>
|
||||
Effect.succeed({
|
||||
environmentId: target.environmentId,
|
||||
label: target.label,
|
||||
const makePrimaryBroker = Effect.fn("clientRuntime.connection.broker.makePrimary")(function* () {
|
||||
const auth = yield* PrimaryEnvironmentAuth;
|
||||
const remote = yield* RemoteEnvironmentAuthorization;
|
||||
|
||||
return Effect.fn("clientRuntime.connection.broker.primary")(function* (
|
||||
target: PrimaryConnectionTarget,
|
||||
) {
|
||||
const bearerToken = yield* auth.bearerToken;
|
||||
if (Option.isNone(bearerToken)) {
|
||||
return {
|
||||
environmentId: target.environmentId,
|
||||
label: target.label,
|
||||
httpBaseUrl: target.httpBaseUrl,
|
||||
socketUrl: primarySocketUrl(target),
|
||||
httpAuthorization: null,
|
||||
target,
|
||||
} satisfies PreparedConnection;
|
||||
}
|
||||
|
||||
const authorized = yield* remote.authorizeBearer({
|
||||
expectedEnvironmentId: target.environmentId,
|
||||
httpBaseUrl: target.httpBaseUrl,
|
||||
socketUrl: primarySocketUrl(target),
|
||||
httpAuthorization: null,
|
||||
wsBaseUrl: target.wsBaseUrl,
|
||||
bearerToken: bearerToken.value,
|
||||
});
|
||||
return {
|
||||
...authorized,
|
||||
target,
|
||||
} satisfies PreparedConnection),
|
||||
);
|
||||
} satisfies PreparedConnection;
|
||||
});
|
||||
});
|
||||
|
||||
const makeBearerBroker = Effect.fn("clientRuntime.connection.broker.makeBearer")(function* () {
|
||||
const credentials = yield* ConnectionCredentialStore;
|
||||
@@ -228,6 +249,7 @@ const makeSshBroker = Effect.fn("clientRuntime.connection.broker.makeSsh")(funct
|
||||
export const connectionResolverLayer = Layer.effect(
|
||||
ConnectionResolver,
|
||||
Effect.gen(function* () {
|
||||
const primary = yield* makePrimaryBroker();
|
||||
const bearer = yield* makeBearerBroker();
|
||||
const relay = yield* makeRelayBroker();
|
||||
const ssh = yield* makeSshBroker();
|
||||
@@ -242,7 +264,7 @@ export const connectionResolverLayer = Layer.effect(
|
||||
});
|
||||
switch (target._tag) {
|
||||
case "PrimaryConnectionTarget":
|
||||
return yield* primaryBroker(target);
|
||||
return yield* primary(target);
|
||||
case "BearerConnectionTarget":
|
||||
return yield* bearer({ ...entry, target });
|
||||
case "RelayConnectionTarget":
|
||||
|
||||
@@ -43,6 +43,13 @@ export class ClientPresentation extends Context.Service<
|
||||
}
|
||||
>()("@t3tools/client-runtime/platform/capabilities/ClientPresentation") {}
|
||||
|
||||
export class PrimaryEnvironmentAuth extends Context.Service<
|
||||
PrimaryEnvironmentAuth,
|
||||
{
|
||||
readonly bearerToken: Effect.Effect<Option.Option<string>, ConnectionAttemptError>;
|
||||
}
|
||||
>()("@t3tools/client-runtime/platform/capabilities/PrimaryEnvironmentAuth") {}
|
||||
|
||||
export class SshEnvironmentGateway extends Context.Service<
|
||||
SshEnvironmentGateway,
|
||||
{
|
||||
|
||||
@@ -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>;
|
||||
|
||||
Generated
+512
-286
File diff suppressed because it is too large.
Load diff
@@ -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": "-"
|
||||
|
||||
@@ -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");
|
||||
|
||||
@@ -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("&", "&")
|
||||
.replaceAll("<", "<")
|
||||
.replaceAll(">", ">")
|
||||
.replaceAll('"', """)
|
||||
.replaceAll("'", "'");
|
||||
}
|
||||
|
||||
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
|
||||
|
||||
Reference in new issue
Block a user