forked from Authenticator-Extension/Authenticator
-
Notifications
You must be signed in to change notification settings - Fork 0
/
syncTime.ts
45 lines (42 loc) · 1.46 KB
/
syncTime.ts
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
import { UserSettings } from "./models/settings";
export async function syncTimeWithGoogle() {
await UserSettings.updateItems();
return new Promise(
(resolve: (value: string) => void, reject: (reason: Error) => void) => {
try {
// @ts-expect-error - these typings are wrong
const xhr = new XMLHttpRequest({ mozAnon: true });
xhr.open("HEAD", "https://www.google.com/generate_204");
const xhrAbort = setTimeout(() => {
xhr.abort();
return resolve("updateFailure");
}, 5000);
xhr.onreadystatechange = () => {
if (xhr.readyState === 4) {
clearTimeout(xhrAbort);
const date = xhr.getResponseHeader("date");
if (!date) {
return resolve("updateFailure");
}
const serverTime = new Date(date).getTime();
const clientTime = new Date().getTime();
const offset = Math.round((serverTime - clientTime) / 1000);
if (Math.abs(offset) <= 300) {
// within 5 minutes
UserSettings.items.offset = Math.round(
(serverTime - clientTime) / 1000
);
UserSettings.commitItems();
return resolve("updateSuccess");
} else {
return resolve("clock_too_far_off");
}
}
};
xhr.send();
} catch (error) {
return reject(error as Error);
}
}
);
}