Rallly is an open-source scheduling and collaboration tool designed to make organizing events and meetings easier.
TypeScript i18nextnext-authnextjspostgresqlprismareact-emailt3-stacktailwindcsstrpcturborepotypescriptzod
✨ Add server-side upload proxy for self-hosted S3 (RAL-1150) (#2345)
Luke Vella81ccabb96ad4
diff --git a/apps/web/src/app/api/storage/[...key]/route.ts b/apps/web/src/app/api/storage/[...key]/route.tsindex 2363c3f7c..26e31456e 100644--- a/apps/web/src/app/api/storage/[...key]/route.ts+++ b/apps/web/src/app/api/storage/[...key]/route.ts@@ -1,13 +1,18 @@-import { GetObjectCommand } from "@aws-sdk/client-s3";+import { GetObjectCommand, PutObjectCommand } from "@aws-sdk/client-s3";import { createLogger } from "@rallly/logger";import type { NextRequest } from "next/server";import { NextResponse } from "next/server";import { env } from "@/env";+import { verifyUploadToken } from "@/lib/storage/image-upload";import { getS3Client } from "@/lib/storage/s3";+import { isSelfHosted } from "@/utils/constants";const logger = createLogger("api/storage");+const MAX_UPLOAD_BYTES = 2 * 1024 * 1024;+const ALLOWED_UPLOAD_CONTENT_TYPES = new Set(["image/jpeg", "image/png"]);+async function getAvatar(key: string) {const s3Client = getS3Client();@@ -61,3 +66,77 @@ export async function GET();}}++export async function PUT(+ req: NextRequest,+ context: { params: Promise<{ key: string[] }> },+) {+ if (!isSelfHosted) {+ return new NextResponse("Not found", { status: 404 });+ }++ const keyParts = (await context.params).key;++ if (keyParts[0] !== "upload" || keyParts.length < 2) {+ return new NextResponse("Not found", { status: 404 });+ }++ const key = keyParts.slice(1).join("/");+ const token = req.nextUrl.searchParams.get("token");++ if (!token || !verifyUploadToken(key, token)) {+ return new NextResponse("Invalid token", { status: 401 });+ }++ const contentType = req.headers.get("content-type") ?? "";++ if (!ALLOWED_UPLOAD_CONTENT_TYPES.has(contentType)) {+ return new NextResponse("Unsupported content type", { status: 415 });+ }++ const contentLength = Number(req.headers.get("content-length"));++ if (+ !Number.isFinite(contentLength) ||+ contentLength <= 0 ||+ contentLength > MAX_UPLOAD_BYTES+ ) {+ return new NextResponse("Invalid content length", { status: 413 });+ }++ const s3Client = getS3Client();++ if (!s3Client) {+ return new NextResponse("Storage not configured", { status: 500 });+ }++ const arrayBuffer = await req.arrayBuffer();++ if (arrayBuffer.byteLength > MAX_UPLOAD_BYTES) {+ return new NextResponse("Payload too large", { status: 413 });+ }++ if (arrayBuffer.byteLength !== contentLength) {+ return new NextResponse("Content length mismatch", { status: 400 });+ }++ try {+ await s3Client.send(+ new PutObjectCommand({+ Bucket: env.S3_BUCKET_NAME,+ Key: key,+ ContentType: contentType,+ ContentLength: arrayBuffer.byteLength,+ Body: new Uint8Array(arrayBuffer),+ }),+ );+ } catch (error) {+ logger.error({ error, key }, "Failed to upload object to storage");+ return NextResponse.json(+ { error: "Failed to upload object" },+ { status: 500 },+ );+ }++ return new NextResponse(null, { status: 200 });+}diff --git a/apps/web/src/lib/storage/image-upload.ts b/apps/web/src/lib/storage/image-upload.tsindex 3502e638a..c47b8be73 100644--- a/apps/web/src/lib/storage/image-upload.ts+++ b/apps/web/src/lib/storage/image-upload.ts@@ -1,11 +1,44 @@import "server-only";+import crypto from "node:crypto";import { DeleteObjectCommand, PutObjectCommand } from "@aws-sdk/client-s3";import { getSignedUrl } from "@aws-sdk/s3-request-presigner";-import { env } from "@/env";import { AppError } from "@/lib/errors";+import { isSelfHosted } from "@/utils/constants";import { getS3Client } from "./s3";+const UPLOAD_TOKEN_TTL_SECONDS = 3600;++function computeSignature(payload: string) {+ return crypto+ .createHmac("sha256", env.SECRET_PASSWORD)+ .update(payload)+ .digest("hex");+}++export function signUploadKey(key: string) {+ const expiry = Math.floor(Date.now() / 1000) + UPLOAD_TOKEN_TTL_SECONDS;+ const signature = computeSignature(`${key}:${expiry}`);+ return `${expiry}.${signature}`;+}++export function verifyUploadToken(key: string, token: string) {+ const parts = token.split(".");+ if (parts.length !== 2) return false;+ const [expiryStr, signature] = parts;+ const expiry = Number(expiryStr);+ if (!Number.isInteger(expiry)) return false;+ if (expiry <= Math.floor(Date.now() / 1000)) return false;++ const expected = computeSignature(`${key}:${expiry}`);+ const expectedBuf = Buffer.from(expected, "hex");+ const tokenBuf = Buffer.from(signature, "hex");+ if (expectedBuf.length === 0 || expectedBuf.length !== tokenBuf.length) {+ return false;+ }+ return crypto.timingSafeEqual(expectedBuf, tokenBuf);+}+const mimeToExtension = {"image/jpeg": "jpg","image/png": "png",@@ -42,6 +75,18 @@ export async function getImageUploadUrl({const key = `${keyPrefix}/${entityId}-${Date.now()}.${mimeToExtension[fileType]}`;+ if (isSelfHosted) {+ const token = signUploadKey(key);+ const url = `/api/storage/upload/${key}?token=${token}`;+ return {+ success: true,+ url,+ fields: {+ key,+ },+ } as const;+ }+const command = new PutObjectCommand({Bucket: env.S3_BUCKET_NAME,Key: key,