Compare commits

...

13 Commits

Author SHA1 Message Date
fiatjaf
c1848d78a0 tag v1.13.0 2023-07-17 13:14:10 -03:00
Dolu
81776ba811 fix(nip98): add export 2023-07-17 11:51:12 -03:00
Dolu
915d6d729b feat(nip98): add getToken and validateToken 2023-07-17 11:51:12 -03:00
jiftechnify
1a23f5ee01 keep up with the latest specs for since/until filter 2023-07-15 16:08:31 -03:00
Alex Gleason
fec40490a2 Merge pull request #249 from alexgleason/fix-nip27-type
Fix nip27 type
2023-07-13 11:02:33 -05:00
Alex Gleason
bb3e41bb89 Also remove failing nip05 test due to server down (this should be mocked) 2023-07-13 10:57:30 -05:00
Alex Gleason
27b971eef3 Fix nip27 type 2023-07-13 10:48:22 -05:00
futpib
0041008b22 Add an option to disable seenOn 2023-07-06 16:38:30 -03:00
Perlover
ae5bf4c72c Fix with "wordlists/english.js"
Details are here: https://github.com/nbd-wtf/nostr-tools/issues/25
2023-07-04 15:07:25 -03:00
Alex Gleason
75fc836cf6 Merge pull request #241 from alexgleason/nip19-cool-type
nip19: use template literal types
2023-07-02 12:22:04 -05:00
Alex Gleason
70b025b8da nip19: use a DRY type 2023-07-01 22:44:04 -05:00
Alex Gleason
c9bc702d90 nip19: use template literal types 2023-07-01 21:28:01 -05:00
Alex Gleason
7652318185 Fix nip27 test 2023-06-29 16:44:44 -03:00
14 changed files with 346 additions and 46 deletions

View File

@@ -27,6 +27,7 @@ export enum Kind {
Zap = 9735,
RelayList = 10002,
ClientAuth = 22242,
HttpAuth = 27235,
ProfileBadge = 30008,
BadgeDefinition = 30009,
Article = 30023

View File

@@ -115,6 +115,16 @@ describe('Filter', () => {
expect(result).toEqual(false)
})
it('should return true when the timestamp of event is equal to the filter since value', () => {
const filter = {since: 100}
const event = buildEvent({created_at: 100})
const result = matchFilter(filter, event)
expect(result).toEqual(true)
})
it('should return false when the event is after the filter until value', () => {
const filter = {until: 100}
@@ -124,6 +134,16 @@ describe('Filter', () => {
expect(result).toEqual(false)
})
it('should return true when the timestamp of event is equal to the filter until value', () => {
const filter = {until: 100}
const event = buildEvent({created_at: 100})
const result = matchFilter(filter, event)
expect(result).toEqual(true)
})
})
describe('matchFilters', () => {

View File

@@ -42,7 +42,7 @@ export function matchFilter(
}
if (filter.since && event.created_at < filter.since) return false
if (filter.until && event.created_at >= filter.until) return false
if (filter.until && event.created_at > filter.until) return false
return true
}

View File

@@ -19,6 +19,7 @@ export * as nip27 from './nip27.ts'
export * as nip39 from './nip39.ts'
export * as nip42 from './nip42.ts'
export * as nip57 from './nip57.ts'
export * as nip98 from './nip98.ts'
export * as fj from './fakejson.ts'
export * as utils from './utils.ts'

View File

@@ -17,17 +17,11 @@ test('fetch nip05 profiles', async () => {
)
expect(p2!.relays).toEqual(['wss://relay.damus.io'])
let p3 = await queryProfile('channel.ninja@channel.ninja')
let p3 = await queryProfile('_@fiatjaf.com')
expect(p3!.pubkey).toEqual(
'36e65b503eba8a6b698e724a59137603101166a1cddb45ddc704247fc8aa0fce'
)
expect(p3!.relays).toEqual(undefined)
let p4 = await queryProfile('_@fiatjaf.com')
expect(p4!.pubkey).toEqual(
'3bf0c63fcb93463407af97a5e5ee64fa883d107ef9e558472c4eb9aaaefa459d'
)
expect(p4!.relays).toEqual([
expect(p3!.relays).toEqual([
'wss://relay.nostr.bg',
'wss://nos.lol',
'wss://nostr-verified.wellorder.net',

View File

@@ -1,5 +1,5 @@
import {bytesToHex} from '@noble/hashes/utils'
import {wordlist} from '@scure/bip39/wordlists/english.js'
import {wordlist} from '@scure/bip39/wordlists/english'
import {
generateMnemonic,
mnemonicToSeedSync,

View File

@@ -30,15 +30,27 @@ export type AddressPointer = {
relays?: string[]
}
export type DecodeResult =
| {type: 'nprofile'; data: ProfilePointer}
| {type: 'nrelay'; data: string}
| {type: 'nevent'; data: EventPointer}
| {type: 'naddr'; data: AddressPointer}
| {type: 'nsec'; data: string}
| {type: 'npub'; data: string}
| {type: 'note'; data: string}
type Prefixes = {
nprofile: ProfilePointer
nrelay: string
nevent: EventPointer
naddr: AddressPointer
nsec: string
npub: string
note: string
}
type DecodeValue<Prefix extends keyof Prefixes> = {
type: Prefix
data: Prefixes[Prefix]
}
export type DecodeResult = {
[P in keyof Prefixes]: DecodeValue<P>
}[keyof Prefixes]
export function decode<Prefix extends keyof Prefixes>(nip19: `${Prefix}1${string}`): DecodeValue<Prefix>
export function decode(nip19: string): DecodeResult
export function decode(nip19: string): DecodeResult {
let {prefix, words} = bech32.decode(nip19, Bech32MaxSize)
let data = new Uint8Array(bech32.fromWords(words))
@@ -131,44 +143,46 @@ function parseTLV(data: Uint8Array): TLV {
return result
}
export function nsecEncode(hex: string): string {
export function nsecEncode(hex: string): `nsec1${string}` {
return encodeBytes('nsec', hex)
}
export function npubEncode(hex: string): string {
export function npubEncode(hex: string): `npub1${string}` {
return encodeBytes('npub', hex)
}
export function noteEncode(hex: string): string {
export function noteEncode(hex: string): `note1${string}` {
return encodeBytes('note', hex)
}
function encodeBytes(prefix: string, hex: string): string {
let data = hexToBytes(hex)
function encodeBech32<Prefix extends string>(prefix: Prefix, data: Uint8Array): `${Prefix}1${string}` {
let words = bech32.toWords(data)
return bech32.encode(prefix, words, Bech32MaxSize)
return bech32.encode(prefix, words, Bech32MaxSize) as `${Prefix}1${string}`
}
export function nprofileEncode(profile: ProfilePointer): string {
function encodeBytes<Prefix extends string>(prefix: Prefix, hex: string): `${Prefix}1${string}` {
let data = hexToBytes(hex)
return encodeBech32(prefix, data)
}
export function nprofileEncode(profile: ProfilePointer): `nprofile1${string}` {
let data = encodeTLV({
0: [hexToBytes(profile.pubkey)],
1: (profile.relays || []).map(url => utf8Encoder.encode(url))
})
let words = bech32.toWords(data)
return bech32.encode('nprofile', words, Bech32MaxSize)
return encodeBech32('nprofile', data)
}
export function neventEncode(event: EventPointer): string {
export function neventEncode(event: EventPointer): `nevent1${string}` {
let data = encodeTLV({
0: [hexToBytes(event.id)],
1: (event.relays || []).map(url => utf8Encoder.encode(url)),
2: event.author ? [hexToBytes(event.author)] : []
})
let words = bech32.toWords(data)
return bech32.encode('nevent', words, Bech32MaxSize)
return encodeBech32('nevent', data)
}
export function naddrEncode(addr: AddressPointer): string {
export function naddrEncode(addr: AddressPointer): `naddr1${string}` {
let kind = new ArrayBuffer(4)
new DataView(kind).setUint32(0, addr.kind, false)
@@ -178,16 +192,14 @@ export function naddrEncode(addr: AddressPointer): string {
2: [hexToBytes(addr.pubkey)],
3: [new Uint8Array(kind)]
})
let words = bech32.toWords(data)
return bech32.encode('naddr', words, Bech32MaxSize)
return encodeBech32('naddr', data)
}
export function nrelayEncode(url: string): string {
export function nrelayEncode(url: string): `nrelay1${string}` {
let data = encodeTLV({
0: [utf8Encoder.encode(url)]
})
let words = bech32.toWords(data)
return bech32.encode('nrelay', words, Bech32MaxSize)
return encodeBech32('nrelay', data)
}
function encodeTLV(tlv: TLV): Uint8Array {

View File

@@ -31,7 +31,7 @@ test('matchAll', () => {
test('matchAll with an invalid nip19', () => {
const result = matchAll(
'Hello npub129tvj896hqqkljerxkccpj9flshwnw999v9uwn9lfmwlj8vnzwgq9y5llnpub1rujdpkd8mwezrvpqd2rx2zphfaztqrtsfg6w3vdnlj!\n\nnostr:note1gmtnz6q2m55epmlpe3semjdcq987av3jvx4emmjsa8g3s9x7tg4sclreky'
'Hello nostr:npub129tvj896hqqkljerxkccpj9flshwnw999v9uwn9lfmwlj8vnzwgq9y5llnpub1rujdpkd8mwezrvpqd2rx2zphfaztqrtsfg6w3vdnlj!\n\nnostr:note1gmtnz6q2m55epmlpe3semjdcq987av3jvx4emmjsa8g3s9x7tg4sclreky'
)
expect([...result]).toEqual([
@@ -40,8 +40,8 @@ test('matchAll with an invalid nip19', () => {
data: '46d731680add2990efe1cc619dc9b8014feeb23261ab9dee50e9d11814de5a2b',
type: 'note'
},
end: 187,
start: 118,
end: 193,
start: 124,
uri: 'nostr:note1gmtnz6q2m55epmlpe3semjdcq987av3jvx4emmjsa8g3s9x7tg4sclreky',
value: 'note1gmtnz6q2m55epmlpe3semjdcq987av3jvx4emmjsa8g3s9x7tg4sclreky'
}

View File

@@ -13,7 +13,7 @@ export interface NostrURIMatch extends NostrURI {
}
/** Find and decode all NIP-21 URIs. */
export function* matchAll(content: string): Iterable<NostrURIMatch> {
export function * matchAll(content: string): Iterable<NostrURIMatch> {
const matches = content.matchAll(regex())
for (const match of matches) {
@@ -56,7 +56,7 @@ export function replaceAll(
content: string,
replacer: (match: NostrURI) => string
): string {
return content.replaceAll(regex(), (uri, value) => {
return content.replaceAll(regex(), (uri, value: string) => {
return replacer({
uri: uri as `nostr:${string}`,
value,

139
nip98.test.ts Normal file
View File

@@ -0,0 +1,139 @@
import {base64} from '@scure/base'
import {getToken, validateToken} from './nip98.ts'
import {Event, Kind, finishEvent} from './event.ts'
import {utf8Decoder} from './utils.ts'
import {generatePrivateKey, getPublicKey} from './keys.ts'
const sk = generatePrivateKey()
describe('getToken', () => {
test('getToken GET returns without authorization scheme', async () => {
let result = await getToken('http://test.com', 'get', e =>
finishEvent(e, sk)
)
const decodedResult: Event = JSON.parse(
utf8Decoder.decode(base64.decode(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', 'get']
])
})
test('getToken POST returns token without authorization scheme', async () => {
let result = await getToken('http://test.com', 'post', e =>
finishEvent(e, sk)
)
const decodedResult: Event = JSON.parse(
utf8Decoder.decode(base64.decode(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']
])
})
test('getToken GET returns token WITH authorization scheme', async () => {
const authorizationScheme = 'Nostr '
let result = await getToken(
'http://test.com',
'post',
e => finishEvent(e, sk),
true
)
expect(result.startsWith(authorizationScheme)).toBe(true)
const decodedResult: Event = JSON.parse(
utf8Decoder.decode(base64.decode(result.replace(authorizationScheme, '')))
)
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']
])
})
test('getToken unknown method throws an error', async () => {
const result = getToken('http://test.com', 'fake', e => finishEvent(e, sk))
await expect(result).rejects.toThrow(Error)
})
test('getToken missing loginUrl throws an error', async () => {
const result = getToken('', 'get', e => finishEvent(e, sk))
await expect(result).rejects.toThrow(Error)
})
test('getToken missing httpMethod throws an error', async () => {
const result = getToken('http://test.com', '', e => finishEvent(e, sk))
await expect(result).rejects.toThrow(Error)
})
})
describe('validateToken', () => {
test('validateToken returns true for valid token without authorization scheme', async () => {
const validToken = await getToken('http://test.com', 'get', e =>
finishEvent(e, sk)
)
const result = await validateToken(validToken, 'http://test.com', 'get')
expect(result).toBe(true)
})
test('validateToken returns true for valid token with authorization scheme', async () => {
const validToken = await getToken(
'http://test.com',
'get',
e => finishEvent(e, sk),
true
)
const result = await validateToken(validToken, 'http://test.com', 'get')
expect(result).toBe(true)
})
test('validateToken throws an error for invalid token', async () => {
const result = validateToken('fake', 'http://test.com', 'get')
await expect(result).rejects.toThrow(Error)
})
test('validateToken throws an error for missing token', async () => {
const result = validateToken('', 'http://test.com', 'get')
await expect(result).rejects.toThrow(Error)
})
test('validateToken throws an error for a wrong url', async () => {
const validToken = await getToken('http://test.com', 'get', e =>
finishEvent(e, sk)
)
const result = validateToken(validToken, 'http://wrong-test.com', 'get')
await expect(result).rejects.toThrow(Error)
})
test('validateToken throws an error for a wrong method', async () => {
const validToken = await getToken('http://test.com', 'get', e =>
finishEvent(e, sk)
)
const result = validateToken(validToken, 'http://test.com', 'post')
await expect(result).rejects.toThrow(Error)
})
})

112
nip98.ts Normal file
View File

@@ -0,0 +1,112 @@
import {base64} from '@scure/base'
import {
Event,
EventTemplate,
Kind,
getBlankEvent,
verifySignature
} from './event'
import {utf8Decoder, utf8Encoder} from './utils'
enum HttpMethod {
Get = 'get',
Post = 'post'
}
const _authorizationScheme = 'Nostr '
/**
* Generate token for NIP-98 flow.
*
* @example
* const sign = window.nostr.signEvent
* await getToken('https://example.com/login', 'post', sign, true)
*/
export async function getToken(
loginUrl: string,
httpMethod: HttpMethod | string,
sign: <K extends number = number>(
e: EventTemplate<K>
) => Promise<Event<K>> | Event<K>,
includeAuthorizationScheme: boolean = false
): Promise<string> {
if (!loginUrl || !httpMethod)
throw new Error('Missing loginUrl or httpMethod')
if (httpMethod !== HttpMethod.Get && httpMethod !== HttpMethod.Post)
throw new Error('Unknown httpMethod')
const event = getBlankEvent(Kind.HttpAuth)
event.tags = [
['u', loginUrl],
['method', httpMethod]
]
event.created_at = Math.round(new Date().getTime() / 1000)
const signedEvent = await sign(event)
const authorizationScheme = includeAuthorizationScheme
? _authorizationScheme
: ''
return (
authorizationScheme +
base64.encode(utf8Encoder.encode(JSON.stringify(signedEvent)))
)
}
/**
* Validate token for NIP-98 flow.
*
* @example
* await validateToken('Nostr base64token', 'https://example.com/login', 'post')
*/
export async function validateToken(
token: string,
url: string,
method: string
): Promise<boolean> {
if (!token) {
throw new Error('Missing token')
}
token = token.replace(_authorizationScheme, '')
const eventB64 = utf8Decoder.decode(base64.decode(token))
if (!eventB64 || eventB64.length === 0 || !eventB64.startsWith('{')) {
throw new Error('Invalid token')
}
const event = JSON.parse(eventB64) as Event
if (!event) {
throw new Error('Invalid nostr event')
}
if (!verifySignature(event)) {
throw new Error('Invalid nostr event, signature invalid')
}
if (event.kind !== Kind.HttpAuth) {
throw new Error('Invalid nostr event, kind invalid')
}
if (!event.created_at) {
throw new Error('Invalid nostr event, created_at invalid')
}
// Event must be less than 60 seconds old
if (Math.round(new Date().getTime() / 1000) - event.created_at > 60) {
throw new Error('Invalid nostr event, expired')
}
const urlTag = event.tags.find(t => t[0] === 'u')
if (urlTag?.length !== 1 && urlTag?.[1] !== url) {
throw new Error('Invalid nostr event, url tag invalid')
}
const methodTag = event.tags.find(t => t[0] === 'method')
if (
methodTag?.length !== 1 &&
methodTag?.[1].toLowerCase() !== method.toLowerCase()
) {
throw new Error('Invalid nostr event, method tag invalid')
}
return true
}

View File

@@ -1,6 +1,6 @@
{
"name": "nostr-tools",
"version": "1.12.1",
"version": "1.13.0",
"description": "Tools for making a Nostr client.",
"repository": {
"type": "git",

View File

@@ -121,3 +121,20 @@ test('list()', async () => {
.reduce((acc, n) => acc.concat(n), [])
expect(relaysForAllEvents.length).toBeGreaterThanOrEqual(events.length)
})
test('seenOnEnabled: false', async () => {
const poolWithoutSeenOn = new SimplePool({seenOnEnabled: false})
const event = await poolWithoutSeenOn.get(relays, {
ids: ['d7dd5eb3ab747e16f8d0212d53032ea2a7cadef53837e5a6c66d42849fcb9027']
})
expect(event).toHaveProperty(
'id',
'd7dd5eb3ab747e16f8d0212d53032ea2a7cadef53837e5a6c66d42849fcb9027'
)
const relaysForEvent = poolWithoutSeenOn.seenOn(event!.id)
expect(relaysForEvent).toHaveLength(0)
})

12
pool.ts
View File

@@ -15,11 +15,13 @@ export class SimplePool {
private eoseSubTimeout: number
private getTimeout: number
private seenOnEnabled: boolean = true
constructor(options: {eoseSubTimeout?: number; getTimeout?: number} = {}) {
constructor(options: {eoseSubTimeout?: number; getTimeout?: number; seenOnEnabled?: boolean} = {}) {
this._conn = {}
this.eoseSubTimeout = options.eoseSubTimeout || 3400
this.getTimeout = options.getTimeout || 3400
this.seenOnEnabled = options.seenOnEnabled !== false
}
close(relays: string[]): void {
@@ -51,9 +53,11 @@ export class SimplePool {
if (opts?.alreadyHaveEvent?.(id, url)) {
return true
}
let set = this._seenOn[id] || new Set()
set.add(url)
this._seenOn[id] = set
if (this.seenOnEnabled) {
let set = this._seenOn[id] || new Set()
set.add(url)
this._seenOn[id] = set
}
return _knownIds.has(id)
}