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(openapi): publish OAuth discovery metadata for /api/v1 and answer 401 with a Bearer challenge (#23679)

Lobehub Coderc9af24fc03a4
diff --git a/.agents/skills/testing/SKILL.md b/.agents/skills/testing/SKILL.md
index 93cacb6a2fb..3cee65e957d 100644
--- a/.agents/skills/testing/SKILL.md
+++ b/.agents/skills/testing/SKILL.md
@@ -42,6 +42,7 @@ cd packages/database && TEST_SERVER_DB=1 bunx vitest run --silent='passed-only'
1. **Prefer `vi.spyOn` over `vi.mock`** - More targeted, easier to maintain. The root Vitest configs do not restore mocks automatically; restore spies in test cleanup with `vi.restoreAllMocks()`.
2. **Test behavior, not implementation details**
- Keep native `node:test` CI checks under `.github/scripts/`, outside the app Vitest discovery paths. When mixing test runners, verify both the intended runner and the owning Vitest project's file discovery before pushing.
+ - The root Vitest config excludes every dot directory (`**/.*/**`), so a test beside a route in `src/app/(backend)/.well-known/…` is never collected and `bun run check` reports `tests 0 passed` instead of failing. Put such a test next to the logic it covers (e.g. `src/libs/oidc-provider/*-route.test.ts`) and import the route through its `@/app/…` alias.
3. **Regression tests for bug fixes** - Include a regression test that fails without the fix and passes with it; write the failing test first when the failure is easy to reproduce. **Skip** pure style/CSS fixes (selector, hover, mask, spacing, color) when the only practical assertion would be source-string matching on the stylesheet — that is not a regression test worth shipping.
4. **No new component tests** - Only update existing React component tests. Complex logic should be extracted into hooks and tested there instead
diff --git a/docs/development/api/authentication.mdx b/docs/development/api/authentication.mdx
index 970d042546c..4ceda072efe 100644
--- a/docs/development/api/authentication.mdx
+++ b/docs/development/api/authentication.mdx
@@ -25,7 +25,13 @@ The server decides what kind of token it is by its shape:
- A token in the API key format (`sk-lh-` plus 58 lowercase letters and digits, or 16 for keys created earlier) is looked up as an **API key**. The key must be enabled and not expired.
- Any other token is validated as an **OIDC access token** (an RS256 JWT for the audience `urn:lobehub:chat`), signed by the deployment's OIDC provider. Self-hosted instances accept OIDC tokens only when `JWKS_KEY` is configured.
-There is no `X-API-Key` header. A missing or invalid token returns `401`.
+There is no `X-API-Key` header. A missing or invalid token returns `401` with a challenge that says where to authenticate:
+
+```http
+WWW-Authenticate: Bearer realm="LobeHub API", resource_metadata="https://app.lobehub.com/.well-known/oauth-protected-resource/api/v1"
+```
+
+That URL is the API's [RFC 9728](https://www.rfc-editor.org/rfc/rfc9728) protected resource metadata: the resource (`<origin>/api/v1`), its authorization server (`<origin>/oidc`, when OIDC is enabled) and the bearer method. The authorization server's [RFC 8414](https://www.rfc-editor.org/rfc/rfc8414) metadata is at `<origin>/.well-known/oauth-authorization-server/oidc`, the same document as the OIDC discovery below.
## Choose a Credential
diff --git a/docs/development/api/authentication.zh-CN.mdx b/docs/development/api/authentication.zh-CN.mdx
index e1c2374c795..23db9ae691a 100644
--- a/docs/development/api/authentication.zh-CN.mdx
+++ b/docs/development/api/authentication.zh-CN.mdx
@@ -25,7 +25,13 @@ Authorization: Bearer <token>
- 符合 API Key 格式(`sk-lh-` 加 58 位小写字母和数字,较早创建的 Key 为 16 位)的令牌按 **API Key** 查找。Key 必须处于启用状态且未过期。
- 其他令牌一律按 **OIDC 访问令牌** 校验(受众为 `urn:lobehub:chat` 的 RS256 JWT),由部署自身的 OIDC 提供方签发。自托管实例只有在配置了 `JWKS_KEY` 时才接受 OIDC 令牌。
-不存在 `X-API-Key` 请求头。缺少令牌或令牌无效时返回 `401`。
+不存在 `X-API-Key` 请求头。缺少令牌或令牌无效时返回 `401`,并附带一个说明去哪里认证的质询头:
+
+```http
+WWW-Authenticate: Bearer realm="LobeHub API", resource_metadata="https://app.lobehub.com/.well-known/oauth-protected-resource/api/v1"
+```
+
+该地址是 API 的 [RFC 9728](https://www.rfc-editor.org/rfc/rfc9728) 受保护资源元数据:资源(`<origin>/api/v1`)、它的授权服务器(启用 OIDC 时为 `<origin>/oidc`)以及令牌的携带方式。授权服务器的 [RFC 8414](https://www.rfc-editor.org/rfc/rfc8414) 元数据位于 `<origin>/.well-known/oauth-authorization-server/oidc`,内容与下文的 OIDC 发现文档相同。
## 选择凭证
diff --git a/packages/openapi/src/app.ts b/packages/openapi/src/app.ts
index e4b70c16029..ec0824b858f 100644
--- a/packages/openapi/src/app.ts
+++ b/packages/openapi/src/app.ts
@@ -13,6 +13,7 @@ import { routeDoc } from './common/openapi';
import { SCALAR_CUSTOM_CSS } from './docs-theme';
// Import user authentication middleware (supports both OIDC and API Key authentication)
import { userAuthMiddleware } from './middleware/auth';
+import { authChallenge, WWW_AUTHENTICATE_HEADER } from './middleware/auth-challenge';
import { idempotencyMiddleware, IDEMPOTENT_REPLAYED_HEADER } from './middleware/idempotency';
import { openResponsesErrors } from './middleware/open-responses-errors';
import { RATE_LIMIT_HEADERS, rateLimit } from './middleware/rate-limit';
@@ -33,11 +34,14 @@ app.use(
cors({
exposeHeaders: [
REQUEST_ID_HEADER,
+ WWW_AUTHENTICATE_HEADER,
IDEMPOTENT_REPLAYED_HEADER,
...Object.values(RATE_LIMIT_HEADERS),
],
}),
);
+// Outermost after CORS: adds the Bearer challenge to whatever 401 the inner layers return.
+app.use('*', authChallenge);
app.use('*', logger());
app.use('*', prettyJSON());
// OpenResponses routes answer errors in the protocol's own shape.
diff --git a/packages/openapi/src/middleware/auth-challenge.test.ts b/packages/openapi/src/middleware/auth-challenge.test.ts
new file mode 100644
index 00000000000..aec6ef795a9
--- /dev/null
+++ b/packages/openapi/src/middleware/auth-challenge.test.ts
@@ -0,0 +1,58 @@
+import { Hono } from 'hono';
+import { HTTPException } from 'hono/http-exception';
+import { describe, expect, it, vi } from 'vitest';
+
+vi.mock('@/envs/app', () => ({ appEnv: { APP_URL: 'https://app.lobehub.com' } }));
+
+const { authChallenge, WWW_AUTHENTICATE_HEADER } = await import('./auth-challenge');
+
+const CHALLENGE =
+ 'Bearer realm="LobeHub API", resource_metadata="https://app.lobehub.com/.well-known/oauth-protected-resource/api/v1"';
+
+const createApp = () => {
+ const app = new Hono();
+ app.use('*', authChallenge);
+ app.onError((error, c) =>
+ error instanceof HTTPException
+ ? c.json({ code: 'unauthorized' }, error.status)
+ : c.json({ code: 'internal' }, 500),
+ );
+ app.get('/thrown', () => {
+ throw new HTTPException(401, { message: 'Authentication required' });
+ });
+ app.get('/returned', (c) => c.json({ code: 'unauthorized' }, 401));
+ app.get('/proxied', async () => {
+ const upstream = await fetch('data:application/json,{}');
+ return new Response(upstream.body, { headers: upstream.headers, status: 401 });
+ });
+ app.get('/own-challenge', (c) =>
+ c.json({}, 401, { [WWW_AUTHENTICATE_HEADER]: 'Payment realm="x"' }),
+ );
+ app.get('/forbidden', (c) => c.json({ code: 'forbidden' }, 403));
+ return app;
+};
+
+describe('authChallenge', () => {
+ it('points a 401 thrown by auth middleware at the protected resource metadata', async () => {
+ const response = await createApp().request('/thrown');
+
+ expect(response.status).toBe(401);
+ expect(response.headers.get(WWW_AUTHENTICATE_HEADER)).toBe(CHALLENGE);
+ });
+
+ it('covers a 401 a handler returns and a proxied response with fixed headers', async () => {
+ const app = createApp();
+
+ expect((await app.request('/returned')).headers.get(WWW_AUTHENTICATE_HEADER)).toBe(CHALLENGE);
+ expect((await app.request('/proxied')).headers.get(WWW_AUTHENTICATE_HEADER)).toBe(CHALLENGE);
+ });
+
+ it('keeps a challenge the route set and leaves other statuses alone', async () => {
+ const app = createApp();
+
+ expect((await app.request('/own-challenge')).headers.get(WWW_AUTHENTICATE_HEADER)).toBe(
+ 'Payment realm="x"',
+ );
+ expect((await app.request('/forbidden')).headers.get(WWW_AUTHENTICATE_HEADER)).toBeNull();
+ });
+});
diff --git a/packages/openapi/src/middleware/auth-challenge.ts b/packages/openapi/src/middleware/auth-challenge.ts
new file mode 100644
index 00000000000..46307234a58
--- /dev/null
+++ b/packages/openapi/src/middleware/auth-challenge.ts
@@ -0,0 +1,32 @@
+import type { MiddlewareHandler } from 'hono';
+
+import { appEnv } from '@/envs/app';
+import { apiBearerChallenge } from '@/libs/oidc-provider/discovery-metadata';
+
+export const WWW_AUTHENTICATE_HEADER = 'WWW-Authenticate';
+
+/**
+ * Every 401 tells the client how to authenticate: a Bearer challenge pointing at the
+ * API's RFC 9728 protected resource metadata (which names the OIDC issuer). Applied
+ * after the response is built, so it covers every 401 whichever layer produced it
+ * (missing credentials, bad token, workspace or permission checks).
+ */
+export const authChallenge: MiddlewareHandler = async (c, next) => {
+ await next();
+
+ if (c.res.status !== 401 || c.res.headers.has(WWW_AUTHENTICATE_HEADER)) return;
+
+ const challenge = apiBearerChallenge(appEnv.APP_URL!);
+ try {
+ c.res.headers.set(WWW_AUTHENTICATE_HEADER, challenge);
+ } catch {
+ // Immutable headers (a proxied upstream response): re-wrap it.
+ const headers = new Headers(c.res.headers);
+ headers.set(WWW_AUTHENTICATE_HEADER, challenge);
+ c.res = new Response(c.res.body, {
+ headers,
+ status: c.res.status,
+ statusText: c.res.statusText,
+ });
+ }
+};
diff --git a/src/app/(backend)/.well-known/oauth-authorization-server/oidc/route.ts b/src/app/(backend)/.well-known/oauth-authorization-server/oidc/route.ts
new file mode 100644
index 00000000000..dd3ecc67096
--- /dev/null
+++ b/src/app/(backend)/.well-known/oauth-authorization-server/oidc/route.ts
@@ -0,0 +1,22 @@
+import { NextRequest } from 'next/server';
+
+import { GET as oidcHandler } from '@/app/(backend)/oidc/[...oidc]/route';
+import { appEnv } from '@/envs/app';
+import { oidcDiscoveryUrl } from '@/libs/oidc-provider/discovery-metadata';
+
+/**
+ * RFC 8414 authorization server metadata of the issuer `<origin>/oidc`, at its
+ * path-inserted well-known URL. It is the provider's own OpenID discovery document
+ * (a superset of RFC 8414), served by the provider, so the two can never disagree.
+ * With OIDC disabled the provider handler answers 404, and so does this route.
+ */
+export const GET = async (req: NextRequest) => {
+ const discovery = await oidcHandler(
+ new NextRequest(oidcDiscoveryUrl(appEnv.APP_URL!), { headers: req.headers, method: 'GET' }),
+ );
+ if (!discovery.ok) return discovery;
+
+ return Response.json(await discovery.json(), {
+ headers: { 'Access-Control-Allow-Origin': '*', 'Cache-Control': 'public, max-age=3600' },
+ });
+};
diff --git a/src/app/(backend)/.well-known/oauth-protected-resource/api/v1/route.ts b/src/app/(backend)/.well-known/oauth-protected-resource/api/v1/route.ts
new file mode 100644
index 00000000000..d25ac59a297
--- /dev/null
+++ b/src/app/(backend)/.well-known/oauth-protected-resource/api/v1/route.ts
@@ -0,0 +1,9 @@
+import { appEnv } from '@/envs/app';
+import { authEnv } from '@/envs/auth';
+import { buildProtectedResourceMetadata } from '@/libs/oidc-provider/discovery-metadata';
+
+/** RFC 9728 protected resource metadata of the public REST API at `/api/v1`. */
+export const GET = () =>
+ Response.json(buildProtectedResourceMetadata(appEnv.APP_URL!, authEnv.ENABLE_OIDC), {
+ headers: { 'Access-Control-Allow-Origin': '*', 'Cache-Control': 'public, max-age=3600' },
+ });
diff --git a/src/libs/oidc-provider/authorization-server-metadata-route.test.ts b/src/libs/oidc-provider/authorization-server-metadata-route.test.ts
new file mode 100644
index 00000000000..486643e1612
--- /dev/null
+++ b/src/libs/oidc-provider/authorization-server-metadata-route.test.ts
@@ -0,0 +1,44 @@
+// The route lives under `.well-known`, a dot directory vitest excludes, so its test sits here.
+import { NextRequest } from 'next/server';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+const oidcHandler = vi.hoisted(() => vi.fn());
+
+vi.mock('@/app/(backend)/oidc/[...oidc]/route', () => ({ GET: oidcHandler }));
+vi.mock('@/envs/app', () => ({ appEnv: { APP_URL: 'https://app.lobehub.com' } }));
+
+const { GET: getAuthorizationServerMetadata } =
+ await import('@/app/(backend)/.well-known/oauth-authorization-server/oidc/route');
+
+const DISCOVERY = {
+ authorization_endpoint: 'https://app.lobehub.com/oidc/auth',
+ issuer: 'https://app.lobehub.com/oidc',
+ token_endpoint: 'https://app.lobehub.com/oidc/token',
+};
+
+beforeEach(() => oidcHandler.mockReset());
+
+describe('GET /.well-known/oauth-authorization-server/oidc', () => {
+ it("serves the provider's own discovery document for the issuer", async () => {
+ oidcHandler.mockResolvedValue(Response.json(DISCOVERY));
+
+ const res = await getAuthorizationServerMetadata(
+ new NextRequest('https://app.lobehub.com/.well-known/oauth-authorization-server/oidc'),
+ );
+
+ expect(await res.json()).toEqual(DISCOVERY);
+ expect(res.headers.get('Access-Control-Allow-Origin')).toBe('*');
+ const forwarded = oidcHandler.mock.calls[0]![0] as NextRequest;
+ expect(forwarded.url).toBe('https://app.lobehub.com/oidc/.well-known/openid-configuration');
+ });
+
+ it('answers 404 like the provider when OIDC is disabled', async () => {
+ oidcHandler.mockResolvedValue(new Response('OIDC is not enabled', { status: 404 }));
+
+ const res = await getAuthorizationServerMetadata(
+ new NextRequest('https://app.lobehub.com/.well-known/oauth-authorization-server/oidc'),
+ );
+
+ expect(res.status).toBe(404);
+ });
+});
diff --git a/src/libs/oidc-provider/discovery-metadata.test.ts b/src/libs/oidc-provider/discovery-metadata.test.ts
new file mode 100644
index 00000000000..f942f9d8538
--- /dev/null
+++ b/src/libs/oidc-provider/discovery-metadata.test.ts
@@ -0,0 +1,41 @@
+import { describe, expect, it } from 'vitest';
+
+import {
+ apiBearerChallenge,
+ AUTHORIZATION_SERVER_METADATA_PATH,
+ buildProtectedResourceMetadata,
+ PROTECTED_RESOURCE_METADATA_PATH,
+} from './discovery-metadata';
+
+const ORIGIN = 'https://app.lobehub.com';
+
+describe('API OAuth discovery metadata', () => {
+ it('inserts the well-known prefix before the resource and issuer paths (RFC 9728, RFC 8414)', () => {
+ expect(PROTECTED_RESOURCE_METADATA_PATH).toBe('/.well-known/oauth-protected-resource/api/v1');
+ expect(AUTHORIZATION_SERVER_METADATA_PATH).toBe('/.well-known/oauth-authorization-server/oidc');
+ });
+
+ it('describes /api/v1 with the deployment issuer and header bearer tokens', () => {
+ expect(buildProtectedResourceMetadata(ORIGIN, true)).toEqual({
+ authorization_servers: ['https://app.lobehub.com/oidc'],
+ bearer_methods_supported: ['header'],
+ resource: 'https://app.lobehub.com/api/v1',
+ resource_documentation: 'https://lobehub.com/docs/development/api/authentication',
+ resource_name: 'LobeHub API',
+ scopes_supported: ['openid', 'profile', 'email', 'offline_access'],
+ });
+ });
+
+ it('names no authorization server when OIDC is off (API keys only)', () => {
+ const metadata = buildProtectedResourceMetadata('https://chat.example.com/', false);
+
+ expect(metadata).not.toHaveProperty('authorization_servers');
+ expect(metadata.resource).toBe('https://chat.example.com/api/v1');
+ });
+
+ it('builds the 401 challenge from the metadata URL', () => {
+ expect(apiBearerChallenge(ORIGIN)).toBe(
+ 'Bearer realm="LobeHub API", resource_metadata="https://app.lobehub.com/.well-known/oauth-protected-resource/api/v1"',
+ );
+ });
+});
diff --git a/src/libs/oidc-provider/discovery-metadata.ts b/src/libs/oidc-provider/discovery-metadata.ts
new file mode 100644
index 00000000000..cce1afa676f
--- /dev/null
+++ b/src/libs/oidc-provider/discovery-metadata.ts
@@ -0,0 +1,49 @@
+import urlJoin from 'url-join';
+
+import { OIDC_DISCOVERY_PATH, OIDC_ISSUER_PATH } from './routes';
+
+/**
+ * OAuth discovery for the public REST API (`/api/v1`, `packages/openapi`).
+ *
+ * RFC 9728 places a resource's metadata at the well-known prefix inserted before the
+ * resource path, and its `resource` must equal that resource URL; RFC 8414 does the
+ * same for the authorization server, whose issuer is `<origin>/oidc`. Both documents
+ * therefore live on the deployment's own origin (APP_URL), next to the API and the
+ * issuer they describe.
+ */
+export const API_V1_PATH = '/api/v1';
+
+export const PROTECTED_RESOURCE_METADATA_PATH = `/.well-known/oauth-protected-resource${API_V1_PATH}`;
+
+export const AUTHORIZATION_SERVER_METADATA_PATH = `/.well-known/oauth-authorization-server${OIDC_ISSUER_PATH}`;
+
+const API_AUTH_DOCS_URL = 'https://lobehub.com/docs/development/api/authentication';
+
+/** Scopes a client requests from the issuer for an `/api/v1` access token. */
+const API_TOKEN_SCOPES = ['openid', 'profile', 'email', 'offline_access'];
+
+export const protectedResourceMetadataUrl = (origin: string) =>
+ urlJoin(origin, PROTECTED_RESOURCE_METADATA_PATH);
+
+export const oidcDiscoveryUrl = (origin: string) => urlJoin(origin, OIDC_DISCOVERY_PATH);
+
+/**
+ * RFC 9728 metadata of `<origin>/api/v1`. Without OIDC the API still takes API keys,
+ * so the document stays but names no authorization server.
+ */
+export const buildProtectedResourceMetadata = (origin: string, oidcEnabled: boolean) => ({
+ ...(oidcEnabled
+ ? {
+ authorization_servers: [urlJoin(origin, OIDC_ISSUER_PATH)],
+ scopes_supported: API_TOKEN_SCOPES,
+ }
+ : {}),
+ bearer_methods_supported: ['header'],
+ resource: urlJoin(origin, API_V1_PATH),
+ resource_documentation: API_AUTH_DOCS_URL,
+ resource_name: 'LobeHub API',
+});
+
+/** The `WWW-Authenticate` challenge a 401 from `/api/v1` carries (RFC 6750, RFC 9728 §5.1). */
+export const apiBearerChallenge = (origin: string) =>
+ `Bearer realm="LobeHub API", resource_metadata="${protectedResourceMetadataUrl(origin)}"`;
diff --git a/src/libs/oidc-provider/protected-resource-metadata-route.test.ts b/src/libs/oidc-provider/protected-resource-metadata-route.test.ts
new file mode 100644
index 00000000000..32fb99e2e0b
--- /dev/null
+++ b/src/libs/oidc-provider/protected-resource-metadata-route.test.ts
@@ -0,0 +1,29 @@
+// The route lives under `.well-known`, a dot directory vitest excludes, so its test sits here.
+import { describe, expect, it, vi } from 'vitest';
+
+const auth = vi.hoisted(() => ({ ENABLE_OIDC: true }));
+
+vi.mock('@/envs/app', () => ({ appEnv: { APP_URL: 'https://app.lobehub.com' } }));
+vi.mock('@/envs/auth', () => ({ authEnv: auth }));
+
+const { GET: getProtectedResourceMetadata } =
+ await import('@/app/(backend)/.well-known/oauth-protected-resource/api/v1/route');
+
+describe('GET /.well-known/oauth-protected-resource/api/v1', () => {
+ it('describes the /api/v1 resource and its issuer (RFC 9728)', async () => {
+ auth.ENABLE_OIDC = true;
+ const res = getProtectedResourceMetadata();
+ const body = await res.json();
+
+ expect(body.resource).toBe('https://app.lobehub.com/api/v1');
+ expect(body.authorization_servers).toEqual(['https://app.lobehub.com/oidc']);
+ expect(body.bearer_methods_supported).toEqual(['header']);
+ expect(res.headers.get('Access-Control-Allow-Origin')).toBe('*');
+ });
+
+ it('names no authorization server without OIDC', async () => {
+ auth.ENABLE_OIDC = false;
+
+ expect(await getProtectedResourceMetadata().json()).not.toHaveProperty('authorization_servers');
+ });
+});