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

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 16 additions & 1 deletion .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -347,6 +347,7 @@ jobs:
"custom",
"hono",
"chrome-extension",
"electron",
]
test-project: ["chrome"]
include:
Expand Down Expand Up @@ -486,10 +487,24 @@ jobs:
working-directory: ./integration/certs
run: ls -la && pwd

- name: Ensure Xvfb is installed
if: ${{ matrix.test-name == 'electron' }}
run: |
if ! command -v xvfb-run &> /dev/null; then
sudo apt-get update
sudo apt-get install -y xvfb
fi
xvfb-run --help > /dev/null

- name: Run Integration Tests
id: integration-tests
timeout-minutes: 25
run: pnpm turbo test:integration:${{ matrix.test-name }} $TURBO_ARGS
run: |
if [ "${{ matrix.test-name }}" = "electron" ]; then
xvfb-run -a pnpm turbo test:integration:${{ matrix.test-name }} $TURBO_ARGS
else
pnpm turbo test:integration:${{ matrix.test-name }} $TURBO_ARGS
fi
env:
E2E_DEBUG: "1"
E2E_APP_CLERK_JS_DIR: ${{runner.temp}}
Expand Down
17 changes: 17 additions & 0 deletions integration/presets/electron.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import { applicationConfig } from '../models/applicationConfig';
import { templates } from '../templates';
import { PKGLAB } from './utils';

const vite = applicationConfig()
.setName('electron-vite')
.useTemplate(templates['electron-vite'])
.setEnvFormatter('public', key => `VITE_${key}`)
.addScript('setup', 'pnpm install')
.addScript('dev', 'pnpm build')
.addScript('build', 'pnpm build')
.addScript('serve', 'echo noop')
.addDependency('@clerk/electron', PKGLAB);

export const electron = {
vite,
} as const;
2 changes: 2 additions & 0 deletions integration/presets/index.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { astro } from './astro';
import { chromeExtension } from './chrome-extension';
import { customFlows } from './custom-flows';
import { electron } from './electron';
import { envs, instanceKeys } from './envs';
import { expo } from './expo';
import { express } from './express';
Expand All @@ -17,6 +18,7 @@ import { vue } from './vue';
export const appConfigs = {
chromeExtension,
customFlows,
electron,
envs,
express,
fastify,
Expand Down
18 changes: 18 additions & 0 deletions integration/templates/electron-vite/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta
name="viewport"
content="width=device-width, initial-scale=1.0"
/>
<title>Clerk Electron Integration</title>
</head>
<body>
<div id="root"></div>
<script
type="module"
src="/src/main.tsx"
></script>
</body>
</html>
98 changes: 98 additions & 0 deletions integration/templates/electron-vite/main.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
import path from 'node:path';
import { fileURLToPath, pathToFileURL } from 'node:url';

import { setupMain } from '@clerk/electron';
import { storage } from '@clerk/electron/storage';
import { app, BrowserWindow, net, protocol } from 'electron';

const __dirname = path.dirname(fileURLToPath(import.meta.url));
const RENDERER_SCHEME = 'clerk';
const RENDERER_HOST = 'app';
// electron-vite sets this in dev. Its presence is how we pick proxy vs. file serving.
const DEV_SERVER_URL = process.env.ELECTRON_RENDERER_URL;
const rendererRoot = path.resolve(__dirname, 'dist');

const clerk = setupMain({
storage: storage(),
renderer: {
scheme: RENDERER_SCHEME,
host: RENDERER_HOST,
},
});

async function createWindow() {
const win = new BrowserWindow({
width: 1000,
height: 800,
webPreferences: {
contextIsolation: true,
nodeIntegration: false,
preload: path.resolve(__dirname, 'preload.mjs'),
sandbox: false,
},
});

await win.loadURL(`${RENDERER_SCHEME}://${RENDERER_HOST}/`);
}

function registerClerkAppProtocol() {
protocol.handle(RENDERER_SCHEME, async request => {
const url = new URL(request.url);

// Only the app host serves the UI. Other hosts can be reserved for deep links.
if (url.host !== RENDERER_HOST) {
return new Response('Not found', { status: 404 });
}

// Dev: proxy to Vite so the renderer always runs from clerk://app.
if (DEV_SERVER_URL) {
const target = new URL(url.pathname + url.search, DEV_SERVER_URL);
// Intentionally do not forward the renderer's request headers to localhost.
const init = { method: request.method };

if (request.method !== 'GET' && request.method !== 'HEAD') {
init.body = request.body;
init.duplex = 'half';
}

try {
return await net.fetch(target.toString(), init);
} catch (error) {
const message = error instanceof Error ? error.message : String(error);
console.error('[clerk-app-protocol] dev proxy failed', {
requested: request.url,
target: target.toString(),
devServer: DEV_SERVER_URL,
error: message,
});
return new Response(`clerk://app dev proxy error: ${message}`, { status: 502 });
}
}

// Prod: serve the bundled renderer with a traversal guard and SPA fallback.
const requestedPath = decodeURIComponent(url.pathname);
const resolvedPath = path.resolve(rendererRoot, `.${requestedPath}`);

if (resolvedPath !== rendererRoot && !resolvedPath.startsWith(rendererRoot + path.sep)) {
return new Response(null, { status: 403 });
}

const hasExtension = /\.[^/]+$/.test(url.pathname);
const filePath = hasExtension ? resolvedPath : path.join(rendererRoot, 'index.html');

return net.fetch(pathToFileURL(filePath).toString());
});
}

app.whenReady().then(async () => {
registerClerkAppProtocol();
await createWindow();
});

app.on('window-all-closed', () => {
app.quit();
});

app.on('before-quit', () => {
clerk.cleanup();
});
26 changes: 26 additions & 0 deletions integration/templates/electron-vite/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
{
"name": "electron-vite",
"version": "0.0.0",
"private": true,
"type": "module",
"scripts": {
"build": "vite build"
},
"dependencies": {
"electron-store": "^8.2.0",
"react": "18.3.1",
"react-dom": "18.3.1"
},
"devDependencies": {
"@types/node": "^22.12.0",
"@types/react": "18.3.12",
"@types/react-dom": "18.3.1",
"@vitejs/plugin-react": "^4.3.4",
"electron": "^39.2.6",
"typescript": "^5.7.3",
"vite": "^7.3.3"
},
"engines": {
"node": ">=22.11.0"
}
}
3 changes: 3 additions & 0 deletions integration/templates/electron-vite/preload.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
import { setupPreload } from '@clerk/electron/preload';

setupPreload();
44 changes: 44 additions & 0 deletions integration/templates/electron-vite/src/main.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
import { ClerkProvider, Show, SignIn, UserButton, useAuth } from '@clerk/electron/react';
import React from 'react';
import ReactDOM from 'react-dom/client';

import './style.css';

const PUBLISHABLE_KEY = import.meta.env.VITE_CLERK_PUBLISHABLE_KEY as string;

function App() {
return (
<ClerkProvider
publishableKey={PUBLISHABLE_KEY}
routerPush={() => {}}
routerReplace={() => {}}
>
<main data-testid='electron-app'>
<Show when='signed-out'>
<SignIn />
</Show>
<Show when='signed-in'>
<UserButton />
<AuthInfo />
</Show>
</main>
</ClerkProvider>
);
}

function AuthInfo() {
const { sessionId, userId } = useAuth();

return (
<div>
<p data-testid='user-id'>{userId}</p>
<p data-testid='session-id'>{sessionId}</p>
</div>
);
}

ReactDOM.createRoot(document.getElementById('root')!).render(
<React.StrictMode>
<App />
</React.StrictMode>,
);
20 changes: 20 additions & 0 deletions integration/templates/electron-vite/src/style.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
body {
margin: 0;
min-width: 320px;
min-height: 100vh;
font-family:
Inter,
ui-sans-serif,
system-ui,
-apple-system,
BlinkMacSystemFont,
'Segoe UI',
sans-serif;
background: #f8fafc;
}

main {
display: grid;
min-height: 100vh;
place-items: center;
}
1 change: 1 addition & 0 deletions integration/templates/electron-vite/src/vite-env.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
/// <reference types="vite/client" />
15 changes: 15 additions & 0 deletions integration/templates/electron-vite/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
{
"compilerOptions": {
"allowSyntheticDefaultImports": true,
"isolatedModules": true,
"jsx": "react-jsx",
"lib": ["DOM", "DOM.Iterable", "ES2020"],
"module": "ESNext",
"moduleResolution": "Bundler",
"noEmit": true,
"strict": true,
"target": "ES2020",
"types": ["vite/client"]
},
"include": ["src"]
}
6 changes: 6 additions & 0 deletions integration/templates/electron-vite/vite.config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
import react from '@vitejs/plugin-react';
import { defineConfig } from 'vite';

export default defineConfig({
plugins: [react()],
});
1 change: 1 addition & 0 deletions integration/templates/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ export const templates = {
'react-router-library': resolve(__dirname, './react-router-library'),
'custom-flows-react-vite': resolve(__dirname, './custom-flows-react-vite'),
'chrome-extension-vite': resolve(__dirname, './chrome-extension-vite'),
'electron-vite': resolve(__dirname, './electron-vite'),
} as const;

if (new Set([...Object.values(templates)]).size !== Object.values(templates).length) {
Expand Down
35 changes: 35 additions & 0 deletions integration/tests/electron/basic.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
import { createPageObjects } from '@clerk/testing/playwright/unstable';

import type { FakeUser } from '../../testUtils';
import { createTestUtils } from '../../testUtils';
import { expect, test } from './fixtures';

test.describe('electron basic auth @electron', () => {
test.describe.configure({ mode: 'serial' });

let fakeUser: FakeUser;

test.beforeAll(async ({ testApp }) => {
const u = createTestUtils({ app: testApp });
fakeUser = u.services.users.createFakeUser();
await u.services.users.createBapiUser(fakeUser);
});

test.afterAll(async () => {
await fakeUser?.deleteIfExists();
});

test('signs in with email and password', async ({ electronPage }) => {
const { signIn } = createPageObjects({ page: electronPage, useTestingToken: false });

await signIn.waitForMounted();
await expect(electronPage.locator('.cl-signIn-root')).toBeVisible();

await signIn.setIdentifier(fakeUser.email);
await signIn.continue();
await signIn.setPassword(fakeUser.password);
await signIn.continue();

await expect(electronPage.locator('[data-testid="user-id"]')).toHaveText(/^user_/, { timeout: 30_000 });
});
});
Loading
Loading