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.

πŸ› fix(share): stop verify cards from sending share readers to sign-in (#21262)

Nekof6ff058351a1
diff --git a/packages/trpc/src/client/lambda.share401.test.ts b/packages/trpc/src/client/lambda.share401.test.ts
new file mode 100644
index 00000000000..4470b7b38cb
--- /dev/null
+++ b/packages/trpc/src/client/lambda.share401.test.ts
@@ -0,0 +1,136 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { lambdaClient } from './lambda';
+
+/**
+ * A shared topic page that renders a `role='verify'` message used to fire
+ * `verify.getVerifyState` / `verify.listResults`. Those run on an authed
+ * procedure, so an anonymous viewer got 401, and the global 401 handler then
+ * sent the reader to /signin with reason=sessionExpired β€” or logged a signed-in
+ * reader out. A public share page must never do either because of a side query
+ * it cannot authorize.
+ */
+
+const openLogin = vi.fn<(reason?: string) => void>();
+const logout = vi.fn();
+const userState = { isSignedIn: false, logout, openLogin };
+
+vi.mock('@/const/version', () => ({ isDesktop: false }));
+vi.mock('@/services/_auth', () => ({ createHeaderWithAuth: async () => ({}) }));
+vi.mock('@/business/client/trpc-headers', () => ({ getBusinessTrpcHeaders: async () => ({}) }));
+vi.mock('i18next', () => ({ t: (key: string) => key }));
+vi.mock('@/store/user/store', () => ({ getUserStoreState: () => userState }));
+vi.mock('@/components/Error/loginRequiredNotification', () => ({
+ loginRequired: { redirect: ({ reason }: { reason?: string } = {}) => openLogin(reason) },
+}));
+
+const unauthorized = (path: string) =>
+ new Response(
+ JSON.stringify({
+ error: {
+ json: {
+ code: -32_001,
+ data: { code: 'UNAUTHORIZED', httpStatus: 401, path },
+ message: 'UNAUTHORIZED',
+ },
+ },
+ }),
+ { headers: { 'content-type': 'application/json' }, status: 401 },
+ );
+
+describe('lambdaClient 401 handling on a public share page', () => {
+ const fetchMock = vi.fn();
+ let clock = 1_000_000_000_000;
+
+ beforeEach(() => {
+ vi.stubGlobal('fetch', fetchMock);
+ vi.stubGlobal('location', new URL('http://localhost/share/t/TFhGJfa4'));
+ vi.spyOn(console, 'error').mockImplementation(() => {});
+ // step past the handler's 5s 401 debounce between cases
+ clock += 60_000;
+ vi.spyOn(Date, 'now').mockReturnValue(clock);
+ openLogin.mockReset();
+ logout.mockReset();
+ });
+
+ afterEach(() => {
+ vi.unstubAllGlobals();
+ vi.restoreAllMocks();
+ fetchMock.mockReset();
+ });
+
+ it('does not send an anonymous reader to /signin when verify.getVerifyState is 401', async () => {
+ userState.isSignedIn = false;
+ fetchMock.mockResolvedValue(unauthorized('verify.getVerifyState'));
+
+ await expect(
+ lambdaClient.verify.getVerifyState.query({ operationId: 'op_r1018' }),
+ ).rejects.toBeDefined();
+ // the handler awaits dynamic imports before redirecting
+ await new Promise((resolve) => setTimeout(resolve, 0));
+
+ expect(openLogin).not.toHaveBeenCalled();
+ });
+
+ it('does not log a signed-in non-owner out when verify.listResults is 401', async () => {
+ userState.isSignedIn = true;
+ fetchMock.mockResolvedValue(unauthorized('verify.listResults'));
+
+ await expect(
+ lambdaClient.verify.listResults.query({ operationId: 'op_r1018' }),
+ ).rejects.toBeDefined();
+ await new Promise((resolve) => setTimeout(resolve, 0));
+
+ expect(logout).not.toHaveBeenCalled();
+ });
+});
+
+describe('lambdaClient 401 handling outside share pages', () => {
+ const fetchMock = vi.fn();
+ let clock = 2_000_000_000_000;
+
+ beforeEach(() => {
+ vi.stubGlobal('fetch', fetchMock);
+ vi.stubGlobal('location', new URL('http://localhost/agent/agt_1'));
+ vi.spyOn(console, 'error').mockImplementation(() => {});
+ clock += 60_000;
+ vi.spyOn(Date, 'now').mockReturnValue(clock);
+ openLogin.mockReset();
+ logout.mockReset();
+ });
+
+ afterEach(() => {
+ vi.unstubAllGlobals();
+ vi.restoreAllMocks();
+ fetchMock.mockReset();
+ });
+
+ it('asks a reader without a session to sign in, without the session-expired notice', async () => {
+ userState.isSignedIn = false;
+ fetchMock.mockResolvedValue(unauthorized('verify.getVerifyState'));
+
+ await expect(
+ lambdaClient.verify.getVerifyState.query({ operationId: 'op_1' }),
+ ).rejects.toBeDefined();
+ await new Promise((resolve) => setTimeout(resolve, 0));
+
+ expect(openLogin).toHaveBeenCalledTimes(1);
+ expect(openLogin).toHaveBeenCalledWith(undefined);
+ });
+
+ it('still logs a signed-in user out with reason=sessionExpired', async () => {
+ userState.isSignedIn = true;
+ fetchMock.mockResolvedValue(unauthorized('verify.listResults'));
+
+ await expect(
+ lambdaClient.verify.listResults.query({ operationId: 'op_1' }),
+ ).rejects.toBeDefined();
+ await new Promise((resolve) => setTimeout(resolve, 0));
+
+ expect(logout).toHaveBeenCalledTimes(1);
+ const { redirectTo } = logout.mock.calls[0][0] as { redirectTo: string };
+ const params = new URL(redirectTo, 'http://localhost').searchParams;
+ expect(params.get('reason')).toBe('sessionExpired');
+ expect(params.get('callbackUrl')).toBe('http://localhost/agent/agt_1');
+ });
+});
diff --git a/packages/trpc/src/client/lambda.ts b/packages/trpc/src/client/lambda.ts
index aa7ec3fb59c..8706b72128d 100644
--- a/packages/trpc/src/client/lambda.ts
+++ b/packages/trpc/src/client/lambda.ts
@@ -23,6 +23,9 @@ let last401Time = 0;
let lastMarket401Time = 0;
const MIN_401_INTERVAL = 5000; // 5 seconds
+const isPublicShareRoute = () =>
+ typeof location !== 'undefined' && location.pathname.startsWith('/share/');
+
// `@trpc/client` throws `TransformResultError` when a response body parses as
// JSON but is not a `TRPCResponse` β€” the desktop proxy's 502 network envelope
// (`{ errorType, body }`), a gateway/WAF JSON error page, and so on. Its message
@@ -96,8 +99,10 @@ const errorHandlingLink: TRPCLink<LambdaRouter> = () => {
if (now - last401Time > MIN_401_INTERVAL) {
last401Time = now;
// Desktop app doesn't have the web auth routes like `/signin`,
- // so skip the login redirect/notification there.
- if (!isDesktop) {
+ // so skip the login redirect/notification there. A public
+ // share page renders without a session, so a 401 from a side
+ // query there must not log the reader out or leave the page.
+ if (!isDesktop && !isPublicShareRoute()) {
const { getUserStoreState } = await import('@/store/user/store');
const { isSignedIn, logout } = getUserStoreState();
// If user is still marked as signed in but got 401,
@@ -107,9 +112,11 @@ const errorHandlingLink: TRPCLink<LambdaRouter> = () => {
params.set('reason', 'sessionExpired');
await logout({ redirectTo: `/signin?${params.toString()}` });
} else {
+ // No session to expire: ask to sign in without the
+ // "session expired" notice.
const { loginRequired } =
await import('@/components/Error/loginRequiredNotification');
- loginRequired.redirect({ reason: 'sessionExpired' });
+ loginRequired.redirect();
}
}
}
diff --git a/src/features/Conversation/Messages/Verify/index.tsx b/src/features/Conversation/Messages/Verify/index.tsx
index 73f31df7a63..68068ec7b92 100644
--- a/src/features/Conversation/Messages/Verify/index.tsx
+++ b/src/features/Conversation/Messages/Verify/index.tsx
@@ -8,7 +8,7 @@ import { CheckerDock, RunResult } from '@/features/Acceptance';
import { useVerifyState } from '@/features/Acceptance/hooks';
import { phaseCardBackground, phaseFromStatus } from '@/features/Acceptance/utils';
-import { dataSelectors, useConversationStore } from '../../store';
+import { contextSelectors, dataSelectors, useConversationStore } from '../../store';
const styles = createStaticStyles(({ css, cssVar }) => ({
card: css`
@@ -36,11 +36,15 @@ const VerifyMessage = memo<VerifyMessageProps>(({ id }) => {
const operationId = item?.metadata?.verifyOperationId;
// Sequence number among all verify messages in the thread (not the repair round).
const ordinal = useConversationStore(dataSelectors.getVerifyOrdinal(id));
+ // A share page is a read-only snapshot. The verify reads are scoped to the
+ // run's owner, so an anonymous reader gets 401 and the global handler sends
+ // them to /signin; the card's plan actions are owner writes too. Skip the card.
+ const isSharePage = useConversationStore(contextSelectors.isSharePage);
- const { data: state } = useVerifyState(operationId ?? null);
+ const { data: state } = useVerifyState(isSharePage ? null : (operationId ?? null));
const phase = phaseFromStatus(state?.verifyStatus);
- if (!operationId) return null;
+ if (!operationId || isSharePage) return null;
return (
<Flexbox paddingBlock={8}>
diff --git a/src/features/Conversation/store/selectors.test.ts b/src/features/Conversation/store/selectors.test.ts
index 4e398f20f40..1587c49fae8 100644
--- a/src/features/Conversation/store/selectors.test.ts
+++ b/src/features/Conversation/store/selectors.test.ts
@@ -148,6 +148,32 @@ describe('conversationSelectors', () => {
expect(conversationSelectors.isTopic(store)).toBe(false);
});
});
+
+ describe('isSharePage', () => {
+ it('should return true on a topic share link', () => {
+ const store = createMockState({
+ context: { agentId: 'session-1', topicId: 'topic-1', topicShareId: 'share-1' },
+ });
+
+ expect(conversationSelectors.isSharePage(store)).toBe(true);
+ });
+
+ it('should return true for a shared-agent visitor', () => {
+ const store = createMockState({
+ context: { agentId: 'session-1', agentShareId: 'agent-share-1', topicId: 'topic-1' },
+ });
+
+ expect(conversationSelectors.isSharePage(store)).toBe(true);
+ });
+
+ it('should return false in the owner conversation', () => {
+ const store = createMockState({
+ context: { agentId: 'session-1', topicId: 'topic-1', threadId: null },
+ });
+
+ expect(conversationSelectors.isSharePage(store)).toBe(false);
+ });
+ });
});
describe('UI State Selectors', () => {
diff --git a/src/features/Conversation/store/slices/context/selectors.ts b/src/features/Conversation/store/slices/context/selectors.ts
index 7b939b2996c..da9af231359 100644
--- a/src/features/Conversation/store/slices/context/selectors.ts
+++ b/src/features/Conversation/store/slices/context/selectors.ts
@@ -9,6 +9,8 @@ const topicId = (s: State) => s.context.topicId;
const threadId = (s: State) => s.context.threadId;
const isThread = (s: State) => !!s.context.threadId;
const isTopic = (s: State) => !!s.context.topicId;
+/** A read-only share-link view (topic share or shared-agent visitor), not the owner's own chat. */
+const isSharePage = (s: State) => !!s.context.topicShareId || !!s.context.agentShareId;
const conversationKey = (s: State): string => {
const { agentId, topicId, threadId, scope, isNew, groupId, subAgentId } = s.context;
@@ -33,6 +35,7 @@ export const contextSelectors = {
groupId,
hook,
hooks,
+ isSharePage,
isThread,
isTopic,
threadId,