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(oidc): sign the acceptance extension in from the web session without login and consent pages (#23026)

Inneic10ff5d81d5c
diff --git a/src/app/(backend)/oidc/extension-sign-in/[uid]/route.test.ts b/src/app/(backend)/oidc/extension-sign-in/[uid]/route.test.ts
new file mode 100644
index 00000000000..7d9ec2cc549
--- /dev/null
+++ b/src/app/(backend)/oidc/extension-sign-in/[uid]/route.test.ts
@@ -0,0 +1,94 @@
+/**
+ * @vitest-environment node
+ */
+import type { NextRequest } from 'next/server';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { GET } from './route';
+
+const mocks = vi.hoisted(() => ({
+ authEnv: { ENABLE_OIDC: true },
+ getInteractionDetails: vi.fn(),
+ getInteractionResult: vi.fn(),
+ getUserAuth: vi.fn(),
+}));
+
+vi.mock('@lobechat/utils/server', () => ({ getUserAuth: mocks.getUserAuth }));
+vi.mock('debug', () => ({ default: () => vi.fn() }));
+vi.mock('@/envs/auth', () => ({ authEnv: mocks.authEnv }));
+vi.mock('@/server/services/oidc', () => ({
+ OIDCService: {
+ initialize: vi.fn(async () => ({
+ getInteractionDetails: mocks.getInteractionDetails,
+ getInteractionResult: mocks.getInteractionResult,
+ })),
+ },
+}));
+
+const visit = (uid: string, search = '') =>
+ GET(
+ new Request(
+ `https://example.com/oidc/extension-sign-in/${uid}${search}`,
+ ) as unknown as NextRequest,
+ { params: Promise.resolve({ uid }) },
+ );
+
+const loginFor = (clientId: string) => ({
+ params: { client_id: clientId },
+ prompt: { name: 'login' },
+});
+
+describe('GET /oidc/extension-sign-in/[uid]', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ mocks.authEnv.ENABLE_OIDC = true;
+ mocks.getInteractionDetails.mockResolvedValue(loginFor('lobehub-acceptance-extension'));
+ mocks.getUserAuth.mockResolvedValue({ userId: 'user_1' });
+ mocks.getInteractionResult.mockResolvedValue('http://internal-host/oidc/auth/uid-1?x=1');
+ });
+
+ it('returns 404 when OIDC is not enabled', async () => {
+ mocks.authEnv.ENABLE_OIDC = false;
+
+ expect((await visit('uid-1')).status).toBe(404);
+ expect(mocks.getInteractionDetails).not.toHaveBeenCalled();
+ });
+
+ it('signs a reviewer with a web session in and resumes on the same origin', async () => {
+ const response = await visit('uid-1');
+
+ expect(mocks.getInteractionResult).toHaveBeenCalledWith('uid-1', {
+ login: { accountId: 'user_1', remember: true },
+ });
+ expect(response.status).toBe(303);
+ expect(response.headers.get('location')).toBe('/oidc/auth/uid-1?x=1');
+ });
+
+ it('hands a browser with no web session to the sign-in page, keeping its language', async () => {
+ mocks.getUserAuth.mockResolvedValue({ userId: undefined });
+
+ const response = await visit('uid-1', '?hl=zh-CN');
+
+ expect(mocks.getInteractionResult).not.toHaveBeenCalled();
+ expect(response.status).toBe(303);
+ expect(response.headers.get('location')).toBe('/oauth/consent/uid-1?hl=zh-CN');
+ });
+
+ it('never signs in for another client or another prompt', async () => {
+ mocks.getInteractionDetails.mockResolvedValue(loginFor('lobehub-desktop'));
+ expect((await visit('uid-1')).headers.get('location')).toBe('/oauth/consent/uid-1');
+
+ mocks.getInteractionDetails.mockResolvedValue({
+ params: { client_id: 'lobehub-acceptance-extension' },
+ prompt: { name: 'consent' },
+ });
+ expect((await visit('uid-1')).headers.get('location')).toBe('/oauth/consent/uid-1');
+ expect(mocks.getInteractionResult).not.toHaveBeenCalled();
+ });
+
+ it('leaves an interaction it cannot read to the consent page', async () => {
+ mocks.getInteractionDetails.mockRejectedValue(new Error('interaction session not found'));
+
+ expect((await visit('uid-1')).headers.get('location')).toBe('/oauth/consent/uid-1');
+ });
+});
diff --git a/src/app/(backend)/oidc/extension-sign-in/[uid]/route.ts b/src/app/(backend)/oidc/extension-sign-in/[uid]/route.ts
new file mode 100644
index 00000000000..7afad77d4cc
--- /dev/null
+++ b/src/app/(backend)/oidc/extension-sign-in/[uid]/route.ts
@@ -0,0 +1,46 @@
+import { getUserAuth } from '@lobechat/utils/server';
+import debug from 'debug';
+import { type NextRequest, NextResponse } from 'next/server';
+
+import { authEnv } from '@/envs/auth';
+import { isAcceptanceExtensionClient } from '@/libs/oidc-provider/acceptanceReview';
+import { OIDCService } from '@/server/services/oidc';
+
+const log = debug('lobe-oidc:extension-sign-in');
+
+const seeOther = (location: string) =>
+ new NextResponse(null, { headers: { location }, status: 303 });
+
+const webSessionLogin = async (uid: string) => {
+ const oidcService = await OIDCService.initialize();
+ const details = await oidcService.getInteractionDetails(uid);
+ if (
+ details.prompt.name !== 'login' ||
+ !isAcceptanceExtensionClient(details.params.client_id as string | undefined)
+ )
+ return undefined;
+
+ const { userId } = await getUserAuth();
+ if (!userId) return undefined;
+
+ const resume = await oidcService.getInteractionResult(uid, {
+ login: { accountId: userId, remember: true },
+ });
+ // The gateway rewrites Host on the way to the origin, so only a relative Location keeps the
+ // browser on the origin that holds the interaction cookies.
+ const { hash, pathname, search } = new URL(resume);
+ return `${pathname}${search}${hash}`;
+};
+
+export async function GET(request: NextRequest, props: { params: Promise<{ uid: string }> }) {
+ if (!authEnv.ENABLE_OIDC) return new NextResponse(null, { status: 404 });
+
+ const { uid } = await props.params;
+ const consentPage = `/oauth/consent/${uid}${new URL(request.url).search}`;
+ try {
+ return seeOther((await webSessionLogin(uid)) ?? consentPage);
+ } catch (error) {
+ log('Falling back to the consent page for %s: %O', uid, error);
+ return seeOther(consentPage);
+ }
+}
diff --git a/src/libs/oidc-provider/acceptanceReview.ts b/src/libs/oidc-provider/acceptanceReview.ts
index 537505e5b6c..91fc41e9404 100644
--- a/src/libs/oidc-provider/acceptanceReview.ts
+++ b/src/libs/oidc-provider/acceptanceReview.ts
@@ -36,6 +36,45 @@ export const extensionCorsDecision = (clientId: string | undefined, origin: stri
return ACCEPTANCE_EXTENSION_IDS.some((id) => origin === `chrome-extension://${id}`);
};
+// The extension is first-party, so a reviewer with a web session signs in without the login and
+// consent pages. PKCE and the registered redirect keep web pages out, but another browser
+// extension that can read tab URLs could start this flow and redeem the code without a click;
+// that was accepted for the acceptance:extension scope only.
+export const EXTENSION_SIGN_IN_PATH = '/oidc/extension-sign-in';
+
+export const interactionPathFor = (clientId: string | undefined, prompt: string, uid: string) =>
+ isAcceptanceExtensionClient(clientId) && prompt === 'login'
+ ? `${EXTENSION_SIGN_IN_PATH}/${uid}`
+ : `/oauth/consent/${uid}`;
+
+export const extensionGrantScopes = (clientId: string | undefined) =>
+ isAcceptanceExtensionClient(clientId)
+ ? {
+ oidc: `openid profile ${ACCEPTANCE_EXTENSION_SCOPE}`,
+ resource: ACCEPTANCE_EXTENSION_RESOURCE,
+ resourceScope: ACCEPTANCE_EXTENSION_SCOPE,
+ }
+ : null;
+
+// oidc-provider drops offline_access from a request that does not prompt for consent, and with
+// it the refresh token; the extension cannot stay signed in without one.
+export const issuesRefreshToken = (
+ client: { clientId: string; grantTypeAllowed: (type: string) => boolean },
+ scopes: Set<string>,
+) =>
+ client.grantTypeAllowed('refresh_token') &&
+ (scopes.has('offline_access') || isAcceptanceExtensionClient(client.clientId));
+
+// A token issued without offline_access normally dies with the browser's provider session, which
+// would sign the extension out whenever the reviewer signs out of the web app.
+export const expiresWithSession = (source: { clientId?: string; scopes: Set<string> }) =>
+ !source.scopes.has('offline_access') && !isAcceptanceExtensionClient(source.clientId);
+
+// Without this the provider reuses whatever account its own session cookie holds, which can be a
+// different person than the one signed in to the web app.
+export const needsWebSessionLogin = (clientId: string | undefined, loggedIn: boolean) =>
+ isAcceptanceExtensionClient(clientId) && !loggedIn;
+
export const defaultResourceFor = (clientId: string | undefined, fallback: string) =>
isAcceptanceExtensionClient(clientId) ? ACCEPTANCE_EXTENSION_RESOURCE : fallback;
diff --git a/src/libs/oidc-provider/interaction-policy.ts b/src/libs/oidc-provider/interaction-policy.ts
index 8e312c18d1f..80325685802 100644
--- a/src/libs/oidc-provider/interaction-policy.ts
+++ b/src/libs/oidc-provider/interaction-policy.ts
@@ -1,37 +1,28 @@
import debug from 'debug';
import { interactionPolicy } from 'oidc-provider';
-const { base } = interactionPolicy; // Import Check and base
+import { needsWebSessionLogin } from './acceptanceReview';
+
+const { base, Check } = interactionPolicy;
const log = debug('lobe-oidc:interaction-policy');
-/**
- * Create custom interaction policy
- */
export const createInteractionPolicy = () => {
- log('Creating custom interaction policy');
const policy = base();
-
- log('Base policy details: %O', {
- promptNames: Array.from(policy.keys()),
- size: policy.length,
- });
-
const loginPrompt = policy.get('login');
- log('Accessing login prompt from policy: %O', !!loginPrompt);
- if (loginPrompt) {
- log('Login prompt details: %O', {
- checks: Array.from(loginPrompt.checks.keys()),
- name: loginPrompt.name,
- requestable: loginPrompt.requestable,
- });
- } else {
- console.warn(
- "Could not find 'login' prompt in the base policy. Custom session check not applied.",
- );
+ if (!loginPrompt) {
+ console.warn("Could not find 'login' prompt in the base policy.");
log('WARNING: login prompt not found in base policy');
+ return policy;
}
- log('Custom interaction policy created successfully');
+ loginPrompt.checks.add(
+ new Check('web_session_login', 'the web session decides who signs in', (ctx) =>
+ needsWebSessionLogin(ctx.oidc.client?.clientId, Boolean(ctx.oidc.result?.login))
+ ? Check.REQUEST_PROMPT
+ : Check.NO_NEED_TO_PROMPT,
+ ),
+ );
+
return policy;
};
diff --git a/src/libs/oidc-provider/provider.extension-sign-in.test.ts b/src/libs/oidc-provider/provider.extension-sign-in.test.ts
new file mode 100644
index 00000000000..6831c68c4ee
--- /dev/null
+++ b/src/libs/oidc-provider/provider.extension-sign-in.test.ts
@@ -0,0 +1,332 @@
+/**
+ * @vitest-environment node
+ *
+ * Boots the real provider configuration and walks the acceptance extension's
+ * sign-in over HTTP, standing in for the app route that turns a web session
+ * into the provider's login result.
+ */
+import { createHash, randomBytes } from 'node:crypto';
+import { createServer, type Server } from 'node:http';
+import type { AddressInfo } from 'node:net';
+
+import {
+ ACCEPTANCE_EXTENSION_CLIENT_ID,
+ ACCEPTANCE_EXTENSION_IDS,
+ ACCEPTANCE_EXTENSION_RESOURCE,
+} from '@lobechat/const';
+import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest';
+
+const USER_ID = 'user_reviewer';
+const REDIRECT_URI = `https://${ACCEPTANCE_EXTENSION_IDS[0]}.chromiumapp.org/oidc`;
+const SIGN_IN_PATH = '/oidc/extension-sign-in/';
+
+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('@/libs/oidc-provider/adapter', () => {
+ const store = ((globalThis as any).oidcTestStore = 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 } };
+});
+
+const { createOIDCProvider } = await import('./provider');
+
+let provider: Awaited<ReturnType<typeof createOIDCProvider>>;
+let server: Server;
+let origin: string;
+
+const stored = (model: string) =>
+ [...((globalThis as any).oidcTestStore as Map<string, unknown>).keys()].filter((key) =>
+ key.startsWith(`${model}:`),
+ );
+
+let loginAs = USER_ID;
+
+const browser = () => {
+ const jar = new Map<string, string>();
+ const visit = async (path: string) => {
+ const response = await fetch(origin + path, {
+ headers: { cookie: [...jar].map(([name, value]) => `${name}=${value}`).join('; ') },
+ redirect: 'manual',
+ });
+ for (const cookie of response.headers.getSetCookie()) {
+ const [pair] = cookie.split(';');
+ const at = pair!.indexOf('=');
+ jar.set(pair!.slice(0, at), pair!.slice(at + 1));
+ }
+ const location = response.headers.get('location');
+ const next = location ? new URL(location, origin) : undefined;
+ return { next, status: response.status };
+ };
+ return { jar, visit };
+};
+
+const authorize = (extra: Record<string, string> = {}) => {
+ const verifier = randomBytes(32).toString('base64url');
+ const query = new URLSearchParams({
+ client_id: ACCEPTANCE_EXTENSION_CLIENT_ID,
+ code_challenge: createHash('sha256').update(verifier).digest('base64url'),
+ code_challenge_method: 'S256',
+ redirect_uri: REDIRECT_URI,
+ resource: ACCEPTANCE_EXTENSION_RESOURCE,
+ response_type: 'code',
+ scope: 'openid profile offline_access acceptance:extension',
+ state: 'state-1',
+ ...extra,
+ });
+ return { path: `/oidc/auth?${query}`, verifier };
+};
+
+const exchange = async (code: string, verifier: string) => {
+ const response = await fetch(`${origin}/oidc/token`, {
+ body: new URLSearchParams({
+ client_id: ACCEPTANCE_EXTENSION_CLIENT_ID,
+ code,
+ code_verifier: verifier,
+ grant_type: 'authorization_code',
+ redirect_uri: REDIRECT_URI,
+ }),
+ headers: { 'content-type': 'application/x-www-form-urlencoded' },
+ method: 'POST',
+ });
+ return { body: (await response.json()) as Record<string, string>, status: response.status };
+};
+
+beforeAll(async () => {
+ const { privateKey } = await crypto.subtle.generateKey(
+ {
+ hash: 'SHA-256',
+ modulusLength: 2048,
+ name: 'RSASSA-PKCS1-v1_5',
+ publicExponent: new Uint8Array([1, 0, 1]),
+ },
+ true,
+ ['sign', 'verify'],
+ );
+ const { key_ops: _, ...privateJwk } = await crypto.subtle.exportKey('jwk', privateKey);
+ authEnvMock.JWKS_KEY = JSON.stringify({
+ keys: [{ ...privateJwk, alg: 'RS256', kid: 'test', use: 'sig' }],
+ });
+ provider = await createOIDCProvider({} as any);
+ const handle = provider.callback();
+ server = createServer(async (req, res) => {
+ const login = req.url?.startsWith(SIGN_IN_PATH) || req.url?.startsWith('/test/login/');
+ if (login) {
+ const location = await provider.interactionResult(req, res, {
+ login: { accountId: loginAs, remember: true },
+ });
+ return void res.writeHead(303, { location }).end();
+ }
+ if (req.url?.startsWith('/test/consent/')) {
+ const details = await provider.interactionDetails(req, res);
+ const grant =
+ (details.grantId && (await provider.Grant.find(details.grantId))) ||
+ new provider.Grant({
+ accountId: details.session!.accountId,
+ clientId: details.params.client_id as string,
+ });
+ grant.addOIDCScope(((details.prompt.details.missingOIDCScope as string[]) ?? []).join(' '));
+ const resources = (details.prompt.details.missingResourceScopes ?? {}) as Record<
+ string,
+ string[]
+ >;
+ for (const [indicator, scopes] of Object.entries(resources))
+ grant.addResourceScope(indicator, scopes.join(' '));
+ const location = await provider.interactionResult(req, res, {
+ consent: { grantId: await grant.save() },
+ });
+ return void res.writeHead(303, { location }).end();
+ }
+ return handle(req, res);
+ });
+ 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('acceptance extension sign-in', () => {
+ it('sends a browser with no provider session to the silent sign-in route', async () => {
+ const { visit } = browser();
+ const { next, status } = await visit(authorize().path);
+
+ expect(status).toBe(303);
+ expect(next?.pathname.startsWith(SIGN_IN_PATH)).toBe(true);
+ });
+
+ it('finishes with a code and a refresh token once signed in, without a consent page', async () => {
+ const { visit } = browser();
+ const { path, verifier } = authorize();
+ const signIn = await visit(path);
+ const resume = await visit(signIn.next!.pathname);
+ const done = await visit(resume.next!.pathname);
+
+ expect(done.next?.origin + done.next!.pathname).toBe(REDIRECT_URI);
+ expect(done.next?.searchParams.get('state')).toBe('state-1');
+ const tokens = await exchange(done.next!.searchParams.get('code')!, verifier);
+ expect(tokens.status).toBe(200);
+ expect(tokens.body.refresh_token).toEqual(expect.any(String));
+
+ const refreshed = await fetch(`${origin}/oidc/token`, {
+ body: new URLSearchParams({
+ client_id: ACCEPTANCE_EXTENSION_CLIENT_ID,
+ grant_type: 'refresh_token',
+ refresh_token: tokens.body.refresh_token!,
+ }),
+ headers: { 'content-type': 'application/x-www-form-urlencoded' },
+ method: 'POST',
+ });
+ expect(refreshed.status).toBe(200);
+ expect(((await refreshed.json()) as Record<string, string>).refresh_token).toEqual(
+ expect.any(String),
+ );
+ });
+
+ it('still shows the consent page to an extension build that asks for it', async () => {
+ const { visit } = browser();
+ const signIn = await visit(authorize({ prompt: 'consent' }).path);
+ const resume = await visit(signIn.next!.pathname);
+ const consent = await visit(resume.next!.pathname);
+
+ expect(consent.next?.pathname.startsWith('/oauth/consent/')).toBe(true);
+ });
+
+ it('keeps the reviewer signed in after the browser session that started it is gone', async () => {
+ const { jar, visit } = browser();
+ const { path, verifier } = authorize();
+ const done = await visit((await visit((await visit(path)).next!.pathname)).next!.pathname);
+ const tokens = await exchange(done.next!.searchParams.get('code')!, verifier);
+
+ const sessionId = jar.get('_session')!.split('.')[0]!;
+ await (await provider.Session.find(sessionId))!.destroy();
+
+ const refreshed = await fetch(`${origin}/oidc/token`, {
+ body: new URLSearchParams({
+ client_id: ACCEPTANCE_EXTENSION_CLIENT_ID,
+ grant_type: 'refresh_token',
+ refresh_token: tokens.body.refresh_token!,
+ }),
+ headers: { 'content-type': 'application/x-www-form-urlencoded' },
+ method: 'POST',
+ });
+ expect(refreshed.status).toBe(200);
+ });
+
+ it('asks the web session who is signing in every time, and reuses the grant it made', async () => {
+ const { visit } = browser();
+ const first = authorize();
+ await visit((await visit((await visit(first.path)).next!.pathname)).next!.pathname);
+ const grants = stored('Grant').length;
+
+ const again = await visit(authorize().path);
+ expect(again.next?.pathname.startsWith(SIGN_IN_PATH)).toBe(true);
+ const done = await visit((await visit(again.next!.pathname)).next!.pathname);
+
+ expect(done.next?.origin + done.next!.pathname).toBe(REDIRECT_URI);
+ expect(stored('Grant')).toHaveLength(grants);
+ });
+
+ it('never carries a provider session over to another account', async () => {
+ const { visit } = browser();
+ await visit((await visit((await visit(authorize().path)).next!.pathname)).next!.pathname);
+
+ loginAs = 'user_other';
+ try {
+ const again = await visit(authorize().path);
+ const resumed = await visit((await visit(again.next!.pathname)).next!.pathname);
+
+ expect(resumed.next?.searchParams.get('code')).toBeFalsy();
+ } finally {
+ loginAs = USER_ID;
+ }
+ });
+
+ it('lets an extension build that asks for consent finish there with a refresh token', async () => {
+ const { visit } = browser();
+ const { path, verifier } = authorize({ prompt: 'consent' });
+ const consent = await visit((await visit((await visit(path)).next!.pathname)).next!.pathname);
+ const uid = consent.next!.pathname.split('/').pop()!;
+ const done = await visit((await visit(`/test/consent/${uid}`)).next!.pathname);
+
+ const tokens = await exchange(done.next!.searchParams.get('code')!, verifier);
+ expect(tokens.body.refresh_token).toEqual(expect.any(String));
+ });
+
+ it('still asks another client for consent after sign-in', async () => {
+ const { visit } = browser();
+ const verifier = randomBytes(32).toString('base64url');
+ const query = new URLSearchParams({
+ client_id: 'lobehub-desktop',
+ code_challenge: createHash('sha256').update(verifier).digest('base64url'),
+ code_challenge_method: 'S256',
+ redirect_uri: 'http://localhost:3210/oidc/callback/desktop',
+ response_type: 'code',
+ scope: 'openid profile',
+ });
+ const login = await visit(`/oidc/auth?${query}`);
+ const uid = login.next!.pathname.split('/').pop()!;
+ const consent = await visit((await visit(`/test/login/${uid}`)).next!.pathname);
+
+ expect(consent.next?.pathname.startsWith('/oauth/consent/')).toBe(true);
+ });
+
+ it('keeps every other client on the consent page for sign-in', async () => {
+ const { visit } = browser();
+ const verifier = randomBytes(32).toString('base64url');
+ const query = new URLSearchParams({
+ client_id: 'lobehub-desktop',
+ code_challenge: createHash('sha256').update(verifier).digest('base64url'),
+ code_challenge_method: 'S256',
+ redirect_uri: 'http://localhost:3210/oidc/callback/desktop',
+ response_type: 'code',
+ scope: 'openid profile',
+ });
+ const { next } = await visit(`/oidc/auth?${query}`);
+
+ expect(next?.pathname.startsWith('/oauth/consent/')).toBe(true);
+ });
+});
diff --git a/src/libs/oidc-provider/provider.ts b/src/libs/oidc-provider/provider.ts
index 3590f35f9c6..8a5e0e14399 100644
--- a/src/libs/oidc-provider/provider.ts
+++ b/src/libs/oidc-provider/provider.ts
@@ -15,9 +15,13 @@ import { findSiteForOrigin } from '@/server/services/projectReview/sites';
import {
accessTokenTTL,
defaultResourceFor,
+ expiresWithSession,
extensionCorsDecision,
+ extensionGrantScopes,
extensionResourceServer,
+ interactionPathFor,
isAcceptanceReviewClient,
+ issuesRefreshToken,
reviewResourceServer,
} from './acceptanceReview';
import { isOIDCUserBanned } from './access-control';
@@ -308,16 +312,37 @@ export const createOIDCProvider = async (db: LobeChatDatabase): Promise<Provider
logProvider('No ui_locales provided in authorization request');
}
- const interactionUrl = `/oauth/consent/${interaction.uid}${query}`;
+ const interactionUrl = `${interactionPathFor(ctx.oidc?.client?.clientId, interaction.prompt.name, interaction.uid)}${query}`;
logProvider('Generated interaction URL: %s', interactionUrl);
// ---> End of added logs <---
return interactionUrl;
},
},
+ expiresWithSession: async (_ctx, source) => expiresWithSession(source),
+
+ issueRefreshToken: async (_ctx, client, source) => issuesRefreshToken(client, source.scopes),
+
// 6. Key configuration - using RS256 JWKS
jwks: jwks as { keys: any[] },
+ loadExistingGrant: async (ctx) => {
+ const { client, provider, result, session } = ctx.oidc;
+ const grantId = result?.consent?.grantId || session!.grantIdFor(client!.clientId);
+ if (grantId) return provider.Grant.find(grantId);
+
+ const scopes = extensionGrantScopes(client?.clientId);
+ if (!scopes || !session?.accountId) return undefined;
+ const grant = new provider.Grant({
+ accountId: session.accountId,
+ clientId: client!.clientId,
+ });
+ grant.addOIDCScope(scopes.oidc);
+ grant.addResourceScope(scopes.resource, scopes.resourceScope);
+ await grant.save();
+ return grant;
+ },
+
// 2. PKCE configuration
pkce: {
required: () => true,