Skip to content

🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

✅ test(e2e): cover OIDC device flow (#17188)

Innei53d69253290d
diff --git a/.github/workflows/e2e.yml b/.github/workflows/e2e.yml
index a86eb2e1d3f..208c490e3d6 100644
--- a/.github/workflows/e2e.yml
+++ b/.github/workflows/e2e.yml
@@ -11,6 +11,7 @@ concurrency:
cancel-in-progress: true
env:
+ APP_URL: http://localhost:3006
DATABASE_URL: postgresql://postgres:postgres@localhost:5432/postgres
DATABASE_DRIVER: node
KEY_VAULTS_SECRET: LA7n9k3JdEcbSgml2sxfw+4TV1AzaaFU5+R176aQz4s=
@@ -74,6 +75,11 @@ jobs:
- name: Install dependencies
run: pnpm install
+ - name: Generate OIDC test signing key
+ run: |
+ JWKS_KEY="$(bun -e "import { createTestOidcJwks } from './e2e/src/support/oidcTestKey'; process.stdout.write(createTestOidcJwks());")"
+ printf 'JWKS_KEY=%s\n' "$JWKS_KEY" >> "$GITHUB_ENV"
+
- name: Install Playwright browsers (with system deps)
run: bunx playwright install --with-deps chromium
diff --git a/e2e/package.json b/e2e/package.json
index 23bdad56122..346f4d2da72 100644
--- a/e2e/package.json
+++ b/e2e/package.json
@@ -9,6 +9,7 @@
"test:ci": "bun run build && bun run test",
"test:community": "cucumber-js --config cucumber.config.js src/features/community/",
"test:headed": "cross-env HEADLESS=false cucumber-js --config cucumber.config.js",
+ "test:oidc": "cucumber-js --config cucumber.config.js --tags '@oidc'",
"test:routes": "cucumber-js --config cucumber.config.js --tags '@routes'",
"test:routes:ci": "cucumber-js --config cucumber.config.js --tags '@routes and not @ci-skip'",
"test:smoke": "cucumber-js --config cucumber.config.js --tags '@smoke'",
diff --git a/e2e/scripts/setup.ts b/e2e/scripts/setup.ts
index 16cdc558c3c..d2793cba376 100644
--- a/e2e/scripts/setup.ts
+++ b/e2e/scripts/setup.ts
@@ -17,7 +17,9 @@
* --help Show help message
*/
import { spawn, spawnSync } from 'node:child_process';
-import { resolve } from 'node:path';
+import path from 'node:path';
+
+import { createTestOidcJwks } from '../src/support/oidcTestKey';
// ============================================================================
// Configuration
@@ -30,7 +32,7 @@ const CONFIG = {
dbPort: 5433,
defaultPort: 3006,
dockerImage: 'paradedb/paradedb:latest',
- projectRoot: resolve(__dirname, '../..'),
+ projectRoot: path.resolve(__dirname, '../..'),
// S3 Mock (required even if not testing file uploads)
s3Mock: {
@@ -45,6 +47,7 @@ const CONFIG = {
secrets: {
betterAuthSecret: 'e2e-test-secret-key-for-better-auth-32chars!',
keyVaultsSecret: 'LA7n9k3JdEcbSgml2sxfw+4TV1AzaaFU5+R176aQz4s=',
+ oidcJwks: createTestOidcJwks(),
},
serverTimeout: 120_000,
@@ -255,13 +258,15 @@ async function runMigration(): Promise<void> {
// Build Operations
// ============================================================================
-async function buildApp(): Promise<void> {
+async function buildApp(port: number): Promise<void> {
log('🔨', 'Building application (this may take a few minutes)...');
await execAsync('bun', ['run', 'build'], {
+ APP_URL: `http://localhost:${port}`,
AUTH_SECRET: CONFIG.secrets.betterAuthSecret,
DATABASE_DRIVER: CONFIG.databaseDriver,
DATABASE_URL: CONFIG.databaseUrl,
+ JWKS_KEY: CONFIG.secrets.oidcJwks,
KEY_VAULTS_SECRET: CONFIG.secrets.keyVaultsSecret,
SKIP_LINT: '1',
});
@@ -284,10 +289,12 @@ async function isServerRunning(port: number): Promise<boolean> {
function getServerEnv(port: number): Record<string, string> {
return {
+ APP_URL: `http://localhost:${port}`,
AUTH_EMAIL_VERIFICATION: '0',
AUTH_SECRET: CONFIG.secrets.betterAuthSecret,
DATABASE_DRIVER: CONFIG.databaseDriver,
DATABASE_URL: CONFIG.databaseUrl,
+ JWKS_KEY: CONFIG.secrets.oidcJwks,
KEY_VAULTS_SECRET: CONFIG.secrets.keyVaultsSecret,
NODE_OPTIONS: '--max-old-space-size=6144',
PORT: String(port),
@@ -493,7 +500,7 @@ ${'─'.repeat(50)}
// Step 3: Build (optional)
if (options.build) {
logStep(++currentStep, totalSteps, 'Building application');
- await buildApp();
+ await buildApp(options.port);
}
// Step 4: Start server (optional)
diff --git a/e2e/src/features/regression/oidc-device-flow.feature b/e2e/src/features/regression/oidc-device-flow.feature
new file mode 100644
index 00000000000..fea7872d15b
--- /dev/null
+++ b/e2e/src/features/regression/oidc-device-flow.feature
@@ -0,0 +1,17 @@
+@oidc @regression @smoke @P0
+Feature: OIDC Device Flow 原生表单提交
+
+ 作为 LobeHub CLI 用户,
+ 我希望设备确认与权限确认在按钮进入 loading 状态后仍能提交,
+ 以便 CLI 可以完成授权并取得令牌。
+
+ @OIDC-DEVICE-001
+ Scenario: loading 状态不会阻断设备授权表单提交
+ Given CLI 已发起 OIDC Device Flow
+ When 用户打开设备授权链接
+ Then 页面应显示待授权的设备码
+ When 用户授权该设备
+ Then 应进入 OIDC 授权交互
+ When 用户同意 CLI 的权限请求
+ Then 应显示设备授权成功页面
+ And CLI 应取得 access token 与 refresh token
diff --git a/e2e/src/steps/auth/oidc-device-flow.steps.ts b/e2e/src/steps/auth/oidc-device-flow.steps.ts
new file mode 100644
index 00000000000..03593d30d3e
--- /dev/null
+++ b/e2e/src/steps/auth/oidc-device-flow.steps.ts
@@ -0,0 +1,207 @@
+import { Given, Then, When } from '@cucumber/cucumber';
+import { expect } from '@playwright/test';
+
+import { TEST_USER } from '../../support/seedTestUser';
+import type { CustomWorld } from '../../support/world';
+
+const CLIENT_ID = 'lobehub-cli';
+const DEVICE_CODE_GRANT = 'urn:ietf:params:oauth:grant-type:device_code';
+const RESOURCE = 'urn:lobehub:chat';
+const SCOPES = 'openid profile email offline_access';
+
+interface DeviceAuthorizationResponse {
+ device_code: string;
+ expires_in: number;
+ interval?: number;
+ user_code: string;
+ verification_uri: string;
+ verification_uri_complete?: string;
+}
+
+interface TokenResponse {
+ access_token?: string;
+ error?: string;
+ error_description?: string;
+ refresh_token?: string;
+ token_type?: string;
+}
+
+interface AccessTokenClaims {
+ aud?: string | string[];
+ iss?: string;
+ sub?: string;
+}
+
+const getDeviceAuthorization = (world: CustomWorld): DeviceAuthorizationResponse => {
+ const deviceAuthorization = world.testContext
+ .oidcDeviceAuthorization as DeviceAuthorizationResponse;
+
+ if (!deviceAuthorization) throw new Error('OIDC device authorization has not been created');
+
+ return deviceAuthorization;
+};
+
+/**
+ * Remove reusable authorization state so every run must traverse both native form submissions.
+ */
+const resetOidcAuthorizationState = async (): Promise<void> => {
+ const databaseUrl = process.env.DATABASE_URL;
+ if (!databaseUrl) throw new Error('DATABASE_URL is required for the OIDC E2E scenario');
+
+ const { default: pg } = await import('pg');
+ const client = new pg.Client({ connectionString: databaseUrl });
+
+ await client.connect();
+
+ try {
+ await client.query('BEGIN');
+ await client.query('DELETE FROM oidc_access_tokens WHERE user_id = $1 AND client_id = $2', [
+ TEST_USER.id,
+ CLIENT_ID,
+ ]);
+ await client.query('DELETE FROM oidc_refresh_tokens WHERE user_id = $1 AND client_id = $2', [
+ TEST_USER.id,
+ CLIENT_ID,
+ ]);
+ await client.query('DELETE FROM oidc_device_codes WHERE user_id = $1 AND client_id = $2', [
+ TEST_USER.id,
+ CLIENT_ID,
+ ]);
+ await client.query('DELETE FROM oidc_grants WHERE user_id = $1 AND client_id = $2', [
+ TEST_USER.id,
+ CLIENT_ID,
+ ]);
+ await client.query('DELETE FROM oidc_sessions WHERE user_id = $1', [TEST_USER.id]);
+ await client.query('DELETE FROM oidc_consents WHERE user_id = $1 AND client_id = $2', [
+ TEST_USER.id,
+ CLIENT_ID,
+ ]);
+ await client.query('COMMIT');
+ } catch (error) {
+ await client.query('ROLLBACK');
+ throw error;
+ } finally {
+ await client.end();
+ }
+};
+
+const decodeAccessToken = (accessToken: string): AccessTokenClaims => {
+ const payload = accessToken.split('.')[1];
+ if (!payload) throw new Error('OIDC access token is not a JWT');
+
+ return JSON.parse(Buffer.from(payload, 'base64url').toString('utf8')) as AccessTokenClaims;
+};
+
+Given('CLI 已发起 OIDC Device Flow', async function (this: CustomWorld) {
+ await resetOidcAuthorizationState();
+
+ const response = await this.browserContext.request.post('/oidc/device/auth', {
+ form: {
+ client_id: CLIENT_ID,
+ resource: RESOURCE,
+ scope: SCOPES,
+ },
+ });
+ const responseBody = await response.text();
+
+ expect(
+ response.ok(),
+ `Device authorization failed with ${response.status()}: ${responseBody}`,
+ ).toBe(true);
+
+ const deviceAuthorization = JSON.parse(responseBody) as DeviceAuthorizationResponse;
+ expect(deviceAuthorization.device_code).toBeTruthy();
+ expect(deviceAuthorization.user_code).toMatch(/^\w{4}-\w{4}$/);
+ expect(deviceAuthorization.verification_uri).toBeTruthy();
+
+ this.testContext.oidcDeviceAuthorization = deviceAuthorization;
+ this.testContext.oidcVerificationUrl =
+ deviceAuthorization.verification_uri_complete ||
+ `${deviceAuthorization.verification_uri}?user_code=${encodeURIComponent(deviceAuthorization.user_code)}`;
+});
+
+When('用户打开设备授权链接', async function (this: CustomWorld) {
+ const verificationUrl = this.testContext.oidcVerificationUrl as string | undefined;
+ if (!verificationUrl) throw new Error('OIDC verification URL is unavailable');
+
+ await this.page.goto(verificationUrl, { waitUntil: 'domcontentloaded' });
+ await expect(this.page).toHaveURL(/\/oauth\/device\/confirm(?:\?|$)/);
+});
+
+Then('页面应显示待授权的设备码', async function (this: CustomWorld) {
+ const { user_code: userCode } = getDeviceAuthorization(this);
+
+ await expect(this.page.getByText(userCode, { exact: true })).toBeVisible();
+ await expect(
+ this.page.locator('form[action="/oidc/device"] button[type="submit"]:not([name="abort"])'),
+ ).toBeEnabled();
+});
+
+When('用户授权该设备', async function (this: CustomWorld) {
+ const authorizeButton = this.page.locator(
+ 'form[action="/oidc/device"] button[type="submit"]:not([name="abort"])',
+ );
+
+ await expect(authorizeButton).toBeVisible();
+ await authorizeButton.click();
+ await expect(this.page).toHaveURL(/\/oauth\/consent\/[^/?]+/);
+});
+
+Then('应进入 OIDC 授权交互', async function (this: CustomWorld) {
+ await expect(
+ this.page.locator('form[action="/oidc/consent"] button[name="consent"][value="accept"]'),
+ ).toBeVisible();
+});
+
+When('用户同意 CLI 的权限请求', async function (this: CustomWorld) {
+ const acceptButton = this.page.locator(
+ 'form[action="/oidc/consent"] button[name="consent"][value="accept"]',
+ );
+ const denyButton = this.page.locator(
+ 'form[action="/oidc/consent"] button[name="consent"][value="deny"]',
+ );
+
+ // Some provider sessions require an account confirmation before the consent prompt.
+ // Advance that interaction when present, then require the explicit allow/deny prompt.
+ if (!(await denyButton.isVisible())) {
+ await acceptButton.click();
+ await expect(denyButton).toBeVisible();
+ }
+
+ await expect(acceptButton).toBeEnabled();
+ await acceptButton.click();
+ await expect(this.page).toHaveURL(/\/oauth\/device\/success(?:\?|$)/);
+});
+
+Then('应显示设备授权成功页面', async function (this: CustomWorld) {
+ await expect(this.page).toHaveURL(/\/oauth\/device\/success(?:\?|$)/);
+ await expect(this.page.getByText(/Authorization Successful|授权成功/i)).toBeVisible();
+});
+
+Then('CLI 应取得 access token 与 refresh token', async function (this: CustomWorld) {
+ const { device_code: deviceCode } = getDeviceAuthorization(this);
+ const response = await this.browserContext.request.post('/oidc/token', {
+ form: {
+ client_id: CLIENT_ID,
+ device_code: deviceCode,
+ grant_type: DEVICE_CODE_GRANT,
+ },
+ });
+ const responseBody = await response.text();
+
+ expect(response.ok(), `Token polling failed with ${response.status()}: ${responseBody}`).toBe(
+ true,
+ );
+
+ const token = JSON.parse(responseBody) as TokenResponse;
+ expect(token.error, token.error_description).toBeUndefined();
+ expect(token.token_type).toBe('Bearer');
+ expect(token.access_token).toBeTruthy();
+ expect(token.refresh_token).toBeTruthy();
+
+ const claims = decodeAccessToken(token.access_token!);
+ const audiences = Array.isArray(claims.aud) ? claims.aud : [claims.aud];
+ expect(audiences).toContain(RESOURCE);
+ expect(claims.iss).toBe(`${new URL(this.page.url()).origin}/oidc`);
+ expect(claims.sub).toBe(TEST_USER.id);
+});
diff --git a/e2e/src/steps/hooks.ts b/e2e/src/steps/hooks.ts
index 6e7e604e435..984ccd493a8 100644
--- a/e2e/src/steps/hooks.ts
+++ b/e2e/src/steps/hooks.ts
@@ -66,6 +66,7 @@ Before(async function (this: CustomWorld, { pickle }) {
tag.name.startsWith('@COMMUNITY-') ||
tag.name.startsWith('@AGENT-') ||
tag.name.startsWith('@HOME-') ||
+ tag.name.startsWith('@OIDC-') ||
tag.name.startsWith('@PAGE-') ||
tag.name.startsWith('@ROUTES-'),
);
@@ -96,6 +97,7 @@ After(async function (this: CustomWorld, { pickle, result }) {
tag.name.startsWith('@COMMUNITY-') ||
tag.name.startsWith('@AGENT-') ||
tag.name.startsWith('@HOME-') ||
+ tag.name.startsWith('@OIDC-') ||
tag.name.startsWith('@PAGE-') ||
tag.name.startsWith('@ROUTES-'),
)
diff --git a/e2e/src/support/oidcTestKey.ts b/e2e/src/support/oidcTestKey.ts
new file mode 100644
index 00000000000..3a80c634531
--- /dev/null
+++ b/e2e/src/support/oidcTestKey.ts
@@ -0,0 +1,22 @@
+import { generateKeyPairSync, randomBytes } from 'node:crypto';
+
+/**
+ * Generate an ephemeral signing key for the local OIDC provider.
+ *
+ * The key is scoped to one E2E server process and must never be reused outside tests.
+ */
+export const createTestOidcJwks = (): string => {
+ const { privateKey } = generateKeyPairSync('rsa', { modulusLength: 2048 });
+ const jwk = privateKey.export({ format: 'jwk' });
+
+ return JSON.stringify({
+ keys: [
+ {
+ ...jwk,
+ alg: 'RS256',
+ kid: randomBytes(8).toString('hex'),
+ use: 'sig',
+ },
+ ],
+ });
+};
diff --git a/e2e/src/support/webServer.ts b/e2e/src/support/webServer.ts
index a91a722daf1..8817b3095b1 100644
--- a/e2e/src/support/webServer.ts
+++ b/e2e/src/support/webServer.ts
@@ -1,13 +1,15 @@
import { type ChildProcess, spawn } from 'node:child_process';
import { existsSync, unlinkSync, writeFileSync } from 'node:fs';
import { connect } from 'node:net';
-import { resolve } from 'node:path';
+import path from 'node:path';
+
+import { createTestOidcJwks } from './oidcTestKey';
let serverProcess: ChildProcess | null = null;
let serverStartPromise: Promise<void> | null = null;
// File-based lock to coordinate between parallel workers
-const LOCK_FILE = resolve(__dirname, '../../.server-starting.lock');
+const LOCK_FILE = path.resolve(__dirname, '../../.server-starting.lock');
export async function stopWebServer(): Promise<void> {
if (serverProcess) {
@@ -129,7 +131,7 @@ export async function startWebServer(options: WebServerOptions): Promise<void> {
console.log(`🚀 Starting web server: ${command}`);
// Get the project root directory (parent of e2e folder)
- const projectRoot = resolve(__dirname, '../../..');
+ const projectRoot = path.resolve(__dirname, '../../..');
const serverEnv = {
...process.env,
@@ -142,6 +144,7 @@ export async function startWebServer(options: WebServerOptions): Promise<void> {
// E2E test secret keys
AUTH_SECRET: 'e2e-test-secret-key-for-better-auth-32chars!',
+ JWKS_KEY: process.env.JWKS_KEY || createTestOidcJwks(),
KEY_VAULTS_SECRET: 'LA7n9k3JdEcbSgml2sxfw+4TV1AzaaFU5+R176aQz4s=',
NODE_OPTIONS: '--max-old-space-size=6144',
PORT: String(port),
diff --git a/package.json b/package.json
index 9809a375add..5a3688ed410 100644
--- a/package.json
+++ b/package.json
@@ -298,7 +298,7 @@
"@lobehub/icons": "^5.11.0",
"@lobehub/market-sdk": "0.39.2",
"@lobehub/tts": "^5.1.2",
- "@lobehub/ui": "^5.20.2",
+ "@lobehub/ui": "^5.20.3",
"@modelcontextprotocol/sdk": "^1.29.0",
"@napi-rs/canvas": "^0.1.100",
"@neondatabase/serverless": "^1.1.0",