diff --git a/package-lock.json b/package-lock.json index 944bf453..a4ac14c1 100644 --- a/package-lock.json +++ b/package-lock.json @@ -415,6 +415,7 @@ "resolved": "https://registry.npmjs.org/@babel/core/-/core-7.28.0.tgz", "integrity": "sha512-UlLAnTPrFdNGoFtbSXwcGFQBtQZJCNjaN6hQNP3UPvuNXT1i82N26KL3dZeIpNalWywr9IuQuncaAfUaS1g6sQ==", "license": "MIT", + "peer": true, "dependencies": { "@ampproject/remapping": "^2.2.0", "@babel/code-frame": "^7.27.1", @@ -1469,6 +1470,10 @@ "resolved": "recipes/create-require-from-path", "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 @@ -1551,6 +1556,7 @@ "resolved": "https://registry.npmjs.org/@octokit/core/-/core-5.2.2.tgz", "integrity": "sha512-/g2d4sW9nUDJOMz3mabVQvOGhVa4e/BN/Um7yca9Bb2XTzPPnfTWHWQg+IsEYO7M3Vx+EXvaM/I2pJWIMun1bg==", "license": "MIT", + "peer": true, "dependencies": { "@octokit/auth-token": "^4.0.0", "@octokit/graphql": "^7.1.0", @@ -2057,6 +2063,7 @@ } ], "license": "MIT", + "peer": true, "dependencies": { "caniuse-lite": "^1.0.30001733", "electron-to-chromium": "^1.5.199", @@ -4287,6 +4294,17 @@ "@codemod.com/jssg-types": "^1.0.9" } }, + "recipes/crypto-createcipheriv-migration": { + "name": "@nodejs/crypto-createcipheriv-migration", + "version": "1.0.0", + "license": "MIT", + "dependencies": { + "@nodejs/codemod-utils": "*" + }, + "devDependencies": { + "@codemod.com/jssg-types": "^1.0.9" + } + }, "recipes/crypto-fips": { "name": "@nodejs/crypto-fips", "version": "1.0.0", 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..2dc423b3 --- /dev/null +++ b/recipes/crypto-createcipheriv-migration/package.json @@ -0,0 +1,24 @@ +{ + "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": "*" + } +} diff --git a/recipes/crypto-createcipheriv-migration/src/workflow.ts b/recipes/crypto-createcipheriv-migration/src/workflow.ts new file mode 100644 index 00000000..e0fade88 --- /dev/null +++ b/recipes/crypto-createcipheriv-migration/src/workflow.ts @@ -0,0 +1,428 @@ +import { EOL } from 'node:os'; +import { + getNodeImportCalls, + getNodeImportStatements, +} from '@nodejs/codemod-utils/ast-grep/import-statement'; +import { getNodeRequireCalls } from '@nodejs/codemod-utils/ast-grep/require-call'; +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 StatementChange = { + rename: Map; + additions: Set; +}; + +type BindingEntry = { + property: string; + local: string; +}; + +type CollectParams = { + rootNode: SgNode; + statement: SgNode; + binding: string; + kind: CallKind; + edits: Edit[]; + statementChanges: Map, StatementChange>; + 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 statementChanges = new Map, StatementChange>(); + const seenCallRanges = new Set(); + + for (const statement of collectCryptoStatements(root)) { + const cipherBinding = safeResolveBinding(statement, '$.createCipher'); + if (cipherBinding) { + collectCallEdits({ + rootNode, + statement, + binding: cipherBinding, + kind: 'cipher', + edits, + statementChanges, + seenCallRanges, + }); + } + + const decipherBinding = safeResolveBinding(statement, '$.createDecipher'); + if (decipherBinding) { + collectCallEdits({ + rootNode, + statement, + binding: decipherBinding, + kind: 'decipher', + edits, + statementChanges, + seenCallRanges, + }); + } + } + + for (const [statement, change] of statementChanges) { + const edit = applyStatementChanges(statement, change); + if (edit) edits.push(edit); + } + + if (edits.length === 0) return null; + + return rootNode.commitEdits(edits); +} + +function collectCallEdits({ + rootNode, + statement, + binding, + kind, + edits, + statementChanges, + seenCallRanges, +}: CollectParams) { + 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 = + kind === 'cipher' + ? buildCipherReplacement({ + binding, + algorithm, + password, + options: optionsText, + }) + : buildDecipherReplacement({ + binding, + algorithm, + password, + options: optionsText, + }); + + edits.push(call.replace(replacement)); + + if (isDestructuredStatement(statement)) { + const change = ensureStatementChange(statementChanges, statement); + // Ensure the binding points to the iv-based API + const sourceName = kind === 'cipher' ? 'createCipher' : 'createDecipher'; + const targetName = `${sourceName}iv`; + change.rename.set(sourceName, targetName); + if (kind === 'cipher') { + change.additions.add('randomBytes'); + } + change.additions.add('scryptSync'); + } + } +} + +function buildCipherReplacement(params: { + binding: string; + algorithm: string; + password: string; + options?: string; +}): string { + const { binding, algorithm, password, options } = params; + const randomBytesCall = getMemberAccess(binding, 'randomBytes'); + const scryptCall = getMemberAccess(binding, 'scryptSync'); + const cipherCall = getCallableBinding(binding, 'createCipheriv'); + + const lines = [ + '(() => {', + `\tconst __dep0106Salt = ${randomBytesCall}(16);`, + '\tconst __dep0106Key = ' + + scryptCall + + '(' + + password + + ', __dep0106Salt, 32);', + `\tconst __dep0106Iv = ${randomBytesCall}(16);`, + '\t// DEP0106: Persist __dep0106Salt and __dep0106Iv with the ciphertext so it can be decrypted later.', + '\t// DEP0106: Adjust the derived key length (32 bytes) and IV length to match the chosen algorithm.', + '\treturn ' + + cipherCall + + '(' + + algorithm + + ', __dep0106Key, __dep0106Iv' + + (options ? `, ${options}` : '') + + ');', + '})()', + ]; + + return lines.join(EOL); +} + +function buildDecipherReplacement(params: { + binding: string; + algorithm: string; + password: string; + options?: string; +}): string { + const { binding, algorithm, password, options } = params; + const scryptCall = getMemberAccess(binding, 'scryptSync'); + const decipherCall = getCallableBinding(binding, 'createDecipheriv'); + + const lines = [ + '(() => {', + '\t// DEP0106: Replace the placeholders below with the salt and IV that were stored with the ciphertext.', + '\tconst __dep0106Salt = /* TODO: stored salt Buffer */ Buffer.alloc(16);', + '\tconst __dep0106Iv = /* TODO: stored IV Buffer */ Buffer.alloc(16);', + '\tconst __dep0106Key = ' + + scryptCall + + '(' + + password + + ', __dep0106Salt, 32);', + '\t// DEP0106: Ensure __dep0106Salt and __dep0106Iv match the values used during encryption.', + '\treturn ' + + decipherCall + + '(' + + algorithm + + ', __dep0106Key, __dep0106Iv' + + (options ? `, ${options}` : '') + + ');', + '})()', + ]; + + return lines.join(EOL); +} + +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 isDestructuredStatement(statement: SgNode): boolean { + return Boolean( + statement.find({ rule: { kind: 'object_pattern' } }) || + statement.find({ rule: { kind: 'named_imports' } }), + ); +} + +function ensureStatementChange( + statementChanges: Map, StatementChange>, + statement: SgNode, +): StatementChange { + let change = statementChanges.get(statement); + if (!change) { + change = { rename: new Map(), additions: new Set() }; + statementChanges.set(statement, change); + } + return change; +} + +function applyStatementChanges( + statement: SgNode, + change: StatementChange, +): Edit | undefined { + if (change.rename.size === 0 && change.additions.size === 0) { + return undefined; + } + + if ( + statement.kind() === 'import_statement' || + statement.kind() === 'import_clause' + ) { + return updateImportSpecifiers(statement, change); + } + + if (statement.find({ rule: { kind: 'object_pattern' } })) { + return updateRequirePattern(statement, change); + } + + return undefined; +} + +function updateImportSpecifiers( + statement: SgNode, + change: StatementChange, +): Edit | undefined { + const clause = + statement.kind() === 'import_clause' + ? statement + : statement.find({ rule: { kind: 'import_clause' } }); + if (!clause) return undefined; + + const namedImports = clause.find({ rule: { kind: 'named_imports' } }); + if (!namedImports) return undefined; + + const specNodes = namedImports.findAll({ + rule: { kind: 'import_specifier' }, + }); + if (specNodes.length === 0) return undefined; + + const entries: BindingEntry[] = specNodes.map((spec) => + parseImportSpecifier(spec.text()), + ); + let modified = false; + + for (const entry of entries) { + const newProperty = change.rename.get(entry.property); + if (newProperty && newProperty !== entry.property) { + entry.property = newProperty; + modified = true; + } + } + + for (const addition of change.additions) { + const exists = entries.some( + (entry) => entry.property === addition || entry.local === addition, + ); + if (!exists) { + entries.push({ property: addition, local: addition }); + modified = true; + } + } + + if (!modified) return undefined; + + const rendered = entries + .map((entry) => + entry.property === entry.local + ? entry.property + : `${entry.property} as ${entry.local}`, + ) + .join(', '); + + return namedImports.replace(`{ ${rendered} }`); +} + +function updateRequirePattern( + statement: SgNode, + change: StatementChange, +): Edit | undefined { + const objectPattern = statement.find({ rule: { kind: 'object_pattern' } }); + if (!objectPattern) return undefined; + + const specNodes = objectPattern.findAll({ + rule: { + any: [ + { kind: 'pair_pattern' }, + { kind: 'shorthand_property_identifier_pattern' }, + ], + }, + }); + if (specNodes.length === 0) return undefined; + + const entries: BindingEntry[] = specNodes.map((spec) => + parseRequireSpecifier(spec.text()), + ); + let modified = false; + + for (const entry of entries) { + const newProperty = change.rename.get(entry.property); + if (newProperty && newProperty !== entry.property) { + entry.property = newProperty; + modified = true; + } + } + + for (const addition of change.additions) { + const exists = entries.some( + (entry) => entry.property === addition || entry.local === addition, + ); + if (!exists) { + entries.push({ property: addition, local: addition }); + modified = true; + } + } + + if (!modified) return undefined; + + const rendered = entries + .map((entry) => + entry.property === entry.local + ? entry.property + : `${entry.property}: ${entry.local}`, + ) + .join(', '); + + return objectPattern.replace(`{ ${rendered} }`); +} + +function parseImportSpecifier(text: string): BindingEntry { + const parts = text + .split(/\s+as\s+/) + .map((value) => value.trim()) + .filter(Boolean); + if (parts.length === 2) { + return { property: parts[0], local: parts[1] }; + } + const name = parts[0] ?? text.trim(); + return { property: name, local: name }; +} + +function parseRequireSpecifier(text: string): BindingEntry { + const parts = text + .split(':') + .map((value) => value.trim()) + .filter(Boolean); + if (parts.length === 2) { + return { property: parts[0], local: parts[1] }; + } + const name = parts[0] ?? text.trim(); + return { property: name, local: name }; +} + +function collectCryptoStatements(root: SgRoot): SgNode[] { + return [ + ...getNodeImportStatements(root, 'crypto'), + ...getNodeImportCalls(root, 'crypto'), + ...getNodeRequireCalls(root, 'crypto'), + ]; +} + +function safeResolveBinding( + node: SgNode, + path: string, +): string | undefined { + try { + return resolveBindingPath(node, path) ?? undefined; + } catch { + return undefined; + } +} + +function getRangeKey(node: SgNode): string { + const range = node.range(); + return `${range.start.line}:${range.start.column}-${range.end.line}:${range.end.column}`; +} 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