refactor: remove upload and web-api routes, migrate to new controller structure
Deploy FileDrop / deploy (push) Failing after 12s

- Deleted `upload.ts` and `web-api.ts` routes, consolidating logic into dedicated controllers.
- Updated import paths in tests to reflect new controller structure.
- Refactored Telegram API utilities to utilize a bot pool for improved bot management and error handling.
- Enhanced environment variable tests to ensure additional bot tokens are correctly populated.
- Adjusted S3 bucket configuration tests to align with new controller imports.
- Updated Telegram queue implementation to reflect new infrastructure organization.
This commit is contained in:
Claude
2026-07-29 07:28:30 +07:00
parent 73adb5f58e
commit ea87397801
23 changed files with 90 additions and 2389 deletions
+20 -2
View File
@@ -46,6 +46,25 @@ if (missing.length > 0) {
throw new Error(`Missing environment variables: ${missing.join(', ')}`);
}
// Validate S3 credentials: if S3_ACCESS_KEY is explicitly set (env var present,
// not relying on default), S3_SECRET_KEY must also be set. An empty secret key
// would cause HMAC-SHA256 to "succeed" silently — a security hole.
const s3AccessKeyExplicit = 'S3_ACCESS_KEY' in process.env;
const s3SecretKeyExplicit = 'S3_SECRET_KEY' in process.env;
if (s3AccessKeyExplicit || s3SecretKeyExplicit) {
const s3Key = (process.env.S3_ACCESS_KEY || '').trim();
const s3Secret = (process.env.S3_SECRET_KEY || '').trim();
if (s3Key && !s3Secret) {
logger.error('S3_ACCESS_KEY is set but S3_SECRET_KEY is empty — this is a security risk');
throw new Error(
'S3_ACCESS_KEY requires S3_SECRET_KEY to be set. Set S3_SECRET_KEY or unset S3_ACCESS_KEY.',
);
}
if (s3Secret && !s3Key) {
logger.warn('S3_SECRET_KEY is set but S3_ACCESS_KEY is not — S3 auth will use the default key');
}
}
const parseNumber = (value: string | undefined, fallback: number): number => {
const parsed = Number.parseInt(value || '', 10);
return Number.isFinite(parsed) && parsed > 0 ? parsed : fallback;
@@ -76,8 +95,7 @@ const maskDatabaseUrl = (value: string): string =>
export const config: AppConfig = {
botToken: process.env.BOT_TOKEN!,
additionalBotTokens:
process.env.NODE_ENV === 'test' ? [] : parseTokens(process.env.ADDITIONAL_BOT_TOKENS),
additionalBotTokens: parseTokens(process.env.ADDITIONAL_BOT_TOKENS),
storageChatId: parseInt(process.env.STORAGE_CHANNEL_ID!, 10),
baseUrl: process.env.BASE_URL!,
databaseUrl: process.env.DATABASE_URL!,
@@ -4,7 +4,8 @@ import { fileInfoCache } from '../../../infrastructure/cache/index';
import logger from '../../../shared/logger/index';
import { cleanupTempFile, formatCreatedAt, getErrorMessage } from '../../../shared/utils/file';
import { createChunkedObjectResponse } from '../../../utils/chunked-storage';
import { getFileInfo, type TelegramFileInfo } from '../../../utils/telegram';
import { botPool } from '../../../infrastructure/telegram/bot-pool';
import type { TelegramFileInfo } from '../../../domain/ports/telegram-service';
import { locateZipEntry } from '../../../utils/zip';
/**
@@ -46,7 +47,7 @@ const getTelegramFileInfo = async (
return cached;
}
const fileInfo = await getFileInfo(telegramFileId);
const fileInfo = await botPool.getFileInfo(telegramFileId);
fileInfoCache.set(cacheKey, fileInfo);
logger.debug('File info cached', { publicId, cacheKey });
@@ -14,7 +14,7 @@ import {
createChunkedObjectResponse,
storeFileInTelegramChunks,
} from '../../../utils/chunked-storage';
import { forwardToStorage, getFileInfo } from '../../../utils/telegram';
import { botPool } from '../../../infrastructure/telegram/bot-pool';
/**
* Route parameters extracted from the URL path.
@@ -239,7 +239,7 @@ export const handleUploadObjectV1 = async (
);
}
const forwardResult = await forwardToStorage(
const forwardResult = await botPool.forwardToStorage(
createReadStream(tempPath),
partFileNamePrefix,
'document',
@@ -318,7 +318,7 @@ export const handleDownloadObjectV1 = async (
return createChunkedObjectResponse({ file, range, reqId: '' });
}
const fileInfo = await getFileInfo(file.telegramFileId);
const fileInfo = await botPool.getFileInfo(file.telegramFileId);
const redirectUrl = `https://api.telegram.org/file/bot${fileInfo.bot_token}/${fileInfo.file_path}`;
return new Response(null, { status: 302, headers: { Location: redirectUrl } });
-64
View File
@@ -1,64 +0,0 @@
import { config } from '../env';
import {
checkBearerToken,
clearSessionCookie,
createSessionCookie,
getAuthSession,
isAuthEnabled,
timingSafeCompare,
} from '../utils/auth';
const json = (data: unknown, status = 200, headers: Record<string, string> = {}): Response =>
Response.json(data, { status, headers });
const notFound = (): Response => json({ error: 'Not found' }, 404);
const readLoginBody = async (req: Request): Promise<{ token: string } | null> => {
try {
const body = (await req.json()) as { token?: unknown };
if (typeof body.token !== 'string' || body.token.length === 0) return null;
return { token: body.token };
} catch {
return null;
}
};
export const handleLogin = async (req: Request): Promise<Response> => {
if (!isAuthEnabled()) return notFound();
const body = await readLoginBody(req);
if (!body) return json({ error: 'Token is required' }, 400);
if (!timingSafeCompare(body.token, config.adminApiToken)) {
return json({ error: 'Invalid token' }, 401);
}
return json({ username: 'admin' }, 200, {
'set-cookie': createSessionCookie('admin'),
});
};
export const handleLogout = async (): Promise<Response> =>
json({ success: true }, 200, {
'set-cookie': clearSessionCookie(),
});
export const handleMe = async (req: Request): Promise<Response> => {
if (!isAuthEnabled()) return notFound();
const session = getAuthSession(req);
if (!session && !checkBearerToken(req.headers.get('authorization'))) {
return json({ error: 'Unauthorized' }, 401);
}
const activeSession = session ?? {
username: 'admin',
expiresAt: null,
method: 'bearer' as const,
};
return json({
username: activeSession.username,
expiresAt: activeSession.expiresAt?.toISOString() ?? null,
});
};
-152
View File
@@ -1,152 +0,0 @@
import { createReadStream } from 'node:fs';
import { nanoid } from 'nanoid';
import { findFileByPublicId } from '../db/files';
import { fileInfoCache } from '../utils/cache';
import { createChunkedObjectResponse } from '../utils/chunked-storage';
import { cleanupTempFile, formatCreatedAt, getErrorMessage } from '../utils/file';
import logger from '../utils/logger';
import { metricsCollector } from '../utils/metrics';
import { getFileInfo, type TelegramFileInfo } from '../utils/telegram';
import { locateZipEntry } from '../utils/zip';
type RequestWithParams = Request & {
params?: {
public_id?: string;
};
};
const getTelegramFileInfo = async (telegramFileId: string, public_id: string) => {
const cacheKey = `file_info_${telegramFileId}`;
let fileInfo = fileInfoCache.get(cacheKey) as TelegramFileInfo | null;
if (!fileInfo) {
metricsCollector.recordCacheMiss();
fileInfo = await getFileInfo(telegramFileId);
fileInfoCache.set(cacheKey, fileInfo);
logger.debug('File info cached', { public_id, cacheKey });
} else {
metricsCollector.recordCacheHit();
logger.debug('File info from cache', { public_id, cacheKey });
}
return fileInfo;
};
const buildTelegramFileUrl = (filePath: string, botToken: string): string =>
`https://api.telegram.org/file/bot${botToken}/${filePath}`;
const sanitizeFilenameHeader = (fileName: string): string =>
fileName.replace(/[\\"]/g, '').replace(/[\n\r]/g, '');
const fail = (status: number, error: string): Response => Response.json({ error }, { status });
export const handleFileRedirect = async (req: RequestWithParams): Promise<Response> => {
const public_id = req.params?.public_id;
try {
if (!public_id) {
return fail(400, 'Missing file id');
}
const file = await findFileByPublicId(public_id);
if (!file) {
logger.warn('File not found', { public_id });
return fail(404, 'File not found');
}
if (file.storageBackend === 'chunked') {
if (file.archiveEntryName) {
return fail(501, 'Archive entry extraction is not supported for chunked files');
}
const range = { type: 'none' as const };
return createChunkedObjectResponse({ file, range, reqId: '' });
}
const archiveEntryName = file.archiveEntryName;
if (archiveEntryName) {
const archiveFileId = file.archiveTelegramFileId || file.telegramFileId;
const archiveInfo = await getTelegramFileInfo(archiveFileId, public_id);
const archiveResponse = await fetch(
buildTelegramFileUrl(archiveInfo.file_path, archiveInfo.bot_token),
);
if (!archiveResponse.ok) {
logger.error('Archive download failed', { public_id, status: archiveResponse.status });
return fail(500, 'Server error');
}
const tempZipPath = `/tmp/filedrop-dl-${nanoid()}.zip`;
await Bun.write(tempZipPath, archiveResponse);
const loc = await locateZipEntry(tempZipPath, archiveEntryName);
if (!loc) {
await cleanupTempFile(tempZipPath);
logger.error('Archive entry not found', { public_id, archiveEntryName });
return fail(404, 'File not found');
}
const fileStream = createReadStream(tempZipPath, {
start: loc.start,
end: loc.start + loc.length - 1,
});
fileStream.on('close', () => {
void cleanupTempFile(tempZipPath);
});
fileStream.on('error', () => {
void cleanupTempFile(tempZipPath);
});
return new Response(fileStream as unknown as ReadableStream, {
status: 200,
headers: {
'Content-Type': file.mimeType || 'application/octet-stream',
'Content-Disposition': `attachment; filename="${sanitizeFilenameHeader(file.fileName)}"`,
'Content-Length': String(loc.length),
},
});
}
const fileInfo = await getTelegramFileInfo(file.telegramFileId, public_id);
const redirectUrl = buildTelegramFileUrl(fileInfo.file_path, fileInfo.bot_token);
return new Response(null, {
status: 302,
headers: {
Location: redirectUrl,
},
});
} catch (error: unknown) {
logger.error('File redirect error', { public_id, error: getErrorMessage(error) });
return fail(500, 'Server error');
}
};
export const handleFileInfo = async (req: RequestWithParams): Promise<Response> => {
const public_id = req.params?.public_id;
try {
if (!public_id) {
return fail(400, 'Missing file id');
}
const file = await findFileByPublicId(public_id);
if (!file) {
logger.warn('File not found', { public_id });
return fail(404, 'File not found');
}
return Response.json(
{
public_id: file.publicId,
file_name: file.fileName,
mime_type: file.mimeType,
size_bytes: file.sizeBytes,
file_type: file.fileType,
created_at: formatCreatedAt(file.createdAt),
},
{ status: 200 },
);
} catch (error: unknown) {
logger.error('File info error', { public_id, error: getErrorMessage(error) });
return fail(500, 'Server error');
}
};
-15
View File
@@ -1,15 +0,0 @@
import { sql } from 'drizzle-orm';
import { db } from '../db';
import { getErrorMessage } from '../utils/file';
import logger from '../utils/logger';
export const handleHealth = async (_req: Request): Promise<Response> => {
try {
await db.execute(sql`SELECT 1`);
return Response.json({ status: 'ok' }, { status: 200 });
} catch (error: unknown) {
const message = getErrorMessage(error);
logger.error('Health check failed', { error: message });
return Response.json({ status: 'error', error: message }, { status: 500 });
}
};
-9
View File
@@ -1,9 +0,0 @@
export const handleHome = async (): Promise<Response> => {
const html = await Bun.file(`${import.meta.dir}/../home.html`).text();
return new Response(html, {
status: 200,
headers: {
'content-type': 'text/html; charset=utf-8',
},
});
};
-1178
View File
File diff suppressed because it is too large Load Diff
-303
View File
@@ -1,303 +0,0 @@
import { createWriteStream } from 'node:fs';
import { nanoid } from 'nanoid';
import { findFileByHash } from '../db/files';
import { config } from '../env';
import { storeFileInTelegramChunks } from '../utils/chunked-storage';
import {
buildUploadResponse,
checkFileSize,
cleanupTempFile,
computeHash,
ensureExtension,
extractMimeType,
getErrorMessage,
getFileType,
} from '../utils/file';
import logger from '../utils/logger';
import { metricsCollector } from '../utils/metrics';
import { enqueuePreparedUpload, type PreparedUpload } from '../utils/uploadBatcher';
interface JsonUploadPayload {
file?: unknown;
fileName?: string;
}
const parseBase64File = (file: string): { base64Data: string; mimeType: string } => {
if (!file.startsWith('data:')) {
return { base64Data: file, mimeType: 'application/octet-stream' };
}
const match = file.match(/^data:([^;]+);base64,(.+)$/);
return match
? { base64Data: match[2], mimeType: match[1] }
: { base64Data: file, mimeType: 'application/octet-stream' };
};
const normalizeFileType = (mimeType: string, fileName: string): string => {
const fileType = getFileType(mimeType, fileName);
return fileType === 'application' ? 'document' : fileType;
};
const JSON_UPLOAD_LIMIT_BYTES = 50 * 1024 * 1024;
const SIGNATURE_BYTES = 16;
const getContentLength = (req: Request): number | null => {
const value = req.headers.get('content-length');
if (!value) return null;
const parsed = Number.parseInt(value, 10);
return Number.isFinite(parsed) && parsed >= 0 ? parsed : null;
};
const rejectOversizedRequest = (req: Request): Response | null => {
const contentLength = getContentLength(req);
if (contentLength !== null && contentLength > config.maxRequestBodyBytes) {
return Response.json({ error: 'Request body too large' }, { status: 413 });
}
return null;
};
const streamFileToTemp = async (file: File, maxSizeBytes: number): Promise<PreparedUpload> => {
const tempPath = `/tmp/filedrop-${nanoid()}`;
const writer = createWriteStream(tempPath);
const hasher = new Bun.CryptoHasher('sha256');
const reader = file.stream().getReader();
const signatureChunks: Buffer[] = [];
let signatureBytes = 0;
let sizeBytes = 0;
const writeChunk = async (chunk: Buffer): Promise<void> => {
if (!writer.write(chunk)) {
await new Promise<void>((resolve, reject) => {
writer.once('drain', resolve);
writer.once('error', reject);
});
}
};
const finishWriter = async (): Promise<void> => {
await new Promise<void>((resolve, reject) => {
writer.end(() => resolve());
writer.once('error', reject);
});
};
try {
while (true) {
const { done, value } = await reader.read();
if (done) break;
const chunk = Buffer.from(value);
sizeBytes += chunk.byteLength;
if (sizeBytes > maxSizeBytes) {
throw new Error('File size exceeds upload limit');
}
hasher.update(chunk);
await writeChunk(chunk);
if (signatureBytes < SIGNATURE_BYTES) {
const remaining = SIGNATURE_BYTES - signatureBytes;
const signatureChunk = chunk.subarray(0, remaining);
signatureChunks.push(signatureChunk);
signatureBytes += signatureChunk.byteLength;
}
}
await finishWriter();
return {
tempPath,
fileHash: hasher.digest('hex'),
sizeBytes,
signatureBuffer: Buffer.concat(signatureChunks, signatureBytes),
};
} catch (error) {
writer.destroy();
await cleanupTempFile(tempPath);
throw error;
} finally {
reader.releaseLock();
}
};
const writeBufferToTemp = async (fileBuffer: Buffer, fileHash: string): Promise<PreparedUpload> => {
const tempPath = `/tmp/filedrop-${nanoid()}`;
try {
await Bun.write(tempPath, fileBuffer);
return {
tempPath,
fileHash,
sizeBytes: fileBuffer.byteLength,
signatureBuffer: fileBuffer.subarray(0, SIGNATURE_BYTES),
};
} catch (error) {
await cleanupTempFile(tempPath);
throw error;
}
};
export const handleUpload = async (req: Request): Promise<Response> => {
const startTime = performance.now();
try {
const contentType = req.headers.get('content-type') || '';
const oversizedResponse = rejectOversizedRequest(req);
if (oversizedResponse) return oversizedResponse;
if (contentType.includes('multipart/form-data')) {
return handleMultipartUpload(req);
} else if (contentType.includes('application/json')) {
return handleJSONUpload(req);
}
return Response.json(
{ error: 'Unsupported content type. Use multipart/form-data or application/json' },
{ status: 400 },
);
} catch (error: unknown) {
metricsCollector.recordError();
const message = getErrorMessage(error);
logger.error('Upload error', { error: message });
return Response.json({ error: message }, { status: 500 });
} finally {
metricsCollector.recordUploadTime(performance.now() - startTime);
}
};
const handleMultipartUpload = async (req: Request): Promise<Response> => {
try {
const formData = await req.formData();
const file = formData.get('file');
const fileName =
(formData.get('fileName') as string) || (file instanceof File ? file.name : null) || 'file';
if (!file || !(file instanceof File)) {
return Response.json({ error: 'No file provided' }, { status: 400 });
}
if (file.size > config.maxRequestBodyBytes) {
return Response.json({ error: 'File size exceeds upload limit' }, { status: 413 });
}
const prepared = await streamFileToTemp(file, config.maxRequestBodyBytes);
const existingFile = await findFileByHash(prepared.fileHash);
if (existingFile) {
await cleanupTempFile(prepared.tempPath);
return Response.json(buildUploadResponse(existingFile, config.baseUrl), { status: 200 });
}
const rawMimeType = file.type || extractMimeType({}, req) || 'application/octet-stream';
const { fileName: finalFileName, mimeType } = ensureExtension(
fileName,
prepared.signatureBuffer,
rawMimeType,
);
const fileType = getFileType(mimeType, finalFileName);
if (!checkFileSize(prepared.sizeBytes, fileType)) {
await cleanupTempFile(prepared.tempPath);
return Response.json({ error: `File size exceeds ${fileType} limit` }, { status: 400 });
}
if (prepared.sizeBytes > config.telegramChunkSizeBytes) {
const file = await storeFileInTelegramChunks({
tempPath: prepared.tempPath,
partFileNamePrefix: `direct-${prepared.fileHash?.slice(0, 16) || 'upload'}`,
fileName: finalFileName,
mimeType,
sizeBytes: prepared.sizeBytes,
fileType,
uploaderId: 0,
});
await cleanupTempFile(prepared.tempPath);
return Response.json(buildUploadResponse(file, config.baseUrl), { status: 200 });
}
const uploaded = await enqueuePreparedUpload({
prepared,
fileName: finalFileName,
mimeType,
fileType,
});
return Response.json(buildUploadResponse(uploaded, config.baseUrl), { status: 200 });
} catch (error: unknown) {
const message = getErrorMessage(error);
logger.error('Multipart upload error', { error: message });
return Response.json({ error: message }, { status: 500 });
}
};
const handleJSONUpload = async (req: Request): Promise<Response> => {
try {
const { file, fileName = 'file' } = (await req.json()) as JsonUploadPayload;
if (!file || typeof file !== 'string') {
return Response.json(
{ error: 'Invalid JSON. Must include "file" (base64) and optional "fileName"' },
{ status: 400 },
);
}
const { base64Data, mimeType: rawMimeType } = parseBase64File(file);
const estimatedSizeBytes = Math.floor((base64Data.length * 3) / 4);
if (
estimatedSizeBytes > JSON_UPLOAD_LIMIT_BYTES ||
estimatedSizeBytes > config.maxRequestBodyBytes
) {
return Response.json(
{
error:
'JSON base64 uploads are limited to 50MB. Use multipart/form-data for larger files',
},
{ status: 400 },
);
}
const fileBytes = Buffer.from(base64Data, 'base64');
const hash = computeHash(fileBytes);
const existingFile = await findFileByHash(hash);
if (existingFile) {
return Response.json(buildUploadResponse(existingFile, config.baseUrl), { status: 200 });
}
const { fileName: finalFileName, mimeType } = ensureExtension(fileName, fileBytes, rawMimeType);
const fileType = normalizeFileType(mimeType, finalFileName);
if (!checkFileSize(fileBytes.byteLength, fileType)) {
return Response.json({ error: `File size exceeds ${fileType} limit` }, { status: 400 });
}
const prepared = await writeBufferToTemp(fileBytes, hash);
if (prepared.sizeBytes > config.telegramChunkSizeBytes) {
const file = await storeFileInTelegramChunks({
tempPath: prepared.tempPath,
partFileNamePrefix: `direct-${prepared.fileHash?.slice(0, 16) || 'json'}`,
fileName: finalFileName,
mimeType,
sizeBytes: prepared.sizeBytes,
fileType,
uploaderId: 0,
});
await cleanupTempFile(prepared.tempPath);
return Response.json(buildUploadResponse(file, config.baseUrl), { status: 200 });
}
const uploaded = await enqueuePreparedUpload({
prepared,
fileName: finalFileName,
mimeType,
fileType,
});
return Response.json(buildUploadResponse(uploaded, config.baseUrl), { status: 200 });
} catch (error: unknown) {
const message = getErrorMessage(error);
logger.error('JSON upload error', { error: message });
return Response.json({ error: message }, { status: 500 });
}
};
-347
View File
@@ -1,347 +0,0 @@
import { createReadStream } from 'node:fs';
import { nanoid } from 'nanoid';
import { createBucket, deleteBucket, findBucketByName, listBuckets } from '../db/buckets';
import {
countBucketObjects,
findFileByBucketAndKey,
listObjectsByPrefix,
softDeleteFile,
} from '../db/files-ext';
import { config } from '../env';
import { createChunkedObjectResponse, storeFileInTelegramChunks } from '../utils/chunked-storage';
import { cleanupTempFile, computeHash, ensureExtension, getErrorMessage } from '../utils/file';
import logger from '../utils/logger';
import { forwardToStorage, getFileInfo } from '../utils/telegram';
type RouteParams = { bucket?: string; key?: string };
const json = (data: unknown, status = 200) => Response.json(data, { status });
const jsonError = (error: string, status: number) => Response.json({ error }, { status });
// ─────── Bucket endpoints ───────
export const handleListBucketsV1 = async (): Promise<Response> => {
const buckets = await listBuckets();
const result = await Promise.all(
buckets.map(async (b) => ({
id: b.id,
name: b.name,
createdAt: b.createdAt.toISOString(),
objectCount: await countBucketObjects(b.id),
})),
);
return json({ buckets: result });
};
export const handleCreateBucketV1 = async (req: Request): Promise<Response> => {
const body = (await req.json()) as { name?: string };
if (!body.name || !/^[a-z0-9][a-z0-9.-]{1,61}[a-z0-9]$/.test(body.name)) {
return jsonError('Invalid bucket name. Use lowercase, 3-63 chars, no underscore', 400);
}
const existing = await findBucketByName(body.name);
if (existing) return jsonError('Bucket already exists', 409);
const bucket = await createBucket(body.name);
return json({ id: bucket.id, name: bucket.name }, 201);
};
export const handleDeleteBucketV1 = async (
_req: Request,
params: RouteParams,
): Promise<Response> => {
const bucket = await findBucketByName(params.bucket!);
if (!bucket) return jsonError('Bucket not found', 404);
const count = await countBucketObjects(bucket.id);
if (count > 0) return jsonError('Bucket is not empty', 409);
await deleteBucket(params.bucket!);
return json({ success: true });
};
// ─────── Object endpoints ───────
export const handleListObjectsV1 = async (req: Request, params: RouteParams): Promise<Response> => {
const bucket = await findBucketByName(params.bucket!);
if (!bucket) return jsonError('Bucket not found', 404);
const url = new URL(req.url);
const prefix = url.searchParams.get('prefix') || '';
const delimiter = url.searchParams.get('delimiter') || '/';
const maxKeys = parseInt(url.searchParams.get('max-keys') || '1000', 10);
const continuationToken = url.searchParams.get('continuation-token') || null;
const { objects, prefixes } = await listObjectsByPrefix(
bucket.id,
prefix,
delimiter,
maxKeys,
continuationToken,
);
const isTruncated = objects.length > maxKeys;
const displayObjects = objects.slice(0, maxKeys);
return json({
objects: displayObjects.map((o) => ({
key: o.s3Key,
fileName: o.fileName,
mimeType: o.mimeType,
sizeBytes: Number(o.sizeBytes),
fileType: o.fileType,
etag: o.fileHash,
lastModified:
o.createdAt instanceof Date
? o.createdAt.toISOString()
: new Date(o.createdAt).toISOString(),
downloadUrl: `${config.baseUrl}/f/${o.publicId}`,
})),
prefixes,
isTruncated,
nextContinuationToken: isTruncated ? displayObjects[displayObjects.length - 1]?.s3Key : null,
});
};
export const handleUploadObjectV1 = async (
req: Request,
params: RouteParams,
): Promise<Response> => {
const bucket = await findBucketByName(params.bucket!);
if (!bucket) return jsonError('Bucket not found', 404);
const formData = await req.formData();
const file = formData.get('file');
if (!file || !(file instanceof File)) {
return jsonError('No file provided', 400);
}
const key = (formData.get('key') as string) || file.name;
const buffer = Buffer.from(await file.arrayBuffer());
const hash = computeHash(buffer);
const tempPath = `/tmp/filedrop-web-${nanoid()}`;
await Bun.write(tempPath, buffer);
const signatureBuffer = buffer.subarray(0, 16);
const { fileName: finalFileName, mimeType } = ensureExtension(
key.split('/').pop() || 'file',
signatureBuffer,
file.type || 'application/octet-stream',
);
const partFileNamePrefix = `s3-${bucket.name}-${key.replace(/\//g, '_')}`;
if (buffer.byteLength > config.telegramChunkSizeBytes) {
const file = await storeFileInTelegramChunks({
tempPath,
partFileNamePrefix,
fileName: finalFileName,
mimeType,
sizeBytes: buffer.byteLength,
fileType: 'document',
uploaderId: 0,
bucketId: bucket.id,
s3Key: key,
});
await cleanupTempFile(tempPath);
return json(
{
key,
size: buffer.byteLength,
etag: hash,
downloadUrl: `${config.baseUrl}/f/${file.publicId}`,
},
201,
);
}
const forwardResult = await forwardToStorage(
createReadStream(tempPath),
partFileNamePrefix,
'document',
);
const publicId = nanoid();
const { db, files: fileSchema } = await import('../db/index');
await db.insert(fileSchema).values({
publicId,
telegramFileId: forwardResult.telegramFileId,
telegramFileUniqueId: forwardResult.telegramFileUniqueId,
storageChatId: config.storageChatId,
storageMessageId: forwardResult.storageMessageId,
fileName: finalFileName,
mimeType,
sizeBytes: buffer.byteLength,
fileType: 'document',
uploaderId: 0,
fileHash: hash,
bucketId: bucket.id,
s3Key: key,
storageBackend: 'telegram',
isDeleted: false,
createdAt: new Date(),
updatedAt: new Date(),
});
await cleanupTempFile(tempPath);
return json(
{ key, size: buffer.byteLength, etag: hash, downloadUrl: `${config.baseUrl}/f/${publicId}` },
201,
);
};
export const handleDeleteObjectV1 = async (
_req: Request,
params: RouteParams,
): Promise<Response> => {
const bucket = await findBucketByName(params.bucket!);
if (!bucket) return jsonError('Bucket not found', 404);
await softDeleteFile(bucket.id, params.key!);
return json({ success: true });
};
export const handleDownloadObjectV1 = async (
_req: Request,
params: RouteParams,
): Promise<Response> => {
const bucket = await findBucketByName(params.bucket!);
if (!bucket) return jsonError('Bucket not found', 404);
const file = await findFileByBucketAndKey(bucket.id, params.key!);
if (!file) return jsonError('Object not found', 404);
if (file.storageBackend === 'chunked') {
const range = { type: 'none' as const };
return createChunkedObjectResponse({ file, range, reqId: '' });
}
const fileInfo = await getFileInfo(file.telegramFileId);
const redirectUrl = `https://api.telegram.org/file/bot${fileInfo.bot_token}/${fileInfo.file_path}`;
return new Response(null, { status: 302, headers: { Location: redirectUrl } });
};
export const handleCopyObjectV1 = async (req: Request, params: RouteParams): Promise<Response> => {
const body = (await req.json()) as {
sourceKey?: string;
destBucket?: string;
destKey?: string;
};
if (!body.sourceKey || !body.destKey) {
return jsonError('sourceKey and destKey are required', 400);
}
const destBucketName = body.destBucket || params.bucket!;
const sourceBucket = await findBucketByName(params.bucket!);
const destBucket = await findBucketByName(destBucketName);
if (!sourceBucket || !destBucket) return jsonError('Bucket not found', 404);
const sourceFile = await findFileByBucketAndKey(sourceBucket.id, body.sourceKey);
if (!sourceFile) return jsonError('Source object not found', 404);
if (sourceFile.storageBackend === 'chunked') {
return json({ error: 'Copying chunked objects is not implemented' }, 501);
}
const publicId = nanoid();
const { db, files: fileSchema } = await import('../db/index');
await db.insert(fileSchema).values({
publicId,
telegramFileId: sourceFile.telegramFileId,
telegramFileUniqueId: sourceFile.telegramFileUniqueId,
storageChatId: sourceFile.storageChatId,
storageMessageId: sourceFile.storageMessageId,
fileName: sourceFile.fileName,
mimeType: sourceFile.mimeType,
sizeBytes: sourceFile.sizeBytes,
fileType: sourceFile.fileType,
uploaderId: 0,
fileHash: sourceFile.fileHash,
bucketId: destBucket.id,
s3Key: body.destKey,
storageBackend: 'telegram',
isDeleted: false,
createdAt: new Date(),
updatedAt: new Date(),
});
return json({ sourceKey: body.sourceKey, destKey: body.destKey, destBucket: destBucketName });
};
// ─────── Router ───────
export const handleWebApiV1 = async (req: Request): Promise<Response> => {
const url = new URL(req.url);
const pathname = url.pathname.replace(/^\/api\/v1/, '');
const parts = pathname.split('/').filter(Boolean);
const method = req.method;
try {
// GET /api/v1/buckets
if (parts.length === 1 && parts[0] === 'buckets' && method === 'GET') {
return await handleListBucketsV1();
}
// POST /api/v1/buckets
if (parts.length === 1 && parts[0] === 'buckets' && method === 'POST') {
return await handleCreateBucketV1(req);
}
// DELETE /api/v1/buckets/{name}
if (parts.length === 2 && parts[0] === 'buckets' && method === 'DELETE') {
return await handleDeleteBucketV1(req, { bucket: parts[1] });
}
// GET /api/v1/buckets/{name}/objects
if (
parts.length === 3 &&
parts[0] === 'buckets' &&
parts[2] === 'objects' &&
method === 'GET'
) {
return await handleListObjectsV1(req, { bucket: parts[1] });
}
// POST /api/v1/buckets/{name}/upload
if (
parts.length === 3 &&
parts[0] === 'buckets' &&
parts[2] === 'upload' &&
method === 'POST'
) {
return await handleUploadObjectV1(req, { bucket: parts[1] });
}
// POST /api/v1/buckets/{name}/copy
if (parts.length === 3 && parts[0] === 'buckets' && parts[2] === 'copy' && method === 'POST') {
return await handleCopyObjectV1(req, { bucket: parts[1] });
}
// DELETE /api/v1/buckets/{name}/{key+}
if (parts.length >= 3 && parts[0] === 'buckets' && method === 'DELETE') {
const bucket = parts[1];
const key = parts.slice(2).join('/');
return await handleDeleteObjectV1(req, { bucket, key });
}
// GET /api/v1/buckets/{name}/download/{key+}
if (
parts.length >= 4 &&
parts[0] === 'buckets' &&
parts[2] === 'download' &&
method === 'GET'
) {
const bucket = parts[1];
const key = parts.slice(3).join('/');
return await handleDownloadObjectV1(req, { bucket, key });
}
return jsonError('Not found', 404);
} catch (error: unknown) {
logger.error('Web API error', { path: pathname, error: getErrorMessage(error) });
return jsonError('Internal server error', 500);
}
};
+3 -3
View File
@@ -9,7 +9,7 @@ import { config } from '../env';
import { computeHash } from './file';
import { createGetObjectResponse, type ObjectPartSource } from './s3/object-stream';
import type { RangeParseResult } from './s3/range';
import { forwardToStorage, getFileInfo } from './telegram';
import { botPool } from '../infrastructure/telegram/bot-pool';
export type ChunkCompressionAlgorithm = 'gzip' | null;
@@ -94,7 +94,7 @@ export const uploadFileInTelegramChunks = async (input: {
input.compress,
input.compressionMinSizeBytes,
);
const forwardResult = await forwardToStorage(
const forwardResult = await botPool.forwardToStorage(
bytes,
`${input.partFileNamePrefix}.part-${partNumber}`,
'document',
@@ -189,7 +189,7 @@ export const buildChunkedObjectSources = async (file: File): Promise<ObjectPartS
const sources: ObjectPartSource[] = [];
for (const part of parts) {
const fileInfo = await getFileInfo(part.telegramFileId);
const fileInfo = await botPool.getFileInfo(part.telegramFileId);
sources.push({
telegramFileId: part.telegramFileId,
telegramUrl: `https://api.telegram.org/file/bot${fileInfo.bot_token}/${fileInfo.file_path}`,
-200
View File
@@ -1,200 +0,0 @@
import { Telegraf } from 'telegraf';
import { config } from '../env';
import logger from './logger';
import { enqueueUpload } from './telegramQueue';
const botTokens = Array.from(new Set([config.botToken, ...config.additionalBotTokens]));
const bots = botTokens.map((token) => new Telegraf(token));
let nextBotIndex = 0;
const claimBotIndex = (): number => {
const botIndex = nextBotIndex;
nextBotIndex = (nextBotIndex + 1) % bots.length;
return botIndex;
};
const sleep = (seconds: number): Promise<void> => {
return new Promise((resolve) => setTimeout(resolve, seconds * 1000));
};
const executeWithBotRetry = async <T>(
action: (botInstance: Telegraf, botToken: string) => Promise<T>,
retries = 5,
attemptedBots = 0,
): Promise<T> => {
const botIndex = claimBotIndex();
const currentBot = bots[botIndex];
const currentToken = botTokens[botIndex];
try {
return await action(currentBot, currentToken);
} catch (error: unknown) {
const errorStr = error instanceof Error ? error.message : String(error);
const match = errorStr.match(/retry after (\d+)/i);
if (match) {
const nextIndex = nextBotIndex;
const nextAttemptedBots = attemptedBots + 1;
if (nextAttemptedBots < bots.length) {
logger.info(
`Bot Index ${botIndex} hit 429. Instantly rotating to Bot Index ${nextIndex}...`,
);
return executeWithBotRetry(action, retries, nextAttemptedBots);
}
if (retries > 0) {
const seconds = parseInt(match[1], 10);
logger.warn(`All bots in the pool are rate-limited. Sleeping for ${seconds} seconds...`, {
error: errorStr,
});
await sleep(seconds);
return executeWithBotRetry(action, retries - 1, 0);
}
}
throw error;
}
};
interface ForwardResult {
telegramFileId: string;
telegramFileUniqueId: string;
storageMessageId: number;
}
export interface TelegramFileInfo {
file_size: number;
mime_type: string;
file_path: string;
bot_token: string;
}
interface UploadedTelegramFile {
file_id?: string;
file_unique_id?: string;
}
interface TelegramMessageResult {
message_id: number;
document?: UploadedTelegramFile;
photo?: UploadedTelegramFile[];
video?: UploadedTelegramFile;
audio?: UploadedTelegramFile;
voice?: UploadedTelegramFile;
animation?: UploadedTelegramFile;
sticker?: UploadedTelegramFile;
video_note?: UploadedTelegramFile;
[key: string]: unknown;
}
type FilePayload = { source: unknown; filename: string };
type SendPayload = { caption?: string };
type SendMethod = (
chatId: number,
filePayload: FilePayload,
payload?: SendPayload,
) => Promise<TelegramMessageResult>;
const sendMethodMap: Record<string, string> = {
photo: 'sendPhoto',
audio: 'sendAudio',
video: 'sendVideo',
voice: 'sendVoice',
animation: 'sendAnimation',
sticker: 'sendSticker',
document: 'sendDocument',
video_note: 'sendDocument',
};
const extractUploadedFile = (
result: TelegramMessageResult,
fileType: string,
): UploadedTelegramFile | undefined => {
if (result.document) return result.document;
if (result.photo) return result.photo?.slice(-1)[0];
if (result.video) return result.video;
if (result.audio) return result.audio;
if (result.voice) return result.voice;
if (result.animation) return result.animation;
if (result.sticker) return result.sticker;
if (result.video_note) return result.video_note;
return result[fileType] as UploadedTelegramFile | undefined;
};
const buildSendPayload = (fileType: string, fileName: string): SendPayload => {
const basePayload = { caption: fileName };
if (fileType === 'sticker') return {};
if (fileType === 'document') return { caption: `📁 ${fileName}` };
return basePayload;
};
export const forwardToStorage = async (
fileChunk: unknown,
fileName: string,
fileType: string,
): Promise<ForwardResult> => {
try {
const result = await enqueueUpload(async (): Promise<TelegramMessageResult> => {
const filePayload = { source: fileChunk, filename: fileName };
const sendMethod = sendMethodMap[fileType] || 'sendDocument';
const payload = buildSendPayload(fileType, fileName);
return executeWithBotRetry((activeBot) => {
const telegram = activeBot.telegram as unknown as Record<string, SendMethod>;
return telegram[sendMethod](config.storageChatId, filePayload, payload);
});
});
const uploadedFile = extractUploadedFile(result, fileType);
logger.info('File forwarded to storage', { fileName, message: result.message_id });
return {
telegramFileId: uploadedFile?.file_id || '',
telegramFileUniqueId: uploadedFile?.file_unique_id || '',
storageMessageId: result.message_id,
};
} catch (error: unknown) {
logger.error('Failed to forward file to storage', {
fileName,
error: error instanceof Error ? error.message : String(error),
});
throw error;
}
};
export const getFileInfo = async (telegramFileId: string): Promise<TelegramFileInfo> => {
let lastError: unknown;
for (const activeBot of bots) {
try {
const result = await activeBot.telegram.getFile(telegramFileId);
const fileData = result as unknown as Omit<TelegramFileInfo, 'bot_token'>;
return {
file_size: fileData.file_size || 0,
mime_type: fileData.mime_type || 'application/octet-stream',
file_path: fileData.file_path || '',
bot_token: activeBot.telegram.token,
};
} catch (error: unknown) {
lastError = error;
const errorStr = error instanceof Error ? error.message : String(error);
if (
errorStr.includes('wrong file_id') ||
errorStr.includes('file is temporarily unavailable') ||
errorStr.includes('retry after')
) {
continue;
}
throw error;
}
}
logger.error('Failed to get file info from any bot', {
error: lastError instanceof Error ? lastError.message : String(lastError),
});
throw lastError;
};
export const getBot = (): Telegraf => bots[nextBotIndex];
export const getCurrentBotIndex = (): number => nextBotIndex;
-42
View File
@@ -1,42 +0,0 @@
import PQueue from 'p-queue';
import { config } from '../env';
import logger from './logger';
const uploadQueue = new PQueue({
concurrency: config.uploadConcurrency,
});
// Monitor queue events
uploadQueue.on('add', () => {
const stats = getQueueStats();
if (stats.size > 5) {
logger.warn('Upload queue building up', { pending: stats.pending, size: stats.size });
}
});
uploadQueue.on('next', () => {
const stats = getQueueStats();
logger.debug('Processing next upload', { pending: stats.pending, size: stats.size });
});
export const enqueueUpload = <T>(task: () => Promise<T>): Promise<T> => {
return uploadQueue.add(task);
};
export const getQueueStats = () => ({
pending: uploadQueue.pending,
size: uploadQueue.size,
});
export const getQueueSize = (): number => uploadQueue.size;
export const getPendingCount = (): number => uploadQueue.pending;
export const clearQueue = async (): Promise<void> => {
uploadQueue.clear();
await uploadQueue.onIdle();
};
export const waitForQueue = async (): Promise<void> => {
await uploadQueue.onIdle();
};
+2 -2
View File
@@ -4,7 +4,7 @@ import { db, files as fileSchema } from '../db';
import type { NewFile } from '../db/schema';
import { config } from '../env';
import { cleanupTempFile } from './file';
import { forwardToStorage } from './telegram';
import { botPool } from '../infrastructure/telegram/bot-pool';
import { createZip, type ZipEntry } from './zip';
export type PreparedUpload = {
@@ -86,7 +86,7 @@ const flushUploads = async (): Promise<void> => {
);
zipTempPath = zip.tempPath;
const archiveFileName = `filedrop-${nanoid()}.zip`;
const archiveResult = await forwardToStorage(
const archiveResult = await botPool.forwardToStorage(
createReadStream(zip.tempPath),
archiveFileName,
'document',