sts.js 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163
  1. // 临时密钥服务例子
  2. var bodyParser = require('body-parser');
  3. var STS = require('qcloud-cos-sts');
  4. var express = require('express');
  5. var crypto = require('crypto');
  6. // 配置参数
  7. var config = {
  8. secretId: process.env.SecretId,
  9. secretKey: process.env.SecretKey,
  10. proxy: process.env.Proxy,
  11. durationSeconds: 1800,
  12. bucket: process.env.Bucket,
  13. region: process.env.Region,
  14. // 允许操作(上传)的对象前缀,可以根据自己网站的用户登录态判断允许上传的目录,例子: user1/* 或者 * 或者a.jpg
  15. // 请注意当使用 * 时,可能存在安全风险,详情请参阅:https://cloud.tencent.com/document/product/436/40265
  16. allowPrefix: '_ALLOW_DIR_/*',
  17. // 简单上传和分片,需要以下的权限,其他权限列表请看 https://cloud.tencent.com/document/product/436/14048
  18. allowActions: [
  19. // 所有 action 请看文档 https://cloud.tencent.com/document/product/436/31923
  20. // 简单上传
  21. 'name/cos:PutObject',
  22. 'name/cos:PostObject',
  23. // 分片上传
  24. 'name/cos:InitiateMultipartUpload',
  25. 'name/cos:ListMultipartUploads',
  26. 'name/cos:ListParts',
  27. 'name/cos:UploadPart',
  28. 'name/cos:CompleteMultipartUpload'
  29. ],
  30. };
  31. // 创建临时密钥服务
  32. var app = express();
  33. app.use(bodyParser.json());
  34. // 格式一:临时密钥接口
  35. app.all('/sts', function (req, res, next) {
  36. // TODO 这里根据自己业务需要做好放行判断
  37. if (config.allowPrefix === '_ALLOW_DIR_/*') {
  38. res.send({error: '请修改 allowPrefix 配置项,指定允许上传的路径前缀'});
  39. return;
  40. }
  41. // 获取临时密钥
  42. var LongBucketName = config.bucket;
  43. var ShortBucketName = LongBucketName.substr(0, LongBucketName.lastIndexOf('-'));
  44. var AppId = LongBucketName.substr(LongBucketName.lastIndexOf('-') + 1);
  45. var policy = {
  46. 'version': '2.0',
  47. 'statement': [{
  48. 'action': config.allowActions,
  49. 'effect': 'allow',
  50. 'resource': [
  51. 'qcs::cos:' + config.region + ':uid/' + AppId + ':prefix//' + AppId + '/' + ShortBucketName + '/' + config.allowPrefix,
  52. ],
  53. }],
  54. };
  55. var startTime = Math.round(Date.now() / 1000);
  56. STS.getCredential({
  57. secretId: config.secretId,
  58. secretKey: config.secretKey,
  59. proxy: config.proxy,
  60. region: config.region,
  61. durationSeconds: config.durationSeconds,
  62. policy: policy,
  63. }, function (err, tempKeys) {
  64. if (tempKeys) tempKeys.startTime = startTime;
  65. res.send(err || tempKeys);
  66. });
  67. });
  68. // // 格式二:临时密钥接口,支持细粒度权限控制
  69. // // 判断是否允许获取密钥
  70. // var allowScope = function (scope) {
  71. // var allow = (scope || []).every(function (item) {
  72. // return config.allowActions.includes(item.action) &&
  73. // item.bucket === config.bucket &&
  74. // item.region === config.region &&
  75. // (item.prefix || '').startsWith(config.allowPrefix);
  76. // });
  77. // return allow;
  78. // };
  79. // app.all('/sts-scope', function (req, res, next) {
  80. // var scope = req.body;
  81. //
  82. // // TODO 这里根据自己业务需要做好放行判断
  83. // if (config.allowPrefix === '_ALLOW_DIR_/*') {
  84. // res.send({error: '请修改 allowPrefix 配置项,指定允许上传的路径前缀'});
  85. // return;
  86. // }
  87. // // TODO 这里可以判断 scope 细粒度控制权限
  88. // if (!scope || !scope.length || !allowScope(scope)) return res.send({error: 'deny'});
  89. //
  90. // // 获取临时密钥
  91. // var policy = STS.getPolicy(scope);
  92. // var startTime = Math.round(Date.now() / 1000);
  93. // STS.getCredential({
  94. // secretId: config.secretId,
  95. // secretKey: config.secretKey,
  96. // proxy: config.proxy,
  97. // durationSeconds: config.durationSeconds,
  98. // policy: policy,
  99. // }, function (err, tempKeys) {
  100. // if (tempKeys) tempKeys.startTime = startTime;
  101. // res.send(err || tempKeys);
  102. // });
  103. // });
  104. //
  105. // 用于 PostObject 签名保护
  106. app.all('/post-policy', function (req, res, next) {
  107. var query = req.query;
  108. var now = Math.round(Date.now() / 1000);
  109. var exp = now + 900;
  110. var qKeyTime = now + ';' + exp;
  111. var qSignAlgorithm = 'sha1';
  112. var policy = JSON.stringify({
  113. 'expiration': new Date(exp * 1000).toISOString(),
  114. 'conditions': [
  115. // {'acl': query.ACL},
  116. // ['starts-with', '$Content-Type', 'image/'],
  117. // ['starts-with', '$success_action_redirect', redirectUrl],
  118. // ['eq', '$x-cos-server-side-encryption', 'AES256'],
  119. {'q-sign-algorithm': qSignAlgorithm},
  120. {'q-ak': config.secretId},
  121. {'q-sign-time': qKeyTime},
  122. {'bucket': config.bucket},
  123. {'key': query.key},
  124. ]
  125. });
  126. // 签名算法说明文档:https://www.qcloud.com/document/product/436/7778
  127. // 步骤一:生成 SignKey
  128. var signKey = crypto.createHmac('sha1', config.secretKey).update(qKeyTime).digest('hex');
  129. // 步骤二:生成 StringToSign
  130. var stringToSign = crypto.createHash('sha1').update(policy).digest('hex');
  131. // 步骤三:生成 Signature
  132. var qSignature = crypto.createHmac('sha1', signKey).update(stringToSign).digest('hex');
  133. console.log(policy);
  134. res.send({
  135. policyObj: JSON.parse(policy),
  136. policy: Buffer.from(policy).toString('base64'),
  137. qSignAlgorithm: qSignAlgorithm,
  138. qAk: config.secretId,
  139. qKeyTime: qKeyTime,
  140. qSignature: qSignature,
  141. // securityToken: securityToken, // 如果使用临时密钥,要返回在这个资源 sessionToken 的值
  142. });
  143. });
  144. app.all('*', function (req, res, next) {
  145. res.send({code: -1, message: '404 Not Found'});
  146. });
  147. // 启动签名服务
  148. app.listen(3000);
  149. console.log('app is listening at http://127.0.0.1:3000');