|
| 1 | +import { createHash, randomBytes, randomUUID } from 'node:crypto' |
| 2 | +import { |
| 3 | + BadRequestException, |
| 4 | + Body, |
| 5 | + Controller, |
| 6 | + Header, |
| 7 | + Injectable, |
| 8 | + Param, |
| 9 | + Post, |
| 10 | + Req, |
| 11 | + ServiceUnavailableException, |
| 12 | + SetMetadata, |
| 13 | + UnauthorizedException, |
| 14 | +} from '@nestjs/common' |
| 15 | +import axios from 'axios' |
| 16 | +import type { Request } from 'express' |
| 17 | +import { z } from 'zod' |
| 18 | + |
| 19 | +import { clientIp, SecurityRateLimiter } from '@shapeshift/shared-utils' |
| 20 | + |
| 21 | +import { PrismaService } from '../prisma/prisma.service' |
| 22 | + |
| 23 | +import { checkoutSchema, signWidgetUrl } from './sign-widget' |
| 24 | + |
| 25 | +const supportedSchema = z.object({ |
| 26 | + message: z.object({ |
| 27 | + crypto: z.array(z.object({ id: z.string(), network: z.string().optional() })).max(20000), |
| 28 | + fiat: z.array(z.object({ code: z.string() })).max(500), |
| 29 | + }), |
| 30 | +}) |
| 31 | +type Catalogue = z.infer<typeof supportedSchema> |
| 32 | + |
| 33 | +@Injectable() |
| 34 | +export class OnramperCatalogue { |
| 35 | + private cache?: { data: Catalogue; expiresAt: number } |
| 36 | + private pending?: Promise<Catalogue> |
| 37 | + |
| 38 | + async get(): Promise<Catalogue> { |
| 39 | + if (this.cache && this.cache.expiresAt > Date.now()) return this.cache.data |
| 40 | + if (this.pending !== undefined) return this.pending |
| 41 | + this.pending = this.fetch().finally(() => { |
| 42 | + this.pending = undefined |
| 43 | + }) |
| 44 | + return this.pending |
| 45 | + } |
| 46 | + |
| 47 | + private async fetch(): Promise<Catalogue> { |
| 48 | + const baseUrl = process.env.ONRAMPER_API_URL ?? 'https://api.onramper.com/' |
| 49 | + const base = new URL(baseUrl) |
| 50 | + if (base.protocol !== 'https:' || base.username || base.password || base.search || base.hash) |
| 51 | + throw new ServiceUnavailableException('Invalid provider configuration') |
| 52 | + const response = await axios.get<unknown>( |
| 53 | + new URL('supported', base.href.endsWith('/') ? base.href : `${base.href}/`).href, |
| 54 | + { |
| 55 | + headers: { Authorization: process.env.ONRAMPER_API_KEY }, |
| 56 | + timeout: 10000, |
| 57 | + maxRedirects: 0, |
| 58 | + maxContentLength: 2 * 1024 * 1024, |
| 59 | + }, |
| 60 | + ) |
| 61 | + const data = supportedSchema.parse(response.data) |
| 62 | + this.cache = { data, expiresAt: Date.now() + 60_000 } |
| 63 | + return data |
| 64 | + } |
| 65 | +} |
| 66 | + |
| 67 | +@Controller('onramper') |
| 68 | +@SetMetadata('public-access', true) |
| 69 | +export class OnramperController { |
| 70 | + constructor( |
| 71 | + private readonly limits: SecurityRateLimiter, |
| 72 | + private readonly catalogue: OnramperCatalogue, |
| 73 | + private readonly db: PrismaService, |
| 74 | + ) {} |
| 75 | + |
| 76 | + @Header('Cache-Control', 'no-store') |
| 77 | + @Post('intents') |
| 78 | + async createIntent(@Req() request: Request, @Body() input: unknown) { |
| 79 | + const parsed = checkoutSchema.safeParse(input) |
| 80 | + if (!parsed.success) throw new BadRequestException('Invalid checkout request') |
| 81 | + await this.limits.consume('onramper-global', 'all', 1000) |
| 82 | + const origin = request.headers.origin |
| 83 | + if (!origin || !checkoutOrigins().includes(origin)) throw new BadRequestException('Unsupported application origin') |
| 84 | + await this.limits.consume( |
| 85 | + 'onramper-ip', |
| 86 | + clientIp(request.socket.remoteAddress, request.headers['x-forwarded-for'] as string | undefined), |
| 87 | + 30, |
| 88 | + ) |
| 89 | + const apiKey = process.env.ONRAMPER_API_KEY |
| 90 | + const privateKey = process.env.ONRAMPER_PRIVATE_KEY |
| 91 | + if (!apiKey || !privateKey) throw new ServiceUnavailableException('Onramper signing is not configured') |
| 92 | + const checkout = parsed.data |
| 93 | + const catalogue = await this.catalogue.get().catch(() => { |
| 94 | + throw new ServiceUnavailableException('Provider unavailable') |
| 95 | + }) |
| 96 | + if ( |
| 97 | + !catalogue.message.crypto.some((crypto) => crypto.id === checkout.crypto) || |
| 98 | + !catalogue.message.fiat.some((fiat) => fiat.code.toUpperCase() === checkout.fiat) |
| 99 | + ) |
| 100 | + throw new BadRequestException('Unsupported currency') |
| 101 | + if (checkout.redirectUrl) { |
| 102 | + const redirect = new URL(checkout.redirectUrl) |
| 103 | + const allowed = process.env.ONRAMPER_REDIRECT_ORIGINS?.split(',').map((value) => value.trim()) ?? [] |
| 104 | + if (!allowed.includes(redirect.origin) || redirect.username || redirect.password) |
| 105 | + throw new BadRequestException('Redirect is not allowed') |
| 106 | + } |
| 107 | + const token = randomBytes(32).toString('hex') |
| 108 | + const id = randomUUID() |
| 109 | + const expiresAt = new Date(Date.now() + 5 * 60_000) |
| 110 | + await this.db.onramperIntent.deleteMany({ where: { expiresAt: { lt: new Date() } } }) |
| 111 | + await this.db.onramperIntent.create({ |
| 112 | + data: { id, tokenHash: createHash('sha256').update(token).digest('hex'), origin, checkout, expiresAt }, |
| 113 | + }) |
| 114 | + return { id, token, expiresAt: expiresAt.toISOString() } |
| 115 | + } |
| 116 | + |
| 117 | + @Header('Cache-Control', 'no-store') |
| 118 | + @Post('intents/:id/checkout') |
| 119 | + async checkout(@Req() request: Request, @Param('id') id: string, @Body() body: unknown) { |
| 120 | + const parsed = z.strictObject({ token: z.string().regex(/^[a-f0-9]{64}$/) }).safeParse(body) |
| 121 | + if (!parsed.success || !z.uuid().safeParse(id).success) throw new BadRequestException('Invalid checkout intent') |
| 122 | + await this.limits.consume('onramper-redeem-global', 'all', 1000) |
| 123 | + await this.limits.consume( |
| 124 | + 'onramper-redeem-ip', |
| 125 | + clientIp(request.socket.remoteAddress, request.headers['x-forwarded-for'] as string | undefined), |
| 126 | + 30, |
| 127 | + ) |
| 128 | + const intent = await this.db.onramperIntent.findUnique({ where: { id } }) |
| 129 | + if ( |
| 130 | + !intent || |
| 131 | + intent.expiresAt <= new Date() || |
| 132 | + intent.tokenHash !== createHash('sha256').update(parsed.data.token).digest('hex') || |
| 133 | + intent.origin !== request.headers.origin || |
| 134 | + !checkoutOrigins().includes(intent.origin) |
| 135 | + ) |
| 136 | + throw new UnauthorizedException('Invalid or expired checkout intent') |
| 137 | + const checkout = checkoutSchema.parse(intent.checkout) |
| 138 | + const apiKey = process.env.ONRAMPER_API_KEY |
| 139 | + const privateKey = process.env.ONRAMPER_PRIVATE_KEY |
| 140 | + if (!apiKey || !privateKey) throw new ServiceUnavailableException('Onramper signing is not configured') |
| 141 | + const url = signWidgetUrl(checkout, { |
| 142 | + apiKey, |
| 143 | + privateKey, |
| 144 | + widgetUrl: process.env.ONRAMPER_WIDGET_URL ?? 'https://buy.onramper.com', |
| 145 | + redirectOrigins: process.env.ONRAMPER_REDIRECT_ORIGINS?.split(',').map((origin) => origin.trim()) ?? [], |
| 146 | + }) |
| 147 | + const consumed = await this.db.onramperIntent.deleteMany({ where: { id, expiresAt: { gt: new Date() } } }) |
| 148 | + if (consumed.count !== 1) throw new UnauthorizedException('Checkout intent already used') |
| 149 | + return { url } |
| 150 | + } |
| 151 | +} |
| 152 | + |
| 153 | +function checkoutOrigins(): string[] { |
| 154 | + const values = process.env.ONRAMPER_ALLOWED_ORIGINS?.split(',').map((value) => value.trim()) ?? [] |
| 155 | + if ( |
| 156 | + !values.length || |
| 157 | + values.some((value) => { |
| 158 | + try { |
| 159 | + const url = new URL(value) |
| 160 | + return ( |
| 161 | + url.origin !== value || |
| 162 | + (url.protocol !== 'https:' && !(url.protocol === 'http:' && url.hostname === 'localhost')) |
| 163 | + ) |
| 164 | + } catch { |
| 165 | + return true |
| 166 | + } |
| 167 | + }) |
| 168 | + ) |
| 169 | + throw new ServiceUnavailableException('Invalid checkout origin configuration') |
| 170 | + return values |
| 171 | +} |
0 commit comments