authorization hook, and spec changes

This commit is contained in:
boufni95 2024-09-18 18:49:29 +00:00
parent 6df5752d46
commit 49b8dd693c
19 changed files with 2655 additions and 216 deletions

View file

@ -30,8 +30,8 @@ The nostr server will send back a message response, and inside the body there wi
- AuthorizeDebit
- auth type: __User__
- input: [DebitAuthorization](#DebitAuthorization)
- output: [AuthorizedDebit](#AuthorizedDebit)
- input: [DebitAuthorizationRequest](#DebitAuthorizationRequest)
- output: [DebitAuthorization](#DebitAuthorization)
- BanUser
- auth type: __Admin__
@ -63,10 +63,10 @@ The nostr server will send back a message response, and inside the body there wi
- input: [AppsMetricsRequest](#AppsMetricsRequest)
- output: [AppsMetrics](#AppsMetrics)
- GetAuthorizedDebits
- GetDebitAuthorizations
- auth type: __User__
- This methods has an __empty__ __request__ body
- output: [AuthorizedDebits](#AuthorizedDebits)
- output: [DebitAuthorizations](#DebitAuthorizations)
- GetHttpCreds
- auth type: __User__
@ -83,6 +83,11 @@ The nostr server will send back a message response, and inside the body there wi
- This methods has an __empty__ __request__ body
- output: [LnurlLinkResponse](#LnurlLinkResponse)
- GetLiveDebitRequests
- auth type: __User__
- This methods has an __empty__ __request__ body
- output: [LiveDebitRequest](#LiveDebitRequest)
- GetLiveUserOperations
- auth type: __User__
- This methods has an __empty__ __request__ body
@ -275,8 +280,8 @@ The nostr server will send back a message response, and inside the body there wi
- auth type: __User__
- http method: __post__
- http route: __/api/user/debit/authorize__
- input: [DebitAuthorization](#DebitAuthorization)
- output: [AuthorizedDebit](#AuthorizedDebit)
- input: [DebitAuthorizationRequest](#DebitAuthorizationRequest)
- output: [DebitAuthorization](#DebitAuthorization)
- BanUser
- auth type: __Admin__
@ -348,12 +353,12 @@ The nostr server will send back a message response, and inside the body there wi
- input: [AppsMetricsRequest](#AppsMetricsRequest)
- output: [AppsMetrics](#AppsMetrics)
- GetAuthorizedDebits
- GetDebitAuthorizations
- auth type: __User__
- http method: __get__
- http route: __/api/user/debit/get__
- This methods has an __empty__ __request__ body
- output: [AuthorizedDebits](#AuthorizedDebits)
- output: [DebitAuthorizations](#DebitAuthorizations)
- GetHttpCreds
- auth type: __User__
@ -376,6 +381,13 @@ The nostr server will send back a message response, and inside the body there wi
- This methods has an __empty__ __request__ body
- output: [LnurlLinkResponse](#LnurlLinkResponse)
- GetLiveDebitRequests
- auth type: __User__
- http method: __post__
- http route: __/api/user/debit/sub__
- This methods has an __empty__ __request__ body
- output: [LiveDebitRequest](#LiveDebitRequest)
- GetLiveUserOperations
- auth type: __User__
- http method: __post__
@ -711,14 +723,6 @@ The nostr server will send back a message response, and inside the body there wi
- __allow_user_creation__: _boolean_ *this field is optional
- __name__: _string_
### AuthorizedDebit
- __debit_id__: _string_
- __debit_type__: _[AuthorizedDebitType](#AuthorizedDebitType)_
- __key__: _string_
### AuthorizedDebits
- __debits__: ARRAY of: _[AuthorizedDebit](#AuthorizedDebit)_
### BanUserRequest
- __user_id__: _string_
@ -747,7 +751,23 @@ The nostr server will send back a message response, and inside the body there wi
- __invitation_link__: _string_
### DebitAuthorization
- __authorize_npub__: _string_ *this field is optional
- __authorized__: _boolean_
- __debit_id__: _string_
- __npub__: _string_
- __rules__: ARRAY of: _[DebitRule](#DebitRule)_
### DebitAuthorizationRequest
- __authorize_npub__: _string_
- __rules__: ARRAY of: _[DebitRule](#DebitRule)_
### DebitAuthorizations
- __debits__: ARRAY of: _[DebitAuthorization](#DebitAuthorization)_
### DebitExpirationRule
- __expires_at_unix__: _number_
### DebitRule
- __rule__: _[DebitRule_rule](#DebitRule_rule)_
### DecodeInvoiceRequest
- __invoice__: _string_
@ -764,6 +784,10 @@ The nostr server will send back a message response, and inside the body there wi
### EnrollAdminTokenRequest
- __admin_token__: _string_
### FrequencyRule
- __interval__: _[IntervalType](#IntervalType)_
- __number_of_intervals__: _number_
### GetAppUserLNURLInfoRequest
- __base_url_override__: _string_
- __user_identifier__: _string_
@ -815,6 +839,11 @@ The nostr server will send back a message response, and inside the body there wi
### LinkNPubThroughTokenRequest
- __token__: _string_
### LiveDebitRequest
- __amount__: _number_
- __debit__: _[LiveDebitRequest_debit](#LiveDebitRequest_debit)_
- __npub__: _string_
### LiveUserOperation
- __operation__: _[UserOperation](#UserOperation)_
@ -951,7 +980,7 @@ The nostr server will send back a message response, and inside the body there wi
- __relays__: ARRAY of: _string_
### RemoveAuthorizedDebitRequest
- __debit_id__: _string_
- __npub__: _string_
### RequestNPubLinkingTokenRequest
- __user_identifier__: _string_
@ -1053,9 +1082,10 @@ The nostr server will send back a message response, and inside the body there wi
- __TAPROOT_PUBKEY__
- __WITNESS_PUBKEY_HASH__
### AuthorizedDebitType
- __KEY__
- __NPUB__
### IntervalType
- __DAY__
- __MONTH__
- __WEEK__
### UserOperationType
- __INCOMING_INVOICE__

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,515 @@
// This file was autogenerated from a .proto file, DO NOT EDIT!
package lightning_pub
type ResultError struct {
Status string `json:"status"`
Reason string `json:"reason"`
}
type AdminContext struct {
Admin_id string `json:"admin_id"`
}
type AppContext struct {
App_id string `json:"app_id"`
}
type GuestContext struct {
}
type GuestWithPubContext struct {
App_id string `json:"app_id"`
Pub string `json:"pub"`
}
type MetricsContext struct {
Operator_id string `json:"operator_id"`
}
type UserContext struct {
App_id string `json:"app_id"`
App_user_id string `json:"app_user_id"`
User_id string `json:"user_id"`
}
type GetLnurlPayInfo_Query struct {
K1 *string `json:"k1,omitempty"`
}
type GetLnurlWithdrawInfo_Query struct {
K1 *string `json:"k1,omitempty"`
}
type HandleLnurlAddress_RouteParams struct {
Address_name string `json:"address_name"`
}
type HandleLnurlPay_Query struct {
Amount *string `json:"amount,omitempty"`
K1 *string `json:"k1,omitempty"`
Lnurl *string `json:"lnurl,omitempty"`
Nostr *string `json:"nostr,omitempty"`
}
type HandleLnurlWithdraw_Query struct {
K1 *string `json:"k1,omitempty"`
Pr *string `json:"pr,omitempty"`
}
type NewProductInvoice_Query struct {
Id *string `json:"id,omitempty"`
}
type AddressType string
const (
NESTED_PUBKEY_HASH AddressType = "NESTED_PUBKEY_HASH"
TAPROOT_PUBKEY AddressType = "TAPROOT_PUBKEY"
WITNESS_PUBKEY_HASH AddressType = "WITNESS_PUBKEY_HASH"
)
type IntervalType string
const (
DAY IntervalType = "DAY"
MONTH IntervalType = "MONTH"
WEEK IntervalType = "WEEK"
)
type UserOperationType string
const (
INCOMING_INVOICE UserOperationType = "INCOMING_INVOICE"
INCOMING_TX UserOperationType = "INCOMING_TX"
INCOMING_USER_TO_USER UserOperationType = "INCOMING_USER_TO_USER"
OUTGOING_INVOICE UserOperationType = "OUTGOING_INVOICE"
OUTGOING_TX UserOperationType = "OUTGOING_TX"
OUTGOING_USER_TO_USER UserOperationType = "OUTGOING_USER_TO_USER"
)
type AddAppInvoiceRequest struct {
Http_callback_url string `json:"http_callback_url"`
Invoice_req *NewInvoiceRequest `json:"invoice_req"`
Payer_identifier string `json:"payer_identifier"`
}
type AddAppRequest struct {
Allow_user_creation bool `json:"allow_user_creation"`
Name string `json:"name"`
}
type AddAppUserInvoiceRequest struct {
Http_callback_url string `json:"http_callback_url"`
Invoice_req *NewInvoiceRequest `json:"invoice_req"`
Payer_identifier string `json:"payer_identifier"`
Receiver_identifier string `json:"receiver_identifier"`
}
type AddAppUserRequest struct {
Balance int64 `json:"balance"`
Fail_if_exists bool `json:"fail_if_exists"`
Identifier string `json:"identifier"`
}
type AddProductRequest struct {
Name string `json:"name"`
Price_sats int64 `json:"price_sats"`
}
type AppMetrics struct {
App *Application `json:"app"`
Available int64 `json:"available"`
Fees int64 `json:"fees"`
Invoices int64 `json:"invoices"`
Operations []UserOperation `json:"operations"`
Received int64 `json:"received"`
Spent int64 `json:"spent"`
Total_fees int64 `json:"total_fees"`
Users *UsersInfo `json:"users"`
}
type AppUser struct {
Identifier string `json:"identifier"`
Info *UserInfo `json:"info"`
Max_withdrawable int64 `json:"max_withdrawable"`
}
type Application struct {
Balance int64 `json:"balance"`
Id string `json:"id"`
Name string `json:"name"`
Npub string `json:"npub"`
}
type AppsMetrics struct {
Apps []AppMetrics `json:"apps"`
}
type AppsMetricsRequest struct {
From_unix int64 `json:"from_unix"`
Include_operations bool `json:"include_operations"`
To_unix int64 `json:"to_unix"`
}
type AuthApp struct {
App *Application `json:"app"`
Auth_token string `json:"auth_token"`
}
type AuthAppRequest struct {
Allow_user_creation bool `json:"allow_user_creation"`
Name string `json:"name"`
}
type BanUserRequest struct {
User_id string `json:"user_id"`
}
type BanUserResponse struct {
Balance_sats int64 `json:"balance_sats"`
Banned_app_users []BannedAppUser `json:"banned_app_users"`
}
type BannedAppUser struct {
App_id string `json:"app_id"`
App_name string `json:"app_name"`
Nostr_pub string `json:"nostr_pub"`
User_identifier string `json:"user_identifier"`
}
type ClosedChannel struct {
Capacity int64 `json:"capacity"`
Channel_id string `json:"channel_id"`
Closed_height int64 `json:"closed_height"`
}
type ClosureMigration struct {
Closes_at_unix int64 `json:"closes_at_unix"`
}
type CreateOneTimeInviteLinkRequest struct {
Sats int64 `json:"sats"`
}
type CreateOneTimeInviteLinkResponse struct {
Invitation_link string `json:"invitation_link"`
}
type DebitAuthorization struct {
Authorized bool `json:"authorized"`
Debit_id string `json:"debit_id"`
Npub string `json:"npub"`
Rules []DebitRule `json:"rules"`
}
type DebitAuthorizationRequest struct {
Authorize_npub string `json:"authorize_npub"`
Rules []DebitRule `json:"rules"`
}
type DebitAuthorizations struct {
Debits []DebitAuthorization `json:"debits"`
}
type DebitExpirationRule struct {
Expires_at_unix int64 `json:"expires_at_unix"`
}
type DebitRule struct {
Rule *DebitRule_rule `json:"rule"`
}
type DecodeInvoiceRequest struct {
Invoice string `json:"invoice"`
}
type DecodeInvoiceResponse struct {
Amount int64 `json:"amount"`
}
type Empty struct {
}
type EncryptionExchangeRequest struct {
Deviceid string `json:"deviceId"`
Publickey string `json:"publicKey"`
}
type EnrollAdminTokenRequest struct {
Admin_token string `json:"admin_token"`
}
type FrequencyRule struct {
Interval IntervalType `json:"interval"`
Number_of_intervals int64 `json:"number_of_intervals"`
}
type GetAppUserLNURLInfoRequest struct {
Base_url_override string `json:"base_url_override"`
User_identifier string `json:"user_identifier"`
}
type GetAppUserRequest struct {
User_identifier string `json:"user_identifier"`
}
type GetInviteTokenStateRequest struct {
Invite_token string `json:"invite_token"`
}
type GetInviteTokenStateResponse struct {
Used bool `json:"used"`
}
type GetPaymentStateRequest struct {
Invoice string `json:"invoice"`
}
type GetProductBuyLinkResponse struct {
Link string `json:"link"`
}
type GetUserOperationsRequest struct {
Latestincominginvoice int64 `json:"latestIncomingInvoice"`
Latestincomingtx int64 `json:"latestIncomingTx"`
Latestincomingusertouserpayment int64 `json:"latestIncomingUserToUserPayment"`
Latestoutgoinginvoice int64 `json:"latestOutgoingInvoice"`
Latestoutgoingtx int64 `json:"latestOutgoingTx"`
Latestoutgoingusertouserpayment int64 `json:"latestOutgoingUserToUserPayment"`
Max_size int64 `json:"max_size"`
}
type GetUserOperationsResponse struct {
Latestincominginvoiceoperations *UserOperations `json:"latestIncomingInvoiceOperations"`
Latestincomingtxoperations *UserOperations `json:"latestIncomingTxOperations"`
Latestincomingusertouserpayemnts *UserOperations `json:"latestIncomingUserToUserPayemnts"`
Latestoutgoinginvoiceoperations *UserOperations `json:"latestOutgoingInvoiceOperations"`
Latestoutgoingtxoperations *UserOperations `json:"latestOutgoingTxOperations"`
Latestoutgoingusertouserpayemnts *UserOperations `json:"latestOutgoingUserToUserPayemnts"`
}
type GraphPoint struct {
X int64 `json:"x"`
Y int64 `json:"y"`
}
type HandleLnurlPayResponse struct {
Pr string `json:"pr"`
Routes []Empty `json:"routes"`
}
type HttpCreds struct {
Token string `json:"token"`
Url string `json:"url"`
}
type LinkNPubThroughTokenRequest struct {
Token string `json:"token"`
}
type LiveDebitRequest struct {
Amount int64 `json:"amount"`
Debit *LiveDebitRequest_debit `json:"debit"`
Npub string `json:"npub"`
}
type LiveUserOperation struct {
Operation *UserOperation `json:"operation"`
}
type LndChannels struct {
Open_channels []OpenChannel `json:"open_channels"`
}
type LndGetInfoRequest struct {
Nodeid int64 `json:"nodeId"`
}
type LndGetInfoResponse struct {
Alias string `json:"alias"`
}
type LndMetrics struct {
Nodes []LndNodeMetrics `json:"nodes"`
}
type LndMetricsRequest struct {
From_unix int64 `json:"from_unix"`
To_unix int64 `json:"to_unix"`
}
type LndNodeMetrics struct {
Chain_balance []GraphPoint `json:"chain_balance"`
Channel_balance []GraphPoint `json:"channel_balance"`
Closed_channels []ClosedChannel `json:"closed_channels"`
Closing_channels int64 `json:"closing_channels"`
External_balance []GraphPoint `json:"external_balance"`
Forwarding_events int64 `json:"forwarding_events"`
Forwarding_fees int64 `json:"forwarding_fees"`
Offline_channels int64 `json:"offline_channels"`
Online_channels int64 `json:"online_channels"`
Open_channels []OpenChannel `json:"open_channels"`
Pending_channels int64 `json:"pending_channels"`
}
type LndSeed struct {
Seed []string `json:"seed"`
}
type LnurlLinkResponse struct {
K1 string `json:"k1"`
Lnurl string `json:"lnurl"`
}
type LnurlPayInfoResponse struct {
Allowsnostr bool `json:"allowsNostr"`
Callback string `json:"callback"`
Maxsendable int64 `json:"maxSendable"`
Metadata string `json:"metadata"`
Minsendable int64 `json:"minSendable"`
Nostrpubkey string `json:"nostrPubkey"`
Tag string `json:"tag"`
}
type LnurlWithdrawInfoResponse struct {
Balancecheck string `json:"balanceCheck"`
Callback string `json:"callback"`
Defaultdescription string `json:"defaultDescription"`
K1 string `json:"k1"`
Maxwithdrawable int64 `json:"maxWithdrawable"`
Minwithdrawable int64 `json:"minWithdrawable"`
Paylink string `json:"payLink"`
Tag string `json:"tag"`
}
type MigrationUpdate struct {
Closure *ClosureMigration `json:"closure"`
Relays *RelaysMigration `json:"relays"`
}
type NewAddressRequest struct {
Addresstype AddressType `json:"addressType"`
}
type NewAddressResponse struct {
Address string `json:"address"`
}
type NewInvoiceRequest struct {
Amountsats int64 `json:"amountSats"`
Memo string `json:"memo"`
}
type NewInvoiceResponse struct {
Invoice string `json:"invoice"`
}
type OpenChannel struct {
Active bool `json:"active"`
Capacity int64 `json:"capacity"`
Channel_id string `json:"channel_id"`
Label string `json:"label"`
Lifetime int64 `json:"lifetime"`
Local_balance int64 `json:"local_balance"`
Remote_balance int64 `json:"remote_balance"`
}
type OpenChannelRequest struct {
Closeaddress string `json:"closeAddress"`
Destination string `json:"destination"`
Fundingamount int64 `json:"fundingAmount"`
Pushamount int64 `json:"pushAmount"`
}
type OpenChannelResponse struct {
Channelid string `json:"channelId"`
}
type PayAddressRequest struct {
Address string `json:"address"`
Amoutsats int64 `json:"amoutSats"`
Satspervbyte int64 `json:"satsPerVByte"`
}
type PayAddressResponse struct {
Network_fee int64 `json:"network_fee"`
Operation_id string `json:"operation_id"`
Service_fee int64 `json:"service_fee"`
Txid string `json:"txId"`
}
type PayAppUserInvoiceRequest struct {
Amount int64 `json:"amount"`
Invoice string `json:"invoice"`
User_identifier string `json:"user_identifier"`
}
type PayInvoiceRequest struct {
Amount int64 `json:"amount"`
Invoice string `json:"invoice"`
}
type PayInvoiceResponse struct {
Amount_paid int64 `json:"amount_paid"`
Network_fee int64 `json:"network_fee"`
Operation_id string `json:"operation_id"`
Preimage string `json:"preimage"`
Service_fee int64 `json:"service_fee"`
}
type PaymentState struct {
Amount int64 `json:"amount"`
Network_fee int64 `json:"network_fee"`
Paid_at_unix int64 `json:"paid_at_unix"`
Service_fee int64 `json:"service_fee"`
}
type Product struct {
Id string `json:"id"`
Name string `json:"name"`
Noffer string `json:"noffer"`
Price_sats int64 `json:"price_sats"`
}
type RelaysMigration struct {
Relays []string `json:"relays"`
}
type RemoveAuthorizedDebitRequest struct {
Npub string `json:"npub"`
}
type RequestNPubLinkingTokenRequest struct {
User_identifier string `json:"user_identifier"`
}
type RequestNPubLinkingTokenResponse struct {
Token string `json:"token"`
}
type RoutingEvent struct {
Event_type string `json:"event_type"`
Failure_string string `json:"failure_string"`
Forward_fail_event bool `json:"forward_fail_event"`
Incoming_amt_msat int64 `json:"incoming_amt_msat"`
Incoming_channel_id int64 `json:"incoming_channel_id"`
Incoming_htlc_id int64 `json:"incoming_htlc_id"`
Offchain bool `json:"offchain"`
Outgoing_amt_msat int64 `json:"outgoing_amt_msat"`
Outgoing_channel_id int64 `json:"outgoing_channel_id"`
Outgoing_htlc_id int64 `json:"outgoing_htlc_id"`
Settled bool `json:"settled"`
Timestamp_ns int64 `json:"timestamp_ns"`
}
type SendAppUserToAppPaymentRequest struct {
Amount int64 `json:"amount"`
From_user_identifier string `json:"from_user_identifier"`
}
type SendAppUserToAppUserPaymentRequest struct {
Amount int64 `json:"amount"`
From_user_identifier string `json:"from_user_identifier"`
To_user_identifier string `json:"to_user_identifier"`
}
type SetMockAppBalanceRequest struct {
Amount int64 `json:"amount"`
}
type SetMockAppUserBalanceRequest struct {
Amount int64 `json:"amount"`
User_identifier string `json:"user_identifier"`
}
type SetMockInvoiceAsPaidRequest struct {
Amount int64 `json:"amount"`
Invoice string `json:"invoice"`
}
type UsageMetric struct {
Auth_in_nano int64 `json:"auth_in_nano"`
Batch bool `json:"batch"`
Batch_size int64 `json:"batch_size"`
Handle_in_nano int64 `json:"handle_in_nano"`
Nostr bool `json:"nostr"`
Parsed_in_nano int64 `json:"parsed_in_nano"`
Processed_at_ms int64 `json:"processed_at_ms"`
Rpc_name string `json:"rpc_name"`
Validate_in_nano int64 `json:"validate_in_nano"`
}
type UsageMetrics struct {
Metrics []UsageMetric `json:"metrics"`
}
type UseInviteLinkRequest struct {
Invite_token string `json:"invite_token"`
}
type UserInfo struct {
Balance int64 `json:"balance"`
Max_withdrawable int64 `json:"max_withdrawable"`
Network_max_fee_bps int64 `json:"network_max_fee_bps"`
Network_max_fee_fixed int64 `json:"network_max_fee_fixed"`
Noffer string `json:"noffer"`
Service_fee_bps int64 `json:"service_fee_bps"`
Userid string `json:"userId"`
User_identifier string `json:"user_identifier"`
}
type UserOperation struct {
Amount int64 `json:"amount"`
Confirmed bool `json:"confirmed"`
Identifier string `json:"identifier"`
Inbound bool `json:"inbound"`
Internal bool `json:"internal"`
Network_fee int64 `json:"network_fee"`
Operationid string `json:"operationId"`
Paidatunix int64 `json:"paidAtUnix"`
Service_fee int64 `json:"service_fee"`
Tx_hash string `json:"tx_hash"`
Type UserOperationType `json:"type"`
}
type UserOperations struct {
Fromindex int64 `json:"fromIndex"`
Operations []UserOperation `json:"operations"`
Toindex int64 `json:"toIndex"`
}
type UsersInfo struct {
Always_been_inactive int64 `json:"always_been_inactive"`
Balance_avg int64 `json:"balance_avg"`
Balance_median int64 `json:"balance_median"`
Negative_balance int64 `json:"negative_balance"`
No_balance int64 `json:"no_balance"`
Total int64 `json:"total"`
}
type DebitRule_rule_type string
const (
EXPIRATION_RULE DebitRule_rule_type = "expiration_rule"
FREQUENCY_RULE DebitRule_rule_type = "frequency_rule"
)
type DebitRule_rule struct {
Type DebitRule_rule_type `json:"type"`
Expiration_rule *DebitExpirationRule `json:"expiration_rule"`
Frequency_rule *FrequencyRule `json:"frequency_rule"`
}
type LiveDebitRequest_debit_type string
const (
FREQUENCY LiveDebitRequest_debit_type = "frequency"
INVOICE LiveDebitRequest_debit_type = "invoice"
)
type LiveDebitRequest_debit struct {
Type LiveDebitRequest_debit_type `json:"type"`
Frequency *FrequencyRule `json:"frequency"`
Invoice *string `json:"invoice"`
}

View file

@ -177,7 +177,7 @@ export default (methods: Types.ServerMethods, opts: ServerOptions) => {
authCtx = authContext
stats.guard = process.hrtime.bigint()
const request = req.body
const error = Types.DebitAuthorizationValidate(request)
const error = Types.DebitAuthorizationRequestValidate(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
@ -247,7 +247,7 @@ export default (methods: Types.ServerMethods, opts: ServerOptions) => {
if (!methods.AuthorizeDebit) {
throw new Error('method AuthorizeDebit not found' )
} else {
const error = Types.DebitAuthorizationValidate(operation.req)
const error = Types.DebitAuthorizationRequestValidate(operation.req)
opStats.validate = process.hrtime.bigint()
if (error !== null) throw error
const res = await methods.AuthorizeDebit({...operation, ctx}); responses.push({ status: 'OK', ...res })
@ -279,12 +279,12 @@ export default (methods: Types.ServerMethods, opts: ServerOptions) => {
callsMetrics.push({ ...opInfo, ...opStats, ...ctx })
}
break
case 'GetAuthorizedDebits':
if (!methods.GetAuthorizedDebits) {
throw new Error('method GetAuthorizedDebits not found' )
case 'GetDebitAuthorizations':
if (!methods.GetDebitAuthorizations) {
throw new Error('method GetDebitAuthorizations not found' )
} else {
opStats.validate = opStats.guard
const res = await methods.GetAuthorizedDebits({...operation, ctx}); responses.push({ status: 'OK', ...res })
const res = await methods.GetDebitAuthorizations({...operation, ctx}); responses.push({ status: 'OK', ...res })
opStats.handle = process.hrtime.bigint()
callsMetrics.push({ ...opInfo, ...opStats, ...ctx })
}
@ -628,20 +628,20 @@ 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.GetAuthorizedDebits) throw new Error('method: GetAuthorizedDebits is not implemented')
if (!opts.allowNotImplementedMethods && !methods.GetDebitAuthorizations) throw new Error('method: GetDebitAuthorizations is not implemented')
app.get('/api/user/debit/get', async (req, res) => {
const info: Types.RequestInfo = { rpcName: 'GetAuthorizedDebits', batch: false, nostr: false, batchSize: 0}
const info: Types.RequestInfo = { rpcName: 'GetDebitAuthorizations', 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.GetAuthorizedDebits) throw new Error('method: GetAuthorizedDebits is not implemented')
if (!methods.GetDebitAuthorizations) throw new Error('method: GetDebitAuthorizations is not implemented')
const authContext = await opts.UserAuthGuard(req.headers['authorization'])
authCtx = authContext
stats.guard = process.hrtime.bigint()
stats.validate = stats.guard
const query = req.query
const params = req.params
const response = await methods.GetAuthorizedDebits({rpcName:'GetAuthorizedDebits', ctx:authContext })
const response = await methods.GetDebitAuthorizations({rpcName:'GetDebitAuthorizations', ctx:authContext })
stats.handle = process.hrtime.bigint()
res.json({status: 'OK', ...response})
opts.metricsCallback([{ ...info, ...stats, ...authContext }])

View file

@ -101,7 +101,7 @@ export default (params: ClientParams) => ({
}
return { status: 'ERROR', reason: 'invalid response' }
},
AuthorizeDebit: async (request: Types.DebitAuthorization): Promise<ResultError | ({ status: 'OK' }& Types.AuthorizedDebit)> => {
AuthorizeDebit: async (request: Types.DebitAuthorizationRequest): Promise<ResultError | ({ status: 'OK' }& Types.DebitAuthorization)> => {
const auth = await params.retrieveUserAuth()
if (auth === null) throw new Error('retrieveUserAuth() returned null')
let finalRoute = '/api/user/debit/authorize'
@ -110,7 +110,7 @@ export default (params: ClientParams) => ({
if (data.status === 'OK') {
const result = data
if(!params.checkResult) return { status: 'OK', ...result }
const error = Types.AuthorizedDebitValidate(result)
const error = Types.DebitAuthorizationValidate(result)
if (error === null) { return { status: 'OK', ...result } } else return { status: 'ERROR', reason: error.message }
}
return { status: 'ERROR', reason: 'invalid response' }
@ -246,7 +246,7 @@ export default (params: ClientParams) => ({
}
return { status: 'ERROR', reason: 'invalid response' }
},
GetAuthorizedDebits: async (): Promise<ResultError | ({ status: 'OK' }& Types.AuthorizedDebits)> => {
GetDebitAuthorizations: async (): Promise<ResultError | ({ status: 'OK' }& Types.DebitAuthorizations)> => {
const auth = await params.retrieveUserAuth()
if (auth === null) throw new Error('retrieveUserAuth() returned null')
let finalRoute = '/api/user/debit/get'
@ -255,7 +255,7 @@ export default (params: ClientParams) => ({
if (data.status === 'OK') {
const result = data
if(!params.checkResult) return { status: 'OK', ...result }
const error = Types.AuthorizedDebitsValidate(result)
const error = Types.DebitAuthorizationsValidate(result)
if (error === null) { return { status: 'OK', ...result } } else return { status: 'ERROR', reason: error.message }
}
return { status: 'ERROR', reason: 'invalid response' }
@ -289,6 +289,7 @@ export default (params: ClientParams) => ({
}
return { status: 'ERROR', reason: 'invalid response' }
},
GetLiveDebitRequests: async (cb: (v:ResultError | ({ status: 'OK' }& Types.LiveDebitRequest)) => void): Promise<void> => { throw new Error('http streams are not supported')},
GetLiveUserOperations: async (cb: (v:ResultError | ({ status: 'OK' }& Types.LiveUserOperation)) => void): Promise<void> => { throw new Error('http streams are not supported')},
GetLndMetrics: async (request: Types.LndMetricsRequest): Promise<ResultError | ({ status: 'OK' }& Types.LndMetrics)> => {
const auth = await params.retrieveMetricsAuth()

View file

@ -57,7 +57,7 @@ export default (params: NostrClientParams, send: (to:string, message: NostrRequ
}
return { status: 'ERROR', reason: 'invalid response' }
},
AuthorizeDebit: async (request: Types.DebitAuthorization): Promise<ResultError | ({ status: 'OK' }& Types.AuthorizedDebit)> => {
AuthorizeDebit: async (request: Types.DebitAuthorizationRequest): Promise<ResultError | ({ status: 'OK' }& Types.DebitAuthorization)> => {
const auth = await params.retrieveNostrUserAuth()
if (auth === null) throw new Error('retrieveNostrUserAuth() returned null')
const nostrRequest: NostrRequest = {}
@ -67,7 +67,7 @@ export default (params: NostrClientParams, send: (to:string, message: NostrRequ
if (data.status === 'OK') {
const result = data
if(!params.checkResult) return { status: 'OK', ...result }
const error = Types.AuthorizedDebitValidate(result)
const error = Types.DebitAuthorizationValidate(result)
if (error === null) { return { status: 'OK', ...result } } else return { status: 'ERROR', reason: error.message }
}
return { status: 'ERROR', reason: 'invalid response' }
@ -155,16 +155,16 @@ export default (params: NostrClientParams, send: (to:string, message: NostrRequ
}
return { status: 'ERROR', reason: 'invalid response' }
},
GetAuthorizedDebits: async (): Promise<ResultError | ({ status: 'OK' }& Types.AuthorizedDebits)> => {
GetDebitAuthorizations: async (): Promise<ResultError | ({ status: 'OK' }& Types.DebitAuthorizations)> => {
const auth = await params.retrieveNostrUserAuth()
if (auth === null) throw new Error('retrieveNostrUserAuth() returned null')
const nostrRequest: NostrRequest = {}
const data = await send(params.pubDestination, {rpcName:'GetAuthorizedDebits',authIdentifier:auth, ...nostrRequest })
const data = await send(params.pubDestination, {rpcName:'GetDebitAuthorizations',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.AuthorizedDebitsValidate(result)
const error = Types.DebitAuthorizationsValidate(result)
if (error === null) { return { status: 'OK', ...result } } else return { status: 'ERROR', reason: error.message }
}
return { status: 'ERROR', reason: 'invalid response' }
@ -213,6 +213,21 @@ export default (params: NostrClientParams, send: (to:string, message: NostrRequ
}
return { status: 'ERROR', reason: 'invalid response' }
},
GetLiveDebitRequests: async (cb: (res:ResultError | ({ status: 'OK' }& Types.LiveDebitRequest)) => void): Promise<void> => {
const auth = await params.retrieveNostrUserAuth()
if (auth === null) throw new Error('retrieveNostrUserAuth() returned null')
const nostrRequest: NostrRequest = {}
subscribe(params.pubDestination, {rpcName:'GetLiveDebitRequests',authIdentifier:auth, ...nostrRequest }, (data) => {
if (data.status === 'ERROR' && typeof data.reason === 'string') return cb(data)
if (data.status === 'OK') {
const result = data
if(!params.checkResult) return cb({ status: 'OK', ...result })
const error = Types.LiveDebitRequestValidate(result)
if (error === null) { return cb({ status: 'OK', ...result }) } else return cb({ status: 'ERROR', reason: error.message })
}
return cb({ status: 'ERROR', reason: 'invalid response' })
})
},
GetLiveUserOperations: async (cb: (res:ResultError | ({ status: 'OK' }& Types.LiveUserOperation)) => void): Promise<void> => {
const auth = await params.retrieveNostrUserAuth()
if (auth === null) throw new Error('retrieveNostrUserAuth() returned null')

View file

@ -87,7 +87,7 @@ export default (methods: Types.ServerMethods, opts: NostrOptions) => {
stats.guard = process.hrtime.bigint()
authCtx = authContext
const request = req.body
const error = Types.DebitAuthorizationValidate(request)
const error = Types.DebitAuthorizationRequestValidate(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.AuthorizeDebit({rpcName:'AuthorizeDebit', ctx:authContext , req: request})
@ -147,7 +147,7 @@ export default (methods: Types.ServerMethods, opts: NostrOptions) => {
if (!methods.AuthorizeDebit) {
throw new Error('method not defined: AuthorizeDebit')
} else {
const error = Types.DebitAuthorizationValidate(operation.req)
const error = Types.DebitAuthorizationRequestValidate(operation.req)
opStats.validate = process.hrtime.bigint()
if (error !== null) throw error
const res = await methods.AuthorizeDebit({...operation, ctx}); responses.push({ status: 'OK', ...res })
@ -179,12 +179,12 @@ export default (methods: Types.ServerMethods, opts: NostrOptions) => {
callsMetrics.push({ ...opInfo, ...opStats, ...ctx })
}
break
case 'GetAuthorizedDebits':
if (!methods.GetAuthorizedDebits) {
throw new Error('method not defined: GetAuthorizedDebits')
case 'GetDebitAuthorizations':
if (!methods.GetDebitAuthorizations) {
throw new Error('method not defined: GetDebitAuthorizations')
} else {
opStats.validate = opStats.guard
const res = await methods.GetAuthorizedDebits({...operation, ctx}); responses.push({ status: 'OK', ...res })
const res = await methods.GetDebitAuthorizations({...operation, ctx}); responses.push({ status: 'OK', ...res })
opStats.handle = process.hrtime.bigint()
callsMetrics.push({ ...opInfo, ...opStats, ...ctx })
}
@ -419,14 +419,14 @@ 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 'GetAuthorizedDebits':
case 'GetDebitAuthorizations':
try {
if (!methods.GetAuthorizedDebits) throw new Error('method: GetAuthorizedDebits is not implemented')
if (!methods.GetDebitAuthorizations) throw new Error('method: GetDebitAuthorizations is not implemented')
const authContext = await opts.NostrUserAuthGuard(req.appId, req.authIdentifier)
stats.guard = process.hrtime.bigint()
authCtx = authContext
stats.validate = stats.guard
const response = await methods.GetAuthorizedDebits({rpcName:'GetAuthorizedDebits', ctx:authContext })
const response = await methods.GetDebitAuthorizations({rpcName:'GetDebitAuthorizations', ctx:authContext })
stats.handle = process.hrtime.bigint()
res({status: 'OK', ...response})
opts.metricsCallback([{ ...info, ...stats, ...authContext }])
@ -474,6 +474,19 @@ 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 'GetLiveDebitRequests':
try {
if (!methods.GetLiveDebitRequests) throw new Error('method: GetLiveDebitRequests is not implemented')
const authContext = await opts.NostrUserAuthGuard(req.appId, req.authIdentifier)
stats.guard = process.hrtime.bigint()
authCtx = authContext
stats.validate = stats.guard
methods.GetLiveDebitRequests({rpcName:'GetLiveDebitRequests', ctx:authContext ,cb: (response, err) => {
stats.handle = process.hrtime.bigint()
if (err) { logErrorAndReturnResponse(err, err.message, res, logger, { ...info, ...stats, ...authContext }, opts.metricsCallback)} else { 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 'GetLiveUserOperations':
try {
if (!methods.GetLiveUserOperations) throw new Error('method: GetLiveUserOperations is not implemented')

View file

@ -34,8 +34,8 @@ export type UserContext = {
app_user_id: string
user_id: string
}
export type UserMethodInputs = AddProduct_Input | AuthorizeDebit_Input | DecodeInvoice_Input | EnrollAdminToken_Input | GetAuthorizedDebits_Input | GetLNURLChannelLink_Input | GetLnurlPayLink_Input | GetLnurlWithdrawLink_Input | GetPaymentState_Input | GetUserInfo_Input | GetUserOperations_Input | NewAddress_Input | NewInvoice_Input | NewProductInvoice_Input | OpenChannel_Input | PayAddress_Input | PayInvoice_Input | RemoveAuthorizedDebit_Input | UserHealth_Input
export type UserMethodOutputs = AddProduct_Output | AuthorizeDebit_Output | DecodeInvoice_Output | EnrollAdminToken_Output | GetAuthorizedDebits_Output | GetLNURLChannelLink_Output | GetLnurlPayLink_Output | GetLnurlWithdrawLink_Output | GetPaymentState_Output | GetUserInfo_Output | GetUserOperations_Output | NewAddress_Output | NewInvoice_Output | NewProductInvoice_Output | OpenChannel_Output | PayAddress_Output | PayInvoice_Output | RemoveAuthorizedDebit_Output | UserHealth_Output
export type UserMethodInputs = AddProduct_Input | AuthorizeDebit_Input | DecodeInvoice_Input | EnrollAdminToken_Input | GetDebitAuthorizations_Input | GetLNURLChannelLink_Input | GetLnurlPayLink_Input | GetLnurlWithdrawLink_Input | GetPaymentState_Input | GetUserInfo_Input | GetUserOperations_Input | NewAddress_Input | NewInvoice_Input | NewProductInvoice_Input | OpenChannel_Input | PayAddress_Input | PayInvoice_Input | RemoveAuthorizedDebit_Input | UserHealth_Input
export type UserMethodOutputs = AddProduct_Output | AuthorizeDebit_Output | DecodeInvoice_Output | EnrollAdminToken_Output | GetDebitAuthorizations_Output | GetLNURLChannelLink_Output | GetLnurlPayLink_Output | GetLnurlWithdrawLink_Output | GetPaymentState_Output | GetUserInfo_Output | GetUserOperations_Output | NewAddress_Output | NewInvoice_Output | NewProductInvoice_Output | OpenChannel_Output | PayAddress_Output | PayInvoice_Output | RemoveAuthorizedDebit_Output | UserHealth_Output
export type AuthContext = AdminContext | AppContext | GuestContext | GuestWithPubContext | MetricsContext | UserContext
export type AddApp_Input = {rpcName:'AddApp', req: AddAppRequest}
@ -56,8 +56,8 @@ export type AddProduct_Output = ResultError | ({ status: 'OK' } & Product)
export type AuthApp_Input = {rpcName:'AuthApp', req: AuthAppRequest}
export type AuthApp_Output = ResultError | ({ status: 'OK' } & AuthApp)
export type AuthorizeDebit_Input = {rpcName:'AuthorizeDebit', req: DebitAuthorization}
export type AuthorizeDebit_Output = ResultError | ({ status: 'OK' } & AuthorizedDebit)
export type AuthorizeDebit_Input = {rpcName:'AuthorizeDebit', req: DebitAuthorizationRequest}
export type AuthorizeDebit_Output = ResultError | ({ status: 'OK' } & DebitAuthorization)
export type BanUser_Input = {rpcName:'BanUser', req: BanUserRequest}
export type BanUser_Output = ResultError | ({ status: 'OK' } & BanUserResponse)
@ -89,8 +89,8 @@ export type GetAppUserLNURLInfo_Output = ResultError | ({ status: 'OK' } & Lnurl
export type GetAppsMetrics_Input = {rpcName:'GetAppsMetrics', req: AppsMetricsRequest}
export type GetAppsMetrics_Output = ResultError | ({ status: 'OK' } & AppsMetrics)
export type GetAuthorizedDebits_Input = {rpcName:'GetAuthorizedDebits'}
export type GetAuthorizedDebits_Output = ResultError | ({ status: 'OK' } & AuthorizedDebits)
export type GetDebitAuthorizations_Input = {rpcName:'GetDebitAuthorizations'}
export type GetDebitAuthorizations_Output = ResultError | ({ status: 'OK' } & DebitAuthorizations)
export type GetHttpCreds_Input = {rpcName:'GetHttpCreds', cb:(res: HttpCreds, err:Error|null)=> void}
export type GetHttpCreds_Output = ResultError | { status: 'OK' }
@ -101,6 +101,9 @@ export type GetInviteLinkState_Output = ResultError | ({ status: 'OK' } & GetInv
export type GetLNURLChannelLink_Input = {rpcName:'GetLNURLChannelLink'}
export type GetLNURLChannelLink_Output = ResultError | ({ status: 'OK' } & LnurlLinkResponse)
export type GetLiveDebitRequests_Input = {rpcName:'GetLiveDebitRequests', cb:(res: LiveDebitRequest, err:Error|null)=> void}
export type GetLiveDebitRequests_Output = ResultError | { status: 'OK' }
export type GetLiveUserOperations_Input = {rpcName:'GetLiveUserOperations', cb:(res: LiveUserOperation, err:Error|null)=> void}
export type GetLiveUserOperations_Output = ResultError | { status: 'OK' }
@ -238,7 +241,7 @@ export type ServerMethods = {
AddAppUserInvoice?: (req: AddAppUserInvoice_Input & {ctx: AppContext }) => Promise<NewInvoiceResponse>
AddProduct?: (req: AddProduct_Input & {ctx: UserContext }) => Promise<Product>
AuthApp?: (req: AuthApp_Input & {ctx: AdminContext }) => Promise<AuthApp>
AuthorizeDebit?: (req: AuthorizeDebit_Input & {ctx: UserContext }) => Promise<AuthorizedDebit>
AuthorizeDebit?: (req: AuthorizeDebit_Input & {ctx: UserContext }) => Promise<DebitAuthorization>
BanUser?: (req: BanUser_Input & {ctx: AdminContext }) => Promise<BanUserResponse>
CreateOneTimeInviteLink?: (req: CreateOneTimeInviteLink_Input & {ctx: AdminContext }) => Promise<CreateOneTimeInviteLinkResponse>
DecodeInvoice?: (req: DecodeInvoice_Input & {ctx: UserContext }) => Promise<DecodeInvoiceResponse>
@ -248,10 +251,11 @@ export type ServerMethods = {
GetAppUser?: (req: GetAppUser_Input & {ctx: AppContext }) => Promise<AppUser>
GetAppUserLNURLInfo?: (req: GetAppUserLNURLInfo_Input & {ctx: AppContext }) => Promise<LnurlPayInfoResponse>
GetAppsMetrics?: (req: GetAppsMetrics_Input & {ctx: MetricsContext }) => Promise<AppsMetrics>
GetAuthorizedDebits?: (req: GetAuthorizedDebits_Input & {ctx: UserContext }) => Promise<AuthorizedDebits>
GetDebitAuthorizations?: (req: GetDebitAuthorizations_Input & {ctx: UserContext }) => Promise<DebitAuthorizations>
GetHttpCreds?: (req: GetHttpCreds_Input & {ctx: UserContext }) => Promise<void>
GetInviteLinkState?: (req: GetInviteLinkState_Input & {ctx: AdminContext }) => Promise<GetInviteTokenStateResponse>
GetLNURLChannelLink?: (req: GetLNURLChannelLink_Input & {ctx: UserContext }) => Promise<LnurlLinkResponse>
GetLiveDebitRequests?: (req: GetLiveDebitRequests_Input & {ctx: UserContext }) => Promise<void>
GetLiveUserOperations?: (req: GetLiveUserOperations_Input & {ctx: UserContext }) => Promise<void>
GetLndMetrics?: (req: GetLndMetrics_Input & {ctx: MetricsContext }) => Promise<LndMetrics>
GetLnurlPayInfo?: (req: GetLnurlPayInfo_Input & {ctx: GuestContext }) => Promise<LnurlPayInfoResponse>
@ -299,12 +303,13 @@ export const enumCheckAddressType = (e?: AddressType): boolean => {
for (const v in AddressType) if (e === v) return true
return false
}
export enum AuthorizedDebitType {
KEY = 'KEY',
NPUB = 'NPUB',
export enum IntervalType {
DAY = 'DAY',
MONTH = 'MONTH',
WEEK = 'WEEK',
}
export const enumCheckAuthorizedDebitType = (e?: AuthorizedDebitType): boolean => {
for (const v in AuthorizedDebitType) if (e === v) return true
export const enumCheckIntervalType = (e?: IntervalType): boolean => {
for (const v in IntervalType) if (e === v) return true
return false
}
export enum UserOperationType {
@ -688,57 +693,6 @@ export const AuthAppRequestValidate = (o?: AuthAppRequest, opts: AuthAppRequestO
return null
}
export type AuthorizedDebit = {
debit_id: string
debit_type: AuthorizedDebitType
key: string
}
export const AuthorizedDebitOptionalFields: [] = []
export type AuthorizedDebitOptions = OptionsBaseMessage & {
checkOptionalsAreSet?: []
debit_id_CustomCheck?: (v: string) => boolean
debit_type_CustomCheck?: (v: AuthorizedDebitType) => boolean
key_CustomCheck?: (v: string) => boolean
}
export const AuthorizedDebitValidate = (o?: AuthorizedDebit, opts: AuthorizedDebitOptions = {}, path: string = 'AuthorizedDebit::root.'): Error | null => {
if (opts.checkOptionalsAreSet && opts.allOptionalsAreSet) return new Error(path + ': only one of checkOptionalsAreSet or allOptionalNonDefault can be set for each message')
if (typeof o !== 'object' || o === null) return new Error(path + ': object is not an instance of an object or is null')
if (typeof o.debit_id !== 'string') return new Error(`${path}.debit_id: is not a string`)
if (opts.debit_id_CustomCheck && !opts.debit_id_CustomCheck(o.debit_id)) return new Error(`${path}.debit_id: custom check failed`)
if (!enumCheckAuthorizedDebitType(o.debit_type)) return new Error(`${path}.debit_type: is not a valid AuthorizedDebitType`)
if (opts.debit_type_CustomCheck && !opts.debit_type_CustomCheck(o.debit_type)) return new Error(`${path}.debit_type: custom check failed`)
if (typeof o.key !== 'string') return new Error(`${path}.key: is not a string`)
if (opts.key_CustomCheck && !opts.key_CustomCheck(o.key)) return new Error(`${path}.key: custom check failed`)
return null
}
export type AuthorizedDebits = {
debits: AuthorizedDebit[]
}
export const AuthorizedDebitsOptionalFields: [] = []
export type AuthorizedDebitsOptions = OptionsBaseMessage & {
checkOptionalsAreSet?: []
debits_ItemOptions?: AuthorizedDebitOptions
debits_CustomCheck?: (v: AuthorizedDebit[]) => boolean
}
export const AuthorizedDebitsValidate = (o?: AuthorizedDebits, opts: AuthorizedDebitsOptions = {}, path: string = 'AuthorizedDebits::root.'): Error | null => {
if (opts.checkOptionalsAreSet && opts.allOptionalsAreSet) return new Error(path + ': only one of checkOptionalsAreSet or allOptionalNonDefault can be set for each message')
if (typeof o !== 'object' || o === null) return new Error(path + ': object is not an instance of an object or is null')
if (!Array.isArray(o.debits)) return new Error(`${path}.debits: is not an array`)
for (let index = 0; index < o.debits.length; index++) {
const debitsErr = AuthorizedDebitValidate(o.debits[index], opts.debits_ItemOptions, `${path}.debits[${index}]`)
if (debitsErr !== null) return debitsErr
}
if (opts.debits_CustomCheck && !opts.debits_CustomCheck(o.debits)) return new Error(`${path}.debits: custom check failed`)
return null
}
export type BanUserRequest = {
user_id: string
}
@ -902,21 +856,128 @@ export const CreateOneTimeInviteLinkResponseValidate = (o?: CreateOneTimeInviteL
}
export type DebitAuthorization = {
authorize_npub?: string
authorized: boolean
debit_id: string
npub: string
rules: DebitRule[]
}
export type DebitAuthorizationOptionalField = 'authorize_npub'
export const DebitAuthorizationOptionalFields: DebitAuthorizationOptionalField[] = ['authorize_npub']
export const DebitAuthorizationOptionalFields: [] = []
export type DebitAuthorizationOptions = OptionsBaseMessage & {
checkOptionalsAreSet?: DebitAuthorizationOptionalField[]
authorize_npub_CustomCheck?: (v?: string) => boolean
checkOptionalsAreSet?: []
authorized_CustomCheck?: (v: boolean) => boolean
debit_id_CustomCheck?: (v: string) => boolean
npub_CustomCheck?: (v: string) => boolean
rules_ItemOptions?: DebitRuleOptions
rules_CustomCheck?: (v: DebitRule[]) => boolean
}
export const DebitAuthorizationValidate = (o?: DebitAuthorization, opts: DebitAuthorizationOptions = {}, path: string = 'DebitAuthorization::root.'): Error | null => {
if (opts.checkOptionalsAreSet && opts.allOptionalsAreSet) return new Error(path + ': only one of checkOptionalsAreSet or allOptionalNonDefault can be set for each message')
if (typeof o !== 'object' || o === null) return new Error(path + ': object is not an instance of an object or is null')
if ((o.authorize_npub || opts.allOptionalsAreSet || opts.checkOptionalsAreSet?.includes('authorize_npub')) && typeof o.authorize_npub !== 'string') return new Error(`${path}.authorize_npub: is not a string`)
if (typeof o.authorized !== 'boolean') return new Error(`${path}.authorized: is not a boolean`)
if (opts.authorized_CustomCheck && !opts.authorized_CustomCheck(o.authorized)) return new Error(`${path}.authorized: custom check failed`)
if (typeof o.debit_id !== 'string') return new Error(`${path}.debit_id: is not a string`)
if (opts.debit_id_CustomCheck && !opts.debit_id_CustomCheck(o.debit_id)) return new Error(`${path}.debit_id: custom check failed`)
if (typeof o.npub !== 'string') return new Error(`${path}.npub: is not a string`)
if (opts.npub_CustomCheck && !opts.npub_CustomCheck(o.npub)) return new Error(`${path}.npub: custom check failed`)
if (!Array.isArray(o.rules)) return new Error(`${path}.rules: is not an array`)
for (let index = 0; index < o.rules.length; index++) {
const rulesErr = DebitRuleValidate(o.rules[index], opts.rules_ItemOptions, `${path}.rules[${index}]`)
if (rulesErr !== null) return rulesErr
}
if (opts.rules_CustomCheck && !opts.rules_CustomCheck(o.rules)) return new Error(`${path}.rules: custom check failed`)
return null
}
export type DebitAuthorizationRequest = {
authorize_npub: string
rules: DebitRule[]
}
export const DebitAuthorizationRequestOptionalFields: [] = []
export type DebitAuthorizationRequestOptions = OptionsBaseMessage & {
checkOptionalsAreSet?: []
authorize_npub_CustomCheck?: (v: string) => boolean
rules_ItemOptions?: DebitRuleOptions
rules_CustomCheck?: (v: DebitRule[]) => boolean
}
export const DebitAuthorizationRequestValidate = (o?: DebitAuthorizationRequest, opts: DebitAuthorizationRequestOptions = {}, path: string = 'DebitAuthorizationRequest::root.'): Error | null => {
if (opts.checkOptionalsAreSet && opts.allOptionalsAreSet) return new Error(path + ': only one of checkOptionalsAreSet or allOptionalNonDefault can be set for each message')
if (typeof o !== 'object' || o === null) return new Error(path + ': object is not an instance of an object or is null')
if (typeof o.authorize_npub !== 'string') return new Error(`${path}.authorize_npub: is not a string`)
if (opts.authorize_npub_CustomCheck && !opts.authorize_npub_CustomCheck(o.authorize_npub)) return new Error(`${path}.authorize_npub: custom check failed`)
if (!Array.isArray(o.rules)) return new Error(`${path}.rules: is not an array`)
for (let index = 0; index < o.rules.length; index++) {
const rulesErr = DebitRuleValidate(o.rules[index], opts.rules_ItemOptions, `${path}.rules[${index}]`)
if (rulesErr !== null) return rulesErr
}
if (opts.rules_CustomCheck && !opts.rules_CustomCheck(o.rules)) return new Error(`${path}.rules: custom check failed`)
return null
}
export type DebitAuthorizations = {
debits: DebitAuthorization[]
}
export const DebitAuthorizationsOptionalFields: [] = []
export type DebitAuthorizationsOptions = OptionsBaseMessage & {
checkOptionalsAreSet?: []
debits_ItemOptions?: DebitAuthorizationOptions
debits_CustomCheck?: (v: DebitAuthorization[]) => boolean
}
export const DebitAuthorizationsValidate = (o?: DebitAuthorizations, opts: DebitAuthorizationsOptions = {}, path: string = 'DebitAuthorizations::root.'): Error | null => {
if (opts.checkOptionalsAreSet && opts.allOptionalsAreSet) return new Error(path + ': only one of checkOptionalsAreSet or allOptionalNonDefault can be set for each message')
if (typeof o !== 'object' || o === null) return new Error(path + ': object is not an instance of an object or is null')
if (!Array.isArray(o.debits)) return new Error(`${path}.debits: is not an array`)
for (let index = 0; index < o.debits.length; index++) {
const debitsErr = DebitAuthorizationValidate(o.debits[index], opts.debits_ItemOptions, `${path}.debits[${index}]`)
if (debitsErr !== null) return debitsErr
}
if (opts.debits_CustomCheck && !opts.debits_CustomCheck(o.debits)) return new Error(`${path}.debits: custom check failed`)
return null
}
export type DebitExpirationRule = {
expires_at_unix: number
}
export const DebitExpirationRuleOptionalFields: [] = []
export type DebitExpirationRuleOptions = OptionsBaseMessage & {
checkOptionalsAreSet?: []
expires_at_unix_CustomCheck?: (v: number) => boolean
}
export const DebitExpirationRuleValidate = (o?: DebitExpirationRule, opts: DebitExpirationRuleOptions = {}, path: string = 'DebitExpirationRule::root.'): Error | null => {
if (opts.checkOptionalsAreSet && opts.allOptionalsAreSet) return new Error(path + ': only one of checkOptionalsAreSet or allOptionalNonDefault can be set for each message')
if (typeof o !== 'object' || o === null) return new Error(path + ': object is not an instance of an object or is null')
if (typeof o.expires_at_unix !== 'number') return new Error(`${path}.expires_at_unix: is not a number`)
if (opts.expires_at_unix_CustomCheck && !opts.expires_at_unix_CustomCheck(o.expires_at_unix)) return new Error(`${path}.expires_at_unix: custom check failed`)
return null
}
export type DebitRule = {
rule: DebitRule_rule
}
export const DebitRuleOptionalFields: [] = []
export type DebitRuleOptions = OptionsBaseMessage & {
checkOptionalsAreSet?: []
rule_Options?: DebitRule_ruleOptions
}
export const DebitRuleValidate = (o?: DebitRule, opts: DebitRuleOptions = {}, path: string = 'DebitRule::root.'): Error | null => {
if (opts.checkOptionalsAreSet && opts.allOptionalsAreSet) return new Error(path + ': only one of checkOptionalsAreSet or allOptionalNonDefault can be set for each message')
if (typeof o !== 'object' || o === null) return new Error(path + ': object is not an instance of an object or is null')
const ruleErr = DebitRule_ruleValidate(o.rule, opts.rule_Options, `${path}.rule`)
if (ruleErr !== null) return ruleErr
return null
}
@ -1010,6 +1071,29 @@ export const EnrollAdminTokenRequestValidate = (o?: EnrollAdminTokenRequest, opt
return null
}
export type FrequencyRule = {
interval: IntervalType
number_of_intervals: number
}
export const FrequencyRuleOptionalFields: [] = []
export type FrequencyRuleOptions = OptionsBaseMessage & {
checkOptionalsAreSet?: []
interval_CustomCheck?: (v: IntervalType) => boolean
number_of_intervals_CustomCheck?: (v: number) => boolean
}
export const FrequencyRuleValidate = (o?: FrequencyRule, opts: FrequencyRuleOptions = {}, path: string = 'FrequencyRule::root.'): Error | null => {
if (opts.checkOptionalsAreSet && opts.allOptionalsAreSet) return new Error(path + ': only one of checkOptionalsAreSet or allOptionalNonDefault can be set for each message')
if (typeof o !== 'object' || o === null) return new Error(path + ': object is not an instance of an object or is null')
if (!enumCheckIntervalType(o.interval)) return new Error(`${path}.interval: is not a valid IntervalType`)
if (opts.interval_CustomCheck && !opts.interval_CustomCheck(o.interval)) return new Error(`${path}.interval: custom check failed`)
if (typeof o.number_of_intervals !== 'number') return new Error(`${path}.number_of_intervals: is not a number`)
if (opts.number_of_intervals_CustomCheck && !opts.number_of_intervals_CustomCheck(o.number_of_intervals)) return new Error(`${path}.number_of_intervals: custom check failed`)
return null
}
export type GetAppUserLNURLInfoRequest = {
base_url_override: string
user_identifier: string
@ -1312,6 +1396,35 @@ export const LinkNPubThroughTokenRequestValidate = (o?: LinkNPubThroughTokenRequ
return null
}
export type LiveDebitRequest = {
amount: number
debit: LiveDebitRequest_debit
npub: string
}
export const LiveDebitRequestOptionalFields: [] = []
export type LiveDebitRequestOptions = OptionsBaseMessage & {
checkOptionalsAreSet?: []
amount_CustomCheck?: (v: number) => boolean
debit_Options?: LiveDebitRequest_debitOptions
npub_CustomCheck?: (v: string) => boolean
}
export const LiveDebitRequestValidate = (o?: LiveDebitRequest, opts: LiveDebitRequestOptions = {}, path: string = 'LiveDebitRequest::root.'): Error | null => {
if (opts.checkOptionalsAreSet && opts.allOptionalsAreSet) return new Error(path + ': only one of checkOptionalsAreSet or allOptionalNonDefault can be set for each message')
if (typeof o !== 'object' || o === null) return new Error(path + ': object is not an instance of an object or is null')
if (typeof o.amount !== 'number') return new Error(`${path}.amount: is not a number`)
if (opts.amount_CustomCheck && !opts.amount_CustomCheck(o.amount)) return new Error(`${path}.amount: custom check failed`)
const debitErr = LiveDebitRequest_debitValidate(o.debit, opts.debit_Options, `${path}.debit`)
if (debitErr !== null) return debitErr
if (typeof o.npub !== 'string') return new Error(`${path}.npub: is not a string`)
if (opts.npub_CustomCheck && !opts.npub_CustomCheck(o.npub)) return new Error(`${path}.npub: custom check failed`)
return null
}
export type LiveUserOperation = {
operation: UserOperation
}
@ -2119,19 +2232,19 @@ export const RelaysMigrationValidate = (o?: RelaysMigration, opts: RelaysMigrati
}
export type RemoveAuthorizedDebitRequest = {
debit_id: string
npub: string
}
export const RemoveAuthorizedDebitRequestOptionalFields: [] = []
export type RemoveAuthorizedDebitRequestOptions = OptionsBaseMessage & {
checkOptionalsAreSet?: []
debit_id_CustomCheck?: (v: string) => boolean
npub_CustomCheck?: (v: string) => boolean
}
export const RemoveAuthorizedDebitRequestValidate = (o?: RemoveAuthorizedDebitRequest, opts: RemoveAuthorizedDebitRequestOptions = {}, path: string = 'RemoveAuthorizedDebitRequest::root.'): Error | null => {
if (opts.checkOptionalsAreSet && opts.allOptionalsAreSet) return new Error(path + ': only one of checkOptionalsAreSet or allOptionalNonDefault can be set for each message')
if (typeof o !== 'object' || o === null) return new Error(path + ': object is not an instance of an object or is null')
if (typeof o.debit_id !== 'string') return new Error(`${path}.debit_id: is not a string`)
if (opts.debit_id_CustomCheck && !opts.debit_id_CustomCheck(o.debit_id)) return new Error(`${path}.debit_id: custom check failed`)
if (typeof o.npub !== 'string') return new Error(`${path}.npub: is not a string`)
if (opts.npub_CustomCheck && !opts.npub_CustomCheck(o.npub)) return new Error(`${path}.npub: custom check failed`)
return null
}
@ -2656,3 +2769,76 @@ export const UsersInfoValidate = (o?: UsersInfo, opts: UsersInfoOptions = {}, pa
return null
}
export enum DebitRule_rule_type {
EXPIRATION_RULE = 'expiration_rule',
FREQUENCY_RULE = 'frequency_rule',
}
export const enumCheckDebitRule_rule_type = (e?: DebitRule_rule_type): boolean => {
for (const v in DebitRule_rule_type) if (e === v) return true
return false
}
export type DebitRule_rule =
{type:DebitRule_rule_type.EXPIRATION_RULE, expiration_rule:DebitExpirationRule}|
{type:DebitRule_rule_type.FREQUENCY_RULE, frequency_rule:FrequencyRule}
export type DebitRule_ruleOptions = {
expiration_rule_Options?: DebitExpirationRuleOptions
frequency_rule_Options?: FrequencyRuleOptions
}
export const DebitRule_ruleValidate = (o?: DebitRule_rule, opts:DebitRule_ruleOptions = {}, path: string = 'DebitRule_rule::root.'): Error | null => {
if (typeof o !== 'object' || o === null) return new Error(path + ': object is not an instance of an object or is null')
const stringType: string = o.type
switch (o.type) {
case DebitRule_rule_type.EXPIRATION_RULE:
const expiration_ruleErr = DebitExpirationRuleValidate(o.expiration_rule, opts.expiration_rule_Options, `${path}.expiration_rule`)
if (expiration_ruleErr !== null) return expiration_ruleErr
break
case DebitRule_rule_type.FREQUENCY_RULE:
const frequency_ruleErr = FrequencyRuleValidate(o.frequency_rule, opts.frequency_rule_Options, `${path}.frequency_rule`)
if (frequency_ruleErr !== null) return frequency_ruleErr
break
default:
return new Error(path + ': unknown type '+ stringType)
}
return null
}
export enum LiveDebitRequest_debit_type {
FREQUENCY = 'frequency',
INVOICE = 'invoice',
}
export const enumCheckLiveDebitRequest_debit_type = (e?: LiveDebitRequest_debit_type): boolean => {
for (const v in LiveDebitRequest_debit_type) if (e === v) return true
return false
}
export type LiveDebitRequest_debit =
{type:LiveDebitRequest_debit_type.FREQUENCY, frequency:FrequencyRule}|
{type:LiveDebitRequest_debit_type.INVOICE, invoice:string}
export type LiveDebitRequest_debitOptions = {
frequency_Options?: FrequencyRuleOptions
invoice_CustomCheck?: (v: string) => boolean
}
export const LiveDebitRequest_debitValidate = (o?: LiveDebitRequest_debit, opts:LiveDebitRequest_debitOptions = {}, path: string = 'LiveDebitRequest_debit::root.'): Error | null => {
if (typeof o !== 'object' || o === null) return new Error(path + ': object is not an instance of an object or is null')
const stringType: string = o.type
switch (o.type) {
case LiveDebitRequest_debit_type.FREQUENCY:
const frequencyErr = FrequencyRuleValidate(o.frequency, opts.frequency_Options, `${path}.frequency`)
if (frequencyErr !== null) return frequencyErr
break
case LiveDebitRequest_debit_type.INVOICE:
if (typeof o.invoice !== 'string') return new Error(`${path}.invoice: is not a string`)
if (opts.invoice_CustomCheck && !opts.invoice_CustomCheck(o.invoice)) return new Error(`${path}.invoice: custom check failed`)
break
default:
return new Error(path + ': unknown type '+ stringType)
}
return null
}