From 64d10e6e9c37e13547eb1b1ff4b5ef762150988e Mon Sep 17 00:00:00 2001 From: Martin Kleppmann Date: Wed, 3 Feb 2021 10:54:07 +0000 Subject: [PATCH] Bounds checking when creating cursor --- frontend/cursor.js | 1 + frontend/text.js | 1 + test/cursor_test.js | 15 +++++++++++++++ 3 files changed, 17 insertions(+) diff --git a/frontend/cursor.js b/frontend/cursor.js index cda161132..9e15f9fc3 100644 --- a/frontend/cursor.js +++ b/frontend/cursor.js @@ -9,6 +9,7 @@ const { isObject } = require('../src/common') class Cursor { constructor(object, index, elemId = undefined) { if (Array.isArray(object) && object[ELEM_IDS] && typeof index === 'number') { + if (index < 0 || index >= object[ELEM_IDS].length) throw new RangeError('list index out of bounds') this.objectId = object[OBJECT_ID] this.elemId = object[ELEM_IDS][index] this.index = index diff --git a/frontend/text.js b/frontend/text.js index a1e724f0a..899934d03 100644 --- a/frontend/text.js +++ b/frontend/text.js @@ -33,6 +33,7 @@ class Text { } getElemId (index) { + if (index < 0 || index >= this.elems.length) throw new RangeError('text index out of bounds') return this.elems[index].elemId } diff --git a/test/cursor_test.js b/test/cursor_test.js index f214bc70b..dcff52de5 100644 --- a/test/cursor_test.js +++ b/test/cursor_test.js @@ -39,4 +39,19 @@ describe('Automerge.Cursor', () => { assert.ok(s3.cursor instanceof Automerge.Cursor) assert.strictEqual(s3.cursor.elemId, `4@${Automerge.getActorId(s1)}`) }) + + it('should not allow an index beyond the length of the list', () => { + assert.throws(() => { + Automerge.change(Automerge.init(), doc => { + doc.list = [1] + doc.cursor = new Automerge.Cursor(doc.list, 1) + }) + }, /index out of bounds/) + assert.throws(() => { + Automerge.change(Automerge.init(), doc => { + doc.text = new Automerge.Text('a') + doc.cursor = doc.text.getCursorAt(1) + }) + }, /index out of bounds/) + }) })