Skip to content

Commit

Permalink
fix: do not allow modifying tuples (#391)
Browse files Browse the repository at this point in the history
Return a clone of the string/tuple list to prevent external
modification of internal state.
  • Loading branch information
achingbrain authored Nov 21, 2024
1 parent 823b45f commit 77f15d2
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 2 deletions.
16 changes: 14 additions & 2 deletions src/multiaddr.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
16 changes: 16 additions & 0 deletions test/index.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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', () => {
Expand All @@ -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', () => {
Expand Down

0 comments on commit 77f15d2

Please sign in to comment.