Skip to content

Conversation

@prateek-hegde
Copy link
Contributor

@prateek-hegde prateek-hegde commented Sep 4, 2025

Summary

Bumps sha.js from 2.4.11 to 2.4.12 to address security advisory CVE: 2025-9288.

Details

  • sha.js@2.4.11 contains a known vulnerability (CVE: 2025-9288).
  • The issue has been fixed in sha.js@2.4.12.
  • Updated hash() to only truncate when options.length > 0

Testing

  • Installed updated dependency.
  • Ran full TypeORM test suite → all tests passed.

Notes

This is a safe, non-breaking patch dependency update.

Pull-Request Checklist

  • Code is up-to-date with the master branch
  • This pull request links relevant issues as Fixes #00000 - N/A
  • There are new or updated unit tests validating the change
  • Documentation has been updated to reflect this change - N/A

Summary by CodeRabbit

  • Bug Fixes

    • Fixed checksum/truncation behavior: non-positive or invalid lengths no longer truncate; truncation is applied only when a positive length is specified and is capped to the digest size.
  • Tests

    • Added unit tests for digest correctness, determinism, truncation rules, edge cases (empty, zero/negative lengths), and output format.
  • Chores

    • Updated hashing dependency to latest patch release.

Prateek Hegde added 4 commits September 4, 2025 08:48
- Verify SHA1 output for known inputs
- Test truncation with options.length
- Handle empty string input
- Confirm deterministic behavior for identical inputs
- Updated hash() to only truncate when options.length > 0
- Prevents accidental truncation when options.length is negative
- Maintains expected behavior for full-length hash
@coderabbitai
Copy link
Contributor

coderabbitai bot commented Sep 4, 2025

Walkthrough

Bump sha.js dependency; add/export a SHA-1 hash(input, options?) in StringUtils with refined length handling (slice only when options.length is defined and > 0); add unit tests verifying digest correctness, truncation, determinism, and edge cases.

Changes

Cohort / File(s) Summary
Dependencies
package.json
Bump sha.js from ^2.4.11 to ^2.4.12.
String utilities
src/util/StringUtils.ts
Export/add hash(input: string, options?: { length?: number }): string. Compute SHA‑1 hex digest; only slice when options.length is defined and > 0 (use truncated integer, clamp to digest length); zero, negative, or non-finite lengths return full digest.
Unit tests
test/unit/util/string-utils.ts
New/expanded tests for hash: verify SHA‑1 hex output, determinism, truncation behavior (positive, zero, negative, oversized), known digest values, and hex format/length assertions.

Sequence Diagram(s)

sequenceDiagram
    participant Caller
    participant StringUtils
    participant SHA1Lib as sha.js

    Caller->>StringUtils: hash(input, options?)
    StringUtils->>SHA1Lib: compute SHA-1 hex digest of input
    SHA1Lib-->>StringUtils: fullDigest (40 hex chars)
    alt options.length is defined and > 0
        StringUtils->>StringUtils: len = Math.trunc(options.length)
        StringUtils->>StringUtils: sliceDigest = fullDigest.slice(0, Math.min(len, fullDigest.length))
        StringUtils-->>Caller: return sliceDigest
    else
        StringUtils-->>Caller: return fullDigest
    end
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Pre-merge checks (3 passed)

✅ Passed checks (3 passed)
Check name Status Explanation
Title Check ✅ Passed The title succinctly describes the core change of bumping sha.js from 2.4.11 to 2.4.12 and references the security fix CVE-2025-9288, making it fully aligned with the main changeset and clear to reviewers.
Description Check ✅ Passed The pull request description clearly outlines the security advisory and version upgrade, details the hash() truncation update, and lists testing steps and notes that the change is non-breaking, making it directly relevant to the changeset.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.

Poem

I nibble bytes beneath moonlight,
SHA‑1 whispers in the night.
Slice when you ask, if length is right,
Zero or minus keeps the whole in sight.
Tests hop forward, tidy and bright. 🐇✨

Tip

👮 Agentic pre-merge checks are now available in preview!

Pro plan users can now enable pre-merge checks in their settings to enforce checklists before merging PRs.

  • Built-in checks – Quickly apply ready-made checks to enforce title conventions, require pull request descriptions that follow templates, validate linked issues for compliance, and more.
  • Custom agentic checks – Define your own rules using CodeRabbit’s advanced agentic capabilities to enforce organization-specific policies and workflows. For example, you can instruct CodeRabbit’s agent to verify that API documentation is updated whenever API schema files are modified in a PR. Note: Upto 5 custom checks are currently allowed during the preview period. Pricing for this feature will be announced in a few weeks.

Example:

reviews:
  pre_merge_checks:
    custom_checks:
		  - name: "Undocumented Breaking Changes"
			  mode: "warning"
			  instructions: |
				  Flag potential breaking changes that are not documented:
				  1. Identify changes to public APIs/exports, CLI flags, environment variables, configuration keys, database schemas, or HTTP/GraphQL endpoints (including removed/renamed items and changes to types, required params, return values, defaults, or behavior).
				  2. Ignore purely internal/private changes (e.g., code not exported from package entry points or marked internal).
				  3. Verify documentation exists: a "Breaking Change" section in the PR description and updates to CHANGELOG.md.

Please share your feedback with us on this Discord post.

Warning

Review ran into problems

🔥 Problems

Errors were encountered while retrieving linked issues.

Errors (1)
  • Failed to retrieve linked issues from the platform client.
✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Nitpick comments (2)
src/util/StringUtils.ts (1)

119-127: Minor hardening: coerce to an integer and clamp explicitly; clarify non-crypto intent.

Avoid surprises with floats/Infinity and document that SHA-1 here is non-security-critical.

Apply:

 export function hash(input: string, options: IHashOptions = {}): string {
   const hashFunction = shajs("sha1")
   hashFunction.update(input, "utf8")
   const hashedInput = hashFunction.digest("hex")
-  if (options.length && options.length > 0) {
-      return hashedInput.slice(0, options.length)
-  }
+  const len = Number.isFinite(options.length as number)
+    ? Math.trunc(options.length as number)
+    : 0
+  if (len > 0) {
+    // slice already caps to hashedInput.length; the Math.min keeps intent explicit
+    return hashedInput.slice(0, Math.min(len, hashedInput.length))
+  }
   return hashedInput
 }

Optional JSDoc tweak:

/**
 * Returns a SHA-1 hex digest for internal IDs/aliases (not for cryptographic security).
 */
test/unit/util/string-utils.ts (1)

123-190: Good coverage; consider deduping the two “length > digest size” cases.

Both tests at Lines 177–182 and 184–189 assert the same behavior. Keep one to reduce redundancy.

Apply:

@@
-        it("should clamp length larger than hash length to full length", () => {
-            const full = "aaf4c61ddcc5e8a2dabede0f3b482cd9aea9434d"
-            const result = hash("hello", { length: 999 })
-            expect(result).to.be.equal(full)
-            expect(result).to.have.lengthOf(40)
-        })
-
         it("should return full length when options.length exceeds digest size", () => {
             const full = hash("hello")
-            const over = hash("hello", { length: 100 })
+            const over = hash("hello", { length: 999 })
             expect(over).to.equal(full)
             expect(over).to.have.lengthOf(40)
         })
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled
  • Linear integration is disabled

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 6965fa2 and 0229fea.

⛔ Files ignored due to path filters (1)
  • package-lock.json is excluded by !**/package-lock.json
📒 Files selected for processing (3)
  • package.json (1 hunks)
  • src/util/StringUtils.ts (1 hunks)
  • test/unit/util/string-utils.ts (2 hunks)
🧰 Additional context used
🧬 Code graph analysis (1)
test/unit/util/string-utils.ts (1)
src/util/StringUtils.ts (1)
  • hash (119-127)
🔇 Additional comments (3)
package.json (1)

107-107: No lockfile updates needed; package-lock.json already pins sha.js@2.4.12
Lockfile verification confirms version 2.4.12 is in use.

src/util/StringUtils.ts (1)

123-126: Correct fix: avoid truncating on length = 0 or negative.

The extra options.length > 0 guard addresses the empty/negative edge cases cleanly.

test/unit/util/string-utils.ts (1)

2-2: Import looks correct for added hash() tests.

Copy link
Collaborator

@gioboa gioboa left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for your help @prateek-hegde 💪

@pkg-pr-new
Copy link

pkg-pr-new bot commented Sep 4, 2025

typeorm-sql-js-example

npm i https://pkg.pr.new/typeorm/typeorm@11639

commit: d50903d

@coveralls
Copy link

coveralls commented Sep 4, 2025

Coverage Status

coverage: 76.358% (+0.01%) from 76.348%
when pulling d50903d on prateek-hegde:chore/bump-sha.js-2.4.12
into 6965fa2 on typeorm:master.

@prateek-hegde
Copy link
Contributor Author

prateek-hegde commented Sep 8, 2025

Hey @alumni @sgarner 🚨
This PR is on a mission to save TypeORM from a tiny but mighty vulnerability CVE-2025-9288🛡️.

Can I count on you both to give it the final ✅ so we can merge and keep things secure? 🙏
(Think of it as patching a leak before it becomes a flood 🌊.)

Copy link
Collaborator

@sgarner sgarner left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for the PR @prateek-hegde !

I have a concern about the added input validation. Otherwise this looks good. I'll let @alumni weigh in before we decide.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Nitpick comments (2)
src/util/StringUtils.ts (2)

113-118: Doc: clarify truncation semantics.

Consider noting explicitly that when options.length is <= 0 or not provided, the function returns the full 40-char digest. This avoids ambiguity for callers reading the JSDoc.

 /**
- * Returns a SHA-1 hex digest for internal IDs/aliases (not for cryptographic security)
+ * Returns a SHA-1 hex digest for internal IDs/aliases (not for cryptographic security).
+ * Note: if `options.length` is not provided or <= 0, the full 40-character digest is returned.
  *
  * @param input String to be hashed.
  * @param options.length Optionally, shorten the output to desired length.
  */

109-111: Export the options type for cleaner public typings.

hash is exported; consumers will see its signature in .d.ts. Exporting IHashOptions improves DX and avoids anonymous inlined types in declarations.

-interface IHashOptions {
+export interface IHashOptions {
   length?: number
 }
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 00f9ee1 and d50903d.

📒 Files selected for processing (1)
  • src/util/StringUtils.ts (2 hunks)
🔇 Additional comments (2)
src/util/StringUtils.ts (2)

123-126: Length > 0 truncation guard — LGTM.

This matches the PR intent and avoids negative-length truncation edge cases. No further validation needed given internal-only usage.


1-1: No changes needed: default import interop enabled. The root tsconfig.json has "allowSyntheticDefaultImports": true and the playground tsconfig.json has "esModuleInterop": true, so import shajs from "sha.js" is safe at runtime.

Copy link
Collaborator

@sgarner sgarner left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM

Thanks for your contribution @prateek-hegde 💜

@sgarner sgarner merged commit 9cdfb20 into typeorm:master Sep 9, 2025
58 checks passed
@diogowbrito
Copy link

@michaelbromley Do you have an expected timeline for when a new release including this vulnerability fix will be published? Thanks!

@naiyarJamalNagarro
Copy link

@michaelbromley getting some critical error to update sha.js to version 2.4.12 or later, and for this pr is already merged (2 days ago) but latest version released 3 week ago (0.3.26). so can we get any patch update to include sha.js PR or any timeline.

@alumni
Copy link
Collaborator

alumni commented Sep 11, 2025

Sorry for the slow reply, I'm having some days off :)

TypeORM does not force you to use a version with a vulnerability, so no immediate release is necessary (neither was the update in this repository, i.e. this PR, it's just nice to have).

BTW, shajs will be removed in the next major version.

@sgarner
Copy link
Collaborator

sgarner commented Sep 11, 2025

Indeed, TypeORM depends on the range ^2.4.11 which means you can update to a newer version locally just by doing:

npm update sha.js@latest

Considering the limited way TypeORM uses sha.js, there is not really any feasible vector to exploit CVE-2025-9288 through it anyway.

But this fix has been merged and will be coming in a release soon.

ThbltLmr pushed a commit to ThbltLmr/typeorm that referenced this pull request Dec 2, 2025
…5-9288) (typeorm#11639)

* chore: bump sha.js from 2.4.11 to 2.4.12 (fix security issue: CVE-2025-9288)

* test: add unit tests for hash() to ensure sha.js upgrade compatibility

- Verify SHA1 output for known inputs
- Test truncation with options.length
- Handle empty string input
- Confirm deterministic behavior for identical inputs

* removed .only from test/unit/util/string-utils.ts to run all the unit tests

* fix(hash): ensure negative or zero options.length returns full hash

- Updated hash() to only truncate when options.length > 0
- Prevents accidental truncation when options.length is negative
- Maintains expected behavior for full-length hash

* added strict +ve number input validation for hash()

* simplified the logic to check number len before applying slice() in StringUtils.ts->hash()

---------

Co-authored-by: Prateek Hegde <prateek.hegde@deliverysolutions.co>
Co-authored-by: Prateek Hegde <prateek@Prateeks-MacBook-Pro.local>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

7 participants