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.

2.2 KB
Raw Blame
import { getSessionUser, authenticateBearer, extractBearer, hasScope } from '../_lib/auth.js';
import { cors, json, error, method, wrap, rateLimited } from '../_lib/http.js';
import { limits, clientIp } from '../_lib/rate-limit.js';
import { getMembershipCard, getReferredUsers, getReferralFunnel } from '../_lib/referrals.js';

// GET /api/users/referrals: the signed-in user's membership card payload:
// referral code (lazily minted if absent), referral count + lifetime earnings,
// signup position ("member #N"), and a derived score. Also returns a real,
// paginated per-referred-user breakdown (who signed up, when, revenue they
// generated, and the commission earned) so the affiliate dashboard can show an
// actionable referral table: not just a counter. Powers /dashboard/referrals.
//
// Query params (optional): ?limit (1-100, default 20) & ?offset (>=0) page the
// referred-user list, sorted by revenue generated (desc). ?funnel_days (1-365,
// default 30) sets the lookback for the `funnel` block, which reports the
// visit → signup → activation conversion recorded by POST /api/referral/visit.
export default wrap(async (req, res) => {
	if (cors(req, res, { methods: 'GET,OPTIONS', credentials: true })) return;
	if (!method(req, res, ['GET'])) return;

	const session = await getSessionUser(req);
	const bearer = session ? null : await authenticateBearer(extractBearer(req));
	if (!session && !bearer) return error(res, 401, 'unauthorized', 'sign in required');
	if (bearer && !hasScope(bearer.scope, 'profile'))
		return error(res, 403, 'insufficient_scope', 'requires profile scope');
	const userId = session?.id ?? bearer.userId;

	const rl = await limits.authedReadIp(clientIp(req));
	if (!rl.success) return rateLimited(res, rl);

	const card = await getMembershipCard(userId);
	if (!card) return error(res, 404, 'not_found', 'user not found');

	const url = new URL(req.url, 'http://localhost');
	const [referredUsers, funnel] = await Promise.all([
		getReferredUsers(userId, {
			limit: url.searchParams.get('limit'),
			offset: url.searchParams.get('offset'),
		}),
		getReferralFunnel(userId, { days: url.searchParams.get('funnel_days') }),
	]);

	return json(res, 200, { ...card, referred_users: referredUsers, funnel });
});