0
# SSRI
1
2
SSRI (Standard Subresource Integrity) is a Node.js utility for parsing, manipulating, serializing, generating, and verifying Subresource Integrity hashes according to the W3C specification. It provides comprehensive functionality for cryptographic integrity validation of external resources in web applications.
3
4
## Package Information
5
6
- **Package Name**: ssri
7
- **Package Type**: npm
8
- **Language**: JavaScript (Node.js)
9
- **Installation**: `npm install ssri`
10
11
## Core Imports
12
13
```javascript
14
const ssri = require('ssri');
15
```
16
17
Or with destructuring:
18
19
```javascript
20
const { parse, stringify, fromData, checkData } = require('ssri');
21
```
22
23
## Basic Usage
24
25
```javascript
26
const ssri = require('ssri');
27
const fs = require('fs');
28
29
// Generate integrity from data
30
const integrity = ssri.fromData(fs.readFileSync('./my-file.js'));
31
console.log(integrity.toString());
32
// -> 'sha512-9KhgCRIx/AmzC8xqYJTZRrnO8OW2Pxyl2DIMZSBOr0oDvtEFyht3xpp71j/r/pAe1DM+JI/A+line3jUBgzQ7A=='
33
34
// Verify data integrity
35
const isValid = ssri.checkData(fs.readFileSync('./my-file.js'), integrity);
36
if (isValid) {
37
console.log('Data integrity verified!');
38
}
39
40
// Stream processing with integrity verification
41
const stream = fs.createReadStream('./my-file.js');
42
ssri.checkStream(stream, integrity)
43
.then(hash => console.log('Stream verified:', hash.algorithm))
44
.catch(err => console.error('Verification failed:', err.message));
45
```
46
47
## Architecture
48
49
SSRI is built around several core components:
50
51
- **Hash Class**: Represents individual integrity hashes with algorithm, digest, and options
52
- **Integrity Class**: Container for multiple hashes organized by algorithm for comprehensive integrity checking
53
- **IntegrityStream**: Transform stream for real-time integrity generation and verification during data processing
54
- **Parser/Serializer**: Standards-compliant parsing and stringification of SRI metadata
55
- **Generation Engine**: Multiple methods for creating integrity hashes from various data sources
56
- **Verification Engine**: Robust validation system supporting both sync and async verification patterns
57
58
## Capabilities
59
60
### Parsing & Serialization
61
62
Core functionality for parsing SRI strings into structured objects and serializing them back to standard format. Essential for working with existing integrity metadata.
63
64
```javascript { .api }
65
function parse(sri, opts): Integrity | Hash | null;
66
function stringify(obj, opts): string;
67
```
68
69
[Parsing & Serialization](./parsing-serialization.md)
70
71
### Integrity Generation
72
73
Generate SRI hashes from various data sources including raw data, streams, and hex values. Supports multiple algorithms and custom options for flexible hash creation.
74
75
```javascript { .api }
76
function fromData(data, opts): Integrity;
77
function fromStream(stream, opts): Promise<Integrity>;
78
function fromHex(hexDigest, algorithm, opts): Integrity | Hash;
79
function create(opts): HashBuilder;
80
```
81
82
[Integrity Generation](./generation.md)
83
84
### Integrity Verification
85
86
Verify data integrity against existing SRI hashes with comprehensive error reporting. Supports both synchronous data verification and asynchronous stream verification.
87
88
```javascript { .api }
89
function checkData(data, sri, opts): Hash | false;
90
function checkStream(stream, sri, opts): Promise<Hash>;
91
function integrityStream(opts): IntegrityStream;
92
```
93
94
[Integrity Verification](./verification.md)
95
96
## Core Types
97
98
```javascript { .api }
99
class Hash {
100
constructor(hash, opts);
101
get isHash(): true;
102
hexDigest(): string;
103
toString(opts): string;
104
toJSON(): string;
105
match(integrity, opts): Hash | false;
106
107
// Properties
108
source: string; // Original hash string
109
algorithm: string; // Hash algorithm name
110
digest: string; // Base64 digest value
111
options: string[]; // Array of option strings
112
}
113
114
class Integrity {
115
get isIntegrity(): true;
116
toString(opts): string;
117
toJSON(): string;
118
isEmpty(): boolean;
119
concat(integrity, opts): Integrity;
120
merge(integrity, opts): void;
121
match(integrity, opts): Hash | false;
122
pickAlgorithm(opts, hashes): string | null;
123
hexDigest(): string;
124
125
// Properties (dynamic)
126
[algorithm: string]: Hash[]; // Hashes grouped by algorithm
127
}
128
129
class IntegrityStream extends Minipass {
130
constructor(opts);
131
// Emits: 'size', 'integrity', 'verified', 'error'
132
}
133
134
interface HashBuilder {
135
update(chunk, enc): HashBuilder;
136
digest(): Integrity;
137
}
138
```
139
140
## Constants
141
142
```javascript { .api }
143
// W3C SRI specification compliant algorithms
144
const SPEC_ALGORITHMS = ['sha512', 'sha384', 'sha256'];
145
146
// Default algorithm used when none specified
147
const DEFAULT_ALGORITHMS = ['sha512'];
148
149
// Algorithm priority for pickAlgorithm (index-based, higher = stronger)
150
const DEFAULT_PRIORITY = [
151
'md5', 'whirlpool', 'sha1', 'sha224', 'sha256', 'sha384', 'sha512',
152
'sha3', 'sha3-256', 'sha3-384', 'sha3-512', 'sha3_256', 'sha3_384', 'sha3_512'
153
];
154
155
// Internal validation patterns (for parsing and validation)
156
const BASE64_REGEX = /^[a-z0-9+/]+(?:=?=?)$/i; // Base64 format validation
157
const SRI_REGEX = /^([a-z0-9]+)-([^?]+)([?\S*]*)$/; // General SRI format
158
const STRICT_SRI_REGEX = /^([a-z0-9]+)-([A-Za-z0-9+/=]{44,88})(\?[\x21-\x7E]*)?$/; // Strict SRI
159
const VCHAR_REGEX = /^[\x21-\x7E]+$/; // Visible character validation
160
```
161
162
## Error Codes
163
164
- **EINTEGRITY**: Integrity verification failed
165
- **EBADSIZE**: Size verification failed (when size option is provided)
166
167
## Options Reference
168
169
```javascript { .api }
170
interface ParseOptions {
171
single?: boolean; // Return single Hash instead of Integrity
172
strict?: boolean; // Use strict SRI spec compliance
173
}
174
175
interface GenerationOptions {
176
algorithms?: string[]; // Algorithms to use (default: ['sha512'])
177
options?: string[]; // Option strings to add to hashes
178
strict?: boolean; // Use strict mode
179
}
180
181
interface VerificationOptions {
182
error?: boolean; // Throw error on mismatch
183
size?: number; // Expected data size
184
pickAlgorithm?: function; // Custom algorithm selection
185
}
186
187
interface StringifyOptions {
188
sep?: string; // Separator for multiple entries (default: ' ')
189
strict?: boolean; // Use strict parsing rules
190
}
191
```