Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

16.3 KB
Raw Blame
import { db } from "@cap/database";
import { isBlockedAccountEmail } from "@cap/database/auth/domain-utils";
import { getCurrentUser } from "@cap/database/auth/session";
import { sendEmail } from "@cap/database/emails/config";
import { Feedback } from "@cap/database/emails/feedback";
import {
	authApiKeys,
	organizationMembers,
	organizations,
	users,
} from "@cap/database/schema";
import { serverEnv } from "@cap/env";
import {
	isProSubscription,
	isValidStripePlanPriceId,
	STRIPE_AVAILABLE,
	stripe,
	userIsPro,
} from "@cap/utils";
import { OrganizationBrandingPatchBody } from "@cap/web-api-contract";
import { ImageUploads } from "@cap/web-backend";
import { type ImageUpload, Organisation } from "@cap/web-domain";
import { zValidator } from "@hono/zod-validator";
import { and, eq, isNull } from "drizzle-orm";
import { Effect, Option } from "effect";
import { type Context, Hono } from "hono";
import type Stripe from "stripe";
import { z } from "zod";
import {
	confirmedDesktopLogWebhookUrl,
	createDesktopLogUpload,
} from "@/lib/desktop-log-upload";
import { getCheckoutRedirectUrls } from "@/lib/mobile-checkout";
import { runPromise } from "@/lib/server";
import { trackServerEvent } from "@/lib/server-analytics";
import { withAuth, withOptionalAuth } from "../../utils";
import {
	canEditOrganizationBranding,
	type DesktopOrganizationRow,
	decodeOrganizationLogoUpdate,
	filterAccessibleOrganizationRows,
	mergeOrganizationBrandingMetadata,
	normalizeOrganizationBrandingPatchBody,
	OrganizationBrandingValidationError,
	toDesktopOrganization,
} from "./organization-branding";

export const app = new Hono();

const MAX_DESKTOP_PROFILE_IMAGE_BYTES = 5 * 1024 * 1024;

async function resolveOrganizationIconUrl(iconUrl: string | null) {
	if (!iconUrl) return null;

	return Effect.gen(function* () {
		const imageUploads = yield* ImageUploads;
		return yield* imageUploads.resolveImageUrl(
			iconUrl as ImageUpload.ImageUrlOrKey,
		);
	}).pipe(runPromise);
}

async function resolveUserImageUrl(imageUrl: string | null) {
	if (!imageUrl) return null;

	return Effect.gen(function* () {
		const imageUploads = yield* ImageUploads;
		return yield* imageUploads.resolveImageUrl(
			imageUrl as ImageUpload.ImageUrlOrKey,
		);
	}).pipe(runPromise);
}

async function fetchDesktopProfileImage(imageUrl: string) {
	const response = await fetch(imageUrl);
	if (!response.ok) return null;

	const contentType = response.headers.get("content-type");
	if (!contentType?.toLowerCase().startsWith("image/")) return null;

	const contentLength = Number(response.headers.get("content-length"));
	if (contentLength > MAX_DESKTOP_PROFILE_IMAGE_BYTES) return null;

	const bytes = await response.arrayBuffer();
	if (bytes.byteLength > MAX_DESKTOP_PROFILE_IMAGE_BYTES) return null;

	return { bytes, contentType };
}

type DesktopProfileUser = {
	name: string | null;
	lastName: string | null;
	email: string | null;
	image: string | null;
};

async function getDesktopProfileUser(c: Context) {
	const authHeader = c.req.header("authorization")?.split(" ")[1];

	if (authHeader?.length === 36) {
		const [user] = await db()
			.select({
				name: users.name,
				lastName: users.lastName,
				email: users.email,
				image: users.image,
			})
			.from(users)
			.innerJoin(authApiKeys, eq(users.id, authApiKeys.userId))
			.where(eq(authApiKeys.id, authHeader))
			.limit(1);

		if (!user || isBlockedAccountEmail(user.email)) return null;
		return user;
	}

	const user = await getCurrentUser();
	if (!user) return null;

	return {
		name: user.name,
		lastName: user.lastName,
		email: user.email,
		image: user.image,
	} satisfies DesktopProfileUser;
}

async function toDesktopOrganizations(
	rows: DesktopOrganizationRow[],
	userId: string,
) {
	return Promise.all(
		filterAccessibleOrganizationRows(rows, userId).map(async (row) =>
			toDesktopOrganization(
				row,
				userId,
				await resolveOrganizationIconUrl(row.iconUrl),
			),
		),
	);
}

function mergeDesktopOrganizationRows(...rowSets: DesktopOrganizationRow[][]) {
	const rowsById = new Map<string, DesktopOrganizationRow>();

	for (const rows of rowSets) {
		for (const row of rows) {
			rowsById.set(row.id, row);
		}
	}

	return Array.from(rowsById.values());
}

async function applyOrganizationLogoUpdate(
	row: DesktopOrganizationRow,
	logo: ReturnType<typeof decodeOrganizationLogoUpdate>,
) {
	if (logo.action === "keep") return;

	await Effect.gen(function* () {
		const imageUploads = yield* ImageUploads;

		yield* imageUploads.applyUpdate({
			payload:
				logo.action === "remove"
					? Option.none()
					: Option.some({
							contentType: logo.contentType,
							fileName: logo.fileName,
							data: logo.data,
						}),
			existing: Option.fromNullable(
				row.iconUrl as ImageUpload.ImageUrlOrKey | null,
			),
			keyPrefix: `organizations/${row.id}`,
			update: (db, urlOrKey) =>
				db
					.update(organizations)
					.set({ iconUrl: urlOrKey })
					.where(
						eq(organizations.id, Organisation.OrganisationId.make(row.id)),
					),
		});
	}).pipe(runPromise);
}

app.post(
	"/logs",
	zValidator(
		"form",
		z.object({
			log: z.string(),
			os: z.string().optional(),
			version: z.string().optional(),
			diagnostics: z.string().optional(),
			report: z.string().optional(),
			context: z.string().optional(),
		}),
	),
	withOptionalAuth,
	async (c) => {
		const {
			log,
			os,
			version,
			diagnostics: diagnosticsJson,
			report,
			context,
		} = c.req.valid("form");
		const user = c.get("user");

		try {
			const discordWebhookUrl = serverEnv().DISCORD_LOGS_WEBHOOK_URL;
			if (!discordWebhookUrl)
				throw new Error("Discord webhook URL is not configured");

			const formData = createDesktopLogUpload({
				log,
				os,
				version,
				diagnostics: diagnosticsJson,
				report,
				context,
				user: user ? { email: user.email, id: user.id } : undefined,
			});

			const response = await fetch(
				confirmedDesktopLogWebhookUrl(discordWebhookUrl),
				{
					method: "POST",
					body: formData,
				},
			);

			if (!response.ok)
				throw new Error(
					`Failed to send logs to Discord: ${response.statusText}`,
				);

			return c.json({
				success: true,
				message: "Logs uploaded successfully",
			});
		} catch (_error) {
			return c.json({ error: "Failed to upload logs" }, { status: 500 });
		}
	},
);

app.post(
	"/feedback",
	withAuth,
	zValidator(
		"form",
		z.object({
			feedback: z.string(),
			os: z.enum(["macos", "windows", "linux"]).optional(),
			version: z.string().optional(),
		}),
	),
	async (c) => {
		const { feedback, os, version } = c.req.valid("form");
		const userEmail = c.get("user").email;

		try {
			await sendEmail({
				email: "[email protected]",
				subject: `New Feedback from ${userEmail}`,
				react: Feedback({
					userEmail,
					feedback,
					os,
					version,
				}),
				cc: userEmail,
				replyTo: userEmail,
				fromOverride: "Richie from Cap <[email protected]>",
			});

			return c.json({
				success: true,
				message: "Feedback submitted successfully",
			});
		} catch (_error) {
			return c.json({ error: "Failed to submit feedback" }, { status: 500 });
		}
	},
);

app.get("/org-custom-domain", withAuth, async (c) => {
	const user = c.get("user");

	try {
		const [result] = await db()
			.select({
				customDomain: organizations.customDomain,
				domainVerified: organizations.domainVerified,
			})
			.from(users)
			.leftJoin(organizations, eq(users.activeOrganizationId, organizations.id))
			.where(eq(users.id, user.id));

		let customDomain = result?.customDomain ?? null;
		if (
			customDomain &&
			!customDomain.startsWith("http://") &&
			!customDomain.startsWith("https://")
		) {
			customDomain = `https://${customDomain}`;
		}

		return c.json({
			custom_domain: customDomain,
			domain_verified: result?.domainVerified ?? null,
		});
	} catch (error) {
		console.error("[GET] Error fetching custom domain:", error);
		return c.json({ error: "Failed to fetch custom domain" }, { status: 500 });
	}
});

app.get("/plan", withAuth, async (c) => {
	const user = c.get("user");

	let isSubscribed = userIsPro(user);

	if (!isSubscribed && !user.stripeSubscriptionId && user.stripeCustomerId) {
		try {
			const subscriptions = await stripe().subscriptions.list({
				customer: user.stripeCustomerId,
			});
			const activeSubscription = subscriptions.data.find(
				(sub) => sub.status === "active" && isProSubscription(sub),
			);
			if (activeSubscription) {
				isSubscribed = true;
				await db()
					.update(users)
					.set({
						stripeSubscriptionStatus: activeSubscription.status,
						stripeSubscriptionId: activeSubscription.id,
					})
					.where(eq(users.id, user.id));
			}
		} catch (error) {
			console.error("[GET] Error fetching subscription from Stripe:", error);
		}
	}

	return c.json({
		upgraded: isSubscribed,
		stripeSubscriptionStatus: user.stripeSubscriptionStatus,
	});
});

app.get("/user/profile", async (c) => {
	const user = await getDesktopProfileUser(c);
	if (!user) return c.text("User not authenticated", 401);

	const name = [user.name, user.lastName].filter(Boolean).join(" ").trim();

	return c.json({
		name: name || null,
		email: user.email,
		imageUrl: await resolveUserImageUrl(user.image ?? null),
	});
});

app.get("/user/profile/image", async (c) => {
	const user = await getDesktopProfileUser(c);
	if (!user) return c.text("User not authenticated", 401);
	if (!user.image) return c.body(null, 404);

	const imageUrl = await resolveUserImageUrl(user.image);
	if (!imageUrl) return c.body(null, 404);

	const image = await fetchDesktopProfileImage(imageUrl);
	if (!image) return c.body(null, 404);

	return new Response(image.bytes, {
		headers: {
			"Cache-Control": "private, max-age=300",
			"Content-Type": image.contentType,
		},
	});
});

app.get("/organizations", withAuth, async (c) => {
	const user = c.get("user");

	const [ownedRows, memberRows] = await Promise.all([
		db()
			.select({
				id: organizations.id,
				name: organizations.name,
				ownerId: organizations.ownerId,
				tombstoneAt: organizations.tombstoneAt,
				iconUrl: organizations.iconUrl,
				metadata: organizations.metadata,
				role: organizationMembers.role,
			})
			.from(organizations)
			.leftJoin(
				organizationMembers,
				and(
					eq(organizationMembers.organizationId, organizations.id),
					eq(organizationMembers.userId, user.id),
				),
			)
			.where(
				and(
					isNull(organizations.tombstoneAt),
					eq(organizations.ownerId, user.id),
				),
			),
		db()
			.select({
				id: organizations.id,
				name: organizations.name,
				ownerId: organizations.ownerId,
				tombstoneAt: organizations.tombstoneAt,
				iconUrl: organizations.iconUrl,
				metadata: organizations.metadata,
				role: organizationMembers.role,
			})
			.from(organizationMembers)
			.innerJoin(
				organizations,
				eq(organizations.id, organizationMembers.organizationId),
			)
			.where(
				and(
					eq(organizationMembers.userId, user.id),
					isNull(organizations.tombstoneAt),
				),
			),
	]);
	const rows = mergeDesktopOrganizationRows(ownedRows, memberRows);

	return c.json(await toDesktopOrganizations(rows, user.id));
});

app.patch(
	"/organizations/:organizationId/branding",
	withAuth,
	zValidator("json", OrganizationBrandingPatchBody),
	async (c) => {
		const user = c.get("user");
		const organizationId = Organisation.OrganisationId.make(
			c.req.param("organizationId"),
		);
		const body = normalizeOrganizationBrandingPatchBody(c.req.valid("json"));
		let logoUpdate: ReturnType<typeof decodeOrganizationLogoUpdate>;

		try {
			logoUpdate = decodeOrganizationLogoUpdate(body.logo);
		} catch (error) {
			if (error instanceof OrganizationBrandingValidationError) {
				return c.json({ error: error.message }, { status: 400 });
			}
			throw error;
		}

		const [row] = await db()
			.select({
				id: organizations.id,
				name: organizations.name,
				ownerId: organizations.ownerId,
				tombstoneAt: organizations.tombstoneAt,
				iconUrl: organizations.iconUrl,
				metadata: organizations.metadata,
				role: organizationMembers.role,
			})
			.from(organizations)
			.leftJoin(
				organizationMembers,
				and(
					eq(organizationMembers.organizationId, organizations.id),
					eq(organizationMembers.userId, user.id),
				),
			)
			.where(eq(organizations.id, organizationId))
			.limit(1);

		if (!row || row.tombstoneAt !== null) {
			return c.json({ error: "Organization not found" }, { status: 404 });
		}

		if (!canEditOrganizationBranding(row, user.id)) {
			return c.json(
				{ error: "Only organization admins and owners can edit branding" },
				{ status: 403 },
			);
		}

		await applyOrganizationLogoUpdate(row, logoUpdate);

		await db()
			.update(organizations)
			.set({
				metadata: mergeOrganizationBrandingMetadata(
					row.metadata,
					body.brandColors,
				),
			})
			.where(eq(organizations.id, organizationId));

		const [updatedRow] = await db()
			.select({
				id: organizations.id,
				name: organizations.name,
				ownerId: organizations.ownerId,
				tombstoneAt: organizations.tombstoneAt,
				iconUrl: organizations.iconUrl,
				metadata: organizations.metadata,
				role: organizationMembers.role,
			})
			.from(organizations)
			.leftJoin(
				organizationMembers,
				and(
					eq(organizationMembers.organizationId, organizations.id),
					eq(organizationMembers.userId, user.id),
				),
			)
			.where(eq(organizations.id, organizationId))
			.limit(1);

		if (!updatedRow) {
			return c.json({ error: "Organization not found" }, { status: 404 });
		}

		return c.json(
			toDesktopOrganization(
				updatedRow,
				user.id,
				await resolveOrganizationIconUrl(updatedRow.iconUrl),
			),
		);
	},
);

app.post(
	"/subscribe",
	withAuth,
	zValidator(
		"json",
		z.object({
			priceId: z
				.string()
				.refine(
					(id) =>
						isValidStripePlanPriceId(
							id,
							serverEnv().VERCEL_ENV === "production"
								? "production"
								: "development",
						),
					{
						message: "Invalid priceId",
					},
				),
			platform: z.literal("mobile").optional(),
		}),
	),
	async (c) => {
		const { priceId, platform } = c.req.valid("json");
		const user = c.get("user");
		const checkoutPlatform = platform ?? "desktop";

		if (userIsPro(user)) {
			console.log("[POST] Error: User already on Pro plan");
			return c.json({ error: true, subscription: true }, { status: 400 });
		}

		if (!STRIPE_AVAILABLE()) {
			console.error(
				JSON.stringify({
					level: "error",
					message: "Stripe checkout is not configured",
					route: "/api/desktop/subscribe",
				}),
			);
			return c.json(
				{ code: "billing_unavailable", error: true },
				{ status: 503 },
			);
		}

		let customerId = user.stripeCustomerId;

		if (user.stripeCustomerId === null) {
			console.log(
				"[POST] Checking for existing Stripe customer for email:",
				user.email,
			);

			const existingCustomers = await stripe().customers.list({
				email: user.email,
				limit: 1,
			});

			let customer: Stripe.Customer;
			if (existingCustomers.data.length > 0 && existingCustomers.data[0]) {
				customer = existingCustomers.data[0];
				console.log("[POST] Found existing Stripe customer:", customer.id);

				customer = await stripe().customers.update(customer.id, {
					metadata: {
						...customer.metadata,
						userId: user.id,
					},
				});
				console.log("[POST] Updated existing customer metadata with userId");
			} else {
				console.log("[POST] Creating new Stripe customer");
				customer = await stripe().customers.create({
					email: user.email,
					metadata: { userId: user.id },
				});
				console.log("[POST] Created Stripe customer:", customer.id);
			}

			await db()
				.update(users)
				.set({ stripeCustomerId: customer.id })
				.where(eq(users.id, user.id));

			customerId = customer.id;
		}

		console.log("[POST] Creating checkout session");
		const redirects = getCheckoutRedirectUrls(
			checkoutPlatform,
			serverEnv().WEB_URL,
		);
		const checkoutSession = await stripe().checkout.sessions.create({
			customer: customerId as string,
			line_items: [{ price: priceId, quantity: 1 }],
			mode: "subscription",
			success_url: redirects.successUrl,
			cancel_url: redirects.cancelUrl,
			allow_promotion_codes: true,
			metadata: { platform: checkoutPlatform, dubCustomerId: user.id },
		});

		if (checkoutSession.url) {
			console.log("[POST] Checkout session created successfully");

			trackServerEvent(user.id, "checkout_started", {
				price_id: priceId,
				quantity: 1,
				platform: checkoutPlatform,
			});

			return c.json({ url: checkoutSession.url });
		}

		console.log("[POST] Error: Failed to create checkout session");
		return c.json({ error: true }, { status: 400 });
	},
);