or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

cli.mdconfiguration.mdformatters.mdindex.mdlibrary.md

library.mddocs/

0

# Library API

1

2

The NSP library provides programmatic access to vulnerability scanning functionality for integration into Node.js applications.

3

4

## Core Imports

5

6

```javascript

7

const nsp = require('nsp');

8

const { check, formatters, getFormatter } = require('nsp');

9

```

10

11

## Capabilities

12

13

### Check Function

14

15

The main function for scanning packages for vulnerabilities.

16

17

```javascript { .api }

18

/**

19

* Scan a Node.js project for known security vulnerabilities

20

* @param {CheckOptions} options - Configuration options for the scan

21

* @param {CheckCallback} callback - Callback function to handle results

22

*/

23

function check(options, callback);

24

25

// Options can also be a function if no options needed

26

function check(callback);

27

28

interface CheckOptions {

29

/** Path to package.json file or parsed package object */

30

package?: string | object;

31

/** Path to npm-shrinkwrap.json file or parsed shrinkwrap object */

32

shrinkwrap?: string | object;

33

/** Path to package-lock.json file or parsed package-lock object */

34

packagelock?: string | object;

35

/** Array of advisory URLs to exclude from results */

36

exceptions?: string[];

37

/** Enable offline mode (requires shrinkwrap and advisories) */

38

offline?: boolean;

39

/** Path to local advisories file for offline mode */

40

advisoriesPath?: string;

41

/** Proxy server URL */

42

proxy?: string;

43

}

44

45

interface CheckCallback {

46

(err: Error | null, results: VulnerabilityResult[]): void;

47

}

48

49

interface VulnerabilityResult {

50

/** Name of the vulnerable module */

51

module: string;

52

/** Installed version of the module */

53

version: string;

54

/** Version range that is vulnerable */

55

vulnerable_versions: string;

56

/** Version range that contains fixes */

57

patched_versions: string;

58

/** Human-readable title of the vulnerability */

59

title: string;

60

/** Dependency path to the vulnerable module */

61

path: string[];

62

/** URL to the full advisory */

63

advisory: string;

64

/** CVSS score if available */

65

cvss_score?: number;

66

/** Line information for shrinkwrap files */

67

line?: { start: number; end: number };

68

/** Markdown content with full vulnerability details */

69

content?: string;

70

}

71

```

72

73

**Usage Examples:**

74

75

```javascript

76

const nsp = require('nsp');

77

const path = require('path');

78

79

// Basic check with default options

80

nsp.check(function(err, results) {

81

if (err) {

82

console.error('Scan failed:', err.message);

83

return;

84

}

85

86

console.log(`Found ${results.length} vulnerabilities`);

87

results.forEach(vuln => {

88

console.log(`${vuln.module}@${vuln.version}: ${vuln.title}`);

89

});

90

});

91

92

// Check specific project

93

nsp.check({

94

package: path.join(__dirname, 'package.json'),

95

shrinkwrap: path.join(__dirname, 'npm-shrinkwrap.json')

96

}, function(err, results) {

97

if (err) throw err;

98

99

const highSeverity = results.filter(v => v.cvss_score >= 7.0);

100

console.log(`${highSeverity.length} high severity issues found`);

101

});

102

103

// Check with exceptions

104

nsp.check({

105

package: './package.json',

106

exceptions: [

107

'https://nodesecurity.io/advisories/123',

108

'https://nodesecurity.io/advisories/456'

109

]

110

}, function(err, results) {

111

// Results will exclude the specified advisories

112

console.log('Filtered results:', results);

113

});

114

115

// Offline mode check

116

nsp.check({

117

package: './package.json',

118

shrinkwrap: './npm-shrinkwrap.json',

119

offline: true,

120

advisoriesPath: './advisories.json'

121

}, function(err, results) {

122

if (err) {

123

console.error('Offline check failed:', err.message);

124

return;

125

}

126

console.log('Offline scan complete:', results.length, 'issues');

127

});

128

```

129

130

### Get Formatter Function

131

132

Retrieves output formatter functions by name.

133

134

```javascript { .api }

135

/**

136

* Get a formatter function by name

137

* @param {string} name - Name of the formatter (built-in or custom)

138

* @returns {FormatterFunction} The formatter function

139

*/

140

function getFormatter(name);

141

142

interface FormatterFunction {

143

(err: Error | null, data: VulnerabilityResult[], pkgPath: string): string;

144

}

145

```

146

147

**Built-in Formatter Names:**

148

- `'default'` - Colorized table format

149

- `'summary'` - Simplified table

150

- `'json'` - JSON output

151

- `'codeclimate'` - Code Climate format

152

- `'none'` - No output

153

- `'quiet'` - Minimal output

154

155

**Custom Formatters:**

156

Custom formatters follow the naming pattern `nsp-formatter-<name>` and can be loaded by name.

157

158

**Usage Examples:**

159

160

```javascript

161

const nsp = require('nsp');

162

163

// Get built-in formatter

164

const jsonFormatter = nsp.getFormatter('json');

165

166

// Use formatter with check results

167

nsp.check(function(err, results) {

168

const output = jsonFormatter(err, results, './package.json');

169

console.log(output);

170

});

171

172

// Get custom formatter (requires nsp-formatter-xml package)

173

const xmlFormatter = nsp.getFormatter('xml');

174

175

// Format results

176

nsp.check({ package: './package.json' }, function(err, results) {

177

const output = xmlFormatter(err, results, './package.json');

178

fs.writeFileSync('security-report.xml', output);

179

});

180

181

// Error handling for unknown formatters

182

try {

183

const unknownFormatter = nsp.getFormatter('nonexistent');

184

} catch (e) {

185

// Falls back to default formatter if custom formatter not found

186

console.log('Using default formatter instead');

187

}

188

```

189

190

### Formatters Object

191

192

Direct access to all built-in formatter functions.

193

194

```javascript { .api }

195

/**

196

* Object containing all built-in formatter functions

197

*/

198

const formatters = {

199

default: FormatterFunction,

200

summary: FormatterFunction,

201

json: FormatterFunction,

202

codeclimate: FormatterFunction,

203

none: FormatterFunction,

204

quiet: FormatterFunction

205

};

206

```

207

208

**Usage Example:**

209

210

```javascript

211

const { formatters } = require('nsp');

212

213

// Use formatters directly

214

nsp.check(function(err, results) {

215

// Generate multiple output formats

216

const jsonOutput = formatters.json(err, results, './package.json');

217

const summaryOutput = formatters.summary(err, results, './package.json');

218

219

// Save both formats

220

fs.writeFileSync('report.json', jsonOutput);

221

console.log(summaryOutput);

222

});

223

```

224

225

### Error Handling

226

227

Common error scenarios and handling patterns:

228

229

```javascript

230

nsp.check(options, function(err, results) {

231

if (err) {

232

if (err.message.includes('package.json is required')) {

233

console.error('No package.json found in the specified location');

234

} else if (err.message.includes('npm-shrinkwrap.json is required')) {

235

console.error('Offline mode requires npm-shrinkwrap.json');

236

} else if (err.message.includes('invalid response')) {

237

console.error('Network error connecting to Node Security API');

238

} else {

239

console.error('Unexpected error:', err.message);

240

}

241

return;

242

}

243

244

// Process results

245

console.log('Scan complete:', results.length, 'vulnerabilities found');

246

});

247

```