fix: improve header handling and error checking in paste loading

This commit is contained in:
2026-03-30 22:51:28 -04:00
parent 094c8e5e08
commit 6d99a06c17
@@ -6,34 +6,34 @@ import { error } from '@sveltejs/kit';
export const load: PageServerLoad = async ({ params, fetch, url, cookies, parent, request }) => { export const load: PageServerLoad = async ({ params, fetch, url, cookies, parent, request }) => {
const { id } = params; const { id } = params;
if (!id) {
// realistically this shouldnt happen
throw error(400, 'Missing paste id.');
}
const parentData = await parent().catch(() => null); const parentData = await parent().catch(() => null);
const token = getServerToken(cookies); const token = getServerToken(cookies);
const userAgent = request.headers.get('user-agent') ?? 'Sharpbin Client'; const userAgent = request.headers.get('user-agent') ?? 'Sharpbin Client';
const clientHeaders = new Headers(request.headers);
clientHeaders.set('Authorization', token ? `Bearer ${token}` : '');
clientHeaders.set('User-Agent', userAgent);
const pasteRes = await fetch(`${apiUrl}/api/paste/${id}`, { const pasteRes = await fetch(`${apiUrl}/api/paste/${id}`, { headers: clientHeaders });
headers: {
Authorization: token ? `Bearer ${token}` : ''
}
});
if (pasteRes.status === 404) { if (pasteRes.status === 404) {
throw error(pasteRes.status, 'Paste not found.'); throw error(pasteRes.status, 'Paste not found.');
} }
const viewedHeaders = new Headers(clientHeaders);
viewedHeaders.set('X-Internal-API-Key', viewInternalApiKey);
const viewed = await fetch(`${apiUrl}/api/paste/${id}/view`, { const viewed = await fetch(`${apiUrl}/api/paste/${id}/view`, {
method: 'POST', method: 'POST',
headers: { headers: viewedHeaders
'X-Internal-API-Key': viewInternalApiKey,
Authorization: token ? `Bearer ${token}` : '',
'User-Agent': userAgent
}
}); });
const pasteData = await pasteRes.json(); const pasteData = await pasteRes.json();
const paste = pasteData.paste as Paste; const paste = pasteData.paste as Paste;
if (viewed.status === 200) { if (viewed.status === 200) {
const viewJson = await viewed.json(); const viewJson = await viewed.json();
if (viewJson.success === true && viewJson.message === 'Paste view recorded.') { if (viewJson.success === true && viewJson.message === 'Paste view recorded.') {
pasteData.views += 1; pasteData.views += 1;
@@ -44,8 +44,8 @@ export const load: PageServerLoad = async ({ params, fetch, url, cookies, parent
); );
} }
const pasteContent = await fetch(`/api/paste/${id}/raw`); const pasteContent = await fetch(`${apiUrl}/api/paste/${id}/raw`, { headers: clientHeaders });
const pasteOptions = await fetch('/api/paste/info'); const pasteOptions = await fetch(`${apiUrl}/api/paste/info`, { headers: clientHeaders });
const options = await pasteOptions.json(); const options = await pasteOptions.json();
const content = await pasteContent.text(); const content = await pasteContent.text();