From 02e50b323aa1e1188c1cfd90a0f72616b70ff390 Mon Sep 17 00:00:00 2001 From: shocknet-justin Date: Mon, 31 Aug 2026 01:33:25 -0400 Subject: [PATCH 01/14] Accept GFY 6 reason tokens and ignore CLINK replies that are not version 1. Legacy events with no clink_version tag still count as v1. k1 is only valid on a direct payment request. Co-authored-by: Cursor --- README.md | 16 ++++- package-lock.json | 4 +- package.json | 2 +- src/ndebit.ts | 108 ++++++++++++++++++++++++++-------- src/sender.ts | 16 +++-- test/unit/builders.test.mjs | 13 ++++ test/unit/sender.test.mjs | 39 +++++++++++- test/unit/signed-reply.mjs | 21 ++++--- test/unit/validators.test.mjs | 49 +++++++++++++++ 9 files changed, 224 insertions(+), 44 deletions(-) diff --git a/README.md b/README.md index c17b4e0..383487a 100644 --- a/README.md +++ b/README.md @@ -140,6 +140,7 @@ import { newNdebitPaymentRequest, newNdebitFullAccessRequest, newNdebitBudgetRequest, + gfy6Reason, } from '@shocknet/clink-sdk'; // Session flow: scan ndebit QR, pay with matching k1 @@ -178,7 +179,17 @@ sdk.Ndebit(simplePaymentRequest).then(response => { console.log('Payment settled internally.'); } } else if (response.res === 'GFY') { - console.error('Debit error:', response.error); + if (response.reason === gfy6Reason.invoiceAlreadyFailed) { + console.error('Submit a new invoice') + } else if (response.reason === gfy6Reason.k1AlreadyProcessed) { + console.error('Session already used') + } else if (response.reason === gfy6Reason.invoiceInProgress) { + console.error('Wait for the in-flight payment') + } else if (response.reason === gfy6Reason.invoiceAlreadyPaid) { + console.error('Invoice already paid') + } else { + console.error('Debit error:', response.code, response.error) + } } }); @@ -281,6 +292,7 @@ ClinkSDK.fromNprofile(nprofile: string, privateKey: Uint8Array, opts?: { default - `decodeBech32(nip19: string): DecodeResult` - `generateK1(): string` — 32-byte session identifier as lowercase hex (ndebit TLV `3`) - `validateK1(k1: unknown): string` — throws unless `k1` is 64 lowercase hex chars; returns it unchanged +- `gfy6Reason` — GFY code 6 `reason` tokens (`k1_already_processed`, `invoice_in_progress`, `invoice_already_failed`, `invoice_already_paid`) - `isNofferReceipt(parsed: unknown): parsed is NofferReceipt` — `{ res: "ok" }` with optional 64-char hex `preimage` ### Validators @@ -314,7 +326,7 @@ Pinned by this package — import these from `@shocknet/clink-sdk`, not from a s - **`NofferResponse`**: `{ bolt11: string } | { code: number, error: string, range?: { min: number, max: number }, latest?: string }` - **`NofferReceipt`**: `{ res: 'ok', preimage?: string }` — Lightning receipts include `preimage`; internal settlement omits it - **`NdebitData`**: `{ pointer?: string, amount_sats?: number, bolt11?: string, frequency?: BudgetFrequency, k1?: string, description?: string }` -- **`NdebitResponse`**: `{ res: 'ok', preimage?: string } | { res: 'GFY', error: string, code: number }` +- **`NdebitResponse`**: `{ res: 'ok', preimage?: string } | { res: 'GFY', error: string, code: number, reason?: Gfy6Reason, delta?: { max_delta_ms: number, actual_delta_ms: number }, retry_after?: number, range?: { min: number, max: number } }` - **`OfferPointer`**: `{ pubkey: string, relay: string, offer: string, priceType: OfferPriceType, price?: number, currency?: string }` - **`DebitPointer`**: `{ pubkey: string, relay: string, pointer?: string, k1?: string }` - **`OfferPriceType`**: `enum { Fixed = 0, Variable = 1, Spontaneous = 2 }` diff --git a/package-lock.json b/package-lock.json index 1593186..3f3209e 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "@shocknet/clink-sdk", - "version": "1.6.1", + "version": "1.7.4", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "@shocknet/clink-sdk", - "version": "1.6.1", + "version": "1.7.4", "license": "MIT", "dependencies": { "@noble/hashes": "^1.8.0", diff --git a/package.json b/package.json index 617e45b..4356f35 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@shocknet/clink-sdk", - "version": "1.7.3", + "version": "1.7.4", "description": "sdk client for clink", "repository": { "type": "git", diff --git a/src/ndebit.ts b/src/ndebit.ts index 581681f..da59b78 100644 --- a/src/ndebit.ts +++ b/src/ndebit.ts @@ -22,9 +22,9 @@ export const validateK1 = (k1: unknown): string => { export const generateK1 = (): string => bytesToHex(randomBytes(32)) export const validateBudgetFrequency = (frequency: unknown): BudgetFrequency => { - if (typeof frequency !== 'object' || frequency === null) throw new Error('frequency must be an object') + if (typeof frequency !== 'object' || frequency === null || Array.isArray(frequency)) throw new Error('frequency must be an object') if (!('number' in frequency) || typeof frequency.number !== 'number') throw new Error('frequency.number must be a number') - if (frequency.number <= 0 || !Number.isInteger(frequency.number)) throw new Error('frequency.number must be a positive integer') + if (frequency.number <= 0 || !Number.isSafeInteger(frequency.number)) throw new Error('frequency.number must be a positive integer') if (!('unit' in frequency) || typeof frequency.unit !== 'string') throw new Error('frequency.unit must be a string') if (frequency.unit !== 'day' && frequency.unit !== 'week' && frequency.unit !== 'month') { throw new Error('frequency.unit must be day, week, or month') @@ -32,18 +32,63 @@ export const validateBudgetFrequency = (frequency: unknown): BudgetFrequency => return frequency as BudgetFrequency } +const defined = (rec: Record, key: string): boolean => + rec[key] !== undefined + +const assertAmountSats = (n: unknown): number => { + if (typeof n !== 'number' || !Number.isSafeInteger(n) || n <= 0) { + throw new Error('amount_sats must be a positive integer') + } + return n +} + +const assertBolt11 = (bolt11: unknown): string => { + if (typeof bolt11 !== 'string' || bolt11.length === 0) { + throw new Error('bolt11 must be a non-empty string if present') + } + return bolt11 +} + export const validateNdebitData = (data: unknown): NdebitData => { - if (typeof data !== 'object' || data === null) throw new Error('data must be an object') - if ('pointer' in data && typeof data.pointer !== 'string') throw new Error('pointer must be a string if present') - if ('amount_sats' in data && typeof data.amount_sats !== 'number') throw new Error('amount_sats must be a number if present') - if ('bolt11' in data && typeof data.bolt11 !== 'string') throw new Error('bolt11 must be a string if present') - if ('frequency' in data) validateBudgetFrequency(data.frequency) - if ('k1' in data) validateK1(data.k1) - if ('description' in data) { - if (typeof data.description !== 'string') throw new Error('description must be a string if present') - assertDescription(data.description) + if (typeof data !== 'object' || data === null || Array.isArray(data)) throw new Error('data must be an object') + const rec = data as Record + if (defined(rec, 'pointer') && typeof rec.pointer !== 'string') throw new Error('pointer must be a string if present') + if (defined(rec, 'amount_sats')) assertAmountSats(rec.amount_sats) + if (defined(rec, 'bolt11')) assertBolt11(rec.bolt11) + if (defined(rec, 'description')) { + if (typeof rec.description !== 'string') throw new Error('description must be a string if present') + assertDescription(rec.description) } - return data as NdebitData + + const bolt11 = defined(rec, 'bolt11') ? rec.bolt11 as string : undefined + const hasFrequency = defined(rec, 'frequency') + const hasAmount = defined(rec, 'amount_sats') + const hasK1 = defined(rec, 'k1') + + if (hasK1) { + validateK1(rec.k1) + if (!bolt11 || hasFrequency) { + throw new Error('k1 requires a bolt11 payment request') + } + } + if (hasFrequency) { + if (bolt11) { + throw new Error('frequency cannot be combined with bolt11') + } + if (!hasAmount) { + throw new Error('frequency requires amount_sats') + } + validateBudgetFrequency(rec.frequency) + } + + const out: NdebitData = {} + if (defined(rec, 'pointer')) out.pointer = rec.pointer as string + if (hasAmount) out.amount_sats = rec.amount_sats as number + if (bolt11) out.bolt11 = bolt11 + if (hasFrequency) out.frequency = rec.frequency as BudgetFrequency + if (hasK1) out.k1 = rec.k1 as string + if (defined(rec, 'description')) out.description = rec.description as string + return out } const assertDescription = (description?: string) => { @@ -53,30 +98,45 @@ const assertDescription = (description?: string) => { } export type NdebitSuccess = { res: 'ok', preimage?: string } -export type NdebitFailure = { res: 'GFY', error: string, code: number } +export const gfy6Reason = { + k1AlreadyProcessed: 'k1_already_processed', + invoiceInProgress: 'invoice_in_progress', + invoiceAlreadyFailed: 'invoice_already_failed', + invoiceAlreadyPaid: 'invoice_already_paid', +} as const +export type Gfy6Reason = typeof gfy6Reason[keyof typeof gfy6Reason] +export type NdebitFailure = { + res: 'GFY' + error: string + code: number + reason?: Gfy6Reason + delta?: { max_delta_ms: number, actual_delta_ms: number } + retry_after?: number + range?: { min: number, max: number } +} export type NdebitResponse = NdebitSuccess | NdebitFailure export const SendNdebitRequest = async (pool: AbstractSimplePool, privateKey: Uint8Array, relays: string[], toPubKey: string, data: NdebitData, timeoutSeconds?: number): Promise => { - assertDescription(data.description) + const payload = validateNdebitData(data) const publicKey = getPublicKey(privateKey) - const content = encrypt(JSON.stringify(data), getConversationKey(privateKey, toPubKey)) + const content = encrypt(JSON.stringify(payload), getConversationKey(privateKey, toPubKey)) const event = newNdebitEvent(content, publicKey, toPubKey) return sendRequest(pool, { privateKey, publicKey }, relays, toPubKey, event, 21002, timeoutSeconds) } export const newNdebitFullAccessRequest = (pointer?: string): NdebitData => { - return { - pointer: pointer - } + const req: NdebitData = {} + if (pointer !== undefined) req.pointer = pointer + return req } export const newNdebitPaymentRequest = (invoice: string, amount?: number, pointer?: string, k1?: string, description?: string): NdebitData => { assertDescription(description) const req: NdebitData = { - bolt11: invoice, - amount_sats: amount, - pointer: pointer, + bolt11: assertBolt11(invoice), } + if (amount !== undefined) req.amount_sats = assertAmountSats(amount) + if (pointer !== undefined) req.pointer = pointer if (k1 !== undefined) req.k1 = validateK1(k1) if (description !== undefined) req.description = description return req @@ -85,10 +145,10 @@ export const newNdebitPaymentRequest = (invoice: string, amount?: number, pointe export const newNdebitBudgetRequest = (frequency: BudgetFrequency, amount: number, pointer?: string, description?: string): NdebitData => { assertDescription(description) const req: NdebitData = { - amount_sats: amount, - frequency: frequency, - pointer: pointer + amount_sats: assertAmountSats(amount), + frequency: validateBudgetFrequency(frequency), } + if (pointer !== undefined) req.pointer = pointer if (description !== undefined) req.description = description return req } diff --git a/src/sender.ts b/src/sender.ts index c261286..9b0cbd5 100644 --- a/src/sender.ts +++ b/src/sender.ts @@ -1,6 +1,5 @@ import { nip44, finalizeEvent, verifyEvent, UnsignedEvent, type Event } from "nostr-tools" import { AbstractSimplePool, SubCloser } from "nostr-tools/lib/types/pool" -import { CLINK_VERSION } from "./constants.js" import { isNofferReceipt } from "./receipt.js" const { getConversationKey, decrypt } = nip44 @@ -25,6 +24,13 @@ const firstTag = (tags: string[][], name: string): string | undefined => const hexEq = (a: string, b: string): boolean => a.toLowerCase() === b.toLowerCase() +const SUPPORTED_CLINK_VERSION = '1' + +export const isSupportedClinkVersion = (tags: string[][]): boolean => { + const versions = tags.filter(t => t[0] === 'clink_version').map(t => t[1]) + return versions.length === 0 || versions.every(v => v === SUPPORTED_CLINK_VERSION) +} + type ResponseExpect = { pubkey: string kind: number @@ -32,7 +38,7 @@ type ResponseExpect = { requestId: string } -/** Accept only a signed CLINK reply from the expected peer, tagged to this request. */ +/** Accept a signed CLINK v1 reply, including legacy events with no version tag. */ export const isClinkResponse = (event: Event, expect: ResponseExpect): boolean => { if (event.kind !== expect.kind) { return false @@ -43,13 +49,13 @@ export const isClinkResponse = (event: Event, expect: ResponseExpect): boolean = if (!verifyEvent(event)) { return false } - if (firstTag(event.tags, "clink_version") !== CLINK_VERSION) { + if (!hexEq(firstTag(event.tags, "p") ?? "", expect.requestorPub)) { return false } - if (!hexEq(firstTag(event.tags, "p") ?? "", expect.requestorPub)) { + if ((firstTag(event.tags, "e") ?? "") !== expect.requestId) { return false } - return (firstTag(event.tags, "e") ?? "") === expect.requestId + return isSupportedClinkVersion(event.tags) } type Pair = { privateKey: Uint8Array, publicKey: string } diff --git a/test/unit/builders.test.mjs b/test/unit/builders.test.mjs index 78d3256..ae09f04 100644 --- a/test/unit/builders.test.mjs +++ b/test/unit/builders.test.mjs @@ -18,6 +18,7 @@ describe('request builders', () => { amount_sats: 5000, pointer: 'ptr', }) + assert.deepEqual(newNdebitPaymentRequest('lnbc1test'), { bolt11: 'lnbc1test' }) }) it('builds ndebit payment request with k1', () => { @@ -29,6 +30,13 @@ describe('request builders', () => { k1, }) assert.throws(() => newNdebitPaymentRequest('lnbc1test', 5000, 'ptr', 'not-a-k1')) + assert.throws(() => newNdebitPaymentRequest('', 5000, 'ptr')) + assert.throws(() => newNdebitPaymentRequest('lnbc1test', 0, 'ptr')) + assert.throws(() => newNdebitPaymentRequest('lnbc1test', -1, 'ptr')) + assert.throws(() => newNdebitPaymentRequest('lnbc1test', 1.5, 'ptr')) + assert.throws(() => newNdebitPaymentRequest('lnbc1test', Number.NaN, 'ptr')) + assert.throws(() => newNdebitPaymentRequest('lnbc1test', Number.POSITIVE_INFINITY, 'ptr')) + assert.throws(() => newNdebitPaymentRequest('lnbc1test', Number.MAX_SAFE_INTEGER + 1, 'ptr')) }) it('builds ndebit payment request with description', () => { @@ -45,6 +53,7 @@ describe('request builders', () => { it('builds ndebit full access request', () => { assert.deepEqual(newNdebitFullAccessRequest('ptr'), { pointer: 'ptr' }) + assert.deepEqual(newNdebitFullAccessRequest(), {}) }) it('builds ndebit budget request', () => { @@ -53,6 +62,10 @@ describe('request builders', () => { frequency: { number: 1, unit: 'week' }, pointer: 'ptr', }) + assert.throws(() => + newNdebitBudgetRequest({ number: Number.MAX_SAFE_INTEGER + 1, unit: 'week' }, 1000) + ) + assert.throws(() => newNdebitBudgetRequest({ number: 1, unit: 'year' }, 1000)) }) it('builds ndebit budget request with description', () => { diff --git a/test/unit/sender.test.mjs b/test/unit/sender.test.mjs index 4bea80f..2d2b460 100644 --- a/test/unit/sender.test.mjs +++ b/test/unit/sender.test.mjs @@ -388,7 +388,23 @@ describe('sender lifecycle', () => { assert.deepEqual(result, { bolt11: 'lnbc1dummy' }) }) - it('ignores a signed reply with an unsupported clink_version', async () => { + it('accepts a signed reply with no clink_version', async () => { + const clientPriv = generateSecretKey() + const clientPub = getPublicKey(clientPriv) + const serverPriv = generateSecretKey() + const serverPub = getPublicKey(serverPriv) + + const pool = createMockPool({ + replyFactory: (request) => [ + signedClinkReply(serverPriv, clientPub, request.id, { bolt11: 'lnbc1legacy' }, 21001, { omitClinkVersion: true }), + ], + }) + + const result = await sendOffer(pool, clientPriv, clientPub, serverPub) + assert.deepEqual(result, { bolt11: 'lnbc1legacy' }) + }) + + it('ignores a signed reply with explicit unsupported clink_version', async () => { const clientPriv = generateSecretKey() const clientPub = getPublicKey(clientPriv) const serverPriv = generateSecretKey() @@ -397,12 +413,29 @@ describe('sender lifecycle', () => { const pool = createMockPool({ replyFactory: (request) => [ signedClinkReply(serverPriv, clientPub, request.id, { bolt11: 'v2' }, 21001, { clinkVersion: '2' }), - signedClinkReply(serverPriv, clientPub, request.id, { bolt11: 'lnbc1dummy' }, 21001), + signedClinkReply(serverPriv, clientPub, request.id, { bolt11: 'lnbc1v1' }, 21001), ], }) const result = await sendOffer(pool, clientPriv, clientPub, serverPub) - assert.deepEqual(result, { bolt11: 'lnbc1dummy' }) + assert.deepEqual(result, { bolt11: 'lnbc1v1' }) + }) + + it('ignores a signed reply with mixed clink_version tags', async () => { + const clientPriv = generateSecretKey() + const clientPub = getPublicKey(clientPriv) + const serverPriv = generateSecretKey() + const serverPub = getPublicKey(serverPriv) + + const pool = createMockPool({ + replyFactory: (request) => [ + signedClinkReply(serverPriv, clientPub, request.id, { bolt11: 'mixed' }, 21001, { extraTags: [['clink_version', '2']] }), + signedClinkReply(serverPriv, clientPub, request.id, { bolt11: 'lnbc1v1' }, 21001), + ], + }) + + const result = await sendOffer(pool, clientPriv, clientPub, serverPub) + assert.deepEqual(result, { bolt11: 'lnbc1v1' }) }) it('matches peer pubkey case-insensitively', async () => { diff --git a/test/unit/signed-reply.mjs b/test/unit/signed-reply.mjs index 317f59f..4c9fc93 100644 --- a/test/unit/signed-reply.mjs +++ b/test/unit/signed-reply.mjs @@ -2,14 +2,21 @@ import { finalizeEvent, nip44 } from 'nostr-tools' const { getConversationKey, encrypt } = nip44 -export const signedClinkReply = (serverPriv, clientPub, requestId, payload, kind, extra = {}) => - finalizeEvent({ +export const signedClinkReply = (serverPriv, clientPub, requestId, payload, kind, extra = {}) => { + const tags = [ + ['p', extra.p ?? clientPub], + ['e', extra.e ?? requestId], + ] + if (!extra.omitClinkVersion) { + tags.push(['clink_version', extra.clinkVersion ?? '1']) + } + if (extra.extraTags) { + tags.push(...extra.extraTags) + } + return finalizeEvent({ kind, created_at: Math.floor(Date.now() / 1000), - tags: [ - ['p', extra.p ?? clientPub], - ['e', extra.e ?? requestId], - ['clink_version', extra.clinkVersion ?? '1'], - ], + tags, content: extra.content ?? encrypt(JSON.stringify(payload), getConversationKey(serverPriv, clientPub)), }, serverPriv) +} diff --git a/test/unit/validators.test.mjs b/test/unit/validators.test.mjs index 4bcee74..3c5d3f9 100644 --- a/test/unit/validators.test.mjs +++ b/test/unit/validators.test.mjs @@ -11,6 +11,12 @@ import { newCreateRequest, newListRequest, newGetRequest, + gfy6Reason, + SendNdebitRequest, + generateSecretKey, + newNdebitFullAccessRequest, + newNdebitPaymentRequest, + newNdebitBudgetRequest, } from '../../build/index.js' describe('validators', () => { @@ -21,6 +27,13 @@ describe('validators', () => { assert.throws(() => validateK1('short')) }) + it('exports gfy6 reason tokens', () => { + assert.equal(gfy6Reason.k1AlreadyProcessed, 'k1_already_processed') + assert.equal(gfy6Reason.invoiceInProgress, 'invoice_in_progress') + assert.equal(gfy6Reason.invoiceAlreadyFailed, 'invoice_already_failed') + assert.equal(gfy6Reason.invoiceAlreadyPaid, 'invoice_already_paid') + }) + it('validates budget frequency', () => { assert.deepEqual(validateBudgetFrequency({ number: 1, unit: 'week' }), { number: 1, @@ -40,6 +53,42 @@ describe('validators', () => { assert.throws(() => validateNdebitData({ bolt11: 1 })) assert.throws(() => validateNdebitData({ description: 'x'.repeat(101) })) assert.throws(() => validateNdebitData({ k1: 'bad' })) + assert.throws(() => validateNdebitData({ pointer: 'p', k1 })) + assert.throws(() => validateNdebitData({ + pointer: 'p', + k1, + amount_sats: 500, + frequency: { number: 1, unit: 'day' }, + })) + assert.throws(() => validateNdebitData([])) + assert.throws(() => validateNdebitData({ bolt11: 'lnbc1', amount_sats: 21, frequency: { number: 1, unit: 'day' } })) + assert.throws(() => validateNdebitData({ frequency: { number: 1, unit: 'day' } })) + assert.throws(() => validateNdebitData({ bolt11: '' })) + assert.throws(() => validateNdebitData({ bolt11: 'lnbc1', amount_sats: 0 })) + assert.throws(() => validateNdebitData({ bolt11: 'lnbc1', amount_sats: -1 })) + assert.throws(() => validateNdebitData({ bolt11: 'lnbc1', amount_sats: 1.5 })) + assert.throws(() => validateNdebitData({ bolt11: 'lnbc1', amount_sats: Number.NaN })) + assert.throws(() => validateNdebitData({ bolt11: 'lnbc1', amount_sats: Number.POSITIVE_INFINITY })) + assert.throws(() => validateNdebitData({ bolt11: 'lnbc1', amount_sats: Number.MAX_SAFE_INTEGER + 1 })) + assert.throws(() => newNdebitBudgetRequest({ number: 1, unit: 'day' }, 0)) + }) + + it('treats undefined optional fields as omitted', () => { + assert.deepEqual(validateNdebitData(newNdebitFullAccessRequest()), {}) + assert.deepEqual(validateNdebitData(newNdebitPaymentRequest('lnbc1')), { bolt11: 'lnbc1' }) + assert.deepEqual( + validateNdebitData(newNdebitBudgetRequest({ number: 1, unit: 'day' }, 500)), + { amount_sats: 500, frequency: { number: 1, unit: 'day' } }, + ) + assert.deepEqual(validateNdebitData({ pointer: undefined, bolt11: 'lnbc1' }), { bolt11: 'lnbc1' }) + }) + + it('SendNdebitRequest validates before sending', async () => { + const k1 = '0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef' + await assert.rejects( + SendNdebitRequest({}, generateSecretKey(), [], 'aa'.repeat(32), { pointer: 'p', k1 }), + /k1 requires a bolt11 payment request/, + ) }) it('validates noffer data', () => { From d22c91f2d98104a480c4fc650df180c2c9834d3e Mon Sep 17 00:00:00 2001 From: shocknet-justin Date: Fri, 4 Sep 2026 09:23:11 -0400 Subject: [PATCH 02/14] beacon includes --- src/nbeacon.ts | 8 ++++---- test/unit/enroll-beacon.test.mjs | 9 +++++++++ 2 files changed, 13 insertions(+), 4 deletions(-) diff --git a/src/nbeacon.ts b/src/nbeacon.ts index 335e66f..157c38e 100644 --- a/src/nbeacon.ts +++ b/src/nbeacon.ts @@ -93,9 +93,9 @@ export const parseClinkBeaconContent = (raw: unknown): ClinkBeaconContent => { return content } -const dTag = (tags: string[][]): string | undefined => tags.find(t => t[0] === "d")?.[1] -const versionTag = (tags: string[][]): string | undefined => tags.find(t => t[0] === "clink_version")?.[1] -const operatorTag = (tags: string[][]): string | undefined => tags.find(t => t[0] === "operator")?.[1] +const dTagValues = (tags: string[][]): string[] => tags.filter(t => t[0] === "d" && t[1]).map(t => t[1]) +const versionTag = (tags: string[][]): string | undefined => tags.find(t => t[0] === "clink_version" && t[1])?.[1] +const operatorTag = (tags: string[][]): string | undefined => tags.find(t => t[0] === "operator" && t[1])?.[1] export const parseClinkBeaconEvent = (event: Event): ClinkBeacon | null => { if (!verifyEvent(event)) { @@ -104,7 +104,7 @@ export const parseClinkBeaconEvent = (event: Event): ClinkBeacon | null => { if (event.kind !== CLINK_BEACON_KIND) { return null } - if (dTag(event.tags) !== CLINK_BEACON_D_TAG) { + if (!dTagValues(event.tags).includes(CLINK_BEACON_D_TAG)) { return null } if (versionTag(event.tags) !== CLINK_VERSION) { diff --git a/test/unit/enroll-beacon.test.mjs b/test/unit/enroll-beacon.test.mjs index ae9bb39..d2ba0ae 100644 --- a/test/unit/enroll-beacon.test.mjs +++ b/test/unit/enroll-beacon.test.mjs @@ -100,6 +100,15 @@ describe('beacon parse', () => { })), null) }) + it('accepts clink-node alongside a legacy d-tag', () => { + const beacon = parseClinkBeaconEvent(signBeacon({ + tags: [['d', 'Lightning.Pub'], ['d', CLINK_BEACON_D_TAG], ['clink_version', CLINK_VERSION]], + content: JSON.stringify({ enroll_difficulty: 18 }), + })) + assert.ok(beacon) + assert.equal(enrollDifficultyFromBeacon(beacon, now * 1000), 18) + }) + it('uses enroll_difficulty only while the beacon is fresh', () => { const beacon = parseClinkBeaconEvent(signBeacon({ tags: [['d', CLINK_BEACON_D_TAG], ['clink_version', CLINK_VERSION], ['operator', 'CD'.repeat(32)]], From 3f49f54da58a7425539db54f140b7e0d49826ca9 Mon Sep 17 00:00:00 2001 From: shocknet-justin Date: Fri, 18 Sep 2026 01:35:28 -0400 Subject: [PATCH 03/14] Reject request timeouts as Error instead of a bare string. Callers that read err.message were getting undefined; 1.8.0 matches the rest of sendRequest. Co-authored-by: Cursor --- package.json | 2 +- src/sender.ts | 2 +- test/unit/sender.test.mjs | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/package.json b/package.json index 617e45b..55bec45 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@shocknet/clink-sdk", - "version": "1.7.3", + "version": "1.8.0", "description": "sdk client for clink", "repository": { "type": "git", diff --git a/src/sender.ts b/src/sender.ts index c261286..4b62ae9 100644 --- a/src/sender.ts +++ b/src/sender.ts @@ -179,7 +179,7 @@ export const sendRequest = async (pool: AbstractSimplePool, pair: Pair, relay if (timeoutSeconds) { timer = setTimeout(() => { log(`[ClinkSDK] Timeout after ${timeoutSeconds}s - no response received for kind=${kindExpected}, eventId=${signed.id}`) - fail('failed to get response in time') + fail(new Error('failed to get response in time')) }, timeoutSeconds * 1000) } diff --git a/test/unit/sender.test.mjs b/test/unit/sender.test.mjs index 4bea80f..be87ec7 100644 --- a/test/unit/sender.test.mjs +++ b/test/unit/sender.test.mjs @@ -433,7 +433,7 @@ describe('sender lifecycle', () => { await assert.rejects( () => sendOffer(pool, clientPriv, clientPub, serverPub, 0.05), - /failed to get response in time/ + (err) => err instanceof Error && err.message === 'failed to get response in time' ) assert.equal(pool.wasClosed(), true) }) From 1fbdfb5cecee5ff46b643c88930788ddb02fe272 Mon Sep 17 00:00:00 2001 From: "Justin (shocknet)" <34176400+shocknet-justin@users.noreply.github.com> Date: Fri, 18 Sep 2026 02:05:26 -0400 Subject: [PATCH 04/14] Update package.json --- package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/package.json b/package.json index 4356f35..55bec45 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@shocknet/clink-sdk", - "version": "1.7.4", + "version": "1.8.0", "description": "sdk client for clink", "repository": { "type": "git", From 191af0bf7e2292400a39e297f6cf354ea3a99aeb Mon Sep 17 00:00:00 2001 From: boufni95 Date: Fri, 25 Sep 2026 18:27:08 +0000 Subject: [PATCH 05/14] update tools --- package-lock.json | 632 ++++++++++++++++++++++++++++++++++------------ package.json | 15 +- src/index.ts | 2 +- src/ndebit.ts | 2 +- src/nmanage.ts | 2 +- src/noffer.ts | 2 +- src/sender.ts | 2 +- 7 files changed, 488 insertions(+), 169 deletions(-) diff --git a/package-lock.json b/package-lock.json index 1593186..476fb30 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,52 +1,75 @@ { "name": "@shocknet/clink-sdk", - "version": "1.6.1", + "version": "1.7.3", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "@shocknet/clink-sdk", - "version": "1.6.1", + "version": "1.7.3", "license": "MIT", "dependencies": { "@noble/hashes": "^1.8.0", - "@scure/base": "^1.2.5", - "nostr-tools": "2.15.1" + "@scure/base": "^2.4.0", + "nostr-tools": "2.25.2", + "rimraf": "^6.0.1", + "typescript": "^5.8.3" }, "devDependencies": { - "@types/node": "^22.15.2", - "rimraf": "^6.1.3", - "typescript": "^5.9.3" + "@types/node": "^22.15.2" + } + }, + "node_modules/@isaacs/cliui": { + "version": "8.0.2", + "resolved": "https://registry.npmjs.org/@isaacs/cliui/-/cliui-8.0.2.tgz", + "integrity": "sha512-O8jcjabXaleOG9DQ0+ARXWZBTfnP4WNAqzuiJK7ll44AmxGKv/J2M4TPjxjY3znBCfvBXFzucm1twdyFybFqEA==", + "license": "ISC", + "dependencies": { + "string-width": "^5.1.2", + "string-width-cjs": "npm:string-width@^4.2.0", + "strip-ansi": "^7.0.1", + "strip-ansi-cjs": "npm:strip-ansi@^6.0.1", + "wrap-ansi": "^8.1.0", + "wrap-ansi-cjs": "npm:wrap-ansi@^7.0.0" + }, + "engines": { + "node": ">=12" } }, "node_modules/@noble/ciphers": { - "version": "0.5.3", - "resolved": "https://registry.npmjs.org/@noble/ciphers/-/ciphers-0.5.3.tgz", - "integrity": "sha512-B0+6IIHiqEs3BPMT0hcRmHvEj2QHOLu+uwt+tqDDeVd0oyVzh7BPrDcPjRnV1PV/5LaknXJJQvOuRGR0zQJz+w==", + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/@noble/ciphers/-/ciphers-2.1.1.tgz", + "integrity": "sha512-bysYuiVfhxNJuldNXlFEitTVdNnYUc+XNJZd7Qm2a5j1vZHgY+fazadNFWFaMK/2vye0JVlxV3gHmC0WDfAOQw==", "license": "MIT", + "engines": { + "node": ">= 20.19.0" + }, "funding": { "url": "https://paulmillr.com/funding/" } }, "node_modules/@noble/curves": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/@noble/curves/-/curves-1.2.0.tgz", - "integrity": "sha512-oYclrNgRaM9SsBUBVbb8M6DTV7ZHRTKugureoYEncY5c65HOmRzvSiTE3y5CYaPYJA/GVkrhXEoF0M3Ya9PMnw==", + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/@noble/curves/-/curves-2.0.1.tgz", + "integrity": "sha512-vs1Az2OOTBiP4q0pwjW5aF0xp9n4MxVrmkFBxc6EKZc6ddYx5gaZiAsZoq0uRRXWbi3AT/sBqn05eRPtn1JCPw==", "license": "MIT", "dependencies": { - "@noble/hashes": "1.3.2" + "@noble/hashes": "2.0.1" + }, + "engines": { + "node": ">= 20.19.0" }, "funding": { "url": "https://paulmillr.com/funding/" } }, "node_modules/@noble/curves/node_modules/@noble/hashes": { - "version": "1.3.2", - "resolved": "https://registry.npmjs.org/@noble/hashes/-/hashes-1.3.2.tgz", - "integrity": "sha512-MVC8EAQp7MvEcm30KWENFjgR+Mkmf+D189XJTkFIlwohU5hcBbn1ZkKq7KVTi2Hme3PMGF390DaL52beVrIihQ==", + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/@noble/hashes/-/hashes-2.0.1.tgz", + "integrity": "sha512-XlOlEbQcE9fmuXxrVTXCTlG2nlRXa9Rj3rr5Ue/+tX+nmkgbX720YHh0VR3hBF9xDvwnb8D2shVGOwNx+ulArw==", "license": "MIT", "engines": { - "node": ">= 16" + "node": ">= 20.19.0" }, "funding": { "url": "https://paulmillr.com/funding/" @@ -65,206 +88,272 @@ } }, "node_modules/@scure/base": { - "version": "1.2.5", - "resolved": "https://registry.npmjs.org/@scure/base/-/base-1.2.5.tgz", - "integrity": "sha512-9rE6EOVeIQzt5TSu4v+K523F8u6DhBsoZWPGKlnCshhlDhy0kJzUX4V+tr2dWmzF1GdekvThABoEQBGBQI7xZw==", + "version": "2.4.0", + "resolved": "https://registry.npmjs.org/@scure/base/-/base-2.4.0.tgz", + "integrity": "sha512-thZ1TuJwFwBblOhgsjDKvvGirBxNp+wSvY/DR6tJBJOTDhdAAcHJ8Vbr2eFnqaxeca4+t0i9KBf+uHYGWwZORg==", "license": "MIT", "funding": { "url": "https://paulmillr.com/funding/" } }, "node_modules/@scure/bip32": { - "version": "1.3.1", - "resolved": "https://registry.npmjs.org/@scure/bip32/-/bip32-1.3.1.tgz", - "integrity": "sha512-osvveYtyzdEVbt3OfwwXFr4P2iVBL5u1Q3q4ONBfDY/UpOuXmOlbgwc1xECEboY8wIays8Yt6onaWMUdUbfl0A==", + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/@scure/bip32/-/bip32-2.0.1.tgz", + "integrity": "sha512-4Md1NI5BzoVP+bhyJaY3K6yMesEFzNS1sE/cP+9nuvE7p/b0kx9XbpDHHFl8dHtufcbdHRUUQdRqLIPHN/s7yA==", "license": "MIT", "dependencies": { - "@noble/curves": "~1.1.0", - "@noble/hashes": "~1.3.1", - "@scure/base": "~1.1.0" + "@noble/curves": "2.0.1", + "@noble/hashes": "2.0.1", + "@scure/base": "2.0.0" }, "funding": { "url": "https://paulmillr.com/funding/" } }, - "node_modules/@scure/bip32/node_modules/@noble/curves": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/@noble/curves/-/curves-1.1.0.tgz", - "integrity": "sha512-091oBExgENk/kGj3AZmtBDMpxQPDtxQABR2B9lb1JbVTs6ytdzZNwvhxQ4MWasRNEzlbEH8jCWFCwhF/Obj5AA==", + "node_modules/@scure/bip32/node_modules/@noble/hashes": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/@noble/hashes/-/hashes-2.0.1.tgz", + "integrity": "sha512-XlOlEbQcE9fmuXxrVTXCTlG2nlRXa9Rj3rr5Ue/+tX+nmkgbX720YHh0VR3hBF9xDvwnb8D2shVGOwNx+ulArw==", "license": "MIT", - "dependencies": { - "@noble/hashes": "1.3.1" + "engines": { + "node": ">= 20.19.0" }, "funding": { "url": "https://paulmillr.com/funding/" } }, - "node_modules/@scure/bip32/node_modules/@noble/curves/node_modules/@noble/hashes": { - "version": "1.3.1", - "resolved": "https://registry.npmjs.org/@noble/hashes/-/hashes-1.3.1.tgz", - "integrity": "sha512-EbqwksQwz9xDRGfDST86whPBgM65E0OH/pCgqW0GBVzO22bNE+NuIbeTb714+IfSjU3aRk47EUvXIb5bTsenKA==", + "node_modules/@scure/bip39": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/@scure/bip39/-/bip39-2.0.1.tgz", + "integrity": "sha512-PsxdFj/d2AcJcZDX1FXN3dDgitDDTmwf78rKZq1a6c1P1Nan1X/Sxc7667zU3U+AN60g7SxxP0YCVw2H/hBycg==", "license": "MIT", - "engines": { - "node": ">= 16" + "dependencies": { + "@noble/hashes": "2.0.1", + "@scure/base": "2.0.0" }, "funding": { "url": "https://paulmillr.com/funding/" } }, - "node_modules/@scure/bip32/node_modules/@noble/hashes": { - "version": "1.3.3", - "resolved": "https://registry.npmjs.org/@noble/hashes/-/hashes-1.3.3.tgz", - "integrity": "sha512-V7/fPHgl+jsVPXqqeOzT8egNj2iBIVt+ECeMMG8TdcnTikP3oaBtUVqpT/gYCR68aEBJSF+XbYUxStjbFMqIIA==", + "node_modules/@scure/bip39/node_modules/@noble/hashes": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/@noble/hashes/-/hashes-2.0.1.tgz", + "integrity": "sha512-XlOlEbQcE9fmuXxrVTXCTlG2nlRXa9Rj3rr5Ue/+tX+nmkgbX720YHh0VR3hBF9xDvwnb8D2shVGOwNx+ulArw==", "license": "MIT", "engines": { - "node": ">= 16" + "node": ">= 20.19.0" }, "funding": { "url": "https://paulmillr.com/funding/" } }, - "node_modules/@scure/bip32/node_modules/@scure/base": { - "version": "1.1.9", - "resolved": "https://registry.npmjs.org/@scure/base/-/base-1.1.9.tgz", - "integrity": "sha512-8YKhl8GHiNI/pU2VMaofa2Tor7PJRAjwQLBBuilkJ9L5+13yVbC7JO/wS7piioAvPSwR3JKM1IJ/u4xQzbcXKg==", + "node_modules/@types/node": { + "version": "22.15.21", + "resolved": "https://registry.npmjs.org/@types/node/-/node-22.15.21.tgz", + "integrity": "sha512-EV/37Td6c+MgKAbkcLG6vqZ2zEYHD7bvSrzqqs2RIhbA6w3x+Dqz8MZM3sP6kGTeLrdoOgKZe+Xja7tUB2DNkQ==", + "dev": true, "license": "MIT", - "funding": { - "url": "https://paulmillr.com/funding/" + "dependencies": { + "undici-types": "~6.21.0" } }, - "node_modules/@scure/bip39": { - "version": "1.2.1", - "resolved": "https://registry.npmjs.org/@scure/bip39/-/bip39-1.2.1.tgz", - "integrity": "sha512-Z3/Fsz1yr904dduJD0NpiyRHhRYHdcnyh73FZWiV+/qhWi83wNJ3NWolYqCEN+ZWsUz2TWwajJggcRE9r1zUYg==", + "node_modules/ansi-regex": { + "version": "6.1.0", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-6.1.0.tgz", + "integrity": "sha512-7HSX4QQb4CspciLpVFwyRe79O3xsIZDDLER21kERQ71oaPodF8jL725AgJMFAYbooIqolJoRLuM81SpeUkpkvA==", "license": "MIT", - "dependencies": { - "@noble/hashes": "~1.3.0", - "@scure/base": "~1.1.0" + "engines": { + "node": ">=12" }, "funding": { - "url": "https://paulmillr.com/funding/" + "url": "https://github.com/chalk/ansi-regex?sponsor=1" } }, - "node_modules/@scure/bip39/node_modules/@noble/hashes": { - "version": "1.3.3", - "resolved": "https://registry.npmjs.org/@noble/hashes/-/hashes-1.3.3.tgz", - "integrity": "sha512-V7/fPHgl+jsVPXqqeOzT8egNj2iBIVt+ECeMMG8TdcnTikP3oaBtUVqpT/gYCR68aEBJSF+XbYUxStjbFMqIIA==", + "node_modules/ansi-styles": { + "version": "6.2.1", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-6.2.1.tgz", + "integrity": "sha512-bN798gFfQX+viw3R7yrGWRqnrN2oRkEkUjjl4JNn4E8GxxbjtG3FbrEIIY3l8/hrwUwIeCZvi4QuOTP4MErVug==", "license": "MIT", "engines": { - "node": ">= 16" + "node": ">=12" }, "funding": { - "url": "https://paulmillr.com/funding/" + "url": "https://github.com/chalk/ansi-styles?sponsor=1" } }, - "node_modules/@scure/bip39/node_modules/@scure/base": { - "version": "1.1.9", - "resolved": "https://registry.npmjs.org/@scure/base/-/base-1.1.9.tgz", - "integrity": "sha512-8YKhl8GHiNI/pU2VMaofa2Tor7PJRAjwQLBBuilkJ9L5+13yVbC7JO/wS7piioAvPSwR3JKM1IJ/u4xQzbcXKg==", + "node_modules/balanced-match": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz", + "integrity": "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==", + "license": "MIT" + }, + "node_modules/brace-expansion": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-2.0.1.tgz", + "integrity": "sha512-XnAIvQ8eM+kC6aULx6wuQiwVsnzsi9d3WxzV3FpWTGA19F621kwdbsAcFKXgKUHZWsy+mY6iL1sHTxWEFCytDA==", "license": "MIT", - "funding": { - "url": "https://paulmillr.com/funding/" + "dependencies": { + "balanced-match": "^1.0.0" } }, - "node_modules/@types/node": { - "version": "22.15.21", - "resolved": "https://registry.npmjs.org/@types/node/-/node-22.15.21.tgz", - "integrity": "sha512-EV/37Td6c+MgKAbkcLG6vqZ2zEYHD7bvSrzqqs2RIhbA6w3x+Dqz8MZM3sP6kGTeLrdoOgKZe+Xja7tUB2DNkQ==", - "dev": true, + "node_modules/color-convert": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz", + "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==", "license": "MIT", "dependencies": { - "undici-types": "~6.21.0" + "color-name": "~1.1.4" + }, + "engines": { + "node": ">=7.0.0" } }, - "node_modules/balanced-match": { - "version": "4.0.4", - "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-4.0.4.tgz", - "integrity": "sha512-BLrgEcRTwX2o6gGxGOCNyMvGSp35YofuYzw9h1IMTRmKqttAZZVU67bdb9Pr2vUHA8+j3i2tJfjO6C6+4myGTA==", - "dev": true, + "node_modules/color-name": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz", + "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==", + "license": "MIT" + }, + "node_modules/cross-spawn": { + "version": "7.0.6", + "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.6.tgz", + "integrity": "sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA==", "license": "MIT", + "dependencies": { + "path-key": "^3.1.0", + "shebang-command": "^2.0.0", + "which": "^2.0.1" + }, "engines": { - "node": "18 || 20 || >=22" + "node": ">= 8" } }, - "node_modules/brace-expansion": { - "version": "5.0.8", - "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-5.0.8.tgz", - "integrity": "sha512-JZyDyq3D4AUifKTPOB7DELf6XsB3WdPuNxCtob1vFXPsSXhdAiHBWJ/tJ8HAc9aH84BK+5JFZLNkJKx3G9kzQg==", - "dev": true, - "license": "MIT", + "node_modules/eastasianwidth": { + "version": "0.2.0", + "resolved": "https://registry.npmjs.org/eastasianwidth/-/eastasianwidth-0.2.0.tgz", + "integrity": "sha512-I88TYZWc9XiYHRQ4/3c5rjjfgkjhLyW2luGIheGERbNQ6OY7yTybanSpDXZa8y7VUP9YmDcYa+eyq4ca7iLqWA==", + "license": "MIT" + }, + "node_modules/emoji-regex": { + "version": "9.2.2", + "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-9.2.2.tgz", + "integrity": "sha512-L18DaJsXSUk2+42pv8mLs5jJT2hqFkFE4j21wOmgbUqsZ2hL72NsUU785g9RXgo3s0ZNgVl42TiHp3ZtOv/Vyg==", + "license": "MIT" + }, + "node_modules/foreground-child": { + "version": "3.3.1", + "resolved": "https://registry.npmjs.org/foreground-child/-/foreground-child-3.3.1.tgz", + "integrity": "sha512-gIXjKqtFuWEgzFRJA9WCQeSJLZDjgJUOMCMzxtvFq/37KojM1BFGufqsCy0r4qSQmYLsZYMeyRqzIWOMup03sw==", + "license": "ISC", "dependencies": { - "balanced-match": "^4.0.2" + "cross-spawn": "^7.0.6", + "signal-exit": "^4.0.1" }, "engines": { - "node": "20 || >=22" + "node": ">=14" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" } }, "node_modules/glob": { - "version": "13.0.6", - "resolved": "https://registry.npmjs.org/glob/-/glob-13.0.6.tgz", - "integrity": "sha512-Wjlyrolmm8uDpm/ogGyXZXb1Z+Ca2B8NbJwqBVg0axK9GbBeoS7yGV6vjXnYdGm6X53iehEuxxbyiKp8QmN4Vw==", - "dev": true, + "version": "11.0.2", + "resolved": "https://registry.npmjs.org/glob/-/glob-11.0.2.tgz", + "integrity": "sha512-YT7U7Vye+t5fZ/QMkBFrTJ7ZQxInIUjwyAjVj84CYXqgBdv30MFUPGnBR6sQaVq6Is15wYJUsnzTuWaGRBhBAQ==", + "license": "ISC", + "dependencies": { + "foreground-child": "^3.1.0", + "jackspeak": "^4.0.1", + "minimatch": "^10.0.0", + "minipass": "^7.1.2", + "package-json-from-dist": "^1.0.0", + "path-scurry": "^2.0.0" + }, + "bin": { + "glob": "dist/esm/bin.mjs" + }, + "engines": { + "node": "20 || >=22" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/is-fullwidth-code-point": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz", + "integrity": "sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==", + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/isexe": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/isexe/-/isexe-2.0.0.tgz", + "integrity": "sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==", + "license": "ISC" + }, + "node_modules/jackspeak": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/jackspeak/-/jackspeak-4.1.1.tgz", + "integrity": "sha512-zptv57P3GpL+O0I7VdMJNBZCu+BPHVQUk55Ft8/QCJjTVxrnJHuVuX/0Bl2A6/+2oyR/ZMEuFKwmzqqZ/U5nPQ==", "license": "BlueOak-1.0.0", "dependencies": { - "minimatch": "^10.2.2", - "minipass": "^7.1.3", - "path-scurry": "^2.0.2" + "@isaacs/cliui": "^8.0.2" }, "engines": { - "node": "18 || 20 || >=22" + "node": "20 || >=22" }, "funding": { "url": "https://github.com/sponsors/isaacs" } }, "node_modules/lru-cache": { - "version": "11.5.2", - "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-11.5.2.tgz", - "integrity": "sha512-4pfM1Ff0x50o0tQwb5ucw/RzNyD0/YJME6IVcStalZuMWxdt3sR3huStTtxz4PUmvZfRguvDejasvQ2kifR11g==", - "dev": true, - "license": "BlueOak-1.0.0", + "version": "11.1.0", + "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-11.1.0.tgz", + "integrity": "sha512-QIXZUBJUx+2zHUdQujWejBkcD9+cs94tLn0+YL8UrCh+D5sCXZ4c7LaEH48pNwRY3MLDgqUFyhlCyjJPf1WP0A==", + "license": "ISC", "engines": { "node": "20 || >=22" } }, "node_modules/minimatch": { - "version": "10.2.5", - "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-10.2.5.tgz", - "integrity": "sha512-MULkVLfKGYDFYejP07QOurDLLQpcjk7Fw+7jXS2R2czRQzR56yHRveU5NDJEOviH+hETZKSkIk5c+T23GjFUMg==", - "dev": true, - "license": "BlueOak-1.0.0", + "version": "10.0.1", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-10.0.1.tgz", + "integrity": "sha512-ethXTt3SGGR+95gudmqJ1eNhRO7eGEGIgYA9vnPatK4/etz2MEVDno5GMCibdMTuBMyElzIlgxMna3K94XDIDQ==", + "license": "ISC", "dependencies": { - "brace-expansion": "^5.0.5" + "brace-expansion": "^2.0.1" }, "engines": { - "node": "18 || 20 || >=22" + "node": "20 || >=22" }, "funding": { "url": "https://github.com/sponsors/isaacs" } }, "node_modules/minipass": { - "version": "7.1.3", - "resolved": "https://registry.npmjs.org/minipass/-/minipass-7.1.3.tgz", - "integrity": "sha512-tEBHqDnIoM/1rXME1zgka9g6Q2lcoCkxHLuc7ODJ5BxbP5d4c2Z5cGgtXAku59200Cx7diuHTOYfSBD8n6mm8A==", - "dev": true, - "license": "BlueOak-1.0.0", + "version": "7.1.2", + "resolved": "https://registry.npmjs.org/minipass/-/minipass-7.1.2.tgz", + "integrity": "sha512-qOOzS1cBTWYF4BH8fVePDBOO9iptMnGUEZwNc/cMWnTV2nVLZ7VoNWEPHkYczZA0pdoA7dl6e7FL659nX9S2aw==", + "license": "ISC", "engines": { "node": ">=16 || 14 >=14.17" } }, "node_modules/nostr-tools": { - "version": "2.15.1", - "resolved": "https://registry.npmjs.org/nostr-tools/-/nostr-tools-2.15.1.tgz", - "integrity": "sha512-LpetHDR9ltnkpJDkva/SONgyKBbsoV+5yLB8DWc0/U3lCWGtoWJw6Nbc2vR2Ai67RIQYrBQeZLyMlhwVZRK/9A==", + "version": "2.25.2", + "resolved": "https://registry.npmjs.org/nostr-tools/-/nostr-tools-2.25.2.tgz", + "integrity": "sha512-7JAx+brEPmqGz1yzaK9MOxvis/Nl1B38j9hVsBSRDMRmxk5XSc0+5LlPEYbzeiUyk41RURBDcfuMzmaT754HAg==", "license": "Unlicense", "dependencies": { - "@noble/ciphers": "^0.5.1", - "@noble/curves": "1.2.0", - "@noble/hashes": "1.3.1", - "@scure/base": "1.1.1", - "@scure/bip32": "1.3.1", - "@scure/bip39": "1.2.1", + "@noble/ciphers": "2.1.1", + "@noble/curves": "2.0.1", + "@noble/hashes": "2.0.1", + "@scure/base": "2.0.0", + "@scure/bip32": "2.0.1", + "@scure/bip39": "2.0.1", "nostr-wasm": "0.1.0" }, "peerDependencies": { @@ -277,29 +366,17 @@ } }, "node_modules/nostr-tools/node_modules/@noble/hashes": { - "version": "1.3.1", - "resolved": "https://registry.npmjs.org/@noble/hashes/-/hashes-1.3.1.tgz", - "integrity": "sha512-EbqwksQwz9xDRGfDST86whPBgM65E0OH/pCgqW0GBVzO22bNE+NuIbeTb714+IfSjU3aRk47EUvXIb5bTsenKA==", + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/@noble/hashes/-/hashes-2.0.1.tgz", + "integrity": "sha512-XlOlEbQcE9fmuXxrVTXCTlG2nlRXa9Rj3rr5Ue/+tX+nmkgbX720YHh0VR3hBF9xDvwnb8D2shVGOwNx+ulArw==", "license": "MIT", "engines": { - "node": ">= 16" + "node": ">= 20.19.0" }, "funding": { "url": "https://paulmillr.com/funding/" } }, - "node_modules/nostr-tools/node_modules/@scure/base": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/@scure/base/-/base-1.1.1.tgz", - "integrity": "sha512-ZxOhsSyxYwLJj3pLZCefNitxsj093tb2vq90mp2txoYeBqbcjDjqFhyM8eUjq/uFm6zJ+mUuqxlS2FkuSY1MTA==", - "funding": [ - { - "type": "individual", - "url": "https://paulmillr.com/funding/" - } - ], - "license": "MIT" - }, "node_modules/nostr-wasm": { "version": "0.1.0", "resolved": "https://registry.npmjs.org/nostr-wasm/-/nostr-wasm-0.1.0.tgz", @@ -310,35 +387,41 @@ "version": "1.0.1", "resolved": "https://registry.npmjs.org/package-json-from-dist/-/package-json-from-dist-1.0.1.tgz", "integrity": "sha512-UEZIS3/by4OC8vL3P2dTXRETpebLI2NiI5vIrjaD/5UtrkFX/tNbwjTSRAGC/+7CAo2pIcBaRgWmcBBHcsaCIw==", - "dev": true, "license": "BlueOak-1.0.0" }, + "node_modules/path-key": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/path-key/-/path-key-3.1.1.tgz", + "integrity": "sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q==", + "license": "MIT", + "engines": { + "node": ">=8" + } + }, "node_modules/path-scurry": { - "version": "2.0.2", - "resolved": "https://registry.npmjs.org/path-scurry/-/path-scurry-2.0.2.tgz", - "integrity": "sha512-3O/iVVsJAPsOnpwWIeD+d6z/7PmqApyQePUtCndjatj/9I5LylHvt5qluFaBT3I5h3r1ejfR056c+FCv+NnNXg==", - "dev": true, + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/path-scurry/-/path-scurry-2.0.0.tgz", + "integrity": "sha512-ypGJsmGtdXUOeM5u93TyeIEfEhM6s+ljAhrk5vAvSx8uyY/02OvrZnA0YNGUrPXfpJMgI1ODd3nwz8Npx4O4cg==", "license": "BlueOak-1.0.0", "dependencies": { "lru-cache": "^11.0.0", "minipass": "^7.1.2" }, "engines": { - "node": "18 || 20 || >=22" + "node": "20 || >=22" }, "funding": { "url": "https://github.com/sponsors/isaacs" } }, "node_modules/rimraf": { - "version": "6.1.3", - "resolved": "https://registry.npmjs.org/rimraf/-/rimraf-6.1.3.tgz", - "integrity": "sha512-LKg+Cr2ZF61fkcaK1UdkH2yEBBKnYjTyWzTJT6KNPcSPaiT7HSdhtMXQuN5wkTX0Xu72KQ1l8S42rlmexS2hSA==", - "dev": true, - "license": "BlueOak-1.0.0", + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/rimraf/-/rimraf-6.0.1.tgz", + "integrity": "sha512-9dkvaxAsk/xNXSJzMgFqqMCuFgt2+KsOFek3TMLfo8NCPfWpBmqwyNn5Y+NX56QUYfCtsyhF3ayiboEoUmJk/A==", + "license": "ISC", "dependencies": { - "glob": "^13.0.3", - "package-json-from-dist": "^1.0.1" + "glob": "^11.0.0", + "package-json-from-dist": "^1.0.0" }, "bin": { "rimraf": "dist/esm/bin.mjs" @@ -350,13 +433,140 @@ "url": "https://github.com/sponsors/isaacs" } }, + "node_modules/shebang-command": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-2.0.0.tgz", + "integrity": "sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA==", + "license": "MIT", + "dependencies": { + "shebang-regex": "^3.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/shebang-regex": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/shebang-regex/-/shebang-regex-3.0.0.tgz", + "integrity": "sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A==", + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/signal-exit": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-4.1.0.tgz", + "integrity": "sha512-bzyZ1e88w9O1iNJbKnOlvYTrWPDl46O1bG0D3XInv+9tkPrxrN8jUUTiFlDkkmKWgn1M6CfIA13SuGqOa9Korw==", + "license": "ISC", + "engines": { + "node": ">=14" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/string-width": { + "version": "5.1.2", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-5.1.2.tgz", + "integrity": "sha512-HnLOCR3vjcY8beoNLtcjZ5/nxn2afmME6lhrDrebokqMap+XbeW8n9TXpPDOqdGK5qcI3oT0GKTW6wC7EMiVqA==", + "license": "MIT", + "dependencies": { + "eastasianwidth": "^0.2.0", + "emoji-regex": "^9.2.2", + "strip-ansi": "^7.0.1" + }, + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/string-width-cjs": { + "name": "string-width", + "version": "4.2.3", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz", + "integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==", + "license": "MIT", + "dependencies": { + "emoji-regex": "^8.0.0", + "is-fullwidth-code-point": "^3.0.0", + "strip-ansi": "^6.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/string-width-cjs/node_modules/ansi-regex": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz", + "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==", + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/string-width-cjs/node_modules/emoji-regex": { + "version": "8.0.0", + "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz", + "integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==", + "license": "MIT" + }, + "node_modules/string-width-cjs/node_modules/strip-ansi": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz", + "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==", + "license": "MIT", + "dependencies": { + "ansi-regex": "^5.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/strip-ansi": { + "version": "7.1.0", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-7.1.0.tgz", + "integrity": "sha512-iq6eVVI64nQQTRYq2KtEg2d2uU7LElhTJwsH4YzIHZshxlgZms/wIc4VoDQTlG/IvVIrBKG06CrZnp0qv7hkcQ==", + "license": "MIT", + "dependencies": { + "ansi-regex": "^6.0.1" + }, + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/strip-ansi?sponsor=1" + } + }, + "node_modules/strip-ansi-cjs": { + "name": "strip-ansi", + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz", + "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==", + "license": "MIT", + "dependencies": { + "ansi-regex": "^5.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/strip-ansi-cjs/node_modules/ansi-regex": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz", + "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==", + "license": "MIT", + "engines": { + "node": ">=8" + } + }, "node_modules/typescript": { - "version": "5.9.3", - "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.9.3.tgz", - "integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==", - "devOptional": true, + "version": "5.8.3", + "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.8.3.tgz", + "integrity": "sha512-p1diW6TqL9L07nNxvRMM7hMMw4c5XOo/1ibL4aAIGmSAt9slTE1Xgw5KWuof2uTOvCg9BY7ZRi+GaF+7sfgPeQ==", "license": "Apache-2.0", - "peer": true, "bin": { "tsc": "bin/tsc", "tsserver": "bin/tsserver" @@ -371,6 +581,112 @@ "integrity": "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ==", "dev": true, "license": "MIT" + }, + "node_modules/which": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz", + "integrity": "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==", + "license": "ISC", + "dependencies": { + "isexe": "^2.0.0" + }, + "bin": { + "node-which": "bin/node-which" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/wrap-ansi": { + "version": "8.1.0", + "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-8.1.0.tgz", + "integrity": "sha512-si7QWI6zUMq56bESFvagtmzMdGOtoxfR+Sez11Mobfc7tm+VkUckk9bW2UeffTGVUbOksxmSw0AA2gs8g71NCQ==", + "license": "MIT", + "dependencies": { + "ansi-styles": "^6.1.0", + "string-width": "^5.0.1", + "strip-ansi": "^7.0.1" + }, + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/wrap-ansi?sponsor=1" + } + }, + "node_modules/wrap-ansi-cjs": { + "name": "wrap-ansi", + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-7.0.0.tgz", + "integrity": "sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q==", + "license": "MIT", + "dependencies": { + "ansi-styles": "^4.0.0", + "string-width": "^4.1.0", + "strip-ansi": "^6.0.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/chalk/wrap-ansi?sponsor=1" + } + }, + "node_modules/wrap-ansi-cjs/node_modules/ansi-regex": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz", + "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==", + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/wrap-ansi-cjs/node_modules/ansi-styles": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz", + "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==", + "license": "MIT", + "dependencies": { + "color-convert": "^2.0.1" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/chalk/ansi-styles?sponsor=1" + } + }, + "node_modules/wrap-ansi-cjs/node_modules/emoji-regex": { + "version": "8.0.0", + "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz", + "integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==", + "license": "MIT" + }, + "node_modules/wrap-ansi-cjs/node_modules/string-width": { + "version": "4.2.3", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz", + "integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==", + "license": "MIT", + "dependencies": { + "emoji-regex": "^8.0.0", + "is-fullwidth-code-point": "^3.0.0", + "strip-ansi": "^6.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/wrap-ansi-cjs/node_modules/strip-ansi": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz", + "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==", + "license": "MIT", + "dependencies": { + "ansi-regex": "^5.0.1" + }, + "engines": { + "node": ">=8" + } } } } diff --git a/package.json b/package.json index 617e45b..7af22b4 100644 --- a/package.json +++ b/package.json @@ -46,12 +46,15 @@ ], "dependencies": { "@noble/hashes": "^1.8.0", - "@scure/base": "^1.2.5", - "nostr-tools": "2.15.1" + "@scure/base": "^2.4.0", + "nostr-tools": "2.25.2", + "rimraf": "^6.0.1", + "typescript": "^5.8.3" }, "devDependencies": { - "@types/node": "^22.15.2", - "rimraf": "^6.1.3", - "typescript": "^5.9.3" + "@types/node": "^22.15.2" + }, + "overrides": { + "@scure/base": "$@scure/base" } -} +} \ No newline at end of file diff --git a/src/index.ts b/src/index.ts index a4b0ffd..cc0f2d3 100644 --- a/src/index.ts +++ b/src/index.ts @@ -1,4 +1,4 @@ -import { AbstractSimplePool } from "nostr-tools/lib/types/pool" +import { AbstractSimplePool } from "nostr-tools/abstract-pool" import { SimplePool, getPublicKey, nip19, generateSecretKey, finalizeEvent, nip44, verifyEvent, type UnsignedEvent } from "nostr-tools" import { SendNofferRequest, NofferData, NofferReceipt } from "./noffer.js" import { NdebitData, SendNdebitRequest, generateK1, validateK1, newNdebitBudgetRequest, newNdebitPaymentRequest } from "./ndebit.js" diff --git a/src/ndebit.ts b/src/ndebit.ts index 581681f..d716a80 100644 --- a/src/ndebit.ts +++ b/src/ndebit.ts @@ -1,6 +1,6 @@ import { randomBytes, bytesToHex } from '@noble/hashes/utils' import { nip44, getPublicKey } from "nostr-tools" -import { AbstractSimplePool } from "nostr-tools/lib/types/pool" +import { AbstractSimplePool } from "nostr-tools/pool" import { sendRequest } from "./sender.js" const { getConversationKey, encrypt } = nip44 diff --git a/src/nmanage.ts b/src/nmanage.ts index 0249691..1f3c2d5 100644 --- a/src/nmanage.ts +++ b/src/nmanage.ts @@ -1,5 +1,5 @@ import { nip44, getPublicKey } from "nostr-tools" -import { AbstractSimplePool } from "nostr-tools/lib/types/pool" +import { AbstractSimplePool } from "nostr-tools/abstract-pool" import { sendRequest } from "./sender.js" const { getConversationKey, encrypt } = nip44 diff --git a/src/noffer.ts b/src/noffer.ts index e811269..224b992 100644 --- a/src/noffer.ts +++ b/src/noffer.ts @@ -1,5 +1,5 @@ import { nip44, getPublicKey } from "nostr-tools" -import { AbstractSimplePool } from "nostr-tools/lib/types/pool" +import { AbstractSimplePool } from "nostr-tools/abstract-pool" import { CLINK_OFFER_KIND, CLINK_VERSION } from "./constants.js" import { type NofferReceipt } from "./receipt.js" import { sendRequest } from "./sender.js" diff --git a/src/sender.ts b/src/sender.ts index c261286..933f31b 100644 --- a/src/sender.ts +++ b/src/sender.ts @@ -1,5 +1,5 @@ import { nip44, finalizeEvent, verifyEvent, UnsignedEvent, type Event } from "nostr-tools" -import { AbstractSimplePool, SubCloser } from "nostr-tools/lib/types/pool" +import { AbstractSimplePool, SubCloser } from "nostr-tools/abstract-pool" import { CLINK_VERSION } from "./constants.js" import { isNofferReceipt } from "./receipt.js" const { getConversationKey, decrypt } = nip44 From 3bc610d8ef70de58d6f4fe54ab74dbc2a9218cb8 Mon Sep 17 00:00:00 2001 From: boufni95 Date: Fri, 25 Sep 2026 18:33:28 +0000 Subject: [PATCH 06/14] import path fix --- src/index.ts | 2 +- src/ndebit.ts | 2 +- src/nmanage.ts | 2 +- src/sender.ts | 4 ++-- 4 files changed, 5 insertions(+), 5 deletions(-) diff --git a/src/index.ts b/src/index.ts index cc0f2d3..56dc86a 100644 --- a/src/index.ts +++ b/src/index.ts @@ -1,4 +1,4 @@ -import { AbstractSimplePool } from "nostr-tools/abstract-pool" +import { AbstractSimplePool } from "nostr-tools/lib/types/abstract-pool" import { SimplePool, getPublicKey, nip19, generateSecretKey, finalizeEvent, nip44, verifyEvent, type UnsignedEvent } from "nostr-tools" import { SendNofferRequest, NofferData, NofferReceipt } from "./noffer.js" import { NdebitData, SendNdebitRequest, generateK1, validateK1, newNdebitBudgetRequest, newNdebitPaymentRequest } from "./ndebit.js" diff --git a/src/ndebit.ts b/src/ndebit.ts index d716a80..1f267b2 100644 --- a/src/ndebit.ts +++ b/src/ndebit.ts @@ -1,6 +1,6 @@ import { randomBytes, bytesToHex } from '@noble/hashes/utils' import { nip44, getPublicKey } from "nostr-tools" -import { AbstractSimplePool } from "nostr-tools/pool" +import { AbstractSimplePool } from "nostr-tools/lib/types/abstract-pool" import { sendRequest } from "./sender.js" const { getConversationKey, encrypt } = nip44 diff --git a/src/nmanage.ts b/src/nmanage.ts index 1f3c2d5..111ad88 100644 --- a/src/nmanage.ts +++ b/src/nmanage.ts @@ -1,5 +1,5 @@ import { nip44, getPublicKey } from "nostr-tools" -import { AbstractSimplePool } from "nostr-tools/abstract-pool" +import { AbstractSimplePool } from "nostr-tools/lib/types/abstract-pool" import { sendRequest } from "./sender.js" const { getConversationKey, encrypt } = nip44 diff --git a/src/sender.ts b/src/sender.ts index 933f31b..b8e5a77 100644 --- a/src/sender.ts +++ b/src/sender.ts @@ -1,5 +1,5 @@ import { nip44, finalizeEvent, verifyEvent, UnsignedEvent, type Event } from "nostr-tools" -import { AbstractSimplePool, SubCloser } from "nostr-tools/abstract-pool" +import { AbstractSimplePool, SubCloser } from "nostr-tools/lib/types/abstract-pool" import { CLINK_VERSION } from "./constants.js" import { isNofferReceipt } from "./receipt.js" const { getConversationKey, decrypt } = nip44 @@ -126,7 +126,7 @@ export const sendRequest = async (pool: AbstractSimplePool, pair: Pair, relay const gen = ++listenGen log(`[ClinkSDK] Setting up subscription with filter:`, JSON.stringify(filter, null, 2)) closer.close() - closer = pool.subscribeMany(relays, [filter], { + closer = pool.subscribeMany(relays, filter, { onevent: async (event) => { log(`[ClinkSDK] Received response event: kind=${event.kind}, eventId=${event.id}, from=${event.pubkey}`) if (!isClinkResponse(event, expect)) { From c9fefbc2e264f6efad0798702cf4c139b43edb37 Mon Sep 17 00:00:00 2001 From: boufni95 Date: Fri, 25 Sep 2026 18:42:21 +0000 Subject: [PATCH 07/14] more types fix --- src/nbeacon.ts | 6 +++--- src/noffer.ts | 2 +- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/src/nbeacon.ts b/src/nbeacon.ts index 335e66f..2e7d762 100644 --- a/src/nbeacon.ts +++ b/src/nbeacon.ts @@ -1,4 +1,4 @@ -import { AbstractSimplePool } from "nostr-tools/lib/types/pool" +import { AbstractSimplePool } from "nostr-tools/lib/types/abstract-pool" import { Event, verifyEvent } from "nostr-tools" import { BEACON_FUTURE_SKEW_SECONDS, @@ -168,11 +168,11 @@ export const FetchClinkBeacon = async ( resolve(best ? parseClinkBeaconEvent(best) : null) } const timer = setTimeout(finish, timeoutSeconds * 1000) - closer = pool.subscribeMany(relays, [{ + closer = pool.subscribeMany(relays, { kinds: [CLINK_BEACON_KIND], authors: [expectedPub], "#d": [CLINK_BEACON_D_TAG], - }], { + }, { onevent: (event: Event) => { if (event.pubkey.toLowerCase() !== expectedPub) { return diff --git a/src/noffer.ts b/src/noffer.ts index 224b992..5bdb905 100644 --- a/src/noffer.ts +++ b/src/noffer.ts @@ -1,5 +1,5 @@ import { nip44, getPublicKey } from "nostr-tools" -import { AbstractSimplePool } from "nostr-tools/abstract-pool" +import { AbstractSimplePool } from "nostr-tools/lib/types/abstract-pool" import { CLINK_OFFER_KIND, CLINK_VERSION } from "./constants.js" import { type NofferReceipt } from "./receipt.js" import { sendRequest } from "./sender.js" From b0b4c9d86e2e6e1ea1b62d0cc899285dc7eee85c Mon Sep 17 00:00:00 2001 From: shocknet-justin Date: Sat, 26 Sep 2026 11:00:57 -0400 Subject: [PATCH 08/14] Keep build tools dev-only, stay compatible with older pools, bump to 1.8.0 - Restore typescript/rimraf to devDependencies and regenerate the lockfile from staging, which drops the downgraded, vulnerable glob/minimatch. - Drop the @scure/base override; it only affected local installs. - Use pool.subscribe (single filter), which has the same signature in nostr-tools 2.15 and 2.25, so caller-supplied older pools keep working. - Make all AbstractSimplePool imports type-only and point nenroll at the same abstract-pool path as the rest. Co-authored-by: Cursor --- package-lock.json | 513 ++++++------------------------- package.json | 15 +- src/index.ts | 2 +- src/nbeacon.ts | 4 +- src/ndebit.ts | 2 +- src/nenroll.ts | 2 +- src/nmanage.ts | 2 +- src/noffer.ts | 2 +- src/sender.ts | 4 +- test/unit/enroll-beacon.test.mjs | 8 +- test/unit/sender.test.mjs | 4 +- 11 files changed, 109 insertions(+), 449 deletions(-) diff --git a/package-lock.json b/package-lock.json index 476fb30..ab58f29 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,39 +1,22 @@ { "name": "@shocknet/clink-sdk", - "version": "1.7.3", + "version": "1.8.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "@shocknet/clink-sdk", - "version": "1.7.3", + "version": "1.8.0", "license": "MIT", "dependencies": { "@noble/hashes": "^1.8.0", "@scure/base": "^2.4.0", - "nostr-tools": "2.25.2", - "rimraf": "^6.0.1", - "typescript": "^5.8.3" + "nostr-tools": "2.25.2" }, "devDependencies": { - "@types/node": "^22.15.2" - } - }, - "node_modules/@isaacs/cliui": { - "version": "8.0.2", - "resolved": "https://registry.npmjs.org/@isaacs/cliui/-/cliui-8.0.2.tgz", - "integrity": "sha512-O8jcjabXaleOG9DQ0+ARXWZBTfnP4WNAqzuiJK7ll44AmxGKv/J2M4TPjxjY3znBCfvBXFzucm1twdyFybFqEA==", - "license": "ISC", - "dependencies": { - "string-width": "^5.1.2", - "string-width-cjs": "npm:string-width@^4.2.0", - "strip-ansi": "^7.0.1", - "strip-ansi-cjs": "npm:strip-ansi@^6.0.1", - "wrap-ansi": "^8.1.0", - "wrap-ansi-cjs": "npm:wrap-ansi@^7.0.0" - }, - "engines": { - "node": ">=12" + "@types/node": "^22.15.2", + "rimraf": "^6.1.3", + "typescript": "^5.9.3" } }, "node_modules/@noble/ciphers": { @@ -122,6 +105,15 @@ "url": "https://paulmillr.com/funding/" } }, + "node_modules/@scure/bip32/node_modules/@scure/base": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/@scure/base/-/base-2.0.0.tgz", + "integrity": "sha512-3E1kpuZginKkek01ovG8krQ0Z44E3DHPjc5S2rjJw9lZn3KSQOs8S7wqikF/AH7iRanHypj85uGyxk0XAyC37w==", + "license": "MIT", + "funding": { + "url": "https://paulmillr.com/funding/" + } + }, "node_modules/@scure/bip39": { "version": "2.0.1", "resolved": "https://registry.npmjs.org/@scure/bip39/-/bip39-2.0.1.tgz", @@ -147,6 +139,15 @@ "url": "https://paulmillr.com/funding/" } }, + "node_modules/@scure/bip39/node_modules/@scure/base": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/@scure/base/-/base-2.0.0.tgz", + "integrity": "sha512-3E1kpuZginKkek01ovG8krQ0Z44E3DHPjc5S2rjJw9lZn3KSQOs8S7wqikF/AH7iRanHypj85uGyxk0XAyC37w==", + "license": "MIT", + "funding": { + "url": "https://paulmillr.com/funding/" + } + }, "node_modules/@types/node": { "version": "22.15.21", "resolved": "https://registry.npmjs.org/@types/node/-/node-22.15.21.tgz", @@ -157,187 +158,79 @@ "undici-types": "~6.21.0" } }, - "node_modules/ansi-regex": { - "version": "6.1.0", - "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-6.1.0.tgz", - "integrity": "sha512-7HSX4QQb4CspciLpVFwyRe79O3xsIZDDLER21kERQ71oaPodF8jL725AgJMFAYbooIqolJoRLuM81SpeUkpkvA==", - "license": "MIT", - "engines": { - "node": ">=12" - }, - "funding": { - "url": "https://github.com/chalk/ansi-regex?sponsor=1" - } - }, - "node_modules/ansi-styles": { - "version": "6.2.1", - "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-6.2.1.tgz", - "integrity": "sha512-bN798gFfQX+viw3R7yrGWRqnrN2oRkEkUjjl4JNn4E8GxxbjtG3FbrEIIY3l8/hrwUwIeCZvi4QuOTP4MErVug==", - "license": "MIT", - "engines": { - "node": ">=12" - }, - "funding": { - "url": "https://github.com/chalk/ansi-styles?sponsor=1" - } - }, "node_modules/balanced-match": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz", - "integrity": "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==", - "license": "MIT" - }, - "node_modules/brace-expansion": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-2.0.1.tgz", - "integrity": "sha512-XnAIvQ8eM+kC6aULx6wuQiwVsnzsi9d3WxzV3FpWTGA19F621kwdbsAcFKXgKUHZWsy+mY6iL1sHTxWEFCytDA==", - "license": "MIT", - "dependencies": { - "balanced-match": "^1.0.0" - } - }, - "node_modules/color-convert": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz", - "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==", + "version": "4.0.4", + "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-4.0.4.tgz", + "integrity": "sha512-BLrgEcRTwX2o6gGxGOCNyMvGSp35YofuYzw9h1IMTRmKqttAZZVU67bdb9Pr2vUHA8+j3i2tJfjO6C6+4myGTA==", + "dev": true, "license": "MIT", - "dependencies": { - "color-name": "~1.1.4" - }, "engines": { - "node": ">=7.0.0" + "node": "18 || 20 || >=22" } }, - "node_modules/color-name": { - "version": "1.1.4", - "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz", - "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==", - "license": "MIT" - }, - "node_modules/cross-spawn": { - "version": "7.0.6", - "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.6.tgz", - "integrity": "sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA==", + "node_modules/brace-expansion": { + "version": "5.0.8", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-5.0.8.tgz", + "integrity": "sha512-JZyDyq3D4AUifKTPOB7DELf6XsB3WdPuNxCtob1vFXPsSXhdAiHBWJ/tJ8HAc9aH84BK+5JFZLNkJKx3G9kzQg==", + "dev": true, "license": "MIT", "dependencies": { - "path-key": "^3.1.0", - "shebang-command": "^2.0.0", - "which": "^2.0.1" - }, - "engines": { - "node": ">= 8" - } - }, - "node_modules/eastasianwidth": { - "version": "0.2.0", - "resolved": "https://registry.npmjs.org/eastasianwidth/-/eastasianwidth-0.2.0.tgz", - "integrity": "sha512-I88TYZWc9XiYHRQ4/3c5rjjfgkjhLyW2luGIheGERbNQ6OY7yTybanSpDXZa8y7VUP9YmDcYa+eyq4ca7iLqWA==", - "license": "MIT" - }, - "node_modules/emoji-regex": { - "version": "9.2.2", - "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-9.2.2.tgz", - "integrity": "sha512-L18DaJsXSUk2+42pv8mLs5jJT2hqFkFE4j21wOmgbUqsZ2hL72NsUU785g9RXgo3s0ZNgVl42TiHp3ZtOv/Vyg==", - "license": "MIT" - }, - "node_modules/foreground-child": { - "version": "3.3.1", - "resolved": "https://registry.npmjs.org/foreground-child/-/foreground-child-3.3.1.tgz", - "integrity": "sha512-gIXjKqtFuWEgzFRJA9WCQeSJLZDjgJUOMCMzxtvFq/37KojM1BFGufqsCy0r4qSQmYLsZYMeyRqzIWOMup03sw==", - "license": "ISC", - "dependencies": { - "cross-spawn": "^7.0.6", - "signal-exit": "^4.0.1" - }, - "engines": { - "node": ">=14" - }, - "funding": { - "url": "https://github.com/sponsors/isaacs" - } - }, - "node_modules/glob": { - "version": "11.0.2", - "resolved": "https://registry.npmjs.org/glob/-/glob-11.0.2.tgz", - "integrity": "sha512-YT7U7Vye+t5fZ/QMkBFrTJ7ZQxInIUjwyAjVj84CYXqgBdv30MFUPGnBR6sQaVq6Is15wYJUsnzTuWaGRBhBAQ==", - "license": "ISC", - "dependencies": { - "foreground-child": "^3.1.0", - "jackspeak": "^4.0.1", - "minimatch": "^10.0.0", - "minipass": "^7.1.2", - "package-json-from-dist": "^1.0.0", - "path-scurry": "^2.0.0" - }, - "bin": { - "glob": "dist/esm/bin.mjs" + "balanced-match": "^4.0.2" }, "engines": { "node": "20 || >=22" - }, - "funding": { - "url": "https://github.com/sponsors/isaacs" } }, - "node_modules/is-fullwidth-code-point": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz", - "integrity": "sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==", - "license": "MIT", - "engines": { - "node": ">=8" - } - }, - "node_modules/isexe": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/isexe/-/isexe-2.0.0.tgz", - "integrity": "sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==", - "license": "ISC" - }, - "node_modules/jackspeak": { - "version": "4.1.1", - "resolved": "https://registry.npmjs.org/jackspeak/-/jackspeak-4.1.1.tgz", - "integrity": "sha512-zptv57P3GpL+O0I7VdMJNBZCu+BPHVQUk55Ft8/QCJjTVxrnJHuVuX/0Bl2A6/+2oyR/ZMEuFKwmzqqZ/U5nPQ==", + "node_modules/glob": { + "version": "13.0.6", + "resolved": "https://registry.npmjs.org/glob/-/glob-13.0.6.tgz", + "integrity": "sha512-Wjlyrolmm8uDpm/ogGyXZXb1Z+Ca2B8NbJwqBVg0axK9GbBeoS7yGV6vjXnYdGm6X53iehEuxxbyiKp8QmN4Vw==", + "dev": true, "license": "BlueOak-1.0.0", "dependencies": { - "@isaacs/cliui": "^8.0.2" + "minimatch": "^10.2.2", + "minipass": "^7.1.3", + "path-scurry": "^2.0.2" }, "engines": { - "node": "20 || >=22" + "node": "18 || 20 || >=22" }, "funding": { "url": "https://github.com/sponsors/isaacs" } }, "node_modules/lru-cache": { - "version": "11.1.0", - "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-11.1.0.tgz", - "integrity": "sha512-QIXZUBJUx+2zHUdQujWejBkcD9+cs94tLn0+YL8UrCh+D5sCXZ4c7LaEH48pNwRY3MLDgqUFyhlCyjJPf1WP0A==", - "license": "ISC", + "version": "11.5.2", + "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-11.5.2.tgz", + "integrity": "sha512-4pfM1Ff0x50o0tQwb5ucw/RzNyD0/YJME6IVcStalZuMWxdt3sR3huStTtxz4PUmvZfRguvDejasvQ2kifR11g==", + "dev": true, + "license": "BlueOak-1.0.0", "engines": { "node": "20 || >=22" } }, "node_modules/minimatch": { - "version": "10.0.1", - "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-10.0.1.tgz", - "integrity": "sha512-ethXTt3SGGR+95gudmqJ1eNhRO7eGEGIgYA9vnPatK4/etz2MEVDno5GMCibdMTuBMyElzIlgxMna3K94XDIDQ==", - "license": "ISC", + "version": "10.2.5", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-10.2.5.tgz", + "integrity": "sha512-MULkVLfKGYDFYejP07QOurDLLQpcjk7Fw+7jXS2R2czRQzR56yHRveU5NDJEOviH+hETZKSkIk5c+T23GjFUMg==", + "dev": true, + "license": "BlueOak-1.0.0", "dependencies": { - "brace-expansion": "^2.0.1" + "brace-expansion": "^5.0.5" }, "engines": { - "node": "20 || >=22" + "node": "18 || 20 || >=22" }, "funding": { "url": "https://github.com/sponsors/isaacs" } }, "node_modules/minipass": { - "version": "7.1.2", - "resolved": "https://registry.npmjs.org/minipass/-/minipass-7.1.2.tgz", - "integrity": "sha512-qOOzS1cBTWYF4BH8fVePDBOO9iptMnGUEZwNc/cMWnTV2nVLZ7VoNWEPHkYczZA0pdoA7dl6e7FL659nX9S2aw==", - "license": "ISC", + "version": "7.1.3", + "resolved": "https://registry.npmjs.org/minipass/-/minipass-7.1.3.tgz", + "integrity": "sha512-tEBHqDnIoM/1rXME1zgka9g6Q2lcoCkxHLuc7ODJ5BxbP5d4c2Z5cGgtXAku59200Cx7diuHTOYfSBD8n6mm8A==", + "dev": true, + "license": "BlueOak-1.0.0", "engines": { "node": ">=16 || 14 >=14.17" } @@ -377,6 +270,15 @@ "url": "https://paulmillr.com/funding/" } }, + "node_modules/nostr-tools/node_modules/@scure/base": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/@scure/base/-/base-2.0.0.tgz", + "integrity": "sha512-3E1kpuZginKkek01ovG8krQ0Z44E3DHPjc5S2rjJw9lZn3KSQOs8S7wqikF/AH7iRanHypj85uGyxk0XAyC37w==", + "license": "MIT", + "funding": { + "url": "https://paulmillr.com/funding/" + } + }, "node_modules/nostr-wasm": { "version": "0.1.0", "resolved": "https://registry.npmjs.org/nostr-wasm/-/nostr-wasm-0.1.0.tgz", @@ -387,41 +289,35 @@ "version": "1.0.1", "resolved": "https://registry.npmjs.org/package-json-from-dist/-/package-json-from-dist-1.0.1.tgz", "integrity": "sha512-UEZIS3/by4OC8vL3P2dTXRETpebLI2NiI5vIrjaD/5UtrkFX/tNbwjTSRAGC/+7CAo2pIcBaRgWmcBBHcsaCIw==", + "dev": true, "license": "BlueOak-1.0.0" }, - "node_modules/path-key": { - "version": "3.1.1", - "resolved": "https://registry.npmjs.org/path-key/-/path-key-3.1.1.tgz", - "integrity": "sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q==", - "license": "MIT", - "engines": { - "node": ">=8" - } - }, "node_modules/path-scurry": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/path-scurry/-/path-scurry-2.0.0.tgz", - "integrity": "sha512-ypGJsmGtdXUOeM5u93TyeIEfEhM6s+ljAhrk5vAvSx8uyY/02OvrZnA0YNGUrPXfpJMgI1ODd3nwz8Npx4O4cg==", + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/path-scurry/-/path-scurry-2.0.2.tgz", + "integrity": "sha512-3O/iVVsJAPsOnpwWIeD+d6z/7PmqApyQePUtCndjatj/9I5LylHvt5qluFaBT3I5h3r1ejfR056c+FCv+NnNXg==", + "dev": true, "license": "BlueOak-1.0.0", "dependencies": { "lru-cache": "^11.0.0", "minipass": "^7.1.2" }, "engines": { - "node": "20 || >=22" + "node": "18 || 20 || >=22" }, "funding": { "url": "https://github.com/sponsors/isaacs" } }, "node_modules/rimraf": { - "version": "6.0.1", - "resolved": "https://registry.npmjs.org/rimraf/-/rimraf-6.0.1.tgz", - "integrity": "sha512-9dkvaxAsk/xNXSJzMgFqqMCuFgt2+KsOFek3TMLfo8NCPfWpBmqwyNn5Y+NX56QUYfCtsyhF3ayiboEoUmJk/A==", - "license": "ISC", + "version": "6.1.3", + "resolved": "https://registry.npmjs.org/rimraf/-/rimraf-6.1.3.tgz", + "integrity": "sha512-LKg+Cr2ZF61fkcaK1UdkH2yEBBKnYjTyWzTJT6KNPcSPaiT7HSdhtMXQuN5wkTX0Xu72KQ1l8S42rlmexS2hSA==", + "dev": true, + "license": "BlueOak-1.0.0", "dependencies": { - "glob": "^11.0.0", - "package-json-from-dist": "^1.0.0" + "glob": "^13.0.3", + "package-json-from-dist": "^1.0.1" }, "bin": { "rimraf": "dist/esm/bin.mjs" @@ -433,140 +329,13 @@ "url": "https://github.com/sponsors/isaacs" } }, - "node_modules/shebang-command": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-2.0.0.tgz", - "integrity": "sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA==", - "license": "MIT", - "dependencies": { - "shebang-regex": "^3.0.0" - }, - "engines": { - "node": ">=8" - } - }, - "node_modules/shebang-regex": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/shebang-regex/-/shebang-regex-3.0.0.tgz", - "integrity": "sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A==", - "license": "MIT", - "engines": { - "node": ">=8" - } - }, - "node_modules/signal-exit": { - "version": "4.1.0", - "resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-4.1.0.tgz", - "integrity": "sha512-bzyZ1e88w9O1iNJbKnOlvYTrWPDl46O1bG0D3XInv+9tkPrxrN8jUUTiFlDkkmKWgn1M6CfIA13SuGqOa9Korw==", - "license": "ISC", - "engines": { - "node": ">=14" - }, - "funding": { - "url": "https://github.com/sponsors/isaacs" - } - }, - "node_modules/string-width": { - "version": "5.1.2", - "resolved": "https://registry.npmjs.org/string-width/-/string-width-5.1.2.tgz", - "integrity": "sha512-HnLOCR3vjcY8beoNLtcjZ5/nxn2afmME6lhrDrebokqMap+XbeW8n9TXpPDOqdGK5qcI3oT0GKTW6wC7EMiVqA==", - "license": "MIT", - "dependencies": { - "eastasianwidth": "^0.2.0", - "emoji-regex": "^9.2.2", - "strip-ansi": "^7.0.1" - }, - "engines": { - "node": ">=12" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/string-width-cjs": { - "name": "string-width", - "version": "4.2.3", - "resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz", - "integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==", - "license": "MIT", - "dependencies": { - "emoji-regex": "^8.0.0", - "is-fullwidth-code-point": "^3.0.0", - "strip-ansi": "^6.0.1" - }, - "engines": { - "node": ">=8" - } - }, - "node_modules/string-width-cjs/node_modules/ansi-regex": { - "version": "5.0.1", - "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz", - "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==", - "license": "MIT", - "engines": { - "node": ">=8" - } - }, - "node_modules/string-width-cjs/node_modules/emoji-regex": { - "version": "8.0.0", - "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz", - "integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==", - "license": "MIT" - }, - "node_modules/string-width-cjs/node_modules/strip-ansi": { - "version": "6.0.1", - "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz", - "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==", - "license": "MIT", - "dependencies": { - "ansi-regex": "^5.0.1" - }, - "engines": { - "node": ">=8" - } - }, - "node_modules/strip-ansi": { - "version": "7.1.0", - "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-7.1.0.tgz", - "integrity": "sha512-iq6eVVI64nQQTRYq2KtEg2d2uU7LElhTJwsH4YzIHZshxlgZms/wIc4VoDQTlG/IvVIrBKG06CrZnp0qv7hkcQ==", - "license": "MIT", - "dependencies": { - "ansi-regex": "^6.0.1" - }, - "engines": { - "node": ">=12" - }, - "funding": { - "url": "https://github.com/chalk/strip-ansi?sponsor=1" - } - }, - "node_modules/strip-ansi-cjs": { - "name": "strip-ansi", - "version": "6.0.1", - "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz", - "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==", - "license": "MIT", - "dependencies": { - "ansi-regex": "^5.0.1" - }, - "engines": { - "node": ">=8" - } - }, - "node_modules/strip-ansi-cjs/node_modules/ansi-regex": { - "version": "5.0.1", - "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz", - "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==", - "license": "MIT", - "engines": { - "node": ">=8" - } - }, "node_modules/typescript": { - "version": "5.8.3", - "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.8.3.tgz", - "integrity": "sha512-p1diW6TqL9L07nNxvRMM7hMMw4c5XOo/1ibL4aAIGmSAt9slTE1Xgw5KWuof2uTOvCg9BY7ZRi+GaF+7sfgPeQ==", + "version": "5.9.3", + "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.9.3.tgz", + "integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==", + "devOptional": true, "license": "Apache-2.0", + "peer": true, "bin": { "tsc": "bin/tsc", "tsserver": "bin/tsserver" @@ -581,112 +350,6 @@ "integrity": "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ==", "dev": true, "license": "MIT" - }, - "node_modules/which": { - "version": "2.0.2", - "resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz", - "integrity": "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==", - "license": "ISC", - "dependencies": { - "isexe": "^2.0.0" - }, - "bin": { - "node-which": "bin/node-which" - }, - "engines": { - "node": ">= 8" - } - }, - "node_modules/wrap-ansi": { - "version": "8.1.0", - "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-8.1.0.tgz", - "integrity": "sha512-si7QWI6zUMq56bESFvagtmzMdGOtoxfR+Sez11Mobfc7tm+VkUckk9bW2UeffTGVUbOksxmSw0AA2gs8g71NCQ==", - "license": "MIT", - "dependencies": { - "ansi-styles": "^6.1.0", - "string-width": "^5.0.1", - "strip-ansi": "^7.0.1" - }, - "engines": { - "node": ">=12" - }, - "funding": { - "url": "https://github.com/chalk/wrap-ansi?sponsor=1" - } - }, - "node_modules/wrap-ansi-cjs": { - "name": "wrap-ansi", - "version": "7.0.0", - "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-7.0.0.tgz", - "integrity": "sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q==", - "license": "MIT", - "dependencies": { - "ansi-styles": "^4.0.0", - "string-width": "^4.1.0", - "strip-ansi": "^6.0.0" - }, - "engines": { - "node": ">=10" - }, - "funding": { - "url": "https://github.com/chalk/wrap-ansi?sponsor=1" - } - }, - "node_modules/wrap-ansi-cjs/node_modules/ansi-regex": { - "version": "5.0.1", - "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz", - "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==", - "license": "MIT", - "engines": { - "node": ">=8" - } - }, - "node_modules/wrap-ansi-cjs/node_modules/ansi-styles": { - "version": "4.3.0", - "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz", - "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==", - "license": "MIT", - "dependencies": { - "color-convert": "^2.0.1" - }, - "engines": { - "node": ">=8" - }, - "funding": { - "url": "https://github.com/chalk/ansi-styles?sponsor=1" - } - }, - "node_modules/wrap-ansi-cjs/node_modules/emoji-regex": { - "version": "8.0.0", - "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz", - "integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==", - "license": "MIT" - }, - "node_modules/wrap-ansi-cjs/node_modules/string-width": { - "version": "4.2.3", - "resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz", - "integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==", - "license": "MIT", - "dependencies": { - "emoji-regex": "^8.0.0", - "is-fullwidth-code-point": "^3.0.0", - "strip-ansi": "^6.0.1" - }, - "engines": { - "node": ">=8" - } - }, - "node_modules/wrap-ansi-cjs/node_modules/strip-ansi": { - "version": "6.0.1", - "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz", - "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==", - "license": "MIT", - "dependencies": { - "ansi-regex": "^5.0.1" - }, - "engines": { - "node": ">=8" - } } } } diff --git a/package.json b/package.json index 7af22b4..3b04aa8 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@shocknet/clink-sdk", - "version": "1.7.3", + "version": "1.8.0", "description": "sdk client for clink", "repository": { "type": "git", @@ -47,14 +47,11 @@ "dependencies": { "@noble/hashes": "^1.8.0", "@scure/base": "^2.4.0", - "nostr-tools": "2.25.2", - "rimraf": "^6.0.1", - "typescript": "^5.8.3" + "nostr-tools": "2.25.2" }, "devDependencies": { - "@types/node": "^22.15.2" - }, - "overrides": { - "@scure/base": "$@scure/base" + "@types/node": "^22.15.2", + "rimraf": "^6.1.3", + "typescript": "^5.9.3" } -} \ No newline at end of file +} diff --git a/src/index.ts b/src/index.ts index 56dc86a..a351160 100644 --- a/src/index.ts +++ b/src/index.ts @@ -1,4 +1,4 @@ -import { AbstractSimplePool } from "nostr-tools/lib/types/abstract-pool" +import type { AbstractSimplePool } from "nostr-tools/lib/types/abstract-pool" import { SimplePool, getPublicKey, nip19, generateSecretKey, finalizeEvent, nip44, verifyEvent, type UnsignedEvent } from "nostr-tools" import { SendNofferRequest, NofferData, NofferReceipt } from "./noffer.js" import { NdebitData, SendNdebitRequest, generateK1, validateK1, newNdebitBudgetRequest, newNdebitPaymentRequest } from "./ndebit.js" diff --git a/src/nbeacon.ts b/src/nbeacon.ts index 2e7d762..ec6f35b 100644 --- a/src/nbeacon.ts +++ b/src/nbeacon.ts @@ -1,4 +1,4 @@ -import { AbstractSimplePool } from "nostr-tools/lib/types/abstract-pool" +import type { AbstractSimplePool } from "nostr-tools/lib/types/abstract-pool" import { Event, verifyEvent } from "nostr-tools" import { BEACON_FUTURE_SKEW_SECONDS, @@ -168,7 +168,7 @@ export const FetchClinkBeacon = async ( resolve(best ? parseClinkBeaconEvent(best) : null) } const timer = setTimeout(finish, timeoutSeconds * 1000) - closer = pool.subscribeMany(relays, { + closer = pool.subscribe(relays, { kinds: [CLINK_BEACON_KIND], authors: [expectedPub], "#d": [CLINK_BEACON_D_TAG], diff --git a/src/ndebit.ts b/src/ndebit.ts index 1f267b2..bda5291 100644 --- a/src/ndebit.ts +++ b/src/ndebit.ts @@ -1,6 +1,6 @@ import { randomBytes, bytesToHex } from '@noble/hashes/utils' import { nip44, getPublicKey } from "nostr-tools" -import { AbstractSimplePool } from "nostr-tools/lib/types/abstract-pool" +import type { AbstractSimplePool } from "nostr-tools/lib/types/abstract-pool" import { sendRequest } from "./sender.js" const { getConversationKey, encrypt } = nip44 diff --git a/src/nenroll.ts b/src/nenroll.ts index 0bb1717..1d231db 100644 --- a/src/nenroll.ts +++ b/src/nenroll.ts @@ -1,5 +1,5 @@ import { nip44, getPublicKey, type UnsignedEvent } from "nostr-tools" -import { AbstractSimplePool } from "nostr-tools/lib/types/pool" +import type { AbstractSimplePool } from "nostr-tools/lib/types/abstract-pool" import { sendRequest } from "./sender.js" import { CLINK_ENROLL_KIND, CLINK_VERSION } from "./constants.js" import { enrollPowBitsOk, mineNip13 } from "./nip13.js" diff --git a/src/nmanage.ts b/src/nmanage.ts index 111ad88..bc03369 100644 --- a/src/nmanage.ts +++ b/src/nmanage.ts @@ -1,5 +1,5 @@ import { nip44, getPublicKey } from "nostr-tools" -import { AbstractSimplePool } from "nostr-tools/lib/types/abstract-pool" +import type { AbstractSimplePool } from "nostr-tools/lib/types/abstract-pool" import { sendRequest } from "./sender.js" const { getConversationKey, encrypt } = nip44 diff --git a/src/noffer.ts b/src/noffer.ts index 5bdb905..6880019 100644 --- a/src/noffer.ts +++ b/src/noffer.ts @@ -1,5 +1,5 @@ import { nip44, getPublicKey } from "nostr-tools" -import { AbstractSimplePool } from "nostr-tools/lib/types/abstract-pool" +import type { AbstractSimplePool } from "nostr-tools/lib/types/abstract-pool" import { CLINK_OFFER_KIND, CLINK_VERSION } from "./constants.js" import { type NofferReceipt } from "./receipt.js" import { sendRequest } from "./sender.js" diff --git a/src/sender.ts b/src/sender.ts index b8e5a77..a3bb4f4 100644 --- a/src/sender.ts +++ b/src/sender.ts @@ -1,5 +1,5 @@ import { nip44, finalizeEvent, verifyEvent, UnsignedEvent, type Event } from "nostr-tools" -import { AbstractSimplePool, SubCloser } from "nostr-tools/lib/types/abstract-pool" +import type { AbstractSimplePool, SubCloser } from "nostr-tools/lib/types/abstract-pool" import { CLINK_VERSION } from "./constants.js" import { isNofferReceipt } from "./receipt.js" const { getConversationKey, decrypt } = nip44 @@ -126,7 +126,7 @@ export const sendRequest = async (pool: AbstractSimplePool, pair: Pair, relay const gen = ++listenGen log(`[ClinkSDK] Setting up subscription with filter:`, JSON.stringify(filter, null, 2)) closer.close() - closer = pool.subscribeMany(relays, filter, { + closer = pool.subscribe(relays, filter, { onevent: async (event) => { log(`[ClinkSDK] Received response event: kind=${event.kind}, eventId=${event.id}, from=${event.pubkey}`) if (!isClinkResponse(event, expect)) { diff --git a/test/unit/enroll-beacon.test.mjs b/test/unit/enroll-beacon.test.mjs index ae9bb39..8a00990 100644 --- a/test/unit/enroll-beacon.test.mjs +++ b/test/unit/enroll-beacon.test.mjs @@ -138,7 +138,7 @@ describe('beacon parse', () => { sig: '11'.repeat(64), } const pool = { - subscribeMany(_relays, _filters, opts) { + subscribe(_relays, _filter, opts) { queueMicrotask(() => { opts.onevent(spoof) opts.onevent(signed) @@ -186,7 +186,7 @@ describe('enroll remine', () => { const published = [] let onevent = null const pool = { - subscribeMany(_relays, _filters, opts) { + subscribe(_relays, _filter, opts) { onevent = opts.onevent return { close: () => {} } }, @@ -218,7 +218,7 @@ describe('enroll remine', () => { const published = [] let onevent = null const pool = { - subscribeMany(_relays, _filters, opts) { + subscribe(_relays, _filter, opts) { onevent = opts.onevent return { close: () => {} } }, @@ -244,7 +244,7 @@ describe('enroll remine', () => { it('throws before mining when caller asks above the client cap', async () => { const published = [] const pool = { - subscribeMany() { return { close: () => {} } }, + subscribe() { return { close: () => {} } }, publish(_relays, event) { published.push(event) return [Promise.resolve('ok')] diff --git a/test/unit/sender.test.mjs b/test/unit/sender.test.mjs index 4bea80f..6a755ee 100644 --- a/test/unit/sender.test.mjs +++ b/test/unit/sender.test.mjs @@ -32,14 +32,14 @@ function createMockPool({ onSubscribe, onPublish, replyFactory }) { order, wasClosed: () => closed, subscribeCount: () => order.filter(item => item === 'subscribe').length, - subscribeMany(relays, filters, opts) { + subscribe(relays, filter, opts) { if (!subscribeCalled) { assert.equal(publishCalled, false, 'subscribe must happen before publish') } subscribeCalled = true closed = false order.push('subscribe') - onSubscribe?.(relays, filters, opts) + onSubscribe?.(relays, filter, opts) onevent = opts.onevent return { close: () => { From 3f371666cb6610ce870679cb692726344d8a6d9f Mon Sep 17 00:00:00 2001 From: shocknet-justin Date: Sat, 26 Sep 2026 11:29:46 -0400 Subject: [PATCH 09/14] Validate input charset in exported nip19.decode Co-authored-by: Cursor --- src/index.ts | 3 ++- src/nip19Strict.ts | 12 ++++++++++++ test/unit/bech32.test.mjs | 31 +++++++++++++++++++++++++++++++ 3 files changed, 45 insertions(+), 1 deletion(-) create mode 100644 src/nip19Strict.ts diff --git a/src/index.ts b/src/index.ts index a351160..1663e1d 100644 --- a/src/index.ts +++ b/src/index.ts @@ -1,5 +1,6 @@ import type { AbstractSimplePool } from "nostr-tools/lib/types/abstract-pool" -import { SimplePool, getPublicKey, nip19, generateSecretKey, finalizeEvent, nip44, verifyEvent, type UnsignedEvent } from "nostr-tools" +import { SimplePool, getPublicKey, generateSecretKey, finalizeEvent, nip44, verifyEvent, type UnsignedEvent } from "nostr-tools" +import { nip19 } from "./nip19Strict.js" import { SendNofferRequest, NofferData, NofferReceipt } from "./noffer.js" import { NdebitData, SendNdebitRequest, generateK1, validateK1, newNdebitBudgetRequest, newNdebitPaymentRequest } from "./ndebit.js" import { NmanageRequest, SendNmanageRequest, newListRequest } from "./nmanage.js" diff --git a/src/nip19Strict.ts b/src/nip19Strict.ts new file mode 100644 index 0000000..fd0eb96 --- /dev/null +++ b/src/nip19Strict.ts @@ -0,0 +1,12 @@ +import { nip19 as nostrNip19 } from "nostr-tools" + +const PRINTABLE_ASCII = /^[\x21-\x7E]+$/ + +const decode = ((value: string) => { + if (!PRINTABLE_ASCII.test(value)) { + throw new Error("invalid bech32 string") + } + return nostrNip19.decode(value) +}) as typeof nostrNip19.decode + +export const nip19: typeof nostrNip19 = { ...nostrNip19, decode } diff --git a/test/unit/bech32.test.mjs b/test/unit/bech32.test.mjs index 981d77f..5e75d26 100644 --- a/test/unit/bech32.test.mjs +++ b/test/unit/bech32.test.mjs @@ -12,6 +12,8 @@ import { nmanageEncode, OfferPriceType, isNofferReceipt, + nip19, + ClinkSDK, } from '../../build/index.js' const fixtures = JSON.parse( @@ -129,6 +131,35 @@ describe('bech32 round-trip', () => { }) }) +const withKelvinSign = (encoded) => { + const upper = encoded.toUpperCase() + const at = upper.indexOf('K', upper.lastIndexOf('1') + 1) + return at < 0 ? null : upper.slice(0, at) + '\u212A' + upper.slice(at + 1) +} + +const nprofileWithK = () => { + for (let n = 0; ; n++) { + const encoded = nip19.nprofileEncode({ pubkey: n.toString(16).padStart(64, 'b'), relays: ['wss://relay.example'] }) + if (withKelvinSign(encoded)) return encoded + } +} + +describe('nip19 decode', () => { + it('rejects non-ASCII look-alike characters', () => { + const encoded = nprofileWithK() + assert.equal(nip19.decode(encoded).type, 'nprofile') + assert.equal(nip19.decode(encoded.toUpperCase()).type, 'nprofile') + assert.throws(() => nip19.decode(withKelvinSign(encoded))) + assert.throws(() => ClinkSDK.fromNprofile(withKelvinSign(encoded), new Uint8Array(32))) + }) + + it('rejects the same trick in noffer decode', () => { + const encoded = withKelvinSign(fixtures.noffer.encoded) ?? withKelvinSign(nmanageEncode(fixtures.nmanage.decoded)) + assert.ok(encoded) + assert.throws(() => decodeBech32(encoded)) + }) +}) + describe('noffer receipts', () => { it('accepts ok with or without a 64-char hex preimage', () => { assert.equal(isNofferReceipt({ res: 'ok' }), true) From d840f128f55ddb76edcb8a5f178ef1e4ffd7b4be Mon Sep 17 00:00:00 2001 From: shocknet-justin Date: Thu, 5 Nov 2026 16:12:42 -0500 Subject: [PATCH 10/14] Reject a TLV that ends before its length byte. A one-byte payload made the length undefined, and slice(NaN) returned the same buffer, so decode looped forever. Co-authored-by: Cursor --- src/nip19Extension.ts | 1 + test/unit/bech32.test.mjs | 8 ++++++++ 2 files changed, 9 insertions(+) diff --git a/src/nip19Extension.ts b/src/nip19Extension.ts index a8175cc..8e9bd9c 100644 --- a/src/nip19Extension.ts +++ b/src/nip19Extension.ts @@ -181,6 +181,7 @@ function parseTLV(data: Uint8Array): TLV { let result: TLV = {} let rest = data while (rest.length > 0) { + if (rest.length < 2) throw new Error(`not enough data to read on TLV ${rest[0]}`) let t = rest[0] let l = rest[1] let v = rest.slice(2, 2 + l) diff --git a/test/unit/bech32.test.mjs b/test/unit/bech32.test.mjs index 5e75d26..dc51d48 100644 --- a/test/unit/bech32.test.mjs +++ b/test/unit/bech32.test.mjs @@ -129,6 +129,14 @@ describe('bech32 round-trip', () => { assert.throws(() => nofferEncode({ ...pointer, price: 21 })) assert.throws(() => nofferEncode({ ...pointer, priceType: OfferPriceType.Fixed })) }) + + it('rejects a TLV that has a tag but no length byte', () => { + // noffer1qq225w60 decodes to a single payload byte [0]: tag, no length/value. + // Without a length-header check, parseTLV would slice(NaN) and loop forever. + assert.throws(() => decodeBech32('noffer1qq225w60'), /not enough data to read on TLV/) + assert.throws(() => decodeBech32(bech32.encode('ndebit', bech32.toWords(new Uint8Array([1])), 5000))) + assert.throws(() => decodeBech32(bech32.encode('nmanage', bech32.toWords(new Uint8Array([2])), 5000))) + }) }) const withKelvinSign = (encoded) => { From b52e70a373018bb89f5e8343547e5f2f7d29d42f Mon Sep 17 00:00:00 2001 From: shocknet-justin Date: Fri, 6 Nov 2026 12:59:37 -0500 Subject: [PATCH 11/14] Support offer payer-data discovery and numeric quantity --- README.md | 23 +++++++++-- src/noffer.ts | 33 ++++++++++----- test/types/noffer.ts | 15 +++++++ test/unit/sender.test.mjs | 39 ++++++++++++++++++ test/unit/types.test.mjs | 12 ++++++ test/unit/validators.test.mjs | 75 +++++++++++++++++++++++++++++++++++ 6 files changed, 185 insertions(+), 12 deletions(-) create mode 100644 test/types/noffer.ts create mode 100644 test/unit/types.test.mjs diff --git a/README.md b/README.md index 383487a..6437f82 100644 --- a/README.md +++ b/README.md @@ -111,7 +111,7 @@ const sdk = new ClinkSDK({ const request: NofferData = { offer: decoded.data.offer, - amount_sats: 1000, // sats (optional for variable/spontaneous offers) + amount_sats: 1000, // payer-selected unit price in sats for spontaneous offers description: 'coffee for bob', // optional, max 100 chars expires_in_seconds: 3600, // optional payer_data: { name: 'Alice' }, // optional @@ -130,6 +130,21 @@ sdk.Noffer(request, receiptCallback).then(response => { }); ``` +#### Payer Data Discovery and Quantity + +An offer host can respond with code `6` and `payer_data: string[]` listing the required payer-data keys. Treat this as discovery: collect the requested values and explicitly retry the same offer with `payer_data` populated. The SDK preserves the list but does not collect values or retry automatically. For example, after receiving `{ code: 6, error: 'Missing payer data', payer_data: ['name', 'quantity'] }`: + +```ts +const retry = await sdk.Noffer({ + ...request, + payer_data: { ...request.payer_data, name: 'Alice', quantity: 2 }, +}); +``` + +The exact key `quantity` must be a positive safe integer JSON number, not a string. All other payer-data values must be strings. Undefined optional fields are treated as omitted. Invalid outgoing requests are rejected locally before encryption or relay contact. + +Offer price categories describe the **unit price**: `Fixed = 0` is a fixed unit price, `Variable = 1` is resolved by the host on request, and `Spontaneous = 2` uses the payer's `amount_sats` as the unit price. Quantity multiplies the unit price only when the host's required payer-data list includes `quantity`; merely sending it does not enable multiplication. The host computes the invoice total, and wallets must verify that total before payment. The SDK client is not a pricing engine. + ### 3. Sending a CLINK Debit Request ```ts @@ -322,8 +337,10 @@ Pinned by this package — import these from `@shocknet/clink-sdk`, not from a s | `UnsignedEvent` | type | Event shape before `finalizeEvent` | ### Types -- **`NofferData`**: `{ offer: string, amount_sats?: number, description?: string, expires_in_seconds?: number, zap?: string, payer_data?: Record }` -- **`NofferResponse`**: `{ bolt11: string } | { code: number, error: string, range?: { min: number, max: number }, latest?: string }` +- **`NofferPayerData`**: `Record & { quantity?: number }` - runtime validation permits numbers only for the exact `quantity` key, as positive safe integers +- **`NofferData`**: `{ offer: string, amount_sats?: number, description?: string, expires_in_seconds?: number, zap?: string, payer_data?: NofferPayerData }` +- **`NofferError`**: `{ code: number, error: string, range?: { min: number, max: number }, latest?: string, payer_data?: string[] }` - code `6` can list required payer-data keys for discovery and retry +- **`NofferResponse`**: `{ bolt11: string } | NofferError` - **`NofferReceipt`**: `{ res: 'ok', preimage?: string }` — Lightning receipts include `preimage`; internal settlement omits it - **`NdebitData`**: `{ pointer?: string, amount_sats?: number, bolt11?: string, frequency?: BudgetFrequency, k1?: string, description?: string }` - **`NdebitResponse`**: `{ res: 'ok', preimage?: string } | { res: 'GFY', error: string, code: number, reason?: Gfy6Reason, delta?: { max_delta_ms: number, actual_delta_ms: number }, retry_after?: number, range?: { min: number, max: number } }` diff --git a/src/noffer.ts b/src/noffer.ts index 6880019..8ec1e3d 100644 --- a/src/noffer.ts +++ b/src/noffer.ts @@ -7,33 +7,48 @@ export type { NofferReceipt } from "./receipt.js" export { isNofferReceipt } from "./receipt.js" const { getConversationKey, encrypt } = nip44 +export type NofferPayerData = Record & { quantity?: number } + export type NofferData = { offer: string amount_sats?: number zap?: string - payer_data?: Record + payer_data?: NofferPayerData expires_in_seconds?: number description?: string } export const validateNofferData = (data: unknown): NofferData => { - if (typeof data !== 'object' || data === null) throw new Error('data must be an object') + if (typeof data !== 'object' || data === null || Array.isArray(data)) throw new Error('data must be an object') if (!('offer' in data) || typeof data.offer !== 'string') throw new Error('offer must be a string') - if ('amount_sats' in data && typeof data.amount_sats !== 'number') throw new Error('amount_sats must be a number if present') - if ('zap' in data && typeof data.zap !== 'string') throw new Error('zap must be a string if present') - if ('payer_data' in data && (typeof data.payer_data !== 'object' || data.payer_data === null || Array.isArray(data.payer_data))) { - throw new Error('payer_data must be an object if present') + if ('amount_sats' in data && data.amount_sats !== undefined && typeof data.amount_sats !== 'number') throw new Error('amount_sats must be a number if present') + if ('zap' in data && data.zap !== undefined && typeof data.zap !== 'string') throw new Error('zap must be a string if present') + if ('payer_data' in data && data.payer_data !== undefined) { + if (typeof data.payer_data !== 'object' || data.payer_data === null || Array.isArray(data.payer_data)) { + throw new Error('payer_data must be an object if present') + } + for (const [key, value] of Object.entries(data.payer_data)) { + if (value === undefined) continue + if (key === 'quantity') { + if (typeof value !== 'number' || !Number.isSafeInteger(value) || value <= 0) { + throw new Error('payer_data.quantity must be a positive safe integer') + } + } else if (typeof value !== 'string') { + throw new Error(`payer_data.${key} must be a string`) + } + } } - if ('expires_in_seconds' in data && typeof data.expires_in_seconds !== 'number') throw new Error('expires_in_seconds must be a number if present') - if ('description' in data && typeof data.description !== 'string') throw new Error('description must be a string if present') + if ('expires_in_seconds' in data && data.expires_in_seconds !== undefined && typeof data.expires_in_seconds !== 'number') throw new Error('expires_in_seconds must be a number if present') + if ('description' in data && data.description !== undefined && typeof data.description !== 'string') throw new Error('description must be a string if present') return data as NofferData } export type NofferSuccess = { bolt11: string } -export type NofferError = { code: number, error: string, range?: { min: number, max: number }, latest?: string } +export type NofferError = { code: number, error: string, range?: { min: number, max: number }, latest?: string, payer_data?: string[] } export type NofferResponse = NofferSuccess | NofferError export const SendNofferRequest = async (pool: AbstractSimplePool, privateKey: Uint8Array, relays: string[], toPubKey: string, data: NofferData, timeoutSeconds = 30, onReceipt?: (receipt: NofferReceipt) => void): Promise => { + validateNofferData(data) if (data.description && data.description.length > 100) { throw new Error('Description must be less than 100 characters') } diff --git a/test/types/noffer.ts b/test/types/noffer.ts new file mode 100644 index 0000000..760bed7 --- /dev/null +++ b/test/types/noffer.ts @@ -0,0 +1,15 @@ +import type { NofferData, NofferError, NofferPayerData, NofferResponse } from '../../build/index.js' + +const payerData: NofferPayerData = { name: 'Alice', quantity: 2 } +const request: NofferData = { offer: 'o', payer_data: payerData } +const legacyRequest: NofferData = { offer: 'o', payer_data: { name: 'Alice' } } +const discovery: NofferError = { code: 6, error: 'Missing payer data', payer_data: ['name', 'quantity'] } +const response: NofferResponse = discovery +const requiredKeys: string[] | undefined = discovery.payer_data + +// @ts-expect-error Quantity must be numeric, not a string. +const invalidPayerData: NofferPayerData = { quantity: '2' } +// @ts-expect-error The request must use the quantity-aware payer-data type. +const invalidRequest: NofferData = { offer: 'o', payer_data: { quantity: '2' } } +// @ts-expect-error Error payer_data lists keys, not request values. +const invalidError: NofferError = { code: 6, error: 'Missing payer data', payer_data: { name: 'Alice' } } diff --git a/test/unit/sender.test.mjs b/test/unit/sender.test.mjs index 851edb0..cfbd957 100644 --- a/test/unit/sender.test.mjs +++ b/test/unit/sender.test.mjs @@ -3,6 +3,7 @@ import assert from 'node:assert/strict' import { generateSecretKey, getPublicKey, nip44 } from 'nostr-tools' import { sendRequest, setDebug } from '../../build/sender.js' import { signedClinkReply } from './signed-reply.mjs' +import { SendNofferRequest } from '../../build/index.js' const { getConversationKey, encrypt } = nip44 @@ -83,6 +84,44 @@ const sendOffer = (pool, clientPriv, clientPub, serverPub, timeoutSeconds = 5, m ) describe('sender lifecycle', () => { + it('preserves code 6 payer-data discovery and sends numeric quantity on explicit retry', async () => { + const clientPriv = generateSecretKey() + const clientPub = getPublicKey(clientPriv) + const serverPriv = generateSecretKey() + const serverPub = getPublicKey(serverPriv) + const discovery = { + code: 6, error: 'Missing payer data', payer_data: ['name', 'quantity'], + range: { min: 1, max: 1000 }, latest: 'noffer1updated', + } + const payloads = [] + const pool = createMockPool({ + replyFactory: (event) => { + payloads.push(JSON.parse(nip44.decrypt(event.content, getConversationKey(serverPriv, clientPub)))) + const response = payloads.length === 1 ? discovery : { bolt11: 'lnbc1dummy' } + return [signedClinkReply(serverPriv, clientPub, event.id, response, 21001)] + }, + }) + const request = { + offer: 'o', amount_sats: 21, description: 'x'.repeat(100), + zap: undefined, expires_in_seconds: undefined, payer_data: undefined, + } + + const response = await SendNofferRequest(pool, clientPriv, ['wss://relay.example.com'], serverPub, request, 5) + assert.deepEqual(response, discovery) + assert.deepEqual(payloads, [{ offer: 'o', amount_sats: 21, description: request.description }]) + assert.equal(pool.wasClosed(), true) + + const retry = await SendNofferRequest(pool, clientPriv, ['wss://relay.example.com'], serverPub, { + ...request, payer_data: { name: 'Alice', quantity: 2, email: undefined }, + }, 5) + assert.deepEqual(retry, { bolt11: 'lnbc1dummy' }) + assert.deepEqual(payloads[1], { + offer: 'o', amount_sats: 21, description: request.description, + payer_data: { name: 'Alice', quantity: 2 }, + }) + assert.equal(pool.wasClosed(), true) + }) + it('subscribes before publish and resolves primary response', async () => { const clientPriv = generateSecretKey() const clientPub = getPublicKey(clientPriv) diff --git a/test/unit/types.test.mjs b/test/unit/types.test.mjs new file mode 100644 index 0000000..b508948 --- /dev/null +++ b/test/unit/types.test.mjs @@ -0,0 +1,12 @@ +import { it } from 'node:test' +import { execFileSync } from 'node:child_process' +import { fileURLToPath } from 'node:url' + +it('typechecks public noffer payer-data and recovery types', () => { + execFileSync(process.execPath, [ + fileURLToPath(new URL('../../node_modules/typescript/bin/tsc', import.meta.url)), + '--noEmit', '--strict', '--skipLibCheck', '--target', 'ES2020', '--module', 'ES2020', + '--moduleResolution', 'node', + fileURLToPath(new URL('../types/noffer.ts', import.meta.url)), + ], { stdio: 'pipe' }) +}) diff --git a/test/unit/validators.test.mjs b/test/unit/validators.test.mjs index 3c5d3f9..1169af7 100644 --- a/test/unit/validators.test.mjs +++ b/test/unit/validators.test.mjs @@ -13,6 +13,7 @@ import { newGetRequest, gfy6Reason, SendNdebitRequest, + SendNofferRequest, generateSecretKey, newNdebitFullAccessRequest, newNdebitPaymentRequest, @@ -103,6 +104,80 @@ describe('validators', () => { ) }) + it('accepts numeric noffer quantity and string payer data', () => { + for (const quantity of [1, 2, Number.MAX_SAFE_INTEGER]) { + const data = { offer: 'o', payer_data: { quantity, name: 'Alice', Quantity: 'custom', quantity_hint: '2' } } + assert.equal(validateNofferData(data), data) + } + assert.doesNotThrow(() => validateNofferData({ offer: 'o', payer_data: {} })) + }) + + it('rejects invalid noffer quantity', () => { + for (const quantity of [ + 0, -0, -1, 1.5, Number.MAX_SAFE_INTEGER + 1, + NaN, Infinity, -Infinity, '2', '', null, true, false, {}, [], 2n, + ]) { + assert.throws( + () => validateNofferData({ offer: 'o', payer_data: { quantity } }), + /payer_data\.quantity must be a positive safe integer/, + ) + } + }) + + it('rejects invalid noffer payer-data values and containers', () => { + for (const value of [2, 0, NaN, Infinity, null, true, false, {}, [], 2n, () => {}, Symbol('value')]) { + for (const key of ['name', 'Quantity', 'quantity_hint']) { + assert.throws( + () => validateNofferData({ offer: 'o', payer_data: { [key]: value } }), + /must be a string/, + ) + } + } + for (const payer_data of [null, [], ['Alice'], 'Alice', 2, true, () => {}]) { + assert.throws(() => validateNofferData({ offer: 'o', payer_data }), /payer_data must be an object/) + } + for (const data of [null, [], Object.assign([], { offer: 'o' }), 'o', 2, undefined]) { + assert.throws(() => validateNofferData(data), /data must be an object/) + } + }) + + it('accepts undefined optional noffer fields as omitted', () => { + const data = { + offer: 'o', amount_sats: undefined, zap: undefined, payer_data: undefined, + expires_in_seconds: undefined, description: undefined, + } + assert.equal(validateNofferData(data), data) + assert.equal(JSON.stringify(data), '{"offer":"o"}') + const withPayerData = { ...data, payer_data: { quantity: undefined, name: undefined } } + assert.equal(validateNofferData(withPayerData), withPayerData) + assert.equal(JSON.stringify(withPayerData), '{"offer":"o","payer_data":{}}') + }) + + it('SendNofferRequest validates before encryption or relay contact', async () => { + let contacted = false + const pool = { + subscribe() { contacted = true; throw new Error('unexpected subscribe') }, + publish() { contacted = true; throw new Error('unexpected publish') }, + } + for (const [data, error] of [ + [{}, /offer must be a string/], + [{ offer: 1 }, /offer must be a string/], + [{ offer: 'o', amount_sats: '21' }, /amount_sats must be a number/], + [{ offer: 'o', zap: null }, /zap must be a string/], + [{ offer: 'o', expires_in_seconds: '60' }, /expires_in_seconds must be a number/], + [{ offer: 'o', description: 1 }, /description must be a string/], + [{ offer: 'o', description: 'x'.repeat(101) }, /Description must be less than 100 characters/], + [{ offer: 'o', payer_data: [] }, /payer_data must be an object/], + [{ offer: 'o', payer_data: { name: 2 } }, /payer_data\.name must be a string/], + [{ offer: 'o', payer_data: { quantity: '2' } }, /payer_data\.quantity must be a positive safe integer/], + [{ offer: 'o', payer_data: { quantity: 0 } }, /payer_data\.quantity must be a positive safe integer/], + ]) { + // Invalid keys ensure validation happens before key derivation and encryption too. + await assert.rejects(SendNofferRequest(pool, new Uint8Array(), [], 'invalid', data), error) + } + assert.equal(contacted, false) + }) + it('validates nmanage requests by action', () => { const created = newCreateRequest('coffee', { price_sats: 21 }, 'ptr') assert.deepEqual(validateNmanageRequest(created), created) From 945fb772319ddf8c19cb99aba944d999fbc5f273 Mon Sep 17 00:00:00 2001 From: shocknet-justin Date: Fri, 6 Nov 2026 16:35:40 -0500 Subject: [PATCH 12/14] Reject oversized TLV values before encoding --- src/nip19Extension.ts | 1 + test/unit/bech32.test.mjs | 48 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 49 insertions(+) diff --git a/src/nip19Extension.ts b/src/nip19Extension.ts index 8e9bd9c..1b50a64 100644 --- a/src/nip19Extension.ts +++ b/src/nip19Extension.ts @@ -258,6 +258,7 @@ function encodeTLV(tlv: TLV): Uint8Array { .reverse() .forEach(([t, vs]) => { vs.forEach(v => { + if (v.length > 255) throw new Error(`TLV ${t} value exceeds 255 bytes`) let entry = new Uint8Array(v.length + 2) entry.set([parseInt(t)], 0) entry.set([v.length], 1) diff --git a/test/unit/bech32.test.mjs b/test/unit/bech32.test.mjs index dc51d48..657387f 100644 --- a/test/unit/bech32.test.mjs +++ b/test/unit/bech32.test.mjs @@ -139,6 +139,54 @@ describe('bech32 round-trip', () => { }) }) +describe('TLV encoding limits', () => { + const encoders = [ + ['noffer', nofferEncode, fixtures.noffer.decoded, 'offer'], + ['ndebit', ndebitEncode, fixtures.ndebit.decoded, 'pointer'], + ['nmanage', nmanageEncode, fixtures.nmanage.decoded, 'pointer'], + ] + + for (const [kind, encode, pointer, identifier] of encoders) { + for (const field of [identifier, 'relay']) { + it(`checks the UTF-8 byte length of ${kind} ${field}`, () => { + for (const value of ['a'.repeat(255), '\u00e9'.repeat(127) + 'a']) { + assert.equal(utf8.encode(value).length, 255) + const expected = { ...pointer, [field]: value } + const decoded = decodeBech32(encode(expected)).data + assert.equal(decoded[field], value) + assert.equal(decoded.pubkey, expected.pubkey) + assert.equal(decoded.relay, expected.relay) + assert.equal(decoded[identifier], expected[identifier]) + } + for (const value of ['a'.repeat(256), 'a'.repeat(257), 'a'.repeat(512), '\u00e9'.repeat(128)]) { + assert.throws(() => encode({ ...pointer, [field]: value }), /TLV [12] value exceeds 255 bytes/) + } + }) + } + } + + it('also rejects an oversized noffer currency value', () => { + assert.throws(() => nofferEncode({ + ...fixtures.noffer.decoded, price: undefined, + priceType: OfferPriceType.Variable, currency: 'a'.repeat(256), + }), /TLV 5 value exceeds 255 bytes/) + }) + + it('rejects an oversized identifier containing injected routing TLVs', () => { + const relay = utf8.encode('wss://injected.example') + const injected = [0, 32, ...new Uint8Array(32).fill(0x41), 1, relay.length, ...relay] + injected.push(127, 100, ...new Uint8Array(100).fill(0x41)) + const padding = 256 - injected.length - 2 + injected.push(127, padding, ...new Uint8Array(padding).fill(0x41)) + const identifier = String.fromCharCode(...injected) + assert.equal(utf8.encode(identifier).length, 256) + // A wrapped length of zero would expose the identifier's bytes as routing TLVs. + for (const [, encode, pointer, field] of encoders) { + assert.throws(() => encode({ ...pointer, [field]: identifier }), /TLV 2 value exceeds 255 bytes/) + } + }) +}) + const withKelvinSign = (encoded) => { const upper = encoded.toUpperCase() const at = upper.indexOf('K', upper.lastIndexOf('1') + 1) From b0bd9e7b24f6ce6585e89a6ea2856db70aff670e Mon Sep 17 00:00:00 2001 From: shocknet-justin Date: Sun, 8 Nov 2026 13:31:41 -0500 Subject: [PATCH 13/14] Harden SDK request handling and encoding for 1.8 --- README.md | 16 ++ src/ndebit.ts | 61 +++----- src/nip19Extension.ts | 40 ++--- src/nip19Strict.ts | 10 +- src/noffer.ts | 48 ++++-- src/sender.ts | 67 +++++--- test/unit/bech32.test.mjs | 99 ++++++++++++ test/unit/sender.test.mjs | 279 ++++++++++++++++++++++++++++++++-- test/unit/validators.test.mjs | 139 ++++++++++++++++- 9 files changed, 656 insertions(+), 103 deletions(-) diff --git a/README.md b/README.md index 6437f82..90d8dc3 100644 --- a/README.md +++ b/README.md @@ -143,8 +143,20 @@ const retry = await sdk.Noffer({ The exact key `quantity` must be a positive safe integer JSON number, not a string. All other payer-data values must be strings. Undefined optional fields are treated as omitted. Invalid outgoing requests are rejected locally before encryption or relay contact. +When supplied, `amount_sats` must be a positive safe integer and `expires_in_seconds` must be a non-negative safe integer. Zero expiry is permitted; the host determines the resulting invoice expiry. Fractions, non-finite numbers, and unsafe integers are rejected rather than rounded or serialized as `null`. + Offer price categories describe the **unit price**: `Fixed = 0` is a fixed unit price, `Variable = 1` is resolved by the host on request, and `Spontaneous = 2` uses the payer's `amount_sats` as the unit price. Quantity multiplies the unit price only when the host's required payer-data list includes `quantity`; merely sending it does not enable multiplication. The host computes the invoice total, and wallets must verify that total before payment. The SDK client is not a pricing engine. +Receipt callbacks keep listening only after an invoice response. Discovery and other error responses close their subscriptions immediately; they cannot produce a receipt for that attempt. + +#### Encoding Bounds + +Each TLV value is limited to 255 bytes, measured after UTF-8 encoding for strings. Oversized offer IDs, pointers, relay URLs, and currency values are rejected before encoding. + +Encoded offer prices support integers from `0` through `Number.MAX_SAFE_INTEGER`. Existing nonzero 32-bit prices retain their four-byte encoding; larger prices use lossless wider big-endian values. An explicit zero price is encoded as zero rather than omitted. An absent price remains optional, and currency cannot be combined with any supplied price, including zero. Decoding rejects empty or unsafe price values instead of returning a rounded number. + +Both `nip19.decode` and `nip19.decodeNostrURI` enforce printable ASCII. The URI helper retains its `{ type: 'invalid', data: null }` result for invalid inputs. + ### 3. Sending a CLINK Debit Request ```ts @@ -317,6 +329,10 @@ For validating inbound/outbound CLINK payloads (e.g. server-side request checks) - `validateNofferData`, `validateNdebitData`, `validateK1`, `validateBudgetFrequency` - `validateNmanageRequest` and per-action helpers: `validateNmanageCreateOffer`, `validateNmanageUpdateOffer`, `validateNmanageDeleteOffer`, `validateNmanageGetOffer`, `validateNmanageListOffers`, `validateOfferFields` +`validateNofferData`, `validateNdebitData`, and `validateBudgetFrequency` return detached, normalized objects rather than the original input. They read recognized values once, omit undefined optional fields and unknown top-level fields, and copy nested payer-data or frequency values. Offer and debit sending serialize this validated payload, not caller-defined `toJSON()` output. + +When publishing to multiple relays, one rejection does not abort another relay's accepted request. Publication fails only when all attempts fail; an empty relay list is rejected. A timeout or publication error is not proof that the host did not act, so callers must not blindly retry payments. + ### Debug - `setDebug(enabled: boolean)` — when `true`, logs relay subscribe/publish/response lifecycle to the console (default `false`) diff --git a/src/ndebit.ts b/src/ndebit.ts index f94cb9b..663fc52 100644 --- a/src/ndebit.ts +++ b/src/ndebit.ts @@ -23,18 +23,16 @@ export const generateK1 = (): string => bytesToHex(randomBytes(32)) export const validateBudgetFrequency = (frequency: unknown): BudgetFrequency => { if (typeof frequency !== 'object' || frequency === null || Array.isArray(frequency)) throw new Error('frequency must be an object') - if (!('number' in frequency) || typeof frequency.number !== 'number') throw new Error('frequency.number must be a number') - if (frequency.number <= 0 || !Number.isSafeInteger(frequency.number)) throw new Error('frequency.number must be a positive integer') - if (!('unit' in frequency) || typeof frequency.unit !== 'string') throw new Error('frequency.unit must be a string') - if (frequency.unit !== 'day' && frequency.unit !== 'week' && frequency.unit !== 'month') { + const { number, unit } = frequency as Record + if (typeof number !== 'number') throw new Error('frequency.number must be a number') + if (number <= 0 || !Number.isSafeInteger(number)) throw new Error('frequency.number must be a positive integer') + if (typeof unit !== 'string') throw new Error('frequency.unit must be a string') + if (unit !== 'day' && unit !== 'week' && unit !== 'month') { throw new Error('frequency.unit must be day, week, or month') } - return frequency as BudgetFrequency + return { number, unit } } -const defined = (rec: Record, key: string): boolean => - rec[key] !== undefined - const assertAmountSats = (n: unknown): number => { if (typeof n !== 'number' || !Number.isSafeInteger(n) || n <= 0) { throw new Error('amount_sats must be a positive integer') @@ -51,43 +49,34 @@ const assertBolt11 = (bolt11: unknown): string => { export const validateNdebitData = (data: unknown): NdebitData => { if (typeof data !== 'object' || data === null || Array.isArray(data)) throw new Error('data must be an object') - const rec = data as Record - if (defined(rec, 'pointer') && typeof rec.pointer !== 'string') throw new Error('pointer must be a string if present') - if (defined(rec, 'amount_sats')) assertAmountSats(rec.amount_sats) - if (defined(rec, 'bolt11')) assertBolt11(rec.bolt11) - if (defined(rec, 'description')) { - if (typeof rec.description !== 'string') throw new Error('description must be a string if present') - assertDescription(rec.description) + const { pointer, amount_sats, bolt11, frequency, k1, description } = data as Record + const out: NdebitData = {} + if (pointer !== undefined) { + if (typeof pointer !== 'string') throw new Error('pointer must be a string if present') + out.pointer = pointer } - - const bolt11 = defined(rec, 'bolt11') ? rec.bolt11 as string : undefined - const hasFrequency = defined(rec, 'frequency') - const hasAmount = defined(rec, 'amount_sats') - const hasK1 = defined(rec, 'k1') - - if (hasK1) { - validateK1(rec.k1) - if (!bolt11 || hasFrequency) { + if (amount_sats !== undefined) out.amount_sats = assertAmountSats(amount_sats) + if (bolt11 !== undefined) out.bolt11 = assertBolt11(bolt11) + if (description !== undefined) { + if (typeof description !== 'string') throw new Error('description must be a string if present') + assertDescription(description) + out.description = description + } + if (k1 !== undefined) { + out.k1 = validateK1(k1) + if (!out.bolt11 || frequency !== undefined) { throw new Error('k1 requires a bolt11 payment request') } } - if (hasFrequency) { - if (bolt11) { + if (frequency !== undefined) { + if (out.bolt11) { throw new Error('frequency cannot be combined with bolt11') } - if (!hasAmount) { + if (amount_sats === undefined) { throw new Error('frequency requires amount_sats') } - validateBudgetFrequency(rec.frequency) + out.frequency = validateBudgetFrequency(frequency) } - - const out: NdebitData = {} - if (defined(rec, 'pointer')) out.pointer = rec.pointer as string - if (hasAmount) out.amount_sats = rec.amount_sats as number - if (bolt11) out.bolt11 = bolt11 - if (hasFrequency) out.frequency = rec.frequency as BudgetFrequency - if (hasK1) out.k1 = rec.k1 as string - if (defined(rec, 'description')) out.description = rec.description as string return out } diff --git a/src/nip19Extension.ts b/src/nip19Extension.ts index 1b50a64..e65ee66 100644 --- a/src/nip19Extension.ts +++ b/src/nip19Extension.ts @@ -23,16 +23,12 @@ export const Bech32MaxSize = 5000 export const BECH32_REGEX = /[\x21-\x7E]{1,83}1[023456789acdefghjklmnpqrstuvwxyz]{6,}/ function integerToUint8Array(number: number) { - // Create a Uint8Array with enough space to hold a 32-bit integer (4 bytes). - const uint8Array = new Uint8Array(4) - - // Use bitwise operations to extract the bytes. - uint8Array[0] = (number >> 24) & 0xff // Most significant byte (MSB) - uint8Array[1] = (number >> 16) & 0xff - uint8Array[2] = (number >> 8) & 0xff - uint8Array[3] = number & 0xff // Least significant byte (LSB) - - return uint8Array + if (!Number.isSafeInteger(number) || number < 0) { + throw new Error('noffer price must be a nonnegative safe integer') + } + const hex = BigInt(number).toString(16) + // Preserve shipped four-byte encodings, widening only when necessary. + return hexToBytes(hex.padStart(Math.max(8, hex.length + hex.length % 2), '0')) } export type ManagePointer = { @@ -149,7 +145,7 @@ const nofferPriceType = (tlv: TLV, price?: number, currency?: string): OfferPric } return flag } - if (currency) return OfferPriceType.Variable + if (currency !== undefined) return OfferPriceType.Variable if (price !== undefined) return OfferPriceType.Fixed return OfferPriceType.Spontaneous } @@ -159,11 +155,17 @@ const decodeNofferTlv = (tlv: TLV): OfferPointer => { const relay = requireTlv(tlv, 1, 'noffer') const offer = requireTlv(tlv, 2, 'noffer') const priceRaw = tlvValue(tlv, 4) - const price = priceRaw ? parseInt(bytesToHex(priceRaw), 16) : undefined + let price: number | undefined + if (priceRaw !== undefined) { + if (priceRaw.length === 0) throw new Error('noffer price TLV must not be empty') + const integer = BigInt(`0x${bytesToHex(priceRaw)}`) + if (integer > BigInt(Number.MAX_SAFE_INTEGER)) throw new Error('noffer price must be a nonnegative safe integer') + price = Number(integer) + } const currency = optionalUtf8(tlv, 5) - if (currency && price !== undefined) throw new Error('noffer currency excludes price') + if (currency !== undefined && price !== undefined) throw new Error('noffer currency excludes price') const priceType = nofferPriceType(tlv, price, currency) - if (currency && priceType !== OfferPriceType.Variable) { + if (currency !== undefined && priceType !== OfferPriceType.Variable) { throw new Error('noffer currency requires variable price type') } const data: OfferPointer = { @@ -173,7 +175,7 @@ const decodeNofferTlv = (tlv: TLV): OfferPointer => { priceType, price, } - if (currency) data.currency = currency + if (currency !== undefined) data.currency = currency return data } @@ -195,11 +197,11 @@ function parseTLV(data: Uint8Array): TLV { export const nofferEncode = (offer: OfferPointer): string => { - if (offer.currency) { + if (offer.currency !== undefined) { if (offer.priceType !== OfferPriceType.Variable) { throw new Error('noffer currency requires variable price type') } - if (offer.price) { + if (offer.price !== undefined) { throw new Error('noffer currency excludes price') } } @@ -209,10 +211,10 @@ export const nofferEncode = (offer: OfferPointer): string => { 2: [utf8Encoder.encode(offer.offer)], 3: [new Uint8Array([Number(offer.priceType)])], } - if (offer.price) { + if (offer.price !== undefined) { o[4] = [integerToUint8Array(offer.price)] } - if (offer.currency) { + if (offer.currency !== undefined) { o[5] = [utf8Encoder.encode(offer.currency)] } const data = encodeTLV(o) diff --git a/src/nip19Strict.ts b/src/nip19Strict.ts index fd0eb96..dde9f43 100644 --- a/src/nip19Strict.ts +++ b/src/nip19Strict.ts @@ -9,4 +9,12 @@ const decode = ((value: string) => { return nostrNip19.decode(value) }) as typeof nostrNip19.decode -export const nip19: typeof nostrNip19 = { ...nostrNip19, decode } +const decodeNostrURI: typeof nostrNip19.decodeNostrURI = (value) => { + try { + return decode(value.startsWith("nostr:") ? value.substring(6) : value) + } catch { + return { type: "invalid", data: null } + } +} + +export const nip19: typeof nostrNip19 = { ...nostrNip19, decode, decodeNostrURI } diff --git a/src/noffer.ts b/src/noffer.ts index 8ec1e3d..0a25979 100644 --- a/src/noffer.ts +++ b/src/noffer.ts @@ -20,14 +20,26 @@ export type NofferData = { export const validateNofferData = (data: unknown): NofferData => { if (typeof data !== 'object' || data === null || Array.isArray(data)) throw new Error('data must be an object') - if (!('offer' in data) || typeof data.offer !== 'string') throw new Error('offer must be a string') - if ('amount_sats' in data && data.amount_sats !== undefined && typeof data.amount_sats !== 'number') throw new Error('amount_sats must be a number if present') - if ('zap' in data && data.zap !== undefined && typeof data.zap !== 'string') throw new Error('zap must be a string if present') - if ('payer_data' in data && data.payer_data !== undefined) { - if (typeof data.payer_data !== 'object' || data.payer_data === null || Array.isArray(data.payer_data)) { + const { offer, amount_sats, zap, payer_data, expires_in_seconds, description } = data as Record + if (typeof offer !== 'string') throw new Error('offer must be a string') + if (offer.length === 0) throw new Error('offer must not be empty') + const out: NofferData = { offer } + if (amount_sats !== undefined) { + if (typeof amount_sats !== 'number' || !Number.isSafeInteger(amount_sats) || amount_sats <= 0) { + throw new Error('amount_sats must be a positive safe integer if present') + } + out.amount_sats = amount_sats + } + if (zap !== undefined) { + if (typeof zap !== 'string') throw new Error('zap must be a string if present') + out.zap = zap + } + if (payer_data !== undefined) { + if (typeof payer_data !== 'object' || payer_data === null || Array.isArray(payer_data)) { throw new Error('payer_data must be an object if present') } - for (const [key, value] of Object.entries(data.payer_data)) { + const entries: [string, string | number][] = [] + for (const [key, value] of Object.entries(payer_data)) { if (value === undefined) continue if (key === 'quantity') { if (typeof value !== 'number' || !Number.isSafeInteger(value) || value <= 0) { @@ -36,11 +48,22 @@ export const validateNofferData = (data: unknown): NofferData => { } else if (typeof value !== 'string') { throw new Error(`payer_data.${key} must be a string`) } + entries.push([key, value]) } + out.payer_data = Object.fromEntries(entries) as NofferPayerData } - if ('expires_in_seconds' in data && data.expires_in_seconds !== undefined && typeof data.expires_in_seconds !== 'number') throw new Error('expires_in_seconds must be a number if present') - if ('description' in data && data.description !== undefined && typeof data.description !== 'string') throw new Error('description must be a string if present') - return data as NofferData + if (expires_in_seconds !== undefined) { + if (typeof expires_in_seconds !== 'number' || !Number.isSafeInteger(expires_in_seconds) || expires_in_seconds < 0) { + throw new Error('expires_in_seconds must be a non-negative safe integer if present') + } + out.expires_in_seconds = expires_in_seconds + } + if (description !== undefined) { + if (typeof description !== 'string') throw new Error('description must be a string if present') + if (description.length > 100) throw new Error('Description must be less than 100 characters') + out.description = description + } + return out } export type NofferSuccess = { bolt11: string } @@ -48,12 +71,9 @@ export type NofferError = { code: number, error: string, range?: { min: number, export type NofferResponse = NofferSuccess | NofferError export const SendNofferRequest = async (pool: AbstractSimplePool, privateKey: Uint8Array, relays: string[], toPubKey: string, data: NofferData, timeoutSeconds = 30, onReceipt?: (receipt: NofferReceipt) => void): Promise => { - validateNofferData(data) - if (data.description && data.description.length > 100) { - throw new Error('Description must be less than 100 characters') - } + const payload = validateNofferData(data) const publicKey = getPublicKey(privateKey) - const content = encrypt(JSON.stringify(data), getConversationKey(privateKey, toPubKey)) + const content = encrypt(JSON.stringify(payload), getConversationKey(privateKey, toPubKey)) const event = newNofferEvent(content, publicKey, toPubKey) return sendRequest(pool, { privateKey, publicKey }, relays, toPubKey, event, CLINK_OFFER_KIND, timeoutSeconds, onReceipt) } diff --git a/src/sender.ts b/src/sender.ts index 8e21622..0c123b0 100644 --- a/src/sender.ts +++ b/src/sender.ts @@ -1,5 +1,6 @@ import { nip44, finalizeEvent, verifyEvent, UnsignedEvent, type Event } from "nostr-tools" import { AbstractSimplePool, SubCloser } from "nostr-tools/lib/types/pool" +import { CLINK_OFFER_KIND } from "./constants.js" import { isNofferReceipt } from "./receipt.js" const { getConversationKey, decrypt } = nip44 @@ -64,6 +65,9 @@ const RECEIPT_RESUBSCRIBE_MS = 4000 const RELISTEN_MS = 500 export const sendRequest = async (pool: AbstractSimplePool, pair: Pair, relays: string[], toPub: string, e: UnsignedEvent, kindExpected: number, timeoutSeconds?: number, moreCb?: (data: any) => void): Promise => { + if (relays.length === 0) { + throw new Error('no relays provided') + } const signed = finalizeEvent(e, pair.privateKey) // Wire events use lowercase hex; callers sometimes pass mixed case. const expectedPub = toPub.toLowerCase() @@ -86,15 +90,15 @@ export const sendRequest = async (pool: AbstractSimplePool, pair: Pair, relay const filter = newFilter(pair.publicKey, signed.id, kindExpected) const stopTimers = () => { - if (timer) { + if (timer !== null) { clearTimeout(timer) timer = null } - if (relistenTimer) { + if (relistenTimer !== null) { clearTimeout(relistenTimer) relistenTimer = null } - if (resubTimer) { + if (resubTimer !== null) { clearInterval(resubTimer) resubTimer = null } @@ -119,7 +123,7 @@ export const sendRequest = async (pool: AbstractSimplePool, pair: Pair, relay } const waitForReceipt = () => { - if (resubTimer) { + if (finished || resubTimer !== null) { return } resubTimer = setInterval(listen, RECEIPT_RESUBSCRIBE_MS) @@ -129,11 +133,18 @@ export const sendRequest = async (pool: AbstractSimplePool, pair: Pair, relay if (finished) { return } + if (relistenTimer !== null) { + clearTimeout(relistenTimer) + relistenTimer = null + } const gen = ++listenGen log(`[ClinkSDK] Setting up subscription with filter:`, JSON.stringify(filter, null, 2)) closer.close() - closer = pool.subscribe(relays, filter, { + const subscription = pool.subscribe(relays, filter, { onevent: async (event) => { + if (finished || gen !== listenGen) { + return + } log(`[ClinkSDK] Received response event: kind=${event.kind}, eventId=${event.id}, from=${event.pubkey}`) if (!isClinkResponse(event, expect)) { log(`[ClinkSDK] Ignoring event that is not a valid CLINK response for eventId=${signed.id}`) @@ -144,26 +155,29 @@ export const sendRequest = async (pool: AbstractSimplePool, pair: Pair, relay const parsed = JSON.parse(content) if (!settled) { settled = true - if (timer) { + if (timer !== null) { clearTimeout(timer) timer = null } log(`[ClinkSDK] Response resolved successfully for eventId=${signed.id}`) res(parsed) - if (!moreCb) { + if (!moreCb || kindExpected !== CLINK_OFFER_KIND || + parsed === null || typeof parsed !== 'object' || + typeof parsed.bolt11 !== 'string' || parsed.bolt11.length === 0 || + 'code' in parsed || 'error' in parsed) { cleanup() return } waitForReceipt() } else if (moreCb && isNofferReceipt(parsed)) { log(`[ClinkSDK] Receipt received for eventId=${signed.id}, calling moreCb`) - moreCb(parsed) cleanup() + moreCb(parsed) } else { log(`[ClinkSDK] Ignoring extra non-receipt event for eventId=${signed.id}`) } } catch (err) { - logError(`[ClinkSDK] Failed to decrypt/parse response for eventId=${signed.id}:`, err) + logError(`[ClinkSDK] Failed to handle response for eventId=${signed.id}:`, err) if (!settled) { fail(err) } @@ -173,13 +187,19 @@ export const sendRequest = async (pool: AbstractSimplePool, pair: Pair, relay log(`[ClinkSDK] End of stored events received for eventId=${signed.id}`) }, onclose: () => { - if (finished || gen !== listenGen) { + if (finished || gen !== listenGen || relistenTimer !== null) { return } log(`[ClinkSDK] Subscription closed, listening again for eventId=${signed.id}`) relistenTimer = setTimeout(listen, RELISTEN_MS) }, }) + // subscribe may invoke callbacks before returning its closer. + if (finished || gen !== listenGen) { + subscription.close() + } else { + closer = subscription + } } if (timeoutSeconds) { @@ -191,14 +211,27 @@ export const sendRequest = async (pool: AbstractSimplePool, pair: Pair, relay try { listen() - Promise.all(pool.publish(relays, signed)).then(() => { - log(`[ClinkSDK] Request published to ${relays.length} relays, waiting for response...`) - }).catch((error) => { - logError(`[ClinkSDK] Failed to publish to relays:`, error) - fail(error) - }) + if (finished) { + return + } + const attempts = pool.publish(relays, signed) + if (attempts.length === 0) { + throw new Error('no publish attempts returned') + } + let remaining = attempts.length + for (const attempt of attempts) { + attempt.then(() => { + log(`[ClinkSDK] Request accepted by a relay, waiting for response...`) + }, (error) => { + logError(`[ClinkSDK] Failed to publish to a relay:`, error) + // A successful attempt leaves remaining above zero. + if (--remaining === 0) { + fail(error) + } + }) + } } catch (error) { - logError(`[ClinkSDK] Failed to establish subscription:`, error) + logError(`[ClinkSDK] Failed to send request:`, error) fail(error) } }) diff --git a/test/unit/bech32.test.mjs b/test/unit/bech32.test.mjs index 657387f..9df33bf 100644 --- a/test/unit/bech32.test.mjs +++ b/test/unit/bech32.test.mjs @@ -33,6 +33,9 @@ const encodeNofferTlv = (fields) => { tlv[0] = [fields[0]] tlv[1] = [utf8.encode(fields[1])] tlv[2] = [utf8.encode(fields[2])] + for (const tag of [3, 4, 5]) { + if (fields[tag] !== undefined) tlv[tag] = [fields[tag]] + } const entries = [] for (const [tag, values] of Object.entries(tlv).reverse()) { for (const value of values) { @@ -139,6 +142,78 @@ describe('bech32 round-trip', () => { }) }) +describe('noffer prices', () => { + const pointer = { ...fixtures.noffer.decoded, priceType: OfferPriceType.Fixed } + const fields = { + 0: hexToBytes32(pointer.pubkey), + 1: pointer.relay, + 2: pointer.offer, + } + + for (const [price, hex] of [ + [0, '00000000'], + [1, '00000001'], + [2 ** 32 - 1, 'ffffffff'], + [2 ** 32, '0100000000'], + [2 ** 32 + 1, '0100000001'], + [Number.MAX_SAFE_INTEGER, '1fffffffffffff'], + ]) { + it(`losslessly round-trips price ${price} with compatible big-endian bytes`, () => { + const encoded = nofferEncode({ ...pointer, price }) + assert.equal(encoded, encodeNofferTlv({ + ...fields, 3: new Uint8Array([OfferPriceType.Fixed]), 4: hexToBytes(hex), + })) + assert.equal(decodeBech32(encoded).data.price, price) + }) + } + + it('keeps TLV 4 optional without changing the price type', () => { + const decoded = decodeBech32(nofferEncode({ ...pointer, price: undefined })).data + assert.equal(decoded.price, undefined) + assert.equal(decoded.priceType, OfferPriceType.Fixed) + }) + + it('rejects invalid numeric prices instead of truncating or omitting them', () => { + for (const price of [NaN, Infinity, -Infinity, -1, -0.5, 0.5, Number.MAX_SAFE_INTEGER + 1, 2 ** 64]) { + assert.throws(() => nofferEncode({ ...pointer, price }), /nonnegative safe integer/) + } + }) + + it('rejects empty and unsafe external price TLVs without rounding', () => { + for (const hex of ['', '20000000000000', '20000000000001', 'ffffffffffffff', 'ff'.repeat(255)]) { + // 0x20000000000001 is the external seven-byte integer 9007199254740993. + assert.throws(() => decodeBech32(encodeNofferTlv({ ...fields, 4: hexToBytes(hex) })), /price/) + } + }) + + it('accepts exact external integer widths and infers fixed pricing even for zero', () => { + for (const [hex, price] of [['00', 0], ['01', 1], ['001fffffffffffff', Number.MAX_SAFE_INTEGER]]) { + const decoded = decodeBech32(encodeNofferTlv({ ...fields, 4: hexToBytes(hex) })).data + assert.equal(decoded.price, price) + assert.equal(decoded.priceType, OfferPriceType.Fixed) + } + }) + + it('checks currency and price presence, including zero and empty currency', () => { + for (const currency of ['USD', '']) { + const variable = { ...pointer, priceType: OfferPriceType.Variable, currency } + assert.throws(() => nofferEncode({ ...variable, price: 0 }), /currency excludes price/) + assert.throws(() => nofferEncode({ ...variable, price: undefined, priceType: OfferPriceType.Fixed }), /currency requires variable/) + const decoded = decodeBech32(nofferEncode({ ...variable, price: undefined })).data + assert.equal(decoded.currency, currency) + assert.equal(decoded.price, undefined) + assert.equal(decoded.priceType, OfferPriceType.Variable) + assert.throws(() => decodeBech32(encodeNofferTlv({ + ...fields, 3: new Uint8Array([OfferPriceType.Variable]), 4: hexToBytes('00000000'), 5: utf8.encode(currency), + })), /currency excludes price/) + assert.throws(() => decodeBech32(encodeNofferTlv({ + ...fields, 3: new Uint8Array([OfferPriceType.Fixed]), 5: utf8.encode(currency), + })), /currency requires variable/) + assert.equal(decodeBech32(encodeNofferTlv({ ...fields, 5: utf8.encode(currency) })).data.priceType, OfferPriceType.Variable) + } + }) +}) + describe('TLV encoding limits', () => { const encoders = [ ['noffer', nofferEncode, fixtures.noffer.decoded, 'offer'], @@ -201,14 +276,38 @@ const nprofileWithK = () => { } describe('nip19 decode', () => { + it('accepts ASCII lower- and uppercase codes with the existing URI prefix handling', () => { + const profile = nprofileWithK() + for (const encoded of [profile, nip19.npubEncode('ab'.repeat(32)), nip19.nsecEncode(new Uint8Array(32).fill(1))]) { + const expected = nip19.decode(encoded) + for (const code of [encoded, encoded.toUpperCase()]) { + assert.deepEqual(nip19.decode(code), expected) + assert.deepEqual(nip19.decodeNostrURI(code), expected) + assert.deepEqual(nip19.decodeNostrURI(`nostr:${code}`), expected) + } + assert.deepEqual(nip19.decodeNostrURI(`NOSTR:${encoded}`), { type: 'invalid', data: null }) + } + }) + it('rejects non-ASCII look-alike characters', () => { const encoded = nprofileWithK() assert.equal(nip19.decode(encoded).type, 'nprofile') assert.equal(nip19.decode(encoded.toUpperCase()).type, 'nprofile') assert.throws(() => nip19.decode(withKelvinSign(encoded))) + assert.deepEqual(nip19.decodeNostrURI(withKelvinSign(encoded)), { type: 'invalid', data: null }) + assert.deepEqual(nip19.decodeNostrURI(`nostr:${withKelvinSign(encoded)}`), { type: 'invalid', data: null }) assert.throws(() => ClinkSDK.fromNprofile(withKelvinSign(encoded), new Uint8Array(32))) }) + it('preserves invalid URI results and rejects invalid direct decode values', () => { + const encoded = nprofileWithK() + for (const value of ['', 'nostr:', 'not-bech32', encoded.slice(0, -1), `N${encoded.slice(1)}`, ` ${encoded}`, `${encoded}\n`, null, undefined, 42, {}]) { + assert.throws(() => nip19.decode(value)) + assert.deepEqual(nip19.decodeNostrURI(value), { type: 'invalid', data: null }) + assert.deepEqual(nip19.decodeNostrURI(`nostr:${value}`), { type: 'invalid', data: null }) + } + }) + it('rejects the same trick in noffer decode', () => { const encoded = withKelvinSign(fixtures.noffer.encoded) ?? withKelvinSign(nmanageEncode(fixtures.nmanage.decoded)) assert.ok(encoded) diff --git a/test/unit/sender.test.mjs b/test/unit/sender.test.mjs index cfbd957..434d1b2 100644 --- a/test/unit/sender.test.mjs +++ b/test/unit/sender.test.mjs @@ -40,12 +40,13 @@ function createMockPool({ onSubscribe, onPublish, replyFactory }) { subscribeCalled = true closed = false order.push('subscribe') - onSubscribe?.(relays, filter, opts) onevent = opts.onevent + onSubscribe?.(relays, filter, opts) return { close: () => { closed = true order.push('close') + opts.onclose?.([]) }, } }, @@ -53,12 +54,12 @@ function createMockPool({ onSubscribe, onPublish, replyFactory }) { publishCalled = true order.push('publish') assert.equal(subscribeCalled, true, 'publish must happen after subscribe') - onPublish?.(relays, event) + const attempts = onPublish?.(relays, event) const replies = replyFactory?.(event, onevent) ?? [] for (const reply of replies) { queueMicrotask(() => onevent(reply)) } - return [Promise.resolve('ok')] + return attempts ?? [Promise.resolve('ok')] }, } } @@ -71,11 +72,11 @@ const requestEvent = (clientPub, serverPub) => ({ pubkey: clientPub, }) -const sendOffer = (pool, clientPriv, clientPub, serverPub, timeoutSeconds = 5, moreCb) => +const sendOffer = (pool, clientPriv, clientPub, serverPub, timeoutSeconds = 5, moreCb, relays = ['wss://relay.example.com']) => sendRequest( pool, { privateKey: clientPriv, publicKey: clientPub }, - ['wss://relay.example.com'], + relays, serverPub, requestEvent(clientPub, serverPub), 21001, @@ -84,7 +85,132 @@ const sendOffer = (pool, clientPriv, clientPub, serverPub, timeoutSeconds = 5, m ) describe('sender lifecycle', () => { - it('preserves code 6 payer-data discovery and sends numeric quantity on explicit retry', async () => { + for (const payload of [ + { code: 1, error: 'Offer unavailable' }, + { code: 6, error: 'Missing payer data', payer_data: ['name', 'quantity'] }, + { code: 6, bolt11: 'lnbc1dummy' }, + { error: 'Invalid invoice', bolt11: 'lnbc1dummy' }, + { bolt11: '' }, + { bolt11: 123 }, + { res: 'ok' }, + {}, [], null, 'invalid', + ]) { + it(`closes without receipt polling for primary ${JSON.stringify(payload)}`, async (t) => { + t.mock.timers.enable({ apis: ['setTimeout', 'setInterval'] }) + const intervals = t.mock.method(globalThis, 'setInterval') + const timeouts = t.mock.method(globalThis, 'setTimeout') + const clientPriv = generateSecretKey() + const clientPub = getPublicKey(clientPriv) + const serverPriv = generateSecretKey() + const serverPub = getPublicKey(serverPriv) + const receipt = t.mock.fn() + let latest + let requestId + const pool = createMockPool({ + onSubscribe: (_r, _f, opts) => { + latest = opts + opts.onclose([]) + }, + replyFactory: (request) => { + requestId = request.id + return [signedClinkReply(serverPriv, clientPub, request.id, payload, 21001)] + }, + }) + + assert.deepEqual(await sendOffer(pool, clientPriv, clientPub, serverPub, 5, receipt), payload) + assert.equal(pool.wasClosed(), true) + assert.equal(intervals.mock.callCount(), 0) + const timeoutCount = timeouts.mock.callCount() + latest.onclose([]) + await latest.onevent(signedClinkReply(serverPriv, clientPub, requestId, { res: 'ok' }, 21001)) + t.mock.timers.tick(12000) + assert.equal(pool.subscribeCount(), 1) + assert.equal(timeouts.mock.callCount(), timeoutCount) + assert.equal(receipt.mock.callCount(), 0) + }) + } + + it('does not wait for receipts for an invoice-shaped response of another kind', async (t) => { + t.mock.timers.enable({ apis: ['setTimeout', 'setInterval'] }) + const intervals = t.mock.method(globalThis, 'setInterval') + const clientPriv = generateSecretKey() + const clientPub = getPublicKey(clientPriv) + const serverPriv = generateSecretKey() + const serverPub = getPublicKey(serverPriv) + const pool = createMockPool({ + replyFactory: (request) => [ + signedClinkReply(serverPriv, clientPub, request.id, { bolt11: 'lnbc1dummy' }, 21002), + ], + }) + + assert.deepEqual(await sendRequest(pool, { privateKey: clientPriv, publicKey: clientPub }, + ['wss://relay.example.com'], serverPub, requestEvent(clientPub, serverPub), 21002, 5, t.mock.fn()), + { bolt11: 'lnbc1dummy' }) + assert.equal(pool.wasClosed(), true) + assert.equal(intervals.mock.callCount(), 0) + t.mock.timers.tick(12000) + assert.equal(pool.subscribeCount(), 1) + }) + + it('closes a subscription returned after synchronous response callbacks, even if moreCb throws', async (t) => { + t.mock.timers.enable({ apis: ['setTimeout', 'setInterval'] }) + const clientPriv = generateSecretKey() + const clientPub = getPublicKey(clientPriv) + const serverPriv = generateSecretKey() + const serverPub = getPublicKey(serverPriv) + const receipt = t.mock.fn(() => { throw new Error('callback failed') }) + const pool = createMockPool({ + onSubscribe: (_r, filter, opts) => { + opts.onevent(signedClinkReply(serverPriv, clientPub, filter['#e'][0], { bolt11: 'lnbc1dummy' }, 21001)) + opts.onevent(signedClinkReply(serverPriv, clientPub, filter['#e'][0], { res: 'ok' }, 21001)) + opts.onevent(signedClinkReply(serverPriv, clientPub, filter['#e'][0], { res: 'ok' }, 21001)) + }, + }) + + assert.deepEqual(await sendOffer(pool, clientPriv, clientPub, serverPub, 5, receipt), { bolt11: 'lnbc1dummy' }) + assert.equal(receipt.mock.callCount(), 1) + assert.equal(pool.wasClosed(), true) + t.mock.timers.tick(12000) + assert.equal(pool.subscribeCount(), 1) + }) + + it('periodically resubscribes, ignores stale callbacks, and cleans up after receipt callback errors', async (t) => { + t.mock.timers.enable({ apis: ['setTimeout', 'setInterval'] }) + const clientPriv = generateSecretKey() + const clientPub = getPublicKey(clientPriv) + const serverPriv = generateSecretKey() + const serverPub = getPublicKey(serverPriv) + const subscriptions = [] + let requestId + const receipt = t.mock.fn(() => { throw new Error('callback failed') }) + const pool = createMockPool({ + onSubscribe: (_r, _f, opts) => subscriptions.push(opts), + replyFactory: (request) => { + requestId = request.id + return [signedClinkReply(serverPriv, clientPub, request.id, { bolt11: 'lnbc1dummy' }, 21001)] + }, + }) + + await sendOffer(pool, clientPriv, clientPub, serverPub, 5, receipt) + t.mock.timers.tick(4000) + assert.equal(pool.subscribeCount(), 2) + const reply = signedClinkReply(serverPriv, clientPub, requestId, { res: 'ok' }, 21001) + subscriptions[0].onclose([]) + await subscriptions[0].onevent(reply) + assert.equal(receipt.mock.callCount(), 0) + t.mock.timers.tick(500) + assert.equal(pool.subscribeCount(), 2) + await subscriptions[1].onevent(reply) + assert.equal(receipt.mock.callCount(), 1) + assert.equal(pool.wasClosed(), true) + await subscriptions[1].onevent(reply) + t.mock.timers.tick(12000) + assert.equal(receipt.mock.callCount(), 1) + assert.equal(pool.subscribeCount(), 2) + }) + + it('preserves code 6 payer-data discovery and sends numeric quantity on explicit retry', async (t) => { + t.mock.timers.enable({ apis: ['setTimeout', 'setInterval'] }) const clientPriv = generateSecretKey() const clientPub = getPublicKey(clientPriv) const serverPriv = generateSecretKey() @@ -106,10 +232,14 @@ describe('sender lifecycle', () => { zap: undefined, expires_in_seconds: undefined, payer_data: undefined, } - const response = await SendNofferRequest(pool, clientPriv, ['wss://relay.example.com'], serverPub, request, 5) + const receipt = t.mock.fn() + const response = await SendNofferRequest(pool, clientPriv, ['wss://relay.example.com'], serverPub, request, 5, receipt) assert.deepEqual(response, discovery) assert.deepEqual(payloads, [{ offer: 'o', amount_sats: 21, description: request.description }]) assert.equal(pool.wasClosed(), true) + t.mock.timers.tick(12000) + assert.equal(pool.subscribeCount(), 1) + assert.equal(receipt.mock.callCount(), 0) const retry = await SendNofferRequest(pool, clientPriv, ['wss://relay.example.com'], serverPub, { ...request, payer_data: { name: 'Alice', quantity: 2, email: undefined }, @@ -173,7 +303,8 @@ describe('sender lifecycle', () => { assert.equal(pool.wasClosed(), true) }) - it('resubscribes after close and still delivers the receipt', async () => { + it('resubscribes after close and still delivers the receipt', async (t) => { + t.mock.timers.enable({ apis: ['setTimeout', 'setInterval'] }) const clientPriv = generateSecretKey() const clientPub = getPublicKey(clientPriv) const serverPriv = generateSecretKey() @@ -198,7 +329,7 @@ describe('sender lifecycle', () => { assert.equal(pool.subscribeCount(), 1) latest.onclose(['closed']) - await new Promise(resolve => setTimeout(resolve, 600)) + t.mock.timers.tick(500) assert.ok(pool.subscribeCount() >= 2) await latest.onevent(signedClinkReply(serverPriv, clientPub, requestId, { res: 'ok' }, 21001)) @@ -207,7 +338,8 @@ describe('sender lifecycle', () => { assert.equal(pool.wasClosed(), true) }) - it('ignores a replayed invoice after resubscribe and still delivers the receipt', async () => { + it('ignores a replayed invoice after resubscribe and still delivers the receipt', async (t) => { + t.mock.timers.enable({ apis: ['setTimeout', 'setInterval'] }) const clientPriv = generateSecretKey() const clientPub = getPublicKey(clientPriv) const serverPriv = generateSecretKey() @@ -231,7 +363,7 @@ describe('sender lifecycle', () => { }) latest.onclose(['closed']) - await new Promise(resolve => setTimeout(resolve, 600)) + t.mock.timers.tick(500) await latest.onevent(signedClinkReply(serverPriv, clientPub, requestId, { bolt11: 'lnbc1dummy' }, 21001)) assert.equal(receipt, null) @@ -511,6 +643,131 @@ describe('sender lifecycle', () => { }) }) +describe('relay publication', () => { + const clientPriv = generateSecretKey() + const clientPub = getPublicKey(clientPriv) + const serverPriv = generateSecretKey() + const serverPub = getPublicKey(serverPriv) + const relays = ['wss://failed.example.com', 'wss://working.example.com'] + + for (const failedIndex of [0, 1]) { + it(`waits for a delayed reply despite relay ${failedIndex} rejecting publication`, async (t) => { + t.mock.timers.enable({ apis: ['setTimeout', 'setInterval'] }) + const pool = createMockPool({ + onPublish: (urls) => { + assert.deepEqual(urls, relays) + return urls.map((_, index) => index === failedIndex + ? Promise.reject(new Error('relay refused')) : Promise.resolve('ok')) + }, + replyFactory: (request, onevent) => { + setTimeout(() => onevent(signedClinkReply(serverPriv, clientPub, request.id, + { bolt11: 'lnbc1dummy' }, 21001)), 50) + }, + }) + const response = sendOffer(pool, clientPriv, clientPub, serverPub, 5, undefined, relays) + const checked = assert.doesNotReject(async () => { + assert.deepEqual(await response, { bolt11: 'lnbc1dummy' }) + }) + await Promise.resolve() + assert.equal(pool.wasClosed(), false) + t.mock.timers.tick(50) + await checked + assert.equal(pool.wasClosed(), true) + t.mock.timers.tick(12000) + assert.equal(pool.subscribeCount(), 1) + }) + } + + it('rejects and cleans up only after every publish attempt fails', async (t) => { + t.mock.timers.enable({ apis: ['setTimeout', 'setInterval'] }) + const lastError = new Error('last relay refused') + let latest + const receipt = t.mock.fn() + const pool = createMockPool({ + onSubscribe: (_r, _f, opts) => { latest = opts }, + onPublish: () => [ + Promise.reject(new Error('first relay refused')), + new Promise((_res, rej) => setTimeout(() => rej(lastError), 50)), + ], + }) + const rejected = assert.rejects( + sendOffer(pool, clientPriv, clientPub, serverPub, 5, receipt, relays), + (error) => error === lastError, + ) + await Promise.resolve() + assert.equal(pool.wasClosed(), false) + t.mock.timers.tick(50) + await rejected + assert.equal(pool.wasClosed(), true) + latest.onclose([]) + t.mock.timers.tick(12000) + assert.equal(pool.subscribeCount(), 1) + assert.equal(receipt.mock.callCount(), 0) + }) + + it('preserves an accepted invoice and receipt waiting when all publish rejections arrive late', async (t) => { + t.mock.timers.enable({ apis: ['setTimeout', 'setInterval'] }) + let latest + let requestId + const receipt = t.mock.fn() + const pool = createMockPool({ + onSubscribe: (_r, _f, opts) => { latest = opts }, + onPublish: () => relays.map(() => new Promise((_res, rej) => { + setTimeout(() => rej(new Error('late rejection')), 50) + })), + replyFactory: (request) => { + requestId = request.id + return [signedClinkReply(serverPriv, clientPub, request.id, { bolt11: 'lnbc1dummy' }, 21001)] + }, + }) + + assert.deepEqual(await sendOffer(pool, clientPriv, clientPub, serverPub, 5, receipt, relays), + { bolt11: 'lnbc1dummy' }) + t.mock.timers.tick(50) + await Promise.resolve() + assert.equal(pool.wasClosed(), false) + t.mock.timers.tick(4000) + assert.equal(pool.subscribeCount(), 2) + await latest.onevent(signedClinkReply(serverPriv, clientPub, requestId, { res: 'ok' }, 21001)) + assert.equal(receipt.mock.callCount(), 1) + assert.equal(pool.wasClosed(), true) + t.mock.timers.tick(12000) + assert.equal(pool.subscribeCount(), 2) + }) + + for (const [name, onPublish, message] of [ + ['synchronous publish throws', () => { throw new Error('publish threw') }, /publish threw/], + ['empty publish results', () => [], /no publish attempts returned/], + ]) { + it(`rejects and cleans up on ${name}`, async (t) => { + t.mock.timers.enable({ apis: ['setTimeout', 'setInterval'] }) + let latest + const pool = createMockPool({ + onSubscribe: (_r, _f, opts) => { latest = opts }, + onPublish, + }) + + await assert.rejects(sendOffer(pool, clientPriv, clientPub, serverPub, 5, t.mock.fn(), relays), message) + assert.equal(pool.wasClosed(), true) + latest.onclose([]) + t.mock.timers.tick(12000) + assert.equal(pool.subscribeCount(), 1) + }) + } + + it('rejects empty relays without subscribing, publishing, or starting timers', async (t) => { + t.mock.timers.enable({ apis: ['setTimeout', 'setInterval'] }) + const timeouts = t.mock.method(globalThis, 'setTimeout') + const intervals = t.mock.method(globalThis, 'setInterval') + const pool = createMockPool({}) + + await assert.rejects(sendOffer(pool, clientPriv, clientPub, serverPub, 5, t.mock.fn(), []), /no relays provided/) + assert.deepEqual(pool.order, []) + assert.equal(timeouts.mock.callCount(), 0) + assert.equal(intervals.mock.callCount(), 0) + }) +}) + describe('debug logging', () => { const clientPriv = generateSecretKey() const clientPub = getPublicKey(clientPriv) diff --git a/test/unit/validators.test.mjs b/test/unit/validators.test.mjs index 1169af7..5bac83f 100644 --- a/test/unit/validators.test.mjs +++ b/test/unit/validators.test.mjs @@ -15,10 +15,13 @@ import { SendNdebitRequest, SendNofferRequest, generateSecretKey, + getPublicKey, + nip44, newNdebitFullAccessRequest, newNdebitPaymentRequest, newNdebitBudgetRequest, } from '../../build/index.js' +import { signedClinkReply } from './signed-reply.mjs' describe('validators', () => { it('validates k1', () => { @@ -107,7 +110,7 @@ describe('validators', () => { it('accepts numeric noffer quantity and string payer data', () => { for (const quantity of [1, 2, Number.MAX_SAFE_INTEGER]) { const data = { offer: 'o', payer_data: { quantity, name: 'Alice', Quantity: 'custom', quantity_hint: '2' } } - assert.equal(validateNofferData(data), data) + assert.deepEqual(validateNofferData(data), data) } assert.doesNotThrow(() => validateNofferData({ offer: 'o', payer_data: {} })) }) @@ -146,10 +149,10 @@ describe('validators', () => { offer: 'o', amount_sats: undefined, zap: undefined, payer_data: undefined, expires_in_seconds: undefined, description: undefined, } - assert.equal(validateNofferData(data), data) + assert.deepEqual(validateNofferData(data), { offer: 'o' }) assert.equal(JSON.stringify(data), '{"offer":"o"}') const withPayerData = { ...data, payer_data: { quantity: undefined, name: undefined } } - assert.equal(validateNofferData(withPayerData), withPayerData) + assert.deepEqual(validateNofferData(withPayerData), { offer: 'o', payer_data: {} }) assert.equal(JSON.stringify(withPayerData), '{"offer":"o","payer_data":{}}') }) @@ -162,9 +165,9 @@ describe('validators', () => { for (const [data, error] of [ [{}, /offer must be a string/], [{ offer: 1 }, /offer must be a string/], - [{ offer: 'o', amount_sats: '21' }, /amount_sats must be a number/], + [{ offer: 'o', amount_sats: '21' }, /amount_sats must be a positive safe integer/], [{ offer: 'o', zap: null }, /zap must be a string/], - [{ offer: 'o', expires_in_seconds: '60' }, /expires_in_seconds must be a number/], + [{ offer: 'o', expires_in_seconds: '60' }, /expires_in_seconds must be a non-negative safe integer/], [{ offer: 'o', description: 1 }, /description must be a string/], [{ offer: 'o', description: 'x'.repeat(101) }, /Description must be less than 100 characters/], [{ offer: 'o', payer_data: [] }, /payer_data must be an object/], @@ -178,6 +181,23 @@ describe('validators', () => { assert.equal(contacted, false) }) + it('requires safe integer offer amounts and expiries before sending', async () => { + for (const value of [NaN, Infinity, -Infinity, -1, 1.5, Number.MAX_SAFE_INTEGER + 1, null, '21']) { + for (const field of ['amount_sats', 'expires_in_seconds']) { + const data = { offer: 'o', [field]: value } + assert.throws(() => validateNofferData(data), /safe integer/) + await assert.rejects(SendNofferRequest({}, new Uint8Array(), [], 'invalid', data), /safe integer/) + } + } + assert.throws(() => validateNofferData({ offer: 'o', amount_sats: 0 }), /positive safe integer/) + assert.deepEqual(validateNofferData({ offer: 'o', amount_sats: Number.MAX_SAFE_INTEGER, expires_in_seconds: 0 }), { + offer: 'o', amount_sats: Number.MAX_SAFE_INTEGER, expires_in_seconds: 0, + }) + assert.doesNotThrow(() => validateNofferData({ offer: 'o', expires_in_seconds: Number.MAX_SAFE_INTEGER })) + assert.throws(() => validateNofferData({ offer: '' }), /offer must not be empty/) + assert.throws(() => validateNofferData({ offer: 'o', description: 'x'.repeat(101) }), /Description/) + }) + it('validates nmanage requests by action', () => { const created = newCreateRequest('coffee', { price_sats: 21 }, 'ptr') assert.deepEqual(validateNmanageRequest(created), created) @@ -202,3 +222,112 @@ describe('validators', () => { ) }) }) + +describe('request serialization', () => { + const captureRequest = async (send, data) => { + const clientKey = generateSecretKey() + const serverKey = generateSecretKey() + const clientPub = getPublicKey(clientKey) + const serverPub = getPublicKey(serverKey) + let payload + let deliver + const pool = { + subscribe(_relays, _filter, handlers) { + deliver = handlers.onevent + return { close() {} } + }, + publish(_relays, event) { + payload = JSON.parse(nip44.decrypt(event.content, nip44.getConversationKey(serverKey, clientPub))) + queueMicrotask(() => deliver(signedClinkReply(serverKey, clientPub, event.id, { res: 'ok' }, event.kind))) + return [Promise.resolve('ok')] + }, + } + await send(pool, clientKey, ['wss://relay.example'], serverPub, data, 1) + return payload + } + + it('detaches validated offer and debit data from later caller mutations', () => { + const offer = { offer: 'o', payer_data: { quantity: 2, name: 'Alice' } } + const offerPayload = validateNofferData(offer) + offer.offer = 'changed' + offer.payer_data.quantity = 100 + assert.deepEqual(offerPayload, { offer: 'o', payer_data: { quantity: 2, name: 'Alice' } }) + const debit = { amount_sats: 21, frequency: { number: 1, unit: 'day' } } + const debitPayload = validateNdebitData(debit) + debit.frequency.number = -1 + debit.frequency.unit = 'year' + assert.deepEqual(debitPayload, { amount_sats: 21, frequency: { number: 1, unit: 'day' } }) + }) + + it('does not invoke top-level or inherited payer-data serializers', async () => { + let serializations = 0 + const payer_data = Object.assign(Object.create({ + toJSON() { serializations++; return { quantity: '2', name: 42 } }, + }), { quantity: 2, name: 'Alice' }) + const data = { + offer: 'o', amount_sats: 21, payer_data, + toJSON() { serializations++; return { offer: 'changed', amount_sats: 1, payer_data: null } }, + } + assert.deepEqual(await captureRequest(SendNofferRequest, data), { + offer: 'o', amount_sats: 21, payer_data: { quantity: 2, name: 'Alice' }, + }) + assert.equal(serializations, 0) + }) + + it('does not invoke debit frequency serializers or drop recurring budgets', async () => { + for (const replacement of [{ number: -1, unit: 'year' }, undefined]) { + let serializations = 0 + const frequency = Object.assign(Object.create({ toJSON() { serializations++; return replacement } }), { number: 1, unit: 'day' }) + const data = { pointer: 'p', amount_sats: 21, frequency, toJSON() { throw new Error('must not serialize caller') } } + assert.deepEqual(await captureRequest(SendNdebitRequest, data), { + pointer: 'p', amount_sats: 21, frequency: { number: 1, unit: 'day' }, + }) + assert.equal(serializations, 0) + } + }) + + it('reads offer scalars and payer-data getters only once before signing', async () => { + const reads = { offer: 0, amount: 0, payerData: 0, quantity: 0, expiry: 0, description: 0 } + const data = { + get offer() { return ++reads.offer === 1 ? 'o' : 'changed' }, + get amount_sats() { return ++reads.amount === 1 ? 21 : -1 }, + get payer_data() { + reads.payerData++ + return { get quantity() { return ++reads.quantity === 1 ? 2 : 'bad' } } + }, + get expires_in_seconds() { return ++reads.expiry === 1 ? 60 : NaN }, + get description() { return ++reads.description === 1 ? 'memo' : 'x'.repeat(101) }, + } + assert.deepEqual(await captureRequest(SendNofferRequest, data), { + offer: 'o', amount_sats: 21, payer_data: { quantity: 2 }, expires_in_seconds: 60, description: 'memo', + }) + assert.deepEqual(Object.values(reads), [1, 1, 1, 1, 1, 1]) + }) + + it('reads debit scalars and nested frequency getters only once before signing', async () => { + const reads = { pointer: 0, amount: 0, frequency: 0, number: 0, unit: 0 } + const data = { + get pointer() { return ++reads.pointer === 1 ? 'p' : 'changed' }, + get amount_sats() { return ++reads.amount === 1 ? 21 : -1 }, + get frequency() { + reads.frequency++ + return { + get number() { return ++reads.number === 1 ? 1 : -1 }, + get unit() { return ++reads.unit === 1 ? 'day' : 'year' }, + } + }, + } + assert.deepEqual(await captureRequest(SendNdebitRequest, data), { pointer: 'p', amount_sats: 21, frequency: { number: 1, unit: 'day' } }) + assert.deepEqual(Object.values(reads), [1, 1, 1, 1, 1]) + }) + + it('materializes inherited/non-enumerable fields and treats payer data as a map, not a serialized value', async () => { + const inherited = Object.create({ offer: 'inherited' }) + assert.deepEqual(await captureRequest(SendNofferRequest, inherited), { offer: 'inherited' }) + const nonEnumerable = Object.defineProperty({}, 'offer', { value: 'hidden' }) + assert.deepEqual(await captureRequest(SendNofferRequest, nonEnumerable), { offer: 'hidden' }) + assert.deepEqual(await captureRequest(SendNofferRequest, { offer: 'o', payer_data: new Date(0) }), { offer: 'o', payer_data: {} }) + const payer_data = JSON.parse('{"quantity":2,"__proto__":"opaque","constructor":"opaque"}') + assert.deepEqual(await captureRequest(SendNofferRequest, { offer: 'o', payer_data }), { offer: 'o', payer_data }) + }) +}) From 33adb19e368c20d566e6f5f1e771b887bca3d76e Mon Sep 17 00:00:00 2001 From: shocknet-justin Date: Mon, 9 Nov 2026 00:00:35 -0500 Subject: [PATCH 14/14] Cancel SDK requests on Stop and validate pointer public keys --- README.md | 7 +- src/index.ts | 19 ++- src/nbeacon.ts | 70 ++++++--- src/ndebit.ts | 5 +- src/nenroll.ts | 11 +- src/nip19Extension.ts | 12 +- src/nmanage.ts | 5 +- src/noffer.ts | 5 +- src/sender.ts | 33 +++- test-vectors/interop.json | 26 +++- test/unit/bech32.test.mjs | 38 ++++- test/unit/stop.test.mjs | 307 ++++++++++++++++++++++++++++++++++++++ 12 files changed, 487 insertions(+), 51 deletions(-) create mode 100644 test/unit/stop.test.mjs diff --git a/README.md b/README.md index 90d8dc3..04a6531 100644 --- a/README.md +++ b/README.md @@ -153,6 +153,8 @@ Receipt callbacks keep listening only after an invoice response. Discovery and o Each TLV value is limited to 255 bytes, measured after UTF-8 encoding for strings. Oversized offer IDs, pointers, relay URLs, and currency values are rejected before encoding. +All pointer encoders require a public key representing exactly 32 raw bytes (64 hexadecimal characters). Compressed 33-byte keys, truncated keys, and other lengths are rejected before a pointer is produced. + Encoded offer prices support integers from `0` through `Number.MAX_SAFE_INTEGER`. Existing nonzero 32-bit prices retain their four-byte encoding; larger prices use lossless wider big-endian values. An explicit zero price is encoded as zero rather than omitted. An absent price remains optional, and currency cannot be combined with any supplied price, including zero. Decoding rejects empty or unsafe price values instead of returning a rounded number. Both `nip19.decode` and `nip19.decodeNostrURI` enforce printable ASCII. The URI helper retains its `{ type: 'invalid', data: null }` result for invalid inputs. @@ -309,7 +311,10 @@ ClinkSDK.fromNprofile(nprofile: string, privateKey: Uint8Array, opts?: { default - `Nenroll(opts?: { difficulty?: number }, timeoutSeconds?: number)` - Sends a kind `21004` Enroll request (`{}`). Mines NIP-13 when `difficulty > 0`, up to `MAX_ENROLL_POW_BITS` (24). If `difficulty` is omitted, uses a fresh beacon’s `enroll_difficulty` when present and in range, otherwise probes and remine once on GFY `5`. - `Stop()` - - Closes relay connections on the internal pool. Call when finished so the process can exit cleanly. + - Cancels this instance's active requests, receipt polling, and relisten timers before closing pool connections. Pending promises reject with `AbortError`; already-resolved invoices remain resolved, but their receipt listeners stop. + - Shutdown is terminal and repeated calls are harmless. Network methods on a stopped instance reject without reconnecting; create a new instance to resume. An injected pool is still destroyed as before. + +Standalone `SendNofferRequest`, `SendNdebitRequest`, `SendNmanageRequest`, `SendNenrollRequest`, and `FetchClinkBeacon` accept an optional trailing `AbortSignal` for caller-controlled cancellation. The abort reason is preserved. Cancellation stops SDK activity; it does not undo a request that the host may already have accepted. ### Encoding/Decoding diff --git a/src/index.ts b/src/index.ts index 1663e1d..6445052 100644 --- a/src/index.ts +++ b/src/index.ts @@ -36,6 +36,7 @@ const nprofileSettings = (nprofile: string, privateKey: Uint8Array, extra?: Pick export class ClinkSDK { pool: AbstractSimplePool settings: ClinkSettings + private readonly shutdown = new AbortController() constructor(settings: ClinkSettings, pool?: AbstractSimplePool) { this.settings = settings if (pool) { @@ -50,29 +51,34 @@ export class ClinkSDK { } Noffer = (data: NofferData, onReceipt?: (receipt: NofferReceipt) => void, timeoutSeconds?: number) => { - return SendNofferRequest(this.pool, this.settings.privateKey, this.settings.relays, this.settings.toPubKey, data, timeoutSeconds || this.settings.defaultTimeoutSeconds, onReceipt) + return SendNofferRequest(this.pool, this.settings.privateKey, this.settings.relays, this.settings.toPubKey, data, timeoutSeconds || this.settings.defaultTimeoutSeconds, onReceipt, this.shutdown.signal) } Ndebit = (data: NdebitData, timeoutSeconds?: number) => { - return SendNdebitRequest(this.pool, this.settings.privateKey, this.settings.relays, this.settings.toPubKey, data, timeoutSeconds || this.settings.defaultTimeoutSeconds) + return SendNdebitRequest(this.pool, this.settings.privateKey, this.settings.relays, this.settings.toPubKey, data, timeoutSeconds || this.settings.defaultTimeoutSeconds, this.shutdown.signal) } Nmanage = (data: NmanageRequest, timeoutSeconds?: number) => { - return SendNmanageRequest(this.pool, this.settings.privateKey, this.settings.relays, this.settings.toPubKey, data, timeoutSeconds || this.settings.defaultTimeoutSeconds) + return SendNmanageRequest(this.pool, this.settings.privateKey, this.settings.relays, this.settings.toPubKey, data, timeoutSeconds || this.settings.defaultTimeoutSeconds, this.shutdown.signal) } Nbeacon = (timeoutSeconds?: number) => { - return FetchClinkBeacon(this.pool, this.settings.relays, this.settings.toPubKey, timeoutSeconds || 10) + return FetchClinkBeacon(this.pool, this.settings.relays, this.settings.toPubKey, timeoutSeconds || 10, this.shutdown.signal) } Nenroll = async (opts?: NenrollOptions, timeoutSeconds?: number) => { + this.shutdown.signal.throwIfAborted() const timeout = timeoutSeconds || this.settings.defaultTimeoutSeconds const difficulty = opts?.difficulty ?? await this.beaconEnrollDifficulty() - return SendNenrollRequest(this.pool, this.settings.privateKey, this.settings.relays, this.settings.toPubKey, difficulty, timeout) + return SendNenrollRequest(this.pool, this.settings.privateKey, this.settings.relays, this.settings.toPubKey, difficulty, timeout, this.shutdown.signal) } - /** Close relay connections. Call when done so the process can exit. */ + /** Cancel owned requests and receipt listeners, then close relay connections. This instance cannot be reused. */ Stop = () => { + if (this.shutdown.signal.aborted) { + return + } + this.shutdown.abort() this.pool.destroy() } @@ -81,6 +87,7 @@ export class ClinkSDK { const beacon = await this.Nbeacon() return enrollDifficultyFromBeacon(beacon) ?? 0 } catch { + this.shutdown.signal.throwIfAborted() return 0 } } diff --git a/src/nbeacon.ts b/src/nbeacon.ts index 8f26d02..73deb4d 100644 --- a/src/nbeacon.ts +++ b/src/nbeacon.ts @@ -152,39 +152,65 @@ export const FetchClinkBeacon = async ( relays: string[], servicePub: string, timeoutSeconds = 10, + signal?: AbortSignal, ): Promise => { + signal?.throwIfAborted() const expectedPub = servicePub.toLowerCase() - return new Promise(resolve => { + return new Promise((resolve, reject) => { let settled = false let best: Event | null = null let closer = { close: () => { } } - const finish = () => { + const finish = (error?: unknown) => { if (settled) { return } settled = true clearTimeout(timer) + signal?.removeEventListener('abort', onAbort) closer.close() - resolve(best ? parseClinkBeaconEvent(best) : null) + if (error !== undefined) { + reject(error) + } else { + resolve(best ? parseClinkBeaconEvent(best) : null) + } + } + const onAbort = () => finish(signal!.reason) + const timer = setTimeout(() => finish(), timeoutSeconds * 1000) + signal?.addEventListener('abort', onAbort, { once: true }) + if (signal?.aborted) { + onAbort() + return + } + try { + const subscription = pool.subscribe(relays, { + kinds: [CLINK_BEACON_KIND], + authors: [expectedPub], + "#d": [CLINK_BEACON_D_TAG], + }, { + onevent: (event: Event) => { + if (settled || signal?.aborted) { + return + } + if (event.pubkey.toLowerCase() !== expectedPub) { + return + } + if (!verifyEvent(event)) { + return + } + if (!best || event.created_at > best.created_at) { + best = event + } + }, + oneose: () => signal?.aborted ? onAbort() : finish(), + }) + // Callbacks (including abort) may run before subscribe returns. + if (settled) { + subscription.close() + } else { + closer = subscription + } + } catch (error) { + finish(error) } - const timer = setTimeout(finish, timeoutSeconds * 1000) - closer = pool.subscribe(relays, { - kinds: [CLINK_BEACON_KIND], - authors: [expectedPub], - "#d": [CLINK_BEACON_D_TAG], - }, { - onevent: (event: Event) => { - if (event.pubkey.toLowerCase() !== expectedPub) { - return - } - if (!verifyEvent(event)) { - return - } - if (!best || event.created_at > best.created_at) { - best = event - } - }, - oneose: finish, - }) }) } diff --git a/src/ndebit.ts b/src/ndebit.ts index 663fc52..326ab57 100644 --- a/src/ndebit.ts +++ b/src/ndebit.ts @@ -105,12 +105,13 @@ export type NdebitFailure = { } export type NdebitResponse = NdebitSuccess | NdebitFailure -export const SendNdebitRequest = async (pool: AbstractSimplePool, privateKey: Uint8Array, relays: string[], toPubKey: string, data: NdebitData, timeoutSeconds?: number): Promise => { +export const SendNdebitRequest = async (pool: AbstractSimplePool, privateKey: Uint8Array, relays: string[], toPubKey: string, data: NdebitData, timeoutSeconds?: number, signal?: AbortSignal): Promise => { + signal?.throwIfAborted() const payload = validateNdebitData(data) const publicKey = getPublicKey(privateKey) const content = encrypt(JSON.stringify(payload), getConversationKey(privateKey, toPubKey)) const event = newNdebitEvent(content, publicKey, toPubKey) - return sendRequest(pool, { privateKey, publicKey }, relays, toPubKey, event, 21002, timeoutSeconds) + return sendRequest(pool, { privateKey, publicKey }, relays, toPubKey, event, 21002, timeoutSeconds, undefined, signal) } diff --git a/src/nenroll.ts b/src/nenroll.ts index 1d231db..e410a2e 100644 --- a/src/nenroll.ts +++ b/src/nenroll.ts @@ -41,14 +41,16 @@ const sendEnrollOnce = ( toPubKey: string, bits: number, timeoutSeconds?: number, + signal?: AbortSignal, ): Promise => { + signal?.throwIfAborted() const publicKey = getPublicKey(privateKey) const content = encrypt(JSON.stringify({}), getConversationKey(privateKey, toPubKey)) let event = newNenrollEvent(content, publicKey, toPubKey) if (bits > 0) { event = mineNip13(event, bits) } - return sendRequest(pool, { privateKey, publicKey }, relays, toPubKey, event, CLINK_ENROLL_KIND, timeoutSeconds) + return sendRequest(pool, { privateKey, publicKey }, relays, toPubKey, event, CLINK_ENROLL_KIND, timeoutSeconds, undefined, signal) } export const SendNenrollRequest = async ( @@ -58,12 +60,15 @@ export const SendNenrollRequest = async ( toPubKey: string, difficulty = 0, timeoutSeconds?: number, + signal?: AbortSignal, ): Promise => { + signal?.throwIfAborted() const used = difficulty > 0 ? difficulty : 0 if (used > 0 && !enrollPowBitsOk(used)) { throw new Error(`enroll PoW difficulty ${used} exceeds max`) } - const first = await sendEnrollOnce(pool, privateKey, relays, toPubKey, used, timeoutSeconds) + const first = await sendEnrollOnce(pool, privateKey, relays, toPubKey, used, timeoutSeconds, signal) + signal?.throwIfAborted() if (!isGfy5(first)) { return first } @@ -71,5 +76,5 @@ export const SendNenrollRequest = async ( if (typeof required !== "number" || !enrollPowBitsOk(required) || required <= used) { return first } - return sendEnrollOnce(pool, privateKey, relays, toPubKey, required, timeoutSeconds) + return sendEnrollOnce(pool, privateKey, relays, toPubKey, required, timeoutSeconds, signal) } diff --git a/src/nip19Extension.ts b/src/nip19Extension.ts index e65ee66..7dab137 100644 --- a/src/nip19Extension.ts +++ b/src/nip19Extension.ts @@ -197,6 +197,8 @@ function parseTLV(data: Uint8Array): TLV { export const nofferEncode = (offer: OfferPointer): string => { + const pubkey = hexToBytes(offer.pubkey) + if (pubkey.length !== 32) throw new Error('raw pubkey buffer should be 32 bytes') if (offer.currency !== undefined) { if (offer.priceType !== OfferPriceType.Variable) { throw new Error('noffer currency requires variable price type') @@ -206,7 +208,7 @@ export const nofferEncode = (offer: OfferPointer): string => { } } const o: TLV = { - 0: [hexToBytes(offer.pubkey)], + 0: [pubkey], 1: [utf8Encoder.encode(offer.relay)], 2: [utf8Encoder.encode(offer.offer)], 3: [new Uint8Array([Number(offer.priceType)])], @@ -223,8 +225,10 @@ export const nofferEncode = (offer: OfferPointer): string => { } export const ndebitEncode = (debit: DebitPointer): string => { + const pubkey = hexToBytes(debit.pubkey) + if (pubkey.length !== 32) throw new Error('raw pubkey buffer should be 32 bytes') const o: TLV = { - 0: [hexToBytes(debit.pubkey)], + 0: [pubkey], 1: [utf8Encoder.encode(debit.relay)], } if (debit.pointer) { @@ -241,8 +245,10 @@ export const ndebitEncode = (debit: DebitPointer): string => { } export const nmanageEncode = (manage: ManagePointer): string => { + const pubkey = hexToBytes(manage.pubkey) + if (pubkey.length !== 32) throw new Error('raw pubkey buffer should be 32 bytes') const o: TLV = { - 0: [hexToBytes(manage.pubkey)], + 0: [pubkey], 1: [utf8Encoder.encode(manage.relay)], } if (manage.pointer) { diff --git a/src/nmanage.ts b/src/nmanage.ts index bc03369..4b93d81 100644 --- a/src/nmanage.ts +++ b/src/nmanage.ts @@ -143,11 +143,12 @@ export const validateNmanageRequest = (data: unknown): NmanageRequest => { } } -export const SendNmanageRequest = async (pool: AbstractSimplePool, privateKey: Uint8Array, relays: string[], toPubKey: string, data: NmanageRequest, timeoutSeconds?: number): Promise => { +export const SendNmanageRequest = async (pool: AbstractSimplePool, privateKey: Uint8Array, relays: string[], toPubKey: string, data: NmanageRequest, timeoutSeconds?: number, signal?: AbortSignal): Promise => { + signal?.throwIfAborted() const publicKey = getPublicKey(privateKey) const content = encrypt(JSON.stringify(data), getConversationKey(privateKey, toPubKey)) const event = newNmanageEvent(content, publicKey, toPubKey) - return sendRequest(pool, { privateKey, publicKey }, relays, toPubKey, event, 21003, timeoutSeconds) + return sendRequest(pool, { privateKey, publicKey }, relays, toPubKey, event, 21003, timeoutSeconds, undefined, signal) } export const newNmanageEvent = (content: string, fromPub: string, toPub: string) => ({ diff --git a/src/noffer.ts b/src/noffer.ts index 0a25979..081c014 100644 --- a/src/noffer.ts +++ b/src/noffer.ts @@ -70,12 +70,13 @@ export type NofferSuccess = { bolt11: string } export type NofferError = { code: number, error: string, range?: { min: number, max: number }, latest?: string, payer_data?: string[] } export type NofferResponse = NofferSuccess | NofferError -export const SendNofferRequest = async (pool: AbstractSimplePool, privateKey: Uint8Array, relays: string[], toPubKey: string, data: NofferData, timeoutSeconds = 30, onReceipt?: (receipt: NofferReceipt) => void): Promise => { +export const SendNofferRequest = async (pool: AbstractSimplePool, privateKey: Uint8Array, relays: string[], toPubKey: string, data: NofferData, timeoutSeconds = 30, onReceipt?: (receipt: NofferReceipt) => void, signal?: AbortSignal): Promise => { + signal?.throwIfAborted() const payload = validateNofferData(data) const publicKey = getPublicKey(privateKey) const content = encrypt(JSON.stringify(payload), getConversationKey(privateKey, toPubKey)) const event = newNofferEvent(content, publicKey, toPubKey) - return sendRequest(pool, { privateKey, publicKey }, relays, toPubKey, event, CLINK_OFFER_KIND, timeoutSeconds, onReceipt) + return sendRequest(pool, { privateKey, publicKey }, relays, toPubKey, event, CLINK_OFFER_KIND, timeoutSeconds, onReceipt, signal) } export const newNofferEvent = (content: string, fromPub: string, toPub: string) => ({ diff --git a/src/sender.ts b/src/sender.ts index 0c123b0..0437937 100644 --- a/src/sender.ts +++ b/src/sender.ts @@ -64,7 +64,8 @@ type Pair = { privateKey: Uint8Array, publicKey: string } const RECEIPT_RESUBSCRIBE_MS = 4000 const RELISTEN_MS = 500 -export const sendRequest = async (pool: AbstractSimplePool, pair: Pair, relays: string[], toPub: string, e: UnsignedEvent, kindExpected: number, timeoutSeconds?: number, moreCb?: (data: any) => void): Promise => { +export const sendRequest = async (pool: AbstractSimplePool, pair: Pair, relays: string[], toPub: string, e: UnsignedEvent, kindExpected: number, timeoutSeconds?: number, moreCb?: (data: any) => void, signal?: AbortSignal): Promise => { + signal?.throwIfAborted() if (relays.length === 0) { throw new Error('no relays provided') } @@ -110,6 +111,7 @@ export const sendRequest = async (pool: AbstractSimplePool, pair: Pair, relay } finished = true stopTimers() + signal?.removeEventListener('abort', onAbort) closer.close() } @@ -122,15 +124,23 @@ export const sendRequest = async (pool: AbstractSimplePool, pair: Pair, relay rej(err) } + const onAbort = () => { + if (settled) { + cleanup() + } else { + fail(signal!.reason) + } + } + const waitForReceipt = () => { - if (finished || resubTimer !== null) { + if (finished || signal?.aborted || resubTimer !== null) { return } resubTimer = setInterval(listen, RECEIPT_RESUBSCRIBE_MS) } const listen = () => { - if (finished) { + if (finished || signal?.aborted) { return } if (relistenTimer !== null) { @@ -140,9 +150,12 @@ export const sendRequest = async (pool: AbstractSimplePool, pair: Pair, relay const gen = ++listenGen log(`[ClinkSDK] Setting up subscription with filter:`, JSON.stringify(filter, null, 2)) closer.close() + if (finished || signal?.aborted) { + return + } const subscription = pool.subscribe(relays, filter, { onevent: async (event) => { - if (finished || gen !== listenGen) { + if (finished || signal?.aborted || gen !== listenGen) { return } log(`[ClinkSDK] Received response event: kind=${event.kind}, eventId=${event.id}, from=${event.pubkey}`) @@ -187,7 +200,7 @@ export const sendRequest = async (pool: AbstractSimplePool, pair: Pair, relay log(`[ClinkSDK] End of stored events received for eventId=${signed.id}`) }, onclose: () => { - if (finished || gen !== listenGen || relistenTimer !== null) { + if (finished || signal?.aborted || gen !== listenGen || relistenTimer !== null) { return } log(`[ClinkSDK] Subscription closed, listening again for eventId=${signed.id}`) @@ -195,13 +208,19 @@ export const sendRequest = async (pool: AbstractSimplePool, pair: Pair, relay }, }) // subscribe may invoke callbacks before returning its closer. - if (finished || gen !== listenGen) { + if (finished || signal?.aborted || gen !== listenGen) { subscription.close() } else { closer = subscription } } + signal?.addEventListener('abort', onAbort, { once: true }) + if (signal?.aborted) { + onAbort() + return + } + if (timeoutSeconds) { timer = setTimeout(() => { log(`[ClinkSDK] Timeout after ${timeoutSeconds}s - no response received for kind=${kindExpected}, eventId=${signed.id}`) @@ -211,7 +230,7 @@ export const sendRequest = async (pool: AbstractSimplePool, pair: Pair, relay try { listen() - if (finished) { + if (finished || signal?.aborted) { return } const attempts = pool.publish(relays, signed) diff --git a/test-vectors/interop.json b/test-vectors/interop.json index c5a0b63..c573f2e 100644 --- a/test-vectors/interop.json +++ b/test-vectors/interop.json @@ -6,14 +6,16 @@ "Length is a single byte (0–255), NOT 2-byte big-endian.", "Tag numbers and meanings are fixed — do not swap pubkey/relay; do not omit required tags.", "Tag 0 (pubkey) is 32 raw bytes, not a UTF-8 hex string.", - "ndebit tag 3 (k1) is 32 raw bytes like tag 0, not a UTF-8 hex string." + "ndebit tag 3 (k1) is 32 raw bytes like tag 0, not a UTF-8 hex string.", + "noffer tag 4 decoders accept 1 to 255 bytes, including leading zeroes, when the unsigned big-endian value is 0..9007199254740991 inclusive; reject empty or larger integer values.", + "noffer tag 4 encoders preserve four-byte encodings for values 0..4294967295, including explicit zero, and use the minimum byte width for larger safe integers." ], "noffer": { "0": "pubkey (32 bytes raw)", "1": "relay (utf8)", "2": "offer id (utf8)", "3": "priceType (optional, 1 byte: 0=Fixed, 1=Variable, 2=Spontaneous; omit with TLV 4/5 absent ⇒ Spontaneous)", - "4": "price (optional, 4-byte big-endian uint32; omit when TLV 5 is present)", + "4": "price (optional, nonempty unsigned big-endian integer 0..9007199254740991 inclusive; omit when TLV 5 is present)", "5": "currency (optional utf8, e.g. USD; requires Variable and excludes TLV 4)" }, "ndebit": { @@ -54,6 +56,26 @@ "price": 1000 } }, + "noffer_price_above_uint32": { + "encoded": "noffer1qszszqqqqqqqxqgqqgyk7enxv4e97ctzvvq3wamnwvaz7tmjv4kxz7fwv4uxzmtsd3jjucm0d5qzqudhpwkwfpnuszlxkzpagjwrwjr0xdusmu82fwlxa88xz7lwxjmx6e27pa", + "decoded": { + "pubkey": "71b70bace4867c80be6b083d449c37486f33790df0ea4bbe6e9ce617bee34b66", + "relay": "wss://relay.example.com", + "offer": "offer_abc", + "priceType": 0, + "price": 4294967296 + } + }, + "noffer_price_max_safe_integer": { + "encoded": "noffer1qsr3llllllllllcrqyqqyzt0venx2ujlv93xxqghwaehxw309aex2mrp0yhx27rpd4cxcefwvdhk6qpqwxmsht8yse7gp0ntpq75f8phfphnx7gd7r4yh0nwnnnp00hrfdnqa75uxg", + "decoded": { + "pubkey": "71b70bace4867c80be6b083d449c37486f33790df0ea4bbe6e9ce617bee34b66", + "relay": "wss://relay.example.com", + "offer": "offer_abc", + "priceType": 0, + "price": 9007199254740991 + } + }, "ndebit": { "encoded": "ndebit1qgy8xar0wfj47dpjqythwumn8ghj7un9d3shjtn90psk6urvv5hxxmmdqqs8rdct4njgvlyqhe4ss02ynsm5smen0yxlp6jthehfeeshhm35kesh4xxz5", "decoded": { diff --git a/test/unit/bech32.test.mjs b/test/unit/bech32.test.mjs index 9df33bf..81da689 100644 --- a/test/unit/bech32.test.mjs +++ b/test/unit/bech32.test.mjs @@ -19,6 +19,9 @@ import { const fixtures = JSON.parse( readFileSync(join(dirname(fileURLToPath(import.meta.url)), '../fixtures/bech32.json'), 'utf8') ) +const interop = JSON.parse( + readFileSync(join(dirname(fileURLToPath(import.meta.url)), '../../test-vectors/interop.json'), 'utf8') +) const utf8 = new TextEncoder() @@ -142,6 +145,23 @@ describe('bech32 round-trip', () => { }) }) +describe('published bech32 interop vectors', () => { + const encoders = { noffer: nofferEncode, ndebit: ndebitEncode, nmanage: nmanageEncode } + + for (const [name, { encoded, decoded }] of Object.entries(interop.bech32_roundtrip)) { + it(`decodes and exactly re-encodes ${name}`, () => { + const type = encoded.slice(0, encoded.indexOf('1')) + const result = decodeBech32(encoded) + assert.equal(result.type, type) + for (const [field, value] of Object.entries(decoded)) { + assert.equal(result.data[field], value) + } + assert.equal(encoders[type](decoded), encoded) + assert.equal(encoders[type](result.data), encoded) + }) + } +}) + describe('noffer prices', () => { const pointer = { ...fixtures.noffer.decoded, priceType: OfferPriceType.Fixed } const fields = { @@ -187,7 +207,10 @@ describe('noffer prices', () => { }) it('accepts exact external integer widths and infers fixed pricing even for zero', () => { - for (const [hex, price] of [['00', 0], ['01', 1], ['001fffffffffffff', Number.MAX_SAFE_INTEGER]]) { + for (const [hex, price] of [ + ['00', 0], ['01', 1], ['0001', 1], ['001fffffffffffff', Number.MAX_SAFE_INTEGER], + ['00'.repeat(255), 0], ['00'.repeat(248) + '1fffffffffffff', Number.MAX_SAFE_INTEGER], + ]) { const decoded = decodeBech32(encodeNofferTlv({ ...fields, 4: hexToBytes(hex) })).data assert.equal(decoded.price, price) assert.equal(decoded.priceType, OfferPriceType.Fixed) @@ -222,6 +245,19 @@ describe('TLV encoding limits', () => { ] for (const [kind, encode, pointer, identifier] of encoders) { + for (const length of [0, 1, 31, 33, 64, 255]) { + it(`rejects a ${length}-byte ${kind} pubkey before encoding`, () => { + assert.throws(() => encode({ ...pointer, pubkey: 'ab'.repeat(length) }), /pubkey buffer should be 32 bytes/) + }) + } + + it(`preserves a valid 32-byte ${kind} pubkey and its fixture encoding`, () => { + const encoded = encode(pointer) + if (fixtures[kind].encoded) assert.equal(encoded, fixtures[kind].encoded) + assert.equal(decodeBech32(encoded).data.pubkey, pointer.pubkey) + assert.equal(encode({ ...pointer, pubkey: pointer.pubkey.toUpperCase() }), encoded) + }) + for (const field of [identifier, 'relay']) { it(`checks the UTF-8 byte length of ${kind} ${field}`, () => { for (const value of ['a'.repeat(255), '\u00e9'.repeat(127) + 'a']) { diff --git a/test/unit/stop.test.mjs b/test/unit/stop.test.mjs new file mode 100644 index 0000000..ef636eb --- /dev/null +++ b/test/unit/stop.test.mjs @@ -0,0 +1,307 @@ +import { describe, it } from 'node:test' +import assert from 'node:assert/strict' +import { getEventListeners } from 'node:events' +import { generateSecretKey, getPublicKey } from 'nostr-tools' +import { + ClinkSDK, FetchClinkBeacon, SendNofferRequest, SendNdebitRequest, + SendNmanageRequest, SendNenrollRequest, CLINK_BEACON_KIND, +} from '../../build/index.js' +import { sendRequest } from '../../build/sender.js' +import { signedClinkReply } from './signed-reply.mjs' + +const clientPriv = generateSecretKey() +const clientPub = getPublicKey(clientPriv) +const serverPriv = generateSecretKey() +const serverPub = getPublicKey(serverPriv) +const relays = ['wss://relay.example'] +const settings = { privateKey: clientPriv, relays, toPubKey: serverPub } +const aborted = { name: 'AbortError' } + +function setup(t, { onSubscribe, onPublish } = {}) { + t.mock.timers.enable({ apis: ['setTimeout', 'setInterval'] }) + const subscriptions = [] + const published = [] + const order = [] + const pool = { + subscribe(_relays, filter, opts) { + order.push('subscribe') + const sub = { + filter, opts, closed: false, + close() { + if (sub.closed) return + sub.closed = true + order.push('close') + opts.onclose?.([]) + }, + } + subscriptions.push(sub) + onSubscribe?.(sub) + return sub + }, + publish(_relays, event) { + order.push('publish') + published.push(event) + onPublish?.(event, subscriptions.at(-1)) + return [Promise.resolve('ok')] + }, + destroy() { + order.push('destroy') + for (const sub of subscriptions) sub.opts.onclose?.([]) + }, + } + const sdk = new ClinkSDK(settings, pool) + return { sdk, pool, subscriptions, published, order } +} + +const reply = (sub, payload) => sub.opts.onevent(signedClinkReply( + serverPriv, clientPub, sub.filter['#e'][0], payload, sub.filter.kinds[0], +)) + +describe('SDK shutdown', () => { + it('cancels receipt polling and queued relistens before destroying the pool', async (t) => { + const { sdk, subscriptions, published, order } = setup(t) + const receipt = t.mock.fn() + const primary = sdk.Noffer({ offer: 'o' }, receipt) + await reply(subscriptions[0], { bolt11: 'lnbc1dummy' }) + assert.deepEqual(await primary, { bolt11: 'lnbc1dummy' }) + t.mock.timers.tick(4000) + assert.equal(subscriptions.length, 2) + subscriptions[1].opts.onclose([]) + const clearTimeouts = t.mock.method(globalThis, 'clearTimeout') + const clearIntervals = t.mock.method(globalThis, 'clearInterval') + + sdk.Stop() + sdk.Stop() + assert.equal(clearTimeouts.mock.callCount(), 1) + assert.equal(clearIntervals.mock.callCount(), 1) + assert.deepEqual(order.slice(-2), ['close', 'destroy']) + assert.equal(order.filter(item => item === 'destroy').length, 1) + const timeouts = t.mock.method(globalThis, 'setTimeout') + for (const sub of subscriptions) { + assert.equal(sub.closed, true) + sub.opts.onclose([]) + await reply(sub, { res: 'ok' }) + } + t.mock.timers.tick(60000) + assert.equal(timeouts.mock.callCount(), 0) + assert.equal(subscriptions.length, 2) + assert.equal(published.length, 1) + assert.equal(receipt.mock.callCount(), 0) + }) + + it('rejects all pending primary requests, including requests without timeouts', async (t) => { + const { sdk, subscriptions, published, order } = setup(t) + const receipt = t.mock.fn() + const pending = [ + sdk.Noffer({ offer: 'o' }, receipt), sdk.Ndebit({}), + sdk.Nmanage({ resource: 'offer', action: 'list' }), + sdk.Nenroll({ difficulty: 0 }), sdk.Nbeacon(), + ].map(promise => assert.rejects(promise, aborted)) + assert.equal(subscriptions.length, 5) + const clearTimeouts = t.mock.method(globalThis, 'clearTimeout') + sdk.Stop() + assert.equal(clearTimeouts.mock.callCount(), 2) + assert.equal(order.at(-1), 'destroy') + assert.ok(subscriptions.every(sub => sub.closed)) + await Promise.all(pending) + for (const sub of subscriptions) { + sub.opts.onclose?.([]) + if (sub.filter.kinds[0] === CLINK_BEACON_KIND) sub.opts.oneose() + else await reply(sub, { bolt11: 'lnbc1late' }) + } + t.mock.timers.tick(60000) + assert.equal(subscriptions.length, 5) + assert.equal(published.length, 4) + assert.equal(receipt.mock.callCount(), 0) + }) + + it('rejects every network method after Stop without reconnecting or starting timers', async (t) => { + const { sdk, order } = setup(t) + sdk.Stop() + const timeouts = t.mock.method(globalThis, 'setTimeout') + const intervals = t.mock.method(globalThis, 'setInterval') + for (const promise of [ + sdk.Noffer({ offer: 'o' }), sdk.Ndebit({}), + sdk.Nmanage({ resource: 'offer', action: 'list' }), sdk.Nbeacon(), + sdk.Nenroll(), sdk.Nenroll({ difficulty: 0 }), + ]) await assert.rejects(promise, aborted) + t.mock.timers.tick(60000) + assert.deepEqual(order, ['destroy']) + assert.equal(timeouts.mock.callCount(), 0) + assert.equal(intervals.mock.callCount(), 0) + }) + + for (const discoveryFinished of [false, true]) { + it(`does not send enrollment when stopped ${discoveryFinished ? 'after' : 'during'} beacon discovery`, async (t) => { + const { sdk, subscriptions, published } = setup(t) + const rejected = assert.rejects(sdk.Nenroll(), aborted) + assert.equal(subscriptions.length, 1) + assert.equal(subscriptions[0].filter.kinds[0], CLINK_BEACON_KIND) + if (discoveryFinished) subscriptions[0].opts.oneose() + sdk.Stop() + await rejected + subscriptions[0].opts.oneose() + t.mock.timers.tick(60000) + assert.equal(subscriptions[0].closed, true) + assert.equal(subscriptions.length, 1) + assert.equal(published.length, 0) + }) + } + + it('does not remine or send an enrollment retry after Stop', async (t) => { + const { sdk, subscriptions, published } = setup(t) + const rejected = assert.rejects(sdk.Nenroll({ difficulty: 0 }), aborted) + // Do not yield: Stop runs before the await continuation that starts the retry. + reply(subscriptions[0], { res: 'GFY', code: 5, required_difficulty: 1 }) + sdk.Stop() + await rejected + t.mock.timers.tick(60000) + assert.equal(subscriptions.length, 1) + assert.equal(published.length, 1) + }) + + it('closes a subscription returned after synchronous Stop and never publishes', async (t) => { + let sdk + const context = setup(t, { onSubscribe: () => sdk.Stop() }) + sdk = context.sdk + await assert.rejects(sdk.Ndebit({}), aborted) + assert.equal(context.subscriptions[0].closed, true) + assert.equal(context.published.length, 0) + t.mock.timers.tick(60000) + assert.equal(context.subscriptions.length, 1) + }) + + it('does not resubscribe if closing the previous subscription triggers Stop', async (t) => { + const { sdk, subscriptions } = setup(t) + const primary = sdk.Noffer({ offer: 'o' }, t.mock.fn()) + await reply(subscriptions[0], { bolt11: 'lnbc1dummy' }) + await primary + const close = subscriptions[0].close + subscriptions[0].close = () => { close(); sdk.Stop() } + t.mock.timers.tick(4000) + t.mock.timers.tick(60000) + assert.equal(subscriptions.length, 1) + }) + + it('does not cancel another instance sharing the same pool', async (t) => { + const { sdk, pool, subscriptions } = setup(t) + const other = new ClinkSDK(settings, pool) + const cancelled = assert.rejects(sdk.Ndebit({}), aborted) + const active = other.Ndebit({}) + sdk.Stop() + await cancelled + assert.equal(subscriptions[0].closed, true) + assert.equal(subscriptions[1].closed, false) + await reply(subscriptions[1], { res: 'ok' }) + assert.deepEqual(await active, { res: 'ok' }) + other.Stop() + }) +}) + +describe('standalone cancellation', () => { + it('accepts already-aborted trailing signals without network or timer activity', async (t) => { + const { pool, order } = setup(t) + const controller = new AbortController() + const reason = new Error('cancelled by caller') + controller.abort(reason) + const signal = controller.signal + const timeouts = t.mock.method(globalThis, 'setTimeout') + const intervals = t.mock.method(globalThis, 'setInterval') + for (const promise of [ + SendNofferRequest(pool, clientPriv, relays, serverPub, { offer: 'o' }, undefined, undefined, signal), + SendNdebitRequest(pool, clientPriv, relays, serverPub, {}, undefined, signal), + SendNmanageRequest(pool, clientPriv, relays, serverPub, {}, undefined, signal), + SendNenrollRequest(pool, clientPriv, relays, serverPub, 0, undefined, signal), + FetchClinkBeacon(pool, relays, serverPub, undefined, signal), + sendRequest(pool, { privateKey: clientPriv, publicKey: clientPub }, relays, serverPub, + {}, 21001, undefined, undefined, signal), + ]) await assert.rejects(promise, error => error === reason) + assert.deepEqual(order, []) + assert.equal(timeouts.mock.callCount(), 0) + assert.equal(intervals.mock.callCount(), 0) + assert.equal(getEventListeners(signal, 'abort').length, 0) + }) + + it('ignores callbacks fired by an earlier abort listener before its own cleanup runs', async (t) => { + const { pool, subscriptions } = setup(t) + const controller = new AbortController() + const receipt = t.mock.fn() + controller.signal.addEventListener('abort', () => { + subscriptions[0].opts.onclose([]) + reply(subscriptions[0], { res: 'ok' }) + }, { once: true }) + const primary = SendNofferRequest(pool, clientPriv, relays, serverPub, + { offer: 'o' }, undefined, receipt, controller.signal) + await reply(subscriptions[0], { bolt11: 'lnbc1dummy' }) + await primary + const timeouts = t.mock.method(globalThis, 'setTimeout') + controller.abort() + assert.equal(timeouts.mock.callCount(), 0) + assert.equal(receipt.mock.callCount(), 0) + assert.equal(getEventListeners(controller.signal, 'abort').length, 0) + t.mock.timers.tick(60000) + assert.equal(subscriptions.length, 1) + }) + + for (const outcome of ['primary error', 'receipt', 'abort', 'timeout', 'publish failure']) { + it(`removes the sender abort listener after ${outcome}`, async (t) => { + const { pool, subscriptions } = setup(t) + if (outcome === 'publish failure') pool.publish = () => [Promise.reject(new Error('refused'))] + const controller = new AbortController() + const signal = controller.signal + const receipt = t.mock.fn() + const primary = SendNofferRequest(pool, clientPriv, relays, serverPub, { offer: 'o' }, 1, receipt, signal) + assert.equal(getEventListeners(signal, 'abort').length, 1) + if (outcome === 'primary error') { + await reply(subscriptions[0], { code: 1, error: 'unavailable' }) + await primary + } else if (outcome === 'receipt') { + await reply(subscriptions[0], { bolt11: 'lnbc1dummy' }) + await primary + assert.equal(getEventListeners(signal, 'abort').length, 1) + await reply(subscriptions[0], { res: 'ok' }) + assert.equal(receipt.mock.callCount(), 1) + } else { + const rejected = assert.rejects(primary) + if (outcome === 'abort') controller.abort() + if (outcome === 'timeout') t.mock.timers.tick(1000) + await rejected + } + assert.equal(getEventListeners(signal, 'abort').length, 0) + controller.abort() + t.mock.timers.tick(60000) + assert.equal(subscriptions.length, 1) + assert.equal(subscriptions[0].closed, true) + }) + } + + for (const outcome of ['eose', 'abort', 'timeout', 'subscribe failure', 'synchronous eose', 'synchronous abort']) { + it(`cleans up beacon subscriptions and listeners after ${outcome}`, async (t) => { + const controller = new AbortController() + const signal = controller.signal + const { pool, subscriptions } = setup(t, { + onSubscribe: sub => { + if (outcome === 'synchronous eose') sub.opts.oneose() + if (outcome === 'synchronous abort') controller.abort() + }, + }) + if (outcome === 'subscribe failure') pool.subscribe = () => { throw new Error('subscribe failed') } + const beacon = FetchClinkBeacon(pool, relays, serverPub, 1, signal) + const checked = outcome.includes('abort') || outcome === 'subscribe failure' + ? assert.rejects(beacon) : assert.doesNotReject(async () => assert.equal(await beacon, null)) + if (outcome === 'eose') subscriptions[0].opts.oneose() + if (outcome === 'abort') controller.abort() + if (outcome === 'timeout') t.mock.timers.tick(1000) + await checked + assert.equal(getEventListeners(signal, 'abort').length, 0) + if (subscriptions.length) { + assert.equal(subscriptions[0].closed, true) + subscriptions[0].opts.onevent({}) + subscriptions[0].opts.oneose() + } + controller.abort() + t.mock.timers.tick(60000) + assert.ok(subscriptions.length <= 1) + }) + } +})