-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathv1.js
636 lines (571 loc) · 19.8 KB
/
v1.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
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
/* ****************************************************************************
* Copyright 2021 51 Degrees Mobile Experts Limited (51degrees.com)
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
* ***************************************************************************/
/**
* @class {owid} Open Web Id (OWID) library for client side parsing and
* verification of Open Web Ids.
* @param {string} data - base 64 encoded byte array
* @property {object} owid - The OWID tree.
* @property {string} domain - Returns the creator of the OWID.
* @property {int} date - Returns the date and time the OWID was created in UTC.
* @property {Uint8Array} signature - Returns the signature as byte array.
*/
owid = function (data) {
"use-strict";
//#region Constructor
if (data !== undefined && typeof data !== "string") {
throw "'data' parameter must be a string or undefined";
}
if (data !== undefined) {
this.data = data;
this.owid = parse(data);
this.date = this.owid.date;
this.domain = this.owid.domain;
this.signature = this.owid.signature;
} else {
this.data = "";
}
//#endregion
//#region constants
// Characters that are allowed in a base 64 string.
const base64Characters = [
"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M",
"N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z",
"a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m",
"n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z",
"0", "1", "2", "3", "4", "5", "6", "7", "8", "9",
"+", "/", "="
];
// RegEx special characters.
const regExpSpecials = [
"[", "\\", "^", "$", ".", "|", "?", "*", "+", "(", ")"
];
// The base year for all OWID dates.
const ioDateBase = '2020-01-01T00:00:00';
// Maximum depth of multi-dimensional Arrays to traverse when verifying
// multiple OWIDs.
const maxVerifyDepth = 3;
// Used to importing PEM keys and verification.
const ECDSA = {
name: "ECDSA",
namedCurve: "P-256",
hash: { name: "SHA-256" }
}
//#endregion
//#region private functions
/**
* Parses a base 64 byte array into an ascii string.
* @param {Uint8Array} v - byte array representation of an OWID tree.
* @returns {string} base 64 string.
*/
function parseToString(v) {
var binary = "";
var len = v.byteLength;
for (var i = 0; i < len; i++) {
binary += String.fromCharCode(v[i]);
}
return btoa(binary);
}
/**
* Decode a base 64 string into a byte array.
* @param {string} v - an OWID tree encoded in base 64.
* @returns {Object} - a byte array.
*/
function parseToByteArray(v) {
return Uint8Array.from(atob(v), c => c.charCodeAt(0));
}
/**
* Parses a base 64 encoded byte array into a OWID tree.
* @param {string} v - an OWID tree encoded in base 64.
* @returns {Object} - OWID tree.
*/
function parse(v) {
function readByte(b) {
return b.array[b.index++];
}
function readString(b) {
var r = "";
while (b.index < b.array.length && b.array[b.index] != 0) {
r += String.fromCharCode(b.array[b.index++]);
}
b.index++;
return r;
}
function readUint32(b) {
return b.array[b.index++] |
b.array[b.index++] << 8 |
b.array[b.index++] << 16 |
b.array[b.index++] << 24;
}
function readByteArray(b) {
var c = readUint32(b);
var r = b.array.slice(b.index, b.index + c)
b.index += c;
return r;
}
function readDate(b, v) {
if (v == 1) {
var h = readByte(b);
var l = readByte(b);
return (h >> 8 | l) * 24 * 60;
}
if (v == 2 || v == 3) {
return readUint32(b);
}
}
function readSignature(b) {
var c = 64; // The OWID signature is always 64 bytes.
var r = b.array.slice(b.index, b.index + c)
b.index += c;
return r;
}
function readOWID(b) {
var o = Object();
o.version = readByte(b);
o.domain = readString(b);
o.date = readDate(b, o.version);
o.payload = readByteArray(b);
o.signature = readSignature(b);
o.payloadAsString = function () {
var s = "";
Uint8Array.from(this.payload, c => s += String.fromCharCode(c));
return s;
};
o.payloadAsPrintable = function () {
var s = "";
Uint8Array.from(this.payload, c => s += (c & 0xFF).toString(16));
return s;
}
return o
}
// Decode the base64 string into a byte array.
var b = Object();
b.index = 0;
b.array = parseToByteArray(v);
// Unpack the byte array into the OWID tree.
var q = [];
var r = readOWID(b);
q.push(r);
while (q.length > 0) {
var n = q.shift();
for (var i = 0; i < n.count; i++) {
var c = readOWID(b);
n.children.push(c)
c.parent = n
q.push(c)
}
}
return r;
}
/**
* Get the byte array representation of an OWID tree.
* @param {Object} t - OWID tree object.
* @returns {Uint8Array} Array of bytes.
*/
function getByteArray(t) {
function writeByte(b, v) {
b.push(v);
}
function writeString(b, v) {
for (var i = 0; i < v.length; i++) {
b.push(v.charCodeAt(i));
}
b.push(0);
}
function writeUint32(b, v) {
var a = new ArrayBuffer(4);
var d = new DataView(a);
d.setUint32(0, v, true);
for (var i = 0; i < 4; i++) {
b.push(d.getUint8(i));
}
}
function writeByteArray(b, v) {
writeUint32(b, v.length)
v.forEach(e => b.push(e));
}
if (t.version && t.domain && t.date && t.payload) {
var buf = [];
writeByte(buf, t.version);
writeString(buf, t.domain);
writeUint32(buf, t.date);
writeByteArray(buf, t.payload);
return new Uint8Array(buf);
}
}
/**
* Use the well known end point for the alleged OWID creator.
* @param {*} p - parent OWID as base 64 encoded byte array.
* @param {string} t - base 64 encoded byte array representing an OWID tree.
* @returns {Promise} Promise resolves to true if OWID is valid.
*/
function verifyOWIDWithAPI(p, t) {
var o = parse(t);
return verifyOWIDObjectWithAPI(p, t, o);
}
/**
* Use the well known end point for the alleged OWID creator.
* @param {*} p - parent OWID as base 64 encoded byte array.
* @param {string} t - base 64 encoded byte array representing an OWID tree.
* @param {Object} o - an OWID tree.
* @returns {Promise} Promise resolves to true if OWID is valid.
*/
function verifyOWIDObjectWithAPI(p, t, o) {
var data = new URLSearchParams();
data.append("parent", p);
data.append("owid", t);
var url = "//" + o.domain + "/owid/api/v" + o.version + "/verify";
return fetch(url,
{
method: "POST",
mode: "cors",
cache: "no-cache",
body: data
})
.then(r => {
if (r.ok) {
return r.json();
}
return fetchError("Verify", r);
})
.then(r => r.valid);
}
/**
* Verify the payload of this OWID is the signature of the parent OWID.
* @param {*} r - parent OWID as base 64 encoded byte array.
* @param {string} t - base 64 encoded byte array representing an OWID tree.
* @returns {Promise} Promise resolves to true if OWID is valid.
*/
function verifyOWIDWithPublicKey(r, t) {
var o = parse(t);
return verifyOWIDObjectWithPublicKey(r, o);
}
function importEcdsaKey(pem) {
// Remove the header, footer and line breaks to get the PEM content.
var lines = pem.split('\n');
var pemContents = '';
for (var i = 0; i < lines.length; i++) {
if (lines[i].trim().length > 0 &&
lines[i].indexOf('-----BEGIN PUBLIC KEY-----') < 0 &&
lines[i].indexOf('-----END PUBLIC KEY-----') < 0) {
pemContents += lines[i].trim();
}
}
// Import the public key with the SHA-256 hash algorithm.
return window.crypto.subtle.importKey(
"spki",
Uint8Array.from(atob(pemContents), c => c.charCodeAt(0)),
ECDSA,
false,
["verify"]
);
}
/**
* Verify the payload of this OWID is the signature of the parent OWID.
* @param {*} r - parent OWID as base 64 encoded byte array.
* @param {Object} o - an OWID tree.
* @returns {Promise} Promise resolves to true if OWID is valid.
*/
function verifyOWIDObjectWithPublicKey(r, o) {
var url = "//" + o.domain + "/owid/api/v1/creator";
return fetch(
url,
{ mode: "cors", cache: "default" })
.then(r => {
if (r.ok) {
return r.json()
}
return fetchError("Creator", r);
})
.then(c => importEcdsaKey(c.publicKeySPKI))
.then(k => {
var a = getByteArray(o);
var b = Uint8Array.from(atob(r), c => c.charCodeAt(0));
var m = new Uint8Array(a.length + b.length);
m.set(a);
m.set(b, a.length);
return crypto.subtle.verify(
ECDSA,
k,
o.signature,
m);
});
}
/**
* Throw error from fetch response.
* @param {string} n - Name of the fetch call
* @param {Object} r - Response object
*/
function fetchError(n, r) {
return r.text().then(text => {
throw "'" + n + "' request HTTP status code: " +
r.status +
". Response: " +
text;
});
}
//#endregion
//#region public functions
/**
* Returns the OWID creation date as a JavaScript Date object.
* @returns {Object} - the OWID instance creation date as a JavaScript Date
* object.
*/
this.dateAsJavaScriptDate = function() {
var jsDate = new Date();
jsDate.setTime(new Date(ioDateBase).getTime() + (this.date * 60 * 1000));
return jsDate;
}
/**
* Parses a base 64 encoded byte array into a OWID tree.
* @param {string} t - base 64 encoded byte array representing an OWID tree.
* @returns {Object} OWID tree.
*/
this.parse = function (t) {
if (t === undefined) {
t = this.data;
}
if (t === "") {
throw "As this instance was created without any data, you must " +
"provide a base 64 encoded OWID as a parameter to this method.";
}
return parse(t);
}
/**
* Returns the payload as a string.
* @function
* @memberof owid
* @returns {string} This OWID instance's payload as a string.
*/
this.payloadAsString = function () {
return this.owid.payloadAsString();
}
/**
* Returns the payload in hexadecimal.
* @function
* @member owid
* @returns {string} This OWID instance's payload as a hexadecimal.
*/
this.payloadAsPrintable = function () {
return this.owid.payloadAsPrintable();
}
/**
* Returns the payload as a base 64 array.
* @function
* @memberof owid
* @returns {string} This instance's payload as a base 64 array.
*/
this.payloadAsBase64 = function () {
return parseToString(this.owid.payload);
}
/**
* Stop an advert.
* @param {*} s - SWAN OWID
* @param {string} d - organization domain.
* @param {string} r - return url
*/
this.stop = function (s, d, r) {
var data = new URLSearchParams();
data.append("host", d);
data.append("returnUrl", r);
fetch("/stop",
{
method: "POST",
mode: "cors",
cache: "no-cache",
body: data
})
.then(r => {
if (r.ok) {
return r.text();
}
return fetchError("Stop", r);
})
.then(m => {
console.log(m);
window.location.href = m;
})
.catch(x => {
console.log(x);
});
}
/**
* Verify the OWID of this instance and optionally any other OWIDs provided.
* @function
* @memberof owid
* @param {(Object|Object[]|string|string[]|Array)} owids - Other OWIDs to
* verify.
* @returns {Promise} Promise object resolves to true if all OWIDs are
* verified.
*/
this.verify = function (owids) {
function verifyStringOWID(p, o) {
if (window.crypto.subtle) {
return verifyOWIDWithPublicKey(p, o);
} else {
return verifyOWIDWithAPI(p, o);
}
}
function verifyObjectOWID(p, o) {
if (window.crypto.subtle) {
return verifyOWIDObjectWithPublicKey(p, o);
} else {
return verifyOWIDObjectWithAPI(p, parseToString(getByteArray(o)), o);
}
}
/**
* Get a useable list of OWIDs.
* @param {(Object|Object[]|string|string[]|Array)} owids - OWIDs to
* verify.
* @returns
*/
function getOWIDs(owids) {
return getOWIDsFromArray([owids]);
}
/**
* Get a useable list of OWIDs from an Array.
* This function can be called from @see getOWIDsFromObject to retrieve
* OWIDs from an Array, keep track of the depth to prevent runaway.
* @param {Array} owids - an array of owids
* @param {number} depth - the current depth when traversing an array of
* OWIDs
* @returns
*/
function getOWIDsFromArray(owids, depth) {
// Set or check depth.
if (typeof depth == 'number') {
if(depth <= maxVerifyDepth) {
depth++;
} else {
throw "Maximum depth reached when parsing OWIDs, make sure" +
" provided OWIDs don't have a reference loop.";
}
} else {
depth = 1;
}
// Iterate over the items in the owids array.
var c = [];
owids.forEach(o => {
if (o !== undefined) {
switch (typeof o) {
case "string":
c = c.concat(getOWIDsFromString(o));
break;
case "object":
c = c.concat(getOWIDsFromObject(o, depth));
break;
default:
console.log(`Cannot parse type ${typeof o}`);
break;
}
}
});
return c;
}
/**
* For a given string, get a list of useable base 64 encoded byte arrays
* that represent OWIDs
* @param {string} o - base 64 encoded byte array(s)
* @returns {string[]}
*/
function getOWIDsFromString(o) {
if (o === undefined || o === ""){
throw "OWID(s) must have a value and cannot be an empty string."
}
var s = [];
for (var i = 0; i < o.length; i++) {
var c = o.charAt(i);
if (base64Characters.indexOf(c) === -1) {
if (regExpSpecials.indexOf(c) !== -2) {
c = "\\" + c;
}
s.push(c);
}
}
var r = new RegExp("[" + s.join("") + "]", "g");
return o.split(r);
}
/**
* For a given object, get a list of useable OWIDs.
* @param {Object} o -
* @returns {Array}
*/
function getOWIDsFromObject(o, depth) {
if (Array.isArray(o)) {
return getOWIDsFromArray(o, depth)
} else if (o.hasOwnProperty('verify') && o.hasOwnProperty('parse')) {
return [o.data];
} else if (o.hasOwnProperty('domain') && o.hasOwnProperty('version')) {
return parseToString(getByteArray(o));
}
throw `unrecognized object ${o}`;
}
/**
* Get combined base 64 string of other owids to verify with
* @param {string} others - other OWIDs
*/
function dataForCypto(others) {
var a = others.map(o => {
if (typeof o === "string") {
return parseToByteArray(o);
} else if (typeof o === "object") {
return getByteArray(o);
} else {
throw `unsupported type: ${typeof o}, supported types are 'string' and 'object'`;
}
});
var length = 0;
a.forEach(b => length += b.length);
var v = new Uint8Array(length);
var offset = 0;
a.forEach(b => {
v.set(b, offset);
offset += b.length;
});
var binary = "";
for (var i = 0; i < length; i++) {
binary += String.fromCharCode(v[i]);
}
return btoa(binary);
}
var owidList = getOWIDs(owids);
if (owidList.length > 0) {
if (this.data !== undefined && this.data !== "") {
var b = dataForCypto(owidList);
return verifyStringOWID(b, this.data);
} else {
return Promise.all(owidList.map(o => {
if (typeof o === "string") {
return verifyStringOWID("", o);
} else if (typeof o === "object") {
return verifyObjectOWID("", o);
} else {
throw `unsupported type: ${typeof o}, supported types are 'string' and 'object'`;
}
}))
.then(r => r.length > 0 && r.every(v => v));
}
} else {
if (this.data === undefined || this.data === "") {
throw "OWID must have a value and cannot be an empty string."
}
return verifyStringOWID("", this.data);
}
}
//#endregion
}
try {
module.exports = owid;
} catch (e) { }