Skip to content

Commit c5f8a72

Browse files
committed
feat: validate input value for fromBuffer()
1 parent 4ce5c24 commit c5f8a72

2 files changed

Lines changed: 68 additions & 1 deletion

File tree

src/lib/nodejs.ts

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -36,9 +36,12 @@ export function fromBuffer(buf: ArrayBuffer | Uint8Array): string {
3636
else if (ArrayBuffer.isView(buf)) {
3737
inst = Buffer.from(buf)
3838
}
39-
else {
39+
else if (buf instanceof ArrayBuffer) {
4040
inst = Buffer.from(buf)
4141
}
42+
else {
43+
throw new TypeError(ErrorMsg.fromArrayBufferInvalidParam)
44+
}
4245

4346
const ret = inst.toString('base64')
4447
return ret

test/20_nodejs.test.ts

Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
/// <reference types="mocha" />
2+
3+
import {
4+
basename,
5+
join,
6+
} from '@waiting/shared-core'
7+
import * as assert from 'power-assert'
8+
import rewire = require('rewire')
9+
import {
10+
TextDecoder as NodeTextDecoder,
11+
TextEncoder as NodeTextEncoder,
12+
} from 'util'
13+
14+
import { ErrorMsg } from '../src/index'
15+
import {
16+
fromBuffer,
17+
} from '../src/lib/browser'
18+
import { defaultConfig } from '../src/lib/config'
19+
20+
import { input44, input8 } from './config'
21+
22+
23+
const filename = basename(__filename)
24+
const mods = rewire('../src/lib/helper')
25+
26+
describe(filename, () => {
27+
describe('fromBuffer() works', () => {
28+
it('with ArrayBuffer input', () => {
29+
input8.forEach(row => {
30+
const u8arr = Uint8Array.from(row[0])
31+
const actual = fromBuffer(u8arr.buffer)
32+
const expected = row[1]
33+
assert(actual === expected, `Ensure that ${u8arr} serialise to ${expected}`)
34+
})
35+
})
36+
37+
it('with Uint8Array input', () => {
38+
input8.forEach(row => {
39+
const u8arr = Uint8Array.from(row[0])
40+
const actual = fromBuffer(u8arr)
41+
const expected = row[1]
42+
assert(actual === expected, `Ensure that ${u8arr} serialise to ${expected}`)
43+
})
44+
})
45+
46+
it('with invalid input', () => {
47+
input44.forEach(value => {
48+
try {
49+
// @ts-ignore
50+
fromBuffer(value)
51+
assert(false, 'Should throw error, but NOT')
52+
}
53+
catch (ex) {
54+
assert(
55+
ex.message && ex.message.includes(ErrorMsg.fromArrayBufferInvalidParam),
56+
ex.message,
57+
)
58+
}
59+
})
60+
})
61+
})
62+
63+
64+
})

0 commit comments

Comments
 (0)