diff --git a/datasource.js b/datasource.js index 8b250b72..c2b68147 100644 --- a/datasource.js +++ b/datasource.js @@ -17,6 +17,7 @@ import { TrackedProvider } from "./build/src/services/storage/entity/TrackedProv import { InviteToken } from "./build/src/services/storage/entity/InviteToken.js" import { DebitAccess } from "./build/src/services/storage/entity/DebitAccess.js" import { UserOffer } from "./build/src/services/storage/entity/UserOffer.js" +import { ManagementGrant } from "./build/src/services/storage/entity/ManagementGrant.js" import { Initial1703170309875 } from './build/src/services/storage/migrations/1703170309875-initial.js' import { LspOrder1718387847693 } from './build/src/services/storage/migrations/1718387847693-lsp_order.js' @@ -29,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 { 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 { ManagementGrant1751307732346 } from './build/src/services/storage/migrations/1751307732346-management_grant.js' export default new DataSource({ type: "sqlite", database: "db.sqlite", // 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, - UserBasicAuth, UserEphemeralKey, Product, UserToUserPayment, Application, ApplicationUser, UserToUserPayment, LspOrder, LndNodeInfo, TrackedProvider, InviteToken, DebitAccess, UserOffer], + UserBasicAuth, UserEphemeralKey, Product, UserToUserPayment, Application, ApplicationUser, UserToUserPayment, LspOrder, LndNodeInfo, TrackedProvider, InviteToken, DebitAccess, UserOffer, ManagementGrant], // synchronize: true, }) -//npx typeorm migration:generate ./src/services/storage/migrations/ops_time -d ./datasource.js \ No newline at end of file +//npx typeorm migration:generate ./src/services/storage/migrations/management_grant_banned -d ./datasource.js \ No newline at end of file diff --git a/package-lock.json b/package-lock.json index 6042c818..1c9a2b8d 100644 --- a/package-lock.json +++ b/package-lock.json @@ -13,7 +13,7 @@ "@protobuf-ts/grpc-transport": "^2.9.4", "@protobuf-ts/plugin": "^2.5.0", "@protobuf-ts/runtime": "^2.5.0", - "@shocknet/clink-sdk": "^1.0.4", + "@shocknet/clink-sdk": "^1.1.7", "@stablelib/xchacha20": "^1.0.1", "@types/express": "^4.17.21", "@types/node": "^17.0.31", @@ -591,9 +591,9 @@ } }, "node_modules/@shocknet/clink-sdk": { - "version": "1.0.4", - "resolved": "https://registry.npmjs.org/@shocknet/clink-sdk/-/clink-sdk-1.0.4.tgz", - "integrity": "sha512-ekkfJpP+YPry4/5+V+3JPx9zOVEjCDOWW7AHzfOLyVGnLuIR6jEBjDkg7avM2f3BVvFKSl4l0mkS9ImK9lX0eQ==", + "version": "1.1.7", + "resolved": "https://registry.npmjs.org/@shocknet/clink-sdk/-/clink-sdk-1.1.7.tgz", + "integrity": "sha512-9qr2WWalrPyi9ZoIsA2oEeQM3fWMCrVarghIStvkd/HoIR7oFjuHl+OUMLwvPxWXuCRIqnyRmXu970JVO8fx7Q==", "license": "ISC", "dependencies": { "@noble/hashes": "^1.8.0", diff --git a/package.json b/package.json index 36412acd..3ded2084 100644 --- a/package.json +++ b/package.json @@ -31,7 +31,7 @@ "@protobuf-ts/grpc-transport": "^2.9.4", "@protobuf-ts/plugin": "^2.5.0", "@protobuf-ts/runtime": "^2.5.0", - "@shocknet/clink-sdk": "^1.0.4", + "@shocknet/clink-sdk": "^1.1.7", "@stablelib/xchacha20": "^1.0.1", "@types/express": "^4.17.21", "@types/node": "^17.0.31", diff --git a/proto/autogenerated/client.md b/proto/autogenerated/client.md index 16aef4db..0f871cd6 100644 --- a/proto/autogenerated/client.md +++ b/proto/autogenerated/client.md @@ -43,6 +43,11 @@ The nostr server will send back a message response, and inside the body there wi - input: [DebitAuthorizationRequest](#DebitAuthorizationRequest) - output: [DebitAuthorization](#DebitAuthorization) +- AuthorizeManage + - auth type: __User__ + - input: [ManageAuthorizationRequest](#ManageAuthorizationRequest) + - output: [ManageAuthorization](#ManageAuthorization) + - BanDebit - auth type: __User__ - 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 - output: [LiveDebitRequest](#LiveDebitRequest) +- GetLiveManageRequests + - auth type: __User__ + - This methods has an __empty__ __request__ body + - output: [LiveManageRequest](#LiveManageRequest) + - GetLiveUserOperations - auth type: __User__ - 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 - output: [LnurlLinkResponse](#LnurlLinkResponse) +- GetManageAuthorizations + - auth type: __User__ + - This methods has an __empty__ __request__ body + - output: [ManageAuthorizations](#ManageAuthorizations) + - GetMigrationUpdate - auth type: __User__ - This methods has an __empty__ __request__ body @@ -270,6 +285,11 @@ The nostr server will send back a message response, and inside the body there wi - input: [DebitOperation](#DebitOperation) - This methods has an __empty__ __response__ body +- ResetManage + - auth type: __User__ + - input: [ManageOperation](#ManageOperation) + - This methods has an __empty__ __response__ body + - ResetMetricsStorages - auth type: __Metrics__ - This methods has an __empty__ __request__ body @@ -418,6 +438,13 @@ The nostr server will send back a message response, and inside the body there wi - input: [DebitAuthorizationRequest](#DebitAuthorizationRequest) - output: [DebitAuthorization](#DebitAuthorization) +- AuthorizeManage + - auth type: __User__ + - http method: __post__ + - http route: __/api/user/manage/authorize__ + - input: [ManageAuthorizationRequest](#ManageAuthorizationRequest) + - output: [ManageAuthorization](#ManageAuthorization) + - BanDebit - auth type: __User__ - http method: __post__ @@ -565,6 +592,13 @@ The nostr server will send back a message response, and inside the body there wi - This methods has an __empty__ __request__ body - 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 - auth type: __User__ - http method: __post__ @@ -618,6 +652,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) +- GetManageAuthorizations + - auth type: __User__ + - http method: __get__ + - http route: __/api/user/manage/get__ + - This methods has an __empty__ __request__ body + - output: [ManageAuthorizations](#ManageAuthorizations) + - GetMigrationUpdate - auth type: __User__ - http method: __post__ @@ -840,6 +881,13 @@ The nostr server will send back a message response, and inside the body there wi - input: [DebitOperation](#DebitOperation) - This methods has an __empty__ __response__ body +- ResetManage + - auth type: __User__ + - http method: __post__ + - http route: __/api/user/manage/reset__ + - input: [ManageOperation](#ManageOperation) + - This methods has an __empty__ __response__ body + - ResetMetricsStorages - auth type: __Metrics__ - http method: __post__ @@ -1216,6 +1264,10 @@ The nostr server will send back a message response, and inside the body there wi - __npub__: _string_ - __request_id__: _string_ +### LiveManageRequest + - __npub__: _string_ + - __request_id__: _string_ + ### LiveUserOperation - __operation__: _[UserOperation](#UserOperation)_ @@ -1290,6 +1342,22 @@ The nostr server will send back a message response, and inside the body there wi - __payLink__: _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)_ + +### ManageOperation + - __npub__: _string_ + ### MetricsFile ### MigrationUpdate @@ -1504,6 +1572,7 @@ The nostr server will send back a message response, and inside the body there wi - __ndebit__: _string_ - __network_max_fee_bps__: _number_ - __network_max_fee_fixed__: _number_ + - __nmanage__: _string_ - __noffer__: _string_ - __service_fee_bps__: _number_ - __userId__: _string_ diff --git a/proto/autogenerated/go/http_client.go b/proto/autogenerated/go/http_client.go index bd9a32f0..7e64e7c8 100644 --- a/proto/autogenerated/go/http_client.go +++ b/proto/autogenerated/go/http_client.go @@ -63,6 +63,7 @@ type Client struct { AddUserOffer func(req OfferConfig) (*OfferId, error) AuthApp func(req AuthAppRequest) (*AuthApp, error) AuthorizeDebit func(req DebitAuthorizationRequest) (*DebitAuthorization, error) + AuthorizeManage func(req ManageAuthorizationRequest) (*ManageAuthorization, error) BanDebit func(req DebitOperation) error BanUser func(req BanUserRequest) (*BanUserResponse, error) // batching method: BatchUser not implemented @@ -84,6 +85,7 @@ type Client struct { GetInviteLinkState func(req GetInviteTokenStateRequest) (*GetInviteTokenStateResponse, error) GetLNURLChannelLink func() (*LnurlLinkResponse, error) GetLiveDebitRequests func() (*LiveDebitRequest, error) + GetLiveManageRequests func() (*LiveManageRequest, error) GetLiveUserOperations func() (*LiveUserOperation, error) GetLndForwardingMetrics func(req LndMetricsRequest) (*LndForwardingMetrics, error) GetLndMetrics func(req LndMetricsRequest) (*LndMetrics, error) @@ -91,6 +93,7 @@ type Client struct { GetLnurlPayLink func() (*LnurlLinkResponse, error) GetLnurlWithdrawInfo func(query GetLnurlWithdrawInfo_Query) (*LnurlWithdrawInfoResponse, error) GetLnurlWithdrawLink func() (*LnurlLinkResponse, error) + GetManageAuthorizations func() (*ManageAuthorizations, error) GetMigrationUpdate func() (*MigrationUpdate, error) GetNPubLinkingState func(req GetNPubLinking) (*NPubLinking, error) GetPaymentState func(req GetPaymentStateRequest) (*PaymentState, error) @@ -121,6 +124,7 @@ type Client struct { PingSubProcesses func() error RequestNPubLinkingToken func(req RequestNPubLinkingTokenRequest) (*RequestNPubLinkingTokenResponse, error) ResetDebit func(req DebitOperation) error + ResetManage func(req ManageOperation) error ResetMetricsStorages func() error ResetNPubLinkingToken func(req RequestNPubLinkingTokenRequest) (*RequestNPubLinkingTokenResponse, error) RespondToDebit func(req DebitResponse) error @@ -397,6 +401,35 @@ func NewClient(params ClientParams) *Client { } 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 { auth, err := params.RetrieveUserAuth() if err != nil { @@ -906,6 +939,7 @@ func NewClient(params ClientParams) *Client { return &res, nil }, // server streaming method: GetLiveDebitRequests not implemented + // server streaming method: GetLiveManageRequests not implemented // server streaming method: GetLiveUserOperations not implemented GetLndForwardingMetrics: func(req LndMetricsRequest) (*LndForwardingMetrics, error) { auth, err := params.RetrieveMetricsAuth() @@ -1069,6 +1103,28 @@ func NewClient(params ClientParams) *Client { } 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 GetNPubLinkingState: func(req GetNPubLinking) (*NPubLinking, error) { auth, err := params.RetrieveAppAuth() @@ -1858,6 +1914,30 @@ func NewClient(params ClientParams) *Client { } return nil }, + ResetManage: func(req ManageOperation) error { + auth, err := params.RetrieveUserAuth() + if err != nil { + return err + } + finalRoute := "/api/user/manage/reset" + body, err := json.Marshal(req) + if err != nil { + return err + } + resBody, err := doPostRequest(params.BaseURL+finalRoute, body, auth) + if err != nil { + return err + } + result := ResultError{} + err = json.Unmarshal(resBody, &result) + if err != nil { + return err + } + if result.Status == "ERROR" { + return fmt.Errorf(result.Reason) + } + return nil + }, ResetMetricsStorages: func() error { auth, err := params.RetrieveMetricsAuth() if err != nil { diff --git a/proto/autogenerated/go/types.go b/proto/autogenerated/go/types.go index 9a1b63ff..f718dccf 100644 --- a/proto/autogenerated/go/types.go +++ b/proto/autogenerated/go/types.go @@ -355,6 +355,10 @@ type LiveDebitRequest struct { Npub string `json:"npub"` Request_id string `json:"request_id"` } +type LiveManageRequest struct { + Npub string `json:"npub"` + Request_id string `json:"request_id"` +} type LiveUserOperation struct { Operation *UserOperation `json:"operation"` } @@ -429,6 +433,22 @@ type LnurlWithdrawInfoResponse struct { Paylink string `json:"payLink"` 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 ManageOperation struct { + Npub string `json:"npub"` +} type MetricsFile struct { } type MigrationUpdate struct { @@ -643,6 +663,7 @@ type UserInfo struct { Ndebit string `json:"ndebit"` Network_max_fee_bps int64 `json:"network_max_fee_bps"` Network_max_fee_fixed int64 `json:"network_max_fee_fixed"` + Nmanage string `json:"nmanage"` Noffer string `json:"noffer"` Service_fee_bps int64 `json:"service_fee_bps"` Userid string `json:"userId"` diff --git a/proto/autogenerated/ts/express_server.ts b/proto/autogenerated/ts/express_server.ts index 8e6e04f2..26ac2294 100644 --- a/proto/autogenerated/ts/express_server.ts +++ b/proto/autogenerated/ts/express_server.ts @@ -232,6 +232,28 @@ export default (methods: Types.ServerMethods, opts: ServerOptions) => { opts.metricsCallback([{ ...info, ...stats, ...authContext }]) } catch (ex) { const e = ex as any; logErrorAndReturnResponse(e, e.message || e, res, logger, { ...info, ...stats, ...authCtx }, opts.metricsCallback); if (opts.throwErrors) throw e } }) + if (!opts.allowNotImplementedMethods && !methods.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') app.post('/api/user/debit/ban', async (req, res) => { 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 }) } 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': if (!methods.BanDebit) { throw new Error('method BanDebit not found' ) @@ -443,6 +477,16 @@ export default (methods: Types.ServerMethods, opts: ServerOptions) => { callsMetrics.push({ ...opInfo, ...opStats, ...ctx }) } 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': if (!methods.GetPaymentState) { throw new Error('method GetPaymentState not found' ) @@ -581,6 +625,18 @@ export default (methods: Types.ServerMethods, opts: ServerOptions) => { callsMetrics.push({ ...opInfo, ...opStats, ...ctx }) } break + case 'ResetManage': + if (!methods.ResetManage) { + throw new Error('method ResetManage not found' ) + } else { + const error = Types.ManageOperationValidate(operation.req) + opStats.validate = process.hrtime.bigint() + if (error !== null) throw error + await methods.ResetManage({...operation, ctx}); responses.push({ status: 'OK' }) + opStats.handle = process.hrtime.bigint() + callsMetrics.push({ ...opInfo, ...opStats, ...ctx }) + } + break case 'RespondToDebit': if (!methods.RespondToDebit) { throw new Error('method RespondToDebit not found' ) @@ -1116,6 +1172,25 @@ 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.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') app.post('/api/app/user/npub/state', async (req, res) => { const info: Types.RequestInfo = { rpcName: 'GetNPubLinkingState', batch: false, nostr: false, batchSize: 0} @@ -1721,6 +1796,28 @@ export default (methods: Types.ServerMethods, opts: ServerOptions) => { opts.metricsCallback([{ ...info, ...stats, ...authContext }]) } catch (ex) { const e = ex as any; logErrorAndReturnResponse(e, e.message || e, res, logger, { ...info, ...stats, ...authCtx }, opts.metricsCallback); if (opts.throwErrors) throw e } }) + if (!opts.allowNotImplementedMethods && !methods.ResetManage) throw new Error('method: ResetManage is not implemented') + app.post('/api/user/manage/reset', async (req, res) => { + const info: Types.RequestInfo = { rpcName: 'ResetManage', 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.ResetManage) throw new Error('method: ResetManage 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.ManageOperationValidate(request) + stats.validate = process.hrtime.bigint() + if (error !== null) return logErrorAndReturnResponse(error, 'invalid request body', res, logger, { ...info, ...stats, ...authContext }, opts.metricsCallback) + const query = req.query + const params = req.params + await methods.ResetManage({rpcName:'ResetManage', ctx:authContext , req: request}) + stats.handle = process.hrtime.bigint() + res.json({status: 'OK'}) + opts.metricsCallback([{ ...info, ...stats, ...authContext }]) + } catch (ex) { const e = ex as any; logErrorAndReturnResponse(e, e.message || e, res, logger, { ...info, ...stats, ...authCtx }, opts.metricsCallback); if (opts.throwErrors) throw e } + }) if (!opts.allowNotImplementedMethods && !methods.ResetMetricsStorages) throw new Error('method: ResetMetricsStorages is not implemented') app.post('/api/metrics/reset', async (req, res) => { const info: Types.RequestInfo = { rpcName: 'ResetMetricsStorages', batch: false, nostr: false, batchSize: 0} diff --git a/proto/autogenerated/ts/http_client.ts b/proto/autogenerated/ts/http_client.ts index 5750aa3e..038d91ad 100644 --- a/proto/autogenerated/ts/http_client.ts +++ b/proto/autogenerated/ts/http_client.ts @@ -140,6 +140,20 @@ export default (params: ClientParams) => ({ } return { status: 'ERROR', reason: 'invalid response' } }, + AuthorizeManage: async (request: Types.ManageAuthorizationRequest): Promise => { + 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 => { const auth = await params.retrieveUserAuth() if (auth === null) throw new Error('retrieveUserAuth() returned null') @@ -403,6 +417,7 @@ export default (params: ClientParams) => ({ return { status: 'ERROR', reason: 'invalid response' } }, GetLiveDebitRequests: async (cb: (v:ResultError | ({ status: 'OK' }& Types.LiveDebitRequest)) => void): Promise => { throw new Error('http streams are not supported')}, + GetLiveManageRequests: async (cb: (v:ResultError | ({ status: 'OK' }& Types.LiveManageRequest)) => void): Promise => { throw new Error('http streams are not supported')}, GetLiveUserOperations: async (cb: (v:ResultError | ({ status: 'OK' }& Types.LiveUserOperation)) => void): Promise => { throw new Error('http streams are not supported')}, GetLndForwardingMetrics: async (request: Types.LndMetricsRequest): Promise => { const auth = await params.retrieveMetricsAuth() @@ -492,6 +507,20 @@ export default (params: ClientParams) => ({ } return { status: 'ERROR', reason: 'invalid response' } }, + GetManageAuthorizations: async (): Promise => { + 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 => { throw new Error('http streams are not supported')}, GetNPubLinkingState: async (request: Types.GetNPubLinking): Promise => { const auth = await params.retrieveAppAuth() @@ -891,6 +920,17 @@ export default (params: ClientParams) => ({ } return { status: 'ERROR', reason: 'invalid response' } }, + ResetManage: async (request: Types.ManageOperation): Promise => { + const auth = await params.retrieveUserAuth() + if (auth === null) throw new Error('retrieveUserAuth() returned null') + let finalRoute = '/api/user/manage/reset' + const { data } = await axios.post(params.baseUrl + finalRoute, request, { headers: { 'authorization': auth } }) + if (data.status === 'ERROR' && typeof data.reason === 'string') return data + if (data.status === 'OK') { + return data + } + return { status: 'ERROR', reason: 'invalid response' } + }, ResetMetricsStorages: async (): Promise => { const auth = await params.retrieveMetricsAuth() if (auth === null) throw new Error('retrieveMetricsAuth() returned null') diff --git a/proto/autogenerated/ts/nostr_client.ts b/proto/autogenerated/ts/nostr_client.ts index a08f4015..f06e4eee 100644 --- a/proto/autogenerated/ts/nostr_client.ts +++ b/proto/autogenerated/ts/nostr_client.ts @@ -99,6 +99,21 @@ export default (params: NostrClientParams, send: (to:string, message: NostrRequ } return { status: 'ERROR', reason: 'invalid response' } }, + AuthorizeManage: async (request: Types.ManageAuthorizationRequest): Promise => { + 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 => { const auth = await params.retrieveNostrUserAuth() 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' }) }) }, + GetLiveManageRequests: async (cb: (res:ResultError | ({ status: 'OK' }& Types.LiveManageRequest)) => void): Promise => { + 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 => { const auth = await params.retrieveNostrUserAuth() 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' } }, + GetManageAuthorizations: async (): Promise => { + 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 => { const auth = await params.retrieveNostrUserAuth() if (auth === null) throw new Error('retrieveNostrUserAuth() returned null') @@ -737,6 +781,18 @@ export default (params: NostrClientParams, send: (to:string, message: NostrRequ } return { status: 'ERROR', reason: 'invalid response' } }, + ResetManage: async (request: Types.ManageOperation): Promise => { + 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:'ResetManage',authIdentifier:auth, ...nostrRequest }) + if (data.status === 'ERROR' && typeof data.reason === 'string') return data + if (data.status === 'OK') { + return data + } + return { status: 'ERROR', reason: 'invalid response' } + }, ResetMetricsStorages: async (): Promise => { const auth = await params.retrieveNostrMetricsAuth() if (auth === null) throw new Error('retrieveNostrMetricsAuth() returned null') diff --git a/proto/autogenerated/ts/nostr_transport.ts b/proto/autogenerated/ts/nostr_transport.ts index 5e9ea211..dc244600 100644 --- a/proto/autogenerated/ts/nostr_transport.ts +++ b/proto/autogenerated/ts/nostr_transport.ts @@ -128,6 +128,22 @@ 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 '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': try { 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 }) } 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': if (!methods.BanDebit) { throw new Error('method not defined: BanDebit') @@ -325,6 +353,16 @@ export default (methods: Types.ServerMethods, opts: NostrOptions) => { callsMetrics.push({ ...opInfo, ...opStats, ...ctx }) } 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': if (!methods.GetPaymentState) { throw new Error('method not defined: GetPaymentState') @@ -463,6 +501,18 @@ export default (methods: Types.ServerMethods, opts: NostrOptions) => { callsMetrics.push({ ...opInfo, ...opStats, ...ctx }) } break + case 'ResetManage': + if (!methods.ResetManage) { + throw new Error('method not defined: ResetManage') + } else { + const error = Types.ManageOperationValidate(operation.req) + opStats.validate = process.hrtime.bigint() + if (error !== null) throw error + await methods.ResetManage({...operation, ctx}); responses.push({ status: 'OK' }) + opStats.handle = process.hrtime.bigint() + callsMetrics.push({ ...opInfo, ...opStats, ...ctx }) + } + break case 'RespondToDebit': if (!methods.RespondToDebit) { throw new Error('method not defined: RespondToDebit') @@ -728,6 +778,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 } 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': try { if (!methods.GetLiveUserOperations) throw new Error('method: GetLiveUserOperations is not implemented') @@ -799,6 +862,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 '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': try { if (!methods.GetMigrationUpdate) throw new Error('method: GetMigrationUpdate is not implemented') @@ -1143,6 +1219,22 @@ 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 'ResetManage': + try { + if (!methods.ResetManage) throw new Error('method: ResetManage 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.ManageOperationValidate(request) + stats.validate = process.hrtime.bigint() + if (error !== null) return logErrorAndReturnResponse(error, 'invalid request body', res, logger, { ...info, ...stats, ...authCtx }, opts.metricsCallback) + await methods.ResetManage({rpcName:'ResetManage', ctx:authContext , req: request}) + stats.handle = process.hrtime.bigint() + res({status: 'OK'}) + opts.metricsCallback([{ ...info, ...stats, ...authContext }]) + }catch(ex){ const e = ex as any; logErrorAndReturnResponse(e, e.message || e, res, logger, { ...info, ...stats, ...authCtx }, opts.metricsCallback); if (opts.throwErrors) throw e } + break case 'ResetMetricsStorages': try { if (!methods.ResetMetricsStorages) throw new Error('method: ResetMetricsStorages is not implemented') diff --git a/proto/autogenerated/ts/types.ts b/proto/autogenerated/ts/types.ts index 9dc61dbd..06af2539 100644 --- a/proto/autogenerated/ts/types.ts +++ b/proto/autogenerated/ts/types.ts @@ -35,8 +35,8 @@ export type UserContext = { app_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 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 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 | ResetManage_Input | RespondToDebit_Input | UpdateCallbackUrl_Input | UpdateUserOffer_Input | UserHealth_Input +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 | ResetManage_Output | RespondToDebit_Output | UpdateCallbackUrl_Output | UpdateUserOffer_Output | UserHealth_Output export type AuthContext = AdminContext | AppContext | GuestContext | GuestWithPubContext | MetricsContext | UserContext 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_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_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_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_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_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_Output = ResultError | { status: 'OK' } @@ -262,6 +271,9 @@ export type RequestNPubLinkingToken_Output = ResultError | ({ status: 'OK' } & R export type ResetDebit_Input = {rpcName:'ResetDebit', req: DebitOperation} export type ResetDebit_Output = ResultError | { status: 'OK' } +export type ResetManage_Input = {rpcName:'ResetManage', req: ManageOperation} +export type ResetManage_Output = ResultError | { status: 'OK' } + export type ResetMetricsStorages_Input = {rpcName:'ResetMetricsStorages'} export type ResetMetricsStorages_Output = ResultError | { status: 'OK' } @@ -320,6 +332,7 @@ export type ServerMethods = { AddUserOffer?: (req: AddUserOffer_Input & {ctx: UserContext }) => Promise AuthApp?: (req: AuthApp_Input & {ctx: AdminContext }) => Promise AuthorizeDebit?: (req: AuthorizeDebit_Input & {ctx: UserContext }) => Promise + AuthorizeManage?: (req: AuthorizeManage_Input & {ctx: UserContext }) => Promise BanDebit?: (req: BanDebit_Input & {ctx: UserContext }) => Promise BanUser?: (req: BanUser_Input & {ctx: AdminContext }) => Promise CloseChannel?: (req: CloseChannel_Input & {ctx: AdminContext }) => Promise @@ -340,6 +353,7 @@ export type ServerMethods = { GetInviteLinkState?: (req: GetInviteLinkState_Input & {ctx: AdminContext }) => Promise GetLNURLChannelLink?: (req: GetLNURLChannelLink_Input & {ctx: UserContext }) => Promise GetLiveDebitRequests?: (req: GetLiveDebitRequests_Input & {ctx: UserContext }) => Promise + GetLiveManageRequests?: (req: GetLiveManageRequests_Input & {ctx: UserContext }) => Promise GetLiveUserOperations?: (req: GetLiveUserOperations_Input & {ctx: UserContext }) => Promise GetLndForwardingMetrics?: (req: GetLndForwardingMetrics_Input & {ctx: MetricsContext }) => Promise GetLndMetrics?: (req: GetLndMetrics_Input & {ctx: MetricsContext }) => Promise @@ -347,6 +361,7 @@ export type ServerMethods = { GetLnurlPayLink?: (req: GetLnurlPayLink_Input & {ctx: UserContext }) => Promise GetLnurlWithdrawInfo?: (req: GetLnurlWithdrawInfo_Input & {ctx: GuestContext }) => Promise GetLnurlWithdrawLink?: (req: GetLnurlWithdrawLink_Input & {ctx: UserContext }) => Promise + GetManageAuthorizations?: (req: GetManageAuthorizations_Input & {ctx: UserContext }) => Promise GetMigrationUpdate?: (req: GetMigrationUpdate_Input & {ctx: UserContext }) => Promise GetNPubLinkingState?: (req: GetNPubLinkingState_Input & {ctx: AppContext }) => Promise GetPaymentState?: (req: GetPaymentState_Input & {ctx: UserContext }) => Promise @@ -377,6 +392,7 @@ export type ServerMethods = { PingSubProcesses?: (req: PingSubProcesses_Input & {ctx: MetricsContext }) => Promise RequestNPubLinkingToken?: (req: RequestNPubLinkingToken_Input & {ctx: AppContext }) => Promise ResetDebit?: (req: ResetDebit_Input & {ctx: UserContext }) => Promise + ResetManage?: (req: ResetManage_Input & {ctx: UserContext }) => Promise ResetMetricsStorages?: (req: ResetMetricsStorages_Input & {ctx: MetricsContext }) => Promise ResetNPubLinkingToken?: (req: ResetNPubLinkingToken_Input & {ctx: AppContext }) => Promise RespondToDebit?: (req: RespondToDebit_Input & {ctx: UserContext }) => Promise @@ -2011,6 +2027,29 @@ export const LiveDebitRequestValidate = (o?: LiveDebitRequest, opts: LiveDebitRe 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 = { operation: UserOperation } @@ -2470,6 +2509,104 @@ export const LnurlWithdrawInfoResponseValidate = (o?: LnurlWithdrawInfoResponse, 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 ManageOperation = { + npub: string +} +export const ManageOperationOptionalFields: [] = [] +export type ManageOperationOptions = OptionsBaseMessage & { + checkOptionalsAreSet?: [] + npub_CustomCheck?: (v: string) => boolean +} +export const ManageOperationValidate = (o?: ManageOperation, opts: ManageOperationOptions = {}, path: string = 'ManageOperation::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`) + + return null +} + export type MetricsFile = { } export const MetricsFileOptionalFields: [] = [] @@ -3680,6 +3817,7 @@ export type UserInfo = { ndebit: string network_max_fee_bps: number network_max_fee_fixed: number + nmanage: string noffer: string service_fee_bps: number userId: string @@ -3695,6 +3833,7 @@ export type UserInfoOptions = OptionsBaseMessage & { ndebit_CustomCheck?: (v: string) => boolean network_max_fee_bps_CustomCheck?: (v: number) => boolean network_max_fee_fixed_CustomCheck?: (v: number) => boolean + nmanage_CustomCheck?: (v: string) => boolean noffer_CustomCheck?: (v: string) => boolean service_fee_bps_CustomCheck?: (v: number) => boolean userId_CustomCheck?: (v: string) => boolean @@ -3725,6 +3864,9 @@ export const UserInfoValidate = (o?: UserInfo, opts: UserInfoOptions = {}, path: if (typeof o.network_max_fee_fixed !== 'number') return new Error(`${path}.network_max_fee_fixed: is not a number`) if (opts.network_max_fee_fixed_CustomCheck && !opts.network_max_fee_fixed_CustomCheck(o.network_max_fee_fixed)) return new Error(`${path}.network_max_fee_fixed: custom check failed`) + if (typeof o.nmanage !== 'string') return new Error(`${path}.nmanage: is not a string`) + if (opts.nmanage_CustomCheck && !opts.nmanage_CustomCheck(o.nmanage)) return new Error(`${path}.nmanage: custom check failed`) + if (typeof o.noffer !== 'string') return new Error(`${path}.noffer: is not a string`) if (opts.noffer_CustomCheck && !opts.noffer_CustomCheck(o.noffer)) return new Error(`${path}.noffer: custom check failed`) diff --git a/proto/service/methods.proto b/proto/service/methods.proto index 21f0a9d6..b20bdb73 100644 --- a/proto/service/methods.proto +++ b/proto/service/methods.proto @@ -592,6 +592,24 @@ service LightningPub { option (http_route) = "/api/user/debit/get"; 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 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 ResetManage(structs.ManageOperation) returns (structs.Empty){ + option (auth_type) = "User"; + option (http_method) = "post"; + option (http_route) = "/api/user/manage/reset"; + option (nostr) = true; + } rpc AuthorizeDebit(structs.DebitAuthorizationRequest) returns (structs.DebitAuthorization){ option (auth_type) = "User"; option (http_method) = "post"; @@ -628,6 +646,14 @@ service LightningPub { option (http_route) = "/api/user/debit/sub"; 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){ option (auth_type) = "User"; option (http_method) = "post"; diff --git a/proto/service/structs.proto b/proto/service/structs.proto index 430198c5..43bb75ad 100644 --- a/proto/service/structs.proto +++ b/proto/service/structs.proto @@ -529,6 +529,7 @@ message UserInfo{ string ndebit = 9; string callback_url = 10; string bridge_url = 11; + string nmanage = 12; } message GetUserOperationsRequest{ int64 latestIncomingInvoice = 1; @@ -674,6 +675,26 @@ message DebitAuthorizationRequest { optional string request_id = 3; } +message ManageOperation { + string npub = 1; +} + +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 { string debit_id = 1; bool authorized = 2; @@ -718,6 +739,11 @@ message LiveDebitRequest { } } +message LiveManageRequest { + string request_id = 1; + string npub = 2; +} + message DebitResponse { string request_id = 1; string npub = 2; diff --git a/src/e2e.ts b/src/e2e.ts index 886202be..bcb16e3d 100644 --- a/src/e2e.ts +++ b/src/e2e.ts @@ -2,7 +2,6 @@ import 'dotenv/config' import NewServer from '../proto/autogenerated/ts/express_server.js' import GetServerMethods from './services/serverMethods/index.js' import serverOptions from './auth.js'; -import { LoadNosrtSettingsFromEnv } from './services/nostr/index.js' import nostrMiddleware from './nostrMiddleware.js' import { getLogger } from './services/helpers/logger.js'; import { initMainHandler } from './services/main/init.js'; @@ -22,7 +21,7 @@ const start = async () => { const { apps, mainHandler, liquidityProviderInfo, wizard, adminManager } = keepOn const serverMethods = GetServerMethods(mainHandler) - const nostrSettings = LoadNosrtSettingsFromEnv() + const nostrSettings = mainSettings.nostrRelaySettings log("initializing nostr middleware") const { Send } = nostrMiddleware(serverMethods, mainHandler, { ...nostrSettings, apps, clients: [liquidityProviderInfo] }, diff --git a/src/index.ts b/src/index.ts index 49ffa1f4..1a56397d 100644 --- a/src/index.ts +++ b/src/index.ts @@ -2,7 +2,6 @@ import 'dotenv/config' import NewServer from '../proto/autogenerated/ts/express_server.js' import GetServerMethods from './services/serverMethods/index.js' import serverOptions from './auth.js'; -import { LoadNosrtSettingsFromEnv } from './services/nostr/index.js' import nostrMiddleware from './nostrMiddleware.js' import { getLogger } from './services/helpers/logger.js'; import { initMainHandler } from './services/main/init.js'; @@ -22,10 +21,9 @@ const start = async () => { const { apps, mainHandler, liquidityProviderInfo, wizard, adminManager } = keepOn const serverMethods = GetServerMethods(mainHandler) - const nostrSettings = LoadNosrtSettingsFromEnv() log("initializing nostr middleware") const { Send, Stop, Ping } = nostrMiddleware(serverMethods, mainHandler, - { ...nostrSettings, apps, clients: [liquidityProviderInfo] }, + { ...mainSettings.nostrRelaySettings, apps, clients: [liquidityProviderInfo] }, (e, p) => mainHandler.liquidityProvider.onEvent(e, p) ) exitHandler(() => { Stop(); mainHandler.Stop() }) @@ -33,9 +31,9 @@ const start = async () => { mainHandler.attachNostrSend(Send) mainHandler.attachNostrProcessPing(Ping) mainHandler.StartBeacons() - const appNprofile = nprofileEncode({ pubkey: liquidityProviderInfo.publicKey, relays: nostrSettings.relays }) + const appNprofile = nprofileEncode({ pubkey: liquidityProviderInfo.publicKey, relays: mainSettings.nostrRelaySettings.relays }) if (wizard) { - wizard.AddConnectInfo(appNprofile, nostrSettings.relays) + wizard.AddConnectInfo(appNprofile, mainSettings.nostrRelaySettings.relays) } adminManager.setAppNprofile(appNprofile) const Server = NewServer(serverMethods, serverOptions(mainHandler)) diff --git a/src/nostrMiddleware.ts b/src/nostrMiddleware.ts index a21aee22..cac2662c 100644 --- a/src/nostrMiddleware.ts +++ b/src/nostrMiddleware.ts @@ -4,7 +4,7 @@ import { NostrEvent, NostrSend, NostrSettings } from "./services/nostr/handler.j import * as Types from '../proto/autogenerated/ts/types.js' import NewNostrTransport, { NostrRequest } from '../proto/autogenerated/ts/nostr_transport.js'; import { ERROR, getLogger } from "./services/helpers/logger.js"; -import { NdebitData, NofferData } from "@shocknet/clink-sdk"; +import { NdebitData, NofferData, NmanageRequest } from "@shocknet/clink-sdk"; export default (serverMethods: Types.ServerMethods, mainHandler: Main, nostrSettings: NostrSettings, onClientEvent: (e: { requestId: string }, fromPub: string) => void): { Stop: () => void, Send: NostrSend, Ping: () => Promise } => { const log = getLogger({}) @@ -37,6 +37,7 @@ export default (serverMethods: Types.ServerMethods, mainHandler: Main, nostrSett }, logger: { log: console.log, error: err => log(ERROR, err) }, }) + const nostr = new Nostr(nostrSettings, mainHandler.utils, event => { let j: NostrRequest try { @@ -54,6 +55,10 @@ export default (serverMethods: Types.ServerMethods, mainHandler: Main, nostrSett const debitReq = j as NdebitData mainHandler.debitManager.handleNip68Debit(debitReq, event) return + } else if (event.kind === 21003) { + const nmanageReq = j as NmanageRequest + mainHandler.managementManager.handleRequest(nmanageReq, event); + return; } if (!j.rpcName) { onClientEvent(j as { requestId: string }, event.pub) @@ -67,6 +72,7 @@ export default (serverMethods: Types.ServerMethods, mainHandler: Main, nostrSett nostr.Send({ type: 'app', appId: event.appId }, { type: 'content', pub: event.pub, content: JSON.stringify({ ...res, requestId: j.requestId }) }) }, event.startAtNano, event.startAtMs) }) + return { Stop: () => nostr.Stop, Send: (...args) => nostr.Send(...args), Ping: () => nostr.Ping() } } diff --git a/src/services/main/appUserManager.ts b/src/services/main/appUserManager.ts index 39b2ba4b..12eae1f9 100644 --- a/src/services/main/appUserManager.ts +++ b/src/services/main/appUserManager.ts @@ -4,8 +4,7 @@ import * as Types from '../../../proto/autogenerated/ts/types.js' import { MainSettings } from './settings.js' import ApplicationManager from './applicationManager.js' -import { LoadNosrtSettingsFromEnv } from '../nostr/index.js' -import { OfferPriceType, ndebitEncode, nofferEncode } from '@shocknet/clink-sdk' +import { OfferPriceType, ndebitEncode, nmanageEncode, nofferEncode } from '@shocknet/clink-sdk' export default class { storage: Storage @@ -66,7 +65,7 @@ export default class { if (!appUser) { throw new Error(`app user ${ctx.user_id} not found`) // TODO: fix logs doxing } - const nostrSettings = LoadNosrtSettingsFromEnv() + const nostrSettings = this.settings.nostrRelaySettings return { userId: ctx.user_id, balance: user.balance_sats, @@ -77,6 +76,7 @@ export default class { service_fee_bps: this.settings.outgoingAppUserInvoiceFeeBps, noffer: nofferEncode({ pubkey: app.nostr_public_key!, offer: appUser.identifier, priceType: OfferPriceType.Spontaneous, relay: nostrSettings.relays[0] }), ndebit: ndebitEncode({ pubkey: app.nostr_public_key!, pointer: appUser.identifier, relay: nostrSettings.relays[0] }), + nmanage: nmanageEncode({ pubkey: app.nostr_public_key!, pointer: appUser.identifier, relay: nostrSettings.relays[0] }), callback_url: appUser.callback_url, bridge_url: this.settings.bridgeUrl } diff --git a/src/services/main/applicationManager.ts b/src/services/main/applicationManager.ts index edab50a2..d216f71c 100644 --- a/src/services/main/applicationManager.ts +++ b/src/services/main/applicationManager.ts @@ -8,9 +8,8 @@ import { ApplicationUser } from '../storage/entity/ApplicationUser.js' import { PubLogger, getLogger } from '../helpers/logger.js' import crypto from 'crypto' import { Application } from '../storage/entity/Application.js' -import { LoadNosrtSettingsFromEnv } from '../nostr/index.js' import { ZapInfo } from '../storage/entity/UserReceivingInvoice.js' -import { nofferEncode, ndebitEncode, OfferPriceType } from '@shocknet/clink-sdk' +import { nofferEncode, ndebitEncode, OfferPriceType, nmanageEncode } from '@shocknet/clink-sdk' const TOKEN_EXPIRY_TIME = 2 * 60 * 1000 // 2 minutes, in milliseconds type NsecLinkingData = { @@ -151,7 +150,7 @@ export default class { u = user if (created) log(u.identifier, u.user.user_id, "user created") } - const nostrSettings = LoadNosrtSettingsFromEnv() + const nostrSettings = this.settings.nostrRelaySettings return { identifier: u.identifier, info: { @@ -164,6 +163,7 @@ export default class { service_fee_bps: this.settings.outgoingAppUserInvoiceFeeBps, noffer: nofferEncode({ pubkey: app.nostr_public_key!, offer: u.identifier, priceType: OfferPriceType.Spontaneous, relay: nostrSettings.relays[0] }), ndebit: ndebitEncode({ pubkey: app.nostr_public_key!, pointer: u.identifier, relay: nostrSettings.relays[0] }), + nmanage: nmanageEncode({ pubkey: app.nostr_public_key!, pointer: u.identifier, relay: nostrSettings.relays[0] }), callback_url: u.callback_url, bridge_url: this.settings.bridgeUrl @@ -205,7 +205,7 @@ export default class { const app = await this.storage.applicationStorage.GetApplication(appId) const user = await this.storage.applicationStorage.GetApplicationUser(app, req.user_identifier) const max = this.paymentManager.GetMaxPayableInvoice(user.user.balance_sats, true) - const nostrSettings = LoadNosrtSettingsFromEnv() + const nostrSettings = this.settings.nostrRelaySettings return { max_withdrawable: max, identifier: req.user_identifier, info: { userId: user.user.user_id, balance: user.user.balance_sats, @@ -216,6 +216,7 @@ export default class { service_fee_bps: this.settings.outgoingAppUserInvoiceFeeBps, noffer: nofferEncode({ pubkey: app.nostr_public_key!, offer: user.identifier, priceType: OfferPriceType.Spontaneous, relay: nostrSettings.relays[0] }), ndebit: ndebitEncode({ pubkey: app.nostr_public_key!, pointer: user.identifier, relay: nostrSettings.relays[0] }), + nmanage: nmanageEncode({ pubkey: app.nostr_public_key!, pointer: user.identifier, relay: nostrSettings.relays[0] }), callback_url: user.callback_url, bridge_url: this.settings.bridgeUrl }, diff --git a/src/services/main/index.ts b/src/services/main/index.ts index 8f1127c2..15f0cf7c 100644 --- a/src/services/main/index.ts +++ b/src/services/main/index.ts @@ -25,6 +25,7 @@ import { defaultInvoiceExpiry } from "../storage/paymentStorage.js" import { DebitManager } from "./debitManager.js" import { OfferManager } from "./offerManager.js" import webRTC from "../webRTC/index.js" +import { ManagementManager } from "./managementManager.js" type UserOperationsSub = { id: string @@ -51,6 +52,7 @@ export default class { liquidityProvider: LiquidityProvider debitManager: DebitManager offerManager: OfferManager + managementManager: ManagementManager utils: Utils rugPullTracker: RugPullTracker unlocker: Unlocker @@ -60,8 +62,8 @@ export default class { constructor(settings: MainSettings, storage: Storage, adminManager: AdminManager, utils: Utils, unlocker: Unlocker) { this.settings = settings this.storage = storage - this.utils = utils this.adminManager = adminManager + this.utils = utils this.unlocker = unlocker const updateProviderBalance = (b: number) => this.storage.liquidityStorage.IncrementTrackedProviderBalance('lnPub', settings.liquiditySettings.liquidityProviderPub, b) this.liquidityProvider = new LiquidityProvider(settings.liquiditySettings.liquidityProviderPub, this.utils, this.invoicePaidCb, updateProviderBalance) @@ -75,7 +77,8 @@ export default class { this.applicationManager = new ApplicationManager(this.storage, this.settings, this.paymentManager) this.appUserManager = new AppUserManager(this.storage, this.settings, this.applicationManager) this.debitManager = new DebitManager(this.storage, this.lnd, this.applicationManager) - this.offerManager = new OfferManager(this.storage, this.lnd, this.applicationManager, this.productManager, this.liquidityManager) + this.offerManager = new OfferManager(this.storage, this.settings, this.lnd, this.applicationManager, this.productManager, this.liquidityManager) + this.managementManager = new ManagementManager(this.storage, this.settings) //this.webRTC = new webRTC(this.storage, this.utils) } @@ -98,6 +101,7 @@ export default class { this.liquidityProvider.attachNostrSend(f) this.debitManager.attachNostrSend(f) this.offerManager.attachNostrSend(f) + this.managementManager.attachNostrSend(f) this.utils.attachNostrSend(f) //this.webRTC.attachNostrSend(f) } diff --git a/src/services/main/managementManager.ts b/src/services/main/managementManager.ts new file mode 100644 index 00000000..ce3f255e --- /dev/null +++ b/src/services/main/managementManager.ts @@ -0,0 +1,343 @@ +import { getRepository } from "typeorm"; +import { User } from "../storage/entity/User.js"; +import { UserOffer } from "../storage/entity/UserOffer.js"; +import { ManagementGrant } from "../storage/entity/ManagementGrant.js"; +import { NostrEvent, NostrSend } from "../nostr/handler.js"; +import Storage from "../storage/index.js"; +import { OfferManager } from "./offerManager.js"; +import * as Types from "../../../proto/autogenerated/ts/types.js"; +import { MainSettings } from "./settings.js"; +import { nofferEncode, OfferPointer, OfferPriceType, NmanageRequest, NmanageResponse, NmanageCreateOffer, NmanageUpdateOffer, NmanageDeleteOffer, NmanageGetOffer, NmanageListOffers, OfferData, OfferFields, NmanageFailure } from "@shocknet/clink-sdk"; +import { UnsignedEvent } from "nostr-tools"; +import { getLogger, PubLogger, ERROR } from "../helpers/logger.js"; +type Result = { state: 'success', result: T } | { state: 'error', err: NmanageFailure } | { state: 'authRequired' } + +export class ManagementManager { + private nostrSend: NostrSend; + private storage: Storage; + private settings: MainSettings; + private awaitingRequests: Record = {} + private logger: PubLogger + constructor(storage: Storage, settings: MainSettings) { + this.storage = storage; + this.settings = settings; + this.logger = getLogger({ component: 'ManagementManager' }) + } + + attachNostrSend(f: NostrSend) { + this.nostrSend = f + } + + ResetManage = async (ctx: Types.UserContext, req: Types.ManageOperation): Promise => { + await this.storage.managementStorage.removeGrant(ctx.app_user_id, req.npub) + } + + AuthorizeManage = async (ctx: Types.UserContext, req: Types.ManageAuthorizationRequest): Promise => { + const grant = await this.storage.managementStorage.addGrant(ctx.app_user_id, req.authorize_npub, req.ban) + const awaiting = this.awaitingRequests[req.authorize_npub] + if (awaiting) { + delete this.awaitingRequests[req.authorize_npub] + if (!grant.banned) { + await this.handleRequest(awaiting.request, awaiting.event) + } + } + return { + manage_id: grant.serial_id.toString(), + authorized: !grant.banned, + npub: grant.app_pubkey, + } + } + + GetManageAuthorizations = async (ctx: Types.UserContext): Promise => { + 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, userPub: 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.logger("Sending manage authorization request to", npub, "for app", appId) + this.nostrSend({ type: 'app', appId: appId }, { type: 'content', content: JSON.stringify(message), pub: userPub }) + } + + 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 async 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 + } + const appUserId = (nmanageReq as { pointer?: string }).pointer + if (!appUserId) { + this.logger(ERROR, "No pointer provided", event.pub) + this.sendError(event, { res: 'GFY', code: 1, error: 'Request Denied: No pointer provided, cannot sent auth request' }) + return + } + const app = await this.storage.applicationStorage.GetApplication(event.appId) + const appUser = await this.storage.applicationStorage.GetApplicationUser(app, appUserId) + if (!appUser.nostr_public_key) { + this.logger(ERROR, "App user has no nostr public key", event.pub) + this.sendError(event, { res: 'GFY', code: 1, error: 'Request Denied: App user has no nostr public key' }) + return + } + this.awaitingRequests[event.pub] = { request: nmanageReq, event } + this.sendManageAuthorizationRequest(event.appId, appUser.nostr_public_key, { requestId: event.id, npub: event.pub }) + } + + + + async handleRequest(nmanageReq: NmanageRequest, event: NostrEvent): Promise { + try { + const r = await this.doNmanage(nmanageReq, event) + if (r.state === 'authRequired') { + await this.handleAuthRequired(nmanageReq, event) + return + } + if (r.state === 'error') { + this.logger(ERROR, "Error in nmanage request", r.err) + 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 } }) + } catch (err: any) { + this.logger(ERROR, err.message || err) + this.sendError(event, { res: 'GFY', code: 2, error: 'Temporary Failure' }) + } + } + + private async doNmanage(nmanageReq: NmanageRequest, event: NostrEvent): Promise> { + const action = nmanageReq.action + switch (action) { + case "create": + const createResult = await this.createOffer(nmanageReq, event.pub) + return this.getNmanageResponse(event.appId, createResult) + case "update": + const updateResult = await this.updateOffer(nmanageReq, event.pub); + return this.getNmanageResponse(event.appId, updateResult) + case "delete": + const deleteResult = await this.deleteOffer(nmanageReq, event.pub); + return this.getNmanageResponse(event.appId, deleteResult) + case "get": + const getResult = await this.getOffer(nmanageReq, event.pub); + return this.getNmanageResponse(event.appId, getResult) + case "list": + const listResult = await this.listOffers(nmanageReq, event.pub); + return this.getNmanageResponse(event.appId, listResult) + default: + return { state: 'error', err: { res: 'GFY', code: 1, error: `Request Denied: Unknown action: ${action}` } } + } + } + + private getOfferData(offer: UserOffer, appPub: string): OfferData { + const pointer: OfferPointer = { + offer: offer.offer_id, + pubkey: appPub, + relay: this.settings.nostrRelaySettings.relays[0], + priceType: offer.price_sats > 0 ? OfferPriceType.Fixed : OfferPriceType.Spontaneous, + price: offer.price_sats, + } + return { + id: offer.offer_id, + label: offer.label, + price_sats: offer.price_sats, + callback_url: offer.callback_url, + payer_data: Object.keys(offer.expected_data || {}), + noffer: nofferEncode(pointer), + } + } + + private async getNmanageResponse(appId: string, result: Result): Promise> { + if (result.state !== 'success') { + return result + } + const args = result.result + const app = await this.storage.applicationStorage.GetApplication(appId) + if (args && Array.isArray(args)) { + return { + state: 'success', result: { + res: 'ok', resource: 'offer', details: args.map(offer => this.getOfferData(offer, app.nostr_public_key!)) + } + } + } + if (!args) { + return { state: 'success', result: { res: 'ok', resource: 'offer' } } + } + return { + state: 'success', result: { + res: 'ok', resource: 'offer', details: this.getOfferData(args, app.nostr_public_key!) + } + } + } + + private async getOffer(nmanageReq: NmanageGetOffer, requestorPub: string): Promise> { + const offer = await this.validateOfferAccess(nmanageReq.offer.id, requestorPub) + if (offer.state !== 'success') { + return offer + } + return { state: 'success', result: offer.result } + } + + private async listOffers(nmanageReq: NmanageListOffers, requestorPub: string): Promise> { + const appUserId = nmanageReq.pointer + if (!appUserId) { + return { state: 'error', err: { res: 'GFY', code: 1, error: 'Request Denied: No pointer provided' } } + } + const grantResult = await this.validateGrantAccess(appUserId, requestorPub) + if (grantResult.state !== 'success') { + return grantResult + } + const offers = await this.storage.offerStorage.getManagedUserOffers(appUserId, requestorPub) + return { state: 'success', result: offers } + } + + private validateOfferFields(fields: OfferFields): Result { + if (!fields.label || typeof fields.label !== 'string') { + return { state: 'error', err: { res: 'GFY', code: 5, error: 'Invalid Field/Value', field: 'label' } } + } + if (fields.price_sats && typeof fields.price_sats !== 'number') { + return { state: 'error', err: { res: 'GFY', code: 5, error: 'Invalid Field/Value', field: 'price_sats' } } + } + if (fields.callback_url && typeof fields.callback_url !== 'string') { + return { state: 'error', err: { res: 'GFY', code: 5, error: 'Invalid Field/Value', field: 'callback_url' } } + } + if (fields.payer_data && !Array.isArray(fields.payer_data)) { + return { state: 'error', err: { res: 'GFY', code: 5, error: 'Invalid Field/Value', field: 'payer_data' } } + } + + return { state: 'success', result: undefined } + } + + private async createOffer(nmanageReq: NmanageCreateOffer, requestorPub: string): Promise> { + const appUserId = nmanageReq.pointer + if (!appUserId) { + return { state: 'error', err: { res: 'GFY', code: 1, error: 'Request Denied: No pointer provided' } } + } + const grantResult = await this.validateGrantAccess(appUserId, requestorPub) + if (grantResult.state !== 'success') { + return grantResult + } + const validateResult = this.validateOfferFields(nmanageReq.offer.fields) + if (validateResult.state !== 'success') { + return validateResult + } + const dataMap: Record = {} + nmanageReq.offer.fields.payer_data.forEach(data => { + dataMap[data] = Types.OfferDataType.DATA_STRING + }) + const offer = await this.storage.offerStorage.AddUserOffer(appUserId, { + label: nmanageReq.offer.fields.label, + callback_url: nmanageReq.offer.fields.callback_url, + price_sats: nmanageReq.offer.fields.price_sats, + expected_data: dataMap, + management_pubkey: requestorPub, + }) + return { state: 'success', result: offer } + } + + private async validateGrantAccess(appUserId: string, requestorPub: string): Promise> { + const grant = await this.storage.managementStorage.getGrant(appUserId, requestorPub) + + if (!grant) { + this.logger(ERROR, "No grant found", appUserId, requestorPub) + return { state: 'authRequired' } + } + + if (grant.expires_at_unix > 0 && grant.expires_at_unix < Date.now()) { + this.logger(ERROR, "Grant expired", appUserId, requestorPub) + return { state: 'authRequired' } + } + + 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> { + const offer = await this.storage.offerStorage.GetOffer(offerId) + if (!offer) { + return { state: 'error', err: { res: 'GFY', code: 1, error: 'Request Denied: Offer not found' } } + } + if (offer.management_pubkey !== requestorPub) { + 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) + if (grantResult.state !== 'success') { + return grantResult + } + return { state: 'success', result: offer } + } + + private async updateOffer(nmanageReq: NmanageUpdateOffer, requestorPub: string): Promise> { + const offer = await this.validateOfferAccess(nmanageReq.offer.id, requestorPub) + if (offer.state !== 'success') { + return offer + } + const validateResult = this.validateOfferFields(nmanageReq.offer.fields) + if (validateResult.state !== 'success') { + return validateResult + } + const dataMap: Record = {} + for (const data of nmanageReq.offer.fields.payer_data || []) { + if (typeof data !== 'string') { + return { state: 'error', err: { res: 'GFY', code: 5, error: 'Invalid Field/Value', field: 'payer_data' } } + } + dataMap[data] = Types.OfferDataType.DATA_STRING + } + await this.storage.offerStorage.UpdateUserOffer(offer.result.app_user_id, nmanageReq.offer.id, { + label: nmanageReq.offer.fields.label, + callback_url: nmanageReq.offer.fields.callback_url, + price_sats: nmanageReq.offer.fields.price_sats, + expected_data: dataMap, + }) + const updatedOffer = await this.storage.offerStorage.GetOffer(nmanageReq.offer.id) + if (!updatedOffer) { + return { state: 'error', err: { res: 'GFY', code: 2, error: 'Temporary Failure: Offer not found' } } + } + return { state: 'success', result: updatedOffer } + } + + private async deleteOffer(nmanageReq: NmanageDeleteOffer, requestorPub: string): Promise> { + const offerResult = await this.validateOfferAccess(nmanageReq.offer.id, requestorPub) + if (offerResult.state !== 'success') { + return offerResult + } + await this.storage.offerStorage.DeleteUserOffer(offerResult.result.app_user_id, offerResult.result.offer_id) + return { state: 'success', result: undefined } + } +} + +const newNmanageResponse = (content: string, event: NostrEvent): UnsignedEvent => { + return { + content, + created_at: Math.floor(Date.now() / 1000), + kind: 21003, + pubkey: "", + tags: [ + ['p', event.pub], + ['e', event.id], + ], + } +} +const codeToMessage = (code: number, reason = "") => { + switch (code) { + case 1: return 'Request Denied' + case 2: return 'Temporary Failure: ' + reason + case 3: return 'Expired Request' + case 4: return 'Rate Limited' + case 5: return 'Invalid Field or Value' + case 6: return 'Invalid Request: ' + reason + default: throw new Error("unknown error code" + code) + } +} \ No newline at end of file diff --git a/src/services/main/offerManager.ts b/src/services/main/offerManager.ts index 26e35816..3aaae490 100644 --- a/src/services/main/offerManager.ts +++ b/src/services/main/offerManager.ts @@ -7,9 +7,9 @@ import { ERROR, getLogger } from "../helpers/logger.js"; import { NostrEvent, NostrSend, SendData, SendInitiator } from '../nostr/handler.js'; import { UnsignedEvent } from 'nostr-tools'; import { UserOffer } from '../storage/entity/UserOffer.js'; -import { LoadNosrtSettingsFromEnv } from '../nostr/index.js'; import { LiquidityManager } from "./liquidityManager.js" import { NofferData, OfferPriceType, nofferEncode } from '@shocknet/clink-sdk'; +import { MainSettings } from "./settings.js"; const mapToOfferConfig = (appUserId: string, offer: UserOffer, { pubkey, relay }: { pubkey: string, relay: string }): Types.OfferConfig => { if (offer.expected_data) { @@ -38,15 +38,16 @@ export class OfferManager { _nostrSend: NostrSend | null = null - + settings: MainSettings applicationManager: ApplicationManager productManager: ProductManager storage: Storage lnd: LND liquidityManager: LiquidityManager logger = getLogger({ component: 'DebitManager' }) - constructor(storage: Storage, lnd: LND, applicationManager: ApplicationManager, productManager: ProductManager, liquidityManager: LiquidityManager) { + constructor(storage: Storage, settings: MainSettings, lnd: LND, applicationManager: ApplicationManager, productManager: ProductManager, liquidityManager: LiquidityManager) { this.storage = storage + this.settings = settings this.lnd = lnd this.applicationManager = applicationManager this.productManager = productManager @@ -113,7 +114,7 @@ export class OfferManager { if (!offer) { throw new Error("Offer not found") } - const nostrSettings = LoadNosrtSettingsFromEnv() + const nostrSettings = this.settings.nostrRelaySettings return mapToOfferConfig(ctx.app_user_id, offer, { pubkey: app.npub, relay: nostrSettings.relays[0] }) } @@ -131,7 +132,7 @@ export class OfferManager { if (toAppend) { offers.push(toAppend) } - const nostrSettings = LoadNosrtSettingsFromEnv() + const nostrSettings = this.settings.nostrRelaySettings return { offers: offers.map(o => mapToOfferConfig(ctx.app_user_id, o, { pubkey: app.npub, relay: nostrSettings.relays[0] })) } diff --git a/src/services/main/settings.ts b/src/services/main/settings.ts index fe1d6b7d..5c831c75 100644 --- a/src/services/main/settings.ts +++ b/src/services/main/settings.ts @@ -7,12 +7,14 @@ import { getLogger } from '../helpers/logger.js' import fs from 'fs' import crypto from 'crypto'; import { LiquiditySettings, LoadLiquiditySettingsFromEnv } from './liquidityManager.js' +import { LoadNosrtRelaySettingsFromEnv, NostrRelaySettings } from '../nostr/handler.js' export type MainSettings = { storageSettings: StorageSettings, lndSettings: LndSettings, watchDogSettings: WatchdogSettings, liquiditySettings: LiquiditySettings, + nostrRelaySettings: NostrRelaySettings, jwtSecret: string walletPasswordPath: string walletSecretPath: string @@ -49,12 +51,13 @@ export type TestSettings = MainSettings & { lndSettings: { otherNode: NodeSettin export const LoadMainSettingsFromEnv = (): MainSettings => { const storageSettings = LoadStorageSettingsFromEnv() const outgoingAppUserInvoiceFeeBps = EnvCanBeInteger("OUTGOING_INVOICE_FEE_USER_BPS", 0) - + const nostrRelaySettings = LoadNosrtRelaySettingsFromEnv() return { watchDogSettings: LoadWatchdogSettingsFromEnv(), lndSettings: LoadLndSettingsFromEnv(), storageSettings: storageSettings, liquiditySettings: LoadLiquiditySettingsFromEnv(), + nostrRelaySettings: nostrRelaySettings, jwtSecret: loadJwtSecret(storageSettings.dataDir), walletSecretPath: process.env.WALLET_SECRET_PATH || getDataPath(storageSettings.dataDir, ".wallet_secret"), walletPasswordPath: process.env.WALLET_PASSWORD_PATH || getDataPath(storageSettings.dataDir, ".wallet_password"), diff --git a/src/services/main/watchdog.ts b/src/services/main/watchdog.ts index b5ffed51..07e59662 100644 --- a/src/services/main/watchdog.ts +++ b/src/services/main/watchdog.ts @@ -78,7 +78,7 @@ export class Watchdog { const knownMaxIndex = paymentFound.length > 0 ? Math.max(paymentFound[0].paymentIndex, 0) : 0 this.latestPaymentIndexOffset = await this.lnd.GetLatestPaymentIndex(knownMaxIndex) const other = { ilnd: this.initialLndBalance, hf: this.accumulatedHtlcFees, iu: this.initialUsersBalance, tu: totalUsersBalance, oext: otherExternal } - getLogger({ component: 'watchdog_debug2' })(JSON.stringify({ deltaLnd: 0, deltaUsers: 0, totalExternal, latestIndex: this.latestPaymentIndexOffset, other })) + //getLogger({ component: 'watchdog_debug2' })(JSON.stringify({ deltaLnd: 0, deltaUsers: 0, totalExternal, latestIndex: this.latestPaymentIndexOffset, other })) this.interval = setInterval(() => { if (this.latestCheckStart + (1000 * 58) < Date.now()) { this.PaymentRequested() @@ -192,7 +192,7 @@ export class Watchdog { const newLatest = await this.lnd.GetLatestPaymentIndex(knownMaxIndex) const historyMismatch = newLatest > knownMaxIndex const other = { ilnd: this.initialLndBalance, hf: this.accumulatedHtlcFees, iu: this.initialUsersBalance, tu: totalUsersBalance, km: knownMaxIndex, nl: newLatest, oext: otherExternal } - getLogger({ component: 'watchdog_debug2' })(JSON.stringify({ deltaLnd, deltaUsers, totalExternal, other })) + //getLogger({ component: 'watchdog_debug2' })(JSON.stringify({ deltaLnd, deltaUsers, totalExternal, other })) const deny = await this.checkBalanceUpdate(deltaLnd, deltaUsers) if (historyMismatch) { getLogger({ component: 'bark' })("History mismatch detected in absolute update, locking outgoing operations") diff --git a/src/services/nostr/handler.ts b/src/services/nostr/handler.ts index 5fa8b430..553c8d6f 100644 --- a/src/services/nostr/handler.ts +++ b/src/services/nostr/handler.ts @@ -7,6 +7,7 @@ import { ERROR, getLogger } from '../helpers/logger.js' import { nip19 } from 'nostr-tools' import { encrypt as encryptV1, decrypt as decryptV1, getSharedSecret as getConversationKeyV1 } from './nip44v1.js' import { ProcessMetrics, ProcessMetricsCollector } from '../storage/tlv/processMetricsCollector.js' +import { EnvCanBeInteger, } from '../helpers/envParser.js' const { nprofileEncode } = nip19 const { v2 } = nip44 const { encrypt: encryptV2, decrypt: decryptV2, utils } = v2 @@ -26,6 +27,25 @@ export type NostrSettings = { clients: ClientInfo[] maxEventContentLength: number } + +export type NostrRelaySettings = { + relays: string[], + maxEventContentLength: number +} + +const getEnvOrDefault = (name: string, defaultValue: string): string => { + return process.env[name] || defaultValue; +} + +export const LoadNosrtRelaySettingsFromEnv = (test = false): NostrRelaySettings => { + const relaysEnv = getEnvOrDefault("NOSTR_RELAYS", "wss://relay.lightning.pub"); + const maxEventContentLength = EnvCanBeInteger("NOSTR_MAX_EVENT_CONTENT_LENGTH", 40000) + return { + relays: relaysEnv.split(' '), + maxEventContentLength + } +} + export type NostrEvent = { id: string pub: string @@ -124,7 +144,7 @@ const sendToNostr: NostrSend = (initiator, data, relays) => { subProcessHandler.Send(initiator, data, relays) } send({ type: 'ready' }) -const supportedKinds = [21000, 21001, 21002] +const supportedKinds = [21000, 21001, 21002, 21003] export default class Handler { pool = new SimplePool() settings: NostrSettings diff --git a/src/services/nostr/index.ts b/src/services/nostr/index.ts index 6e6a6e6b..288478ec 100644 --- a/src/services/nostr/index.ts +++ b/src/services/nostr/index.ts @@ -4,18 +4,9 @@ import { NostrSettings, NostrEvent, ChildProcessRequest, ChildProcessResponse, S import { Utils } from '../helpers/utilsWrapper.js' type EventCallback = (event: NostrEvent) => void -const getEnvOrDefault = (name: string, defaultValue: string): string => { - return process.env[name] || defaultValue; -} -export const LoadNosrtSettingsFromEnv = (test = false) => { - const relaysEnv = getEnvOrDefault("NOSTR_RELAYS", "wss://relay.lightning.pub"); - const maxEventContentLength = EnvCanBeInteger("NOSTR_MAX_EVENT_CONTENT_LENGTH", 40000) - return { - relays: relaysEnv.split(' '), - maxEventContentLength - } -} + + export default class NostrSubprocess { settings: NostrSettings diff --git a/src/services/serverMethods/index.ts b/src/services/serverMethods/index.ts index 5e204369..653eadb9 100644 --- a/src/services/serverMethods/index.ts +++ b/src/services/serverMethods/index.ts @@ -289,6 +289,7 @@ export default (mainHandler: Main): Types.ServerMethods => { await mainHandler.applicationManager.SetMockAppBalance(ctx.app_id, req) }, GetLiveDebitRequests: async ({ ctx }) => { }, + GetLiveManageRequests: async ({ ctx }) => { }, GetLiveUserOperations: async ({ ctx, cb }) => { }, GetMigrationUpdate: async ({ ctx, cb }) => { @@ -355,6 +356,19 @@ export default (mainHandler: Main): Types.ServerMethods => { GetDebitAuthorizations: async ({ ctx }) => { return mainHandler.debitManager.GetDebitAuthorizations(ctx) }, + AuthorizeManage: async ({ ctx, req }) => { + return mainHandler.managementManager.AuthorizeManage(ctx, req) + }, + GetManageAuthorizations: async ({ ctx }) => { + return mainHandler.managementManager.GetManageAuthorizations(ctx) + }, + ResetManage: async ({ ctx, req }) => { + const err = Types.ManageOperationValidate(req, { + npub_CustomCheck: pub => pub !== '', + }) + if (err != null) throw new Error(err.message) + return mainHandler.managementManager.ResetManage(ctx, req) + }, BanDebit: async ({ ctx, req }) => { const err = Types.DebitOperationValidate(req, { npub_CustomCheck: pub => pub !== '', diff --git a/src/services/storage/db/db.ts b/src/services/storage/db/db.ts index de0e6aa2..770476a9 100644 --- a/src/services/storage/db/db.ts +++ b/src/services/storage/db/db.ts @@ -24,6 +24,7 @@ import { InviteToken } from "../entity/InviteToken.js" import { DebitAccess } from "../entity/DebitAccess.js" import { RootOperation } from "../entity/RootOperation.js" import { UserOffer } from "../entity/UserOffer.js" +import { ManagementGrant } from "../entity/ManagementGrant.js" import { ChannelEvent } from "../entity/ChannelEvent.js" @@ -66,7 +67,8 @@ export const MainDbEntities = { 'InviteToken': InviteToken, 'DebitAccess': DebitAccess, 'UserOffer': UserOffer, - 'Product': Product + 'Product': Product, + 'ManagementGrant': ManagementGrant } export type MainDbNames = keyof typeof MainDbEntities export const MainDbEntitiesNames = Object.keys(MainDbEntities) diff --git a/src/services/storage/entity/ManagementGrant.ts b/src/services/storage/entity/ManagementGrant.ts new file mode 100644 index 00000000..1ce4650d --- /dev/null +++ b/src/services/storage/entity/ManagementGrant.ts @@ -0,0 +1,26 @@ +import { Entity, PrimaryGeneratedColumn, Column, CreateDateColumn, ManyToOne, JoinColumn, UpdateDateColumn } from "typeorm"; +import { User } from "./User"; + +@Entity() +export class ManagementGrant { + @PrimaryGeneratedColumn() + serial_id: number + + @Column() + app_user_id: string + + @Column() + app_pubkey: string; + + @Column() + expires_at_unix: number + + @Column() + banned: boolean + + @CreateDateColumn() + created_at: Date + + @UpdateDateColumn() + updated_at: Date +} \ No newline at end of file diff --git a/src/services/storage/entity/UserOffer.ts b/src/services/storage/entity/UserOffer.ts index 409c4e8d..691a529b 100644 --- a/src/services/storage/entity/UserOffer.ts +++ b/src/services/storage/entity/UserOffer.ts @@ -13,6 +13,9 @@ export class UserOffer { @Column({ unique: true, nullable: false }) offer_id: string + @Column({ default: "" }) + management_pubkey: string + @Column() label: string diff --git a/src/services/storage/index.ts b/src/services/storage/index.ts index e8f9e771..0bdcc1a2 100644 --- a/src/services/storage/index.ts +++ b/src/services/storage/index.ts @@ -10,6 +10,7 @@ import EventsLogManager from "./eventsLog.js"; import { LiquidityStorage } from "./liquidityStorage.js"; import DebitStorage from "./debitStorage.js" import OfferStorage from "./offerStorage.js" +import { ManagementStorage } from "./managementStorage.js"; import { StorageInterface, TX } from "./db/storageInterface.js"; import { PubLogger } from "../helpers/logger.js" import { TlvStorageFactory } from './tlv/tlvFilesStorageFactory.js'; @@ -36,6 +37,7 @@ export default class { liquidityStorage: LiquidityStorage debitStorage: DebitStorage offerStorage: OfferStorage + managementStorage: ManagementStorage eventsLog: EventsLogManager utils: Utils constructor(settings: StorageSettings, utils: Utils) { @@ -58,6 +60,7 @@ export default class { this.liquidityStorage = new LiquidityStorage(this.dbs) this.debitStorage = new DebitStorage(this.dbs) this.offerStorage = new OfferStorage(this.dbs) + this.managementStorage = new ManagementStorage(this.dbs); try { if (this.settings.dataDir) fs.mkdirSync(this.settings.dataDir) } catch (e) { } /* const executedMetricsMigrations = */ await this.metricsStorage.Connect() /* if (executedMigrations.length > 0) { diff --git a/src/services/storage/managementStorage.ts b/src/services/storage/managementStorage.ts new file mode 100644 index 00000000..1cc263b5 --- /dev/null +++ b/src/services/storage/managementStorage.ts @@ -0,0 +1,25 @@ +import { StorageInterface } from "./db/storageInterface.js"; +import { ManagementGrant } from "./entity/ManagementGrant.js"; + +export class ManagementStorage { + private dbs: StorageInterface; + constructor(dbs: StorageInterface) { + this.dbs = dbs; + } + + getGrant(appUserId: string, appPubkey: string) { + return this.dbs.FindOne('ManagementGrant', { where: { app_pubkey: appPubkey, app_user_id: appUserId } }); + } + + async addGrant(appUserId: string, appPubkey: string, banned: boolean, expires_at_unix = 0) { + return this.dbs.CreateAndSave('ManagementGrant', { app_user_id: appUserId, app_pubkey: appPubkey, banned, expires_at_unix }); + } + + async getGrants(appUserId: string) { + return this.dbs.Find('ManagementGrant', { where: { app_user_id: appUserId } }); + } + + async removeGrant(appUserId: string, appPubkey: string) { + return this.dbs.Delete('ManagementGrant', { app_pubkey: appPubkey, app_user_id: appUserId }); + } +} \ No newline at end of file diff --git a/src/services/storage/migrations/1751307732346-management_grant.ts b/src/services/storage/migrations/1751307732346-management_grant.ts new file mode 100644 index 00000000..170fba69 --- /dev/null +++ b/src/services/storage/migrations/1751307732346-management_grant.ts @@ -0,0 +1,22 @@ +import { MigrationInterface, QueryRunner } from "typeorm"; + +export class ManagementGrant1751307732346 implements MigrationInterface { + name = 'ManagementGrant1751307732346' + + public async up(queryRunner: QueryRunner): Promise { + 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(`CREATE TABLE "temporary_user_offer" ("serial_id" integer PRIMARY KEY AUTOINCREMENT NOT NULL, "app_user_id" varchar NOT NULL, "offer_id" varchar NOT NULL, "label" varchar NOT NULL, "price_sats" integer NOT NULL DEFAULT (0), "callback_url" varchar NOT NULL DEFAULT (''), "expected_data" text, "created_at" datetime NOT NULL DEFAULT (datetime('now')), "updated_at" datetime NOT NULL DEFAULT (datetime('now')), "management_pubkey" varchar NOT NULL DEFAULT (''), CONSTRAINT "UQ_478f72095abd8a516d3a309a5c5" UNIQUE ("offer_id"))`); + await queryRunner.query(`INSERT INTO "temporary_user_offer"("serial_id", "app_user_id", "offer_id", "label", "price_sats", "callback_url", "expected_data", "created_at", "updated_at") SELECT "serial_id", "app_user_id", "offer_id", "label", "price_sats", "callback_url", "expected_data", "created_at", "updated_at" FROM "user_offer"`); + await queryRunner.query(`DROP TABLE "user_offer"`); + await queryRunner.query(`ALTER TABLE "temporary_user_offer" RENAME TO "user_offer"`); + } + + public async down(queryRunner: QueryRunner): Promise { + await queryRunner.query(`ALTER TABLE "user_offer" RENAME TO "temporary_user_offer"`); + await queryRunner.query(`CREATE TABLE "user_offer" ("serial_id" integer PRIMARY KEY AUTOINCREMENT NOT NULL, "app_user_id" varchar NOT NULL, "offer_id" varchar NOT NULL, "label" varchar NOT NULL, "price_sats" integer NOT NULL DEFAULT (0), "callback_url" varchar NOT NULL DEFAULT (''), "expected_data" text, "created_at" datetime NOT NULL DEFAULT (datetime('now')), "updated_at" datetime NOT NULL DEFAULT (datetime('now')), CONSTRAINT "UQ_478f72095abd8a516d3a309a5c5" UNIQUE ("offer_id"))`); + await queryRunner.query(`INSERT INTO "user_offer"("serial_id", "app_user_id", "offer_id", "label", "price_sats", "callback_url", "expected_data", "created_at", "updated_at") SELECT "serial_id", "app_user_id", "offer_id", "label", "price_sats", "callback_url", "expected_data", "created_at", "updated_at" FROM "temporary_user_offer"`); + await queryRunner.query(`DROP TABLE "temporary_user_offer"`); + await queryRunner.query(`DROP TABLE "management_grant"`); + } + +} diff --git a/src/services/storage/migrations/1751989251513-management_grant_banned.ts b/src/services/storage/migrations/1751989251513-management_grant_banned.ts new file mode 100644 index 00000000..511734a4 --- /dev/null +++ b/src/services/storage/migrations/1751989251513-management_grant_banned.ts @@ -0,0 +1,20 @@ +import { MigrationInterface, QueryRunner } from "typeorm"; + +export class ManagementGrantBanned1751989251513 implements MigrationInterface { + name = 'ManagementGrantBanned1751989251513' + + public async up(queryRunner: QueryRunner): Promise { + 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 { + 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"`); + } + +} diff --git a/src/services/storage/migrations/runner.ts b/src/services/storage/migrations/runner.ts index a12491d6..36e84a5a 100644 --- a/src/services/storage/migrations/runner.ts +++ b/src/services/storage/migrations/runner.ts @@ -17,7 +17,11 @@ import { RootOps1732566440447 } from './1732566440447-root_ops.js' import { UserOffer1733502626042 } from './1733502626042-user_offer.js' import { RootOpsTime1745428134124 } from './1745428134124-root_ops_time.js' import { ChannelEvents1750777346411 } from './1750777346411-channel_events.js' -export const allMigrations = [Initial1703170309875, LspOrder1718387847693, LiquidityProvider1719335699480, LndNodeInfo1720187506189, TrackedProvider1720814323679, CreateInviteTokenTable1721751414878, PaymentIndex1721760297610, DebitAccess1726496225078, DebitAccessFixes1726685229264, DebitToPub1727105758354, UserCbUrl1727112281043, UserOffer1733502626042] +import { ManagementGrant1751307732346 } from './1751307732346-management_grant.js' +import { ManagementGrantBanned1751989251513 } from './1751989251513-management_grant_banned.js' +export const allMigrations = [Initial1703170309875, LspOrder1718387847693, LiquidityProvider1719335699480, LndNodeInfo1720187506189, + TrackedProvider1720814323679, CreateInviteTokenTable1721751414878, PaymentIndex1721760297610, DebitAccess1726496225078, DebitAccessFixes1726685229264, + DebitToPub1727105758354, UserCbUrl1727112281043, UserOffer1733502626042, ManagementGrant1751307732346, ManagementGrantBanned1751989251513] export const allMetricsMigrations = [LndMetrics1703170330183, ChannelRouting1709316653538, HtlcCount1724266887195, BalanceEvents1724860966825, RootOps1732566440447, RootOpsTime1745428134124, ChannelEvents1750777346411] /* export const TypeOrmMigrationRunner = async (log: PubLogger, storageManager: Storage, settings: DbSettings, arg: string | undefined): Promise => { await connectAndMigrate(log, storageManager, allMigrations, allMetricsMigrations) diff --git a/src/services/storage/offerStorage.ts b/src/services/storage/offerStorage.ts index 2a921c57..4e6ff657 100644 --- a/src/services/storage/offerStorage.ts +++ b/src/services/storage/offerStorage.ts @@ -34,6 +34,11 @@ export default class { async GetUserOffers(app_user_id: string): Promise { return this.dbs.Find('UserOffer', { where: { app_user_id } }) } + + async getManagedUserOffers(app_user_id: string, management_pubkey: string): Promise { + return this.dbs.Find('UserOffer', { where: { app_user_id, management_pubkey } }) + } + async GetUserOffer(app_user_id: string, offer_id: string): Promise { return this.dbs.FindOne('UserOffer', { where: { app_user_id, offer_id } }) }