@preventive/triage 1.0.0-alpha.37 → 1.0.0-alpha.38

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (175) hide show
  1. package/README.md +16 -0
  2. package/common/bundle-compare-diff.d.ts +3 -0
  3. package/common/bundle-compare-diff.js +522 -0
  4. package/common/bundle-compare-inputs.d.ts +2 -0
  5. package/common/bundle-compare-inputs.js +65 -0
  6. package/common/bundle-metadata.d.ts +6 -2
  7. package/common/bundle-metadata.js +63 -20
  8. package/common/bundle-pkg-of.d.ts +1 -0
  9. package/common/bundle-pkg-of.js +90 -0
  10. package/common/bundle-source-links.js +7 -0
  11. package/common/bundle-sourcemap.d.ts +10 -0
  12. package/common/bundle-sourcemap.js +100 -0
  13. package/common/bundle-sources.d.ts +3 -1
  14. package/common/bundle-sources.js +47 -19
  15. package/common/code-language.js +16 -2
  16. package/common/default-scan-models.ts +2 -1
  17. package/common/dependency-reviews.d.ts +23 -0
  18. package/common/dependency-reviews.js +81 -0
  19. package/common/finding-duplicates.js +58 -0
  20. package/common/finding-filters.js +274 -0
  21. package/common/github-pr.ts +1 -1
  22. package/common/gzip.js +59 -0
  23. package/common/line-diff.d.ts +8 -0
  24. package/common/line-diff.js +56 -0
  25. package/common/linked-workspace-groups.js +63 -0
  26. package/common/managed/npm-packages.d.ts +5 -0
  27. package/common/managed/npm-packages.js +34 -0
  28. package/common/managed/permissions.ts +1 -5
  29. package/common/managed/routes.js +123 -12
  30. package/common/managed/team-app.d.ts +2 -0
  31. package/common/managed/team-app.js +31 -0
  32. package/common/managed/triage.ts +1 -1
  33. package/common/managed/upload-seal.ts +126 -0
  34. package/common/pretty-print.d.ts +5 -0
  35. package/common/pretty-print.js +24 -0
  36. package/common/revalidation-conflicts.js +48 -0
  37. package/common/revalidation-input-groups.js +56 -0
  38. package/common/workspace-app.js +23 -0
  39. package/common/workspace-groups.js +176 -0
  40. package/out/brotli-fallback.js +3 -3
  41. package/out/chunk-2KBF5TZ7.js +2 -0
  42. package/out/chunk-2XUEZHIP.js +28 -0
  43. package/out/chunk-35VE6CDH.js +2 -0
  44. package/out/chunk-3BZ7JERB.js +1 -0
  45. package/out/chunk-4XCDFGDP.js +10 -0
  46. package/out/chunk-5FKRIJGF.js +1 -0
  47. package/out/chunk-6Z5XLSPJ.js +1 -0
  48. package/out/chunk-ABW5FVSN.js +1 -0
  49. package/out/chunk-BJKRVROW.js +1 -0
  50. package/out/chunk-BYUEDJOM.js +7 -0
  51. package/out/chunk-C4Z6ZBXV.js +10 -0
  52. package/out/chunk-CMQA4DM6.js +1 -0
  53. package/out/chunk-CVVJAXVY.js +2 -0
  54. package/out/chunk-DCQX2J3C.js +223 -0
  55. package/out/chunk-DIJJNTRH.js +10 -0
  56. package/out/chunk-F4OMDNEY.js +1 -0
  57. package/out/chunk-FU4MTW7F.js +1 -0
  58. package/out/chunk-GJ4IUCNS.js +1 -0
  59. package/out/chunk-GMFXFEUA.js +2 -0
  60. package/out/chunk-GNXOKIGP.js +80 -0
  61. package/out/chunk-GZ4MS3TE.js +13 -0
  62. package/out/chunk-HIV7SVI7.js +1 -0
  63. package/out/chunk-IU3CCINR.js +3 -0
  64. package/out/chunk-JAKWIZWL.js +2 -0
  65. package/out/chunk-K3X5EJBQ.js +2 -0
  66. package/out/chunk-KEX2ATEW.js +2 -0
  67. package/out/chunk-KYCNJVB7.js +1 -0
  68. package/out/chunk-NRPC74AM.js +1 -0
  69. package/out/chunk-OJ5DGP5E.js +33 -0
  70. package/out/chunk-OOJM4CTU.js +1 -0
  71. package/out/chunk-PNHBZGDD.js +1 -0
  72. package/out/chunk-R5O6FAW4.js +2 -0
  73. package/out/chunk-RFZQQXSG.js +17 -0
  74. package/out/chunk-SD2WJAXN.js +48 -0
  75. package/out/chunk-TUII34K2.js +1 -0
  76. package/out/chunk-TZ5KB2Y5.js +10 -0
  77. package/out/chunk-UNTRGE26.js +2 -0
  78. package/out/chunk-UYAXVRVL.js +1 -0
  79. package/out/chunk-V3ME6FI5.js +2 -0
  80. package/out/chunk-V5O7M2YT.js +1 -0
  81. package/out/chunk-VIHGO77Y.js +1 -0
  82. package/out/chunk-W4J3MGLB.js +1 -0
  83. package/out/chunk-WGG7KQUH.js +1 -0
  84. package/out/chunk-XYFXXB2G.js +10 -0
  85. package/out/chunk-YVZH5SHP.js +1 -0
  86. package/out/chunk-ZPD5R5RP.js +3 -0
  87. package/out/client-managed-import.js +3 -87
  88. package/out/client-managed.js +26 -338
  89. package/out/client-sync.js +8 -14
  90. package/out/graph.js +17 -30
  91. package/out/index.html +34 -0
  92. package/out/prism.js +6 -2
  93. package/out/terminal.js +241 -257
  94. package/out/view.css +1 -1
  95. package/out/view.js +76 -520
  96. package/package.json +88 -7
  97. package/risk/files/characters.js +196 -0
  98. package/risk/files/hosts.js +205 -0
  99. package/risk/files/readability.js +164 -0
  100. package/risk/files/runs-code.js +329 -0
  101. package/risk/files/script.js +112 -0
  102. package/risk/files/stamps.js +46 -0
  103. package/risk/index.d.ts +142 -0
  104. package/risk/index.js +7 -0
  105. package/risk/npm/assess.js +219 -0
  106. package/risk/npm/combined.js +65 -0
  107. package/risk/npm/compare.js +222 -0
  108. package/risk/npm/dependencies.js +153 -0
  109. package/risk/npm/diff.js +43 -0
  110. package/risk/npm/downloads.js +84 -0
  111. package/risk/npm/files.js +34 -0
  112. package/risk/npm/held.js +60 -0
  113. package/risk/npm/install-scripts.js +33 -0
  114. package/risk/npm/malware.js +36 -0
  115. package/risk/npm/manifest.js +65 -0
  116. package/risk/npm/new-dependency.js +30 -0
  117. package/risk/npm/old-version.js +108 -0
  118. package/risk/npm/registry.js +282 -0
  119. package/risk/npm/release.js +85 -0
  120. package/risk/npm/specs.js +124 -0
  121. package/risk/npm/tarball.js +113 -0
  122. package/server-e2e/http.ts +7 -7
  123. package/server-e2e/npm-proxy.ts +1 -1
  124. package/server-e2e/objstore/fetch-mint-guard.ts +2 -2
  125. package/server-e2e/objstore/handlers.ts +1 -1
  126. package/server-e2e/objstore/tokens.ts +1 -1
  127. package/server-e2e/sign.ts +1 -1
  128. package/server-managed/bundle-advisories.ts +68 -11
  129. package/server-managed/bundle-cache.ts +37 -4
  130. package/server-managed/bundle-commits.ts +140 -0
  131. package/server-managed/bundle-summary-cache.ts +24 -10
  132. package/server-managed/config.ts +4 -0
  133. package/server-managed/db-methods.ts +98 -11
  134. package/server-managed/db-neon.ts +39 -4
  135. package/server-managed/db-schema.ts +14 -2
  136. package/server-managed/db-table-names.ts +1 -1
  137. package/server-managed/db.ts +7 -3
  138. package/server-managed/dependency-reviews.ts +248 -0
  139. package/server-managed/github-issue-oauth.ts +5 -6
  140. package/server-managed/github-metadata.ts +115 -0
  141. package/server-managed/github-oauth.ts +38 -2
  142. package/server-managed/http-response.ts +26 -0
  143. package/server-managed/http.ts +943 -52
  144. package/server-managed/index.ts +11 -5
  145. package/server-managed/kept.ts +28 -0
  146. package/server-managed/locked-packages.ts +85 -0
  147. package/server-managed/lru.ts +30 -0
  148. package/server-managed/npm-insights.ts +440 -0
  149. package/server-managed/npm-kept.ts +65 -0
  150. package/server-managed/npm-loads.ts +167 -0
  151. package/server-managed/npm-manifest.ts +115 -0
  152. package/server-managed/npm-packages.ts +378 -0
  153. package/server-managed/npm-provenance.ts +123 -0
  154. package/server-managed/npm-risk.ts +177 -0
  155. package/server-managed/pretty-print.ts +352 -0
  156. package/server-managed/public-workspace.ts +78 -7
  157. package/server-managed/rename-diff-worker.js +26 -0
  158. package/server-managed/rename-diff.ts +270 -0
  159. package/server-managed/report-sources.ts +13 -2
  160. package/server-managed/repository-browser.ts +19 -5
  161. package/server-managed/repository-risk.ts +413 -0
  162. package/server-managed/session.ts +16 -2
  163. package/server-managed/sql.ts +5 -2
  164. package/server-managed/storage-encryption.ts +5 -3
  165. package/server-managed/storage-payload.ts +4 -0
  166. package/server-managed/storage-stores.ts +2 -0
  167. package/server-managed/storage.ts +6 -3
  168. package/server-managed/team-app.ts +94 -0
  169. package/server-managed/team-feed.ts +1 -1
  170. package/server-managed/team-npm-scopes.ts +77 -0
  171. package/server-managed/type-only-worker.js +19 -0
  172. package/server-managed/type-only.ts +103 -0
  173. package/server-managed/uploads.ts +25 -4
  174. package/server-managed/upstream-cache.ts +147 -5
  175. package/server-managed/view-as.ts +58 -0
@@ -10,6 +10,8 @@ import { startServer } from '../server-common/standalone.ts'
10
10
  import { initializeApp } from '../server-common/initialize.ts'
11
11
  import { type ManagedConfig, loadManagedConfig } from './config.ts'
12
12
  import { type ManagedHttpDeps, createManagedRequestHandler } from './http.ts'
13
+ import { setNpmTarballCache } from './npm-loads.ts'
14
+ import { setNpmDocumentCache } from './npm-packages.ts'
13
15
  import { loadManagedStatic } from './static.ts'
14
16
  import { openManagedStorage } from './storage.ts'
15
17
  import { setCacheDir } from '@preventive/upstream/npm.js'
@@ -23,8 +25,12 @@ type ManagedAppOptions = Partial<Pick<ManagedHttpDeps, 'next' | 'serverInfo' | '
23
25
 
24
26
  export async function createManagedApp(config: ManagedConfig, options: ManagedAppOptions = {}) {
25
27
  // Audits keep upstream's records on disk where the config has a cache
26
- // directory; bundle builds set it in their own worker.
28
+ // directory; bundle builds set it in their own worker. The npm viewer
29
+ // keeps the tarballs it downloads there too, beside theirs, and public
30
+ // packages' whole documents (npm-packages.ts).
27
31
  setCacheDir(config.upstreamCacheDir ?? false)
32
+ setNpmTarballCache(config.upstreamCacheDir ?? null)
33
+ setNpmDocumentCache(config.upstreamCacheDir ?? null)
28
34
  // Load the optional peer only for serverless managed deployments. Embedding
29
35
  // hosts can discard listener promises, so retain maintenance inside the app.
30
36
  const waitUntil = config.serverless ? (await import('@vercel/functions')).waitUntil : undefined
@@ -33,7 +39,7 @@ export async function createManagedApp(config: ManagedConfig, options: ManagedAp
33
39
 
34
40
  async function assembleManagedApp(config: ManagedConfig, options: ManagedAppOptions, rollback: AsyncDisposableStack, waitUntil?: (promise: Promise<unknown>) => void) {
35
41
  const storage = await openManagedStorage(config)
36
- const { db, avatarStore, reportStore, bundleStore, bundleCache, reportSourcesCache } = storage
42
+ const { db, avatarStore, reportStore, bundleStore, bundleCache, reportSourcesCache, prettyCache, npmCacheStorage } = storage
37
43
  rollback.defer(() => db.close())
38
44
  const originGate = createOriginGate(config.host, config.trustProxyEnv)
39
45
 
@@ -49,13 +55,12 @@ async function assembleManagedApp(config: ManagedConfig, options: ManagedAppOpti
49
55
  indexOnly: options.next != null, scanServer: options.serverInfo?.deepviewScanServer ?? null,
50
56
  })
51
57
  const routeRequest = createManagedRequestHandler({
52
- ...options, config, db, avatarStore, reportStore, bundleStore, bundleCache, reportSourcesCache, originGate, serveStatic,
58
+ ...options, config, db, avatarStore, reportStore, bundleStore, bundleCache, reportSourcesCache, prettyCache, npmCacheStorage, originGate, serveStatic,
53
59
  ...(storage.uploadStore ? { uploadStore: storage.uploadStore } : {}),
54
60
  isShuttingDown, track,
55
61
  })
56
62
 
57
- let cleanup: Promise<void> | undefined
58
- let nextCleanupAt = 0
63
+ let cleanup: Promise<void> | undefined, nextCleanupAt = 0
59
64
  const maintenance = new AbortController()
60
65
  function reap(automatic = false): Promise<void> {
61
66
  if (cleanup) return cleanup
@@ -71,6 +76,7 @@ async function assembleManagedApp(config: ManagedConfig, options: ManagedAppOpti
71
76
  await runReapers({
72
77
  sessions: async () => { sessions = await db.deleteExpiredSessions(Date.now()) },
73
78
  ...(storage.reapUploads ? { uploads: async () => { uploads = await storage.reapUploads!(maintenance.signal) } } : {}),
79
+ ...('reapPrettyCopies' in storage ? { prettyCopies: () => storage.reapPrettyCopies(maintenance.signal) } : {}),
74
80
  ...('reapStorage' in storage ? { storage: () => storage.reapStorage(maintenance.signal) } : {}),
75
81
  })
76
82
  succeeded = true
@@ -0,0 +1,28 @@
1
+ // Answers kept for an hour, by what they answer (npm-insights.ts,
2
+ // npm-provenance.ts), at most `max` of them, the oldest asked going first;
3
+ // one still being asked for is shared, and one that failed, or that `whole`
4
+ // says is partial, is dropped once it is answered. `peek` gives one already
5
+ // answered, asking for nothing; undefined where none is.
6
+ const KEPT_MS = 60 * 60_000
7
+
8
+ export function kept<T>(max: number, whole: (value: T) => boolean = () => true) {
9
+ const answers = new Map<string, { at: number; value: Promise<T>; answered?: { value: T } }>()
10
+ const get = (key: string, ask: () => Promise<T>): Promise<T> => {
11
+ const now = Date.now()
12
+ const hit = answers.get(key)
13
+ if (hit && now - hit.at < KEPT_MS) return hit.value
14
+ const value = ask()
15
+ const entry: { at: number; value: Promise<T>; answered?: { value: T } } = { at: now, value }
16
+ answers.delete(key)
17
+ answers.set(key, entry)
18
+ while (answers.size > max) answers.delete(answers.keys().next().value!)
19
+ const drop = () => { if (answers.get(key) === entry) answers.delete(key) }
20
+ value.then(answer => { if (whole(answer)) entry.answered = { value: answer }; else drop(); return answer }, drop)
21
+ return value
22
+ }
23
+ const peek = (key: string): T | undefined => {
24
+ const hit = answers.get(key)
25
+ return hit?.answered && Date.now() - hit.at < KEPT_MS ? hit.answered.value : undefined
26
+ }
27
+ return Object.assign(get, { peek })
28
+ }
@@ -0,0 +1,85 @@
1
+ // The packages a lockfile of npm's ecosystem locks, as @preventive/lockfile
2
+ // reads package-lock.json and npm-shrinkwrap.json of `lockfileVersion: 3`,
3
+ // pnpm-lock.yaml of pnpm 9 to 12 and Yarn 1's yarn.lock, each with where it
4
+ // is installed from (repository-risk.ts).
5
+ import { LockfileError, parseNpmLockfile } from '@preventive/lockfile/npm.js'
6
+ import { parsePnpmLockfile } from '@preventive/lockfile/pnpm.js'
7
+ import { parseYarn1Lockfile } from '@preventive/lockfile/yarn1.js'
8
+ import type { LockfileFormat } from '@preventive/upstream/github.js'
9
+
10
+ export interface LockedPackage {
11
+ name: string
12
+ // None for a git dependency whose package.json has none.
13
+ version: string | null
14
+ // Where it is installed from: npm's registry, another host's tarball with
15
+ // an integrity, such as a company's mirror of npm's, a git repository, a
16
+ // tarball with none, or a file of the project.
17
+ source: 'registry' | 'mirror' | 'git' | 'tarball' | 'file'
18
+ // Where one from elsewhere than npm's registry comes from, without any
19
+ // credentials its URL has.
20
+ from?: string
21
+ // A mirror's tarball's, as the lockfile has it: npm's package of its name
22
+ // and version only where npm's integrity is among it.
23
+ integrity?: string
24
+ }
25
+
26
+ // A package as each reader resolves one, its name the one it is published
27
+ // under, and a registry tarball's URL held to its name and version.
28
+ type Resolution =
29
+ | { type: 'tarball'; tarball: string | undefined; integrity: string | undefined; gitHosted?: boolean }
30
+ | { type: 'git'; repo: string }
31
+ | { type: 'directory' }
32
+ interface ReadPackage { name: string; version: string | undefined; resolution: Resolution | undefined }
33
+
34
+ // The packages of a lockfile of `format`, as its reader resolves them.
35
+ // Versions go unchecked against ranges, as only what is locked is asked for.
36
+ function packagesOf(format: LockfileFormat, text: string): ReadPackage[] {
37
+ if (format === 'npm') return Object.values(parseNpmLockfile(text, { checkVersions: false }).packages)
38
+ if (format === 'pnpm') {
39
+ const { lockfile, env } = parsePnpmLockfile(text)
40
+ return [...Object.values(env?.packages ?? {}), ...Object.values(lockfile?.packages ?? {})]
41
+ }
42
+ if (format !== 'yarn') throw new TypeError(`lockedPackages: ${format} lockfiles are not read`)
43
+ // Yarn 2 and later write another format, which only the text tells apart.
44
+ if (/^__metadata:/mu.test(text)) throw new LockfileError('a yarn.lock of Yarn 2 or later, which is not read')
45
+ // Yarn 1 names an alias, `my-q@npm:q@^1.5.1`, by its own name.
46
+ return Object.values(parseYarn1Lockfile(text, { checkVersions: false }).packages)
47
+ .map(pkg => ({ ...pkg, name: /@npm:((?:@[^/@]+\/)?[^/@]+)/u.exec(pkg.patterns[0] ?? '')?.[1] ?? pkg.name }))
48
+ }
49
+
50
+ // npm's registry, by either of its names, and yarn's mirror of it, as
51
+ // @preventive/lockfile holds their tarballs to a package's name and version.
52
+ const REGISTRY_HOSTS = new Set(['registry.npmjs.org', 'registry.npmjs.com', 'registry.yarnpkg.com'])
53
+ const isRegistry = (url: URL) => url.protocol === 'https:' && !url.port && !url.username && !url.password
54
+ && REGISTRY_HOSTS.has(url.hostname.replace(/\.+$/u, ''))
55
+ // Where a URL is, as it may be shown: its credentials, query and fragment
56
+ // left out.
57
+ const shown = (url: URL | null) => url ? { from: `${url.protocol}//${url.host}${url.pathname}` } : {}
58
+
59
+ // Where a package read comes from (LockedPackage); null for one a package
60
+ // bundles, with no resolution, or one of the project's own directories.
61
+ function locked({ name, version, resolution }: ReadPackage): LockedPackage | null {
62
+ const at = { name, version: version ?? null }
63
+ if (resolution === undefined || resolution.type === 'directory') return null
64
+ if (resolution.type === 'git') return { ...at, source: 'git', ...shown(URL.parse(resolution.repo)) }
65
+ const { tarball, integrity } = resolution
66
+ if (resolution.gitHosted) return { ...at, source: 'git', ...shown(URL.parse(tarball ?? '')) }
67
+ if (tarball === undefined) return { ...at, source: 'registry' }
68
+ if (tarball.startsWith('file:')) return { ...at, source: 'file' }
69
+ const url = URL.parse(tarball)
70
+ if (url && isRegistry(url)) return { ...at, source: 'registry' }
71
+ return integrity ? { ...at, ...shown(url), source: 'mirror', integrity } : { ...at, ...shown(url), source: 'tarball' }
72
+ }
73
+
74
+ // The packages a lockfile of `format` (npm, pnpm or yarn, as
75
+ // findRepoLockfiles names them) locks, each once, in the lockfile's order.
76
+ // Throws the reader's LockfileError or YamlError for one it refuses.
77
+ export function lockedPackages(format: LockfileFormat, text: string): LockedPackage[] {
78
+ const found = new Map<string, LockedPackage>()
79
+ for (const pkg of packagesOf(format, text)) {
80
+ const one = locked(pkg)
81
+ const key = one && `${one.source}\0${one.name}@${one.version ?? ''}\0${one.from ?? ''}\0${one.integrity ?? ''}`
82
+ if (one && key && !found.has(key)) found.set(key, one)
83
+ }
84
+ return [...found.values()]
85
+ }
@@ -0,0 +1,30 @@
1
+ // Values by key, the least recently used going first once their weights
2
+ // (`weight`, 1 each unless given) are past `limit`.
3
+ export interface Lru<V> { get(key: string): V | undefined; set(key: string, value: V): void }
4
+ export function lru<V>(limit: number, weight: (value: V) => number = () => 1): Lru<V> {
5
+ const kept = new Map<string, V>()
6
+ let total = 0
7
+ const forget = (key: string) => {
8
+ const value = kept.get(key)
9
+ if (value === undefined) return
10
+ kept.delete(key)
11
+ total -= weight(value)
12
+ }
13
+ return {
14
+ get(key) {
15
+ const value = kept.get(key)
16
+ if (value !== undefined) { kept.delete(key); kept.set(key, value) }
17
+ return value
18
+ },
19
+ set(key, value) {
20
+ forget(key)
21
+ if (weight(value) > limit) return
22
+ kept.set(key, value)
23
+ total += weight(value)
24
+ for (const first of kept.keys()) {
25
+ if (total <= limit) break
26
+ forget(first)
27
+ }
28
+ },
29
+ }
30
+ }
@@ -0,0 +1,440 @@
1
+ // Figures and advisories for the npm package viewer's Overview, beside a
2
+ // version's files (npm-packages.ts, npm-loads.ts): the package's downloads
3
+ // over the last year, from npm's public downloads API; its GitHub
4
+ // repository's stars, forks and open issues; and its advisories across every
5
+ // published version, as `npm audit` has them and as its repository publishes
6
+ // them on GitHub, asked as bundle advisories ask (bundle-advisories.ts); and
7
+ // Socket's scores and alerts for a version. All of it is public: npm is asked
8
+ // without the server's token, Socket only about a version npm answers for
9
+ // without one (http.ts), and a repository's figures, tags and advisories are
10
+ // asked for, and kept, only where GitHub says it is public. Each
11
+ // answer is kept for an hour, a failure not at all; the reader's access to
12
+ // the package is checked on every request before any of it is answered
13
+ // (http.ts handleNpm).
14
+ import type { Advisory, CacheStore } from '@preventive/upstream/advisories.js'
15
+ import { type Client, HttpError, createClient } from '@preventive/upstream/github.js'
16
+ import { ADVISORIES_TIMEOUT_MS, fetchBundleAdvisories } from './bundle-advisories.ts'
17
+ import { isExactVersion } from '@preventive/upstream/semver.js'
18
+ import { kept } from './kept.ts'
19
+ import { type NpmProvenance, keptNpmProvenance } from './npm-provenance.ts'
20
+ import { NpmPackageError, askUpstreamJson, plainObject, readLimited } from './npm-packages.ts'
21
+
22
+ const DOWNLOADS_API = 'https://api.npmjs.org/downloads/range'
23
+ // What npm's range API may answer for each package asked: a year of days is
24
+ // some 16 KiB.
25
+ const DOWNLOADS_BYTES = 64 * 1024
26
+ // Socket's answer for a package version, by its purl, as Socket Firewall
27
+ // asks it: no key needed. Its scores are cut to two decimals; its badge's,
28
+ // the supply chain score, is rounded (askSocketBadge).
29
+ const SOCKET_API = 'https://firewall-api.socket.dev/purl'
30
+ const SOCKET_BADGE = 'https://badge.socket.dev/npm/package'
31
+ const BADGE_BYTES = 16 * 1024
32
+ const API_TIMEOUT_MS = 30_000
33
+ const API_BYTES = 1024 * 1024
34
+ const DAY_MS = 24 * 60 * 60_000
35
+ const SEVERITY_RANK: Record<string, number> = { critical: 0, high: 1, moderate: 2, low: 3 }
36
+
37
+ const count = (value: unknown) => Number.isSafeInteger(value) && (value as number) >= 0 ? value as number : 0
38
+ const isDay = (value: unknown): value is string => typeof value === 'string' && /^\d{4}-\d{2}-\d{2}$/u.test(value) && !Number.isNaN(Date.parse(value))
39
+
40
+ // A package's downloads, one count a day from `start` to `end` (UTC dates),
41
+ // none for a day npm leaves out; null where npm has none for it.
42
+ export interface NpmDownloads { start: string; end: string; days: number[] }
43
+
44
+ const isoDay = (time: number) => new Date(time).toISOString().slice(0, 10)
45
+
46
+ // Its last year, as npm counts it (to the last day it has counted), from
47
+ // the first of the month that year starts in, so that month is whole too.
48
+ async function askDownloads(name: string): Promise<NpmDownloads | null> {
49
+ const year = await askDownloadRange('last-year', name)
50
+ const start = new Date(year?.start ?? 0)
51
+ if (year === null || start.getUTCDate() === 1) return year
52
+ const first = Date.UTC(start.getUTCFullYear(), start.getUTCMonth(), 1)
53
+ const before = await askDownloadRange(`${isoDay(first)}:${isoDay(start.getTime() - DAY_MS)}`, name).catch(() => null)
54
+ return before?.start === isoDay(first) && before.days.length === (start.getTime() - first) / DAY_MS
55
+ ? { start: before.start, end: year.end, days: [...before.days, ...year.days] } : year
56
+ }
57
+
58
+ // npm's downloads of `name` over `range`: null where npm has none.
59
+ async function askDownloadRange(range: string, name: string): Promise<NpmDownloads | null> {
60
+ const json = await askUpstreamJson(`${DOWNLOADS_API}/${range}/${name.replace('/', '%2f')}`, { headers: { accept: 'application/json' }, limit: DOWNLOADS_BYTES })
61
+ return json === null ? null : readDownloads(json)
62
+ }
63
+
64
+ // One package's downloads as npm's range API gives them.
65
+ function readDownloads(json: unknown): NpmDownloads {
66
+ if (!plainObject(json) || !isDay(json['start']) || !isDay(json['end']) || !Array.isArray(json['downloads'])) throw new NpmPackageError(502, 'upstream-invalid')
67
+ const start = Date.parse(json['start'])
68
+ const length = (Date.parse(json['end']) - start) / DAY_MS + 1
69
+ if (!Number.isSafeInteger(length) || length < 1 || length > 400) throw new NpmPackageError(502, 'upstream-invalid')
70
+ const days = Array.from({ length }, () => 0)
71
+ for (const row of json['downloads']) {
72
+ if (!plainObject(row) || !isDay(row['day'])) continue
73
+ const at = (Date.parse(row['day']) - start) / DAY_MS
74
+ if (Number.isSafeInteger(at) && at >= 0 && at < length) days[at] = count(row['downloads'])
75
+ }
76
+ return { start: json['start'], end: json['end'], days }
77
+ }
78
+
79
+ const downloads = kept<NpmDownloads | null>(500)
80
+ // The repository each package's latest version names (owner/name, null where
81
+ // it names none), as its figures were first asked with within the hour: what
82
+ // npmKnown finds them by.
83
+ const latestRepos = kept<string | null>(500)
84
+
85
+ export const npmLatestRepo = (name: string, repo: string | null): void => void latestRepos(name, () => Promise.resolve(repo))
86
+
87
+ export function npmDownloads(name: string): Promise<NpmDownloads | null> {
88
+ return downloads(name, () => askDownloads(name))
89
+ }
90
+
91
+ const SOCKET_SCORES = ['overall', 'supplyChain', 'vulnerability', 'quality', 'maintenance', 'license'] as const
92
+ const SOCKET_SEVERITY_RANK: Record<string, number> = { critical: 0, high: 1, middle: 2, low: 3 }
93
+ const SOCKET_ALERTS = 50
94
+ const SOCKET_NOTE_CHARS = 4000
95
+
96
+ // Socket's report on a version: its scores, each 0 to 1 (null where Socket
97
+ // gave none), and the alerts it raises, such as malware, most severe first,
98
+ // each with the file it was found in, by its path in the package (the
99
+ // tarball's root left out, as the package's files have it), where it names
100
+ // one, and Socket's note on it.
101
+ export interface NpmSocketAlert { type: string; severity: string; category: string | null; file: string | null; note: string | null }
102
+ export interface NpmSocketReport { scores: Record<typeof SOCKET_SCORES[number], number> | null; alerts: NpmSocketAlert[] }
103
+
104
+ const text = (value: unknown) => typeof value === 'string' && value !== '' ? value : null
105
+
106
+ // The supply chain score, out of 100, that the version's badge shows; null
107
+ // where it shows none, and undefined where it can't be had, as while Socket
108
+ // limits how often it's asked.
109
+ async function askSocketBadge(name: string, version: string): Promise<number | null | undefined> {
110
+ try {
111
+ const res = await fetch(`${SOCKET_BADGE}/${name}/${encodeURIComponent(version)}`,
112
+ { headers: { accept: 'image/svg+xml' }, redirect: 'error', signal: AbortSignal.timeout(API_TIMEOUT_MS) })
113
+ if (!res.ok) { await res.body?.cancel(); return res.status === 429 || res.status >= 500 ? undefined : null }
114
+ const shown = /<title>Socket: (\d{1,3})<\/title>/u.exec((await readLimited(res, BADGE_BYTES)).toString('utf8'))
115
+ return shown ? Number(shown[1]) : null
116
+ } catch { return undefined }
117
+ }
118
+
119
+ // Scores the badge couldn't round: Socket's own, a point low at most, their
120
+ // report answered but not kept, so the next view asks again.
121
+ const unbadged = new WeakSet<object>()
122
+
123
+ async function askSocket(name: string, version: string): Promise<NpmSocketReport | null> {
124
+ const badge = askSocketBadge(name, version)
125
+ // One line, as one purl was asked.
126
+ const json = await askUpstreamJson(`${SOCKET_API}/${encodeURIComponent(`pkg:npm/${name}@${version}`)}`,
127
+ { headers: { accept: 'application/x-ndjson' }, limit: API_BYTES }, body => JSON.parse(body.split('\n', 1)[0]!))
128
+ if (json === null) return null
129
+ if (!plainObject(json) || json['version'] !== version || [json['namespace'], json['name']].filter(Boolean).join('/') !== name) throw new NpmPackageError(502, 'upstream-invalid')
130
+ // A version Socket hasn't seen is answered with a made-up id and nothing else.
131
+ if (String(json['id']).startsWith('synthetic:')) return null
132
+ const score = json['score']
133
+ const scores = plainObject(score) && SOCKET_SCORES.every(key => typeof score[key] === 'number' && score[key] >= 0 && score[key] <= 1)
134
+ ? Object.fromEntries(SOCKET_SCORES.map(key => [key, score[key]])) as NpmSocketReport['scores'] : null
135
+ // The supply chain score as the badge rounds it, at most one more than the
136
+ // score cut to two decimals; lower where the badge is, as when the score
137
+ // has fallen since.
138
+ const shown = await badge
139
+ if (scores && typeof shown === 'number') scores.supplyChain = Math.min(Math.round(scores.supplyChain * 100) + 1, shown) / 100
140
+ else if (scores && shown === undefined) unbadged.add(scores)
141
+ const alerts = (Array.isArray(json['alerts']) ? json['alerts'] : [])
142
+ .filter((alert): alert is Record<string, unknown> => plainObject(alert) && text(alert['type']) !== null && typeof alert['severity'] === 'string' && alert['severity'] in SOCKET_SEVERITY_RANK)
143
+ .slice(0, SOCKET_ALERTS)
144
+ .map(alert => ({
145
+ type: alert['type'] as string, severity: alert['severity'] as string, category: text(alert['category']),
146
+ file: text(text(alert['file'])?.replace(/^[^/]*\//u, '')),
147
+ note: text(plainObject(alert['props']) ? alert['props']['note'] : null)?.slice(0, SOCKET_NOTE_CHARS) ?? null,
148
+ }))
149
+ .toSorted((a, b) => SOCKET_SEVERITY_RANK[a.severity]! - SOCKET_SEVERITY_RANK[b.severity]!)
150
+ return scores === null && alerts.length === 0 ? null : { scores, alerts }
151
+ }
152
+
153
+ const socketReports = kept<NpmSocketReport | null>(1000, report => !report?.scores || !unbadged.has(report.scores))
154
+
155
+ // Socket's report on a version of a public package; null where Socket has
156
+ // none. Its name goes to Socket: never ask it about a private one.
157
+ export function npmSocketReport(name: string, version: string): Promise<NpmSocketReport | null> {
158
+ return socketReports(`${name}@${version}`, () => askSocket(name, version))
159
+ }
160
+
161
+ // A public repository's figures: GitHub's `openIssues` takes in its open pull
162
+ // requests, which `openPulls` counts on their own, null where GitHub didn't
163
+ // say.
164
+ export interface NpmGithubStats {
165
+ repo: string; stars: number; forks: number; openIssues: number; openPulls: number | null; archived: boolean; pushedAt: string | null
166
+ }
167
+
168
+ // How many pull requests a repository has open: the last page of their list,
169
+ // one a page, as its Link header names it, or the one page's length.
170
+ async function countOpenPulls(repo: string, token: string | null): Promise<number | null> {
171
+ const path = repo.split('/').map(encodeURIComponent).join('/')
172
+ let res: Response
173
+ try {
174
+ res = await fetch(`https://api.github.com/repos/${path}/pulls?state=open&per_page=1`, {
175
+ headers: { accept: 'application/vnd.github+json', 'user-agent': 'deepview-triage', ...token && { authorization: `Bearer ${token}` } },
176
+ redirect: 'error', signal: AbortSignal.timeout(API_TIMEOUT_MS),
177
+ })
178
+ } catch { return null }
179
+ if (!res.ok) { await res.body?.cancel(); return null }
180
+ const last = /[?&]page=(\d+)>;\s*rel="last"/u.exec(res.headers.get('link') ?? '')?.[1]
181
+ if (last !== undefined) { await res.body?.cancel(); return Number(last) }
182
+ try {
183
+ const json = JSON.parse((await readLimited(res, API_BYTES)).toString('utf8')) as unknown
184
+ return Array.isArray(json) ? json.length : null
185
+ } catch { return null }
186
+ }
187
+
188
+ // GitHub has no repository to show: none by that name, or a redirect upstream
189
+ // won't follow, anywhere but to the repository by its id, or a second.
190
+ const NONE = new Set([301, 302, 307, 308, 404])
191
+
192
+ // What GitHub answers for `repo`, or where it was renamed or transferred, for
193
+ // the repository it is now (its `full_name`), where it says it is public,
194
+ // with the token it was asked with: `token`, or none where that is revoked.
195
+ // Upstream follows GitHub's redirect for such a repository to it by its id
196
+ // (`followRedirect`), once, with the same token. Null where GitHub has no such
197
+ // repository to show, or it is not public; anything else fails, to be asked
198
+ // again next time. Public is `visibility: 'public'`, as github-app.ts
199
+ // requires: an internal repository answers `private: false`.
200
+ async function publicRepo(repo: string, token: string | null): Promise<{ json: Record<string, unknown> & { full_name: string }; auth: string | null } | null> {
201
+ const ask = (auth: string | null) => createClient({ token: auth, userAgent: 'deepview-triage' }).getRepo({ repo, followRedirect: true }) as Promise<unknown>
202
+ let auth = token, json: unknown
203
+ try { json = await ask(token) }
204
+ catch (error) {
205
+ if (!(error instanceof HttpError) || !(error.status === 401 || NONE.has(error.status))) throw error
206
+ if (error.status !== 401 || token === null) return null
207
+ auth = null
208
+ try { json = await ask(null) }
209
+ catch (retry) { if (retry instanceof HttpError && NONE.has(retry.status)) return null; throw retry }
210
+ }
211
+ if (!plainObject(json) || json['private'] !== false || json['visibility'] !== 'public' || typeof json['full_name'] !== 'string') return null
212
+ return { json: json as Record<string, unknown> & { full_name: string }, auth }
213
+ }
214
+
215
+ async function askGithub(repo: string, token: string | null): Promise<NpmGithubStats | null> {
216
+ const found = await publicRepo(repo, token)
217
+ if (found === null) return null
218
+ const { json, auth } = found
219
+ return {
220
+ repo: json['full_name'], stars: count(json['stargazers_count']), forks: count(json['forks_count']), openIssues: count(json['open_issues_count']),
221
+ openPulls: await countOpenPulls(json['full_name'], auth),
222
+ archived: json['archived'] === true, pushedAt: typeof json['pushed_at'] === 'string' ? json['pushed_at'] : null,
223
+ }
224
+ }
225
+
226
+ const repositories = kept<NpmGithubStats | null>(1000)
227
+
228
+ // `repo` as a package's manifest names it (owner/name); `githubToken` the
229
+ // reader's own, where they have one, for GitHub's rate limits, never for what
230
+ // it shows, asked for only where the figures aren't kept.
231
+ export function npmGithubStats(repo: string, githubToken: () => Promise<string | null>): Promise<NpmGithubStats | null> {
232
+ return repositories(repo.toLowerCase(), async () => askGithub(repo, await githubToken()))
233
+ }
234
+
235
+ const GITHUB_GRAPHQL = 'https://api.github.com/graphql'
236
+ // A ref's target is a commit, or for an annotated tag a tag object, which may
237
+ // itself name another tag before the commit.
238
+ const TAGS_QUERY = `query($owner: String!, $name: String!, $query: String!) {
239
+ repository(owner: $owner, name: $name) {
240
+ visibility
241
+ refs(refPrefix: "refs/tags/", query: $query, first: 100) {
242
+ nodes { name target { __typename oid ... on Tag { target { __typename oid ... on Tag { target { __typename oid } } } } } }
243
+ }
244
+ }
245
+ }`
246
+
247
+ function taggedCommit(target: unknown): unknown {
248
+ let at = target
249
+ for (let depth = 0; depth < 3 && plainObject(at) && at['__typename'] === 'Tag'; depth++) at = at['target']
250
+ return plainObject(at) && at['__typename'] === 'Commit' ? at['oid'] : null
251
+ }
252
+
253
+ async function askTags(repo: string, sha: string, version: string, token: string): Promise<string[]> {
254
+ const [owner, name] = repo.split('/')
255
+ const json = await askUpstreamJson(GITHUB_GRAPHQL, {
256
+ method: 'POST', limit: API_BYTES, absent: [],
257
+ headers: { authorization: `Bearer ${token}`, 'content-type': 'application/json', 'user-agent': 'deepview-triage' },
258
+ body: JSON.stringify({ query: TAGS_QUERY, variables: { owner, name, query: version } }),
259
+ })
260
+ const data = plainObject(json) ? json['data'] : null
261
+ const repository = plainObject(data) ? data['repository'] : null
262
+ // A repository gone, or not public (private, or internal to an enterprise),
263
+ // has none to show anyone.
264
+ if (!plainObject(repository) || repository['visibility'] !== 'PUBLIC') return []
265
+ const refs = repository['refs']
266
+ const nodes = plainObject(refs) && Array.isArray(refs['nodes']) ? refs['nodes'] as unknown[] : []
267
+ return nodes.filter((node): node is { name: string; target: unknown } => plainObject(node) && typeof node['name'] === 'string' && node['name'] !== '')
268
+ .filter(node => taggedCommit(node.target) === sha).map(node => node.name).toSorted()
269
+ }
270
+
271
+ // Null where no token asked: nothing to keep for a reader who has one.
272
+ const commitTags = kept<string[] | null>(500, tags => tags !== null)
273
+
274
+ // The tags of a public repository (owner/name) that point to `sha`, a
275
+ // version's publish commit, among those naming its `version` (`v1.2.3`,
276
+ // `pkg@1.2.3`, …), as GitHub's GraphQL API finds them by name. GraphQL needs
277
+ // a token: the reader's own (`githubToken`, asked for only where the tags
278
+ // aren't kept), where they have one; without, none are asked.
279
+ export async function npmCommitTags(repo: string, sha: string, version: string, githubToken: () => Promise<string | null>): Promise<string[]> {
280
+ return await commitTags(`${repo.toLowerCase()}\0${sha}\0${version}`, async () => {
281
+ const token = await githubToken()
282
+ return token === null ? null : askTags(repo, sha, version, token)
283
+ }) ?? []
284
+ }
285
+
286
+ // An advisory on the package, with the versions it covers as their indexes in
287
+ // the list it was asked with: npm's (`registry`), or one its repository
288
+ // publishes on GitHub before GitHub reviews it into npm's (`repository`); its
289
+ // text (markdown) where its source has one.
290
+ export interface NpmAdvisory {
291
+ id: string; source: Advisory['source']; ghsa?: string; url?: string; title?: string; severity?: string; cvss?: number; cwe: string[]; range?: string
292
+ details?: string; affected: number[]
293
+ }
294
+
295
+ // `versions` those `affected` indexes; `repository` false where the
296
+ // repository's advisories could not be had (GitHub refusing, its rate limit
297
+ // spent), leaving npm's alone; `keptAt`, where GitHub couldn't give them but
298
+ // their listing was kept before, however long ago, when it was.
299
+ export interface NpmAdvisoryList { versions: string[]; advisories: NpmAdvisory[]; repository: boolean; keptAt?: string }
300
+
301
+ export interface NpmAdvisoryOptions {
302
+ // The reader's GitHub token, and the repository the package names (owner/
303
+ // name, null where it names none), each asked for only where the list is
304
+ // not kept.
305
+ githubToken: () => Promise<string | null>
306
+ repo: () => Promise<string | null>
307
+ // Where repositories' listings are kept, as bundle advisories keep them
308
+ // (upstream-cache.ts auditCache), for as long as `signal` asks; and a
309
+ // repository's as last kept there, however old (lastListing).
310
+ cache: (signal: AbortSignal) => CacheStore | undefined
311
+ lastListing: (repo: string) => Promise<{ at: number; cache: CacheStore } | null>
312
+ debug?: boolean
313
+ }
314
+
315
+ async function askAdvisories(name: string, versions: string[], { githubToken, repo, cache, lastListing, debug = false }: NpmAdvisoryOptions): Promise<NpmAdvisoryList> {
316
+ // Every version upstream takes, as it checks each one it is asked about.
317
+ const asked = versions.filter(version => isExactVersion(version))
318
+ if (asked.length === 0) return { versions, advisories: [], repository: true }
319
+ // Its repository's own advisories are asked for only where GitHub says, now
320
+ // and not from an answer kept, that it is public, and that repository is the
321
+ // one asked, by the name GitHub gives it now where it was renamed or
322
+ // transferred: the list is kept for every reader of the package, and the
323
+ // reader's token could read a private repository's, or a listing of one
324
+ // kept for another reader.
325
+ let github: string | null = null, named: string | null = null, repository = true
326
+ try {
327
+ named = await repo()
328
+ github = named === null ? null : (await publicRepo(named, await githubToken()))?.json.full_name ?? null
329
+ } catch { repository = false }
330
+ // With the advisories `listed` publishes, where it isn't null, GitHub asked
331
+ // with the reader's token or by a client of the caller's.
332
+ const ask = (listed: string | null, store: (signal: AbortSignal) => CacheStore | undefined, client: { githubToken: string | null } | { github: Client }) => {
333
+ const signal = AbortSignal.timeout(ADVISORIES_TIMEOUT_MS)
334
+ const packages = [{ ecosystem: 'npm' as const, name, versions: asked, ...listed !== null && { github: listed } }]
335
+ return fetchBundleAdvisories(packages, signal, { debug, repoAdvisories: listed !== null, details: true, ...client, cache: store(signal) })
336
+ }
337
+ let result = repository ? await ask(github, cache, { githubToken: github === null ? null : await githubToken() }) : null
338
+ // Where GitHub can't say whether it is public, or refuses its listing, its
339
+ // listing as last kept is taken instead, however old (lastListing), as
340
+ // audits take a kept listing for any reader: only public repositories
341
+ // publish advisories (upstream-cache.ts). GitHub is asked nothing for it:
342
+ // upstream asks for a listing only once npm has answered, and where it
343
+ // won't take the kept one, which leaves npm's alone, as where none is kept.
344
+ // An audit failing otherwise is npm's, not asked a third time. Neither list
345
+ // is kept, so GitHub is asked again next time.
346
+ let keptAt: string | undefined
347
+ if (result === null || (result.status !== 200 && github !== null)) {
348
+ const unreached = github ?? named
349
+ const last = unreached === null ? null : await lastListing(unreached)
350
+ let untaken = false
351
+ const offline: Client = { ...createClient({ token: null, userAgent: 'deepview-triage' }),
352
+ listRepoAdvisories: () => { untaken = true; return Promise.reject(new Error('GitHub can\'t be reached')) } }
353
+ const listed = last && await ask(unreached, () => last.cache, { github: offline })
354
+ if (last && listed?.status === 200) {
355
+ result = listed
356
+ repository = true
357
+ keptAt = new Date(last.at).toISOString()
358
+ } else {
359
+ result = listed && !untaken ? listed : await ask(null, cache, { githubToken: null })
360
+ repository = false
361
+ }
362
+ }
363
+ if (result.status !== 200) throw new NpmPackageError(502, 'upstream-unavailable')
364
+ const index = new Map(versions.map((version, i) => [version, i]))
365
+ // npm's registry answers an advisory once a range it covers: here it is one
366
+ // row, its ranges joined as semver joins them, the versions and CWEs they
367
+ // cover together, and the highest score.
368
+ const merged = new Map<string, NpmAdvisory>()
369
+ for (const row of result.body) {
370
+ const affected = row.versions.map(version => index.get(version)).filter(at => at !== undefined)
371
+ const key = `${row.source}\0${row.id}`
372
+ const known = merged.get(key)
373
+ if (!known) {
374
+ merged.set(key, {
375
+ id: row.id, source: row.source, ...row.ghsa && { ghsa: row.ghsa }, ...row.url && { url: row.url }, ...row.title && { title: row.title },
376
+ ...row.severity && { severity: row.severity }, ...row.cvss !== undefined && { cvss: row.cvss }, cwe: row.cwe, ...row.range && { range: row.range },
377
+ ...row.details && { details: row.details }, affected,
378
+ })
379
+ continue
380
+ }
381
+ const range = [known.range, row.range].filter(Boolean).join(' || ')
382
+ const cvss = Math.max(known.cvss ?? -1, row.cvss ?? -1)
383
+ merged.set(key, { ...known, ...range && { range }, ...cvss >= 0 && { cvss }, cwe: [...new Set([...known.cwe, ...row.cwe])], affected: [...known.affected, ...affected] })
384
+ }
385
+ return {
386
+ versions, repository, ...keptAt && { keptAt },
387
+ advisories: [...merged.values()].map(row => ({ ...row, affected: [...new Set(row.affected)].toSorted((a, b) => a - b) })).filter(row => row.affected.length > 0)
388
+ .toSorted((a, b) => (SEVERITY_RANK[a.severity ?? ''] ?? 4) - (SEVERITY_RANK[b.severity ?? ''] ?? 4) || a.id.localeCompare(b.id)),
389
+ }
390
+ }
391
+
392
+ const ADVISORY_LISTS = 100
393
+ const advisoryLists = kept<NpmAdvisoryList>(ADVISORY_LISTS, list => list.repository && !list.keptAt)
394
+ // What each package's list was last asked by, for npmKnown.
395
+ const advisoryKeys = new Map<string, string>()
396
+
397
+ // The package's advisories, `versions` its published versions as the version
398
+ // list has them; asked again once a version is published, and a list without
399
+ // its repository's, next time.
400
+ export function npmAdvisories(name: string, versions: string[], options: NpmAdvisoryOptions): Promise<NpmAdvisoryList> {
401
+ const key = `${name}\0${versions.length}\0${versions[0] ?? ''}`
402
+ advisoryKeys.delete(name)
403
+ advisoryKeys.set(name, key)
404
+ while (advisoryKeys.size > ADVISORY_LISTS) advisoryKeys.delete(advisoryKeys.keys().next().value!)
405
+ return advisoryLists(key, () => askAdvisories(name, versions, options))
406
+ }
407
+
408
+ // What is kept about a version's package, each part as its own route answers
409
+ // it (http.ts handleNpm), for the version's response to carry: its figures,
410
+ // where those of the repository its latest version names are kept too; its
411
+ // advisories, where kept for a version list that has this version; the tags
412
+ // of its publish commit (`sha`, in `repo`, the repository it names);
413
+ // Socket's report on it; and npm's provenance for it (npm-provenance.ts).
414
+ // Nothing is asked for: what isn't kept is left out, for the viewer to ask
415
+ // for. A private package's name never leaves for Socket, so its report is
416
+ // none, nor is it asked for provenance.
417
+ export interface NpmKnown {
418
+ stats?: { name: string; downloads: NpmDownloads | null; github: NpmGithubStats | null }
419
+ advisories?: { name: string } & NpmAdvisoryList
420
+ tags?: { name: string; version: string; tags: string[] }
421
+ socket?: { name: string; version: string; socket: NpmSocketReport | null }
422
+ provenance?: { name: string; version: string; provenance: NpmProvenance | null }
423
+ }
424
+
425
+ export function npmKnown(name: string, version: string, isPrivate: boolean, repo: string | null, sha: string | null): NpmKnown {
426
+ const known: NpmKnown = {}
427
+ const days = downloads.peek(name), latest = latestRepos.peek(name)
428
+ const github = latest === null ? null : latest === undefined ? undefined : repositories.peek(latest.toLowerCase())
429
+ if (days !== undefined && github !== undefined) known.stats = { name, downloads: days, github }
430
+ const key = advisoryKeys.get(name)
431
+ const list = key === undefined ? undefined : advisoryLists.peek(key)
432
+ if (list?.versions.includes(version)) known.advisories = { name, ...list }
433
+ const tags = repo === null || sha === null ? [] : commitTags.peek(`${repo.toLowerCase()}\0${sha}\0${version}`)
434
+ if (tags) known.tags = { name, version, tags }
435
+ const socket = isPrivate ? null : socketReports.peek(`${name}@${version}`)
436
+ if (socket !== undefined) known.socket = { name, version, socket }
437
+ const provenance = isPrivate ? null : keptNpmProvenance(name, version)
438
+ if (provenance !== undefined) known.provenance = { name, version, provenance }
439
+ return known
440
+ }