Skip to content

Commit 13bc945

Browse files
committed
Move uxLookup to utils/alert-rules
1 parent d189bb0 commit 13bc945

2 files changed

Lines changed: 174 additions & 180 deletions

File tree

src/shadow/arborist/lib/arborist/reify.ts

Lines changed: 7 additions & 146 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,9 @@
1-
import { readFileSync } from 'node:fs'
21
import path from 'node:path'
3-
import { setTimeout as wait } from 'node:timers/promises'
42

53
import semver from 'semver'
64

7-
import config from '@socketsecurity/config'
85
import { getManifestData } from '@socketsecurity/registry'
9-
import { hasOwn, isObject } from '@socketsecurity/registry/lib/objects'
6+
import { hasOwn } from '@socketsecurity/registry/lib/objects'
107
import {
118
fetchPackagePackument,
129
resolvePackageName
@@ -17,25 +14,16 @@ import { Spinner } from '@socketsecurity/registry/lib/spinner'
1714
import { batchScan, isAlertFixable, isAlertFixableCve, walk } from './alerts'
1815
import { kCtorArgs, kRiskyReify } from './index'
1916
import constants from '../../../../constants'
20-
import { createAlertUXLookup } from '../../../../utils/alert-rules'
17+
import { uxLookup } from '../../../../utils/alert-rules'
2118
import { ColorOrMarkdown } from '../../../../utils/color-or-markdown'
22-
import { isErrnoException } from '../../../../utils/misc'
23-
import { getPublicToken, setupSdk } from '../../../../utils/sdk'
24-
import { getSetting } from '../../../../utils/settings'
25-
import { npmNmPath } from '../../../npm-paths'
19+
import { pacotePath } from '../../../npm-paths'
2620
import { Edge, SafeEdge } from '../edge'
2721

2822
import type { InstallEffect, SocketArtifact } from './alerts'
2923
import type { ArboristClass, AuditAdvisory, SafeArborist } from './index'
3024
import type { SafeNode } from '../node'
3125
import type { Writable } from 'node:stream'
3226

33-
type AlertUxLookup = ReturnType<typeof createAlertUXLookup>
34-
35-
type AlertUxLookupSettings = Parameters<AlertUxLookup>[0]
36-
37-
type AlertUxLookupResult = ReturnType<AlertUxLookup>
38-
3927
type SocketPackageAlert = {
4028
key: string
4129
type: string
@@ -46,7 +34,7 @@ type SocketPackageAlert = {
4634
raw?: any
4735
}
4836

49-
const pacote: typeof import('pacote') = require(path.join(npmNmPath, 'pacote'))
37+
const pacote: typeof import('pacote') = require(pacotePath)
5038

5139
const {
5240
ENV,
@@ -83,15 +71,12 @@ function findBestPatchVersion(
8371
return semver.maxSatisfying(eligibleVersions, '*')
8472
}
8573

86-
function findPackageRecursively(
87-
tree: SafeNode,
88-
packageName: string
89-
): SafeNode | null {
74+
function findPackage(tree: SafeNode, packageName: string): SafeNode | null {
9075
const queue: { node: typeof tree }[] = [{ node: tree }]
9176
let sentinel = 0
9277
while (queue.length) {
9378
if (sentinel++ === LOOP_SENTINEL) {
94-
throw new Error('Detected infinite loop in findPackageRecursively')
79+
throw new Error('Detected infinite loop in findPackage')
9580
}
9681
const { node: currentNode } = queue.pop()!
9782
const node = currentNode.children.get(packageName)
@@ -107,32 +92,6 @@ function findPackageRecursively(
10792
return null
10893
}
10994

110-
function findSocketYmlSync() {
111-
let prevDir = null
112-
let dir = process.cwd()
113-
while (dir !== prevDir) {
114-
let ymlPath = path.join(dir, 'socket.yml')
115-
let yml = maybeReadfileSync(ymlPath)
116-
if (yml === undefined) {
117-
ymlPath = path.join(dir, 'socket.yaml')
118-
yml = maybeReadfileSync(ymlPath)
119-
}
120-
if (typeof yml === 'string') {
121-
try {
122-
return {
123-
path: ymlPath,
124-
parsed: config.parseSocketConfig(yml)
125-
}
126-
} catch {
127-
throw new Error(`Found file but was unable to parse ${ymlPath}`)
128-
}
129-
}
130-
prevDir = dir
131-
dir = path.join(dir, '..')
132-
}
133-
return null
134-
}
135-
13695
type GetPackageAlertsOptions = {
13796
output?: Writable
13897
fixable?: boolean
@@ -279,13 +238,6 @@ function getTranslations() {
279238
return _translations!
280239
}
281240

282-
function maybeReadfileSync(filepath: string): string | undefined {
283-
try {
284-
return readFileSync(filepath, 'utf8')
285-
} catch {}
286-
return undefined
287-
}
288-
289241
function packageAlertsToReport(alerts: SocketPackageAlert[]) {
290242
let report: { [dependency: string]: AuditAdvisory[] } | null = null
291243
for (const alert of alerts) {
@@ -328,7 +280,7 @@ async function updateAdvisoryDependencies(
328280

329281
for (const name of Object.keys(report)) {
330282
const advisories = report[name]!
331-
const node = findPackageRecursively(tree, name)
283+
const node = findPackage(tree, name)
332284
if (!node) {
333285
// Package not found in the tree.
334286
continue
@@ -403,17 +355,6 @@ async function updateAdvisoryDependencies(
403355
}
404356
}
405357

406-
let _uxLookup: AlertUxLookup | undefined
407-
async function uxLookup(
408-
settings: AlertUxLookupSettings
409-
): Promise<AlertUxLookupResult> {
410-
while (_uxLookup === undefined) {
411-
// eslint-disable-next-line no-await-in-loop
412-
await wait(1, { signal: abortSignal })
413-
}
414-
return _uxLookup(settings)
415-
}
416-
417358
export async function reify(
418359
this: SafeArborist,
419360
...args: Parameters<InstanceType<ArboristClass>['reify']>
@@ -493,83 +434,3 @@ export async function reify(
493434
throw new Error('Socket npm exiting due to risks')
494435
}
495436
}
496-
497-
void (async () => {
498-
const { orgs, settings } = await (async () => {
499-
try {
500-
const socketSdk = await setupSdk(getPublicToken())
501-
const orgResult = await socketSdk.getOrganizations()
502-
if (!orgResult.success) {
503-
throw new Error(
504-
`Failed to fetch Socket organization info: ${orgResult.error.message}`
505-
)
506-
}
507-
const orgs: Exclude<
508-
(typeof orgResult.data.organizations)[string],
509-
undefined
510-
>[] = []
511-
for (const org of Object.values(orgResult.data.organizations)) {
512-
if (org) {
513-
orgs.push(org)
514-
}
515-
}
516-
const result = await socketSdk.postSettings(
517-
orgs.map(org => ({ organization: org.id }))
518-
)
519-
if (!result.success) {
520-
throw new Error(
521-
`Failed to fetch API key settings: ${result.error.message}`
522-
)
523-
}
524-
return {
525-
orgs,
526-
settings: result.data
527-
}
528-
} catch (e: any) {
529-
const cause = isObject(e) && 'cause' in e ? e.cause : undefined
530-
if (
531-
isErrnoException(cause) &&
532-
(cause.code === 'ENOTFOUND' || cause.code === 'ECONNREFUSED')
533-
) {
534-
throw new Error(
535-
'Unable to connect to socket.dev, ensure internet connectivity before retrying',
536-
{
537-
cause: e
538-
}
539-
)
540-
}
541-
throw e
542-
}
543-
})()
544-
545-
// Remove any organizations not being enforced.
546-
const enforcedOrgs = getSetting('enforcedOrgs') ?? []
547-
for (const { 0: i, 1: org } of orgs.entries()) {
548-
if (!enforcedOrgs.includes(org.id)) {
549-
settings.entries.splice(i, 1)
550-
}
551-
}
552-
553-
const socketYml = findSocketYmlSync()
554-
if (socketYml) {
555-
settings.entries.push({
556-
start: socketYml.path,
557-
settings: {
558-
[socketYml.path]: {
559-
deferTo: null,
560-
// TODO: TypeScript complains about the type not matching. We should
561-
// figure out why are providing
562-
// issueRules: { [issueName: string]: boolean }
563-
// but expecting
564-
// issueRules: { [issueName: string]: { action: 'defer' | 'error' | 'ignore' | 'monitor' | 'warn' } }
565-
issueRules: (<unknown>socketYml.parsed.issueRules) as {
566-
[key: string]: {
567-
action: 'defer' | 'error' | 'ignore' | 'monitor' | 'warn'
568-
}
569-
}
570-
}
571-
}
572-
})
573-
}
574-
_uxLookup = createAlertUXLookup(settings)
575-
})()

0 commit comments

Comments
 (0)