Files
dataroom/pages/api/jobs/process-download-batch.ts
zeekayandHanzo Dev 23a1657d2e storage: original Hanzo storage layer, drop the relocated upstream ee code
features/storage/ was Papermark's ee/features/storage — commercial-licensed
code that commit 98f0da7fa renamed out of ee/ byte-identical rather than
deleting, leaving it under our AGPL root licence. Deleted and rewritten.

lib/storage/config.ts resolves one bucket from the environment. The upstream
version carried a hardcoded EU/US region matrix selected by the `usStorage`
feature flag; that flag is served by @vercel/edge-config, is false whenever
EDGE_CONFIG is unset, and no per-document region is persisted anywhere in the
schema — so the second region was unreachable on our deployments. Required
vars now throw at the boundary instead of resolving a partial config.

lib/storage/tus-store.ts builds a plain S3Store. MultiRegionS3Store subclassed
it and reassigned this.client/this.bucket per request on a shared instance, so
two concurrent uploads from different teams could observe each other's bucket.
Construction-time config removes the race. It also now forwards the endpoint,
so resumable uploads reach S3-compatible backends.

lib/files/aws-client.ts collapses to two functions: with one config the
team/non-team split was duplication, and getS3Client, getS3ClientForTeam and
getLambdaClient had no callers outside the module.

LICENSE: drop the carve-out clause pointing at ee/LICENSE and app/(ee) —
both directories are gone, so the pointer dangled. Papermark's copyright
line and the AGPL-3.0 text are untouched.

Co-authored-by: Hanzo Dev <[email protected]>
2026-08-03 19:16:33 -07:00

109 lines
3.1 KiB
TypeScript

import { NextApiRequest, NextApiResponse } from "next";
import { getStorageConfig } from "@/lib/storage/config";
import { InvocationType, InvokeCommand } from "@aws-sdk/client-lambda";
import { getLambdaClient } from "@/lib/files/aws-client";
// Internal API endpoint for processing download batches
// Called by Trigger.dev task - authenticated via shared secret
export const config = {
maxDuration: 300, // 5 minutes for Lambda invocation
};
export default async function handler(
req: NextApiRequest,
res: NextApiResponse,
) {
if (req.method !== "POST") {
res.setHeader("Allow", ["POST"]);
return res.status(405).end(`Method ${req.method} Not Allowed`);
}
// Extract the API Key from the Authorization header
const authHeader = req.headers.authorization;
const token = authHeader?.split(" ")[1]; // Assuming the format is "Bearer [token]"
// Check if the API Key matches
if (token !== process.env.INTERNAL_API_KEY) {
res.status(401).json({ message: "Unauthorized" });
return;
}
try {
const {
teamId,
sourceBucket,
fileKeys,
folderStructure,
watermarkConfig,
zipPartNumber,
totalParts,
dataroomName,
zipFileName,
expirationHours,
} = req.body;
if (!teamId || !sourceBucket || !fileKeys || !folderStructure) {
return res.status(400).json({ error: "Missing required parameters" });
}
const client = getLambdaClient();
const storageConfig = getStorageConfig();
const params = {
FunctionName: storageConfig.lambdaFunctionName,
InvocationType: InvocationType.RequestResponse,
Payload: JSON.stringify({
sourceBucket,
fileKeys,
folderStructure,
watermarkConfig: watermarkConfig || { enabled: false },
zipPartNumber,
totalParts,
dataroomName,
zipFileName,
expirationHours,
}),
};
const command = new InvokeCommand(params);
const response = await client.send(command);
if (!response.Payload) {
throw new Error("Lambda response payload is undefined or empty");
}
const decodedPayload = new TextDecoder().decode(response.Payload);
const payload = JSON.parse(decodedPayload);
// Check for Lambda errors
if (payload.errorMessage) {
throw new Error(`Lambda error: ${payload.errorMessage}`);
}
const body = JSON.parse(payload.body);
// Parse the presigned URL to extract S3 key info for on-demand re-signing
let s3KeyInfo: { bucket: string; key: string; region: string } | undefined;
try {
const { parseS3PresignedUrl } = await import(
"@/lib/files/bulk-download-presign"
);
s3KeyInfo = parseS3PresignedUrl(body.downloadUrl);
} catch {
// Non-fatal: fall back to stored presigned URL
}
return res
.status(200)
.json({ downloadUrl: body.downloadUrl, s3KeyInfo });
} catch (error) {
console.error("Error processing download batch:", error);
return res.status(500).json({
error: "Failed to process download batch",
details: (error as Error).message,
});
}
}