stacker.news/api/resolvers/ofac.js

30 lines
951 B
JavaScript
Raw Normal View History

2023-12-14 17:30:51 +00:00
import { GraphQLError } from 'graphql'
// this function makes america more secure apparently
2023-12-17 21:14:59 +00:00
export default async function assertGofacYourself ({ models, headers, ip }) {
const country = await gOFACYourself({ models, headers, ip })
2023-12-14 17:30:51 +00:00
if (!country) return
throw new GraphQLError(
`Your IP address is in ${country}. We cannot provide financial services to residents of ${country}.`,
{ extensions: { code: 'FORBIDDEN' } })
}
2023-12-17 21:14:59 +00:00
export async function gOFACYourself ({ models, headers = {}, ip }) {
2023-12-14 17:30:51 +00:00
const { 'x-forwarded-for': xForwardedFor, 'x-real-ip': xRealIp } = headers
2023-12-17 21:14:59 +00:00
ip ||= xRealIp || xForwardedFor?.split(',')?.[0]
2023-12-14 17:30:51 +00:00
if (!ip) return false
2023-12-21 02:05:09 +00:00
try {
const countries = await models.$queryRaw`
SELECT * FROM "OFAC" WHERE iprange("startIP","endIP") >>= ${ip}::ipaddress`
2023-12-14 17:30:51 +00:00
2023-12-21 02:05:09 +00:00
if (countries.length === 0) return false
2023-12-14 17:30:51 +00:00
2023-12-21 02:05:09 +00:00
return countries[0].country
} catch (e) {
console.error('gOFACYourself', e)
return false
}
2023-12-14 17:30:51 +00:00
}