-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlib.js
137 lines (117 loc) · 2.56 KB
/
lib.js
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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
export const b32 = {
ALPHABET: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567',
ALPHABET_MAP: {},
decode(s) {
const buf = new Uint8Array(Math.ceil((s.length * 5) / 8));
let bits = 0;
let bitsLen = 0;
let bufPos = 0;
for (const c of s) {
bits = (bits << 5) | this.ALPHABET_MAP[c];
bitsLen += 5;
while (bitsLen >= 8) {
buf[bufPos++] = bits >>> (bitsLen - 8);
bitsLen -= 8;
}
}
return buf;
},
encode(buf) {
let s = '';
let bits = 0;
let bitsLen = 0;
for (const b of buf) {
bits = (bits << 8) | b;
bitsLen += 8;
while (bitsLen >= 5) {
s += this.ALPHABET[(bits >>> (bitsLen - 5)) & 31];
bitsLen -= 5;
}
}
if (bitsLen > 0) {
s += this.ALPHABET[(bits << (5 - bitsLen)) & 31];
}
return s;
},
};
for (let i = 0; i < b32.ALPHABET.length; i++) {
b32.ALPHABET_MAP[(b32.ALPHABET_MAP[i] = b32.ALPHABET[i])] = i;
}
export const hotp = {
HALF: 2 ** 32,
async generate({ key, digits = 6, counter = 0 }) {
const buf = new DataView(new ArrayBuffer(8));
buf.setUint32(0, Math.floor(counter / this.HALF));
buf.setUint32(4, counter % this.HALF);
const secret = await window.crypto.subtle.importKey(
'raw',
key,
{
name: 'HMAC',
hash: 'SHA-1',
},
false,
['sign'],
);
const hmac = new Uint8Array(
await window.crypto.subtle.sign('HMAC', secret, buf),
);
const o = hmac[hmac.length - 1] & 15;
return (
(((hmac[o] & 127) << 24) |
((hmac[o + 1] & 255) << 16) |
((hmac[o + 2] & 255) << 8) |
(hmac[o + 3] & 255)) %
10 ** digits
)
.toString()
.padStart(digits, '0');
},
async validate({
key,
digits = 6,
counter = 0,
token,
windowBack = 1,
windowForward = 1,
}) {
for (let i = -windowBack; i <= windowForward; i++) {
if (
(await this.generate({
key,
digits,
counter: counter + i,
})) === token
) {
return i;
}
}
},
};
export const totp = {
generate({ key, digits = 6, period = 30, ts = Date.now() }) {
return hotp.generate({
key,
digits,
counter: Math.floor(ts / 1000 / period),
});
},
validate({
key,
digits = 6,
period = 30,
ts = Date.now(),
token,
windowBack = 1,
windowForward = 1,
}) {
return hotp.validate({
key,
digits,
counter: Math.floor(ts / 1000 / period),
token,
windowBack,
windowForward,
});
},
};