Skip to content

Commit

Permalink
fix(siwe): createSiweMessage domain validation
Browse files Browse the repository at this point in the history
  • Loading branch information
tmm committed May 23, 2024
1 parent f3d77e7 commit fdfcbab
Show file tree
Hide file tree
Showing 3 changed files with 51 additions and 2 deletions.
5 changes: 5 additions & 0 deletions .changeset/chatty-flies-tan.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"viem": patch
---

Fixed `createSiweMessage` `domain` validation.
34 changes: 34 additions & 0 deletions src/utils/siwe/createSiweMessage.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -332,3 +332,37 @@ test('behavior: invalid resources', () => {
Version: viem@1.0.2]
`)
})

test.each([
'example.com',
'localhost',
'127.0.0.1',
'example.com:3000',
'localhost:3000',
'127.0.0.1:3000',
])('valid domain `%s`', (domain) => {
expect(
createSiweMessage({
...message,
domain,
}),
).toBeTypeOf('string')
})

test.each([
'http://example.com',
'http://localhost',
'http://127.0.0.1',
'http://example.com:3000',
'http://localhost:3000',
'http://127.0.0.1:3000',
'foobarbaz',
'-example.com',
])('invalid domain `%s`', (domain) => {
expect(() =>
createSiweMessage({
...message,
domain,
}),
).toThrowError()
})
14 changes: 12 additions & 2 deletions src/utils/siwe/createSiweMessage.ts
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,13 @@ export function createSiweMessage(
`Provided value: ${chainId}`,
],
})
if (!domainRegex.test(domain))
if (
!(
domainRegex.test(domain) ||
ipRegex.test(domain) ||
localhostRegex.test(domain)

Check warning on line 68 in src/utils/siwe/createSiweMessage.ts

View check run for this annotation

Codecov / codecov/patch

src/utils/siwe/createSiweMessage.ts#L68

Added line #L68 was not covered by tests
)
)
throw new SiweInvalidMessageFieldError({
field: 'domain',
metaMessages: [
Expand Down Expand Up @@ -163,6 +169,10 @@ export function createSiweMessage(
return `${prefix}\n${suffix}`
}

const domainRegex = /^(?:(?:(?!-)[a-zA-Z0-9-]{1,63}(?<!-)\.)+[a-zA-Z]{2,63})$/
const domainRegex =
/^([a-zA-Z0-9][-a-zA-Z0-9]{0,61}[a-zA-Z0-9])\.[a-zA-Z]{2,}(:[0-9]{1,5})?$/
const ipRegex =
/^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)(:[0-9]{1,5})?$/
const localhostRegex = /^localhost(:[0-9]{1,5})?$/
const nonceRegex = /^[a-zA-Z0-9]{8,}$/
const schemeRegex = /^([a-zA-Z][a-zA-Z0-9+-.]*)$/

0 comments on commit fdfcbab

Please sign in to comment.