Skip to content
3 changes: 2 additions & 1 deletion packages/core/src/integrations/reportSdkConfig.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down Expand Up @@ -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<object>()): 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.
Expand Down
103 changes: 103 additions & 0 deletions packages/core/src/utils/fingerprintFunction.ts
Original file line number Diff line number Diff line change
@@ -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(' '));
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Feat lacks integration coverage

Low Severity

This is a feat PR and only adds unit tests (plus a TestClient assertion in reportSdkConfig.test.ts). The review rules for feat work require at least one integration or E2E test, for example covering a minified beforeSend through a real init and config payload. I flagged this because it was mentioned in the PR review guidelines.

Fix in Cursor Fix in Web

Triggered by project rule: PR Review Guidelines for Cursor Bot

Reviewed by Cursor Bugbot for commit b6d5905. Configure here.


/**
* 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;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Value keywords misread as regex

Low Severity

The slash after this is treated as division, but the other value keywords null, true, false, and undefined still take the regex path. A minifier that rewrites true / foo / bar as true/a/g therefore keeps the renamed names inside a fake regex, so the fingerprint can change when only locals were renamed.

Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit b6d5905. Configure here.

}

tokens.push((prev = token));
}

return tokens;
}
17 changes: 17 additions & 0 deletions packages/core/test/lib/integrations/reportSdkConfig.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -226,6 +226,23 @@ describe('experimentalReportSdkConfigIntegration', () => {
expect((payload.options as Record<string, unknown>).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<string, unknown> =>
reportConfig(
getDefaultTestClientOptions({
dsn: 'https://username@domain/123',
...captureOptionsSetByUser({ beforeSend, integrations: [experimentalReportSdkConfigIntegration()] }),
}),
).options as Record<string, unknown>;

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()],
Expand Down
130 changes: 130 additions & 0 deletions packages/core/test/lib/utils/fingerprintFunction.test.ts
Original file line number Diff line number Diff line change
@@ -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));
});
});
Loading