-
Notifications
You must be signed in to change notification settings - Fork 11
/
scalar-api-interaction.js
431 lines (372 loc) · 16.5 KB
/
scalar-api-interaction.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
(function() {
console.log("Script loaded and running...");
function hideElement() {
let elementsToHide = [];
elementsToHide.push(document.querySelector('#app > div.api-references-layout > div.scalar-app.scalar-api-reference.references-layout.references-sidebar.references-sidebar-mobile-open > section > div.narrow-references-container > div:nth-child(2) > section > div > div > div:nth-child(2) > div > div > div:nth-child(2)'));
elementsToHide.push(document.querySelector('#app > div.api-references-layout > div.scalar-app.scalar-api-reference.references-layout.references-sidebar.references-sidebar-mobile-open > section > div.narrow-references-container > div:nth-child(2) > section > div > div > div:nth-child(2) > div > div > div:nth-child(3)'));
elementsToHide
.filter(element => element !== null)
.forEach(elementToHide => {
elementToHide.style.display = 'none';
console.log("Element hidden successfully");
});
}
setTimeout( () => {
hideElement();
}, 3000)
function handleRouteChange() {
console.log("Route change detected");
// Remove existing injected elements to avoid duplicates
const existingContainer = document.getElementById('custom-input-container');
if (existingContainer) {
existingContainer.remove();
}
hideElement();
injectFields();
}
// 1. Watch for URL changes
let lastUrl = location.href;
new MutationObserver(() => {
const url = location.href;
if (url !== lastUrl) {
lastUrl = url;
console.log("URL changed to:", url);
handleRouteChange();
}
}).observe(document, { subtree: true, childList: true });
// 2. Watch for specific container changes
const appContainer = document.querySelector('#app');
if (appContainer) {
new MutationObserver((mutations) => {
for (const mutation of mutations) {
if (mutation.type === 'childList' &&
mutation.target.classList.contains('api-references-layout')) {
console.log("API reference layout changed");
handleRouteChange();
}
}
}).observe(appContainer, {
childList: true,
subtree: true
});
}
// Test DOM query first
const testQuery = document.querySelector('#app');
console.log("Can find #app:", !!testQuery);
// Function to inject the input fields
function injectFields() {
try {
console.log("Attempting to inject fields...");
const mainContainer = document.querySelector('#app > div.api-references-layout > div.scalar-app.scalar-api-reference.references-layout.references-sidebar.references-sidebar-mobile-open > section > div.narrow-references-container > div:nth-child(2) > section > div > div > div:nth-child(2) > div > div');
console.log("Found main container:", !!mainContainer);
if (!mainContainer) {
console.log("Main container not found, will retry in 2 seconds");
setTimeout(injectFields, 2000);
return;
}
console.log("Creating input container...");
// Create input container
const inputContainer = document.createElement('div');
inputContainer.id = 'custom-input-container';
inputContainer.style.padding = '1rem';
inputContainer.style.position = 'relative';
// Create notification
const notification = document.createElement('div');
notification.id = 'api-notification';
notification.style.backgroundColor = 'transparent';
notification.style.color = '#6c757d';
notification.style.padding = '10px';
notification.style.borderRadius = '4px';
notification.style.marginBottom = '1rem';
notification.style.display = 'none';
notification.innerHTML = "You can test the API using the API Reference page only in Sandbox workspaces. <br>Ensure that the SERVER URL value above is set to the Sandbox base URL.";
// Create input fields container
const fieldsContainer = document.createElement('div');
fieldsContainer.id = 'fields-container';
fieldsContainer.style.display = 'none'; // Hidden by default
// Create API Key label and input
const apiKeyLabel = document.createElement('label');
apiKeyLabel.textContent = 'API Key:';
apiKeyLabel.style.display = 'block';
apiKeyLabel.style.marginBottom = '5px';
apiKeyLabel.style.fontWeight = '500';
apiKeyLabel.style.color = '#6c757d';
const apiKeyInput = document.createElement('input');
apiKeyInput.type = 'text';
apiKeyInput.id = 'apiKeyInput';
apiKeyInput.style.width = '100%';
apiKeyInput.style.marginBottom = '10px';
apiKeyInput.style.padding = '8px';
apiKeyInput.style.borderRadius = '4px';
apiKeyInput.style.border = '1px solid #ddd';
apiKeyInput.placeholder = 'Enter API Key';
apiKeyInput.value = localStorage.getItem('apiKey') || '';
// Create API Secret label and input
const apiSecretLabel = document.createElement('label');
apiSecretLabel.textContent = 'API Secret (.key file):';
apiSecretLabel.style.display = 'block';
apiSecretLabel.style.marginBottom = '5px';
apiSecretLabel.style.marginTop = '10px';
apiSecretLabel.style.fontWeight = '500';
apiSecretLabel.style.color = '#6c757d';
const apiSecretInput = document.createElement('input');
apiSecretInput.type = 'file';
apiSecretInput.id = 'apiSecretInput';
apiSecretInput.accept = '.key';
apiSecretInput.style.width = '100%';
apiSecretInput.style.marginBottom = '15px';
apiSecretInput.style.padding = '8px';
apiSecretInput.style.borderRadius = '4px';
apiSecretInput.style.border = '1px solid #ddd';
// Create save button with updated styling
const saveButton = document.createElement('button');
saveButton.textContent = 'Save Credentials';
saveButton.style.padding = '8px 16px';
saveButton.style.backgroundColor = '#1677ff';
saveButton.style.color = 'white';
saveButton.style.border = 'none';
saveButton.style.borderRadius = '4px';
saveButton.style.cursor = 'pointer';
saveButton.style.display = 'block';
saveButton.style.margin = '0 auto';
saveButton.disabled = true;
// Add hover effect
saveButton.onmouseover = function() {
if (!this.disabled) {
this.style.backgroundColor = '#4096ff';
}
};
saveButton.onmouseout = function() {
if (!this.disabled) {
this.style.backgroundColor = '#1677ff';
}
};
// Function to disable inputs and switch to edit mode
function setEditMode() {
apiKeyInput.disabled = true;
apiSecretInput.disabled = true;
saveButton.textContent = 'Edit Credentials';
saveButton.disabled = false;
saveButton.style.backgroundColor = '#1677ff';
saveButton.style.cursor = 'pointer';
}
// Function to enable inputs and switch to save mode
function setSaveMode() {
apiKeyInput.disabled = false;
apiSecretInput.disabled = false;
saveButton.textContent = 'Save Credentials';
validateInputs();
}
// Update save button click handler
saveButton.onclick = function() {
if (saveButton.textContent === 'Save Credentials') {
if (apiKeyInput.value.trim() && localStorage.getItem('apiSecret')) {
localStorage.setItem('apiKey', apiKeyInput.value.trim());
alert('API credentials saved successfully!');
setEditMode();
}
} else {
setSaveMode();
}
};
// Update initial state based on existing credentials
function updateInitialState() {
const hasApiKey = localStorage.getItem('apiKey');
const hasApiSecret = localStorage.getItem('apiSecret');
if (hasApiKey && hasApiSecret) {
apiKeyInput.value = hasApiKey;
setEditMode();
} else {
setSaveMode();
}
}
// Update validation function
function validateInputs() {
if (saveButton.textContent === 'Edit Credentials') {
return;
}
const hasApiKey = apiKeyInput.value.trim() !== '';
const hasApiSecret = localStorage.getItem('apiSecret');
saveButton.disabled = !(hasApiKey && hasApiSecret);
saveButton.style.backgroundColor = saveButton.disabled ? '#d9d9d9' : '#1677ff';
saveButton.style.cursor = saveButton.disabled ? 'not-allowed' : 'pointer';
}
// Add input event listeners
apiKeyInput.addEventListener('input', validateInputs);
apiSecretInput.addEventListener('change', function(e) {
const file = e.target.files[0];
if (file) {
const reader = new FileReader();
reader.onload = function(e) {
localStorage.setItem('apiSecret', e.target.result);
validateInputs();
};
reader.readAsText(file);
}
});
console.log("Adding elements to containers...");
// Add elements to the fields container
fieldsContainer.appendChild(apiKeyLabel);
fieldsContainer.appendChild(apiKeyInput);
fieldsContainer.appendChild(apiSecretLabel);
fieldsContainer.appendChild(apiSecretInput);
fieldsContainer.appendChild(saveButton);
// Add all elements to the main container
inputContainer.appendChild(notification);
inputContainer.appendChild(fieldsContainer);
console.log("Attempting to append to main container...");
// Add the input container to the main container
mainContainer.appendChild(inputContainer);
console.log("Elements appended successfully");
// Update the visibility function
function updateOverlayVisibility() {
const urlElement = mainContainer.querySelector('.base-url');
if (!urlElement) {
console.warn('URL element not found');
return;
}
const currentUrl = urlElement.textContent;
console.log('Current URL:', currentUrl); // Debug log
const notification = document.getElementById('api-notification');
const fieldsContainer = document.getElementById('fields-container');
if (!notification || !fieldsContainer) {
console.warn('Required elements not found');
return;
}
// Show notification and hide fields for any non-sandbox URL
if (!currentUrl.includes('sandbox-api.fireblocks.io')) {
console.log('Non-sandbox URL detected, showing notification'); // Debug log
notification.style.display = 'block';
fieldsContainer.style.display = 'none';
} else {
console.log('Sandbox URL detected, showing fields'); // Debug log
notification.style.display = 'none';
fieldsContainer.style.display = 'block';
validateInputs();
}
}
// Initial check
updateOverlayVisibility();
validateInputs();
// Set up the observer
const observer = new MutationObserver((mutations) => {
const urlElement = mainContainer.querySelector('.base-url');
if (urlElement) {
updateOverlayVisibility();
}
});
observer.observe(mainContainer, {
childList: true,
subtree: true,
characterData: true
});
// Call this after creating all elements and adding them to the container
updateInitialState();
} catch (error) {
console.error('Error in injectFields:', error);
console.log("Will retry in 2 seconds");
setTimeout(injectFields, 2000);
}
}
// Function to dynamically load the jsrsasign library
function loadJsrsasign(callback) {
var script = document.createElement('script');
script.src = "https://kjur.github.io/jsrsasign/jsrsasign-all-min.js";
script.onload = callback;
document.head.appendChild(script);
}
// Function to generate JWT using jsrsasign with detailed logging
async function generateJWT(apiKey, apiSecret, uri, body, method) {
await new Promise((resolve) => loadJsrsasign(resolve));
const header = {
alg: "RS256",
typ: "JWT"
};
const nonce = Date.now().toString();
const iat = Math.floor(Date.now() / 1000);
const exp = iat + 30;
let bodyToHash = '';
console.log(`Non-GET request (${method}), hashing the request body as an object:`, body);
if (body) {
try {
if (typeof body === 'string') {
bodyToHash = JSON.stringify(JSON.parse(body), null, 2);
} else {
bodyToHash = JSON.stringify(body, null, 2);
}
} catch (e) {
console.error('Error parsing body JSON for hashing:', e);
}
}
const bodyHash = KJUR.crypto.Util.sha256(bodyToHash);
const payload = {
uri,
nonce,
iat,
exp,
sub: apiKey,
bodyHash
};
const sHeader = JSON.stringify(header);
const sPayload = JSON.stringify(payload);
const jwt = KJUR.jws.JWS.sign("RS256", sHeader, sPayload, apiSecret);
console.log('Generated JWT:', jwt);
return jwt;
}
// Intercepting fetch requests
const originalFetch = window.fetch;
window.fetch = async function(input, init) {
const proxyURL = 'https://proxy.scalar.com/?scalar_url=';
const directURL = 'https://sandbox-api.fireblocks.io/v1';
let url = input;
let method = 'GET';
if (typeof input === 'object') {
url = input.url;
method = input.method || 'GET';
} else if (init && init.method) {
method = init.method;
}
// Check if this is a Fireblocks API request (either direct or already proxied)
const isFireblocksRequest = url && url.includes('fireblocks.io');
if (!isFireblocksRequest) {
return originalFetch(input, init);
}
try {
// Always ensure we're using the proxy URL
let finalUrl = url;
if (!url.includes(proxyURL)) {
finalUrl = `${proxyURL}${encodeURIComponent(url)}`;
}
// Extract the URI path for JWT generation
const urlObj = new URL(url.includes(proxyURL) ? decodeURIComponent(url.split('scalar_url=')[1]) : url);
const uri = '/v1' + urlObj.pathname.replace('/v1', '') + urlObj.search;
const apiKey = localStorage.getItem('apiKey') || 'No API Key Found';
const apiSecret = localStorage.getItem('apiSecret') || 'No API Secret Found';
const body = init?.body ? init.body : '';
const jwt = await generateJWT(apiKey, apiSecret, uri, body, method);
// Prepare the final request
const finalInit = {
...init,
headers: {
...init?.headers,
'X-API-Key': apiKey,
'Authorization': `Bearer ${jwt}`
}
};
// Update the input URL if it's an object
if (typeof input === 'object') {
input.url = finalUrl;
return originalFetch(input, finalInit);
} else {
return originalFetch(finalUrl, finalInit);
}
} catch (error) {
console.error('Error processing API request:', error);
return originalFetch(input, init);
}
};
console.log("Setting up initial injection...");
setTimeout(() => {
injectFields();
}, 1000);
})();