UNPKG

2.8 kBJavaScriptView Raw
1const { xHubSignatureMiddleware: middleware } = require('./index')
2
3function mockRequest (signature, body) {
4 const req = {
5 headers: {},
6 rawBody: Buffer.from(body),
7 header: function (name) {
8 return this.headers[name]
9 }
10 }
11
12 if (signature) {
13 req.headers[`X-Hub-Signature${signature.startsWith('sha256') ? '-256' : ''}`] = signature
14 }
15
16 return req
17}
18
19describe('x-hub-signature.middleware', function () {
20 it('should pass when the request signature is valid', function (done) {
21 const body = '{ "id": "realtime_update" }'
22 const signature = 'sha1=c1a072c0aca15c6bd2f5bfae288ff8420e74aa5e'
23 const req = mockRequest(signature, body)
24 const middle = middleware({
25 algorithm: 'sha1',
26 secret: 'my_little_secret'
27 })
28 middle(req, null, function (err) {
29 expect(typeof err).not.toBe('object')
30 done()
31 })
32 })
33
34 it('should pass when the request custom signature (sha256) is valid', function (done) {
35 const body = '{ "id": "realtime_update" }'
36 const signature = 'sha256=2bee603b1bd2b873912ee43469a3b4a377ad70e7f64cbd58ccdbc67eb9a1b37f'
37 const req = mockRequest(signature, body)
38 const middle = middleware({
39 algorithm: 'sha256',
40 secret: 'my_little_secret',
41 header: 'X-Hub-Signature-256'
42 })
43 middle(req, null, function (err) {
44 expect(typeof err).not.toBe('object')
45 done()
46 })
47 })
48
49 it('should pass when the request signature is missing and not required', function (done) {
50 const body = '{ "id": "realtime_update" }'
51 const signature = undefined
52 const req = mockRequest(signature, body)
53 const middle = middleware({
54 algorithm: 'sha1',
55 secret: 'my_little_secret',
56 require: false
57 })
58 middle(req, null, function (err) {
59 expect(typeof err).not.toBe('object')
60 done()
61 })
62 })
63
64 it('should return HTTP 400 when the request signature is missing and required', function (done) {
65 const body = '{ "id": "realtime_update" }'
66 const signature = undefined
67 const req = mockRequest(signature, body)
68 const middle = middleware({
69 algorithm: 'sha1',
70 secret: 'my_little_secret'
71 })
72 middle(req, null, function (err) {
73 expect(typeof err).toBe('object')
74 expect(err.status).toBe(400)
75 done()
76 })
77 })
78
79 it('should return HTTP 400 when the request signature is invalid', function (done) {
80 const body = '{ "id": "realtime_update" }'
81 const signature = 'sha1=invalid_req_signature'
82 const req = mockRequest(signature, body)
83 const middle = middleware({
84 algorithm: 'sha1',
85 secret: 'my_little_secret',
86 required: false
87 })
88 middle(req, null, function (err) {
89 expect(typeof err).toBe('object')
90 expect(err.status).toBe(400)
91 done()
92 })
93 })
94})