Skip to content
Merged
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
5 changes: 5 additions & 0 deletions .changeset/add-eol-date.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"node-version": minor
---

Added `eolDate` property to `NodeVersion` interface to provide the specific End-of-Life date for a major version.
5 changes: 5 additions & 0 deletions .changeset/security-fix.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"node-version": patch
---

Added security enhancements: DoS prevention via input length limit and robust 'v' prefix stripping.
2 changes: 2 additions & 0 deletions Readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,8 @@ const v = getVersion();
| `isLTS` | `boolean` | `true` if the current version is an LTS release. |
| `ltsName` | `string` | The LTS codename (e.g., 'Iron') or `undefined`. |
| `isEOL` | `boolean` | `true` if the current version is past its End-of-Life date. |
| `eolDate` | `Date \| undefined` | The date when this major version becomes End-of-Life. |
| `toString()` | `() => string` | Returns the original version string prefixed with 'v'. |

## Compare Versions

Expand Down
2 changes: 1 addition & 1 deletion bun.lock
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"lockfileVersion": 1,
"configVersion": 1,
"configVersion": 0,
Copy link

Choose a reason for hiding this comment

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

style: configVersion downgraded from 1 to 0. Verify this was intentional and doesn't affect dependency resolution.

Prompt To Fix With AI
This is a comment left during a code review.
Path: bun.lock
Line: 3:3

Comment:
**style:** `configVersion` downgraded from 1 to 0. Verify this was intentional and doesn't affect dependency resolution.

How can I resolve this? If you propose a fix, please make it concise.

"workspaces": {
"": {
"name": "node-version",
Expand Down
6 changes: 3 additions & 3 deletions src/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -104,9 +104,9 @@ describe("node-version", () => {
expect(typeof v.build).toBe("string");
});

test("object should have exactly 15 properties", () => {
expect(Object.keys(version)).toHaveLength(15);
expect(Object.keys(getVersion())).toHaveLength(15);
test("object should have exactly 16 properties", () => {
expect(Object.keys(version)).toHaveLength(16);
expect(Object.keys(getVersion())).toHaveLength(16);
});

test("original property should start with v", () => {
Expand Down
117 changes: 80 additions & 37 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,41 @@ import type { NodeVersion } from "./types.js";

export type { NodeVersion };

/**
* End-of-Life dates for Node.js major versions.
*/
export const EOL_DATES: Record<string, string> = {
"18": "2025-04-30",
"20": "2026-04-30",
"22": "2027-04-30",
"24": "2028-04-30",
};

/**
* Maximum allowed length for version strings to prevent DoS.
*/
export const MAX_VERSION_LENGTH = 256;

/**
* Calculate the minimum version tracked.
*/
const MIN_TRACKED_MAJOR = Math.min(...Object.keys(EOL_DATES).map(Number));

/**
* Check if a major version is EOL.
*/
const checkEOL = (major: string): boolean => {
const majorNum = Number(major);
// If it's a valid number and less than the minimum tracked version, it's EOL.
if (!Number.isNaN(majorNum) && majorNum < MIN_TRACKED_MAJOR) {
return true;
}

const eolDate = EOL_DATES[major];
if (!eolDate) return false;
return new Date() > new Date(eolDate);
};

/**
* Get Node current version.
*/
Expand All @@ -17,12 +52,45 @@ export const getVersion = (): NodeVersion => {
const split = nodeVersion.split(".");
// Pre-calculate numeric version parts for faster comparison
const nodeVersionParts = split.map((s) => Number(s) || 0);
const major = split[0] || "0";
const eolString = EOL_DATES[major];

/**
* Compare the current node version with a target version string.
*/
const compareTo = (target: string): number => {
const s2 = target.replace(/^v/i, "").split(".");
if (
target !== target.trim() ||
target.length === 0 ||
target.length > MAX_VERSION_LENGTH
) {
return NaN;
}

let start = 0;
// Optimized stripping of 'v' prefix using charCodeAt (118='v', 86='V')
while (
start < target.length &&
(target.charCodeAt(start) === 118 ||
target.charCodeAt(start) === 86)
) {
start++;
}

const stripped = start > 0 ? target.slice(start) : target;

if (stripped.length === 0) {
return NaN;
}

const s2 = stripped.split(".");

for (const segment of s2) {
if (segment === "" || !/^\d+$/.test(segment)) {
return NaN;
}
}
Comment on lines +88 to +92
Copy link

Choose a reason for hiding this comment

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

style: Validation checks each segment but only validates digits. Leading zeros in version segments like "010.0.0" parse as 10 (see test at src/security.test.ts:68), but this may not match semver expectations where leading zeros could be considered invalid in some contexts.

Suggested change
for (const segment of s2) {
if (segment === "" || !/^\d+$/.test(segment)) {
return NaN;
}
}
for (const segment of s2) {
if (segment === "" || !/^\d+$/.test(segment)) {
return NaN;
}
// Reject leading zeros (except "0" itself) per strict semver
if (segment.length > 1 && segment[0] === "0") {
return NaN;
}
}

Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!

Prompt To Fix With AI
This is a comment left during a code review.
Path: src/index.ts
Line: 88:92

Comment:
**style:** Validation checks each segment but only validates digits. Leading zeros in version segments like `"010.0.0"` parse as `10` (see test at src/security.test.ts:68), but this may not match semver expectations where leading zeros could be considered invalid in some contexts.

```suggestion
        for (const segment of s2) {
            if (segment === "" || !/^\d+$/.test(segment)) {
                return NaN;
            }
            // Reject leading zeros (except "0" itself) per strict semver
            if (segment.length > 1 && segment[0] === "0") {
                return NaN;
            }
        }
```

<sub>Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!</sub>

How can I resolve this? If you propose a fix, please make it concise.


const len = Math.max(nodeVersionParts.length, s2.length);

for (let i = 0; i < len; i++) {
Expand All @@ -39,61 +107,36 @@ export const getVersion = (): NodeVersion => {
original: `v${nodeVersion}`,
short: `${split[0] || "0"}.${split[1] || "0"}`,
long: nodeVersion,
major: split[0] || "0",
major: major,
minor: split[1] || "0",
build: split[2] || "0",
isAtLeast: (version: string): boolean => {
return compareTo(version) >= 0;
const cmp = compareTo(version);
return !Number.isNaN(cmp) && cmp >= 0;
},
is: (version: string): boolean => {
return nodeVersion === version;
},
isAbove: (version: string): boolean => {
return compareTo(version) > 0;
const cmp = compareTo(version);
return !Number.isNaN(cmp) && cmp > 0;
},
isBelow: (version: string): boolean => {
return compareTo(version) < 0;
const cmp = compareTo(version);
return !Number.isNaN(cmp) && cmp < 0;
},
isAtMost: (version: string): boolean => {
return compareTo(version) <= 0;
const cmp = compareTo(version);
return !Number.isNaN(cmp) && cmp <= 0;
},
isLTS: !!release.lts,
ltsName: String(release.lts || "") || undefined,
isEOL: checkEOL(split[0] || "0"),
isEOL: checkEOL(major),
eolDate: eolString ? new Date(eolString) : undefined,
toString: () => `v${nodeVersion}`,
};
};

/**
* End-of-Life dates for Node.js major versions.
*/
export const EOL_DATES: Record<string, string> = {
"18": "2025-04-30",
"20": "2026-04-30",
"22": "2027-04-30",
"24": "2028-04-30",
};

/**
* Calculate the minimum version tracked.
*/
const MIN_TRACKED_MAJOR = Math.min(...Object.keys(EOL_DATES).map(Number));

/**
* Check if a major version is EOL.
*/
const checkEOL = (major: string): boolean => {
const majorNum = Number(major);
// If it's a valid number and less than the minimum tracked version, it's EOL.
if (!Number.isNaN(majorNum) && majorNum < MIN_TRACKED_MAJOR) {
return true;
}

const eolDate = EOL_DATES[major];
if (!eolDate) return false;
return new Date() > new Date(eolDate);
};

/**
* Node version information.
*/
Expand Down
87 changes: 87 additions & 0 deletions src/security.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
import { describe, expect, test, vi } from "vitest";
import { getVersion } from "./index.js";

// We mock process.versions to control the "current" version
const { mockVersion } = vi.hoisted(() => ({
mockVersion: { node: "20.0.0" },
}));

vi.mock("node:process", () => ({
versions: mockVersion,
release: {},
}));
Comment on lines +5 to +12
Copy link

Choose a reason for hiding this comment

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

syntax: vi.hoisted is not available in the version of vitest used by this project (based on test failure). Use the same mocking pattern as src/index.test.ts:11-14.

Suggested change
const { mockVersion } = vi.hoisted(() => ({
mockVersion: { node: "20.0.0" },
}));
vi.mock("node:process", () => ({
versions: mockVersion,
release: {},
}));
const { mockVersion } = vi.hoisted(() => ({
mockVersion: { node: "20.0.0" },
}));
vi.mock("node:process", () => ({
versions: mockVersion,
release: {},
}));
Prompt To Fix With AI
This is a comment left during a code review.
Path: src/security.test.ts
Line: 5:12

Comment:
**syntax:** `vi.hoisted` is not available in the version of vitest used by this project (based on test failure). Use the same mocking pattern as `src/index.test.ts:11-14`.

```suggestion
const { mockVersion } = vi.hoisted(() => ({
    mockVersion: { node: "20.0.0" },
}));

vi.mock("node:process", () => ({
    versions: mockVersion,
    release: {},
}));
```

How can I resolve this? If you propose a fix, please make it concise.


describe("security fixes", () => {
test("should treat multiple 'v' prefixes as valid version if numeric part follows", () => {
// Current: 20.0.0
// Target: vv99.0.0
// With robust stripping: "vv99.0.0" -> "99.0.0".
// Comparison: 20 < 99.
// isAtLeast("vv99.0.0") should be false.
const v = getVersion();
expect(v.isAtLeast("vv99.0.0")).toBe(false);
// However, isBelow should now be true because it's a valid version comparison
expect(v.isBelow("vv99.0.0")).toBe(true);
});

test("should return false (fail-closed) for excessively long version strings", () => {
const v = getVersion();
const longString = `1.${"1.".repeat(500)}`; // > 256 chars
expect(v.isAtLeast(longString)).toBe(false);
expect(v.isBelow(longString)).toBe(false);
});

test("should treat invalid strings as non-match (fail-closed)", () => {
// Current: 20.0.0
// Target: "garbage"
// Before fix: NaN -> 0.0.0. Result: 20 > 0 -> true.
// After fix: Returns false for all comparisons.
const v = getVersion();

expect(v.isAtLeast("garbage")).toBe(false);
expect(v.isBelow("garbage")).toBe(false);
expect(v.isAbove("garbage")).toBe(false);
expect(v.isAtMost("garbage")).toBe(false);
});

test("should reject malformed version strings", () => {
const v = getVersion();

expect(v.isAtLeast("")).toBe(false);
expect(v.isAtLeast("v")).toBe(false);
expect(v.isAtLeast("10.garbage.0")).toBe(false);
expect(v.isAtLeast("10.0.garbage")).toBe(false);
expect(v.isAtLeast(" 10.0.0")).toBe(false);
expect(v.isAtLeast("10.0.0 ")).toBe(false);
expect(v.isAtLeast(" 10.0.0 ")).toBe(false);
});

test("should handle 'version X' strings correctly", () => {
const v = getVersion();
// "version 99" -> parsed as NaN -> returns false
expect(v.isAtLeast("version 99")).toBe(false);
});

test("should handle numeric edge cases correctly (fail-closed)", () => {
const v = getVersion();
// Current version is 20.0.0
expect(v.isAtLeast("010.0.0")).toBe(true); // Leading zeros (parsed as 10)
expect(v.isAtLeast("1e10.0.0")).toBe(false); // Scientific notation
expect(v.isAtLeast("0x10.0.0")).toBe(false); // Hex notation
expect(v.isAtLeast("-1.0.0")).toBe(false); // Negative numbers
expect(v.isAtLeast("+20.0.0")).toBe(false); // Plus signs
expect(v.isAtLeast("1..0")).toBe(false); // Double dots
});

test("should still handle valid versions with v prefix", () => {
const v = getVersion();
expect(v.isAtLeast("v10.0.0")).toBe(true);
expect(v.isAtLeast("v20.0.0")).toBe(true);
expect(v.isBelow("v30.0.0")).toBe(true);
});

test("should still handle valid versions without v prefix", () => {
const v = getVersion();
expect(v.isAtLeast("10.0.0")).toBe(true);
});
});
5 changes: 5 additions & 0 deletions src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,11 @@ export interface NodeVersion {
* Check if the current version is considered End-of-Life (EOL).
*/
isEOL: boolean;
/**
* The date when this major version becomes End-of-Life.
* Undefined if the EOL date is not known (e.g., for very old or future versions not yet in the map).
*/
eolDate: Date | undefined;
/**
* Returns the original version string.
*/
Expand Down