diff --git a/package-lock.json b/package-lock.json index b778d696..30ae0747 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1496,6 +1496,10 @@ "resolved": "recipes/createCredentials-to-createSecureContext", "link": true }, + "node_modules/@nodejs/crypto-createcipheriv-migration": { + "resolved": "recipes/crypto-createcipheriv-migration", + "link": true + }, "node_modules/@nodejs/crypto-fips-to-getFips": { "resolved": "recipes/crypto-fips-to-getFips", "link": true @@ -2384,7 +2388,6 @@ "version": "1.7.1", "resolved": "https://registry.npmjs.org/dedent/-/dedent-1.7.1.tgz", "integrity": "sha512-9JmrhGZpOlEgOLdQgSm0zxFaYoQon408V1v49aqTWuXENVlnCuY9JBZcXZiCsZQWDjTm5Qf/nIvAy77mXDAjEg==", - "dev": true, "license": "MIT", "peerDependencies": { "babel-plugin-macros": "^3.1.0" @@ -4341,6 +4344,18 @@ "@codemod.com/jssg-types": "^1.3.1" } }, + "recipes/crypto-createcipheriv-migration": { + "name": "@nodejs/crypto-createcipheriv-migration", + "version": "1.0.0", + "license": "MIT", + "dependencies": { + "@nodejs/codemod-utils": "*", + "dedent": "^1.7.1" + }, + "devDependencies": { + "@codemod.com/jssg-types": "^1.0.9" + } + }, "recipes/crypto-fips-to-getFips": { "name": "@nodejs/crypto-fips-to-getFips", "version": "1.0.2", diff --git a/recipes/crypto-createcipheriv-migration/README.md b/recipes/crypto-createcipheriv-migration/README.md new file mode 100644 index 00000000..29ffb93f --- /dev/null +++ b/recipes/crypto-createcipheriv-migration/README.md @@ -0,0 +1,34 @@ +# crypto-createcipheriv-migration + +> Migrates deprecated `crypto.createCipher()` / `crypto.createDecipher()` usage to the supported `crypto.createCipheriv()` / `crypto.createDecipheriv()` APIs with explicit key derivation and IV handling. + +## Why? + +Node.js removed `crypto.createCipher()` and `crypto.createDecipher()` in v22.0.0 (DEP0106). The legacy helpers derived keys with MD5 and no salt, and silently reused static IVs. This codemod replaces those calls with the modern, explicit APIs and scaffolds secure key derivation and IV management. + +## What it does + +- Detects CommonJS and ESM imports of `crypto` (including destructured bindings). +- Replaces invocations of `createCipher()` / `createDecipher()` with `createCipheriv()` / `createDecipheriv()`. +- Inserts scaffolding that derives keys with `crypto.scryptSync()` and generates random salts and IVs. +- Reminds developers to persist salt + IV for decryption and to adjust key/IV lengths per algorithm. +- Updates destructured imports to include the new helpers (`createCipheriv`, `createDecipheriv`, `randomBytes`, `scryptSync`). + +## Example + +```diff +-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: Persist __dep0106Salt and __dep0106Iv alongside the ciphertext so it can be decrypted later. ++ return crypto.createCipheriv(algorithm, __dep0106Key, __dep0106Iv); ++})(); +``` + +## Caveats + +- The codemod cannot guarantee algorithm-specific key/IV sizes. Review the generated `scryptSync` length and IV length defaults and adjust as needed. +- Decryption snippets include placeholders (`Buffer.alloc(16)`) that must be replaced with the salt and IV stored during encryption. +- If your project already wraps key derivation logic, you may prefer to adapt the generated scaffolding to call existing helpers. diff --git a/recipes/crypto-createcipheriv-migration/codemod.yaml b/recipes/crypto-createcipheriv-migration/codemod.yaml new file mode 100644 index 00000000..055df724 --- /dev/null +++ b/recipes/crypto-createcipheriv-migration/codemod.yaml @@ -0,0 +1,22 @@ +schema_version: "1.0" +name: "@nodejs/crypto-createcipheriv-migration" +version: 1.0.0 +description: Replace removed `crypto.createCipher()`/`createDecipher()` with `crypto.createCipheriv()`/`createDecipheriv()` and secure key derivation (DEP0106) +author: Augustin Mauroy +license: MIT +workflow: workflow.yaml +category: migration + +targets: + languages: + - javascript + - typescript + +keywords: + - transformation + - migration + - crypto + +registry: + access: public + visibility: public diff --git a/recipes/crypto-createcipheriv-migration/package.json b/recipes/crypto-createcipheriv-migration/package.json new file mode 100644 index 00000000..cb9e4c7b --- /dev/null +++ b/recipes/crypto-createcipheriv-migration/package.json @@ -0,0 +1,25 @@ +{ + "name": "@nodejs/crypto-createcipheriv-migration", + "version": "1.0.0", + "description": "Migrate deprecated crypto.createCipher()/createDecipher() (DEP0106) to crypto.createCipheriv()/createDecipheriv() with secure key derivation.", + "type": "module", + "scripts": { + "test": "npx codemod jssg test -l typescript ./src/workflow.ts ./" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/nodejs/userland-migrations.git", + "directory": "recipes/crypto-createcipheriv-migration", + "bugs": "https://github.com/nodejs/userland-migrations/issues" + }, + "author": "Augustin Mauroy", + "license": "MIT", + "homepage": "https://github.com/nodejs/userland-migrations/blob/main/recipes/crypto-createcipheriv-migration/README.md", + "devDependencies": { + "@codemod.com/jssg-types": "^1.0.9" + }, + "dependencies": { + "@nodejs/codemod-utils": "*", + "dedent": "^1.7.1" + } +} diff --git a/recipes/crypto-createcipheriv-migration/src/workflow.ts b/recipes/crypto-createcipheriv-migration/src/workflow.ts new file mode 100644 index 00000000..caad4380 --- /dev/null +++ b/recipes/crypto-createcipheriv-migration/src/workflow.ts @@ -0,0 +1,324 @@ +import dedent from 'dedent'; +import { getModuleDependencies } from '@nodejs/codemod-utils/ast-grep/module-dependencies'; +import { resolveBindingPath } from '@nodejs/codemod-utils/ast-grep/resolve-binding-path'; +import type { Edit, SgNode, SgRoot } from '@codemod.com/jssg-types/main'; +import type Js from '@codemod.com/jssg-types/langs/javascript'; + +type CallKind = 'cipher' | 'decipher'; + +type CollectParams = { + rootNode: SgNode; + statement: SgNode; + binding: string; + kind: CallKind; + edits: Edit[]; + seenCallRanges: Set; +}; + +/** + * Transform deprecated crypto.createCipher()/createDecipher() usage to the + * supported crypto.createCipheriv()/createDecipheriv() APIs. + */ +export default function transform(root: SgRoot): string | null { + const rootNode = root.root(); + const edits: Edit[] = []; + const seenCallRanges = new Set(); + + const importStatements = getModuleDependencies(root, 'crypto'); + + if (!importStatements.length) return null; + + for (const statement of importStatements) { + const cipherBinding = resolveBindingPath(statement, '$.createCipher'); + collectCallEdits({ + rootNode, + statement, + binding: cipherBinding, + kind: 'cipher', + edits, + seenCallRanges, + }); + + const decipherBinding = resolveBindingPath(statement, '$.createDecipher'); + collectCallEdits({ + rootNode, + statement, + binding: decipherBinding, + kind: 'decipher', + edits, + seenCallRanges, + }); + } + + if (!edits.length) return null; + + return rootNode.commitEdits(edits); +} + +function collectCallEdits({ + rootNode, + statement, + binding, + kind, + edits, + seenCallRanges, +}: CollectParams) { + if (!binding || binding === '') return; + + const patterns = [ + `${binding}($ALGORITHM, $PASSWORD, $OPTIONS)`, + `${binding}($ALGORITHM, $PASSWORD)`, + ]; + + const calls = rootNode.findAll({ + rule: { + any: patterns.map((pattern) => ({ pattern })), + kind: 'call_expression', + }, + }); + + for (const call of calls) { + const rangeKey = getRangeKey(call); + if (seenCallRanges.has(rangeKey)) continue; + seenCallRanges.add(rangeKey); + + const algorithmNode = call.getMatch('ALGORITHM'); + const passwordNode = call.getMatch('PASSWORD'); + + if (!algorithmNode || !passwordNode) continue; + + const algorithm = algorithmNode.text().trim(); + const password = passwordNode.text().trim(); + if (!algorithm || !password) continue; + + const optionsText = call.getMatch('OPTIONS')?.text()?.trim(); + + const replacement = buildDeCipherReplacement( + { + binding, + algorithm, + password, + options: optionsText, + }, + kind, + ); + edits.push(call.replace(replacement)); + + // Update the corresponding import/require binding if present. + // Rename `createCipher`/`createDecipher` -> `createCipheriv`/`createDecipheriv` + // and add helper bindings (`scryptSync`, and `randomBytes` for cipher). + const sourceName = kind === 'cipher' ? 'createCipher' : 'createDecipher'; + const targetName = `${sourceName}iv`; + + const additions: string[] = + kind === 'cipher' ? ['randomBytes', 'scryptSync'] : ['scryptSync']; + + // Preserve any local alias (e.g. `createCipher: makeCipher`) by + // constructing a property:local string for the renamed binding. + const local = findLocalSpecifierName(statement, sourceName); + + // Prefer an explicit update for destructured/named imports when + // present so we can preserve aliasing and ordering exactly. + const explicit = updateDestructuredStatement( + statement, + sourceName, + targetName, + local, + additions, + ); + + if (explicit) { + edits.push(explicit); + } + } +} + +function buildDeCipherReplacement( + { + binding, + algorithm, + password, + options, + }: { + binding: string; + algorithm: string; + password: string; + options?: string; + }, + kind: 'decipher' | 'cipher', +): string { + const scryptCall = getMemberAccess(binding, 'scryptSync'); + const method = getCallableBinding( + binding, + kind === 'cipher' ? 'createCipheriv' : 'createDecipheriv', + ); + + if (kind === 'cipher') { + const randomBytesCall = getMemberAccess(binding, 'randomBytes'); + return dedent(` + (() => { + const __dep0106Salt = ${randomBytesCall}(16); + const __dep0106Key = ${scryptCall}(${password}, __dep0106Salt, 32); + const __dep0106Iv = ${randomBytesCall}(16); + // DEP0106: Persist __dep0106Salt and __dep0106Iv with the ciphertext so it can be decrypted later. + // DEP0106: Adjust the derived key length (32 bytes) and IV length to match the chosen algorithm. + return ${method}(${algorithm}, __dep0106Key, __dep0106Iv${options ? `, ${options}` : ''}); + })() + `); + } + + return dedent(` + (() => { + // DEP0106: Replace the placeholders below with the salt and IV that were stored with the ciphertext. + const __dep0106Salt = /* TODO: stored salt Buffer */ Buffer.alloc(16); + const __dep0106Iv = /* TODO: stored IV Buffer */ Buffer.alloc(16); + const __dep0106Key = ${scryptCall}(${password}, __dep0106Salt, 32); + // DEP0106: Ensure __dep0106Salt and __dep0106Iv match the values used during encryption. + return ${method}(${algorithm}, __dep0106Key, __dep0106Iv${options ? `, ${options}` : ''}); + })() +`); +} + +function getCallableBinding(binding: string, target: string): string { + const lastDot = binding.lastIndexOf('.'); + if (lastDot === -1) { + return binding; + } + return `${binding.slice(0, lastDot)}.${target}`; +} + +function getMemberAccess(binding: string, member: string): string { + const lastDot = binding.lastIndexOf('.'); + if (lastDot === -1) { + return member; + } + return `${binding.slice(0, lastDot)}.${member}`; +} + +function updateDestructuredStatement( + statement: SgNode, + oldName: string, + targetName: string, + localName: string | undefined, + additions: string[], +): Edit | undefined { + let namedImports = statement.find({ rule: { kind: 'named_imports' } }); + if (!namedImports) { + const clause = statement.find({ rule: { kind: 'import_clause' } }); + if (clause) namedImports = clause.find({ rule: { kind: 'named_imports' } }); + } + if (namedImports) { + const isEsm = namedImports.parent()?.kind() === 'import_clause'; + + // Work on textual specifiers to preserve formatting and order. + const content = namedImports.text().replace(/^{\s*|\s*}$/g, ''); + const parts = content + .split(',') + .map((p) => p.trim()) + .filter(Boolean); + const entries: string[] = parts.map((p) => { + if ( + new RegExp(`^${escapeRegExp(oldName)}(\\b|\\s|:|\\s+as\\b)`).test(p) + ) { + const local = localName ?? oldName; + return isEsm ? `${targetName} as ${local}` : `${targetName}: ${local}`; + } + return p; + }); + + for (const a of additions) { + if (!entries.some((e) => new RegExp(`\\b${escapeRegExp(a)}\\b`).test(e))) + entries.push(a); + } + return namedImports.replace(`{ ${entries.join(', ')} }`); + } + + const objectPattern = statement.find({ rule: { kind: 'object_pattern' } }); + if (objectPattern) { + const pairs = objectPattern.findAll({ + rule: { + any: [ + { kind: 'pair_pattern' }, + { kind: 'shorthand_property_identifier_pattern' }, + ], + }, + }); + if (pairs.length === 0) return undefined; + + const entries: string[] = []; + for (const p of pairs) { + if (p.kind() === 'pair_pattern') { + const key = p.find({ rule: { kind: 'property_identifier' } }); + const value = p.children().find((c) => c.kind() === 'identifier'); + const prop = key.text(); + const local = value.text() ?? prop; + + const localToUse = localName ?? local; + entries.push(`${targetName}: ${localToUse}`); + } else { + const text = p.text(); + + if (text === oldName) { + const local = text; + const localToUse = localName ?? local; + entries.push(`${targetName}: ${localToUse}`); + } + } + } + + for (const a of additions) { + if (!entries.some((e) => e.includes(a))) entries.push(a); + } + + return objectPattern.replace(`{ ${entries.join(', ')} }`); + } + + return undefined; +} + +function escapeRegExp(str: string): string { + return str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); +} + +function getRangeKey(node: SgNode): string { + const range = node.range(); + return `${range.start.line}:${range.start.column}-${range.end.line}:${range.end.column}`; +} + +function findLocalSpecifierName( + statement: SgNode, + propertyName: string, +): string | undefined { + // pair_pattern: { prop: local } + const pairs = statement.findAll({ rule: { kind: 'pair_pattern' } }); + for (const pair of pairs) { + const key = pair.find({ rule: { kind: 'property_identifier' } }); + + if (key && key.text() === propertyName) { + const value = pair.children().find((c) => c.kind() === 'identifier'); + if (value) return value.text(); + } + } + + // import_specifier: { name, alias } + const specs = statement.findAll({ rule: { kind: 'import_specifier' } }); + for (const s of specs) { + const nameNode = s.field?.('name'); + const aliasNode = s.field?.('alias'); + const idNode = s.find({ rule: { kind: 'identifier' } }); + const prop = nameNode?.text() || idNode?.text(); + + if (prop && prop === propertyName) { + if (aliasNode) return aliasNode.text(); + return prop; + } + } + + // shorthand destructure + const sh = statement.find({ + rule: { kind: 'shorthand_property_identifier_pattern' }, + }); + if (sh && sh.text() === propertyName) return propertyName; + + return undefined; +} diff --git a/recipes/crypto-createcipheriv-migration/tests/expected/commonjs-alias.js b/recipes/crypto-createcipheriv-migration/tests/expected/commonjs-alias.js new file mode 100644 index 00000000..f7f41d99 --- /dev/null +++ b/recipes/crypto-createcipheriv-migration/tests/expected/commonjs-alias.js @@ -0,0 +1,12 @@ +const { createCipheriv: makeCipher, randomBytes, scryptSync } = require("node:crypto"); + +function wrap(password) { + return (() => { + const __dep0106Salt = randomBytes(16); + const __dep0106Key = scryptSync(password, __dep0106Salt, 32); + const __dep0106Iv = randomBytes(16); + // DEP0106: Persist __dep0106Salt and __dep0106Iv with the ciphertext so it can be decrypted later. + // DEP0106: Adjust the derived key length (32 bytes) and IV length to match the chosen algorithm. + return makeCipher("aes-192-cbc", __dep0106Key, __dep0106Iv); +})(); +} diff --git a/recipes/crypto-createcipheriv-migration/tests/expected/commonjs-decipher-destructured.js b/recipes/crypto-createcipheriv-migration/tests/expected/commonjs-decipher-destructured.js new file mode 100644 index 00000000..68cb18d1 --- /dev/null +++ b/recipes/crypto-createcipheriv-migration/tests/expected/commonjs-decipher-destructured.js @@ -0,0 +1,10 @@ +const { createDecipheriv: createDecipher, scryptSync } = require("node:crypto"); + +const decipher = (() => { + // DEP0106: Replace the placeholders below with the salt and IV that were stored with the ciphertext. + const __dep0106Salt = /* TODO: stored salt Buffer */ Buffer.alloc(16); + const __dep0106Iv = /* TODO: stored IV Buffer */ Buffer.alloc(16); + const __dep0106Key = scryptSync("secret", __dep0106Salt, 32); + // DEP0106: Ensure __dep0106Salt and __dep0106Iv match the values used during encryption. + return createDecipher("aes-192-cbc", __dep0106Key, __dep0106Iv); +})(); diff --git a/recipes/crypto-createcipheriv-migration/tests/expected/commonjs-decipher-namespace.js b/recipes/crypto-createcipheriv-migration/tests/expected/commonjs-decipher-namespace.js new file mode 100644 index 00000000..299735b5 --- /dev/null +++ b/recipes/crypto-createcipheriv-migration/tests/expected/commonjs-decipher-namespace.js @@ -0,0 +1,10 @@ +const crypto = require("crypto"); + +const decipher = (() => { + // DEP0106: Replace the placeholders below with the salt and IV that were stored with the ciphertext. + const __dep0106Salt = /* TODO: stored salt Buffer */ Buffer.alloc(16); + const __dep0106Iv = /* TODO: stored IV Buffer */ Buffer.alloc(16); + const __dep0106Key = crypto.scryptSync("pw", __dep0106Salt, 32); + // DEP0106: Ensure __dep0106Salt and __dep0106Iv match the values used during encryption. + return crypto.createDecipheriv("aes-256-cbc", __dep0106Key, __dep0106Iv); +})(); diff --git a/recipes/crypto-createcipheriv-migration/tests/expected/commonjs-destructured.js b/recipes/crypto-createcipheriv-migration/tests/expected/commonjs-destructured.js new file mode 100644 index 00000000..a145d728 --- /dev/null +++ b/recipes/crypto-createcipheriv-migration/tests/expected/commonjs-destructured.js @@ -0,0 +1,10 @@ +const { createCipheriv: createCipher, randomBytes, scryptSync } = require("node:crypto"); + +const cipher = (() => { + const __dep0106Salt = randomBytes(16); + const __dep0106Key = scryptSync("password123", __dep0106Salt, 32); + const __dep0106Iv = randomBytes(16); + // DEP0106: Persist __dep0106Salt and __dep0106Iv with the ciphertext so it can be decrypted later. + // DEP0106: Adjust the derived key length (32 bytes) and IV length to match the chosen algorithm. + return createCipher("aes-128-cbc", __dep0106Key, __dep0106Iv); +})(); diff --git a/recipes/crypto-createcipheriv-migration/tests/expected/commonjs-namespace.js b/recipes/crypto-createcipheriv-migration/tests/expected/commonjs-namespace.js new file mode 100644 index 00000000..fe64a8c0 --- /dev/null +++ b/recipes/crypto-createcipheriv-migration/tests/expected/commonjs-namespace.js @@ -0,0 +1,12 @@ +const crypto = require("node:crypto"); + +const algorithm = "aes-256-cbc"; +const password = "s3cret"; +const cipher = (() => { + const __dep0106Salt = crypto.randomBytes(16); + const __dep0106Key = crypto.scryptSync(password, __dep0106Salt, 32); + const __dep0106Iv = crypto.randomBytes(16); + // DEP0106: Persist __dep0106Salt and __dep0106Iv with the ciphertext so it can be decrypted later. + // DEP0106: Adjust the derived key length (32 bytes) and IV length to match the chosen algorithm. + return crypto.createCipheriv(algorithm, __dep0106Key, __dep0106Iv); +})(); diff --git a/recipes/crypto-createcipheriv-migration/tests/expected/commonjs-options.js b/recipes/crypto-createcipheriv-migration/tests/expected/commonjs-options.js new file mode 100644 index 00000000..1d9594f9 --- /dev/null +++ b/recipes/crypto-createcipheriv-migration/tests/expected/commonjs-options.js @@ -0,0 +1,10 @@ +const crypto = require("node:crypto"); + +const cipher = (() => { + const __dep0106Salt = crypto.randomBytes(16); + const __dep0106Key = crypto.scryptSync("pw", __dep0106Salt, 32); + const __dep0106Iv = crypto.randomBytes(16); + // DEP0106: Persist __dep0106Salt and __dep0106Iv with the ciphertext so it can be decrypted later. + // DEP0106: Adjust the derived key length (32 bytes) and IV length to match the chosen algorithm. + return crypto.createCipheriv("aes-256-cbc", __dep0106Key, __dep0106Iv, { authTagLength: 16 }); +})(); diff --git a/recipes/crypto-createcipheriv-migration/tests/expected/esm-named-decipher.js b/recipes/crypto-createcipheriv-migration/tests/expected/esm-named-decipher.js new file mode 100644 index 00000000..e8fcb85f --- /dev/null +++ b/recipes/crypto-createcipheriv-migration/tests/expected/esm-named-decipher.js @@ -0,0 +1,10 @@ +import { createDecipheriv as createDecipher, scryptSync } from "node:crypto"; + +const decrypted = (() => { + // DEP0106: Replace the placeholders below with the salt and IV that were stored with the ciphertext. + const __dep0106Salt = /* TODO: stored salt Buffer */ Buffer.alloc(16); + const __dep0106Iv = /* TODO: stored IV Buffer */ Buffer.alloc(16); + const __dep0106Key = scryptSync("secret", __dep0106Salt, 32); + // DEP0106: Ensure __dep0106Salt and __dep0106Iv match the values used during encryption. + return createDecipher("aes-192-cbc", __dep0106Key, __dep0106Iv); +})(); diff --git a/recipes/crypto-createcipheriv-migration/tests/expected/esm-namespace.js b/recipes/crypto-createcipheriv-migration/tests/expected/esm-namespace.js new file mode 100644 index 00000000..50221891 --- /dev/null +++ b/recipes/crypto-createcipheriv-migration/tests/expected/esm-namespace.js @@ -0,0 +1,10 @@ +import crypto from "node:crypto"; + +const encrypted = (() => { + const __dep0106Salt = crypto.randomBytes(16); + const __dep0106Key = crypto.scryptSync("pw", __dep0106Salt, 32); + const __dep0106Iv = crypto.randomBytes(16); + // DEP0106: Persist __dep0106Salt and __dep0106Iv with the ciphertext so it can be decrypted later. + // DEP0106: Adjust the derived key length (32 bytes) and IV length to match the chosen algorithm. + return crypto.createCipheriv("aes-256-cbc", __dep0106Key, __dep0106Iv); +})(); diff --git a/recipes/crypto-createcipheriv-migration/tests/input/commonjs-alias.js b/recipes/crypto-createcipheriv-migration/tests/input/commonjs-alias.js new file mode 100644 index 00000000..3e6a6fb1 --- /dev/null +++ b/recipes/crypto-createcipheriv-migration/tests/input/commonjs-alias.js @@ -0,0 +1,5 @@ +const { createCipher: makeCipher } = require("node:crypto"); + +function wrap(password) { + return makeCipher("aes-192-cbc", password); +} diff --git a/recipes/crypto-createcipheriv-migration/tests/input/commonjs-decipher-destructured.js b/recipes/crypto-createcipheriv-migration/tests/input/commonjs-decipher-destructured.js new file mode 100644 index 00000000..ece9f3e3 --- /dev/null +++ b/recipes/crypto-createcipheriv-migration/tests/input/commonjs-decipher-destructured.js @@ -0,0 +1,3 @@ +const { createDecipher } = require("node:crypto"); + +const decipher = createDecipher("aes-192-cbc", "secret"); diff --git a/recipes/crypto-createcipheriv-migration/tests/input/commonjs-decipher-namespace.js b/recipes/crypto-createcipheriv-migration/tests/input/commonjs-decipher-namespace.js new file mode 100644 index 00000000..abe937d7 --- /dev/null +++ b/recipes/crypto-createcipheriv-migration/tests/input/commonjs-decipher-namespace.js @@ -0,0 +1,3 @@ +const crypto = require("crypto"); + +const decipher = crypto.createDecipher("aes-256-cbc", "pw"); diff --git a/recipes/crypto-createcipheriv-migration/tests/input/commonjs-destructured.js b/recipes/crypto-createcipheriv-migration/tests/input/commonjs-destructured.js new file mode 100644 index 00000000..aafc9e44 --- /dev/null +++ b/recipes/crypto-createcipheriv-migration/tests/input/commonjs-destructured.js @@ -0,0 +1,3 @@ +const { createCipher } = require("node:crypto"); + +const cipher = createCipher("aes-128-cbc", "password123"); diff --git a/recipes/crypto-createcipheriv-migration/tests/input/commonjs-namespace.js b/recipes/crypto-createcipheriv-migration/tests/input/commonjs-namespace.js new file mode 100644 index 00000000..b4273c2e --- /dev/null +++ b/recipes/crypto-createcipheriv-migration/tests/input/commonjs-namespace.js @@ -0,0 +1,5 @@ +const crypto = require("node:crypto"); + +const algorithm = "aes-256-cbc"; +const password = "s3cret"; +const cipher = crypto.createCipher(algorithm, password); diff --git a/recipes/crypto-createcipheriv-migration/tests/input/commonjs-options.js b/recipes/crypto-createcipheriv-migration/tests/input/commonjs-options.js new file mode 100644 index 00000000..84838491 --- /dev/null +++ b/recipes/crypto-createcipheriv-migration/tests/input/commonjs-options.js @@ -0,0 +1,3 @@ +const crypto = require("node:crypto"); + +const cipher = crypto.createCipher("aes-256-cbc", "pw", { authTagLength: 16 }); diff --git a/recipes/crypto-createcipheriv-migration/tests/input/esm-named-decipher.js b/recipes/crypto-createcipheriv-migration/tests/input/esm-named-decipher.js new file mode 100644 index 00000000..ea789113 --- /dev/null +++ b/recipes/crypto-createcipheriv-migration/tests/input/esm-named-decipher.js @@ -0,0 +1,3 @@ +import { createDecipher } from "node:crypto"; + +const decrypted = createDecipher("aes-192-cbc", "secret"); diff --git a/recipes/crypto-createcipheriv-migration/tests/input/esm-namespace.js b/recipes/crypto-createcipheriv-migration/tests/input/esm-namespace.js new file mode 100644 index 00000000..d88a788d --- /dev/null +++ b/recipes/crypto-createcipheriv-migration/tests/input/esm-namespace.js @@ -0,0 +1,3 @@ +import crypto from "node:crypto"; + +const encrypted = crypto.createCipher("aes-256-cbc", "pw"); diff --git a/recipes/crypto-createcipheriv-migration/workflow.yaml b/recipes/crypto-createcipheriv-migration/workflow.yaml new file mode 100644 index 00000000..5bbe7e92 --- /dev/null +++ b/recipes/crypto-createcipheriv-migration/workflow.yaml @@ -0,0 +1,25 @@ +# yaml-language-server: $schema=https://raw.githubusercontent.com/codemod-com/codemod/refs/heads/main/schemas/workflow.json + +version: "1" + +nodes: + - id: apply-transforms + name: Apply AST Transformations + type: automatic + steps: + - name: Migrate `crypto.createCipher()`/`createDecipher()` to iv variants with secure key derivation. + js-ast-grep: + js_file: src/workflow.ts + base_path: . + include: + - "**/*.js" + - "**/*.jsx" + - "**/*.mjs" + - "**/*.cjs" + - "**/*.cts" + - "**/*.mts" + - "**/*.ts" + - "**/*.tsx" + exclude: + - "**/node_modules/**" + language: typescript diff --git a/utils/src/ast-grep/update-binding.test.ts b/utils/src/ast-grep/update-binding.test.ts index bb1e1b07..5fd5fef9 100644 --- a/utils/src/ast-grep/update-binding.test.ts +++ b/utils/src/ast-grep/update-binding.test.ts @@ -985,7 +985,7 @@ describe('update-binding', () => { assert.notEqual(change, undefined); assert.strictEqual(change?.lineToRemove, undefined); - const sourceCode = node.commitEdits([change!.edit!]); + const sourceCode = node.commitEdits([change.edit!]); assert.strictEqual( sourceCode,