@@ -5,7 +5,9 @@ import { cheerio, logger } from '@winner-fed/utils';
55import type { IApi } from '@winner-fed/winjs' ;
66
77interface SecurityConfig {
8- sri : boolean ;
8+ sri : boolean | {
9+ algorithm : 'sha256' | 'sha384' | 'sha512' ;
10+ } ;
911}
1012
1113export default ( api : IApi ) => {
@@ -15,7 +17,12 @@ export default (api: IApi) => {
1517 config : {
1618 schema ( { zod } ) {
1719 return zod . object ( {
18- sri : zod . boolean ( ) ,
20+ sri : zod . union ( [
21+ zod . boolean ( ) ,
22+ zod . object ( {
23+ algorithm : zod . enum ( [ 'sha256' , 'sha384' , 'sha512' ] ) . default ( 'sha512' ) ,
24+ } )
25+ ] )
1926 } ) ;
2027 } ,
2128 } ,
@@ -26,11 +33,22 @@ export default (api: IApi) => {
2633 async ( html : { htmlFiles ?: Array < { path : string ; content : string } > } ) => {
2734 const config = api . config . security as SecurityConfig ;
2835
29- // 只有当 sri 配置为 true 时才生成 SRI
36+ // 只有当 sri 配置为 true 或对象时才生成 SRI
3037 if ( ! config ?. sri ) {
3138 return ;
3239 }
3340
41+ // 处理 sri 配置,支持 boolean 和对象
42+ let sriConfig : { algorithm : 'sha256' | 'sha384' | 'sha512' } ;
43+ if ( config . sri === true ) {
44+ sriConfig = { algorithm : 'sha512' } ;
45+ } else if ( typeof config . sri === 'object' && config . sri !== null && typeof ( config . sri as any ) . algorithm === 'string' ) {
46+ sriConfig = { algorithm : ( config . sri as any ) . algorithm } ;
47+ } else {
48+ // 未指定算法时,默认 sha512
49+ sriConfig = { algorithm : 'sha512' } ;
50+ }
51+
3452 const htmlFiles = html ?. htmlFiles || [ ] ;
3553 if ( api . env === 'development' || htmlFiles . length === 0 ) {
3654 return ;
@@ -68,9 +86,9 @@ export default (api: IApi) => {
6886 }
6987
7088 if ( source ) {
71- const hash = createHash ( 'sha512' ) . update ( source ) . digest ( 'base64' ) ;
89+ const hash = createHash ( sriConfig . algorithm ) . update ( source ) . digest ( 'base64' ) ;
7290
73- $el . attr ( 'integrity' , `sha512 -${ hash } ` ) ;
91+ $el . attr ( 'integrity' , `${ sriConfig . algorithm } -${ hash } ` ) ;
7492
7593 // https://developer.mozilla.org/zh-CN/docs/Web/HTML/Attributes/crossorigin
7694 // 在进行跨域资源请求时,integrity 必须配合 crossorigin 使用,不然浏览器会丢弃这个资源的请求
0 commit comments