From 77f15d29b07e7b7e2fb9e3ef39cd0e1da0982388 Mon Sep 17 00:00:00 2001 From: Alex Potsides Date: Thu, 21 Nov 2024 15:29:31 +0000 Subject: [PATCH] fix: do not allow modifying tuples (#391) Return a clone of the string/tuple list to prevent external modification of internal state. --- src/multiaddr.ts | 16 ++++++++++++++-- test/index.spec.ts | 16 ++++++++++++++++ 2 files changed, 30 insertions(+), 2 deletions(-) diff --git a/src/multiaddr.ts b/src/multiaddr.ts index a99470e5..52320217 100644 --- a/src/multiaddr.ts +++ b/src/multiaddr.ts @@ -137,11 +137,23 @@ export class Multiaddr implements MultiaddrInterface { } tuples (): Array<[number, Uint8Array?]> { - return this.#tuples + return this.#tuples.map(([code, value]) => { + if (value == null) { + return [code] + } + + return [code, value] + }) } stringTuples (): Array<[number, string?]> { - return this.#stringTuples + return this.#stringTuples.map(([code, value]) => { + if (value == null) { + return [code] + } + + return [code, value] + }) } encapsulate (addr: MultiaddrInput): Multiaddr { diff --git a/test/index.spec.ts b/test/index.spec.ts index bc4e6211..18bf5845 100644 --- a/test/index.spec.ts +++ b/test/index.spec.ts @@ -731,6 +731,14 @@ describe('helpers', () => { [302] ]) }) + + it('does not allow modifying parts', () => { + const ma = multiaddr('/ip4/0.0.0.0/tcp/1234') + const tuples = ma.tuples() + tuples[0][0] = 41 + + expect(ma.toOptions()).to.have.property('family', 4) + }) }) describe('.stringTuples', () => { @@ -741,6 +749,14 @@ describe('helpers', () => { [302] ]) }) + + it('does not allow modifying string parts', () => { + const ma = multiaddr('/ip4/0.0.0.0/tcp/1234') + const tuples = ma.stringTuples() + tuples[0][0] = 41 + + expect(ma.toOptions()).to.have.property('family', 4) + }) }) describe('.decapsulate', () => {