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.

22.5 KB
Raw Blame
// Auth primitives: password hashing, JWTs, session cookies, bearer extraction.

import bcrypt from 'bcryptjs';
import { SignJWT, jwtVerify, createRemoteJWKSet } from 'jose';
import { env } from './env.js';
import { sql } from './db.js';
import { logAudit } from './audit.js';
import { randomToken, sha256, hmacSha256, constantTimeEquals } from './crypto.js';
import { recordDailyActivity } from './streaks.js';
import { clientIp } from './rate-limit.js';
import { effectiveKeyScope, withImpliedScopes } from './key-scopes.js';
import { getCachedKeyRow, rememberKeyRow, keyRevokedSinceCached, shouldTouchLastUsed, invalidateApiKey } from './api-key-cache.js';
import { ipAllowed } from './ip-allowlist.js';
import { currentRequest } from './request-context.js';

const ACCESS_TTL_SEC = 60 * 60; // 1h access tokens
const REFRESH_TTL_SEC = 60 * 60 * 24 * 30; // 30d refresh tokens
const SESSION_TTL_SEC = 60 * 60 * 24 * 30; // 30d browser sessions
const SESSION_REFRESH_WINDOW_SEC = 60 * 60 * 24 * 7; // rotate when < 7d remain

// Lazy: env.JWT_SECRET throws if unset, so defer encoding until first use.
let _jwtKey;
function jwtKey() {
	if (!_jwtKey) _jwtKey = new TextEncoder().encode(env.JWT_SECRET);
	return _jwtKey;
}

// ── passwords ────────────────────────────────────────────────────────────────
export async function hashPassword(plain) {
	return bcrypt.hash(plain, env.PASSWORD_ROUNDS);
}
export async function verifyPassword(plain, hash) {
	if (!hash) return false;
	return bcrypt.compare(plain, hash);
}

// ── access tokens (JWT) ──────────────────────────────────────────────────────
export async function mintAccessToken({ userId, clientId, scope, resource, tokenUse = 'access' }) {
	const now = Math.floor(Date.now() / 1000);
	return new SignJWT({ scope, client_id: clientId, resource, token_use: tokenUse })
		.setProtectedHeader({ alg: 'HS256', kid: env.JWT_KID, typ: 'JWT' })
		.setIssuer(env.ISSUER)
		.setSubject(userId)
		.setAudience(resource || env.MCP_RESOURCE)
		.setIssuedAt(now)
		.setExpirationTime(now + ACCESS_TTL_SEC)
		.setJti(randomToken(16))
		.sign(jwtKey());
}

export async function verifyAccessToken(token, { audience } = {}) {
	// Passing `issuer` to jose.jwtVerify enforces the `iss` claim equals
	// env.ISSUER and throws otherwise — no separate check needed in
	// authenticateBearer(), which treats any throw here as auth failure.
	const { payload } = await jwtVerify(token, jwtKey(), {
		issuer: env.ISSUER,
		audience: audience || env.MCP_RESOURCE,
		algorithms: ['HS256'],
	});
	return payload;
}

// ── refresh tokens (opaque, hashed at rest) ──────────────────────────────────
export async function issueRefreshToken({ userId, clientId, scope, resource }) {
	const secret = randomToken(32);
	const hash = await sha256(secret);
	const [row] = await sql`
		insert into oauth_refresh_tokens (token_hash, client_id, user_id, scope, resource, expires_at)
		values (${hash}, ${clientId}, ${userId}, ${scope}, ${resource ?? null}, now() + ${`${REFRESH_TTL_SEC} seconds`}::interval)
		returning id
	`;
	return { token: secret, id: row.id };
}

export async function rotateRefreshToken({ oldSecret, clientId, narrowScope }) {
	const hash = await sha256(oldSecret);
	const rows = await sql`
		select id, user_id, scope, resource, expires_at, revoked_at
		from oauth_refresh_tokens
		where token_hash = ${hash} and client_id = ${clientId}
		limit 1
	`;
	const row = rows[0];
	if (!row) throw Object.assign(new Error('invalid_grant'), { status: 400 });
	const reuse = async () => {
		// Reuse detected: revoke the whole chain for this user+client.
		await sql`update oauth_refresh_tokens set revoked_at = now()
		          where user_id = ${row.user_id} and client_id = ${clientId} and revoked_at is null`;
		throw Object.assign(new Error('invalid_grant'), {
			status: 400,
			code: 'refresh_reuse_detected',
		});
	};
	if (row.revoked_at) await reuse();
	if (new Date(row.expires_at) < new Date()) {
		throw Object.assign(new Error('invalid_grant'), { status: 400, code: 'refresh_expired' });
	}
	// Resolved before the claim so a rejected scope request does not burn the token.
	// Bind the rotated refresh token to the narrowed scope (RFC 6749 §6 allows a
	// subset). Without this, a caller could re-widen back to the full scope on
	// the next rotation by omitting `scope`.
	const effectiveScope = typeof narrowScope === 'function' ? narrowScope(row.scope) : row.scope;
	// Claim the token before issuing its successor, in one conditional UPDATE.
	// Two simultaneous redemptions of the same token cannot both win it: the
	// loser gets zero rows and is treated as reuse, so the chain never forks.
	const claimed = await sql`update oauth_refresh_tokens set revoked_at = now(), last_used_at = now()
	          where id = ${row.id} and revoked_at is null returning id`;
	if (!claimed.length) await reuse();
	const next = await issueRefreshToken({
		userId: row.user_id,
		clientId,
		scope: effectiveScope,
		resource: row.resource,
	});
	await sql`update oauth_refresh_tokens set replaced_by = ${next.id} where id = ${row.id}`;
	return { next, userId: row.user_id, scope: effectiveScope, resource: row.resource };
}

export async function revokeRefreshToken(secret, clientId) {
	const hash = await sha256(secret);
	const [row] = await sql`update oauth_refresh_tokens set revoked_at = now()
	          where token_hash = ${hash} and client_id = ${clientId} and revoked_at is null
	          returning id, user_id`;
	if (row) {
		// The client ended its own grant (RFC 7009): the access tokens already in
		// flight for this user and client stop with it, same as Connected apps.
		await sql`
			insert into oauth_client_revocations (user_id, client_id, revoked_at)
			values (${row.user_id}, ${clientId}, now())
			on conflict (user_id, client_id) do update set revoked_at = excluded.revoked_at
		`;
		logAudit({
			userId: row.user_id,
			action: 'revoke_oauth_token',
			resourceId: row.id,
			meta: { client_id: clientId },
		});
	}
}

// ── browser sessions (cookie auth for the site itself) ──────────────────────
// __Host- prefix requires Path=/; Secure; no Domain — browser enforces cookie
// can't be set by any subdomain, eliminating subdomain cookie injection.
const SESSION_COOKIE = '__Host-sid';
// The unprefixed legacy name is never read (any sibling subdomain can plant it,
// which would allow session fixation). It is only cleared on logout so old
// browsers drop it.
const LEGACY_COOKIE = 'sid';

function readSessionCookie(req) {
	const cookie = req.headers.cookie || '';
	const m = cookie.match(/(?:^|;\s*)__Host-sid=([^;]+)/);
	return m ? decodeURIComponent(m[1]) : null;
}

export function hasSessionCookie(req) {
	return readSessionCookie(req) !== null;
}

/**
 * Issue a new session and revoke the old one. Returns the new plaintext token.
 * @param {{ currentSid: string, userId: string, userAgent: string|null, ip: string|null }} opts
 */
export async function rotateSession({ currentSid, userId, userAgent, ip }) {
	const newSecret = await createSession({ userId, userAgent, ip });
	await sql`update sessions set revoked_at = now() where id = ${currentSid}`;
	return newSecret;
}

export async function createSession({ userId, userAgent, ip, recordActivity = true }) {
	const secret = randomToken(32);
	const hash = await sha256(secret);
	await sql`
		insert into sessions (user_id, token_hash, user_agent, ip, expires_at)
		values (${userId}, ${hash}, ${userAgent ?? null}, ${ip ?? null}, now() + ${`${SESSION_TTL_SEC} seconds`}::interval)
	`;
	// A login (or the once-a-day silent session rotation in getSessionUser)
	// is a qualifying activity for the cross-surface streak. Fire-and-forget —
	// a streak-tracking hiccup must never block sign-in.
	//
	// Machine callers that mint a session purely to reach an owner-scoped
	// endpoint on the user's behalf (the launcher claimer's fee sweep, and any
	// future background sweep) pass recordActivity:false. A cron running on a
	// timer is not the owner showing up, and counting it would keep those
	// owners' streaks alive forever without them ever opening the site.
	if (recordActivity) recordDailyActivity(userId).catch(() => {});
	return secret;
}

/**
 * Revoke a session by its plaintext token. Machine callers that mint a
 * short-lived session use this to leave no usable credential behind once their
 * sweep is done, instead of letting it sit valid for the full session TTL.
 */
export async function revokeSessionToken(token) {
	if (!token) return;
	const hash = await sha256(token);
	await sql`update sessions set revoked_at = now() where token_hash = ${hash}`;
}

export function sessionCookie(token, { clear = false } = {}) {
	if (clear) {
		// Clear both the current and legacy cookie names so logout fully drops session.
		return [
			`${SESSION_COOKIE}=; Path=/; HttpOnly; Secure; SameSite=Lax; Max-Age=0`,
			`${LEGACY_COOKIE}=; Path=/; HttpOnly; Secure; SameSite=Lax; Max-Age=0`,
		];
	}
	return `${SESSION_COOKIE}=${token}; Path=/; HttpOnly; Secure; SameSite=Lax; Max-Age=${SESSION_TTL_SEC}`;
}

/**
 * Resolve the session user from the request cookie.
 * When `res` is provided, silently rotates the session cookie if it is within
 * the refresh window (last seen > 1 day ago and expiring within 7 days).
 * Returns the user object including `sid` (session UUID) for callers that need it.
 *
 * @param {import('http').IncomingMessage} req
 * @param {import('http').ServerResponse} [res]
 */
export async function getSessionUser(req, res) {
	const token = readSessionCookie(req);
	if (!token) return null;
	const hash = await sha256(token);
	const rows = await sql`
		select s.id as sid, s.last_seen_at, s.expires_at,
		       u.id, u.email, u.display_name, u.username, u.plan, u.avatar_url, u.wallet_address, u.is_admin, u.referral_code
		from sessions s join users u on u.id = s.user_id
		where s.token_hash = ${hash}
		  and s.revoked_at is null
		  and s.expires_at > now()
		  and u.deleted_at is null
		limit 1
	`;
	if (!rows[0]) return null;

	const { last_seen_at, expires_at, ...userFields } = rows[0];

	// Touch last_seen best-effort; don't block the request on a write.
	sql`update sessions set last_seen_at = now() where id = ${userFields.sid}`.catch(() => {});

	// Rolling refresh: rotate if last seen > 1 day ago and expiring within 7 days.
	if (res) {
		const seenMs = last_seen_at ? new Date(last_seen_at).getTime() : 0;
		const expiresMs = expires_at ? new Date(expires_at).getTime() : 0;
		const nowMs = Date.now();
		if (nowMs - seenMs > 86_400_000 && expiresMs - nowMs < SESSION_REFRESH_WINDOW_SEC * 1000) {
			const ua = req.headers['user-agent'] || null;
			const ip = clientIp(req);
			rotateSession({ currentSid: userFields.sid, userId: userFields.id, userAgent: ua, ip })
				.then((newToken) => {
					try {
						const existing = res.getHeader('set-cookie') || [];
						const arr = Array.isArray(existing) ? existing : [existing];
						res.setHeader('set-cookie', [...arr, sessionCookie(newToken)]);
					} catch {
						// header already sent — rotation missed this request, next one will retry
					}
				})
				.catch(() => {});
		}
	}

	return userFields; // includes sid alongside u.id, email, display_name, plan, avatar_url
}

export async function destroySession(req) {
	await revokeSessionToken(readSessionCookie(req));
}

// CSRF token bound to the session cookie value. Because the cookie is HttpOnly,
// an attacker's JS can't read it and therefore can't forge a matching token.
export async function csrfTokenFor(req) {
	const token = readSessionCookie(req);
	if (!token) return null;
	return hmacSha256(env.JWT_SECRET, `csrf:${token}`);
}

export async function verifyCsrfToken(req, submitted) {
	if (!submitted) return false;
	const expected = await csrfTokenFor(req);
	if (!expected) return false;
	return constantTimeEquals(expected, String(submitted));
}

// Reject cross-site POSTs by requiring Origin (preferred) or Referer to match
// the configured APP_ORIGIN. Call before honoring state-changing form posts.
export function isSameSiteOrigin(req) {
	const origin = req.headers.origin;
	if (origin) return origin === env.APP_ORIGIN;
	const referer = req.headers.referer;
	if (!referer) return false;
	try {
		return new URL(referer).origin === env.APP_ORIGIN;
	} catch {
		return false;
	}
}

// ── bearer extraction (OAuth access tokens OR API keys) ─────────────────────
export function extractBearer(req) {
	const h = req.headers.authorization || '';
	if (!h.toLowerCase().startsWith('bearer ')) return null;
	return h.slice(7).trim();
}

// Access tokens are stateless JWTs, so revoking a connected app also records a
// cutoff per (user, client). A token issued at or before the cutoff is dead on
// its next use; a token minted after the person re-authorizes the app is not.
export async function oauthGrantRevoked(payload) {
	const rows = await sql`
		select 1 from oauth_client_revocations
		where user_id = ${payload.sub} and client_id = ${payload.client_id}
			and revoked_at >= to_timestamp(${payload.iat})
		limit 1
	`;
	return rows.length > 0;
}

// Revoke everything one client holds for one user: its refresh tokens and, via
// the cutoff row, every access token already in flight. Returns how many
// refresh tokens were revoked.
export async function revokeClientGrant({ userId, clientId }) {
	const revoked = await sql`
		update oauth_refresh_tokens set revoked_at = now()
		where user_id = ${userId} and client_id = ${clientId} and revoked_at is null
		returning id
	`;
	await sql`
		insert into oauth_client_revocations (user_id, client_id, revoked_at)
		values (${userId}, ${clientId}, now())
		on conflict (user_id, client_id) do update set revoked_at = excluded.revoked_at
	`;
	return revoked.length;
}

// The client id the Walk Avatar extension token carries (api/auth/extension-token.js).
// That token is a stateless JWT with no refresh-token row, so the cutoff row
// written for it here is the only way to kill one already handed out.
export const WALK_EXTENSION_CLIENT_ID = 'walk-extension';

// Cut off every non-session credential an account holds: a cutoff for every
// OAuth client it granted (plus the walk extension) so access tokens in flight
// die on next use, every refresh token, and, unless `includeApiKeys` is false,
// every API key (evicted from every instance's key cache). Sessions are the
// caller's to revoke. Account deletion and password reset pass everything;
// a routine logout-everywhere keeps long-lived keys unless asked.
// Returns how many API keys were revoked.
export async function revokeAccountCredentials({ userId, includeApiKeys = true }) {
	await sql`
		insert into oauth_client_revocations (user_id, client_id, revoked_at)
		select distinct user_id, client_id, now() from oauth_refresh_tokens where user_id = ${userId}
		union
		select ${userId}::uuid, ${WALK_EXTENSION_CLIENT_ID}, now()
		on conflict (user_id, client_id) do update set revoked_at = excluded.revoked_at
	`;
	await sql`update oauth_refresh_tokens set revoked_at = now() where user_id = ${userId} and revoked_at is null`;
	if (!includeApiKeys) return 0;
	const keys = await sql`update api_keys set revoked_at = now() where user_id = ${userId} and revoked_at is null returning id`;
	await Promise.all(keys.map((k) => invalidateApiKey(k.id)));
	return keys.length;
}

// Returns { userId, scope, source: 'oauth'|'apikey', clientId?, apiKeyId? } or null.
//
// `ip` is the caller's address, used for the key's IP allowlist. Callers that
// only hold a token (most of them) leave it out and the address is read from
// the request context server/index.mjs opens around every API dispatch, so an
// allowlisted key is enforced on every route, not only the ones that pass it.
export async function authenticateBearer(token, { audience, ip } = {}) {
	if (!token) return null;
	// API keys are prefixed with `sk_live_` (or `sk_test_`) — short-circuit.
	if (token.startsWith('sk_live_') || token.startsWith('sk_test_')) {
		const hash = await sha256(token);
		let row = getCachedKeyRow(hash);
		if (row === undefined) {
			const rows = await sql`
				select id, user_id, scope, preset, expires_at, revoked_at, ip_allowlist, overlap_until
				from api_keys where token_hash = ${hash}
				  and exists (select 1 from users u where u.id = api_keys.user_id and u.deleted_at is null)
				limit 1
			`;
			row = rows[0] ?? null;
			rememberKeyRow(hash, row);
		} else if (row && (await keyRevokedSinceCached(row.id))) {
			// Revoked on this or another instance since the row was cached: the
			// cache window must never outlive a revoke (api-key-cache.js).
			return null;
		}
		if (!row || row.revoked_at) return null;
		const now = new Date();
		if (row.expires_at && new Date(row.expires_at) < now) return null;
		// A rotated key keeps working through its overlap window, then stops.
		if (row.overlap_until && new Date(row.overlap_until) < now) return null;
		const ctxReq = ip ? null : currentRequest();
		const callerIp = ip ?? (ctxReq ? clientIp(ctxReq) : null);
		if (Array.isArray(row.ip_allowlist) && row.ip_allowlist.length && !ipAllowed(callerIp, row.ip_allowlist)) return null;
		if (shouldTouchLastUsed(row.id)) await sql`update api_keys set last_used_at = now() where id = ${row.id}`;
		// Coarse scopes expand to the fine ones every route checks, and a
		// connector key is stripped of every spend-capable scope (key-scopes.js).
		const { scope, connector } = effectiveKeyScope(row);
		return { userId: row.user_id, scope, source: 'apikey', apiKeyId: row.id, ...(connector ? { connector: true } : {}) };
	}
	// Otherwise treat as JWT access token.
	try {
		const payload = await verifyAccessToken(token, { audience });
		// Only ACCESS tokens authorize API calls. Refresh tokens are opaque (never
		// JWTs) so this is belt-and-suspenders, but rejecting any non-'access'
		// token_use prevents a future token type (e.g. an id/refresh JWT) from
		// being replayed against resource endpoints.
		if (payload.token_use !== 'access') return null;
		if (payload.client_id && await oauthGrantRevoked(payload)) return null;
		return {
			userId: payload.sub,
			scope: payload.scope || '',
			source: 'oauth',
			clientId: payload.client_id,
		};
	} catch {
		return null;
	}
}

// Resolve the request's user from a session cookie OR a bearer credential
// (OAuth access token / API key). Returns the full user object for cookie
// callers (same shape as getSessionUser) or a minimal { id, source, scope } for
// bearer callers; null when neither authenticates. Use in account-scoped routes
// that must serve both the browser (cookie) and machine clients / MCP servers
// (Authorization: Bearer …). CSRF is enforced separately and self-exempts bearer.
export async function getRequestUser(req, res) {
	const session = await getSessionUser(req, res);
	if (session) return session;
	const bearer = await authenticateBearer(extractBearer(req), { ip: clientIp(req) });
	if (bearer) return { id: bearer.userId, source: 'bearer', scope: bearer.scope || '', ...(bearer.connector ? { connector: true } : {}) };
	return null;
}

// ── Privy token verification (JWKS) ─────────────────────────────────────────
// Lazy singleton — the JWKS set caches the remote keyset and handles rotation
// automatically; it is only created on first call so imports don't fail when
// PRIVY_APP_ID is unset in environments that don't use Privy.
let _privyJWKS;
function privyJWKS() {
	if (!_privyJWKS) {
		const endpoint = env.PRIVY_JWKS_ENDPOINT;
		if (!endpoint) throw new Error('Missing required env var: PRIVY_JWKS_ENDPOINT (or VITE_PRIVY_APP_ID)');
		// cooldownDuration throttles refetches when an unknown `kid` is seen
		// (rotation), so a burst of requests during a key rotation triggers at
		// most one upstream fetch instead of one per request.
		_privyJWKS = createRemoteJWKSet(new URL(endpoint), { cooldownDuration: 30_000 });
	}
	return _privyJWKS;
}

// Verify a Privy access token issued by the Privy auth service.
// Returns the JWT payload on success; throws on invalid/expired tokens.
// payload.sub is the user's Privy DID (e.g. "did:privy:clxxx...").
// clockTolerance absorbs small skew between Privy's clock and ours so a freshly
// minted token isn't rejected as "not yet valid".
export async function verifyPrivyToken(token) {
	if (!token) throw new Error('missing token');
	const { payload } = await jwtVerify(token, privyJWKS(), {
		issuer: 'privy.io',
		audience: env.PRIVY_APP_ID,
		clockTolerance: 30,
	});
	return payload;
}

// Privy sends its access token as the `privy-id-token` header, an
// Authorization: Bearer, or the `privy-token` cookie (in that preference order).
// Returns the raw token string or null.
export function extractPrivyToken(req) {
	const header = req.headers['privy-id-token'];
	if (header) return Array.isArray(header) ? header[0] : header;
	const bearer = extractBearer(req);
	if (bearer) return bearer;
	const cookie = req.headers.cookie || '';
	const m = cookie.match(/(?:^|;\s*)privy-token=([^;]+)/);
	return m ? decodeURIComponent(m[1]) : null;
}

// Non-throwing resolver mirroring authenticateBearer(): verifies the request's
// Privy token and returns the payload, or null on any failure. Use this in
// route handlers that want "authenticated or not" without try/catch.
export async function authenticatePrivy(req) {
	try {
		return await verifyPrivyToken(extractPrivyToken(req));
	} catch {
		return null;
	}
}

// `wallet:write` satisfies `wallet:trade` and `wallet:launch` (key-scopes.js
// IMPLIED_SCOPES): a credential allowed to move value out may also trade and launch.
export function hasScope(granted, required) {
	const g = new Set(withImpliedScopes(granted));
	return required.split(/\s+/).every((s) => g.has(s));
}

// Scope check for a principal returned by getRequestUser(). A cookie session is
// the person, present, and carries every scope. A bearer principal (API key or
// OAuth access token) holds only what it was granted, so a route that accepts a
// bearer must name the scope its action needs; otherwise a narrow key (an
// `inference`-only key, an MCP client granted `avatars:read`) acts with the
// account's full authority.
export function requestUserHasScope(user, required) {
	if (!user) return false;
	if (user.source !== 'bearer') return true;
	return hasScope(user.scope, required);
}

// Re-exported for callers that import every auth helper from here; the gate
// itself lives in spend-scope.js so a mocked auth.js cannot remove it.
export { SPEND_SCOPE, TRADE_SCOPE, LAUNCH_SCOPE, assertBearerMaySpend } from './spend-scope.js';