You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

VSCode扩展中SecretStorage安全使用及密钥方案咨询

VSCode扩展SecretStorage固定密钥的安全问题解析

固定密钥的泄露风险

哪怕你不对外公开源码,固定密钥依然有很高的泄露风险:

  • VSCode扩展最终会打包成.vsix格式,本质就是个ZIP压缩包,任何人都能解压拿到里面的编译后代码(哪怕是混淆过的JS,也能通过工具还原出密钥逻辑)。
  • 只要有人拿到你的扩展包,就能直接从代码里抠出AzureDevOpsPAT这个固定密钥,接着用VSCode的SecretStorage API读取存储的机密值。
  • 另外,要是你的开发环境被入侵、私有代码仓库权限失控,密钥也会直接暴露。

更安全的实现方案

1. 让用户自定义密钥

别硬编码固定密钥,改成让用户在扩展的设置面板里自行配置一个唯一标识(比如自定义密钥、用户专属ID),用这个标识作为SecretStorage的访问密钥:

// 读取用户配置的自定义密钥
const customSecretKey = vscode.workspace.getConfiguration('yourExtension').get<string>('secretAccessKey');
if (customSecretKey) {
  const storedPAT = await context.secrets.get(customSecretKey);
}

这种方式下,只有知道用户自定义密钥的人才能访问对应机密,就算扩展代码被拿到,也没法直接获取密钥。

2. 绑定机器/会话身份

利用VSCode提供的vscode.env.machineId(机器唯一标识)或vscode.env.sessionId(当前会话ID)作为密钥的一部分,让机密和特定机器或会话绑定:

const machineBoundKey = `AzureDevOpsPAT_${vscode.env.machineId}`;
const storedPAT = await context.secrets.get(machineBoundKey);

这样一来,就算代码泄露,其他机器也读取不了当前机器存储的机密值。

3. 双重加密存储机密

就算要用固定密钥,也可以对要存储的机密值额外做一次加密,加密密钥可以基于用户输入或机器硬件信息生成(比如用机器ID生成哈希值作为加密密钥):

import * as crypto from 'crypto';

// 基于机器ID生成AES加密密钥
const generateEncryptionKey = () => {
  return crypto.createHash('sha256').update(vscode.env.machineId).digest('hex');
};

// 加密函数
const encryptSecret = (secret: string, key: string) => {
  const iv = crypto.randomBytes(16);
  const cipher = crypto.createCipheriv('aes-256-cbc', Buffer.from(key, 'hex'), iv);
  let encrypted = cipher.update(secret);
  encrypted = Buffer.concat([encrypted, cipher.final()]);
  return `${iv.toString('hex')}:${encrypted.toString('hex')}`;
};

// 解密函数
const decryptSecret = (encryptedSecret: string, key: string) => {
  const [ivHex, encryptedHex] = encryptedSecret.split(':');
  const iv = Buffer.from(ivHex, 'hex');
  const encryptedData = Buffer.from(encryptedHex, 'hex');
  const decipher = crypto.createDecipheriv('aes-256-cbc', Buffer.from(key, 'hex'), iv);
  let decrypted = decipher.update(encryptedData);
  decrypted = Buffer.concat([decrypted, decipher.final()]);
  return decrypted.toString();
};

// 使用示例:加密后存储
const userPAT = 'your-azure-devops-pat';
const encryptionKey = generateEncryptionKey();
const encryptedPAT = encryptSecret(userPAT, encryptionKey);
await context.secrets.store('AzureDevOpsPAT', encryptedPAT);

总结

固定密钥的方案安全性极差,不管代码是否公开都存在严重泄露风险,强烈建议采用用户自定义密钥或绑定机器身份的方案,在此基础上结合双重加密能进一步提升机密的安全性。

内容的提问来源于stack exchange,提问作者dekanutyan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.08 18:45:39