Skip to content

Commit

Permalink
fix: do not allow modifying tuples
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 committed Nov 21, 2024
1 parent d4164fb commit fd1a08a
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 @@ -151,11 +151,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 fd1a08a

Please sign in to comment.