Skip to content
Merged
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
77 changes: 77 additions & 0 deletions ui/artalk/src/lib/user-agent.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
import { afterEach, describe, expect, it, vi } from 'vitest'
import { getCorrectUserAgent } from './utils'
import SubmitAddPreset from '@/plugins/editor/submit-add'
import type PlugKit from '@/plugins/editor/_kit'

const windowsUA = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64)'
const macUA = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7)'

function mockNavigator(userAgentData?: unknown, userAgent = windowsUA) {
vi.stubGlobal('navigator', { userAgent, userAgentData })
}

afterEach(() => {
vi.unstubAllGlobals()
vi.restoreAllMocks()
})

describe('User-Agent client hints', () => {
it.each([undefined, null, {}, { getHighEntropyValues: true }])(
'uses the original User-Agent when the client hints API is unavailable: %j',
async (userAgentData) => {
mockNavigator(userAgentData)
await expect(getCorrectUserAgent()).resolves.toBe(windowsUA)
},
)

it.each([
undefined,
null,
{},
{ platformVersion: null },
{ platformVersion: 13 },
{ platformVersion: '' },
{ platformVersion: 'unknown' },
{ platformVersion: 'Infinity' },
{ platformVersion: '13.invalid' },
])('uses the original User-Agent for incomplete or invalid hints: %j', async (hints) => {
mockNavigator({ platform: 'Windows', getHighEntropyValues: vi.fn().mockResolvedValue(hints) })
await expect(getCorrectUserAgent()).resolves.toBe(windowsUA)
})

it('uses the original User-Agent if the browser rejects the hints request', async () => {
vi.spyOn(console, 'error').mockImplementation(() => {})
mockNavigator({ getHighEntropyValues: vi.fn().mockRejectedValue(new Error('Denied')) })
await expect(getCorrectUserAgent()).resolves.toBe(windowsUA)
})

it.each([
['Windows', '13.0.0', windowsUA, windowsUA.replace('10.0', '11.0')],
['Windows', '10.0.0', windowsUA, windowsUA],
['macOS', '12.3.0', macUA, macUA.replace('10_15_7', '12_3_0')],
['macOS', '10.15.7', macUA, macUA],
['Linux', '13.0.0', 'Linux browser', 'Linux browser'],
])('preserves platform correction for %s %s', async (platform, platformVersion, ua, expected) => {
const getHighEntropyValues = vi.fn().mockResolvedValue({ platformVersion })
mockNavigator({ platform, getHighEntropyValues }, ua)
await expect(getCorrectUserAgent()).resolves.toBe(expected)
expect(getHighEntropyValues).toHaveBeenCalledWith(['platformVersion'])
})

it('still submits a comment when a privacy extension omits platformVersion', async () => {
mockNavigator({ platform: 'Windows', getHighEntropyValues: vi.fn().mockResolvedValue({}) })
const comment = { id: 1, content: 'Hello' }
const createComment = vi.fn().mockResolvedValue({ data: comment })
const kit = {
useUser: () => ({ getData: () => ({ name: 'Test', email: 'test@example.com', link: '' }) }),
useConf: () => ({ pageKey: '/', pageTitle: 'Test page', site: 'Test site' }),
useEditor: () => ({ getContentFinal: () => 'Hello' }),
useApi: () => ({ comments: { createComment } }),
} as unknown as PlugKit

await expect(new SubmitAddPreset(kit).reqAdd()).resolves.toEqual(comment)
expect(createComment).toHaveBeenCalledWith(
expect.objectContaining({ content: 'Hello', ua: windowsUA }),
)
})
})
14 changes: 10 additions & 4 deletions ui/artalk/src/lib/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -135,21 +135,27 @@ export function versionCompare(a: string, b: string) {
/** 获取修正后的 UserAgent */
export async function getCorrectUserAgent() {
const uaRaw = navigator.userAgent
if (!(navigator as any).userAgentData || !(navigator as any).userAgentData.getHighEntropyValues) {
const uaData = (navigator as any).userAgentData
if (typeof uaData?.getHighEntropyValues !== 'function') {
return uaRaw
}

// @link https://web.dev/migrate-to-ua-ch/
// @link https://web.dev/user-agent-client-hints/
const uaData = (navigator as any).userAgentData
let uaGot: any
try {
uaGot = await uaData.getHighEntropyValues(['platformVersion'])
} catch (err) {
console.error(err)
return uaRaw
}
const majorPlatformVersion = Number(uaGot.platformVersion.split('.')[0])
// Privacy extensions may omit or redact high-entropy hints. UA correction is
// optional and must not prevent a comment from being submitted.
const platformVersion = uaGot?.platformVersion
if (typeof platformVersion !== 'string' || !/^\d+(\.\d+)*$/.test(platformVersion)) {
return uaRaw
}
const majorPlatformVersion = Number(platformVersion.split('.')[0])

if (uaData.platform === 'Windows') {
if (majorPlatformVersion >= 13) {
Expand All @@ -167,7 +173,7 @@ export async function getCorrectUserAgent() {
// (Arm Chip) macOS 样本:"Mozilla/5.0 (Macintosh; ARM Mac OS X 10_15_6) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/14.0.2 Safari/605.1.15"
return uaRaw.replace(
/(Mac OS X \d+_\d+_\d+|Mac OS X)/,
`Mac OS X ${uaGot.platformVersion.replace(/\./g, '_')}`,
`Mac OS X ${platformVersion.replace(/\./g, '_')}`,
)
}
}
Expand Down