Repository navigation
Expand file tree
/
Copy pathauth.js
More file actions
175 lines (156 loc) · 5.89 KB
/
Copy pathauth.js
File metadata and controls
175 lines (156 loc) · 5.89 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
(function () {
const isBrowser = typeof window !== 'undefined' && typeof window.document !== 'undefined';
const isNode = !isBrowser;
// Provide minimal Node helpers for unit tests (do not affect browser globals)
if (isNode) {
if (typeof atob === 'undefined') {
global.atob = (b64) => Buffer.from(b64, 'base64').toString('binary');
}
}
const API_ORIGIN = 'https://source-score.onrender.com';
const API_BASE = API_ORIGIN + '/api/v1';
const AUTH_TOKEN_URL = API_ORIGIN + '/auth/token';
const CLIENT_ID = 'web-dashboard';
const AUTH_CACHE_KEY = 'sourceScoreJwtToken';
let tokenRequest = null;
let tokenInvalidationTimer = null;
function invalidateAuthToken(tokenToInvalidate) {
try {
if (tokenToInvalidate) {
const raw = localStorage.getItem(AUTH_CACHE_KEY);
const cached = raw ? JSON.parse(raw) : null;
if (!cached || cached.token !== tokenToInvalidate) return;
}
localStorage.removeItem(AUTH_CACHE_KEY);
} catch (err) {
localStorage.removeItem(AUTH_CACHE_KEY);
}
}
function scheduleTokenInvalidation(cached) {
if (tokenInvalidationTimer) clearTimeout(tokenInvalidationTimer);
if (!cached || !cached.expiresAt) return;
const delay = Math.max(cached.expiresAt - Date.now(), 0);
tokenInvalidationTimer = setTimeout(() => invalidateAuthToken(cached.token), delay);
}
function parseJwtPayload(token) {
try {
const payload = token.split('.')[1];
if (!payload) return null;
const base64 = payload.replace(/-/g, '+').replace(/_/g, '/');
const padded = base64 + '='.repeat((4 - base64.length % 4) % 4);
return JSON.parse(atob(padded));
} catch (err) {
return null;
}
}
function getTokenExpiresAt(token) {
const payload = parseJwtPayload(token);
if (!payload) throw new Error('Token payload missing');
// Accept several common expiry fields: standard 'exp' (seconds),
// 'ExpiresAt' or 'expiresAt' (string or number), or 'expires_at'.
let expiresAt = null;
if (payload.exp != null) {
// 'exp' is the standard JWT claim (seconds since epoch)
expiresAt = payload.exp;
} else if (payload.ExpiresAt != null) {
expiresAt = payload.ExpiresAt;
} else if (payload.expiresAt != null) {
expiresAt = payload.expiresAt;
} else if (payload.expires_at != null) {
expiresAt = payload.expires_at;
}
if (expiresAt == null) throw new Error('Token payload missing ExpiresAt/exp');
// Numeric timestamps may be in seconds (<= 1e12) or milliseconds.
if (typeof expiresAt === 'number') {
return expiresAt > 1000000000000 ? expiresAt : expiresAt * 1000;
}
// Numeric strings
if (typeof expiresAt === 'string' && /^\d+$/.test(expiresAt)) {
const numericExpiresAt = Number(expiresAt);
return numericExpiresAt > 1000000000000 ? numericExpiresAt : numericExpiresAt * 1000;
}
// Try parseable date string
const parsed = Date.parse(expiresAt);
if (Number.isNaN(parsed)) throw new Error('Token ExpiresAt is invalid');
return parsed;
}
function getCachedAuthToken() {
try {
const raw = localStorage.getItem(AUTH_CACHE_KEY);
if (!raw) return null;
const cached = JSON.parse(raw);
if (!cached || !cached.token || !cached.expiresAt) {
invalidateAuthToken();
return null;
}
if (Date.now() >= cached.expiresAt) {
invalidateAuthToken(cached.token);
return null;
}
scheduleTokenInvalidation(cached);
return cached;
} catch (err) {
invalidateAuthToken();
return null;
}
}
function cacheAuthToken(token) {
const expiresAt = getTokenExpiresAt(token);
if (Date.now() >= expiresAt) throw new Error('Received expired token');
const cached = { token, expiresAt };
try {
localStorage.setItem(
AUTH_CACHE_KEY,
JSON.stringify(cached)
);
} catch (err) {
console.warn('Failed to cache auth token:', err);
}
scheduleTokenInvalidation(cached);
return token;
}
async function fetchAuthToken() {
const res = await fetch(AUTH_TOKEN_URL, {
method: 'POST',
headers: { 'Client-ID': CLIENT_ID },
signal: AbortSignal.timeout(90000),
});
if (!res.ok) throw new Error(`Token HTTP ${res.status}`);
const data = await res.json();
if (!data || !data.token) throw new Error('Token response missing token');
return cacheAuthToken(data.token);
}
async function getAuthToken() {
const cached = getCachedAuthToken();
if (cached) return cached.token;
if (!tokenRequest) {
tokenRequest = fetchAuthToken().finally(() => {
tokenRequest = null;
});
}
return tokenRequest;
}
async function getApiHeaders() {
const token = await getAuthToken();
return {
'Client-ID': CLIENT_ID,
'Authorization': `Bearer ${token}`
};
}
if (isBrowser) {
scheduleTokenInvalidation(getCachedAuthToken());
window.SourceScoreAuth = {
apiBase: API_BASE,
getApiHeaders,
getAuthToken,
invalidateAuthToken
};
}
// Export helpers for Node-based unit tests
if (typeof module !== 'undefined' && module.exports) {
module.exports = {
parseJwtPayload,
getTokenExpiresAt
};
}
})();