Skip to content

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

TypeScript fluxerfluxerapp

feat(api): add sign-in backdrop branding and clean unused images

Hampusc73659d525d9
diff --git a/fluxer_api/src/api/admin/tests/InstanceConfigBrandingAssetCleanup.test.ts b/fluxer_api/src/api/admin/tests/InstanceConfigBrandingAssetCleanup.test.ts
new file mode 100644
index 000000000..348e37449
--- /dev/null
+++ b/fluxer_api/src/api/admin/tests/InstanceConfigBrandingAssetCleanup.test.ts
@@ -0,0 +1,116 @@
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+import type {TestAccount} from '@app/api/auth/tests/AuthTestUtils';
+import {createTestAccount, setUserACLs} from '@app/api/auth/tests/AuthTestUtils';
+import {Config, getConfig} from '@app/api/Config';
+import {getPngDataUrl} from '@app/api/emoji/tests/EmojiTestUtils';
+import {NoopPurgeQueue} from '@app/api/infrastructure/CachePurgeQueue';
+import {getAssetDeletionQueue, getInstanceConfigRepository} from '@app/api/middleware/ServiceSingletons';
+import {type ApiTestHarness, createApiTestHarness} from '@app/api/test/ApiTestHarness';
+import {NoopLogger} from '@app/api/test/mocks/NoopLogger';
+import {createBuilder} from '@app/api/test/TestRequestBuilder';
+import processAssetDeletionQueue from '@app/api/worker/tasks/ProcessAssetDeletionQueue';
+import {clearWorkerDependencies, setWorkerDependenciesForTest} from '@app/api/worker/WorkerContext';
+import {AdminACLs} from '@fluxer/constants/src/AdminACLs';
+import type {InstanceConfigResponse} from '@fluxer/schema/src/domains/admin/AdminSchemas';
+import sharp from 'sharp';
+import {afterAll, afterEach, beforeAll, beforeEach, describe, expect, it} from 'vitest';
+
+type BrandingKind = 'icon' | 'logo' | 'sign_in_backdrop';
+
+async function solidPng(background: string): Promise<string> {
+ const buffer = await sharp({create: {width: 4, height: 4, channels: 4, background}})
+ .png()
+ .toBuffer();
+ return getPngDataUrl(buffer.toString('base64'));
+}
+
+function storageKey(url: string | null): string {
+ const match = /\/(branding(?:-backdrops)?\/0)\/(?:a_)?([0-9a-f]{8})\.[a-z0-9]+$/.exec(url ?? '');
+ if (!match) throw new Error(`Not an uploaded branding URL: ${url}`);
+ return `${match[1]}/${match[2]}`;
+}
+
+describe('branding image cleanup', () => {
+ let harness: ApiTestHarness;
+ let admin: TestAccount;
+ let originalSelfHosted: boolean;
+
+ beforeAll(async () => {
+ originalSelfHosted = getConfig().instance.selfHosted;
+ getConfig().instance.selfHosted = true;
+ harness = await createApiTestHarness();
+ });
+
+ beforeEach(async () => {
+ await harness.reset();
+ admin = await setUserACLs(harness, await createTestAccount(harness), [
+ AdminACLs.AUTHENTICATE,
+ AdminACLs.INSTANCE_CONFIG_VIEW,
+ AdminACLs.INSTANCE_CONFIG_UPDATE,
+ ]);
+ setWorkerDependenciesForTest({
+ assetDeletionQueue: getAssetDeletionQueue(),
+ purgeQueue: new NoopPurgeQueue(),
+ storageService: harness.storageService,
+ instanceConfigRepository: getInstanceConfigRepository(),
+ userRepository: {findUnique: async () => null} as never,
+ guildRepository: {findUnique: async () => null, getMember: async () => null} as never,
+ });
+ });
+
+ afterEach(() => {
+ clearWorkerDependencies();
+ });
+
+ afterAll(async () => {
+ await harness.shutdown();
+ getConfig().instance.selfHosted = originalSelfHosted;
+ });
+
+ async function upload(kind: BrandingKind, image: string | null): Promise<InstanceConfigResponse> {
+ return await createBuilder<InstanceConfigResponse>(harness, admin.token)
+ .post('/admin/instance/config/branding-assets')
+ .body({kind, image})
+ .execute();
+ }
+
+ async function patchBranding(branding: Record<string, string | null>): Promise<InstanceConfigResponse> {
+ return await createBuilder<InstanceConfigResponse>(harness, admin.token)
+ .patch('/admin/instance/config')
+ .body({app_public: {branding}})
+ .execute();
+ }
+
+ async function storedAfterCleanup(key: string): Promise<boolean> {
+ await processAssetDeletionQueue({}, HELPERS);
+ return harness.storageService.hasObject(Config.s3.buckets.cdn, key);
+ }
+
+ it('keeps the image while another branding field still uses it', async () => {
+ const image = await solidPng('#ff0000');
+ const shared = storageKey((await upload('icon', image)).app_public.branding.icon_url);
+ expect(storageKey((await upload('logo', image)).app_public.branding.logo_url)).toBe(shared);
+
+ await upload('icon', await solidPng('#00ff00'));
+ expect(await storedAfterCleanup(shared)).toBe(true);
+
+ await patchBranding({logo_url: null});
+ expect(await storedAfterCleanup(shared)).toBe(false);
+ });
+
+ it('keeps the image when the same file is uploaded again', async () => {
+ const image = await solidPng('#ff0000');
+ const key = storageKey((await upload('icon', image)).app_public.branding.icon_url);
+ await upload('icon', image);
+ expect(await storedAfterCleanup(key)).toBe(true);
+ });
+
+ it('keeps the image when it is set again before the cleanup runs', async () => {
+ const image = await solidPng('#ff0000');
+ const key = storageKey((await upload('icon', image)).app_public.branding.icon_url);
+ await upload('icon', null);
+ await upload('logo', image);
+ expect(await storedAfterCleanup(key)).toBe(true);
+ });
+});
diff --git a/fluxer_api/src/api/infrastructure/EntityAssetService.ts b/fluxer_api/src/api/infrastructure/EntityAssetService.ts
index 62001de62..e4f7c3561 100644
--- a/fluxer_api/src/api/infrastructure/EntityAssetService.ts
+++ b/fluxer_api/src/api/infrastructure/EntityAssetService.ts
@@ -8,18 +8,18 @@ import type {IAssetDeletionQueue, QueuedAssetReference} from '@app/api/infrastru
import type {IMediaService, MediaProxyMetadataResponse} 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 type {User} from '@app/api/models/User';
import {awaitAll} from '@app/api/utils/ConcurrencyUtils';
-import type {AssetKind} from '@fluxer/constants/src/AssetFormatPolicy';
+import {type AssetKind, getPolicy} from '@fluxer/constants/src/AssetFormatPolicy';
import {AVATAR_MAX_SIZE} from '@fluxer/constants/src/LimitConstants';
import {ValidationErrorCodes} from '@fluxer/constants/src/ValidationErrorCodes';
import {InputValidationError} from '@fluxer/errors/src/domains/core/InputValidationError';
import {ms} from 'itty-time';
import sharp from 'sharp';
-type AssetType = 'avatar' | 'banner' | 'icon' | 'splash' | 'embed_splash' | 'branding';
+type AssetType = 'avatar' | 'banner' | 'icon' | 'splash' | 'embed_splash' | 'branding' | 'branding_backdrop';
type EntityType = 'user' | 'guild' | 'guild_member' | 'instance';
const ASSET_TYPE_TO_PREFIX: Record<AssetType, string> = {
@@ -29,6 +29,7 @@ const ASSET_TYPE_TO_PREFIX: Record<AssetType, string> = {
splash: 'splashes',
embed_splash: 'embed-splashes',
branding: 'branding',
+ branding_backdrop: 'branding-backdrops',
};
function normalizeContentType(contentType: string | null | undefined): string {
@@ -66,6 +67,7 @@ interface PrepareAssetUploadOptions {
previousHash: string | null;
base64Image: string | null;
errorPath: string;
+ uploader?: User | null;
}
type LimitConfigSnapshotProvider = Pick<LimitConfigService, 'getConfigSnapshot'>;
@@ -92,11 +94,13 @@ export class EntityAssetService {
return 'embed_splash';
case 'branding':
return 'guild_icon';
+ case 'branding_backdrop':
+ return 'sign_in_backdrop';
}
}
async prepareAssetUpload(options: PrepareAssetUploadOptions): Promise<PreparedAssetUpload> {
- const {assetType, entityType, entityId, guildId, previousHash, base64Image, errorPath} = options;
+ const {assetType, entityType, entityId, guildId, previousHash, base64Image, errorPath, uploader} = options;
const s3KeyBase = this.buildS3KeyBase(assetType, entityType, entityId, guildId);
const cdnUrlBase = `${Config.endpoints.media}/${s3KeyBase}`;
const previousS3Key = previousHash ? `${s3KeyBase}/${stripAnimationPrefix(previousHash)}` : null;
@@ -126,7 +130,7 @@ export class EntityAssetService {
width,
contentType,
animated: isAnimated,
- } = await this.validateAndProcessImage(base64Image, errorPath, assetType);
+ } = await this.validateAndProcessImage(base64Image, errorPath, assetType, uploader ?? null);
const imageHash = crypto.createHash('md5').update(Buffer.from(imageBuffer)).digest('hex');
const imageHashShort = imageHash.slice(0, 8);
const newHash = isAnimated ? `a_${imageHashShort}` : imageHashShort;
@@ -264,6 +268,7 @@ export class EntityAssetService {
base64Image: string,
errorPath: string,
assetType: AssetType,
+ uploader: User | null,
): Promise<{
imageBuffer: Uint8Array;
format: string;
@@ -272,11 +277,15 @@ export class EntityAssetService {
contentType: string | null;
animated: boolean;
}> {
+ const kind = this.mapAssetTypeToAssetKind(assetType);
const {imageBuffer, metadata} = await decodeValidatedImage(this.mediaService, {
base64Image,
errorPath,
- kind: this.mapAssetTypeToAssetKind(assetType),
- maxSize: resolveAssetSizeLimit(this.limitConfigService, 'avatar_max_size', AVATAR_MAX_SIZE),
+ kind,
+ maxSize:
+ kind === 'sign_in_backdrop'
+ ? getPolicy(kind).maxBytes
+ : resolveAssetSizeLimit(this.limitConfigService, 'avatar_max_size', AVATAR_MAX_SIZE, null, uploader),
});
const isAnimatedImage = metadata.animated ?? false;
const keepDimensions = !isSvgMetadata(metadata);
diff --git a/fluxer_api/src/api/infrastructure/IAssetDeletionQueue.ts b/fluxer_api/src/api/infrastructure/IAssetDeletionQueue.ts
index aefd72b7d..540294123 100644
--- a/fluxer_api/src/api/infrastructure/IAssetDeletionQueue.ts
+++ b/fluxer_api/src/api/infrastructure/IAssetDeletionQueue.ts
@@ -1,7 +1,14 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
export type QueuedAssetEntityType = 'user' | 'guild' | 'guild_member' | 'instance';
-export type QueuedAssetType = 'avatar' | 'banner' | 'icon' | 'splash' | 'embed_splash' | 'branding';
+export type QueuedAssetType =
+ | 'avatar'
+ | 'banner'
+ | 'icon'
+ | 'splash'
+ | 'embed_splash'
+ | 'branding'
+ | 'branding_backdrop';
export interface QueuedAssetReference {
entityType: QueuedAssetEntityType;
diff --git a/fluxer_api/src/api/instance/BrandingAssetReferences.ts b/fluxer_api/src/api/instance/BrandingAssetReferences.ts
index 34e050ff3..b622e65ce 100644
--- a/fluxer_api/src/api/instance/BrandingAssetReferences.ts
+++ b/fluxer_api/src/api/instance/BrandingAssetReferences.ts
@@ -1,11 +1,19 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
-export const BRANDING_ASSET_FIELDS = ['icon_url', 'symbol_url', 'logo_url', 'wordmark_url', 'favicon_url'] as const;
+export const BRANDING_ASSET_FIELDS = [
+ 'icon_url',
+ 'symbol_url',
+ 'logo_url',
+ 'wordmark_url',
+ 'favicon_url',
+ 'favicon_dark_url',
+ 'sign_in_backdrop_url',
+] as const;
export type BrandingAssetField = (typeof BRANDING_ASSET_FIELDS)[number];
-const BRANDING_ASSET_REFERENCE = /^branding\/\d{1,20}\/(?:a_)?[0-9a-f]{8}\.[a-z0-9]{2,5}$/;
-const BRANDING_ASSET_PATH = /\/(branding\/\d{1,20}\/(?:a_)?[0-9a-f]{8}\.[a-z0-9]{2,5})$/;
+const BRANDING_ASSET_REFERENCE = /^branding(?:-backdrops)?\/\d{1,20}\/(?:a_)?[0-9a-f]{8}\.[a-z0-9]{2,5}$/;
+const BRANDING_ASSET_PATH = /\/(branding(?:-backdrops)?\/\d{1,20}\/(?:a_)?[0-9a-f]{8}\.[a-z0-9]{2,5})$/;
function trimTrailingSlashes(value: string): string {
return value.replace(/\/+$/u, '');
@@ -15,7 +23,7 @@ export function isBrandingAssetReference(value: string): boolean {
return BRANDING_ASSET_REFERENCE.test(value);
}
-export function brandingAssetReferenceFromOwnUrl(value: string, mediaEndpoint: string): string | null {
+function brandingAssetReferenceFromOwnUrl(value: string, mediaEndpoint: string): string | null {
const prefix = `${trimTrailingSlashes(mediaEndpoint)}/`;
if (!value.startsWith(prefix)) return null;
const remainder = value.slice(prefix.length);
@@ -65,3 +73,29 @@ export function mapBrandingAssets<T extends Partial<Record<BrandingAssetField, s
}
return next;
}
+
+export function brandingAssetStorageKeys(
+ branding: Partial<Record<BrandingAssetField, string | null | undefined>>,
+): Set<string> {
+ const keys = new Set<string>();
+ for (const field of BRANDING_ASSET_FIELDS) {
+ const value = branding[field];
+ if (typeof value === 'string' && isBrandingAssetReference(value)) keys.add(brandingAssetStorageKey(value));
+ }
+ return keys;
+}
+
+export function releasedBrandingAssetReferences(
+ before: Partial<Record<BrandingAssetField, string | null | undefined>>,
+ after: Partial<Record<BrandingAssetField, string | null | undefined>>,
+): Array<string> {
+ const kept = brandingAssetStorageKeys(after);
+ const released = new Map<string, string>();
+ for (const field of BRANDING_ASSET_FIELDS) {
+ const value = before[field];
+ if (typeof value !== 'string' || !isBrandingAssetReference(value)) continue;
+ const key = brandingAssetStorageKey(value);
+ if (!kept.has(key) && !released.has(key)) released.set(key, value);
+ }
+ return [...released.values()];
+}
diff --git a/fluxer_api/src/api/worker/tasks/ProcessAssetDeletionQueue.ts b/fluxer_api/src/api/worker/tasks/ProcessAssetDeletionQueue.ts
index 2aba92454..15635d883 100644
--- a/fluxer_api/src/api/worker/tasks/ProcessAssetDeletionQueue.ts
+++ b/fluxer_api/src/api/worker/tasks/ProcessAssetDeletionQueue.ts
@@ -13,6 +13,7 @@ import type {
QueuedAssetType,
} from '@app/api/infrastructure/IAssetDeletionQueue';
import type {IStorageService} from '@app/api/infrastructure/IStorageService';
+import type {InstanceConfigRepository} from '@app/api/instance/InstanceConfigRepository';
import {Logger} from '@app/api/Logger';
import type {UserRepository} from '@app/api/user/repositories/UserRepository';
import {getWorkerDependencies} from '@app/api/worker/WorkerContext';
@@ -31,6 +32,7 @@ interface ProcessItemResult {
interface AssetReferenceRepositories {
userRepository: Pick<UserRepository, 'findUnique'>;
guildRepository: Pick<GuildRepository, 'findUnique' | 'getMember'>;
+ instanceConfigRepository: Pick<InstanceConfigRepository, 'readStoredBrandingAssetKeys'>;
}
interface AssetDeletionDependencies extends AssetReferenceRepositories {
@@ -39,7 +41,8 @@ interface AssetDeletionDependencies extends AssetReferenceRepositories {
}
const processAssetDeletionQueue: WorkerTaskHandler = async (_payload, _helpers) => {
- const {assetDeletionQueue, purgeQueue, storageService, userRepository, guildRepository} = getWorkerDependencies();
+ const {assetDeletionQueue, purgeQueue, storageService, userRepository, guildRepository, instanceConfigRepository} =
+ getWorkerDependencies();
const queueSize = await assetDeletionQueue.getQueueSize();
if (!Number.isSafeInteger(queueSize) || queueSize < 0) {
throw new Error('Asset deletion queue size must be a non-negative safe integer');
@@ -49,7 +52,13 @@ const processAssetDeletionQueue: WorkerTaskHandler = async (_payload, _helpers)
return;
}
Logger.info({queueSize}, 'Starting asset deletion queue processing');
- const dependencies: AssetDeletionDependencies = {storageService, purgeQueue, userRepository, guildRepository};
+ const dependencies: AssetDeletionDependencies = {
+ storageService,
+ purgeQueue,
+ userRepository,
+ guildRepository,
+ instanceConfigRepository,
+ };
let remainingReadBudget = Math.min(MAX_ITEMS_PER_RUN, queueSize);
let totalProcessed = 0;
let totalDeleted = 0;
@@ -169,6 +178,9 @@ async function isQueuedAssetStillCurrent(
item: QueuedAssetDeletion,
deps: AssetReferenceRepositories,
): Promise<boolean> {
+ if (/^branding(?:-backdrops)?\//.test(item.s3Key)) {
+ return (await deps.instanceConfigRepository.readStoredBrandingAssetKeys()).has(item.s3Key);
+ }
const references = inferAssetReferencesFromS3Key(item.s3Key);
const {staleReference} = item;
if (
@@ -238,8 +250,6 @@ function inferAssetReferencesFromS3Key(s3Key: string): Array<QueuedAssetReferenc
return [createAssetReference(parts, 'guild', 'embed_splash')];
case 'banners':
return [createAssetReference(parts, 'user', 'banner'), createAssetReference(parts, 'guild', 'banner')];
- case 'branding':
- throw new Error('Branding asset deletion requires an instance reference lookup');
case 'guilds':
if (parts.length !== 6 || parts[2] !== 'users' || (parts[4] !== 'avatars' && parts[4] !== 'banners')) {
throw new Error('Asset deletion storage key has an invalid guild member path');