From 5da2daa50b5f9151041fdd016fb06fc4a5e1dcb5 Mon Sep 17 00:00:00 2001 From: Gerardo Sabetta Date: Fri, 4 Dec 2026 13:51:50 -0300 Subject: [PATCH 1/2] fix(depscore): poll for packages not yet scanned (SURF-2362) --- lib/tool-depscore.mts | 8 +++++--- test/repo/unit/tool-depscore.test.mts | 2 ++ 2 files changed, 7 insertions(+), 3 deletions(-) diff --git a/lib/tool-depscore.mts b/lib/tool-depscore.mts index 65fc65f9..2a7c8b86 100644 --- a/lib/tool-depscore.mts +++ b/lib/tool-depscore.mts @@ -41,10 +41,12 @@ export interface DepscoreRequestOptions { // Default Socket API URL. SOCKET_DEBUG=true points at localhost for local // stack development; the default targets production. Both env vars resolved // via shared helpers. Alert summaries list returned types and severities -// without including the full alert payload in the tool response. +// without including the full alert payload in the tool response. `poll` +// waits for packages Socket hasn't scanned yet; `timeoutSec` stays under +// httpRequest's 30s default timeout. const DEFAULT_SOCKET_API_URL = envAsBoolean(getSocketDebug()) - ? 'http://localhost:8866/v0/purl?alerts=true&compact=false&fixable=false&licenseattrib=false&licensedetails=false' - : 'https://api.socket.dev/v0/purl?alerts=true&compact=false&fixable=false&licenseattrib=false&licensedetails=false' + ? 'http://localhost:8866/v0/purl?alerts=true&compact=false&fixable=false&licenseattrib=false&licensedetails=false&poll=true&timeoutSec=20' + : 'https://api.socket.dev/v0/purl?alerts=true&compact=false&fixable=false&licenseattrib=false&licensedetails=false&poll=true&timeoutSec=20' const SOCKET_API_URL = getSocketApiUrl() || DEFAULT_SOCKET_API_URL const SOCKET_ALERT_TYPES_URL = new URL( diff --git a/test/repo/unit/tool-depscore.test.mts b/test/repo/unit/tool-depscore.test.mts index bd33ceb7..e54b35a4 100644 --- a/test/repo/unit/tool-depscore.test.mts +++ b/test/repo/unit/tool-depscore.test.mts @@ -358,6 +358,8 @@ describe('handleDepscore', () => { fixable: 'false', licenseattrib: 'false', licensedetails: 'false', + poll: 'true', + timeoutSec: '20', }) .reply( 200, From ed2f5e937a2c650b5b787a3dd871867d669048c9 Mon Sep 17 00:00:00 2001 From: Gerardo Sabetta Date: Fri, 4 Dec 2026 15:03:35 -0300 Subject: [PATCH 2/2] fix(depscore): poll only packages the first lookup left unscored --- lib/tool-depscore.mts | 97 ++++++++++++++++++++++++--- test/repo/unit/tool-depscore.test.mts | 83 ++++++++++++++++++++++- 2 files changed, 170 insertions(+), 10 deletions(-) diff --git a/lib/tool-depscore.mts b/lib/tool-depscore.mts index 2a7c8b86..0ceeb930 100644 --- a/lib/tool-depscore.mts +++ b/lib/tool-depscore.mts @@ -41,14 +41,20 @@ export interface DepscoreRequestOptions { // Default Socket API URL. SOCKET_DEBUG=true points at localhost for local // stack development; the default targets production. Both env vars resolved // via shared helpers. Alert summaries list returned types and severities -// without including the full alert payload in the tool response. `poll` -// waits for packages Socket hasn't scanned yet; `timeoutSec` stays under -// httpRequest's 30s default timeout. +// without including the full alert payload in the tool response. const DEFAULT_SOCKET_API_URL = envAsBoolean(getSocketDebug()) - ? 'http://localhost:8866/v0/purl?alerts=true&compact=false&fixable=false&licenseattrib=false&licensedetails=false&poll=true&timeoutSec=20' - : 'https://api.socket.dev/v0/purl?alerts=true&compact=false&fixable=false&licenseattrib=false&licensedetails=false&poll=true&timeoutSec=20' + ? 'http://localhost:8866/v0/purl?alerts=true&compact=false&fixable=false&licenseattrib=false&licensedetails=false' + : '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, @@ -393,7 +399,13 @@ 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, @@ -401,8 +413,8 @@ export async function handleDepscoreRequest( ) 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; @@ -435,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 { + const lines = isNdjson ? responseText.split(/\r?\n/) : [responseText] + const unscored = new Map() + 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() + } + } + } 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. diff --git a/test/repo/unit/tool-depscore.test.mts b/test/repo/unit/tool-depscore.test.mts index e54b35a4..20ed5e6d 100644 --- a/test/repo/unit/tool-depscore.test.mts +++ b/test/repo/unit/tool-depscore.test.mts @@ -358,8 +358,6 @@ describe('handleDepscore', () => { fixable: 'false', licenseattrib: 'false', licensedetails: 'false', - poll: 'true', - timeoutSec: '20', }) .reply( 200, @@ -382,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')