one time invites and GuestWithPub Auth
This commit is contained in:
parent
943073ae3e
commit
e2c20eb9ac
22 changed files with 5185 additions and 4424 deletions
|
|
@ -14,18 +14,20 @@ import { UserTransactionPayment } from "./build/src/services/storage/entity/User
|
|||
import { LspOrder } from "./build/src/services/storage/entity/LspOrder.js"
|
||||
import { LndNodeInfo } from "./build/src/services/storage/entity/LndNodeInfo.js"
|
||||
import { TrackedProvider } from "./build/src/services/storage/entity/TrackedProvider.js"
|
||||
import { InviteToken } from "./build/src/services/storage/entity/InviteToken.js"
|
||||
|
||||
import { Initial1703170309875 } from './build/src/services/storage/migrations/1703170309875-initial.js'
|
||||
import { LspOrder1718387847693 } from './build/src/services/storage/migrations/1718387847693-lsp_order.js'
|
||||
import { LndNodeInfo1720187506189 } from './build/src/services/storage/migrations/1720187506189-lnd_node_info.js'
|
||||
import { LiquidityProvider1719335699480 } from './build/src/services/storage/migrations/1719335699480-liquidity_provider.js'
|
||||
import { CreateInviteTokenTable1721751414878 } from './build/src/services/storage/migrations/1721751414878-create_invite_token_table.js'
|
||||
export default new DataSource({
|
||||
type: "sqlite",
|
||||
database: "db.sqlite",
|
||||
// logging: true,
|
||||
migrations: [Initial1703170309875, LspOrder1718387847693, LiquidityProvider1719335699480, LndNodeInfo1720187506189],
|
||||
migrations: [Initial1703170309875, LspOrder1718387847693, LiquidityProvider1719335699480, LndNodeInfo1720187506189, CreateInviteTokenTable1721751414878],
|
||||
entities: [User, UserReceivingInvoice, UserReceivingAddress, AddressReceivingTransaction, UserInvoicePayment, UserTransactionPayment,
|
||||
UserBasicAuth, UserEphemeralKey, Product, UserToUserPayment, Application, ApplicationUser, UserToUserPayment, LspOrder, LndNodeInfo, TrackedProvider],
|
||||
UserBasicAuth, UserEphemeralKey, Product, UserToUserPayment, Application, ApplicationUser, UserToUserPayment, LspOrder, LndNodeInfo, TrackedProvider, InviteToken],
|
||||
// synchronize: true,
|
||||
})
|
||||
//npx typeorm migration:generate ./src/services/storage/migrations/lnd_node_info -d ./datasource.js
|
||||
|
|
@ -48,16 +48,31 @@ The nostr server will send back a message response, and inside the body there wi
|
|||
- input: [LndMetricsRequest](#LndMetricsRequest)
|
||||
- output: [LndMetrics](#LndMetrics)
|
||||
|
||||
- LinkNPubThroughToken
|
||||
- auth type: __User__
|
||||
- input: [LinkNPubThroughTokenRequest](#LinkNPubThroughTokenRequest)
|
||||
- This methods has an __empty__ __response__ body
|
||||
- CreateOneTimeInviteLink
|
||||
- auth type: __Admin__
|
||||
- input: [CreateOneTimeInviteLinkRequest](#CreateOneTimeInviteLinkRequest)
|
||||
- output: [CreateOneTimeInviteLinkResponse](#CreateOneTimeInviteLinkResponse)
|
||||
|
||||
- GetInviteLinkState
|
||||
- auth type: __Admin__
|
||||
- input: [GetInviteTokenStateRequest](#GetInviteTokenStateRequest)
|
||||
- output: [GetInviteTokenStateResponse](#GetInviteTokenStateResponse)
|
||||
|
||||
- EnrollAdminToken
|
||||
- auth type: __User__
|
||||
- input: [EnrollAdminTokenRequest](#EnrollAdminTokenRequest)
|
||||
- This methods has an __empty__ __response__ body
|
||||
|
||||
- LinkNPubThroughToken
|
||||
- auth type: __GuestWithPub__
|
||||
- input: [LinkNPubThroughTokenRequest](#LinkNPubThroughTokenRequest)
|
||||
- This methods has an __empty__ __response__ body
|
||||
|
||||
- UseInviteLink
|
||||
- auth type: __GuestWithPub__
|
||||
- input: [UseInviteLinkRequest](#UseInviteLinkRequest)
|
||||
- output: [UseInviteLinkResponse](#UseInviteLinkResponse)
|
||||
|
||||
- UserHealth
|
||||
- auth type: __User__
|
||||
- This methods has an __empty__ __request__ body
|
||||
|
|
@ -176,6 +191,11 @@ The nostr server will send back a message response, and inside the body there wi
|
|||
- expected context content
|
||||
- __app_id__: _string_
|
||||
|
||||
- __GuestWithPub__:
|
||||
- expected context content
|
||||
- __pub__: _string_
|
||||
- __app_id__: _string_
|
||||
|
||||
## HTTP Methods
|
||||
### These are the http methods the client implements to communicate with the API
|
||||
|
||||
|
|
@ -228,6 +248,20 @@ The nostr server will send back a message response, and inside the body there wi
|
|||
- input: [LndMetricsRequest](#LndMetricsRequest)
|
||||
- output: [LndMetrics](#LndMetrics)
|
||||
|
||||
- CreateOneTimeInviteLink
|
||||
- auth type: __Admin__
|
||||
- http method: __post__
|
||||
- http route: __/api/admin/app/invite/create__
|
||||
- input: [CreateOneTimeInviteLinkRequest](#CreateOneTimeInviteLinkRequest)
|
||||
- output: [CreateOneTimeInviteLinkResponse](#CreateOneTimeInviteLinkResponse)
|
||||
|
||||
- GetInviteLinkState
|
||||
- auth type: __Admin__
|
||||
- http method: __post__
|
||||
- http route: __/api/admin/app/invite/get__
|
||||
- input: [GetInviteTokenStateRequest](#GetInviteTokenStateRequest)
|
||||
- output: [GetInviteTokenStateResponse](#GetInviteTokenStateResponse)
|
||||
|
||||
- Health
|
||||
- auth type: __Guest__
|
||||
- http method: __get__
|
||||
|
|
@ -298,13 +332,6 @@ The nostr server will send back a message response, and inside the body there wi
|
|||
- This methods has an __empty__ __request__ body
|
||||
- output: [LnurlPayInfoResponse](#LnurlPayInfoResponse)
|
||||
|
||||
- LinkNPubThroughToken
|
||||
- auth type: __User__
|
||||
- http method: __post__
|
||||
- http route: __/api/guest/npub/link__
|
||||
- input: [LinkNPubThroughTokenRequest](#LinkNPubThroughTokenRequest)
|
||||
- This methods has an __empty__ __response__ body
|
||||
|
||||
- EnrollAdminToken
|
||||
- auth type: __User__
|
||||
- http method: __post__
|
||||
|
|
@ -312,6 +339,20 @@ The nostr server will send back a message response, and inside the body there wi
|
|||
- input: [EnrollAdminTokenRequest](#EnrollAdminTokenRequest)
|
||||
- This methods has an __empty__ __response__ body
|
||||
|
||||
- LinkNPubThroughToken
|
||||
- auth type: __GuestWithPub__
|
||||
- http method: __post__
|
||||
- http route: __/api/guest/npub/link__
|
||||
- input: [LinkNPubThroughTokenRequest](#LinkNPubThroughTokenRequest)
|
||||
- This methods has an __empty__ __response__ body
|
||||
|
||||
- UseInviteLink
|
||||
- auth type: __GuestWithPub__
|
||||
- http method: __post__
|
||||
- http route: __/api/guest/invite__
|
||||
- input: [UseInviteLinkRequest](#UseInviteLinkRequest)
|
||||
- output: [UseInviteLinkResponse](#UseInviteLinkResponse)
|
||||
|
||||
- GetApp
|
||||
- auth type: __App__
|
||||
- http method: __post__
|
||||
|
|
@ -529,301 +570,20 @@ 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
|
||||
|
||||
### Empty
|
||||
|
||||
### LndMetricsRequest
|
||||
- __from_unix__: _number_ *this field is optional
|
||||
- __to_unix__: _number_ *this field is optional
|
||||
|
||||
### LndGetInfoResponse
|
||||
- __alias__: _string_
|
||||
|
||||
### PayAppUserInvoiceRequest
|
||||
- __user_identifier__: _string_
|
||||
- __invoice__: _string_
|
||||
- __amount__: _number_
|
||||
|
||||
### Product
|
||||
- __id__: _string_
|
||||
- __name__: _string_
|
||||
- __price_sats__: _number_
|
||||
|
||||
### LndGetInfoRequest
|
||||
- __nodeId__: _number_
|
||||
|
||||
### BanUserResponse
|
||||
- __balance_sats__: _number_
|
||||
- __banned_app_users__: ARRAY of: _[BannedAppUser](#BannedAppUser)_
|
||||
|
||||
### AuthAppRequest
|
||||
- __name__: _string_
|
||||
- __allow_user_creation__: _boolean_ *this field is optional
|
||||
|
||||
### PayAddressRequest
|
||||
- __address__: _string_
|
||||
- __amoutSats__: _number_
|
||||
- __satsPerVByte__: _number_
|
||||
|
||||
### AppsMetricsRequest
|
||||
- __from_unix__: _number_ *this field is optional
|
||||
- __to_unix__: _number_ *this field is optional
|
||||
- __include_operations__: _boolean_ *this field is optional
|
||||
|
||||
### AppsMetrics
|
||||
- __apps__: ARRAY of: _[AppMetrics](#AppMetrics)_
|
||||
|
||||
### RoutingEvent
|
||||
- __timestamp_ns__: _number_
|
||||
- __event_type__: _string_
|
||||
- __settled__: _boolean_
|
||||
- __offchain__: _boolean_
|
||||
- __incoming_channel_id__: _number_
|
||||
- __incoming_htlc_id__: _number_
|
||||
- __outgoing_channel_id__: _number_
|
||||
- __outgoing_htlc_id__: _number_
|
||||
- __forward_fail_event__: _boolean_
|
||||
- __incoming_amt_msat__: _number_
|
||||
- __outgoing_amt_msat__: _number_
|
||||
- __failure_string__: _string_
|
||||
|
||||
### BannedAppUser
|
||||
- __app_name__: _string_
|
||||
- __app_id__: _string_
|
||||
- __user_identifier__: _string_
|
||||
- __nostr_pub__: _string_
|
||||
|
||||
### GetUserOperationsResponse
|
||||
- __latestOutgoingTxOperations__: _[UserOperations](#UserOperations)_
|
||||
- __latestIncomingTxOperations__: _[UserOperations](#UserOperations)_
|
||||
- __latestOutgoingUserToUserPayemnts__: _[UserOperations](#UserOperations)_
|
||||
- __latestIncomingUserToUserPayemnts__: _[UserOperations](#UserOperations)_
|
||||
- __latestOutgoingInvoiceOperations__: _[UserOperations](#UserOperations)_
|
||||
- __latestIncomingInvoiceOperations__: _[UserOperations](#UserOperations)_
|
||||
|
||||
### RequestNPubLinkingTokenResponse
|
||||
- __token__: _string_
|
||||
|
||||
### UsageMetric
|
||||
- __processed_at_ms__: _number_
|
||||
- __auth_in_nano__: _number_
|
||||
- __rpc_name__: _string_
|
||||
- __nostr__: _boolean_
|
||||
- __batch_size__: _number_
|
||||
- __parsed_in_nano__: _number_
|
||||
- __validate_in_nano__: _number_
|
||||
- __handle_in_nano__: _number_
|
||||
- __batch__: _boolean_
|
||||
|
||||
### NewInvoiceRequest
|
||||
- __amountSats__: _number_
|
||||
- __memo__: _string_
|
||||
|
||||
### OpenChannelRequest
|
||||
- __destination__: _string_
|
||||
- __fundingAmount__: _number_
|
||||
- __pushAmount__: _number_
|
||||
- __closeAddress__: _string_
|
||||
|
||||
### ChainBalanceEvent
|
||||
- __block_height__: _number_
|
||||
- __confirmed_balance__: _number_
|
||||
- __unconfirmed_balance__: _number_
|
||||
- __total_balance__: _number_
|
||||
|
||||
### GetAppUserRequest
|
||||
- __user_identifier__: _string_
|
||||
|
||||
### NewAddressResponse
|
||||
- __address__: _string_
|
||||
|
||||
### PayInvoiceResponse
|
||||
- __preimage__: _string_
|
||||
- __amount_paid__: _number_
|
||||
- __operation_id__: _string_
|
||||
- __service_fee__: _number_
|
||||
- __network_fee__: _number_
|
||||
|
||||
### AddProductRequest
|
||||
- __name__: _string_
|
||||
- __price_sats__: _number_
|
||||
|
||||
### MigrationUpdate
|
||||
- __closure__: _[ClosureMigration](#ClosureMigration)_ *this field is optional
|
||||
- __relays__: _[RelaysMigration](#RelaysMigration)_ *this field is optional
|
||||
|
||||
### ClosureMigration
|
||||
- __closes_at_unix__: _number_
|
||||
|
||||
### EncryptionExchangeRequest
|
||||
- __publicKey__: _string_
|
||||
- __deviceId__: _string_
|
||||
|
||||
### UsersInfo
|
||||
- __total__: _number_
|
||||
- __no_balance__: _number_
|
||||
- __negative_balance__: _number_
|
||||
- __always_been_inactive__: _number_
|
||||
- __balance_avg__: _number_
|
||||
- __balance_median__: _number_
|
||||
|
||||
### ChannelBalanceEvent
|
||||
- __block_height__: _number_
|
||||
- __channel_id__: _string_
|
||||
- __local_balance_sats__: _number_
|
||||
- __remote_balance_sats__: _number_
|
||||
|
||||
### ChannelRouting
|
||||
- __receive_errors__: _number_
|
||||
- __forward_errors_as_output__: _number_
|
||||
- __missed_forward_fee_as_output__: _number_
|
||||
- __events_number__: _number_
|
||||
- __channel_id__: _string_
|
||||
- __forward_errors_as_input__: _number_
|
||||
- __missed_forward_fee_as_input__: _number_
|
||||
- __forward_fee_as_input__: _number_
|
||||
- __forward_fee_as_output__: _number_
|
||||
- __send_errors__: _number_
|
||||
|
||||
### SendAppUserToAppPaymentRequest
|
||||
- __from_user_identifier__: _string_
|
||||
- __amount__: _number_
|
||||
|
||||
### SetMockAppBalanceRequest
|
||||
- __amount__: _number_
|
||||
|
||||
### HttpCreds
|
||||
- __url__: _string_
|
||||
- __token__: _string_
|
||||
|
||||
### ClosedChannel
|
||||
- __channel_id__: _string_
|
||||
- __capacity__: _number_
|
||||
- __closed_height__: _number_
|
||||
|
||||
### Application
|
||||
- __id__: _string_
|
||||
- __balance__: _number_
|
||||
- __npub__: _string_
|
||||
- __name__: _string_
|
||||
|
||||
### AddAppUserRequest
|
||||
- __balance__: _number_
|
||||
- __identifier__: _string_
|
||||
- __fail_if_exists__: _boolean_
|
||||
|
||||
### SetMockAppUserBalanceRequest
|
||||
- __user_identifier__: _string_
|
||||
- __amount__: _number_
|
||||
|
||||
### PayAddressResponse
|
||||
- __operation_id__: _string_
|
||||
- __service_fee__: _number_
|
||||
- __network_fee__: _number_
|
||||
- __txId__: _string_
|
||||
|
||||
### NewInvoiceResponse
|
||||
- __invoice__: _string_
|
||||
|
||||
### RequestNPubLinkingTokenRequest
|
||||
- __user_identifier__: _string_
|
||||
|
||||
### LinkNPubThroughTokenRequest
|
||||
- __token__: _string_
|
||||
- __nostr_pub__: _string_
|
||||
|
||||
### OpenChannel
|
||||
- __channel_id__: _string_
|
||||
- __capacity__: _number_
|
||||
- __active__: _boolean_
|
||||
- __lifetime__: _number_
|
||||
- __local_balance__: _number_
|
||||
- __remote_balance__: _number_
|
||||
|
||||
### SetMockInvoiceAsPaidRequest
|
||||
- __invoice__: _string_
|
||||
- __amount__: _number_
|
||||
|
||||
### AddAppUserInvoiceRequest
|
||||
- __receiver_identifier__: _string_
|
||||
- __payer_identifier__: _string_
|
||||
- __http_callback_url__: _string_
|
||||
- __invoice_req__: _[NewInvoiceRequest](#NewInvoiceRequest)_
|
||||
|
||||
### DecodeInvoiceResponse
|
||||
- __amount__: _number_
|
||||
|
||||
### OpenChannelResponse
|
||||
- __channelId__: _string_
|
||||
|
||||
### RelaysMigration
|
||||
- __relays__: ARRAY of: _string_
|
||||
|
||||
### LndMetrics
|
||||
- __nodes__: ARRAY of: _[LndNodeMetrics](#LndNodeMetrics)_
|
||||
|
||||
### AppUser
|
||||
- __identifier__: _string_
|
||||
- __info__: _[UserInfo](#UserInfo)_
|
||||
- __max_withdrawable__: _number_
|
||||
|
||||
### AddAppInvoiceRequest
|
||||
- __payer_identifier__: _string_
|
||||
- __http_callback_url__: _string_
|
||||
- __invoice_req__: _[NewInvoiceRequest](#NewInvoiceRequest)_
|
||||
|
||||
### UserOperations
|
||||
- __fromIndex__: _number_
|
||||
- __toIndex__: _number_
|
||||
- __operations__: ARRAY of: _[UserOperation](#UserOperation)_
|
||||
|
||||
### BanUserRequest
|
||||
- __user_id__: _string_
|
||||
|
||||
### NewAddressRequest
|
||||
- __addressType__: _[AddressType](#AddressType)_
|
||||
### Empty
|
||||
|
||||
### DecodeInvoiceRequest
|
||||
- __invoice__: _string_
|
||||
|
||||
### LnurlWithdrawInfoResponse
|
||||
- __callback__: _string_
|
||||
- __k1__: _string_
|
||||
- __defaultDescription__: _string_
|
||||
- __minWithdrawable__: _number_
|
||||
- __maxWithdrawable__: _number_
|
||||
- __balanceCheck__: _string_
|
||||
- __payLink__: _string_
|
||||
- __tag__: _string_
|
||||
|
||||
### GetUserOperationsRequest
|
||||
- __latestOutgoingInvoice__: _number_
|
||||
- __latestIncomingTx__: _number_
|
||||
- __latestOutgoingTx__: _number_
|
||||
- __latestIncomingUserToUserPayment__: _number_
|
||||
- __latestOutgoingUserToUserPayment__: _number_
|
||||
- __max_size__: _number_
|
||||
- __latestIncomingInvoice__: _number_
|
||||
|
||||
### AppMetrics
|
||||
- __spent__: _number_
|
||||
- __available__: _number_
|
||||
- __fees__: _number_
|
||||
- __invoices__: _number_
|
||||
- __total_fees__: _number_
|
||||
- __app__: _[Application](#Application)_
|
||||
- __users__: _[UsersInfo](#UsersInfo)_
|
||||
- __received__: _number_
|
||||
- __operations__: ARRAY of: _[UserOperation](#UserOperation)_
|
||||
|
||||
### AddAppRequest
|
||||
- __name__: _string_
|
||||
- __allow_user_creation__: _boolean_
|
||||
|
||||
### SendAppUserToAppUserPaymentRequest
|
||||
- __amount__: _number_
|
||||
- __from_user_identifier__: _string_
|
||||
- __to_user_identifier__: _string_
|
||||
|
||||
### LnurlPayInfoResponse
|
||||
- __callback__: _string_
|
||||
- __maxSendable__: _number_
|
||||
|
|
@ -833,70 +593,369 @@ The nostr server will send back a message response, and inside the body there wi
|
|||
- __nostrPubkey__: _string_
|
||||
- __tag__: _string_
|
||||
|
||||
### HandleLnurlPayResponse
|
||||
- __pr__: _string_
|
||||
- __routes__: ARRAY of: _[Empty](#Empty)_
|
||||
### UserOperation
|
||||
- __paidAtUnix__: _number_
|
||||
- __identifier__: _string_
|
||||
- __network_fee__: _number_
|
||||
- __tx_hash__: _string_
|
||||
- __internal__: _boolean_
|
||||
- __type__: _[UserOperationType](#UserOperationType)_
|
||||
- __inbound__: _boolean_
|
||||
- __amount__: _number_
|
||||
- __operationId__: _string_
|
||||
- __service_fee__: _number_
|
||||
- __confirmed__: _boolean_
|
||||
|
||||
### EnrollAdminTokenRequest
|
||||
- __admin_token__: _string_
|
||||
### Product
|
||||
- __price_sats__: _number_
|
||||
- __id__: _string_
|
||||
- __name__: _string_
|
||||
|
||||
### UsageMetrics
|
||||
- __metrics__: ARRAY of: _[UsageMetric](#UsageMetric)_
|
||||
### UsageMetric
|
||||
- __processed_at_ms__: _number_
|
||||
- __parsed_in_nano__: _number_
|
||||
- __auth_in_nano__: _number_
|
||||
- __validate_in_nano__: _number_
|
||||
- __handle_in_nano__: _number_
|
||||
- __rpc_name__: _string_
|
||||
- __batch__: _boolean_
|
||||
- __nostr__: _boolean_
|
||||
- __batch_size__: _number_
|
||||
|
||||
### LnurlLinkResponse
|
||||
- __k1__: _string_
|
||||
- __lnurl__: _string_
|
||||
### AddAppInvoiceRequest
|
||||
- __payer_identifier__: _string_
|
||||
- __http_callback_url__: _string_
|
||||
- __invoice_req__: _[NewInvoiceRequest](#NewInvoiceRequest)_
|
||||
|
||||
### NewAddressResponse
|
||||
- __address__: _string_
|
||||
|
||||
### RequestNPubLinkingTokenRequest
|
||||
- __user_identifier__: _string_
|
||||
|
||||
### CreateOneTimeInviteLinkRequest
|
||||
- __sats__: _number_ *this field is optional
|
||||
|
||||
### CreateOneTimeInviteLinkResponse
|
||||
- __invitation_link__: _string_
|
||||
|
||||
### Application
|
||||
- __name__: _string_
|
||||
- __id__: _string_
|
||||
- __balance__: _number_
|
||||
- __npub__: _string_
|
||||
|
||||
### SendAppUserToAppPaymentRequest
|
||||
- __from_user_identifier__: _string_
|
||||
- __amount__: _number_
|
||||
|
||||
### OpenChannelResponse
|
||||
- __channelId__: _string_
|
||||
|
||||
### LiveUserOperation
|
||||
- __operation__: _[UserOperation](#UserOperation)_
|
||||
|
||||
### PayInvoiceRequest
|
||||
- __invoice__: _string_
|
||||
- __amount__: _number_
|
||||
|
||||
### GetProductBuyLinkResponse
|
||||
- __link__: _string_
|
||||
|
||||
### LndNodeMetrics
|
||||
- __chain_balance_events__: ARRAY of: _[ChainBalanceEvent](#ChainBalanceEvent)_
|
||||
- __online_channels__: _number_
|
||||
- __closing_channels__: _number_
|
||||
- __channels_balance_events__: ARRAY of: _[ChannelBalanceEvent](#ChannelBalanceEvent)_
|
||||
- __pending_channels__: _number_
|
||||
- __open_channels__: ARRAY of: _[OpenChannel](#OpenChannel)_
|
||||
- __closed_channels__: ARRAY of: _[ClosedChannel](#ClosedChannel)_
|
||||
- __channel_routing__: ARRAY of: _[ChannelRouting](#ChannelRouting)_
|
||||
- __offline_channels__: _number_
|
||||
|
||||
### AuthApp
|
||||
- __app__: _[Application](#Application)_
|
||||
- __auth_token__: _string_
|
||||
### GetInviteTokenStateRequest
|
||||
- __invite_token__: _string_
|
||||
|
||||
### GetAppUserLNURLInfoRequest
|
||||
- __user_identifier__: _string_
|
||||
- __base_url_override__: _string_
|
||||
|
||||
### NewAddressRequest
|
||||
- __addressType__: _[AddressType](#AddressType)_
|
||||
|
||||
### RequestNPubLinkingTokenResponse
|
||||
- __token__: _string_
|
||||
|
||||
### LinkNPubThroughTokenRequest
|
||||
- __token__: _string_
|
||||
- __nostr_pub__: _string_
|
||||
|
||||
### HttpCreds
|
||||
- __url__: _string_
|
||||
- __token__: _string_
|
||||
|
||||
### LndMetrics
|
||||
- __nodes__: ARRAY of: _[LndNodeMetrics](#LndNodeMetrics)_
|
||||
|
||||
### PayInvoiceRequest
|
||||
- __invoice__: _string_
|
||||
- __amount__: _number_
|
||||
|
||||
### RoutingEvent
|
||||
- __incoming_htlc_id__: _number_
|
||||
- __outgoing_channel_id__: _number_
|
||||
- __outgoing_htlc_id__: _number_
|
||||
- __event_type__: _string_
|
||||
- __settled__: _boolean_
|
||||
- __offchain__: _boolean_
|
||||
- __forward_fail_event__: _boolean_
|
||||
- __incoming_channel_id__: _number_
|
||||
- __timestamp_ns__: _number_
|
||||
- __incoming_amt_msat__: _number_
|
||||
- __outgoing_amt_msat__: _number_
|
||||
- __failure_string__: _string_
|
||||
|
||||
### GetProductBuyLinkResponse
|
||||
- __link__: _string_
|
||||
|
||||
### AuthAppRequest
|
||||
- __allow_user_creation__: _boolean_ *this field is optional
|
||||
- __name__: _string_
|
||||
|
||||
### SetMockAppUserBalanceRequest
|
||||
- __user_identifier__: _string_
|
||||
- __amount__: _number_
|
||||
|
||||
### UserInfo
|
||||
- __network_max_fee_fixed__: _number_
|
||||
- __userId__: _string_
|
||||
- __balance__: _number_
|
||||
- __max_withdrawable__: _number_
|
||||
- __user_identifier__: _string_
|
||||
- __service_fee_bps__: _number_
|
||||
- __network_max_fee_bps__: _number_
|
||||
- __network_max_fee_fixed__: _number_
|
||||
|
||||
### UserOperation
|
||||
- __paidAtUnix__: _number_
|
||||
- __service_fee__: _number_
|
||||
- __confirmed__: _boolean_
|
||||
- __tx_hash__: _string_
|
||||
- __internal__: _boolean_
|
||||
- __network_fee__: _number_
|
||||
- __type__: _[UserOperationType](#UserOperationType)_
|
||||
- __inbound__: _boolean_
|
||||
- __amount__: _number_
|
||||
### GetUserOperationsResponse
|
||||
- __latestOutgoingUserToUserPayemnts__: _[UserOperations](#UserOperations)_
|
||||
- __latestIncomingUserToUserPayemnts__: _[UserOperations](#UserOperations)_
|
||||
- __latestOutgoingInvoiceOperations__: _[UserOperations](#UserOperations)_
|
||||
- __latestIncomingInvoiceOperations__: _[UserOperations](#UserOperations)_
|
||||
- __latestOutgoingTxOperations__: _[UserOperations](#UserOperations)_
|
||||
- __latestIncomingTxOperations__: _[UserOperations](#UserOperations)_
|
||||
|
||||
### AppsMetricsRequest
|
||||
- __from_unix__: _number_ *this field is optional
|
||||
- __to_unix__: _number_ *this field is optional
|
||||
- __include_operations__: _boolean_ *this field is optional
|
||||
|
||||
### OpenChannel
|
||||
- __remote_balance__: _number_
|
||||
- __channel_id__: _string_
|
||||
- __capacity__: _number_
|
||||
- __active__: _boolean_
|
||||
- __lifetime__: _number_
|
||||
- __local_balance__: _number_
|
||||
|
||||
### AddAppRequest
|
||||
- __name__: _string_
|
||||
- __allow_user_creation__: _boolean_
|
||||
|
||||
### AddAppUserRequest
|
||||
- __identifier__: _string_
|
||||
- __operationId__: _string_
|
||||
- __fail_if_exists__: _boolean_
|
||||
- __balance__: _number_
|
||||
|
||||
### AddAppUserInvoiceRequest
|
||||
- __http_callback_url__: _string_
|
||||
- __invoice_req__: _[NewInvoiceRequest](#NewInvoiceRequest)_
|
||||
- __receiver_identifier__: _string_
|
||||
- __payer_identifier__: _string_
|
||||
|
||||
### MigrationUpdate
|
||||
- __closure__: _[ClosureMigration](#ClosureMigration)_ *this field is optional
|
||||
- __relays__: _[RelaysMigration](#RelaysMigration)_ *this field is optional
|
||||
|
||||
### GetInviteTokenStateResponse
|
||||
- __used__: _boolean_
|
||||
|
||||
### EncryptionExchangeRequest
|
||||
- __deviceId__: _string_
|
||||
- __publicKey__: _string_
|
||||
|
||||
### LndGetInfoRequest
|
||||
- __nodeId__: _number_
|
||||
|
||||
### PayAppUserInvoiceRequest
|
||||
- __user_identifier__: _string_
|
||||
- __invoice__: _string_
|
||||
- __amount__: _number_
|
||||
|
||||
### NewInvoiceRequest
|
||||
- __amountSats__: _number_
|
||||
- __memo__: _string_
|
||||
|
||||
### PayInvoiceResponse
|
||||
- __network_fee__: _number_
|
||||
- __preimage__: _string_
|
||||
- __amount_paid__: _number_
|
||||
- __operation_id__: _string_
|
||||
- __service_fee__: _number_
|
||||
|
||||
### HandleLnurlPayResponse
|
||||
- __pr__: _string_
|
||||
- __routes__: ARRAY of: _[Empty](#Empty)_
|
||||
|
||||
### ClosedChannel
|
||||
- __channel_id__: _string_
|
||||
- __capacity__: _number_
|
||||
- __closed_height__: _number_
|
||||
|
||||
### GetAppUserRequest
|
||||
- __user_identifier__: _string_
|
||||
|
||||
### NewInvoiceResponse
|
||||
- __invoice__: _string_
|
||||
|
||||
### ClosureMigration
|
||||
- __closes_at_unix__: _number_
|
||||
|
||||
### EnrollAdminTokenRequest
|
||||
- __admin_token__: _string_
|
||||
|
||||
### SendAppUserToAppUserPaymentRequest
|
||||
- __from_user_identifier__: _string_
|
||||
- __to_user_identifier__: _string_
|
||||
- __amount__: _number_
|
||||
|
||||
### PayAddressResponse
|
||||
- __txId__: _string_
|
||||
- __operation_id__: _string_
|
||||
- __service_fee__: _number_
|
||||
- __network_fee__: _number_
|
||||
|
||||
### LndGetInfoResponse
|
||||
- __alias__: _string_
|
||||
|
||||
### BannedAppUser
|
||||
- __nostr_pub__: _string_
|
||||
- __app_name__: _string_
|
||||
- __app_id__: _string_
|
||||
- __user_identifier__: _string_
|
||||
|
||||
### BanUserResponse
|
||||
- __balance_sats__: _number_
|
||||
- __banned_app_users__: ARRAY of: _[BannedAppUser](#BannedAppUser)_
|
||||
|
||||
### PayAddressRequest
|
||||
- __address__: _string_
|
||||
- __amoutSats__: _number_
|
||||
- __satsPerVByte__: _number_
|
||||
|
||||
### UserOperations
|
||||
- __fromIndex__: _number_
|
||||
- __toIndex__: _number_
|
||||
- __operations__: ARRAY of: _[UserOperation](#UserOperation)_
|
||||
|
||||
### UseInviteLinkResponse
|
||||
- __nostr_secret__: _string_
|
||||
|
||||
### UsageMetrics
|
||||
- __metrics__: ARRAY of: _[UsageMetric](#UsageMetric)_
|
||||
|
||||
### AppsMetrics
|
||||
- __apps__: ARRAY of: _[AppMetrics](#AppMetrics)_
|
||||
|
||||
### ChannelBalanceEvent
|
||||
- __local_balance_sats__: _number_
|
||||
- __remote_balance_sats__: _number_
|
||||
- __block_height__: _number_
|
||||
- __channel_id__: _string_
|
||||
|
||||
### BanUserRequest
|
||||
- __user_id__: _string_
|
||||
|
||||
### LnurlWithdrawInfoResponse
|
||||
- __defaultDescription__: _string_
|
||||
- __minWithdrawable__: _number_
|
||||
- __maxWithdrawable__: _number_
|
||||
- __balanceCheck__: _string_
|
||||
- __payLink__: _string_
|
||||
- __tag__: _string_
|
||||
- __callback__: _string_
|
||||
- __k1__: _string_
|
||||
|
||||
### AppMetrics
|
||||
- __spent__: _number_
|
||||
- __available__: _number_
|
||||
- __total_fees__: _number_
|
||||
- __users__: _[UsersInfo](#UsersInfo)_
|
||||
- __received__: _number_
|
||||
- __invoices__: _number_
|
||||
- __operations__: ARRAY of: _[UserOperation](#UserOperation)_
|
||||
- __app__: _[Application](#Application)_
|
||||
- __fees__: _number_
|
||||
|
||||
### LndMetricsRequest
|
||||
- __from_unix__: _number_ *this field is optional
|
||||
- __to_unix__: _number_ *this field is optional
|
||||
|
||||
### ChainBalanceEvent
|
||||
- __block_height__: _number_
|
||||
- __confirmed_balance__: _number_
|
||||
- __unconfirmed_balance__: _number_
|
||||
- __total_balance__: _number_
|
||||
|
||||
### GetUserOperationsRequest
|
||||
- __latestOutgoingInvoice__: _number_
|
||||
- __latestIncomingTx__: _number_
|
||||
- __latestOutgoingTx__: _number_
|
||||
- __latestIncomingUserToUserPayment__: _number_
|
||||
- __latestOutgoingUserToUserPayment__: _number_
|
||||
- __max_size__: _number_
|
||||
- __latestIncomingInvoice__: _number_
|
||||
|
||||
### AddProductRequest
|
||||
- __name__: _string_
|
||||
- __price_sats__: _number_
|
||||
|
||||
### UsersInfo
|
||||
- __negative_balance__: _number_
|
||||
- __always_been_inactive__: _number_
|
||||
- __balance_avg__: _number_
|
||||
- __balance_median__: _number_
|
||||
- __total__: _number_
|
||||
- __no_balance__: _number_
|
||||
|
||||
### AppUser
|
||||
- __identifier__: _string_
|
||||
- __info__: _[UserInfo](#UserInfo)_
|
||||
- __max_withdrawable__: _number_
|
||||
|
||||
### SetMockAppBalanceRequest
|
||||
- __amount__: _number_
|
||||
|
||||
### DecodeInvoiceResponse
|
||||
- __amount__: _number_
|
||||
|
||||
### LnurlLinkResponse
|
||||
- __lnurl__: _string_
|
||||
- __k1__: _string_
|
||||
|
||||
### LndNodeMetrics
|
||||
- __pending_channels__: _number_
|
||||
- __closing_channels__: _number_
|
||||
- __open_channels__: ARRAY of: _[OpenChannel](#OpenChannel)_
|
||||
- __closed_channels__: ARRAY of: _[ClosedChannel](#ClosedChannel)_
|
||||
- __channel_routing__: ARRAY of: _[ChannelRouting](#ChannelRouting)_
|
||||
- __chain_balance_events__: ARRAY of: _[ChainBalanceEvent](#ChainBalanceEvent)_
|
||||
- __offline_channels__: _number_
|
||||
- __online_channels__: _number_
|
||||
- __channels_balance_events__: ARRAY of: _[ChannelBalanceEvent](#ChannelBalanceEvent)_
|
||||
|
||||
### AuthApp
|
||||
- __app__: _[Application](#Application)_
|
||||
- __auth_token__: _string_
|
||||
|
||||
### UseInviteLinkRequest
|
||||
- __invite_token__: _string_
|
||||
|
||||
### ChannelRouting
|
||||
- __missed_forward_fee_as_output__: _number_
|
||||
- __channel_id__: _string_
|
||||
- __forward_errors_as_output__: _number_
|
||||
- __forward_errors_as_input__: _number_
|
||||
- __missed_forward_fee_as_input__: _number_
|
||||
- __forward_fee_as_input__: _number_
|
||||
- __forward_fee_as_output__: _number_
|
||||
- __events_number__: _number_
|
||||
- __send_errors__: _number_
|
||||
- __receive_errors__: _number_
|
||||
|
||||
### SetMockInvoiceAsPaidRequest
|
||||
- __invoice__: _string_
|
||||
- __amount__: _number_
|
||||
## Enums
|
||||
### The enumerators used in the messages
|
||||
|
||||
|
|
|
|||
File diff suppressed because it is too large
Load diff
|
|
@ -18,6 +18,7 @@ export type ServerOptions = {
|
|||
AdminAuthGuard: (authorizationHeader?: string) => Promise<Types.AdminContext>
|
||||
MetricsAuthGuard: (authorizationHeader?: string) => Promise<Types.MetricsContext>
|
||||
AppAuthGuard: (authorizationHeader?: string) => Promise<Types.AppContext>
|
||||
GuestWithPubAuthGuard: (authorizationHeader?: string) => Promise<Types.GuestWithPubContext>
|
||||
}
|
||||
declare module 'express-serve-static-core' { interface Request { startTime?: bigint, bodySize?: number, startTimeMs: number } }
|
||||
const logErrorAndReturnResponse = (error: Error, response: string, res: Response, logger: Logger, metric: Types.RequestMetric, metricsCallback: (metrics: Types.RequestMetric[]) => void) => {
|
||||
|
|
@ -184,6 +185,50 @@ export default (methods: Types.ServerMethods, opts: ServerOptions) => {
|
|||
opts.metricsCallback([{ ...info, ...stats, ...authContext }])
|
||||
} catch (ex) { const e = ex as any; logErrorAndReturnResponse(e, e.message || e, res, logger, { ...info, ...stats, ...authCtx }, opts.metricsCallback); if (opts.throwErrors) throw e }
|
||||
})
|
||||
if (!opts.allowNotImplementedMethods && !methods.CreateOneTimeInviteLink) throw new Error('method: CreateOneTimeInviteLink is not implemented')
|
||||
app.post('/api/admin/app/invite/create', async (req, res) => {
|
||||
const info: Types.RequestInfo = { rpcName: 'CreateOneTimeInviteLink', batch: false, nostr: false, batchSize: 0}
|
||||
const stats: Types.RequestStats = { startMs:req.startTimeMs || 0, start:req.startTime || 0n, parse: process.hrtime.bigint(), guard: 0n, validate: 0n, handle: 0n }
|
||||
let authCtx: Types.AuthContext = {}
|
||||
try {
|
||||
if (!methods.CreateOneTimeInviteLink) throw new Error('method: CreateOneTimeInviteLink is not implemented')
|
||||
const authContext = await opts.AdminAuthGuard(req.headers['authorization'])
|
||||
authCtx = authContext
|
||||
stats.guard = process.hrtime.bigint()
|
||||
const request = req.body
|
||||
const error = Types.CreateOneTimeInviteLinkRequestValidate(request)
|
||||
stats.validate = process.hrtime.bigint()
|
||||
if (error !== null) return logErrorAndReturnResponse(error, 'invalid request body', res, logger, { ...info, ...stats, ...authContext }, opts.metricsCallback)
|
||||
const query = req.query
|
||||
const params = req.params
|
||||
const response = await methods.CreateOneTimeInviteLink({rpcName:'CreateOneTimeInviteLink', ctx:authContext , req: request})
|
||||
stats.handle = process.hrtime.bigint()
|
||||
res.json({status: 'OK', ...response})
|
||||
opts.metricsCallback([{ ...info, ...stats, ...authContext }])
|
||||
} catch (ex) { const e = ex as any; logErrorAndReturnResponse(e, e.message || e, res, logger, { ...info, ...stats, ...authCtx }, opts.metricsCallback); if (opts.throwErrors) throw e }
|
||||
})
|
||||
if (!opts.allowNotImplementedMethods && !methods.GetInviteLinkState) throw new Error('method: GetInviteLinkState is not implemented')
|
||||
app.post('/api/admin/app/invite/get', async (req, res) => {
|
||||
const info: Types.RequestInfo = { rpcName: 'GetInviteLinkState', batch: false, nostr: false, batchSize: 0}
|
||||
const stats: Types.RequestStats = { startMs:req.startTimeMs || 0, start:req.startTime || 0n, parse: process.hrtime.bigint(), guard: 0n, validate: 0n, handle: 0n }
|
||||
let authCtx: Types.AuthContext = {}
|
||||
try {
|
||||
if (!methods.GetInviteLinkState) throw new Error('method: GetInviteLinkState is not implemented')
|
||||
const authContext = await opts.AdminAuthGuard(req.headers['authorization'])
|
||||
authCtx = authContext
|
||||
stats.guard = process.hrtime.bigint()
|
||||
const request = req.body
|
||||
const error = Types.GetInviteTokenStateRequestValidate(request)
|
||||
stats.validate = process.hrtime.bigint()
|
||||
if (error !== null) return logErrorAndReturnResponse(error, 'invalid request body', res, logger, { ...info, ...stats, ...authContext }, opts.metricsCallback)
|
||||
const query = req.query
|
||||
const params = req.params
|
||||
const response = await methods.GetInviteLinkState({rpcName:'GetInviteLinkState', ctx:authContext , req: request})
|
||||
stats.handle = process.hrtime.bigint()
|
||||
res.json({status: 'OK', ...response})
|
||||
opts.metricsCallback([{ ...info, ...stats, ...authContext }])
|
||||
} catch (ex) { const e = ex as any; logErrorAndReturnResponse(e, e.message || e, res, logger, { ...info, ...stats, ...authCtx }, opts.metricsCallback); 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) => {
|
||||
const info: Types.RequestInfo = { rpcName: 'Health', batch: false, nostr: false, batchSize: 0}
|
||||
|
|
@ -342,28 +387,6 @@ export default (methods: Types.ServerMethods, opts: ServerOptions) => {
|
|||
opts.metricsCallback([{ ...info, ...stats, ...authContext }])
|
||||
} catch (ex) { const e = ex as any; logErrorAndReturnResponse(e, e.message || e, res, logger, { ...info, ...stats, ...authCtx }, opts.metricsCallback); if (opts.throwErrors) throw e }
|
||||
})
|
||||
if (!opts.allowNotImplementedMethods && !methods.LinkNPubThroughToken) throw new Error('method: LinkNPubThroughToken is not implemented')
|
||||
app.post('/api/guest/npub/link', async (req, res) => {
|
||||
const info: Types.RequestInfo = { rpcName: 'LinkNPubThroughToken', batch: false, nostr: false, batchSize: 0}
|
||||
const stats: Types.RequestStats = { startMs:req.startTimeMs || 0, start:req.startTime || 0n, parse: process.hrtime.bigint(), guard: 0n, validate: 0n, handle: 0n }
|
||||
let authCtx: Types.AuthContext = {}
|
||||
try {
|
||||
if (!methods.LinkNPubThroughToken) throw new Error('method: LinkNPubThroughToken is not implemented')
|
||||
const authContext = await opts.UserAuthGuard(req.headers['authorization'])
|
||||
authCtx = authContext
|
||||
stats.guard = process.hrtime.bigint()
|
||||
const request = req.body
|
||||
const error = Types.LinkNPubThroughTokenRequestValidate(request)
|
||||
stats.validate = process.hrtime.bigint()
|
||||
if (error !== null) return logErrorAndReturnResponse(error, 'invalid request body', res, logger, { ...info, ...stats, ...authContext }, opts.metricsCallback)
|
||||
const query = req.query
|
||||
const params = req.params
|
||||
await methods.LinkNPubThroughToken({rpcName:'LinkNPubThroughToken', ctx:authContext , req: request})
|
||||
stats.handle = process.hrtime.bigint()
|
||||
res.json({status: 'OK'})
|
||||
opts.metricsCallback([{ ...info, ...stats, ...authContext }])
|
||||
} catch (ex) { const e = ex as any; logErrorAndReturnResponse(e, e.message || e, res, logger, { ...info, ...stats, ...authCtx }, opts.metricsCallback); if (opts.throwErrors) throw e }
|
||||
})
|
||||
if (!opts.allowNotImplementedMethods && !methods.EnrollAdminToken) throw new Error('method: EnrollAdminToken is not implemented')
|
||||
app.post('/api/guest/npub/enroll/admin', async (req, res) => {
|
||||
const info: Types.RequestInfo = { rpcName: 'EnrollAdminToken', batch: false, nostr: false, batchSize: 0}
|
||||
|
|
@ -386,6 +409,50 @@ export default (methods: Types.ServerMethods, opts: ServerOptions) => {
|
|||
opts.metricsCallback([{ ...info, ...stats, ...authContext }])
|
||||
} catch (ex) { const e = ex as any; logErrorAndReturnResponse(e, e.message || e, res, logger, { ...info, ...stats, ...authCtx }, opts.metricsCallback); if (opts.throwErrors) throw e }
|
||||
})
|
||||
if (!opts.allowNotImplementedMethods && !methods.LinkNPubThroughToken) throw new Error('method: LinkNPubThroughToken is not implemented')
|
||||
app.post('/api/guest/npub/link', async (req, res) => {
|
||||
const info: Types.RequestInfo = { rpcName: 'LinkNPubThroughToken', batch: false, nostr: false, batchSize: 0}
|
||||
const stats: Types.RequestStats = { startMs:req.startTimeMs || 0, start:req.startTime || 0n, parse: process.hrtime.bigint(), guard: 0n, validate: 0n, handle: 0n }
|
||||
let authCtx: Types.AuthContext = {}
|
||||
try {
|
||||
if (!methods.LinkNPubThroughToken) throw new Error('method: LinkNPubThroughToken is not implemented')
|
||||
const authContext = await opts.GuestWithPubAuthGuard(req.headers['authorization'])
|
||||
authCtx = authContext
|
||||
stats.guard = process.hrtime.bigint()
|
||||
const request = req.body
|
||||
const error = Types.LinkNPubThroughTokenRequestValidate(request)
|
||||
stats.validate = process.hrtime.bigint()
|
||||
if (error !== null) return logErrorAndReturnResponse(error, 'invalid request body', res, logger, { ...info, ...stats, ...authContext }, opts.metricsCallback)
|
||||
const query = req.query
|
||||
const params = req.params
|
||||
await methods.LinkNPubThroughToken({rpcName:'LinkNPubThroughToken', ctx:authContext , req: request})
|
||||
stats.handle = process.hrtime.bigint()
|
||||
res.json({status: 'OK'})
|
||||
opts.metricsCallback([{ ...info, ...stats, ...authContext }])
|
||||
} catch (ex) { const e = ex as any; logErrorAndReturnResponse(e, e.message || e, res, logger, { ...info, ...stats, ...authCtx }, opts.metricsCallback); if (opts.throwErrors) throw e }
|
||||
})
|
||||
if (!opts.allowNotImplementedMethods && !methods.UseInviteLink) throw new Error('method: UseInviteLink is not implemented')
|
||||
app.post('/api/guest/invite', async (req, res) => {
|
||||
const info: Types.RequestInfo = { rpcName: 'UseInviteLink', batch: false, nostr: false, batchSize: 0}
|
||||
const stats: Types.RequestStats = { startMs:req.startTimeMs || 0, start:req.startTime || 0n, parse: process.hrtime.bigint(), guard: 0n, validate: 0n, handle: 0n }
|
||||
let authCtx: Types.AuthContext = {}
|
||||
try {
|
||||
if (!methods.UseInviteLink) throw new Error('method: UseInviteLink is not implemented')
|
||||
const authContext = await opts.GuestWithPubAuthGuard(req.headers['authorization'])
|
||||
authCtx = authContext
|
||||
stats.guard = process.hrtime.bigint()
|
||||
const request = req.body
|
||||
const error = Types.UseInviteLinkRequestValidate(request)
|
||||
stats.validate = process.hrtime.bigint()
|
||||
if (error !== null) return logErrorAndReturnResponse(error, 'invalid request body', res, logger, { ...info, ...stats, ...authContext }, opts.metricsCallback)
|
||||
const query = req.query
|
||||
const params = req.params
|
||||
const response = await methods.UseInviteLink({rpcName:'UseInviteLink', ctx:authContext , req: request})
|
||||
stats.handle = process.hrtime.bigint()
|
||||
res.json({status: 'OK', ...response})
|
||||
opts.metricsCallback([{ ...info, ...stats, ...authContext }])
|
||||
} catch (ex) { const e = ex as any; logErrorAndReturnResponse(e, e.message || e, res, logger, { ...info, ...stats, ...authCtx }, opts.metricsCallback); 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) => {
|
||||
const info: Types.RequestInfo = { rpcName: 'GetApp', batch: false, nostr: false, batchSize: 0}
|
||||
|
|
@ -958,18 +1025,6 @@ export default (methods: Types.ServerMethods, opts: ServerOptions) => {
|
|||
const opStats: Types.RequestStats = { startMs:req.startTimeMs || 0, start:req.startTime || 0n, parse: stats.parse, guard: stats.guard, validate: 0n, handle: 0n }
|
||||
try {
|
||||
switch(operation.rpcName) {
|
||||
case 'LinkNPubThroughToken':
|
||||
if (!methods.LinkNPubThroughToken) {
|
||||
throw new Error('method LinkNPubThroughToken not found' )
|
||||
} else {
|
||||
const error = Types.LinkNPubThroughTokenRequestValidate(operation.req)
|
||||
opStats.validate = process.hrtime.bigint()
|
||||
if (error !== null) throw error
|
||||
await methods.LinkNPubThroughToken({...operation, ctx}); responses.push({ status: 'OK' })
|
||||
opStats.handle = process.hrtime.bigint()
|
||||
callsMetrics.push({ ...opInfo, ...opStats, ...ctx })
|
||||
}
|
||||
break
|
||||
case 'EnrollAdminToken':
|
||||
if (!methods.EnrollAdminToken) {
|
||||
throw new Error('method EnrollAdminToken not found' )
|
||||
|
|
|
|||
|
|
@ -10,6 +10,7 @@ export type ClientParams = {
|
|||
retrieveAdminAuth: () => Promise<string | null>
|
||||
retrieveMetricsAuth: () => Promise<string | null>
|
||||
retrieveAppAuth: () => Promise<string | null>
|
||||
retrieveGuestWithPubAuth: () => Promise<string | null>
|
||||
encryptCallback: (plain: any) => Promise<any>
|
||||
decryptCallback: (encrypted: any) => Promise<any>
|
||||
deviceId: string
|
||||
|
|
@ -114,6 +115,34 @@ export default (params: ClientParams) => ({
|
|||
}
|
||||
return { status: 'ERROR', reason: 'invalid response' }
|
||||
},
|
||||
CreateOneTimeInviteLink: async (request: Types.CreateOneTimeInviteLinkRequest): Promise<ResultError | ({ status: 'OK' }& Types.CreateOneTimeInviteLinkResponse)> => {
|
||||
const auth = await params.retrieveAdminAuth()
|
||||
if (auth === null) throw new Error('retrieveAdminAuth() returned null')
|
||||
let finalRoute = '/api/admin/app/invite/create'
|
||||
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.CreateOneTimeInviteLinkResponseValidate(result)
|
||||
if (error === null) { return { status: 'OK', ...result } } else return { status: 'ERROR', reason: error.message }
|
||||
}
|
||||
return { status: 'ERROR', reason: 'invalid response' }
|
||||
},
|
||||
GetInviteLinkState: async (request: Types.GetInviteTokenStateRequest): Promise<ResultError | ({ status: 'OK' }& Types.GetInviteTokenStateResponse)> => {
|
||||
const auth = await params.retrieveAdminAuth()
|
||||
if (auth === null) throw new Error('retrieveAdminAuth() returned null')
|
||||
let finalRoute = '/api/admin/app/invite/get'
|
||||
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.GetInviteTokenStateResponseValidate(result)
|
||||
if (error === null) { return { status: 'OK', ...result } } else return { status: 'ERROR', reason: error.message }
|
||||
}
|
||||
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')
|
||||
|
|
@ -223,17 +252,6 @@ export default (params: ClientParams) => ({
|
|||
}
|
||||
return { status: 'ERROR', reason: 'invalid response' }
|
||||
},
|
||||
LinkNPubThroughToken: async (request: Types.LinkNPubThroughTokenRequest): Promise<ResultError | ({ status: 'OK' })> => {
|
||||
const auth = await params.retrieveUserAuth()
|
||||
if (auth === null) throw new Error('retrieveUserAuth() returned null')
|
||||
let finalRoute = '/api/guest/npub/link'
|
||||
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' }
|
||||
},
|
||||
EnrollAdminToken: async (request: Types.EnrollAdminTokenRequest): Promise<ResultError | ({ status: 'OK' })> => {
|
||||
const auth = await params.retrieveUserAuth()
|
||||
if (auth === null) throw new Error('retrieveUserAuth() returned null')
|
||||
|
|
@ -245,6 +263,31 @@ export default (params: ClientParams) => ({
|
|||
}
|
||||
return { status: 'ERROR', reason: 'invalid response' }
|
||||
},
|
||||
LinkNPubThroughToken: async (request: Types.LinkNPubThroughTokenRequest): Promise<ResultError | ({ status: 'OK' })> => {
|
||||
const auth = await params.retrieveGuestWithPubAuth()
|
||||
if (auth === null) throw new Error('retrieveGuestWithPubAuth() returned null')
|
||||
let finalRoute = '/api/guest/npub/link'
|
||||
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' }
|
||||
},
|
||||
UseInviteLink: async (request: Types.UseInviteLinkRequest): Promise<ResultError | ({ status: 'OK' }& Types.UseInviteLinkResponse)> => {
|
||||
const auth = await params.retrieveGuestWithPubAuth()
|
||||
if (auth === null) throw new Error('retrieveGuestWithPubAuth() returned null')
|
||||
let finalRoute = '/api/guest/invite'
|
||||
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.UseInviteLinkResponseValidate(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')
|
||||
|
|
|
|||
|
|
@ -5,6 +5,7 @@ export type ResultError = { status: 'ERROR', reason: string }
|
|||
|
||||
export type NostrClientParams = {
|
||||
pubDestination: string
|
||||
retrieveNostrGuestWithPubAuth: () => Promise<string | null>
|
||||
retrieveNostrAdminAuth: () => Promise<string | null>
|
||||
retrieveNostrMetricsAuth: () => Promise<string | null>
|
||||
retrieveNostrUserAuth: () => Promise<string | null>
|
||||
|
|
@ -115,15 +116,33 @@ export default (params: NostrClientParams, send: (to:string, message: NostrRequ
|
|||
}
|
||||
return { status: 'ERROR', reason: 'invalid response' }
|
||||
},
|
||||
LinkNPubThroughToken: async (request: Types.LinkNPubThroughTokenRequest): Promise<ResultError | ({ status: 'OK' })> => {
|
||||
const auth = await params.retrieveNostrUserAuth()
|
||||
if (auth === null) throw new Error('retrieveNostrUserAuth() returned null')
|
||||
CreateOneTimeInviteLink: async (request: Types.CreateOneTimeInviteLinkRequest): Promise<ResultError | ({ status: 'OK' }& Types.CreateOneTimeInviteLinkResponse)> => {
|
||||
const auth = await params.retrieveNostrAdminAuth()
|
||||
if (auth === null) throw new Error('retrieveNostrAdminAuth() returned null')
|
||||
const nostrRequest: NostrRequest = {}
|
||||
nostrRequest.body = request
|
||||
const data = await send(params.pubDestination, {rpcName:'LinkNPubThroughToken',authIdentifier:auth, ...nostrRequest })
|
||||
const data = await send(params.pubDestination, {rpcName:'CreateOneTimeInviteLink',authIdentifier:auth, ...nostrRequest })
|
||||
if (data.status === 'ERROR' && typeof data.reason === 'string') return data
|
||||
if (data.status === 'OK') {
|
||||
return data
|
||||
const result = data
|
||||
if(!params.checkResult) return { status: 'OK', ...result }
|
||||
const error = Types.CreateOneTimeInviteLinkResponseValidate(result)
|
||||
if (error === null) { return { status: 'OK', ...result } } else return { status: 'ERROR', reason: error.message }
|
||||
}
|
||||
return { status: 'ERROR', reason: 'invalid response' }
|
||||
},
|
||||
GetInviteLinkState: async (request: Types.GetInviteTokenStateRequest): Promise<ResultError | ({ status: 'OK' }& Types.GetInviteTokenStateResponse)> => {
|
||||
const auth = await params.retrieveNostrAdminAuth()
|
||||
if (auth === null) throw new Error('retrieveNostrAdminAuth() returned null')
|
||||
const nostrRequest: NostrRequest = {}
|
||||
nostrRequest.body = request
|
||||
const data = await send(params.pubDestination, {rpcName:'GetInviteLinkState',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.GetInviteTokenStateResponseValidate(result)
|
||||
if (error === null) { return { status: 'OK', ...result } } else return { status: 'ERROR', reason: error.message }
|
||||
}
|
||||
return { status: 'ERROR', reason: 'invalid response' }
|
||||
},
|
||||
|
|
@ -139,6 +158,33 @@ export default (params: NostrClientParams, send: (to:string, message: NostrRequ
|
|||
}
|
||||
return { status: 'ERROR', reason: 'invalid response' }
|
||||
},
|
||||
LinkNPubThroughToken: async (request: Types.LinkNPubThroughTokenRequest): Promise<ResultError | ({ status: 'OK' })> => {
|
||||
const auth = await params.retrieveNostrGuestWithPubAuth()
|
||||
if (auth === null) throw new Error('retrieveNostrGuestWithPubAuth() returned null')
|
||||
const nostrRequest: NostrRequest = {}
|
||||
nostrRequest.body = request
|
||||
const data = await send(params.pubDestination, {rpcName:'LinkNPubThroughToken',authIdentifier:auth, ...nostrRequest })
|
||||
if (data.status === 'ERROR' && typeof data.reason === 'string') return data
|
||||
if (data.status === 'OK') {
|
||||
return data
|
||||
}
|
||||
return { status: 'ERROR', reason: 'invalid response' }
|
||||
},
|
||||
UseInviteLink: async (request: Types.UseInviteLinkRequest): Promise<ResultError | ({ status: 'OK' }& Types.UseInviteLinkResponse)> => {
|
||||
const auth = await params.retrieveNostrGuestWithPubAuth()
|
||||
if (auth === null) throw new Error('retrieveNostrGuestWithPubAuth() returned null')
|
||||
const nostrRequest: NostrRequest = {}
|
||||
nostrRequest.body = request
|
||||
const data = await send(params.pubDestination, {rpcName:'UseInviteLink',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.UseInviteLinkResponseValidate(result)
|
||||
if (error === null) { return { status: 'OK', ...result } } else return { status: 'ERROR', reason: error.message }
|
||||
}
|
||||
return { status: 'ERROR', reason: 'invalid response' }
|
||||
},
|
||||
UserHealth: async (): Promise<ResultError | ({ status: 'OK' })> => {
|
||||
const auth = await params.retrieveNostrUserAuth()
|
||||
if (auth === null) throw new Error('retrieveNostrUserAuth() returned null')
|
||||
|
|
|
|||
|
|
@ -19,6 +19,7 @@ export type NostrOptions = {
|
|||
NostrAdminAuthGuard: (appId?:string, identifier?: string) => Promise<Types.AdminContext>
|
||||
NostrMetricsAuthGuard: (appId?:string, identifier?: string) => Promise<Types.MetricsContext>
|
||||
NostrUserAuthGuard: (appId?:string, identifier?: string) => Promise<Types.UserContext>
|
||||
NostrGuestWithPubAuthGuard: (appId?:string, identifier?: string) => Promise<Types.GuestWithPubContext>
|
||||
}
|
||||
const logErrorAndReturnResponse = (error: Error, response: string, res: NostrResponse, logger: Logger, metric: Types.RequestMetric, metricsCallback: (metrics: Types.RequestMetric[]) => void) => {
|
||||
logger.error(error.message || error); metricsCallback([{ ...metric, error: response }]); res({ status: 'ERROR', reason: response })
|
||||
|
|
@ -140,19 +141,35 @@ export default (methods: Types.ServerMethods, opts: NostrOptions) => {
|
|||
opts.metricsCallback([{ ...info, ...stats, ...authContext }])
|
||||
}catch(ex){ const e = ex as any; logErrorAndReturnResponse(e, e.message || e, res, logger, { ...info, ...stats, ...authCtx }, opts.metricsCallback); if (opts.throwErrors) throw e }
|
||||
break
|
||||
case 'LinkNPubThroughToken':
|
||||
case 'CreateOneTimeInviteLink':
|
||||
try {
|
||||
if (!methods.LinkNPubThroughToken) throw new Error('method: LinkNPubThroughToken is not implemented')
|
||||
const authContext = await opts.NostrUserAuthGuard(req.appId, req.authIdentifier)
|
||||
if (!methods.CreateOneTimeInviteLink) throw new Error('method: CreateOneTimeInviteLink is not implemented')
|
||||
const authContext = await opts.NostrAdminAuthGuard(req.appId, req.authIdentifier)
|
||||
stats.guard = process.hrtime.bigint()
|
||||
authCtx = authContext
|
||||
const request = req.body
|
||||
const error = Types.LinkNPubThroughTokenRequestValidate(request)
|
||||
const error = Types.CreateOneTimeInviteLinkRequestValidate(request)
|
||||
stats.validate = process.hrtime.bigint()
|
||||
if (error !== null) return logErrorAndReturnResponse(error, 'invalid request body', res, logger, { ...info, ...stats, ...authCtx }, opts.metricsCallback)
|
||||
await methods.LinkNPubThroughToken({rpcName:'LinkNPubThroughToken', ctx:authContext , req: request})
|
||||
const response = await methods.CreateOneTimeInviteLink({rpcName:'CreateOneTimeInviteLink', ctx:authContext , req: request})
|
||||
stats.handle = process.hrtime.bigint()
|
||||
res({status: 'OK'})
|
||||
res({status: 'OK', ...response})
|
||||
opts.metricsCallback([{ ...info, ...stats, ...authContext }])
|
||||
}catch(ex){ const e = ex as any; logErrorAndReturnResponse(e, e.message || e, res, logger, { ...info, ...stats, ...authCtx }, opts.metricsCallback); if (opts.throwErrors) throw e }
|
||||
break
|
||||
case 'GetInviteLinkState':
|
||||
try {
|
||||
if (!methods.GetInviteLinkState) throw new Error('method: GetInviteLinkState is not implemented')
|
||||
const authContext = await opts.NostrAdminAuthGuard(req.appId, req.authIdentifier)
|
||||
stats.guard = process.hrtime.bigint()
|
||||
authCtx = authContext
|
||||
const request = req.body
|
||||
const error = Types.GetInviteTokenStateRequestValidate(request)
|
||||
stats.validate = process.hrtime.bigint()
|
||||
if (error !== null) return logErrorAndReturnResponse(error, 'invalid request body', res, logger, { ...info, ...stats, ...authCtx }, opts.metricsCallback)
|
||||
const response = await methods.GetInviteLinkState({rpcName:'GetInviteLinkState', ctx:authContext , req: request})
|
||||
stats.handle = process.hrtime.bigint()
|
||||
res({status: 'OK', ...response})
|
||||
opts.metricsCallback([{ ...info, ...stats, ...authContext }])
|
||||
}catch(ex){ const e = ex as any; logErrorAndReturnResponse(e, e.message || e, res, logger, { ...info, ...stats, ...authCtx }, opts.metricsCallback); if (opts.throwErrors) throw e }
|
||||
break
|
||||
|
|
@ -172,6 +189,38 @@ export default (methods: Types.ServerMethods, opts: NostrOptions) => {
|
|||
opts.metricsCallback([{ ...info, ...stats, ...authContext }])
|
||||
}catch(ex){ const e = ex as any; logErrorAndReturnResponse(e, e.message || e, res, logger, { ...info, ...stats, ...authCtx }, opts.metricsCallback); if (opts.throwErrors) throw e }
|
||||
break
|
||||
case 'LinkNPubThroughToken':
|
||||
try {
|
||||
if (!methods.LinkNPubThroughToken) throw new Error('method: LinkNPubThroughToken is not implemented')
|
||||
const authContext = await opts.NostrGuestWithPubAuthGuard(req.appId, req.authIdentifier)
|
||||
stats.guard = process.hrtime.bigint()
|
||||
authCtx = authContext
|
||||
const request = req.body
|
||||
const error = Types.LinkNPubThroughTokenRequestValidate(request)
|
||||
stats.validate = process.hrtime.bigint()
|
||||
if (error !== null) return logErrorAndReturnResponse(error, 'invalid request body', res, logger, { ...info, ...stats, ...authCtx }, opts.metricsCallback)
|
||||
await methods.LinkNPubThroughToken({rpcName:'LinkNPubThroughToken', ctx:authContext , req: request})
|
||||
stats.handle = process.hrtime.bigint()
|
||||
res({status: 'OK'})
|
||||
opts.metricsCallback([{ ...info, ...stats, ...authContext }])
|
||||
}catch(ex){ const e = ex as any; logErrorAndReturnResponse(e, e.message || e, res, logger, { ...info, ...stats, ...authCtx }, opts.metricsCallback); if (opts.throwErrors) throw e }
|
||||
break
|
||||
case 'UseInviteLink':
|
||||
try {
|
||||
if (!methods.UseInviteLink) throw new Error('method: UseInviteLink is not implemented')
|
||||
const authContext = await opts.NostrGuestWithPubAuthGuard(req.appId, req.authIdentifier)
|
||||
stats.guard = process.hrtime.bigint()
|
||||
authCtx = authContext
|
||||
const request = req.body
|
||||
const error = Types.UseInviteLinkRequestValidate(request)
|
||||
stats.validate = process.hrtime.bigint()
|
||||
if (error !== null) return logErrorAndReturnResponse(error, 'invalid request body', res, logger, { ...info, ...stats, ...authCtx }, opts.metricsCallback)
|
||||
const response = await methods.UseInviteLink({rpcName:'UseInviteLink', ctx:authContext , req: request})
|
||||
stats.handle = process.hrtime.bigint()
|
||||
res({status: 'OK', ...response})
|
||||
opts.metricsCallback([{ ...info, ...stats, ...authContext }])
|
||||
}catch(ex){ const e = ex as any; logErrorAndReturnResponse(e, e.message || e, res, logger, { ...info, ...stats, ...authCtx }, opts.metricsCallback); if (opts.throwErrors) throw e }
|
||||
break
|
||||
case 'UserHealth':
|
||||
try {
|
||||
if (!methods.UserHealth) throw new Error('method: UserHealth is not implemented')
|
||||
|
|
@ -436,18 +485,6 @@ export default (methods: Types.ServerMethods, opts: NostrOptions) => {
|
|||
const opStats: Types.RequestStats = { startMs, start: startTime, parse: stats.parse, guard: stats.guard, validate: 0n, handle: 0n }
|
||||
try {
|
||||
switch(operation.rpcName) {
|
||||
case 'LinkNPubThroughToken':
|
||||
if (!methods.LinkNPubThroughToken) {
|
||||
throw new Error('method not defined: LinkNPubThroughToken')
|
||||
} else {
|
||||
const error = Types.LinkNPubThroughTokenRequestValidate(operation.req)
|
||||
opStats.validate = process.hrtime.bigint()
|
||||
if (error !== null) throw error
|
||||
await methods.LinkNPubThroughToken({...operation, ctx}); responses.push({ status: 'OK' })
|
||||
opStats.handle = process.hrtime.bigint()
|
||||
callsMetrics.push({ ...opInfo, ...opStats, ...ctx })
|
||||
}
|
||||
break
|
||||
case 'EnrollAdminToken':
|
||||
if (!methods.EnrollAdminToken) {
|
||||
throw new Error('method not defined: EnrollAdminToken')
|
||||
|
|
|
|||
File diff suppressed because it is too large
Load diff
|
|
@ -53,6 +53,20 @@ option (file_options) = {
|
|||
key:"app_id",
|
||||
value: "string"
|
||||
}
|
||||
},
|
||||
{
|
||||
id: "guestPub",
|
||||
name: "GuestWithPub",
|
||||
context:[
|
||||
{
|
||||
key: "pub",
|
||||
value:"string"
|
||||
},
|
||||
{
|
||||
key: "app_id",
|
||||
value: "string"
|
||||
}
|
||||
]
|
||||
}
|
||||
];
|
||||
};
|
||||
|
|
@ -137,6 +151,20 @@ service LightningPub {
|
|||
option (nostr) = true;
|
||||
}
|
||||
|
||||
rpc CreateOneTimeInviteLink(structs.CreateOneTimeInviteLinkRequest) returns (structs.CreateOneTimeInviteLinkResponse) {
|
||||
option (auth_type) = "Admin";
|
||||
option (http_method) = "post";
|
||||
option (http_route) = "/api/admin/app/invite/create";
|
||||
option (nostr) = true;
|
||||
}
|
||||
|
||||
rpc GetInviteLinkState(structs.GetInviteTokenStateRequest) returns (structs.GetInviteTokenStateResponse) {
|
||||
option (auth_type) = "Admin";
|
||||
option (http_method) = "post";
|
||||
option (http_route) = "/api/admin/app/invite/get";
|
||||
option (nostr) = true;
|
||||
}
|
||||
|
||||
|
||||
// </Admin>
|
||||
|
||||
|
|
@ -187,12 +215,6 @@ service LightningPub {
|
|||
option (http_route) = "/.well-known/lnurlp/:address_name";
|
||||
}
|
||||
|
||||
rpc LinkNPubThroughToken(structs.LinkNPubThroughTokenRequest) returns (structs.Empty) {
|
||||
option (auth_type) = "User";
|
||||
option (http_method) = "post";
|
||||
option (http_route) = "/api/guest/npub/link";
|
||||
option (nostr) = true;
|
||||
}
|
||||
rpc EnrollAdminToken(structs.EnrollAdminTokenRequest) returns (structs.Empty) {
|
||||
option (auth_type) = "User";
|
||||
option (http_method) = "post";
|
||||
|
|
@ -201,6 +223,23 @@ service LightningPub {
|
|||
}
|
||||
//</Guest>
|
||||
|
||||
|
||||
//<GuestWithPub>
|
||||
rpc LinkNPubThroughToken(structs.LinkNPubThroughTokenRequest) returns (structs.Empty) {
|
||||
option (auth_type) = "GuestWithPub";
|
||||
option (http_method) = "post";
|
||||
option (http_route) = "/api/guest/npub/link";
|
||||
option (nostr) = true;
|
||||
}
|
||||
|
||||
rpc UseInviteLink(structs.UseInviteLinkRequest) returns (structs.UseInviteLinkResponse) {
|
||||
option (auth_type) = "GuestWithPub";
|
||||
option (http_method) = "post";
|
||||
option (http_route) = "/api/guest/invite";
|
||||
option (nostr) = true;
|
||||
}
|
||||
//<GuestWithPub>
|
||||
|
||||
// <App>
|
||||
rpc GetApp(structs.Empty) returns (structs.Application) {
|
||||
option (auth_type) = "App";
|
||||
|
|
|
|||
|
|
@ -453,4 +453,28 @@ message HttpCreds {
|
|||
|
||||
message EnrollAdminTokenRequest {
|
||||
string admin_token = 1;
|
||||
}
|
||||
|
||||
message CreateOneTimeInviteLinkRequest {
|
||||
optional int64 sats = 1;
|
||||
}
|
||||
|
||||
message CreateOneTimeInviteLinkResponse {
|
||||
string invitation_link = 1;
|
||||
}
|
||||
|
||||
message UseInviteLinkRequest {
|
||||
string invite_token = 1;
|
||||
}
|
||||
|
||||
message UseInviteLinkResponse {
|
||||
string nostr_secret = 1;
|
||||
}
|
||||
|
||||
message GetInviteTokenStateRequest {
|
||||
string invite_token = 1;
|
||||
}
|
||||
|
||||
message GetInviteTokenStateResponse {
|
||||
bool used = 1;
|
||||
}
|
||||
|
|
@ -12,6 +12,7 @@ const serverOptions = (mainHandler: Main): ServerOptions => {
|
|||
MetricsAuthGuard: metricsAuth,
|
||||
AppAuthGuard: async (authHeader) => { return { app_id: mainHandler.applicationManager.DecodeAppToken(stripBearer(authHeader)) } },
|
||||
UserAuthGuard: async (authHeader) => { return mainHandler.appUserManager.DecodeUserToken(stripBearer(authHeader)) },
|
||||
GuestWithPubAuthGuard: async (_) => ({ pub: "", app_id: "" }),
|
||||
GuestAuthGuard: async (_) => ({}),
|
||||
metricsCallback: metrics => mainHandler.settings.recordPerformance ? mainHandler.metricsManager.AddMetrics(metrics) : null,
|
||||
allowCors: true,
|
||||
|
|
|
|||
|
|
@ -28,7 +28,13 @@ export default (serverMethods: Types.ServerMethods, mainHandler: Main, nostrSett
|
|||
return { operator_id: pub }
|
||||
},
|
||||
metricsCallback: metrics => mainHandler.settings.recordPerformance ? mainHandler.metricsManager.AddMetrics(metrics) : null,
|
||||
logger: { log: console.log, error: err => log(ERROR, err) }
|
||||
NostrGuestWithPubAuthGuard: async (appId, pub) => {
|
||||
if (!pub || !appId) {
|
||||
throw new Error("Unknown error occured")
|
||||
}
|
||||
return { pub, app_id: appId }
|
||||
},
|
||||
logger: { log: console.log, error: err => log(ERROR, err) },
|
||||
})
|
||||
const nostr = new Nostr(nostrSettings, event => {
|
||||
let j: NostrRequest
|
||||
|
|
|
|||
|
|
@ -3,6 +3,7 @@ import crypto from 'crypto'
|
|||
import { getLogger } from "../helpers/logger.js";
|
||||
import { MainSettings, getDataPath } from "./settings.js";
|
||||
import Storage from "../storage/index.js";
|
||||
import * as Types from '../../../proto/autogenerated/ts/types.js'
|
||||
export class AdminManager {
|
||||
storage: Storage
|
||||
log = getLogger({ component: "adminManager" })
|
||||
|
|
@ -112,4 +113,25 @@ export class AdminManager {
|
|||
fs.unlinkSync(this.adminConnectPath)
|
||||
this.adminNpub = npub
|
||||
}
|
||||
|
||||
CreateInviteLink = async (adminNpub: string, sats?: number): Promise<Types.CreateOneTimeInviteLinkResponse> => {
|
||||
const adminAppUser = await this.storage.applicationStorage.FindNostrAppUser(adminNpub)
|
||||
if (!adminAppUser) {
|
||||
throw new Error("Admin user expected but not found!!!");
|
||||
}
|
||||
const newInviteToken = await this.storage.applicationStorage.AddInviteToken(adminAppUser.application, sats);
|
||||
return {
|
||||
invitation_link: newInviteToken.inviteToken
|
||||
}
|
||||
}
|
||||
|
||||
async GetInviteTokenState(ctx: Types.AdminContext, req: Types.GetInviteTokenStateRequest): Promise<Types.GetInviteTokenStateResponse> {
|
||||
const inviteToken = await this.storage.applicationStorage.FindInviteToken(req.invite_token);
|
||||
if (!inviteToken) {
|
||||
throw new Error("Invite token not found");
|
||||
}
|
||||
return {
|
||||
used: inviteToken.used
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -8,6 +8,7 @@ import { ApplicationUser } from '../storage/entity/ApplicationUser.js'
|
|||
import { PubLogger, getLogger } from '../helpers/logger.js'
|
||||
import crypto from 'crypto'
|
||||
import { Application } from '../storage/entity/Application.js'
|
||||
import { generatePrivateKey, getPublicKey } from '../nostr/tools/keys.js'
|
||||
|
||||
const TOKEN_EXPIRY_TIME = 2 * 60 * 1000 // 2 minutes, in milliseconds
|
||||
|
||||
|
|
@ -244,27 +245,33 @@ export default class {
|
|||
|
||||
|
||||
|
||||
async LinkNpubThroughToken(ctx: Types.UserContext, req: Types.LinkNPubThroughTokenRequest): Promise<void> {
|
||||
const { app_id: appId, app_user_id: appUserId } = ctx
|
||||
const app = await this.storage.applicationStorage.GetApplication(appId)
|
||||
const appUser = await this.storage.applicationStorage.GetApplicationUser(app, appUserId)
|
||||
await this.storage.txQueue.PushToQueue({
|
||||
dbTx: true,
|
||||
exec: async tx => {
|
||||
await this.storage.applicationStorage.RemoveApplicationUserAndBaseUser(appUser, tx);
|
||||
const entry = this.nPubLinkingTokens.get(req.token)
|
||||
if (entry && entry.expiry > Date.now()) {
|
||||
const copy = { ...entry }
|
||||
const deleted = this.nPubLinkingTokens.delete(req.token)
|
||||
if (deleted) {
|
||||
await this.storage.applicationStorage.AddNPubToApplicationUser(copy.serialId, req.nostr_pub, tx)
|
||||
} else {
|
||||
throw new Error("An uknown error occured")
|
||||
}
|
||||
} else {
|
||||
throw new Error("Token invalid or expired")
|
||||
}
|
||||
async LinkNpubThroughToken(ctx: Types.GuestWithPubContext, req: Types.LinkNPubThroughTokenRequest): Promise<void> {
|
||||
const entry = this.nPubLinkingTokens.get(req.token)
|
||||
if (entry && entry.expiry > Date.now()) {
|
||||
const copy = { ...entry }
|
||||
const deleted = this.nPubLinkingTokens.delete(req.token)
|
||||
if (deleted) {
|
||||
await this.storage.applicationStorage.AddNPubToApplicationUser(copy.serialId, req.nostr_pub)
|
||||
} else {
|
||||
throw new Error("An uknown error occured")
|
||||
}
|
||||
})
|
||||
} else {
|
||||
throw new Error("Token invalid or expired")
|
||||
}
|
||||
}
|
||||
|
||||
async UseInviteLink(ctx: Types.GuestWithPubContext, req: Types.UseInviteLinkRequest): Promise<Types.UseInviteLinkResponse> {
|
||||
const app = await this.storage.applicationStorage.GetApplication(ctx.app_id);
|
||||
const inviteToken = await this.storage.applicationStorage.FindInviteToken(req.invite_token);
|
||||
if (!inviteToken || inviteToken.used || inviteToken.application.app_id !== ctx.app_id) {
|
||||
throw new Error("Invite token not found");
|
||||
}
|
||||
const nostrPriv = generatePrivateKey();
|
||||
const nostrPub = getPublicKey(nostrPriv);
|
||||
const appUser = await this.storage.applicationStorage.AddApplicationUser(app, crypto.randomBytes(32).toString('hex'), 0, nostrPub)
|
||||
await this.storage.applicationStorage.SetInviteTokenAsUsed(inviteToken);
|
||||
return {
|
||||
nostr_secret: nostrPriv
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -45,6 +45,7 @@ export class LiquidityProvider {
|
|||
retrieveNostrUserAuth: async () => this.myPub,
|
||||
retrieveNostrAdminAuth: async () => this.myPub,
|
||||
retrieveNostrMetricsAuth: async () => this.myPub,
|
||||
retrieveNostrGuestWithPubAuth: async () => this.myPub
|
||||
}, this.clientSend, this.clientSub)
|
||||
|
||||
this.configuredInterval = setInterval(() => {
|
||||
|
|
|
|||
|
|
@ -222,5 +222,27 @@ export default (mainHandler: Main): Types.ServerMethods => {
|
|||
if (err != null) throw new Error(err.message)
|
||||
return mainHandler.adminManager.PromoteUserToAdmin(ctx.app_id, ctx.app_user_id, req.admin_token)
|
||||
},
|
||||
CreateOneTimeInviteLink: async ({ ctx, req }) => {
|
||||
const err = Types.CreateOneTimeInviteLinkRequestValidate(req, {
|
||||
sats_CustomCheck: sats => sats === undefined || typeof sats === "number"
|
||||
})
|
||||
if (err != null) throw new Error(err.message)
|
||||
return mainHandler.adminManager.CreateInviteLink(ctx.admin_id, req.sats)
|
||||
},
|
||||
UseInviteLink: async ({ ctx, req }) => {
|
||||
const err = Types.UseInviteLinkRequestValidate(req, {
|
||||
invite_token_CustomCheck: token => token !== ''
|
||||
})
|
||||
if (err != null) throw new Error(err.message)
|
||||
return mainHandler.applicationManager.UseInviteLink(ctx, req);
|
||||
},
|
||||
GetInviteLinkState: async ({ ctx, req }) => {
|
||||
const err = Types.GetInviteTokenStateRequestValidate(req, {
|
||||
invite_token_CustomCheck: token => token !== ''
|
||||
})
|
||||
if (err != null) throw new Error(err.message)
|
||||
return mainHandler.adminManager.GetInviteTokenState(ctx, req);
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
|
@ -7,6 +7,7 @@ import { ApplicationUser } from './entity/ApplicationUser.js';
|
|||
import { getLogger } from '../helpers/logger.js';
|
||||
import TransactionsQueue, { TX } from "./transactionsQueue.js";
|
||||
import { User } from './entity/User.js';
|
||||
import { InviteToken } from './entity/InviteToken.js';
|
||||
export default class {
|
||||
DB: DataSource | EntityManager
|
||||
userStorage: UserStorage
|
||||
|
|
@ -169,4 +170,30 @@ export default class {
|
|||
await entityManager.getRepository(ApplicationUser).remove(appUser);
|
||||
await entityManager.getRepository(User).remove(baseUser);
|
||||
}
|
||||
|
||||
|
||||
async AddInviteToken(app: Application, sats?: number) {
|
||||
return this.DB.transaction(async tx => {
|
||||
const inviteRepo = tx.getRepository(InviteToken);
|
||||
const newInviteToken = inviteRepo.create({
|
||||
inviteToken: crypto.randomBytes(32).toString('hex'),
|
||||
used: false,
|
||||
sats: sats,
|
||||
application: app
|
||||
});
|
||||
|
||||
return inviteRepo.save(newInviteToken)
|
||||
})
|
||||
}
|
||||
|
||||
async FindInviteToken(token: string) {
|
||||
return this.DB.getRepository(InviteToken).findOne({ where: { inviteToken: token } })
|
||||
}
|
||||
|
||||
|
||||
async SetInviteTokenAsUsed(inviteToken: InviteToken) {
|
||||
return this.DB.transaction(async tx => {
|
||||
return tx.getRepository(InviteToken).update(inviteToken, { used: true });
|
||||
})
|
||||
}
|
||||
}
|
||||
|
|
@ -20,6 +20,7 @@ import { LspOrder } from "./entity/LspOrder.js"
|
|||
import { Product } from "./entity/Product.js"
|
||||
import { LndNodeInfo } from "./entity/LndNodeInfo.js"
|
||||
import { TrackedProvider } from "./entity/TrackedProvider.js"
|
||||
import { InviteToken } from "./entity/InviteToken.js"
|
||||
|
||||
|
||||
export type DbSettings = {
|
||||
|
|
@ -59,7 +60,9 @@ export default async (settings: DbSettings, migrations: Function[]): Promise<{ s
|
|||
database: settings.databaseFile,
|
||||
// logging: true,
|
||||
entities: [User, UserReceivingInvoice, UserReceivingAddress, AddressReceivingTransaction, UserInvoicePayment, UserTransactionPayment,
|
||||
UserBasicAuth, UserEphemeralKey, Product, UserToUserPayment, Application, ApplicationUser, UserToUserPayment, LspOrder, LndNodeInfo, TrackedProvider],
|
||||
UserBasicAuth, UserEphemeralKey, Product, UserToUserPayment, Application, ApplicationUser, UserToUserPayment, LspOrder, LndNodeInfo, TrackedProvider,
|
||||
InviteToken
|
||||
],
|
||||
//synchronize: true,
|
||||
migrations
|
||||
}).initialize()
|
||||
|
|
|
|||
28
src/services/storage/entity/InviteToken.ts
Normal file
28
src/services/storage/entity/InviteToken.ts
Normal file
|
|
@ -0,0 +1,28 @@
|
|||
import { Entity, PrimaryGeneratedColumn, Column, Index, CreateDateColumn, UpdateDateColumn, ManyToOne, JoinColumn } from "typeorm";
|
||||
import { Application } from "./Application.js";
|
||||
|
||||
@Entity()
|
||||
export class InviteToken {
|
||||
@PrimaryGeneratedColumn()
|
||||
serial_id: number
|
||||
|
||||
@Column({ unique: true })
|
||||
@Index("IDX_invite_token")
|
||||
inviteToken: string
|
||||
|
||||
@ManyToOne(type => Application, { eager: true })
|
||||
@JoinColumn()
|
||||
application: Application
|
||||
|
||||
@Column({ nullable: true })
|
||||
sats: number
|
||||
|
||||
@Column()
|
||||
used: boolean
|
||||
|
||||
@CreateDateColumn()
|
||||
created_at: Date
|
||||
|
||||
@UpdateDateColumn()
|
||||
updated_at: Date
|
||||
}
|
||||
|
|
@ -0,0 +1,28 @@
|
|||
import { MigrationInterface, QueryRunner } from "typeorm";
|
||||
|
||||
export class CreateInviteTokenTable1721751414878 implements MigrationInterface {
|
||||
name = 'CreateInviteTokenTable1721751414878'
|
||||
|
||||
public async up(queryRunner: QueryRunner): Promise<void> {
|
||||
await queryRunner.query(`CREATE TABLE "invite_token" ("serial_id" integer PRIMARY KEY AUTOINCREMENT NOT NULL, "inviteToken" varchar NOT NULL, "sats" integer, "used" boolean NOT NULL, "created_at" datetime NOT NULL DEFAULT (datetime('now')), "updated_at" datetime NOT NULL DEFAULT (datetime('now')), "applicationSerialId" integer, CONSTRAINT "UQ_0ded0098656758c761f14a43c58" UNIQUE ("inviteToken"))`);
|
||||
await queryRunner.query(`CREATE INDEX "IDX_invite_token" ON "invite_token" ("inviteToken") `);
|
||||
await queryRunner.query(`DROP INDEX "IDX_invite_token"`);
|
||||
await queryRunner.query(`CREATE TABLE "temporary_invite_token" ("serial_id" integer PRIMARY KEY AUTOINCREMENT NOT NULL, "inviteToken" varchar NOT NULL, "sats" integer, "used" boolean NOT NULL, "created_at" datetime NOT NULL DEFAULT (datetime('now')), "updated_at" datetime NOT NULL DEFAULT (datetime('now')), "applicationSerialId" integer, CONSTRAINT "UQ_0ded0098656758c761f14a43c58" UNIQUE ("inviteToken"), CONSTRAINT "FK_a1f025b46b1438eae2a08932169" FOREIGN KEY ("applicationSerialId") REFERENCES "application" ("serial_id") ON DELETE NO ACTION ON UPDATE NO ACTION)`);
|
||||
await queryRunner.query(`INSERT INTO "temporary_invite_token"("serial_id", "inviteToken", "sats", "used", "created_at", "updated_at", "applicationSerialId") SELECT "serial_id", "inviteToken", "sats", "used", "created_at", "updated_at", "applicationSerialId" FROM "invite_token"`);
|
||||
await queryRunner.query(`DROP TABLE "invite_token"`);
|
||||
await queryRunner.query(`ALTER TABLE "temporary_invite_token" RENAME TO "invite_token"`);
|
||||
await queryRunner.query(`CREATE INDEX "IDX_invite_token" ON "invite_token" ("inviteToken") `);
|
||||
}
|
||||
|
||||
public async down(queryRunner: QueryRunner): Promise<void> {
|
||||
await queryRunner.query(`DROP INDEX "IDX_invite_token"`);
|
||||
await queryRunner.query(`ALTER TABLE "invite_token" RENAME TO "temporary_invite_token"`);
|
||||
await queryRunner.query(`CREATE TABLE "invite_token" ("serial_id" integer PRIMARY KEY AUTOINCREMENT NOT NULL, "inviteToken" varchar NOT NULL, "sats" integer, "used" boolean NOT NULL, "created_at" datetime NOT NULL DEFAULT (datetime('now')), "updated_at" datetime NOT NULL DEFAULT (datetime('now')), "applicationSerialId" integer, CONSTRAINT "UQ_0ded0098656758c761f14a43c58" UNIQUE ("inviteToken"))`);
|
||||
await queryRunner.query(`INSERT INTO "invite_token"("serial_id", "inviteToken", "sats", "used", "created_at", "updated_at", "applicationSerialId") SELECT "serial_id", "inviteToken", "sats", "used", "created_at", "updated_at", "applicationSerialId" FROM "temporary_invite_token"`);
|
||||
await queryRunner.query(`DROP TABLE "temporary_invite_token"`);
|
||||
await queryRunner.query(`CREATE INDEX "IDX_invite_token" ON "invite_token" ("inviteToken") `);
|
||||
await queryRunner.query(`DROP INDEX "IDX_invite_token"`);
|
||||
await queryRunner.query(`DROP TABLE "invite_token"`);
|
||||
}
|
||||
|
||||
}
|
||||
|
|
@ -8,7 +8,8 @@ import { LspOrder1718387847693 } from './1718387847693-lsp_order.js'
|
|||
import { LiquidityProvider1719335699480 } from './1719335699480-liquidity_provider.js'
|
||||
import { LndNodeInfo1720187506189 } from './1720187506189-lnd_node_info.js'
|
||||
import { TrackedProvider1720814323679 } from './1720814323679-tracked_provider.js'
|
||||
const allMigrations = [Initial1703170309875, LspOrder1718387847693, LiquidityProvider1719335699480, LndNodeInfo1720187506189, TrackedProvider1720814323679]
|
||||
import { CreateInviteTokenTable1721751414878 } from "./1721751414878-create_invite_token_table.js"
|
||||
const allMigrations = [Initial1703170309875, LspOrder1718387847693, LiquidityProvider1719335699480, LndNodeInfo1720187506189, TrackedProvider1720814323679, CreateInviteTokenTable1721751414878]
|
||||
const allMetricsMigrations = [LndMetrics1703170330183, ChannelRouting1709316653538]
|
||||
export const TypeOrmMigrationRunner = async (log: PubLogger, storageManager: Storage, settings: DbSettings, arg: string | undefined): Promise<boolean> => {
|
||||
if (arg === 'fake_initial_migration') {
|
||||
|
|
|
|||
|
|
@ -167,8 +167,8 @@
|
|||
document.getElementById("relayStatus").innerHTML = `<span class="${j.relay_connected ? 'green-dot' : 'red-dot'}">●</span> ${j.relay_connected ? 'Connected' : 'Disconnected'}`
|
||||
document.getElementById("lndStatus").innerHTML = `<span class="${j.lnd_state === 'ONLINE' ? 'green-dot' : 'red-dot'}">●</span> ${j.lnd_state}`
|
||||
document.getElementById("watchdog-status").innerHTML = `<span class="${j.watchdog_ok ? 'green-dot' : 'red-dot'}">●</span> ${j.watchdog_ok ? 'No Alerts' : 'ALERT!!'}`
|
||||
document.getElementById("inviteLinkHttp").href = `https://my.shockwallet.app/#/source?addSource=${j.nprofile}`
|
||||
document.getElementById("inviteLinkHttp").innerHTML = `https://my.shockwallet.app/#/source?addSource=${j.nprofile}`
|
||||
document.getElementById("inviteLinkHttp").href = `https://my.shockwallet.app/#/sources?addSource=${j.nprofile}`
|
||||
document.getElementById("inviteLinkHttp").innerHTML = `https://my.shockwallet.app/#/sources?addSource=${j.nprofile}`
|
||||
document.querySelector('input[name="show-nodey"]').placeholder = j.provider_name;
|
||||
document.title = j.provider_name;
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue