Skip to content

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

TypeScript fluxerfluxerapp

fix(api): accept empty embed field names and values (#3838)

Hampusb088323c9bc4
diff --git a/fluxer_api/src/api/Validator.ts b/fluxer_api/src/api/Validator.ts
index 7fa1b1688..971986fe1 100644
--- a/fluxer_api/src/api/Validator.ts
+++ b/fluxer_api/src/api/Validator.ts
@@ -15,6 +15,7 @@ import {
type core,
type input,
type output,
+ ZodArray,
ZodNullable,
ZodObject,
ZodOptional,
@@ -60,7 +61,10 @@ function convertEmptyValuesToNull(obj: unknown, schema?: core.$ZodType, isRoot =
const metadata = schema ? schemaMetadata.get(schema) : undefined;
if (metadata?.preserveEmptyValues) return obj;
if (typeof obj === 'string' && obj === '') return null;
- if (Array.isArray(obj)) return obj.map((item) => convertEmptyValuesToNull(item, undefined, false));
+ if (Array.isArray(obj)) {
+ const element = schema instanceof ZodArray ? schema.element : undefined;
+ return obj.map((item) => convertEmptyValuesToNull(item, element, false));
+ }
if (obj !== null && typeof obj === 'object') {
if (isEmptyObject(obj) && !isRoot) return null;
const shape = schema instanceof ZodObject ? schema.shape : undefined;
diff --git a/fluxer_api/src/api/channel/services/message/MessageRequestParser.ts b/fluxer_api/src/api/channel/services/message/MessageRequestParser.ts
index c25400f50..41310dc38 100644
--- a/fluxer_api/src/api/channel/services/message/MessageRequestParser.ts
+++ b/fluxer_api/src/api/channel/services/message/MessageRequestParser.ts
@@ -397,6 +397,6 @@ export async function parseMessageRequestBody<T extends z.ZodType<MessageRequest
if (isMultipartFormData(ctx.req.header('content-type')))
return (await parseMultipartMessageData(ctx, user, channelId, schema)) as z.output<T>;
const result = schema.safeParse(normalizeMessageRequestPayload(await readMessageJsonBody(ctx)));
- if (!result.success) throw InputValidationError.fromCode('message_data', ValidationErrorCodes.INVALID_MESSAGE_DATA);
+ if (!result.success) throw inputValidationErrorFromZodIssues(result.error.issues);
return result.data;
}
diff --git a/fluxer_api/src/api/channel/tests/EmbedFieldEmptyStrings.test.ts b/fluxer_api/src/api/channel/tests/EmbedFieldEmptyStrings.test.ts
new file mode 100644
index 000000000..71a683a94
--- /dev/null
+++ b/fluxer_api/src/api/channel/tests/EmbedFieldEmptyStrings.test.ts
@@ -0,0 +1,111 @@
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+import {createTestAccount} from '@app/api/auth/tests/AuthTestUtils';
+import {createGuild} from '@app/api/channel/tests/ChannelTestUtils';
+import {ensureSessionStarted} from '@app/api/message/tests/MessageTestUtils';
+import {type ApiTestHarness, createApiTestHarness} from '@app/api/test/ApiTestHarness';
+import {createBuilder, createBuilderWithoutAuth} from '@app/api/test/TestRequestBuilder';
+import {createWebhook} from '@app/api/webhook/tests/WebhookTestUtils';
+import type {MessageResponse} from '@fluxer/schema/src/domains/message/MessageResponseSchemas';
+import {afterAll, beforeAll, beforeEach, describe, expect, it} from 'vitest';
+
+const EMPTY_FIELDS = [
+ {name: 'Status', value: ''},
+ {name: '', value: 'Online'},
+ {name: '', value: ''},
+];
+
+function fieldPairs(message: MessageResponse): Array<[string, string]> {
+ return (message.embeds?.[0]?.fields ?? []).map((field) => [field.name, field.value]);
+}
+
+const EXPECTED_PAIRS: Array<[string, string]> = [
+ ['Status', ''],
+ ['', 'Online'],
+ ['', ''],
+];
+
+describe('Embed fields with empty names and values', () => {
+ let harness: ApiTestHarness;
+
+ beforeAll(async () => {
+ harness = await createApiTestHarness();
+ });
+
+ beforeEach(async () => {
+ await harness.reset();
+ });
+
+ afterAll(async () => {
+ await harness?.shutdown();
+ });
+
+ it('accepts empty field names and values on webhook create and edit', async () => {
+ const owner = await createTestAccount(harness);
+ const guild = await createGuild(harness, owner.token, 'Empty embed fields');
+ const webhook = await createWebhook(harness, guild.system_channel_id!, owner.token, 'Empty fields');
+ const base = `/webhooks/${webhook.id}/${webhook.token}`;
+
+ const created = await createBuilderWithoutAuth<MessageResponse>(harness)
+ .post(`${base}?wait=true`)
+ .body({embeds: [{fields: EMPTY_FIELDS}]})
+ .execute();
+ expect(fieldPairs(created)).toEqual(EXPECTED_PAIRS);
+
+ const plain = await createBuilderWithoutAuth<MessageResponse>(harness)
+ .post(`${base}?wait=true`)
+ .body({embeds: [{fields: [{name: 'a', value: 'b'}]}]})
+ .execute();
+ const edited = await createBuilderWithoutAuth<MessageResponse>(harness)
+ .patch(`${base}/messages/${plain.id}`)
+ .body({embeds: [{fields: EMPTY_FIELDS}]})
+ .execute();
+ expect(fieldPairs(edited)).toEqual(EXPECTED_PAIRS);
+ });
+
+ it('accepts empty field names and values on message create and edit', async () => {
+ const account = await createTestAccount(harness);
+ const guild = await createGuild(harness, account.token, 'Empty embed fields');
+ const channelId = guild.system_channel_id!;
+ await ensureSessionStarted(harness, account.token);
+
+ const created = await createBuilder<MessageResponse>(harness, account.token)
+ .post(`/channels/${channelId}/messages`)
+ .body({embeds: [{fields: EMPTY_FIELDS}]})
+ .execute();
+ expect(fieldPairs(created)).toEqual(EXPECTED_PAIRS);
+
+ const plain = await createBuilder<MessageResponse>(harness, account.token)
+ .post(`/channels/${channelId}/messages`)
+ .body({content: 'plain'})
+ .execute();
+ const edited = await createBuilder<MessageResponse>(harness, account.token)
+ .patch(`/channels/${channelId}/messages/${plain.id}`)
+ .body({embeds: [{fields: EMPTY_FIELDS}]})
+ .execute();
+ expect(fieldPairs(edited)).toEqual(EXPECTED_PAIRS);
+ });
+
+ it('still rejects a missing field value with the exact field path', async () => {
+ const owner = await createTestAccount(harness);
+ const guild = await createGuild(harness, owner.token, 'Missing embed field value');
+ const channelId = guild.system_channel_id!;
+ const webhook = await createWebhook(harness, channelId, owner.token, 'Missing value');
+ await ensureSessionStarted(harness, owner.token);
+ const body = {embeds: [{fields: [{name: 'Status', value: null}]}]};
+
+ const webhookResult = await createBuilderWithoutAuth(harness)
+ .post(`/webhooks/${webhook.id}/${webhook.token}?wait=true`)
+ .body(body)
+ .executeRaw();
+ const messageResult = await createBuilder(harness, owner.token)
+ .post(`/channels/${channelId}/messages`)
+ .body(body)
+ .executeRaw();
+
+ for (const result of [webhookResult, messageResult]) {
+ expect(result.response.status).toBe(400);
+ expect(result.text).toContain('"path":"embeds.0.fields.0.value"');
+ }
+ });
+});
diff --git a/fluxer_api/src/api/openapi/openapi.json b/fluxer_api/src/api/openapi/openapi.json
index 5efe2d57c..58ed45c6f 100644
--- a/fluxer_api/src/api/openapi/openapi.json
+++ b/fluxer_api/src/api/openapi/openapi.json
@@ -40774,7 +40774,7 @@
"items": {
"type": "object",
"properties": {
- "name": {"description": "Name of the field", "type": "string"},
+ "name": {"description": "Name of the field (0-256 characters)", "type": "string"},
"value": {"description": "Value of the field (0-1024 characters)", "type": "string"},
"inline": {
"default": false,
diff --git a/fluxer_api/src/api/webhook/WebhookController.ts b/fluxer_api/src/api/webhook/WebhookController.ts
index 8adb782d9..571fb028a 100644
--- a/fluxer_api/src/api/webhook/WebhookController.ts
+++ b/fluxer_api/src/api/webhook/WebhookController.ts
@@ -25,7 +25,7 @@ import {RateLimitConfigs} from '@app/api/RateLimitConfig';
import type {HonoApp, HonoEnv} from '@app/api/types/HonoEnv';
import {assertAccountNotLimited} from '@app/api/user/AccountLimit';
import {parseJsonPreservingLargeIntegers} from '@app/api/utils/LosslessJsonParser';
-import {Validator} from '@app/api/Validator';
+import {inputValidationErrorFromZodIssues, Validator} from '@app/api/Validator';
import type {WebhookExecuteMessageData} from '@app/api/webhook/WebhookService';
import {DELETED_USER_ID} from '@fluxer/constants/src/UserConstants';
import {ValidationErrorCodes} from '@fluxer/constants/src/ValidationErrorCodes';
@@ -72,7 +72,7 @@ const WebhookMultipartMessagePayload = WebhookMultipartMessageRequest.omit(FORUM
function validateWebhookMessagePayload(data: unknown): z.infer<typeof WebhookMessagePayload> {
const validationResult = WebhookMessagePayload.safeParse(normalizeMessageRequestPayload(data));
if (!validationResult.success) {
- throw InputValidationError.fromCode('message_data', ValidationErrorCodes.INVALID_MESSAGE_DATA);
+ throw inputValidationErrorFromZodIssues(validationResult.error.issues);
}
return validationResult.data;
}
@@ -80,7 +80,7 @@ function validateWebhookMessagePayload(data: unknown): z.infer<typeof WebhookMes
function validateWebhookMultipartMessagePayload(data: unknown): z.infer<typeof WebhookMultipartMessagePayload> {
const validationResult = WebhookMultipartMessagePayload.safeParse(normalizeMessageRequestPayload(data));
if (!validationResult.success) {
- throw InputValidationError.fromCode('message_data', ValidationErrorCodes.INVALID_MESSAGE_DATA);
+ throw inputValidationErrorFromZodIssues(validationResult.error.issues);
}
return validationResult.data;
}
diff --git a/fluxer_app/src/features/notification/utils/MessageNotificationPreview.ts b/fluxer_app/src/features/notification/utils/MessageNotificationPreview.ts
index fbb499156..5840d2ba4 100644
--- a/fluxer_app/src/features/notification/utils/MessageNotificationPreview.ts
+++ b/fluxer_app/src/features/notification/utils/MessageNotificationPreview.ts
@@ -88,7 +88,7 @@ function buildEmbedNotificationPreview(embeds: ReadonlyArray<MessageEmbed> | nul
}
if (embed.fields?.length) {
const field = embed.fields[0];
- return `${field.name}: ${field.value}`;
+ return [field.name, field.value].filter(Boolean).join(': ');
}
return '';
}
diff --git a/packages/schema/src/domains/message/MessageRequestSchemas.ts b/packages/schema/src/domains/message/MessageRequestSchemas.ts
index 1132b4f35..2421c1307 100644
--- a/packages/schema/src/domains/message/MessageRequestSchemas.ts
+++ b/packages/schema/src/domains/message/MessageRequestSchemas.ts
@@ -20,6 +20,7 @@ import {
withOpenApiType,
} from '@fluxer/schema/src/primitives/SchemaPrimitives';
import {AttachmentURLType, URLType} from '@fluxer/schema/src/primitives/UrlValidators';
+import {schemaMetadata} from '@fluxer/schema/src/SchemaMetadata';
import {z} from 'zod';
const RICH_EMBED_AUTHOR_NAME_MAX_LENGTH = 256 as const;
@@ -84,13 +85,17 @@ export const RichEmbedFooterRequest = z.preprocess(
export type RichEmbedFooterRequest = z.infer<typeof RichEmbedFooterRequest>;
-const RichEmbedFieldRequest = z.object({
- name: createStringType(1, RICH_EMBED_FIELD_NAME_MAX_LENGTH).describe('Name of the field'),
- value: createStringType(0, RICH_EMBED_FIELD_VALUE_MAX_LENGTH).describe(
- `Value of the field (0-${RICH_EMBED_FIELD_VALUE_MAX_LENGTH} characters)`,
- ),
- inline: z.boolean().default(false).describe('Whether the field should display inline'),
-});
+const RichEmbedFieldRequest = z
+ .object({
+ name: createStringType(0, RICH_EMBED_FIELD_NAME_MAX_LENGTH).describe(
+ `Name of the field (0-${RICH_EMBED_FIELD_NAME_MAX_LENGTH} characters)`,
+ ),
+ value: createStringType(0, RICH_EMBED_FIELD_VALUE_MAX_LENGTH).describe(
+ `Value of the field (0-${RICH_EMBED_FIELD_VALUE_MAX_LENGTH} characters)`,
+ ),
+ inline: z.boolean().default(false).describe('Whether the field should display inline'),
+ })
+ .register(schemaMetadata, {preserveEmptyValues: true});
export const RichEmbedRequest = z.object({
url: URLType.nullish().describe('URL of the embed'),