Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(siwe): createSiweMessage domain validation #2299

Merged
merged 1 commit into from
May 23, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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 @@
`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 @@
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+-.]*)$/
Loading