manage authorization
This commit is contained in:
parent
819cf74d2f
commit
df088bf0fe
18 changed files with 623 additions and 56 deletions
|
|
@ -30,13 +30,16 @@ import { DebitAccessFixes1726685229264 } from './build/src/services/storage/migr
|
||||||
import { DebitToPub1727105758354 } from './build/src/services/storage/migrations/1727105758354-debit_to_pub.js'
|
import { DebitToPub1727105758354 } from './build/src/services/storage/migrations/1727105758354-debit_to_pub.js'
|
||||||
import { UserCbUrl1727112281043 } from './build/src/services/storage/migrations/1727112281043-user_cb_url.js'
|
import { UserCbUrl1727112281043 } from './build/src/services/storage/migrations/1727112281043-user_cb_url.js'
|
||||||
import { UserOffer1733502626042 } from './build/src/services/storage/migrations/1733502626042-user_offer.js'
|
import { UserOffer1733502626042 } from './build/src/services/storage/migrations/1733502626042-user_offer.js'
|
||||||
|
import { ManagementGrant1751307732346 } from './build/src/services/storage/migrations/1751307732346-management_grant.js'
|
||||||
export default new DataSource({
|
export default new DataSource({
|
||||||
type: "sqlite",
|
type: "sqlite",
|
||||||
database: "db.sqlite",
|
database: "db.sqlite",
|
||||||
// logging: true,
|
// logging: true,
|
||||||
migrations: [Initial1703170309875, LspOrder1718387847693, LiquidityProvider1719335699480, LndNodeInfo1720187506189, CreateInviteTokenTable1721751414878, PaymentIndex1721760297610, DebitAccess1726496225078, DebitAccessFixes1726685229264, DebitToPub1727105758354, UserCbUrl1727112281043, UserOffer1733502626042],
|
migrations: [Initial1703170309875, LspOrder1718387847693, LiquidityProvider1719335699480, LndNodeInfo1720187506189, CreateInviteTokenTable1721751414878,
|
||||||
|
PaymentIndex1721760297610, DebitAccess1726496225078, DebitAccessFixes1726685229264, DebitToPub1727105758354, UserCbUrl1727112281043,
|
||||||
|
UserOffer1733502626042, ManagementGrant1751307732346],
|
||||||
entities: [User, UserReceivingInvoice, UserReceivingAddress, AddressReceivingTransaction, UserInvoicePayment, UserTransactionPayment,
|
entities: [User, UserReceivingInvoice, UserReceivingAddress, AddressReceivingTransaction, UserInvoicePayment, UserTransactionPayment,
|
||||||
UserBasicAuth, UserEphemeralKey, Product, UserToUserPayment, Application, ApplicationUser, UserToUserPayment, LspOrder, LndNodeInfo, TrackedProvider, InviteToken, DebitAccess, UserOffer, ManagementGrant],
|
UserBasicAuth, UserEphemeralKey, Product, UserToUserPayment, Application, ApplicationUser, UserToUserPayment, LspOrder, LndNodeInfo, TrackedProvider, InviteToken, DebitAccess, UserOffer, ManagementGrant],
|
||||||
// synchronize: true,
|
// synchronize: true,
|
||||||
})
|
})
|
||||||
//npx typeorm migration:generate ./src/services/storage/migrations/management_grant -d ./datasource.js
|
//npx typeorm migration:generate ./src/services/storage/migrations/management_grant_banned -d ./datasource.js
|
||||||
8
package-lock.json
generated
8
package-lock.json
generated
|
|
@ -13,7 +13,7 @@
|
||||||
"@protobuf-ts/grpc-transport": "^2.9.4",
|
"@protobuf-ts/grpc-transport": "^2.9.4",
|
||||||
"@protobuf-ts/plugin": "^2.5.0",
|
"@protobuf-ts/plugin": "^2.5.0",
|
||||||
"@protobuf-ts/runtime": "^2.5.0",
|
"@protobuf-ts/runtime": "^2.5.0",
|
||||||
"@shocknet/clink-sdk": "^1.1.4",
|
"@shocknet/clink-sdk": "^1.1.6",
|
||||||
"@stablelib/xchacha20": "^1.0.1",
|
"@stablelib/xchacha20": "^1.0.1",
|
||||||
"@types/express": "^4.17.21",
|
"@types/express": "^4.17.21",
|
||||||
"@types/node": "^17.0.31",
|
"@types/node": "^17.0.31",
|
||||||
|
|
@ -591,9 +591,9 @@
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/@shocknet/clink-sdk": {
|
"node_modules/@shocknet/clink-sdk": {
|
||||||
"version": "1.1.4",
|
"version": "1.1.6",
|
||||||
"resolved": "https://registry.npmjs.org/@shocknet/clink-sdk/-/clink-sdk-1.1.4.tgz",
|
"resolved": "https://registry.npmjs.org/@shocknet/clink-sdk/-/clink-sdk-1.1.6.tgz",
|
||||||
"integrity": "sha512-b0YVsisIkTxOAwxrb1a9DGDxwWkHm7kJ2BpqOzkEbtJ6flkJxo2ggmRH3fxsVIiJOeVWwgSPATab68JU8DSLOA==",
|
"integrity": "sha512-PXNXdaS5sFIgfdWV5yMW0/ghrORAEVTy9K3fY4j/Rf4fjbNspBAaDioYn7to+lU/boPUxRMmFE0ix/2Mr6pkFQ==",
|
||||||
"license": "ISC",
|
"license": "ISC",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@noble/hashes": "^1.8.0",
|
"@noble/hashes": "^1.8.0",
|
||||||
|
|
|
||||||
|
|
@ -31,7 +31,7 @@
|
||||||
"@protobuf-ts/grpc-transport": "^2.9.4",
|
"@protobuf-ts/grpc-transport": "^2.9.4",
|
||||||
"@protobuf-ts/plugin": "^2.5.0",
|
"@protobuf-ts/plugin": "^2.5.0",
|
||||||
"@protobuf-ts/runtime": "^2.5.0",
|
"@protobuf-ts/runtime": "^2.5.0",
|
||||||
"@shocknet/clink-sdk": "^1.1.4",
|
"@shocknet/clink-sdk": "^1.1.6",
|
||||||
"@stablelib/xchacha20": "^1.0.1",
|
"@stablelib/xchacha20": "^1.0.1",
|
||||||
"@types/express": "^4.17.21",
|
"@types/express": "^4.17.21",
|
||||||
"@types/node": "^17.0.31",
|
"@types/node": "^17.0.31",
|
||||||
|
|
|
||||||
|
|
@ -43,6 +43,11 @@ The nostr server will send back a message response, and inside the body there wi
|
||||||
- input: [DebitAuthorizationRequest](#DebitAuthorizationRequest)
|
- input: [DebitAuthorizationRequest](#DebitAuthorizationRequest)
|
||||||
- output: [DebitAuthorization](#DebitAuthorization)
|
- output: [DebitAuthorization](#DebitAuthorization)
|
||||||
|
|
||||||
|
- AuthorizeManage
|
||||||
|
- auth type: __User__
|
||||||
|
- input: [ManageAuthorizationRequest](#ManageAuthorizationRequest)
|
||||||
|
- output: [ManageAuthorization](#ManageAuthorization)
|
||||||
|
|
||||||
- BanDebit
|
- BanDebit
|
||||||
- auth type: __User__
|
- auth type: __User__
|
||||||
- input: [DebitOperation](#DebitOperation)
|
- input: [DebitOperation](#DebitOperation)
|
||||||
|
|
@ -128,6 +133,11 @@ The nostr server will send back a message response, and inside the body there wi
|
||||||
- This methods has an __empty__ __request__ body
|
- This methods has an __empty__ __request__ body
|
||||||
- output: [LiveDebitRequest](#LiveDebitRequest)
|
- output: [LiveDebitRequest](#LiveDebitRequest)
|
||||||
|
|
||||||
|
- GetLiveManageRequests
|
||||||
|
- auth type: __User__
|
||||||
|
- This methods has an __empty__ __request__ body
|
||||||
|
- output: [LiveManageRequest](#LiveManageRequest)
|
||||||
|
|
||||||
- GetLiveUserOperations
|
- GetLiveUserOperations
|
||||||
- auth type: __User__
|
- auth type: __User__
|
||||||
- This methods has an __empty__ __request__ body
|
- This methods has an __empty__ __request__ body
|
||||||
|
|
@ -153,6 +163,11 @@ The nostr server will send back a message response, and inside the body there wi
|
||||||
- This methods has an __empty__ __request__ body
|
- This methods has an __empty__ __request__ body
|
||||||
- output: [LnurlLinkResponse](#LnurlLinkResponse)
|
- output: [LnurlLinkResponse](#LnurlLinkResponse)
|
||||||
|
|
||||||
|
- GetManageAuthorizations
|
||||||
|
- auth type: __User__
|
||||||
|
- This methods has an __empty__ __request__ body
|
||||||
|
- output: [ManageAuthorizations](#ManageAuthorizations)
|
||||||
|
|
||||||
- GetMigrationUpdate
|
- GetMigrationUpdate
|
||||||
- auth type: __User__
|
- auth type: __User__
|
||||||
- This methods has an __empty__ __request__ body
|
- This methods has an __empty__ __request__ body
|
||||||
|
|
@ -418,6 +433,13 @@ The nostr server will send back a message response, and inside the body there wi
|
||||||
- input: [DebitAuthorizationRequest](#DebitAuthorizationRequest)
|
- input: [DebitAuthorizationRequest](#DebitAuthorizationRequest)
|
||||||
- output: [DebitAuthorization](#DebitAuthorization)
|
- output: [DebitAuthorization](#DebitAuthorization)
|
||||||
|
|
||||||
|
- AuthorizeManage
|
||||||
|
- auth type: __User__
|
||||||
|
- http method: __post__
|
||||||
|
- http route: __/api/user/manage/authorize__
|
||||||
|
- input: [ManageAuthorizationRequest](#ManageAuthorizationRequest)
|
||||||
|
- output: [ManageAuthorization](#ManageAuthorization)
|
||||||
|
|
||||||
- BanDebit
|
- BanDebit
|
||||||
- auth type: __User__
|
- auth type: __User__
|
||||||
- http method: __post__
|
- http method: __post__
|
||||||
|
|
@ -565,6 +587,13 @@ The nostr server will send back a message response, and inside the body there wi
|
||||||
- This methods has an __empty__ __request__ body
|
- This methods has an __empty__ __request__ body
|
||||||
- output: [LiveDebitRequest](#LiveDebitRequest)
|
- output: [LiveDebitRequest](#LiveDebitRequest)
|
||||||
|
|
||||||
|
- GetLiveManageRequests
|
||||||
|
- auth type: __User__
|
||||||
|
- http method: __post__
|
||||||
|
- http route: __/api/user/manage/sub__
|
||||||
|
- This methods has an __empty__ __request__ body
|
||||||
|
- output: [LiveManageRequest](#LiveManageRequest)
|
||||||
|
|
||||||
- GetLiveUserOperations
|
- GetLiveUserOperations
|
||||||
- auth type: __User__
|
- auth type: __User__
|
||||||
- http method: __post__
|
- http method: __post__
|
||||||
|
|
@ -618,6 +647,13 @@ The nostr server will send back a message response, and inside the body there wi
|
||||||
- This methods has an __empty__ __request__ body
|
- This methods has an __empty__ __request__ body
|
||||||
- output: [LnurlLinkResponse](#LnurlLinkResponse)
|
- output: [LnurlLinkResponse](#LnurlLinkResponse)
|
||||||
|
|
||||||
|
- GetManageAuthorizations
|
||||||
|
- auth type: __User__
|
||||||
|
- http method: __get__
|
||||||
|
- http route: __/api/user/manage/get__
|
||||||
|
- This methods has an __empty__ __request__ body
|
||||||
|
- output: [ManageAuthorizations](#ManageAuthorizations)
|
||||||
|
|
||||||
- GetMigrationUpdate
|
- GetMigrationUpdate
|
||||||
- auth type: __User__
|
- auth type: __User__
|
||||||
- http method: __post__
|
- http method: __post__
|
||||||
|
|
@ -1216,6 +1252,10 @@ The nostr server will send back a message response, and inside the body there wi
|
||||||
- __npub__: _string_
|
- __npub__: _string_
|
||||||
- __request_id__: _string_
|
- __request_id__: _string_
|
||||||
|
|
||||||
|
### LiveManageRequest
|
||||||
|
- __npub__: _string_
|
||||||
|
- __request_id__: _string_
|
||||||
|
|
||||||
### LiveUserOperation
|
### LiveUserOperation
|
||||||
- __operation__: _[UserOperation](#UserOperation)_
|
- __operation__: _[UserOperation](#UserOperation)_
|
||||||
|
|
||||||
|
|
@ -1290,6 +1330,19 @@ The nostr server will send back a message response, and inside the body there wi
|
||||||
- __payLink__: _string_
|
- __payLink__: _string_
|
||||||
- __tag__: _string_
|
- __tag__: _string_
|
||||||
|
|
||||||
|
### ManageAuthorization
|
||||||
|
- __authorized__: _boolean_
|
||||||
|
- __manage_id__: _string_
|
||||||
|
- __npub__: _string_
|
||||||
|
|
||||||
|
### ManageAuthorizationRequest
|
||||||
|
- __authorize_npub__: _string_
|
||||||
|
- __ban__: _boolean_
|
||||||
|
- __request_id__: _string_ *this field is optional
|
||||||
|
|
||||||
|
### ManageAuthorizations
|
||||||
|
- __manages__: ARRAY of: _[ManageAuthorization](#ManageAuthorization)_
|
||||||
|
|
||||||
### MetricsFile
|
### MetricsFile
|
||||||
|
|
||||||
### MigrationUpdate
|
### MigrationUpdate
|
||||||
|
|
|
||||||
|
|
@ -63,6 +63,7 @@ type Client struct {
|
||||||
AddUserOffer func(req OfferConfig) (*OfferId, error)
|
AddUserOffer func(req OfferConfig) (*OfferId, error)
|
||||||
AuthApp func(req AuthAppRequest) (*AuthApp, error)
|
AuthApp func(req AuthAppRequest) (*AuthApp, error)
|
||||||
AuthorizeDebit func(req DebitAuthorizationRequest) (*DebitAuthorization, error)
|
AuthorizeDebit func(req DebitAuthorizationRequest) (*DebitAuthorization, error)
|
||||||
|
AuthorizeManage func(req ManageAuthorizationRequest) (*ManageAuthorization, error)
|
||||||
BanDebit func(req DebitOperation) error
|
BanDebit func(req DebitOperation) error
|
||||||
BanUser func(req BanUserRequest) (*BanUserResponse, error)
|
BanUser func(req BanUserRequest) (*BanUserResponse, error)
|
||||||
// batching method: BatchUser not implemented
|
// batching method: BatchUser not implemented
|
||||||
|
|
@ -84,6 +85,7 @@ type Client struct {
|
||||||
GetInviteLinkState func(req GetInviteTokenStateRequest) (*GetInviteTokenStateResponse, error)
|
GetInviteLinkState func(req GetInviteTokenStateRequest) (*GetInviteTokenStateResponse, error)
|
||||||
GetLNURLChannelLink func() (*LnurlLinkResponse, error)
|
GetLNURLChannelLink func() (*LnurlLinkResponse, error)
|
||||||
GetLiveDebitRequests func() (*LiveDebitRequest, error)
|
GetLiveDebitRequests func() (*LiveDebitRequest, error)
|
||||||
|
GetLiveManageRequests func() (*LiveManageRequest, error)
|
||||||
GetLiveUserOperations func() (*LiveUserOperation, error)
|
GetLiveUserOperations func() (*LiveUserOperation, error)
|
||||||
GetLndForwardingMetrics func(req LndMetricsRequest) (*LndForwardingMetrics, error)
|
GetLndForwardingMetrics func(req LndMetricsRequest) (*LndForwardingMetrics, error)
|
||||||
GetLndMetrics func(req LndMetricsRequest) (*LndMetrics, error)
|
GetLndMetrics func(req LndMetricsRequest) (*LndMetrics, error)
|
||||||
|
|
@ -91,6 +93,7 @@ type Client struct {
|
||||||
GetLnurlPayLink func() (*LnurlLinkResponse, error)
|
GetLnurlPayLink func() (*LnurlLinkResponse, error)
|
||||||
GetLnurlWithdrawInfo func(query GetLnurlWithdrawInfo_Query) (*LnurlWithdrawInfoResponse, error)
|
GetLnurlWithdrawInfo func(query GetLnurlWithdrawInfo_Query) (*LnurlWithdrawInfoResponse, error)
|
||||||
GetLnurlWithdrawLink func() (*LnurlLinkResponse, error)
|
GetLnurlWithdrawLink func() (*LnurlLinkResponse, error)
|
||||||
|
GetManageAuthorizations func() (*ManageAuthorizations, error)
|
||||||
GetMigrationUpdate func() (*MigrationUpdate, error)
|
GetMigrationUpdate func() (*MigrationUpdate, error)
|
||||||
GetNPubLinkingState func(req GetNPubLinking) (*NPubLinking, error)
|
GetNPubLinkingState func(req GetNPubLinking) (*NPubLinking, error)
|
||||||
GetPaymentState func(req GetPaymentStateRequest) (*PaymentState, error)
|
GetPaymentState func(req GetPaymentStateRequest) (*PaymentState, error)
|
||||||
|
|
@ -397,6 +400,35 @@ func NewClient(params ClientParams) *Client {
|
||||||
}
|
}
|
||||||
return &res, nil
|
return &res, nil
|
||||||
},
|
},
|
||||||
|
AuthorizeManage: func(req ManageAuthorizationRequest) (*ManageAuthorization, error) {
|
||||||
|
auth, err := params.RetrieveUserAuth()
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
finalRoute := "/api/user/manage/authorize"
|
||||||
|
body, err := json.Marshal(req)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
resBody, err := doPostRequest(params.BaseURL+finalRoute, body, auth)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
result := ResultError{}
|
||||||
|
err = json.Unmarshal(resBody, &result)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if result.Status == "ERROR" {
|
||||||
|
return nil, fmt.Errorf(result.Reason)
|
||||||
|
}
|
||||||
|
res := ManageAuthorization{}
|
||||||
|
err = json.Unmarshal(resBody, &res)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return &res, nil
|
||||||
|
},
|
||||||
BanDebit: func(req DebitOperation) error {
|
BanDebit: func(req DebitOperation) error {
|
||||||
auth, err := params.RetrieveUserAuth()
|
auth, err := params.RetrieveUserAuth()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
|
@ -906,6 +938,7 @@ func NewClient(params ClientParams) *Client {
|
||||||
return &res, nil
|
return &res, nil
|
||||||
},
|
},
|
||||||
// server streaming method: GetLiveDebitRequests not implemented
|
// server streaming method: GetLiveDebitRequests not implemented
|
||||||
|
// server streaming method: GetLiveManageRequests not implemented
|
||||||
// server streaming method: GetLiveUserOperations not implemented
|
// server streaming method: GetLiveUserOperations not implemented
|
||||||
GetLndForwardingMetrics: func(req LndMetricsRequest) (*LndForwardingMetrics, error) {
|
GetLndForwardingMetrics: func(req LndMetricsRequest) (*LndForwardingMetrics, error) {
|
||||||
auth, err := params.RetrieveMetricsAuth()
|
auth, err := params.RetrieveMetricsAuth()
|
||||||
|
|
@ -1069,6 +1102,28 @@ func NewClient(params ClientParams) *Client {
|
||||||
}
|
}
|
||||||
return &res, nil
|
return &res, nil
|
||||||
},
|
},
|
||||||
|
GetManageAuthorizations: func() (*ManageAuthorizations, error) {
|
||||||
|
auth, err := params.RetrieveUserAuth()
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
finalRoute := "/api/user/manage/get"
|
||||||
|
resBody, err := doGetRequest(params.BaseURL+finalRoute, auth)
|
||||||
|
result := ResultError{}
|
||||||
|
err = json.Unmarshal(resBody, &result)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if result.Status == "ERROR" {
|
||||||
|
return nil, fmt.Errorf(result.Reason)
|
||||||
|
}
|
||||||
|
res := ManageAuthorizations{}
|
||||||
|
err = json.Unmarshal(resBody, &res)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return &res, nil
|
||||||
|
},
|
||||||
// server streaming method: GetMigrationUpdate not implemented
|
// server streaming method: GetMigrationUpdate not implemented
|
||||||
GetNPubLinkingState: func(req GetNPubLinking) (*NPubLinking, error) {
|
GetNPubLinkingState: func(req GetNPubLinking) (*NPubLinking, error) {
|
||||||
auth, err := params.RetrieveAppAuth()
|
auth, err := params.RetrieveAppAuth()
|
||||||
|
|
|
||||||
|
|
@ -355,6 +355,10 @@ type LiveDebitRequest struct {
|
||||||
Npub string `json:"npub"`
|
Npub string `json:"npub"`
|
||||||
Request_id string `json:"request_id"`
|
Request_id string `json:"request_id"`
|
||||||
}
|
}
|
||||||
|
type LiveManageRequest struct {
|
||||||
|
Npub string `json:"npub"`
|
||||||
|
Request_id string `json:"request_id"`
|
||||||
|
}
|
||||||
type LiveUserOperation struct {
|
type LiveUserOperation struct {
|
||||||
Operation *UserOperation `json:"operation"`
|
Operation *UserOperation `json:"operation"`
|
||||||
}
|
}
|
||||||
|
|
@ -429,6 +433,19 @@ type LnurlWithdrawInfoResponse struct {
|
||||||
Paylink string `json:"payLink"`
|
Paylink string `json:"payLink"`
|
||||||
Tag string `json:"tag"`
|
Tag string `json:"tag"`
|
||||||
}
|
}
|
||||||
|
type ManageAuthorization struct {
|
||||||
|
Authorized bool `json:"authorized"`
|
||||||
|
Manage_id string `json:"manage_id"`
|
||||||
|
Npub string `json:"npub"`
|
||||||
|
}
|
||||||
|
type ManageAuthorizationRequest struct {
|
||||||
|
Authorize_npub string `json:"authorize_npub"`
|
||||||
|
Ban bool `json:"ban"`
|
||||||
|
Request_id string `json:"request_id"`
|
||||||
|
}
|
||||||
|
type ManageAuthorizations struct {
|
||||||
|
Manages []ManageAuthorization `json:"manages"`
|
||||||
|
}
|
||||||
type MetricsFile struct {
|
type MetricsFile struct {
|
||||||
}
|
}
|
||||||
type MigrationUpdate struct {
|
type MigrationUpdate struct {
|
||||||
|
|
|
||||||
|
|
@ -232,6 +232,28 @@ export default (methods: Types.ServerMethods, opts: ServerOptions) => {
|
||||||
opts.metricsCallback([{ ...info, ...stats, ...authContext }])
|
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 }
|
} 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.AuthorizeManage) throw new Error('method: AuthorizeManage is not implemented')
|
||||||
|
app.post('/api/user/manage/authorize', async (req, res) => {
|
||||||
|
const info: Types.RequestInfo = { rpcName: 'AuthorizeManage', 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.AuthorizeManage) throw new Error('method: AuthorizeManage is not implemented')
|
||||||
|
const authContext = await opts.UserAuthGuard(req.headers['authorization'])
|
||||||
|
authCtx = authContext
|
||||||
|
stats.guard = process.hrtime.bigint()
|
||||||
|
const request = req.body
|
||||||
|
const error = Types.ManageAuthorizationRequestValidate(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.AuthorizeManage({rpcName:'AuthorizeManage', 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.BanDebit) throw new Error('method: BanDebit is not implemented')
|
if (!opts.allowNotImplementedMethods && !methods.BanDebit) throw new Error('method: BanDebit is not implemented')
|
||||||
app.post('/api/user/debit/ban', async (req, res) => {
|
app.post('/api/user/debit/ban', async (req, res) => {
|
||||||
const info: Types.RequestInfo = { rpcName: 'BanDebit', batch: false, nostr: false, batchSize: 0}
|
const info: Types.RequestInfo = { rpcName: 'BanDebit', batch: false, nostr: false, batchSize: 0}
|
||||||
|
|
@ -333,6 +355,18 @@ export default (methods: Types.ServerMethods, opts: ServerOptions) => {
|
||||||
callsMetrics.push({ ...opInfo, ...opStats, ...ctx })
|
callsMetrics.push({ ...opInfo, ...opStats, ...ctx })
|
||||||
}
|
}
|
||||||
break
|
break
|
||||||
|
case 'AuthorizeManage':
|
||||||
|
if (!methods.AuthorizeManage) {
|
||||||
|
throw new Error('method AuthorizeManage not found' )
|
||||||
|
} else {
|
||||||
|
const error = Types.ManageAuthorizationRequestValidate(operation.req)
|
||||||
|
opStats.validate = process.hrtime.bigint()
|
||||||
|
if (error !== null) throw error
|
||||||
|
const res = await methods.AuthorizeManage({...operation, ctx}); responses.push({ status: 'OK', ...res })
|
||||||
|
opStats.handle = process.hrtime.bigint()
|
||||||
|
callsMetrics.push({ ...opInfo, ...opStats, ...ctx })
|
||||||
|
}
|
||||||
|
break
|
||||||
case 'BanDebit':
|
case 'BanDebit':
|
||||||
if (!methods.BanDebit) {
|
if (!methods.BanDebit) {
|
||||||
throw new Error('method BanDebit not found' )
|
throw new Error('method BanDebit not found' )
|
||||||
|
|
@ -443,6 +477,16 @@ export default (methods: Types.ServerMethods, opts: ServerOptions) => {
|
||||||
callsMetrics.push({ ...opInfo, ...opStats, ...ctx })
|
callsMetrics.push({ ...opInfo, ...opStats, ...ctx })
|
||||||
}
|
}
|
||||||
break
|
break
|
||||||
|
case 'GetManageAuthorizations':
|
||||||
|
if (!methods.GetManageAuthorizations) {
|
||||||
|
throw new Error('method GetManageAuthorizations not found' )
|
||||||
|
} else {
|
||||||
|
opStats.validate = opStats.guard
|
||||||
|
const res = await methods.GetManageAuthorizations({...operation, ctx}); responses.push({ status: 'OK', ...res })
|
||||||
|
opStats.handle = process.hrtime.bigint()
|
||||||
|
callsMetrics.push({ ...opInfo, ...opStats, ...ctx })
|
||||||
|
}
|
||||||
|
break
|
||||||
case 'GetPaymentState':
|
case 'GetPaymentState':
|
||||||
if (!methods.GetPaymentState) {
|
if (!methods.GetPaymentState) {
|
||||||
throw new Error('method GetPaymentState not found' )
|
throw new Error('method GetPaymentState not found' )
|
||||||
|
|
@ -1116,6 +1160,25 @@ export default (methods: Types.ServerMethods, opts: ServerOptions) => {
|
||||||
opts.metricsCallback([{ ...info, ...stats, ...authContext }])
|
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 }
|
} 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.GetManageAuthorizations) throw new Error('method: GetManageAuthorizations is not implemented')
|
||||||
|
app.get('/api/user/manage/get', async (req, res) => {
|
||||||
|
const info: Types.RequestInfo = { rpcName: 'GetManageAuthorizations', 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.GetManageAuthorizations) throw new Error('method: GetManageAuthorizations 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.GetManageAuthorizations({rpcName:'GetManageAuthorizations', ctx:authContext })
|
||||||
|
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.GetNPubLinkingState) throw new Error('method: GetNPubLinkingState is not implemented')
|
if (!opts.allowNotImplementedMethods && !methods.GetNPubLinkingState) throw new Error('method: GetNPubLinkingState is not implemented')
|
||||||
app.post('/api/app/user/npub/state', async (req, res) => {
|
app.post('/api/app/user/npub/state', async (req, res) => {
|
||||||
const info: Types.RequestInfo = { rpcName: 'GetNPubLinkingState', batch: false, nostr: false, batchSize: 0}
|
const info: Types.RequestInfo = { rpcName: 'GetNPubLinkingState', batch: false, nostr: false, batchSize: 0}
|
||||||
|
|
|
||||||
|
|
@ -140,6 +140,20 @@ export default (params: ClientParams) => ({
|
||||||
}
|
}
|
||||||
return { status: 'ERROR', reason: 'invalid response' }
|
return { status: 'ERROR', reason: 'invalid response' }
|
||||||
},
|
},
|
||||||
|
AuthorizeManage: async (request: Types.ManageAuthorizationRequest): Promise<ResultError | ({ status: 'OK' }& Types.ManageAuthorization)> => {
|
||||||
|
const auth = await params.retrieveUserAuth()
|
||||||
|
if (auth === null) throw new Error('retrieveUserAuth() returned null')
|
||||||
|
let finalRoute = '/api/user/manage/authorize'
|
||||||
|
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.ManageAuthorizationValidate(result)
|
||||||
|
if (error === null) { return { status: 'OK', ...result } } else return { status: 'ERROR', reason: error.message }
|
||||||
|
}
|
||||||
|
return { status: 'ERROR', reason: 'invalid response' }
|
||||||
|
},
|
||||||
BanDebit: async (request: Types.DebitOperation): Promise<ResultError | ({ status: 'OK' })> => {
|
BanDebit: async (request: Types.DebitOperation): Promise<ResultError | ({ status: 'OK' })> => {
|
||||||
const auth = await params.retrieveUserAuth()
|
const auth = await params.retrieveUserAuth()
|
||||||
if (auth === null) throw new Error('retrieveUserAuth() returned null')
|
if (auth === null) throw new Error('retrieveUserAuth() returned null')
|
||||||
|
|
@ -403,6 +417,7 @@ export default (params: ClientParams) => ({
|
||||||
return { status: 'ERROR', reason: 'invalid response' }
|
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')},
|
GetLiveDebitRequests: async (cb: (v:ResultError | ({ status: 'OK' }& Types.LiveDebitRequest)) => void): Promise<void> => { throw new Error('http streams are not supported')},
|
||||||
|
GetLiveManageRequests: async (cb: (v:ResultError | ({ status: 'OK' }& Types.LiveManageRequest)) => 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')},
|
GetLiveUserOperations: async (cb: (v:ResultError | ({ status: 'OK' }& Types.LiveUserOperation)) => void): Promise<void> => { throw new Error('http streams are not supported')},
|
||||||
GetLndForwardingMetrics: async (request: Types.LndMetricsRequest): Promise<ResultError | ({ status: 'OK' }& Types.LndForwardingMetrics)> => {
|
GetLndForwardingMetrics: async (request: Types.LndMetricsRequest): Promise<ResultError | ({ status: 'OK' }& Types.LndForwardingMetrics)> => {
|
||||||
const auth = await params.retrieveMetricsAuth()
|
const auth = await params.retrieveMetricsAuth()
|
||||||
|
|
@ -492,6 +507,20 @@ export default (params: ClientParams) => ({
|
||||||
}
|
}
|
||||||
return { status: 'ERROR', reason: 'invalid response' }
|
return { status: 'ERROR', reason: 'invalid response' }
|
||||||
},
|
},
|
||||||
|
GetManageAuthorizations: async (): Promise<ResultError | ({ status: 'OK' }& Types.ManageAuthorizations)> => {
|
||||||
|
const auth = await params.retrieveUserAuth()
|
||||||
|
if (auth === null) throw new Error('retrieveUserAuth() returned null')
|
||||||
|
let finalRoute = '/api/user/manage/get'
|
||||||
|
const { data } = await axios.get(params.baseUrl + finalRoute, { headers: { 'authorization': auth } })
|
||||||
|
if (data.status === 'ERROR' && typeof data.reason === 'string') return data
|
||||||
|
if (data.status === 'OK') {
|
||||||
|
const result = data
|
||||||
|
if(!params.checkResult) return { status: 'OK', ...result }
|
||||||
|
const error = Types.ManageAuthorizationsValidate(result)
|
||||||
|
if (error === null) { return { status: 'OK', ...result } } else return { status: 'ERROR', reason: error.message }
|
||||||
|
}
|
||||||
|
return { status: 'ERROR', reason: 'invalid response' }
|
||||||
|
},
|
||||||
GetMigrationUpdate: async (cb: (v:ResultError | ({ status: 'OK' }& Types.MigrationUpdate)) => void): Promise<void> => { throw new Error('http streams are not supported')},
|
GetMigrationUpdate: async (cb: (v:ResultError | ({ status: 'OK' }& Types.MigrationUpdate)) => void): Promise<void> => { throw new Error('http streams are not supported')},
|
||||||
GetNPubLinkingState: async (request: Types.GetNPubLinking): Promise<ResultError | ({ status: 'OK' }& Types.NPubLinking)> => {
|
GetNPubLinkingState: async (request: Types.GetNPubLinking): Promise<ResultError | ({ status: 'OK' }& Types.NPubLinking)> => {
|
||||||
const auth = await params.retrieveAppAuth()
|
const auth = await params.retrieveAppAuth()
|
||||||
|
|
|
||||||
|
|
@ -99,6 +99,21 @@ export default (params: NostrClientParams, send: (to:string, message: NostrRequ
|
||||||
}
|
}
|
||||||
return { status: 'ERROR', reason: 'invalid response' }
|
return { status: 'ERROR', reason: 'invalid response' }
|
||||||
},
|
},
|
||||||
|
AuthorizeManage: async (request: Types.ManageAuthorizationRequest): Promise<ResultError | ({ status: 'OK' }& Types.ManageAuthorization)> => {
|
||||||
|
const auth = await params.retrieveNostrUserAuth()
|
||||||
|
if (auth === null) throw new Error('retrieveNostrUserAuth() returned null')
|
||||||
|
const nostrRequest: NostrRequest = {}
|
||||||
|
nostrRequest.body = request
|
||||||
|
const data = await send(params.pubDestination, {rpcName:'AuthorizeManage',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.ManageAuthorizationValidate(result)
|
||||||
|
if (error === null) { return { status: 'OK', ...result } } else return { status: 'ERROR', reason: error.message }
|
||||||
|
}
|
||||||
|
return { status: 'ERROR', reason: 'invalid response' }
|
||||||
|
},
|
||||||
BanDebit: async (request: Types.DebitOperation): Promise<ResultError | ({ status: 'OK' })> => {
|
BanDebit: async (request: Types.DebitOperation): Promise<ResultError | ({ status: 'OK' })> => {
|
||||||
const auth = await params.retrieveNostrUserAuth()
|
const auth = await params.retrieveNostrUserAuth()
|
||||||
if (auth === null) throw new Error('retrieveNostrUserAuth() returned null')
|
if (auth === null) throw new Error('retrieveNostrUserAuth() returned null')
|
||||||
|
|
@ -334,6 +349,21 @@ export default (params: NostrClientParams, send: (to:string, message: NostrRequ
|
||||||
return cb({ status: 'ERROR', reason: 'invalid response' })
|
return cb({ status: 'ERROR', reason: 'invalid response' })
|
||||||
})
|
})
|
||||||
},
|
},
|
||||||
|
GetLiveManageRequests: async (cb: (res:ResultError | ({ status: 'OK' }& Types.LiveManageRequest)) => void): Promise<void> => {
|
||||||
|
const auth = await params.retrieveNostrUserAuth()
|
||||||
|
if (auth === null) throw new Error('retrieveNostrUserAuth() returned null')
|
||||||
|
const nostrRequest: NostrRequest = {}
|
||||||
|
subscribe(params.pubDestination, {rpcName:'GetLiveManageRequests',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.LiveManageRequestValidate(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> => {
|
GetLiveUserOperations: async (cb: (res:ResultError | ({ status: 'OK' }& Types.LiveUserOperation)) => void): Promise<void> => {
|
||||||
const auth = await params.retrieveNostrUserAuth()
|
const auth = await params.retrieveNostrUserAuth()
|
||||||
if (auth === null) throw new Error('retrieveNostrUserAuth() returned null')
|
if (auth === null) throw new Error('retrieveNostrUserAuth() returned null')
|
||||||
|
|
@ -407,6 +437,20 @@ export default (params: NostrClientParams, send: (to:string, message: NostrRequ
|
||||||
}
|
}
|
||||||
return { status: 'ERROR', reason: 'invalid response' }
|
return { status: 'ERROR', reason: 'invalid response' }
|
||||||
},
|
},
|
||||||
|
GetManageAuthorizations: async (): Promise<ResultError | ({ status: 'OK' }& Types.ManageAuthorizations)> => {
|
||||||
|
const auth = await params.retrieveNostrUserAuth()
|
||||||
|
if (auth === null) throw new Error('retrieveNostrUserAuth() returned null')
|
||||||
|
const nostrRequest: NostrRequest = {}
|
||||||
|
const data = await send(params.pubDestination, {rpcName:'GetManageAuthorizations',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.ManageAuthorizationsValidate(result)
|
||||||
|
if (error === null) { return { status: 'OK', ...result } } else return { status: 'ERROR', reason: error.message }
|
||||||
|
}
|
||||||
|
return { status: 'ERROR', reason: 'invalid response' }
|
||||||
|
},
|
||||||
GetMigrationUpdate: async (cb: (res:ResultError | ({ status: 'OK' }& Types.MigrationUpdate)) => void): Promise<void> => {
|
GetMigrationUpdate: async (cb: (res:ResultError | ({ status: 'OK' }& Types.MigrationUpdate)) => void): Promise<void> => {
|
||||||
const auth = await params.retrieveNostrUserAuth()
|
const auth = await params.retrieveNostrUserAuth()
|
||||||
if (auth === null) throw new Error('retrieveNostrUserAuth() returned null')
|
if (auth === null) throw new Error('retrieveNostrUserAuth() returned null')
|
||||||
|
|
|
||||||
|
|
@ -128,6 +128,22 @@ export default (methods: Types.ServerMethods, opts: NostrOptions) => {
|
||||||
opts.metricsCallback([{ ...info, ...stats, ...authContext }])
|
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 }
|
}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
|
break
|
||||||
|
case 'AuthorizeManage':
|
||||||
|
try {
|
||||||
|
if (!methods.AuthorizeManage) throw new Error('method: AuthorizeManage is not implemented')
|
||||||
|
const authContext = await opts.NostrUserAuthGuard(req.appId, req.authIdentifier)
|
||||||
|
stats.guard = process.hrtime.bigint()
|
||||||
|
authCtx = authContext
|
||||||
|
const request = req.body
|
||||||
|
const error = Types.ManageAuthorizationRequestValidate(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.AuthorizeManage({rpcName:'AuthorizeManage', ctx:authContext , req: request})
|
||||||
|
stats.handle = process.hrtime.bigint()
|
||||||
|
res({status: 'OK', ...response})
|
||||||
|
opts.metricsCallback([{ ...info, ...stats, ...authContext }])
|
||||||
|
}catch(ex){ const e = ex as any; logErrorAndReturnResponse(e, e.message || e, res, logger, { ...info, ...stats, ...authCtx }, opts.metricsCallback); if (opts.throwErrors) throw e }
|
||||||
|
break
|
||||||
case 'BanDebit':
|
case 'BanDebit':
|
||||||
try {
|
try {
|
||||||
if (!methods.BanDebit) throw new Error('method: BanDebit is not implemented')
|
if (!methods.BanDebit) throw new Error('method: BanDebit is not implemented')
|
||||||
|
|
@ -215,6 +231,18 @@ export default (methods: Types.ServerMethods, opts: NostrOptions) => {
|
||||||
callsMetrics.push({ ...opInfo, ...opStats, ...ctx })
|
callsMetrics.push({ ...opInfo, ...opStats, ...ctx })
|
||||||
}
|
}
|
||||||
break
|
break
|
||||||
|
case 'AuthorizeManage':
|
||||||
|
if (!methods.AuthorizeManage) {
|
||||||
|
throw new Error('method not defined: AuthorizeManage')
|
||||||
|
} else {
|
||||||
|
const error = Types.ManageAuthorizationRequestValidate(operation.req)
|
||||||
|
opStats.validate = process.hrtime.bigint()
|
||||||
|
if (error !== null) throw error
|
||||||
|
const res = await methods.AuthorizeManage({...operation, ctx}); responses.push({ status: 'OK', ...res })
|
||||||
|
opStats.handle = process.hrtime.bigint()
|
||||||
|
callsMetrics.push({ ...opInfo, ...opStats, ...ctx })
|
||||||
|
}
|
||||||
|
break
|
||||||
case 'BanDebit':
|
case 'BanDebit':
|
||||||
if (!methods.BanDebit) {
|
if (!methods.BanDebit) {
|
||||||
throw new Error('method not defined: BanDebit')
|
throw new Error('method not defined: BanDebit')
|
||||||
|
|
@ -325,6 +353,16 @@ export default (methods: Types.ServerMethods, opts: NostrOptions) => {
|
||||||
callsMetrics.push({ ...opInfo, ...opStats, ...ctx })
|
callsMetrics.push({ ...opInfo, ...opStats, ...ctx })
|
||||||
}
|
}
|
||||||
break
|
break
|
||||||
|
case 'GetManageAuthorizations':
|
||||||
|
if (!methods.GetManageAuthorizations) {
|
||||||
|
throw new Error('method not defined: GetManageAuthorizations')
|
||||||
|
} else {
|
||||||
|
opStats.validate = opStats.guard
|
||||||
|
const res = await methods.GetManageAuthorizations({...operation, ctx}); responses.push({ status: 'OK', ...res })
|
||||||
|
opStats.handle = process.hrtime.bigint()
|
||||||
|
callsMetrics.push({ ...opInfo, ...opStats, ...ctx })
|
||||||
|
}
|
||||||
|
break
|
||||||
case 'GetPaymentState':
|
case 'GetPaymentState':
|
||||||
if (!methods.GetPaymentState) {
|
if (!methods.GetPaymentState) {
|
||||||
throw new Error('method not defined: GetPaymentState')
|
throw new Error('method not defined: GetPaymentState')
|
||||||
|
|
@ -728,6 +766,19 @@ export default (methods: Types.ServerMethods, opts: NostrOptions) => {
|
||||||
}})
|
}})
|
||||||
}catch(ex){ const e = ex as any; logErrorAndReturnResponse(e, e.message || e, res, logger, { ...info, ...stats, ...authCtx }, opts.metricsCallback); if (opts.throwErrors) throw e }
|
}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
|
break
|
||||||
|
case 'GetLiveManageRequests':
|
||||||
|
try {
|
||||||
|
if (!methods.GetLiveManageRequests) throw new Error('method: GetLiveManageRequests is not implemented')
|
||||||
|
const authContext = await opts.NostrUserAuthGuard(req.appId, req.authIdentifier)
|
||||||
|
stats.guard = process.hrtime.bigint()
|
||||||
|
authCtx = authContext
|
||||||
|
stats.validate = stats.guard
|
||||||
|
methods.GetLiveManageRequests({rpcName:'GetLiveManageRequests', 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':
|
case 'GetLiveUserOperations':
|
||||||
try {
|
try {
|
||||||
if (!methods.GetLiveUserOperations) throw new Error('method: GetLiveUserOperations is not implemented')
|
if (!methods.GetLiveUserOperations) throw new Error('method: GetLiveUserOperations is not implemented')
|
||||||
|
|
@ -799,6 +850,19 @@ export default (methods: Types.ServerMethods, opts: NostrOptions) => {
|
||||||
opts.metricsCallback([{ ...info, ...stats, ...authContext }])
|
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 }
|
}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
|
break
|
||||||
|
case 'GetManageAuthorizations':
|
||||||
|
try {
|
||||||
|
if (!methods.GetManageAuthorizations) throw new Error('method: GetManageAuthorizations 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.GetManageAuthorizations({rpcName:'GetManageAuthorizations', ctx:authContext })
|
||||||
|
stats.handle = process.hrtime.bigint()
|
||||||
|
res({status: 'OK', ...response})
|
||||||
|
opts.metricsCallback([{ ...info, ...stats, ...authContext }])
|
||||||
|
}catch(ex){ const e = ex as any; logErrorAndReturnResponse(e, e.message || e, res, logger, { ...info, ...stats, ...authCtx }, opts.metricsCallback); if (opts.throwErrors) throw e }
|
||||||
|
break
|
||||||
case 'GetMigrationUpdate':
|
case 'GetMigrationUpdate':
|
||||||
try {
|
try {
|
||||||
if (!methods.GetMigrationUpdate) throw new Error('method: GetMigrationUpdate is not implemented')
|
if (!methods.GetMigrationUpdate) throw new Error('method: GetMigrationUpdate is not implemented')
|
||||||
|
|
|
||||||
|
|
@ -35,8 +35,8 @@ export type UserContext = {
|
||||||
app_user_id: string
|
app_user_id: string
|
||||||
user_id: string
|
user_id: string
|
||||||
}
|
}
|
||||||
export type UserMethodInputs = AddProduct_Input | AddUserOffer_Input | AuthorizeDebit_Input | BanDebit_Input | DecodeInvoice_Input | DeleteUserOffer_Input | EditDebit_Input | EnrollAdminToken_Input | GetDebitAuthorizations_Input | GetHttpCreds_Input | GetLNURLChannelLink_Input | GetLnurlPayLink_Input | GetLnurlWithdrawLink_Input | GetPaymentState_Input | GetUserInfo_Input | GetUserOffer_Input | GetUserOfferInvoices_Input | GetUserOffers_Input | GetUserOperations_Input | NewAddress_Input | NewInvoice_Input | NewProductInvoice_Input | PayAddress_Input | PayInvoice_Input | ResetDebit_Input | RespondToDebit_Input | UpdateCallbackUrl_Input | UpdateUserOffer_Input | UserHealth_Input
|
export type UserMethodInputs = AddProduct_Input | AddUserOffer_Input | AuthorizeDebit_Input | AuthorizeManage_Input | BanDebit_Input | DecodeInvoice_Input | DeleteUserOffer_Input | EditDebit_Input | EnrollAdminToken_Input | GetDebitAuthorizations_Input | GetHttpCreds_Input | GetLNURLChannelLink_Input | GetLnurlPayLink_Input | GetLnurlWithdrawLink_Input | GetManageAuthorizations_Input | GetPaymentState_Input | GetUserInfo_Input | GetUserOffer_Input | GetUserOfferInvoices_Input | GetUserOffers_Input | GetUserOperations_Input | NewAddress_Input | NewInvoice_Input | NewProductInvoice_Input | PayAddress_Input | PayInvoice_Input | ResetDebit_Input | RespondToDebit_Input | UpdateCallbackUrl_Input | UpdateUserOffer_Input | UserHealth_Input
|
||||||
export type UserMethodOutputs = AddProduct_Output | AddUserOffer_Output | AuthorizeDebit_Output | BanDebit_Output | DecodeInvoice_Output | DeleteUserOffer_Output | EditDebit_Output | EnrollAdminToken_Output | GetDebitAuthorizations_Output | GetHttpCreds_Output | GetLNURLChannelLink_Output | GetLnurlPayLink_Output | GetLnurlWithdrawLink_Output | GetPaymentState_Output | GetUserInfo_Output | GetUserOffer_Output | GetUserOfferInvoices_Output | GetUserOffers_Output | GetUserOperations_Output | NewAddress_Output | NewInvoice_Output | NewProductInvoice_Output | PayAddress_Output | PayInvoice_Output | ResetDebit_Output | RespondToDebit_Output | UpdateCallbackUrl_Output | UpdateUserOffer_Output | UserHealth_Output
|
export type UserMethodOutputs = AddProduct_Output | AddUserOffer_Output | AuthorizeDebit_Output | AuthorizeManage_Output | BanDebit_Output | DecodeInvoice_Output | DeleteUserOffer_Output | EditDebit_Output | EnrollAdminToken_Output | GetDebitAuthorizations_Output | GetHttpCreds_Output | GetLNURLChannelLink_Output | GetLnurlPayLink_Output | GetLnurlWithdrawLink_Output | GetManageAuthorizations_Output | GetPaymentState_Output | GetUserInfo_Output | GetUserOffer_Output | GetUserOfferInvoices_Output | GetUserOffers_Output | GetUserOperations_Output | NewAddress_Output | NewInvoice_Output | NewProductInvoice_Output | PayAddress_Output | PayInvoice_Output | ResetDebit_Output | RespondToDebit_Output | UpdateCallbackUrl_Output | UpdateUserOffer_Output | UserHealth_Output
|
||||||
export type AuthContext = AdminContext | AppContext | GuestContext | GuestWithPubContext | MetricsContext | UserContext
|
export type AuthContext = AdminContext | AppContext | GuestContext | GuestWithPubContext | MetricsContext | UserContext
|
||||||
|
|
||||||
export type AddApp_Input = {rpcName:'AddApp', req: AddAppRequest}
|
export type AddApp_Input = {rpcName:'AddApp', req: AddAppRequest}
|
||||||
|
|
@ -66,6 +66,9 @@ export type AuthApp_Output = ResultError | ({ status: 'OK' } & AuthApp)
|
||||||
export type AuthorizeDebit_Input = {rpcName:'AuthorizeDebit', req: DebitAuthorizationRequest}
|
export type AuthorizeDebit_Input = {rpcName:'AuthorizeDebit', req: DebitAuthorizationRequest}
|
||||||
export type AuthorizeDebit_Output = ResultError | ({ status: 'OK' } & DebitAuthorization)
|
export type AuthorizeDebit_Output = ResultError | ({ status: 'OK' } & DebitAuthorization)
|
||||||
|
|
||||||
|
export type AuthorizeManage_Input = {rpcName:'AuthorizeManage', req: ManageAuthorizationRequest}
|
||||||
|
export type AuthorizeManage_Output = ResultError | ({ status: 'OK' } & ManageAuthorization)
|
||||||
|
|
||||||
export type BanDebit_Input = {rpcName:'BanDebit', req: DebitOperation}
|
export type BanDebit_Input = {rpcName:'BanDebit', req: DebitOperation}
|
||||||
export type BanDebit_Output = ResultError | { status: 'OK' }
|
export type BanDebit_Output = ResultError | { status: 'OK' }
|
||||||
|
|
||||||
|
|
@ -129,6 +132,9 @@ export type GetLNURLChannelLink_Output = ResultError | ({ status: 'OK' } & Lnurl
|
||||||
export type GetLiveDebitRequests_Input = {rpcName:'GetLiveDebitRequests', cb:(res: LiveDebitRequest, err:Error|null)=> void}
|
export type GetLiveDebitRequests_Input = {rpcName:'GetLiveDebitRequests', cb:(res: LiveDebitRequest, err:Error|null)=> void}
|
||||||
export type GetLiveDebitRequests_Output = ResultError | { status: 'OK' }
|
export type GetLiveDebitRequests_Output = ResultError | { status: 'OK' }
|
||||||
|
|
||||||
|
export type GetLiveManageRequests_Input = {rpcName:'GetLiveManageRequests', cb:(res: LiveManageRequest, err:Error|null)=> void}
|
||||||
|
export type GetLiveManageRequests_Output = ResultError | { status: 'OK' }
|
||||||
|
|
||||||
export type GetLiveUserOperations_Input = {rpcName:'GetLiveUserOperations', cb:(res: LiveUserOperation, err:Error|null)=> void}
|
export type GetLiveUserOperations_Input = {rpcName:'GetLiveUserOperations', cb:(res: LiveUserOperation, err:Error|null)=> void}
|
||||||
export type GetLiveUserOperations_Output = ResultError | { status: 'OK' }
|
export type GetLiveUserOperations_Output = ResultError | { status: 'OK' }
|
||||||
|
|
||||||
|
|
@ -156,6 +162,9 @@ export type GetLnurlWithdrawInfo_Output = ResultError | ({ status: 'OK' } & Lnur
|
||||||
export type GetLnurlWithdrawLink_Input = {rpcName:'GetLnurlWithdrawLink'}
|
export type GetLnurlWithdrawLink_Input = {rpcName:'GetLnurlWithdrawLink'}
|
||||||
export type GetLnurlWithdrawLink_Output = ResultError | ({ status: 'OK' } & LnurlLinkResponse)
|
export type GetLnurlWithdrawLink_Output = ResultError | ({ status: 'OK' } & LnurlLinkResponse)
|
||||||
|
|
||||||
|
export type GetManageAuthorizations_Input = {rpcName:'GetManageAuthorizations'}
|
||||||
|
export type GetManageAuthorizations_Output = ResultError | ({ status: 'OK' } & ManageAuthorizations)
|
||||||
|
|
||||||
export type GetMigrationUpdate_Input = {rpcName:'GetMigrationUpdate', cb:(res: MigrationUpdate, err:Error|null)=> void}
|
export type GetMigrationUpdate_Input = {rpcName:'GetMigrationUpdate', cb:(res: MigrationUpdate, err:Error|null)=> void}
|
||||||
export type GetMigrationUpdate_Output = ResultError | { status: 'OK' }
|
export type GetMigrationUpdate_Output = ResultError | { status: 'OK' }
|
||||||
|
|
||||||
|
|
@ -320,6 +329,7 @@ export type ServerMethods = {
|
||||||
AddUserOffer?: (req: AddUserOffer_Input & {ctx: UserContext }) => Promise<OfferId>
|
AddUserOffer?: (req: AddUserOffer_Input & {ctx: UserContext }) => Promise<OfferId>
|
||||||
AuthApp?: (req: AuthApp_Input & {ctx: AdminContext }) => Promise<AuthApp>
|
AuthApp?: (req: AuthApp_Input & {ctx: AdminContext }) => Promise<AuthApp>
|
||||||
AuthorizeDebit?: (req: AuthorizeDebit_Input & {ctx: UserContext }) => Promise<DebitAuthorization>
|
AuthorizeDebit?: (req: AuthorizeDebit_Input & {ctx: UserContext }) => Promise<DebitAuthorization>
|
||||||
|
AuthorizeManage?: (req: AuthorizeManage_Input & {ctx: UserContext }) => Promise<ManageAuthorization>
|
||||||
BanDebit?: (req: BanDebit_Input & {ctx: UserContext }) => Promise<void>
|
BanDebit?: (req: BanDebit_Input & {ctx: UserContext }) => Promise<void>
|
||||||
BanUser?: (req: BanUser_Input & {ctx: AdminContext }) => Promise<BanUserResponse>
|
BanUser?: (req: BanUser_Input & {ctx: AdminContext }) => Promise<BanUserResponse>
|
||||||
CloseChannel?: (req: CloseChannel_Input & {ctx: AdminContext }) => Promise<CloseChannelResponse>
|
CloseChannel?: (req: CloseChannel_Input & {ctx: AdminContext }) => Promise<CloseChannelResponse>
|
||||||
|
|
@ -340,6 +350,7 @@ export type ServerMethods = {
|
||||||
GetInviteLinkState?: (req: GetInviteLinkState_Input & {ctx: AdminContext }) => Promise<GetInviteTokenStateResponse>
|
GetInviteLinkState?: (req: GetInviteLinkState_Input & {ctx: AdminContext }) => Promise<GetInviteTokenStateResponse>
|
||||||
GetLNURLChannelLink?: (req: GetLNURLChannelLink_Input & {ctx: UserContext }) => Promise<LnurlLinkResponse>
|
GetLNURLChannelLink?: (req: GetLNURLChannelLink_Input & {ctx: UserContext }) => Promise<LnurlLinkResponse>
|
||||||
GetLiveDebitRequests?: (req: GetLiveDebitRequests_Input & {ctx: UserContext }) => Promise<void>
|
GetLiveDebitRequests?: (req: GetLiveDebitRequests_Input & {ctx: UserContext }) => Promise<void>
|
||||||
|
GetLiveManageRequests?: (req: GetLiveManageRequests_Input & {ctx: UserContext }) => Promise<void>
|
||||||
GetLiveUserOperations?: (req: GetLiveUserOperations_Input & {ctx: UserContext }) => Promise<void>
|
GetLiveUserOperations?: (req: GetLiveUserOperations_Input & {ctx: UserContext }) => Promise<void>
|
||||||
GetLndForwardingMetrics?: (req: GetLndForwardingMetrics_Input & {ctx: MetricsContext }) => Promise<LndForwardingMetrics>
|
GetLndForwardingMetrics?: (req: GetLndForwardingMetrics_Input & {ctx: MetricsContext }) => Promise<LndForwardingMetrics>
|
||||||
GetLndMetrics?: (req: GetLndMetrics_Input & {ctx: MetricsContext }) => Promise<LndMetrics>
|
GetLndMetrics?: (req: GetLndMetrics_Input & {ctx: MetricsContext }) => Promise<LndMetrics>
|
||||||
|
|
@ -347,6 +358,7 @@ export type ServerMethods = {
|
||||||
GetLnurlPayLink?: (req: GetLnurlPayLink_Input & {ctx: UserContext }) => Promise<LnurlLinkResponse>
|
GetLnurlPayLink?: (req: GetLnurlPayLink_Input & {ctx: UserContext }) => Promise<LnurlLinkResponse>
|
||||||
GetLnurlWithdrawInfo?: (req: GetLnurlWithdrawInfo_Input & {ctx: GuestContext }) => Promise<LnurlWithdrawInfoResponse>
|
GetLnurlWithdrawInfo?: (req: GetLnurlWithdrawInfo_Input & {ctx: GuestContext }) => Promise<LnurlWithdrawInfoResponse>
|
||||||
GetLnurlWithdrawLink?: (req: GetLnurlWithdrawLink_Input & {ctx: UserContext }) => Promise<LnurlLinkResponse>
|
GetLnurlWithdrawLink?: (req: GetLnurlWithdrawLink_Input & {ctx: UserContext }) => Promise<LnurlLinkResponse>
|
||||||
|
GetManageAuthorizations?: (req: GetManageAuthorizations_Input & {ctx: UserContext }) => Promise<ManageAuthorizations>
|
||||||
GetMigrationUpdate?: (req: GetMigrationUpdate_Input & {ctx: UserContext }) => Promise<void>
|
GetMigrationUpdate?: (req: GetMigrationUpdate_Input & {ctx: UserContext }) => Promise<void>
|
||||||
GetNPubLinkingState?: (req: GetNPubLinkingState_Input & {ctx: AppContext }) => Promise<NPubLinking>
|
GetNPubLinkingState?: (req: GetNPubLinkingState_Input & {ctx: AppContext }) => Promise<NPubLinking>
|
||||||
GetPaymentState?: (req: GetPaymentState_Input & {ctx: UserContext }) => Promise<PaymentState>
|
GetPaymentState?: (req: GetPaymentState_Input & {ctx: UserContext }) => Promise<PaymentState>
|
||||||
|
|
@ -2011,6 +2023,29 @@ export const LiveDebitRequestValidate = (o?: LiveDebitRequest, opts: LiveDebitRe
|
||||||
return null
|
return null
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export type LiveManageRequest = {
|
||||||
|
npub: string
|
||||||
|
request_id: string
|
||||||
|
}
|
||||||
|
export const LiveManageRequestOptionalFields: [] = []
|
||||||
|
export type LiveManageRequestOptions = OptionsBaseMessage & {
|
||||||
|
checkOptionalsAreSet?: []
|
||||||
|
npub_CustomCheck?: (v: string) => boolean
|
||||||
|
request_id_CustomCheck?: (v: string) => boolean
|
||||||
|
}
|
||||||
|
export const LiveManageRequestValidate = (o?: LiveManageRequest, opts: LiveManageRequestOptions = {}, path: string = 'LiveManageRequest::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.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 (typeof o.request_id !== 'string') return new Error(`${path}.request_id: is not a string`)
|
||||||
|
if (opts.request_id_CustomCheck && !opts.request_id_CustomCheck(o.request_id)) return new Error(`${path}.request_id: custom check failed`)
|
||||||
|
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
|
||||||
export type LiveUserOperation = {
|
export type LiveUserOperation = {
|
||||||
operation: UserOperation
|
operation: UserOperation
|
||||||
}
|
}
|
||||||
|
|
@ -2470,6 +2505,86 @@ export const LnurlWithdrawInfoResponseValidate = (o?: LnurlWithdrawInfoResponse,
|
||||||
return null
|
return null
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export type ManageAuthorization = {
|
||||||
|
authorized: boolean
|
||||||
|
manage_id: string
|
||||||
|
npub: string
|
||||||
|
}
|
||||||
|
export const ManageAuthorizationOptionalFields: [] = []
|
||||||
|
export type ManageAuthorizationOptions = OptionsBaseMessage & {
|
||||||
|
checkOptionalsAreSet?: []
|
||||||
|
authorized_CustomCheck?: (v: boolean) => boolean
|
||||||
|
manage_id_CustomCheck?: (v: string) => boolean
|
||||||
|
npub_CustomCheck?: (v: string) => boolean
|
||||||
|
}
|
||||||
|
export const ManageAuthorizationValidate = (o?: ManageAuthorization, opts: ManageAuthorizationOptions = {}, path: string = 'ManageAuthorization::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.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.manage_id !== 'string') return new Error(`${path}.manage_id: is not a string`)
|
||||||
|
if (opts.manage_id_CustomCheck && !opts.manage_id_CustomCheck(o.manage_id)) return new Error(`${path}.manage_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
|
||||||
|
}
|
||||||
|
|
||||||
|
export type ManageAuthorizationRequest = {
|
||||||
|
authorize_npub: string
|
||||||
|
ban: boolean
|
||||||
|
request_id?: string
|
||||||
|
}
|
||||||
|
export type ManageAuthorizationRequestOptionalField = 'request_id'
|
||||||
|
export const ManageAuthorizationRequestOptionalFields: ManageAuthorizationRequestOptionalField[] = ['request_id']
|
||||||
|
export type ManageAuthorizationRequestOptions = OptionsBaseMessage & {
|
||||||
|
checkOptionalsAreSet?: ManageAuthorizationRequestOptionalField[]
|
||||||
|
authorize_npub_CustomCheck?: (v: string) => boolean
|
||||||
|
ban_CustomCheck?: (v: boolean) => boolean
|
||||||
|
request_id_CustomCheck?: (v?: string) => boolean
|
||||||
|
}
|
||||||
|
export const ManageAuthorizationRequestValidate = (o?: ManageAuthorizationRequest, opts: ManageAuthorizationRequestOptions = {}, path: string = 'ManageAuthorizationRequest::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 (typeof o.ban !== 'boolean') return new Error(`${path}.ban: is not a boolean`)
|
||||||
|
if (opts.ban_CustomCheck && !opts.ban_CustomCheck(o.ban)) return new Error(`${path}.ban: custom check failed`)
|
||||||
|
|
||||||
|
if ((o.request_id || opts.allOptionalsAreSet || opts.checkOptionalsAreSet?.includes('request_id')) && typeof o.request_id !== 'string') return new Error(`${path}.request_id: is not a string`)
|
||||||
|
if (opts.request_id_CustomCheck && !opts.request_id_CustomCheck(o.request_id)) return new Error(`${path}.request_id: custom check failed`)
|
||||||
|
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
|
||||||
|
export type ManageAuthorizations = {
|
||||||
|
manages: ManageAuthorization[]
|
||||||
|
}
|
||||||
|
export const ManageAuthorizationsOptionalFields: [] = []
|
||||||
|
export type ManageAuthorizationsOptions = OptionsBaseMessage & {
|
||||||
|
checkOptionalsAreSet?: []
|
||||||
|
manages_ItemOptions?: ManageAuthorizationOptions
|
||||||
|
manages_CustomCheck?: (v: ManageAuthorization[]) => boolean
|
||||||
|
}
|
||||||
|
export const ManageAuthorizationsValidate = (o?: ManageAuthorizations, opts: ManageAuthorizationsOptions = {}, path: string = 'ManageAuthorizations::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.manages)) return new Error(`${path}.manages: is not an array`)
|
||||||
|
for (let index = 0; index < o.manages.length; index++) {
|
||||||
|
const managesErr = ManageAuthorizationValidate(o.manages[index], opts.manages_ItemOptions, `${path}.manages[${index}]`)
|
||||||
|
if (managesErr !== null) return managesErr
|
||||||
|
}
|
||||||
|
if (opts.manages_CustomCheck && !opts.manages_CustomCheck(o.manages)) return new Error(`${path}.manages: custom check failed`)
|
||||||
|
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
|
||||||
export type MetricsFile = {
|
export type MetricsFile = {
|
||||||
}
|
}
|
||||||
export const MetricsFileOptionalFields: [] = []
|
export const MetricsFileOptionalFields: [] = []
|
||||||
|
|
|
||||||
|
|
@ -592,12 +592,24 @@ service LightningPub {
|
||||||
option (http_route) = "/api/user/debit/get";
|
option (http_route) = "/api/user/debit/get";
|
||||||
option (nostr) = true;
|
option (nostr) = true;
|
||||||
}
|
}
|
||||||
|
rpc GetManageAuthorizations(structs.Empty) returns (structs.ManageAuthorizations){
|
||||||
|
option (auth_type) = "User";
|
||||||
|
option (http_method) = "get";
|
||||||
|
option (http_route) = "/api/user/manage/get";
|
||||||
|
option (nostr) = true;
|
||||||
|
}
|
||||||
rpc AuthorizeDebit(structs.DebitAuthorizationRequest) returns (structs.DebitAuthorization){
|
rpc AuthorizeDebit(structs.DebitAuthorizationRequest) returns (structs.DebitAuthorization){
|
||||||
option (auth_type) = "User";
|
option (auth_type) = "User";
|
||||||
option (http_method) = "post";
|
option (http_method) = "post";
|
||||||
option (http_route) = "/api/user/debit/authorize";
|
option (http_route) = "/api/user/debit/authorize";
|
||||||
option (nostr) = true;
|
option (nostr) = true;
|
||||||
}
|
}
|
||||||
|
rpc AuthorizeManage(structs.ManageAuthorizationRequest) returns (structs.ManageAuthorization){
|
||||||
|
option (auth_type) = "User";
|
||||||
|
option (http_method) = "post";
|
||||||
|
option (http_route) = "/api/user/manage/authorize";
|
||||||
|
option (nostr) = true;
|
||||||
|
}
|
||||||
rpc EditDebit(structs.DebitAuthorizationRequest) returns (structs.Empty){
|
rpc EditDebit(structs.DebitAuthorizationRequest) returns (structs.Empty){
|
||||||
option (auth_type) = "User";
|
option (auth_type) = "User";
|
||||||
option (http_method) = "post";
|
option (http_method) = "post";
|
||||||
|
|
@ -628,6 +640,14 @@ service LightningPub {
|
||||||
option (http_route) = "/api/user/debit/sub";
|
option (http_route) = "/api/user/debit/sub";
|
||||||
option (nostr) = true;
|
option (nostr) = true;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
rpc GetLiveManageRequests(structs.Empty) returns (stream structs.LiveManageRequest){
|
||||||
|
option (auth_type) = "User";
|
||||||
|
option (http_method) = "post";
|
||||||
|
option (http_route) = "/api/user/manage/sub";
|
||||||
|
option (nostr) = true;
|
||||||
|
}
|
||||||
|
|
||||||
rpc GetLiveUserOperations(structs.Empty) returns (stream structs.LiveUserOperation){
|
rpc GetLiveUserOperations(structs.Empty) returns (stream structs.LiveUserOperation){
|
||||||
option (auth_type) = "User";
|
option (auth_type) = "User";
|
||||||
option (http_method) = "post";
|
option (http_method) = "post";
|
||||||
|
|
|
||||||
|
|
@ -674,6 +674,22 @@ message DebitAuthorizationRequest {
|
||||||
optional string request_id = 3;
|
optional string request_id = 3;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
message ManageAuthorizationRequest {
|
||||||
|
string authorize_npub = 1;
|
||||||
|
optional string request_id = 2;
|
||||||
|
bool ban = 3;
|
||||||
|
}
|
||||||
|
|
||||||
|
message ManageAuthorization {
|
||||||
|
string manage_id = 1;
|
||||||
|
bool authorized = 2;
|
||||||
|
string npub = 3;
|
||||||
|
}
|
||||||
|
|
||||||
|
message ManageAuthorizations {
|
||||||
|
repeated ManageAuthorization manages = 1;
|
||||||
|
}
|
||||||
|
|
||||||
message DebitAuthorization {
|
message DebitAuthorization {
|
||||||
string debit_id = 1;
|
string debit_id = 1;
|
||||||
bool authorized = 2;
|
bool authorized = 2;
|
||||||
|
|
@ -718,6 +734,11 @@ message LiveDebitRequest {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
message LiveManageRequest {
|
||||||
|
string request_id = 1;
|
||||||
|
string npub = 2;
|
||||||
|
}
|
||||||
|
|
||||||
message DebitResponse {
|
message DebitResponse {
|
||||||
string request_id = 1;
|
string request_id = 1;
|
||||||
string npub = 2;
|
string npub = 2;
|
||||||
|
|
|
||||||
|
|
@ -7,14 +7,15 @@ import Storage from "../storage/index.js";
|
||||||
import { OfferManager } from "./offerManager.js";
|
import { OfferManager } from "./offerManager.js";
|
||||||
import * as Types from "../../../proto/autogenerated/ts/types.js";
|
import * as Types from "../../../proto/autogenerated/ts/types.js";
|
||||||
import { MainSettings } from "./settings.js";
|
import { MainSettings } from "./settings.js";
|
||||||
import { nofferEncode, OfferPointer, OfferPriceType, NmanageRequest, NmanageResponse, NmanageCreateOffer, NmanageUpdateOffer, NmanageDeleteOffer, NmanageGetOffer, NmanageListOffers, OfferData, OfferFields } from "@shocknet/clink-sdk";
|
import { nofferEncode, OfferPointer, OfferPriceType, NmanageRequest, NmanageResponse, NmanageCreateOffer, NmanageUpdateOffer, NmanageDeleteOffer, NmanageGetOffer, NmanageListOffers, OfferData, OfferFields, NmanageFailure } from "@shocknet/clink-sdk";
|
||||||
import { UnsignedEvent } from "nostr-tools";
|
import { UnsignedEvent } from "nostr-tools";
|
||||||
type Result<T> = { success: true, result: T } | { success: false, error: string, code: number }
|
type Result<T> = { state: 'success', result: T } | { state: 'error', err: NmanageFailure } | { state: 'authRequired' }
|
||||||
|
|
||||||
export class ManagementManager {
|
export class ManagementManager {
|
||||||
private nostrSend: NostrSend;
|
private nostrSend: NostrSend;
|
||||||
private storage: Storage;
|
private storage: Storage;
|
||||||
private settings: MainSettings;
|
private settings: MainSettings;
|
||||||
|
private awaitingRequests: Record<string, { request: NmanageRequest, event: NostrEvent }> = {}
|
||||||
|
|
||||||
constructor(storage: Storage, settings: MainSettings) {
|
constructor(storage: Storage, settings: MainSettings) {
|
||||||
this.storage = storage;
|
this.storage = storage;
|
||||||
|
|
@ -25,19 +26,62 @@ export class ManagementManager {
|
||||||
this.nostrSend = f
|
this.nostrSend = f
|
||||||
}
|
}
|
||||||
|
|
||||||
public async handleRequest(nmanageReq: NmanageRequest, event: NostrEvent): Promise<void> {
|
AuthorizeManage = async (ctx: Types.UserContext, req: Types.ManageAuthorizationRequest): Promise<Types.ManageAuthorization> => {
|
||||||
|
const grant = await this.storage.managementStorage.addGrant(ctx.app_user_id, req.authorize_npub, req.ban)
|
||||||
|
return {
|
||||||
|
manage_id: grant.serial_id.toString(),
|
||||||
|
authorized: !grant.banned,
|
||||||
|
npub: grant.app_pubkey,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
GetManageAuthorizations = async (ctx: Types.UserContext): Promise<Types.ManageAuthorizations> => {
|
||||||
|
const grants = await this.storage.managementStorage.getGrants(ctx.app_user_id)
|
||||||
|
return {
|
||||||
|
manages: grants.map(grant => ({
|
||||||
|
manage_id: grant.serial_id.toString(),
|
||||||
|
authorized: !grant.banned,
|
||||||
|
npub: grant.app_pubkey,
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private sendManageAuthorizationRequest = (appId: string, { requestId, npub }: { requestId: string, npub: string }) => {
|
||||||
|
const message: Types.LiveManageRequest & { requestId: string, status: 'OK' } = { requestId: "GetLiveManageRequests", status: 'OK', npub: npub, request_id: requestId }
|
||||||
|
this.nostrSend({ type: 'app', appId: appId }, { type: 'content', content: JSON.stringify(message), pub: npub })
|
||||||
|
}
|
||||||
|
|
||||||
|
private sendError(event: NostrEvent, err: NmanageFailure) {
|
||||||
|
const e = newNmanageResponse(JSON.stringify(err), event)
|
||||||
|
this.nostrSend({ type: 'app', appId: event.appId }, { type: 'event', event: e, encrypt: { toPub: event.pub } })
|
||||||
|
}
|
||||||
|
|
||||||
|
private handleAuthRequired(nmanageReq: NmanageRequest, event: NostrEvent) {
|
||||||
|
if (this.awaitingRequests[event.pub]) {
|
||||||
|
this.sendError(event, { res: 'GFY', code: 4, error: 'Rate Limited', retry_after: 60 * 10 })
|
||||||
|
return
|
||||||
|
}
|
||||||
|
this.awaitingRequests[event.pub] = { request: nmanageReq, event }
|
||||||
|
this.sendManageAuthorizationRequest(event.appId, { requestId: event.id, npub: event.pub })
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
async handleRequest(nmanageReq: NmanageRequest, event: NostrEvent): Promise<void> {
|
||||||
try {
|
try {
|
||||||
const r = await this.doNmanage(nmanageReq, event)
|
const r = await this.doNmanage(nmanageReq, event)
|
||||||
let e: UnsignedEvent
|
if (r.state === 'authRequired') {
|
||||||
if (!r.success) {
|
this.handleAuthRequired(nmanageReq, event)
|
||||||
e = newNmanageResponse(JSON.stringify({ code: r.code, error: codeToMessage(r.code) }), event)
|
return
|
||||||
} else {
|
|
||||||
e = newNmanageResponse(JSON.stringify(r.result), event)
|
|
||||||
}
|
}
|
||||||
|
if (r.state === 'error') {
|
||||||
|
this.sendError(event, r.err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
const e = newNmanageResponse(JSON.stringify(r.result), event)
|
||||||
this.nostrSend({ type: 'app', appId: event.appId }, { type: 'event', event: e, encrypt: { toPub: event.pub } })
|
this.nostrSend({ type: 'app', appId: event.appId }, { type: 'event', event: e, encrypt: { toPub: event.pub } })
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
const e = newNmanageResponse(JSON.stringify({ code: 2, error: codeToMessage(2) }), event)
|
this.sendError(event, { res: 'GFY', code: 2, error: 'Temporary Failure' })
|
||||||
this.nostrSend({ type: 'app', appId: event.appId }, { type: 'event', event: e, encrypt: { toPub: event.pub } })
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -60,7 +104,7 @@ export class ManagementManager {
|
||||||
const listResult = await this.listOffers(nmanageReq, event.pub);
|
const listResult = await this.listOffers(nmanageReq, event.pub);
|
||||||
return this.getNmanageResponse(event.appId, listResult)
|
return this.getNmanageResponse(event.appId, listResult)
|
||||||
default:
|
default:
|
||||||
return { success: false, error: `Unknown action: ${action}`, code: 1 }
|
return { state: 'error', err: { res: 'GFY', code: 1, error: `Request Denied: Unknown action: ${action}` } }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -83,23 +127,23 @@ export class ManagementManager {
|
||||||
}
|
}
|
||||||
|
|
||||||
private async getNmanageResponse(appId: string, result: Result<UserOffer | UserOffer[] | void>): Promise<Result<NmanageResponse>> {
|
private async getNmanageResponse(appId: string, result: Result<UserOffer | UserOffer[] | void>): Promise<Result<NmanageResponse>> {
|
||||||
if (!result.success) {
|
if (result.state !== 'success') {
|
||||||
return result
|
return result
|
||||||
}
|
}
|
||||||
const args = result.result
|
const args = result.result
|
||||||
const app = await this.storage.applicationStorage.GetApplication(appId)
|
const app = await this.storage.applicationStorage.GetApplication(appId)
|
||||||
if (args && Array.isArray(args)) {
|
if (args && Array.isArray(args)) {
|
||||||
return {
|
return {
|
||||||
success: true, result: {
|
state: 'success', result: {
|
||||||
res: 'ok', resource: 'offer', details: args.map(offer => this.getOfferData(offer, app.nostr_public_key!))
|
res: 'ok', resource: 'offer', details: args.map(offer => this.getOfferData(offer, app.nostr_public_key!))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (!args) {
|
if (!args) {
|
||||||
return { success: true, result: { res: 'ok', resource: 'offer' } }
|
return { state: 'success', result: { res: 'ok', resource: 'offer' } }
|
||||||
}
|
}
|
||||||
return {
|
return {
|
||||||
success: true, result: {
|
state: 'success', result: {
|
||||||
res: 'ok', resource: 'offer', details: this.getOfferData(args, app.nostr_public_key!)
|
res: 'ok', resource: 'offer', details: this.getOfferData(args, app.nostr_public_key!)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
@ -107,53 +151,53 @@ export class ManagementManager {
|
||||||
|
|
||||||
private async getOffer(nmanageReq: NmanageGetOffer, requestorPub: string): Promise<Result<UserOffer>> {
|
private async getOffer(nmanageReq: NmanageGetOffer, requestorPub: string): Promise<Result<UserOffer>> {
|
||||||
const offer = await this.validateOfferAccess(nmanageReq.offer.id, requestorPub)
|
const offer = await this.validateOfferAccess(nmanageReq.offer.id, requestorPub)
|
||||||
if (!offer.success) {
|
if (offer.state !== 'success') {
|
||||||
return offer
|
return offer
|
||||||
}
|
}
|
||||||
return { success: true, result: offer.result }
|
return { state: 'success', result: offer.result }
|
||||||
}
|
}
|
||||||
|
|
||||||
private async listOffers(nmanageReq: NmanageListOffers, requestorPub: string): Promise<Result<UserOffer[]>> {
|
private async listOffers(nmanageReq: NmanageListOffers, requestorPub: string): Promise<Result<UserOffer[]>> {
|
||||||
const appUserId = nmanageReq.pointer
|
const appUserId = nmanageReq.pointer
|
||||||
if (!appUserId) {
|
if (!appUserId) {
|
||||||
return { success: false, error: 'No pointer provided', code: 1 }
|
return { state: 'error', err: { res: 'GFY', code: 1, error: 'Request Denied: No pointer provided' } }
|
||||||
}
|
}
|
||||||
const grantResult = await this.validateGrantAccess(appUserId, requestorPub)
|
const grantResult = await this.validateGrantAccess(appUserId, requestorPub)
|
||||||
if (!grantResult.success) {
|
if (grantResult.state !== 'success') {
|
||||||
return grantResult
|
return grantResult
|
||||||
}
|
}
|
||||||
const offers = await this.storage.offerStorage.getManagedUserOffers(appUserId, requestorPub)
|
const offers = await this.storage.offerStorage.getManagedUserOffers(appUserId, requestorPub)
|
||||||
return { success: true, result: offers }
|
return { state: 'success', result: offers }
|
||||||
}
|
}
|
||||||
|
|
||||||
private validateOfferFields(fields: OfferFields): Result<void> {
|
private validateOfferFields(fields: OfferFields): Result<void> {
|
||||||
if (!fields.label || typeof fields.label !== 'string') {
|
if (!fields.label || typeof fields.label !== 'string') {
|
||||||
return { success: false, error: 'Label is required', code: 1 }
|
return { state: 'error', err: { res: 'GFY', code: 5, error: 'Invalid Field/Value', field: 'label' } }
|
||||||
}
|
}
|
||||||
if (fields.price_sats && typeof fields.price_sats !== 'number') {
|
if (fields.price_sats && typeof fields.price_sats !== 'number') {
|
||||||
return { success: false, error: 'Price must be a number', code: 1 }
|
return { state: 'error', err: { res: 'GFY', code: 5, error: 'Invalid Field/Value', field: 'price_sats' } }
|
||||||
}
|
}
|
||||||
if (fields.callback_url && typeof fields.callback_url !== 'string') {
|
if (fields.callback_url && typeof fields.callback_url !== 'string') {
|
||||||
return { success: false, error: 'Callback URL must be a string', code: 1 }
|
return { state: 'error', err: { res: 'GFY', code: 5, error: 'Invalid Field/Value', field: 'callback_url' } }
|
||||||
}
|
}
|
||||||
if (fields.payer_data && !Array.isArray(fields.payer_data)) {
|
if (fields.payer_data && !Array.isArray(fields.payer_data)) {
|
||||||
return { success: false, error: 'Payer data must be an array', code: 1 }
|
return { state: 'error', err: { res: 'GFY', code: 5, error: 'Invalid Field/Value', field: 'payer_data' } }
|
||||||
}
|
}
|
||||||
|
|
||||||
return { success: true, result: undefined }
|
return { state: 'success', result: undefined }
|
||||||
}
|
}
|
||||||
|
|
||||||
private async createOffer(nmanageReq: NmanageCreateOffer): Promise<Result<UserOffer>> {
|
private async createOffer(nmanageReq: NmanageCreateOffer): Promise<Result<UserOffer>> {
|
||||||
const appUserId = nmanageReq.pointer
|
const appUserId = nmanageReq.pointer
|
||||||
if (!appUserId) {
|
if (!appUserId) {
|
||||||
return { success: false, error: 'No pointer provided', code: 1 }
|
return { state: 'error', err: { res: 'GFY', code: 1, error: 'Request Denied: No pointer provided' } }
|
||||||
}
|
}
|
||||||
const grantResult = await this.validateGrantAccess(appUserId, appUserId)
|
const grantResult = await this.validateGrantAccess(appUserId, appUserId)
|
||||||
if (!grantResult.success) {
|
if (grantResult.state !== 'success') {
|
||||||
return grantResult
|
return grantResult
|
||||||
}
|
}
|
||||||
const validateResult = this.validateOfferFields(nmanageReq.offer.fields)
|
const validateResult = this.validateOfferFields(nmanageReq.offer.fields)
|
||||||
if (!validateResult.success) {
|
if (validateResult.state !== 'success') {
|
||||||
return validateResult
|
return validateResult
|
||||||
}
|
}
|
||||||
const dataMap: Record<string, Types.OfferDataType> = {}
|
const dataMap: Record<string, Types.OfferDataType> = {}
|
||||||
|
|
@ -166,51 +210,56 @@ export class ManagementManager {
|
||||||
price_sats: nmanageReq.offer.fields.price_sats,
|
price_sats: nmanageReq.offer.fields.price_sats,
|
||||||
expected_data: dataMap,
|
expected_data: dataMap,
|
||||||
})
|
})
|
||||||
return { success: true, result: offer }
|
return { state: 'success', result: offer }
|
||||||
}
|
}
|
||||||
|
|
||||||
private async validateGrantAccess(appUserId: string, requestorPub: string): Promise<Result<void>> {
|
private async validateGrantAccess(appUserId: string, requestorPub: string): Promise<Result<void>> {
|
||||||
const grant = await this.storage.managementStorage.getGrant(appUserId, requestorPub)
|
const grant = await this.storage.managementStorage.getGrant(appUserId, requestorPub)
|
||||||
|
|
||||||
if (!grant) {
|
if (!grant) {
|
||||||
// TODO request from user
|
return { state: 'authRequired' }
|
||||||
return { success: false, error: 'No grant found', code: 1 }
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if (grant.expires_at_unix < Date.now()) {
|
if (grant.expires_at_unix > 0 && grant.expires_at_unix < Date.now()) {
|
||||||
return { success: false, error: 'Grant expired', code: 3 }
|
return { state: 'authRequired' }
|
||||||
}
|
}
|
||||||
return { success: true, result: undefined }
|
|
||||||
|
if (grant.banned) {
|
||||||
|
return { state: 'error', err: { res: 'GFY', code: 1, error: 'Request Denied: App is banned' } }
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
return { state: 'success', result: undefined }
|
||||||
}
|
}
|
||||||
|
|
||||||
private async validateOfferAccess(offerId: string, requestorPub: string): Promise<Result<UserOffer>> {
|
private async validateOfferAccess(offerId: string, requestorPub: string): Promise<Result<UserOffer>> {
|
||||||
const offer = await this.storage.offerStorage.GetOffer(offerId)
|
const offer = await this.storage.offerStorage.GetOffer(offerId)
|
||||||
if (!offer) {
|
if (!offer) {
|
||||||
return { success: false, error: 'Offer not found', code: 1 }
|
return { state: 'error', err: { res: 'GFY', code: 1, error: 'Request Denied: Offer not found' } }
|
||||||
}
|
}
|
||||||
if (offer.management_pubkey !== requestorPub) {
|
if (offer.management_pubkey !== requestorPub) {
|
||||||
return { success: false, error: 'App not authorized to update offer', code: 1 }
|
return { state: 'error', err: { res: 'GFY', code: 1, error: 'Request Denied: App not authorized to update offer' } }
|
||||||
}
|
}
|
||||||
const grantResult = await this.validateGrantAccess(offer.app_user_id, requestorPub)
|
const grantResult = await this.validateGrantAccess(offer.app_user_id, requestorPub)
|
||||||
if (!grantResult.success) {
|
if (grantResult.state !== 'success') {
|
||||||
return grantResult
|
return grantResult
|
||||||
}
|
}
|
||||||
return { success: true, result: offer }
|
return { state: 'success', result: offer }
|
||||||
}
|
}
|
||||||
|
|
||||||
private async updateOffer(nmanageReq: NmanageUpdateOffer, requestorPub: string): Promise<Result<UserOffer>> {
|
private async updateOffer(nmanageReq: NmanageUpdateOffer, requestorPub: string): Promise<Result<UserOffer>> {
|
||||||
const offer = await this.validateOfferAccess(nmanageReq.offer.id, requestorPub)
|
const offer = await this.validateOfferAccess(nmanageReq.offer.id, requestorPub)
|
||||||
if (!offer.success) {
|
if (offer.state !== 'success') {
|
||||||
return offer
|
return offer
|
||||||
}
|
}
|
||||||
const validateResult = this.validateOfferFields(nmanageReq.offer.fields)
|
const validateResult = this.validateOfferFields(nmanageReq.offer.fields)
|
||||||
if (!validateResult.success) {
|
if (validateResult.state !== 'success') {
|
||||||
return validateResult
|
return validateResult
|
||||||
}
|
}
|
||||||
const dataMap: Record<string, Types.OfferDataType> = {}
|
const dataMap: Record<string, Types.OfferDataType> = {}
|
||||||
for (const data of nmanageReq.offer.fields.payer_data || []) {
|
for (const data of nmanageReq.offer.fields.payer_data || []) {
|
||||||
if (typeof data !== 'string') {
|
if (typeof data !== 'string') {
|
||||||
return { success: false, error: 'Payer data must be a string', code: 1 }
|
return { state: 'error', err: { res: 'GFY', code: 5, error: 'Invalid Field/Value', field: 'payer_data' } }
|
||||||
}
|
}
|
||||||
dataMap[data] = Types.OfferDataType.DATA_STRING
|
dataMap[data] = Types.OfferDataType.DATA_STRING
|
||||||
}
|
}
|
||||||
|
|
@ -222,18 +271,18 @@ export class ManagementManager {
|
||||||
})
|
})
|
||||||
const updatedOffer = await this.storage.offerStorage.GetOffer(nmanageReq.offer.id)
|
const updatedOffer = await this.storage.offerStorage.GetOffer(nmanageReq.offer.id)
|
||||||
if (!updatedOffer) {
|
if (!updatedOffer) {
|
||||||
return { success: false, error: 'Offer not found', code: 2 }
|
return { state: 'error', err: { res: 'GFY', code: 2, error: 'Temporary Failure: Offer not found' } }
|
||||||
}
|
}
|
||||||
return { success: true, result: updatedOffer }
|
return { state: 'success', result: updatedOffer }
|
||||||
}
|
}
|
||||||
|
|
||||||
private async deleteOffer(nmanageReq: NmanageDeleteOffer, requestorPub: string): Promise<Result<void>> {
|
private async deleteOffer(nmanageReq: NmanageDeleteOffer, requestorPub: string): Promise<Result<void>> {
|
||||||
const offerResult = await this.validateOfferAccess(nmanageReq.offer.id, requestorPub)
|
const offerResult = await this.validateOfferAccess(nmanageReq.offer.id, requestorPub)
|
||||||
if (!offerResult.success) {
|
if (offerResult.state !== 'success') {
|
||||||
return offerResult
|
return offerResult
|
||||||
}
|
}
|
||||||
await this.storage.offerStorage.DeleteUserOffer(offerResult.result.app_user_id, offerResult.result.offer_id)
|
await this.storage.offerStorage.DeleteUserOffer(offerResult.result.app_user_id, offerResult.result.offer_id)
|
||||||
return { success: true, result: undefined }
|
return { state: 'success', result: undefined }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -289,6 +289,7 @@ export default (mainHandler: Main): Types.ServerMethods => {
|
||||||
await mainHandler.applicationManager.SetMockAppBalance(ctx.app_id, req)
|
await mainHandler.applicationManager.SetMockAppBalance(ctx.app_id, req)
|
||||||
},
|
},
|
||||||
GetLiveDebitRequests: async ({ ctx }) => { },
|
GetLiveDebitRequests: async ({ ctx }) => { },
|
||||||
|
GetLiveManageRequests: async ({ ctx }) => { },
|
||||||
GetLiveUserOperations: async ({ ctx, cb }) => {
|
GetLiveUserOperations: async ({ ctx, cb }) => {
|
||||||
},
|
},
|
||||||
GetMigrationUpdate: async ({ ctx, cb }) => {
|
GetMigrationUpdate: async ({ ctx, cb }) => {
|
||||||
|
|
@ -355,6 +356,12 @@ export default (mainHandler: Main): Types.ServerMethods => {
|
||||||
GetDebitAuthorizations: async ({ ctx }) => {
|
GetDebitAuthorizations: async ({ ctx }) => {
|
||||||
return mainHandler.debitManager.GetDebitAuthorizations(ctx)
|
return mainHandler.debitManager.GetDebitAuthorizations(ctx)
|
||||||
},
|
},
|
||||||
|
AuthorizeManage: async ({ ctx, req }) => {
|
||||||
|
return mainHandler.managementManager.AuthorizeManage(ctx, req)
|
||||||
|
},
|
||||||
|
GetManageAuthorizations: async ({ ctx }) => {
|
||||||
|
return mainHandler.managementManager.GetManageAuthorizations(ctx)
|
||||||
|
},
|
||||||
BanDebit: async ({ ctx, req }) => {
|
BanDebit: async ({ ctx, req }) => {
|
||||||
const err = Types.DebitOperationValidate(req, {
|
const err = Types.DebitOperationValidate(req, {
|
||||||
npub_CustomCheck: pub => pub !== '',
|
npub_CustomCheck: pub => pub !== '',
|
||||||
|
|
|
||||||
|
|
@ -15,6 +15,9 @@ export class ManagementGrant {
|
||||||
@Column()
|
@Column()
|
||||||
expires_at_unix: number
|
expires_at_unix: number
|
||||||
|
|
||||||
|
@Column()
|
||||||
|
banned: boolean
|
||||||
|
|
||||||
@CreateDateColumn()
|
@CreateDateColumn()
|
||||||
created_at: Date
|
created_at: Date
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -11,7 +11,11 @@ export class ManagementStorage {
|
||||||
return this.dbs.FindOne<ManagementGrant>('ManagementGrant', { where: { app_pubkey: appPubkey, app_user_id: appUserId } });
|
return this.dbs.FindOne<ManagementGrant>('ManagementGrant', { where: { app_pubkey: appPubkey, app_user_id: appUserId } });
|
||||||
}
|
}
|
||||||
|
|
||||||
async addGrant(appUserId: string, appPubkey: string, expires_at_unix: number) {
|
async addGrant(appUserId: string, appPubkey: string, banned: boolean, expires_at_unix = 0) {
|
||||||
return this.dbs.CreateAndSave<ManagementGrant>('ManagementGrant', { app_user_id: appUserId, app_pubkey: appPubkey, expires_at_unix });
|
return this.dbs.CreateAndSave<ManagementGrant>('ManagementGrant', { app_user_id: appUserId, app_pubkey: appPubkey, banned, expires_at_unix });
|
||||||
|
}
|
||||||
|
|
||||||
|
async getGrants(appUserId: string) {
|
||||||
|
return this.dbs.Find<ManagementGrant>('ManagementGrant', { where: { app_user_id: appUserId } });
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
@ -0,0 +1,20 @@
|
||||||
|
import { MigrationInterface, QueryRunner } from "typeorm";
|
||||||
|
|
||||||
|
export class ManagementGrantBanned1751989251513 implements MigrationInterface {
|
||||||
|
name = 'ManagementGrantBanned1751989251513'
|
||||||
|
|
||||||
|
public async up(queryRunner: QueryRunner): Promise<void> {
|
||||||
|
await queryRunner.query(`CREATE TABLE "temporary_management_grant" ("serial_id" integer PRIMARY KEY AUTOINCREMENT NOT NULL, "app_user_id" varchar NOT NULL, "app_pubkey" varchar NOT NULL, "expires_at_unix" integer NOT NULL, "created_at" datetime NOT NULL DEFAULT (datetime('now')), "updated_at" datetime NOT NULL DEFAULT (datetime('now')), "banned" boolean NOT NULL)`);
|
||||||
|
await queryRunner.query(`INSERT INTO "temporary_management_grant"("serial_id", "app_user_id", "app_pubkey", "expires_at_unix", "created_at", "updated_at") SELECT "serial_id", "app_user_id", "app_pubkey", "expires_at_unix", "created_at", "updated_at" FROM "management_grant"`);
|
||||||
|
await queryRunner.query(`DROP TABLE "management_grant"`);
|
||||||
|
await queryRunner.query(`ALTER TABLE "temporary_management_grant" RENAME TO "management_grant"`);
|
||||||
|
}
|
||||||
|
|
||||||
|
public async down(queryRunner: QueryRunner): Promise<void> {
|
||||||
|
await queryRunner.query(`ALTER TABLE "management_grant" RENAME TO "temporary_management_grant"`);
|
||||||
|
await queryRunner.query(`CREATE TABLE "management_grant" ("serial_id" integer PRIMARY KEY AUTOINCREMENT NOT NULL, "app_user_id" varchar NOT NULL, "app_pubkey" varchar NOT NULL, "expires_at_unix" integer NOT NULL, "created_at" datetime NOT NULL DEFAULT (datetime('now')), "updated_at" datetime NOT NULL DEFAULT (datetime('now')))`);
|
||||||
|
await queryRunner.query(`INSERT INTO "management_grant"("serial_id", "app_user_id", "app_pubkey", "expires_at_unix", "created_at", "updated_at") SELECT "serial_id", "app_user_id", "app_pubkey", "expires_at_unix", "created_at", "updated_at" FROM "temporary_management_grant"`);
|
||||||
|
await queryRunner.query(`DROP TABLE "temporary_management_grant"`);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
Loading…
Add table
Add a link
Reference in a new issue