@preventive/triage 1.0.0-alpha.89 → 1.0.0-alpha.90
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.
- package/out/activity.js +2 -2
- package/out/{chunk-U6JONPTN.js → chunk-3DOSBILK.js} +1 -1
- package/out/{chunk-A4HSJCXG.js → chunk-CJVMNJDZ.js} +2 -2
- package/out/chunk-HGWFRZNC.js +267 -0
- package/out/{chunk-3TJCEPHF.js → chunk-JZAROLQT.js} +1 -1
- package/out/{chunk-4GHLPL2P.js → chunk-LRWB6QVO.js} +1 -1
- package/out/{chunk-G5JKKNZF.js → chunk-SMNFBOLO.js} +1 -1
- package/out/{chunk-ZPIUN4FW.js → chunk-SZTCJVZJ.js} +1 -1
- package/out/{chunk-VRFGZ6MV.js → chunk-UTYWTUTC.js} +1 -1
- package/out/client-managed.js +28 -28
- package/out/compare.js +13 -13
- package/out/dialogs.js +15 -15
- package/out/graph.js +1 -1
- package/out/index.html +5 -5
- package/out/prism.js +1 -1
- package/out/scan.js +2 -2
- package/out/view.css +1 -1
- package/out/view.js +7 -7
- package/package.json +3 -1
- package/risk/index.d.ts +15 -0
- package/risk/index.js +1 -1
- package/risk/npm/assess.js +21 -3
- package/risk/npm/registry.js +16 -7
- package/server-managed/bundle-advisories.ts +97 -0
- package/server-managed/config.ts +1 -1
- package/server-managed/github-issue-links.ts +1 -1
- package/server-managed/github-metadata.ts +6 -1
- package/server-managed/github-pulls.ts +43 -10
- package/server-managed/http.ts +170 -52
- package/server-managed/known-listings.ts +112 -0
- package/server-managed/npm-packages.ts +10 -2
- package/server-managed/npm-risk.ts +31 -8
- package/server-managed/public-workspace.ts +6 -7
- package/server-managed/pull-dependency-reviews.ts +64 -13
- package/server-managed/queue.ts +1 -1
- package/server-managed/repository-dependency-reviews.ts +38 -0
- package/server-managed/repository-risk-audit.ts +83 -16
- package/server-managed/repository-risk.ts +33 -12
- package/server-managed/team-app.ts +1 -1
- package/server-managed/team-progress.ts +77 -0
- package/server-managed/upstream-cache.ts +42 -23
- package/out/chunk-7KUZQB6S.js +0 -267
|
@@ -25,7 +25,11 @@
|
|
|
25
25
|
// registry or a mirror are asked of npm's advisories all at once, as `npm
|
|
26
26
|
// audit` asks, each advisory told with whether it is of malware (upstream's
|
|
27
27
|
// `malware`), which alone is a supply chain's risk; the rest are
|
|
28
|
-
// vulnerabilities, told beside
|
|
28
|
+
// vulnerabilities, told beside; with those its packages' repositories publish
|
|
29
|
+
// as known, none waited on, and where those weren't all known fresh, told
|
|
30
|
+
// again as soon as GitHub answers, meanwhile, where they changed, and once
|
|
31
|
+
// more once the rest is done where its packages' repositories weren't all
|
|
32
|
+
// known then (repository-risk-audit.ts). A repository's Dependabot alerts of npm's, open or dismissed,
|
|
29
33
|
// are told once its lockfiles' advisories are, each with the versions its
|
|
30
34
|
// lockfile locks that it covers, for the page to blend them into npm's; one
|
|
31
35
|
// whose alerts couldn't be had tells why, and the scan goes on. Its GitHub
|
|
@@ -48,7 +52,7 @@ import type { LockedPackage } from './locked-packages.ts'
|
|
|
48
52
|
import { type Queue, inTurns, queue } from './queue.ts'
|
|
49
53
|
import type { DownloadsSource } from './scan-downloads.ts'
|
|
50
54
|
import { type AssessedPackage, type AssessingSource, RISK_KEPT_MS, type RiskFailure, type ToldFinding, assessPackage, failureOf } from './repository-risk-assess.ts'
|
|
51
|
-
import { type AdvisoryRow, type Audit, type AuditSource, auditLockfiles } from './repository-risk-audit.ts'
|
|
55
|
+
import { type AdvisoryRow, type Audit, type AuditSource, type PendingAudit, type ToldAudit, auditAgain, auditLockfiles, pend, resumedAudit } from './repository-risk-audit.ts'
|
|
52
56
|
import { type DependabotAlertRow, type ListedLockfile, type LockfileRead, type OpenedRepository, type RepositoryArchived, type RepositoryFailure, type RepositoryRead, SCAN_READ_KEPT_MS,
|
|
53
57
|
type StasisConfigsRead, dependabotLine, readRepository, rechecked, stasisBuilding, stasisVersions } from './repository-risk-read.ts'
|
|
54
58
|
import { type KeptRepositories, tellKept } from './repository-risk-kept.ts'
|
|
@@ -129,11 +133,11 @@ export type RepositoryRiskLine =
|
|
|
129
133
|
// by its id, its name and a team's directories in it then, and its
|
|
130
134
|
// lockfiles' keys (`${format}\0${sha}`) of those read, the references its
|
|
131
135
|
// Actions make, to resolve, the versions its Stasis builds made install
|
|
132
|
-
// (versionKey), assessed before the rest,
|
|
133
|
-
// to
|
|
136
|
+
// (versionKey), assessed before the rest, its builds still to be made, to
|
|
137
|
+
// watch, and its lockfiles' advisories still to be had again (PendingAudit).
|
|
134
138
|
export interface ScanProgress { repos: ToldRepository[] }
|
|
135
139
|
interface ToldRepository { id: number; name: string; paths: readonly string[] | null; lockfiles: string[]; actions?: ActionRef[]; stasis?: string[]
|
|
136
|
-
building?: { commit: string; configs: string[] } }
|
|
140
|
+
building?: { commit: string; configs: string[] }; again?: PendingAudit[] }
|
|
137
141
|
|
|
138
142
|
export type RiskLine = Extract<RepositoryRiskLine, { type: 'risk' }>
|
|
139
143
|
|
|
@@ -143,6 +147,8 @@ export type RiskLine = Extract<RepositoryRiskLine, { type: 'risk' }>
|
|
|
143
147
|
const READ_AHEAD = 6
|
|
144
148
|
// How many lockfiles' advisories are asked of npm at once, those of the
|
|
145
149
|
// repositories read ahead as they are read, each told in its turn.
|
|
150
|
+
// As many are had again at once, as GitHub answers for their packages'
|
|
151
|
+
// repositories (auditAgain), apart from those.
|
|
146
152
|
const AUDITS_AT_ONCE = 4
|
|
147
153
|
// How long a part's progress, written as it ends (`progress`), is waited on.
|
|
148
154
|
const PROGRESS_WRITE_MS = 5000
|
|
@@ -171,6 +177,10 @@ interface Scan {
|
|
|
171
177
|
told: Map<number, ToldRepository>
|
|
172
178
|
actions: ReturnType<typeof resolvingActions> | null
|
|
173
179
|
audits: ReturnType<typeof inTurns>
|
|
180
|
+
// The lockfiles told with their repositories' advisories not all known
|
|
181
|
+
// fresh, had again meanwhile, AUDITS_AT_ONCE (`retells`), each with what to
|
|
182
|
+
// have once the rest is done where it may change once more.
|
|
183
|
+
retells: ReturnType<typeof inTurns>; again: Promise<(() => Promise<unknown>) | null>[]
|
|
174
184
|
// Whether what is kept is told first; its writes under way, waited for as it or its part ends.
|
|
175
185
|
keptFirst: boolean
|
|
176
186
|
keeping: Promise<unknown>[]
|
|
@@ -283,11 +293,17 @@ function madeSince(scan: Scan, build: StasisBuild, versions: string[]) {
|
|
|
283
293
|
export type LockfileLine = Extract<RepositoryRiskLine, { type: 'lockfile' }>
|
|
284
294
|
|
|
285
295
|
// A lockfile's advisories line, of its audit (repository-risk-audit.ts auditLockfile).
|
|
286
|
-
const advisoriesLine = ({ repo, path }: LockfileLine, audit: Audit) => ({ type: 'advisories', repo, path, ...Array.isArray(audit) ? { advisories: audit } : audit } as const)
|
|
296
|
+
const advisoriesLine = ({ repo, path }: Pick<LockfileLine, 'repo' | 'path'>, audit: Audit) => ({ type: 'advisories', repo, path, ...Array.isArray(audit) ? { advisories: audit } : audit } as const)
|
|
297
|
+
|
|
298
|
+
// A lockfile's audit `told` had again, told where it changed, as `entry` of
|
|
299
|
+
// its repository's `pending` notes it (auditAgain); then what to have once
|
|
300
|
+
// the rest is done, where it may change once more.
|
|
301
|
+
const retell = (scan: Scan, repo: number, pending: PendingAudit[], entry: PendingAudit, told: ToldAudit): Promise<(() => Promise<unknown>) | null> => scan.retells(() => auditAgain(told,
|
|
302
|
+
pending, entry, scan.signal, audit => { scan.lines.add(advisoriesLine({ repo, path: entry.path }, audit)) })).then(again => again && (() => retell(scan, repo, pending, entry, again)), () => null)
|
|
287
303
|
|
|
288
304
|
// A repository read, its lockfiles' audits asked meanwhile, AUDITS_AT_ONCE
|
|
289
305
|
// across the scan (auditLockfiles), to tell in turn once access is checked again.
|
|
290
|
-
type Audited = (RepositoryRead & { audits: Promise<
|
|
306
|
+
type Audited = (RepositoryRead & { audits: Promise<ToldAudit | null>[] }) | RepositoryFailure | RepositoryArchived
|
|
291
307
|
const audited = (scan: Scan, read: RepositoryRead | RepositoryFailure | RepositoryArchived | null): Audited | null => (read === null || 'type' in read ? read : { ...read, audits: auditLockfiles(scan.source, scan.caches.advisories,
|
|
292
308
|
scan.signal, read.lockfiles.map(({ sha, line }) => ({ key: `${line.format}\0${sha}`, packages: 'packages' in line ? line.packages : null })), scan.audits) })
|
|
293
309
|
|
|
@@ -313,7 +329,7 @@ async function tellRepository(scan: Scan, repo: RepositoryRiskRepo, read: Audite
|
|
|
313
329
|
const tell = (line: RepositoryRiskLine) => { told.push(line); scan.lines.add(line) }
|
|
314
330
|
const { commit, lockfiles } = read
|
|
315
331
|
tell({ type: 'repo', id: repo.repoId, commit, lockfiles: lockfiles.map(({ line: { path, format } }) => ({ path, format })) })
|
|
316
|
-
const building = stasisBuilding(read.stasis), reached = stasisVersions(read.stasis)
|
|
332
|
+
const building = stasisBuilding(read.stasis), pending: PendingAudit[] = [], reached = stasisVersions(read.stasis)
|
|
317
333
|
reach(scan, reached)
|
|
318
334
|
scan.reach.building(building.map(config => ({ repoId: repo.repoId, commit, config })))
|
|
319
335
|
for (const { line } of lockfiles) {
|
|
@@ -322,10 +338,11 @@ async function tellRepository(scan: Scan, repo: RepositoryRiskRepo, read: Audite
|
|
|
322
338
|
}
|
|
323
339
|
if (read.stasis) tell({ type: 'stasis', repo: repo.repoId, ...read.stasis })
|
|
324
340
|
const refs = read.actions ? tellActions(scan, repo, read.actions, lockfiles, tell) : []
|
|
325
|
-
for (const [at, { line }] of lockfiles.entries()) {
|
|
341
|
+
for (const [at, { sha, line }] of lockfiles.entries()) {
|
|
326
342
|
if (scan.signal.aborted) return
|
|
327
343
|
const audit = await read.audits[at]
|
|
328
|
-
if (audit) tell(advisoriesLine(line, audit))
|
|
344
|
+
if (audit) tell(advisoriesLine(line, audit.audit))
|
|
345
|
+
if (audit?.again) scan.again.push(retell(scan, repo.repoId, pending, pend(pending, line.path, `${line.format}\0${sha}`, audit.audit), audit))
|
|
329
346
|
}
|
|
330
347
|
if (scan.signal.aborted) return
|
|
331
348
|
const dependabot = read.dependabot && await rechecked(read.dependabot)
|
|
@@ -333,7 +350,7 @@ async function tellRepository(scan: Scan, repo: RepositoryRiskRepo, read: Audite
|
|
|
333
350
|
if (dependabot) scan.lines.add(dependabotLine(repo.repoId, dependabot, lockfiles))
|
|
334
351
|
scan.told.set(repo.repoId, { id: repo.repoId, name: repo.fullName, paths: repo.paths ?? null,
|
|
335
352
|
lockfiles: lockfiles.flatMap(({ sha, line }) => 'packages' in line ? [`${line.format}\0${sha}`] : []), ...refs.length > 0 ? { actions: refs } : {}, ...reached.length > 0 ? { stasis: reached } : {},
|
|
336
|
-
...building.length > 0 ? { building: { commit, configs: building } } : {} })
|
|
353
|
+
...building.length > 0 ? { building: { commit, configs: building } } : {}, ...pending.length > 0 ? { again: pending } : {} })
|
|
337
354
|
keep(scan.source.kept?.write(repo, { name: repo.fullName, lines: told, refs }, Date.now()))
|
|
338
355
|
}
|
|
339
356
|
|
|
@@ -374,6 +391,7 @@ async function toldBefore(scan: Scan, repo: RepositoryRiskRepo) {
|
|
|
374
391
|
const { building } = told
|
|
375
392
|
reseed(scan, { stasis: told.stasis ?? [], building: building?.configs.map(config => ({ repoId: told.id, commit: building.commit, config })) ?? [], packages: reads,
|
|
376
393
|
refs: told.actions ?? [] })
|
|
394
|
+
for (const entry of [...told.again ?? []]) scan.again.push(retell(scan, told.id, told.again!, entry, resumedAudit(scan.source, scan.caches.advisories, entry, reads[told.lockfiles.indexOf(entry.key)] ?? [])))
|
|
377
395
|
return true
|
|
378
396
|
}
|
|
379
397
|
|
|
@@ -443,6 +461,9 @@ async function runScan(scan: Scan, fail: (error: unknown) => void, everyMs: numb
|
|
|
443
461
|
for (const pkg of left) from.delete(seenKey(pkg))
|
|
444
462
|
if (!scan.signal.aborted && left.length > 0) await assessing(scan, assess => { assess(left); return Promise.resolve() }, stale)
|
|
445
463
|
}
|
|
464
|
+
// then the advisories of lockfiles had again meanwhile that may change
|
|
465
|
+
// once more, as their packages' repositories are known now.
|
|
466
|
+
await Promise.all((await Promise.all(scan.again.splice(0))).map(again => again?.()))
|
|
446
467
|
await scan.actions?.close()
|
|
447
468
|
await Promise.all(scan.keeping)
|
|
448
469
|
if (!scan.signal.aborted) scan.lines.add({ type: 'done' })
|
|
@@ -478,7 +499,7 @@ export async function* repositoryRiskLines<R extends RepositoryRiskRepo>(source:
|
|
|
478
499
|
const actions = source.actions ? resolvingActions({ source: source.actions, signal: running, tell: line => { lines.add(line) }, memory: caches.actions,
|
|
479
500
|
answers: caches.actionAnswers, store: source.actionLines }) : null
|
|
480
501
|
const scan: Scan = { source, caches, signal: running, lines, lookups: queue(running), seen: new Map(), dev: new Map(), stale: new Map(), reach: stasisReach(),
|
|
481
|
-
turn: null, told: new Map(), actions, audits: inTurns(AUDITS_AT_ONCE), keptFirst: kept, keeping: [] }
|
|
502
|
+
turn: null, told: new Map(), actions, audits: inTurns(AUDITS_AT_ONCE), retells: inTurns(AUDITS_AT_ONCE), again: [], keptFirst: kept, keeping: [] }
|
|
482
503
|
// A failure of the scan itself kept, to throw once the lines before it are
|
|
483
504
|
// told, and the scan stopped.
|
|
484
505
|
const failed: unknown[] = []
|
|
@@ -33,7 +33,7 @@ const NO_APP: TeamWorkspaceSummary = { app: { appMode: false }, empty: [] }
|
|
|
33
33
|
|
|
34
34
|
const CACHE_MAX_ENTRIES = 4096
|
|
35
35
|
// Each workspace build already reads four reports at a time.
|
|
36
|
-
const CLASSIFY_CONCURRENCY = 2
|
|
36
|
+
export const CLASSIFY_CONCURRENCY = 2
|
|
37
37
|
const caches = new WeakMap<ManagedDb, Map<string, TeamWorkspaceSummary>>()
|
|
38
38
|
const pendingJobs = new WeakMap<ManagedDb, Map<string, Promise<TeamWorkspaceSummary | null>>>()
|
|
39
39
|
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
// What the landing counts of each of a reader's teams, and of all of them
|
|
2
|
+
// together: the findings triaged In progress and Fixed, and the GitHub issues
|
|
3
|
+
// (open, closed) and pull requests (open, merged) linked to its findings, as
|
|
4
|
+
// GET /api/teams/<id>/fixes reads them (github-pulls.ts workspaceFixUrls), by
|
|
5
|
+
// their status as last read of GitHub (cachedFixStatuses).
|
|
6
|
+
// GitHub is never asked: an item not read yet counts in neither, as does a
|
|
7
|
+
// pull request closed unmerged. A finding or item several teams share counts
|
|
8
|
+
// once in the total.
|
|
9
|
+
import type { BlobStore } from './blob-store.ts'
|
|
10
|
+
import type { ManagedDb } from './db.ts'
|
|
11
|
+
import { type CachedFixStatus, cachedFixStatuses, workspaceFixUrls } from './github-pulls.ts'
|
|
12
|
+
import { visibleManagedIssues } from './managed-issues.ts'
|
|
13
|
+
import { eachOf } from './queue.ts'
|
|
14
|
+
import { CLASSIFY_CONCURRENCY } from './team-app.ts'
|
|
15
|
+
import { TeamReportsError, recheckTeam, teamSnapshot, teamWorkspaceFindingIds } from './team-reports.ts'
|
|
16
|
+
|
|
17
|
+
export interface TeamProgress {
|
|
18
|
+
inprogress: number
|
|
19
|
+
fixed: number
|
|
20
|
+
issues: { open: number; closed: number }
|
|
21
|
+
pulls: { open: number; merged: number }
|
|
22
|
+
}
|
|
23
|
+
// A team's In progress and Fixed findings, by their IDs, and its linked items'
|
|
24
|
+
// statuses, by their cache keys: what its progress counts, and the total
|
|
25
|
+
// counts each once.
|
|
26
|
+
interface Tally {
|
|
27
|
+
findings: Map<string, 'inprogress' | 'fixed'>
|
|
28
|
+
items: Map<string, CachedFixStatus>
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
// A team's, as its reader's workspace of it shows it (teamWorkspaceFindingIds);
|
|
32
|
+
// null where it shows none now: too large or unreadable, or changed while it
|
|
33
|
+
// was read. A session ended while it is read ends the request.
|
|
34
|
+
async function tallyTeam(db: ManagedDb, store: BlobStore, sessionId: string, teamId: string): Promise<Tally | null> {
|
|
35
|
+
try {
|
|
36
|
+
const snapshot = await teamSnapshot(db, sessionId, teamId)
|
|
37
|
+
const ids = [...await teamWorkspaceFindingIds(db, store, snapshot)]
|
|
38
|
+
const [rows, issues] = await Promise.all([db.listTriage(ids), db.listManagedIssues(ids)])
|
|
39
|
+
const findings: Tally['findings'] = new Map()
|
|
40
|
+
for (const row of rows) if (row.triage === 'inprogress' || row.triage === 'fixed') findings.set(row.findingId, row.triage)
|
|
41
|
+
const items = await cachedFixStatuses(db, snapshot, workspaceFixUrls(rows.map(row => row.fix), visibleManagedIssues(issues, snapshot)))
|
|
42
|
+
await recheckTeam(db, sessionId, snapshot)
|
|
43
|
+
return { findings, items }
|
|
44
|
+
} catch (error) {
|
|
45
|
+
if (error instanceof TeamReportsError && error.status !== 401) return null
|
|
46
|
+
throw error
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
function count({ findings, items }: Tally): TeamProgress {
|
|
51
|
+
const progress: TeamProgress = { inprogress: 0, fixed: 0, issues: { open: 0, closed: 0 }, pulls: { open: 0, merged: 0 } }
|
|
52
|
+
for (const triage of findings.values()) progress[triage]++
|
|
53
|
+
for (const { kind, status } of items.values()) {
|
|
54
|
+
if (kind === 'issue') {
|
|
55
|
+
if (status === 'open') progress.issues.open++
|
|
56
|
+
else if (status === 'closed') progress.issues.closed++
|
|
57
|
+
} else if (status === 'open' || status === 'draft') progress.pulls.open++
|
|
58
|
+
else if (status === 'merged') progress.pulls.merged++
|
|
59
|
+
}
|
|
60
|
+
return progress
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
// Those of `teamIds` (a reader's catalog), by team, a team counted none of
|
|
64
|
+
// left out, and their total.
|
|
65
|
+
export async function teamProgress(db: ManagedDb, store: BlobStore, sessionId: string, teamIds: readonly string[]): Promise<{ teams: Record<string, TeamProgress>; total: TeamProgress }> {
|
|
66
|
+
// Each team's workspace a cold instance builds as its catalog does.
|
|
67
|
+
const tallies = await eachOf(teamIds, CLASSIFY_CONCURRENCY, teamId => tallyTeam(db, store, sessionId, teamId))
|
|
68
|
+
const teams: Record<string, TeamProgress> = {}
|
|
69
|
+
const all: Tally = { findings: new Map(), items: new Map() }
|
|
70
|
+
tallies.forEach((tally, index) => {
|
|
71
|
+
if (!tally) return
|
|
72
|
+
teams[teamIds[index]!] = count(tally)
|
|
73
|
+
for (const [id, triage] of tally.findings) all.findings.set(id, triage)
|
|
74
|
+
for (const [key, item] of tally.items) all.items.set(key, item)
|
|
75
|
+
})
|
|
76
|
+
return { teams, total: count(all) }
|
|
77
|
+
}
|
|
@@ -89,17 +89,23 @@ export function upstreamCacheMethods(db: ManagedSql): UpstreamCacheStore {
|
|
|
89
89
|
}
|
|
90
90
|
}
|
|
91
91
|
|
|
92
|
-
// An audit's `cache`:
|
|
93
|
-
//
|
|
94
|
-
//
|
|
95
|
-
|
|
96
|
-
|
|
92
|
+
// An audit's `cache`: this store keeps listings and public names
|
|
93
|
+
// (upstreamCache), those of `keys` (auditedKeys) read at once, shared by every
|
|
94
|
+
// instance and with every other place that asks for listings
|
|
95
|
+
// (known-listings.ts); where the server has an upstream disk cache (off
|
|
96
|
+
// Vercel, set at startup), that keeps the rest (diskCache), else nothing does.
|
|
97
|
+
export function auditCache(cacheDir: string | null | undefined, db: UpstreamCacheStore, signal: AbortSignal, debug = false, keys: Iterable<string> = []): CacheStore {
|
|
98
|
+
const kept = upstreamCache(db, signal, debug, keys)
|
|
99
|
+
if (!cacheDir) return kept
|
|
100
|
+
const disk = diskCache(cacheDir)
|
|
101
|
+
return { read: (type, key) => (CACHED_TYPES.has(type) ? kept : disk).read(type, key),
|
|
102
|
+
write: (type, key, value) => (CACHED_TYPES.has(type) ? kept : disk).write(type, key, value) }
|
|
97
103
|
}
|
|
98
104
|
|
|
99
105
|
// Only listings and public names are kept: upstream's other records (npm
|
|
100
106
|
// version documents, registries' repository lookups) read as misses and are
|
|
101
107
|
// not written.
|
|
102
|
-
const LISTINGS = 'github/advisories'
|
|
108
|
+
export const LISTINGS = 'github/advisories'
|
|
103
109
|
const PUBLIC_NAMES = 'npm/public'
|
|
104
110
|
const PUBLIC_REPOS = 'github/public'
|
|
105
111
|
const CACHED_TYPES = new Set([LISTINGS, PUBLIC_NAMES, PUBLIC_REPOS])
|
|
@@ -222,27 +228,40 @@ export async function keepJson(path: string, etag: string, body: Buffer) {
|
|
|
222
228
|
await keepFile(path, await gzipAsync(Buffer.concat([Buffer.from(`{"etag":${JSON.stringify(etag)},"json":`), body, Buffer.from('}')])))
|
|
223
229
|
}
|
|
224
230
|
|
|
225
|
-
//
|
|
226
|
-
//
|
|
227
|
-
|
|
231
|
+
// Upstream's disk cache at `root` (setCacheDir) as a store of what audits
|
|
232
|
+
// keep there, all JSON, each in the file upstream's own reads and writes use:
|
|
233
|
+
// `key.json`, gzipped as `key.json.gz` in the directories upstream gzips, and
|
|
234
|
+
// read to no more than upstream reads (its MAX_BYTES). Bytes, which audits
|
|
235
|
+
// don't keep, aren't kept.
|
|
236
|
+
const GZIPPED = new Set([LISTINGS, 'npm/versions', 'rubysec/index', 'rubysec/advisories'])
|
|
237
|
+
const KEPT_BYTES = 512 * 1024 * 1024
|
|
238
|
+
const utf8 = new TextDecoder('utf-8', { fatal: true })
|
|
239
|
+
function diskCache(root: string): CacheStore {
|
|
240
|
+
const pathOf = (type: string, key: string) => upstreamCachePath(root, type, GZIPPED.has(type) ? `${key}.json.gz` : `${key}.json`)
|
|
241
|
+
return {
|
|
242
|
+
async read(type, key) {
|
|
243
|
+
const bytes = await readKeptFile(pathOf(type, key), KEPT_BYTES)
|
|
244
|
+
try { return bytes && JSON.parse(utf8.decode(GZIPPED.has(type) ? await gunzipAsync(bytes, { maxOutputLength: KEPT_BYTES }) : bytes)) as unknown } catch { return null }
|
|
245
|
+
},
|
|
246
|
+
async write(type, key, value) {
|
|
247
|
+
if (value instanceof Uint8Array) return
|
|
248
|
+
const json = Buffer.from(JSON.stringify(value))
|
|
249
|
+
await keepFile(pathOf(type, key), GZIPPED.has(type) ? await gzipAsync(json) : json)
|
|
250
|
+
},
|
|
251
|
+
}
|
|
252
|
+
}
|
|
228
253
|
|
|
229
|
-
// A repository's listing as last kept
|
|
230
|
-
//
|
|
231
|
-
//
|
|
232
|
-
//
|
|
233
|
-
//
|
|
234
|
-
|
|
235
|
-
export async function lastListing(cacheDir: string | null | undefined, db: UpstreamCacheStore, repo: string, debug = false): Promise<{ at: number; cache: CacheStore } | null> {
|
|
254
|
+
// A repository's listing as last kept (upstreamCache), however old, for when
|
|
255
|
+
// GitHub can't be reached to refresh it: `at`, when it was kept, and `cache`,
|
|
256
|
+
// a store answering it to upstream as kept just now, so that upstream takes
|
|
257
|
+
// it rather than ask GitHub, and keeping nothing. Upstream checks it as it
|
|
258
|
+
// checks its own. Null where none is kept, or it can't be read.
|
|
259
|
+
export async function lastListing(db: UpstreamCacheStore, repo: string, debug = false): Promise<{ at: number; cache: CacheStore } | null> {
|
|
236
260
|
const key = repo.toLowerCase()
|
|
237
261
|
let kept: { at?: unknown } | null
|
|
238
262
|
try {
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
kept = bytes && JSON.parse((await gunzipAsync(bytes, { maxOutputLength: LISTING_BYTES })).toString('utf8'))
|
|
242
|
-
} else {
|
|
243
|
-
const value = await db.getUpstreamCacheEntry(`${LISTINGS}/${key}`)
|
|
244
|
-
kept = value === null ? null : JSON.parse(value)
|
|
245
|
-
}
|
|
263
|
+
const value = await db.getUpstreamCacheEntry(`${LISTINGS}/${key}`)
|
|
264
|
+
kept = value === null ? null : JSON.parse(value)
|
|
246
265
|
} catch (error) {
|
|
247
266
|
if (debug) console.warn('managed: kept listing read failed:', error)
|
|
248
267
|
return null
|