Validate event signing, make it more Mastodonic

This commit is contained in:
Alex Gleason 2023-05-20 21:16:14 -05:00
parent ec5e0ed330
commit da6e31c647
No known key found for this signature in database
GPG Key ID: 7211D1F99744FBB7
3 changed files with 27 additions and 6 deletions

View File

@ -20,6 +20,7 @@ export {
nip05,
nip19,
nip21,
verifySignature,
} from 'npm:nostr-tools@^1.11.1';
export { findReplyTag } from 'https://gitlab.com/soapbox-pub/mostr/-/raw/c67064aee5ade5e01597c6d23e22e53c628ef0e2/src/nostr/tags.ts';
export { parseFormData } from 'npm:formdata-helper@^0.3.0';

View File

@ -1,4 +1,4 @@
import { z } from '@/deps.ts';
import { verifySignature, z } from '@/deps.ts';
import type { Event } from './event.ts';
@ -67,10 +67,23 @@ const relaySchema = z.custom<URL>((relay) => {
}
});
const nostrIdSchema = z.string().regex(/^[0-9a-f]{64}$/);
const eventSchema = z.object({
id: nostrIdSchema,
kind: z.number(),
tags: z.array(z.array(z.string())),
content: z.string(),
created_at: z.number(),
pubkey: nostrIdSchema,
sig: z.string(),
}).refine(verifySignature);
const emojiTagSchema = z.tuple([z.literal('emoji'), z.string(), z.string().url()]);
export {
emojiTagSchema,
eventSchema,
filteredArray,
jsonSchema,
type MetaContent,

View File

@ -1,5 +1,6 @@
import { type AppContext } from '@/app.ts';
import { getEventHash, getPublicKey, getSignature, HTTPException } from '@/deps.ts';
import { getEventHash, getPublicKey, getSignature, HTTPException, z } from '@/deps.ts';
import { eventSchema } from '@/schema.ts';
import ws from '@/stream.ts';
import type { Event, EventTemplate, SignedEvent } from '@/event.ts';
@ -15,6 +16,11 @@ function getSignStream(c: AppContext): WebSocket | undefined {
}
}
const nostrStreamingEventSchema = z.object({
type: z.literal('nostr.sign'),
data: eventSchema,
});
/**
* Sign Nostr event using the app context.
*
@ -29,11 +35,12 @@ async function signEvent<K extends number = number>(event: EventTemplate<K>, c:
try {
return await new Promise<SignedEvent<K>>((resolve, reject) => {
const handleMessage = (e: MessageEvent) => {
// TODO: parse and validate with zod
const data = JSON.parse(e.data);
if (data.event === 'nostr.sign') {
try {
const { data: event } = nostrStreamingEventSchema.parse(JSON.parse(e.data));
stream.removeEventListener('message', handleMessage);
resolve(JSON.parse(data.payload));
resolve(event as SignedEvent<K>);
} catch (_e) {
//
}
};
stream.addEventListener('message', handleMessage);