Skip to content

Commit dfd4589

Browse files
authored
fix(support): harden ticket endpoint and Slack payload against abuse (#2174)
- Fail loudly at module load if NEXT_PUBLIC_TURNSTILE_SITE_KEY is missing in production so the Cloudflare test siteKey can never ship. - Render the user-supplied description in a plain_text Slack block so URLs are not auto-linkified, breaking phishing-by-inertia in the support channel. - Strip invisible Unicode controls (RTL overrides, directional isolates, zero-width chars, BOM) from anything the user provides before it reaches Slack, so payloads cannot be visually disguised. - Add an unverified-content warning banner above every ticket. - Enforce a Content-Length ceiling before parsing the JSON body to cut DoS amplification via oversized requests. - Stop leaking Cloudflare siteverify error codes to the client; return a generic captcha_failed instead and log details server-side. - Drop the user-controlled x-forwarded-for hop that was sent as remoteip to Cloudflare — the header is spoofable and siteverify does not require it.
1 parent d49c814 commit dfd4589

2 files changed

Lines changed: 62 additions & 20 deletions

File tree

‎src/app/api/support/ticket/route.ts‎

Lines changed: 46 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,10 @@ const ROUTE = '/api/support/ticket'
1010
const MAX_DESCRIPTION_LENGTH = 1000
1111
const MIN_DESCRIPTION_LENGTH = 10
1212
const MAX_EMAIL_LENGTH = 254
13+
// Legit payloads top out around ~3.5 KB (Turnstile token + capped fields).
14+
// Rejecting anything larger before JSON.parse blocks DoS amplification with
15+
// oversized bodies that would otherwise consume memory just to be discarded.
16+
const MAX_BODY_BYTES = 8_192
1317

1418
interface SiteVerifyResponse {
1519
success: boolean
@@ -39,13 +43,24 @@ const FIELD_ERROR_CODES: Record<keyof TicketData, string> = {
3943
}
4044
const FIELD_PRIORITY: (keyof TicketData)[] = ['token', 'topic', 'description', 'email']
4145

46+
/**
47+
* Strips Unicode control characters a reader can't see but that change how
48+
* text is rendered — RTL overrides (U+202A–202E), directional isolates
49+
* (U+2066–2069), zero-width spaces/joiners (U+200B–200D), and BOM (U+FEFF).
50+
* These are used to disguise URLs (e.g. `evil.com/‮exe.doc`) or hide payloads
51+
* inside otherwise-innocent text.
52+
*/
53+
const stripInvisibleControls = (text: string): string =>
54+
text.replaceAll(/[\u202A-\u202E\u2066-\u2069\u200B-\u200D\uFEFF]/g, '')
55+
4256
/**
4357
* Escapes characters that Slack interprets in `mrkdwn` text so that
4458
* user-supplied content can't inject mentions (e.g. `<!channel>`, `<@U…>`)
45-
* or break the block layout. See https://api.slack.com/reference/surfaces/formatting#escaping
59+
* or break the block layout, and strips invisible control chars.
60+
* See https://api.slack.com/reference/surfaces/formatting#escaping
4661
*/
47-
const escapeSlack = (text: string): string =>
48-
text.replaceAll('&', '&amp;').replaceAll('<', '&lt;').replaceAll('>', '&gt;')
62+
const escapeSlackMrkdwn = (text: string): string =>
63+
stripInvisibleControls(text).replaceAll('&', '&amp;').replaceAll('<', '&lt;').replaceAll('>', '&gt;')
4964

5065
const generateTicketRef = (): string =>
5166
`SUP-${crypto.randomUUID().replaceAll('-', '').slice(0, 8).toUpperCase()}`
@@ -61,19 +76,34 @@ const buildSlackBlocks = (
6176
type: 'header',
6277
text: { type: 'plain_text', text: 'New support ticket', emoji: false },
6378
},
79+
{
80+
type: 'context',
81+
elements: [
82+
{
83+
type: 'mrkdwn',
84+
text: ':warning: Content submitted by an unverified user. Verify any link before clicking.',
85+
},
86+
],
87+
},
6488
{
6589
type: 'section',
6690
fields: [
6791
{ type: 'mrkdwn', text: `*Ticket:*\n${ticketRef}` },
6892
{ type: 'mrkdwn', text: `*Topic:*\n${topic}` },
69-
{ type: 'mrkdwn', text: `*From:*\n${email ? escapeSlack(email) : '_anonymous_'}` },
93+
{ type: 'mrkdwn', text: `*From:*\n${email ? escapeSlackMrkdwn(email) : '_anonymous_'}` },
7094
{ type: 'mrkdwn', text: `*Received:*\n${receivedAt}` },
7195
],
7296
},
7397
{ type: 'divider' },
7498
{
7599
type: 'section',
76-
text: { type: 'mrkdwn', text: `*Description:*\n${escapeSlack(description)}` },
100+
text: { type: 'mrkdwn', text: '*Description:*' },
101+
},
102+
{
103+
type: 'section',
104+
// plain_text disables Slack's URL auto-linkification, so a phishing link
105+
// in the description is not clickable — the agent must copy it out.
106+
text: { type: 'plain_text', text: stripInvisibleControls(description), emoji: false },
77107
},
78108
]
79109

@@ -89,6 +119,11 @@ export async function POST(request: NextRequest) {
89119
return NextResponse.json({ success: false, error: 'server_misconfigured' }, { status: 500 })
90120
}
91121

122+
const contentLength = Number(request.headers.get('content-length') ?? 0)
123+
if (contentLength > MAX_BODY_BYTES) {
124+
return NextResponse.json({ success: false, error: 'body_too_large' }, { status: 413 })
125+
}
126+
92127
let rawBody: unknown
93128
try {
94129
rawBody = await request.json()
@@ -107,26 +142,20 @@ export async function POST(request: NextRequest) {
107142

108143
const { token, topic, description, email } = parsed.data
109144

110-
const remoteip = request.headers.get('x-forwarded-for')?.split(',')[0].trim()
111-
112145
try {
146+
// `remoteip` is intentionally omitted — the only header we could source it
147+
// from (`x-forwarded-for`) is attacker-controllable and would let a spoofed
148+
// value reach Cloudflare. siteverify accepts requests without it.
113149
const cfResponse = await fetch(SITEVERIFY_URL, {
114150
method: 'POST',
115151
headers: { 'content-type': 'application/x-www-form-urlencoded' },
116-
body: new URLSearchParams({
117-
secret,
118-
response: token,
119-
...(remoteip ? { remoteip } : {}),
120-
}),
152+
body: new URLSearchParams({ secret, response: token }),
121153
})
122154
const verification = (await cfResponse.json()) as SiteVerifyResponse
123155

124156
if (!verification.success) {
125157
logger.warn({ route: ROUTE, errorCodes: verification['error-codes'] }, 'Turnstile verification failed')
126-
return NextResponse.json(
127-
{ success: false, errorCodes: verification['error-codes'] ?? [] },
128-
{ status: 403 },
129-
)
158+
return NextResponse.json({ success: false, error: 'captcha_failed' }, { status: 403 })
130159
}
131160
} catch (err) {
132161
logger.error({ err, route: ROUTE }, 'Error contacting Cloudflare siteverify')
@@ -140,7 +169,7 @@ export async function POST(request: NextRequest) {
140169
method: 'POST',
141170
headers: { 'content-type': 'application/json' },
142171
body: JSON.stringify({
143-
text: `New support ticket ${ticketRef} (${topic}) from ${email ? escapeSlack(email) : 'anonymous'}`,
172+
text: `New support ticket ${ticketRef} (${topic}) from ${email ? escapeSlackMrkdwn(email) : 'anonymous'}`,
144173
blocks: buildSlackBlocks(ticketRef, topic, description, email, new Date().toISOString()),
145174
}),
146175
})

‎src/components/MainContainer/sidebars/SupportModal.tsx‎

Lines changed: 16 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -14,11 +14,20 @@ import { Header, Paragraph, Span } from '@/components/Typography'
1414
import { SUPPORT_TOPICS } from '@/shared/constants'
1515
import { showToast } from '@/shared/notification'
1616

17-
// Cloudflare-published test key that always passes. Safe as a public default;
18-
// production builds must set NEXT_PUBLIC_TURNSTILE_SITE_KEY to a real siteKey.
17+
// Cloudflare-published test key that always passes verification. Never ship it —
18+
// paired with a matching test secret it would let any client through without a
19+
// real captcha.
1920
const TURNSTILE_TEST_SITE_KEY = '1x00000000000000000000AA'
2021

21-
const TURNSTILE_SITE_KEY = process.env.NEXT_PUBLIC_TURNSTILE_SITE_KEY || TURNSTILE_TEST_SITE_KEY
22+
const envSiteKey = process.env.NEXT_PUBLIC_TURNSTILE_SITE_KEY
23+
24+
if (process.env.NODE_ENV === 'production' && !envSiteKey) {
25+
throw new Error(
26+
'NEXT_PUBLIC_TURNSTILE_SITE_KEY must be set in production. The test siteKey always passes and must never ship.',
27+
)
28+
}
29+
30+
const TURNSTILE_SITE_KEY = envSiteKey || TURNSTILE_TEST_SITE_KEY
2231

2332
const emptyString = z.literal('').transform(() => {})
2433

@@ -39,6 +48,9 @@ const resolveSubmitError = (status: number, errorCode?: string): string => {
3948
if (status === 429) {
4049
return 'Too many requests. Please wait a moment and try again.'
4150
}
51+
if (status === 413) {
52+
return 'Your message is too large. Please shorten it and try again.'
53+
}
4254
switch (errorCode) {
4355
case 'delivery_failed':
4456
return 'Could not deliver your request. Please try again in a moment.'
@@ -51,6 +63,7 @@ const resolveSubmitError = (status: number, errorCode?: string): string => {
5163
case 'server_misconfigured':
5264
case 'verification_failed':
5365
return 'Something went wrong on our side. Please try again later.'
66+
case 'captcha_failed':
5467
default:
5568
return 'Captcha verification failed. Please try again.'
5669
}

0 commit comments

Comments
 (0)