diff --git a/nip98.test.ts b/nip98.test.ts index 1b636b20..91144371 100644 --- a/nip98.test.ts +++ b/nip98.test.ts @@ -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() @@ -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', () => { @@ -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) + }) })