Skip to content

JiuwenSwarm is an intelligent AI Agent built on openJiuwen. It extends the powerful capabilities of large language models directly to your fingertips through various communication apps you use daily.

Python

fix(auth): refresh expired enterprise sessions

whqbdf1f007d0ce
diff --git a/jiuwenswarm/channels/web/frontend/package.json b/jiuwenswarm/channels/web/frontend/package.json
index 993138e859..ae7ea298fb 100644
--- a/jiuwenswarm/channels/web/frontend/package.json
+++ b/jiuwenswarm/channels/web/frontend/package.json
@@ -24,6 +24,7 @@
"test:file-download-dedup": "tsc src/utils/fileDownloadDedup.ts --target ES2020 --module ES2020 --moduleResolution Bundler --rootDir src --outDir node_modules/.cache/file-download-dedup --skipLibCheck --noEmitOnError && node --test tests/fileDownloadDedup.test.mjs",
"test:web-http-client": "tsc src/services/webHttpClient.ts --target ES2020 --module ES2020 --moduleResolution Bundler --rootDir src --outDir node_modules/.cache/web-http-client --skipLibCheck --noEmitOnError && node --test tests/webHttpClient.test.mjs",
"test:runtime-scope": "tsc src/services/runtimeScope.ts --target ES2020 --module ES2020 --moduleResolution Bundler --rootDir src --outDir node_modules/.cache/runtime-scope --skipLibCheck --noEmitOnError && node --test tests/runtimeScope.test.mjs",
+ "test:auth-session": "tsc src/auth/manager/authSession.ts --target ES2020 --module ES2020 --moduleResolution Bundler --rootDir src --outDir node_modules/.cache/auth-session --skipLibCheck --noEmitOnError && node --test tests/authSession.test.mjs",
"test:user-web-entry": "esbuild src/EnterpriseEntry.tsx --bundle --packages=external --platform=node --format=esm --outfile=node_modules/.cache/user-web-entry/EnterpriseEntry.mjs --alias:virtual:login-auth-simulate-provider=./src/auth/simulate/available.ts --define:import.meta.env.VITE_JIUWENSWARM_EDITION='\"personal\"' --define:import.meta.env.VITE_LOGIN_AUTH_SIMULATE='\"false\"' && esbuild src/auth/config.ts src/auth/simulate/SimulatedAuthProvider.ts --bundle --packages=external --platform=node --format=esm --outdir=node_modules/.cache/user-web-entry/auth && node --test tests/userWebEntry.test.mjs",
"test:editable-combobox": "tsc src/components/SessionSidebar/editableComboboxModel.ts --target ES2020 --module ES2020 --moduleResolution Bundler --rootDir src --outDir node_modules/.cache/editable-combobox --skipLibCheck --noEmitOnError && node --test tests/editableCombobox.test.mjs",
"test:click-outside": "tsc src/components/SessionSidebar/clickOutside.ts --target ES2020 --module ES2020 --moduleResolution Bundler --rootDir src --outDir node_modules/.cache/click-outside --skipLibCheck --noEmitOnError && node --test tests/clickOutside.test.mjs",
diff --git a/jiuwenswarm/channels/web/frontend/src/auth/manager/ManagerAuthProvider.ts b/jiuwenswarm/channels/web/frontend/src/auth/manager/ManagerAuthProvider.ts
index f6fc2a1634..9c0c0b9e64 100644
--- a/jiuwenswarm/channels/web/frontend/src/auth/manager/ManagerAuthProvider.ts
+++ b/jiuwenswarm/channels/web/frontend/src/auth/manager/ManagerAuthProvider.ts
@@ -5,10 +5,13 @@ import type {
EnterpriseUser,
} from '../../services/enterpriseContext';
import { EnterpriseAuthError, type EnterpriseAuthProvider } from '../types';
-import { isAuthEntryPath } from '../config';
-
-const ACCESS_KEY = 'openjiuwen_access_token';
-const REFRESH_KEY = 'openjiuwen_refresh_token';
+import {
+ clearManagerTokens,
+ getManagerAccessToken,
+ getManagerRefreshToken,
+ managerAuthenticatedFetch,
+ redirectToManagerLogin,
+} from './authSession';
interface ManagerResponse<T> {
code: number;
@@ -16,15 +19,6 @@ interface ManagerResponse<T> {
data: T;
}
-function accessToken(): string | null {
- return typeof localStorage === 'undefined' ? null : localStorage.getItem(ACCESS_KEY);
-}
-
-function authHeaders(): HeadersInit {
- const token = accessToken();
- return token ? { Authorization: `Bearer ${token}` } : {};
-}
-
function requestMessage(body: unknown, fallback: string): string {
if (body && typeof body === 'object') {
const value = body as Record<string, unknown>;
@@ -37,7 +31,7 @@ function requestMessage(body: unknown, fallback: string): string {
async function requestJson<T>(path: string): Promise<T> {
let response: Response;
try {
- response = await fetch(path, { headers: authHeaders() });
+ response = await managerAuthenticatedFetch(path);
} catch (error) {
throw new EnterpriseAuthError(0, `网络请求失败:${error instanceof Error ? error.message : String(error)}`);
}
@@ -51,25 +45,12 @@ async function requestJson<T>(path: string): Promise<T> {
return body as T;
}
-function clearLogin(): void {
- if (typeof localStorage !== 'undefined') {
- localStorage.removeItem(ACCESS_KEY);
- localStorage.removeItem(REFRESH_KEY);
- }
- if (typeof document !== 'undefined') {
- document.cookie = `${ACCESS_KEY}=; Path=/; Max-Age=0; SameSite=Strict`;
- }
-}
-
export const managerAuthProvider: EnterpriseAuthProvider = {
id: 'manager',
startupMessage: '【正式身份认证模式,依赖manager ID认证服务】',
- isAuthenticated: () => Boolean(accessToken()),
+ isAuthenticated: () => Boolean(getManagerAccessToken()),
redirectToLogin() {
- clearLogin();
- if (isAuthEntryPath(window.location.pathname)) return false;
- window.location.replace('/auth');
- return true;
+ return redirectToManagerLogin();
},
getCurrentUser: () => requestJson<EnterpriseUser>('/idp/v1/auth/me'),
async listOrganizations() {
@@ -88,18 +69,24 @@ export const managerAuthProvider: EnterpriseAuthProvider = {
return result.data?.agents ?? [];
},
async logout() {
- const refreshToken = typeof localStorage === 'undefined' ? null : localStorage.getItem(REFRESH_KEY);
+ const refreshToken = getManagerRefreshToken();
if (refreshToken) {
try {
await fetch('/idp/v1/auth/logout', {
method: 'POST',
- headers: { ...authHeaders(), 'Content-Type': 'application/json' },
+ headers: {
+ ...(getManagerAccessToken()
+ ? { Authorization: `Bearer ${getManagerAccessToken()}` }
+ : {}),
+ 'Content-Type': 'application/json',
+ },
body: JSON.stringify({ refresh_token: refreshToken }),
});
} catch {
// Local logout must still complete when the identity service is unavailable.
}
}
+ clearManagerTokens();
this.redirectToLogin();
},
};
diff --git a/jiuwenswarm/channels/web/frontend/src/auth/manager/authSession.ts b/jiuwenswarm/channels/web/frontend/src/auth/manager/authSession.ts
new file mode 100644
index 0000000000..76dfd965c8
--- /dev/null
+++ b/jiuwenswarm/channels/web/frontend/src/auth/manager/authSession.ts
@@ -0,0 +1,137 @@
+const ACCESS_KEY = 'openjiuwen_access_token';
+const REFRESH_KEY = 'openjiuwen_refresh_token';
+
+interface TokenBundle {
+ access_token: string;
+ refresh_token: string;
+}
+
+let refreshInFlight: Promise<boolean> | null = null;
+let redirectStarted = false;
+
+function storageValue(key: string): string | null {
+ return typeof localStorage === 'undefined' ? null : localStorage.getItem(key);
+}
+
+function syncAccessCookie(accessToken: string | null): void {
+ if (typeof document === 'undefined') return;
+ const secure = typeof window !== 'undefined' && window.location.protocol === 'https:' ? '; Secure' : '';
+ if (accessToken) {
+ document.cookie = `${ACCESS_KEY}=${encodeURIComponent(accessToken)}; Path=/; SameSite=Strict${secure}`;
+ } else {
+ document.cookie = `${ACCESS_KEY}=; Path=/; Max-Age=0; SameSite=Strict${secure}`;
+ }
+}
+
+export function getManagerAccessToken(): string | null {
+ return storageValue(ACCESS_KEY);
+}
+
+export function getManagerRefreshToken(): string | null {
+ return storageValue(REFRESH_KEY);
+}
+
+export function hasManagerSessionCredentials(): boolean {
+ return Boolean(getManagerAccessToken() || getManagerRefreshToken());
+}
+
+export function setManagerTokens(accessToken: string, refreshToken: string): void {
+ if (typeof localStorage !== 'undefined') {
+ localStorage.setItem(ACCESS_KEY, accessToken);
+ localStorage.setItem(REFRESH_KEY, refreshToken);
+ }
+ syncAccessCookie(accessToken);
+ redirectStarted = false;
+}
+
+export function clearManagerTokens(): void {
+ if (typeof localStorage !== 'undefined') {
+ localStorage.removeItem(ACCESS_KEY);
+ localStorage.removeItem(REFRESH_KEY);
+ }
+ syncAccessCookie(null);
+}
+
+export function redirectToManagerLogin(): boolean {
+ clearManagerTokens();
+ if (typeof window === 'undefined' || /^\/auth\/?$/.test(window.location.pathname)) {
+ return false;
+ }
+ if (!redirectStarted) {
+ redirectStarted = true;
+ window.location.replace('/auth');
+ }
+ return true;
+}
+
+function withCurrentAccessToken(init: RequestInit, accessToken: string | null): RequestInit {
+ const headers = new Headers(init.headers);
+ if (accessToken) headers.set('Authorization', `Bearer ${accessToken}`);
+ else headers.delete('Authorization');
+ return { ...init, headers };
+}
+
+function isTokenBundle(value: unknown): value is TokenBundle {
+ if (!value || typeof value !== 'object') return false;
+ const bundle = value as Record<string, unknown>;
+ return (
+ typeof bundle.access_token === 'string' &&
+ Boolean(bundle.access_token.trim()) &&
+ typeof bundle.refresh_token === 'string' &&
+ Boolean(bundle.refresh_token.trim())
+ );
+}
+
+async function performRefresh(): Promise<boolean> {
+ const refreshToken = getManagerRefreshToken();
+ const accessBeforeRefresh = getManagerAccessToken();
+ if (!refreshToken) return false;
+ try {
+ const response = await fetch('/idp/v1/auth/refresh', {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ refresh_token: refreshToken }),
+ });
+ if (!response.ok) {
+ return getManagerRefreshToken() !== refreshToken && getManagerAccessToken() !== accessBeforeRefresh;
+ }
+ const body: unknown = await response.json();
+ if (!isTokenBundle(body)) return false;
+ setManagerTokens(body.access_token, body.refresh_token);
+ return true;
+ } catch {
+ return false;
+ }
+}
+
+export function refreshManagerSession(): Promise<boolean> {
+ if (refreshInFlight) return refreshInFlight;
+ refreshInFlight = performRefresh().finally(() => {
+ refreshInFlight = null;
+ });
+ return refreshInFlight;
+}
+
+/**
+ * Send one request with the current access token. A first 401 performs a
+ * single-flight refresh and retries exactly once with the rotated token pair.
+ */
+export async function managerAuthenticatedFetch(input: RequestInfo | URL, init: RequestInit = {}): Promise<Response> {
+ const accessUsed = getManagerAccessToken();
+ const response = await fetch(input, withCurrentAccessToken(init, accessUsed));
+ if (response.status !== 401) return response;
+
+ // Another concurrent request may already have refreshed while this request
+ // was in flight. Retry with that token without rotating refresh again.
+ const currentAccess = getManagerAccessToken();
+ if (currentAccess && currentAccess !== accessUsed) {
+ return fetch(input, withCurrentAccessToken(init, currentAccess));
+ }
+
+ if (await refreshManagerSession()) {
+ return fetch(input, withCurrentAccessToken(init, getManagerAccessToken()));
+ }
+
+ redirectToManagerLogin();
+ return response;
+}
diff --git a/jiuwenswarm/channels/web/frontend/src/services/webHttpClient.ts b/jiuwenswarm/channels/web/frontend/src/services/webHttpClient.ts
index 53a0b3dc22..f4af9eb1b6 100644
--- a/jiuwenswarm/channels/web/frontend/src/services/webHttpClient.ts
+++ b/jiuwenswarm/channels/web/frontend/src/services/webHttpClient.ts
@@ -11,6 +11,10 @@ import {
} from '../types';
import { getGatewayHttpBase } from '../utils/env';
import { isEnterprise } from '../edition';
+import {
+ hasManagerSessionCredentials,
+ managerAuthenticatedFetch,
+} from '../auth/manager/authSession';
import i18n from '../i18n';
import { buildRuntimeIdentityHeaders } from './runtimeScope';
import { PauseBufferHook, PAUSABLE_STREAM_EVENTS } from './webClient';
@@ -673,7 +677,7 @@ export class WebHttpClient {
if (assembled.jsonBody) {
headers['Content-Type'] = 'application/json';
}
- const response = await fetch(appendQuery(assembled.url, assembled.query), {
+ const response = await this.authenticatedFetch(appendQuery(assembled.url, assembled.query), {
method: assembled.verb,
headers,
body: assembled.jsonBody ? JSON.stringify(assembled.jsonBody) : undefined,
@@ -799,7 +803,7 @@ export class WebHttpClient {
this.connectAbort = new AbortController();
const url = `${getGatewayHttpBase().replace(/\/+$/, '')}/connection/status`;
try {
- const response = await fetch(url, {
+ const response = await this.authenticatedFetch(url, {
method: 'GET',
headers: this.identityHeaders(requestId, {}),
signal: this.connectAbort.signal,
@@ -907,7 +911,7 @@ export class WebHttpClient {
if (!assembled) {
return;
}
- await fetch(appendQuery(assembled.url, assembled.query), {
+ await this.authenticatedFetch(appendQuery(assembled.url, assembled.query), {
method: assembled.verb,
headers: {
...this.identityHeaders(requestId, { session_id: sessionId }),
@@ -960,6 +964,13 @@ export class WebHttpClient {
return buildRuntimeIdentityHeaders(requestId, params);
}
+ private authenticatedFetch(input: RequestInfo | URL, init: RequestInit): Promise<Response> {
+ if (isEnterprise() && hasManagerSessionCredentials()) {
+ return managerAuthenticatedFetch(input, init);
+ }
+ return fetch(input, init);
+ }
+
private dispatchEvent(event: WsEvent): void {
if (this.streamEventFilter && !this.streamEventFilter(event)) {
return;
diff --git a/jiuwenswarm/channels/web/frontend/tests/authSession.test.mjs b/jiuwenswarm/channels/web/frontend/tests/authSession.test.mjs
new file mode 100644
index 0000000000..af0a01dddd
--- /dev/null
+++ b/jiuwenswarm/channels/web/frontend/tests/authSession.test.mjs
@@ -0,0 +1,149 @@
+import assert from 'node:assert/strict';
+import test from 'node:test';
+
+const values = new Map();
+let cookie = '';
+let redirects = [];
+
+globalThis.localStorage = {
+ getItem(key) {
+ return values.get(key) ?? null;
+ },
+ removeItem(key) {
+ values.delete(key);
+ },
+ setItem(key, value) {
+ values.set(key, String(value));
+ },
+};
+globalThis.document = {
+ get cookie() {
+ return cookie;
+ },
+ set cookie(value) {
+ cookie = String(value);
+ },
+};
+globalThis.window = {
+ location: {
+ pathname: '/chat/',
+ protocol: 'http:',
+ replace(path) {
+ redirects.push(path);
+ },
+ },
+};
+
+const { clearManagerTokens, getManagerAccessToken, getManagerRefreshToken, managerAuthenticatedFetch, setManagerTokens } =
+ await import('../node_modules/.cache/auth-session/auth/manager/authSession.js');
+
+function reset() {
+ values.clear();
+ cookie = '';
+ redirects = [];
+ window.location.pathname = '/chat/';
+}
+
+function authHeader(init) {
+ return new Headers(init?.headers).get('Authorization');
+}
+
+test('concurrent 401 responses share one refresh and retry with the rotated access token', async () => {
+ reset();
+ setManagerTokens('old-access', 'old-refresh');
+ let refreshCalls = 0;
+ let protectedCalls = 0;
+
+ globalThis.fetch = async (input, init) => {
+ if (String(input) === '/idp/v1/auth/refresh') {
+ refreshCalls += 1;
+ await new Promise(resolve => setTimeout(resolve, 5));
+ return new Response(
+ JSON.stringify({
+ access_token: 'new-access',
+ refresh_token: 'new-refresh',
+ }),
+ { status: 200, headers: { 'Content-Type': 'application/json' } },
+ );
+ }
+ protectedCalls += 1;
+ const authorized = authHeader(init) === 'Bearer new-access';
+ return new Response(JSON.stringify({ ok: authorized }), {
+ status: authorized ? 200 : 401,
+ headers: { 'Content-Type': 'application/json' },
+ });
+ };
+
+ const responses = await Promise.all([managerAuthenticatedFetch('/gateway-api/v1/health'), managerAuthenticatedFetch('/gateway-api/v1/sessions')]);
+
+ assert.deepEqual(
+ responses.map(response => response.status),
+ [200, 200],
+ );
+ assert.equal(refreshCalls, 1);
+ assert.equal(protectedCalls, 4);
+ assert.equal(getManagerAccessToken(), 'new-access');
+ assert.equal(getManagerRefreshToken(), 'new-refresh');
+ assert.match(cookie, /^openjiuwen_access_token=new-access;/);
+ assert.deepEqual(redirects, []);
+});
+
+test('a failed refresh clears the session and redirects to the login page', async () => {
+ reset();
+ setManagerTokens('expired-access', 'expired-refresh');
+ let refreshCalls = 0;
+ globalThis.fetch = async input => {
+ if (String(input) === '/idp/v1/auth/refresh') {
+ refreshCalls += 1;
+ return new Response('{"detail":"auth_invalid_refresh"}', { status: 401 });
+ }
+ return new Response('{"detail":"invalid or expired token"}', { status: 401 });
+ };
+
+ const response = await managerAuthenticatedFetch('/gateway-api/v1/sessions/session-1/history');
+
+ assert.equal(response.status, 401);
+ assert.equal(refreshCalls, 1);
+ assert.equal(getManagerAccessToken(), null);
+ assert.equal(getManagerRefreshToken(), null);
+ assert.match(cookie, /Max-Age=0/);
+ assert.deepEqual(redirects, ['/auth']);
+});
+
+test('the retried request is sent only once even when it also returns 401', async () => {
+ reset();
+ setManagerTokens('old-access', 'refresh-1');
+ let refreshCalls = 0;
+ let protectedCalls = 0;
+ globalThis.fetch = async input => {
+ if (String(input) === '/idp/v1/auth/refresh') {
+ refreshCalls += 1;
+ return new Response(
+ JSON.stringify({
+ access_token: 'new-access',
+ refresh_token: 'refresh-2',
+ }),
+ { status: 200, headers: { 'Content-Type': 'application/json' } },
+ );
+ }
+ protectedCalls += 1;
+ return new Response('{"detail":"still unauthorized"}', { status: 401 });
+ };
+
+ const response = await managerAuthenticatedFetch('/gateway-api/v1/health');
+
+ assert.equal(response.status, 401);
+ assert.equal(refreshCalls, 1);
+ assert.equal(protectedCalls, 2);
+ assert.deepEqual(redirects, []);
+});
+
+test('clearing tokens removes both local values and expires the access cookie', () => {
+ reset();
+ setManagerTokens('access', 'refresh');
+ clearManagerTokens();
+
+ assert.equal(getManagerAccessToken(), null);
+ assert.equal(getManagerRefreshToken(), null);
+ assert.match(cookie, /Max-Age=0/);
+});