π€― 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
β»οΈ refactor(feature-flags): evaluate agent_share by user id only (#19093)
YuTengjing5390ba8f1a8e
diff --git a/apps/server/src/featureFlags/index.test.ts b/apps/server/src/featureFlags/index.test.tsindex a3eae66306f..041162dc196 100644--- a/apps/server/src/featureFlags/index.test.ts+++ b/apps/server/src/featureFlags/index.test.ts@@ -1,20 +1,6 @@-import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { afterEach, describe, expect, it, vi } from 'vitest';-const mockFindById = vi.fn();-vi.mock('@/database/models/user', () => ({- UserModel: { findById: (...args: unknown[]) => mockFindById(...args) },-}));--const mockGetServerDB = vi.fn();-vi.mock('@/database/server', () => ({- getServerDB: (...args: unknown[]) => mockGetServerDB(...args),-}));--const {- applyDevelopmentFeatureFlagDefaults,- clearFeatureFlagEmailCache,- resolveEmailForEvaluation,-} = await import('./index');+const { applyDevelopmentFeatureFlagDefaults } = await import('./index');afterEach(() => {vi.unstubAllEnvs();@@ -62,102 +48,3 @@ describe('applyDevelopmentFeatureFlagDefaults', () => {).toEqual(['production-user']);});});--describe('resolveEmailForEvaluation', () => {- beforeEach(() => {- mockFindById.mockReset();- mockGetServerDB.mockReset();- mockGetServerDB.mockResolvedValue({});- clearFeatureFlagEmailCache();- });-- it('returns undefined without a userId, never touching UserModel', async () => {- await expect(- resolveEmailForEvaluation({ agent_share: ['[email protected]'] }),- ).resolves.toBeUndefined();- expect(mockFindById).not.toHaveBeenCalled();- });-- it('never touches UserModel when every array flag only carries user IDs', async () => {- await expect(- resolveEmailForEvaluation(- { agent_share: ['user-1', 'user-2'], workspace: ['user-3'] },- 'user-1',- ),- ).resolves.toBeUndefined();- expect(mockFindById).not.toHaveBeenCalled();- });-- it('resolves the email when some flag array carries an email entry', async () => {- mockFindById.mockResolvedValue({ email: '[email protected]' });-- await expect(- resolveEmailForEvaluation({ agent_share: ['[email protected]', 'user-2'] }, 'user-1'),- ).resolves.toBe('[email protected]');- expect(mockFindById).toHaveBeenCalledWith({}, 'user-1');- });-- it('ignores email entries in flags that are never evaluated against an email', async () => {- // `workspace` is evaluated by user ID only, so an '@' there must not cost a- // users-table read on every single flag evaluation.- await expect(- resolveEmailForEvaluation({ workspace: ['[email protected]'] }, 'user-1'),- ).resolves.toBeUndefined();- expect(mockFindById).not.toHaveBeenCalled();- });-- it('reuses the cached email for repeated evaluations of the same user', async () => {- mockFindById.mockResolvedValue({ email: '[email protected]' });- const flags = { agent_share: ['[email protected]'] };-- await expect(resolveEmailForEvaluation(flags, 'user-1')).resolves.toBe('[email protected]');- await expect(resolveEmailForEvaluation(flags, 'user-1')).resolves.toBe('[email protected]');-- expect(mockFindById).toHaveBeenCalledTimes(1);- });-- it('caches per user rather than globally', async () => {- mockFindById.mockResolvedValueOnce({ email: '[email protected]' });- mockFindById.mockResolvedValueOnce({ email: '[email protected]' });- const flags = { agent_share: ['[email protected]'] };-- await expect(resolveEmailForEvaluation(flags, 'user-1')).resolves.toBe('[email protected]');- await expect(resolveEmailForEvaluation(flags, 'user-2')).resolves.toBe('[email protected]');- await expect(resolveEmailForEvaluation(flags, 'user-1')).resolves.toBe('[email protected]');-- expect(mockFindById).toHaveBeenCalledTimes(2);- });-- it('expires cached emails once the TTL has elapsed', async () => {- vi.useFakeTimers();- try {- mockFindById.mockResolvedValue({ email: '[email protected]' });- const flags = { agent_share: ['[email protected]'] };-- await resolveEmailForEvaluation(flags, 'user-1');- vi.advanceTimersByTime(5 * 60 * 1000 + 1);- await resolveEmailForEvaluation(flags, 'user-1');-- expect(mockFindById).toHaveBeenCalledTimes(2);- } finally {- vi.useRealTimers();- }- });-- it('swallows a lookup failure and returns undefined instead of throwing', async () => {- mockFindById.mockRejectedValue(new Error('db unavailable'));-- await expect(- resolveEmailForEvaluation({ agent_share: ['[email protected]'] }, 'user-1'),- ).resolves.toBeUndefined();- });-- it('does not cache a failed lookup, so a transient DB error is retried', async () => {- const flags = { agent_share: ['[email protected]'] };- mockFindById.mockRejectedValueOnce(new Error('db unavailable'));- mockFindById.mockResolvedValueOnce({ email: '[email protected]' });-- await expect(resolveEmailForEvaluation(flags, 'user-1')).resolves.toBeUndefined();- await expect(resolveEmailForEvaluation(flags, 'user-1')).resolves.toBe('[email protected]');- });-});diff --git a/apps/server/src/featureFlags/index.ts b/apps/server/src/featureFlags/index.tsindex 81a020bac94..cefb4e634ec 100644--- a/apps/server/src/featureFlags/index.ts+++ b/apps/server/src/featureFlags/index.ts@@ -119,104 +119,11 @@ export const getServerFeatureFlagsFromRuntimeConfig = async (userId?: string) =>return flags;};-/**- * The only flags whose whitelist arrays are ever matched against an email β- * see `mapFeatureFlagsEnvToState`, where they are the sole `evaluateFeatureFlag`- * calls that receive `userEmail`. Every other flag is evaluated by user ID- * alone, so an '@' in one of those arrays can never change an outcome and must- * not be allowed to trigger a users-table read.- */-const EMAIL_AWARE_FLAG_KEYS = ['agent_share'] as const satisfies readonly (keyof IFeatureFlags)[];--const EMAIL_CACHE_TTL_MS = 5 * 60 * 1000;-/**- * Bounded so a burst of distinct users cannot grow the map without limit in a- * long-lived server process. Eviction is plain insertion-order (oldest first),- * which is enough here: entries are cheap and expire on their own anyway.- */-const EMAIL_CACHE_MAX_ENTRIES = 1000;--const emailCache = new Map<string, { email: string | undefined; expiresAt: number }>();--const readCachedEmail = (userId: string) => {- const cached = emailCache.get(userId);- if (!cached) return;- if (cached.expiresAt <= Date.now()) {- emailCache.delete(userId);- return;- }- return cached;-};--const writeCachedEmail = (userId: string, email: string | undefined) => {- // Refresh insertion order so the entry counts as recently written.- emailCache.delete(userId);- emailCache.set(userId, { email, expiresAt: Date.now() + EMAIL_CACHE_TTL_MS });-- while (emailCache.size > EMAIL_CACHE_MAX_ENTRIES) {- const oldest = emailCache.keys().next();- if (oldest.done) break;- emailCache.delete(oldest.value);- }-};--/** Test-only escape hatch so cached emails cannot leak across test cases. */-export const clearFeatureFlagEmailCache = () => emailCache.clear();--/**- * Whitelist arrays may hold emails as well as user IDs (admins configure- * grayscale rollouts by email β see `evaluateFeatureFlag`). Feature flags are- * evaluated on essentially every tRPC procedure, so this runs on the hot path- * and is kept off the database twice over:- *- * 1. Only the two email-aware flags are inspected for an '@' entry, so the- * common configuration (all booleans / user-ID arrays) never looks anything- * up.- * 2. Resolved emails are memoized per user for {@link EMAIL_CACHE_TTL_MS}, so- * repeated evaluations within one user's session hit memory instead of the- * users table. A stale email only matters while an admin is rolling out by- * email to a user who just changed their address β bounded by the TTL.- *- * Exported (rather than kept module-private) so it has its own focused unit- * tests instead of only being exercised indirectly through the full- * RuntimeConfigProvider chain in `getServerFeatureFlagsStateFromRuntimeConfig`.- */-export const resolveEmailForEvaluation = async (- flags: IFeatureFlags,- userId?: string,-): Promise<string | undefined> => {- if (!userId) return;-- const hasEmailEntry = EMAIL_AWARE_FLAG_KEYS.some((key) => {- const value = flags[key];- return Array.isArray(value) && value.some((entry) => entry.includes('@'));- });- if (!hasEmailEntry) return;-- const cached = readCachedEmail(userId);- if (cached) return cached.email;-- try {- const { UserModel } = await import('@/database/models/user');- const { getServerDB } = await import('@/database/server');- const user = await UserModel.findById(await getServerDB(), userId);- const email = user?.email ?? undefined;- writeCachedEmail(userId, email);- return email;- } catch (error) {- // Deliberately not cached: a transient DB failure must not pin the user to- // "no email" (and therefore out of an email whitelist) for the whole TTL.- debug('Failed to resolve user email for feature flag evaluation: %O', error);- return;- }-};-/*** Get server feature flags from RuntimeConfig and map them to state with user ID* @param userId - Optional user ID for user-specific feature flag evaluation*/export const getServerFeatureFlagsStateFromRuntimeConfig = async (userId?: string) => {const flags = await getServerFeatureFlagsFromRuntimeConfig(userId);- const userEmail = await resolveEmailForEvaluation(flags, userId);- return mapFeatureFlagsEnvToState(flags, userId, userEmail);+ return mapFeatureFlagsEnvToState(flags, userId);};diff --git a/apps/server/src/routers/lambda/_helpers/agentShareFeatureGate.ts b/apps/server/src/routers/lambda/_helpers/agentShareFeatureGate.tsindex b5a0d3b7041..2716c0d36d6 100644--- a/apps/server/src/routers/lambda/_helpers/agentShareFeatureGate.ts+++ b/apps/server/src/routers/lambda/_helpers/agentShareFeatureGate.ts@@ -44,8 +44,8 @@ const createAgentShareGate =* 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- * or emails) published by admins, evaluated per user. It fails closed on+ * 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.*diff --git a/packages/app-config/src/featureFlags/schema.test.ts b/packages/app-config/src/featureFlags/schema.test.tsindex f01296c854b..cef875e40e6 100644--- a/packages/app-config/src/featureFlags/schema.test.ts+++ b/packages/app-config/src/featureFlags/schema.test.ts@@ -114,14 +114,6 @@ describe('evaluateFeatureFlag', () => {expect(evaluateFeatureFlag([], 'user-123')).toBe(false);expect(evaluateFeatureFlag([])).toBe(false);});-- it('should match allowlist entries against the user email as well', () => {- const allowlist = ['[email protected]', 'user-456'];- expect(evaluateFeatureFlag(allowlist, 'user-123', '[email protected]')).toBe(true);- expect(evaluateFeatureFlag(allowlist, 'user-456', '[email protected]')).toBe(true);- expect(evaluateFeatureFlag(allowlist, 'user-123', '[email protected]')).toBe(false);- expect(evaluateFeatureFlag(allowlist, 'user-123')).toBe(false);- });});describe('mapFeatureFlagsEnvToState', () => {@@ -179,34 +171,28 @@ describe('mapFeatureFlagsEnvToState', () => {expect(mapFeatureFlagsEnvToState(config).enableDevDock).toBe(false);});- it('should keep agent share off by default and narrow it to listed user IDs or emails', () => {+ it('should keep agent share off by default and narrow it to listed user IDs', () => {expect(DEFAULT_FEATURE_FLAGS.agent_share).toBe(false);expect(mapFeatureFlagsEnvToState(DEFAULT_FEATURE_FLAGS, 'user-1').enableAgentShare).toBe(false);- const config = { agent_share: ['creator-123', '[email protected]'] };+ const config = { agent_share: ['creator-123'] };expect(mapFeatureFlagsEnvToState(config, 'creator-123').enableAgentShare).toBe(true);- expect(- mapFeatureFlagsEnvToState(config, 'user-456', '[email protected]').enableAgentShare,- ).toBe(true);expect(mapFeatureFlagsEnvToState(config, 'user-456').enableAgentShare).toBe(false);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 entry (id or email) that would let them publish a share.+ // 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', '[email protected]'] };+ const config = { agent_share: ['visitor-123'] };expect(mapFeatureFlagsEnvToState(config, 'visitor-123').enableAgentShare).toBe(true);- expect(- mapFeatureFlagsEnvToState(config, 'user-456', '[email protected]').enableAgentShare,- ).toBe(true);expect(mapFeatureFlagsEnvToState(config, 'user-456').enableAgentShare).toBe(false);expect(mapFeatureFlagsEnvToState(config).enableAgentShare).toBe(false);});diff --git a/packages/app-config/src/featureFlags/schema.ts b/packages/app-config/src/featureFlags/schema.tsindex 4b4cf78088f..f5b1959a2a7 100644--- a/packages/app-config/src/featureFlags/schema.ts+++ b/packages/app-config/src/featureFlags/schema.ts@@ -2,13 +2,6 @@ import type { IFeatureFlagsState } from '@lobechat/types';import { z } from 'zod';// Define a union type for feature flag values: either boolean or array of user IDs-//-// NOTE: `agent_share` additionally accepts raw EMAIL addresses in that array-// (see `evaluateFeatureFlag`). Such arrays live in the published runtime config-// (Redis) and in env vars, which therefore hold user email addresses β a data-// category that was previously absent from flag storage. Keep that in mind when-// logging, exporting, or replicating the runtime config, and prefer user IDs-// when an ID is already at hand.const FeatureFlagValue = z.union([z.boolean(), z.array(z.string())]);const isDev = process.env.NODE_ENV === 'development';@@ -29,9 +22,7 @@ export const FeatureFlagsSchema = z.object({* 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 or emails (see- * `evaluateFeatureFlag`), so admins can grant a rollout by email without- * resolving a user ID first. The share OWNER previewing their own share is+ * 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@@ -74,24 +65,19 @@ export const FeatureFlagsSchema = z.object({export type IFeatureFlags = z.infer<typeof FeatureFlagsSchema>;/**- * Evaluate a feature flag value against a user ID (and optionally their email)- * @param flagValue - The feature flag value (boolean or array of user IDs/emails)+ * Evaluate a feature flag value against a user ID+ * @param flagValue - The feature flag value (boolean or array of user IDs)* @param userId - The current user ID- * @param userEmail - The current user's email; array entries match either- * identifier, so an admin can whitelist a rollout by email without- * resolving user IDs first* @returns boolean indicating if the feature is enabled for the user*/export const evaluateFeatureFlag = (flagValue: boolean | string[] | undefined,userId?: string,- userEmail?: string,): boolean | undefined => {if (typeof flagValue === 'boolean') return flagValue;if (Array.isArray(flagValue)) {if (userId && flagValue.includes(userId)) return true;- if (userEmail && flagValue.includes(userEmail)) return true;return false;}};@@ -106,7 +92,7 @@ export const DEFAULT_FEATURE_FLAGS: IFeatureFlags = {edit_agent: true,// Cloud-only grayscale: off everywhere until an admin publishes a whitelist- // (array of user IDs/emails) or flips it to true. Self-hosted deployments+ // (array of user IDs) or flips it to true. Self-hosted deployments// are additionally hard-blocked by ENABLE_BUSINESS_FEATURES on the server// gate, so setting this env-side does not enable the feature there.agent_share: false,@@ -147,14 +133,11 @@ export const DEFAULT_FEATURE_FLAGS: IFeatureFlags = {export const mapFeatureFlagsEnvToState = (config: IFeatureFlags,userId?: string,- userEmail?: string,): IFeatureFlagsState => {return {isAgentEditable: evaluateFeatureFlag(config.edit_agent, userId),- // The only email-aware flag: its grayscale whitelist is maintained by- // admins as raw emails (see evaluateFeatureFlag).- enableAgentShare: evaluateFeatureFlag(config.agent_share, userId, userEmail),+ enableAgentShare: evaluateFeatureFlag(config.agent_share, userId),showProvider: evaluateFeatureFlag(config.provider_settings, userId),showOpenAIApiKey: evaluateFeatureFlag(config.openai_api_key, userId),