Skip to content

Instantly share code, notes, and snippets.

@devsnek

devsnek/cf.js Secret

Created June 29, 2021 21:20
Show Gist options
  • Star 24 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save devsnek/77275f6e3f810a9545440931ed314dc1 to your computer and use it in GitHub Desktop.
Save devsnek/77275f6e3f810a9545440931ed314dc1 to your computer and use it in GitHub Desktop.
'use strict';
function hex2bin(hex) {
const buf = new Uint8Array(Math.ceil(hex.length / 2));
for (var i = 0; i < buf.length; i++) {
buf[i] = parseInt(hex.substr(i * 2, 2), 16);
}
return buf;
}
const PUBLIC_KEY = crypto.subtle.importKey(
'raw',
hex2bin('bef3c62aed7c2711bdb06c58e483c995227b2593d0b5ab6e4a802f6b08c647f4'),
{
name: 'NODE-ED25519',
namedCurve: 'NODE-ED25519',
public: true,
},
true,
['verify'],
);
const encoder = new TextEncoder();
async function handleRequest(request) {
if (request.method !== 'POST') {
return new Response('invalid method', { status: 405 });
}
const signature = hex2bin(request.headers.get('X-Signature-Ed25519'));
const timestamp = request.headers.get('X-Signature-Timestamp');
const unknown = await request.text();
const verified = await crypto.subtle.verify(
'NODE-ED25519',
await PUBLIC_KEY,
signature,
encoder.encode(timestamp + unknown),
);
if (!verified) {
return new Response('invalid request', { status: 401 });
}
const data = JSON.parse(unknown);
switch (data.type) {
case 1:
return new Response(JSON.stringify({ type: 1 }), {
headers: {'Content-Type': 'application/json'},
});
default:
return new Response('invalid request', { status: 400 });
}
}
addEventListener('fetch', (event) => {
event.respondWith(handleRequest(event.request)
.catch(() => new Response('internal error', { status: 500 })));
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment