Skip to content

A free and open source instant messaging and VoIP chat app built for friends, groups, and communities.

TypeScript fluxerfluxerapp

refactor(api): strip uploaded media through the media proxy

Hampus824c38d49c1b
diff --git a/fluxer_api/src/api/channel/services/message/AttachmentProcessingService.ts b/fluxer_api/src/api/channel/services/message/AttachmentProcessingService.ts
index 33df9fc80..e2531bfac 100644
--- a/fluxer_api/src/api/channel/services/message/AttachmentProcessingService.ts
+++ b/fluxer_api/src/api/channel/services/message/AttachmentProcessingService.ts
@@ -14,7 +14,7 @@ import type {
MediaProxyNsfwMode,
} from '@app/api/infrastructure/IMediaService';
import type {ISnowflakeService} from '@app/api/infrastructure/ISnowflakeService';
-import type {IStorageService, ProcessedStorageObjectMetadata} from '@app/api/infrastructure/IStorageService';
+import type {IStorageService} from '@app/api/infrastructure/IStorageService';
import {hashFileSha256} from '@app/api/infrastructure/StorageObjectHelpers';
import {Logger} from '@app/api/Logger';
import type {Channel} from '@app/api/models/Channel';
@@ -63,6 +63,14 @@ interface ProcessedAttachment {
sniffedContentType: string | null;
}
+interface StoredAttachmentObject {
+ contentType: string;
+ contentLength: number;
+ contentHash: string;
+ width?: number;
+ height?: number;
+}
+
export class AttachmentProcessingService {
constructor(
private storageService: IStorageService,
@@ -86,46 +94,28 @@ export class AttachmentProcessingService {
hasVirusDetected: boolean;
}> {
validateAttachmentIds(params.attachments.map((a) => ({id: BigInt(a.id)})));
- const retainedLocalPaths: Array<string> = [];
- let results: Array<ProcessedAttachment>;
- let copyResults: Array<ProcessedStorageObjectMetadata | null>;
- let hasVirusDetected: boolean;
- try {
- results = await mapWithConcurrency(
- params.attachments,
- ATTACHMENT_PROCESSING_CONCURRENCY,
- async (attachment, index) => {
- const result = await this.processAttachment({
- message: params.message,
- attachment,
- index,
- uploadUserId: params.uploadUserId,
- uploadChannelId: params.uploadChannelId,
- channel: params.channel,
- guild: params.guild,
- member: params.member,
- nsfwMode: params.nsfwMode,
- });
- if (result.sourceLocalPath !== null) retainedLocalPaths.push(result.sourceLocalPath);
- return result;
- },
- );
- hasVirusDetected = results.some((result) => result.hasVirusDetected);
- copyResults = hasVirusDetected
- ? []
- : await mapWithConcurrency(results, ATTACHMENT_PROCESSING_CONCURRENCY, (result) =>
- this.storageService.copyObjectWithMetadataStripping({
- sourceBucket: result.copyOperation.sourceBucket,
- sourceKey: result.copyOperation.sourceKey,
- destinationBucket: result.copyOperation.destinationBucket,
- destinationKey: result.copyOperation.destinationKey,
- contentType: result.copyOperation.newContentType,
- ...(result.sourceLocalPath ? {sourceLocalPath: result.sourceLocalPath} : {}),
- }),
- );
- } finally {
- await Promise.all(retainedLocalPaths.map((localPath) => fs.promises.unlink(localPath).catch(() => undefined)));
- }
+ const results = await mapWithConcurrency(
+ params.attachments,
+ ATTACHMENT_PROCESSING_CONCURRENCY,
+ (attachment, index) =>
+ this.processAttachment({
+ message: params.message,
+ attachment,
+ index,
+ uploadUserId: params.uploadUserId,
+ uploadChannelId: params.uploadChannelId,
+ channel: params.channel,
+ guild: params.guild,
+ member: params.member,
+ nsfwMode: params.nsfwMode,
+ }),
+ );
+ const hasVirusDetected = results.some((result) => result.hasVirusDetected);
+ const copyResults = hasVirusDetected
+ ? []
+ : await mapWithConcurrency(results, ATTACHMENT_PROCESSING_CONCURRENCY, (result) =>
+ this.storeAttachmentObject(result.copyOperation),
+ );
if (hasVirusDetected) {
for (const result of results) {
this.deleteUploadObject(result.copyOperation.sourceBucket, result.copyOperation.sourceKey);
@@ -264,8 +254,7 @@ export class AttachmentProcessingService {
nsfw = metadata.nsfw;
}
}
- const needsLocalDownload =
- this.virusScanService.enabled || metadata == null || isSupportedMediaContentType(contentType);
+ const needsLocalDownload = this.virusScanService.enabled || metadata == null;
let sourceLocalPath: string | null = null;
try {
if (needsLocalDownload) {
@@ -340,11 +329,50 @@ export class AttachmentProcessingService {
applyFinalObjectMetadata,
sniffedContentType,
};
- } catch (error) {
+ } finally {
if (sourceLocalPath) {
await fs.promises.unlink(sourceLocalPath).catch(() => undefined);
}
- throw error;
+ }
+ }
+
+ private async storeAttachmentObject(operation: AttachmentCopyOperation): Promise<StoredAttachmentObject | null> {
+ const {sourceBucket, sourceKey, destinationBucket, destinationKey, newContentType} = operation;
+ const copyOriginal = () =>
+ this.storageService.copyObject({sourceBucket, sourceKey, destinationBucket, destinationKey, newContentType});
+ if (!isSupportedMediaContentType(newContentType)) {
+ await copyOriginal();
+ return null;
+ }
+ const strippedPath = temporaryFile();
+ try {
+ const stripped = await this.mediaService.stripObjectMetadata(
+ {bucket: sourceBucket, key: sourceKey},
+ newContentType,
+ strippedPath,
+ );
+ if (!stripped) {
+ Logger.error(
+ {contentType: newContentType, sourceBucket, sourceKey},
+ 'Failed to strip attachment media metadata',
+ );
+ await copyOriginal();
+ return null;
+ }
+ const [contentHash, {size: contentLength}] = await Promise.all([
+ hashFileSha256(strippedPath),
+ fs.promises.stat(strippedPath),
+ ]);
+ await this.storageService.uploadObjectFromFile({
+ bucket: destinationBucket,
+ key: destinationKey,
+ filePath: strippedPath,
+ contentType: stripped.contentType,
+ contentLength,
+ });
+ return {...stripped, contentLength, contentHash};
+ } finally {
+ await fs.promises.unlink(strippedPath).catch(() => undefined);
}
}
diff --git a/fluxer_api/src/api/infrastructure/AvatarService.ts b/fluxer_api/src/api/infrastructure/AvatarService.ts
index a158cef9c..8b35e77c5 100644
--- a/fluxer_api/src/api/infrastructure/AvatarService.ts
+++ b/fluxer_api/src/api/infrastructure/AvatarService.ts
@@ -7,7 +7,6 @@ import {contentModerationService} from '@app/api/infrastructure/ContentModeratio
import type {IMediaService} from '@app/api/infrastructure/IMediaService';
import {decodeValidatedImage, resolveAssetSizeLimit} from '@app/api/infrastructure/ImageUploadValidation';
import type {IStorageService} from '@app/api/infrastructure/IStorageService';
-import {stripNonJpegImageMetadata} from '@app/api/infrastructure/StorageObjectHelpers';
import {Logger} from '@app/api/Logger';
import type {LimitConfigService} from '@app/api/limits/LimitConfigService';
import {bannedAvatarHashCache} from '@app/api/middleware/BannedAvatarHashCache';
@@ -50,7 +49,12 @@ export class AvatarService {
if (isJpeg) {
return await sharp(buffer).jpeg({quality: 100}).toBuffer();
}
- return await stripNonJpegImageMetadata(buffer);
+ const stripped = await this.mediaService.stripImageMetadata(buffer);
+ if (stripped) {
+ return stripped;
+ }
+ Logger.error({format}, 'Failed to strip image metadata, using original buffer');
+ return buffer;
} catch (error) {
Logger.error({error, format}, 'Failed to strip image metadata, using original buffer');
return buffer;
diff --git a/fluxer_api/src/api/infrastructure/ChangeFeedStorageService.ts b/fluxer_api/src/api/infrastructure/ChangeFeedStorageService.ts
index fd5a57a29..18e8898b2 100644
--- a/fluxer_api/src/api/infrastructure/ChangeFeedStorageService.ts
+++ b/fluxer_api/src/api/infrastructure/ChangeFeedStorageService.ts
@@ -1,7 +1,7 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
import {Config} from '@app/api/Config';
-import type {IStorageService, ProcessedStorageObjectMetadata} from '@app/api/infrastructure/IStorageService';
+import type {IStorageService} from '@app/api/infrastructure/IStorageService';
import type {StorageChangeFeed, StorageChangeOp} from '@app/api/infrastructure/StorageChangeFeed';
type Params<K extends keyof IStorageService> = Parameters<IStorageService[K]>;
@@ -79,17 +79,6 @@ export class ChangeFeedStorageService implements IStorageService {
this.emit(params.destinationBucket, params.destinationKey, 'put', {contentType: params.newContentType});
}
- async copyObjectWithMetadataStripping(
- params: Params<'copyObjectWithMetadataStripping'>[0],
- ): Promise<ProcessedStorageObjectMetadata | null> {
- const processed = await this.inner.copyObjectWithMetadataStripping(params);
- this.emit(params.destinationBucket, params.destinationKey, 'put', {
- size: processed?.contentLength,
- contentType: processed?.contentType ?? params.contentType,
- });
- return processed;
- }
-
getPresignedDownloadURL(...args: Params<'getPresignedDownloadURL'>): Result<'getPresignedDownloadURL'> {
return this.inner.getPresignedDownloadURL(...args);
}
diff --git a/fluxer_api/src/api/infrastructure/EntityAssetService.ts b/fluxer_api/src/api/infrastructure/EntityAssetService.ts
index e4f7c3561..0e2944e61 100644
--- a/fluxer_api/src/api/infrastructure/EntityAssetService.ts
+++ b/fluxer_api/src/api/infrastructure/EntityAssetService.ts
@@ -153,12 +153,17 @@ export class EntityAssetService {
contentType,
};
if (newHash === previousHash) return prepared;
- let uploadBuffer = imageBuffer;
+ let uploadBuffer: Uint8Array = imageBuffer;
try {
const isJpeg = format === 'jpg' || format === 'jpeg';
- uploadBuffer = isJpeg
+ const stripped = isJpeg
? await sharp(imageBuffer).jpeg({quality: 100}).toBuffer()
- : await stripNonJpegImageMetadata(imageBuffer);
+ : await this.mediaService.stripImageMetadata(imageBuffer);
+ if (stripped) {
+ uploadBuffer = stripped;
+ } else {
+ Logger.error({assetType, entityType}, 'Failed to strip metadata from entity asset, uploading original');
+ }
} catch (error) {
Logger.error({error, assetType, entityType}, 'Failed to strip metadata from entity asset, uploading original');
}
diff --git a/fluxer_api/src/api/infrastructure/IMediaService.ts b/fluxer_api/src/api/infrastructure/IMediaService.ts
index 0011375e1..e7cd44215 100644
--- a/fluxer_api/src/api/infrastructure/IMediaService.ts
+++ b/fluxer_api/src/api/infrastructure/IMediaService.ts
@@ -65,6 +65,17 @@ export interface MediaProxySniffResponse {
content_type: string | null;
}
+export interface MediaProxyStorageObject {
+ bucket: string;
+ key: string;
+}
+
+export interface MediaProxyStrippedObject {
+ contentType: string;
+ width?: number;
+ height?: number;
+}
+
export abstract class IMediaService {
abstract getMetadata(
request: MediaProxyMetadataRequest,
@@ -74,4 +85,14 @@ export abstract class IMediaService {
abstract getExternalMediaProxyURL(url: string): string;
abstract sniffUpload(uploadFilename: string): Promise<MediaProxySniffResponse | null>;
+
+ abstract stripObjectMetadata(
+ source: MediaProxyStorageObject,
+ contentType: string,
+ outputPath: string,
+ ): Promise<MediaProxyStrippedObject | null>;
+
+ abstract stripImageMetadata(image: Uint8Array): Promise<Uint8Array | null>;
+
+ abstract getAudioDurationSeconds(base64: string): Promise<number | null>;
}
diff --git a/fluxer_api/src/api/infrastructure/IStorageService.ts b/fluxer_api/src/api/infrastructure/IStorageService.ts
index 09408ef8a..7a3071885 100644
--- a/fluxer_api/src/api/infrastructure/IStorageService.ts
+++ b/fluxer_api/src/api/infrastructure/IStorageService.ts
@@ -30,14 +30,6 @@ export class StorageObjectListingOverflowError extends Error {
}
}
-export interface ProcessedStorageObjectMetadata {
- contentType: string;
- contentLength: number;
- contentHash: string;
- width?: number;
- height?: number;
-}
-
export interface IStorageService {
uploadObject(params: {
bucket: string;
@@ -82,14 +74,6 @@ export interface IStorageService {
destinationKey: string;
newContentType?: string;
}): Promise<void>;
- copyObjectWithMetadataStripping(params: {
- sourceBucket: string;
- sourceKey: string;
- destinationBucket: string;
- destinationKey: string;
- contentType: string;
- sourceLocalPath?: string;
- }): Promise<ProcessedStorageObjectMetadata | null>;
getPresignedDownloadURL(params: {
bucket: string;
key: string;
diff --git a/fluxer_api/src/api/infrastructure/MediaService.ts b/fluxer_api/src/api/infrastructure/MediaService.ts
index 53f3ff153..f28473700 100644
--- a/fluxer_api/src/api/infrastructure/MediaService.ts
+++ b/fluxer_api/src/api/infrastructure/MediaService.ts
@@ -1,5 +1,9 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
+import fs from 'node:fs';
+import {Readable} from 'node:stream';
+import {pipeline} from 'node:stream/promises';
+import type {ReadableStream as NodeReadableStream} from 'node:stream/web';
import {signAttachmentUrl} from '@app/api/attachment/AttachmentUrls';
import {Config} from '@app/api/Config';
import {
@@ -10,6 +14,8 @@ import {
type MediaProxyMetadataResponse,
type MediaProxyNsfwMode,
type MediaProxySniffResponse,
+ type MediaProxyStorageObject,
+ type MediaProxyStrippedObject,
} from '@app/api/infrastructure/IMediaService';
import {Logger} from '@app/api/Logger';
import * as FetchUtils from '@app/api/utils/FetchUtils';
@@ -24,6 +30,16 @@ type MediaProxyRequestBody =
| {
type: 'upload';
upload_filename: string;
+ }
+ | {
+ type: 's3';
+ bucket: string;
+ key: string;
+ content_type: string;
+ }
+ | {
+ type: 'base64';
+ base64: string;
};
const MEDIA_PROXY_METADATA_MAX_BYTES = 256 * 1024;
@@ -32,6 +48,12 @@ const MEDIA_PROXY_ERROR_MAX_BYTES = 16 * 1024;
const MEDIA_PROXY_SNIFF_MAX_BYTES = 1024;
const MEDIA_PROXY_REQUEST_TIMEOUT_MS = ms('30 seconds');
const MEDIA_PROXY_SNIFF_TIMEOUT_MS = ms('2 seconds');
+const MEDIA_PROXY_STRIP_TIMEOUT_MS = ms('10 minutes') + ms('30 seconds');
+const MEDIA_PROXY_STRIPPED_IMAGE_MAX_BYTES = 64 * 1024 * 1024;
+const MEDIA_PROXY_AUDIO_DURATION_TIMEOUT_MS = ms('5 seconds');
+const MEDIA_PROXY_AUDIO_DURATION_MAX_BYTES = 1024;
+const MEDIA_PROXY_WIDTH_HEADER = 'x-fluxer-media-width';
+const MEDIA_PROXY_HEIGHT_HEADER = 'x-fluxer-media-height';
const MEDIA_PROXY_BUFFERED_INPUT_MAX_BYTES = 500 * 1024 * 1024;
const MEDIA_PROXY_SPOOLED_INPUT_BYTES_PER_SECOND = 16 * 1024 * 1024;
@@ -66,6 +88,24 @@ function isMediaProxyMetadataResponse(value: unknown): value is MediaProxyMetada
);
}
+function isMediaProxyAudioDurationResponse(value: unknown): value is {duration_seconds: number | null} {
+ return isJsonRecord(value) && (value.duration_seconds === null || typeof value.duration_seconds === 'number');
+}
+
+function positiveIntegerHeader(headers: Headers, name: string): number | undefined {
+ const value = Number(headers.get(name));
+ return Number.isSafeInteger(value) && value > 0 ? value : undefined;
+}
+
+function strippedObjectFromHeaders(headers: Headers, fallbackContentType: string): MediaProxyStrippedObject {
+ const width = positiveIntegerHeader(headers, MEDIA_PROXY_WIDTH_HEADER);
+ const height = positiveIntegerHeader(headers, MEDIA_PROXY_HEIGHT_HEADER);
+ return {
+ contentType: headers.get('content-type') ?? fallbackContentType,
+ ...(width && height ? {width, height} : {}),
+ };
+}
+
function metadataResponseLimit(request: MediaProxyMetadataRequest): number {
if ((request.type === 'external' || request.type === 's3') && request.with_base64) {
return MEDIA_PROXY_METADATA_WITH_BASE64_MAX_BYTES;
@@ -190,6 +230,68 @@ export class MediaService extends IMediaService {
}
}
+ async stripObjectMetadata(
+ source: MediaProxyStorageObject,
+ contentType: string,
+ outputPath: string,
+ ): Promise<MediaProxyStrippedObject | null> {
+ const response = await this.makeRequest(
+ '/_strip',
+ {type: 's3', bucket: source.bucket, key: source.key, content_type: contentType},
+ MEDIA_PROXY_STRIP_TIMEOUT_MS,
+ );
+ if (!response?.body) return null;
+ try {
+ await pipeline(
+ Readable.fromWeb(response.body as NodeReadableStream<Uint8Array>),
+ fs.createWriteStream(outputPath),
+ );
+ return strippedObjectFromHeaders(response.headers, contentType);
+ } catch (error) {
+ Logger.error({error, bucket: source.bucket, key: source.key}, 'Failed to read media proxy strip response');
+ return null;
+ }
+ }
+
+ async stripImageMetadata(image: Uint8Array): Promise<Uint8Array | null> {
+ const response = await this.makeRequest(
+ '/_strip',
+ {type: 'base64', base64: Buffer.from(image).toString('base64')},
+ MEDIA_PROXY_REQUEST_TIMEOUT_MS,
+ );
+ if (!response) return null;
+ try {
+ return await FetchUtils.streamToBufferWithLimit(response.body, {
+ maxBytes: MEDIA_PROXY_STRIPPED_IMAGE_MAX_BYTES,
+ headers: response.headers,
+ description: 'Media proxy strip response',
+ });
+ } catch (error) {
+ Logger.error({error}, 'Failed to read media proxy strip response');
+ return null;
+ }
+ }
+
+ async getAudioDurationSeconds(base64: string): Promise<number | null> {
+ const response = await this.makeRequest(
+ '/_audio_duration',
+ {type: 'base64', base64},
+ MEDIA_PROXY_AUDIO_DURATION_TIMEOUT_MS,
+ );
+ if (!response) return null;
+ try {
+ const responseText = await FetchUtils.streamToStringWithLimit(response.body, {
+ maxBytes: MEDIA_PROXY_AUDIO_DURATION_MAX_BYTES,
+ headers: response.headers,
+ description: 'Media proxy audio duration response',
+ });
+ return parseJsonWithGuard(responseText, isMediaProxyAudioDurationResponse)?.duration_seconds ?? null;
+ } catch (error) {
+ Logger.error({error}, 'Failed to read media proxy audio duration response');
+ return null;
+ }
+ }
+
private async makeRequest(
endpoint: string,
body: MediaProxyRequestBody,
diff --git a/fluxer_api/src/api/infrastructure/StorageObjectHelpers.test.ts b/fluxer_api/src/api/infrastructure/StorageObjectHelpers.test.ts
deleted file mode 100644
index 0b5ba7f32..000000000
--- a/fluxer_api/src/api/infrastructure/StorageObjectHelpers.test.ts
+++ /dev/null
@@ -1,117 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {stripNonJpegImageMetadataForUpload} from '@app/api/infrastructure/StorageObjectHelpers';
-import {describe, expect, it} from 'vitest';
-
-const PNG_SIGNATURE = new Uint8Array([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]);
-
-function concatBytes(chunks: ReadonlyArray<Uint8Array>): Uint8Array {
- const totalLength = chunks.reduce((sum, chunk) => sum + chunk.length, 0);
- const out = new Uint8Array(totalLength);
- let offset = 0;
- for (const chunk of chunks) {
- out.set(chunk, offset);
- offset += chunk.length;
- }
- return out;
-}
-
-function textBytes(value: string): Uint8Array {
- const encoded = new TextEncoder().encode(value);
- const out = new Uint8Array(encoded.length);
- out.set(encoded);
- return out;
-}
-
-function chunk(type: string, data: Uint8Array<ArrayBufferLike> = new Uint8Array()): Uint8Array {
- const out = new Uint8Array(12 + data.length);
- out[0] = (data.length >>> 24) & 0xff;
- out[1] = (data.length >>> 16) & 0xff;
- out[2] = (data.length >>> 8) & 0xff;
- out[3] = data.length & 0xff;
- out.set(textBytes(type), 4);
- out.set(data, 8);
- return out;
-}
-
-function chunkNames(data: Uint8Array): Array<string> {
- const names: Array<string> = [];
- let offset = PNG_SIGNATURE.length;
- while (offset + 12 <= data.length) {
- const length =
- ((data[offset]! << 24) | (data[offset + 1]! << 16) | (data[offset + 2]! << 8) | data[offset + 3]!) >>> 0;
- names.push(String.fromCharCode(data[offset + 4]!, data[offset + 5]!, data[offset + 6]!, data[offset + 7]!));
- offset += 12 + length;
- }
- return names;
-}
-
-function pngWithPrivateChunks(): Uint8Array {
- return concatBytes([
- PNG_SIGNATURE,
- chunk('IHDR', new Uint8Array(13)),
- chunk('tEXt', textBytes('GPS=1,2')),
- chunk('prIv', textBytes('private metadata')),
- chunk('IDAT', new Uint8Array([1, 2, 3])),
- chunk('IEND'),
- ]);
-}
-
-describe('stripNonJpegImageMetadataForUpload', () => {
- it('strips PNG metadata and unknown ancillary chunks while preserving image chunks', async () => {
- const input = pngWithPrivateChunks();
- const stripped = await stripNonJpegImageMetadataForUpload(input, 'image/png');
- expect(stripped.contentType).toBe('image/png');
- expect(chunkNames(stripped.body)).toEqual(['IHDR', 'IDAT', 'IEND']);
- });
- it('preserves APNG animation chunks', async () => {
- const input = concatBytes([
- PNG_SIGNATURE,
- chunk('IHDR', new Uint8Array(13)),
- chunk('acTL', new Uint8Array(8)),
- chunk('fcTL', new Uint8Array(26)),
- chunk('tEXt', textBytes('camera=private')),
- chunk('fdAT', new Uint8Array([1, 2, 3])),
- chunk('IDAT', new Uint8Array([4, 5, 6])),
- chunk('IEND'),
- ]);
- const stripped = await stripNonJpegImageMetadataForUpload(input, 'image/apng');
- expect(stripped.contentType).toBe('image/apng');
- expect(chunkNames(stripped.body)).toEqual(['IHDR', 'acTL', 'fcTL', 'fdAT', 'IDAT', 'IEND']);
- });
-});
-
-function riffChunk(type: string, data: Uint8Array): Uint8Array {
- const out = new Uint8Array(8 + data.length + (data.length & 1));
- out.set(textBytes(type), 0);
- new DataView(out.buffer).setUint32(4, data.length, true);
- out.set(data, 8);
- return out;
-}
-
-function webp(chunks: ReadonlyArray<Uint8Array>): Uint8Array {
- const body = concatBytes(chunks);
- const header = concatBytes([textBytes('RIFF'), new Uint8Array(4), textBytes('WEBP')]);
- new DataView(header.buffer).setUint32(4, 4 + body.length, true);
- return concatBytes([header, body]);
-}
-
-describe('stripNonJpegImageMetadataForUpload for WebP', () => {
- it('drops EXIF and XMP chunks without re-encoding frames', async () => {
- const vp8x = new Uint8Array(10);
- vp8x[0] = 0x02 | 0x08 | 0x04;
- const anmf = riffChunk('ANMF', new Uint8Array([9, 8, 7]));
- const input = webp([
- riffChunk('VP8X', vp8x),
- riffChunk('ANIM', new Uint8Array(6)),
- anmf,
- riffChunk('EXIF', textBytes('GPS=1,2')),
- riffChunk('XMP ', textBytes('private metadata')),
- ]);
- const stripped = await stripNonJpegImageMetadataForUpload(input, 'image/webp');
- const expectedVp8x = new Uint8Array(10);
- expectedVp8x[0] = 0x02;
- expect(stripped.contentType).toBe('image/webp');
- expect(stripped.body).toEqual(webp([riffChunk('VP8X', expectedVp8x), riffChunk('ANIM', new Uint8Array(6)), anmf]));
- });
-});
diff --git a/fluxer_api/src/api/infrastructure/StorageService.ts b/fluxer_api/src/api/infrastructure/StorageService.ts
index e55a744c7..9c8ec418a 100644
--- a/fluxer_api/src/api/infrastructure/StorageService.ts
+++ b/fluxer_api/src/api/infrastructure/StorageService.ts
@@ -9,11 +9,9 @@ import {promisify} from 'node:util';
import {Config} from '@app/api/Config';
import {
type IStorageService,
- type ProcessedStorageObjectMetadata,
StorageObjectListingOverflowError,
StorageObjectRangeNotSatisfiableError,
} from '@app/api/infrastructure/IStorageService';
-import {processMediaFile} from '@app/api/infrastructure/StorageObjectHelpers';
import {Logger} from '@app/api/Logger';
import {
AbortMultipartUploadCommand,
@@ -34,7 +32,6 @@ import {
import {Upload} from '@aws-sdk/lib-storage';
import {getSignedUrl} from '@aws-sdk/s3-request-presigner';
import type {S3ProviderSettings} from '@fluxer/config/src/S3ProviderSettings';
-import {isSupportedMediaContentType} from '@pkgs/mime_utils/src/ContentTypeUtils';
import {seconds} from 'itty-time';
import {temporaryFile} from 'tempy';
@@ -574,74 +571,6 @@ export class StorageService implements IStorageService {
}
}
- async copyObjectWithMetadataStripping({
- sourceBucket,
- sourceKey,
- destinationBucket,
- destinationKey,
- contentType,
- sourceLocalPath,
- }: {
- sourceBucket: string;
- sourceKey: string;
- destinationBucket: string;
- destinationKey: string;
- contentType: string;
- sourceLocalPath?: string;
- }): Promise<ProcessedStorageObjectMetadata | null> {
- if (!isSupportedMediaContentType(contentType)) {
- await this.copyObject({
- sourceBucket,
- sourceKey,
- destinationBucket,
- destinationKey,
- newContentType: contentType,
- });
- return null;
- }
- const downloadedSource = sourceLocalPath ?? temporaryFile();
- const ownsDownload = !sourceLocalPath;
- const processedPath = temporaryFile();
- try {
- if (ownsDownload) {
- await this.writeObjectToDisk(sourceBucket, sourceKey, downloadedSource);
- }
- const processed = await processMediaFile(downloadedSource, processedPath, contentType).catch((error) => {
- Logger.error({error, contentType, sourceBucket, sourceKey}, 'Failed to strip attachment media metadata');
- return null;
- });
- if (!processed) {
- await this.copyObject({
- sourceBucket,
- sourceKey,
- destinationBucket,
- destinationKey,
- newContentType: contentType,
- });
- return null;
- }
- await this.uploadObjectFromFile({
- bucket: destinationBucket,
- key: destinationKey,
- filePath: processed.filePath,
- contentType: processed.contentType,
- contentLength: processed.contentLength,
- });
- return {
- contentType: processed.contentType,
- contentLength: processed.contentLength,
- contentHash: processed.contentHash,
- ...(processed.width != null ? {width: processed.width} : {}),
- ...(processed.height != null ? {height: processed.height} : {}),
- };
- } finally {
- await fs.promises.unlink(processedPath).catch(() => undefined);
- if (ownsDownload) {
- await fs.promises.unlink(downloadedSource).catch(() => undefined);
- }
- }
- }
-
async uploadAvatar(params: {prefix: string; key: string; body: Uint8Array}): Promise<void> {
const {prefix, key, body} = params;
await this.uploadObject({
diff --git a/fluxer_api/src/api/infrastructure/StorageServiceCrossBucketCopy.test.ts b/fluxer_api/src/api/infrastructure/StorageServiceCrossBucketCopy.test.ts
index 6629eec80..f3acf271c 100644
--- a/fluxer_api/src/api/infrastructure/StorageServiceCrossBucketCopy.test.ts
+++ b/fluxer_api/src/api/infrastructure/StorageServiceCrossBucketCopy.test.ts
@@ -118,40 +118,19 @@ describe('StorageService copies on providers that reject cross-bucket CopyObject
it('stores a non-media attachment in the CDN bucket', async () => {
ceph.objects.set(`${UPLOADS}/upload-1`, {body: PDF, contentType: 'application/octet-stream'});
- await expect(
- storage().copyObjectWithMetadataStripping({
- sourceBucket: UPLOADS,
- sourceKey: 'upload-1',
- destinationBucket: CDN,
- destinationKey: 'attachments/1/2/file.pdf',
- contentType: 'application/pdf',
- }),
- ).resolves.toBeNull();
+ await storage().copyObject({
+ sourceBucket: UPLOADS,
+ sourceKey: 'upload-1',
+ destinationBucket: CDN,
+ destinationKey: 'attachments/1/2/file.pdf',
+ newContentType: 'application/pdf',
+ });
const stored = ceph.objects.get(`${CDN}/attachments/1/2/file.pdf`);
expect(stored?.contentType).toBe('application/pdf');
expect(Buffer.from(stored!.body).equals(Buffer.from(PDF))).toBe(true);
});
- it('keeps the original file when media processing fails', async () => {
- const brokenHeic = new Uint8Array(4096).fill(7);
- ceph.objects.set(`${UPLOADS}/upload-2`, {body: brokenHeic, contentType: 'application/octet-stream'});
-
- await expect(
- storage().copyObjectWithMetadataStripping({
- sourceBucket: UPLOADS,
- sourceKey: 'upload-2',
- destinationBucket: CDN,
- destinationKey: 'attachments/1/3/photo.heic',
- contentType: 'image/heic',
- }),
- ).resolves.toBeNull();
-
- const stored = ceph.objects.get(`${CDN}/attachments/1/3/photo.heic`);
- expect(stored?.contentType).toBe('image/heic');
- expect(Buffer.from(stored!.body).equals(Buffer.from(brokenHeic))).toBe(true);
- });
-
it('keeps the source headers when no new content type is given', async () => {
ceph.objects.set(`${CDN}/avatars/1/a.png`, {
body: PDF,
diff --git a/fluxer_api/src/api/infrastructure/StorageServiceEndpointPath.test.ts b/fluxer_api/src/api/infrastructure/StorageServiceEndpointPath.test.ts
index cb3796fe0..1c8e2bad5 100644
--- a/fluxer_api/src/api/infrastructure/StorageServiceEndpointPath.test.ts
+++ b/fluxer_api/src/api/infrastructure/StorageServiceEndpointPath.test.ts
@@ -97,15 +97,13 @@ describe('StorageService with every bucket inside one real bucket', () => {
const service = storage(`https://${HOST}/${REAL_BUCKET}`, true);
await service.uploadObject({bucket: 'fluxer-uploads', key: 'upload 1', body: PDF});
- await expect(
- service.copyObjectWithMetadataStripping({
- sourceBucket: 'fluxer-uploads',
- sourceKey: 'upload 1',
- destinationBucket: 'fluxer-cdn',
- destinationKey: 'attachments/1/2/file.pdf',
- contentType: 'application/pdf',
- }),
- ).resolves.toBeNull();
+ await service.copyObject({
+ sourceBucket: 'fluxer-uploads',
+ sourceKey: 'upload 1',
+ destinationBucket: 'fluxer-cdn',
+ destinationKey: 'attachments/1/2/file.pdf',
+ newContentType: 'application/pdf',
+ });
expect(objects.get('fluxer-cdn/attachments/1/2/file.pdf')?.contentType).toBe('application/pdf');
await expect(service.readObject('fluxer-cdn', 'attachments/1/2/file.pdf')).resolves.toEqual(PDF);
@@ -141,15 +139,13 @@ describe.each(['NoSuchBucket', 'AccessDenied'])(
const service = storage(`https://${REAL_BUCKET}.${HOST}`, true);
await service.uploadObject({bucket: 'fluxer-uploads', key: 'upload 1', body: PDF});
- await expect(
- service.copyObjectWithMetadataStripping({
- sourceBucket: 'fluxer-uploads',
- sourceKey: 'upload 1',
- destinationBucket: 'fluxer',
- destinationKey: 'attachments/1/2/file.pdf',
- contentType: 'application/pdf',
- }),
- ).resolves.toBeNull();
+ await service.copyObject({
+ sourceBucket: 'fluxer-uploads',
+ sourceKey: 'upload 1',
+ destinationBucket: 'fluxer',
+ destinationKey: 'attachments/1/2/file.pdf',
+ newContentType: 'application/pdf',
+ });
expect(objects.get('fluxer/attachments/1/2/file.pdf')).toEqual({body: PDF, contentType: 'application/pdf'});
});
diff --git a/fluxer_api/src/api/test/TestMediaService.ts b/fluxer_api/src/api/test/TestMediaService.ts
index c3965a428..a198fe0a8 100644
--- a/fluxer_api/src/api/test/TestMediaService.ts
+++ b/fluxer_api/src/api/test/TestMediaService.ts
@@ -1,12 +1,15 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
import crypto from 'node:crypto';
+import fs from 'node:fs';
import {Config} from '@app/api/Config';
import {
IMediaService,
type MediaProxyMetadataRequest,
type MediaProxyMetadataResponse,
type MediaProxySniffResponse,
+ type MediaProxyStorageObject,
+ type MediaProxyStrippedObject,
} from '@app/api/infrastructure/IMediaService';
import type {IStorageService} from '@app/api/infrastructure/IStorageService';
@@ -86,6 +89,23 @@ export class TestMediaService extends IMediaService {
return {content_type: null};
}
+ async stripObjectMetadata(
+ source: MediaProxyStorageObject,
+ contentType: string,
+ outputPath: string,
+ ): Promise<MediaProxyStrippedObject | null> {
+ await fs.promises.writeFile(outputPath, await this.storageService.readObject(source.bucket, source.key));
+ return {contentType, width: 100, height: 100};
+ }
+
+ async stripImageMetadata(image: Uint8Array): Promise<Uint8Array | null> {
+ return image;
+ }
+
+ async getAudioDurationSeconds(_base64: string): Promise<number | null> {
+ return null;
+ }
+
private analyzeBase64Image(base64: string): MediaProxyMetadataResponse | null {
try {
const buffer = Buffer.from(base64, 'base64');
diff --git a/fluxer_api/src/api/user/entrance_sound/EntranceSoundDurationProbe.ts b/fluxer_api/src/api/user/entrance_sound/EntranceSoundDurationProbe.ts
deleted file mode 100644
index c88f9041a..000000000
--- a/fluxer_api/src/api/user/entrance_sound/EntranceSoundDurationProbe.ts
+++ /dev/null
@@ -1,158 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {execFile} from 'node:child_process';
-import fs from 'node:fs/promises';
-import {promisify} from 'node:util';
-import {Logger} from '@app/api/Logger';
-import {isJsonRecord, parseJsonWithGuard} from '@app/api/utils/JsonBoundaryUtils';
-import type {EntranceSoundExtension} from '@fluxer/constants/src/EntranceSoundConstants';
-import {temporaryFile} from 'tempy';
-
-const execFilePromise = promisify(execFile);
-const FFPROBE_TIMEOUT_MS = 5_000;
-const FFPROBE_MAX_BUFFER_BYTES = 512 * 1024;
-
-interface FfprobeFrame {
- duration_time?: string;
- pkt_duration_time?: string;
-}
-
-interface FfprobeStream {
- duration?: string;
-}
-
-interface FfprobeOutput {
- frames?: Array<FfprobeFrame>;
- streams?: Array<FfprobeStream>;
- format?: {
- duration?: string;
- };
-}
-
-function isFfprobeFrame(value: unknown): value is FfprobeFrame {
- return (
- isJsonRecord(value) &&
- (value.duration_time === undefined || typeof value.duration_time === 'string') &&
- (value.pkt_duration_time === undefined || typeof value.pkt_duration_time === 'string')
- );
-}
-
-function isFfprobeStream(value: unknown): value is FfprobeStream {
- return isJsonRecord(value) && (value.duration === undefined || typeof value.duration === 'string');
-}
-
-function isFfprobeOutput(value: unknown): value is FfprobeOutput {
- if (!isJsonRecord(value)) return false;
- const format = value.format;
- return (
- (value.frames === undefined || (Array.isArray(value.frames) && value.frames.every(isFfprobeFrame))) &&
- (value.streams === undefined || (Array.isArray(value.streams) && value.streams.every(isFfprobeStream))) &&
- (format === undefined ||
- (isJsonRecord(format) && (format.duration === undefined || typeof format.duration === 'string')))
- );
-}
-
-export async function resolveEntranceSoundDurationMs(params: {
- bytes: Buffer;
- extension: EntranceSoundExtension;
- metadataDurationSeconds: number | null;
-}): Promise<number | null> {
- const preciseDurationSeconds = await probeEntranceSoundDurationSeconds(params.bytes, params.extension).catch(
- (error) => {
- Logger.warn(
- {error, extension: params.extension, sizeBytes: params.bytes.length},
- 'Failed to probe precise entrance sound duration; falling back to media metadata duration',
- );
- return null;
- },
- );
- const durationSeconds = preciseDurationSeconds ?? normalizeDurationSeconds(params.metadataDurationSeconds);
- if (durationSeconds == null) {
- return null;
- }
- return Math.round(durationSeconds * 1000);
-}
-
-async function probeEntranceSoundDurationSeconds(
- bytes: Buffer,
- extension: EntranceSoundExtension,
-): Promise<number | null> {
- const inputPath = temporaryFile({extension});
- try {
- await fs.writeFile(inputPath, bytes);
- const {stdout} = await execFilePromise(
- 'ffprobe',
- [
- '-v',
- 'error',
- '-select_streams',
- 'a:0',
- '-show_frames',
- '-show_entries',
- 'frame=duration_time,pkt_duration_time:stream=duration:format=duration',
- '-of',
- 'json',
- inputPath,
- ],
- {
- timeout: FFPROBE_TIMEOUT_MS,
- maxBuffer: FFPROBE_MAX_BUFFER_BYTES,
- },
- );
- const output = parseJsonWithGuard(stdout.toString(), isFfprobeOutput);
- return output ? durationSecondsFromFfprobe(output) : null;
- } finally {
- await fs.unlink(inputPath).catch(() => {});
- }
-}
-
-function durationSecondsFromFfprobe(output: FfprobeOutput): number | null {
- const frameDurationSeconds = sumFrameDurationSeconds(output.frames);
- if (frameDurationSeconds != null) {
- return frameDurationSeconds;
- }
- const streamDurationSeconds = firstDurationSeconds(output.streams?.map((stream) => stream.duration));
- if (streamDurationSeconds != null) {
- return streamDurationSeconds;
- }
- return normalizeDurationSeconds(output.format?.duration ?? null);
-}
-
-function sumFrameDurationSeconds(frames: ReadonlyArray<FfprobeFrame> | undefined): number | null {
- if (!frames || frames.length === 0) {
- return null;
- }
- let total = 0;
- let counted = 0;
- for (const frame of frames) {
- const duration = normalizeDurationSeconds(frame.duration_time ?? frame.pkt_duration_time ?? null);
- if (duration == null) continue;
- total += duration;
- counted += 1;
- }
- return counted > 0 ? total : null;
-}
-
-function firstDurationSeconds(values: ReadonlyArray<string | undefined> | undefined): number | null {
- if (!values) {
- return null;
- }
- for (const value of values) {
- const duration = normalizeDurationSeconds(value ?? null);
- if (duration != null) {
- return duration;
- }
- }
- return null;
-}
-
-function normalizeDurationSeconds(value: string | number | null | undefined): number | null {
- if (value == null) {
- return null;
- }
- const duration = typeof value === 'number' ? value : Number.parseFloat(value);
- if (!Number.isFinite(duration) || duration <= 0) {
- return null;
- }
- return duration;
-}
diff --git a/fluxer_api/src/api/user/entrance_sound/EntranceSoundService.ts b/fluxer_api/src/api/user/entrance_sound/EntranceSoundService.ts
index f0b8e9c3a..e483d89fc 100644
--- a/fluxer_api/src/api/user/entrance_sound/EntranceSoundService.ts
+++ b/fluxer_api/src/api/user/entrance_sound/EntranceSoundService.ts
@@ -7,7 +7,6 @@ import type {IMediaService} from '@app/api/infrastructure/IMediaService';
import type {IStorageService} from '@app/api/infrastructure/IStorageService';
import {Logger} from '@app/api/Logger';
import {EntranceSound, EntranceSoundSelection} from '@app/api/models/EntranceSound';
-import {resolveEntranceSoundDurationMs} from '@app/api/user/entrance_sound/EntranceSoundDurationProbe';
import type {EntranceSoundRepository} from '@app/api/user/entrance_sound/EntranceSoundRepository';
import {
ENTRANCE_SOUND_EXT_TO_MIME,
@@ -128,15 +127,15 @@ export class EntranceSoundService {
format: metadata.format ?? metadata.content_type ?? 'unknown',
});
}
- const metadataDurationSeconds = typeof metadata.duration === 'number' ? metadata.duration : null;
- const durationMs = await resolveEntranceSoundDurationMs({
- bytes,
- extension,
- metadataDurationSeconds,
- });
- if (durationMs == null) {
+ const metadataDurationSeconds =
+ typeof metadata.duration === 'number' && Number.isFinite(metadata.duration) && metadata.duration > 0
+ ? metadata.duration
+ : null;
+ const durationSeconds = (await this.mediaService.getAudioDurationSeconds(trimmed)) ?? metadataDurationSeconds;
+ if (durationSeconds == null) {
throw InputValidationError.fromCode('audio', ValidationErrorCodes.ENTRANCE_SOUND_INVALID_FORMAT);
}
+ const durationMs = Math.round(durationSeconds * 1000);
if (durationMs > ENTRANCE_SOUND_MAX_DURATION_MS) {
throw InputValidationError.fromCode('audio', ValidationErrorCodes.ENTRANCE_SOUND_DURATION_EXCEEDS_LIMIT, {
max_ms: ENTRANCE_SOUND_MAX_DURATION_MS,