@@ -44,6 +44,24 @@ var defaultOptions = {
4444 UserAgent : '' ,
4545 ConfCwd : '' ,
4646 ForceSignHost : true , // 默认将host加入签名计算,关闭后可能导致越权风险,建议保持为true
47+ // 动态秘钥,优先级Credentials > SecretId/SecretKey。注意Cred内是小写的secretId、secretKey
48+ Credentials : {
49+ secretId : '' ,
50+ secretKey : '' ,
51+ } ,
52+ } ;
53+
54+ const watch = ( obj , name , callback ) => {
55+ let value = obj [ name ] ;
56+ Object . defineProperty ( obj , name , {
57+ get ( ) {
58+ return value ;
59+ } ,
60+ set ( newValue ) {
61+ value = newValue ;
62+ callback ( ) ;
63+ }
64+ } ) ;
4765} ;
4866
4967// 对外暴露的类
@@ -66,6 +84,11 @@ var COS = function (options) {
6684 if ( this . options . secretId && ! this . options . SecretId ) this . options . SecretId = this . options . secretId ;
6785 if ( this . options . secretKey && ! this . options . SecretKey ) this . options . SecretKey = this . options . secretKey ;
6886 console . warn ( 'warning: Please change options secretId/secretKey to SecretId/SecretKey.' ) ;
87+ }
88+ // 支持外部传入Cred动态秘钥
89+ if ( this . options . Credentials ) {
90+ this . options . SecretId = this . options . Credentials . secretId || '' ;
91+ this . options . SecretKey = this . options . Credentials . secretKey || '' ;
6992 }
7093 if ( this . options . SecretId && this . options . SecretId . indexOf ( ' ' ) > - 1 ) {
7194 console . error ( 'error: SecretId格式错误,请检查' ) ;
@@ -81,6 +104,16 @@ var COS = function (options) {
81104 }
82105 event . init ( this ) ;
83106 task . init ( this ) ;
107+
108+ // 支持动态秘钥,监听到cred里secretId、secretKey变化时,主动给cos替换秘钥
109+ watch ( this . options . Credentials , 'secretId' , ( ) => {
110+ console . log ( 'Credentials secretId changed' ) ;
111+ this . options . SecretId = this . options . Credentials . secretId ;
112+ } ) ;
113+ watch ( this . options . Credentials , 'secretKey' , ( ) => {
114+ console . log ( 'Credentials secretKey changed' ) ;
115+ this . options . SecretKey = this . options . Credentials . secretKey ;
116+ } ) ;
84117} ;
85118
86119base . init ( COS , task ) ;
0 commit comments