-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathbackground.js
501 lines (471 loc) · 14.3 KB
/
background.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
/*
* SPDX-License-Identifier: MPL-2.0
* SPDX-FileCopyrightText: Copyright 2024 Siemens AG
*/
let CHROME_PRT_SSO_REFRESH_INTERVAL_MIN = 30;
let prt_sso_cookie = {
data: {},
hasData: false,
};
let accounts = {
registered: [],
active: null,
queried: false,
};
let host_versions = {
native: null,
broker: null,
};
let initialized = false;
let graph_api_token = null;
let state_active = true;
let broker_online = false;
let port_native = null;
let port_menu = null;
function ssoLog(message) {
console.log("[Linux Entra SSO] " + message);
}
function ssoLogError(message) {
console.error("[Linux Entra SSO] " + message);
}
function isFirefox() {
return typeof browser !== "undefined";
}
/*
* Helpers to wait for a value to become available
*/
async function sleep(ms) {
return new Promise((r) => setTimeout(r, ms));
}
async function waitFor(f) {
let retries = 50;
while (!f() && --retries > 0) {
await sleep(200);
}
if (retries <= 0) {
ssoLogError("timeout while waiting for native messaging host");
return false;
}
return true;
}
/*
* Check if all conditions for SSO are met
*/
function is_operational() {
return state_active && accounts.active;
}
/*
* Update the UI according to the current state
*/
function update_ui() {
if (state_active && accounts.active) {
chrome.action.enable();
let imgdata = {};
let icon_title = "EntraID SSO: " + accounts.active.username;
let color = null;
if (!broker_online) {
color = "#cc0000";
icon_title += " (offline)";
}
for (const r of [16, 32, 48]) {
imgdata[r] = decorate_avatar(
accounts.active.avatar_imgdata,
color,
r,
);
}
chrome.action.setIcon({
imageData: imgdata,
});
chrome.action.setTitle({
title: icon_title,
});
return;
}
/* inactive states */
if (isFirefox()) {
chrome.action.setIcon({
path: "icons/linux-entra-sso.svg",
});
} else {
chrome.action.setIcon({
path: {
48: "icons/linux-entra-sso_48.png",
128: "icons/linux-entra-sso_128.png",
},
});
}
let title = "EntraID SSO disabled. Click to enable.";
if (state_active) title = "EntraID SSO disabled (waiting for broker).";
if (accounts.registered.length == 0) {
title = "EntraID SSO disabled (no accounts registered).";
if (!broker_online) chrome.action.disable();
}
chrome.action.setTitle({ title: title });
}
function update_handlers_firefox() {
if (!is_operational()) {
chrome.webRequest.onBeforeSendHeaders.removeListener(
on_before_send_headers,
);
return;
}
chrome.webRequest.onBeforeSendHeaders.addListener(
on_before_send_headers,
{ urls: ["https://login.microsoftonline.com/*"] },
["blocking", "requestHeaders"],
);
}
function update_handlers_chrome() {
if (!is_operational()) {
chrome.alarms.clear("prt-sso-refresh");
clear_net_rules();
return;
}
chrome.alarms.create("prt-sso-refresh", {
periodInMinutes: CHROME_PRT_SSO_REFRESH_INTERVAL_MIN,
});
chrome.alarms.onAlarm.addListener((alarm) => {
update_net_rules(alarm);
});
update_net_rules();
}
function update_handlers() {
ssoLog("update handlers");
if (isFirefox()) {
update_handlers_firefox();
} else {
update_handlers_chrome();
}
}
/*
* Update the tray icon, (un)register the handlers and notify
* the menu about a state change.
*/
function notify_state_change(ui_only = false) {
update_ui();
if (!ui_only) update_handlers();
if (port_menu === null) return;
port_menu.postMessage({
event: "stateChanged",
account: accounts.registered.length > 0 ? accounts.registered[0] : null,
broker_online: broker_online,
enabled: state_active,
host_version: host_versions.native,
broker_version: host_versions.broker,
});
}
function decorate_avatar(imgdata, color, width) {
const sWidth = imgdata.width;
const lineWidth = Math.min(2, width / 12);
let buffer = new OffscreenCanvas(sWidth, sWidth);
let ctx_buffer = buffer.getContext("2d");
ctx_buffer.putImageData(imgdata, 0, 0);
let canvas = new OffscreenCanvas(width, width);
let ctx = canvas.getContext("2d");
ctx.save();
const img_margin = color === null ? 0 : lineWidth + 1;
ctx.beginPath();
ctx.arc(
width / 2,
width / 2,
width / 2 - img_margin,
0,
Math.PI * 2,
false,
);
ctx.clip();
ctx.drawImage(
buffer,
0,
0,
sWidth,
sWidth,
img_margin,
img_margin,
width - img_margin * 2,
width - img_margin * 2,
);
ctx.restore();
if (color === null) {
return ctx.getImageData(0, 0, width, width);
}
ctx.strokeStyle = color;
ctx.lineWidth = lineWidth;
ctx.beginPath();
ctx.arc(
width / 2,
width / 2,
width / 2 - Math.min(1, lineWidth / 2),
0,
Math.PI * 2,
false,
);
ctx.stroke();
return ctx.getImageData(0, 0, width, width);
}
async function load_icon(path, width) {
const response = await fetch(chrome.runtime.getURL(path));
let imgBitmap = await createImageBitmap(await response.blob(), {
resizeWidth: width,
resizeHeight: width,
});
let canvas = new OffscreenCanvas(width, width);
let ctx = canvas.getContext("2d");
ctx.save();
ctx.drawImage(imgBitmap, 0, 0);
ctx.restore();
return ctx.getImageData(0, 0, width, width);
}
async function load_accounts() {
ssoLog("loading accounts");
port_native.postMessage({ command: "getAccounts" });
let success = await waitFor(() => {
if (accounts.queried) {
return true;
}
return false;
});
if (!success) {
accounts.queried = false;
return;
} else if (accounts.registered.length == 0) {
ssoLog("no accounts registered");
return;
}
accounts.active = accounts.registered[0];
accounts.active.avatar = null;
accounts.active.avatar_imgdata = null;
ssoLog("active account: " + accounts.active.username);
// load profile picture and set it as icon
if (!graph_api_token || graph_api_token.expiresOn < Date.now() + 60000) {
graph_api_token = null;
port_native.postMessage({
command: "acquireTokenSilently",
account: accounts.active,
});
let success = await waitFor(() => {
return graph_api_token !== null;
});
if (!success) {
return;
} else if ("error" in graph_api_token) {
ssoLog(
"couldn't aquire API token for avatar: " +
graph_api_token.error,
);
return;
}
ssoLog("API token acquired");
}
const response = await fetch(
"https://graph.microsoft.com/v1.0/me/photos/48x48/$value",
{
headers: {
"Content-Type": "image/jpeg",
Authorization: "Bearer " + graph_api_token.accessToken,
},
},
);
if (response.ok) {
let avatar = await createImageBitmap(await response.blob());
let canvas = new OffscreenCanvas(48, 48);
let ctx = canvas.getContext("2d");
ctx.save();
ctx.beginPath();
ctx.arc(24, 24, 24, 0, Math.PI * 2, false);
ctx.clip();
ctx.drawImage(avatar, 0, 0);
ctx.restore();
/* serialize image to data URL (ugly, but portable) */
let blob = await canvas.convertToBlob();
const dataUrl = await new Promise((r) => {
let a = new FileReader();
a.onload = r;
a.readAsDataURL(blob);
}).then((e) => e.target.result);
/* store image data */
ctx.clearRect(0, 0, 48, 48);
ctx.drawImage(avatar, 0, 0, 48, 48);
accounts.active.avatar_imgdata = ctx.getImageData(0, 0, 48, 48);
accounts.active.avatar = dataUrl;
} else {
ssoLog("Warning: Could not get profile picture.");
accounts.active.avatar_imgdata = await load_icon(
"icons/profile-outline_48.png",
48,
);
}
}
async function get_or_request_prt(ssoUrl) {
ssoLog("request new PrtSsoCookie from broker for ssoUrl: " + ssoUrl);
port_native.postMessage({
command: "acquirePrtSsoCookie",
account: accounts.active,
ssoUrl: ssoUrl,
});
let success = await waitFor(() => {
if (prt_sso_cookie.hasData) {
return true;
}
return false;
});
if (!success) {
return { error: "timeout while waiting for native messaging host" };
}
prt_sso_cookie.hasData = false;
const data = prt_sso_cookie.data;
if ("error" in data) {
ssoLog("could not acquire PRT SSO cookie: " + data.error);
}
return data;
}
async function on_before_send_headers(e) {
// filter out requests that are not part of the OAuth2.0 flow
accept = e.requestHeaders.find(
(header) => header.name.toLowerCase() === "accept",
);
if (accept === undefined || !accept.value.includes("text/html")) {
return { requestHeaders: e.requestHeaders };
}
if (!is_operational()) {
return { requestHeaders: e.requestHeaders };
}
let prt = await get_or_request_prt(e.url);
if ("error" in prt) {
return { requestHeaders: e.requestHeaders };
}
// ms-oapxbc OAuth2 protocol extension
ssoLog("inject PRT SSO into request headers");
e.requestHeaders.push({ name: prt.cookieName, value: prt.cookieContent });
return { requestHeaders: e.requestHeaders };
}
async function update_net_rules(e) {
ssoLog("update network rules");
const SSO_URL = "https://login.microsoftonline.com";
let prt = await get_or_request_prt(SSO_URL);
if ("error" in prt) {
ssoLogError("could not acquire PRT SSO cookie: " + prt.error);
return;
}
const newRules = [
{
id: 1,
priority: 1,
condition: {
urlFilter: SSO_URL + "/*",
resourceTypes: ["main_frame"],
},
action: {
type: "modifyHeaders",
requestHeaders: [
{
header: prt.cookieName,
operation: "set",
value: prt.cookieContent,
},
],
},
},
];
const oldRules = await chrome.declarativeNetRequest.getSessionRules();
const oldRuleIds = oldRules.map((rule) => rule.id);
// Use the arrays to update the dynamic rules
await chrome.declarativeNetRequest.updateSessionRules({
removeRuleIds: oldRuleIds,
addRules: newRules,
});
ssoLog("network rules updated");
}
async function clear_net_rules() {
ssoLog("clear network rules");
const oldRules = await chrome.declarativeNetRequest.getSessionRules();
const oldRuleIds = oldRules.map((rule) => rule.id);
await chrome.declarativeNetRequest.updateSessionRules({
removeRuleIds: oldRuleIds,
});
}
async function on_message_native(response) {
if (response.command == "acquirePrtSsoCookie") {
prt_sso_cookie.data = response.message;
prt_sso_cookie.hasData = true;
} else if (response.command == "getAccounts") {
accounts.queried = true;
if ("error" in response.message) {
ssoLog("could not get accounts: " + response.message.error);
return;
}
accounts.registered = response.message.accounts;
} else if (response.command == "getVersion") {
host_versions.native = response.message.native;
host_versions.broker = response.message.linuxBrokerVersion;
notify_state_change(true);
} else if (response.command == "acquireTokenSilently") {
if ("error" in response.message) {
graph_api_token = {
error: response.message.error,
};
return;
}
graph_api_token = response.message.brokerTokenResponse;
} else if (response.command == "brokerStateChanged") {
if (response.message == "online") {
ssoLog("connection to broker restored");
broker_online = true;
// only reload data if we did not see the broker before
if (accounts.queried === false) {
await load_accounts();
notify_state_change();
}
if (host_versions.native === null) {
port_native.postMessage({ command: "getVersion" });
}
} else {
ssoLog("lost connection to broker");
broker_online = false;
}
notify_state_change(true);
} else {
ssoLog("unknown command: " + response.command);
}
}
async function on_message_menu(request) {
if (request.command == "enable") {
state_active = true;
} else if (request.command == "disable") {
state_active = false;
}
notify_state_change();
}
function on_startup() {
if (initialized) {
ssoLog("linux-entra-sso already initialized");
return;
}
initialized = true;
ssoLog("start linux-entra-sso");
notify_state_change(true);
port_native = chrome.runtime.connectNative("linux_entra_sso");
port_native.onDisconnect.addListener(() => {
if (chrome.runtime.lastError) {
ssoLogError(
"Error in native application connection:" +
chrome.runtime.lastError,
);
} else {
ssoLogError("Native application connection closed.");
}
});
port_native.onMessage.addListener(on_message_native);
chrome.runtime.onConnect.addListener((port) => {
port_menu = port;
port_menu.onMessage.addListener(on_message_menu);
notify_state_change(true);
port_menu.onDisconnect.addListener(() => {
port_menu = null;
});
});
}
// use this API to prevent the extension from being disabled
chrome.runtime.onStartup.addListener(on_startup);
on_startup();