roles-bot/packages/bot/verify.ts

37 lines
862 B
TypeScript
Raw Normal View History

2021-12-21 12:55:10 +01:00
// from https://github.com/advaith1/activities/blob/main/src/verify.ts
'use strict';
function hex2bin(hex: string) {
2022-01-02 18:54:19 +01:00
const buf = new Uint8Array(Math.ceil(hex.length / 2));
for (let i = 0; i < buf.length; i++) {
buf[i] = parseInt(hex.substr(i * 2, 2), 16);
}
return buf;
}
2021-12-21 12:55:10 +01:00
const PUBLIC_KEY = crypto.subtle.importKey(
2022-01-02 18:54:19 +01:00
'raw',
hex2bin(CLIENT_PUBLIC_KEY || ''),
{
name: 'NODE-ED25519',
namedCurve: 'NODE-ED25519',
},
true,
['verify'],
2021-12-21 12:55:10 +01:00
);
const encoder = new TextEncoder();
export async function verify(request: Request) {
2022-01-02 18:54:19 +01:00
const signature = hex2bin(request.headers.get('X-Signature-Ed25519') || '');
const timestamp = request.headers.get('X-Signature-Timestamp');
const unknown = await request.clone().text();
2021-12-21 12:55:10 +01:00
2022-01-02 18:54:19 +01:00
return await crypto.subtle.verify(
'NODE-ED25519',
await PUBLIC_KEY,
signature,
encoder.encode(timestamp + unknown),
);
2021-12-21 12:55:10 +01:00
}