🤯 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.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
🐛 fix: restrict agent share rollout checks to creators (#19380)
YuTengjing7be9722ae1c8
diff --git a/apps/server/src/routers/lambda/__tests__/share.test.ts b/apps/server/src/routers/lambda/__tests__/share.test.tsindex 31c62fd2b81..b1f038cc6f6 100644--- a/apps/server/src/routers/lambda/__tests__/share.test.ts+++ b/apps/server/src/routers/lambda/__tests__/share.test.ts@@ -209,18 +209,21 @@ describe('shareRouter', () => {expect(AgentShareModel.findBySlugOrId).not.toHaveBeenCalled();});- it('rejects a non-owner visitor when the agent share flag is off', async () => {- mockGetFeatureFlagsState.mockResolvedValue({ enableAgentShare: false });- const caller = shareRouter.createCaller(- await createContextInner({ userId: 'visitor-user' }),- );-- await expect(caller.getSharedAgent({ slugOrId: 'shared-agent' })).rejects.toMatchObject({- code: 'FORBIDDEN',- });- expect(mockGetFeatureFlagsState).toHaveBeenCalledWith('visitor-user');- expect(AgentShareModel.incrementUserViewCount).not.toHaveBeenCalled();- });+ it.each([false, undefined])(+ 'admits a non-owner visitor when the agent share flag is %s',+ async (enableAgentShare) => {+ mockGetFeatureFlagsState.mockResolvedValue({ enableAgentShare });+ const caller = shareRouter.createCaller(+ await createContextInner({ userId: 'visitor-user' }),+ );++ await expect(caller.getSharedAgent({ slugOrId: 'shared-agent' })).resolves.toMatchObject({+ isOwner: false,+ });+ expect(mockGetFeatureFlagsState).not.toHaveBeenCalled();+ expect(AgentShareModel.incrementUserViewCount).toHaveBeenCalled();+ },+ );it('still lets the owner preview their own share when the agent share flag is off', async () => {mockGetFeatureFlagsState.mockResolvedValue({ enableAgentShare: false });diff --git a/apps/server/src/routers/lambda/__tests__/shareChat.test.ts b/apps/server/src/routers/lambda/__tests__/shareChat.test.tsindex 3f7cbc2201c..ee54329b0de 100644--- a/apps/server/src/routers/lambda/__tests__/shareChat.test.ts+++ b/apps/server/src/routers/lambda/__tests__/shareChat.test.ts@@ -579,26 +579,30 @@ describe('shareChatRouter', () => {expect(mockAccessCheck).not.toHaveBeenCalled();});- it('rejects every procedure when the agent share flag is off for this visitor', async () => {- mockGetFeatureFlagsState.mockResolvedValue({ enableAgentShare: false });- const caller = await createCaller();-- await expect(caller.getTopics({ shareId: 'share-1' })).rejects.toMatchObject({- code: 'FORBIDDEN',- });- await expect(- caller.getMessages({ shareId: 'share-1', topicId: 'tpc_visitor' }),- ).rejects.toMatchObject({ code: 'FORBIDDEN' });- await expect(caller.execAgent({ prompt: 'hi', shareId: 'share-1' })).rejects.toMatchObject({- code: 'FORBIDDEN',- });- await expect(- caller.interruptTask({ operationId: 'op-1', shareId: 'share-1', topicId: 'tpc_visitor' }),- ).rejects.toMatchObject({ code: 'FORBIDDEN' });- await expect(- caller.refreshGatewayToken({ shareId: 'share-1', topicId: 'tpc_visitor' }),- ).rejects.toMatchObject({ code: 'FORBIDDEN' });- expect(mockAccessCheck).not.toHaveBeenCalled();- });+ it.each([false, undefined])(+ 'admits visitor procedures when the agent share flag is %s',+ async (enableAgentShare) => {+ mockGetFeatureFlagsState.mockResolvedValue({ enableAgentShare });+ mockMessageQueryForVisitor.mockResolvedValue([]);+ const caller = await createCaller();++ await expect(caller.getTopics({ shareId: 'share-1' })).resolves.toEqual([]);+ await expect(+ caller.getMessages({ shareId: 'share-1', topicId: 'tpc_visitor' }),+ ).resolves.toEqual([]);+ await expect(caller.execAgent({ prompt: 'hi', shareId: 'share-1' })).resolves.toMatchObject(+ {+ success: true,+ },+ );+ await expect(+ caller.interruptTask({ operationId: 'op-1', shareId: 'share-1', topicId: 'tpc_visitor' }),+ ).resolves.toMatchObject({ success: true });+ await expect(+ caller.refreshGatewayToken({ shareId: 'share-1', topicId: 'tpc_visitor' }),+ ).resolves.toEqual({ token: 'visitor-jwt' });+ expect(mockGetFeatureFlagsState).not.toHaveBeenCalled();+ },+ );});});diff --git a/apps/server/src/routers/lambda/_helpers/__tests__/agentShareFeatureGate.test.ts b/apps/server/src/routers/lambda/_helpers/__tests__/agentShareFeatureGate.test.tsindex f74048b30a0..b24e37a9f2c 100644--- a/apps/server/src/routers/lambda/_helpers/__tests__/agentShareFeatureGate.test.ts+++ b/apps/server/src/routers/lambda/_helpers/__tests__/agentShareFeatureGate.test.ts@@ -65,30 +65,31 @@ describe('assertAgentShareVisitorEnabled', () => {mocks.businessConst.ENABLE_BUSINESS_FEATURES = false;mocks.getFlags.mockResolvedValue({ enableAgentShare: true });- await expect(assertAgentShareVisitorEnabled('visitor-1')).rejects.toMatchObject({- code: 'FORBIDDEN',- });+ expect(() => assertAgentShareVisitorEnabled()).toThrow(+ expect.objectContaining({+ code: 'FORBIDDEN',+ }),+ );expect(mocks.getFlags).not.toHaveBeenCalled();});- it('rejects visitors outside the grayscale whitelist', async () => {+ it('admits visitors outside the grayscale whitelist', async () => {mocks.getFlags.mockResolvedValue({ enableAgentShare: false });- await expect(assertAgentShareVisitorEnabled('visitor-1')).rejects.toBeInstanceOf(TRPCError);- expect(mocks.getFlags).toHaveBeenCalledWith('visitor-1');+ expect(() => assertAgentShareVisitorEnabled()).not.toThrow();+ expect(mocks.getFlags).not.toHaveBeenCalled();});- it('fails closed when the flag is unconfigured', async () => {+ it('admits visitors when the flag is unconfigured', async () => {mocks.getFlags.mockResolvedValue({ enableAgentShare: undefined });- await expect(assertAgentShareVisitorEnabled('visitor-1')).rejects.toMatchObject({- code: 'FORBIDDEN',- });+ expect(() => assertAgentShareVisitorEnabled()).not.toThrow();+ expect(mocks.getFlags).not.toHaveBeenCalled();});it('admits whitelisted visitors', async () => {mocks.getFlags.mockResolvedValue({ enableAgentShare: true });- await expect(assertAgentShareVisitorEnabled('visitor-1')).resolves.toBeUndefined();+ expect(() => assertAgentShareVisitorEnabled()).not.toThrow();});});diff --git a/apps/server/src/routers/lambda/_helpers/agentShareFeatureGate.ts b/apps/server/src/routers/lambda/_helpers/agentShareFeatureGate.tsindex 2716c0d36d6..56a268c5417 100644--- a/apps/server/src/routers/lambda/_helpers/agentShareFeatureGate.ts+++ b/apps/server/src/routers/lambda/_helpers/agentShareFeatureGate.ts@@ -4,67 +4,31 @@ import { TRPCError } from '@trpc/server';import { getServerFeatureFlagsStateFromRuntimeConfig } from '@/server/featureFlags';/**- * Shared shape of {@link assertAgentShareCreationEnabled} and- * {@link assertAgentShareVisitorEnabled}: both check the same- * `ENABLE_BUSINESS_FEATURES` compile-time gate, then the same- * `enableAgentShare` feature flag, differing only in which error message to- * use. Factored out so the two exports cannot drift.+ * Existing shares remain accessible regardless of a visitor's rollout flags.+ * Deployment support is still enforced before resolving any shared data.*/-const createAgentShareGate =- (flagKey: 'enableAgentShare', notEnabledMessage: string) => async (userId: string) => {- if (!ENABLE_BUSINESS_FEATURES) {- throw new TRPCError({- code: 'FORBIDDEN',- message: 'Agent sharing is not available on this deployment',- });- }-- const featureFlags = await getServerFeatureFlagsStateFromRuntimeConfig(userId);- if (featureFlags[flagKey] !== true) {- throw new TRPCError({- code: 'FORBIDDEN',- message: notEnabledMessage,- });- }- };+export const assertAgentShareVisitorEnabled = () => {+ if (!ENABLE_BUSINESS_FEATURES) {+ throw new TRPCError({+ code: 'FORBIDDEN',+ message: 'Agent sharing is not available on this deployment',+ });+ }+};/**- * Availability gates for Agent Share. The feature has two capabilities —- * CREATING a share (publishing) and VISITING one (opening/chatting on an- * already-live share) — but a SINGLE rollout allowlist governs both: a user- * matched by `agent_share` can publish and visit, everyone else can do- * neither. Two exports remain only so each call site can raise the message- * that fits its surface.- *- * Both gates are checked here on the server rather than only in the UI (the- * gap topic-share has — its `ENABLE_BUSINESS_FEATURES` check is client-only,- * so a self-hosted deployment can enable topic sharing by calling the API- * directly), in two layers:- *- * 1. `ENABLE_BUSINESS_FEATURES` — compile-time business-slot constant, false- * in OSS builds. Self-hosted deployments cannot flip it with env vars, so- * agent sharing is structurally cloud-only end to end.- * 2. The `enableAgentShare` feature flag — the grayscale whitelist (user IDs)- * published by admins, evaluated per user. It fails closed on- * anything other than `true` (including `undefined`, i.e. unconfigured),- * so a deployment must explicitly opt a user in.- *- * Deliberately NOT applied to `disableShare` / visibility→private, nor to any- * other management mutation (`updateShareConfig`, `updateSlug`,- * `getShareStatus`, `getShareStats`): a creator removed from the whitelist- * must still be able to revoke and manage an existing share. Symmetrically,- * `assertAgentShareVisitorEnabled` must never run for the share OWNER- * previewing their own share — an owner who is later dropped from the- * whitelist would otherwise lose access to their own live share. See the call- * site in `share.ts`'s `getSharedAgent`, which only applies it to non-owner- * viewers.+ * Only publishing or re-enabling a share requires the creator's explicit opt-in.+ * Managing, revoking, and previewing existing shares remain available when the+ * creator is removed from the rollout, as does visitor access.*/-export const assertAgentShareCreationEnabled = createAgentShareGate(- 'enableAgentShare',- 'Agent sharing is not enabled for this account',-);+export const assertAgentShareCreationEnabled = async (userId: string) => {+ assertAgentShareVisitorEnabled();-export const assertAgentShareVisitorEnabled = createAgentShareGate(- 'enableAgentShare',- 'Shared agents are not available for this account',-);+ const featureFlags = await getServerFeatureFlagsStateFromRuntimeConfig(userId);+ if (featureFlags.enableAgentShare !== true) {+ throw new TRPCError({+ code: 'FORBIDDEN',+ message: 'Agent sharing is not enabled for this account',+ });+ }+};diff --git a/apps/server/src/routers/lambda/share.ts b/apps/server/src/routers/lambda/share.tsindex d71b1470a33..4e9a62f289c 100644--- a/apps/server/src/routers/lambda/share.ts+++ b/apps/server/src/routers/lambda/share.ts@@ -1,4 +1,3 @@-import { ENABLE_BUSINESS_FEATURES } from '@lobechat/business-const';import { type SharedAgentData, type SharedTopicData } from '@lobechat/types';import { TRPCError } from '@trpc/server';import debug from 'debug';@@ -23,22 +22,14 @@ export const shareRouter = router({* link → any authed viewer) gate runs on the resolved row via the shared* `assertShareAccess` helper, so no second lookup is needed.*- * Gated in two layers matching `_helpers/agentShareFeatureGate.ts`:- * `ENABLE_BUSINESS_FEATURES` applies unconditionally (even to the OWNER- * previewing their own share — an OSS deployment has no agent-share surface- * at all), while the `enableAgentShare` grayscale flag only ever applies to- * OTHER visitors, never the owner.+ * Deployment support applies to every viewer, including owner previews.+ * The rollout flag only gates publishing, never access to an existing share.*/getSharedAgent: authedProcedure.use(serverDatabase).input(z.object({ slugOrId: z.string().trim().min(1) })).query(async ({ input, ctx }): Promise<SharedAgentData> => {- if (!ENABLE_BUSINESS_FEATURES) {- throw new TRPCError({- code: 'FORBIDDEN',- message: 'Agent sharing is not available on this deployment',- });- }+ assertAgentShareVisitorEnabled();const share = await AgentShareModel.findBySlugOrId(ctx.serverDB, input.slugOrId);@@ -51,11 +42,6 @@ export const shareRouter = router({const isOwner = share.ownerId === ctx.userId;if (!isOwner) {- // The owner previewing their own (possibly unpublished) share must- // always be able to see it — the grayscale rollout only narrows OTHER- // visitors' admission.- await assertAgentShareVisitorEnabled(ctx.userId);-// Owner previews are not counted: userViewCount tracks visitor page// views (PV, not deduplicated visitors). The counter is analytics// only, so it is best-effort: a failed increment must never turn andiff --git a/apps/server/src/routers/lambda/shareChat.ts b/apps/server/src/routers/lambda/shareChat.tsindex 605c8843d9e..364eb2b68d4 100644--- a/apps/server/src/routers/lambda/shareChat.ts+++ b/apps/server/src/routers/lambda/shareChat.ts@@ -51,12 +51,9 @@ const log = debug('lobe-server:router:shareChat');* workspaceId is ever threaded into the creator-scoped models/services.*/const shareChatProcedure = authedProcedure.use(serverDatabase).use(async (opts) => {- // Availability gate for the VISITOR side of Agent Share (see- // `_helpers/agentShareFeatureGate.ts`): `ENABLE_BUSINESS_FEATURES`- // (compile-time, false in OSS) AND the `enableAgentShare` grayscale flag,- // both evaluated for the VISITOR calling in — never the share owner,- // who reaches their own agent through `aiAgent.execAgent`, not this router.- await assertAgentShareVisitorEnabled(opts.ctx.userId);+ // Visitor access depends on deployment support and share permissions,+ // not the publishing rollout flag.+ assertAgentShareVisitorEnabled();return opts.next();});diff --git a/packages/app-config/src/featureFlags/schema.test.ts b/packages/app-config/src/featureFlags/schema.test.tsindex cef875e40e6..20cf973a0e8 100644--- a/packages/app-config/src/featureFlags/schema.test.ts+++ b/packages/app-config/src/featureFlags/schema.test.ts@@ -171,7 +171,7 @@ describe('mapFeatureFlagsEnvToState', () => {expect(mapFeatureFlagsEnvToState(config).enableDevDock).toBe(false);});- it('should keep agent share off by default and narrow it to listed user IDs', () => {+ it('should keep agent share publishing off by default and enable it for listed creators', () => {expect(DEFAULT_FEATURE_FLAGS.agent_share).toBe(false);expect(mapFeatureFlagsEnvToState(DEFAULT_FEATURE_FLAGS, 'user-1').enableAgentShare).toBe(false);@@ -182,21 +182,6 @@ describe('mapFeatureFlagsEnvToState', () => {expect(mapFeatureFlagsEnvToState(config).enableAgentShare).toBe(false);});- it('should gate agent share visitors with the same `agent_share` allowlist', () => {- // One flag drives both capabilities, so a visitor is admitted by exactly- // the same user ID that would let them publish a share.- expect(DEFAULT_FEATURE_FLAGS.agent_share).toBe(false);- expect(mapFeatureFlagsEnvToState(DEFAULT_FEATURE_FLAGS, 'visitor-1').enableAgentShare).toBe(- false,- );-- const config = { agent_share: ['visitor-123'] };-- expect(mapFeatureFlagsEnvToState(config, 'visitor-123').enableAgentShare).toBe(true);- expect(mapFeatureFlagsEnvToState(config, 'user-456').enableAgentShare).toBe(false);- expect(mapFeatureFlagsEnvToState(config).enableAgentShare).toBe(false);- });-it('should correctly map boolean feature flags to state', () => {const config = {provider_settings: true,diff --git a/packages/app-config/src/featureFlags/schema.ts b/packages/app-config/src/featureFlags/schema.tsindex f5b1959a2a7..fe7ed5bfcbd 100644--- a/packages/app-config/src/featureFlags/schema.ts+++ b/packages/app-config/src/featureFlags/schema.ts@@ -19,14 +19,10 @@ export const FeatureFlagsSchema = z.object({edit_agent: FeatureFlagValue.optional(),/**- * Cloud-only grayscale gate for Agent Share, covering BOTH capabilities the- * feature has: PUBLISHING a share (creator side) and OPENING/chatting on a- * shared agent (visitor side). A user matched by this flag can do both;- * everyone else can do neither. Array values are user IDs. The share OWNER previewing their own share is- * never subject to the visitor check — only other visitors are. Self-hosted- * builds are additionally hard-blocked server-side by- * `ENABLE_BUSINESS_FEATURES` (see `_helpers/agentShareFeatureGate.ts`), so- * this flag alone can never enable the feature outside Cloud.+ * Rollout gate for publishing or re-enabling Agent Share. Array values are+ * creator user IDs. Visiting, chatting on, and managing existing shares do+ * not require this flag. Deployment support is independently enforced by+ * `ENABLE_BUSINESS_FEATURES` (see `_helpers/agentShareFeatureGate.ts`).*/agent_share: FeatureFlagValue.optional(),