-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
368 lines (312 loc) · 12.6 KB
/
Copy pathscript.js
File metadata and controls
368 lines (312 loc) · 12.6 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
// JWT Decoder & Validator
class JWTDecoder {
constructor() {
this.jwtInput = document.getElementById('jwt-input');
this.headerContent = document.getElementById('header-content');
this.payloadContent = document.getElementById('payload-content');
this.timestampInfo = document.getElementById('timestamp-info');
this.algorithmSelect = document.getElementById('algorithm-select');
this.secretInput = document.getElementById('secret-input');
this.verificationStatus = document.getElementById('verification-status');
this.errorMessage = document.getElementById('error-message');
this.currentJWT = null;
this.currentHeader = null;
this.currentPayload = null;
this.initializeEventListeners();
}
initializeEventListeners() {
// Real-time JWT input processing
this.jwtInput.addEventListener('input', () => {
this.processJWT();
this.applyColorCoding();
});
// Verification controls
this.algorithmSelect.addEventListener('change', () => {
this.verifySignature();
});
this.secretInput.addEventListener('input', () => {
this.verifySignature();
});
// Initial color coding setup
this.jwtInput.addEventListener('keyup', () => this.applyColorCoding());
this.jwtInput.addEventListener('paste', () => {
setTimeout(() => this.applyColorCoding(), 10);
});
}
processJWT() {
const jwtString = this.jwtInput.value.trim();
if (!jwtString) {
this.clearAll();
return;
}
try {
// Basic JWT format validation
const parts = jwtString.split('.');
if (parts.length !== 3) {
throw new Error('Invalid JWT format: must have 3 parts separated by dots');
}
// Decode header and payload
const header = this.decodeBase64Url(parts[0]);
const payload = this.decodeBase64Url(parts[1]);
this.currentJWT = jwtString;
this.currentHeader = JSON.parse(header);
this.currentPayload = JSON.parse(payload);
// Update displays
this.displayHeader(this.currentHeader);
this.displayPayload(this.currentPayload);
this.updateAlgorithmSelect();
this.verifySignature();
this.hideError();
} catch (error) {
this.showError(`Invalid JWT: ${error.message}`);
this.clearDecodedSections();
}
}
decodeBase64Url(str) {
// Add padding if needed
let base64 = str.replace(/-/g, '+').replace(/_/g, '/');
while (base64.length % 4) {
base64 += '=';
}
try {
return atob(base64);
} catch (error) {
throw new Error('Invalid base64 encoding');
}
}
displayHeader(header) {
this.headerContent.textContent = JSON.stringify(header, null, 2);
}
displayPayload(payload) {
this.payloadContent.textContent = JSON.stringify(payload, null, 2);
this.displayTimestamps(payload);
}
displayTimestamps(payload) {
const timestampFields = ['iat', 'exp', 'nbf'];
const timestampInfo = [];
timestampFields.forEach(field => {
if (payload[field]) {
const timestamp = payload[field];
const date = new Date(timestamp * 1000);
const now = new Date();
const diff = date.getTime() - now.getTime();
let relativeTime;
if (Math.abs(diff) < 60000) {
relativeTime = 'just now';
} else if (diff > 0) {
relativeTime = this.formatRelativeTime(diff, 'in');
} else {
relativeTime = this.formatRelativeTime(Math.abs(diff), 'ago');
}
const fieldName = {
'iat': 'Issued At',
'exp': 'Expires',
'nbf': 'Not Before'
}[field];
timestampInfo.push(`
<div class="timestamp-item">
<strong>${fieldName}:</strong> ${date.toLocaleString()} (${relativeTime})
</div>
`);
}
});
this.timestampInfo.innerHTML = timestampInfo.join('');
}
formatRelativeTime(milliseconds, prefix) {
const seconds = Math.floor(milliseconds / 1000);
const minutes = Math.floor(seconds / 60);
const hours = Math.floor(minutes / 60);
const days = Math.floor(hours / 24);
if (days > 0) {
return `${prefix} ${days} day${days > 1 ? 's' : ''}`;
} else if (hours > 0) {
return `${prefix} ${hours} hour${hours > 1 ? 's' : ''}`;
} else if (minutes > 0) {
return `${prefix} ${minutes} minute${minutes > 1 ? 's' : ''}`;
} else {
return `${prefix} ${seconds} second${seconds > 1 ? 's' : ''}`;
}
}
updateAlgorithmSelect() {
if (this.currentHeader && this.currentHeader.alg) {
this.algorithmSelect.value = this.currentHeader.alg;
}
}
async verifySignature() {
if (!this.currentJWT || !this.secretInput.value.trim()) {
this.updateVerificationStatus('not-verified', 'Signature Not Verified');
return;
}
try {
const algorithm = this.algorithmSelect.value;
const secret = this.secretInput.value.trim();
const isValid = await this.validateJWTSignature(this.currentJWT, secret, algorithm);
if (isValid) {
this.updateVerificationStatus('verified', '✔️ Signature Verified');
} else {
this.updateVerificationStatus('invalid', '❌ Invalid Signature');
}
} catch (error) {
this.updateVerificationStatus('invalid', `❌ Verification Error: ${error.message}`);
}
}
async validateJWTSignature(jwt, secret, algorithm) {
try {
// For HMAC algorithms (HS256, HS384, HS512)
if (algorithm.startsWith('HS')) {
const encoder = new TextEncoder();
const secretKey = await crypto.subtle.importKey(
'raw',
encoder.encode(secret),
{ name: 'HMAC', hash: this.getHashAlgorithm(algorithm) },
false,
['verify']
);
const parts = jwt.split('.');
const data = encoder.encode(parts[0] + '.' + parts[1]);
const signature = this.base64UrlDecode(parts[2]);
return await crypto.subtle.verify('HMAC', secretKey, signature, data);
}
// For RSA algorithms (RS256, RS384, RS512)
if (algorithm.startsWith('RS')) {
const publicKey = await this.importRSAPublicKey(secret, algorithm);
const parts = jwt.split('.');
const data = new TextEncoder().encode(parts[0] + '.' + parts[1]);
const signature = this.base64UrlDecode(parts[2]);
return await crypto.subtle.verify(
{ name: 'RSASSA-PKCS1-v1_5' },
publicKey,
signature,
data
);
}
// For ECDSA algorithms (ES256, ES384, ES512)
if (algorithm.startsWith('ES')) {
const publicKey = await this.importECDSAPublicKey(secret, algorithm);
const parts = jwt.split('.');
const data = new TextEncoder().encode(parts[0] + '.' + parts[1]);
const signature = this.base64UrlDecode(parts[2]);
return await crypto.subtle.verify(
{ name: 'ECDSA', hash: this.getHashAlgorithm(algorithm) },
publicKey,
signature,
data
);
}
throw new Error(`Unsupported algorithm: ${algorithm}`);
} catch (error) {
throw new Error(`Signature verification failed: ${error.message}`);
}
}
getHashAlgorithm(algorithm) {
const hashMap = {
'HS256': 'SHA-256',
'HS384': 'SHA-384',
'HS512': 'SHA-512',
'RS256': 'SHA-256',
'RS384': 'SHA-384',
'RS512': 'SHA-512',
'ES256': 'SHA-256',
'ES384': 'SHA-384',
'ES512': 'SHA-512'
};
return hashMap[algorithm] || 'SHA-256';
}
async importRSAPublicKey(pemKey, algorithm) {
const binaryDer = this.pemToBinary(pemKey);
return await crypto.subtle.importKey(
'spki',
binaryDer,
{
name: 'RSASSA-PKCS1-v1_5',
hash: this.getHashAlgorithm(algorithm)
},
false,
['verify']
);
}
async importECDSAPublicKey(pemKey, algorithm) {
const binaryDer = this.pemToBinary(pemKey);
const namedCurve = algorithm === 'ES256' ? 'P-256' :
algorithm === 'ES384' ? 'P-384' : 'P-521';
return await crypto.subtle.importKey(
'spki',
binaryDer,
{
name: 'ECDSA',
namedCurve: namedCurve
},
false,
['verify']
);
}
pemToBinary(pem) {
const base64 = pem
.replace(/-----BEGIN.*-----/g, '')
.replace(/-----END.*-----/g, '')
.replace(/\s/g, '');
const binaryString = atob(base64);
const bytes = new Uint8Array(binaryString.length);
for (let i = 0; i < binaryString.length; i++) {
bytes[i] = binaryString.charCodeAt(i);
}
return bytes.buffer;
}
base64UrlDecode(str) {
let base64 = str.replace(/-/g, '+').replace(/_/g, '/');
while (base64.length % 4) {
base64 += '=';
}
const binaryString = atob(base64);
const bytes = new Uint8Array(binaryString.length);
for (let i = 0; i < binaryString.length; i++) {
bytes[i] = binaryString.charCodeAt(i);
}
return bytes.buffer;
}
updateVerificationStatus(status, message) {
this.verificationStatus.textContent = message;
this.verificationStatus.className = `verification-status ${status}`;
}
applyColorCoding() {
const text = this.jwtInput.value;
const parts = text.split('.');
if (parts.length === 3) {
// Create a temporary div to apply color coding
const coloredText = `<span class="jwt-header">${parts[0]}</span>.<span class="jwt-payload">${parts[1]}</span>.<span class="jwt-signature">${parts[2]}</span>`;
// Note: Direct HTML manipulation in textarea is not possible
// This is a limitation - we'll use CSS classes on the sections instead
// The color coding will be visual feedback through the section borders
}
}
clearAll() {
this.clearDecodedSections();
this.updateVerificationStatus('not-verified', 'Signature Not Verified');
this.hideError();
}
clearDecodedSections() {
this.headerContent.textContent = '';
this.payloadContent.textContent = '';
this.timestampInfo.innerHTML = '';
this.currentJWT = null;
this.currentHeader = null;
this.currentPayload = null;
}
showError(message) {
this.errorMessage.textContent = message;
this.errorMessage.classList.remove('hidden');
// Auto-hide error after 5 seconds
setTimeout(() => {
this.hideError();
}, 5000);
}
hideError() {
this.errorMessage.classList.add('hidden');
}
}
// Initialize the JWT Decoder when the page loads
document.addEventListener('DOMContentLoaded', () => {
new JWTDecoder();
});
// Sample JWT for testing (optional - can be removed)
const sampleJWT = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c';