A free and open source instant messaging and VoIP chat app built for friends, groups, and communities.
refactor(api): validate URL and client identity input directly
Hampusc9f6e20c75f1
diff --git a/fluxer_api/src/api/utils/SessionClientIdentity.ts b/fluxer_api/src/api/utils/SessionClientIdentity.tsindex d0cfbbe92..1e9c3421e 100644--- a/fluxer_api/src/api/utils/SessionClientIdentity.ts+++ b/fluxer_api/src/api/utils/SessionClientIdentity.ts@@ -1,7 +1,7 @@// SPDX-License-Identifier: AGPL-3.0-or-laterimport {Logger} from '@app/api/Logger';-import {parseJsonRecord} from '@app/api/utils/JsonBoundaryUtils';+import {isRecord} from '@fluxer/record_utils/src/RecordGuards';import Bowser from 'bowser';type SessionDeviceClass = 'mobile' | 'desktop';@@ -12,7 +12,7 @@ interface SessionClientSignals {productName: string;}-export interface SessionClientInfo {+interface SessionClientInfo {platform: string | null;os: string | null;browser: string | null;@@ -76,14 +76,18 @@ export function parseReportedClientOs(headerValue: string | null): OsToken | nulif (!headerValue) return null;const trimmed = headerValue.trim();if (!trimmed || trimmed.length > CLIENT_PROPERTIES_HEADER_MAX_LENGTH) return null;- let decoded: string;+ let record: Record<string, unknown>;try {- decoded = Buffer.from(trimmed, 'base64').toString('utf8');- } catch {+ const decoded = Buffer.from(trimmed, 'base64').toString('utf8');+ const value: unknown = JSON.parse(decoded);+ if (!isRecord(value)) return null;+ record = value;+ } catch (error) {+ if (!(error instanceof SyntaxError)) {+ Logger.warn({error}, 'Failed to decode reported client operating system');+ }return null;}- const record = parseJsonRecord(decoded);- if (!record) return null;const os = record.os;return typeof os === 'string' ? narrowOsToken(os) : null;}@@ -97,15 +101,18 @@ export function resolveSessionClientInfo({const nativeMatch = NATIVE_UA_REGEX.exec(ua);if (nativeMatch) {- const productToken = nativeMatch[1] as keyof typeof PRODUCT_TOKEN_OS;+ const productToken = nativeMatch[1];const osToken = narrowOsToken(reportedOs) ?? PRODUCT_TOKEN_OS[productToken] ?? bowserOsToken(ua);const osDisplay = osToken ? OS_DISPLAY[osToken] : null;const mobile = osToken === 'ios' || osToken === 'android';- const platform = osDisplay- ? mobile- ? `${productName} ${osDisplay}`- : `${productName} Lite ${osDisplay}`- : `${productName} Lite`;+ let platform: string;+ if (!osDisplay) {+ platform = `${productName} Lite`;+ } else if (mobile) {+ platform = `${productName} ${osDisplay}`;+ } else {+ platform = `${productName} Lite ${osDisplay}`;+ }return {platform, os: osDisplay, browser: null, device: mobile ? 'mobile' : 'desktop'};}diff --git a/fluxer_api/src/api/utils/UrlNormalizer.ts b/fluxer_api/src/api/utils/UrlNormalizer.tsindex b9724b568..cc46b3421 100644--- a/fluxer_api/src/api/utils/UrlNormalizer.ts+++ b/fluxer_api/src/api/utils/UrlNormalizer.ts@@ -1,6 +1,7 @@// SPDX-License-Identifier: AGPL-3.0-or-laterimport {domainToASCII} from 'node:url';+import {compareText} from '@app/api/utils/StringComparison';const TRACKING_PARAMS = new Set(['gclid',@@ -14,13 +15,19 @@ const TRACKING_PARAMS = new Set(['ref_src','ref_url',]);-// biome-ignore lint/complexity/useRegexLiterals: The literal form trips noControlCharactersInRegex for C0 controls.-const CONTROL_OR_WS_RE = new RegExp('[\\s\\x00-\\x1f]');+const FIRST_PRINTABLE_ASCII_CODE = 0x20;+const WHITESPACE_RE = /\s/;export function canonicalizeUrl(raw: string): string | null {const trimmed = raw.trim();if (!trimmed) return null;- if (CONTROL_OR_WS_RE.test(trimmed)) return null;+ const checked = `${trimmed}`;+ for (let index = 0; index < checked.length; index++) {+ if (checked.charCodeAt(index) < FIRST_PRINTABLE_ASCII_CODE) {+ return null;+ }+ }+ if (WHITESPACE_RE.test(checked)) return null;let parsed: URL;try {parsed = new URL(trimmed);@@ -49,7 +56,7 @@ export function canonicalizeUrl(raw: string): string | null {}kept.push([k, v]);}- kept.sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0));+ kept.sort(([a], [b]) => compareText(a, b));parsed.search = '';for (const [k, v] of kept) {parsed.searchParams.append(k, v);diff --git a/fluxer_api/src/api/utils/tests/SessionClientIdentity.test.ts b/fluxer_api/src/api/utils/tests/SessionClientIdentity.test.tsnew file mode 100644index 000000000..ad3cf7e5c--- /dev/null+++ b/fluxer_api/src/api/utils/tests/SessionClientIdentity.test.ts@@ -0,0 +1,47 @@+// SPDX-License-Identifier: AGPL-3.0-or-later++import {parseReportedClientOs} from '@app/api/utils/SessionClientIdentity';+import {describe, expect, it} from 'vitest';++describe('reported session operating system', () => {+ it.each([+ {json: '{"os":"android"}', expected: 'android'},+ {json: '{"os":"ios"}', expected: 'ios'},+ {json: '{"os":"macos"}', expected: 'macos'},+ {json: '{"os":"windows"}', expected: 'windows'},+ {json: '{"os":"linux"}', expected: 'linux'},+ {json: '{"os":"Android"}', expected: null},+ {json: '{"os":"unknown"}', expected: null},+ {json: '{"os":"__proto__"}', expected: null},+ {json: '{"os":"constructor"}', expected: null},+ {json: '{"os":null}', expected: null},+ {json: '{"os":1}', expected: null},+ {json: '{"__proto__":{"os":"linux"}}', expected: null},+ {json: '{}', expected: null},+ {json: '[{"os":"linux"}]', expected: null},+ {json: '"linux"', expected: null},+ {json: 'null', expected: null},+ {json: '{"os":', expected: null},+ ])('decodes $json as $expected', ({json, expected}) => {+ expect(parseReportedClientOs(Buffer.from(json).toString('base64'))).toBe(expected);+ });++ it.each([+ {header: null, expected: null},+ {header: '', expected: null},+ {header: ' \t ', expected: null},+ {header: '!@#$', expected: null},+ {header: '/w==', expected: null},+ {header: ' eyJvcyI6ImxpbnV4In0= \n', expected: 'linux'},+ ])('handles header $header', ({header, expected}) => {+ expect(parseReportedClientOs(header)).toBe(expected);+ });++ it.each([+ {padding: 4076, expected: 'linux'},+ {padding: 4077, expected: null},+ ])('bounds a valid padded header with $padding internal spaces', ({padding, expected}) => {+ const header = `e${' '.repeat(padding)}yJvcyI6ImxpbnV4In0=`;+ expect(parseReportedClientOs(header)).toBe(expected);+ });+});diff --git a/fluxer_api/src/api/utils/tests/UrlNormalizer.test.ts b/fluxer_api/src/api/utils/tests/UrlNormalizer.test.tsindex ada6c6ac4..9bd824378 100644--- a/fluxer_api/src/api/utils/tests/UrlNormalizer.test.ts+++ b/fluxer_api/src/api/utils/tests/UrlNormalizer.test.ts@@ -185,3 +185,50 @@ describe('extractLinkHosts', () => {expect(extractLinkHosts(null)).toEqual([]);});});++describe('canonicalizeUrl character boundaries', () => {+ it.each([+ {name: 'start of heading', input: 'https://example.com/a\x01z', expected: null},+ {name: 'backspace', input: 'https://example.com/a\x08z', expected: null},+ {name: 'form feed', input: 'https://example.com/a\x0cz', expected: null},+ {name: 'last C0 control', input: 'https://example.com/a\x1fz', expected: null},+ {name: 'space after C0 range', input: 'https://example.com/a z', expected: null},+ {name: 'delete character', input: 'https://example.com/a\x7fz', expected: 'https://example.com/a%7fz'},+ {name: 'next line C1 character', input: 'https://example.com/a\x85z', expected: 'https://example.com/a%c2%85z'},+ {name: 'nonbreaking space', input: 'https://example.com/a\u00a0z', expected: null},+ {name: 'zero width space', input: 'https://example.com/a\u200bz', expected: 'https://example.com/a%e2%80%8bz'},+ {name: 'line separator', input: 'https://example.com/a\u2028z', expected: null},+ {name: 'paragraph separator', input: 'https://example.com/a\u2029z', expected: null},+ {name: 'byte order mark', input: 'https://example.com/a\ufeffz', expected: null},+ {+ name: 'outer Unicode whitespace',+ input: '\u00a0\ufeffHTTPS://Example.com/Path\u00a0\ufeff',+ expected: 'https://example.com/path',+ },+ {+ name: 'encoded controls and space',+ input: 'https://example.com/%00%1F%20',+ expected: 'https://example.com/%00%1f%20',+ },+ {name: 'leading null control', input: '\x00https://example.com/path', expected: null},+ {name: 'trailing unit separator', input: 'https://example.com/path\x1f', expected: null},+ {+ name: 'unpaired high surrogate',+ input: 'https://example.com/a\ud800z',+ expected: 'https://example.com/a%ef%bf%bdz',+ },+ {+ name: 'surrogate pair',+ input: 'https://example.com/a\ud83d\ude00z',+ expected: 'https://example.com/a%f0%9f%98%80z',+ },+ {name: 'query control', input: 'https://example.com/?q=a\x1fz', expected: null},+ {+ name: 'query zero width space',+ input: 'https://example.com/?q=a\u200bz',+ expected: 'https://example.com/?q=a%e2%80%8bz',+ },+ ])('$name', ({input, expected}) => {+ expect(canonicalizeUrl(input)).toBe(expected);+ });+});