Skip to content

Commit 582ac51

Browse files
fix: reject invalid escape sequences in JSON Pointer strings (#13)
* fix: reject invalid escape sequences in JSON Pointer strings * refactor: use RegExp.test instead of String.search for escape validation
1 parent b57107b commit 582ac51

File tree

2 files changed

+64
-0
lines changed

2 files changed

+64
-0
lines changed

lib/index.js

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,10 @@ export const pointerSegments = function* (pointer) {
1010
throw Error("Invalid JSON Pointer");
1111
}
1212

13+
if (/~(?![01])/.test(pointer)) {
14+
throw Error("Invalid JSON Pointer");
15+
}
16+
1317
let segmentStart = 1;
1418
let segmentEnd = 0;
1519

lib/pointerSegments.test.js

Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
import { describe, expect, test } from "vitest";
2+
import { pointerSegments } from "./index.js";
3+
4+
5+
describe("JsonPointer", () => {
6+
describe("pointerSegments", () => {
7+
/** @type [string, string[]][] */
8+
const tests = [
9+
["", []],
10+
["/", [""]],
11+
["/foo", ["foo"]],
12+
["/foo/bar", ["foo", "bar"]],
13+
["/foo/0", ["foo", "0"]],
14+
["/a~1b", ["a/b"]],
15+
["/m~0n", ["m~n"]],
16+
["/~00", ["~0"]],
17+
["/~01", ["~1"]],
18+
["/~10", ["/0"]],
19+
["/~11", ["/1"]],
20+
["/~01~10", ["~1/0"]],
21+
["/~00/~11", ["~0", "/1"]],
22+
["/ ", [" "]],
23+
["/c%d", ["c%d"]],
24+
["/e^f", ["e^f"]],
25+
["/g|h", ["g|h"]],
26+
["/i\\j", ["i\\j"]],
27+
["/k\"l", ["k\"l"]]
28+
];
29+
30+
tests.forEach(([pointer, expected]) => {
31+
test(`${JSON.stringify(pointer)} => ${JSON.stringify(expected)}`, () => {
32+
expect([...pointerSegments(pointer)]).to.eql(expected);
33+
});
34+
});
35+
});
36+
37+
describe("a pointer that doesn't start with '/'", () => {
38+
test("should throw an error", () => {
39+
expect(() => [...pointerSegments("foo")]).to.throw(Error, "Invalid JSON Pointer");
40+
});
41+
});
42+
43+
describe("a pointer with an invalid escape sequence", () => {
44+
/** @type string[] */
45+
const tests = [
46+
"/~",
47+
"/~2",
48+
"/~a",
49+
"/a~",
50+
"/~~",
51+
"/~0~"
52+
];
53+
54+
tests.forEach((pointer) => {
55+
test(`${JSON.stringify(pointer)} should throw an error`, () => {
56+
expect(() => [...pointerSegments(pointer)]).to.throw(Error, "Invalid JSON Pointer");
57+
});
58+
});
59+
});
60+
});

0 commit comments

Comments
 (0)