-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclient-id.js
More file actions
50 lines (50 loc) · 1.56 KB
/
client-id.js
File metadata and controls
50 lines (50 loc) · 1.56 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
let fallbackClientId;
function generateClientId() {
return `${Math.round(Math.random() * (Math.pow(2, 31) - 1))}.${Math.round(Date.now() / 1000)}`;
}
function setClientIdCookie(clientId) {
const value = `GH1.1.${clientId}`;
const now = Date.now();
const expires = new Date(now + 1 * 365 * 86400 * 1000).toUTCString();
let { domain } = document;
if (domain.endsWith('.github.com')) {
domain = 'github.com';
}
document.cookie = `_octo=${value}; expires=${expires}; path=/; domain=${domain}; secure; samesite=lax`;
}
function getClientIdFromCookie() {
let clientId;
const cookie = document.cookie;
const matches = cookie.match(/_octo=([^;]+)/g);
if (!matches) {
return;
}
let latestVersion = [0, 0];
for (const match of matches) {
const [, value] = match.split('=');
const [, version, ...clientIdPortions] = value.split('.');
const semanticVersion = version.split('-').map(Number);
if (semanticVersion > latestVersion) {
latestVersion = semanticVersion;
clientId = clientIdPortions.join('.');
}
}
return clientId;
}
export function getOrCreateClientId() {
try {
const existingId = getClientIdFromCookie();
if (existingId) {
return existingId;
}
const clientId = generateClientId();
setClientIdCookie(clientId);
return clientId;
}
catch (_) {
if (!fallbackClientId) {
fallbackClientId = generateClientId();
}
return fallbackClientId;
}
}