-
Notifications
You must be signed in to change notification settings - Fork 16
/
sign.ts
41 lines (36 loc) · 1.06 KB
/
sign.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
// TODO(#323): remove on v6, move it to ../entities/Development
import { createHmac } from 'crypto'
export function sign(data: any, secret: string) {
const str = JSON.stringify(data)
const signature = hash(str, secret)
return String(
Buffer.from(str, 'utf8').toString('base64') + '.' + signature
).replace(/\+/gi, '-')
}
function hash(str: string, secret: string) {
return createHmac('sha256', secret).update(str).digest('base64')
}
export function decode(data: string) {
try {
const [str] = data.split('.')
const decoded = Buffer.from(str.replace(/-/gi, '+'), 'base64').toString(
'utf8'
)
return JSON.parse(decoded)
} catch (err) {
return null
}
}
export function verify(data: string, secret: string): any {
try {
const [str, expectedSignature] = data.replace(/-/gi, '+').split('.')
const decoded = Buffer.from(str, 'base64').toString('utf8')
const signature = hash(decoded, secret)
if (signature !== expectedSignature) {
return null
}
return JSON.parse(decoded)
} catch (err) {
return null
}
}