@@ -8,6 +8,7 @@ import { pathToFileURL } from "node:url";
|
8 | 8 | const DEFAULT_REGISTRY = "https://registry.npmjs.org"; |
9 | 9 | const BULK_ADVISORY_PATH = "/-/npm/v1/security/advisories/bulk"; |
10 | 10 | const MIN_SEVERITY = "high"; |
| 11 | +export const BULK_ADVISORY_ERROR_BODY_MAX_CHARS = 4096; |
11 | 12 | const SEVERITY_RANK = { |
12 | 13 | info: 0, |
13 | 14 | low: 1, |
@@ -676,6 +677,45 @@ function resolveRegistryBaseUrl() {
|
676 | 677 | return configured.replace(/\/+$/u, ""); |
677 | 678 | } |
678 | 679 | |
| 680 | +export async function readBoundedBulkAdvisoryErrorText( |
| 681 | +response, |
| 682 | +maxChars = BULK_ADVISORY_ERROR_BODY_MAX_CHARS, |
| 683 | +) { |
| 684 | +if (!response.body) { |
| 685 | +return ""; |
| 686 | +} |
| 687 | + |
| 688 | +const reader = response.body.getReader(); |
| 689 | +const decoder = new TextDecoder(); |
| 690 | +let text = ""; |
| 691 | +let truncated = false; |
| 692 | + |
| 693 | +try { |
| 694 | +while (text.length <= maxChars) { |
| 695 | +const { done, value } = await reader.read(); |
| 696 | +if (done) { |
| 697 | +text += decoder.decode(); |
| 698 | +break; |
| 699 | +} |
| 700 | + |
| 701 | +text += decoder.decode(value, { stream: true }); |
| 702 | +if (text.length > maxChars) { |
| 703 | +text = text.slice(0, maxChars); |
| 704 | +truncated = true; |
| 705 | +break; |
| 706 | +} |
| 707 | +} |
| 708 | +} finally { |
| 709 | +if (truncated) { |
| 710 | +await reader.cancel().catch(() => undefined); |
| 711 | +} else { |
| 712 | +reader.releaseLock(); |
| 713 | +} |
| 714 | +} |
| 715 | + |
| 716 | +return truncated ? `${text}\n[truncated]` : text; |
| 717 | +} |
| 718 | + |
679 | 719 | export async function fetchBulkAdvisories({ |
680 | 720 | payload, |
681 | 721 | fetchImpl = fetch, |
@@ -692,7 +732,7 @@ export async function fetchBulkAdvisories({
|
692 | 732 | }); |
693 | 733 | |
694 | 734 | if (!response.ok) { |
695 | | -const bodyText = await response.text(); |
| 735 | +const bodyText = await readBoundedBulkAdvisoryErrorText(response); |
696 | 736 | throw new Error( |
697 | 737 | `Bulk advisory request failed (${response.status} ${response.statusText}): ${bodyText}`, |
698 | 738 | ); |
|