This repository was archived by the owner on Apr 19, 2026. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbackground.js
More file actions
740 lines (661 loc) · 17.1 KB
/
Copy pathbackground.js
File metadata and controls
740 lines (661 loc) · 17.1 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
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
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
/* Copyright 2023 Google LLC
*
* 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. */
/**
* Admin console configured managed settings
*/
const managed = {};
/**
* In memory storage
*/
const storage = [];
/**
* Javascript and determined types to BigQuery types
*/
const BQDict = {
'number': 'NUMERIC',
'bigint': 'BIGNUMERIC',
'string': 'STRING',
'boolean': 'BOOL',
'date': 'DATE',
'datetime': 'DATETIME',
};
/**
* Checks if the object is empty
*
* @param {object} obj
* @returns
*/
const isEmpty = (obj) => Object.keys(obj).length === 0;
/**
* Helper for local storage
*/
const localStorage = {
getAllItems: () => chrome.storage.local.get(),
getItem: async key => (await chrome.storage.local.get(key))[key],
setItem: (key, val) => chrome.storage.local.set({ [key]: val }),
removeItems: keys => chrome.storage.local.remove(keys),
};
/**
* Removes object parameters which are empty
*
* @param {object} obj
* @returns
*/
const clearEmptyObjects = (obj) => {
Object.keys(obj).forEach(k => {
if (typeof obj[k] == 'object') {
if (!obj[k]) {
delete obj[k];
}
else if (Object.keys(obj[k]).length == 0) {
delete obj[k];
}
else {
obj[k] = clearEmptyObjects(obj[k]);
}
}
});
return obj;
};
/**
* Helper to clear local storage
*/
const clearStorage = () => {
chrome.storage.local.clear();
};
/**
* Cache a value to the local chrome storage for a limited time period.
*
* @param {string} key
* @param {*} value
* @param {integer} time
* @param {boolean} override
* @returns
*/
const cache = async (key, value, time = 21600000, override = false) => {
let info = await localStorage.getItem(key);
//no cache and not saving a value
if (!info && !value) {
return null;
}
//if the value isn't an object assign as an object
if (typeof value != 'object') {
value = { value: value };
}
//overriding and forcing the cache storage
if (key && value && override) {
value.timestamp = new Date().getTime();
localStorage.setItem(key, JSON.stringify(value));
return value;
}
//no currently stored value, first time save
if (!info && value) {
value.timestamp = new Date().getTime();
localStorage.setItem(key, JSON.stringify(value));
return value;
}
//safety
if (!info) {
return null;
}
info = JSON.parse(info);
try {
const date = new Date(info.timestamp);
//updating cache if expired
if ((Date.now() > date.getTime() + time) && value) {
value.timestamp = new Date().getTime();
localStorage.setItem(key, JSON.stringify(value));
return value;
}
} catch (e) {
if (managed.debug) sendInfo({ type: 'backend', cache: e, info: info });
}
return info;
};
/**
* Helper to convert object the JSON format
* @param {object} obj
* @returns
*/
const toJson = (obj) => {
const json = {};
for (let x in obj) {
if (typeof obj[x] != 'function') {
json[x] = obj[x];
}
if (typeof obj[x] == 'object') {
json[x] = toJson(obj[x]);
}
}
return json;
};
/**
* Initalizes the managed storage values and sets the service worker alarms
*/
async function startup() {
try {
await getManagedStorage();
} catch (e) {
try {
if (managed.debug) sendInfo({
type: 'backend', message: 'startup', err: e
});
} catch (e) { }
}
setAlarm();
}
/**
* Pulls the JSON object set from the Admin Console, saves to local storage and
* assigns to a variable
* @returns {object} data
*/
function getManagedStorage() {
return new Promise((resolve, reject) => {
try {
chrome.storage.managed.get(null, function (data) {
Object.keys(data).forEach(k => {
localStorage.setItem(k, data[k]);
managed[k] = data[k];
});
resolve(data);
});
} catch (e) {
resolve('');
}
});
}
/**
* Checks the state of the manage variabble and requests again if empty
*/
async function getManaged() {
if (isEmpty(managed)) {
getManagedStorage();
}
if (managed.debug) sendInfo({ type: 'backend', managed: managed });
}
/**
* Set the service worker alarms
*/
async function setAlarm() {
let period = managed.period ? managed.period : 5;
let frequency = managed.frequency ? managed.frequency : 2;
let tabactivity = managed.tabactivity ? managed.tabactivity : true;
if (managed.debug) sendInfo({ type: 'backend', managed: { tabactivity: tabactivity, frequency: frequency, period: period } });
chrome.alarms.getAll((alarms) => {
const names = alarms.map(a => a.name);
if (!names.includes('sendToBackend')) {
chrome.alarms.create('sendToBackend', { delayInMinutes: 1, periodInMinutes: period });
chrome.alarms.onAlarm.addListener((e) => {
if (e.name == 'sendToBackend') sendToBackend();
});
}
if (!names.includes('request')) {
chrome.alarms.create('request', { delayInMinutes: 1, periodInMinutes: frequency });
chrome.alarms.onAlarm.addListener((e) => {
if (e.name == 'request') requestData(null, 'timed check');
});
}
});
if (managed.tabactivity) {
try {
chrome.tabs.onActivated.removeListener(activatedRequest);
} catch (e) { }
chrome.tabs.onActivated.addListener(activatedRequest);
}
}
/**
* Callback when a tab is activated
*/
function activatedRequest() {
requestData(null, 'tab activated');
}
/**
* Sets the event listener of installations
*/
chrome.runtime.onInstalled.addListener(async () => {
clearStorage();
await cache('schema', null, 600, true);
requestData(null, 'install');
});
/**
* Sets the event listener for extension startup
*/
chrome.runtime.onStartup.addListener(async () => {
requestData(null, 'startup');
});
/**
* Sets the event listener for managed installation
*/
chrome.management.onInstalled.addListener(() => {
requestData(null, 'managed install');
});
/**
* Sets the ebvent listener for extension removal
*/
chrome.management.onUninstalled.addListener(sendToBackend);
/**
* Sets the event listener for when a window is removed.
*/
chrome.windows.onRemoved.addListener(sendToBackend);
/**
* Sets the event listener for when the extension is suspended
*/
chrome.runtime.onSuspend.addListener(sendToBackend);
/**
* Sets the event listener for when a device restart is requested
*/
chrome.runtime.onRestartRequired.addListener(sendToBackend);
/**
* Sets the listener for message passing
*/
chrome.runtime.onMessage.addListener(async (request, sender, sendResponse) => {
if (request && request.type == 'start') {
if (managed.debug) sendInfo({ type: 'backend', message: 'starting' });
startup();
requestData(null, 'loaded');
} else {
updateData(request);
}
sendResponse({ received: true });
});
/**
* Formats and appends data from the backend to the the client request.
* Sends to the data storage cache.
* @param {object} request
*/
async function updateData(request) {
try {
if (request.agent) {
switch (true) {
case /CrOS/.test(request.agent):
request.os = 'ChromeOS';
break;
case /Android/.test(request.agent):
request.os = 'Android';
break;
case /Mac/.test(request.agent):
request.os = 'MacOS';
break;
case /Win/.test(request.agent):
request.os = 'Windows';
break;
case /Linux/.test(request.agent):
request.os = 'Linux';
break;
default:
request.os = 'Unknown';
break;
}
request.chromeversion = request.agent.match('Chrome\/([0-9]*\.[0-9]*\.[0-9]*\.[0-9]*)')[1];
}
let device = await localStorage.getItem('device');
if (!device || (device && Object.keys(device).length == 0)) {
const values = await getAllDeviceInfo();
device = {
getDeviceSerialNumber: values[0],
getDeviceAnnotatedLocation: values[1],
getDeviceAssetId: values[2],
getDirectoryDeviceId: values[3],
getDeviceHostname: values[4],
getHardwarePlatform: values[6],
ismanaged: values[3] ? true : false
};
if (values[5] && Object.keys(values[5]).length > 0) {
device = { ...device, ...values[5] };
} else if (values[5]) {
device.getNetworkDetails = values[5];
}
if (values[7] && Object.keys(values[7]).length > 0) {
const { modelName, numOfProcessors, archName } = values[7];
device.modelName = modelName;
device.archName = archName;
device.numOfProcessors = numOfProcessors;
}
localStorage.setItem('device', JSON.stringify(device));
}
if (!device) {
device = {};
}
if (typeof device == 'string') {
device = JSON.parse(device);
}
let ip = await cache('ip');
if (!ip) {
ip = await getIP();
cache('ip', ip, (3600 + Math.floor(Math.random() * 1000)));
}
if (ip && ip.value) {
ip = { ip: ip.value };
}
const user = await getUser();
let deviceinfo = {};
if (device && Object.keys(device).length > 0) {
deviceinfo = device;
}
const allinfo = { ...request, ...user, ...ip, ...deviceinfo };
if (managed.debug) sendInfo({ type: 'backend', allinfo: allinfo });
if (allinfo.event) {
sendData(allinfo);
}
} catch (e) {
if (managed.debug) sendInfo({ type: 'backend', dataerror: e });
}
}
/**
* Sends data to a POST endpoint
* @param {object} data
* @param {string} url
* @returns
*/
async function sendToSink(data, url) {
if (!data || data.length == 0 || !url) {
return;
}
try {
const res = await fetch(url, {
method: 'POST',
body: JSON.stringify(data)
});
if (managed.debug) sendInfo({ type: 'backend', res: res });
} catch (e) {
if (managed.debug) sendInfo({ type: 'backend', res: e });
}
}
/**
* Retrieves managed device info
* @returns {Array} Device Info
*/
function getAllDeviceInfo() {
return Promise.all([getDeviceInfo('getDeviceSerialNumber'),
getDeviceInfo('getDeviceAnnotatedLocation'),
getDeviceInfo('getDeviceAssetId'),
getDeviceInfo('getDirectoryDeviceId'),
getDeviceInfo('getDeviceHostname'),
getNetworkInfo(),
getHardwarePlatform(),
getSystemCpuInfo()
]);
}
/**
* Retrieves network info for a managed device
* @returns {object} getNetworkDetails
*/
function getNetworkInfo() {
return new Promise((resolve, reject) => {
try {
chrome.enterprise.networkingAttributes.getNetworkDetails(resolve);
} catch (e) {
resolve('');
}
});
}
/**
* Retrieves hardware info for a managed device
* @returns {object} getHardwarePlatformInfo
*/
function getHardwarePlatform() {
return new Promise((resolve, reject) => {
try {
chrome.enterprise.hardwarePlatform.getHardwarePlatformInfo(resolve);
} catch (e) {
resolve('');
}
});
}
/**
* Retrieves managed device info
* @param {string} type
* @returns {object | string | number} Device info
*/
function getDeviceInfo(type) {
return new Promise((resolve, reject) => {
try {
chrome.enterprise.deviceAttributes[type](resolve);
} catch (e) {
resolve('');
}
});
}
/**
* Retrieves system CPU info
* @returns {object} cpu info
*/
function getSystemCpuInfo() {
return new Promise((resolve, reject) => {
try {
chrome.system.cpu.getInfo(resolve);
} catch (e) {
resolve('');
}
});
}
/**
* Retrieves the logged in user information
* @returns {object} User
*/
function getUser() {
return new Promise((resolve, reject) => {
try {
chrome.identity.getProfileUserInfo(resolve);
} catch (e) {
reject(e);
}
});
}
/**
* Performs a GET call to a URL set on the the Admin Console.
* Expects an unauthenticated url to retrieve the user IP address
* @returns {object} ip info
*/
async function getIP() {
const ipurl = managed.ipurl;
if (!ipurl) {
return {};
}
const res = await fetch(ipurl);
const geoip = await res.json();
if (ipurl.includes('ip-api.com')) {
if (geoip.status) {
delete geoip.status;
}
if (geoip.query && !geoip.ip) {
geoip.ip = geoip.query;
delete geoip.query;
}
}
return geoip;
}
/**
* Message passing to the client when the tab id is known
* @param {object} e
*/
function sendInfo(e) {
chrome.tabs.query({ active: true, currentWindow: true }, function (tabs) {
if (!tabs[0].id) return;
chrome.tabs.sendMessage(tabs[0].id, e);
});
}
/**
* Requests the client side information
* @param {object} data
* @param {string} event
*/
function requestData(data, event) {
try {
if (typeof data != 'object' || !data) { data = { tabId: data }; }
if (event) data.event = event;
if (data && data.tabId) {
chrome.tabs.sendMessage(data.tabId, { type: 'request', item: data }, (res) => { });
}
else {
sendInfo({ type: 'request', item: data });
}
} catch (e) {
if (managed.debug) sendInfo({ type: 'backend', request: e });
}
}
/**
* Formats and Assigns data to the storage array
* @param {object} e
*/
async function sendData(e) {
try {
getManaged();
} catch (e) { }
if (e.url) {
const url = new URL(e.url);
try {
e.urlObject = toJson(url);
} catch (e) {
if (managed.debug) sendInfo({ type: 'backend', err: e });
}
delete e.urlObject.searchParams;
}
const schemaurl = managed.schemaurl;
if (schemaurl) {
let savedSchema = await cache('schema');
if (savedSchema && savedSchema.value) {
savedSchema = savedSchema.value;
}
if (!Array.isArray(savedSchema)) {
savedSchema = null;
}
const schema = createSchema(e);
const newSchema = checkSchema(schema, savedSchema);
if (newSchema) {
await cache('schema', schema, 600, true);
await sendToSink(schema, schemaurl);
}
}
const all = clearEmptyObjects(e);
all.timestamp = new Date().getTime();
storage.push(all);
}
/**
* Sends the storage data to the sink and clears the storage
* @returns
*/
async function sendToBackend() {
if (managed.debug) sendInfo({ type: 'backend', storage: storage });
const posturl = managed.posturl;
if (!posturl) return;
await sendToSink(storage, posturl);
storage.splice(0, storage.length);
}
/**
* Compares two objects
* @param {object} schema
* @param {object} savedSchema
* @returns {boolean}
*/
function checkSchema(schema, savedSchema) {
return objectCompare(schema, savedSchema);
}
function objectCompare(obj, savedObj) {
let newSchema = false;
if (!savedObj || savedObj.length == 0) {
return true;
}
if ((!savedObj || savedObj.length == 0) && obj && obj.length > 0) {
return true;
}
obj.forEach(k => {
const saved = savedObj.find(o => o.name == k.name);
if (saved && saved.type != k.type) {
newSchema = true;
}
if (!saved) {
newSchema = true;
}
if (k && k.type == 'STRUCT') {
if (!saved) {
newSchema = true;
} else {
newSchema = objectCompare(k.fields, saved.fields);
}
}
});
return newSchema;
}
/**
* Creates a BigQuery schema from JSON object
* @param {object} data
* @returns
*/
function createSchema(data) {
if (!data) return;
const schema = [];
const keys = Object.keys(data);
keys.forEach(k => {
const obj = {};
const type = typeof data[k];
if (type == 'object') {
if (Array.isArray(data[k])) {
obj['type'] = 'RECORD';
obj['mode'] = 'REPEATED';
const repeated = {};
const fields = [];
data[k].forEach((d, i) => {
const atype = typeof d;
if (atype == 'object') {
const akeys = Object.keys(d);
const rkeys = Object.keys(repeated);
akeys.forEach(ak => {
if (!rkeys.includes(ak)) {
repeated[ak] = d[ak];
}
if (repeated[ak] == undefined && d[ak]) {
repeated[ak] = d[ak];
}
});
}
else {
const o = {
name: `item${i}`,
type: BQDict[typeof d]
};
fields.push(o);
}
});
if (Object.keys(repeated).length > 0) {
obj['fields'] = createSchema(repeated);
}
else if (fields && fields.length > 0) {
obj['fields'] = fields;
}
else {
obj['fields'] = createSchema(data[k][0]);
}
}
else {
obj['type'] = 'STRUCT';
obj['fields'] = createSchema(data[k]);
if (!obj['fields'] || obj['fields'].length == 0) {
return;
}
}
}
else {
obj['type'] = BQDict[type];
}
if (Object.keys(obj).length > 0) {
obj['name'] = k;
if (!obj['type']) {
obj['type'] = 'STRING';
}
schema.push(obj);
}
});
return schema;
}