-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathtemplate-scripts.ts
More file actions
247 lines (231 loc) · 10.1 KB
/
template-scripts.ts
File metadata and controls
247 lines (231 loc) · 10.1 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
function getButtonInjectionScript(): string {
return `
function findConfigureButton(container) {
let btn = Array.from(container.querySelectorAll('button')).find(b => b.textContent?.trim() === 'Configure');
if (!btn) btn = Array.from(container.querySelectorAll('button')).find(b => b.textContent?.toLowerCase().trim() === 'configure');
if (!btn) {
const buttons = Array.from(container.querySelectorAll('button'));
if (buttons.length === 0) return null;
btn = buttons[buttons.length - 1];
}
return btn;
}
function createLoginButton(configureButton, scalarApiReference, showModal) {
const link = document.createElement('button');
const currentToken = localStorage.getItem('scalar-token');
link.textContent = currentToken ? 'Logout' : 'Login';
link.setAttribute('data-login-link', 'true');
link.setAttribute('type', 'button');
const style = window.getComputedStyle(configureButton);
const props = ['background', 'border', 'color', 'cursor', 'fontSize', 'fontFamily', 'fontWeight', 'fontStyle', 'letterSpacing', 'lineHeight', 'padding', 'margin', 'borderRadius', 'transition', 'display', 'alignItems', 'gap', 'textDecoration', 'textTransform'];
link.style.cssText = props.map(p => p + ': ' + style[p]).join('; ') + ';';
if (configureButton.className) link.className = configureButton.className;
link.onmouseenter = () => {
const hover = window.getComputedStyle(configureButton, ':hover');
if (hover.backgroundColor) link.style.backgroundColor = hover.backgroundColor;
};
link.onmouseleave = () => link.style.backgroundColor = style.backgroundColor;
link.onclick = (e) => {
e.preventDefault();
e.stopPropagation();
const token = localStorage.getItem('scalar-token');
if (token) {
localStorage.removeItem('scalar-token');
updateScalarAuth(scalarApiReference, '');
location.reload();
} else {
showModal();
}
};
configureButton.insertAdjacentElement('afterend', link);
return true;
}
function injectLoginLinkInternal(scalarApiReference, showModal) {
let injected = false;
let attempts = 0;
const maxAttempts = 150;
const tryInject = () => {
attempts++;
if (document.querySelector('[data-login-link]')) return true;
const devBtn = Array.from(document.querySelectorAll('button')).find(b => b.textContent?.trim() === 'Developer Tools');
if (devBtn) {
let container = devBtn.parentElement;
while (container && container !== document.body) {
const buttons = Array.from(container.querySelectorAll('button'));
if (buttons.length >= 4 && buttons.includes(devBtn)) {
const cfgBtn = findConfigureButton(container);
if (cfgBtn) return createLoginButton(cfgBtn, scalarApiReference, showModal);
}
container = container.parentElement;
}
if (devBtn.parentElement) {
const parentBtns = Array.from(devBtn.parentElement.querySelectorAll('button'));
if (parentBtns.length >= 2 && parentBtns.some(b => b.textContent?.trim() === 'Configure')) {
const cfgBtn = findConfigureButton(devBtn.parentElement);
if (cfgBtn) return createLoginButton(cfgBtn, scalarApiReference, showModal);
}
}
}
return false;
};
window.updateLoginButton = () => {
const link = document.querySelector('[data-login-link]');
if (link) link.textContent = localStorage.getItem('scalar-token') ? 'Logout' : 'Login';
};
if (tryInject()) return;
const observer = new MutationObserver(() => {
if (!injected && tryInject()) {
injected = true;
observer.disconnect();
}
});
observer.observe(document.body, { childList: true, subtree: true });
const interval = setInterval(() => {
if (injected || tryInject() || attempts >= maxAttempts) {
clearInterval(interval);
observer.disconnect();
}
}, 100);
}`
}
export function getInitScript(opts: {
apiUrl: string
openApiUrl: string
callbackUrl: string
jwtToken: string | null
verificationId?: string
}): string {
const { apiUrl, openApiUrl, callbackUrl, jwtToken, verificationId } = opts
const jwtJson = jwtToken ? JSON.stringify(jwtToken) : 'null'
const verificationIdJson = verificationId ? JSON.stringify(verificationId) : 'null'
const buttonScript = getButtonInjectionScript()
return `
(function() {
const apiUrl = ${JSON.stringify(apiUrl)};
const callbackUrl = ${JSON.stringify(callbackUrl)};
const openApiUrl = ${JSON.stringify(openApiUrl)};
const jwtFromServer = ${jwtJson};
const verificationIdFromUrl = ${verificationIdJson};
function updateScalarAuth(scalarApiReference, token) {
const authConfig = {
preferredSecurityScheme: 'bearerAuth',
securitySchemes: { bearerAuth: { token } },
};
if (scalarApiReference?.updateConfiguration) {
scalarApiReference.updateConfiguration({ authentication: authConfig });
} else if (scalarApiReference?.updateAuthentication) {
scalarApiReference.updateAuthentication(authConfig);
}
}
const storedToken = localStorage.getItem('scalar-token');
const token = jwtFromServer || storedToken;
let scalarApiReference = null;
try {
scalarApiReference = Scalar.createApiReference('#scalar-container', {
url: openApiUrl,
theme: 'moon',
authentication: {
preferredSecurityScheme: 'bearerAuth',
securitySchemes: { bearerAuth: { token: token || '' } },
},
});
} catch (error) {
console.error('Failed to initialize Scalar:', error);
}
if (jwtFromServer) {
localStorage.setItem('scalar-token', jwtFromServer);
history.replaceState({}, '', '/reference');
updateScalarAuth(scalarApiReference, jwtFromServer);
} else if (verificationIdFromUrl) {
const banner = document.createElement('div');
banner.id = 'verify-banner';
banner.style.cssText = 'position:fixed;top:0;left:0;right:0;padding:12px 16px;background:#1e3a5f;color:#fff;display:flex;align-items:center;justify-content:center;gap:12px;flex-wrap:wrap;z-index:10000;font-size:14px;';
banner.innerHTML = '<span>Enter the 6-digit code from your email:</span><form style="display:inline-flex;gap:8px;align-items:center;flex-wrap:wrap;"><input type="text" inputmode="numeric" pattern="\\\\d*" maxlength="6" placeholder="000000" style="width:80px;padding:6px;font-size:14px;border-radius:4px;"/><button type="submit" style="padding:6px 12px;background:#667eea;color:#fff;border:none;border-radius:4px;cursor:pointer;">Verify</button><span data-verify-error="" aria-live="polite" style="color:#ef4444;font-size:12px;margin-left:8px;"></span></form>';
document.body.prepend(banner);
banner.querySelector('form')?.addEventListener('submit', async (e) => {
e.preventDefault();
const input = banner.querySelector('input');
const code = input?.value?.trim();
if (!code || code.length !== 6) return;
const errorEl = banner.querySelector('[data-verify-error]');
if (errorEl) errorEl.textContent = '';
try {
const res = await fetch(apiUrl + '/auth/magiclink/verify', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ verificationId: verificationIdFromUrl, token: code }),
});
if (res.ok) {
const data = await res.json();
localStorage.setItem('scalar-token', data.token);
history.replaceState({}, '', '/reference');
updateScalarAuth(scalarApiReference, data.token);
banner.remove();
if (window.updateLoginButton) window.updateLoginButton();
} else {
let msg = 'Verification failed. Please try again.';
try {
const body = await res.json();
msg = body.message || msg;
} catch {}
const errDiv = banner.querySelector('[data-verify-error]');
if (errDiv) errDiv.textContent = msg;
}
} catch (err) {
const msg = 'Verification failed. Please try again.';
const errDiv = banner.querySelector('[data-verify-error]');
if (errDiv) errDiv.textContent = msg;
}
});
}
window.scalarApiReference = scalarApiReference;
const modalOverlay = document.getElementById('modal-overlay');
const closeModal = document.getElementById('close-modal');
const loginForm = document.getElementById('login-form');
const emailInput = document.getElementById('email');
const emailError = document.getElementById('email-error');
const emailSuccess = document.getElementById('email-success');
const submitButton = document.getElementById('submit-button');
function showModal() {
modalOverlay.classList.add('show');
}
function hideModal() {
modalOverlay.classList.remove('show');
emailInput.value = '';
emailError.textContent = '';
emailSuccess.textContent = '';
}
window.showLogin = showModal;
closeModal.addEventListener('click', hideModal);
modalOverlay.addEventListener('click', (e) => {
if (e.target === modalOverlay) hideModal();
});
loginForm.addEventListener('submit', async (e) => {
e.preventDefault();
const email = emailInput.value.trim();
emailError.textContent = '';
emailSuccess.textContent = '';
submitButton.disabled = true;
submitButton.textContent = 'Sending...';
try {
const response = await fetch(apiUrl + '/auth/magiclink/request', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ email, callbackUrl }),
});
const data = await response.json();
if (!response.ok) throw new Error(data.message || 'Failed to send magic link');
emailSuccess.textContent = 'Check your email for the magic link';
submitButton.textContent = 'Magic link sent';
} catch (error) {
emailError.textContent = error.message || 'Failed to send magic link. Please try again.';
submitButton.textContent = 'Send magic link';
} finally {
submitButton.disabled = false;
}
});
${buttonScript}
injectLoginLinkInternal(scalarApiReference, showModal);
})();
`
}