or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

generation.mdindex.mdparsing-serialization.mdverification.md

generation.mddocs/

0

# Integrity Generation

1

2

Generate SRI hashes from various data sources including raw data, streams, and hex values. Supports multiple algorithms and custom options for flexible hash creation in different scenarios.

3

4

## Capabilities

5

6

### From Data Function

7

8

Creates integrity hashes directly from string or Buffer data using multiple algorithms simultaneously.

9

10

```javascript { .api }

11

/**

12

* Creates Integrity object from string or Buffer data

13

* @param {string|Buffer} data - Data to hash

14

* @param {object} opts - Optional configuration

15

* @param {string[]} opts.algorithms - Algorithms to use (default: ['sha512'])

16

* @param {string[]} opts.options - Option strings to add to hashes

17

* @param {boolean} opts.strict - Use strict mode

18

* @returns {Integrity} Generated integrity object

19

*/

20

function fromData(data, opts);

21

```

22

23

**Usage Examples:**

24

25

```javascript

26

const ssri = require('ssri');

27

const fs = require('fs');

28

29

// Basic usage with default SHA-512

30

const integrity = ssri.fromData('hello world');

31

console.log(integrity.toString());

32

// -> 'sha512-MJ7MSJwS1utMxA9QyQLytNDtd+5RGnx6m808qG1M2G+YndNbxf9JlnDaNCVbRbDP2DDoH2Bdz33FVC6TrpzXbw=='

33

34

// Multiple algorithms

35

const multiAlgo = ssri.fromData(fs.readFileSync('./package.json'), {

36

algorithms: ['sha256', 'sha384', 'sha512']

37

});

38

console.log(multiAlgo.toString());

39

// -> 'sha256-abc... sha384-def... sha512-ghi...'

40

41

// With custom options

42

const withOptions = ssri.fromData('data', {

43

algorithms: ['sha256'],

44

options: ['cors', 'integrity-metadata']

45

});

46

console.log(withOptions.toString());

47

// -> 'sha256-abc...?cors?integrity-metadata'

48

49

// From Buffer

50

const buffer = Buffer.from('binary data', 'utf8');

51

const bufferIntegrity = ssri.fromData(buffer);

52

```

53

54

### From Stream Function

55

56

Asynchronously generates integrity hashes by reading from a stream, ideal for large files or network streams.

57

58

```javascript { .api }

59

/**

60

* Generates Integrity by reading from stream

61

* @param {ReadableStream} stream - Stream to read data from

62

* @param {object} opts - Optional configuration (same as fromData)

63

* @returns {Promise<Integrity>} Promise resolving to generated integrity

64

*/

65

function fromStream(stream, opts);

66

```

67

68

**Usage Examples:**

69

70

```javascript

71

const ssri = require('ssri');

72

const fs = require('fs');

73

74

// Generate integrity from file stream

75

ssri.fromStream(fs.createReadStream('./large-file.zip'))

76

.then(integrity => {

77

console.log('File integrity:', integrity.toString());

78

// Save integrity for later verification

79

fs.writeFileSync('./large-file.zip.integrity', integrity.toString());

80

})

81

.catch(err => console.error('Generation failed:', err));

82

83

// Multiple algorithms from stream

84

ssri.fromStream(fs.createReadStream('./data.json'), {

85

algorithms: ['sha1', 'sha256', 'sha512']

86

})

87

.then(integrity => {

88

console.log('Multi-algorithm integrity generated');

89

// Can verify with any of the algorithms

90

});

91

92

// HTTP response stream

93

const https = require('https');

94

https.get('https://example.com/file.js', (response) => {

95

ssri.fromStream(response, { algorithms: ['sha384'] })

96

.then(integrity => {

97

console.log('CDN file integrity:', integrity.toString());

98

});

99

});

100

```

101

102

### From Hex Function

103

104

Creates integrity from existing hex-formatted hash digests, useful for converting from other hash formats.

105

106

```javascript { .api }

107

/**

108

* Creates Integrity from hex-formatted hash

109

* @param {string} hexDigest - Hex string of hash digest

110

* @param {string} algorithm - Hash algorithm name

111

* @param {object} opts - Optional configuration

112

* @param {string[]} opts.options - Option strings to add

113

* @param {boolean} opts.strict - Use strict mode

114

* @param {boolean} opts.single - Return single Hash instead of Integrity

115

* @returns {Integrity|Hash} Generated integrity or hash object

116

*/

117

function fromHex(hexDigest, algorithm, opts);

118

```

119

120

**Usage Examples:**

121

122

```javascript

123

const ssri = require('ssri');

124

const crypto = require('crypto');

125

126

// Convert existing hex hash to SRI format

127

const hexHash = crypto.createHash('sha256').update('hello').digest('hex');

128

const integrity = ssri.fromHex(hexHash, 'sha256');

129

console.log(integrity.toString());

130

// -> 'sha256-LPJNul+wow4m6DsqxbninhsWHlwfp0JecwQzYpOLmCQ='

131

132

// With options

133

const withOptions = ssri.fromHex('deadbeef', 'sha1', {

134

options: ['legacy-hash']

135

});

136

console.log(withOptions.toString());

137

// -> 'sha1-3q2+7w==?legacy-hash'

138

139

// Return single Hash instead of Integrity

140

const singleHash = ssri.fromHex('abcd1234', 'sha256', { single: true });

141

console.log(singleHash.algorithm); // 'sha256'

142

console.log(singleHash.hexDigest()); // 'abcd1234'

143

144

// Converting from other systems

145

const md5Hash = 'd41d8cd98f00b204e9800998ecf8427e'; // empty string MD5

146

const md5Integrity = ssri.fromHex(md5Hash, 'md5');

147

```

148

149

### Create Function

150

151

Creates a hash builder object that mimics Node.js crypto.Hash interface for incremental hashing.

152

153

```javascript { .api }

154

/**

155

* Creates hash builder with update/digest pattern

156

* @param {object} opts - Optional configuration (same as fromData)

157

* @returns {object} Hash builder with update() and digest() methods

158

*/

159

function create(opts);

160

161

interface HashBuilder {

162

/**

163

* Updates hash with new data chunk

164

* @param {string|Buffer} chunk - Data to add

165

* @param {string} enc - Encoding for string data

166

* @returns {HashBuilder} This builder for chaining

167

*/

168

update(chunk, enc);

169

170

/**

171

* Finalizes hash and returns Integrity object

172

* @returns {Integrity} Generated integrity object

173

*/

174

digest();

175

}

176

```

177

178

**Usage Examples:**

179

180

```javascript

181

const ssri = require('ssri');

182

183

// Incremental hashing

184

const hasher = ssri.create();

185

hasher.update('Hello, ');

186

hasher.update('world!');

187

const integrity = hasher.digest();

188

console.log(integrity.toString());

189

190

// Stream-like usage

191

const builder = ssri.create({ algorithms: ['sha256', 'sha512'] });

192

const chunks = ['chunk1', 'chunk2', 'chunk3'];

193

chunks.forEach(chunk => builder.update(chunk));

194

const result = builder.digest();

195

196

// Processing form data

197

const formHasher = ssri.create();

198

formHasher.update('field1=value1&');

199

formHasher.update('field2=value2&');

200

formHasher.update('field3=value3');

201

const formIntegrity = formHasher.digest();

202

203

// Compatible with crypto.Hash pattern

204

function hashData(data) {

205

return ssri.create()

206

.update(data)

207

.digest();

208

}

209

```

210

211

## Generation Options

212

213

### Algorithm Selection

214

215

```javascript { .api }

216

interface GenerationOptions {

217

/** Algorithms to use for hash generation */

218

algorithms?: string[]; // Default: ['sha512']

219

220

/** Option strings to append to generated hashes */

221

options?: string[]; // Default: undefined

222

223

/** Use strict SRI spec compliance */

224

strict?: boolean; // Default: false

225

}

226

```

227

228

**Available Algorithms:**

229

230

```javascript

231

// Standard SRI algorithms (recommended)

232

['sha256', 'sha384', 'sha512']

233

234

// Extended algorithms (when not in strict mode)

235

crypto.getHashes() // All Node.js supported algorithms

236

```

237

238

### Custom Options

239

240

```javascript

241

// Add custom metadata to hashes

242

const integrity = ssri.fromData(data, {

243

algorithms: ['sha384'],

244

options: ['cors', 'version=1.2.3', 'env=prod']

245

});

246

// Result: 'sha384-abc...?cors?version=1.2.3?env=prod'

247

```

248

249

### Performance Considerations

250

251

```javascript

252

// Single algorithm for performance

253

const fast = ssri.fromData(largeData, { algorithms: ['sha256'] });

254

255

// Multiple algorithms for security (more CPU intensive)

256

const secure = ssri.fromData(sensitiveData, {

257

algorithms: ['sha256', 'sha384', 'sha512']

258

});

259

260

// Stream processing for large files (memory efficient)

261

const streamIntegrity = await ssri.fromStream(

262

fs.createReadStream('./huge-file.bin'),

263

{ algorithms: ['sha512'] }

264

);

265

```

266

267

## Error Handling

268

269

Generation functions are generally robust but can encounter these scenarios:

270

271

```javascript

272

// Stream errors propagate to Promise rejection

273

ssri.fromStream(badStream)

274

.catch(err => {

275

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

276

// Handle stream read errors, network issues, etc.

277

});

278

279

// Invalid algorithm names silently ignored in permissive mode

280

const partial = ssri.fromData('test', {

281

algorithms: ['sha256', 'invalid-algo', 'sha512']

282

});

283

// Only generates sha256 and sha512 hashes

284

285

// Strict mode validation

286

const strict = ssri.fromData('test', {

287

algorithms: ['md5'],

288

strict: true

289

});

290

// May not include md5 if not in SPEC_ALGORITHMS

291

```

292

293

## Integration Patterns

294

295

### Package Manager Integration

296

297

```javascript

298

// Generate package integrity

299

const packageIntegrity = ssri.fromData(

300

fs.readFileSync('./package.tgz'),

301

{ algorithms: ['sha512'] }

302

);

303

304

// Store in package-lock.json format

305

const lockEntry = {

306

integrity: packageIntegrity.toString(),

307

// ... other metadata

308

};

309

```

310

311

### CDN Resource Verification

312

313

```javascript

314

// Generate integrity for CDN resources

315

const cdnResource = await fetch('https://cdn.example.com/lib.js');

316

const resourceData = await cdnResource.text();

317

const cdnIntegrity = ssri.fromData(resourceData, {

318

algorithms: ['sha384'] // Common for CDN SRI

319

});

320

321

// Use in HTML

322

console.log(`<script src="https://cdn.example.com/lib.js"

323

integrity="${cdnIntegrity.toString()}"

324

crossorigin="anonymous"></script>`);

325

```

326

327

### Build System Integration

328

329

```javascript

330

// Generate integrity hashes during build

331

const buildFiles = glob.sync('./dist/**/*.{js,css}');

332

const integrityMap = {};

333

334

buildFiles.forEach(file => {

335

const content = fs.readFileSync(file);

336

integrityMap[file] = ssri.fromData(content, {

337

algorithms: ['sha384']

338

}).toString();

339

});

340

341

fs.writeFileSync('./dist/integrity.json', JSON.stringify(integrityMap));

342

```