From f967ad10773c30d3a45213a585d2e16878a78b4f Mon Sep 17 00:00:00 2001 From: Slava Rudkovskiy Date: Wed, 28 Oct 2026 11:00:00 +0200 Subject: [PATCH] prevent prototype pollution and add event listener tests --- src/GuideChimp.js | 5 +++-- test/specs/emit.spec.js | 43 +++++++++++++++++++++++++++++++++++++++++ 2 files changed, 46 insertions(+), 2 deletions(-) create mode 100644 test/specs/emit.spec.js diff --git a/src/GuideChimp.js b/src/GuideChimp.js index 7bcf2d1..de86986 100644 --- a/src/GuideChimp.js +++ b/src/GuideChimp.js @@ -52,7 +52,8 @@ export default class GuideChimp { this.cache = new Map(); - this.listeners = {}; + // Event names are caller-controlled, so keep them out of Object.prototype. + this.listeners = Object.create(null); this.observers = {}; @@ -1534,7 +1535,7 @@ export default class GuideChimp { const e = event.trim(); - this.listeners[e] = this.listeners[e] || {}; + this.listeners[e] = this.listeners[e] || Object.create(null); this.listeners[e][priority] = this.listeners[e][priority] || []; this.listeners[e][priority].push(listener); diff --git a/test/specs/emit.spec.js b/test/specs/emit.spec.js new file mode 100644 index 0000000..5d3806c --- /dev/null +++ b/test/specs/emit.spec.js @@ -0,0 +1,43 @@ +import GuideChimp from '../../src/GuideChimp'; + +describe('GuideChimp event listeners', () => { + let guideChimp; + + beforeEach(() => { + guideChimp = new GuideChimp([]); + }); + + it('registers listeners and emits arguments with the GuideChimp instance as this', async () => { + const listener = vi.fn(function listener(...args) { + expect(this).toBe(guideChimp); + return args.join(' '); + }); + + expect(guideChimp.on('customEvent', listener)).toBe(guideChimp); + await expect(guideChimp.emit('customEvent', 'hello', 'world')).resolves.toEqual(['hello world']); + expect(listener).toHaveBeenCalledOnce(); + }); + + it('supports event names that exist on Object.prototype without modifying it', async () => { + const originalProperties = Object.getOwnPropertyNames(Object.prototype); + const listener = vi.fn(); + + guideChimp.on('__proto__', listener); + await guideChimp.emit('__proto__'); + + expect(listener).toHaveBeenCalledOnce(); + expect(Object.getOwnPropertyNames(Object.prototype)).toEqual(originalProperties); + }); + + it('emits listeners from highest to lowest priority', async () => { + const calls = []; + + guideChimp.on('customEvent', () => calls.push('low'), { priority: 'low' }); + guideChimp.on('customEvent', () => calls.push('high'), { priority: 'high' }); + guideChimp.on('customEvent', () => calls.push('critical'), { priority: 'critical' }); + + await guideChimp.emit('customEvent'); + + expect(calls).toEqual(['critical', 'high', 'low']); + }); +});