Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

8.1 KB
Raw Blame
import { HeadBucketCommand, S3Client } from "@aws-sdk/client-s3";
import { db } from "@cap/database";
import { decrypt, encrypt } from "@cap/database/crypto";
import { nanoId } from "@cap/database/helpers";
import { s3Buckets } from "@cap/database/schema";
import { Organisation, S3Bucket } from "@cap/web-domain";
import { zValidator } from "@hono/zod-validator";
import { and, desc, eq, isNull } from "drizzle-orm";
import { Hono } from "hono";
import { z } from "zod";
import { withAuth } from "@/app/api/utils";
import {
	blockedS3EndpointMessage,
	isDisallowedS3Endpoint,
	publicOnlyS3Agents,
} from "@/lib/s3-endpoint-policy";
import {
	getAccessibleOrganization,
	getManagedOrganizationStorage,
	getOrganizationS3Bucket,
} from "./organizationStorage";

export const app = new Hono().use(withAuth);

const defaultS3Config = {
	provider: "aws",
	accessKeyId: "",
	secretAccessKey: "",
	endpoint: "https://s3.amazonaws.com",
	bucketName: "",
	region: "us-east-1",
};

const orgIdQuery = z.object({
	orgId: z
		.string()
		.optional()
		.transform((value) =>
			value ? Organisation.OrganisationId.make(value) : undefined,
		),
});

const decryptBucketConfig = async (
	bucket: typeof s3Buckets.$inferSelect,
	exposeSecrets: boolean,
) => ({
	provider: bucket.provider,
	accessKeyId: exposeSecrets ? await decrypt(bucket.accessKeyId) : "",
	secretAccessKey: exposeSecrets ? await decrypt(bucket.secretAccessKey) : "",
	endpoint: bucket.endpoint
		? await decrypt(bucket.endpoint)
		: "https://s3.amazonaws.com",
	bucketName: await decrypt(bucket.bucketName),
	region: await decrypt(bucket.region),
});

const getS3ErrorMetadata = (error: unknown) => {
	if (!error || typeof error !== "object" || !("$metadata" in error)) {
		return undefined;
	}

	return error.$metadata as { httpStatusCode?: number } | undefined;
};

const blockedEndpointResponse = {
	error: blockedS3EndpointMessage,
	details: "The provided endpoint is not allowed.",
};

app.post(
	"/",
	zValidator(
		"json",
		z.object({
			provider: z.string(),
			accessKeyId: z.string(),
			secretAccessKey: z.string(),
			endpoint: z.string(),
			bucketName: z.string(),
			region: z.string(),
		}),
	),
	async (c) => {
		const user = c.get("user");
		const data = c.req.valid("json");

		if (await isDisallowedS3Endpoint(data.endpoint)) {
			return c.json(blockedEndpointResponse, { status: 400 });
		}

		try {
			const encryptedConfig = {
				id: S3Bucket.S3BucketId.make(nanoId()),
				provider: data.provider,
				accessKeyId: await encrypt(data.accessKeyId),
				secretAccessKey: await encrypt(data.secretAccessKey),
				endpoint: data.endpoint ? await encrypt(data.endpoint) : null,
				bucketName: await encrypt(data.bucketName),
				region: await encrypt(data.region),
				ownerId: user.id,
				organizationId: null,
				active: true,
			};

			await db().transaction(async (tx) => {
				await tx
					.update(s3Buckets)
					.set({ active: false })
					.where(
						and(
							eq(s3Buckets.ownerId, user.id),
							isNull(s3Buckets.organizationId),
						),
					);
				await tx.insert(s3Buckets).values(encryptedConfig);
			});

			return c.json({ success: true });
		} catch (error) {
			console.error("Error in S3 config route:", error);
			return c.json(
				{
					error: "Failed to save S3 configuration",
					details: error instanceof Error ? error.message : String(error),
				},
				{ status: 500 },
			);
		}
	},
);

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

	try {
		await db()
			.update(s3Buckets)
			.set({ active: false })
			.where(
				and(eq(s3Buckets.ownerId, user.id), isNull(s3Buckets.organizationId)),
			);

		return c.json({ success: true });
	} catch (error) {
		console.error("Error in S3 config delete route:", error);
		return c.json(
			{
				error: "Failed to delete S3 configuration",
				details: error instanceof Error ? error.message : String(error),
			},
			{ status: 500 },
		);
	}
});

app.get("/get", zValidator("query", orgIdQuery), async (c) => {
	const user = c.get("user");
	const { orgId } = c.req.valid("query");

	try {
		if (orgId) {
			const organization = await getAccessibleOrganization(user.id, orgId);
			if (!organization)
				return c.json({ error: "forbidden_org" }, { status: 403 });

			const managedByOrganization = await getManagedOrganizationStorage(
				user.id,
				orgId,
			);
			if (managedByOrganization?.activeProvider === "s3") {
				const bucket = await getOrganizationS3Bucket(orgId);
				if (bucket) {
					return c.json({
						config: await decryptBucketConfig(bucket, false),
						source: "organization" as const,
						managedByOrganization,
					});
				}
			}

			if (managedByOrganization) {
				return c.json({
					config: defaultS3Config,
					source: "organization" as const,
					managedByOrganization,
				});
			}
		}

		const [bucket] = await db()
			.select()
			.from(s3Buckets)
			.where(
				and(
					eq(s3Buckets.ownerId, user.id),
					isNull(s3Buckets.organizationId),
					eq(s3Buckets.active, true),
				),
			)
			.orderBy(desc(s3Buckets.updatedAt))
			.limit(1);

		if (!bucket)
			return c.json({
				config: defaultS3Config,
				source: "default" as const,
				managedByOrganization: null,
			});

		return c.json({
			config: await decryptBucketConfig(bucket, true),
			source: "user" as const,
			managedByOrganization: null,
		});
	} catch (error) {
		console.error("Error in S3 config get route:", error);
		return c.json(
			{
				error: "Failed to fetch S3 configuration",
				details: error instanceof Error ? error.message : String(error),
			},
			{ status: 500 },
		);
	}
});

app.post(
	"/test",
	zValidator(
		"json",
		z.object({
			provider: z.string(),
			accessKeyId: z.string(),
			secretAccessKey: z.string(),
			endpoint: z.string(),
			bucketName: z.string(),
			region: z.string(),
		}),
	),
	async (c) => {
		const TIMEOUT_MS = 5000; // 5 second timeout
		const data = c.req.valid("json");

		if (await isDisallowedS3Endpoint(data.endpoint)) {
			return c.json(
				{ ...blockedEndpointResponse, metadata: undefined },
				{ status: 400 },
			);
		}

		try {
			const controller = new AbortController();
			const timeoutId = setTimeout(() => {
				controller.abort();
			}, TIMEOUT_MS);

			const s3Client = new S3Client({
				endpoint: data.endpoint,
				region: data.region,
				credentials: {
					accessKeyId: data.accessKeyId,
					secretAccessKey: data.secretAccessKey,
				},
				requestHandler: {
					abortSignal: controller.signal,
					...publicOnlyS3Agents(),
				},
			});

			try {
				await s3Client.send(new HeadBucketCommand({ Bucket: data.bucketName }));

				clearTimeout(timeoutId);
			} catch (error) {
				console.log(error);
				clearTimeout(timeoutId);
				let errorMessage = "Failed to connect to S3";

				if (error instanceof Error) {
					if (error.name === "AbortError" || error.name === "TimeoutError") {
						errorMessage =
							"Connection timed out after 5 seconds. Please check the endpoint URL and your network connection.";
					} else if (error.name === "NoSuchBucket") {
						errorMessage = `Bucket '${data.bucketName}' does not exist`;
					} else if (error.name === "NetworkingError") {
						errorMessage =
							"Network error. Please check the endpoint URL and your network connection.";
					} else if (error.name === "InvalidAccessKeyId") {
						errorMessage = "Invalid Access Key ID";
					} else if (error.name === "SignatureDoesNotMatch") {
						errorMessage = "Invalid Secret Access Key";
					} else if (error.name === "AccessDenied") {
						errorMessage =
							"Access denied. Please check your credentials and bucket permissions.";
					} else if (getS3ErrorMetadata(error)?.httpStatusCode === 301) {
						errorMessage =
							"Received 301 redirect. This usually means the endpoint URL is incorrect or the bucket is in a different region.";
					}
				}

				return c.json(
					{
						error: errorMessage,
						details: error instanceof Error ? error.message : String(error),
						metadata: getS3ErrorMetadata(error),
					},
					{ status: 500 },
				);
			}

			return c.json({ success: true });
		} catch (error) {
			return c.json(
				{
					error: "Failed to connect to S3",
					details: error instanceof Error ? error.message : String(error),
					metadata: getS3ErrorMetadata(error),
				},
				{ status: 500 },
			);
		}
	},
);