1
0
forked from Kieran/snort
snort4/functions/_middleware.ts

53 lines
1.7 KiB
TypeScript
Raw Normal View History

2024-01-10 16:15:26 +00:00
interface Env {}
const HOST = "snort.social";
export const onRequest: PagesFunction<Env> = async context => {
const u = new URL(context.request.url);
const prefixes = ["npub1", "nprofile1", "naddr1", "nevent1", "note1"];
2024-01-10 20:06:57 +00:00
const isEntityPath = prefixes.some(
a => u.pathname.startsWith(`/${a}`) || u.pathname.startsWith(`/e/${a}`) || u.pathname.startsWith(`/p/${a}`),
);
2024-01-10 16:15:26 +00:00
const nostrAddress = u.pathname.match(/^\/([a-zA-Z0-9_]+)$/i);
const next = await context.next();
2024-01-10 20:06:57 +00:00
if (u.pathname != "/" && (isEntityPath || nostrAddress)) {
//console.log("Handeling path: ", u.pathname, isEntityPath, nostrAddress[1]);
2024-01-10 16:15:26 +00:00
try {
2024-01-10 20:06:57 +00:00
let id = u.pathname.split("/").at(-1);
if (!isEntityPath && nostrAddress) {
2024-01-10 22:44:37 +00:00
id = `${id}@${HOST}`;
2024-01-10 16:15:26 +00:00
}
2024-01-11 11:18:17 +00:00
const fetchApi = `https://nostr.api.v0l.io/api/v1/opengraph/${id}?canonical=${encodeURIComponent(
2024-01-10 20:06:57 +00:00
`https://${HOST}/%s`,
)}`;
console.log("Fetching tags from: ", fetchApi);
const rsp = await fetch(fetchApi, {
method: "POST",
body: await next.arrayBuffer(),
headers: {
"user-agent": `SnortFunctions/1.0 (https://${HOST})`,
"content-type": "text/html",
accept: "text/html",
2024-01-10 16:15:26 +00:00
},
2024-01-10 20:06:57 +00:00
});
2024-01-10 16:15:26 +00:00
if (rsp.ok) {
const body = await rsp.text();
if (body.length > 0) {
return new Response(body, {
headers: {
2024-01-11 11:18:17 +00:00
...Object.fromEntries(rsp.headers.entries()),
"cache-control": "public, max-age=60",
2024-01-19 13:12:39 +00:00
"Cross-Origin-Opener-Policy": "same-origin",
"Cross-Origin-Embedder-Policy": "require-corp",
2024-01-10 16:15:26 +00:00
},
});
}
}
2024-01-10 20:06:57 +00:00
} catch (e) {
console.error(e);
2024-01-10 16:15:26 +00:00
}
}
return next;
};