-
Notifications
You must be signed in to change notification settings - Fork 116
/
utils.js
252 lines (211 loc) · 5.21 KB
/
utils.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
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
import * as tools from "./toolbox.js";
function ab2str(buf) {
let str = "";
new Uint8Array(buf).forEach((ch) => {
str += String.fromCharCode(ch);
});
return str;
}
function isBase64Url(str) {
return !!str.match(/^[A-Za-z0-9\-_]+={0,2}$/);
}
function isPem(pem) {
if (typeof pem !== "string") {
return false;
}
const pemRegex = /^-----BEGIN .+-----$\n([A-Za-z0-9+/=]|\n)*^-----END .+-----$/m;
return !!pem.match(pemRegex);
}
function isPositiveInteger(n) {
return n >>> 0 === parseFloat(n);
}
function abToBuf(ab) {
return new Uint8Array(ab).buffer;
}
function abToInt(ab) {
if (!(ab instanceof ArrayBuffer)) {
throw new Error("abToInt: expected ArrayBuffer");
}
const buf = new Uint8Array(ab);
let cnt = ab.byteLength - 1;
let ret = 0;
buf.forEach((byte) => {
ret |= byte << (cnt * 8);
cnt--;
});
return ret;
}
function abToPem(type, ab) {
if (typeof type !== "string") {
throw new Error(
"abToPem expected 'type' to be string like 'CERTIFICATE', got: " +
type,
);
}
const str = coerceToBase64(ab, "pem buffer");
return [
`-----BEGIN ${type}-----\n`,
...str.match(/.{1,64}/g).map((s) => s + "\n"),
`-----END ${type}-----\n`,
].join("");
}
/**
* Creates a new Uint8Array based on two different ArrayBuffers
*
* @private
* @param {ArrayBuffers} buffer1 The first buffer.
* @param {ArrayBuffers} buffer2 The second buffer.
* @return {ArrayBuffers} The new ArrayBuffer created out of the two.
*/
const appendBuffer = function(buffer1, buffer2) {
const tmp = new Uint8Array(buffer1.byteLength + buffer2.byteLength);
tmp.set(new Uint8Array(buffer1), 0);
tmp.set(new Uint8Array(buffer2), buffer1.byteLength);
return tmp.buffer;
};
function coerceToArrayBuffer(buf, name) {
if (!name) {
throw new TypeError("name not specified in coerceToArrayBuffer");
}
// Handle empty strings
if (typeof buf === "string" && buf === "") {
buf = new Uint8Array(0);
// Handle base64url and base64 strings
} else if (typeof buf === "string") {
// base64 to base64url
buf = buf.replace(/\+/g, "-").replace(/\//g, "_").replace("=", "");
// base64 to Buffer
buf = tools.base64.toArrayBuffer(buf, true);
}
// Extract typed array from Array
if (Array.isArray(buf)) {
buf = new Uint8Array(buf);
}
// Extract ArrayBuffer from Node buffer
if (typeof Buffer !== "undefined" && buf instanceof Buffer) {
buf = new Uint8Array(buf);
buf = buf.buffer;
}
// Extract arraybuffer from TypedArray
if (buf instanceof Uint8Array) {
buf = buf.slice(0, buf.byteLength, buf.buffer.byteOffset).buffer;
}
// error if none of the above worked
if (!(buf instanceof ArrayBuffer)) {
throw new TypeError(`could not coerce '${name}' to ArrayBuffer`);
}
return buf;
}
function coerceToBase64(thing, name) {
if (!name) {
throw new TypeError("name not specified in coerceToBase64");
}
if (typeof thing !== "string") {
try {
thing = tools.base64.fromArrayBuffer(
coerceToArrayBuffer(thing, name),
);
} catch (_err) {
throw new Error(`could not coerce '${name}' to string`);
}
}
return thing;
}
function str2ab(str) {
const buf = new ArrayBuffer(str.length);
const bufView = new Uint8Array(buf);
for (let i = 0, strLen = str.length; i < strLen; i++) {
bufView[i] = str.charCodeAt(i);
}
return buf;
}
function coerceToBase64Url(thing, name) {
if (!name) {
throw new TypeError("name not specified in coerceToBase64");
}
if (typeof thing === "string") {
// Convert from base64 to base64url
thing = thing.replace(/\+/g, "-").replace(/\//g, "_").replace(/=*$/g, "");
}
if (typeof thing !== "string") {
try {
thing = tools.base64.fromArrayBuffer(
coerceToArrayBuffer(thing, name),
true,
);
} catch (_err) {
throw new Error(`could not coerce '${name}' to string`);
}
}
return thing;
}
// Merged with previous arrayBufferEquals
function arrayBufferEquals(b1, b2) {
if (
!(b1 instanceof ArrayBuffer) ||
!(b2 instanceof ArrayBuffer)
) {
return false;
}
if (b1.byteLength !== b2.byteLength) {
return false;
}
b1 = new Uint8Array(b1);
b2 = new Uint8Array(b2);
for (let i = 0; i < b1.byteLength; i++) {
if (b1[i] !== b2[i]) return false;
}
return true;
}
function abToHex(ab) {
if (!(ab instanceof ArrayBuffer)) {
throw new TypeError("Invalid argument passed to abToHex");
}
const result = Array.prototype.map.call(
new Uint8Array(ab),
(x) => ("00" + x.toString(16)).slice(-2),
).join("");
return result;
}
function b64ToJsObject(b64, desc) {
return JSON.parse(ab2str(coerceToArrayBuffer(b64, desc)));
}
function jsObjectToB64(obj) {
return tools.base64.fromString(
JSON.stringify(obj).replace(/[\u{0080}-\u{FFFF}]/gu, ""),
);
}
function pemToBase64(pem) {
// Clean up base64 string
if (typeof pem === "string" || pem instanceof String) {
pem = pem.replace(/\r/g, "");
}
if (!isPem(pem)) {
throw new Error("expected PEM string as input");
}
// Split on \n
let pemArr = pem.split("\n");
// remove first and last lines
pemArr = pemArr.slice(1, pemArr.length - 2);
return pemArr.join("");
}
export {
arrayBufferEquals,
abToBuf,
abToHex,
abToInt,
abToPem,
ab2str,
appendBuffer,
b64ToJsObject,
coerceToArrayBuffer,
coerceToBase64,
coerceToBase64Url,
isBase64Url,
isPem,
isPositiveInteger,
jsObjectToB64,
pemToBase64,
str2ab,
tools
};