|
| 1 | +import middy from "@middy/core"; |
| 2 | +import jsonBodyParser from "@middy/http-json-body-parser"; |
| 3 | +import { createClient } from "@supabase/supabase-js"; |
| 4 | +import * as jwt from "jose"; |
| 5 | +import { SiweMessage } from "siwe"; |
| 6 | + |
| 7 | +import { DEFAULT_CHAIN } from "consts/chains"; |
| 8 | +import { ETH_SIGNATURE_REGEX } from "consts/index"; |
| 9 | + |
| 10 | +import { netlifyUri, netlifyDeployUri, netlifyDeployPrimeUri } from "src/generatedNetlifyInfo.json"; |
| 11 | +import { Database } from "src/types/supabase-notification"; |
| 12 | + |
| 13 | +import config from "../config"; |
| 14 | + |
| 15 | +const authUser = async (event) => { |
| 16 | + try { |
| 17 | + if (!event.body) { |
| 18 | + throw new Error("No body provided"); |
| 19 | + } |
| 20 | + |
| 21 | + const signature = event?.body?.signature; |
| 22 | + if (!signature) { |
| 23 | + throw new Error("Missing key : signature"); |
| 24 | + } |
| 25 | + |
| 26 | + if (!ETH_SIGNATURE_REGEX.test(signature)) { |
| 27 | + throw new Error("Invalid signature"); |
| 28 | + } |
| 29 | + |
| 30 | + const message = event?.body?.message; |
| 31 | + if (!message) { |
| 32 | + throw new Error("Missing key : message"); |
| 33 | + } |
| 34 | + |
| 35 | + const address = event?.body?.address; |
| 36 | + if (!address) { |
| 37 | + throw new Error("Missing key : address"); |
| 38 | + } |
| 39 | + |
| 40 | + const siweMessage = new SiweMessage(message); |
| 41 | + |
| 42 | + if ( |
| 43 | + !( |
| 44 | + (netlifyUri && netlifyUri === siweMessage.uri) || |
| 45 | + (netlifyDeployUri && netlifyDeployUri === siweMessage.uri) || |
| 46 | + (netlifyDeployPrimeUri && netlifyDeployPrimeUri === siweMessage.uri) |
| 47 | + ) |
| 48 | + ) { |
| 49 | + console.debug( |
| 50 | + `Invalid URI: expected one of [${netlifyUri} ${netlifyDeployUri} ${netlifyDeployPrimeUri}] but got ${siweMessage.uri}` |
| 51 | + ); |
| 52 | + throw new Error(`Invalid URI`); |
| 53 | + } |
| 54 | + |
| 55 | + if (siweMessage.chainId !== DEFAULT_CHAIN) { |
| 56 | + console.debug(`Invalid chain ID: expected ${DEFAULT_CHAIN} but got ${siweMessage.chainId}`); |
| 57 | + throw new Error(`Invalid chain ID`); |
| 58 | + } |
| 59 | + |
| 60 | + const lowerCaseAddress = siweMessage.address.toLowerCase(); |
| 61 | + if (lowerCaseAddress !== address.toLowerCase()) { |
| 62 | + throw new Error("Address mismatch in provided address and message"); |
| 63 | + } |
| 64 | + |
| 65 | + if (!config.supabaseUrl || !config.supabaseApiKey) { |
| 66 | + throw new Error("Supabase URL or API key is undefined"); |
| 67 | + } |
| 68 | + const supabase = createClient<Database>(config.supabaseUrl, config.supabaseApiKey); |
| 69 | + |
| 70 | + // get nonce from db, if its null that means it was already used |
| 71 | + const { error: nonceError, data: nonceData } = await supabase |
| 72 | + .from("user-nonce") |
| 73 | + .select("nonce") |
| 74 | + .eq("address", lowerCaseAddress) |
| 75 | + .single(); |
| 76 | + |
| 77 | + if (nonceError || !nonceData?.nonce) { |
| 78 | + throw new Error("Unable to fetch nonce from DB"); |
| 79 | + } |
| 80 | + |
| 81 | + try { |
| 82 | + await siweMessage.verify({ signature, nonce: nonceData.nonce, time: new Date().toISOString() }); |
| 83 | + } catch (err) { |
| 84 | + throw new Error("Invalid signer"); |
| 85 | + } |
| 86 | + |
| 87 | + const { error } = await supabase.from("user-nonce").delete().match({ address: lowerCaseAddress }); |
| 88 | + |
| 89 | + if (error) { |
| 90 | + throw new Error("Error updating nonce in DB"); |
| 91 | + } |
| 92 | + |
| 93 | + if (!config.jwtSecret) { |
| 94 | + throw new Error("Secret not set in environment"); |
| 95 | + } |
| 96 | + // user verified, generate auth token |
| 97 | + const encodedSecret = new TextEncoder().encode(config.jwtSecret); |
| 98 | + |
| 99 | + const token = await new jwt.SignJWT({ id: address.toLowerCase() }) |
| 100 | + .setProtectedHeader({ alg: "HS256" }) |
| 101 | + .setIssuer(config.jwtIssuer) |
| 102 | + .setAudience(config.jwtAudience) |
| 103 | + .setExpirationTime(config.jwtExpTime) |
| 104 | + .sign(encodedSecret); |
| 105 | + |
| 106 | + return { statusCode: 200, body: JSON.stringify({ message: "User authorised", token }) }; |
| 107 | + } catch (err) { |
| 108 | + return { statusCode: 500, body: JSON.stringify({ message: `${err}` }) }; |
| 109 | + } |
| 110 | +}; |
| 111 | + |
| 112 | +export const handler = middy(authUser).use(jsonBodyParser()); |
0 commit comments