Skip to content

Commit 64d10e6

Browse files
committed
Bounds checking when creating cursor
1 parent 08fd595 commit 64d10e6

File tree

3 files changed

+17
-0
lines changed

3 files changed

+17
-0
lines changed

frontend/cursor.js

+1
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ const { isObject } = require('../src/common')
99
class Cursor {
1010
constructor(object, index, elemId = undefined) {
1111
if (Array.isArray(object) && object[ELEM_IDS] && typeof index === 'number') {
12+
if (index < 0 || index >= object[ELEM_IDS].length) throw new RangeError('list index out of bounds')
1213
this.objectId = object[OBJECT_ID]
1314
this.elemId = object[ELEM_IDS][index]
1415
this.index = index

frontend/text.js

+1
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,7 @@ class Text {
3333
}
3434

3535
getElemId (index) {
36+
if (index < 0 || index >= this.elems.length) throw new RangeError('text index out of bounds')
3637
return this.elems[index].elemId
3738
}
3839

test/cursor_test.js

+15
Original file line numberDiff line numberDiff line change
@@ -39,4 +39,19 @@ describe('Automerge.Cursor', () => {
3939
assert.ok(s3.cursor instanceof Automerge.Cursor)
4040
assert.strictEqual(s3.cursor.elemId, `4@${Automerge.getActorId(s1)}`)
4141
})
42+
43+
it('should not allow an index beyond the length of the list', () => {
44+
assert.throws(() => {
45+
Automerge.change(Automerge.init(), doc => {
46+
doc.list = [1]
47+
doc.cursor = new Automerge.Cursor(doc.list, 1)
48+
})
49+
}, /index out of bounds/)
50+
assert.throws(() => {
51+
Automerge.change(Automerge.init(), doc => {
52+
doc.text = new Automerge.Text('a')
53+
doc.cursor = doc.text.getCursorAt(1)
54+
})
55+
}, /index out of bounds/)
56+
})
4257
})

0 commit comments

Comments
 (0)