diff --git a/.changeset/bootstrap-public-flags-only.md b/.changeset/bootstrap-public-flags-only.md new file mode 100644 index 000000000..c54509cbe --- /dev/null +++ b/.changeset/bootstrap-public-flags-only.md @@ -0,0 +1,5 @@ +--- +"@reflag/node-sdk": patch +--- + +Keep secret flags and their remote config out of browser data returned by `getFlagsForBootstrap()`, including bound clients. They remain available on the server. The v1 data format does not change. diff --git a/packages/node-sdk/src/client.ts b/packages/node-sdk/src/client.ts index 1f10be5c0..33f5720bb 100644 --- a/packages/node-sdk/src/client.ts +++ b/packages/node-sdk/src/client.ts @@ -174,9 +174,11 @@ type BulkEvent = function compileFlagDefinitions( flags: FlagAPIResponse[], ): CachedFlagDefinition[] { - return flags.map((flagDef) => { + return structuredClone(flags).map((flagDef) => { return { ...flagDef, + // Only an explicit public marker may authorize browser bootstrap export. + secret: flagDef.secret !== false, enabledEvaluator: newEvaluator( flagDef.targeting.rules.map((rule) => ({ filter: rule.filter, @@ -204,7 +206,7 @@ function createFlagsFallbackSnapshot( return { version: 1, savedAt: new Date().toISOString(), - flags, + flags: structuredClone(flags), }; } @@ -652,6 +654,8 @@ export class ReflagClient { snapshot: FlagsCacheSnapshot, etag?: string, ) { + // Own the response before asynchronous persistence can observe caller mutation. + const fallbackSnapshot = createFlagsFallbackSnapshot(flags); // Serialize background writes so an older save cannot overwrite a newer one. this.flagsFallbackSavePromise = this.flagsFallbackSavePromise.then( async () => { @@ -660,7 +664,7 @@ export class ReflagClient { if (provider) { await provider.save( this._config.flagsFallbackProviderContext, - createFlagsFallbackSnapshot(flags), + fallbackSnapshot, ); } // Enable revalidation only after saving. A late save updates only its @@ -1025,6 +1029,7 @@ export class ReflagClient { const flags = this.flagsCache.get() || []; return flags.map((f) => ({ key: f.key, + secret: f.secret, description: f.description, flag: f.targeting, config: f.config, @@ -1083,8 +1088,7 @@ export class ReflagClient { } /** - * Gets the evaluated flags for the current context without wrapping them in getters. - * This method returns raw flag data suitable for bootstrapping client-side applications. + * Get public flag data to send to a browser. * * @param options - The options for the context. * @param options.enableTracking - Whether to enable tracking for the context. @@ -1097,7 +1101,9 @@ export class ReflagClient { * * @remarks * Call `initialize` before calling this method to ensure the flag definitions are cached, no flags will be returned otherwise. - * This method returns RawFlag objects without wrapping them in getters, making them suitable for serialization. + * Only flags marked `secret: false` are included. Secret flags, unknown overrides + * and fallback values without definitions are left out. Older definitions without + * the `secret` field are also left out. Include only browser-safe context attributes. **/ public getFlagsForBootstrap({ enableTracking = true, @@ -1105,10 +1111,21 @@ export class ReflagClient { }: ContextWithTracking): BootstrappedFlags { const contextWithTracking = { enableTracking, ...context }; const flagStateVersion = this.flagsCache.getFlagStateVersion(); + const publicKeys = new Set( + this.flagsCache + .get() + ?.filter((flag) => flag.secret === false) + .map((flag) => flag.key), + ); + const flags = this._getFlags(contextWithTracking); return { context: contextWithTracking, - flags: this._getFlags(contextWithTracking), + flags: structuredClone( + Object.fromEntries( + Object.entries(flags).filter(([key]) => publicKeys.has(key)), + ), + ), ...(flagStateVersion !== undefined ? { flagStateVersion } : {}), }; } diff --git a/packages/node-sdk/src/types.ts b/packages/node-sdk/src/types.ts index 3757f504e..231d9dc9c 100644 --- a/packages/node-sdk/src/types.ts +++ b/packages/node-sdk/src/types.ts @@ -235,6 +235,9 @@ export type FlagOverride = * Describes a feature definition. */ export type FlagDefinition = { + /** Only explicit false authorizes browser bootstrap export. */ + secret?: boolean; + /** * The key of the feature. */ @@ -348,6 +351,9 @@ export type FlagConfigVariant = { * @internal */ export type FlagAPIResponse = { + /** Missing visibility in older responses is not a public declaration. */ + secret?: boolean; + /** * The key of the feature. */ diff --git a/packages/node-sdk/test/bootstrap-secrecy.test.ts b/packages/node-sdk/test/bootstrap-secrecy.test.ts new file mode 100644 index 000000000..d07edbc15 --- /dev/null +++ b/packages/node-sdk/test/bootstrap-secrecy.test.ts @@ -0,0 +1,295 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; + +import { + fallbackProviders, + ReflagClient, + type ClientOptions, + type FlagAPIResponse, + type FlagsFallbackSnapshot, + type HttpClient, + type HttpClientResponse, +} from "../src"; + +const clients: ReflagClient[] = []; +const context = { company: { id: "acme" }, enableTracking: false }; +const privatePayload = "SERVER_ONLY_PAYLOAD"; + +function definition( + key: string, + secret: boolean, +): FlagAPIResponse & { secret: boolean } { + return { + key, + secret, + description: null, + targeting: { + version: 1, + rules: [{ filter: { type: "constant", value: true } }], + }, + config: { + version: 1, + variants: [ + { + key: "chosen", + payload: key === "public" ? { enabled: true } : privatePayload, + filter: { type: "constant", value: true }, + }, + ], + }, + }; +} +function definitions() { + return [definition("public", false), definition("private", true)]; +} +function response(features = definitions(), flagStateVersion = 1) { + return { + status: 200, + ok: true, + etag: '"flags"', + body: { success: true, flagStateVersion, features }, + }; +} +function harness(options: ClientOptions = {}) { + const state: { response: HttpClientResponse } = { + response: response(), + }; + const get = vi.fn(async () => state.response); + const post = vi.fn(async () => ({ + status: 200, + ok: true, + body: { success: true }, + })); + const client = new ReflagClient({ + secretKey: "syntheticSecretKeyWithMoreThan22Chars", + offline: false, + flagsSyncMode: "in-request", + flagsFetchRetries: 0, + logger: { debug: vi.fn(), info: vi.fn(), warn: vi.fn(), error: vi.fn() }, + batchOptions: { intervalMs: 1e9, flushOnExit: false }, + httpClient: { get, post } as unknown as HttpClient, + ...options, + }); + clients.push(client); + return { client, state, get, post }; +} +async function refresh(client: ReflagClient) { + await vi.advanceTimersByTimeAsync(1001); + await client.refreshFlags(); +} +beforeEach(() => vi.useFakeTimers()); +afterEach(() => { + for (const client of clients.splice(0)) client.destroy(); + vi.useRealTimers(); +}); + +describe("v1 bootstrap visibility boundary", () => { + it.each(["direct", "bound"])( + "exports only public flags through %s bootstrap while retaining secret server reads", + async (mode) => { + const h = harness(); + await h.client.initialize(); + const bootstrap = + mode === "direct" + ? h.client.getFlagsForBootstrap(context) + : h.client.bindClient(context).getFlagsForBootstrap(); + expect(Object.keys(bootstrap.flags)).toEqual(["public"]); + expect(bootstrap).toMatchObject({ + flagStateVersion: 1, + context: { company: { id: "acme" } }, + flags: { + public: { + key: "public", + isEnabled: true, + targetingVersion: 1, + config: { + key: "chosen", + payload: { enabled: true }, + targetingVersion: 1, + }, + }, + }, + }); + expect(JSON.stringify(bootstrap)).not.toContain("private"); + expect(JSON.stringify(bootstrap)).not.toContain(privatePayload); + await h.client.flush(); + expect(h.post).not.toHaveBeenCalled(); + expect(h.client.getFlag(context, "private").config.payload).toBe( + privatePayload, + ); + expect(h.client.getFlagDefinitions()).toContainEqual( + expect.objectContaining({ key: "private", secret: true }), + ); + bootstrap.flags.public!.config!.payload.enabled = false; + expect( + h.client.getFlagsForBootstrap(context).flags.public!.config!.payload, + ).toEqual({ enabled: true }); + }, + ); + + it.each([undefined, null, "false", 0, {}, true])( + "does not treat visibility %j as explicitly public", + async (secret) => { + const flags = definitions(); + Reflect.deleteProperty(flags[0]!, "secret"); + if (secret !== undefined) Reflect.set(flags[0]!, "secret", secret); + const h = harness(); + h.state.response = response(flags); + await h.client.initialize(); + expect(h.client.getFlag(context, "public").isEnabled).toBe(true); + expect(h.client.getFlagsForBootstrap(context).flags).toEqual({}); + }, + ); + + it("does not let base or temporary overrides authorize secret or unknown keys", async () => { + const h = harness({ + flagOverrides: () => ({ public: false, private: true, unknown: true }), + }); + await h.client.initialize(); + const pop = h.client.pushFlagOverrides({ + public: { + isEnabled: true, + config: { key: "local", payload: { local: true } }, + }, + extra: true, + }); + expect(h.client.getFlagsForBootstrap(context).flags).toEqual({ + public: { + key: "public", + isEnabled: true, + config: { key: "local", payload: { local: true } }, + }, + }); + pop(); + expect(h.client.getFlagsForBootstrap(context).flags).toEqual({ + public: { key: "public", isEnabled: false, config: undefined }, + }); + expect(h.client.getFlag(context, "unknown").isEnabled).toBe(true); + }); + + it.each(["offline", "unavailable", "static"])( + "excludes value-only %s fallbacks without visibility", + async (mode) => { + const h = harness({ + offline: mode === "offline", + fallbackFlags: ["fallback"], + flagOverrides: { override: true }, + ...(mode === "static" + ? { + flagsFallbackProvider: fallbackProviders.static({ + flags: { fallback: true }, + }), + } + : {}), + }); + h.state.response = { status: 503, ok: false, body: undefined }; + expect(h.client.getFlagsForBootstrap(context).flags).toEqual({}); + await h.client.initialize(); + expect(h.client.getFlagsForBootstrap(context).flags).toEqual({}); + if (mode !== "offline") + expect(h.client.getFlag(context, "fallback").isEnabled).toBe(true); + }, + ); + + it("owns visibility and values independently of response and definition copies", async () => { + const flags = definitions(); + const h = harness(); + h.state.response = response(flags); + await h.client.initialize(); + flags[1]!.secret = false; + const copy = h.client.getFlagDefinitions(); + Reflect.set(copy[1]!, "secret", false); + expect(Object.keys(h.client.getFlagsForBootstrap(context).flags)).toEqual([ + "public", + ]); + expect(h.client.getFlagDefinitions()[0]).toHaveProperty("secret", false); + }); + + it("retains visibility through 304, visibility-only refreshes, and stale responses", async () => { + const h = harness(); + await h.client.initialize(); + h.state.response = { status: 304, ok: false, body: undefined }; + await refresh(h.client); + expect(Object.keys(h.client.getFlagsForBootstrap(context).flags)).toEqual([ + "public", + ]); + const flags = definitions(); + flags[0]!.secret = true; + h.state.response = response(flags); + await refresh(h.client); + expect(h.client.getFlagsForBootstrap(context).flags).toEqual({}); + h.state.response = response(flags, 2); + await refresh(h.client); + h.state.response = response(); + await refresh(h.client); + expect(h.client.getFlagsForBootstrap(context)).toMatchObject({ + flagStateVersion: 2, + flags: {}, + }); + }); + + it("owns visibility while fallback saves wait behind an earlier write", async () => { + let finishFirstSave!: () => void; + const pendingSave = new Promise((resolve) => { + finishFirstSave = resolve; + }); + let saves = 0; + let saved: FlagsFallbackSnapshot | undefined; + const provider = { + load: vi.fn(async () => saved), + save: vi.fn(async (_context: unknown, next: FlagsFallbackSnapshot) => { + if (++saves === 1) await pendingSave; + saved = JSON.parse(JSON.stringify(next)) as FlagsFallbackSnapshot; + }), + }; + const h = harness({ flagsFallbackProvider: provider }); + await h.client.initialize(); + const next = definitions(); + h.state.response = response(next, 2); + await refresh(h.client); + expect(provider.save).toHaveBeenCalledTimes(1); + next[1]!.secret = false; + finishFirstSave(); + await h.client.flush(); + expect(provider.save).toHaveBeenCalledTimes(2); + expect(saved!.flags).toEqual(definitions()); + const fallback = harness({ flagsFallbackProvider: provider }); + fallback.state.response = { status: 503, ok: false, body: undefined }; + await fallback.client.initialize(); + expect( + Object.keys(fallback.client.getFlagsForBootstrap(context).flags), + ).toEqual(["public"]); + }); + + it("persists owned visibility and rejects bootstrap from older snapshots without it", async () => { + let saved: FlagsFallbackSnapshot | undefined; + const provider = { + load: vi.fn(async () => saved), + save: vi.fn(async (_context: unknown, next: FlagsFallbackSnapshot) => { + saved = JSON.parse(JSON.stringify(next)) as FlagsFallbackSnapshot; + }), + }; + const flags = definitions(); + const live = harness({ flagsFallbackProvider: provider }); + live.state.response = response(flags); + await live.client.initialize(); + // Mutating an HTTP response must not change the queued fallback snapshot. + flags[1]!.secret = false; + await live.client.flush(); + expect(saved!.flags).toEqual(definitions()); + const fallback = harness({ flagsFallbackProvider: provider }); + fallback.state.response = { status: 503, ok: false, body: undefined }; + await fallback.client.initialize(); + expect( + Object.keys(fallback.client.getFlagsForBootstrap(context).flags), + ).toEqual(["public"]); + expect(fallback.client.getFlag(context, "private").config.payload).toBe( + privatePayload, + ); + for (const flag of saved!.flags) Reflect.deleteProperty(flag, "secret"); + const legacy = harness({ flagsFallbackProvider: provider }); + legacy.state.response = { status: 503, ok: false, body: undefined }; + await legacy.client.initialize(); + expect(legacy.client.getFlag(context, "public").isEnabled).toBe(true); + expect(legacy.client.getFlagsForBootstrap(context).flags).toEqual({}); + }); +}); diff --git a/packages/node-sdk/test/client.test.ts b/packages/node-sdk/test/client.test.ts index 02b0fe490..fb9a09a47 100644 --- a/packages/node-sdk/test/client.test.ts +++ b/packages/node-sdk/test/client.test.ts @@ -150,6 +150,7 @@ const flagDefinitions: FlagsAPIResponse = { features: [ { key: "flag1", + secret: false, description: "Flag 1", targeting: { version: 1, @@ -182,6 +183,7 @@ const flagDefinitions: FlagsAPIResponse = { }, { key: "flag2", + secret: false, description: "Flag 2", targeting: { version: 2, @@ -3082,7 +3084,7 @@ describe("ReflagClient", () => { expect(flags.flags.flag2).not.toHaveProperty("track"); }); - it("should return fallback flags when client is not initialized", async () => { + it("should exclude value-only fallback flags when client is not initialized", async () => { const flags = client.getFlagsForBootstrap({ company, user, @@ -3090,7 +3092,7 @@ describe("ReflagClient", () => { enableTracking: true, }); - // Should return the fallback flags defined in validOptions + // Value-only fallbacks do not establish public visibility. expect(flags).toStrictEqual({ context: { company, @@ -3098,12 +3100,7 @@ describe("ReflagClient", () => { other: otherContext, enableTracking: true, }, - flags: { - key: { - isEnabled: true, - key: "key", - }, - }, + flags: {}, }); }); @@ -3204,7 +3201,7 @@ describe("ReflagClient", () => { }); }); - it("should use fallback flags when provided and no definitions available", async () => { + it("should exclude configured fallbacks when no definitions establish visibility", async () => { const fallbackTestFlags = { fallbackFlag: { key: "fallbackFlag", @@ -3233,7 +3230,7 @@ describe("ReflagClient", () => { other: otherContext, enableTracking: true, }, - flags: fallbackTestFlags, + flags: {}, }); }); });