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.

🐛 fix(oidc): serve revocation under /oidc and add a client slot (#22917)

Rdmclin21e2614c151e2
diff --git a/packages/business/const/src/index.ts b/packages/business/const/src/index.ts
index 7dd9364d131..267e101bfc1 100644
--- a/packages/business/const/src/index.ts
+++ b/packages/business/const/src/index.ts
@@ -2,6 +2,7 @@ import { BRANDING_PROVIDER } from './branding';
export * from './branding';
export * from './llm';
+export * from './oidc';
export * from './url';
export const ENABLE_BUSINESS_FEATURES = false;
diff --git a/packages/business/const/src/oidc.ts b/packages/business/const/src/oidc.ts
new file mode 100644
index 00000000000..4e8562ad958
--- /dev/null
+++ b/packages/business/const/src/oidc.ts
@@ -0,0 +1,27 @@
+/**
+ * OIDC business slot.
+ *
+ * The open-source distribution registers its own first-party clients in
+ * `src/libs/oidc-provider/config.ts`. A distribution adds further statically
+ * registered clients here; the default registers none.
+ */
+
+/**
+ * The subset of oidc-provider client metadata a distribution registers.
+ * Kept structural so this package does not depend on oidc-provider.
+ */
+export interface BusinessOidcClientMetadata {
+ [key: string]: unknown;
+ application_type?: 'native' | 'web';
+ client_id: string;
+ client_name?: string;
+ grant_types?: string[];
+ logo_uri?: string;
+ post_logout_redirect_uris?: string[];
+ redirect_uris?: string[];
+ response_types?: string[];
+ scope?: string;
+ token_endpoint_auth_method?: string;
+}
+
+export const BUSINESS_OIDC_CLIENTS: BusinessOidcClientMetadata[] = [];
diff --git a/src/libs/next/proxy/define-config.test.ts b/src/libs/next/proxy/define-config.test.ts
index 12e4815afe4..85fe58c1a1d 100644
--- a/src/libs/next/proxy/define-config.test.ts
+++ b/src/libs/next/proxy/define-config.test.ts
@@ -150,6 +150,8 @@ describe('OIDC protocol endpoints', () => {
'/oidc/me',
'/oidc/acceptance/callback?error=invalid_target&state=s',
'/oauth/connector/client-metadata.json',
+ '/oidc/token/revocation',
+ '/oidc/token/introspection',
])('serves %s without sending an unauthenticated client to sign-in', async (path) => {
const { getSession, response } = await callMiddleware(path);
diff --git a/src/libs/next/proxy/define-config.ts b/src/libs/next/proxy/define-config.ts
index b025d8894f9..8d958c9436f 100644
--- a/src/libs/next/proxy/define-config.ts
+++ b/src/libs/next/proxy/define-config.ts
@@ -243,6 +243,10 @@ export function defineConfig() {
'/oidc/handoff',
'/oidc/device/auth',
'/oidc/token',
+ // RFC 7009 / RFC 7662: native clients revoke (sign out) and introspect with
+ // their client_id and token; a session gate sent them to the sign-in page.
+ '/oidc/token/revocation',
+ '/oidc/token/introspection',
// OIDC protocol endpoints a client reads before (or without) any browser
// session: discovery and JWKS are public by spec, and userinfo authenticates
// with the bearer access token the provider itself checks. Session-gating them
diff --git a/src/libs/oidc-provider/config.test.ts b/src/libs/oidc-provider/config.test.ts
index da1c30f02b7..60db98f2b73 100644
--- a/src/libs/oidc-provider/config.test.ts
+++ b/src/libs/oidc-provider/config.test.ts
@@ -57,3 +57,43 @@ describe('OIDC default clients', () => {
);
});
});
+
+describe('distribution OIDC clients', () => {
+ const nativeClient = {
+ application_type: 'native' as const,
+ client_id: 'native-app',
+ grant_types: ['authorization_code', 'refresh_token'],
+ redirect_uris: ['http://127.0.0.1/callback'],
+ response_types: ['code'],
+ token_endpoint_auth_method: 'none',
+ };
+
+ const loadClients = async (clients: BusinessConst.BusinessOidcClientMetadata[]) => {
+ vi.resetModules();
+ vi.doMock('@lobechat/business-const', async (importOriginal) => ({
+ ...(await importOriginal<typeof BusinessConst>()),
+ BUSINESS_OIDC_CLIENTS: clients,
+ }));
+ await import('@lobechat/business-const');
+ return import('./config');
+ };
+
+ it('registers nothing extra by default', async () => {
+ const { defaultClients } = await import('./config');
+
+ expect(defaultClients.map((client) => client.client_id)).not.toContain('native-app');
+ });
+
+ it('appends the business slot clients after the built-in ones', async () => {
+ const { defaultClients } = await loadClients([nativeClient]);
+
+ expect(defaultClients.at(-1)).toEqual(nativeClient);
+ expect(defaultClients[0].client_id).toBe('lobehub-desktop');
+ });
+
+ it('refuses a business client that reuses a built-in client id', async () => {
+ await expect(loadClients([{ ...nativeClient, client_id: 'lobehub-desktop' }])).rejects.toThrow(
+ 'OIDC client "lobehub-desktop" is registered more than once',
+ );
+ });
+});
diff --git a/src/libs/oidc-provider/config.ts b/src/libs/oidc-provider/config.ts
index c573f2dc546..84baa0fa581 100644
--- a/src/libs/oidc-provider/config.ts
+++ b/src/libs/oidc-provider/config.ts
@@ -1,4 +1,4 @@
-import { BRANDING_NAME } from '@lobechat/business-const';
+import { BRANDING_NAME, BUSINESS_OIDC_CLIENTS } from '@lobechat/business-const';
import {
ACCEPTANCE_CLIENT_ID,
ACCEPTANCE_EXTENSION_CLIENT_ID,
@@ -19,9 +19,9 @@ const desktopAppOrigins = cloudAppOrigins.includes(new URL(appUrl).origin)
const marketBaseUrl = new URL(appEnv.MARKET_BASE_URL ?? 'https://market.lobehub.com').origin;
/**
- * Default OIDC client configuration
+ * Clients the open-source distribution registers itself.
*/
-export const defaultClients: ClientMetadata[] = [
+const builtinClients: ClientMetadata[] = [
{
application_type: 'web',
client_id: 'lobehub-desktop',
@@ -128,6 +128,37 @@ export const defaultClients: ClientMetadata[] = [
},
];
+/**
+ * Appends a distribution's statically registered clients to the built-in ones.
+ *
+ * A distribution client may not reuse a built-in `client_id`: oidc-provider
+ * would silently keep one of the two, and a slot that replaced the desktop
+ * client's redirect URIs or grant types would change who can sign in as it.
+ */
+export const mergeBusinessClients = (
+ builtin: ClientMetadata[],
+ business: readonly ClientMetadata[],
+): ClientMetadata[] => {
+ const seen = new Set(builtin.map((client) => client.client_id));
+
+ for (const client of business) {
+ if (seen.has(client.client_id)) {
+ throw new Error(`OIDC client "${client.client_id}" is registered more than once`);
+ }
+ seen.add(client.client_id);
+ }
+
+ return [...builtin, ...business];
+};
+
+/**
+ * Default OIDC client configuration
+ */
+export const defaultClients: ClientMetadata[] = mergeBusinessClients(
+ builtinClients,
+ BUSINESS_OIDC_CLIENTS as ClientMetadata[],
+);
+
/**
* OIDC Scopes definition
*/
diff --git a/src/libs/oidc-provider/provider.native-client.test.ts b/src/libs/oidc-provider/provider.native-client.test.ts
new file mode 100644
index 00000000000..58f289ace34
--- /dev/null
+++ b/src/libs/oidc-provider/provider.native-client.test.ts
@@ -0,0 +1,197 @@
+/**
+ * @vitest-environment node
+ *
+ * Boots the real provider configuration (`createOIDCProvider`) with an in-memory
+ * adapter and a distribution-registered native client, and talks to it over
+ * HTTP: discovery, a code + PKCE sign-in, and sign-out through the advertised
+ * revocation endpoint.
+ */
+import { createHash, generateKeyPairSync, randomBytes } from 'node:crypto';
+import { createServer, type Server } from 'node:http';
+import type { AddressInfo } from 'node:net';
+
+import type * as BusinessConst from '@lobechat/business-const';
+import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest';
+
+const NATIVE_CLIENT_ID = 'native-app';
+const REDIRECT_URI = 'http://127.0.0.1:53682/callback';
+const USER_ID = 'user_native';
+
+const { authEnvMock } = vi.hoisted(() => ({
+ authEnvMock: { ENABLE_OIDC: true, JWKS_KEY: '' },
+}));
+
+vi.mock('@/envs/auth', () => ({ authEnv: authEnvMock }));
+vi.mock('@/config/db', () => ({ serverDBEnv: { KEY_VAULTS_SECRET: 'test-secret-key' } }));
+vi.mock('@/envs/app', () => ({ appEnv: { APP_URL: 'http://localhost:3010' } }));
+vi.mock('@/server/services/projectReview/sites', () => ({ findSiteForOrigin: vi.fn() }));
+vi.mock('@/database/models/user', () => ({
+ UserModel: {
+ findById: vi.fn(async () => ({ banExpires: null, banned: false, id: USER_ID })),
+ },
+}));
+vi.mock('@lobechat/business-const', async (importOriginal) => ({
+ ...(await importOriginal<typeof BusinessConst>()),
+ BUSINESS_OIDC_CLIENTS: [
+ {
+ application_type: 'native',
+ client_id: 'native-app',
+ client_name: 'Native App',
+ grant_types: ['authorization_code', 'refresh_token'],
+ redirect_uris: ['http://127.0.0.1/callback', 'http://[::1]/callback'],
+ response_types: ['code'],
+ token_endpoint_auth_method: 'none',
+ },
+ ],
+}));
+
+vi.mock('@/libs/oidc-provider/adapter', () => {
+ const store = new Map<string, any>();
+ const key = (model: string, id: string) => `${model}:${id}`;
+
+ class MemoryAdapter {
+ constructor(private readonly model: string) {}
+ async upsert(id: string, payload: any) {
+ store.set(key(this.model, id), { ...payload });
+ }
+ async find(id: string) {
+ return store.get(key(this.model, id));
+ }
+ async findByUid(uid: string) {
+ for (const [k, payload] of store) {
+ if (k.startsWith(`${this.model}:`) && payload.uid === uid) return payload;
+ }
+ }
+ async findByUserCode() {
+ return undefined;
+ }
+ async consume(id: string) {
+ const payload = store.get(key(this.model, id));
+ if (payload) payload.consumed = Math.floor(Date.now() / 1000);
+ }
+ async destroy(id: string) {
+ store.delete(key(this.model, id));
+ }
+ async revokeByGrantId(grantId: string) {
+ for (const [k, payload] of store) {
+ if (payload.grantId === grantId) store.delete(k);
+ }
+ }
+ }
+
+ return { DrizzleAdapter: { createAdapterFactory: () => MemoryAdapter } };
+});
+
+// Imported after the mocks above.
+const { createOIDCProvider } = await import('./provider');
+
+let provider: Awaited<ReturnType<typeof createOIDCProvider>>;
+let server: Server;
+let origin: string;
+
+const form = (url: string, body: Record<string, string>) =>
+ fetch(url, {
+ body: new URLSearchParams(body),
+ headers: { 'content-type': 'application/x-www-form-urlencoded' },
+ method: 'POST',
+ });
+
+/** The provider serves discovery here; the app's HTTP adapter maps the issuer-relative URL onto it. */
+const discovery = async () =>
+ (await (await fetch(`${origin}/.well-known/openid-configuration`)).json()) as Record<
+ string,
+ string
+ >;
+
+/** Ends a code + PKCE sign-in the way the consent flow does: a grant, a code, an exchange. */
+const signIn = async () => {
+ const client = await provider.Client.find(NATIVE_CLIENT_ID);
+ const grant = new provider.Grant({ accountId: USER_ID, clientId: NATIVE_CLIENT_ID });
+ grant.addOIDCScope('openid profile offline_access');
+ grant.addResourceScope('urn:lobehub:chat', 'openid profile offline_access');
+ const grantId = await grant.save();
+
+ const verifier = randomBytes(32).toString('base64url');
+ const code = await new provider.AuthorizationCode({
+ accountId: USER_ID,
+ client,
+ codeChallenge: createHash('sha256').update(verifier).digest('base64url'),
+ codeChallengeMethod: 'S256',
+ grantId,
+ redirectUri: REDIRECT_URI,
+ resource: 'urn:lobehub:chat',
+ scope: 'openid profile offline_access',
+ }).save();
+
+ const response = await form(`${origin}/oidc/token`, {
+ client_id: NATIVE_CLIENT_ID,
+ code,
+ code_verifier: verifier,
+ grant_type: 'authorization_code',
+ redirect_uri: REDIRECT_URI,
+ });
+ expect(response.status).toBe(200);
+ return (await response.json()) as { access_token: string; refresh_token: string };
+};
+
+beforeAll(async () => {
+ const { privateKey } = generateKeyPairSync('rsa', { modulusLength: 2048 });
+ authEnvMock.JWKS_KEY = JSON.stringify({
+ keys: [{ ...privateKey.export({ format: 'jwk' }), alg: 'RS256', kid: 'test', use: 'sig' }],
+ });
+ provider = await createOIDCProvider({} as any);
+ server = createServer(provider.callback());
+ await new Promise<void>((resolve) => server.listen(0, '127.0.0.1', resolve));
+ origin = `http://127.0.0.1:${(server.address() as AddressInfo).port}`;
+});
+
+afterAll(async () => {
+ await new Promise<void>((resolve) => (server ? server.close(() => resolve()) : resolve()));
+});
+
+describe('native client endpoints', () => {
+ // The provider is mounted under /oidc and receives the untouched pathname, so an
+ // endpoint left at its default path (`/token/revocation`) is advertised where
+ // nothing serves it, and a client's sign-out lands on the web app instead.
+ it('advertises revocation and introspection under the issuer path', async () => {
+ const config = await discovery();
+
+ expect(new URL(config.revocation_endpoint).pathname).toBe('/oidc/token/revocation');
+ expect(new URL(config.introspection_endpoint).pathname).toBe('/oidc/token/introspection');
+ });
+
+ it('registers the distribution client as a public native client', async () => {
+ const client = await provider.Client.find(NATIVE_CLIENT_ID);
+
+ expect(client?.applicationType).toBe('native');
+ expect(client?.clientAuthMethod).toBe('none');
+ expect(client?.grantTypeAllowed('refresh_token')).toBe(true);
+ });
+
+ it('lets a native client sign out by revoking its refresh token at the advertised endpoint', async () => {
+ const tokens = await signIn();
+ const { introspection_endpoint, revocation_endpoint } = await discovery();
+ const at = (endpoint: string) => `${origin}${new URL(endpoint).pathname}`;
+
+ const before = await form(at(introspection_endpoint), {
+ client_id: NATIVE_CLIENT_ID,
+ token: tokens.refresh_token,
+ });
+ expect(await before.json()).toMatchObject({ active: true, client_id: NATIVE_CLIENT_ID });
+
+ const revoked = await form(at(revocation_endpoint), {
+ client_id: NATIVE_CLIENT_ID,
+ token: tokens.refresh_token,
+ token_type_hint: 'refresh_token',
+ });
+ expect(revoked.status).toBe(200);
+
+ const refresh = await form(`${origin}/oidc/token`, {
+ client_id: NATIVE_CLIENT_ID,
+ grant_type: 'refresh_token',
+ refresh_token: tokens.refresh_token,
+ });
+ expect(refresh.status).toBe(400);
+ expect(await refresh.json()).toMatchObject({ error: 'invalid_grant' });
+ });
+});
diff --git a/src/libs/oidc-provider/routes.ts b/src/libs/oidc-provider/routes.ts
index 8415aafbb40..ee01f030298 100644
--- a/src/libs/oidc-provider/routes.ts
+++ b/src/libs/oidc-provider/routes.ts
@@ -13,7 +13,9 @@ export const OIDC_ROUTES = {
code_verification: '/oidc/device',
device_authorization: '/oidc/device/auth',
end_session: '/oidc/session/end',
+ introspection: '/oidc/token/introspection',
jwks: '/oidc/jwks',
+ revocation: '/oidc/token/revocation',
token: '/oidc/token',
userinfo: '/oidc/me',
} as const;