mirror of
https://github.com/kmc7468/arkvault.git
synced 2025-12-16 23:18:48 +00:00
Request Body의 필드마다 서명하지 않고, 데이터 전체에 대해 서명하도록 개선
This commit is contained in:
@@ -1,5 +1,8 @@
|
||||
import { error } from "@sveltejs/kit";
|
||||
import { constants, randomBytes, createPublicKey, publicEncrypt, verify } from "crypto";
|
||||
import { promisify } from "util";
|
||||
import { z } from "zod";
|
||||
import { getClient } from "$lib/server/db/client";
|
||||
|
||||
const makePubKeyToPem = (pubKey: string) =>
|
||||
`-----BEGIN PUBLIC KEY-----\n${pubKey}\n-----END PUBLIC KEY-----`;
|
||||
@@ -17,10 +20,10 @@ export const encryptAsymmetric = (data: Buffer, encPubKey: string) => {
|
||||
return publicEncrypt({ key: makePubKeyToPem(encPubKey), oaepHash: "sha256" }, data);
|
||||
};
|
||||
|
||||
export const verifySignature = (data: string, signature: string, sigPubKey: string) => {
|
||||
export const verifySignature = (data: Buffer, signature: string, sigPubKey: string) => {
|
||||
return verify(
|
||||
"rsa-sha256",
|
||||
Buffer.from(data, "base64"),
|
||||
data,
|
||||
{
|
||||
key: makePubKeyToPem(sigPubKey),
|
||||
padding: constants.RSA_PKCS1_PSS_PADDING,
|
||||
@@ -34,3 +37,31 @@ export const generateChallenge = async (length: number, encPubKey: string) => {
|
||||
const challenge = encryptAsymmetric(answer, encPubKey);
|
||||
return { answer, challenge };
|
||||
};
|
||||
|
||||
export const parseSignedRequest = async <T extends z.ZodTypeAny>(
|
||||
clientId: number,
|
||||
data: unknown,
|
||||
schema: T,
|
||||
) => {
|
||||
const zodRes = z
|
||||
.object({
|
||||
data: schema,
|
||||
signature: z.string().base64().nonempty(),
|
||||
})
|
||||
.safeParse(data);
|
||||
if (!zodRes.success) error(400, "Invalid request body");
|
||||
|
||||
const { data: parsedData, signature } = zodRes.data;
|
||||
if (!parsedData) error(500, "Invalid request body");
|
||||
|
||||
const client = await getClient(clientId);
|
||||
if (!client) {
|
||||
error(500, "Invalid access token");
|
||||
} else if (
|
||||
!verifySignature(Buffer.from(JSON.stringify(parsedData)), signature, client.sigPubKey)
|
||||
) {
|
||||
error(400, "Invalid signature");
|
||||
}
|
||||
|
||||
return parsedData;
|
||||
};
|
||||
|
||||
Reference in New Issue
Block a user