-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathgenerate-sri.js
More file actions
executable file
·164 lines (140 loc) · 4.78 KB
/
generate-sri.js
File metadata and controls
executable file
·164 lines (140 loc) · 4.78 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
#!/usr/bin/env node
/**
* Generate SRI (Subresource Integrity) hashes for all built assets
* Run after build: node generate-sri.js
*/
import crypto from 'crypto';
import fs from 'fs';
import path from 'path';
import { fileURLToPath } from 'url';
import { dirname } from 'path';
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
const DIST_DIR = path.join(__dirname, 'dist');
const ASSETS_DIR = path.join(DIST_DIR, 'assets');
const SRI_OUTPUT = path.join(DIST_DIR, 'sri-mapping.json');
const INDEX_HTML = path.join(DIST_DIR, 'index.html');
/**
* Generate SHA-384 hash for a file
*/
function generateSRI(filePath) {
const content = fs.readFileSync(filePath);
const hash = crypto.createHash('sha384').update(content).digest('base64');
return `sha384-${hash}`;
}
/**
* Find all JavaScript and CSS files in assets directory
*/
function findAssets() {
const assets = {};
if (!fs.existsSync(ASSETS_DIR)) {
console.error('Assets directory not found:', ASSETS_DIR);
return assets;
}
const files = fs.readdirSync(ASSETS_DIR);
for (const file of files) {
if (file.endsWith('.js') || file.endsWith('.css')) {
const filePath = path.join(ASSETS_DIR, file);
const sri = generateSRI(filePath);
assets[file] = sri;
console.log(`✓ ${file}: ${sri}`);
}
}
return assets;
}
/**
* Update index.html with integrity attributes
*/
function updateIndexHTML(sriMapping) {
if (!fs.existsSync(INDEX_HTML)) {
console.error('index.html not found');
return;
}
let html = fs.readFileSync(INDEX_HTML, 'utf8');
let updated = false;
// Update script tags with integrity
for (const [filename, hash] of Object.entries(sriMapping)) {
if (filename.endsWith('.js')) {
// Match script tags with this file
const scriptRegex = new RegExp(
`(<script[^>]*src=["']/assets/${filename.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}["'][^>]*)(>)`,
'g'
);
html = html.replace(scriptRegex, (match, before, after) => {
// Check if integrity already exists
if (before.includes('integrity=')) {
// Update existing integrity
const newBefore = before.replace(/integrity=["'][^"']*["']/, `integrity="${hash}"`);
updated = true;
return newBefore + after;
} else {
// Add integrity attribute
updated = true;
return `${before} integrity="${hash}" crossorigin${after}`;
}
});
// Match modulepreload links
const preloadRegex = new RegExp(
`(<link[^>]*rel=["']modulepreload["'][^>]*href=["']/assets/${filename.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}["'][^>]*)(>)`,
'g'
);
html = html.replace(preloadRegex, (match, before, after) => {
// Check if integrity already exists
if (before.includes('integrity=')) {
// Update existing integrity
const newBefore = before.replace(/integrity=["'][^"']*["']/, `integrity="${hash}"`);
updated = true;
return newBefore + after;
} else {
// Add integrity attribute
updated = true;
return `${before} integrity="${hash}" crossorigin${after}`;
}
});
} else if (filename.endsWith('.css')) {
// Match CSS link tags
const cssRegex = new RegExp(
`(<link[^>]*href=["']/assets/${filename.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}["'][^>]*)(>)`,
'g'
);
html = html.replace(cssRegex, (match, before, after) => {
if (before.includes('integrity=')) {
const newBefore = before.replace(/integrity=["'][^"']*["']/, `integrity="${hash}"`);
updated = true;
return newBefore + after;
} else {
updated = true;
return `${before} integrity="${hash}" crossorigin${after}`;
}
});
}
}
if (updated) {
fs.writeFileSync(INDEX_HTML, html);
console.log('\n✓ Updated index.html with integrity attributes');
}
}
/**
* Main execution
*/
function main() {
console.log('🔐 Generating SRI hashes for assets...\n');
// Generate SRI hashes
const sriMapping = findAssets();
if (Object.keys(sriMapping).length === 0) {
console.error('\n❌ No assets found to hash');
process.exit(1);
}
// Save SRI mapping
fs.writeFileSync(SRI_OUTPUT, JSON.stringify(sriMapping, null, 2));
console.log(`\n✓ SRI mapping saved to: ${SRI_OUTPUT}`);
console.log(` ${Object.keys(sriMapping).length} files hashed`);
// Update index.html
updateIndexHTML(sriMapping);
console.log('\n✅ SRI generation complete!');
console.log('\n📋 Next steps:');
console.log(' 1. Verify integrity attributes in dist/index.html');
console.log(' 2. Update CSP headers to enforce script hashes');
console.log(' 3. Deploy updated files to Cloud Run');
}
main();