Skip to content

Commit

Permalink
update to support body payload and hash
Browse files Browse the repository at this point in the history
  • Loading branch information
joshr4 authored and fiatjaf committed Nov 13, 2023
1 parent a2a1556 commit dc04d1e
Showing 1 changed file with 22 additions and 1 deletion.
23 changes: 22 additions & 1 deletion nip98.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,16 @@
import { bytesToHex } from '@noble/hashes/utils'
import { sha256 } from '@noble/hashes/sha256'
import { base64 } from '@scure/base'
import { Event, EventTemplate, Kind, getBlankEvent, verifySignature } from './event'
import { utf8Decoder, utf8Encoder } from './utils'

const _authorizationScheme = 'Nostr '

function hashPayload(payload: any): string {
const hash = sha256(utf8Encoder.encode(JSON.stringify(payload)))
return bytesToHex(hash)
}

/**
* Generate token for NIP-98 flow.
*
Expand All @@ -16,6 +23,7 @@ export async function getToken(
httpMethod: string,
sign: <K extends number = number>(e: EventTemplate<K>) => Promise<Event<K>> | Event<K>,
includeAuthorizationScheme: boolean = false,
payload?: Record<string, any>,
): Promise<string> {
if (!loginUrl || !httpMethod) throw new Error('Missing loginUrl or httpMethod')

Expand All @@ -25,6 +33,11 @@ export async function getToken(
['u', loginUrl],
['method', httpMethod],
]

if (payload) {
event.tags.push(['payload', bytesToHex(sha256(utf8Encoder.encode(JSON.stringify(payload))))])
}

event.created_at = Math.round(new Date().getTime() / 1000)

const signedEvent = await sign(event)
Expand Down Expand Up @@ -66,7 +79,7 @@ export async function unpackEventFromToken(token: string): Promise<Event> {
return event
}

export async function validateEvent(event: Event, url: string, method: string): Promise<boolean> {
export async function validateEvent(event: Event, url: string, method: string, body?: any): Promise<boolean> {
if (!event) {
throw new Error('Invalid nostr event')
}
Expand Down Expand Up @@ -96,5 +109,13 @@ export async function validateEvent(event: Event, url: string, method: string):
throw new Error('Invalid nostr event, method tag invalid')
}

if (Boolean(body) && Object.keys(body).length > 0) {
const payloadTag = event.tags.find(t => t[0] === 'payload')
const payloadHash = bytesToHex(sha256(utf8Encoder.encode(JSON.stringify(body))))
if (payloadTag?.[1] !== payloadHash) {
throw new Error('Invalid payload tag hash, does not match request body hash')
}
}

return true
}

0 comments on commit dc04d1e

Please sign in to comment.