Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

51 changes: 51 additions & 0 deletions recipes/crypto-hmac-digest-redundant/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
---
authors: vishalrajofficial
---

# DEP0206: Remove Provably Redundant `Hmac.digest()` Calls

Removes redundant, standalone argument-free `hmac.digest()` expression statements on already-finalized Hmac instances created through `crypto.createHmac()`. Supports CommonJS and ESM imports, aliases, and both `crypto` and `node:crypto` specifiers. See [DEP0206](https://nodejs.org/api/deprecations.html#DEP0206).

## Usage

Run this codemod with:

```sh
npx codemod @nodejs/crypto-hmac-digest-redundant
```

## Examples

### Example 1

Adjacent redundant `hmac.digest()` call after finalizing the instance:

```diff
import { createHmac } from 'node:crypto';

const hmac = createHmac('sha256', 'secret');
hmac.update('message');
const digest = hmac.digest('hex');
-hmac.digest();
console.log(digest);
```

### Example 2

CommonJS and aliased `createHmac` with standalone calls:

```diff
const { createHmac: makeHmac } = require('node:crypto');

const hmac = makeHmac('sha256', 'secret');
hmac.digest('hex');
-hmac.digest();
```

## Notes

### Limitations

- Only argument-free `hmac.digest()` calls on stable, unescaped local bindings in straight-line code are automatically removed.
- Calls where the return value is consumed (e.g. assigned to a variable or passed as an argument) are left unchanged for manual review, as reusing the first digest changes behavior.
- Repeated calls with arguments or calls occurring across different branches are not modified.
25 changes: 25 additions & 0 deletions recipes/crypto-hmac-digest-redundant/codemod.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
schema_version: "1.0"
name: "@nodejs/crypto-hmac-digest-redundant"
version: "1.0.0"
description: Handle DEP0206 by removing redundant, argument-free Hmac.digest() calls on finalized instances.
author: Vishal Raj
license: MIT
workflow: workflow.yaml
category: migration
repository: https://github.com/nodejs/userland-migrations

targets:
languages:
- javascript
- typescript

keywords:
- transformation
- migration
- nodejs
- DEP0206
- crypto

registry:
access: public
visibility: public
13 changes: 13 additions & 0 deletions recipes/crypto-hmac-digest-redundant/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
{
"name": "@nodejs/crypto-hmac-digest-redundant",
"type": "module",
"scripts": {
"test": "npx codemod jssg test -l typescript ./src/workflow.ts"
},
"devDependencies": {
"@codemod.com/jssg-types": "^1.6.3"
},
"dependencies": {
"@nodejs/codemod-utils": "*"
}
}
208 changes: 208 additions & 0 deletions recipes/crypto-hmac-digest-redundant/src/workflow.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,208 @@
import type { Range, SgNode, SgRoot } from '@codemod.com/jssg-types/main';
import type Js from '@codemod.com/jssg-types/langs/javascript';
import { getModuleDependencies } from '@nodejs/codemod-utils/ast-grep/module-dependencies';
import { resolveBindingPath } from '@nodejs/codemod-utils/ast-grep/resolve-binding-path';
import { removeLines } from '@nodejs/codemod-utils/ast-grep/remove-lines';
import { getScope } from '@nodejs/codemod-utils/ast-grep/get-scope';

const BRANCH_KINDS = [
'if_statement',
'for_statement',
'for_in_statement',
'while_statement',
'do_statement',
'switch_statement',
'try_statement',
] as const;

/**
* Transforms code by removing provably redundant argument-free Hmac.digest() calls
* on already-finalized Hmac instances (DEP0206).
*/
export default function transform(root: SgRoot<Js>): string | null {
const rootNode = root.root();
const cryptoDeps = getModuleDependencies(root, 'crypto');
if (!cryptoDeps.length) return null;

const createHmacCallees = new Set<string>();
for (const dep of cryptoDeps) {
Comment thread
vishalrajofficial marked this conversation as resolved.
Resolved

const resolved = resolveBindingPath(dep, '$.createHmac');
if (resolved) {
createHmacCallees.add(resolved);
}
}

if (!createHmacCallees.size) return null;

const linesToRemove: Range[] = [];
const declarators = rootNode.findAll({
rule: { kind: 'variable_declarator' },
});

for (const decl of declarators) {
const nameNode = decl.field('name');
const valueNode = decl.field('value');

if (
!nameNode?.is('identifier') ||
!valueNode?.is('call_expression')
) {
continue;
}

const fnNode = valueNode.field('function');
if (!fnNode || !createHmacCallees.has(fnNode.text())) {
continue;
}

const hmacName = nameNode.text();
const scopeNode = getScope(decl);
if (!scopeNode) continue;

if (!isSafeHmac(decl, hmacName, scopeNode)) {
continue;
}

const redundantStmts = findRedundantCalls(scopeNode, decl, hmacName);
for (const stmt of redundantStmts) {
linesToRemove.push(stmt.range());
}
}

if (!linesToRemove.length) return null;

return removeLines(rootNode.text(), linesToRemove);
}

function isSafeHmac(
declNode: SgNode<Js>,
hmacName: string,
scopeNode: SgNode<Js>,
): boolean {
// 1. Check for reassignments to hmacName or property mutations on hmacName
const assignments = scopeNode.findAll({
rule: { kind: 'assignment_expression' },
});

for (const assign of assignments) {
const left = assign.field('left');
if (left?.is('identifier') && left.text() === hmacName) {
return false;
}
if (
left?.is('member_expression') &&
left.field('object')?.text() === hmacName
) {
return false;
}
}

// 2. Check for update expressions (e.g. hmac++)
const updates = scopeNode.findAll({ rule: { kind: 'update_expression' } });
for (const update of updates) {
if (update.field('argument')?.text() === hmacName) {
return false;
}
}

// 3. Check all identifier occurrences to verify hmac does not escape
const identifiers = scopeNode.findAll({
rule: {
kind: 'identifier',
pattern: hmacName,
},
});

const declNameId = declNode.field('name')?.id();

for (const id of identifiers) {
if (id.id() === declNameId) continue;

const parent = id.parent();
if (
parent?.is('member_expression') &&
parent.field('object')?.id() === id.id()
) {
const prop = parent.field('property')?.text();
if (prop !== 'update' && prop !== 'digest') {
return false;
}

const grandParent = parent.parent();
if (
grandParent?.kind() === 'call_expression' &&
grandParent.field('function')?.id() === parent.id()
) {
continue;
}

return false;
}

return false;
}

return true;
}

function findRedundantCalls(
scopeNode: SgNode<Js>,
declNode: SgNode<Js>,
hmacName: string,
): SgNode<Js>[] {
const declLine = declNode.range().start.line;
const statements = scopeNode.children().filter((c) => {
const k = c.kind();
return k.endsWith('_statement') || k.endsWith('_declaration');
});

let finalized = false;
const redundant: SgNode<Js>[] = [];

for (const stmt of statements) {
if (stmt.range().start.line <= declLine) continue;

const hasBranch =
BRANCH_KINDS.some((k) => k === stmt.kind()) ||
stmt.find({
rule: {
any: BRANCH_KINDS.map((k) => ({ kind: k })),
},
});

if (hasBranch) {
const referencesHmac = stmt.find({
rule: { kind: 'identifier', pattern: hmacName },
});
if (referencesHmac) {
return [];
}
}

const digestCalls = stmt.findAll({
rule: {
pattern: `${hmacName}.digest($$$ARGS)`,
},
});

if (digestCalls.length === 0) continue;

for (const call of digestCalls) {
if (!finalized) {
finalized = true;
} else {
const isStandaloneExpr = stmt.kind() === 'expression_statement';
const args = call.field('arguments');
const isArgFree =
args?.children().length === 2 || args?.text().trim() === '()';

if (isStandaloneExpr && isArgFree) {
redundant.push(stmt);
}
}
}
}

return redundant;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
import { createHmac } from 'node:crypto';

const hmac = createHmac('sha256', 'secret');
hmac.update('message');
const digest = hmac.digest('hex');
console.log(digest);
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import { createHmac } from 'node:crypto';

const hmac = createHmac('sha256', 'secret');
hmac.update('message');
const digest = hmac.digest('hex');
hmac.digest();
console.log(digest);
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
import { createHmac as myHmac } from 'crypto';

const hmac = myHmac('sha256', 'secret');
const digest = hmac.digest('hex');
5 changes: 5 additions & 0 deletions recipes/crypto-hmac-digest-redundant/tests/aliases/input.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import { createHmac as myHmac } from 'crypto';

const hmac = myHmac('sha256', 'secret');
const digest = hmac.digest('hex');
hmac.digest();
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
import { createHmac } from 'node:crypto';

const hmac = createHmac('sha256', 'secret');
if (condition) {
hmac.digest('hex');
} else {
hmac.digest();
}
8 changes: 8 additions & 0 deletions recipes/crypto-hmac-digest-redundant/tests/branches/input.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
import { createHmac } from 'node:crypto';

const hmac = createHmac('sha256', 'secret');
if (condition) {
hmac.digest('hex');
} else {
hmac.digest();
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
const crypto = require('node:crypto');

const hmac = crypto.createHmac('sha256', 'secret');
hmac.digest('hex');
5 changes: 5 additions & 0 deletions recipes/crypto-hmac-digest-redundant/tests/commonjs/input.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
const crypto = require('node:crypto');

const hmac = crypto.createHmac('sha256', 'secret');
hmac.digest('hex');
hmac.digest();
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
import { createHmac } from 'node:crypto';

const hmac = createHmac('sha256', 'secret');
const first = hmac.digest('hex');
const second = hmac.digest('hex');
consume(first, second);
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
import { createHmac } from 'node:crypto';

const hmac = createHmac('sha256', 'secret');
const first = hmac.digest('hex');
const second = hmac.digest('hex');
consume(first, second);
Loading