config-static: support integrity

This commit is contained in:
E. S. 2024-03-13 01:27:35 +00:00
parent 73476cc3b9
commit 3be0e8474d
3 changed files with 21 additions and 7 deletions

View File

@ -1,9 +1,8 @@
#!/usr/bin/env php #!/usr/bin/env php
<?php <?php
use util\cli;
require __DIR__.'/../init.php'; require __DIR__.'/../init.php';
require 'engine/skin.php';
if ($argc <= 1) { if ($argc <= 1) {
usage(); usage();
@ -36,8 +35,14 @@ foreach (['css', 'js'] as $type) {
continue; continue;
} }
foreach ($entries as $file) foreach ($entries as $file) {
$hashes[$type.'/'.basename($file)] = get_hash($file); $hashes[$type.'/'.basename($file)] = [
'version' => get_hash($file),
'integrity' => []
];
foreach (RESOURCE_INTEGRITY_HASHES as $hash_type)
$hashes[$type.'/'.basename($file)]['integrity'][$hash_type] = base64_encode(hash_file($hash_type, $file, true));
}
} }
echo "<?php\n\n"; echo "<?php\n\n";

View File

@ -2,6 +2,8 @@
require_once 'lib/themes.php'; require_once 'lib/themes.php';
const RESOURCE_INTEGRITY_HASHES = ['sha256', 'sha384', 'sha512'];
$SkinState = new class { $SkinState = new class {
public array $lang = []; public array $lang = [];
public string $title = 'title'; public string $title = 'title';

View File

@ -146,7 +146,7 @@ function jsLink(string $name): string {
} else { } else {
$href = '/dist-js/'.$bname.'.js?'.getStaticVersion($name); $href = '/dist-js/'.$bname.'.js?'.getStaticVersion($name);
} }
return '<script src="'.$href.'" type="text/javascript"></script>'; return '<script src="'.$href.'" type="text/javascript"'.getStaticIntegrityAttribute($name).'></script>';
} }
function cssLink(string $name, string $theme, &$bname = null): string { function cssLink(string $name, string $theme, &$bname = null): string {
@ -165,7 +165,7 @@ function cssLink(string $name, string $theme, &$bname = null): string {
if ($theme == 'dark') if ($theme == 'dark')
$id .= '_dark'; $id .= '_dark';
return '<link rel="stylesheet" id="'.$id.'" type="text/css" href="'.$href.'">'; return '<link rel="stylesheet" id="'.$id.'" type="text/css" href="'.$href.'"'.getStaticIntegrityAttribute($name).'>';
} }
function cssPrefetchLink(string $name): string { function cssPrefetchLink(string $name): string {
@ -195,7 +195,14 @@ function getStaticVersion(string $name): string {
logWarning(__FUNCTION__.': '.$name.' starts with /'); logWarning(__FUNCTION__.': '.$name.' starts with /');
$name = substr($name, 1); $name = substr($name, 1);
} }
return $config['static'][$name] ?? 'notfound'; return $config['static'][$name]['version'] ?? 'notfound';
}
function getStaticIntegrityAttribute(string $name): string {
if (is_dev())
return '';
global $config;
return ' integrity="'.implode(' ', array_map(fn($hash_type) => $hash_type.'-'.$config['static'][$name]['integrity'][$hash_type], RESOURCE_INTEGRITY_HASHES)).'"';
} }