-
-
Notifications
You must be signed in to change notification settings - Fork 2.4k
Expand file tree
/
Copy pathisJWT.js
More file actions
70 lines (62 loc) · 2.03 KB
/
isJWT.js
File metadata and controls
70 lines (62 loc) · 2.03 KB
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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
import assertString from './util/assertString';
import isBase64 from './isBase64';
function decodeBase64Url(b64) {
/* istanbul ignore else */
if (typeof Buffer !== 'undefined') {
/* istanbul ignore else */
if (typeof Buffer.from === 'function') {
return Buffer.from(b64, 'base64').toString('utf8');
}
/* istanbul ignore next */
// eslint-disable-next-line no-buffer-constructor
return new Buffer(b64, 'base64').toString('utf8');
}
/* istanbul ignore next */
if (typeof atob === 'function') {
const binary = atob(b64);
if (typeof TextDecoder !== 'undefined') {
const bytes = new Uint8Array(binary.length);
for (let i = 0; i < binary.length; i += 1) {
bytes[i] = binary.charCodeAt(i);
}
return new TextDecoder('utf-8').decode(bytes);
}
let encoded = '';
for (let i = 0; i < binary.length; i += 1) {
const hex = binary.charCodeAt(i).toString(16);
const code = hex.length === 1 ? `0${hex}` : hex;
encoded += `%${code}`;
}
return decodeURIComponent(encoded);
}
/* istanbul ignore next */
return b64;
}
function tryDecodeJSON(segment) {
if (!isBase64(segment, { urlSafe: true })) return false;
try {
// Normalize base64url alphabet to base64, then restore stripped padding
let b64 = segment.replace(/-/g, '+').replace(/_/g, '/');
while (b64.length % 4) b64 += '=';
const decoded = decodeBase64Url(b64);
const parsed = JSON.parse(decoded);
if (typeof parsed !== 'object') return false;
if (parsed === null) return false;
if (Array.isArray(parsed)) return false;
return parsed;
} catch (e) {
return false;
}
}
export default function isJWT(str) {
assertString(str);
const dotSplit = str.split('.');
if (dotSplit.length !== 3) return false;
const header = dotSplit[0];
const payload = dotSplit[1];
const signature = dotSplit[2];
if (!tryDecodeJSON(header)) return false;
if (!tryDecodeJSON(payload)) return false;
if (!isBase64(signature, { urlSafe: true })) return false;
return true;
}