|
| 1 | +import { createLogger } from '@sim/logger' |
| 2 | +import { getErrorMessage } from '@sim/utils/errors' |
| 3 | +import { type NextRequest, NextResponse } from 'next/server' |
| 4 | +import { awsMarketplaceRegistrationFormSchema } from '@/lib/api/contracts/aws-marketplace' |
| 5 | +import { serializeClaimCookie } from '@/lib/billing/aws-marketplace/claim' |
| 6 | +import { getAwsMarketplaceProductCode } from '@/lib/billing/aws-marketplace/config' |
| 7 | +import { |
| 8 | + AWS_MARKETPLACE_ONBOARDING_PATH, |
| 9 | + type AwsMarketplaceOnboardingError, |
| 10 | +} from '@/lib/billing/aws-marketplace/onboarding' |
| 11 | +import { registerAwsMarketplaceBuyer } from '@/lib/billing/aws-marketplace/registration' |
| 12 | +import { enforceIpRateLimit, type TokenBucketConfig } from '@/lib/core/rate-limiter' |
| 13 | +import { readFormDataWithLimit } from '@/lib/core/utils/stream-limits' |
| 14 | +import { getBaseUrl } from '@/lib/core/utils/urls' |
| 15 | +import { withRouteHandler } from '@/lib/core/utils/with-route-handler' |
| 16 | + |
| 17 | +export const dynamic = 'force-dynamic' |
| 18 | + |
| 19 | +const logger = createLogger('AwsMarketplaceRegisterAPI') |
| 20 | + |
| 21 | +/** The form carries one opaque token; anything larger is not from AWS. */ |
| 22 | +const MAX_FORM_BYTES = 16 * 1024 |
| 23 | + |
| 24 | +const REGISTER_RATE_LIMIT: TokenBucketConfig = { |
| 25 | + maxTokens: 20, |
| 26 | + refillRate: 10, |
| 27 | + refillIntervalMs: 60_000, |
| 28 | +} |
| 29 | + |
| 30 | +function redirectToOnboarding(error?: AwsMarketplaceOnboardingError): NextResponse { |
| 31 | + const url = new URL(AWS_MARKETPLACE_ONBOARDING_PATH, getBaseUrl()) |
| 32 | + if (error) url.searchParams.set('error', error) |
| 33 | + return NextResponse.redirect(url, 303) |
| 34 | +} |
| 35 | + |
| 36 | +async function readRegistrationToken(request: NextRequest): Promise<string | null> { |
| 37 | + const mediaType = request.headers.get('content-type')?.split(';', 1)[0]?.trim().toLowerCase() |
| 38 | + if (mediaType !== 'application/x-www-form-urlencoded') return null |
| 39 | + let form: FormData |
| 40 | + try { |
| 41 | + form = await readFormDataWithLimit(request, { |
| 42 | + maxBytes: MAX_FORM_BYTES, |
| 43 | + label: 'AWS Marketplace registration', |
| 44 | + }) |
| 45 | + } catch { |
| 46 | + return null |
| 47 | + } |
| 48 | + const token = form.get('x-amzn-marketplace-token') |
| 49 | + const parsed = awsMarketplaceRegistrationFormSchema.safeParse({ |
| 50 | + 'x-amzn-marketplace-token': typeof token === 'string' ? token : undefined, |
| 51 | + }) |
| 52 | + return parsed.success ? parsed.data['x-amzn-marketplace-token'] : null |
| 53 | +} |
| 54 | + |
| 55 | +/** |
| 56 | + * The listing's fulfillment URL. AWS sends the buyer's browser here with a cross-site form POST, |
| 57 | + * so the request carries no Sim session and is authenticated only by the registration token, |
| 58 | + * which ResolveCustomer verifies. The response is always a 303 to the onboarding page, carrying |
| 59 | + * the claim cookie unless the license lapsed. The token is never logged. |
| 60 | + */ |
| 61 | +export const POST = withRouteHandler(async (request: NextRequest) => { |
| 62 | + const productCode = getAwsMarketplaceProductCode() |
| 63 | + if (!productCode) return NextResponse.json({ error: 'Not found' }, { status: 404 }) |
| 64 | + |
| 65 | + try { |
| 66 | + const rateLimited = await enforceIpRateLimit( |
| 67 | + 'aws-marketplace-register', |
| 68 | + request, |
| 69 | + REGISTER_RATE_LIMIT |
| 70 | + ) |
| 71 | + if (rateLimited) return redirectToOnboarding('unavailable') |
| 72 | + |
| 73 | + const token = await readRegistrationToken(request) |
| 74 | + if (!token) { |
| 75 | + logger.warn('AWS Marketplace registration arrived without a usable token') |
| 76 | + return redirectToOnboarding('invalid') |
| 77 | + } |
| 78 | + |
| 79 | + const outcome = await registerAwsMarketplaceBuyer(productCode, token) |
| 80 | + if (outcome.kind !== 'claimed') return redirectToOnboarding(outcome.kind) |
| 81 | + |
| 82 | + const response = redirectToOnboarding() |
| 83 | + response.headers.append('set-cookie', serializeClaimCookie(outcome.claimToken)) |
| 84 | + response.headers.set('Cache-Control', 'no-store') |
| 85 | + return response |
| 86 | + } catch (error) { |
| 87 | + logger.error('AWS Marketplace registration failed', { error: getErrorMessage(error) }) |
| 88 | + return redirectToOnboarding('unavailable') |
| 89 | + } |
| 90 | +}) |
| 91 | + |
| 92 | +/** A refresh, back button, or bookmark of the fulfillment URL lands on the onboarding page. */ |
| 93 | +export const GET = withRouteHandler(async () => { |
| 94 | + if (!getAwsMarketplaceProductCode()) |
| 95 | + return NextResponse.json({ error: 'Not found' }, { status: 404 }) |
| 96 | + return redirectToOnboarding() |
| 97 | +}) |
0 commit comments