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

🎀 Support sing in with Gnosis #24

Merged
merged 2 commits into from
Jul 21, 2023
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/good-starfishes-dance.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'fastify-siwe': patch
---

Add support for sign in with Gnosis
3 changes: 1 addition & 2 deletions packages/fastify-siwe/src/constants.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,5 @@ export const GNOSIS_SAFE_ABI = [
'function getMessageHash(bytes memory message) public view returns (bytes32)',
'function signedMessages(bytes32 msgHash) public view returns (uint256)',
'function isValidSignature(bytes calldata _data, bytes calldata _signature) public view returns (bytes4)',
'function checkSignatures(bytes32 dataHash, bytes memory data, bytes memory signatures) public view',
]

export const EIP1271_MAGIC_VALUE = '0x20c13b0b'
78 changes: 27 additions & 51 deletions packages/fastify-siwe/src/plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,11 @@ import fastifyPlugin from 'fastify-plugin'
import type {} from '@fastify/cookie' // Has to be there in order to override the Fastify types with cookies.
import { InMemoryStore } from './InMemoryStore'
import { ethers, utils } from 'ethers'
import { EIP1271_MAGIC_VALUE, GNOSIS_SAFE_ABI } from './constants'
import { GNOSIS_SAFE_ABI } from './constants'
import { RegisterSiweRoutesOpts, registerSiweRoutes } from './registerSiweRoutes'

export interface FastifySiweOptions {
infuraId?: string
store?: SessionStore
}

Expand All @@ -21,7 +22,7 @@ const defaultOpts: RegisterSiweRoutesOpts = {
}

export const signInWithEthereum = (
{ store = new InMemoryStore() }: FastifySiweOptions = {},
{ store = new InMemoryStore(), infuraId }: FastifySiweOptions = {},
{
cookieSecure = defaultOpts.cookieSecure,
cookieSameSite = defaultOpts.cookieSameSite,
Expand All @@ -37,7 +38,7 @@ export const signInWithEthereum = (
}
})

registerSiweRoutes(fastify, { cookieSecure, cookieSameSite, cookieMaxAge, cookiePath })
registerSiweRoutes(fastify, { cookieSecure, cookieSameSite, cookieMaxAge, cookiePath, infuraId })

fastify.addHook('preHandler', async (request: FastifyRequest, reply: FastifyReply) => {
request.siwe = new SiweApi(store)
Expand All @@ -52,14 +53,7 @@ export const signInWithEthereum = (
let token: Token | undefined = undefined
try {
token = JSON.parse(tokenCookie) as Token
const { signature, message } = token

const userIsContract = signature === '0x'
if (userIsContract) {
return handleMultisigWallet(message)
}

const siweMessage = await validateToken(token)
const siweMessage = await validateToken(token, infuraId)

const currentSession = await store.get(siweMessage.nonce)
if (!currentSession?.message || currentSession.message.address !== siweMessage.address) {
Expand All @@ -84,56 +78,38 @@ export const signInWithEthereum = (
})
.send('Invalid SIWE token')
}

async function handleMultisigWallet(message: SiweMessage): Promise<void> {
const siweMessage = new SiweMessage(message)

const currentSession = await store.get(siweMessage.nonce)

if (!currentSession) {
return reply
.status(403)
.clearCookie(`__Host_authToken${address}${chainId}`, {
secure: cookieSecure,
sameSite: cookieSameSite,
path: cookiePath,
})
.send()
}

if (path === '/siwe/signout') {
request.siwe.session = siweMessage
return
}

const provider = ethers.getDefaultProvider(siweMessage.chainId)
const contract = new ethers.Contract(siweMessage.address, new utils.Interface(GNOSIS_SAFE_ABI), provider)

const msgHash = utils.hashMessage(siweMessage.prepareMessage())
let value: string | undefined
try {
value = await contract.isValidSignature(msgHash, '0x')
} catch (err) {
console.error(err)
}
if (value !== EIP1271_MAGIC_VALUE) {
return reply.status(403).send()
}
request.siwe.session = siweMessage
return
}
})
},
{ name: 'SIWE' }
)

export async function validateToken(token: Token): Promise<SiweMessage> {
export async function validateToken(token: Token, infuraId?: string): Promise<SiweMessage> {
const { signature, message } = token
const siweMessage = new SiweMessage(message)
let valid = false

try {
await siweMessage.verify({ signature })
} catch (err) {
valid = true
} catch {} // eslint-disable-line no-empty

try {
await verifyGnosisSafeSignature(siweMessage, signature, infuraId)
valid = true
} catch {} // eslint-disable-line no-empty

if (!valid) {
throw new Error('Invalid SIWE token')
}
return siweMessage
}

async function verifyGnosisSafeSignature(message: SiweMessage, signature: string, infuraId?: string) {
const provider = infuraId
? new ethers.providers.InfuraProvider(message.chainId, infuraId)
: ethers.providers.getDefaultProvider(message.chainId)
const contract = new ethers.Contract(message.address, new utils.Interface(GNOSIS_SAFE_ABI), provider)
const hashedMessage = utils.hashMessage(message.prepareMessage())
const msgHash = await contract.getMessageHash(hashedMessage, { from: message.address })
await contract.checkSignatures(msgHash, hashedMessage, signature)
}
5 changes: 3 additions & 2 deletions packages/fastify-siwe/src/registerSiweRoutes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,12 @@ export interface RegisterSiweRoutesOpts {
cookieSameSite?: boolean | 'strict' | 'lax' | 'none'
cookieMaxAge?: number
cookiePath?: string
infuraId?: string
}

export const registerSiweRoutes = (
fastify: FastifyInstance,
{ cookieSecure, cookieSameSite, cookieMaxAge, cookiePath }: RegisterSiweRoutesOpts
{ cookieSecure, cookieSameSite, cookieMaxAge, cookiePath, infuraId }: RegisterSiweRoutesOpts
) => {
fastify.post(
'/siwe/init',
Expand Down Expand Up @@ -46,7 +47,7 @@ export const registerSiweRoutes = (

if (signature !== '0x') {
try {
await validateToken(token)
await validateToken(token, infuraId)
await req.siwe.setMessage(message)
} catch (err: any) {
return reply.status(403).send(err.message ?? 'Invalid SIWE token')
Expand Down
Loading