Skip to content

Commit 77f15d2

Browse files
authored
fix: do not allow modifying tuples (#391)
Return a clone of the string/tuple list to prevent external modification of internal state.
1 parent 823b45f commit 77f15d2

File tree

2 files changed

+30
-2
lines changed

2 files changed

+30
-2
lines changed

src/multiaddr.ts

Lines changed: 14 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -137,11 +137,23 @@ export class Multiaddr implements MultiaddrInterface {
137137
}
138138

139139
tuples (): Array<[number, Uint8Array?]> {
140-
return this.#tuples
140+
return this.#tuples.map(([code, value]) => {
141+
if (value == null) {
142+
return [code]
143+
}
144+
145+
return [code, value]
146+
})
141147
}
142148

143149
stringTuples (): Array<[number, string?]> {
144-
return this.#stringTuples
150+
return this.#stringTuples.map(([code, value]) => {
151+
if (value == null) {
152+
return [code]
153+
}
154+
155+
return [code, value]
156+
})
145157
}
146158

147159
encapsulate (addr: MultiaddrInput): Multiaddr {

test/index.spec.ts

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -731,6 +731,14 @@ describe('helpers', () => {
731731
[302]
732732
])
733733
})
734+
735+
it('does not allow modifying parts', () => {
736+
const ma = multiaddr('/ip4/0.0.0.0/tcp/1234')
737+
const tuples = ma.tuples()
738+
tuples[0][0] = 41
739+
740+
expect(ma.toOptions()).to.have.property('family', 4)
741+
})
734742
})
735743

736744
describe('.stringTuples', () => {
@@ -741,6 +749,14 @@ describe('helpers', () => {
741749
[302]
742750
])
743751
})
752+
753+
it('does not allow modifying string parts', () => {
754+
const ma = multiaddr('/ip4/0.0.0.0/tcp/1234')
755+
const tuples = ma.stringTuples()
756+
tuples[0][0] = 41
757+
758+
expect(ma.toOptions()).to.have.property('family', 4)
759+
})
744760
})
745761

746762
describe('.decapsulate', () => {

0 commit comments

Comments
 (0)