This commit is contained in:
boufni95 2023-10-18 20:06:44 +02:00
parent 29f2493d6e
commit 1bf5193be6
19 changed files with 2753 additions and 3014 deletions

View file

@ -70,6 +70,11 @@ The nostr server will send back a message response, and inside the body there wi
- This methods has an __empty__ __request__ body
- output: [LnurlLinkResponse](#LnurlLinkResponse)
- GetLnurlPayLink
- auth type: __User__
- This methods has an __empty__ __request__ body
- output: [LnurlLinkResponse](#LnurlLinkResponse)
- GetLNURLChannelLink
- auth type: __User__
- This methods has an __empty__ __request__ body
@ -85,9 +90,9 @@ The nostr server will send back a message response, and inside the body there wi
- __User__:
- expected context content
- __app_id__: _string_
- __app_user_id__: _string_
- __user_id__: _string_
- __app_id__: _string_
- __Admin__:
- expected context content
@ -100,6 +105,27 @@ The nostr server will send back a message response, and inside the body there wi
## HTTP Methods
### These are the http methods the client implements to communicate with the API
- LndGetInfo
- auth type: __Admin__
- http method: __post__
- http route: __/api/admin/lnd/getinfo__
- input: [LndGetInfoRequest](#LndGetInfoRequest)
- output: [LndGetInfoResponse](#LndGetInfoResponse)
- AddApp
- auth type: __Admin__
- http method: __post__
- http route: __/api/admin/app/add__
- input: [AddAppRequest](#AddAppRequest)
- output: [AuthApp](#AuthApp)
- AuthApp
- auth type: __Admin__
- http method: __post__
- http route: __/api/admin/app/auth__
- input: [AuthAppRequest](#AuthAppRequest)
- output: [AuthApp](#AuthApp)
- Health
- auth type: __Guest__
- http method: __get__
@ -114,13 +140,6 @@ The nostr server will send back a message response, and inside the body there wi
- input: [EncryptionExchangeRequest](#EncryptionExchangeRequest)
- This methods has an __empty__ __response__ body
- LndGetInfo
- auth type: __Admin__
- http method: __post__
- http route: __/api/admin/lnd/getinfo__
- input: [LndGetInfoRequest](#LndGetInfoRequest)
- output: [LndGetInfoResponse](#LndGetInfoResponse)
- SetMockInvoiceAsPaid
- auth type: __Guest__
- http method: __post__
@ -128,19 +147,43 @@ The nostr server will send back a message response, and inside the body there wi
- input: [SetMockInvoiceAsPaidRequest](#SetMockInvoiceAsPaidRequest)
- This methods has an __empty__ __response__ body
- AddApp
- auth type: __Admin__
- http method: __post__
- http route: __/api/admin/app/add__
- input: [AddAppRequest](#AddAppRequest)
- output: [AuthApp](#AuthApp)
- GetLnurlWithdrawInfo
- auth type: __Guest__
- http method: __get__
- http route: __/api/guest/lnurl_withdraw/info__
- the request url __query__ can take the following string items:
- k1
- This methods has an __empty__ __request__ body
- output: [LnurlWithdrawInfoResponse](#LnurlWithdrawInfoResponse)
- AuthApp
- auth type: __Admin__
- http method: __post__
- http route: __/api/admin/app/auth__
- input: [AuthAppRequest](#AuthAppRequest)
- output: [AuthApp](#AuthApp)
- HandleLnurlWithdraw
- auth type: __Guest__
- http method: __get__
- http route: __/api/guest/lnurl_withdraw/handle__
- the request url __query__ can take the following string items:
- k1
- pr
- This methods has an __empty__ __request__ body
- This methods has an __empty__ __response__ body
- GetLnurlPayInfo
- auth type: __Guest__
- http method: __get__
- http route: __/api/guest/lnurl_pay/info__
- the request url __query__ can take the following string items:
- k1
- This methods has an __empty__ __request__ body
- output: [LnurlPayInfoResponse](#LnurlPayInfoResponse)
- HandleLnurlPay
- auth type: __Guest__
- http method: __get__
- http route: __/api/guest/lnurl_pay/handle__
- the request url __query__ can take the following string items:
- k1
- amount
- This methods has an __empty__ __request__ body
- output: [HandleLnurlPayResponse](#HandleLnurlPayResponse)
- GetApp
- auth type: __App__
@ -219,20 +262,6 @@ The nostr server will send back a message response, and inside the body there wi
- input: [SetMockAppBalanceRequest](#SetMockAppBalanceRequest)
- This methods has an __empty__ __response__ body
- AddUser
- auth type: __Guest__
- http method: __post__
- http route: __/api/user/add__
- input: [AddUserRequest](#AddUserRequest)
- output: [AddUserResponse](#AddUserResponse)
- AuthUser
- auth type: __Guest__
- http method: __post__
- http route: __/api/user/auth__
- input: [AuthUserRequest](#AuthUserRequest)
- output: [AuthUserResponse](#AuthUserResponse)
- GetUserInfo
- auth type: __User__
- http method: __post__
@ -312,43 +341,12 @@ The nostr server will send back a message response, and inside the body there wi
- This methods has an __empty__ __request__ body
- output: [LnurlLinkResponse](#LnurlLinkResponse)
- GetLnurlWithdrawInfo
- auth type: __Guest__
- GetLnurlPayLink
- auth type: __User__
- http method: __get__
- http route: __/api/guest/lnurl_withdraw/info__
- the request url __query__ can take the following string items:
- k1
- http route: __/api/user/lnurl_pay/link__
- This methods has an __empty__ __request__ body
- output: [LnurlWithdrawInfoResponse](#LnurlWithdrawInfoResponse)
- HandleLnurlWithdraw
- auth type: __Guest__
- http method: __get__
- http route: __/api/guest/lnurl_withdraw/handle__
- the request url __query__ can take the following string items:
- k1
- pr
- This methods has an __empty__ __request__ body
- This methods has an __empty__ __response__ body
- GetLnurlPayInfo
- auth type: __Guest__
- http method: __get__
- http route: __/api/guest/lnurl_pay/info__
- the request url __query__ can take the following string items:
- k1
- This methods has an __empty__ __request__ body
- output: [LnurlPayInfoResponse](#LnurlPayInfoResponse)
- HandleLnurlPay
- auth type: __Guest__
- http method: __get__
- http route: __/api/guest/lnurl_pay/handle__
- the request url __query__ can take the following string items:
- k1
- amount
- This methods has an __empty__ __request__ body
- output: [HandleLnurlPayResponse](#HandleLnurlPayResponse)
- output: [LnurlLinkResponse](#LnurlLinkResponse)
- GetLNURLChannelLink
- auth type: __User__
@ -362,64 +360,44 @@ The nostr server will send back a message response, and inside the body there wi
## Messages
### The content of requests and response from the methods
### NewAddressRequest
- __addressType__: _[AddressType](#AddressType)_
### EncryptionExchangeRequest
- __publicKey__: _string_
- __deviceId__: _string_
### NewAddressResponse
- __address__: _string_
### LnurlPayInfoResponse
- __tag__: _string_
- __callback__: _string_
- __maxSendable__: _number_
- __minSendable__: _number_
- __metadata__: _string_
### AddAppUserRequest
- __identifier__: _string_
- __fail_if_exists__: _boolean_
- __balance__: _number_
### PayAppUserInvoiceRequest
- __user_identifier__: _string_
- __invoice__: _string_
- __amount__: _number_
### PayInvoiceResponse
- __preimage__: _string_
- __amount_paid__: _number_
### SetMockAppUserBalanceRequest
- __user_identifier__: _string_
- __amount__: _number_
### AuthUserResponse
- __userId__: _string_
- __authToken__: _string_
### HandleLnurlPayResponse
- __pr__: _string_
- __routes__: ARRAY of: _[Empty](#Empty)_
### AuthApp
- __app__: _[Application](#Application)_
- __auth_token__: _string_
### UserOperations
- __fromIndex__: _number_
- __toIndex__: _number_
- __operations__: ARRAY of: _[UserOperation](#UserOperation)_
### GetAppUserRequest
- __user_identifier__: _string_
### SendAppUserToAppPaymentRequest
- __from_user_identifier__: _string_
- __amount__: _number_
### Empty
### GetAppUserLNURLInfoRequest
- __user_identifier__: _string_
- __base_url_override__: _string_
### NewInvoiceRequest
- __amountSats__: _number_
- __memo__: _string_
### SendAppUserToAppPaymentRequest
- __from_user_identifier__: _string_
- __amount__: _number_
### AddUserRequest
- __callbackUrl__: _string_
- __name__: _string_
- __secret__: _string_
### UserInfo
- __userId__: _string_
- __balance__: _number_
### GetUserOperationsRequest
- __latestIncomingInvoice__: _number_
- __latestOutgoingInvoice__: _number_
- __latestIncomingTx__: _number_
- __latestOutgoingTx__: _number_
- __latestIncomingUserToUserPayment__: _number_
- __latestOutgoingUserToUserPayment__: _number_
### UserOperation
- __paidAtUnix__: _number_
@ -427,26 +405,48 @@ The nostr server will send back a message response, and inside the body there wi
- __inbound__: _boolean_
- __amount__: _number_
### AddAppUserInvoiceRequest
- __receiver_identifier__: _string_
- __payer_identifier__: _string_
- __http_callback_url__: _string_
- __invoice_req__: _[NewInvoiceRequest](#NewInvoiceRequest)_
### Product
- __id__: _string_
- __name__: _string_
- __price_sats__: _number_
### GetProductBuyLinkResponse
- __link__: _string_
### LndGetInfoResponse
- __alias__: _string_
### SetMockInvoiceAsPaidRequest
- __invoice__: _string_
### AddAppUserRequest
- __identifier__: _string_
- __fail_if_exists__: _boolean_
- __balance__: _number_
### OpenChannelResponse
- __channelId__: _string_
### LnurlLinkResponse
- __lnurl__: _string_
- __k1__: _string_
### AddProductRequest
- __name__: _string_
- __price_sats__: _number_
### DecodeInvoiceResponse
- __amount__: _number_
### PayInvoiceRequest
- __invoice__: _string_
- __amount__: _number_
### LnurlLinkResponse
- __lnurl__: _string_
- __k1__: _string_
### AuthApp
- __app__: _[Application](#Application)_
- __auth_token__: _string_
### AppUser
- __identifier__: _string_
- __info__: _[UserInfo](#UserInfo)_
- __max_withdrawable__: _number_
### PayAddressResponse
- __txId__: _string_
### LnurlWithdrawInfoResponse
- __tag__: _string_
@ -458,13 +458,41 @@ The nostr server will send back a message response, and inside the body there wi
- __balanceCheck__: _string_
- __payLink__: _string_
### GetUserOperationsRequest
- __latestIncomingInvoice__: _number_
- __latestOutgoingInvoice__: _number_
- __latestIncomingTx__: _number_
- __latestOutgoingTx__: _number_
- __latestIncomingUserToUserPayment__: _number_
- __latestOutgoingUserToUserPayment__: _number_
### LndGetInfoRequest
- __nodeId__: _number_
### SetMockInvoiceAsPaidRequest
- __invoice__: _string_
- __amount__: _number_
### PayAppUserInvoiceRequest
- __user_identifier__: _string_
- __invoice__: _string_
- __amount__: _number_
### SendAppUserToAppUserPaymentRequest
- __from_user_identifier__: _string_
- __to_user_identifier__: _string_
- __amount__: _number_
### SetMockAppBalanceRequest
- __amount__: _number_
### NewAddressRequest
- __addressType__: _[AddressType](#AddressType)_
### NewAddressResponse
- __address__: _string_
### NewInvoiceResponse
- __invoice__: _string_
### AddAppRequest
- __name__: _string_
- __allow_user_creation__: _boolean_
### GetAppUserRequest
- __user_identifier__: _string_
### GetUserOperationsResponse
- __latestOutgoingInvoiceOperations__: _[UserOperations](#UserOperations)_
@ -474,46 +502,8 @@ The nostr server will send back a message response, and inside the body there wi
- __latestOutgoingUserToUserPayemnts__: _[UserOperations](#UserOperations)_
- __latestIncomingUserToUserPayemnts__: _[UserOperations](#UserOperations)_
### LndGetInfoRequest
- __nodeId__: _number_
### Application
- __name__: _string_
- __id__: _string_
- __balance__: _number_
- __npub__: _string_
### PayAppUserInvoiceResponse
- __preimage__: _string_
- __amount_paid__: _number_
### DecodeInvoiceResponse
- __amount__: _number_
### AuthUserRequest
- __name__: _string_
- __secret__: _string_
### EncryptionExchangeRequest
- __publicKey__: _string_
- __deviceId__: _string_
### SendAppUserToAppUserPaymentRequest
- __from_user_identifier__: _string_
- __to_user_identifier__: _string_
- __amount__: _number_
### PayAddressRequest
- __address__: _string_
- __amoutSats__: _number_
- __satsPerVByte__: _number_
### NewInvoiceResponse
- __invoice__: _string_
### PayInvoiceResponse
- __preimage__: _string_
- __amount_paid__: _number_
### GetProductBuyLinkResponse
- __link__: _string_
### OpenChannelRequest
- __destination__: _string_
@ -521,62 +511,53 @@ The nostr server will send back a message response, and inside the body there wi
- __pushAmount__: _number_
- __closeAddress__: _string_
### UserOperations
- __fromIndex__: _number_
- __toIndex__: _number_
- __operations__: ARRAY of: _[UserOperation](#UserOperation)_
### LnurlPayInfoResponse
- __tag__: _string_
- __callback__: _string_
- __maxSendable__: _number_
- __minSendable__: _number_
- __metadata__: _string_
### AddProductRequest
- __name__: _string_
- __price_sats__: _number_
### AddAppUserInvoiceRequest
- __receiver_identifier__: _string_
- __payer_identifier__: _string_
- __http_callback_url__: _string_
- __invoice_req__: _[NewInvoiceRequest](#NewInvoiceRequest)_
### AddAppRequest
- __name__: _string_
- __allow_user_creation__: _boolean_
### Product
- __id__: _string_
- __name__: _string_
- __price_sats__: _number_
### AppUser
- __identifier__: _string_
- __info__: _[UserInfo](#UserInfo)_
- __max_withdrawable__: _number_
### UserInfo
- __userId__: _string_
- __balance__: _number_
### AddAppInvoiceRequest
- __payer_identifier__: _string_
- __http_callback_url__: _string_
- __invoice_req__: _[NewInvoiceRequest](#NewInvoiceRequest)_
### PayAddressResponse
- __txId__: _string_
### PayAppUserInvoiceResponse
- __preimage__: _string_
- __amount_paid__: _number_
### OpenChannelResponse
- __channelId__: _string_
### PayAddressRequest
- __address__: _string_
- __amoutSats__: _number_
- __satsPerVByte__: _number_
### HandleLnurlPayResponse
- __pr__: _string_
- __routes__: ARRAY of: _[Empty](#Empty)_
### NewInvoiceRequest
- __amountSats__: _number_
- __memo__: _string_
### AddUserResponse
- __userId__: _string_
- __authToken__: _string_
### DecodeInvoiceRequest
- __invoice__: _string_
### AuthAppRequest
- __name__: _string_
- __allow_user_creation__: _boolean_ *this field is optional
### LndGetInfoResponse
- __alias__: _string_
### SetMockAppBalanceRequest
- __amount__: _number_
### DecodeInvoiceRequest
- __invoice__: _string_
### Empty
### Application
- __name__: _string_
- __id__: _string_
- __balance__: _number_
- __npub__: _string_
## Enums
### The enumerators used in the messages

File diff suppressed because it is too large Load diff

View file

@ -31,31 +31,6 @@ export default (methods: Types.ServerMethods, opts: ServerOptions) => {
app.use(urlencoded({ extended: true }))
if (opts.logMethod) app.use((req, _, next) => { console.log(req.method, req.path); if (opts.logBody) console.log(req.body); next() })
const overrides = opts.overrides || {} as MethodsOverride
if (!opts.allowNotImplementedMethods && !methods.Health) throw new Error('method: Health is not implemented')
app.get('/api/health', async (req, res) => {
try {
if (!methods.Health) throw new Error('method: Health is not implemented')
const authContext = await opts.GuestAuthGuard(req.headers['authorization'])
const query = req.query
const params = req.params
await methods.Health({ ...authContext, ...query, ...params })
if (overrides.Health_Override) await overrides.Health_Override(res); else res.json({status: 'OK'})
} catch (ex) { const e = ex as any; logErrorAndReturnResponse(e, e.message || e, res, logger); if (opts.throwErrors) throw e }
})
if (!opts.allowNotImplementedMethods && !methods.EncryptionExchange) throw new Error('method: EncryptionExchange is not implemented')
app.post('/api/encryption/exchange', async (req, res) => {
try {
if (!methods.EncryptionExchange) throw new Error('method: EncryptionExchange is not implemented')
const authContext = await opts.GuestAuthGuard(req.headers['authorization'])
const request = req.body
const error = Types.EncryptionExchangeRequestValidate(request)
if (error !== null) return logErrorAndReturnResponse(error, 'invalid request body', res, logger)
const query = req.query
const params = req.params
await methods.EncryptionExchange({ ...authContext, ...query, ...params }, request)
if (overrides.EncryptionExchange_Override) await overrides.EncryptionExchange_Override(res); else res.json({status: 'OK'})
} catch (ex) { const e = ex as any; logErrorAndReturnResponse(e, e.message || e, res, logger); if (opts.throwErrors) throw e }
})
if (!opts.allowNotImplementedMethods && !methods.LndGetInfo) throw new Error('method: LndGetInfo is not implemented')
app.post('/api/admin/lnd/getinfo', async (req, res) => {
try {
@ -70,20 +45,6 @@ export default (methods: Types.ServerMethods, opts: ServerOptions) => {
if (overrides.LndGetInfo_Override) await overrides.LndGetInfo_Override(res, response); else res.json({status: 'OK', ...response})
} catch (ex) { const e = ex as any; logErrorAndReturnResponse(e, e.message || e, res, logger); if (opts.throwErrors) throw e }
})
if (!opts.allowNotImplementedMethods && !methods.SetMockInvoiceAsPaid) throw new Error('method: SetMockInvoiceAsPaid is not implemented')
app.post('/api/lnd/mock/invoice/paid', async (req, res) => {
try {
if (!methods.SetMockInvoiceAsPaid) throw new Error('method: SetMockInvoiceAsPaid is not implemented')
const authContext = await opts.GuestAuthGuard(req.headers['authorization'])
const request = req.body
const error = Types.SetMockInvoiceAsPaidRequestValidate(request)
if (error !== null) return logErrorAndReturnResponse(error, 'invalid request body', res, logger)
const query = req.query
const params = req.params
await methods.SetMockInvoiceAsPaid({ ...authContext, ...query, ...params }, request)
if (overrides.SetMockInvoiceAsPaid_Override) await overrides.SetMockInvoiceAsPaid_Override(res); else res.json({status: 'OK'})
} catch (ex) { const e = ex as any; logErrorAndReturnResponse(e, e.message || e, res, logger); if (opts.throwErrors) throw e }
})
if (!opts.allowNotImplementedMethods && !methods.AddApp) throw new Error('method: AddApp is not implemented')
app.post('/api/admin/app/add', async (req, res) => {
try {
@ -112,6 +73,89 @@ export default (methods: Types.ServerMethods, opts: ServerOptions) => {
if (overrides.AuthApp_Override) await overrides.AuthApp_Override(res, response); else res.json({status: 'OK', ...response})
} catch (ex) { const e = ex as any; logErrorAndReturnResponse(e, e.message || e, res, logger); if (opts.throwErrors) throw e }
})
if (!opts.allowNotImplementedMethods && !methods.Health) throw new Error('method: Health is not implemented')
app.get('/api/health', async (req, res) => {
try {
if (!methods.Health) throw new Error('method: Health is not implemented')
const authContext = await opts.GuestAuthGuard(req.headers['authorization'])
const query = req.query
const params = req.params
await methods.Health({ ...authContext, ...query, ...params })
if (overrides.Health_Override) await overrides.Health_Override(res); else res.json({status: 'OK'})
} catch (ex) { const e = ex as any; logErrorAndReturnResponse(e, e.message || e, res, logger); if (opts.throwErrors) throw e }
})
if (!opts.allowNotImplementedMethods && !methods.EncryptionExchange) throw new Error('method: EncryptionExchange is not implemented')
app.post('/api/encryption/exchange', async (req, res) => {
try {
if (!methods.EncryptionExchange) throw new Error('method: EncryptionExchange is not implemented')
const authContext = await opts.GuestAuthGuard(req.headers['authorization'])
const request = req.body
const error = Types.EncryptionExchangeRequestValidate(request)
if (error !== null) return logErrorAndReturnResponse(error, 'invalid request body', res, logger)
const query = req.query
const params = req.params
await methods.EncryptionExchange({ ...authContext, ...query, ...params }, request)
if (overrides.EncryptionExchange_Override) await overrides.EncryptionExchange_Override(res); else res.json({status: 'OK'})
} catch (ex) { const e = ex as any; logErrorAndReturnResponse(e, e.message || e, res, logger); if (opts.throwErrors) throw e }
})
if (!opts.allowNotImplementedMethods && !methods.SetMockInvoiceAsPaid) throw new Error('method: SetMockInvoiceAsPaid is not implemented')
app.post('/api/lnd/mock/invoice/paid', async (req, res) => {
try {
if (!methods.SetMockInvoiceAsPaid) throw new Error('method: SetMockInvoiceAsPaid is not implemented')
const authContext = await opts.GuestAuthGuard(req.headers['authorization'])
const request = req.body
const error = Types.SetMockInvoiceAsPaidRequestValidate(request)
if (error !== null) return logErrorAndReturnResponse(error, 'invalid request body', res, logger)
const query = req.query
const params = req.params
await methods.SetMockInvoiceAsPaid({ ...authContext, ...query, ...params }, request)
if (overrides.SetMockInvoiceAsPaid_Override) await overrides.SetMockInvoiceAsPaid_Override(res); else res.json({status: 'OK'})
} catch (ex) { const e = ex as any; logErrorAndReturnResponse(e, e.message || e, res, logger); if (opts.throwErrors) throw e }
})
if (!opts.allowNotImplementedMethods && !methods.GetLnurlWithdrawInfo) throw new Error('method: GetLnurlWithdrawInfo is not implemented')
app.get('/api/guest/lnurl_withdraw/info', async (req, res) => {
try {
if (!methods.GetLnurlWithdrawInfo) throw new Error('method: GetLnurlWithdrawInfo is not implemented')
const authContext = await opts.GuestAuthGuard(req.headers['authorization'])
const query = req.query
const params = req.params
const response = await methods.GetLnurlWithdrawInfo({ ...authContext, ...query, ...params })
if (overrides.GetLnurlWithdrawInfo_Override) await overrides.GetLnurlWithdrawInfo_Override(res, response); else res.json({status: 'OK', ...response})
} catch (ex) { const e = ex as any; logErrorAndReturnResponse(e, e.message || e, res, logger); if (opts.throwErrors) throw e }
})
if (!opts.allowNotImplementedMethods && !methods.HandleLnurlWithdraw) throw new Error('method: HandleLnurlWithdraw is not implemented')
app.get('/api/guest/lnurl_withdraw/handle', async (req, res) => {
try {
if (!methods.HandleLnurlWithdraw) throw new Error('method: HandleLnurlWithdraw is not implemented')
const authContext = await opts.GuestAuthGuard(req.headers['authorization'])
const query = req.query
const params = req.params
await methods.HandleLnurlWithdraw({ ...authContext, ...query, ...params })
if (overrides.HandleLnurlWithdraw_Override) await overrides.HandleLnurlWithdraw_Override(res); else res.json({status: 'OK'})
} catch (ex) { const e = ex as any; logErrorAndReturnResponse(e, e.message || e, res, logger); if (opts.throwErrors) throw e }
})
if (!opts.allowNotImplementedMethods && !methods.GetLnurlPayInfo) throw new Error('method: GetLnurlPayInfo is not implemented')
app.get('/api/guest/lnurl_pay/info', async (req, res) => {
try {
if (!methods.GetLnurlPayInfo) throw new Error('method: GetLnurlPayInfo is not implemented')
const authContext = await opts.GuestAuthGuard(req.headers['authorization'])
const query = req.query
const params = req.params
const response = await methods.GetLnurlPayInfo({ ...authContext, ...query, ...params })
if (overrides.GetLnurlPayInfo_Override) await overrides.GetLnurlPayInfo_Override(res, response); else res.json({status: 'OK', ...response})
} catch (ex) { const e = ex as any; logErrorAndReturnResponse(e, e.message || e, res, logger); if (opts.throwErrors) throw e }
})
if (!opts.allowNotImplementedMethods && !methods.HandleLnurlPay) throw new Error('method: HandleLnurlPay is not implemented')
app.get('/api/guest/lnurl_pay/handle', async (req, res) => {
try {
if (!methods.HandleLnurlPay) throw new Error('method: HandleLnurlPay is not implemented')
const authContext = await opts.GuestAuthGuard(req.headers['authorization'])
const query = req.query
const params = req.params
const response = await methods.HandleLnurlPay({ ...authContext, ...query, ...params })
if (overrides.HandleLnurlPay_Override) await overrides.HandleLnurlPay_Override(res, response); else res.json({status: 'OK', ...response})
} catch (ex) { const e = ex as any; logErrorAndReturnResponse(e, e.message || e, res, logger); if (opts.throwErrors) throw e }
})
if (!opts.allowNotImplementedMethods && !methods.GetApp) throw new Error('method: GetApp is not implemented')
app.post('/api/app/get', async (req, res) => {
try {
@ -263,34 +307,6 @@ export default (methods: Types.ServerMethods, opts: ServerOptions) => {
if (overrides.SetMockAppBalance_Override) await overrides.SetMockAppBalance_Override(res); else res.json({status: 'OK'})
} catch (ex) { const e = ex as any; logErrorAndReturnResponse(e, e.message || e, res, logger); if (opts.throwErrors) throw e }
})
if (!opts.allowNotImplementedMethods && !methods.AddUser) throw new Error('method: AddUser is not implemented')
app.post('/api/user/add', async (req, res) => {
try {
if (!methods.AddUser) throw new Error('method: AddUser is not implemented')
const authContext = await opts.GuestAuthGuard(req.headers['authorization'])
const request = req.body
const error = Types.AddUserRequestValidate(request)
if (error !== null) return logErrorAndReturnResponse(error, 'invalid request body', res, logger)
const query = req.query
const params = req.params
const response = await methods.AddUser({ ...authContext, ...query, ...params }, request)
if (overrides.AddUser_Override) await overrides.AddUser_Override(res, response); else res.json({status: 'OK', ...response})
} catch (ex) { const e = ex as any; logErrorAndReturnResponse(e, e.message || e, res, logger); if (opts.throwErrors) throw e }
})
if (!opts.allowNotImplementedMethods && !methods.AuthUser) throw new Error('method: AuthUser is not implemented')
app.post('/api/user/auth', async (req, res) => {
try {
if (!methods.AuthUser) throw new Error('method: AuthUser is not implemented')
const authContext = await opts.GuestAuthGuard(req.headers['authorization'])
const request = req.body
const error = Types.AuthUserRequestValidate(request)
if (error !== null) return logErrorAndReturnResponse(error, 'invalid request body', res, logger)
const query = req.query
const params = req.params
const response = await methods.AuthUser({ ...authContext, ...query, ...params }, request)
if (overrides.AuthUser_Override) await overrides.AuthUser_Override(res, response); else res.json({status: 'OK', ...response})
} catch (ex) { const e = ex as any; logErrorAndReturnResponse(e, e.message || e, res, logger); if (opts.throwErrors) throw e }
})
if (!opts.allowNotImplementedMethods && !methods.GetUserInfo) throw new Error('method: GetUserInfo is not implemented')
app.post('/api/user/info', async (req, res) => {
try {
@ -436,48 +452,15 @@ export default (methods: Types.ServerMethods, opts: ServerOptions) => {
if (overrides.GetLnurlWithdrawLink_Override) await overrides.GetLnurlWithdrawLink_Override(res, response); else res.json({status: 'OK', ...response})
} catch (ex) { const e = ex as any; logErrorAndReturnResponse(e, e.message || e, res, logger); if (opts.throwErrors) throw e }
})
if (!opts.allowNotImplementedMethods && !methods.GetLnurlWithdrawInfo) throw new Error('method: GetLnurlWithdrawInfo is not implemented')
app.get('/api/guest/lnurl_withdraw/info', async (req, res) => {
if (!opts.allowNotImplementedMethods && !methods.GetLnurlPayLink) throw new Error('method: GetLnurlPayLink is not implemented')
app.get('/api/user/lnurl_pay/link', async (req, res) => {
try {
if (!methods.GetLnurlWithdrawInfo) throw new Error('method: GetLnurlWithdrawInfo is not implemented')
const authContext = await opts.GuestAuthGuard(req.headers['authorization'])
if (!methods.GetLnurlPayLink) throw new Error('method: GetLnurlPayLink is not implemented')
const authContext = await opts.UserAuthGuard(req.headers['authorization'])
const query = req.query
const params = req.params
const response = await methods.GetLnurlWithdrawInfo({ ...authContext, ...query, ...params })
if (overrides.GetLnurlWithdrawInfo_Override) await overrides.GetLnurlWithdrawInfo_Override(res, response); else res.json({status: 'OK', ...response})
} catch (ex) { const e = ex as any; logErrorAndReturnResponse(e, e.message || e, res, logger); if (opts.throwErrors) throw e }
})
if (!opts.allowNotImplementedMethods && !methods.HandleLnurlWithdraw) throw new Error('method: HandleLnurlWithdraw is not implemented')
app.get('/api/guest/lnurl_withdraw/handle', async (req, res) => {
try {
if (!methods.HandleLnurlWithdraw) throw new Error('method: HandleLnurlWithdraw is not implemented')
const authContext = await opts.GuestAuthGuard(req.headers['authorization'])
const query = req.query
const params = req.params
await methods.HandleLnurlWithdraw({ ...authContext, ...query, ...params })
if (overrides.HandleLnurlWithdraw_Override) await overrides.HandleLnurlWithdraw_Override(res); else res.json({status: 'OK'})
} catch (ex) { const e = ex as any; logErrorAndReturnResponse(e, e.message || e, res, logger); if (opts.throwErrors) throw e }
})
if (!opts.allowNotImplementedMethods && !methods.GetLnurlPayInfo) throw new Error('method: GetLnurlPayInfo is not implemented')
app.get('/api/guest/lnurl_pay/info', async (req, res) => {
try {
if (!methods.GetLnurlPayInfo) throw new Error('method: GetLnurlPayInfo is not implemented')
const authContext = await opts.GuestAuthGuard(req.headers['authorization'])
const query = req.query
const params = req.params
const response = await methods.GetLnurlPayInfo({ ...authContext, ...query, ...params })
if (overrides.GetLnurlPayInfo_Override) await overrides.GetLnurlPayInfo_Override(res, response); else res.json({status: 'OK', ...response})
} catch (ex) { const e = ex as any; logErrorAndReturnResponse(e, e.message || e, res, logger); if (opts.throwErrors) throw e }
})
if (!opts.allowNotImplementedMethods && !methods.HandleLnurlPay) throw new Error('method: HandleLnurlPay is not implemented')
app.get('/api/guest/lnurl_pay/handle', async (req, res) => {
try {
if (!methods.HandleLnurlPay) throw new Error('method: HandleLnurlPay is not implemented')
const authContext = await opts.GuestAuthGuard(req.headers['authorization'])
const query = req.query
const params = req.params
const response = await methods.HandleLnurlPay({ ...authContext, ...query, ...params })
if (overrides.HandleLnurlPay_Override) await overrides.HandleLnurlPay_Override(res, response); else res.json({status: 'OK', ...response})
const response = await methods.GetLnurlPayLink({ ...authContext, ...query, ...params })
if (overrides.GetLnurlPayLink_Override) await overrides.GetLnurlPayLink_Override(res, response); else res.json({status: 'OK', ...response})
} catch (ex) { const e = ex as any; logErrorAndReturnResponse(e, e.message || e, res, logger); if (opts.throwErrors) throw e }
})
if (!opts.allowNotImplementedMethods && !methods.GetLNURLChannelLink) throw new Error('method: GetLNURLChannelLink is not implemented')
@ -502,12 +485,16 @@ export default (methods: Types.ServerMethods, opts: ServerOptions) => {
}
}
export type MethodsOverride = {
Health_Override?: (httpRes:Response) => Promise<void>
EncryptionExchange_Override?: (httpRes:Response) => Promise<void>
LndGetInfo_Override?: (httpRes:Response, handlerRes:Types.LndGetInfoResponse) => Promise<void>
SetMockInvoiceAsPaid_Override?: (httpRes:Response) => Promise<void>
AddApp_Override?: (httpRes:Response, handlerRes:Types.AuthApp) => Promise<void>
AuthApp_Override?: (httpRes:Response, handlerRes:Types.AuthApp) => Promise<void>
Health_Override?: (httpRes:Response) => Promise<void>
EncryptionExchange_Override?: (httpRes:Response) => Promise<void>
SetMockInvoiceAsPaid_Override?: (httpRes:Response) => Promise<void>
GetLnurlWithdrawInfo_Override?: (httpRes:Response, handlerRes:Types.LnurlWithdrawInfoResponse) => Promise<void>
HandleLnurlWithdraw_Override?: (httpRes:Response) => Promise<void>
GetLnurlPayInfo_Override?: (httpRes:Response, handlerRes:Types.LnurlPayInfoResponse) => Promise<void>
HandleLnurlPay_Override?: (httpRes:Response, handlerRes:Types.HandleLnurlPayResponse) => Promise<void>
GetApp_Override?: (httpRes:Response, handlerRes:Types.Application) => Promise<void>
AddAppUser_Override?: (httpRes:Response, handlerRes:Types.AppUser) => Promise<void>
AddAppInvoice_Override?: (httpRes:Response, handlerRes:Types.NewInvoiceResponse) => Promise<void>
@ -519,8 +506,6 @@ export type MethodsOverride = {
GetAppUserLNURLInfo_Override?: (httpRes:Response, handlerRes:Types.LnurlPayInfoResponse) => Promise<void>
SetMockAppUserBalance_Override?: (httpRes:Response) => Promise<void>
SetMockAppBalance_Override?: (httpRes:Response) => Promise<void>
AddUser_Override?: (httpRes:Response, handlerRes:Types.AddUserResponse) => Promise<void>
AuthUser_Override?: (httpRes:Response, handlerRes:Types.AuthUserResponse) => Promise<void>
GetUserInfo_Override?: (httpRes:Response, handlerRes:Types.UserInfo) => Promise<void>
AddProduct_Override?: (httpRes:Response, handlerRes:Types.Product) => Promise<void>
NewProductInvoice_Override?: (httpRes:Response, handlerRes:Types.NewInvoiceResponse) => Promise<void>
@ -532,9 +517,6 @@ export type MethodsOverride = {
PayInvoice_Override?: (httpRes:Response, handlerRes:Types.PayInvoiceResponse) => Promise<void>
OpenChannel_Override?: (httpRes:Response, handlerRes:Types.OpenChannelResponse) => Promise<void>
GetLnurlWithdrawLink_Override?: (httpRes:Response, handlerRes:Types.LnurlLinkResponse) => Promise<void>
GetLnurlWithdrawInfo_Override?: (httpRes:Response, handlerRes:Types.LnurlWithdrawInfoResponse) => Promise<void>
HandleLnurlWithdraw_Override?: (httpRes:Response) => Promise<void>
GetLnurlPayInfo_Override?: (httpRes:Response, handlerRes:Types.LnurlPayInfoResponse) => Promise<void>
HandleLnurlPay_Override?: (httpRes:Response, handlerRes:Types.HandleLnurlPayResponse) => Promise<void>
GetLnurlPayLink_Override?: (httpRes:Response, handlerRes:Types.LnurlLinkResponse) => Promise<void>
GetLNURLChannelLink_Override?: (httpRes:Response, handlerRes:Types.LnurlLinkResponse) => Promise<void>
}

View file

@ -15,28 +15,6 @@ export type ClientParams = {
checkResult?: true
}
export default (params: ClientParams) => ({
Health: async (): Promise<ResultError | ({ status: 'OK' })> => {
const auth = await params.retrieveGuestAuth()
if (auth === null) throw new Error('retrieveGuestAuth() returned null')
let finalRoute = '/api/health'
const { data } = await axios.get(params.baseUrl + finalRoute, { headers: { 'authorization': auth } })
if (data.status === 'ERROR' && typeof data.reason === 'string') return data
if (data.status === 'OK') {
return data
}
return { status: 'ERROR', reason: 'invalid response' }
},
EncryptionExchange: async (request: Types.EncryptionExchangeRequest): Promise<ResultError | ({ status: 'OK' })> => {
const auth = await params.retrieveGuestAuth()
if (auth === null) throw new Error('retrieveGuestAuth() returned null')
let finalRoute = '/api/encryption/exchange'
const { data } = await axios.post(params.baseUrl + finalRoute, request, { headers: { 'authorization': auth } })
if (data.status === 'ERROR' && typeof data.reason === 'string') return data
if (data.status === 'OK') {
return data
}
return { status: 'ERROR', reason: 'invalid response' }
},
LndGetInfo: async (request: Types.LndGetInfoRequest): Promise<ResultError | ({ status: 'OK' }& Types.LndGetInfoResponse)> => {
const auth = await params.retrieveAdminAuth()
if (auth === null) throw new Error('retrieveAdminAuth() returned null')
@ -51,17 +29,6 @@ export default (params: ClientParams) => ({
}
return { status: 'ERROR', reason: 'invalid response' }
},
SetMockInvoiceAsPaid: async (request: Types.SetMockInvoiceAsPaidRequest): Promise<ResultError | ({ status: 'OK' })> => {
const auth = await params.retrieveGuestAuth()
if (auth === null) throw new Error('retrieveGuestAuth() returned null')
let finalRoute = '/api/lnd/mock/invoice/paid'
const { data } = await axios.post(params.baseUrl + finalRoute, request, { headers: { 'authorization': auth } })
if (data.status === 'ERROR' && typeof data.reason === 'string') return data
if (data.status === 'OK') {
return data
}
return { status: 'ERROR', reason: 'invalid response' }
},
AddApp: async (request: Types.AddAppRequest): Promise<ResultError | ({ status: 'OK' }& Types.AuthApp)> => {
const auth = await params.retrieveAdminAuth()
if (auth === null) throw new Error('retrieveAdminAuth() returned null')
@ -90,6 +57,100 @@ export default (params: ClientParams) => ({
}
return { status: 'ERROR', reason: 'invalid response' }
},
Health: async (): Promise<ResultError | ({ status: 'OK' })> => {
const auth = await params.retrieveGuestAuth()
if (auth === null) throw new Error('retrieveGuestAuth() returned null')
let finalRoute = '/api/health'
const { data } = await axios.get(params.baseUrl + finalRoute, { headers: { 'authorization': auth } })
if (data.status === 'ERROR' && typeof data.reason === 'string') return data
if (data.status === 'OK') {
return data
}
return { status: 'ERROR', reason: 'invalid response' }
},
EncryptionExchange: async (request: Types.EncryptionExchangeRequest): Promise<ResultError | ({ status: 'OK' })> => {
const auth = await params.retrieveGuestAuth()
if (auth === null) throw new Error('retrieveGuestAuth() returned null')
let finalRoute = '/api/encryption/exchange'
const { data } = await axios.post(params.baseUrl + finalRoute, request, { headers: { 'authorization': auth } })
if (data.status === 'ERROR' && typeof data.reason === 'string') return data
if (data.status === 'OK') {
return data
}
return { status: 'ERROR', reason: 'invalid response' }
},
SetMockInvoiceAsPaid: async (request: Types.SetMockInvoiceAsPaidRequest): Promise<ResultError | ({ status: 'OK' })> => {
const auth = await params.retrieveGuestAuth()
if (auth === null) throw new Error('retrieveGuestAuth() returned null')
let finalRoute = '/api/lnd/mock/invoice/paid'
const { data } = await axios.post(params.baseUrl + finalRoute, request, { headers: { 'authorization': auth } })
if (data.status === 'ERROR' && typeof data.reason === 'string') return data
if (data.status === 'OK') {
return data
}
return { status: 'ERROR', reason: 'invalid response' }
},
GetLnurlWithdrawInfo: async (query: Types.GetLnurlWithdrawInfo_Query): Promise<ResultError | ({ status: 'OK' }& Types.LnurlWithdrawInfoResponse)> => {
const auth = await params.retrieveGuestAuth()
if (auth === null) throw new Error('retrieveGuestAuth() returned null')
let finalRoute = '/api/guest/lnurl_withdraw/info'
const q = (new URLSearchParams(query)).toString()
finalRoute = finalRoute + (q === '' ? '' : '?' + q)
const { data } = await axios.get(params.baseUrl + finalRoute, { headers: { 'authorization': auth } })
if (data.status === 'ERROR' && typeof data.reason === 'string') return data
if (data.status === 'OK') {
const result = data
if(!params.checkResult) return { status: 'OK', ...result }
const error = Types.LnurlWithdrawInfoResponseValidate(result)
if (error === null) { return { status: 'OK', ...result } } else return { status: 'ERROR', reason: error.message }
}
return { status: 'ERROR', reason: 'invalid response' }
},
HandleLnurlWithdraw: async (query: Types.HandleLnurlWithdraw_Query): Promise<ResultError | ({ status: 'OK' })> => {
const auth = await params.retrieveGuestAuth()
if (auth === null) throw new Error('retrieveGuestAuth() returned null')
let finalRoute = '/api/guest/lnurl_withdraw/handle'
const q = (new URLSearchParams(query)).toString()
finalRoute = finalRoute + (q === '' ? '' : '?' + q)
const { data } = await axios.get(params.baseUrl + finalRoute, { headers: { 'authorization': auth } })
if (data.status === 'ERROR' && typeof data.reason === 'string') return data
if (data.status === 'OK') {
return data
}
return { status: 'ERROR', reason: 'invalid response' }
},
GetLnurlPayInfo: async (query: Types.GetLnurlPayInfo_Query): Promise<ResultError | ({ status: 'OK' }& Types.LnurlPayInfoResponse)> => {
const auth = await params.retrieveGuestAuth()
if (auth === null) throw new Error('retrieveGuestAuth() returned null')
let finalRoute = '/api/guest/lnurl_pay/info'
const q = (new URLSearchParams(query)).toString()
finalRoute = finalRoute + (q === '' ? '' : '?' + q)
const { data } = await axios.get(params.baseUrl + finalRoute, { headers: { 'authorization': auth } })
if (data.status === 'ERROR' && typeof data.reason === 'string') return data
if (data.status === 'OK') {
const result = data
if(!params.checkResult) return { status: 'OK', ...result }
const error = Types.LnurlPayInfoResponseValidate(result)
if (error === null) { return { status: 'OK', ...result } } else return { status: 'ERROR', reason: error.message }
}
return { status: 'ERROR', reason: 'invalid response' }
},
HandleLnurlPay: async (query: Types.HandleLnurlPay_Query): Promise<ResultError | ({ status: 'OK' }& Types.HandleLnurlPayResponse)> => {
const auth = await params.retrieveGuestAuth()
if (auth === null) throw new Error('retrieveGuestAuth() returned null')
let finalRoute = '/api/guest/lnurl_pay/handle'
const q = (new URLSearchParams(query)).toString()
finalRoute = finalRoute + (q === '' ? '' : '?' + q)
const { data } = await axios.get(params.baseUrl + finalRoute, { headers: { 'authorization': auth } })
if (data.status === 'ERROR' && typeof data.reason === 'string') return data
if (data.status === 'OK') {
const result = data
if(!params.checkResult) return { status: 'OK', ...result }
const error = Types.HandleLnurlPayResponseValidate(result)
if (error === null) { return { status: 'OK', ...result } } else return { status: 'ERROR', reason: error.message }
}
return { status: 'ERROR', reason: 'invalid response' }
},
GetApp: async (): Promise<ResultError | ({ status: 'OK' }& Types.Application)> => {
const auth = await params.retrieveAppAuth()
if (auth === null) throw new Error('retrieveAppAuth() returned null')
@ -232,34 +293,6 @@ export default (params: ClientParams) => ({
}
return { status: 'ERROR', reason: 'invalid response' }
},
AddUser: async (request: Types.AddUserRequest): Promise<ResultError | ({ status: 'OK' }& Types.AddUserResponse)> => {
const auth = await params.retrieveGuestAuth()
if (auth === null) throw new Error('retrieveGuestAuth() returned null')
let finalRoute = '/api/user/add'
const { data } = await axios.post(params.baseUrl + finalRoute, request, { headers: { 'authorization': auth } })
if (data.status === 'ERROR' && typeof data.reason === 'string') return data
if (data.status === 'OK') {
const result = data
if(!params.checkResult) return { status: 'OK', ...result }
const error = Types.AddUserResponseValidate(result)
if (error === null) { return { status: 'OK', ...result } } else return { status: 'ERROR', reason: error.message }
}
return { status: 'ERROR', reason: 'invalid response' }
},
AuthUser: async (request: Types.AuthUserRequest): Promise<ResultError | ({ status: 'OK' }& Types.AuthUserResponse)> => {
const auth = await params.retrieveGuestAuth()
if (auth === null) throw new Error('retrieveGuestAuth() returned null')
let finalRoute = '/api/user/auth'
const { data } = await axios.post(params.baseUrl + finalRoute, request, { headers: { 'authorization': auth } })
if (data.status === 'ERROR' && typeof data.reason === 'string') return data
if (data.status === 'OK') {
const result = data
if(!params.checkResult) return { status: 'OK', ...result }
const error = Types.AuthUserResponseValidate(result)
if (error === null) { return { status: 'OK', ...result } } else return { status: 'ERROR', reason: error.message }
}
return { status: 'ERROR', reason: 'invalid response' }
},
GetUserInfo: async (): Promise<ResultError | ({ status: 'OK' }& Types.UserInfo)> => {
const auth = await params.retrieveUserAuth()
if (auth === null) throw new Error('retrieveUserAuth() returned null')
@ -416,63 +449,16 @@ export default (params: ClientParams) => ({
}
return { status: 'ERROR', reason: 'invalid response' }
},
GetLnurlWithdrawInfo: async (query: Types.GetLnurlWithdrawInfo_Query): Promise<ResultError | ({ status: 'OK' }& Types.LnurlWithdrawInfoResponse)> => {
const auth = await params.retrieveGuestAuth()
if (auth === null) throw new Error('retrieveGuestAuth() returned null')
let finalRoute = '/api/guest/lnurl_withdraw/info'
const q = (new URLSearchParams(query)).toString()
finalRoute = finalRoute + (q === '' ? '' : '?' + q)
GetLnurlPayLink: async (): Promise<ResultError | ({ status: 'OK' }& Types.LnurlLinkResponse)> => {
const auth = await params.retrieveUserAuth()
if (auth === null) throw new Error('retrieveUserAuth() returned null')
let finalRoute = '/api/user/lnurl_pay/link'
const { data } = await axios.get(params.baseUrl + finalRoute, { headers: { 'authorization': auth } })
if (data.status === 'ERROR' && typeof data.reason === 'string') return data
if (data.status === 'OK') {
const result = data
if(!params.checkResult) return { status: 'OK', ...result }
const error = Types.LnurlWithdrawInfoResponseValidate(result)
if (error === null) { return { status: 'OK', ...result } } else return { status: 'ERROR', reason: error.message }
}
return { status: 'ERROR', reason: 'invalid response' }
},
HandleLnurlWithdraw: async (query: Types.HandleLnurlWithdraw_Query): Promise<ResultError | ({ status: 'OK' })> => {
const auth = await params.retrieveGuestAuth()
if (auth === null) throw new Error('retrieveGuestAuth() returned null')
let finalRoute = '/api/guest/lnurl_withdraw/handle'
const q = (new URLSearchParams(query)).toString()
finalRoute = finalRoute + (q === '' ? '' : '?' + q)
const { data } = await axios.get(params.baseUrl + finalRoute, { headers: { 'authorization': auth } })
if (data.status === 'ERROR' && typeof data.reason === 'string') return data
if (data.status === 'OK') {
return data
}
return { status: 'ERROR', reason: 'invalid response' }
},
GetLnurlPayInfo: async (query: Types.GetLnurlPayInfo_Query): Promise<ResultError | ({ status: 'OK' }& Types.LnurlPayInfoResponse)> => {
const auth = await params.retrieveGuestAuth()
if (auth === null) throw new Error('retrieveGuestAuth() returned null')
let finalRoute = '/api/guest/lnurl_pay/info'
const q = (new URLSearchParams(query)).toString()
finalRoute = finalRoute + (q === '' ? '' : '?' + q)
const { data } = await axios.get(params.baseUrl + finalRoute, { headers: { 'authorization': auth } })
if (data.status === 'ERROR' && typeof data.reason === 'string') return data
if (data.status === 'OK') {
const result = data
if(!params.checkResult) return { status: 'OK', ...result }
const error = Types.LnurlPayInfoResponseValidate(result)
if (error === null) { return { status: 'OK', ...result } } else return { status: 'ERROR', reason: error.message }
}
return { status: 'ERROR', reason: 'invalid response' }
},
HandleLnurlPay: async (query: Types.HandleLnurlPay_Query): Promise<ResultError | ({ status: 'OK' }& Types.HandleLnurlPayResponse)> => {
const auth = await params.retrieveGuestAuth()
if (auth === null) throw new Error('retrieveGuestAuth() returned null')
let finalRoute = '/api/guest/lnurl_pay/handle'
const q = (new URLSearchParams(query)).toString()
finalRoute = finalRoute + (q === '' ? '' : '?' + q)
const { data } = await axios.get(params.baseUrl + finalRoute, { headers: { 'authorization': auth } })
if (data.status === 'ERROR' && typeof data.reason === 'string') return data
if (data.status === 'OK') {
const result = data
if(!params.checkResult) return { status: 'OK', ...result }
const error = Types.HandleLnurlPayResponseValidate(result)
const error = Types.LnurlLinkResponseValidate(result)
if (error === null) { return { status: 'OK', ...result } } else return { status: 'ERROR', reason: error.message }
}
return { status: 'ERROR', reason: 'invalid response' }

View file

@ -172,6 +172,20 @@ export default (params: NostrClientParams, send: (to:string, message: NostrRequ
}
return { status: 'ERROR', reason: 'invalid response' }
},
GetLnurlPayLink: async (): Promise<ResultError | ({ status: 'OK' }& Types.LnurlLinkResponse)> => {
const auth = await params.retrieveNostrUserAuth()
if (auth === null) throw new Error('retrieveNostrUserAuth() returned null')
const nostrRequest: NostrRequest = {}
const data = await send(params.pubDestination, {rpcName:'GetLnurlPayLink',authIdentifier:auth, ...nostrRequest })
if (data.status === 'ERROR' && typeof data.reason === 'string') return data
if (data.status === 'OK') {
const result = data
if(!params.checkResult) return { status: 'OK', ...result }
const error = Types.LnurlLinkResponseValidate(result)
if (error === null) { return { status: 'OK', ...result } } else return { status: 'ERROR', reason: error.message }
}
return { status: 'ERROR', reason: 'invalid response' }
},
GetLNURLChannelLink: async (): Promise<ResultError | ({ status: 'OK' }& Types.LnurlLinkResponse)> => {
const auth = await params.retrieveNostrUserAuth()
if (auth === null) throw new Error('retrieveNostrUserAuth() returned null')

View file

@ -156,6 +156,16 @@ export default (methods: Types.ServerMethods, opts: NostrOptions) => {
res({status: 'OK', ...response})
}catch(ex){ const e = ex as any; logErrorAndReturnResponse(e, e.message || e, res, logger); if (opts.throwErrors) throw e }
break
case 'GetLnurlPayLink':
try {
if (!methods.GetLnurlPayLink) throw new Error('method: GetLnurlPayLink is not implemented')
const authContext = await opts.NostrUserAuthGuard(req.appId, req.authIdentifier)
const query = req.query
const params = req.params
const response = await methods.GetLnurlPayLink({ ...authContext, ...query, ...params })
res({status: 'OK', ...response})
}catch(ex){ const e = ex as any; logErrorAndReturnResponse(e, e.message || e, res, logger); if (opts.throwErrors) throw e }
break
case 'GetLNURLChannelLink':
try {
if (!methods.GetLNURLChannelLink) throw new Error('method: GetLNURLChannelLink is not implemented')

File diff suppressed because it is too large Load diff

View file

@ -77,31 +77,13 @@ extend google.protobuf.FileOptions {
}
service LightningPub {
rpc Health(structs.Empty) returns (structs.Empty){
option (auth_type) = "Guest";
option (http_method) = "get";
option (http_route) = "/api/health";
};
rpc EncryptionExchange(structs.EncryptionExchangeRequest) returns (structs.Empty){
option (auth_type) = "Guest";
option (http_method) = "post";
option (http_route) = "/api/encryption/exchange";
};
// <Admin>
rpc LndGetInfo(structs.LndGetInfoRequest) returns (structs.LndGetInfoResponse){
option (auth_type) = "Admin";
option (http_method) = "post";
option (http_route) = "/api/admin/lnd/getinfo";
};
rpc SetMockInvoiceAsPaid(structs.SetMockInvoiceAsPaidRequest) returns (structs.Empty) {
option (auth_type) = "Guest";
option (http_method) = "post";
option (http_route) = "/api/lnd/mock/invoice/paid";
}
// <App>
rpc AddApp(structs.AddAppRequest) returns (structs.AuthApp) {
option (auth_type) = "Admin";
option (http_method) = "post";
@ -113,7 +95,52 @@ service LightningPub {
option (http_method) = "post";
option (http_route) = "/api/admin/app/auth";
}
// </Admin>
// <Guest>
rpc Health(structs.Empty) returns (structs.Empty){
option (auth_type) = "Guest";
option (http_method) = "get";
option (http_route) = "/api/health";
};
rpc EncryptionExchange(structs.EncryptionExchangeRequest) returns (structs.Empty){
option (auth_type) = "Guest";
option (http_method) = "post";
option (http_route) = "/api/encryption/exchange";
};
rpc SetMockInvoiceAsPaid(structs.SetMockInvoiceAsPaidRequest) returns (structs.Empty) {
option (auth_type) = "Guest";
option (http_method) = "post";
option (http_route) = "/api/lnd/mock/invoice/paid";
}
rpc GetLnurlWithdrawInfo(structs.Empty) returns (structs.LnurlWithdrawInfoResponse){
option (auth_type) = "Guest";
option (http_method) = "get";
option (http_route) = "/api/guest/lnurl_withdraw/info";
option (query) = {items: ["k1"]};
}
rpc HandleLnurlWithdraw(structs.Empty) returns (structs.Empty){
option (auth_type) = "Guest";
option (http_method) = "get";
option (http_route) = "/api/guest/lnurl_withdraw/handle";
option (query) = {items: ["k1", "pr"]};
}
rpc GetLnurlPayInfo(structs.Empty)returns (structs.LnurlPayInfoResponse) {
option (auth_type) = "Guest";
option (http_method) = "get";
option (http_route) = "/api/guest/lnurl_pay/info";
option (query) = {items: ["k1"]};
}
rpc HandleLnurlPay(structs.Empty)returns (structs.HandleLnurlPayResponse) {
option (auth_type) = "Guest";
option (http_method) = "get";
option (http_route) = "/api/guest/lnurl_pay/handle";
option (query) = {items: ["k1", "amount"]};
}
//</Guest>
// <App>
rpc GetApp(structs.Empty) returns (structs.Application) {
option (auth_type) = "App";
option (http_method) = "post";
@ -177,32 +204,23 @@ service LightningPub {
option (http_method) = "post";
option (http_route) = "/api/app/mock/blance/set";
}
// </App>
rpc AddUser(structs.AddUserRequest)returns (structs.AddUserResponse){
option (auth_type) = "Guest";
option (http_method) = "post";
option (http_route) = "/api/user/add";
}
rpc AuthUser(structs.AuthUserRequest)returns (structs.AuthUserResponse){
option (auth_type) = "Guest";
option (http_method) = "post";
option (http_route) = "/api/user/auth";
}
// USER
// <User>
rpc GetUserInfo(structs.Empty)returns(structs.UserInfo){
option (auth_type) = "User";
option (http_method) = "post";
option (http_route) = "/api/user/info";
option (nostr) = true;
}
rpc AddProduct(structs.AddProductRequest) returns (structs.Product){
option (auth_type) = "User";
option (http_method) = "post";
option (http_route) = "/api/user/product/add";
option (nostr) = true;
};
rpc NewProductInvoice(structs.Empty) returns (structs.NewInvoiceResponse){
option (auth_type) = "User";
option (http_method) = "get";
@ -210,82 +228,75 @@ service LightningPub {
option (query) = {items: ["id"]};
option (nostr) = true;
};
rpc GetUserOperations(structs.GetUserOperationsRequest) returns (structs.GetUserOperationsResponse) {
option (auth_type) = "User";
option (http_method) = "post";
option (http_route) = "/api/user/operations";
option (nostr) = true;
}
rpc NewAddress(structs.NewAddressRequest) returns (structs.NewAddressResponse) {
option (auth_type) = "User";
option (http_method) = "post";
option (http_route) = "/api/user/chain/new";
option (nostr) = true;
}
rpc PayAddress(structs.PayAddressRequest) returns (structs.PayAddressResponse){
option (auth_type) = "User";
option (http_method) = "post";
option (http_route) = "/api/user/chain/pay";
option (nostr) = true;
}
rpc NewInvoice(structs.NewInvoiceRequest) returns (structs.NewInvoiceResponse){
option (auth_type) = "User";
option (http_method) = "post";
option (http_route) = "/api/user/invoice/new";
option (nostr) = true;
}
rpc DecodeInvoice(structs.DecodeInvoiceRequest) returns (structs.DecodeInvoiceResponse){
option (auth_type) = "User";
option (http_method) = "post";
option (http_route) = "/api/user/invoice/decode";
option (nostr) = true;
}
rpc PayInvoice(structs.PayInvoiceRequest) returns (structs.PayInvoiceResponse){
option (auth_type) = "User";
option (http_method) = "post";
option (http_route) = "/api/user/invoice/pay";
option (nostr) = true;
}
rpc OpenChannel(structs.OpenChannelRequest) returns (structs.OpenChannelResponse){
option (auth_type) = "User";
option (http_method) = "post";
option (http_route) = "/api/user/open/channel";
option (nostr) = true;
}
rpc GetLnurlWithdrawLink(structs.Empty) returns (structs.LnurlLinkResponse){
option (auth_type) = "User";
option (http_method) = "get";
option (http_route) = "/api/user/lnurl_withdraw/link";
option (nostr) = true;
}
rpc GetLnurlWithdrawInfo(structs.Empty) returns (structs.LnurlWithdrawInfoResponse){
option (auth_type) = "Guest";
rpc GetLnurlPayLink(structs.Empty) returns (structs.LnurlLinkResponse){
option (auth_type) = "User";
option (http_method) = "get";
option (http_route) = "/api/guest/lnurl_withdraw/info";
option (query) = {items: ["k1"]};
}
rpc HandleLnurlWithdraw(structs.Empty) returns (structs.Empty){
option (auth_type) = "Guest";
option (http_method) = "get";
option (http_route) = "/api/guest/lnurl_withdraw/handle";
option (query) = {items: ["k1", "pr"]};
}
rpc GetLnurlPayInfo(structs.Empty)returns (structs.LnurlPayInfoResponse) {
option (auth_type) = "Guest";
option (http_method) = "get";
option (http_route) = "/api/guest/lnurl_pay/info";
option (query) = {items: ["k1"]};
}
rpc HandleLnurlPay(structs.Empty)returns (structs.HandleLnurlPayResponse) {
option (auth_type) = "Guest";
option (http_method) = "get";
option (http_route) = "/api/guest/lnurl_pay/handle";
option (query) = {items: ["k1", "amount"]};
option (http_route) = "/api/user/lnurl_pay/link";
option (nostr) = true;
}
rpc GetLNURLChannelLink(structs.Empty) returns (structs.LnurlLinkResponse){
option (auth_type) = "User";
option (http_method) = "post";
option (http_route) = "/api/user/lnurl_channel/url";
option (nostr) = true;
}
// </User>
}

View file

@ -196,26 +196,7 @@ message HandleLnurlPayResponse {
string pr = 1;
repeated Empty routes = 2;
}
message AddUserRequest{
string callbackUrl = 1;
string name = 2;
string secret = 3;
}
message AddUserResponse{
string userId = 1;
string authToken = 2;
}
message AuthUserRequest{
string name = 2;
string secret = 3;
}
message AuthUserResponse{
string userId = 1;
string authToken = 2;
}
message UserInfo{
string userId = 1;
int64 balance = 2;

View file

@ -8,7 +8,7 @@ const serverOptions = (mainHandler: Main): ServerOptions => {
logger: { log, error: err => log("ERROR", err) },
AdminAuthGuard: adminAuth,
AppAuthGuard: async (authHeader) => { return { app_id: mainHandler.applicationManager.DecodeAppToken(stripBearer(authHeader)) } },
UserAuthGuard: async (authHeader) => { return { user_id: mainHandler.userManager.DecodeUserToken(stripBearer(authHeader)), app_id: "", app_user_id: "" } },
UserAuthGuard: async (authHeader) => { return mainHandler.appUserManager.DecodeUserToken(stripBearer(authHeader)) },
GuestAuthGuard: async (_) => ({}),
encryptCallback: async (_, b) => b,
decryptCallback: async (_, b) => b,

View file

@ -0,0 +1,57 @@
import jwt from 'jsonwebtoken'
import Storage from '../storage/index.js'
import * as Types from '../../../proto/autogenerated/ts/types.js'
import { MainSettings } from './settings.js'
import ApplicationManager from './applicationManager.js'
export default class {
storage: Storage
settings: MainSettings
applicationManager: ApplicationManager
constructor(storage: Storage, settings: MainSettings, applicationManager: ApplicationManager) {
this.storage = storage
this.settings = settings
this.applicationManager = applicationManager
}
SignUserToken(userId: string, appId: string, userIdentifier: string): string {
return jwt.sign({ user_id: userId, app_id: appId, app_user_id: userIdentifier }, this.settings.jwtSecret);
}
DecodeUserToken(token?: string): { user_id: string, app_id: string, app_user_id: string } {
if (!token) throw new Error("empty user token provided")
let t = token
if (token.startsWith("Bearer ")) {
t = token.substring("Bearer ".length)
}
if (!t) throw new Error("no user token provided")
const decoded = jwt.verify(token, this.settings.jwtSecret) as { user_id: string, app_id: string, app_user_id: string }
if (!decoded.user_id || !decoded.app_id || !decoded.app_user_id) {
throw new Error("the provided token is not a valid app user token token")
}
return decoded
}
async GetUserInfo(ctx: Types.UserContext): Promise<Types.UserInfo> {
const user = await this.storage.userStorage.GetUser(ctx.user_id)
return {
userId: ctx.user_id,
balance: user.balance_sats
}
}
async NewInvoice(ctx: Types.UserContext, req: Types.NewInvoiceRequest): Promise<Types.NewInvoiceResponse> {
return this.applicationManager.AddAppUserInvoice(ctx.app_id, {
http_callback_url: "",
invoice_req: req,
payer_identifier: ctx.app_user_id,
receiver_identifier: ctx.app_user_id
})
}
async PayInvoice(ctx: Types.UserContext, req: Types.PayInvoiceRequest): Promise<Types.PayInvoiceResponse> {
return this.applicationManager.PayAppUserInvoice(ctx.app_id, {
amount: req.amount,
invoice: req.invoice,
user_identifier: ctx.app_user_id
})
}
}

View file

@ -1,7 +1,6 @@
import jwt from 'jsonwebtoken'
import Storage from '../storage/index.js'
import * as Types from '../../../proto/autogenerated/ts/types.js'
import UserManager from './userManager.js'
import { MainSettings } from './settings.js'
import PaymentManager from './paymentManager.js'
import { InboundOptionals, defaultInvoiceExpiry } from '../storage/paymentStorage.js'
@ -10,12 +9,10 @@ import { getLogger } from '../helpers/logger.js'
export default class {
storage: Storage
settings: MainSettings
userManager: UserManager
paymentManager: PaymentManager
constructor(storage: Storage, settings: MainSettings, userManager: UserManager, paymentManager: PaymentManager) {
constructor(storage: Storage, settings: MainSettings, paymentManager: PaymentManager) {
this.storage = storage
this.settings = settings
this.userManager = userManager
this.paymentManager = paymentManager
}
SignAppToken(appId: string): string {

View file

@ -4,12 +4,12 @@ import * as Types from '../../../proto/autogenerated/ts/types.js'
import { EnvMustBeInteger, EnvMustBeNonEmptyString } from '../helpers/envParser.js'
import ProductManager from './productManager.js'
import ApplicationManager from './applicationManager.js'
import UserManager from './userManager.js'
import PaymentManager from './paymentManager.js'
import { MainSettings } from './settings.js'
import NewLightningHandler, { LoadLndSettingsFromEnv, LightningHandler } from "../lnd/index.js"
import { AddressPaidCb, InvoicePaidCb } from "../lnd/settings.js"
import { getLogger, PubLogger } from "../helpers/logger.js"
import AppUserManager from "./appUserManager.js"
export const LoadMainSettingsFromEnv = (test = false): MainSettings => {
return {
lndSettings: LoadLndSettingsFromEnv(test),
@ -43,7 +43,7 @@ export default class {
userOperationsSub: UserOperationsSub | null = null
productManager: ProductManager
applicationManager: ApplicationManager
userManager: UserManager
appUserManager: AppUserManager
paymentManager: PaymentManager
constructor(settings: MainSettings) {
@ -51,10 +51,10 @@ export default class {
this.storage = new Storage(settings.storageSettings)
this.lnd = NewLightningHandler(settings.lndSettings, this.addressPaidCb, this.invoicePaidCb)
this.userManager = new UserManager(this.storage, this.settings)
this.paymentManager = new PaymentManager(this.storage, this.lnd, this.settings)
this.productManager = new ProductManager(this.storage, this.paymentManager, this.settings)
this.applicationManager = new ApplicationManager(this.storage, this.settings, this.userManager, this.paymentManager)
this.applicationManager = new ApplicationManager(this.storage, this.settings, this.paymentManager)
this.appUserManager = new AppUserManager(this.storage, this.settings, this.applicationManager)
}
addressPaidCb: AddressPaidCb = (txOutput, address, amount) => {

View file

@ -64,9 +64,10 @@ export default class {
await this.storage.userStorage.UpdateUser(userId, { balance_sats: balance })
}
async NewAddress(userId: string, req: Types.NewAddressRequest): Promise<Types.NewAddressResponse> {
async NewAddress(ctx: Types.UserContext, req: Types.NewAddressRequest): Promise<Types.NewAddressResponse> {
const app = await this.storage.applicationStorage.GetApplication(ctx.app_id)
const res = await this.lnd.NewAddress(req.addressType)
const userAddress = await this.storage.paymentStorage.AddUserAddress(userId, res.address)
const userAddress = await this.storage.paymentStorage.AddUserAddress(ctx.user_id, res.address, { linkedApplication: app })
return {
address: userAddress.address
}
@ -147,17 +148,13 @@ export default class {
}
}
async PayAddress(userId: string, req: Types.PayAddressRequest, linkedApplication?: Application): Promise<Types.PayAddressResponse> {
async PayAddress(ctx: Types.UserContext, req: Types.PayAddressRequest): Promise<Types.PayAddressResponse> {
const userId = ctx.user_id
const app = await this.storage.applicationStorage.GetApplication(ctx.app_id)
const estimate = await this.lnd.EstimateChainFees(req.address, req.amoutSats, 1)
const vBytes = Math.ceil(Number(estimate.feeSat / estimate.satPerVbyte))
const chainFees = vBytes * req.satsPerVByte
const total = req.amoutSats + chainFees
if (!linkedApplication) {
throw new Error("only application operations are supported") // TODO - make this check obsolete
}
if (userId !== linkedApplication.owner.user_id) {
throw new Error("chain operations only supported for applications")
}
const serviceFee = this.getServiceFee(Types.UserOperationType.OUTGOING_INVOICE, req.amoutSats, false)
await this.lockUserWithMinBalance(userId, total + serviceFee)
let payment
@ -179,8 +176,9 @@ export default class {
return `${this.settings.serviceUrl}/api/guest/lnurl_withdraw/info?k1=${k1}`
}
async GetLnurlChannelLink(userId: string): Promise<Types.LnurlLinkResponse> {
const key = await this.storage.paymentStorage.AddUserEphemeralKey(userId, 'balanceCheck')
async GetLnurlWithdrawLink(ctx: Types.UserContext): Promise<Types.LnurlLinkResponse> {
const app = await this.storage.applicationStorage.GetApplication(ctx.app_id)
const key = await this.storage.paymentStorage.AddUserEphemeralKey(ctx.user_id, 'balanceCheck', app)
return {
lnurl: this.encodeLnurl(this.balanceCheckUrl(key.key)),
k1: key.key
@ -216,32 +214,44 @@ export default class {
}
}
async GetLnurlPayInfoFromUser(userId: string, linkedApplication?: Application, baseUrl?: string): Promise<Types.LnurlPayInfoResponse> {
lnurlPayUrl(k1: string): string {
return `${this.settings.serviceUrl}/api/guest/lnurl_pay/info?k1=${k1}`
}
async GetLnurlPayLink(ctx: Types.UserContext): Promise<Types.LnurlLinkResponse> {
const app = await this.storage.applicationStorage.GetApplication(ctx.app_id)
const key = await this.storage.paymentStorage.AddUserEphemeralKey(ctx.user_id, 'pay', app)
return {
lnurl: this.encodeLnurl(this.lnurlPayUrl(key.key)),
k1: key.key
}
}
async GetLnurlPayInfoFromUser(userId: string, linkedApplication: Application, baseUrl?: string): Promise<Types.LnurlPayInfoResponse> {
const payK1 = await this.storage.paymentStorage.AddUserEphemeralKey(userId, 'pay', linkedApplication)
const url = baseUrl ? baseUrl : `${this.settings.serviceUrl}/api/guest/lnurl_pay/handle`
return {
tag: 'payRequest',
callback: `${url}?k1=${payK1.key}`,
maxSendable: 10000000000,
maxSendable: this.GetMaxPayableInvoice(payK1.user.balance_sats, true),
minSendable: 10000,
metadata: defaultLnurlPayMetadata
}
}
async GetLnurlPayInfoFromK1(payInfoK1: string): Promise<Types.LnurlPayInfoResponse> {
const key = await this.storage.paymentStorage.UseUserEphemeralKey(payInfoK1, 'payInfo')
const payK1 = await this.storage.paymentStorage.AddUserEphemeralKey(key.user.user_id, 'pay')
async GetLnurlPayInfo(payInfoK1: string): Promise<Types.LnurlPayInfoResponse> {
const key = await this.storage.paymentStorage.UseUserEphemeralKey(payInfoK1, 'pay', true)
return {
tag: 'payRequest',
callback: `${this.settings.serviceUrl}/api/guest/lnurl_pay/handle?k1=${payK1.key}`,
maxSendable: 10000000,
callback: `${this.settings.serviceUrl}/api/guest/lnurl_pay/handle?k1=${payInfoK1}`,
maxSendable: this.GetMaxPayableInvoice(key.user.balance_sats, true),
minSendable: 10000,
metadata: defaultLnurlPayMetadata
}
}
async HandleLnurlPay(payK1: string, amountMillis: number): Promise<Types.HandleLnurlPayResponse> {
const key = await this.storage.paymentStorage.UseUserEphemeralKey(payK1, 'pay')
const key = await this.storage.paymentStorage.UseUserEphemeralKey(payK1, 'pay', true)
const sats = amountMillis / 1000
if (!Number.isInteger(sats)) {
throw new Error("millisats amount must be integer sats amount")

View file

@ -1,45 +0,0 @@
import jwt from 'jsonwebtoken'
import Storage from '../storage/index.js'
import * as Types from '../../../proto/autogenerated/ts/types.js'
import { MainSettings } from './settings.js'
export default class {
storage: Storage
settings: MainSettings
constructor(storage: Storage, settings: MainSettings) {
this.storage = storage
this.settings = settings
}
SignUserToken(userId: string): string {
return jwt.sign({ userId }, this.settings.jwtSecret);
}
DecodeUserToken(token?: string): string {
if (!token) throw new Error("empty user token provided")
let t = token
if (token.startsWith("Bearer ")) {
t = token.substring("Bearer ".length)
}
if (!t) throw new Error("no user token provided")
const decoded = jwt.verify(token, this.settings.jwtSecret) as { userId?: string }
if (!decoded.userId) {
throw new Error("the provided token is not an app token")
}
return decoded.userId
}
async AddBasicUser(req: Types.AddUserRequest): Promise<Types.AddUserResponse> {
const { user } = await this.storage.userStorage.AddBasicUser(req.name, req.secret)
return {
userId: user.user_id,
authToken: this.SignUserToken(user.user_id)
}
}
async GetUserInfo(userId: string): Promise<Types.UserInfo> {
const user = await this.storage.userStorage.GetUser(userId)
return {
userId: userId,
balance: user.balance_sats
}
}
}

View file

@ -15,21 +15,7 @@ export default (mainHandler: Main): Types.ServerMethods => {
if (err != null) throw new Error(err.message)
await mainHandler.paymentManager.SetMockInvoiceAsPaid(req)
},
AddUser: async (ctx, req) => {
const err = Types.AddUserRequestValidate(req, {
callbackUrl_CustomCheck: url => url.startsWith("http://") || url.startsWith("https://"),
name_CustomCheck: name => name.length > 0,
secret_CustomCheck: secret => secret.length >= 8
})
if (err != null) throw new Error(err.message)
return mainHandler.userManager.AddBasicUser(req)
},
AuthUser: async (ctx, req) => {
throw new Error("unimplemented")
},
GetUserInfo: async (ctx) => {
return mainHandler.userManager.GetUserInfo(ctx.user_id)
},
GetUserInfo: mainHandler.appUserManager.GetUserInfo,
GetUserOperations: async (ctx, req) => {
return mainHandler.paymentManager.GetUserOperations(ctx.user_id, req)
},
@ -42,9 +28,7 @@ export default (mainHandler: Main): Types.ServerMethods => {
if (err != null) throw new Error(err.message)
return mainHandler.paymentManager.OpenChannel(ctx.user_id, req)
},
NewAddress: async (ctx, req) => {
return mainHandler.paymentManager.NewAddress(ctx.user_id, req)
},
NewAddress: mainHandler.paymentManager.NewAddress,
PayAddress: async (ctx, req) => {
const err = Types.PayAddressRequestValidate(req, {
address_CustomCheck: addr => addr !== '',
@ -52,16 +36,9 @@ export default (mainHandler: Main): Types.ServerMethods => {
satsPerVByte_CustomCheck: spb => spb > 0
})
if (err != null) throw new Error(err.message)
return mainHandler.paymentManager.PayAddress(ctx.user_id, req)
},
NewInvoice: async (ctx, req) => {
return mainHandler.applicationManager.AddAppUserInvoice(ctx.app_id, {
http_callback_url: "",
invoice_req: req,
payer_identifier: ctx.app_user_id,
receiver_identifier: ctx.app_user_id
})
return mainHandler.paymentManager.PayAddress(ctx, req)
},
NewInvoice: mainHandler.appUserManager.NewInvoice,
DecodeInvoice: async (ctx, req) => {
return mainHandler.paymentManager.DecodeInvoice(req)
},
@ -70,11 +47,9 @@ export default (mainHandler: Main): Types.ServerMethods => {
invoice_CustomCheck: invoice => invoice !== ''
})
if (err != null) throw new Error(err.message)
return mainHandler.paymentManager.PayInvoice(ctx.user_id, req)
},
GetLnurlWithdrawLink: async (ctx) => {
return mainHandler.paymentManager.GetLnurlChannelLink(ctx.user_id)
return mainHandler.appUserManager.PayInvoice(ctx, req)
},
GetLnurlWithdrawLink: mainHandler.paymentManager.GetLnurlWithdrawLink,
GetLnurlWithdrawInfo: async (ctx) => {
if (!ctx.k1) {
throw new Error("invalid lnurl withdraw to get info")
@ -87,11 +62,12 @@ export default (mainHandler: Main): Types.ServerMethods => {
}
return mainHandler.paymentManager.HandleLnurlWithdraw(ctx.k1, ctx.pr)
},
GetLnurlPayLink: mainHandler.paymentManager.GetLnurlPayLink,
GetLnurlPayInfo: async (ctx) => {
if (!ctx.k1) {
throw new Error("invalid lnurl pay to get info")
}
return mainHandler.paymentManager.GetLnurlPayInfoFromK1(ctx.k1)
return mainHandler.paymentManager.GetLnurlPayInfo(ctx.k1)
},
HandleLnurlPay: async (ctx) => {
if (!ctx.k1 || !ctx.amount) {

View file

@ -1,7 +1,7 @@
import { Entity, PrimaryGeneratedColumn, Column, Index, Check, ManyToOne, JoinColumn, CreateDateColumn, UpdateDateColumn } from "typeorm"
import { User } from "./User.js"
import { Application } from "./Application.js"
export type EphemeralKeyType = 'balanceCheck' | 'payInfo' | 'pay' | 'withdraw'
export type EphemeralKeyType = 'balanceCheck' | 'withdraw' | 'pay'
@Entity()
export class UserEphemeralKey {

View file

@ -1,5 +1,6 @@
import { Entity, PrimaryGeneratedColumn, Column, Index, Check, ManyToOne, JoinColumn, CreateDateColumn, UpdateDateColumn } from "typeorm"
import { User } from "./User.js"
import { Application } from "./Application.js"
@Entity()
export class UserReceivingAddress {
@ -18,6 +19,9 @@ export class UserReceivingAddress {
@Column()
callbackUrl: string
@ManyToOne(type => Application, { eager: true })
linkedApplication: Application | null
@CreateDateColumn()
created_at: Date

View file

@ -47,10 +47,11 @@ export default class {
async AddUserAddress(userId: string, address: string, callbackUrl = "", entityManager = this.DB): Promise<UserReceivingAddress> {
async AddUserAddress(userId: string, address: string, opts: { callbackUrl?: string, linkedApplication?: Application } = {}, entityManager = this.DB): Promise<UserReceivingAddress> {
const newUserAddress = entityManager.getRepository(UserReceivingAddress).create({
address,
callbackUrl,
callbackUrl: opts.callbackUrl,
linkedApplication: opts.linkedApplication,
user: await this.userStorage.GetUser(userId, entityManager)
})
return entityManager.getRepository(UserReceivingAddress).save(newUserAddress)
@ -161,7 +162,11 @@ export default class {
}
async AddUserEphemeralKey(userId: string, keyType: EphemeralKeyType, linkedApplication?: Application, entityManager = this.DB): Promise<UserEphemeralKey> {
async AddUserEphemeralKey(userId: string, keyType: EphemeralKeyType, linkedApplication: Application, entityManager = this.DB): Promise<UserEphemeralKey> {
const found = await entityManager.getRepository(UserEphemeralKey).findOne({ where: { type: keyType, user: { user_id: userId }, linkedApplication: { app_id: linkedApplication.app_id } } })
if (found) {
return found
}
const newKey = entityManager.getRepository(UserEphemeralKey).create({
user: await this.userStorage.GetUser(userId, entityManager),
key: crypto.randomBytes(31).toString('hex'),
@ -171,7 +176,7 @@ export default class {
return entityManager.getRepository(UserEphemeralKey).save(newKey)
}
async UseUserEphemeralKey(key: string, keyType: EphemeralKeyType, entityManager = this.DB): Promise<UserEphemeralKey> {
async UseUserEphemeralKey(key: string, keyType: EphemeralKeyType, persist = false, entityManager = this.DB): Promise<UserEphemeralKey> {
const found = await entityManager.getRepository(UserEphemeralKey).findOne({
where: {
key: key,
@ -181,7 +186,9 @@ export default class {
if (!found) {
throw new Error("the provided ephemeral key is invalid")
}
if (!persist) {
await entityManager.getRepository(UserEphemeralKey).delete(found.serial_id)
}
return found
}