跳到主要内容

Node.js 从 v20 到 v22

AugustinMauroy

Node.js v20 到 v22

!

本文介绍从 Node.js v20 迁移到 v22 的部分内容。userland migrations 团队正在开发更多 codemods,以帮助你完成 迁移。

本页提供了一个 codemods 列表,可帮助你将代码从 Node.js v20 迁移到 v22。

import-assertions-to-attributes

在 TC39 标准化过程中,引入了 import assert 特性以支持导入 JSON modules,但在过渡到 stage 4 时,assert 关键字被 import 语句上的 with 属性所取代。

因此,在 node.js v22 中,import assert 特性已被移除,改为必须使用 with 属性。

另请注意,with 关键字在 node.js v18.20 中引入,但直到 v22 才成为强制要求。

此 codemod 的源代码位于 import-assertions-to-attributes directory 中。

你可以在 Codemod Registry 中找到此 codemod。

示例:

- import data from './data.json' assert { type: 'json' };
+ import data from './data.json' with { type: 'json' };

crypto-createcipheriv-migration

将已弃用的 crypto.createCipher() / crypto.createDecipher() 用法迁移到受支持的 crypto.createCipheriv() / crypto.createDecipheriv() APIs,并采用显式的密钥派生和 IV 处理。

Node.js 在 v22.0.0 中移除了 crypto.createCipher() 和 crypto.createDecipher()(DEP0106)。旧的辅助函数使用 MD5 派生密钥且不使用盐,并且会静默重用静态 IV。此 codemod 将这些调用替换为现代的显式 APIs,并提供安全密钥派生和 IV 管理的脚手架代码。

此 codemod 的源代码位于 crypto-createcipheriv-migration directory 中。

你可以在 Codemod Registry 中找到此 codemod。

它会做什么

  • 将 createCipher() / createDecipher() 的调用替换为 createCipheriv() / createDecipheriv()。
  • 插入脚手架代码,使用 crypto.scryptSync() 派生密钥,并生成随机盐和 IV。
  • 提醒开发者为解密持久化保存盐 + IV,并根据算法调整密钥/IV 长度。
  • 更新解构导入,使其包含新的辅助函数(createCipheriv、createDecipheriv、randomBytes、scryptSync)。

示例

- const cipher = crypto.createCipher(algorithm, password);
+ const cipher = (() => {
+   const __dep0106Salt = crypto.randomBytes(16);
+   const __dep0106Key = crypto.scryptSync(password, __dep0106Salt, 32);
+   const __dep0106Iv = crypto.randomBytes(16);
+   // DEP0106: 将 __dep0106Salt 和 __dep0106Iv 与密文一起持久化,以便日后可解密。
+   return crypto.createCipheriv(algorithm, __dep0106Key, __dep0106Iv);
+ })();

重要注意事项

  • codemod 无法保证特定算法的密钥/IV 长度。请检查生成的 scryptSync 长度和 IV 长度默认值,并根据需要调整。
  • 解密代码片段包含占位符 (Buffer.alloc(16)),必须将其替换为加密时存储的 salt 和 IV。
  • 如果你的项目已经封装了密钥派生逻辑,你可能更倾向于调整生成的脚手架代码以调用现有的辅助函数。
  • 生成的代码不向后兼容,将无法解密使用 createCipher() 加密的数据。
  • 使用 scrypt 从密码派生密钥只是一种可能的选择,但你可能希望改用 Argon2id 或 PBKDF2。