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.

✨ feat: expose client version metadata (#17571)

YuTengjing41c7bc948fa5
diff --git a/packages/const/src/fetch.ts b/packages/const/src/fetch.ts
index 065d3b1a8a0..42338d09f69 100644
--- a/packages/const/src/fetch.ts
+++ b/packages/const/src/fetch.ts
@@ -10,6 +10,7 @@ export const OAUTH_AUTHORIZED = 'X-oauth-authorized';
export const REQUEST_TRIGGER_HEADER = 'x-lobechat-request-trigger';
export const REQUEST_AGENT_ID_HEADER = 'x-agent-id';
export const REQUEST_TOPIC_ID_HEADER = 'x-topic-id';
+export const CLIENT_VERSION_HEADER = 'x-lobe-client-version';
/**
* @deprecated
diff --git a/packages/trpc/src/lambda/context.test.ts b/packages/trpc/src/lambda/context.test.ts
index e391e1c271a..31c069d07a6 100644
--- a/packages/trpc/src/lambda/context.test.ts
+++ b/packages/trpc/src/lambda/context.test.ts
@@ -92,6 +92,7 @@ describe('createContextInner', () => {
const context = await createContextInner();
expect(context).toMatchObject({
+ clientMetadata: { type: 'unknown' },
marketAccessToken: undefined,
oidcAuth: undefined,
userAgent: undefined,
@@ -114,6 +115,22 @@ describe('createContextInner', () => {
expect(context.userAgent).toBe('Mozilla/5.0');
});
+ it('should create context with client metadata', async () => {
+ const context = await createContextInner({
+ clientMetadata: {
+ platform: 'ios',
+ type: 'mobile',
+ version: '1.2.0',
+ },
+ });
+
+ expect(context.clientMetadata).toEqual({
+ platform: 'ios',
+ type: 'mobile',
+ version: '1.2.0',
+ });
+ });
+
it('should create context with market access token', async () => {
const context = await createContextInner({
marketAccessToken: 'mp-token-xyz',
@@ -196,6 +213,22 @@ describe('createLambdaContext', () => {
mockUpdateLastUsed.mockResolvedValue(undefined);
});
+ it('should expose parsed web client metadata', async () => {
+ const request = new NextRequest('https://example.com/trpc/lambda', {
+ headers: {
+ 'user-agent': 'Mozilla/5.0 Chrome/140.0.0.0',
+ 'x-lobe-client-version': '2.2.10',
+ },
+ });
+
+ const context = await createLambdaContext(request);
+
+ expect(context.clientMetadata).toEqual({
+ type: 'web',
+ version: '2.2.10',
+ });
+ });
+
it('should authenticate with API key and skip session fallback', async () => {
const apiKeyRecord = {
accessedAt: new Date(),
diff --git a/packages/trpc/src/lambda/context.ts b/packages/trpc/src/lambda/context.ts
index 95f9f9b716d..c4ec7f251c1 100644
--- a/packages/trpc/src/lambda/context.ts
+++ b/packages/trpc/src/lambda/context.ts
@@ -1,5 +1,7 @@
import { type Context as OtContext } from '@lobechat/observability-otel/api';
import { type ClientSecretPayload } from '@lobechat/types';
+import type { ClientMetadata } from '@lobechat/utils/server';
+import { parseClientMetadata } from '@lobechat/utils/server';
import { parse } from 'cookie';
import debug from 'debug';
import { type NextRequest } from 'next/server';
@@ -77,6 +79,7 @@ export interface OIDCAuth {
export interface AuthContext {
clientIp?: string | null;
+ clientMetadata?: ClientMetadata;
jwtPayload?: ClientSecretPayload | null;
marketAccessToken?: string;
// Add OIDC authentication information
@@ -94,6 +97,7 @@ export interface AuthContext {
* This is useful for testing when we don't want to mock Next.js' request/response
*/
export const createContextInner = async (params?: {
+ clientMetadata?: ClientMetadata;
clientIp?: string | null;
marketAccessToken?: string;
oidcAuth?: OIDCAuth | null;
@@ -107,6 +111,7 @@ export const createContextInner = async (params?: {
const responseHeaders = new Headers();
return {
+ clientMetadata: params?.clientMetadata || { type: 'unknown' },
clientIp: params?.clientIp,
marketAccessToken: params?.marketAccessToken,
oidcAuth: params?.oidcAuth,
@@ -126,6 +131,8 @@ export type LambdaContext = Awaited<ReturnType<typeof createContextInner>>;
* @link https://trpc.io/docs/v11/context
*/
export const createLambdaContext = async (request: NextRequest): Promise<LambdaContext> => {
+ const clientMetadata = parseClientMetadata(request.headers);
+
// we have a special header to debug the api endpoint in development mode
// IT WON'T GO INTO PRODUCTION ANYMORE
const isDebugApi = request.headers.get('lobe-auth-dev-backend-api') === '1';
@@ -133,6 +140,7 @@ export const createLambdaContext = async (request: NextRequest): Promise<LambdaC
if (process.env.NODE_ENV === 'development' && (isDebugApi || isMockUser)) {
return createContextInner({
+ clientMetadata,
userId: process.env.MOCK_DEV_USER_ID,
});
}
@@ -154,6 +162,7 @@ export const createLambdaContext = async (request: NextRequest): Promise<LambdaC
const workspaceId = request.headers.get('X-Workspace-Id')?.trim() || undefined;
const commonContext = {
+ clientMetadata,
clientIp,
marketAccessToken,
userAgent,
diff --git a/packages/utils/src/server/__tests__/clientMetadata.test.ts b/packages/utils/src/server/__tests__/clientMetadata.test.ts
new file mode 100644
index 00000000000..fcb31721d21
--- /dev/null
+++ b/packages/utils/src/server/__tests__/clientMetadata.test.ts
@@ -0,0 +1,101 @@
+import { CLIENT_VERSION_HEADER } from '@lobechat/const';
+import { describe, expect, it } from 'vitest';
+
+import { parseClientMetadata } from '../clientMetadata';
+
+describe('parseClientMetadata', () => {
+ it('should parse the current iOS mobile user agent', () => {
+ const headers = new Headers({
+ 'user-agent': 'LobeHub-Mobile/ios-v1.2.0',
+ });
+
+ expect(parseClientMetadata(headers)).toEqual({
+ platform: 'ios',
+ type: 'mobile',
+ version: '1.2.0',
+ });
+ });
+
+ it('should parse the current Android mobile user agent', () => {
+ const headers = new Headers({
+ 'user-agent': 'LobeHub-Mobile/android-v2.0.0-beta.1',
+ });
+
+ expect(parseClientMetadata(headers)).toEqual({
+ platform: 'android',
+ type: 'mobile',
+ version: '2.0.0-beta.1',
+ });
+ });
+
+ it('should parse the desktop user agent', () => {
+ const headers = new Headers({
+ 'user-agent': 'LobeHub Desktop/1.2.3',
+ });
+
+ expect(parseClientMetadata(headers)).toEqual({
+ type: 'desktop',
+ version: '1.2.3',
+ });
+ });
+
+ it.each([
+ ['LobeHub-iOS/2.0', '2.0'],
+ ['LobeHub/1 CFNetwork/3860.300.31 Darwin/25.3.0', '1'],
+ ])('should parse a legacy iOS user agent', (userAgent, version) => {
+ expect(parseClientMetadata(new Headers({ 'user-agent': userAgent }))).toEqual({
+ platform: 'ios',
+ type: 'mobile',
+ version,
+ });
+ });
+
+ it('should identify an Android okhttp request without inventing an app version', () => {
+ const headers = new Headers({ 'user-agent': 'okhttp/4.12.0' });
+
+ expect(parseClientMetadata(headers)).toEqual({
+ platform: 'android',
+ type: 'mobile',
+ });
+ });
+
+ it('should identify a web request from the client version header', () => {
+ const headers = new Headers({
+ [CLIENT_VERSION_HEADER]: '2.2.10',
+ 'user-agent': 'Mozilla/5.0 Chrome/140.0.0.0',
+ });
+
+ expect(parseClientMetadata(headers)).toEqual({
+ type: 'web',
+ version: '2.2.10',
+ });
+ });
+
+ it('should prefer a native user agent over the web version header', () => {
+ const headers = new Headers({
+ [CLIENT_VERSION_HEADER]: '2.2.10',
+ 'user-agent': 'LobeHub Desktop/1.2.3',
+ });
+
+ expect(parseClientMetadata(headers)).toEqual({
+ type: 'desktop',
+ version: '1.2.3',
+ });
+ });
+
+ it('should return unknown when no supported client metadata exists', () => {
+ const headers = new Headers({ 'user-agent': 'curl/8.7.1' });
+
+ expect(parseClientMetadata(headers)).toEqual({ type: 'unknown' });
+ });
+
+ it('should ignore an empty or oversized web version', () => {
+ const emptyVersionHeaders = new Headers({ [CLIENT_VERSION_HEADER]: ' ' });
+ const oversizedVersionHeaders = new Headers({
+ [CLIENT_VERSION_HEADER]: '1'.repeat(129),
+ });
+
+ expect(parseClientMetadata(emptyVersionHeaders)).toEqual({ type: 'unknown' });
+ expect(parseClientMetadata(oversizedVersionHeaders)).toEqual({ type: 'unknown' });
+ });
+});
diff --git a/packages/utils/src/server/clientMetadata.ts b/packages/utils/src/server/clientMetadata.ts
new file mode 100644
index 00000000000..bc3573c7cc7
--- /dev/null
+++ b/packages/utils/src/server/clientMetadata.ts
@@ -0,0 +1,64 @@
+import { CLIENT_VERSION_HEADER } from '@lobechat/const';
+
+export type ClientType = 'desktop' | 'mobile' | 'unknown' | 'web';
+export type MobileClientPlatform = 'android' | 'ios';
+
+export interface ClientMetadata {
+ platform?: MobileClientPlatform;
+ type: ClientType;
+ version?: string;
+}
+
+const MAX_CLIENT_VERSION_LENGTH = 128;
+const DESKTOP_USER_AGENT_PATTERN = /\bLobeHub Desktop\/(\S+)/i;
+const MOBILE_USER_AGENT_PATTERN = /\bLobeHub-Mobile\/(android|ios)-v(\S+)/i;
+const LEGACY_IOS_USER_AGENT_PATTERNS = [/\bLobeHub-iOS\/(\S+)/i, /\bLobeHub\/(\S+)\s+CFNetwork\//i];
+
+const normalizeVersion = (version: string | null | undefined) => {
+ const normalizedVersion = version?.trim();
+
+ if (!normalizedVersion || normalizedVersion.length > MAX_CLIENT_VERSION_LENGTH) return;
+
+ return normalizedVersion;
+};
+
+export const parseClientMetadata = (headers: Headers): ClientMetadata => {
+ const userAgent = headers.get('user-agent') || '';
+
+ const mobileMatch = userAgent.match(MOBILE_USER_AGENT_PATTERN);
+ if (mobileMatch) {
+ return {
+ platform: mobileMatch[1].toLowerCase() as MobileClientPlatform,
+ type: 'mobile',
+ version: normalizeVersion(mobileMatch[2]),
+ };
+ }
+
+ const desktopMatch = userAgent.match(DESKTOP_USER_AGENT_PATTERN);
+ if (desktopMatch) {
+ return {
+ type: 'desktop',
+ version: normalizeVersion(desktopMatch[1]),
+ };
+ }
+
+ for (const pattern of LEGACY_IOS_USER_AGENT_PATTERNS) {
+ const legacyIosMatch = userAgent.match(pattern);
+ if (legacyIosMatch) {
+ return {
+ platform: 'ios',
+ type: 'mobile',
+ version: normalizeVersion(legacyIosMatch[1]),
+ };
+ }
+ }
+
+ if (/\bokhttp\//i.test(userAgent)) {
+ return { platform: 'android', type: 'mobile' };
+ }
+
+ const webVersion = normalizeVersion(headers.get(CLIENT_VERSION_HEADER));
+ if (webVersion) return { type: 'web', version: webVersion };
+
+ return { type: 'unknown' };
+};
diff --git a/packages/utils/src/server/index.ts b/packages/utils/src/server/index.ts
index 19d7f0c4a14..34b806f1012 100644
--- a/packages/utils/src/server/index.ts
+++ b/packages/utils/src/server/index.ts
@@ -1,5 +1,6 @@
export * from './apiKeyHash';
export * from './auth';
+export * from './clientMetadata';
export * from './response';
export * from './responsive';
export * from './sse';
diff --git a/src/libs/better-auth/auth-client.ts b/src/libs/better-auth/auth-client.ts
index e38459f433c..9680315711b 100644
--- a/src/libs/better-auth/auth-client.ts
+++ b/src/libs/better-auth/auth-client.ts
@@ -1,3 +1,4 @@
+import { CLIENT_VERSION_HEADER, CURRENT_VERSION } from '@lobechat/const';
import {
adminClient,
genericOAuthClient,
@@ -23,6 +24,11 @@ export const {
unlinkAccount,
useSession,
} = createAuthClient({
+ fetchOptions: {
+ headers: {
+ [CLIENT_VERSION_HEADER]: CURRENT_VERSION,
+ },
+ },
plugins: [
adminClient(),
inferAdditionalFields<typeof auth>(),
diff --git a/src/services/__tests__/_auth.test.ts b/src/services/__tests__/_auth.test.ts
index 4d2a409f17d..4df93d7a52e 100644
--- a/src/services/__tests__/_auth.test.ts
+++ b/src/services/__tests__/_auth.test.ts
@@ -1,10 +1,11 @@
+import { CLIENT_VERSION_HEADER, CURRENT_VERSION } from '@lobechat/const';
import { act } from '@testing-library/react';
import { ModelProvider } from 'model-bank';
import { afterEach, describe, expect, it, vi } from 'vitest';
import { useUserStore } from '@/store/user';
-import { getProviderAuthPayload } from '../_auth';
+import { createHeaderWithAuth, getProviderAuthPayload } from '../_auth';
// Mock data for different providers
const mockZhiPuAPIKey = 'zhipu-api-key';
@@ -28,6 +29,29 @@ const mockCryptoValue = (value: number) => {
});
};
+describe('createHeaderWithAuth', () => {
+ it('should include the current web client version', async () => {
+ const headers = await createHeaderWithAuth();
+
+ expect(headers).toEqual({
+ [CLIENT_VERSION_HEADER]: CURRENT_VERSION,
+ });
+ });
+
+ it('should preserve request headers without allowing a client version override', async () => {
+ const headers = await createHeaderWithAuth({
+ headers: {
+ 'X-Lobe-Client-Version': 'spoofed',
+ 'Content-Type': 'application/json',
+ },
+ });
+ const normalizedHeaders = new Headers(headers);
+
+ expect(normalizedHeaders.get(CLIENT_VERSION_HEADER)).toBe(CURRENT_VERSION);
+ expect(normalizedHeaders.get('content-type')).toBe('application/json');
+ });
+});
+
const setModelProviderConfig = (provider: string, config: any) => {
useUserStore.setState({
settings: { keyVaults: { [provider]: config } },
diff --git a/src/services/_auth.ts b/src/services/_auth.ts
index 3b0d10761e9..8f57378d902 100644
--- a/src/services/_auth.ts
+++ b/src/services/_auth.ts
@@ -1,3 +1,4 @@
+import { CLIENT_VERSION_HEADER, CURRENT_VERSION } from '@lobechat/const';
import {
type AWSBedrockKeyVault,
type AzureOpenAIKeyVault,
@@ -111,5 +112,8 @@ export const createPayloadWithKeyVaults = (provider: string) => {
};
export const createHeaderWithAuth = async (params?: AuthParams): Promise<HeadersInit> => {
- return { ...params?.headers };
+ const headers = new Headers(params?.headers);
+ headers.set(CLIENT_VERSION_HEADER, CURRENT_VERSION);
+
+ return Object.fromEntries(headers.entries());
};