Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 37 additions & 0 deletions packages/common/server/parser-user-agent.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -128,6 +128,43 @@ describe('parseUserAgent', () => {
model: 'Custom Model',
});
});

it('should apply overrides on a non-browser sdk user agent', () => {
// A native SDK sends a plain name/version UA, which the server heuristic
// matches, but it also states what the device is. The overrides win.
const ua = 'my-sdk/1.0.0';
const overrides = {
__os: 'Android',
__osVersion: '13',
__device: 'mobile',
__brand: 'Acme',
__model: 'A105',
};

expect(parseUserAgent(ua, overrides)).toEqual({
isServer: false,
device: 'mobile',
os: 'Android',
osVersion: '13',
browser: undefined,
browserVersion: undefined,
brand: 'Acme',
model: 'A105',
});
});

it('should still be a server when a non-browser user agent sends no device overrides', () => {
expect(parseUserAgent('my-sdk/1.0.0', { __ip: '1.2.3.4' })).toEqual({
isServer: true,
device: 'server',
os: '',
osVersion: '',
browser: '',
browserVersion: '',
brand: '',
model: '',
});
});
});

describe('getDevice', () => {
Expand Down
14 changes: 13 additions & 1 deletion packages/common/server/parser-user-agent.ts
Original file line number Diff line number Diff line change
Expand Up @@ -247,7 +247,10 @@ export function parseUserAgent(
if (!ua) return parsedServerUa;
const res = parse(ua);

if (isServer(res)) {
// A native SDK sends a plain name/version UA, which the server heuristic
// matches, but it also states what device it is running on. Trust that over
// the heuristic, otherwise the overrides are silently dropped.
if (isServer(res) && !hasDeviceOverrides(overrides)) {
return parsedServerUa;
}

Expand Down Expand Up @@ -287,6 +290,15 @@ export function parseUserAgent(
} as const;
}

const DEVICE_OVERRIDE_KEYS = ['__os', '__device', '__brand', '__model'] as const;

function hasDeviceOverrides(overrides?: Record<string, unknown>) {
if (!overrides) return false;
return DEVICE_OVERRIDE_KEYS.some(
(key) => typeof overrides[key] === 'string' && overrides[key] !== '',
);
}

function isServer(res: UAParser.IResult) {
// Matches user agents like "Go-http-client/1.0" or "Go Http Client/1.0"
// It should just match the first name (with optional spaces) and version
Expand Down