Skip to content

Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.

17.8 KB
Raw Blame
// GET /api/x402/vanity-premium
//   • no ?address        → browse the premium inventory (available patterns +
//                          difficulty-scaled prices). Public, no payment.
//   • ?address=<base58>  → buy that pre-ground address via x402. On payment the
//                          server reserves it, settles, and delivers the sealed
//                          key ONCE, then destroys the ciphertext (delete-after-
//                          reveal). The address is never served again.
//
// This is the SELL-FROM-STOCK tier: 4–5+ char brandable addresses ground ahead of
// time on batch CPU (workers/vanity-grinder) and held encrypted in
// vanity_inventory. It is separate from — and leaves untouched — the live $0.05
// grind tier (/api/x402/vanity, the vanity_grinder MCP tool), which grinds a
// fresh ≤3-char keypair per request.
//
// CUSTODY HONESTY (required, non-negotiable copy): the platform generated these
// keys. Every listing and every delivery tells the buyer plainly to use a bought
// address as a token MINT or to sweep assets to a self-generated wallet — never
// as a high-value treasury. See CUSTODY_NOTICE below.
//
// SECURITY: single-use delivery is enforced server-side in
// api/_lib/vanity-inventory-store.js (atomic status-guarded reveal). The
// plaintext key is NEVER logged and NEVER written to the x402 idempotency cache
// (the stored copy strips it, exactly like /api/x402/vanity). Optional
// sealTo=<X25519 pubkey> delivers the key sealed (ECIES) so plaintext never even
// appears in the response body.

import { wrap, cors, error } from '../_lib/http.js';
import {
	send402,
	verifyPayment,
	settlePayment,
	encodePaymentResponseHeader,
	buildExactRequirements,
	resolveResourceUrl,
	buildBazaarSchema,
} from '../_lib/x402-spec.js';
import { env } from '../_lib/env.js';
import { limits, clientIp } from '../_lib/rate-limit.js';
import {
	PAYMENT_IDENTIFIER,
	checkCache,
	claimSlotOrRespond,
	extractIdFromHeader,
	hashPaymentProof,
	hashRequestPayload,
	paymentIdentifierExtension,
	releaseSlot,
	storeResponse,
	writeCachedResponse,
	writeConflict,
} from '../_lib/x402/payment-identifier-server.js';
import { withService } from '../_lib/x402/bazaar-helpers.js';
import {
	listAvailable,
	countAvailable,
	getPublicItem,
	inventoryStats,
	reserveForPurchase,
	peekReservedSecret,
	reserveAndReveal,
	isDbUnavailableError,
} from '../_lib/vanity-inventory-store.js';
import { openSecret } from '../_lib/vanity-vault.js';
import {
	sealToRecipient,
	parseX25519Key,
	SEALED_ENVELOPE_SCHEME,
} from '../../src/solana/vanity/sealed-envelope.js';

const ROUTE = '/api/x402/vanity-premium';
const PUBLIC_ORIGIN = env.APP_ORIGIN || 'https://three.ws';

// The required custody-honesty disclosure. Shipped in every listing response and
// every delivery payload, and mirrored in the listing UI.
export const CUSTODY_NOTICE =
	'This address and its key were GENERATED BY three.ws, not by you. For high-value use, ' +
	'treat it as a TOKEN MINT ADDRESS or sweep any assets to a wallet you generated yourself — ' +
	'do not use it as a long-term treasury. The key is delivered to you exactly once and its ' +
	'stored ciphertext is destroyed on delivery (delete-after-reveal), so three.ws cannot ' +
	'recover or re-deliver it afterward. Import it into a wallet immediately and, for anything ' +
	'of value, move funds to self-generated custody.';

const ROUTE_DESCRIPTION =
	'three.ws Premium Vanity Inventory — buy a pre-ground Solana address with a long (4–5+ char) ' +
	'brandable prefix, delivered instantly from stock. Browse available patterns and prices with a ' +
	'plain GET; buy one with GET ?address=<base58> via x402 (USDC on Base or Solana). Price scales ' +
	'with grind difficulty ($1–$50). The key is delivered ONCE and its ciphertext is destroyed on ' +
	'delivery. Optional sealTo=<X25519 public key> seals the key to you so plaintext never appears ' +
	'in the response. CUSTODY: keys are platform-generated — use as a token mint or sweep to ' +
	'self-generated custody, not as a treasury.';

// ── Listing (public, no payment) ─────────────────────────────────────────────
async function handleListing(req, res) {
	const q = req.query || {};
	const prefix = typeof q.prefix === 'string' ? q.prefix.trim() : undefined;
	const tier = typeof q.tier === 'string' ? q.tier.trim() : undefined;
	const sort = ['rarity', 'price', 'new'].includes(q.sort) ? q.sort : 'rarity';
	const limit = Math.min(Math.max(1, Number(q.limit) || 60), 200);
	const offset = Math.max(0, Number(q.offset) || 0);

	let items = [];
	let stats = { available: 0, sold: 0, total: 0, minPrice: 0, maxPrice: 0, tiers: 0 };
	let matching = 0;
	try {
		[items, stats, matching] = await Promise.all([
			listAvailable({ prefix, tier, sort, limit, offset }),
			inventoryStats(),
			countAvailable({ prefix, tier }),
		]);
	} catch (err) {
		if (isDbUnavailableError(err)) {
			return error(res, 503, 'inventory_unavailable', 'inventory store temporarily unavailable — retry shortly');
		}
		return error(res, 500, 'internal_error', err.message);
	}

	res.setHeader('cache-control', 'public, max-age=15, stale-while-revalidate=60');
	res.setHeader('content-type', 'application/json; charset=utf-8');
	res.end(
		JSON.stringify({
			route: ROUTE,
			custodyNotice: CUSTODY_NOTICE,
			stats,
			priceRange: { minUsd: stats.minPrice, maxUsd: stats.maxPrice },
			count: items.length,
			// Paging over the full shelf: `matching` counts every available row this
			// filter selects, so a client knows when it is looking at a partial page
			// instead of assuming `count` is the whole inventory.
			matching,
			limit,
			offset,
			hasMore: offset + items.length < matching,
			items: items.map((it) => ({
				...it,
				buyUrl: `${PUBLIC_ORIGIN}${ROUTE}?address=${encodeURIComponent(it.address)}`,
				explorerUrl: `https://solscan.io/account/${it.address}`,
			})),
			purchase: {
				how: `GET ${ROUTE}?address=<base58> with an x402 payment (USDC on Base or Solana).`,
				optionalSealTo: 'Add &sealTo=<X25519 public key> to receive the key sealed to you (plaintext never in the response).',
			},
		}),
	);
}

function buildRequirements(resourceUrl, priceAtomics) {
	return buildExactRequirements(resourceUrl, priceAtomics);
}

// Build the buyer-facing delivery payload from the decrypted secret bundle. The
// bundle is the JSON workers/vanity-grinder sealed at grind time:
//   { format, address, secretKeyBase58, secretKey:[64], mnemonic?, ... }
function shapeDelivery(item, bundle) {
	return {
		address: item.address,
		prefix: item.prefix,
		suffix: item.suffix,
		ignoreCase: item.ignoreCase,
		patternLabel: item.patternLabel,
		format: bundle.format || item.format,
		rarityTier: item.rarityTier,
		rarityBits: item.rarityBits,
		rarityScore: item.rarityScore,
		difficultyAttempts: item.difficultyAttempts,
		priceUsd: item.priceUsd,
		network: 'solana',
		explorerUrl: `https://solscan.io/account/${item.address}`,
		secretKeyBase58: bundle.secretKeyBase58,
		secretKey: bundle.secretKey,
		mnemonic: bundle.mnemonic || null,
		wordCount: bundle.wordCount || null,
		derivationPath: bundle.derivationPath || null,
		delivery: 'once',
		custodyNotice: CUSTODY_NOTICE,
		_secretWarning:
			'secretKeyBase58/secretKey (and mnemonic if present) are a REAL Solana key delivered ONCE. ' +
			'The stored ciphertext was destroyed on this delivery — three.ws cannot re-send it. Import it now.',
	};
}

// Seal the secret bundle to the buyer's X25519 key so plaintext never lands in
// the response body / any proxy log. Mirrors /api/x402/vanity's sealSecret.
async function sealDelivery(delivery, sealTo) {
	const bundle = {
		format: delivery.format,
		secretKeyBase58: delivery.secretKeyBase58,
		secretKey: delivery.secretKey,
		mnemonic: delivery.mnemonic,
		wordCount: delivery.wordCount,
		derivationPath: delivery.derivationPath,
	};
	const sealedSecret = await sealToRecipient(JSON.stringify(bundle), sealTo);
	const { secretKeyBase58, secretKey, mnemonic, wordCount, derivationPath, ...clear } = delivery;
	void secretKeyBase58; void secretKey; void mnemonic; void wordCount; void derivationPath;
	return {
		...clear,
		sealed: true,
		sealedScheme: SEALED_ENVELOPE_SCHEME,
		sealedContentType: 'application/json',
		sealedFields: Object.keys(bundle),
		sealedSecret,
	};
}

function buildBazaar() {
	return {
		discoverable: true,
		info: {
			input: { type: 'http', method: 'GET', queryParams: { address: '<base58 from the listing>' } },
			output: { type: 'json', example: { address: 'PUMPExample…', secretKeyBase58: '<delivered once>', delivery: 'once' } },
		},
		schema: buildBazaarSchema({
			method: 'GET',
			queryParamsSchema: {
				$schema: 'https://json-schema.org/draft/2020-12/schema',
				type: 'object',
				properties: {
					address: { type: 'string', description: 'A Base58 address from the premium inventory listing.' },
					sealTo: { type: 'string', description: 'Optional X25519 public key to seal the delivered key to.' },
				},
			},
			outputSchema: {
				$schema: 'https://json-schema.org/draft/2020-12/schema',
				type: 'object',
				required: ['address', 'delivery', 'custodyNotice'],
				properties: {
					address: { type: 'string' },
					secretKeyBase58: { type: 'string', description: 'Delivered once; ciphertext destroyed on delivery.' },
					secretKey: { type: 'array', items: { type: 'integer' }, minItems: 64, maxItems: 64 },
					delivery: { type: 'string', enum: ['once'] },
					custodyNotice: { type: 'string' },
				},
			},
		}),
	};
}

// ── Purchase (x402) ──────────────────────────────────────────────────────────
async function handlePurchase(req, res, address) {
	let sealTo = null;
	const q = req.query || {};
	if (typeof q.sealTo === 'string' && q.sealTo.trim()) {
		try {
			sealTo = q.sealTo.trim();
			parseX25519Key(sealTo, 'sealTo');
		} catch (err) {
			return error(res, err.status || 400, err.code || 'validation_error', err.message);
		}
	}

	// Look up the item so we can price the 402 challenge for THIS exact address and
	// reject an unknown/sold address before the buyer pays.
	let item;
	try {
		item = await getPublicItem(address);
	} catch (err) {
		if (isDbUnavailableError(err)) return error(res, 503, 'inventory_unavailable', 'inventory store temporarily unavailable');
		return error(res, 500, 'internal_error', err.message);
	}
	if (!item) return error(res, 404, 'not_found', `no inventory item for address ${address}`);
	if (item.status !== 'available') {
		return error(res, 409, 'unavailable', `address ${address} is ${item.status} — pick another from the listing`);
	}

	const resourceUrl = resolveResourceUrl(req, ROUTE);
	const priceAtomics = Math.round(item.priceUsd * 1_000_000);
	const requirements = buildRequirements(resourceUrl, priceAtomics);
	const service = withService({
		serviceName: 'three.ws Premium Vanity Inventory',
		tags: ['solana', 'vanity', 'wallet', 'address', 'premium', 'inventory'],
	});
	const challenge = {
		resourceUrl,
		accepts: requirements,
		description: `${ROUTE_DESCRIPTION} — buying ${item.patternLabel} (${item.rarityTier}) at $${item.priceUsd}.`,
		bazaar: buildBazaar(),
		extensions: { [PAYMENT_IDENTIFIER]: paymentIdentifierExtension(false) },
		serviceName: service.serviceName,
		tags: service.tags,
		iconUrl: service.iconUrl,
		item: { address: item.address, patternLabel: item.patternLabel, rarityTier: item.rarityTier, priceUsd: item.priceUsd },
		custodyNotice: CUSTODY_NOTICE,
	};

	const paymentHeader = req.headers['x-payment'] || req.headers['payment-signature'];
	if (!paymentHeader) return send402(res, challenge);

	// Idempotency / replay: a retried payment returns the SAME (already-delivered)
	// stored response — which by contract has the secret STRIPPED — instead of
	// re-charging or double-delivering.
	const clientPaymentId = extractIdFromHeader(paymentHeader);
	const payloadHash = hashRequestPayload({ method: req.method, url: req.url, body: null });
	const paymentHash = hashPaymentProof(paymentHeader);
	const paymentId = clientPaymentId || (paymentHash ? `proof:${paymentHash}` : null);
	if (!paymentId) return error(res, 400, 'payment_id_required', 'could not derive a payment id from the payment proof');

	const lookup = await checkCache({ route: ROUTE, paymentId, payloadHash, paymentHash });
	if (lookup.kind === 'hit') return writeCachedResponse(res, lookup.entry);
	if (lookup.kind === 'conflict') {
		return writeConflict(res, {
			route: ROUTE,
			attemptedHash: lookup.attemptedHash,
			existingHash: lookup.existingHash,
			reason: lookup.reason,
		});
	}

	// Close the check-then-act window: N concurrent requests carrying the same
	// payment could all miss the cache, all verify, and all race reserveForPurchase
	// (the loser strands a reservation on a payment that never settles). The NX
	// claim admits exactly one; the rest are answered inside claimSlotOrRespond.
	const ownsReservation = await claimSlotOrRespond({ res, route: ROUTE, paymentId, payloadHash, paymentHash });
	if (!ownsReservation) return;

	// 1) verify the payment.
	let verified;
	try {
		verified = await verifyPayment({ paymentHeader, requirements });
	} catch (err) {
		if (ownsReservation) await releaseSlot({ route: ROUTE, paymentId });
		if (err.status === 402) return send402(res, { ...challenge, error: err.message });
		return error(res, err.status || 502, err.code || 'verify_failed', err.message);
	}

	// 2) reserve the item for THIS payment (atomic available→reserved). If someone
	// bought it between the 402 and now, we bail BEFORE settling — buyer not charged.
	const purchaser = verified?.payer || verified?.from || clientPaymentId || 'x402';
	let reservation;
	try {
		reservation = await reserveForPurchase(address, { paymentId, purchaser });
	} catch (err) {
		if (ownsReservation) await releaseSlot({ route: ROUTE, paymentId });
		return error(res, 502, 'reserve_failed', err.message);
	}
	if (!reservation.ok) {
		if (ownsReservation) await releaseSlot({ route: ROUTE, paymentId });
		const code = reservation.reason === 'not_found' ? 404 : 409;
		return error(res, code, 'unavailable', `address ${address} could not be reserved (${reservation.reason}) — it may have just sold`);
	}

	// 3) prove we can DECRYPT before charging (KMS reachability etc.). Non-
	// destructive peek — if this fails we have not settled and the ciphertext is
	// intact, so the buyer is not charged and can retry.
	let bundle;
	try {
		const peek = await peekReservedSecret(address, { paymentId });
		if (!peek.ok) {
			if (ownsReservation) await releaseSlot({ route: ROUTE, paymentId });
			return error(res, 500, 'reveal_failed', `secret not retrievable (${peek.reason})`);
		}
		bundle = JSON.parse(await openSecret(peek.ciphertext, peek.scheme));
	} catch (err) {
		// Decrypt/KMS failure BEFORE settle: don't charge. Reservation is left in
		// place (buyer's payment can be retried against the same reserved row).
		if (ownsReservation) await releaseSlot({ route: ROUTE, paymentId });
		return error(res, 502, 'decrypt_failed', 'could not decrypt the stored key — not charged, retry shortly');
	}

	// 4) settle the payment.
	let settled;
	try {
		settled = await settlePayment({ verified });
	} catch (err) {
		if (ownsReservation) await releaseSlot({ route: ROUTE, paymentId });
		return error(res, err.status || 502, err.code || 'settle_failed', err.message);
	}

	// 5) one-shot reveal: flip to revealed and DESTROY the ciphertext atomically.
	// We already hold the plaintext from step 3, so even a transient error here
	// doesn't cost the buyer the key — but a normal success is what destroys it.
	try {
		await reserveAndReveal(address, { paymentId });
	} catch (err) {
		// Non-fatal to delivery (buyer paid, we have the key) but log the state drift.
		console.error('[vanity-premium] reveal/destroy after settle failed', err?.message || err);
	}

	// 6) deliver once.
	let delivery = shapeDelivery(item, bundle);
	if (sealTo) delivery = await sealDelivery(delivery, sealTo);

	const paymentResponseHeader = encodePaymentResponseHeader(settled);
	const contentType = 'application/json; charset=utf-8';
	const body = JSON.stringify(delivery);
	res.setHeader('x-payment-response', paymentResponseHeader);
	res.setHeader('cache-control', 'no-store');
	res.setHeader('content-type', contentType);
	res.end(body);

	// Cache a SECRET-FREE copy for replay: a retried payment gets the public
	// metadata + an explicit "already delivered" marker, never the key again.
	let storedBody = body;
	if (!delivery.sealed) {
		const { secretKeyBase58, secretKey, mnemonic, ...publicMeta } = delivery;
		void secretKeyBase58; void secretKey; void mnemonic;
		storedBody = JSON.stringify({
			...publicMeta,
			secret_omitted_from_cache: true,
			note: 'The purchased key was delivered once in the original response and the ciphertext was destroyed. It is never stored or re-served.',
		});
	}
	try {
		await storeResponse({
			route: ROUTE,
			paymentId,
			payloadHash,
			paymentHash,
			status: 200,
			body: storedBody,
			contentType,
			paymentResponseHeader,
		});
	} catch (err) {
		console.error('[vanity-premium] idempotency store failed (non-fatal)', err?.message || err);
	}
}

export default wrap(async (req, res) => {
	if (cors(req, res, { methods: 'GET,OPTIONS', origins: '*' })) return;
	if (req.method !== 'GET') {
		res.setHeader('allow', 'GET');
		return error(res, 405, 'method_not_allowed', 'use GET');
	}

	const rl = await limits.publicIp(clientIp(req));
	if (!rl.success) {
		res.setHeader('retry-after', String(rl.retryAfter ?? 1));
		return error(res, 429, 'rate_limited', 'slow down');
	}

	const address = typeof req.query?.address === 'string' ? req.query.address.trim() : '';
	if (!address) return handleListing(req, res);
	// Cheap shape guard before any DB/payment work.
	if (!/^[1-9A-HJ-NP-Za-km-z]{32,44}$/.test(address)) {
		return error(res, 400, 'validation_error', 'address must be a Base58 Solana public key');
	}
	return handlePurchase(req, res, address);
});