+ create user with public/private key
+ sign and verify votes and prevent unverified updates
This commit is contained in:
@@ -1,3 +1,4 @@
|
||||
import * as Y from 'yjs';
|
||||
// server/api/polls/[id].ts
|
||||
export default defineEventHandler(async (event) => {
|
||||
const method = event.node.req.method;
|
||||
@@ -23,6 +24,40 @@ export default defineEventHandler(async (event) => {
|
||||
const body = await readBody(event);
|
||||
|
||||
if (body.update && Array.isArray(body.update)) {
|
||||
// create a temp Y.Doc to encode the Data
|
||||
const tempDoc = new Y.Doc();
|
||||
Y.applyUpdate(tempDoc, new Uint8Array(body.update));
|
||||
const yMap = tempDoc.getMap('shared-poll');
|
||||
const pollData = yMap.toJSON();
|
||||
|
||||
// verify pollData
|
||||
for(var option in pollData){
|
||||
const votes = pollData[option] || [];
|
||||
var pubKeys: CryptoKey[] = [];
|
||||
|
||||
const verifyAllVotesForOption = async (votes: SignedData<VoteData>[]) => {
|
||||
console.log("verifying votes for option " + option,votes);
|
||||
// check last votes first. if there is something wrong, its likely in the last vote.
|
||||
for (let i = votes.length-1; i >= 0 ; i--) {
|
||||
const userStorage = useStorage('users');
|
||||
const votePubKeyString = await userStorage.getItem(`user:${votes[i]?.data.userid}`);
|
||||
//console.log("Using public key: "+votePubKeyString)
|
||||
const votePubKey = await stringToCryptoKey(String(votePubKeyString),'public')
|
||||
const isValid = await verifyChainedVote(votes, i,votePubKey);
|
||||
if(!isValid){
|
||||
console.error("Error! Invalid Vote at: " + i,votes)
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
};
|
||||
const verified = await verifyAllVotesForOption(votes);
|
||||
if(!verified){
|
||||
console.error("Failed to verify option: "+option)
|
||||
throw createError({ statusCode: 400, statusMessage: 'PollData contains unverifyable content!' });
|
||||
}
|
||||
}
|
||||
|
||||
// Save the binary update (sent as an array of numbers) to storage
|
||||
await storage.setItem(`poll:${pollId}`, body.update);
|
||||
return { success: true };
|
||||
|
||||
41
server/api/users/[id].ts
Normal file
41
server/api/users/[id].ts
Normal file
@@ -0,0 +1,41 @@
|
||||
// server/api/users/[id].ts
|
||||
export default defineEventHandler(async (event) => {
|
||||
const method = event.node.req.method;
|
||||
const userId = getRouterParam(event, 'id');
|
||||
|
||||
// We use Nitro's built-in storage.
|
||||
// 'polls' is the storage namespace.
|
||||
const storage = useStorage('users');
|
||||
|
||||
if (!userId) {
|
||||
throw createError({ statusCode: 400, statusMessage: 'User ID required' });
|
||||
}
|
||||
|
||||
// GET: Fetch the saved Yjs document state
|
||||
if (method === 'GET') {
|
||||
const data = await storage.getItem(`user:${userId}`);
|
||||
// Return the array of numbers (or null if it doesn't exist yet)
|
||||
return { public_key: data };
|
||||
}
|
||||
|
||||
// POST: Save a new Yjs document state
|
||||
if (method === 'POST') {
|
||||
const body = await readBody(event);
|
||||
|
||||
if (body.public_key) {
|
||||
const data = await storage.getItem(`user:${userId}`);
|
||||
|
||||
if (data == undefined || data == null) {
|
||||
// Save the binary update (sent as an array of numbers) to storage
|
||||
await storage.setItem(`user:${userId}`, body.public_key);
|
||||
console.log("New User created: " + userId)
|
||||
console.log("Public Key: " + body.public_key);
|
||||
return { success: true };
|
||||
}
|
||||
|
||||
throw createError({ statusCode: 400, statusMessage: 'User already exists.' });
|
||||
}
|
||||
|
||||
throw createError({ statusCode: 400, statusMessage: 'Invalid update payload' });
|
||||
}
|
||||
});
|
||||
@@ -1,24 +0,0 @@
|
||||
import { v4 as uuidv4 } from 'uuid';
|
||||
|
||||
export default defineEventHandler((event) => {
|
||||
// 1. Check if the cookie already exists
|
||||
const cookie = getCookie(event, 'user_guid');
|
||||
|
||||
// 2. If it doesn't exist, generate and set it
|
||||
if (!cookie) {
|
||||
const newUuid = uuidv4();
|
||||
|
||||
setCookie(event, 'user_guid', newUuid, {
|
||||
maxAge: 60 * 60 * 24 * 7, // 1 week
|
||||
path: '/',
|
||||
// httpOnly: true, // Set to true if you DON'T need to read it in Vue/JS
|
||||
sameSite: 'lax',
|
||||
});
|
||||
|
||||
// 3. Inject it into the context so it's available
|
||||
// to other server routes/plugins during this same request
|
||||
event.context.userGuid = newUuid;
|
||||
} else {
|
||||
event.context.userGuid = cookie;
|
||||
}
|
||||
});
|
||||
86
server/utils/crypto.ts
Normal file
86
server/utils/crypto.ts
Normal file
@@ -0,0 +1,86 @@
|
||||
import { SignedData, VoteData } from "./types";
|
||||
/**
|
||||
* Gets the WebCrypto API regardless of environment (Node vs Browser)
|
||||
*/
|
||||
const getCrypto = () => {
|
||||
return (globalThis as any).crypto;
|
||||
};
|
||||
|
||||
export const verifyVote = async (data: any, signatureStr: string, publicKey: CryptoKey) => {
|
||||
const encoder = new TextEncoder();
|
||||
const encodedData = encoder.encode(JSON.stringify(data));
|
||||
|
||||
// Convert Base64 back to Uint8Array
|
||||
const signature = Uint8Array.from(atob(signatureStr), c => c.charCodeAt(0));
|
||||
|
||||
return await getCrypto().subtle.verify(
|
||||
"RSASSA-PKCS1-v1_5",
|
||||
publicKey,
|
||||
signature,
|
||||
encodedData
|
||||
);
|
||||
};
|
||||
|
||||
/**
|
||||
* Verifies a specific vote within an array of votes by
|
||||
* reconstructing the "signed state" at that point in time.
|
||||
*/
|
||||
export const verifyChainedVote = async (
|
||||
voteData: SignedData<VoteData>[],
|
||||
index: number,
|
||||
pubKey: CryptoKey
|
||||
) => {
|
||||
const voteToVerify = voteData[index];
|
||||
console.log("Verifying vote: " + voteToVerify)
|
||||
if(voteToVerify) {
|
||||
// 1. Reconstruct the exact data state the user signed
|
||||
// We need the array exactly as it was when they pushed their vote
|
||||
const historicalState = voteData.slice(0, index + 1).map((v, i) => {
|
||||
if (i === index) {
|
||||
// For the current vote, the signature must be empty string
|
||||
// because it wasn't signed yet when passed to signVote
|
||||
return { ...v, signature: "" };
|
||||
}
|
||||
return v;
|
||||
});
|
||||
|
||||
try {
|
||||
// 3. Verify: Does this historicalState match the signature?
|
||||
return await verifyVote(historicalState, voteToVerify.signature, pubKey);
|
||||
} catch (err) {
|
||||
console.error("Verification failed")
|
||||
console.error(err);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
console.error("Vote is undefined or null");
|
||||
return false;
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Converts a Base64 string back into a usable CryptoKey object
|
||||
* @param keyStr The Base64 string (without PEM headers)
|
||||
* @param type 'public' or 'private'
|
||||
*/
|
||||
export const stringToCryptoKey = async (keyStr: string, type: 'public' | 'private'): Promise<CryptoKey> => {
|
||||
// 1. Convert Base64 string to a Uint8Array (binary)
|
||||
const bytes = Buffer.from(keyStr, 'base64');
|
||||
|
||||
// 2. Identify the format based on the key type
|
||||
// Public keys usually use 'spki', Private keys use 'pkcs8'
|
||||
const format = type === 'public' ? 'spki' : 'pkcs8';
|
||||
const usages: KeyUsage[] = type === 'public' ? ['verify'] : ['sign'];
|
||||
|
||||
// 3. Import the key
|
||||
return await getCrypto().subtle.importKey(
|
||||
format,
|
||||
bytes,
|
||||
{
|
||||
name: "RSASSA-PKCS1-v1_5",
|
||||
hash: "SHA-256",
|
||||
},
|
||||
true, // extractable (set to false if you want to lock it in memory)
|
||||
usages
|
||||
);
|
||||
};
|
||||
36
server/utils/types.ts
Normal file
36
server/utils/types.ts
Normal file
@@ -0,0 +1,36 @@
|
||||
export interface PollProps {
|
||||
userid: string | undefined,
|
||||
activePollId: string,
|
||||
pollData: PollData,
|
||||
addOption: (name: string) => void,
|
||||
vote: (optionName: string) => void
|
||||
}
|
||||
|
||||
export interface PollListProps {
|
||||
userid: string | undefined,
|
||||
}
|
||||
|
||||
export interface PollData extends Record<string, SignedData<VoteData>[]> {
|
||||
}
|
||||
|
||||
export interface SignedData<T> {
|
||||
data: T,
|
||||
signature: string
|
||||
}
|
||||
|
||||
export interface VoteData {
|
||||
userid: string,
|
||||
timestamp: string
|
||||
}
|
||||
|
||||
export interface OptionData {
|
||||
userid: string,
|
||||
timestamp: string,
|
||||
optionName: string
|
||||
}
|
||||
|
||||
export interface UserData {
|
||||
userid: string,
|
||||
private_key: CryptoKey | undefined,
|
||||
public_key: CryptoKey | undefined
|
||||
}
|
||||
Reference in New Issue
Block a user