mirror of
https://github.com/tompro/sattle.git
synced 2026-08-27 07:15:59 +00:00
fix: validate NWC requests before dispatch
This commit is contained in:
@@ -9,6 +9,7 @@ import {noteK1, sameInvoice} from 'lnurlcash-kit'
|
||||
import type {Bearer} from '../types'
|
||||
import type {PreparedMint} from '../ops'
|
||||
import {prepareMint} from '../ops'
|
||||
import {PollAbortedError} from '../ops/shared'
|
||||
|
||||
import type {PendingInvoice, RequestContext} from './context'
|
||||
import {invoiceResult, resolvePaymentHash, settleAndClaim} from './invoices'
|
||||
@@ -19,10 +20,7 @@ import {NWC_METHODS, errResult, okResult} from './protocol'
|
||||
// the same eligibility carve applies - the balance answers "what could
|
||||
// this wallet actually pay with right now"
|
||||
const spendable = (bearer: Bearer): boolean =>
|
||||
!bearer.spent &&
|
||||
bearer.callback !== '' &&
|
||||
!bearer.deviceId &&
|
||||
!!noteK1(bearer.url)
|
||||
!bearer.spent && bearer.callback !== '' && !bearer.deviceId && !!noteK1(bearer.url)
|
||||
|
||||
const handleGetInfo = (ctx: RequestContext): NwcResponse =>
|
||||
okResult('get_info', {
|
||||
@@ -34,7 +32,7 @@ const handleGetInfo = (ctx: RequestContext): NwcResponse =>
|
||||
// block height/hash exists, so those fields are simply absent.
|
||||
network: 'mainnet',
|
||||
methods: [...NWC_METHODS],
|
||||
notifications: []
|
||||
notifications: [],
|
||||
})
|
||||
|
||||
const handleGetBalance = (ctx: RequestContext): NwcResponse =>
|
||||
@@ -42,20 +40,16 @@ const handleGetBalance = (ctx: RequestContext): NwcResponse =>
|
||||
balance: ctx.deps
|
||||
.getBearers()
|
||||
.filter(spendable)
|
||||
.reduce((sum, b) => sum + b.amount, 0)
|
||||
.reduce((sum, b) => sum + b.amount, 0),
|
||||
})
|
||||
|
||||
const handleMakeInvoice = async (
|
||||
ctx: RequestContext,
|
||||
params: Record<string, unknown>
|
||||
params: Record<string, unknown>,
|
||||
): Promise<NwcResponse> => {
|
||||
const amountMsat = Number(params.amount)
|
||||
if (!Number.isInteger(amountMsat) || amountMsat <= 0) {
|
||||
return errResult(
|
||||
'make_invoice',
|
||||
'OTHER',
|
||||
'Amount must be a positive whole number of msat.'
|
||||
)
|
||||
return errResult('make_invoice', 'OTHER', 'Amount must be a positive whole number of msat.')
|
||||
}
|
||||
const mint = ctx.deps.getDefaultMint()
|
||||
if (!mint) {
|
||||
@@ -65,11 +59,7 @@ const handleMakeInvoice = async (
|
||||
try {
|
||||
prepared = await prepareMint(mint, amountMsat, ctx.deps.kit ?? {})
|
||||
} catch (err) {
|
||||
return errResult(
|
||||
'make_invoice',
|
||||
'INTERNAL',
|
||||
err instanceof Error ? err.message : String(err)
|
||||
)
|
||||
return errResult('make_invoice', 'INTERNAL', err instanceof Error ? err.message : String(err))
|
||||
}
|
||||
const entry: PendingInvoice = {
|
||||
invoice: prepared.invoice,
|
||||
@@ -77,7 +67,7 @@ const handleMakeInvoice = async (
|
||||
amountMsat: prepared.grossMsat,
|
||||
createdAt: ctx.nowSeconds(),
|
||||
prepared,
|
||||
state: 'pending'
|
||||
state: 'pending',
|
||||
}
|
||||
if (typeof params.description === 'string' && params.description) {
|
||||
entry.description = params.description
|
||||
@@ -88,30 +78,29 @@ const handleMakeInvoice = async (
|
||||
}
|
||||
ctx.invoices.set(entry.paymentHash, entry)
|
||||
// phase two runs in the background; the invoice goes out now and
|
||||
// lookup_invoice reports the settlement the claim observes
|
||||
void settleAndClaim(ctx, entry).catch(err => {
|
||||
// lookup_invoice reports the settlement the service-owned claim observes
|
||||
const started = ctx.startBackground(() =>
|
||||
settleAndClaim(ctx, entry).catch((err) => {
|
||||
entry.state = 'failed'
|
||||
// an interrupted claim poll is normal service teardown (stop
|
||||
// aborted it), not a background failure worth surfacing
|
||||
if (err instanceof PollAbortedError) return
|
||||
ctx.deps.onError?.(err, ctx.connection())
|
||||
}),
|
||||
)
|
||||
if (!started) {
|
||||
entry.state = 'failed'
|
||||
ctx.deps.onError?.(err, ctx.connection())
|
||||
})
|
||||
return errResult('make_invoice', 'INTERNAL', 'The wallet service is stopping.')
|
||||
}
|
||||
return okResult('make_invoice', invoiceResult(entry))
|
||||
}
|
||||
|
||||
const handleLookupInvoice = (
|
||||
ctx: RequestContext,
|
||||
params: Record<string, unknown>
|
||||
): NwcResponse => {
|
||||
const invoiceParam =
|
||||
typeof params.invoice === 'string' ? params.invoice : undefined
|
||||
const handleLookupInvoice = (ctx: RequestContext, params: Record<string, unknown>): NwcResponse => {
|
||||
const invoiceParam = typeof params.invoice === 'string' ? params.invoice : undefined
|
||||
const hashParam =
|
||||
typeof params.payment_hash === 'string'
|
||||
? params.payment_hash.toLowerCase()
|
||||
: undefined
|
||||
typeof params.payment_hash === 'string' ? params.payment_hash.toLowerCase() : undefined
|
||||
if (!invoiceParam && !hashParam) {
|
||||
return errResult(
|
||||
'lookup_invoice',
|
||||
'OTHER',
|
||||
'Provide an invoice or a payment hash.'
|
||||
)
|
||||
return errResult('lookup_invoice', 'OTHER', 'Provide an invoice or a payment hash.')
|
||||
}
|
||||
let entry = hashParam ? ctx.invoices.get(hashParam) : undefined
|
||||
if (!entry && invoiceParam) {
|
||||
@@ -128,10 +117,7 @@ const handleLookupInvoice = (
|
||||
return okResult('lookup_invoice', invoiceResult(entry))
|
||||
}
|
||||
|
||||
export const dispatch = async (
|
||||
ctx: RequestContext,
|
||||
request: NwcRequest
|
||||
): Promise<NwcResponse> => {
|
||||
export const dispatch = async (ctx: RequestContext, request: NwcRequest): Promise<NwcResponse> => {
|
||||
switch (request.method) {
|
||||
case 'get_info':
|
||||
return handleGetInfo(ctx)
|
||||
@@ -144,10 +130,6 @@ export const dispatch = async (
|
||||
case 'lookup_invoice':
|
||||
return handleLookupInvoice(ctx, request.params)
|
||||
default:
|
||||
return errResult(
|
||||
request.method,
|
||||
'NOT_IMPLEMENTED',
|
||||
`Unknown method: ${request.method}.`
|
||||
)
|
||||
return errResult(request.method, 'NOT_IMPLEMENTED', `Unknown method: ${request.method}.`)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -29,7 +29,7 @@ export const NWC_METHODS = [
|
||||
'get_balance',
|
||||
'make_invoice',
|
||||
'pay_invoice',
|
||||
'lookup_invoice'
|
||||
'lookup_invoice',
|
||||
] as const
|
||||
|
||||
export type NwcMethod = (typeof NWC_METHODS)[number]
|
||||
@@ -61,17 +61,13 @@ export type NwcResponse = {
|
||||
export const okResult = (method: string, result: unknown): NwcResponse => ({
|
||||
result_type: method,
|
||||
error: null,
|
||||
result
|
||||
result,
|
||||
})
|
||||
|
||||
export const errResult = (
|
||||
method: string,
|
||||
code: NwcErrorCode,
|
||||
message: string
|
||||
): NwcResponse => ({
|
||||
export const errResult = (method: string, code: NwcErrorCode, message: string): NwcResponse => ({
|
||||
result_type: method,
|
||||
error: {code, message},
|
||||
result: null
|
||||
result: null,
|
||||
})
|
||||
|
||||
// the two encryption schemes this service speaks; the scheme of a request
|
||||
@@ -79,16 +75,14 @@ export const errResult = (
|
||||
// requested by the client")
|
||||
export type NwcEncryption = 'nip44_v2' | 'nip04'
|
||||
|
||||
const conversationKey = (
|
||||
walletSecretKey: Uint8Array,
|
||||
clientPubkey: string
|
||||
): Uint8Array => nip44v2.utils.getConversationKey(walletSecretKey, clientPubkey)
|
||||
const conversationKey = (walletSecretKey: Uint8Array, clientPubkey: string): Uint8Array =>
|
||||
nip44v2.utils.getConversationKey(walletSecretKey, clientPubkey)
|
||||
|
||||
export const encryptFor = (
|
||||
scheme: NwcEncryption,
|
||||
walletSecretKey: Uint8Array,
|
||||
clientPubkey: string,
|
||||
plaintext: string
|
||||
plaintext: string,
|
||||
): string =>
|
||||
scheme === 'nip44_v2'
|
||||
? nip44v2.encrypt(plaintext, conversationKey(walletSecretKey, clientPubkey))
|
||||
@@ -98,14 +92,14 @@ const decryptFrom = (
|
||||
scheme: NwcEncryption,
|
||||
walletSecretKey: Uint8Array,
|
||||
clientPubkey: string,
|
||||
content: string
|
||||
content: string,
|
||||
): string =>
|
||||
scheme === 'nip44_v2'
|
||||
? nip44v2.decrypt(content, conversationKey(walletSecretKey, clientPubkey))
|
||||
: nip04Decrypt(walletSecretKey, clientPubkey, content)
|
||||
|
||||
const tagValue = (event: NostrEvent, name: string): string | undefined =>
|
||||
event.tags.find(t => t[0] === name)?.[1]
|
||||
event.tags.find((t) => t[0] === name)?.[1]
|
||||
|
||||
// The outcome of validating + decrypting a candidate request event:
|
||||
// - a request to dispatch (encryption scheme carried so the response can
|
||||
@@ -126,7 +120,7 @@ export const decryptRequest = (
|
||||
walletServicePubkey: string,
|
||||
clientPubkey: string,
|
||||
event: NostrEvent,
|
||||
nowSeconds: number = Math.floor(Date.now() / 1000)
|
||||
nowSeconds: number = Math.floor(Date.now() / 1000),
|
||||
): DecryptedNwcRequest | null => {
|
||||
if (event.kind !== NWC_REQUEST_KIND) return null
|
||||
// only the authorized client may talk to this connection, and the
|
||||
@@ -155,8 +149,8 @@ export const decryptRequest = (
|
||||
response: errResult(
|
||||
'',
|
||||
'UNSUPPORTED_ENCRYPTION',
|
||||
`Unsupported encryption scheme: ${advertised}.`
|
||||
)
|
||||
`Unsupported encryption scheme: ${advertised}.`,
|
||||
),
|
||||
}
|
||||
}
|
||||
let plaintext: string
|
||||
@@ -173,7 +167,7 @@ export const decryptRequest = (
|
||||
return {
|
||||
respond: true,
|
||||
encryption,
|
||||
response: errResult('', 'OTHER', 'The request is not valid JSON.')
|
||||
response: errResult('', 'OTHER', 'The request is not valid JSON.'),
|
||||
}
|
||||
}
|
||||
if (
|
||||
@@ -185,14 +179,11 @@ export const decryptRequest = (
|
||||
return {
|
||||
respond: true,
|
||||
encryption,
|
||||
response: errResult('', 'OTHER', 'The request has no method.')
|
||||
response: errResult('', 'OTHER', 'The request has no method.'),
|
||||
}
|
||||
}
|
||||
const request = data as NwcRequest
|
||||
const params =
|
||||
typeof request.params === 'object' && request.params !== null
|
||||
? request.params
|
||||
: {}
|
||||
const params = typeof request.params === 'object' && request.params !== null ? request.params : {}
|
||||
return {respond: false, request: {method: request.method, params}, encryption}
|
||||
}
|
||||
|
||||
@@ -204,7 +195,7 @@ export const buildResponseEvent = (
|
||||
encryption: NwcEncryption,
|
||||
requestEventId: string,
|
||||
response: NwcResponse,
|
||||
createdAt: number = Math.floor(Date.now() / 1000)
|
||||
createdAt: number = Math.floor(Date.now() / 1000),
|
||||
): NostrEvent =>
|
||||
finalizeEvent(
|
||||
{
|
||||
@@ -213,29 +204,24 @@ export const buildResponseEvent = (
|
||||
tags: [
|
||||
['p', clientPubkey],
|
||||
['e', requestEventId],
|
||||
['encryption', encryption]
|
||||
['encryption', encryption],
|
||||
],
|
||||
content: encryptFor(
|
||||
encryption,
|
||||
walletSecretKey,
|
||||
clientPubkey,
|
||||
JSON.stringify(response)
|
||||
)
|
||||
content: encryptFor(encryption, walletSecretKey, clientPubkey, JSON.stringify(response)),
|
||||
},
|
||||
walletSecretKey
|
||||
walletSecretKey,
|
||||
)
|
||||
|
||||
// the replaceable info event advertising this service's capabilities
|
||||
export const buildInfoEvent = (
|
||||
walletSecretKey: Uint8Array,
|
||||
createdAt: number = Math.floor(Date.now() / 1000)
|
||||
createdAt: number = Math.floor(Date.now() / 1000),
|
||||
): NostrEvent =>
|
||||
finalizeEvent(
|
||||
{
|
||||
kind: NWC_INFO_KIND,
|
||||
created_at: createdAt,
|
||||
tags: [['encryption', 'nip44_v2 nip04']],
|
||||
content: NWC_METHODS.join(' ')
|
||||
content: NWC_METHODS.join(' '),
|
||||
},
|
||||
walletSecretKey
|
||||
walletSecretKey,
|
||||
)
|
||||
|
||||
Reference in New Issue
Block a user