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
89 changes: 86 additions & 3 deletions lib/tool-depscore.mts
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,14 @@ const DEFAULT_SOCKET_API_URL = envAsBoolean(getSocketDebug())
: 'https://api.socket.dev/v0/purl?alerts=true&compact=false&fixable=false&licenseattrib=false&licensedetails=false'

const SOCKET_API_URL = getSocketApiUrl() || DEFAULT_SOCKET_API_URL
// `poll` waits for packages Socket hasn't scanned yet; `timeoutSec` stays
// under httpRequest's 30s default timeout.
const SOCKET_API_POLL_URL = (() => {
const url = new URL(SOCKET_API_URL)
url.searchParams.set('poll', 'true')
url.searchParams.set('timeoutSec', '20')
return url.toString()
})()
const SOCKET_ALERT_TYPES_URL = new URL(
'/v0/alert-types',
SOCKET_API_URL,
Expand Down Expand Up @@ -391,16 +399,22 @@ export async function handleDepscoreRequest(
try {
const contentTypeValue = response.headers['content-type'] || ''
const isNdjson = contentTypeValue.includes('x-ndjson')
const alertTypes = collectDepscoreAlertTypes(responseText, isNdjson)
const bodyText = await pollUnscored(
responseText,
isNdjson,
accessToken,
userAgent,
)
const alertTypes = collectDepscoreAlertTypes(bodyText, isNdjson)
const alertMetadata = await fetchDepscoreAlertTypeMetadata(
alertTypes,
accessToken,
userAgent,
)

const parseResult = isNdjson
? parseNdjsonPackageBody(responseText, platform, alertMetadata)
: parseSinglePackageBody(responseText, alertMetadata)
? parseNdjsonPackageBody(bodyText, platform, alertMetadata)
: parseSinglePackageBody(bodyText, alertMetadata)

if (!Array.isArray(parseResult)) {
// Only control frames (every purl unresolved) is the caller's outcome;
Expand Down Expand Up @@ -433,6 +447,75 @@ export async function handleDepscoreRequest(
}
}

function hasOverallScore(doc: unknown): boolean {
const score: unknown = isObject(doc) ? Reflect.get(doc, 'score') : undefined
return isObject(score) && Reflect.get(score, 'overall') !== undefined
}

// Wait for the packages the first lookup left unscored. Only those are
// polled: poll=true answers pendingScan for many already-scored packages
// while Socket re-analyzes them, so each answer is kept only with a score.
async function pollUnscored(
responseText: string,
isNdjson: boolean,
accessToken: string,
userAgent: string | undefined,
): Promise<string> {
const lines = isNdjson ? responseText.split(/\r?\n/) : [responseText]
const unscored = new Map<string, number>()
for (let i = 0, { length } = lines; i < length; i += 1) {
let doc: unknown
try {
doc = JSON.parse(lines[i]!)
} catch {
continue
}
if (!isObject(doc) || Reflect.get(doc, '_type') || hasOverallScore(doc)) {
continue
}
const inputPurl: unknown = Reflect.get(doc, 'inputPurl')
if (typeof inputPurl === 'string') {
unscored.set(inputPurl, i)
}
}
if (!unscored.size) {
return responseText
}

try {
const response = await httpRequest(SOCKET_API_POLL_URL, {
method: 'POST',
headers: buildSocketHeaders(accessToken, userAgent),
body: JSON.stringify({
components: [...unscored.keys()].map(purl => ({ purl })),
}),
})
if (response.status !== 200) {
return responseText
}
const fallbackLines = response.text().split(/\r?\n/)
for (let i = 0, { length } = fallbackLines; i < length; i += 1) {
let doc: unknown
try {
doc = JSON.parse(fallbackLines[i]!)
} catch {
continue
}
const inputPurl: unknown = isObject(doc)
? Reflect.get(doc, 'inputPurl')
: undefined
const index =
typeof inputPurl === 'string' ? unscored.get(inputPurl) : undefined
if (index !== undefined && hasOverallScore(doc)) {
lines[index] = fallbackLines[i]!.trim()
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Poll keeps one artifact per purl

Medium Severity

pollUnscored keeps only the last line index for each inputPurl. Both the lookup and the poll can return several artifacts for one purl. Each scored poll row overwrites that same index, leaving earlier rows unscored. deduplicateArtifacts can then keep an unscored sibling or the wrong build, so platform does not choose among the poll artifacts.

Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit ed2f5e9. Configure here.

}
} catch {
logger.warn({ tool: 'depscore' }, 'poll for unscored packages failed')
}
return lines.join('\n')
}

// Parse an NDJSON response body — one JSON document per line — into result
// lines, dropping `_type`-tagged control frames and running the platform-aware
// artifact deduplication before formatting.
Expand Down
81 changes: 81 additions & 0 deletions test/repo/unit/tool-depscore.test.mts
Original file line number Diff line number Diff line change
Expand Up @@ -380,6 +380,87 @@ describe('handleDepscore', () => {
expect(result.content[0]!.text).toMatch(/pkg:npm\/express@4.18.2/)
})

test('polls only the packages the first lookup left unscored', async () => {
const scanned = {
inputPurl: 'pkg:npm/express@4.18.2',
type: 'npm',
name: 'express',
version: '4.18.2',
score: { overall: 0.88, supplyChain: 0.97 },
}
const missing = {
inputPurl: 'pkg:npm/fresh@1.0.0',
type: 'npm',
name: 'fresh',
version: '1.0.0',
alerts: [{ type: 'notFound' }],
}
nock(API)
.post('/v0/purl')
.query(q => q['poll'] === undefined && q['timeoutSec'] === undefined)
.reply(200, `${JSON.stringify(scanned)}\n${JSON.stringify(missing)}\n`, {
'content-type': 'application/x-ndjson',
})
const poll = nock(API)
.post('/v0/purl', { components: [{ purl: 'pkg:npm/fresh@1.0.0' }] })
.query(q => q['poll'] === 'true' && q['timeoutSec'] === '20')
.reply(
200,
JSON.stringify({
...missing,
alerts: [],
score: { overall: 0.95, maintenance: 0.96 },
}),
{ 'content-type': 'application/x-ndjson' },
)

const result = await handleDepscore(
[
{ depname: 'express', version: '4.18.2' },
{ depname: 'fresh', version: '1.0.0' },
],
undefined,
'tok',
)
expect(poll.isDone()).toBe(true)
expect(result.content[0]!.text).toMatch(/express@4\.18\.2: supplyChain: 97/)
expect(result.content[0]!.text).toMatch(/fresh@1\.0\.0: maintenance: 96/)
})

test('keeps the first answer when polling returns no score', async () => {
const missing = {
inputPurl: 'pkg:npm/new@0.0.1',
type: 'npm',
name: 'new',
version: '0.0.1',
alerts: [{ type: 'notFound' }],
}
nock(API)
.post('/v0/purl')
.query(q => q['poll'] === undefined)
.reply(200, JSON.stringify(missing), {
'content-type': 'application/x-ndjson',
})
const poll = nock(API)
.post('/v0/purl')
.query(q => q['poll'] === 'true')
.reply(
200,
JSON.stringify({ ...missing, alerts: [{ type: 'pendingScan' }] }),
{ 'content-type': 'application/x-ndjson' },
)

const result = await handleDepscore(
[{ depname: 'new', version: '0.0.1' }],
undefined,
'tok',
)
expect(poll.isDone()).toBe(true)
expect(result.content[0]!.text).toMatch(/new@0\.0\.1: No score found/)
expect(result.content[0]!.text).toMatch(/notFound/)
expect(result.content[0]!.text).not.toMatch(/pendingScan/)
})

test('includes human-readable alert reasons from Socket metadata', async () => {
nock(API)
.post('/v0/purl')
Expand Down
Loading