Merge branch 'master' into watchdog

This commit is contained in:
boufni95 2024-03-26 18:51:29 +01:00
commit b1dcf946b2
25 changed files with 4424 additions and 3985 deletions

34
package-lock.json generated
View file

@ -20,6 +20,7 @@
"axios": "^0.27.2",
"bech32": "^2.0.0",
"chai": "^4.3.7",
"chai-string": "^1.5.0",
"copyfiles": "^2.4.1",
"cors": "^2.8.5",
"csv": "^6.3.8",
@ -47,6 +48,7 @@
},
"devDependencies": {
"@types/chai": "^4.3.4",
"@types/chai-string": "^1.4.5",
"@types/cors": "^2.8.12",
"@types/eccrypto": "^1.1.3",
"@types/jsonwebtoken": "^8.5.9",
@ -485,6 +487,15 @@
"integrity": "sha512-KnRanxnpfpjUTqTCXslZSEdLfXExwgNxYPdiO2WGUj8+HDjFi8R3k5RVKPeSCzLjCcshCAtVO2QBbVuAV4kTnw==",
"dev": true
},
"node_modules/@types/chai-string": {
"version": "1.4.5",
"resolved": "https://registry.npmjs.org/@types/chai-string/-/chai-string-1.4.5.tgz",
"integrity": "sha512-IecXRMSnpUvRnTztdpSdjcmcW7EdNme65bfDCQMi7XrSEPGmyDYYTEfc5fcactWDA6ioSm8o7NUqg9QxjBCCEw==",
"dev": true,
"dependencies": {
"@types/chai": "*"
}
},
"node_modules/@types/connect": {
"version": "3.4.35",
"resolved": "https://registry.npmjs.org/@types/connect/-/connect-3.4.35.tgz",
@ -1127,6 +1138,14 @@
"node": ">=4"
}
},
"node_modules/chai-string": {
"version": "1.5.0",
"resolved": "https://registry.npmjs.org/chai-string/-/chai-string-1.5.0.tgz",
"integrity": "sha512-sydDC3S3pNAQMYwJrs6dQX0oBQ6KfIPuOZ78n7rocW0eJJlsHPh2t3kwW7xfwYA/1Bf6/arGtSUo16rxR2JFlw==",
"peerDependencies": {
"chai": "^4.1.2"
}
},
"node_modules/chalk": {
"version": "4.1.2",
"resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.2.tgz",
@ -4929,6 +4948,15 @@
"integrity": "sha512-KnRanxnpfpjUTqTCXslZSEdLfXExwgNxYPdiO2WGUj8+HDjFi8R3k5RVKPeSCzLjCcshCAtVO2QBbVuAV4kTnw==",
"dev": true
},
"@types/chai-string": {
"version": "1.4.5",
"resolved": "https://registry.npmjs.org/@types/chai-string/-/chai-string-1.4.5.tgz",
"integrity": "sha512-IecXRMSnpUvRnTztdpSdjcmcW7EdNme65bfDCQMi7XrSEPGmyDYYTEfc5fcactWDA6ioSm8o7NUqg9QxjBCCEw==",
"dev": true,
"requires": {
"@types/chai": "*"
}
},
"@types/connect": {
"version": "3.4.35",
"resolved": "https://registry.npmjs.org/@types/connect/-/connect-3.4.35.tgz",
@ -5455,6 +5483,12 @@
"type-detect": "^4.0.5"
}
},
"chai-string": {
"version": "1.5.0",
"resolved": "https://registry.npmjs.org/chai-string/-/chai-string-1.5.0.tgz",
"integrity": "sha512-sydDC3S3pNAQMYwJrs6dQX0oBQ6KfIPuOZ78n7rocW0eJJlsHPh2t3kwW7xfwYA/1Bf6/arGtSUo16rxR2JFlw==",
"requires": {}
},
"chalk": {
"version": "4.1.2",
"resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.2.tgz",

View file

@ -36,6 +36,7 @@
"axios": "^0.27.2",
"bech32": "^2.0.0",
"chai": "^4.3.7",
"chai-string": "^1.5.0",
"copyfiles": "^2.4.1",
"cors": "^2.8.5",
"csv": "^6.3.8",
@ -63,6 +64,7 @@
},
"devDependencies": {
"@types/chai": "^4.3.4",
"@types/chai-string": "^1.4.5",
"@types/cors": "^2.8.12",
"@types/eccrypto": "^1.1.3",
"@types/jsonwebtoken": "^8.5.9",

View file

@ -110,9 +110,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
@ -150,6 +150,13 @@ The nostr server will send back a message response, and inside the body there wi
- input: [AuthAppRequest](#AuthAppRequest)
- output: [AuthApp](#AuthApp)
- BanUser
- auth type: __Admin__
- http method: __post__
- http route: __/api/admin/user/ban__
- input: [BanUserRequest](#BanUserRequest)
- output: [BanUserResponse](#BanUserResponse)
- GetUsageMetrics
- auth type: __Metrics__
- http method: __post__
@ -444,186 +451,52 @@ 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
### ChannelRouting
- __channel_id__: _string_
- __send_errors__: _number_
- __receive_errors__: _number_
- __forward_errors_as_input__: _number_
- __forward_errors_as_output__: _number_
- __missed_forward_fee_as_input__: _number_
- __missed_forward_fee_as_output__: _number_
- __forward_fee_as_input__: _number_
- __forward_fee_as_output__: _number_
- __events_number__: _number_
### AddAppInvoiceRequest
- __payer_identifier__: _string_
- __http_callback_url__: _string_
- __invoice_req__: _[NewInvoiceRequest](#NewInvoiceRequest)_
### GetAppUserLNURLInfoRequest
- __user_identifier__: _string_
- __base_url_override__: _string_
### PayInvoiceResponse
- __preimage__: _string_
- __amount_paid__: _number_
- __operation_id__: _string_
- __service_fee__: _number_
- __network_fee__: _number_
### ChainBalanceEvent
- __block_height__: _number_
- __confirmed_balance__: _number_
- __unconfirmed_balance__: _number_
- __total_balance__: _number_
### SetMockInvoiceAsPaidRequest
- __invoice__: _string_
- __amount__: _number_
### AddAppUserRequest
- __identifier__: _string_
- __fail_if_exists__: _boolean_
- __balance__: _number_
### NewInvoiceResponse
- __invoice__: _string_
### RoutingEvent
- __incoming_channel_id__: _number_
- __incoming_htlc_id__: _number_
- __outgoing_channel_id__: _number_
- __outgoing_htlc_id__: _number_
- __timestamp_ns__: _number_
- __event_type__: _string_
- __incoming_amt_msat__: _number_
- __outgoing_amt_msat__: _number_
- __failure_string__: _string_
- __settled__: _boolean_
- __offchain__: _boolean_
- __forward_fail_event__: _boolean_
### AuthApp
- __app__: _[Application](#Application)_
- __auth_token__: _string_
### DecodeInvoiceResponse
- __amount__: _number_
### EncryptionExchangeRequest
- __publicKey__: _string_
- __deviceId__: _string_
### AppUser
- __identifier__: _string_
- __info__: _[UserInfo](#UserInfo)_
- __max_withdrawable__: _number_
### SetMockAppUserBalanceRequest
- __user_identifier__: _string_
- __amount__: _number_
### NewAddressRequest
- __addressType__: _[AddressType](#AddressType)_
### OpenChannelRequest
- __destination__: _string_
- __fundingAmount__: _number_
- __pushAmount__: _number_
- __closeAddress__: _string_
### UserOperation
- __paidAtUnix__: _number_
- __type__: _[UserOperationType](#UserOperationType)_
- __inbound__: _boolean_
- __amount__: _number_
- __identifier__: _string_
- __operationId__: _string_
- __service_fee__: _number_
- __network_fee__: _number_
- __confirmed__: _boolean_
- __tx_hash__: _string_
- __internal__: _boolean_
### LnurlPayInfoResponse
- __tag__: _string_
- __callback__: _string_
- __maxSendable__: _number_
- __minSendable__: _number_
- __metadata__: _string_
- __allowsNostr__: _boolean_
- __nostrPubkey__: _string_
### AddProductRequest
- __name__: _string_
- __price_sats__: _number_
### AddAppUserInvoiceRequest
- __receiver_identifier__: _string_
- __payer_identifier__: _string_
- __http_callback_url__: _string_
- __invoice_req__: _[NewInvoiceRequest](#NewInvoiceRequest)_
### LndGetInfoRequest
- __nodeId__: _number_
### GetAppUserRequest
- __user_identifier__: _string_
### PayAppUserInvoiceRequest
- __user_identifier__: _string_
- __invoice__: _string_
- __amount__: _number_
### SetMockAppBalanceRequest
- __amount__: _number_
### GetUserOperationsRequest
- __latestIncomingInvoice__: _number_
- __latestOutgoingInvoice__: _number_
- __latestIncomingTx__: _number_
- __latestOutgoingTx__: _number_
- __latestIncomingUserToUserPayment__: _number_
- __latestOutgoingUserToUserPayment__: _number_
- __max_size__: _number_
### AppMetrics
- __app__: _[Application](#Application)_
- __users__: _[UsersInfo](#UsersInfo)_
- __received__: _number_
- __spent__: _number_
- __available__: _number_
- __fees__: _number_
- __invoices__: _number_
- __total_fees__: _number_
### UserOperations
- __fromIndex__: _number_
- __toIndex__: _number_
- __operations__: ARRAY of: _[UserOperation](#UserOperation)_
### LndGetInfoResponse
- __alias__: _string_
### SendAppUserToAppPaymentRequest
- __from_user_identifier__: _string_
- __amount__: _number_
### PayInvoiceRequest
- __invoice__: _string_
- __amount__: _number_
### LiveUserOperation
- __operation__: _[UserOperation](#UserOperation)_
### MigrationUpdate
- __closure__: _[ClosureMigration](#ClosureMigration)_ *this field is optional
- __relays__: _[RelaysMigration](#RelaysMigration)_ *this field is optional
### OpenChannel
- __channel_id__: _string_
- __capacity__: _number_
- __active__: _boolean_
- __lifetime__: _number_
- __local_balance__: _number_
- __remote_balance__: _number_
### SendAppUserToAppPaymentRequest
- __from_user_identifier__: _string_
- __amount__: _number_
### DecodeInvoiceRequest
- __invoice__: _string_
### UserInfo
- __userId__: _string_
- __balance__: _number_
- __max_withdrawable__: _number_
### GetAppUserLNURLInfoRequest
- __user_identifier__: _string_
- __base_url_override__: _string_
### NewAddressRequest
- __addressType__: _[AddressType](#AddressType)_
### BanUserResponse
- __balance_sats__: _number_
- __banned_app_users__: ARRAY of: _[BannedAppUser](#BannedAppUser)_
### Product
- __id__: _string_
- __name__: _string_
- __price_sats__: _number_
### LiveUserOperation
- __operation__: _[UserOperation](#UserOperation)_
### UsageMetric
- __processed_at_ms__: _number_
@ -642,54 +515,11 @@ The nostr server will send back a message response, and inside the body there wi
- __local_balance_sats__: _number_
- __remote_balance_sats__: _number_
### AddAppRequest
- __name__: _string_
- __allow_user_creation__: _boolean_
### Application
- __name__: _string_
- __id__: _string_
- __balance__: _number_
- __npub__: _string_
### 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
### LndMetricsRequest
- __from_unix__: _number_ *this field is optional
- __to_unix__: _number_ *this field is optional
### SendAppUserToAppUserPaymentRequest
- __from_user_identifier__: _string_
- __to_user_identifier__: _string_
- __amount__: _number_
### LnurlLinkResponse
- __lnurl__: _string_
- __k1__: _string_
### LnurlPayInfoResponse
- __tag__: _string_
- __callback__: _string_
- __maxSendable__: _number_
- __minSendable__: _number_
- __metadata__: _string_
- __allowsNostr__: _boolean_
- __nostrPubkey__: _string_
### UsageMetrics
- __metrics__: ARRAY of: _[UsageMetric](#UsageMetric)_
### AuthAppRequest
- __name__: _string_
- __allow_user_creation__: _boolean_ *this field is optional
### ChainBalanceEvent
- __block_height__: _number_
- __confirmed_balance__: _number_
- __unconfirmed_balance__: _number_
- __total_balance__: _number_
### GetUserOperationsResponse
- __latestOutgoingInvoiceOperations__: _[UserOperations](#UserOperations)_
@ -699,56 +529,39 @@ The nostr server will send back a message response, and inside the body there wi
- __latestOutgoingUserToUserPayemnts__: _[UserOperations](#UserOperations)_
- __latestIncomingUserToUserPayemnts__: _[UserOperations](#UserOperations)_
### LndNodeMetrics
- __channels_balance_events__: ARRAY of: _[ChannelBalanceEvent](#ChannelBalanceEvent)_
- __chain_balance_events__: ARRAY of: _[ChainBalanceEvent](#ChainBalanceEvent)_
- __offline_channels__: _number_
- __online_channels__: _number_
- __pending_channels__: _number_
- __closing_channels__: _number_
- __open_channels__: ARRAY of: _[OpenChannel](#OpenChannel)_
- __closed_channels__: ARRAY of: _[ClosedChannel](#ClosedChannel)_
- __channel_routing__: ARRAY of: _[ChannelRouting](#ChannelRouting)_
### UserOperations
- __fromIndex__: _number_
- __toIndex__: _number_
- __operations__: ARRAY of: _[UserOperation](#UserOperation)_
### RelaysMigration
- __relays__: ARRAY of: _string_
### Empty
### UsersInfo
- __total__: _number_
- __no_balance__: _number_
- __negative_balance__: _number_
- __always_been_inactive__: _number_
- __balance_avg__: _number_
- __balance_median__: _number_
### NewAddressResponse
- __address__: _string_
### Product
- __id__: _string_
### AuthAppRequest
- __name__: _string_
- __price_sats__: _number_
- __allow_user_creation__: _boolean_ *this field is optional
### AppsMetrics
- __apps__: ARRAY of: _[AppMetrics](#AppMetrics)_
### AuthApp
- __app__: _[Application](#Application)_
- __auth_token__: _string_
### ClosedChannel
### AddAppUserRequest
- __identifier__: _string_
- __fail_if_exists__: _boolean_
- __balance__: _number_
### OpenChannel
- __channel_id__: _string_
- __capacity__: _number_
- __closed_height__: _number_
- __active__: _boolean_
- __lifetime__: _number_
- __local_balance__: _number_
- __remote_balance__: _number_
### PayAddressResponse
- __txId__: _string_
- __operation_id__: _string_
- __service_fee__: _number_
- __network_fee__: _number_
### LndGetInfoRequest
- __nodeId__: _number_
### AddAppUserInvoiceRequest
- __receiver_identifier__: _string_
- __payer_identifier__: _string_
- __http_callback_url__: _string_
- __invoice_req__: _[NewInvoiceRequest](#NewInvoiceRequest)_
### NewInvoiceRequest
- __amountSats__: _number_
- __memo__: _string_
### LnurlWithdrawInfoResponse
- __tag__: _string_
@ -764,21 +577,228 @@ The nostr server will send back a message response, and inside the body there wi
- __pr__: _string_
- __routes__: ARRAY of: _[Empty](#Empty)_
### GetProductBuyLinkResponse
- __link__: _string_
### NewInvoiceRequest
- __amountSats__: _number_
- __memo__: _string_
### ClosureMigration
- __closes_at_unix__: _number_
### LndMetrics
- __nodes__: ARRAY of: _[LndNodeMetrics](#LndNodeMetrics)_
### AppMetrics
- __app__: _[Application](#Application)_
- __users__: _[UsersInfo](#UsersInfo)_
- __received__: _number_
- __spent__: _number_
- __available__: _number_
- __fees__: _number_
- __invoices__: _number_
- __total_fees__: _number_
- __operations__: ARRAY of: _[UserOperation](#UserOperation)_
### RoutingEvent
- __incoming_channel_id__: _number_
- __incoming_htlc_id__: _number_
- __outgoing_channel_id__: _number_
- __outgoing_htlc_id__: _number_
- __timestamp_ns__: _number_
- __event_type__: _string_
- __incoming_amt_msat__: _number_
- __outgoing_amt_msat__: _number_
- __failure_string__: _string_
- __settled__: _boolean_
- __offchain__: _boolean_
- __forward_fail_event__: _boolean_
### SetMockAppBalanceRequest
- __amount__: _number_
### NewAddressResponse
- __address__: _string_
### PayAddressRequest
- __address__: _string_
- __amoutSats__: _number_
- __satsPerVByte__: _number_
### LnurlLinkResponse
- __lnurl__: _string_
- __k1__: _string_
### SetMockInvoiceAsPaidRequest
- __invoice__: _string_
- __amount__: _number_
### BannedAppUser
- __app_name__: _string_
- __app_id__: _string_
- __user_identifier__: _string_
- __nostr_pub__: _string_
### Application
- __name__: _string_
- __id__: _string_
- __balance__: _number_
- __npub__: _string_
### AddAppInvoiceRequest
- __payer_identifier__: _string_
- __http_callback_url__: _string_
- __invoice_req__: _[NewInvoiceRequest](#NewInvoiceRequest)_
### AddProductRequest
- __name__: _string_
- __price_sats__: _number_
### RelaysMigration
- __relays__: ARRAY of: _string_
### GetProductBuyLinkResponse
- __link__: _string_
### AddAppRequest
- __name__: _string_
- __allow_user_creation__: _boolean_
### SetMockAppUserBalanceRequest
- __user_identifier__: _string_
- __amount__: _number_
### OpenChannelResponse
- __channelId__: _string_
### ClosedChannel
- __channel_id__: _string_
- __capacity__: _number_
- __closed_height__: _number_
### PayAppUserInvoiceRequest
- __user_identifier__: _string_
- __invoice__: _string_
- __amount__: _number_
### EncryptionExchangeRequest
- __publicKey__: _string_
- __deviceId__: _string_
### AppsMetricsRequest
- __from_unix__: _number_ *this field is optional
- __to_unix__: _number_ *this field is optional
- __include_operations__: _boolean_ *this field is optional
### UsersInfo
- __total__: _number_
- __no_balance__: _number_
- __negative_balance__: _number_
- __always_been_inactive__: _number_
- __balance_avg__: _number_
- __balance_median__: _number_
### SendAppUserToAppUserPaymentRequest
- __from_user_identifier__: _string_
- __to_user_identifier__: _string_
- __amount__: _number_
### NewInvoiceResponse
- __invoice__: _string_
### UserInfo
- __userId__: _string_
- __balance__: _number_
- __max_withdrawable__: _number_
- __user_identifier__: _string_
### GetUserOperationsRequest
- __latestIncomingInvoice__: _number_
- __latestOutgoingInvoice__: _number_
- __latestIncomingTx__: _number_
- __latestOutgoingTx__: _number_
- __latestIncomingUserToUserPayment__: _number_
- __latestOutgoingUserToUserPayment__: _number_
- __max_size__: _number_
### Empty
### BanUserRequest
- __user_id__: _string_
### GetAppUserRequest
- __user_identifier__: _string_
### ChannelRouting
- __channel_id__: _string_
- __send_errors__: _number_
- __receive_errors__: _number_
- __forward_errors_as_input__: _number_
- __forward_errors_as_output__: _number_
- __missed_forward_fee_as_input__: _number_
- __missed_forward_fee_as_output__: _number_
- __forward_fee_as_input__: _number_
- __forward_fee_as_output__: _number_
- __events_number__: _number_
### PayInvoiceRequest
- __invoice__: _string_
- __amount__: _number_
### AppsMetrics
- __apps__: ARRAY of: _[AppMetrics](#AppMetrics)_
### LndGetInfoResponse
- __alias__: _string_
### UserOperation
- __paidAtUnix__: _number_
- __type__: _[UserOperationType](#UserOperationType)_
- __inbound__: _boolean_
- __amount__: _number_
- __identifier__: _string_
- __operationId__: _string_
- __service_fee__: _number_
- __network_fee__: _number_
- __confirmed__: _boolean_
- __tx_hash__: _string_
- __internal__: _boolean_
### UsageMetrics
- __metrics__: ARRAY of: _[UsageMetric](#UsageMetric)_
### AppUser
- __identifier__: _string_
- __info__: _[UserInfo](#UserInfo)_
- __max_withdrawable__: _number_
### PayInvoiceResponse
- __preimage__: _string_
- __amount_paid__: _number_
- __operation_id__: _string_
- __service_fee__: _number_
- __network_fee__: _number_
### PayAddressResponse
- __txId__: _string_
- __operation_id__: _string_
- __service_fee__: _number_
- __network_fee__: _number_
### DecodeInvoiceRequest
- __invoice__: _string_
### DecodeInvoiceResponse
- __amount__: _number_
### LndMetricsRequest
- __from_unix__: _number_ *this field is optional
- __to_unix__: _number_ *this field is optional
### LndNodeMetrics
- __channels_balance_events__: ARRAY of: _[ChannelBalanceEvent](#ChannelBalanceEvent)_
- __chain_balance_events__: ARRAY of: _[ChainBalanceEvent](#ChainBalanceEvent)_
- __offline_channels__: _number_
- __online_channels__: _number_
- __pending_channels__: _number_
- __closing_channels__: _number_
- __open_channels__: ARRAY of: _[OpenChannel](#OpenChannel)_
- __closed_channels__: ARRAY of: _[ClosedChannel](#ClosedChannel)_
- __channel_routing__: ARRAY of: _[ChannelRouting](#ChannelRouting)_
### LndMetrics
- __nodes__: ARRAY of: _[LndNodeMetrics](#LndNodeMetrics)_
## Enums
### The enumerators used in the messages

File diff suppressed because it is too large Load diff

View file

@ -99,6 +99,28 @@ 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.BanUser) throw new Error('method: BanUser is not implemented')
app.post('/api/admin/user/ban', async (req, res) => {
const info: Types.RequestInfo = { rpcName: 'BanUser', 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.BanUser) throw new Error('method: BanUser 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.BanUserRequestValidate(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.BanUser({rpcName:'BanUser', 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.GetUsageMetrics) throw new Error('method: GetUsageMetrics is not implemented')
app.post('/api/admin/metrics/usage', async (req, res) => {
const info: Types.RequestInfo = { rpcName: 'GetUsageMetrics', batch: false, nostr: false, batchSize: 0}

View file

@ -58,6 +58,20 @@ export default (params: ClientParams) => ({
}
return { status: 'ERROR', reason: 'invalid response' }
},
BanUser: async (request: Types.BanUserRequest): Promise<ResultError | ({ status: 'OK' }& Types.BanUserResponse)> => {
const auth = await params.retrieveAdminAuth()
if (auth === null) throw new Error('retrieveAdminAuth() returned null')
let finalRoute = '/api/admin/user/ban'
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.BanUserResponseValidate(result)
if (error === null) { return { status: 'OK', ...result } } else return { status: 'ERROR', reason: error.message }
}
return { status: 'ERROR', reason: 'invalid response' }
},
GetUsageMetrics: async (): Promise<ResultError | ({ status: 'OK' }& Types.UsageMetrics)> => {
const auth = await params.retrieveMetricsAuth()
if (auth === null) throw new Error('retrieveMetricsAuth() returned null')

File diff suppressed because it is too large Load diff

View file

@ -106,6 +106,12 @@ service LightningPub {
option (http_route) = "/api/admin/app/auth";
}
rpc BanUser(structs.BanUserRequest) returns (structs.BanUserResponse) {
option (auth_type) = "Admin";
option (http_method) = "post";
option (http_route) = "/api/admin/user/ban";
}
rpc GetUsageMetrics(structs.Empty) returns (structs.UsageMetrics) {
option (auth_type) = "Metrics";
option (http_method) = "post";
@ -123,6 +129,8 @@ service LightningPub {
option (http_method) = "post";
option (http_route) = "/api/admin/metrics/lnd";
}
// </Admin>
// <Guest>

View file

@ -155,6 +155,21 @@ message LndGetInfoResponse {
string alias = 1;
}
message BanUserRequest {
string user_id = 1;
}
message BannedAppUser {
string app_name = 1;
string app_id = 2;
string user_identifier = 3;
string nostr_pub = 4;
}
message BanUserResponse {
int64 balance_sats = 1;
repeated BannedAppUser banned_app_users = 2;
}
message AddAppRequest {
string name = 1;
bool allow_user_creation = 2;

View file

@ -2,62 +2,26 @@ import 'dotenv/config'
import NewServer from '../proto/autogenerated/ts/express_server.js'
import GetServerMethods from './services/serverMethods/index.js'
import serverOptions from './auth.js';
import Main, { LoadMainSettingsFromEnv } from './services/main/index.js'
import Storage from './services/storage/index.js'
import { LoadNosrtSettingsFromEnv } from './services/nostr/index.js'
import nostrMiddleware from './nostrMiddleware.js'
import { TypeOrmMigrationRunner } from './services/storage/migrations/runner.js';
import { getLogger } from './services/helpers/logger.js';
import { initMainHandler } from './services/main/init.js';
import { LoadMainSettingsFromEnv } from './services/main/settings.js';
const start = async () => {
const log = getLogger({})
const mainSettings = LoadMainSettingsFromEnv()
const storageManager = new Storage(mainSettings.storageSettings)
const manualMigration = await TypeOrmMigrationRunner(log, storageManager, mainSettings.storageSettings.dbSettings, process.argv[2])
if (manualMigration) {
log("migrations run sucessfully, exiting")
const keepOn = await initMainHandler(log, mainSettings)
if (!keepOn) {
log("manual process ended")
return
}
if (process.argv[2] === 'updateUserBalance') {
await storageManager.userStorage.UpdateUser(process.argv[3], { balance_sats: +process.argv[4] })
log("user balance updated correctly")
}
const mainHandler = new Main(mainSettings, storageManager)
await mainHandler.lnd.Warmup()
if (!mainSettings.skipSanityCheck) {
const totalUsersBalance = await mainHandler.VerifyEventsLog()
await mainHandler.paymentManager.watchDog.SeedLndBalance(totalUsersBalance)
}
const { apps, mainHandler } = keepOn
const serverMethods = GetServerMethods(mainHandler)
const nostrSettings = LoadNosrtSettingsFromEnv()
const appsData = await mainHandler.storage.applicationStorage.GetApplications()
const existingWalletApp = await appsData.find(app => app.name === 'wallet' || app.name === 'wallet-test')
if (!existingWalletApp) {
log("no default wallet app found, creating one...")
const newWalletApp = await mainHandler.storage.applicationStorage.AddApplication('wallet', true)
appsData.push(newWalletApp)
}
const apps = await Promise.all(appsData.map(app => {
if (!app.nostr_private_key || !app.nostr_public_key) { // TMP --
return mainHandler.storage.applicationStorage.GenerateApplicationKeys(app);
} // --
else {
return { privateKey: app.nostr_private_key, publicKey: app.nostr_public_key, appId: app.app_id, name: app.name }
}
}))
const { Send } = nostrMiddleware(serverMethods, mainHandler, { ...nostrSettings, apps })
mainHandler.attachNostrSend(Send)
const Server = NewServer(serverMethods, serverOptions(mainHandler))
if (process.argv[2] === 'unlock') {
const u = process.argv[3]
if (u) {
console.log("unlocking user", u)
await mainHandler.storage.userStorage.UnlockUser(u)
} else {
console.log("no user id found to unlock")
}
}
Server.Listen(mainSettings.servicePort)
}
start()

View file

@ -10,7 +10,7 @@ export default (serverMethods: Types.ServerMethods, mainHandler: Main, nostrSett
const nostrTransport = NewNostrTransport(serverMethods, {
NostrUserAuthGuard: async (appId, pub) => {
const app = await mainHandler.storage.applicationStorage.GetApplication(appId || "")
let nostrUser = await mainHandler.storage.applicationStorage.GetOrCreateNostrAppUser(app, pub || "")
const nostrUser = await mainHandler.storage.applicationStorage.GetOrCreateNostrAppUser(app, pub || "")
return { user_id: nostrUser.user.user_id, app_user_id: nostrUser.identifier, app_id: appId || "" }
},
metricsCallback: metrics => mainHandler.settings.recordPerformance ? mainHandler.metricsManager.AddMetrics(metrics) : null,

View file

@ -5,7 +5,7 @@ import { AddressPaidCb, BalanceInfo, DecodedInvoice, HtlcCb, Invoice, InvoicePai
import LND from './lnd.js'
import MockLnd from './mock.js'
import { getLogger } from '../helpers/logger.js'
export const LoadLndSettingsFromEnv = (test = false): LndSettings => {
export const LoadLndSettingsFromEnv = (): LndSettings => {
const lndAddr = EnvMustBeNonEmptyString("LND_ADDRESS")
const lndCertPath = EnvMustBeNonEmptyString("LND_CERT_PATH")
const lndMacaroonPath = EnvMustBeNonEmptyString("LND_MACAROON_PATH")

View file

@ -5,7 +5,7 @@ import NewLightningHandler, { LightningHandler, LoadLndSettingsFromEnv } from '.
let lnd: LightningHandler
export const ignore = true
export const setup = async () => {
lnd = NewLightningHandler(LoadLndSettingsFromEnv(true), console.log, console.log, console.log, console.log)
lnd = NewLightningHandler(LoadLndSettingsFromEnv(), console.log, console.log, console.log, console.log)
await lnd.Warmup()
}
export const teardown = () => {

View file

@ -31,9 +31,23 @@ export default class {
return decoded
}
async BanUser(userId: string): Promise<Types.BanUserResponse> {
const banned = await this.storage.userStorage.BanUser(userId)
const appUsers = await this.storage.applicationStorage.GetAllAppUsersFromUser(userId)
return {
balance_sats: banned.balance_sats,
banned_app_users: appUsers.map(appUser => ({
app_id: appUser.application.app_id,
app_name: appUser.application.name,
user_identifier: appUser.identifier,
nostr_pub: appUser.nostr_public_key || ""
}))
}
}
async GetUserInfo(ctx: Types.UserContext): Promise<Types.UserInfo> {
const user = await this.storage.userStorage.GetUser(ctx.user_id)
const app = await this.storage.applicationStorage.GetApplication(ctx.app_id);
const app = await this.storage.applicationStorage.GetApplication(ctx.app_id)
const appUser = await this.storage.applicationStorage.GetAppUserFromUser(app, user.user_id)
if (!appUser) {
throw new Error(`app user ${ctx.user_id} not found`) // TODO: fix logs doxing

View file

@ -2,43 +2,20 @@ import crypto from 'crypto'
import fetch from "node-fetch"
import Storage, { LoadStorageSettingsFromEnv } from '../storage/index.js'
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 PaymentManager, { PendingTx } from './paymentManager.js'
import { MainSettings } from './settings.js'
import NewLightningHandler, { LoadLndSettingsFromEnv, LightningHandler } from "../lnd/index.js"
import NewLightningHandler, { LightningHandler } from "../lnd/index.js"
import { AddressPaidCb, HtlcCb, InvoicePaidCb, NewBlockCb } from "../lnd/settings.js"
import { getLogger, PubLogger } from "../helpers/logger.js"
import AppUserManager from "./appUserManager.js"
import { Application } from '../storage/entity/Application.js'
import { UserReceivingInvoice, ZapInfo } from '../storage/entity/UserReceivingInvoice.js'
import { UserReceivingInvoice } from '../storage/entity/UserReceivingInvoice.js'
import { UnsignedEvent } from '../nostr/tools/event.js'
import { NostrSend } from '../nostr/handler.js'
import MetricsManager from '../metrics/index.js'
import EventsLogManager, { LoggedEvent } from '../storage/eventsLog.js'
import { LoadWatchdogSettingsFromEnv } from '../lnd/watchdog.js'
export const LoadMainSettingsFromEnv = (test = false): MainSettings => {
return {
watchDogSettings: LoadWatchdogSettingsFromEnv(test),
lndSettings: LoadLndSettingsFromEnv(test),
storageSettings: LoadStorageSettingsFromEnv(test),
jwtSecret: EnvMustBeNonEmptyString("JWT_SECRET"),
incomingTxFee: EnvMustBeInteger("INCOMING_CHAIN_FEE_ROOT_BPS") / 10000,
outgoingTxFee: EnvMustBeInteger("OUTGOING_CHAIN_FEE_ROOT_BPS") / 10000,
incomingAppInvoiceFee: EnvMustBeInteger("INCOMING_INVOICE_FEE_ROOT_BPS") / 10000,
outgoingAppInvoiceFee: EnvMustBeInteger("OUTGOING_INVOICE_FEE_ROOT_BPS") / 10000,
incomingAppUserInvoiceFee: EnvMustBeInteger("INCOMING_INVOICE_FEE_USER_BPS") / 10000,
outgoingAppUserInvoiceFee: EnvMustBeInteger("OUTGOING_INVOICE_FEE_USER_BPS") / 10000,
userToUserFee: EnvMustBeInteger("TX_FEE_INTERNAL_USER_BPS") / 10000,
appToUserFee: EnvMustBeInteger("TX_FEE_INTERNAL_ROOT_BPS") / 10000,
serviceUrl: EnvMustBeNonEmptyString("SERVICE_URL"),
servicePort: EnvMustBeInteger("PORT"),
recordPerformance: process.env.RECORD_PERFORMANCE === 'true' || false,
skipSanityCheck: process.env.SKIP_SANITY_CHECK === 'true' || false,
disableExternalPayments: process.env.DISABLE_EXTERNAL_PAYMENTS === 'true' || false
}
}
import { LoggedEvent } from '../storage/eventsLog.js'
type UserOperationsSub = {
id: string

58
src/services/main/init.ts Normal file
View file

@ -0,0 +1,58 @@
import { PubLogger, getLogger } from "../helpers/logger.js"
import Storage from "../storage/index.js"
import { TypeOrmMigrationRunner } from "../storage/migrations/runner.js"
import Main from "./index.js"
import { MainSettings } from "./settings.js"
export type AppData = {
privateKey: string;
publicKey: string;
appId: string;
name: string;
}
export const initMainHandler = async (log: PubLogger, mainSettings: MainSettings) => {
const storageManager = new Storage(mainSettings.storageSettings)
const manualMigration = await TypeOrmMigrationRunner(log, storageManager, mainSettings.storageSettings.dbSettings, process.argv[2])
if (manualMigration) {
return
}
const mainHandler = new Main(mainSettings, storageManager)
await mainHandler.lnd.Warmup()
if (!mainSettings.skipSanityCheck) {
await mainHandler.VerifyEventsLog()
}
const appsData = await mainHandler.storage.applicationStorage.GetApplications()
const existingWalletApp = await appsData.find(app => app.name === 'wallet' || app.name === 'wallet-test')
if (!existingWalletApp) {
log("no default wallet app found, creating one...")
const newWalletApp = await mainHandler.storage.applicationStorage.AddApplication('wallet', true)
appsData.push(newWalletApp)
}
const apps: AppData[] = await Promise.all(appsData.map(app => {
if (!app.nostr_private_key || !app.nostr_public_key) { // TMP --
return mainHandler.storage.applicationStorage.GenerateApplicationKeys(app);
} // --
else {
return { privateKey: app.nostr_private_key, publicKey: app.nostr_public_key, appId: app.app_id, name: app.name }
}
}))
const stop = await processArgs(mainHandler)
if (stop) {
return
}
return { mainHandler, apps }
}
const processArgs = async (mainHandler: Main) => {
switch (process.argv[2]) {
case 'updateUserBalance':
await mainHandler.storage.userStorage.UpdateUser(process.argv[3], { balance_sats: +process.argv[4] })
getLogger({ userId: process.argv[3] })(`user balance updated correctly`)
return false
case 'unlock':
await mainHandler.storage.userStorage.UnbanUser(process.argv[3])
getLogger({ userId: process.argv[3] })(`user unlocked`)
return false
default:
return false
}
}

View file

@ -0,0 +1,47 @@
import 'dotenv/config' // TODO - test env
import chai from 'chai'
import { AppData, initMainHandler } from './init.js'
import Main from './index.js'
import { User } from '../storage/entity/User.js'
import { LoadMainSettingsFromEnv, LoadTestSettingsFromEnv, MainSettings } from './settings.js'
import chaiString from 'chai-string'
import { defaultInvoiceExpiry } from '../storage/paymentStorage.js'
chai.use(chaiString)
const expect = chai.expect
export const ignore = false
let main: Main
let app: AppData
let user1: { userId: string, appUserIdentifier: string, appId: string }
let user2: { userId: string, appUserIdentifier: string, appId: string }
export const setup = async () => {
const settings = LoadTestSettingsFromEnv()
const initialized = await initMainHandler(console.log, settings)
if (!initialized) {
throw new Error("failed to initialize main handler")
}
main = initialized.mainHandler
app = initialized.apps[0]
const u1 = await main.applicationManager.AddAppUser(app.appId, { identifier: "user1", balance: 0, fail_if_exists: true })
const u2 = await main.applicationManager.AddAppUser(app.appId, { identifier: "user2", balance: 2000, fail_if_exists: true })
user1 = { userId: u1.info.userId, appUserIdentifier: u1.identifier, appId: app.appId }
user2 = { userId: u2.info.userId, appUserIdentifier: u2.identifier, appId: app.appId }
}
export const teardown = () => {
console.log("teardown")
}
export default async (d: (message: string, failure?: boolean) => void) => {
const application = await main.storage.applicationStorage.GetApplication(app.appId)
const invoice = await main.paymentManager.NewInvoice(user1.userId, { amountSats: 1000, memo: "test" }, { linkedApplication: application, expiry: defaultInvoiceExpiry })
expect(invoice.invoice).to.startWith("lnbcrtmockin")
d("got the invoice")
const pay = await main.paymentManager.PayInvoice(user2.userId, { invoice: invoice.invoice, amount: 0 }, application)
expect(pay.amount_paid).to.be.equal(1000)
const u1 = await main.storage.userStorage.GetUser(user1.userId)
const u2 = await main.storage.userStorage.GetUser(user2.userId)
const owner = await main.storage.userStorage.GetUser(application.owner.user_id)
expect(u1.balance_sats).to.be.equal(1000)
expect(u2.balance_sats).to.be.equal(994)
expect(owner.balance_sats).to.be.equal(6)
}

View file

@ -100,6 +100,9 @@ export default class {
async NewAddress(ctx: Types.UserContext, req: Types.NewAddressRequest): Promise<Types.NewAddressResponse> {
const app = await this.storage.applicationStorage.GetApplication(ctx.app_id)
const user = await this.storage.userStorage.GetUser(ctx.user_id)
if (user.locked) {
throw new Error("user is banned, cannot generate address")
}
const existingAddress = await this.storage.paymentStorage.GetExistingUserAddress(ctx.user_id, app)
if (existingAddress) {
return { address: existingAddress.address }
@ -112,6 +115,9 @@ export default class {
async NewInvoice(userId: string, req: Types.NewInvoiceRequest, options: InboundOptionals = { expiry: defaultInvoiceExpiry }): Promise<Types.NewInvoiceResponse> {
const user = await this.storage.userStorage.GetUser(userId)
if (user.locked) {
throw new Error("user is banned, cannot generate invoice")
}
const res = await this.lnd.NewInvoice(req.amountSats, req.memo, options.expiry)
const userInvoice = await this.storage.paymentStorage.AddUserInvoice(user, res.payRequest, options)
const appId = options.linkedApplication ? options.linkedApplication.app_id : ""
@ -145,6 +151,10 @@ export default class {
async PayInvoice(userId: string, req: Types.PayInvoiceRequest, linkedApplication: Application): Promise<Types.PayInvoiceResponse> {
this.log("paying invoice", req.invoice, "for user", userId, "with amount", req.amount)
await this.WatchdogCheck()
const maybeBanned = await this.storage.userStorage.GetUser(userId)
if (maybeBanned.locked) {
throw new Error("user is banned, cannot send payment")
}
const decoded = await this.lnd.DecodeInvoice(req.invoice)
if (decoded.numSatoshis !== 0 && req.amount !== 0) {
throw new Error("invoice has value, do not provide amount the the request")
@ -202,6 +212,11 @@ export default class {
async PayAddress(ctx: Types.UserContext, req: Types.PayAddressRequest): Promise<Types.PayAddressResponse> {
throw new Error("address payment currently disabled, use Lightning instead")
await this.WatchdogCheck()
this.log("paying address", req.address, "for user", ctx.user_id, "with amount", req.amoutSats)
const maybeBanned = await this.storage.userStorage.GetUser(ctx.user_id)
if (maybeBanned.locked) {
throw new Error("user is banned, cannot send chain tx")
}
const { blockHeight } = await this.lnd.GetInfo()
const app = await this.storage.applicationStorage.GetApplication(ctx.app_id)
const serviceFee = this.getServiceFee(Types.UserOperationType.OUTGOING_TX, req.amoutSats, false)
@ -469,6 +484,10 @@ export default class {
}
async GetUserOperations(userId: string, req: Types.GetUserOperationsRequest): Promise<Types.GetUserOperationsResponse> {
const user = await this.storage.userStorage.GetUser(userId)
if (user.locked) {
throw new Error("user is banned, cannot retrieve operations")
}
const [outgoingInvoices, outgoingTransactions, incomingInvoices, incomingTransactions, incomingUserToUser, outgoingUserToUser] = await Promise.all([
this.storage.paymentStorage.GetUserInvoicePayments(userId, req.latestOutgoingInvoice, req.max_size),
this.storage.paymentStorage.GetUserTransactionPayments(userId, req.latestOutgoingTx, req.max_size),
@ -492,6 +511,9 @@ export default class {
await this.storage.StartTransaction(async tx => {
const fromUser = await this.storage.userStorage.GetUser(fromUserId, tx)
const toUser = await this.storage.userStorage.GetUser(toUserId, tx)
if (fromUser.locked || toUser.locked) {
throw new Error("one of the users is banned, cannot send payment")
}
if (fromUser.balance_sats < amount) {
throw new Error("not enough balance to send payment")
}

View file

@ -1,6 +1,8 @@
import { StorageSettings } from '../storage/index.js'
import { LoadStorageSettingsFromEnv, StorageSettings } from '../storage/index.js'
import { LndSettings } from '../lnd/settings.js'
import { WatchdogSettings } from '../lnd/watchdog.js'
import { LoadWatchdogSettingsFromEnv, WatchdogSettings } from '../lnd/watchdog.js'
import { LoadLndSettingsFromEnv } from '../lnd/index.js'
import { EnvMustBeInteger, EnvMustBeNonEmptyString } from '../helpers/envParser.js'
export type MainSettings = {
storageSettings: StorageSettings,
lndSettings: LndSettings,
@ -19,5 +21,35 @@ export type MainSettings = {
recordPerformance: boolean
skipSanityCheck: boolean
disableExternalPayments: boolean
}
export const LoadMainSettingsFromEnv = (): MainSettings => {
return {
watchDogSettings: LoadWatchdogSettingsFromEnv(),
lndSettings: LoadLndSettingsFromEnv(),
storageSettings: LoadStorageSettingsFromEnv(),
jwtSecret: EnvMustBeNonEmptyString("JWT_SECRET"),
incomingTxFee: EnvMustBeInteger("INCOMING_CHAIN_FEE_ROOT_BPS") / 10000,
outgoingTxFee: EnvMustBeInteger("OUTGOING_CHAIN_FEE_ROOT_BPS") / 10000,
incomingAppInvoiceFee: EnvMustBeInteger("INCOMING_INVOICE_FEE_ROOT_BPS") / 10000,
outgoingAppInvoiceFee: EnvMustBeInteger("OUTGOING_INVOICE_FEE_ROOT_BPS") / 10000,
incomingAppUserInvoiceFee: EnvMustBeInteger("INCOMING_INVOICE_FEE_USER_BPS") / 10000,
outgoingAppUserInvoiceFee: EnvMustBeInteger("OUTGOING_INVOICE_FEE_USER_BPS") / 10000,
userToUserFee: EnvMustBeInteger("TX_FEE_INTERNAL_USER_BPS") / 10000,
appToUserFee: EnvMustBeInteger("TX_FEE_INTERNAL_ROOT_BPS") / 10000,
serviceUrl: EnvMustBeNonEmptyString("SERVICE_URL"),
servicePort: EnvMustBeInteger("PORT"),
recordPerformance: process.env.RECORD_PERFORMANCE === 'true' || false,
skipSanityCheck: process.env.SKIP_SANITY_CHECK === 'true' || false,
disableExternalPayments: process.env.DISABLE_EXTERNAL_PAYMENTS === 'true' || false,
}
}
export const LoadTestSettingsFromEnv = (): MainSettings => {
const settings = LoadMainSettingsFromEnv()
return {
...settings,
storageSettings: { dbSettings: { ...settings.storageSettings.dbSettings, databaseFile: ":memory:", metricsDatabaseFile: ":memory:" } },
skipSanityCheck: true
}
}

View file

@ -19,6 +19,13 @@ export default (mainHandler: Main): Types.ServerMethods => {
const info = await mainHandler.lnd.GetInfo()
return { alias: info.alias }
},
BanUser: async ({ ctx, req }) => {
const err = Types.BanUserRequestValidate(req, {
user_id_CustomCheck: id => id !== ''
})
if (err != null) throw new Error(err.message)
return mainHandler.appUserManager.BanUser(req.user_id)
},
SetMockInvoiceAsPaid: async ({ ctx, req }) => {
const err = Types.SetMockInvoiceAsPaidRequestValidate(req, {
invoice_CustomCheck: invoice => invoice !== '',

View file

@ -142,7 +142,11 @@ export default class {
}
async GetAppUserFromUser(application: Application, userId: string, entityManager = this.DB): Promise<ApplicationUser | null> {
return await entityManager.getRepository(ApplicationUser).findOne({ where: { user: { user_id: userId }, application: { app_id: application.app_id } } })
return entityManager.getRepository(ApplicationUser).findOne({ where: { user: { user_id: userId }, application: { app_id: application.app_id } } })
}
async GetAllAppUsersFromUser(userId: string, entityManager = this.DB): Promise<ApplicationUser[]> {
return entityManager.getRepository(ApplicationUser).find({ where: { user: { user_id: userId } } })
}
async IsApplicationOwner(userId: string, entityManager = this.DB) {

View file

@ -24,11 +24,11 @@ export type DbSettings = {
migrate: boolean
metricsDatabaseFile: string
}
export const LoadDbSettingsFromEnv = (test = false): DbSettings => {
export const LoadDbSettingsFromEnv = (): DbSettings => {
return {
databaseFile: test ? ":memory:" : EnvMustBeNonEmptyString("DATABASE_FILE"),
databaseFile: EnvMustBeNonEmptyString("DATABASE_FILE"),
migrate: process.env.MIGRATE_DB === 'true' || false,
metricsDatabaseFile: test ? ":memory" : EnvMustBeNonEmptyString("METRICS_DATABASE_FILE")
metricsDatabaseFile: EnvMustBeNonEmptyString("METRICS_DATABASE_FILE")
}
}

View file

@ -10,8 +10,8 @@ import EventsLogManager from "./eventsLog.js";
export type StorageSettings = {
dbSettings: DbSettings
}
export const LoadStorageSettingsFromEnv = (test = false): StorageSettings => {
return { dbSettings: LoadDbSettingsFromEnv(test) }
export const LoadStorageSettingsFromEnv = (): StorageSettings => {
return { dbSettings: LoadDbSettingsFromEnv() }
}
export default class {
DB: DataSource | EntityManager

View file

@ -14,6 +14,7 @@ export default class {
this.txQueue = txQueue
this.eventsLog = eventsLog
}
async AddUser(balance: number, dbTx: DataSource | EntityManager): Promise<User> {
if (balance && process.env.ALLOW_BALANCE_MIGRATION !== 'true') {
throw new Error("balance migration is not allowed")
@ -53,15 +54,7 @@ export default class {
return user
}
async LockUser(userId: string, entityManager = this.DB) {
const res = await entityManager.getRepository(User).update({
user_id: userId
}, { locked: true })
if (!res.affected) {
throw new Error("unaffected user lock for " + userId) // TODO: fix logs doxing
}
}
async UnlockUser(userId: string, entityManager = this.DB) {
async UnbanUser(userId: string, entityManager = this.DB) {
const res = await entityManager.getRepository(User).update({
user_id: userId
}, { locked: false })
@ -69,6 +62,20 @@ export default class {
throw new Error("unaffected user unlock for " + userId) // TODO: fix logs doxing
}
}
async BanUser(userId: string, entityManager = this.DB) {
const user = await this.GetUser(userId, entityManager)
const res = await entityManager.getRepository(User).update({
user_id: userId
}, { balance_sats: 0, locked: true })
if (!res.affected) {
throw new Error("unaffected ban user for " + userId) // TODO: fix logs doxing
}
if (user.balance_sats > 0) {
this.eventsLog.LogEvent({ type: 'balance_decrement', userId, appId: "", appUserId: "", balance: user.balance_sats, data: 'ban', amount: user.balance_sats })
}
return user
}
async IncrementUserBalance(userId: string, increment: number, reason: string, entityManager = this.DB) {
const user = await this.GetUser(userId, entityManager)
const res = await entityManager.getRepository(User).increment({

View file

@ -24,7 +24,6 @@ const start = async () => {
}
const runTestFile = async (fileName: string, mod: TestModule) => {
const d = getDescribe(fileName)
if (mod.ignore) {