From 5e9cffaf85feb3d845aac47deccb5426ff4471d4 Mon Sep 17 00:00:00 2001 From: Didier Garcia Date: Fri, 4 Sep 2026 15:44:10 -0400 Subject: [PATCH] fix(browser): resolve CDN and write key only from the tag that loaded us SECOPS-25767 / LIBRARIES-3140. getCDNUrlFromScriptTag(), getLegacyAJSPath() and getWriteKey() each scanned every `) + .join('\n') + + const html = `${tags}`.trim() const virtualConsole = new VirtualConsole() const jsd = new JSDOM(html, { @@ -20,69 +26,125 @@ function withTag(tag: string) { virtualConsole, }) - const windowSpy = jest.spyOn(global, 'window', 'get') - - const documentSpy = jest.spyOn(global, 'document', 'get') + const doc = jsd.window.document - jest.spyOn(console, 'warn').mockImplementationOnce(() => {}) - - windowSpy.mockImplementation(() => { - return jsd.window as unknown as Window & typeof globalThis + // Point document.currentScript at the loader tag (the last one rendered), + // shadowing the prototype getter that otherwise returns null in jsdom. + const loaderEl = loaderSrc + ? doc.querySelector(`script[src="${loaderSrc}"]`) + : null + Object.defineProperty(doc, 'currentScript', { + configurable: true, + get: () => loaderEl, }) - documentSpy.mockImplementation( - () => jsd.window.document as unknown as Document - ) + jest.spyOn(console, 'warn').mockImplementationOnce(() => {}) + jest + .spyOn(global, 'window', 'get') + .mockImplementation( + () => jsd.window as unknown as Window & typeof globalThis + ) + jest + .spyOn(global, 'document', 'get') + .mockImplementation(() => doc as unknown as Document) } beforeEach(async () => { jest.restoreAllMocks() jest.resetAllMocks() + jest.resetModules() + ;({ getCDN } = await import('../parse-cdn')) +}) + +const SEGMENT_TAG = + 'https://cdn.segment.com/analytics.js/v1/gA5MBlJXrtZaB5sMMZvCF6czfBcfzNO6/analytics.min.js' +const CUSTOM_TAG = + 'https://my.cdn.domain/analytics.js/v1/gA5MBlJXrtZaB5sMMZvCF6czfBcfzNO6/analytics.min.js' +const EVIL_TAG = 'https://evil.example.com/x/analytics.js/v1/evilkey/platform' + +it('detects the existing segment cdn from the loading tag', () => { + withTags(SEGMENT_TAG) + expect(getCDN()).toBe('https://cdn.segment.com') +}) + +it('returns the overridden cdn if window.analytics._cdn is set', () => { + withTags(SEGMENT_TAG) + ;(window as any).analytics = { _cdn: 'http://foo.cdn.com' } + expect(getCDN()).toBe('http://foo.cdn.com') +}) + +it('detects custom / proxy cdns from the loading tag (proxy support preserved)', () => { + withTags(CUSTOM_TAG) + expect(getCDN()).toBe('https://my.cdn.domain') +}) + +it('falls back to Segment if the loading tag src does not match the pattern', () => { + withTags('https://my.cdn.proxy/custom-analytics.min.js') + expect(getCDN()).toBe('https://cdn.segment.com') }) -it('detects the existing segment cdn', () => { - withTag(` -