mirror of
https://github.com/nbd-wtf/nostr-tools.git
synced 2025-12-09 00:28:51 +00:00
Compare commits
9 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f0357805c3 | ||
|
|
ffa7fb926e | ||
|
|
12acb900ab | ||
|
|
d773012658 | ||
|
|
b8f91c37fa | ||
|
|
2da3528362 | ||
|
|
315e9a472c | ||
|
|
a2b1bf0338 | ||
|
|
861a77e2b3 |
@@ -4,7 +4,7 @@ Tools for developing [Nostr](https://github.com/fiatjaf/nostr) clients.
|
|||||||
|
|
||||||
Only depends on _@scure_ and _@noble_ packages.
|
Only depends on _@scure_ and _@noble_ packages.
|
||||||
|
|
||||||
This package is only providing lower-level functionality. If you want more higher-level features, take a look at [Nostrify](https://nostrify.dev), or if you want an easy-to-use fully-fledged solution that abstracts the hard parts of Nostr and makes decisions on your behalf, take a look at [NDK](https://github.com/nostr-dev-kit/ndk) and [@snort/system](https://www.npmjs.com/package/@snort/system).
|
This package is only providing lower-level functionality. If you want higher-level features, take a look at [@nostr/gadgets](https://jsr.io/@nostr/gadgets) which is based on this library and expands upon it and has other goodies (it's only available on jsr).
|
||||||
|
|
||||||
## Installation
|
## Installation
|
||||||
|
|
||||||
|
|||||||
@@ -12,13 +12,15 @@ import type { Event, EventTemplate, Nostr, VerifiedEvent } from './core.ts'
|
|||||||
import { type Filter } from './filter.ts'
|
import { type Filter } from './filter.ts'
|
||||||
import { alwaysTrue } from './helpers.ts'
|
import { alwaysTrue } from './helpers.ts'
|
||||||
|
|
||||||
export type SubCloser = { close: () => void }
|
export type SubCloser = { close: (reason?: string) => void }
|
||||||
|
|
||||||
export type AbstractPoolConstructorOptions = AbstractRelayConstructorOptions & {}
|
export type AbstractPoolConstructorOptions = AbstractRelayConstructorOptions & {}
|
||||||
|
|
||||||
export type SubscribeManyParams = Omit<SubscriptionParams, 'onclose'> & {
|
export type SubscribeManyParams = Omit<SubscriptionParams, 'onclose'> & {
|
||||||
maxWait?: number
|
maxWait?: number
|
||||||
onclose?: (reasons: string[]) => void
|
onclose?: (reasons: string[]) => void
|
||||||
|
onauth?: (event: EventTemplate) => Promise<VerifiedEvent>
|
||||||
|
// Deprecated: use onauth instead
|
||||||
doauth?: (event: EventTemplate) => Promise<VerifiedEvent>
|
doauth?: (event: EventTemplate) => Promise<VerifiedEvent>
|
||||||
id?: string
|
id?: string
|
||||||
label?: string
|
label?: string
|
||||||
@@ -63,6 +65,8 @@ export class AbstractSimplePool {
|
|||||||
}
|
}
|
||||||
|
|
||||||
subscribe(relays: string[], filter: Filter, params: SubscribeManyParams): SubCloser {
|
subscribe(relays: string[], filter: Filter, params: SubscribeManyParams): SubCloser {
|
||||||
|
params.onauth = params.onauth || params.doauth
|
||||||
|
|
||||||
return this.subscribeMap(
|
return this.subscribeMap(
|
||||||
relays.map(url => ({ url, filter })),
|
relays.map(url => ({ url, filter })),
|
||||||
params,
|
params,
|
||||||
@@ -70,6 +74,8 @@ export class AbstractSimplePool {
|
|||||||
}
|
}
|
||||||
|
|
||||||
subscribeMany(relays: string[], filters: Filter[], params: SubscribeManyParams): SubCloser {
|
subscribeMany(relays: string[], filters: Filter[], params: SubscribeManyParams): SubCloser {
|
||||||
|
params.onauth = params.onauth || params.doauth
|
||||||
|
|
||||||
return this.subscribeMap(
|
return this.subscribeMap(
|
||||||
relays.flatMap(url => filters.map(filter => ({ url, filter }))),
|
relays.flatMap(url => filters.map(filter => ({ url, filter }))),
|
||||||
params,
|
params,
|
||||||
@@ -77,6 +83,8 @@ export class AbstractSimplePool {
|
|||||||
}
|
}
|
||||||
|
|
||||||
subscribeMap(requests: { url: string; filter: Filter }[], params: SubscribeManyParams): SubCloser {
|
subscribeMap(requests: { url: string; filter: Filter }[], params: SubscribeManyParams): SubCloser {
|
||||||
|
params.onauth = params.onauth || params.doauth
|
||||||
|
|
||||||
if (this.trackRelays) {
|
if (this.trackRelays) {
|
||||||
params.receivedEvent = (relay: AbstractRelay, id: string) => {
|
params.receivedEvent = (relay: AbstractRelay, id: string) => {
|
||||||
let set = this.seenOn.get(id)
|
let set = this.seenOn.get(id)
|
||||||
@@ -141,9 +149,9 @@ export class AbstractSimplePool {
|
|||||||
...params,
|
...params,
|
||||||
oneose: () => handleEose(i),
|
oneose: () => handleEose(i),
|
||||||
onclose: reason => {
|
onclose: reason => {
|
||||||
if (reason.startsWith('auth-required:') && params.doauth) {
|
if (reason.startsWith('auth-required: ') && params.onauth) {
|
||||||
relay
|
relay
|
||||||
.auth(params.doauth)
|
.auth(params.onauth)
|
||||||
.then(() => {
|
.then(() => {
|
||||||
relay.subscribe([filter], {
|
relay.subscribe([filter], {
|
||||||
...params,
|
...params,
|
||||||
@@ -171,10 +179,10 @@ export class AbstractSimplePool {
|
|||||||
)
|
)
|
||||||
|
|
||||||
return {
|
return {
|
||||||
async close() {
|
async close(reason?: string) {
|
||||||
await allOpened
|
await allOpened
|
||||||
subs.forEach(sub => {
|
subs.forEach(sub => {
|
||||||
sub.close()
|
sub.close(reason)
|
||||||
})
|
})
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
@@ -183,12 +191,14 @@ export class AbstractSimplePool {
|
|||||||
subscribeEose(
|
subscribeEose(
|
||||||
relays: string[],
|
relays: string[],
|
||||||
filter: Filter,
|
filter: Filter,
|
||||||
params: Pick<SubscribeManyParams, 'label' | 'id' | 'onevent' | 'onclose' | 'maxWait' | 'doauth'>,
|
params: Pick<SubscribeManyParams, 'label' | 'id' | 'onevent' | 'onclose' | 'maxWait' | 'onauth' | 'doauth'>,
|
||||||
): SubCloser {
|
): SubCloser {
|
||||||
|
params.onauth = params.onauth || params.doauth
|
||||||
|
|
||||||
const subcloser = this.subscribe(relays, filter, {
|
const subcloser = this.subscribe(relays, filter, {
|
||||||
...params,
|
...params,
|
||||||
oneose() {
|
oneose() {
|
||||||
subcloser.close()
|
subcloser.close('closed automatically on eose')
|
||||||
},
|
},
|
||||||
})
|
})
|
||||||
return subcloser
|
return subcloser
|
||||||
@@ -197,12 +207,14 @@ export class AbstractSimplePool {
|
|||||||
subscribeManyEose(
|
subscribeManyEose(
|
||||||
relays: string[],
|
relays: string[],
|
||||||
filters: Filter[],
|
filters: Filter[],
|
||||||
params: Pick<SubscribeManyParams, 'label' | 'id' | 'onevent' | 'onclose' | 'maxWait' | 'doauth'>,
|
params: Pick<SubscribeManyParams, 'label' | 'id' | 'onevent' | 'onclose' | 'maxWait' | 'onauth' | 'doauth'>,
|
||||||
): SubCloser {
|
): SubCloser {
|
||||||
|
params.onauth = params.onauth || params.doauth
|
||||||
|
|
||||||
const subcloser = this.subscribeMany(relays, filters, {
|
const subcloser = this.subscribeMany(relays, filters, {
|
||||||
...params,
|
...params,
|
||||||
oneose() {
|
oneose() {
|
||||||
subcloser.close()
|
subcloser.close('closed automatically on eose')
|
||||||
},
|
},
|
||||||
})
|
})
|
||||||
return subcloser
|
return subcloser
|
||||||
@@ -238,7 +250,11 @@ export class AbstractSimplePool {
|
|||||||
return events[0] || null
|
return events[0] || null
|
||||||
}
|
}
|
||||||
|
|
||||||
publish(relays: string[], event: Event): Promise<string>[] {
|
publish(
|
||||||
|
relays: string[],
|
||||||
|
event: Event,
|
||||||
|
options?: { onauth?: (evt: EventTemplate) => Promise<VerifiedEvent> },
|
||||||
|
): Promise<string>[] {
|
||||||
return relays.map(normalizeURL).map(async (url, i, arr) => {
|
return relays.map(normalizeURL).map(async (url, i, arr) => {
|
||||||
if (arr.indexOf(url) !== i) {
|
if (arr.indexOf(url) !== i) {
|
||||||
// duplicate
|
// duplicate
|
||||||
@@ -246,7 +262,16 @@ export class AbstractSimplePool {
|
|||||||
}
|
}
|
||||||
|
|
||||||
let r = await this.ensureRelay(url)
|
let r = await this.ensureRelay(url)
|
||||||
return r.publish(event).then(reason => {
|
return r
|
||||||
|
.publish(event)
|
||||||
|
.catch(async err => {
|
||||||
|
if (err instanceof Error && err.message.startsWith('auth-required: ') && options?.onauth) {
|
||||||
|
await r.auth(options.onauth)
|
||||||
|
return r.publish(event) // retry
|
||||||
|
}
|
||||||
|
throw err
|
||||||
|
})
|
||||||
|
.then(reason => {
|
||||||
if (this.trackRelays) {
|
if (this.trackRelays) {
|
||||||
let set = this.seenOn.get(event.id)
|
let set = this.seenOn.get(event.id)
|
||||||
if (!set) {
|
if (!set) {
|
||||||
|
|||||||
@@ -26,9 +26,6 @@ export class AbstractRelay {
|
|||||||
public onclose: (() => void) | null = null
|
public onclose: (() => void) | null = null
|
||||||
public onnotice: (msg: string) => void = msg => console.debug(`NOTICE from ${this.url}: ${msg}`)
|
public onnotice: (msg: string) => void = msg => console.debug(`NOTICE from ${this.url}: ${msg}`)
|
||||||
|
|
||||||
// this is exposed just to help in ndk migration, shouldn't be relied upon
|
|
||||||
public _onauth: ((challenge: string) => void) | null = null
|
|
||||||
|
|
||||||
public baseEoseTimeout: number = 4400
|
public baseEoseTimeout: number = 4400
|
||||||
public connectionTimeout: number = 4400
|
public connectionTimeout: number = 4400
|
||||||
public publishTimeout: number = 4400
|
public publishTimeout: number = 4400
|
||||||
@@ -233,7 +230,6 @@ export class AbstractRelay {
|
|||||||
return
|
return
|
||||||
case 'AUTH': {
|
case 'AUTH': {
|
||||||
this.challenge = data[1] as string
|
this.challenge = data[1] as string
|
||||||
this._onauth?.(data[1] as string)
|
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -256,9 +252,10 @@ export class AbstractRelay {
|
|||||||
if (this.authPromise) return this.authPromise
|
if (this.authPromise) return this.authPromise
|
||||||
|
|
||||||
this.authPromise = new Promise<string>(async (resolve, reject) => {
|
this.authPromise = new Promise<string>(async (resolve, reject) => {
|
||||||
const evt = await signAuthEvent(makeAuthEvent(this.url, challenge))
|
try {
|
||||||
const timeout = setTimeout(() => {
|
let evt = await signAuthEvent(makeAuthEvent(this.url, challenge))
|
||||||
const ep = this.openEventPublishes.get(evt.id) as EventPublishResolver
|
let timeout = setTimeout(() => {
|
||||||
|
let ep = this.openEventPublishes.get(evt.id) as EventPublishResolver
|
||||||
if (ep) {
|
if (ep) {
|
||||||
ep.reject(new Error('auth timed out'))
|
ep.reject(new Error('auth timed out'))
|
||||||
this.openEventPublishes.delete(evt.id)
|
this.openEventPublishes.delete(evt.id)
|
||||||
@@ -266,6 +263,9 @@ export class AbstractRelay {
|
|||||||
}, this.publishTimeout)
|
}, this.publishTimeout)
|
||||||
this.openEventPublishes.set(evt.id, { resolve, reject, timeout })
|
this.openEventPublishes.set(evt.id, { resolve, reject, timeout })
|
||||||
this.send('["AUTH",' + JSON.stringify(evt) + ']')
|
this.send('["AUTH",' + JSON.stringify(evt) + ']')
|
||||||
|
} catch (err) {
|
||||||
|
console.warn('subscribe auth function failed:', err)
|
||||||
|
}
|
||||||
})
|
})
|
||||||
return this.authPromise
|
return this.authPromise
|
||||||
}
|
}
|
||||||
|
|||||||
4
jsr.json
4
jsr.json
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "@nostr/tools",
|
"name": "@nostr/tools",
|
||||||
"version": "2.13.3",
|
"version": "2.15.0",
|
||||||
"exports": {
|
"exports": {
|
||||||
".": "./index.ts",
|
".": "./index.ts",
|
||||||
"./core": "./core.ts",
|
"./core": "./core.ts",
|
||||||
@@ -42,7 +42,9 @@
|
|||||||
"./nip94": "./nip94.ts",
|
"./nip94": "./nip94.ts",
|
||||||
"./nip98": "./nip98.ts",
|
"./nip98": "./nip98.ts",
|
||||||
"./nip99": "./nip99.ts",
|
"./nip99": "./nip99.ts",
|
||||||
|
"./nipb7": "./nipb7.ts",
|
||||||
"./fakejson": "./fakejson.ts",
|
"./fakejson": "./fakejson.ts",
|
||||||
"./utils": "./utils.ts"
|
"./utils": "./utils.ts"
|
||||||
|
"./signer": "./signer.ts"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
3
nip46.ts
3
nip46.ts
@@ -6,6 +6,7 @@ import { NIP05_REGEX } from './nip05.ts'
|
|||||||
import { SimplePool } from './pool.ts'
|
import { SimplePool } from './pool.ts'
|
||||||
import { Handlerinformation, NostrConnect } from './kinds.ts'
|
import { Handlerinformation, NostrConnect } from './kinds.ts'
|
||||||
import type { RelayRecord } from './relay.ts'
|
import type { RelayRecord } from './relay.ts'
|
||||||
|
import { Signer } from './signer.ts'
|
||||||
|
|
||||||
var _fetch: any
|
var _fetch: any
|
||||||
|
|
||||||
@@ -82,7 +83,7 @@ export type BunkerSignerParams = {
|
|||||||
onauth?: (url: string) => void
|
onauth?: (url: string) => void
|
||||||
}
|
}
|
||||||
|
|
||||||
export class BunkerSigner {
|
export class BunkerSigner implements Signer {
|
||||||
private params: BunkerSignerParams
|
private params: BunkerSignerParams
|
||||||
private pool: AbstractSimplePool
|
private pool: AbstractSimplePool
|
||||||
private subCloser: SubCloser | undefined
|
private subCloser: SubCloser | undefined
|
||||||
|
|||||||
55
nipb7.test.ts
Normal file
55
nipb7.test.ts
Normal file
@@ -0,0 +1,55 @@
|
|||||||
|
import { test, expect } from 'bun:test'
|
||||||
|
import { BlossomClient } from './nipb7.ts'
|
||||||
|
import { sha256 } from '@noble/hashes/sha256'
|
||||||
|
import { bytesToHex } from './utils.ts'
|
||||||
|
import { PlainKeySigner } from './signer.ts'
|
||||||
|
import { generateSecretKey } from './pure.ts'
|
||||||
|
|
||||||
|
test('blossom', async () => {
|
||||||
|
const BLOSSOM_SERVER = 'blossom.primal.net'
|
||||||
|
const TEST_CONTENT = 'hello world'
|
||||||
|
const TEST_BLOB = new Blob([TEST_CONTENT], { type: 'text/plain' })
|
||||||
|
|
||||||
|
const expectedHash = bytesToHex(sha256(new TextEncoder().encode(TEST_CONTENT)))
|
||||||
|
|
||||||
|
const signer = new PlainKeySigner(generateSecretKey())
|
||||||
|
const client = new BlossomClient(BLOSSOM_SERVER, signer)
|
||||||
|
expect(client).toBeDefined()
|
||||||
|
|
||||||
|
// check for non-existent file should throw
|
||||||
|
const invalidHash = expectedHash.slice(0, 62) + 'ba'
|
||||||
|
let hasThrown = false
|
||||||
|
try {
|
||||||
|
await client.check(invalidHash)
|
||||||
|
} catch (err) {
|
||||||
|
hasThrown = true
|
||||||
|
}
|
||||||
|
expect(hasThrown).toBeTrue()
|
||||||
|
|
||||||
|
// upload hello world blob
|
||||||
|
const descriptor = await client.uploadBlob(TEST_BLOB, 'text/plain')
|
||||||
|
expect(descriptor).toBeDefined()
|
||||||
|
expect(descriptor.sha256).toBe(expectedHash)
|
||||||
|
expect(descriptor.size).toBe(TEST_CONTENT.length)
|
||||||
|
expect(descriptor.type).toBe('text/plain')
|
||||||
|
expect(descriptor.url).toContain(expectedHash)
|
||||||
|
expect(descriptor.uploaded).toBeGreaterThan(0)
|
||||||
|
await client.check(expectedHash)
|
||||||
|
|
||||||
|
// download and verify
|
||||||
|
const downloadedBuffer = await client.download(expectedHash)
|
||||||
|
const downloadedContent = new TextDecoder().decode(downloadedBuffer)
|
||||||
|
expect(downloadedContent).toBe(TEST_CONTENT)
|
||||||
|
|
||||||
|
// list blobs should include our uploaded file
|
||||||
|
const blobs = await client.list()
|
||||||
|
|
||||||
|
expect(Array.isArray(blobs)).toBe(true)
|
||||||
|
const ourBlob = blobs.find(blob => blob.sha256 === expectedHash)
|
||||||
|
expect(ourBlob).toBeDefined()
|
||||||
|
expect(ourBlob?.type).toBe('text/plain')
|
||||||
|
expect(ourBlob?.size).toBe(TEST_CONTENT.length)
|
||||||
|
|
||||||
|
// delete
|
||||||
|
await client.delete(expectedHash)
|
||||||
|
})
|
||||||
203
nipb7.ts
Normal file
203
nipb7.ts
Normal file
@@ -0,0 +1,203 @@
|
|||||||
|
import { sha256 } from '@noble/hashes/sha256'
|
||||||
|
import { EventTemplate } from './core.ts'
|
||||||
|
import { Signer } from './signer.ts'
|
||||||
|
import { bytesToHex } from './utils.ts'
|
||||||
|
|
||||||
|
export type BlobDescriptor = {
|
||||||
|
url: string
|
||||||
|
sha256: string
|
||||||
|
size: number
|
||||||
|
type: string
|
||||||
|
uploaded: number
|
||||||
|
}
|
||||||
|
|
||||||
|
export class BlossomClient {
|
||||||
|
private mediaserver: string
|
||||||
|
private signer: Signer
|
||||||
|
|
||||||
|
constructor(mediaserver: string, signer: Signer) {
|
||||||
|
if (!mediaserver.startsWith('http')) {
|
||||||
|
mediaserver = 'https://' + mediaserver
|
||||||
|
}
|
||||||
|
this.mediaserver = mediaserver.replace(/\/$/, '') + '/'
|
||||||
|
this.signer = signer
|
||||||
|
}
|
||||||
|
|
||||||
|
private async httpCall(
|
||||||
|
method: string,
|
||||||
|
url: string,
|
||||||
|
contentType?: string,
|
||||||
|
addAuthorization?: () => Promise<string>,
|
||||||
|
body?: File | Blob,
|
||||||
|
result?: any,
|
||||||
|
): Promise<any> {
|
||||||
|
const headers: { [_: string]: string } = {}
|
||||||
|
|
||||||
|
if (contentType) {
|
||||||
|
headers['Content-Type'] = contentType
|
||||||
|
}
|
||||||
|
|
||||||
|
if (addAuthorization) {
|
||||||
|
const auth = await addAuthorization()
|
||||||
|
if (auth) {
|
||||||
|
headers['Authorization'] = auth
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const response = await fetch(this.mediaserver + url, {
|
||||||
|
method,
|
||||||
|
headers,
|
||||||
|
body,
|
||||||
|
})
|
||||||
|
|
||||||
|
if (response.status >= 300) {
|
||||||
|
const reason = response.headers.get('X-Reason') || response.statusText
|
||||||
|
throw new Error(`${url} returned an error (${response.status}): ${reason}`)
|
||||||
|
}
|
||||||
|
|
||||||
|
if (result !== null && response.headers.get('content-type')?.includes('application/json')) {
|
||||||
|
return await response.json()
|
||||||
|
}
|
||||||
|
|
||||||
|
return response
|
||||||
|
}
|
||||||
|
|
||||||
|
private async authorizationHeader(modify?: (event: EventTemplate) => void): Promise<string> {
|
||||||
|
const now = Math.floor(Date.now() / 1000)
|
||||||
|
const event: EventTemplate = {
|
||||||
|
created_at: now,
|
||||||
|
kind: 24242,
|
||||||
|
content: 'blossom stuff',
|
||||||
|
tags: [['expiration', String(now + 60)]],
|
||||||
|
}
|
||||||
|
|
||||||
|
if (modify) {
|
||||||
|
modify(event)
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const signedEvent = await this.signer.signEvent(event)
|
||||||
|
const eventJson = JSON.stringify(signedEvent)
|
||||||
|
return 'Nostr ' + btoa(eventJson)
|
||||||
|
} catch (error) {
|
||||||
|
return ''
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private isValid32ByteHex(hash: string): boolean {
|
||||||
|
return /^[a-f0-9]{64}$/i.test(hash)
|
||||||
|
}
|
||||||
|
|
||||||
|
async check(hash: string): Promise<void> {
|
||||||
|
if (!this.isValid32ByteHex(hash)) {
|
||||||
|
throw new Error(`${hash} is not a valid 32-byte hex string`)
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
await this.httpCall('HEAD', hash)
|
||||||
|
} catch (error) {
|
||||||
|
throw new Error(`failed to check for ${hash}: ${error}`)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async uploadBlob(file: File | Blob, contentType?: string): Promise<BlobDescriptor> {
|
||||||
|
const hash = bytesToHex(sha256(new Uint8Array(await file.arrayBuffer())))
|
||||||
|
const actualContentType = contentType || file.type || 'application/octet-stream'
|
||||||
|
|
||||||
|
const bd = await this.httpCall(
|
||||||
|
'PUT',
|
||||||
|
'upload',
|
||||||
|
actualContentType,
|
||||||
|
() =>
|
||||||
|
this.authorizationHeader(evt => {
|
||||||
|
evt.tags.push(['t', 'upload'])
|
||||||
|
evt.tags.push(['x', hash])
|
||||||
|
}),
|
||||||
|
file,
|
||||||
|
{},
|
||||||
|
)
|
||||||
|
|
||||||
|
return bd
|
||||||
|
}
|
||||||
|
|
||||||
|
async uploadFile(file: File): Promise<BlobDescriptor> {
|
||||||
|
return this.uploadBlob(file, file.type)
|
||||||
|
}
|
||||||
|
|
||||||
|
async download(hash: string): Promise<ArrayBuffer> {
|
||||||
|
if (!this.isValid32ByteHex(hash)) {
|
||||||
|
throw new Error(`${hash} is not a valid 32-byte hex string`)
|
||||||
|
}
|
||||||
|
|
||||||
|
const authHeader = await this.authorizationHeader(evt => {
|
||||||
|
evt.tags.push(['t', 'get'])
|
||||||
|
evt.tags.push(['x', hash])
|
||||||
|
})
|
||||||
|
|
||||||
|
const response = await fetch(this.mediaserver + hash, {
|
||||||
|
method: 'GET',
|
||||||
|
headers: {
|
||||||
|
Authorization: authHeader,
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
if (response.status >= 300) {
|
||||||
|
throw new Error(`${hash} is not present in ${this.mediaserver}: ${response.status}`)
|
||||||
|
}
|
||||||
|
|
||||||
|
return await response.arrayBuffer()
|
||||||
|
}
|
||||||
|
|
||||||
|
async downloadAsBlob(hash: string): Promise<Blob> {
|
||||||
|
const arrayBuffer = await this.download(hash)
|
||||||
|
return new Blob([arrayBuffer])
|
||||||
|
}
|
||||||
|
|
||||||
|
async list(): Promise<BlobDescriptor[]> {
|
||||||
|
const pubkey = await this.signer.getPublicKey()
|
||||||
|
|
||||||
|
if (!this.isValid32ByteHex(pubkey)) {
|
||||||
|
throw new Error(`pubkey ${pubkey} is not valid`)
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const bds = await this.httpCall(
|
||||||
|
'GET',
|
||||||
|
`list/${pubkey}`,
|
||||||
|
undefined,
|
||||||
|
() =>
|
||||||
|
this.authorizationHeader(evt => {
|
||||||
|
evt.tags.push(['t', 'list'])
|
||||||
|
}),
|
||||||
|
undefined,
|
||||||
|
[],
|
||||||
|
)
|
||||||
|
return bds
|
||||||
|
} catch (error) {
|
||||||
|
throw new Error(`failed to list blobs: ${error}`)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async delete(hash: string): Promise<void> {
|
||||||
|
if (!this.isValid32ByteHex(hash)) {
|
||||||
|
throw new Error(`${hash} is not a valid 32-byte hex string`)
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
await this.httpCall(
|
||||||
|
'DELETE',
|
||||||
|
hash,
|
||||||
|
undefined,
|
||||||
|
() =>
|
||||||
|
this.authorizationHeader(evt => {
|
||||||
|
evt.tags.push(['t', 'delete'])
|
||||||
|
evt.tags.push(['x', hash])
|
||||||
|
}),
|
||||||
|
undefined,
|
||||||
|
null,
|
||||||
|
)
|
||||||
|
} catch (error) {
|
||||||
|
throw new Error(`failed to delete ${hash}: ${error}`)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
12
package.json
12
package.json
@@ -1,7 +1,7 @@
|
|||||||
{
|
{
|
||||||
"type": "module",
|
"type": "module",
|
||||||
"name": "nostr-tools",
|
"name": "nostr-tools",
|
||||||
"version": "2.13.3",
|
"version": "2.15.0",
|
||||||
"description": "Tools for making a Nostr client.",
|
"description": "Tools for making a Nostr client.",
|
||||||
"repository": {
|
"repository": {
|
||||||
"type": "git",
|
"type": "git",
|
||||||
@@ -213,11 +213,21 @@
|
|||||||
"require": "./lib/cjs/nip99.js",
|
"require": "./lib/cjs/nip99.js",
|
||||||
"types": "./lib/types/nip99.d.ts"
|
"types": "./lib/types/nip99.d.ts"
|
||||||
},
|
},
|
||||||
|
"./nipb7": {
|
||||||
|
"import": "./lib/esm/nipb7.js",
|
||||||
|
"require": "./lib/cjs/nipb7.js",
|
||||||
|
"types": "./lib/types/nipb7.d.ts"
|
||||||
|
},
|
||||||
"./fakejson": {
|
"./fakejson": {
|
||||||
"import": "./lib/esm/fakejson.js",
|
"import": "./lib/esm/fakejson.js",
|
||||||
"require": "./lib/cjs/fakejson.js",
|
"require": "./lib/cjs/fakejson.js",
|
||||||
"types": "./lib/types/fakejson.d.ts"
|
"types": "./lib/types/fakejson.d.ts"
|
||||||
},
|
},
|
||||||
|
"./signer": {
|
||||||
|
"import": "./lib/esm/signer.js",
|
||||||
|
"require": "./lib/cjs/signer.js",
|
||||||
|
"types": "./lib/types/signer.d.ts"
|
||||||
|
},
|
||||||
"./utils": {
|
"./utils": {
|
||||||
"import": "./lib/esm/utils.js",
|
"import": "./lib/esm/utils.js",
|
||||||
"require": "./lib/cjs/utils.js",
|
"require": "./lib/cjs/utils.js",
|
||||||
|
|||||||
23
signer.ts
Normal file
23
signer.ts
Normal file
@@ -0,0 +1,23 @@
|
|||||||
|
import { EventTemplate, VerifiedEvent } from './core.ts'
|
||||||
|
import { finalizeEvent, getPublicKey } from './pure.ts'
|
||||||
|
|
||||||
|
export interface Signer {
|
||||||
|
getPublicKey(): Promise<string>
|
||||||
|
signEvent(event: EventTemplate): Promise<VerifiedEvent>
|
||||||
|
}
|
||||||
|
|
||||||
|
export class PlainKeySigner implements Signer {
|
||||||
|
private secretKey: Uint8Array
|
||||||
|
|
||||||
|
constructor(secretKey: Uint8Array) {
|
||||||
|
this.secretKey = secretKey
|
||||||
|
}
|
||||||
|
|
||||||
|
async getPublicKey(): Promise<string> {
|
||||||
|
return getPublicKey(this.secretKey)
|
||||||
|
}
|
||||||
|
|
||||||
|
async signEvent(event: EventTemplate): Promise<VerifiedEvent> {
|
||||||
|
return finalizeEvent(event, this.secretKey)
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user