diff --git a/packages/core/src/integrations/reportSdkConfig.ts b/packages/core/src/integrations/reportSdkConfig.ts index 7b4160e887ba..286bcd1b1028 100644 --- a/packages/core/src/integrations/reportSdkConfig.ts +++ b/packages/core/src/integrations/reportSdkConfig.ts @@ -6,6 +6,7 @@ import { count } from '../metrics/public-api'; import { Scope } from '../scope'; import type { Integration, IntegrationFn } from '../types/integration'; import { debug } from '../utils/debug-logger'; +import { fingerprintFunction } from '../utils/fingerprintFunction'; import { fnv1a32 } from '../utils/hash'; import { isPlainObject } from '../utils/is'; import { isBrowser } from '../utils/isBrowser'; @@ -55,7 +56,7 @@ export const experimentalReportSdkConfigIntegration = defineIntegration(_experim // and unsupported values with fingerprints before hashing the config. function serialize(value: unknown, ancestors = new Set()): unknown { if (typeof value === 'function') { - return `[Function:${fnv1a32(Function.prototype.toString.call(value))}]`; + return `[Function:${fingerprintFunction(value as (...args: never[]) => unknown)}]`; } // JSON throws on bigints and omits symbols. diff --git a/packages/core/src/utils/fingerprintFunction.ts b/packages/core/src/utils/fingerprintFunction.ts new file mode 100644 index 000000000000..9eefa7812713 --- /dev/null +++ b/packages/core/src/utils/fingerprintFunction.ts @@ -0,0 +1,103 @@ +import { fnv1a32 } from './hash'; + +/** + * Keywords minifiers never rename and that change what a function does. + * Contextual words (`async`, `of`, `get`, `set`, `static`) are left out on purpose: minifiers may use them as names. + */ +const KEYWORDS = new Set( + 'break catch const continue default delete else finally for function if instanceof let new switch throw try var while await return typeof void in case this null true false undefined'.split( + ' ', + ), +); + +/** + * One alternative per kind of token: whitespace and comments, quoted string, backtick, spread, increment, a name (with + * an optional leading `.` or `?.` and a lookahead for a following `:`), regex literal, number, and any other character. + */ +const TOKEN = + /(?:\s|\/\/.*|\/\*[^]*?(?:\*\/|$))+|"(?:[^"\\]|\\.)*"?|'(?:[^'\\]|\\.)*'?|`|\.\.\.|\+\+|--|(\??\.#?|#)?([A-Za-z_$][\w$]*)(?=(\s*:)?)|\/(?:[^/\\\n[]|\\.|\[(?:[^\]\\\n]|\\.)*\])+\/\w*|\d[\w.]*|[^]/g; + +/** + * The rest of a template part, up to the closing backtick or the next `${`. + */ +const TEMPLATE = /(?:[^`\\$]|\\.|\$(?!\{))*(?:`|\$\{|$)/y; + +/** + * Tokens after which a `/` is a division rather than the start of a regex literal. + */ +const ENDS_VALUE = /(?:[\w$"'`)\]]|\+\+|--)$/; + +/** + * Matches the source text engines report for built-in and bound functions, which has no real body and is spelled + * differently by each engine. + */ +const NATIVE = /\{\s*\[native code\]\s*\}\s*$/; + +/** + * Fingerprints a function with every name a minifier can rename blanked out, so that a bundler renaming identifiers + * doesn't change the result. + * + * This is a regex-driven scan rather than a parser, kept small for bundle size. It only aims to be stable across + * builds made with the same minifier: inlined helpers, reordered operands, different quote or number spellings, and + * shorthand keys written out in full still change the result. Method names and shorthand keys are blanked like any + * other name, and a label at the start of a block is kept like an object key. + */ +export function fingerprintFunction(fn: (...args: never[]) => unknown): string { + let source: string; + try { + source = Function.prototype.toString.call(fn); + } catch { + return 'unknown'; + } + + if (NATIVE.test(source)) { + return 'native'; + } + + return fnv1a32(tokenize(source).join(' ')); +} + +/** + * Splits source into tokens, replacing every name that is not a keyword, a property or an object key with `_`. + */ +export function tokenize(src: string): string[] { + const tokens: string[] = []; + // `true` for each open `${`, `false` for each open `{`. + const braces: boolean[] = []; + let prev = ''; + let match; + TOKEN.lastIndex = 0; + + while ((match = TOKEN.exec(src))) { + let token = match[0]; + const ch = token[0] as string; + + if (ch <= ' ' || (ch === '/' && (token[1] === '/' || token[1] === '*'))) { + continue; + } + + if (ch === '`' || (ch === '}' && braces.pop())) { + TEMPLATE.lastIndex = TOKEN.lastIndex; + TEMPLATE.test(src); + token = src.slice(match.index, (TOKEN.lastIndex = TEMPLATE.lastIndex)); + if (token.endsWith('${')) { + braces.push(true); + } + } else if (ch === '{') { + braces.push(false); + } else if (match[2]) { + // Property names and object keys survive minification, every other name is anonymous. + if (!match[1] && !KEYWORDS.has(token) && !(match[3] && (prev === '{' || prev === ','))) { + token = '_'; + } + } else if (ch === '/' && token[1] && ENDS_VALUE.test(prev) && (!KEYWORDS.has(prev) || prev === 'this')) { + // A division, not a regex literal: emit the slash alone and rescan what follows. + token = ch; + TOKEN.lastIndex = match.index + 1; + } + + tokens.push((prev = token)); + } + + return tokens; +} diff --git a/packages/core/test/lib/integrations/reportSdkConfig.test.ts b/packages/core/test/lib/integrations/reportSdkConfig.test.ts index 009ef6aa9760..4e444314e3cd 100644 --- a/packages/core/test/lib/integrations/reportSdkConfig.test.ts +++ b/packages/core/test/lib/integrations/reportSdkConfig.test.ts @@ -226,6 +226,23 @@ describe('experimentalReportSdkConfigIntegration', () => { expect((payload.options as Record).initialScope).toMatch(/^\[Function:\w+\]$/); }); + it('reports callbacks that differ only in their local names as the same function', () => { + const report = (beforeSend: (event: unknown) => unknown): Record => + reportConfig( + getDefaultTestClientOptions({ + dsn: 'https://username@domain/123', + ...captureOptionsSetByUser({ beforeSend, integrations: [experimentalReportSdkConfigIntegration()] }), + }), + ).options as Record; + + const original = report(event => event); + const renamed = report(e => e); + const dropsEverything = report(() => null); + + expect(renamed.beforeSend).toBe(original.beforeSend); + expect(dropsEverything.beforeSend).not.toBe(original.beforeSend); + }); + it('reports the names of the default integrations the user passed', () => { const userOptions = captureOptionsSetByUser({ defaultIntegrations: [experimentalReportSdkConfigIntegration()], diff --git a/packages/core/test/lib/utils/fingerprintFunction.test.ts b/packages/core/test/lib/utils/fingerprintFunction.test.ts new file mode 100644 index 000000000000..90dad6fbd5c6 --- /dev/null +++ b/packages/core/test/lib/utils/fingerprintFunction.test.ts @@ -0,0 +1,130 @@ +import { describe, expect, it } from 'vitest'; +import { fingerprintFunction, tokenize } from '../../../src/utils/fingerprintFunction'; + +const norm = (src: string): string => tokenize(src).join(' '); + +describe('fingerprintFunction', () => { + describe('stays the same when only minification changes', () => { + it.each([ + ['renamed locals and imports', 'e=>n(e)?null:e', 't=>r(t)?null:t'], + ['spread of a renamed local', 'e=>({...e.tags})', 't=>({...t.tags})'], + ['whitespace', 'e => e', 'e=>e'], + ['comments', 'e=>e // keep all\n', 'e=>/* keep */e'], + ['renamed ternary branches', '(a,b)=>a?b:a', '(x,y)=>x?y:x'], + ['renamed destructuring targets', '({event:e})=>e', '({event:t})=>t'], + ['renamed names in template substitutions', "e=>`'${n(e)}' and '${e}'`", "t=>`'${r(t)}' and '${t}'`"], + ['renamed names after a regex containing quotes', `e=>/["']/.test(e)?n("x"):r`, `t=>/["']/.test(t)?a("x"):o`], + ['renamed operands of a division', 'e=>e/n/r', 't=>t/a/o'], + ['renamed call arguments inside an object', 'e=>({a:f(x,y,z)})', 't=>({a:g(p,q,r)})'], + ['renamed array items inside an object', 'e=>({a:[x,y,z]})', 't=>({a:[p,q,r]})'], + ['renamed arrow parameters inside an object', 'e=>({a:(x,y,z)=>x})', 't=>({a:(p,q,r)=>p})'], + ])('%s', (_label, a, b) => { + expect(norm(a)).toBe(norm(b)); + }); + }); + + describe('changes when behavior changes', () => { + it.each([ + ['always null vs passthrough', '()=>null', 'e=>e'], + ['return null vs return event', 'function(e){return null}', 'function(e){return e}'], + ['return undefined vs return event', 'function(e){return undefined}', 'function(e){return e}'], + ['property', 'e=>e.exception?e:null', 'e=>e.message?e:null'], + ['optional chaining property', 'e=>e?.exception?e:null', 'e=>e?.message?e:null'], + ['string literal', `e=>e.type==="transaction"?null:e`, `e=>e.type==="error"?null:e`], + ['bracket key', `e=>e["exception"]?e:null`, `e=>e["message"]?e:null`], + ['template literal', 'e=>`${e.level}:drop`', 'e=>`${e.level}:keep`'], + ['regex literal', 'e=>/foo/.test(e.message)?null:e', 'e=>/bar/.test(e.message)?null:e'], + ['regex flags', 'e=>/foo/i.test(e)', 'e=>/foo/g.test(e)'], + ['number', 'e=>Math.random()<0.1?e:null', 'e=>Math.random()<1?e:null'], + ['branches swapped', 'e=>n(e)?null:e', 'e=>n(e)?e:null'], + ['throw vs return', 'e=>{throw e}', 'e=>{return e}'], + ['object key', 'e=>({level:e})', 'e=>({type:e})'], + ['private field', 'e=>e.#a', 'e=>e.#b'], + ['destructured key', 'e=>{const{exception:t}=e;return t}', 'e=>{const{message:t}=e;return t}'], + ['thrown object key', 'e=>{throw{level:e}}', 'e=>{throw{type:e}}'], + ['regex after a block', 'e=>{if(e){return e}/a/.test(e)}', 'e=>{if(e){return e}/b/.test(e)}'], + ])('%s', (_label, a, b) => { + expect(norm(a)).not.toBe(norm(b)); + }); + }); + + describe('tokenizer', () => { + it('tells a regex from a division', () => { + expect(norm('e=>e/2/1')).toBe('_ = > _ / 2 / 1'); + expect(norm('e=>/2/.test(e)')).toBe('_ = > /2/ .test ( _ )'); + }); + + it('keeps regex character classes containing slashes intact', () => { + expect(norm('e=>/[/]a/.test(e)')).toBe('_ = > /[/]a/ .test ( _ )'); + }); + + it('handles nested template literals and object literals in substitutions', () => { + expect(norm('e=>`a${`b${e}`}c${({k:e})}`')).toBe('_ = > `a${ `b${ _ }` }c${ ( { k : _ } ) }`'); + }); + + it('reads a regex inside a template substitution and a division after a template', () => { + expect(norm('e=>`${/a/.test(e)}`')).toBe('_ = > `${ /a/ .test ( _ ) }`'); + expect(norm('e=>`${e}`/2/e')).toBe('_ = > `${ _ }` / 2 / _'); + }); + + it('cannot tell a label at the start of a block from an object key', () => { + expect(norm('e=>{a:e}')).toBe('_ = > { a : _ }'); + }); + + it('survives unterminated input', () => { + expect(() => norm('e=>"abc')).not.toThrow(); + expect(() => norm('e=>`abc${')).not.toThrow(); + expect(() => norm('e=>/abc')).not.toThrow(); + expect(() => norm('e=>/* abc')).not.toThrow(); + expect(() => norm('}}}}')).not.toThrow(); + expect(() => norm('`a\\`')).not.toThrow(); + }); + + it('keeps spread and increments whole', () => { + expect(norm('a++ +b-- -c')).toBe('_ ++ + _ -- - _'); + expect(norm('f(...a,..b)')).toBe('_ ( ... _ , . .b )'); + }); + + it('keeps object keys next to calls and arrays, and in objects nested inside them', () => { + expect(norm('({a:f(x,y),b:[y,{c:z}]})')).toBe('( { a : _ ( _ , _ ) , b : [ _ , { c : _ } ] } )'); + }); + + it('does not mistake a ternary branch for an object key', () => { + expect(norm('f(x,a?b:c)')).toBe('_ ( _ , _ ? _ : _ )'); + }); + + it('keeps object keys but not shorthand keys or method names', () => { + expect(norm('e=>({a:1,b(){},c,...d})')).toBe('_ = > ( { a : 1 , _ ( ) { } , _ , ... _ } )'); + }); + + it('keeps `undefined` but no other global', () => { + expect(norm('e=>Math.now()===undefined')).toBe('_ = > _ .now ( ) = = = undefined'); + }); + + it('tells a regex from a division after keywords, operators and closing brackets', () => { + expect(norm('return/a/g')).toBe('return /a/g'); + expect(norm('this/a/g')).toBe('this / _ / _'); + expect(norm('(a)/b/c')).toBe('( _ ) / _ / _'); + expect(norm('e=>e++/2+n(e)')).toBe('_ = > _ ++ / 2 + _ ( _ )'); + expect(norm('e=>e--/2')).toBe('_ = > _ -- / 2'); + expect(norm('({}/2)')).toBe('( { } / 2 )'); + expect(norm('if(a){}/a/g')).toBe('if ( _ ) { } /a/g'); + expect(norm('e=>e?/a/.test(e):e')).toBe('_ = > _ ? /a/ .test ( _ ) : _'); + }); + }); + + it('marks built-in and bound functions as native', () => { + const bound = function (this: unknown): unknown { + return this; + }.bind(null); + + expect(fingerprintFunction(bound)).toBe('native'); + expect(fingerprintFunction(Math.max)).toBe('native'); + expect(fingerprintFunction(() => '{ [native code] }'.length)).not.toBe('native'); + }); + + it('fingerprints functions', () => { + expect(fingerprintFunction(e => e)).toBe(fingerprintFunction(t => t)); + expect(fingerprintFunction(() => null)).not.toBe(fingerprintFunction(e => e)); + }); +});