Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

fix(billing): 绑定恢复订阅的账号上下文

liugaoweie9af3bcdbfd3
diff --git a/apps/desktop/src/main/__tests__/serverApiClient.test.ts b/apps/desktop/src/main/__tests__/serverApiClient.test.ts
index e6292e0d26..0beb2a5bf1 100644
--- a/apps/desktop/src/main/__tests__/serverApiClient.test.ts
+++ b/apps/desktop/src/main/__tests__/serverApiClient.test.ts
@@ -89,6 +89,57 @@ describe('serverApiFetch', () => {
);
});
+ it('账号上下文在首个 401 返回前变化时不 refresh 或重试', async () => {
+ let retryContextCurrent = true;
+ mocks.getAccessToken.mockReturnValue('token-a');
+ mocks.netFetch.mockImplementationOnce(async () => {
+ retryContextCurrent = false;
+ return {
+ ok: false,
+ status: 401,
+ json: async () => ({ error: { code: 'TOKEN_EXPIRED' } }),
+ };
+ });
+
+ await expect(
+ serverApiFetch('/api/billing/subscription/resume', {
+ method: 'POST',
+ baseUrl: 'https://billing.example.com',
+ isAuthContextCurrent: () => retryContextCurrent,
+ }),
+ ).rejects.toMatchObject({ code: 'TOKEN_EXPIRED', statusCode: 401 });
+
+ expect(mocks.refresh).not.toHaveBeenCalled();
+ expect(mocks.netFetch).toHaveBeenCalledTimes(1);
+ expect(mocks.invalidateSession).not.toHaveBeenCalled();
+ });
+
+ it('refresh 切换账号上下文时不使用新账号 token 重试', async () => {
+ let retryContextCurrent = true;
+ mocks.getAccessToken.mockReturnValue('token-a');
+ mocks.refresh.mockImplementation(async () => {
+ retryContextCurrent = false;
+ return true;
+ });
+ mocks.netFetch.mockResolvedValueOnce({
+ ok: false,
+ status: 401,
+ json: async () => ({ error: { code: 'TOKEN_EXPIRED' } }),
+ });
+
+ await expect(
+ serverApiFetch('/api/billing/subscription/resume', {
+ method: 'POST',
+ baseUrl: 'https://billing.example.com',
+ isAuthContextCurrent: () => retryContextCurrent,
+ }),
+ ).rejects.toMatchObject({ code: 'TOKEN_EXPIRED', statusCode: 401 });
+
+ expect(mocks.refresh).toHaveBeenCalledTimes(1);
+ expect(mocks.netFetch).toHaveBeenCalledTimes(1);
+ expect(mocks.invalidateSession).not.toHaveBeenCalled();
+ });
+
it('refresh 切换区域后重新解析业务端点,避免新 token 重试到旧区域', async () => {
let baseUrl = 'https://resource.cn.example.com';
mocks.getAccessToken.mockReturnValueOnce('token-cn').mockReturnValueOnce('token-global');
@@ -156,6 +207,30 @@ describe('serverApiFetch', () => {
expect(mocks.invalidateSession).toHaveBeenCalledWith('account-unavailable');
});
+ it('旧账号的 ACCOUNT_UNAVAILABLE 响应不退登当前新账号', async () => {
+ let authContextCurrent = true;
+ mocks.getAccessToken.mockReturnValue('token-a');
+ mocks.netFetch.mockImplementationOnce(async () => {
+ authContextCurrent = false;
+ return {
+ ok: false,
+ status: 401,
+ json: async () => ({ error: { code: 'ACCOUNT_UNAVAILABLE' } }),
+ };
+ });
+
+ await expect(
+ serverApiFetch('/api/billing/subscription/resume', {
+ method: 'POST',
+ baseUrl: 'https://billing.example.com',
+ isAuthContextCurrent: () => authContextCurrent,
+ }),
+ ).rejects.toMatchObject({ code: 'ACCOUNT_UNAVAILABLE', statusCode: 401 });
+
+ expect(mocks.refresh).not.toHaveBeenCalled();
+ expect(mocks.invalidateSession).not.toHaveBeenCalled();
+ });
+
it.each(['INVALID_TOKEN', 'UNAUTHORIZED'])('%s refresh 一次后重试', async (code) => {
mocks.getAccessToken.mockReturnValueOnce('token-a').mockReturnValueOnce('token-b');
mocks.refresh.mockResolvedValue(true);
@@ -204,6 +279,37 @@ describe('serverApiFetch', () => {
expect(mocks.invalidateSession).toHaveBeenCalledWith('resource-unauthorized-after-refresh');
});
+ it('重试响应返回前账号变化时不退登当前新账号', async () => {
+ let authContextCurrent = true;
+ mocks.getAccessToken.mockReturnValue('token-a');
+ mocks.refresh.mockResolvedValue(true);
+ mocks.netFetch
+ .mockResolvedValueOnce({
+ ok: false,
+ status: 401,
+ json: async () => ({ error: { code: 'TOKEN_EXPIRED' } }),
+ })
+ .mockImplementationOnce(async () => {
+ authContextCurrent = false;
+ return {
+ ok: false,
+ status: 401,
+ json: async () => ({ error: { code: 'UNAUTHORIZED' } }),
+ };
+ });
+
+ await expect(
+ serverApiFetch('/api/billing/subscription/resume', {
+ method: 'POST',
+ baseUrl: 'https://billing.example.com',
+ isAuthContextCurrent: () => authContextCurrent,
+ }),
+ ).rejects.toMatchObject({ code: 'UNAUTHORIZED', statusCode: 401 });
+
+ expect(mocks.netFetch).toHaveBeenCalledTimes(2);
+ expect(mocks.invalidateSession).not.toHaveBeenCalled();
+ });
+
it.each([
{ name: '403', response: { ok: false, status: 403, json: async () => ({}) } },
{ name: 'network failure', response: new Error('offline') },
diff --git a/apps/desktop/src/main/billing/__tests__/index.test.ts b/apps/desktop/src/main/billing/__tests__/index.test.ts
index 86b7cc202e..25a9e324f8 100644
--- a/apps/desktop/src/main/billing/__tests__/index.test.ts
+++ b/apps/desktop/src/main/billing/__tests__/index.test.ts
@@ -5,6 +5,15 @@ import { BILLING_INVOKE } from '../../../shared/billing.js';
import { ServerApiError } from '../../serverApiClient.js';
import { createBillingHandlers } from '../index.js';
+const ownerBoundary = vi.hoisted(() => ({
+ pending: false,
+ scopeKey: 'cloud:user-a:1',
+}));
+
+vi.mock('../../appSessionState.js', () => ({
+ activeOwnerScopeKey: () => ownerBoundary.scopeKey,
+ isAppSessionBoundaryPending: () => ownerBoundary.pending,
+}));
vi.mock('../../clientEndpointsService.js', () => ({ getClientEndpoint: vi.fn() }));
vi.mock('../../serverApiClient.js', () => {
class ServerApiError extends Error {
@@ -20,6 +29,8 @@ vi.mock('../../serverApiClient.js', () => {
});
function harness() {
+ ownerBoundary.pending = false;
+ ownerBoundary.scopeKey = 'cloud:user-a:1';
const mainFrame = { routingId: 1 };
const mainWebContents = { id: 1, mainFrame };
const mainWindow = {
@@ -303,7 +314,15 @@ describe('billing IPC', () => {
redactErrorDetails: true,
method: 'POST',
allowedRedactedErrorCodes: ['RESUME_NOT_AVAILABLE'],
- });
+ isAuthContextCurrent: expect.any(Function),
+ });
+ const isAuthContextCurrent = fetch.mock.calls[0]?.[1]?.isAuthContextCurrent;
+ expect(isAuthContextCurrent?.()).toBe(true);
+ ownerBoundary.scopeKey = 'cloud:user-b:2';
+ expect(isAuthContextCurrent?.()).toBe(false);
+ ownerBoundary.scopeKey = 'cloud:user-a:1';
+ ownerBoundary.pending = true;
+ expect(isAuthContextCurrent?.()).toBe(false);
});
it('preserves the safe subscription-resume rejection code across IPC', async () => {
diff --git a/apps/desktop/src/main/billing/index.ts b/apps/desktop/src/main/billing/index.ts
index a6a2fec42c..09148e495f 100644
--- a/apps/desktop/src/main/billing/index.ts
+++ b/apps/desktop/src/main/billing/index.ts
@@ -6,6 +6,7 @@ import {
type CreateBillingSubscriptionRequest,
type CreateBillingTopupRequest,
} from '../../shared/billing.js';
+import { activeOwnerScopeKey, isAppSessionBoundaryPending } from '../appSessionState.js';
import { getClientEndpoint } from '../clientEndpointsService.js';
import { ServerApiError, serverApiFetch, type ApiFetchOptions } from '../serverApiClient.js';
import { requireObject, throwIpcError } from '../utils/ipcValidate.js';
@@ -372,10 +373,13 @@ export function createBillingHandlers(
if (raw !== undefined) {
throwIpcError('INVALID_PARAMS', 'subscription resume does not accept a payload');
}
+ const ownerScopeKey = activeOwnerScopeKey();
return projectResponse(
await invoke<unknown>('/api/billing/subscription/resume', {
method: 'POST',
allowedRedactedErrorCodes: ['RESUME_NOT_AVAILABLE'],
+ isAuthContextCurrent: () =>
+ !isAppSessionBoundaryPending() && activeOwnerScopeKey() === ownerScopeKey,
}),
projectBillingSubscription,
);
diff --git a/apps/desktop/src/main/serverApiClient.ts b/apps/desktop/src/main/serverApiClient.ts
index 059234abb5..177ef80c7d 100644
--- a/apps/desktop/src/main/serverApiClient.ts
+++ b/apps/desktop/src/main/serverApiClient.ts
@@ -45,6 +45,11 @@ export interface ApiFetchOptions {
token?: string | null;
/** 跳过 401 自动 refresh(避免无限循环;refresh 自身调用时禁用)。 */
skipAutoRefresh?: boolean;
+ /**
+ * 401 自动 refresh / retry 及会话失效前校验请求上下文;返回 false 时停止处理。
+ * 有账号副作用的调用可用它避免旧请求误操作或失效新账号。
+ */
+ isAuthContextCurrent?: () => boolean;
/**
* 目标服务 base URL(必传;来自 clientEndpoints 的对应字段或注入方)。
* 区域相关服务必须传 resolver:401 refresh 可能切换登录区域,重试前要重新
@@ -137,10 +142,11 @@ export async function serverApiFetch<T>(apiPath: string, opts: ApiFetchOptions):
result.status === 401 &&
!opts.skipAutoRefresh &&
firstCode !== 'ACCOUNT_UNAVAILABLE' &&
- isRefreshableUnauthorizedCode(firstCode)
+ isRefreshableUnauthorizedCode(firstCode) &&
+ opts.isAuthContextCurrent?.() !== false
) {
const refreshed = await authManager.refresh();
- if (refreshed) {
+ if (refreshed && opts.isAuthContextCurrent?.() !== false) {
refreshedAndRetried = true;
result = await rawFetch<T>(apiPath, opts);
}
@@ -151,6 +157,7 @@ export async function serverApiFetch<T>(apiPath: string, opts: ApiFetchOptions):
const errMsg = readErrorMessage(result.data) ?? `请求失败 (${result.status})`;
if (
result.status === 401 &&
+ opts.isAuthContextCurrent?.() !== false &&
(errCode === 'ACCOUNT_UNAVAILABLE' ||
(refreshedAndRetried && isRefreshableUnauthorizedCode(errCode)))
) {