Skip to content

Commit 49eeea3

Browse files
committed
feat(api): add User-Agent header to raw apiFetch calls
Add getCliUserAgent() to sdk.mts that builds the CLI's full user agent string for direct (non-SDK) API calls, including the CLI product token, Node.js version, and OS platform/arch: socket/1.1.96 node/v22.0.0 linux/arm64 Add User-Agent header to queryApi() and sendApiRequest() which both go through apiFetch() bypassing the SDK. For SDK-routed calls the userAgent option already passes just the CLI product token (socket/1.1.96 ...) and the SDK constructs the full UA by prepending its own base including node/OS.
1 parent bb561fa commit 49eeea3

2 files changed

Lines changed: 23 additions & 1 deletion

File tree

src/utils/api.mts

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -39,7 +39,7 @@ import constants, {
3939
HTTP_STATUS_UNAUTHORIZED,
4040
} from '../constants.mts'
4141
import { getRequirements, getRequirementsKey } from './requirements.mts'
42-
import { getDefaultApiToken, getExtraCaCerts } from './sdk.mts'
42+
import { getCliUserAgent, getDefaultApiToken, getExtraCaCerts } from './sdk.mts'
4343

4444
import type { CResult } from '../types.mts'
4545
import type { Spinner } from '@socketsecurity/registry/lib/spinner'
@@ -437,6 +437,7 @@ async function queryApi(path: string, apiToken: string) {
437437
method: 'GET',
438438
headers: {
439439
Authorization: `Basic ${btoa(`${apiToken}:`)}`,
440+
'User-Agent': getCliUserAgent(),
440441
},
441442
})
442443
return result
@@ -622,6 +623,7 @@ export async function sendApiRequest<T>(
622623
headers: {
623624
Authorization: `Basic ${btoa(`${apiToken}:`)}`,
624625
'Content-Type': 'application/json',
626+
'User-Agent': getCliUserAgent(),
625627
},
626628
...(body ? { body: JSON.stringify(body) } : {}),
627629
}

src/utils/sdk.mts

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -50,6 +50,26 @@ import { trackCliEvent } from './telemetry/integration.mts'
5050
import type { CResult } from '../types.mts'
5151
import type { RequestInfo, ResponseInfo } from '@socketsecurity/sdk'
5252

53+
// Lazy-evaluated full CLI user agent for direct (non-SDK) API calls.
54+
// Includes the CLI product token, Node.js version, and OS platform/arch.
55+
// e.g. "socket/1.1.96 node/v22.0.0 linux/arm64"
56+
let _cliUserAgent: string | undefined
57+
export function getCliUserAgent(): string {
58+
if (!_cliUserAgent) {
59+
const name = constants.ENV.INLINED_SOCKET_CLI_NAME.replace('@', '').replace(
60+
'/',
61+
'-',
62+
)
63+
const version = constants.ENV.INLINED_SOCKET_CLI_VERSION
64+
_cliUserAgent = [
65+
`${name}/${version}`,
66+
`node/${process.version}`,
67+
`${process.platform}/${process.arch}`,
68+
].join(' ')
69+
}
70+
return _cliUserAgent
71+
}
72+
5373
const TOKEN_PREFIX = 'sktsec_'
5474
const TOKEN_PREFIX_LENGTH = TOKEN_PREFIX.length
5575
const TOKEN_VISIBLE_LENGTH = 5

0 commit comments

Comments
 (0)