Skip to content

Commit

Permalink
update to test for body payload and payload 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 dc04d1e commit c5f3c80
Showing 1 changed file with 37 additions and 0 deletions.
37 changes: 37 additions & 0 deletions nip98.test.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
import { getToken, unpackEventFromToken, validateEvent, validateToken } from './nip98.ts'
import { Event, Kind, finishEvent } from './event.ts'
import { generatePrivateKey, getPublicKey } from './keys.ts'
import { sha256 } from '@noble/hashes/sha256'
import { utf8Encoder } from './utils.ts'
import { bytesToHex } from '@noble/hashes/utils'

const sk = generatePrivateKey()

Expand Down Expand Up @@ -63,6 +66,24 @@ describe('getToken', () => {
const result = getToken('http://test.com', '', e => finishEvent(e, sk))
await expect(result).rejects.toThrow(Error)
})

test('getToken returns token with a valid payload tag when payload is present', async () => {
const payload = { test: 'payload' }
const payloadHash = bytesToHex(sha256(utf8Encoder.encode(JSON.stringify(payload))))
let result = await getToken('http://test.com', 'post', e => finishEvent(e, sk), true, payload)

const decodedResult: Event = await unpackEventFromToken(result)

expect(decodedResult.created_at).toBeGreaterThan(0)
expect(decodedResult.content).toBe('')
expect(decodedResult.kind).toBe(Kind.HttpAuth)
expect(decodedResult.pubkey).toBe(getPublicKey(sk))
expect(decodedResult.tags).toStrictEqual([
['u', 'http://test.com'],
['method', 'post'],
['payload', payloadHash],
])
})
})

describe('validateToken', () => {
Expand Down Expand Up @@ -127,4 +148,20 @@ describe('validateToken', () => {
const result = validateEvent(decodedResult, 'http://test.com', 'post')
await expect(result).rejects.toThrow(Error)
})

test('validateEvent returns true for valid payload tag hash', async () => {
const validToken = await getToken('http://test.com', 'post', e => finishEvent(e, sk), true, { test: 'payload' })
const decodedResult: Event = await unpackEventFromToken(validToken)

const result = await validateEvent(decodedResult, 'http://test.com', 'post', { test: 'payload' })
expect(result).toBe(true)
})

test('validateEvent returns false for invalid payload tag hash', async () => {
const validToken = await getToken('http://test.com', 'post', e => finishEvent(e, sk), true, { test: 'a-payload' })
const decodedResult: Event = await unpackEventFromToken(validToken)

const result = validateEvent(decodedResult, 'http://test.com', 'post', { test: 'a-different-payload' })
await expect(result).rejects.toThrow(Error)
})
})

0 comments on commit c5f3c80

Please sign in to comment.